File size: 11,209 Bytes
5a5e5cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/env python3
"""Freeze accepted CoDrive routes into a reproducible benchmark catalog."""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
import statistics
from collections import Counter, defaultdict
from pathlib import Path


PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_DATASET_ROOT = PROJECT_ROOT / "closed_dataset"
DEFAULT_RUN_ROOT = DEFAULT_DATASET_ROOT / "acceptance_final_v1_runs"
DEFAULT_OUTPUT = DEFAULT_DATASET_ROOT / "acceptance_final_v1"


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()


def _route_path(dataset_root: Path, route_id: str) -> Path:
    matches = list((dataset_root / "routes").glob(f"*/{route_id}.xml"))
    if len(matches) != 1:
        raise RuntimeError(f"expected one XML for {route_id}, found {len(matches)}")
    return matches[0]


def _report_path(run_root: Path, route_id: str) -> Path:
    matches = list(run_root.glob(f"*/{route_id}/acceptance_report.json"))
    if len(matches) != 1:
        raise RuntimeError(
            f"expected one acceptance report for {route_id}, found {len(matches)}"
        )
    return matches[0]


def _format_average(values: list[float]) -> str:
    return f"{statistics.fmean(values):.2f}" if values else "n/a"


def finalize(dataset_root: Path, run_root: Path, output: Path) -> dict:
    manifest_path = dataset_root / "manifest.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    routes = manifest.get("routes", [])
    if len(routes) != 60:
        raise RuntimeError(f"expected 60 manifest routes, found {len(routes)}")

    output.mkdir(parents=True, exist_ok=True)
    reports_dir = output / "reports"
    if reports_dir.exists():
        shutil.rmtree(reports_dir)
    reports_dir.mkdir(parents=True)

    scenario_path = dataset_root / "scenarios/closed_coopeval_scenarios.py"
    validator_path = dataset_root / "scripts/validate_pdm_acceptance.py"
    records = []
    errors = []
    for route in routes:
        route_id = route["route_id"]
        route_path = _route_path(dataset_root, route_id)
        report_path = _report_path(run_root, route_id)
        report = json.loads(report_path.read_text(encoding="utf-8"))
        route_hash = _sha256(route_path)

        route_errors = []
        if not report.get("accepted"):
            route_errors.append("acceptance report rejected the route")
        if report.get("route_sha256") != route_hash:
            route_errors.append("route hash differs from the accepted XML")
        if report.get("route_status") not in {"Completed", "Perfect"}:
            route_errors.append(f"route status is {report.get('route_status')!r}")
        if float(report.get("route_completion", 0.0)) < 99.0:
            route_errors.append("route completion is below 99%")
        if any(int(value) for value in report.get("collision_counts", {}).values()):
            route_errors.append("collision count is nonzero")
        if int(report.get("blocked_count", 0)):
            route_errors.append("blocked count is nonzero")
        if int(report.get("scenario_timeout_count", 0)):
            route_errors.append("scenario timeout count is nonzero")
        if not report.get("physical_completion_event"):
            route_errors.append("physical completion event is missing")
        if "hint_on" not in report.get("cooperative_agent_events", []):
            route_errors.append("hint_on is missing")
        if "hint_off" not in report.get("cooperative_agent_events", []):
            route_errors.append("hint_off is missing")
        if int(report.get("frame_count", 0)) <= 0:
            route_errors.append("no RGB frames were saved")
        if int(report.get("video_count", 0)) <= 0:
            route_errors.append("no video was saved")

        if route_errors:
            errors.append({"route_id": route_id, "errors": route_errors})

        copied_report = reports_dir / route["family"] / f"{route_id}.json"
        copied_report.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(report_path, copied_report)
        records.append(
            {
                "route_id": route_id,
                "family": route["family"],
                "town": route["town"],
                "source_route_id": route["source_route_id"],
                "weather_profile": route["weather_profile"],
                "route_length_m": route["route_length_m"],
                "route_xml": str(route_path.relative_to(dataset_root)),
                "route_sha256": route_hash,
                "accepted": not route_errors,
                "physical_completion_event": report.get("physical_completion_event"),
                "event_release_reason": report.get("event_release_reason"),
                "duration_game_s": report.get("duration_game_s"),
                "frame_count": report.get("frame_count"),
                "route_completion": report.get("route_completion"),
                "variation": {
                    key: route[key]
                    for key in (
                        "occluder_model",
                        "ped_age",
                        "cut_in_from",
                        "cut_in_model",
                        "deterministic_actor",
                        "obstacle_model",
                        "car_a_dir",
                        "ghost_model",
                        "ghost_speed",
                        "flow_speed",
                    )
                    if key in route
                },
                "evidence_run_dir": report.get("run_dir"),
            }
        )

    if errors:
        raise RuntimeError(json.dumps(errors, indent=2))

    family_records: dict[str, list[dict]] = defaultdict(list)
    for record in records:
        family_records[record["family"]].append(record)

    lock = {
        "benchmark": "CoDrive",
        "version": "1.0",
        "route_count": len(records),
        "manifest_sha256": _sha256(manifest_path),
        "scenario_script_sha256": _sha256(scenario_path),
        "acceptance_validator_sha256": _sha256(validator_path),
        "source_xml_sha256": manifest["source_xml_sha256"],
        "family_counts": dict(Counter(record["family"] for record in records)),
        "acceptance": {
            "accepted": len(records),
            "rejected": 0,
            "collision_routes": 0,
            "blocked_routes": 0,
            "timeout_routes": 0,
        },
        "routes": records,
    }
    lock_path = dataset_root / "benchmark_v1.lock.json"
    lock_path.write_text(json.dumps(lock, indent=2) + "\n", encoding="utf-8")

    lines = [
        "# CoDrive Benchmark v1.0 Audit",
        "",
        "This file is generated by `closed_dataset/scripts/finalize_benchmark_v1.py`.",
        "",
        "## Release Contract",
        "",
        f"- Routes: {len(records)} total, 10 per scenario family.",
        "- Static validation: passed.",
        "- PDM-Lite acceptance: 60/60 passed.",
        "- Collisions, blocked routes, and scenario timeouts: 0.",
        "- Every run contains hint-on, physical completion, hint-off, RGB frames, and video.",
        f"- Scenario implementation SHA256: `{lock['scenario_script_sha256']}`.",
        "",
        "## Scenario Summary",
        "",
        "| Scenario family | Routes | Towns | Weather profiles | Mean length (m) | Mean duration (s) |",
        "| --- | ---: | ---: | ---: | ---: | ---: |",
    ]
    for family in sorted(family_records):
        values = family_records[family]
        lines.append(
            "| {family} | {routes} | {towns} | {weather} | {length} | {duration} |".format(
                family=family.replace("_", " ").title(),
                routes=len(values),
                towns=len({record["town"] for record in values}),
                weather=len({record["weather_profile"] for record in values}),
                length=_format_average(
                    [float(record["route_length_m"]) for record in values]
                ),
                duration=_format_average(
                    [float(record["duration_game_s"]) for record in values]
                ),
            )
        )
    lines.extend(
        [
            "",
            "## Reproduction",
            "",
            "Run the static and PDM-Lite validators before publishing modified routes:",
            "",
            "```bash",
            "python closed_dataset/validate.py --root closed_dataset",
            "python closed_dataset/scripts/run_pdm_acceptance_suite.py \\",
            "  --route-root closed_dataset/routes \\",
            "  --run-root closed_dataset/acceptance_final_v1_runs \\",
            "  --gpu 2 --graphics-adapter 0 --port 4897 --tm-port 10897 --rerun",
            "python closed_dataset/scripts/finalize_benchmark_v1.py",
            "```",
            "",
            "The exact XML hashes and evidence paths are recorded in",
            "`closed_dataset/benchmark_v1.lock.json`.",
            "",
        ]
    )
    (dataset_root / "BENCHMARK_V1_AUDIT.md").write_text(
        "\n".join(lines), encoding="utf-8"
    )
    catalog_lines = [
        "# CoDrive v1.0 Route Catalog",
        "",
        "| Route | Scenario family | Town | Weather | Length (m) | Source | Variation |",
        "| --- | --- | --- | --- | ---: | --- | --- |",
    ]
    for record in sorted(records, key=lambda item: (item["family"], item["route_id"])):
        variation = ", ".join(
            f"{key}={value}" for key, value in sorted(record["variation"].items())
        )
        catalog_lines.append(
            "| {route} | {family} | {town} | {weather} | {length:.2f} | {source} | {variation} |".format(
                route=record["route_id"],
                family=record["family"].replace("_", " ").title(),
                town=record["town"],
                weather=record["weather_profile"].replace("_", " "),
                length=float(record["route_length_m"]),
                source=record["source_route_id"],
                variation=variation or "geometry and actor placement",
            )
        )
    catalog_lines.append("")
    (dataset_root / "ROUTE_CATALOG.md").write_text(
        "\n".join(catalog_lines), encoding="utf-8"
    )
    (output / "acceptance_summary.json").write_text(
        json.dumps(lock, indent=2) + "\n", encoding="utf-8"
    )
    return lock


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT)
    parser.add_argument("--run-root", type=Path, default=DEFAULT_RUN_ROOT)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    args = parser.parse_args()
    lock = finalize(
        args.dataset_root.resolve(),
        args.run_root.resolve(),
        args.output.resolve(),
    )
    print(
        f"CoDrive v{lock['version']} frozen: "
        f"{lock['acceptance']['accepted']}/{lock['route_count']} accepted"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())