File size: 10,629 Bytes
314ecfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Multi-object tracker turning per-frame 3D detections into object-bank rows (stage-2 perception).

Each track is a constant-velocity Kalman filter in the world frame whose measurements are the
detector's position (anisotropic: depth uncertainty along the viewing ray, small across it) and its
two-frame velocity, both with the detector's predicted uncertainties. Detections are associated by
Hungarian matching on the Mahalanobis distance of the position. Confirmation and deletion are
defined in seconds so the same settings work for 4 Hz logs and the 20 Hz closed loop.

Rows are rendered like dataloader.object_bank.ObjectBank: ego frame, nearest first, RAW_VISIBLE when
the track was detected this frame, RAW_UNSEEN / RAW_AGE in seconds.
"""
from dataclasses import dataclass, field

import numpy as np
from scipy.optimize import linear_sum_assignment

from dataloader.object_bank import (
    CLASS_STATIC, CLASS_WALKER, NUM_CLASSES, RAW_AGE, RAW_CLASS, RAW_DIM, RAW_LENGTH, RAW_SPEED, RAW_UNSEEN,
    RAW_VISIBLE, RAW_WIDTH, RAW_X, RAW_Y, RAW_YAW, normalize_angle, world_to_ego,
)

CHI2_GATE_2D = 13.8  # 99.9 % for 2 dof


@dataclass
class Detection:
    """One detection in the world frame."""
    xy: np.ndarray  # (2,)
    pos_cov: np.ndarray  # (2, 2)
    vel: np.ndarray  # (2,)
    vel_cov: np.ndarray  # (2, 2)
    yaw: float
    half_l: float
    half_w: float
    cls: int
    score: float


@dataclass
class TrackerConfig:
    max_objects: int = 32
    birth_score: float = 0.35  # minimum detection score that may start a track
    confirm_s: float = 0.2  # a tentative track needs >= 2 hits spanning this long
    tentative_timeout_s: float = 0.3  # tentative tracks unseen this long are dropped
    max_coast_s: float = 2.0  # confirmed tracks are coasted this long after their last detection
    full_coast_hits: int = 0  # tracks with fewer hits than this coast only short_coast_s (0 = off)
    short_coast_s: float = 0.5
    max_keep_distance: float = 80.0
    max_behind_distance: float = 20.0
    camera_x: float = -1.5
    accel_sigma: tuple = (3.0, 1.5, 0.3)  # process noise per class (car, walker, static), m/s^2
    moving_speed: float = 1.0  # above this the heading follows the velocity
    extent_alpha: float = 0.2


@dataclass
class _Track:
    track_id: int
    x: np.ndarray  # px, py, vx, vy (world)
    P: np.ndarray
    yaw: float
    half_l: float
    half_w: float
    class_score: np.ndarray
    first_seen: float
    last_seen: float
    last_t: float
    hits: int = 1
    confirmed: bool = False
    detected_now: bool = True
    extras: dict = field(default_factory=dict)

    @property
    def cls(self):
        return int(np.argmax(self.class_score))


def _vehicle_like(c):
    return c != CLASS_WALKER


class Tracker:
    def __init__(self, config: TrackerConfig = None):
        self.cfg = config or TrackerConfig()
        self.reset()

    def reset(self):
        self.tracks = []
        self._next_id = 1

    # ------------------------------------------------------------------ kalman
    def _predict(self, tr, t):
        dt = t - tr.last_t
        if dt <= 0:
            return
        F = np.eye(4)
        F[0, 2] = F[1, 3] = dt
        q = self.cfg.accel_sigma[min(tr.cls, NUM_CLASSES - 1)] ** 2
        g = np.array([0.5 * dt * dt, dt])
        Q1 = np.outer(g, g) * q
        Q = np.zeros((4, 4))
        Q[np.ix_([0, 2], [0, 2])] = Q1
        Q[np.ix_([1, 3], [1, 3])] = Q1
        tr.x = F @ tr.x
        tr.P = F @ tr.P @ F.T + Q
        tr.last_t = t

    def _update(self, tr, det, t):
        z = np.concatenate((det.xy, det.vel))
        R = np.zeros((4, 4))
        R[:2, :2], R[2:, 2:] = det.pos_cov, det.vel_cov
        S = tr.P + R
        K = tr.P @ np.linalg.inv(S)
        tr.x = tr.x + K @ (z - tr.x)
        tr.P = (np.eye(4) - K) @ tr.P
        speed = float(np.hypot(tr.x[2], tr.x[3]))
        if speed > self.cfg.moving_speed:
            tr.yaw = float(np.arctan2(tr.x[3], tr.x[2]))
        else:
            # appearance heading is ambiguous front/back; keep the hypothesis closest to the track's
            d = normalize_angle(det.yaw - tr.yaw)
            if abs(d) > np.pi / 2:
                d = normalize_angle(d + np.pi)
            tr.yaw = normalize_angle(tr.yaw + 0.3 * d)
        a = self.cfg.extent_alpha
        tr.half_l = (1 - a) * tr.half_l + a * det.half_l
        tr.half_w = (1 - a) * tr.half_w + a * det.half_w
        tr.class_score[det.cls] += det.score
        tr.hits += 1
        tr.last_seen = t
        tr.detected_now = True
        if not tr.confirmed and t - tr.first_seen >= self.cfg.confirm_s - 1e-6:
            tr.confirmed = True

    def _new_track(self, det, t):
        P = np.zeros((4, 4))
        P[:2, :2] = det.pos_cov
        P[2:, 2:] = det.vel_cov + np.eye(2) * 1.0
        class_score = np.zeros(NUM_CLASSES)
        class_score[det.cls] = det.score
        tr = _Track(self._next_id, np.concatenate((det.xy, det.vel)), P, det.yaw, det.half_l, det.half_w,
                    class_score, t, t, t)
        if np.hypot(*det.vel) > self.cfg.moving_speed:
            tr.yaw = float(np.arctan2(det.vel[1], det.vel[0]))
        self._next_id += 1
        self.tracks.append(tr)

    # ------------------------------------------------------------------ step
    def step(self, t, detections, ego_xy, ego_yaw):
        """Advance to time t with this frame's detections; returns (raw rows, ids, count)."""
        for tr in self.tracks:
            self._predict(tr, t)
            tr.detected_now = False
        self._associate(detections, t)
        self._prune(t, ego_xy, ego_yaw)
        return self._render(t, ego_xy, ego_yaw)

    def _associate(self, detections, t):
        if not detections:
            return
        n_t, n_d = len(self.tracks), len(detections)
        matched_det = np.zeros(n_d, dtype=bool)
        if n_t:
            cost = np.full((n_t, n_d), 1e6)
            for i, tr in enumerate(self.tracks):
                for j, det in enumerate(detections):
                    if _vehicle_like(tr.cls) != _vehicle_like(det.cls):
                        continue
                    d = det.xy - tr.x[:2]
                    S = tr.P[:2, :2] + det.pos_cov
                    m = float(d @ np.linalg.solve(S, d))
                    if m < CHI2_GATE_2D:
                        # confirmed tracks win ties against tentative ones
                        cost[i, j] = m + (0.0 if tr.confirmed else 2.0)
            rows, cols = linear_sum_assignment(cost)
            for i, j in zip(rows, cols):
                if cost[i, j] < 1e5:
                    self._update(self.tracks[i], detections[j], t)
                    matched_det[j] = True
        for j, det in enumerate(detections):
            if not matched_det[j] and det.score >= self.cfg.birth_score:
                self._new_track(det, t)

    def _prune(self, t, ego_xy, ego_yaw):
        keep = []
        for tr in self.tracks:
            unseen = t - tr.last_seen
            if not tr.confirmed and unseen > self.cfg.tentative_timeout_s:
                continue
            if tr.confirmed and unseen > self.cfg.max_coast_s:
                continue
            if tr.confirmed and tr.hits < self.cfg.full_coast_hits and unseen > self.cfg.short_coast_s:
                continue
            rel = world_to_ego(tr.x[:2], ego_xy, ego_yaw)[0]
            if np.hypot(rel[0] - self.cfg.camera_x, rel[1]) > self.cfg.max_keep_distance \
                    or rel[0] < -self.cfg.max_behind_distance:
                continue
            keep.append(tr)
        self.tracks = keep

    def render(self, t, ego_xy, ego_yaw, t_obs):
        """Rows at time t between updates, state untouched: positions extrapolated from the last update,
        visibility / time unseen / age as of the last update t_obs (the layout the 4 Hz banks have)."""
        return self._render(t, ego_xy, ego_yaw, t_obs)

    def _render(self, t, ego_xy, ego_yaw, t_obs=None):
        t_obs = t if t_obs is None else t_obs
        n = self.cfg.max_objects
        raw = np.zeros((n, RAW_DIM), dtype=np.float32)
        ids = np.zeros(n, dtype=np.int64)
        rows = []
        for tr in self.tracks:
            if not tr.confirmed:
                continue
            xy = tr.x[:2] + tr.x[2:] * max(t - tr.last_t, 0.0)
            rel = world_to_ego(xy, ego_xy, ego_yaw)[0]
            rows.append((float(np.hypot(rel[0] - self.cfg.camera_x, rel[1])), rel, tr))
        rows.sort(key=lambda r: r[0])
        count = min(len(rows), n)
        for k, (_, rel, tr) in enumerate(rows[:count]):
            cls = tr.cls
            raw[k, RAW_X], raw[k, RAW_Y] = rel
            raw[k, RAW_YAW] = normalize_angle(tr.yaw - ego_yaw)
            raw[k, RAW_SPEED] = 0.0 if cls == CLASS_STATIC else float(np.hypot(tr.x[2], tr.x[3]))
            raw[k, RAW_LENGTH], raw[k, RAW_WIDTH] = tr.half_l, tr.half_w
            raw[k, RAW_CLASS] = cls
            raw[k, RAW_VISIBLE] = 1.0 if tr.detected_now else 0.0
            raw[k, RAW_UNSEEN] = t_obs - tr.last_seen
            raw[k, RAW_AGE] = t_obs - tr.first_seen
            ids[k] = tr.track_id
        return raw, ids, count


