5"""Read verifiable QDpy runs and compare them by seed."""
8from collections
import defaultdict
9from dataclasses
import dataclass
10from hashlib
import sha256
11from itertools
import combinations
13from math
import isfinite, prod
14from pathlib
import Path
15from statistics
import median
23from qdpy.results import _grid_snapshot, _json_bytes, _json_value, _write, load_grid, read_run_manifest
25__all__ = [
"ArchiveComparison",
"ArchiveCellComparison",
"audit_archive",
"compare_archive_cells",
26 "compare_runs",
"make_retry_plan"]
29def _grid_for(template, source):
30 if type(template)
not in (Grid, CVTGrid):
31 raise ValueError(
"Use a Grid or CVTGrid reporting template.")
32 if (len(template.fitness_domain) != len(source.fitness_domain)
33 or len(template.features_domain) != len(source.features_domain)):
34 raise ValueError(
"The reporting grid must match the measurement dimensions.")
35 weights =
None if source.fitness_weights
is None else tuple(source.fitness_weights)
36 if template.fitness_weights
is not None:
37 selected = tuple(template.fitness_weights)
38 if weights
is not None and weights != selected:
39 raise ValueError(
"Reporting weights differ from the source objective weights.")
41 options = dict(shape=template.shape, fitness_domain=template.fitness_domain,
42 features_domain=template.features_domain, fitness_weights=weights)
43 return (Grid(**options)
if type(template)
is Grid
44 else CVTGrid(centroids=template.cluster_centers, **options))
47def _offer(target, source, elite):
48 fitness = source.get_ind_fitness(elite)
49 features = tuple(source.get_ind_features(elite))
50 if target.fitness_weights
is not None and tuple(fitness.weights) != tuple(target.fitness_weights):
51 raise ValueError(
"Reporting weights differ from an elite's objective weights.")
52 if not target.in_bounds(fitness.values, target.fitness_domain):
55 cell = target.index_grid(features)
58 candidate = _CellIndividual(elite, cell, fitness=Fitness(fitness.values, weights=fitness.weights),
59 features=Features(features))
64 metrics = {
"coverage": grid.filled_bins / prod(grid.shape),
"qd_score":
None,
"retained": len(grid)}
65 if isinstance(grid, ParetoGrid):
66 metrics.update(qd_hypervolume=
None, global_hypervolume=
None, hypervolume_reference=
None)
67 if len(grid.fitness_domain) == 2:
68 reference = [float(high
if weight < 0
else low)
69 for (low, high), weight
in zip(grid.fitness_domain, grid.fitness_weights)]
70 if all(map(isfinite, reference)):
71 qd_volume = grid.qd_hypervolume(reference)
72 global_volume = grid.global_hypervolume(reference)
73 metrics.update(hypervolume_reference=reference,
74 qd_hypervolume=qd_volume
if isfinite(qd_volume)
else None,
75 global_hypervolume=global_volume
if isfinite(global_volume)
else None)
78 metrics[
"qd_score"] = float(qd)
if isfinite(qd)
else None
82@dataclass(frozen=True)
84 """Audited archives, per-geometry metrics, and shared rollout counts."""
93def audit_archive(archive, evaluate, reporting, *, samples=32, seed=0, estimator="median", executor=None):
94 """Reevaluate one best elite per occupied source cell in a scalar-objective archive.
96 ``evaluate(candidate, seed)`` is the native noisy-QD evaluation
97 interface. ``reporting`` maps names to Grid or CVTGrid templates.
98 Each template contributes its geometry and fitness bounds. Its
99 existing elites are ignored. All targets share one set of fresh
100 measurements and keep one elite per cell. The source archive and
101 reporting templates are read-only for the operation.
103 if type(archive)
not in (Grid, CVTGrid)
or len(archive.fitness_domain) != 1:
104 raise ValueError(
"Supply a scalar-objective Grid or CVTGrid to audit.")
106 raise ValueError(
"Supply at least one reporting geometry.")
107 targets = {name: _grid_for(template, archive)
for name, template
in reporting.items()}
108 runner, measurements = _measurement_groups(archive, evaluate, samples=samples, seed=seed,
109 estimator=estimator, executor=executor)
110 for _, elite, _
in measurements:
111 for target
in targets.values():
112 _offer(target, archive, elite)
113 return ArchiveComparison(targets, {name: _metrics(grid)
for name, grid
in targets.items()},
114 runner.attempted, runner.failed)
118 keys = (
"archive_type",
"shape",
"descriptor_domain",
"fitness_domain",
"fitness_weights",
"centroids")
119 snapshot = _grid_snapshot(grid)
120 weights = sorted({tuple(row[
"fitness_weights"])
for row
in snapshot[
"entries"]})
121 return [*(snapshot[key]
for key
in keys), snapshot.get(
"bin_edges"),
122 weights
if grid.fitness_weights
is None else None]
125def _result(path, manifest, seed, template):
126 row = {
"seed": seed,
"manifest": str(path)}
128 evaluation = manifest[
"evaluation"]
129 attempted, budget = evaluation[
"attempted"], evaluation[
"budget"]
130 if type(attempted)
is not int
or type(budget)
is not int
or not 0 <= attempted <= budget:
131 raise ValueError(
"Invalid finite search budget or evaluation count.")
132 row.update(attempted=attempted, budget=budget)
133 if attempted != budget:
134 return {**row,
"status":
"incomplete"},
None
135 archive = manifest[
"archive"]
136 digest = archive[
"sha256"]
137 if (
not isinstance(digest, str)
or len(digest) != 64
138 or any(char
not in "0123456789abcdef" for char
in digest)
139 or archive[
"file"] != f
"archive-{digest}.json"):
140 raise ValueError(
"Invalid content-addressed archive reference.")
141 grid = load_grid(path.with_name(archive[
"file"]), expected_sha256=digest)
142 if template
is not None:
143 target = _grid_for(template, grid)
145 _offer(target, grid, elite)
147 return {**row,
"status":
"ok",
"sha256": digest, **_metrics(grid)}, _signature(grid)
148 except (KeyError, OSError, TypeError, ValueError)
as error:
149 return {**row,
"status":
"failed",
"error": str(error)},
None
153def compare_runs(groups, seeds, *, reporting_grid=None):
154 """Return run status and paired metric differences for named directories.
156 Each directory is scanned for ``run.json`` and ``run_*.json`` files.
157 Missing, incomplete, duplicate, and invalid runs receive explicit
158 statuses. Successful pairs must have matching grid geometry and
159 objective scale. Two-objective Pareto grids report hypervolume using
160 the worst raw bound of each objective as the common reference when
161 both bounds are finite. A common Grid or CVTGrid reporting template
162 reprojects source archives to one representative per reporting cell.
165 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):
166 raise ValueError(
"Provide run groups and unique nonnegative seeds.")
167 groups_out, signatures, invalid = {}, {}, {}
168 for name, directory
in groups.items():
169 roots = Path(directory)
170 rows = defaultdict(list)
172 for path
in sorted([*roots.rglob(
"run.json"), *roots.rglob(
"run_*.json")]):
174 manifest = read_run_manifest(path)
175 seed = manifest[
"seed"]
176 if type(seed)
is not int:
177 raise ValueError(
"Missing integer seed.")
178 except (KeyError, OSError, TypeError, ValueError)
as error:
179 invalid[name].append({
"manifest": str(path),
"error": str(error)})
182 rows[seed].append((path, manifest))
183 groups_out[name] = {}
186 row = {
"seed": seed,
"status":
"missing"}
188 row.update(status=
"duplicate", manifests=[str(path)
for path, _
in matches])
190 path, manifest = matches[0]
191 row, signatures[name, seed] = _result(path, manifest, seed, reporting_grid)
192 groups_out[name][seed] = row
195 for left, right
in combinations(groups_out, 2):
196 pairs, mismatched = [], []
198 a, b = groups_out[left][seed], groups_out[right][seed]
199 if a[
"status"] !=
"ok" or b[
"status"] !=
"ok":
201 if a[
"budget"] != b[
"budget"]
or signatures[left, seed] != signatures[right, seed]:
202 mismatched.append(seed)
204 pair = {
"seed": seed,
"coverage_delta": b[
"coverage"] - a[
"coverage"],
205 "qd_score_delta": _delta(a, b,
"qd_score")}
206 if "qd_hypervolume" in a:
207 pair[
"qd_hypervolume_delta"] = _delta(a, b,
"qd_hypervolume")
209 qd_deltas = [pair[
"qd_score_delta"]
for pair
in pairs
if pair[
"qd_score_delta"]
is not None]
210 comparison = {
"reference": left,
"comparison": right,
"pairs": pairs,
"incompatible_seeds": mismatched,
211 "median_coverage_delta": median(p[
"coverage_delta"]
for p
in pairs)
if pairs
else None,
212 "median_qd_score_delta": median(qd_deltas)
if qd_deltas
else None}
213 if any(
"qd_hypervolume_delta" in pair
for pair
in pairs):
214 volumes = [pair[
"qd_hypervolume_delta"]
for pair
in pairs
if pair.get(
"qd_hypervolume_delta")
is not None]
215 comparison[
"median_qd_hypervolume_delta"] = median(volumes)
if volumes
else None
216 comparisons.append(comparison)
217 return {
"schema_version": 1,
"groups": {name: list(rows.values())
for name, rows
in groups_out.items()},
218 "invalid_manifests": invalid,
"comparisons": comparisons}
221def _delta(left, right, key):
222 a, b = left.get(key), right.get(key)
223 return b - a
if a
is not None and b
is not None else None
226def _configuration_digest(configuration):
227 if not isinstance(configuration, dict):
228 raise ValueError(
"Expected a resolved configuration mapping.")
229 settings = _json_value({key: value
for key, value
in configuration.items()
if key !=
"seed"})
230 return sha256(json.dumps(settings, sort_keys=
True, separators=(
",",
":"), allow_nan=
False).encode()).hexdigest()
233def _run_identity(group, digest, seed):
234 return sha256(json.dumps([group, digest, seed], separators=(
",",
":")).encode()).hexdigest()
237def _retry_plan(groups, seeds, configurations, report):
238 if set(groups) != set(configurations):
239 raise ValueError(
"Supply one retry configuration file per run group.")
240 inventory, jobs, blocked = {}, [], []
241 for group, rows
in report[
"groups"].items():
242 config_path = Path(configurations[group]).resolve()
243 digest = _configuration_digest(yaml.safe_load(config_path.read_text(encoding=
"utf-8")))
244 inventory[group] = {
"results": str(Path(groups[group]).resolve()),
245 "config": str(config_path),
"configuration_sha256": digest}
247 identity = {
"group": group,
"seed": row[
"seed"],
"status": row[
"status"],
248 "run_id": _run_identity(group, digest, row[
"seed"])}
250 if row[
"status"] ==
"duplicate":
251 blocked.append({**identity,
"reason":
"multiple manifests for the seed"})
253 if "manifest" in row:
254 manifest = Path(row[
"manifest"]).resolve()
256 saved = read_run_manifest(manifest)
257 actual = _configuration_digest(saved[
"configuration"])
258 except (OSError, KeyError, TypeError, ValueError):
261 blocked.append({**identity,
"reason":
"manifest configuration differs from the group configuration"})
263 archive = saved.get(
"archive")
264 if (row.get(
"budget")
is not None and row[
"attempted"] == row[
"budget"]
265 and isinstance(archive, dict)
and "export_error" in archive):
266 blocked.append({**identity,
"reason":
"full-budget run has no verifiable portable archive"})
268 if row[
"status"] ==
"ok":
270 job = {**identity,
"config": str(config_path),
"configuration_sha256": digest,
"action":
"restart"}
271 if manifest
is not None:
272 checkpoint = manifest.with_name(
"checkpoint.pkl")
273 journal = manifest.with_name(
"evaluations.jsonl")
274 if checkpoint.is_file()
and journal.is_file():
275 job.update(action=
"resume", checkpoint=str(checkpoint), journal=str(journal))
277 return {
"schema_version": 1,
"groups": inventory,
"seeds": list(seeds),
"jobs": jobs,
"blocked": blocked}
285def make_retry_plan(groups, seeds, configurations):
286 """Return a JSON-ready retry plan for one resolved configuration per group.
288 Each run is identified by its group, configuration fingerprint, and
289 seed. Successful runs are omitted. Duplicate seeds, configuration
290 mismatches, and full-budget runs that cannot export an archive are
291 reported separately. An incomplete or failed run with a checkpoint
292 and journal next to its manifest gets a resume action.
293 Paths are resolved on the planning machine.
296 return _retry_plan(groups, seeds, configurations, compare_runs(groups, seeds))
300 """Run the portable comparison from the command line."""
301 parser = argparse.ArgumentParser(description=__doc__)
302 parser.add_argument(
"--group", action=
"append", metavar=
"NAME=DIRECTORY", required=
True)
303 parser.add_argument(
"--seeds", type=int, nargs=
"+", required=
True)
304 parser.add_argument(
"--reporting-grid", type=Path, help=
"Portable Grid or CVTGrid template.")
305 parser.add_argument(
"--retry-config", action=
"append", metavar=
"NAME=FILE")
306 parser.add_argument(
"--retry-plan", type=Path, help=
"Write a retry plan for the selected groups and seeds.")
307 parser.add_argument(
"--output", type=Path)
308 args = parser.parse_args(argv)
309 def named_paths(values, label):
312 name, _, path = value.partition(
"=")
313 if not name
or not path
or name
in paths:
314 parser.error(f
"Supply distinct {label} as NAME=PATH.")
318 groups = named_paths(args.group,
"groups")
319 if (args.retry_plan
is None) != (args.retry_config
is None):
320 parser.error(
"--retry-plan and --retry-config need to be used together.")
321 if args.retry_plan
is not None and args.output
is not None and args.retry_plan.resolve() == args.output.resolve():
322 parser.error(
"The report and the retry plan need distinct paths.")
323 template = load_grid(args.reporting_grid)
if args.reporting_grid
is not None else None
324 report = compare_runs(groups, args.seeds, reporting_grid=template)
325 if args.retry_plan
is not None:
326 configurations = named_paths(args.retry_config,
"retry configurations")
328 plan = _retry_plan(groups, args.seeds, configurations, report)
330 plan = make_retry_plan(groups, args.seeds, configurations)
331 args.retry_plan.parent.mkdir(parents=
True, exist_ok=
True)
332 _write(args.retry_plan, _json_bytes(plan))
333 data = _json_bytes(report)
334 if args.output
is None:
335 print(data.decode(), end=
"")
337 args.output.parent.mkdir(parents=
True, exist_ok=
True)
338 _write(args.output, data)
341if __name__ ==
"__main__":