# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Quality Evolvability ES for a single mutation-ready center.
# @see https://arxiv.org/abs/2103.10790
"""Search for centers with high-quality, behaviourally diverse offspring."""
from bisect import bisect_right
from dataclasses import dataclass
from itertools import groupby
from operator import index
import numpy as np
from scipy.stats import rankdata
from qdpy.containers.pareto import _crowding_distance
from .me_es import _rank_gradient
from .modern import _bounds, _positive_int
__all__ = ["QualityEvolvabilityES", "EvolvabilityESStats", "OffspringSample"]
def _pareto_utilities(fitness, spread):
# Descending lexicographic order is a dominance order. A longest
# nonincreasing chain in the second objective gives each front depth.
order = np.lexsort((-spread, -fitness))
tails = []
fronts = []
for (_, second), group in groupby(order, key=lambda i: (fitness[i], spread[i])):
slots = list(group)
depth = bisect_right(tails, -second)
if depth == len(tails):
tails.append(-second)
fronts.append([])
else:
tails[depth] = -second
fronts[depth].extend(slots)
utilities = np.empty(len(fitness))
remaining = len(fitness)
for front in fronts:
points = np.column_stack((fitness[front], spread[front]))
unique, inverse = np.unique(points, axis=0, return_inverse=True)
remaining -= len(front)
utilities[front] = rankdata(_crowding_distance(unique)[inverse], method="average") + remaining
return utilities
## @brief Cumulative search attempts and committed ES updates.
[docs]
@dataclass(frozen=True)
class EvolvabilityESStats:
"""Count training evaluator calls, including attempts that raise."""
evaluations: int
updates: int
## @brief Independent offspring measurements around a fixed center.
[docs]
@dataclass(frozen=True)
class OffspringSample:
"""Keep quality scores and corresponding descriptors in sampling order."""
fitness: tuple[float, ...]
descriptors: tuple[tuple[float, ...], ...]
## @brief Optimize one center by Pareto-ranking quality and descriptor displacement.
[docs]
class QualityEvolvabilityES:
"""Run mirrored ES with centered Pareto ranks and an Adam ascent step.
Evolvability is squared descriptor distance from the current offspring
mean. Normalize descriptor axes in the evaluator if their units differ.
Search optimizes the mutation distribution with one fixed sigma. It
maintains a single center and evaluates offspring around it.
:param x0: Finite initial parameter vector.
:param pairs: Number of mirrored perturbation pairs per ES update.
:param sigma: Gaussian standard deviation for mutation.
:param learning_rate: Adam ascent step size.
:param l2: Nonnegative L2 coefficient applied to the gradient.
:param maximize: Maximize fitness if true, minimize otherwise.
:param quality_only: Run the matched fitness-only ES control if true.
:param ind_domain: Optional common inclusive parameter bounds.
:param seed: Private seed for mirrored noise and evaluator seeds.
"""
def __init__(self, x0, *, pairs=16, sigma=.1, learning_rate=.03, l2=.005,
maximize=True, quality_only=False, ind_domain=None, seed=0):
self._center = np.array(x0, dtype=float, copy=True)
if self._center.ndim != 1 or not len(self._center) or not np.isfinite(self._center).all():
raise ValueError("x0 must be a nonempty finite parameter vector.")
if not (0 < sigma < np.inf and 0 < learning_rate < np.inf and 0 <= l2 < np.inf):
raise ValueError("Use a finite positive sigma and learning rate, and finite nonnegative l2.")
self._domain = None if ind_domain is None else _bounds(ind_domain)
if self._domain is not None and np.any(self._center != self._bounded(self._center)):
raise ValueError("x0 must be inside ind_domain.")
self._pairs = _positive_int(pairs, "pairs")
self._sigma, self._rate, self._l2 = sigma, learning_rate, l2
self._direction = 1. if maximize else -1.
self._quality_only = quality_only
self._noise, self._seeds = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
self._moment = np.zeros_like(self._center)
self._variance = np.zeros_like(self._center)
self._calls = self._updates = 0
self._descriptor_size = None
## @brief Return a copy of the current parameters.
@property
def center(self):
"""Return a copy of the center, which can be used with a new evaluator."""
return self._center.copy()
## @brief Return the training evaluator and ES update counts.
@property
def stats(self):
"""Return cumulative search statistics."""
return EvolvabilityESStats(self._calls, self._updates)
def _bounded(self, points):
return points if self._domain is None else np.clip(points, *self._domain)
def _measure(self, evaluate, points, rng, *, training):
fitness, descriptors = [], []
width = self._descriptor_size
for point in points:
if not np.isfinite(point).all():
raise ValueError("ES generated nonfinite parameters. Reduce sigma or learning_rate.")
if training:
self._calls += 1
reward, descriptor = evaluate(tuple(point), int(rng.integers(2**32)))
reward, descriptor = float(reward), np.asarray(descriptor, dtype=float)
if (not np.isfinite(reward) or descriptor.ndim != 1 or not len(descriptor)
or not np.isfinite(descriptor).all()):
raise ValueError("Return finite fitness and a nonempty finite descriptor vector.")
if width is None:
width = len(descriptor)
elif len(descriptor) != width:
raise ValueError("Descriptor dimensions must remain fixed.")
fitness.append(reward)
descriptors.append(tuple(descriptor))
if training:
self._descriptor_size = width
return OffspringSample(tuple(fitness), tuple(descriptors))
## @brief Use an additional budget of offspring evaluations, in complete mirrored batches.
# @param evaluate Callable of (parameters, rollout_seed) returning (fitness, descriptors).
# @param budget Maximum additional training calls.
# @return Cumulative EvolvabilityESStats.
[docs]
def run(self, evaluate, budget):
"""Use up to budget calls. Any remainder smaller than 2*pairs stays unspent."""
budget = index(budget)
if budget < 0:
raise ValueError("budget must be nonnegative.")
for _ in range(budget // (2 * self._pairs)):
noise = self._noise.normal(size=(self._pairs, len(self._center)))
points = self._bounded(self._center + self._sigma * np.concatenate((noise, -noise)))
sample = self._measure(evaluate, points, self._seeds, training=True)
quality = self._direction * np.asarray(sample.fitness)
scores = quality
if not self._quality_only:
features = np.asarray(sample.descriptors)
features /= np.abs(features).max() or 1.
spread = np.square(features - features.mean(axis=0)).sum(axis=1)
scores = _pareto_utilities(quality, spread)
gradient = _rank_gradient(noise, scores, self._sigma) - self._l2 * self._center
step = self._updates + 1
moment = .9 * self._moment + .1 * gradient
variance = .999 * self._variance + .001 * np.square(gradient)
move = self._rate * (moment / (1. - .9**step)) / (np.sqrt(variance / (1. - .999**step)) + 1e-8)
center = self._bounded(self._center + move)
if not (np.isfinite(center).all() and np.isfinite(variance).all()):
raise ValueError("ES update overflowed. Reduce the gradient scale.")
self._center, self._moment, self._variance = center, moment, variance
self._updates = step
return self.stats
## @brief Measure fresh, independently drawn offspring without changing the search streams.
# @param evaluate Callable with the same contract as run().
# @param count Number of fresh offspring to evaluate.
# @param seed Seed for independent mutation and evaluation.
# @return OffspringSample with exactly count rows.
[docs]
def sample_offspring(self, evaluate, count, *, seed):
"""Measure an independent sample around the current center using the training sigma."""
count = _positive_int(count, "count")
noise, seeds = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
points = self._bounded(self._center + self._sigma * noise.normal(size=(count, len(self._center))))
return self._measure(evaluate, points, seeds, training=False)