22def _novelty_scores(population, history, embedding, neighbors):
32 scores = np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
70 """Keep independent bounded populations and novelty histories.
72 FINS chooses feasible parents by novelty and infeasible parents by
73 low total positive violation. FI2NS uses novelty in both populations.
74 An offspring enters the pool appropriate to its measured constraints.
75 Only feasible measurements are offered to the independent native grid.
77 :param archive: Empty parentless best-only Grid or CVTGrid.
78 :param initializer: Callable (rng) returning an immutable genome sequence.
79 :param mutate: Callable (genome, rng) returning a new genome sequence.
80 :param mode: FINS or FI2NS, specified as "fins" or "fi2ns".
81 :param population_size: Capacity of each breeding population.
82 :param history_size: Number of distinct recent genomes per novelty history.
83 :param neighbors: Nearest-neighbor count for novelty.
84 :param feasible_parent_probability: Fraction of births allocated to feasible
85 breeders when both populations are available.
86 :param initial_samples: Number of initial proposals from initializer.
87 :param seed: Seed for variation, selection, and evaluation calls.
90 def __init__(self, archive, *, initializer, mutate, mode="fins", population_size=32,
91 history_size=128, neighbors=5, feasible_parent_probability=.5, initial_samples=16, seed=0):
92 _validate_grid(archive)
93 if not callable(initializer)
or not callable(mutate):
94 raise TypeError(
"Supply initializer and mutate callbacks.")
95 if mode
not in (
"fins",
"fi2ns")
or not 0 <= feasible_parent_probability <= 1.:
96 raise ValueError(
"Use fins or fi2ns and a parent probability between zero and one.")
100 self.
_capacity = _positive_int(population_size,
"population_size")
101 self.
_neighbors = _positive_int(neighbors,
"neighbors")
102 self.
_initial = _positive_int(initial_samples,
"initial_samples")
103 memory = _positive_int(history_size,
"history_size")
105 self.
_history = (deque(maxlen=memory), deque(maxlen=memory))
106 rng, evaluations = np.random.SeedSequence(seed).spawn(2)
107 self.
_rng = np.random.default_rng(rng)
108 self.
_evaluation_seed = int(evaluations.generate_state(1, dtype=np.uint64)[0])
114 """Return cumulative measured search costs and outcomes."""
119 """Return immutable active feasible genomes."""
120 return tuple(row.genome
for row
in self.
_groups[1])
124 """Return immutable active infeasible genomes."""
125 return tuple(row.genome
for row
in self.
_groups[0])
127 def _scores(self, group):
128 population = self.
_groups[group]
129 if group == 0
and self.
_mode ==
"fins":
130 return -np.asarray([row.violation
for row
in population])
131 return _novelty_scores(population, self.
_history[group],
lambda row: row.descriptor, self.
_neighbors)
134 infeasible, feasible = self.
_groups
137 group = int(bool(feasible)
and (
not infeasible
or self.
_rng.random() < self.
_probability))
139 return (group, _tournament(pool, self.
_scores(group), self.
_rng))
if pool
else (
None,
None)
141 def _candidate(self, genome, descriptor, violation, residuals):
142 return _Candidate(genome, descriptor, violation)
148 def run(self, evaluate, budget) -> FeasibleNoveltyStats:
149 """Use residuals at or below zero for feasible admission and propagate invalid evaluations."""
150 if not callable(evaluate):
151 raise TypeError(
"Supply a callable evaluator.")
152 for _
in range(_positive_int(budget,
"budget")):
153 origin, parent = self.
_parent()
156 attempt = self.
_counts[
"evaluations"]
157 self.
_counts[
"evaluations"] += 1
158 fitness, descriptors, residuals = evaluate(genome, _rollout_seed(self.
_evaluation_seed, 0, attempt))
159 residuals = tuple(map(float, residuals))
160 if (
not residuals
or not np.isfinite(residuals).all()
162 raise ValueError(
"Return a fixed nonempty vector of finite residuals.")
164 violation = fsum(max(0., value)
for value
in residuals)
165 measurement = _measurement(self.
archive, ((fitness,), descriptors), genome)
166 measured, _ = measurement
167 group = int(violation == 0.)
169 self.
_counts[
"feasible_evaluations"] += 1
173 self.
_counts[
"feasible_from_infeasible"] += 1
175 _offer(self.
archive, measurement)
178 self.
_counts[
"infeasible_from_feasible"] += 1
181 if any(row.genome == genome
for row
in pool):
183 row = self.
_candidate(genome, tuple(self.
archive.get_ind_features(measured)), violation, residuals)
187 pool.pop(len(pool) - 1 - int(scores[::-1].argmin()))
188 if group
or self.
_mode ==
"fi2ns":
189 _remember(self.
_history[group], row)