QDpy
Loading...
Searching...
No Matches
base.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""TODO"""
20#from __future__ import annotations
21
22__all__ = ["BackendLike", "SimpleOrderedSet", "ContainerLike", "Container", "ContainerDecorator"]
23
24
25import sys
26from copy import deepcopy
27import warnings
28import math
29import numpy as np
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
32import traceback
33import deprecation
34import functools
35from itertools import islice, zip_longest
36import sortedcollections
37
38from qdpy.utils import *
39from qdpy.phenotype import *
40from qdpy.phenotype import _COPY_ATOMS, _FEATURE_FIELDS, _FITNESS_FIELDS, _flat_values
41from qdpy.base import *
42from qdpy.metrics import novelty, novelty_local_competition, novelty_nn
43
44
45
46
47
48
49@registry.register
50class SimpleOrderedSet(MutableSet[T], Sequence[T]):
51 """Store unique hashable entries in insertion order with integer indexing.
52
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.
56 """
57
58 _items: List[T] # Internal storage
59
60 def __init__(self, iterable: Optional[Iterable] = None) -> None:
61 self._items = []
62 if iterable is not None:
63 self.update(iterable)
64
65 def __len__(self) -> int:
66 return len(self._items)
67
68 @overload
69 def __getitem__(self, index: int) -> T: ...
70
71 @overload
72 def __getitem__(self, s: slice) -> Sequence[T]: ...
73
74 def __getitem__(self, key):
75 if isinstance(key, slice):
76 raise NotImplementedError
77 return self._items[key]
78
79 def __contains__(self, key: Any) -> bool:
80 return key in self._items
81
82 def __iter__(self) -> Iterator[T]:
83 return iter(self._items)
84
85 def __reversed__(self) -> Iterator[T]:
86 return reversed(self._items)
87
88 def __repr__(self) -> str:
89 if not self:
90 return "%s()" % (self.__class__.__name__,)
91 return "%s(%r)" % (self.__class__.__name__, list(self))
92
93 def __delitem__(self, idx) -> None:
94 del self._items[idx]
95
96 def count(self, key: T) -> int:
97 return 1 if key in self else 0
98
99 def index(self, key: T, start: int = 0, stop: int = sys.maxsize) -> int:
100 return self._items.index(key, start, stop)
101
102 def add(self, key: T) -> None:
103 """Add ``key`` to this SimpleOrderedSet, if it is not already present. """
104 try:
105 self._items.index(key)
106 except ValueError:
107 self._items.append(key)
108
109 def discard(self, key: T) -> None:
110 """Discard ``key`` in this SimpleOrderedSet. Does not raise an exception if absent."""
111 try:
112 self._items.remove(key)
113 except ValueError:
114 return
115
116 def update(self, iterable: Iterable) -> None:
117 """Add the items in ``iterable``, if they are not already present in the SimpleOrderedSet. """
118 try:
119 for item in iterable:
120 self.add(item)
121 except TypeError:
122 raise ValueError(f"Argument needs to be an iterable, got {type(iterable)}")
123
124
125class _IndexedOrderedSet(sortedcollections.OrderedSet):
126 """Provide the positional lookup and deletion required by an archive."""
127
128 def __getstate__(self):
129 # Rebuild the hash index and insertion counter from the live entries.
130 return list(self)
131
132 def __setstate__(self, items):
133 self.__init__(items)
134
135 def index(self, value) -> int:
136 # OrderedSet returns the insertion serial. Its sorted mapping of
137 # live serials gives the current position even after deletions.
138 return self._nums.bisect_left(super().index(value))
139
140 def __delitem__(self, index: int) -> None:
141 self.discard(self[index])
142
143
144
145BackendLike = Union[MutableSequence[T], SimpleOrderedSet[T]]
146
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",
152))
153
154
155
156
157
158@runtime
159class ContainerLike(Protocol):
160 """Structural interface for archives and archive decorators.
161
162 Optimisers use the archive's fitness and descriptor accessors, even
163 when a candidate carries a separate fitness object or named scores.
164 """
165 def all_parents_inds(self) -> Sequence[IndividualLike]: ...
166
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): ...
180 @property
181 def capacity(self) -> float: ...
182 @property
183 def free(self) -> float: ...
184 @property
185 def size(self) -> int: ...
186 @property
187 def best(self) -> Any: ...
188 @property
189 def best_fitness(self) -> Optional[FitnessLike]: ...
190 @property
191 def best_features(self) -> Optional[FeaturesLike]: ...
192 @property
193 def nb_discarded(self) -> int: ...
194 @property
195 def nb_added(self) -> int: ...
196 @property
197 def nb_rejected(self) -> int: ...
198 @property
199 def nb_operations(self) -> int: ...
200 @property
201 def fitness_extrema(self) -> Optional[Sequence[DomainLike]]: ...
202 @property
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]
208
209
210# TODO verify that containers are thread-safe
211@registry.register
213 """Store evaluated candidates subject to capacity and domain bounds.
214
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.
218
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.
236
237 The archive stores candidate objects. Mutate a copy during variation,
238 and serialise archive updates through the controlling process.
239 """
240
241 name: Optional[str]
242 items: BackendLike[IndividualLike]
243 #depot: Optional[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]
251 _capacity: float
252 _size: int
253 _best: Optional[IndividualLike]
254 _best_fitness: Optional[FitnessLike]
255 _best_features: Optional[FeaturesLike]
256 _nb_discarded: int
257 _nb_added: int
258 _nb_rejected: int
259
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:
270 self.items = self._create_storage(storage_type)
271 self.parents = [] if parents is None else parents
272 self.only_add_accepted_inds_to_parents = only_add_accepted_inds_to_parents
273 self.disable_parents_pickling = disable_parents_pickling
274 self.fitness_domain = fitness_domain
275 if self.fitness_domain is not None:
276 for f in self.fitness_domain:
277 if not is_iterable(f) or len(f) != 2:
278 raise ValueError("``fitness_domain`` must be a sequence of 2-tuples.")
279 self.features_domain = features_domain
280 if self.features_domain is not None:
281 for f in self.features_domain:
282 if not is_iterable(f) or len(f) != 2:
283 raise ValueError("``features_domain`` must be a sequence of 2-tuples.")
284 self.fitness_score_names = fitness_score_names
285 self.features_score_names = features_score_names
286 self.fitness_weights = fitness_weights
287 self.recentness = []
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
290 self._size = 0
291 self._best = None
292 self._best_fitness = None
293 self._best_features = None
294 self._nb_discarded = 0
295 self._nb_rejected = 0
296 self._nb_added = 0
297 if iterable is not None:
298 self.update(iterable)
299
300 def _create_storage(self, storage_type: Union[str,BackendLike,Type[BackendLike]] = list):
301 if isinstance(storage_type, str):
302 t = storage_type.lower()
303 if t == "list":
304 return list()
305 elif t == "simpleorderedset":
306 return SimpleOrderedSet()
307 elif t == "orderedset":
308 return _IndexedOrderedSet()
309 elif t == "indexableset":
310 return sortedcollections.IndexableSet()
311 else:
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:
314 return _IndexedOrderedSet()
315 elif isinstance(storage_type, Type): # type: ignore
316 return storage_type() # type: ignore
317 else:
318 #elif isinstance(storage_type, BackendLike):
319 return storage_type
320 #else:
321 #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.")
322
323 def __getstate__(self):
324 odict = self.__dict__.copy()
325 if odict['disable_parents_pickling'] and 'parents' in odict:
326 del odict['parents']
327 return odict
328
329 def __setstate__(self, state):
330 state.setdefault("parents", [])
331 if type(state.get("items")) is sortedcollections.OrderedSet:
332 state["items"] = _IndexedOrderedSet(state["items"])
333 self.__dict__.update(state)
334
335 @property
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."""
338 return self._capacity
339
340 @property
341 def free(self) -> float:
342 """Return the number of free spots in the container. Can be math.inf."""
343 return self._capacity - self._size
344
345 @property
346 def size(self) -> int:
347 """Return the size of the container (i.e. number of items, spots, bins, etc)."""
348 return self._size
349
350 @property
351 def best(self) -> Any:
352 """Return the best individual. """
353 return self._best
354
355 @property
356 def best_fitness(self) -> Optional[FitnessLike]:
357 """Return the fitness values of the individual with the best quality, or None. """
358 return self._best_fitness
359
360 @property
361 def best_features(self) -> Optional[FeaturesLike]:
362 """Return the features values of the individual with the best quality, or None. """
363 return self._best_features
364
365 @property
366 def nb_discarded(self) -> int:
367 """Return the number of individuals discarded by the container since its creation. """
368 return self._nb_discarded
369
370 @property
371 def nb_added(self) -> int:
372 """Return the number of individuals added into the container since its creation. """
373 return self._nb_added
374
375 @property
376 def nb_rejected(self) -> int:
377 """Return the number of individuals rejected (when added) by the container since its creation. """
378 return self._nb_rejected
379
380 @property
381 def nb_operations(self) -> int:
382 """Return the number of adds, modifications and discards since the creation of this container. """
383 return self._nb_added + self._nb_discarded
384
385
386 @property
387 def fitness_extrema(self) -> Optional[Sequence[DomainLike]]:
388 """Return the extrema values of the fitnesses of the stored individuals."""
389 if len(self) == 0:
390 return None
391 minima = list(self.get_ind_fitness(self[0]).values)
392 maxima = minima.copy()
393 for ind in self:
394 ind_f = self.get_ind_fitness(ind).values
395 for i in range(len(maxima)):
396 value = ind_f[i]
397 if value > maxima[i]:
398 maxima[i] = value
399 elif value < minima[i]:
400 minima[i] = value
401 return tuple(zip(minima, maxima))
402
403
404 @property
405 def features_extrema(self) -> Optional[Sequence[DomainLike]]:
406 """Return the extrema values of the features of the stored individuals."""
407 size = len(self)
408 if size == 0:
409 return None
410 if size >= 8:
411 extrema = self._float_feature_extrema()
412 if extrema is not None:
413 return extrema
414 maxima = np.array(self.get_ind_features(self[0])) # type: ignore
415 minima = np.array(self.get_ind_features(self[0])) # type: ignore
416 for ind in self:
417 ind_f = self.get_ind_features(ind)
418 for i in range(len(maxima)):
419 if ind_f[i] > maxima[i]:
420 maxima[i] = ind_f[i]
421 elif ind_f[i] < minima[i]:
422 minima[i] = ind_f[i]
423 return tuple(zip(minima, maxima))
424
425 def _float_feature_extrema(self) -> Optional[Sequence[DomainLike]]:
426 """Reduce built-in float descriptors in column order."""
427 if (self.features_score_names
428 or getattr(self.get_ind_features, "__func__", None) is not Container.get_ind_features):
429 return None
430 rows = []
431 for ind in self:
432 if type(ind) is not Individual:
433 return None
434 features = ind.features
435 if type(features) is not Features:
436 return None
437 values = features.values
438 if type(values) is not tuple and type(values) is not list:
439 return None
440 rows.append(values)
441 extrema = []
442 # Like the scalar path, min/max retain the first sign on tied
443 # zeroes and ignore NaNs that follow an initial numeric value.
444 # Missing values in ragged rows also go through the scalar path.
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:
448 return None
449 extrema.append((np.float64(min(column)), np.float64(max(column))))
450 return tuple(extrema)
451
452
453 def all_parents_inds(self) -> Sequence[IndividualLike]:
454 """Return immediate parent entries in parent order, including repeated entries."""
455 return flatten_seq_of_seq(self.parents) # type: ignore
456
457
458 def size_str(self) -> str:
459 """Return a string describing the fullness of the container."""
460 if math.isinf(self.capacity):
461 return str(self.size)
462 else:
463 return "%i/%i" % (self.size, self.capacity)
464
465 def __len__(self) -> int:
466 return len(self.items)
467
468 @overload
469 def __getitem__(self, index: int) -> T: ...
470
471 @overload
472 def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
473
474 def __getitem__(self, key):
475 if isinstance(key, slice):
476 raise NotImplementedError
477 return self.items[key]
478
479 def __contains__(self, key: Any) -> bool:
480 return key in self.items
481
482 def __iter__(self) -> Iterator[IndividualLike]:
483 return iter(self.items)
484
485# def __reversed__(self) -> Iterator[IndividualLike]:
486# return reversed(self.items)
487
488 def __repr__(self) -> str:
489 if not self:
490 return "%s()" % (self.__class__.__name__,)
491 return "%s(%r)" % (self.__class__.__name__, list(self))
492
493
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)
503 else:
504 return True, len(collection) - 1
505 elif isinstance(collection, MutableSequence):
506 added: bool = False
507 try:
508 index: int = collection.index(individual)
509 except ValueError:
510 collection.append(individual)
511 index = len(collection) - 1
512 added = True
513 return added, index
514 else:
515 raise ValueError("collection must be an ordered set implementing MutableSet or a Sequence")
516
517
518 def in_bounds(self, val: Any, domain: Any) -> bool:
519 """Check inclusive bounds. An empty or omitted domain allows any value."""
520 if domain is None or len(domain) == 0:
521 return True
522 return in_bounds(val, domain)
523
524 def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
525 """Resolve the descriptor vector used by this container.
526
527 Select configured named scores in descriptor order when names are
528 supplied. Otherwise use the candidate's feature object.
529 """
530 if len(self.features_score_names) == 0:
531 return individual.features
532 else:
533 return individual.scores.to_features(self.features_score_names, *args, **kwargs)
534
535 def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
536 """Resolve the fitness used by this container for admission and ranking.
537
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.
541 """
542 if len(self.fitness_score_names) == 0:
543 return self._fitness_with_container_weights(individual.fitness)
544 else:
545 return individual.scores.to_fitness(self.fitness_score_names, *args, weights=self.fitness_weights, **kwargs)
546
547 def _fitness_with_container_weights(self, fitness: FitnessLike) -> FitnessLike:
548 if self.fitness_weights is None or tuple(fitness.weights) == tuple(self.fitness_weights):
549 return fitness
550 weighted = copy.copy(fitness)
551 weighted.weights = tuple(self.fitness_weights)
552 if not isinstance(weighted, Fitness):
553 weighted.values = fitness.values
554 return weighted
555
556 def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
557 """Store the raw fitness in the configured location.
558
559 Write named objective scores when configured. Otherwise replace the
560 candidate's fitness object, applying the container's weights if set.
561 """
562 if len(self.fitness_score_names) == 0:
563 individual.fitness = self._fitness_with_container_weights(fitness)
564 else:
565 for name,val in zip(self.fitness_score_names,fitness.values):
566 individual.scores[name] = val
567
568 def _check_if_can_be_added(self, individual: IndividualLike) -> None:
569 """Validate the resolved objective and descriptor vectors.
570
571 Reject invalid fitness and vectors outside declared coordinate
572 bounds. This step runs before storage or parent forwarding.
573 """
574 # Retrieve features and fitness from individual
575 #ind_fitness: FitnessValuesLike = self._get_fitness_from_ind(individual)
576 #ind_features: FeaturesLike = self._get_features_from_ind(individual)
577 exc = None
578 fit = self.get_ind_fitness(individual)
579 if not fit.valid or any(math.isnan(value) for value in fit.values):
580 exc = ValueError(f"Fitness is not valid.")
581 # Check if fitness and features are out of bounds
582 if not self.in_bounds(fit.values, self.fitness_domain):
583 exc = ValueError(f"fitness ({str(fit)}) out of bounds ({str(self.fitness_domain)}).")
584 ft = self.get_ind_features(individual)
585 if not self.in_bounds(ft, self.features_domain):
586 #exc = ValueError(f"features ({str(ft)}) out of bounds ({str(self.features_domain)}).")
587 exc = ValueError(f"features ({str(ft)}) out of bounds ({str(self.features_domain)}). fitness={fit}. scores={individual.scores}") # XXX
588 if exc:
589 self._nb_rejected += 1
590 raise exc
591
592
593
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:
607 self._nb_rejected += 1
608 raise IndexError("No free slot available in this container.")
609 if only_to_parents and len(self.parents) == 0:
610 self._nb_rejected += 1
611 raise ValueError("`only_to_parents` can only be set to True if at least one parent is specified.")
612
613 added = False
614 index = None
615 if not only_to_parents:
616 added, index = self._add_to_collection(self.items, individual)
617 replaces_equal = replace_index is not None and index == replace_index
618 previous_best = self._best, self._best_fitness, self._best_features
619 try:
620 if added:
621 self._consider_for_best(individual)
622 if not self.only_add_accepted_inds_to_parents or added or replaces_equal:
623 self._add_to_parents(individual, raise_if_not_added_to_parents)
624 except Exception:
625 if added:
626 del self.items[index]
627 self._best, self._best_fitness, self._best_features = previous_best
628 raise
629
630 if replaces_equal:
631 # Storage keeps one entry for equal candidates.
632 self._discard_by_index(self.items[replace_index], replace_index)
633 replace_index = None
634 added, index = self._add_to_collection(self.items, individual)
635 self._consider_for_best(individual)
636
637 if added:
638 self.recentness.append(self._nb_added)
639 self._size += 1
640 self._nb_added += 1
641 if replace_index is not None:
642 self._discard_by_index(self.items[replace_index], replace_index)
643 index -= 1
644 return index
645
646
651 def _add_to_parents(self, individual: IndividualLike, require_admission: bool) -> None:
652 if not self.parents:
653 return
654 snapshots = []
655 if require_admission and len(self.parents) > 1:
656 if self._can_undo_parent_appends(individual):
657 self._add_to_append_only_parents(individual)
658 return
659 snapshots = self._snapshot_parents()
660 snapshotted = {id(parent) for parent, _ in snapshots}
661 updated_parents = []
662 for parent in self.parents:
663 try:
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:
671 continue
672 self._nb_rejected += 1
673 for updated_parent in reversed(updated_parents):
674 try:
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
682
683 def _can_undo_parent_appends(self, individual):
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)):
694 return False
695 return all(
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
701 for parent in self.parents
702 )
703
704
705 def _add_to_append_only_parents(self, individual):
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()]
709 try:
710 for parent in self.parents:
711 parent.add(individual, raise_if_not_added_to_parents=True)
712 except Exception as error:
713 self._nb_rejected += 1
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)
719 memo[id(items)] = prefix if type(items) is list else _IndexedOrderedSet(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:
726 vars(parent).clear()
727 vars(parent).update(state)
728 raise ValueError(f"Individual could not be added to the parents: {error}") from error
729
731 """Copy built-in archive bookkeeping while retaining archive and elite identities."""
732 pending = list(self.parents)
733 seen = {id(self)}
734 archives = []
735 memo = {id(self): self}
736 for parent in pending:
737 if id(parent) in seen:
738 continue
739 seen.add(id(parent))
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
746 for elite in parent:
747 memo[id(elite)] = elite
748 return [(archive, deepcopy(archive.__dict__, memo)) for archive in archives]
749
750 def _consider_for_best(self, individual: IndividualLike) -> None:
751 fitness = self.get_ind_fitness(individual)
752 if self._best_fitness is None or fitness.dominates(self._best_fitness):
753 features = self.get_ind_features(individual)
754 self._best = individual
755 self._best_fitness = fitness
756 self._best_features = features
757
758 def _recompute_best(self) -> None:
759 self._best = self._best_fitness = self._best_features = None
760 for individual in self.items:
761 self._consider_for_best(individual)
762
763 def _set_fitness_weights(self, weights: FitnessValuesLike) -> None:
764 previous = self.fitness_weights
765 self.fitness_weights = weights
766 if previous is None or tuple(previous) != tuple(weights):
767 self._recompute_best()
768
769 def _index_of(self, individual: IndividualLike) -> Optional[int]:
770 try:
771 return self.items.index(individual)
772 except (ValueError, KeyError):
773 return None
774
775
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.
778
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.
785 """
786 # Retrieve features and fitness from individual and check if they are not out-of-bounds
787 self._check_if_can_be_added(individual)
788 # Add
789 return self._add_internal(individual, raise_if_not_added_to_parents, False)
790
791
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."""
794 # Remove from parents
795 if also_from_parents:
796 try:
797 for p in self.parents:
798 p.discard(individual, also_from_parents = True)
799 except Exception as e:
800 pass
801 # Remove from container
802 if idx is None:
803 idx = self._index_of(individual)
804 if idx is None:
805 return
806 removed_best = self.items[idx] is self._best
807 del self.items[idx]
808 del self.recentness[idx]
809 self._size -= 1
810 self._nb_discarded += 1
811 if removed_best:
812 self._recompute_best()
813 if self._size < 0:
814 raise RuntimeError("`self.size` < 0 !")
815
816
817 def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
818 """Remove the matching entry if present.
819
820 Use ``also_from_parents`` to request removal from parent history
821 as well. Removing the cached best triggers recomputation from the
822 remaining entries.
823 """
824 self._discard_by_index(individual, also_from_parents=also_from_parents)
825
826
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.
829
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.
835 """
836 nb_inserted: int = 0
837 item_index: Optional[int] = None
838 try:
839 for item in iterable:
840 only_to_parents = False
841 try:
842 self._check_if_can_be_added(item)
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)}")
850 else:
851 warnings.warn(f"Adding individual failed: {str(e)}")
852 traceback.print_exc()
853 elif not ignore_exceptions:
854 raise e
855 if not only_to_parents or len(self.parents) > 0:
856 item_index = self._add_internal(item, True, only_to_parents)
857 if item_index is not None:
858 nb_inserted += 1
859
860 except TypeError:
861 raise ValueError(f"Argument needs to be an Iterable, got {type(Iterable)}")
862 return nb_inserted
863
864
865 def clear(self, also_from_parents: bool = False) -> None:
866 """Remove all local entries and refresh the cached best.
867
868 With ``also_from_parents=True``, remove matching local entries from
869 the parents as well. Parent-only entries may remain.
870 """
871 self._best = self._best_fitness = self._best_features = None
872 try:
873 for individual in list(self):
874 self.discard(individual, also_from_parents)
875 finally:
876 self._recompute_best()
877
878
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.")
882 def clear_all(self) -> None:
883 """Clear all individual in the collection, and clear also those individuals in the parent containers."""
884 self.clear(also_from_parents = True)
885
886
887 def novelty(self, individual: IndividualLike, **kwargs):
888 """Score novelty against immediate parent entries.
889
890 The metric uses the candidates' feature attributes. At least one
891 parent is required.
892 """
893 if len(self.parents) == 0:
894 raise RuntimeError(f"At least one parent is necessary to assess novelty.")
895 return novelty(individual, self.all_parents_inds(), **kwargs)
896
897 def novelty_local_competition(self, individual: IndividualLike, **kwargs):
898 """Score novelty and local competition against immediate parents.
899
900 Metric options such as ``k`` and ``ignore_first`` are forwarded.
901 At least one parent is required.
902 """
903 if len(self.parents) == 0:
904 raise RuntimeError(f"At least one parent is necessary to assess novelty.")
905 return novelty_local_competition(individual, self.all_parents_inds(), **kwargs)
906
907
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.
912
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
916 unless overridden.
917
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.
923 """
924 if not 'fitness_domain' in kwargs:
925 kwargs['fitness_domain'] = self.fitness_domain if self.fitness_domain is not None else self.fitness_extrema
926 if not 'features_domain' in kwargs:
927 kwargs['features_domain'] = self.features_domain if self.features_domain is not None else self.features_extrema
928 if not 'fitness_score_names' in kwargs:
929 kwargs['fitness_score_names'] = self.fitness_score_names
930 if not 'features_score_names' in kwargs:
931 kwargs['features_score_names'] = self.features_score_names
932 if not 'fitness_weights' in kwargs:
933 kwargs['fitness_weights'] = self.fitness_weights
934 return qdpy.containers.Grid(self, shape=shape, max_items_per_bin=max_items_per_bin, capacity=capacity, **kwargs) # type: ignore
935
936
937 def _has_infinite_fitness_bounds(self) -> bool:
938 domain = self.fitness_domain
939 return domain is not None and any(
940 bound in (-math.inf, math.inf) for interval in domain for bound in interval
941 )
942
943
944 def qd_score(self, normalized: bool = True) -> float:
945 """Sum quality over all locally stored individuals.
946
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.
954 """
955 score: float = 0.
956 if normalized:
957 if self.fitness_domain is None:
958 raise RuntimeError(f"'fitness_domain' must be set to compute normalized QD scores.")
959 elif len(self) and self._has_infinite_fitness_bounds():
960 return math.nan
961 else:
962 for ind in self:
963 ind_fit = self.get_ind_fitness(ind)
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
966 if w < 0.:
967 score += (bounds[1] - v) / (d)
968 else:
969 score += (v - bounds[0]) / (d)
970 else:
971 for ind in self:
972 ind_fit = self.get_ind_fitness(ind)
973 score += np.sum(ind_fit.values)
974 return score
975
976
977
978
979
980
981@registry.register
983 """Forward the archive interface to a wrapped container.
984
985 Subclasses can intercept admission or transform measurements while
986 retaining the underlying collection and storage configuration.
987 """
988
989 container: ContainerLike
990 name: Optional[str]
991
992 def __init__(self, container: ContainerLike,
993 name: Optional[str] = None,
994 **kwargs: Any) -> None:
995 self.container = container
996 self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
997
998 def __getstate__(self):
999 odict = self.__dict__.copy()
1000 return odict
1001
1002 def __setstate__(self, state):
1003 self.__dict__.update(state)
1004
1005 def __setattr__(self, attr, value):
1006 if attr in self.__dict__:
1007 self.__dict__[attr] = value
1008 elif "container" in self.__dict__:
1009 setattr(self.container, attr, value)
1010 else:
1011 self.__dict__[attr] = value
1012
1013 def __getattr__(self, attr):
1014 if attr in self.__dict__:
1015 return getattr(self, attr)
1016 if "container" not in self.__dict__:
1017 raise AttributeError
1018 return getattr(self.container, attr)
1019
1020
1021 def __len__(self) -> int:
1022 return self.container.__len__()
1023
1024 @overload
1025 def __getitem__(self, index: int) -> T: ...
1026
1027 @overload
1028 def __getitem__(self, s: slice) -> Sequence[IndividualLike]: ...
1029
1030 def __getitem__(self, key):
1031 return self.container.__getitem__(key)
1032
1033
1034 def all_parents_inds(self) -> Sequence[IndividualLike]:
1035 return self.container.all_parents_inds()
1036
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)
1039
1040 def discard(self, individual: IndividualLike, also_from_parents: bool = False) -> None:
1041 return self.container.discard(individual, also_from_parents)
1042
1043 update = functools.partialmethod(Container.update) # type: ignore
1044 clear = functools.partialmethod(Container.clear) # type: ignore
1045
1046 def novelty(self, individual: IndividualLike, **kwargs):
1047 return self.container.novelty(individual, **kwargs)
1048
1049 def novelty_local_competition(self, individual: IndividualLike, **kwargs):
1050 return self.container.novelty_local_competition(individual, **kwargs)
1051
1052 def qd_score(self, normalized: bool = True) -> float:
1053 return self.container.qd_score(normalized)
1054
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)
1057
1058 def __iter__(self) -> Iterator:
1059 return self.container.__iter__()
1060
1061 def get_ind_features(self, individual: IndividualLike, *args, **kwargs) -> FeaturesLike:
1062 return self.container.get_ind_features(individual, *args, **kwargs)
1063
1064 def get_ind_fitness(self, individual: IndividualLike, *args, **kwargs) -> FitnessLike:
1065 return self.container.get_ind_fitness(individual, *args, **kwargs)
1066
1067 def set_ind_fitness(self, individual: IndividualLike, fitness: FitnessLike, *args, **kwargs):
1068 self.container.set_ind_fitness(individual, fitness, *args, **kwargs)
1069
1070 @property
1071 def capacity(self) -> float:
1072 return self.container.capacity
1073
1074 @property
1075 def free(self) -> float:
1076 return self.container.free
1077
1078 @property
1079 def size(self) -> int:
1080 return self.container.size
1081
1082 @property
1083 def best(self) -> Any:
1084 return self.container.best
1085
1086 @property
1087 def best_fitness(self) -> Optional[FitnessLike]:
1088 return self.container.best_fitness
1089
1090 @property
1091 def best_features(self) -> Optional[FeaturesLike]:
1092 return self.container.best_features
1093
1094 @property
1095 def nb_discarded(self) -> int:
1096 return self.container.nb_discarded
1097
1098 @property
1099 def nb_added(self) -> int:
1100 return self.container.nb_added
1101
1102 @property
1103 def nb_rejected(self) -> int:
1104 return self.container.nb_rejected
1105
1106 @property
1107 def nb_operations(self) -> int:
1108 return self.container.nb_operations
1109
1110 @property
1111 def fitness_extrema(self) -> Optional[Sequence[DomainLike]]:
1112 return self.container.fitness_extrema
1113
1114 @property
1115 def features_extrema(self) -> Optional[Sequence[DomainLike]]:
1116 return self.container.features_extrema
1117
1118
1119
1120
CONTAINER CLASSES ########### {{{1.
Definition base.py:159
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:178
None discard(self, IndividualLike individual, bool also_from_parents=False)
Definition base.py:168
Optional[Sequence[DomainLike]] features_extrema(self)
Definition base.py:203
Optional[Sequence[DomainLike]] fitness_extrema(self)
Definition base.py:201
None clear(self, bool also_from_parents=False)
Definition base.py:170
Sequence[IndividualLike] all_parents_inds(self)
Definition base.py:165
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Definition base.py:169
Sequence[IndividualLike] all_parents_inds(self)
Definition base.py:453
None _discard_by_index(self, IndividualLike individual, Optional[int] idx=None, bool also_from_parents=False)
Definition base.py:792
Optional[Sequence[DomainLike]] _float_feature_extrema(self)
Definition base.py:425
novelty_local_competition(self, IndividualLike individual, **kwargs)
Definition base.py:897
Tuple[bool, int] _add_to_collection(self, BackendLike[IndividualLike] collection, IndividualLike individual)
Definition base.py:494
None clear(self, bool also_from_parents=False)
Definition base.py:865
FitnessLike get_ind_fitness(self, IndividualLike individual, *args, **kwargs)
Definition base.py:535
float qd_score(self, bool normalized=True)
Definition base.py:944
set_ind_fitness(self, IndividualLike individual, FitnessLike fitness, *args, **kwargs)
Definition base.py:556
_create_storage(self, Union[str, BackendLike, Type[BackendLike]] storage_type=list)
Definition base.py:300
bool in_bounds(self, Any val, Any domain)
Definition base.py:518
Optional[FeaturesLike] best_features(self)
Definition base.py:361
None _add_to_parents(self, IndividualLike individual, bool require_admission)
Forward a candidate to each immediate parent in order.
Definition base.py:651
None _check_if_can_be_added(self, IndividualLike individual)
Definition base.py:568
Any to_grid(self, Union[ShapeLike, int] shape, int max_items_per_bin=1, Optional[float] capacity=None, **Any kwargs)
Definition base.py:910
novelty(self, IndividualLike individual, **kwargs)
Definition base.py:887
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.
Definition base.py:604
_add_to_append_only_parents(self, individual)
Take a short pre-admission record and rebuild a snapshot only after rejection.
Definition base.py:705
MutableSequence recentness
Definition base.py:249
Optional[Sequence[DomainLike]] fitness_extrema(self)
Definition base.py:387
FitnessLike _fitness_with_container_weights(self, FitnessLike fitness)
Definition base.py:547
int update(self, Iterable iterable, bool ignore_exceptions=True, bool issue_warning=False)
Definition base.py:827
Optional[int] _index_of(self, IndividualLike individual)
Definition base.py:769
None discard(self, IndividualLike individual, bool also_from_parents=False)
Definition base.py:817
Optional[int] add(self, IndividualLike individual, bool raise_if_not_added_to_parents=False)
Definition base.py:776
Optional[Sequence[DomainLike]] features_extrema(self)
Definition base.py:405
_can_undo_parent_appends(self, individual)
Definition base.py:683
Optional[FitnessLike] best_fitness(self)
Definition base.py:356
bool _has_infinite_fitness_bounds(self)
Definition base.py:937
None _consider_for_best(self, IndividualLike individual)
Definition base.py:750
BACKEND CLASSES ########### {{{1.
Definition base.py:50
None update(self, Iterable iterable)
Definition base.py:116