61 """Run novelty search with a queue of distinct rewarding discoveries.
63 Exploratory offspring compete with the existing population on Euclidean
64 k-nearest-neighbour novelty. A discovery above reward_threshold seeds
65 a Gaussian emitter in its first rewarding cell. During exploitation,
66 bootstrap the most novel queued discovery, then select qualified
67 emitters on the novelty and improvement Pareto front. Only positive
68 bootstrap improvement qualifies an emitter. Novel emitter offspring
69 also enter the exploration memory. The reward grid stores measured
70 rewards independently of novelty selection.
72 :param archive: Empty, parentless, best-only Grid or CVTGrid with one maximized reward.
73 :param dimension: Genome length.
74 :param ind_domain: Shared inclusive bounds on genome coordinates.
75 :param reward_threshold: Reward must exceed this value to be stored or seed an emitter.
76 :param population_size: Maximum exploration population.
77 :param novelty_capacity: Maximum retained novelty records.
78 :param novelty_neighbors: Neighbours used for descriptor novelty.
79 :param chunk_size: Calls allotted to each consecutive phase when both can run.
80 :param exploration_sigma: Exploration mutation scale as a fraction of the genome interval.
81 :param emitter_sigma: Local mutation scale as a fraction of the genome interval.
82 :param emitter_size: Maximum reward-selected parents per emitter.
83 :param bootstrap_calls: Calls during a local probe, before testing for improvement.
84 :param stagnation_calls: Consecutive calls without a new best reward before retiring an emitter.
85 :param seed: Private seed for proposals, phase choices, and evaluations.
88 def __init__(self, archive, dimension, *, ind_domain=(0., 1.), reward_threshold=0.,
89 population_size=24, novelty_capacity=256, novelty_neighbors=10, chunk_size=32,
90 exploration_sigma=.15, emitter_sigma=.03, emitter_size=4, bootstrap_calls=8,
91 stagnation_calls=30, seed=0):
92 if (type(archive)
not in (Grid, CVTGrid)
or len(archive)
or archive.parents
93 or archive.max_items_per_bin != 1
or archive.discard_random_on_bin_overload
94 or archive.features_score_names
or archive.fitness_score_names
95 or len(archive.fitness_domain
or ()) != 1
or len(archive.fitness_weights
or ()) != 1
96 or not 0 < archive.fitness_weights[0] < np.inf):
97 raise ValueError(
"Use an empty, parentless best-only grid with one maximized reward.")
98 if not (np.isfinite(reward_threshold)
and 0 < emitter_sigma < np.inf
99 and 0 < exploration_sigma < np.inf):
100 raise ValueError(
"Use a finite reward threshold and positive finite mutation scales.")
102 self.
dimension = _positive_int(dimension,
"dimension")
103 self.
_bounds = _bounds(ind_domain)
107 raise ValueError(
"The scaled mutation standard deviations must be positive and finite.")
109 self.
_neighbors = _positive_int(novelty_neighbors,
"novelty_neighbors")
110 self.
_chunk = _positive_int(chunk_size,
"chunk_size")
111 self.
_emitter_size = _positive_int(emitter_size,
"emitter_size")
113 self.
_stagnation = _positive_int(stagnation_calls,
"stagnation_calls")
115 self.
_rng = np.random.default_rng(seed)
116 self.
_rollouts = np.random.default_rng(np.random.SeedSequence(seed).spawn(1)[0])
117 self.
_memory = deque(maxlen=_positive_int(novelty_capacity,
"novelty_capacity"))
123 self.
_counts = dict(exploration_evaluations=0, bootstrap_evaluations=0, emitter_evaluations=0,
124 failed_evaluations=0, reward_updates=0, emitters_started=0)
128 """Return the bounded memory of measured novelty discoveries."""
133 """Return the current novelty-selected breeding population."""
138 """Return cumulative search costs since construction."""
141 def _novelty(self, rows, reference):
143 return np.zeros(len(rows))
144 distances = cdist([row.descriptor
for row
in rows], [row.descriptor
for row
in reference])
145 by_id = {id(row): i
for i, row
in enumerate(reference)}
146 for i, row
in enumerate(rows):
148 distances[i, by_id[id(row)]] = np.inf
150 nearest = np.partition(distances, count - 1, axis=1)[:, :count]
151 finite = np.isfinite(nearest)
152 return np.where(finite, nearest, 0.).sum(axis=1) / np.maximum(1, finite.sum(axis=1))
154 def _reference(self):
157 def _measure(self, evaluate, parent, scale, phase):
159 np.clip(np.asarray(parent.genome) + self.
_rng.normal(0., scale, self.
dimension), *self.
_bounds))
160 genome = tuple(map(float, point))
163 measurement = evaluate(genome, int(self.
_rollouts.integers(2**32)))
164 if measurement
is None:
165 self.
_counts[
"failed_evaluations"] += 1
167 reward, descriptor = measurement
168 reward, descriptor = float(reward), np.asarray(descriptor, dtype=float)
169 if (
not np.isfinite(reward)
or descriptor.shape != (len(self.
archive.features_domain),)
170 or not np.isfinite(descriptor).all()):
171 raise ValueError(
"Return a finite scalar reward and a descriptor matching the grid, or None.")
172 elite =
SereneElite(genome, reward, tuple(map(float, descriptor)))
177 if (
not self.
archive.in_bounds(elite.descriptor, self.
archive.features_domain)
178 or not self.
archive.in_bounds((reward,), self.
archive.fitness_domain)):
180 cell = self.
archive.index_grid(elite.descriptor)
182 previous = self.
archive.nb_added
184 features=
Features(elite.descriptor)))
185 self.
_counts[
"reward_updates"] += self.
archive.nb_added - previous
188 def _explore(self, evaluate):
194 if cell
is not None and cell
not in self.
_discovered:
195 if cell
not in self.
_queued or row.reward > self.
_queued[cell].reward:
198 reference = tuple({id(item): item
for item
in (*pool, *self.
_memory)}.values())
199 scores = self.
_novelty(pool, reference)
205 def _select_emitter(self):
207 cells, rows = zip(*self.
_queued.items())
210 i = int(np.argmax(self.
_novelty(rows, reward_reference)))
212 row = self.
_queued.pop(cells[i])
214 self.
_counts[
"emitters_started"] += 1
215 if self.
_probe is not None:
217 scores = np.asarray([(emitter.novelty, emitter.improvement)
for emitter
in self.
_active])
218 dominates = (scores[:,
None] >= scores).all(axis=2) & (scores[:,
None] > scores).any(axis=2)
219 front = np.flatnonzero(~dominates.any(axis=0))
222 def _exploit(self, evaluate):
224 probing = emitter
is self.
_probe
225 parent = emitter.population[self.
_rng.integers(len(emitter.population))]
226 best = emitter.population[0].reward
228 "bootstrap_evaluations" if probing
else "emitter_evaluations")
230 emitter.population.append(row)
231 emitter.population.sort(key=
lambda item: item.reward, reverse=
True)
235 gain = emitter.population[0].reward - best
237 emitter.improvement += gain
240 if emitter.improvement > 0.:
244 emitter.improvement = .9 * emitter.improvement + .1 * gain
245 emitter.stalls = 0
if gain > 0.
else emitter.stalls + 1
253 def run(self, evaluate, budget):
254 """Continue from the current population and phase, including partial chunks."""
255 for _
in range(_positive_int(budget,
"budget")):