# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Prior-guided offline MAP-Elites for generic categorical designs.
# @see https://arxiv.org/abs/2611.00716
"""Search categorical configurations under frozen predictions and a bounded prior."""
from dataclasses import dataclass
import numpy as np
from qdpy.phenotype import Features, Fitness, Individual
from .modern import _positive_int
from .offline import OfflineMAPElites, OfflineSearchResult, _empty_geometry, _frozen_matern
from .task_search import _validate_grid
__all__ = ["PriorGuidedOfflineMAPElites", "PriorGuidedSearchResult"]
## @brief Predicted raw-quality archive and the number of prior and model queries.
[docs]
@dataclass(frozen=True)
class PriorGuidedSearchResult(OfflineSearchResult):
"""Each elite's scores include its selection score, uncertainty, and prior weight."""
prior_queries: int
## @brief Adapt prior-guided offline design to products of finite categories.
[docs]
class PriorGuidedOfflineMAPElites:
"""Use a frozen Matérn GP and a caller-supplied categorical prior.
Mutation samples single-locus changes and optionally chooses among
them using prior scores. At admission, increasing model uncertainty
increases the contribution of the prior to a normalized quality score.
The returned archive stores raw predicted quality and descriptors.
Disagreement is an acquisition signal and carries no coverage guarantee.
:param archive: Empty parentless best-only Grid or CVTGrid with one signed objective.
:param genomes: Integer training designs, one row per measurement.
:param fitnesses: Measured scalar qualities for the training designs.
:param descriptors: Measured descriptors for the training designs.
:param nvec: Number of zero-based categories in each locus.
:param prior: Callable scoring a design on [0, 1], with higher being more plausible.
:param prior_weight: Maximum fraction of the acquisition score determined by the prior.
:param uncertainty_scale: Predicted deviation at which the prior receives half its maximum weight.
Defaults to one quarter of the logged quality span.
:param uncertainty_penalty: Fixed standard-deviation penalty in quality units.
:param mutation_choices: Number of prior-scored edits per mutation.
:param proposal_strength: Inverse temperature applied to prior scores on edits.
:param length_scale: Fixed Matérn length scale on one-hot genomes.
:param noise: Positive GP covariance regularization.
:param seed: Private seed for seed selection and mutations.
"""
def __init__(self, archive, genomes, fitnesses, descriptors, *, nvec, prior=None,
prior_weight=1., uncertainty_scale=None, uncertainty_penalty=0., mutation_choices=4,
proposal_strength=3., length_scale=1.8, noise=1e-6, seed=0):
_validate_grid(archive)
weights = archive.fitness_weights
if weights is None or archive.fitness_score_names or archive.features_score_names:
raise ValueError("Use native scores and an explicit nonzero fitness weight.")
counts = tuple(_positive_int(count, "category count") for count in nvec)
if not counts:
raise ValueError("Supply at least one locus.")
rows = np.asarray(genomes)
scores = np.asarray(fitnesses, dtype=float)
descriptors = np.asarray(descriptors, dtype=float)
if (rows.ndim != 2 or len(rows) < 2 or rows.shape[1] != len(counts)
or rows.dtype.kind not in "iu" or (rows < 0).any() or (rows >= counts).any()
or scores.shape != (len(rows),) or not np.isfinite(scores).all()
or descriptors.shape != (len(rows), len(archive.features_domain))
or not np.isfinite(descriptors).all()):
raise ValueError("Supply aligned finite measurements for valid categorical genomes.")
if (prior is not None and not callable(prior) or not 0. <= prior_weight <= 1.
or not 0. <= uncertainty_penalty < np.inf or not 0. <= proposal_strength < np.inf
or not 0. < length_scale < np.inf or not 0. < noise < np.inf):
raise ValueError("Provide a callable prior and finite, valid acquisition and GP settings.")
self._weights = weights
self._direction = 1. if weights[0] > 0. else -1.
minimum = float((self._direction * scores).min())
span = float((self._direction * scores).max()) - minimum
self._span = span or max(1., abs(minimum))
self._uncertainty = max(self._span / 4., np.finfo(float).tiny) if uncertainty_scale is None else uncertainty_scale
if not 0. < self._span < np.inf or not 0. < self._uncertainty < np.inf:
raise ValueError("The logged quality span and uncertainty scale must be finite.")
self._minimum = minimum
self._groups = counts
self._offsets = np.cumsum((0, *counts[:-1]))
self._movable = tuple(i for i, count in enumerate(counts) if count > 1)
self._rows = rows.astype(np.int64, copy=True)
self._geometry = _empty_geometry(archive)
self._model = _frozen_matern(self._encode(self._rows), np.column_stack((scores, descriptors)),
length_scale, noise)
self._prior = prior if prior_weight else None
self._weight, self._penalty = prior_weight, uncertainty_penalty
self._choices = _positive_int(mutation_choices, "mutation_choices")
self._strength = proposal_strength
self.seed = seed
def _encode(self, rows):
features = np.zeros((len(rows), sum(self._groups)))
features[np.arange(len(rows))[:, None], rows + self._offsets] = 1.
return features
def _acquire(self, mean, deviation, prior):
weight = (self._weight * (deviation / np.hypot(self._uncertainty, deviation))**2
if self._prior is not None else 0.)
normalized = (self._direction * mean - self._minimum) / self._span
quality = (1. - weight) * normalized + weight * prior - self._penalty * (deviation / self._span)
return float(quality), float(weight)
def _edit(self, point, rng):
if not self._movable:
return point
locus = self._movable[int(rng.integers(len(self._movable)))]
draw = int(rng.integers(self._groups[locus] - 1))
return (*point[:locus], draw + (draw >= point[locus]), *point[locus + 1:])
## @brief Search with a hard cap on frozen-model predictions.
# @param budget Maximum number of proposed designs measured by the model.
# @param initial_samples Number of measured training designs to rescore first.
# @return A predicted archive with raw predictive quality and separate acquisition scores.
[docs]
def run(self, budget, *, initial_samples=16):
"""Make a new predicted archive and count every prior call."""
budget = _positive_int(budget, "budget")
initial = min(_positive_int(initial_samples, "initial_samples"), budget, len(self._rows))
rng = np.random.default_rng(self.seed)
seeds = rng.permutation(len(self._rows))[:initial]
archive = _empty_geometry(self._geometry)
winners = {}
prior_calls = 0
def prior_score(point):
nonlocal prior_calls
if self._prior is None:
return 0.
prior_calls += 1
value = float(self._prior(point))
if not 0. <= value <= 1.:
raise ValueError("The prior must return a finite score in [0, 1].")
return value
for step in range(budget):
if step < initial:
point = tuple(map(int, self._rows[seeds[step]]))
prior = prior_score(point)
else:
if winners:
parent = tuple(winners.values())[int(rng.integers(len(winners)))]
else:
parent = self._rows[int(rng.integers(len(self._rows)))]
parent = tuple(map(int, parent))
if self._prior is None or not self._strength:
point = self._edit(parent, rng)
prior = prior_score(point)
else:
edits = tuple(dict.fromkeys(self._edit(parent, rng) for _ in range(self._choices)))
ranking = np.asarray([prior_score(point) for point in edits])
weights = np.exp(self._strength * (ranking - ranking.max()))
selected = int(rng.choice(len(edits), p=weights / weights.sum()))
point, prior = edits[selected], ranking[selected]
mean, std = self._model.predict(self._encode(np.asarray([point])), return_std=True)
quality, *features = mean[0]
deviation = float(std[0, 0])
value, weight = self._acquire(quality, deviation, prior)
if not np.isfinite((value, quality, deviation, *features)).all():
raise ValueError("The frozen surrogate produced a nonfinite prediction or acquisition.")
if not (archive.in_bounds((quality,), archive.fitness_domain)
and archive.in_bounds(features, archive.features_domain)):
continue
cell = archive.index_grid(features)
previous = winners.get(cell)
if previous is None and len(winners) >= archive.capacity:
continue
if previous is None or value > previous.scores["acquisition"]:
winners[cell] = Individual(point, fitness=Fitness((quality,), weights=self._weights),
features=Features(features), scores={
"acquisition": value, "prediction_std": deviation,
"predicted_fitness": float(quality), "prior": prior,
"prior_fraction": weight,
})
archive.update(winners.values())
return PriorGuidedSearchResult(archive, budget, prior_calls)
verify = staticmethod(OfflineMAPElites.verify)