# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Optimize a fixed population with the Soft QD pairwise objective.
"""NumPy implementation of Soft QD Using Approximated Diversity."""
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from scipy.spatial.distance import cdist
from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .differentiable import GradientEvaluation
from .modern import _positive_int
from .task_search import _measure, _offer, _search_bounds, _validate_grid
__all__ = ["SQUADResult", "squad_search", "soft_qd_score"]
## @brief Final evaluated population and optional reporting grid.
[docs]
@dataclass(frozen=True)
class SQUADResult:
"""The raw measurements, evaluation count and optimizer objective."""
population: tuple[Individual, ...]
archive: Grid | None
evaluations: int
objective: float
## @brief Estimate the mean Soft QD behavior value over fixed probe points.
[docs]
def soft_qd_score(qualities, descriptors, probes, *, sigma):
"""Average the highest Gaussian-discounted quality at each probe.
Provide nonnegative qualities, one descriptor per solution, and a
nonempty matrix of probe descriptors. For uniform probes in a box,
multiplying by its volume estimates the integral over that box.
"""
qualities, descriptors, probes = (np.asarray(values, dtype=float)
for values in (qualities, descriptors, probes))
if (qualities.ndim != 1 or descriptors.ndim != 2 or probes.ndim != 2
or len(qualities) != len(descriptors) or not len(probes)
or not probes.shape[1] or descriptors.shape[1] != probes.shape[1]
or any(not np.isfinite(array).all() for array in (qualities, descriptors, probes))
or np.any(qualities < 0) or not isfinite(sigma) or sigma <= 0):
raise ValueError("Supply finite aligned solutions and probes, nonnegative qualities, and positive sigma.")
if not len(qualities):
return 0.
with np.errstate(over="ignore"):
distances = cdist(probes, descriptors) / sigma
return float(np.mean(np.max(np.exp(-0.5 * distances ** 2) * qualities, axis=1)))
def _batch_objective(quality, descriptors, rows, neighbors, gamma):
"""Return the directed minibatch objective and its derivatives for all rows."""
gradient = np.zeros((len(quality), 1 + descriptors.shape[1]))
gradient[rows, 0] = 1.
value = quality[rows].sum()
if neighbors == 0:
return value, gradient
distances = cdist(descriptors[rows], descriptors, metric="sqeuclidean")
distances[np.arange(len(rows)), rows] = np.inf
adjacent = np.argsort(distances, axis=1, kind="stable")[:, :neighbors]
left, right = np.repeat(rows, neighbors), adjacent.ravel()
with np.errstate(over="ignore"):
diff = (descriptors[left] - descriptors[right]) / gamma
kernel = np.exp(-np.sum(diff * diff, axis=1))
weight = 0.5 * np.sqrt(quality[left]) * np.sqrt(quality[right]) * kernel
value -= weight.sum()
np.add.at(gradient[:, 0], left, -0.5 * weight / quality[left])
np.add.at(gradient[:, 0], right, -0.5 * weight / quality[right])
# At an underflowed kernel value, the representable repulsion is zero.
repulsion = (2. * weight[:, None] * np.where(kernel[:, None] > 0., diff, 0.)) / gamma
np.add.at(gradient[:, 1:], left, repulsion)
np.add.at(gradient[:, 1:], right, -repulsion)
return value, gradient
## @brief Update a population using measured objective and descriptor Jacobians.
[docs]
def squad_search(gradient_evaluate, initial_population, *, epochs, gamma, quality_floor,
ind_domain=(0., 1.), batch_size=None, neighbors=None,
learning_rate=0.02, maximize=True, archive=None, seed=0):
"""Maximize the SQUAD objective with seeded minibatch Adam updates.
:param gradient_evaluate: Callable returning a GradientEvaluation for
one genome. Its Jacobian rows match raw fitness and descriptor order.
:param initial_population: Matrix of finite bounded genomes.
:param epochs: Number of complete passes after the initial evaluations.
Every pass reevaluates each updated point once.
:param gamma: Positive distance scale in descriptor units.
:param quality_floor: Lower bound in signed fitness units. Each signed
fitness must strictly exceed it for the square-root gradient.
:param ind_domain: Common bounds. Adam proposals are projected to this interval.
:param batch_size: Number of points per update. Defaults to the entire population.
:param neighbors: Maximum nearest neighbors per point. Defaults to all other
points. Zero gives independent quality optimization.
:param learning_rate: Positive Adam step size.
:param maximize: False negates raw fitness and its derivative.
:param archive: Optional empty best-only Grid or CVTGrid for final reporting.
:param seed: Local seed for minibatch order.
:returns: Measured final population and optional reporting archive.
"""
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)
if (population.ndim != 2 or not all(population.shape) or not np.isfinite(population).all()
or np.any(population < bounds[0]) or np.any(population > bounds[1])):
raise ValueError("Supply a nonempty matrix of finite genomes inside ind_domain.")
if (epochs < 0 or not isfinite(quality_floor) or not isfinite(gamma) or gamma <= 0
or not isfinite(learning_rate) or learning_rate <= 0):
raise ValueError("Use nonnegative epochs, a finite quality floor, and positive gamma and learning rate.")
count, dimension = population.shape
size = count if batch_size is None else min(count, _positive_int(batch_size, "batch_size"))
neighbors = count - 1 if neighbors is None else index(neighbors)
if not 0 <= neighbors < count:
raise ValueError("neighbors must be between zero and the population size minus one.")
direction = 1. if maximize else -1.
if archive is not None:
_validate_grid(archive)
if archive.fitness_weights is not None and np.sign(archive.fitness_weights[0]) != direction:
raise ValueError("The reporting grid and optimizer must use the same fitness direction.")
def measure(genome, descriptor_size=None):
result = gradient_evaluate(tuple(genome))
if not isinstance(result, GradientEvaluation):
raise TypeError("SQUAD requires a GradientEvaluation.")
quality = direction * float(result.fitness) - quality_floor
descriptors = np.asarray(result.descriptors, dtype=float)
jacobian = np.array(result.jacobian, dtype=float, copy=True)
if (not isfinite(quality) or quality <= 0 or descriptors.ndim != 1 or not descriptors.size
or (descriptor_size is not None and descriptors.size != descriptor_size)
or jacobian.shape != (descriptors.size + 1, dimension)
or not np.isfinite(descriptors).all() or not np.isfinite(jacobian).all()):
raise ValueError("SQUAD needs positive shifted fitness, finite descriptors, and a matching finite Jacobian.")
jacobian[0] *= direction
return float(result.fitness), quality, descriptors.copy(), jacobian
measured = [measure(population[0])]
width = measured[0][2].size
measured.extend(measure(genome, width) for genome in population[1:])
raw, quality, descriptors, jacobians = map(np.array, zip(*measured))
if archive is not None and len(archive.features_domain) != width:
raise ValueError("Descriptor size must match the reporting grid.")
first, second = np.zeros_like(population), np.zeros_like(population)
rng = np.random.default_rng(seed)
for epoch in range(1, epochs + 1):
order = np.arange(count) if size == count else rng.permutation(count)
for start in range(0, count, size):
rows = order[start:start + size]
_, gradient = _batch_objective(quality, descriptors, rows, neighbors, gamma)
update = np.einsum("br,brd->bd", gradient[rows], jacobians[rows])
mean = 0.9 * first[rows] + 0.1 * update
moment = 0.999 * second[rows] + 0.001 * update ** 2
new = population[rows] + learning_rate * (mean / (1 - 0.9 ** epoch)) / (
np.sqrt(moment / (1 - 0.999 ** epoch)) + 1e-8)
if not np.isfinite(moment).all() or not np.isfinite(new).all():
raise FloatingPointError("The SQUAD update overflowed. Rescale the objective or descriptors.")
new = np.clip(new, *bounds)
measurements = [measure(genome, width) for genome in new]
raw[rows], quality[rows], descriptors[rows], jacobians[rows] = map(np.array, zip(*measurements))
population[rows], first[rows], second[rows] = new, mean, moment
objective, _ = _batch_objective(quality, descriptors, np.arange(count), neighbors, gamma)
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 SQUADResult(result, archive, count * (epochs + 1), float(objective))