QDpy
Loading...
Searching...
No Matches
surprise.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Surprise Search with Local Competition for bounded real vectors."""
7
8from collections import deque
9from dataclasses import dataclass
10
11import numpy as np
12from scipy.spatial.distance import cdist
13from sklearn.cluster import KMeans
14from threadpoolctl import threadpool_limits
15
16from qdpy.containers import Grid
17from qdpy.phenotype import Individual
18from .modern import _bounds, _positive_int
19from .sampling import _aggregate
20from .uncertain import _Rollouts, _cell
21
22__all__ = ["SurpriseSearchLC", "NoveltySurpriseSearchLC", "SurpriseSearchResult", "surprise_local_scores"]
23
24
25
26def surprise_local_scores(descriptors, qualities, predictions, *, surprise_neighbors=2, local_neighbors=5):
27 """Return an array with columns (mean forecast distance, local fitness wins).
28
29 Qualities use the maximization convention. For local competition the
30 candidate itself is excluded, even when other descriptors coincide.
31 Distances are Euclidean in the supplied descriptor coordinates.
32 """
33 descriptors, qualities, predictions = map(lambda x: np.asarray(x, dtype=float),
34 (descriptors, qualities, predictions))
35 if (descriptors.ndim != 2 or min(descriptors.shape) == 0 or predictions.ndim != 2
36 or predictions.shape[1] != descriptors.shape[1] or not len(predictions)
37 or qualities.shape != (len(descriptors),)
38 or not all(np.isfinite(x).all() for x in (descriptors, qualities, predictions))):
39 raise ValueError("Supply finite descriptor and prediction matrices and one quality per candidate.")
40 ks = min(_positive_int(surprise_neighbors, "surprise_neighbors"), len(predictions))
41 kl = min(_positive_int(local_neighbors, "local_neighbors"), len(descriptors) - 1)
42 differences = cdist(descriptors, predictions)
43 surprise = np.partition(differences, ks - 1, axis=1)[:, :ks].mean(axis=1)
44 distances = cdist(descriptors, descriptors)
45 np.fill_diagonal(distances, np.inf)
46 neighbors = np.argsort(distances, axis=1, kind="stable")[:, :kl]
47 wins = (qualities[:, None] > qualities[neighbors]).sum(axis=1)
48 return np.column_stack((surprise, wins))
49
50
51def _order(objectives):
52 dominates = ((objectives[:, None] >= objectives).all(axis=2) &
53 (objectives[:, None] > objectives).any(axis=2))
54 remaining = dominates.sum(axis=0)
55 ranks, crowding = np.empty(len(objectives), dtype=int), np.zeros(len(objectives))
56 rank = 0
57 while (front := np.flatnonzero(remaining == 0)).size:
58 ranks[front] = rank
59 remaining[front] = -1
60 remaining -= dominates[front].sum(axis=0)
61 if len(front) <= 2:
62 crowding[front] = np.inf
63 else:
64 for values in objectives.T:
65 ordered = front[np.argsort(values[front], kind="stable")]
66 span = values[ordered[-1]] - values[ordered[0]]
67 if span > 0:
68 crowding[ordered[[0, -1]]] = np.inf
69 crowding[ordered[1:-1]] += (values[ordered[2:]] - values[ordered[:-2]]) / span
70 rank += 1
71 return ranks, crowding
72
73
74def _memory_distances(descriptors, population, history, features):
75 # A point retained both as a breeder and in the novelty memory counts once.
76 active = {id(individual) for individual in population}
77 extras = [individual for individual in history if id(individual) not in active]
78 reference = descriptors if not extras else np.concatenate((descriptors, [features(ind) for ind in extras]))
79 distances = cdist(descriptors, reference)
80 np.fill_diagonal(distances, np.inf)
81 return distances, extras
82
83
84
85@dataclass(frozen=True)
87 """Keep the terminal population separately from the reporting grid."""
88
89 population: tuple
90 evaluations: int
91 failed_evaluations: int
92 forecasts: int
93
94
95
97 """Forecast cluster motion from consecutive population snapshots.
98
99 The grid receives measurements for reporting and cannot influence
100 selection. The breeding population and forecast reset on each call.
101 The grid can retain measurements accumulated before the search.
102
103 :param archive: Reporting Grid or CVTGrid with one signed objective.
104 :param dimension: Number of real-valued decision variables.
105 :param ind_domain: Shared finite lower and upper decision bounds.
106 :param population_size: Number of candidates retained for breeding.
107 :param clusters: Maximum cluster count per snapshot.
108 :param forecast_interval: Offspring between model updates. Defaults to population_size.
109 :param surprise_neighbors: Predictions used for the surprise objective.
110 :param local_neighbors: Population neighbors used for local competition.
111 :param mutation_sigma: Gaussian variation in units of the decision interval.
112 :param seed: Private seed for clustering, offspring, and evaluations.
113 """
114
115 def __init__(self, archive, dimension, *, ind_domain=(0., 1.), population_size=64,
116 clusters=16, forecast_interval=None, surprise_neighbors=2, local_neighbors=5,
117 mutation_sigma=.1, seed=0):
118 if (not isinstance(archive, Grid) or len(archive.fitness_domain or ()) != 1
119 or len(archive.fitness_weights or ()) != 1
120 or not np.isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]
121 or archive.parents):
122 raise ValueError("Use a reporting grid with one signed fitness objective.")
123 self.archive, self.seed = archive, seed
124 self.dimension = _positive_int(dimension, "dimension")
125 self.population_size = _positive_int(population_size, "population_size")
126 if self.population_size < 2 or not 0 < mutation_sigma < np.inf:
127 raise ValueError("Use at least two individuals and positive finite mutation_sigma.")
128 self.clusters = _positive_int(clusters, "clusters")
129 self.forecast_interval = (self.population_size if forecast_interval is None
130 else _positive_int(forecast_interval, "forecast_interval"))
131 self.surprise_neighbors = _positive_int(surprise_neighbors, "surprise_neighbors")
132 self.local_neighbors = _positive_int(local_neighbors, "local_neighbors")
133 self.ind_domain, self.mutation_sigma = _bounds(ind_domain), mutation_sigma
134
135 def _centers(self, population, rng):
136 descriptors = np.asarray([self.archive.get_ind_features(ind) for ind in population])
137 distinct = np.unique(descriptors, axis=0)
138 if len(distinct) <= self.clusters:
139 return distinct
140 with threadpool_limits(limits=1):
141 return KMeans(self.clusters, n_init=1, random_state=int(rng.integers(2**31))).fit(
142 descriptors).cluster_centers_
143
144 def _rank(self, population, predictions, history):
145 descriptors = [self.archive.get_ind_features(ind) for ind in population]
146 qualities = [self.archive.fitness_weights[0] * self.archive.get_ind_fitness(ind).values[0]
147 for ind in population]
148 return _order(surprise_local_scores(descriptors, qualities, predictions,
149 surprise_neighbors=self.surprise_neighbors,
150 local_neighbors=self.local_neighbors))
151
152 def _memory(self):
153 return None
154
155 def _remember(self, population, history):
156 """The original surprise search uses only the active population."""
157
158
162 def run(self, evaluate, budget):
163 """Run bounded real-valued variation with binary NSGA-II tournaments."""
164 budget = _positive_int(budget, "budget")
165 rng = np.random.default_rng([self.seed, 3])
166 runner = _Rollouts(self.archive, evaluate, None, self.seed, stream=3, seeded=True)
167 lo, hi = self.ind_domain
168 population = []
169 history = self._memory()
170
171 def measure(vector):
172 candidate = Individual(vector.tolist())
173 rows, = runner.evaluate_groups([(candidate, 1)])
174 if not rows:
175 return None
176 individual = _aggregate(self.archive, candidate, rows)
177 cell = _cell(self.archive, individual)
178 if (cell is not None and (self.archive.free or self.archive.solutions[cell])
179 and self.archive.in_bounds(self.archive.get_ind_fitness(individual).values,
180 self.archive.fitness_domain)):
181 self.archive.add(individual)
182 return individual
183
184 for _ in range(min(budget, self.population_size)):
185 measured = measure(rng.uniform(lo, hi, size=self.dimension))
186 if measured is not None:
187 population.append(measured)
188 previous = predictions = ranks = crowding = None
189 forecasts = 0
190 for step in range(budget - runner.attempted):
191 if len(population) < self.population_size:
192 measured = measure(rng.uniform(lo, hi, size=self.dimension))
193 if measured is not None:
194 population.append(measured)
195 continue
196 if predictions is None or step % self.forecast_interval == 0:
197 current = self._centers(population, rng)
198 predictions = (current if previous is None else
199 2 * current - previous[cdist(current, previous).argmin(axis=1)])
200 previous = current
201 ranks, crowding = self._rank(population, predictions, history)
202 forecasts += 1
203
204 def tournament():
205 a, b = rng.choice(len(population), 2, replace=False)
206 return np.asarray(population[min((a, b), key=lambda i: (ranks[i], -crowding[i]))])
207
208 first, second = tournament(), tournament()
209 fraction = rng.random(self.dimension)
210 child = first + fraction * (second - first) + rng.normal(
211 scale=self.mutation_sigma * (hi - lo), size=self.dimension)
212 measured = measure(np.clip(child, lo, hi))
213 if measured is not None:
214 population.append(measured)
215 ranks, crowding = self._rank(population, predictions, history)
216 self._remember(population, history)
217 worst = max(range(len(population)), key=lambda i: (ranks[i], -crowding[i], i))
218 population.pop(worst)
219 ranks, crowding = self._rank(population, predictions, history)
220 return SurpriseSearchResult(tuple(population), runner.attempted, runner.failed, forecasts)
221
222
223
225 """Use the same forecasts and steady-state variation as SurpriseSearchLC.
226
227 With a real-valued novelty_weight, NSGA-II maximizes the weighted sum
228 of novelty and surprise beside local wins. With novelty_weight=None,
229 it treats all three signals as separate objectives. Novelty and local
230 wins consider both the live population and past novel offspring.
231 Distances are Euclidean in descriptor coordinates, as in SS-LC.
232
233 :param archive: Passive reporting grid, as in SurpriseSearchLC.
234 :param dimension: Number of decision coordinates.
235 :param novelty_weight: Novelty fraction of the aggregated divergence score.
236 Use None for three-objective NS-SS-LC.
237 :param novelty_neighbors: Number of neighbors for the novelty score.
238 :param novelty_threshold: Add measured offspring whose novelty meets this threshold.
239 :param novelty_history: Maximum number of older novel offspring retained in FIFO order.
240 :param kwargs: Search, forecast, and variation settings accepted by SurpriseSearchLC.
241 """
242
243 def __init__(self, archive, dimension, *, novelty_weight=.5, novelty_neighbors=15,
244 novelty_threshold=.1, novelty_history=512, **kwargs):
245 super().__init__(archive, dimension, **kwargs)
246 if novelty_weight is not None and not 0. <= novelty_weight <= 1.:
247 raise ValueError("Use a novelty_weight between zero and one, or None.")
248 if not 0. <= novelty_threshold < np.inf:
249 raise ValueError("Use a finite nonnegative novelty_threshold.")
250 self.novelty_weight, self.novelty_threshold = novelty_weight, novelty_threshold
251 self.novelty_neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
252 self.novelty_history = _positive_int(novelty_history, "novelty_history")
253
254 def _memory(self):
255 return deque(maxlen=self.novelty_history)
256
257 def _rank(self, population, predictions, history):
258 features, fitness = self.archive.get_ind_features, self.archive.get_ind_fitness
259 descriptors = np.asarray([features(individual) for individual in population], dtype=float)
260 distances, extras = _memory_distances(descriptors, population, history, features)
261 kn = min(self.novelty_neighbors, distances.shape[1] - 1)
262 novelty = np.partition(distances, kn - 1, axis=1)[:, :kn].mean(axis=1)
263 kl = min(self.local_neighbors, distances.shape[1] - 1)
264 local = np.argsort(distances, axis=1, kind="stable")[:, :kl]
265 direction = self.archive.fitness_weights[0]
266 qualities = np.asarray([fitness(ind).values[0] * direction for ind in (*population, *extras)])
267 wins = (qualities[:len(population), None] > qualities[local]).sum(axis=1)
268 deviations = cdist(descriptors, predictions)
269 ks = min(self.surprise_neighbors, len(predictions))
270 surprise = np.partition(deviations, ks - 1, axis=1)[:, :ks].mean(axis=1)
271 weight = self.novelty_weight
272 objectives = ((novelty, surprise, wins) if weight is None
273 else (weight * novelty + (1. - weight) * surprise, wins))
274 return _order(np.column_stack(objectives))
275
276 def _remember(self, population, history):
277 child = population[-1]
278 features = self.archive.get_ind_features
279 active = {id(individual) for individual in population}
280 reference = (*population[:-1], *(ind for ind in history if id(ind) not in active))
281 distances = cdist([features(child)], [features(ind) for ind in reference])[0]
282 kn = min(self.novelty_neighbors, len(distances))
283 if np.partition(distances, kn - 1)[:kn].mean() >= self.novelty_threshold:
284 history.append(child)
Combine novelty, forecast deviation, and local fitness competition.
Definition surprise.py:224
Steady-state NSGA-II using surprise and local fitness competition.
Definition surprise.py:96
_remember(self, population, history)
Definition surprise.py:155
run(self, evaluate, budget)
Perform one-offspring updates and charge all evaluation attempts.
Definition surprise.py:162
_rank(self, population, predictions, history)
Definition surprise.py:144
Return the final breeding population and attempted evaluation counts.
Definition surprise.py:86
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95