Source code for qdpy.algorithms.boil

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Interactive Bayesian illumination with explicit measurement budgets.

"""Bayesian Optimization with Interactive Illumination."""

from dataclasses import dataclass
from math import log
from operator import index

import numpy as np
from scipy.special import ndtri, xlogy
from scipy.stats import qmc

from qdpy.base import registry
from .bayesian import BOPElites, _expected_improvement, _region_probabilities
from .modern import _positive_int

__all__ = ["BOIL", "BOILPrediction", "BOILTargetResult"]


## @brief Predicted cell representative and its posterior membership probability.
[docs] @dataclass(frozen=True) class BOILPrediction: """A surrogate estimate for inspection before running a real evaluation.""" cell: tuple[int, ...] genome: tuple[float, ...] fitness_mean: float descriptor_mean: tuple[float, ...] probability: float
## @brief Best actual measurement for the currently requested descriptor target.
[docs] @dataclass(frozen=True) class BOILTargetResult: """Report measured fitness, descriptors and target utility in their original units.""" genome: tuple[float, ...] fitness: float descriptors: tuple[float, ...] utility: float
## @brief Alternate model building, focused illumination, and search for a chosen descriptor.
[docs] @registry.register class BOIL(BOPElites): """Bayesian Optimization with Interactive Illumination (Kent and Branke, 2023). Reuse the measured design and descriptor posteriors across all three phases. Use a fixed one- or two-dimensional rectangular reporting grid. Model building multiplies expected joint improvement by one plus the normalized entropy of posterior region membership. Focused illumination considers only selected cells. Target search uses common Monte Carlo draws to estimate the expected improvement in target utility. :param container: Best-only Grid with one objective and one or two descriptors. :param budget: Total measurement attempts across repeated optimise calls and manual batches. :param dimension: Length of a real-valued genome. :param ind_domain: Common lower and upper decision bounds. :param quality_floor: Empty-cell threshold in weighted fitness units. :param entropy_weight: Nonnegative multiplier on normalized descriptor entropy. :param target_samples: Power-of-two count of fixed, scrambled Sobol posterior draws. :param kwargs: Native optimizer arguments and BOP-Elites initialization and search settings. """ def __init__(self, container, budget, dimension, ind_domain, quality_floor, *, entropy_weight=1., target_samples=64, **kwargs): if not 0 <= entropy_weight < np.inf: raise ValueError("entropy_weight must be finite and nonnegative.") self.entropy_weight = float(entropy_weight) self.evaluation_limit = _positive_int(budget, "budget") self.target_samples = _positive_int(target_samples, "target_samples") if self.target_samples & (self.target_samples - 1): raise ValueError("target_samples must be a power of two.") unsupported = ("model_feasibility", "descriptor_transform", "latent_size") if any(name in kwargs for name in unsupported): raise TypeError("BOIL takes direct descriptor observations.") super().__init__(container, budget, dimension, ind_domain, quality_floor, **kwargs) if (not self._fitness_weights[0] or not np.isfinite(self.ind_domain[1] - self.ind_domain[0]) or not np.isfinite(self._region_upper - self._region_lower).all()): raise ValueError("Use finite search widths and a nonzero fitness weight.") def reinit(self): """Reset measurements, the phase, and the lifetime attempt count.""" super().reinit() self._focus = None self._target = None self._distance_weight = 0. self._target_baseline = None stream = qmc.Sobol(len(self.container.shape) + 1, scramble=True, seed=0 if self.seed is None else self.seed) self._draws = ndtri(np.clip(stream.random_base2(self.target_samples.bit_length() - 1), 1e-12, 1 - 1e-12)) @property def remaining_evaluations(self): """Return the number of attempts still available, including future phases.""" return self.evaluation_limit - self.nb_evaluations def _expect_idle(self): if self._pending_size: raise RuntimeError("Finish the outstanding BOIL batch before changing phases.") ## @brief Restrict the illumination phase to grid cells selected from the preview.
[docs] def focus(self, cells=None): """Select a nonempty sequence of grid indices, or pass None to use the full map.""" self._expect_idle() ranks = None if cells is not None: selected = {tuple(index(axis) for axis in cell) for cell in cells} if not selected or not selected.issubset(self.container.solutions): raise ValueError("Select at least one valid grid cell.") ranks = np.array([cell in selected for cell in self._cells]) self._focus, self._target = ranks, None
## @brief Search for measured solutions with a chosen target descriptor.
[docs] def set_target(self, descriptor, *, distance_weight=1.): """Maximize weighted fitness minus distance_weight times Euclidean descriptor error.""" self._expect_idle() target = np.asarray(descriptor, dtype=float) if (target.shape != (len(self.container.shape),) or not np.isfinite(target).all() or not self.container.in_bounds(target, self.container.features_domain)): raise ValueError("The target must be finite and within the descriptor domain.") if not 0 <= distance_weight < np.inf: raise ValueError("distance_weight must be finite and nonnegative.") self._target = target.copy() self._distance_weight = float(distance_weight) self._focus = None
def _utility(self, values): if self._distance_weight == 0: return values[..., 0] distances = np.linalg.norm(values[..., 1:] - self._target, axis=-1) return values[..., 0] - self._distance_weight * distances ## @brief Find the strongest measured target utility, including measurements rejected by the grid.
[docs] def best_target(self): """Return a BOILTargetResult for the active target, or None before any observations.""" if self._target is None: raise RuntimeError("Call set_target() before requesting target results.") if not self._observations: return None values = np.asarray([row for _, row in self._observations]) scores = self._utility(values) row = int(np.argmax(scores)) return BOILTargetResult(tuple(map(float, self._raw_point(self._observations[row][0]))), float(values[row, 0] / self._fitness_weights[0]), tuple(map(float, values[row, 1:])), float(scores[row]))
def _probabilities(self, means, deviations): return _region_probabilities(means[:, None, 1:], deviations[:, None, 1:], self._region_lower, self._region_upper, self._closed_upper) def _modelled_point(self): if self._target is not None: self._target_baseline = self.best_target().utility return super()._modelled_point() def _acquisition(self, models, points, thresholds, cutoff): means, deviations = self._posterior(models, points) if self._target is not None: samples = means[:, None, :] + deviations[:, None, :] * self._draws gains = np.maximum(self._utility(samples) - self._target_baseline, 0.).mean(axis=1) # BOPElites uses the regional axis to choose restarts and track predictions. contributions = np.zeros((len(points), len(self._cells))) slot = self._cells.index(self.container.index_grid(self._target)) contributions[:, slot] = gains else: probabilities = self._probabilities(means, deviations) if self._focus is not None: probabilities[:, ~self._focus] = 0. improvement = _expected_improvement(means[:, :1], deviations[:, :1], thresholds) entropy = -xlogy(probabilities, probabilities).sum(axis=1) / log(max(2, len(self._cells))) contributions = probabilities * improvement * (1 + self.entropy_weight * entropy[:, None]) return contributions, means[:, 1:] ## @brief Build a model-only prediction map without spending evaluations or advancing the search.
[docs] def prediction_map(self, *, samples=512, min_probability=.5, seed=0): """Return up to one provisional solution per cell, ranked by predicted weighted fitness.""" self._expect_idle() samples = _positive_int(samples, "samples") if not 0 < min_probability <= 1: raise ValueError("min_probability must be in (0, 1].") if len(self._observations) < 2: raise RuntimeError("Evaluate at least two valid solutions before building a preview.") points = qmc.Sobol(self.dimension, scramble=True, seed=seed).random_base2((samples - 1).bit_length()) points = np.vstack((points[:samples], [point for point, _ in self._observations])) means, deviations = self._posterior(self._fit_models(), points) probabilities = self._probabilities(means, deviations) predictions = [] for slot, cell in enumerate(self._cells): rows = np.flatnonzero(probabilities[:, slot] >= min_probability) if len(rows): row = rows[np.argmax(means[rows, 0])] predictions.append(BOILPrediction(cell, tuple(map(float, self._raw_point(points[row]))), float(means[row, 0] / self._fitness_weights[0]), tuple(map(float, means[row, 1:])), float(probabilities[row, slot]))) return tuple(predictions)
def _start_fixed_batch(self, size): if size > self.remaining_evaluations: raise RuntimeError("The BOIL evaluation budget is exhausted.") super()._start_fixed_batch(size) ## @brief Spend a phase budget within the lifetime evaluation limit.
[docs] def optimise(self, evaluate, budget=None, **kwargs): """Run an additional phase, using the remaining budget if none is given.""" count = self.remaining_evaluations if budget is None else _positive_int(budget, "budget") if count > self.remaining_evaluations: raise ValueError("The phase budget exceeds remaining_evaluations.") return super().optimise(evaluate, budget=count, **kwargs)