QDpy
Loading...
Searching...
No Matches
as_delta.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Adaptive repeats and depth-ranked delta comparison for noisy illumination."""
7
8from math import isfinite
9
10import numpy as np
11
12from qdpy.containers import CVTGrid, Grid
13from qdpy.phenotype import Features, Fitness, Individual
14from qdpy.tools import iso_line_dd
15
16from .modern import _positive_int, _variation_settings
17from .sampling import _fresh, _stage_archive
18from .uncertain import _Rollouts, _cell
19
20__all__ = ["ASDelta"]
21
22
23
24def _delta_preferred(candidate, incumbent, delta_f, delta_r):
25 fitness, reproducibility = candidate
26 previous_fitness, previous_reproducibility = incumbent
27 if candidate == incumbent:
28 return False
29 gain = fitness - previous_fitness
30 if gain >= delta_f:
31 return True
32 if gain >= 0. and reproducibility >= previous_reproducibility:
33 return True
34 return gain >= -delta_f and reproducibility - previous_reproducibility >= delta_r
35
36
37
38def _negative_mean_std(rows):
39 scales = np.max(np.abs(rows), axis=0)
40 normalized = rows / np.where(scales == 0., 1., scales)
41 spread = np.std(normalized, axis=0).clip(max=1.) * scales
42 return -float(np.sum(spread / len(spread)))
43
44
45
46class ASDelta:
47 """Maintain a preference-ordered depth in every occupied descriptor cell.
48
49 Refresh every incumbent once per generation before selecting new parents.
50 An offspring requires a complete initial repeat group. Failed refreshes
51 retain the last estimate and every attempted rollout counts. Rebuild the
52 rankings from refreshed measurements, including changes of niche. A
53 final generation needs room for all refreshes and one offspring group.
54
55 :param container: Empty standalone Grid or CVTGrid with one objective.
56 Its max_items_per_bin sets the depth. Leave it under the search's control.
57 :param budget: Total raw rollout attempts, including incumbent refreshes.
58 :param dimension: Number of bounded real decision variables.
59 :param delta_f: Fitness tolerance in raw fitness units.
60 :param delta_r: Reproducibility improvement required to accept a performance loss.
61 :param sampling_size: Maximum raw rollout attempts per generation. It must
62 allow a full archive refresh and at least one new candidate.
63 :param initial_samples: Number of repeated measurements for new candidates.
64 :param estimator: "mean" or "median" for both measurements, or a pair
65 selecting the fitness and descriptor estimators independently.
66 :param reproducibility: Optional callable taking the matrix of raw descriptors
67 and returning a finite scalar to maximize. Defaults to negative mean
68 population standard deviation across the descriptor coordinates.
69 :param ind_domain: Shared decision bounds.
70 :param iso_sigma: Independent Iso+LineDD noise scale.
71 :param line_sigma: Directional Iso+LineDD noise scale.
72 :param seed: Seed for variation and the independent rollout stream.
73 """
74
75 def __init__(self, container, budget, dimension, *, delta_f, delta_r,
76 sampling_size=128, initial_samples=2, estimator="median", reproducibility=None,
77 ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0):
78 if (type(container) not in (Grid, CVTGrid) or len(container) or container.parents
79 or len(container.fitness_domain) != 1 or not len(container.features_domain)
80 or container.fitness_score_names or container.features_score_names):
81 raise ValueError("Use an empty standalone scalar Grid or CVTGrid with direct measurements.")
82 weights = container.fitness_weights
83 if weights is not None and (len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0):
84 raise ValueError("Use one finite nonzero fitness weight.")
85 if not all(0 <= value < np.inf for value in (delta_f, delta_r)):
86 raise ValueError("Both delta tolerances must be finite and nonnegative.")
87 reducers = {"mean": np.mean, "median": np.median}
88 estimators = (estimator, estimator) if isinstance(estimator, str) else tuple(estimator)
89 if len(estimators) != 2 or any(name not in reducers for name in estimators):
90 raise ValueError("Choose 'mean' or 'median' for each estimator.")
91 if reproducibility is not None and not callable(reproducibility):
92 raise TypeError("reproducibility must be callable.")
93 self.container = container
94 self.budget = _positive_int(budget, "budget")
95 self.dimension = _positive_int(dimension, "dimension")
96 self.sampling_size = _positive_int(sampling_size, "sampling_size")
97 self.initial_samples = _positive_int(initial_samples, "initial_samples")
98 if (self.sampling_size < container.capacity + self.initial_samples
99 or not 2 <= self.initial_samples <= self.budget):
100 raise ValueError("Fit all refreshes and a new group of at least two rollouts within the limits.")
101 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
102 if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
103 raise ValueError("Use finite decision spans.")
104 self.delta_f, self.delta_r = delta_f, delta_r
105 self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
106 self._direction = -1. if weights is None else float(np.sign(weights[0]))
107 self._fitness_estimator, self._descriptor_estimator = (reducers[name] for name in estimators)
108 self._reproducibility = _negative_mean_std if reproducibility is None else reproducibility
109 self.seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
110 self._rng = np.random.default_rng(self.seed)
111 self._fronts = {}
112 self.nb_evaluations = self.failed_evaluations = self.completed_candidates = 0
113 self.incumbent_evaluations = self.offspring_evaluations = 0
114
115
116 def front(self, cell):
117 """Return the most-to-least preferred members of one descriptor cell."""
118 return tuple(self._fronts.get(cell, ()))
119
120 def _measurement(self, candidate, observations):
121 rows = np.asarray([(*obs.fitness, *obs.features) for obs in observations], dtype=float)
122 scale = np.max(np.abs(rows), axis=0)
123 normalized = rows / np.where(scale == 0., 1., scale)
124 fitness = self._fitness_estimator(normalized[:, 0]) * scale[0]
125 descriptors = self._descriptor_estimator(normalized[:, 1:], axis=0) * scale[1:]
126 score = float(self._reproducibility(rows[:, 1:]))
127 if not isfinite(score):
128 raise ValueError("The reproducibility estimator must return a finite scalar.")
129 measured = Individual(candidate, name=candidate.name,
130 fitness=Fitness((fitness,), weights=(self._direction,)),
131 features=Features(descriptors))
132 measured.elapsed = sum(row.elapsed for row in observations)
133 measured._observations = observations
134 measured.scores.update(reproducibility=score, rollout_count=len(rows))
135 return measured
136
137 def _scores(self, item):
138 return self._direction * item.fitness.values[0], item.scores["reproducibility"]
139
140 def _cascade(self, fronts, seen, candidate):
141 cell = _cell(self.container, candidate)
142 genome = tuple(candidate)
143 if (genome in seen or cell is None
144 or not self.container.in_bounds(candidate.fitness.values, self.container.fitness_domain)):
145 return
146 seen.add(genome)
147 front = fronts.setdefault(cell, [])
148 for i, incumbent in enumerate(front):
149 if _delta_preferred(self._scores(candidate), self._scores(incumbent), self.delta_f, self.delta_r):
150 front[i], candidate = candidate, incumbent
151 if len(front) < self.container.max_items_per_bin:
152 front.append(candidate)
153
154 def _propose(self, count, fronts):
155 occupied = tuple(fronts.values())
156 if not occupied:
157 return [Individual(self._rng.uniform(*self.ind_domain, self.dimension)) for _ in range(count)]
158
159 def parent():
160 return occupied[self._rng.integers(len(occupied))][0]
161
162 return [Individual(iso_line_dd(parent(), parent(), iso_sigma=self.iso_sigma,
163 line_sigma=self.line_sigma, bounds=self.ind_domain, rng=self._rng))
164 for _ in range(count)]
165
166 def _publish(self, fronts):
167 staged = _stage_archive(self.container)
168 retained = {id(item) for front in fronts.values() for item in front}
169 for item in self.container:
170 if id(item) not in retained:
171 staged.discard(item)
172 previous = {id(item) for item in staged}
173 for cell, front in fronts.items():
174 for item in front:
175 if id(item) not in previous:
176 staged._add_to_grid(item, cell, False)
177 self.container.__dict__.update(staged.__dict__)
178 self._fronts = fronts
179
180
181 def optimise(self, evaluate, *, executor=None, seeded=False):
182 """Supply evaluate(candidate) or evaluate(candidate, seed) with seeded=True."""
183 if self.nb_evaluations or len(self.container):
184 raise RuntimeError("Construct a fresh ASDelta search and archive for each run.")
185 if not callable(evaluate):
186 raise TypeError("evaluate must be callable.")
187 rollouts = _Rollouts(self.container, evaluate, executor, self.seed, seeded=seeded)
188 try:
189 while True:
190 incumbents = [entry for front in self._fronts.values() for entry in front]
191 slots = min(self.sampling_size, self.budget - rollouts.attempted)
192 count = (slots - len(incumbents)) // self.initial_samples
193 if count < 1:
194 break
195 fronts, seen = {}, set()
196 self.incumbent_evaluations += len(incumbents)
197 refreshed = rollouts.evaluate_groups([(item, 1) for item in incumbents])
198 for item, observations in zip(incumbents, refreshed, strict=True):
199 revised = self._measurement(_fresh(item), item._observations + observations) if observations else item
200 self._cascade(fronts, seen, revised)
201
202 offspring = self._propose(count, fronts)
203 self.offspring_evaluations += count * self.initial_samples
204 measured = rollouts.evaluate_groups([(item, self.initial_samples) for item in offspring])
205 for item, observations in zip(offspring, measured, strict=True):
206 if len(observations) == self.initial_samples:
207 self.completed_candidates += 1
208 self._cascade(fronts, seen, self._measurement(item, observations))
209 self._publish(fronts)
210 finally:
211 self.nb_evaluations, self.failed_evaluations = rollouts.attempted, rollouts.failed
212 return self.container
Apply adaptive Archive-Sampling with bounded cascade replacement.
Definition as_delta.py:46
optimise(self, evaluate, *, executor=None, seeded=False)
Run ordered raw evaluations and return the native reporting grid.
Definition as_delta.py:181
_cascade(self, fronts, seen, candidate)
Definition as_delta.py:140
_measurement(self, candidate, observations)
Definition as_delta.py:120
_propose(self, count, fronts)
Definition as_delta.py:154
front(self, cell)
Return the live entries in cascade order, with the preferred elite first.
Definition as_delta.py:116
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405