QDpy
Loading...
Searching...
No Matches
mepgd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Allow otherwise rejected offspring to become parents without replacing elites."""
7
8import numpy as np
9
10from qdpy.base import registry
11from .constrained import _validate_grid
12from .modern import _FixedGeneration, _bounds, _positive_int
13
14__all__ = ["MEPGD"]
15
16
17
18@registry.register
20 """Retain one reporting elite and at most one auxiliary breeder per cell.
21
22 A strict fitness improvement replaces the reporting elite. An
23 otherwise eligible candidate may overwrite the auxiliary slot
24 even when its fitness is lower. Parent selection samples an occupied
25 cell uniformly and chooses between its two live occupants when both
26 exist. All data in the reporting grid comes from elite competition.
27
28 :param container: Empty parentless best-only Grid or CVTGrid with one objective.
29 :param budget: Candidate evaluation attempts.
30 :param dimension: Number of real-valued genome coordinates.
31 :param replacement_probability: Chance a non-improving candidate occupies the second slot.
32 :param sigma: Scale of default bounded Gaussian mutation.
33 :param mutate: Optional callback taking (parent_genome, rng).
34 :param ind_domain: Common bounds for all genome coordinates.
35 :param batch_size: Number of simultaneous proposals.
36 :param seed: Private seed for parent selection, mutation, and second-slot admission.
37 :param kwargs: Native QDAlgorithm settings.
38 """
39
40 _requires_proposed_genome = True
41
42 def __init__(self, container, budget, dimension, *, replacement_probability=.3,
43 sigma=.1, mutate=None, ind_domain=(0., 1.), batch_size=1, seed=0, **kwargs):
44 _validate_grid(container)
45 if container.parents:
46 raise ValueError("MEPGD needs a parentless reporting archive.")
47 if not 0. <= replacement_probability <= 1. or not 0. <= sigma < np.inf:
48 raise ValueError("Use probabilities in [0, 1] and finite nonnegative sigma.")
49 if mutate is not None and not callable(mutate):
50 raise TypeError("mutate must be callable.")
51 self.ind_domain = _bounds(ind_domain)
52 if not np.isfinite(self.ind_domain[1] - self.ind_domain[0]):
53 raise ValueError("Use finite decision spans.")
54 self.replacement_probability = replacement_probability
55 self.sigma, self.mutate, self.seed = sigma, mutate, seed
56 if container.fitness_weights is not None:
57 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
58 super().__init__(container, _positive_int(budget, "budget"),
59 dimension=_positive_int(dimension, "dimension"),
60 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
61 if not self._fitness_weights[0]:
62 raise ValueError("A nonzero scalar fitness weight is required.")
63
64 def reinit(self):
65 """Reset auxiliary slots, admission counters, and random state."""
66 super().reinit()
67 self._breeders = {}
68 self._rng = np.random.default_rng(self.seed)
70
71 @property
72 def breeding_slots(self):
73 """Return the second-slot occupants indexed by reporting cell."""
74 return dict(self._breeders)
75
76 @property
78 """Return the cumulative number of second-slot updates."""
79 return self._auxiliary_admissions
80
81 def _internal_ask(self, base_ind):
82 if not self.container:
83 base_ind[:] = self._rng.uniform(*self.ind_domain, size=self.dimension)
84 return base_ind
85 parent = self.container[self._rng.integers(len(self.container))]
86 backup = self._breeders.get(self.container.index_grid(parent))
87 if backup is not None and self._rng.integers(2):
88 parent = backup
89 if self.mutate is None:
90 genome = np.clip(np.asarray(parent, dtype=float) + self._rng.normal(0., self.sigma, self.dimension),
91 *self.ind_domain)
92 else:
93 genome = np.asarray(self.mutate(tuple(parent), self._rng), dtype=float)
94 lower, upper = self.ind_domain
95 if genome.shape != (self.dimension,) or not np.all((genome >= lower) & (genome <= upper)):
96 raise ValueError("Mutation must return a bounded real genome of the configured length.")
97 base_ind[:] = genome
98 return base_ind
99
100 def _check_candidate(self, individual):
101 super()._check_candidate(individual)
102 self.container.index_grid(individual)
103
104 def _commit_generation(self, evaluated):
105 admitted = set()
106 for slot, candidate in enumerate(evaluated):
107 if candidate is None:
108 continue
109 cell = self.container.index_grid(candidate)
110 front = self.container.solutions[cell]
111 if self._offer_to_grid(candidate, cell):
112 admitted.add(slot)
113 if candidate == self._breeders.get(cell):
114 del self._breeders[cell]
115 elif (front and candidate != front[0] and candidate != self._breeders.get(cell)
116 and self.replacement_probability and self._rng.random() < self.replacement_probability):
117 self._breeders[cell] = candidate
118 self._auxiliary_admissions += 1
119 return admitted
Keep a second breeding slot with stochastic admission in each occupied niche.
Definition mepgd.py:19
_commit_generation(self, evaluated)
Definition mepgd.py:104
_internal_ask(self, base_ind)
Definition mepgd.py:81
_offer_to_grid(self, individual, cell)
Definition modern.py:228