Source code for qdpy.algorithms.uncertain

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites policies for allocating rollouts in uncertain domains.

"""Uncertain MAP-Elites and independent archive evaluation."""

from collections import Counter, deque
from dataclasses import dataclass
import math
from time import perf_counter
import warnings

import numpy as np

from qdpy.base import SequentialExecutor, registry
from qdpy.containers import CVTGrid, Grid

from .evolution import RandomSearchMutPolyBounded
from .sampling import (
    SamplingDecorator, _aggregate, _fresh, _history, _observe_result,
    _rollout_seed, _stage_archive, _valid_observation,
)

__all__ = ["UncertainMAPElites", "StandardErrorSamplingDecorator", "ArchiveAudit", "reevaluate_archive"]

_POLICIES = ("adaptive", "deep_grid", "deep_grid_sampling", "archive_sampling",
             "parallel_adaptive", "extract_me", "fill_then_refine")


## @brief Pick the highest-weighted objective in a scalar-objective archive.
def _quality(archive, individual):
    fitness = archive.get_ind_fitness(individual)
    return fitness.weighted_values(fitness.weights)[0]


## @brief Choose a cell uniformly and select its highest-quality member.
def _select_elite(archive):
    cells = [entries for entries in archive.solutions.values() if entries]
    return max(cells[np.random.randint(len(cells))], key=lambda ind: _quality(archive, ind))


## @brief Convert quality measurements to nonnegative proportional selection weights.
def _selection_weights(archive, entries):
    values = np.asarray([_quality(archive, ind) for ind in entries])
    low, high = archive.fitness_domain[0]
    weight = archive.get_ind_fitness(entries[0]).weights[0]
    worst = (low if weight > 0 else high) * weight
    if np.isfinite(worst):
        offset = min(worst, values.min())
    else:
        offset = min(0., values.min())
    scale = max(abs(offset), np.max(np.abs(values)), 1.)
    weights = values / scale - offset / scale
    return weights / weights.sum() if weights.sum() else None


## @brief Choose uniformly among occupied cells, then proportionately to fitness.
# @see https://arxiv.org/html/2006.14253
def _select_deep_grid(archive):
    cells = [entries for entries in archive.solutions.values() if entries]
    entries = cells[np.random.randint(len(cells))]
    return entries[np.random.choice(len(entries), p=_selection_weights(archive, entries))]


## @brief Report whether a descriptor estimate maps into a configured cell.
def _cell(archive, individual):
    try:
        return archive.index_grid(individual)
    except IndexError:
        return None


## @brief Select the active incumbent for a local comparison.
def _incumbent(archive, cell):
    if cell is None:
        return None
    return max(archive.solutions[cell], key=lambda ind: _quality(archive, ind), default=None)


## @brief Evaluate one worker job and preserve in-place evaluation results.
def _worker(evaluate, individual, seeded):
    start = perf_counter()
    try:
        result = evaluate(individual, individual.evaluation_seed) if seeded else evaluate(individual)
        if isinstance(result, (tuple, list)) and not result and not hasattr(result, "fitness"):
            result = individual
        return result, perf_counter() - start, None
    except Exception as error:
        return None, perf_counter() - start, f"{type(error).__name__}: {error}"


## @brief Dispatch rollouts and resolve them in submission order.
# @details Count failures against the budget. Each group receives a list of
# successful paired observations and a separate failure count.
class _Rollouts:
    def __init__(self, archive, evaluate, executor, seed, *, stream=0, seeded=False):
        self.archive = archive
        self.evaluate = evaluate
        self.executor = SequentialExecutor() if executor is None else executor
        self.seed = seed
        self.stream = stream
        self.seeded = seeded
        self.attempted = 0
        self.failed = 0

    ## @brief Return observations per candidate in request order.
    def evaluate_groups(self, groups):
        jobs = []
        for original, count in groups:
            group = []
            for _ in range(count):
                candidate = _fresh(original)
                candidate.evaluation_seed = _rollout_seed(self.seed, self.stream, self.attempted)
                self.attempted += 1
                group.append((candidate, self.executor.submit(_worker, self.evaluate, candidate, self.seeded)))
            jobs.append(group)

        output = []
        for group in jobs:
            observations = []
            for candidate, future in group:
                result, elapsed, failure = future.result()
                try:
                    if failure is not None:
                        raise ValueError(failure)
                    obs = _observe_result(self.archive, candidate, result, elapsed)
                    _valid_observation(obs, len(self.archive.fitness_domain), len(self.archive.features_domain))
                    observations.append(obs)
                except (KeyError, ValueError, TypeError) as error:
                    if self.failed == 0:
                        warnings.warn(f"First failed rollout: {error}", stacklevel=2)
                    self.failed += 1
            output.append(observations)
        return output


