Source code for qdpy.algorithms.constrained_novelty

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Evolve feasible and infeasible populations with independent selection.
# @see https://antoniosliapis.com/papers/constrained_novelty_search.pdf

"""Steady-state FINS and FI2NS with a passive feasible reporting archive."""

from collections import Counter, deque
from dataclasses import dataclass
from math import fsum

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

from .modern import _positive_int
from .sampling import _rollout_seed
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["FeasibleInfeasibleNoveltySearch", "FeasibleNoveltyStats"]


def _novelty_scores(population, history, embedding, neighbors):
    """Mean distance to the nearest other records, excluding identical live references."""
    present = {row.genome for row in population}
    extra = [row for row in history if row.genome not in present]
    count = min(neighbors, len(population) + len(extra) - 1)
    if count < 1:
        return np.zeros(len(population))
    points = [embedding(row) for row in population]
    distances = cdist(points, points + [embedding(row) for row in extra])
    np.fill_diagonal(distances, np.inf)
    scores = np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
    if not np.isfinite(scores).all():
        raise ValueError("Novelty distances must stay finite. Scale the descriptor coordinates.")
    return scores


def _remember(history, row):
    if not any(old.genome == row.genome for old in history):
        history.append(row)


def _tournament(population, scores, rng):
    choices = rng.integers(len(population), size=2)
    return population[int(choices[np.argmax(scores[choices])])]


@dataclass(frozen=True)
class _Candidate:
    genome: tuple
    descriptor: tuple[float, ...]
    violation: float


## @brief Account for feasible measurements, migrations, and reporting-archive changes.
[docs] @dataclass(frozen=True) class FeasibleNoveltyStats: """Evaluations count attempted calls, with one-based first-feasible indexing.""" evaluations: int = 0 feasible_evaluations: int = 0 feasible_from_infeasible: int = 0 infeasible_from_feasible: int = 0 archive_updates: int = 0 first_feasible: int | None = None
## @brief Search with feasible novelty and either violation or infeasible novelty.
[docs] class FeasibleInfeasibleNoveltySearch: """Keep independent bounded populations and novelty histories. FINS chooses feasible parents by novelty and infeasible parents by low total positive violation. FI2NS uses novelty in both populations. An offspring enters the pool appropriate to its measured constraints. Only feasible measurements are offered to the independent native grid. :param archive: Empty parentless best-only Grid or CVTGrid. :param initializer: Callable (rng) returning an immutable genome sequence. :param mutate: Callable (genome, rng) returning a new genome sequence. :param mode: FINS or FI2NS, specified as "fins" or "fi2ns". :param population_size: Capacity of each breeding population. :param history_size: Number of distinct recent genomes per novelty history. :param neighbors: Nearest-neighbor count for novelty. :param feasible_parent_probability: Fraction of births allocated to feasible breeders when both populations are available. :param initial_samples: Number of initial proposals from initializer. :param seed: Seed for variation, selection, and evaluation calls. """ def __init__(self, archive, *, initializer, mutate, mode="fins", population_size=32, history_size=128, neighbors=5, feasible_parent_probability=.5, initial_samples=16, seed=0): _validate_grid(archive) if not callable(initializer) or not callable(mutate): raise TypeError("Supply initializer and mutate callbacks.") if mode not in ("fins", "fi2ns") or not 0 <= feasible_parent_probability <= 1.: raise ValueError("Use fins or fi2ns and a parent probability between zero and one.") self.archive = archive self._initializer, self._mutate = initializer, mutate self._mode, self._probability = mode, feasible_parent_probability self._capacity = _positive_int(population_size, "population_size") self._neighbors = _positive_int(neighbors, "neighbors") self._initial = _positive_int(initial_samples, "initial_samples") memory = _positive_int(history_size, "history_size") self._groups = ([], []) self._history = (deque(maxlen=memory), deque(maxlen=memory)) rng, evaluations = np.random.SeedSequence(seed).spawn(2) self._rng = np.random.default_rng(rng) self._evaluation_seed = int(evaluations.generate_state(1, dtype=np.uint64)[0]) self._counts = Counter() self._residual_count = self._first = None @property def stats(self): """Return cumulative measured search costs and outcomes.""" return FeasibleNoveltyStats(**self._counts, first_feasible=self._first) @property def feasible_population(self): """Return immutable active feasible genomes.""" return tuple(row.genome for row in self._groups[1]) @property def infeasible_population(self): """Return immutable active infeasible genomes.""" return tuple(row.genome for row in self._groups[0]) def _scores(self, group): population = self._groups[group] if group == 0 and self._mode == "fins": return -np.asarray([row.violation for row in population]) return _novelty_scores(population, self._history[group], lambda row: row.descriptor, self._neighbors) def _parent(self): infeasible, feasible = self._groups if self._counts["evaluations"] < self._initial: return None, None group = int(bool(feasible) and (not infeasible or self._rng.random() < self._probability)) pool = self._groups[group] return (group, _tournament(pool, self._scores(group), self._rng)) if pool else (None, None) def _candidate(self, genome, descriptor, violation, residuals): return _Candidate(genome, descriptor, violation) ## @brief Spend an additional hard evaluator budget. # @param evaluate Callback (genome, seed) returning scalar fitness, descriptors, and residuals. # @param budget Maximum number of additional attempted evaluations. # @return Cumulative FeasibleNoveltyStats.
[docs] def run(self, evaluate, budget) -> FeasibleNoveltyStats: """Use residuals at or below zero for feasible admission and propagate invalid evaluations.""" if not callable(evaluate): raise TypeError("Supply a callable evaluator.") for _ in range(_positive_int(budget, "budget")): origin, parent = self._parent() genome = tuple(self._initializer(self._rng) if parent is None else self._mutate(parent.genome, self._rng)) hash(genome) attempt = self._counts["evaluations"] self._counts["evaluations"] += 1 fitness, descriptors, residuals = evaluate(genome, _rollout_seed(self._evaluation_seed, 0, attempt)) residuals = tuple(map(float, residuals)) if (not residuals or not np.isfinite(residuals).all() or self._residual_count is not None and len(residuals) != self._residual_count): raise ValueError("Return a fixed nonempty vector of finite residuals.") self._residual_count = len(residuals) violation = fsum(max(0., value) for value in residuals) measurement = _measurement(self.archive, ((fitness,), descriptors), genome) measured, _ = measurement group = int(violation == 0.) if group: self._counts["feasible_evaluations"] += 1 if self._first is None: self._first = attempt + 1 if origin == 0: self._counts["feasible_from_infeasible"] += 1 before = self.archive.nb_added _offer(self.archive, measurement) self._counts["archive_updates"] += self.archive.nb_added - before elif origin == 1: self._counts["infeasible_from_feasible"] += 1 pool = self._groups[group] if any(row.genome == genome for row in pool): continue row = self._candidate(genome, tuple(self.archive.get_ind_features(measured)), violation, residuals) pool.append(row) if len(pool) > self._capacity: scores = self._scores(group) pool.pop(len(pool) - 1 - int(scores[::-1].argmin())) if group or self._mode == "fi2ns": _remember(self._history[group], row) return self.stats