QDpy
Loading...
Searching...
No Matches
conditional_bayesian.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Promote promising designs across conditional subspaces under an exact-call budget."""
7
8from collections import deque
9from functools import partial
10
11import numpy as np
12from scipy.special import ndtr
13
14from qdpy.base import registry
15from .bayesian import _expected_improvement
16from .constrained import HiGeME, RealVariable, _constraint_violation, _mutate_gene, _sample_gene
17from .mixed_bayesian import _MixedGaussianProcess, _gower_covariance
18from .modern import _positive_int
19
20__all__ = ["ConditionalBayesianQD"]
21
22
24 """Fit objective, descriptor and residual GPs using only active genes."""
25
26 def __init__(self, search, branch):
27 self.active = search._active[branch]
28 self.continuous = np.asarray([isinstance(search.variables[i], RealVariable) for i in self.active], dtype=bool)
29 lower = [search._bounds[i][0] for i in self.active if isinstance(search.variables[i], RealVariable)]
30 upper = [search._bounds[i][1] for i in self.active if isinstance(search.variables[i], RealVariable)]
31 self.origin = np.asarray(lower)
32 self.span = np.asarray([hi - lo or 1. for lo, hi in zip(lower, upper)])
33 covariance = partial(_gower_covariance, continuous=self.continuous,
34 length_scale=search.real_length_scale, correlation=search.discrete_correlation)
35 genomes, responses = zip(*search._observations[branch])
36 self.gp = _MixedGaussianProcess(self._encode(genomes), np.asarray(responses), covariance)
37
38 def _encode(self, genomes):
39 points = np.asarray([[genome[i + 1] for i in self.active] for genome in genomes], dtype=float)
40 real = self.continuous
41 points[:, real] = (points[:, real] - self.origin) / self.span
42 return points
43
44 def predict(self, genomes):
45 return self.gp.predict(self._encode(genomes))
46
47
48def _probability_feasible(mean, sigma):
49 with np.errstate(over="ignore"):
50 z = np.divide(-mean, sigma, out=np.zeros_like(mean), where=sigma > 0)
51 return np.prod(np.where(sigma > 0, ndtr(z), mean <= 0.), axis=-1)
52
53
54
55@registry.register
57 """Fit per-configuration surrogates and promote exact evaluations into a shared grid.
58
59 Each cheap pool uses a mix of uniform designs and perturbations of prior
60 measurements from that configuration. Assign each predicted design to
61 its posterior-mean descriptor cell. Rank proposals by feasibility-weighted
62 expected improvement over the measured cell incumbent. Select at most
63 one predicted winner per cell per batch before filling unused slots.
64 Only measured feasible designs are offered to the reporting grid.
65
66 :param container: Empty best-only Grid or CVTGrid with one objective.
67 :param budget: Total exact evaluation attempts.
68 :param variables: Ordered mapping from variable names to HiGeME gene specifications.
69 :param configurations: Allowed ConditionalConfiguration objects.
70 :param initial_samples: Space-filling draws per configuration before fitting.
71 :param surrogate_budget: Candidate prediction attempts per fitted configuration and batch.
72 :param quality_floor: Optional raw fitness reference for empty cells. By
73 default use the worst signed fitness measured so far.
74 :param exploration_probability: Chance of a fresh random draw after warm-up.
75 :param real_length_scale: Gaussian length scale on normalized real genes.
76 :param discrete_correlation: Kernel factor for mismatched discrete genes.
77 :param batch_size: Total exact proposals per acquisition update.
78 :param seed: Private random seed.
79 :param optimisation_task: Single objective direction or weight. Defaults
80 to the supplied archive's direction when set.
81 """
82
83 def __init__(self, container, budget, variables, *, configurations, initial_samples=4,
84 surrogate_budget=96, quality_floor=None, exploration_probability=.1,
85 real_length_scale=.25, discrete_correlation=.25, batch_size=1, seed=0,
86 optimisation_task=None):
87 if not (0 <= exploration_probability <= 1 and 0 < real_length_scale < np.inf
88 and 0 <= discrete_correlation < 1):
89 raise ValueError("Use finite GP settings and an exploration probability in [0, 1].")
90 if quality_floor is not None and not np.isfinite(quality_floor):
91 raise ValueError("quality_floor must be finite.")
92 self.initial_samples = _positive_int(initial_samples, "initial_samples")
93 self.surrogate_budget = _positive_int(surrogate_budget, "surrogate_budget")
94 self.quality_floor = quality_floor
95 self.exploration_probability = exploration_probability
96 self.real_length_scale, self.discrete_correlation = real_length_scale, discrete_correlation
97 if optimisation_task is None:
98 optimisation_task = "minimisation" if container.fitness_weights is None else container.fitness_weights
99 super().__init__(container, budget, variables, configurations=configurations, seed=seed,
100 batch_size=batch_size, optimisation_task=optimisation_task)
101 self._direction = float(np.sign(self._fitness_weights[0]))
102 if not np.isfinite(self._fitness_weights[0]) or not self._direction:
103 raise ValueError("Use a finite nonzero fitness weight.")
104 active = {i for branch in self._active for i in branch}
105 if any(not isinstance(self.variables[i], RealVariable) and max(map(abs, self._bounds[i])) > 2**53
106 for i in active):
107 raise ValueError("Active discrete genes must be exactly representable in float64.")
108 self._mutable_by_branch = tuple(tuple(i for i in indices if self._bounds[i][0] < self._bounds[i][1])
109 for indices in self._active)
110
111 def reinit(self):
112 """Reset models, proposal streams, and conditional evaluation counts."""
113 super().reinit()
114 self._observations = [[] for _ in self.configurations]
115 self._counts = [0] * len(self.configurations)
116 self._seen, self._promoted = set(), deque()
117 self._surrogate_evaluations = self._model_fits = self._modelled_proposals = 0
118
119 @property
121 """Return exact proposals in configuration order, including failed evaluations."""
122 return tuple(self._counts)
123
124 @property
126 """Return counts of finite observations used by each configuration model."""
127 return tuple(map(len, self._observations))
128
129 @property
131 """Return the number of distinct cheap predictions across all batches."""
132 return self._surrogate_evaluations
133
134 @property
135 def model_fits(self):
136 """Return the number of per-configuration model refits."""
137 return self._model_fits
138
139 @property
141 """Return exact proposals chosen by the surrogate."""
142 return self._modelled_proposals
143
144 def _random(self, branch):
145 genome = [lo for lo, _ in self._bounds]
146 for i in self._active[branch]:
147 genome[i] = _sample_gene(self.variables[i], self._bounds[i], self._rng)
148 return (branch, *genome)
149
150 def _draw(self, branch, reserved=()):
151 for _ in range(64):
152 vector = self._random(branch)
153 if vector not in self._seen and vector not in reserved:
154 break
155 return vector
156
157 def _pool(self, branch, observations):
158 """Draw cheap trials from between and around prior exact designs."""
159 mutable = self._mutable_by_branch[branch]
160 if not mutable:
161 return ()
162 pool = {}
163 for _ in range(self.surrogate_budget):
164 if self._rng.random() < .5:
165 genome = list(self._rng.choice(observations)[0])
166 i = self._rng.choice(mutable)
167 genome[i + 1] = _mutate_gene(genome[i + 1], self.variables[i], self._bounds[i], .15, self._rng)
168 vector = tuple(genome)
169 else:
170 vector = self._random(branch)
171 if vector not in self._seen:
172 pool[vector] = None
173 return tuple(pool)
174
175 def _rank_pool(self, branch, vectors, floor):
176 model = _BranchModel(self, branch)
177 self._model_fits += 1
178 means, deviations = model.predict(vectors)
179 self._surrogate_evaluations += len(vectors)
180 grid = self.container
181 width = len(grid.features_domain)
182 probability = _probability_feasible(means[:, width + 1:], deviations[:, width + 1:])
183 rows = []
184 for i, vector in enumerate(vectors):
185 features = tuple(means[i, 1:width + 1])
186 if not np.isfinite(features).all() or not grid.in_bounds(features, grid.features_domain):
187 continue
188 cell = grid.index_grid(features)
189 threshold = self._acquisition_reference(branch, cell, floor)
190 rows.append((i, threshold, cell, vector))
191 if not rows:
192 return ()
193 indices, thresholds, _, _ = zip(*rows)
194 indices = list(indices)
195 with np.errstate(over="ignore", divide="ignore", invalid="ignore"):
196 improvement = _expected_improvement(means[indices, 0], deviations[indices, 0], np.asarray(thresholds))
197 scores = probability[indices] * improvement
198 return [(float(score), float(probability[i]), float(deviations[i, 0]), cell, vector)
199 for (i, _, cell, vector), score in zip(rows, scores) if np.isfinite(score)]
200
201 def _acquisition_reference(self, branch, cell, floor):
202 occupants = self.container.solutions[cell]
203 return self._direction * self.container.get_ind_fitness(occupants[0]).values[0] if occupants else floor
204
205 def _acquisition_key(self, cell, vector):
206 return cell
207
208 def _plan_batch(self, size):
209 floor = (self._direction * self.quality_floor if self.quality_floor is not None else
210 min(row[0] for observations in self._observations for _, row in observations))
211 ranked = []
212 for branch, observations in enumerate(self._observations):
213 if observations:
214 pool = self._pool(branch, observations)
215 if pool:
216 ranked.extend(self._rank_pool(branch, pool, floor))
217 ranked.sort(key=lambda row: row[:3], reverse=True)
218 selected = {}
219 for _, _, _, cell, vector in ranked:
220 selected.setdefault(self._acquisition_key(cell, vector), vector)
221 if len(selected) == size:
222 break
223 return selected.values()
224
225 def _start_fixed_batch(self, size):
226 super()._start_fixed_batch(size)
227 self._promoted.clear()
228 self._prepare_promotions(size)
229
230 def _prepare_promotions(self, size):
231 """Queue model-based proposals for the next fixed batch."""
232 if self.nb_suggestions >= self.initial_samples * len(self.configurations) and any(self._observations):
233 picks = size - sum(self._rng.random() < self.exploration_probability for _ in range(size))
234 if picks:
235 self._promoted.extend(self._plan_batch(picks))
236
237 def _next_vector(self):
238 count = len(self.configurations)
239 if self._promoted:
240 vector = self._promoted.popleft()
241 self._modelled_proposals += 1
242 else:
243 branch = (self.nb_suggestions % count if self.nb_suggestions < self.initial_samples * count
244 else self._rng.randrange(count))
245 vector = self._draw(branch)
246 return vector
247
248 def _internal_ask(self, base_ind):
249 vector = self._next_vector()
250 self._counts[vector[0]] += 1
251 self._seen.add(vector)
252 base_ind[:] = vector
253 return base_ind
254
255 def _check_candidate(self, individual):
256 self.decode(individual)
257 self._check_measurements(individual)
258 if len(self.container.get_ind_features(individual)) != len(self.container.features_domain):
259 raise ValueError("Provide one measured descriptor per grid axis.")
260 _constraint_violation(individual, self.configurations[individual[0]].constraints)
261
262 def _offer_feasible(self, individual, cell):
263 return self._offer_to_grid(individual, cell)
264
265 def _commit_generation(self, evaluated):
266 grid, admitted = self.container, set()
267 for slot, individual in enumerate(evaluated):
268 if individual is None:
269 continue
270 branch = individual[0]
271 fitness = grid.get_ind_fitness(individual).values
272 features = tuple(grid.get_ind_features(individual))
273 residuals = tuple(float(individual.scores[name]) for name in self.configurations[branch].constraints)
274 response = (self._direction * float(fitness[0]), *features, *residuals)
275 self._observations[branch].append((tuple(individual), response))
276 if (all(value <= 0. for value in residuals) and grid.in_bounds(fitness, grid.fitness_domain)
277 and grid.in_bounds(features, grid.features_domain)
278 and self._offer_feasible(individual, grid.index_grid(features))):
279 admitted.add(slot)
280 return admitted
Reuse HiGeME's conditional schema with competitive Bayesian infill.
Search a union of conditional design spaces using hidden numeric genes.
decode(self, candidate)
Decode a candidate into the design visible to the evaluator.
_check_measurements(self, individual)
Definition modern.py:216
_offer_to_grid(self, individual, cell)
Definition modern.py:228