7"""Retain candidates by the distribution of a scalar outcome across rollouts."""
9from dataclasses
import dataclass
10from math
import isfinite
13from scipy.stats
import wasserstein_distance
15from .medoid_map_elites
import MedoidArchive, MedoidElite, MedoidMAPElites
16from .modern
import _positive_int
18__all__ = [
"EmpiricalDistribution",
"wasserstein_descriptor_distance",
"DistributionMAPElites",
23@dataclass(frozen=True, init=False)
25 """Store a nonempty sorted tuple of finite scalar observations.
27 Repeated values keep their multiplicity. The distance accepts
28 distributions with unequal sample counts.
31 samples: tuple[float, ...]
33 def __init__(self, samples):
34 values = tuple(sorted(map(float, samples)))
35 if not values
or not all(map(isfinite, values)):
36 raise ValueError(
"An empirical distribution requires finite scalar observations.")
37 object.__setattr__(self,
"samples", values)
41def wasserstein_descriptor_distance(first, second):
42 """Return the average transport cost with absolute distance in outcome units."""
43 if not isinstance(first, EmpiricalDistribution)
or not isinstance(second, EmpiricalDistribution):
44 raise TypeError(
"Wasserstein descriptors must be EmpiricalDistribution objects.")
45 left, right = first.samples, second.samples
46 scale = max(abs(left[0]), abs(left[-1]), abs(right[0]), abs(right[-1]))
47 if scale > np.finfo(float).max / 2.:
48 return float(wasserstein_distance(np.asarray(left) / scale, np.asarray(right) / scale)) * scale
49 return float(wasserstein_distance(left, right))
53@dataclass(frozen=True)
55 """Compare the search assignment and a held-out measurement of one elite.
57 :param elite: Archive record containing the genome and search measurements.
58 :param search_niche: Niche index assigned during search.
59 :param audit_niche: Niche index from the audit descriptor.
60 :param fitness: Mean held-out fitness.
61 :param descriptor: Held-out outcome distribution.
68 descriptor: EmpiricalDistribution
72 """Return whether reassessment kept the elite in its original niche."""
78 """Use mean rollout fitness and the empirical distribution of scalar outcomes.
80 :param archive: MedoidArchive with EmpiricalDistribution reference descriptors.
81 Use wasserstein_descriptor_distance for one-dimensional Wasserstein niches.
82 :param propose: Callback (rng) producing an immutable genome.
83 :param mutate: Callback (parent, rng) producing an immutable offspring.
84 :param rollouts: Number of attempted calls per complete search measurement.
85 :param seed: Seed for variation and independent search and audit rollout streams.
87 The evaluator receives (genome, integer_seed) and returns (fitness,
88 scalar_outcome). Fitness controls replacement. The outcome controls
89 the niche. The evaluator can return the same value for both.
92 def __init__(self, archive, *, propose, mutate, rollouts, seed=0):
93 if not isinstance(archive, MedoidArchive)
or any(
94 not isinstance(anchor, EmpiricalDistribution)
for anchor
in archive.medoids):
95 raise TypeError(
"Supply a MedoidArchive with empirical distribution anchors.")
96 self.
_rollouts = _positive_int(rollouts,
"rollouts")
97 variation, search, self.
_audit_seed = np.random.SeedSequence(seed).spawn(3)
98 super().__init__(archive, propose=propose, mutate=mutate, seed=variation)
103 def _measure(self, genome, evaluate, seeds, counter):
104 scores, outcomes = [], []
106 setattr(self, counter, getattr(self, counter) + 1)
107 fitness, outcome = map(float, evaluate(genome, int(seed)))
108 if not isfinite(fitness)
or not isfinite(outcome):
109 raise ValueError(
"Every rollout must return finite scalar fitness and outcome.")
110 scores.append(fitness)
111 outcomes.append(outcome)
116 """Return the search archive after up to budget complete candidate measurements."""
117 if not callable(evaluate):
118 raise TypeError(
"evaluate must be callable.")
125 lambda genome: self.
_measure(genome, evaluate, seeds(),
"nb_rollouts"), budget=budget)
128 def audit(self, evaluate, *, rollouts):
129 """Return audit records in niche order, without writing measurements to the archive.
131 Every elite receives the same fixed seed panel, drawn independently
132 of search. Repeating an audit with the same size reuses that panel.
134 if not callable(evaluate):
135 raise TypeError(
"evaluate must be callable.")
136 count = _positive_int(rollouts,
"rollouts")
137 seeds = self.
_audit_seed.generate_state(count, dtype=np.uint64)
139 for niche, elite
in sorted(self.
archive.cells.items()):
140 fitness, descriptor = self.
_measure(elite.genome, evaluate, seeds,
"nb_audit_rollouts")
Report how an archive elite maps to the same geometry under independent rollouts.
Measure stochastic outcomes repeatedly and illuminate fixed distributional niches.
audit(self, evaluate, *, rollouts)
Reassess archived genomes on a common held-out seed panel.
_measure(self, genome, evaluate, seeds, counter)
optimise(self, evaluate, *, budget)
Spend a candidate budget, charging every attempted rollout separately.
Represent an empirical probability measure with equal mass per observation.
Draw parents from occupied medoid niches and mutate with caller-defined operators.