#!/usr/bin/env python3 """Validate paired CoDrive Route-B controls against frozen Route A.""" from __future__ import annotations import argparse import copy import hashlib import json import xml.etree.ElementTree as ET from collections import Counter from pathlib import Path from typing import Optional PROJECT_ROOT = Path(__file__).resolve().parents[2] DEFAULT_DATASET_ROOT = PROJECT_ROOT / "closed_dataset" EXPECTED_FAMILIES = ( "occluded_pedestrian", "vehicle_cut_in", "static_obstacle_reveal", "wrong_way_left_turn", "wrong_way_right_turn", "right_turn_on_red_yield", ) def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _canonical(element: ET.Element) -> bytes: clone = copy.deepcopy(element) for node in clone.iter(): if node.text is not None and not node.text.strip(): node.text = None if node.tail is not None and not node.tail.strip(): node.tail = None return ET.tostring(clone, encoding="utf-8") def _single_route(path: Path) -> ET.Element: root = ET.parse(path).getroot() routes = root.findall("route") assert len(routes) == 1, f"{path}: expected one route, found {len(routes)}" return routes[0] def _a_payload(route: ET.Element) -> bytes: clone = copy.deepcopy(route) clone.attrib.pop("id", None) scenarios = clone.find("scenarios") if scenarios is not None: clone.remove(scenarios) return _canonical(clone) def _b_payload(route: ET.Element) -> bytes: clone = copy.deepcopy(route) clone.attrib.pop("id", None) clone.attrib.pop("benchmark_variant", None) clone.attrib.pop("paired_route_a_id", None) scenarios = clone.find("scenarios") if scenarios is not None: clone.remove(scenarios) return _canonical(clone) def validate(dataset_root: Path, expected_per_family: Optional[int] = None) -> dict: manifest_a_path = dataset_root / "manifest.json" manifest_b_path = dataset_root / "route_b_manifest.json" lock_b_path = dataset_root / "route_b.lock.json" combined_b_path = dataset_root / "coopeval_closed_B.xml" manifest_a = json.loads(manifest_a_path.read_text(encoding="utf-8")) manifest_b = json.loads(manifest_b_path.read_text(encoding="utf-8")) lock_b = json.loads(lock_b_path.read_text(encoding="utf-8")) if expected_per_family is None: route_count = int(manifest_a["route_count"]) assert route_count % len(EXPECTED_FAMILIES) == 0, route_count expected_per_family = route_count // len(EXPECTED_FAMILIES) expected_total = expected_per_family * len(EXPECTED_FAMILIES) expected_family_counts = { family: expected_per_family for family in EXPECTED_FAMILIES } assert manifest_a["route_count"] == expected_total assert manifest_b["route_count"] == expected_total assert manifest_b["variant"] == "B" assert lock_b["route_count"] == expected_total assert lock_b["route_a_manifest_sha256"] == _sha256(manifest_a_path) assert lock_b["route_b_manifest_sha256"] == _sha256(manifest_b_path) assert lock_b["combined_route_b_sha256"] == _sha256(combined_b_path) assert lock_b["scenario_wrapper_sha256"] == _sha256( dataset_root / "scenarios" / "closed_coopeval_scenarios.py" ) records_a = {record["route_id"]: record for record in manifest_a["routes"]} records_b = { record["route_b_id"]: record for record in manifest_b["routes"] } assert len(records_a) == len(records_b) == expected_total combined_routes = ET.parse(combined_b_path).getroot().findall("route") assert len(combined_routes) == expected_total combined_by_id = {route.attrib["id"]: route for route in combined_routes} assert len(combined_by_id) == expected_total, "duplicate Route-B IDs" assert set(combined_by_id) == set(records_b), ( "combined Route-B XML and manifest disagree" ) family_counts: Counter[str] = Counter() towns: Counter[str] = Counter() for route_b_id, record_b in records_b.items(): route_a_id = record_b["route_a_id"] assert route_a_id in records_a, f"{route_b_id}: missing paired Route A" assert route_b_id == f"{route_a_id}_B" route_a_path = dataset_root / record_b["route_a_xml"] route_b_path = dataset_root / record_b["route_b_xml"] assert route_a_path.is_file(), route_a_path assert route_b_path.is_file(), route_b_path assert record_b["route_a_sha256"] == _sha256(route_a_path) assert record_b["route_b_sha256"] == _sha256(route_b_path) route_a = _single_route(route_a_path) route_b = _single_route(route_b_path) assert route_b.attrib["id"] == route_b_id assert route_b.attrib.get("benchmark_variant") == "B" assert route_b.attrib.get("paired_route_a_id") == route_a_id assert route_b.attrib.get("town") == route_a.attrib.get("town") assert route_b.attrib.get("source_route_id") == route_a.attrib.get( "source_route_id" ) assert _a_payload(route_a) == _b_payload(route_b), ( f"{route_b_id}: Route-A/B weather or waypoint payload differs" ) scenarios_a = route_a.findall("./scenarios/scenario") scenarios_b = route_b.findall("./scenarios/scenario") assert len(scenarios_a) == len(scenarios_b) == 1 scenario_a, scenario_b = scenarios_a[0], scenarios_b[0] assert scenario_b.attrib.get("type") == scenario_a.attrib.get("type") assert scenario_b.attrib.get("name") == f"{scenario_a.attrib['name']}_B" assert scenario_b.find("route_b_control") is not None assert scenario_b.find("route_b_control").attrib.get("value") == "true" assert scenario_b.find("cooperative_enabled") is not None assert scenario_b.find("cooperative_enabled").attrib.get("value") == "false" for required in ( "trigger_point", "cooperative_trigger_point", "event_trigger_point", "collision_point", "closed_loop_family", ): assert scenario_b.find(required) is not None, ( f"{route_b_id}: missing context field {required!r}" ) assert _canonical(route_b) == _canonical(combined_by_id[route_b_id]), ( f"{route_b_id}: standalone and combined XML differ" ) family_counts[record_b["family"]] += 1 towns[record_b["town"]] += 1 assert dict(family_counts) == expected_family_counts, family_counts assert lock_b["family_counts"] == expected_family_counts summary = { "valid": True, "route_a_count": len(records_a), "route_b_count": len(records_b), "paired_count": len(records_b), "family_counts": dict(family_counts), "town_counts": dict(sorted(towns.items())), "hazard_behaviors_in_route_b": 0, "context_preserving_control_scenarios": len(records_b), "cooperative_hints_in_route_b": 0, "route_geometry_weather_mismatches": 0, "manifest": str(manifest_b_path), "lock": str(lock_b_path), } (dataset_root / "route_b_validation.json").write_text( json.dumps(summary, indent=2) + "\n", encoding="utf-8", ) return summary def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--root", type=Path, default=DEFAULT_DATASET_ROOT, help="Closed dataset root (default: %(default)s)", ) parser.add_argument( "--expected-per-family", type=int, default=None, help="Expected A/B pairs per family; inferred from Route-A manifest when omitted.", ) args = parser.parse_args() summary = validate(args.root.resolve(), args.expected_per_family) print(json.dumps(summary, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())