# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with novelty and surprise in a separate descriptor space.
# @see https://doi.org/10.1145/3319619.3321987
"""Use one behavioral descriptor for selection and another for grid admission."""
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from threadpoolctl import threadpool_limits
from qdpy.base import registry
from qdpy.containers import Grid
from qdpy.tools import iso_line_dd
from ._population import _finite_vector, _tournament
from .modern import _FixedGeneration, _positive_int, _variation_settings
from .surprise import _order
__all__ = ["MultiDescriptorMAPElites"]
def _nearest_means(distances, count):
return np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
## @brief Use novelty, surprise, or both to select parents among native archive elites.
[docs]
@registry.register
class MultiDescriptorMAPElites(_FixedGeneration):
"""Independently measure selection and archive descriptors.
The third item of the evaluator result is a score mapping. Store
the numeric selection vector under ``selection_score``. The archive
uses the ordinary feature vector and scalar fitness. All parents in
a batch come from the same measured archive snapshot.
:param container: Parentless best-only Grid or CVTGrid.
:param budget: Managed evaluation attempts.
:param dimension: Length of each real vector.
:param selection_size: Number of coordinates in the selection vector.
:param selection_score: Name of the vector in candidate scores.
:param mode: ``uniform``, ``novelty``, ``surprise``, ``blend``, or ``pareto``.
:param neighbors: Number of closest other elites for novelty.
:param clusters: Maximum number of cluster centers for forecasting surprise.
:param surprise_neighbors: Forecast centers averaged in the surprise score.
:param novelty_weight: Weight of novelty in the blended score.
:param ind_domain: Common interval for all genome coordinates.
:param iso_sigma: Independent Gaussian variation per coordinate.
:param line_sigma: Gaussian variation along the difference of two parents.
:param seed: Private seed for selection, variation, and forecasting.
:param batch_size: Evaluations per archive snapshot.
:param kwargs: Native optimiser options such as the objective direction.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, *, selection_size, selection_score="selection",
mode="novelty", neighbors=15, clusters=12, surprise_neighbors=2, novelty_weight=.6,
ind_domain=(0., 1.), iso_sigma=.05, line_sigma=.2, seed=0, batch_size=16, **kwargs):
if (not isinstance(container, Grid) or container.parents or container.max_items_per_bin != 1
or container.discard_random_on_bin_overload or len(container.fitness_weights or ()) != 1
or not np.isfinite(container.fitness_weights[0]) or not container.fitness_weights[0]):
raise ValueError("Supply a parentless best-only grid with one signed objective.")
if mode not in ("uniform", "novelty", "surprise", "blend", "pareto"):
raise ValueError("Choose uniform, novelty, surprise, blend, or pareto selection.")
if not isinstance(selection_score, str) or not selection_score or not 0. <= novelty_weight <= 1.:
raise ValueError("Supply a score name and a novelty weight in [0, 1].")
self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
self._width = _positive_int(selection_size, "selection_size")
self._score, self.mode, self._weight = selection_score, mode, novelty_weight
self._neighbors = _positive_int(neighbors, "neighbors")
self._clusters = _positive_int(clusters, "clusters")
self._surprise_neighbors = _positive_int(surprise_neighbors, "surprise_neighbors")
self._iso, self._line, self.seed = iso_sigma, line_sigma, seed
dimension = _positive_int(dimension, "dimension")
for row in container:
self._descriptor(row)
if len(row) != dimension or not all(self.ind_domain[0] <= x <= self.ind_domain[1] for x in row):
raise ValueError("Warm-start genomes must match dimension and bounds.")
kwargs.setdefault("optimisation_task", container.fitness_weights)
super().__init__(container, _positive_int(budget, "budget"), dimension=dimension,
batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
[docs]
def reinit(self):
"""Reset forecasting and private random streams."""
super().reinit()
self._rng, self._model_rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(2))
self._previous_centers = None
self._breeders = ()
self._probabilities = self._keys = None
self._forecasts = 0
@property
def forecasts(self):
"""Return the number of forecasts with two observed archive snapshots."""
return self._forecasts
def _descriptor(self, row):
if self._score not in row.scores:
raise ValueError(f"Missing selection descriptor {self._score!r}.")
return _finite_vector(row.scores[self._score], "Selection descriptor", self._width)
def _check_candidate(self, individual):
super()._check_candidate(individual)
self._descriptor(individual)
def _selection_scores(self, points):
# A common scaling of the two distance scores preserves rankings and
# roulette weights. Work in scaled coordinates before extrapolating.
previous = self._previous_centers
scale = max(1., float(np.max(np.abs(points))),
0. if previous is None else float(np.max(np.abs(previous))))
scaled = points / scale
novelty = np.zeros(len(points))
surprise = np.zeros(len(points))
if len(points) > 1 and self.mode in ("novelty", "blend", "pareto"):
distances = cdist(scaled, scaled)
np.fill_diagonal(distances, np.inf)
novelty = _nearest_means(distances, min(len(points) - 1, self._neighbors))
if self.mode in ("surprise", "blend", "pareto"):
centers = np.unique(scaled, axis=0)
if len(centers) > self._clusters:
with threadpool_limits(limits=1):
centers = KMeans(self._clusters, n_init=1, random_state=int(
self._model_rng.integers(2**31))).fit(scaled).cluster_centers_
if previous is not None:
old = previous / scale
predicted = 2. * centers - old[cdist(centers, old).argmin(axis=1)]
surprise = _nearest_means(cdist(scaled, predicted), min(self._surprise_neighbors, len(centers)))
self._forecasts += 1
self._previous_centers = np.clip(centers, scaled.min(axis=0), scaled.max(axis=0)) * scale
return novelty, surprise
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
self._breeders = tuple(self.container)
if not self._breeders or self.mode == "uniform":
return
novelty, surprise = self._selection_scores(np.asarray([self._descriptor(row) for row in self._breeders]))
if self.mode == "pareto":
rank, crowding = _order(np.column_stack((novelty, surprise)))
self._keys = tuple(zip(rank, -crowding))
return
if self.mode == "novelty":
weights = novelty
elif self.mode == "surprise":
weights = surprise
else:
weights = self._weight * novelty + (1. - self._weight) * surprise
self._probabilities = weights / weights.sum() if weights.any() else None
def _clear_generation(self):
super()._clear_generation()
self._breeders = ()
self._probabilities = self._keys = None
def _parent(self):
if self._keys is not None:
return _tournament(self._breeders, self._keys, self._rng)
return self._breeders[self._rng.choice(len(self._breeders), p=self._probabilities)]
def _internal_ask(self, base_ind):
if not self._breeders:
base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension).tolist()
return base_ind
first, second = self._parent(), self._parent()
if self._lineage_recorder is not None:
self._lineage_recorder._parentage("iso_line_dd", (first, second))
base_ind[:] = iso_line_dd(first, second, bounds=self.ind_domain, iso_sigma=self._iso,
line_sigma=self._line, rng=self._rng)
return base_ind