QDpy
Loading...
Searching...
No Matches
uncertain.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Uncertain MAP-Elites and independent archive evaluation."""
6
7from collections import Counter, deque
8from dataclasses import dataclass
9import math
10from time import perf_counter
11import warnings
12
13import numpy as np
14
15from qdpy.base import SequentialExecutor, registry
16from qdpy.containers import CVTGrid, Grid
17
18from .evolution import RandomSearchMutPolyBounded
19from .sampling import (
20 SamplingDecorator, _aggregate, _fresh, _history, _observe_result,
21 _rollout_seed, _stage_archive, _valid_observation,
22)
23
24__all__ = ["UncertainMAPElites", "StandardErrorSamplingDecorator", "ArchiveAudit", "reevaluate_archive"]
25
26_POLICIES = ("adaptive", "deep_grid", "deep_grid_sampling", "archive_sampling",
27 "parallel_adaptive", "extract_me", "fill_then_refine")
28
29
30
31def _quality(archive, individual):
32 fitness = archive.get_ind_fitness(individual)
33 return fitness.weighted_values(fitness.weights)[0]
34
35
36
37def _select_elite(archive):
38 cells = [entries for entries in archive.solutions.values() if entries]
39 return max(cells[np.random.randint(len(cells))], key=lambda ind: _quality(archive, ind))
40
41
42
43def _selection_weights(archive, entries):
44 values = np.asarray([_quality(archive, ind) for ind in entries])
45 low, high = archive.fitness_domain[0]
46 weight = archive.get_ind_fitness(entries[0]).weights[0]
47 worst = (low if weight > 0 else high) * weight
48 if np.isfinite(worst):
49 offset = min(worst, values.min())
50 else:
51 offset = min(0., values.min())
52 scale = max(abs(offset), np.max(np.abs(values)), 1.)
53 weights = values / scale - offset / scale
54 return weights / weights.sum() if weights.sum() else None
55
56
57
59def _select_deep_grid(archive):
60 cells = [entries for entries in archive.solutions.values() if entries]
61 entries = cells[np.random.randint(len(cells))]
62 return entries[np.random.choice(len(entries), p=_selection_weights(archive, entries))]
63
64
65
66def _cell(archive, individual):
67 try:
68 return archive.index_grid(individual)
69 except IndexError:
70 return None
71
72
73
74def _incumbent(archive, cell):
75 if cell is None:
76 return None
77 return max(archive.solutions[cell], key=lambda ind: _quality(archive, ind), default=None)
78
79
80
81def _worker(evaluate, individual, seeded):
82 start = perf_counter()
83 try:
84 result = evaluate(individual, individual.evaluation_seed) if seeded else evaluate(individual)
85 if isinstance(result, (tuple, list)) and not result and not hasattr(result, "fitness"):
86 result = individual
87 return result, perf_counter() - start, None
88 except Exception as error:
89 return None, perf_counter() - start, f"{type(error).__name__}: {error}"
90
91
92
96 def __init__(self, archive, evaluate, executor, seed, *, stream=0, seeded=False):
97 self.archive = archive
98 self.evaluate = evaluate
99 self.executor = SequentialExecutor() if executor is None else executor
100 self.seed = seed
101 self.stream = stream
102 self.seeded = seeded
103 self.attempted = 0
104 self.failed = 0
105
106
107 def evaluate_groups(self, groups):
108 jobs = []
109 for original, count in groups:
110 group = []
111 for _ in range(count):
112 candidate = _fresh(original)
113 candidate.evaluation_seed = _rollout_seed(self.seed, self.stream, self.attempted)
114 self.attempted += 1
115 group.append((candidate, self.executor.submit(_worker, self.evaluate, candidate, self.seeded)))
116 jobs.append(group)
117
118 output = []
119 for group in jobs:
120 observations = []
121 for candidate, future in group:
122 result, elapsed, failure = future.result()
123 try:
124 if failure is not None:
125 raise ValueError(failure)
126 obs = _observe_result(self.archive, candidate, result, elapsed)
127 _valid_observation(obs, len(self.archive.fitness_domain), len(self.archive.features_domain))
128 observations.append(obs)
129 except (KeyError, ValueError, TypeError) as error:
130 if self.failed == 0:
131 warnings.warn(f"First failed rollout: {error}", stacklevel=2)
132 self.failed += 1
133 output.append(observations)
134 return output
135
136
137
138@registry.register
140 """Use separate absolute standard-error tolerances for fitness and descriptors.
141
142 :param fitness_tolerance: Maximum objective standard error.
143 :param descriptor_tolerance: Maximum standard error in any descriptor coordinate.
144 :param min_samples: Minimum count needed to estimate standard error.
145 :param max_samples: Hard cap on observations for one proposal.
146 """
147
148 def __init__(self, base_alg, *, fitness_tolerance=0.02, descriptor_tolerance=0.01,
149 min_samples=3, max_samples=10, **kwargs):
150 if (not isinstance(min_samples, int) or not isinstance(max_samples, int)
151 or not 2 <= min_samples <= max_samples):
152 raise ValueError("Use integer sample counts with 2 <= min_samples <= max_samples.")
153 if any(not math.isfinite(tol) or tol < 0 for tol in (fitness_tolerance, descriptor_tolerance)):
154 raise ValueError("Standard-error tolerances must be finite and nonnegative.")
155 self.fitness_tolerance = fitness_tolerance
156 self.descriptor_tolerance = descriptor_tolerance
157 self.min_samples = min_samples
158 self.max_samples = max_samples
159 super().__init__(base_alg, **kwargs)
160
161 def _target(self, individual):
162 return self.min_samples
163
164
165 def _next_target(self, individual, sample_count):
166 if sample_count >= self.max_samples:
167 return sample_count
168 observations = individual._observations
169 scale = math.sqrt(sample_count)
170 fit_error = np.std([row.fitness for row in observations], axis=0, ddof=1) / scale
171 bd_error = np.std([row.features for row in observations], axis=0, ddof=1) / scale
172 return sample_count + int(np.any(fit_error > self.fitness_tolerance)
173 or np.any(bd_error > self.descriptor_tolerance))
174
175
176
178 """Run one published or experimental sampling and archive policy.
179
180 :param container: A standalone fixed Grid or CVTGrid with one objective.
181 :param budget: Maximum search rollouts, inclusive of reevaluations.
182 :param sampling_size: Rollout slots available per generation.
183 :param dimension: Genome length used by the default polynomial emitter.
184 :param policy: Adaptive, Deep-Grid, Deep-Grid-Sampling, Archive-Sampling,
185 Parallel-Adaptive-Sampling, Extract-ME, or fill-then-refine.
186 :param base_alg: Optional QDpy emitter using the same archive. Its
187 selection rule replaces the default selector for the policy.
188 :param initial_samples: Override new-offspring repeats where applicable.
189 :param extraction_fraction: Fraction of a generation reserved for Extract-ME.
190 :param max_samples: Per-solution cap for the local adaptive race.
191 :param limit_descriptor_drift: Apply the cell-visit stopping rule in adaptive races.
192 :param seed: Seed for rollout IDs and the extraction RNG. Seed the
193 caller's Python and NumPy RNGs separately for emitter reproduction.
194 """
195
196 def __init__(self, container, budget, dimension, *, policy="extract_me", sampling_size=128,
197 base_alg=None, ind_domain=(0., 1.), optimisation_task="minimisation",
198 initial_samples=None, extraction_fraction=0.25, max_samples=100,
199 limit_descriptor_drift=True, seed=0):
200 if type(container) not in (Grid, CVTGrid) or container.parents or len(container.fitness_domain) != 1:
201 raise ValueError("UncertainMAPElites requires a standalone fixed grid with a scalar objective.")
202 if policy not in _POLICIES:
203 raise ValueError(f"Use one of the uncertain MAP-Elites policies {_POLICIES}.")
204 if any(not isinstance(n, int) or n < 1 for n in (budget, sampling_size, dimension, max_samples)):
205 raise ValueError("Budget, sampling size, dimension and max_samples must be positive integers.")
206 if initial_samples is None:
207 initial_samples = 5 if policy == "deep_grid_sampling" else 1
208 if not isinstance(initial_samples, int) or not 1 <= initial_samples <= sampling_size:
209 raise ValueError("initial_samples must fit within one generation.")
210 if policy in ("adaptive", "fill_then_refine") and initial_samples != 1:
211 raise ValueError("This policy starts each new candidate with one rollout.")
212 if policy == "fill_then_refine" and sampling_size < 5:
213 raise ValueError("Fill-then-refine requires a sampling size of at least five.")
214 if not 0 <= extraction_fraction < 1:
215 raise ValueError("extraction_fraction must lie in [0, 1).")
216 if policy in ("archive_sampling", "parallel_adaptive") and sampling_size < container.capacity + initial_samples:
217 raise ValueError("The sampling size must fit all incumbents and at least one offspring group.")
218 deep = policy in ("deep_grid", "deep_grid_sampling")
219 if base_alg is not None and base_alg.container is not container:
220 raise ValueError("The base emitter must use the same grid.")
221 if base_alg is None:
223 container, budget, dimension, ind_domain=ind_domain, init_pb=0.1, sel_pb=0.9,
224 mut_pb=1 / dimension, optimisation_task=optimisation_task,
225 parent_selector=_select_deep_grid if deep else _select_elite)
226 self.container = container
227 self.base_alg = base_alg
228 self.budget = budget
229 self.sampling_size = sampling_size
230 self.policy = policy
231 self.initial_samples = initial_samples
232 self.extraction_fraction = extraction_fraction
233 self.max_samples = max_samples
234 self.limit_descriptor_drift = limit_descriptor_drift
235 self.seed = seed
236 self._rng = np.random.default_rng(seed)
237 self._refine = None
238 self._qs = []
239 self.nb_evaluations = 0
240 self.failed_evaluations = 0
241 self.offspring_evaluations = 0
242 self.incumbent_evaluations = 0
243 self.completed_generations = 0
244 if deep:
245 container.discard_random_on_bin_overload = True
246
247
251 def optimise(self, evaluate, *, executor=None, seeded=False):
252 if self.nb_evaluations:
253 raise RuntimeError("Build a new UncertainMAPElites run to restart the search.")
254 self._rollouts = _Rollouts(self.container, evaluate, executor, self.seed, seeded=seeded)
255 try:
256 if self.policy == "adaptive":
257 self._run_adaptive()
258 else:
259 while self._rollouts.attempted < self.budget and self._generation():
260 self.completed_generations += 1
261 finally:
262 self.nb_evaluations = self._rollouts.attempted
263 self.failed_evaluations = self._rollouts.failed
264 del self._rollouts
265 return self.base_alg.best()
266
267
268 def _extract(self, archive, count):
269 entries = []
270 weights = []
271 for cell in archive.solutions.values():
272 ranked = sorted(cell, key=lambda ind: _quality(archive, ind), reverse=True)
273 entries.extend(ranked)
274 weights.extend(np.exp(-np.arange(len(ranked), dtype=float)))
275 count = min(count, len(entries))
276 if not count:
277 return []
278 weights = np.asarray(weights)
279 selected = self._rng.choice(len(entries), count, replace=False, p=weights / weights.sum())
280 return [(entries[i], 1) for i in selected]
281
282
283 def _schedule(self, slots):
284 archive = self.container
285 offspring_samples = self.initial_samples
286 repeats = []
287 if self.policy in ("archive_sampling", "parallel_adaptive"):
288 repeats = [(ind, 1) for ind in archive]
289 if self.policy == "parallel_adaptive" and len(archive):
290 offspring_samples = max(1, int(np.median([len(_history(archive, ind)) for ind in archive])))
291 elif self.policy == "extract_me":
292 repeats = self._extract(archive, int(slots * self.extraction_fraction))
293 elif self.policy == "fill_then_refine":
294 if self._refine is None and archive.filled_bins * 2 >= math.prod(archive.shape):
295 self._refine = deque(sorted(archive, key=lambda ind: len(_history(archive, ind))))
296 if self._refine is not None:
297 offspring_samples = 5
298 capacity = slots // 4
299 while capacity and self._refine:
300 elite = self._refine.popleft()
301 target = max(0, 5 - len(_history(archive, elite)))
302 if archive._index_of(elite) is None or not target:
303 continue
304 if target > capacity:
305 self._refine.appendleft(elite)
306 break
307 repeats.append((elite, target))
308 capacity -= target
309 return repeats, offspring_samples
310
311
312 def _generation(self):
313 slots = min(self.sampling_size, self.budget - self._rollouts.attempted)
314 repeats, offspring_samples = self._schedule(slots)
315 required = sum(count for _, count in repeats)
316 count = (slots - required) // offspring_samples
317 if count < 1:
318 if slots == self.sampling_size:
319 raise ValueError("The generation budget cannot fit all reevaluations and an offspring group.")
320 return False
321 staged = _stage_archive(self.container)
322 self.base_alg.container = staged
323 try:
324 # Archive-sampling generates parents after refilling the archive.
325 # Extract-ME generates offspring from the pre-extraction repertoire.
326 if self.policy == "extract_me":
327 offspring = [self.base_alg.ask() for _ in range(count)]
328 for incumbent, _ in repeats:
329 staged.discard(incumbent)
330 self.incumbent_evaluations += required
331 offspring_rows = None
332 if self.policy == "extract_me":
333 measured = self._rollouts.evaluate_groups(repeats + [(ind, offspring_samples) for ind in offspring])
334 rows, offspring_rows = measured[:len(repeats)], measured[len(repeats):]
335 else:
336 rows = self._rollouts.evaluate_groups(repeats)
337 for (old, _), measured in zip(repeats, rows, strict=True):
338 if not measured:
339 staged.add(old)
340 else:
341 revised = _aggregate(staged, _fresh(old), list(_history(self.container, old)) + measured)
342 self._admit(staged, revised)
343 if self.policy != "extract_me":
344 offspring = [self.base_alg.ask() for _ in range(count)]
345 self.offspring_evaluations += count * offspring_samples
346 if offspring_rows is None:
347 offspring_rows = self._rollouts.evaluate_groups([(ind, offspring_samples) for ind in offspring])
348 for individual, rows in zip(offspring, offspring_rows, strict=True):
349 if len(rows) == offspring_samples:
350 self.base_alg.tell(_aggregate(staged, individual, rows))
351 else:
352 self.base_alg._forget_suggestion(individual)
353 finally:
354 self.base_alg.container = self.container
355 self.container.__dict__.update(staged.__dict__)
356 return True
357
358
359 @staticmethod
360 def _admit(archive, individual):
361 if not archive.in_bounds(archive.get_ind_fitness(individual).values, archive.fitness_domain):
362 return False
363 if _cell(archive, individual) is None:
364 return False
365 return archive.add(individual) is not None
366
367
368 def _run_adaptive(self):
369 while self._rollouts.attempted < self.budget:
370 proposal = self.base_alg.ask()
371 observation = self._one(proposal, incumbent=False)
372 if not observation:
373 self.base_alg._forget_suggestion(proposal)
374 continue
375 _aggregate(self.container, proposal, observation)
376 cell = _cell(self.container, proposal)
377 rival = _incumbent(self.container, cell)
378 if cell is None or rival is None or (
379 len(_history(self.container, rival)) == 1
380 and _quality(self.container, proposal) > _quality(self.container, rival)):
381 self.base_alg.tell(proposal, tell_container=cell is not None)
382 continue
383 staged = _stage_archive(self.container)
384 self.base_alg.container = staged
385 try:
386 result = self._race(staged, proposal, observation)
387 if result is None:
388 self.base_alg._forget_suggestion(proposal)
389 break
390 self.base_alg.tell(proposal, tell_container=result)
391 finally:
392 self.base_alg.container = self.container
393 self.container.__dict__.update(staged.__dict__)
394
395
396 def _one(self, individual, *, incumbent):
397 if self._rollouts.attempted >= self.budget:
398 return None
399 if incumbent:
400 self.incumbent_evaluations += 1
401 else:
402 self.offspring_evaluations += 1
403 return self._rollouts.evaluate_groups([(individual, 1)])[0]
404
405
407 def _race(self, archive, individual, observations, *, incumbent=False):
408 visits = Counter()
409 while True:
410 _aggregate(archive, individual, observations)
411 cell = _cell(archive, individual)
412 if cell is None:
413 return False
414 visits[cell] += 1
415 rival = _incumbent(archive, cell)
416 if rival is None:
417 return True
418 history = _history(archive, rival)
419 ahead = _quality(archive, individual) > _quality(archive, rival)
420 if ahead and len(observations) >= min(len(history), self.max_samples):
421 return True
422 if not ahead:
423 if len(history) < self.max_samples:
424 repeat = self._one(rival, incumbent=True)
425 if repeat is None:
426 return None
427 if repeat:
428 revised_rows = list(history) + repeat
429 revised = _aggregate(archive, _fresh(rival), revised_rows)
430 archive.discard(rival)
431 if _cell(archive, revised) == cell:
432 self._admit(archive, revised)
433 else:
434 moved = self._race(archive, revised, revised_rows, incumbent=True)
435 if moved is None:
436 return None
437 if moved:
438 self._admit(archive, revised)
439 rival = _incumbent(archive, cell)
440 if rival is None:
441 return True
442 behind = _quality(archive, individual) <= _quality(archive, rival)
443 settled = not self.limit_descriptor_drift or 2 * visits[cell] > sum(visits.values())
444 if behind and settled:
445 return False
446 if not behind and len(observations) >= min(len(_history(archive, rival)), self.max_samples):
447 return True
448 if len(observations) >= self.max_samples:
449 return _quality(archive, individual) > _quality(archive, rival)
450 repeat = self._one(individual, incumbent=incumbent)
451 if repeat is None:
452 return None
453 if not repeat:
454 return False
455 observations = observations + repeat
456
457
458
459@dataclass(frozen=True)
461 """Hold corrected metrics independently of search measurements and budget."""
462
463 archive: Grid
464 corrected_qd_score: float
465 corrected_coverage: float
466 cell_drift: float
467 rollout_cell_change: float
468 rollouts: int
469 failed_rollouts: int
470
471
472def _measurement_groups(archive, evaluate, *, samples, seed, estimator,
473 representative="best", selector=None, executor=None):
474 """Share independent rollout measurements across archive projections."""
475 if not isinstance(samples, int) or samples < 1:
476 raise ValueError("samples must be a positive integer.")
477 if estimator not in ("mean", "median") or representative not in ("best", "selector"):
478 raise ValueError("Use mean or median and best or selector.")
479 runner = _Rollouts(archive, evaluate, executor, seed, stream=1, seeded=True)
480 rng = np.random.default_rng([seed, 1])
481 reducer = np.mean if estimator == "mean" else np.median
482
483 def measure():
484 for cell, entries in archive.solutions.items():
485 if not entries:
486 continue
487 best = _incumbent(archive, cell)
488 if representative == "best":
489 requested = [(best, samples)]
490 else:
491 chosen = [selector(archive, entries, rng) if selector else
492 entries[rng.choice(len(entries), p=_selection_weights(archive, entries))]
493 for _ in range(samples)]
494 requested = [(ind, 1) for ind in chosen]
495 rows = [row for group in runner.evaluate_groups(requested) for row in group]
496 if rows:
497 revised = _aggregate(archive, _fresh(best), rows, estimator=lambda values: reducer(values, axis=0))
498 yield cell, revised, rows
499
500 return runner, measure()
501
502
503
513def reevaluate_archive(archive, evaluate, *, samples=32, seed=0, estimator="median",
514 representative="best", selector=None, executor=None):
515 """Build a new depth-one archive without changing the input archive.
516
517 The selector-based audit draws a member on each rollout. Its aggregate
518 describes a source cell's deployment policy. The corrected coverage
519 denominator is the number of cells in the source geometry.
520 """
521 runner, measurements = _measurement_groups(archive, evaluate, samples=samples, seed=seed,
522 estimator=estimator, representative=representative,
523 selector=selector, executor=executor)
524 corrected = _stage_archive(archive)
525 corrected.clear()
526 corrected._max_items_per_bin = 1
527 corrected.discard_random_on_bin_overload = False
528 corrected._capacity = math.prod(corrected.shape)
529 drifted = total = changed_rollouts = successful = 0
530 for cell, revised, rows in measurements:
531 for row in rows:
532 try:
533 destination = archive.index_grid(row.features)
534 except IndexError:
535 destination = None
536 changed_rollouts += destination != cell
537 successful += len(rows)
538 total += 1
539 drifted += _cell(archive, revised) != cell
540 UncertainMAPElites._admit(corrected, revised)
541 return ArchiveAudit(corrected, corrected.qd_score(), corrected.filled_bins / math.prod(archive.shape),
542 drifted / total if total else 0., changed_rollouts / successful if successful else 0.,
543 runner.attempted, runner.failed)
Wrap an optimiser to aggregate one or more rollouts per proposal.
Definition sampling.py:427
Independent audit results and the corresponding corrected archive.
Definition uncertain.py:460
Request repeats until coordinate-wise standard errors meet the tolerances.
Definition uncertain.py:139
_target(self, individual)
Select the initial count for a fresh proposal.
Definition uncertain.py:161
_next_target(self, individual, sample_count)
Use sample standard deviation divided by the square root of sample count.
Definition uncertain.py:165
Coordinate scalar-objective MAP-Elites policies that reevaluate archives.
Definition uncertain.py:177
_one(self, individual, *, incumbent)
Spend one remaining rollout and record the work category.
Definition uncertain.py:396
_schedule(self, slots)
Assign repeat groups using the generation limit and active policy.
Definition uncertain.py:283
optimise(self, evaluate, *, executor=None, seeded=False)
Run the chosen policy and return the current best solution.
Definition uncertain.py:251
_run_adaptive(self)
Run one local race at a time, committing completed archive updates.
Definition uncertain.py:368
_generation(self)
Stage a complete generation with the published reevaluation order.
Definition uncertain.py:312
_admit(archive, individual)
Reject finite estimates outside the grid without treating them as worker errors.
Definition uncertain.py:360
_race(self, archive, individual, observations, *, incumbent=False)
Resolve a challenger or drifting incumbent using successive local comparisons.
Definition uncertain.py:407
_extract(self, archive, count)
Choose one distinct ranked subset for Extract-ME.
Definition uncertain.py:268
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95
evaluate_groups(self, groups)
Return observations per candidate in request order.
Definition uncertain.py:107