QDpy
Loading...
Searching...
No Matches
reporting.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Read verifiable QDpy runs and compare them by seed."""
6
7import argparse
8from collections import defaultdict
9from dataclasses import dataclass
10from hashlib import sha256
11from itertools import combinations
12import json
13from math import isfinite, prod
14from pathlib import Path
15from statistics import median
16
17import yaml
18
19from qdpy._archive_comparison import ArchiveCellComparison, compare_archive_cells
20from qdpy.algorithms.uncertain import _measurement_groups
21from qdpy.containers import CVTGrid, Grid, ParetoGrid
22from qdpy.phenotype import Features, Fitness, _CellIndividual
23from qdpy.results import _grid_snapshot, _json_bytes, _json_value, _write, load_grid, read_run_manifest
24
25__all__ = ["ArchiveComparison", "ArchiveCellComparison", "audit_archive", "compare_archive_cells",
26 "compare_runs", "make_retry_plan"]
27
28
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.")
40 weights = selected
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))
45
46
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):
53 return
54 try:
55 cell = target.index_grid(features)
56 except IndexError:
57 return
58 candidate = _CellIndividual(elite, cell, fitness=Fitness(fitness.values, weights=fitness.weights),
59 features=Features(features))
60 target.add(candidate)
61
62
63def _metrics(grid):
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)
76 return metrics
77 qd = grid.qd_score()
78 metrics["qd_score"] = float(qd) if isfinite(qd) else None
79 return metrics
80
81
82@dataclass(frozen=True)
84 """Audited archives, per-geometry metrics, and shared rollout counts."""
85
86 archives: dict
87 metrics: dict
88 rollouts: int
89 failed_rollouts: int
90
91
92
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.
95
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.
102 """
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.")
105 if not reporting:
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)
115
116
117def _signature(grid):
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]
123
124
125def _result(path, manifest, seed, template):
126 row = {"seed": seed, "manifest": str(path)}
127 try:
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)
144 for elite in grid:
145 _offer(target, grid, elite)
146 grid = target
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
150
151
152
153def compare_runs(groups, seeds, *, reporting_grid=None):
154 """Return run status and paired metric differences for named directories.
155
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.
163 """
164 seeds = tuple(seeds)
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)
171 invalid[name] = []
172 for path in sorted([*roots.rglob("run.json"), *roots.rglob("run_*.json")]):
173 try:
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)})
180 continue
181 if seed in seeds:
182 rows[seed].append((path, manifest))
183 groups_out[name] = {}
184 for seed in seeds:
185 matches = rows[seed]
186 row = {"seed": seed, "status": "missing"}
187 if len(matches) > 1:
188 row.update(status="duplicate", manifests=[str(path) for path, _ in matches])
189 elif matches:
190 path, manifest = matches[0]
191 row, signatures[name, seed] = _result(path, manifest, seed, reporting_grid)
192 groups_out[name][seed] = row
193
194 comparisons = []
195 for left, right in combinations(groups_out, 2):
196 pairs, mismatched = [], []
197 for seed in seeds:
198 a, b = groups_out[left][seed], groups_out[right][seed]
199 if a["status"] != "ok" or b["status"] != "ok":
200 continue
201 if a["budget"] != b["budget"] or signatures[left, seed] != signatures[right, seed]:
202 mismatched.append(seed)
203 continue
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")
208 pairs.append(pair)
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}
219
220
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
224
225
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()
231
232
233def _run_identity(group, digest, seed):
234 return sha256(json.dumps([group, digest, seed], separators=(",", ":")).encode()).hexdigest()
235
236
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}
246 for row in rows:
247 identity = {"group": group, "seed": row["seed"], "status": row["status"],
248 "run_id": _run_identity(group, digest, row["seed"])}
249 manifest = None
250 if row["status"] == "duplicate":
251 blocked.append({**identity, "reason": "multiple manifests for the seed"})
252 continue
253 if "manifest" in row:
254 manifest = Path(row["manifest"]).resolve()
255 try:
256 saved = read_run_manifest(manifest)
257 actual = _configuration_digest(saved["configuration"])
258 except (OSError, KeyError, TypeError, ValueError):
259 actual = None
260 if actual != digest:
261 blocked.append({**identity, "reason": "manifest configuration differs from the group configuration"})
262 continue
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"})
267 continue
268 if row["status"] == "ok":
269 continue
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))
276 jobs.append(job)
277 return {"schema_version": 1, "groups": inventory, "seeds": list(seeds), "jobs": jobs, "blocked": blocked}
278
279
280
285def make_retry_plan(groups, seeds, configurations):
286 """Return a JSON-ready retry plan for one resolved configuration per group.
287
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.
294 """
295 seeds = tuple(seeds)
296 return _retry_plan(groups, seeds, configurations, compare_runs(groups, seeds))
297
298
299def main(argv=None):
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):
310 paths = {}
311 for value in values:
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.")
315 paths[name] = path
316 return paths
317
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")
327 if template is None:
328 plan = _retry_plan(groups, args.seeds, configurations, report)
329 else:
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="")
336 else:
337 args.output.parent.mkdir(parents=True, exist_ok=True)
338 _write(args.output, data)
339
340
341if __name__ == "__main__":
342 main()