QDpy
Loading...
Searching...
No Matches
lucie.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Race a challenger against the incumbent in a fixed descriptor cell."""
7
8from dataclasses import dataclass
9from math import isfinite, log, pi, sqrt
10
11import numpy as np
12
13from qdpy.containers import CVTGrid, Grid
14from qdpy.phenotype import Features, Fitness, Individual
15from qdpy.tools import iso_line_dd
16
17from .modern import _positive_int, _variation_settings
18from .sampling import _rollout_seed
19
20__all__ = ["LUCIEMAPElites", "LUCIESearchStats"]
21
22
23
24@dataclass(frozen=True)
26 """Counters refer to an individual run call."""
27
28 evaluations: int
29 incumbent_evaluations: int
30 proposals: int
31 out_of_domain: int
32 certified_races: int
33 unresolved_races: int
34 replacements: int
35
36
37@dataclass(frozen=True)
38class _Arm:
39 genome: tuple
40 features: tuple
41 identifier: int
42 samples: int = 0
43 mean: float = 0.
44
45 def observe(self, quality):
46 count = self.samples + 1
47 return _Arm(self.genome, self.features, self.identifier,
48 count, self.mean + (quality - self.mean) / count)
49
50
51
52def _confidence(arm, delta):
53 # Spend delta across arms and across sample counts with two summable
54 # inverse-square schedules. The leading factor two is two-sided Hoeffding.
55 log_term = log(pi**4 / 18.) + 2 * log(arm.identifier) + 2 * log(arm.samples) - log(delta)
56 radius = sqrt(log_term / (2 * arm.samples))
57 return max(0., arm.mean - radius), min(1., arm.mean + radius)
58
59
60
62 """Assume deterministic descriptors and independent bounded fitness observations.
63
64 Race against an incumbent only within the challenger's predetermined
65 cell. Reuse the incumbent's earlier observations. Once the outsider's
66 upper bound is within epsilon of the leader's lower bound, the leader
67 is an epsilon-accurate choice under the confidence event. If the
68 rollout or pair budget ends first, use the empirical leader and
69 record an unresolved race. Exact ties retain the incumbent.
70
71 :param archive: Empty standalone best-only Grid or CVTGrid, with one
72 finite fitness interval covering the support of every observation.
73 Unweighted archives maximize fitness.
74 :param dimension: Real genome length.
75 :param delta: Total confidence error allowance across arms and sample counts.
76 :param epsilon: Additive fitness tolerance in original units.
77 :param initial_samples: Number of fitness observations for a new arm.
78 :param max_pairs: Maximum extra pairs per local race.
79 :param ind_domain: Shared finite, increasing genome bounds.
80 :param iso_sigma: Isotropic mutation scale.
81 :param line_sigma: Directional mutation scale.
82 :param seed: Private variation and evaluator seed.
83 """
84
85 def __init__(self, archive, dimension, *, delta=.05, epsilon=0., initial_samples=2,
86 max_pairs=16, ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0):
87 if (type(archive) not in (Grid, CVTGrid) or len(archive) or archive.parents
88 or archive.max_items_per_bin != 1 or archive.discard_random_on_bin_overload
89 or archive.fitness_domain is None or len(archive.fitness_domain) != 1
90 or archive.fitness_score_names or archive.features_score_names):
91 raise ValueError("Use an empty standalone scalar best-only Grid or CVTGrid.")
92 low, high = archive.fitness_domain[0]
93 span = high - low
94 weights = archive.fitness_weights
95 if weights is None:
96 weights = (1.,)
97 if (not 0. < span < np.inf or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0.
98 or not 0. < delta < 1. or not 0. <= epsilon <= span):
99 raise ValueError("Supply a finite fitness span, nonzero weight, delta in (0, 1), and epsilon within the span.")
100 self.archive = archive
101 self.dimension = _positive_int(dimension, "dimension")
102 self.initial_samples = _positive_int(initial_samples, "initial_samples")
103 self.max_pairs = _positive_int(max_pairs, "max_pairs")
104 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
105 if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
106 raise ValueError("Use a finite genome span.")
107 self._low, self._high, self._span = low, high, span
108 self._weights = tuple(weights)
109 self._maximizing = weights[0] > 0
110 self._epsilon, self._delta = epsilon / span, delta
111 self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
112 self.seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
113 self._rng = np.random.default_rng(self.seed)
114 self._evaluations = self._arms = 0
115
116 def _propose(self):
117 if not self.archive:
118 return tuple(self._rng.uniform(*self.ind_domain, size=self.dimension))
119 slots = self._rng.integers(len(self.archive), size=2)
120 return tuple(iso_line_dd(self.archive[int(slots[0])], self.archive[int(slots[1])],
121 iso_sigma=self.iso_sigma, line_sigma=self.line_sigma,
122 bounds=self.ind_domain, rng=self._rng))
123
124 def _observe(self, evaluate, arm):
125 seed = _rollout_seed(self.seed, 0, self._evaluations)
126 self._evaluations += 1
127 fitness = float(evaluate(arm.genome, seed))
128 if not self._low <= fitness <= self._high:
129 raise ValueError("Fitness observations must be finite and within the declared support.")
130 fraction = (fitness - self._low) / self._span
131 return arm.observe(fraction if self._maximizing else 1. - fraction)
132
133 def _select(self, incumbent, challenger):
134 keep = incumbent.mean >= challenger.mean
135 leader, outsider = (incumbent, challenger) if keep else (challenger, incumbent)
136 lower, _ = _confidence(leader, self._delta)
137 _, upper = _confidence(outsider, self._delta)
138 return leader, upper - lower <= self._epsilon
139
140 def _admit(self, winner, old=None):
141 quality = (self._low + self._span * winner.mean if self._maximizing
142 else self._high - self._span * winner.mean)
143 elite = Individual(winner.genome, fitness=Fitness((float(np.clip(quality, self._low, self._high)),),
144 weights=self._weights),
145 features=Features(winner.features))
146 elite._lucie_arm = winner
147 elite.scores["rollout_count"] = winner.samples
148 if old is not None:
149 self.archive.discard(old)
150 self.archive.add(elite)
151
152
158 def run(self, evaluate, descriptor, budget, *, proposal_limit=None):
159 """Use evaluate(genome, seed) for fitness and descriptor(genome) for a fixed cell."""
160 if not callable(evaluate) or not callable(descriptor):
161 raise TypeError("Supply callable evaluate and descriptor functions.")
162 budget = _positive_int(budget, "budget")
163 limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
164 start = self._evaluations
165 end = start + budget
166 incumbent_calls = proposals = outside = certified = unresolved = replacements = 0
167 while self._evaluations < end and proposals < limit:
168 proposals += 1
169 genome = self._propose()
170 features = tuple(map(float, descriptor(genome)))
171 if len(features) != len(self.archive.features_domain) or not all(map(isfinite, features)):
172 raise ValueError("Return a finite descriptor of the configured length.")
173 if not self.archive.in_bounds(features, self.archive.features_domain):
174 outside += 1
175 continue
176 cell = self.archive.index_grid(features)
177 front = self.archive.solutions[cell]
178 prior = front[0] if front else None
179 if prior is not None and tuple(prior) == genome:
180 revised = self._observe(evaluate, prior._lucie_arm)
181 incumbent_calls += 1
182 self._admit(revised, prior)
183 continue
184 self._arms += 1
185 challenger = _Arm(genome, features, self._arms)
186 for _ in range(min(self.initial_samples, end - self._evaluations)):
187 challenger = self._observe(evaluate, challenger)
188 if prior is None:
189 if self.archive.free >= 1:
190 self._admit(challenger)
191 continue
192
193 incumbent = prior._lucie_arm
194 winner, complete = self._select(incumbent, challenger)
195 for _ in range(self.max_pairs):
196 if complete or self._evaluations + 2 > end:
197 break
198 incumbent = self._observe(evaluate, incumbent)
199 challenger = self._observe(evaluate, challenger)
200 incumbent_calls += 1
201 winner, complete = self._select(incumbent, challenger)
202 certified += complete
203 unresolved += not complete
204 replacements += winner is challenger
205 if winner is challenger or winner is not prior._lucie_arm:
206 self._admit(winner, prior)
207
208 return LUCIESearchStats(self._evaluations - start, incumbent_calls, proposals, outside,
209 certified, unresolved, replacements)
Use paired confidence bounds to resolve local replacement under a rollout budget.
Definition lucie.py:61
_select(self, incumbent, challenger)
Definition lucie.py:133
run(self, evaluate, descriptor, budget, *, proposal_limit=None)
Spend an additional hard budget of scalar fitness calls.
Definition lucie.py:158
_admit(self, winner, old=None)
Definition lucie.py:140
_observe(self, evaluate, arm)
Definition lucie.py:124
Raw rollout costs and the outcomes of two-elite confidence races.
Definition lucie.py:25
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405