# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Limited-memory matrix adaptation for CMA-MAE-style illumination.
"""LM-MA-MAE with native archives and generation accounting."""
from math import exp, log
import numpy as np
from qdpy.base import registry
from .modern import CMAMAE, _positive_int
__all__ = ["LMMAMAE"]
class _LMMAES:
"""Rank-based LM-MA-ES adaptation in an implicit transformation."""
def __init__(self, center, sigma, population, memory_size, bounds, rng):
self.center = np.array(center, dtype=float)
self.sigma, self.population, self.bounds, self.rng = sigma, population, bounds, rng
dimension = len(center)
self.paths = np.zeros((memory_size, dimension))
self.path = np.zeros(dimension)
times = np.arange(memory_size, dtype=float)
self.transforms = np.exp(-times * log(1.5)) / dimension
self.rates = np.minimum(1., (population / dimension) * np.exp(-times * log(4.)))
self.sigma_rate = min(1., 2 * population / dimension)
self.generation = 0
def stop(self):
return not 1e-12 <= self.sigma <= 1e12 or not np.isfinite(self.paths).all()
def ask(self, number):
self.normal = self.rng.standard_normal((number, len(self.center)))
directions = self.normal.copy()
for rate, path in zip(self.transforms[:self.generation], self.paths):
directions = (1 - rate) * directions + rate * (directions @ path)[:, None] * path
proposals = self.center + self.sigma * directions
return proposals if self.bounds is None else np.clip(proposals, *self.bounds)
def adapt(self, vectors, order):
selected = order[:self.population // 2]
count = len(selected)
if not count:
return
weights = log(count + 0.5) - np.log(np.arange(1, count + 1))
weights /= weights.sum()
effective = 1 / (weights @ weights)
normal_step = weights @ self.normal[selected]
self.center = weights @ vectors[selected]
rate = self.sigma_rate
self.path = (1 - rate) * self.path + np.sqrt(effective * rate * (2 - rate)) * normal_step
rates = self.rates[:, None]
self.paths = (1 - rates) * self.paths + np.sqrt(effective * rates * (2 - rates)) * normal_step
exponent = rate / 2 * (np.mean(self.path ** 2) - 1)
self.sigma *= exp(min(exponent, 100))
self.generation += 1
## @brief Replace full covariance adaptation with limited-memory LM-MA-ES.
[docs]
@registry.register
class LMMAMAE(CMAMAE):
"""LM-MA-MAE for fixed one-elite grids and CVT grids.
Uses the CMA-MAE annealed thresholds and reporting archive with the
LM-MA-ES optimizer from Loshchilov et al. The optimizer stores direction
vectors instead of a square covariance matrix. No CMA extra is needed.
:param container: Fixed, one-elite Grid or CVTGrid.
:param budget: Candidate evaluations per run.
:param x0: Finite center vector in genome coordinates.
:param sigma0: Positive initial search step size.
:param batch_size: Population size (at least two).
:param threshold_min: Initial threshold in weighted quality units.
:param memory_size: Number of direction vectors, at most the genome
length. The default is the smaller of that length and
four plus the floor of three times the natural logarithm of the length.
:param kwargs: CMA-MAE threshold, seed, and native QD options.
Bounded candidates are clipped to the genome domain. On small problems
the path learning rates are capped at one. Incomplete trailing batches
update the archives only. Failed slots are excluded from adaptation.
"""
def __init__(self, container, budget, x0, sigma0, batch_size, threshold_min, *,
memory_size=None, **kwargs):
self.memory_size = memory_size
super().__init__(container, budget, x0, sigma0, batch_size, threshold_min, **kwargs)
if memory_size is None:
self.memory_size = min(self.dimension, 4 + int(3 * log(self.dimension)))
else:
self.memory_size = _positive_int(memory_size, "memory_size")
if self.memory_size > self.dimension:
raise ValueError("memory_size cannot exceed the genome length.")
def _check_optimizer_dependency(self):
pass
def _new_strategy(self, center, *, bounded=True):
rng = np.random.default_rng(self._search_rng().randint(0, 2**32 - 1))
return _LMMAES(center, self.sigma0, self.batch_size, self.memory_size,
self.ind_domain if bounded else None, rng)
def _adapt_strategy(self, vectors):
valid = np.flatnonzero(np.isfinite(self._gains))
order = valid[np.argsort(-self._gains[valid], kind="stable")]
self._strategy.adapt(vectors, order)
return order