6"""Select for novelty across behavior spaces with optionally missing views."""
8from collections
import deque
9from dataclasses
import dataclass
10from math
import isfinite
13from scipy.spatial.distance
import cdist
15from ._population
import _attempt_budget, _finite_vector
16from .modern
import _positive_int
18__all__ = [
"MultiBehaviorRecord",
"NSMBS",
"NSMBSStats"]
22@dataclass(frozen=True, eq=False)
24 """Fitness is available for reporting and plays no part in selection."""
28 descriptors: tuple[tuple[float, ...] |
None, ...]
32@dataclass(frozen=True)
34 """Measured views and selections are counted in descriptor order."""
39 measured_views: tuple[int, ...]
40 selected_views: tuple[int, ...]
41 fallback_selections: int
44def _view_novelty(pool, history, view, neighbors):
45 eligible = [row
for row
in pool
if row.descriptors[view]
is not None]
48 reference = [row
for row
in dict.fromkeys((*eligible, *history))
if row.descriptors[view]
is not None]
49 count = min(neighbors, len(reference) - 1)
51 return dict.fromkeys(eligible, 0.)
52 coordinates = np.asarray([row.descriptors[view]
for row
in reference])
54 largest = np.max(np.abs(coordinates))
56 coordinates = coordinates / largest
57 distances = cdist(coordinates[:len(eligible)], coordinates)
58 np.fill_diagonal(distances, np.inf)
59 novelty = np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
60 return dict(zip(eligible, novelty))
65 """Each view supplies a novelty ranking over its defined descriptors.
67 Survivors are selected one at a time, without replacement. Draw uniformly
68 among views with remaining eligible candidates. If those views are exhausted,
69 draw any remaining candidates uniformly. Past records use a bounded FIFO.
81 def __init__(self, descriptor_sizes, *, sample, mutate, population_size=32, offspring=32,
82 neighbors=15, archive_capacity=256, archive_additions=4, seed=0):
83 self.
_sizes = tuple(_positive_int(size,
"descriptor size")
for size
in descriptor_sizes)
84 if not self.
_sizes or not callable(sample)
or not callable(mutate):
85 raise ValueError(
"Provide at least one descriptor size and callable sampling and mutation.")
86 self.
_size = _positive_int(population_size,
"population_size")
87 self.
_offspring = _positive_int(offspring,
"offspring")
88 self.
_neighbors = _positive_int(neighbors,
"neighbors")
90 self.
_history = deque(maxlen=_attempt_budget(archive_capacity))
93 np.random.default_rng(child)
for child
in np.random.SeedSequence(seed).spawn(4))
116 def _finish_generation(self):
121 for view
in range(len(self.
_sizes)):
123 eligible = tuple(novelty)
125 rankings.append(sorted((eligible[i]
for i
in order), key=novelty.__getitem__))
127 remaining = dict.fromkeys(pool)
128 while remaining
and len(survivors) < self.
_size:
130 for view, ranking
in enumerate(rankings):
131 while ranking
and ranking[-1]
not in remaining:
137 record = rankings[view].pop()
140 record = tuple(remaining)[int(self.
_selection_rng.integers(len(remaining)))]
142 del remaining[record]
143 survivors.append(record)
145 eligible = [row
for row
in self.
_pending if any(view
is not None for view
in row.descriptors)]
147 for position
in self.
_archive_rng.choice(len(eligible), size=count, replace=
False):
148 self.
_history.append(eligible[position])
156 def run(self, evaluate, budget):
157 if not callable(evaluate):
158 raise ValueError(
"evaluate must be callable.")
159 for _
in range(_attempt_budget(budget)):
168 result = evaluate(genome, rollout_seed)
172 fitness, descriptors = result
173 descriptors = tuple(descriptors)
174 if not isfinite(fitness)
or len(descriptors) != len(self.
_sizes):
175 raise ValueError(
"Provide finite fitness and one descriptor or None per view.")
176 views = tuple(
None if view
is None else _finite_vector(view,
"descriptor", size)
177 for view, size
in zip(descriptors, self.
_sizes))
179 for view, descriptor
in enumerate(views):
180 self.
_measured[view] += descriptor
is not None
One measured candidate, with None marking an undefined behavior view.
Cumulative evaluation and environmental selection counters.
Generational novelty search with a uniform choice among eligible behavior views.
population(self)
Survivors of the last completed generation.
__init__(self, descriptor_sizes, *, sample, mutate, population_size=32, offspring=32, neighbors=15, archive_capacity=256, archive_additions=4, seed=0)
run(self, evaluate, budget)
Attempt evaluations, keeping incomplete generations for the next call.
stats(self)
Cumulative counters, including measurements in a partial generation.
novelty_archive(self)
History shared across views, excluding undefined records when scored.