QDpy
Loading...
Searching...
No Matches
multi_descriptor_selection.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Use one behavioral descriptor for selection and another for grid admission."""
7
8import numpy as np
9from scipy.spatial.distance import cdist
10from sklearn.cluster import KMeans
11from threadpoolctl import threadpool_limits
12
13from qdpy.base import registry
14from qdpy.containers import Grid
15from qdpy.tools import iso_line_dd
16
17from ._population import _finite_vector, _tournament
18from .modern import _FixedGeneration, _positive_int, _variation_settings
19from .surprise import _order
20
21__all__ = ["MultiDescriptorMAPElites"]
22
23
24def _nearest_means(distances, count):
25 return np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
26
27
28
29@registry.register
31 """Independently measure selection and archive descriptors.
32
33 The third item of the evaluator result is a score mapping. Store
34 the numeric selection vector under ``selection_score``. The archive
35 uses the ordinary feature vector and scalar fitness. All parents in
36 a batch come from the same measured archive snapshot.
37
38 :param container: Parentless best-only Grid or CVTGrid.
39 :param budget: Managed evaluation attempts.
40 :param dimension: Length of each real vector.
41 :param selection_size: Number of coordinates in the selection vector.
42 :param selection_score: Name of the vector in candidate scores.
43 :param mode: ``uniform``, ``novelty``, ``surprise``, ``blend``, or ``pareto``.
44 :param neighbors: Number of closest other elites for novelty.
45 :param clusters: Maximum number of cluster centers for forecasting surprise.
46 :param surprise_neighbors: Forecast centers averaged in the surprise score.
47 :param novelty_weight: Weight of novelty in the blended score.
48 :param ind_domain: Common interval for all genome coordinates.
49 :param iso_sigma: Independent Gaussian variation per coordinate.
50 :param line_sigma: Gaussian variation along the difference of two parents.
51 :param seed: Private seed for selection, variation, and forecasting.
52 :param batch_size: Evaluations per archive snapshot.
53 :param kwargs: Native optimiser options such as the objective direction.
54 """
55
56 _requires_proposed_genome = True
57
58 def __init__(self, container, budget, dimension, *, selection_size, selection_score="selection",
59 mode="novelty", neighbors=15, clusters=12, surprise_neighbors=2, novelty_weight=.6,
60 ind_domain=(0., 1.), iso_sigma=.05, line_sigma=.2, seed=0, batch_size=16, **kwargs):
61 if (not isinstance(container, Grid) or container.parents or container.max_items_per_bin != 1
62 or container.discard_random_on_bin_overload or len(container.fitness_weights or ()) != 1
63 or not np.isfinite(container.fitness_weights[0]) or not container.fitness_weights[0]):
64 raise ValueError("Supply a parentless best-only grid with one signed objective.")
65 if mode not in ("uniform", "novelty", "surprise", "blend", "pareto"):
66 raise ValueError("Choose uniform, novelty, surprise, blend, or pareto selection.")
67 if not isinstance(selection_score, str) or not selection_score or not 0. <= novelty_weight <= 1.:
68 raise ValueError("Supply a score name and a novelty weight in [0, 1].")
69 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
70 self._width = _positive_int(selection_size, "selection_size")
71 self._score, self.mode, self._weight = selection_score, mode, novelty_weight
72 self._neighbors = _positive_int(neighbors, "neighbors")
73 self._clusters = _positive_int(clusters, "clusters")
74 self._surprise_neighbors = _positive_int(surprise_neighbors, "surprise_neighbors")
75 self._iso, self._line, self.seed = iso_sigma, line_sigma, seed
76 dimension = _positive_int(dimension, "dimension")
77 for row in container:
78 self._descriptor(row)
79 if len(row) != dimension or not all(self.ind_domain[0] <= x <= self.ind_domain[1] for x in row):
80 raise ValueError("Warm-start genomes must match dimension and bounds.")
81 kwargs.setdefault("optimisation_task", container.fitness_weights)
82 super().__init__(container, _positive_int(budget, "budget"), dimension=dimension,
83 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
84
85 def reinit(self):
86 """Reset forecasting and private random streams."""
87 super().reinit()
88 self._rng, self._model_rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(2))
89 self._previous_centers = None
90 self._breeders = ()
91 self._probabilities = self._keys = None
92 self._forecasts = 0
93
94 @property
95 def forecasts(self):
96 """Return the number of forecasts with two observed archive snapshots."""
97 return self._forecasts
98
99 def _descriptor(self, row):
100 if self._score not in row.scores:
101 raise ValueError(f"Missing selection descriptor {self._score!r}.")
102 return _finite_vector(row.scores[self._score], "Selection descriptor", self._width)
103
104 def _check_candidate(self, individual):
105 super()._check_candidate(individual)
106 self._descriptor(individual)
107
108 def _selection_scores(self, points):
109 # A common scaling of the two distance scores preserves rankings and
110 # roulette weights. Work in scaled coordinates before extrapolating.
111 previous = self._previous_centers
112 scale = max(1., float(np.max(np.abs(points))),
113 0. if previous is None else float(np.max(np.abs(previous))))
114 scaled = points / scale
115 novelty = np.zeros(len(points))
116 surprise = np.zeros(len(points))
117 if len(points) > 1 and self.mode in ("novelty", "blend", "pareto"):
118 distances = cdist(scaled, scaled)
119 np.fill_diagonal(distances, np.inf)
120 novelty = _nearest_means(distances, min(len(points) - 1, self._neighbors))
121 if self.mode in ("surprise", "blend", "pareto"):
122 centers = np.unique(scaled, axis=0)
123 if len(centers) > self._clusters:
124 with threadpool_limits(limits=1):
125 centers = KMeans(self._clusters, n_init=1, random_state=int(
126 self._model_rng.integers(2**31))).fit(scaled).cluster_centers_
127 if previous is not None:
128 old = previous / scale
129 predicted = 2. * centers - old[cdist(centers, old).argmin(axis=1)]
130 surprise = _nearest_means(cdist(scaled, predicted), min(self._surprise_neighbors, len(centers)))
131 self._forecasts += 1
132 self._previous_centers = np.clip(centers, scaled.min(axis=0), scaled.max(axis=0)) * scale
133 return novelty, surprise
134
135 def _start_fixed_batch(self, size):
136 super()._start_fixed_batch(size)
137 self._breeders = tuple(self.container)
138 if not self._breeders or self.mode == "uniform":
139 return
140 novelty, surprise = self._selection_scores(np.asarray([self._descriptor(row) for row in self._breeders]))
141 if self.mode == "pareto":
142 rank, crowding = _order(np.column_stack((novelty, surprise)))
143 self._keys = tuple(zip(rank, -crowding))
144 return
145 if self.mode == "novelty":
146 weights = novelty
147 elif self.mode == "surprise":
148 weights = surprise
149 else:
150 weights = self._weight * novelty + (1. - self._weight) * surprise
151 self._probabilities = weights / weights.sum() if weights.any() else None
152
153 def _clear_generation(self):
154 super()._clear_generation()
155 self._breeders = ()
156 self._probabilities = self._keys = None
157
158 def _parent(self):
159 if self._keys is not None:
160 return _tournament(self._breeders, self._keys, self._rng)
161 return self._breeders[self._rng.choice(len(self._breeders), p=self._probabilities)]
162
163 def _internal_ask(self, base_ind):
164 if not self._breeders:
165 base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension).tolist()
166 return base_ind
167 first, second = self._parent(), self._parent()
168 if self._lineage_recorder is not None:
169 self._lineage_recorder._parentage("iso_line_dd", (first, second))
170 base_ind[:] = iso_line_dd(first, second, bounds=self.ind_domain, iso_sigma=self._iso,
171 line_sigma=self._line, rng=self._rng)
172 return base_ind
Use novelty, surprise, or both to select parents among native archive elites.