QDpy
Loading...
Searching...
No Matches
sampling.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"""Sampled measurements and budgeted resampling decorators."""
20
21
22__all__ = ["SampleAveragingStrategy", "ExplicitSampleAveragingStrategy", "SampledFitness", "SampledFeatures", "SampledIndividual", "GenSampledIndividuals", "SamplingDecorator", "FixedSamplingDecorator", "TimeBasedSamplingDecorator", "AdaptiveSamplingDecorator"]
23
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
26import copy
27from dataclasses import dataclass, field
28import math
29from uuid import uuid4
30import warnings
31
32import numpy as np
33
34from .base import *
35from qdpy.base import *
36from qdpy.phenotype import *
37from qdpy.utils import *
38from qdpy.containers import *
39from qdpy import tools
40
41
42@runtime
44 """Reduce a sequence of observed score vectors to one representative vector."""
45 def sample(self, collection: Sequence[Any]) -> Tuple: ...
46
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))
52 else:
53 return ()
54
55
56
58 """Keep individual fitness observations and expose their mean as Fitness.
59
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.
63 """
64 sampling_strategy: SampleAveragingStrategy
65
66 _samples: List[FitnessValuesLike]
67
68# def __new__(cls, values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=None):
69# return super(Fitness, cls).__new__(cls)
70
71 def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), values: FitnessValuesLike=(), weights: Optional[FitnessValuesLike]=None) -> None:
72 self.sampling_strategy = sampling_strategy
73 self._samples = []
74 self._values = ()
75 super().__init__((), weights)
76 self.add_sample(values)
77
78 def reset(self) -> None:
79 """Clear the recorded samples and invalidate the aggregate fitness."""
80 del self.values
81
82 def _compute_values(self) -> None:
83 Fitness.values.fset(self, self.sampling_strategy.sample(self._samples))
84
85 @Fitness.values.setter
86 def values(self, values: FitnessValuesLike) -> None:
87 self.add_sample(values)
88
89 @values.deleter
90 def values(self) -> None:
91 self._samples = []
92 self._values = ()
93
94 @property
95 def samples(self) -> Sequence[FitnessValuesLike]:
96 """Return a new list containing the raw objective observations."""
97 return list(self._samples)
98
99 @property
100 def nb_samples(self) -> int:
101 """Number of contributing fitness observations."""
102 return len(self._samples)
103
104 def add_sample(self, sample) -> None:
105 """Add a nonempty raw objective vector and refresh the aggregate."""
106 sample = tuple(sample)
107 if not sample:
108 return
109 if len(self.weights) and len(sample) != len(self.weights):
110 raise ValueError("Fitness values and weights must have the same length.")
111 self._samples.append(sample)
112 self._compute_values()
113
114 def merge(self, other) -> None:
115 """Append the observations from another sampled fitness and recompute the aggregate."""
116 self._samples += [x for x in other._samples if x != ()]
117 self._compute_values()
118 #print("DEBUG merge:", self._samples)
119
120
121
123 """Keep descriptor observations and expose their coordinate-wise aggregate."""
124 sampling_strategy: SampleAveragingStrategy
125 #_nb_samples: int
126 _samples: List[FeaturesValuesLike]
127
128 def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), *args, **kwargs) -> None:
129 self.sampling_strategy = sampling_strategy
130 self._samples = []
131 super().__init__(*args, **kwargs)
133
134 def reset(self) -> None:
135 super().reset()
136 self._samples = []
137
138 def _compute_values(self) -> None:
139
141 self._values = tuple(self.sampling_strategy.sample(self._samples))
142 #self._values = np.mean(np.array(self._samples), axis=0)
143
144 # XXX slow
145 @property
146 def values(self) -> FeaturesValuesLike:
147 #self._compute_values()
148 return self._values
149
150 # XXX slow
151 @values.setter
152 def values(self, values: FeaturesValuesLike) -> None:
153 self.add_sample(values)
154
155 @property
156 def samples(self) -> List[FeaturesValuesLike]:
157 """Return a new list containing the observed descriptor vectors."""
158 return list(self._samples)
159
160 @property
161 def nb_samples(self) -> int:
162 """Number of retained descriptor observations."""
163 return len(self._samples)
164
165 def add_sample(self, sample) -> None:
166 """Add a nonempty descriptor observation and refresh the aggregate."""
167 sample = tuple(sample)
168 if sample:
169 self._samples.append(sample)
170 self._compute_values()
171
172 def merge(self, other) -> None:
173 """Combine recorded descriptor observations with another sampled vector."""
174 self._samples += other._samples
175 self._compute_values()
176
177
178
180 """Read old named score mappings and their original sample history.
181
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.
185
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.
189 """
190
191 def __init__(self, sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(),
192 *args, **kwargs) -> None:
193 warnings.warn("SampledScores is deprecated. Use ScoresDict and a sampling decorator for new runs.",
194 DeprecationWarning, stacklevel=2)
195 self.sampling_strategy = sampling_strategy
196 self._samples = []
197 super().__init__(*args, **kwargs)
198 self._compute_values()
199
200 def _compute_values(self) -> None:
201 self._values = tuple(self.sampling_strategy.sample(self._samples))
202
203
204 @property
205 def samples(self):
206 return list(self._samples)
207
208
209 @property
210 def nb_samples(self) -> int:
211 return len(self._samples)
212
213
214 def add_sample(self, sample) -> None:
215 self._samples.append(sample)
216 self._compute_values()
217
218
219 def merge(self, other) -> None:
220 self._samples += other._samples
221 self._compute_values()
222
223
224 def clear(self) -> None:
225 super().clear()
226 self._samples = []
227
228
230 """Represent one genome evaluated several times.
231
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.
235 """
236 def __init__(self, iterable: Optional[Iterable] = None,
237 name: Optional[str] = None,
238 fitness: Optional[FitnessLike] = None, features: Optional[FeaturesLike] = None) -> None:
239 fitness = SampledFitness() if fitness is None else fitness
240 features = SampledFeatures() if features is None else features
241 super().__init__(iterable, name, fitness, features)
242 self.expected_max_samples = 1
243 assert(isinstance(fitness, SampledFitness))
244 assert(isinstance(features, SampledFeatures))
245
246 def reset(self):
247 super().reset()
248 self.expected_max_samples = 1
249 self.__dict__.pop("_observations", None)
250
251 def merge(self, other):
252 """Merge another evaluation's fitness and descriptors and add its elapsed time."""
253 self.fitness.merge(other.fitness)
254 self.features.merge(other.features)
255 self.elapsed += other.elapsed
256
257 @property
258 def nb_samples(self) -> int:
259 """Count fitness observations. The scheduling interface uses a minimum count of one."""
260 return self.fitness.nb_samples or 1 # type: ignore # XXX hack ?
261
262
263
264@registry.register
266 """Supply fresh sampled candidates to an ask/tell optimiser."""
267 def __next__(self):
268 return SampledIndividual()
269
270
271
272
273
274@dataclass(frozen=True)
276 fitness: tuple
277 features: tuple
278 scores: dict
279 elapsed: float = 0.
280
281
282
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
286 if fitness is None:
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
291 if features_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):
297 named[name] = value
298 return _Observation(fitness, features, copy.deepcopy(named), elapsed or 0.)
299
300
301
302def _observe_result(archive, candidate, result, elapsed=0.):
303 if hasattr(result, "fitness") and hasattr(result, "features"):
304 return _observe(archive, result, elapsed=elapsed)
305 if len(result) == 0:
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.")
310
311
312
313def _rollout_seed(seed, stream, index):
314 return int(np.random.SeedSequence([seed, stream, index]).generate_state(1, dtype=np.uint64)[0])
315
316
317def _fresh(individual):
318 candidate = copy.deepcopy(individual)
319 candidate.reset()
320 for attribute in ("_observations", "evaluation_seed", "_sampling_owner"):
321 if hasattr(candidate, attribute):
322 delattr(candidate, attribute)
323 return candidate
324
325
326
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)]
337
338
339
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))
351 scores = {}
352 keys = {key: None for obs in observations for key in obs.scores}
353 for key in keys:
354 values = [obs.scores[key] for obs in observations if key in obs.scores]
355 try:
356 array = np.asarray(values)
357 except (TypeError, ValueError):
358 array = None
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)
366 else:
367 individual.fitness.values = fitness
368 if isinstance(individual.features, SampledFeatures):
369 individual.features._samples = features_rows
370 individual.features._values = features
371 else:
372 individual.features.values = features
373 individual.scores = scores
374 individual.elapsed = sum(obs.elapsed for obs in observations)
375 individual._observations = observations
376 return individual
377
378
379
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.")
387
388
389
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)
394 staged.parents = []
395 return staged
396
397
398
401def _replace_observation(archive, original, revised):
402 if not any(ind is original for ind in archive):
403 return False
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__)
412 return added
413
414
415
416@dataclass
418 individual: IndividualLike
419 target: int
420 incumbent: IndividualLike | None = None
421 submitted: int = 0
422 resolved: int = 0
423 observations: dict = field(default_factory=dict)
424
425
426
428 """Schedule repeats independently of genome equality or worker completion order.
429
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.
434
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.
438 """
439
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.")
444 self.base_alg = base_alg
445 self.seed = seed
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:
454 base_alg._base_ind_gen = GenSampledIndividuals() if generator is None else generator
455 self._sampler_id = uuid4().hex
456 super().__init__(container=container, **kwargs)
457
458
459 def reinit(self):
460 self._clear_requests()
461 self.failed_evaluations = 0
462 super().reinit()
463
464
466 for request in getattr(self, "_requests", {}).values():
467 if request.incumbent is None:
468 self.base_alg._forget_suggestion(request.individual)
469 self._requests = {}
470 self._rollouts = {}
471 self.inds_to_ask = deque()
472 self.staging_inds = []
473
474 @property
475 def dimension(self):
476 return self.base_alg.dimension
477
478 @dimension.setter
479 def dimension(self, dimension):
480 self.base_alg.dimension = dimension
481
482
483 def _target(self, individual):
484 return 1
485
486
487 def _queue(self, individual, target, incumbent=None):
488 request = _SampleRequest(individual, target, incumbent)
489 key = id(request)
490 self._requests[key] = request
491 self.inds_to_ask.append(key)
492 return key
493
494
495 def _internal_ask(self, base_ind):
496 if not self.inds_to_ask:
497 individual = self.base_alg.ask()
498 self._queue(individual, self._target(individual))
499 key = self.inds_to_ask[0]
500 request = self._requests[key]
501 candidate = _fresh(request.individual)
502 if isinstance(candidate, SampledIndividual):
503 candidate.expected_max_samples = request.target
504 candidate._sampling_owner = self._sampler_id
505 if self.seed is not None:
506 candidate.evaluation_seed = _rollout_seed(self.seed, 0, self.nb_suggestions)
507 self._rollouts[id(candidate)] = (candidate, key, request.submitted)
508 request.submitted += 1
509 if request.submitted == request.target:
510 self.inds_to_ask.popleft()
511 return candidate
512
513
514 def _transfer_suggestion(self, individual, evaluated):
515 pending = self._rollouts.pop(id(individual), None)
516 if pending is not None:
517 self._rollouts[id(evaluated)] = (evaluated, *pending[1:])
518 evaluated._sampling_owner = self._sampler_id
519
520
521 def _forget_suggestion(self, individual):
522 pending = self._rollouts.pop(id(individual), None)
523 if pending is not None:
524 self.failed_evaluations += 1
525 self._resolve(pending[1], pending[2], None, True)
526
527
528 def _next_target(self, individual, sample_count):
529 return sample_count
530
531
532 def _resolve(self, key, slot, observation, tell_container):
533 request = self._requests[key]
534 request.resolved += 1
535 if observation is not None:
536 request.observations[slot] = observation
537 if request.resolved < request.target:
538 return False
539 if len(request.observations) < request.target:
540 del self._requests[key]
541 if request.incumbent is None:
542 self.base_alg._forget_suggestion(request.individual)
543 return False
544
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)
548 if inconsistent:
549 self.failed_evaluations += inconsistent
550 warnings.warn("A sampled candidate returned inconsistent descriptor lengths.", stacklevel=2)
551 del self._requests[key]
552 if request.incumbent is None:
553 self.base_alg._forget_suggestion(request.individual)
554 return False
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:
561 target = self._next_target(individual, len(rows))
562 if target > request.target:
563 request.target = target
564 self.inds_to_ask.appendleft(key)
565 return False
566 del self._requests[key]
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)
570
571
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)
580 if pending is None:
581 added = self.base_alg.tell(individual, fitness, features, scores, elapsed, verbose,
582 tell_container)
583 else:
584 self._rollouts.pop(id(individual))
585 added = self._resolve(pending[1], pending[2], observation, tell_container)
586 self._tell_after_container_update(individual, added)
587 return added
588
589
590 def _tell_evaluation_result(self, individual, result, elapsed, verbose):
591 try:
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}")
597 return False
598 pending = self._rollouts.pop(id(individual))
599 if hasattr(result, "fitness") and hasattr(result, "features"):
600 result._sampling_owner = self._sampler_id
601 added = self._resolve(pending[1], pending[2], observation, True)
602 self._tell_after_container_update(individual, added)
603 return True
604
605
606 def optimise(self, *args, **kwargs):
607 try:
608 return super().optimise(*args, **kwargs)
609 finally:
610 self._clear_requests()
611
612
613 def __getstate__(self):
614 state = super().__getstate__()
615 state.update(_requests={}, _rollouts={}, inds_to_ask=deque(), staging_inds=[])
616 return state
617
618
619
620@registry.register
622 """Request ``nb_samples`` observations per proposed genome."""
623
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.")
627 self.nb_samples = nb_samples
628 super().__init__(base_alg, **kwargs)
629
630 def _target(self, individual):
631 return self.nb_samples
632
633
634
635@registry.register
637 """Interpolate from ``min_samples`` to ``max_samples`` and round down."""
638
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.")
642 self.min_samples = min_samples
643 self.max_samples = max_samples
644 super().__init__(base_alg, **kwargs)
645
646 def _target(self, individual):
647 return int(self.min_samples + (self.max_samples - self.min_samples)
648 * min(1., self.nb_evaluations / self.budget))
649
650
651
652@registry.register
654 """Perform local sample-count comparisons using the current cell's best entry.
655
656 This decorator supplies the basic matching rule. Use
657 ``UncertainMAPElites`` with ``adaptive`` for the drifting-elite race.
658 """
659
660 def _target(self, individual):
661 return self.min_samples
662
663 def _next_target(self, individual, sample_count):
664 if not isinstance(self.container, Grid):
665 return sample_count
666 try:
667 cell = self.container.index_grid(individual)
668 except IndexError:
669 return sample_count
670 incumbents = self.container.solutions[cell]
671 if incumbents:
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)):
675 elite = contender
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)
681 return sample_count
IndividualLike ask(self)
Definition base.py:481
None _tell_after_container_update(self, IndividualLike individual, bool added, Mapping[str, Any] xattr={})
Account for a completed tell and send feedback.
Definition base.py:630
Match a promising challenger's sample count and resample losing incumbents.
Definition sampling.py:653
_target(self, individual)
Select the initial count for a fresh proposal.
Definition sampling.py:660
_next_target(self, individual, sample_count)
Allow a policy to increase a completed request's target.
Definition sampling.py:663
Allocate a fixed positive rollout count to each new proposal.
Definition sampling.py:621
_target(self, individual)
Select the initial count for a fresh proposal.
Definition sampling.py:630
List[FeaturesValuesLike] samples(self)
Definition sampling.py:156
Sequence[FitnessValuesLike] samples(self)
Definition sampling.py:95
Legacy named score mapping with a separate history of sample vectors.
Definition sampling.py:179
None merge(self, other)
Append another mapping's sample history.
Definition sampling.py:219
int nb_samples(self)
Count the stored sample vectors.
Definition sampling.py:210
samples(self)
Return a copy of the sample history in observation order.
Definition sampling.py:205
None clear(self)
Remove the named measurements and recorded samples.
Definition sampling.py:224
None add_sample(self, sample)
Append a sample and recompute the legacy aggregate.
Definition sampling.py:214
Wrap an optimiser to aggregate one or more rollouts per proposal.
Definition sampling.py:427
_resolve(self, key, slot, observation, tell_container)
Collect a rollout and publish measurements only after a complete decision.
Definition sampling.py:532
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.
Definition sampling.py:573
_transfer_suggestion(self, individual, evaluated)
Keep the rollout slot when a worker returns a replacement object.
Definition sampling.py:514
optimise(self, *args, **kwargs)
Cancel incomplete proposal ownership at the end of a managed search.
Definition sampling.py:606
reinit(self)
Reset counters and discard outstanding work.
Definition sampling.py:459
_forget_suggestion(self, individual)
Mark a failed rollout resolved.
Definition sampling.py:521
_next_target(self, individual, sample_count)
Allow a policy to increase a completed request's target.
Definition sampling.py:528
__getstate__(self)
Keep live identities and worker requests out of saved snapshots.
Definition sampling.py:613
_queue(self, individual, target, incumbent=None)
Queue a materialized request with an object-independent ID.
Definition sampling.py:487
_tell_evaluation_result(self, individual, result, elapsed, verbose)
Treat invalid worker measurements as failed rollout slots.
Definition sampling.py:590
_clear_requests(self)
Release proposal feedback ownership after the search or restart.
Definition sampling.py:465
_target(self, individual)
Select the initial count for a fresh proposal.
Definition sampling.py:483
_internal_ask(self, base_ind)
Request the next rollout or start an independent offspring.
Definition sampling.py:495
Increase the rollout target with the fraction of budget consumed.
Definition sampling.py:636
_target(self, individual)
Select the initial count for a fresh proposal.
Definition sampling.py:646
One successful rollout with paired objective, descriptor and named measurements.
Definition sampling.py:275
Track one pending offspring or incumbent and its requested rollout slots.
Definition sampling.py:417
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405
ScoreValuesLike values
Definition phenotype.py:249