File size: 11,256 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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()