File size: 7,115 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
#!/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())