# This file is part of qdpy.
#
# qdpy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# qdpy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
## @file
# @brief Genome, fitness, descriptor, and named-score types used by ask/tell.
"""Some base classes, stubs and types."""
#from __future__ import annotations
#__all__ = ["jit"]
########### IMPORTS ########### {{{1
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, MutableMapping, overload
from typing_extensions import runtime, Protocol
from operator import mul, truediv
import math
import sys
import importlib
import pickle
import textwrap
import copy
from inspect import signature
from functools import partial
import warnings
import numpy as np
import os
import psutil
import signal
import deprecation
import traceback
from qdpy.utils import *
from qdpy.base import *
import qdpy
########### INTERFACES AND STUBS ########### {{{1
ScoreValuesLike = Union[Sequence[Any], np.ndarray]
FitnessValuesLike = ScoreValuesLike # Union[Sequence[T], np.ndarray]
#FeaturesLike = Union[Sequence[Any], np.ndarray]
FeaturesValuesLike = ScoreValuesLike # Union[Sequence[Any], np.ndarray]
@runtime
class ScoreLike(Protocol):
"""Protocol describing a generic score, that could be used as a fitness score or as a feature descriptor score."""
def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool: ...
@property
def values(self) -> ScoreValuesLike: ...
@values.setter
def values(self, values: ScoreValuesLike) -> None: ...
@values.deleter
def values(self) -> None: ...
@property
def valid(self) -> bool: ...
def reset(self) -> None: ...
def __getitem__(self, key) -> Any: ...
def __setitem__(self, idx, value) -> None: ...
def __len__(self) -> int: ...
[docs]
@runtime
class FitnessLike(ScoreLike, Protocol):
"""Fitness protocol inspired from (and compatible with) DEAP Fitness class."""
weights: FitnessValuesLike
# def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool: ...
# def getValues(self) -> FitnessValuesLike: ...
# def setValues(self, values: FitnessValuesLike) -> None: ...
# def delValues(self) -> None: ...
@property
def values(self) -> FitnessValuesLike: ...
@values.setter
def values(self, values: FitnessValuesLike) -> None: ...
@values.deleter
def values(self) -> None: ...
# @property
# def valid(self) -> bool: ...
# def reset(self) -> None: ...
# @overload
# def __getitem__(self, i: int) -> Any: ...
# @overload
# def __getitem__(self, s: slice) -> Sequence[Any]: ...
# def __len__(self) -> int: ...
[docs]
@runtime
class FeaturesLike(ScoreLike, Protocol):
"""Features protocol similar to the ``FitnessLike`` protocol."""
pass
# def getValues(self) -> FeaturesValuesLike: ...
# def setValues(self, values: FeaturesValuesLike) -> None: ...
# def delValues(self) -> None: ...
# @property
# def values(self) -> FeaturesValuesLike: ...
# @values.setter
# def values(self, values: FeaturesValuesLike) -> None: ...
# @values.deleter
# def values(self) -> None: ...
# @property
# def valid(self) -> bool: ...
# def reset(self) -> None: ...
# def __getitem__(self, key) -> Any: ...
# def __len__(self) -> int: ...
[docs]
@runtime
class ScoresDictLike(Protocol):
"""Protocol containing a map of scores values, which could then be selected as fitness scores or as feature descriptor scores."""
def clear(self) -> None: ...
def select(self, names: Sequence[str]) -> Sequence[Any]: ...
def to_fitness(self, names: Sequence[str], *args, **kwargs) -> FitnessLike: ...
def to_features(self, names: Sequence[str], *args, **kwargs) -> FeaturesLike: ...
def __getitem__(self, key) -> Any: ...
def __setitem__(self, key, value) -> None: ...
def __contains__(self, value) -> bool: ...
def items(self) -> Any: ...
def keys(self) -> Any: ...
def values(self) -> Any: ...
[docs]
@runtime
class IndividualLike(Protocol):
"""Describe the candidate interface accepted by native QD algorithms.
A candidate exposes a mutable genome, fitness, descriptors, scores,
and a reset operation. Implementations used in hash-based containers
also need stable equality and hashing while stored.
"""
name: str
#fitness: FitnessLike
@property
def fitness(self) -> FitnessLike: ...
@fitness.setter
def fitness(self, fit: FitnessLike) -> None: ...
#features: FeaturesLike
@property
def features(self) -> FeaturesLike: ...
@features.setter
def features(self, ft: FeaturesLike) -> None: ...
#scores: ScoresDictLike
@property
def scores(self) -> ScoresDictLike: ...
@scores.setter
def scores(self, scores: ScoresDictLike) -> None: ...
elapsed: float
def dominates(self, other: Any) -> bool: ...
def reset(self) -> None: ...
def __setitem__(self, key, values) -> None: ...
#FitnessLike = Sequence
FitnessGetter = Callable[[T], FitnessLike]
FeaturesGetter = Callable[[T], FeaturesLike]
GridIndexLike = ShapeLike
########### BASE OPTIMISATION CLASSES ########### {{{1
[docs]
class Score(ScoreLike, Sequence[Any]):
"""Represent an ordered vector of measurements.
The sequence interface exposes the stored values. Equality and
ordering operators use raw values. Use :meth:`dominates` for Pareto
comparisons. An empty vector represents missing measurements.
"""
_values: ScoreValuesLike
def __init__(self, values: ScoreValuesLike=(), *args, **kwargs) -> None:
self._values = values
def weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
return tuple(map(mul, self, weights))
def inv_weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
return tuple(map(truediv, self, weights))
# Inspired by the dominates method from DEAP
[docs]
def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool:
"""Compare two score vectors by Pareto dominance.
Every selected value must be at least as good as its counterpart,
and at least one must be strictly better. A plain score treats
larger values as better. A fitness uses objective weights.
:param other: Score to compare against.
:param obj: Slice selecting the objectives to compare.
:param weights: Optional comparison weights applied to both vectors.
:raises ValueError: If the selected vectors have different lengths.
"""
# :param obj: Slice indicating on which objectives the domination is
# tested. The default value is `slice(None)`, representing
# every objectives. """
self_wvalues = self._comparison_values(weights)[obj]
if isinstance(other, Score):
other_wvalues = other._comparison_values(weights)[obj]
else:
other_weights = weights if weights is not None else getattr(other, "weights", None)
other_wvalues = (
tuple(map(mul, other.values, other_weights)) if other_weights is not None else other.values
)[obj]
if len(self_wvalues) != len(other_wvalues):
raise ValueError("Scores must have the same dimension to compare them.")
not_equal: bool = False
for self_wvalue, other_wvalue in zip(self_wvalues, other_wvalues):
if self_wvalue > other_wvalue:
not_equal = True
elif self_wvalue < other_wvalue:
return False
return not_equal
def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
return self.values if weights is None else self.weighted_values(weights)
@property
def valid(self) -> bool:
"""Assess if a Score is valid or not."""
return len(self._values) != 0
@property
def values(self) -> ScoreValuesLike:
return self._values
@values.setter
def values(self, values: ScoreValuesLike) -> None:
self._values = values
@values.deleter
def values(self) -> None:
self._values = ()
def reset(self) -> None:
self._values = (np.nan,) * len(self._values)
def __len__(self) -> int:
return len(self.values)
# @overload
# def __getitem__(self, index: int) -> T: ...
#
# @overload
# def __getitem__(self, s: slice) -> Sequence: ...
def __getitem__(self, key):
return self.values[key]
def __setitem__(self, idx, value):
self._values[idx] = value
#if idx == slice(None, None, None):
# self.add_sample(value)
#else:
# self._values[idx] = value
def __contains__(self, key: Any) -> bool:
return key in self.values
def __iter__(self) -> Iterator:
return iter(self.values)
def __reversed__(self) -> Iterator:
return reversed(self.values)
def __hash__(self) -> int:
return hash(self.values)
def __gt__(self, other: Any) -> bool:
return not self.__le__(other)
def __ge__(self, other: Any) -> bool:
return not self.__lt__(other)
def __le__(self, other: Any) -> bool:
return self.values <= other.values
def __lt__(self, other: Any) -> bool:
return self.values < other.values
def __eq__(self, other: Any) -> bool:
return self.values == other.values
def __ne__(self, other: Any) -> bool:
return not self.__eq__(other)
def __str__(self) -> str:
#return str(self.values if self.valid else tuple())
return str(self.values)
def __repr__(self) -> str:
if not self:
return "%s()" % (self.__class__.__name__,)
return "%s(%r)" % (self.__class__.__name__, tuple(self))
[docs]
class Fitness(Score, FitnessLike):
"""Store raw objectives and their comparison weights.
Supply one weight per objective. Negative weights minimise and
positive weights maximise. A weight of zero ignores its objective
in a weighted comparison. The default is minimisation.
Assigning weights keeps the raw objective values unchanged.
Empty fitness and fitness containing NaN are invalid. Use container
domains to specify which otherwise valid scores may enter an archive.
"""
weights: FitnessValuesLike = ()
def __init__(self, values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=None) -> None:
self.weights = tuple(self.weights if weights is None else weights)
self.values = values
def __getstate__(self):
return {**self.__dict__, "_fitness_state_version": 1}
## @brief Verify that a snapshot stores unweighted objective values.
# @param state Serialized fitness attributes with a format marker.
# @throws ValueError If the marker is absent or unsupported. An
# older weighted tuple could otherwise be read as a raw objective.
def __setstate__(self, state):
if state.pop("_fitness_state_version", None) != 1:
raise ValueError("This result uses an unsupported fitness format. Rerun the experiment with this QDpy version.")
self.__dict__.update(state)
def _comparison_values(self, weights: Optional[ScoreValuesLike]) -> ScoreValuesLike:
return self.weighted_values(self.weights if weights is None else weights)
[docs]
def weighted_values(self, weights: ScoreValuesLike) -> ScoreValuesLike:
"""Return one weighted value per objective in the same order.
:param weights: Comparison weights for this calculation.
:raises ValueError: If a nonempty fitness and the weights differ
in length.
"""
if self.values and len(weights) != len(self.values):
raise ValueError("Fitness values and weights must have the same length.")
return tuple(value * weight if weight != 0 else 0.0 for value, weight in zip(self.values, weights))
@property
def valid(self) -> bool:
"""Whether the fitness has at least one objective and contains no NaN values."""
return bool(self.values) and not any(math.isnan(value) for value in self.values)
@property
def values(self) -> FitnessValuesLike:
"""Objective values before applying weights."""
return self._values
@values.setter
def values(self, values: FitnessValuesLike) -> None:
values = tuple(values)
if values and not len(self.weights):
self.weights = (-1.0,) * len(values)
if values and len(self.weights) != len(values):
raise ValueError("Fitness values and weights must have the same length.")
self._values = values
@values.deleter
def values(self) -> None:
self._values = ()
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'foo = fitness.values' instead.")
def getValues(self) -> FitnessValuesLike:
return self.values
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'fitness.values = (42,)' instead.")
def setValues(self, values: FitnessValuesLike) -> None:
self.values = values
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'del fitness.values' instead.")
def delValues(self) -> None:
del self.values
# def dominates(self, other: Any, obj: Any = slice(None), weights: Optional[ScoreValuesLike] = None) -> bool:
# """Return true if each objective of ``self`` is not strictly worse than
# the corresponding objective of ``other`` and at least one objective is
# strictly better.
# """
## :param obj: Slice indicating on which objectives the domination is
## tested. The default value is `slice(None)`, representing
## every objectives. """
# return super().dominates(other, None, obj)
[docs]
class Features(Score, FeaturesLike):
"""Hold the ordered behaviour descriptors of a candidate.
Descriptor coordinates are separate from objectives. A grid expects
the vector length and coordinate domains declared by its configuration.
"""
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'foo = features.values' instead. ")
def getValues(self) -> FeaturesValuesLike:
return self.values
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'features.values = (42,)' instead. ")
def setValues(self, values: FeaturesValuesLike) -> None:
self.values = values
@deprecation.deprecated(deprecated_in="0.1.3", removed_in="0.2.0",
current_version=qdpy.__version__,
details="Use 'del features.values' instead. ")
def delValues(self) -> None:
del self.values
[docs]
class ScoresDict(dict, ScoresDictLike):
"""Store named measurements that can supply objectives or descriptors.
Containers select measurements in their configured name order.
A missing name yields NaN, which fails validation in a bounded
descriptor domain or as fitness.
"""
[docs]
def select(self, names: Sequence[str]) -> Sequence[Any]:
#if isinstance(names, str):
# names = [names]
"""Return values in name order and use NaN for missing names."""
res = []
for n in names:
res.append(self.get(n, np.nan))
return res
[docs]
def to_fitness(self, names: Sequence[str], *args, **kwargs) -> FitnessLike:
"""Build a fitness vector in the requested name order."""
return Fitness(self.select(names), *args, **kwargs)
[docs]
def to_features(self, names: Sequence[str], *args, **kwargs) -> FeaturesLike:
"""Build a descriptor vector in the requested name order."""
return Features(self.select(names), *args, **kwargs)
[docs]
class Individual(list, IndividualLike):
"""Store a mutable genome with separate evaluation results.
The list contents are the genome. Fitness, descriptors, named
scores, elapsed evaluation time, and the name are stored separately.
Genome equality is independent of those measurements.
Keep the genome unchanged while the candidate is in an archive.
Use a copy for mutation or remove the candidate before editing it.
Updating the descriptor of a stored individual does not relocate
its grid cell automatically.
"""
name: str
_fitness: FitnessLike
_features: FeaturesLike
_scores: ScoresDictLike
elapsed: float = math.nan
def __init__(self, iterable: Optional[Iterable] = None,
name: Optional[str] = None,
fitness: Optional[FitnessLike] = None, features: Optional[FeaturesLike] = None,
scores: Optional[ScoresDictLike] = None) -> None:
if iterable is not None:
self.extend(iterable)
self.name = name if name else ""
self.scores = scores if scores is not None else ScoresDict()
self.fitness = fitness if fitness is not None else Fitness()
self.features = features if features is not None else Features([])
def __repr__(self) -> str:
if not self:
return "%s()" % (self.__class__.__name__,)
return "%s(%r)" % (self.__class__.__name__, list(self))
@property
def fitness(self) -> FitnessLike:
"""Fitness object attached to this candidate."""
return self._fitness
# return self.scores.setdefault("fitness", Fitness())
@fitness.setter
def fitness(self, fit: FitnessLike) -> None:
#self._scores["fitness"] = fit
self._fitness = fit
@property
def features(self) -> FeaturesLike:
#return self._scores.setdefault("features", Features())
"""Descriptor object attached to this candidate."""
return self._features
@features.setter
def features(self, ft: FeaturesLike) -> None:
#self._scores["features"] = ft
self._features = ft
@property
def scores(self) -> ScoresDictLike:
"""Named measurements attached to this candidate."""
return self._scores
@scores.setter
def scores(self, scores: ScoresDictLike) -> None:
if type(scores) is ScoresDict or (type(scores) is not dict and isinstance(scores, ScoresDictLike)):
self._scores = scores
else:
self._scores = ScoresDict(scores)
[docs]
def dominates(self, other: Any, score_name: Optional[str] = None) -> bool:
"""Compare fitness or the specified named score by dominance.
Without a score name, compare the attached fitness objects.
With a name, both candidates must supply a score with a dominance
operation at that key.
"""
if score_name is None:
return self.fitness.dominates(other.fitness)
else:
return self._scores[score_name].dominates(other._scores[score_name])
[docs]
def reset(self) -> None:
"""Clear named scores and reset the attached fitness, descriptors, and elapsed time."""
self._scores.clear()
self.fitness.reset()
#self._scores["fitness"] = self._fitness
self.features.reset()
#self._scores["features"] = self._features
self.elapsed = math.nan
# TODO : improve performance ! (quick and dirty solution !)
def __hash__(self):
return hash(tuple(self))
def __eq__(self, other):
return (self.__class__ == other.__class__ and tuple(self) == tuple(other))
class _CellIndividual(Individual):
"""Scope a genome's identity to its measured archive cell."""
def __init__(self, parameters, cell, **kwargs):
super().__init__(parameters, **kwargs)
self._cell = cell
def __eq__(self, other):
return type(other) is type(self) and self._cell == other._cell and list.__eq__(self, other)
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((self._cell, tuple(self)))
_COPY_ATOMS = frozenset((float, int, bool, str, bytes, complex, type(None)))
_INDIVIDUAL_FIELDS = frozenset(("name", "_fitness", "_features", "_scores"))
_TIMED_INDIVIDUAL_FIELDS = _INDIVIDUAL_FIELDS | {"elapsed"}
_FITNESS_FIELDS = frozenset(("weights", "_values"))
_FEATURE_FIELDS = frozenset(("_values",))
def _flat_values(values, sequence_type):
return type(values) is sequence_type and all(type(value) in _COPY_ATOMS for value in values)
## @brief Copy a flat native individual, with deepcopy for user-defined state.
def _copy_individual(individual):
"""Preserve deepcopy semantics for the native scalar genome and fields."""
if type(individual) is not Individual:
return copy.deepcopy(individual)
state = individual.__dict__
if (state.keys() not in (_INDIVIDUAL_FIELDS, _TIMED_INDIVIDUAL_FIELDS)
or type(individual.name) is not str or type(individual.elapsed) is not float):
return copy.deepcopy(individual)
fitness, features, scores = individual.fitness, individual.features, individual.scores
if (type(fitness) is not Fitness or fitness.__dict__.keys() != _FITNESS_FIELDS
or type(features) is not Features or features.__dict__.keys() != _FEATURE_FIELDS
or type(scores) is not ScoresDict or scores.__dict__
or not _flat_values(fitness.values, tuple) or not _flat_values(fitness.weights, tuple)
or not all(type(gene) in _COPY_ATOMS for gene in individual)
or not all(type(key) in _COPY_ATOMS and type(value) in _COPY_ATOMS
for key, value in scores.items())):
return copy.deepcopy(individual)
values = features.values
if _flat_values(values, list):
values = values.copy()
elif not _flat_values(values, tuple):
return copy.deepcopy(individual)
copied_fitness = Fitness.__new__(Fitness)
copied_fitness.__dict__.update(fitness.__dict__)
offspring = Individual.__new__(Individual)
offspring.extend(individual)
offspring.__dict__.update(state, _fitness=copied_fitness, _features=Features(values), _scores=ScoresDict(scores))
return offspring
@registry.register # type: ignore
class GenIndividuals(CreatableFromConfig):
"""Generate a fresh empty Individual for each ask, for use as a base candidate generator."""
def __init__(self, *args, **kwargs):
pass
def __iter__(self):
return self
def __next__(self):
return Individual()
def __call__(self):
while(True):
yield self.__next__()
# MODELINE "{{{1
# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
# vim:foldmethod=marker