QDpy
Loading...
Searching...
No Matches
ruda.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Use downstream behavior selections to guide unstructured archive admission."""
7
8from collections import deque
9from dataclasses import dataclass, replace
10from operator import index
11
12import numpy as np
13from scipy.spatial.distance import cdist
14from sklearn.decomposition import PCA
15
16from qdpy.tools import iso_line_dd
17from ._population import _attempt_budget, _finite_vector
18from .modern import _positive_int
19from .task_search import _search_bounds
20
21__all__ = ["RUDAEntry", "RUDAResult", "ruda_search"]
22
23
24
25@dataclass(frozen=True, slots=True)
27 """Preserve the raw observation so descriptor refits can use it directly."""
28
29 genome: tuple[float, ...]
30 fitness: float
31 observation: tuple[float, ...]
32 descriptor: tuple[float, ...]
33
34
35
36@dataclass(frozen=True)
38 """The useful observations can outlive their archived individuals."""
39
40 archive: tuple[RUDAEntry, ...]
41 useful_observations: tuple[tuple[float, ...], ...]
42 encoder: object | None
43 evaluations: int
44 failures: int
45 admissions: int
46 solver_calls: int
47 encoder_fits: int
48
49
50def _relevance(points, useful, neighbors, floor):
51 if not len(useful):
52 return np.ones(len(points))
53 distances = cdist(points, useful)
54 count = min(neighbors, len(useful))
55 nearest = np.partition(distances, count - 1, axis=1)[:, :count]
56 return 1. / np.maximum(floor, (nearest / count).sum(axis=1))
57
58
59def _admit(entries, entry, useful, capacity, threshold, neighbors, floor):
60 if not entries:
61 entries.append(entry)
62 return True
63 points = np.asarray([row.descriptor for row in entries])
64 point = np.asarray([entry.descriptor])
65 distances = cdist(point, points)[0] * _relevance(point, useful, neighbors, floor)[0]
66 nearest = np.argmin(distances)
67 if distances[nearest] <= threshold:
68 if entry.fitness > entries[nearest].fitness:
69 entries[nearest] = entry
70 return True
71 return False
72 if len(entries) < capacity:
73 entries.append(entry)
74 return True
75 if capacity == 1:
76 return False
77 separation = cdist(points, points)
78 np.fill_diagonal(separation, np.inf)
79 spacing = separation.min(axis=1) * _relevance(points, useful, neighbors, floor)
80 crowded = min(range(capacity), key=lambda i: (spacing[i], entries[i].fitness))
81 # A measured proposal can displace the least separated member only
82 # when its own spacing improves on that member's.
83 if distances[nearest] > spacing[crowded]:
84 entries[crowded] = entry
85 return True
86 return False
87
88
89
109def ruda_search(evaluate, solve_task, *, dimension, budget, capacity=128, descriptor_size=2,
110 ind_domain=(0., 1.), novelty_threshold=.12, task_period=32, useful_capacity=64,
111 neighbors=5, distance_floor=.02, guidance=True, fit_period=64, training_capacity=1024,
112 encoder_factory=None, initial_samples=16, seed=0):
113 """Use directed distances from each candidate to the current archive.
114
115 Scale distance by the inverse mean distance to the closest useful
116 behaviors. The task solver returns indices from the provided immutable
117 snapshot. Retrain a fresh PCA encoder by default, then re-encode the
118 entire repertoire and useful buffer from raw observations. Supply an
119 encoder factory to use a different representation learner.
120
121 Before fitting, use the first descriptor_size observation coordinates.
122 An exact-size bound uses directed spacing to evict a crowded incumbent.
123 Fitness is maximized when a close proposal competes with a neighbor.
124 """
125 dimension, capacity = _positive_int(dimension, "dimension"), _positive_int(capacity, "capacity")
126 width = _positive_int(descriptor_size, "descriptor_size")
127 neighbors = _positive_int(neighbors, "neighbors")
128 task_period = _positive_int(task_period, "task_period")
129 useful_capacity = _positive_int(useful_capacity, "useful_capacity")
130 training_capacity = _positive_int(training_capacity, "training_capacity")
131 fit_period = None if fit_period is None else _positive_int(fit_period, "fit_period")
132 if (not 0. <= novelty_threshold < np.inf or not 0. < distance_floor < np.inf
133 or (fit_period is not None and training_capacity < max(2, width))):
134 raise ValueError("Use finite distance settings and enough samples for a fit.")
135 if (not callable(evaluate) or not callable(solve_task)
136 or (encoder_factory is not None and not callable(encoder_factory))):
137 raise TypeError("Supply callable evaluation, task solving and optional encoder factory.")
138 budget, initial_samples = _attempt_budget(budget), _attempt_budget(initial_samples)
139 low, high = _search_bounds(ind_domain)
140 rng, task_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
141 archive, useful = [], deque(maxlen=useful_capacity)
142 observations = deque(maxlen=training_capacity)
143 encoder = None
144 references = np.empty((0, width))
145 observation_width = None
146 failures = admissions = solver_calls = fits = 0
147
148 def encode(rows, model):
149 if not len(rows):
150 return np.empty((0, width))
151 data = np.asarray(rows, dtype=float)
152 points = data[:, :width] if model is None else np.asarray(model.transform(data), dtype=float)
153 if points.shape != (len(rows), width) or not np.isfinite(points).all():
154 raise ValueError("The encoder must return finite descriptors of the configured width.")
155 return points
156
157 for attempt in range(1, budget + 1):
158 if not archive or attempt <= initial_samples:
159 genome = rng.uniform(low, high, size=dimension)
160 else:
161 left, right = (archive[i].genome for i in rng.integers(len(archive), size=2))
162 genome = iso_line_dd(left, right, iso_sigma=.05 * (high - low), bounds=(low, high), rng=rng)
163 genome = tuple(map(float, genome))
164 result = evaluate(genome)
165 if result is None:
166 failures += 1
167 else:
168 fitness, raw = result
169 observation = _finite_vector(raw, "Observation", observation_width)
170 observation_width = len(observation)
171 if not np.isfinite(fitness) or observation_width < width:
172 raise ValueError("Use finite fitness and observations at least as wide as the descriptor.")
173 if fit_period is not None:
174 observations.append(observation)
175 descriptor = tuple(map(float, encode((observation,), encoder)[0]))
176 entry = RUDAEntry(genome, float(fitness), observation, descriptor)
177 admissions += _admit(archive, entry, references, capacity, novelty_threshold, neighbors, distance_floor)
178 if fit_period is not None and attempt % fit_period == 0 and len(observations) >= max(2, width):
179 model = PCA(n_components=width, svd_solver="full") if encoder_factory is None else encoder_factory()
180 model.fit(np.asarray(observations))
181 updated = encode([entry.observation for entry in archive], model)
182 references = encode(useful, model) if guidance else np.empty((0, width))
183 rebuilt = []
184 for old, descriptor in zip(archive, updated):
185 entry = replace(old, descriptor=tuple(map(float, descriptor)))
186 _admit(rebuilt, entry, references, capacity, novelty_threshold, neighbors, distance_floor)
187 archive, encoder = rebuilt, model
188 fits += 1
189 if archive and attempt % task_period == 0:
190 selected = tuple(map(index, solve_task(tuple(archive), task_rng)))
191 if any(not 0 <= slot < len(archive) for slot in selected):
192 raise ValueError("Task solver returned an index outside its archive snapshot.")
193 solver_calls += 1
194 useful.extend(archive[i].observation for i in selected)
195 if guidance:
196 references = encode(useful, encoder)
197 return RUDAResult(tuple(archive), tuple(useful), encoder, budget, failures, admissions, solver_calls, fits)
An evaluated behavior and its descriptor in the current encoder.
Definition ruda.py:26
Final unstructured archive, live encoder and search accounting.
Definition ruda.py:37