QDpy
Loading...
Searching...
No Matches
lm_ma_mae.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""LM-MA-MAE with native archives and generation accounting."""
6
7from math import exp, log
8
9import numpy as np
10
11from qdpy.base import registry
12from .modern import CMAMAE, _positive_int
13
14__all__ = ["LMMAMAE"]
15
16
17class _LMMAES:
18 """Rank-based LM-MA-ES adaptation in an implicit transformation."""
19
20 def __init__(self, center, sigma, population, memory_size, bounds, rng):
21 self.center = np.array(center, dtype=float)
22 self.sigma, self.population, self.bounds, self.rng = sigma, population, bounds, rng
23 dimension = len(center)
24 self.paths = np.zeros((memory_size, dimension))
25 self.path = np.zeros(dimension)
26 times = np.arange(memory_size, dtype=float)
27 self.transforms = np.exp(-times * log(1.5)) / dimension
28 self.rates = np.minimum(1., (population / dimension) * np.exp(-times * log(4.)))
29 self.sigma_rate = min(1., 2 * population / dimension)
30 self.generation = 0
31
32 def stop(self):
33 return not 1e-12 <= self.sigma <= 1e12 or not np.isfinite(self.paths).all()
34
35 def ask(self, number):
36 self.normal = self.rng.standard_normal((number, len(self.center)))
37 directions = self.normal.copy()
38 for rate, path in zip(self.transforms[:self.generation], self.paths):
39 directions = (1 - rate) * directions + rate * (directions @ path)[:, None] * path
40 proposals = self.center + self.sigma * directions
41 return proposals if self.bounds is None else np.clip(proposals, *self.bounds)
42
43 def adapt(self, vectors, order):
44 selected = order[:self.population // 2]
45 count = len(selected)
46 if not count:
47 return
48 weights = log(count + 0.5) - np.log(np.arange(1, count + 1))
49 weights /= weights.sum()
50 effective = 1 / (weights @ weights)
51 normal_step = weights @ self.normal[selected]
52 self.center = weights @ vectors[selected]
53 rate = self.sigma_rate
54 self.path = (1 - rate) * self.path + np.sqrt(effective * rate * (2 - rate)) * normal_step
55 rates = self.rates[:, None]
56 self.paths = (1 - rates) * self.paths + np.sqrt(effective * rates * (2 - rates)) * normal_step
57 exponent = rate / 2 * (np.mean(self.path ** 2) - 1)
58 self.sigma *= exp(min(exponent, 100))
59 self.generation += 1
60
61
62
63@registry.register
65 """LM-MA-MAE for fixed one-elite grids and CVT grids.
66
67 Uses the CMA-MAE annealed thresholds and reporting archive with the
68 LM-MA-ES optimizer from Loshchilov et al. The optimizer stores direction
69 vectors instead of a square covariance matrix. No CMA extra is needed.
70
71 :param container: Fixed, one-elite Grid or CVTGrid.
72 :param budget: Candidate evaluations per run.
73 :param x0: Finite center vector in genome coordinates.
74 :param sigma0: Positive initial search step size.
75 :param batch_size: Population size (at least two).
76 :param threshold_min: Initial threshold in weighted quality units.
77 :param memory_size: Number of direction vectors, at most the genome
78 length. The default is the smaller of that length and
79 four plus the floor of three times the natural logarithm of the length.
80 :param kwargs: CMA-MAE threshold, seed, and native QD options.
81
82 Bounded candidates are clipped to the genome domain. On small problems
83 the path learning rates are capped at one. Incomplete trailing batches
84 update the archives only. Failed slots are excluded from adaptation.
85 """
86
87 def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
88 memory_size=None, **kwargs):
89 self.memory_size = memory_size
90 super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, **kwargs)
91 if memory_size is None:
92 self.memory_size = min(self.dimension, 4 + int(3 * log(self.dimension)))
93 else:
94 self.memory_size = _positive_int(memory_size, "memory_size")
95 if self.memory_size > self.dimension:
96 raise ValueError("memory_size cannot exceed the genome length.")
97
98 def _check_optimizer_dependency(self):
99 pass
100
101 def _new_strategy(self, center, *, bounded=True):
102 rng = np.random.default_rng(self._search_rng().randint(0, 2**32 - 1))
103 return _LMMAES(center, self.sigma0, self.batch_size, self.memory_size,
104 self.ind_domain if bounded else None, rng)
105
106 def _adapt_strategy(self, vectors):
107 valid = np.flatnonzero(np.isfinite(self._gains))
108 order = valid[np.argsort(-self._gains[valid], kind="stable")]
109 self._strategy.adapt(vectors, order)
110 return order
Replace full covariance adaptation with limited-memory LM-MA-ES.
Definition lm_ma_mae.py:64
Adapt a covariance matrix using annealed cell-level improvement.
Definition modern.py:343