QDpy
Loading...
Searching...
No Matches
boil.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Bayesian Optimization with Interactive Illumination."""
6
7from dataclasses import dataclass
8from math import log
9from operator import index
10
11import numpy as np
12from scipy.special import ndtri, xlogy
13from scipy.stats import qmc
14
15from qdpy.base import registry
16from .bayesian import BOPElites, _expected_improvement, _region_probabilities
17from .modern import _positive_int
18
19__all__ = ["BOIL", "BOILPrediction", "BOILTargetResult"]
20
21
22
23@dataclass(frozen=True)
25 """A surrogate estimate for inspection before running a real evaluation."""
26
27 cell: tuple[int, ...]
28 genome: tuple[float, ...]
29 fitness_mean: float
30 descriptor_mean: tuple[float, ...]
31 probability: float
32
33
34
35@dataclass(frozen=True)
37 """Report measured fitness, descriptors and target utility in their original units."""
38
39 genome: tuple[float, ...]
40 fitness: float
41 descriptors: tuple[float, ...]
42 utility: float
43
44
45
46@registry.register
48 """Bayesian Optimization with Interactive Illumination (Kent and Branke, 2023).
49
50 Reuse the measured design and descriptor posteriors across all three
51 phases. Use a fixed one- or two-dimensional rectangular reporting grid.
52 Model building multiplies expected joint improvement by one plus the
53 normalized entropy of posterior region membership. Focused
54 illumination considers only selected cells. Target search uses common
55 Monte Carlo draws to estimate the expected improvement in target utility.
56
57 :param container: Best-only Grid with one objective and one or two descriptors.
58 :param budget: Total measurement attempts across repeated optimise calls and manual batches.
59 :param dimension: Length of a real-valued genome.
60 :param ind_domain: Common lower and upper decision bounds.
61 :param quality_floor: Empty-cell threshold in weighted fitness units.
62 :param entropy_weight: Nonnegative multiplier on normalized descriptor entropy.
63 :param target_samples: Power-of-two count of fixed, scrambled Sobol posterior draws.
64 :param kwargs: Native optimizer arguments and BOP-Elites initialization and search settings.
65 """
66
67 def __init__(self, container, budget, dimension, ind_domain, quality_floor, *,
68 entropy_weight=1., target_samples=64, **kwargs):
69 if not 0 <= entropy_weight < np.inf:
70 raise ValueError("entropy_weight must be finite and nonnegative.")
71 self.entropy_weight = float(entropy_weight)
72 self.evaluation_limit = _positive_int(budget, "budget")
73 self.target_samples = _positive_int(target_samples, "target_samples")
74 if self.target_samples & (self.target_samples - 1):
75 raise ValueError("target_samples must be a power of two.")
76 unsupported = ("model_feasibility", "descriptor_transform", "latent_size")
77 if any(name in kwargs for name in unsupported):
78 raise TypeError("BOIL takes direct descriptor observations.")
79 super().__init__(container, budget, dimension, ind_domain, quality_floor, **kwargs)
80 if (not self._fitness_weights[0] or not np.isfinite(self.ind_domain[1] - self.ind_domain[0])
81 or not np.isfinite(self._region_upper - self._region_lower).all()):
82 raise ValueError("Use finite search widths and a nonzero fitness weight.")
83
84 def reinit(self):
85 """Reset measurements, the phase, and the lifetime attempt count."""
86 super().reinit()
87 self._focus = None
88 self._target = None
89 self._distance_weight = 0.
90 self._target_baseline = None
91 stream = qmc.Sobol(len(self.container.shape) + 1, scramble=True, seed=0 if self.seed is None else self.seed)
92 self._draws = ndtri(np.clip(stream.random_base2(self.target_samples.bit_length() - 1), 1e-12, 1 - 1e-12))
93
94 @property
95 def remaining_evaluations(self):
96 """Return the number of attempts still available, including future phases."""
97 return self.evaluation_limit - self.nb_evaluations
98
99 def _expect_idle(self):
100 if self._pending_size:
101 raise RuntimeError("Finish the outstanding BOIL batch before changing phases.")
102
103
104 def focus(self, cells=None):
105 """Select a nonempty sequence of grid indices, or pass None to use the full map."""
106 self._expect_idle()
107 ranks = None
108 if cells is not None:
109 selected = {tuple(index(axis) for axis in cell) for cell in cells}
110 if not selected or not selected.issubset(self.container.solutions):
111 raise ValueError("Select at least one valid grid cell.")
112 ranks = np.array([cell in selected for cell in self._cells])
113 self._focus, self._target = ranks, None
114
115
116 def set_target(self, descriptor, *, distance_weight=1.):
117 """Maximize weighted fitness minus distance_weight times Euclidean descriptor error."""
118 self._expect_idle()
119 target = np.asarray(descriptor, dtype=float)
120 if (target.shape != (len(self.container.shape),) or not np.isfinite(target).all()
121 or not self.container.in_bounds(target, self.container.features_domain)):
122 raise ValueError("The target must be finite and within the descriptor domain.")
123 if not 0 <= distance_weight < np.inf:
124 raise ValueError("distance_weight must be finite and nonnegative.")
125 self._target = target.copy()
126 self._distance_weight = float(distance_weight)
127 self._focus = None
128
129 def _utility(self, values):
130 if self._distance_weight == 0:
131 return values[..., 0]
132 distances = np.linalg.norm(values[..., 1:] - self._target, axis=-1)
133 return values[..., 0] - self._distance_weight * distances
134
135
136 def best_target(self):
137 """Return a BOILTargetResult for the active target, or None before any observations."""
138 if self._target is None:
139 raise RuntimeError("Call set_target() before requesting target results.")
140 if not self._observations:
141 return None
142 values = np.asarray([row for _, row in self._observations])
143 scores = self._utility(values)
144 row = int(np.argmax(scores))
145 return BOILTargetResult(tuple(map(float, self._raw_point(self._observations[row][0]))),
146 float(values[row, 0] / self._fitness_weights[0]),
147 tuple(map(float, values[row, 1:])), float(scores[row]))
148
149 def _probabilities(self, means, deviations):
150 return _region_probabilities(means[:, None, 1:], deviations[:, None, 1:],
152
153 def _modelled_point(self):
154 if self._target is not None:
155 self._target_baseline = self.best_target().utility
156 return super()._modelled_point()
157
158 def _acquisition(self, models, points, thresholds, cutoff):
159 means, deviations = self._posterior(models, points)
160 if self._target is not None:
161 samples = means[:, None, :] + deviations[:, None, :] * self._draws
162 gains = np.maximum(self._utility(samples) - self._target_baseline, 0.).mean(axis=1)
163 # BOPElites uses the regional axis to choose restarts and track predictions.
164 contributions = np.zeros((len(points), len(self._cells)))
165 slot = self._cells.index(self.container.index_grid(self._target))
166 contributions[:, slot] = gains
167 else:
168 probabilities = self._probabilities(means, deviations)
169 if self._focus is not None:
170 probabilities[:, ~self._focus] = 0.
171 improvement = _expected_improvement(means[:, :1], deviations[:, :1], thresholds)
172 entropy = -xlogy(probabilities, probabilities).sum(axis=1) / log(max(2, len(self._cells)))
173 contributions = probabilities * improvement * (1 + self.entropy_weight * entropy[:, None])
174 return contributions, means[:, 1:]
175
176
177 def prediction_map(self, *, samples=512, min_probability=.5, seed=0):
178 """Return up to one provisional solution per cell, ranked by predicted weighted fitness."""
179 self._expect_idle()
180 samples = _positive_int(samples, "samples")
181 if not 0 < min_probability <= 1:
182 raise ValueError("min_probability must be in (0, 1].")
183 if len(self._observations) < 2:
184 raise RuntimeError("Evaluate at least two valid solutions before building a preview.")
185 points = qmc.Sobol(self.dimension, scramble=True, seed=seed).random_base2((samples - 1).bit_length())
186 points = np.vstack((points[:samples], [point for point, _ in self._observations]))
187 means, deviations = self._posterior(self._fit_models(), points)
188 probabilities = self._probabilities(means, deviations)
189 predictions = []
190 for slot, cell in enumerate(self._cells):
191 rows = np.flatnonzero(probabilities[:, slot] >= min_probability)
192 if len(rows):
193 row = rows[np.argmax(means[rows, 0])]
194 predictions.append(BOILPrediction(cell, tuple(map(float, self._raw_point(points[row]))),
195 float(means[row, 0] / self._fitness_weights[0]),
196 tuple(map(float, means[row, 1:])),
197 float(probabilities[row, slot])))
198 return tuple(predictions)
199
200 def _start_fixed_batch(self, size):
201 if size > self.remaining_evaluations:
202 raise RuntimeError("The BOIL evaluation budget is exhausted.")
203 super()._start_fixed_batch(size)
204
205
206 def optimise(self, evaluate, budget=None, **kwargs):
207 """Run an additional phase, using the remaining budget if none is given."""
208 count = self.remaining_evaluations if budget is None else _positive_int(budget, "budget")
209 if count > self.remaining_evaluations:
210 raise ValueError("The phase budget exceeds remaining_evaluations.")
211 return super().optimise(evaluate, budget=count, **kwargs)
Select one genuine evaluation with expected joint improvement of elites.
Definition bayesian.py:99
_posterior(self, models, points)
Definition bayesian.py:294
Predicted cell representative and its posterior membership probability.
Definition boil.py:24
Best actual measurement for the currently requested descriptor target.
Definition boil.py:36
Alternate model building, focused illumination, and search for a chosen descriptor.
Definition boil.py:47
optimise(self, evaluate, budget=None, **kwargs)
Spend a phase budget within the lifetime evaluation limit.
Definition boil.py:206
_start_fixed_batch(self, size)
Definition boil.py:200
best_target(self)
Find the strongest measured target utility, including measurements rejected by the grid.
Definition boil.py:136
prediction_map(self, *, samples=512, min_probability=.5, seed=0)
Build a model-only prediction map without spending evaluations or advancing the search.
Definition boil.py:177
set_target(self, descriptor, *, distance_weight=1.)
Search for measured solutions with a chosen target descriptor.
Definition boil.py:116
focus(self, cells=None)
Restrict the illumination phase to grid cells selected from the preview.
Definition boil.py:104
_probabilities(self, means, deviations)
Definition boil.py:149
_utility(self, values)
Definition boil.py:129