"""Two-frame monocular 3D detection samples from SimLingo logs (stage-2 perception). Each sample is the front image at frame t and at t-1 (0.25 s earlier, the 4 Hz log interval), the ego motion between them, and CenterNet-style targets for the ground-truth boxes of frame t (dataloader.detection_labels). Box coordinates are in SimLingo's ego frame, whose origin is the ego bounding-box centre; the camera sits at (-1.5, 0, 2.0) relative to the actor origin on the ground, i.e. CAMERA_Z above the box-frame origin. """ import glob import hashlib import math import zlib from pathlib import Path import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from torchvision.io import ImageReadMode, decode_jpeg, read_file from dataloader.detection_labels import ( EGO_SPEED, EGO_X, EGO_Y, EGO_YAW, OBJ_BANK_VISIBLE, OBJ_CLASS, OBJ_HALF_H, OBJ_HALF_L, OBJ_HALF_W, OBJ_LIDAR_POINTS, OBJ_SPEED, OBJ_X, OBJ_Y, OBJ_YAW, OBJ_Z, ) from dataloader.object_bank import CLASS_CAR, CLASS_WALKER, NUM_CLASSES, normalize_angle IMAGE_W, IMAGE_H = 896, 448 # model input (the 1024x512 log images resized, same 110 degree FOV) FOV_DEG = 110.0 FOCAL = IMAGE_W / (2.0 * math.tan(math.radians(FOV_DEG / 2.0))) CAMERA_X = -1.5 CAMERA_Z = 2.0 - 0.745 # camera height above the box-frame origin (half height of the MKZ ego) STRIDE = 8 GRID_W, GRID_H = IMAGE_W // STRIDE, IMAGE_H // STRIDE MAX_TARGETS = 64 # per-target regression layout (T_OFF_U, T_OFF_V, T_LOG_DEPTH, T_LOG_L, T_LOG_W, T_LOG_H, T_SIN, T_COS, T_VX, T_VY) = range(10) TARGET_DIM = 10 def ego_to_camera(xyz): """Box-frame points [..., 3] -> camera frame (forward, right, up).""" xyz = np.asarray(xyz, dtype=np.float64) return np.stack((xyz[..., 0] - CAMERA_X, xyz[..., 1], xyz[..., 2] - CAMERA_Z), -1) def project(cam): """Camera-frame points [..., 3] (forward > 0) -> pixels [..., 2] in the model image.""" return np.stack((IMAGE_W / 2 + FOCAL * cam[..., 1] / cam[..., 0], IMAGE_H / 2 - FOCAL * cam[..., 2] / cam[..., 0]), -1) def box_corners(rows): """[N, OBJ_DIM] -> box-frame corners [N, 8, 3].""" signs = np.array([[sx, sy, sz] for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)], dtype=np.float64) ext = rows[:, [OBJ_HALF_L, OBJ_HALF_W, OBJ_HALF_H]].astype(np.float64) local = signs[None] * ext[:, None] c, s = np.cos(rows[:, OBJ_YAW]), np.sin(rows[:, OBJ_YAW]) x = c[:, None] * local[..., 0] - s[:, None] * local[..., 1] + rows[:, None, OBJ_X] y = s[:, None] * local[..., 0] + c[:, None] * local[..., 1] + rows[:, None, OBJ_Y] return np.stack((x, y, local[..., 2] + rows[:, None, OBJ_Z]), -1) def gaussian_radius(height, width, min_overlap=0.7): """CenterNet's radius for which a shifted box keeps IoU >= min_overlap (in grid cells).""" a1, b1 = 1, height + width c1 = width * height * (1 - min_overlap) / (1 + min_overlap) r1 = (b1 + np.sqrt(b1 ** 2 - 4 * a1 * c1)) / 2 a2, b2 = 4, 2 * (height + width) c2 = (1 - min_overlap) * width * height r2 = (b2 + np.sqrt(b2 ** 2 - 4 * a2 * c2)) / 2 a3, b3 = 4 * min_overlap, -2 * min_overlap * (height + width) c3 = (min_overlap - 1) * width * height r3 = (b3 + np.sqrt(b3 ** 2 - 4 * a3 * c3)) / 2 return min(r1, r2, r3) def draw_gaussian(heatmap, cx, cy, radius): radius = max(0, int(radius)) sigma = (2 * radius + 1) / 6.0 ys, xs = np.ogrid[-radius:radius + 1, -radius:radius + 1] g = np.exp(-(xs * xs + ys * ys) / (2 * sigma * sigma)) h, w = heatmap.shape left, right = min(cx, radius), min(w - cx, radius + 1) top, bottom = min(cy, radius), min(h - cy, radius + 1) if right <= -left or bottom <= -top: return region = heatmap[cy - top:cy + bottom, cx - left:cx + right] np.maximum(region, g[radius - top:radius + bottom, radius - left:radius + right], out=region) def is_positive(rows, max_range, min_lidar_points=1): """Boxes the detector must find: pass the bank's visibility test, are in range and were hit by the lidar (the bank's BEV test does not know about buildings, terrain or fog-free sight lines).""" dist = np.hypot(rows[:, OBJ_X] - CAMERA_X, rows[:, OBJ_Y]) return (rows[:, OBJ_BANK_VISIBLE] > 0.5) & (dist <= max_range) & (rows[:, OBJ_LIDAR_POINTS] >= min_lidar_points) def build_targets(rows, max_range, min_lidar_points=1): """CenterNet targets for one frame. rows: [N, OBJ_DIM] labels of frame t. Positives see is_positive; every other labelled box only switches off the negative loss around its centre, since whether it is visible is uncertain. """ heatmap = np.zeros((NUM_CLASSES, GRID_H, GRID_W), dtype=np.float32) ignore = np.zeros((GRID_H, GRID_W), dtype=np.float32) index = np.zeros(MAX_TARGETS, dtype=np.int64) cls = np.zeros(MAX_TARGETS, dtype=np.int64) target = np.zeros((MAX_TARGETS, TARGET_DIM), dtype=np.float32) mask = np.zeros(MAX_TARGETS, dtype=np.float32) if len(rows) == 0: return heatmap, ignore, index, cls, target, mask centre = ego_to_camera(rows[:, [OBJ_X, OBJ_Y, OBJ_Z]]) corners = ego_to_camera(box_corners(rows)) positives = is_positive(rows, max_range, min_lidar_points) k = 0 for i in range(len(rows)): if centre[i, 0] < 1.0: continue uv = project(centre[i]) cu, cv = uv[0] / STRIDE, uv[1] / STRIDE if not (0 <= cu < GRID_W and 0 <= cv < GRID_H): continue front = corners[i][corners[i][:, 0] > 0.3] if len(front) < 2: continue box_uv = project(front) bw = (np.clip(box_uv[:, 0].max(), 0, IMAGE_W) - np.clip(box_uv[:, 0].min(), 0, IMAGE_W)) / STRIDE bh = (np.clip(box_uv[:, 1].max(), 0, IMAGE_H) - np.clip(box_uv[:, 1].min(), 0, IMAGE_H)) / STRIDE radius = max(0.0, gaussian_radius(max(bh, 1e-3), max(bw, 1e-3))) ix, iy = int(cu), int(cv) if not positives[i]: draw_gaussian(ignore, ix, iy, max(radius, 1.0)) continue c = int(rows[i, OBJ_CLASS]) draw_gaussian(heatmap[c], ix, iy, radius) if k >= MAX_TARGETS: continue yaw = float(rows[i, OBJ_YAW]) alpha = normalize_angle(yaw - math.atan2(centre[i, 1], centre[i, 0])) speed = float(rows[i, OBJ_SPEED]) index[k] = iy * GRID_W + ix cls[k] = c target[k] = (cu - ix, cv - iy, math.log(centre[i, 0]), math.log(rows[i, OBJ_HALF_L]), math.log(rows[i, OBJ_HALF_W]), math.log(rows[i, OBJ_HALF_H]), math.sin(alpha), math.cos(alpha), speed * math.cos(yaw), speed * math.sin(yaw)) mask[k] = 1.0 k += 1 # a positive's own peak must not be switched off by an overlapping ignored box ignore = np.where(heatmap.max(0) > 0.0, 0.0, ignore) return heatmap, ignore, index, cls, target, mask def ego_motion(ego_prev, ego_now): """Previous ego pose in the current ego frame (dx forward, dy right, dyaw) and current speed.""" dxw, dyw = ego_prev[EGO_X] - ego_now[EGO_X], ego_prev[EGO_Y] - ego_now[EGO_Y] c, s = math.cos(ego_now[EGO_YAW]), math.sin(ego_now[EGO_YAW]) return np.array((c * dxw + s * dyw, -s * dxw + c * dyw, normalize_angle(float(ego_prev[EGO_YAW] - ego_now[EGO_YAW])), ego_now[EGO_SPEED]), dtype=np.float32) def _route_flags(label_file): with np.load(label_file) as z: objects, count = z["objects"], z["count"] flags = np.zeros((len(count), 2), dtype=np.uint8) for f in range(len(count)): rows = objects[f, :count[f]] pos = is_positive(rows, 50.0) flags[f, 0] = min(255, int((pos & (rows[:, OBJ_CLASS] == CLASS_WALKER)).sum())) flags[f, 1] = min(255, int((pos & (rows[:, OBJ_CLASS] == CLASS_CAR) & (rows[:, OBJ_SPEED] > 1.0)).sum())) return flags def build_frame_flags(data_root="simlingo_data", workers=64): """Per-frame [walker positives, moving-car positives] counts for every route, cached once in detection_labels/frame_flags.npz (used for sampling weights).""" from multiprocessing import Pool data_root = Path(data_root).resolve() files = sorted(glob.glob(str(data_root / "detection_labels/simlingo/*/*/*/Town*/labels.npz"))) with Pool(workers) as pool: flags = pool.map(_route_flags, files, chunksize=8) rel = [str(Path(f).parent.relative_to(data_root / "detection_labels")) for f in files] lengths = np.array([len(x) for x in flags]) np.savez(data_root / "detection_labels/frame_flags.npz", routes=np.array(rel), lengths=lengths, flags=np.concatenate(flags)) def route_split(route_dir, val_mod=50): """Deterministic route-level split: about 1/val_mod of the routes are validation.""" return "val" if zlib.crc32(str(route_dir).encode()) % val_mod == 0 else "train" def route_fold(route_dir, num_folds): """Deterministic cross-fitting fold of a route (md5: crc32 is affine, so it would correlate with route_split).""" return int(hashlib.md5(str(route_dir).encode()).hexdigest(), 16) % num_folds def load_image(path): try: return decode_jpeg(read_file(path), mode=ImageReadMode.RGB) except RuntimeError: return torch.from_numpy(np.asarray(Image.open(path).convert("RGB"))).permute(2, 0, 1).contiguous() class DetectionDataset(Dataset): """(image_t, image_t-1, ego motion, targets) over every SimLingo route of one split.""" def __init__(self, data_root="simlingo_data", split="train", max_range=50.0, min_lidar_points=1, frame_stride=1, route_filter=None, val_mod=50): self.data_root = Path(data_root).resolve() self.max_range = float(max_range) self.min_lidar_points = int(min_lidar_points) label_files = sorted(glob.glob(str(self.data_root / "detection_labels/simlingo/*/*/*/Town*/labels.npz"))) routes, index = [], [] for lf in label_files: route_dir = Path(lf).parent rel = route_dir.relative_to(self.data_root / "detection_labels") if route_split(rel, val_mod) != split: continue if route_filter is not None and not route_filter(str(rel)): continue with np.load(lf) as z: n = len(z["count"]) r = len(routes) routes.append((str(self.data_root / "data" / rel), lf)) index.extend((r, f) for f in range(1, n, frame_stride)) self.routes = routes self.index = np.asarray(index, dtype=np.int32).reshape(-1, 2) self._cache = {} def __len__(self): return len(self.index) def _labels(self, r): if r not in self._cache: if len(self._cache) > 64: self._cache.clear() with np.load(self.routes[r][1]) as z: self._cache[r] = (z["objects"], z["count"], z["ego"]) return self._cache[r] def __getitem__(self, i): r, f = (int(v) for v in self.index[i]) route_dir = self.routes[r][0] objects, count, ego = self._labels(r) rows = objects[f, :count[f]] heatmap, ignore, index, cls, target, mask = build_targets(rows, self.max_range, self.min_lidar_points) return dict( image=load_image(f"{route_dir}/rgb/{f:04d}.jpg"), image_prev=load_image(f"{route_dir}/rgb/{f - 1:04d}.jpg"), ego_motion=torch.from_numpy(ego_motion(ego[f - 1], ego[f])), heatmap=torch.from_numpy(heatmap), ignore=torch.from_numpy(ignore), index=torch.from_numpy(index), cls=torch.from_numpy(cls), target=torch.from_numpy(target), mask=torch.from_numpy(mask), sample=torch.tensor((r, f), dtype=torch.int32), ) def sample_weights(self, walker_weight=5.0, moving_weight=2.0): """Per-sample weights that oversample frames with walkers and with moving cars (needs build_frame_flags).""" with np.load(self.data_root / "detection_labels/frame_flags.npz") as z: starts = np.concatenate(([0], np.cumsum(z["lengths"])[:-1])) where = {r: (s, n) for r, s, n in zip(z["routes"], starts, z["lengths"])} flags = z["flags"] per_route = [] for route_dir, _ in self.routes: s, n = where[str(Path(route_dir).relative_to(self.data_root / "data"))] per_route.append(flags[s:s + n]) f = np.stack([per_route[r][i] for r, i in self.index]).astype(np.float64) return 1.0 + (walker_weight - 1.0) * (f[:, 0] > 0) + (moving_weight - 1.0) * (f[:, 1] > 0) def gt_rows(self, i): """Raw ground-truth rows of sample i (for evaluation).""" r, f = (int(v) for v in self.index[i]) objects, count, _ = self._labels(r) return objects[f, :count[f]]