File size: 5,212 Bytes
1fc8dae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
from __future__ import annotations

import argparse
import hashlib
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np

from hutace_benchmark.config import EnvConfig
from hutace_benchmark.datasets import ManifestTerrainDataset
from hutace_benchmark.evaluation import fixed_specs, run_episode
from hutace_benchmark.heuristics import MAIN_HEURISTICS, full_map_greedy_oracle_diagnostic


ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "artifacts" / "phase10" / "final" / "selected_manifest.jsonl"
OUTPUT = ROOT / "artifacts" / "phase13" / "heuristics"
REPORT = ROOT / "reports" / "phase13_heuristic_test.json"
_DATASET = None
_CONTROLLER = None
_CFG = None


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest().upper()


def init_worker(method: str) -> None:
    global _DATASET, _CONTROLLER, _CFG
    _DATASET = ManifestTerrainDataset(MANIFEST, root=ROOT, cache_size=8)
    _CONTROLLER = (
        full_map_greedy_oracle_diagnostic
        if method == "full_map_greedy_oracle_diagnostic"
        else MAIN_HEURISTICS[method]
    )
    _CFG = EnvConfig()


def evaluate_spec(index_and_spec):
    index, spec = index_and_spec
    row, curve, _ = run_episode(
        _DATASET, spec, _CONTROLLER, _CFG, allow_test=True
    )
    return index, row, curve


def write_jsonl(path: Path, rows: list[dict]) -> None:
    path.write_text(
        "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows),
        encoding="utf-8",
    )


def summarize(rows: list[dict]) -> dict:
    return {
        "episodes": len(rows),
        "final_coverage": float(np.mean([row["coverage"] for row in rows])),
        "coverage_energy_auc": float(np.mean([row["coverage_auc"] for row in rows])),
        "coverage_at_320": float(np.mean([row["coverage_at_320"] for row in rows])),
        "revisit_ratio": float(np.mean([row["revisit_ratio"] for row in rows])),
        "reach_rate_0_50": float(np.mean([row["reached_0_50"] for row in rows])),
        "energy_to_0_50_censored": float(np.mean([row["energy_to_0_50"] for row in rows])),
        "distance_m": float(np.mean([row["distance_m"] for row in rows])),
        "decisions": float(np.mean([row["decisions"] for row in rows])),
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--episodes", type=int, default=256)
    parser.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1))
    args = parser.parse_args()
    OUTPUT.mkdir(parents=True, exist_ok=True)
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    dataset = ManifestTerrainDataset(MANIFEST, root=ROOT)
    specs = fixed_specs(dataset, "test", args.episodes, 230524)
    methods = list(MAIN_HEURISTICS) + ["full_map_greedy_oracle_diagnostic"]
    report = {
        "schema_version": 1,
        "phase": 13,
        "status": "running",
        "test_episodes": args.episodes,
        "fixed_spec_seed": 230524,
        "workers": args.workers,
        "test_accessed": True,
        "protocol": {
            "fair_baselines_use_partial_observation_only": True,
            "oracle_excluded_from_primary_comparison": True,
        },
        "methods": {},
    }
    REPORT.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    for method in methods:
        started = time.perf_counter()
        results = []
        with ProcessPoolExecutor(
            max_workers=args.workers, initializer=init_worker, initargs=(method,)
        ) as pool:
            for count, result in enumerate(
                pool.map(evaluate_spec, enumerate(specs), chunksize=1), 1
            ):
                results.append(result)
                if count % 16 == 0 or count == len(specs):
                    print(
                        f"PHASE13_HEURISTIC_PROGRESS={method}:{count}/{len(specs)}",
                        flush=True,
                    )
        results.sort(key=lambda item: item[0])
        rows = [item[1] for item in results]
        curves = np.stack([item[2] for item in results])
        rows_path = OUTPUT / f"{method}_test_rows.jsonl"
        curves_path = OUTPUT / f"{method}_test_curves.npz"
        write_jsonl(rows_path, rows)
        np.savez_compressed(curves_path, curves=curves)
        report["methods"][method] = {
            **summarize(rows),
            "wall_seconds": time.perf_counter() - started,
            "rows_sha256": sha256(rows_path),
            "curves_sha256": sha256(curves_path),
            "diagnostic_only": method == "full_map_greedy_oracle_diagnostic",
            "fair_primary_baseline": method != "full_map_greedy_oracle_diagnostic",
        }
        REPORT.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    report["status"] = "completed"
    report["gate_passed"] = True
    REPORT.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    print("PHASE13_HEURISTIC_RESULT=" + json.dumps(report, separators=(",", ":")), flush=True)


if __name__ == "__main__":
    main()