Source code for qdpy.algorithms.evolution

#    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 Evolutionary operators, bounded mutation, and the optional CMA-ES backend.

"""A collection of all algorithms based on Evolutionary algorithms."""

__all__ = ["Evolution", "RandomSearchMutPolyBounded", "MutPolyBounded", "CuriosityMutPolyBounded", "RandomSearchMutGaussian", "MutGaussian", "CMAES"]

########### IMPORTS ########### {{{1

from timeit import default_timer as timer
from typing import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
import warnings
import numpy as np
import copy
from functools import partial
import random
import sys
from inspect import signature


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


########### EVOLUTION CLASSES ########### {{{1

[docs] class Evolution(QDAlgorithm): """Build an ask/tell algorithm from selection and variation callables. Supply either ``select`` or ``select_or_initialise``. Selection receives the archive. The combined callable can also receive the empty base candidate and reports whether variation should follow. Selected candidates are deep-copied by default so variation can mutate safely. The optional tell hook receives the evaluated individual and the archive's update flag. """ _select_fn: Optional[Callable] _select_or_initialise_fn: Optional[Callable] _select_or_initialise_fn_nb_parameters: int _vary_fn: Callable[[IndividualLike], IndividualLike] _tell_fn: Optional[Callable] deepcopy_on_selection: bool _lineage_operator = None def __getstate__(self): odict = super().__getstate__() del odict['_select_fn'] del odict['_select_or_initialise_fn'] del odict['_vary_fn'] del odict['_tell_fn'] return odict def __init__(self, container: Container, budget: int, vary: Callable[[IndividualLike], IndividualLike], select: Optional[Callable[[Container], IndividualLike]] = None, select_or_initialise: Optional[Callable[[Container], Tuple[IndividualLike, bool]]] = None, tell: Optional[Callable] = None, deepcopy_on_selection: bool = True, **kwargs): super().__init__(container, budget, **kwargs) if select is not None and select_or_initialise is not None: raise ValueError("Only one of `select` and `select_or_initialise` can be provided.") self._select_fn = select self._select_or_initialise_fn = select_or_initialise self._vary_fn = vary # type: ignore self._tell_fn = tell # type: ignore self.deepcopy_on_selection = deepcopy_on_selection # Find the number of parameters of self._select_or_initialise_fn if self._select_or_initialise_fn is not None: sig = signature(self._select_or_initialise_fn) self._select_or_initialise_fn_nb_parameters = len(sig.parameters) if self._select_or_initialise_fn_nb_parameters == 0: raise ValueError("`select_or_initialise` function must take at least one parameter.") ## @brief Convert a selection result into a private offspring or initial genome. # @param base_ind Empty candidate supplied to the ask. # @return Candidate whose genome will be evaluated. # @details Copy archived parents before in-place variation by default. # Preserve the callback result convention for both a candidate and # a sequence containing one candidate. def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: # Select the next individual perform_variation: bool = False if self._select_fn is not None: selected: IndividualLike = self._select_fn(self.container) if self.deepcopy_on_selection: selected = _copy_individual(selected) if type(selected) is not Individual and not isinstance(selected, IndividualLike): if isinstance(selected, Sequence) and isinstance(selected[0], IndividualLike): selected = selected[0] else: raise RuntimeError("`select` function returned an unknown type of individual.") perform_variation = True elif self._select_or_initialise_fn is not None: if self._select_or_initialise_fn_nb_parameters == 1: selected, perform_variation = self._select_or_initialise_fn(self.container) elif self._select_or_initialise_fn_nb_parameters >= 2: selected, perform_variation = self._select_or_initialise_fn(self.container, base_ind) if perform_variation and self._lineage_recorder is not None and self._lineage_operator is not None: self._lineage_recorder._parentage(self._lineage_operator, (selected,)) # Slice assignment copies a flat genome of immutable floats into a built-in candidate. if self.deepcopy_on_selection and ( perform_variation or type(base_ind) is not Individual or type(selected) is not list or any(type(gene) is not float for gene in selected) ): selected = _copy_individual(selected) if perform_variation and type(selected) is not Individual and not isinstance(selected, IndividualLike): raise RuntimeError("`select_or_initialise` function returned an unknown type of individual.") else: raise RuntimeError("Either `select` or `select_or_initialise` must be provided.") # Vary the suggestion if perform_variation: varied = self._vary_fn(selected) # type: ignore if type(varied) is not Individual and not isinstance(varied, IndividualLike): if is_iterable(varied) and isinstance(varied[0], IndividualLike): varied = varied[0] elif is_iterable(varied): pass # Try anyway else: raise RuntimeError("`vary` function returned an unknown type of individual.") base_ind[:] = varied else: return varied else: if type(selected) is Individual or (type(selected) is not list and isinstance(selected, IndividualLike)): return selected else: base_ind[:] = selected # Reset fitness and features base_ind.reset() return base_ind 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)
[docs] @registry.register class RandomSearchMutPolyBounded(Evolution): """Alternate uniform initialisation and bounded polynomial mutation. Initialisation samples each coordinate independently from ``ind_domain``. Mutation selects an archived genome, copies it, and applies Deb's bounded polynomial operator. :param sel_pb: Probability of selecting for variation in a nonempty archive. :param init_pb: Probability of uniform initialisation in a nonempty archive. :param mut_pb: Independent mutation probability per coordinate. :param eta: Polynomial distribution index. Larger values concentrate changes near the parent. :param ind_domain: Common lower and upper genome coordinate bounds. :param parent_selector: Callable drawing one archived parent. Defaults to a uniform draw. """ _lineage_operator = "polynomial" ind_domain: DomainLike sel_pb: float init_pb: float mut_pb: float eta: float def __init__(self, container: Container, budget: int, dimension: int, ind_domain: DomainLike = (0., 1.), sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., *, parent_selector=tools.sel_random, **kwargs): self.ind_domain = ind_domain self.sel_pb = sel_pb self.init_pb = init_pb self.mut_pb = mut_pb self.eta = eta def init_fn(base_ind): return [random.uniform(ind_domain[0], ind_domain[1]) for _ in range(self.dimension)] select_or_initialise = partial(tools.sel_or_init, sel_fn = parent_selector, sel_pb = sel_pb, init_fn = init_fn, init_pb = init_pb) def vary(ind): return tools.mut_polynomial_bounded(ind, low=self.ind_domain[0], up=self.ind_domain[1], eta=self.eta, mut_pb=self.mut_pb) super().__init__(container, budget, dimension=dimension, # type: ignore select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
[docs] @registry.register class MutPolyBounded(RandomSearchMutPolyBounded): """Use bounded polynomial mutation after the archive has a parent to select.""" def __init__(self, container: Container, budget: int, dimension: int, ind_domain: DomainLike = (0., 1.), mut_pb: float = 0.2, eta: float = 20., **kwargs): super().__init__(container, budget, dimension=dimension, ind_domain=ind_domain, sel_pb=1.0, init_pb=0.0, mut_pb=mut_pb, eta=eta, **kwargs)
## @brief Select parents by curiosity and update their scores on archive feedback.
[docs] @registry.register class CuriosityMutPolyBounded(Evolution): """Use named curiosity scores to select parents for polynomial mutation. Update the proposing parent's score by ``reward`` when the archive reports an update, or subtract ``penalty`` on rejection. Uniform initialisation has no parent to credit. Feedback is applied in tell order on the coordinator, including when workers return a new object. :param score_name: Name of the curiosity score stored on parents. :param default_score: Initial curiosity for an unscored parent. :param reward: Nonnegative credit for an archive update. :param penalty: Nonnegative amount to subtract on rejection. :param init_pb: Probability of uniform initialisation with a nonempty archive. :param mut_pb: Independent mutation probability per coordinate. :param eta: Distribution index for bounded polynomial mutation. :param ind_domain: Common lower and upper genome bounds. """ def __init__(self, container: Container, budget: int, dimension: int, ind_domain: DomainLike = (0., 1.), *, score_name: str = "curiosity", default_score: float = 0.01, reward: float = 1., penalty: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., **kwargs): if not all(math.isfinite(value) for value in (default_score, reward, penalty)): raise ValueError("Curiosity scores and update amounts must be finite.") if reward < 0 or penalty < 0 or not 0 <= init_pb <= 1: raise ValueError("Use nonnegative curiosity update amounts and an init_pb in [0, 1].") self.score_name = score_name self.default_score = default_score self.reward = reward self.penalty = penalty self._selected_parent = None def select(collection): parent = tools.sel_roulette_score(collection, score_name, default_score) if type(parent) is Individual and all(type(gene) in (float, int) for gene in parent): child = Individual(parent) else: child = copy.deepcopy(parent) child.reset() self._selected_parent = parent return child def initialise(_): return [random.uniform(*ind_domain) for _ in range(dimension)] select_or_initialise = partial(tools.sel_or_init, sel_fn=select, init_fn=initialise, sel_pb=1.0 - init_pb, init_pb=init_pb) vary = partial(tools.mut_polynomial_bounded, low=ind_domain[0], up=ind_domain[1], eta=eta, mut_pb=mut_pb) super().__init__(container, budget, vary=vary, dimension=dimension, select_or_initialise=select_or_initialise, deepcopy_on_selection=False, **kwargs) ## @brief Drop pending parent credit when restarting the optimiser. def reinit(self): super().reinit() self._pending_parents = {} ## @brief Keep lineage on the coordinator instead of copying it into offspring. def _internal_ask(self, base_ind): try: child = super()._internal_ask(base_ind) if self._selected_parent is not None: self._pending_parents[id(child)] = (child, self._selected_parent) if self._lineage_recorder is not None: self._lineage_recorder._parentage("curiosity_polynomial", (self._selected_parent,)) return child finally: self._selected_parent = None ## @brief Transfer pending curiosity credit to a worker's returned candidate. def _transfer_suggestion(self, individual, evaluated): super()._transfer_suggestion(individual, evaluated) record = self._pending_parents.pop(id(individual), None) if record is not None: self._pending_parents[id(evaluated)] = (evaluated, record[1]) ## @brief Remove pending credit for a failed evaluation. def _forget_suggestion(self, individual): super()._forget_suggestion(individual) self._pending_parents.pop(id(individual), None) ## @brief Apply curiosity credit once when the corresponding offspring is told. def _internal_tell(self, individual, added_to_container, xattr=None): record = self._pending_parents.pop(id(individual), None) if record is not None: parent = record[1] previous = parent.scores.get(self.score_name, self.default_score) parent.scores[self.score_name] = previous + (self.reward if added_to_container else -self.penalty) ## @brief Omit unevaluated offspring from result snapshots. def __getstate__(self): state = super().__getstate__() state["_pending_parents"] = {} state["_selected_parent"] = None return state
# TODO refactor: redundant code with RandomSearchMutPolyBounded
[docs] @registry.register class DGRandomSearchMutPolyBounded(Evolution): """Use uniform initialisation and grid-based roulette selection. Selected genomes are varied by bounded polynomial mutation. Use a Grid as the archive because the selection operator draws from an occupied cell. """ ind_domain: DomainLike sel_pb: float init_pb: float mut_pb: float eta: float def __init__(self, container: Container, budget: int, dimension: int, ind_domain: DomainLike = (0., 1.), sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., **kwargs): self.ind_domain = ind_domain self.sel_pb = sel_pb self.init_pb = init_pb self.mut_pb = mut_pb self.eta = eta def init_fn(base_ind): return [random.uniform(ind_domain[0], ind_domain[1]) for _ in range(self.dimension)] select_or_initialise = partial(tools.sel_or_init, sel_fn = tools.sel_grid_roulette, sel_pb = sel_pb, init_fn = init_fn, init_pb = init_pb) def vary(ind): return tools.mut_polynomial_bounded(ind, low=self.ind_domain[0], up=self.ind_domain[1], eta=self.eta, mut_pb=self.mut_pb) super().__init__(container, budget, dimension=dimension, # type: ignore select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
[docs] @registry.register class RandomSearchMutGaussian(Evolution): """Initialise and mutate real-valued genomes with a Gaussian. The mean and standard deviation are ``mu`` and ``sigma``. Mutation adds a Gaussian draw to each selected coordinate with probability ``mut_pb``. An explicit ``ind_domain`` clips both initialisation and mutation. The default search is unbounded. """ _lineage_operator = "gaussian" sel_pb: float init_pb: float mut_pb: float mu: float sigma: float def __init__(self, container: Container, budget: int, dimension: int, sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, mu: float = 0., sigma: float = 1.0, *, ind_domain: Optional[DomainLike] = None, **kwargs): self.sel_pb = sel_pb self.init_pb = init_pb self.mut_pb = mut_pb self.mu = mu self.sigma = sigma def init_fn(base_ind): values = [random.normalvariate(self.mu, self.sigma) for _ in range(self.dimension)] if ind_domain is not None: return np.clip(values, ind_domain[0], ind_domain[1]) return values select_or_initialise = partial(tools.sel_or_init, sel_fn = tools.sel_random, sel_pb = sel_pb, init_fn = init_fn, init_pb = init_pb) def vary(ind): return tools.mut_gaussian(ind, mu=self.mu, sigma=self.sigma, mut_pb=self.mut_pb, bounds=ind_domain) super().__init__(container, budget, dimension=dimension, # type: ignore select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
[docs] @registry.register class MutGaussian(RandomSearchMutGaussian): """Use Gaussian mutation after the archive has a parent to select.""" def __init__(self, container: Container, budget: int, dimension: int, mut_pb: float = 0.2, mu: float = 0., sigma: float = 1.0, **kwargs): super().__init__(container, budget, dimension=dimension, sel_pb=1.0, init_pb=0.0, mut_pb=mut_pb, mu=mu, sigma=sigma, **kwargs)
try: import cma @registry.register class CMAES(QDAlgorithm): """Adapt a Gaussian search distribution with pycma. Install the ``cma`` extra. Ordinary CMA-ES accepts exactly one fitness objective. Negate the weighted objective to provide pycma with a loss to minimise. Feedback is buffered until the backend population size is reached. :param dimension: Genome length. :param ind_domain: Optional common bounds for all coordinates. :param sigma0: Initial search standard deviation. :param separable_cma: Use diagonal covariance in the backend. :param ignore_if_not_added_to_container: Exclude nonaccepted archive feedback from the backend's population. """ ind_domain: Optional[DomainLike] sigma0: float es: Any _pop_inds: MutableSequence[IndividualLike] _pop_fitness_vals: MutableSequence[Any] _requires_single_objective = True def __init__(self, container: Container, budget: int, dimension: int, ind_domain: Optional[DomainLike] = None, sigma0: float = 1.0, separable_cma: bool = False, ignore_if_not_added_to_container: bool = False, **kwargs): self.sigma0 = sigma0 self.ind_domain = ind_domain self.separable_cma = separable_cma self.ignore_if_not_added_to_container = ignore_if_not_added_to_container super().__init__(container, budget, dimension=dimension, **kwargs) def reinit(self) -> None: """Reset counters and create a new pycma strategy centred at the zero genome.""" super().reinit() if self._requires_single_objective and self._nb_objectives != 1: raise ValueError("CMA-ES requires exactly one fitness objective.") self._opts: MutableMapping[str, Any] = {} if self.ind_domain is not None: self._opts['bounds'] = list(self.ind_domain) if self._batch_size is not None: self._opts['popsize'] = self._batch_size self._opts['seed'] = random.randint(0, 2**32-1) self._opts['verbose'] = -9 if self.separable_cma: self._opts['CMA_diagonal'] = True self.es = cma.CMAEvolutionStrategy([0.] * self.dimension, self.sigma0, self._opts) # type: ignore self._pop_inds = [] self._pop_fitness_vals = [] if self._batch_size is None: self._batch_size = self.es.popsize def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: base_ind[:] = self.es.ask(1)[0] return base_ind def _weighted_fitness(self, fitness: FitnessLike) -> Tuple[float, ...]: return tuple(value * weight for value, weight in zip(fitness.values, self._fitness_weights)) ## @brief Buffer one numeric loss per accepted backend candidate. # @param individual Evaluated candidate. # @param added_to_container Archive update result. # @param xattr Pre-admission feedback metadata. # @details The loss sign is independent of the archive's raw values. # Successful pycma feedback consumes the buffered population. def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None: if self.ignore_if_not_added_to_container and not added_to_container: return self._pop_inds += [individual] fitness = self.container.get_ind_fitness(individual) self._pop_fitness_vals.append(-self._weighted_fitness(fitness)[0]) if len(self._pop_inds) >= self.es.popsize: try: self.es.tell(self._pop_inds, self._pop_fitness_vals) except RuntimeError: pass else: self._pop_inds.clear() self._pop_fitness_vals.clear() except ImportError: @registry.register # type: ignore class CMAES(QDAlgorithm): # type: ignore def __init__(self, *args, **kwargs): raise NotImplementedError("`CMAES` needs the 'cma' package to be installed and importable.") def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike: raise NotImplementedError("`CMAES` needs the 'cma' package to be installed and importable.") # MODELINE "{{{1 # vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8 # vim:foldmethod=marker