Algorithm Search⌘K

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.

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
Properties
deterministicexactnot iterativenot localonline
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 jj to track ii 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 nn tracks and a set of mm measurements z1,…,zmz_1, \ldots, z_m in Rp\mathbb{R}^p. Each track ii 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 z^i=Hx^i\hat z_i = H \hat x_i and the innovation covariance Si=HPiHT+RS_i = H P_i H^{\mathsf T} + R. The gate is a threshold γ\gamma on the squared Mahalanobis distance, for example the 99 percent point γ=9.210\gamma = 9.210 of the chi-square distribution with 2 degrees of freedom, as on track gating.

A feasible answer is a partial one-to-one matching MM of tracks to measurements in which every pair is inside the gate. Its cost is

J(M)=∑(i,j)∈Mdij2+cmiss⋅(tracks not in M)+cnew⋅(measurements not in M),J(M) = \sum_{(i, j) \in M} d^2_{ij} + c_{\text{miss}} \cdot (\text{tracks not in } M) + c_{\text{new}} \cdot (\text{measurements not in } M),

with dij2=(zj−z^i)TSi−1(zj−z^i)d^2_{ij} = (z_j - \hat z_i)^{\mathsf T} S_i^{-1} (z_j - \hat z_i). GNN returns a matching of least cost. The tracks in MM are updated with their measurements, the other tracks coast on their prediction, and the other measurements can start new tracks. In a likelihood form, dij2d^2_{ij} is replaced by dij2+ln⁡det⁡Sid^2_{ij} + \ln \det S_i, the negative log of the Gaussian density up to a constant. This page uses the plain distance, as many trackers do.

The algorithm

  1. GNN-STEP(the tracks, the measurements z_1..z_m, the gate γ, the costs c_miss and c_new)
  2. 1for each track i: predict x̂_i and P_i, then ẑ_i ← H x̂_i and S_i ← H P_i Hᵀ + R
  3. 2for each track i and each measurement j do
  4. 3d²_ij ← (z_j - ẑ_i)ᵀ S_i⁻¹ (z_j - ẑ_i)
  5. 4c_ij ← d²_ij if d²_ij ≤ γ, else ∞
  6. 5A ← the (n + m) × (m + n) matrix [[C, D_miss], [D_new, 0]] ▷ D_miss, D_new: c_miss, c_new on the diagonal, ∞ elsewhere
  7. 6solve the assignment problem on A with the Hungarian algorithm
  8. 7for each track i assigned to a column j ≤ m: Kalman update of track i with z_j
  9. 8other 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 cmissc_{\text{miss}}. A measurement whose dummy row takes the measurement's column is left over, at the cost cnewc_{\text{new}}. 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 AA is a partial matching of the same cost, and the reverse is also true. The default cmiss=cnew=γ/2c_{\text{miss}} = c_{\text{new}} = \gamma / 2 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 z^A=(0,0)\hat z_A = (0, 0) and z^B=(2,0)\hat z_B = (2, 0), both with S=IS = I. The frame has three measurements, z1=(1.2,0)z_1 = (1.2, 0), z2=(3.5,0)z_2 = (3.5, 0) and z3=(10,5)z_3 = (10, 5). The gate is γ=9.21\gamma = 9.21, and cmiss=cnew=4.605c_{\text{miss}} = c_{\text{new}} = 4.605. The squared distances are

z1z_1 z2z_2 z3z_3
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 z1z_1, at 0.64. After it is taken, track A has no measurement left in its gate, so A is missed, and z2z_2 and z3z_3 start new tracks. The cost is 0.64+3⋅4.605=14.4550.64 + 3 \cdot 4.605 = 14.455. 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 z1,z2,z3z_1, z_2, z_3, and the columns z1,z2,z3z_1, z_2, z_3 and the dummy columns of A and B, is

A=(1.44∞∞4.605∞0.642.25∞∞4.6054.605∞∞00∞4.605∞00∞∞4.60500).A = \begin{pmatrix} 1.44 & \infty & \infty & 4.605 & \infty \\ 0.64 & 2.25 & \infty & \infty & 4.605 \\ 4.605 & \infty & \infty & 0 & 0 \\ \infty & 4.605 & \infty & 0 & 0 \\ \infty & \infty & 4.605 & 0 & 0 \end{pmatrix}.

