43 """Use a StageOpt-inspired expansion phase and then per-niche improvement.
45 :param archive: Empty parentless best-only Grid or CVTGrid.
46 :param points: Finite matrix of distinct real candidate genomes.
47 :param descriptors: Known descriptor vector for each candidate. All
48 must lie in the reporting archive's descriptor domain.
49 :param safe_seeds: Ordered distinct indices trusted safe to evaluate.
50 Their evaluations count against the same budget as other trials.
51 :param constraints: Number of reported safety margins. Zero is safe.
52 :param expansion_budget: Maximum post-seed attempts in the expansion phase.
53 :param quality_floor: Raw objective baseline for an empty niche. The
54 default uses the archive's worst allowed objective.
55 :param confidence: Safety confidence multiplier for the Gaussian processes.
56 :param length_scale: Fixed Matérn length scale in raw decision units.
57 :param noise: Positive GP diagonal regularization.
58 :param lipschitz: Scalar or per-constraint Lipschitz upper bounds in
59 raw Euclidean units. When supplied, use the deterministic margin
60 certificates for dispatch and the GPs for ranking.
61 :param observation_error: Absolute bound on measurement error for each
62 safety margin in Lipschitz mode.
65 def __init__(self, archive, points, descriptors, *, safe_seeds, constraints=1, expansion_budget=8,
66 quality_floor=None, confidence=3., length_scale=.2, noise=1e-6,
67 lipschitz=None, observation_error=0.):
68 _validate_grid(archive)
69 points = np.array(points, dtype=float, copy=
True)
70 features = np.array(descriptors, dtype=float, copy=
True)
71 if (points.ndim != 2
or not points.size
or not np.isfinite(points).all()
72 or len({tuple(row)
for row
in points}) != len(points)):
73 raise ValueError(
"Supply a nonempty matrix of distinct finite candidates.")
74 if (features.shape != (len(points), len(archive.features_domain))
or not np.isfinite(features).all()
75 or any(
not archive.in_bounds(row, archive.features_domain)
for row
in features)):
76 raise ValueError(
"Supply one finite in-domain descriptor vector per candidate.")
77 seeds = tuple(map(index, safe_seeds))
78 if not seeds
or len(set(seeds)) != len(seeds)
or any(
not 0 <= i < len(points)
for i
in seeds):
79 raise ValueError(
"Supply distinct valid indices for the trusted safe seeds.")
80 if not np.isfinite((confidence, length_scale, noise)).all()
or min(confidence, length_scale, noise) <= 0.:
81 raise ValueError(
"Use a positive finite confidence, length scale, and GP noise.")
82 constraints = _positive_int(constraints,
"constraints")
83 expansion_budget = index(expansion_budget)
84 if expansion_budget < 0:
85 raise ValueError(
"expansion_budget must be nonnegative.")
86 weights = archive.fitness_weights
or (1.,)
88 self.
_direction = 1.
if weights[0] > 0.
else -1.
89 if quality_floor
is None:
90 quality_floor = archive.fitness_domain[0][int(self.
_direction < 0.)]
91 if not np.isfinite(quality_floor):
92 raise ValueError(
"Supply a finite raw quality_floor for an unbounded fitness domain.")
94 self.
_lipschitz =
None if lipschitz
is None else _safety_vector(lipschitz, constraints,
"lipschitz")
95 self.
_error = _safety_vector(observation_error, constraints,
"observation_error")
97 raise ValueError(
"Use observation_error with Lipschitz bounds.")
100 raise ValueError(
"Candidate distances must be finite.")
101 self.
_cells = tuple(archive.index_grid(row)
for row
in features)
102 if archive.fitness_weights
is None:
103 archive._set_fitness_weights(weights)
110 self.
_attempted = np.zeros(len(points), dtype=bool)
118 """Return attempts in dispatch order, including failed evaluations."""
123 """Return whether an observed negative safety margin stopped the search."""
126 def _gp(self, observations, *, normalize=False):
127 estimator = GaussianProcessRegressor(kernel=Matern(self.
_length, nu=2.5),
128 alpha=self.
_noise, normalize_y=normalize, optimizer=
None)
131 def _certificates(self):
134 return safe,
None,
None
136 for values
in np.asarray(self.
_safety).T:
137 mean, std = self.
_gp(values).predict(self.
_points, return_std=
True)
140 mean, spread = np.asarray(means).T, np.asarray(stds).T
146 lower = np.max(margin - distances * self.
_lipschitz, axis=0)
147 return lower, mean + self.
_confidence * spread, spread
149 def _safe_mask(self, lower):
150 mask = np.all(lower >= 0., axis=1)
151 mask[list(self.
_seeds)] =
True
156 """Return safe-set indices, including trusted seeds, or empty after a halt."""
160 return tuple(map(int, np.flatnonzero(self.
_safe_mask(lower))))
162 def _choose_expander(self, ready, unknown, lower, upper, spread):
165 nearest = self.
_distances[np.ix_(ready, unknown)].min(axis=1)
166 score = spread[ready].sum(axis=1) * np.exp(-nearest / self.
_length)
167 return int(ready[np.argmax(score)])
168 best, best_rank =
None, (0, 0.)
171 gain = int(np.count_nonzero(np.all((lower[unknown] >= 0.) | (possible >= 0.), axis=1)))
172 rank = (gain, float(spread[slot].sum()))
173 if gain
and rank > best_rank:
174 best, best_rank = int(slot), rank
177 def _choose_quality(self, ready):
179 mean, deviation = model.predict(self.
_points[ready], return_std=
True)
183 targets.append(self.
_direction * self.
archive.get_ind_fitness(front[0]).values[0]
184 if front
else self.
_floor)
185 return int(ready[np.argmax(_expected_improvement(mean, deviation, np.asarray(targets)))])
187 def _next_trial(self):
195 ready = np.flatnonzero(mask & ~self.
_attempted)
198 unknown = np.flatnonzero(~mask & ~self.
_attempted)
202 return slot,
"expansion"
206 def _observe(self, slot, phase, evaluate):
211 genome = tuple(map(float, self.
_points[slot]))
212 outcome = evaluate(genome)
215 fitness, margins = outcome
216 margins = tuple(map(float, margins))
217 if len(margins) != self.
_constraints or not np.isfinite(margins).all():
218 raise ValueError(
"Return the configured number of finite safety margins.")
219 self.
_halted = any(margin < 0.
for margin
in margins)
221 measured = _measurement(self.
archive, ((fitness,), self.
_features[slot]), genome)
222 fitness = measured[0].fitness.values[0]
234 def run(self, evaluate, *, budget):
235 """Use evaluate(genome) for (scalar fitness, safety-margin vector) or None.
237 Each pool candidate is evaluated at most once. Stop when no new
238 point satisfies the safety gate or a violation is observed.
239 The GP gate depends on calibrated confidence bounds. A Lipschitz
240 gate depends on correct supplied constants and measurement error.
242 if not callable(evaluate):
243 raise TypeError(
"Supply a callable evaluator.")
245 raise ValueError(
"The archive objective weights changed.")
246 for _
in range(_positive_int(budget,
"budget")):
248 if selection
is None: