FromSim2Real / gpudrive-main /data_utils /nuscenes_adapter.py
lzhts1's picture
Upload 385 files
9897e20 verified
Raw
History Blame Contribute Delete
25.3 kB
"""NuScenes to GPUDrive JSON conversion utilities.
The adapter keeps NuScenes-specific logic at the dataset boundary and emits the
same JSON schema consumed by GPUDrive's existing C++ map reader.
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
import json
import logging
import math
from pathlib import Path
from typing import Any, Iterable, Optional
import numpy as np
try:
from .datatypes import MapElementIds
except ImportError: # pragma: no cover - supports running as a script.
from datatypes import MapElementIds
ERR_VAL = -1e4
@dataclass
class NuScenesAdapterConfig:
"""Configuration for converting NuScenes scenes into GPUDrive scenarios."""
target_hz: float = 10.0
num_steps: int = 91
max_annotation_gap_sec: float = 1.1
min_valid_steps: int = 2
require_start_valid: bool = True
require_full_window: bool = True
include_ego: bool = True
ego_width: float = 2.0
ego_length: float = 4.8
ego_height: float = 1.8
include_map: bool = True
fail_on_missing_map: bool = False
map_radius_m: float = 120.0
map_discretization_m: float = 1.0
max_road_elements: int = 900
max_geometry_points: int = 512
@property
def dt(self) -> float:
return 1.0 / self.target_hz
@property
def horizon_sec(self) -> float:
return (self.num_steps - 1) * self.dt
def load_nuscenes(version: str, dataroot: str, verbose: bool = True):
"""Load the NuScenes SDK object with a clear optional-dependency error."""
try:
from nuscenes.nuscenes import NuScenes
except ImportError as exc: # pragma: no cover - depends on local install.
raise ImportError(
"NuScenes conversion requires the optional NuScenes devkit. "
"Install it with `pip install nuscenes-devkit`."
) from exc
return NuScenes(version=version, dataroot=dataroot, verbose=verbose)
def wrap_yaw(yaw: float | np.ndarray) -> float | np.ndarray:
"""Wrap yaw angles to [-pi, pi]."""
return (yaw + np.pi) % (2 * np.pi) - np.pi
def yaw_from_quaternion(rotation: Iterable[float]) -> float:
"""Return z-yaw from a NuScenes quaternion stored as [w, x, y, z]."""
w, x, y, z = rotation
siny_cosp = 2.0 * (w * z + x * y)
cosy_cosp = 1.0 - 2.0 * (y * y + z * z)
return wrap_yaw(math.atan2(siny_cosp, cosy_cosp))
def category_to_gpudrive(category_name: str) -> Optional[str]:
"""Map NuScenes categories to GPUDrive object types."""
if category_name.startswith("pedestrian."):
return "pedestrian"
if category_name in {"vehicle.bicycle", "vehicle.motorcycle"}:
return "cyclist"
if category_name.startswith("vehicle."):
return "vehicle"
return None
def _dedupe_states_by_time(states: list[dict[str, Any]]) -> list[dict[str, Any]]:
deduped: dict[float, dict[str, Any]] = {}
for state in states:
deduped[float(state["time_sec"])] = state
return [deduped[t] for t in sorted(deduped)]
def _empty_series(num_steps: int) -> tuple[list[dict[str, float]], list[float], list[dict[str, float]], list[bool]]:
positions = [{"x": ERR_VAL, "y": ERR_VAL, "z": ERR_VAL} for _ in range(num_steps)]
headings = [ERR_VAL for _ in range(num_steps)]
velocities = [{"x": ERR_VAL, "y": ERR_VAL} for _ in range(num_steps)]
valid = [False for _ in range(num_steps)]
return positions, headings, velocities, valid
def _interpolate_value(
raw_t: np.ndarray,
raw_values: np.ndarray,
target_t: float,
right_idx: int,
) -> Optional[np.ndarray]:
if right_idx < len(raw_t) and abs(raw_t[right_idx] - target_t) <= 1e-6:
return raw_values[right_idx]
if right_idx == 0 or right_idx >= len(raw_t):
return None
left_idx = right_idx - 1
denom = raw_t[right_idx] - raw_t[left_idx]
if denom <= 0:
return None
alpha = (target_t - raw_t[left_idx]) / denom
return raw_values[left_idx] * (1.0 - alpha) + raw_values[right_idx] * alpha
def _is_interpolation_gap_valid(
raw_t: np.ndarray,
target_t: float,
right_idx: int,
max_gap_sec: float,
) -> bool:
if right_idx < len(raw_t) and abs(raw_t[right_idx] - target_t) <= 1e-6:
return True
if right_idx == 0 or right_idx >= len(raw_t):
return False
return raw_t[right_idx] - raw_t[right_idx - 1] <= max_gap_sec
def _compute_velocities(
xy: np.ndarray,
valid: np.ndarray,
dt: float,
) -> list[dict[str, float]]:
velocities = [{"x": ERR_VAL, "y": ERR_VAL} for _ in range(len(valid))]
valid_indices = np.flatnonzero(valid)
for idx in valid_indices:
prev_valid = idx > 0 and valid[idx - 1]
next_valid = idx + 1 < len(valid) and valid[idx + 1]
if prev_valid and next_valid:
vel = (xy[idx + 1] - xy[idx - 1]) / (2.0 * dt)
elif next_valid:
vel = (xy[idx + 1] - xy[idx]) / dt
elif prev_valid:
vel = (xy[idx] - xy[idx - 1]) / dt
else:
vel = np.array([0.0, 0.0])
velocities[idx] = {"x": float(vel[0]), "y": float(vel[1])}
return velocities
def interpolate_track(
states: list[dict[str, Any]],
target_times_sec: np.ndarray,
config: NuScenesAdapterConfig,
) -> Optional[dict[str, Any]]:
"""Interpolate one NuScenes track to GPUDrive's fixed time grid."""
states = _dedupe_states_by_time(states)
num_steps = len(target_times_sec)
if not states:
return None
raw_t = np.array([float(s["time_sec"]) for s in states], dtype=np.float64)
raw_xyz = np.array([s["translation"] for s in states], dtype=np.float64)
raw_yaw = np.unwrap(np.array([s["yaw"] for s in states], dtype=np.float64))
positions, headings, _, valid_list = _empty_series(num_steps)
interp_xy = np.full((num_steps, 2), ERR_VAL, dtype=np.float64)
valid = np.zeros(num_steps, dtype=bool)
for out_idx, target_t in enumerate(target_times_sec):
right_idx = int(np.searchsorted(raw_t, target_t, side="left"))
if not _is_interpolation_gap_valid(
raw_t, target_t, right_idx, config.max_annotation_gap_sec
):
continue
xyz = _interpolate_value(raw_t, raw_xyz, target_t, right_idx)
yaw = _interpolate_value(raw_t, raw_yaw, target_t, right_idx)
if xyz is None or yaw is None:
continue
positions[out_idx] = {
"x": float(xyz[0]),
"y": float(xyz[1]),
"z": float(xyz[2]),
}
headings[out_idx] = float(wrap_yaw(float(yaw)))
interp_xy[out_idx] = xyz[:2]
valid[out_idx] = True
if config.require_start_valid and not valid[0]:
return None
if int(valid.sum()) < config.min_valid_steps:
return None
valid_indices = np.flatnonzero(valid)
last_valid_idx = int(valid_indices[-1])
velocities = _compute_velocities(interp_xy, valid, config.dt)
valid_list = [bool(v) for v in valid]
size = np.median(np.array([s["size"] for s in states], dtype=np.float64), axis=0)
return {
"position": positions,
"width": float(size[0]),
"length": float(size[1]),
"height": float(size[2]),
"heading": headings,
"velocity": velocities,
"valid": valid_list,
"goalPosition": positions[last_valid_idx],
}
def _sample_time_sec(sample: dict[str, Any]) -> float:
return float(sample["timestamp"]) / 1e6
def collect_scene_samples(nusc: Any, scene: dict[str, Any]) -> list[dict[str, Any]]:
"""Collect all keyframe samples for one NuScenes scene."""
samples = []
sample_token = scene["first_sample_token"]
while sample_token:
sample = nusc.get("sample", sample_token)
samples.append(sample)
sample_token = sample["next"]
return samples
def collect_annotation_tracks(
nusc: Any,
samples: list[dict[str, Any]],
) -> dict[str, list[dict[str, Any]]]:
"""Collect NuScenes sample annotations into per-instance tracks."""
tracks: dict[str, list[dict[str, Any]]] = defaultdict(list)
for sample in samples:
time_sec = _sample_time_sec(sample)
for ann_token in sample["anns"]:
ann = nusc.get("sample_annotation", ann_token)
gpudrive_type = category_to_gpudrive(ann["category_name"])
if gpudrive_type is None:
continue
tracks[ann["instance_token"]].append(
{
"time_sec": time_sec,
"translation": ann["translation"],
"yaw": yaw_from_quaternion(ann["rotation"]),
"size": ann["size"],
"category_name": ann["category_name"],
"gpudrive_type": gpudrive_type,
}
)
return tracks
def collect_ego_track(
nusc: Any,
samples: list[dict[str, Any]],
config: NuScenesAdapterConfig,
) -> list[dict[str, Any]]:
"""Collect ego poses as a synthetic vehicle track."""
ego_track = []
ego_size = [config.ego_width, config.ego_length, config.ego_height]
for sample in samples:
lidar_token = sample["data"].get("LIDAR_TOP")
if lidar_token is None:
continue
sample_data = nusc.get("sample_data", lidar_token)
pose = nusc.get("ego_pose", sample_data["ego_pose_token"])
ego_track.append(
{
"time_sec": _sample_time_sec(sample),
"translation": pose["translation"],
"yaw": yaw_from_quaternion(pose["rotation"]),
"size": ego_size,
"category_name": "vehicle.ego",
"gpudrive_type": "vehicle",
}
)
return ego_track
def iter_window_starts(
samples: list[dict[str, Any]],
config: NuScenesAdapterConfig,
window_stride_sec: Optional[float] = None,
) -> list[float]:
"""Return conversion window starts in absolute NuScenes seconds."""
if not samples:
return []
first_time = _sample_time_sec(samples[0])
last_time = _sample_time_sec(samples[-1])
latest_start = last_time - config.horizon_sec
if config.require_full_window and latest_start < first_time:
return []
if window_stride_sec is None or window_stride_sec <= 0:
return [first_time]
latest_allowed_start = latest_start if config.require_full_window else last_time
starts = []
cur = first_time
while cur <= latest_allowed_start + 1e-6:
starts.append(cur)
cur += window_stride_sec
return starts
def _geometry_point(x: float, y: float, z: float = 0.0) -> dict[str, float]:
return {"x": float(x), "y": float(y), "z": float(z)}
def _dedupe_points(points: list[dict[str, float]]) -> list[dict[str, float]]:
if not points:
return points
deduped = [points[0]]
for point in points[1:]:
prev = deduped[-1]
if abs(point["x"] - prev["x"]) > 1e-6 or abs(point["y"] - prev["y"]) > 1e-6:
deduped.append(point)
if len(deduped) > 2:
first = deduped[0]
last = deduped[-1]
if abs(first["x"] - last["x"]) <= 1e-6 and abs(first["y"] - last["y"]) <= 1e-6:
deduped.pop()
return deduped
def _thin_points(
points: list[dict[str, float]],
max_points: int,
) -> list[dict[str, float]]:
if len(points) <= max_points:
return points
keep = np.linspace(0, len(points) - 1, max_points).round().astype(int)
return [points[int(i)] for i in keep]
def _coords_to_geometry(
coords: Iterable[Any],
max_points: int,
) -> list[dict[str, float]]:
points = []
for coord in coords:
x = coord[0]
y = coord[1]
points.append(_geometry_point(x, y, 0.0))
return _thin_points(_dedupe_points(points), max_points)
def _add_road(
roads: list[dict[str, Any]],
geometry: list[dict[str, float]],
road_type: str,
map_element_id: int,
road_id: int,
config: NuScenesAdapterConfig,
) -> int:
if len(roads) >= config.max_road_elements:
return road_id
min_points = 4 if road_type in {"crosswalk", "speed_bump"} else 2
if road_type == "stop_sign":
min_points = 1
if len(geometry) < min_points:
return road_id
roads.append(
{
"geometry": geometry,
"type": road_type,
"map_element_id": int(map_element_id),
"id": road_id,
}
)
return road_id + 1
def _get_records_in_radius(
nusc_map: Any,
center_xy: tuple[float, float],
radius_m: float,
layer_names: list[str],
) -> dict[str, list[str]]:
try:
return nusc_map.get_records_in_radius(
center_xy[0],
center_xy[1],
radius_m,
layer_names,
mode="intersect",
)
except TypeError: # pragma: no cover - SDK-version compatibility.
return nusc_map.get_records_in_radius(
center_xy[0],
center_xy[1],
radius_m,
layer_names,
)
def _discretize_lanes(
nusc_map: Any,
lane_tokens: list[str],
discretization_m: float,
) -> dict[str, Any]:
try:
return nusc_map.discretize_lanes(
lane_tokens, resolution_meters=discretization_m
)
except TypeError: # pragma: no cover - SDK-version compatibility.
return nusc_map.discretize_lanes(
lane_tokens, discretization_meters=discretization_m
)
def _extract_polygon_exterior(nusc_map: Any, polygon_token: str) -> list[Any]:
polygon = nusc_map.extract_polygon(polygon_token)
return list(polygon.exterior.coords)
def _extract_line_coords(nusc_map: Any, line_token: str) -> list[Any]:
line = nusc_map.extract_line(line_token)
return list(line.coords)
def _road_center_from_objects(objects: list[dict[str, Any]]) -> tuple[float, float]:
starts = []
for obj in objects:
for idx, valid in enumerate(obj["valid"]):
if valid:
pos = obj["position"][idx]
starts.append((pos["x"], pos["y"]))
break
if not starts:
return 0.0, 0.0
arr = np.array(starts, dtype=np.float64)
return float(arr[:, 0].mean()), float(arr[:, 1].mean())
def load_nuscenes_map(dataroot: str, map_name: str):
"""Load a NuScenes map object."""
try:
from nuscenes.map_expansion.map_api import NuScenesMap
except ImportError as exc: # pragma: no cover - depends on local install.
raise ImportError(
"NuScenes map conversion requires `nuscenes-devkit`."
) from exc
return NuScenesMap(dataroot=dataroot, map_name=map_name)
def get_scene_map_name(nusc: Any, scene: dict[str, Any]) -> str:
log = nusc.get("log", scene["log_token"])
return log["location"]
def extract_roads(
nusc_map: Any,
center_xy: tuple[float, float],
config: NuScenesAdapterConfig,
) -> list[dict[str, Any]]:
"""Extract nearby NuScenes map layers as GPUDrive road objects."""
layer_names = [
"lane",
"lane_connector",
"road_divider",
"lane_divider",
"drivable_area",
"ped_crossing",
"stop_line",
]
records = _get_records_in_radius(
nusc_map, center_xy, config.map_radius_m, layer_names
)
roads: list[dict[str, Any]] = []
road_id = 0
lane_tokens = records.get("lane", []) + records.get("lane_connector", [])
if lane_tokens:
lane_paths = _discretize_lanes(
nusc_map, lane_tokens, config.map_discretization_m
)
for points in lane_paths.values():
geometry = _coords_to_geometry(points, config.max_geometry_points)
road_id = _add_road(
roads,
geometry,
"lane",
MapElementIds.LANE_SURFACE_STREET,
road_id,
config,
)
for layer_name, map_id in [
("road_divider", MapElementIds.ROAD_LINE_SOLID_SINGLE_WHITE),
("lane_divider", MapElementIds.ROAD_LINE_BROKEN_SINGLE_WHITE),
("stop_line", MapElementIds.ROAD_LINE_UNKNOWN),
]:
for token in records.get(layer_name, []):
record = nusc_map.get(layer_name, token)
line_token = record.get("line_token")
if not line_token:
continue
geometry = _coords_to_geometry(
_extract_line_coords(nusc_map, line_token),
config.max_geometry_points,
)
road_id = _add_road(
roads,
geometry,
"road_line",
map_id,
road_id,
config,
)
for token in records.get("drivable_area", []):
record = nusc_map.get("drivable_area", token)
for polygon_token in record.get("polygon_tokens", []):
geometry = _coords_to_geometry(
_extract_polygon_exterior(nusc_map, polygon_token),
config.max_geometry_points,
)
road_id = _add_road(
roads,
geometry,
"road_edge",
MapElementIds.ROAD_EDGE_BOUNDARY,
road_id,
config,
)
for token in records.get("ped_crossing", []):
record = nusc_map.get("ped_crossing", token)
polygon_token = record.get("polygon_token")
if not polygon_token:
continue
geometry = _coords_to_geometry(
_extract_polygon_exterior(nusc_map, polygon_token),
config.max_geometry_points,
)
road_id = _add_road(
roads,
geometry,
"crosswalk",
MapElementIds.CROSSWALK,
road_id,
config,
)
return roads
def _make_gpudrive_object(
obj_id: int,
gpudrive_type: str,
states: list[dict[str, Any]],
target_times_sec: np.ndarray,
config: NuScenesAdapterConfig,
mark_as_expert: bool = False,
) -> Optional[dict[str, Any]]:
obj = interpolate_track(states, target_times_sec, config)
if obj is None:
return None
obj["type"] = gpudrive_type
obj["id"] = obj_id
obj["mark_as_expert"] = mark_as_expert
return obj
def scene_to_gpudrive_scenarios(
nusc: Any,
scene: dict[str, Any],
dataroot: str,
config: NuScenesAdapterConfig,
file_prefix: str = "tfrecord-nuscenes",
window_stride_sec: Optional[float] = None,
map_cache: Optional[dict[str, Any]] = None,
) -> list[dict[str, Any]]:
"""Convert a NuScenes scene into one or more GPUDrive scenario dicts."""
samples = collect_scene_samples(nusc, scene)
window_starts = iter_window_starts(samples, config, window_stride_sec)
if not window_starts:
return []
annotation_tracks = collect_annotation_tracks(nusc, samples)
ego_track = collect_ego_track(nusc, samples, config) if config.include_ego else []
map_cache = map_cache if map_cache is not None else {}
scenarios = []
for window_idx, window_start in enumerate(window_starts):
target_times = window_start + np.arange(config.num_steps, dtype=np.float64) * config.dt
objects = []
next_id = 0
if config.include_ego:
ego_obj = _make_gpudrive_object(
obj_id=next_id,
gpudrive_type="vehicle",
states=ego_track,
target_times_sec=target_times,
config=config,
)
if ego_obj is not None:
objects.append(ego_obj)
next_id += 1
sorted_tracks = sorted(
annotation_tracks.items(),
key=lambda item: (item[1][0]["time_sec"], item[0]),
)
for _, states in sorted_tracks:
gpudrive_type = states[0]["gpudrive_type"]
obj = _make_gpudrive_object(
obj_id=next_id,
gpudrive_type=gpudrive_type,
states=states,
target_times_sec=target_times,
config=config,
)
if obj is None:
continue
objects.append(obj)
next_id += 1
if not objects:
continue
center_xy = _road_center_from_objects(objects)
roads: list[dict[str, Any]] = []
if config.include_map:
try:
map_name = get_scene_map_name(nusc, scene)
if map_name not in map_cache:
map_cache[map_name] = load_nuscenes_map(dataroot, map_name)
roads = extract_roads(map_cache[map_name], center_xy, config)
except Exception as exc: # pragma: no cover - SDK/data dependent.
if config.fail_on_missing_map:
raise
logging.warning(
"Skipping map extraction for scene %s window %d: %s",
scene.get("name", scene.get("token")),
window_idx,
exc,
)
sdc_track_index = 0 if config.include_ego and objects and objects[0]["id"] == 0 else -1
tracks_to_predict = [
{"track_index": idx, "difficulty": 0}
for idx, obj in enumerate(objects)
if obj["type"] in {"vehicle", "cyclist", "pedestrian"}
and not obj.get("mark_as_expert", False)
]
objects_of_interest = [
obj["id"]
for obj in objects
if obj["type"] in {"vehicle", "cyclist"}
and not obj.get("mark_as_expert", False)
]
output_name = f"{file_prefix}_{scene['name']}_{window_idx:03d}.json"
scenarios.append(
{
"name": output_name,
"scenario_id": f"{scene['token'][:24]}_{window_idx:03d}",
"objects": objects,
"roads": roads,
"tl_states": {},
"metadata": {
"sdc_track_index": sdc_track_index,
"objects_of_interest": objects_of_interest,
"tracks_to_predict": tracks_to_predict,
"source": {
"dataset": "nuscenes",
"scene_name": scene["name"],
"scene_token": scene["token"],
"window_start_sec": float(window_start),
"target_hz": config.target_hz,
"num_steps": config.num_steps,
},
},
}
)
return scenarios
def select_scenes(
nusc: Any,
split: Optional[str] = None,
scene_names: Optional[set[str]] = None,
max_scenes: Optional[int] = None,
) -> list[dict[str, Any]]:
"""Select NuScenes scenes by split/name."""
selected_names = scene_names
if split:
try:
from nuscenes.utils.splits import create_splits_scenes
except ImportError as exc: # pragma: no cover - depends on local install.
raise ImportError(
"NuScenes split selection requires `nuscenes-devkit`."
) from exc
splits = create_splits_scenes()
if split not in splits:
valid = ", ".join(sorted(splits))
raise ValueError(f"Unknown NuScenes split '{split}'. Valid splits: {valid}")
selected_names = set(splits[split])
scenes = [
scene
for scene in nusc.scene
if selected_names is None or scene["name"] in selected_names
]
if max_scenes is not None:
scenes = scenes[:max_scenes]
return scenes
def convert_nuscenes_dataset(
dataroot: str,
version: str,
output_dir: str | Path,
config: NuScenesAdapterConfig,
split: Optional[str] = None,
scene_names: Optional[set[str]] = None,
max_scenes: Optional[int] = None,
file_prefix: str = "tfrecord-nuscenes",
window_stride_sec: Optional[float] = None,
verbose: bool = True,
) -> dict[str, int]:
"""Convert NuScenes scenes and write GPUDrive JSON files."""
nusc = load_nuscenes(version=version, dataroot=dataroot, verbose=verbose)
scenes = select_scenes(
nusc,
split=split,
scene_names=scene_names,
max_scenes=max_scenes,
)
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
map_cache: dict[str, Any] = {}
written = 0
skipped = 0
for scene in scenes:
scenarios = scene_to_gpudrive_scenarios(
nusc=nusc,
scene=scene,
dataroot=dataroot,
config=config,
file_prefix=file_prefix,
window_stride_sec=window_stride_sec,
map_cache=map_cache,
)
if not scenarios:
skipped += 1
continue
for scenario in scenarios:
with (output_path / scenario["name"]).open("w", encoding="utf-8") as f:
json.dump(scenario, f)
written += 1
return {
"scenes_selected": len(scenes),
"scenes_without_outputs": skipped,
"files_written": written,
}