QDpy
Loading...
Searching...
No Matches
phenotype.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"""Some base classes, stubs and types."""
20#from __future__ import annotations
21
22#__all__ = ["jit"]
23
24
25
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
29import math
30import sys
31import importlib
32import pickle
33import textwrap
34import copy
35from inspect import signature
36from functools import partial
37import warnings
38import numpy as np
39
40import os
41import psutil
42import signal
43import deprecation
44import traceback
45
46from qdpy.utils import *
47from qdpy.base import *
48import qdpy
49
50
51
52ScoreValuesLike = Union[Sequence[Any], np.ndarray]
53FitnessValuesLike = ScoreValuesLike # Union[Sequence[T], np.ndarray]
54#FeaturesLike = Union[Sequence[Any], np.ndarray]
55FeaturesValuesLike = ScoreValuesLike # Union[Sequence[Any], np.ndarray]
56
57@runtime
58class ScoreLike(Protocol):
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: ...
61 @property
62 def values(self) -> ScoreValuesLike: ...
63 @values.setter
64 def values(self, values: ScoreValuesLike) -> None: ...
65 @values.deleter
66 def values(self) -> None: ...
67 @property
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: ...
73
74@runtime
75class FitnessLike(ScoreLike, Protocol):
76 """Fitness protocol inspired from (and compatible with) DEAP Fitness class."""
77 weights: FitnessValuesLike
78# def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool: ...
79# def getValues(self) -> FitnessValuesLike: ...
80# def setValues(self, values: FitnessValuesLike) -> None: ...
81# def delValues(self) -> None: ...
82 @property
83 def values(self) -> FitnessValuesLike: ...
84 @values.setter
85 def values(self, values: FitnessValuesLike) -> None: ...
86 @values.deleter
87 def values(self) -> None: ...
88# @property
89# def valid(self) -> bool: ...
90# def reset(self) -> None: ...
91# @overload
92# def __getitem__(self, i: int) -> Any: ...
93# @overload
94# def __getitem__(self, s: slice) -> Sequence[Any]: ...
95# def __len__(self) -> int: ...
96
97
98@runtime
99class FeaturesLike(ScoreLike, Protocol):
100 """Features protocol similar to the ``FitnessLike`` protocol."""
101 pass
102# def getValues(self) -> FeaturesValuesLike: ...
103# def setValues(self, values: FeaturesValuesLike) -> None: ...
104# def delValues(self) -> None: ...
105# @property
106# def values(self) -> FeaturesValuesLike: ...
107# @values.setter
108# def values(self, values: FeaturesValuesLike) -> None: ...
109# @values.deleter
110# def values(self) -> None: ...
111# @property
112# def valid(self) -> bool: ...
113# def reset(self) -> None: ...
114# def __getitem__(self, key) -> Any: ...
115# def __len__(self) -> int: ...
116
117
118
119@runtime
120class ScoresDictLike(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: ...
132
133
134@runtime
135class IndividualLike(Protocol):
136 """Describe the candidate interface accepted by native QD algorithms.
137
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.
141 """
142 name: str
143 #fitness: FitnessLike
144 @property
145 def fitness(self) -> FitnessLike: ...
146 @fitness.setter
147 def fitness(self, fit: FitnessLike) -> None: ...
148 #features: FeaturesLike
149 @property
150 def features(self) -> FeaturesLike: ...
151 @features.setter
152 def features(self, ft: FeaturesLike) -> None: ...
153 #scores: ScoresDictLike
154 @property
155 def scores(self) -> ScoresDictLike: ...
156 @scores.setter
157 def scores(self, scores: ScoresDictLike) -> None: ...
158 elapsed: float
159 def dominates(self, other: Any) -> bool: ...
160 def reset(self) -> None: ...
161 def __setitem__(self, key, values) -> None: ...
162
163
164
165#FitnessLike = Sequence
166FitnessGetter = Callable[[T], FitnessLike]
167FeaturesGetter = Callable[[T], FeaturesLike]
168GridIndexLike = ShapeLike
169
170
171
172
173
174class Score(ScoreLike, Sequence[Any]):
175 """Represent an ordered vector of measurements.
176
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.
180 """
181 _values: ScoreValuesLike
182
183 def __init__(self, values: ScoreValuesLike=(), *args, **kwargs) -> None:
184 self._values = values
185
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))
190
191 # Inspired by the dominates method from DEAP
192 def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool:
193 """Compare two score vectors by Pareto dominance.
194
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.
198
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.
203 """
204# :param obj: Slice indicating on which objectives the domination is
205# tested. The default value is `slice(None)`, representing
206# every objectives. """
207 self_wvalues = self._comparison_values(weights)[obj]
208 if isinstance(other, Score):
209 other_wvalues = other._comparison_values(weights)[obj]
210 else:
211 other_weights = weights if weights is not None else getattr(other, "weights", None)
212 other_wvalues = (
213 tuple(map(mul, other.values, other_weights)) if other_weights is not None else other.values
214 )[obj]
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:
220 not_equal = True
221 elif self_wvalue < other_wvalue:
222 return False
223 return not_equal
224
225 def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
226 return self.values if weights is None else self.weighted_values(weights)
227
228 @property
229 def valid(self) -> bool:
230 """Assess if a Score is valid or not."""
231 return len(self._values) != 0
232
233 @property
234 def values(self) -> ScoreValuesLike:
235 return self._values
236
237 @values.setter
238 def values(self, values: ScoreValuesLike) -> None:
239 self._values = values
240
241 @values.deleter
242 def values(self) -> None:
243 self._values = ()
244
245 def reset(self) -> None:
246 self._values = (np.nan,) * len(self._values)
247
248 def __len__(self) -> int:
249 return len(self.values)
250
251# @overload
252# def __getitem__(self, index: int) -> T: ...
253#
254# @overload
255# def __getitem__(self, s: slice) -> Sequence: ...
256
257 def __getitem__(self, key):
258 return self.values[key]
259
260 def __setitem__(self, idx, value):
261 self._values[idx] = value
262 #if idx == slice(None, None, None):
263 # self.add_sample(value)
264 #else:
265 # self._values[idx] = value
266
267 def __contains__(self, key: Any) -> bool:
268 return key in self.values
269
270 def __iter__(self) -> Iterator:
271 return iter(self.values)
272
273 def __reversed__(self) -> Iterator:
274 return reversed(self.values)
275
276
277 def __hash__(self) -> int:
278 return hash(self.values)
279
280 def __gt__(self, other: Any) -> bool:
281 return not self.__le__(other)
282
283 def __ge__(self, other: Any) -> bool:
284 return not self.__lt__(other)
285
286 def __le__(self, other: Any) -> bool:
287 return self.values <= other.values
288
289 def __lt__(self, other: Any) -> bool:
290 return self.values < other.values
291
292 def __eq__(self, other: Any) -> bool:
293 return self.values == other.values
294
295 def __ne__(self, other: Any) -> bool:
296 return not self.__eq__(other)
297
298 def __str__(self) -> str:
299 #return str(self.values if self.valid else tuple())
300 return str(self.values)
301
302 def __repr__(self) -> str:
303 if not self:
304 return "%s()" % (self.__class__.__name__,)
305 return "%s(%r)" % (self.__class__.__name__, tuple(self))
306
307
308
310 """Store raw objectives and their comparison weights.
311
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.
315
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.
319 """
320
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)
324 self.values = values
325
326 def __getstate__(self):
327 return {**self.__dict__, "_fitness_state_version": 1}
328
329
333 def __setstate__(self, state):
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.")
336 self.__dict__.update(state)
337
338 def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
339 return self.weighted_values(self.weights if weights is None else weights)
340
341 def weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
342 """Return one weighted value per objective in the same order.
343
344 :param weights: Comparison weights for this calculation.
345 :raises ValueError: If a nonempty fitness and the weights differ
346 in length.
347 """
348 if self.values and len(weights) != len(self.values):
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))
351
352 @property
353 def valid(self) -> bool:
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)
356
357 @property
358 def values(self) -> FitnessValuesLike:
359 """Objective values before applying weights."""
360 return self._values
361
362 @values.setter
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.")
369 self._values = values
370
371 @values.deleter
372 def values(self) -> None:
373 self._values = ()
374
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:
379 return self.values
380
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:
385 self.values = values
386
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:
391 del self.values
392
393# def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool:
394# """Return true if each objective of ``self`` is not strictly worse than
395# the corresponding objective of ``other`` and at least one objective is
396# strictly better.
397# """
398
402
403
404
406 """Hold the ordered behaviour descriptors of a candidate.
407
408 Descriptor coordinates are separate from objectives. A grid expects
409 the vector length and coordinate domains declared by its configuration.
410 """
411
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:
416 return self.values
417
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:
422 self.values = values
423
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:
428 del self.values
429
430
431
433 """Store named measurements that can supply objectives or descriptors.
434
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.
438 """
439
440 def select(self, names: Sequence[str]) -> Sequence[Any]:
441 #if isinstance(names, str):
442 # names = [names]
443 """Return values in name order and use NaN for missing names."""
444 res = []
445 for n in names:
446 res.append(self.get(n, np.nan))
447 return res
448
449 def to_fitness(self, names: Sequence[str], *args, **kwargs) -> FitnessLike:
450 """Build a fitness vector in the requested name order."""
451 return Fitness(self.select(names), *args, **kwargs)
452
453 def to_features(self, names: Sequence[str], *args, **kwargs) -> FeaturesLike:
454 """Build a descriptor vector in the requested name order."""
455 return Features(self.select(names), *args, **kwargs)
456
457
458
460 """Store a mutable genome with separate evaluation results.
461
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.
465
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.
470 """
471
472 name: str
473 _fitness: FitnessLike
474 _features: FeaturesLike
475 _scores: ScoresDictLike
476 elapsed: float = math.nan
477
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 ""
485 self.scores = scores if scores is not None else ScoresDict()
486 self.fitness = fitness if fitness is not None else Fitness()
487 self.features = features if features is not None else Features([])
488
489 def __repr__(self) -> str:
490 if not self:
491 return "%s()" % (self.__class__.__name__,)
492 return "%s(%r)" % (self.__class__.__name__, list(self))
493
494 @property
495 def fitness(self) -> FitnessLike:
496 """Fitness object attached to this candidate."""
497 return self._fitness
498# return self.scores.setdefault("fitness", Fitness())
499 @fitness.setter
500 def fitness(self, fit: FitnessLike) -> None:
501 #self._scores["fitness"] = fit
502 self._fitness = fit
503
504 @property
505 def features(self) -> FeaturesLike:
506 #return self._scores.setdefault("features", Features())
507 """Descriptor object attached to this candidate."""
508 return self._features
509 @features.setter
510 def features(self, ft: FeaturesLike) -> None:
511 #self._scores["features"] = ft
512 self._features = ft
513
514 @property
515 def scores(self) -> ScoresDictLike:
516 """Named measurements attached to this candidate."""
517 return self._scores
518 @scores.setter
519 def scores(self, scores: ScoresDictLike) -> None:
520 if type(scores) is ScoresDict or (type(scores) is not dict and isinstance(scores, ScoresDictLike)):
521 self._scores = scores
522 else:
523 self._scores = ScoresDict(scores)
524
525 def dominates(self, other: Any, score_name: Optional[str] = None) -> bool:
526 """Compare fitness or the specified named score by dominance.
527
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.
531 """
532 if score_name is None:
533 return self.fitness.dominates(other.fitness)
534 else:
535 return self._scores[score_name].dominates(other._scores[score_name])
536
537 def reset(self) -> None:
538 """Clear named scores and reset the attached fitness, descriptors, and elapsed time."""
539 self._scores.clear()
540 self.fitness.reset()
541 #self._scores["fitness"] = self._fitness
542 self.features.reset()
543 #self._scores["features"] = self._features
544 self.elapsed = math.nan
545
546
547 # TODO : improve performance ! (quick and dirty solution !)
548 def __hash__(self):
549 return hash(tuple(self))
550
551 def __eq__(self, other):
552 return (self.__class__ == other.__class__ and tuple(self) == tuple(other))
553
554
556 """Scope a genome's identity to its measured archive cell."""
557
558 def __init__(self, parameters, cell, **kwargs):
559 super().__init__(parameters, **kwargs)
560 self._cell = cell
561
562 def __eq__(self, other):
563 return type(other) is type(self) and self._cell == other._cell and list.__eq__(self, other)
564
565 def __ne__(self, other):
566 return not self == other
567
568 def __hash__(self):
569 return hash((self._cell, tuple(self)))
570
571
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",))
577
578
579def _flat_values(values, sequence_type):
580 return type(values) is sequence_type and all(type(value) in _COPY_ATOMS for value in values)
581
582
583
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)
601
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))
612 return offspring
613
614
615@registry.register # type: ignore
617 """Generate a fresh empty Individual for each ask, for use as a base candidate generator."""
618 def __init__(self, *args, **kwargs):
619 pass
620 def __iter__(self):
621 return self
622 def __next__(self):
623 return Individual()
624 def __call__(self):
625 while(True):
626 yield self.__next__()
627
628
629
630# MODELINE "{{{1
631# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
632# vim:foldmethod=marker
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
ScoreValuesLike weighted_values(self, ScoreValuesLike weights)
Definition phenotype.py:341
__setstate__(self, state)
Verify that a snapshot stores unweighted objective values.
Definition phenotype.py:333
bool dominates(self, Any other, Optional[str] score_name=None)
Definition phenotype.py:525
ScoresDictLike _scores
Definition phenotype.py:521
BASE OPTIMISATION CLASSES ########### {{{1.
Definition phenotype.py:174
ScoreValuesLike _comparison_values(self, Optional[ScoreValuesLike] weights)
Definition phenotype.py:225
bool __le__(self, Any other)
Definition phenotype.py:286
ScoreValuesLike weighted_values(self, ScoreValuesLike weights)
Definition phenotype.py:186
bool __eq__(self, Any other)
Definition phenotype.py:292
bool __lt__(self, Any other)
Definition phenotype.py:289
bool dominates(self, Any other, Any obj=slice(None), Optional[ScoreValuesLike] weights=None)
Definition phenotype.py:192
ScoreValuesLike _values
Definition phenotype.py:184
Sequence[Any] select(self, Sequence[str] names)
Definition phenotype.py:123
FitnessLike to_fitness(self, Sequence[str] names, *args, **kwargs)
Definition phenotype.py:449
FeaturesLike to_features(self, Sequence[str] names, *args, **kwargs)
Definition phenotype.py:453
Sequence[Any] select(self, Sequence[str] names)
Definition phenotype.py:440