Source code for qdpy.algorithms.multi_descriptor_nslc

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Multi-descriptor novelty search and local competition (NS–NSLC).
# @see https://doi.org/10.3389/frobt.2016.00040

"""Breed one population using two novelty views and local fitness competition."""

from math import isfinite

import numpy as np
from scipy.spatial.distance import cdist

from qdpy.base import registry
from qdpy.containers import Container
from qdpy.containers.pareto import _crowding_distance
from .modern import _FixedGeneration, _bounds, _positive_int

__all__ = ["MultiDescriptorNSLC"]


def _pareto_survivors(scores, capacity, rng):
    """Order the required survivor fronts by rank and crowding."""
    first, second = scores[:, None], scores[None, :]
    dominates = np.all(first >= second, axis=2) & np.any(first > second, axis=2)
    remaining = np.sum(dominates, axis=0)
    ordered = []
    while len(ordered) < capacity:
        front = np.flatnonzero(remaining == 0)
        points, inverse = np.unique(scores[front], axis=0, return_inverse=True)
        spread = _crowding_distance(points)[inverse.reshape(-1)]
        order = np.lexsort((rng.random(len(front)), -spread))
        ordered.extend(front[order][:capacity - len(ordered)])
        remaining -= np.sum(dominates[front], axis=0)
        remaining[front] = -1
    return ordered


## @brief Preserve two kinds of novelty and compete locally in the reporting view.
[docs] @registry.register class MultiDescriptorNSLC(_FixedGeneration): """Use the NS–NSLC objectives described by Pugh, Soros, and Stanley. The evaluator returns (fitness, reporting_descriptors, scores). A named score holds the independent exploration descriptor vector. The reporting view defines the neighbors for local competition. Each novelty view keeps a separate bounded memory. The objective direction for local competition is the raw scalar fitness direction. :param budget: Candidate evaluation attempts. :param dimension: Number of real-valued genes. :param population_size: Maximum size of the current breeding population. :param batch_size: Number of offspring before committing feedback. :param exploration_score_name: Score containing the exploration descriptor. :param reference_capacity: Maximum entries in each novelty memory. :param k: Number of nearest neighbors for novelty and local competition. :param ind_domain: Shared bounds on genome coordinates. :param sigma: Standard deviation of default bounded Gaussian variation. :param mutate: Optional callback taking (parent_genome, rng). :param seed: Private proposal and tie-breaking seed. :param kwargs: Native settings including optimization direction. """ _requires_proposed_genome = True def __init__(self, budget, dimension, population_size, batch_size=1, *, exploration_score_name="exploration", reference_capacity=128, k=15, ind_domain=(0., 1.), sigma=.1, mutate=None, seed=0, **kwargs): if not isinstance(exploration_score_name, str) or not exploration_score_name: raise ValueError("Supply a nonempty exploration descriptor score name.") 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 finite nonnegative sigma.") if mutate is not None and not callable(mutate): raise TypeError("mutate must be callable.") self.exploration_score_name = exploration_score_name self.reference_capacity = _positive_int(reference_capacity, "reference_capacity") self.k = _positive_int(k, "k") self.sigma, self.mutate, self.seed = sigma, mutate, seed archive = Container(capacity=_positive_int(population_size, "population_size"), fitness_domain=((-np.inf, np.inf),)) super().__init__(archive, _positive_int(budget, "budget"), nb_objectives=1, batch_size=_positive_int(batch_size, "batch_size"), dimension=_positive_int(dimension, "dimension"), **kwargs) if not self._fitness_weights[0]: raise ValueError("A nonzero scalar fitness weight is required.") def reinit(self): """Reset the two reference histories and the proposal stream.""" super().reinit() self._rng = np.random.default_rng(self.seed) self._widths = None self._memories = ({}, {}) self._ranked = () @property def reference_sizes(self): """Return the sizes of the exploration and reporting memories, in order.""" return tuple(map(len, self._memories)) def _internal_ask(self, base_ind): if not self.container: base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension) return base_ind ranked = self._ranked or tuple(self.container) parent = tuple(ranked[min(self._rng.integers(len(ranked), size=2))]) if self.mutate is None: genome = np.clip(np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension), *self.ind_domain) else: genome = np.asarray(self.mutate(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 _exploration(self, individual): return np.asarray(individual.scores[self.exploration_score_name], dtype=float) def _check_candidate(self, individual): super()._check_candidate(individual) vector = self._exploration(individual) if vector.ndim != 1 or not vector.size or not np.isfinite(vector).all(): raise ValueError("Provide a nonempty finite vector for the exploration descriptor.") widths = vector.size, len(individual.features) if self._widths is not None and self._widths != widths: raise ValueError("Descriptor widths must remain fixed in both views.") self._widths = widths def _neighbors(self, points, reference, view): # The prefix is the query population itself. Ignore its diagonal, # and keep only one entry per genome in the reference. entries = {tuple(item): item for item in points} for key, item in reference.items(): entries.setdefault(key, item) entries = tuple(entries.values()) data = np.asarray([self._exploration(item) if view == 0 else tuple(item.features) for item in entries]) scale = np.max(np.abs(data)) if scale > 1e140: data = data / scale distances = cdist(data[:len(points)], data) np.fill_diagonal(distances, np.inf) count = min(self.k, len(entries) - 1) indices = np.argsort(distances, axis=1, kind="stable")[:, :count] if not count: return np.zeros(len(points)), np.zeros(len(points)) novelty = np.take_along_axis(distances, indices, axis=1).mean(axis=1) quality = np.sign(self._fitness_weights[0]) * np.asarray([item.fitness.values[0] for item in entries]) return novelty, (quality[:len(points), None] > quality[indices]).mean(axis=1) def _update_memory(self, points, offspring, view): memory = self._memories[view] for candidate in offspring: memory.setdefault(tuple(candidate), candidate) if len(memory) > self.reference_capacity: entries = tuple(memory.values()) novelty, _ = self._neighbors(entries, {tuple(item): item for item in points}, view) selected = np.argsort(-novelty, kind="stable")[:self.reference_capacity] memory.clear() memory.update((tuple(entries[i]), entries[i]) for i in sorted(selected)) def _commit_generation(self, evaluated): archive = self.container parents = tuple(archive) pool = {tuple(parent): parent for parent in parents} offspring = {} for slot, individual in enumerate(evaluated): if individual is not None and tuple(individual) not in pool: pool[tuple(individual)] = individual offspring[id(individual)] = slot if not pool: return set() points = tuple(pool.values()) first, _ = self._neighbors(points, self._memories[0], 0) second, competition = self._neighbors(points, self._memories[1], 1) scores = np.column_stack((first, second, competition)) order = _pareto_survivors(scores, min(len(points), archive.capacity), self._rng) self._ranked = tuple(points[i] for i in order) keep = {id(item) for item in self._ranked} for item in parents: if id(item) not in keep: archive.discard(item) admitted = set() for item in self._ranked: key = id(item) if key in offspring: archive.add(item) admitted.add(offspring[key]) children = tuple(item for item in points if id(item) in offspring) for view in range(2): self._update_memory(points, children, view) return admitted