Source code for qdpy.algorithms.surprise

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Forecast-based diversity with steady-state local competition.
# @see https://arxiv.org/abs/1807.02397

"""Surprise Search with Local Competition for bounded real vectors."""

from collections import deque
from dataclasses import dataclass

import numpy as np
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from threadpoolctl import threadpool_limits

from qdpy.containers import Grid
from qdpy.phenotype import Individual
from .modern import _bounds, _positive_int
from .sampling import _aggregate
from .uncertain import _Rollouts, _cell

__all__ = ["SurpriseSearchLC", "NoveltySurpriseSearchLC", "SurpriseSearchResult", "surprise_local_scores"]


## @brief Score forecast deviations and the number of worse behavioral neighbors.
def surprise_local_scores(descriptors, qualities, predictions, *, surprise_neighbors=2, local_neighbors=5):
    """Return an array with columns (mean forecast distance, local fitness wins).

    Qualities use the maximization convention. For local competition the
    candidate itself is excluded, even when other descriptors coincide.
    Distances are Euclidean in the supplied descriptor coordinates.
    """
    descriptors, qualities, predictions = map(lambda x: np.asarray(x, dtype=float),
                                               (descriptors, qualities, predictions))
    if (descriptors.ndim != 2 or min(descriptors.shape) == 0 or predictions.ndim != 2
            or predictions.shape[1] != descriptors.shape[1] or not len(predictions)
            or qualities.shape != (len(descriptors),)
            or not all(np.isfinite(x).all() for x in (descriptors, qualities, predictions))):
        raise ValueError("Supply finite descriptor and prediction matrices and one quality per candidate.")
    ks = min(_positive_int(surprise_neighbors, "surprise_neighbors"), len(predictions))
    kl = min(_positive_int(local_neighbors, "local_neighbors"), len(descriptors) - 1)
    differences = cdist(descriptors, predictions)
    surprise = np.partition(differences, ks - 1, axis=1)[:, :ks].mean(axis=1)
    distances = cdist(descriptors, descriptors)
    np.fill_diagonal(distances, np.inf)
    neighbors = np.argsort(distances, axis=1, kind="stable")[:, :kl]
    wins = (qualities[:, None] > qualities[neighbors]).sum(axis=1)
    return np.column_stack((surprise, wins))


def _order(objectives):
    dominates = ((objectives[:, None] >= objectives).all(axis=2) &
                 (objectives[:, None] > objectives).any(axis=2))
    remaining = dominates.sum(axis=0)
    ranks, crowding = np.empty(len(objectives), dtype=int), np.zeros(len(objectives))
    rank = 0
    while (front := np.flatnonzero(remaining == 0)).size:
        ranks[front] = rank
        remaining[front] = -1
        remaining -= dominates[front].sum(axis=0)
        if len(front) <= 2:
            crowding[front] = np.inf
        else:
            for values in objectives.T:
                ordered = front[np.argsort(values[front], kind="stable")]
                span = values[ordered[-1]] - values[ordered[0]]
                if span > 0:
                    crowding[ordered[[0, -1]]] = np.inf
                    crowding[ordered[1:-1]] += (values[ordered[2:]] - values[ordered[:-2]]) / span
        rank += 1
    return ranks, crowding


def _memory_distances(descriptors, population, history, features):
    # A point retained both as a breeder and in the novelty memory counts once.
    active = {id(individual) for individual in population}
    extras = [individual for individual in history if id(individual) not in active]
    reference = descriptors if not extras else np.concatenate((descriptors, [features(ind) for ind in extras]))
    distances = cdist(descriptors, reference)
    np.fill_diagonal(distances, np.inf)
    return distances, extras


## @brief Return the final breeding population and attempted evaluation counts.
@dataclass(frozen=True)
class SurpriseSearchResult:
    """Keep the terminal population separately from the reporting grid."""

    population: tuple
    evaluations: int
    failed_evaluations: int
    forecasts: int


