QDpy
Loading...
Searching...
No Matches
produqd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Discover design families in a surrogate repertoire and use them to steer search."""
7
8from dataclasses import dataclass
9from math import isfinite
10from operator import index
11
12import numpy as np
13from scipy.spatial.distance import cdist
14from scipy.stats import qmc
15from sklearn.cluster import DBSCAN
16from sklearn.decomposition import PCA
17from sklearn.gaussian_process import GaussianProcessRegressor
18from sklearn.gaussian_process.kernels import Matern
19from sklearn.manifold import TSNE
20
21from ._population import _attempt_budget, _finite_vector
22from .modern import _positive_int
23from .task_search import _measurement, _offer, _validate_grid
24
25__all__ = ["PRODUQD", "PRODUQDStats", "Prototype", "PrototypePrediction"]
26
27
28
29@dataclass(frozen=True)
31 """Fitness is a model prediction in the original objective units."""
32
33 genome: tuple[float, ...]
34 descriptor: tuple[float, ...]
35 fitness: float
36
37
38
39@dataclass(frozen=True)
41 """The representative is a member of the cluster. All members can seed search."""
42
43 representative: PrototypePrediction
44 members: tuple[PrototypePrediction, ...]
45
46
47
48@dataclass(frozen=True)
50 """An unsuccessful expensive call still counts against the evaluation budget."""
51
52 evaluations: int
53 failures: int
54 observations: int
55 model_fits: int
56 acquisition_predictions: int
57 mean_predictions: int
58
59
60@dataclass(frozen=True)
62 descriptor: tuple[float, ...]
63 fitness: float
64 score: float
65
66
67def _ranges(domain, size, name):
68 bounds = np.asarray(domain, dtype=float)
69 if bounds.shape == (2,):
70 bounds = np.tile(bounds, (size, 1))
71 if bounds.shape != (size, 2) or not np.isfinite(bounds).all():
72 raise ValueError(f"{name} must provide finite bounds for every coordinate.")
73 with np.errstate(over="ignore"):
74 widths = bounds[:, 1] - bounds[:, 0]
75 if np.any(widths <= 0.) or not np.isfinite(widths).all():
76 raise ValueError(f"{name} must have finite positive widths.")
77 return bounds[:, 0].copy(), bounds[:, 1].copy(), widths
78
79
80
81class PRODUQD:
82 """The supplied grid only stores measured elites. All valid measurements train the GP.
83
84 Inspect predictions and prototypes after each run, then select any number of
85 prototype families before resuming. Selecting families sets breeding seeds
86 in both surrogate maps. Mutation may still visit other parts of the domain.
87 """
88
89
103 def __init__(self, archive, dimension, describe, *, ind_domain=(0., 1.), initial_samples=16,
104 acquisition_steps=128, prediction_steps=256, evaluations_per_fit=4,
105 kappa=2., mutation_sigma=.08, embedding="pca", cluster_eps=.2,
106 min_samples=2, seed=0):
107 _validate_grid(archive)
108 self._dimension = _positive_int(dimension, "dimension")
109 self._feature_count = len(archive.features_domain)
110 self._lower, self._upper, _ = _ranges(ind_domain, self._dimension, "ind_domain")
111 self._feature_lower, _, self._feature_width = _ranges(
112 archive.features_domain, self._feature_count, "features_domain")
113 if (not callable(describe) or embedding not in ("pca", "tsne")
114 or not all(isfinite(value) and value > 0. for value in (kappa, mutation_sigma, cluster_eps))):
115 raise ValueError("Supply a descriptor callable, PCA or t-SNE, and positive finite scales.")
116 self._initial = _positive_int(initial_samples, "initial_samples")
117 self._acquisition_steps = _positive_int(acquisition_steps, "acquisition_steps")
118 self._prediction_steps = _positive_int(prediction_steps, "prediction_steps")
119 self._batch = _positive_int(evaluations_per_fit, "evaluations_per_fit")
120 self._min_samples = _positive_int(min_samples, "min_samples")
121 self._describe = describe
122 self._kappa, self._sigma, self._embedding, self._eps = kappa, mutation_sigma, embedding, cluster_eps
123 if archive.fitness_weights is None:
124 archive._set_fitness_weights((1.,))
125 self.archive = archive
126 self._sign = np.sign(archive.fitness_weights[0])
127 decisions, features, variation, preview, clustering = np.random.SeedSequence(seed).spawn(5)
128 self._designs = qmc.Sobol(self._dimension, seed=np.random.default_rng(decisions))
129 self._anchors = qmc.Sobol(self._feature_count, seed=np.random.default_rng(features))
130 self._rng = np.random.default_rng(variation)
131 self._preview_rng = np.random.default_rng(preview)
132 self._cluster_seed = int(clustering.generate_state(1)[0])
133 self._attempted = set()
134 self._observations = {}
135 self._model = None
136 self._model_size = 0
137 self._failures = self._fits = self._acquired = self._predicted = 0
138 self._selected = None
139 self._predictions = self._prototypes = self._families = ()
140
141
142 @property
143 def predictions(self):
144 return self._predictions
145
146
147 @property
148 def prototypes(self):
149 return self._prototypes
150
151
152 @property
153 def stats(self):
154 return PRODUQDStats(len(self._attempted), self._failures, len(self._observations),
155 self._fits, self._acquired, self._predicted)
156
157
159 def select_prototypes(self, indices=None):
160 if indices is None:
161 self._selected = None
162 return
163 indices = tuple(index(position) for position in indices)
164 if not indices or any(not 0 <= position < len(self._families) for position in indices):
165 raise ValueError("Select valid indices from the latest prototypes, or clear with None.")
166 self._selected = dict.fromkeys(point for position in indices for point in self._families[position])
167
168 def _raw(self, point):
169 # Interpolation preserves both endpoints even when the rounded span loses precision.
170 unit = np.asarray(point)
171 return tuple(map(float, np.clip((1. - unit) * self._lower + unit * self._upper,
172 self._lower, self._upper)))
173
174 def _descriptor(self, genome):
175 descriptor = self._describe(genome)
176 if descriptor is not None:
177 return _finite_vector(descriptor, "descriptor", self._feature_count)
178 return None
179
180 def _unused_design(self):
181 for _ in range(128):
182 point = tuple(self._designs.random(1)[0])
183 if self._raw(point) not in self._attempted:
184 return point
185 raise RuntimeError("Could not find an unmeasured design. Check parameter bounds and numerical precision.")
186
187 def _evaluate(self, evaluate, point, seeds):
188 genome = self._raw(point)
189 self._attempted.add(genome)
190 fitness = evaluate(genome)
191 if fitness is None:
192 self._failures += 1
193 return
194 if not isfinite(fitness):
195 raise ValueError("The objective must return finite scalar fitness or None.")
196 descriptor = self._descriptor(genome)
197 if descriptor is not None:
198 _offer(self.archive, _measurement(self.archive, ((fitness,), descriptor), genome))
199 self._observations[point] = float(fitness)
200 if seeds is not None:
201 seeds[point] = None
202
203 def _fit(self):
204 if self._model_size != len(self._observations):
205 self._model = GaussianProcessRegressor(
206 kernel=Matern(length_scale=.25, nu=2.5), alpha=1e-6,
207 normalize_y=True, optimizer=None,
208 ).fit(tuple(self._observations), tuple(self._observations.values()))
209 self._model_size = len(self._observations)
210 self._fits += 1
211 return self._model
212
213 def _illuminate(self, model, seeds, confidence, steps, rng):
214 # One entry per cell. A separate dictionary provides constant-time parent sampling.
215 entries = {}
216 cells = []
217 seen = set()
218
219 def consider(point):
220 genome = self._raw(point)
221 if genome in seen:
222 return
223 seen.add(genome)
224 descriptor = self._descriptor(genome)
225 if descriptor is None or not self.archive.in_bounds(descriptor, self.archive.features_domain):
226 return
227 cell = self.archive.index_grid(descriptor)
228 if confidence:
229 mean, deviation = model.predict([point], return_std=True)
230 score = self._sign * mean[0] + confidence * deviation[0]
231 self._acquired += 1
232 else:
233 mean = model.predict([point])
234 score = self._sign * mean[0]
235 self._predicted += 1
236 if cell not in entries:
237 cells.append(cell)
238 elif entries[cell][1].score >= score:
239 return
240 entries[cell] = point, _MapEntry(descriptor, float(mean[0]), float(score))
241
242 for point in seeds:
243 consider(point)
244 for _ in range(steps):
245 if cells:
246 parent, _ = entries[cells[int(rng.integers(len(cells)))]]
247 point = np.clip(parent + self._sigma * rng.standard_normal(self._dimension), 0., 1.)
248 else:
249 point = rng.random(self._dimension)
250 consider(tuple(point))
251 return tuple(entries.values())
252
253 def _acquisition_batch(self, entries, count):
254 available = {point: row.descriptor for point, row in entries if self._raw(point) not in self._attempted}
255 for _ in range(count):
256 if available:
257 points = tuple(available)
258 coords = (np.asarray(tuple(available.values())) - self._feature_lower) / self._feature_width
259 anchor = self._anchors.random(1)
260 position = cdist(anchor, coords, metric="sqeuclidean").argmin()
261 point = points[position]
262 del available[point]
263 else:
264 point = self._unused_design()
265 # Clipped mutation can map different unit vectors to the same physical point.
266 if self._raw(point) in self._attempted:
267 point = self._unused_design()
268 yield point
269
270 def _preview(self, model, seeds):
271 entries = self._illuminate(model, seeds, 0., self._prediction_steps, self._preview_rng)
272 self._predictions = tuple(PrototypePrediction(self._raw(point), row.descriptor, row.fitness)
273 for point, row in entries)
274 if not entries:
275 self._prototypes = self._families = ()
276 return
277 points = np.asarray([point for point, _ in entries])
278 if self._embedding == "tsne" and len(points) >= 4:
279 embedded = TSNE(n_components=2, perplexity=min(30, max(2, (len(points) - 1) // 3)),
280 init="random", random_state=self._cluster_seed).fit_transform(points)
281 embedded -= embedded.mean(axis=0)
282 radius = np.linalg.norm(embedded, axis=1).max()
283 if radius > 0.:
284 embedded /= radius
285 elif len(points) > 1 and points.shape[1] > 2:
286 embedded = PCA(n_components=2, svd_solver="full").fit_transform(points)
287 else:
288 embedded = points
289 labels = DBSCAN(eps=self._eps, min_samples=self._min_samples).fit_predict(embedded)
290 families = {}
291 for position, label in enumerate(labels):
292 families.setdefault((label, position if label < 0 else -1), []).append(position)
293 prototypes, family_points = [], []
294 for members in families.values():
295 distances = cdist(embedded[members], embedded[members])
296 medoid = members[distances.sum(axis=1).argmin()]
297 prototypes.append(Prototype(self.predictions[medoid], tuple(self.predictions[i] for i in members)))
298 family_points.append(tuple(entries[i][0] for i in members))
299 self._prototypes, self._families = tuple(prototypes), tuple(family_points)
300
301
304 def run(self, evaluate, budget):
305 if not callable(evaluate):
306 raise ValueError("evaluate must be callable.")
307 remaining = _attempt_budget(budget)
308 if remaining == 0:
309 return self.stats
310 seeds = self._observations if self._selected is None else self._selected
311 while remaining and (len(self._attempted) < self._initial or len(self._observations) < 2):
312 self._evaluate(evaluate, self._unused_design(), self._selected)
313 remaining -= 1
314 while remaining:
315 entries = self._illuminate(self._fit(), seeds, self._kappa, self._acquisition_steps, self._rng)
316 count = min(remaining, self._batch)
317 for point in self._acquisition_batch(entries, count):
318 self._evaluate(evaluate, point, self._selected)
319 remaining -= count
320 if len(self._observations) >= 2:
321 self._preview(self._fit(), seeds)
322 return self.stats
Cumulative simulator and surrogate work.
Definition produqd.py:49
Surrogate illuminate, cluster predicted elites, and reseed search from selected families.
Definition produqd.py:81
_preview(self, model, seeds)
Definition produqd.py:270
__init__(self, archive, dimension, describe, *, ind_domain=(0., 1.), initial_samples=16, acquisition_steps=128, prediction_steps=256, evaluations_per_fit=4, kappa=2., mutation_sigma=.08, embedding="pca", cluster_eps=.2, min_samples=2, seed=0)
Definition produqd.py:106
_acquisition_batch(self, entries, count)
Definition produqd.py:253
run(self, evaluate, budget)
Spend the supplied true-evaluation budget and refresh prototypes.
Definition produqd.py:304
prototypes(self)
Current clusters and medoids, available after two successful observations.
Definition produqd.py:148
predictions(self)
Predicted fitness and descriptors for current mean-only map elites.
Definition produqd.py:143
_illuminate(self, model, seeds, confidence, steps, rng)
Definition produqd.py:213
stats(self)
Cumulative budgets from the lifetime of this search.
Definition produqd.py:153
select_prototypes(self, indices=None)
Use the specified families from the latest round to seed both maps.
Definition produqd.py:159
_evaluate(self, evaluate, point, seeds)
Definition produqd.py:187
An unevaluated recommendation from the mean-only map.
Definition produqd.py:30
A cluster of predicted elites and its representative in embedding space.
Definition produqd.py:40