QDpy
Loading...
Searching...
No Matches
tbr_evolution.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Discover locally good behaviors while learning the source-to-target descriptor error."""
7
8from dataclasses import dataclass
9from math import dist, fsum, isfinite
10
11import numpy as np
12from sklearn.svm import NuSVR
13
14from ._population import _attempt_budget, _finite_vector, _nsga_order, _tournament
15from .modern import _positive_int
16
17__all__ = ["TBREvolution", "TBREntry", "TBRTransfer", "TBRStats"]
18
19
20
21@dataclass(frozen=True)
23 """Store predicted-system measurements and the simulator attempt ID."""
24
25 genome: tuple
26 quality: float
27 descriptor: tuple[float, ...]
28 evaluation_id: int
29
30
31
32@dataclass(frozen=True)
34 """Record simulator output, target output, and observed Euclidean error."""
35
36 source: TBREntry
37 target_descriptor: tuple[float, ...]
38 error: float
39
40
41
42@dataclass(frozen=True)
44 """Count attempts at each fidelity, failed calls, and committed generations."""
45
46 simulation_evaluations: int
47 target_evaluations: int
48 simulation_failures: int
49 target_failures: int
50 generations: int
51
52
53
55 """Maintain a simulator repertoire with occasional measurements on a target system.
56
57 Periodically sample one candidate from the combined population and
58 repertoire, observe its target descriptor, and update a linear
59 nu-SVR discrepancy model. Novelty and local quality and error ranks
60 determine NSGA-II survival. A locally competing archive candidate
61 wins on quality when both errors meet the transfer threshold. If
62 either misses that threshold, the lower predicted error wins.
63
64 :param sample: Callable (rng) returning a genome iterable.
65 :param mutate: Callable (parent_genome, rng) returning an offspring.
66 :param population_size: Initial and offspring batch size and survivor capacity.
67 :param neighbors: Number of neighbors in the population and repertoire union.
68 :param novelty_threshold: Novelty needed to enter without replacing a neighbor.
69 :param transfer_threshold: Maximum acceptable predicted target descriptor error.
70 :param transfer_period: Number of completed simulator batches between transfer attempts.
71 :param maximize: Prefer larger quality when True and smaller quality otherwise.
72 :param seed: Random seed for variation, transfer selection, and both evaluators.
73 """
74
75 def __init__(self, *, sample, mutate, population_size=24, neighbors=15, novelty_threshold=.1,
76 transfer_threshold=.2, transfer_period=4, maximize=True, seed=0):
77 if not callable(sample) or not callable(mutate):
78 raise TypeError("sample and mutate must be callable.")
79 if not 0 <= novelty_threshold < np.inf or not 0 <= transfer_threshold < np.inf:
80 raise ValueError("Thresholds must be finite and nonnegative.")
81 self._sample, self._mutate = sample, mutate
82 self._size = _positive_int(population_size, "population_size")
83 self._neighbors = _positive_int(neighbors, "neighbors")
84 self._period = _positive_int(transfer_period, "transfer_period")
85 self._novelty, self._threshold = novelty_threshold, transfer_threshold
86 self._direction = 1. if maximize else -1.
87 self._variation, self._select_target, self._simulation_rng, self._target_rng = map(
88 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
89 self._archive, self._transfers, self._children = [], [], []
90 self._population, self._keys = (), ()
91 self._model = None
92 self._descriptor_size = None
93 self._pending = self._simulations = self._targets = self._sim_failures = self._target_failures = 0
94 self._generations = 0
95
96 @property
97 def archive(self):
98 """Return the current repertoire with simulated quality and descriptors."""
99 return tuple(self._archive)
100
101 @property
102 def population(self):
103 """Return the last selected breeding population."""
104 return self._population
105
106 @property
107 def transfers(self):
108 """Return measured simulator–target pairs used for fitting."""
109 return tuple(self._transfers)
110
111 @property
112 def stats(self):
113 """Return attempts and failures by evaluation source."""
114 return TBRStats(self._simulations, self._targets, self._sim_failures,
116
117
120 def predict_error(self, descriptors):
121 """Use an optimistic zero before transfer data and the observed constant for one pair."""
122 points = np.asarray([_finite_vector(row, "Simulated descriptor", self._descriptor_size)
123 for row in descriptors], dtype=float)
124 if not len(points):
125 return np.empty(0)
126 if self._model is not None:
127 values = self._model.predict(points)
128 if not np.isfinite(values).all():
129 raise ValueError("The transfer estimator overflowed. Rescale the descriptor space.")
130 return np.maximum(0., values)
131 return np.full(len(points), self._transfers[0].error if self._transfers else 0.)
132
133 def _transfer(self, evaluate_target, pool):
134 row = pool[int(self._select_target.integers(len(pool)))]
135 self._targets += 1
136 result = evaluate_target(row.genome, int(self._target_rng.integers(2**32)))
137 if result is None:
138 self._target_failures += 1
139 return
140 descriptor = _finite_vector(result, "Target descriptor", self._descriptor_size)
141 error = dist(row.descriptor, descriptor)
142 if not isfinite(error):
143 raise ValueError("The measured target discrepancy is outside the representable range.")
144 record = TBRTransfer(row, descriptor, error)
145 if self._transfers:
146 examples = [*self._transfers, record]
147 self._model = NuSVR(kernel="linear").fit(
148 [item.source.descriptor for item in examples], [item.error for item in examples])
149 self._transfers.append(record)
150
151 def _prefer(self, row, incumbent, errors):
152 error, existing = errors[row.evaluation_id], errors[incumbent.evaluation_id]
153 if max(error, existing) <= self._threshold:
154 return self._direction * row.quality > self._direction * incumbent.quality
155 return error < existing
156
157 def _offer(self, row, novelty, errors):
158 if not self._archive:
159 self._archive.append(row)
160 return
161 if any(old.evaluation_id == row.evaluation_id for old in self._archive):
162 return
163 distances = [dist(row.descriptor, incumbent.descriptor) for incumbent in self._archive]
164 nearest = int(np.argmin(distances))
165 if distances[nearest] > 0. and novelty > self._novelty:
166 self._archive.append(row)
167 elif self._prefer(row, self._archive[nearest], errors):
168 self._archive[nearest] = row
169
170 def _commit(self, evaluate_target, targets_remaining):
171 candidates = self._population + tuple(self._children)
172 # Candidates can also be archived. Give each observation one vote.
173 pool = tuple({row.evaluation_id: row for row in (*candidates, *self._archive)}.values())
174 if pool and targets_remaining and (self._generations + 1) % self._period == 0:
175 self._transfer(evaluate_target, pool)
176 if candidates:
177 errors = {row.evaluation_id: error for row, error in
178 zip(pool, self.predict_error(row.descriptor for row in pool))}
179 scores = []
180 for row in candidates:
181 neighbors = sorted((dist(row.descriptor, other.descriptor), other.evaluation_id, other)
182 for other in pool if other.evaluation_id != row.evaluation_id)[:self._neighbors]
183 novelty = fsum(distance / len(neighbors) for distance, _, _ in neighbors)
184 if not isfinite(novelty):
185 raise ValueError("Novelty is outside the representable range. Rescale descriptors.")
186 local_quality = -sum(self._direction * other.quality > self._direction * row.quality
187 for _, _, other in neighbors)
188 local_transfer = -sum(errors[other.evaluation_id] < errors[row.evaluation_id]
189 for _, _, other in neighbors)
190 scores.append((novelty, local_quality, local_transfer))
191 for row, score in zip(candidates, scores):
192 self._offer(row, score[0], errors)
193 survivors, keys = _nsga_order(np.asarray(scores, dtype=float), self._size)
194 self._population = tuple(candidates[i] for i in survivors)
195 self._keys = keys
196 self._generations += 1
197 self._children.clear()
198 self._pending = 0
199
200
206 def run(self, simulate, simulation_budget, *, evaluate_target=None, target_budget=0):
207 """Spend simulator attempts and skip scheduled transfers when the target budget is exhausted."""
208 simulations, targets = _attempt_budget(simulation_budget), _attempt_budget(target_budget)
209 if targets and not callable(evaluate_target):
210 raise TypeError("A positive target budget requires an evaluate_target callback.")
211 limit = self._targets + targets
212 if self._pending == self._size:
213 self._commit(evaluate_target, limit - self._targets)
214 for _ in range(simulations):
215 if self._population:
216 parent = _tournament(self._population, self._keys, self._variation)
217 genome = tuple(self._mutate(parent.genome, self._variation))
218 else:
219 genome = tuple(self._sample(self._variation))
220 self._simulations += 1
221 result = simulate(genome, int(self._simulation_rng.integers(2**32)))
222 if result is None:
223 self._sim_failures += 1
224 else:
225 quality, descriptor = result
226 values = _finite_vector(descriptor, "Simulated descriptor", self._descriptor_size)
227 if not isfinite(quality):
228 raise ValueError("Simulation quality must be finite.")
229 self._descriptor_size = len(values)
230 self._children.append(TBREntry(genome, float(quality), values, self._simulations))
231 self._pending += 1
232 if self._pending == self._size:
233 self._commit(evaluate_target, limit - self._targets)
234 return self.stats
A measured simulation candidate with an immutable identifier.
Breed by novelty, local quality, and local predicted transferability.
run(self, simulate, simulation_budget, *, evaluate_target=None, target_budget=0)
Run simulation and optional target evaluations with independent attempt caps.
_transfer(self, evaluate_target, pool)
predict_error(self, descriptors)
Predict Euclidean descriptor discrepancy with the current transfer data.
_prefer(self, row, incumbent, errors)
_commit(self, evaluate_target, targets_remaining)
Keep simulator and target costs independently visible.
One paired source/target measurement used to fit the discrepancy model.