ConsDrive / team_code /oracle_noise.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
7.96 kB
"""Detector / tracker error model for the oracle object source.
Ablation tool for sizing stage 2: corrupts the privileged observations the way a camera tracker would
before they enter the ObjectBank, so the bank's memory and constant-velocity coasting propagate the
errors exactly as they would with a real tracker. Per-object errors are AR(1) processes (a detector's
depth error for one object drifts slowly rather than flickering at 20 Hz); misses come in bursts;
false positives are short-lived ghosts; identity switches start a new track while the old one coasts.
Tracks that are lost after less than `confirm_s` of visibility are deleted, like tentative tracks.
"""
import math
import numpy as np
from dataloader.object_bank import (
CLASS_CAR, CLASS_STATIC, CLASS_WALKER, RAW_AGE, RAW_UNSEEN, RAW_VISIBLE, Observation,
ego_to_world, world_to_ego,
)
NOISE_PRESETS = {
# Roughly a good camera-only 3D tracker (nuScenes-class mATE ~0.5 m, mAOE ~0.3 rad, mAVE ~0.4 m/s
# averaged over range), with errors growing with distance from the camera.
"realistic": dict(
range_sigma=(0.2, 0.03), # radial position std = a + b * range [m]
lateral_sigma=(0.1, 0.01), # tangential position std = a + b * range [m]
yaw_sigma_deg=(8.0, 30.0), # vehicles and statics, walkers
speed_sigma=(0.3, 0.1), # a + b * speed [m/s]
extent_sigma=0.1, # multiplicative, constant per object
noise_tau=0.5, # AR(1) time constant of the per-object errors [s]
miss_rate=(0.05, 0.30), # stationary miss probability up to 20 m and at 50 m
miss_duration=0.5, # mean length of a miss burst [s]
fp_rate=0.3, # ghost detections per second
fp_duration=0.3, # mean ghost lifetime [s]
id_switch_rate=0.02, # per tracked object per second
confirm_s=0.5,
),
# A weak monocular detector (mATE ~1 m): about twice the realistic errors, longer miss bursts,
# three times the ghosts and frequent identity switches.
"harsh": dict(
range_sigma=(0.4, 0.06),
lateral_sigma=(0.2, 0.02),
yaw_sigma_deg=(15.0, 45.0),
speed_sigma=(0.6, 0.2),
extent_sigma=0.2,
noise_tau=0.5,
miss_rate=(0.15, 0.50),
miss_duration=1.0,
fp_rate=1.0,
fp_duration=0.5,
id_switch_rate=0.1,
confirm_s=0.5,
),
}
GHOST_ID_OFFSET = 3_000_000 # ghosts get ids -(offset + k)
ALIAS_ID_OFFSET = 10_000_000 # identity switches get ids offset + k
GHOST_EXTENTS = {CLASS_CAR: (2.3, 1.0, 0.75), CLASS_WALKER: (0.3, 0.3, 0.9), CLASS_STATIC: (0.5, 0.5, 0.5)}
class _ObjectNoise:
__slots__ = ("z", "extent_scale", "missed", "alias", "last_t")
def __init__(self, rng, extent_sigma, alias, t):
self.z = rng.standard_normal(4) # radial, lateral, yaw, speed (unit variance)
self.extent_scale = np.clip(1.0 + extent_sigma * rng.standard_normal(2), 0.5, 1.5)
self.missed = False
self.alias = alias
self.last_t = t
class TrackerNoise:
def __init__(self, preset="realistic", seed=0, **overrides):
if preset not in NOISE_PRESETS:
raise ValueError(f"unknown noise preset {preset!r}; options: {sorted(NOISE_PRESETS)}")
self.params = dict(NOISE_PRESETS[preset], **overrides)
self.preset = preset
self.seed = int(seed)
self.reset()
def reset(self):
self.rng = np.random.default_rng(self.seed)
self.objects = {}
self.ghosts = []
self.last_t = None
self._next_alias = ALIAS_ID_OFFSET
self._next_ghost = GHOST_ID_OFFSET
def _miss_rate(self, r):
near, far = self.params["miss_rate"]
return near + (far - near) * float(np.clip((r - 20.0) / 30.0, 0.0, 1.0))
def apply(self, t, observations, ego_xy, ego_yaw, camera_x=-1.5):
p = self.params
dt = 0.05 if self.last_t is None else max(t - self.last_t, 0.0)
self.last_t = t
a = math.exp(-dt / p["noise_tau"])
b = math.sqrt(max(1.0 - a * a, 0.0))
p_recover = 1.0 - math.exp(-dt / p["miss_duration"])
p_switch = 1.0 - math.exp(-dt * p["id_switch_rate"])
cam = np.array([camera_x, 0.0])
out = []
for obs in observations:
st = self.objects.get(obs.obj_id)
if st is None:
st = self.objects[obs.obj_id] = _ObjectNoise(self.rng, p["extent_sigma"], obs.obj_id, t)
else:
st.z = a * st.z + b * self.rng.standard_normal(4)
st.last_t = t
rel = world_to_ego(obs.world_xy, ego_xy, ego_yaw)[0]
d = rel - cam
r = max(float(np.hypot(*d)), 1e-3)
u = d / r
m = min(self._miss_rate(r), 0.95)
if st.missed:
st.missed = self.rng.random() >= p_recover
else:
st.missed = self.rng.random() < m / (1.0 - m) * p_recover
if st.missed:
continue
if self.rng.random() < p_switch:
st.alias = self._next_alias
self._next_alias += 1
sigma_r = p["range_sigma"][0] + p["range_sigma"][1] * r
sigma_l = p["lateral_sigma"][0] + p["lateral_sigma"][1] * r
noisy_rel = rel + u * st.z[0] * sigma_r + np.array([-u[1], u[0]]) * st.z[1] * sigma_l
yaw_sigma = math.radians(p["yaw_sigma_deg"][1 if obs.cls == CLASS_WALKER else 0])
speed = 0.0
if obs.cls != CLASS_STATIC:
speed = max(0.0, obs.speed + st.z[3] * (p["speed_sigma"][0] + p["speed_sigma"][1] * obs.speed))
out.append(Observation(
obj_id=st.alias, cls=obs.cls, world_xy=ego_to_world(noisy_rel, ego_xy, ego_yaw)[0],
world_yaw=obs.world_yaw + st.z[2] * yaw_sigma, speed=speed,
length=obs.length * st.extent_scale[0], width=obs.width * st.extent_scale[1], height=obs.height))
# forget per-object state of objects that have been out of range for a while
stale = [k for k, st in self.objects.items() if t - st.last_t > 30.0]
for k in stale:
del self.objects[k]
out.extend(self._ghosts(t, dt, ego_xy, ego_yaw, cam))
return out
def _ghosts(self, t, dt, ego_xy, ego_yaw, cam):
p = self.params
self.ghosts = [g for g in self.ghosts if g["t_end"] > t]
for _ in range(self.rng.poisson(p["fp_rate"] * dt)):
r = self.rng.uniform(5.0, 45.0)
bearing = math.radians(self.rng.uniform(-40.0, 40.0))
rel = cam + r * np.array([math.cos(bearing), math.sin(bearing)])
cls = int(self.rng.choice([CLASS_CAR, CLASS_WALKER, CLASS_STATIC], p=[0.7, 0.2, 0.1]))
speed = {CLASS_CAR: self.rng.uniform(0.0, 10.0), CLASS_WALKER: self.rng.uniform(0.0, 1.5)}.get(cls, 0.0)
self.ghosts.append(dict(
obj_id=-self._next_ghost, cls=cls, world_xy=ego_to_world(rel, ego_xy, ego_yaw)[0],
world_yaw=ego_yaw + self.rng.normal(0.0, 0.3), speed=speed,
extent=GHOST_EXTENTS[cls], t_end=t + self.rng.exponential(p["fp_duration"])))
self._next_ghost += 1
return [Observation(obj_id=g["obj_id"], cls=g["cls"], world_xy=g["world_xy"], world_yaw=g["world_yaw"],
speed=g["speed"], length=g["extent"][0], width=g["extent"][1], height=g["extent"][2])
for g in self.ghosts]
def filter_rows(self, raw, ids, count):
"""Drop lost tracks that were never confirmed (visible for less than confirm_s)."""
rows = raw[:count]
keep = (rows[:, RAW_VISIBLE] > 0.5) | (rows[:, RAW_AGE] - rows[:, RAW_UNSEEN] >= self.params["confirm_s"])
out_raw = np.zeros_like(raw)
out_ids = np.zeros_like(ids)
n = int(keep.sum())
out_raw[:n] = rows[keep]
out_ids[:n] = ids[:count][keep]
return out_raw, out_ids, n