21__all__ = [
"Grid",
"CVTGrid",
"AutoScalingGrid"]
25from functools
import reduce
28from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
36from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
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]]
52def _bin_index(value, low, high, size, width):
53 """Return the native rectangular bin for a coordinate inside its interval."""
56 return min(size - 1, int((float(value) - float(low)) / width))
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),)
71 """Retain quality-diversity elites in a rectangular descriptor grid.
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.
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
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.
95 fitness_domain: Sequence[DomainLike]
96 features_domain: Sequence[DomainLike]
99 _max_items_per_bin: 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]
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
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)))
125 raise ValueError(
"Grid dimensions and max_items_per_bin must be positive.")
127 super().__init__([], fitness_domain=fitness_domain, **kwargs)
129 raise ValueError(
"`features_domain` must be specified and have a length > 0.")
131 raise ValueError(
"`fitness_domain` must be specified and have a length > 0.")
133 if len(self.
shape) != 1:
134 raise ValueError(
"CVTGrid shape must specify one centroid count.")
136 raise ValueError(
"Each CVT descriptor interval must be ordered.")
141 if not "capacity" in kwargs:
143 if iterable
is not None:
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)):
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.")
158 """Initialise the grid to correspond to the shape `self.shape`."""
166 (float(upper) - float(lower)) / bins
177 def shape(self) -> ShapeLike:
178 """Return the shape of the grid."""
182 def max_items_per_bin(self) -> int:
183 """Return the maximal number of items stored in a bin of the grid."""
187 def filled_bins(self) -> int:
188 """Return the number of filled bins of the container."""
193 """Return the solutions in the grid."""
198 """Return the number of items stored in each bin of the grid."""
203 """Return the fitness values in the grid."""
208 """Return the features values in the grid."""
213 """One representative fitness object per cell, or None when empty."""
218 """Array of representative raw fitness values with objectives on the last axis.
220 Empty cells contain NaN. For one objective, use
221 ``quality_array[..., 0]`` to get the descriptor-shaped fitness surface.
227 """Stored cell index of the cached best individual, or None for an empty grid."""
228 if self.
_best is None:
234 """Return a string describing the fullness of the grid (not the container itself, which is handled by ``Container.size_str``)."""
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)):
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]))
253 def index_grid(self, features: FeaturesLike) -> GridIndexLike: ...
256 def index_grid(self, scores: ScoresDictLike) -> GridIndexLike: ...
259 def index_grid(self, ind: IndividualLike) -> GridIndexLike: ...
261 def index_grid(self, param):
262 """Return a cell index from an individual, descriptors, or named scores.
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.
268 :raises IndexError: If descriptors have the wrong length or exceed
270 :raises RuntimeError: If a score mapping lacks configured names.
272 if type(param)
is Individual:
274 elif isinstance(param, ScoresDictLike):
276 raise RuntimeError(f
"'features_score_names' must be set to compute an individual grid index from scores.")
278 elif isinstance(param, IndividualLike):
280 elif hasattr(param,
"features"):
281 features = param.features
288 """Return an iterator of the index of the grid, based on ``self.shape``."""
289 val: List[int] = [0] * len(self.
_shape)
292 for i
in reversed(range(len(self.
_shape))):
294 if val[i] >= self.
_shape[i]:
303 """Update quality in bin ``ig`` of the grid."""
305 val: Optional[FitnessLike] =
None
309 best: IndividualLike = self.
solutions[ig][0]
313 if fit_s.dominates(fit_best):
323 def _set_fitness_weights(self, weights: FitnessValuesLike) ->
None:
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():
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:
345 return self.
_add_to_grid(individual, ig, raise_if_not_added_to_parents)
347 if replacement
is not None:
348 return self.
_add_to_grid(individual, ig, raise_if_not_added_to_parents, replacement)
351 super().
_add_internal(individual, raise_if_not_added_to_parents,
True)
355 def _replacement_in_bin(self, individual: IndividualLike, solutions: Sequence[IndividualLike]) -> Optional[int]:
359 return random.randint(0, len(solutions) - 1)
362 for index, solution
in enumerate(solutions[1:], start=1):
364 if worst_fitness.dominates(fitness):
366 worst_fitness = fitness
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])
385 index = super().
_add_internal(individual, raise_if_not_added_to_parents,
False, replace_index)
389 if replacement
is not None:
404 def _discard_from_grid(self, ig: GridIndexLike, index_in_bin: int) ->
None:
418 def discard(self, individual: IndividualLike, also_from_parents: bool =
False) ->
None:
419 """Remove the matching entry and refresh cell quality and occupancy.
421 Use the cell in which the stored object was admitted. A descriptor
422 edit after admission does not relocate it.
426 super().
discard(individual, also_from_parents)
428 stored = self.
items[index]
430 index_in_bin = self.
solutions[ig].index(stored)
445 if any(stored
is individual
for stored
in self.
solutions[current_cell]):
447 for cell, individuals
in self.
solutions.items():
448 if any(stored
is individual
for stored
in individuals):
450 raise RuntimeError(
"Stored individual is missing from the grid cells.")
452 def _get_best_inds(self):
455 getattr(get_fitness,
"__func__",
None)
is Container.get_ind_fitness
457 is Container._fitness_with_container_weights
464 if len(inds) > 1
or not default_getter:
465 best_fit = get_fitness(best)
467 ind_fit = get_fitness(ind)
468 if ind_fit.dominates(best_fit):
470 best_fit = get_fitness(best)
471 best_inds.append(best)
475 def qd_score(self, normalized: bool =
True) -> float:
476 """Sum quality across the grid.
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.
488 raise RuntimeError(f
"'fitness_domain' must be set to compute normalized QD scores.")
495 if (getattr(get_fitness,
"__func__",
None)
is Container.get_ind_fitness
497 is Container._fitness_with_container_weights
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
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
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
516 score += (bounds[1] - v) / (d)
518 score += (v - bounds[0]) / (d)
522 score += np.sum(ind_fit.values)
529from sklearn.cluster
import KMeans
530from sklearn.gaussian_process
import GaussianProcessRegressor
534 """Assign descriptors to the nearest fitted centroid.
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.
541 :param shape: Number of centroid cells as an integer or a one-item
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.
551 _grid_shape: ShapeLike
552 _nb_sampled_points: int
553 cluster_centers: np.array
554 _uses_centroids =
True
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:
561 super().__init__(
None, shape, max_items_per_bin, **kwargs)
563 self.
_grid_shape = (1,) * dimension
if grid_shape
is None else tuplify(grid_shape)
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.")
573 matrix = np.array(centroids, dtype=float, copy=
True, order=
"C")
575 raise ValueError(
"centroids must have one row per cell and one column per descriptor.")
577 if not np.all(np.isfinite(matrix) & (matrix >= lower) & (matrix <= upper)):
578 raise ValueError(
"Centroids must be finite and within the descriptor domain.")
580 if iterable
is not None:
584 """Initialise the clusters and tessellate the grid."""
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)
594 """Return the shape of the grid."""
599 """Return the number of sampled points to identify cluster centers."""
603 """Return the first nearest centroid for descriptors within the CVT domain."""
605 or not all(map(math.isfinite, features))):
606 raise IndexError(f
"Features are outside the CVT domain: {features}")
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])
619 return (np.intp(nearest),)
620 deltas = np.ascontiguousarray(centers[:n_centers] - descriptors)
621 squares = np.square(deltas, out=deltas)
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:
628 return _stable_nearest(centers[:n_centers], descriptors)
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),)
641 """Rebuild a grid as its observed objective or descriptor ranges change.
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.
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.
656 scaling_containers: Sequence[Container]
657 fitness_scaling: bool
658 features_scaling: bool
659 rescaling_period: int
662 def _allows_unbounded_initial_domain(self):
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:
678 super().__init__(iterable, shape, max_items_per_bin, **kwargs)
681 def rescale(self, fitness_domain: Sequence[DomainLike], features_domain: Sequence[DomainLike]) ->
None:
684 """Rebuild the cells with explicit objective and descriptor bounds.
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.
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])
717 for i
in range(len(maxima)):
718 if ind_f[i] > maxima[i]:
720 elif ind_f[i] < minima[i]:
722 for f
in new_ind_fits:
724 for i
in range(len(maxima)):
725 if ind_f[i] > maxima[i]:
727 elif ind_f[i] < minima[i]:
729 return tuple(zip(minima, maxima))
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])
737 for i
in range(len(maxima)):
738 if ind_f[i] > maxima[i]:
740 elif ind_f[i] < minima[i]:
742 for f
in new_ind_fts:
744 for i
in range(len(maxima)):
745 if ind_f[i] > maxima[i]:
747 elif ind_f[i] < minima[i]:
749 return tuple(zip(minima, maxima))
771 if not all(map(math.isfinite, fit.values))
or not all(map(math.isfinite, ft)):
778 valid_inds.append(ind)
781 if len(valid_inds) == 0:
790 rescale = new_fit_domain != tuple(map(tuple, self.
fitness_domain))
795 self.
rescale(new_fit_domain, new_ft_domain)
799 def _maybe_rescale(self, individuals: Sequence[IndividualLike]) ->
None:
807 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool =
False) -> Optional[int]:
808 """Check automatic rescaling before admitting an individual."""
810 return super().
add(individual, raise_if_not_added_to_parents)
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)
817 return super().
update(individuals, ignore_exceptions, issue_warning)
Sequence fitness_score_names
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Sequence features_score_names
None clear(self, bool also_from_parents=False)
Sequence[IndividualLike] all_parents_inds(self)
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
bool in_bounds(self, Any val, Any domain)
Optional[int] _index_of(self, IndividualLike individual)
bool _has_infinite_fitness_bounds(self)
Sequence scaling_containers
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Optional[int] add(self, IndividualLike individual, bool raise_if_not_added_to_parents=False)
None _maybe_rescale(self, Sequence[IndividualLike] individuals)
Sequence[DomainLike] _recompute_features_extrema(self, Sequence[FeaturesLike] new_ind_fts)
Sequence[DomainLike] _recompute_fitness_extrema(self, Sequence[FitnessLike] new_ind_fits)
None _add_rescaling(self, Sequence[IndividualLike] inds)
Compute candidate extrema and rebuild if either enabled domain changes.
None rescale(self, Sequence[DomainLike] fitness_domain, Sequence[DomainLike] features_domain)
ShapeLike grid_shape(self)
None _init_clusters(self)
int nb_sampled_points(self)
GridIndexLike _index_grid_features(self, FeaturesLike features)
Optional[int] _replacement_in_bin(self, IndividualLike individual, Sequence[IndividualLike] solutions)
GridIndexLike _index_grid_features(self, FeaturesLike features)
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.
None _discard_from_grid(self, GridIndexLike ig, int index_in_bin)
np.ndarray quality_array(self)
GridIndexLike index_grid(self, FeaturesLike features)
GridIndexLike _stored_cell(self, IndividualLike individual)
Find the admitted cell by object identity.
GridFitnessLike fitness(self)
Optional[GridIndexLike] best_index(self)
Generator[GridIndexLike, None, None] _index_grid_iterator(self)
GridItemsPerBinLike nb_items_per_bin(self)
None discard(self, IndividualLike individual, bool also_from_parents=False)
GridQualityLike quality(self)
_validate_descriptor_domain(self, domain, *, allow_unbounded=False)
bool _allows_unbounded_initial_domain
None _update_quality(self, GridIndexLike ig)
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.
GridSolutionsLike solutions(self)
GridFeaturesLike features(self)
float qd_score(self, bool normalized=True)
dict history_recentness_per_bin
discard_random_on_bin_overload