# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Local Bayesian optimization of separated portfolios.
# @see https://arxiv.org/html/2511.00750
"""Sequential and interleaved diversity-constrained TuRBO1."""
from dataclasses import dataclass
from math import isfinite
import numpy as np
from scipy.linalg import cholesky
from scipy.stats import qmc
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern
from .modern import _positive_int
from .parametric import _Coordinates
__all__ = ["DivTuRBO1", "DivTuRBOResult", "DivTuRBOPoint"]
## @brief A measured portfolio member in the original decision and objective units.
[docs]
@dataclass(frozen=True)
class DivTuRBOPoint:
"""Store the evaluated design and its raw fitness."""
genome: tuple[float, ...]
fitness: float
## @brief A portfolio with exact search costs and measured separation.
[docs]
@dataclass(frozen=True)
class DivTuRBOResult:
"""Minimum distance is None for a singleton portfolio."""
solutions: tuple[DivTuRBOPoint, ...]
evaluations_by_slot: tuple[int, ...]
restarts_by_slot: tuple[int, ...]
minimum_distance: float | None
violating_pairs: int
@property
def evaluations(self):
"""Return the total number of objective calls."""
return sum(self.evaluations_by_slot)
def _distances(points, references):
if not len(references):
return np.full(len(points), np.inf)
with np.errstate(over="ignore"):
return np.hypot.reduce(np.asarray(points)[:, None, :] - references, axis=2).min(axis=1)
def _selection(quality, distances, threshold):
feasible = np.flatnonzero(distances >= threshold)
if len(feasible):
return int(feasible[np.argmax(quality[feasible])]), True
farthest = np.flatnonzero(distances == distances.max())
return int(farthest[np.argmax(quality[farthest])]), False
def _thompson(points, observed, objectives, rng):
"""Draw a correlated posterior sample over one trust-region candidate pool."""
kernel = Matern(length_scale=np.full(points.shape[1], .25), nu=2.5)
scale = max(np.max(np.abs(objectives)), np.finfo(float).tiny)
model = GaussianProcessRegressor(kernel=kernel, alpha=1e-6, optimizer=None, normalize_y=True)
model.fit(observed, objectives / scale)
mean, cov = model.predict(points, return_cov=True)
# Repeated coordinates can make the latent posterior singular.
diagonal = np.diag_indices(len(cov))
cov[diagonal] += max(np.max(cov[diagonal]), 1.) * 1e-10
return mean + cholesky(cov, lower=True) @ rng.standard_normal(len(points))
class _TrustRegion:
def __init__(self, search, rng, evaluate):
self.search, self.rng, self.evaluate = search, rng, evaluate
self.dimension = len(search._coordinates.bounds)
self._sobol = qmc.Sobol(self.dimension, scramble=True, seed=int(rng.integers(2**32)))
self.history = []
self.restarts = 0
self._reset()
def _reset(self):
self.local = []
self.length = .8
self.successes = self.failures = self.no_centre = 0
def _measure(self, point):
genome = self.search._coordinates.physical(point)
fitness = float(self.evaluate(genome))
if not isfinite(fitness):
raise ValueError("Return one finite scalar objective.")
record = (point, DivTuRBOPoint(genome, fitness))
self.history.append(record)
self.local.append(record)
def _select_measured(self, records, references):
points = [record[1].genome for record in records]
quality = np.asarray([record[1].fitness for record in records]) * self.search._direction
distances = _distances(points, references)
best, feasible = _selection(quality, distances, self.search.distance)
return best, (feasible, quality[best] if feasible else distances[best])
def _propose(self, centre, references):
lower = np.maximum(centre - self.length / 2, 0.)
upper = np.minimum(centre + self.length / 2, 1.)
pool = self.rng.uniform(lower, upper, size=(self.search.candidate_pool, self.dimension))
mask = self.rng.random(pool.shape) < min(20 / self.dimension, 1.)
empty = np.flatnonzero(~mask.any(axis=1))
mask[empty, self.rng.integers(self.dimension, size=len(empty))] = True
pool = np.unique(np.where(mask, pool, centre), axis=0)
coordinates = self.search._coordinates
physical = np.clip(coordinates.lower + pool * coordinates.span,
coordinates.lower, coordinates.upper)
distances = _distances(physical, references)
eligible = distances >= self.search.distance
if not eligible.any():
return pool[int(np.argmax(distances))]
pool = pool[eligible]
observed, measured = zip(*self.local)
quality = self.search._direction * np.asarray([record.fitness for record in measured])
sampled = _thompson(pool, observed, quality, self.rng)
return pool[int(np.argmax(sampled))]
def _resize(self, improved):
if improved:
self.successes += 1
self.failures = 0
if self.successes == 3:
self.length = min(1.6, 2 * self.length)
self.successes = 0
else:
self.successes = 0
self.failures += 1
if self.failures == max(4, self.dimension):
self.length /= 2
self.failures = 0
def advance(self, budget, representatives):
references = np.asarray([point.genome for point in representatives])
for _ in range(budget):
if len(self.local) < self.search.initial_samples:
self._measure(self._sobol.random(1)[0])
continue
centre, before = self._select_measured(self.local, references)
self.no_centre = 0 if before[0] else self.no_centre + 1
if self.no_centre == 3:
self.restarts += 1
self._reset()
self._measure(self._sobol.random(1)[0])
continue
self._measure(self._propose(self.local[centre][0], references))
_, after = self._select_measured(self.local, references)
self._resize(after > before)
if self.length < 2. ** -7:
self.restarts += 1
self._reset()
index, _ = self._select_measured(self.history, references)
return self.history[index][1]
## @brief Build a small separated portfolio with independent Bayesian trust regions.
[docs]
class DivTuRBO1:
"""Implement the sequential and interleaved schedules of Perera et al.
Fit a local Matérn GP and sample from its posterior over a perturbed
candidate pool. Fit only the current region's measurements and keep
all measurements for final selection. Choose the best feasible
centre and prefer feasible candidates. If no point meets the
separation requirement, favor the one farthest from its nearest
reference. Check the returned minimum distance and violation count.
:param genome_bounds: One finite increasing interval per decision coordinate.
:param population_size: Number of portfolio members to search for.
:param distance: Minimum Euclidean separation in the original decision units.
:param phases: One for the sequential method. Use more for interleaving.
:param fitness_weight: Sign of the objective direction. Positive maximizes.
:param initial_samples: Global Sobol calls when starting or restarting a region.
:param candidate_pool: Maximum number of local candidates per evaluation.
:param seed: Private seed for the independent trust regions.
"""
def __init__(self, genome_bounds, *, population_size, distance, phases=1, fitness_weight=-1.,
initial_samples=5, candidate_pool=64, seed=0):
self._coordinates = _Coordinates(genome_bounds)
self.population_size = _positive_int(population_size, "population_size")
self.phases = _positive_int(phases, "phases")
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.candidate_pool = _positive_int(candidate_pool, "candidate_pool")
if not 0. <= distance < np.inf or not isfinite(fitness_weight) or fitness_weight == 0.:
raise ValueError("Use finite nonnegative distance and a finite nonzero fitness weight.")
self.distance, self._direction = float(distance), float(np.sign(fitness_weight))
self.seed = seed
## @brief Allocate the exact objective budget across portfolio slots and phases.
[docs]
def optimise(self, evaluate, budget):
"""Call evaluate(genome) for each raw objective and return measured points."""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
budget = _positive_int(budget, "budget")
slots = self.population_size * self.phases
if budget < slots:
raise ValueError("The budget must cover at least one evaluation per slot and phase.")
blocks, extra = divmod(budget, slots)
streams = np.random.SeedSequence(self.seed).spawn(self.population_size)
regions = [_TrustRegion(self, np.random.default_rng(stream), evaluate) for stream in streams]
portfolio = [None] * len(regions)
for phase in range(self.phases):
for index, region in enumerate(regions):
references = [point for i, point in enumerate(portfolio) if i != index and point is not None]
steps = blocks + (phase * len(regions) + index < extra)
portfolio[index] = region.advance(steps, references)
distances = [float(np.hypot.reduce(np.subtract(point.genome, prior.genome)))
for i, point in enumerate(portfolio) for prior in portfolio[:i]]
return DivTuRBOResult(tuple(portfolio), tuple(len(region.history) for region in regions),
tuple(region.restarts for region in regions), min(distances, default=None),
sum(distance < self.distance for distance in distances))