QDpy
Loading...
Searching...
No Matches
dynamic_mutation.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Run Nordmoen's dynamic mutation schedules on a native archive."""
7
8from math import prod, sqrt
9
10import numpy as np
11
12from qdpy.base import registry
13from qdpy.containers import CVTGrid, Grid
14from .base import QDAlgorithm
15from .modern import _bounds, _positive_int
16
17__all__ = ["DynamicMutationMAPElites"]
18_SIGMA = "dynamic_mutation_sigma"
19
20
21
22@registry.register
24 """Use fixed, coverage-based, annealed, or log-normal inherited mutation.
25
26 Scales are in unit-genome coordinates, multiplied by the domain span
27 and divided by the square root of the active dimension minus one
28 (one for a single coordinate). Both global schedules use committed
29 feedback when generating a proposal. Inherited scales travel with
30 survivors and remain independent of the genome itself.
31
32 :param container: Native one-elite Grid or CVTGrid.
33 :param budget: Nominal number of evaluations, also the annealing horizon.
34 :param dimension: Number of real-valued genome variables.
35 :param mode: "fixed", "coverage", "anneal", or "self_adaptive".
36 :param ind_domain: Common finite coordinate bounds.
37 :param sigma_start: Initial Gaussian strength, or the fixed strength.
38 :param sigma_stop: Final Gaussian strength, or the inherited scale floor.
39 :param coverage_target: Occupied fraction of the grid at which coverage annealing ends.
40 :param adaptation_rate: Log-normal learning rate, defaulting to one over the square root of the dimension.
41 :param seed: Private initialization and mutation seed.
42 :param batch_size: Maximum proposals before feedback. The default updates after each evaluation.
43 :param kwargs: Native QDAlgorithm configuration, including the optimization direction.
44 """
45
46 def __init__(self, container, budget, dimension, *, mode="coverage", ind_domain=(0., 1.),
47 sigma_start=.2, sigma_stop=.025, coverage_target=1., adaptation_rate=None, seed=0,
48 batch_size=1, **kwargs):
49 if type(container) not in (Grid, CVTGrid) or container.max_items_per_bin != 1:
50 raise ValueError("Use a one-elite Grid or CVTGrid.")
51 if mode not in ("fixed", "coverage", "anneal", "self_adaptive"):
52 raise ValueError("Choose fixed, coverage, anneal, or self_adaptive.")
53 if not (0 < sigma_stop <= sigma_start < np.inf and 0 < coverage_target <= 1.):
54 raise ValueError("Use positive finite scales and a coverage target in (0, 1].")
55 dimension, budget = _positive_int(dimension, "dimension"), _positive_int(budget, "budget")
56 self._tau = 1. / sqrt(dimension) if adaptation_rate is None else adaptation_rate
57 if not 0 < self._tau < np.inf:
58 raise ValueError("adaptation_rate must be finite and positive.")
59 if _SIGMA in (*container.fitness_score_names, *container.features_score_names):
60 raise ValueError(f"{_SIGMA} is reserved for the mutation scale.")
61 self.ind_domain = _bounds(ind_domain)
62 self._scale = (self.ind_domain[1] - self.ind_domain[0]) / sqrt(max(1, dimension - 1))
63 if not (0 < self._scale * sigma_stop and self._scale * sigma_start < np.inf):
64 raise ValueError("The scaled mutation strength must be finite and positive.")
65 self.mode, self.sigma_start, self.sigma_stop = mode, sigma_start, sigma_stop
66 self.coverage_target, self._cells, self._seed = coverage_target, prod(container.shape), seed
67 super().__init__(container, budget, dimension=dimension, batch_size=_positive_int(batch_size, "batch_size"),
68 **kwargs)
69
70 def reinit(self):
71 """Reset progress and variation state while keeping the native archive."""
72 super().reinit()
73 self._rng = np.random.default_rng(self._seed)
74
75 @property
76 def scheduled_sigma(self):
77 """Return the current global mutation scale before domain scaling."""
78 if self.mode == "coverage":
79 progress = self.container.filled_bins / self._cells / self.coverage_target
80 elif self.mode == "anneal":
81 progress = self.nb_evaluations / self.budget
82 else:
83 return self.sigma_start
84 progress = min(1., progress)
85 return self.sigma_start * (1. - progress) + self.sigma_stop * progress
86
87 def _internal_ask(self, base_ind):
88 sigma = self.scheduled_sigma
89 if not self.container:
90 base_ind[:] = self._rng.uniform(*self.ind_domain, self.dimension)
91 else:
92 parent = self.container[int(self._rng.integers(len(self.container)))]
93 if self.mode == "self_adaptive":
94 previous = parent.scores.get(_SIGMA, self.sigma_start)
95 if not 0 < previous < np.inf:
96 raise ValueError("The inherited mutation strength must be finite and positive.")
97 log_sigma = np.log(previous) + self._rng.normal(0., self._tau)
98 # Keep the standard deviation representable in physical coordinates.
99 upper = np.log(np.finfo(float).max) - max(0., np.log(self._scale)) - 2.
100 sigma = float(np.exp(np.clip(log_sigma, np.log(self.sigma_stop), upper)))
101 base_ind[:] = np.clip(np.asarray(parent) + self._rng.normal(0., sigma * self._scale, self.dimension),
102 *self.ind_domain)
103 if self._lineage_recorder is not None:
104 self._lineage_recorder._parentage("dynamic_gaussian_mutation", (parent,))
105 base_ind.scores[_SIGMA] = sigma
106 return base_ind
107
108 def _apply_evaluation(self, ind, fitness, features, scores, elapsed):
109 sigma = ind.scores.get(_SIGMA)
110 if scores is not None and sigma is not None:
111 scores = dict(scores)
112 super()._apply_evaluation(ind, fitness, features, scores, elapsed)
113 if sigma is not None:
114 ind.scores[_SIGMA] = sigma
Illuminate a fixed descriptor partition with an adaptive Gaussian operator.