Source code for qdpy.algorithms.tbr_evolution

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Transferability-based Behavioral Repertoire Evolution with two evaluation sources.
# @see https://doi.org/10.1162/EVCO_a_00143

"""Discover locally good behaviors while learning the source-to-target descriptor error."""

from dataclasses import dataclass
from math import dist, fsum, isfinite

import numpy as np
from sklearn.svm import NuSVR

from ._population import _attempt_budget, _finite_vector, _nsga_order, _tournament
from .modern import _positive_int

__all__ = ["TBREvolution", "TBREntry", "TBRTransfer", "TBRStats"]


## @brief A measured simulation candidate with an immutable identifier.
[docs] @dataclass(frozen=True) class TBREntry: """Store predicted-system measurements and the simulator attempt ID.""" genome: tuple quality: float descriptor: tuple[float, ...] evaluation_id: int
## @brief One paired source/target measurement used to fit the discrepancy model.
[docs] @dataclass(frozen=True) class TBRTransfer: """Record simulator output, target output, and observed Euclidean error.""" source: TBREntry target_descriptor: tuple[float, ...] error: float
## @brief Keep simulator and target costs independently visible.
[docs] @dataclass(frozen=True) class TBRStats: """Count attempts at each fidelity, failed calls, and committed generations.""" simulation_evaluations: int target_evaluations: int simulation_failures: int target_failures: int generations: int
## @brief Breed by novelty, local quality, and local predicted transferability.
[docs] class TBREvolution: """Maintain a simulator repertoire with occasional measurements on a target system. Periodically sample one candidate from the combined population and repertoire, observe its target descriptor, and update a linear nu-SVR discrepancy model. Novelty and local quality and error ranks determine NSGA-II survival. A locally competing archive candidate wins on quality when both errors meet the transfer threshold. If either misses that threshold, the lower predicted error wins. :param sample: Callable (rng) returning a genome iterable. :param mutate: Callable (parent_genome, rng) returning an offspring. :param population_size: Initial and offspring batch size and survivor capacity. :param neighbors: Number of neighbors in the population and repertoire union. :param novelty_threshold: Novelty needed to enter without replacing a neighbor. :param transfer_threshold: Maximum acceptable predicted target descriptor error. :param transfer_period: Number of completed simulator batches between transfer attempts. :param maximize: Prefer larger quality when True and smaller quality otherwise. :param seed: Random seed for variation, transfer selection, and both evaluators. """ def __init__(self, *, sample, mutate, population_size=24, neighbors=15, novelty_threshold=.1, transfer_threshold=.2, transfer_period=4, maximize=True, seed=0): if not callable(sample) or not callable(mutate): raise TypeError("sample and mutate must be callable.") if not 0 <= novelty_threshold < np.inf or not 0 <= transfer_threshold < np.inf: raise ValueError("Thresholds must be finite and nonnegative.") self._sample, self._mutate = sample, mutate self._size = _positive_int(population_size, "population_size") self._neighbors = _positive_int(neighbors, "neighbors") self._period = _positive_int(transfer_period, "transfer_period") self._novelty, self._threshold = novelty_threshold, transfer_threshold self._direction = 1. if maximize else -1. self._variation, self._select_target, self._simulation_rng, self._target_rng = map( np.random.default_rng, np.random.SeedSequence(seed).spawn(4)) self._archive, self._transfers, self._children = [], [], [] self._population, self._keys = (), () self._model = None self._descriptor_size = None self._pending = self._simulations = self._targets = self._sim_failures = self._target_failures = 0 self._generations = 0 @property def archive(self): """Return the current repertoire with simulated quality and descriptors.""" return tuple(self._archive) @property def population(self): """Return the last selected breeding population.""" return self._population @property def transfers(self): """Return measured simulator–target pairs used for fitting.""" return tuple(self._transfers) @property def stats(self): """Return attempts and failures by evaluation source.""" return TBRStats(self._simulations, self._targets, self._sim_failures, self._target_failures, self._generations) ## @brief Predict Euclidean descriptor discrepancy with the current transfer data. # @param descriptors Batch of simulated descriptors with consistent dimensions. # @return Predicted nonnegative errors in descriptor units.
[docs] def predict_error(self, descriptors): """Use an optimistic zero before transfer data and the observed constant for one pair.""" points = np.asarray([_finite_vector(row, "Simulated descriptor", self._descriptor_size) for row in descriptors], dtype=float) if not len(points): return np.empty(0) if self._model is not None: values = self._model.predict(points) if not np.isfinite(values).all(): raise ValueError("The transfer estimator overflowed. Rescale the descriptor space.") return np.maximum(0., values) return np.full(len(points), self._transfers[0].error if self._transfers else 0.)
def _transfer(self, evaluate_target, pool): row = pool[int(self._select_target.integers(len(pool)))] self._targets += 1 result = evaluate_target(row.genome, int(self._target_rng.integers(2**32))) if result is None: self._target_failures += 1 return descriptor = _finite_vector(result, "Target descriptor", self._descriptor_size) error = dist(row.descriptor, descriptor) if not isfinite(error): raise ValueError("The measured target discrepancy is outside the representable range.") record = TBRTransfer(row, descriptor, error) if self._transfers: examples = [*self._transfers, record] self._model = NuSVR(kernel="linear").fit( [item.source.descriptor for item in examples], [item.error for item in examples]) self._transfers.append(record) def _prefer(self, row, incumbent, errors): error, existing = errors[row.evaluation_id], errors[incumbent.evaluation_id] if max(error, existing) <= self._threshold: return self._direction * row.quality > self._direction * incumbent.quality return error < existing def _offer(self, row, novelty, errors): if not self._archive: self._archive.append(row) return if any(old.evaluation_id == row.evaluation_id for old in self._archive): return distances = [dist(row.descriptor, incumbent.descriptor) for incumbent in self._archive] nearest = int(np.argmin(distances)) if distances[nearest] > 0. and novelty > self._novelty: self._archive.append(row) elif self._prefer(row, self._archive[nearest], errors): self._archive[nearest] = row def _commit(self, evaluate_target, targets_remaining): candidates = self._population + tuple(self._children) # Candidates can also be archived. Give each observation one vote. pool = tuple({row.evaluation_id: row for row in (*candidates, *self._archive)}.values()) if pool and targets_remaining and (self._generations + 1) % self._period == 0: self._transfer(evaluate_target, pool) if candidates: errors = {row.evaluation_id: error for row, error in zip(pool, self.predict_error(row.descriptor for row in pool))} scores = [] for row in candidates: neighbors = sorted((dist(row.descriptor, other.descriptor), other.evaluation_id, other) for other in pool if other.evaluation_id != row.evaluation_id)[:self._neighbors] novelty = fsum(distance / len(neighbors) for distance, _, _ in neighbors) if not isfinite(novelty): raise ValueError("Novelty is outside the representable range. Rescale descriptors.") local_quality = -sum(self._direction * other.quality > self._direction * row.quality for _, _, other in neighbors) local_transfer = -sum(errors[other.evaluation_id] < errors[row.evaluation_id] for _, _, other in neighbors) scores.append((novelty, local_quality, local_transfer)) for row, score in zip(candidates, scores): self._offer(row, score[0], errors) survivors, keys = _nsga_order(np.asarray(scores, dtype=float), self._size) self._population = tuple(candidates[i] for i in survivors) self._keys = keys self._generations += 1 self._children.clear() self._pending = 0 ## @brief Run simulation and optional target evaluations with independent attempt caps. # @param simulate Callable (genome, seed) returning (quality, simulated descriptor) or None. # @param simulation_budget Additional simulator evaluation attempts. # @param evaluate_target Callable (genome, seed) returning a target descriptor or None. # @param target_budget Maximum additional target attempts. # @return Cumulative TBRStats.
[docs] def run(self, simulate, simulation_budget, *, evaluate_target=None, target_budget=0): """Spend simulator attempts and skip scheduled transfers when the target budget is exhausted.""" simulations, targets = _attempt_budget(simulation_budget), _attempt_budget(target_budget) if targets and not callable(evaluate_target): raise TypeError("A positive target budget requires an evaluate_target callback.") limit = self._targets + targets if self._pending == self._size: self._commit(evaluate_target, limit - self._targets) for _ in range(simulations): if self._population: parent = _tournament(self._population, self._keys, self._variation) genome = tuple(self._mutate(parent.genome, self._variation)) else: genome = tuple(self._sample(self._variation)) self._simulations += 1 result = simulate(genome, int(self._simulation_rng.integers(2**32))) if result is None: self._sim_failures += 1 else: quality, descriptor = result values = _finite_vector(descriptor, "Simulated descriptor", self._descriptor_size) if not isfinite(quality): raise ValueError("Simulation quality must be finite.") self._descriptor_size = len(values) self._children.append(TBREntry(genome, float(quality), values, self._simulations)) self._pending += 1 if self._pending == self._size: self._commit(evaluate_target, limit - self._targets) return self.stats