QDpy
Loading...
Searching...
No Matches
multiple_behavior_spaces.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Select for novelty across behavior spaces with optionally missing views."""
7
8from collections import deque
9from dataclasses import dataclass
10from math import isfinite
11
12import numpy as np
13from scipy.spatial.distance import cdist
14
15from ._population import _attempt_budget, _finite_vector
16from .modern import _positive_int
17
18__all__ = ["MultiBehaviorRecord", "NSMBS", "NSMBSStats"]
19
20
21
22@dataclass(frozen=True, eq=False)
24 """Fitness is available for reporting and plays no part in selection."""
25
26 genome: tuple
27 fitness: float
28 descriptors: tuple[tuple[float, ...] | None, ...]
29
30
31
32@dataclass(frozen=True)
34 """Measured views and selections are counted in descriptor order."""
35
36 evaluations: int
37 failures: int
38 generations: int
39 measured_views: tuple[int, ...]
40 selected_views: tuple[int, ...]
41 fallback_selections: int
42
43
44def _view_novelty(pool, history, view, neighbors):
45 eligible = [row for row in pool if row.descriptors[view] is not None]
46 if not eligible:
47 return {}
48 reference = [row for row in dict.fromkeys((*eligible, *history)) if row.descriptors[view] is not None]
49 count = min(neighbors, len(reference) - 1)
50 if count == 0:
51 return dict.fromkeys(eligible, 0.)
52 coordinates = np.asarray([row.descriptors[view] for row in reference])
53 # A common rescaling preserves within-view ranks and prevents squared overflow.
54 largest = np.max(np.abs(coordinates))
55 if largest > 1e150:
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))
61
62
63
64class NSMBS:
65 """Each view supplies a novelty ranking over its defined descriptors.
66
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.
70 """
71
72
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")
89 self._archive_additions = _attempt_budget(archive_additions)
90 self._history = deque(maxlen=_attempt_budget(archive_capacity))
91 self._sample, self._mutate = sample, mutate
93 np.random.default_rng(child) for child in np.random.SeedSequence(seed).spawn(4))
94 self._population = ()
95 self._pending = []
96 self._attempts = self._evaluations = self._failures = self._generations = self._fallback = 0
97 self._measured = [0] * len(self._sizes)
98 self._selected = [0] * len(self._sizes)
99
100
101 @property
102 def population(self):
103 return self._population
104
105
106 @property
108 return tuple(self._history)
109
110
111 @property
112 def stats(self):
113 return NSMBSStats(self._evaluations, self._failures, self._generations, tuple(self._measured),
114 tuple(self._selected), self._fallback)
115
116 def _finish_generation(self):
117 pool = (*self._population, *self._pending)
118 # Sort once per view, randomizing ties. A view is active while its ranking has
119 # at least one record that has not been selected from any view.
120 rankings = []
121 for view in range(len(self._sizes)):
122 novelty = _view_novelty(pool, self._history, view, self._neighbors)
123 eligible = tuple(novelty)
124 order = self._selection_rng.permutation(len(eligible))
125 rankings.append(sorted((eligible[i] for i in order), key=novelty.__getitem__))
126 survivors = []
127 remaining = dict.fromkeys(pool)
128 while remaining and len(survivors) < self._size:
129 active = []
130 for view, ranking in enumerate(rankings):
131 while ranking and ranking[-1] not in remaining:
132 ranking.pop()
133 if ranking:
134 active.append(view)
135 if active:
136 view = active[int(self._selection_rng.integers(len(active)))]
137 record = rankings[view].pop()
138 self._selected[view] += 1
139 else:
140 record = tuple(remaining)[int(self._selection_rng.integers(len(remaining)))]
141 self._fallback += 1
142 del remaining[record]
143 survivors.append(record)
144 self._population = tuple(survivors)
145 eligible = [row for row in self._pending if any(view is not None for view in row.descriptors)]
146 count = min(len(eligible), self._archive_additions, self._history.maxlen)
147 for position in self._archive_rng.choice(len(eligible), size=count, replace=False):
148 self._history.append(eligible[position])
149 self._pending.clear()
150 self._attempts = 0
151 self._generations += 1
152
153
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)):
160 if self._population:
161 parent = self._population[int(self._variation_rng.integers(len(self._population)))]
162 genome = tuple(self._mutate(parent.genome, self._variation_rng))
163 else:
164 genome = tuple(self._sample(self._variation_rng))
165 rollout_seed = int(self._measurement_rng.integers(2**32))
166 self._evaluations += 1
167 self._attempts += 1
168 result = evaluate(genome, rollout_seed)
169 if result is None:
170 self._failures += 1
171 else:
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))
178 self._pending.append(MultiBehaviorRecord(genome, float(fitness), views))
179 for view, descriptor in enumerate(views):
180 self._measured[view] += descriptor is not None
181 if self._generations:
182 if self._attempts >= self._offspring:
183 self._finish_generation()
184 elif self._attempts >= self._size:
185 self._population = tuple(self._pending)
186 self._pending.clear()
187 self._attempts = 0
188 self._generations += 1
189 return self.stats
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.