QDpy
Loading...
Searching...
No Matches
occupancy_me.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Fixed Voronoi state bins and a CVT repertoire in the histogram simplex."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12from scipy.spatial.distance import cdist
13from sklearn.cluster import KMeans
14from threadpoolctl import threadpool_limits
15
16from qdpy.base import registry
17from qdpy.containers import CVTGrid
18from qdpy.containers.grids import _stable_nearest
19from qdpy.tools import iso_line_dd
20
21from .modern import IsoLineMAPElites, _FixedGeneration, _positive_int
22
23__all__ = ["OccupancyHistogram", "OccupancyMAPElites"]
24
25_DISTANCE_BLOCK = 1 << 20
26_MIN_STABLE_DISTANCE = np.sqrt(np.finfo(float).tiny)
27
28
29
31 """Build a frequency descriptor using fixed state or state-action centroids.
32
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
36 the first centroid.
37
38 :param state_centroids: Matrix with one row per state bin and one
39 column per observed coordinate.
40 """
41
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.")
46 self._centroids = matrix
47
48 @property
49 def state_centroids(self):
50 """Return a copy of the state-bin centroids."""
51 return self._centroids.copy()
52
53 @property
54 def bins(self):
55 """Count state bins, which is also the descriptor width."""
56 return len(self._centroids)
57
58 @property
60 """Number of state or state-action coordinates per trajectory row."""
61 return self._centroids.shape[1]
62
63
64 @classmethod
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):
75 model.fit(rows)
76 return cls(model.cluster_centers_)
77
78
79 def encode(self, trajectory):
80 """Return a probability vector with one component per state bin."""
81 points = np.asarray(trajectory, dtype=float)
82 if (points.ndim != 2 or points.shape[1] != self.observation_size
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]
89 distances = cdist(rows, self._centroids)
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))
93 for row in unusual:
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)
98
99
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)
108 else:
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,))
115
116
117@dataclass(frozen=True)
119 evaluate: object
120 encode: object
121 packed: bool
122 steps_score: str
123
124 def __call__(self, individual):
125 result = self.evaluate(individual)
126 if self.packed:
127 return [self._encode(row) for row in result]
128 return self._encode(result)
129
130 def _encode(self, result):
131 if result is None:
132 return None
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)}
139
140
142 """Reuse ordered feedback and seeded variation for fixed trajectory encoders."""
143
144 def __init__(self, container, budget, dimension, *, initial_samples, seed, **kwargs):
145 self.seed = seed
146 initial_samples = _positive_int(initial_samples, "initial_samples")
147 self._initial_samples = 0 if len(container) else initial_samples
148 if container.fitness_weights is not None:
149 kwargs.setdefault("optimisation_task", container.fitness_weights)
150 else:
151 kwargs.setdefault("optimisation_task", "maximisation")
152 super().__init__(container, budget, dimension, **kwargs)
153
154 def reinit(self):
155 """Reset optimisation counters and the private proposal stream."""
156 super().reinit()
157 self._rng = np.random.default_rng(self.seed)
158
159 def _internal_ask(self, base_ind):
160 if self.nb_suggestions < self._initial_samples or not len(self.container):
161 point = self._rng.uniform(*self.ind_domain, size=self.dimension)
162 else:
163 first, second = self._rng.integers(len(self.container), size=2)
164 point = iso_line_dd(self.container[first], self.container[second], bounds=self.ind_domain,
165 iso_sigma=self.iso_sigma, line_sigma=self.line_sigma, rng=self._rng)
166 base_ind[:] = point.tolist()
167 return base_ind
168
169
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.
173
174 Packed callbacks return one ordered result per candidate.
175 """
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,
179 self._steps_score)
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)
183
184
185
186@registry.register
188 """Use a caller-owned CVTGrid and a fixed occupancy encoder.
189
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().
195
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.
203 """
204
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.")
213 self.histogram = histogram
214 super().__init__(container, budget, dimension, initial_samples=initial_samples, seed=seed, **kwargs)
215
216 _steps_score = "occupancy_steps"
217
218 @property
219 def _trajectory_encoder(self):
220 return self.histogram
Fill a one-elite grid using Iso+LineDD variation.
Definition modern.py:56
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.
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.