QDpy
Loading...
Searching...
No Matches
safe_illumination.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Expand an estimated safe set before optimizing its descriptor niches."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12from scipy.spatial.distance import cdist
13from sklearn.gaussian_process import GaussianProcessRegressor
14from sklearn.gaussian_process.kernels import Matern
15
16from .bayesian import _expected_improvement
17from .modern import _positive_int
18from .task_search import _measurement, _offer, _validate_grid
19
20__all__ = ["SafeBayesianIllumination", "SafeIlluminationTrial"]
21
22
23
24@dataclass(frozen=True)
26 """The phase is "seed", "expansion", or "illumination"."""
27
28 index: int
29 phase: str
30 fitness: float | None = None
31 margins: tuple[float, ...] | None = None
32
33
34def _safety_vector(values, count, label):
35 vector = np.broadcast_to(np.asarray(values, dtype=float), (count,)).copy()
36 if not np.isfinite(vector).all() or (vector < 0.).any():
37 raise ValueError(f"{label} must contain finite nonnegative values.")
38 return vector
39
40
41
43 """Use a StageOpt-inspired expansion phase and then per-niche improvement.
44
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.
63 """
64
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.,)
87 self._weights = tuple(weights)
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.")
93 self._floor = self._direction * float(quality_floor)
94 self._lipschitz = None if lipschitz is None else _safety_vector(lipschitz, constraints, "lipschitz")
95 self._error = _safety_vector(observation_error, constraints, "observation_error")
96 if self._lipschitz is None and np.any(self._error):
97 raise ValueError("Use observation_error with Lipschitz bounds.")
98 self._distances = cdist(points, points)
99 if not np.isfinite(self._distances).all():
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)
104 self.archive = archive
105 self._points, self._features = points, features
106 self._confidence, self._length, self._noise = confidence, length_scale, noise
107 self._seeds, self._constraints = seeds, constraints
108 self._expansion_budget = expansion_budget
109 self._trials = []
110 self._attempted = np.zeros(len(points), dtype=bool)
111 self._inputs, self._safety, self._quality = [], [], []
112 self._expansion_trials = 0
113 self._expanding = True
114 self._halted = False
115
116 @property
117 def trials(self):
118 """Return attempts in dispatch order, including failed evaluations."""
119 return tuple(self._trials)
120
121 @property
122 def halted(self):
123 """Return whether an observed negative safety margin stopped the search."""
124 return self._halted
125
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)
129 return estimator.fit(self._points[self._inputs], observations)
130
131 def _certificates(self):
132 if not self._inputs:
133 safe = np.full((len(self._points), self._constraints), -np.inf)
134 return safe, None, None
135 means, stds = [], []
136 for values in np.asarray(self._safety).T:
137 mean, std = self._gp(values).predict(self._points, return_std=True)
138 means.append(mean)
139 stds.append(std)
140 mean, spread = np.asarray(means).T, np.asarray(stds).T
141 if self._lipschitz is None:
142 lower = mean - self._confidence * spread
143 else:
144 distances = self._distances[self._inputs, :, None]
145 margin = np.asarray(self._safety)[:, None, :] - self._error
146 lower = np.max(margin - distances * self._lipschitz, axis=0)
147 return lower, mean + self._confidence * spread, spread
148
149 def _safe_mask(self, lower):
150 mask = np.all(lower >= 0., axis=1)
151 mask[list(self._seeds)] = True
152 return mask
153
154
156 """Return safe-set indices, including trusted seeds, or empty after a halt."""
157 if self._halted:
158 return ()
159 lower, _, _ = self._certificates()
160 return tuple(map(int, np.flatnonzero(self._safe_mask(lower))))
161
162 def _choose_expander(self, ready, unknown, lower, upper, spread):
163 if self._lipschitz is None:
164 # Use uncertainty near the uncertified frontier as an expansion proxy.
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.)
169 for slot in ready:
170 possible = upper[slot] - self._error - self._distances[slot, unknown, None] * self._lipschitz
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
175 return best
176
177 def _choose_quality(self, ready):
178 model = self._gp(self._quality, normalize=True)
179 mean, deviation = model.predict(self._points[ready], return_std=True)
180 targets = []
181 for slot in ready:
182 front = self.archive.solutions[self._cells[slot]]
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)))])
186
187 def _next_trial(self):
188 for slot in self._seeds:
189 if not self._attempted[slot]:
190 return slot, "seed"
191 if not self._inputs:
192 return None
193 lower, upper, spread = self._certificates()
194 mask = self._safe_mask(lower)
195 ready = np.flatnonzero(mask & ~self._attempted)
196 if not len(ready):
197 return None
198 unknown = np.flatnonzero(~mask & ~self._attempted)
199 if self._expanding and len(unknown) and self._expansion_trials < self._expansion_budget:
200 slot = self._choose_expander(ready, unknown, lower, upper, spread)
201 if slot is not None:
202 return slot, "expansion"
203 self._expanding = False
204 return self._choose_quality(ready), "illumination"
205
206 def _observe(self, slot, phase, evaluate):
207 self._attempted[slot] = True
208 self._expansion_trials += phase == "expansion"
209 row = SafeIlluminationTrial(slot, phase)
210 try:
211 genome = tuple(map(float, self._points[slot]))
212 outcome = evaluate(genome)
213 if outcome is None:
214 return
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)
220 row = SafeIlluminationTrial(slot, phase, margins=margins)
221 measured = _measurement(self.archive, ((fitness,), self._features[slot]), genome)
222 fitness = measured[0].fitness.values[0]
223 row = SafeIlluminationTrial(slot, phase, fitness, margins)
224 if self._halted:
225 return
226 self._inputs.append(slot)
227 self._safety.append(margins)
228 self._quality.append(self._direction * fitness)
229 _offer(self.archive, measured)
230 finally:
231 self._trials.append(row)
232
233
234 def run(self, evaluate, *, budget):
235 """Use evaluate(genome) for (scalar fitness, safety-margin vector) or None.
236
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.
241 """
242 if not callable(evaluate):
243 raise TypeError("Supply a callable evaluator.")
244 if tuple(self.archive.fitness_weights or ()) != self._weights:
245 raise ValueError("The archive objective weights changed.")
246 for _ in range(_positive_int(budget, "budget")):
247 selection = None if self._halted else self._next_trial()
248 if selection is None:
249 break
250 self._observe(*selection, evaluate)
251 return self.archive
Illuminate a pool of measurable designs while separating safety and quality.
_choose_expander(self, ready, unknown, lower, upper, spread)
run(self, evaluate, *, budget)
Spend up to the requested number of additional safe-pool trials.
certified_indices(self)
List candidates currently supported by the safety rules.
One attempted trial and the observations available afterward.