QDpy
Loading...
Searching...
No Matches
mixed_bayesian.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Bayesian QD for mixed real, integer, and categorical designs."""
7
8from collections import deque
9from math import isfinite
10import random
11
12import numpy as np
13from scipy.linalg import cholesky, cho_solve, solve_triangular
14from scipy.spatial.distance import cdist
15from scipy.stats import qmc
16
17from qdpy.base import registry
18from qdpy.containers import Grid
19from .bayesian import _expected_improvement
20from .constrained import (CategoricalVariable, IntegerVariable, RealVariable,
21 _constraint_violation, _decode_gene, _encoded_bounds,
22 _mutate_gene, _names, _sample_gene, _validate_grid)
23from .modern import _FixedGeneration, _positive_int
24
25__all__ = ["MixedBayesianQD"]
26
27
28def _gower_covariance(first, second, continuous, length_scale, correlation):
29 """Multiply an RBF kernel on normalized reals by one equality kernel per discrete axis."""
30 distance = cdist(first[:, continuous], second[:, continuous])
31 with np.errstate(over="ignore"):
32 matrix = np.exp(-.5 * (distance / length_scale) ** 2)
33 for index in np.flatnonzero(~continuous):
34 matrix *= np.where(first[:, index, None] == second[None, :, index], 1., correlation)
35 return matrix
36
37
39 """Fit independent unit-amplitude GPs with one shared kernel factorization."""
40
41 def __init__(self, points, responses, covariance):
42 self.points, self.covariance = points, covariance
43 self.mean = responses.mean(axis=0)
44 self.scale = responses.std(axis=0)
45 self.scale[self.scale == 0.] = 1.
46 gram = covariance(points, points)
47 gram.flat[::len(points) + 1] += 1e-6
48 self.factor = cholesky(gram, lower=True)
49 self.coefficients = cho_solve((self.factor, True), (responses - self.mean) / self.scale)
50
51 def predict(self, points):
52 cross = self.covariance(points, self.points)
53 means = (cross @ self.coefficients) * self.scale + self.mean
54 solved = solve_triangular(self.factor, cross.T, lower=True)
55 deviations = np.sqrt(np.maximum(0., 1. - np.einsum("ij,ij->j", solved, solved)))
56 return means, deviations[:, None] * self.scale
57
58
59
60@registry.register
62 """Fit objective, descriptor, and residual models from exact measurements.
63
64 Real coordinates use a Gaussian kernel. Integer and categorical
65 coordinates use the paper's compound-symmetry (Gower) kernel.
66 A cheap mixed-variable MAP-Elites loop illuminates optimistic
67 objective values under expected-violation limits. A Sobol stream
68 in normalized descriptor coordinates selects which predicted cells
69 to measure next. Only exactly feasible measurements enter the grid.
70
71 :param container: Empty parentless regular best-only Grid with finite descriptor bounds.
72 :param budget: Exact evaluation attempts in the managed run.
73 :param variables: Sequence of RealVariable, IntegerVariable and CategoricalVariable.
74 :param constraint_names: Distinct score names for residuals g(x) <= 0.
75 :param initial_samples: Minimum successful exact measurements before modelled proposals.
76 :param surrogate_budget: Number of GP predictions per acquisition batch.
77 :param surrogate_batch_size: Number of offspring between auxiliary archive updates.
78 :param exploration: Nonnegative multiplier of the predicted objective standard deviation.
79 :param violation_tolerance: Allowable expected violation per constraint in the auxiliary search.
80 :param real_length_scale: Gaussian length scale in normalized real coordinates.
81 :param discrete_correlation: Covariance factor for two distinct discrete values.
82 :param batch_size: Maximum simultaneous exact proposals.
83 :param seed: Private mixed-space and Sobol seed.
84 :param kwargs: Native optimisation settings, including objective direction.
85 """
86
87 _requires_proposed_genome = True
88
89 def __init__(self, container, budget, variables, *, constraint_names=(),
90 initial_samples=12, surrogate_budget=128, surrogate_batch_size=16, exploration=2.,
91 violation_tolerance=.05, real_length_scale=.25, discrete_correlation=.25,
92 batch_size=4, seed=0, **kwargs):
93 _validate_grid(container)
94 domains = np.asarray(container.features_domain, dtype=float)
95 if (type(container) is not Grid or container.parents or domains.shape != (len(container.shape), 2)
96 or not np.isfinite(domains).all() or np.any(domains[:, 1] <= domains[:, 0])
97 or not np.isfinite(domains[:, 1] - domains[:, 0]).all()):
98 raise ValueError("Supply a fixed parentless rectangular grid with finite positive descriptor widths.")
99 self.variables = tuple(variables)
100 if not self.variables or not all(isinstance(v, (RealVariable, IntegerVariable, CategoricalVariable))
101 for v in self.variables):
102 raise ValueError("Supply one supported variable specification per coordinate.")
103 self._bounds = tuple(map(_encoded_bounds, self.variables))
104 self._continuous = np.array([isinstance(v, RealVariable) for v in self.variables])
105 if any(max(abs(lo), abs(hi)) > 2**53 for (lo, hi), real in zip(self._bounds, self._continuous)
106 if not real):
107 raise ValueError("Discrete coordinates must be exactly representable in float64.")
108 self._low, high = np.asarray(self._bounds, dtype=float).T
109 # Discrete values keep their original level labels (as exact numeric indices).
110 self._span = np.where(self._continuous & (high != self._low), high - self._low, 1.)
111 self._mutable = [i for i, (lo, hi) in enumerate(self._bounds) if hi != lo]
112 self.constraint_names = _names(constraint_names, "constraint scores")
113 if set(self.constraint_names).intersection((*container.fitness_score_names, *container.features_score_names)):
114 raise ValueError("Use separate score names for constraints.")
115 if (not 0 <= exploration < np.inf or not 0 <= violation_tolerance < np.inf
116 or not 0 < real_length_scale < np.inf or not 0 <= discrete_correlation < 1):
117 raise ValueError("Use finite acquisition settings and discrete_correlation in [0, 1).")
118 self.initial_samples = _positive_int(initial_samples, "initial_samples")
119 self.surrogate_budget = _positive_int(surrogate_budget, "surrogate_budget")
120 self.surrogate_batch_size = _positive_int(surrogate_batch_size, "surrogate_batch_size")
121 self.exploration, self.violation_tolerance = exploration, violation_tolerance
122 self.real_length_scale, self.discrete_correlation = real_length_scale, discrete_correlation
123 self.seed = seed
124 if container.fitness_weights is not None:
125 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
126 super().__init__(container, _positive_int(budget, "budget"), dimension=len(self.variables),
127 batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
128 if len(self._fitness_weights) != 1 or not isfinite(self._fitness_weights[0]) or not self._fitness_weights[0]:
129 raise ValueError("Use a finite, nonzero signed fitness weight.")
130
131 def reinit(self):
132 """Reset proposal streams, exact models, and surrogate accounting."""
133 super().reinit()
134 self._rng = random.Random(self.seed)
135 self._targets = qmc.Sobol(len(self.container.shape), scramble=True, seed=self._rng.randrange(2**32))
136 self._seen, self._observations, self._promoted = set(), [], deque()
137 self._surrogate_evaluations = self._model_fits = 0
138
139 @property
141 """Return the cumulative number of genomes predicted by auxiliary search."""
142 return self._surrogate_evaluations
143
144 @property
145 def model_fits(self):
146 """Return the number of exact-data refits across acquisition batches."""
147 return self._model_fits
148
149
150 def decode(self, candidate):
151 """Return one typed value per declared decision coordinate."""
152 if len(candidate) != self.dimension:
153 raise ValueError("Genome length must match the variable specifications.")
154 return tuple(_decode_gene(value, variable, bounds)
155 for value, variable, bounds in zip(candidate, self.variables, self._bounds))
156
157 def _encode(self, points):
158 points = np.array(points, dtype=float, copy=True, ndmin=2)
159 mask = self._continuous
160 points[:, mask] = (points[:, mask] - self._low[mask]) / self._span[mask]
161 return points
162
163 def _covariance(self, first, second):
164 return _gower_covariance(first, second, self._continuous,
166
167 def _random(self):
168 return tuple(_sample_gene(v, bounds, self._rng) for v, bounds in zip(self.variables, self._bounds))
169
170 def _novel_draw(self):
171 for _ in range(128):
172 vector = self._random()
173 if vector not in self._seen:
174 break
175 return vector
176
177 def _offspring(self, parent):
178 if not self._mutable:
179 return parent
180 child = list(parent)
181 index = self._rng.choice(self._mutable)
182 child[index] = _mutate_gene(child[index], self.variables[index], self._bounds[index], .15, self._rng)
183 return tuple(child)
184
185 def _auxiliary_archive(self, model):
186 # Use mean descriptors for cell assignment and retain the best
187 # optimistic candidate with the lowest excess expected violation.
188 grid, best = self.container, {}
189 count = len(grid.shape)
190 for start in range(0, self.surrogate_budget, self.surrogate_batch_size):
191 size = min(self.surrogate_batch_size, self.surrogate_budget - start)
192 parents = [entry[1] for entry in best.values()]
193 vectors = [self._offspring(self._rng.choice(parents)) if parents and self._rng.random() < .8
194 else self._random() for _ in range(size)]
195 means, deviations = model.predict(self._encode(vectors))
196 self._surrogate_evaluations += size
197 expected = _expected_improvement(means[:, count+1:], deviations[:, count+1:], 0.)
198 excess = np.maximum(expected - self.violation_tolerance, 0.).sum(axis=1)
199 optimistic = means[:, 0] + self.exploration * deviations[:, 0]
200 for vector, descriptor, violation, quality in zip(vectors, means[:, 1:count+1], excess, optimistic):
201 try:
202 cell = grid.index_grid(tuple(descriptor))
203 except IndexError:
204 continue
205 if vector not in self._seen:
206 rank = (violation, -quality)
207 if cell not in best or rank < best[cell][0]:
208 best[cell] = (rank, vector)
209 return best
210
211 def _plan_batch(self, size):
212 points, responses = zip(*self._observations)
213 model = _MixedGaussianProcess(self._encode(points), np.asarray(responses), self._covariance)
214 self._model_fits += 1
215 elites = self._auxiliary_archive(model)
216 picks = []
217 for _ in range(min(size, len(elites))):
218 wanted = self._targets.random(1)[0]
219 cell = min(elites, key=lambda cell: (elites[cell][0][0] > 0., elites[cell][0][0],
220 np.linalg.norm((np.asarray(cell) + .5) / self.container.shape - wanted),
221 elites[cell][0][1]))
222 picks.append(elites.pop(cell)[1])
223 return list(dict.fromkeys(picks))
224
225 def _start_fixed_batch(self, size):
226 # Plan once against the last resolved measurements. Queue candidates
227 # before issuing callbacks so worker completion order cannot affect it.
228 super()._start_fixed_batch(size)
229 self._promoted.clear()
230 if len(self._observations) >= self.initial_samples:
231 self._promoted.extend(self._plan_batch(size))
232
233 def _internal_ask(self, base_ind):
234 # An unseen draw never consumes a point reserved for this same batch
235 # because planned candidates are issued before the random fallback.
236 vector = self._promoted.popleft() if self._promoted else self._novel_draw()
237 self._seen.add(vector)
238 base_ind[:] = vector
239 return base_ind
240
241 def _check_candidate(self, individual):
242 self.decode(individual)
243 self._check_measurements(individual)
244 if len(self.container.get_ind_features(individual)) != len(self.container.shape):
245 raise ValueError("Provide one measured descriptor per grid axis.")
246 _constraint_violation(individual, self.constraint_names)
247
248 def _commit_generation(self, evaluated):
249 grid, admitted = self.container, set()
250 for slot, individual in enumerate(evaluated):
251 if individual is None:
252 continue
253 fit = grid.get_ind_fitness(individual).values
254 descriptors = tuple(grid.get_ind_features(individual))
255 residuals = tuple(float(individual.scores[name]) for name in self.constraint_names)
256 quality = self._fitness_weights[0] * fit[0]
257 self._observations.append((tuple(individual), (quality, *descriptors, *residuals)))
258 if (all(value <= 0. for value in residuals) and grid.in_bounds(fit, grid.fitness_domain)
259 and grid.in_bounds(descriptors, grid.features_domain)
260 and self._offer_to_grid(individual, grid.index_grid(descriptors))):
261 admitted.add(slot)
262 return admitted
Use mixed-domain surrogates to illuminate and promote promising candidates.
decode(self, candidate)
Translate discrete category indices into the original labels.
_check_measurements(self, individual)
Definition modern.py:216
_offer_to_grid(self, individual, cell)
Definition modern.py:228