5"""Adapt a repertoire by testing its existing policies in a new setting."""
7from collections.abc
import Mapping
8from dataclasses
import dataclass
10from numbers
import Real
11from os
import PathLike
12from pathlib
import Path
15from scipy.linalg
import cholesky, cho_solve, solve_triangular
16from scipy.spatial.distance
import cdist
20from .modern
import _positive_int
22__all__ = [
"MBOA",
"MBOACandidate",
"MBOATrial"]
26@dataclass(frozen=True)
30 descriptor: tuple[float, ...]
35@dataclass(frozen=True)
37 candidate: MBOACandidate
41def _repertoire(source):
42 if isinstance(source, (str, PathLike)):
43 source = json.loads(Path(source).read_text(encoding=
"utf-8"), object_hook=_decode_float)
44 geometry = _archive_data(source)
45 if isinstance(source, Mapping):
46 if source[
"archive_type"]
not in (
"Grid",
"CVTGrid",
"SlidingBoundariesGrid")
or any(
"genome" not in row
for row
in source[
"entries"]):
47 raise ValueError(
"Use a numeric grid export containing its genomes.")
48 genomes = tuple(tuple(row[
"genome"])
for row
in source[
"entries"])
50 genomes = tuple(map(tuple, source))
51 if (
not geometry.entries
or not geometry.dimension
or len(genomes) != len(geometry.entries)
52 or any(len(row.fitness) != 1
or len(row.fitness_weights) != 1
for row
in geometry.entries)):
53 raise ValueError(
"M-BOA requires a nonempty numeric repertoire with one objective and descriptors.")
54 weights = [row.fitness_weights[0]
for row
in geometry.entries]
55 directions = np.sign(weights)
56 if not np.all(np.isfinite(weights))
or directions[0] == 0
or not np.all(directions == directions[0]):
57 raise ValueError(
"Use a consistent, nonzero objective direction for the repertoire.")
58 if not all(isinstance(value, (Real, np.bool_))
for genome
in genomes
for value
in genome):
59 raise ValueError(
"Use fixed-length numeric repertoire genomes.")
61 encoding = np.asarray(genomes, dtype=float)
62 except (OverflowError, TypeError, ValueError)
as error:
63 raise ValueError(
"Use fixed-length numeric repertoire genomes.")
from error
64 if encoding.ndim != 2
or not encoding.shape[1]
or not np.isfinite(encoding).all():
65 raise ValueError(
"Use nonempty finite numeric repertoire genomes of the same length.")
66 rows = tuple(
MBOACandidate(i, genome, entry.descriptors, entry.fitness[0])
67 for i, (genome, entry)
in enumerate(zip(genomes, geometry.entries)))
68 return rows, directions[0], geometry.descriptor_domain
73 """Map-based Bayesian optimization using original fitness as the prior mean.
75 The repertoire stays fixed. The posterior combines its nominal scores
76 with measured residuals in the new conditions. Upper confidence bounds
77 rank the available entries. All returned fitnesses use the raw units.
79 :param repertoire: Live numeric container, numeric grid JSON
80 export path, or the decoded JSON mapping.
81 :param budget: Maximum number of adaptation trials.
82 :param length_scale: Positive Matérn-5/2 length scale, in normalized
83 descriptor coordinates. Axes without finite bounds use raw units.
84 :param kappa: Nonnegative exploration coefficient.
85 :param noise_variance: Positive observation variance in squared fitness units.
86 :param signal_variance: Positive GP variance in squared fitness units.
87 :param allow_repeats: Permit more than one new trial per repertoire entry.
90 def __init__(self, repertoire, budget, *, length_scale=.4, kappa=.05,
91 noise_variance=.001, signal_variance=1., allow_repeats=False):
93 self.
budget = _positive_int(budget,
"budget")
94 values = (length_scale, noise_variance, signal_variance, kappa)
95 if not np.isfinite(values).all()
or min(values[:3]) <= 0
or kappa < 0:
96 raise ValueError(
"Use positive finite GP scales and a nonnegative exploration coefficient.")
101 if not np.isfinite(self.
_prior).all()
or not np.isfinite(self.
_points).all():
102 raise ValueError(
"Repertoire fitness and descriptors must be finite.")
103 for axis, (lower, upper)
in enumerate(bounds):
104 if np.isfinite((lower, upper)).all()
and lower < upper:
105 factor = .5
if not np.isfinite(upper - lower)
else 1.
106 self.
_points[:, axis] = ((self.
_points[:, axis] * factor - lower * factor)
107 / (upper * factor - lower * factor))
115 """Return the attempted trials in their original order."""
120 """Return the best genuine adaptation trial, or None before a success."""
121 return max(self.
_observed, key=
lambda trial: self.
_sign * trial.fitness, default=
None)
123 def _kernel(self, first, second):
124 with np.errstate(over=
"ignore", invalid=
"ignore"):
125 distance = np.sqrt(5.) * cdist(first, second) / self.
_rho
127 distance = np.minimum(distance, 800.)
128 return self.
_signal * ((1. + distance + distance ** 2 / 3.) * np.exp(-distance))
132 """Return posterior mean in raw fitness units and standard deviation."""
135 indices = np.array([trial.candidate.index
for trial
in self.
_observed])
136 residual = np.array([trial.fitness
for trial
in self.
_observed]) - self.
_prior[indices]
137 locations = self.
_points[indices]
138 covariance = self.
_kernel(locations, locations)
139 diagonal = np.diag_indices_from(covariance)
140 covariance[diagonal] += self.
_noise
142 factor = cholesky(covariance, lower=
True)
143 except np.linalg.LinAlgError:
146 covariance[diagonal] += np.spacing(self.
_signal) * len(locations)
147 factor = cholesky(covariance, lower=
True)
149 projections = solve_triangular(factor, cross, lower=
True)
150 mean = self.
_prior + cross.T @ cho_solve((factor,
True), residual)
151 variance = self.
_signal - np.sum(projections ** 2, axis=0)
152 return mean, np.sqrt(np.maximum(variance, 0.))
156 """Return the next candidate or raise StopIteration when out of trials."""
158 raise RuntimeError(
"Report the pending trial before asking again.")
160 raise StopIteration(
"No adaptation trials remain.")
162 scores = self.
_sign * mean + self.
_kappa * deviation
170 """Record a finite raw fitness or None if the trial failed."""
172 raise RuntimeError(
"Ask for a candidate before reporting a trial.")
173 if fitness
is not None:
174 fitness = float(fitness)
175 if not np.isfinite(fitness):
176 raise ValueError(
"Report a finite fitness or None for a failed trial.")
180 if fitness
is not None:
187 """Evaluate each selected numeric genome and return the best measured trial."""
190 candidate = self.
ask()
191 except StopIteration:
193 self.
tell(evaluate(candidate.genome))
One source repertoire entry and its original measurement.
One attempted new measurement, with None representing a failed trial.
Use a Matérn residual model to select existing elites for deployment trials.
posterior(self)
Return the current posterior over the repertoire.
_kernel(self, first, second)
run(self, evaluate)
Spend the remaining budget with a caller-supplied evaluation function.
ask(self)
Select one candidate for a real trial.
tell(self, fitness)
Record the one pending observation and spend its trial budget.