QDpy
Loading...
Searching...
No Matches
task_search.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Sequential MAP-Elites runners for fixed tasks and changing environments."""
6
7from collections import deque
8from collections.abc import Mapping
9from dataclasses import dataclass
10from math import isfinite
11from numbers import Real
12import warnings
13
14import numpy as np
15
16from qdpy.containers import CVTGrid, Grid
17from qdpy.containers.base import _IndexedOrderedSet
18from qdpy.phenotype import Features, Fitness, Individual, ScoresDict
19from qdpy.tools import iso_line_dd
20from .modern import _bounds, _positive_int
21
22__all__ = ["MultiTaskResult", "DynamicResult", "mtmb_search", "dynamic_map_elites"]
23
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",
28))
29
30
31
32@dataclass(frozen=True)
34 """Per-task attempt and failure counts alongside the supplied grids."""
35
36 archives: dict
37 attempts_by_task: dict
38 failures_by_task: dict
39
40
41
42@dataclass(frozen=True)
44 """Search and refresh attempts include failed and discarded measurements."""
45
46 archive: Grid
47 offspring_attempts: int
48 refresh_attempts: int
49 failures: int
50 detected_change_ticks: tuple[int, ...]
51 incomplete_updates: int
52
53
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.")
58 return lower, upper
59
60
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.")
73
74
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))
85 scores = ScoresDict()
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
96
97
98def _measure(archive, evaluate, args, genome):
99 """Build a fresh grid entry and resolve its destination before admission."""
100 try:
101 return _measurement(archive, evaluate(*args), genome)
102 except Exception as error:
103 warnings.warn(f"MAP-Elites evaluation failed: {error}", stacklevel=3)
104 return None
105
106
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)
111
112
113
114def _offer_with_age(archive, measurement, last_touched, step):
115 candidate, cell = measurement
116 if cell is None:
117 return
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
126
127
128
129def mtmb_search(archives, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, share_parents=True,
130 on_step=None):
131 """Run fixed-task Multi-Task Multi-Behavior MAP-Elites.
132
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.
136
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.
149 """
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])
171
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)
181 else:
182 child = rng.uniform(*bounds, size=dimension)
183 genome = tuple(map(float, child))
184 attempts[task] += 1
185 measurement = _measure(archive, evaluate, (task, genome), genome)
186 if measurement is None:
187 failures[task] += 1
188 else:
189 _offer(archive, measurement)
190 if on_step is not None:
191 on_step(archives, iteration=step, evaluations=step)
192 return MultiTaskResult(archives, attempts, failures)
193
194
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)}
199 staged = {}
200 changed = False
201 while pending:
202 old = pending.popleft()
203 fresh = remeasure(old)
204 if fresh is None:
205 return None, changed
206 new, cell = fresh
207 different = (
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))
210 )
211 changed |= different
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
221
222
223
224def dynamic_map_elites(archive, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, refresh="local",
225 on_step=None):
226 """Run sequential Dynamic MAP-Elites with a shared attempt budget.
227
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.
231
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.
244 """
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)
257 last_touched = {}
258 offspring_attempts = refresh_attempts = failures = incomplete_updates = step = 0
259 change_ticks = []
260 track_ages = type(archive) is Grid and on_step is None
261
262 def measure(args, genome):
263 nonlocal track_ages
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)):
271 # An evaluator can close over the archive and change its members.
272 track_ages = False
273 return result
274
275 def offer(measurement):
276 if track_ages:
277 _offer_with_age(archive, measurement, last_touched, step)
278 else:
279 _offer(archive, measurement)
280
281 while offspring_attempts + refresh_attempts < budget:
282 tick = offspring_attempts + refresh_attempts
283 step += 1
284 if archive:
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)
289 else:
290 child = rng.uniform(*bounds, size=dimension)
291 genome = tuple(map(float, child))
292 offspring_attempts += 1
293 offspring = measure((genome, tick), genome)
294 complete = True
295 if offspring is None:
296 failures += 1
297 complete = False
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:
302 return None
303 genome = tuple(elite)
304 refresh_attempts += 1
305 result = measure((genome, tick), genome)
306 failures += result is None
307 return result
308
309 staged, changed = _stage_refresh(archive, archive.solutions[cell][0], refresh, remeasure)
310 if changed:
311 change_ticks.append(tick)
312 if staged is None:
313 incomplete_updates += 1
314 complete = False
315 else:
316 original_order = [elite for elite in archive if id(elite) in staged]
317 for old in original_order:
318 archive.discard(old)
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:
323 offer(offspring)
324 if not track_ages:
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)
328
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.
Definition phenotype.py:405