# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites with empirical outcome distributions as descriptors.
# @see https://doi.org/10.1109/TEVC.2023.3273560
# @see https://doi.org/10.1561/2200000073
"""Retain candidates by the distribution of a scalar outcome across rollouts."""
from dataclasses import dataclass
from math import isfinite
import numpy as np
from scipy.stats import wasserstein_distance
from .medoid_map_elites import MedoidArchive, MedoidElite, MedoidMAPElites
from .modern import _positive_int
__all__ = ["EmpiricalDistribution", "wasserstein_descriptor_distance", "DistributionMAPElites",
"DistributionAudit"]
## @brief Represent an empirical probability measure with equal mass per observation.
[docs]
@dataclass(frozen=True, init=False)
class EmpiricalDistribution:
"""Store a nonempty sorted tuple of finite scalar observations.
Repeated values keep their multiplicity. The distance accepts
distributions with unequal sample counts.
"""
samples: tuple[float, ...]
def __init__(self, samples):
values = tuple(sorted(map(float, samples)))
if not values or not all(map(isfinite, values)):
raise ValueError("An empirical distribution requires finite scalar observations.")
object.__setattr__(self, "samples", values)
## @brief Compute the one-dimensional first Wasserstein distance between empirical measures.
[docs]
def wasserstein_descriptor_distance(first, second):
"""Return the average transport cost with absolute distance in outcome units."""
if not isinstance(first, EmpiricalDistribution) or not isinstance(second, EmpiricalDistribution):
raise TypeError("Wasserstein descriptors must be EmpiricalDistribution objects.")
left, right = first.samples, second.samples
scale = max(abs(left[0]), abs(left[-1]), abs(right[0]), abs(right[-1]))
if scale > np.finfo(float).max / 2.:
return float(wasserstein_distance(np.asarray(left) / scale, np.asarray(right) / scale)) * scale
return float(wasserstein_distance(left, right))
## @brief Report how an archive elite maps to the same geometry under independent rollouts.
[docs]
@dataclass(frozen=True)
class DistributionAudit:
"""Compare the search assignment and a held-out measurement of one elite.
:param elite: Archive record containing the genome and search measurements.
:param search_niche: Niche index assigned during search.
:param audit_niche: Niche index from the audit descriptor.
:param fitness: Mean held-out fitness.
:param descriptor: Held-out outcome distribution.
"""
elite: MedoidElite
search_niche: int
audit_niche: int
fitness: float
descriptor: EmpiricalDistribution
@property
def stable(self):
"""Return whether reassessment kept the elite in its original niche."""
return self.search_niche == self.audit_niche
## @brief Measure stochastic outcomes repeatedly and illuminate fixed distributional niches.
[docs]
class DistributionMAPElites(MedoidMAPElites):
"""Use mean rollout fitness and the empirical distribution of scalar outcomes.
:param archive: MedoidArchive with EmpiricalDistribution reference descriptors.
Use wasserstein_descriptor_distance for one-dimensional Wasserstein niches.
:param propose: Callback (rng) producing an immutable genome.
:param mutate: Callback (parent, rng) producing an immutable offspring.
:param rollouts: Number of attempted calls per complete search measurement.
:param seed: Seed for variation and independent search and audit rollout streams.
The evaluator receives (genome, integer_seed) and returns (fitness,
scalar_outcome). Fitness controls replacement. The outcome controls
the niche. The evaluator can return the same value for both.
"""
def __init__(self, archive, *, propose, mutate, rollouts, seed=0):
if not isinstance(archive, MedoidArchive) or any(
not isinstance(anchor, EmpiricalDistribution) for anchor in archive.medoids):
raise TypeError("Supply a MedoidArchive with empirical distribution anchors.")
self._rollouts = _positive_int(rollouts, "rollouts")
variation, search, self._audit_seed = np.random.SeedSequence(seed).spawn(3)
super().__init__(archive, propose=propose, mutate=mutate, seed=variation)
self._rollout_rng = np.random.default_rng(search)
self.nb_rollouts = 0
self.nb_audit_rollouts = 0
def _measure(self, genome, evaluate, seeds, counter):
scores, outcomes = [], []
for seed in seeds:
setattr(self, counter, getattr(self, counter) + 1)
fitness, outcome = map(float, evaluate(genome, int(seed)))
if not isfinite(fitness) or not isfinite(outcome):
raise ValueError("Every rollout must return finite scalar fitness and outcome.")
scores.append(fitness)
outcomes.append(outcome)
return float(np.mean(scores)), EmpiricalDistribution(outcomes)
## @brief Spend a candidate budget, charging every attempted rollout separately.
[docs]
def optimise(self, evaluate, *, budget):
"""Return the search archive after up to budget complete candidate measurements."""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
def seeds():
for _ in range(self._rollouts):
yield self._rollout_rng.bit_generator.random_raw()
return super().optimise(
lambda genome: self._measure(genome, evaluate, seeds(), "nb_rollouts"), budget=budget)
## @brief Reassess archived genomes on a common held-out seed panel.
[docs]
def audit(self, evaluate, *, rollouts):
"""Return audit records in niche order, without writing measurements to the archive.
Every elite receives the same fixed seed panel, drawn independently
of search. Repeating an audit with the same size reuses that panel.
"""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
count = _positive_int(rollouts, "rollouts")
seeds = self._audit_seed.generate_state(count, dtype=np.uint64)
rows = []
for niche, elite in sorted(self.archive.cells.items()):
fitness, descriptor = self._measure(elite.genome, evaluate, seeds, "nb_audit_rollouts")
rows.append(DistributionAudit(elite, niche, self.archive.index(descriptor), fitness, descriptor))
return tuple(rows)