QDpy
Loading...
Searching...
No Matches
distribution_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Retain candidates by the distribution of a scalar outcome across rollouts."""
8
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13from scipy.stats import wasserstein_distance
14
15from .medoid_map_elites import MedoidArchive, MedoidElite, MedoidMAPElites
16from .modern import _positive_int
17
18__all__ = ["EmpiricalDistribution", "wasserstein_descriptor_distance", "DistributionMAPElites",
19 "DistributionAudit"]
20
21
22
23@dataclass(frozen=True, init=False)
25 """Store a nonempty sorted tuple of finite scalar observations.
26
27 Repeated values keep their multiplicity. The distance accepts
28 distributions with unequal sample counts.
29 """
30
31 samples: tuple[float, ...]
32
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)
38
39
40
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))
50
51
52
53@dataclass(frozen=True)
55 """Compare the search assignment and a held-out measurement of one elite.
56
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.
62 """
63
64 elite: MedoidElite
65 search_niche: int
66 audit_niche: int
67 fitness: float
68 descriptor: EmpiricalDistribution
69
70 @property
71 def stable(self):
72 """Return whether reassessment kept the elite in its original niche."""
73 return self.search_niche == self.audit_niche
74
75
76
78 """Use mean rollout fitness and the empirical distribution of scalar outcomes.
79
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.
86
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.
90 """
91
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)
99 self._rollout_rng = np.random.default_rng(search)
100 self.nb_rollouts = 0
101 self.nb_audit_rollouts = 0
102
103 def _measure(self, genome, evaluate, seeds, counter):
104 scores, outcomes = [], []
105 for seed in seeds:
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)
112 return float(np.mean(scores)), EmpiricalDistribution(outcomes)
113
114
115 def optimise(self, evaluate, *, budget):
116 """Return the search archive after up to budget complete candidate measurements."""
117 if not callable(evaluate):
118 raise TypeError("evaluate must be callable.")
119
120 def seeds():
121 for _ in range(self._rollouts):
122 yield self._rollout_rng.bit_generator.random_raw()
123
124 return super().optimise(
125 lambda genome: self._measure(genome, evaluate, seeds(), "nb_rollouts"), budget=budget)
126
127
128 def audit(self, evaluate, *, rollouts):
129 """Return audit records in niche order, without writing measurements to the archive.
130
131 Every elite receives the same fixed seed panel, drawn independently
132 of search. Repeating an audit with the same size reuses that panel.
133 """
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)
138 rows = []
139 for niche, elite in sorted(self.archive.cells.items()):
140 fitness, descriptor = self._measure(elite.genome, evaluate, seeds, "nb_audit_rollouts")
141 rows.append(DistributionAudit(elite, niche, self.archive.index(descriptor), fitness, descriptor))
142 return tuple(rows)
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.
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.