19"""Sampled measurements and budgeted resampling decorators."""
22__all__ = [
"SampleAveragingStrategy",
"ExplicitSampleAveragingStrategy",
"SampledFitness",
"SampledFeatures",
"SampledIndividual",
"GenSampledIndividuals",
"SamplingDecorator",
"FixedSamplingDecorator",
"TimeBasedSamplingDecorator",
"AdaptiveSamplingDecorator"]
24from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
25from collections
import deque
27from dataclasses
import dataclass, field
44 """Reduce a sequence of observed score vectors to one representative vector."""
45 def sample(self, collection: Sequence[Any]) -> Tuple: ...
48 """Return the coordinate-wise arithmetic mean, or an empty tuple for no samples."""
49 def sample(self, collection: Sequence[Any]) -> Tuple:
50 if len(collection) > 0:
51 return tuple(np.mean(np.array(collection), axis=0))
58 """Keep individual fitness observations and expose their mean as Fitness.
60 Setting values appends a raw observation. Dominance applies comparison
61 weights to the aggregate. Changing weights leaves the observations
62 unchanged. Reset before gathering an independent estimate.
64 sampling_strategy: SampleAveragingStrategy
66 _samples: List[FitnessValuesLike]
71 def __init__(self, sampling_strategy: SampleAveragingStrategy =
ExplicitSampleAveragingStrategy(), values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=
None) ->
None:
75 super().__init__((), weights)
79 """Clear the recorded samples and invalidate the aggregate fitness."""
82 def _compute_values(self) -> None:
85 @Fitness.values.setter
86 def values(self, values: FitnessValuesLike) ->
None:
90 def values(self) -> None:
95 def samples(self) -> Sequence[FitnessValuesLike]:
96 """Return a new list containing the raw objective observations."""
101 """Number of contributing fitness observations."""
105 """Add a nonempty raw objective vector and refresh the aggregate."""
106 sample = tuple(sample)
110 raise ValueError(
"Fitness values and weights must have the same length.")
115 """Append the observations from another sampled fitness and recompute the aggregate."""
116 self.
_samples += [x
for x
in other._samples
if x != ()]
123 """Keep descriptor observations and expose their coordinate-wise aggregate."""
124 sampling_strategy: SampleAveragingStrategy
126 _samples: List[FeaturesValuesLike]
131 super().__init__(*args, **kwargs)
134 def reset(self) -> None:
138 def _compute_values(self) -> None:
146 def values(self) -> FeaturesValuesLike:
152 def values(self, values: FeaturesValuesLike) ->
None:
156 def samples(self) -> List[FeaturesValuesLike]:
157 """Return a new list containing the observed descriptor vectors."""
162 """Number of retained descriptor observations."""
166 """Add a nonempty descriptor observation and refresh the aggregate."""
167 sample = tuple(sample)
173 """Combine recorded descriptor observations with another sampled vector."""
180 """Read old named score mappings and their original sample history.
182 This compatibility class is deprecated for new experiments. As in
183 QDpy 0.1.3, named lookups read the mapping and samples are stored
184 separately. Use a sampling decorator for new repeated evaluations.
186 :param sampling_strategy: Reducer used for the stored sample vectors.
187 :param args: Initial mapping arguments passed to :class:`ScoresDict`.
188 :param kwargs: Initial named measurements.
192 *args, **kwargs) ->
None:
193 warnings.warn(
"SampledScores is deprecated. Use ScoresDict and a sampling decorator for new runs.",
194 DeprecationWarning, stacklevel=2)
197 super().__init__(*args, **kwargs)
200 def _compute_values(self) -> None:
230 """Represent one genome evaluated several times.
232 Fitness and features are independent sample accumulators. The
233 sampling decorator tracks the total expected observations on each
234 proposal before reporting aggregated feedback to the base search.
236 def __init__(self, iterable: Optional[Iterable] =
None,
237 name: Optional[str] =
None,
238 fitness: Optional[FitnessLike] =
None, features: Optional[FeaturesLike] =
None) ->
None:
241 super().__init__(iterable, name, fitness, features)
243 assert(isinstance(fitness, SampledFitness))
244 assert(isinstance(features, SampledFeatures))
249 self.__dict__.pop(
"_observations",
None)
252 """Merge another evaluation's fitness and descriptors and add its elapsed time."""
259 """Count fitness observations. The scheduling interface uses a minimum count of one."""
260 return self.
fitness.nb_samples
or 1
266 """Supply fresh sampled candidates to an ask/tell optimiser."""
274@dataclass(frozen=True)
283def _observe(archive, individual, fitness=None, features=None, scores=None, elapsed=None):
284 named = dict(individual.scores
if scores
is None else scores)
285 fitness_names = archive.fitness_score_names
287 fitness = [named[name]
for name
in fitness_names]
if fitness_names
else individual.fitness.values
288 elif hasattr(fitness,
"values"):
289 fitness = fitness.values
290 features_names = archive.features_score_names
292 features = [named[name]
for name
in features_names]
293 elif features
is None:
294 features = individual.features.values
295 fitness, features = tuple(fitness), tuple(features)
296 for name, value
in zip(fitness_names, fitness):
298 return _Observation(fitness, features, copy.deepcopy(named), elapsed
or 0.)
302def _observe_result(archive, candidate, result, elapsed=0.):
303 if hasattr(result,
"fitness")
and hasattr(result,
"features"):
304 return _observe(archive, result, elapsed=elapsed)
306 return _observe(archive, candidate, elapsed=elapsed)
307 if len(result)
in (2, 3):
308 return _observe(archive, candidate, *result, elapsed=elapsed)
309 raise ValueError(
"Expected an evaluated individual or a tuple of fitness, descriptors and optional scores.")
313def _rollout_seed(seed, stream, index):
314 return int(np.random.SeedSequence([seed, stream, index]).generate_state(1, dtype=np.uint64)[0])
317def _fresh(individual):
318 candidate = copy.deepcopy(individual)
320 for attribute
in (
"_observations",
"evaluation_seed",
"_sampling_owner"):
321 if hasattr(candidate, attribute):
322 delattr(candidate, attribute)
327def _history(archive, individual):
328 if hasattr(individual,
"_observations"):
329 return individual._observations
330 if isinstance(individual, SampledIndividual)
and individual.fitness.nb_samples:
331 fitness = individual.fitness.samples
332 descriptors = individual.features.samples
333 return [
_Observation(row, descriptors[i]
if i < len(descriptors)
else tuple(individual.features),
334 dict(individual.scores))
335 for i, row
in enumerate(fitness)]
336 return [_observe(archive, individual)]
342def _aggregate(archive, individual, observations, estimator=None):
343 fitness_rows = [obs.fitness
for obs
in observations]
344 features_rows = [obs.features
for obs
in observations]
345 fit_reducer = estimator
or getattr(getattr(individual.fitness,
"sampling_strategy",
None),
346 "sample",
None)
or (
lambda rows: np.mean(rows, axis=0))
347 ft_reducer = estimator
or getattr(getattr(individual.features,
"sampling_strategy",
None),
348 "sample",
None)
or (
lambda rows: np.mean(rows, axis=0))
349 fitness = tuple(fit_reducer(fitness_rows))
350 features = tuple(ft_reducer(features_rows))
352 keys = {key:
None for obs
in observations
for key
in obs.scores}
354 values = [obs.scores[key]
for obs
in observations
if key
in obs.scores]
356 array = np.asarray(values)
357 except (TypeError, ValueError):
359 scores[key] = (np.mean(array, axis=0)
if array
is not None and array.dtype.kind
in "buifc"
360 else copy.deepcopy(values[-1]))
361 scores.update(zip(archive.fitness_score_names, fitness))
362 scores.update(zip(archive.features_score_names, features))
363 if isinstance(individual.fitness, SampledFitness):
364 individual.fitness._samples = fitness_rows
365 Fitness.values.fset(individual.fitness, fitness)
367 individual.fitness.values = fitness
368 if isinstance(individual.features, SampledFeatures):
369 individual.features._samples = features_rows
370 individual.features._values = features
372 individual.features.values = features
373 individual.scores = scores
374 individual.elapsed = sum(obs.elapsed
for obs
in observations)
375 individual._observations = observations
380def _valid_observation(observation, objectives, descriptor_count):
381 if len(observation.fitness) != objectives:
382 raise ValueError(
"The rollout returned the wrong number of objectives.")
383 if descriptor_count
is not None and len(observation.features) != descriptor_count:
384 raise ValueError(
"The rollout returned the wrong number of descriptors.")
385 if not all(math.isfinite(value)
for value
in (*observation.fitness, *observation.features)):
386 raise ValueError(
"The rollout returned nonfinite measurements.")
390def _stage_archive(archive):
391 memo = {id(ind): ind
for ind
in archive}
392 memo[id(archive.parents)] = archive.parents
393 staged = copy.deepcopy(archive, memo)
401def _replace_observation(archive, original, revised):
402 if not any(ind
is original
for ind
in archive):
404 staged = _stage_archive(archive)
405 staged._check_if_can_be_added(revised)
406 staged.discard(original)
407 added = staged.add(revised)
is not None
408 if not archive.only_add_accepted_inds_to_parents
or added:
409 archive._add_to_parents(revised,
True)
410 staged.parents = archive.parents
411 archive.__dict__.update(staged.__dict__)
418 individual: IndividualLike
420 incumbent: IndividualLike |
None =
None
423 observations: dict = field(default_factory=dict)
428 """Schedule repeats independently of genome equality or worker completion order.
430 ``budget`` and ``batch_size`` count attempted rollouts. If ``seed`` is
431 supplied, each evaluator input carries a deterministic ``evaluation_seed``.
432 One aggregated feedback event is sent to the base optimiser for each
433 completed offspring. Incumbent reevaluation only updates the archive.
435 :param base_alg: Emitter that generates proposals and receives aggregate feedback.
436 :param seed: Nonnegative seed for rollout IDs, or None to leave seeding to the evaluator.
437 :ivar failed_evaluations: Number of failed or malformed rollout attempts.
440 def __init__(self, base_alg: QDAlgorithm, *, seed=
None, **kwargs):
441 container = kwargs.pop(
"container", base_alg.container)
442 if container
is not base_alg.container:
443 raise ValueError(
"A sampling decorator must use the same container as its base algorithm.")
446 kwargs.setdefault(
"batch_size", base_alg.batch_size)
447 kwargs.setdefault(
"dimension", base_alg.dimension)
448 kwargs.setdefault(
"optimisation_task", base_alg.optimisation_task)
449 kwargs.setdefault(
"name", base_alg.name)
450 kwargs.setdefault(
"budget", base_alg.budget)
451 kwargs.setdefault(
"nb_objectives", base_alg._nb_objectives)
452 generator = kwargs.pop(
"base_ind_gen",
None)
453 if base_alg._base_ind_gen
is None:
456 super().__init__(container=container, **kwargs)
466 for request
in getattr(self,
"_requests", {}).values():
467 if request.incumbent
is None:
479 def dimension(self, dimension):
487 def _queue(self, individual, target, incumbent=None):
501 candidate = _fresh(request.individual)
502 if isinstance(candidate, SampledIndividual):
503 candidate.expected_max_samples = request.target
505 if self.
seed is not None:
507 self.
_rollouts[id(candidate)] = (candidate, key, request.submitted)
508 request.submitted += 1
509 if request.submitted == request.target:
515 pending = self.
_rollouts.pop(id(individual),
None)
516 if pending
is not None:
517 self.
_rollouts[id(evaluated)] = (evaluated, *pending[1:])
522 pending = self.
_rollouts.pop(id(individual),
None)
523 if pending
is not None:
525 self.
_resolve(pending[1], pending[2],
None,
True)
532 def _resolve(self, key, slot, observation, tell_container):
534 request.resolved += 1
535 if observation
is not None:
536 request.observations[slot] = observation
537 if request.resolved < request.target:
539 if len(request.observations) < request.target:
541 if request.incumbent
is None:
545 rows = [request.observations[i]
for i
in sorted(request.observations)]
546 descriptor_width = len(rows[0].features)
547 inconsistent = sum(len(row.features) != descriptor_width
for row
in rows)
550 warnings.warn(
"A sampled candidate returned inconsistent descriptor lengths.", stacklevel=2)
552 if request.incumbent
is None:
555 if request.incumbent
is not None:
556 rows = list(_history(self.
container, request.incumbent)) + rows
557 individual = _aggregate(self.
container, request.individual, rows)
558 if isinstance(individual, SampledIndividual):
559 individual.expected_max_samples = len(rows)
560 if request.incumbent
is None:
562 if target > request.target:
563 request.target = target
567 if request.incumbent
is not None:
568 return tell_container
and _replace_observation(self.
container, request.incumbent, individual)
569 return self.
base_alg.
tell(individual, tell_container=tell_container)
572 def tell(self, individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False,
573 tell_container=True):
574 pending = self.
_rollouts.get(id(individual))
575 if pending
is None and getattr(individual,
"_sampling_owner",
None) == self.
_sampler_id:
576 raise ValueError(
"The rollout has already been resolved or belongs to an ended search.")
577 observation = _observe(self.
container, individual, fitness, features, scores, elapsed)
578 descriptor_count =
None if self.
container.features_domain
is None else len(self.
container.features_domain)
579 _valid_observation(observation, self.
_nb_objectives, descriptor_count)
581 added = self.
base_alg.
tell(individual, fitness, features, scores, elapsed, verbose,
585 added = self.
_resolve(pending[1], pending[2], observation, tell_container)
592 observation = _observe_result(self.
container, individual, result, elapsed)
593 descriptor_count =
None if self.
container.features_domain
is None else len(self.
container.features_domain)
594 _valid_observation(observation, self.
_nb_objectives, descriptor_count)
595 except (KeyError, TypeError, ValueError)
as error:
596 warnings.warn(f
"Invalid sampling result: {error}")
598 pending = self.
_rollouts.pop(id(individual))
599 if hasattr(result,
"fitness")
and hasattr(result,
"features"):
601 added = self.
_resolve(pending[1], pending[2], observation,
True)
608 return super().
optimise(*args, **kwargs)
615 state.update(_requests={}, _rollouts={}, inds_to_ask=deque(), staging_inds=[])
622 """Request ``nb_samples`` observations per proposed genome."""
624 def __init__(self, base_alg: QDAlgorithm, nb_samples=1, **kwargs):
625 if not isinstance(nb_samples, int)
or nb_samples < 1:
626 raise ValueError(
"nb_samples must be a positive integer.")
628 super().__init__(base_alg, **kwargs)
637 """Interpolate from ``min_samples`` to ``max_samples`` and round down."""
639 def __init__(self, base_alg: QDAlgorithm, min_samples=5, max_samples=100, **kwargs):
640 if not isinstance(min_samples, int)
or not isinstance(max_samples, int)
or not 1 <= min_samples <= max_samples:
641 raise ValueError(
"Use integer sample targets with 1 <= min_samples <= max_samples.")
644 super().__init__(base_alg, **kwargs)
654 """Perform local sample-count comparisons using the current cell's best entry.
656 This decorator supplies the basic matching rule. Use
657 ``UncertainMAPElites`` with ``adaptive`` for the drifting-elite race.
667 cell = self.
container.index_grid(individual)
670 incumbents = self.
container.solutions[cell]
672 elite = incumbents[0]
673 for contender
in incumbents[1:]:
674 if self.
container.get_ind_fitness(contender).dominates(self.
container.get_ind_fitness(elite)):
676 observations = len(_history(self.
container, elite))
677 if self.
container.get_ind_fitness(individual).dominates(self.
container.get_ind_fitness(elite)):
678 return max(sample_count, min(observations, self.
max_samples))
679 if observations < self.
max_samples and not any(r.incumbent
is elite
for r
in self.
_requests.values()):
680 self.
_queue(copy.deepcopy(elite), 1, incumbent=elite)
None _tell_after_container_update(self, IndividualLike individual, bool added, Mapping[str, Any] xattr={})
Account for a completed tell and send feedback.
Match a promising challenger's sample count and resample losing incumbents.
_target(self, individual)
Select the initial count for a fresh proposal.
_next_target(self, individual, sample_count)
Allow a policy to increase a completed request's target.
Allocate a fixed positive rollout count to each new proposal.
_target(self, individual)
Select the initial count for a fresh proposal.
None _compute_values(self)
None add_sample(self, sample)
List[FeaturesValuesLike] samples(self)
Sequence[FitnessValuesLike] samples(self)
None add_sample(self, sample)
List _samples
nb_samples: int
None _compute_values(self)
Legacy named score mapping with a separate history of sample vectors.
None merge(self, other)
Append another mapping's sample history.
int nb_samples(self)
Count the stored sample vectors.
samples(self)
Return a copy of the sample history in observation order.
None _compute_values(self)
None clear(self)
Remove the named measurements and recorded samples.
None add_sample(self, sample)
Append a sample and recompute the legacy aggregate.
Wrap an optimiser to aggregate one or more rollouts per proposal.
_resolve(self, key, slot, observation, tell_container)
Collect a rollout and publish measurements only after a complete decision.
tell(self, individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)
Resolve one observation or admit a manually evaluated individual.
_transfer_suggestion(self, individual, evaluated)
Keep the rollout slot when a worker returns a replacement object.
optimise(self, *args, **kwargs)
Cancel incomplete proposal ownership at the end of a managed search.
reinit(self)
Reset counters and discard outstanding work.
_forget_suggestion(self, individual)
Mark a failed rollout resolved.
_next_target(self, individual, sample_count)
Allow a policy to increase a completed request's target.
__getstate__(self)
Keep live identities and worker requests out of saved snapshots.
_queue(self, individual, target, incumbent=None)
Queue a materialized request with an object-independent ID.
_tell_evaluation_result(self, individual, result, elapsed, verbose)
Treat invalid worker measurements as failed rollout slots.
_clear_requests(self)
Release proposal feedback ownership after the search or restart.
_target(self, individual)
Select the initial count for a fresh proposal.
_internal_ask(self, base_ind)
Request the next rollout or start an independent offspring.
Increase the rollout target with the fraction of budget consumed.
_target(self, individual)
Select the initial count for a fresh proposal.
One successful rollout with paired objective, descriptor and named measurements.
Track one pending offspring or incumbent and its requested rollout slots.
:param obj: Slice indicating on which objectives the domination is tested.