5"""Per-cell occupancy and paired fitness comparisons."""
7from collections
import defaultdict
8from collections.abc
import Mapping
9from dataclasses
import dataclass, replace
10from operator
import index
11from statistics
import median
15from ._archive_data
import _ArchiveData, _archive_data
16from .containers
import CVTGrid, Grid
19def _cell_geometry(data):
20 return (data.shape, data.descriptor_domain, data.centroids, data.bin_edges)
23def _cell_bests(data, objective, reporting_grid=None):
24 """Return the best raw value and objective direction in each cell."""
26 for entry
in data.entries:
27 if objective >= len(entry.fitness)
or objective >= len(entry.fitness_weights):
28 raise ValueError(
"The selected objective is missing from an archive entry.")
29 raw, weight = entry.fitness[objective], entry.fitness_weights[objective]
30 if not np.isfinite(raw):
32 if not np.isfinite(weight)
or weight == 0:
33 raise ValueError(
"Use a finite nonzero weight for the selected objective.")
35 if reporting_grid
is not None:
36 if not np.isfinite(entry.descriptors).all():
39 cell = reporting_grid.index_grid(entry.descriptors)
44 direction = 1
if weight > 0
else -1
45 if cell
in best
and best[cell][1] != direction:
46 raise ValueError(
"Objective directions differ within a cell.")
47 if cell
not in best
or direction * raw > direction * best[cell][0]:
48 best[cell] = raw, direction
53@dataclass(frozen=True)
55 """Store shared geometry, seed pairing, occupancy counts, and raw fitness differences.
57 Positive ``median_difference`` means the contender improved the selected
58 objective. Cells without joint occupancy have NaN differences.
61 geometry: _ArchiveData
63 unmatched_reference: tuple
64 unmatched_contender: tuple
65 reference_only: np.ndarray
66 contender_only: np.ndarray
68 median_difference: np.ndarray
73def compare_archive_cells(reference, contender, *, reporting_grid, objective=0):
74 """Compare mappings from seed to live archive or portable archive JSON.
76 Use a common Grid or CVTGrid with the same descriptor meaning for both
77 methods. In each seed and cell, retain the best finite measurement of
78 the selected objective. Report occupancy counts and the median of the
79 within-seed differences where both methods reach the cell. Differences
80 use raw fitness units with the sign oriented toward improvement.
82 :param reference: Seed-to-archive mapping for the reference method.
83 :param contender: Seed-to-archive mapping for the comparison method.
84 :param reporting_grid: Fixed geometry used to assign measurements to cells.
85 :param objective: Zero-based index of the selected objective.
86 :return: An ArchiveCellComparison containing per-cell arrays.
88 if not isinstance(reference, Mapping)
or not isinstance(contender, Mapping):
89 raise TypeError(
"Provide two seed-to-archive mappings.")
90 if type(reporting_grid)
not in (Grid, CVTGrid):
91 raise TypeError(
"Use a fixed Grid or CVTGrid as the reporting geometry.")
92 objective = index(objective)
94 raise ValueError(
"objective must be nonnegative.")
95 seeds = tuple(seed
for seed
in reference
if seed
in contender)
97 raise ValueError(
"The methods have no matching seeds.")
99 geometry = replace(_archive_data(reporting_grid), entries=(), activity=
None)
100 left_only, right_only, both = (np.zeros(geometry.shape, dtype=int)
for _
in range(3))
101 deltas = defaultdict(list)
102 weights = reporting_grid.fitness_weights
103 if geometry.fitness_domain
and objective >= len(geometry.fitness_domain):
104 raise ValueError(
"The reporting grid has no selected objective.")
105 if weights
is not None and objective >= len(weights):
106 raise ValueError(
"The reporting grid has no selected objective weight.")
107 if weights
is not None and (
not np.isfinite(weights[objective])
or weights[objective] == 0):
108 raise ValueError(
"Use a finite nonzero reporting weight for the selected objective.")
109 directions = set()
if weights
is None else {1
if weights[objective] > 0
else -1}
111 archives = [_archive_data(source[seed])
for source
in (reference, contender)]
112 if any(data.dimension
not in (0, geometry.dimension)
for data
in archives):
113 raise ValueError(
"Archive descriptor dimensions differ from the reporting grid.")
114 left, right = [_cell_bests(data, objective, reporting_grid)
for data
in archives]
115 directions.update(direction
for cells
in (left, right)
for _, direction
in cells.values())
116 if len(directions) > 1:
117 raise ValueError(
"The paired archives must use the same objective direction.")
118 for cell
in left.keys() - right.keys():
120 for cell
in right.keys() - left.keys():
121 right_only[cell] += 1
122 for cell
in left.keys() & right.keys():
124 deltas[cell].append((right[cell][0] - left[cell][0]) * right[cell][1])
126 difference = np.full(geometry.shape, np.nan)
127 for cell, samples
in deltas.items():
128 difference[cell] = median(samples)
130 tuple(k
for k
in contender
if k
not in reference),
131 left_only, right_only, both, difference, objective)
Matched seed counts and median fitness differences for each reporting cell.