# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with sampling from the most recently admitted elites.
# @see https://doi.org/10.1145/3449726.3459493
"""Limit MAP-Elites parent sampling to a window of live archive admissions."""
from random import randrange
import numpy as np
from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .modern import _FixedGeneration, _bounds, _positive_int
__all__ = ["YouthMAPElites", "select_youth"]
## @brief Draw one parent from the newest surviving entries of a native archive.
[docs]
def select_youth(archive, count, *, rng=None):
"""Return a live recent elite from a nonempty insertion-ordered archive.
A NumPy Generator can supply the draw. The default uses Python's
random stream, as do the native polynomial mutation operators.
"""
count = _positive_int(count, "count")
size = len(archive)
if not size:
raise ValueError("Cannot select a parent from an empty archive.")
first = max(0, size - count)
return archive[randrange(first, size) if rng is None else rng.integers(first, size)]
## @brief Use the youngest retained elites as a parent population.
[docs]
@registry.register
class YouthMAPElites(_FixedGeneration):
"""Draw uniformly from the last parent_window current archive admissions.
Successful insertions and replacements appear at the end of the native
Grid or CVTGrid storage. Rejected offspring leave that order unchanged.
The list therefore reflects the youngest retained parents, including
when starting from a prefilled archive. Each generation commits
feedback in proposal order. Manual evaluations use ask_batch() and
tell_batch().
:param container: Best-only regular Grid or CVTGrid.
:param budget: Candidate evaluation attempts.
:param dimension: Number of real genome coordinates.
:param parent_window: Maximum number of recent elites eligible for sampling.
:param ind_domain: Common lower and upper bounds for each coordinate.
:param sigma: Standard deviation of default Gaussian mutation.
:param mutate: Optional callable taking (parent_tuple, rng) and returning a genome.
:param seed: Private seed.
:param kwargs: Native algorithm settings such as batch_size.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, *, parent_window=16, ind_domain=(0., 1.),
sigma=.1, mutate=None, seed=0, **kwargs):
if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
or container.discard_random_on_bin_overload):
raise ValueError("YouthMAPElites requires a best-only Grid or CVTGrid.")
if not 0 <= sigma < np.inf or (mutate is not None and not callable(mutate)):
raise ValueError("Use a finite nonnegative sigma and an optional mutation callback.")
self.ind_domain = _bounds(ind_domain)
if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
raise ValueError("Use decision bounds with a finite span.")
self.parent_window = _positive_int(parent_window, "parent_window")
self.sigma, self.mutate, self.seed = sigma, mutate, seed
dimension = _positive_int(dimension, "dimension")
lo, hi = self.ind_domain
for item in container:
genome = np.asarray(item, dtype=float)
if genome.shape != (dimension,) or not np.all((genome >= lo) & (genome <= hi)):
raise ValueError("Existing elites must be bounded real genomes of the configured length.")
if container.fitness_weights is not None:
kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
super().__init__(container, _positive_int(budget, "budget"), dimension=dimension, **kwargs)
[docs]
def reinit(self):
"""Reset the proposal stream and recover admission order from the current archive."""
super().reinit()
self._rng = np.random.default_rng(self.seed)
def _internal_ask(self, base_ind):
size = len(self.container)
if not size:
base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension)
return base_ind
parent = tuple(select_youth(self.container, self.parent_window, rng=self._rng))
if self.mutate is None:
genome = np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension)
genome = np.clip(genome, *self.ind_domain)
else:
genome = np.asarray(self.mutate(parent, self._rng), dtype=float)
lo, hi = self.ind_domain
if genome.shape != (self.dimension,) or not np.all((genome >= lo) & (genome <= hi)):
raise ValueError("Mutation must return a finite bounded genome of the configured length.")
base_ind[:] = genome
return base_ind