55 """Maintain a simulator repertoire with occasional measurements on a target system.
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.
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.
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.")
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")
88 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
98 """Return the current repertoire with simulated quality and descriptors."""
103 """Return the last selected breeding population."""
108 """Return measured simulator–target pairs used for fitting."""
113 """Return attempts and failures by evaluation source."""
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)
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)
133 def _transfer(self, evaluate_target, pool):
136 result = evaluate_target(row.genome, int(self.
_target_rng.integers(2**32)))
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.")
147 self.
_model = NuSVR(kernel=
"linear").fit(
148 [item.source.descriptor
for item
in examples], [item.error
for item
in examples])
151 def _prefer(self, row, incumbent, errors):
152 error, existing = errors[row.evaluation_id], errors[incumbent.evaluation_id]
155 return error < existing
157 def _offer(self, row, novelty, errors):
161 if any(old.evaluation_id == row.evaluation_id
for old
in self.
_archive):
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:
170 def _commit(self, evaluate_target, targets_remaining):
173 pool = tuple({row.evaluation_id: row
for row
in (*candidates, *self.
_archive)}.values())
177 errors = {row.evaluation_id: error
for row, error
in
178 zip(pool, self.
predict_error(row.descriptor
for row
in pool))}
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.")
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)
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.")
214 for _
in range(simulations):
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.")
A measured simulation candidate with an immutable identifier.
run(self, simulate, simulation_budget, *, evaluate_target=None, target_budget=0)
Run simulation and optional target evaluations with independent attempt caps.