Source code for qdpy.algorithms.minimize_surprise

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Illuminate diverse sensor behaviors by coevolving actor and predictor genomes.
# @see https://doi.org/10.1145/3520304.3528773

"""Use next-observation prediction accuracy as a task-independent objective."""

from dataclasses import dataclass

import numpy as np

from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["MinimizeSurpriseResult", "minimize_surprise_map_elites", "prediction_accuracy"]


## @brief Average one minus absolute prediction error over all sensors, agents, and steps.
# @param predicted Next-observation predictions in [0, 1].
# @param observed Actual next observations in [0, 1], with the same nonempty shape.
# @return Scalar prediction accuracy in [0, 1].
[docs] def prediction_accuracy(predicted, observed): """Align each prediction with the actual observation after the chosen action.""" predicted, observed = (np.asarray(values, dtype=float) for values in (predicted, observed)) if (predicted.shape != observed.shape or predicted.ndim < 1 or not predicted.size or not all(np.all((0. <= values) & (values <= 1.)) for values in (predicted, observed))): raise ValueError("Provide nonempty arrays of identical shape with sensor values in [0, 1].") return float(1. - np.mean(np.abs(predicted - observed)))
## @brief Sensor repertoire, number of evaluated genomes, and rollout accounting.
[docs] @dataclass(frozen=True) class MinimizeSurpriseResult: """Every repeat contributes prediction accuracy and a measured descriptor.""" archive: object evaluations: int rollout_calls: int sensor_steps: int admissions: int
## @brief Search actor-predictor genomes with worst-repeat predictive quality. # @param archive Empty best-only Grid or CVTGrid with maximizing fitness. # @param rollout Callable (genome, seed) returning paired prediction and observation arrays. # @param describe Callable (observed) returning one behavior descriptor vector. # @param sample Callable (rng) returning an initial actor-predictor genome. # @param mutate Callable (parent, rng) returning an offspring genome. # @param budget Number of measured genomes. # @param repeats Number of common seeded rollouts per genome. # @param initial_samples Number of unconditional sample calls. # @param seed Private variation and rollout seed. # @return MinimizeSurpriseResult with the archive and separate work counts.
[docs] def minimize_surprise_map_elites(archive, rollout, *, describe, sample, mutate, budget, repeats=3, initial_samples=16, seed=0): """Use the minimum prediction accuracy over repeats and average observed descriptors.""" _validate_grid(archive) if not all(map(callable, (rollout, describe, sample, mutate))): raise TypeError("Supply callable rollout, descriptors and variation.") budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples) repeats = _positive_int(repeats, "repeats") if archive.fitness_weights is None: archive._set_fitness_weights((1.,)) if archive.fitness_weights[0] <= 0: raise ValueError("The archive must maximize prediction accuracy.") rng, rollout_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2)) seeds = tuple(map(int, rollout_rng.integers(2**32, size=repeats))) before = archive.nb_added steps = 0 for i in range(budget): if i < initial or not archive: genome = tuple(sample(rng)) else: genome = tuple(mutate(tuple(archive[int(rng.integers(len(archive)))]), rng)) values, descriptors = [], [] for world in seeds: predicted, observed = rollout(genome, world) observed = np.asarray(observed, dtype=float) values.append(prediction_accuracy(predicted, observed)) steps += len(observed) descriptors.append(_finite_vector(describe(observed), "Behavior descriptor", len(archive.features_domain))) average = (np.asarray(descriptors, dtype=float) / repeats).sum(axis=0) _offer(archive, _measurement(archive, ((min(values),), average), genome)) return MinimizeSurpriseResult(archive, budget, budget * repeats, steps, archive.nb_added - before)