# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Compare portable runs and project independent archive measurements.
"""Read verifiable QDpy runs and compare them by seed."""
import argparse
from collections import defaultdict
from dataclasses import dataclass
from hashlib import sha256
from itertools import combinations
import json
from math import isfinite, prod
from pathlib import Path
from statistics import median
import yaml
from qdpy._archive_comparison import ArchiveCellComparison, compare_archive_cells
from qdpy.algorithms.uncertain import _measurement_groups
from qdpy.containers import CVTGrid, Grid, ParetoGrid
from qdpy.phenotype import Features, Fitness, _CellIndividual
from qdpy.results import _grid_snapshot, _json_bytes, _json_value, _write, load_grid, read_run_manifest
__all__ = ["ArchiveComparison", "ArchiveCellComparison", "audit_archive", "compare_archive_cells",
"compare_runs", "make_retry_plan"]
def _grid_for(template, source):
if type(template) not in (Grid, CVTGrid):
raise ValueError("Use a Grid or CVTGrid reporting template.")
if (len(template.fitness_domain) != len(source.fitness_domain)
or len(template.features_domain) != len(source.features_domain)):
raise ValueError("The reporting grid must match the measurement dimensions.")
weights = None if source.fitness_weights is None else tuple(source.fitness_weights)
if template.fitness_weights is not None:
selected = tuple(template.fitness_weights)
if weights is not None and weights != selected:
raise ValueError("Reporting weights differ from the source objective weights.")
weights = selected
options = dict(shape=template.shape, fitness_domain=template.fitness_domain,
features_domain=template.features_domain, fitness_weights=weights)
return (Grid(**options) if type(template) is Grid
else CVTGrid(centroids=template.cluster_centers, **options))
def _offer(target, source, elite):
fitness = source.get_ind_fitness(elite)
features = tuple(source.get_ind_features(elite))
if target.fitness_weights is not None and tuple(fitness.weights) != tuple(target.fitness_weights):
raise ValueError("Reporting weights differ from an elite's objective weights.")
if not target.in_bounds(fitness.values, target.fitness_domain):
return
try:
cell = target.index_grid(features)
except IndexError:
return
candidate = _CellIndividual(elite, cell, fitness=Fitness(fitness.values, weights=fitness.weights),
features=Features(features))
target.add(candidate)
def _metrics(grid):
metrics = {"coverage": grid.filled_bins / prod(grid.shape), "qd_score": None, "retained": len(grid)}
if isinstance(grid, ParetoGrid):
metrics.update(qd_hypervolume=None, global_hypervolume=None, hypervolume_reference=None)
if len(grid.fitness_domain) == 2:
reference = [float(high if weight < 0 else low)
for (low, high), weight in zip(grid.fitness_domain, grid.fitness_weights)]
if all(map(isfinite, reference)):
qd_volume = grid.qd_hypervolume(reference)
global_volume = grid.global_hypervolume(reference)
metrics.update(hypervolume_reference=reference,
qd_hypervolume=qd_volume if isfinite(qd_volume) else None,
global_hypervolume=global_volume if isfinite(global_volume) else None)
return metrics
qd = grid.qd_score()
metrics["qd_score"] = float(qd) if isfinite(qd) else None
return metrics
[docs]
@dataclass(frozen=True)
class ArchiveComparison:
"""Audited archives, per-geometry metrics, and shared rollout counts."""
archives: dict
metrics: dict
rollouts: int
failed_rollouts: int
## @brief Measure once per requested repeat and project the aggregates into several geometries.
[docs]
def audit_archive(archive, evaluate, reporting, *, samples=32, seed=0, estimator="median", executor=None):
"""Reevaluate one best elite per occupied source cell in a scalar-objective archive.
``evaluate(candidate, seed)`` is the native noisy-QD evaluation
interface. ``reporting`` maps names to Grid or CVTGrid templates.
Each template contributes its geometry and fitness bounds. Its
existing elites are ignored. All targets share one set of fresh
measurements and keep one elite per cell. The source archive and
reporting templates are read-only for the operation.
"""
if type(archive) not in (Grid, CVTGrid) or len(archive.fitness_domain) != 1:
raise ValueError("Supply a scalar-objective Grid or CVTGrid to audit.")
if not reporting:
raise ValueError("Supply at least one reporting geometry.")
targets = {name: _grid_for(template, archive) for name, template in reporting.items()}
runner, measurements = _measurement_groups(archive, evaluate, samples=samples, seed=seed,
estimator=estimator, executor=executor)
for _, elite, _ in measurements:
for target in targets.values():
_offer(target, archive, elite)
return ArchiveComparison(targets, {name: _metrics(grid) for name, grid in targets.items()},
runner.attempted, runner.failed)
def _signature(grid):
keys = ("archive_type", "shape", "descriptor_domain", "fitness_domain", "fitness_weights", "centroids")
snapshot = _grid_snapshot(grid)
weights = sorted({tuple(row["fitness_weights"]) for row in snapshot["entries"]})
return [*(snapshot[key] for key in keys), snapshot.get("bin_edges"),
weights if grid.fitness_weights is None else None]
def _result(path, manifest, seed, template):
row = {"seed": seed, "manifest": str(path)}
try:
evaluation = manifest["evaluation"]
attempted, budget = evaluation["attempted"], evaluation["budget"]
if type(attempted) is not int or type(budget) is not int or not 0 <= attempted <= budget:
raise ValueError("Invalid finite search budget or evaluation count.")
row.update(attempted=attempted, budget=budget)
if attempted != budget:
return {**row, "status": "incomplete"}, None
archive = manifest["archive"]
digest = archive["sha256"]
if (not isinstance(digest, str) or len(digest) != 64
or any(char not in "0123456789abcdef" for char in digest)
or archive["file"] != f"archive-{digest}.json"):
raise ValueError("Invalid content-addressed archive reference.")
grid = load_grid(path.with_name(archive["file"]), expected_sha256=digest)
if template is not None:
target = _grid_for(template, grid)
for elite in grid:
_offer(target, grid, elite)
grid = target
return {**row, "status": "ok", "sha256": digest, **_metrics(grid)}, _signature(grid)
except (KeyError, OSError, TypeError, ValueError) as error:
return {**row, "status": "failed", "error": str(error)}, None
## @brief Verify manifest and archive pairs and compare matching seeds.
[docs]
def compare_runs(groups, seeds, *, reporting_grid=None):
"""Return run status and paired metric differences for named directories.
Each directory is scanned for ``run.json`` and ``run_*.json`` files.
Missing, incomplete, duplicate, and invalid runs receive explicit
statuses. Successful pairs must have matching grid geometry and
objective scale. Two-objective Pareto grids report hypervolume using
the worst raw bound of each objective as the common reference when
both bounds are finite. A common Grid or CVTGrid reporting template
reprojects source archives to one representative per reporting cell.
"""
seeds = tuple(seeds)
if not groups or not seeds or any(type(seed) is not int or seed < 0 for seed in seeds) or len(set(seeds)) != len(seeds):
raise ValueError("Provide run groups and unique nonnegative seeds.")
groups_out, signatures, invalid = {}, {}, {}
for name, directory in groups.items():
roots = Path(directory)
rows = defaultdict(list)
invalid[name] = []
for path in sorted([*roots.rglob("run.json"), *roots.rglob("run_*.json")]):
try:
manifest = read_run_manifest(path)
seed = manifest["seed"]
if type(seed) is not int:
raise ValueError("Missing integer seed.")
except (KeyError, OSError, TypeError, ValueError) as error:
invalid[name].append({"manifest": str(path), "error": str(error)})
continue
if seed in seeds:
rows[seed].append((path, manifest))
groups_out[name] = {}
for seed in seeds:
matches = rows[seed]
row = {"seed": seed, "status": "missing"}
if len(matches) > 1:
row.update(status="duplicate", manifests=[str(path) for path, _ in matches])
elif matches:
path, manifest = matches[0]
row, signatures[name, seed] = _result(path, manifest, seed, reporting_grid)
groups_out[name][seed] = row
comparisons = []
for left, right in combinations(groups_out, 2):
pairs, mismatched = [], []
for seed in seeds:
a, b = groups_out[left][seed], groups_out[right][seed]
if a["status"] != "ok" or b["status"] != "ok":
continue
if a["budget"] != b["budget"] or signatures[left, seed] != signatures[right, seed]:
mismatched.append(seed)
continue
pair = {"seed": seed, "coverage_delta": b["coverage"] - a["coverage"],
"qd_score_delta": _delta(a, b, "qd_score")}
if "qd_hypervolume" in a:
pair["qd_hypervolume_delta"] = _delta(a, b, "qd_hypervolume")
pairs.append(pair)
qd_deltas = [pair["qd_score_delta"] for pair in pairs if pair["qd_score_delta"] is not None]
comparison = {"reference": left, "comparison": right, "pairs": pairs, "incompatible_seeds": mismatched,
"median_coverage_delta": median(p["coverage_delta"] for p in pairs) if pairs else None,
"median_qd_score_delta": median(qd_deltas) if qd_deltas else None}
if any("qd_hypervolume_delta" in pair for pair in pairs):
volumes = [pair["qd_hypervolume_delta"] for pair in pairs if pair.get("qd_hypervolume_delta") is not None]
comparison["median_qd_hypervolume_delta"] = median(volumes) if volumes else None
comparisons.append(comparison)
return {"schema_version": 1, "groups": {name: list(rows.values()) for name, rows in groups_out.items()},
"invalid_manifests": invalid, "comparisons": comparisons}
def _delta(left, right, key):
a, b = left.get(key), right.get(key)
return b - a if a is not None and b is not None else None
def _configuration_digest(configuration):
if not isinstance(configuration, dict):
raise ValueError("Expected a resolved configuration mapping.")
settings = _json_value({key: value for key, value in configuration.items() if key != "seed"})
return sha256(json.dumps(settings, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
def _run_identity(group, digest, seed):
return sha256(json.dumps([group, digest, seed], separators=(",", ":")).encode()).hexdigest()
def _retry_plan(groups, seeds, configurations, report):
if set(groups) != set(configurations):
raise ValueError("Supply one retry configuration file per run group.")
inventory, jobs, blocked = {}, [], []
for group, rows in report["groups"].items():
config_path = Path(configurations[group]).resolve()
digest = _configuration_digest(yaml.safe_load(config_path.read_text(encoding="utf-8")))
inventory[group] = {"results": str(Path(groups[group]).resolve()),
"config": str(config_path), "configuration_sha256": digest}
for row in rows:
identity = {"group": group, "seed": row["seed"], "status": row["status"],
"run_id": _run_identity(group, digest, row["seed"])}
manifest = None
if row["status"] == "duplicate":
blocked.append({**identity, "reason": "multiple manifests for the seed"})
continue
if "manifest" in row:
manifest = Path(row["manifest"]).resolve()
try:
saved = read_run_manifest(manifest)
actual = _configuration_digest(saved["configuration"])
except (OSError, KeyError, TypeError, ValueError):
actual = None
if actual != digest:
blocked.append({**identity, "reason": "manifest configuration differs from the group configuration"})
continue
archive = saved.get("archive")
if (row.get("budget") is not None and row["attempted"] == row["budget"]
and isinstance(archive, dict) and "export_error" in archive):
blocked.append({**identity, "reason": "full-budget run has no verifiable portable archive"})
continue
if row["status"] == "ok":
continue
job = {**identity, "config": str(config_path), "configuration_sha256": digest, "action": "restart"}
if manifest is not None:
checkpoint = manifest.with_name("checkpoint.pkl")
journal = manifest.with_name("evaluations.jsonl")
if checkpoint.is_file() and journal.is_file():
job.update(action="resume", checkpoint=str(checkpoint), journal=str(journal))
jobs.append(job)
return {"schema_version": 1, "groups": inventory, "seeds": list(seeds), "jobs": jobs, "blocked": blocked}
## @brief Plan retries for missing, failed, and incomplete seeds without submitting jobs.
# @param groups Mapping from study group names to result directories.
# @param seeds Expected distinct nonnegative seeds in every group.
# @param configurations Mapping from group names to resolved YAML configuration files.
# @return Versioned retry plan with configuration fingerprints and a list of blocked runs.
[docs]
def make_retry_plan(groups, seeds, configurations):
"""Return a JSON-ready retry plan for one resolved configuration per group.
Each run is identified by its group, configuration fingerprint, and
seed. Successful runs are omitted. Duplicate seeds, configuration
mismatches, and full-budget runs that cannot export an archive are
reported separately. An incomplete or failed run with a checkpoint
and journal next to its manifest gets a resume action.
Paths are resolved on the planning machine.
"""
seeds = tuple(seeds)
return _retry_plan(groups, seeds, configurations, compare_runs(groups, seeds))
def main(argv=None):
"""Run the portable comparison from the command line."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--group", action="append", metavar="NAME=DIRECTORY", required=True)
parser.add_argument("--seeds", type=int, nargs="+", required=True)
parser.add_argument("--reporting-grid", type=Path, help="Portable Grid or CVTGrid template.")
parser.add_argument("--retry-config", action="append", metavar="NAME=FILE")
parser.add_argument("--retry-plan", type=Path, help="Write a retry plan for the selected groups and seeds.")
parser.add_argument("--output", type=Path)
args = parser.parse_args(argv)
def named_paths(values, label):
paths = {}
for value in values:
name, _, path = value.partition("=")
if not name or not path or name in paths:
parser.error(f"Supply distinct {label} as NAME=PATH.")
paths[name] = path
return paths
groups = named_paths(args.group, "groups")
if (args.retry_plan is None) != (args.retry_config is None):
parser.error("--retry-plan and --retry-config need to be used together.")
if args.retry_plan is not None and args.output is not None and args.retry_plan.resolve() == args.output.resolve():
parser.error("The report and the retry plan need distinct paths.")
template = load_grid(args.reporting_grid) if args.reporting_grid is not None else None
report = compare_runs(groups, args.seeds, reporting_grid=template)
if args.retry_plan is not None:
configurations = named_paths(args.retry_config, "retry configurations")
if template is None:
plan = _retry_plan(groups, args.seeds, configurations, report)
else:
plan = make_retry_plan(groups, args.seeds, configurations)
args.retry_plan.parent.mkdir(parents=True, exist_ok=True)
_write(args.retry_plan, _json_bytes(plan))
data = _json_bytes(report)
if args.output is None:
print(data.decode(), end="")
else:
args.output.parent.mkdir(parents=True, exist_ok=True)
_write(args.output, data)
if __name__ == "__main__":
main()