5"""Sequential MAP-Elites runners for fixed tasks and changing environments."""
7from collections
import deque
8from collections.abc
import Mapping
9from dataclasses
import dataclass
10from math
import isfinite
11from numbers
import Real
18from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
20from .modern
import _bounds, _positive_int
22__all__ = [
"MultiTaskResult",
"DynamicResult",
"mtmb_search",
"dynamic_map_elites"]
24_GRID_ADMISSION_HOOKS = frozenset((
25 "add",
"discard",
"index_grid",
"_add_internal",
"_add_to_grid",
"_replacement_in_bin",
26 "_add_to_collection",
"_add_to_parents",
"_consider_for_best",
"_check_if_can_be_added",
27 "get_ind_fitness",
"get_ind_features",
"in_bounds",
"_fitness_with_container_weights",
32@dataclass(frozen=True)
34 """Per-task attempt and failure counts alongside the supplied grids."""
37 attempts_by_task: dict
38 failures_by_task: dict
42@dataclass(frozen=True)
44 """Search and refresh attempts include failed and discarded measurements."""
47 offspring_attempts: int
50 detected_change_ticks: tuple[int, ...]
51 incomplete_updates: int
54def _search_bounds(domain):
55 lower, upper = _bounds(tuple(map(float, domain)))
56 if not isfinite(upper - lower):
57 raise ValueError(
"Genome bounds must have a finite span.")
61def _validate_grid(archive, *, empty=True):
62 if (type(archive)
not in (Grid, CVTGrid)
or (empty
and len(archive))
or archive.parents
63 or len(archive.fitness_domain) != 1
or archive.max_items_per_bin != 1
64 or archive.discard_random_on_bin_overload):
65 condition =
"an empty" if empty
else "a"
66 raise ValueError(f
"Supply {condition} parentless, best-only Grid or CVTGrid with one objective.")
67 weights = archive.fitness_weights
68 if weights
is not None and (len(weights) != 1
or not isfinite(weights[0])
or weights[0] == 0):
69 raise ValueError(
"Supply a finite nonzero objective weight.")
70 if len(archive.fitness_score_names)
not in (0, 1)
or len(archive.features_score_names)
not in (
71 0, len(archive.features_domain)):
72 raise ValueError(
"Named scores must match the grid's objective and descriptor counts.")
75def _measurement(archive, result, genome):
76 """Validate measurements and resolve their cell before admission."""
77 (fitness,), descriptors = result
78 descriptors = tuple(descriptors)
79 if len(descriptors) != len(archive.features_domain):
80 raise ValueError(
"Descriptor length must match the grid.")
81 if not all(isinstance(value, Real)
and isfinite(value)
for value
in (fitness, *descriptors)):
82 raise ValueError(
"Fitness and descriptors must be finite real numbers.")
83 fitness = float(fitness)
84 descriptors = tuple(map(float, descriptors))
86 for name, value
in [*zip(archive.fitness_score_names, (fitness,)),
87 *zip(archive.features_score_names, descriptors)]:
88 if scores.setdefault(name, value) != value:
89 raise ValueError(f
"Conflicting measurements for score {name!r}.")
90 candidate =
Individual(genome, fitness=
Fitness((fitness,), weights=archive.fitness_weights),
91 features=
Features(descriptors), scores=scores)
92 if (archive.in_bounds(descriptors, archive.features_domain)
93 and archive.in_bounds((fitness,), archive.fitness_domain)):
94 return candidate, archive.index_grid(descriptors)
95 return candidate,
None
98def _measure(archive, evaluate, args, genome):
99 """Build a fresh grid entry and resolve its destination before admission."""
101 return _measurement(archive, evaluate(*args), genome)
102 except Exception
as error:
103 warnings.warn(f
"MAP-Elites evaluation failed: {error}", stacklevel=3)
107def _offer(archive, measurement):
108 candidate, cell = measurement
109 if cell
is not None and (archive.solutions[cell]
or archive.free >= 1):
110 archive.add(candidate)
114def _offer_with_age(archive, measurement, last_touched, step):
115 candidate, cell = measurement
118 front = archive.solutions[cell]
119 previous = front[0]
if front
else None
120 nb_added = archive.nb_added
121 _offer(archive, measurement)
122 if archive.nb_added != nb_added:
123 if previous
is not None:
124 del last_touched[id(previous)]
125 last_touched[id(candidate)] = step
129def mtmb_search(archives, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, share_parents=
True,
131 """Run fixed-task Multi-Task Multi-Behavior MAP-Elites.
133 Each proposal is evaluated for one task and can only enter that task's
134 grid. After warm-up, select each parent by first drawing a populated task
135 and then drawing an elite from it.
137 :param archives: Mapping from task IDs to distinct, empty best-only grids.
138 :param evaluate: Callable taking a task ID and a tuple of real coordinates.
139 Return a one-value fitness tuple followed by the descriptors.
140 :param dimension: Number of genome coordinates.
141 :param budget: Total attempted evaluations across all tasks.
142 :param ind_domain: Shared inclusive genome bounds.
143 :param seed: Seed for independent task-selection and variation streams.
144 :param share_parents: Draw from all populated tasks. False limits the
145 parent pool to the task being evaluated.
146 :param on_step: Optional callback receiving the task archives and the
147 keyword arguments ``iteration`` and ``evaluations`` after each attempt.
148 :returns: The live task archives and their attempt and failure counts.
150 if not isinstance(archives, Mapping)
or not archives:
151 raise ValueError(
"Supply a nonempty mapping of task IDs to grids.")
152 archives = dict(archives)
153 if len({id(archive)
for archive
in archives.values()}) != len(archives):
154 raise ValueError(
"Use a distinct archive for each task.")
155 for archive
in archives.values():
156 _validate_grid(archive)
157 if not callable(evaluate):
158 raise TypeError(
"evaluate must be callable.")
159 if on_step
is not None and not callable(on_step):
160 raise TypeError(
"on_step must be callable.")
161 dimension = _positive_int(dimension,
"dimension")
162 budget = _positive_int(budget,
"budget")
163 bounds = _search_bounds(ind_domain)
164 task_seed, variation_seed = np.random.SeedSequence(seed).spawn(2)
165 tasks_rng = np.random.default_rng(task_seed)
166 rng = np.random.default_rng(variation_seed)
167 tasks = tuple(archives)
168 attempts = dict.fromkeys(tasks, 0)
169 failures = dict.fromkeys(tasks, 0)
170 iso_sigma = 0.01 * (bounds[1] - bounds[0])
172 for step
in range(1, budget + 1):
173 task = tasks[tasks_rng.integers(len(tasks))]
174 archive = archives[task]
175 populated = [grid
for grid
in archives.values()
if grid]
176 parents = populated
if share_parents
else ([archive]
if archive
else [])
177 if parents
and sum(map(len, populated)) >= len(tasks):
178 first, second = (parents[i]
for i
in rng.integers(len(parents), size=2))
179 child = iso_line_dd(first[rng.integers(len(first))], second[rng.integers(len(second))],
180 iso_sigma=iso_sigma, bounds=bounds, rng=rng)
182 child = rng.uniform(*bounds, size=dimension)
183 genome = tuple(map(float, child))
185 measurement = _measure(archive, evaluate, (task, genome), genome)
186 if measurement
is None:
189 _offer(archive, measurement)
190 if on_step
is not None:
191 on_step(archives, iteration=step, evaluations=step)
195def _stage_refresh(archive, incumbent, refresh, remeasure):
196 """Follow occupied destinations with the original grid still in place."""
197 pending = deque([incumbent])
198 visited = {id(incumbent)}
202 old = pending.popleft()
203 fresh = remeasure(old)
208 archive.get_ind_fitness(new).values != archive.get_ind_fitness(old).values
209 or tuple(archive.get_ind_features(new)) != tuple(archive.get_ind_features(old))
212 staged[id(old)] = fresh
213 if refresh ==
"all" and old
is incumbent
and different:
214 pending.extend(elite
for elite
in archive
if elite
is not incumbent)
215 elif refresh ==
"local" and cell
is not None and archive.solutions[cell]:
216 neighbour = archive.solutions[cell][0]
217 if id(neighbour)
not in visited:
218 visited.add(id(neighbour))
219 pending.append(neighbour)
220 return staged, changed
224def dynamic_map_elites(archive, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, refresh=
"local",
226 """Run sequential Dynamic MAP-Elites with a shared attempt budget.
228 The evaluator receives a frozen tick for the offspring and its refresh
229 chain. Publish a step only after all required refresh calls succeed.
230 A finite measurement outside the archive domain is valid and unstorable.
232 :param archive: Empty, parentless, best-only Grid or CVTGrid.
233 :param evaluate: Callable accepting a genome and the attempts already
234 spent at the start of the step. Return ``((fitness,), descriptors)``.
235 :param dimension: Number of real genome coordinates.
236 :param budget: Attempt limit inclusive of incumbent refreshes.
237 :param ind_domain: Shared inclusive genome bounds.
238 :param seed: Seed for parent selection and mutation.
239 :param refresh: Use local cascading refresh, refresh all on a change,
240 or perform no refresh (``"local"``, ``"all"``, ``"none"``).
241 :param on_step: Optional callback receiving the archive and the keyword
242 arguments ``iteration`` and ``evaluations`` after each search step.
243 :returns: The live archive and counts for search, refreshes and failures.
245 _validate_grid(archive)
246 if refresh
not in (
"local",
"all",
"none"):
247 raise ValueError(
"refresh must be 'local', 'all', or 'none'.")
248 if not callable(evaluate):
249 raise TypeError(
"evaluate must be callable.")
250 if on_step
is not None and not callable(on_step):
251 raise TypeError(
"on_step must be callable.")
252 dimension = _positive_int(dimension,
"dimension")
253 budget = _positive_int(budget,
"budget")
254 bounds = _search_bounds(ind_domain)
255 sigma = 0.1 * (bounds[1] - bounds[0])
256 rng = np.random.default_rng(seed)
258 offspring_attempts = refresh_attempts = failures = incomplete_updates = step = 0
260 track_ages = type(archive)
is Grid
and on_step
is None
262 def measure(args, genome):
264 revision = archive.nb_operations
if track_ages
else None
265 result = _measure(archive, evaluate, args, genome)
266 if revision
is not None and (revision != archive.nb_operations
or archive.parents
267 or archive.max_items_per_bin != 1
268 or archive.discard_random_on_bin_overload
269 or type(archive.items)
not in (list, _IndexedOrderedSet)
270 or not vars(archive).keys().isdisjoint(_GRID_ADMISSION_HOOKS)):
275 def offer(measurement):
277 _offer_with_age(archive, measurement, last_touched, step)
279 _offer(archive, measurement)
281 while offspring_attempts + refresh_attempts < budget:
282 tick = offspring_attempts + refresh_attempts
285 scales = [1 + step - last_touched[id(elite)]
for elite
in archive]
286 parent = archive[rng.exponential(scales).argmax()]
287 last_touched[id(parent)] = step
288 child = np.clip(np.asarray(parent) + rng.normal(0, sigma, size=dimension), *bounds)
290 child = rng.uniform(*bounds, size=dimension)
291 genome = tuple(map(float, child))
292 offspring_attempts += 1
293 offspring = measure((genome, tick), genome)
295 if offspring
is None:
298 elif (cell := offspring[1])
is not None and refresh !=
"none" and archive.solutions[cell]:
299 def remeasure(elite):
300 nonlocal refresh_attempts, failures
301 if offspring_attempts + refresh_attempts >= budget:
303 genome = tuple(elite)
304 refresh_attempts += 1
305 result = measure((genome, tick), genome)
306 failures += result
is None
309 staged, changed = _stage_refresh(archive, archive.solutions[cell][0], refresh, remeasure)
311 change_ticks.append(tick)
313 incomplete_updates += 1
316 original_order = [elite
for elite
in archive
if id(elite)
in staged]
317 for old
in original_order:
319 del last_touched[id(old)]
320 for old
in original_order:
321 offer(staged[id(old)])
322 if complete
and offspring[1]
is not None:
325 last_touched = {id(elite): last_touched.get(id(elite), step)
for elite
in archive}
326 if on_step
is not None:
327 on_step(archive, iteration=step, evaluations=offspring_attempts + refresh_attempts)
329 return DynamicResult(archive, offspring_attempts, refresh_attempts, failures,
330 tuple(change_ticks), incomplete_updates)
A dynamic archive and the evaluator calls spent maintaining it.
Live task archives and counters from a fixed-task search.
:param obj: Slice indicating on which objectives the domination is tested.