Its least-cost assignment takes A to z1z_1, B to z2z_2, the dummy row of z3z_3 to z3z_3, and the dummy rows of z1z_1 and z2z_2 to the two dummy columns. The cost is 1.44+2.25+4.605=8.2951.44 + 2.25 + 4.605 = 8.295. Track B gives up its closest measurement because track A has no other choice, and only z3z_3, 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 SiS_i, then dij2d^2_{ij} has the chi-square distribution with pp degrees of freedom. For p=2p = 2 the gate γ\gamma keeps it with probability exactly 1−e−γ/21 - e^{-\gamma/2}, which is 0.99 for γ=9.21\gamma = 9.21.
  • Theorem: the augmented matrix. The partial matchings inside the gate and the assignments of finite cost of AA correspond, with equal costs. So an optimal assignment of AA gives an optimal matching for the cost JJ. Such an assignment always exists, because all tracks missed and all measurements new is finite.
  • Theorem: gated pairs are used. If dij2<cmiss+cnewd^2_{ij} < c_{\text{miss}} + c_{\text{new}}, no optimal matching leaves both track ii and measurement jj 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 nn tracks and mm measurements. The gated cost is cij=dij2c_{ij} = d^2_{ij} if dij2≤γd^2_{ij} \le \gamma and cij=∞c_{ij} = \infty otherwise. A partial matching MM is a set of pairs (i,j)(i, j) with finite cijc_{ij} in which no track and no measurement appears twice. Its cost is J(M)=∑(i,j)∈Mcij+cmiss(n−∣M∣)+cnew(m−∣M∣)J(M) = \sum_{(i, j) \in M} c_{ij} + c_{\text{miss}} (n - |M|) + c_{\text{new}} (m - |M|), with cmiss,cnew≥0c_{\text{miss}}, c_{\text{new}} \ge 0 finite. The claims are about one frame.

Claim 1: the probability of the gate

Let ν=z−z^\nu = z - \hat z be Gaussian with mean 0 and a positive definite covariance SS in Rp\mathbb{R}^p. Then d2=νTS−1νd^2 = \nu^{\mathsf T} S^{-1} \nu has the chi-square distribution with pp degrees of freedom. For p=2p = 2, Pr⁡(d2≤γ)=1−e−γ/2\Pr(d^2 \le \gamma) = 1 - e^{-\gamma/2}.

Proof. Let S=LLTS = L L^{\mathsf T} be the Cholesky factorization and w=L−1νw = L^{-1} \nu. Then ww is Gaussian with covariance L−1SL−T=IL^{-1} S L^{-\mathsf T} = I, so its components are independent standard normal numbers. Also νTS−1ν=νTL−TL−1ν=wTw=∑kwk2\nu^{\mathsf T} S^{-1} \nu = \nu^{\mathsf T} L^{-\mathsf T} L^{-1} \nu = w^{\mathsf T} w = \sum_k w_k^2, a sum of pp squares of independent standard normal numbers, which is the definition of the chi-square distribution with pp degrees of freedom. For p=2p = 2 its density is 12e−x/2\tfrac12 e^{-x/2} on x≥0x \ge 0, and the integral from 0 to γ\gamma is 1−e−γ/21 - e^{-\gamma/2}. □\square

For γ=9.21\gamma = 9.21 this is 1−e−4.605=0.99001 - e^{-4.605} = 0.9900, and for γ=5.991\gamma = 5.991 it is 0.95000.9500. 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 AA be the (n+m)×(n+m)(n + m) \times (n + m) matrix of line L5. Rows 1,…,n1, \ldots, n are the tracks, rows n+1,…,n+mn + 1, \ldots, n + m are dummy rows of the measurements. Columns 1,…,m1, \ldots, m are the measurements, columns m+1,…,m+nm + 1, \ldots, m + n are dummy columns of the tracks. The entries are Aij=cijA_{ij} = c_{ij} for a track and a measurement, Ai,m+i=cmissA_{i, m+i} = c_{\text{miss}} and Ai,m+k=∞A_{i, m+k} = \infty for k≠ik \ne i, An+j,j=cnewA_{n+j, j} = c_{\text{new}} and An+j,k=∞A_{n+j, k} = \infty for a measurement column k≠jk \ne j, and An+j,m+i=0A_{n+j, m+i} = 0.

(a) Every partial matching MM gives a permutation σ\sigma with ∑rArσ(r)=J(M)\sum_r A_{r \sigma(r)} = J(M).

(b) Every permutation σ\sigma of finite cost gives the partial matching Mσ={(i,σ(i)):i≤n,σ(i)≤m}M_\sigma = \{(i, \sigma(i)) : i \le n, \sigma(i) \le m\} with J(Mσ)=∑rArσ(r)J(M_\sigma) = \sum_r A_{r \sigma(r)}.

