19"""Some base classes, stubs and types."""
26from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, overload
27from typing_extensions
import runtime, Protocol
28from operator
import mul, truediv
35from inspect
import signature
36from functools
import partial
52ScoreValuesLike = Union[Sequence[Any], np.ndarray]
53FitnessValuesLike = ScoreValuesLike
55FeaturesValuesLike = ScoreValuesLike
59 """Protocol describing a generic score, that could be used as a fitness score or as a feature descriptor score."""
60 def dominates(self, other: Any, obj: Any = slice(
None), weights: Optional[ScoreValuesLike] =
None) -> bool: ...
62 def values(self) -> ScoreValuesLike: ...
64 def values(self, values: ScoreValuesLike) ->
None: ...
66 def values(self) -> None: ...
68 def valid(self) -> bool: ...
69 def reset(self) -> None: ...
70 def __getitem__(self, key) -> Any: ...
71 def __setitem__(self, idx, value) -> None: ...
72 def __len__(self) -> int: ...
76 """Fitness protocol inspired from (and compatible with) DEAP Fitness class."""
77 weights: FitnessValuesLike
83 def values(self) -> FitnessValuesLike: ...
85 def values(self, values: FitnessValuesLike) ->
None: ...
87 def values(self) -> None: ...
100 """Features protocol similar to the ``FitnessLike`` protocol."""
121 """Protocol containing a map of scores values, which could then be selected as fitness scores or as feature descriptor scores."""
122 def clear(self) -> None: ...
123 def select(self, names: Sequence[str]) -> Sequence[Any]: ...
124 def to_fitness(self, names: Sequence[str], *args, **kwargs) -> FitnessLike: ...
125 def to_features(self, names: Sequence[str], *args, **kwargs) -> FeaturesLike: ...
126 def __getitem__(self, key) -> Any: ...
127 def __setitem__(self, key, value) -> None: ...
128 def __contains__(self, value) -> bool: ...
129 def items(self) -> Any: ...
130 def keys(self) -> Any: ...
131 def values(self) -> Any: ...
136 """Describe the candidate interface accepted by native QD algorithms.
138 A candidate exposes a mutable genome, fitness, descriptors, scores,
139 and a reset operation. Implementations used in hash-based containers
140 also need stable equality and hashing while stored.
145 def fitness(self) -> FitnessLike: ...
147 def fitness(self, fit: FitnessLike) ->
None: ...
150 def features(self) -> FeaturesLike: ...
152 def features(self, ft: FeaturesLike) ->
None: ...
155 def scores(self) -> ScoresDictLike: ...
157 def scores(self, scores: ScoresDictLike) ->
None: ...
159 def dominates(self, other: Any) -> bool: ...
160 def reset(self) -> None: ...
161 def __setitem__(self, key, values) -> None: ...
166FitnessGetter = Callable[[T], FitnessLike]
167FeaturesGetter = Callable[[T], FeaturesLike]
168GridIndexLike = ShapeLike
175 """Represent an ordered vector of measurements.
177 The sequence interface exposes the stored values. Equality and
178 ordering operators use raw values. Use :meth:`dominates` for Pareto
179 comparisons. An empty vector represents missing measurements.
181 _values: ScoreValuesLike
183 def __init__(self, values: ScoreValuesLike=(), *args, **kwargs) ->
None:
186 def weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
187 return tuple(map(mul, self, weights))
188 def inv_weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
189 return tuple(map(truediv, self, weights))
192 def dominates(self, other: Any, obj: Any = slice(
None), weights: Optional[ScoreValuesLike] =
None) -> bool:
193 """Compare two score vectors by Pareto dominance.
195 Every selected value must be at least as good as its counterpart,
196 and at least one must be strictly better. A plain score treats
197 larger values as better. A fitness uses objective weights.
199 :param other: Score to compare against.
200 :param obj: Slice selecting the objectives to compare.
201 :param weights: Optional comparison weights applied to both vectors.
202 :raises ValueError: If the selected vectors have different lengths.
208 if isinstance(other, Score):
209 other_wvalues = other._comparison_values(weights)[obj]
211 other_weights = weights
if weights
is not None else getattr(other,
"weights",
None)
213 tuple(map(mul, other.values, other_weights))
if other_weights
is not None else other.values
215 if len(self_wvalues) != len(other_wvalues):
216 raise ValueError(
"Scores must have the same dimension to compare them.")
217 not_equal: bool =
False
218 for self_wvalue, other_wvalue
in zip(self_wvalues, other_wvalues):
219 if self_wvalue > other_wvalue:
221 elif self_wvalue < other_wvalue:
225 def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
230 """Assess if a Score is valid or not."""
234 def values(self) -> ScoreValuesLike:
238 def values(self, values: ScoreValuesLike) ->
None:
242 def values(self) -> None:
245 def reset(self) -> None:
248 def __len__(self) -> int:
257 def __getitem__(self, key):
260 def __setitem__(self, idx, value):
267 def __contains__(self, key: Any) -> bool:
270 def __iter__(self) -> Iterator:
273 def __reversed__(self) -> Iterator:
274 return reversed(self.
values)
277 def __hash__(self) -> int:
280 def __gt__(self, other: Any) -> bool:
281 return not self.
__le__(other)
283 def __ge__(self, other: Any) -> bool:
284 return not self.
__lt__(other)
286 def __le__(self, other: Any) -> bool:
287 return self.
values <= other.values
289 def __lt__(self, other: Any) -> bool:
290 return self.
values < other.values
292 def __eq__(self, other: Any) -> bool:
293 return self.
values == other.values
295 def __ne__(self, other: Any) -> bool:
296 return not self.
__eq__(other)
298 def __str__(self) -> str:
302 def __repr__(self) -> str:
304 return "%s()" % (self.__class__.__name__,)
305 return "%s(%r)" % (self.__class__.__name__, tuple(self))
310 """Store raw objectives and their comparison weights.
312 Supply one weight per objective. Negative weights minimise and
313 positive weights maximise. A weight of zero ignores its objective
314 in a weighted comparison. The default is minimisation.
316 Assigning weights keeps the raw objective values unchanged.
317 Empty fitness and fitness containing NaN are invalid. Use container
318 domains to specify which otherwise valid scores may enter an archive.
321 weights: FitnessValuesLike = ()
322 def __init__(self, values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=
None) ->
None:
323 self.
weights = tuple(self.
weights if weights
is None else weights)
326 def __getstate__(self):
327 return {**self.
__dict__,
"_fitness_state_version": 1}
334 if state.pop(
"_fitness_state_version",
None) != 1:
335 raise ValueError(
"This result uses an unsupported fitness format. Rerun the experiment with this QDpy version.")
338 def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
342 """Return one weighted value per objective in the same order.
344 :param weights: Comparison weights for this calculation.
345 :raises ValueError: If a nonempty fitness and the weights differ
349 raise ValueError(
"Fitness values and weights must have the same length.")
350 return tuple(value * weight
if weight != 0
else 0.0
for value, weight
in zip(self.
values, weights))
354 """Whether the fitness has at least one objective and contains no NaN values."""
355 return bool(self.
values)
and not any(math.isnan(value)
for value
in self.
values)
358 def values(self) -> FitnessValuesLike:
359 """Objective values before applying weights."""
363 def values(self, values: FitnessValuesLike) ->
None:
364 values = tuple(values)
365 if values
and not len(self.
weights):
366 self.
weights = (-1.0,) * len(values)
367 if values
and len(self.
weights) != len(values):
368 raise ValueError(
"Fitness values and weights must have the same length.")
372 def values(self) -> None:
375 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
376 current_version=qdpy.__version__,
377 details=
"Use 'foo = fitness.values' instead.")
378 def getValues(self) -> FitnessValuesLike:
381 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
382 current_version=qdpy.__version__,
383 details=
"Use 'fitness.values = (42,)' instead.")
384 def setValues(self, values: FitnessValuesLike) ->
None:
387 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
388 current_version=qdpy.__version__,
389 details=
"Use 'del fitness.values' instead.")
390 def delValues(self) -> None:
406 """Hold the ordered behaviour descriptors of a candidate.
408 Descriptor coordinates are separate from objectives. A grid expects
409 the vector length and coordinate domains declared by its configuration.
412 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
413 current_version=qdpy.__version__,
414 details=
"Use 'foo = features.values' instead. ")
415 def getValues(self) -> FeaturesValuesLike:
418 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
419 current_version=qdpy.__version__,
420 details=
"Use 'features.values = (42,)' instead. ")
421 def setValues(self, values: FeaturesValuesLike) ->
None:
424 @deprecation.deprecated(deprecated_in=
"0.1.3", removed_in=
"0.2.0",
425 current_version=qdpy.__version__,
426 details=
"Use 'del features.values' instead. ")
427 def delValues(self) -> None:
433 """Store named measurements that can supply objectives or descriptors.
435 Containers select measurements in their configured name order.
436 A missing name yields NaN, which fails validation in a bounded
437 descriptor domain or as fitness.
440 def select(self, names: Sequence[str]) -> Sequence[Any]:
443 """Return values in name order and use NaN for missing names."""
446 res.append(self.get(n, np.nan))
449 def to_fitness(self, names: Sequence[str], *args, **kwargs) -> FitnessLike:
450 """Build a fitness vector in the requested name order."""
453 def to_features(self, names: Sequence[str], *args, **kwargs) -> FeaturesLike:
454 """Build a descriptor vector in the requested name order."""
460 """Store a mutable genome with separate evaluation results.
462 The list contents are the genome. Fitness, descriptors, named
463 scores, elapsed evaluation time, and the name are stored separately.
464 Genome equality is independent of those measurements.
466 Keep the genome unchanged while the candidate is in an archive.
467 Use a copy for mutation or remove the candidate before editing it.
468 Updating the descriptor of a stored individual does not relocate
469 its grid cell automatically.
473 _fitness: FitnessLike
474 _features: FeaturesLike
475 _scores: ScoresDictLike
476 elapsed: float = math.nan
478 def __init__(self, iterable: Optional[Iterable] =
None,
479 name: Optional[str] =
None,
480 fitness: Optional[FitnessLike] =
None, features: Optional[FeaturesLike] =
None,
481 scores: Optional[ScoresDictLike] =
None) ->
None:
482 if iterable
is not None:
483 self.extend(iterable)
484 self.
name = name
if name
else ""
489 def __repr__(self) -> str:
491 return "%s()" % (self.
__class__.__name__,)
492 return "%s(%r)" % (self.
__class__.__name__, list(self))
495 def fitness(self) -> FitnessLike:
496 """Fitness object attached to this candidate."""
500 def fitness(self, fit: FitnessLike) ->
None:
505 def features(self) -> FeaturesLike:
507 """Descriptor object attached to this candidate."""
510 def features(self, ft: FeaturesLike) ->
None:
515 def scores(self) -> ScoresDictLike:
516 """Named measurements attached to this candidate."""
519 def scores(self, scores: ScoresDictLike) ->
None:
520 if type(scores)
is ScoresDict
or (type(scores)
is not dict
and isinstance(scores, ScoresDictLike)):
525 def dominates(self, other: Any, score_name: Optional[str] =
None) -> bool:
526 """Compare fitness or the specified named score by dominance.
528 Without a score name, compare the attached fitness objects.
529 With a name, both candidates must supply a score with a dominance
530 operation at that key.
532 if score_name
is None:
538 """Clear named scores and reset the attached fitness, descriptors, and elapsed time."""
549 return hash(tuple(self))
551 def __eq__(self, other):
552 return (self.
__class__ == other.__class__
and tuple(self) == tuple(other))
556 """Scope a genome's identity to its measured archive cell."""
558 def __init__(self, parameters, cell, **kwargs):
559 super().__init__(parameters, **kwargs)
562 def __eq__(self, other):
563 return type(other)
is type(self)
and self.
_cell == other._cell
and list.__eq__(self, other)
565 def __ne__(self, other):
566 return not self == other
569 return hash((self.
_cell, tuple(self)))
572_COPY_ATOMS = frozenset((float, int, bool, str, bytes, complex, type(
None)))
573_INDIVIDUAL_FIELDS = frozenset((
"name",
"_fitness",
"_features",
"_scores"))
574_TIMED_INDIVIDUAL_FIELDS = _INDIVIDUAL_FIELDS | {
"elapsed"}
575_FITNESS_FIELDS = frozenset((
"weights",
"_values"))
576_FEATURE_FIELDS = frozenset((
"_values",))
579def _flat_values(values, sequence_type):
580 return type(values)
is sequence_type
and all(type(value)
in _COPY_ATOMS
for value
in values)
584def _copy_individual(individual):
585 """Preserve deepcopy semantics for the native scalar genome and fields."""
586 if type(individual)
is not Individual:
587 return copy.deepcopy(individual)
588 state = individual.__dict__
589 if (state.keys()
not in (_INDIVIDUAL_FIELDS, _TIMED_INDIVIDUAL_FIELDS)
590 or type(individual.name)
is not str
or type(individual.elapsed)
is not float):
591 return copy.deepcopy(individual)
592 fitness, features, scores = individual.fitness, individual.features, individual.scores
593 if (type(fitness)
is not Fitness
or fitness.__dict__.keys() != _FITNESS_FIELDS
594 or type(features)
is not Features
or features.__dict__.keys() != _FEATURE_FIELDS
595 or type(scores)
is not ScoresDict
or scores.__dict__
596 or not _flat_values(fitness.values, tuple)
or not _flat_values(fitness.weights, tuple)
597 or not all(type(gene)
in _COPY_ATOMS
for gene
in individual)
598 or not all(type(key)
in _COPY_ATOMS
and type(value)
in _COPY_ATOMS
599 for key, value
in scores.items())):
600 return copy.deepcopy(individual)
602 values = features.values
603 if _flat_values(values, list):
604 values = values.copy()
605 elif not _flat_values(values, tuple):
606 return copy.deepcopy(individual)
607 copied_fitness = Fitness.__new__(Fitness)
608 copied_fitness.__dict__.update(fitness.__dict__)
609 offspring = Individual.__new__(Individual)
610 offspring.extend(individual)
611 offspring.__dict__.update(state, _fitness=copied_fitness, _features=
Features(values), _scores=
ScoresDict(scores))
617 """Generate a fresh empty Individual for each ask, for use as a base candidate generator."""
618 def __init__(self, *args, **kwargs):
626 yield self.__next__()
:param obj: Slice indicating on which objectives the domination is tested.
ScoreValuesLike weighted_values(self, ScoreValuesLike weights)
__setstate__(self, state)
Verify that a snapshot stores unweighted objective values.
bool dominates(self, Any other, Optional[str] score_name=None)
BASE OPTIMISATION CLASSES ########### {{{1.
ScoreValuesLike _comparison_values(self, Optional[ScoreValuesLike] weights)
bool __le__(self, Any other)
ScoreValuesLike weighted_values(self, ScoreValuesLike weights)
bool __eq__(self, Any other)
bool __lt__(self, Any other)
bool dominates(self, Any other, Any obj=slice(None), Optional[ScoreValuesLike] weights=None)
Sequence[Any] select(self, Sequence[str] names)
FitnessLike to_fitness(self, Sequence[str] names, *args, **kwargs)
FeaturesLike to_features(self, Sequence[str] names, *args, **kwargs)
Sequence[Any] select(self, Sequence[str] names)