# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Surrogate-Assisted Phenotypic Niching with measured and predicted repertoires.
# @see https://doi.org/10.1007/978-3-030-58112-1_10
"""Illuminate expensive fitness and descriptor functions with Gaussian processes."""
from collections import deque
from dataclasses import dataclass
import numpy as np
from scipy.stats import qmc
from qdpy.base import registry
from qdpy.containers import Grid
from .constrained import _validate_grid
from .mixed_bayesian import _gower_covariance, _MixedGaussianProcess
from .modern import _bounds, _FixedGeneration, _positive_int
__all__ = ["SPHEN", "SPHENPrediction"]
## @brief Posterior means for one design in the prediction-only map.
[docs]
@dataclass(frozen=True)
class SPHENPrediction:
"""Describe a model-selected design in raw units.
:ivar cell: Predicted cell in the supplied grid geometry.
:ivar genome: Proposed design in the original decision domain.
:ivar fitness: Predicted objective in its original optimisation direction.
:ivar features: Predicted descriptor vector used to assign the cell.
"""
cell: tuple
genome: tuple
fitness: float
features: tuple
## @brief Use posterior-mean descriptors and optimistic fitness to guide exact sampling.
[docs]
@registry.register
class SPHEN(_FixedGeneration):
"""Build acquisition and prediction maps on a fixed regular grid.
Each exact batch refits Gaussian processes for the objective and each
descriptor. MAP-Elites perturbs observed points and predicted elites.
An auxiliary cell retains the highest signed objective UCB within its
predicted descriptor bounds. Sobol targets in descriptor space select
cells for exact measurement. The supplied grid only receives measurements.
:param container: Empty, parentless, best-only Grid with one signed objective.
:param budget: Exact evaluation attempts for optimise().
:param dimension: Length of the continuous decision vector.
:param ind_domain: Common lower and upper decision bounds.
:param initial_samples: Minimum successful measurements before fitting models.
:param surrogate_budget: Maximum number of predicted genomes per acquisition map.
:param surrogate_batch_size: Number of offspring per auxiliary MAP-Elites update.
:param exploration: Nonnegative objective standard deviation multiplier.
:param mutation_sigma: Gaussian variation scale in normalized decision space.
:param length_scale: Fixed RBF kernel length scale in normalized decision space.
:param batch_size: Maximum exact proposals per model update.
:param seed: Private Sobol and variation seed.
:param kwargs: Native QDAlgorithm settings.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *,
initial_samples=12, surrogate_budget=128, surrogate_batch_size=16,
exploration=2., mutation_sigma=.1, length_scale=.25, batch_size=4,
seed=0, **kwargs):
_validate_grid(container)
domains = np.asarray(container.features_domain, dtype=float)
if (type(container) is not Grid or container.parents or domains.shape != (len(container.shape), 2)
or not np.isfinite(domains).all() or np.any(domains[:, 1] <= domains[:, 0])
or not np.isfinite(domains[:, 1] - domains[:, 0]).all()):
raise ValueError("Supply a regular parentless grid with finite increasing descriptor bounds.")
lo, hi = _bounds(ind_domain)
self._origin, self._upper = float(lo), float(hi)
self._span = self._upper - self._origin
if (not np.isfinite(self._span) or not 0 <= exploration < np.inf
or not 0 < mutation_sigma <= 1 or not 0 < length_scale < np.inf):
raise ValueError("Use finite bounds and GP settings, and mutation_sigma in (0, 1].")
self.initial_samples = _positive_int(initial_samples, "initial_samples")
self.surrogate_budget = _positive_int(surrogate_budget, "surrogate_budget")
self.surrogate_batch_size = _positive_int(surrogate_batch_size, "surrogate_batch_size")
self.exploration, self.mutation_sigma, self.length_scale = exploration, mutation_sigma, length_scale
self.seed = seed
dimension = _positive_int(dimension, "dimension")
self._continuous = np.ones(dimension, dtype=bool)
if container.fitness_weights is not None:
kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
super().__init__(container, _positive_int(budget, "budget"), dimension=dimension,
batch_size=_positive_int(batch_size, "batch_size"), **kwargs)
if len(self._fitness_weights) != 1 or not np.isfinite(self._fitness_weights[0]) or not self._fitness_weights[0]:
raise ValueError("Use a finite nonzero fitness weight.")
self._direction = np.sign(self._fitness_weights[0])
[docs]
def reinit(self):
"""Reset measurements, pending proposals, counters, and private random streams."""
super().reinit()
self._rng = np.random.default_rng(self.seed)
self._sobol = qmc.Sobol(self.dimension, scramble=True, seed=int(self._rng.integers(2**32)))
self._targets = qmc.Sobol(len(self.container.shape), scramble=True, seed=int(self._rng.integers(2**32)))
self._seen, self._observations, self._promoted = set(), [], deque()
self._predicted_cells = []
self._surrogate_evaluations = self._modelled = self._checked = self._misclassified = 0
@property
def surrogate_evaluations(self):
"""Return the number of predictions used to plan exact proposals."""
return self._surrogate_evaluations
@property
def modelled_proposals(self):
"""Return the number of exact proposals promoted from an acquisition cell."""
return self._modelled
@property
def prediction_checks(self):
"""Return the number of promoted proposals with a valid measurement."""
return self._checked
@property
def misclassified(self):
"""Return checked predictions assigned to a different cell, including out-of-grid measures."""
return self._misclassified
def _raw(self, points):
return tuple(np.clip(self._origin + self._span * points, self._origin, self._upper))
def _covariance(self, first, second):
return _gower_covariance(first, second, self._continuous, self.length_scale, 0.)
def _cell(self, features):
if self.container.in_bounds(features, self.container.features_domain):
return self.container.index_grid(features)
return None
def _build_map(self, budget, exploration, rng, excluded):
observed, responses = zip(*self._observations)
points = (np.asarray(observed) - self._origin) / self._span
model = _MixedGaussianProcess(points, np.asarray(responses), self._covariance)
elites = {}
for start in range(0, budget, self.surrogate_batch_size):
size = min(self.surrogate_batch_size, budget - start)
parents = [row[1] for row in elites.values()]
base = parents if parents else points
trials = rng.uniform(size=(size, self.dimension))
mutate = rng.random(size) < .9
if np.any(mutate):
selected = np.asarray(base)[rng.integers(len(base), size=mutate.sum())]
perturbation = rng.normal(0., self.mutation_sigma, selected.shape)
trials[mutate] = np.clip(selected + perturbation, 0., 1.)
if start == 0 and excluded is None:
count = min(size, len(points))
trials[:count] = points[rng.choice(len(points), count, replace=False)]
means, deviations = model.predict(trials)
for trial, response, score in zip(trials, means, means[:, 0] + exploration * deviations[:, 0]):
features = tuple(response[1:])
cell = self._cell(features)
if (cell is None or not np.isfinite(score)
or (excluded is not None and self._raw(trial) in excluded)):
continue
if cell not in elites or score > elites[cell][0]:
elites[cell] = (float(score), trial, float(response[0]), features)
return elites
def _start_fixed_batch(self, size):
super()._start_fixed_batch(size)
self._promoted.clear()
self._predicted_cells.clear()
if len(self._observations) < self.initial_samples:
return
elites = self._build_map(self.surrogate_budget, self.exploration, self._rng, self._seen)
self._surrogate_evaluations += self.surrogate_budget
cells = tuple(elites)
if cells:
centers = (np.asarray(cells) + .5) / self.container.shape
scheduled = set()
for _ in range(min(size, len(cells))):
wanted = self._targets.random(1)[0]
closest = int(np.argmin(np.sum((centers - wanted) ** 2, axis=1)))
cell = cells[closest]
centers[closest] = np.inf
vector = self._raw(elites[cell][1])
if vector not in scheduled:
self._promoted.append((vector, cell))
scheduled.add(vector)
def _internal_ask(self, base_ind):
if self._promoted:
vector, cell = self._promoted.popleft()
self._modelled += 1
else:
for _ in range(1024):
vector = self._raw(self._sobol.random(1)[0])
if vector not in self._seen:
break
else:
raise RuntimeError("The Sobol stream could not find an unseen genome in the decision bounds.")
cell = None
self._seen.add(vector)
self._predicted_cells.append(cell)
base_ind[:] = vector
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("Provide one descriptor per grid axis.")
def _commit_generation(self, evaluated):
grid, admitted = self.container, set()
for slot, individual in enumerate(evaluated):
if individual is None:
continue
fitness = grid.get_ind_fitness(individual).values
features = tuple(grid.get_ind_features(individual))
self._observations.append((tuple(individual), (self._direction * fitness[0], *features)))
actual, predicted = self._cell(features), self._predicted_cells[slot]
if predicted is not None:
self._checked += 1
self._misclassified += actual != predicted
if actual is not None and grid.in_bounds(fitness, grid.fitness_domain):
if self._offer_to_grid(individual, actual):
admitted.add(slot)
return admitted
## @brief Build a separate prediction map with objective uncertainty turned off.
[docs]
def prediction_map(self, budget=None, *, seed=0):
"""Return immutable SPHENPrediction rows without calling the evaluator.
The budget counts model queries for this map alone. It defaults to
surrogate_budget. The method uses the latest completed measurements
and a local random stream. It leaves the measured archive, search
streams, and acquisition counters intact.
"""
if budget is None:
budget = self.surrogate_budget
budget = _positive_int(budget, "budget")
if not self._observations:
raise ValueError("Record at least one exact measurement before predicting a map.")
elites = self._build_map(budget, 0., np.random.default_rng(seed), None)
return tuple(SPHENPrediction(cell, self._raw(row[1]), float(self._direction * row[2]), row[3])
for cell, row in sorted(elites.items()))