diff --git a/src/planning/plant2_io/.gitignore b/src/planning/plant2_io/.gitignore new file mode 100644 index 0000000..23d6cad --- /dev/null +++ b/src/planning/plant2_io/.gitignore @@ -0,0 +1 @@ +records*/ diff --git a/src/planning/plant2_io/README.md b/src/planning/plant2_io/README.md new file mode 100644 index 0000000..7748853 --- /dev/null +++ b/src/planning/plant2_io/README.md @@ -0,0 +1,302 @@ +# PlanT 2.0 — inputs & outputs reference + +What goes into PlanT 2.0, what comes out, and how the outputs turn into vehicle control. Each item is traced to the code in [autonomousvision/plant2](https://github.com/autonomousvision/plant2) (commit `6269e5a`) and to the PlanT 2.0 paper (arXiv 2511.07292). Shapes and values come from the released config, `PlanT/config/model/PlanT.yaml`. + +``` +CARLA world ──► boxes + measurements ──► PlanTDataset / PlanTAgent.get_input_batch ──► generate_batch ──► HFLM.forward ──► (path, waypoints) ──► controllers ──► carla.VehicleControl + (privileged ground truth) (filter + encode objects, BEV, route) (pad/batch) (BERT-medium) +``` + +**Contents** +1. Conventions +2. Inputs: object matrix, BEV image, route, speed limit +3. How the inputs become a token sequence +4. Outputs: path, waypoints, forecasting head, attention +5. From outputs to vehicle control +6. Code samples +7. Sample records (on the Notion task card) +8. Gotchas + +--- + +## 1. Conventions + +| | | +|---|---| +| Frame | **Ego-relative**, origin at the ego vehicle's centre, at the current frame | +| Axes | **x = forward**, **y = right** (CARLA's left-handed frame), z = up (z is used only for filtering) | +| Yaw | relative to ego heading. **Radians** in raw boxes, **degrees** in model input, normalised to (-180, 180]. Positive = turned right | +| Speed | **m/s** in raw data. Object speeds are converted to **km/h** in the model input | +| Rate | Data is saved at **4 Hz** (CARLA 20 fps, `data_save_freq = 5`), so waypoints are 0.25 s apart | +| Perception | None. PlanT gets **ground-truth** boxes from the simulator (privileged planner) | + +--- + +## 2. Inputs + +The model's `forward(batch)` reads these keys (`PlanT/model.py`): + +| Key | Type / shape (batched) | Meaning | +|---|---|---| +| `x_objs` | `float32 [1 + ΣN, 7]` | All objects of all samples stacked, plus a padding row at index 0 | +| `idxs` | `int32 [B, maxN]` | For each sample, the rows of `x_objs` that belong to it (0 = padding) | +| `BEV` | `float32 [B, 3, 128, 128]` | Road-layout image (SD map). Used because `input_bev: True` | +| `route_original` | `float32 [B, 20, 2]` | 20 route points, 1 m apart | +| `speed_limit` | `int32 [B]` | Speed-limit category 0–3 | +| `input_ego_speed` | `float32 [B]` | **Off** in the released config (`input_ego_speed: False`) | +| `y_objs` | `int64 [1 + ΣN, 4]` or `None` | Forecasting targets. Training only; `None` at inference | + +### 2.1 Object matrix — "other agents, lights & signs" + +Each object becomes **one row of 7 floats**: + +| col | name | unit | notes | +|---|---|---|---| +| 0 | `type` | class index | see table below. The model strips this column and uses it to pick a **class-specific linear projection** | +| 1 | `x` | m | forward | +| 2 | `y` | m | right | +| 3 | `yaw` | deg | relative to ego | +| 4 | `speed` | km/h | always 0 for static classes | +| 5 | `width` | m | `extent[1] * 2`. **+1 m** for a vehicle whose scenario name contains `"Door"` (door-opening scenario) | +| 6 | `length` | m | `extent[0] * 2` | + +> The comment in `model.py` says `x, y, yaw, speed/id, extent x, extent y`, but the code puts the **y-extent (width) first**: col 5 = width, col 6 = length. + +**Classes** (`PlanT/plant_variables.py`): + +| index | class | taken from | included when… | +|---|---|---|---| +| 0 | padding | — | — | +| 1 | `car` | every `*vehicle*` actor | inside the range (below) | +| 1 | `static_car` (parked) | parked-car meshes | `input_static_cars: True`. Extents come from the `CAR_EXTENTS` table because CARLA reports wrong ones | +| 2 | `walker` | `*walker*` actors | in range. **At inference** a pedestrian only appears once it has moved (speed ≥ 0.1 m/s at least once) | +| 3 | `static` | static props | only `static.prop.constructioncone` and `static.prop.trafficwarning`. Extents come from `STATIC_EXTENTS` | +| 4 | `stop_sign` | a box on the stop line | affects the ego, within 30 m, not yet cleared | +| 5 | `traffic_light` | a box on the stop line (one per lane waypoint) | state **Red or Yellow** and affects the ego, within 30 m | +| 6 | `emergency` | vehicles with `type_id` in {`dodge.charger_police`, `dodge.charger_police_2020`, `carlamotors.firetruck`, `ford.ambulance`} | in range | + +Lights and stop signs are fixed 3 × 3 m boxes (`extent [1.5, 1.5, 0.5]`). They mark **where the car must stop**, not where the pole stands. + +**Input range** (`range: 50`, `range_factor_front: 2`): +- behind the ego (x ≤ 0): circle of **50 m** +- ahead (x > 0): ellipse, **100 m** along x and **50 m** along y: `x²/4 + y² ≤ 50²` +- lights and stop signs: circle of **30 m** +- anything with |z| > 30 m is dropped + +Row order: dynamic objects (car, walker, emergency) first, then lights, signs, statics and parked cars. The number of objects varies per sample, which is why batches use the flat `x_objs` + `idxs` layout. + +### 2.2 Bird's-eye-view image (SD map) + +| | | +|---|---| +| Shape / dtype | `float32 [3, 128, 128]` (CHW) | +| Coverage | **64 m × 64 m**, centred on the ego, **0.5 m per pixel** | +| Source | `ObsManager` (`carla_garage/birds_eye_view/chauffeurnet.py`) renders a 256 × 256 class map at 2 px/m. The training data stores it as `bev_no_car_semantics/XXXX.png` | +| Processing | `rot90` → crop `[64:-64, 64:-64]` → look up each class index in `bev_colors` | +| Encoder | ResNet-18 (ImageNet-pretrained, `num_classes=512`) → **1 token** | +| Orientation | Ego faces **up** (row 0 is 32 m ahead) and +y points right. This is how `util/viz_batch.py` lays the image under the boxes | + +Class → RGB (each channel 0–1): + +| idx | class | colour | +|---|---|---| +| 0 | background | ImageNet mean (0.485, 0.456, 0.406) | +| 1 | drivable road | (0.25, 0.25, 0.75) blue | +| 2 | sidewalk | same as background (the model can't tell them apart) | +| 3 | solid lane marking | (0.75, 0.25, 0.25) red | +| 4 | broken lane marking | (0.25, 0.75, 0.25) green | + +The image has **no cars**. It tells the model which lanes go which way and how many lanes there are. + +### 2.3 Route + +| | | +|---|---| +| Key | `route_original` | +| Shape | `float32 [20, 2]`, (x, y) in m | +| Sampling | starts **2.5 m ahead** of the ego (`tf_first_checkpoint_distance`), then one point **every 1 m** | +| Encoder | flattened to 40 numbers → `Linear(40, 512)` → **1 token** | + +There are two routes in the data: +- **`route_original`** is the GPS route from the leaderboard. This is the model **input**. +- **`route`** is the expert's adjusted route, e.g. a detour around a construction zone. It is used as the **path target**. + +### 2.4 Speed limit + +| | | +|---|---| +| Value | `int` in {0, 1, 2, 3} ↔ {50, 80, 100, 120} km/h. Computed as `speed_cats[round(speed_limit_mps * 3.6)]` | +| Encoder | `nn.Embedding(4, 512)` → **1 token** | + +--- + +## 3. How the inputs become a token sequence + +From `HFLM.forward`, with the released config (`path+wps`, `linear` generator): + +``` +[ 8 waypoint query tokens | 20 path query tokens | BEV | speed limit | route | obj_1 … obj_N ] + └──────── learned (28) ────────────────────────┘ └── 1 ┘ └── 1 ──┘ └ 1 ┘ └─ class-specific Linear(6→512) +``` + +The sequence goes through a **BERT-medium** encoder (`prajjwal1/bert-medium`: 8 layers, hidden size 512, 8 heads), built from its config, i.e. not pretrained. Its built-in word embeddings and pooler are removed. The first 28 output tokens become the plan. The object tokens (from index 31 on) feed the forecasting heads. + +--- + +## 4. Outputs + +`HFLM.forward` returns `(logits, targets, (pred_path, pred_wps, pred_speed), attn_map)`. + +| Output | Shape | Unit | How it is made | Used for | +|---|---|---|---|---| +| `pred_wps` | `float32 [B, 8, 2]` | m, ego frame | Linear(512→2) on each of the 8 waypoint tokens, then **cumulative sum** | **Longitudinal** control (speed). Points are 0.25 s apart, so they cover 2 s | +| `pred_path` | `float32 [B, 20, 2]` | m, ego frame | Linear(512→2) on each of the 20 path tokens, then cumsum | **Lateral** control (steering). Spatial points meant to be ~1 m apart; the target starts at (0, 0) | +| `pred_speed` | `None` | — | Only exists in the `path+2hot` variant (8-way classifier over `target_speeds`) | not used in the release | +| `logits` | list of 4 × `[ΣN·…, vocab]` | bins | 4 linear heads on the object tokens. Vocab sizes **[192, 128, 32, 32]** for x, y, yaw, speed | **Training only.** Auxiliary task: predict each object's state 0.25 s ahead. `None` when `y_objs` is `None` | +| `attn_map` | tuple of 8 × `[B, 8, T, T]` | — | BERT attentions | explainability / visualisation | + +**Training targets** (`lit_module.py`): `waypoints` = the expert's next 8 positions (from `ego_matrix` at t+1…t+8). `route` = the expert's adjusted route resampled to 20 points 1 m apart (`interpolate_route`). The losses are L1 on both, weighted path × 5 and waypoints × 1, plus cross-entropy on the forecasting bins. + +**How forecasting targets are quantised** (`quantize_box`): + +| attribute | normalise | bins | +|---|---|---| +| x | `(x + 50) / 100`, clipped to [0, 1.5] | 128 × 1.5 → **0–191** (≈ 0.79 m per bin) | +| y | `(y + 50) / 100`, clipped to [0, 1] | **0–127** | +| yaw | `(yaw mod 360) / 360` | **0–31** (11.25° per bin) | +| speed | `speed_kmh / 120` | **0–31** (≈ 3.9 km/h per bin) | + +`-999` marks objects with no target (lights, stop signs, statics, actors that disappeared). Parked cars use their current pose as the target. + +--- + +## 5. From outputs to vehicle control + +From `PlanT_agent.py::_get_control`: + +1. **Desired speed** = `‖wps[2] − wps[3]‖ × 4` m/s, i.e. the distance between the 3rd and 4th waypoints divided by 0.25 s. + *Creep heuristic:* if the ego is stopped (< 0.01 m/s), the desired speed becomes `min(mean waypoint spacing × 4, 0.1)`. +2. **Throttle / brake** come from `LongitudinalLinearRegressionController` (PDM-Lite's controller). It brakes when the desired speed is below 0.05 m/s. +3. **Steering**: `pred_path` is resampled every 0.1 m with a PCHIP spline and sent to `LateralPIDController` (variable look-ahead). If the car is stopped and braking, steering is computed against a straight dummy path. +4. The result is a `carla.VehicleControl(steer ∈ [-1, 1], throttle ∈ [0, 1], brake ∈ [0, 1])`. For the first 40 frames the agent always sends full brake. + +--- + +## 6. Code samples + +**One sample → model-ready input** (same logic as `get_input_batch` and `PlanTDataset.__getitem__`): + +```python +from plant_variables import PlanTVariables +from dataset import generate_batch + +type_nums = PlanTVariables.class_nums +rows = [] +for x in boxes: # ego-frame boxes, ego removed, filtered as in §2.1 + cls = x["class"] + if cls in ["car", "walker", "emergency"]: + rows.append([type_nums[cls], x["position"][0], x["position"][1], + rad2deg(x["yaw"]), x["speed"] * 3.6, + x["extent"][1] * 2, x["extent"][0] * 2]) + elif cls in type_nums: # static, static_car, stop_sign, traffic_light + rows.append([type_nums[cls], x["position"][0], x["position"][1], + rad2deg(x["yaw"]), 0.0, + x["extent"][1] * 2, x["extent"][0] * 2]) + +sample = { + "input": rows, # N x 7 + "output": [], # no forecasting targets at inference + "route_original": route_xy[:20], # 20 x 2, metres, ego frame + "speed_limit": PlanTVariables.speed_cats[round(speed_limit_mps * 3.6)], + "BEV": bev_tensor, # torch.float32 [3,128,128] + "ego_speed": ego_speed_mps, "waypoints": 0, "route": [], "target_speed": 0, # dummies +} +batch = generate_batch([sample]) +batch["y_objs"] = None +``` + +**Run the model and read the outputs:** + +```python +import torch +from lit_module import LitHFLM + +net = LitHFLM.load_from_checkpoint(ckpt_path, map_location="cpu").eval() +with torch.no_grad(): + _, _, (pred_path, pred_wps, _), attn = net(batch) + +pred_wps = pred_wps[0].numpy() # (8, 2) metres, 0.25 s apart +pred_path = pred_path[0].numpy() # (20, 2) metres +desired_speed = float(((pred_wps[2] - pred_wps[3]) ** 2).sum() ** 0.5 * 4.0) # m/s +``` + +**Load a sample record** (unzipped from Notion, or built with `make_records.py`): + +```python +import json, numpy as np +from PIL import Image +rec = json.load(open("records/02_red_light_stop.json")) +x_objs = np.array(rec["model_input"]["x_objs"]["rows"], dtype=np.float32) # N x 7 +route = np.array(rec["model_input"]["route_original"]["points_xy_m"]) # 20 x 2 +bev = np.asarray(Image.open("records/" + rec["model_input"]["BEV"]["png"]), + dtype=np.float32).transpose(2, 0, 1) / 255 # 3 x 128 x 128 (±0.002) +wps = np.array(rec["model_output"]["pred_wps"]["points_xy_m"]) # 8 x 2 +``` + +`plant2_pipeline.py` has a numpy-only port of the whole pipeline: object filtering and encoding, quantisation, `interpolate_route`, `generate_batch`, and the desired-speed rule. It runs without torch or CARLA. + +--- + +## 7. Sample records + +The records are **not stored in the repo**. They're attached to the Notion task card ("PlanT2.0 ins/outs records") as `plant2_sample_records.zip`. To rebuild them locally from this folder: + +```bash +python make_records.py --out records +``` + +Generated `records*/` folders are git-ignored, so they won't be committed by accident. + +Seven records. Each one has: +- `.json` — the record: raw boxes and measurements → model input → model output → controller value +- `_bev.png` — the BEV input tensor as an RGB image (divide by 255 for the float tensor; run the script with `--save-npy` for the exact float32 `.npy`) +- `_preview.png` — a picture of the scene + +`batch_example.json` shows all seven batched together, as `generate_batch` would produce them. + +| # | record | what it shows | +|---|---|---| +| 1 | `01_urban_follow_lead` | Basic case: lead car, oncoming car, follower. 50 km/h (`speed_limit = 0`) | +| 2 | `02_red_light_stop` | Red light as a stop-line box (class 5). A red light on the other approach and a green light are **dropped**. The waypoints shrink as the car brakes to a stop | +| 3 | `03_pedestrian_crossing` | Walker class (2) crossing the lane. A standing pedestrian is kept by the dataset loader but would be dropped by the agent (§8) | +| 4 | `04_construction_detour` | Cones and a warning sign (class 3) with corrected extents. A barbecue prop is dropped. **`route_original` (input) ≠ path target**: the expert detours into the oncoming lane | +| 5 | `05_emergency_vehicle_yield` | An ambulance becomes class 6. 100 km/h (`speed_limit = 2`). The path moves one lane to the right | +| 6 | `06_stop_sign_parked_car` | Stop sign (class 4), a parked `static_car` (id −999, shares class 1), and a car 120 m ahead **outside the range ellipse** (dropped) | +| 7 | `07_highway_cut_in` | 120 km/h (`speed_limit = 3`). A car cutting in, and a car 85 m ahead that is **still in range** thanks to the 100 m front ellipse | + +**Where these records come from:** the scenes were built by hand. They are not recordings from a CARLA run, because the dataset on HuggingFace can't be downloaded from the environment where these were made. Every input does go through the ported PlanT 2.0 pipeline, so formats, filtering, units and quantisation are exact. The "outputs" are **expert targets** (what the model is trained to output), not predictions from a trained checkpoint. + +**Making records from the real dataset**, after downloading a route folder from [`SimonGer/PlanT2_Dataset`](https://huggingface.co/datasets/SimonGer/PlanT2_Dataset): + +```bash +python make_records.py --out records_real \ + --route-dir /path/to/PlanT2_Dataset/data// \ + --frames 20 60 100 --plant2-repo /path/to/plant2 +``` + +This uses `load_real_sample`, a port of `PlanTDataset.__getitem__` without augmentation, and writes records in the same format. + +Requirements: `numpy`, `pillow`, `matplotlib`. + +--- + +## 8. Gotchas + +- **The dataset and the agent filter slightly differently.** + - Stationary pedestrians: the agent drops them until they first move; the dataset loader keeps them. + - Traffic lights: the dataset checks the box's `affects_ego` flag; the agent picks the next light along the route itself. + - `static` objects are removed entirely on `longest6` routes. +- **The speed limit must be 50/80/100/120 km/h.** Any other value raises a `KeyError` in `speed_cats`. +- **`augment_parked: True`** loads `car_data.npy` from a hard-coded cluster path (`/home/geiger/...`) in `dataset.py`. Change it before training locally. +- **Augmentation** (50 % of samples): shifts and rotates the scene using `augmentation_translation` / `augmentation_rotation`, so the model learns to recover from drifting off the route. The BEV then switches to `bev_no_car_semantics_augmented`. +- **Data filtering:** the loader skips routes where the expert scored < 100 (minimum-speed infractions excepted). It also skips the first 5 and last ~10 frames of each route. diff --git a/src/planning/plant2_io/make_records.py b/src/planning/plant2_io/make_records.py new file mode 100644 index 0000000..47b4fbc --- /dev/null +++ b/src/planning/plant2_io/make_records.py @@ -0,0 +1,471 @@ +""" +Build PlanT 2.0 input/output sample records. + +Two modes: + python make_records.py --out records + Builds the hand-made scenarios below (synthetic: they did not come from a + CARLA run, but every number goes through the same pipeline PlanT 2.0 uses). + + python make_records.py --out records_real --route-dir \ + --frames 20 60 100 --plant2-repo + Builds records from real PlanT 2.0 dataset frames (HuggingFace SimonGer/PlanT2_Dataset). + +Each record = .json + _bev.png (model-ready BEV, RGB uint8; /255 gives the float tensor to within 0.002) + + _bev.npy (exact float32 [3,128,128], only with --save-npy) + + _preview.png (what the scene looks like). +""" +import argparse +import json +import math +import os + +import numpy as np +from PIL import Image + +import plant2_pipeline as P + +DT = 0.25 # 4 Hz between waypoints (20 fps / data_save_freq 5) +PX = 0.5 # BEV metres per pixel +N = 128 # BEV size in pixels +LANE = 3.5 # lane width used for the hand-made road layouts + +LINCOLN = "/Game/Carla/Static/Car/4Wheeled/ParkedVehicles/Lincoln/SM_LincolnParked.SM_LincolnParked" +EGO_EXTENT = [2.44619083404541, 1.0005781650543213, 0.7606233954429626] +CAR_EXTENT = [2.3958897590637207, 1.081725001335144, 0.7438300848007202] +WALKER_EXTENT = [0.18767888844013214, 0.18767888844013214, 0.9300000071525574] +AMBULANCE_EXTENT = [3.18, 1.1923, 1.235] + + +# --------------------------------------------------------------------------- +# BEV drawing for the hand-made scenes (class map: 0 bg, 1 road, 2 sidewalk, 3 solid, 4 broken) +# Orientation: row 0 = 32 m ahead of ego, col 0 = 32 m to the left (ego faces up), +# which is how PlanT/util/viz_batch.py pastes the BEV under the boxes. +# --------------------------------------------------------------------------- +def grid(): + r = np.arange(N) + xs = (N / 2 - 0.5 - r) * PX # forward metres per row + ys = (r - N / 2 + 0.5) * PX # right metres per column + return np.meshgrid(xs, ys, indexing="ij") + + +def draw_road_along_x(cm, y_left, y_right, centre_y, x_from=-99, x_to=99, dashed=True): + """Road running forward/back between y_left..y_right with a solid centre divider at centre_y.""" + X, Y = grid() + band = (X >= x_from) & (X <= x_to) + cm[band & (Y >= y_left - 3) & (Y <= y_right + 3) & (cm == 0)] = 2 # sidewalks + cm[band & (Y >= y_left) & (Y <= y_right)] = 1 # road + for edge in (y_left, y_right, centre_y): + cm[band & (np.abs(Y - edge) < PX * 0.6)] = 3 # solid lines + if dashed: + dash = (np.floor(X / 3.0) % 2) == 0 + for y in np.arange(y_left + LANE, y_right - 0.1, LANE): + if abs(y - centre_y) > 0.1: + cm[band & dash & (np.abs(Y - y) < PX * 0.6)] = 4 # broken lines + + +def draw_road_along_y(cm, x_near, x_far, centre_x): + X, Y = grid() + cm[(X >= x_near - 3) & (X <= x_far + 3) & (cm == 0)] = 2 + cm[(X >= x_near) & (X <= x_far)] = 1 + for edge in (x_near, x_far, centre_x): + cm[np.abs(X - edge) < PX * 0.6] = 3 # junction interior is cleared afterwards + + +def clear_junction(cm, x_near, x_far, y_left, y_right): + X, Y = grid() + cm[(X >= x_near) & (X <= x_far) & (Y >= y_left) & (Y <= y_right)] = 1 + + +# --------------------------------------------------------------------------- +# Geometry helpers +# --------------------------------------------------------------------------- +def polyline_at(poly, s): + poly = np.asarray(poly, dtype=float) + seg = np.linalg.norm(np.diff(poly, axis=0), axis=1) + cum = np.concatenate([[0], np.cumsum(seg)]) + s = np.clip(s, 0, cum[-1]) + return np.array([np.interp(s, cum, poly[:, 0]), np.interp(s, cum, poly[:, 1])]).T + + +def lane_change_path(y_end, start=8.0, length=18.0, total=80.0): + xs = np.arange(0, total, 0.5) + t = np.clip((xs - start) / length, 0, 1) + ys = y_end * (3 * t ** 2 - 2 * t ** 3) + return np.stack([xs, ys], 1) + + +def straight_path(total=80.0): + return np.stack([np.arange(0, total, 0.5), np.zeros(int(total / 0.5))], 1) + + +def route_from_path(path): + """autopilot.py: route points start 2.5 m ahead (tf_first_checkpoint_distance) and are 1 m apart.""" + return polyline_at(path, 2.5 + np.arange(20)).tolist() + + +def ego_waypoints(path, v0, accel, v_min=0.0, stop_at=None): + """Expert future positions at t = 0.25..2.0 s along `path` with constant accel (clamped).""" + s, v, out = 0.0, v0, [] + for _ in range(P.WPS_LEN): + for _ in range(25): # integrate in 10 ms steps + v = max(v_min, v + accel * 0.01) + s += v * 0.01 + if stop_at is not None: + s = min(s, stop_at) + out.append(polyline_at(path, s).tolist()) + return out + + +def car(i, x, y, yaw_deg, speed, type_id="vehicle.tesla.model3", extent=CAR_EXTENT, scenario=""): + return {"class": "car", "id": i, "type_id": type_id, "position": [x, y, 0.0], + "yaw": math.radians(yaw_deg), "speed": speed, "extent": list(extent), + "num_points": -1, "role_name": "scenario" if scenario else "background", "scenario": scenario} + + +def walker(i, x, y, yaw_deg, speed): + return {"class": "walker", "id": i, "position": [x, y, 0.0], "yaw": math.radians(yaw_deg), + "speed": speed, "extent": list(WALKER_EXTENT), "num_points": -1} + + +def static(i, x, y, yaw_deg, type_id, extent=(0.5, 0.5, 0.5)): + return {"class": "static", "id": i, "type_id": type_id, "position": [x, y, 0.0], + "yaw": math.radians(yaw_deg), "extent": list(extent)} + + +def static_car(i, x, y, yaw_deg, mesh=LINCOLN): + return {"class": "static_car", "id": i, "mesh_path": mesh, "position": [x, y, 0.0], + "yaw": math.radians(yaw_deg), "extent": [2.0, 1.0, 0.7], "scale": None} + + +def light(x, y, state, affects_ego, yaw_deg=0.0): + return {"class": "traffic_light", "position": [x, y, 0.0], "yaw": math.radians(yaw_deg), + "extent": [1.5, 1.5, 0.5], "state": state, "affects_ego": affects_ego} + + +def stop_sign(x, y, affects_ego, yaw_deg=0.0): + return {"class": "stop_sign", "position": [x, y, 0.0], "yaw": math.radians(yaw_deg), + "extent": [1.5, 1.5, 0.5], "affects_ego": affects_ego} + + +def ego_box(speed): + return {"class": "ego_car", "id": 0, "position": [0.0, 0.0, 0.0], "yaw": 0.0, "speed": speed, + "extent": EGO_EXTENT, "num_points": -1, "distance": -1, "brake": 0.0} + + +# --------------------------------------------------------------------------- +# Hand-made scenarios +# --------------------------------------------------------------------------- +def scenarios(): + S = [] + + # 1. Urban two-lane road, following a slower lead car, oncoming traffic ----------------- + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 0.5 * LANE, -0.5 * LANE) + path = straight_path() + S.append(dict( + id="01_urban_follow_lead", + title="Urban road, following a slower lead car (50 km/h zone)", + speed_limit=50 / 3.6, ego_speed=11.0, target_speed=9.0, brake=False, + boxes=[car(101, 18.0, 0.0, 0.0, 9.0), + car(102, 35.0, -LANE, 180.0, 12.0), + car(103, -12.0, 0.0, 0.0, 11.5)], + route=route_from_path(path), route_original=route_from_path(path), + wps=ego_waypoints(path, 11.0, -1.2), bev=cm)) + + # 2. Red light at a signalised junction ------------------------------------------------ + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 0.5 * LANE, -0.5 * LANE) + draw_road_along_y(cm, 16.0, 23.0, 19.5) + clear_junction(cm, 16.0, 23.0, -1.5 * LANE, 0.5 * LANE) + path = straight_path() + stop_line = 13.5 + S.append(dict( + id="02_red_light_stop", + title="Approaching a red light: stop-line box makes the expert brake to a stop", + speed_limit=50 / 3.6, ego_speed=8.0, target_speed=0.0, brake=True, + boxes=[light(stop_line, 0.0, "Red", True), + light(stop_line, -LANE, "Red", False), # opposite-direction light -> dropped + light(26.0, LANE, "Green", False), # green -> dropped + car(201, 19.5, -12.0, 90.0, 10.0), # cross traffic with green + car(202, 9.0, -LANE, 180.0, 0.0)], # oncoming car waiting + route=route_from_path(path), route_original=route_from_path(path), + wps=ego_waypoints(path, 8.0, -8.0 ** 2 / (2 * (stop_line - 3.0)), stop_at=stop_line - 3.0), bev=cm)) + + # 3. Pedestrian crossing in front of the ego ------------------------------------------ + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 0.5 * LANE, -0.5 * LANE) + path = straight_path() + S.append(dict( + id="03_pedestrian_crossing", + title="Pedestrian crossing the ego lane; a standing pedestrian on the sidewalk", + speed_limit=50 / 3.6, ego_speed=7.0, target_speed=0.0, brake=True, + boxes=[walker(301, 12.0, 4.5, -90.0, 1.4), # walking right->left into the lane + walker(302, 6.0, -5.5, 0.0, 0.0), # standing (dataset keeps it; agent drops it) + car(303, 30.0, -LANE, 180.0, 10.0)], + route=route_from_path(path), route_original=route_from_path(path), + wps=ego_waypoints(path, 7.0, -7.0 ** 2 / (2 * 7.5), stop_at=7.5), bev=cm)) + + # 4. Construction zone blocking the lane: route is shifted into the oncoming lane ------ + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 0.5 * LANE, -0.5 * LANE) + detour = lane_change_path(-LANE, start=6.0, length=14.0) + path_orig = straight_path() + cones = [static(400 + k, 18.0 + 1.5 * k, 0.3 * (k % 3) - 0.5, 0.0, "static.prop.constructioncone") + for k in range(8)] + S.append(dict( + id="04_construction_detour", + title="Construction zone in ego lane: expert detours into the oncoming lane", + speed_limit=50 / 3.6, ego_speed=6.0, target_speed=6.0, brake=False, + boxes=cones + [static(420, 16.0, 0.0, 0.0, "static.prop.trafficwarning"), + static(421, 10.0, 6.5, 0.0, "static.prop.barbeque"), # irrelevant prop -> dropped + car(422, 70.0, -LANE, 180.0, 8.0)], + route=route_from_path(detour), route_original=route_from_path(path_orig), + wps=ego_waypoints(detour, 6.0, 0.0), bev=cm)) + + # 5. Ambulance approaching from behind on a highway ------------------------------------- + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 1.5 * LANE, -1.5 * LANE) # 3 same-direction lanes + side = lane_change_path(LANE, start=4.0, length=20.0) + S.append(dict( + id="05_emergency_vehicle_yield", + title="Ambulance approaching from behind at 100 km/h: expert moves one lane right", + speed_limit=100 / 3.6, ego_speed=24.0, target_speed=22.0, brake=False, + boxes=[car(501, -28.0, 0.0, 0.0, 31.0, type_id="vehicle.ford.ambulance", extent=AMBULANCE_EXTENT, + scenario="YieldToEmergencyVehicle_1"), + car(502, 40.0, -LANE, 0.0, 26.0), + car(503, 60.0, LANE, 0.0, 21.0)], + route=route_from_path(side), route_original=route_from_path(straight_path()), + wps=ego_waypoints(side, 24.0, -0.8), bev=cm)) + + # 6. Stop sign at a junction, parked car at the kerb, a far-away car ------------------ + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 0.5 * LANE, -0.5 * LANE) + draw_road_along_y(cm, 14.0, 21.0, 17.5) + clear_junction(cm, 14.0, 21.0, -1.5 * LANE, 0.5 * LANE) + path = straight_path() + S.append(dict( + id="06_stop_sign_parked_car", + title="Stop sign ahead, parked car at the kerb, car beyond the input range", + speed_limit=50 / 3.6, ego_speed=5.0, target_speed=0.0, brake=True, + boxes=[stop_sign(11.5, 0.0, True), + stop_sign(23.5, -LANE, False), # other approach's sign -> dropped + static_car(601, 6.0, 0.5 * LANE + 1.2, 0.0), + car(602, 17.5, 14.0, -90.0, 7.0), + car(603, 120.0, 0.0, 0.0, 10.0)], # x=120 > 100 m ellipse -> dropped + route=route_from_path(path), route_original=route_from_path(path), + wps=ego_waypoints(path, 5.0, -5.0 ** 2 / (2 * 8.5), stop_at=8.5), bev=cm)) + + # 7. Highway cut-in at 120 km/h --------------------------------------------------------- + cm = np.zeros((N, N), np.uint8) + draw_road_along_x(cm, -1.5 * LANE, 1.5 * LANE, -1.5 * LANE) # 3 same-direction lanes + path = straight_path(120) + S.append(dict( + id="07_highway_cut_in", + title="Car cutting in from the right lane at 120 km/h; expert brakes moderately", + speed_limit=120 / 3.6, ego_speed=30.0, target_speed=25.0, brake=False, + boxes=[car(701, 14.0, 2.4, -8.0, 26.0, scenario="HighwayCutIn_1"), + car(702, 85.0, 0.0, 0.0, 29.0), # 85 m ahead: inside the ellipse + car(703, -20.0, LANE, 0.0, 31.0)], + route=route_from_path(path), route_original=route_from_path(path), + wps=ego_waypoints(path, 30.0, -3.0), bev=cm)) + + return S + + +# --------------------------------------------------------------------------- +# Record assembly +# --------------------------------------------------------------------------- +def next_frame(boxes): + """Move dynamic actors forward 0.25 s along their heading (constant velocity), in the current ego frame.""" + out = {} + for b in boxes: + if "speed" not in b or "id" not in b: + continue + x, y = b["position"][:2] + out[b["id"]] = [x + b["speed"] * DT * math.cos(b["yaw"]), y + b["speed"] * DT * math.sin(b["yaw"]), + P.rad2deg(b["yaw"]), b["speed"] * 3.6] + return out + + +def rnd(x, d=4): + if isinstance(x, (list, tuple)): + return [rnd(v, d) for v in x] + if isinstance(x, (float, np.floating)): + return round(float(x), d) + if isinstance(x, np.integer): + return int(x) + return x + + +def build_synthetic(sc): + boxes = [ego_box(sc["ego_speed"])] + sc["boxes"] + rows, dropped = P.encode_objects(boxes[1:]) + floating, quant = P.forecast_targets(rows, next_frame(sc["boxes"])) + sample = { + "input": [r[:-1] for r in rows], + "input_with_ids": rows, + "output": quant, + "output_floating": floating, + "route_original": sc["route_original"], + "route": P.interpolate_route(sc["route"]).tolist(), + "waypoints": sc["wps"], + "speed_limit": P.SPEED_CATS[round(sc["speed_limit"] * 3.6)], + "target_speed": 0.0 if sc["brake"] else sc["target_speed"], + "ego_speed": sc["ego_speed"], + "bev_classes": sc["bev"], + "BEV": P.bev_classes_to_tensor(sc["bev"]), + } + raw = { + "measurements": { + "speed": sc["ego_speed"], "speed_limit": sc["speed_limit"], "target_speed": sc["target_speed"], + "brake": sc["brake"], "theta": 0.0, + "route": sc["route"], "route_original": sc["route_original"], + "changed_route": sc["route"] != sc["route_original"], + "augmentation_translation": 0.0, "augmentation_rotation": 0.0, + }, + "boxes": boxes, + } + return sample, dropped, raw + + +def write_record(out_dir, rid, title, sample, dropped, raw, provenance, save_npy=False): + os.makedirs(out_dir, exist_ok=True) + bev_png = f"{rid}_bev.png" + bev_npy = f"{rid}_bev.npy" if save_npy else None + Image.fromarray((sample["BEV"].transpose(1, 2, 0) * 255).round().astype(np.uint8)).save(os.path.join(out_dir, bev_png)) + if save_npy: + np.save(os.path.join(out_dir, bev_npy), sample["BEV"]) + + desired, creep = P.desired_speed_from_wps(sample["waypoints"], sample["ego_speed"]) + ids = [r[-1] for r in sample["input_with_ids"]] + record = { + "record_id": rid, + "title": title, + "provenance": provenance, + "raw": rnd(raw), + "model_input": { + "x_objs": { + "columns": ["type", "x_m", "y_m", "yaw_deg", "speed_kmh", "width_m", "length_m"], + "dtype": "float32", "shape": [len(sample["input"]), 7], + "rows": rnd(sample["input"]), + "source_actor_ids": ids, + }, + "route_original": {"dtype": "float32", "shape": [20, 2], "points_xy_m": rnd(sample["route_original"])}, + "speed_limit": {"dtype": "int", "value": sample["speed_limit"], + "kmh": {v: k for k, v in P.SPEED_CATS.items()}[sample["speed_limit"]]}, + "BEV": {"dtype": "float32", "shape": [3, 128, 128], "png": bev_png, "npy": bev_npy, + "class_pixel_counts": {name: int((sample["bev_classes"] == i).sum()) for i, name in + enumerate(["background", "road", "sidewalk", "solid_line", "broken_line"])}}, + "dropped_objects": dropped, + }, + "model_output": { + "note": "Training targets (expert labels): what PlanT 2.0 learns to output for this input.", + "pred_path": {"dtype": "float32", "shape": [20, 2], "points_xy_m": rnd(sample["route"])}, + "pred_wps": {"dtype": "float32", "shape": [8, 2], "dt_s": DT, "points_xy_m": rnd(sample["waypoints"])}, + "pred_speed": None, + "forecast_y_objs": { + "note": "Auxiliary training target only (not used for driving): each input object's state " + "0.25 s later, quantised. -999 = no target (lights, stop signs, statics).", + "columns": ["x_bin(0-191)", "y_bin(0-127)", "yaw_bin(0-31)", "speed_bin(0-31)"], + "dtype": "int64", "shape": [len(sample["output"]), 4], + "rows": sample["output"], + "rows_unquantised": rnd(sample["output_floating"], 2), + }, + }, + "controller": { + "desired_speed_mps": round(desired, 3), + "creep_mode": creep, + "expert_target_speed_mps": rnd(sample["target_speed"]), + "ego_speed_mps": rnd(sample["ego_speed"]), + }, + } + with open(os.path.join(out_dir, f"{rid}.json"), "w") as f: + json.dump(record, f, indent=1) + render_preview(os.path.join(out_dir, f"{rid}_preview.png"), title, sample) + return record + + +def render_preview(path, title, sample): + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + from matplotlib.patches import Polygon + + colours = {1: "#d62728", 2: "#17becf", 3: "#7f7f7f", 4: "#e377c2", 5: "#ff7f0e", 6: "#9467bd"} + names = {1: "vehicle / parked", 2: "pedestrian", 3: "static", 4: "stop sign", 5: "traffic light", 6: "emergency"} + fig, ax = plt.subplots(figsize=(5.2, 7)) + ax.imshow(sample["BEV"].transpose(1, 2, 0), extent=[-32, 32, -32, 32], origin="upper", zorder=0) + ax.add_patch(Polygon([[-1.0, -2.45], [1.0, -2.45], [1.0, 2.45], [-1.0, 2.45]], closed=True, + fc="white", ec="black", zorder=3, label="ego")) + seen = set() + for r in sample["input"]: + t, x, y, yaw, v, w, l = r + a = math.radians(yaw) + f, s = np.array([math.cos(a), math.sin(a)]), np.array([-math.sin(a), math.cos(a)]) + c = [np.array([x, y]) + sx * f * l / 2 + sy * s * w / 2 for sx, sy in [(1, 1), (1, -1), (-1, -1), (-1, 1)]] + ax.add_patch(Polygon([[p[1], p[0]] for p in c], closed=True, fc=colours[int(t)], ec="black", alpha=0.85, + zorder=4, label=None if t in seen else names[int(t)])) + seen.add(t) + if v > 0: + d = f * v / 3.6 * 0.5 + ax.arrow(y, x, d[1], d[0], width=0.15, color="black", zorder=5) + ro, pa, wp = map(np.array, (sample["route_original"], sample["route"], sample["waypoints"])) + ax.plot(ro[:, 1], ro[:, 0], "o", ms=3, color="#1f77b4", label="input: route_original", zorder=6) + ax.plot(pa[:, 1], pa[:, 0], "-", lw=2, color="#ff4500", label="output: path (20 pts)", zorder=7) + ax.plot(wp[:, 1], wp[:, 0], "s", ms=4, color="#2ca02c", mec="black", label="output: waypoints (8 @ 4 Hz)", zorder=8) + xmax = max(40, float(np.max([r[1] for r in sample["input"]] + [30])) + 8) + ax.set_xlim(-30, 30); ax.set_ylim(-35, min(xmax, 105)) + ax.set_xlabel("y (m, right +)"); ax.set_ylabel("x (m, forward +)") + ax.set_title(title, fontsize=9) + ax.legend(fontsize=6.5, loc="lower left", framealpha=0.9) + ax.set_aspect("equal") + fig.tight_layout() + fig.savefig(path, dpi=130) + plt.close(fig) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", required=True) + ap.add_argument("--route-dir", help="real dataset route folder (boxes/, measurements/, bev_no_car_semantics/)") + ap.add_argument("--frames", type=int, nargs="*", default=[20, 60, 100]) + ap.add_argument("--plant2-repo", help="plant2 clone, to load the full static extent tables") + ap.add_argument("--save-npy", action="store_true", help="also write the exact float32 BEV tensor as .npy") + args = ap.parse_args() + if args.plant2_repo: + P.load_full_extent_tables(args.plant2_repo) + + built = [] + if args.route_dir: + name = os.path.basename(args.route_dir.rstrip("/")) + for t in args.frames: + sample, dropped, raw = P.load_real_sample(args.route_dir, t) + rid = f"{name}_{t:04d}" + built.append((rid, write_record(args.out, rid, f"{name} frame {t}", sample, dropped, raw, + f"PlanT 2.0 dataset, {args.route_dir}, frame {t}", args.save_npy), sample)) + else: + for sc in scenarios(): + sample, dropped, raw = build_synthetic(sc) + built.append((sc["id"], write_record( + args.out, sc["id"], sc["title"], sample, dropped, raw, + "Hand-built scene (not from a CARLA run), processed with the PlanT 2.0 input pipeline " + "(ported from PlanT/dataset.py). Outputs are expert-style targets, not model predictions.", args.save_npy), sample)) + + batch = P.generate_batch([s for _, _, s in built]) + summary = { + "records": [rid for rid, _, _ in built], + "batch_shapes": {k: {"shape": list(v.shape), "dtype": str(v.dtype)} for k, v in batch.items()}, + "batch_idxs": batch["idxs"].tolist(), + "x_objs_first_rows": rnd(batch["x_objs"][:6].tolist()), + } + with open(os.path.join(args.out, "batch_example.json"), "w") as f: + json.dump(summary, f, indent=1) + for rid, rec, _ in built: + print(f"{rid}: {rec['model_input']['x_objs']['shape'][0]} objects, " + f"{len(rec['model_input']['dropped_objects'])} dropped, speed_limit idx {rec['model_input']['speed_limit']['value']}, " + f"desired {rec['controller']['desired_speed_mps']} m/s") + print("batch:", summary["batch_shapes"]) + + +if __name__ == "__main__": + main() diff --git a/src/planning/plant2_io/plant2_pipeline.py b/src/planning/plant2_io/plant2_pipeline.py new file mode 100644 index 0000000..06257b0 --- /dev/null +++ b/src/planning/plant2_io/plant2_pipeline.py @@ -0,0 +1,361 @@ +""" +Numpy-only port of the PlanT 2.0 input/target pipeline. + +Everything in here mirrors code in autonomousvision/plant2 so the records we +produce have exactly the layout the model sees. Each function names the file +and function it was ported from. Nothing here needs torch or CARLA. + +Config values match PlanT/config/model/PlanT.yaml (the released config). +""" +import gzip +import json +import os + +import numpy as np + +# --------------------------------------------------------------------------- +# Config (PlanT/config/model/PlanT.yaml + PlanT/plant_variables.py) +# --------------------------------------------------------------------------- +RANGE = 50 # training.range (m, sides/behind) +RANGE_FACTOR_FRONT = 2 # training.range_factor_front (front ellipse = 100 m) +PRECISION_POS = 7 # pre_training.precision_pos -> 128 bins +PRECISION_ANGLE = 5 # pre_training.precision_angle -> 32 bins +PRECISION_SPEED = 5 # pre_training.precision_speed -> 32 bins +WPS_LEN = 8 # waypoints.wps_len (4 Hz -> 2 s horizon) +PATH_LEN = 20 # waypoints.path_len (1 m spacing) +SEQ_LEN = 1 # training.seq_len + +BEV_COLORS = np.array([ + [0.485, 0.456, 0.406], # 0 background (ImageNet mean) + [0.25, 0.25, 0.75], # 1 road + [0.485, 0.456, 0.406], # 2 sidewalk (same as background) + [0.75, 0.25, 0.25], # 3 solid lane markings + [0.25, 0.75, 0.25], # 4 broken lane markings +], dtype=np.float32) + +SPEED_CATS = {50: 0, 80: 1, 100: 2, 120: 3} # km/h -> speed-limit token index + +CLASS_NUMS = { # object class -> type index (0 = padding) + "car": 1.0, + "walker": 2.0, + "static": 3.0, + "static_car": 1.0, # parked cars share the vehicle projection + "stop_sign": 4.0, + "traffic_light": 5.0, + "emergency": 6.0, +} +CAR_TYPES = ["car", "walker", "emergency"] # "dynamic" classes (carry speed + id) + +TARGET_SPEEDS = [0.0, 4.0, 8.0, 10, 13.88888888, 16, 17.77777777, 20] # m/s, only used by PATH variant + +EMERGENCY_TYPE_IDS = [ + "vehicle.dodge.charger_police", + "vehicle.dodge.charger_police_2020", + "vehicle.carlamotors.firetruck", + "vehicle.ford.ambulance", +] +RELEVANT_STATIC_TYPE_IDS = ["static.prop.constructioncone", "static.prop.trafficwarning"] + +# Subset of PlanT/util/static_extents.py (CARLA reports wrong extents for statics). +# Pass --plant2-repo to load the full tables instead. +STATIC_EXTENTS = { + "static.prop.constructioncone": [0.1720348298549652, 0.1720348298549652, 0.2928849756717682], + "static.prop.trafficwarning": [1.186714768409729, 1.4352929592132568, 1.784761667251587], +} +CAR_EXTENTS = { + "/Game/Carla/Static/Car/4Wheeled/ParkedVehicles/Lincoln/SM_LincolnParked.SM_LincolnParked": + [2.44619083404541, 1.115301489830017, 0.7606233954429626], +} + + +def load_full_extent_tables(repo_root): + """Replace the embedded extent subset with PlanT/util/static_extents.py.""" + ns = {} + with open(os.path.join(repo_root, "PlanT", "util", "static_extents.py")) as f: + exec(f.read(), ns) + STATIC_EXTENTS.clear(); STATIC_EXTENTS.update(ns["STATIC_EXTENTS"]) + CAR_EXTENTS.clear(); CAR_EXTENTS.update(ns["CAR_EXTENTS"]) + + +# --------------------------------------------------------------------------- +# Small helpers (PlanT/dataset.py) +# --------------------------------------------------------------------------- +def normalize_angle_degree(x): + x = x % 360.0 + if isinstance(x, np.ndarray): + x[x > 180] -= 360 + elif x > 180.0: + x -= 360.0 + return x + + +def rad2deg(theta): + return float(normalize_angle_degree(np.rad2deg(theta).item())) + + +def interpolate_route(points): + """dataset.interpolate_route: resample route to 20 points 1 m apart (arc length).""" + points = np.asarray(points, dtype=np.float64) + route = np.concatenate((np.zeros_like(points[:1]), points)) + shift = np.roll(route, 1, axis=0) + shift[0] = shift[1] + dists = np.linalg.norm(route - shift, axis=1) + dists = np.cumsum(dists) + dists += np.arange(0, len(dists)) * 1e-4 + x = np.arange(0, 20, 1) + return np.array([np.interp(x, dists, route[:, 0]), np.interp(x, dists, route[:, 1])]).T + + +def quantize_box(boxes): + """dataset.PlanTDataset.quantize_box: [x, y, yaw_deg, speed_kmh] floats -> int bins (-999 kept).""" + boxes = np.array(boxes, dtype=np.float64) + if len(boxes) == 0: + return [] + max_d, max_dd = RANGE, 2 * RANGE + dummy = boxes == -999 + boxes[:, 0] = (boxes[:, 0] + max_d) / max_dd + boxes[:, 1] = (boxes[:, 1] + max_d) / max_dd + boxes[:, 2] = (boxes[:, 2] % 360) / 360 + boxes[:, 3] = boxes[:, 3] / 120 + boxes[:, 0] = np.clip(boxes[:, 0], 0, (1 + RANGE_FACTOR_FRONT) / 2) + boxes[:, 1:] = np.clip(boxes[:, 1:], 0, 1) + size_pos, size_speed, size_angle = 2 ** PRECISION_POS, 2 ** PRECISION_SPEED, 2 ** PRECISION_ANGLE + boxes[:, :2] = (boxes[:, :2] * (size_pos - 1)).round() + boxes[:, 2] = (boxes[:, 2] * (size_angle - 1)).round() + boxes[:, 3] = (boxes[:, 3] * (size_speed - 1)).round() + boxes[dummy] = -999 + return boxes.astype(np.int32).tolist() + + +def bev_classes_to_tensor(class_map_128): + """BEV class indices (128x128, values 0..4) -> float32 tensor [3,128,128] (bev_colors lookup).""" + return BEV_COLORS[class_map_128.astype(np.int64)].transpose(2, 0, 1).astype(np.float32) + + +def raw_bev_png_to_classes(png_array): + """dataset.__getitem__ BEV branch: raw 256x256 PNG -> rot90 -> crop [64:-64] -> 128x128 class map.""" + arr = png_array if png_array.ndim == 3 else png_array[None] # CHW like pil_to_tensor + arr = np.rot90(arr, axes=(1, 2)) + return np.ascontiguousarray(arr[0, 64:-64, 64:-64]) + + +# --------------------------------------------------------------------------- +# Object encoding (port of the object block in dataset.PlanTDataset.__getitem__) +# --------------------------------------------------------------------------- +def encode_objects(labels_data, input_static_cars=True): + """ + labels_data: CARLA-style box dicts in the ego frame (ego entry already removed). + Returns (input_objects_with_id, dropped) where each row is + [type, x, y, yaw_deg, speed_kmh, width, length, id] + and dropped is a list of {id, class, reason} for documentation. + """ + type_nums = dict(CLASS_NUMS) + if not input_static_cars: + type_nums.pop("static_car") + + labels_data = [dict(x) for x in labels_data] # don't mutate caller's data + dropped = [] + + for x in labels_data: + orig_class = x["class"] + if "position" in x: + px, py, pz = x["position"] + if x["class"] in ["traffic_light", "stop_sign"]: + if px ** 2 + py ** 2 > 30 ** 2 or abs(pz) > 30: + x["class"] = "too far" + else: + x_div = RANGE_FACTOR_FRONT ** 2 if px > 0 else 1 + if px ** 2 / x_div + py ** 2 > RANGE ** 2 or abs(pz) > 30: + x["class"] = "too far" + + if x["class"] == "car" and x.get("type_id") in EMERGENCY_TYPE_IDS: + x["class"] = "emergency" + elif x["class"] == "static": + if "type_id" in x and x["type_id"] not in RELEVANT_STATIC_TYPE_IDS: + x["class"] = "irrelevant_static" + elif x["type_id"] in STATIC_EXTENTS: + x["extent"] = STATIC_EXTENTS[x["type_id"]] + elif x["class"] == "static_car": + if x["mesh_path"] in CAR_EXTENTS: + x["extent"] = CAR_EXTENTS[x["mesh_path"]] + if x.get("scale") is not None: + x["extent"] = [a * float(x["scale"]) for a in x["extent"]] + + x["_orig_class"] = orig_class + + rows = [ + [ + type_nums[x["class"].lower()], + x["position"][0], + x["position"][1], + rad2deg(x["yaw"]), + x["speed"] * 3.6, + x["extent"][1] * 2 + (0 if "scenario" not in x or "Door" not in (x["scenario"] or "") else 1), + x["extent"][0] * 2, + x["id"], + ] + for x in labels_data + if x["class"].lower() in CAR_TYPES + ] + + def keep_static(x): + c = x["class"].lower() + if c in CAR_TYPES or c not in type_nums: + return False + if c == "traffic_light" and not (x["state"] in ["Red", "Yellow"] and x["affects_ego"]): + return False + if c == "stop_sign" and not x["affects_ego"]: + return False + return True + + rows += [ + [ + type_nums[x["class"].lower()], + x["position"][0], + x["position"][1], + rad2deg(x["yaw"]), + 0.0, + x["extent"][1] * 2, + x["extent"][0] * 2, + -1 if x["class"].lower() != "static_car" else -999, + ] + for x in labels_data + if keep_static(x) + ] + + for x in labels_data: + c = x["class"].lower() + if c in CAR_TYPES or keep_static(x): + continue + if c == "too far": + reason = "outside input range (50 m circle behind / 100x50 m ellipse ahead; 30 m for lights & stop signs)" + elif c == "irrelevant_static": + reason = "static prop that is not a construction cone / traffic warning" + elif c == "traffic_light": + reason = ("red/yellow light that does not affect the ego lane" if x.get("state") in ["Red", "Yellow"] + else f"{x.get('state')} light (only Red/Yellow lights are input)") + elif c == "stop_sign": + reason = "stop sign does not affect ego" + else: + reason = f"class '{c}' not in the model's class list" + dropped.append({"id": x.get("id"), "class": x["_orig_class"], "reason": reason}) + + return rows, dropped + + +def forecast_targets(input_rows, next_frame_objects_in_current_ego): + """ + dataset.__getitem__ forecasting block. next_frame_objects maps id -> [x, y, yaw_deg, speed_kmh] + already expressed in the *current* ego frame (that is what output_input_tf does). + """ + matched = [] + for row in input_rows: + oid = row[-1] + if oid == -999: # parked car: doesn't move + matched.append(row[1:5]) + elif oid in next_frame_objects_in_current_ego: + matched.append(next_frame_objects_in_current_ego[oid]) + else: # lights, stop signs, statics, vanished actors + matched.append([-999.0, -999.0, -999.0, -999.0]) + return matched, quantize_box(matched) + + +# --------------------------------------------------------------------------- +# Batching (port of dataset.generate_batch, numpy instead of torch) +# --------------------------------------------------------------------------- +def generate_batch(samples): + """Returns a dict with the same keys/shapes/dtypes generate_batch builds (as numpy).""" + maxseq = max(len(s["input"]) for s in samples) + B = len(samples) + x_objs = [[0, 0, 0, 0, 0, 0, 0]] # row 0 = shared padding row + y_objs = [[-999, -999, -999, -999]] + idxs = np.zeros((B, maxseq), dtype=np.int32) + n = 1 + for i, s in enumerate(samples): + k = len(s["input"]) + idxs[i, :k] = np.arange(n, n + k) + n += k + x_objs.extend(s["input"]) + y_objs.extend(s.get("output", [[-999] * 4] * k)) + out = { + "idxs": idxs, # int32 [B, maxN] + "x_objs": np.array(x_objs, dtype=np.float32), # float32 [1+sumN, 7] + "y_objs": np.array(y_objs, dtype=np.int64), # int64 [1+sumN, 4] + "route_original": np.array([s["route_original"] for s in samples], dtype=np.float32), # [B,20,2] + "speed_limit": np.array([s["speed_limit"] for s in samples], dtype=np.int32), # [B] + } + if all("BEV" in s for s in samples): + out["BEV"] = np.stack([s["BEV"] for s in samples]).astype(np.float32) # [B,3,128,128] + for key in ["route", "waypoints", "target_speed", "ego_speed"]: + if all(key in s for s in samples): + out[key] = np.array([s[key] for s in samples], dtype=np.float32) + return out + + +# --------------------------------------------------------------------------- +# Controller-side post-processing (PlanT/PlanT_agent.py::_get_control) +# --------------------------------------------------------------------------- +def desired_speed_from_wps(pred_wps, ego_speed): + """Target speed the longitudinal controller gets for the path+wps model.""" + pred_wps = np.asarray(pred_wps) + desired = float(np.linalg.norm(pred_wps[2] - pred_wps[3]) * 4.0) + mean_speed = float(np.linalg.norm(pred_wps[:-1] - pred_wps[1:], axis=-1).mean() * 4.0) + creep = ego_speed < 0.01 + if creep: + desired = min(mean_speed, 0.1) + return desired, creep + + +# --------------------------------------------------------------------------- +# Real dataset loader (dataset.PlanTDataset.__getitem__ without augmentation) +# --------------------------------------------------------------------------- +def load_real_sample(route_dir, seq, with_bev=True): + """ + route_dir: one route folder of the PlanT 2.0 dataset (contains boxes/, measurements/, + bev_no_car_semantics/). seq: frame index t (needs t+1..t+8 to exist). + Returns (sample, dropped, raw) in the same structure as the synthetic records. + """ + from PIL import Image + + def jload(p): + with gzip.open(p, "rt", encoding="utf-8") as f: + return json.load(f) + + n = SEQ_LEN + WPS_LEN + meas = [jload(os.path.join(route_dir, "measurements", f"{seq + i:04d}.json.gz")) for i in range(n)] + boxes = [jload(os.path.join(route_dir, "boxes", f"{seq + i:04d}.json.gz")) for i in range(n)] + m0, b0 = meas[SEQ_LEN - 1], boxes[SEQ_LEN - 1] + + mats = [x["ego_matrix"] for x in meas[SEQ_LEN - 1:]] + ego_inv = np.linalg.inv(mats[0]) + pts = np.array(mats[1:])[:, :, 3] + waypoints = (ego_inv @ pts.T).T[:, :2].tolist() + + sample = { + "waypoints": waypoints, + "route_original": m0["route_original"][:20], + "route": interpolate_route(m0["route"][:20]).tolist(), + "target_speed": 0.0 if m0["brake"] else m0["target_speed"], + "ego_speed": m0["speed"], + "speed_limit": SPEED_CATS[round(m0["speed_limit"] * 3.6)], + } + if with_bev: + png = np.array(Image.open(os.path.join(route_dir, "bev_no_car_semantics", f"{seq + SEQ_LEN - 1:04d}.png"))) + png = png.transpose(2, 0, 1) if png.ndim == 3 else png[None] + sample["bev_classes"] = raw_bev_png_to_classes(png) + sample["BEV"] = bev_classes_to_tensor(sample["bev_classes"]) + + rows, dropped = encode_objects(b0[1:]) + # forecasting: next frame boxes transformed into current ego frame + m1, b1 = meas[SEQ_LEN], boxes[SEQ_LEN] + tf = np.linalg.inv(np.array(m0["ego_matrix"])) @ np.array(m1["ego_matrix"]) + dyaw = m0["theta"] - m1["theta"] + nxt = {x["id"]: [*(tf @ np.append(x["position"], [1]))[:2], rad2deg(x["yaw"] - dyaw), x["speed"] * 3.6] + for x in b1 if "id" in x and "speed" in x} + floating, quant = forecast_targets(rows, nxt) + sample["output_floating"] = floating + sample["output"] = quant + sample["input_with_ids"] = rows + sample["input"] = [r[:-1] for r in rows] + raw = {"measurements": m0, "boxes": b0} + return sample, dropped, raw