def detections_to_world(det, ego_xy, ego_yaw, camera_x=-1.5, min_depth_sigma=0.15):
    """Decoded detector output for one image (dict of 1-D numpy arrays, ego frame) -> [Detection]."""
    out = []
    c, s = np.cos(ego_yaw), np.sin(ego_yaw)
    R_ego = np.array([[c, -s], [s, c]])
    for k in range(len(det["x"])):
        x, y = float(det["x"][k]), float(det["y"][k])
        rng = float(np.hypot(x - camera_x, y))
        ray = np.arctan2(y, x - camera_x)
        # Laplace scale b -> standard deviation sqrt(2) b
        sr = max(np.sqrt(2.0) * float(det["depth_sigma"][k]) / max(np.cos(ray), 0.3), min_depth_sigma)
        st = 0.05 + 0.01 * rng
        cr, sn = np.cos(ray), np.sin(ray)
        Rr = np.array([[cr, -sn], [sn, cr]])
        pos_cov_ego = Rr @ np.diag((sr * sr, st * st)) @ Rr.T
        sv = np.sqrt(2.0) * np.asarray(det["velocity_sigma"][k], dtype=np.float64)
        vel_cov_ego = np.diag(np.maximum(sv, 0.1) ** 2)
        xy_w = R_ego @ np.array((x, y)) + np.asarray(ego_xy, dtype=np.float64)
        out.append(Detection(
            xy=xy_w, pos_cov=R_ego @ pos_cov_ego @ R_ego.T,
            vel=R_ego @ np.array((float(det["vx"][k]), float(det["vy"][k]))),
            vel_cov=R_ego @ vel_cov_ego @ R_ego.T,
            yaw=normalize_angle(float(det["yaw"][k]) + ego_yaw),
            half_l=float(det["half_l"][k]), half_w=float(det["half_w"][k]),
            cls=int(det["cls"][k]), score=float(det["score"][k])))
    return out