Source code for qdpy.algorithms.omg_mega

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Objective and Measure Gradient MAP-Elites using per-elite Jacobians.
# @see https://arxiv.org/abs/2106.03894

"""Use the gradients of retained elites to illuminate a fixed descriptor grid."""

from math import isfinite
import warnings

import numpy as np

from qdpy.base import registry
from .constrained import _validate_grid
from .differentiable import GradientEvaluation, _gradient_basis
from .modern import _FixedGeneration, _bounds, _positive_int

__all__ = ["OMGMEGA"]

_BASIS_SCORE = "omg_mega_gradient_basis"


## @brief Vary an archived elite along normalized objective and descriptor gradients.
[docs] @registry.register class OMGMEGA(_FixedGeneration): """Draw Gaussian coefficients and use the absolute coefficient for fitness. One combined evaluator call yields a GradientEvaluation for each candidate. Its normalized Jacobian is stored with the candidate if admitted, so future offspring reuse the measured basis. Descriptor coefficients remain signed. The fitness row follows the configured optimization direction. :param container: Empty parentless best-only Grid or CVTGrid with one objective. :param budget: Combined fitness, descriptor, and Jacobian calls. :param dimension: Number of decision variables. :param sigma: Standard deviation of the sampled coefficients. :param batch_size: Number of candidates proposed before a generation commits. :param ind_domain: Shared decision bounds for sampling and clipping. :param seed: Private seed for initialization, selection, and gradient coefficients. :param kwargs: Native QDAlgorithm settings. """ _requires_proposed_genome = True def __init__(self, container, budget, dimension, *, sigma=.1, batch_size=1, ind_domain=(0., 1.), seed=0, **kwargs): _validate_grid(container) if container.parents or container.fitness_score_names or container.features_score_names: raise ValueError("Use a parentless archive with native fitness and descriptors.") self.ind_domain = _bounds(ind_domain) if not isfinite(self.ind_domain[1] - self.ind_domain[0]) or not 0. < sigma < np.inf: raise ValueError("Use finite decision spans and a positive finite sigma.") self.sigma, self.seed = sigma, seed if container.fitness_weights is not None: kwargs.setdefault("optimisation_task", tuple(container.fitness_weights)) super().__init__(container, _positive_int(budget, "budget"), dimension=_positive_int(dimension, "dimension"), batch_size=_positive_int(batch_size, "batch_size"), **kwargs) if not self._fitness_weights[0]: raise ValueError("A nonzero scalar fitness weight is required.") def reinit(self): """Reset the proposal stream while retaining measured elite bases.""" super().reinit() self._rng = np.random.default_rng(self.seed) @property def gradient_evaluations(self): """Return combined evaluation attempts, including failed gradient calls.""" return self.nb_evaluations def _internal_ask(self, base_ind): if self.container: parent = self.container[self._rng.integers(len(self.container))] basis = np.asarray(parent.scores[_BASIS_SCORE]) coefficients = self._rng.normal(0., self.sigma, len(basis)) coefficients[0] = abs(coefficients[0]) base_ind[:] = np.clip(np.asarray(parent) + coefficients @ basis, *self.ind_domain) else: base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension) return base_ind def _payload(self, result): if not isinstance(result, GradientEvaluation): raise TypeError("The evaluator must return a GradientEvaluation.") fitness = float(result.fitness) descriptors = np.asarray(result.descriptors, dtype=float) jacobian = np.asarray(result.jacobian, dtype=float) width = len(self.container.features_domain) if (descriptors.shape != (width,) or jacobian.shape != (width + 1, self.dimension) or not isfinite(fitness) or not np.isfinite(descriptors).all() or not np.isfinite(jacobian).all()): raise ValueError("Supply finite fitness, descriptors, and a Jacobian matching the archive and genome.") basis = _gradient_basis(jacobian, self._fitness_weights[0]) return (fitness,), descriptors, {_BASIS_SCORE: tuple(tuple(row) for row in basis)} def _check_candidate(self, individual): super()._check_candidate(individual) self.container.index_grid(individual) def _receive_fixed_batch(self, records, verbose, batch_start_time): staged = [] for individual, result, elapsed in records: if result is not None: try: result = self._payload(result) except (TypeError, ValueError, OverflowError) as error: warnings.warn(f"Invalid gradient evaluation: {error}", stacklevel=2) result = None staged.append((individual, result, elapsed)) super()._receive_fixed_batch(staged, verbose, batch_start_time)