# 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 Archive storage, validation, parent admission, and decorator contracts.
"""TODO"""
#from __future__ import annotations
__all__ = ["BackendLike", "SimpleOrderedSet", "ContainerLike", "Container", "ContainerDecorator"]
########### IMPORTS ########### {{{1
import sys
from copy import deepcopy
import warnings
import math
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
from typing_extensions import runtime, Protocol
import traceback
import deprecation
import functools
from itertools import islice, zip_longest
import sortedcollections
from qdpy.utils import *
from qdpy.phenotype import *
from qdpy.phenotype import _COPY_ATOMS, _FEATURE_FIELDS, _FITNESS_FIELDS, _flat_values
from qdpy.base import *
from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
########### BACKEND CLASSES ########### {{{1
[docs]
@registry.register
class SimpleOrderedSet(MutableSet[T], Sequence[T]):
"""Store unique hashable entries in insertion order with integer indexing.
Equality controls uniqueness. Re-adding an equal entry keeps the
original entry and index. Keep the hash-relevant part of a genome
unchanged while stored.
"""
_items: List[T] # Internal storage
def __init__(self, iterable: Optional[Iterable] = None) -> None:
self._items = []
if iterable is not None:
self.update(iterable)
def __len__(self) -> int:
return len(self._items)
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, s: slice) -> Sequence[T]: ...
def __getitem__(self, key):
if isinstance(key, slice):
raise NotImplementedError
return self._items[key]
def __contains__(self, key: Any) -> bool:
return key in self._items
def __iter__(self) -> Iterator[T]:
return iter(self._items)
def __reversed__(self) -> Iterator[T]:
return reversed(self._items)
def __repr__(self) -> str:
if not self:
return "%s()" % (self.__class__.__name__,)
return "%s(%r)" % (self.__class__.__name__, list(self))
def __delitem__(self, idx) -> None:
del self._items[idx]
def count(self, key: T) -> int:
return 1 if key in self else 0
def index(self, key: T, start: int = 0, stop: int = sys.maxsize) -> int:
return self._items.index(key, start, stop)
def add(self, key: T) -> None:
"""Add ``key`` to this SimpleOrderedSet, if it is not already present. """
try:
self._items.index(key)
except ValueError:
self._items.append(key)
def discard(self, key: T) -> None:
"""Discard ``key`` in this SimpleOrderedSet. Does not raise an exception if absent."""
try:
self._items.remove(key)
except ValueError:
return
def update(self, iterable: Iterable) -> None:
"""Add the items in ``iterable``, if they are not already present in the SimpleOrderedSet. """
try:
for item in iterable:
self.add(item)
except TypeError:
raise ValueError(f"Argument needs to be an iterable, got {type(iterable)}")
class _IndexedOrderedSet(sortedcollections.OrderedSet):
"""Provide the positional lookup and deletion required by an archive."""
def __getstate__(self):
# Rebuild the hash index and insertion counter from the live entries.
return list(self)
def __setstate__(self, items):
self.__init__(items)
def index(self, value) -> int:
# OrderedSet returns the insertion serial. Its sorted mapping of
# live serials gives the current position even after deletions.
return self._nums.bisect_left(super().index(value))
def __delitem__(self, index: int) -> None:
self.discard(self[index])
BackendLike = Union[MutableSequence[T], SimpleOrderedSet[T]]
_APPEND_PARENT_FIELDS = frozenset((
"items", "parents", "only_add_accepted_inds_to_parents", "disable_parents_pickling",
"fitness_domain", "features_domain", "fitness_score_names", "features_score_names",
"fitness_weights", "recentness", "name", "_capacity", "_size", "_best",
"_best_fitness", "_best_features", "_nb_discarded", "_nb_rejected", "_nb_added",
))
########### CONTAINER CLASSES ########### {{{1
[docs]
@runtime
class ContainerLike(Protocol):
"""Structural interface for archives and archive decorators.
Optimisers use the archive's fitness and descriptor accessors, even
when a candidate carries a separate fitness object or named scores.
"""
def all_parents_inds(self) -> Sequence[IndividualLike]: ...
def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool = False) -> Optional[int]: ...
def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None: ...
def update(self, iterable: Iterable, ignore_exceptions: bool = True, issue_warning: bool = False) -> int: ...
def clear(self, also_from_parents: bool = False) -> None: ...
def novelty(self, individual: IndividualLike, **kwargs): ...
def novelty_local_competition(self, individual: IndividualLike, **kwargs): ...
def qd_score(self, normalized: bool = True) -> float: ...
def to_grid(self, shape: Union[ShapeLike, int], max_items_per_bin: int = 1, capacity: Optional[float] = None, **kwargs: Any) -> Any: ...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator: ...
def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike: ...
def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike: ...
def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs): ...
@property
def capacity(self) -> float: ...
@property
def free(self) -> float: ...
@property
def size(self) -> int: ...
@property
def best(self) -> Any: ...
@property
def best_fitness(self) -> Optional[FitnessLike]: ...
@property
def best_features(self) -> Optional[FeaturesLike]: ...
@property
def nb_discarded(self) -> int: ...
@property
def nb_added(self) -> int: ...
@property
def nb_rejected(self) -> int: ...
@property
def nb_operations(self) -> int: ...
@property
def fitness_extrema(self) -> Optional[Sequence[DomainLike]]: ...
@property
def features_extrema(self) -> Optional[Sequence[DomainLike]]: ...
fitness_domain: Optional[Sequence[DomainLike]]
features_domain: Optional[Sequence[DomainLike]]
fitness_score_names: Sequence[str]
features_score_names: Sequence[str]
# TODO verify that containers are thread-safe
[docs]
@registry.register
class Container(ContainerLike, Sequence, Summarisable, Copyable, CreatableFromConfig):
"""Store evaluated candidates subject to capacity and domain bounds.
Each declared objective and descriptor coordinate has a closed
interval. Omit a domain to leave its vector unbounded. An evaluated
candidate needs nonempty fitness without NaN values.
:param iterable: Initial candidates, admitted in order by update.
:param storage_type: Storage implementation or supported storage name.
The default list compares genomes for duplicates. Use ``"orderedset"``
for indexed lookup when candidates are hashable and their genomes
stay unchanged while stored.
:param parents: Archives offered candidates for evaluation history.
:param fitness_domain: One closed interval per objective.
:param features_domain: One closed interval per behaviour descriptor.
:param fitness_score_names: Named scores used as objectives, in order.
:param features_score_names: Named scores used as descriptors, in order.
:param fitness_weights: Comparison weights to apply in this container.
:param capacity: Total local capacity. None allows unbounded storage.
:param name: Display name used by loggers and configuration.
:param only_add_accepted_inds_to_parents: Forward local admissions
only. Otherwise a rejected local candidate can reach the parents.
:param disable_parents_pickling: Omit parent links from result files
by default. Set false to keep the immediate links.
The archive stores candidate objects. Mutate a copy during variation,
and serialise archive updates through the controlling process.
"""
name: Optional[str]
items: BackendLike[IndividualLike]
#depot: Optional[BackendLike[IndividualLike]]
parents: Sequence[ContainerLike]
fitness_domain: Optional[Sequence[DomainLike]]
features_domain: Optional[Sequence[DomainLike]]
fitness_score_names: Sequence[str]
features_score_names: Sequence[str]
recentness: MutableSequence[int]
fitness_weights: Optional[FitnessValuesLike]
_capacity: float
_size: int
_best: Optional[IndividualLike]
_best_fitness: Optional[FitnessLike]
_best_features: Optional[FeaturesLike]
_nb_discarded: int
_nb_added: int
_nb_rejected: int
def __init__(self, iterable: Optional[Iterable] = None,
storage_type: Union[str,BackendLike,Type[BackendLike]] = list, parents: Optional[Sequence[ContainerLike]] = None,
fitness_domain: Optional[Sequence[DomainLike]] = None,
features_domain: Optional[Sequence[DomainLike]] = None,
fitness_score_names: Sequence[str] = (), features_score_names: Sequence[str] = (),
fitness_weights: Optional[FitnessValuesLike] = None,
capacity: Optional[float] = None, name: Optional[str] = None,
only_add_accepted_inds_to_parents: bool = False,
disable_parents_pickling: bool = True,
**kwargs: Any) -> None:
self.items = self._create_storage(storage_type)
self.parents = [] if parents is None else parents
self.only_add_accepted_inds_to_parents = only_add_accepted_inds_to_parents
self.disable_parents_pickling = disable_parents_pickling
self.fitness_domain = fitness_domain
if self.fitness_domain is not None:
for f in self.fitness_domain:
if not is_iterable(f) or len(f) != 2:
raise ValueError("``fitness_domain`` must be a sequence of 2-tuples.")
self.features_domain = features_domain
if self.features_domain is not None:
for f in self.features_domain:
if not is_iterable(f) or len(f) != 2:
raise ValueError("``features_domain`` must be a sequence of 2-tuples.")
self.fitness_score_names = fitness_score_names
self.features_score_names = features_score_names
self.fitness_weights = fitness_weights
self.recentness = []
self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
self._capacity = math.inf if capacity is None else capacity
self._size = 0
self._best = None
self._best_fitness = None
self._best_features = None
self._nb_discarded = 0
self._nb_rejected = 0
self._nb_added = 0
if iterable is not None:
self.update(iterable)
def _create_storage(self, storage_type: Union[str,BackendLike,Type[BackendLike]] = list):
if isinstance(storage_type, str):
t = storage_type.lower()
if t == "list":
return list()
elif t == "simpleorderedset":
return SimpleOrderedSet()
elif t == "orderedset":
return _IndexedOrderedSet()
elif t == "indexableset":
return sortedcollections.IndexableSet()
else:
raise ValueError(f"Unknown class name specified for ``storage_type`` ({storage_type}). Known names include 'list', 'simpleorderedset', 'orderedset,' and 'indexableset'.")
elif storage_type is sortedcollections.OrderedSet:
return _IndexedOrderedSet()
elif isinstance(storage_type, Type): # type: ignore
return storage_type() # type: ignore
else:
#elif isinstance(storage_type, BackendLike):
return storage_type
#else:
#raise ValueError("``storage_type`` must be either a BackendLike object or the class of a BackendLike or a string containing the name of the BackendLike class.")
def __getstate__(self):
odict = self.__dict__.copy()
if odict['disable_parents_pickling'] and 'parents' in odict:
del odict['parents']
return odict
def __setstate__(self, state):
state.setdefault("parents", [])
if type(state.get("items")) is sortedcollections.OrderedSet:
state["items"] = _IndexedOrderedSet(state["items"])
self.__dict__.update(state)
@property
def capacity(self) -> float:
"""Return the capacity of the container (i.e. maximal number of items/spots/bins/etc). Can be math.inf."""
return self._capacity
@property
def free(self) -> float:
"""Return the number of free spots in the container. Can be math.inf."""
return self._capacity - self._size
@property
def size(self) -> int:
"""Return the size of the container (i.e. number of items, spots, bins, etc)."""
return self._size
@property
def best(self) -> Any:
"""Return the best individual. """
return self._best
@property
def best_fitness(self) -> Optional[FitnessLike]:
"""Return the fitness values of the individual with the best quality, or None. """
return self._best_fitness
@property
def best_features(self) -> Optional[FeaturesLike]:
"""Return the features values of the individual with the best quality, or None. """
return self._best_features
@property
def nb_discarded(self) -> int:
"""Return the number of individuals discarded by the container since its creation. """
return self._nb_discarded
@property
def nb_added(self) -> int:
"""Return the number of individuals added into the container since its creation. """
return self._nb_added
@property
def nb_rejected(self) -> int:
"""Return the number of individuals rejected (when added) by the container since its creation. """
return self._nb_rejected
@property
def nb_operations(self) -> int:
"""Return the number of adds, modifications and discards since the creation of this container. """
return self._nb_added + self._nb_discarded
@property
def fitness_extrema(self) -> Optional[Sequence[DomainLike]]:
"""Return the extrema values of the fitnesses of the stored individuals."""
if len(self) == 0:
return None
minima = list(self.get_ind_fitness(self[0]).values)
maxima = minima.copy()
for ind in self:
ind_f = self.get_ind_fitness(ind).values
for i in range(len(maxima)):
value = ind_f[i]
if value > maxima[i]:
maxima[i] = value
elif value < minima[i]:
minima[i] = value
return tuple(zip(minima, maxima))
@property
def features_extrema(self) -> Optional[Sequence[DomainLike]]:
"""Return the extrema values of the features of the stored individuals."""
size = len(self)
if size == 0:
return None
if size >= 8:
extrema = self._float_feature_extrema()
if extrema is not None:
return extrema
maxima = np.array(self.get_ind_features(self[0])) # type: ignore
minima = np.array(self.get_ind_features(self[0])) # type: ignore
for ind in self:
ind_f = 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]
return tuple(zip(minima, maxima))
def _float_feature_extrema(self) -> Optional[Sequence[DomainLike]]:
"""Reduce built-in float descriptors in column order."""
if (self.features_score_names
or getattr(self.get_ind_features, "__func__", None) is not Container.get_ind_features):
return None
rows = []
for ind in self:
if type(ind) is not Individual:
return None
features = ind.features
if type(features) is not Features:
return None
values = features.values
if type(values) is not tuple and type(values) is not list:
return None
rows.append(values)
extrema = []
# Like the scalar path, min/max retain the first sign on tied
# zeroes and ignore NaNs that follow an initial numeric value.
# Missing values in ragged rows also go through the scalar path.
for column in zip_longest(*rows):
for value_type in map(type, column):
if value_type is not float and value_type is not np.float64:
return None
extrema.append((np.float64(min(column)), np.float64(max(column))))
return tuple(extrema)
def all_parents_inds(self) -> Sequence[IndividualLike]:
"""Return immediate parent entries in parent order, including repeated entries."""
return flatten_seq_of_seq(self.parents) # type: ignore
def size_str(self) -> str:
"""Return a string describing the fullness of the container."""
if math.isinf(self.capacity):
return str(self.size)
else:
return "%i/%i" % (self.size, self.capacity)
def __len__(self) -> int:
return len(self.items)
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
def __getitem__(self, key):
if isinstance(key, slice):
raise NotImplementedError
return self.items[key]
def __contains__(self, key: Any) -> bool:
return key in self.items
def __iter__(self) -> Iterator[IndividualLike]:
return iter(self.items)
# def __reversed__(self) -> Iterator[IndividualLike]:
# return reversed(self.items)
def __repr__(self) -> str:
if not self:
return "%s()" % (self.__class__.__name__,)
return "%s(%r)" % (self.__class__.__name__, list(self))
def _add_to_collection(self, collection: BackendLike[IndividualLike], individual: IndividualLike) -> Tuple[bool,int]:
"""Add ``individual`` to ``collection``.
Return a tuple containing (added, index), with ``added`` a bool saying whether ``individual`` was added or not to ``collection``, and ``index`` the index in the ``collection``.
``collection`` can be a MutableSequence or an ordered set implementing Sequence and MutableSet."""
old_len: int = len(collection)
if isinstance(collection, MutableSet):
collection.add(individual)
if len(collection) == old_len:
return False, collection.index(individual)
else:
return True, len(collection) - 1
elif isinstance(collection, MutableSequence):
added: bool = False
try:
index: int = collection.index(individual)
except ValueError:
collection.append(individual)
index = len(collection) - 1
added = True
return added, index
else:
raise ValueError("collection must be an ordered set implementing MutableSet or a Sequence")
def in_bounds(self, val: Any, domain: Any) -> bool:
"""Check inclusive bounds. An empty or omitted domain allows any value."""
if domain is None or len(domain) == 0:
return True
return in_bounds(val, domain)
[docs]
def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
"""Resolve the descriptor vector used by this container.
Select configured named scores in descriptor order when names are
supplied. Otherwise use the candidate's feature object.
"""
if len(self.features_score_names) == 0:
return individual.features
else:
return individual.scores.to_features(self.features_score_names, *args, **kwargs)
[docs]
def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
"""Resolve the fitness used by this container for admission and ranking.
Select named scores in objective order or use the candidate's fitness.
When the container applies different weights, return a weighted copy
so other archives sharing the same candidate keep their own semantics.
"""
if len(self.fitness_score_names) == 0:
return self._fitness_with_container_weights(individual.fitness)
else:
return individual.scores.to_fitness(self.fitness_score_names, *args, weights=self.fitness_weights, **kwargs)
def _fitness_with_container_weights(self, fitness: FitnessLike) -> FitnessLike:
if self.fitness_weights is None or tuple(fitness.weights) == tuple(self.fitness_weights):
return fitness
weighted = copy.copy(fitness)
weighted.weights = tuple(self.fitness_weights)
if not isinstance(weighted, Fitness):
weighted.values = fitness.values
return weighted
def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
"""Store the raw fitness in the configured location.
Write named objective scores when configured. Otherwise replace the
candidate's fitness object, applying the container's weights if set.
"""
if len(self.fitness_score_names) == 0:
individual.fitness = self._fitness_with_container_weights(fitness)
else:
for name,val in zip(self.fitness_score_names,fitness.values):
individual.scores[name] = val
def _check_if_can_be_added(self, individual: IndividualLike) -> None:
"""Validate the resolved objective and descriptor vectors.
Reject invalid fitness and vectors outside declared coordinate
bounds. This step runs before storage or parent forwarding.
"""
# Retrieve features and fitness from individual
#ind_fitness: FitnessValuesLike = self._get_fitness_from_ind(individual)
#ind_features: FeaturesLike = self._get_features_from_ind(individual)
exc = None
fit = self.get_ind_fitness(individual)
if not fit.valid or any(math.isnan(value) for value in fit.values):
exc = ValueError(f"Fitness is not valid.")
# Check if fitness and features are out of bounds
if not self.in_bounds(fit.values, self.fitness_domain):
exc = ValueError(f"fitness ({str(fit)}) out of bounds ({str(self.fitness_domain)}).")
ft = self.get_ind_features(individual)
if not self.in_bounds(ft, self.features_domain):
#exc = ValueError(f"features ({str(ft)}) out of bounds ({str(self.features_domain)}).")
exc = ValueError(f"features ({str(ft)}) out of bounds ({str(self.features_domain)}). fitness={fit}. scores={individual.scores}") # XXX
if exc:
self._nb_rejected += 1
raise exc
## @brief Commit local storage and eviction after required parent admission.
# @param individual Candidate passed by the admission policy.
# @param raise_if_not_added_to_parents Whether parent errors must propagate.
# @param only_to_parents Forward the candidate without a local insertion.
# @param replace_index Optional local storage index of the incumbent.
# @return The reported storage index, or None for a parent-only offer.
# @details Stage a new entry before contacting the parents, then update
# local counters and evict the incumbent after those calls succeed.
# Restore the prior local best and remove the staged entry on failure.
# An equal reevaluation needs its incumbent removed before insertion.
def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool,
only_to_parents: bool, replace_index: Optional[int] = None) -> Optional[int]:
"""Store a candidate and commit any local eviction after parent admission."""
if not only_to_parents and replace_index is None and self.free < 1 and self._index_of(individual) is None:
self._nb_rejected += 1
raise IndexError("No free slot available in this container.")
if only_to_parents and len(self.parents) == 0:
self._nb_rejected += 1
raise ValueError("`only_to_parents` can only be set to True if at least one parent is specified.")
added = False
index = None
if not only_to_parents:
added, index = self._add_to_collection(self.items, individual)
replaces_equal = replace_index is not None and index == replace_index
previous_best = self._best, self._best_fitness, self._best_features
try:
if added:
self._consider_for_best(individual)
if not self.only_add_accepted_inds_to_parents or added or replaces_equal:
self._add_to_parents(individual, raise_if_not_added_to_parents)
except Exception:
if added:
del self.items[index]
self._best, self._best_fitness, self._best_features = previous_best
raise
if replaces_equal:
# Storage keeps one entry for equal candidates.
self._discard_by_index(self.items[replace_index], replace_index)
replace_index = None
added, index = self._add_to_collection(self.items, individual)
self._consider_for_best(individual)
if added:
self.recentness.append(self._nb_added)
self._size += 1
self._nb_added += 1
if replace_index is not None:
self._discard_by_index(self.items[replace_index], replace_index)
index -= 1
return index
## @brief Forward a candidate to each immediate parent in order.
# @param individual Candidate to offer.
# @param require_admission Whether to raise when a parent insertion fails.
# @details Restore built-in archives after a failure in a parent graph
# with multiple branches. Custom parents can have external effects.
def _add_to_parents(self, individual: IndividualLike, require_admission: bool) -> None:
if not self.parents:
return
snapshots = []
if require_admission and len(self.parents) > 1:
if self._can_undo_parent_appends(individual):
self._add_to_append_only_parents(individual)
return
snapshots = self._snapshot_parents()
snapshotted = {id(parent) for parent, _ in snapshots}
updated_parents = []
for parent in self.parents:
try:
previous_additions = parent.nb_added if require_admission else None
parent.add(individual, raise_if_not_added_to_parents=require_admission)
if (previous_additions is not None and id(parent) not in snapshotted
and parent.nb_added > previous_additions):
updated_parents.append(parent)
except Exception as exc:
if not require_admission:
continue
self._nb_rejected += 1
for updated_parent in reversed(updated_parents):
try:
updated_parent.discard(individual)
except Exception as e:
exc.add_note(f"Could not undo a parent insertion: {e}")
for archive, state in snapshots:
archive.__dict__.clear()
archive.__dict__.update(state)
raise ValueError(f"Individual could not be added to the parents: {exc}") from exc
def _can_undo_parent_appends(self, individual):
"""Restrict the short undo record to plain append-only parent storage."""
if (type(individual) is not Individual or type(individual.fitness) is not Fitness
or type(individual.features) is not Features
or individual.fitness.__dict__.keys() != _FITNESS_FIELDS
or individual.features.__dict__.keys() != _FEATURE_FIELDS
or not _flat_values(individual.fitness.values, tuple)
or not _flat_values(individual.fitness.weights, tuple)
or not (_flat_values(individual.features.values, tuple)
or _flat_values(individual.features.values, list))
or not all(type(gene) in _COPY_ATOMS for gene in individual)):
return False
return all(
type(parent) is Container and not parent.parents
and not parent.fitness_score_names and not parent.features_score_names
and type(parent.items) in (list, _IndexedOrderedSet) and type(parent.recentness) is list
and (parent._best_fitness is None or type(parent._best_fitness) is Fitness)
and parent.__dict__.keys() == _APPEND_PARENT_FIELDS
for parent in self.parents
)
## @brief Take a short pre-admission record and rebuild a snapshot only after rejection.
def _add_to_append_only_parents(self, individual):
parents = {id(parent): parent for parent in self.parents}
undo = [(parent, vars(parent).copy(), len(parent.items), len(parent.recentness))
for parent in parents.values()]
try:
for parent in self.parents:
parent.add(individual, raise_if_not_added_to_parents=True)
except Exception as error:
self._nb_rejected += 1
memo = {id(self): self, **parents}
for _, state, size, _ in undo:
items = state["items"]
prefix = items[:size] if type(items) is list else list(islice(items, size))
memo.update((id(elite), elite) for elite in prefix)
memo[id(items)] = prefix if type(items) is list else _IndexedOrderedSet(prefix)
memo[id(state["parents"])] = state["parents"]
for _, state, _, recent in undo:
original = state["recentness"]
memo[id(original)] = deepcopy(original[:recent], memo)
snapshots = [(parent, deepcopy(state, memo)) for parent, state, _, _ in undo]
for parent, state in snapshots:
vars(parent).clear()
vars(parent).update(state)
raise ValueError(f"Individual could not be added to the parents: {error}") from error
def _snapshot_parents(self):
"""Copy built-in archive bookkeeping while retaining archive and elite identities."""
pending = list(self.parents)
seen = {id(self)}
archives = []
memo = {id(self): self}
for parent in pending:
if id(parent) in seen:
continue
seen.add(id(parent))
memo[id(parent)] = parent
parents = getattr(parent, "parents", ())
pending.extend(parents)
if isinstance(parent, Container) and type(parent).__module__.startswith("qdpy.containers."):
archives.append(parent)
memo[id(parents)] = parents
for elite in parent:
memo[id(elite)] = elite
return [(archive, deepcopy(archive.__dict__, memo)) for archive in archives]
def _consider_for_best(self, individual: IndividualLike) -> None:
fitness = self.get_ind_fitness(individual)
if self._best_fitness is None or fitness.dominates(self._best_fitness):
features = self.get_ind_features(individual)
self._best = individual
self._best_fitness = fitness
self._best_features = features
def _recompute_best(self) -> None:
self._best = self._best_fitness = self._best_features = None
for individual in self.items:
self._consider_for_best(individual)
def _set_fitness_weights(self, weights: FitnessValuesLike) -> None:
previous = self.fitness_weights
self.fitness_weights = weights
if previous is None or tuple(previous) != tuple(weights):
self._recompute_best()
def _index_of(self, individual: IndividualLike) -> Optional[int]:
try:
return self.items.index(individual)
except (ValueError, KeyError):
return None
[docs]
def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool = False) -> Optional[int]:
"""Validate one candidate and return its local storage index.
An equal entry can return its existing index. Grid and novelty
subclasses can decline a candidate locally and return None.
Pass ``raise_if_not_added_to_parents=True`` to propagate parent
insertion failures and preserve the current local entry. A failure
across built-in parents restores the earlier branch contents.
Custom parents are responsible for their own external side effects.
"""
# Retrieve features and fitness from individual and check if they are not out-of-bounds
self._check_if_can_be_added(individual)
# Add
return self._add_internal(individual, raise_if_not_added_to_parents, False)
def _discard_by_index(self, individual: IndividualLike, idx: Optional[int] = None, also_from_parents: bool = False) -> None:
"""Remove ``individual`` of the container. If ``also_from_parents`` is True, discard it also from the parents, if they exist. Use the indexes ``idx`` if it is provided."""
# Remove from parents
if also_from_parents:
try:
for p in self.parents:
p.discard(individual, also_from_parents = True)
except Exception as e:
pass
# Remove from container
if idx is None:
idx = self._index_of(individual)
if idx is None:
return
removed_best = self.items[idx] is self._best
del self.items[idx]
del self.recentness[idx]
self._size -= 1
self._nb_discarded += 1
if removed_best:
self._recompute_best()
if self._size < 0:
raise RuntimeError("`self.size` < 0 !")
[docs]
def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
"""Remove the matching entry if present.
Use ``also_from_parents`` to request removal from parent history
as well. Removing the cached best triggers recomputation from the
remaining entries.
"""
self._discard_by_index(individual, also_from_parents=also_from_parents)
[docs]
def update(self, iterable: Iterable, ignore_exceptions: bool = True, issue_warning: bool = False) -> int:
"""Offer each candidate for insertion and count reported local indexes.
The count can include an existing equal entry. Use the change in
``nb_added`` to count actual insertions. With ``ignore_exceptions=True``,
validation failures can be offered to parents instead. Set
``issue_warning=True`` to report them. Capacity and parent storage
errors can still propagate.
"""
nb_inserted: int = 0
item_index: Optional[int] = None
try:
for item in iterable:
only_to_parents = False
try:
self._check_if_can_be_added(item)
except Exception as e:
only_to_parents = True
if ignore_exceptions and issue_warning:
if isinstance(e,IndexError):
warnings.warn(f"Adding individual failed (index out of bounds): {str(e)}")
elif isinstance(e,ValueError):
warnings.warn(f"Adding individual failed (attribute out of bounds): {str(e)}")
else:
warnings.warn(f"Adding individual failed: {str(e)}")
traceback.print_exc()
elif not ignore_exceptions:
raise e
if not only_to_parents or len(self.parents) > 0:
item_index = self._add_internal(item, True, only_to_parents)
if item_index is not None:
nb_inserted += 1
except TypeError:
raise ValueError(f"Argument needs to be an Iterable, got {type(Iterable)}")
return nb_inserted
[docs]
def clear(self, also_from_parents: bool = False) -> None:
"""Remove all local entries and refresh the cached best.
With ``also_from_parents=True``, remove matching local entries from
the parents as well. Parent-only entries may remain.
"""
self._best = self._best_fitness = self._best_features = None
try:
for individual in list(self):
self.discard(individual, also_from_parents)
finally:
self._recompute_best()
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'self.clear(also_from_parents=True)' instead.")
def clear_all(self) -> None:
"""Clear all individual in the collection, and clear also those individuals in the parent containers."""
self.clear(also_from_parents = True)
def novelty(self, individual: IndividualLike, **kwargs):
"""Score novelty against immediate parent entries.
The metric uses the candidates' feature attributes. At least one
parent is required.
"""
if len(self.parents) == 0:
raise RuntimeError(f"At least one parent is necessary to assess novelty.")
return novelty(individual, self.all_parents_inds(), **kwargs)
def novelty_local_competition(self, individual: IndividualLike, **kwargs):
"""Score novelty and local competition against immediate parents.
Metric options such as ``k`` and ``ignore_first`` are forwarded.
At least one parent is required.
"""
if len(self.parents) == 0:
raise RuntimeError(f"At least one parent is necessary to assess novelty.")
return novelty_local_competition(individual, self.all_parents_inds(), **kwargs)
[docs]
def to_grid(self, shape: Union[ShapeLike, int],
max_items_per_bin: int = 1,
capacity: Optional[float] = None, **kwargs: Any) -> Any:
"""Re-admit the stored entries to a new descriptor grid.
Reuse declared domains by default. If absent, use the archive's
observed extrema. Supply explicit domains when converting an empty
archive. Named score selection and fitness weights are inherited
unless overridden.
:param shape: Number of cells per descriptor coordinate.
:param max_items_per_bin: Maximum number of local entries in one cell.
:param capacity: Total capacity override. None leaves it unbounded.
:param kwargs: Other Grid options such as domains or storage type.
:returns: A new grid containing the entries it admitted.
"""
if not 'fitness_domain' in kwargs:
kwargs['fitness_domain'] = self.fitness_domain if self.fitness_domain is not None else self.fitness_extrema
if not 'features_domain' in kwargs:
kwargs['features_domain'] = self.features_domain if self.features_domain is not None else self.features_extrema
if not 'fitness_score_names' in kwargs:
kwargs['fitness_score_names'] = self.fitness_score_names
if not 'features_score_names' in kwargs:
kwargs['features_score_names'] = self.features_score_names
if not 'fitness_weights' in kwargs:
kwargs['fitness_weights'] = self.fitness_weights
return qdpy.containers.Grid(self, shape=shape, max_items_per_bin=max_items_per_bin, capacity=capacity, **kwargs) # type: ignore
def _has_infinite_fitness_bounds(self) -> bool:
domain = self.fitness_domain
return domain is not None and any(
bound in (-math.inf, math.inf) for interval in domain for bound in interval
)
[docs]
def qd_score(self, normalized: bool = True) -> float:
"""Sum quality over all locally stored individuals.
With normalisation, measure each objective's improvement from the
worst domain endpoint and divide by the interval width. Use the
lower endpoint for maximisation and the upper for minimisation.
A collapsed interval uses a divisor of one. A populated archive
with an infinite fitness bound returns NaN when normalised. An
empty archive with a fitness domain has a score of zero. Use
``normalized=False`` to sum raw values without applying weights.
"""
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:
for ind in self:
ind_fit = self.get_ind_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
########### DECORATOR CLASSES ########### {{{2
[docs]
@registry.register
class ContainerDecorator(ContainerLike, Sequence, Summarisable, Copyable, CreatableFromConfig):
"""Forward the archive interface to a wrapped container.
Subclasses can intercept admission or transform measurements while
retaining the underlying collection and storage configuration.
"""
container: ContainerLike
name: Optional[str]
def __init__(self, container: ContainerLike,
name: Optional[str] = None,
**kwargs: Any) -> None:
self.container = container
self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
def __getstate__(self):
odict = self.__dict__.copy()
return odict
def __setstate__(self, state):
self.__dict__.update(state)
def __setattr__(self, attr, value):
if attr in self.__dict__:
self.__dict__[attr] = value
elif "container" in self.__dict__:
setattr(self.container, attr, value)
else:
self.__dict__[attr] = value
def __getattr__(self, attr):
if attr in self.__dict__:
return getattr(self, attr)
if "container" not in self.__dict__:
raise AttributeError
return getattr(self.container, attr)
def __len__(self) -> int:
return self.container.__len__()
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
def __getitem__(self, key):
return self.container.__getitem__(key)
def all_parents_inds(self) -> Sequence[IndividualLike]:
return self.container.all_parents_inds()
def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool = False) -> Optional[int]:
return self.container.add(individual, raise_if_not_added_to_parents)
def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
return self.container.discard(individual, also_from_parents)
update = functools.partialmethod(Container.update) # type: ignore
clear = functools.partialmethod(Container.clear) # type: ignore
def novelty(self, individual: IndividualLike, **kwargs):
return self.container.novelty(individual, **kwargs)
def novelty_local_competition(self, individual: IndividualLike, **kwargs):
return self.container.novelty_local_competition(individual, **kwargs)
def qd_score(self, normalized: bool = True) -> float:
return self.container.qd_score(normalized)
def to_grid(self, shape: Union[ShapeLike, int], max_items_per_bin: int = 1, capacity: Optional[float] = None, **kwargs: Any) -> Any:
return self.container.to_grid(shape, max_items_per_bin, capacity, **kwargs)
def __iter__(self) -> Iterator:
return self.container.__iter__()
def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
return self.container.get_ind_features(individual, *args, **kwargs)
def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
return self.container.get_ind_fitness(individual, *args, **kwargs)
def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
self.container.set_ind_fitness(individual, fitness, *args, **kwargs)
@property
def capacity(self) -> float:
return self.container.capacity
@property
def free(self) -> float:
return self.container.free
@property
def size(self) -> int:
return self.container.size
@property
def best(self) -> Any:
return self.container.best
@property
def best_fitness(self) -> Optional[FitnessLike]:
return self.container.best_fitness
@property
def best_features(self) -> Optional[FeaturesLike]:
return self.container.best_features
@property
def nb_discarded(self) -> int:
return self.container.nb_discarded
@property
def nb_added(self) -> int:
return self.container.nb_added
@property
def nb_rejected(self) -> int:
return self.container.nb_rejected
@property
def nb_operations(self) -> int:
return self.container.nb_operations
@property
def fitness_extrema(self) -> Optional[Sequence[DomainLike]]:
return self.container.fitness_extrema
@property
def features_extrema(self) -> Optional[Sequence[DomainLike]]:
return self.container.features_extrema
## MODELINE "{{{1
## vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
## vim:foldmethod=marker