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).
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`. """
23__all__ = [
"partial",
"QDAlgorithmLike",
"QDAlgorithm",
"Lambda",
"AlgWithBatchSuggestions",
"Sq",
"AlgWrapper",
"AlternatingAlgWrapper",
"SqAlgWrapper",
"FromArchive"]
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
47partial = functools.partial
49def _result_size(result: Any) -> Optional[int]:
50 if isinstance(result, (str, bytes, Mapping)):
58def _positional_feedback_sizes(tell):
59 """Keep positional feedback for overrides that already accept it.
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.
66 tell_signature = signature(tell)
67 except (TypeError, ValueError):
70 for names
in ((
"fitness",
"features"), (
"fitness",
"features",
"scores")):
72 tell_signature.bind(
None, elapsed=
None, verbose=
False, **dict.fromkeys(names))
74 positional.append(len(names))
76 if any(name
in tell_signature.parameters
and tell_signature.parameters[name].kind
is Parameter.KEYWORD_ONLY
80 tell_signature.bind(
None, *(
None,) * len(names), elapsed=
None, verbose=
False)
83 positional.append(len(names))
84 return tuple(positional)
88 """An evaluator payload failed before archive admission or feedback."""
91def _evaluation_limit(value, name, *, minimum, allow_infinity=False):
92 if allow_infinity
and value == math.inf:
95 count = integer_index(value)
96 except TypeError
as error:
97 raise ValueError(f
"{name} must be an integer.")
from error
99 raise ValueError(f
"{name} must be at least {minimum}.")
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."""
114 res = fn(*args, **kwargs)
115 except Exception
as e:
116 print(f
"Exception during evaluation: {e}")
117 traceback.print_exc()
119 elapsed = timer() - start_time
120 return eval_id, elapsed, res, exc
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."""
131 res = fn(*args, **kwargs)
132 except Exception
as e:
133 print(f
"Exception during evaluation: {e}")
134 traceback.print_exc()
136 elapsed = timer() - start_time
137 return eval_id, elapsed, res, exc
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.
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]]
153 def __getstate__(self):
155 del odict[
'callbacks']
158 def get(self, event: str) -> Sequence[Callable]:
159 """Return the Sequence of functions that can be triggered when `event` happens.
164 The event triggering the returned callback functions.
169 """Attach a callable `fn` to this CallbacksManager. `fn` will be called each time the event specified in `event` occurs.
174 The event triggering the callback.
176 The callback function called when the event specified in `event` occurs.
178 self.
callbacks.setdefault(event, []).append(fn)
183 """Interface shared by native optimisers and algorithm sequences.
185 Callers may ask for a candidate and tell its result directly, or
186 use optimise to manage evaluation and executor dispatch.
190 dimension: Optional[int]
193 def reinit(self) -> None: ...
195 def ask(self) -> IndividualLike: ...
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: ...
201 def tell_container_entries(self, cont: Optional[Container] =
None) ->
None: ...
203 def best(self) -> IndividualLike: ...
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: ...
210 def add_callback(self, event: str, fn: Callable) ->
None: ...
213 def nb_suggestions(self) -> int: ...
216 def nb_suggestions_in_iteration(self) -> int: ...
219 def nb_evaluations(self) -> int: ...
222 def nb_evaluations_in_iteration(self) -> int: ...
225 def nb_updated(self) -> int: ...
228 def nb_updated_in_iteration(self) -> int: ...
231 def batch_size(self) -> int: ...
234 def nb_max_iter(self) -> Union[int,float]: ...
237 def current_iter(self) -> int: ...
245 """Combine a candidate generator, an evaluation budget, and an archive.
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.
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.
274 dimension: Optional[int]
276 _base_ind_gen: Optional[Generator[IndividualLike,
None,
None]]
278 _optimisation_task: Union[str, Sequence[float]]
280 _fitness_weights: Sequence
282 _nb_suggestions_in_iteration: int
284 _nb_evaluations_in_iteration: int
286 _nb_updated_in_iteration: int
287 _batch_size: Optional[int]
288 _callbacks: _CallbacksManager
291 _fixed_batch_feedback =
False
292 _lineage_recorder =
None
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,
299 add_default_logger: bool =
False, name: Optional[str] =
None,
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))
307 self.
name = name
if name
is not None else f
"{self.__class__.__name__}-{id(self)}"
309 if nb_objectives
is not None:
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.")
322 if add_default_logger:
323 from .logging
import default_algorithm_logger
324 default_algorithm_logger.monitor(self)
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
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:
338 raise ValueError(
"`tell_container_parents` can only be set to 'parents' if `container` possesses at least one parent.")
349 """Reset counters for suggestions, evaluation, and archive updates.
351 This base method leaves the archive and callbacks in place.
352 Subclasses may also reset their generator or optimiser state.
362 def __getstate__(self):
364 del odict[
'_base_ind_gen']
365 odict.pop(
'_lineage_recorder',
None)
369 def __deepcopy__(self, memo):
371 result = cls.__new__(cls)
372 memo[id(self)] = result
374 if k ==
"_lineage_recorder":
377 setattr(result, k, v)
379 setattr(result, k, copy.deepcopy(v, memo))
384 def optimisation_task(self) -> Union[str, Sequence[float]]:
385 """The objective direction or explicit comparison weights."""
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`.
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.
405 if isinstance(optimisation_task, str)
and \
406 any((optimisation_task == a
for a
in [
"minimisation",
"minimization",
"minimise",
"minimize",
"min"])):
407 task =
"minimisation"
409 elif isinstance(optimisation_task, str)
and \
410 any((optimisation_task == a
for a
in [
"maximisation",
"maximization",
"maximise",
"maximize",
"max"])):
411 task =
"maximisation"
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)
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:
428 """Catch conflicting objective directions before proposing or admitting candidates."""
431 raise ValueError(
"Archive fitness weights conflict with this optimiser. "
432 "Use the same optimisation_task for optimisers sharing an archive.")
437 """Number of candidates returned by ask since initialisation or reinitialisation."""
442 """Number of asks recorded since the last managed iteration ended."""
446 def nb_evaluations(self) -> int:
447 """Number of tell calls or candidate slots consumed by the managed scheduler."""
452 """Number of accounted evaluations since the last iteration ended."""
457 """Number of evaluations for which the archive reported a local update."""
462 """Number of reported archive updates since the last iteration ended."""
466 def batch_size(self) -> int:
467 """Configured candidate count per iteration, or the current budget when omitted."""
472 """Ceiling of the current budget divided by the batch size for a finite run."""
477 """Number of full batches accounted for by the evaluation counter."""
481 def ask(self) -> IndividualLike:
482 """Return the next candidate for evaluation.
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.
496 if recorder
is not None:
497 recorder._parentage(
"initialise", ())
501 if suggestion.name ==
"":
502 suggestion.name = f
"{int(round(time.time() * 1000))}-{self._nb_suggestions}"
506 if recorder
is not None:
516 """Internal ask method. To be implemented by subclasses.
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.
527 The suggested individual.
529 raise NotImplementedError(
"Method `_internal_ask` must be implemented by QDAlgorithm subclasses.")
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.
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.
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.
561 def _offer_to_container(self, individual, verbose):
563 self.
container.update([individual], issue_warning=verbose)
568 """Apply the native evaluator payload without admitting the candidate."""
572 except (AttributeError, IndexError, KeyError, TypeError, ValueError, OverflowError)
as error:
575 def _apply_evaluation(self, ind, fitness, features, scores, elapsed) -> None:
576 if scores
is not None:
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)
584 ind_fit = copy.copy(fitness)
586 ind_fit.values = fitness
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)
598 ind.features = features
600 ind.features.values = features
601 if elapsed
is not None:
602 ind.elapsed = elapsed
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
618 :param individual: IndividualLike
619 The `individual` provided to the algorithm.
640 fn(self, individual, added, xattr)
642 def _account_evaluations(self, count=1):
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.
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.
661 """Send stored entries to the optimiser's internal feedback hook.
663 :param cont: Source of the warm-start entries. Defaults to the
664 optimiser's own archive.
666 Entries are marked as accepted for the hook. Archive admission,
667 evaluation counters, and tell callbacks are bypassed.
675 def best(self) -> IndividualLike:
676 """Return the best retained candidate.
678 :raises RuntimeError: If the container has no candidates.
682 raise RuntimeError(
"`self.container` contains no individual !")
687 """Return the individual with the best quality. To be overridden by subclasses.
688 By default, returns the best individual of `self.container`."""
694 """Emit the iteration event at an exact evaluation boundary.
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.
703 batch_elapsed: float = timer() - batch_start_time
706 fn(self, batch_elapsed)
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:
718 if size
not in (0, 2, 3):
719 warnings.warn(
"Evaluation function returned malformatted results.")
721 evaluated, measurements = individual, result
722 elif result_type
is Individual
or isinstance(result, IndividualLike):
723 if result
is not individual:
725 evaluated, measurements, size = result, (), 0
727 evaluated = individual
728 size = _result_size(result)
729 if size
not in (0, 2, 3):
730 warnings.warn(
"Evaluation function returned malformatted results.")
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}")
738 if size
in positional_sizes:
739 self.
tell(evaluated, *measurements, elapsed=elapsed, verbose=verbose)
741 self.
tell(evaluated, fitness=measurements[0], features=measurements[1],
742 elapsed=elapsed, verbose=verbose)
744 self.
tell(evaluated, fitness=measurements[0], features=measurements[1], scores=measurements[2],
745 elapsed=elapsed, verbose=verbose)
747 self.
tell(evaluated, elapsed=elapsed, verbose=verbose)
748 except _InvalidEvaluation
as error:
749 if evaluated
is not individual:
751 warnings.warn(f
"Evaluation function returned malformatted results: {error}")
755 def _forget_suggestion(self, individual: IndividualLike) ->
None:
765 """Prepare a generation for an optimiser that opts into batch feedback."""
766 raise NotImplementedError
769 """Commit a generation in proposal order for an opted-in optimiser."""
770 raise NotImplementedError
773 """Select the size and evaluator for the next fixed phase."""
774 return size, evaluate, packed
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.
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.
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.
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.
808 raise ValueError(
"This optimiser requires batch_mode=True.")
809 optimisation_start_time: float = timer()
812 limit = self.
budget if budget
is None else budget
814 raise ValueError(
"`budget` must be provided.")
815 self.
budget = _evaluation_limit(limit,
"budget", minimum=0, allow_infinity=
True)
817 _evaluation_limit(self.
batch_size,
"batch_size", minimum=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)
825 for fn
in self.
_callbacks.get(
"started_optimisation"):
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)
833 receive_feedback = partial(receive_feedback, positional_sizes=positional_sizes)
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]] = {}
844 available = min(budget_fn() - submitted_evals, self.
batch_size - pending_evals)
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)
850 future = _executor.submit(_severalEvalsWrapper, next_eval_id, evaluator, inds)
852 future = _executor.submit(_evalWrapper, next_eval_id, evaluator, inds[0])
853 futures[next_eval_id] = future
855 pending_evals += group_size
856 submitted_evals += group_size
857 available -= group_size
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)
867 pending_evals -= len(inds)
869 if error
is not None:
870 warnings.warn(f
"Individual evaluation raised the following exception: {error} !")
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.")
879 elif _result_size(result) == len(inds):
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}")
886 warnings.warn(
"Packed evaluation must return one result per candidate.")
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)
896 for index, individual
in enumerate(inds):
897 if results
is None or not receive_feedback(individual, results[index], elapsed, verbose):
901 batch_start_time = timer()
903 if completed_groups
is not None:
904 records = [record
for group
in sorted(completed_groups)
for record
in completed_groups[group]]
909 while completed_evals < self.
budget:
913 budget_iteration, evaluate, send_several_suggestions_to_fn,
916 optimisation_loop(
lambda: budget_iteration, evaluator, packed)
918 optimisation_loop(
lambda: budget_iteration)
919 completed_evals += budget_iteration
924 optimisation_loop(ret_budget)
927 optimisation_elapsed: float = timer() - optimisation_start_time
928 for fn
in self.
_callbacks.get(
"finished_optimisation"):
929 fn(self, optimisation_elapsed)
935 """Attach a callable `fn` to the optimiser. `fn` will be called each time the event specified in `event` occurs.
940 The event triggering the callback. Can be either 'ask', 'tell', 'iteration' (when an iteration finishes)
941 'started_optimisation', or 'finished_optimisation'.
943 The callback function called when the event specified in `event` occurs.
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)}.")
955 """Build an algorithm from user-supplied ask and optional tell functions.
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
961 _ask_fn: Union[Callable[[], IndividualLike], Callable[[IndividualLike], IndividualLike]]
962 _tell_fn: Optional[Callable]
964 def __getstate__(self):
965 odict = super().__getstate__()
967 del odict[
'_tell_fn']
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)
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)."""
983 if len(sig.parameters) == 0:
989 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) ->
None:
991 self.
_tell_fn(individual, added_to_container)
997 """Buffer candidates prepared in groups and return them one at a time.
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.
1004 _batch_inds: List[IndividualLike]
1006 def __init__(self, container: Container, budget: int, **kwargs):
1007 super().__init__(container, budget, **kwargs)
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.")
1026 """Coordinate child optimisers under one ask/tell interface.
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.
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.
1038 algorithms: Sequence[QDAlgorithm]
1039 current_idx: int = 0
1040 current: QDAlgorithm
1041 tell_container_when_switching: Union[bool, str]
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.")
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:
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'.")
1077 self.
name = name
if name
is not None else f
"{self.__class__.__name__}-{id(self)}"
1084 def __getstate__(self):
1085 state = super().__getstate__()
1086 state[
"_pending_emitters"] = {}
1090 def __getattr__(self, attr):
1092 return getattr(self, attr)
1094 raise AttributeError
1095 if attr ==
"container" and not self.
current.container:
1098 return child.container
1099 return getattr(self.
current, attr)
1105 raise ValueError(
"An explicit wrapper archive requires matching objective weights on all children.")
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.")
1124 """Switch to another algorithm of index `idx` in `self.algorithms`."""
1125 assert idx < len(self.
algorithms), f
"`idx` must be < len(self.algorithms)."
1135 self.
current.
tell(previous.best(), verbose=verbose)
1141 return super().
best()
1156 batch_size = self.
current.batch_size
1157 if np.isinf(batch_size):
1159 if np.isinf(batch_size):
1161 if self.
current.nb_suggestions % batch_size == 0:
1169 def _forget_suggestion(self, individual: IndividualLike) ->
None:
1171 if emitter
is not None:
1172 emitter._forget_suggestion(individual)
1181 if emitter
is not None:
1183 emitter._transfer_suggestion(individual, evaluated)
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.
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.
1198 report_archive = self.
__dict__.get(
"container")
1199 before = report_archive.nb_added
if report_archive
is not None else None
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)
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)
1210 emitter.container.get_ind_features(individual),
None,
None)
1212 added = report_archive.nb_added > before
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."""
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."""
1260 """Run complete child optimisations in a fixed sequence.
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.
1266 algorithms: Sequence[QDAlgorithm]
1267 current_idx: int = 0
1268 current: QDAlgorithm
1269 tell_container_when_switching: Union[bool, str]
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.")
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'.")
1282 self.
name = name
if name
is not None else f
"{self.__class__.__name__}-{id(self)}"
1287 def __getattr__(self, attr):
1289 return getattr(self, attr)
1291 raise AttributeError
1292 return getattr(self.
current, attr)
1296 """Return a dictionary containing the relevant information to save. Only include information from `self.algorithms`."""
1298 entries = {k:v
for k,v
in inspect.getmembers(self)
if not k.startswith(
'_')
and not inspect.ismethod(v)}
1299 return {**entries, **res}
1302 def next(self, verbose: bool =
False) ->
None:
1303 """Switch to the next algorithm in Sequence `self.algorithms`, if there is one."""
1308 """Switch to another algorithm of index `idx` in `self.algorithms`."""
1309 assert idx < len(self.
algorithms), f
"`idx` must be < len(self.algorithms)."
1315 self.
current.tell_container_entries()
1318 self.
current.tell(previous.best(), verbose=verbose)
1322 def best(self) -> IndividualLike:
1325 def ask(self) -> IndividualLike:
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)
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:
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,
1345 except Exception
as e:
1346 warnings.warn(f
"Optimisation failed with algorithm '{self.current.name}': {e}")
1353 def add_callback(self, event: str, fn: Callable) ->
None:
1355 a.add_callback(event, fn)
1363 """Use genomes from trusted current result snapshots as suggestions.
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.
1370 reference_data_files: List[str]
1371 reference_inds_idx: int = 0
1373 def __init__(self, container: Container, reference_data_files: List[str], **kwargs):
1377 reference_data = tools.open_pickle_file(reference_data_file)
1380 super().__init__(container, budget, **kwargs)
IndividualLike _internal_ask(self, IndividualLike base_ind)
None _generate_batch_suggestions(self)
switch_to(self, int idx, bool verbose=False)
IndividualLike _internal_ask(self, IndividualLike base_ind)
_check_archive_weights(self)
IndividualLike best(self)
Union tell_container_when_switching
None _transfer_suggestion(self, IndividualLike individual, IndividualLike evaluated)
Move proposer ownership to an evaluator's returned individual.
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)
None next(self, bool verbose=False)
None next(self, bool verbose=False)
IndividualLike _internal_ask(self, IndividualLike base_ind)
List reference_data_files
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
IndividualLike _internal_ask(self, IndividualLike base_ind)
IndividualLike best(self)
_offer_to_container(self, individual, verbose)
bool _verify_if_finished_iteration(self, float batch_start_time)
_fixed_batch_plan(self, size, evaluate, packed)
None add_callback(self, str event, Callable fn)
IndividualLike _internal_ask(self, IndividualLike base_ind)
_check_archive_weights(self)
Tuple[MutableMapping[str, Any], bool] _tell_before_container_update(self, IndividualLike individual)
Read pre-admission state for optimiser feedback.
Union[str, Sequence[float]] optimisation_task
_account_evaluations(self, count=1)
None _apply_evaluation(self, ind, fitness, features, scores, elapsed)
int _nb_updated_in_iteration
int nb_evaluations_in_iteration(self)
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)
None _attach_evaluation(self, ind, fitness, features, scores, elapsed)
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
None _forget_suggestion(self, IndividualLike individual)
int _nb_evaluations_in_iteration
None _transfer_suggestion(self, IndividualLike individual, IndividualLike evaluated)
Transfer coordinator-side metadata when evaluation returns a new object.
int nb_suggestions_in_iteration(self)
None _start_fixed_batch(self, int size)
None _receive_fixed_batch(self, records, verbose, batch_start_time)
int nb_updated_in_iteration(self)
int _nb_suggestions_in_iteration
_CallbacksManager _fixed_batch_feedback
Union[int, float] nb_max_iter(self)
IndividualLike best(self)
bool _tell_evaluation_result(self, IndividualLike individual, Any result, float elapsed, bool verbose, *, positional_sizes=())
IndividualLike _internal_best(self)
None tell_container_entries(self, Optional[Container] cont=None)
None _tell_after_container_update(self, IndividualLike individual, bool added, Mapping[str, Any] xattr={})
Account for a completed tell and send feedback.
None next(self, bool verbose=False)
switch_to(self, int idx, bool verbose=False)
Union tell_container_when_switching
Mapping[str, Any] __get_saved_state__(self)
None next(self, bool verbose=False)
Sequence[Callable] get(self, str event)
None add_callback(self, str event, Callable fn)