## @brief Steady-state NSGA-II using surprise and local fitness competition.
class SurpriseSearchLC:
    """Forecast cluster motion from consecutive population snapshots.

    The grid receives measurements for reporting and cannot influence
    selection. The breeding population and forecast reset on each call.
    The grid can retain measurements accumulated before the search.

    :param archive: Reporting Grid or CVTGrid with one signed objective.
    :param dimension: Number of real-valued decision variables.
    :param ind_domain: Shared finite lower and upper decision bounds.
    :param population_size: Number of candidates retained for breeding.
    :param clusters: Maximum cluster count per snapshot.
    :param forecast_interval: Offspring between model updates. Defaults to population_size.
    :param surprise_neighbors: Predictions used for the surprise objective.
    :param local_neighbors: Population neighbors used for local competition.
    :param mutation_sigma: Gaussian variation in units of the decision interval.
    :param seed: Private seed for clustering, offspring, and evaluations.
    """

    def __init__(self, archive, dimension, *, ind_domain=(0., 1.), population_size=64,
                 clusters=16, forecast_interval=None, surprise_neighbors=2, local_neighbors=5,
                 mutation_sigma=.1, seed=0):
        if (not isinstance(archive, Grid) or len(archive.fitness_domain or ()) != 1
                or len(archive.fitness_weights or ()) != 1
                or not np.isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]
                or archive.parents):
            raise ValueError("Use a reporting grid with one signed fitness objective.")
        self.archive, self.seed = archive, seed
        self.dimension = _positive_int(dimension, "dimension")
        self.population_size = _positive_int(population_size, "population_size")
        if self.population_size < 2 or not 0 < mutation_sigma < np.inf:
            raise ValueError("Use at least two individuals and positive finite mutation_sigma.")
        self.clusters = _positive_int(clusters, "clusters")
        self.forecast_interval = (self.population_size if forecast_interval is None
                                  else _positive_int(forecast_interval, "forecast_interval"))
        self.surprise_neighbors = _positive_int(surprise_neighbors, "surprise_neighbors")
        self.local_neighbors = _positive_int(local_neighbors, "local_neighbors")
        self.ind_domain, self.mutation_sigma = _bounds(ind_domain), mutation_sigma

    def _centers(self, population, rng):
        descriptors = np.asarray([self.archive.get_ind_features(ind) for ind in population])
        distinct = np.unique(descriptors, axis=0)
        if len(distinct) <= self.clusters:
            return distinct
        with threadpool_limits(limits=1):
            return KMeans(self.clusters, n_init=1, random_state=int(rng.integers(2**31))).fit(
                descriptors).cluster_centers_

    def _rank(self, population, predictions, history):
        descriptors = [self.archive.get_ind_features(ind) for ind in population]
        qualities = [self.archive.fitness_weights[0] * self.archive.get_ind_fitness(ind).values[0]
                     for ind in population]
        return _order(surprise_local_scores(descriptors, qualities, predictions,
                                            surprise_neighbors=self.surprise_neighbors,
                                            local_neighbors=self.local_neighbors))

    def _memory(self):
        return None

    def _remember(self, population, history):
        """The original surprise search uses only the active population."""

    ## @brief Perform one-offspring updates and charge all evaluation attempts.
    # @param evaluate Seeded evaluator taking (Individual, rollout_seed).
    # @param budget Total evaluation attempts including initialization.
    # @return SurpriseSearchResult with final population and forecast counts.
    def run(self, evaluate, budget):
        """Run bounded real-valued variation with binary NSGA-II tournaments."""
        budget = _positive_int(budget, "budget")
        rng = np.random.default_rng([self.seed, 3])
        runner = _Rollouts(self.archive, evaluate, None, self.seed, stream=3, seeded=True)
        lo, hi = self.ind_domain
        population = []
        history = self._memory()

        def measure(vector):
            candidate = Individual(vector.tolist())
            rows, = runner.evaluate_groups([(candidate, 1)])
            if not rows:
                return None
            individual = _aggregate(self.archive, candidate, rows)
            cell = _cell(self.archive, individual)
            if (cell is not None and (self.archive.free or self.archive.solutions[cell])
                    and self.archive.in_bounds(self.archive.get_ind_fitness(individual).values,
                                               self.archive.fitness_domain)):
                self.archive.add(individual)
            return individual

        for _ in range(min(budget, self.population_size)):
            measured = measure(rng.uniform(lo, hi, size=self.dimension))
            if measured is not None:
                population.append(measured)
        previous = predictions = ranks = crowding = None
        forecasts = 0
        for step in range(budget - runner.attempted):
            if len(population) < self.population_size:
                measured = measure(rng.uniform(lo, hi, size=self.dimension))
                if measured is not None:
                    population.append(measured)
                continue
            if predictions is None or step % self.forecast_interval == 0:
                current = self._centers(population, rng)
                predictions = (current if previous is None else
                               2 * current - previous[cdist(current, previous).argmin(axis=1)])
                previous = current
                ranks, crowding = self._rank(population, predictions, history)
                forecasts += 1

            def tournament():
                a, b = rng.choice(len(population), 2, replace=False)
                return np.asarray(population[min((a, b), key=lambda i: (ranks[i], -crowding[i]))])

            first, second = tournament(), tournament()
            fraction = rng.random(self.dimension)
            child = first + fraction * (second - first) + rng.normal(
                scale=self.mutation_sigma * (hi - lo), size=self.dimension)
            measured = measure(np.clip(child, lo, hi))
            if measured is not None:
                population.append(measured)
                ranks, crowding = self._rank(population, predictions, history)
                self._remember(population, history)
                worst = max(range(len(population)), key=lambda i: (ranks[i], -crowding[i], i))
                population.pop(worst)
                ranks, crowding = self._rank(population, predictions, history)
        return SurpriseSearchResult(tuple(population), runner.attempted, runner.failed, forecasts)


