QDpy
Loading...
Searching...
No Matches
descriptor_mutation.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""In-run descriptor replacement with measured archive transfer."""
7
8from collections.abc import Mapping
9from dataclasses import dataclass
10from math import isfinite
11from numbers import Real
12from operator import index
13
14import numpy as np
15
16from qdpy.containers import Grid
17from qdpy.tools import iso_line_dd
18from .modern import _positive_int, _variation_settings
19from .task_search import _measurement, _offer, _search_bounds
20
21__all__ = ["DescriptorAxis", "DescriptorMutationMAPElites", "DescriptorMutationStats", "DescriptorSwitch"]
22
23
24
25@dataclass(frozen=True)
27 """Use the same name in the evaluator's measurement mapping."""
28
29 name: str
30 bounds: tuple[float, float]
31 bins: int
32
33 def __post_init__(self):
34 low, high = map(float, self.bounds)
35 if not isinstance(self.name, str) or not self.name or not (low < high and isfinite(high - low)):
36 raise ValueError("Use a nonempty axis name and a finite, increasing interval.")
37 object.__setattr__(self, "bounds", (low, high))
38 object.__setattr__(self, "bins", _positive_int(self.bins, "bins"))
39
40
41
42@dataclass(frozen=True)
44 """Evaluation counts include attempted callback calls."""
45
46 evaluations: int
47 refresh_evaluations: int
48 switches: int
49
50
51
52@dataclass(frozen=True)
54 """Report source, projected, and transferred elite counts for one switch."""
55
56 previous: DescriptorAxis
57 replacement: DescriptorAxis
58 source_elites: int
59 projected_elites: int
60 transferred_elites: int
61 refresh_evaluations: int
62
63
64
66 """Search with interpretable descriptors and reuse historical elite measurements.
67
68 Evaluators receive a real-valued genome and private integer seed.
69 Return scalar fitness and a mapping of named finite measurements.
70 Include all active axes and optionally any measurements for future
71 swaps. The search owns its Grid and replaces it after a successful
72 rebuild. Retaining a reference to the old Grid gives a snapshot.
73
74 :param axes: Nonempty sequence of distinct DescriptorAxis objects.
75 :param dimension: Number of real genome coordinates.
76 :param fitness_domain: Inclusive scalar reporting fitness bounds.
77 :param maximize: True to prefer higher fitness.
78 :param ind_domain: Shared finite interval for all genome coordinates.
79 :param iso_sigma: Independent mutation standard deviation.
80 :param line_sigma: Shared directional mutation standard deviation.
81 :param seed: Seed for proposals, evaluations, and separate refreshes.
82 """
83
84 def __init__(self, axes, dimension, *, fitness_domain, maximize=True, ind_domain=(0., 1.),
85 iso_sigma=.05, line_sigma=.2, seed=0):
86 self._axes = self._checked_axes(axes)
87 self._dimension = _positive_int(dimension, "dimension")
88 self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma))
89 self._iso, self._line = iso_sigma, line_sigma
90 low, high = map(float, fitness_domain)
91 if not low < high:
92 raise ValueError("Use an increasing fitness interval.")
93 self._fitness_domain = ((low, high),)
94 self._weights = (1.,) if maximize else (-1.,)
95 self._archive = self._grid(self._axes)
96 self._variation, self._measurement, self._refresh = map(
97 np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
98 self._evaluations = self._refresh_evaluations = self._switches = 0
99
100 @staticmethod
101 def _checked_axes(axes):
102 axes = tuple(axes)
103 if (not axes or any(not isinstance(axis, DescriptorAxis) for axis in axes)
104 or len({axis.name for axis in axes}) != len(axes)):
105 raise ValueError("Supply distinct named DescriptorAxis objects.")
106 return axes
107
108 def _grid(self, axes):
109 return Grid(shape=tuple(axis.bins for axis in axes), features_domain=tuple(axis.bounds for axis in axes),
110 fitness_domain=self._fitness_domain, fitness_weights=self._weights, storage_type="orderedset")
111
112 @property
113 def archive(self):
114 """Return the active native grid."""
115 return self._archive
116
117 @property
118 def axes(self):
119 """Return the active named axes in grid order."""
120 return self._axes
121
122 @property
123 def stats(self):
124 """Snapshot cumulative evaluation and switch counts."""
126
127 @staticmethod
128 def _put(archive, axes, genome, fitness, scores):
129 if (not isinstance(scores, Mapping)
130 or any(not isinstance(name, str) or not isinstance(value, Real) or not isfinite(value)
131 for name, value in scores.items())):
132 raise ValueError("Return a mapping from names to finite measurements.")
133 missing = [axis.name for axis in axes if axis.name not in scores]
134 if missing:
135 raise ValueError(f"Missing active descriptor measurements: {', '.join(missing)}.")
136 measurement = _measurement(archive, ((fitness,), tuple(scores[axis.name] for axis in axes)), genome)
137 measurement[0].scores.update({name: float(value) for name, value in scores.items()})
138 _offer(archive, measurement)
139
140 @staticmethod
141 def _seed(rng):
142 return int(rng.integers(2**32))
143
144
145 def run(self, evaluate, budget):
146 """Return cumulative statistics. Evaluator errors propagate to the caller."""
147 if not callable(evaluate):
148 raise TypeError("Provide a callable evaluator.")
149 budget = _positive_int(budget, "budget")
150 rng, archive = self._variation, self._archive
151 for _ in range(budget):
152 if len(archive):
153 first, second = rng.integers(len(archive), size=2)
154 genome = iso_line_dd(archive[first], archive[second], bounds=self._bounds,
155 iso_sigma=self._iso, line_sigma=self._line, rng=rng)
156 else:
157 genome = rng.uniform(*self._bounds, size=self._dimension)
158 genome = tuple(map(float, genome))
159 self._evaluations += 1
160 fitness, scores = evaluate(genome, self._seed(self._measurement))
161 self._put(archive, self._axes, genome, fitness, scores)
162 return self.stats
163
164
165 def report(self, axes):
166 """Project current elites onto supplied axes without new evaluator calls."""
167 axes = self._checked_axes(axes)
168 report = self._grid(axes)
169 for elite in self._archive:
170 self._put(report, axes, elite, elite.fitness.values[0], elite.scores)
171 return report
172
173
174 def switch_axis(self, name, replacement, *, refresh=None, refresh_budget=0):
175 """Replace an axis and rebuild the active grid as one operation.
176
177 Keep the best elite in each cell of the unaffected projection.
178 With one axis, keep the single best elite. Reuse cached values
179 for the replacement axis. If a survivor lacks that measurement,
180 refresh(genome, seed) must return its new scalar descriptor. The
181 refresh budget must cover all missing values before any call is
182 made. On failure the original grid remains active and attempted
183 refreshes are still counted.
184 """
185 if not isinstance(replacement, DescriptorAxis):
186 raise TypeError("replacement must be a DescriptorAxis.")
187 names = [axis.name for axis in self._axes]
188 if name not in names:
189 raise ValueError("The requested descriptor axis is not active.")
190 slot = names.index(name)
191 previous = self._axes[slot]
192 axes = self._checked_axes((*self._axes[:slot], replacement, *self._axes[slot + 1:]))
193 if previous == replacement:
194 raise ValueError("The replacement must change the active axis.")
195 budget = index(refresh_budget)
196 if budget < 0 or (refresh is not None and not callable(refresh)):
197 raise ValueError("Use a nonnegative refresh budget and a callable refresh.")
198 other_axes = tuple(axis for i, axis in enumerate(self._axes) if i != slot)
199 source = self._archive
200 survivors = self.report(other_axes) if other_axes else ((source.best,) if source else ())
201 missing = sum(replacement.name not in elite.scores for elite in survivors)
202 if missing and (refresh is None or missing > budget):
203 raise ValueError(f"The rebuild needs {missing} refresh evaluations.")
204 destination = self._grid(axes)
205 before = self._refresh_evaluations
206 for elite in survivors:
207 scores = dict(elite.scores)
208 if replacement.name not in scores:
209 self._refresh_evaluations += 1
210 scores[replacement.name] = refresh(tuple(elite), self._seed(self._refresh))
211 self._put(destination, axes, elite, elite.fitness.values[0], scores)
212 self._archive, self._axes = destination, axes
213 self._switches += 1
214 return DescriptorSwitch(previous, replacement, len(source), len(survivors), len(destination),
215 self._refresh_evaluations - before)
Describe one named measurement and its grid discretization.
Run MAP-Elites with explicit, transactional descriptor swaps.
switch_axis(self, name, replacement, *, refresh=None, refresh_budget=0)
Collapse onto unaffected axes and transfer the surviving elites.
run(self, evaluate, budget)
Run additional proposals with the current set of descriptor axes.
report(self, axes)
Build a separate reporting grid from cached elite measurements.
Report offspring, extra measurement calls, and successful axis switches.
Summarize the committed rebuild onto the new descriptor geometry.