# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Alternate model-based MAP-Elites and gradient refinement with archive dropout.
# @see https://wrap.warwick.ac.uk/id/eprint/189556/1/WRAP_Theses_Kent_2024.pdf
"""Gradient-Augmented MAP-Elites over a differentiable frozen surrogate."""
from dataclasses import dataclass
from operator import index
import numpy as np
from scipy.linalg import cho_solve
from scipy.stats import qmc
from qdpy.phenotype import Features, Fitness, Individual
from qdpy.tools import iso_line_dd
from .modern import _positive_int
from .offline import OfflineMAPElites, OfflineSearchResult, _empty_geometry, _insert
__all__ = ["GradientAugmentedMAPElites", "GAMESearchResult"]
## @brief Report prediction calls per search phase and drops from the breeding archive.
[docs]
@dataclass(frozen=True)
class GAMESearchResult(OfflineSearchResult):
"""Keep the best predicted elites across all cycles and dropout events."""
targeting_predictions: int
refinement_predictions: int
dropped_elites: int
def _matern_jacobian(point, centers, coefficients, length):
"""Differentiate the Matérn-5/2 mean at a normalized decision vector."""
# Use unit directions before the derivative to limit intermediate scaling.
with np.errstate(over="ignore"):
offsets = (point - centers) / length
radius = np.sqrt(5.) * np.linalg.norm(offsets, axis=1)
active = (radius > 0.) & (radius <= 700.)
derivative = np.zeros_like(centers)
distance = radius[active]
with np.errstate(over="ignore"):
scale = -(5. / 3.) * ((1. + distance) * np.exp(-distance)) / length
derivative[active] = scale[:, None] * offsets[active]
return derivative.T @ coefficients
## @brief Refine frozen-model elites while preserving a separate best-seen archive.
[docs]
class GradientAugmentedMAPElites(OfflineMAPElites):
"""Build a surrogate prediction map following Kent's GA-ME.
Target Sobol descriptor points from nearby logged designs. Alternate
variation with local ascent on newly improved elites. Accept refinement
moves that improve predicted fitness within the original cell.
Drop random breeders between cycles and retain a separate result
archive. Search charges every surrogate query, including gradients
and rejected moves. Inherited verify() measures selected designs
independently.
:param archive: Empty best-only Grid or CVTGrid with finite descriptor bounds.
:param genomes: Matrix of real-valued logged genomes.
:param fitnesses: One scalar outcome per logged genome.
:param descriptors: One measured descriptor vector per logged genome.
:param kwargs: OfflineMAPElites genome, kernel, mutation, and seed settings.
GA-ME searches posterior means. Use the default uncertainty_weight=0.
"""
def __init__(self, archive, genomes, fitnesses, descriptors, **kwargs):
if kwargs.get("uncertainty_weight", 0.) != 0.:
raise ValueError("GA-ME refines posterior means. Set uncertainty_weight=0.")
super().__init__(archive, genomes, fitnesses, descriptors, **kwargs)
bounds = np.asarray(archive.features_domain, dtype=float)
with np.errstate(over="ignore"):
spans = bounds[:, 1] - bounds[:, 0]
if not np.all(np.isfinite(spans) & (spans > 0.)):
raise ValueError("GA-ME needs finite positive descriptor spans.")
self._feature_low, self._feature_span = bounds[:, 0].copy(), spans
self._logged_features = (np.asarray(descriptors, dtype=float) - self._feature_low) / spans
outputs = np.column_stack((fitnesses, descriptors))
# Public L_ already factorizes the fixed kernel. Solving in raw
# units recovers coefficients without scikit-learn's private scales.
self._coefficients = cho_solve((self._model.L_, True), outputs - outputs.mean(axis=0))
def _prediction(self, point, gradient):
normalized = self._normalized(np.asarray(point))
means, deviations = self._model.predict(normalized[None], return_std=True)
mean, *features = means[0]
deviation = deviations[0, 0]
if not np.isfinite((mean, deviation, *features)).all():
raise ValueError("The frozen surrogate produced a nonfinite prediction.")
candidate = Individual(list(point), fitness=Fitness((mean,), weights=self._source.fitness_weights),
features=Features(features),
scores={"predicted_fitness": float(mean), "prediction_std": float(deviation)})
jacobian = None
if gradient:
jacobian = _matern_jacobian(normalized, self._model.X_train_, self._coefficients,
self._model.kernel_.length_scale)
if not np.isfinite(jacobian).all():
raise ValueError("The frozen surrogate produced a nonfinite gradient.")
return candidate, jacobian
def _move(self, point, direction, rate):
scale = np.max(np.abs(direction))
if not scale:
return None
unit = direction / scale
normalized = self._normalized(np.asarray(point))
moved = self.ind_domain[0] + self._width * np.clip(normalized + rate * unit / np.linalg.norm(unit), 0., 1.)
moved = np.clip(moved, *self.ind_domain)
return None if np.array_equal(moved, point) else moved
## @brief Spend one shared surrogate budget on targeting, variation, and refinement.
# @return GAMESearchResult compatible with OfflineMAPElites.verify().
[docs]
def run(self, budget, *, initial_samples=16, targeting_steps=3, mutation_steps=24, refinement_steps=3,
dropout=.25, step_size=.08):
"""Return an independently reproducible prediction map.
Target at most initial_samples descriptor points, each using
up to targeting_steps gradient moves. Each cycle uses mutation_steps
evaluated candidates, then up to refinement_steps moves for each
new elite. Set either gradient phase to zero for ablation.
"""
budget = _positive_int(budget, "budget")
initial = _positive_int(initial_samples, "initial_samples")
mutation = _positive_int(mutation_steps, "mutation_steps")
targeting, refinement = index(targeting_steps), index(refinement_steps)
if min(targeting, refinement) < 0 or not (0 <= dropout <= 1 and 0 < step_size < np.inf):
raise ValueError("Use nonnegative gradient steps, dropout in [0, 1], and a positive finite step size.")
active, report = _empty_geometry(self._source), _empty_geometry(self._source)
geometry, rng = map(np.random.default_rng, np.random.SeedSequence(self.seed).spawn(2))
sobol = qmc.Sobol(len(self._feature_span), scramble=True, seed=int(geometry.integers(2**32)))
seed_order = rng.permutation(len(self._genomes))
used = target_cost = refine_cost = drops = 0
def measure(point, gradient=False):
nonlocal used
used += 1
return self._prediction(point, gradient)
def offer(candidate):
_insert(report, candidate)
before = active.nb_added
cell = _insert(active, candidate)
return cell if before != active.nb_added else None
for slot in range(min(initial, budget)):
target = sobol.random(1)[0]
if targeting:
offsets = self._logged_features - target
first = np.argmin(np.linalg.norm(offsets, axis=1))
else:
first = seed_order[slot % len(seed_order)]
point = self._genomes[first]
start = used
for step in range(targeting + 1):
if used == budget:
break
candidate, jacobian = measure(point, step < targeting)
offer(candidate)
if jacobian is None:
break
distance = (np.asarray(candidate.features.values) - self._feature_low) / self._feature_span - target
point = self._move(point, -(jacobian[:, 1:] / self._feature_span) @ distance, step_size)
if point is None:
break
target_cost += used - start
if used == budget:
break
while used < budget:
changed = {}
for _ in range(min(mutation, budget - used)):
if active:
first, second = rng.integers(len(active), size=2)
point = iso_line_dd(active[first], active[second], bounds=self.ind_domain,
iso_sigma=self._iso_sigma, line_sigma=self._line_sigma, rng=rng)
else:
point = rng.uniform(*self.ind_domain, size=self._genomes.shape[1])
candidate, _ = measure(point)
cell = offer(candidate)
if cell is not None:
changed[cell] = candidate
for cell, incumbent in changed.items():
rate = step_size
for _ in range(refinement):
if budget - used < 2:
break
_, jacobian = measure(incumbent, True)
refine_cost += 1
point = self._move(incumbent, self._direction * jacobian[:, 0], rate)
if point is None:
break
candidate, _ = measure(point)
refine_cost += 1
features = candidate.features.values
if (active.in_bounds(features, active.features_domain) and active.index_grid(features) == cell
and candidate.fitness.dominates(incumbent.fitness)):
if offer(candidate) is not None:
incumbent = candidate
continue
rate *= .5
if used < budget and dropout and active:
# Draw independently for each retained breeding elite.
for candidate in list(active):
if rng.random() < dropout:
active.discard(candidate)
drops += 1
return GAMESearchResult(report, used, target_cost, refine_cost, drops)