# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Optimize a compact repertoire against a shared panel of behavior targets.
# @see https://arxiv.org/abs/2602.00478
"""Smooth Sum-of-Minimum and Smooth Tchebycheff Set optimization."""
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from scipy.special import logsumexp
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .differentiable import GradientEvaluation
from .task_search import _measure, _offer, _search_bounds, _validate_grid
__all__ = ["SetScalarizationResult", "set_scalarized_search"]
## @brief Final repertoire and per-target costs, with exact evaluator accounting.
[docs]
@dataclass(frozen=True)
class SetScalarizationResult:
"""Report the measured final set and unsmoothed minimum cost at each target.
The objective is the final smooth loss and is minimized. Target
costs retain probe order and are negative discounted qualities.
A reporting archive, if supplied, contains the final set's elites.
"""
population: tuple[Individual, ...]
archive: Grid | None
evaluations: int
objective: float
target_costs: tuple[float, ...]
def _target_cost(qualities, descriptors, targets, bandwidth):
with np.errstate(over="ignore"):
offsets = (descriptors[:, None, :] - targets) / bandwidth
kernel = np.exp(-np.square(offsets).sum(axis=-1))
return -qualities[:, None] * kernel, kernel, offsets
def _scalarize(costs, smoothing, reference):
"""Return the smooth loss and its derivatives with respect to probe costs."""
minimum = costs.min(axis=0)
with np.errstate(over="ignore"):
logits = (minimum - costs) / smoothing
normalizer = logsumexp(logits, axis=0)
soft_min = minimum - smoothing * normalizer
within = np.exp(logits - normalizer)
if reference is None:
return soft_min.sum(), within
shortfall = soft_min - reference
worst = shortfall.max()
logits = (shortfall - worst) / smoothing
normalizer = logsumexp(logits)
return worst + smoothing * normalizer, within * np.exp(logits - normalizer)
## @brief Minimize smooth target costs jointly over a fixed population.
# @return SetScalarizationResult with the final evaluated designs.
[docs]
def set_scalarized_search(gradient_evaluate, initial_population, targets, *, epochs, bandwidth,
smoothing=.05, scalarization="ssom", reference=None, quality_floor=0.,
learning_rate=.02, ind_domain=(0., 1.), maximize=True, archive=None):
"""Use projected Adam on the SSoM or STCH-Set objective from Lin et al.
:param gradient_evaluate: Callback returning one GradientEvaluation per point.
:param initial_population: Nonempty matrix of bounded genomes.
:param targets: Nonempty matrix of desired descriptors in measurement units.
:param epochs: Full-population updates after the initial measurements.
:param bandwidth: Gaussian distance scale in descriptor units.
:param smoothing: Positive log-sum-exp temperature in quality units.
:param scalarization: "ssom" or "stch-set".
:param reference: Fixed target-wise ideal costs for STCH-Set. If omitted,
use each target's initial best cost minus smoothing.
:param quality_floor: Lower bound in signed fitness units. Shifted qualities
must be nonnegative for distance discounting.
:param learning_rate: Projected Adam step in genome units.
:param ind_domain: Inclusive common genome interval.
:param maximize: Use higher raw fitness as better if true.
:param archive: Optional empty best-only Grid or CVTGrid for final reporting.
"""
if not callable(gradient_evaluate):
raise TypeError("Supply a gradient evaluator.")
epochs = index(epochs)
bounds = _search_bounds(ind_domain)
population = np.array(initial_population, dtype=float, copy=True)
targets = np.asarray(targets, dtype=float)
if (population.ndim != 2 or not all(population.shape) or not np.isfinite(population).all()
or not np.all((bounds[0] <= population) & (population <= bounds[1]))
or targets.ndim != 2 or not all(targets.shape) or not np.isfinite(targets).all()):
raise ValueError("Supply nonempty finite matrices of bounded genomes and behavior targets.")
if (epochs < 0 or not isfinite(quality_floor)
or not all(isfinite(value) and value > 0 for value in (bandwidth, smoothing, learning_rate))):
raise ValueError("Use nonnegative epochs, a finite quality floor, and finite positive optimizer scales.")
if scalarization not in ("ssom", "stch-set") or (reference is not None and scalarization != "stch-set"):
raise ValueError("Choose ssom or stch-set. Only stch-set takes a target reference.")
if reference is not None:
reference = np.asarray(reference, dtype=float)
if reference.shape != (len(targets),) or not np.isfinite(reference).all():
raise ValueError("Supply one finite reference cost per behavior target.")
direction = 1. if maximize else -1.
if archive is not None:
_validate_grid(archive)
if (len(archive.features_domain) != targets.shape[1]
or (archive.fitness_weights is not None and np.sign(archive.fitness_weights[0]) != direction)):
raise ValueError("Reporting archive descriptors and fitness direction must match the evaluator.")
def measure(genome):
result = gradient_evaluate(tuple(genome))
if not isinstance(result, GradientEvaluation):
raise TypeError("The evaluator must return a GradientEvaluation.")
fitness = float(result.fitness)
descriptor = np.asarray(result.descriptors, dtype=float)
jacobian = np.asarray(result.jacobian, dtype=float)
quality = direction * fitness - quality_floor
if (not isfinite(quality) or quality < 0 or descriptor.shape != (targets.shape[1],)
or jacobian.shape != (1 + targets.shape[1], population.shape[1])
or not np.isfinite(descriptor).all() or not np.isfinite(jacobian).all()):
raise ValueError("Expected nonnegative shifted fitness and finite descriptors with a matching Jacobian.")
return fitness, quality, descriptor.copy(), jacobian.copy()
first, second = np.zeros_like(population), np.zeros_like(population)
for epoch in range(epochs + 1):
raw, quality, descriptors, jacobians = map(np.array, zip(*(measure(genome) for genome in population)))
costs, kernel, offsets = _target_cost(quality, descriptors, targets, bandwidth)
if reference is None and scalarization == "stch-set":
reference = costs.min(axis=0) - smoothing
objective, weights = _scalarize(costs, smoothing, reference)
if not isfinite(objective):
raise FloatingPointError("The set objective overflowed. Rescale fitness or the reference.")
if epoch == epochs:
break
fitness_gradient = -direction * (weights * kernel).sum(axis=1)
offsets = np.where(kernel[..., None] > 0., offsets, 0.)
descriptor_gradient = -2. * np.einsum("pm,pmd->pd", weights * costs, offsets) / bandwidth
gradient = np.einsum("pr,prd->pd", np.column_stack((fitness_gradient, descriptor_gradient)), jacobians)
first = .9 * first + .1 * gradient
second = .999 * second + .001 * np.square(gradient)
proposal = population - learning_rate * (first / (1. - .9 ** (epoch + 1))) / (
np.sqrt(second / (1. - .999 ** (epoch + 1))) + 1e-8)
if not np.isfinite(second).all() or not np.isfinite(proposal).all():
raise FloatingPointError("The set gradient update overflowed. Rescale fitness or descriptors.")
population = np.clip(proposal, *bounds)
result = tuple(Individual(genome, fitness=Fitness((value,), weights=(direction,)),
features=Features(tuple(features)))
for genome, value, features in zip(population, raw, descriptors))
if archive is not None:
if archive.fitness_weights is None:
archive._set_fitness_weights((direction,))
for individual in result:
measurement = _measure(archive, lambda: (tuple(individual.fitness), tuple(individual.features)),
(), individual)
if measurement is not None:
_offer(archive, measurement)
return SetScalarizationResult(result, archive, len(result) * (epochs + 1), float(objective),
tuple(costs.min(axis=0)))