6"""Fixed Voronoi state bins and a CVT repertoire in the histogram simplex."""
8from dataclasses
import dataclass
9from math
import isfinite
12from scipy.spatial.distance
import cdist
13from sklearn.cluster
import KMeans
14from threadpoolctl
import threadpool_limits
21from .modern
import IsoLineMAPElites, _FixedGeneration, _positive_int
23__all__ = [
"OccupancyHistogram",
"OccupancyMAPElites"]
25_DISTANCE_BLOCK = 1 << 20
26_MIN_STABLE_DISTANCE = np.sqrt(np.finfo(float).tiny)
31 """Build a frequency descriptor using fixed state or state-action centroids.
33 Each row has one state or state-action observation. Assign it to its
34 nearest Euclidean centroid and normalize the counts by trajectory
35 length. The order of visits does not affect the result. Ties go to
38 :param state_centroids: Matrix with one row per state bin and one
39 column per observed coordinate.
42 def __init__(self, state_centroids):
43 matrix = np.array(state_centroids, dtype=float, order=
"C", copy=
True)
44 if matrix.ndim != 2
or not matrix.size
or not np.isfinite(matrix).all():
45 raise ValueError(
"Use a nonempty finite matrix of state centroids.")
50 """Return a copy of the state-bin centroids."""
55 """Count state bins, which is also the descriptor width."""
60 """Number of state or state-action coordinates per trajectory row."""
65 def fit(cls, reference_states, bins, *, seed=0):
66 """Return a fixed state partition from seeded k-means on reference observations."""
67 bins = _positive_int(bins,
"bins")
68 rows = np.asarray(reference_states, dtype=float)
69 if (rows.ndim != 2
or not rows.size
or not np.isfinite(rows).all()
70 or len(np.unique(rows, axis=0)) < bins):
71 raise ValueError(
"Provide at least one distinct finite reference row per state bin.")
72 rng = np.random.default_rng(seed)
73 model = KMeans(bins, n_init=1, random_state=int(rng.integers(2**32)))
74 with threadpool_limits(limits=1):
76 return cls(model.cluster_centers_)
80 """Return a probability vector with one component per state bin."""
81 points = np.asarray(trajectory, dtype=float)
83 or not len(points)
or not np.isfinite(points).all()):
84 raise ValueError(
"Supply a nonempty finite trajectory of the declared observation width.")
85 counts = np.zeros(self.
bins, dtype=np.int64)
86 block = max(1, _DISTANCE_BLOCK // self.
bins)
87 for start
in range(0, len(points), block):
88 rows = points[start:start + block]
90 ids = distances.argmin(axis=1)
91 nearest = distances[np.arange(len(rows)), ids]
92 unusual = np.flatnonzero(~np.isfinite(nearest) | (nearest < _MIN_STABLE_DISTANCE))
94 if nearest[row] != 0
or not np.array_equal(rows[row], self.
_centroids[ids[row]]):
95 ids[row], = _stable_nearest(self.
_centroids, rows[row])
96 counts += np.bincount(ids, minlength=self.
bins)
97 return counts / len(points)
100 def make_archive(self, cells, *, fitness_domain=(-np.inf, np.inf), fitness_weight=1.,
101 centroids=
None, seed=0):
102 """Use explicit probability vectors or draw uniform Dirichlet centroids."""
103 cells = _positive_int(cells,
"cells")
104 if not isfinite(fitness_weight)
or not fitness_weight:
105 raise ValueError(
"Use one finite nonzero fitness weight.")
106 if centroids
is None:
107 centroids = np.random.default_rng(seed).dirichlet(np.ones(self.
bins), size=cells)
109 centroids = np.asarray(centroids, dtype=float)
110 if (centroids.shape != (cells, self.
bins)
111 or not np.allclose(centroids.sum(axis=1), 1., rtol=0., atol=1e-8)):
112 raise ValueError(
"Supply one probability vector per repertoire cell.")
113 return CVTGrid(shape=cells, centroids=centroids, features_domain=((0., 1.),) * self.
bins,
114 fitness_domain=(tuple(fitness_domain),), fitness_weights=(fitness_weight,))
117@dataclass(frozen=True)
124 def __call__(self, individual):
125 result = self.evaluate(individual)
127 return [self.
_encode(row)
for row
in result]
130 def _encode(self, result):
133 fitness, trajectory = result
134 quality = np.asarray(fitness, dtype=float)
135 if quality.shape
not in ((), (1,))
or not np.isfinite(quality).all():
136 raise ValueError(
"Use finite scalar fitness for trajectory search.")
137 descriptor = self.encode(trajectory)
138 return (float(quality.item()),), tuple(descriptor), {self.
steps_score: len(trajectory)}
142 """Reuse ordered feedback and seeded variation for fixed trajectory encoders."""
144 def __init__(self, container, budget, dimension, *, initial_samples, seed, **kwargs):
146 initial_samples = _positive_int(initial_samples,
"initial_samples")
148 if container.fitness_weights
is not None:
149 kwargs.setdefault(
"optimisation_task", container.fitness_weights)
151 kwargs.setdefault(
"optimisation_task",
"maximisation")
152 super().__init__(container, budget, dimension, **kwargs)
155 """Reset optimisation counters and the private proposal stream."""
157 self.
_rng = np.random.default_rng(self.
seed)
163 first, second = self.
_rng.integers(len(self.
container), size=2)
166 base_ind[:] = point.tolist()
170 def optimise(self, evaluate, budget=None, batch_mode=True, executor=None,
171 send_several_suggestions_to_fn=False, max_nb_suggestions_per_call=10, verbose=False):
172 """Evaluate each candidate once using (fitness, trajectory) or None on failure.
174 Packed callbacks return one ordered result per candidate.
176 if not callable(evaluate):
177 raise TypeError(
"evaluate must be callable.")
178 adapter =
_TrajectoryEvaluator(evaluate, self._trajectory_encoder.encode, send_several_suggestions_to_fn,
180 return super().
optimise(adapter, budget=budget, batch_mode=batch_mode, executor=executor,
181 send_several_suggestions_to_fn=send_several_suggestions_to_fn,
182 max_nb_suggestions_per_call=max_nb_suggestions_per_call, verbose=verbose)
188 """Use a caller-owned CVTGrid and a fixed occupancy encoder.
190 optimise() takes an evaluator returning (scalar fitness, trajectory).
191 Use already encoded descriptors with ask_batch() and tell_batch().
192 Feedback is integrated in proposal order within each generation. Each
193 archive elite stores the number of observations in its measured
194 trajectory as scores["occupancy_steps"] when using optimise().
196 :param container: Best-only CVTGrid with simplex centroids and one objective.
197 :param budget: Attempted candidate evaluations.
198 :param dimension: Number of real decision coordinates.
199 :param histogram: OccupancyHistogram used on every evaluation.
200 :param initial_samples: Uniform proposals before archive variation.
201 :param seed: Private proposal seed.
202 :param kwargs: IsoLineMAPElites and native optimiser options.
205 def __init__(self, container, budget, dimension, *, histogram, initial_samples=16, seed=0, **kwargs):
206 if not isinstance(histogram, OccupancyHistogram):
207 raise TypeError(
"Supply an OccupancyHistogram.")
208 if (type(container)
is not CVTGrid
or tuple(map(tuple, container.features_domain)) != ((0., 1.),) * histogram.bins
209 or len(container.fitness_domain
or ()) != 1
or container.discard_random_on_bin_overload
210 or container.fitness_score_names
or container.features_score_names
211 or not np.allclose(container.cluster_centers.sum(axis=1), 1., rtol=0., atol=1e-8)):
212 raise ValueError(
"Use a native best-only CVTGrid over the occupancy simplex with ordinary fitness.")
214 super().__init__(container, budget, dimension, initial_samples=initial_samples, seed=seed, **kwargs)
216 _steps_score =
"occupancy_steps"
219 def _trajectory_encoder(self):
Fill a one-elite grid using Iso+LineDD variation.
Count nearest-centroid visits along a fixed-width trajectory.
make_archive(self, cells, *, fitness_domain=(-np.inf, np.inf), fitness_weight=1., centroids=None, seed=0)
Build a native CVT repertoire over the descriptor probability simplex.
encode(self, trajectory)
Encode one trajectory as normalized state-bin visits.
fit(cls, reference_states, bins, *, seed=0)
Fit the state tessellation to caller-supplied reference rows.
Run Iso+LineDD MAP-Elites on raw trajectories and a fixed occupancy grid.
len(trajectory)} steps_score
_internal_ask(self, base_ind)
optimise(self, evaluate, budget=None, batch_mode=True, executor=None, send_several_suggestions_to_fn=False, max_nb_suggestions_per_call=10, verbose=False)
Encode trajectories in the native evaluation loop.