6"""Reseed MAP-Elites and adjust within-cell competition from a selected panel."""
8from dataclasses
import dataclass
9from math
import isfinite
10from operator
import index
13from scipy.spatial.distance
import cdist
14from sklearn.decomposition
import PCA
15from sklearn.manifold
import TSNE
16from threadpoolctl
import threadpool_limits
18from ._population
import _attempt_budget, _finite_vector
19from .offline
import _empty_geometry, _frozen_matern
20from .task_search
import _measurement, _offer, _validate_grid
22__all__ = [
"UserDecisionModel",
"UserDrivenQD",
"UserDrivenQDStats"]
24_RAW =
"udqd_raw_fitness"
28def _selection_indices(selected, count):
29 selected = frozenset(index(i)
for i
in selected)
30 if (
not selected
or any(
not 0 <= i < count
for i
in selected)
or len(selected) == count):
31 raise ValueError(
"Choose a nonempty proper subset of current panel indices.")
37 """Build a positional preference model from selected and deselected reference designs."""
39 def __init__(self, points, embedded, selected, model):
41 self.
_reference = dict(zip(map(tuple, points), embedded))
53 def fit(cls, genomes, selected, *, projection="tsne", seed=0):
54 points = np.asarray(genomes, dtype=float)
55 if (points.ndim != 2
or points.shape[0] < 2
or not points.shape[1]
56 or not np.isfinite(points).all()
or len(np.unique(points, axis=0)) != len(points)
57 or projection
not in (
"tsne",
"pca")):
58 raise ValueError(
"Supply distinct finite design vectors and projection 'tsne' or 'pca'.")
59 positions = _selection_indices(selected, len(points))
60 labels = np.asarray([i
in positions
for i
in range(len(points))])
61 with threadpool_limits(limits=1):
62 if projection ==
"tsne" and len(points) >= 4:
63 embedded = TSNE(n_components=2, perplexity=min(30, max(2, (len(points) - 1) // 3)),
64 init=
"random", random_state=seed).fit_transform(points).astype(float)
66 embedded = PCA(n_components=min(2, *points.shape), svd_solver=
"full").fit_transform(points)
67 distances = cdist(points, points)
68 scale = distances.sum() / (len(points) * (len(points) - 1))
69 if not 0. < scale < np.inf:
70 raise ValueError(
"Distances between designs must be finite and positive. Scale the genome coordinates.")
71 model = _frozen_matern(points, embedded, scale, 1e-6)
72 return cls(points, embedded, labels, model)
76 points = np.asarray(genomes, dtype=float)
77 if (points.ndim
not in (1, 2)
or points.shape[-1] != self.
_dimension
78 or not np.isfinite(points).all()):
79 raise ValueError(
"Supply finite design vectors with the fitted number of coordinates.")
80 rows = np.atleast_2d(points)
81 result = np.empty((len(rows), self.
_selected.shape[1]))
83 for i, genome
in enumerate(rows):
90 result[unseen] = np.asarray(self.
_model.predict(rows[unseen])).reshape(len(unseen), -1)
91 return result[0]
if points.ndim == 1
else result
95 projected = self.
project(genomes)
96 vectors = np.atleast_2d(projected)
97 selected = cdist(vectors, self.
_selected).min(axis=1)
98 deselected = cdist(vectors, self.
_deselected).min(axis=1)
99 denominator = selected + deselected
100 if not np.isfinite(denominator).all():
101 raise ValueError(
"Distances in the decision embedding must be finite.")
102 result = np.divide(selected, denominator, out=np.full_like(selected, .5), where=denominator > 0.)
103 return float(result[0])
if projected.ndim == 1
else result
107@dataclass(frozen=True)
109 """Admissions include replacements. Reseeding contributes to the feedback counter."""
113 measured_admissions: int
114 preference_admissions: int
120 """Fit a new decision model from the active panel at each user feedback round.
122 The active archive ranks by preference-adjusted fitness and records the
123 underlying measurement and drift in the scores udqd_raw_fitness and
124 udqd_drift. The measured archive always ranks by raw fitness.
132 def __init__(self, archive, *, sample, mutate, initial_samples=8, seed=0):
133 _validate_grid(archive)
136 if (
not 0. < self.
_span < np.inf
or not all(map(callable, (sample, mutate)))
137 or {_RAW, _DRIFT}.intersection((*archive.fitness_score_names, *archive.features_score_names))):
138 raise ValueError(
"Supply callable operators, finite nonzero fitness span, and nonreserved score names.")
139 self.
_initial = _attempt_budget(initial_samples)
141 if archive.fitness_weights
is None:
142 archive._set_fitness_weights((1.,))
143 self.
_maximize = archive.fitness_weights[0] > 0
147 for child
in np.random.SeedSequence(seed).spawn(3))
173 def _offer_preferred(archive, genome, fitness, descriptor, adjusted, drift):
174 measurement = _measurement(archive, ((adjusted,), descriptor), genome)
175 measurement[0].scores.update({_RAW: fitness, _DRIFT: drift})
176 _offer(archive, measurement)
182 def choose(self, indices, *, penalty=.75, projection="tsne"):
183 if not 0. <= penalty <= 1.:
184 raise ValueError(
"penalty must be in [0, 1].")
186 selected = _selection_indices(indices, len(rows))
187 model = UserDecisionModel.fit([tuple(row)
for row
in rows], selected, projection=projection,
189 destination = _empty_geometry(self.
_archive)
190 for i, row
in enumerate(rows):
192 raw = row.scores[_RAW]
193 drift = model.drift(tuple(row))
195 self.
_adjust(raw, drift, penalty), drift)
200 def _adjust(self, fitness, drift, penalty):
201 if drift == 0.
or penalty == 0.:
204 fraction = drift * penalty
205 return float(np.clip((1. - fraction) * fitness + fraction * limit, self.
_lower, self.
_upper))
210 def run(self, evaluate, budget):
211 if not callable(evaluate):
212 raise TypeError(
"Supply a callable evaluator.")
214 for _
in range(_attempt_budget(budget)):
219 genome = self.
_mutate(parent, rng)
220 genome = _finite_vector(genome,
"genome", self.
_dimension)
223 result = evaluate(genome, int(self.
_rollouts.integers(2**32)))
227 fitness, descriptor = result
228 measured, cell = _measurement(self.
measured_archive, ((fitness,), descriptor), genome)
231 fitness = measured.fitness.values[0]
236 drift = 0.
if self.
_model is None else self.
_model.drift(genome)
Frozen decision projection and selection-drift function.
drift(self, genomes)
Return normalized distances to selected versus deselected reference designs.
project(self, genomes)
Map one genome or a matrix of genomes to the fixed similarity space.
fit(cls, genomes, selected, *, projection="tsne", seed=0)
Fit the fixed embedding and its out-of-sample Gaussian process.
Cumulative raw and preference-adjusted evaluation counters.
Run MAP-Elites between feedback rounds and penalize drift in competition.
run(self, evaluate, budget)
Spend additional evaluator attempts with the current preference model.
decision_model(self)
Current fitted decision model, or None before feedback.
_adjust(self, fitness, drift, penalty)
choose(self, indices, *, penalty=.75, projection="tsne")
Refit the preference model and seed a new live archive from selected designs.
archive(self)
Active preference-ranked grid, replaced after each successful choice.
panel(self)
Current selectable designs, in archive iteration order.
_offer_preferred(archive, genome, fitness, descriptor, adjusted, drift)
__init__(self, archive, *, sample, mutate, initial_samples=8, seed=0)
stats(self)
Cumulative evaluation and feedback costs.