62 """Fit objective, descriptor, and residual models from exact measurements.
64 Real coordinates use a Gaussian kernel. Integer and categorical
65 coordinates use the paper's compound-symmetry (Gower) kernel.
66 A cheap mixed-variable MAP-Elites loop illuminates optimistic
67 objective values under expected-violation limits. A Sobol stream
68 in normalized descriptor coordinates selects which predicted cells
69 to measure next. Only exactly feasible measurements enter the grid.
71 :param container: Empty parentless regular best-only Grid with finite descriptor bounds.
72 :param budget: Exact evaluation attempts in the managed run.
73 :param variables: Sequence of RealVariable, IntegerVariable and CategoricalVariable.
74 :param constraint_names: Distinct score names for residuals g(x) <= 0.
75 :param initial_samples: Minimum successful exact measurements before modelled proposals.
76 :param surrogate_budget: Number of GP predictions per acquisition batch.
77 :param surrogate_batch_size: Number of offspring between auxiliary archive updates.
78 :param exploration: Nonnegative multiplier of the predicted objective standard deviation.
79 :param violation_tolerance: Allowable expected violation per constraint in the auxiliary search.
80 :param real_length_scale: Gaussian length scale in normalized real coordinates.
81 :param discrete_correlation: Covariance factor for two distinct discrete values.
82 :param batch_size: Maximum simultaneous exact proposals.
83 :param seed: Private mixed-space and Sobol seed.
84 :param kwargs: Native optimisation settings, including objective direction.
87 _requires_proposed_genome =
True
89 def __init__(self, container, budget, variables, *, constraint_names=(),
90 initial_samples=12, surrogate_budget=128, surrogate_batch_size=16, exploration=2.,
91 violation_tolerance=.05, real_length_scale=.25, discrete_correlation=.25,
92 batch_size=4, seed=0, **kwargs):
93 _validate_grid(container)
94 domains = np.asarray(container.features_domain, dtype=float)
95 if (type(container)
is not Grid
or container.parents
or domains.shape != (len(container.shape), 2)
96 or not np.isfinite(domains).all()
or np.any(domains[:, 1] <= domains[:, 0])
97 or not np.isfinite(domains[:, 1] - domains[:, 0]).all()):
98 raise ValueError(
"Supply a fixed parentless rectangular grid with finite positive descriptor widths.")
100 if not self.
variables or not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable))
102 raise ValueError(
"Supply one supported variable specification per coordinate.")
105 if any(max(abs(lo), abs(hi)) > 2**53
for (lo, hi), real
in zip(self.
_bounds, self.
_continuous)
107 raise ValueError(
"Discrete coordinates must be exactly representable in float64.")
108 self.
_low, high = np.asarray(self.
_bounds, dtype=float).T
111 self.
_mutable = [i
for i, (lo, hi)
in enumerate(self.
_bounds)
if hi != lo]
113 if set(self.
constraint_names).intersection((*container.fitness_score_names, *container.features_score_names)):
114 raise ValueError(
"Use separate score names for constraints.")
115 if (
not 0 <= exploration < np.inf
or not 0 <= violation_tolerance < np.inf
116 or not 0 < real_length_scale < np.inf
or not 0 <= discrete_correlation < 1):
117 raise ValueError(
"Use finite acquisition settings and discrete_correlation in [0, 1).")
118 self.
initial_samples = _positive_int(initial_samples,
"initial_samples")
124 if container.fitness_weights
is not None:
125 kwargs.setdefault(
"optimisation_task", tuple(container.fitness_weights))
126 super().__init__(container, _positive_int(budget,
"budget"), dimension=len(self.
variables),
127 batch_size=_positive_int(batch_size,
"batch_size"), **kwargs)
129 raise ValueError(
"Use a finite, nonzero signed fitness weight.")
132 """Reset proposal streams, exact models, and surrogate accounting."""
134 self.
_rng = random.Random(self.
seed)
141 """Return the cumulative number of genomes predicted by auxiliary search."""
146 """Return the number of exact-data refits across acquisition batches."""
147 return self._model_fits
151 """Return one typed value per declared decision coordinate."""
153 raise ValueError(
"Genome length must match the variable specifications.")
154 return tuple(_decode_gene(value, variable, bounds)
155 for value, variable, bounds
in zip(candidate, self.
variables, self.
_bounds))
157 def _encode(self, points):
158 points = np.array(points, dtype=float, copy=
True, ndmin=2)
160 points[:, mask] = (points[:, mask] - self.
_low[mask]) / self.
_span[mask]
163 def _covariance(self, first, second):
164 return _gower_covariance(first, second, self.
_continuous,
168 return tuple(_sample_gene(v, bounds, self.
_rng)
for v, bounds
in zip(self.
variables, self.
_bounds))
170 def _novel_draw(self):
173 if vector
not in self.
_seen:
177 def _offspring(self, parent):
182 child[index] = _mutate_gene(child[index], self.
variables[index], self.
_bounds[index], .15, self.
_rng)
185 def _auxiliary_archive(self, model):
189 count = len(grid.shape)
192 parents = [entry[1]
for entry
in best.values()]
193 vectors = [self.
_offspring(self.
_rng.choice(parents))
if parents
and self.
_rng.random() < .8
194 else self.
_random()
for _
in range(size)]
195 means, deviations = model.predict(self.
_encode(vectors))
197 expected = _expected_improvement(means[:, count+1:], deviations[:, count+1:], 0.)
199 optimistic = means[:, 0] + self.
exploration * deviations[:, 0]
200 for vector, descriptor, violation, quality
in zip(vectors, means[:, 1:count+1], excess, optimistic):
202 cell = grid.index_grid(tuple(descriptor))
205 if vector
not in self.
_seen:
206 rank = (violation, -quality)
207 if cell
not in best
or rank < best[cell][0]:
208 best[cell] = (rank, vector)
211 def _plan_batch(self, size):
214 self._model_fits += 1
217 for _
in range(min(size, len(elites))):
219 cell = min(elites, key=
lambda cell: (elites[cell][0][0] > 0., elites[cell][0][0],
220 np.linalg.norm((np.asarray(cell) + .5) / self.
container.shape - wanted),
222 picks.append(elites.pop(cell)[1])
223 return list(dict.fromkeys(picks))
237 self.
_seen.add(vector)
241 def _check_candidate(self, individual):
245 raise ValueError(
"Provide one measured descriptor per grid axis.")
250 for slot, individual
in enumerate(evaluated):
251 if individual
is None:
253 fit = grid.get_ind_fitness(individual).values
254 descriptors = tuple(grid.get_ind_features(individual))
255 residuals = tuple(float(individual.scores[name])
for name
in self.
constraint_names)
257 self.
_observations.append((tuple(individual), (quality, *descriptors, *residuals)))
258 if (all(value <= 0.
for value
in residuals)
and grid.in_bounds(fit, grid.fitness_domain)
259 and grid.in_bounds(descriptors, grid.features_domain)
260 and self.
_offer_to_grid(individual, grid.index_grid(descriptors))):