trackflow-python-tensorrt 0.7.0__cp310-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
trackflow/nltrack.py ADDED
@@ -0,0 +1,1107 @@
1
+ """Non-linear multi-object tracker with dual-anchor motion and adaptive gallery Re-ID.
2
+
3
+ Clean-room Apache-2.0 tracker combining:
4
+
5
+ 1. **Dual-anchor non-linear motion**: NSA :class:`XywhKalmanFilter` + :class:`SparseOpticalFlowCMC`
6
+ with observation-centric re-update (ORU) and momentum (OCM), exponential velocity damping on
7
+ lost tracks (``vx, vy`` damped per missed frame, ``vw, vh`` zeroed), and dual-anchor spatial
8
+ affinity ``max(HMIoU(damped_pred), HMIoU(last_obs))`` with controlled occlusion-age expansion.
9
+ 2. **Clean-bank adaptive appearance**: 15-frame ring buffer plus clean EMA per track updated only
10
+ on clean crops (overlap ``<= 0.40``, or when the bank is empty), scored via blended max-bank/EMA
11
+ cosine with per-sequence running non-matching cosine normalization (GHOST-style), virtual-null
12
+ dual-softmax, and row/col margin weighting fused additively with motion.
13
+ 3. **Confirmed-track immediate recovery + iterative mutual-best association**: iterative mutual-best
14
+ (TPA-style) followed by Hungarian assignment, immediate re-reporting on recovery, extended
15
+ buffer (``>= 60`` frames), guarded low-score recovery for recently lost tracks, and track-aware
16
+ duplicate-spawn blocking (TAI).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections import defaultdict, deque
22
+ from dataclasses import dataclass, field
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+
27
+ from trackflow._accel import native_module
28
+ from trackflow.tracker import (
29
+ SparseOpticalFlowCMC,
30
+ XywhKalmanFilter,
31
+ _assign,
32
+ _boxes,
33
+ _expand_boxes,
34
+ _switch_event,
35
+ compute_hmiou_matrix,
36
+ compute_ioa_matrix,
37
+ compute_iou_matrix,
38
+ )
39
+ from trackflow.types import Detection, Track
40
+
41
+ Box = tuple[float, float, float, float]
42
+
43
+
44
+ def _centers(boxes: np.ndarray) -> np.ndarray:
45
+ return np.stack([(boxes[:, 0] + boxes[:, 2]) * 0.5, (boxes[:, 1] + boxes[:, 3]) * 0.5], axis=1)
46
+
47
+
48
+ def _direction(a: Box, b: Box) -> np.ndarray:
49
+ """Unit vector ``(dy, dx)`` from center of ``a`` to center of ``b``; zero if nearly static."""
50
+ dx = 0.5 * ((b[0] + b[2]) - (a[0] + a[2]))
51
+ dy = 0.5 * ((b[1] + b[3]) - (a[1] + a[3]))
52
+ norm = float(np.hypot(dy, dx))
53
+ if norm < 1.0:
54
+ return np.zeros(2, dtype=np.float64)
55
+ return np.array([dy / norm, dx / norm], dtype=np.float64)
56
+
57
+
58
+ def _warp_box(box: Box, rot: np.ndarray, trans: np.ndarray, scale: float) -> Box:
59
+ x1, y1, x2, y2 = box
60
+ cx, cy = rot @ np.array([(x1 + x2) * 0.5, (y1 + y2) * 0.5], dtype=np.float64) + trans
61
+ hw = max(0.5, (x2 - x1) * scale * 0.5)
62
+ hh = max(0.5, (y2 - y1) * scale * 0.5)
63
+ return (float(cx - hw), float(cy - hh), float(cx + hw), float(cy + hh))
64
+
65
+
66
+ def _expanded_iou_hmiou(
67
+ t_boxes: np.ndarray,
68
+ d_boxes: np.ndarray,
69
+ t_expand: np.ndarray,
70
+ ) -> tuple[np.ndarray, np.ndarray]:
71
+ """Pairwise IoU and HMIoU where each track row ``i`` expands both boxes by ``t_expand[i]``."""
72
+ n, m = len(t_boxes), len(d_boxes)
73
+ if n == 0 or m == 0:
74
+ empty = np.zeros((n, m), dtype=np.float64)
75
+ return empty, empty
76
+
77
+ exp = t_expand[:, None]
78
+ tw = (t_boxes[:, 2] - t_boxes[:, 0])[:, None]
79
+ th = (t_boxes[:, 3] - t_boxes[:, 1])[:, None]
80
+ dw = (d_boxes[:, 2] - d_boxes[:, 0])[None, :]
81
+ dh = (d_boxes[:, 3] - d_boxes[:, 1])[None, :]
82
+
83
+ tx1 = t_boxes[:, 0:1] - exp * tw
84
+ ty1 = t_boxes[:, 1:2] - exp * th
85
+ tx2 = t_boxes[:, 2:3] + exp * tw
86
+ ty2 = t_boxes[:, 3:4] + exp * th
87
+
88
+ dx1 = d_boxes[None, :, 0] - exp * dw
89
+ dy1 = d_boxes[None, :, 1] - exp * dh
90
+ dx2 = d_boxes[None, :, 2] + exp * dw
91
+ dy2 = d_boxes[None, :, 3] + exp * dh
92
+
93
+ iw = np.maximum(0.0, np.minimum(tx2, dx2) - np.maximum(tx1, dx1))
94
+ ih = np.maximum(0.0, np.minimum(ty2, dy2) - np.maximum(ty1, dy1))
95
+ inter = iw * ih
96
+ area_t = np.maximum(0.0, tx2 - tx1) * np.maximum(0.0, ty2 - ty1)
97
+ area_d = np.maximum(0.0, dx2 - dx1) * np.maximum(0.0, dy2 - dy1)
98
+ iou = inter / np.maximum(area_t + area_d - inter, 1e-6)
99
+
100
+ v_inter = np.minimum(t_boxes[:, None, 3], d_boxes[None, :, 3]) - np.maximum(
101
+ t_boxes[:, None, 1], d_boxes[None, :, 1]
102
+ )
103
+ v_union = np.maximum(t_boxes[:, None, 3], d_boxes[None, :, 3]) - np.minimum(
104
+ t_boxes[:, None, 1], d_boxes[None, :, 1]
105
+ )
106
+ hmiou = iou * (0.75 + 0.25 * np.maximum(v_inter, 0.0) / np.maximum(v_union, 1e-6))
107
+ return iou, hmiou
108
+
109
+
110
+ def _mutual_best_assign(
111
+ similarity: np.ndarray, valid: np.ndarray
112
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
113
+ """Iterative mutual-best matching over valid pairs, finishing leftovers with Hungarian."""
114
+ n, m = similarity.shape
115
+ if n == 0 or m == 0:
116
+ return [], list(range(n)), list(range(m))
117
+
118
+ s = np.where(valid, similarity, -np.inf)
119
+ row_alive = np.ones(n, dtype=bool)
120
+ col_alive = np.ones(m, dtype=bool)
121
+ matches: list[tuple[int, int]] = []
122
+
123
+ while bool(row_alive.any()) and bool(col_alive.any()):
124
+ sub_r = np.flatnonzero(row_alive)
125
+ sub_c = np.flatnonzero(col_alive)
126
+ sub_s = s[np.ix_(sub_r, sub_c)]
127
+ row_best_c = np.argmax(sub_s, axis=1)
128
+ col_best_r = np.argmax(sub_s, axis=0)
129
+ found = False
130
+ for ri_local, ci_local in enumerate(row_best_c.tolist()):
131
+ if not np.isfinite(float(sub_s[ri_local, ci_local])):
132
+ continue
133
+ if int(col_best_r[ci_local]) == ri_local:
134
+ r_idx = int(sub_r[ri_local])
135
+ c_idx = int(sub_c[ci_local])
136
+ matches.append((r_idx, c_idx))
137
+ row_alive[r_idx] = False
138
+ col_alive[c_idx] = False
139
+ found = True
140
+ if not found:
141
+ break
142
+
143
+ rem_r = np.flatnonzero(row_alive).tolist()
144
+ rem_c = np.flatnonzero(col_alive).tolist()
145
+ if rem_r and rem_c:
146
+ sub_m, left_r, left_c = _assign(
147
+ similarity[np.ix_(rem_r, rem_c)], valid[np.ix_(rem_r, rem_c)]
148
+ )
149
+ for ri, ci in sub_m:
150
+ matches.append((rem_r[ri], rem_c[ci]))
151
+ rem_r = [rem_r[i] for i in left_r]
152
+ rem_c = [rem_c[i] for i in left_c]
153
+ return matches, rem_r, rem_c
154
+
155
+
156
+ class _NlMotion:
157
+ """NSA xywh Kalman filter with lost-track velocity damping, OCM direction, and ORU re-update."""
158
+
159
+ def __init__(self, box: Box, *, delta_t: int = 3, vel_damp: float = 0.80) -> None:
160
+ self.kf = XywhKalmanFilter(box, height_scaled=True, min_nsa=0.03)
161
+ self.delta_t = int(delta_t)
162
+ self.vel_damp = float(vel_damp)
163
+ self.observations: dict[int, Box] = {0: box}
164
+ self.last_observation: Box = box
165
+ self.direction: np.ndarray = np.zeros(2, dtype=np.float64)
166
+ self._frozen: tuple[np.ndarray, np.ndarray] | None = None
167
+ self._missed: int = 0
168
+
169
+ @property
170
+ def box(self) -> Box:
171
+ return self.kf.box
172
+
173
+ def predict(self, *, is_lost: bool) -> None:
174
+ if is_lost:
175
+ self.kf.mean[4:6] *= self.vel_damp
176
+ self.kf.mean[6:8] = 0.0
177
+ self.kf.predict()
178
+
179
+ def apply_camera_warp(self, warp_2x3: np.ndarray) -> None:
180
+ rot = warp_2x3[:2, :2]
181
+ trans = warp_2x3[:2, 2]
182
+ scale = float(np.sqrt(abs(np.linalg.det(rot))))
183
+ if scale <= 1e-6:
184
+ return
185
+ self.kf.apply_camera_warp(warp_2x3)
186
+ if self._frozen is not None:
187
+ t_mat = np.zeros((8, 8), dtype=np.float64)
188
+ t_mat[0:2, 0:2] = rot
189
+ t_mat[2, 2] = t_mat[3, 3] = scale
190
+ t_mat[4:6, 4:6] = rot
191
+ t_mat[6, 6] = t_mat[7, 7] = scale
192
+ f_mean, f_cov = self._frozen
193
+ f_mean = t_mat @ f_mean
194
+ f_mean[:2] += trans
195
+ self._frozen = (f_mean, t_mat @ f_cov @ t_mat.T)
196
+ if float(np.hypot(self.direction[0], self.direction[1])) > 1e-6:
197
+ v_xy = rot @ np.array([self.direction[1], self.direction[0]], dtype=np.float64)
198
+ v_norm = float(np.hypot(v_xy[0], v_xy[1]))
199
+ if v_norm > 1e-6:
200
+ self.direction = np.array([v_xy[1] / v_norm, v_xy[0] / v_norm], dtype=np.float64)
201
+ self.last_observation = _warp_box(self.last_observation, rot, trans, scale)
202
+ self.observations = {
203
+ age: _warp_box(b, rot, trans, scale) for age, b in self.observations.items()
204
+ }
205
+
206
+ def reference_observation(self, age: int) -> Box:
207
+ for dt in range(self.delta_t, 0, -1):
208
+ obs = self.observations.get(age - dt)
209
+ if obs is not None:
210
+ return obs
211
+ return self.last_observation
212
+
213
+ def miss(self) -> None:
214
+ if self._frozen is None:
215
+ self._frozen = (self.kf.mean.copy(), self.kf.cov.copy())
216
+ self._missed += 1
217
+
218
+ def update(self, box: Box, age: int, confidence: float) -> None:
219
+ self.direction = _direction(self.reference_observation(age), box)
220
+ if self._frozen is None:
221
+ self.kf.update(box, confidence=confidence)
222
+ else:
223
+ f_mean, f_cov = self._frozen
224
+ self.kf.mean = f_mean
225
+ self.kf.cov = f_cov
226
+ gap = self._missed + 1
227
+ self._frozen = None
228
+ self._missed = 0
229
+ x0a, y0a, x0b, y0b = self.last_observation
230
+ x1a, y1a, x1b, y1b = box
231
+ for step in range(1, gap + 1):
232
+ f = step / gap
233
+ interp = (
234
+ x0a + f * (x1a - x0a),
235
+ y0a + f * (y1a - y0a),
236
+ x0b + f * (x1b - x0b),
237
+ y0b + f * (y1b - y0b),
238
+ )
239
+ step_conf = confidence if step == gap else min(confidence, 0.85)
240
+ self.kf.update(interp, confidence=step_conf)
241
+ if step < gap:
242
+ self.kf.predict()
243
+ self.last_observation = box
244
+ self.observations[age] = box
245
+ oldest = age + 1 - self.delta_t
246
+ self.observations = {a: b for a, b in self.observations.items() if a >= oldest}
247
+
248
+
249
+ @dataclass(eq=False)
250
+ class _NlTrack:
251
+ uid: int
252
+ motion: _NlMotion
253
+ confidence: float
254
+ class_id: int
255
+ class_name: str
256
+ start_frame: int
257
+ peak_height: float
258
+ track_id: int = 0
259
+ is_activated: bool = False
260
+ age: int = 1
261
+ hits: int = 1
262
+ high_hits: int = 1
263
+ time_since_update: int = 0
264
+ state: str = "tracked" # tracked | lost
265
+ recovered_now: bool = False
266
+ bank_has_clean: bool = False
267
+ emb_bank: deque[np.ndarray] = field(default_factory=lambda: deque(maxlen=15), repr=False)
268
+ emb_ema: np.ndarray | None = field(default=None, repr=False)
269
+
270
+ @property
271
+ def bbox(self) -> Box:
272
+ return self.motion.box
273
+
274
+ def update_embedding(
275
+ self, emb: np.ndarray | None, *, ovl: float, clean_ovl_thresh: float
276
+ ) -> None:
277
+ if emb is None:
278
+ return
279
+ norm = float(np.linalg.norm(emb))
280
+ if norm <= 1e-6:
281
+ return
282
+ unit = np.asarray(emb, dtype=np.float64) / norm
283
+ if ovl <= clean_ovl_thresh:
284
+ if not self.bank_has_clean:
285
+ self.emb_bank.clear()
286
+ self.bank_has_clean = True
287
+ self.emb_ema = unit
288
+ else:
289
+ blended = 0.90 * self.emb_ema + 0.10 * unit if self.emb_ema is not None else unit
290
+ self.emb_ema = blended / max(float(np.linalg.norm(blended)), 1e-6)
291
+ self.emb_bank.append(unit)
292
+ elif not self.emb_bank:
293
+ self.emb_bank.append(unit)
294
+ self.emb_ema = unit
295
+
296
+ def to_track(self, *, coasting: bool = False) -> Track:
297
+ return Track(
298
+ track_id=self.track_id,
299
+ bbox=self.bbox,
300
+ confidence=self.confidence,
301
+ class_id=self.class_id,
302
+ class_name=self.class_name,
303
+ age=self.age,
304
+ hits=self.hits,
305
+ recovered=self.recovered_now and not coasting,
306
+ coasting=coasting,
307
+ )
308
+
309
+
310
+ class NonLinearTracker:
311
+ """Dual-anchor non-linear tracker with clean-bank adaptive appearance and lost-track recovery."""
312
+
313
+ name: str = "nltrack"
314
+
315
+ def __init__(
316
+ self,
317
+ *,
318
+ track_high_thresh: float = 0.5,
319
+ track_low_thresh: float = 0.15,
320
+ new_track_thresh: float = 0.55,
321
+ track_buffer: int = 60,
322
+ iou_buffer: float = 0.0,
323
+ use_cmc: bool = True,
324
+ vel_damp: float = 0.90,
325
+ delta_t: int = 3,
326
+ inertia: float = 0.15,
327
+ bank_size: int = 15,
328
+ clean_ovl_thresh: float = 0.40,
329
+ emb_weight: float = 3.5,
330
+ softmax_temp: float = 0.13,
331
+ null_std: float = 1.0,
332
+ margin_weight: float = 0.25,
333
+ ema_blend: float = 0.50,
334
+ occ_exp_max: float = 0.20,
335
+ occ_exp_rate: float = 0.03,
336
+ active_iou_gate: float = 0.20,
337
+ lost_iou_gate: float = 0.18,
338
+ reid_active_iou_gate: float = 0.05,
339
+ reid_rescue_z: float = 1.3,
340
+ reid_rescue_margin: float = 0.25,
341
+ reid_rescue_max_disp: float = 8.0,
342
+ active_low_iou: float = 0.50,
343
+ lost_low_max_tsu: int = 14,
344
+ lost_low_iou: float = 0.60,
345
+ lost_low_conf: float = 0.20,
346
+ stage2_min_rel_height: float = 0.52,
347
+ stage2_high_frac: float = 0.92,
348
+ tai_iou_thresh: float = 0.55,
349
+ spawn_overlap_thresh: float = 0.80,
350
+ duplicate_iou: float = 0.85,
351
+ min_confirm_hits: int = 4,
352
+ ) -> None:
353
+ self.track_high_thresh = float(track_high_thresh)
354
+ self.track_low_thresh = float(track_low_thresh)
355
+ self.new_track_thresh = float(new_track_thresh)
356
+ self.track_buffer = int(track_buffer)
357
+ self.iou_buffer = float(iou_buffer)
358
+ self.use_cmc = bool(use_cmc)
359
+ self.vel_damp = float(vel_damp)
360
+ self.delta_t = int(delta_t)
361
+ self.inertia = float(inertia)
362
+ self.bank_size = int(bank_size)
363
+ self.clean_ovl_thresh = float(clean_ovl_thresh)
364
+ self.emb_weight = float(emb_weight)
365
+ self.softmax_temp = float(softmax_temp)
366
+ self.null_std = float(null_std)
367
+ self.margin_weight = float(margin_weight)
368
+ self.ema_blend = float(ema_blend)
369
+ self.occ_exp_max = float(occ_exp_max)
370
+ self.occ_exp_rate = float(occ_exp_rate)
371
+ self.active_iou_gate = float(active_iou_gate)
372
+ self.lost_iou_gate = float(lost_iou_gate)
373
+ self.reid_active_iou_gate = float(reid_active_iou_gate)
374
+ self.reid_rescue_z = float(reid_rescue_z)
375
+ self.reid_rescue_margin = float(reid_rescue_margin)
376
+ self.reid_rescue_max_disp = float(reid_rescue_max_disp)
377
+ self.active_low_iou = float(active_low_iou)
378
+ self.lost_low_max_tsu = int(lost_low_max_tsu)
379
+ self.lost_low_iou = float(lost_low_iou)
380
+ self.lost_low_conf = float(lost_low_conf)
381
+ self.stage2_min_rel_height = float(stage2_min_rel_height)
382
+ self.stage2_high_frac = float(stage2_high_frac)
383
+ self.tai_iou_thresh = float(tai_iou_thresh)
384
+ self.spawn_overlap_thresh = float(spawn_overlap_thresh)
385
+ self.duplicate_iou = float(duplicate_iou)
386
+ self.min_confirm_hits = int(min_confirm_hits)
387
+ self.embedding_min_confidence: float | None = self.track_high_thresh
388
+ self._native: Any = None
389
+ if type(self) is NonLinearTracker:
390
+ native = native_module()
391
+ if native is not None:
392
+ self._native = native.NativeNonLinearTracker(
393
+ self.track_high_thresh,
394
+ self.track_low_thresh,
395
+ self.new_track_thresh,
396
+ self.track_buffer,
397
+ self.iou_buffer,
398
+ self.vel_damp,
399
+ self.delta_t,
400
+ self.inertia,
401
+ self.bank_size,
402
+ self.clean_ovl_thresh,
403
+ self.emb_weight,
404
+ self.softmax_temp,
405
+ self.null_std,
406
+ self.margin_weight,
407
+ self.ema_blend,
408
+ self.occ_exp_max,
409
+ self.occ_exp_rate,
410
+ self.active_iou_gate,
411
+ self.lost_iou_gate,
412
+ self.reid_active_iou_gate,
413
+ self.reid_rescue_z,
414
+ self.reid_rescue_margin,
415
+ self.reid_rescue_max_disp,
416
+ self.active_low_iou,
417
+ self.lost_low_max_tsu,
418
+ self.lost_low_iou,
419
+ self.lost_low_conf,
420
+ self.stage2_min_rel_height,
421
+ self.stage2_high_frac,
422
+ self.tai_iou_thresh,
423
+ self.spawn_overlap_thresh,
424
+ self.duplicate_iou,
425
+ self.min_confirm_hits,
426
+ )
427
+ self.reset()
428
+
429
+ def reset(self) -> None:
430
+ self._next_id = 1
431
+ self._next_uid = 1
432
+ self._frame_id = 0
433
+ self._tracks: list[_NlTrack] = []
434
+ self.last_events: list[dict[str, Any]] = []
435
+ self.last_cmc_warp: np.ndarray | None = None
436
+ self._cmc = SparseOpticalFlowCMC(drop_foreground_flow=True) if self.use_cmc else None
437
+ self._bg_count: float = 10.0
438
+ self._bg_mean: float = 0.55
439
+ self._bg_m2: float = 10.0 * (0.12**2)
440
+ if self._native is not None:
441
+ self._native.reset()
442
+
443
+ def _update_bg_stats(
444
+ self,
445
+ d_emb: np.ndarray,
446
+ d_has: np.ndarray,
447
+ d_cls: np.ndarray,
448
+ det_iou: np.ndarray,
449
+ ) -> None:
450
+ """Update running mean/variance of cosines between distinct detections in this frame."""
451
+ m = len(d_has)
452
+ if m < 2 or int(d_has.sum()) < 2:
453
+ return
454
+ cos_mat = d_emb @ d_emb.T
455
+ tri = np.triu(np.ones((m, m), dtype=bool), k=1)
456
+ valid = tri & np.outer(d_has, d_has) & (d_cls[:, None] == d_cls[None, :]) & (det_iou < 0.30)
457
+ vals = cos_mat[valid]
458
+ if vals.size == 0:
459
+ return
460
+ if self._bg_count > 4000.0:
461
+ scale = 4000.0 / self._bg_count
462
+ self._bg_count *= scale
463
+ self._bg_m2 *= scale
464
+ batch_n = float(vals.size)
465
+ batch_mean = float(vals.mean())
466
+ batch_m2 = float(((vals - batch_mean) ** 2).sum())
467
+ delta = batch_mean - self._bg_mean
468
+ new_count = self._bg_count + batch_n
469
+ self._bg_mean = self._bg_mean + delta * (batch_n / new_count)
470
+ self._bg_m2 = self._bg_m2 + batch_m2 + (delta**2) * (self._bg_count * batch_n / new_count)
471
+ self._bg_count = new_count
472
+
473
+ def _bg_mean_std(self) -> tuple[float, float]:
474
+ var = max(self._bg_m2 / max(self._bg_count, 1.0), 0.06**2)
475
+ return self._bg_mean, float(np.sqrt(var))
476
+
477
+ @staticmethod
478
+ def _unit_det_embeddings(dets: list[Detection]) -> tuple[np.ndarray, np.ndarray, int]:
479
+ dim = 0
480
+ for d in dets:
481
+ if d.embedding is not None:
482
+ dim = int(d.embedding.shape[0])
483
+ break
484
+ if dim == 0:
485
+ return np.zeros((len(dets), 0), dtype=np.float64), np.zeros(len(dets), dtype=bool), 0
486
+ out = np.zeros((len(dets), dim), dtype=np.float64)
487
+ has = np.zeros(len(dets), dtype=bool)
488
+ for j, d in enumerate(dets):
489
+ if d.embedding is None or d.embedding.shape[0] != dim:
490
+ continue
491
+ n = float(np.linalg.norm(d.embedding))
492
+ if n > 1e-6:
493
+ out[j] = np.asarray(d.embedding, dtype=np.float64) / n
494
+ has[j] = True
495
+ return out, has, dim
496
+
497
+ @staticmethod
498
+ def _det_overlaps(dets: list[Detection], d_boxes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
499
+ m = len(dets)
500
+ if m == 0:
501
+ return np.zeros((0, 0), dtype=np.float64), np.zeros(0, dtype=np.float64)
502
+ det_iou = compute_iou_matrix(d_boxes, d_boxes)
503
+ if m == 1:
504
+ return det_iou, np.zeros(1, dtype=np.float64)
505
+ d_cls = np.array([d.class_id for d in dets], dtype=np.int64)
506
+ same_other = (d_cls[:, None] == d_cls[None, :]) & ~np.eye(m, dtype=bool)
507
+ ovl = np.where(same_other, det_iou, 0.0).max(axis=1)
508
+ return det_iou, ovl
509
+
510
+ def _appearance_scores(
511
+ self,
512
+ tracks: list[_NlTrack],
513
+ d_emb: np.ndarray,
514
+ d_has: np.ndarray,
515
+ dim: int,
516
+ same_class: np.ndarray,
517
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
518
+ """Return ``(app_sim, p_dual, z_ghost, margin, has_pair)`` matrices of shape ``[N, M]``."""
519
+ n, m = same_class.shape
520
+ zeros = np.zeros((n, m), dtype=np.float64)
521
+ no_pair = np.zeros((n, m), dtype=bool)
522
+ if dim == 0 or n == 0 or m == 0 or not bool(d_has.any()):
523
+ return zeros, zeros, zeros, zeros, no_pair
524
+
525
+ bank_rows: list[np.ndarray] = []
526
+ offsets: list[int] = []
527
+ t_idx_with_emb: list[int] = []
528
+ ema_rows: list[np.ndarray] = []
529
+ t_has = np.zeros(n, dtype=bool)
530
+ cursor = 0
531
+ for i, tr in enumerate(tracks):
532
+ if not tr.emb_bank:
533
+ continue
534
+ vecs = [v for v in tr.emb_bank if v.shape[0] == dim]
535
+ if not vecs:
536
+ continue
537
+ t_has[i] = True
538
+ t_idx_with_emb.append(i)
539
+ offsets.append(cursor)
540
+ bank_rows.extend(vecs)
541
+ ema_rows.append(tr.emb_ema if tr.emb_ema is not None else vecs[-1])
542
+ cursor += len(vecs)
543
+
544
+ if not t_idx_with_emb:
545
+ return zeros, zeros, zeros, zeros, no_pair
546
+
547
+ all_bank = np.asarray(bank_rows, dtype=np.float64)
548
+ raw_sims = all_bank @ d_emb.T
549
+ max_per_t = np.maximum.reduceat(raw_sims, offsets, axis=0)
550
+ if self.ema_blend > 0.0:
551
+ ema_sims = np.asarray(ema_rows, dtype=np.float64) @ d_emb.T
552
+ max_per_t = (1.0 - self.ema_blend) * max_per_t + self.ema_blend * ema_sims
553
+
554
+ max_cos = np.full((n, m), -1.0, dtype=np.float64)
555
+ max_cos[t_idx_with_emb] = max_per_t
556
+ has_pair = t_has[:, None] & d_has[None, :] & same_class
557
+ if not bool(has_pair.any()):
558
+ return zeros, zeros, zeros, zeros, no_pair
559
+
560
+ bg_mean, bg_std = self._bg_mean_std()
561
+ c_null = bg_mean + self.null_std * bg_std
562
+ inv_t = 1.0 / max(self.softmax_temp, 1e-3)
563
+
564
+ logits = np.where(has_pair, max_cos * inv_t, -1e9)
565
+ null_logit = c_null * inv_t
566
+
567
+ row_ext = np.column_stack([logits, np.full((n, 1), null_logit, dtype=np.float64)])
568
+ row_max = row_ext.max(axis=1, keepdims=True)
569
+ row_exp = np.exp(row_ext - row_max)
570
+ p_row = (row_exp[:, :m] / np.maximum(row_exp.sum(axis=1, keepdims=True), 1e-12)) * has_pair
571
+
572
+ col_ext = np.vstack([logits, np.full((1, m), null_logit, dtype=np.float64)])
573
+ col_max = col_ext.max(axis=0, keepdims=True)
574
+ col_exp = np.exp(col_ext - col_max)
575
+ p_col = (col_exp[:n, :] / np.maximum(col_exp.sum(axis=0, keepdims=True), 1e-12)) * has_pair
576
+
577
+ p_dual = np.sqrt(np.maximum(p_row * p_col, 0.0))
578
+
579
+ # Row/col top-1 vs second-best margin (invariant to pool size N).
580
+ c_masked = np.where(has_pair, max_cos, -1e9)
581
+ c_row_ext = np.column_stack([c_masked, np.full((n, 1), c_null, dtype=np.float64)])
582
+ row_part = np.partition(c_row_ext, -2, axis=1)
583
+ row_top1 = row_part[:, -1:]
584
+ row_top2 = row_part[:, -2:-1]
585
+ best_other_row = np.where(c_masked >= row_top1 - 1e-12, row_top2, row_top1)
586
+ m_row = np.maximum(0.0, c_masked - best_other_row)
587
+
588
+ c_col_ext = np.vstack([c_masked, np.full((1, m), c_null, dtype=np.float64)])
589
+ col_part = np.partition(c_col_ext, -2, axis=0)
590
+ col_top1 = col_part[-1:, :]
591
+ col_top2 = col_part[-2:-1, :]
592
+ best_other_col = np.where(c_masked >= col_top1 - 1e-12, col_top2, col_top1)
593
+ m_col = np.maximum(0.0, c_masked - best_other_col)
594
+
595
+ margin = np.clip(0.5 * (m_row + m_col) / bg_std, 0.0, 1.5)
596
+
597
+ z_ghost = np.where(has_pair, (max_cos - bg_mean) / bg_std, 0.0)
598
+ ghost_norm = np.clip((max_cos - bg_mean) / max(1.0 - bg_mean, 0.12), -0.5, 1.0)
599
+ app_sim = np.where(
600
+ has_pair,
601
+ 0.55 * p_dual
602
+ + 0.30 * np.maximum(ghost_norm, 0.0)
603
+ + self.margin_weight * margin
604
+ + 0.25 * np.minimum(ghost_norm, 0.0),
605
+ 0.0,
606
+ )
607
+ return app_sim, p_dual, z_ghost, margin, has_pair
608
+
609
+ def _momentum_bonus(
610
+ self, tracks: list[_NlTrack], d_boxes: np.ndarray, d_scores: np.ndarray
611
+ ) -> np.ndarray:
612
+ n, m = len(tracks), len(d_boxes)
613
+ if n == 0 or m == 0 or self.inertia <= 0.0:
614
+ return np.zeros((n, m), dtype=np.float64)
615
+ refs = np.array([t.motion.reference_observation(t.age) for t in tracks], dtype=np.float64)
616
+ delta = _centers(d_boxes)[None, :, :] - _centers(refs)[:, None, :]
617
+ norm = np.hypot(delta[..., 0], delta[..., 1]) + 1e-6
618
+ dx, dy = delta[..., 0] / norm, delta[..., 1] / norm
619
+ vel = np.array([t.motion.direction for t in tracks], dtype=np.float64)
620
+ has_vel = (np.hypot(vel[:, 0], vel[:, 1]) > 0.5) & (
621
+ np.array([t.time_since_update for t in tracks]) <= 3
622
+ )
623
+ cos = np.clip(vel[:, 0:1] * dy + vel[:, 1:2] * dx, -1.0, 1.0)
624
+ agreement = (np.pi * 0.5 - np.abs(np.arccos(cos))) / np.pi
625
+ bonus = agreement * self.inertia * d_scores[None, :]
626
+ bonus[~has_vel] = 0.0
627
+ return bonus
628
+
629
+ def _associate_stage1(
630
+ self,
631
+ pool: list[_NlTrack],
632
+ dets: list[Detection],
633
+ d_boxes: np.ndarray,
634
+ d_emb: np.ndarray,
635
+ d_has: np.ndarray,
636
+ dim: int,
637
+ ) -> tuple[list[tuple[int, int]], list[int], list[int]]:
638
+ if not pool or not dets:
639
+ return [], list(range(len(pool))), list(range(len(dets)))
640
+
641
+ n = len(pool)
642
+ same_class = np.equal.outer([t.class_id for t in pool], [d.class_id for d in dets])
643
+ pred_boxes = np.array([t.motion.box for t in pool], dtype=np.float64)
644
+ last_boxes = np.array([t.motion.last_observation for t in pool], dtype=np.float64)
645
+ tsu = np.array([t.time_since_update for t in pool], dtype=np.int64)
646
+ is_lost = tsu >= 2
647
+
648
+ base_exp = np.full(n, self.iou_buffer, dtype=np.float64)
649
+ occ_exp = np.where(
650
+ is_lost,
651
+ self.iou_buffer + np.minimum(self.occ_exp_max, self.occ_exp_rate * tsu),
652
+ self.iou_buffer,
653
+ )
654
+
655
+ pred_iou, pred_hmiou = _expanded_iou_hmiou(pred_boxes, d_boxes, base_exp)
656
+ spatial_hmiou = pred_hmiou.copy()
657
+ gate_iou = pred_iou.copy()
658
+
659
+ if bool(is_lost.any()):
660
+ li = np.flatnonzero(is_lost)
661
+ l_last_raw_iou, l_last_raw_hm = _expanded_iou_hmiou(
662
+ last_boxes[li], d_boxes, base_exp[li]
663
+ )
664
+ raw_hm = np.maximum(pred_hmiou[li], l_last_raw_hm)
665
+ raw_iou = np.maximum(pred_iou[li], l_last_raw_iou)
666
+ if self.occ_exp_max > 0.0:
667
+ l_pred_iou, l_pred_hm = _expanded_iou_hmiou(pred_boxes[li], d_boxes, occ_exp[li])
668
+ l_last_exp_iou, l_last_exp_hm = _expanded_iou_hmiou(
669
+ last_boxes[li], d_boxes, occ_exp[li]
670
+ )
671
+ exp_hm = np.maximum(l_pred_hm, l_last_exp_hm)
672
+ spatial_hmiou[li] = np.maximum(raw_hm, 0.85 * exp_hm)
673
+ gate_iou[li] = np.maximum.reduce([raw_iou, l_pred_iou, l_last_exp_iou])
674
+ else:
675
+ spatial_hmiou[li] = raw_hm
676
+ gate_iou[li] = raw_iou
677
+
678
+ d_scores = np.array([d.confidence for d in dets], dtype=np.float64)
679
+ ocm = self._momentum_bonus(pool, d_boxes, d_scores)
680
+ app_sim, p_dual, z_ghost, margin, has_pair = self._appearance_scores(
681
+ pool, d_emb, d_has, dim, same_class
682
+ )
683
+
684
+ iou_thresh = np.where(is_lost, self.lost_iou_gate, self.active_iou_gate)[:, None]
685
+ valid = same_class & (gate_iou >= iou_thresh)
686
+
687
+ if bool(has_pair.any()):
688
+ t_h = np.maximum(last_boxes[:, 3] - last_boxes[:, 1], 1.0)[:, None]
689
+ t_w = np.maximum(last_boxes[:, 2] - last_boxes[:, 0], 1.0)[:, None]
690
+ d_h = np.maximum(d_boxes[:, 3] - d_boxes[:, 1], 1.0)[None, :]
691
+ h_ratio = d_h / t_h
692
+ h_ok = (h_ratio >= 0.55) & (h_ratio <= 1.80)
693
+
694
+ d_c = _centers(d_boxes)[None, :, :]
695
+ dist_pred = np.hypot(
696
+ d_c[..., 0] - _centers(pred_boxes)[:, None, 0],
697
+ d_c[..., 1] - _centers(pred_boxes)[:, None, 1],
698
+ )
699
+ dist_last = np.hypot(
700
+ d_c[..., 0] - _centers(last_boxes)[:, None, 0],
701
+ d_c[..., 1] - _centers(last_boxes)[:, None, 1],
702
+ )
703
+ min_dist = np.minimum(dist_pred, dist_last)
704
+ t_scale = np.maximum(t_w, t_h)
705
+ max_disp = (
706
+ np.minimum(self.reid_rescue_max_disp, np.maximum(1.5, 0.35 * tsu))[:, None]
707
+ * t_scale
708
+ )
709
+ reid_strong = (z_ghost >= self.reid_rescue_z) & (
710
+ (margin >= self.reid_rescue_margin) | (p_dual >= 0.65)
711
+ )
712
+ reid_lost = is_lost[:, None] & has_pair & h_ok & (min_dist <= max_disp) & reid_strong
713
+ reid_active = (
714
+ (~is_lost[:, None])
715
+ & has_pair
716
+ & (gate_iou >= self.reid_active_iou_gate)
717
+ & h_ok
718
+ & reid_strong
719
+ )
720
+ valid |= reid_lost | reid_active
721
+
722
+ sim = spatial_hmiou + ocm + self.emb_weight * app_sim
723
+ sim = np.where(valid, np.maximum(sim, 1e-4), 0.0)
724
+ return _mutual_best_assign(sim, valid)
725
+
726
+ def _activate(self, tr: _NlTrack, events: list[dict[str, Any]]) -> None:
727
+ tr.is_activated = True
728
+ tr.track_id = self._next_id
729
+ self._next_id += 1
730
+ events.append({"type": "track_started", "track_id": tr.track_id})
731
+ switch = _switch_event(
732
+ tr.track_id,
733
+ tr.bbox,
734
+ [
735
+ (t.track_id, t.bbox)
736
+ for t in self._tracks
737
+ if t.state == "lost"
738
+ and t.class_id == tr.class_id
739
+ and t.is_activated
740
+ and t.time_since_update <= 5
741
+ ],
742
+ )
743
+ if switch is not None:
744
+ events.append(switch)
745
+
746
+ def _apply_detection(
747
+ self,
748
+ tr: _NlTrack,
749
+ det: Detection,
750
+ *,
751
+ update_class: bool,
752
+ ovl: float | None,
753
+ ) -> None:
754
+ tr.motion.update(det.bbox, tr.age, det.confidence)
755
+ tr.confidence = det.confidence
756
+ if update_class:
757
+ tr.class_id = det.class_id
758
+ tr.class_name = det.class_name
759
+ tr.high_hits += 1
760
+ tr.peak_height = max(tr.peak_height, float(det.bbox[3] - det.bbox[1]))
761
+ tr.hits += 1
762
+ tr.time_since_update = 0
763
+ if ovl is not None:
764
+ tr.update_embedding(det.embedding, ovl=ovl, clean_ovl_thresh=self.clean_ovl_thresh)
765
+
766
+ def _stage2_eligible(self, tr: _NlTrack, med_h: float) -> bool:
767
+ """Keep persistent low-confidence tiny background tracks out of Stage-2 maintenance."""
768
+ if self.stage2_min_rel_height <= 0.0 or med_h <= 0.0:
769
+ return True
770
+ if tr.peak_height >= self.stage2_min_rel_height * med_h:
771
+ return True
772
+ return (tr.high_hits / max(tr.hits, 1)) >= self.stage2_high_frac
773
+
774
+ def update(
775
+ self,
776
+ detections: list[Detection],
777
+ frame_bgr: np.ndarray | None = None,
778
+ ) -> list[Track]:
779
+ """Advance the tracker by one frame and return confirmed tracks observed this frame."""
780
+ if self._native is not None:
781
+ self.last_cmc_warp = None
782
+ warp: np.ndarray | None = None
783
+ if self._cmc is not None:
784
+ if frame_bgr is None:
785
+ self._cmc = SparseOpticalFlowCMC(drop_foreground_flow=True)
786
+ else:
787
+ warp = self._cmc.estimate(frame_bgr, _boxes(detections))
788
+ self.last_cmc_warp = warp
789
+ outputs, events = self._native.update(detections, self.iou_buffer, warp)
790
+ self.last_events = events
791
+ return outputs
792
+ self._frame_id += 1
793
+ events: list[dict[str, Any]] = []
794
+
795
+ for tr in self._tracks:
796
+ tr.recovered_now = False
797
+ tr.motion.predict(is_lost=(tr.state != "tracked"))
798
+ tr.age += 1
799
+ tr.time_since_update += 1
800
+
801
+ self.last_cmc_warp = None
802
+ if self._cmc is not None:
803
+ if frame_bgr is None:
804
+ self._cmc = SparseOpticalFlowCMC(drop_foreground_flow=True)
805
+ else:
806
+ warp = self._cmc.estimate(frame_bgr, _boxes(detections))
807
+ if warp is not None:
808
+ self.last_cmc_warp = warp
809
+ scale = float(np.sqrt(abs(np.linalg.det(warp[:2, :2]))))
810
+ for tr in self._tracks:
811
+ tr.motion.apply_camera_warp(warp)
812
+ if scale > 1e-6:
813
+ tr.peak_height *= scale
814
+
815
+ high_dets = [d for d in detections if d.confidence >= self.track_high_thresh]
816
+ low_dets = [
817
+ d for d in detections if self.track_low_thresh <= d.confidence < self.track_high_thresh
818
+ ]
819
+
820
+ high_boxes = _boxes(high_dets)
821
+ det_iou, high_ovl = self._det_overlaps(high_dets, high_boxes)
822
+ d_emb, d_has, dim = self._unit_det_embeddings(high_dets)
823
+ if dim > 0:
824
+ d_cls = np.array([d.class_id for d in high_dets], dtype=np.int64)
825
+ self._update_bg_stats(d_emb, d_has, d_cls, det_iou)
826
+
827
+ confirmed = [t for t in self._tracks if t.is_activated and t.state == "tracked"]
828
+ lost = [t for t in self._tracks if t.is_activated and t.state == "lost"]
829
+ unconfirmed = [t for t in self._tracks if not t.is_activated]
830
+ pool = confirmed + lost
831
+ updated: set[int] = set()
832
+
833
+ # Stage 1: confirmed + lost tracks <-> high-score detections.
834
+ matches, u_pool, u_high = self._associate_stage1(
835
+ pool, high_dets, high_boxes, d_emb, d_has, dim
836
+ )
837
+ for ti, di in matches:
838
+ tr = pool[ti]
839
+ if tr.state == "lost":
840
+ tr.recovered_now = True
841
+ events.append({"type": "track_recovered", "track_id": tr.track_id})
842
+ tr.state = "tracked"
843
+ self._apply_detection(tr, high_dets[di], update_class=True, ovl=float(high_ovl[di]))
844
+ updated.add(tr.uid)
845
+
846
+ heights_by_cls: dict[int, list[float]] = defaultdict(list)
847
+ for t in confirmed:
848
+ heights_by_cls[t.class_id].append(float(t.bbox[3] - t.bbox[1]))
849
+ med_h_by_cls = {
850
+ cid: float(np.median(hs)) for cid, hs in heights_by_cls.items() if len(hs) >= 3
851
+ }
852
+
853
+ # Stage 2a: remaining active tracks <-> low-score detections.
854
+ rem_tracked = [
855
+ pool[i]
856
+ for i in u_pool
857
+ if pool[i].state == "tracked"
858
+ and self._stage2_eligible(pool[i], med_h_by_cls.get(pool[i].class_id, 0.0))
859
+ ]
860
+ used_low: set[int] = set()
861
+ if rem_tracked and low_dets:
862
+ t_boxes = np.array([t.motion.box for t in rem_tracked], dtype=np.float64)
863
+ l_boxes = _boxes(low_dets)
864
+ iou = compute_iou_matrix(t_boxes, l_boxes)
865
+ hmiou = compute_hmiou_matrix(t_boxes, l_boxes, iou)
866
+ same_cls = np.equal.outer(
867
+ [t.class_id for t in rem_tracked], [d.class_id for d in low_dets]
868
+ )
869
+ low_matches, _, _ = _assign(hmiou, same_cls & (iou >= self.active_low_iou))
870
+ for ti, di in low_matches:
871
+ tr = rem_tracked[ti]
872
+ self._apply_detection(tr, low_dets[di], update_class=False, ovl=None)
873
+ updated.add(tr.uid)
874
+ used_low.add(di)
875
+
876
+ # Stage 2b: guarded low-score recovery for recently lost tracks.
877
+ if self.lost_low_max_tsu > 0:
878
+ rem_lost_rec = [
879
+ pool[i]
880
+ for i in u_pool
881
+ if pool[i].state == "lost"
882
+ and 2 <= pool[i].time_since_update <= self.lost_low_max_tsu
883
+ and self._stage2_eligible(pool[i], med_h_by_cls.get(pool[i].class_id, 0.0))
884
+ ]
885
+ rem_low_idx = [
886
+ i
887
+ for i in range(len(low_dets))
888
+ if i not in used_low and low_dets[i].confidence >= self.lost_low_conf
889
+ ]
890
+ if rem_lost_rec and rem_low_idx:
891
+ cand_low = [low_dets[i] for i in rem_low_idx]
892
+ l_boxes = _boxes(cand_low)
893
+
894
+ upd_by_cls: dict[int, list[Box]] = defaultdict(list)
895
+ for t in self._tracks:
896
+ if t.uid in updated:
897
+ upd_by_cls[t.class_id].append(t.bbox)
898
+ low_ok = np.ones(len(cand_low), dtype=bool)
899
+ cand_by_cls: dict[int, list[int]] = defaultdict(list)
900
+ for j, d in enumerate(cand_low):
901
+ if d.class_id in upd_by_cls:
902
+ cand_by_cls[d.class_id].append(j)
903
+ for cid, j_idxs in cand_by_cls.items():
904
+ upd_arr = np.asarray(upd_by_cls[cid], dtype=np.float64)
905
+ d_sub = l_boxes[j_idxs]
906
+ blocked = (compute_ioa_matrix(d_sub, upd_arr).max(axis=1) >= 0.70) | (
907
+ compute_iou_matrix(d_sub, upd_arr).max(axis=1) >= 0.55
908
+ )
909
+ if blocked.any():
910
+ low_ok[np.asarray(j_idxs, dtype=np.intp)[blocked]] = False
911
+
912
+ if bool(low_ok.any()):
913
+ pred_b = np.array([t.motion.box for t in rem_lost_rec], dtype=np.float64)
914
+ last_b = np.array(
915
+ [t.motion.last_observation for t in rem_lost_rec], dtype=np.float64
916
+ )
917
+ iou_p = compute_iou_matrix(pred_b, l_boxes)
918
+ iou_l = compute_iou_matrix(last_b, l_boxes)
919
+ hm_p = compute_hmiou_matrix(pred_b, l_boxes, iou_p)
920
+ hm_l = compute_hmiou_matrix(last_b, l_boxes, iou_l)
921
+ iou_dual = np.maximum(iou_p, iou_l)
922
+ hm_dual = np.maximum(hm_p, hm_l)
923
+
924
+ t_h = np.maximum(last_b[:, 3] - last_b[:, 1], 1.0)[:, None]
925
+ d_h = np.maximum(l_boxes[:, 3] - l_boxes[:, 1], 1.0)[None, :]
926
+ h_ok = (d_h / t_h >= 0.65) & (d_h / t_h <= 1.55)
927
+ same_cls = np.equal.outer(
928
+ [t.class_id for t in rem_lost_rec], [d.class_id for d in cand_low]
929
+ )
930
+ valid_rec = same_cls & low_ok[None, :] & h_ok & (iou_dual >= self.lost_low_iou)
931
+ rec_matches, _, _ = _assign(hm_dual, valid_rec)
932
+ for ti, di in rec_matches:
933
+ tr = rem_lost_rec[ti]
934
+ tr.recovered_now = True
935
+ tr.state = "tracked"
936
+ events.append({"type": "track_recovered", "track_id": tr.track_id})
937
+ self._apply_detection(tr, cand_low[di], update_class=False, ovl=None)
938
+ updated.add(tr.uid)
939
+
940
+ # Stage 3: unconfirmed tracks <-> leftover high-score detections.
941
+ rem_high_idx = list(u_high)
942
+ if unconfirmed and rem_high_idx:
943
+ rem_dets = [high_dets[i] for i in rem_high_idx]
944
+ rem_boxes = high_boxes[rem_high_idx]
945
+ u_boxes = np.array([t.motion.box for t in unconfirmed], dtype=np.float64)
946
+ u_iou = compute_iou_matrix(
947
+ _expand_boxes(u_boxes, self.iou_buffer),
948
+ _expand_boxes(rem_boxes, self.iou_buffer),
949
+ )
950
+ u_hmiou = compute_hmiou_matrix(u_boxes, rem_boxes, u_iou)
951
+ same_cls = np.equal.outer(
952
+ [t.class_id for t in unconfirmed], [d.class_id for d in rem_dets]
953
+ )
954
+ un_matches, _, u_rem_local = _assign(u_hmiou, same_cls & (u_iou >= 0.30))
955
+ for ti, di in un_matches:
956
+ tr = unconfirmed[ti]
957
+ orig_idx = rem_high_idx[di]
958
+ self._apply_detection(
959
+ tr, high_dets[orig_idx], update_class=True, ovl=float(high_ovl[orig_idx])
960
+ )
961
+ updated.add(tr.uid)
962
+ if tr.hits >= self.min_confirm_hits:
963
+ self._activate(tr, events)
964
+ rem_high_idx = [rem_high_idx[i] for i in u_rem_local]
965
+
966
+ # Lost transitions, ORU miss snapshots, expiry, and drop unmatched unconfirmed.
967
+ surviving: list[_NlTrack] = []
968
+ for tr in self._tracks:
969
+ if tr.uid in updated:
970
+ surviving.append(tr)
971
+ continue
972
+ if not tr.is_activated:
973
+ continue
974
+ if tr.state == "tracked":
975
+ tr.state = "lost"
976
+ events.append({"type": "track_lost", "track_id": tr.track_id})
977
+ tr.motion.miss()
978
+ if tr.time_since_update <= self.track_buffer:
979
+ surviving.append(tr)
980
+ else:
981
+ events.append({"type": "track_ended", "track_id": tr.track_id})
982
+ self._tracks = surviving
983
+
984
+ # Spawn new tracks with TAI duplicate-spawn blocking.
985
+ occupied: dict[int, list[Box]] = defaultdict(list)
986
+ for t in self._tracks:
987
+ if t.uid in updated:
988
+ occupied[t.class_id].append(t.bbox)
989
+
990
+ sorted_rem = sorted(rem_high_idx, key=lambda i: high_dets[i].confidence, reverse=True)
991
+ # Pre-check leftover detections against static occupied tracks in one batch per class.
992
+ blocked_by_static_occ: set[int] = set()
993
+ if sorted_rem and occupied:
994
+ cand_by_cls_spawn: dict[int, list[int]] = defaultdict(list)
995
+ for idx in sorted_rem:
996
+ det = high_dets[idx]
997
+ if det.confidence >= self.new_track_thresh and det.class_id in occupied:
998
+ cand_by_cls_spawn[det.class_id].append(idx)
999
+ for cid, c_idxs in cand_by_cls_spawn.items():
1000
+ occ_arr = np.asarray(occupied[cid], dtype=np.float64)
1001
+ c_boxes = high_boxes[c_idxs]
1002
+ bad = (compute_iou_matrix(c_boxes, occ_arr).max(axis=1) >= self.tai_iou_thresh) | (
1003
+ compute_ioa_matrix(c_boxes, occ_arr).max(axis=1) >= self.spawn_overlap_thresh
1004
+ )
1005
+ for pos in np.flatnonzero(bad).tolist():
1006
+ blocked_by_static_occ.add(c_idxs[pos])
1007
+
1008
+ spawned_occ: dict[int, list[Box]] = defaultdict(list)
1009
+ higher_leftovers: dict[int, list[Box]] = defaultdict(list)
1010
+
1011
+ for idx in sorted_rem:
1012
+ det = high_dets[idx]
1013
+ if det.confidence < self.new_track_thresh or idx in blocked_by_static_occ:
1014
+ higher_leftovers[det.class_id].append(det.bbox)
1015
+ continue
1016
+ bx1, by1, bx2, by2 = det.bbox
1017
+ area_a = max(0.0, bx2 - bx1) * max(0.0, by2 - by1)
1018
+ area_a_safe = area_a if area_a > 1e-6 else 1e-6
1019
+
1020
+ blocked = False
1021
+ for ox1, oy1, ox2, oy2 in spawned_occ[det.class_id]:
1022
+ iw = min(bx2, ox2) - max(bx1, ox1)
1023
+ ih = min(by2, oy2) - max(by1, oy1)
1024
+ if iw > 0.0 and ih > 0.0:
1025
+ inter = iw * ih
1026
+ area_b = max(0.0, ox2 - ox1) * max(0.0, oy2 - oy1)
1027
+ union = area_a + area_b - inter
1028
+ if (
1029
+ inter / (union if union > 1e-6 else 1e-6) >= self.tai_iou_thresh
1030
+ or inter / area_a_safe >= self.spawn_overlap_thresh
1031
+ ):
1032
+ blocked = True
1033
+ break
1034
+ if not blocked:
1035
+ for lx1, ly1, lx2, ly2 in higher_leftovers[det.class_id]:
1036
+ iw = min(bx2, lx2) - max(bx1, lx1)
1037
+ ih = min(by2, ly2) - max(by1, ly1)
1038
+ if iw > 0.0 and ih > 0.0:
1039
+ inter = iw * ih
1040
+ area_b = max(0.0, lx2 - lx1) * max(0.0, ly2 - ly1)
1041
+ union = area_a + area_b - inter
1042
+ if inter / (union if union > 1e-6 else 1e-6) >= self.tai_iou_thresh:
1043
+ blocked = True
1044
+ break
1045
+ if blocked:
1046
+ higher_leftovers[det.class_id].append(det.bbox)
1047
+ continue
1048
+
1049
+ tr = _NlTrack(
1050
+ uid=self._next_uid,
1051
+ motion=_NlMotion(det.bbox, delta_t=self.delta_t, vel_damp=self.vel_damp),
1052
+ confidence=det.confidence,
1053
+ class_id=det.class_id,
1054
+ class_name=det.class_name,
1055
+ start_frame=self._frame_id,
1056
+ peak_height=float(det.bbox[3] - det.bbox[1]),
1057
+ emb_bank=deque(maxlen=self.bank_size),
1058
+ )
1059
+ self._next_uid += 1
1060
+ tr.update_embedding(
1061
+ det.embedding, ovl=float(high_ovl[idx]), clean_ovl_thresh=self.clean_ovl_thresh
1062
+ )
1063
+ self._tracks.append(tr)
1064
+ updated.add(tr.uid)
1065
+ spawned_occ[det.class_id].append(tr.bbox)
1066
+ higher_leftovers[det.class_id].append(det.bbox)
1067
+ if self._frame_id == 1:
1068
+ self._activate(tr, events)
1069
+
1070
+ self._remove_duplicates(updated)
1071
+
1072
+ self.last_events = events
1073
+ outputs = [t.to_track() for t in self._tracks if t.is_activated and t.uid in updated]
1074
+ outputs.sort(key=lambda t: t.track_id)
1075
+ return outputs
1076
+
1077
+ def _remove_duplicates(self, updated: set[int]) -> None:
1078
+ tracked = [t for t in self._tracks if t.state == "tracked" and t.uid in updated]
1079
+ lost = [t for t in self._tracks if t.state == "lost"]
1080
+ if not tracked or not lost:
1081
+ return
1082
+ iou = compute_iou_matrix(_boxes(tracked), _boxes(lost))
1083
+ drop: set[int] = set()
1084
+ for p, q in zip(*np.where(iou > self.duplicate_iou), strict=False):
1085
+ a, b = tracked[int(p)], lost[int(q)]
1086
+ if a.class_id != b.class_id:
1087
+ continue
1088
+ if a.is_activated or (self._frame_id - a.start_frame) >= (
1089
+ self._frame_id - b.start_frame
1090
+ ):
1091
+ drop.add(b.uid)
1092
+ else:
1093
+ drop.add(a.uid)
1094
+ if drop:
1095
+ self._tracks = [t for t in self._tracks if t.uid not in drop]
1096
+
1097
+ def coasting_tracks(self, max_frames: int = 3) -> list[Track]:
1098
+ """Confirmed tracks missed for at most ``max_frames`` frames, at their predicted position."""
1099
+ if self._native is not None:
1100
+ return self._native.coasting_tracks(max_frames)
1101
+ out = [
1102
+ t.to_track(coasting=True)
1103
+ for t in self._tracks
1104
+ if t.is_activated and t.state == "lost" and t.time_since_update <= max_frames
1105
+ ]
1106
+ out.sort(key=lambda t: t.track_id)
1107
+ return out