Source code for qdpy.algorithms.repertoire_selection
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Select a fixed-size repertoire from already measured candidates.
# @see https://arxiv.org/abs/1709.05135
"""Greedy determinantal point process inference on measured candidates."""
from dataclasses import dataclass
from math import isfinite
from operator import attrgetter
import numpy as np
from qdpy.containers import Container
from .modern import _positive_int
__all__ = ["select_dpp", "DPPRepertoire"]
## @brief Selected archive members with comparable diversity and quality scores.
[docs]
@dataclass(frozen=True)
class DPPRepertoire:
"""Members reference the input objects. Indices retain greedy selection order."""
indices: tuple[int, ...]
members: tuple
similarity_logdet: float
objective_logdet: float
def _scalar_quality(fitness):
values, weights = fitness.values, fitness.weights
if len(values) != 1 or len(weights) != 1:
raise ValueError("Use scalar weighted fitness or supply a quality callback.")
return values[0] * weights[0] if weights[0] != 0 else 0.
## @brief Pick exactly k alternatives with quality-weighted greedy DPP inference.
# @param candidates Iterable of measured, eligible alternatives in tie-break order.
# @param size Number to select.
# @param embedding Optional callable returning a vector for an alternative.
# @param quality Optional callable returning a scalar with larger values preferred.
# @param bandwidth Length scale of the Gaussian similarity kernel.
# @param quality_strength Maximum log-weight bonus of quality relative to diversity.
# @param ridge Positive diagonal regularization on the similarity kernel.
# @return Input indices, selected objects, and the selected kernel scores.
[docs]
def select_dpp(candidates, size, *, embedding=None, quality=None,
bandwidth=1., quality_strength=1., ridge=1e-8):
"""Select a compact repertoire without modifying or reevaluating candidates.
The defaults use each elite's feature vector and its scalar weighted
fitness, resolving named scores and weights when given a container.
Rescale features before selection when axes have different units.
The maximum quality gets zero log penalty and the minimum gets
a penalty of quality_strength. Set
quality_strength to zero for diversity-only selection. An incremental
Cholesky update needs only one kernel column per selected member.
"""
pool = tuple(candidates)
size = _positive_int(size, "size")
if size > len(pool):
raise ValueError("size cannot exceed the candidate count.")
if (not isfinite(bandwidth) or bandwidth <= 0. or not isfinite(quality_strength)
or quality_strength < 0. or not np.finfo(float).eps <= ridge <= 1.):
raise ValueError("Use positive finite bandwidth, nonnegative finite quality strength, and ridge in [eps, 1].")
archive = candidates if isinstance(candidates, Container) else None
if embedding is None:
get_features = archive.get_ind_features if archive is not None else attrgetter("features")
embedding = lambda member: get_features(member).values
points = np.asarray([embedding(member) for member in pool], dtype=float)
if points.ndim != 2 or not points.shape[1] or not np.isfinite(points).all():
raise ValueError("Embeddings must be finite nonempty vectors of the same length.")
normalized = np.zeros(len(pool))
if quality_strength:
if quality is None:
get_fitness = archive.get_ind_fitness if archive is not None else attrgetter("fitness")
quality = lambda member: _scalar_quality(get_fitness(member))
values = np.asarray([quality(member) for member in pool], dtype=float)
if values.shape != (len(pool),) or not np.isfinite(values).all():
raise ValueError("Quality must return one finite scalar per member.")
# Rescale first so that the finite quality span cannot overflow.
scaled = values / max(float(np.abs(values).max()), np.finfo(float).tiny)
low, high = scaled.min(), scaled.max()
if low < high:
normalized = (scaled - high) / (high - low)
bonus = quality_strength * normalized
diagonal = np.full(len(pool), 1. + ridge)
eligible = np.ones(len(pool), dtype=bool)
factors = np.empty((size - 1, len(pool)))
indices = []
diversity = objective = 0.
for row in range(size):
residuals = np.maximum(diagonal, np.finfo(float).tiny)
scores = np.where(eligible, np.log(residuals) + bonus, -np.inf)
pick = int(np.argmax(scores))
indices.append(pick)
diversity += float(np.log(residuals[pick]))
objective += float(scores[pick])
eligible[pick] = False
if row == size - 1:
break
with np.errstate(over="ignore", under="ignore"):
# In the rare overflow cases halve the operands before subtraction.
delta = points - points[pick]
scale = np.isinf(delta)
offsets = delta / bandwidth
offsets[scale] = ((points / 2 - points[pick] / 2)[scale] / bandwidth) * 2
distances = np.hypot.reduce(offsets, axis=1)
similarities = np.exp(-.5 * distances**2)
projection = factors[:row, pick] @ factors[:row]
factors[row] = (similarities - projection) / np.sqrt(residuals[pick])
factors[row, ~eligible] = 0.
diagonal -= factors[row] ** 2
return DPPRepertoire(tuple(indices), tuple(pool[i] for i in indices), diversity, objective)