Download scripts/phase13_generate_statistics.py from Moon-Young-Choi/HUTACE_Mapzen_Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/datasets/Moon-Young-Choi/HUTACE_Mapzen_Benchmark/resolve/main/scripts/phase13_generate_statistics.py
- Command line
-
hf download hf://datasets/Moon-Young-Choi/HUTACE_Mapzen_Benchmark/scripts/phase13_generate_statistics.py
-
curl -L -o phase13_generate_statistics.py https://huggingface.co/datasets/Moon-Young-Choi/HUTACE_Mapzen_Benchmark/resolve/main/scripts/phase13_generate_statistics.py
11.3 kB
| from __future__ import annotations | |
| import csv | |
| import json | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| ROOT = Path(__file__).resolve().parents[1] | |
| LEARNED = ROOT / "artifacts" / "phase13" / "learned_results_v2" | |
| HEURISTICS = ROOT / "artifacts" / "phase13" / "heuristics" | |
| MANIFEST = ROOT / "artifacts" / "phase10" / "final" / "selected_manifest.jsonl" | |
| OUTPUT = ROOT / "artifacts" / "phase13" / "analysis" | |
| REPORT = ROOT / "reports" / "phase13_statistical_analysis.json" | |
| BOOTSTRAP_REPS = 10_000 | |
| BOOTSTRAP_SEED = 130524 | |
| ALPHA = 0.05 | |
| LEARNED_METHODS = [ | |
| "hutace_full", | |
| "ariadne_graph_attention_ppo_adapted", | |
| "cnn_ppo", | |
| "plain_unet_ppo", | |
| ] | |
| HEURISTIC_METHODS = [ | |
| "random_local_waypoint", | |
| "nearest_frontier", | |
| "expected_gain_per_estimated_energy", | |
| ] | |
| ORACLE = "full_map_greedy_oracle_diagnostic" | |
| METRICS = { | |
| "final_coverage": ("coverage", "higher"), | |
| "coverage_energy_auc": ("coverage_auc", "higher"), | |
| "coverage_at_320": ("coverage_at_320", "higher"), | |
| "energy_to_0_50_censored": ("energy_to_0_50", "lower"), | |
| } | |
| def read_jsonl(path: Path) -> list[dict]: | |
| with path.open("r", encoding="utf-8") as handle: | |
| return [json.loads(line) for line in handle if line.strip()] | |
| def write_csv(path: Path, rows: list[dict]) -> None: | |
| if not rows: | |
| raise RuntimeError(f"Refusing to write empty table: {path}") | |
| with path.open("w", newline="", encoding="utf-8") as handle: | |
| writer = csv.DictWriter(handle, fieldnames=list(rows[0])) | |
| writer.writeheader() | |
| writer.writerows(rows) | |
| def load_results(): | |
| learned_rows: dict[str, list[tuple[int, list[dict]]]] = defaultdict(list) | |
| learned_curves: dict[str, list[np.ndarray]] = defaultdict(list) | |
| for directory in sorted(path for path in LEARNED.iterdir() if path.is_dir()): | |
| summary = json.loads((directory / "summary.json").read_text(encoding="utf-8")) | |
| method = summary["model_id"] | |
| learned_rows[method].append((int(summary["seed"]), read_jsonl(directory / "test_rows.jsonl"))) | |
| learned_curves[method].append(np.load(directory / "test_curves.npz")["curves"]) | |
| for method in learned_rows: | |
| learned_rows[method].sort(key=lambda item: item[0]) | |
| heuristic_rows = { | |
| method: read_jsonl(HEURISTICS / f"{method}_test_rows.jsonl") | |
| for method in HEURISTIC_METHODS + [ORACLE] | |
| } | |
| heuristic_curves = { | |
| method: np.load(HEURISTICS / f"{method}_test_curves.npz")["curves"] | |
| for method in HEURISTIC_METHODS + [ORACLE] | |
| } | |
| return learned_rows, learned_curves, heuristic_rows, heuristic_curves | |
| def validate_alignment(learned_rows, heuristic_rows) -> list[tuple[str, int]]: | |
| if set(learned_rows) != set(LEARNED_METHODS): | |
| raise RuntimeError(f"Learned method mismatch: {set(learned_rows)}") | |
| reference = None | |
| for method in LEARNED_METHODS: | |
| if len(learned_rows[method]) != 10: | |
| raise RuntimeError(f"Expected 10 seeds for {method}") | |
| for _, rows in learned_rows[method]: | |
| keys = [(row["terrain_id"], int(row["start_seed"])) for row in rows] | |
| if len(keys) != 256 or len(set(keys)) != 256: | |
| raise RuntimeError(f"Episode-key failure for {method}") | |
| reference = keys if reference is None else reference | |
| if keys != reference: | |
| raise RuntimeError(f"Episode alignment failure for {method}") | |
| for method, rows in heuristic_rows.items(): | |
| keys = [(row["terrain_id"], int(row["start_seed"])) for row in rows] | |
| if keys != reference: | |
| raise RuntimeError(f"Episode alignment failure for {method}") | |
| return reference | |
| def holm_adjust(p_values: list[float]) -> list[float]: | |
| order = np.argsort(p_values) | |
| adjusted = np.empty(len(p_values), dtype=float) | |
| running = 0.0 | |
| total = len(p_values) | |
| for rank, index in enumerate(order): | |
| value = min(1.0, (total - rank) * p_values[index]) | |
| running = max(running, value) | |
| adjusted[index] = running | |
| return adjusted.tolist() | |
| def main() -> None: | |
| OUTPUT.mkdir(parents=True, exist_ok=True) | |
| learned_rows, learned_curves, heuristic_rows, heuristic_curves = load_results() | |
| keys = validate_alignment(learned_rows, heuristic_rows) | |
| metadata = { | |
| row["candidate_id"]: row | |
| for row in read_jsonl(MANIFEST) | |
| if row["split"] == "test" | |
| } | |
| strata: dict[tuple[str, str], list[int]] = defaultdict(list) | |
| for index, (terrain_id, _) in enumerate(keys): | |
| row = metadata[terrain_id] | |
| strata[(row["continent"], row["stratum"])].append(index) | |
| arrays: dict[str, dict[str, np.ndarray]] = {} | |
| seeds: dict[str, list[int]] = {} | |
| for method, runs in learned_rows.items(): | |
| seeds[method] = [seed for seed, _ in runs] | |
| arrays[method] = { | |
| metric: np.asarray([[row[field] for row in rows] for _, rows in runs], dtype=float) | |
| for metric, (field, _) in METRICS.items() | |
| } | |
| for method, rows in heuristic_rows.items(): | |
| arrays[method] = { | |
| metric: np.asarray([[row[field] for row in rows]], dtype=float) | |
| for metric, (field, _) in METRICS.items() | |
| } | |
| if any(seeds[method] != seeds["hutace_full"] for method in LEARNED_METHODS): | |
| raise RuntimeError("Learned methods do not share paired training seeds") | |
| overall = [] | |
| for method in LEARNED_METHODS + HEURISTIC_METHODS + [ORACLE]: | |
| for metric in METRICS: | |
| per_seed = arrays[method][metric].mean(axis=1) | |
| overall.append({ | |
| "method": method, | |
| "method_type": "learned" if method in LEARNED_METHODS else ("oracle_diagnostic" if method == ORACLE else "heuristic"), | |
| "metric": metric, | |
| "mean": float(per_seed.mean()), | |
| "training_seed_sd": float(per_seed.std(ddof=1)) if len(per_seed) > 1 else "", | |
| "training_seeds": len(per_seed) if method in LEARNED_METHODS else 0, | |
| "test_episodes": 256, | |
| }) | |
| write_csv(OUTPUT / "overall_metrics.csv", overall) | |
| rng = np.random.default_rng(BOOTSTRAP_SEED) | |
| terrain_samples = np.empty((BOOTSTRAP_REPS, len(keys)), dtype=np.int32) | |
| cursor = 0 | |
| for group in sorted(strata): | |
| indices = np.asarray(strata[group], dtype=np.int32) | |
| width = len(indices) | |
| terrain_samples[:, cursor:cursor + width] = rng.choice( | |
| indices, size=(BOOTSTRAP_REPS, width), replace=True | |
| ) | |
| cursor += width | |
| seed_samples = rng.integers(0, 10, size=(BOOTSTRAP_REPS, 10), dtype=np.int16) | |
| comparisons = [] | |
| raw_p_values = [] | |
| for baseline in LEARNED_METHODS[1:] + HEURISTIC_METHODS: | |
| for metric, (_, direction) in METRICS.items(): | |
| hut = arrays["hutace_full"][metric] | |
| hut_boot = hut[seed_samples[:, :, None], terrain_samples[:, None, :]].mean(axis=(1, 2)) | |
| base = arrays[baseline][metric] | |
| if baseline in LEARNED_METHODS: | |
| base_boot = base[seed_samples[:, :, None], terrain_samples[:, None, :]].mean(axis=(1, 2)) | |
| else: | |
| base_boot = base[0, terrain_samples].mean(axis=1) | |
| raw_diff = hut_boot - base_boot | |
| oriented = raw_diff if direction == "higher" else -raw_diff | |
| point_raw = float(hut.mean() - base.mean()) | |
| probability = float(np.mean(oriented > 0.0)) | |
| p_value = min(1.0, 2.0 * min(np.mean(oriented <= 0.0), np.mean(oriented >= 0.0))) | |
| row = { | |
| "model": "hutace_full", | |
| "baseline": baseline, | |
| "metric": metric, | |
| "preferred_direction": direction, | |
| "hutace_mean": float(hut.mean()), | |
| "baseline_mean": float(base.mean()), | |
| "raw_difference_hutace_minus_baseline": point_raw, | |
| "oriented_improvement": point_raw if direction == "higher" else -point_raw, | |
| "ci95_low_oriented": float(np.quantile(oriented, 0.025)), | |
| "ci95_high_oriented": float(np.quantile(oriented, 0.975)), | |
| "probability_improvement": probability, | |
| "bootstrap_two_sided_p": float(p_value), | |
| } | |
| comparisons.append(row) | |
| raw_p_values.append(float(p_value)) | |
| adjusted = holm_adjust(raw_p_values) | |
| for row, p_adjusted in zip(comparisons, adjusted): | |
| row["holm_adjusted_p"] = p_adjusted | |
| row["holm_significant_0_05"] = p_adjusted < ALPHA | |
| write_csv(OUTPUT / "paired_hierarchical_bootstrap_holm.csv", comparisons) | |
| stratum_rows = [] | |
| for (continent, stratum), indices in sorted(strata.items()): | |
| for method in LEARNED_METHODS + HEURISTIC_METHODS + [ORACLE]: | |
| for metric in METRICS: | |
| stratum_rows.append({ | |
| "continent": continent, | |
| "stratum": stratum, | |
| "episodes": len(indices), | |
| "method": method, | |
| "metric": metric, | |
| "mean": float(arrays[method][metric][:, indices].mean()), | |
| }) | |
| write_csv(OUTPUT / "metrics_by_continent_stratum.csv", stratum_rows) | |
| energy_grid = np.linspace(0.0, 640.0, 65) | |
| plt.figure(figsize=(9, 5.5)) | |
| for method in LEARNED_METHODS: | |
| curve = np.mean(np.stack(learned_curves[method]), axis=(0, 1)) | |
| plt.plot(energy_grid, curve, label=method, linewidth=2.0 if method == "hutace_full" else 1.4) | |
| for method in HEURISTIC_METHODS: | |
| plt.plot(energy_grid, heuristic_curves[method].mean(axis=0), label=method, linestyle="--", linewidth=1.2) | |
| plt.xlabel("Energy consumed") | |
| plt.ylabel("Observed-map coverage") | |
| plt.ylim(0, 1) | |
| plt.grid(alpha=0.25) | |
| plt.legend(fontsize=7, ncol=2) | |
| plt.tight_layout() | |
| plt.savefig(OUTPUT / "coverage_energy_curves.png", dpi=220) | |
| plt.close() | |
| report = { | |
| "schema_version": 1, | |
| "phase": 13, | |
| "status": "completed", | |
| "gate_passed": True, | |
| "test_accessed": True, | |
| "test_episodes": len(keys), | |
| "learned_seeds_per_method": 10, | |
| "bootstrap": { | |
| "repetitions": BOOTSTRAP_REPS, | |
| "seed": BOOTSTRAP_SEED, | |
| "resampling": "paired training seeds plus test episodes within continent-by-terrain-stratum cells", | |
| "confidence_interval": "percentile 95%", | |
| "multiplicity": "Holm family-wise correction across 24 primary comparisons", | |
| }, | |
| "primary_baselines": LEARNED_METHODS[1:] + HEURISTIC_METHODS, | |
| "oracle": {"method": ORACLE, "primary_comparison": False, "purpose": "diagnostic upper reference only"}, | |
| "outputs": [ | |
| "artifacts/phase13/analysis/overall_metrics.csv", | |
| "artifacts/phase13/analysis/paired_hierarchical_bootstrap_holm.csv", | |
| "artifacts/phase13/analysis/metrics_by_continent_stratum.csv", | |
| "artifacts/phase13/analysis/coverage_energy_curves.png", | |
| ], | |
| } | |
| REPORT.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") | |
| print("PHASE13_STATISTICS_COMPLETED", flush=True) | |
| if __name__ == "__main__": | |
| main() | |