22__all__ = [
"BackendLike",
"SimpleOrderedSet",
"ContainerLike",
"Container",
"ContainerDecorator"]
26from copy
import deepcopy
30from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, Mapping, overload
31from typing_extensions
import runtime, Protocol
35from itertools
import islice, zip_longest
36import sortedcollections
40from qdpy.phenotype import _COPY_ATOMS, _FEATURE_FIELDS, _FITNESS_FIELDS, _flat_values
42from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
51 """Store unique hashable entries in insertion order with integer indexing.
53 Equality controls uniqueness. Re-adding an equal entry keeps the
54 original entry and index. Keep the hash-relevant part of a genome
55 unchanged while stored.
60 def __init__(self, iterable: Optional[Iterable] =
None) ->
None:
62 if iterable
is not None:
65 def __len__(self) -> int:
69 def __getitem__(self, index: int) -> T: ...
72 def __getitem__(self, s: slice) -> Sequence[T]: ...
74 def __getitem__(self, key):
75 if isinstance(key, slice):
76 raise NotImplementedError
79 def __contains__(self, key: Any) -> bool:
82 def __iter__(self) -> Iterator[T]:
85 def __reversed__(self) -> Iterator[T]:
86 return reversed(self.
_items)
88 def __repr__(self) -> str:
90 return "%s()" % (self.__class__.__name__,)
91 return "%s(%r)" % (self.__class__.__name__, list(self))
93 def __delitem__(self, idx) -> None:
96 def count(self, key: T) -> int:
97 return 1
if key
in self
else 0
99 def index(self, key: T, start: int = 0, stop: int = sys.maxsize) -> int:
100 return self.
_items.index(key, start, stop)
102 def add(self, key: T) ->
None:
103 """Add ``key`` to this SimpleOrderedSet, if it is not already present. """
110 """Discard ``key`` in this SimpleOrderedSet. Does not raise an exception if absent."""
116 def update(self, iterable: Iterable) ->
None:
117 """Add the items in ``iterable``, if they are not already present in the SimpleOrderedSet. """
119 for item
in iterable:
122 raise ValueError(f
"Argument needs to be an iterable, got {type(iterable)}")
126 """Provide the positional lookup and deletion required by an archive."""
128 def __getstate__(self):
132 def __setstate__(self, items):
135 def index(self, value) -> int:
138 return self._nums.bisect_left(super().index(value))
140 def __delitem__(self, index: int) ->
None:
141 self.discard(self[index])
145BackendLike = Union[MutableSequence[T], SimpleOrderedSet[T]]
147_APPEND_PARENT_FIELDS = frozenset((
148 "items",
"parents",
"only_add_accepted_inds_to_parents",
"disable_parents_pickling",
149 "fitness_domain",
"features_domain",
"fitness_score_names",
"features_score_names",
150 "fitness_weights",
"recentness",
"name",
"_capacity",
"_size",
"_best",
151 "_best_fitness",
"_best_features",
"_nb_discarded",
"_nb_rejected",
"_nb_added",
160 """Structural interface for archives and archive decorators.
162 Optimisers use the archive's fitness and descriptor accessors, even
163 when a candidate carries a separate fitness object or named scores.
165 def all_parents_inds(self) -> Sequence[IndividualLike]: ...
167 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool =
False) -> Optional[int]: ...
168 def discard(self, individual: IndividualLike, also_from_parents: bool =
False) ->
None: ...
169 def update(self, iterable: Iterable, ignore_exceptions: bool =
True, issue_warning: bool =
False) -> int: ...
170 def clear(self, also_from_parents: bool =
False) ->
None: ...
171 def novelty(self, individual: IndividualLike, **kwargs): ...
172 def novelty_local_competition(self, individual: IndividualLike, **kwargs): ...
173 def qd_score(self, normalized: bool =
True) -> float: ...
174 def to_grid(self, shape: Union[ShapeLike, int], max_items_per_bin: int = 1, capacity: Optional[float] =
None, **kwargs: Any) -> Any: ...
175 def __len__(self) -> int: ...
176 def __iter__(self) -> Iterator: ...
177 def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike: ...
178 def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike: ...
179 def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs): ...
181 def capacity(self) -> float: ...
183 def free(self) -> float: ...
185 def size(self) -> int: ...
187 def best(self) -> Any: ...
189 def best_fitness(self) -> Optional[FitnessLike]: ...
191 def best_features(self) -> Optional[FeaturesLike]: ...
193 def nb_discarded(self) -> int: ...
195 def nb_added(self) -> int: ...
197 def nb_rejected(self) -> int: ...
199 def nb_operations(self) -> int: ...
201 def fitness_extrema(self) -> Optional[Sequence[DomainLike]]: ...
203 def features_extrema(self) -> Optional[Sequence[DomainLike]]: ...
204 fitness_domain: Optional[Sequence[DomainLike]]
205 features_domain: Optional[Sequence[DomainLike]]
206 fitness_score_names: Sequence[str]
207 features_score_names: Sequence[str]
213 """Store evaluated candidates subject to capacity and domain bounds.
215 Each declared objective and descriptor coordinate has a closed
216 interval. Omit a domain to leave its vector unbounded. An evaluated
217 candidate needs nonempty fitness without NaN values.
219 :param iterable: Initial candidates, admitted in order by update.
220 :param storage_type: Storage implementation or supported storage name.
221 The default list compares genomes for duplicates. Use ``"orderedset"``
222 for indexed lookup when candidates are hashable and their genomes
223 stay unchanged while stored.
224 :param parents: Archives offered candidates for evaluation history.
225 :param fitness_domain: One closed interval per objective.
226 :param features_domain: One closed interval per behaviour descriptor.
227 :param fitness_score_names: Named scores used as objectives, in order.
228 :param features_score_names: Named scores used as descriptors, in order.
229 :param fitness_weights: Comparison weights to apply in this container.
230 :param capacity: Total local capacity. None allows unbounded storage.
231 :param name: Display name used by loggers and configuration.
232 :param only_add_accepted_inds_to_parents: Forward local admissions
233 only. Otherwise a rejected local candidate can reach the parents.
234 :param disable_parents_pickling: Omit parent links from result files
235 by default. Set false to keep the immediate links.
237 The archive stores candidate objects. Mutate a copy during variation,
238 and serialise archive updates through the controlling process.
242 items: BackendLike[IndividualLike]
244 parents: Sequence[ContainerLike]
245 fitness_domain: Optional[Sequence[DomainLike]]
246 features_domain: Optional[Sequence[DomainLike]]
247 fitness_score_names: Sequence[str]
248 features_score_names: Sequence[str]
249 recentness: MutableSequence[int]
250 fitness_weights: Optional[FitnessValuesLike]
253 _best: Optional[IndividualLike]
254 _best_fitness: Optional[FitnessLike]
255 _best_features: Optional[FeaturesLike]
260 def __init__(self, iterable: Optional[Iterable] =
None,
261 storage_type: Union[str,BackendLike,Type[BackendLike]] = list, parents: Optional[Sequence[ContainerLike]] =
None,
262 fitness_domain: Optional[Sequence[DomainLike]] =
None,
263 features_domain: Optional[Sequence[DomainLike]] =
None,
264 fitness_score_names: Sequence[str] = (), features_score_names: Sequence[str] = (),
265 fitness_weights: Optional[FitnessValuesLike] =
None,
266 capacity: Optional[float] =
None, name: Optional[str] =
None,
267 only_add_accepted_inds_to_parents: bool =
False,
268 disable_parents_pickling: bool =
True,
269 **kwargs: Any) ->
None:
271 self.
parents = []
if parents
is None else parents
277 if not is_iterable(f)
or len(f) != 2:
278 raise ValueError(
"``fitness_domain`` must be a sequence of 2-tuples.")
282 if not is_iterable(f)
or len(f) != 2:
283 raise ValueError(
"``features_domain`` must be a sequence of 2-tuples.")
288 self.
name = name
if name
is not None else f
"{self.__class__.__name__}-{id(self)}"
289 self.
_capacity = math.inf
if capacity
is None else capacity
297 if iterable
is not None:
300 def _create_storage(self, storage_type: Union[str,BackendLike,Type[BackendLike]] = list):
301 if isinstance(storage_type, str):
302 t = storage_type.lower()
305 elif t ==
"simpleorderedset":
307 elif t ==
"orderedset":
309 elif t ==
"indexableset":
310 return sortedcollections.IndexableSet()
312 raise ValueError(f
"Unknown class name specified for ``storage_type`` ({storage_type}). Known names include 'list', 'simpleorderedset', 'orderedset,' and 'indexableset'.")
313 elif storage_type
is sortedcollections.OrderedSet:
315 elif isinstance(storage_type, Type):
316 return storage_type()
323 def __getstate__(self):
325 if odict[
'disable_parents_pickling']
and 'parents' in odict:
329 def __setstate__(self, state):
330 state.setdefault(
"parents", [])
331 if type(state.get(
"items"))
is sortedcollections.OrderedSet:
336 def capacity(self) -> float:
337 """Return the capacity of the container (i.e. maximal number of items/spots/bins/etc). Can be math.inf."""
342 """Return the number of free spots in the container. Can be math.inf."""
346 def size(self) -> int:
347 """Return the size of the container (i.e. number of items, spots, bins, etc)."""
352 """Return the best individual. """
357 """Return the fitness values of the individual with the best quality, or None. """
362 """Return the features values of the individual with the best quality, or None. """
367 """Return the number of individuals discarded by the container since its creation. """
372 """Return the number of individuals added into the container since its creation. """
377 """Return the number of individuals rejected (when added) by the container since its creation. """
382 """Return the number of adds, modifications and discards since the creation of this container. """
388 """Return the extrema values of the fitnesses of the stored individuals."""
392 maxima = minima.copy()
395 for i
in range(len(maxima)):
397 if value > maxima[i]:
399 elif value < minima[i]:
401 return tuple(zip(minima, maxima))
406 """Return the extrema values of the features of the stored individuals."""
412 if extrema
is not None:
418 for i
in range(len(maxima)):
419 if ind_f[i] > maxima[i]:
421 elif ind_f[i] < minima[i]:
423 return tuple(zip(minima, maxima))
426 """Reduce built-in float descriptors in column order."""
428 or getattr(self.
get_ind_features,
"__func__",
None)
is not Container.get_ind_features):
432 if type(ind)
is not Individual:
434 features = ind.features
435 if type(features)
is not Features:
437 values = features.values
438 if type(values)
is not tuple
and type(values)
is not list:
445 for column
in zip_longest(*rows):
446 for value_type
in map(type, column):
447 if value_type
is not float
and value_type
is not np.float64:
449 extrema.append((np.float64(min(column)), np.float64(max(column))))
450 return tuple(extrema)
454 """Return immediate parent entries in parent order, including repeated entries."""
455 return flatten_seq_of_seq(self.
parents)
459 """Return a string describing the fullness of the container."""
461 return str(self.
size)
465 def __len__(self) -> int:
466 return len(self.
items)
469 def __getitem__(self, index: int) -> T: ...
472 def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
474 def __getitem__(self, key):
475 if isinstance(key, slice):
476 raise NotImplementedError
477 return self.
items[key]
479 def __contains__(self, key: Any) -> bool:
480 return key
in self.
items
482 def __iter__(self) -> Iterator[IndividualLike]:
483 return iter(self.
items)
488 def __repr__(self) -> str:
490 return "%s()" % (self.__class__.__name__,)
491 return "%s(%r)" % (self.__class__.__name__, list(self))
494 def _add_to_collection(self, collection: BackendLike[IndividualLike], individual: IndividualLike) -> Tuple[bool,int]:
495 """Add ``individual`` to ``collection``.
496 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``.
497 ``collection`` can be a MutableSequence or an ordered set implementing Sequence and MutableSet."""
498 old_len: int = len(collection)
499 if isinstance(collection, MutableSet):
500 collection.add(individual)
501 if len(collection) == old_len:
502 return False, collection.index(individual)
504 return True, len(collection) - 1
505 elif isinstance(collection, MutableSequence):
508 index: int = collection.index(individual)
510 collection.append(individual)
511 index = len(collection) - 1
515 raise ValueError(
"collection must be an ordered set implementing MutableSet or a Sequence")
519 """Check inclusive bounds. An empty or omitted domain allows any value."""
520 if domain
is None or len(domain) == 0:
524 def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
525 """Resolve the descriptor vector used by this container.
527 Select configured named scores in descriptor order when names are
528 supplied. Otherwise use the candidate's feature object.
531 return individual.features
535 def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
536 """Resolve the fitness used by this container for admission and ranking.
538 Select named scores in objective order or use the candidate's fitness.
539 When the container applies different weights, return a weighted copy
540 so other archives sharing the same candidate keep their own semantics.
547 def _fitness_with_container_weights(self, fitness: FitnessLike) -> FitnessLike:
550 weighted = copy.copy(fitness)
552 if not isinstance(weighted, Fitness):
553 weighted.values = fitness.values
556 def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
557 """Store the raw fitness in the configured location.
559 Write named objective scores when configured. Otherwise replace the
560 candidate's fitness object, applying the container's weights if set.
566 individual.scores[name] = val
569 """Validate the resolved objective and descriptor vectors.
571 Reject invalid fitness and vectors outside declared coordinate
572 bounds. This step runs before storage or parent forwarding.
579 if not fit.valid
or any(math.isnan(value)
for value
in fit.values):
580 exc = ValueError(f
"Fitness is not valid.")
583 exc = ValueError(f
"fitness ({str(fit)}) out of bounds ({str(self.fitness_domain)}).")
587 exc = ValueError(f
"features ({str(ft)}) out of bounds ({str(self.features_domain)}). fitness={fit}. scores={individual.scores}")
603 def _add_internal(self, individual: IndividualLike, raise_if_not_added_to_parents: bool,
604 only_to_parents: bool, replace_index: Optional[int] =
None) -> Optional[int]:
605 """Store a candidate and commit any local eviction after parent admission."""
606 if not only_to_parents
and replace_index
is None and self.
free < 1
and self.
_index_of(individual)
is None:
608 raise IndexError(
"No free slot available in this container.")
609 if only_to_parents
and len(self.
parents) == 0:
611 raise ValueError(
"`only_to_parents` can only be set to True if at least one parent is specified.")
615 if not only_to_parents:
617 replaces_equal = replace_index
is not None and index == replace_index
626 del self.
items[index]
641 if replace_index
is not None:
651 def _add_to_parents(self, individual: IndividualLike, require_admission: bool) ->
None:
655 if require_admission
and len(self.
parents) > 1:
660 snapshotted = {id(parent)
for parent, _
in snapshots}
664 previous_additions = parent.nb_added
if require_admission
else None
665 parent.add(individual, raise_if_not_added_to_parents=require_admission)
666 if (previous_additions
is not None and id(parent)
not in snapshotted
667 and parent.nb_added > previous_additions):
668 updated_parents.append(parent)
669 except Exception
as exc:
670 if not require_admission:
673 for updated_parent
in reversed(updated_parents):
675 updated_parent.discard(individual)
676 except Exception
as e:
677 exc.add_note(f
"Could not undo a parent insertion: {e}")
678 for archive, state
in snapshots:
679 archive.__dict__.clear()
680 archive.__dict__.update(state)
681 raise ValueError(f
"Individual could not be added to the parents: {exc}")
from exc
684 """Restrict the short undo record to plain append-only parent storage."""
685 if (type(individual)
is not Individual
or type(individual.fitness)
is not Fitness
686 or type(individual.features)
is not Features
687 or individual.fitness.__dict__.keys() != _FITNESS_FIELDS
688 or individual.features.__dict__.keys() != _FEATURE_FIELDS
689 or not _flat_values(individual.fitness.values, tuple)
690 or not _flat_values(individual.fitness.weights, tuple)
691 or not (_flat_values(individual.features.values, tuple)
692 or _flat_values(individual.features.values, list))
693 or not all(type(gene)
in _COPY_ATOMS
for gene
in individual)):
696 type(parent)
is Container
and not parent.parents
697 and not parent.fitness_score_names
and not parent.features_score_names
698 and type(parent.items)
in (list, _IndexedOrderedSet)
and type(parent.recentness)
is list
699 and (parent._best_fitness
is None or type(parent._best_fitness)
is Fitness)
700 and parent.__dict__.keys() == _APPEND_PARENT_FIELDS
706 parents = {id(parent): parent
for parent
in self.
parents}
707 undo = [(parent, vars(parent).copy(), len(parent.items), len(parent.recentness))
708 for parent
in parents.values()]
711 parent.add(individual, raise_if_not_added_to_parents=
True)
712 except Exception
as error:
714 memo = {id(self): self, **parents}
715 for _, state, size, _
in undo:
716 items = state[
"items"]
717 prefix = items[:size]
if type(items)
is list
else list(islice(items, size))
718 memo.update((id(elite), elite)
for elite
in prefix)
720 memo[id(state[
"parents"])] = state[
"parents"]
721 for _, state, _, recent
in undo:
722 original = state[
"recentness"]
723 memo[id(original)] = deepcopy(original[:recent], memo)
724 snapshots = [(parent, deepcopy(state, memo))
for parent, state, _, _
in undo]
725 for parent, state
in snapshots:
727 vars(parent).
update(state)
728 raise ValueError(f
"Individual could not be added to the parents: {error}")
from error
731 """Copy built-in archive bookkeeping while retaining archive and elite identities."""
735 memo = {id(self): self}
736 for parent
in pending:
737 if id(parent)
in seen:
740 memo[id(parent)] = parent
741 parents = getattr(parent,
"parents", ())
742 pending.extend(parents)
743 if isinstance(parent, Container)
and type(parent).__module__.startswith(
"qdpy.containers."):
744 archives.append(parent)
745 memo[id(parents)] = parents
747 memo[id(elite)] = elite
748 return [(archive, deepcopy(archive.__dict__, memo))
for archive
in archives]
750 def _consider_for_best(self, individual: IndividualLike) ->
None:
754 self.
_best = individual
758 def _recompute_best(self) -> None:
760 for individual
in self.
items:
763 def _set_fitness_weights(self, weights: FitnessValuesLike) ->
None:
766 if previous
is None or tuple(previous) != tuple(weights):
769 def _index_of(self, individual: IndividualLike) -> Optional[int]:
771 return self.
items.index(individual)
772 except (ValueError, KeyError):
776 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool =
False) -> Optional[int]:
777 """Validate one candidate and return its local storage index.
779 An equal entry can return its existing index. Grid and novelty
780 subclasses can decline a candidate locally and return None.
781 Pass ``raise_if_not_added_to_parents=True`` to propagate parent
782 insertion failures and preserve the current local entry. A failure
783 across built-in parents restores the earlier branch contents.
784 Custom parents are responsible for their own external side effects.
789 return self.
_add_internal(individual, raise_if_not_added_to_parents,
False)
792 def _discard_by_index(self, individual: IndividualLike, idx: Optional[int] =
None, also_from_parents: bool =
False) ->
None:
793 """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."""
795 if also_from_parents:
798 p.discard(individual, also_from_parents =
True)
799 except Exception
as e:
814 raise RuntimeError(
"`self.size` < 0 !")
817 def discard(self, individual: IndividualLike, also_from_parents: bool =
False) ->
None:
818 """Remove the matching entry if present.
820 Use ``also_from_parents`` to request removal from parent history
821 as well. Removing the cached best triggers recomputation from the
827 def update(self, iterable: Iterable, ignore_exceptions: bool =
True, issue_warning: bool =
False) -> int:
828 """Offer each candidate for insertion and count reported local indexes.
830 The count can include an existing equal entry. Use the change in
831 ``nb_added`` to count actual insertions. With ``ignore_exceptions=True``,
832 validation failures can be offered to parents instead. Set
833 ``issue_warning=True`` to report them. Capacity and parent storage
834 errors can still propagate.
837 item_index: Optional[int] =
None
839 for item
in iterable:
840 only_to_parents =
False
843 except Exception
as e:
844 only_to_parents =
True
845 if ignore_exceptions
and issue_warning:
846 if isinstance(e,IndexError):
847 warnings.warn(f
"Adding individual failed (index out of bounds): {str(e)}")
848 elif isinstance(e,ValueError):
849 warnings.warn(f
"Adding individual failed (attribute out of bounds): {str(e)}")
851 warnings.warn(f
"Adding individual failed: {str(e)}")
852 traceback.print_exc()
853 elif not ignore_exceptions:
855 if not only_to_parents
or len(self.
parents) > 0:
857 if item_index
is not None:
861 raise ValueError(f
"Argument needs to be an Iterable, got {type(Iterable)}")
865 def clear(self, also_from_parents: bool =
False) ->
None:
866 """Remove all local entries and refresh the cached best.
868 With ``also_from_parents=True``, remove matching local entries from
869 the parents as well. Parent-only entries may remain.
873 for individual
in list(self):
874 self.
discard(individual, also_from_parents)
879 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
880 current_version=qdpy.__version__,
881 details=
"Use 'self.clear(also_from_parents=True)' instead.")
883 """Clear all individual in the collection, and clear also those individuals in the parent containers."""
884 self.
clear(also_from_parents =
True)
887 def novelty(self, individual: IndividualLike, **kwargs):
888 """Score novelty against immediate parent entries.
890 The metric uses the candidates' feature attributes. At least one
894 raise RuntimeError(f
"At least one parent is necessary to assess novelty.")
898 """Score novelty and local competition against immediate parents.
900 Metric options such as ``k`` and ``ignore_first`` are forwarded.
901 At least one parent is required.
904 raise RuntimeError(f
"At least one parent is necessary to assess novelty.")
908 def to_grid(self, shape: Union[ShapeLike, int],
909 max_items_per_bin: int = 1,
910 capacity: Optional[float] =
None, **kwargs: Any) -> Any:
911 """Re-admit the stored entries to a new descriptor grid.
913 Reuse declared domains by default. If absent, use the archive's
914 observed extrema. Supply explicit domains when converting an empty
915 archive. Named score selection and fitness weights are inherited
918 :param shape: Number of cells per descriptor coordinate.
919 :param max_items_per_bin: Maximum number of local entries in one cell.
920 :param capacity: Total capacity override. None leaves it unbounded.
921 :param kwargs: Other Grid options such as domains or storage type.
922 :returns: A new grid containing the entries it admitted.
924 if not 'fitness_domain' in kwargs:
926 if not 'features_domain' in kwargs:
928 if not 'fitness_score_names' in kwargs:
930 if not 'features_score_names' in kwargs:
932 if not 'fitness_weights' in kwargs:
934 return qdpy.containers.Grid(self, shape=shape, max_items_per_bin=max_items_per_bin, capacity=capacity, **kwargs)
937 def _has_infinite_fitness_bounds(self) -> bool:
939 return domain
is not None and any(
940 bound
in (-math.inf, math.inf)
for interval
in domain
for bound
in interval
944 def qd_score(self, normalized: bool =
True) -> float:
945 """Sum quality over all locally stored individuals.
947 With normalisation, measure each objective's improvement from the
948 worst domain endpoint and divide by the interval width. Use the
949 lower endpoint for maximisation and the upper for minimisation.
950 A collapsed interval uses a divisor of one. A populated archive
951 with an infinite fitness bound returns NaN when normalised. An
952 empty archive with a fitness domain has a score of zero. Use
953 ``normalized=False`` to sum raw values without applying weights.
958 raise RuntimeError(f
"'fitness_domain' must be set to compute normalized QD scores.")
964 for v, w, bounds
in zip(ind_fit.values, ind_fit.weights, self.
fitness_domain):
965 d = (bounds[1] - bounds[0])
if bounds[1] > bounds[0]
else 1
967 score += (bounds[1] - v) / (d)
969 score += (v - bounds[0]) / (d)
973 score += np.sum(ind_fit.values)
983 """Forward the archive interface to a wrapped container.
985 Subclasses can intercept admission or transform measurements while
986 retaining the underlying collection and storage configuration.
989 container: ContainerLike
992 def __init__(self, container: ContainerLike,
993 name: Optional[str] =
None,
994 **kwargs: Any) ->
None:
996 self.
name = name
if name
is not None else f
"{self.__class__.__name__}-{id(self)}"
998 def __getstate__(self):
1002 def __setstate__(self, state):
1005 def __setattr__(self, attr, value):
1013 def __getattr__(self, attr):
1015 return getattr(self, attr)
1016 if "container" not in self.
__dict__:
1017 raise AttributeError
1021 def __len__(self) -> int:
1025 def __getitem__(self, index: int) -> T: ...
1028 def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
1030 def __getitem__(self, key):
1034 def all_parents_inds(self) -> Sequence[IndividualLike]:
1035 return self.
container.all_parents_inds()
1037 def add(self, individual: IndividualLike, raise_if_not_added_to_parents: bool =
False) -> Optional[int]:
1038 return self.
container.add(individual, raise_if_not_added_to_parents)
1040 def discard(self, individual: IndividualLike, also_from_parents: bool =
False) ->
None:
1041 return self.
container.discard(individual, also_from_parents)
1043 update = functools.partialmethod(Container.update)
1044 clear = functools.partialmethod(Container.clear)
1046 def novelty(self, individual: IndividualLike, **kwargs):
1047 return self.
container.novelty(individual, **kwargs)
1049 def novelty_local_competition(self, individual: IndividualLike, **kwargs):
1050 return self.
container.novelty_local_competition(individual, **kwargs)
1052 def qd_score(self, normalized: bool =
True) -> float:
1053 return self.
container.qd_score(normalized)
1055 def to_grid(self, shape: Union[ShapeLike, int], max_items_per_bin: int = 1, capacity: Optional[float] =
None, **kwargs: Any) -> Any:
1056 return self.
container.to_grid(shape, max_items_per_bin, capacity, **kwargs)
1058 def __iter__(self) -> Iterator:
1061 def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
1062 return self.
container.get_ind_features(individual, *args, **kwargs)
1064 def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
1065 return self.
container.get_ind_fitness(individual, *args, **kwargs)
1067 def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
1068 self.
container.set_ind_fitness(individual, fitness, *args, **kwargs)
1071 def capacity(self) -> float:
1075 def free(self) -> float:
1079 def size(self) -> int:
1083 def best(self) -> Any:
1087 def best_fitness(self) -> Optional[FitnessLike]:
1091 def best_features(self) -> Optional[FeaturesLike]:
1095 def nb_discarded(self) -> int:
1099 def nb_added(self) -> int:
1103 def nb_rejected(self) -> int:
1107 def nb_operations(self) -> int:
1111 def fitness_extrema(self) -> Optional[Sequence[DomainLike]]:
1115 def features_extrema(self) -> Optional[Sequence[DomainLike]]:
CONTAINER CLASSES ########### {{{1.
Sequence fitness_score_names
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
None discard(self, IndividualLike individual, bool also_from_parents=False)
Optional[Sequence[DomainLike]] features_extrema(self)
Optional[Sequence[DomainLike]] fitness_extrema(self)
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)
Sequence[IndividualLike] all_parents_inds(self)
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Optional[Sequence[DomainLike]] _float_feature_extrema(self)
novelty_local_competition(self, IndividualLike individual, **kwargs)
Tuple[bool, int] _add_to_collection(self, BackendLike[IndividualLike] collection, IndividualLike individual)
None clear(self, bool also_from_parents=False)
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
only_add_accepted_inds_to_parents
float qd_score(self, bool normalized=True)
set_ind_fitness(self, IndividualLike individual, FitnessLike fitness, *args, **kwargs)
_create_storage(self, Union[str, BackendLike, Type[BackendLike]] storage_type=list)
bool in_bounds(self, Any val, Any domain)
Optional[FeaturesLike] best_features(self)
None _add_to_parents(self, IndividualLike individual, bool require_admission)
Forward a candidate to each immediate parent in order.
None _check_if_can_be_added(self, IndividualLike individual)
Any to_grid(self, Union[ShapeLike, int] shape, int max_items_per_bin=1, Optional[float] capacity=None, **Any kwargs)
novelty(self, IndividualLike individual, **kwargs)
Optional[int] _add_internal(self, IndividualLike individual, bool raise_if_not_added_to_parents, bool only_to_parents, Optional[int] replace_index=None)
Commit local storage and eviction after required parent admission.
_add_to_append_only_parents(self, individual)
Take a short pre-admission record and rebuild a snapshot only after rejection.
MutableSequence recentness
Optional[Sequence[DomainLike]] fitness_extrema(self)
FitnessLike _fitness_with_container_weights(self, FitnessLike fitness)
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Optional[int] _index_of(self, IndividualLike individual)
None discard(self, IndividualLike individual, bool also_from_parents=False)
Optional[int] add(self, IndividualLike individual, bool raise_if_not_added_to_parents=False)
Optional[Sequence[DomainLike]] features_extrema(self)
_can_undo_parent_appends(self, individual)
None _recompute_best(self)
Optional[FitnessLike] best_fitness(self)
bool _has_infinite_fitness_bounds(self)
None _consider_for_best(self, IndividualLike individual)
BACKEND CLASSES ########### {{{1.
None discard(self, T key)
None update(self, Iterable iterable)