23 """Search and replay measured designs under inclusive score bounds.
25 :param archive: Empty parentless, best-only Grid or CVTGrid with a
26 single objective and native fitness and descriptors.
27 :param score_names: Names of the finite scalar measurements returned
28 by every successful evaluation, including currently unused scores.
29 :param constraints: Mapping from score names to (lower, upper). Use
30 None for an open end. Omit a name to remove its constraint.
31 :param history_size: Number of recent valid measurements to remember
32 alongside the live elites. Zero keeps only the live elites.
33 :param propose: Callback (rng) returning an immutable hashable genome.
34 :param mutate: Callback (parent_genome, rng) returning an offspring.
35 :param seed: Seed for proposal and parent selection.
38 def __init__(self, archive, *, score_names, constraints, history_size=1024,
39 propose, mutate, seed=0):
40 _validate_grid(archive)
41 if archive.fitness_score_names
or archive.features_score_names:
42 raise ValueError(
"Supply a grid with native fitness and descriptors.")
43 names = (score_names,)
if isinstance(score_names, str)
else tuple(score_names)
44 if (
not names
or any(
not isinstance(name, str)
or not name
for name
in names)
45 or len(set(names)) != len(names)):
46 raise ValueError(
"Use distinct nonempty score names.")
47 if not callable(propose)
or not callable(mutate):
48 raise TypeError(
"Supply callable proposal and mutation operators.")
51 self.
_history = deque(maxlen=index(history_size))
52 if archive.fitness_weights
is None:
53 archive._set_fitness_weights((1.,))
56 self.
_rng = np.random.default_rng(seed)
62 """Return a copy of the active score bounds."""
65 def _validate_constraints(self, constraints):
66 if not isinstance(constraints, Mapping)
or constraints.keys() - self.
_score_names:
67 raise ValueError(
"Constrain only declared measurement names.")
69 for key, (lower, upper)
in constraints.items():
70 lower =
None if lower
is None else float(lower)
71 upper =
None if upper
is None else float(upper)
72 if ((lower
is not None and not isfinite(lower))
73 or (upper
is not None and not isfinite(upper))
74 or (lower
is not None and upper
is not None and lower > upper)):
75 raise ValueError(
"Constraint bounds must be ordered and finite or None.")
76 bounds[key] = lower, upper
80 def _feasible(candidate, constraints):
81 return all((lower
is None or candidate.scores[name] >= lower)
82 and (upper
is None or candidate.scores[name] <= upper)
83 for name, (lower, upper)
in constraints.items())
87 """Apply new bounds to live and remembered designs and return the archive."""
92 eligible = {elite[0]: (elite, archive.index_grid(elite))
for elite
in archive}
93 eligible.update((candidate[0], (candidate, cell))
for candidate, cell
in self.
_history)
94 feasible = [pair
for pair
in eligible.values()
if self.
_feasible(pair[0], bounds)]
95 direction = np.sign(archive.fitness_weights[0])
96 feasible.sort(key=
lambda pair: direction * pair[0].fitness.values[0], reverse=
True)
98 for measurement
in feasible:
99 _offer(archive, measurement)
104 def run(self, evaluate, *, budget):
105 """Evaluate new genomes and return the live archive.
107 Return (scalar fitness, descriptors, scores) from evaluate(genome).
108 Scores must contain every declared measurement. Return None to report
109 a failed attempt. Use stable measurements for repeated genomes.
111 for _
in range(_positive_int(budget,
"budget")):
119 result = evaluate(genome)
123 fitness, descriptors, measured = result
124 if not isinstance(measured, Mapping)
or self.
_score_names != measured.keys():
125 raise ValueError(
"Return exactly the declared scores for every measured genome.")
126 scores = {name: float(value)
for name, value
in measured.items()}
127 if not all(map(isfinite, scores.values())):
128 raise ValueError(
"Constraint measurements must be finite.")
129 candidate, cell = _measurement(self.
archive, ((fitness,), descriptors), (genome,))
132 candidate.scores.update(scores)
133 measurement = (candidate, cell)
136 _offer(self.
archive, measurement)