#!/usr/bin/env python3 """Validate the frozen CoDrive closed-loop route package.""" from __future__ import annotations import argparse import hashlib import json import math import xml.etree.ElementTree as ET from collections import Counter, defaultdict from pathlib import Path from typing import Optional DEFAULT_ROOT = Path(__file__).resolve().parent EXPECTED_FAMILIES = { "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", } EXPECTED_SCENARIO_TYPES = { "occluded_pedestrian": "ClosedOccludedPedestrian", "vehicle_cut_in": "ClosedLaneCutIn", "static_obstacle_reveal": "ClosedRevealObstacle", "wrong_way_left_turn": "ClosedGhostDriverLeftTurn", "wrong_way_right_turn": "ClosedGhostDriverRightTurn", "right_turn_on_red_yield": "ClosedSignalizedJunctionRightTurnOnRed", } EXPECTED_WEATHER_PROFILES = { "clear_day", "cloudy_day", "wet_day", "light_rain", "dusk", } POINT_TAGS = ( "scenario_arm_point", "cooperative_trigger_point", "event_trigger_point", "collision_point", ) POINT_RECORD_KEYS = { "scenario_arm_point": "arm", "cooperative_trigger_point": "hint", "event_trigger_point": "event", "collision_point": "reference", } def _value(scenario: ET.Element, tag: str) -> str: element = scenario.find(tag) assert element is not None, f"missing <{tag}>" assert "value" in element.attrib, f"<{tag}> has no value" return element.attrib["value"] def _point(element: ET.Element) -> tuple[float, float, float]: return tuple(float(element.attrib.get(key, 0.0)) for key in ("x", "y", "z")) def _route_points(route: ET.Element) -> list[tuple[float, float, float]]: points = [_point(node) for node in route.findall("./waypoints/position")] assert len(points) >= 2, f"{route.attrib.get('id')}: fewer than two waypoints" return points def _cumulative(points: list[tuple[float, float, float]]) -> list[float]: lengths = [0.0] for first, second in zip(points, points[1:]): lengths.append(lengths[-1] + math.hypot(second[0] - first[0], second[1] - first[1])) return lengths def _project( points: list[tuple[float, float, float]], lengths: list[float], target: tuple[float, float, float], ) -> tuple[float, float]: best_distance = float("inf") best_s = 0.0 for index, (first, second) in enumerate(zip(points, points[1:])): delta = (second[0] - first[0], second[1] - first[1]) segment_sq = sum(value * value for value in delta) if segment_sq <= 1e-9: continue ratio = sum( (target[axis] - first[axis]) * delta[axis] for axis in range(2) ) / segment_sq ratio = min(max(ratio, 0.0), 1.0) projection = tuple(first[axis] + ratio * delta[axis] for axis in range(2)) distance = math.hypot(target[0] - projection[0], target[1] - projection[1]) if distance < best_distance: best_distance = distance best_s = lengths[index] + ratio * math.sqrt(segment_sq) return best_s, best_distance 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 _normalized_geometry(route: ET.Element) -> tuple: points = _route_points(route) return tuple( ( round(point[0], 2), round(point[1], 2), round(point[2], 2), ) for point in points ) def _canonical_xml(element: ET.Element) -> bytes: clone = ET.fromstring(ET.tostring(element, encoding="utf-8")) 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 _standalone_path(root: Path, family: str, route_id: str) -> Path: return root / "routes" / EXPECTED_FAMILIES[family] / f"{route_id}.xml" def validate(root: Path, expected_per_family: Optional[int] = None) -> dict: manifest_path = root / "manifest.json" combined_path = root / "coopeval_closed.xml" assert manifest_path.is_file(), manifest_path assert combined_path.is_file(), combined_path manifest = json.loads(manifest_path.read_text(encoding="utf-8")) assert manifest["version"] in { "codrive_closed_v1.0", "lantern_closed_v1.1", }, manifest["version"] if expected_per_family is None: route_count = int(manifest["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) assert manifest["route_count"] == expected_total, manifest["route_count"] assert len(manifest["routes"]) == expected_total, len(manifest["routes"]) combined = ET.parse(combined_path).getroot() routes = combined.findall("route") assert len(routes) == expected_total, len(routes) route_ids = [route.attrib["id"] for route in routes] assert len(route_ids) == len(set(route_ids)), "route IDs are not globally unique" records = {record["route_id"]: record for record in manifest["routes"]} assert set(records) == set(route_ids), "manifest and combined XML disagree" counts: Counter[str] = Counter() towns: dict[str, set[str]] = defaultdict(set) geometries: dict[str, set[tuple]] = defaultdict(set) source_ids: dict[str, set[str]] = defaultdict(set) variants: dict[str, dict[str, list[str]]] = defaultdict( lambda: defaultdict(list) ) route_lengths = [] for route in routes: route_id = route.attrib["id"] record = records[route_id] scenario = route.find("./scenarios/scenario") assert scenario is not None, f"{route_id}: missing scenario" assert len(route.findall("./scenarios/scenario")) == 1, ( f"{route_id}: expected exactly one scenario" ) family = _value(scenario, "closed_loop_family") assert family in EXPECTED_FAMILIES, f"{route_id}: unknown family {family}" assert scenario.attrib.get("type") == EXPECTED_SCENARIO_TYPES[family], ( f"{route_id}: wrong scenario type" ) assert record["family"] == family, f"{route_id}: manifest family mismatch" assert route.attrib.get("source_route_id") == record["source_route_id"] counts[family] += 1 towns[family].add(route.attrib.get("town", "")) source_ids[family].add(route.attrib.get("source_route_id", "")) variants[family]["weather_profile"].append(record["weather_profile"]) for tag in ( "occluder_model", "ped_age", "cut_in_from", "cut_in_model", "deterministic_actor", "obstacle_model", "car_a_dir", "ghost_model", "ghost_speed", "flow_speed", ): element = scenario.find(tag) if element is not None and "value" in element.attrib: variants[family][tag].append(element.attrib["value"]) prompt = _value(scenario, "cooperative_prompt") assert prompt == record["prompt"], f"{route_id}: prompt mismatch" assert "" in prompt, f"{route_id}: prompt has no position token" assert _value(scenario, "event_trigger_policy") == "distance_or_timeout" assert _value(scenario, "cooperative_enabled").lower() == "true" points = _route_points(route) lengths = _cumulative(points) segment_lengths = [ lengths[index + 1] - lengths[index] for index in range(len(lengths) - 1) ] assert min(segment_lengths) > 1e-3, f"{route_id}: duplicate waypoints" # Sparse route anchors are intentional. CARLA's global route planner # connects anchors along the road graph; straight-line densification # through an intersection can snap intermediate points to wrong lanes. max_segment_length = max(segment_lengths) candidate_length_raw = route.attrib.get("candidate_route_length_m") candidate_geometry_hash = route.attrib.get("candidate_geometry_sha256", "") sparse_candidate = ( len(points) == 2 and route.attrib.get("candidate_source") and candidate_length_raw is not None and len(candidate_geometry_hash) == 64 ) if sparse_candidate: candidate_length = float(candidate_length_raw) assert candidate_length <= 160.0, ( f"{route_id}: candidate route is too long ({candidate_length:.2f} m)" ) assert max_segment_length <= candidate_length + 5.0, ( f"{route_id}: endpoint gap {max_segment_length:.2f} m exceeds " f"candidate length {candidate_length:.2f} m" ) route_length = candidate_length else: route_length = lengths[-1] route_lengths.append(route_length) if max_segment_length > 100.0: assert ( sparse_candidate ), f"{route_id}: unverified sparse route anchors" route_s = {} trigger = scenario.find("trigger_point") assert trigger is not None, f"{route_id}: missing trigger_point" if sparse_candidate: assert set(record["route_s"]) >= {"arm", "hint", "event", "reference"} assert set(record["points"]) >= {"arm", "hint", "event", "reference"} for tag in POINT_TAGS: element = scenario.find(tag) assert element is not None, f"{route_id}: missing <{tag}>" record_key = POINT_RECORD_KEYS[tag] expected_point = tuple( float(record["points"][record_key][axis]) for axis in ("x", "y", "z") ) point_error = math.dist(_point(element), expected_point) assert point_error <= 0.02, ( f"{route_id}: <{tag}> differs from frozen candidate " f"by {point_error:.3f} m" ) route_s[tag] = float(record["route_s"][record_key]) activation_policy = scenario.find("scenario_activation_policy") if ( activation_policy is not None and activation_policy.attrib.get("value") == "route_start" ): expected_trigger = points[0] else: expected_trigger = _point(scenario.find("scenario_arm_point")) trigger_error = math.dist(_point(trigger), expected_trigger) assert trigger_error <= 0.02, ( f"{route_id}: trigger point differs from its activation point " f"by {trigger_error:.3f} m" ) else: for tag in POINT_TAGS: element = scenario.find(tag) assert element is not None, f"{route_id}: missing <{tag}>" route_s[tag], off_route = _project(points, lengths, _point(element)) assert off_route <= 0.35, ( f"{route_id}: <{tag}> is {off_route:.2f} m off route" ) trigger_s, trigger_off_route = _project(points, lengths, _point(trigger)) assert trigger_off_route <= 0.35 assert abs(trigger_s - route_s["scenario_arm_point"]) <= 0.1 arm_s = route_s["scenario_arm_point"] hint_s = route_s["cooperative_trigger_point"] event_s = route_s["event_trigger_point"] reference_s = route_s["collision_point"] assert -0.01 <= arm_s <= hint_s <= event_s <= reference_s <= route_length + 0.01, ( f"{route_id}: invalid temporal point order " f"{arm_s:.2f}/{hint_s:.2f}/{event_s:.2f}/{reference_s:.2f}" ) assert abs((hint_s - arm_s) - 4.0) <= 0.12, ( f"{route_id}: arm-to-hint distance is {hint_s - arm_s:.2f} m" ) expected_hint = float(_value(scenario, "hint_lead_distance")) expected_event = float(_value(scenario, "event_lead_distance")) assert abs((reference_s - hint_s) - expected_hint) <= 0.15, ( f"{route_id}: hint lead mismatch" ) assert abs((reference_s - event_s) - expected_event) <= 0.15, ( f"{route_id}: event lead mismatch" ) force_after = float(_value(scenario, "event_force_after_hint_time")) expected_force = 0.0 if family == "right_turn_on_red_yield" else 2.0 assert abs(force_after - expected_force) <= 1e-6, ( f"{route_id}: force timeout {force_after}" ) start_buffer = arm_s recovery = route_length - reference_s assert start_buffer + 0.15 >= float(record["start_before_arm_m"]), ( f"{route_id}: only {start_buffer:.2f} m before arm" ) assert recovery + 0.15 >= float(record["min_recovery_m"]), ( f"{route_id}: only {recovery:.2f} m recovery" ) assert abs(route_length - float(record["route_length_m"])) <= 0.15, ( f"{route_id}: route length={route_length:.2f}, " f"manifest={record['route_length_m']}" ) assert abs(recovery - float(record["recovery_distance_m"])) <= 0.15, ( f"{route_id}: recovery XML={recovery:.2f}, " f"manifest={record['recovery_distance_m']}" ) if family == "vehicle_cut_in": assert float(_value(scenario, "same_lane_time")) == 0.0 assert float(_value(scenario, "closed_cut_in_min_speed_mps")) >= 6.5 assert _value(scenario, "closed_cut_in_direct_steer").lower() == "false" elif family == "static_obstacle_reveal": assert _value(scenario, "preserve_background_traffic").lower() == "true" assert _value(scenario, "keep_obstacle").lower() == "false" standalone = _standalone_path(root, family, route_id) assert standalone.is_file(), standalone standalone_routes = ET.parse(standalone).getroot().findall("route") assert len(standalone_routes) == 1, standalone assert standalone_routes[0].attrib["id"] == route_id, standalone assert _canonical_xml(standalone_routes[0]) == _canonical_xml(route), ( f"{route_id}: standalone XML differs from combined XML" ) geometry = _normalized_geometry(route) assert geometry not in geometries[family], ( f"{route_id}: duplicate normalized geometry within {family}" ) geometries[family].add(geometry) assert counts == Counter( {family: expected_per_family for family in EXPECTED_FAMILIES} ), dict(counts) assert all(len(ids) == expected_per_family for ids in source_ids.values()), { family: len(ids) for family, ids in source_ids.items() } assert manifest["family_counts"] == dict(counts), manifest["family_counts"] assert all( set(values["weather_profile"]) == EXPECTED_WEATHER_PROFILES for values in variants.values() ), "each family must cover all frozen weather profiles" pedestrian = variants["occluded_pedestrian"] assert len(set(pedestrian["occluder_model"])) >= 3 assert set(pedestrian["ped_age"]) == {"adult", "child"} cut_in = variants["vehicle_cut_in"] cut_in_directions = Counter(cut_in["cut_in_from"]) assert set(cut_in_directions) == {"left", "right"} assert min(cut_in_directions.values()) >= max(1, int(expected_per_family * 0.4)) assert len(set(cut_in["cut_in_model"])) >= 5 assert set(cut_in["deterministic_actor"]) == {"true"} reveal = variants["static_obstacle_reveal"] assert len(set(reveal["obstacle_model"])) >= 8 assert set(reveal["car_a_dir"]) == {"left", "right"} for family in ("wrong_way_left_turn", "wrong_way_right_turn"): wrong_way = variants[family] assert len(set(wrong_way["ghost_model"])) >= 5 assert len(set(wrong_way["ghost_speed"])) >= 5 assert len(set(variants["right_turn_on_red_yield"]["flow_speed"])) >= 5 minimum_towns = { "occluded_pedestrian": 5, "vehicle_cut_in": 3, "static_obstacle_reveal": 2, "wrong_way_left_turn": 3, "wrong_way_right_turn": 2, "right_turn_on_red_yield": 3, } assert all( len(towns[family]) >= minimum for family, minimum in minimum_towns.items() ), { family: len(towns[family]) for family in minimum_towns } snapshot_xml = root / "source_snapshot/coopeval_scenes.xml" overrides = Path(manifest["route_geometry_overrides"]) if not overrides.is_file(): overrides = root / "config/route_geometry_overrides.json" assert snapshot_xml.is_file() assert overrides.is_file() assert _sha256(snapshot_xml) == manifest["source_xml_sha256"] assert _sha256(overrides) == manifest["route_geometry_overrides_sha256"] return { "root": str(root), "route_count": len(routes), "family_counts": dict(sorted(counts.items())), "town_counts": {family: len(values) for family, values in sorted(towns.items())}, "route_length_min_m": round(min(route_lengths), 2), "route_length_max_m": round(max(route_lengths), 2), } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) parser.add_argument( "--expected-per-family", type=int, default=None, help="Expected Route-A count per family; inferred from manifest when omitted.", ) args = parser.parse_args() summary = validate(args.root.resolve(), args.expected_per_family) print("validation passed") print(json.dumps(summary, indent=2, sort_keys=True)) return 0 if __name__ == "__main__": raise SystemExit(main())