19"""A collection of all algorithms based on Evolutionary algorithms."""
21__all__ = [
"Evolution",
"RandomSearchMutPolyBounded",
"MutPolyBounded",
"CuriosityMutPolyBounded",
"RandomSearchMutGaussian",
"MutGaussian",
"CMAES"]
25from timeit
import default_timer
as timer
26from typing
import Optional, Tuple, List, Iterable, Iterator, Any, TypeVar, Generic, Union, Sequence, MutableSet, MutableSequence, Type, Callable, Generator, Mapping, MutableMapping, overload
30from functools
import partial
33from inspect
import signature
48 """Build an ask/tell algorithm from selection and variation callables.
50 Supply either ``select`` or ``select_or_initialise``. Selection
51 receives the archive. The combined callable can also receive the
52 empty base candidate and reports whether variation should follow.
53 Selected candidates are deep-copied by default so variation can
54 mutate safely. The optional tell hook receives the evaluated
55 individual and the archive's update flag.
57 _select_fn: Optional[Callable]
58 _select_or_initialise_fn: Optional[Callable]
59 _select_or_initialise_fn_nb_parameters: int
60 _vary_fn: Callable[[IndividualLike], IndividualLike]
61 _tell_fn: Optional[Callable]
62 deepcopy_on_selection: bool
63 _lineage_operator =
None
65 def __getstate__(self):
66 odict = super().__getstate__()
67 del odict[
'_select_fn']
68 del odict[
'_select_or_initialise_fn']
73 def __init__(self, container: Container, budget: int,
74 vary: Callable[[IndividualLike], IndividualLike],
75 select: Optional[Callable[[Container], IndividualLike]] =
None,
76 select_or_initialise: Optional[Callable[[Container], Tuple[IndividualLike, bool]]] =
None,
77 tell: Optional[Callable] =
None,
78 deepcopy_on_selection: bool =
True, **kwargs):
79 super().__init__(container, budget, **kwargs)
80 if select
is not None and select_or_initialise
is not None:
81 raise ValueError(
"Only one of `select` and `select_or_initialise` can be provided.")
92 raise ValueError(
"`select_or_initialise` function must take at least one parameter.")
102 perform_variation: bool =
False
106 selected = _copy_individual(selected)
107 if type(selected)
is not Individual
and not isinstance(selected, IndividualLike):
108 if isinstance(selected, Sequence)
and isinstance(selected[0], IndividualLike):
109 selected = selected[0]
111 raise RuntimeError(
"`select` function returned an unknown type of individual.")
112 perform_variation =
True
122 perform_variation
or type(base_ind)
is not Individual
or type(selected)
is not list
123 or any(type(gene)
is not float
for gene
in selected)
125 selected = _copy_individual(selected)
126 if perform_variation
and type(selected)
is not Individual
and not isinstance(selected, IndividualLike):
127 raise RuntimeError(
"`select_or_initialise` function returned an unknown type of individual.")
129 raise RuntimeError(
"Either `select` or `select_or_initialise` must be provided.")
132 if perform_variation:
134 if type(varied)
is not Individual
and not isinstance(varied, IndividualLike):
135 if is_iterable(varied)
and isinstance(varied[0], IndividualLike):
137 elif is_iterable(varied):
140 raise RuntimeError(
"`vary` function returned an unknown type of individual.")
145 if type(selected)
is Individual
or (type(selected)
is not list
and isinstance(selected, IndividualLike)):
148 base_ind[:] = selected
153 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) ->
None:
155 self.
_tell_fn(individual, added_to_container)
162 """Alternate uniform initialisation and bounded polynomial mutation.
164 Initialisation samples each coordinate independently from
165 ``ind_domain``. Mutation selects an archived genome, copies it,
166 and applies Deb's bounded polynomial operator.
168 :param sel_pb: Probability of selecting for variation in a nonempty archive.
169 :param init_pb: Probability of uniform initialisation in a nonempty archive.
170 :param mut_pb: Independent mutation probability per coordinate.
171 :param eta: Polynomial distribution index. Larger values concentrate
172 changes near the parent.
173 :param ind_domain: Common lower and upper genome coordinate bounds.
174 :param parent_selector: Callable drawing one archived parent. Defaults to a uniform draw.
176 _lineage_operator =
"polynomial"
177 ind_domain: DomainLike
183 def __init__(self, container: Container, budget: int,
184 dimension: int, ind_domain: DomainLike = (0., 1.),
185 sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20.,
186 *, parent_selector=tools.sel_random, **kwargs):
193 def init_fn(base_ind):
194 return [random.uniform(ind_domain[0], ind_domain[1])
for _
in range(self.
dimension)]
195 select_or_initialise = partial(tools.sel_or_init,
196 sel_fn = parent_selector,
203 super().__init__(container, budget, dimension=dimension,
204 select_or_initialise=select_or_initialise, vary=vary, **kwargs)
209 """Use bounded polynomial mutation after the archive has a parent to select."""
210 def __init__(self, container: Container, budget: int,
211 dimension: int, ind_domain: DomainLike = (0., 1.),
212 mut_pb: float = 0.2, eta: float = 20., **kwargs):
213 super().__init__(container, budget, dimension=dimension,
214 ind_domain=ind_domain,
215 sel_pb=1.0, init_pb=0.0,
216 mut_pb=mut_pb, eta=eta, **kwargs)
222 """Use named curiosity scores to select parents for polynomial mutation.
224 Update the proposing parent's score by ``reward`` when the archive
225 reports an update, or subtract ``penalty`` on rejection. Uniform
226 initialisation has no parent to credit. Feedback is applied in tell
227 order on the coordinator, including when workers return a new object.
229 :param score_name: Name of the curiosity score stored on parents.
230 :param default_score: Initial curiosity for an unscored parent.
231 :param reward: Nonnegative credit for an archive update.
232 :param penalty: Nonnegative amount to subtract on rejection.
233 :param init_pb: Probability of uniform initialisation with a nonempty archive.
234 :param mut_pb: Independent mutation probability per coordinate.
235 :param eta: Distribution index for bounded polynomial mutation.
236 :param ind_domain: Common lower and upper genome bounds.
239 def __init__(self, container: Container, budget: int, dimension: int,
240 ind_domain: DomainLike = (0., 1.), *, score_name: str =
"curiosity",
241 default_score: float = 0.01, reward: float = 1., penalty: float = 0.5,
242 init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., **kwargs):
243 if not all(math.isfinite(value)
for value
in (default_score, reward, penalty)):
244 raise ValueError(
"Curiosity scores and update amounts must be finite.")
245 if reward < 0
or penalty < 0
or not 0 <= init_pb <= 1:
246 raise ValueError(
"Use nonnegative curiosity update amounts and an init_pb in [0, 1].")
253 def select(collection):
254 parent = tools.sel_roulette_score(collection, score_name, default_score)
255 if type(parent)
is Individual
and all(type(gene)
in (float, int)
for gene
in parent):
258 child = copy.deepcopy(parent)
264 return [random.uniform(*ind_domain)
for _
in range(dimension)]
266 select_or_initialise = partial(tools.sel_or_init, sel_fn=select, init_fn=initialise,
267 sel_pb=1.0 - init_pb, init_pb=init_pb)
268 vary = partial(tools.mut_polynomial_bounded, low=ind_domain[0], up=ind_domain[1],
269 eta=eta, mut_pb=mut_pb)
270 super().__init__(container, budget, vary=vary, dimension=dimension,
271 select_or_initialise=select_or_initialise, deepcopy_on_selection=
False, **kwargs)
294 if record
is not None:
305 if record
is not None:
313 state[
"_pending_parents"] = {}
314 state[
"_selected_parent"] =
None
321 """Use uniform initialisation and grid-based roulette selection.
323 Selected genomes are varied by bounded polynomial mutation.
324 Use a Grid as the archive because the selection operator draws
325 from an occupied cell.
327 ind_domain: DomainLike
333 def __init__(self, container: Container, budget: int,
334 dimension: int, ind_domain: DomainLike = (0., 1.),
335 sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20.,
343 def init_fn(base_ind):
344 return [random.uniform(ind_domain[0], ind_domain[1])
for _
in range(self.
dimension)]
345 select_or_initialise = partial(tools.sel_or_init,
346 sel_fn = tools.sel_grid_roulette,
353 super().__init__(container, budget, dimension=dimension,
354 select_or_initialise=select_or_initialise, vary=vary, **kwargs)
359 """Initialise and mutate real-valued genomes with a Gaussian.
361 The mean and standard deviation are ``mu`` and ``sigma``.
362 Mutation adds a Gaussian draw to each selected coordinate with
363 probability ``mut_pb``. An explicit ``ind_domain`` clips both
364 initialisation and mutation. The default search is unbounded.
366 _lineage_operator =
"gaussian"
373 def __init__(self, container: Container, budget: int,
374 dimension: int, sel_pb: float = 0.5, init_pb: float = 0.5,
375 mut_pb: float = 0.2, mu: float = 0., sigma: float = 1.0, *,
376 ind_domain: Optional[DomainLike] =
None, **kwargs):
383 def init_fn(base_ind):
384 values = [random.normalvariate(self.
mu, self.
sigma)
for _
in range(self.
dimension)]
385 if ind_domain
is not None:
386 return np.clip(values, ind_domain[0], ind_domain[1])
388 select_or_initialise = partial(tools.sel_or_init,
389 sel_fn = tools.sel_random,
394 return tools.mut_gaussian(ind, mu=self.
mu, sigma=self.
sigma, mut_pb=self.
mut_pb, bounds=ind_domain)
396 super().__init__(container, budget, dimension=dimension,
397 select_or_initialise=select_or_initialise, vary=vary, **kwargs)
402 """Use Gaussian mutation after the archive has a parent to select."""
403 def __init__(self, container: Container, budget: int,
404 dimension: int, mut_pb: float = 0.2,
405 mu: float = 0., sigma: float = 1.0, **kwargs):
406 super().__init__(container, budget, dimension=dimension,
407 sel_pb=1.0, init_pb=0.0,
408 mut_pb=mut_pb, mu=mu, sigma=sigma, **kwargs)
416 """Adapt a Gaussian search distribution with pycma.
418 Install the ``cma`` extra. Ordinary CMA-ES accepts exactly one
419 fitness objective. Negate the weighted objective to provide pycma
420 with a loss to minimise. Feedback is buffered until the backend
421 population size is reached.
423 :param dimension: Genome length.
424 :param ind_domain: Optional common bounds for all coordinates.
425 :param sigma0: Initial search standard deviation.
426 :param separable_cma: Use diagonal covariance in the backend.
427 :param ignore_if_not_added_to_container: Exclude nonaccepted archive
428 feedback from the backend's population.
430 ind_domain: Optional[DomainLike]
433 _pop_inds: MutableSequence[IndividualLike]
434 _pop_fitness_vals: MutableSequence[Any]
435 _requires_single_objective =
True
437 def __init__(self, container: Container, budget: int,
438 dimension: int, ind_domain: Optional[DomainLike] =
None,
440 separable_cma: bool =
False,
441 ignore_if_not_added_to_container: bool =
False, **kwargs):
446 super().__init__(container, budget, dimension=dimension, **kwargs)
449 """Reset counters and create a new pycma strategy centred at the zero genome."""
452 raise ValueError(
"CMA-ES requires exactly one fitness objective.")
453 self.
_opts: MutableMapping[str, Any] = {}
458 self.
_opts[
'seed'] = random.randint(0, 2**32-1)
459 self.
_opts[
'verbose'] = -9
461 self.
_opts[
'CMA_diagonal'] =
True
469 base_ind[:] = self.
es.
ask(1)[0]
472 def _weighted_fitness(self, fitness: FitnessLike) -> Tuple[float, ...]:
473 return tuple(value * weight
for value, weight
in zip(fitness.values, self.
_fitness_weights))
481 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) ->
None:
485 fitness = self.
container.get_ind_fitness(individual)
500 def __init__(self, *args, **kwargs):
501 raise NotImplementedError(
"`CMAES` needs the 'cma' package to be installed and importable.")
503 raise NotImplementedError(
"`CMAES` needs the 'cma' package to be installed and importable.")
IndividualLike _internal_ask(self, IndividualLike base_ind)
Select parents by curiosity and update their scores on archive feedback.
reinit(self)
Drop pending parent credit when restarting the optimiser.
_internal_ask(self, base_ind)
Keep lineage on the coordinator instead of copying it into offspring.
__getstate__(self)
Omit unevaluated offspring from result snapshots.
_forget_suggestion(self, individual)
Remove pending credit for a failed evaluation.
_internal_tell(self, individual, added_to_container, xattr=None)
Apply curiosity credit once when the corresponding offspring is told.
_transfer_suggestion(self, individual, evaluated)
Transfer pending curiosity credit to a worker's returned candidate.
EVOLUTION CLASSES ########### {{{1.
Optional _select_or_initialise_fn
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
IndividualLike _internal_ask(self, IndividualLike base_ind)
Convert a selection result into a private offspring or initial genome.
int _select_or_initialise_fn_nb_parameters
Tuple[float,...] _weighted_fitness(self, FitnessLike fitness)
IndividualLike _internal_ask(self, IndividualLike base_ind)
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Buffer one numeric loss per accepted backend candidate.
MutableSequence _pop_fitness_vals
bool _requires_single_objective
MutableSequence _pop_inds
ignore_if_not_added_to_container