QDpy
Loading...
Searching...
No Matches
base.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"""All the base classes and protocols describing QD algorithms (optimisers). All of these algorithms perform optimisation on a defined objective functions, and use a provided container to store the evaluated solutions. The base abstract class of algorithms is `QDAlgorithm`, itself implementing the `QDAlgorithmLike` Protocol. Most QD algorithms will subclass QDAlgorithm directly, but in some special cases, algorithms might need to subclass QDAlgorithmLike instead (e.g. sequences `Sq` of QD algorithms).
20
21All algorithms must be registered to the default qdpy.base.Registry `qdpy.base.registry` if they are to be easily accessed or created by factories. It can be done by decorating QD algorithms classes with `@registry.register`. """
22
23__all__ = ["partial", "QDAlgorithmLike", "QDAlgorithm", "Lambda", "AlgWithBatchSuggestions", "Sq", "AlgWrapper", "AlternatingAlgWrapper", "SqAlgWrapper", "FromArchive"]
24
25import abc
26import math
27import time
28from operator import index as integer_index
29from timeit import default_timer as timer
30from inspect import Parameter, signature
31from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
32from typing_extensions import runtime, Protocol
33import warnings
34import numpy as np
35import copy
36import traceback
37import os
38
39
40from qdpy.utils import *
41from qdpy.phenotype import *
42from qdpy.base import *
43from qdpy.containers import *
44from qdpy import tools
45
46import functools
47partial = functools.partial # type: ignore
48
49def _result_size(result: Any) -> Optional[int]:
50 if isinstance(result, (str, bytes, Mapping)):
51 return None
52 try:
53 return len(result)
54 except TypeError:
55 return None
56
57
58def _positional_feedback_sizes(tell):
59 """Keep positional feedback for overrides that already accept it.
60
61 A declared keyword-only measurement takes precedence over ``*args``.
62 Check pairs and triples separately since ``scores`` can be keyword-only
63 even when fitness and features accept either call form.
64 """
65 try:
66 tell_signature = signature(tell)
67 except (TypeError, ValueError):
68 return (2, 3)
69 positional = []
70 for names in (("fitness", "features"), ("fitness", "features", "scores")):
71 try:
72 tell_signature.bind(None, elapsed=None, verbose=False, **dict.fromkeys(names))
73 except TypeError:
74 positional.append(len(names))
75 continue
76 if any(name in tell_signature.parameters and tell_signature.parameters[name].kind is Parameter.KEYWORD_ONLY
77 for name in names):
78 continue
79 try:
80 tell_signature.bind(None, *(None,) * len(names), elapsed=None, verbose=False)
81 except TypeError:
82 continue
83 positional.append(len(names))
84 return tuple(positional)
85
86
87class _InvalidEvaluation(ValueError):
88 """An evaluator payload failed before archive admission or feedback."""
89
90
91def _evaluation_limit(value, name, *, minimum, allow_infinity=False):
92 if allow_infinity and value == math.inf:
93 return math.inf
94 try:
95 count = integer_index(value)
96 except TypeError as error:
97 raise ValueError(f"{name} must be an integer.") from error
98 if count < minimum:
99 raise ValueError(f"{name} must be at least {minimum}.")
100 return count
101
102
106def _evalWrapper(eval_id: int, fn: Callable, *args, **kwargs) -> Tuple[int, float, Any, Any]:
107 """Wrapper around an evaluation function. It catches any exceptions raised by the evaluation function (as exceptions might be lost depending on which kind of parallelism scheme is applied to launch evaluations). It also measures the time elapsed by the evaluation function computation."""
108 start_time = timer()
109 exc = None
110 #fitness = None
111 #features = None
112 res = None
113 try:
114 res = fn(*args, **kwargs)
115 except Exception as e:
116 print(f"Exception during evaluation: {e}")
117 traceback.print_exc()
118 exc = e
119 elapsed = timer() - start_time
120 return eval_id, elapsed, res, exc
121
122
123def _severalEvalsWrapper(eval_id: int, fn: Callable, *args, **kwargs) -> Tuple[int, float, Any, Any]:
124 """Wrapper around several evaluations of an objective function. It catches any exceptions raised by the evaluation function (as exceptions might be lost depending on which kind of parallelism scheme is applied to launch evaluations). It also measures the time elapsed by the evaluation function computation."""
125 start_time = timer()
126 exc = None
127 #fitness = None
128 #features = None
129 res = None
130 try:
131 res = fn(*args, **kwargs)
132 except Exception as e:
133 print(f"Exception during evaluation: {e}")
134 traceback.print_exc()
135 exc = e
136 elapsed = timer() - start_time
137 return eval_id, elapsed, res, exc
138
139
141 """Manager of callback functions that are called when specific events of the `QDAlgorithm` class are triggered.
142 It is possible to register a callback function using the `self.add_callback` method. The callback functions
143 attached to a specific event are retrieved through the `self.get` method.
144
145 We regroup callback function handling in this private class to ease the serialisation of QDAlgorithm and its sub-classes.
146 Namely, the callback functions provided by the user may not be pickleable. To prevent them to be taken into account during serialisation, we declare a __getstate__ method returning the __dict__ dictionary of object attributes, minus the registered callback function objects. This __getstate__ is not inherited by sub-classes, which make it unadapted to be specified directly in the QDAlgorithm class, as it would force all sub-classes of QDAlgorithm to redefine the __getstate__ method to be pickleable."""
147 callbacks: MutableMapping[str, MutableSequence[Callable]]
148
149 def __init__(self):
150 self.callbacks = {}
151 pass
152
153 def __getstate__(self):
154 odict = self.__dict__.copy()
155 del odict['callbacks']
156 return odict
157
158 def get(self, event: str) -> Sequence[Callable]:
159 """Return the Sequence of functions that can be triggered when `event` happens.
160
161 Parameters
162 ----------
163 :param event: str
164 The event triggering the returned callback functions.
165 """
166 return self.callbacks.get(event, [])
167
168 def add_callback(self, event: str, fn: Callable) -> None:
169 """Attach a callable `fn` to this CallbacksManager. `fn` will be called each time the event specified in `event` occurs.
170
171 Parameters
172 ----------
173 :param event: str
174 The event triggering the callback.
175 :param fn: Callable
176 The callback function called when the event specified in `event` occurs.
177 """
178 self.callbacks.setdefault(event, []).append(fn)
179
180
181@runtime
182class QDAlgorithmLike(Protocol):
183 """Interface shared by native optimisers and algorithm sequences.
184
185 Callers may ask for a candidate and tell its result directly, or
186 use optimise to manage evaluation and executor dispatch.
187 """
188 name: str
189 container: Container
190 dimension: Optional[int]
191 budget: int
192
193 def reinit(self) -> None: ...
194
195 def ask(self) -> IndividualLike: ...
196
197 def tell(self, individual: IndividualLike, fitness: Optional[Any] = None,
198 features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None,
199 elapsed: Optional[float] = None, verbose: bool = False) -> bool: ...
200
201 def tell_container_entries(self, cont: Optional[Container] = None) -> None: ...
202
203 def best(self) -> IndividualLike: ...
204
205 def optimise(self, evaluate: Callable, budget: Optional[int] = None,
206 batch_mode: bool = True, executor: Optional[ExecutorLike] = None,
207 send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10,
208 verbose: bool = False) -> IndividualLike: ...
209
210 def add_callback(self, event: str, fn: Callable) -> None: ...
211
212 @property
213 def nb_suggestions(self) -> int: ...
214
215 @property
216 def nb_suggestions_in_iteration(self) -> int: ...
217
218 @property
219 def nb_evaluations(self) -> int: ...
220
221 @property
222 def nb_evaluations_in_iteration(self) -> int: ...
223
224 @property
225 def nb_updated(self) -> int: ...
226
227 @property
228 def nb_updated_in_iteration(self) -> int: ...
229
230 @property
231 def batch_size(self) -> int: ...
232
233 @property
234 def nb_max_iter(self) -> Union[int,float]: ...
235
236 @property
237 def current_iter(self) -> int: ...
238
239
240
241
242
243# Inspiration from the nevergrad library
245 """Combine a candidate generator, an evaluation budget, and an archive.
246
247 The container resolves objective and descriptor vectors and controls
248 admission. The optimiser generates genomes and consumes feedback.
249 Ask and tell support an application-managed evaluator. Optimise adds
250 scheduling, timing, and callbacks to the same protocol.
251
252 :param container: Archive used for admission and best-candidate queries.
253 :param budget: Candidate evaluations available to each managed run.
254 :param batch_size: Candidates in one iteration and maximum number
255 pending at once. Defaults to the budget.
256 :param dimension: Genome length for algorithms that generate vectors.
257 :param nb_objectives: Objective count. When omitted, infer it from
258 the container's fitness domain or use one objective.
259 :param optimisation_task: Minimise, maximise, or supply one finite
260 comparison weight per objective.
261 :param base_ind_gen: Iterator supplying a fresh candidate for each ask.
262 :param tell_container_at_init: Feed stored entries to the algorithm
263 when true or ``"yes"``. Use ``"parents"`` to feed entries from
264 immediate parents and pass their child membership to the hook.
265 :param add_default_logger: Attach the shared console logger.
266 :param name: Name for callbacks, logs, and saved result metadata.
267 """
268
269 #ind_domain: Optional[DomainLike]
270 #executor: Optional[ExecutorLike]
271
272 name: str
273 container: Container
274 dimension: Optional[int]
275 budget: int
276 _base_ind_gen: Optional[Generator[IndividualLike, None, None]]
277 _nb_objectives: int
278 _optimisation_task: Union[str, Sequence[float]]
279 #_elapsed: float = 0.
280 _fitness_weights: Sequence
281 _nb_suggestions: int
282 _nb_suggestions_in_iteration: int
283 _nb_evaluations: int
284 _nb_evaluations_in_iteration: int
285 _nb_updated: int
286 _nb_updated_in_iteration: int
287 _batch_size: Optional[int]
288 _callbacks: _CallbacksManager
289
290
291 _fixed_batch_feedback = False
292 _lineage_recorder = None
293
294 def __init__(self, container: Container, budget: int, batch_size: Optional[int] = None,
295 dimension: Optional[int] = None, nb_objectives: Optional[int] = None,
296 optimisation_task: Union[str, Sequence[float]] = "minimisation",
297 base_ind_gen: Optional[Generator[IndividualLike, None, None]] = None,
298 tell_container_at_init: Union[bool, str] = False, # XXX
299 add_default_logger: bool = False, name: Optional[str] = None,
300 **kwargs):
301 self.container = container
302 self.dimension = dimension
303 self.budget = None if budget is None else _evaluation_limit(budget, "budget", minimum=0, allow_infinity=True)
304 self._batch_size = (None if batch_size is None else
305 _evaluation_limit(batch_size, "batch_size", minimum=1, allow_infinity=True))
306 self._base_ind_gen = base_ind_gen
307 self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
308
309 if nb_objectives is not None:
310 self._nb_objectives = nb_objectives
311 else:
312 if self.container.fitness_domain is None or len(self.container.fitness_domain) == 0:
313 #raise ValueError("You must either specify `nb_objectives` or providing as `container` a Container with a declared fitness domain.")
314 warnings.warn(f"Unspecified number of objectives ! When creating a QDAlgorithm class, you must either specify `nb_objectives` or providing as `container` a Container with a declared fitness domain. Defaulting to only 1 objective.")
315 self._nb_objectives = 1
316 else:
317 self._nb_objectives = len(self.container.fitness_domain)
318
319 self.reinit()
321 self.optimisation_task = optimisation_task
322 if add_default_logger:
323 from .logging import default_algorithm_logger
324 default_algorithm_logger.monitor(self)
325
326 # If needed, tell container entries
327 tell_container_parents: bool = False
328 tell_container: bool = False
329 if isinstance(tell_container_at_init, bool):
330 tell_container = tell_container_at_init
331 else:
332 if tell_container_at_init.lower() == "yes":
333 tell_container = True
334 elif tell_container_at_init.lower() == "parents":
335 tell_container_parents = True
336 if tell_container_parents:
337 if not self.container.parents:
338 raise ValueError("`tell_container_parents` can only be set to 'parents' if `container` possesses at least one parent.")
339 for p in self.container.parents:
340 for e in p:
341 is_in_container = e in self.container
342 self._internal_tell(e, is_in_container)
343 elif tell_container:
344 for e in self.container:
345 self._internal_tell(e, True)
346
347
348 def reinit(self) -> None:
349 """Reset counters for suggestions, evaluation, and archive updates.
350
351 This base method leaves the archive and callbacks in place.
352 Subclasses may also reset their generator or optimiser state.
353 """
354 self._nb_suggestions = 0
356 self._nb_evaluations = 0
358 self._nb_updated = 0
360
361
362 def __getstate__(self):
363 odict = self.__dict__.copy()
364 del odict['_base_ind_gen']
365 odict.pop('_lineage_recorder', None)
366 return odict
367
368 # Do not copy the container when deep copying
369 def __deepcopy__(self, memo):
370 cls = self.__class__
371 result = cls.__new__(cls)
372 memo[id(self)] = result
373 for k, v in self.__dict__.items():
374 if k == "_lineage_recorder":
375 continue
376 if k == "container":
377 setattr(result, k, v)
378 else:
379 setattr(result, k, copy.deepcopy(v, memo))
380 return result
381
382
383 @property
384 def optimisation_task(self) -> Union[str, Sequence[float]]:
385 """The objective direction or explicit comparison weights."""
386 return self._optimisation_task
387
388 # TODO init fitness_weights of container, instead of algorithm
389 @optimisation_task.setter
390 def optimisation_task(self, optimisation_task: Union[str, Sequence[float]]) -> None:
391 """Update the kind of optimisation task performed by this `QDAlgorithm`.
392
393 Parameters
394 ----------
395 :param optimisation_task: Union[str, Sequence[float]]
396 The kind of optimisation task to perform for all objectives of the fitness functions.
397 If `optimisation_task` is a string, it can take the following values:
398 - for minimising all fitness objectives: 'minimisation', 'minimization', 'minimise', 'minimize', 'min'
399 - for maximising all fitness objectives: 'maximisation', 'maximization', 'maximise', 'maximize', 'max'
400 If `optimisation_task` is a Sequence of floats, its length corresponds to the number of objectives, and each
401 entry is a weight to apply to each objective score.
402 Maximised objectives have a corresponding weight > 0 while minimised objectives have weights < 0.
403 The length of this Sequence must be same as the length of the `self.container.fitness_domain` attribute.
404 """
405 if isinstance(optimisation_task, str) and \
406 any((optimisation_task == a for a in ["minimisation", "minimization", "minimise", "minimize", "min"])):
407 task = "minimisation"
408 weights = (-1.,) * self._nb_objectives
409 elif isinstance(optimisation_task, str) and \
410 any((optimisation_task == a for a in ["maximisation", "maximization", "maximise", "maximize", "max"])):
411 task = "maximisation"
412 weights = (1.,) * self._nb_objectives
413 elif isinstance(optimisation_task, Sequence) and not isinstance(optimisation_task, str):
414 if len(optimisation_task) != self._nb_objectives or not all(map(math.isfinite, optimisation_task)):
415 raise ValueError("Supply one finite weight per objective.")
416 task = weights = tuple(optimisation_task)
417 else:
418 raise ValueError("`optimisation_task` must be either a tuple of fitness weights, or a string equals to either 'minimisation' or 'maximisation'.")
419 set_weights = getattr(self.container, "_set_fitness_weights", None)
420 if set_weights is None:
421 self.container.fitness_weights = weights
422 else:
423 set_weights(weights)
424 self._optimisation_task = task
425 self._fitness_weights = weights
426
428 """Catch conflicting objective directions before proposing or admitting candidates."""
429 weights = self.container.fitness_weights
430 if weights is None or tuple(weights) != self._fitness_weights:
431 raise ValueError("Archive fitness weights conflict with this optimiser. "
432 "Use the same optimisation_task for optimisers sharing an archive.")
433
434
435 @property
436 def nb_suggestions(self) -> int:
437 """Number of candidates returned by ask since initialisation or reinitialisation."""
438 return self._nb_suggestions
439
440 @property
442 """Number of asks recorded since the last managed iteration ended."""
444
445 @property
446 def nb_evaluations(self) -> int:
447 """Number of tell calls or candidate slots consumed by the managed scheduler."""
448 return self._nb_evaluations
449
450 @property
452 """Number of accounted evaluations since the last iteration ended."""
454
455 @property
456 def nb_updated(self) -> int:
457 """Number of evaluations for which the archive reported a local update."""
458 return self._nb_updated
459
460 @property
461 def nb_updated_in_iteration(self) -> int:
462 """Number of reported archive updates since the last iteration ended."""
463 return self._nb_updated_in_iteration
464
465 @property
466 def batch_size(self) -> int:
467 """Configured candidate count per iteration, or the current budget when omitted."""
468 return self._batch_size if self._batch_size is not None else self.budget
469
470 @property
471 def nb_max_iter(self) -> Union[int,float]:
472 """Ceiling of the current budget divided by the batch size for a finite run."""
473 return math.ceil(self.budget / self.batch_size) if not math.isinf(self.budget) else math.inf
474
475 @property
476 def current_iter(self) -> int:
477 """Number of full batches accounted for by the evaluation counter."""
478 return math.floor(self._nb_evaluations / self.batch_size)
479
480
481 def ask(self) -> IndividualLike:
482 """Return the next candidate for evaluation.
483
484 Create the base individual, let the subclass propose its genome,
485 assign a name if empty, increment the suggestion counters, and
486 invoke ask callbacks. Keep the suggested object available when
487 sending feedback to a wrapper with multiple emitters.
488 """
490 # Create base individual
491 if self._base_ind_gen is None:
492 base_ind: IndividualLike = Individual()
493 else:
494 base_ind = next(self._base_ind_gen)
495 recorder = self._lineage_recorder
496 if recorder is not None:
497 recorder._parentage("initialise", ())
498 # Call _internal_ask
499 suggestion = self._internal_ask(base_ind)
500 # Update individual name and fitness weights
501 if suggestion.name == "":
502 suggestion.name = f"{int(round(time.time() * 1000))}-{self._nb_suggestions}"
503 #suggestion.fitness.weights = self._fitness_weights # XXX
504 self._nb_suggestions += 1
506 if recorder is not None:
507 recorder._proposed(suggestion, self._nb_suggestions)
508 # Call callback functions
509 for fn in self._callbacks.get("ask"):
510 fn(self, suggestion)
511 return suggestion
512
513
514 @abc.abstractmethod
515 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
516 """Internal ask method. To be implemented by subclasses.
517
518 Parameters
519 ----------
520 :param base_ind: IndividualLike
521 The base (empty) individual object. The `_internal_ask` method must change
522 this object, by filling out the genome and providing other information.
523
524 Returns
525 -------
526 out: IndividualLike
527 The suggested individual.
528 """
529 raise NotImplementedError("Method `_internal_ask` must be implemented by QDAlgorithm subclasses.")
530
531
532 def tell(self, individual: IndividualLike, fitness: Optional[Any] = None,
533 features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None,
534 elapsed: Optional[float] = None, verbose: bool = False, tell_container = True) -> bool:
535 """Report an evaluated candidate and offer it to the container.
536
537 A call updates the candidate's supplied evaluation attributes. The
538 container applies comparison weights to raw objective values. The
539 algorithm's pre-admission hook may add feedback metadata or decline
540 insertion. Feedback and evaluation counters still run when archive
541 insertion is disabled.
542
543 :param individual: Candidate associated with this evaluation.
544 :param fitness: Objective values or a fitness object. If omitted,
545 use the candidate's existing or named fitness.
546 :param features: Descriptor values or a descriptor object.
547 :param scores: Named scores to store on the candidate first.
548 :param elapsed: Evaluation duration in seconds.
549 :param verbose: Report archive validation warnings.
550 :param tell_container: Permit an archive update.
551 :returns: Whether the container reported a local update.
552 :raises ValueError: If the objective count differs from the configured count.
553 """
554 ind = individual
555 self._attach_evaluation(ind, fitness, features, scores, elapsed)
556 xattr, allowed_to_tell = self._tell_before_container_update(ind)
557 added = tell_container and allowed_to_tell and self._offer_to_container(ind, verbose)
558 self._tell_after_container_update(ind, added, xattr)
559 return added
560
561 def _offer_to_container(self, individual, verbose):
562 before = self.container.nb_added
563 self.container.update([individual], issue_warning=verbose)
564 return self.container.nb_added > before
565
566
567 def _attach_evaluation(self, ind, fitness, features, scores, elapsed) -> None:
568 """Apply the native evaluator payload without admitting the candidate."""
570 try:
571 self._apply_evaluation(ind, fitness, features, scores, elapsed)
572 except (AttributeError, IndexError, KeyError, TypeError, ValueError, OverflowError) as error:
573 raise _InvalidEvaluation(str(error)) from error
574
575 def _apply_evaluation(self, ind, fitness, features, scores, elapsed) -> None:
576 if scores is not None:
577 ind.scores = scores
578 ind_fit = self.container.get_ind_fitness(ind)
579 if fitness is not None:
580 fitness_type = type(fitness)
581 if fitness_type is Fitness or (
582 fitness_type is not tuple and fitness_type is not list and isinstance(fitness, FitnessLike)
583 ):
584 ind_fit = copy.copy(fitness)
585 else:
586 ind_fit.values = fitness
587 if len(ind_fit.values) != self._nb_objectives:
588 #if len(ind.fitness.values) != self._nb_objectives:
589 #print(f"DEBUG: scores: {ind.scores} ind_fit: {self.container.get_ind_fitness(ind)} individual.scores: {individual.scores} individual.fitness: {individual.fitness} fitness: {fitness}(type: {type(fitness)}) ind_fit: {ind_fit}")
590 raise ValueError(f"`individual` must possess a `fitness` attribute of dimension {self._nb_objectives} (specified through parameter `nb_objectives` when creating a QDAlgorithm sub-class), instead of {len(ind_fit.values)}.")
591 if fitness is not None:
592 self.container.set_ind_fitness(ind, ind_fit)
593 if features is not None:
594 features_type = type(features)
595 if features_type is Features or (
596 features_type is not tuple and features_type is not list and isinstance(features, FeaturesLike)
597 ):
598 ind.features = features
599 else:
600 ind.features.values = features
601 if elapsed is not None:
602 ind.elapsed = elapsed
603
604
605
610 def _tell_before_container_update(self, individual: IndividualLike) -> Tuple[MutableMapping[str, Any], bool]:
611 """Called by the ``tell`` method before adding the individual to the container. Can be used to compile
612 a dictionary of information about the individual or container before the update operation occurs.
613 Return a dictionary of extended attributes and a boolean flag indicating whether the algorithm is allowed to tell the
614 individual or not.
615
616 Parameters
617 ----------
618 :param individual: IndividualLike
619 The `individual` provided to the algorithm.
620 """
621 return {}, True
622
623
624
630 def _tell_after_container_update(self, individual: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None:
631 if added:
632 self._nb_updated += 1
634 self._internal_tell(individual, added, xattr)
636 if self._lineage_recorder is not None:
637 self._lineage_recorder._result(individual, "accepted" if added else "rejected", self.nb_evaluations)
638 # Call callback functions
639 for fn in self._callbacks.get("tell"):
640 fn(self, individual, added, xattr)
641
642 def _account_evaluations(self, count=1):
643 self._nb_evaluations += count
644 self._nb_evaluations_in_iteration += count
645
646
647 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
648 """Internal tell method. To be overridden by subclasses, or left empty.
649
650 Parameters
651 ----------
652 :param individual: IndividualLike
653 The `individual` provided to the algorithm.
654 :param added_to_container: bool
655 True if `individual` was successfully added to the container.
656 """
657 pass
658
659
660 def tell_container_entries(self, cont: Optional[Container] = None) -> None:
661 """Send stored entries to the optimiser's internal feedback hook.
662
663 :param cont: Source of the warm-start entries. Defaults to the
664 optimiser's own archive.
665
666 Entries are marked as accepted for the hook. Archive admission,
667 evaluation counters, and tell callbacks are bypassed.
668 """
669 if cont is None:
670 cont = self.container
671 for ind in cont:
672 self._internal_tell(ind, True)
673
674
675 def best(self) -> IndividualLike:
676 """Return the best retained candidate.
677
678 :raises RuntimeError: If the container has no candidates.
679 """
681 if len(self.container) == 0:
682 raise RuntimeError("`self.container` contains no individual !")
683 return self._internal_best()
684
685
686 def _internal_best(self) -> IndividualLike:
687 """Return the individual with the best quality. To be overridden by subclasses.
688 By default, returns the best individual of `self.container`."""
689 return self.container.best # Assume `self.container` is not empty
690
691
692
693 def _verify_if_finished_iteration(self, batch_start_time: float) -> bool:
694 """Emit the iteration event at an exact evaluation boundary.
695
696 Callbacks can read the just-finished iteration counters. Reset those
697 counters only after callbacks have run. Partial final batches leave
698 their counters available in the result.
699 """
700 # Verify if we finished an iteration
701 if self.batch_size <= 0 or self._nb_evaluations % self.batch_size != 0:
702 return False
703 batch_elapsed: float = timer() - batch_start_time
704 # Call callback functions
705 for fn in self._callbacks.get("iteration"):
706 fn(self, batch_elapsed)
710 return True
711
712
713 def _tell_evaluation_result(self, individual: IndividualLike, result: Any,
714 elapsed: float, verbose: bool, *, positional_sizes=()) -> bool:
715 result_type = type(result)
716 if result_type is tuple or result_type is list:
717 size = len(result)
718 if size not in (0, 2, 3):
719 warnings.warn("Evaluation function returned malformatted results.")
720 return False
721 evaluated, measurements = individual, result
722 elif result_type is Individual or isinstance(result, IndividualLike):
723 if result is not individual:
724 self._transfer_suggestion(individual, result)
725 evaluated, measurements, size = result, (), 0
726 else:
727 evaluated = individual
728 size = _result_size(result)
729 if size not in (0, 2, 3):
730 warnings.warn("Evaluation function returned malformatted results.")
731 return False
732 try:
733 measurements = tuple(result[i] for i in range(size))
734 except (IndexError, KeyError, TypeError, ValueError) as error:
735 warnings.warn(f"Evaluation function returned malformatted results: {error}")
736 return False
737 try:
738 if size in positional_sizes:
739 self.tell(evaluated, *measurements, elapsed=elapsed, verbose=verbose)
740 elif size == 2:
741 self.tell(evaluated, fitness=measurements[0], features=measurements[1],
742 elapsed=elapsed, verbose=verbose)
743 elif size == 3:
744 self.tell(evaluated, fitness=measurements[0], features=measurements[1], scores=measurements[2],
745 elapsed=elapsed, verbose=verbose)
746 else:
747 self.tell(evaluated, elapsed=elapsed, verbose=verbose)
748 except _InvalidEvaluation as error:
749 if evaluated is not individual:
750 self._forget_suggestion(evaluated)
751 warnings.warn(f"Evaluation function returned malformatted results: {error}")
752 return False
753 return True
754
755 def _forget_suggestion(self, individual: IndividualLike) -> None:
756 if self._lineage_recorder is not None:
757 self._lineage_recorder._result(individual, "failed", self.nb_evaluations + 1)
758
759
760 def _transfer_suggestion(self, individual: IndividualLike, evaluated: IndividualLike) -> None:
761 if self._lineage_recorder is not None:
762 self._lineage_recorder._transfer(individual, evaluated)
763
764 def _start_fixed_batch(self, size: int) -> None:
765 """Prepare a generation for an optimiser that opts into batch feedback."""
766 raise NotImplementedError
767
768 def _receive_fixed_batch(self, records, verbose, batch_start_time) -> None:
769 """Commit a generation in proposal order for an opted-in optimiser."""
770 raise NotImplementedError
771
772 def _fixed_batch_plan(self, size, evaluate, packed):
773 """Select the size and evaluator for the next fixed phase."""
774 return size, evaluate, packed
775
776 def optimise(self, evaluate: Callable, budget: Optional[int] = None,
777 batch_mode: bool = True, executor: Optional[ExecutorLike] = None,
778 send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10,
779 verbose: bool = False) -> IndividualLike:
780 """Manage evaluation and return the best candidate in the archive.
781
782 A single-candidate evaluator can return a fitness and descriptor
783 pair, that pair followed by named scores, or an evaluated individual.
784 Return an empty sequence after updating the supplied object in place
785 during in-process execution. A packed evaluator receives a list and
786 returns one such result per candidate in the same order.
787
788 Both the budget and batch size count candidates. A failed evaluation or
789 malformed group consumes its dispatched slots. Results are consumed in
790 completion order, which can affect archive-dependent searches.
791 Iteration callbacks run after full batches.
792
793 :param evaluate: Callable executed for each candidate or packed group.
794 :param budget: Optional override of the configured budget.
795 :param batch_mode: Wait for the current batch before asking for the
796 next one. In steady state, refill available slots as work completes.
797 :param executor: Evaluation executor. Defaults to in-process sequential
798 execution. The caller manages any supplied executor's lifetime.
799 :param send_several_suggestions_to_fn: Pass a list per evaluator call.
800 :param max_nb_suggestions_per_call: Positive cap on a packed call.
801 :param verbose: Emit archive validation warnings.
802 :returns: The best retained candidate after the run.
803 :raises RuntimeError: If no candidate is available to return.
804 :raises ValueError: If the budget is missing or a positive run has an
805 invalid batch size or packed-call limit.
806 """
807 if self._fixed_batch_feedback and not batch_mode:
808 raise ValueError("This optimiser requires batch_mode=True.")
809 optimisation_start_time: float = timer()
810 # Init budget
812 limit = self.budget if budget is None else budget
813 if limit is None:
814 raise ValueError("`budget` must be provided.")
815 self.budget = _evaluation_limit(limit, "budget", minimum=0, allow_infinity=True)
816 if self.budget:
817 _evaluation_limit(self.batch_size, "batch_size", minimum=1)
818 group_limit = 1
819 if send_several_suggestions_to_fn:
820 group_limit = _evaluation_limit(max_nb_suggestions_per_call, "max_nb_suggestions_per_call", minimum=1)
821
822 _executor: ExecutorLike = executor if executor is not None else SequentialExecutor()
823
824 # Call callback functions
825 for fn in self._callbacks.get("started_optimisation"):
826 fn(self)
827
828 receive_feedback = self._tell_evaluation_result
829 if (getattr(receive_feedback, "__func__", None) is QDAlgorithm._tell_evaluation_result
830 and getattr(self.tell, "__func__", None) not in (QDAlgorithm.tell, AlgWrapper.tell)):
831 positional_sizes = _positional_feedback_sizes(self.tell)
832 if positional_sizes:
833 receive_feedback = partial(receive_feedback, positional_sizes=positional_sizes)
834
835 def optimisation_loop(budget_fn: Callable, evaluator=evaluate, packed=send_several_suggestions_to_fn):
836 batch_start_time: float = timer()
837 futures: MutableMapping[int, FutureLike] = {}
838 individuals: MutableMapping[int, Sequence[IndividualLike]] = {}
839 completed_groups = {} if self._fixed_batch_feedback else None
840 submitted_evals = 0
841 pending_evals = 0
842 next_eval_id = 0
843 while True:
844 available = min(budget_fn() - submitted_evals, self.batch_size - pending_evals)
845 while available > 0:
846 group_size = min(group_limit if packed else 1, available)
847 inds = [self.ask() for _ in range(group_size)]
848 individuals[next_eval_id] = tuple(inds)
849 if packed:
850 future = _executor.submit(_severalEvalsWrapper, next_eval_id, evaluator, inds)
851 else:
852 future = _executor.submit(_evalWrapper, next_eval_id, evaluator, inds[0])
853 futures[next_eval_id] = future
854 next_eval_id += 1
855 pending_evals += group_size
856 submitted_evals += group_size
857 available -= group_size
858
859 if not futures:
860 break
861 future = next(iter(futures.values()))
862 if type(future) is not SequentialFuture:
863 future = generic_as_completed(list(futures.values()))
864 eval_id, elapsed, result, error = future.result()
865 inds = individuals.pop(eval_id)
866 del futures[eval_id]
867 pending_evals -= len(inds)
868
869 if error is not None:
870 warnings.warn(f"Individual evaluation raised the following exception: {error} !")
871 results = None
872 elif not packed:
873 results = (result,)
874 elif type(result) is list or type(result) is tuple:
875 results = tuple(result)
876 if len(results) != len(inds):
877 warnings.warn("Packed evaluation must return one result per candidate.")
878 results = None
879 elif _result_size(result) == len(inds):
880 try:
881 results = tuple(result[i] for i in range(len(inds)))
882 except (IndexError, KeyError, TypeError, ValueError) as error:
883 warnings.warn(f"Packed evaluation must return one result per candidate: {error}")
884 results = None
885 else:
886 warnings.warn("Packed evaluation must return one result per candidate.")
887 results = None
888
889 if completed_groups is not None:
890 completed_groups[eval_id] = [
891 (individual, None if results is None else results[index], elapsed)
892 for index, individual in enumerate(inds)
893 ]
894 continue
895
896 for index, individual in enumerate(inds):
897 if results is None or not receive_feedback(individual, results[index], elapsed, verbose):
898 self._forget_suggestion(individual)
900 if self._verify_if_finished_iteration(batch_start_time):
901 batch_start_time = timer()
902
903 if completed_groups is not None:
904 records = [record for group in sorted(completed_groups) for record in completed_groups[group]]
905 self._receive_fixed_batch(records, verbose, batch_start_time)
906
907 if batch_mode:
908 completed_evals = 0
909 while completed_evals < self.budget:
910 budget_iteration = min(self.budget - completed_evals, self.batch_size)
911 if self._fixed_batch_feedback:
912 budget_iteration, evaluator, packed = self._fixed_batch_plan(
913 budget_iteration, evaluate, send_several_suggestions_to_fn,
914 )
915 self._start_fixed_batch(budget_iteration)
916 optimisation_loop(lambda: budget_iteration, evaluator, packed)
917 else:
918 optimisation_loop(lambda: budget_iteration)
919 completed_evals += budget_iteration
920
921 else:
922 def ret_budget():
923 return self.budget
924 optimisation_loop(ret_budget)
925
926 # Call callback functions
927 optimisation_elapsed: float = timer() - optimisation_start_time
928 for fn in self._callbacks.get("finished_optimisation"):
929 fn(self, optimisation_elapsed)
930
931 return self.best()
932
933
934 def add_callback(self, event: str, fn: Callable) -> None:
935 """Attach a callable `fn` to the optimiser. `fn` will be called each time the event specified in `event` occurs.
936
937 Parameters
938 ----------
939 :param event: str
940 The event triggering the callback. Can be either 'ask', 'tell', 'iteration' (when an iteration finishes)
941 'started_optimisation', or 'finished_optimisation'.
942 :param fn: Callable
943 The callback function called when the event specified in `event` occurs.
944 """
945 _lst_events: Sequence[str] = ['ask', 'tell', 'iteration', 'started_optimisation', 'finished_optimisation']
946 if not event in _lst_events:
947 raise ValueError(f"`event` can be either {','.join(_lst_events)}.")
948 #self._callbacks.setdefault(event, []).append(fn)
949 self._callbacks.add_callback(event, fn)
950
951
952
953@registry.register
955 """Build an algorithm from user-supplied ask and optional tell functions.
956
957 The ask function can return a genome or accept and return a base individual.
958 A tell function receives the evaluated individual and the container's
959 update flag.
960 """
961 _ask_fn: Union[Callable[[], IndividualLike], Callable[[IndividualLike], IndividualLike]]
962 _tell_fn: Optional[Callable]
963
964 def __getstate__(self):
965 odict = super().__getstate__()
966 del odict['_ask_fn']
967 del odict['_tell_fn']
968 return odict
969
970 def __init__(self, container: Container, budget: int,
971 ask: Union[Callable[[], IndividualLike], Callable[[IndividualLike], IndividualLike]],
972 tell: Optional[Callable] = None, **kwargs):
973 super().__init__(container, budget, **kwargs)
974 self._ask_fn = ask
975 self._tell_fn = tell
976
977 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
978 """Internal ask method. Call the function specified by the `ask` argument of the constructor.
979 This function can either take no argument (and must return a Sequence corresponding to the genome)
980 or take a base (empty) `qdpy.base.IndividualLike` as sole argument
981 (and must return a `qdpy.base.IndividualLike` with a filled out genome)."""
982 sig = signature(self._ask_fn)
983 if len(sig.parameters) == 0:
984 base_ind[:] = self._ask_fn() # type: ignore
985 return base_ind
986 else:
987 return self._ask_fn(base_ind) # type: ignore
988
989 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
990 if self._tell_fn is not None:
991 self._tell_fn(individual, added_to_container)
992
993
994
995
997 """Buffer candidates prepared in groups and return them one at a time.
998
999 Subclasses fill the buffer in the batch-generation hook. This batch is
1000 an algorithm's suggestion buffer. The scheduler's batch size separately
1001 limits in-flight candidate evaluations.
1002 """
1003
1004 _batch_inds: List[IndividualLike]
1005
1006 def __init__(self, container: Container, budget: int, **kwargs):
1007 super().__init__(container, budget, **kwargs)
1008 self._batch_inds = []
1009
1010 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
1011 if len(self._batch_inds) == 0:
1013 #assert len(self._batch_inds) == self._batch_size, f"`self._generate_batch_suggestions` must populate `self._batch_inds` with `self.batch_size` IndividualLike objects."
1014 base_ind[:] = self._batch_inds.pop()
1015 return base_ind
1016
1017 @abc.abstractmethod
1019 """Compute all suggestions for the current batch and store them in `self._batch_inds`."""
1020 raise NotImplementedError("Method `_generate_batch_suggestions` must be implemented by AlgWithBatchSuggestions subclasses.")
1021
1022
1023
1024#class EmitterManager(QDAlgorithmLike, Summarisable, Saveable, Copyable, CreatableFromConfig):
1026 """Coordinate child optimisers under one ask/tell interface.
1027
1028 The active child supplies each ask. Feedback follows the original
1029 proposer even if the active child changes before a result returns.
1030 With ``tell_all``, every child receives feedback and non-proposers
1031 receive copies. Child switching can warm-start the next child from
1032 its archive or the previous child's best candidate.
1033
1034 An explicit container collects all reported candidates and supplies the
1035 result. Otherwise report the active child's archive, or the first
1036 populated child when the active archive is empty.
1037 """
1038 algorithms: Sequence[QDAlgorithm]
1039 current_idx: int = 0
1040 current: QDAlgorithm
1041 tell_container_when_switching: Union[bool, str]
1042 batch_mode: bool
1043 tell_all: bool
1044
1045 def __init__(self, algorithms: Any, container: Optional[Container] = None, budget: Optional[int] = None,
1046 tell_container_when_switching: Union[bool, str] = False,
1047 name: Optional[str] = None, batch_mode: bool = False,
1048 tell_all: bool = False, **kwargs):
1049 if len(algorithms) == 0:
1050 raise ValueError("`algorithms` must not be empty.")
1051# if isinstance(algorithms, Mapping):
1052# self.algorithms = []
1053# for k,v in algorithms.items():
1054# for i in range(v):
1055# self.algorithms.append(k)
1056# else:
1057# self.algorithms = list(algorithms)
1058 self.algorithms = list(algorithms)
1059 self.current_idx = 0
1060 self.current = self.algorithms[self.current_idx]
1061 self.batch_mode = batch_mode
1062 self.tell_all = tell_all
1063
1064 explicit_container = container is not None
1065 container = self.current.container if container is None else container
1066 budget_: int = sum((algo.budget for algo in self.algorithms)) if budget is None else budget
1067 kwargs.setdefault("optimisation_task", self.current.optimisation_task)
1068 kwargs.setdefault("nb_objectives", self.current._nb_objectives)
1069 super().__init__(container, budget_, **kwargs)
1070 if not explicit_container:
1071 del self.container
1072
1073 if isinstance(tell_container_when_switching, str):
1074 if tell_container_when_switching not in ["True", "False", "only_best"]:
1075 raise ValueError("`tell_container_when_switching` must be a bool or one of these strings: 'True', 'False', 'only_best'.")
1076 self.tell_container_when_switching = tell_container_when_switching
1077 self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
1078 self.switch_to(0)
1079
1080 def reinit(self) -> None:
1081 super().reinit()
1082 self._pending_emitters = {}
1083
1084 def __getstate__(self):
1085 state = super().__getstate__()
1086 state["_pending_emitters"] = {}
1087 return state
1088
1089
1090 def __getattr__(self, attr):
1091 if attr in self.__dict__:
1092 return getattr(self, attr)
1093 if "current" not in self.__dict__:
1094 raise AttributeError
1095 if attr == "container" and not self.current.container:
1096 for child in self.algorithms:
1097 if child.container:
1098 return child.container
1099 return getattr(self.current, attr)
1100
1102 if "container" in self.__dict__:
1103 super()._check_archive_weights()
1104 if any(child._fitness_weights != self._fitness_weights for child in self.algorithms):
1105 raise ValueError("An explicit wrapper archive requires matching objective weights on all children.")
1106
1107# def __get_saved_state__(self) -> Mapping[str, Any]:
1108# """Return a dictionary containing the relevant information to save. Only include information from `self.algorithms`."""
1109# res = copy.deepcopy(self.current.__get_saved_state__())
1110# entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)}
1111# return {**entries, **res}
1112
1113
1114 @abc.abstractmethod
1115 def next(self, verbose: bool = False) -> None:
1116 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
1117 raise NotImplementedError("Method `_internal_ask` must be implemented by AlgWrapper subclasses.")
1118# if self.current_idx < len(self.algorithms) - 1:
1119# self.switch_to(self.current_idx + 1)
1120# else:
1121# self.switch_to(0)
1122
1123 def switch_to(self, idx: int, verbose: bool = False):
1124 """Switch to another algorithm of index `idx` in `self.algorithms`."""
1125 assert idx < len(self.algorithms), f"`idx` must be < len(self.algorithms)."
1126 #print(f"SWITCH to {idx}")
1127 previous = self.current
1128 self.current_idx = idx
1129 self.current = self.algorithms[idx]
1130 if (isinstance(self.tell_container_when_switching, bool) and self.tell_container_when_switching) or \
1131 self.tell_container_when_switching == "True":
1133 elif self.tell_container_when_switching == "only_best":
1134 try:
1135 self.current.tell(previous.best(), verbose=verbose) # Exception when no individual is present
1136 except Exception:
1137 pass
1138
1139 def best(self) -> IndividualLike:
1140 if "container" in self.__dict__:
1141 return super().best()
1142 if self.current.container:
1143 return self.current.best()
1144 for child in self.algorithms:
1145 if child.container:
1146 return child.best()
1147 return self.current.best()
1148
1149# def ask(self) -> IndividualLike:
1150# ind = self.current.ask()
1151# self.next()
1152# return ind
1153
1154 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
1155 if self.batch_mode:
1156 batch_size = self.current.batch_size
1157 if np.isinf(batch_size):
1158 batch_size = self.batch_size
1159 if np.isinf(batch_size):
1160 batch_size = 1
1161 if self.current.nb_suggestions % batch_size == 0:
1162 self.next()
1163 else:
1164 self.next()
1165 ind = self.current.ask()
1166 self._pending_emitters[id(ind)] = (ind, self.current)
1167 return ind
1168
1169 def _forget_suggestion(self, individual: IndividualLike) -> None:
1170 _, emitter = self._pending_emitters.pop(id(individual), (individual, None))
1171 if emitter is not None:
1172 emitter._forget_suggestion(individual)
1173
1174
1179 def _transfer_suggestion(self, individual: IndividualLike, evaluated: IndividualLike) -> None:
1180 _, emitter = self._pending_emitters.pop(id(individual), (individual, None))
1181 if emitter is not None:
1182 self._pending_emitters[id(evaluated)] = (evaluated, emitter)
1183 emitter._transfer_suggestion(individual, evaluated)
1184
1185 def tell(self, individual: IndividualLike, fitness: Optional[Any] = None,
1186 features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None,
1187 elapsed: Optional[float] = None, verbose: bool = False, tell_container = True) -> bool:
1188 """Deliver an evaluation to the proposer, or to every child in tell-all mode.
1189
1190 A manually supplied candidate with no pending ask goes to the active
1191 child. Forward the optional evaluation arguments and update permission
1192 to the child. The wrapper accounts for one evaluation and reports an
1193 update if any child reports one.
1194 """
1196 _, emitter = self._pending_emitters.get(id(individual), (individual, self.current))
1197 recipients = self.algorithms if self.tell_all else (emitter,)
1198 report_archive = self.__dict__.get("container")
1199 before = report_archive.nb_added if report_archive is not None else None
1200 added = False
1201 for child in recipients:
1202 candidate = individual if child is emitter else copy.deepcopy(individual)
1203 added |= child.tell(candidate, fitness, features, scores, elapsed, verbose=verbose,
1204 tell_container=tell_container)
1205 self._pending_emitters.pop(id(individual), None)
1206 if report_archive is not None:
1207 if tell_container and all(child.container is not report_archive for child in recipients):
1208 report = copy.deepcopy(individual)
1209 self._apply_evaluation(report, emitter.container.get_ind_fitness(individual),
1210 emitter.container.get_ind_features(individual), None, None)
1211 self._offer_to_container(report, verbose)
1212 added = report_archive.nb_added > before
1213 self._tell_after_container_update(individual, added)
1214 return added
1215
1216# def optimise(self, evaluate: Callable, budget: Optional[int] = None,
1217# batch_mode: bool = True, executor: Optional[ExecutorLike] = None,
1218# send_several_suggestions_to_fn: bool = False) -> IndividualLike:
1219# for _ in range(self.current_idx, len(self.algorithms)):
1220# try:
1221# res = self.current.optimise(evaluate, budget, batch_mode, executor, send_several_suggestions_to_fn)
1222# except Exception as e:
1223# warnings.warn(f"Optimisation failed with algorithm '{self.current.name}': {e}")
1224# traceback.print_exc()
1225# self.next()
1226# return res
1227
1228# def add_callback(self, event: str, fn: Callable) -> None:
1229# for a in self.algorithms:
1230# a.add_callback(event, fn)
1231
1232
1233
1234
1235@registry.register
1237 """Cycle through child optimisers in order when the wrapper switches."""
1238 def next(self, verbose: bool = False) -> None:
1239 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
1240 if self.current_idx < len(self.algorithms) - 1:
1241 self.switch_to(self.current_idx + 1, verbose)
1242 else:
1243 self.switch_to(0, verbose)
1244
1245
1246@registry.register
1248 """Advance to the next child when the active child has issued its budget of suggestions."""
1249 def next(self, verbose: bool = False) -> None:
1250 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
1251 if self.current.nb_suggestions >= self.current.budget:
1252 if self.current_idx < len(self.algorithms) - 1:
1253 self.switch_to(self.current_idx + 1, verbose)
1254
1255
1256
1257
1258@registry.register
1260 """Run complete child optimisations in a fixed sequence.
1261
1262 Switching can feed the next child from its archive or the previous
1263 child's best candidate. A stage failure emits a warning and the next
1264 stage can still run. When every stage fails, the last error is raised.
1265 """
1266 algorithms: Sequence[QDAlgorithm]
1267 current_idx: int = 0
1268 current: QDAlgorithm
1269 tell_container_when_switching: Union[bool, str]
1270
1271 def __init__(self, algorithms: Any, tell_container_when_switching: Union[bool, str] = True,
1272 name: Optional[str] = None, **kwargs):
1273 if len(algorithms) == 0:
1274 raise ValueError("`algorithms` must not be empty.")
1275 self.algorithms = list(algorithms)
1276 self.current_idx = 0
1277 self.current = self.algorithms[self.current_idx]
1278 if isinstance(tell_container_when_switching, str):
1279 if tell_container_when_switching not in ["True", "False", "only_best"]:
1280 raise ValueError("`tell_container_when_switching` must be a bool or one of these strings: 'True', 'False', 'only_best'.")
1281 self.tell_container_when_switching = tell_container_when_switching
1282 self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}"
1283 #self.budget = sum((algo.budget for algo in self.algorithms))
1284 self.switch_to(0)
1285
1286
1287 def __getattr__(self, attr):
1288 if attr in self.__dict__:
1289 return getattr(self, attr)
1290 if "current" not in self.__dict__:
1291 raise AttributeError
1292 return getattr(self.current, attr)
1293
1294
1295 def __get_saved_state__(self) -> Mapping[str, Any]:
1296 """Return a dictionary containing the relevant information to save. Only include information from `self.algorithms`."""
1297 res = copy.deepcopy(self.current.__get_saved_state__())
1298 entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)}
1299 return {**entries, **res}
1300
1301
1302 def next(self, verbose: bool = False) -> None:
1303 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
1304 if self.current_idx < len(self.algorithms) - 1:
1305 self.switch_to(self.current_idx + 1, verbose)
1306
1307 def switch_to(self, idx: int, verbose: bool = False):
1308 """Switch to another algorithm of index `idx` in `self.algorithms`."""
1309 assert idx < len(self.algorithms), f"`idx` must be < len(self.algorithms)."
1310 previous = self.current
1311 self.current_idx = idx
1312 self.current = self.algorithms[idx]
1313 if (isinstance(self.tell_container_when_switching, bool) and self.tell_container_when_switching) or \
1314 self.tell_container_when_switching == "True":
1315 self.current.tell_container_entries()
1316 elif self.tell_container_when_switching == "only_best":
1317 try:
1318 self.current.tell(previous.best(), verbose=verbose) # Exception when no individual is present
1319 except Exception:
1320 pass
1321
1322 def best(self) -> IndividualLike:
1323 return self.current.best()
1324
1325 def ask(self) -> IndividualLike:
1326 return self.current.ask()
1327
1328 def tell(self, individual: IndividualLike, fitness: Optional[Any] = None,
1329 features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None,
1330 elapsed: Optional[float] = None, verbose: bool = False) -> bool:
1331 return self.current.tell(individual, fitness, features, scores, elapsed, verbose=verbose)
1332
1333 def optimise(self, evaluate: Callable, budget: Optional[int] = None,
1334 batch_mode: bool = True, executor: Optional[ExecutorLike] = None,
1335 send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10,
1336 verbose: bool = False) -> IndividualLike:
1337 res = None
1338 last_failure = None
1339 for _ in range(self.current_idx, len(self.algorithms)):
1340 try:
1341 res = self.current.optimise(evaluate, budget, batch_mode, executor,
1342 send_several_suggestions_to_fn = send_several_suggestions_to_fn,
1343 max_nb_suggestions_per_call = max_nb_suggestions_per_call,
1344 verbose = verbose)
1345 except Exception as e:
1346 warnings.warn(f"Optimisation failed with algorithm '{self.current.name}': {e}")
1347 last_failure = e
1348 self.next()
1349 if res is None:
1350 raise last_failure
1351 return res
1352
1353 def add_callback(self, event: str, fn: Callable) -> None:
1354 for a in self.algorithms:
1355 a.add_callback(event, fn)
1356
1357
1358
1359
1360
1361@registry.register
1363 """Use genomes from trusted current result snapshots as suggestions.
1364
1365 Read the saved container entries in file order. The initial budget is
1366 the number of loaded genomes. Each ask copies a reference genome into
1367 a new base candidate and leaves fitness and descriptors to the next
1368 evaluation. Reinitialisation rewinds the cursor.
1369 """
1370 reference_data_files: List[str]
1371 reference_inds_idx: int = 0
1372
1373 def __init__(self, container: Container, reference_data_files: List[str], **kwargs):
1374 self.reference_data_files = [os.path.expanduser(x) for x in reference_data_files]
1375 self.reference_inds: List[Any] = []
1376 for reference_data_file in self.reference_data_files:
1377 reference_data = tools.open_pickle_file(reference_data_file)
1378 self.reference_inds += list(reference_data['container'])
1379 budget = len(self.reference_inds)
1380 super().__init__(container, budget, **kwargs)
1381
1382 def reinit(self) -> None:
1383 super().reinit()
1384 self.reference_inds_idx = 0
1385
1386 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
1387 base_ind[:] = self.reference_inds[self.reference_inds_idx]
1388 self.reference_inds_idx += 1
1389 return base_ind
1390
1391
1392
1393
1394
1395# MODELINE "{{{1
1396# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
1397# vim:foldmethod=marker
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition base.py:1010
switch_to(self, int idx, bool verbose=False)
Definition base.py:1123
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition base.py:1154
IndividualLike best(self)
Definition base.py:1139
None _transfer_suggestion(self, IndividualLike individual, IndividualLike evaluated)
Move proposer ownership to an evaluator's returned individual.
Definition base.py:1179
bool tell(self, IndividualLike individual, Optional[Any] fitness=None, Optional[FeaturesLike] features=None, Optional[ScoresDictLike] scores=None, Optional[float] elapsed=None, bool verbose=False, tell_container=True)
Definition base.py:1187
None next(self, bool verbose=False)
Definition base.py:1115
None next(self, bool verbose=False)
Definition base.py:1238
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition base.py:1386
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition base.py:989
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition base.py:977
IndividualLike ask(self)
Definition base.py:195
IndividualLike best(self)
Definition base.py:203
_offer_to_container(self, individual, verbose)
Definition base.py:561
bool _verify_if_finished_iteration(self, float batch_start_time)
Definition base.py:693
_fixed_batch_plan(self, size, evaluate, packed)
Definition base.py:772
None add_callback(self, str event, Callable fn)
Definition base.py:934
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition base.py:515
Tuple[MutableMapping[str, Any], bool] _tell_before_container_update(self, IndividualLike individual)
Read pre-admission state for optimiser feedback.
Definition base.py:610
Union[str, Sequence[float]] optimisation_task
Definition base.py:321
_account_evaluations(self, count=1)
Definition base.py:642
None _apply_evaluation(self, ind, fitness, features, scores, elapsed)
Definition base.py:575
int nb_evaluations_in_iteration(self)
Definition base.py:451
IndividualLike optimise(self, Callable evaluate, Optional[int] budget=None, bool batch_mode=True, Optional[ExecutorLike] executor=None, bool send_several_suggestions_to_fn=False, int max_nb_suggestions_per_call=10, bool verbose=False)
Definition base.py:779
None _attach_evaluation(self, ind, fitness, features, scores, elapsed)
Definition base.py:567
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition base.py:647
IndividualLike ask(self)
Definition base.py:481
None _forget_suggestion(self, IndividualLike individual)
Definition base.py:755
None _transfer_suggestion(self, IndividualLike individual, IndividualLike evaluated)
Transfer coordinator-side metadata when evaluation returns a new object.
Definition base.py:760
int nb_suggestions_in_iteration(self)
Definition base.py:441
None _start_fixed_batch(self, int size)
Definition base.py:764
None _receive_fixed_batch(self, records, verbose, batch_start_time)
Definition base.py:768
_CallbacksManager _fixed_batch_feedback
Definition base.py:291
Union[int, float] nb_max_iter(self)
Definition base.py:471
IndividualLike best(self)
Definition base.py:675
bool _tell_evaluation_result(self, IndividualLike individual, Any result, float elapsed, bool verbose, *, positional_sizes=())
Definition base.py:714
IndividualLike _internal_best(self)
Definition base.py:686
None tell_container_entries(self, Optional[Container] cont=None)
Definition base.py:660
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
None next(self, bool verbose=False)
Definition base.py:1249
switch_to(self, int idx, bool verbose=False)
Definition base.py:1307
Union tell_container_when_switching
Definition base.py:1269
Mapping[str, Any] __get_saved_state__(self)
Definition base.py:1295
None next(self, bool verbose=False)
Definition base.py:1302
Sequence[Callable] get(self, str event)
Definition base.py:158
None add_callback(self, str event, Callable fn)
Definition base.py:168