# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Non-surrounded-dominated sorting for native MAP-Elites.
"""Rank archive parents by surrounded dominance in descriptor space."""
from itertools import product
import numpy as np
from qdpy.base import registry
from qdpy.containers import CVTGrid, Grid
from .modern import _FixedGeneration, _bounds, _positive_int
__all__ = ["nss_fronts", "NSSMAPElites"]
## @brief Return zero-based front ranks, with zero for the first front.
[docs]
def nss_fronts(qualities, descriptors):
"""Rank finite scalar qualities (larger is better) and descriptor rows.
A candidate is surrounded if, for every sign direction, some
strictly fitter candidate weakly improves every signed coordinate
and strictly improves at least one. Remove each front before
determining the next. The returned ranks follow input order.
Exact direction enumeration is intended for low-dimensional descriptors.
"""
scores = np.asarray(qualities, dtype=float)
features = np.asarray(descriptors, dtype=float)
if (features.ndim != 2 or not features.shape[1] or scores.shape != (len(features),)
or not np.isfinite(features).all() or not np.isfinite(scores).all()):
raise ValueError("Supply finite scalar qualities and a matching descriptor matrix.")
ranks = np.zeros(len(features), dtype=np.intp)
order = np.argsort(-scores, kind="stable")
for position, i in enumerate(order):
higher = order[:position]
higher = higher[(scores[higher] > scores[i]) & np.any(features[higher] != features[i], axis=1)]
if not len(higher):
continue
points = features[higher]
active = np.any(points != features[i], axis=0)
le, ge = points[:, active] <= features[i, active], points[:, active] >= features[i, active]
# The last surviving rank in each direction determines when that
# direction first becomes empty during front peeling.
earliest_empty = int(ranks[higher].max()) + 1
for signs in product((False, True), repeat=int(active.sum())):
covers = np.all(np.where(signs, ge, le), axis=1)
if not covers.any():
earliest_empty = 0
break
earliest_empty = min(earliest_empty, int(ranks[higher[covers]].max()) + 1)
ranks[i] = earliest_empty
return ranks
## @brief MAP-Elites with non-surrounded-dominated parent selection.
[docs]
@registry.register
class NSSMAPElites(_FixedGeneration):
"""Run NSS-ME on a one-elite Grid or CVTGrid with one fitness objective.
Parents come from the highest-ranking fronts of the measured archive.
A partial boundary front is sampled uniformly without replacement.
If the archive has fewer members than the generation size, select
every member and fill the remaining slots from the first front.
Offspring use clipped Gaussian mutation and native grid admission.
Use ask_batch and tell_batch for manual evaluation.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, *, batch_size=16, ind_domain=(0., 1.),
sigma=.1, seed=None, **kwargs):
if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
or len(container.fitness_domain) != 1):
raise ValueError("NSSMAPElites needs a scalar, one-elite Grid or CVTGrid.")
if not 0 <= sigma < np.inf:
raise ValueError("sigma must be finite and nonnegative.")
self.ind_domain = _bounds(ind_domain)
self.sigma = float(sigma)
self._rng = np.random.default_rng(seed)
self._parents = ()
super().__init__(container, _positive_int(budget, "budget"),
dimension=_positive_int(dimension, "dimension"),
batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
archive = self.container
if not len(archive):
self._parents = ()
return
self._check_archive_weights()
direction = np.sign(self._fitness_weights[0])
ranks = nss_fronts([direction * archive.get_ind_fitness(ind).values[0] for ind in archive],
[tuple(archive.get_ind_features(ind)) for ind in archive])
parents = []
for rank in range(int(ranks.max()) + 1):
front = np.flatnonzero(ranks == rank)
remaining = size - len(parents)
parents.extend(self._rng.choice(front, size=min(remaining, len(front)), replace=False))
if len(parents) == size:
break
if len(parents) < size:
parents.extend(self._rng.choice(np.flatnonzero(ranks == 0), size=size - len(parents)))
self._parents = tuple(tuple(archive[i]) for i in parents)
def _internal_ask(self, base_ind):
if self._parents:
parent = self._parents[len(self._issued)]
base_ind[:] = np.clip(np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension),
*self.ind_domain)
else:
base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
return base_ind
def _commit_generation(self, evaluated):
return {i for i, individual in enumerate(evaluated)
if individual is not None and self._offer_to_grid(individual, self.container.index_grid(individual))}