# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief MAP-Elites driven by antithetic evolution-strategy updates.
"""Evaluate perturbation batches and separately admit measured ES centers."""
from math import isfinite
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import rankdata
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _bounds, _positive_int
__all__ = ["MEES"]
def _rank_gradient(noise, scores, sigma):
"""Compute the ascent direction from paired scores and centered ranks."""
ranks = (rankdata(scores, method="average") - 1) / (len(scores) - 1) - .5
first, second = np.split(ranks, 2)
return (first - second) @ noise / (len(scores) * sigma)
## @brief Alternate ES quality and novelty updates from an archive of measured centers.
[docs]
class MEES:
"""Black-box MAP-Elites with Evolution Strategies.
Perturbation measurements guide an Adam update. Independently evaluate
the resulting center before offering it to the grid. Novelty uses the
descriptors of previously evaluated centers, including rejected ones.
:param archive: Best-only Grid or CVTGrid with one finite nonzero fitness weight.
:param x0: Initial parameter vector.
:param pairs: Number of antithetic Gaussian pairs per ES step.
:param block_steps: Number of ES steps before selecting a new elite.
:param mode: "exploit", "explore", or "explore-exploit" (alternating blocks).
:param evaluations_per_center: Number of rollouts averaged per center.
:param sigma: Gaussian standard deviation.
:param learning_rate: Adam step size.
:param l2: Parameter decay included in the ascent gradient.
:param novelty_neighbors: Number of nearest center descriptors for novelty.
:param ind_domain: Optional common lower and upper parameter bounds.
:param seed: Private random seed.
"""
def __init__(self, archive, x0, *, pairs=16, block_steps=5, mode="explore-exploit",
evaluations_per_center=1, sigma=.05, learning_rate=.03, l2=.005,
novelty_neighbors=10, ind_domain=None, seed=0):
if (not isinstance(archive, Grid) or archive.max_items_per_bin != 1 or archive.parents
or archive.discard_random_on_bin_overload or len(archive.fitness_domain or ()) != 1
or not archive.fitness_weights or len(archive.fitness_weights) != 1
or not isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]):
raise ValueError("Supply a parentless best-only grid with one signed fitness objective.")
self._x0 = np.asarray(x0, dtype=float).copy()
if self._x0.ndim != 1 or not self._x0.size or not np.isfinite(self._x0).all():
raise ValueError("x0 must be a nonempty finite vector.")
if not (0 < sigma < np.inf and 0 < learning_rate < np.inf and 0 <= l2 < np.inf):
raise ValueError("Use positive finite sigma and learning rate and a nonnegative penalty.")
if mode not in ("exploit", "explore", "explore-exploit"):
raise ValueError("Choose exploit, explore, or explore-exploit.")
self.archive, self.mode = archive, mode
self.pairs, self.block_steps = _positive_int(pairs, "pairs"), _positive_int(block_steps, "block_steps")
self.evaluations_per_center = _positive_int(evaluations_per_center, "evaluations_per_center")
self.novelty_neighbors = _positive_int(novelty_neighbors, "novelty_neighbors")
self.sigma, self.learning_rate, self.l2 = sigma, learning_rate, l2
self._bounds = None if ind_domain is None else _bounds(ind_domain)
if not np.array_equal(self._bounded(self._x0), self._x0):
raise ValueError("x0 lies outside ind_domain.")
for elite in archive:
vector = np.asarray(elite, dtype=float)
if vector.shape != self._x0.shape or not np.isfinite(vector).all() or not np.array_equal(
self._bounded(vector), vector):
raise ValueError("Warm-start elites must match x0 and its bounds.")
self._direction = np.sign(archive.fitness_weights[0])
self._rng = np.random.default_rng(seed)
self._history = [tuple(archive.get_ind_features(ind)) for ind in archive]
self._center = None
self._step = self._completed = self._perturbations = self._center_calls = 0
@property
def evaluations(self):
"""Return attempted perturbation and center evaluations combined."""
return self._perturbations + self._center_calls
@property
def center_evaluations(self):
"""Return attempted center rollouts, including initialization."""
return self._center_calls
@property
def updates(self):
"""Return the number of completed ES steps."""
return self._completed
def _bounded(self, point):
return point if self._bounds is None else np.clip(point, *self._bounds)
def _measure(self, evaluate, points, executor, *, center):
genomes = [tuple(map(float, point)) for point in points]
counter = "_center_calls" if center else "_perturbations"
submitted = []
for genome in genomes:
if executor is None:
setattr(self, counter, getattr(self, counter) + 1)
submitted.append(evaluate(genome))
else:
submitted.append(executor.submit(evaluate, genome))
setattr(self, counter, getattr(self, counter) + 1)
results = submitted if executor is None else [future.result() for future in submitted]
measured = []
for result in results:
if result is None:
measured.append(None)
continue
fitness, features = result
values = np.asarray(fitness)
if values.shape not in ((), (1,)):
raise ValueError("MEES requires one fitness objective.")
fitness, features = float(values.item()), tuple(map(float, features))
if (len(features) != len(self.archive.features_domain) or not np.isfinite(features).all()
or not isfinite(fitness)):
raise ValueError("Use finite measurements matching the archive or return None.")
measured.append((fitness, features))
return measured
def _record(self, evaluate, point, executor):
results = self._measure(evaluate, [point] * self.evaluations_per_center, executor, center=True)
if any(row is None for row in results):
return
fitness, features = zip(*results)
value = sum(raw / len(fitness) for raw in fitness)
descriptors = tuple(np.sum(np.asarray(features) / len(features), axis=0))
self._history.append(descriptors)
if (self.archive.in_bounds((value,), self.archive.fitness_domain)
and self.archive.in_bounds(descriptors, self.archive.features_domain)):
cell = self.archive.index_grid(descriptors)
if self.archive.free > 0 or self.archive.solutions[cell]:
self.archive.add(Individual(point.tolist(), fitness=Fitness((value,), weights=self.archive.fitness_weights),
features=Features(descriptors)))
def _novelty(self, descriptors):
if not self._history:
return np.zeros(len(descriptors))
distances = cdist(descriptors, self._history)
count = min(self.novelty_neighbors, len(self._history))
return np.partition(distances, count - 1, axis=1)[:, :count].mean(axis=1)
def _start_block(self):
self._exploring = self.mode == "explore" or (
self.mode == "explore-exploit" and self._completed // self.block_steps % 2 == 0)
elites = list(self.archive)
if not elites:
self._center = self._x0.copy() if self._center is None else self._center
elif self._exploring:
descriptors = [tuple(self.archive.get_ind_features(ind)) for ind in elites]
novelty = self._novelty(descriptors)
top = np.argsort(-novelty, kind="stable")[:5]
weights = novelty[top]
choice = self._rng.choice(top, p=weights / weights.sum() if np.any(weights) else None)
self._center = np.asarray(elites[choice], dtype=float)
else:
if self._rng.random() < .5:
elites = [row[1] for row in sorted(zip(self.archive.recentness, elites),
key=lambda row: -row[0])[:5]]
ranked = sorted(elites, key=lambda ind: self._direction * self.archive.get_ind_fitness(ind).values[0],
reverse=True)
self._center = np.asarray(ranked[self._rng.integers(min(2, len(ranked)))], dtype=float)
self._first = np.zeros_like(self._center)
self._second = np.zeros_like(self._center)
self._step = 0
def _update(self, evaluate, executor):
noise = self._rng.normal(size=(self.pairs, len(self._center)))
points = self._bounded(self._center + self.sigma * np.concatenate((noise, -noise)))
rows = self._measure(evaluate, points, executor, center=False)
paired = [i for i in range(self.pairs) if rows[i] is not None and rows[i + self.pairs] is not None]
self._step += 1
if paired:
feedback = [rows[i + offset] for offset in (0, self.pairs) for i in paired]
quality, descriptors = zip(*feedback)
scores = self._novelty(descriptors) if self._exploring else self._direction * np.array(quality)
grad = _rank_gradient(noise[paired], scores, self.sigma) - self.l2 * self._center
self._first += .1 * (grad - self._first)
self._second += .001 * (grad ** 2 - self._second)
first = self._first / (1 - .9 ** self._step)
second = self._second / (1 - .999 ** self._step)
self._center = self._bounded(self._center + self.learning_rate * first / (np.sqrt(second) + 1e-8))
self._record(evaluate, self._center, executor)
self._completed += 1
## @brief Spend an additional budget on whole ES and center evaluation batches.
[docs]
def run(self, evaluate, budget, *, executor=None):
"""Return the result archive after using at most budget evaluator calls.
Return (scalar fitness, descriptors) or None for a failed rollout.
A caller-owned executor must support submit and Future.result.
Feedback order follows submission order.
"""
stop = self.evaluations + _positive_int(budget, "budget")
if self._center is None and stop - self.evaluations >= self.evaluations_per_center:
self._center = self._x0.copy()
self._record(evaluate, self._center, executor)
cost = 2 * self.pairs + self.evaluations_per_center
while self.evaluations + cost <= stop:
if self._completed % self.block_steps == 0:
self._start_block()
self._update(evaluate, executor)
return self.archive