# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with Passive Genetic Diversity and one auxiliary breeder per cell.
# @see https://doi.org/10.3389/frobt.2016.00040
"""Allow otherwise rejected offspring to become parents without replacing elites."""
import numpy as np
from qdpy.base import registry
from .constrained import _validate_grid
from .modern import _FixedGeneration, _bounds, _positive_int
__all__ = ["MEPGD"]
## @brief Keep a second breeding slot with stochastic admission in each occupied niche.
[docs]
@registry.register
class MEPGD(_FixedGeneration):
"""Retain one reporting elite and at most one auxiliary breeder per cell.
A strict fitness improvement replaces the reporting elite. An
otherwise eligible candidate may overwrite the auxiliary slot
even when its fitness is lower. Parent selection samples an occupied
cell uniformly and chooses between its two live occupants when both
exist. All data in the reporting grid comes from elite competition.
:param container: Empty parentless best-only Grid or CVTGrid with one objective.
:param budget: Candidate evaluation attempts.
:param dimension: Number of real-valued genome coordinates.
:param replacement_probability: Chance a non-improving candidate occupies the second slot.
:param sigma: Scale of default bounded Gaussian mutation.
:param mutate: Optional callback taking (parent_genome, rng).
:param ind_domain: Common bounds for all genome coordinates.
:param batch_size: Number of simultaneous proposals.
:param seed: Private seed for parent selection, mutation, and second-slot admission.
:param kwargs: Native QDAlgorithm settings.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, *, replacement_probability=.3,
sigma=.1, mutate=None, ind_domain=(0., 1.), batch_size=1, seed=0, **kwargs):
_validate_grid(container)
if container.parents:
raise ValueError("MEPGD needs a parentless reporting archive.")
if not 0. <= replacement_probability <= 1. or not 0. <= sigma < np.inf:
raise ValueError("Use probabilities in [0, 1] and finite nonnegative sigma.")
if mutate is not None and not callable(mutate):
raise TypeError("mutate must be callable.")
self.ind_domain = _bounds(ind_domain)
if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
raise ValueError("Use finite decision spans.")
self.replacement_probability = replacement_probability
self.sigma, self.mutate, self.seed = sigma, mutate, 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 auxiliary slots, admission counters, and random state."""
super().reinit()
self._breeders = {}
self._rng = np.random.default_rng(self.seed)
self._auxiliary_admissions = 0
@property
def breeding_slots(self):
"""Return the second-slot occupants indexed by reporting cell."""
return dict(self._breeders)
@property
def auxiliary_admissions(self):
"""Return the cumulative number of second-slot updates."""
return self._auxiliary_admissions
def _internal_ask(self, base_ind):
if not self.container:
base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
return base_ind
parent = self.container[self._rng.integers(len(self.container))]
backup = self._breeders.get(self.container.index_grid(parent))
if backup is not None and self._rng.integers(2):
parent = backup
if self.mutate is None:
genome = np.clip(np.asarray(parent, dtype=float) + self._rng.normal(0., self.sigma, self.dimension),
*self.ind_domain)
else:
genome = np.asarray(self.mutate(tuple(parent), self._rng), dtype=float)
lower, upper = self.ind_domain
if genome.shape != (self.dimension,) or not np.all((genome >= lower) & (genome <= upper)):
raise ValueError("Mutation must return a bounded real genome of the configured length.")
base_ind[:] = genome
return base_ind
def _check_candidate(self, individual):
super()._check_candidate(individual)
self.container.index_grid(individual)
def _commit_generation(self, evaluated):
admitted = set()
for slot, candidate in enumerate(evaluated):
if candidate is None:
continue
cell = self.container.index_grid(candidate)
front = self.container.solutions[cell]
if self._offer_to_grid(candidate, cell):
admitted.add(slot)
if candidate == self._breeders.get(cell):
del self._breeders[cell]
elif (front and candidate != front[0] and candidate != self._breeders.get(cell)
and self.replacement_probability and self._rng.random() < self.replacement_probability):
self._breeders[cell] = candidate
self._auxiliary_admissions += 1
return admitted