QDpy
Loading...
Searching...
No Matches
evolution.py
Go to the documentation of this file.
1# This file is part of qdpy.
2#
3# qdpy is free software: you can redistribute it and/or modify
4# it under the terms of the GNU Lesser General Public License as
5# published by the Free Software Foundation, either version 3 of
6# the License, or (at your option) any later version.
7#
8# qdpy is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU Lesser General Public License for more details.
12#
13# You should have received a copy of the GNU Lesser General Public
14# License along with qdpy. If not, see <http://www.gnu.org/licenses/>.
15
16
18
19"""A collection of all algorithms based on Evolutionary algorithms."""
20
21__all__ = ["Evolution", "RandomSearchMutPolyBounded", "MutPolyBounded", "CuriosityMutPolyBounded", "RandomSearchMutGaussian", "MutGaussian", "CMAES"]
22
23
24
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
27import warnings
28import numpy as np
29import copy
30from functools import partial
31import random
32import sys
33from inspect import signature
34
35
36from .base import *
37from qdpy.utils import *
38from qdpy.phenotype import *
39from qdpy.phenotype import _copy_individual
40from qdpy.base import *
41from qdpy.containers import *
42from qdpy import tools
43
44
45
46
48 """Build an ask/tell algorithm from selection and variation callables.
49
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.
56 """
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
64
65 def __getstate__(self):
66 odict = super().__getstate__()
67 del odict['_select_fn']
68 del odict['_select_or_initialise_fn']
69 del odict['_vary_fn']
70 del odict['_tell_fn']
71 return odict
72
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.")
82 self._select_fn = select
83 self._select_or_initialise_fn = select_or_initialise
84 self._vary_fn = vary # type: ignore
85 self._tell_fn = tell # type: ignore
86 self.deepcopy_on_selection = deepcopy_on_selection
87 # Find the number of parameters of self._select_or_initialise_fn
88 if self._select_or_initialise_fn is not None:
89 sig = signature(self._select_or_initialise_fn)
90 self._select_or_initialise_fn_nb_parameters = len(sig.parameters)
92 raise ValueError("`select_or_initialise` function must take at least one parameter.")
93
94
100 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
101 # Select the next individual
102 perform_variation: bool = False
103 if self._select_fn is not None:
104 selected: IndividualLike = self._select_fn(self.container)
105 if self.deepcopy_on_selection:
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]
110 else:
111 raise RuntimeError("`select` function returned an unknown type of individual.")
112 perform_variation = True
113 elif self._select_or_initialise_fn is not None:
115 selected, perform_variation = self._select_or_initialise_fn(self.container)
117 selected, perform_variation = self._select_or_initialise_fn(self.container, base_ind)
118 if perform_variation and self._lineage_recorder is not None and self._lineage_operator is not None:
119 self._lineage_recorder._parentage(self._lineage_operator, (selected,))
120 # Slice assignment copies a flat genome of immutable floats into a built-in candidate.
121 if self.deepcopy_on_selection and (
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)
124 ):
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.")
128 else:
129 raise RuntimeError("Either `select` or `select_or_initialise` must be provided.")
130
131 # Vary the suggestion
132 if perform_variation:
133 varied = self._vary_fn(selected) # type: ignore
134 if type(varied) is not Individual and not isinstance(varied, IndividualLike):
135 if is_iterable(varied) and isinstance(varied[0], IndividualLike):
136 varied = varied[0]
137 elif is_iterable(varied):
138 pass # Try anyway
139 else:
140 raise RuntimeError("`vary` function returned an unknown type of individual.")
141 base_ind[:] = varied
142 else:
143 return varied
144 else:
145 if type(selected) is Individual or (type(selected) is not list and isinstance(selected, IndividualLike)):
146 return selected
147 else:
148 base_ind[:] = selected
149 # Reset fitness and features
150 base_ind.reset()
151 return base_ind
152
153 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
154 if self._tell_fn is not None:
155 self._tell_fn(individual, added_to_container)
156
157
158
159
160@registry.register
162 """Alternate uniform initialisation and bounded polynomial mutation.
163
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.
167
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.
175 """
176 _lineage_operator = "polynomial"
177 ind_domain: DomainLike
178 sel_pb: float
179 init_pb: float
180 mut_pb: float
181 eta: float
182
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):
187 self.ind_domain = ind_domain
188 self.sel_pb = sel_pb
189 self.init_pb = init_pb
190 self.mut_pb = mut_pb
191 self.eta = eta
192
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,
197 sel_pb = sel_pb,
198 init_fn = init_fn,
199 init_pb = init_pb)
200 def vary(ind):
201 return tools.mut_polynomial_bounded(ind, low=self.ind_domain[0], up=self.ind_domain[1], eta=self.eta, mut_pb=self.mut_pb)
202
203 super().__init__(container, budget, dimension=dimension, # type: ignore
204 select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
205
206
207@registry.register
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)
217
218
219
220@registry.register
222 """Use named curiosity scores to select parents for polynomial mutation.
223
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.
228
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.
237 """
238
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].")
247 self.score_name = score_name
248 self.default_score = default_score
249 self.reward = reward
250 self.penalty = penalty
251 self._selected_parent = None
252
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):
256 child = Individual(parent)
257 else:
258 child = copy.deepcopy(parent)
259 child.reset()
260 self._selected_parent = parent
261 return child
262
263 def initialise(_):
264 return [random.uniform(*ind_domain) for _ in range(dimension)]
265
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)
272
273
274 def reinit(self):
275 super().reinit()
276 self._pending_parents = {}
277
278
279 def _internal_ask(self, base_ind):
280 try:
281 child = super()._internal_ask(base_ind)
282 if self._selected_parent is not None:
283 self._pending_parents[id(child)] = (child, self._selected_parent)
284 if self._lineage_recorder is not None:
285 self._lineage_recorder._parentage("curiosity_polynomial", (self._selected_parent,))
286 return child
287 finally:
288 self._selected_parent = None
289
290
291 def _transfer_suggestion(self, individual, evaluated):
292 super()._transfer_suggestion(individual, evaluated)
293 record = self._pending_parents.pop(id(individual), None)
294 if record is not None:
295 self._pending_parents[id(evaluated)] = (evaluated, record[1])
296
297
298 def _forget_suggestion(self, individual):
299 super()._forget_suggestion(individual)
300 self._pending_parents.pop(id(individual), None)
301
302
303 def _internal_tell(self, individual, added_to_container, xattr=None):
304 record = self._pending_parents.pop(id(individual), None)
305 if record is not None:
306 parent = record[1]
307 previous = parent.scores.get(self.score_name, self.default_score)
308 parent.scores[self.score_name] = previous + (self.reward if added_to_container else -self.penalty)
309
310
311 def __getstate__(self):
312 state = super().__getstate__()
313 state["_pending_parents"] = {}
314 state["_selected_parent"] = None
315 return state
316
317
318# TODO refactor: redundant code with RandomSearchMutPolyBounded
319@registry.register
321 """Use uniform initialisation and grid-based roulette selection.
322
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.
326 """
327 ind_domain: DomainLike
328 sel_pb: float
329 init_pb: float
330 mut_pb: float
331 eta: float
332
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.,
336 **kwargs):
337 self.ind_domain = ind_domain
338 self.sel_pb = sel_pb
339 self.init_pb = init_pb
340 self.mut_pb = mut_pb
341 self.eta = eta
342
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,
347 sel_pb = sel_pb,
348 init_fn = init_fn,
349 init_pb = init_pb)
350 def vary(ind):
351 return tools.mut_polynomial_bounded(ind, low=self.ind_domain[0], up=self.ind_domain[1], eta=self.eta, mut_pb=self.mut_pb)
352
353 super().__init__(container, budget, dimension=dimension, # type: ignore
354 select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
355
356
357@registry.register
359 """Initialise and mutate real-valued genomes with a Gaussian.
360
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.
365 """
366 _lineage_operator = "gaussian"
367 sel_pb: float
368 init_pb: float
369 mut_pb: float
370 mu: float
371 sigma: float
372
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):
377 self.sel_pb = sel_pb
378 self.init_pb = init_pb
379 self.mut_pb = mut_pb
380 self.mu = mu
381 self.sigma = sigma
382
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])
387 return values
388 select_or_initialise = partial(tools.sel_or_init,
389 sel_fn = tools.sel_random,
390 sel_pb = sel_pb,
391 init_fn = init_fn,
392 init_pb = init_pb)
393 def vary(ind):
394 return tools.mut_gaussian(ind, mu=self.mu, sigma=self.sigma, mut_pb=self.mut_pb, bounds=ind_domain)
395
396 super().__init__(container, budget, dimension=dimension, # type: ignore
397 select_or_initialise=select_or_initialise, vary=vary, **kwargs) # type: ignore
398
399
400@registry.register
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)
409
410
411try:
412 import cma
413
414 @registry.register
416 """Adapt a Gaussian search distribution with pycma.
417
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.
422
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.
429 """
430 ind_domain: Optional[DomainLike]
431 sigma0: float
432 es: Any
433 _pop_inds: MutableSequence[IndividualLike]
434 _pop_fitness_vals: MutableSequence[Any]
435 _requires_single_objective = True
436
437 def __init__(self, container: Container, budget: int,
438 dimension: int, ind_domain: Optional[DomainLike] = None,
439 sigma0: float = 1.0,
440 separable_cma: bool = False,
441 ignore_if_not_added_to_container: bool = False, **kwargs):
442 self.sigma0 = sigma0
443 self.ind_domain = ind_domain
444 self.separable_cma = separable_cma
445 self.ignore_if_not_added_to_container = ignore_if_not_added_to_container
446 super().__init__(container, budget, dimension=dimension, **kwargs)
447
448 def reinit(self) -> None:
449 """Reset counters and create a new pycma strategy centred at the zero genome."""
450 super().reinit()
451 if self._requires_single_objective and self._nb_objectives != 1:
452 raise ValueError("CMA-ES requires exactly one fitness objective.")
453 self._opts: MutableMapping[str, Any] = {}
454 if self.ind_domain is not None:
455 self._opts['bounds'] = list(self.ind_domain)
456 if self._batch_size is not None:
457 self._opts['popsize'] = self._batch_size
458 self._opts['seed'] = random.randint(0, 2**32-1)
459 self._opts['verbose'] = -9
460 if self.separable_cma:
461 self._opts['CMA_diagonal'] = True
462 self.es = cma.CMAEvolutionStrategy([0.] * self.dimension, self.sigma0, self._opts) # type: ignore
463 self._pop_inds = []
464 self._pop_fitness_vals = []
465 if self._batch_size is None:
466 self._batch_size = self.es.popsize
467
468 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
469 base_ind[:] = self.es.ask(1)[0]
470 return base_ind
471
472 def _weighted_fitness(self, fitness: FitnessLike) -> Tuple[float, ...]:
473 return tuple(value * weight for value, weight in zip(fitness.values, self._fitness_weights))
474
475
481 def _internal_tell(self, individual: IndividualLike, added_to_container: bool, xattr: Mapping[str, Any] = {}) -> None:
482 if self.ignore_if_not_added_to_container and not added_to_container:
483 return
484 self._pop_inds += [individual]
485 fitness = self.container.get_ind_fitness(individual)
486 self._pop_fitness_vals.append(-self._weighted_fitness(fitness)[0])
487 if len(self._pop_inds) >= self.es.popsize:
488 try:
489 self.es.tell(self._pop_inds, self._pop_fitness_vals)
490 except RuntimeError:
491 pass
492 else:
493 self._pop_inds.clear()
494 self._pop_fitness_vals.clear()
495
496
497except ImportError:
498 @registry.register # type: ignore
499 class CMAES(QDAlgorithm): # type: ignore
500 def __init__(self, *args, **kwargs):
501 raise NotImplementedError("`CMAES` needs the 'cma' package to be installed and importable.")
502 def _internal_ask(self, base_ind: IndividualLike) -> IndividualLike:
503 raise NotImplementedError("`CMAES` needs the 'cma' package to be installed and importable.")
504
505
506
507
508# MODELINE "{{{1
509# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
510# vim:foldmethod=marker
IndividualLike ask(self)
Definition base.py:481
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition evolution.py:502
Select parents by curiosity and update their scores on archive feedback.
Definition evolution.py:221
reinit(self)
Drop pending parent credit when restarting the optimiser.
Definition evolution.py:274
_internal_ask(self, base_ind)
Keep lineage on the coordinator instead of copying it into offspring.
Definition evolution.py:279
__getstate__(self)
Omit unevaluated offspring from result snapshots.
Definition evolution.py:311
_forget_suggestion(self, individual)
Remove pending credit for a failed evaluation.
Definition evolution.py:298
_internal_tell(self, individual, added_to_container, xattr=None)
Apply curiosity credit once when the corresponding offspring is told.
Definition evolution.py:303
_transfer_suggestion(self, individual, evaluated)
Transfer pending curiosity credit to a worker's returned candidate.
Definition evolution.py:291
EVOLUTION CLASSES ########### {{{1.
Definition evolution.py:47
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Definition evolution.py:153
IndividualLike _internal_ask(self, IndividualLike base_ind)
Convert a selection result into a private offspring or initial genome.
Definition evolution.py:100
Tuple[float,...] _weighted_fitness(self, FitnessLike fitness)
Definition evolution.py:472
IndividualLike _internal_ask(self, IndividualLike base_ind)
Definition evolution.py:468
None _internal_tell(self, IndividualLike individual, bool added_to_container, Mapping[str, Any] xattr={})
Buffer one numeric loss per accepted backend candidate.
Definition evolution.py:481