Source code for qdpy.algorithms.safe_illumination

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Gate finite-pool Bayesian illumination with a separate safety model.
# @see https://proceedings.mlr.press/v80/sui18a.html

"""Expand an estimated safe set before optimizing its descriptor niches."""

from dataclasses import dataclass
from operator import index

import numpy as np
from scipy.spatial.distance import cdist
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern

from .bayesian import _expected_improvement
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["SafeBayesianIllumination", "SafeIlluminationTrial"]


## @brief One attempted trial and the observations available afterward.
[docs] @dataclass(frozen=True) class SafeIlluminationTrial: """The phase is "seed", "expansion", or "illumination".""" index: int phase: str fitness: float | None = None margins: tuple[float, ...] | None = None
def _safety_vector(values, count, label): vector = np.broadcast_to(np.asarray(values, dtype=float), (count,)).copy() if not np.isfinite(vector).all() or (vector < 0.).any(): raise ValueError(f"{label} must contain finite nonnegative values.") return vector ## @brief Illuminate a pool of measurable designs while separating safety and quality.
[docs] class SafeBayesianIllumination: """Use a StageOpt-inspired expansion phase and then per-niche improvement. :param archive: Empty parentless best-only Grid or CVTGrid. :param points: Finite matrix of distinct real candidate genomes. :param descriptors: Known descriptor vector for each candidate. All must lie in the reporting archive's descriptor domain. :param safe_seeds: Ordered distinct indices trusted safe to evaluate. Their evaluations count against the same budget as other trials. :param constraints: Number of reported safety margins. Zero is safe. :param expansion_budget: Maximum post-seed attempts in the expansion phase. :param quality_floor: Raw objective baseline for an empty niche. The default uses the archive's worst allowed objective. :param confidence: Safety confidence multiplier for the Gaussian processes. :param length_scale: Fixed Matérn length scale in raw decision units. :param noise: Positive GP diagonal regularization. :param lipschitz: Scalar or per-constraint Lipschitz upper bounds in raw Euclidean units. When supplied, use the deterministic margin certificates for dispatch and the GPs for ranking. :param observation_error: Absolute bound on measurement error for each safety margin in Lipschitz mode. """ def __init__(self, archive, points, descriptors, *, safe_seeds, constraints=1, expansion_budget=8, quality_floor=None, confidence=3., length_scale=.2, noise=1e-6, lipschitz=None, observation_error=0.): _validate_grid(archive) points = np.array(points, dtype=float, copy=True) features = np.array(descriptors, dtype=float, copy=True) if (points.ndim != 2 or not points.size or not np.isfinite(points).all() or len({tuple(row) for row in points}) != len(points)): raise ValueError("Supply a nonempty matrix of distinct finite candidates.") if (features.shape != (len(points), len(archive.features_domain)) or not np.isfinite(features).all() or any(not archive.in_bounds(row, archive.features_domain) for row in features)): raise ValueError("Supply one finite in-domain descriptor vector per candidate.") seeds = tuple(map(index, safe_seeds)) if not seeds or len(set(seeds)) != len(seeds) or any(not 0 <= i < len(points) for i in seeds): raise ValueError("Supply distinct valid indices for the trusted safe seeds.") if not np.isfinite((confidence, length_scale, noise)).all() or min(confidence, length_scale, noise) <= 0.: raise ValueError("Use a positive finite confidence, length scale, and GP noise.") constraints = _positive_int(constraints, "constraints") expansion_budget = index(expansion_budget) if expansion_budget < 0: raise ValueError("expansion_budget must be nonnegative.") weights = archive.fitness_weights or (1.,) self._weights = tuple(weights) self._direction = 1. if weights[0] > 0. else -1. if quality_floor is None: quality_floor = archive.fitness_domain[0][int(self._direction < 0.)] if not np.isfinite(quality_floor): raise ValueError("Supply a finite raw quality_floor for an unbounded fitness domain.") self._floor = self._direction * float(quality_floor) self._lipschitz = None if lipschitz is None else _safety_vector(lipschitz, constraints, "lipschitz") self._error = _safety_vector(observation_error, constraints, "observation_error") if self._lipschitz is None and np.any(self._error): raise ValueError("Use observation_error with Lipschitz bounds.") self._distances = cdist(points, points) if not np.isfinite(self._distances).all(): raise ValueError("Candidate distances must be finite.") self._cells = tuple(archive.index_grid(row) for row in features) if archive.fitness_weights is None: archive._set_fitness_weights(weights) self.archive = archive self._points, self._features = points, features self._confidence, self._length, self._noise = confidence, length_scale, noise self._seeds, self._constraints = seeds, constraints self._expansion_budget = expansion_budget self._trials = [] self._attempted = np.zeros(len(points), dtype=bool) self._inputs, self._safety, self._quality = [], [], [] self._expansion_trials = 0 self._expanding = True self._halted = False @property def trials(self): """Return attempts in dispatch order, including failed evaluations.""" return tuple(self._trials) @property def halted(self): """Return whether an observed negative safety margin stopped the search.""" return self._halted def _gp(self, observations, *, normalize=False): estimator = GaussianProcessRegressor(kernel=Matern(self._length, nu=2.5), alpha=self._noise, normalize_y=normalize, optimizer=None) return estimator.fit(self._points[self._inputs], observations) def _certificates(self): if not self._inputs: safe = np.full((len(self._points), self._constraints), -np.inf) return safe, None, None means, stds = [], [] for values in np.asarray(self._safety).T: mean, std = self._gp(values).predict(self._points, return_std=True) means.append(mean) stds.append(std) mean, spread = np.asarray(means).T, np.asarray(stds).T if self._lipschitz is None: lower = mean - self._confidence * spread else: distances = self._distances[self._inputs, :, None] margin = np.asarray(self._safety)[:, None, :] - self._error lower = np.max(margin - distances * self._lipschitz, axis=0) return lower, mean + self._confidence * spread, spread def _safe_mask(self, lower): mask = np.all(lower >= 0., axis=1) mask[list(self._seeds)] = True return mask ## @brief List candidates currently supported by the safety rules.
[docs] def certified_indices(self): """Return safe-set indices, including trusted seeds, or empty after a halt.""" if self._halted: return () lower, _, _ = self._certificates() return tuple(map(int, np.flatnonzero(self._safe_mask(lower))))
def _choose_expander(self, ready, unknown, lower, upper, spread): if self._lipschitz is None: # Use uncertainty near the uncertified frontier as an expansion proxy. nearest = self._distances[np.ix_(ready, unknown)].min(axis=1) score = spread[ready].sum(axis=1) * np.exp(-nearest / self._length) return int(ready[np.argmax(score)]) best, best_rank = None, (0, 0.) for slot in ready: possible = upper[slot] - self._error - self._distances[slot, unknown, None] * self._lipschitz gain = int(np.count_nonzero(np.all((lower[unknown] >= 0.) | (possible >= 0.), axis=1))) rank = (gain, float(spread[slot].sum())) if gain and rank > best_rank: best, best_rank = int(slot), rank return best def _choose_quality(self, ready): model = self._gp(self._quality, normalize=True) mean, deviation = model.predict(self._points[ready], return_std=True) targets = [] for slot in ready: front = self.archive.solutions[self._cells[slot]] targets.append(self._direction * self.archive.get_ind_fitness(front[0]).values[0] if front else self._floor) return int(ready[np.argmax(_expected_improvement(mean, deviation, np.asarray(targets)))]) def _next_trial(self): for slot in self._seeds: if not self._attempted[slot]: return slot, "seed" if not self._inputs: return None lower, upper, spread = self._certificates() mask = self._safe_mask(lower) ready = np.flatnonzero(mask & ~self._attempted) if not len(ready): return None unknown = np.flatnonzero(~mask & ~self._attempted) if self._expanding and len(unknown) and self._expansion_trials < self._expansion_budget: slot = self._choose_expander(ready, unknown, lower, upper, spread) if slot is not None: return slot, "expansion" self._expanding = False return self._choose_quality(ready), "illumination" def _observe(self, slot, phase, evaluate): self._attempted[slot] = True self._expansion_trials += phase == "expansion" row = SafeIlluminationTrial(slot, phase) try: genome = tuple(map(float, self._points[slot])) outcome = evaluate(genome) if outcome is None: return fitness, margins = outcome margins = tuple(map(float, margins)) if len(margins) != self._constraints or not np.isfinite(margins).all(): raise ValueError("Return the configured number of finite safety margins.") self._halted = any(margin < 0. for margin in margins) row = SafeIlluminationTrial(slot, phase, margins=margins) measured = _measurement(self.archive, ((fitness,), self._features[slot]), genome) fitness = measured[0].fitness.values[0] row = SafeIlluminationTrial(slot, phase, fitness, margins) if self._halted: return self._inputs.append(slot) self._safety.append(margins) self._quality.append(self._direction * fitness) _offer(self.archive, measured) finally: self._trials.append(row) ## @brief Spend up to the requested number of additional safe-pool trials.
[docs] def run(self, evaluate, *, budget): """Use evaluate(genome) for (scalar fitness, safety-margin vector) or None. Each pool candidate is evaluated at most once. Stop when no new point satisfies the safety gate or a violation is observed. The GP gate depends on calibrated confidence bounds. A Lipschitz gate depends on correct supplied constants and measurement error. """ if not callable(evaluate): raise TypeError("Supply a callable evaluator.") if tuple(self.archive.fitness_weights or ()) != self._weights: raise ValueError("The archive objective weights changed.") for _ in range(_positive_int(budget, "budget")): selection = None if self._halted else self._next_trial() if selection is None: break self._observe(*selection, evaluate) return self.archive