LANTERN / closedloop /scripts /build_route_b.py
YongshuoLiu's picture
Add LANTERN metadata and closed-loop benchmark
5a5e5cf verified
Raw History Blame Contribute Delete
11.9 kB
#!/usr/bin/env python3
"""Build paired CoDrive Route-B controls from the frozen Route-A suite."""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
import shutil
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from pathlib import Path
from typing import Optional
PROJECT_ROOT = Path(__file__).resolve().parents[2]
DEFAULT_DATASET_ROOT = PROJECT_ROOT / "closed_dataset"
FAMILY_DIRS = {
"occluded_pedestrian": "occluded_pedestrian",
"vehicle_cut_in": "lane_cut_in",
"static_obstacle_reveal": "reveal_obstacle",
"wrong_way_left_turn": "ghost_driver_left_turn",
"wrong_way_right_turn": "ghost_driver_right_turn",
"right_turn_on_red_yield": "right_turn_on_red",
}
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 _indent(element: ET.Element, level: int = 0) -> None:
"""Python-3.8-compatible XML indentation."""
prefix = "\n" + level * " "
child_prefix = "\n" + (level + 1) * " "
children = list(element)
if children:
if not element.text or not element.text.strip():
element.text = child_prefix
for child in children:
_indent(child, level + 1)
if not child.tail or not child.tail.strip():
child.tail = child_prefix
children[-1].tail = prefix
elif level and (not element.tail or not element.tail.strip()):
element.tail = prefix
def _write_routes(path: Path, routes: list[ET.Element]) -> None:
root = ET.Element("routes")
for route in routes:
root.append(copy.deepcopy(route))
_indent(root)
path.parent.mkdir(parents=True, exist_ok=True)
ET.ElementTree(root).write(path, encoding="utf-8", xml_declaration=True)
def _find_route_a(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 exactly one Route-A XML for {route_id}, found {len(matches)}"
)
return matches[0]
def _parse_single_route(path: Path) -> ET.Element:
root = ET.parse(path).getroot()
routes = root.findall("route")
if len(routes) != 1:
raise RuntimeError(f"{path}: expected one <route>, found {len(routes)}")
return routes[0]
def _semantic_signature(element: ET.Element) -> tuple:
children = sorted(
(_semantic_signature(child) for child in element),
key=repr,
)
return (
element.tag,
tuple(sorted(element.attrib.items())),
(element.text or "").strip(),
tuple(children),
)
def _make_route_b(route_a: ET.Element, route_a_id: str) -> ET.Element:
route_b = copy.deepcopy(route_a)
route_b.set("id", f"{route_a_id}_B")
route_b.set("benchmark_variant", "B")
route_b.set("paired_route_a_id", route_a_id)
scenarios = route_b.findall("./scenarios/scenario")
if len(scenarios) != 1:
raise RuntimeError(
f"{route_a_id}: expected one scenario, found {len(scenarios)}"
)
scenario = scenarios[0]
scenario.set("name", f"{scenario.attrib['name']}_B")
def set_value(name: str, value: str) -> None:
node = scenario.find(name)
if node is None:
node = ET.SubElement(scenario, name)
node.attrib.clear()
node.set("value", value)
# Route B preserves the physical context and all route-relative points.
# The corresponding Closed* scenario class uses this flag to retain
# non-hazard actors while suppressing only the hazardous maneuver.
set_value("route_b_control", "true")
set_value("cooperative_enabled", "false")
set_value("event_trigger_policy", "disabled_route_b_control")
return route_b
def build(
dataset_root: Path,
expected_per_family: Optional[int] = None,
preserve_existing: bool = False,
) -> dict:
manifest_path = dataset_root / "manifest.json"
lock_a_path = dataset_root / "benchmark_v1.lock.json"
manifest_a = json.loads(manifest_path.read_text(encoding="utf-8"))
records_a = manifest_a.get("routes", [])
family_counts = Counter(record.get("family") for record in records_a)
expected_families = set(FAMILY_DIRS)
if set(family_counts) != expected_families:
raise RuntimeError(
"Route-A manifest families differ from the benchmark contract: "
f"{dict(family_counts)}"
)
if expected_per_family is None:
distinct_counts = set(family_counts.values())
if len(distinct_counts) != 1:
raise RuntimeError(
"cannot infer a common per-family count from Route-A manifest: "
f"{dict(family_counts)}"
)
expected_per_family = distinct_counts.pop()
expected_counts = Counter(
{family: expected_per_family for family in expected_families}
)
if family_counts != expected_counts:
raise RuntimeError(
f"expected {expected_per_family} Route-A records per family, "
f"found {dict(family_counts)}"
)
output_paths = [
dataset_root / "routes_B_by_family",
dataset_root / "routes_B_by_town",
]
if not preserve_existing:
output_paths.insert(0, dataset_root / "routes_B")
for path in output_paths:
if path.exists():
shutil.rmtree(path)
all_routes_b: list[ET.Element] = []
routes_by_family: dict[str, list[ET.Element]] = defaultdict(list)
routes_by_town: dict[str, list[ET.Element]] = defaultdict(list)
records_b = []
for record_a in records_a:
route_a_id = record_a["route_id"]
family = record_a["family"]
if family not in FAMILY_DIRS:
raise RuntimeError(f"{route_a_id}: unsupported family {family!r}")
route_a_path = _find_route_a(dataset_root, route_a_id)
route_a = _parse_single_route(route_a_path)
scenarios_a = route_a.findall("./scenarios/scenario")
if len(scenarios_a) != 1:
raise RuntimeError(
f"{route_a_path}: expected one Route-A scenario, found {len(scenarios_a)}"
)
expected_route_b = _make_route_b(route_a, route_a_id)
route_b_id = expected_route_b.attrib["id"]
family_dir = FAMILY_DIRS[family]
route_b_path = dataset_root / "routes_B" / family_dir / f"{route_b_id}.xml"
if preserve_existing and route_b_path.is_file():
route_b = _parse_single_route(route_b_path)
if _semantic_signature(route_b) != _semantic_signature(expected_route_b):
raise RuntimeError(
f"{route_b_path}: existing Route-B XML is not semantically "
"equivalent to the current Route-A control"
)
else:
route_b = expected_route_b
_write_routes(route_b_path, [route_b])
all_routes_b.append(route_b)
routes_by_family[family_dir].append(route_b)
routes_by_town[route_b.attrib["town"]].append(route_b)
records_b.append(
{
"route_a_id": route_a_id,
"route_b_id": route_b_id,
"family": family,
"family_dir": family_dir,
"town": route_b.attrib["town"],
"source_route_id": route_b.attrib.get("source_route_id"),
"weather_profile": record_a["weather_profile"],
"route_length_m": record_a["route_length_m"],
"route_a_xml": str(route_a_path.relative_to(dataset_root)),
"route_b_xml": str(route_b_path.relative_to(dataset_root)),
"route_a_sha256": _sha256(route_a_path),
"route_b_sha256": _sha256(route_b_path),
"physical_hazard": False,
"physical_context": True,
"cooperative_hint": False,
}
)
combined_path = dataset_root / "coopeval_closed_B.xml"
_write_routes(combined_path, all_routes_b)
for family_dir, routes in sorted(routes_by_family.items()):
_write_routes(
dataset_root / "routes_B_by_family" / f"{family_dir}.xml",
routes,
)
for town, routes in sorted(routes_by_town.items()):
_write_routes(dataset_root / "routes_B_by_town" / f"{town}.xml", routes)
manifest_b = {
"benchmark": "CoDrive",
"version": "codrive_closed_route_b_v1.1",
"variant": "B",
"definition": (
"Paired control routes preserving Route-A town, weather, waypoints, "
"navigation objective, background traffic, and non-hazard context "
"actors while disabling only the hazardous behavior and cooperative "
"hint."
),
"route_count": len(records_b),
"family_counts": dict(Counter(record["family"] for record in records_b)),
"source_route_a_manifest": str(manifest_path.relative_to(dataset_root)),
"source_route_a_manifest_sha256": _sha256(manifest_path),
"routes": records_b,
}
manifest_b_path = dataset_root / "route_b_manifest.json"
manifest_b_path.write_text(
json.dumps(manifest_b, indent=2) + "\n",
encoding="utf-8",
)
validator_path = Path(__file__).with_name("validate_route_b.py")
scenario_wrapper_path = (
dataset_root / "scenarios" / "closed_coopeval_scenarios.py"
)
lock_b = {
"benchmark": "CoDrive",
"version": "1.1-route-b-context-preserving",
"variant": "B",
"route_count": len(records_b),
"family_counts": manifest_b["family_counts"],
"route_a_manifest_sha256": _sha256(manifest_path),
"route_a_lock_sha256": _sha256(lock_a_path) if lock_a_path.is_file() else None,
"route_b_manifest_sha256": _sha256(manifest_b_path),
"combined_route_b_sha256": _sha256(combined_path),
"builder_sha256": _sha256(Path(__file__)),
"validator_sha256": _sha256(validator_path),
"scenario_wrapper_sha256": _sha256(scenario_wrapper_path),
"routes": [
{
"route_a_id": record["route_a_id"],
"route_b_id": record["route_b_id"],
"family": record["family"],
"town": record["town"],
"route_a_sha256": record["route_a_sha256"],
"route_b_sha256": record["route_b_sha256"],
}
for record in records_b
],
}
(dataset_root / "route_b.lock.json").write_text(
json.dumps(lock_b, indent=2) + "\n",
encoding="utf-8",
)
return manifest_b
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 Route-A count per family; inferred from manifest when omitted.",
)
parser.add_argument(
"--preserve-existing",
action="store_true",
help=(
"Keep semantically valid standalone Route-B XML files byte-identical; "
"create only missing files and rebuild aggregate metadata."
),
)
args = parser.parse_args()
manifest = build(
args.root.resolve(),
args.expected_per_family,
preserve_existing=args.preserve_existing,
)
print(
f"Built {manifest['route_count']} paired Route-B controls under "
f"{args.root.resolve() / 'routes_B'}"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())