37def _promote(trials, cells, count, direction, rng, num_cells):
54 """Search designs over increasing evaluation fidelities.
56 :param archive: Best-only Grid or CVTGrid with one signed objective.
57 :param dimension: Number of real design coordinates.
58 :param fidelities: Increasing positive integer resource units. Rungs
59 are charged their total cost, including evaluations of promotions.
60 :param eta: Integer successive-halving factor, at least two.
61 :param ind_domain: Common lower and upper bounds for design coordinates.
62 :param seed: Private seed for new proposals and promotion.
65 def __init__(self, archive, dimension, fidelities, *, eta=3, ind_domain=(0., 1.), seed=0):
66 if (type(archive)
not in (Grid, CVTGrid)
or archive.max_items_per_bin != 1
67 or archive.parents
or archive.discard_random_on_bin_overload
68 or len(archive.fitness_domain
or ()) != 1
or not archive.features_domain
69 or not archive.fitness_weights
or len(archive.fitness_weights) != 1):
70 raise ValueError(
"Supply a parentless best-only Grid or CVTGrid with one configured objective.")
72 self.
dimension = _positive_int(dimension,
"dimension")
73 self.
fidelities = tuple(_positive_int(cost,
"fidelity")
for cost
in fidelities)
74 self.
eta = _positive_int(eta,
"eta")
76 raise ValueError(
"Fidelities must strictly increase and eta must be at least two.")
78 self.
_direction = np.sign(archive.fitness_weights[0])
79 if self.
_direction not in (-1, 1)
or not np.isfinite(archive.fitness_weights[0]):
80 raise ValueError(
"Provide a finite nonzero objective weight.")
81 self.
_rng = np.random.default_rng(seed)
82 self.
_cells = {cell: i
for i, cell
in enumerate(archive.solutions)}
89 """Return attempted evaluations in their submission order."""
94 """Return cumulative resource units including failed calls."""
97 def _propose(self, count, fidelity):
100 def _measure(self, evaluate, genome, fidelity):
101 genome = tuple(map(float, genome))
103 outcome = evaluate(genome, fidelity)
108 fitness, descriptors = outcome
109 fitness = float(fitness)
110 descriptors = tuple(map(float, descriptors))
111 if not np.isfinite(fitness)
or not np.isfinite(descriptors).all():
112 raise ValueError(
"Return finite fitness and descriptors or None for a failed measurement.")
116 cell = self.
archive.index_grid(descriptors)
118 if len(descriptors) != len(self.
archive.features_domain):
119 raise ValueError(
"The evaluator returned the wrong descriptor dimension.")
from None
129 def run(self, evaluate, budget):
130 """Return the archive after spending at most budget additional units.
132 The evaluator accepts (genome, fidelity) and returns (scalar fitness,
133 descriptors) or None. Only results at the highest fidelity can enter
134 the reporting archive. A promotion uses its most recent descriptor.
136 budget = _positive_int(budget,
"budget")
137 stop = self.
_spent + budget
142 if sum(cost * count
for cost, count
in schedule) <= stop - self.
_spent:
148 genomes = self.
_propose(schedule[0][1], schedule[0][0])
149 for rung, (fidelity, _)
in enumerate(schedule):
151 for genome
in genomes:
152 row, cell = self.
_measure(evaluate, genome, fidelity)
155 cells.append(self.
_cells[cell])
156 if rung + 1 < len(schedule):
157 genomes = list(_promote(rows, cells, schedule[rung + 1][1], self.
_direction,
164 """Rank proposals by expected joint improvement over regular grid cells.
166 Forests train on all successful observations with the fidelity as an
167 input. Their predictions and incumbent comparisons use the first rung
168 of the planned bracket. A uniform fraction can be reserved for exploration.
170 :param quality_floor: Raw comparison value for a cell without observations.
171 :param model_after: Number of successful observations before fitting.
172 :param pool_size: Minimum number of candidates ranked at bracket start.
173 :param random_fraction: Fraction of each bracket reserved for uniform draws.
174 :param trees: Number of trees per output prediction.
175 :param kwargs: Arguments accepted by QDHyperband.
178 def __init__(self, archive, dimension, fidelities, *, quality_floor, model_after=12,
179 pool_size=256, random_fraction=.1, trees=32, **kwargs):
180 super().__init__(archive, dimension, fidelities, **kwargs)
181 if type(archive)
is not Grid
or not np.isfinite(quality_floor)
or not 0 <= random_fraction <= 1:
182 raise ValueError(
"Use a regular Grid, finite quality_floor and random_fraction in [0, 1].")
184 self.
_model_after = _positive_int(model_after,
"model_after")
185 self.
_pool_size = _positive_int(pool_size,
"pool_size")
186 self.
_trees = _positive_int(trees,
"trees")
188 lower, upper = np.asarray(archive.features_domain).T
189 index = np.array(tuple(self.
_cells))
190 self.
_lower = lower + index / archive.shape * (upper - lower)
191 self.
_upper = lower + (index + 1) / archive.shape * (upper - lower)
192 self.
_closed = index + 1 == archive.shape
195 def _propose(self, count, fidelity):
196 training = [row
for row
in self.
_trials if row.fitness
is not None]
198 return super()._propose(count, fidelity)
200 def encode(genomes, levels):
201 return np.column_stack((genomes, np.asarray(levels) / self.
fidelities[-1]))
203 fitted = RandomForestRegressor(n_estimators=self.
_trees,
204 random_state=int(self.
_rng.integers(2**32)))
205 fitted.fit(encode([row.genome
for row
in training], [row.fidelity
for row
in training]),
206 [(self.
_direction * row.fitness, *row.descriptors)
for row
in training])
209 if row.fidelity == fidelity:
211 cell = self.
archive.index_grid(row.descriptors)
214 if cell
not in incumbents
or self.
_direction * row.fitness > self.
_direction * incumbents[cell].fitness:
215 incumbents[cell] = row
216 pool = super()._propose(max(count, self.
_pool_size), fidelity)
218 seeds = np.array([row.genome
for row
in incumbents.values()])
219 local = seeds[self.
_rng.integers(len(seeds), size=len(pool))]
220 pool = np.concatenate((pool, np.clip(local + self.
_rng.normal(
222 points = encode(pool, np.full(len(pool), fidelity))
223 predictions = np.stack([tree.predict(points)
for tree
in fitted.estimators_])
224 mean, std = predictions.mean(axis=0), predictions.std(axis=0)
225 thresholds = np.array([self.
_floor if cell
not in incumbents
else self.
_direction * incumbents[cell].fitness
227 probability = _region_probabilities(mean[:,
None, 1:], std[:,
None, 1:],
229 acquisition = (probability * _expected_improvement(mean[:, :1], std[:, :1], thresholds)).sum(axis=1)
231 n = count - random_count
233 ranked = np.argsort(-acquisition, kind=
"stable")[:n]
234 return np.concatenate((pool[ranked], super()._propose(random_count, fidelity)))