LANTERN / closedloop /scripts /sync_route_indexes.py
YongshuoLiu's picture
Add LANTERN metadata and closed-loop benchmark
5a5e5cf verified
Raw History Blame Contribute Delete
7.12 kB
#!/usr/bin/env python3
"""Regenerate Route-A aggregate XML indexes from standalone route files."""
from __future__ import annotations
import argparse
import copy
import json
import math
import xml.etree.ElementTree as ET
from collections import defaultdict
from pathlib import Path
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 _indent(element: ET.Element, level: int = 0) -> None:
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 _single_route(path: Path) -> ET.Element:
routes = ET.parse(path).getroot().findall("route")
if len(routes) != 1:
raise RuntimeError(f"{path}: expected one route, found {len(routes)}")
return routes[0]
def _route_length(route: ET.Element) -> float:
points = [
tuple(float(node.attrib.get(key, 0.0)) for key in ("x", "y", "z"))
for node in route.findall("./waypoints/position")
]
return sum(
math.hypot(second[0] - first[0], second[1] - first[1])
for first, second in zip(points, points[1:])
)
def _route_progress(route: ET.Element, target: tuple[float, float]) -> float:
points = [
tuple(float(node.attrib.get(key, 0.0)) for key in ("x", "y"))
for node in route.findall("./waypoints/position")
]
best_distance = float("inf")
best_progress = 0.0
progress = 0.0
for first, second in zip(points, points[1:]):
dx = second[0] - first[0]
dy = second[1] - first[1]
length = math.hypot(dx, dy)
if length <= 1e-9:
continue
ratio = (
(target[0] - first[0]) * dx
+ (target[1] - first[1]) * dy
) / (length * length)
ratio = min(max(ratio, 0.0), 1.0)
px = first[0] + ratio * dx
py = first[1] + ratio * dy
distance = math.hypot(target[0] - px, target[1] - py)
if distance < best_distance:
best_distance = distance
best_progress = progress + ratio * length
progress += length
return best_progress
def _route_metrics(
route: ET.Element,
record: dict,
reference: ET.Element | None,
) -> tuple[float, float | None]:
candidate_length = route.attrib.get("candidate_route_length_m")
if candidate_length is None:
route_length = _route_length(route)
reference_s = None
if reference is not None:
reference_s = _route_progress(
route,
(
float(reference.attrib["x"]),
float(reference.attrib["y"]),
),
)
return route_length, reference_s
route_length = float(candidate_length)
if not math.isfinite(route_length) or route_length <= 0.0:
raise RuntimeError(
f"{route.attrib.get('id')}: invalid candidate route length "
f"{candidate_length!r}"
)
route_s = record.get("route_s")
if not isinstance(route_s, dict) or "reference" not in route_s:
raise RuntimeError(
f"{route.attrib.get('id')}: sparse candidate route is missing "
"manifest route_s.reference"
)
reference_s = float(route_s["reference"])
if not 0.0 <= reference_s <= route_length:
raise RuntimeError(
f"{route.attrib.get('id')}: reference progress {reference_s:.3f} "
f"is outside candidate route length {route_length:.3f}"
)
return route_length, reference_s
def sync(root: Path) -> None:
manifest_path = root / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
all_routes = []
by_family: dict[str, list[ET.Element]] = defaultdict(list)
by_town: dict[str, list[ET.Element]] = defaultdict(list)
for record in manifest["routes"]:
family_dir = FAMILY_DIRS[record["family"]]
path = root / "routes" / family_dir / f"{record['route_id']}.xml"
route = _single_route(path)
if route.attrib["id"] != record["route_id"]:
raise RuntimeError(f"{path}: route ID differs from manifest")
scenario = route.find("./scenarios/scenario")
reference = scenario.find("collision_point") if scenario is not None else None
route_length, reference_s = _route_metrics(route, record, reference)
record["route_length_m"] = round(route_length, 3)
if reference_s is not None:
recovery_distance = route_length - reference_s
if route.attrib.get("candidate_route_length_m") is not None:
frozen_recovery = record.get("recovery_distance_m")
if frozen_recovery is not None:
if abs(float(frozen_recovery) - recovery_distance) > 0.01:
raise RuntimeError(
f"{record['route_id']}: frozen recovery distance "
f"{float(frozen_recovery):.3f} disagrees with "
f"candidate geometry ({recovery_distance:.3f})"
)
recovery_distance = float(frozen_recovery)
record["recovery_distance_m"] = round(recovery_distance, 3)
all_routes.append(route)
by_family[family_dir].append(route)
by_town[route.attrib["town"]].append(route)
_write_routes(root / "coopeval_closed.xml", all_routes)
for family, routes in sorted(by_family.items()):
_write_routes(root / "routes_by_family" / f"{family}.xml", routes)
for town, routes in sorted(by_town.items()):
_write_routes(root / "routes_by_town" / f"{town}.xml", routes)
manifest_path.write_text(
json.dumps(manifest, indent=2) + "\n",
encoding="utf-8",
)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--root",
type=Path,
default=Path(__file__).resolve().parents[1],
)
args = parser.parse_args()
sync(args.root.resolve())
print(f"Synchronized Route-A indexes under {args.root.resolve()}")
return 0
if __name__ == "__main__":
raise SystemExit(main())