Source code for qdpy.algorithms.base

#    This file is part of qdpy.
#
#    qdpy is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as
#    published by the Free Software Foundation, either version 3 of
#    the License, or (at your option) any later version.
#
#    qdpy is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public
#    License along with qdpy. If not, see <http://www.gnu.org/licenses/>.

## @file
# @brief Ask/tell protocols, evaluation scheduling, callbacks, and algorithm composition.

"""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).

All 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`. """

__all__ = ["partial", "QDAlgorithmLike", "QDAlgorithm", "Lambda", "AlgWithBatchSuggestions", "Sq", "AlgWrapper", "AlternatingAlgWrapper", "SqAlgWrapper", "FromArchive"]

import abc
import math
import time
from operator import index as integer_index
from timeit import default_timer as timer
from inspect import Parameter, signature
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
from typing_extensions import runtime, Protocol
import warnings
import numpy as np
import copy
import traceback
import os


from qdpy.utils import *
from qdpy.phenotype import *
from qdpy.base import *
from qdpy.containers import *
from qdpy import tools

import functools
partial = functools.partial # type: ignore

def _result_size(result: Any) -> Optional[int]:
    if isinstance(result, (str, bytes, Mapping)):
        return None
    try:
        return len(result)
    except TypeError:
        return None


def _positional_feedback_sizes(tell):
    """Keep positional feedback for overrides that already accept it.

    A declared keyword-only measurement takes precedence over ``*args``.
    Check pairs and triples separately since ``scores`` can be keyword-only
    even when fitness and features accept either call form.
    """
    try:
        tell_signature = signature(tell)
    except (TypeError, ValueError):
        return (2, 3)
    positional = []
    for names in (("fitness", "features"), ("fitness", "features", "scores")):
        try:
            tell_signature.bind(None, elapsed=None, verbose=False, **dict.fromkeys(names))
        except TypeError:
            positional.append(len(names))
            continue
        if any(name in tell_signature.parameters and tell_signature.parameters[name].kind is Parameter.KEYWORD_ONLY
               for name in names):
            continue
        try:
            tell_signature.bind(None, *(None,) * len(names), elapsed=None, verbose=False)
        except TypeError:
            continue
        positional.append(len(names))
    return tuple(positional)


class _InvalidEvaluation(ValueError):
    """An evaluator payload failed before archive admission or feedback."""


def _evaluation_limit(value, name, *, minimum, allow_infinity=False):
    if allow_infinity and value == math.inf:
        return math.inf
    try:
        count = integer_index(value)
    except TypeError as error:
        raise ValueError(f"{name} must be an integer.") from error
    if count < minimum:
        raise ValueError(f"{name} must be at least {minimum}.")
    return count

## @brief Return a scheduler result even when an evaluator raises.
# @details The dispatch ID binds the response to its candidate. A
#     captured error reaches the scheduler as data so its consumed
#     budget is accounted for alongside successful calls.
def _evalWrapper(eval_id: int, fn: Callable, *args, **kwargs) -> Tuple[int, float, Any, Any]:
    """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."""
    start_time = timer()
    exc = None
    #fitness = None
    #features = None
    res = None
    try:
        res = fn(*args, **kwargs)
    except Exception as e:
        print(f"Exception during evaluation: {e}")
        traceback.print_exc()
        exc = e
    elapsed = timer() - start_time
    return eval_id, elapsed, res, exc


def _severalEvalsWrapper(eval_id: int, fn: Callable, *args, **kwargs) -> Tuple[int, float, Any, Any]:
    """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."""
    start_time = timer()
    exc = None
    #fitness = None
    #features = None
    res = None
    try:
        res = fn(*args, **kwargs)
    except Exception as e:
        print(f"Exception during evaluation: {e}")
        traceback.print_exc()
        exc = e
    elapsed = timer() - start_time
    return eval_id, elapsed, res, exc


class _CallbacksManager(Copyable):
    """Manager of callback functions that are called when specific events of the `QDAlgorithm` class are triggered.
    It is possible to register a callback function using the `self.add_callback` method. The callback functions
    attached to a specific event are retrieved through the `self.get` method.

    We regroup callback function handling in this private class to ease the serialisation of QDAlgorithm and its sub-classes.
    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."""
    callbacks: MutableMapping[str, MutableSequence[Callable]]

    def __init__(self):
        self.callbacks = {}
        pass

    def __getstate__(self):
        odict = self.__dict__.copy()
        del odict['callbacks']
        return odict

    def get(self, event: str) -> Sequence[Callable]:
        """Return the Sequence of functions that can be triggered when `event` happens. 

        Parameters
        ----------
        :param event: str
            The event triggering the returned callback functions.
        """
        return self.callbacks.get(event, [])

    def add_callback(self, event: str, fn: Callable) -> None:
        """Attach a callable `fn` to this CallbacksManager. `fn` will be called each time the event specified in `event` occurs.
        
        Parameters
        ----------
        :param event: str
            The event triggering the callback.
        :param fn: Callable
            The callback function called when the event specified in `event` occurs.
        """
        self.callbacks.setdefault(event, []).append(fn)


