QDpy
Loading...
Searching...
No Matches
youth.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Limit MAP-Elites parent sampling to a window of live archive admissions."""
7
8from random import randrange
9
10import numpy as np
11
12from qdpy.base import registry
13from qdpy.containers import CVTGrid, Grid
14from .modern import _FixedGeneration, _bounds, _positive_int
15
16__all__ = ["YouthMAPElites", "select_youth"]
17
18
19
20def select_youth(archive, count, *, rng=None):
21 """Return a live recent elite from a nonempty insertion-ordered archive.
22
23 A NumPy Generator can supply the draw. The default uses Python's
24 random stream, as do the native polynomial mutation operators.
25 """
26 count = _positive_int(count, "count")
27 size = len(archive)
28 if not size:
29 raise ValueError("Cannot select a parent from an empty archive.")
30 first = max(0, size - count)
31 return archive[randrange(first, size) if rng is None else rng.integers(first, size)]
32
33
34
35@registry.register
37 """Draw uniformly from the last parent_window current archive admissions.
38
39 Successful insertions and replacements appear at the end of the native
40 Grid or CVTGrid storage. Rejected offspring leave that order unchanged.
41 The list therefore reflects the youngest retained parents, including
42 when starting from a prefilled archive. Each generation commits
43 feedback in proposal order. Manual evaluations use ask_batch() and
44 tell_batch().
45
46 :param container: Best-only regular Grid or CVTGrid.
47 :param budget: Candidate evaluation attempts.
48 :param dimension: Number of real genome coordinates.
49 :param parent_window: Maximum number of recent elites eligible for sampling.
50 :param ind_domain: Common lower and upper bounds for each coordinate.
51 :param sigma: Standard deviation of default Gaussian mutation.
52 :param mutate: Optional callable taking (parent_tuple, rng) and returning a genome.
53 :param seed: Private seed.
54 :param kwargs: Native algorithm settings such as batch_size.
55 """
56
57 _requires_proposed_genome = True
58
59 def __init__(self, container, budget, dimension, *, parent_window=16, ind_domain=(0., 1.),
60 sigma=.1, mutate=None, seed=0, **kwargs):
61 if (type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1
62 or container.discard_random_on_bin_overload):
63 raise ValueError("YouthMAPElites requires a best-only Grid or CVTGrid.")
64 if not 0 <= sigma < np.inf or (mutate is not None and not callable(mutate)):
65 raise ValueError("Use a finite nonnegative sigma and an optional mutation callback.")
66 self.ind_domain = _bounds(ind_domain)
67 if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
68 raise ValueError("Use decision bounds with a finite span.")
69 self.parent_window = _positive_int(parent_window, "parent_window")
70 self.sigma, self.mutate, self.seed = sigma, mutate, seed
71 dimension = _positive_int(dimension, "dimension")
72 lo, hi = self.ind_domain
73 for item in container:
74 genome = np.asarray(item, dtype=float)
75 if genome.shape != (dimension,) or not np.all((genome >= lo) & (genome <= hi)):
76 raise ValueError("Existing elites must be bounded real genomes of the configured length.")
77 if container.fitness_weights is not None:
78 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
79 super().__init__(container, _positive_int(budget, "budget"), dimension=dimension, **kwargs)
80
81 def reinit(self):
82 """Reset the proposal stream and recover admission order from the current archive."""
83 super().reinit()
84 self._rng = np.random.default_rng(self.seed)
85
86 def _internal_ask(self, base_ind):
87 size = len(self.container)
88 if not size:
89 base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension)
90 return base_ind
91
92 parent = tuple(select_youth(self.container, self.parent_window, rng=self._rng))
93 if self.mutate is None:
94 genome = np.asarray(parent) + self._rng.normal(0., self.sigma, self.dimension)
95 genome = np.clip(genome, *self.ind_domain)
96 else:
97 genome = np.asarray(self.mutate(parent, self._rng), dtype=float)
98 lo, hi = self.ind_domain
99 if genome.shape != (self.dimension,) or not np.all((genome >= lo) & (genome <= hi)):
100 raise ValueError("Mutation must return a finite bounded genome of the configured length.")
101 base_ind[:] = genome
102 return base_ind
Use the youngest retained elites as a parent population.
Definition youth.py:36