6"""Surprise Search with Local Competition for bounded real vectors."""
8from collections
import deque
9from dataclasses
import dataclass
12from scipy.spatial.distance
import cdist
13from sklearn.cluster
import KMeans
14from threadpoolctl
import threadpool_limits
18from .modern
import _bounds, _positive_int
19from .sampling
import _aggregate
20from .uncertain
import _Rollouts, _cell
22__all__ = [
"SurpriseSearchLC",
"NoveltySurpriseSearchLC",
"SurpriseSearchResult",
"surprise_local_scores"]
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).
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.
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))
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))
57 while (front := np.flatnonzero(remaining == 0)).size:
60 remaining -= dominates[front].sum(axis=0)
62 crowding[front] = np.inf
64 for values
in objectives.T:
65 ordered = front[np.argsort(values[front], kind=
"stable")]
66 span = values[ordered[-1]] - values[ordered[0]]
68 crowding[ordered[[0, -1]]] = np.inf
69 crowding[ordered[1:-1]] += (values[ordered[2:]] - values[ordered[:-2]]) / span
71 return ranks, crowding
74def _memory_distances(descriptors, population, history, features):
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
85@dataclass(frozen=True)
87 """Keep the terminal population separately from the reporting grid."""
91 failed_evaluations: int
97 """Forecast cluster motion from consecutive population snapshots.
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.
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.
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]
122 raise ValueError(
"Use a reporting grid with one signed fitness objective.")
124 self.
dimension = _positive_int(dimension,
"dimension")
125 self.
population_size = _positive_int(population_size,
"population_size")
127 raise ValueError(
"Use at least two individuals and positive finite mutation_sigma.")
128 self.
clusters = _positive_int(clusters,
"clusters")
130 else _positive_int(forecast_interval,
"forecast_interval"))
132 self.
local_neighbors = _positive_int(local_neighbors,
"local_neighbors")
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)
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_
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,
156 """The original surprise search uses only the active population."""
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])
173 rows, = runner.evaluate_groups([(candidate, 1)])
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,
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
190 for step
in range(budget - runner.attempted):
192 measured = measure(rng.uniform(lo, hi, size=self.
dimension))
193 if measured
is not None:
194 population.append(measured)
197 current = self.
_centers(population, rng)
198 predictions = (current
if previous
is None else
199 2 * current - previous[cdist(current, previous).argmin(axis=1)])
201 ranks, crowding = self.
_rank(population, predictions, history)
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]))])
208 first, second = tournament(), tournament()
210 child = first + fraction * (second - first) + rng.normal(
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)
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)
225 """Use the same forecasts and steady-state variation as SurpriseSearchLC.
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.
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.
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.")
252 self.
novelty_history = _positive_int(novelty_history,
"novelty_history")
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)
262 novelty = np.partition(distances, kn - 1, axis=1)[:, :kn].mean(axis=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)
270 surprise = np.partition(deviations, ks - 1, axis=1)[:, :ks].mean(axis=1)
272 objectives = ((novelty, surprise, wins)
if weight
is None
273 else (weight * novelty + (1. - weight) * surprise, wins))
274 return _order(np.column_stack(objectives))
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]
284 history.append(child)
Combine novelty, forecast deviation, and local fitness competition.
_remember(self, population, history)
Steady-state NSGA-II using surprise and local fitness competition.
_remember(self, population, history)
_centers(self, population, rng)
run(self, evaluate, budget)
Perform one-offspring updates and charge all evaluation attempts.
_rank(self, population, predictions, history)
Return the final breeding population and attempted evaluation counts.
Dispatch rollouts and resolve them in submission order.