# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Two-objective CMA-MAE with annealed threshold fronts.
"""Covariance search with separate search thresholds and reporting fronts."""
from math import isfinite
import random
import numpy as np
from qdpy.base import registry
from qdpy.containers import ParetoGrid
from .modern import _CMAEmitter, _bounds, _positive_int
__all__ = ["MOCMAMAE"]
def _gain(point, front):
"""Integrate the uncovered part of a rectangle over the threshold staircase."""
width, height = point
gain = previous = 0.
for x, y in front:
edge = min(width, x)
gain += (edge - previous) * max(height - y, 0.)
previous = edge
if edge == width:
return gain
return gain + (width - previous) * height
def _insert(point, front):
if any(x >= point[0] and y >= point[1] for x, y in front):
return front
return tuple(sorted([point, *((x, y) for x, y in front if x > point[0] or y > point[1])]))
def _discount(point, front, gain, rate):
target = gain * rate
if target == 0.:
return (0., 0.)
low, high = 0., 1.
for _ in range(48):
middle = (low + high) / 2
scaled = (point[0] * middle, point[1] * middle)
if _gain(scaled, front) < target:
low = middle
else:
high = middle
return point[0] * high, point[1] * high
## @brief Rank CMA candidates by their improvement over annealed Pareto thresholds.
[docs]
@registry.register
class MOCMAMAE(_CMAEmitter):
"""Two-objective MO-CMA-MAE with a dynamic threshold archive.
Each candidate is scored against its cell's current threshold front, in
proposal order. The learning rate determines how much hypervolume of
an improvement is inserted into the threshold front. The reporting
ParetoGrid stores original, nondominated measurements.
:param container: Two-objective ParetoGrid with declared objective directions.
:param budget: Number of attempted candidate evaluations.
:param x0: Initial genome centre, with at least two coordinates.
:param sigma0: Initial CMA step size.
:param batch_size: Population size, at least two.
:param reference: Hypervolume reference in raw objective units. Candidate
objectives must be at least as good as the reference in both coordinates.
:param learning_rate: Fraction of the hypervolume improvement applied to the
threshold front, in [0, 1]. Zero freezes thresholds and one applies full gain.
:param ind_domain: Optional shared genome bounds.
:param seed: Optional private random seed for CMA and restarts.
"""
def __init__(self, container, budget, x0, sigma0, batch_size, reference, *,
learning_rate=.1, ind_domain=None, seed=None, **kwargs):
try:
import cma
except ImportError as error:
raise ImportError("MOCMAMAE requires the QDpy 'cma' extra.") from error
if not isinstance(container, ParetoGrid) or len(container.fitness_domain) != 2:
raise ValueError("MOCMAMAE requires a two-objective ParetoGrid.")
self.x0 = np.asarray(x0, dtype=float).copy()
if self.x0.ndim != 1 or self.x0.size < 2 or not np.isfinite(self.x0).all():
raise ValueError("x0 must be a finite vector with at least two coordinates.")
if not (0 < sigma0 < np.inf and 0 <= learning_rate <= 1):
raise ValueError("Use a positive finite sigma0 and learning_rate in [0, 1].")
batch_size = _positive_int(batch_size, "batch_size")
if batch_size < 2:
raise ValueError("MOCMAMAE needs at least two candidates per population.")
reference = np.asarray(reference, dtype=float)
if reference.shape != (2,) or not np.isfinite(reference).all():
raise ValueError("Use a finite two-objective reference point.")
self.reference = tuple(reference)
self.ind_domain = None if ind_domain is None else _bounds(ind_domain)
if self.ind_domain is not None and not np.all(np.clip(self.x0, *self.ind_domain) == self.x0):
raise ValueError("x0 lies outside the genome bounds.")
self.sigma0, self.learning_rate, self.seed = sigma0, learning_rate, seed
kwargs.setdefault("optimisation_task", container.fitness_weights)
super().__init__(container, _positive_int(budget, "budget"), batch_size=batch_size,
dimension=len(self.x0), **kwargs)
for individual in container:
self._point(individual)
def reinit(self):
"""Reset the emitter and threshold fronts while retaining reported elites."""
super().reinit()
self._threshold_fronts = {}
self._strategy = None
self._vectors = ()
self._gains = ()
self._rng = random.Random(self.seed) if self.seed is not None else None
## @brief Read the annealed objective front in raw objective coordinates.
[docs]
def threshold_front(self, cell):
"""Return the threshold points in the original objective units."""
direction = tuple(np.sign(self._fitness_weights))
return tuple(tuple(ref + sign * value for ref, sign, value in zip(self.reference, direction, point))
for point in self._threshold_fronts.get(cell, ()))
def _restart_center(self):
if not len(self.container):
return self.x0
center = self._search_rng().choice(self.container)
return center if self.ind_domain is None else np.clip(center, *self.ind_domain)
def _point(self, individual):
values = self.container.get_ind_fitness(individual).values
point = tuple(float(np.sign(weight)) * (float(value) - ref)
for value, ref, weight in zip(values, self.reference, self._fitness_weights))
if len(point) != 2 or min(point) < 0 or not isfinite(point[0] * point[1]):
raise ValueError("Both objectives must dominate the reference and give finite hypervolume.")
return point
def _check_candidate(self, individual):
super()._check_candidate(individual)
self._point(individual)
def _commit_generation(self, evaluated):
self._gains = np.full(len(evaluated), -np.inf)
new = {}
for slot, individual in enumerate(evaluated):
if individual is None:
continue
cell = self.container.index_grid(individual)
point = self._point(individual)
front = self._threshold_fronts.get(cell, ())
gain = self._gains[slot] = _gain(point, front)
if gain > 0:
new[id(individual)] = slot
if self.learning_rate == 1:
self._threshold_fronts[cell] = _insert(point, front)
elif self.learning_rate > 0:
discounted = _discount(point, front, gain, self.learning_rate)
if discounted != (0., 0.):
self._threshold_fronts[cell] = _insert(discounted, front)
admitted = self.container._merge_fronts((evaluated[slot] for slot in new.values()),
truncation_rng=self._search_rng())
if len(evaluated) == self.batch_size and np.isfinite(self._gains).any():
self._adapt_strategy(self._vectors)
return {new[key] for key in admitted}