## @brief Combine novelty, forecast deviation, and local fitness competition.
[docs] class NoveltySurpriseSearchLC(SurpriseSearchLC): """Use the same forecasts and steady-state variation as SurpriseSearchLC. With a real-valued novelty_weight, NSGA-II maximizes the weighted sum of novelty and surprise beside local wins. With novelty_weight=None, it treats all three signals as separate objectives. Novelty and local wins consider both the live population and past novel offspring. Distances are Euclidean in descriptor coordinates, as in SS-LC. :param archive: Passive reporting grid, as in SurpriseSearchLC. :param dimension: Number of decision coordinates. :param novelty_weight: Novelty fraction of the aggregated divergence score. Use None for three-objective NS-SS-LC. :param novelty_neighbors: Number of neighbors for the novelty score. :param novelty_threshold: Add measured offspring whose novelty meets this threshold. :param novelty_history: Maximum number of older novel offspring retained in FIFO order. :param kwargs: Search, forecast, and variation settings accepted by SurpriseSearchLC. """ def __init__(self, archive, dimension, *, novelty_weight=.5, novelty_neighbors=15, novelty_threshold=.1, novelty_history=512, **kwargs): super().__init__(archive, dimension, **kwargs) if novelty_weight is not None and not 0. <= novelty_weight <= 1.: raise ValueError("Use a novelty_weight between zero and one, or None.") if not 0. <= novelty_threshold < np.inf: raise ValueError("Use a finite nonnegative novelty_threshold.") self.novelty_weight, self.novelty_threshold = novelty_weight, novelty_threshold self.novelty_neighbors = _positive_int(novelty_neighbors, "novelty_neighbors") self.novelty_history = _positive_int(novelty_history, "novelty_history") def _memory(self): return deque(maxlen=self.novelty_history) def _rank(self, population, predictions, history): features, fitness = self.archive.get_ind_features, self.archive.get_ind_fitness descriptors = np.asarray([features(individual) for individual in population], dtype=float) distances, extras = _memory_distances(descriptors, population, history, features) kn = min(self.novelty_neighbors, distances.shape[1] - 1) novelty = np.partition(distances, kn - 1, axis=1)[:, :kn].mean(axis=1) kl = min(self.local_neighbors, distances.shape[1] - 1) local = np.argsort(distances, axis=1, kind="stable")[:, :kl] direction = self.archive.fitness_weights[0] qualities = np.asarray([fitness(ind).values[0] * direction for ind in (*population, *extras)]) wins = (qualities[:len(population), None] > qualities[local]).sum(axis=1) deviations = cdist(descriptors, predictions) ks = min(self.surprise_neighbors, len(predictions)) surprise = np.partition(deviations, ks - 1, axis=1)[:, :ks].mean(axis=1) weight = self.novelty_weight objectives = ((novelty, surprise, wins) if weight is None else (weight * novelty + (1. - weight) * surprise, wins)) return _order(np.column_stack(objectives)) def _remember(self, population, history): child = population[-1] features = self.archive.get_ind_features active = {id(individual) for individual in population} reference = (*population[:-1], *(ind for ind in history if id(ind) not in active)) distances = cdist([features(child)], [features(ind) for ind in reference])[0] kn = min(self.novelty_neighbors, len(distances)) if np.partition(distances, kn - 1)[:kn].mean() >= self.novelty_threshold: history.append(child)