"""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(), )