100 """Fit independent objective and descriptor Gaussian processes after each observation.
102 A scrambled Sobol sequence supplies initial points and acquisition
103 restarts. The result grid contains genuine evaluations. Surrogates include
104 finite observations that did not improve an elite or fell outside the grid.
105 Powell search is bounded to the supplied decision domain.
107 With feasibility modelling enabled, return
108 ``(None, None, {"bop_valid": False})`` for a known infeasible design.
109 Unsuccessful calls without explicit infeasibility teach neither the
110 quality models nor the feasibility model.
112 With a descriptor transform, return the measured sources as
113 ``(fitness, None, {"bop_latents": values})``. The same transform sets
114 measured descriptors and projects posterior samples during acquisition.
116 :param container: One-elite Grid with one or two descriptor axes.
117 :param budget: Maximum number of genuine evaluation attempts per run.
118 :param dimension: Number of continuous decision coordinates.
119 :param ind_domain: Common lower and upper decision bounds.
120 :param quality_floor: Empty-cell comparison value in signed quality units.
121 :param initial_samples: Number of Sobol proposals before modelling, default
122 ten times the decision dimension.
123 :param candidate_pool: Number of Sobol points scored at each modelled step.
124 :param restarts: Maximum number of local acquisition searches per step.
125 :param seed: Optional seed for the Sobol sequence.
126 :param model_feasibility: Weight acquisition by a calibrated SVM after
127 at least three valid and three explicitly infeasible observations.
128 :param descriptor_transform: Optional vectorized function of two arrays,
129 raw genomes and measured or predicted latent rows. Return one
130 descriptor row per input row. Use ordinary Grid features.
131 :param latent_size: Number of measured source values when a transform is set.
132 :param posterior_samples: Power-of-two number of shared normal draws for
133 joint descriptor probabilities.
136 _requires_proposed_genome =
True
139 model_feasibility =
False
140 descriptor_transform =
None
141 _feasibility_model =
None
142 _explicit_invalid =
False
145 def _validate_grid(container):
146 if (type(container)
is not Grid
or len(container.shape)
not in (1, 2)
147 or container.max_items_per_bin != 1
or len(container.fitness_domain) != 1):
148 raise ValueError(
"BOPElites requires a one-elite Grid for one objective and one or two descriptors.")
150 def __init__(self, container, budget, dimension, ind_domain, quality_floor, *,
151 initial_samples=None, candidate_pool=128, restarts=8, seed=None,
152 model_feasibility=False, descriptor_transform=None, latent_size=None,
153 posterior_samples=256, **kwargs):
155 lower, upper = np.asarray(container.features_domain, dtype=float).T
156 if len(lower) != len(container.shape)
or not np.all(np.isfinite([lower, upper]))
or np.any(lower >= upper):
157 raise ValueError(
"Provide finite increasing bounds for each descriptor axis.")
158 if not isfinite(quality_floor):
159 raise ValueError(
"quality_floor must be finite.")
161 dimension = _positive_int(dimension,
"dimension")
164 self.
initial_samples = 10 * dimension
if initial_samples
is None else _positive_int(initial_samples,
"initial_samples")
165 self.
candidate_pool = _positive_int(candidate_pool,
"candidate_pool")
166 self.
restarts = _positive_int(restarts,
"restarts")
170 if descriptor_transform
is not None:
171 if not callable(descriptor_transform)
or container.features_score_names:
172 raise ValueError(
"Use a callable descriptor transform with ordinary grid features.")
173 self.
latent_size = _positive_int(latent_size,
"latent_size")
176 raise ValueError(
"posterior_samples must be a power of two.")
177 elif latent_size
is not None:
178 raise ValueError(
"latent_size requires a descriptor transform.")
179 self.
_cells = tuple(container.solutions)
180 cells = np.asarray(self.
_cells)
181 width = (upper - lower) / np.asarray(container.shape)
182 if descriptor_transform
is not None:
183 if np.any(width <= 0)
or not np.isfinite(width).all():
184 raise ValueError(
"The grid needs finite positive cell widths.")
187 self.
_closed_upper = cells == np.asarray(container.shape) - 1
189 super().__init__(container, _positive_int(budget,
"budget"), batch_size=self.
_bop_batch_size,
190 dimension=dimension, **kwargs)
193 """Reset the Sobol stream, observations, and acquisition counters."""
209 def n_observations(self):
210 """Number of finite observations available to the models."""
214 def n_invalid_observations(self):
215 """Number of explicit infeasibility labels received in this run."""
218 def _sobol_point(self):
220 seed = random.randrange(2**32)
if self.
seed is None else self.
seed
222 for _
in range(1024):
223 point = self.
_sobol.random(1)[0]
226 raise RuntimeError(
"The Sobol stream could not find an unseen genome in the decision bounds.")
228 def _raw_point(self, point):
230 return lower + point * (upper - lower)
232 def _fit_models(self):
233 points = np.asarray([point
for point, _
in self.
_observations])
234 targets = np.asarray([target
for _, target
in self.
_observations])
236 for column
in targets.T:
237 kernel = Matern(length_scale=[0.25] * self.
dimension, nu=2.5)
238 model = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, normalize_y=
True, optimizer=
None)
239 models.append(model.fit(points, column))
240 return _SharedGaussianProcesses.of(models)
242 def _fit_feasibility(self):
246 folds = StratifiedKFold(n_splits=3, shuffle=
True, random_state=0)
247 model = CalibratedClassifierCV(SVC(), method=
"sigmoid", cv=folds, ensemble=
False)
248 return model.fit(np.asarray(points), np.asarray(valid, dtype=int))
250 def _descriptors(self, genomes, latents):
252 if descriptors.shape != (len(genomes), len(self.
container.shape))
or not np.isfinite(descriptors).all():
253 raise ValueError(
"The descriptor transform must return one finite descriptor vector per row.")
256 def _structured_probabilities(self, points, means, deviations):
258 seed = random.randrange(2**32)
if self.
seed is None else self.
seed
259 stream = np.random.SeedSequence(seed).spawn(1)[0]
260 sobol = qmc.Sobol(self.
latent_size, scramble=
True, seed=np.random.default_rng(stream))
262 eps = np.finfo(float).eps
269 inside = np.all((descriptors >= lower) & (descriptors <= upper), axis=1)
271 indices = np.minimum(shape - 1, ((descriptors[inside] - lower) / width).astype(np.intp))
272 flat_cells = np.ravel_multi_index(indices.T, self.
container.shape)
274 column_count = len(self.
_cells)
275 counts = np.bincount(point_ids * column_count + flat_cells, minlength=len(points) * column_count)
276 probabilities = counts.reshape(len(points), column_count) / self.
posterior_samples
278 locations = draws.mean(axis=1)
279 deterministic = np.all(deviations == 0., axis=1)
280 locations[deterministic] = draws[deterministic, 0]
281 return probabilities, locations
283 def _thresholds(self):
288 fitness = self.
container.get_ind_fitness(front[0])
289 thresholds.append(fitness.values[0] * fitness.weights[0])
292 return np.array(thresholds)
294 def _posterior(self, models, points):
295 prediction = models.predict(points)
if type(models)
is _SharedGaussianProcesses
else None
296 if prediction
is None:
297 predictions = [model.predict(points, return_std=
True)
for model
in models]
298 means = np.asarray([mean
for mean, _
in predictions]).T
299 deviations = np.asarray([deviation
for _, deviation
in predictions]).T
300 return means, deviations
303 def _acquisition(self, models, points, thresholds, cutoff):
304 means, deviations = self.
_posterior(models, points)
306 probabilities = _region_probabilities(
307 means[:,
None, 1:], deviations[:,
None, 1:], self.
_region_lower,
310 descriptor_means = means[:, 1:]
313 points, means[:, 1:], deviations[:, 1:])
314 improvement = _expected_improvement(means[:, :1], deviations[:, :1], thresholds)
315 contributions = _joint_improvement(probabilities, improvement, cutoff)
318 contributions *= probabilities.sum(axis=1, keepdims=
True)
321 return contributions, descriptor_means
323 def _predicted_cell(self, features):
325 return self.
container.index_grid(features)
329 def _probability_cutoff(self):
331 return 0.5 * (2 / len(self.
_cells)) ** sqrt(10 * self.
dimension / denominator)
333 def _modelled_point(self):
340 contributions, means = self.
_acquisition(models, pool, thresholds, cutoff)
341 if cutoff
is not None and not np.any(contributions > 0):
344 contributions, means = self.
_acquisition(models, pool, thresholds, cutoff)
346 values = contributions.sum(axis=1)
347 order = np.argsort(-values, kind=
"stable")
348 selected = int(order[0])
349 best = pool[selected]
350 best_value = values[selected]
351 best_contributions = contributions[selected]
355 regional = self.
_acquisition(models, point[
None, :], thresholds, cutoff)[0][0]
360 if predicted
in visited:
362 visited.add(predicted)
363 candidate = minimize(
lambda point: -float(acquire(point).sum()), pool[row], method=
"Powell",
364 bounds=[(0, 1)] * self.
dimension, options={
"maxiter": 8,
"maxfev": 50}).x
365 candidate = np.clip(candidate, 0, 1)
367 regional = acquire(candidate)
368 value = regional.sum()
369 if value > best_value:
370 best, best_value, best_contributions = candidate, value, regional
374 region = int(np.argmax(best_contributions))
389 self.
_seen.add(tuple(base_ind))
392 def _check_candidate(self, individual):
395 raise ValueError(
"Descriptor length must match the grid.")
397 def tell(self, individual, fitness=None, features=None, scores=None,
398 elapsed=None, verbose=False, tell_container=True):
399 """Stage a native result, including optional feasibility and source values."""
402 raise RuntimeError(
"Use tell_batch() to report a manual generation.")
404 raise ValueError(
"The evaluated genome differs from the proposal for this slot.")
405 metadata = individual.scores
if scores
is None else scores
407 valid = metadata[
"bop_valid"]
if "bop_valid" in metadata
else True
408 if not isinstance(valid, (bool, np.bool_)):
409 raise ValueError(
"bop_valid must be a boolean.")
414 latents = np.asarray(metadata[
"bop_latents"], dtype=float)
415 if latents.shape != (self.
latent_size,)
or not np.isfinite(latents).all():
416 raise ValueError(
"bop_latents must contain one finite value per measured source.")
417 features = tuple(self.
_descriptors(np.asarray(individual, dtype=float)[
None, :],
418 latents[
None, :])[0])
420 return super().
tell(individual, fitness, features, scores, elapsed, verbose, tell_container)
423 individual = evaluated[0]
424 if individual
is None:
429 fitness = archive.get_ind_fitness(individual)
430 features = tuple(archive.get_ind_features(individual))
431 quality = fitness.values[0] * fitness.weights[0]
440 if actual
is None or not archive.in_bounds(fitness.values, archive.fitness_domain):
472 """Sequential Bayesian illumination of measured two-objective Pareto fronts.
474 Fit independent fixed-kernel GP models for each objective and descriptor.
475 For each candidate, sum per-cell expected hypervolume improvement
476 multiplied by the probability of landing in that cell. Use actual
477 evaluations for Pareto admission. Finite evaluations outside the
478 archive bounds can still inform the models.
480 :param container: A crowding ParetoGrid with two objectives and one or two
481 descriptors. Use direct fitness and features.
482 :param budget: Number of true evaluation attempts.
483 :param dimension: Number of bounded real decision variables.
484 :param ind_domain: Shared finite decision bounds.
485 :param reference: Two raw objective coordinates weakly dominated by the
486 worst objective corner of the declared fitness domain.
487 :param initial_samples: Number of initial Sobol proposals.
488 :param candidate_pool: Sobol candidates screened per acquisition.
489 :param restarts: Maximum number of local acquisition refinements.
490 :param seed: Seed for the scrambled Sobol proposal stream.
494 def _validate_grid(container):
495 if (type(container)
is not ParetoGrid
or len(container.shape)
not in (1, 2)
496 or len(container.fitness_domain) != 2
or container.truncation !=
"crowding"
497 or container.fitness_score_names
or container.features_score_names):
498 raise ValueError(
"Use a two-objective crowding ParetoGrid with one or two direct descriptors.")
500 def __init__(self, container, budget, dimension, ind_domain, *, reference,
501 initial_samples=None, candidate_pool=128, restarts=8, seed=0):
503 direction = np.sign(container.fitness_weights)
504 ref = np.asarray(reference, dtype=float)
505 bounds = np.asarray(container.fitness_domain, dtype=float)
506 worst = np.where(direction > 0, bounds[:, 0], -bounds[:, 1])
507 if ref.shape != (2,)
or not np.isfinite(ref).all()
or not np.all(direction * ref <= worst):
508 raise ValueError(
"The finite reference point must be weakly dominated by the fitness domain.")
512 super().__init__(container, budget, dimension, ind_domain, quality_floor=0.,
513 initial_samples=initial_samples, candidate_pool=candidate_pool, restarts=restarts,
514 seed=seed, optimisation_task=container.fitness_weights)
516 def _probability_cutoff(self):
519 def _thresholds(self):
521 _improvement_strips([self.
_direction * ind.fitness.values
for ind
in self.
container.solutions[cell]],
526 def _acquisition(self, models, points, thresholds, cutoff):
527 means, deviations = self.
_posterior(models, points)
528 descriptors = means[:, 2:]
529 probabilities = _region_probabilities(
530 descriptors[:,
None, :], deviations[:,
None, 2:], self.
_region_lower,
532 improvement = np.column_stack([
533 _expected_hypervolume_improvement(means[:, :2], deviations[:, :2], strips)
534 for strips
in thresholds
536 return probabilities * improvement, descriptors
538 def _check_candidate(self, individual):
539 super()._check_candidate(individual)
540 if len(individual.fitness.values) != 2:
541 raise ValueError(
"Supply exactly two measured objectives.")
544 individual = evaluated[0]
545 if individual
is None:
547 fitness, features = individual.fitness.values, tuple(individual.features)
551 return {0}
if self.
container._merge_fronts([individual])
else set()