Source code for qdpy.algorithms.dynamic_mutation

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Gaussian MAP-Elites with feedback from coverage, time, or inherited mutation strength.
# @see https://doi.org/10.1162/isal_a_00110

"""Run Nordmoen's dynamic mutation schedules on a native archive."""

from math import prod, sqrt

import numpy as np

from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .base import QDAlgorithm
from .modern import _bounds, _positive_int

__all__ = ["DynamicMutationMAPElites"]
_SIGMA = "dynamic_mutation_sigma"


## @brief Illuminate a fixed descriptor partition with an adaptive Gaussian operator.
[docs] @registry.register class DynamicMutationMAPElites(QDAlgorithm): """Use fixed, coverage-based, annealed, or log-normal inherited mutation. Scales are in unit-genome coordinates, multiplied by the domain span and divided by the square root of the active dimension minus one (one for a single coordinate). Both global schedules use committed feedback when generating a proposal. Inherited scales travel with survivors and remain independent of the genome itself. :param container: Native one-elite Grid or CVTGrid. :param budget: Nominal number of evaluations, also the annealing horizon. :param dimension: Number of real-valued genome variables. :param mode: "fixed", "coverage", "anneal", or "self_adaptive". :param ind_domain: Common finite coordinate bounds. :param sigma_start: Initial Gaussian strength, or the fixed strength. :param sigma_stop: Final Gaussian strength, or the inherited scale floor. :param coverage_target: Occupied fraction of the grid at which coverage annealing ends. :param adaptation_rate: Log-normal learning rate, defaulting to one over the square root of the dimension. :param seed: Private initialization and mutation seed. :param batch_size: Maximum proposals before feedback. The default updates after each evaluation. :param kwargs: Native QDAlgorithm configuration, including the optimization direction. """ def __init__(self, container, budget, dimension, *, mode="coverage", ind_domain=(0., 1.), sigma_start=.2, sigma_stop=.025, coverage_target=1., adaptation_rate=None, seed=0, batch_size=1, **kwargs): if type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1: raise ValueError("Use a one-elite Grid or CVTGrid.") if mode not in ("fixed", "coverage", "anneal", "self_adaptive"): raise ValueError("Choose fixed, coverage, anneal, or self_adaptive.") if not (0 < sigma_stop <= sigma_start < np.inf and 0 < coverage_target <= 1.): raise ValueError("Use positive finite scales and a coverage target in (0, 1].") dimension, budget = _positive_int(dimension, "dimension"), _positive_int(budget, "budget") self._tau = 1. / sqrt(dimension) if adaptation_rate is None else adaptation_rate if not 0 < self._tau < np.inf: raise ValueError("adaptation_rate must be finite and positive.") if _SIGMA in (*container.fitness_score_names, *container.features_score_names): raise ValueError(f"{_SIGMA} is reserved for the mutation scale.") self.ind_domain = _bounds(ind_domain) self._scale = (self.ind_domain[1] - self.ind_domain[0]) / sqrt(max(1, dimension - 1)) if not (0 < self._scale * sigma_stop and self._scale * sigma_start < np.inf): raise ValueError("The scaled mutation strength must be finite and positive.") self.mode, self.sigma_start, self.sigma_stop = mode, sigma_start, sigma_stop self.coverage_target, self._cells, self._seed = coverage_target, prod(container.shape), seed super().__init__(container, budget, dimension=dimension, batch_size=_positive_int(batch_size, "batch_size"), **kwargs) def reinit(self): """Reset progress and variation state while keeping the native archive.""" super().reinit() self._rng = np.random.default_rng(self._seed) @property def scheduled_sigma(self): """Return the current global mutation scale before domain scaling.""" if self.mode == "coverage": progress = self.container.filled_bins / self._cells / self.coverage_target elif self.mode == "anneal": progress = self.nb_evaluations / self.budget else: return self.sigma_start progress = min(1., progress) return self.sigma_start * (1. - progress) + self.sigma_stop * progress def _internal_ask(self, base_ind): sigma = self.scheduled_sigma if not self.container: base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension) else: parent = self.container[int(self._rng.integers(len(self.container)))] if self.mode == "self_adaptive": previous = parent.scores.get(_SIGMA, self.sigma_start) if not 0 < previous < np.inf: raise ValueError("The inherited mutation strength must be finite and positive.") log_sigma = np.log(previous) + self._rng.normal(0., self._tau) # Keep the standard deviation representable in physical coordinates. upper = np.log(np.finfo(float).max) - max(0., np.log(self._scale)) - 2. sigma = float(np.exp(np.clip(log_sigma, np.log(self.sigma_stop), upper))) base_ind[:] = np.clip(np.asarray(parent) + self._rng.normal(0., sigma * self._scale, self.dimension), *self.ind_domain) if self._lineage_recorder is not None: self._lineage_recorder._parentage("dynamic_gaussian_mutation", (parent,)) base_ind.scores[_SIGMA] = sigma return base_ind def _apply_evaluation(self, ind, fitness, features, scores, elapsed): sigma = ind.scores.get(_SIGMA) if scores is not None and sigma is not None: scores = dict(scores) super()._apply_evaluation(ind, fitness, features, scores, elapsed) if sigma is not None: ind.scores[_SIGMA] = sigma