# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Sequential Bayesian optimisation of elites with uncertain descriptor predictions.
"""BOP-Elites for fixed, low-dimensional descriptor grids."""
from math import isfinite, sqrt
import random
import numpy as np
from scipy.linalg import solve_triangular
from scipy.optimize import minimize
from scipy.special import ndtr, ndtri
from scipy.stats import qmc
from sklearn.calibration import CalibratedClassifierCV
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from sklearn.model_selection import StratifiedKFold
from sklearn.svm import SVC
from qdpy.base import registry
from qdpy.containers import Grid, ParetoGrid
from .modern import _FixedGeneration, _bounds, _positive_int
__all__ = ["BOPElites", "BayesianParetoIllumination"]
def _expected_improvement(mean, deviation, target):
gain = mean - target
z = np.divide(gain, deviation, out=np.zeros_like(gain), where=deviation > 0)
ei = gain * ndtr(z) + deviation * np.exp(-0.5 * z ** 2) / sqrt(2 * np.pi)
return np.where(deviation > 0, np.maximum(ei, 0), np.maximum(gain, 0))
def _region_probabilities(mean, deviation, lower, upper, closed):
low_delta, high_delta = lower - mean, upper - mean
z_lower = np.divide(low_delta, deviation, out=np.zeros_like(low_delta), where=deviation > 0)
z_upper = np.divide(high_delta, deviation, out=np.zeros_like(high_delta), where=deviation > 0)
# Evaluate the upper tail by symmetry to avoid subtracting numbers near one.
mass = np.where(z_lower >= 0, ndtr(-z_lower) - ndtr(-z_upper), ndtr(z_upper) - ndtr(z_lower))
point = (mean >= lower) & ((mean < upper) | (closed & (mean == upper)))
return np.prod(np.where(deviation > 0, mass, point), axis=-1)
def _joint_improvement(probability, improvement, cutoff):
if cutoff is None:
return probability * improvement
weights = np.where(probability > cutoff, probability, 0)
total = weights.sum(axis=-1, keepdims=True)
weights = np.divide(weights, total, out=weights, where=total > 0)
return weights * improvement
class _SharedGaussianProcesses(tuple):
"""Share the fitted input geometry of independent, fixed-kernel GPs."""
@classmethod
def of(cls, models):
if not models or not all(
type(model) is GaussianProcessRegressor and type(getattr(model, "kernel_", None)) is Matern
and np.isscalar(getattr(model, "_y_train_mean", None))
and np.isscalar(getattr(model, "_y_train_std", None))
and model.alpha_.ndim == 1 for model in models
):
return models
first = models[0]
if all(np.array_equal(model.X_train_, first.X_train_)
and np.array_equal(model.kernel_.theta, first.kernel_.theta)
and model.kernel_.nu == first.kernel_.nu
and np.array_equal(model.L_, first.L_) for model in models[1:]):
return cls(models)
return models
## @brief Evaluate a common kernel and variance solve for all responses.
def predict(self, points):
"""Return response columns, or defer to the individual predictors."""
first = self[0]
if (type(points) is not np.ndarray or points.ndim != 2 or not len(points)
or points.dtype != np.float64 or points.shape[1] != first.X_train_.shape[1]
or not np.isfinite(points).all()):
return None
kernel = first.kernel_(points, first.X_train_)
triangle = solve_triangular(first.L_, kernel.T, lower=True, check_finite=False)
variance = first.kernel_.diag(points).copy()
variance -= np.einsum("ij,ji->i", triangle.T, triangle)
if np.any(variance < 0):
# Preserve the individual predictors' numerical warning and correction.
return None
means, deviations = [], []
for model in self:
# Keep scikit-learn's per-target matvec and scaling arithmetic.
means.append(model._y_train_std * (kernel @ model.alpha_) + model._y_train_mean)
deviations.append(np.sqrt(np.outer(variance, model._y_train_std**2).ravel()))
return np.asarray(means).T, np.asarray(deviations).T
## @brief Select one genuine evaluation with expected joint improvement of elites.
[docs]
@registry.register
class BOPElites(_FixedGeneration):
"""Fit independent objective and descriptor Gaussian processes after each observation.
A scrambled Sobol sequence supplies initial points and acquisition
restarts. The result grid contains genuine evaluations. Surrogates include
finite observations that did not improve an elite or fell outside the grid.
Powell search is bounded to the supplied decision domain.
With feasibility modelling enabled, return
``(None, None, {"bop_valid": False})`` for a known infeasible design.
Unsuccessful calls without explicit infeasibility teach neither the
quality models nor the feasibility model.
With a descriptor transform, return the measured sources as
``(fitness, None, {"bop_latents": values})``. The same transform sets
measured descriptors and projects posterior samples during acquisition.
:param container: One-elite Grid with one or two descriptor axes.
:param budget: Maximum number of genuine evaluation attempts per run.
:param dimension: Number of continuous decision coordinates.
:param ind_domain: Common lower and upper decision bounds.
:param quality_floor: Empty-cell comparison value in signed quality units.
:param initial_samples: Number of Sobol proposals before modelling, default
ten times the decision dimension.
:param candidate_pool: Number of Sobol points scored at each modelled step.
:param restarts: Maximum number of local acquisition searches per step.
:param seed: Optional seed for the Sobol sequence.
:param model_feasibility: Weight acquisition by a calibrated SVM after
at least three valid and three explicitly infeasible observations.
:param descriptor_transform: Optional vectorized function of two arrays,
raw genomes and measured or predicted latent rows. Return one
descriptor row per input row. Use ordinary Grid features.
:param latent_size: Number of measured source values when a transform is set.
:param posterior_samples: Power-of-two number of shared normal draws for
joint descriptor probabilities.
"""
_requires_proposed_genome = True
_bop_batch_size = 1
# Defaults also cover archives loaded from older BOPElites pickles.
model_feasibility = False
descriptor_transform = None
_feasibility_model = None
_explicit_invalid = False
@staticmethod
def _validate_grid(container):
if (type(container) is not Grid or len(container.shape) not in (1, 2)
or container.max_items_per_bin != 1 or len(container.fitness_domain) != 1):
raise ValueError("BOPElites requires a one-elite Grid for one objective and one or two descriptors.")
def __init__(self, container, budget, dimension, ind_domain, quality_floor, *,
initial_samples=None, candidate_pool=128, restarts=8, seed=None,
model_feasibility=False, descriptor_transform=None, latent_size=None,
posterior_samples=256, **kwargs):
self._validate_grid(container)
lower, upper = np.asarray(container.features_domain, dtype=float).T
if len(lower) != len(container.shape) or not np.all(np.isfinite([lower, upper])) or np.any(lower >= upper):
raise ValueError("Provide finite increasing bounds for each descriptor axis.")
if not isfinite(quality_floor):
raise ValueError("quality_floor must be finite.")
dimension = _positive_int(dimension, "dimension")
self.ind_domain = _bounds(ind_domain)
self.quality_floor = quality_floor
self.initial_samples = 10 * dimension if initial_samples is None else _positive_int(initial_samples, "initial_samples")
self.candidate_pool = _positive_int(candidate_pool, "candidate_pool")
self.restarts = _positive_int(restarts, "restarts")
self.seed = seed
self.model_feasibility = model_feasibility
self.descriptor_transform = descriptor_transform
if descriptor_transform is not None:
if not callable(descriptor_transform) or container.features_score_names:
raise ValueError("Use a callable descriptor transform with ordinary grid features.")
self.latent_size = _positive_int(latent_size, "latent_size")
self.posterior_samples = _positive_int(posterior_samples, "posterior_samples")
if self.posterior_samples & (self.posterior_samples - 1):
raise ValueError("posterior_samples must be a power of two.")
elif latent_size is not None:
raise ValueError("latent_size requires a descriptor transform.")
self._cells = tuple(container.solutions)
cells = np.asarray(self._cells)
width = (upper - lower) / np.asarray(container.shape)
if descriptor_transform is not None:
if np.any(width <= 0) or not np.isfinite(width).all():
raise ValueError("The grid needs finite positive cell widths.")
self._descriptor_bounds = lower, upper, width
self._region_lower = lower + cells * width
self._closed_upper = cells == np.asarray(container.shape) - 1
self._region_upper = np.where(self._closed_upper, upper, lower + (cells + 1) * width)
super().__init__(container, _positive_int(budget, "budget"), batch_size=self._bop_batch_size,
dimension=dimension, **kwargs)
def reinit(self):
"""Reset the Sobol stream, observations, and acquisition counters."""
super().reinit()
self._sobol = None
self._seen = set()
self._observations = []
self._misclassified = 0
self._all_cut_off = 0
self._prediction_cell = None
self._unit_candidate = None
self._posterior_normals = None
self._validity = []
self._feasibility_model = None
self._explicit_invalid = False
self._reported_latents = None
@property
def n_observations(self):
"""Number of finite observations available to the models."""
return len(self._observations)
@property
def n_invalid_observations(self):
"""Number of explicit infeasibility labels received in this run."""
return len(self._validity) - self.n_observations if self.model_feasibility else 0
def _sobol_point(self):
if self._sobol is None:
seed = random.randrange(2**32) if self.seed is None else self.seed
self._sobol = qmc.Sobol(self.dimension, scramble=True, seed=seed)
for _ in range(1024):
point = self._sobol.random(1)[0]
if tuple(self._raw_point(point)) not in self._seen:
return point
raise RuntimeError("The Sobol stream could not find an unseen genome in the decision bounds.")
def _raw_point(self, point):
lower, upper = self.ind_domain
return lower + point * (upper - lower)
def _fit_models(self):
points = np.asarray([point for point, _ in self._observations])
targets = np.asarray([target for _, target in self._observations])
models = []
for column in targets.T:
kernel = Matern(length_scale=[0.25] * self.dimension, nu=2.5)
model = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, normalize_y=True, optimizer=None)
models.append(model.fit(points, column))
return _SharedGaussianProcesses.of(models)
def _fit_feasibility(self):
if min(self.n_invalid_observations, self.n_observations) < 3:
return None
points, valid = zip(*self._validity)
folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=0)
model = CalibratedClassifierCV(SVC(), method="sigmoid", cv=folds, ensemble=False)
return model.fit(np.asarray(points), np.asarray(valid, dtype=int))
def _descriptors(self, genomes, latents):
descriptors = np.asarray(self.descriptor_transform(genomes, latents), dtype=float)
if descriptors.shape != (len(genomes), len(self.container.shape)) or not np.isfinite(descriptors).all():
raise ValueError("The descriptor transform must return one finite descriptor vector per row.")
return descriptors
def _structured_probabilities(self, points, means, deviations):
if self._posterior_normals is None:
seed = random.randrange(2**32) if self.seed is None else self.seed
stream = np.random.SeedSequence(seed).spawn(1)[0]
sobol = qmc.Sobol(self.latent_size, scramble=True, seed=np.random.default_rng(stream))
unit = sobol.random_base2(self.posterior_samples.bit_length() - 1)
eps = np.finfo(float).eps
self._posterior_normals = ndtri(np.clip(unit, eps, 1. - eps))
samples = means[:, None, :] + deviations[:, None, :] * self._posterior_normals
genomes = np.repeat(self._raw_point(points), self.posterior_samples, axis=0)
descriptors = self._descriptors(genomes, samples.reshape(-1, self.latent_size))
lower, upper, width = self._descriptor_bounds
inside = np.all((descriptors >= lower) & (descriptors <= upper), axis=1)
shape = np.asarray(self.container.shape)
indices = np.minimum(shape - 1, ((descriptors[inside] - lower) / width).astype(np.intp))
flat_cells = np.ravel_multi_index(indices.T, self.container.shape)
point_ids = np.flatnonzero(inside) // self.posterior_samples
column_count = len(self._cells)
counts = np.bincount(point_ids * column_count + flat_cells, minlength=len(points) * column_count)
probabilities = counts.reshape(len(points), column_count) / self.posterior_samples
draws = descriptors.reshape(len(points), self.posterior_samples, -1)
locations = draws.mean(axis=1)
deterministic = np.all(deviations == 0., axis=1)
locations[deterministic] = draws[deterministic, 0]
return probabilities, locations
def _thresholds(self):
thresholds = []
for cell in self._cells:
front = self.container.solutions[cell]
if front:
fitness = self.container.get_ind_fitness(front[0])
thresholds.append(fitness.values[0] * fitness.weights[0])
else:
thresholds.append(self.quality_floor)
return np.array(thresholds)
def _posterior(self, models, points):
prediction = models.predict(points) if type(models) is _SharedGaussianProcesses else None
if prediction is None:
predictions = [model.predict(points, return_std=True) for model in models]
means = np.asarray([mean for mean, _ in predictions]).T
deviations = np.asarray([deviation for _, deviation in predictions]).T
return means, deviations
return prediction
def _acquisition(self, models, points, thresholds, cutoff):
means, deviations = self._posterior(models, points)
if self.descriptor_transform is None:
probabilities = _region_probabilities(
means[:, None, 1:], deviations[:, None, 1:], self._region_lower,
self._region_upper, self._closed_upper,
)
descriptor_means = means[:, 1:]
else:
probabilities, descriptor_means = self._structured_probabilities(
points, means[:, 1:], deviations[:, 1:])
improvement = _expected_improvement(means[:, :1], deviations[:, :1], thresholds)
contributions = _joint_improvement(probabilities, improvement, cutoff)
if self.descriptor_transform is not None and cutoff is not None:
# Keep the total probability of falling within the grid after truncation.
contributions *= probabilities.sum(axis=1, keepdims=True)
if self._feasibility_model is not None:
contributions *= self._feasibility_model.predict_proba(points)[:, 1, None]
return contributions, descriptor_means
def _predicted_cell(self, features):
try:
return self.container.index_grid(features)
except IndexError:
return None
def _probability_cutoff(self):
denominator = max(1, self.nb_evaluations + self._misclassified - 2 * self._all_cut_off)
return 0.5 * (2 / len(self._cells)) ** sqrt(10 * self.dimension / denominator)
def _modelled_point(self):
models = self._fit_models()
if self.model_feasibility:
self._feasibility_model = self._fit_feasibility()
thresholds = self._thresholds()
pool = np.asarray([self._sobol_point() for _ in range(self.candidate_pool)])
cutoff = self._probability_cutoff()
contributions, means = self._acquisition(models, pool, thresholds, cutoff)
if cutoff is not None and not np.any(contributions > 0):
self._all_cut_off += 1
cutoff = None
contributions, means = self._acquisition(models, pool, thresholds, cutoff)
values = contributions.sum(axis=1)
order = np.argsort(-values, kind="stable")
selected = int(order[0])
best = pool[selected]
best_value = values[selected]
best_contributions = contributions[selected]
visited = set()
def acquire(point):
regional = self._acquisition(models, point[None, :], thresholds, cutoff)[0][0]
return regional
for row in order:
predicted = self._predicted_cell(means[row])
if predicted in visited:
continue
visited.add(predicted)
candidate = minimize(lambda point: -float(acquire(point).sum()), pool[row], method="Powell",
bounds=[(0, 1)] * self.dimension, options={"maxiter": 8, "maxfev": 50}).x
candidate = np.clip(candidate, 0, 1)
if tuple(self._raw_point(candidate)) not in self._seen:
regional = acquire(candidate)
value = regional.sum()
if value > best_value:
best, best_value, best_contributions = candidate, value, regional
if len(visited) >= self.restarts:
break
region = int(np.argmax(best_contributions))
self._prediction_cell = self._cells[region] if best_contributions[region] > best_value / 2 else None
return best
def _internal_ask(self, base_ind):
self._explicit_invalid = False
self._reported_latents = None
if self.nb_suggestions < self.initial_samples or self.n_observations < 2:
self._unit_candidate = self._sobol_point()
self._prediction_cell = None
else:
self._unit_candidate = self._modelled_point()
# Key the proposed genome in raw coordinates. Distinct normalised
# floats can map to the same genome when the user chooses tight bounds.
base_ind[:] = self._raw_point(self._unit_candidate)
self._seen.add(tuple(base_ind))
return base_ind
def _check_candidate(self, individual):
self._check_measurements(individual)
if len(self.container.get_ind_features(individual)) != len(self.container.shape):
raise ValueError("Descriptor length must match the grid.")
def tell(self, individual, fitness=None, features=None, scores=None,
elapsed=None, verbose=False, tell_container=True):
"""Stage a native result, including optional feasibility and source values."""
if self.model_feasibility or self.descriptor_transform is not None:
if not self._staging:
raise RuntimeError("Use tell_batch() to report a manual generation.")
if tuple(individual) != self._expected_genome:
raise ValueError("The evaluated genome differs from the proposal for this slot.")
metadata = individual.scores if scores is None else scores
if self.model_feasibility:
valid = metadata["bop_valid"] if "bop_valid" in metadata else True
if not isinstance(valid, (bool, np.bool_)):
raise ValueError("bop_valid must be a boolean.")
if not valid:
self._explicit_invalid = True
return False
if self.descriptor_transform is not None:
latents = np.asarray(metadata["bop_latents"], dtype=float)
if latents.shape != (self.latent_size,) or not np.isfinite(latents).all():
raise ValueError("bop_latents must contain one finite value per measured source.")
features = tuple(self._descriptors(np.asarray(individual, dtype=float)[None, :],
latents[None, :])[0])
self._reported_latents = tuple(latents)
return super().tell(individual, fitness, features, scores, elapsed, verbose, tell_container)
def _commit_generation(self, evaluated):
individual = evaluated[0]
if individual is None:
if self._explicit_invalid:
self._validity.append((self._unit_candidate.copy(), False))
return set()
archive = self.container
fitness = archive.get_ind_fitness(individual)
features = tuple(archive.get_ind_features(individual))
quality = fitness.values[0] * fitness.weights[0]
point = self._unit_candidate.copy()
sources = features if self.descriptor_transform is None else self._reported_latents
self._observations.append((point, (quality, *sources)))
if self.model_feasibility:
self._validity.append((point, True))
actual = self._predicted_cell(features)
if self._prediction_cell is not None and self._prediction_cell != actual:
self._misclassified += 1
if actual is None or not archive.in_bounds(fitness.values, archive.fitness_domain):
return set()
return {0} if self._offer_to_grid(individual, actual) else set()
## @brief Partition the undominated region into vertical strips in maximization coordinates.
def _improvement_strips(front, reference):
left = reference[0]
strips = []
for x, y in sorted(set(map(tuple, front)), key=lambda point: (point[0], -point[1])):
if x > left:
strips.append((left, x, y))
left = x
strips.append((left, np.inf, reference[1]))
return np.asarray(strips)
## @brief Integrate the independent Gaussian survival probabilities over the strips.
def _expected_hypervolume_improvement(means, deviations, strips):
left, right, bottom = strips.T
gain = _expected_improvement(means[:, :1], deviations[:, :1], left)
finite = np.isfinite(right)
gain[:, finite] -= _expected_improvement(means[:, :1], deviations[:, :1], right[finite])
height = _expected_improvement(means[:, 1:], deviations[:, 1:], bottom)
return np.sum(np.maximum(gain, 0.) * height, axis=1)
## @brief Combine probability of cell membership with exact two-objective Gaussian EHVI.
# @see https://arxiv.org/abs/2307.09326
# @see https://proceedings.neurips.cc/paper/2020/hash/6fec24eac8f18ed793f5eaad3dd7977c-Abstract.html
[docs]
@registry.register
class BayesianParetoIllumination(BOPElites):
"""Sequential Bayesian illumination of measured two-objective Pareto fronts.
Fit independent fixed-kernel GP models for each objective and descriptor.
For each candidate, sum per-cell expected hypervolume improvement
multiplied by the probability of landing in that cell. Use actual
evaluations for Pareto admission. Finite evaluations outside the
archive bounds can still inform the models.
:param container: A crowding ParetoGrid with two objectives and one or two
descriptors. Use direct fitness and features.
:param budget: Number of true evaluation attempts.
:param dimension: Number of bounded real decision variables.
:param ind_domain: Shared finite decision bounds.
:param reference: Two raw objective coordinates weakly dominated by the
worst objective corner of the declared fitness domain.
:param initial_samples: Number of initial Sobol proposals.
:param candidate_pool: Sobol candidates screened per acquisition.
:param restarts: Maximum number of local acquisition refinements.
:param seed: Seed for the scrambled Sobol proposal stream.
"""
@staticmethod
def _validate_grid(container):
if (type(container) is not ParetoGrid or len(container.shape) not in (1, 2)
or len(container.fitness_domain) != 2 or container.truncation != "crowding"
or container.fitness_score_names or container.features_score_names):
raise ValueError("Use a two-objective crowding ParetoGrid with one or two direct descriptors.")
def __init__(self, container, budget, dimension, ind_domain, *, reference,
initial_samples=None, candidate_pool=128, restarts=8, seed=0):
self._validate_grid(container)
direction = np.sign(container.fitness_weights)
ref = np.asarray(reference, dtype=float)
bounds = np.asarray(container.fitness_domain, dtype=float)
worst = np.where(direction > 0, bounds[:, 0], -bounds[:, 1])
if ref.shape != (2,) or not np.isfinite(ref).all() or not np.all(direction * ref <= worst):
raise ValueError("The finite reference point must be weakly dominated by the fitness domain.")
self.reference = tuple(ref)
self._direction = direction
self._signed_reference = direction * ref
super().__init__(container, budget, dimension, ind_domain, quality_floor=0.,
initial_samples=initial_samples, candidate_pool=candidate_pool, restarts=restarts,
seed=seed, optimisation_task=container.fitness_weights)
def _probability_cutoff(self):
return None
def _thresholds(self):
return [
_improvement_strips([self._direction * ind.fitness.values for ind in self.container.solutions[cell]],
self._signed_reference)
for cell in self._cells
]
def _acquisition(self, models, points, thresholds, cutoff):
means, deviations = self._posterior(models, points)
descriptors = means[:, 2:]
probabilities = _region_probabilities(
descriptors[:, None, :], deviations[:, None, 2:], self._region_lower,
self._region_upper, self._closed_upper)
improvement = np.column_stack([
_expected_hypervolume_improvement(means[:, :2], deviations[:, :2], strips)
for strips in thresholds
])
return probabilities * improvement, descriptors
def _check_candidate(self, individual):
super()._check_candidate(individual)
if len(individual.fitness.values) != 2:
raise ValueError("Supply exactly two measured objectives.")
def _commit_generation(self, evaluated):
individual = evaluated[0]
if individual is None:
return set()
fitness, features = individual.fitness.values, tuple(individual.features)
self._observations.append((self._unit_candidate.copy(), (*self._direction * fitness, *features)))
if self._predicted_cell(features) is None or not self.container.in_bounds(fitness, self.container.fitness_domain):
return set()
return {0} if self.container._merge_fronts([individual]) else set()