Source code for qdpy.algorithms.reference_niches

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Set reference examples as archive sites and measure target fidelity.
# @see https://arxiv.org/html/2601.01082#S6.SS2

"""Quality diversity with user-supplied datasets of numeric measures."""

from dataclasses import dataclass
from math import dist, fsum, isfinite, inf

import numpy as np

from qdpy.containers import CVTGrid

__all__ = ["reference_cvt", "audit_reference_cvt", "ReferenceTarget", "ReferenceAudit"]


## @brief Build a measured CVT archive with one cell per reference row.
# @param targets 2D matrix of distinct finite reference descriptors, in target ID order.
# @param features_domain Optional bounds for the candidate descriptors.
# @param fitness_domain Inclusive bounds on the scalar quality.
# @param fitness_weights One positive or negative weight for maximization or minimization.
# @return A native best-only CVTGrid with explicit centroids.
[docs] def reference_cvt(targets, *, features_domain=None, fitness_domain=((0., inf),), fitness_weights=(1.,)): """Use raw or embedded examples as nearest-neighbour archive targets. Pass the same representation for every reference and candidate. The default descriptor domain is unbounded. Use explicit finite intervals if the search algorithm needs a bounded model, as DMS does. Each input row has a stable zero-based target ID. Deterministic distance ties go to the first matching row. """ points = np.asarray(targets, dtype=float) if points.ndim != 2 or min(points.shape) < 1 or not np.isfinite(points).all(): raise ValueError("Supply a nonempty matrix of finite target rows.") if len(np.unique(points, axis=0)) != len(points): raise ValueError("Target rows must be distinct.") if features_domain is None: features_domain = ((-inf, inf),) * points.shape[1] else: domain = np.asarray(features_domain, dtype=float) if (domain.shape != (points.shape[1], 2) or np.isnan(domain).any() or np.any(domain[:, 0] > domain[:, 1])): raise ValueError("Use one ordered descriptor interval per target column.") features_domain = tuple(map(tuple, domain)) fitness_domain = tuple(tuple(map(float, bounds)) for bounds in fitness_domain) weights = tuple(map(float, fitness_weights)) if (len(fitness_domain) != 1 or len(fitness_domain[0]) != 2 or not fitness_domain[0][0] <= fitness_domain[0][1] or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0): raise ValueError("Provide one ordered fitness interval and one finite, nonzero weight.") return CVTGrid(shape=len(points), centroids=points, features_domain=features_domain, fitness_domain=fitness_domain, fitness_weights=weights)
## @brief Identify an occupied or empty reference niche and its measured fidelity.
[docs] @dataclass(frozen=True) class ReferenceTarget: """Distance is in the same Euclidean space that defines archive cells.""" target_id: int fitness: float | None distance: float | None
## @brief Report occupancy independently of the fraction within a distance limit.
[docs] @dataclass(frozen=True) class ReferenceAudit: """Mean distance uses occupied cells. The coverage denominator is all targets.""" targets: tuple[ReferenceTarget, ...] occupied: int coverage: float mean_distance: float | None matched_coverage: float | None
## @brief Audit measured fitness and Euclidean target distance without new evaluations. # @param archive A native scalar best-only CVTGrid with explicit targets. # @param distance_limit Optional radius for counting a target as matched. # @return A per-target table and aggregate occupancy and fidelity.
[docs] def audit_reference_cvt(archive, *, distance_limit=None): """Read each incumbent's fitness and displacement from its target.""" if type(archive) is not CVTGrid or archive.max_items_per_bin != 1 or len(archive.fitness_domain) != 1: raise ValueError("Supply a scalar best-only CVTGrid.") if distance_limit is not None and (not isfinite(distance_limit) or distance_limit < 0): raise ValueError("Use a finite nonnegative distance limit.") rows = [] distances = [] for target_id, target in enumerate(archive.cluster_centers): members = archive.solutions[(target_id,)] if members: elite = members[0] distance = dist(target, archive.get_ind_features(elite).values) if not isfinite(distance): raise ValueError("Target distance exceeds the representable range.") distances.append(distance) rows.append(ReferenceTarget(target_id, archive.get_ind_fitness(elite).values[0], distance)) else: rows.append(ReferenceTarget(target_id, None, None)) occupied = len(distances) matched = None if distance_limit is None else sum(d <= distance_limit for d in distances) / len(rows) return ReferenceAudit(tuple(rows), occupied, occupied / len(rows), fsum(d / occupied for d in distances) if occupied else None, matched)