QDpy
Loading...
Searching...
No Matches
scenario_risk.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Common-scenario MAP-Elites with empirical conditional value-at-risk."""
7
8from collections import Counter
9from dataclasses import dataclass
10from math import fsum
11from random import Random
12
13import numpy as np
14
15from qdpy.containers import Grid, ParetoGrid
16from qdpy.phenotype import Features, Fitness, Individual
17from .modern import _positive_int
18from .offline import _empty_geometry
19from .task_search import _validate_grid
20
21__all__ = ["ScenarioRiskMAPElites", "ScenarioRiskStats", "ScenarioRiskAudit", "empirical_cvar"]
22
23
24def _probabilities(count, probabilities):
25 if not count:
26 raise ValueError("A scenario panel must be nonempty.")
27 if probabilities is None:
28 return np.full(count, 1. / count)
29 weights = np.asarray(probabilities, dtype=float)
30 if (weights.shape != (count,) or not np.isfinite(weights).all()
31 or (weights < 0.).any() or not weights.any()):
32 raise ValueError("Provide one nonnegative finite weight per scenario and positive total mass.")
33 weights = weights / weights.max()
34 return weights / weights.sum()
35
36
37def _tail(values, weights, fraction, maximize):
38 order = np.argsort(values if maximize else -values, kind="stable")
39 mass = weights[order]
40 before = np.r_[0., np.cumsum(mass[:-1])]
41 used = np.minimum(mass, np.maximum(fraction - before, 0.))
42 used /= fsum(used)
43 return fsum(float(value) * float(weight) for value, weight in zip(values[order], used, strict=True))
44
45
46
52def empirical_cvar(values, tail_fraction, *, maximize=True, probabilities=None) -> float:
53 """Use fractional mass at the cutoff, including for tied or weighted scenarios."""
54 values = np.asarray(values, dtype=float)
55 if (values.ndim != 1 or not np.isfinite(values).all() or not 0. < tail_fraction <= 1.
56 or type(maximize) is not bool):
57 raise ValueError("Use finite one-dimensional outcomes, a tail fraction in (0, 1], and Boolean maximize.")
58 weights = _probabilities(len(values), probabilities)
59 return _tail(values, weights, tail_fraction, maximize)
60
61
62
63@dataclass(frozen=True)
65 """A budget can have a remainder too short to compare another complete design."""
66
67 scenario_calls: int = 0
68 candidates: int = 0
69 archive_updates: int = 0
70 out_of_domain: int = 0
71
72
73
74@dataclass(frozen=True)
76 """The result records each candidate's mean, tail, and descriptor before archive truncation."""
77
78 archive: Grid
79 stats: ScenarioRiskStats
80 measurements: tuple[Individual, ...]
81
82
83
85 """Measure the same scenario panel for every design before archive admission.
86
87 Use mean performance, empirical CVaR, or a Pareto front with mean
88 and CVaR in that order. Average descriptors over the same panel with
89 the supplied weights. Report raw performance and propagate errors
90 when a scenario yields invalid data.
91
92 :param archive: Empty best-only Grid or CVTGrid, or a native two-objective ParetoGrid.
93 :param scenarios: Nonempty fixed sequence of scenario inputs.
94 :param initializer: Callable (rng) generating a design.
95 :param mutate: Callable (genome, rng) generating a new design.
96 :param tail_fraction: Worst probability mass used for CVaR.
97 :param objective: Mean, CVaR, or Pareto, specified in lowercase.
98 :param probabilities: Optional weights aligned with the scenario panel.
99 :param initial_samples: Number of proposals drawn from the initializer.
100 :param seed: Private selection, initialization, and variation seed.
101 """
102
103 def __init__(self, archive, scenarios, *, initializer, mutate, tail_fraction=.2, objective="cvar",
104 probabilities=None, initial_samples=16, seed=0):
105 if not callable(initializer) or not callable(mutate):
106 raise TypeError("Supply initializer and mutation callbacks.")
107 if objective not in ("mean", "cvar", "pareto") or not 0. < tail_fraction <= 1.:
108 raise ValueError("Use mean, cvar, or pareto and a tail fraction in (0, 1].")
109 if objective == "pareto":
110 if (not isinstance(archive, ParetoGrid) or len(archive.fitness_domain) != 2
111 or len(archive) or archive.parents
112 or np.sign(archive.fitness_weights[0]) != np.sign(archive.fitness_weights[1])):
113 raise ValueError("Use an empty two-objective ParetoGrid with matching directions.")
114 else:
115 _validate_grid(archive)
116 if archive.fitness_weights is None or archive.fitness_score_names or archive.features_score_names:
117 raise ValueError("Provide explicit fitness weights and native descriptors.")
118 self._maximize = archive.fitness_weights[0] > 0.
119 self.archive = archive
120 self._scenarios = tuple(scenarios)
121 self._weight = _probabilities(len(self._scenarios), probabilities)
122 self._initializer, self._mutate = initializer, mutate
123 self._tail_fraction, self._objective = tail_fraction, objective
124 self._initial = _positive_int(initial_samples, "initial_samples")
125 variation, training, audit = np.random.SeedSequence(seed).spawn(3)
126 self._rng = np.random.default_rng(variation)
127 self._truncation = Random(int(training.generate_state(1)[0]))
128 self._audit_seed = int(audit.generate_state(1)[0])
129 self._counts = Counter()
130
131 @property
132 def stats(self):
133 """Return cumulative scenario attempts and archive changes."""
134 return ScenarioRiskStats(**self._counts)
135
136 def _measure(self, evaluate, genome, scenarios, weights, archive, counts, truncation):
137 qualities, descriptors = [], []
138 dimension = len(archive.features_domain)
139 for scenario in scenarios:
140 counts["scenario_calls"] += 1
141 quality, features = evaluate(genome, scenario)
142 features = tuple(map(float, features))
143 quality = float(quality)
144 if len(features) != dimension or not np.isfinite((quality, *features)).all():
145 raise ValueError("Return finite scalar quality and descriptors consistent with the grid.")
146 qualities.append(quality)
147 descriptors.append(features)
148 mean = fsum(q * float(w) for q, w in zip(qualities, weights, strict=True))
149 tail = _tail(np.asarray(qualities), weights, self._tail_fraction, self._maximize)
150 features = tuple(fsum(x * float(w) for x, w in zip(column, weights, strict=True))
151 for column in zip(*descriptors, strict=True))
152 metrics = (mean, tail)
153 fitness = metrics if self._objective == "pareto" else (tail if self._objective == "cvar" else mean,)
154 candidate = Individual(genome, features=Features(features), fitness=Fitness(fitness, weights=archive.fitness_weights),
155 scores={"scenario_mean": mean, "scenario_cvar": tail, "scenario_count": len(scenarios)})
156 counts["candidates"] += 1
157 if (archive.in_bounds(fitness, archive.fitness_domain)
158 and archive.in_bounds(features, archive.features_domain)):
159 cell = archive.index_grid(features)
160 if archive.free >= 1 or archive.solutions[cell]:
161 before = archive.nb_added
162 if isinstance(archive, ParetoGrid):
163 archive._merge_fronts((candidate,), truncation_rng=truncation)
164 else:
165 archive.add(candidate)
166 counts["archive_updates"] += archive.nb_added - before
167 else:
168 counts["out_of_domain"] += 1
169 return candidate
170
171
175 def run(self, evaluate, budget) -> ScenarioRiskStats:
176 """Reuse the common panel and leave a partial panel unspent."""
177 if not callable(evaluate):
178 raise TypeError("Supply a callable evaluator.")
179 for _ in range(_positive_int(budget, "budget") // len(self._scenarios)):
180 if not self.archive or self._counts["candidates"] < self._initial:
181 genome = tuple(self._initializer(self._rng))
182 else:
183 fronts = [front for front in self.archive.solutions.values() if front]
184 front = fronts[int(self._rng.integers(len(fronts)))]
185 parent = tuple(front[int(self._rng.integers(len(front)))])
186 genome = tuple(self._mutate(parent, self._rng))
187 self._measure(evaluate, genome, self._scenarios, self._weight, self.archive, self._counts, self._truncation)
188 return self.stats
189
190
196 def audit(self, evaluate, scenarios, *, probabilities=None, budget=None) -> ScenarioRiskAudit:
197 """Reassign audited designs by measured behaviour while preserving the source archive."""
198 if not callable(evaluate):
199 raise TypeError("Supply a callable evaluator.")
200 scenarios = tuple(scenarios)
201 weights = _probabilities(len(scenarios), probabilities)
202 count = len(self.archive) if budget is None else _positive_int(budget, "budget") // len(scenarios)
203 report = _empty_geometry(self.archive)
204 costs = Counter()
205 truncation = Random(self._audit_seed)
206 measured = tuple(self._measure(evaluate, tuple(item), scenarios, weights, report, costs, truncation)
207 for item in tuple(self.archive)[:count])
208 return ScenarioRiskAudit(report, ScenarioRiskStats(**costs), measured)
An independently rescored archive and held-out measurement costs.
Compare designs on the same panel by mean, CVaR, or both.
ScenarioRiskAudit audit(self, evaluate, scenarios, *, probabilities=None, budget=None)
Remeasure current elites on a caller-supplied held-out panel.
ScenarioRiskStats run(self, evaluate, budget)
Search under an additional scenario-call budget.
_measure(self, evaluate, genome, scenarios, weights, archive, counts, truncation)
Count attempted scenarios and completed designs separately.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405