Algorithmcore
Global nearest neighbor association
Also called GNN data association.
Assign measurements to tracks by the one-to-one assignment of least total distance in each frame, solved with the Hungarian or auction algorithm.
- Solves
- Data association
- Time
- O(n p³ + n m p² + (n + m)³) worst · averageΩ(n m p² + (n + m)²) best
- Space
- Θ((n + m)²) extra
- Where
- m = the number of measurements in the frame; n = the number of tracks; p = the dimension of a measurement
- Model
- Real RAM
- Properties
- deterministicexactnot iterativenot localonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Samuel S. Blackman, 1986
Global nearest neighbor association, or GNN, decides in each frame which measurement belongs to which track. Each track predicts where its next measurement should be, with a covariance. The cost of giving measurement to track is the squared Mahalanobis distance between them, and a pair outside the gate is not allowed. A track may stay without a measurement, and a measurement may stay without a track, each at a fixed cost. GNN then picks the one-to-one assignment of least total cost over all tracks at once, with the Hungarian algorithm or another solver of the assignment problem. The word "global" is the difference from the local nearest neighbor rule, which lets each track take its closest measurement and so can give one measurement to two tracks, or take a measurement that another track needs more. GNN keeps exactly one hypothesis per frame and never revises it, which is what separates it from JPDA and MHT.
In plain words
A teacher has a seating chart with the places where each student should sit, but the students walked in and sat down a little off. To match students to names, the teacher could let each name grab the nearest student. That fails when two names want the same student. GNN instead looks at all possible ways to match names to students and picks the one where the sum of the distances is smallest. Some names may have no student today, because the student is absent, and some students may be new. Each of these leftovers costs a fixed penalty, so a far-away match is not forced just to use everyone. The teacher then moves each name to where its student actually sits, and the next day starts again.
The problem
The input of one frame is a set of tracks and a set of measurements in . Each track has a state estimate and a covariance, which a Kalman filter predicts to the time of the frame. From the prediction come the predicted measurement and the innovation covariance . The gate is a threshold on the squared Mahalanobis distance, for example the 99 percent point of the chi-square distribution with 2 degrees of freedom, as on track gating.
A feasible answer is a partial one-to-one matching of tracks to measurements in which every pair is inside the gate. Its cost is
with . GNN returns a matching of least cost. The tracks in are updated with their measurements, the other tracks coast on their prediction, and the other measurements can start new tracks. In a likelihood form, is replaced by , the negative log of the Gaussian density up to a constant. This page uses the plain distance, as many trackers do.
The algorithm
GNN-STEP(the tracks, the measurements z_1..z_m, the gate γ, the costs c_miss and c_new)- 1
for each track i: predict x̂_i and P_i, then ẑ_i ← H x̂_i and S_i ← H P_i Hᵀ + R - 2
for each track i and each measurement j do - 3
d²_ij ← (z_j - ẑ_i)ᵀ S_i⁻¹ (z_j - ẑ_i) - 4
c_ij ← d²_ij if d²_ij ≤ γ, else ∞ - 5
A ← the (n + m) × (m + n) matrix [[C, D_miss], [D_new, 0]] ▷ D_miss, D_new: c_miss, c_new on the diagonal, ∞ elsewhere - 6
solve the assignment problem on A with the Hungarian algorithm - 7
for each track i assigned to a column j ≤ m: Kalman update of track i with z_j - 8
other tracks: count a miss, delete after too many; other measurements: start a new track
The matrix of line L5 has one row per track and one dummy row per measurement, and one column per measurement and one dummy column per track. A track that takes its own dummy column is missed, at the cost . A measurement whose dummy row takes the measurement's column is left over, at the cost . The block of zeros lets the dummy rows of the matched measurements take the dummy columns of the matched tracks for free. So every assignment of finite cost of is a partial matching of the same cost, and the reverse is also true. The default makes every gated pair at least as cheap as leaving both of its ends unmatched.
Line L8 is the track management. It is a heuristic and not part of the optimization. The code deletes a track after 3 frames in a row with no measurement and starts a track at every leftover measurement, with zero velocity and a large velocity variance.
Example
Two tracks predict and , both with . The frame has three measurements, , and . The gate is , and . The squared distances are
| A | 1.44 | 12.25 (outside the gate) | 125 (outside) |
| B | 0.64 | 2.25 | 89 (outside) |
The local rule. The closest gated pair is B and , at 0.64. After it is taken, track A has no measurement left in its gate, so A is missed, and and start new tracks. The cost is . The real target of A is lost, and the real target of B gets a second track.
GNN. The augmented matrix, with the rows A, B and the dummy rows of , and the columns and the dummy columns of A and B, is
Its least-cost assignment takes A to , B to , the dummy row of to , and the dummy rows of and to the two dummy columns. The cost is . Track B gives up its closest measurement because track A has no other choice, and only , which is far from both tracks, starts a new track.
A short sequence. The code also runs a tracker with a constant velocity model on three targets for 30 frames, with measurement noise of standard deviation 0.5, one clutter point every 7 frames, and two targets whose paths cross near frame 14. Each target keeps the same track through the crossing, and the mean position error after frame 5 is below 0.6. The clutter points start short tracks that die after 3 frames.
Correctness
The full proof is in proofs/correctness.md. It shows these facts.
- Theorem: the gate. If the true measurement is Gaussian with the predicted mean and covariance , then has the chi-square distribution with degrees of freedom. For the gate keeps it with probability exactly , which is 0.99 for .
- Theorem: the augmented matrix. The partial matchings inside the gate and the assignments of finite cost of correspond, with equal costs. So an optimal assignment of gives an optimal matching for the cost . Such an assignment always exists, because all tracks missed and all measurements new is finite.
- Theorem: gated pairs are used. If , no optimal matching leaves both track and measurement unmatched.
- Theorem: never worse than the local rule. The cost of GNN is at most the cost of the greedy nearest neighbor matching, and the example shows that it can be strictly less.
These facts are about one frame. Whether the tracks follow the true targets over many frames depends on the motion model, the detection rate and the clutter, and is not proved.
Proof: Why the chi-square gate has the stated probability, why the augmented matrix gives an optimal partial matching, and why GNN is never worse than the greedy rulefull
Notation as on the page. There are tracks and measurements. The gated cost is if and otherwise. A partial matching is a set of pairs with finite in which no track and no measurement appears twice. Its cost is , with finite. The claims are about one frame.
Claim 1: the probability of the gate
Let be Gaussian with mean 0 and a positive definite covariance in . Then has the chi-square distribution with degrees of freedom. For , .
Proof. Let be the Cholesky factorization and . Then is Gaussian with covariance , so its components are independent standard normal numbers. Also , a sum of squares of independent standard normal numbers, which is the definition of the chi-square distribution with degrees of freedom. For its density is on , and the integral from 0 to is .
For this is , and for it is . The claim needs the Gaussian model. With a wrong model, for example a maneuver that the motion model does not allow, the true measurement leaves the gate more often.
Claim 2: the augmented matrix
Let be the matrix of line L5. Rows are the tracks, rows are dummy rows of the measurements. Columns are the measurements, columns are dummy columns of the tracks. The entries are for a track and a measurement, and for , and for a measurement column , and .
(a) Every partial matching gives a permutation with .
(b) Every permutation of finite cost gives the partial matching with .
(c) So if is an optimal permutation, is an optimal partial matching, and the two optimal costs are equal.
Proof of (a). Let . Send each matched track to its measurement , at cost . Send each unmatched track to its dummy column , at cost . Send the dummy row of each unmatched measurement to column , at cost . So far the rows used are the track rows and the dummy rows of unmatched measurements, and the columns used are the matched measurement columns, the dummy columns of unmatched tracks, and the unmatched measurement columns. What is left is dummy rows of the matched measurements and dummy columns of the matched tracks. Pair them in any order, at cost 0 each, since the lower right block is all zero. Every row and every column is used once, so is a permutation, and its cost is .
Proof of (b). Since the cost is finite, no entry is used. Track row goes either to a measurement column with finite, or to its own dummy column . The pairs of the first kind form , and since is a permutation, no measurement appears twice, so is a partial matching. Let . The other tracks each pay . A measurement column is used by exactly one row. If is in , that row is a track row. Otherwise it is a dummy row, and the only finite entry of a dummy row in a measurement column is , so the row is the dummy row of , at cost . That gives costs . The remaining dummy rows go to dummy columns at cost 0. The total is .
Proof of (c). By (a), the least permutation cost is at most . By (b), the cost of an optimal equals . So the two minima are equal and attains it.
The empty matching has the finite cost , so by (a) always has a permutation of finite cost and the solver of line L6 always returns one. The Hungarian algorithm with potentials returns a permutation of least cost on any matrix whose entries are finite or with at least one finite permutation; its correctness is proved on the Hungarian algorithm page. The code reports infeasibility when every unvisited column has reduced cost , which cannot happen here.
Claim 3: gated pairs are used
If , then no optimal matching leaves both track and measurement unmatched.
Proof. Let leave both unmatched. Then is a partial matching, and . So is not optimal.
With the default the condition is , which holds for every gated pair except those on the boundary of the gate.
Claim 4: never worse than the greedy rule
Let be the matching of the greedy rule, which repeatedly takes the gated pair of least distance among unused tracks and measurements. Then the GNN cost is at most .
Proof. uses only gated pairs and never uses a track or a measurement twice, so it is a partial matching. By Claim 2 the GNN matching has the least over all partial matchings, so its cost is at most .
The example on the page has and a GNN cost of , so the inequality can be strict.
Complexity
With the inverse of computed once per track, the distances cost . The augmented matrix has entries. The Hungarian algorithm with potentials solves an assignment in time, so a frame costs time and extra space. The Kalman updates of line L7 add for a state of dimension . In practice the gate makes the matrix sparse, and trackers split it into independent clusters of tracks that share gated measurements, then solve each cluster alone. A cluster of size costs , so many small clusters are much cheaper than one large matrix.
Properties
- One hypothesis. GNN keeps a single assignment per frame and never changes a past decision.
- Optimal for its frame. The assignment is the best one under the cost , not just a good one.
- Deterministic. The same input gives the same output, up to ties between assignments of equal cost.
- Hard decisions. A track takes a full measurement or none. A wrong assignment is used as if it were right, and the error goes into the state.
- Independent of order. Unlike the greedy rule, the result does not depend on the order of the tracks or the measurements.
Variants and improvements
- Other assignment solvers. The auction algorithm of Bertsekas and the Jonker-Volgenant algorithm solve the same problem, often faster on sparse matrices.
- Rectangular matrices. Instead of dummy rows and columns, a solver for rectangular matrices with a cost of non-assignment can work on the matrix directly.
- Likelihood costs. Use , and costs of a miss and of a new target taken from the detection probability and the clutter density.
- Two-stage matching. ByteTrack matches the high-confidence detections first and the low-confidence ones second, each stage by an assignment.
- IoU costs. SORT uses between predicted and detected boxes as the cost, with a threshold on the IoU as the gate.
- Soft association. JPDA replaces the single assignment by a weighted average over all feasible assignments.
- Deferred decisions. MHT keeps the best few assignments per frame and decides later.
When to use it
Use GNN when targets are mostly well apart, the detection rate is high, and clutter is light. Many tracking-by-detection systems for video are of this kind, and GNN is their usual association step. It is cheap and easy to reason about. When targets come close and stay close for many frames, or the clutter is dense, a single wrong decision can swap identities for good, and JPDA or MHT do better at a higher cost.
Pitfalls
- Costs of a miss and a new track that are too low. Then the solver prefers to leave good pairs unmatched. With below a gated distance, a true pair can be split.
- Costs that are too high. Then far pairs inside a wide gate are forced, and clutter attaches to tracks.
- A large finite value instead of infinity. If "forbidden" is a big number, the solver can still pick it when nothing else fits, and the caller must check every pair against the gate.
- Distances with different covariances. A track with a large gets small distances to everything. The term fixes this in the likelihood form.
- Greedy instead of global. Taking the closest pair first is not GNN and can be much worse, as the example shows.
- Track management taken as part of the method. The rules for starting and deleting tracks are heuristics, and they often matter more than the assignment.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/global-nearest-neighbor-association/. The authors are listed in prov/VW85MF.jsonl.
"""Global nearest neighbor (GNN) data association with Kalman filter tracks.
Each frame, every track predicts its measurement z_hat with the innovation
covariance S. The cost of the pair (track i, measurement j) is the squared
Mahalanobis distance d2 = (z_j - z_hat_i)^T S_i^-1 (z_j - z_hat_i), and a pair
with d2 above the gate gamma is forbidden. A track may stay unassigned at the
cost c_miss, and a measurement at the cost c_new. The one-to-one assignment of
least total cost is found by the Hungarian algorithm on an augmented square
matrix. Matrices are lists of rows. Cost of one step: O((n + m)^3) time for n
tracks and m measurements, and O((n + m)^2) space.
"""
import math
INF = float("inf")
def mat_mul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]
def transpose(a):
return [list(r) for r in zip(*a)]
def mat_add(a, b):
return [[x + y for x, y in zip(r, s)] for r, s in zip(a, b)]
def mat_sub(a, b):
return [[x - y for x, y in zip(r, s)] for r, s in zip(a, b)]
def inverse(a):
"""Inverse of a small nonsingular matrix by Gauss-Jordan elimination with partial pivoting."""
n = len(a)
m = [list(map(float, r)) + [1.0 if i == j else 0.0 for j in range(n)] for i, r in enumerate(a)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) < 1e-300:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
m[c] = [x / piv for x in m[c]]
for r in range(n):
if r != c and m[r][c] != 0.0:
f = m[r][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return [r[n:] for r in m]
def mahalanobis2(z, z_hat, s):
"""Squared Mahalanobis distance of the innovation z - z_hat under the covariance s."""
nu = [[a - b] for a, b in zip(z, z_hat)]
return mat_mul(mat_mul(transpose(nu), inverse(s)), nu)[0][0]
def hungarian(cost):
"""Minimum cost assignment of the rows of an r x c matrix (r <= c) to distinct columns.
Entries may be INF (forbidden). Returns (row_to_col, total), or None when no
assignment of finite cost exists. The potentials method takes O(r^2 c) time.
"""
r = len(cost)
if r == 0:
return [], 0.0
c = len(cost[0])
u, v = [0.0] * (r + 1), [0.0] * (c + 1)
p, way = [0] * (c + 1), [0] * (c + 1)
for i in range(1, r + 1):
p[0], j0 = i, 0
minv, used = [INF] * (c + 1), [False] * (c + 1)
while True:
used[j0] = True
i0, delta, j1 = p[j0], INF, 0
for j in range(1, c + 1):
if not used[j]:
cur = cost[i0 - 1][j - 1] - u[i0] - v[j]
if cur < minv[j]:
minv[j], way[j] = cur, j0
if minv[j] < delta:
delta, j1 = minv[j], j
if delta == INF:
return None
for j in range(c + 1):
if used[j]:
u[p[j]] += delta
v[j] -= delta
else:
minv[j] -= delta
j0 = j1
if p[j0] == 0:
break
while j0:
j1 = way[j0]
p[j0] = p[j1]
j0 = j1
row_to_col = [-1] * r
for j in range(1, c + 1):
if p[j]:
row_to_col[p[j] - 1] = j - 1
return row_to_col, sum(cost[i][row_to_col[i]] for i in range(r))
def gnn_assign(z_hats, covs, zs, gamma, c_miss=None, c_new=None):
"""GNN association of one frame (lines L2 to L6 of the page).
z_hats, covs: the predicted measurement and innovation covariance of each track.
zs: the measurements. gamma: the gate on the squared Mahalanobis distance.
c_miss, c_new: the costs of an unassigned track and of an unassigned
measurement, gamma / 2 each by default, so that a gated pair is always
worth taking. Returns (pairs, missed_tracks, new_measurements, total_cost)
with pairs a dict from track to measurement.
"""
if c_miss is None:
c_miss = gamma / 2
if c_new is None:
c_new = gamma / 2
n, m = len(z_hats), len(zs)
c = [[INF] * m for _ in range(n)]
for i in range(n): # @line L2
for j in range(m):
d2 = mahalanobis2(zs[j], z_hats[i], covs[i]) # @line L3
c[i][j] = d2 if d2 <= gamma else INF # @line L4
size = n + m
a = [[INF] * size for _ in range(size)] # @line L5
for i in range(n):
for j in range(m):
a[i][j] = c[i][j]
a[i][m + i] = c_miss
for j in range(m):
a[n + j][j] = c_new
for i in range(n):
a[n + j][m + i] = 0.0
row_to_col, total = hungarian(a) # @line L6
pairs = {i: row_to_col[i] for i in range(n) if row_to_col[i] < m}
missed = [i for i in range(n) if i not in pairs]
taken = set(pairs.values())
new = [j for j in range(m) if j not in taken]
return pairs, missed, new, total
def cv_model(q, r):
"""Constant velocity model in 2D with a time step of 1: F, Q, H, R."""
f = [[1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
qm = [[q / 3, 0.0, q / 2, 0.0], [0.0, q / 3, 0.0, q / 2], [q / 2, 0.0, q, 0.0], [0.0, q / 2, 0.0, q]]
h = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]
rm = [[r, 0.0], [0.0, r]]
return f, qm, h, rm
class GNNTracker:
"""A multi-target tracker: Kalman prediction, GNN association, Kalman update, births."""
def __init__(self, gamma=9.21, q=0.05, r=0.25, p_vel=4.0, max_misses=3):
self.gamma, self.p_vel, self.max_misses = gamma, p_vel, max_misses
self.f, self.q, self.h, self.r = cv_model(q, r)
self.tracks = [] # each: {"id", "x" (4 x 1), "p" (4 x 4), "misses"}
self.next_id = 0
def _birth(self, z):
rr = self.r[0][0]
p = [[rr, 0, 0, 0], [0, rr, 0, 0], [0, 0, self.p_vel, 0], [0, 0, 0, self.p_vel]]
self.tracks.append({"id": self.next_id, "x": [[z[0]], [z[1]], [0.0], [0.0]], "p": p, "misses": 0})
self.next_id += 1
def step(self, zs):
"""Process the measurements of one frame. Returns {track id: (x, y)} after the update."""
z_hats, covs, gains = [], [], []
for t in self.tracks: # @line L1
t["x"] = mat_mul(self.f, t["x"])
t["p"] = mat_add(mat_mul(mat_mul(self.f, t["p"]), transpose(self.f)), self.q)
ph = mat_mul(t["p"], transpose(self.h))
s = mat_add(mat_mul(self.h, ph), self.r)
z_hats.append([row[0] for row in mat_mul(self.h, t["x"])])
covs.append(s)
gains.append(mat_mul(ph, inverse(s)))
pairs, missed, new, _ = gnn_assign(z_hats, covs, zs, self.gamma)
for i, j in pairs.items(): # @line L7
t, k = self.tracks[i], gains[i]
nu = [[zs[j][0] - z_hats[i][0]], [zs[j][1] - z_hats[i][1]]]
t["x"] = mat_add(t["x"], mat_mul(k, nu))
t["p"] = mat_sub(t["p"], mat_mul(mat_mul(k, covs[i]), transpose(k)))
t["misses"] = 0
for i in missed: # @line L8
self.tracks[i]["misses"] += 1
self.tracks = [t for t in self.tracks if t["misses"] < self.max_misses]
for j in new:
self._birth(zs[j])
return {t["id"]: (t["x"][0][0], t["x"][1][0]) for t in self.tracks}
def greedy_nearest_neighbor(z_hats, covs, zs, gamma):
"""The local rule for comparison: take the gated pair of least distance, remove both, repeat."""
cand = []
for i in range(len(z_hats)):
for j in range(len(zs)):
d2 = mahalanobis2(zs[j], z_hats[i], covs[i])
if d2 <= gamma:
cand.append((d2, i, j))
cand.sort()
pairs, used_t, used_m = {}, set(), set()
for _, i, j in cand:
if i not in used_t and j not in used_m:
pairs[i] = j
used_t.add(i)
used_m.add(j)
return pairs
test_global_nearest_neighbor_association.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/global-nearest-neighbor-association/. The authors are listed in prov/VW85MF.jsonl.
import itertools
import math
import random
from global_nearest_neighbor_association import (
INF,
GNNTracker,
gnn_assign,
greedy_nearest_neighbor,
hungarian,
mahalanobis2,
)
I2 = [[1.0, 0.0], [0.0, 1.0]]
def brute_partial(c, n, m, c_miss, c_new):
"""Least cost over all partial one-to-one matchings of tracks to measurements."""
best = INF
for k in range(0, min(n, m) + 1):
for rows in itertools.combinations(range(n), k):
for cols in itertools.permutations(range(m), k):
s = sum(c[i][j] for i, j in zip(rows, cols))
s += (n - k) * c_miss + (m - k) * c_new
best = min(best, s)
return best
def test_page_example():
z_hats = [(0.0, 0.0), (2.0, 0.0)]
zs = [(1.2, 0.0), (3.5, 0.0), (10.0, 5.0)]
pairs, missed, new, total = gnn_assign(z_hats, [I2, I2], zs, 9.21)
assert pairs == {0: 0, 1: 1}
assert missed == [] and new == [2]
assert abs(total - (1.44 + 2.25 + 4.605)) < 1e-9
assert greedy_nearest_neighbor(z_hats, [I2, I2], zs, 9.21) == {1: 0}
def test_mahalanobis():
s = [[4.0, 0.0], [0.0, 1.0]]
assert abs(mahalanobis2((2.0, 1.0), (0.0, 0.0), s) - 2.0) < 1e-12
s = [[2.0, 1.0], [1.0, 2.0]]
# inverse is [[2, -1], [-1, 2]] / 3, so (1, 1) gives 2 / 3
assert abs(mahalanobis2((1.0, 1.0), (0.0, 0.0), s) - 2.0 / 3.0) < 1e-12
def test_empty_inputs():
assert gnn_assign([], [], [], 9.21)[:3] == ({}, [], [])
pairs, missed, new, total = gnn_assign([(0.0, 0.0)], [I2], [], 9.21)
assert pairs == {} and missed == [0] and new == [] and abs(total - 4.605) < 1e-12
pairs, missed, new, total = gnn_assign([], [], [(1.0, 1.0)], 9.21)
assert pairs == {} and missed == [] and new == [0]
def test_hungarian_against_brute_force():
rng = random.Random(4417)
for _ in range(300):
r = rng.randint(1, 4)
c = rng.randint(r, 5)
a = [[rng.choice([INF] + [rng.randint(0, 20)] * 4) for _ in range(c)] for _ in range(r)]
best = INF
for cols in itertools.permutations(range(c), r):
best = min(best, sum(a[i][j] for i, j in enumerate(cols)))
res = hungarian(a)
if best == INF:
assert res is None
else:
row_to_col, total = res
assert len(set(row_to_col)) == r
assert total == best
def test_gnn_is_optimal_against_brute_force():
rng = random.Random(9031)
for _ in range(500):
n, m = rng.randint(0, 4), rng.randint(0, 4)
z_hats = [(rng.uniform(0, 8), rng.uniform(0, 8)) for _ in range(n)]
zs = [(rng.uniform(0, 8), rng.uniform(0, 8)) for _ in range(m)]
covs = []
for _ in range(n):
a, b, d = rng.uniform(0.5, 3), rng.uniform(-0.4, 0.4), rng.uniform(0.5, 3)
covs.append([[a, b], [b, d]])
gamma = rng.choice([5.991, 9.21])
c_miss, c_new = rng.uniform(1, 5), rng.uniform(1, 5)
pairs, missed, new, total = gnn_assign(z_hats, covs, zs, gamma, c_miss, c_new)
c = [[INF] * m for _ in range(n)]
for i in range(n):
for j in range(m):
d2 = mahalanobis2(zs[j], z_hats[i], covs[i])
c[i][j] = d2 if d2 <= gamma else INF
assert abs(total - brute_partial(c, n, m, c_miss, c_new)) < 1e-9
# the reported pairs are gated, one to one, and their cost is the total
assert len(set(pairs.values())) == len(pairs)
own = sum(c[i][j] for i, j in pairs.items()) + len(missed) * c_miss + len(new) * c_new
assert abs(own - total) < 1e-9
assert sorted(list(pairs) + missed) == list(range(n))
assert sorted(list(pairs.values()) + new) == list(range(m))
def test_gnn_never_worse_than_greedy():
rng = random.Random(77)
for _ in range(300):
n, m = rng.randint(1, 4), rng.randint(1, 4)
z_hats = [(rng.uniform(0, 5), rng.uniform(0, 5)) for _ in range(n)]
zs = [(rng.uniform(0, 5), rng.uniform(0, 5)) for _ in range(m)]
covs = [I2] * n
g = greedy_nearest_neighbor(z_hats, covs, zs, 9.21)
cost_g = sum(mahalanobis2(zs[j], z_hats[i], I2) for i, j in g.items())
cost_g += (n - len(g)) * 4.605 + (m - len(g)) * 4.605
total = gnn_assign(z_hats, covs, zs, 9.21)[3]
assert total <= cost_g + 1e-9
def test_tracker_follows_three_targets():
rng = random.Random(2024)
starts = [(0.0, 0.0, 1.0, 0.5), (0.0, 10.0, 1.0, -0.2), (20.0, 5.0, -0.8, 0.0)]
tracker = GNNTracker()
ids = None
errors = []
for t in range(30):
truth = [(x + vx * t, y + vy * t) for x, y, vx, vy in starts]
zs = [(a + rng.gauss(0, 0.5), b + rng.gauss(0, 0.5)) for a, b in truth]
if t % 7 == 3:
zs.append((rng.uniform(-5, 25), rng.uniform(-5, 15))) # a clutter point
rng.shuffle(zs)
est = tracker.step(zs)
if t < 5:
continue
if ids is None: # the track nearest to each target in frame 5
ids = [min(est, key=lambda k: math.hypot(est[k][0] - a, est[k][1] - b)) for a, b in truth]
assert len(set(ids)) == 3
for k, (a, b) in enumerate(truth):
ex, ey = est[ids[k]] # the same track must still exist
errors.append(math.hypot(ex - a, ey - b))
# each target keeps its track through the crossing of targets 0 and 1 near frame 14
assert max(errors) < 2.0
assert sum(errors) / len(errors) < 0.6
History
The assignment problem was solved by Harold Kuhn's Hungarian method in 1955, and James Munkres showed in 1957 that it runs in polynomial time. Radar trackers of the 1970s and 1980s used it to associate the returns of one scan with the existing tracks. Samuel Blackman's book of 1986, Multiple-Target Tracking with Radar Applications, presented the optimal assignment by the Munkres algorithm next to cheaper suboptimal rules, and his later survey of 2004 named the single best assignment of each scan the global nearest neighbor approach. Bar-Shalom and Fortmann (1988) and Blackman and Popoli (1999) give the method with gating and track management. In computer vision, the same step became the core of tracking-by-detection systems such as SORT (2016) and Deep SORT (2017), with box overlap or appearance features as the cost.
References
- Samuel S. Blackman and Robert Popoli, Design and Analysis of Modern Tracking Systems, Artech House, 1999, the chapters on gating and on data association (the global nearest neighbor method and its solution as an assignment problem)
- Samuel S. Blackman, Multiple hypothesis tracking for multiple target tracking, IEEE Aerospace and Electronic Systems Magazine 19(1), 2004, 5 to 18, the introduction (the name GNN for the single best assignment of each scan, and its comparison with MHT)
- Yaakov Bar-Shalom and Thomas E. Fortmann, Tracking and Data Association, Academic Press, 1988, the chapters on validation gates and on the nearest neighbor and assignment approaches to association
- Harold W. Kuhn, The Hungarian method for the assignment problem, Naval Research Logistics Quarterly 2(1-2), 1955, 83 to 97, the whole paper (the Hungarian method)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VW85MF Edit this page History Report an error Markdown