File size: 11,257 Bytes
3e56913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""Offline cache of future actor boxes for plan-consequence supervision.



The raw dataset stores one gzip JSON per frame under ``route/boxes/``; loading

a training sample means probing and parsing ten of them.  This module bakes

each route's physical boxes into three mmap-friendly numpy arrays instead:



- ``boxes.npy``       float32 ``[F, M, 6]`` - world x, y, z, extent_x,

  extent_y, world yaw

- ``box_valid.npy``   bool ``[F, M]``

- ``frame_valid.npy`` bool ``[F]`` - False means the box file was missing or

  malformed (never "empty scene")



Positions are stored in *world* coordinates so a sample anchored at any frame

only needs its own ego matrix to move boxes into the current ego frame; the

camera-shift augmentation is applied afterwards at load time, exactly like the

direct file path in ``BaseDataset._future_box_in_current_frame``.



Route identity reuses the canonical route id scheme of ``future_cache`` so the

cache is host independent.

"""

from __future__ import annotations

import gzip
import json
import os
from collections import OrderedDict
from pathlib import Path
from typing import Dict, Optional, Tuple

import numpy as np

from dataloader.future_cache import canonical_route_id, route_hash

CACHE_SCHEMA_VERSION = 1
PHYSICAL_CLASSES = {"car", "walker", "static", "static_car"}
BOX_FEATURES = 6  # world x, y, z, extent_x, extent_y, world yaw


def _matrix_yaw(matrix: np.ndarray) -> float:
    return float(np.arctan2(matrix[1, 0], matrix[0, 0]))


def _parse_frame_boxes(raw_boxes, ego_matrix: np.ndarray, max_boxes: int) -> np.ndarray:
    """Return ``[N, 6]`` world-frame rows for the nearest physical boxes."""
    if isinstance(raw_boxes, dict):
        raw_boxes = raw_boxes.get("boxes", raw_boxes.get("bounding_boxes"))
    if not isinstance(raw_boxes, list):
        raise ValueError("box payload is not a list")

    ego_yaw = _matrix_yaw(ego_matrix)
    rotation = ego_matrix[:3, :3]
    translation = ego_matrix[:3, 3]
    rows = []
    for box in raw_boxes:
        if (
            not isinstance(box, dict)
            or box.get("class") not in PHYSICAL_CLASSES
            or "position" not in box
            or "extent" not in box
        ):
            continue
        position = np.asarray(box["position"], dtype=np.float64)
        extent = np.asarray(box["extent"], dtype=np.float64)
        if position.size < 2 or extent.size < 2:
            continue
        if not np.isfinite(position[:2]).all() or not np.isfinite(extent[:2]).all():
            continue
        position_3d = np.zeros(3, dtype=np.float64)
        position_3d[: min(3, position.size)] = position[:3]
        world = rotation @ position_3d + translation
        world_yaw = ego_yaw + float(box.get("yaw", 0.0))
        distance = float(np.linalg.norm(position[:2]))
        rows.append((
            distance,
            [
                world[0],
                world[1],
                world[2],
                max(float(extent[0]), 0.0),
                max(float(extent[1]), 0.0),
                world_yaw,
            ],
        ))
    rows.sort(key=lambda item: item[0])
    rows = [row for _, row in rows[:max_boxes]]
    if not rows:
        return np.zeros((0, BOX_FEATURES), dtype=np.float32)
    return np.asarray(rows, dtype=np.float32)


def build_route_cache(

    route_dir: str | os.PathLike,

    cache_root: str | os.PathLike,

    *,

    max_boxes: int = 64,

    force: bool = False,

) -> Tuple[str, str]:
    """Bake one route's boxes into the cache.  Returns (route_hash, status)."""
    route_dir = Path(route_dir)
    cache_root = Path(cache_root)
    # A suffixed filename makes canonical_route_id strip both the file and the
    # measurements/ component, matching the loader's boxes/NNNN.json.gz key.
    route_id = canonical_route_id(route_dir / "measurements" / "0000.json.gz")
    key = route_hash(route_id)
    out_dir = cache_root / key
    if not force and (out_dir / "metadata.json").is_file():
        return key, "skipped"

    boxes_dir = route_dir / "boxes"
    measurements_dir = route_dir / "measurements"
    frame_files = sorted(boxes_dir.glob("[0-9]" * 4 + ".json.gz"))
    if not frame_files:
        return key, "no_boxes"

    frames = [int(path.name.split(".")[0]) for path in frame_files]
    count = len(frames)
    boxes = np.zeros((count, max_boxes, BOX_FEATURES), dtype=np.float32)
    box_valid = np.zeros((count, max_boxes), dtype=np.bool_)
    frame_valid = np.zeros(count, dtype=np.bool_)

    for slot, (frame, box_path) in enumerate(zip(frames, frame_files)):
        measurement_path = measurements_dir / f"{frame:04}.json.gz"
        try:
            with gzip.open(measurement_path, "rt") as handle:
                measurement = json.load(handle)
            ego_matrix = np.asarray(measurement["ego_matrix"], dtype=np.float64)
            if ego_matrix.shape != (4, 4):
                continue
            with gzip.open(box_path, "rt") as handle:
                raw_boxes = json.load(handle)
            rows = _parse_frame_boxes(raw_boxes, ego_matrix, max_boxes)
        except (OSError, KeyError, ValueError, json.JSONDecodeError):
            continue
        frame_valid[slot] = True
        if len(rows):
            boxes[slot, : len(rows)] = rows
            box_valid[slot, : len(rows)] = True

    out_dir.mkdir(parents=True, exist_ok=True)
    tmp_suffix = f".{os.getpid()}.tmp"
    for name, array in (
        ("boxes.npy", boxes),
        ("box_valid.npy", box_valid),
        ("frame_valid.npy", frame_valid),
        ("frame_index.npy", np.asarray(frames, dtype=np.int32)),
    ):
        tmp = out_dir / (name + tmp_suffix)
        # np.save appends ".npy" to plain paths; write through the handle to
        # keep the temporary name intact for the atomic rename.
        with tmp.open("wb") as handle:
            np.save(handle, array, allow_pickle=False)
        os.replace(tmp, out_dir / name)
    metadata = {
        "schema_version": CACHE_SCHEMA_VERSION,
        "route_id": route_id,
        "route_hash": key,
        "count": count,
        "max_boxes": int(max_boxes),
        "box_features": BOX_FEATURES,
        "valid_frames": int(frame_valid.sum()),
    }
    tmp = out_dir / ("metadata.json" + tmp_suffix)
    tmp.write_text(json.dumps(metadata, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, out_dir / "metadata.json")
    return key, "built"


def write_manifest(cache_root: str | os.PathLike) -> dict:
    """Scan route dirs and (re)write the root manifest."""
    cache_root = Path(cache_root)
    routes: Dict[str, dict] = {}
    max_boxes = None
    for metadata_path in sorted(cache_root.glob("*/metadata.json")):
        metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
        if metadata.get("schema_version") != CACHE_SCHEMA_VERSION:
            continue
        routes[metadata["route_hash"]] = {
            "route_id": metadata["route_id"],
            "count": metadata["count"],
            "valid_frames": metadata["valid_frames"],
        }
        if max_boxes is None:
            max_boxes = int(metadata["max_boxes"])
        elif max_boxes != int(metadata["max_boxes"]):
            raise RuntimeError("mixed max_boxes values in cache; rebuild with --force")
    manifest = {
        "schema_version": CACHE_SCHEMA_VERSION,
        "max_boxes": max_boxes,
        "box_features": BOX_FEATURES,
        "route_count": len(routes),
        "routes": routes,
    }
    tmp = cache_root / f".manifest.json.{os.getpid()}.tmp"
    tmp.write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8")
    os.replace(tmp, cache_root / "manifest.json")
    return manifest


class ConsequenceBoxCache:
    """Per-process LRU of route-level read-only numpy memory maps."""

    def __init__(self, root: str | os.PathLike, *, lru_size: int = 8) -> None:
        self.root = Path(root)
        self.lru_size = int(lru_size)
        if self.lru_size <= 0:
            raise ValueError("box cache lru_size must be positive")
        manifest_path = self.root / "manifest.json"
        if not manifest_path.is_file():
            raise FileNotFoundError(
                f"consequence box cache manifest is missing: {manifest_path}"
            )
        with manifest_path.open("r", encoding="utf-8") as handle:
            manifest = json.load(handle)
        if manifest.get("schema_version") != CACHE_SCHEMA_VERSION:
            raise RuntimeError("consequence box cache schema version mismatch")
        if manifest.get("box_features") != BOX_FEATURES:
            raise RuntimeError("consequence box cache feature layout mismatch")
        self.routes: Dict[str, dict] = manifest["routes"]
        self._pid = os.getpid()
        self._handles: OrderedDict[
            str, Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]
        ] = OrderedDict()

    def _reset_after_fork(self) -> None:
        if self._pid != os.getpid():
            self._handles = OrderedDict()
            self._pid = os.getpid()

    def _open_route(self, key: str):
        self._reset_after_fork()
        if key in self._handles:
            self._handles.move_to_end(key)
            return self._handles[key]
        if key not in self.routes:
            return None
        route_dir = self.root / key
        try:
            boxes = np.load(route_dir / "boxes.npy", mmap_mode="r", allow_pickle=False)
            box_valid = np.load(route_dir / "box_valid.npy", mmap_mode="r", allow_pickle=False)
            frame_valid = np.load(route_dir / "frame_valid.npy", mmap_mode="r", allow_pickle=False)
            frames = np.load(route_dir / "frame_index.npy", mmap_mode="r", allow_pickle=False)
        except OSError as error:
            raise RuntimeError(f"consequence box cache route unreadable: {key}") from error
        if boxes.ndim != 3 or boxes.shape[2] != BOX_FEATURES:
            raise RuntimeError(f"consequence box cache schema mismatch: {key}")
        self._handles[key] = (boxes, box_valid, frame_valid, frames)
        while len(self._handles) > self.lru_size:
            self._handles.popitem(last=False)
        return self._handles[key]

    def get(self, key: str, frame_index: int) -> Optional[Tuple[np.ndarray, np.ndarray]]:
        """Return (world boxes ``[M, 6]``, validity ``[M]``) or None.



        None means the route/frame is absent from the cache or the raw box

        file was missing/malformed, i.e. geometry must stay masked.

        """
        arrays = self._open_route(str(key))
        if arrays is None:
            return None
        boxes, box_valid, frame_valid, frames = arrays
        position = int(np.searchsorted(frames, int(frame_index)))
        if position >= len(frames) or int(frames[position]) != int(frame_index):
            return None
        if not bool(frame_valid[position]):
            return None
        return (
            np.asarray(boxes[position], dtype=np.float32).copy(),
            np.asarray(box_valid[position]).copy(),
        )