QDpy
Loading...
Searching...
No Matches
mboa.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Adapt a repertoire by testing its existing policies in a new setting."""
6
7from collections.abc import Mapping
8from dataclasses import dataclass
9import json
10from numbers import Real
11from os import PathLike
12from pathlib import Path
13
14import numpy as np
15from scipy.linalg import cholesky, cho_solve, solve_triangular
16from scipy.spatial.distance import cdist
17
18from qdpy._archive_data import _archive_data
19from qdpy.results import _decode_float
20from .modern import _positive_int
21
22__all__ = ["MBOA", "MBOACandidate", "MBOATrial"]
23
24
25
26@dataclass(frozen=True)
28 index: int
29 genome: tuple
30 descriptor: tuple[float, ...]
31 prior_fitness: float
32
33
34
35@dataclass(frozen=True)
37 candidate: MBOACandidate
38 fitness: float | None
39
40
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"])
49 else:
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.")
60 try:
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
69
70
71
72class MBOA:
73 """Map-based Bayesian optimization using original fitness as the prior mean.
74
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.
78
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.
88 """
89
90 def __init__(self, repertoire, budget, *, length_scale=.4, kappa=.05,
91 noise_variance=.001, signal_variance=1., allow_repeats=False):
92 self.candidates, self._sign, bounds = _repertoire(repertoire)
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.")
97 self._rho, self._noise, self._signal, self._kappa = values
98 self._repeat = allow_repeats
99 self._prior = np.array([row.prior_fitness for row in self.candidates])
100 self._points = np.array([row.descriptor for row in self.candidates])
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))
108 self._trials = []
109 self._observed = []
110 self._attempted = np.zeros(len(self.candidates), dtype=bool)
111 self._pending = None
112
113 @property
114 def trials(self):
115 """Return the attempted trials in their original order."""
116 return tuple(self._trials)
117
118 @property
119 def best(self):
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)
122
123 def _kernel(self, first, second):
124 with np.errstate(over="ignore", invalid="ignore"):
125 distance = np.sqrt(5.) * cdist(first, second) / self._rho
126 # Beyond this point the kernel has decayed below floating-point range.
127 distance = np.minimum(distance, 800.)
128 return self._signal * ((1. + distance + distance ** 2 / 3.) * np.exp(-distance))
129
130
131 def posterior(self):
132 """Return posterior mean in raw fitness units and standard deviation."""
133 if not self._observed:
134 return self._prior.copy(), np.full(len(self.candidates), np.sqrt(self._signal))
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
141 try:
142 factor = cholesky(covariance, lower=True)
143 except np.linalg.LinAlgError:
144 # A user-specified noise much smaller than the signal can round
145 # away when multiple trials share one descriptor.
146 covariance[diagonal] += np.spacing(self._signal) * len(locations)
147 factor = cholesky(covariance, lower=True)
148 cross = self._kernel(locations, self._points)
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.))
153
154
155 def ask(self):
156 """Return the next candidate or raise StopIteration when out of trials."""
157 if self._pending is not None:
158 raise RuntimeError("Report the pending trial before asking again.")
159 if len(self._trials) >= self.budget or (not self._repeat and self._attempted.all()):
160 raise StopIteration("No adaptation trials remain.")
161 mean, deviation = self.posterior()
162 scores = self._sign * mean + self._kappa * deviation
163 if not self._repeat:
164 scores[self._attempted] = -np.inf
165 self._pending = self.candidates[int(np.argmax(scores))]
166 return self._pending
167
168
169 def tell(self, fitness):
170 """Record a finite raw fitness or None if the trial failed."""
171 if self._pending is None:
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.")
177 trial = MBOATrial(self._pending, fitness)
178 self._attempted[self._pending.index] = True
179 self._trials.append(trial)
180 if fitness is not None:
181 self._observed.append(trial)
182 self._pending = None
183 return trial
184
185
186 def run(self, evaluate):
187 """Evaluate each selected numeric genome and return the best measured trial."""
188 while True:
189 try:
190 candidate = self.ask()
191 except StopIteration:
192 return self.best
193 self.tell(evaluate(candidate.genome))
One source repertoire entry and its original measurement.
Definition mboa.py:27
One attempted new measurement, with None representing a failed trial.
Definition mboa.py:36
Use a Matérn residual model to select existing elites for deployment trials.
Definition mboa.py:72
posterior(self)
Return the current posterior over the repertoire.
Definition mboa.py:131
_kernel(self, first, second)
Definition mboa.py:123
run(self, evaluate)
Spend the remaining budget with a caller-supplied evaluation function.
Definition mboa.py:186
ask(self)
Select one candidate for a real trial.
Definition mboa.py:155
tell(self, fitness)
Record the one pending observation and spend its trial budget.
Definition mboa.py:169