QDpy
Loading...
Searching...
No Matches
voronoi_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Voronoi-Elites with native QDpy evaluation and accounting."""
8
9import numpy as np
10
11from qdpy.base import registry
12from qdpy.containers import VoronoiArchive
13
14from .modern import _FixedGeneration, _bounds, _positive_int
15
16__all__ = ["VoronoiElites"]
17
18
19
20@registry.register
22 """Use bounded Gaussian mutation and a VoronoiArchive.
23
24 Draw an initial population uniformly, then mutate parents sampled
25 uniformly from the retained archive. Feedback within a batch is
26 applied one candidate at a time in proposal order.
27
28 :param container: The VoronoiArchive that will hold evaluated elites.
29 :param budget: Attempted evaluations.
30 :param dimension: Number of real genome coordinates.
31 :param ind_domain: Shared inclusive genome bounds.
32 :param sigma: Gaussian standard deviation as a fraction of the genome range.
33 :param initial_samples: Uniform proposals for an empty archive.
34 Defaults to archive capacity.
35 :param batch_size: Number of proposals evaluated before feedback.
36 :param seed: Seed for private proposal randomness.
37 :param extinction_period: Optional interval in completed batches between extinctions.
38 :param extinction_size: Live population cap in extinction batches.
39 :param kwargs: Standard QDpy optimiser options.
40 """
41
42 def __init__(self, container, budget, dimension, *, ind_domain=(0., 1.), sigma=.08,
43 initial_samples=None, batch_size=1, seed=0, extinction_period=None, extinction_size=None,
44 **kwargs):
45 if not isinstance(container, VoronoiArchive):
46 raise TypeError("Supply a VoronoiArchive.")
47 self.ind_domain = _bounds(ind_domain)
48 self._scale = sigma * (self.ind_domain[1] - self.ind_domain[0])
49 if not 0. < self._scale < np.inf:
50 raise ValueError("Use finite genome bounds and a positive finite mutation scale.")
51 self.seed = seed
52 if (extinction_period is None) != (extinction_size is None):
53 raise ValueError("Supply both extinction_period and extinction_size.")
54 self.extinction_period = self.extinction_size = None
55 if extinction_period is not None:
56 self.extinction_period = _positive_int(extinction_period, "extinction_period")
57 self.extinction_size = _positive_int(extinction_size, "extinction_size")
58 if self.extinction_size >= container.capacity:
59 raise ValueError("extinction_size must be below the normal archive capacity.")
60 initial = container.capacity if initial_samples is None else _positive_int(initial_samples, "initial_samples")
61 self._initial_samples = 0 if len(container) else initial
62 dimension = _positive_int(dimension, "dimension")
63 for candidate in container:
64 values = np.asarray(candidate, dtype=float)
65 if (values.shape != (dimension,) or not np.isfinite(values).all()
66 or np.any(values < self.ind_domain[0]) or np.any(values > self.ind_domain[1])):
67 raise ValueError("Warm-start genomes must match the search dimension and bounds.")
68 kwargs.setdefault("optimisation_task", container.fitness_weights)
69 super().__init__(container, _positive_int(budget, "budget"), dimension=dimension,
70 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
71
72 def reinit(self):
73 """Reset search accounting and the private random stream."""
74 super().reinit()
75 self._rng = np.random.default_rng(self.seed)
76 self._extinctions = self._pruned = 0
77
78 @property
79 def extinctions(self):
80 """Return the number of completed extinction batches."""
81 return getattr(self, "_extinctions", 0)
82
83 @property
84 def pruned(self):
85 """Return removals made to enforce the reduced population cap."""
86 return getattr(self, "_pruned", 0)
87
88 def _internal_ask(self, base_ind):
89 if self.nb_suggestions < self._initial_samples or not len(self.container):
90 point = self._rng.uniform(*self.ind_domain, size=self.dimension)
91 else:
92 parent = np.asarray(self.container[self._rng.integers(len(self.container))], dtype=float)
93 point = np.clip(parent + self._rng.normal(scale=self._scale, size=self.dimension), *self.ind_domain)
94 base_ind[:] = point.tolist()
95 return base_ind
96
97 def _commit_generation(self, evaluated):
98 admitted = set()
99 period = getattr(self, "extinction_period", None)
100 extinction = period is not None and (self.current_iter + 1) % period == 0
101 for slot, ind in enumerate(evaluated):
102 if ind is not None:
103 before = self.container.nb_added
104 self.container.add(ind)
105 if self.container.nb_added != before:
106 admitted.add(slot)
107 if extinction:
108 self._pruned += self.container.prune_to(self.extinction_size)
109 if extinction:
110 self._pruned += self.container.prune_to(self.extinction_size)
111 self._extinctions += 1
112 return admitted
Mutate uniformly sampled elites and admit results in proposal order.