QDpy
Loading...
Searching...
No Matches
sphen.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Illuminate expensive fitness and descriptor functions with Gaussian processes."""
7
8from collections import deque
9from dataclasses import dataclass
10
11import numpy as np
12from scipy.stats import qmc
13
14from qdpy.base import registry
15from qdpy.containers import Grid
16from .constrained import _validate_grid
17from .mixed_bayesian import _gower_covariance, _MixedGaussianProcess
18from .modern import _bounds, _FixedGeneration, _positive_int
19
20__all__ = ["SPHEN", "SPHENPrediction"]
21
22
23
24@dataclass(frozen=True)
26 """Describe a model-selected design in raw units.
27
28 :ivar cell: Predicted cell in the supplied grid geometry.
29 :ivar genome: Proposed design in the original decision domain.
30 :ivar fitness: Predicted objective in its original optimisation direction.
31 :ivar features: Predicted descriptor vector used to assign the cell.
32 """
33
34 cell: tuple
35 genome: tuple
36 fitness: float
37 features: tuple
38
39
40
41@registry.register
43 """Build acquisition and prediction maps on a fixed regular grid.
44
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.
50
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.
64 """
65
66 _requires_proposed_genome = True
67
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,
71 seed=0, **kwargs):
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)
79 self._origin, self._upper = float(lo), float(hi)
80 self._span = self._upper - self._origin
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")
85 self.surrogate_budget = _positive_int(surrogate_budget, "surrogate_budget")
86 self.surrogate_batch_size = _positive_int(surrogate_batch_size, "surrogate_batch_size")
87 self.exploration, self.mutation_sigma, self.length_scale = exploration, mutation_sigma, length_scale
88 self.seed = seed
89 dimension = _positive_int(dimension, "dimension")
90 self._continuous = np.ones(dimension, dtype=bool)
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)
95 if len(self._fitness_weights) != 1 or not np.isfinite(self._fitness_weights[0]) or not self._fitness_weights[0]:
96 raise ValueError("Use a finite nonzero fitness weight.")
97 self._direction = np.sign(self._fitness_weights[0])
98
99 def reinit(self):
100 """Reset measurements, pending proposals, counters, and private random streams."""
101 super().reinit()
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)))
105 self._seen, self._observations, self._promoted = set(), [], deque()
106 self._predicted_cells = []
107 self._surrogate_evaluations = self._modelled = self._checked = self._misclassified = 0
108
109 @property
111 """Return the number of predictions used to plan exact proposals."""
112 return self._surrogate_evaluations
113
114 @property
116 """Return the number of exact proposals promoted from an acquisition cell."""
117 return self._modelled
118
119 @property
121 """Return the number of promoted proposals with a valid measurement."""
122 return self._checked
123
124 @property
125 def misclassified(self):
126 """Return checked predictions assigned to a different cell, including out-of-grid measures."""
127 return self._misclassified
128
129 def _raw(self, points):
130 return tuple(np.clip(self._origin + self._span * points, self._origin, self._upper))
131
132 def _covariance(self, first, second):
133 return _gower_covariance(first, second, self._continuous, self.length_scale, 0.)
134
135 def _cell(self, features):
136 if self.container.in_bounds(features, self.container.features_domain):
137 return self.container.index_grid(features)
138 return None
139
140 def _build_map(self, budget, exploration, rng, excluded):
141 observed, responses = zip(*self._observations)
142 points = (np.asarray(observed) - self._origin) / self._span
143 model = _MixedGaussianProcess(points, np.asarray(responses), self._covariance)
144 elites = {}
145 for start in range(0, budget, self.surrogate_batch_size):
146 size = min(self.surrogate_batch_size, budget - start)
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
151 if np.any(mutate):
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)):
164 continue
165 if cell not in elites or score > elites[cell][0]:
166 elites[cell] = (float(score), trial, float(response[0]), features)
167 return elites
168
169 def _start_fixed_batch(self, size):
170 super()._start_fixed_batch(size)
171 self._promoted.clear()
172 self._predicted_cells.clear()
173 if len(self._observations) < self.initial_samples:
174 return
175 elites = self._build_map(self.surrogate_budget, self.exploration, self._rng, self._seen)
177 cells = tuple(elites)
178 if cells:
179 centers = (np.asarray(cells) + .5) / self.container.shape
180 scheduled = set()
181 for _ in range(min(size, len(cells))):
182 wanted = self._targets.random(1)[0]
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:
188 self._promoted.append((vector, cell))
189 scheduled.add(vector)
190
191 def _internal_ask(self, base_ind):
192 if self._promoted:
193 vector, cell = self._promoted.popleft()
194 self._modelled += 1
195 else:
196 for _ in range(1024):
197 vector = self._raw(self._sobol.random(1)[0])
198 if vector not in self._seen:
199 break
200 else:
201 raise RuntimeError("The Sobol stream could not find an unseen genome in the decision bounds.")
202 cell = None
203 self._seen.add(vector)
204 self._predicted_cells.append(cell)
205 base_ind[:] = vector
206 return base_ind
207
208 def _check_candidate(self, individual):
209 self._check_measurements(individual)
210 if len(self.container.get_ind_features(individual)) != len(self.container.shape):
211 raise ValueError("Provide one descriptor per grid axis.")
212
213 def _commit_generation(self, evaluated):
214 grid, admitted = self.container, set()
215 for slot, individual in enumerate(evaluated):
216 if individual is None:
217 continue
218 fitness = grid.get_ind_fitness(individual).values
219 features = tuple(grid.get_ind_features(individual))
220 self._observations.append((tuple(individual), (self._direction * fitness[0], *features)))
221 actual, predicted = self._cell(features), self._predicted_cells[slot]
222 if predicted is not None:
223 self._checked += 1
224 self._misclassified += actual != predicted
225 if actual is not None and grid.in_bounds(fitness, grid.fitness_domain):
226 if self._offer_to_grid(individual, actual):
227 admitted.add(slot)
228 return admitted
229
230
231 def prediction_map(self, budget=None, *, seed=0):
232 """Return immutable SPHENPrediction rows without calling the evaluator.
233
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.
238 """
239 if budget is None:
240 budget = self.surrogate_budget
241 budget = _positive_int(budget, "budget")
242 if not self._observations:
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)
245 return tuple(SPHENPrediction(cell, self._raw(row[1]), float(self._direction * row[2]), row[3])
246 for cell, row in sorted(elites.items()))
_check_measurements(self, individual)
Definition modern.py:216
_offer_to_grid(self, individual, cell)
Definition modern.py:228
Posterior means for one design in the prediction-only map.
Definition sphen.py:25
Use posterior-mean descriptors and optimistic fitness to guide exact sampling.
Definition sphen.py:42
_internal_ask(self, base_ind)
Definition sphen.py:191
prediction_map(self, budget=None, *, seed=0)
Build a separate prediction map with objective uncertainty turned off.
Definition sphen.py:231
_cell(self, features)
Definition sphen.py:135
_start_fixed_batch(self, size)
Definition sphen.py:169
_build_map(self, budget, exploration, rng, excluded)
Definition sphen.py:140
_covariance(self, first, second)
Definition sphen.py:132
_commit_generation(self, evaluated)
Definition sphen.py:213