# This file is part of qdpy.
#
# qdpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# qdpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
## @file
# @brief Rectangular, centroidal, and autoscaling archives with per-cell quality.
"""TODO"""
__all__ = ["Grid", "CVTGrid", "AutoScalingGrid"]
########### IMPORTS ########### {{{1
import math
from functools import reduce
import operator
import numpy as np
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
import random
#import traceback
from qdpy.utils import *
from qdpy.phenotype import *
from qdpy.base import *
from qdpy._acceleration import kernels as _kernels
from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
from .base import *
########### GRID-BASED CLASSES ########### {{{2
# Custom types
GridSolutionsLike = MutableMapping[GridIndexLike, MutableSequence]
GridItemsPerBinLike = MutableMapping[GridIndexLike, int]
GridFitnessLike = MutableMapping[GridIndexLike, MutableSequence[FitnessLike]]
GridFeaturesLike = MutableMapping[GridIndexLike, MutableSequence[FeaturesLike]]
GridQualityLike = MutableMapping[GridIndexLike, Optional[FitnessLike]]
GridRecentnessPerBinLike = MutableMapping[GridIndexLike, MutableSequence[int]]
def _bin_index(value, low, high, size, width):
"""Return the native rectangular bin for a coordinate inside its interval."""
if value == high:
return size - 1
return min(size - 1, int((float(value) - float(low)) / width))
def _stable_nearest(centers, descriptors):
"""Compare distances when squaring would lose their ordering."""
distances = [math.dist(center, descriptors) for center in centers]
if all(math.isinf(distance) for distance in distances):
scale = max(np.max(np.abs(centers)), max(map(abs, descriptors)))
scaled = tuple(value / scale for value in descriptors)
distances = [math.dist(tuple(value / scale for value in center), scaled) for center in centers]
return (np.argmin(distances),)
[docs]
@registry.register
class Grid(Container):
"""Retain quality-diversity elites in a rectangular descriptor grid.
Each descriptor coordinate maps into a discrete bin, and the
coordinates together identify a cell. Both boundaries are included.
The upper boundary of an axis maps to its final bin.
An occupied cell with spare space can accept another genome. At
capacity the candidate must dominate the selected incumbent, unless
random replacement is configured. With multiple objectives the
incumbent comparisons use Pareto dominance and storage order.
This policy retains cell representatives without maintaining a full
Pareto front.
:param iterable: Initial candidate sequence.
:param shape: Number of cells along each descriptor axis.
:param max_items_per_bin: Local capacity of each cell.
:param fitness_domain: Closed intervals for the objective vector.
:param discard_random_on_bin_overload: Replace a random member when
the selected cell is full.
:param kwargs: Container options. Provide ``features_domain`` with
one interval per axis. The default total capacity is the number
of cells times the per-cell capacity.
"""
fitness_domain: Sequence[DomainLike]
features_domain: Sequence[DomainLike]
_shape: ShapeLike
_max_items_per_bin: int
_filled_bins: int
_solutions: GridSolutionsLike
_nb_items_per_bin: GridItemsPerBinLike
_fitness: GridFitnessLike
_features: GridFeaturesLike
_quality: GridQualityLike
_quality_array: np.ndarray
_bins_size: Sequence[float]
_nb_bins: int
recentness_per_bin: GridRecentnessPerBinLike
history_recentness_per_bin: GridRecentnessPerBinLike
activity_per_bin: np.array
discard_random_on_bin_overload: bool
_uses_centroids = False
_allows_unbounded_initial_domain = False
def __init__(self, iterable: Optional[Iterable] = None,
shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
fitness_domain: Optional[Sequence[DomainLike]] = ((0., np.inf),),
discard_random_on_bin_overload = False,
**kwargs: Any) -> None:
self._shape = tuple(map(operator.index, tuplify(shape)))
self._max_items_per_bin = operator.index(max_items_per_bin)
if not self._shape or min(self._shape) < 1 or self._max_items_per_bin < 1:
raise ValueError("Grid dimensions and max_items_per_bin must be positive.")
self.discard_random_on_bin_overload = discard_random_on_bin_overload
super().__init__([], fitness_domain=fitness_domain, **kwargs)
if self.features_domain is None or len(self.features_domain) == 0:
raise ValueError("`features_domain` must be specified and have a length > 0.")
if self.fitness_domain is None or len(self.fitness_domain) == 0:
raise ValueError("`fitness_domain` must be specified and have a length > 0.")
if self._uses_centroids:
if len(self.shape) != 1:
raise ValueError("CVTGrid shape must specify one centroid count.")
if any(not lower <= upper for lower, upper in self.features_domain):
raise ValueError("Each CVT descriptor interval must be ordered.")
else:
self._validate_descriptor_domain(self.features_domain,
allow_unbounded=self._allows_unbounded_initial_domain)
self._init_grid()
if not "capacity" in kwargs:
self._capacity = self._nb_bins * self._max_items_per_bin
if iterable is not None:
self.update(iterable)
def _validate_descriptor_domain(self, domain, *, allow_unbounded=False):
if len(domain) != len(self.shape):
raise ValueError("Provide one descriptor interval per grid axis.")
for (lower, upper), bins in zip(domain, self.shape):
if allow_unbounded and lower < upper and (math.isinf(lower) or math.isinf(upper)):
continue
span = float(upper) - float(lower)
if not math.isfinite(span) or lower > upper or (span > 0 and span / bins == 0):
raise ValueError("Rectangular descriptor intervals need a finite bin width and ordered bounds.")
def _init_grid(self) -> None:
"""Initialise the grid to correspond to the shape `self.shape`."""
self._solutions = {x: [] for x in self._index_grid_iterator()}
self._nb_items_per_bin = np.zeros(self._shape, dtype=int) #{x: 0 for x in self._index_grid_iterator()}
self._fitness = {x: [] for x in self._index_grid_iterator()}
self._features = {x: [] for x in self._index_grid_iterator()}
self._quality = {x: None for x in self._index_grid_iterator()}
self._quality_array = np.full(self._shape + (len(self.fitness_domain),), np.nan)
self._bins_size = [] if self._uses_centroids else [
(float(upper) - float(lower)) / bins
for (lower, upper), bins in zip(self.features_domain, self.shape)
]
self._filled_bins = 0
self._nb_bins = reduce(operator.mul, self._shape)
self.recentness_per_bin = {x: [] for x in self._index_grid_iterator()}
self.history_recentness_per_bin = {x: [] for x in self._index_grid_iterator()}
self.activity_per_bin = np.zeros(self._shape, dtype=int)
@property
def shape(self) -> ShapeLike:
"""Return the shape of the grid."""
return self._shape
@property
def max_items_per_bin(self) -> int:
"""Return the maximal number of items stored in a bin of the grid."""
return self._max_items_per_bin
@property
def filled_bins(self) -> int:
"""Return the number of filled bins of the container."""
return self._filled_bins
@property
def solutions(self) -> GridSolutionsLike:
"""Return the solutions in the grid."""
return self._solutions
@property
def nb_items_per_bin(self) -> GridItemsPerBinLike:
"""Return the number of items stored in each bin of the grid."""
return self._nb_items_per_bin
@property
def fitness(self) -> GridFitnessLike:
"""Return the fitness values in the grid."""
return self._fitness
@property
def features(self) -> GridFeaturesLike:
"""Return the features values in the grid."""
return self._features
@property
def quality(self) -> GridQualityLike:
"""One representative fitness object per cell, or None when empty."""
return self._quality
@property
def quality_array(self) -> np.ndarray:
"""Array of representative raw fitness values with objectives on the last axis.
Empty cells contain NaN. For one objective, use
``quality_array[..., 0]`` to get the descriptor-shaped fitness surface.
"""
return self._quality_array
@property
def best_index(self) -> Optional[GridIndexLike]:
"""Stored cell index of the cached best individual, or None for an empty grid."""
if self._best is None:
return None
return self._stored_cell(self._best)
def filled_str(self) -> str:
"""Return a string describing the fullness of the grid (not the container itself, which is handled by ``Container.size_str``)."""
return "%i/%i" % (self.filled_bins, self._nb_bins)
def _index_grid_features(self, features: FeaturesLike) -> GridIndexLike:
"""Get the index in the grid of a given individual with features ``features``, raising an IndexError if it is outside the grid. """
index: List[int] = []
if len(features) != len(self.shape):
raise IndexError(f"Length of parameter ``features`` ({len(features)}) does not corresponds to the number of dimensions of the grid ({len(self.shape)}).")
for i in range(len(features)):
lower, upper = self.features_domain[i]
feature = features[i]
if not lower <= feature <= upper:
raise IndexError(f"``features`` ({str(features)}) out of bounds ({str(self.features_domain)})")
index.append(_bin_index(feature, lower, upper, self.shape[i], self._bins_size[i]))
return tuple(index)
@overload
def index_grid(self, features: FeaturesLike) -> GridIndexLike: ...
@overload
def index_grid(self, scores: ScoresDictLike) -> GridIndexLike: ...
@overload
def index_grid(self, ind: IndividualLike) -> GridIndexLike: ...
[docs]
def index_grid(self, param):
"""Return a cell index from an individual, descriptors, or named scores.
Individuals use this grid's descriptor accessor. A score mapping
requires ``features_score_names``. The regular grid includes both
endpoints and places the upper endpoint in the last bin.
:raises IndexError: If descriptors have the wrong length or exceed
their domain.
:raises RuntimeError: If a score mapping lacks configured names.
"""
if type(param) is Individual:
features = self.get_ind_features(param)
elif isinstance(param, ScoresDictLike):
if len(self.features_score_names) == 0:
raise RuntimeError(f"'features_score_names' must be set to compute an individual grid index from scores.")
features = param.to_features(self.features_score_names)
elif isinstance(param, IndividualLike):
features = self.get_ind_features(param)
elif hasattr(param, "features"):
features = param.features
else:
features = param
return self._index_grid_features(features)
def _index_grid_iterator(self) -> Generator[GridIndexLike, None, None]:
"""Return an iterator of the index of the grid, based on ``self.shape``."""
val: List[int] = [0] * len(self._shape)
yield tuple(val)
while True:
for i in reversed(range(len(self._shape))):
val[i] += 1
if val[i] >= self._shape[i]:
if i == 0:
return
val[i] = 0
else:
yield tuple(val)
break
def _update_quality(self, ig: GridIndexLike) -> None:
"""Update quality in bin ``ig`` of the grid."""
if self._nb_items_per_bin[ig] == 0:
val: Optional[FitnessLike] = None
elif self._nb_items_per_bin[ig] == 1:
val = self.fitness[ig][0]
else:
best: IndividualLike = self.solutions[ig][0]
fit_best = self.get_ind_fitness(best)
for s in self.solutions[ig][1:]:
fit_s = self.get_ind_fitness(s)
if fit_s.dominates(fit_best):
best = s
fit_best = self.get_ind_fitness(best)
val = fit_best
self.quality[ig] = val
if val is None:
self.quality_array[ig] = math.nan
else:
self.quality_array[ig] = val.values
def _set_fitness_weights(self, weights: FitnessValuesLike) -> None:
previous = self.fitness_weights
super()._set_fitness_weights(weights)
if self and (previous is None or tuple(previous) != tuple(weights)):
for cell, solutions in self.solutions.items():
self.fitness[cell][:] = [self.get_ind_fitness(ind) for ind in solutions]
self._update_quality(cell)
## @brief Choose a cell and apply its admission policy.
# @param individual Candidate with validated local measurements.
# @param raise_if_not_added_to_parents Whether parent errors must propagate.
# @param only_to_parents Bypass cell admission.
# @return A storage index for locally admitted or existing entries.
def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool, only_to_parents: bool) -> Optional[int]:
if not only_to_parents:
try:
ig = self.index_grid(individual)
except IndexError:
pass
else:
if self._nb_items_per_bin[ig] < self.max_items_per_bin:
return self._add_to_grid(individual, ig, raise_if_not_added_to_parents)
replacement = self._replacement_in_bin(individual, self.solutions[ig])
if replacement is not None:
return self._add_to_grid(individual, ig, raise_if_not_added_to_parents, replacement)
if self.parents:
super()._add_internal(individual, raise_if_not_added_to_parents, True)
return None
def _replacement_in_bin(self, individual: IndividualLike, solutions: Sequence[IndividualLike]) -> Optional[int]:
if not solutions:
return None
if self.discard_random_on_bin_overload:
return random.randint(0, len(solutions) - 1)
worst_index = 0
worst_fitness = self.get_ind_fitness(solutions[0])
for index, solution in enumerate(solutions[1:], start=1):
fitness = self.get_ind_fitness(solution)
if worst_fitness.dominates(fitness):
worst_index = index
worst_fitness = fitness
if self.get_ind_fitness(individual).dominates(worst_fitness):
return worst_index
return None
## @brief Apply a successful storage update to per-cell bookkeeping.
# @param individual Candidate proposed for local insertion.
# @param ig Index of the candidate's destination cell.
# @param raise_if_not_added_to_parents Whether required parent errors propagate.
# @param replacement The incumbent's position within the cell, if any.
# @return The storage index reported by the container.
# @details Translate a cell-relative replacement to a storage index.
# Update the cell only when storage records a new insertion. This
# keeps occupancy, scores, and activity aligned on duplicate offers.
def _add_to_grid(self, individual: IndividualLike, ig: GridIndexLike,
raise_if_not_added_to_parents: bool, replacement: Optional[int] = None) -> Optional[int]:
replace_index = None if replacement is None else self.items.index(self.solutions[ig][replacement])
previous_additions = self._nb_added
index = super()._add_internal(individual, raise_if_not_added_to_parents, False, replace_index)
if previous_additions == self._nb_added:
return index
if replacement is not None:
self._discard_from_grid(ig, replacement)
if self._nb_items_per_bin[ig] == 0:
self._filled_bins += 1
self._solutions[ig].append(individual)
self._fitness[ig].append(self.get_ind_fitness(individual))
self._features[ig].append(self.get_ind_features(individual))
self.recentness_per_bin[ig].append(self._nb_added)
self.history_recentness_per_bin[ig].append(self._nb_added)
self._nb_items_per_bin[ig] += 1
self.activity_per_bin[ig] += 1
self._update_quality(ig)
return index
def _discard_from_grid(self, ig: GridIndexLike, index_in_bin: int) -> None:
# Remove individual from grid
del self._solutions[ig][index_in_bin]
self._nb_items_per_bin[ig] -= 1
del self._fitness[ig][index_in_bin]
del self._features[ig][index_in_bin]
del self.recentness_per_bin[ig][index_in_bin]
# Update quality
self._update_quality(ig)
# Update number of filled bins
if self._nb_items_per_bin[ig] == 0:
self._filled_bins -= 1
def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
"""Remove the matching entry and refresh cell quality and occupancy.
Use the cell in which the stored object was admitted. A descriptor
edit after admission does not relocate it.
"""
index = self._index_of(individual)
if index is None:
super().discard(individual, also_from_parents)
return
stored = self.items[index]
ig = self._stored_cell(stored)
index_in_bin = self.solutions[ig].index(stored)
self._discard_by_index(stored, index, also_from_parents)
self._discard_from_grid(ig, index_in_bin)
## @brief Find the admitted cell by object identity.
# @param individual Stored individual whose cell is needed.
# @return Cell containing the exact stored object.
# @details Try its current descriptor index first. Fall back to searching
# occupied entries when descriptors have changed since insertion.
def _stored_cell(self, individual: IndividualLike) -> GridIndexLike:
try:
current_cell = self.index_grid(individual)
except IndexError:
pass
else:
if any(stored is individual for stored in self.solutions[current_cell]):
return current_cell
for cell, individuals in self.solutions.items():
if any(stored is individual for stored in individuals):
return cell
raise RuntimeError("Stored individual is missing from the grid cells.")
def _get_best_inds(self):
get_fitness = self.get_ind_fitness
default_getter = (
getattr(get_fitness, "__func__", None) is Container.get_ind_fitness
and getattr(self._fitness_with_container_weights, "__func__", None)
is Container._fitness_with_container_weights
)
best_inds = []
for inds in self.solutions.values():
if not inds:
continue
best = inds[0]
if len(inds) > 1 or not default_getter:
best_fit = get_fitness(best)
for ind in inds[1:]:
ind_fit = get_fitness(ind)
if ind_fit.dominates(best_fit):
best = ind
best_fit = get_fitness(best)
best_inds.append(best)
return best_inds
[docs]
def qd_score(self, normalized: bool = True) -> float:
"""Sum quality across the grid.
By default use the normalised fitness of one representative per
occupied cell, with direction determined by each objective's weight
sign. A populated grid with an infinite fitness bound returns NaN
when normalised. An empty grid has a score of zero.
With ``normalized=False``, sum raw objective values across all stored
entries, including multiple entries in one cell.
"""
score: float = 0.
if normalized:
if self.fitness_domain is None:
raise RuntimeError(f"'fitness_domain' must be set to compute normalized QD scores.")
elif len(self) and self._has_infinite_fitness_bounds():
return math.nan
else:
best_inds = self._get_best_inds()
get_fitness = self.get_ind_fitness
domain = self.fitness_domain
if (getattr(get_fitness, "__func__", None) is Container.get_ind_fitness
and getattr(self._fitness_with_container_weights, "__func__", None)
is Container._fitness_with_container_weights
and len(self.fitness_score_names) == 0
and type(domain) is tuple and all(
type(bounds) is tuple and len(bounds) == 2
and type(bounds[0]) is float and type(bounds[1]) is float for bounds in domain
)):
# A plain float domain is fixed during the sum. Keep the
# original division and accumulation order for each elite.
intervals = tuple((lo, hi, hi - lo if hi > lo else 1) for lo, hi in domain)
for ind in best_inds:
fit = get_fitness(ind)
for v, w, (lo, hi, width) in zip(fit.values, fit.weights, intervals):
score += (hi - v if w < 0. else v - lo) / width
return score
for ind in best_inds:
ind_fit = get_fitness(ind)
for v, w, bounds in zip(ind_fit.values, ind_fit.weights, self.fitness_domain):
d = (bounds[1] - bounds[0]) if bounds[1] > bounds[0] else 1
if w < 0.:
score += (bounds[1] - v) / (d)
else:
score += (v - bounds[0]) / (d)
else:
for ind in self:
ind_fit = self.get_ind_fitness(ind)
score += np.sum(ind_fit.values)
return score
from sklearn.cluster import KMeans
from sklearn.gaussian_process import GaussianProcessRegressor
[docs]
@registry.register
class CVTGrid(Grid):
"""Assign descriptors to the nearest fitted centroid.
Sample a uniform set of points inside the specified feature domain,
then fit one k-means centroid per cell. Retain individuals with the
same admission policy as Grid. Centroid fitting uses NumPy's random
state, so seed it before constructing the grid for a repeatable setup.
:param shape: Number of centroid cells as an integer or a one-item
sequence.
:param grid_shape: Optional legacy shape with one entry per descriptor.
The descriptor domain determines dimensionality when omitted.
:param nb_sampled_points: Number of samples used to fit the centroids.
:param centroids: Optional precomputed matrix with one row per cell and
one column per descriptor. Omit to fit centroids by sampling.
:param kwargs: Grid options including the descriptor domain.
"""
_grid_shape: ShapeLike
_nb_sampled_points: int
cluster_centers: np.array
_uses_centroids = True
def __init__(self, iterable: Optional[Iterable] = None,
shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
grid_shape: Optional[Union[ShapeLike, int]] = None, nb_sampled_points: int = 50000, *,
centroids=None, **kwargs: Any) -> None:
self._nb_sampled_points = nb_sampled_points
super().__init__(None, shape, max_items_per_bin, **kwargs)
dimension = len(self.features_domain)
self._grid_shape = (1,) * dimension if grid_shape is None else tuplify(grid_shape)
if len(self._grid_shape) != dimension:
raise ValueError("CVT grid_shape must have one entry per descriptor interval.")
if centroids is None:
if nb_sampled_points < self.shape[0]:
raise ValueError("nb_sampled_points must be at least the number of centroids.")
if any(not math.isfinite(float(upper) - float(lower)) for lower, upper in self.features_domain):
raise ValueError("Fitting CVT centroids requires finite descriptor intervals and spans.")
self._init_clusters()
else:
matrix = np.array(centroids, dtype=float, copy=True, order="C")
if matrix.shape != (self.shape[0], len(self.features_domain)):
raise ValueError("centroids must have one row per cell and one column per descriptor.")
lower, upper = np.asarray(self.features_domain).T
if not np.all(np.isfinite(matrix) & (matrix >= lower) & (matrix <= upper)):
raise ValueError("Centroids must be finite and within the descriptor domain.")
self.cluster_centers = matrix
if iterable is not None:
self.update(iterable)
def _init_clusters(self) -> None:
"""Initialise the clusters and tessellate the grid."""
sample = np.random.uniform(0.0, 1.0, (self.nb_sampled_points, len(self.grid_shape)))
for i, d in enumerate(self.features_domain):
sample[:, i] = d[0] + (d[1] - d[0]) * sample[:, i]
kmeans = KMeans(init="k-means++", n_clusters=self.shape[0], n_init=1, verbose=0)
kmeans.fit(sample)
self.cluster_centers = kmeans.cluster_centers_
@property
def grid_shape(self) -> ShapeLike:
"""Return the shape of the grid."""
return self._grid_shape
@property
def nb_sampled_points(self) -> int:
"""Return the number of sampled points to identify cluster centers."""
return self._nb_sampled_points
def _index_grid_features(self, features: FeaturesLike) -> GridIndexLike:
"""Return the first nearest centroid for descriptors within the CVT domain."""
if (len(features) != len(self.features_domain) or not self.in_bounds(features, self.features_domain)
or not all(map(math.isfinite, features))):
raise IndexError(f"Features are outside the CVT domain: {features}")
centers = self.cluster_centers
n_centers = self._shape[0]
if (type(centers) is np.ndarray and centers.ndim == 2 and len(centers) >= n_centers
and centers.dtype.kind == "f" and centers.dtype.itemsize <= 8
and type(features) in (Features, np.ndarray, tuple, list)):
descriptors = np.asarray(features)
if descriptors.ndim == 1 and descriptors.dtype.kind in "biuf" and descriptors.dtype.itemsize <= 8:
if (_kernels is not None and n_centers >= 64 and centers.shape[1] == descriptors.size == 2
and centers.dtype == descriptors.dtype == np.float64
and centers.flags.c_contiguous and centers.flags.aligned):
nearest = _kernels.nearest_centroid_2d(centers[:n_centers], descriptors[0], descriptors[1])
if nearest >= 0:
return (np.intp(nearest),)
deltas = np.ascontiguousarray(centers[:n_centers] - descriptors)
squares = np.square(deltas, out=deltas)
# Keep the usual double-precision square root and tie order.
distances = np.sqrt(np.sum(squares, axis=1), dtype=np.float64)
nearest = np.argmin(distances)
distance = distances[nearest]
if math.isnan(distance) or math.sqrt(np.finfo(squares.dtype).tiny) <= distance < math.inf:
return (nearest,)
return _stable_nearest(centers[:n_centers], descriptors)
# Preserve per-centroid arithmetic for custom descriptor or array types.
dists = np.empty(n_centers)
for i in range(len(dists)):
dists[i] = math.sqrt(np.sum(np.square(centers[i] - features)))
return (np.argmin(dists),)
[docs]
@registry.register
class AutoScalingGrid(Grid):
"""Rebuild a grid as its observed objective or descriptor ranges change.
Each enabled axis family is checked independently. The first finite
descriptor vector can bootstrap initially unbounded axes before the
normal rescaling interval. With ``rescaling_period <= 0``, automatic
rescaling is disabled.
:param scaling_containers: Preferred source of records on rebuild.
If empty, use immediate parents or the entries in this grid.
:param fitness_scaling: Update the objective bounds.
:param features_scaling: Update descriptor bounds and cell widths.
:param rescaling_period: Candidate interval between automatic
rescale checks after a rebuild.
"""
scaling_containers: Sequence[Container]
fitness_scaling: bool
features_scaling: bool
rescaling_period: int
@property
def _allows_unbounded_initial_domain(self):
return self.features_scaling and self.rescaling_period > 0
def __init__(self, iterable: Optional[Iterable] = None,
shape: Union[ShapeLike, int] = (1,), max_items_per_bin: int = 1,
scaling_containers: Sequence[Container] = (),
fitness_scaling: bool = True,
features_scaling: bool = True,
rescaling_period: int = 1,
**kwargs: Any) -> None:
self.scaling_containers = scaling_containers
self.fitness_scaling = fitness_scaling
self.features_scaling = features_scaling
self.rescaling_period = rescaling_period # max(rescaling_period, 1)
self._nb_rescaled = 0
self._last_nb_rescaled = 0
super().__init__(iterable, shape, max_items_per_bin, **kwargs)
[docs]
def rescale(self, fitness_domain: Sequence[DomainLike], features_domain: Sequence[DomainLike]) -> None:
#print(f"# rescale {features_domain} {len(self)}")
# Identify which individuals should be added after the rescaling
"""Rebuild the cells with explicit objective and descriptor bounds.
Read records from scaling containers, parents, or the retained grid
before clearing it. Reapply admission to those records in order.
Entries that fail readmission are omitted from the rebuilt grid.
"""
self._validate_descriptor_domain(features_domain)
if len(self.scaling_containers) > 0:
inds = flatten_seq_of_seq(self.scaling_containers)
elif len(self.parents) > 0:
inds = self.all_parents_inds()
else:
inds = list(self)
# Rescale the container
self.clear()
self.fitness_domain = fitness_domain
self.features_domain = features_domain
self._init_grid()
for i in inds:
try:
super().add(i)
except Exception:
pass
#print(f"# rescale flatten: {len(flatten_seq_of_seq(self.scaling_containers))} {len(self)}")
def _recompute_fitness_extrema(self, new_ind_fits: Sequence[FitnessLike]) -> Sequence[DomainLike]:
assert(len(new_ind_fits) > 0)
maxima = np.array(new_ind_fits[0])
minima = np.array(new_ind_fits[0])
for ind in self:
ind_f = np.array(self.get_ind_fitness(ind).values)
for i in range(len(maxima)):
if ind_f[i] > maxima[i]:
maxima[i] = ind_f[i]
elif ind_f[i] < minima[i]:
minima[i] = ind_f[i]
for f in new_ind_fits:
ind_f = np.array(f)
for i in range(len(maxima)):
if ind_f[i] > maxima[i]:
maxima[i] = ind_f[i]
elif ind_f[i] < minima[i]:
minima[i] = ind_f[i]
return tuple(zip(minima, maxima))
def _recompute_features_extrema(self, new_ind_fts: Sequence[FeaturesLike]) -> Sequence[DomainLike]:
assert(len(new_ind_fts) > 0)
maxima = np.array(new_ind_fts[0])
minima = np.array(new_ind_fts[0])
for ind in self:
ind_f = np.array(self.get_ind_features(ind))
for i in range(len(maxima)):
if ind_f[i] > maxima[i]:
maxima[i] = ind_f[i]
elif ind_f[i] < minima[i]:
minima[i] = ind_f[i]
for f in new_ind_fts:
ind_f = np.array(f)
for i in range(len(maxima)):
if ind_f[i] > maxima[i]:
maxima[i] = ind_f[i]
elif ind_f[i] < minima[i]:
minima[i] = ind_f[i]
return tuple(zip(minima, maxima))
## @brief Compute candidate extrema and rebuild if either enabled domain changes.
# @param inds Candidate batch considered before admission.
# @details Use finite, dimensionally valid observations. Compare fitness
# and descriptor domains separately so an unchanged descriptor range
# cannot suppress a fitness-only rebuild.
def _add_rescaling(self, inds: Sequence[IndividualLike]) -> None:
# self._nb_rescaled += len(inds)
# if self.rescaling_period <= 0 or self._nb_rescaled - self._last_nb_rescaled < self.rescaling_period:
# return
#
fits = []
fts = []
valid_inds = []
# Iterate and find valid inds, their fitness and feature descriptors
for ind in inds:
fit = self.get_ind_fitness(ind)
ft = self.get_ind_features(ind)
if not fit.valid or len(fit.values) != len(self.fitness_domain) or len(ft) != len(self.features_domain):
continue
if not all(map(math.isfinite, fit.values)) or not all(map(math.isfinite, ft)):
continue
# If needed, check if fitness and features are within bounds
if not self.fitness_scaling and not self.in_bounds(fit.values, self.fitness_domain):
continue
if not self.features_scaling and not self.in_bounds(ft, self.features_domain):
continue
valid_inds.append(ind)
fits.append(fit)
fts.append(ft)
if len(valid_inds) == 0:
return
# Rescale grid
new_fit_domain = self.fitness_domain
new_ft_domain = self.features_domain
rescale = False
if self.fitness_scaling:
new_fit_domain = self._recompute_fitness_extrema(fits)
rescale = new_fit_domain != tuple(map(tuple, self.fitness_domain))
if self.features_scaling:
new_ft_domain = self._recompute_features_extrema(fts)
rescale |= new_ft_domain != tuple(map(tuple, self.features_domain))
if rescale:
self.rescale(new_fit_domain, new_ft_domain)
self._last_nb_rescaled = self._nb_rescaled
def _maybe_rescale(self, individuals: Sequence[IndividualLike]) -> None:
self._nb_rescaled += len(individuals)
if self.rescaling_period <= 0 or not individuals:
return
needs_initial_bounds = self.features_scaling and not np.isfinite(self.features_domain).all()
if needs_initial_bounds or self._nb_rescaled - self._last_nb_rescaled >= self.rescaling_period:
self._add_rescaling(individuals)
def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool = False) -> Optional[int]:
"""Check automatic rescaling before admitting an individual."""
self._maybe_rescale([individual])
return super().add(individual, raise_if_not_added_to_parents)
def update(self, iterable: Iterable, ignore_exceptions: bool = True, issue_warning: bool = False) -> int:
"""Materialise the input once, rescale as needed, then admit candidates in order."""
individuals = list(iterable)
self._maybe_rescale(individuals)
return super().update(individuals, ignore_exceptions, issue_warning)
## MODELINE "{{{1
## vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
## vim:foldmethod=marker