QDpy
Loading...
Searching...
No Matches
grids.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""TODO"""
20
21__all__ = ["Grid", "CVTGrid", "AutoScalingGrid"]
22
23
24import math
25from functools import reduce
26import operator
27import numpy as np
28from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
29import random
30#import traceback
31
32from qdpy.utils import *
33from qdpy.phenotype import *
34from qdpy.base import *
35from qdpy._acceleration import kernels as _kernels
36from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
37from .base import *
38
39
40
41
42
43
44# Custom types
45GridSolutionsLike = MutableMapping[GridIndexLike, MutableSequence]
46GridItemsPerBinLike = MutableMapping[GridIndexLike, int]
47GridFitnessLike = MutableMapping[GridIndexLike, MutableSequence[FitnessLike]]
48GridFeaturesLike = MutableMapping[GridIndexLike, MutableSequence[FeaturesLike]]
49GridQualityLike = MutableMapping[GridIndexLike, Optional[FitnessLike]]
50GridRecentnessPerBinLike = MutableMapping[GridIndexLike, MutableSequence[int]]
51
52def _bin_index(value, low, high, size, width):
53 """Return the native rectangular bin for a coordinate inside its interval."""
54 if value == high:
55 return size - 1
56 return min(size - 1, int((float(value) - float(low)) / width))
57
58
59def _stable_nearest(centers, descriptors):
60 """Compare distances when squaring would lose their ordering."""
61 distances = [math.dist(center, descriptors) for center in centers]
62 if all(math.isinf(distance) for distance in distances):
63 scale = max(np.max(np.abs(centers)), max(map(abs, descriptors)))
64 scaled = tuple(value / scale for value in descriptors)
65 distances = [math.dist(tuple(value / scale for value in center), scaled) for center in centers]
66 return (np.argmin(distances),)
67
68
69@registry.register
71 """Retain quality-diversity elites in a rectangular descriptor grid.
72
73 Each descriptor coordinate maps into a discrete bin, and the
74 coordinates together identify a cell. Both boundaries are included.
75 The upper boundary of an axis maps to its final bin.
76
77 An occupied cell with spare space can accept another genome. At
78 capacity the candidate must dominate the selected incumbent, unless
79 random replacement is configured. With multiple objectives the
80 incumbent comparisons use Pareto dominance and storage order.
81 This policy retains cell representatives without maintaining a full
82 Pareto front.
83
84 :param iterable: Initial candidate sequence.
85 :param shape: Number of cells along each descriptor axis.
86 :param max_items_per_bin: Local capacity of each cell.
87 :param fitness_domain: Closed intervals for the objective vector.
88 :param discard_random_on_bin_overload: Replace a random member when
89 the selected cell is full.
90 :param kwargs: Container options. Provide ``features_domain`` with
91 one interval per axis. The default total capacity is the number
92 of cells times the per-cell capacity.
93 """
94
95 fitness_domain: Sequence[DomainLike]
96 features_domain: Sequence[DomainLike]
97
98 _shape: ShapeLike
99 _max_items_per_bin: int
100 _filled_bins: int
101 _solutions: GridSolutionsLike
102 _nb_items_per_bin: GridItemsPerBinLike
103 _fitness: GridFitnessLike
104 _features: GridFeaturesLike
105 _quality: GridQualityLike
106 _quality_array: np.ndarray
107 _bins_size: Sequence[float]
108 _nb_bins: int
109 recentness_per_bin: GridRecentnessPerBinLike
110 history_recentness_per_bin: GridRecentnessPerBinLike
111 activity_per_bin: np.array
112 discard_random_on_bin_overload: bool
113 _uses_centroids = False
114 _allows_unbounded_initial_domain = False
115
116
117 def __init__(self, iterable: Optional[Iterable] = None,
118 shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
119 fitness_domain: Optional[Sequence[DomainLike]] = ((0., np.inf),),
120 discard_random_on_bin_overload = False,
121 **kwargs: Any) -> None:
122 self._shape = tuple(map(operator.index, tuplify(shape)))
123 self._max_items_per_bin = operator.index(max_items_per_bin)
124 if not self._shape or min(self._shape) < 1 or self._max_items_per_bin < 1:
125 raise ValueError("Grid dimensions and max_items_per_bin must be positive.")
126 self.discard_random_on_bin_overload = discard_random_on_bin_overload
127 super().__init__([], fitness_domain=fitness_domain, **kwargs)
128 if self.features_domain is None or len(self.features_domain) == 0:
129 raise ValueError("`features_domain` must be specified and have a length > 0.")
130 if self.fitness_domain is None or len(self.fitness_domain) == 0:
131 raise ValueError("`fitness_domain` must be specified and have a length > 0.")
132 if self._uses_centroids:
133 if len(self.shape) != 1:
134 raise ValueError("CVTGrid shape must specify one centroid count.")
135 if any(not lower <= upper for lower, upper in self.features_domain):
136 raise ValueError("Each CVT descriptor interval must be ordered.")
137 else:
139 allow_unbounded=self._allows_unbounded_initial_domain)
140 self._init_grid()
141 if not "capacity" in kwargs:
142 self._capacity = self._nb_bins * self._max_items_per_bin
143 if iterable is not None:
144 self.update(iterable)
145
146
147 def _validate_descriptor_domain(self, domain, *, allow_unbounded=False):
148 if len(domain) != len(self.shape):
149 raise ValueError("Provide one descriptor interval per grid axis.")
150 for (lower, upper), bins in zip(domain, self.shape):
151 if allow_unbounded and lower < upper and (math.isinf(lower) or math.isinf(upper)):
152 continue
153 span = float(upper) - float(lower)
154 if not math.isfinite(span) or lower > upper or (span > 0 and span / bins == 0):
155 raise ValueError("Rectangular descriptor intervals need a finite bin width and ordered bounds.")
156
157 def _init_grid(self) -> None:
158 """Initialise the grid to correspond to the shape `self.shape`."""
159 self._solutions = {x: [] for x in self._index_grid_iterator()}
160 self._nb_items_per_bin = np.zeros(self._shape, dtype=int) #{x: 0 for x in self._index_grid_iterator()}
161 self._fitness = {x: [] for x in self._index_grid_iterator()}
162 self._features = {x: [] for x in self._index_grid_iterator()}
163 self._quality = {x: None for x in self._index_grid_iterator()}
164 self._quality_array = np.full(self._shape + (len(self.fitness_domain),), np.nan)
165 self._bins_size = [] if self._uses_centroids else [
166 (float(upper) - float(lower)) / bins
167 for (lower, upper), bins in zip(self.features_domain, self.shape)
168 ]
169 self._filled_bins = 0
170 self._nb_bins = reduce(operator.mul, self._shape)
171 self.recentness_per_bin = {x: [] for x in self._index_grid_iterator()}
172 self.history_recentness_per_bin = {x: [] for x in self._index_grid_iterator()}
173 self.activity_per_bin = np.zeros(self._shape, dtype=int)
174
175
176 @property
177 def shape(self) -> ShapeLike:
178 """Return the shape of the grid."""
179 return self._shape
180
181 @property
182 def max_items_per_bin(self) -> int:
183 """Return the maximal number of items stored in a bin of the grid."""
184 return self._max_items_per_bin
185
186 @property
187 def filled_bins(self) -> int:
188 """Return the number of filled bins of the container."""
189 return self._filled_bins
190
191 @property
192 def solutions(self) -> GridSolutionsLike:
193 """Return the solutions in the grid."""
194 return self._solutions
195
196 @property
197 def nb_items_per_bin(self) -> GridItemsPerBinLike:
198 """Return the number of items stored in each bin of the grid."""
199 return self._nb_items_per_bin
200
201 @property
202 def fitness(self) -> GridFitnessLike:
203 """Return the fitness values in the grid."""
204 return self._fitness
205
206 @property
207 def features(self) -> GridFeaturesLike:
208 """Return the features values in the grid."""
209 return self._features
210
211 @property
212 def quality(self) -> GridQualityLike:
213 """One representative fitness object per cell, or None when empty."""
214 return self._quality
215
216 @property
217 def quality_array(self) -> np.ndarray:
218 """Array of representative raw fitness values with objectives on the last axis.
219
220 Empty cells contain NaN. For one objective, use
221 ``quality_array[..., 0]`` to get the descriptor-shaped fitness surface.
222 """
223 return self._quality_array
224
225 @property
226 def best_index(self) -> Optional[GridIndexLike]:
227 """Stored cell index of the cached best individual, or None for an empty grid."""
228 if self._best is None:
229 return None
230 return self._stored_cell(self._best)
231
232
233 def filled_str(self) -> str:
234 """Return a string describing the fullness of the grid (not the container itself, which is handled by ``Container.size_str``)."""
235 return "%i/%i" % (self.filled_bins, self._nb_bins)
236
237
238 def _index_grid_features(self, features: FeaturesLike) -> GridIndexLike:
239 """Get the index in the grid of a given individual with features ``features``, raising an IndexError if it is outside the grid. """
240 index: List[int] = []
241 if len(features) != len(self.shape):
242 raise IndexError(f"Length of parameter ``features`` ({len(features)}) does not corresponds to the number of dimensions of the grid ({len(self.shape)}).")
243 for i in range(len(features)):
244 lower, upper = self.features_domain[i]
245 feature = features[i]
246 if not lower <= feature <= upper:
247 raise IndexError(f"``features`` ({str(features)}) out of bounds ({str(self.features_domain)})")
248 index.append(_bin_index(feature, lower, upper, self.shape[i], self._bins_size[i]))
249 return tuple(index)
250
251
252 @overload
253 def index_grid(self, features: FeaturesLike) -> GridIndexLike: ...
254
255 @overload
256 def index_grid(self, scores: ScoresDictLike) -> GridIndexLike: ...
257
258 @overload
259 def index_grid(self, ind: IndividualLike) -> GridIndexLike: ...
260
261 def index_grid(self, param):
262 """Return a cell index from an individual, descriptors, or named scores.
263
264 Individuals use this grid's descriptor accessor. A score mapping
265 requires ``features_score_names``. The regular grid includes both
266 endpoints and places the upper endpoint in the last bin.
267
268 :raises IndexError: If descriptors have the wrong length or exceed
269 their domain.
270 :raises RuntimeError: If a score mapping lacks configured names.
271 """
272 if type(param) is Individual:
273 features = self.get_ind_features(param)
274 elif isinstance(param, ScoresDictLike):
275 if len(self.features_score_names) == 0:
276 raise RuntimeError(f"'features_score_names' must be set to compute an individual grid index from scores.")
277 features = param.to_features(self.features_score_names)
278 elif isinstance(param, IndividualLike):
279 features = self.get_ind_features(param)
280 elif hasattr(param, "features"):
281 features = param.features
282 else:
283 features = param
284 return self._index_grid_features(features)
285
286
287 def _index_grid_iterator(self) -> Generator[GridIndexLike, None, None]:
288 """Return an iterator of the index of the grid, based on ``self.shape``."""
289 val: List[int] = [0] * len(self._shape)
290 yield tuple(val)
291 while True:
292 for i in reversed(range(len(self._shape))):
293 val[i] += 1
294 if val[i] >= self._shape[i]:
295 if i == 0:
296 return
297 val[i] = 0
298 else:
299 yield tuple(val)
300 break
301
302 def _update_quality(self, ig: GridIndexLike) -> None:
303 """Update quality in bin ``ig`` of the grid."""
304 if self._nb_items_per_bin[ig] == 0:
305 val: Optional[FitnessLike] = None
306 elif self._nb_items_per_bin[ig] == 1:
307 val = self.fitness[ig][0]
308 else:
309 best: IndividualLike = self.solutions[ig][0]
310 fit_best = self.get_ind_fitness(best)
311 for s in self.solutions[ig][1:]:
312 fit_s = self.get_ind_fitness(s)
313 if fit_s.dominates(fit_best):
314 best = s
315 fit_best = self.get_ind_fitness(best)
316 val = fit_best
317 self.quality[ig] = val
318 if val is None:
319 self.quality_array[ig] = math.nan
320 else:
321 self.quality_array[ig] = val.values
322
323 def _set_fitness_weights(self, weights: FitnessValuesLike) -> None:
324 previous = self.fitness_weights
325 super()._set_fitness_weights(weights)
326 if self and (previous is None or tuple(previous) != tuple(weights)):
327 for cell, solutions in self.solutions.items():
328 self.fitness[cell][:] = [self.get_ind_fitness(ind) for ind in solutions]
329 self._update_quality(cell)
330
331
332
337 def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool, only_to_parents: bool) -> Optional[int]:
338 if not only_to_parents:
339 try:
340 ig = self.index_grid(individual)
341 except IndexError:
342 pass
343 else:
344 if self._nb_items_per_bin[ig] < self.max_items_per_bin:
345 return self._add_to_grid(individual, ig, raise_if_not_added_to_parents)
346 replacement = self._replacement_in_bin(individual, self.solutions[ig])
347 if replacement is not None:
348 return self._add_to_grid(individual, ig, raise_if_not_added_to_parents, replacement)
349
350 if self.parents:
351 super()._add_internal(individual, raise_if_not_added_to_parents, True)
352 return None
353
354
355 def _replacement_in_bin(self, individual: IndividualLike, solutions: Sequence[IndividualLike]) -> Optional[int]:
356 if not solutions:
357 return None
359 return random.randint(0, len(solutions) - 1)
360 worst_index = 0
361 worst_fitness = self.get_ind_fitness(solutions[0])
362 for index, solution in enumerate(solutions[1:], start=1):
363 fitness = self.get_ind_fitness(solution)
364 if worst_fitness.dominates(fitness):
365 worst_index = index
366 worst_fitness = fitness
367 if self.get_ind_fitness(individual).dominates(worst_fitness):
368 return worst_index
369 return None
370
371
372
381 def _add_to_grid(self, individual: IndividualLike, ig: GridIndexLike,
382 raise_if_not_added_to_parents: bool, replacement: Optional[int] = None) -> Optional[int]:
383 replace_index = None if replacement is None else self.items.index(self.solutions[ig][replacement])
384 previous_additions = self._nb_added
385 index = super()._add_internal(individual, raise_if_not_added_to_parents, False, replace_index)
386 if previous_additions == self._nb_added:
387 return index
388
389 if replacement is not None:
390 self._discard_from_grid(ig, replacement)
391 if self._nb_items_per_bin[ig] == 0:
392 self._filled_bins += 1
393 self._solutions[ig].append(individual)
394 self._fitness[ig].append(self.get_ind_fitness(individual))
395 self._features[ig].append(self.get_ind_features(individual))
396 self.recentness_per_bin[ig].append(self._nb_added)
397 self.history_recentness_per_bin[ig].append(self._nb_added)
398 self._nb_items_per_bin[ig] += 1
399 self.activity_per_bin[ig] += 1
400 self._update_quality(ig)
401 return index
402
403
404 def _discard_from_grid(self, ig: GridIndexLike, index_in_bin: int) -> None:
405 # Remove individual from grid
406 del self._solutions[ig][index_in_bin]
407 self._nb_items_per_bin[ig] -= 1
408 del self._fitness[ig][index_in_bin]
409 del self._features[ig][index_in_bin]
410 del self.recentness_per_bin[ig][index_in_bin]
411 # Update quality
412 self._update_quality(ig)
413 # Update number of filled bins
414 if self._nb_items_per_bin[ig] == 0:
415 self._filled_bins -= 1
416
417
418 def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
419 """Remove the matching entry and refresh cell quality and occupancy.
420
421 Use the cell in which the stored object was admitted. A descriptor
422 edit after admission does not relocate it.
423 """
424 index = self._index_of(individual)
425 if index is None:
426 super().discard(individual, also_from_parents)
427 return
428 stored = self.items[index]
429 ig = self._stored_cell(stored)
430 index_in_bin = self.solutions[ig].index(stored)
431 self._discard_by_index(stored, index, also_from_parents)
432 self._discard_from_grid(ig, index_in_bin)
433
434
439 def _stored_cell(self, individual: IndividualLike) -> GridIndexLike:
440 try:
441 current_cell = self.index_grid(individual)
442 except IndexError:
443 pass
444 else:
445 if any(stored is individual for stored in self.solutions[current_cell]):
446 return current_cell
447 for cell, individuals in self.solutions.items():
448 if any(stored is individual for stored in individuals):
449 return cell
450 raise RuntimeError("Stored individual is missing from the grid cells.")
451
452 def _get_best_inds(self):
453 get_fitness = self.get_ind_fitness
454 default_getter = (
455 getattr(get_fitness, "__func__", None) is Container.get_ind_fitness
456 and getattr(self._fitness_with_container_weights, "__func__", None)
457 is Container._fitness_with_container_weights
458 )
459 best_inds = []
460 for inds in self.solutions.values():
461 if not inds:
462 continue
463 best = inds[0]
464 if len(inds) > 1 or not default_getter:
465 best_fit = get_fitness(best)
466 for ind in inds[1:]:
467 ind_fit = get_fitness(ind)
468 if ind_fit.dominates(best_fit):
469 best = ind
470 best_fit = get_fitness(best)
471 best_inds.append(best)
472 return best_inds
473
474
475 def qd_score(self, normalized: bool = True) -> float:
476 """Sum quality across the grid.
477
478 By default use the normalised fitness of one representative per
479 occupied cell, with direction determined by each objective's weight
480 sign. A populated grid with an infinite fitness bound returns NaN
481 when normalised. An empty grid has a score of zero.
482 With ``normalized=False``, sum raw objective values across all stored
483 entries, including multiple entries in one cell.
484 """
485 score: float = 0.
486 if normalized:
487 if self.fitness_domain is None:
488 raise RuntimeError(f"'fitness_domain' must be set to compute normalized QD scores.")
489 elif len(self) and self._has_infinite_fitness_bounds():
490 return math.nan
491 else:
492 best_inds = self._get_best_inds()
493 get_fitness = self.get_ind_fitness
494 domain = self.fitness_domain
495 if (getattr(get_fitness, "__func__", None) is Container.get_ind_fitness
496 and getattr(self._fitness_with_container_weights, "__func__", None)
497 is Container._fitness_with_container_weights
498 and len(self.fitness_score_names) == 0
499 and type(domain) is tuple and all(
500 type(bounds) is tuple and len(bounds) == 2
501 and type(bounds[0]) is float and type(bounds[1]) is float for bounds in domain
502 )):
503 # A plain float domain is fixed during the sum. Keep the
504 # original division and accumulation order for each elite.
505 intervals = tuple((lo, hi, hi - lo if hi > lo else 1) for lo, hi in domain)
506 for ind in best_inds:
507 fit = get_fitness(ind)
508 for v, w, (lo, hi, width) in zip(fit.values, fit.weights, intervals):
509 score += (hi - v if w < 0. else v - lo) / width
510 return score
511 for ind in best_inds:
512 ind_fit = get_fitness(ind)
513 for v, w, bounds in zip(ind_fit.values, ind_fit.weights, self.fitness_domain):
514 d = (bounds[1] - bounds[0]) if bounds[1] > bounds[0] else 1
515 if w < 0.:
516 score += (bounds[1] - v) / (d)
517 else:
518 score += (v - bounds[0]) / (d)
519 else:
520 for ind in self:
521 ind_fit = self.get_ind_fitness(ind)
522 score += np.sum(ind_fit.values)
523 return score
524
525
526
527
528
529from sklearn.cluster import KMeans
530from sklearn.gaussian_process import GaussianProcessRegressor
531
532@registry.register
534 """Assign descriptors to the nearest fitted centroid.
535
536 Sample a uniform set of points inside the specified feature domain,
537 then fit one k-means centroid per cell. Retain individuals with the
538 same admission policy as Grid. Centroid fitting uses NumPy's random
539 state, so seed it before constructing the grid for a repeatable setup.
540
541 :param shape: Number of centroid cells as an integer or a one-item
542 sequence.
543 :param grid_shape: Optional legacy shape with one entry per descriptor.
544 The descriptor domain determines dimensionality when omitted.
545 :param nb_sampled_points: Number of samples used to fit the centroids.
546 :param centroids: Optional precomputed matrix with one row per cell and
547 one column per descriptor. Omit to fit centroids by sampling.
548 :param kwargs: Grid options including the descriptor domain.
549 """
550
551 _grid_shape: ShapeLike
552 _nb_sampled_points: int
553 cluster_centers: np.array
554 _uses_centroids = True
555
556 def __init__(self, iterable: Optional[Iterable] = None,
557 shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
558 grid_shape: Optional[Union[ShapeLike, int]] = None, nb_sampled_points: int = 50000, *,
559 centroids=None, **kwargs: Any) -> None:
560 self._nb_sampled_points = nb_sampled_points
561 super().__init__(None, shape, max_items_per_bin, **kwargs)
562 dimension = len(self.features_domain)
563 self._grid_shape = (1,) * dimension if grid_shape is None else tuplify(grid_shape)
564 if len(self._grid_shape) != dimension:
565 raise ValueError("CVT grid_shape must have one entry per descriptor interval.")
566 if centroids is None:
567 if nb_sampled_points < self.shape[0]:
568 raise ValueError("nb_sampled_points must be at least the number of centroids.")
569 if any(not math.isfinite(float(upper) - float(lower)) for lower, upper in self.features_domain):
570 raise ValueError("Fitting CVT centroids requires finite descriptor intervals and spans.")
571 self._init_clusters()
572 else:
573 matrix = np.array(centroids, dtype=float, copy=True, order="C")
574 if matrix.shape != (self.shape[0], len(self.features_domain)):
575 raise ValueError("centroids must have one row per cell and one column per descriptor.")
576 lower, upper = np.asarray(self.features_domain).T
577 if not np.all(np.isfinite(matrix) & (matrix >= lower) & (matrix <= upper)):
578 raise ValueError("Centroids must be finite and within the descriptor domain.")
579 self.cluster_centers = matrix
580 if iterable is not None:
581 self.update(iterable)
582
583 def _init_clusters(self) -> None:
584 """Initialise the clusters and tessellate the grid."""
585 sample = np.random.uniform(0.0, 1.0, (self.nb_sampled_points, len(self.grid_shape)))
586 for i, d in enumerate(self.features_domain):
587 sample[:, i] = d[0] + (d[1] - d[0]) * sample[:, i]
588 kmeans = KMeans(init="k-means++", n_clusters=self.shape[0], n_init=1, verbose=0)
589 kmeans.fit(sample)
590 self.cluster_centers = kmeans.cluster_centers_
591
592 @property
593 def grid_shape(self) -> ShapeLike:
594 """Return the shape of the grid."""
595 return self._grid_shape
596
597 @property
598 def nb_sampled_points(self) -> int:
599 """Return the number of sampled points to identify cluster centers."""
600 return self._nb_sampled_points
601
602 def _index_grid_features(self, features: FeaturesLike) -> GridIndexLike:
603 """Return the first nearest centroid for descriptors within the CVT domain."""
604 if (len(features) != len(self.features_domain) or not self.in_bounds(features, self.features_domain)
605 or not all(map(math.isfinite, features))):
606 raise IndexError(f"Features are outside the CVT domain: {features}")
607 centers = self.cluster_centers
608 n_centers = self._shape[0]
609 if (type(centers) is np.ndarray and centers.ndim == 2 and len(centers) >= n_centers
610 and centers.dtype.kind == "f" and centers.dtype.itemsize <= 8
611 and type(features) in (Features, np.ndarray, tuple, list)):
612 descriptors = np.asarray(features)
613 if descriptors.ndim == 1 and descriptors.dtype.kind in "biuf" and descriptors.dtype.itemsize <= 8:
614 if (_kernels is not None and n_centers >= 64 and centers.shape[1] == descriptors.size == 2
615 and centers.dtype == descriptors.dtype == np.float64
616 and centers.flags.c_contiguous and centers.flags.aligned):
617 nearest = _kernels.nearest_centroid_2d(centers[:n_centers], descriptors[0], descriptors[1])
618 if nearest >= 0:
619 return (np.intp(nearest),)
620 deltas = np.ascontiguousarray(centers[:n_centers] - descriptors)
621 squares = np.square(deltas, out=deltas)
622 # Keep the usual double-precision square root and tie order.
623 distances = np.sqrt(np.sum(squares, axis=1), dtype=np.float64)
624 nearest = np.argmin(distances)
625 distance = distances[nearest]
626 if math.isnan(distance) or math.sqrt(np.finfo(squares.dtype).tiny) <= distance < math.inf:
627 return (nearest,)
628 return _stable_nearest(centers[:n_centers], descriptors)
629
630 # Preserve per-centroid arithmetic for custom descriptor or array types.
631 dists = np.empty(n_centers)
632 for i in range(len(dists)):
633 dists[i] = math.sqrt(np.sum(np.square(centers[i] - features)))
634 return (np.argmin(dists),)
635
636
637
638
639@registry.register
641 """Rebuild a grid as its observed objective or descriptor ranges change.
642
643 Each enabled axis family is checked independently. The first finite
644 descriptor vector can bootstrap initially unbounded axes before the
645 normal rescaling interval. With ``rescaling_period <= 0``, automatic
646 rescaling is disabled.
647
648 :param scaling_containers: Preferred source of records on rebuild.
649 If empty, use immediate parents or the entries in this grid.
650 :param fitness_scaling: Update the objective bounds.
651 :param features_scaling: Update descriptor bounds and cell widths.
652 :param rescaling_period: Candidate interval between automatic
653 rescale checks after a rebuild.
654 """
655
656 scaling_containers: Sequence[Container]
657 fitness_scaling: bool
658 features_scaling: bool
659 rescaling_period: int
660
661 @property
662 def _allows_unbounded_initial_domain(self):
663 return self.features_scaling and self.rescaling_period > 0
664
665 def __init__(self, iterable: Optional[Iterable] = None,
666 shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
667 scaling_containers: Sequence[Container] = (),
668 fitness_scaling: bool = True,
669 features_scaling: bool = True,
670 rescaling_period: int = 1,
671 **kwargs: Any) -> None:
672 self.scaling_containers = scaling_containers
673 self.fitness_scaling = fitness_scaling
674 self.features_scaling = features_scaling
675 self.rescaling_period = rescaling_period # max(rescaling_period, 1)
676 self._nb_rescaled = 0
677 self._last_nb_rescaled = 0
678 super().__init__(iterable, shape, max_items_per_bin, **kwargs)
679
680
681 def rescale(self, fitness_domain: Sequence[DomainLike], features_domain: Sequence[DomainLike]) -> None:
682 #print(f"# rescale {features_domain} {len(self)}")
683 # Identify which individuals should be added after the rescaling
684 """Rebuild the cells with explicit objective and descriptor bounds.
685
686 Read records from scaling containers, parents, or the retained grid
687 before clearing it. Reapply admission to those records in order.
688 Entries that fail readmission are omitted from the rebuilt grid.
689 """
690 self._validate_descriptor_domain(features_domain)
691 if len(self.scaling_containers) > 0:
692 inds = flatten_seq_of_seq(self.scaling_containers)
693 elif len(self.parents) > 0:
694 inds = self.all_parents_inds()
695 else:
696 inds = list(self)
697
698 # Rescale the container
699 self.clear()
700 self.fitness_domain = fitness_domain
701 self.features_domain = features_domain
702 self._init_grid()
703 for i in inds:
704 try:
705 super().add(i)
706 except Exception:
707 pass
708 #print(f"# rescale flatten: {len(flatten_seq_of_seq(self.scaling_containers))} {len(self)}")
709
710
711 def _recompute_fitness_extrema(self, new_ind_fits: Sequence[FitnessLike]) -> Sequence[DomainLike]:
712 assert(len(new_ind_fits) > 0)
713 maxima = np.array(new_ind_fits[0])
714 minima = np.array(new_ind_fits[0])
715 for ind in self:
716 ind_f = np.array(self.get_ind_fitness(ind).values)
717 for i in range(len(maxima)):
718 if ind_f[i] > maxima[i]:
719 maxima[i] = ind_f[i]
720 elif ind_f[i] < minima[i]:
721 minima[i] = ind_f[i]
722 for f in new_ind_fits:
723 ind_f = np.array(f)
724 for i in range(len(maxima)):
725 if ind_f[i] > maxima[i]:
726 maxima[i] = ind_f[i]
727 elif ind_f[i] < minima[i]:
728 minima[i] = ind_f[i]
729 return tuple(zip(minima, maxima))
730
731 def _recompute_features_extrema(self, new_ind_fts: Sequence[FeaturesLike]) -> Sequence[DomainLike]:
732 assert(len(new_ind_fts) > 0)
733 maxima = np.array(new_ind_fts[0])
734 minima = np.array(new_ind_fts[0])
735 for ind in self:
736 ind_f = np.array(self.get_ind_features(ind))
737 for i in range(len(maxima)):
738 if ind_f[i] > maxima[i]:
739 maxima[i] = ind_f[i]
740 elif ind_f[i] < minima[i]:
741 minima[i] = ind_f[i]
742 for f in new_ind_fts:
743 ind_f = np.array(f)
744 for i in range(len(maxima)):
745 if ind_f[i] > maxima[i]:
746 maxima[i] = ind_f[i]
747 elif ind_f[i] < minima[i]:
748 minima[i] = ind_f[i]
749 return tuple(zip(minima, maxima))
750
751
752
757 def _add_rescaling(self, inds: Sequence[IndividualLike]) -> None:
758# self._nb_rescaled += len(inds)
759# if self.rescaling_period <= 0 or self._nb_rescaled - self._last_nb_rescaled < self.rescaling_period:
760# return
761#
762 fits = []
763 fts = []
764 valid_inds = []
765 # Iterate and find valid inds, their fitness and feature descriptors
766 for ind in inds:
767 fit = self.get_ind_fitness(ind)
768 ft = self.get_ind_features(ind)
769 if not fit.valid or len(fit.values) != len(self.fitness_domain) or len(ft) != len(self.features_domain):
770 continue
771 if not all(map(math.isfinite, fit.values)) or not all(map(math.isfinite, ft)):
772 continue
773 # If needed, check if fitness and features are within bounds
774 if not self.fitness_scaling and not self.in_bounds(fit.values, self.fitness_domain):
775 continue
776 if not self.features_scaling and not self.in_bounds(ft, self.features_domain):
777 continue
778 valid_inds.append(ind)
779 fits.append(fit)
780 fts.append(ft)
781 if len(valid_inds) == 0:
782 return
783
784 # Rescale grid
785 new_fit_domain = self.fitness_domain
786 new_ft_domain = self.features_domain
787 rescale = False
788 if self.fitness_scaling:
789 new_fit_domain = self._recompute_fitness_extrema(fits)
790 rescale = new_fit_domain != tuple(map(tuple, self.fitness_domain))
791 if self.features_scaling:
792 new_ft_domain = self._recompute_features_extrema(fts)
793 rescale |= new_ft_domain != tuple(map(tuple, self.features_domain))
794 if rescale:
795 self.rescale(new_fit_domain, new_ft_domain)
797
798
799 def _maybe_rescale(self, individuals: Sequence[IndividualLike]) -> None:
800 self._nb_rescaled += len(individuals)
801 if self.rescaling_period <= 0 or not individuals:
802 return
803 needs_initial_bounds = self.features_scaling and not np.isfinite(self.features_domain).all()
804 if needs_initial_bounds or self._nb_rescaled - self._last_nb_rescaled >= self.rescaling_period:
805 self._add_rescaling(individuals)
806
807 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool = False) -> Optional[int]:
808 """Check automatic rescaling before admitting an individual."""
809 self._maybe_rescale([individual])
810 return super().add(individual, raise_if_not_added_to_parents)
811
812
813 def update(self, iterable: Iterable, ignore_exceptions: bool = True, issue_warning: bool = False) -> int:
814 """Materialise the input once, rescale as needed, then admit candidates in order."""
815 individuals = list(iterable)
816 self._maybe_rescale(individuals)
817 return super().update(individuals, ignore_exceptions, issue_warning)
818
819
820
821
822
823
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
None clear(self, bool also_from_parents=False)
Definition base.py:170
Sequence[IndividualLike] all_parents_inds(self)
Definition base.py:165
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Definition base.py:169
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Definition base.py:792
bool in_bounds(self, Any val, Any domain)
Definition base.py:518
Optional[int] _index_of(self, IndividualLike individual)
Definition base.py:769
bool _has_infinite_fitness_bounds(self)
Definition base.py:937
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Definition grids.py:813
Optional[int] add(self, IndividualLike individual, bool raise_if_not_added_to_parents=False)
Definition grids.py:807
None _maybe_rescale(self, Sequence[IndividualLike] individuals)
Definition grids.py:799
Sequence[DomainLike] _recompute_features_extrema(self, Sequence[FeaturesLike] new_ind_fts)
Definition grids.py:731
Sequence[DomainLike] _recompute_fitness_extrema(self, Sequence[FitnessLike] new_ind_fits)
Definition grids.py:711
None _add_rescaling(self, Sequence[IndividualLike] inds)
Compute candidate extrema and rebuild if either enabled domain changes.
Definition grids.py:757
None rescale(self, Sequence[DomainLike] fitness_domain, Sequence[DomainLike] features_domain)
Definition grids.py:681
ShapeLike grid_shape(self)
Definition grids.py:593
GridIndexLike _index_grid_features(self, FeaturesLike features)
Definition grids.py:602
Optional[int] _replacement_in_bin(self, IndividualLike individual, Sequence[IndividualLike] solutions)
Definition grids.py:355
GridIndexLike _index_grid_features(self, FeaturesLike features)
Definition grids.py:238
Optional[int] _add_internal(self, IndividualLike individual, bool raise_if_not_added_to_parents, bool only_to_parents)
Choose a cell and apply its admission policy.
Definition grids.py:337
None _discard_from_grid(self, GridIndexLike ig, int index_in_bin)
Definition grids.py:404
np.ndarray quality_array(self)
Definition grids.py:217
GridIndexLike index_grid(self, FeaturesLike features)
Definition grids.py:253
GridIndexLike _stored_cell(self, IndividualLike individual)
Find the admitted cell by object identity.
Definition grids.py:439
GridFitnessLike fitness(self)
Definition grids.py:202
Optional[GridIndexLike] best_index(self)
Definition grids.py:226
Generator[GridIndexLike, None, None] _index_grid_iterator(self)
Definition grids.py:287
GridItemsPerBinLike nb_items_per_bin(self)
Definition grids.py:197
None discard(self, IndividualLike individual, bool also_from_parents=False)
Definition grids.py:418
GridQualityLike quality(self)
Definition grids.py:212
_validate_descriptor_domain(self, domain, *, allow_unbounded=False)
Definition grids.py:147
bool _allows_unbounded_initial_domain
Definition grids.py:114
None _update_quality(self, GridIndexLike ig)
Definition grids.py:302
Optional[int] _add_to_grid(self, IndividualLike individual, GridIndexLike ig, bool raise_if_not_added_to_parents, Optional[int] replacement=None)
Apply a successful storage update to per-cell bookkeeping.
Definition grids.py:382
GridSolutionsLike solutions(self)
Definition grids.py:192
GridFeaturesLike features(self)
Definition grids.py:207
float qd_score(self, bool normalized=True)
Definition grids.py:475