(c) So if σ\sigma is an optimal permutation, MσM_\sigma is an optimal partial matching, and the two optimal costs are equal.

Proof of (a). Let ∣M∣=k|M| = k. Send each matched track ii to its measurement jj, at cost cijc_{ij}. Send each unmatched track ii to its dummy column m+im + i, at cost cmissc_{\text{miss}}. Send the dummy row of each unmatched measurement jj to column jj, at cost cnewc_{\text{new}}. So far the rows used are the nn track rows and the m−km - k dummy rows of unmatched measurements, and the columns used are the kk matched measurement columns, the n−kn - k dummy columns of unmatched tracks, and the m−km - k unmatched measurement columns. What is left is kk dummy rows of the matched measurements and kk 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 σ\sigma is a permutation, and its cost is ∑Mcij+(n−k)cmiss+(m−k)cnew=J(M)\sum_{M} c_{ij} + (n - k) c_{\text{miss}} + (m - k) c_{\text{new}} = J(M).

Proof of (b). Since the cost is finite, no entry ∞\infty is used. Track row ii goes either to a measurement column jj with cijc_{ij} finite, or to its own dummy column m+im + i. The pairs of the first kind form MσM_\sigma, and since σ\sigma is a permutation, no measurement appears twice, so MσM_\sigma is a partial matching. Let k=∣Mσ∣k = |M_\sigma|. The other n−kn - k tracks each pay cmissc_{\text{miss}}. A measurement column jj is used by exactly one row. If jj is in MσM_\sigma, 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 An+j,jA_{n+j, j}, so the row is the dummy row of jj, at cost cnewc_{\text{new}}. That gives m−km - k costs cnewc_{\text{new}}. The remaining dummy rows go to dummy columns at cost 0. The total is J(Mσ)J(M_\sigma).

Proof of (c). By (a), the least permutation cost is at most min⁡MJ(M)\min_M J(M). By (b), the cost of an optimal σ\sigma equals J(Mσ)≥min⁡MJ(M)J(M_\sigma) \ge \min_M J(M). So the two minima are equal and MσM_\sigma attains it. □\square

The empty matching has the finite cost ncmiss+mcnewn c_{\text{miss}} + m c_{\text{new}}, so by (a) AA 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 ∞\infty 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 ∞\infty, which cannot happen here.

Claim 3: gated pairs are used

If cij<cmiss+cnewc_{ij} < c_{\text{miss}} + c_{\text{new}}, then no optimal matching leaves both track ii and measurement jj unmatched.

Proof. Let MM leave both unmatched. Then M′=M∪{(i,j)}M' = M \cup \{(i, j)\} is a partial matching, and J(M′)=J(M)+cij−cmiss−cnew<J(M)J(M') = J(M) + c_{ij} - c_{\text{miss}} - c_{\text{new}} < J(M). So MM is not optimal. □\square

With the default cmiss=cnew=γ/2c_{\text{miss}} = c_{\text{new}} = \gamma / 2 the condition is dij2<γd^2_{ij} < \gamma, which holds for every gated pair except those on the boundary of the gate.

Claim 4: never worse than the greedy rule

Let GG 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 J(G)J(G).

Proof. GG 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 JJ over all partial matchings, so its cost is at most J(G)J(G). □\square

The example on the page has J(G)=14.455J(G) = 14.455 and a GNN cost of 8.2958.295, so the inequality can be strict.

Complexity

With the inverse of SiS_i computed once per track, the distances cost O(np3+nmp2)O(n p^3 + n m p^2). The augmented matrix has (n+m)2(n + m)^2 entries. The Hungarian algorithm with potentials solves an N×NN \times N assignment in O(N3)O(N^3) time, so a frame costs O(np3+nmp2+(n+m)3)O(n p^3 + n m p^2 + (n + m)^3) time and Θ((n+m)2)\Theta((n + m)^2) extra space. The Kalman updates of line L7 add O(nd3)O(n d^3) for a state of dimension dd. 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 kk costs O(k3)O(k^3), 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 JJ, 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 n×mn \times m matrix directly.
  • Likelihood costs. Use dij2+ln⁡det⁡Sid^2_{ij} + \ln \det S_i, 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 1−IoU1 - \mathrm{IoU} 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 cmiss+cnewc_{\text{miss}} + c_{\text{new}} 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 SiS_i gets small distances to everything. The term ln⁡det⁡Si\ln \det S_i 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.

global_nearest_neighbor_association.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example