# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Map-based Bayesian optimization over an existing numeric repertoire.
"""Adapt a repertoire by testing its existing policies in a new setting."""
from collections.abc import Mapping
from dataclasses import dataclass
import json
from numbers import Real
from os import PathLike
from pathlib import Path
import numpy as np
from scipy.linalg import cholesky, cho_solve, solve_triangular
from scipy.spatial.distance import cdist
from qdpy._archive_data import _archive_data
from qdpy.results import _decode_float
from .modern import _positive_int
__all__ = ["MBOA", "MBOACandidate", "MBOATrial"]
## @brief One source repertoire entry and its original measurement.
[docs]
@dataclass(frozen=True)
class MBOACandidate:
index: int
genome: tuple
descriptor: tuple[float, ...]
prior_fitness: float
## @brief One attempted new measurement, with None representing a failed trial.
[docs]
@dataclass(frozen=True)
class MBOATrial:
candidate: MBOACandidate
fitness: float | None
def _repertoire(source):
if isinstance(source, (str, PathLike)):
source = json.loads(Path(source).read_text(encoding="utf-8"), object_hook=_decode_float)
geometry = _archive_data(source)
if isinstance(source, Mapping):
if source["archive_type"] not in ("Grid", "CVTGrid", "SlidingBoundariesGrid") or any("genome" not in row for row in source["entries"]):
raise ValueError("Use a numeric grid export containing its genomes.")
genomes = tuple(tuple(row["genome"]) for row in source["entries"])
else:
genomes = tuple(map(tuple, source))
if (not geometry.entries or not geometry.dimension or len(genomes) != len(geometry.entries)
or any(len(row.fitness) != 1 or len(row.fitness_weights) != 1 for row in geometry.entries)):
raise ValueError("M-BOA requires a nonempty numeric repertoire with one objective and descriptors.")
weights = [row.fitness_weights[0] for row in geometry.entries]
directions = np.sign(weights)
if not np.all(np.isfinite(weights)) or directions[0] == 0 or not np.all(directions == directions[0]):
raise ValueError("Use a consistent, nonzero objective direction for the repertoire.")
if not all(isinstance(value, (Real, np.bool_)) for genome in genomes for value in genome):
raise ValueError("Use fixed-length numeric repertoire genomes.")
try:
encoding = np.asarray(genomes, dtype=float)
except (OverflowError, TypeError, ValueError) as error:
raise ValueError("Use fixed-length numeric repertoire genomes.") from error
if encoding.ndim != 2 or not encoding.shape[1] or not np.isfinite(encoding).all():
raise ValueError("Use nonempty finite numeric repertoire genomes of the same length.")
rows = tuple(MBOACandidate(i, genome, entry.descriptors, entry.fitness[0])
for i, (genome, entry) in enumerate(zip(genomes, geometry.entries)))
return rows, directions[0], geometry.descriptor_domain
## @brief Use a Matérn residual model to select existing elites for deployment trials.
[docs]
class MBOA:
"""Map-based Bayesian optimization using original fitness as the prior mean.
The repertoire stays fixed. The posterior combines its nominal scores
with measured residuals in the new conditions. Upper confidence bounds
rank the available entries. All returned fitnesses use the raw units.
:param repertoire: Live numeric container, numeric grid JSON
export path, or the decoded JSON mapping.
:param budget: Maximum number of adaptation trials.
:param length_scale: Positive Matérn-5/2 length scale, in normalized
descriptor coordinates. Axes without finite bounds use raw units.
:param kappa: Nonnegative exploration coefficient.
:param noise_variance: Positive observation variance in squared fitness units.
:param signal_variance: Positive GP variance in squared fitness units.
:param allow_repeats: Permit more than one new trial per repertoire entry.
"""
def __init__(self, repertoire, budget, *, length_scale=.4, kappa=.05,
noise_variance=.001, signal_variance=1., allow_repeats=False):
self.candidates, self._sign, bounds = _repertoire(repertoire)
self.budget = _positive_int(budget, "budget")
values = (length_scale, noise_variance, signal_variance, kappa)
if not np.isfinite(values).all() or min(values[:3]) <= 0 or kappa < 0:
raise ValueError("Use positive finite GP scales and a nonnegative exploration coefficient.")
self._rho, self._noise, self._signal, self._kappa = values
self._repeat = allow_repeats
self._prior = np.array([row.prior_fitness for row in self.candidates])
self._points = np.array([row.descriptor for row in self.candidates])
if not np.isfinite(self._prior).all() or not np.isfinite(self._points).all():
raise ValueError("Repertoire fitness and descriptors must be finite.")
for axis, (lower, upper) in enumerate(bounds):
if np.isfinite((lower, upper)).all() and lower < upper:
factor = .5 if not np.isfinite(upper - lower) else 1.
self._points[:, axis] = ((self._points[:, axis] * factor - lower * factor)
/ (upper * factor - lower * factor))
self._trials = []
self._observed = []
self._attempted = np.zeros(len(self.candidates), dtype=bool)
self._pending = None
@property
def trials(self):
"""Return the attempted trials in their original order."""
return tuple(self._trials)
@property
def best(self):
"""Return the best genuine adaptation trial, or None before a success."""
return max(self._observed, key=lambda trial: self._sign * trial.fitness, default=None)
def _kernel(self, first, second):
with np.errstate(over="ignore", invalid="ignore"):
distance = np.sqrt(5.) * cdist(first, second) / self._rho
# Beyond this point the kernel has decayed below floating-point range.
distance = np.minimum(distance, 800.)
return self._signal * ((1. + distance + distance ** 2 / 3.) * np.exp(-distance))
## @brief Return the current posterior over the repertoire.
[docs]
def posterior(self):
"""Return posterior mean in raw fitness units and standard deviation."""
if not self._observed:
return self._prior.copy(), np.full(len(self.candidates), np.sqrt(self._signal))
indices = np.array([trial.candidate.index for trial in self._observed])
residual = np.array([trial.fitness for trial in self._observed]) - self._prior[indices]
locations = self._points[indices]
covariance = self._kernel(locations, locations)
diagonal = np.diag_indices_from(covariance)
covariance[diagonal] += self._noise
try:
factor = cholesky(covariance, lower=True)
except np.linalg.LinAlgError:
# A user-specified noise much smaller than the signal can round
# away when multiple trials share one descriptor.
covariance[diagonal] += np.spacing(self._signal) * len(locations)
factor = cholesky(covariance, lower=True)
cross = self._kernel(locations, self._points)
projections = solve_triangular(factor, cross, lower=True)
mean = self._prior + cross.T @ cho_solve((factor, True), residual)
variance = self._signal - np.sum(projections ** 2, axis=0)
return mean, np.sqrt(np.maximum(variance, 0.))
## @brief Select one candidate for a real trial.
[docs]
def ask(self):
"""Return the next candidate or raise StopIteration when out of trials."""
if self._pending is not None:
raise RuntimeError("Report the pending trial before asking again.")
if len(self._trials) >= self.budget or (not self._repeat and self._attempted.all()):
raise StopIteration("No adaptation trials remain.")
mean, deviation = self.posterior()
scores = self._sign * mean + self._kappa * deviation
if not self._repeat:
scores[self._attempted] = -np.inf
self._pending = self.candidates[int(np.argmax(scores))]
return self._pending
## @brief Record the one pending observation and spend its trial budget.
[docs]
def tell(self, fitness):
"""Record a finite raw fitness or None if the trial failed."""
if self._pending is None:
raise RuntimeError("Ask for a candidate before reporting a trial.")
if fitness is not None:
fitness = float(fitness)
if not np.isfinite(fitness):
raise ValueError("Report a finite fitness or None for a failed trial.")
trial = MBOATrial(self._pending, fitness)
self._attempted[self._pending.index] = True
self._trials.append(trial)
if fitness is not None:
self._observed.append(trial)
self._pending = None
return trial
## @brief Spend the remaining budget with a caller-supplied evaluation function.
[docs]
def run(self, evaluate):
"""Evaluate each selected numeric genome and return the best measured trial."""
while True:
try:
candidate = self.ask()
except StopIteration:
return self.best
self.tell(evaluate(candidate.genome))