## @brief Request repeats until coordinate-wise standard errors meet the tolerances.
[docs] @registry.register class StandardErrorSamplingDecorator(SamplingDecorator): """Use separate absolute standard-error tolerances for fitness and descriptors. :param fitness_tolerance: Maximum objective standard error. :param descriptor_tolerance: Maximum standard error in any descriptor coordinate. :param min_samples: Minimum count needed to estimate standard error. :param max_samples: Hard cap on observations for one proposal. """ def __init__(self, base_alg, *, fitness_tolerance=0.02, descriptor_tolerance=0.01, min_samples=3, max_samples=10, **kwargs): if (not isinstance(min_samples, int) or not isinstance(max_samples, int) or not 2 <= min_samples <= max_samples): raise ValueError("Use integer sample counts with 2 <= min_samples <= max_samples.") if any(not math.isfinite(tol) or tol < 0 for tol in (fitness_tolerance, descriptor_tolerance)): raise ValueError("Standard-error tolerances must be finite and nonnegative.") self.fitness_tolerance = fitness_tolerance self.descriptor_tolerance = descriptor_tolerance self.min_samples = min_samples self.max_samples = max_samples super().__init__(base_alg, **kwargs) def _target(self, individual): return self.min_samples ## @brief Use sample standard deviation divided by the square root of sample count. def _next_target(self, individual, sample_count): if sample_count >= self.max_samples: return sample_count observations = individual._observations scale = math.sqrt(sample_count) fit_error = np.std([row.fitness for row in observations], axis=0, ddof=1) / scale bd_error = np.std([row.features for row in observations], axis=0, ddof=1) / scale return sample_count + int(np.any(fit_error > self.fitness_tolerance) or np.any(bd_error > self.descriptor_tolerance))
## @brief Coordinate scalar-objective MAP-Elites policies that reevaluate archives.
[docs] class UncertainMAPElites: """Run one published or experimental sampling and archive policy. :param container: A standalone fixed Grid or CVTGrid with one objective. :param budget: Maximum search rollouts, inclusive of reevaluations. :param sampling_size: Rollout slots available per generation. :param dimension: Genome length used by the default polynomial emitter. :param policy: Adaptive, Deep-Grid, Deep-Grid-Sampling, Archive-Sampling, Parallel-Adaptive-Sampling, Extract-ME, or fill-then-refine. :param base_alg: Optional QDpy emitter using the same archive. Its selection rule replaces the default selector for the policy. :param initial_samples: Override new-offspring repeats where applicable. :param extraction_fraction: Fraction of a generation reserved for Extract-ME. :param max_samples: Per-solution cap for the local adaptive race. :param limit_descriptor_drift: Apply the cell-visit stopping rule in adaptive races. :param seed: Seed for rollout IDs and the extraction RNG. Seed the caller's Python and NumPy RNGs separately for emitter reproduction. """ def __init__(self, container, budget, dimension, *, policy="extract_me", sampling_size=128, base_alg=None, ind_domain=(0., 1.), optimisation_task="minimisation", initial_samples=None, extraction_fraction=0.25, max_samples=100, limit_descriptor_drift=True, seed=0): if type(container) not in (Grid, CVTGrid) or container.parents or len(container.fitness_domain) != 1: raise ValueError("UncertainMAPElites requires a standalone fixed grid with a scalar objective.") if policy not in _POLICIES: raise ValueError(f"Use one of the uncertain MAP-Elites policies {_POLICIES}.") if any(not isinstance(n, int) or n < 1 for n in (budget, sampling_size, dimension, max_samples)): raise ValueError("Budget, sampling size, dimension and max_samples must be positive integers.") if initial_samples is None: initial_samples = 5 if policy == "deep_grid_sampling" else 1 if not isinstance(initial_samples, int) or not 1 <= initial_samples <= sampling_size: raise ValueError("initial_samples must fit within one generation.") if policy in ("adaptive", "fill_then_refine") and initial_samples != 1: raise ValueError("This policy starts each new candidate with one rollout.") if policy == "fill_then_refine" and sampling_size < 5: raise ValueError("Fill-then-refine requires a sampling size of at least five.") if not 0 <= extraction_fraction < 1: raise ValueError("extraction_fraction must lie in [0, 1).") if policy in ("archive_sampling", "parallel_adaptive") and sampling_size < container.capacity + initial_samples: raise ValueError("The sampling size must fit all incumbents and at least one offspring group.") deep = policy in ("deep_grid", "deep_grid_sampling") if base_alg is not None and base_alg.container is not container: raise ValueError("The base emitter must use the same grid.") if base_alg is None: base_alg = RandomSearchMutPolyBounded( container, budget, dimension, ind_domain=ind_domain, init_pb=0.1, sel_pb=0.9, mut_pb=1 / dimension, optimisation_task=optimisation_task, parent_selector=_select_deep_grid if deep else _select_elite) self.container = container self.base_alg = base_alg self.budget = budget self.sampling_size = sampling_size self.policy = policy self.initial_samples = initial_samples self.extraction_fraction = extraction_fraction self.max_samples = max_samples self.limit_descriptor_drift = limit_descriptor_drift self.seed = seed self._rng = np.random.default_rng(seed) self._refine = None self._qs = [] self.nb_evaluations = 0 self.failed_evaluations = 0 self.offspring_evaluations = 0 self.incumbent_evaluations = 0 self.completed_generations = 0 if deep: container.discard_random_on_bin_overload = True ## @brief Run the chosen policy and return the current best solution. # @param evaluate Ordinary QDpy evaluator, or evaluate(individual, seed) with seeded=True. # @param executor Optional standard QDpy evaluation executor. # @param seeded Pass a deterministic rollout seed separately to the evaluator. def optimise(self, evaluate, *, executor=None, seeded=False): if self.nb_evaluations: raise RuntimeError("Build a new UncertainMAPElites run to restart the search.") self._rollouts = _Rollouts(self.container, evaluate, executor, self.seed, seeded=seeded) try: if self.policy == "adaptive": self._run_adaptive() else: while self._rollouts.attempted < self.budget and self._generation(): self.completed_generations += 1 finally: self.nb_evaluations = self._rollouts.attempted self.failed_evaluations = self._rollouts.failed del self._rollouts return self.base_alg.best() ## @brief Choose one distinct ranked subset for Extract-ME. def _extract(self, archive, count): entries = [] weights = [] for cell in archive.solutions.values(): ranked = sorted(cell, key=lambda ind: _quality(archive, ind), reverse=True) entries.extend(ranked) weights.extend(np.exp(-np.arange(len(ranked), dtype=float))) count = min(count, len(entries)) if not count: return [] weights = np.asarray(weights) selected = self._rng.choice(len(entries), count, replace=False, p=weights / weights.sum()) return [(entries[i], 1) for i in selected] ## @brief Assign repeat groups using the generation limit and active policy. def _schedule(self, slots): archive = self.container offspring_samples = self.initial_samples repeats = [] if self.policy in ("archive_sampling", "parallel_adaptive"): repeats = [(ind, 1) for ind in archive] if self.policy == "parallel_adaptive" and len(archive): offspring_samples = max(1, int(np.median([len(_history(archive, ind)) for ind in archive]))) elif self.policy == "extract_me": repeats = self._extract(archive, int(slots * self.extraction_fraction)) elif self.policy == "fill_then_refine": if self._refine is None and archive.filled_bins * 2 >= math.prod(archive.shape): self._refine = deque(sorted(archive, key=lambda ind: len(_history(archive, ind)))) if self._refine is not None: offspring_samples = 5 capacity = slots // 4 while capacity and self._refine: elite = self._refine.popleft() target = max(0, 5 - len(_history(archive, elite))) if archive._index_of(elite) is None or not target: continue if target > capacity: self._refine.appendleft(elite) break repeats.append((elite, target)) capacity -= target return repeats, offspring_samples ## @brief Stage a complete generation with the published reevaluation order. def _generation(self): slots = min(self.sampling_size, self.budget - self._rollouts.attempted) repeats, offspring_samples = self._schedule(slots) required = sum(count for _, count in repeats) count = (slots - required) // offspring_samples if count < 1: if slots == self.sampling_size: raise ValueError("The generation budget cannot fit all reevaluations and an offspring group.") return False staged = _stage_archive(self.container) self.base_alg.container = staged try: # Archive-sampling generates parents after refilling the archive. # Extract-ME generates offspring from the pre-extraction repertoire. if self.policy == "extract_me": offspring = [self.base_alg.ask() for _ in range(count)] for incumbent, _ in repeats: staged.discard(incumbent) self.incumbent_evaluations += required offspring_rows = None if self.policy == "extract_me": measured = self._rollouts.evaluate_groups(repeats + [(ind, offspring_samples) for ind in offspring]) rows, offspring_rows = measured[:len(repeats)], measured[len(repeats):] else: rows = self._rollouts.evaluate_groups(repeats) for (old, _), measured in zip(repeats, rows, strict=True): if not measured: staged.add(old) else: revised = _aggregate(staged, _fresh(old), list(_history(self.container, old)) + measured) self._admit(staged, revised) if self.policy != "extract_me": offspring = [self.base_alg.ask() for _ in range(count)] self.offspring_evaluations += count * offspring_samples if offspring_rows is None: offspring_rows = self._rollouts.evaluate_groups([(ind, offspring_samples) for ind in offspring]) for individual, rows in zip(offspring, offspring_rows, strict=True): if len(rows) == offspring_samples: self.base_alg.tell(_aggregate(staged, individual, rows)) else: self.base_alg._forget_suggestion(individual) finally: self.base_alg.container = self.container self.container.__dict__.update(staged.__dict__) return True ## @brief Reject finite estimates outside the grid without treating them as worker errors. @staticmethod def _admit(archive, individual): if not archive.in_bounds(archive.get_ind_fitness(individual).values, archive.fitness_domain): return False if _cell(archive, individual) is None: return False return archive.add(individual) is not None ## @brief Run one local race at a time, committing completed archive updates. def _run_adaptive(self): while self._rollouts.attempted < self.budget: proposal = self.base_alg.ask() observation = self._one(proposal, incumbent=False) if not observation: self.base_alg._forget_suggestion(proposal) continue _aggregate(self.container, proposal, observation) cell = _cell(self.container, proposal) rival = _incumbent(self.container, cell) if cell is None or rival is None or ( len(_history(self.container, rival)) == 1 and _quality(self.container, proposal) > _quality(self.container, rival)): self.base_alg.tell(proposal, tell_container=cell is not None) continue staged = _stage_archive(self.container) self.base_alg.container = staged try: result = self._race(staged, proposal, observation) if result is None: self.base_alg._forget_suggestion(proposal) break self.base_alg.tell(proposal, tell_container=result) finally: self.base_alg.container = self.container self.container.__dict__.update(staged.__dict__) ## @brief Spend one remaining rollout and record the work category. def _one(self, individual, *, incumbent): if self._rollouts.attempted >= self.budget: return None if incumbent: self.incumbent_evaluations += 1 else: self.offspring_evaluations += 1 return self._rollouts.evaluate_groups([(individual, 1)])[0] ## @brief Resolve a challenger or drifting incumbent using successive local comparisons. # @return True to admit the challenger, False to reject it, or None at the budget limit. def _race(self, archive, individual, observations, *, incumbent=False): visits = Counter() while True: _aggregate(archive, individual, observations) cell = _cell(archive, individual) if cell is None: return False visits[cell] += 1 rival = _incumbent(archive, cell) if rival is None: return True history = _history(archive, rival) ahead = _quality(archive, individual) > _quality(archive, rival) if ahead and len(observations) >= min(len(history), self.max_samples): return True if not ahead: if len(history) < self.max_samples: repeat = self._one(rival, incumbent=True) if repeat is None: return None if repeat: revised_rows = list(history) + repeat revised = _aggregate(archive, _fresh(rival), revised_rows) archive.discard(rival) if _cell(archive, revised) == cell: self._admit(archive, revised) else: moved = self._race(archive, revised, revised_rows, incumbent=True) if moved is None: return None if moved: self._admit(archive, revised) rival = _incumbent(archive, cell) if rival is None: return True behind = _quality(archive, individual) <= _quality(archive, rival) settled = not self.limit_descriptor_drift or 2 * visits[cell] > sum(visits.values()) if behind and settled: return False if not behind and len(observations) >= min(len(_history(archive, rival)), self.max_samples): return True if len(observations) >= self.max_samples: return _quality(archive, individual) > _quality(archive, rival) repeat = self._one(individual, incumbent=incumbent) if repeat is None: return None if not repeat: return False observations = observations + repeat
## @brief Independent audit results and the corresponding corrected archive.
[docs] @dataclass(frozen=True) class ArchiveAudit: """Hold corrected metrics independently of search measurements and budget.""" archive: Grid corrected_qd_score: float corrected_coverage: float cell_drift: float rollout_cell_change: float rollouts: int failed_rollouts: int
def _measurement_groups(archive, evaluate, *, samples, seed, estimator, representative="best", selector=None, executor=None): """Share independent rollout measurements across archive projections.""" if not isinstance(samples, int) or samples < 1: raise ValueError("samples must be a positive integer.") if estimator not in ("mean", "median") or representative not in ("best", "selector"): raise ValueError("Use mean or median and best or selector.") runner = _Rollouts(archive, evaluate, executor, seed, stream=1, seeded=True) rng = np.random.default_rng([seed, 1]) reducer = np.mean if estimator == "mean" else np.median def measure(): for cell, entries in archive.solutions.items(): if not entries: continue best = _incumbent(archive, cell) if representative == "best": requested = [(best, samples)] else: chosen = [selector(archive, entries, rng) if selector else entries[rng.choice(len(entries), p=_selection_weights(archive, entries))] for _ in range(samples)] requested = [(ind, 1) for ind in chosen] rows = [row for group in runner.evaluate_groups(requested) for row in group] if rows: revised = _aggregate(archive, _fresh(best), rows, estimator=lambda values: reducer(values, axis=0)) yield cell, revised, rows return runner, measure() ## @brief Reevaluate one result per occupied cell using fresh, seeded rollouts. # @param archive Fixed Grid or CVTGrid to audit. # @param evaluate Callable taking an individual and the independent rollout seed. # @param samples Number of independent rollouts per occupied source cell. # @param seed Base seed for the audit stream. # @param estimator Coordinate-wise mean or median. # @param representative Best-per-cell or selector-based measurements. # @param selector Optional in-cell selector taking the archive, entries and RNG. # @param executor Optional QDpy executor. # @return ArchiveAudit with independent metrics and rollout counts.
[docs] def reevaluate_archive(archive, evaluate, *, samples=32, seed=0, estimator="median", representative="best", selector=None, executor=None): """Build a new depth-one archive without changing the input archive. The selector-based audit draws a member on each rollout. Its aggregate describes a source cell's deployment policy. The corrected coverage denominator is the number of cells in the source geometry. """ runner, measurements = _measurement_groups(archive, evaluate, samples=samples, seed=seed, estimator=estimator, representative=representative, selector=selector, executor=executor) corrected = _stage_archive(archive) corrected.clear() corrected._max_items_per_bin = 1 corrected.discard_random_on_bin_overload = False corrected._capacity = math.prod(corrected.shape) drifted = total = changed_rollouts = successful = 0 for cell, revised, rows in measurements: for row in rows: try: destination = archive.index_grid(row.features) except IndexError: destination = None changed_rollouts += destination != cell successful += len(rows) total += 1 drifted += _cell(archive, revised) != cell UncertainMAPElites._admit(corrected, revised) return ArchiveAudit(corrected, corrected.qd_score(), corrected.filled_bins / math.prod(archive.shape), drifted / total if total else 0., changed_rollouts / successful if successful else 0., runner.attempted, runner.failed)