[docs] @runtime class QDAlgorithmLike(Protocol): """Interface shared by native optimisers and algorithm sequences. Callers may ask for a candidate and tell its result directly, or use optimise to manage evaluation and executor dispatch. """ name: str container: Container dimension: Optional[int] budget: int def reinit(self) -> None: ... def ask(self) -> IndividualLike: ... def tell(self, individual: IndividualLike, fitness: Optional[Any] = None, features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None, elapsed: Optional[float] = None, verbose: bool = False) -> bool: ... def tell_container_entries(self, cont: Optional[Container] = None) -> None: ... def best(self) -> IndividualLike: ... def optimise(self, evaluate: Callable, budget: Optional[int] = None, batch_mode: bool = True, executor: Optional[ExecutorLike] = None, send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10, verbose: bool = False) -> IndividualLike: ... def add_callback(self, event: str, fn: Callable) -> None: ... @property def nb_suggestions(self) -> int: ... @property def nb_suggestions_in_iteration(self) -> int: ... @property def nb_evaluations(self) -> int: ... @property def nb_evaluations_in_iteration(self) -> int: ... @property def nb_updated(self) -> int: ... @property def nb_updated_in_iteration(self) -> int: ... @property def batch_size(self) -> int: ... @property def nb_max_iter(self) -> Union[int,float]: ... @property def current_iter(self) -> int: ...
# Inspiration from the nevergrad library
[docs] class QDAlgorithm(abc.ABC, QDAlgorithmLike, Summarisable, Saveable, Copyable, CreatableFromConfig): """Combine a candidate generator, an evaluation budget, and an archive. The container resolves objective and descriptor vectors and controls admission. The optimiser generates genomes and consumes feedback. Ask and tell support an application-managed evaluator. Optimise adds scheduling, timing, and callbacks to the same protocol. :param container: Archive used for admission and best-candidate queries. :param budget: Candidate evaluations available to each managed run. :param batch_size: Candidates in one iteration and maximum number pending at once. Defaults to the budget. :param dimension: Genome length for algorithms that generate vectors. :param nb_objectives: Objective count. When omitted, infer it from the container's fitness domain or use one objective. :param optimisation_task: Minimise, maximise, or supply one finite comparison weight per objective. :param base_ind_gen: Iterator supplying a fresh candidate for each ask. :param tell_container_at_init: Feed stored entries to the algorithm when true or ``"yes"``. Use ``"parents"`` to feed entries from immediate parents and pass their child membership to the hook. :param add_default_logger: Attach the shared console logger. :param name: Name for callbacks, logs, and saved result metadata. """ #ind_domain: Optional[DomainLike] #executor: Optional[ExecutorLike] name: str container: Container dimension: Optional[int] budget: int _base_ind_gen: Optional[Generator[IndividualLike, None, None]] _nb_objectives: int _optimisation_task: Union[str, Sequence[float]] #_elapsed: float = 0. _fitness_weights: Sequence _nb_suggestions: int _nb_suggestions_in_iteration: int _nb_evaluations: int _nb_evaluations_in_iteration: int _nb_updated: int _nb_updated_in_iteration: int _batch_size: Optional[int] _callbacks: _CallbacksManager _fixed_batch_feedback = False _lineage_recorder = None def __init__(self, container: Container, budget: int, batch_size: Optional[int] = None, dimension: Optional[int] = None, nb_objectives: Optional[int] = None, optimisation_task: Union[str, Sequence[float]] = "minimisation", base_ind_gen: Optional[Generator[IndividualLike, None, None]] = None, tell_container_at_init: Union[bool, str] = False, # XXX add_default_logger: bool = False, name: Optional[str] = None, **kwargs): self.container = container self.dimension = dimension self.budget = None if budget is None else _evaluation_limit(budget, "budget", minimum=0, allow_infinity=True) self._batch_size = (None if batch_size is None else _evaluation_limit(batch_size, "batch_size", minimum=1, allow_infinity=True)) self._base_ind_gen = base_ind_gen self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}" if nb_objectives is not None: self._nb_objectives = nb_objectives else: if self.container.fitness_domain is None or len(self.container.fitness_domain) == 0: #raise ValueError("You must either specify `nb_objectives` or providing as `container` a Container with a declared fitness domain.") 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.") self._nb_objectives = 1 else: self._nb_objectives = len(self.container.fitness_domain) self.reinit() self._callbacks = _CallbacksManager() self.optimisation_task = optimisation_task if add_default_logger: from .logging import default_algorithm_logger default_algorithm_logger.monitor(self) # If needed, tell container entries tell_container_parents: bool = False tell_container: bool = False if isinstance(tell_container_at_init, bool): tell_container = tell_container_at_init else: if tell_container_at_init.lower() == "yes": tell_container = True elif tell_container_at_init.lower() == "parents": tell_container_parents = True if tell_container_parents: if not self.container.parents: raise ValueError("`tell_container_parents` can only be set to 'parents' if `container` possesses at least one parent.") for p in self.container.parents: for e in p: is_in_container = e in self.container self._internal_tell(e, is_in_container) elif tell_container: for e in self.container: self._internal_tell(e, True)
[docs] def reinit(self) -> None: """Reset counters for suggestions, evaluation, and archive updates. This base method leaves the archive and callbacks in place. Subclasses may also reset their generator or optimiser state. """ self._nb_suggestions = 0 self._nb_suggestions_in_iteration = 0 self._nb_evaluations = 0 self._nb_evaluations_in_iteration = 0 self._nb_updated = 0 self._nb_updated_in_iteration = 0
def __getstate__(self): odict = self.__dict__.copy() del odict['_base_ind_gen'] odict.pop('_lineage_recorder', None) return odict # Do not copy the container when deep copying def __deepcopy__(self, memo): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result for k, v in self.__dict__.items(): if k == "_lineage_recorder": continue if k == "container": setattr(result, k, v) else: setattr(result, k, copy.deepcopy(v, memo)) return result @property def optimisation_task(self) -> Union[str, Sequence[float]]: """The objective direction or explicit comparison weights.""" return self._optimisation_task # TODO init fitness_weights of container, instead of algorithm @optimisation_task.setter def optimisation_task(self, optimisation_task: Union[str, Sequence[float]]) -> None: """Update the kind of optimisation task performed by this `QDAlgorithm`. Parameters ---------- :param optimisation_task: Union[str, Sequence[float]] The kind of optimisation task to perform for all objectives of the fitness functions. If `optimisation_task` is a string, it can take the following values: - for minimising all fitness objectives: 'minimisation', 'minimization', 'minimise', 'minimize', 'min' - for maximising all fitness objectives: 'maximisation', 'maximization', 'maximise', 'maximize', 'max' If `optimisation_task` is a Sequence of floats, its length corresponds to the number of objectives, and each entry is a weight to apply to each objective score. Maximised objectives have a corresponding weight > 0 while minimised objectives have weights < 0. The length of this Sequence must be same as the length of the `self.container.fitness_domain` attribute. """ if isinstance(optimisation_task, str) and \ any((optimisation_task == a for a in ["minimisation", "minimization", "minimise", "minimize", "min"])): task = "minimisation" weights = (-1.,) * self._nb_objectives elif isinstance(optimisation_task, str) and \ any((optimisation_task == a for a in ["maximisation", "maximization", "maximise", "maximize", "max"])): task = "maximisation" weights = (1.,) * self._nb_objectives elif isinstance(optimisation_task, Sequence) and not isinstance(optimisation_task, str): if len(optimisation_task) != self._nb_objectives or not all(map(math.isfinite, optimisation_task)): raise ValueError("Supply one finite weight per objective.") task = weights = tuple(optimisation_task) else: raise ValueError("`optimisation_task` must be either a tuple of fitness weights, or a string equals to either 'minimisation' or 'maximisation'.") set_weights = getattr(self.container, "_set_fitness_weights", None) if set_weights is None: self.container.fitness_weights = weights else: set_weights(weights) self._optimisation_task = task self._fitness_weights = weights def _check_archive_weights(self): """Catch conflicting objective directions before proposing or admitting candidates.""" weights = self.container.fitness_weights if weights is None or tuple(weights) != self._fitness_weights: raise ValueError("Archive fitness weights conflict with this optimiser. " "Use the same optimisation_task for optimisers sharing an archive.") @property def nb_suggestions(self) -> int: """Number of candidates returned by ask since initialisation or reinitialisation.""" return self._nb_suggestions @property def nb_suggestions_in_iteration(self) -> int: """Number of asks recorded since the last managed iteration ended.""" return self._nb_suggestions_in_iteration @property def nb_evaluations(self) -> int: """Number of tell calls or candidate slots consumed by the managed scheduler.""" return self._nb_evaluations @property def nb_evaluations_in_iteration(self) -> int: """Number of accounted evaluations since the last iteration ended.""" return self._nb_evaluations_in_iteration @property def nb_updated(self) -> int: """Number of evaluations for which the archive reported a local update.""" return self._nb_updated @property def nb_updated_in_iteration(self) -> int: """Number of reported archive updates since the last iteration ended.""" return self._nb_updated_in_iteration @property def batch_size(self) -> int: """Configured candidate count per iteration, or the current budget when omitted.""" return self._batch_size if self._batch_size is not None else self.budget @property def nb_max_iter(self) -> Union[int,float]: """Ceiling of the current budget divided by the batch size for a finite run.""" return math.ceil(self.budget / self.batch_size) if not math.isinf(self.budget) else math.inf @property def current_iter(self) -> int: """Number of full batches accounted for by the evaluation counter.""" return math.floor(self._nb_evaluations / self.batch_size)
[docs] def ask(self) -> IndividualLike: """Return the next candidate for evaluation. Create the base individual, let the subclass propose its genome, assign a name if empty, increment the suggestion counters, and invoke ask callbacks. Keep the suggested object available when sending feedback to a wrapper with multiple emitters. """ self._check_archive_weights() # Create base individual if self._base_ind_gen is None: base_ind: IndividualLike = Individual() else: base_ind = next(self._base_ind_gen) recorder = self._lineage_recorder if recorder is not None: recorder._parentage("initialise", ()) # Call _internal_ask suggestion = self._internal_ask(base_ind) # Update individual name and fitness weights if suggestion.name == "": suggestion.name = f"{int(round(time.time() * 1000))}-{self._nb_suggestions}" #suggestion.fitness.weights = self._fitness_weights # XXX self._nb_suggestions += 1 self._nb_suggestions_in_iteration += 1 if recorder is not None: recorder._proposed(suggestion, self._nb_suggestions) # Call callback functions for fn in self._callbacks.get("ask"): fn(self, suggestion) return suggestion
@abc.abstractmethod def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: """Internal ask method. To be implemented by subclasses. Parameters ---------- :param base_ind: IndividualLike The base (empty) individual object. The `_internal_ask` method must change this object, by filling out the genome and providing other information. Returns ------- out: IndividualLike The suggested individual. """ raise NotImplementedError("Method `_internal_ask` must be implemented by QDAlgorithm subclasses.")
[docs] def tell(self, individual: IndividualLike, fitness: Optional[Any] = None, features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None, elapsed: Optional[float] = None, verbose: bool = False, tell_container = True) -> bool: """Report an evaluated candidate and offer it to the container. A call updates the candidate's supplied evaluation attributes. The container applies comparison weights to raw objective values. The algorithm's pre-admission hook may add feedback metadata or decline insertion. Feedback and evaluation counters still run when archive insertion is disabled. :param individual: Candidate associated with this evaluation. :param fitness: Objective values or a fitness object. If omitted, use the candidate's existing or named fitness. :param features: Descriptor values or a descriptor object. :param scores: Named scores to store on the candidate first. :param elapsed: Evaluation duration in seconds. :param verbose: Report archive validation warnings. :param tell_container: Permit an archive update. :returns: Whether the container reported a local update. :raises ValueError: If the objective count differs from the configured count. """ ind = individual self._attach_evaluation(ind, fitness, features, scores, elapsed) xattr, allowed_to_tell = self._tell_before_container_update(ind) added = tell_container and allowed_to_tell and self._offer_to_container(ind, verbose) self._tell_after_container_update(ind, added, xattr) return added
def _offer_to_container(self, individual, verbose): before = self.container.nb_added self.container.update([individual], issue_warning=verbose) return self.container.nb_added > before def _attach_evaluation(self, ind, fitness, features, scores, elapsed) -> None: """Apply the native evaluator payload without admitting the candidate.""" self._check_archive_weights() try: self._apply_evaluation(ind, fitness, features, scores, elapsed) except (AttributeError, IndexError, KeyError, TypeError, ValueError, OverflowError) as error: raise _InvalidEvaluation(str(error)) from error def _apply_evaluation(self, ind, fitness, features, scores, elapsed) -> None: if scores is not None: ind.scores = scores ind_fit = self.container.get_ind_fitness(ind) if fitness is not None: fitness_type = type(fitness) if fitness_type is Fitness or ( fitness_type is not tuple and fitness_type is not list and isinstance(fitness, FitnessLike) ): ind_fit = copy.copy(fitness) else: ind_fit.values = fitness if len(ind_fit.values) != self._nb_objectives: #if len(ind.fitness.values) != self._nb_objectives: #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}") 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)}.") if fitness is not None: self.container.set_ind_fitness(ind, ind_fit) if features is not None: features_type = type(features) if features_type is Features or ( features_type is not tuple and features_type is not list and isinstance(features, FeaturesLike) ): ind.features = features else: ind.features.values = features if elapsed is not None: ind.elapsed = elapsed ## @brief Read pre-admission state for optimiser feedback. # @param individual Candidate with its reported evaluation attached. # @return A metadata mapping and a flag permitting archive admission. # @details Improvement emitters read the incumbent here so the signed # gain is measured against the previous cell quality. def _tell_before_container_update(self, individual: IndividualLike) -> Tuple[MutableMapping[str, Any], bool]: """Called by the ``tell`` method before adding the individual to the container. Can be used to compile a dictionary of information about the individual or container before the update operation occurs. Return a dictionary of extended attributes and a boolean flag indicating whether the algorithm is allowed to tell the individual or not. Parameters ---------- :param individual: IndividualLike The `individual` provided to the algorithm. """ return {}, True ## @brief Account for a completed tell and send feedback. # @param individual Evaluated candidate. # @param added Whether admission reported a local update. # @param xattr Metadata captured by the pre-admission hook. # @details Feedback runs before the evaluation count advances. Tell # callbacks run afterwards and can read the updated counters. def _tell_after_container_update(self, individual: IndividualLike, added: bool, xattr: Mapping[str, Any] = {}) -> None: if added: self._nb_updated += 1 self._nb_updated_in_iteration += 1 self._internal_tell(individual, added, xattr) self._account_evaluations() if self._lineage_recorder is not None: self._lineage_recorder._result(individual, "accepted" if added else "rejected", self.nb_evaluations) # Call callback functions for fn in self._callbacks.get("tell"): fn(self, individual, added, xattr) def _account_evaluations(self, count=1): self._nb_evaluations += count self._nb_evaluations_in_iteration += count def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None: """Internal tell method. To be overridden by subclasses, or left empty. Parameters ---------- :param individual: IndividualLike The `individual` provided to the algorithm. :param added_to_container: bool True if `individual` was successfully added to the container. """ pass
[docs] def tell_container_entries(self, cont: Optional[Container] = None) -> None: """Send stored entries to the optimiser's internal feedback hook. :param cont: Source of the warm-start entries. Defaults to the optimiser's own archive. Entries are marked as accepted for the hook. Archive admission, evaluation counters, and tell callbacks are bypassed. """ if cont is None: cont = self.container for ind in cont: self._internal_tell(ind, True)
[docs] def best(self) -> IndividualLike: """Return the best retained candidate. :raises RuntimeError: If the container has no candidates. """ self._check_archive_weights() if len(self.container) == 0: raise RuntimeError("`self.container` contains no individual !") return self._internal_best()
def _internal_best(self) -> IndividualLike: """Return the individual with the best quality. To be overridden by subclasses. By default, returns the best individual of `self.container`.""" return self.container.best # Assume `self.container` is not empty def _verify_if_finished_iteration(self, batch_start_time: float) -> bool: """Emit the iteration event at an exact evaluation boundary. Callbacks can read the just-finished iteration counters. Reset those counters only after callbacks have run. Partial final batches leave their counters available in the result. """ # Verify if we finished an iteration if self.batch_size <= 0 or self._nb_evaluations % self.batch_size != 0: return False batch_elapsed: float = timer() - batch_start_time # Call callback functions for fn in self._callbacks.get("iteration"): fn(self, batch_elapsed) self._nb_suggestions_in_iteration = 0 self._nb_evaluations_in_iteration = 0 self._nb_updated_in_iteration = 0 return True def _tell_evaluation_result(self, individual: IndividualLike, result: Any, elapsed: float, verbose: bool, *, positional_sizes=()) -> bool: result_type = type(result) if result_type is tuple or result_type is list: size = len(result) if size not in (0, 2, 3): warnings.warn("Evaluation function returned malformatted results.") return False evaluated, measurements = individual, result elif result_type is Individual or isinstance(result, IndividualLike): if result is not individual: self._transfer_suggestion(individual, result) evaluated, measurements, size = result, (), 0 else: evaluated = individual size = _result_size(result) if size not in (0, 2, 3): warnings.warn("Evaluation function returned malformatted results.") return False try: measurements = tuple(result[i] for i in range(size)) except (IndexError, KeyError, TypeError, ValueError) as error: warnings.warn(f"Evaluation function returned malformatted results: {error}") return False try: if size in positional_sizes: self.tell(evaluated, *measurements, elapsed=elapsed, verbose=verbose) elif size == 2: self.tell(evaluated, fitness=measurements[0], features=measurements[1], elapsed=elapsed, verbose=verbose) elif size == 3: self.tell(evaluated, fitness=measurements[0], features=measurements[1], scores=measurements[2], elapsed=elapsed, verbose=verbose) else: self.tell(evaluated, elapsed=elapsed, verbose=verbose) except _InvalidEvaluation as error: if evaluated is not individual: self._forget_suggestion(evaluated) warnings.warn(f"Evaluation function returned malformatted results: {error}") return False return True def _forget_suggestion(self, individual: IndividualLike) -> None: if self._lineage_recorder is not None: self._lineage_recorder._result(individual, "failed", self.nb_evaluations + 1) ## @brief Transfer coordinator-side metadata when evaluation returns a new object. def _transfer_suggestion(self, individual: IndividualLike, evaluated: IndividualLike) -> None: if self._lineage_recorder is not None: self._lineage_recorder._transfer(individual, evaluated) def _start_fixed_batch(self, size: int) -> None: """Prepare a generation for an optimiser that opts into batch feedback.""" raise NotImplementedError def _receive_fixed_batch(self, records, verbose, batch_start_time) -> None: """Commit a generation in proposal order for an opted-in optimiser.""" raise NotImplementedError def _fixed_batch_plan(self, size, evaluate, packed): """Select the size and evaluator for the next fixed phase.""" return size, evaluate, packed
[docs] def optimise(self, evaluate: Callable, budget: Optional[int] = None, batch_mode: bool = True, executor: Optional[ExecutorLike] = None, send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10, verbose: bool = False) -> IndividualLike: """Manage evaluation and return the best candidate in the archive. A single-candidate evaluator can return a fitness and descriptor pair, that pair followed by named scores, or an evaluated individual. Return an empty sequence after updating the supplied object in place during in-process execution. A packed evaluator receives a list and returns one such result per candidate in the same order. Both the budget and batch size count candidates. A failed evaluation or malformed group consumes its dispatched slots. Results are consumed in completion order, which can affect archive-dependent searches. Iteration callbacks run after full batches. :param evaluate: Callable executed for each candidate or packed group. :param budget: Optional override of the configured budget. :param batch_mode: Wait for the current batch before asking for the next one. In steady state, refill available slots as work completes. :param executor: Evaluation executor. Defaults to in-process sequential execution. The caller manages any supplied executor's lifetime. :param send_several_suggestions_to_fn: Pass a list per evaluator call. :param max_nb_suggestions_per_call: Positive cap on a packed call. :param verbose: Emit archive validation warnings. :returns: The best retained candidate after the run. :raises RuntimeError: If no candidate is available to return. :raises ValueError: If the budget is missing or a positive run has an invalid batch size or packed-call limit. """ if self._fixed_batch_feedback and not batch_mode: raise ValueError("This optimiser requires batch_mode=True.") optimisation_start_time: float = timer() # Init budget self._check_archive_weights() limit = self.budget if budget is None else budget if limit is None: raise ValueError("`budget` must be provided.") self.budget = _evaluation_limit(limit, "budget", minimum=0, allow_infinity=True) if self.budget: _evaluation_limit(self.batch_size, "batch_size", minimum=1) group_limit = 1 if send_several_suggestions_to_fn: group_limit = _evaluation_limit(max_nb_suggestions_per_call, "max_nb_suggestions_per_call", minimum=1) _executor: ExecutorLike = executor if executor is not None else SequentialExecutor() # Call callback functions for fn in self._callbacks.get("started_optimisation"): fn(self) receive_feedback = self._tell_evaluation_result if (getattr(receive_feedback, "__func__", None) is QDAlgorithm._tell_evaluation_result and getattr(self.tell, "__func__", None) not in (QDAlgorithm.tell, AlgWrapper.tell)): positional_sizes = _positional_feedback_sizes(self.tell) if positional_sizes: receive_feedback = partial(receive_feedback, positional_sizes=positional_sizes) def optimisation_loop(budget_fn: Callable, evaluator=evaluate, packed=send_several_suggestions_to_fn): batch_start_time: float = timer() futures: MutableMapping[int, FutureLike] = {} individuals: MutableMapping[int, Sequence[IndividualLike]] = {} completed_groups = {} if self._fixed_batch_feedback else None submitted_evals = 0 pending_evals = 0 next_eval_id = 0 while True: available = min(budget_fn() - submitted_evals, self.batch_size - pending_evals) while available > 0: group_size = min(group_limit if packed else 1, available) inds = [self.ask() for _ in range(group_size)] individuals[next_eval_id] = tuple(inds) if packed: future = _executor.submit(_severalEvalsWrapper, next_eval_id, evaluator, inds) else: future = _executor.submit(_evalWrapper, next_eval_id, evaluator, inds[0]) futures[next_eval_id] = future next_eval_id += 1 pending_evals += group_size submitted_evals += group_size available -= group_size if not futures: break future = next(iter(futures.values())) if type(future) is not SequentialFuture: future = generic_as_completed(list(futures.values())) eval_id, elapsed, result, error = future.result() inds = individuals.pop(eval_id) del futures[eval_id] pending_evals -= len(inds) if error is not None: warnings.warn(f"Individual evaluation raised the following exception: {error} !") results = None elif not packed: results = (result,) elif type(result) is list or type(result) is tuple: results = tuple(result) if len(results) != len(inds): warnings.warn("Packed evaluation must return one result per candidate.") results = None elif _result_size(result) == len(inds): try: results = tuple(result[i] for i in range(len(inds))) except (IndexError, KeyError, TypeError, ValueError) as error: warnings.warn(f"Packed evaluation must return one result per candidate: {error}") results = None else: warnings.warn("Packed evaluation must return one result per candidate.") results = None if completed_groups is not None: completed_groups[eval_id] = [ (individual, None if results is None else results[index], elapsed) for index, individual in enumerate(inds) ] continue for index, individual in enumerate(inds): if results is None or not receive_feedback(individual, results[index], elapsed, verbose): self._forget_suggestion(individual) self._account_evaluations() if self._verify_if_finished_iteration(batch_start_time): batch_start_time = timer() if completed_groups is not None: records = [record for group in sorted(completed_groups) for record in completed_groups[group]] self._receive_fixed_batch(records, verbose, batch_start_time) if batch_mode: completed_evals = 0 while completed_evals < self.budget: budget_iteration = min(self.budget - completed_evals, self.batch_size) if self._fixed_batch_feedback: budget_iteration, evaluator, packed = self._fixed_batch_plan( budget_iteration, evaluate, send_several_suggestions_to_fn, ) self._start_fixed_batch(budget_iteration) optimisation_loop(lambda: budget_iteration, evaluator, packed) else: optimisation_loop(lambda: budget_iteration) completed_evals += budget_iteration else: def ret_budget(): return self.budget optimisation_loop(ret_budget) # Call callback functions optimisation_elapsed: float = timer() - optimisation_start_time for fn in self._callbacks.get("finished_optimisation"): fn(self, optimisation_elapsed) return self.best()
[docs] def add_callback(self, event: str, fn: Callable) -> None: """Attach a callable `fn` to the optimiser. `fn` will be called each time the event specified in `event` occurs. Parameters ---------- :param event: str The event triggering the callback. Can be either 'ask', 'tell', 'iteration' (when an iteration finishes) 'started_optimisation', or 'finished_optimisation'. :param fn: Callable The callback function called when the event specified in `event` occurs. """ _lst_events: Sequence[str] = ['ask', 'tell', 'iteration', 'started_optimisation', 'finished_optimisation'] if not event in _lst_events: raise ValueError(f"`event` can be either {','.join(_lst_events)}.") #self._callbacks.setdefault(event, []).append(fn) self._callbacks.add_callback(event, fn)
[docs] @registry.register class Lambda(QDAlgorithm): """Build an algorithm from user-supplied ask and optional tell functions. The ask function can return a genome or accept and return a base individual. A tell function receives the evaluated individual and the container's update flag. """ _ask_fn: Union[Callable[[], IndividualLike], Callable[[IndividualLike], IndividualLike]] _tell_fn: Optional[Callable] def __getstate__(self): odict = super().__getstate__() del odict['_ask_fn'] del odict['_tell_fn'] return odict def __init__(self, container: Container, budget: int, ask: Union[Callable[[], IndividualLike], Callable[[IndividualLike], IndividualLike]], tell: Optional[Callable] = None, **kwargs): super().__init__(container, budget, **kwargs) self._ask_fn = ask self._tell_fn = tell def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: """Internal ask method. Call the function specified by the `ask` argument of the constructor. This function can either take no argument (and must return a Sequence corresponding to the genome) or take a base (empty) `qdpy.base.IndividualLike` as sole argument (and must return a `qdpy.base.IndividualLike` with a filled out genome).""" sig = signature(self._ask_fn) if len(sig.parameters) == 0: base_ind[:] = self._ask_fn() # type: ignore return base_ind else: return self._ask_fn(base_ind) # type: ignore def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None: if self._tell_fn is not None: self._tell_fn(individual, added_to_container)
class AlgWithBatchSuggestions(QDAlgorithm): """Buffer candidates prepared in groups and return them one at a time. Subclasses fill the buffer in the batch-generation hook. This batch is an algorithm's suggestion buffer. The scheduler's batch size separately limits in-flight candidate evaluations. """ _batch_inds: List[IndividualLike] def __init__(self, container: Container, budget: int, **kwargs): super().__init__(container, budget, **kwargs) self._batch_inds = [] def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: if len(self._batch_inds) == 0: self._generate_batch_suggestions() #assert len(self._batch_inds) == self._batch_size, f"`self._generate_batch_suggestions` must populate `self._batch_inds` with `self.batch_size` IndividualLike objects." base_ind[:] = self._batch_inds.pop() return base_ind @abc.abstractmethod def _generate_batch_suggestions(self) -> None: """Compute all suggestions for the current batch and store them in `self._batch_inds`.""" raise NotImplementedError("Method `_generate_batch_suggestions` must be implemented by AlgWithBatchSuggestions subclasses.") #class EmitterManager(QDAlgorithmLike, Summarisable, Saveable, Copyable, CreatableFromConfig):
[docs] class AlgWrapper(QDAlgorithm): """Coordinate child optimisers under one ask/tell interface. The active child supplies each ask. Feedback follows the original proposer even if the active child changes before a result returns. With ``tell_all``, every child receives feedback and non-proposers receive copies. Child switching can warm-start the next child from its archive or the previous child's best candidate. An explicit container collects all reported candidates and supplies the result. Otherwise report the active child's archive, or the first populated child when the active archive is empty. """ algorithms: Sequence[QDAlgorithm] current_idx: int = 0 current: QDAlgorithm tell_container_when_switching: Union[bool, str] batch_mode: bool tell_all: bool def __init__(self, algorithms: Any, container: Optional[Container] = None, budget: Optional[int] = None, tell_container_when_switching: Union[bool, str] = False, name: Optional[str] = None, batch_mode: bool = False, tell_all: bool = False, **kwargs): if len(algorithms) == 0: raise ValueError("`algorithms` must not be empty.") # if isinstance(algorithms, Mapping): # self.algorithms = [] # for k,v in algorithms.items(): # for i in range(v): # self.algorithms.append(k) # else: # self.algorithms = list(algorithms) self.algorithms = list(algorithms) self.current_idx = 0 self.current = self.algorithms[self.current_idx] self.batch_mode = batch_mode self.tell_all = tell_all explicit_container = container is not None container = self.current.container if container is None else container budget_: int = sum((algo.budget for algo in self.algorithms)) if budget is None else budget kwargs.setdefault("optimisation_task", self.current.optimisation_task) kwargs.setdefault("nb_objectives", self.current._nb_objectives) super().__init__(container, budget_, **kwargs) if not explicit_container: del self.container if isinstance(tell_container_when_switching, str): if tell_container_when_switching not in ["True", "False", "only_best"]: raise ValueError("`tell_container_when_switching` must be a bool or one of these strings: 'True', 'False', 'only_best'.") self.tell_container_when_switching = tell_container_when_switching self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}" self.switch_to(0) def reinit(self) -> None: super().reinit() self._pending_emitters = {} def __getstate__(self): state = super().__getstate__() state["_pending_emitters"] = {} return state def __getattr__(self, attr): if attr in self.__dict__: return getattr(self, attr) if "current" not in self.__dict__: raise AttributeError if attr == "container" and not self.current.container: for child in self.algorithms: if child.container: return child.container return getattr(self.current, attr) def _check_archive_weights(self): if "container" in self.__dict__: super()._check_archive_weights() if any(child._fitness_weights != self._fitness_weights for child in self.algorithms): raise ValueError("An explicit wrapper archive requires matching objective weights on all children.") # def __get_saved_state__(self) -> Mapping[str, Any]: # """Return a dictionary containing the relevant information to save. Only include information from `self.algorithms`.""" # res = copy.deepcopy(self.current.__get_saved_state__()) # entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)} # return {**entries, **res} @abc.abstractmethod def next(self, verbose: bool = False) -> None: """Switch to the next algorithm in Sequence `self.algorithms`, if there is one.""" raise NotImplementedError("Method `_internal_ask` must be implemented by AlgWrapper subclasses.") # if self.current_idx < len(self.algorithms) - 1: # self.switch_to(self.current_idx + 1) # else: # self.switch_to(0)
[docs] def switch_to(self, idx: int, verbose: bool = False): """Switch to another algorithm of index `idx` in `self.algorithms`.""" assert idx < len(self.algorithms), f"`idx` must be < len(self.algorithms)." #print(f"SWITCH to {idx}") previous = self.current self.current_idx = idx self.current = self.algorithms[idx] if (isinstance(self.tell_container_when_switching, bool) and self.tell_container_when_switching) or \ self.tell_container_when_switching == "True": self.current.tell_container_entries() elif self.tell_container_when_switching == "only_best": try: self.current.tell(previous.best(), verbose=verbose) # Exception when no individual is present except Exception: pass
def best(self) -> IndividualLike: if "container" in self.__dict__: return super().best() if self.current.container: return self.current.best() for child in self.algorithms: if child.container: return child.best() return self.current.best() # def ask(self) -> IndividualLike: # ind = self.current.ask() # self.next() # return ind def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: if self.batch_mode: batch_size = self.current.batch_size if np.isinf(batch_size): batch_size = self.batch_size if np.isinf(batch_size): batch_size = 1 if self.current.nb_suggestions % batch_size == 0: self.next() else: self.next() ind = self.current.ask() self._pending_emitters[id(ind)] = (ind, self.current) return ind def _forget_suggestion(self, individual: IndividualLike) -> None: _, emitter = self._pending_emitters.pop(id(individual), (individual, None)) if emitter is not None: emitter._forget_suggestion(individual) ## @brief Move proposer ownership to an evaluator's returned individual. # @param individual Original ask object retained by the scheduler. # @param evaluated Replacement object returned by the evaluator. # @details Propagate the transfer through nested wrappers. Tracking # uses object identity, so equal genomes can have distinct owners. def _transfer_suggestion(self, individual: IndividualLike, evaluated: IndividualLike) -> None: _, emitter = self._pending_emitters.pop(id(individual), (individual, None)) if emitter is not None: self._pending_emitters[id(evaluated)] = (evaluated, emitter) emitter._transfer_suggestion(individual, evaluated)
[docs] def tell(self, individual: IndividualLike, fitness: Optional[Any] = None, features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None, elapsed: Optional[float] = None, verbose: bool = False, tell_container = True) -> bool: """Deliver an evaluation to the proposer, or to every child in tell-all mode. A manually supplied candidate with no pending ask goes to the active child. Forward the optional evaluation arguments and update permission to the child. The wrapper accounts for one evaluation and reports an update if any child reports one. """ self._check_archive_weights() _, emitter = self._pending_emitters.get(id(individual), (individual, self.current)) recipients = self.algorithms if self.tell_all else (emitter,) report_archive = self.__dict__.get("container") before = report_archive.nb_added if report_archive is not None else None added = False for child in recipients: candidate = individual if child is emitter else copy.deepcopy(individual) added |= child.tell(candidate, fitness, features, scores, elapsed, verbose=verbose, tell_container=tell_container) self._pending_emitters.pop(id(individual), None) if report_archive is not None: if tell_container and all(child.container is not report_archive for child in recipients): report = copy.deepcopy(individual) self._apply_evaluation(report, emitter.container.get_ind_fitness(individual), emitter.container.get_ind_features(individual), None, None) self._offer_to_container(report, verbose) added = report_archive.nb_added > before self._tell_after_container_update(individual, added) return added
# def optimise(self, evaluate: Callable, budget: Optional[int] = None, # batch_mode: bool = True, executor: Optional[ExecutorLike] = None, # send_several_suggestions_to_fn: bool = False) -> IndividualLike: # for _ in range(self.current_idx, len(self.algorithms)): # try: # res = self.current.optimise(evaluate, budget, batch_mode, executor, send_several_suggestions_to_fn) # except Exception as e: # warnings.warn(f"Optimisation failed with algorithm '{self.current.name}': {e}") # traceback.print_exc() # self.next() # return res # def add_callback(self, event: str, fn: Callable) -> None: # for a in self.algorithms: # a.add_callback(event, fn)
[docs] @registry.register class AlternatingAlgWrapper(AlgWrapper): """Cycle through child optimisers in order when the wrapper switches.""" def next(self, verbose: bool = False) -> None: """Switch to the next algorithm in Sequence `self.algorithms`, if there is one.""" if self.current_idx < len(self.algorithms) - 1: self.switch_to(self.current_idx + 1, verbose) else: self.switch_to(0, verbose)
[docs] @registry.register class SqAlgWrapper(AlgWrapper): """Advance to the next child when the active child has issued its budget of suggestions.""" def next(self, verbose: bool = False) -> None: """Switch to the next algorithm in Sequence `self.algorithms`, if there is one.""" if self.current.nb_suggestions >= self.current.budget: if self.current_idx < len(self.algorithms) - 1: self.switch_to(self.current_idx + 1, verbose)
[docs] @registry.register class Sq(QDAlgorithmLike, Summarisable, Saveable, Copyable, CreatableFromConfig): """Run complete child optimisations in a fixed sequence. Switching can feed the next child from its archive or the previous child's best candidate. A stage failure emits a warning and the next stage can still run. When every stage fails, the last error is raised. """ algorithms: Sequence[QDAlgorithm] current_idx: int = 0 current: QDAlgorithm tell_container_when_switching: Union[bool, str] def __init__(self, algorithms: Any, tell_container_when_switching: Union[bool, str] = True, name: Optional[str] = None, **kwargs): if len(algorithms) == 0: raise ValueError("`algorithms` must not be empty.") self.algorithms = list(algorithms) self.current_idx = 0 self.current = self.algorithms[self.current_idx] if isinstance(tell_container_when_switching, str): if tell_container_when_switching not in ["True", "False", "only_best"]: raise ValueError("`tell_container_when_switching` must be a bool or one of these strings: 'True', 'False', 'only_best'.") self.tell_container_when_switching = tell_container_when_switching self.name = name if name is not None else f"{self.__class__.__name__}-{id(self)}" #self.budget = sum((algo.budget for algo in self.algorithms)) self.switch_to(0) def __getattr__(self, attr): if attr in self.__dict__: return getattr(self, attr) if "current" not in self.__dict__: raise AttributeError return getattr(self.current, attr) def __get_saved_state__(self) -> Mapping[str, Any]: """Return a dictionary containing the relevant information to save. Only include information from `self.algorithms`.""" res = copy.deepcopy(self.current.__get_saved_state__()) entries = {k:v for k,v in inspect.getmembers(self) if not k.startswith('_') and not inspect.ismethod(v)} return {**entries, **res} def next(self, verbose: bool = False) -> None: """Switch to the next algorithm in Sequence `self.algorithms`, if there is one.""" if self.current_idx < len(self.algorithms) - 1: self.switch_to(self.current_idx + 1, verbose) def switch_to(self, idx: int, verbose: bool = False): """Switch to another algorithm of index `idx` in `self.algorithms`.""" assert idx < len(self.algorithms), f"`idx` must be < len(self.algorithms)." previous = self.current self.current_idx = idx self.current = self.algorithms[idx] if (isinstance(self.tell_container_when_switching, bool) and self.tell_container_when_switching) or \ self.tell_container_when_switching == "True": self.current.tell_container_entries() elif self.tell_container_when_switching == "only_best": try: self.current.tell(previous.best(), verbose=verbose) # Exception when no individual is present except Exception: pass def best(self) -> IndividualLike: return self.current.best() def ask(self) -> IndividualLike: return self.current.ask() def tell(self, individual: IndividualLike, fitness: Optional[Any] = None, features: Optional[FeaturesLike] = None, scores: Optional[ScoresDictLike] = None, elapsed: Optional[float] = None, verbose: bool = False) -> bool: return self.current.tell(individual, fitness, features, scores, elapsed, verbose=verbose) def optimise(self, evaluate: Callable, budget: Optional[int] = None, batch_mode: bool = True, executor: Optional[ExecutorLike] = None, send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10, verbose: bool = False) -> IndividualLike: res = None last_failure = None for _ in range(self.current_idx, len(self.algorithms)): try: res = self.current.optimise(evaluate, budget, batch_mode, executor, send_several_suggestions_to_fn = send_several_suggestions_to_fn, max_nb_suggestions_per_call = max_nb_suggestions_per_call, verbose = verbose) except Exception as e: warnings.warn(f"Optimisation failed with algorithm '{self.current.name}': {e}") last_failure = e self.next() if res is None: raise last_failure return res def add_callback(self, event: str, fn: Callable) -> None: for a in self.algorithms: a.add_callback(event, fn)
[docs] @registry.register class FromArchive(QDAlgorithm): """Use genomes from trusted current result snapshots as suggestions. Read the saved container entries in file order. The initial budget is the number of loaded genomes. Each ask copies a reference genome into a new base candidate and leaves fitness and descriptors to the next evaluation. Reinitialisation rewinds the cursor. """ reference_data_files: List[str] reference_inds_idx: int = 0 def __init__(self, container: Container, reference_data_files: List[str], **kwargs): self.reference_data_files = [os.path.expanduser(x) for x in reference_data_files] self.reference_inds: List[Any] = [] for reference_data_file in self.reference_data_files: reference_data = tools.open_pickle_file(reference_data_file) self.reference_inds += list(reference_data['container']) budget = len(self.reference_inds) super().__init__(container, budget, **kwargs) def reinit(self) -> None: super().reinit() self.reference_inds_idx = 0 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: base_ind[:] = self.reference_inds[self.reference_inds_idx] self.reference_inds_idx += 1 return base_ind
# MODELINE "{{{1 # vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8 # vim:foldmethod=marker