5"""Uncertain MAP-Elites and independent archive evaluation."""
7from collections
import Counter, deque
8from dataclasses
import dataclass
10from time
import perf_counter
15from qdpy.base import SequentialExecutor, registry
18from .evolution
import RandomSearchMutPolyBounded
19from .sampling
import (
20 SamplingDecorator, _aggregate, _fresh, _history, _observe_result,
21 _rollout_seed, _stage_archive, _valid_observation,
24__all__ = [
"UncertainMAPElites",
"StandardErrorSamplingDecorator",
"ArchiveAudit",
"reevaluate_archive"]
26_POLICIES = (
"adaptive",
"deep_grid",
"deep_grid_sampling",
"archive_sampling",
27 "parallel_adaptive",
"extract_me",
"fill_then_refine")
31def _quality(archive, individual):
32 fitness = archive.get_ind_fitness(individual)
33 return fitness.weighted_values(fitness.weights)[0]
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))
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())
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
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))]
66def _cell(archive, individual):
68 return archive.index_grid(individual)
74def _incumbent(archive, cell):
77 return max(archive.solutions[cell], key=
lambda ind: _quality(archive, ind), default=
None)
81def _worker(evaluate, individual, seeded):
82 start = perf_counter()
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"):
87 return result, perf_counter() - start,
None
88 except Exception
as error:
89 return None, perf_counter() - start, f
"{type(error).__name__}: {error}"
96 def __init__(self, archive, evaluate, executor, seed, *, stream=0, seeded=False):
109 for original, count
in groups:
111 for _
in range(count):
112 candidate = _fresh(original)
121 for candidate, future
in group:
122 result, elapsed, failure = future.result()
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:
131 warnings.warn(f
"First failed rollout: {error}", stacklevel=2)
133 output.append(observations)
140 """Use separate absolute standard-error tolerances for fitness and descriptors.
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.
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.")
159 super().__init__(base_alg, **kwargs)
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
178 """Run one published or experimental sampling and archive policy.
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.
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.")
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)
236 self.
_rng = np.random.default_rng(seed)
245 container.discard_random_on_bin_overload =
True
251 def optimise(self, evaluate, *, executor=None, seeded=False):
253 raise RuntimeError(
"Build a new UncertainMAPElites run to restart the search.")
256 if self.
policy ==
"adaptive":
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))
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]
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":
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))))
297 offspring_samples = 5
298 capacity = slots // 4
299 while capacity
and self.
_refine:
301 target = max(0, 5 - len(_history(archive, elite)))
302 if archive._index_of(elite)
is None or not target:
304 if target > capacity:
307 repeats.append((elite, target))
309 return repeats, offspring_samples
314 repeats, offspring_samples = self.
_schedule(slots)
315 required = sum(count
for _, count
in repeats)
316 count = (slots - required) // offspring_samples
319 raise ValueError(
"The generation budget cannot fit all reevaluations and an offspring group.")
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)
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):]
336 rows = self.
_rollouts.evaluate_groups(repeats)
337 for (old, _), measured
in zip(repeats, rows, strict=
True):
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)]
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))
352 self.
base_alg._forget_suggestion(individual)
355 self.
container.__dict__.update(staged.__dict__)
361 if not archive.in_bounds(archive.get_ind_fitness(individual).values, archive.fitness_domain):
363 if _cell(archive, individual)
is None:
365 return archive.add(individual)
is not None
371 observation = self.
_one(proposal, incumbent=
False)
373 self.
base_alg._forget_suggestion(proposal)
375 _aggregate(self.
container, proposal, observation)
378 if cell
is None or rival
is None or (
379 len(_history(self.
container, rival)) == 1
381 self.
base_alg.tell(proposal, tell_container=cell
is not None)
386 result = self.
_race(staged, proposal, observation)
388 self.
base_alg._forget_suggestion(proposal)
390 self.
base_alg.tell(proposal, tell_container=result)
393 self.
container.__dict__.update(staged.__dict__)
396 def _one(self, individual, *, incumbent):
403 return self.
_rollouts.evaluate_groups([(individual, 1)])[0]
407 def _race(self, archive, individual, observations, *, incumbent=False):
410 _aggregate(archive, individual, observations)
411 cell = _cell(archive, individual)
415 rival = _incumbent(archive, cell)
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):
424 repeat = self.
_one(rival, incumbent=
True)
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)
434 moved = self.
_race(archive, revised, revised_rows, incumbent=
True)
438 self.
_admit(archive, revised)
439 rival = _incumbent(archive, cell)
442 behind = _quality(archive, individual) <= _quality(archive, rival)
444 if behind
and settled:
446 if not behind
and len(observations) >= min(len(_history(archive, rival)), self.
max_samples):
449 return _quality(archive, individual) > _quality(archive, rival)
450 repeat = self.
_one(individual, incumbent=incumbent)
455 observations = observations + repeat
459@dataclass(frozen=True)
461 """Hold corrected metrics independently of search measurements and budget."""
464 corrected_qd_score: float
465 corrected_coverage: float
467 rollout_cell_change: float
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
484 for cell, entries
in archive.solutions.items():
487 best = _incumbent(archive, cell)
488 if representative ==
"best":
489 requested = [(best, samples)]
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]
497 revised = _aggregate(archive, _fresh(best), rows, estimator=
lambda values: reducer(values, axis=0))
498 yield cell, revised, rows
500 return runner, measure()
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.
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.
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)
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:
533 destination = archive.index_grid(row.features)
536 changed_rollouts += destination != cell
537 successful += len(rows)
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.
Independent audit results and the corresponding corrected archive.
Request repeats until coordinate-wise standard errors meet the tolerances.
_target(self, individual)
Select the initial count for a fresh proposal.
_next_target(self, individual, sample_count)
Use sample standard deviation divided by the square root of sample count.
Coordinate scalar-objective MAP-Elites policies that reevaluate archives.
_one(self, individual, *, incumbent)
Spend one remaining rollout and record the work category.
_schedule(self, slots)
Assign repeat groups using the generation limit and active policy.
optimise(self, evaluate, *, executor=None, seeded=False)
Run the chosen policy and return the current best solution.
_run_adaptive(self)
Run one local race at a time, committing completed archive updates.
int offspring_evaluations
int incumbent_evaluations
_generation(self)
Stage a complete generation with the published reevaluation order.
int completed_generations
_admit(archive, individual)
Reject finite estimates outside the grid without treating them as worker errors.
_race(self, archive, individual, observations, *, incumbent=False)
Resolve a challenger or drifting incumbent using successive local comparisons.
_extract(self, archive, count)
Choose one distinct ranked subset for Extract-ME.
Dispatch rollouts and resolve them in submission order.
evaluate_groups(self, groups)
Return observations per candidate in request order.