Source code for qdpy.algorithms.descriptor_mutation

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Replace one named descriptor axis during MAP-Elites.
# @see https://pubs.cs.uct.ac.za/id/eprint/1823/

"""In-run descriptor replacement with measured archive transfer."""

from collections.abc import Mapping
from dataclasses import dataclass
from math import isfinite
from numbers import Real
from operator import index

import numpy as np

from qdpy.containers import Grid
from qdpy.tools import iso_line_dd
from .modern import _positive_int, _variation_settings
from .task_search import _measurement, _offer, _search_bounds

__all__ = ["DescriptorAxis", "DescriptorMutationMAPElites", "DescriptorMutationStats", "DescriptorSwitch"]


## @brief Describe one named measurement and its grid discretization.
[docs] @dataclass(frozen=True) class DescriptorAxis: """Use the same name in the evaluator's measurement mapping.""" name: str bounds: tuple[float, float] bins: int def __post_init__(self): low, high = map(float, self.bounds) if not isinstance(self.name, str) or not self.name or not (low < high and isfinite(high - low)): raise ValueError("Use a nonempty axis name and a finite, increasing interval.") object.__setattr__(self, "bounds", (low, high)) object.__setattr__(self, "bins", _positive_int(self.bins, "bins"))
## @brief Report offspring, extra measurement calls, and successful axis switches.
[docs] @dataclass(frozen=True) class DescriptorMutationStats: """Evaluation counts include attempted callback calls.""" evaluations: int refresh_evaluations: int switches: int
## @brief Summarize the committed rebuild onto the new descriptor geometry.
[docs] @dataclass(frozen=True) class DescriptorSwitch: """Report source, projected, and transferred elite counts for one switch.""" previous: DescriptorAxis replacement: DescriptorAxis source_elites: int projected_elites: int transferred_elites: int refresh_evaluations: int
## @brief Run MAP-Elites with explicit, transactional descriptor swaps.
[docs] class DescriptorMutationMAPElites: """Search with interpretable descriptors and reuse historical elite measurements. Evaluators receive a real-valued genome and private integer seed. Return scalar fitness and a mapping of named finite measurements. Include all active axes and optionally any measurements for future swaps. The search owns its Grid and replaces it after a successful rebuild. Retaining a reference to the old Grid gives a snapshot. :param axes: Nonempty sequence of distinct DescriptorAxis objects. :param dimension: Number of real genome coordinates. :param fitness_domain: Inclusive scalar reporting fitness bounds. :param maximize: True to prefer higher fitness. :param ind_domain: Shared finite interval for all genome coordinates. :param iso_sigma: Independent mutation standard deviation. :param line_sigma: Shared directional mutation standard deviation. :param seed: Seed for proposals, evaluations, and separate refreshes. """ def __init__(self, axes, dimension, *, fitness_domain, maximize=True, ind_domain=(0., 1.), iso_sigma=.05, line_sigma=.2, seed=0): self._axes = self._checked_axes(axes) self._dimension = _positive_int(dimension, "dimension") self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma)) self._iso, self._line = iso_sigma, line_sigma low, high = map(float, fitness_domain) if not low < high: raise ValueError("Use an increasing fitness interval.") self._fitness_domain = ((low, high),) self._weights = (1.,) if maximize else (-1.,) self._archive = self._grid(self._axes) self._variation, self._measurement, self._refresh = map( np.random.default_rng, np.random.SeedSequence(seed).spawn(3)) self._evaluations = self._refresh_evaluations = self._switches = 0 @staticmethod def _checked_axes(axes): axes = tuple(axes) if (not axes or any(not isinstance(axis, DescriptorAxis) for axis in axes) or len({axis.name for axis in axes}) != len(axes)): raise ValueError("Supply distinct named DescriptorAxis objects.") return axes def _grid(self, axes): return Grid(shape=tuple(axis.bins for axis in axes), features_domain=tuple(axis.bounds for axis in axes), fitness_domain=self._fitness_domain, fitness_weights=self._weights, storage_type="orderedset") @property def archive(self): """Return the active native grid.""" return self._archive @property def axes(self): """Return the active named axes in grid order.""" return self._axes @property def stats(self): """Snapshot cumulative evaluation and switch counts.""" return DescriptorMutationStats(self._evaluations, self._refresh_evaluations, self._switches) @staticmethod def _put(archive, axes, genome, fitness, scores): if (not isinstance(scores, Mapping) or any(not isinstance(name, str) or not isinstance(value, Real) or not isfinite(value) for name, value in scores.items())): raise ValueError("Return a mapping from names to finite measurements.") missing = [axis.name for axis in axes if axis.name not in scores] if missing: raise ValueError(f"Missing active descriptor measurements: {', '.join(missing)}.") measurement = _measurement(archive, ((fitness,), tuple(scores[axis.name] for axis in axes)), genome) measurement[0].scores.update({name: float(value) for name, value in scores.items()}) _offer(archive, measurement) @staticmethod def _seed(rng): return int(rng.integers(2**32)) ## @brief Run additional proposals with the current set of descriptor axes.
[docs] def run(self, evaluate, budget): """Return cumulative statistics. Evaluator errors propagate to the caller.""" if not callable(evaluate): raise TypeError("Provide a callable evaluator.") budget = _positive_int(budget, "budget") rng, archive = self._variation, self._archive for _ in range(budget): if len(archive): first, second = rng.integers(len(archive), size=2) genome = iso_line_dd(archive[first], archive[second], bounds=self._bounds, iso_sigma=self._iso, line_sigma=self._line, rng=rng) else: genome = rng.uniform(*self._bounds, size=self._dimension) genome = tuple(map(float, genome)) self._evaluations += 1 fitness, scores = evaluate(genome, self._seed(self._measurement)) self._put(archive, self._axes, genome, fitness, scores) return self.stats
## @brief Build a separate reporting grid from cached elite measurements.
[docs] def report(self, axes): """Project current elites onto supplied axes without new evaluator calls.""" axes = self._checked_axes(axes) report = self._grid(axes) for elite in self._archive: self._put(report, axes, elite, elite.fitness.values[0], elite.scores) return report
## @brief Collapse onto unaffected axes and transfer the surviving elites.
[docs] def switch_axis(self, name, replacement, *, refresh=None, refresh_budget=0): """Replace an axis and rebuild the active grid as one operation. Keep the best elite in each cell of the unaffected projection. With one axis, keep the single best elite. Reuse cached values for the replacement axis. If a survivor lacks that measurement, refresh(genome, seed) must return its new scalar descriptor. The refresh budget must cover all missing values before any call is made. On failure the original grid remains active and attempted refreshes are still counted. """ if not isinstance(replacement, DescriptorAxis): raise TypeError("replacement must be a DescriptorAxis.") names = [axis.name for axis in self._axes] if name not in names: raise ValueError("The requested descriptor axis is not active.") slot = names.index(name) previous = self._axes[slot] axes = self._checked_axes((*self._axes[:slot], replacement, *self._axes[slot + 1:])) if previous == replacement: raise ValueError("The replacement must change the active axis.") budget = index(refresh_budget) if budget < 0 or (refresh is not None and not callable(refresh)): raise ValueError("Use a nonnegative refresh budget and a callable refresh.") other_axes = tuple(axis for i, axis in enumerate(self._axes) if i != slot) source = self._archive survivors = self.report(other_axes) if other_axes else ((source.best,) if source else ()) missing = sum(replacement.name not in elite.scores for elite in survivors) if missing and (refresh is None or missing > budget): raise ValueError(f"The rebuild needs {missing} refresh evaluations.") destination = self._grid(axes) before = self._refresh_evaluations for elite in survivors: scores = dict(elite.scores) if replacement.name not in scores: self._refresh_evaluations += 1 scores[replacement.name] = refresh(tuple(elite), self._seed(self._refresh)) self._put(destination, axes, elite, elite.fitness.values[0], scores) self._archive, self._axes = destination, axes self._switches += 1 return DescriptorSwitch(previous, replacement, len(source), len(survivors), len(destination), self._refresh_evaluations - before)