Source code for qdpy._archive_comparison
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Compare paired archived measurements on common descriptor geometry.
"""Per-cell occupancy and paired fitness comparisons."""
from collections import defaultdict
from collections.abc import Mapping
from dataclasses import dataclass, replace
from operator import index
from statistics import median
import numpy as np
from ._archive_data import _ArchiveData, _archive_data
from .containers import CVTGrid, Grid
def _cell_geometry(data):
return (data.shape, data.descriptor_domain, data.centroids, data.bin_edges)
def _cell_bests(data, objective, reporting_grid=None):
"""Return the best raw value and objective direction in each cell."""
best = {}
for entry in data.entries:
if objective >= len(entry.fitness) or objective >= len(entry.fitness_weights):
raise ValueError("The selected objective is missing from an archive entry.")
raw, weight = entry.fitness[objective], entry.fitness_weights[objective]
if not np.isfinite(raw):
continue
if not np.isfinite(weight) or weight == 0:
raise ValueError("Use a finite nonzero weight for the selected objective.")
cell = entry.cell
if reporting_grid is not None:
if not np.isfinite(entry.descriptors).all():
continue
try:
cell = reporting_grid.index_grid(entry.descriptors)
except IndexError:
continue
if cell is None:
continue
direction = 1 if weight > 0 else -1
if cell in best and best[cell][1] != direction:
raise ValueError("Objective directions differ within a cell.")
if cell not in best or direction * raw > direction * best[cell][0]:
best[cell] = raw, direction
return best
## @brief Matched seed counts and median fitness differences for each reporting cell.
@dataclass(frozen=True)
class ArchiveCellComparison:
"""Store shared geometry, seed pairing, occupancy counts, and raw fitness differences.
Positive ``median_difference`` means the contender improved the selected
objective. Cells without joint occupancy have NaN differences.
"""
geometry: _ArchiveData
paired_seeds: tuple
unmatched_reference: tuple
unmatched_contender: tuple
reference_only: np.ndarray
contender_only: np.ndarray
both: np.ndarray
median_difference: np.ndarray
objective: int
## @brief Pair archive measurements by seed and rebin them on a common grid.
[docs]
def compare_archive_cells(reference, contender, *, reporting_grid, objective=0):
"""Compare mappings from seed to live archive or portable archive JSON.
Use a common Grid or CVTGrid with the same descriptor meaning for both
methods. In each seed and cell, retain the best finite measurement of
the selected objective. Report occupancy counts and the median of the
within-seed differences where both methods reach the cell. Differences
use raw fitness units with the sign oriented toward improvement.
:param reference: Seed-to-archive mapping for the reference method.
:param contender: Seed-to-archive mapping for the comparison method.
:param reporting_grid: Fixed geometry used to assign measurements to cells.
:param objective: Zero-based index of the selected objective.
:return: An ArchiveCellComparison containing per-cell arrays.
"""
if not isinstance(reference, Mapping) or not isinstance(contender, Mapping):
raise TypeError("Provide two seed-to-archive mappings.")
if type(reporting_grid) not in (Grid, CVTGrid):
raise TypeError("Use a fixed Grid or CVTGrid as the reporting geometry.")
objective = index(objective)
if objective < 0:
raise ValueError("objective must be nonnegative.")
seeds = tuple(seed for seed in reference if seed in contender)
if not seeds:
raise ValueError("The methods have no matching seeds.")
geometry = replace(_archive_data(reporting_grid), entries=(), activity=None)
left_only, right_only, both = (np.zeros(geometry.shape, dtype=int) for _ in range(3))
deltas = defaultdict(list)
weights = reporting_grid.fitness_weights
if geometry.fitness_domain and objective >= len(geometry.fitness_domain):
raise ValueError("The reporting grid has no selected objective.")
if weights is not None and objective >= len(weights):
raise ValueError("The reporting grid has no selected objective weight.")
if weights is not None and (not np.isfinite(weights[objective]) or weights[objective] == 0):
raise ValueError("Use a finite nonzero reporting weight for the selected objective.")
directions = set() if weights is None else {1 if weights[objective] > 0 else -1}
for seed in seeds:
archives = [_archive_data(source[seed]) for source in (reference, contender)]
if any(data.dimension not in (0, geometry.dimension) for data in archives):
raise ValueError("Archive descriptor dimensions differ from the reporting grid.")
left, right = [_cell_bests(data, objective, reporting_grid) for data in archives]
directions.update(direction for cells in (left, right) for _, direction in cells.values())
if len(directions) > 1:
raise ValueError("The paired archives must use the same objective direction.")
for cell in left.keys() - right.keys():
left_only[cell] += 1
for cell in right.keys() - left.keys():
right_only[cell] += 1
for cell in left.keys() & right.keys():
both[cell] += 1
deltas[cell].append((right[cell][0] - left[cell][0]) * right[cell][1])
difference = np.full(geometry.shape, np.nan)
for cell, samples in deltas.items():
difference[cell] = median(samples)
return ArchiveCellComparison(geometry, seeds, tuple(k for k in reference if k not in contender),
tuple(k for k in contender if k not in reference),
left_only, right_only, both, difference, objective)