# 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 Sampled phenotype types and resampling policies for noisy evaluators.
"""Sampled measurements and budgeted resampling decorators."""
__all__ = ["SampleAveragingStrategy", "ExplicitSampleAveragingStrategy", "SampledFitness", "SampledFeatures", "SampledIndividual", "GenSampledIndividuals", "SamplingDecorator", "FixedSamplingDecorator", "TimeBasedSamplingDecorator", "AdaptiveSamplingDecorator"]
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
from collections import deque
import copy
from dataclasses import dataclass, field
import math
from uuid import uuid4
import warnings
import numpy as np
from .base import *
from qdpy.base import *
from qdpy.phenotype import *
from qdpy.utils import *
from qdpy.containers import *
from qdpy import tools
[docs]
@runtime
class SampleAveragingStrategy(Protocol):
"""Reduce a sequence of observed score vectors to one representative vector."""
def sample(self, collection: Sequence[Any]) -> Tuple: ...
[docs]
class ExplicitSampleAveragingStrategy(SampleAveragingStrategy):
"""Return the coordinate-wise arithmetic mean, or an empty tuple for no samples."""
def sample(self, collection: Sequence[Any]) -> Tuple:
if len(collection) > 0:
return tuple(np.mean(np.array(collection), axis=0))
else:
return ()
[docs]
class SampledFitness(Fitness):
"""Keep individual fitness observations and expose their mean as Fitness.
Setting values appends a raw observation. Dominance applies comparison
weights to the aggregate. Changing weights leaves the observations
unchanged. Reset before gathering an independent estimate.
"""
sampling_strategy: SampleAveragingStrategy
##nb_samples: int
_samples: List[FitnessValuesLike]
# def __new__(cls, values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=None):
# return super(Fitness, cls).__new__(cls)
def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=None) -> None:
self.sampling_strategy = sampling_strategy
self._samples = []
self._values = ()
super().__init__((), weights)
self.add_sample(values)
[docs]
def reset(self) -> None:
"""Clear the recorded samples and invalidate the aggregate fitness."""
del self.values
def _compute_values(self) -> None:
Fitness.values.fset(self, self.sampling_strategy.sample(self._samples))
@Fitness.values.setter
def values(self, values: FitnessValuesLike) -> None:
self.add_sample(values)
@values.deleter
def values(self) -> None:
self._samples = []
self._values = ()
@property
def samples(self) -> Sequence[FitnessValuesLike]:
"""Return a new list containing the raw objective observations."""
return list(self._samples)
@property
def nb_samples(self) -> int:
"""Number of contributing fitness observations."""
return len(self._samples)
[docs]
def add_sample(self, sample) -> None:
"""Add a nonempty raw objective vector and refresh the aggregate."""
sample = tuple(sample)
if not sample:
return
if len(self.weights) and len(sample) != len(self.weights):
raise ValueError("Fitness values and weights must have the same length.")
self._samples.append(sample)
self._compute_values()
def merge(self, other) -> None:
"""Append the observations from another sampled fitness and recompute the aggregate."""
self._samples += [x for x in other._samples if x != ()]
self._compute_values()
#print("DEBUG merge:", self._samples)
[docs]
class SampledFeatures(Features):
"""Keep descriptor observations and expose their coordinate-wise aggregate."""
sampling_strategy: SampleAveragingStrategy
#_nb_samples: int
_samples: List[FeaturesValuesLike]
def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), *args, **kwargs) -> None:
self.sampling_strategy = sampling_strategy
self._samples = []
super().__init__(*args, **kwargs)
self.add_sample(self._values)
def reset(self) -> None:
super().reset()
self._samples = []
def _compute_values(self) -> None:
##if self._samples_changed:
##print("DEBUG _compute_values:", self._samples, self.sampling_strategy.sample(self._samples))
self._values = tuple(self.sampling_strategy.sample(self._samples))
#self._values = np.mean(np.array(self._samples), axis=0)
# XXX slow
@property
def values(self) -> FeaturesValuesLike:
#self._compute_values()
return self._values
# XXX slow
@values.setter
def values(self, values: FeaturesValuesLike) -> None:
self.add_sample(values)
@property
def samples(self) -> List[FeaturesValuesLike]:
"""Return a new list containing the observed descriptor vectors."""
return list(self._samples)
@property
def nb_samples(self) -> int:
"""Number of retained descriptor observations."""
return len(self._samples)
[docs]
def add_sample(self, sample) -> None:
"""Add a nonempty descriptor observation and refresh the aggregate."""
sample = tuple(sample)
if sample:
self._samples.append(sample)
self._compute_values()
def merge(self, other) -> None:
"""Combine recorded descriptor observations with another sampled vector."""
self._samples += other._samples
self._compute_values()
## @brief Legacy named score mapping with a separate history of sample vectors.
class SampledScores(ScoresDict):
"""Read old named score mappings and their original sample history.
This compatibility class is deprecated for new experiments. As in
QDpy 0.1.3, named lookups read the mapping and samples are stored
separately. Use a sampling decorator for new repeated evaluations.
:param sampling_strategy: Reducer used for the stored sample vectors.
:param args: Initial mapping arguments passed to :class:`ScoresDict`.
:param kwargs: Initial named measurements.
"""
def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(),
*args, **kwargs) -> None:
warnings.warn("SampledScores is deprecated. Use ScoresDict and a sampling decorator for new runs.",
DeprecationWarning, stacklevel=2)
self.sampling_strategy = sampling_strategy
self._samples = []
super().__init__(*args, **kwargs)
self._compute_values()
def _compute_values(self) -> None:
self._values = tuple(self.sampling_strategy.sample(self._samples))
## @brief Return a copy of the sample history in observation order.
@property
def samples(self):
return list(self._samples)
## @brief Count the stored sample vectors.
@property
def nb_samples(self) -> int:
return len(self._samples)
## @brief Append a sample and recompute the legacy aggregate.
def add_sample(self, sample) -> None:
self._samples.append(sample)
self._compute_values()
## @brief Append another mapping's sample history.
def merge(self, other) -> None:
self._samples += other._samples
self._compute_values()
## @brief Remove the named measurements and recorded samples.
def clear(self) -> None:
super().clear()
self._samples = []
[docs]
class SampledIndividual(Individual):
"""Represent one genome evaluated several times.
Fitness and features are independent sample accumulators. The
sampling decorator tracks the total expected observations on each
proposal before reporting aggregated feedback to the base search.
"""
def __init__(self, iterable: Optional[Iterable] = None,
name: Optional[str] = None,
fitness: Optional[FitnessLike] = None, features: Optional[FeaturesLike] = None) -> None:
fitness = SampledFitness() if fitness is None else fitness
features = SampledFeatures() if features is None else features
super().__init__(iterable, name, fitness, features)
self.expected_max_samples = 1
assert(isinstance(fitness, SampledFitness))
assert(isinstance(features, SampledFeatures))
def reset(self):
super().reset()
self.expected_max_samples = 1
self.__dict__.pop("_observations", None)
[docs]
def merge(self, other):
"""Merge another evaluation's fitness and descriptors and add its elapsed time."""
self.fitness.merge(other.fitness)
self.features.merge(other.features)
self.elapsed += other.elapsed
@property
def nb_samples(self) -> int:
"""Count fitness observations. The scheduling interface uses a minimum count of one."""
return self.fitness.nb_samples or 1 # type: ignore # XXX hack ?
@registry.register
class GenSampledIndividuals(GenIndividuals):
"""Supply fresh sampled candidates to an ask/tell optimiser."""
def __next__(self):
return SampledIndividual()
## @brief One successful rollout with paired objective, descriptor and named measurements.
@dataclass(frozen=True)
class _Observation:
fitness: tuple
features: tuple
scores: dict
elapsed: float = 0.
## @brief Extract one raw rollout using the archive's configured score names.
def _observe(archive, individual, fitness=None, features=None, scores=None, elapsed=None):
named = dict(individual.scores if scores is None else scores)
fitness_names = archive.fitness_score_names
if fitness is None:
fitness = [named[name] for name in fitness_names] if fitness_names else individual.fitness.values
elif hasattr(fitness, "values"):
fitness = fitness.values
features_names = archive.features_score_names
if features_names:
features = [named[name] for name in features_names]
elif features is None:
features = individual.features.values
fitness, features = tuple(fitness), tuple(features)
for name, value in zip(fitness_names, fitness):
named[name] = value
return _Observation(fitness, features, copy.deepcopy(named), elapsed or 0.)
## @brief Interpret an ordinary QDpy evaluator result.
def _observe_result(archive, candidate, result, elapsed=0.):
if hasattr(result, "fitness") and hasattr(result, "features"):
return _observe(archive, result, elapsed=elapsed)
if len(result) == 0:
return _observe(archive, candidate, elapsed=elapsed)
if len(result) in (2, 3):
return _observe(archive, candidate, *result, elapsed=elapsed)
raise ValueError("Expected an evaluated individual or a tuple of fitness, descriptors and optional scores.")
## @brief Derive a repeatable seed in a separate search or audit stream.
def _rollout_seed(seed, stream, index):
return int(np.random.SeedSequence([seed, stream, index]).generate_state(1, dtype=np.uint64)[0])
## @brief Copy a proposal for evaluation without carrying its old measurements.
def _fresh(individual):
candidate = copy.deepcopy(individual)
candidate.reset()
for attribute in ("_observations", "evaluation_seed", "_sampling_owner"):
if hasattr(candidate, attribute):
delattr(candidate, attribute)
return candidate
## @brief Use retained rollout pairs or reconstruct the history of an older sampled individual.
def _history(archive, individual):
if hasattr(individual, "_observations"):
return individual._observations
if isinstance(individual, SampledIndividual) and individual.fitness.nb_samples:
fitness = individual.fitness.samples
descriptors = individual.features.samples
return [_Observation(row, descriptors[i] if i < len(descriptors) else tuple(individual.features),
dict(individual.scores))
for i, row in enumerate(fitness)]
return [_observe(archive, individual)]
## @brief Install aggregated measurements and retain their complete paired history.
# @details Numeric named scores with one common shape are reduced over
# observations that supply them. Other payloads retain the last supplied value.
def _aggregate(archive, individual, observations, estimator=None):
fitness_rows = [obs.fitness for obs in observations]
features_rows = [obs.features for obs in observations]
fit_reducer = estimator or getattr(getattr(individual.fitness, "sampling_strategy", None),
"sample", None) or (lambda rows: np.mean(rows, axis=0))
ft_reducer = estimator or getattr(getattr(individual.features, "sampling_strategy", None),
"sample", None) or (lambda rows: np.mean(rows, axis=0))
fitness = tuple(fit_reducer(fitness_rows))
features = tuple(ft_reducer(features_rows))
scores = {}
keys = {key: None for obs in observations for key in obs.scores}
for key in keys:
values = [obs.scores[key] for obs in observations if key in obs.scores]
try:
array = np.asarray(values)
except (TypeError, ValueError):
array = None
scores[key] = (np.mean(array, axis=0) if array is not None and array.dtype.kind in "buifc"
else copy.deepcopy(values[-1]))
scores.update(zip(archive.fitness_score_names, fitness))
scores.update(zip(archive.features_score_names, features))
if isinstance(individual.fitness, SampledFitness):
individual.fitness._samples = fitness_rows
Fitness.values.fset(individual.fitness, fitness)
else:
individual.fitness.values = fitness
if isinstance(individual.features, SampledFeatures):
individual.features._samples = features_rows
individual.features._values = features
else:
individual.features.values = features
individual.scores = scores
individual.elapsed = sum(obs.elapsed for obs in observations)
individual._observations = observations
return individual
## @brief Validate a rollout before adding it to an aggregate.
def _valid_observation(observation, objectives, descriptor_count):
if len(observation.fitness) != objectives:
raise ValueError("The rollout returned the wrong number of objectives.")
if descriptor_count is not None and len(observation.features) != descriptor_count:
raise ValueError("The rollout returned the wrong number of descriptors.")
if not all(math.isfinite(value) for value in (*observation.fitness, *observation.features)):
raise ValueError("The rollout returned nonfinite measurements.")
## @brief Copy archive bookkeeping while preserving candidate and parent identity.
def _stage_archive(archive):
memo = {id(ind): ind for ind in archive}
memo[id(archive.parents)] = archive.parents
staged = copy.deepcopy(archive, memo)
staged.parents = []
return staged
## @brief Readmit a revised incumbent without exposing intermediate archive states.
# @details A valid move that loses to the destination cell's elite removes
# the old placement. Validation or parent admission errors keep it intact.
def _replace_observation(archive, original, revised):
if not any(ind is original for ind in archive):
return False
staged = _stage_archive(archive)
staged._check_if_can_be_added(revised)
staged.discard(original)
added = staged.add(revised) is not None
if not archive.only_add_accepted_inds_to_parents or added:
archive._add_to_parents(revised, True)
staged.parents = archive.parents
archive.__dict__.update(staged.__dict__)
return added
## @brief Track one pending offspring or incumbent and its requested rollout slots.
@dataclass
class _SampleRequest:
individual: IndividualLike
target: int
incumbent: IndividualLike | None = None
submitted: int = 0
resolved: int = 0
observations: dict = field(default_factory=dict)
## @brief Wrap an optimiser to aggregate one or more rollouts per proposal.
[docs]
class SamplingDecorator(QDAlgorithm):
"""Schedule repeats independently of genome equality or worker completion order.
``budget`` and ``batch_size`` count attempted rollouts. If ``seed`` is
supplied, each evaluator input carries a deterministic ``evaluation_seed``.
One aggregated feedback event is sent to the base optimiser for each
completed offspring. Incumbent reevaluation only updates the archive.
:param base_alg: Emitter that generates proposals and receives aggregate feedback.
:param seed: Nonnegative seed for rollout IDs, or None to leave seeding to the evaluator.
:ivar failed_evaluations: Number of failed or malformed rollout attempts.
"""
def __init__(self, base_alg: QDAlgorithm, *, seed=None, **kwargs):
container = kwargs.pop("container", base_alg.container)
if container is not base_alg.container:
raise ValueError("A sampling decorator must use the same container as its base algorithm.")
self.base_alg = base_alg
self.seed = seed
kwargs.setdefault("batch_size", base_alg.batch_size)
kwargs.setdefault("dimension", base_alg.dimension)
kwargs.setdefault("optimisation_task", base_alg.optimisation_task)
kwargs.setdefault("name", base_alg.name)
kwargs.setdefault("budget", base_alg.budget)
kwargs.setdefault("nb_objectives", base_alg._nb_objectives)
generator = kwargs.pop("base_ind_gen", None)
if base_alg._base_ind_gen is None:
base_alg._base_ind_gen = GenSampledIndividuals() if generator is None else generator
self._sampler_id = uuid4().hex
super().__init__(container=container, **kwargs)
## @brief Reset counters and discard outstanding work.
def reinit(self):
self._clear_requests()
self.failed_evaluations = 0
super().reinit()
## @brief Release proposal feedback ownership after the search or restart.
def _clear_requests(self):
for request in getattr(self, "_requests", {}).values():
if request.incumbent is None:
self.base_alg._forget_suggestion(request.individual)
self._requests = {}
self._rollouts = {}
self.inds_to_ask = deque()
self.staging_inds = []
@property
def dimension(self):
return self.base_alg.dimension
@dimension.setter
def dimension(self, dimension):
self.base_alg.dimension = dimension
## @brief Select the initial count for a fresh proposal.
def _target(self, individual):
return 1
## @brief Queue a materialized request with an object-independent ID.
def _queue(self, individual, target, incumbent=None):
request = _SampleRequest(individual, target, incumbent)
key = id(request)
self._requests[key] = request
self.inds_to_ask.append(key)
return key
## @brief Request the next rollout or start an independent offspring.
def _internal_ask(self, base_ind):
if not self.inds_to_ask:
individual = self.base_alg.ask()
self._queue(individual, self._target(individual))
key = self.inds_to_ask[0]
request = self._requests[key]
candidate = _fresh(request.individual)
if isinstance(candidate, SampledIndividual):
candidate.expected_max_samples = request.target
candidate._sampling_owner = self._sampler_id
if self.seed is not None:
candidate.evaluation_seed = _rollout_seed(self.seed, 0, self.nb_suggestions)
self._rollouts[id(candidate)] = (candidate, key, request.submitted)
request.submitted += 1
if request.submitted == request.target:
self.inds_to_ask.popleft()
return candidate
## @brief Keep the rollout slot when a worker returns a replacement object.
def _transfer_suggestion(self, individual, evaluated):
pending = self._rollouts.pop(id(individual), None)
if pending is not None:
self._rollouts[id(evaluated)] = (evaluated, *pending[1:])
evaluated._sampling_owner = self._sampler_id
## @brief Mark a failed rollout resolved. The executor accounts for its cost.
def _forget_suggestion(self, individual):
pending = self._rollouts.pop(id(individual), None)
if pending is not None:
self.failed_evaluations += 1
self._resolve(pending[1], pending[2], None, True)
## @brief Allow a policy to increase a completed request's target.
def _next_target(self, individual, sample_count):
return sample_count
## @brief Collect a rollout and publish measurements only after a complete decision.
def _resolve(self, key, slot, observation, tell_container):
request = self._requests[key]
request.resolved += 1
if observation is not None:
request.observations[slot] = observation
if request.resolved < request.target:
return False
if len(request.observations) < request.target:
del self._requests[key]
if request.incumbent is None:
self.base_alg._forget_suggestion(request.individual)
return False
rows = [request.observations[i] for i in sorted(request.observations)]
descriptor_width = len(rows[0].features)
inconsistent = sum(len(row.features) != descriptor_width for row in rows)
if inconsistent:
self.failed_evaluations += inconsistent
warnings.warn("A sampled candidate returned inconsistent descriptor lengths.", stacklevel=2)
del self._requests[key]
if request.incumbent is None:
self.base_alg._forget_suggestion(request.individual)
return False
if request.incumbent is not None:
rows = list(_history(self.container, request.incumbent)) + rows
individual = _aggregate(self.container, request.individual, rows)
if isinstance(individual, SampledIndividual):
individual.expected_max_samples = len(rows)
if request.incumbent is None:
target = self._next_target(individual, len(rows))
if target > request.target:
request.target = target
self.inds_to_ask.appendleft(key)
return False
del self._requests[key]
if request.incumbent is not None:
return tell_container and _replace_observation(self.container, request.incumbent, individual)
return self.base_alg.tell(individual, tell_container=tell_container)
## @brief Resolve one observation or admit a manually evaluated individual.
def tell(self, individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False,
tell_container=True):
pending = self._rollouts.get(id(individual))
if pending is None and getattr(individual, "_sampling_owner", None) == self._sampler_id:
raise ValueError("The rollout has already been resolved or belongs to an ended search.")
observation = _observe(self.container, individual, fitness, features, scores, elapsed)
descriptor_count = None if self.container.features_domain is None else len(self.container.features_domain)
_valid_observation(observation, self._nb_objectives, descriptor_count)
if pending is None:
added = self.base_alg.tell(individual, fitness, features, scores, elapsed, verbose,
tell_container)
else:
self._rollouts.pop(id(individual))
added = self._resolve(pending[1], pending[2], observation, tell_container)
self._tell_after_container_update(individual, added)
return added
## @brief Treat invalid worker measurements as failed rollout slots.
def _tell_evaluation_result(self, individual, result, elapsed, verbose):
try:
observation = _observe_result(self.container, individual, result, elapsed)
descriptor_count = None if self.container.features_domain is None else len(self.container.features_domain)
_valid_observation(observation, self._nb_objectives, descriptor_count)
except (KeyError, TypeError, ValueError) as error:
warnings.warn(f"Invalid sampling result: {error}")
return False
pending = self._rollouts.pop(id(individual))
if hasattr(result, "fitness") and hasattr(result, "features"):
result._sampling_owner = self._sampler_id
added = self._resolve(pending[1], pending[2], observation, True)
self._tell_after_container_update(individual, added)
return True
## @brief Cancel incomplete proposal ownership at the end of a managed search.
def optimise(self, *args, **kwargs):
try:
return super().optimise(*args, **kwargs)
finally:
self._clear_requests()
## @brief Keep live identities and worker requests out of saved snapshots.
def __getstate__(self):
state = super().__getstate__()
state.update(_requests={}, _rollouts={}, inds_to_ask=deque(), staging_inds=[])
return state
## @brief Allocate a fixed positive rollout count to each new proposal.
[docs]
@registry.register
class FixedSamplingDecorator(SamplingDecorator):
"""Request ``nb_samples`` observations per proposed genome."""
def __init__(self, base_alg: QDAlgorithm, nb_samples=1, **kwargs):
if not isinstance(nb_samples, int) or nb_samples < 1:
raise ValueError("nb_samples must be a positive integer.")
self.nb_samples = nb_samples
super().__init__(base_alg, **kwargs)
def _target(self, individual):
return self.nb_samples
## @brief Increase the rollout target with the fraction of budget consumed.
[docs]
@registry.register
class TimeBasedSamplingDecorator(SamplingDecorator):
"""Interpolate from ``min_samples`` to ``max_samples`` and round down."""
def __init__(self, base_alg: QDAlgorithm, min_samples=5, max_samples=100, **kwargs):
if not isinstance(min_samples, int) or not isinstance(max_samples, int) or not 1 <= min_samples <= max_samples:
raise ValueError("Use integer sample targets with 1 <= min_samples <= max_samples.")
self.min_samples = min_samples
self.max_samples = max_samples
super().__init__(base_alg, **kwargs)
def _target(self, individual):
return int(self.min_samples + (self.max_samples - self.min_samples)
* min(1., self.nb_evaluations / self.budget))
## @brief Match a promising challenger's sample count and resample losing incumbents.
[docs]
@registry.register
class AdaptiveSamplingDecorator(TimeBasedSamplingDecorator):
"""Perform local sample-count comparisons using the current cell's best entry.
This decorator supplies the basic matching rule. Use
``UncertainMAPElites`` with ``adaptive`` for the drifting-elite race.
"""
def _target(self, individual):
return self.min_samples
def _next_target(self, individual, sample_count):
if not isinstance(self.container, Grid):
return sample_count
try:
cell = self.container.index_grid(individual)
except IndexError:
return sample_count
incumbents = self.container.solutions[cell]
if incumbents:
elite = incumbents[0]
for contender in incumbents[1:]:
if self.container.get_ind_fitness(contender).dominates(self.container.get_ind_fitness(elite)):
elite = contender
observations = len(_history(self.container, elite))
if self.container.get_ind_fitness(individual).dominates(self.container.get_ind_fitness(elite)):
return max(sample_count, min(observations, self.max_samples))
if observations < self.max_samples and not any(r.incumbent is elite for r in self._requests.values()):
self._queue(copy.deepcopy(elite), 1, incumbent=elite)
return sample_count