43 """Build acquisition and prediction maps on a fixed regular grid.
45 Each exact batch refits Gaussian processes for the objective and each
46 descriptor. MAP-Elites perturbs observed points and predicted elites.
47 An auxiliary cell retains the highest signed objective UCB within its
48 predicted descriptor bounds. Sobol targets in descriptor space select
49 cells for exact measurement. The supplied grid only receives measurements.
51 :param container: Empty, parentless, best-only Grid with one signed objective.
52 :param budget: Exact evaluation attempts for optimise().
53 :param dimension: Length of the continuous decision vector.
54 :param ind_domain: Common lower and upper decision bounds.
55 :param initial_samples: Minimum successful measurements before fitting models.
56 :param surrogate_budget: Maximum number of predicted genomes per acquisition map.
57 :param surrogate_batch_size: Number of offspring per auxiliary MAP-Elites update.
58 :param exploration: Nonnegative objective standard deviation multiplier.
59 :param mutation_sigma: Gaussian variation scale in normalized decision space.
60 :param length_scale: Fixed RBF kernel length scale in normalized decision space.
61 :param batch_size: Maximum exact proposals per model update.
62 :param seed: Private Sobol and variation seed.
63 :param kwargs: Native QDAlgorithm settings.
66 _requires_proposed_genome =
True
68 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *,
69 initial_samples=12, surrogate_budget=128, surrogate_batch_size=16,
70 exploration=2., mutation_sigma=.1, length_scale=.25, batch_size=4,
72 _validate_grid(container)
73 domains = np.asarray(container.features_domain, dtype=float)
74 if (type(container)
is not Grid
or container.parents
or domains.shape != (len(container.shape), 2)
75 or not np.isfinite(domains).all()
or np.any(domains[:, 1] <= domains[:, 0])
76 or not np.isfinite(domains[:, 1] - domains[:, 0]).all()):
77 raise ValueError(
"Supply a regular parentless grid with finite increasing descriptor bounds.")
78 lo, hi = _bounds(ind_domain)
81 if (
not np.isfinite(self.
_span)
or not 0 <= exploration < np.inf
82 or not 0 < mutation_sigma <= 1
or not 0 < length_scale < np.inf):
83 raise ValueError(
"Use finite bounds and GP settings, and mutation_sigma in (0, 1].")
84 self.
initial_samples = _positive_int(initial_samples,
"initial_samples")
89 dimension = _positive_int(dimension,
"dimension")
91 if container.fitness_weights
is not None:
92 kwargs.setdefault(
"optimisation_task", tuple(container.fitness_weights))
93 super().__init__(container, _positive_int(budget,
"budget"), dimension=dimension,
94 batch_size=_positive_int(batch_size,
"batch_size"), **kwargs)
96 raise ValueError(
"Use a finite nonzero fitness weight.")
100 """Reset measurements, pending proposals, counters, and private random streams."""
102 self.
_rng = np.random.default_rng(self.
seed)
103 self.
_sobol = qmc.Sobol(self.
dimension, scramble=
True, seed=int(self.
_rng.integers(2**32)))
104 self.
_targets = qmc.Sobol(len(self.
container.shape), scramble=
True, seed=int(self.
_rng.integers(2**32)))
111 """Return the number of predictions used to plan exact proposals."""
116 """Return the number of exact proposals promoted from an acquisition cell."""
117 return self._modelled
121 """Return the number of promoted proposals with a valid measurement."""
126 """Return checked predictions assigned to a different cell, including out-of-grid measures."""
127 return self._misclassified
129 def _raw(self, points):
132 def _covariance(self, first, second):
135 def _cell(self, features):
137 return self.
container.index_grid(features)
140 def _build_map(self, budget, exploration, rng, excluded):
142 points = (np.asarray(observed) - self.
_origin) / self.
_span
147 parents = [row[1]
for row
in elites.values()]
148 base = parents
if parents
else points
149 trials = rng.uniform(size=(size, self.
dimension))
150 mutate = rng.random(size) < .9
152 selected = np.asarray(base)[rng.integers(len(base), size=mutate.sum())]
153 perturbation = rng.normal(0., self.
mutation_sigma, selected.shape)
154 trials[mutate] = np.clip(selected + perturbation, 0., 1.)
155 if start == 0
and excluded
is None:
156 count = min(size, len(points))
157 trials[:count] = points[rng.choice(len(points), count, replace=
False)]
158 means, deviations = model.predict(trials)
159 for trial, response, score
in zip(trials, means, means[:, 0] + exploration * deviations[:, 0]):
160 features = tuple(response[1:])
161 cell = self.
_cell(features)
162 if (cell
is None or not np.isfinite(score)
163 or (excluded
is not None and self.
_raw(trial)
in excluded)):
165 if cell
not in elites
or score > elites[cell][0]:
166 elites[cell] = (float(score), trial, float(response[0]), features)
177 cells = tuple(elites)
179 centers = (np.asarray(cells) + .5) / self.
container.shape
181 for _
in range(min(size, len(cells))):
183 closest = int(np.argmin(np.sum((centers - wanted) ** 2, axis=1)))
184 cell = cells[closest]
185 centers[closest] = np.inf
186 vector = self.
_raw(elites[cell][1])
187 if vector
not in scheduled:
189 scheduled.add(vector)
196 for _
in range(1024):
198 if vector
not in self.
_seen:
201 raise RuntimeError(
"The Sobol stream could not find an unseen genome in the decision bounds.")
203 self.
_seen.add(vector)
208 def _check_candidate(self, individual):
211 raise ValueError(
"Provide one descriptor per grid axis.")
215 for slot, individual
in enumerate(evaluated):
216 if individual
is None:
218 fitness = grid.get_ind_fitness(individual).values
219 features = tuple(grid.get_ind_features(individual))
222 if predicted
is not None:
224 self._misclassified += actual != predicted
225 if actual
is not None and grid.in_bounds(fitness, grid.fitness_domain):
232 """Return immutable SPHENPrediction rows without calling the evaluator.
234 The budget counts model queries for this map alone. It defaults to
235 surrogate_budget. The method uses the latest completed measurements
236 and a local random stream. It leaves the measured archive, search
237 streams, and acquisition counters intact.
241 budget = _positive_int(budget,
"budget")
243 raise ValueError(
"Record at least one exact measurement before predicting a map.")
244 elites = self.
_build_map(budget, 0., np.random.default_rng(seed),
None)
246 for cell, row
in sorted(elites.items()))