Source code for qdpy.algorithms.multi_bd_mes

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites Success with multiple descriptor views of each evaluation.

"""Illuminate several descriptor spaces with a shared success condition."""

from collections.abc import Mapping
from dataclasses import dataclass
import warnings

import numpy as np

from .modern import _positive_int
from .task_search import _measurement, _offer, _search_bounds, _validate_grid

__all__ = ["MultiBDMESResult", "multi_bd_mes"]


## @brief Live archives and accounting for a shared sequence of evaluations.
@dataclass(frozen=True)
class MultiBDMESResult:
    """Grids, evaluator attempts and failures, successes, and admissions by view."""

    archives: dict
    attempts: int
    failures: int
    successful_evaluations: int
    admissions: dict


def _offer_success(grid, measurement):
    candidate, cell = measurement
    if cell is None:
        return
    front = grid.solutions[cell]
    if front and candidate.scores["success"] != front[0].scores["success"]:
        if not candidate.scores["success"]:
            return
        # A duplicate stored in another cell cannot replace this incumbent.
        if candidate in grid and candidate != front[0]:
            return
        grid.discard(front[0])
    _offer(grid, measurement)


## @brief Use one evaluation to update multiple success-prioritised archives.
[docs] def multi_bd_mes(archives, evaluate, *, dimension, budget, ind_domain=(0, 1), mutation_sigma=0.1, seed=0, on_step=None): """Run steady-state multi-descriptor MAP-Elites Success. Each grid has independent local competition. A success takes precedence within its cell. Fitness breaks comparisons between entries with equal success status. Select parent grids in round-robin order, falling back to a populated grid if necessary. Within each grid, sample uniformly from successful elites when available, or from all elites while searching for a first success. Mutate real-valued candidates with bounded Gaussian noise. Garrabé et al. use the multi-grid method with inferred descriptor functions. This runner accepts them as part of the supplied evaluator. :param archives: Mapping from descriptor view names to distinct, empty, parentless, best-only Grid or CVTGrid instances. :param evaluate: Callable taking an immutable genome and returning (success, (fitness,), {view: descriptors}). Success is a bool. :param dimension: Number of real variables in each genome. :param budget: Total evaluator attempts across all descriptor views. :param ind_domain: Inclusive lower and upper genome bounds. :param mutation_sigma: Gaussian standard deviation as a fraction of the bounds' span. :param seed: Private random seed for initialization, selection and mutation. :param on_step: Optional callback taking the archives and keyword arguments iteration and evaluations after each attempted evaluation. :returns: Live archives and shared evaluation accounting. """ if not isinstance(archives, Mapping) or not archives: raise ValueError("Supply a nonempty mapping of descriptor views to grids.") archives = dict(archives) if len({id(grid) for grid in archives.values()}) != len(archives): raise ValueError("Each descriptor view needs a distinct archive.") for grid in archives.values(): _validate_grid(grid) if "success" in (*grid.fitness_score_names, *grid.features_score_names): raise ValueError("The score name 'success' is reserved for success status.") if not callable(evaluate) or (on_step is not None and not callable(on_step)): raise TypeError("Supply a callable evaluator and, optionally, a callable step hook.") dimension = _positive_int(dimension, "dimension") budget = _positive_int(budget, "budget") bounds = _search_bounds(ind_domain) sigma = mutation_sigma * (bounds[1] - bounds[0]) if not 0 < sigma < np.inf: raise ValueError("Mutation must have a positive finite standard deviation.") rng = np.random.default_rng(seed) grids = tuple(archives.values()) admitted = dict.fromkeys(archives, 0) failures = successes = 0 for step in range(budget): grid = grids[step % len(grids)] if not grid: populated = [item for item in grids if item] if populated: grid = populated[rng.integers(len(populated))] if grid: parents = [elite for elite in grid if elite.scores["success"]] parents = parents or grid parent = parents[rng.integers(len(parents))] point = np.clip(np.asarray(parent) + rng.normal(0, sigma, dimension), *bounds) else: point = rng.uniform(*bounds, dimension) genome = tuple(map(float, point)) try: success, fitness, descriptors = evaluate(genome) if not isinstance(success, (bool, np.bool_)) or not isinstance(descriptors, Mapping): raise ValueError("Return a boolean success and a mapping of descriptor views.") if descriptors.keys() != archives.keys(): raise ValueError("Report descriptors for each configured view.") staged = {name: _measurement(archive, (fitness, descriptors[name]), genome) for name, archive in archives.items()} except Exception as error: warnings.warn(f"MAP-Elites Success evaluation failed: {error}", stacklevel=2) failures += 1 else: successes += int(success) for name, archive in archives.items(): measurement = staged[name] measurement[0].scores["success"] = bool(success) previous = archive.nb_added _offer_success(archive, measurement) admitted[name] += archive.nb_added - previous if on_step is not None: on_step(archives, iteration=step + 1, evaluations=step + 1) return MultiBDMESResult(archives, budget, failures, successes, admitted)