Algorithm Search⌘K

Algorithmadvanced

Multiple hypothesis tracking

Also called MHT, Reid's algorithm.

Keep a tree of association hypotheses over several frames, score them by likelihood, and prune, so that hard choices are made only when later data decide them.

Time
O(M² m³ (n + m) + M n d³) worst · average · best
Space
O(M (n d² + m (n + m))) extra
Where
M = the number of hypotheses kept; d = the dimension of a state; m = the number of measurements in a frame; n = the number of tracks in a hypothesis
Properties
deterministicnot exactnot iterativenot localonline
Origin
Donald B. Reid, 1979

Multiple hypothesis tracking, or MHT, keeps several explanations of the measurements alive at once and decides between them only when later frames make the answer clear. A hypothesis is a complete story so far: which measurements form which tracks, which were false alarms, and which started new targets. In each frame every hypothesis is extended in every way the new measurements allow, each extension gets a probability by Reid's formula, and the least likely hypotheses are dropped. Donald Reid gave the method in 1979. Cox and Hingorani showed in 1996 that the best extensions of a hypothesis are the best solutions of one assignment problem, so they can be found in order with Murty's k-best method instead of by listing all of them. With one hypothesis kept, MHT is GNN with likelihood costs. With many, it can recover from a decision that looked best in one frame but was wrong.

In plain words

A detective with three suspects and a few clues does not name the culprit after the first clue. She keeps a short list of the stories that fit, each with a rough score. Each new clue can split a story into several, and stories that no longer fit drop off the list. MHT does this with measurements. A blip on the screen might be the plane we already follow, a new plane, or noise, so each story splits into several. The list is kept short by keeping only the few best stories, and the tracker reports the best story so far. If a later frame shows that the second-best story was right, the tracker switches to it, and the past is fixed at the same time.

The problem

The input is a sequence of frames, each with a set of measurements z1,…,zmz_1, \ldots, z_m, and a model: a Kalman filter per target, a detection probability pDp_D, a density βFT\beta_{FT} of false alarms and a density βNT\beta_{NT} of new targets per unit of measurement space, and a gate γ\gamma. A hypothesis hh is a partition of all past measurements into tracks and false alarms. Reid's formula gives its probability recursively. If a child h′h' of hh assigns the new measurements so that NDTN_{DT} of the nn tracks of hh are detected, NFTN_{FT} measurements are false alarms and NNTN_{NT} start new targets, then

P(h′)∝P(h)  pDNDT(1−pD)n−NDT  βFTNFT  βNTNNT∏(i,j)N(zj;z^i,Si),P(h') \propto P(h) \; p_D^{N_{DT}} (1 - p_D)^{n - N_{DT}} \; \beta_{FT}^{N_{FT}} \; \beta_{NT}^{N_{NT}} \prod_{(i, j)} \mathcal N(z_j; \hat z_i, S_i),

with the product over the pairs of a track and its measurement, and the constant the same for all children in the frame. The output in each frame is the track set of the most probable hypothesis.

The algorithm

  1. MHT-STEP(the hypotheses h with log weights w_h, the measurements z_1..z_m, the number M kept)
  2. 1for each hypothesis h: predict every track of h, with ẑ_i and S_i
  3. 2C ← the m × (n + 2m) matrix of h: c_ji ← -ln(p_D N(z_j; ẑ_i, S_i) / (1 - p_D)) if gated, else ∞; c_j,NT_j ← -ln β_NT; c_j,FT_j ← -ln β_FT
  4. 3the M assignments of least cost of C, by Murty's method
  5. 4for each such assignment a: a child of h with log weight w_h + n ln(1 - p_D) - cost(a)
  6. 5keep the M children of highest weight over all hypotheses, and normalize their weights
  7. 6in each kept child: update the assigned tracks, start the new targets, delete tracks missed too often
  8. 7return the tracks of the hypothesis of highest weight

A row of CC is a measurement. It can go to a track in its gate, to its own new-target column, or to its own false-alarm column. Other entries are ∞\infty, so each measurement has exactly one role, and each track takes at most one measurement. The cost of an assignment is the negative log of Reid's factor for that child, divided by the factor (1−pD)n(1 - p_D)^n of a child with no detection. Line L4 puts the factor back.

Murty's method. It finds the assignments of a matrix in order of cost. Solve the matrix with the Hungarian algorithm and put the solution in a priority queue. Pop the cheapest solution aa and report it. Then split the rest of its subproblem into disjoint parts: in part tt, the free rows before row tt keep their columns in aa, and row tt may not use its column a(t)a(t). Solve each part and push it. Every other assignment of the subproblem falls in exactly one part.

Line L6 holds the track management, and it is a heuristic. The code deletes a track after 3 misses in a row and starts a new track at a measurement assigned to its new-target column, with zero velocity.

Example

One frame by hand. Two tracks predict z^A=(1,0)\hat z_A = (1, 0) and z^B=(1,2)\hat z_B = (1, 2), both with S=0.653IS = 0.653 I. The measurements are z1=(1.2,0.3)z_1 = (1.2, 0.3), z2=(1.0,1.4)z_2 = (1.0, 1.4) and z3=(0.8,2.2)z_3 = (0.8, 2.2), and pD=0.8p_D = 0.8, βFT=0.02\beta_{FT} = 0.02, βNT=0.002\beta_{NT} = 0.002. The cost matrix, with the columns A, B, the three new-target columns and the three false-alarm columns, is

C=(0.1252.2686.215∞∞3.912∞∞1.5260.301∞6.215∞∞3.912∞3.7610.087∞∞6.215∞∞3.912).C = \begin{pmatrix} 0.125 & 2.268 & 6.215 & \infty & \infty & 3.912 & \infty & \infty \\ 1.526 & 0.301 & \infty & 6.215 & \infty & \infty & 3.912 & \infty \\ 3.761 & 0.087 & \infty & \infty & 6.215 & \infty & \infty & 3.912 \end{pmatrix}.

The frame has 44 children. The best three, with their probabilities among all children, are:

Child Probability
z1→Az_1 \to A, z2z_2 false, z3→Bz_3 \to B 0.416
z1→Az_1 \to A, z2→Bz_2 \to B, z3z_3 false 0.336
z1z_1 false, z2→Az_2 \to A, z3→Bz_3 \to B 0.103

The first two are close. GNN would commit to the first. MHT keeps both, and the next frame, where the true track of B lands near one of z2z_2 and z3z_3, decides.

A short sequence. In the code, two targets with velocities (1,±0.25)(1, \pm 0.25) cross at frame 10, each is detected with probability 0.85 and noise 0.5, and about one clutter point per frame falls near them. With M=5M = 5 hypotheses over 20 frames, both tracks keep their identities, with a largest error of 0.99 and a mean error of 0.43. In this scene M=1M = 1 does about as well. The benefit of more hypotheses shows when detections are missed for several frames during a close approach, when the best single choice is often wrong.

Correctness

The full proof is in proofs/correctness.md. It shows these facts.

  • Theorem: costs and Reid's formula. The assignments of finite cost of CC correspond one to one with the children of hh, and the log weight of line L4 is the log of Reid's formula up to a constant that is the same for all children of all hypotheses in the frame.
  • Theorem: Murty's method. It returns the assignments in order of nondecreasing cost, with no repeats and no gaps.
  • Theorem: global pruning. Keeping the MM best children of each hypothesis and then the MM best overall gives exactly the MM best children of all hypotheses.
  • Theorem: hardness of the batch problem. Finding the best partition of the measurements of 3 frames into tracks is NP-hard, by a reduction from three-dimensional matching. So MHT prunes, and the hypothesis it returns is the best among those it kept, not always the best overall.
Proof: Why the cost matrix encodes Reid's formula, why Murty's method lists the assignments in order, why global pruning keeps the best children, and why the batch problem is NP-hardfull

Notation as on the page. A hypothesis hh has nn tracks and the log weight whw_h. The frame has mm measurements. The matrix CC of hh has mm rows and n+2mn + 2m columns: the tracks, then one new-target column NTjNT_j and one false-alarm column FTjFT_j for each measurement jj.

Claim 1: the children of a hypothesis and the cost of an assignment

A child of hh gives each measurement exactly one role: a track of hh whose gate holds it, a new target, or a false alarm, with no track given two measurements. The children of hh correspond one to one with the assignments of finite cost of CC (each row to a distinct column), and for the child of the assignment aa,

wh+nln⁡(1−pD)−cost⁡(a)=wh+NDTln⁡pD+(n−NDT)ln⁡(1−pD)+NFTln⁡βFT+NNTln⁡βNT+∑(i,j)ln⁡N(zj;z^i,Si),w_h + n \ln(1 - p_D) - \operatorname{cost}(a) = w_h + N_{DT} \ln p_D + (n - N_{DT}) \ln(1 - p_D) + N_{FT} \ln \beta_{FT} + N_{NT} \ln \beta_{NT} + \sum_{(i,j)} \ln \mathcal N(z_j; \hat z_i, S_i),

which is the log of Reid's formula.

Proof. Given a child, send row jj to the column of the track of zjz_j, or to NTjNT_j, or to FTjFT_j. Two rows never share a track column because a track takes at most one measurement, and they never share an NTNT or FTFT column because column NTjNT_j and column FTjFT_j are finite only in row jj. A track column is used only if the pair is gated, so the cost is finite. Conversely, an assignment of finite cost uses only finite entries, which are exactly the allowed roles, and distinct columns mean that no track gets two measurements. The two maps are inverse to each other.

The cost of aa is ∑(i,j)[−ln⁡pD−ln⁡Nij+ln⁡(1−pD)]−NNTln⁡βNT−NFTln⁡βFT\sum_{(i,j)} [-\ln p_D - \ln \mathcal N_{ij} + \ln(1 - p_D)] - N_{NT} \ln \beta_{NT} - N_{FT} \ln \beta_{FT}, with NDTN_{DT} terms in the sum. So nln⁡(1−pD)−cost⁡(a)=NDTln⁡pD+(n−NDT)ln⁡(1−pD)+∑ln⁡Nij+NNTln⁡βNT+NFTln⁡βFTn \ln(1 - p_D) - \operatorname{cost}(a) = N_{DT} \ln p_D + (n - N_{DT}) \ln(1 - p_D) + \sum \ln \mathcal N_{ij} + N_{NT} \ln \beta_{NT} + N_{FT} \ln \beta_{FT}. □\square

In Reid's derivation, the posterior of a child is this factor times the posterior of its parent, divided by a normalizing constant that depends only on the measurements of the frame. So the constant is the same for every child of every hypothesis, and comparing log weights compares posterior probabilities. Line L5 removes the constant by normalizing.

Claim 2: Murty's method lists the assignments in order of cost

A node of the search is a subproblem: the assignments that use every pair of a set FF (forced) and no pair of a set BB (forbidden). Let aa be the best assignment of the subproblem (F,B)(F, B) and r1<…<rkr_1 < \ldots < r_k the rows not forced by FF. For t=1,…,kt = 1, \ldots, k let part tt be the subproblem (F∪{(rs,a(rs)):s<t}, B∪{(rt,a(rt))})(F \cup \{(r_s, a(r_s)) : s < t\},\ B \cup \{(r_t, a(r_t))\}). Then the assignments of (F,B)(F, B) other than aa are split by the parts: each lies in exactly one part, and each assignment of a part lies in (F,B)(F, B).

Proof. A part only adds constraints, so its assignments lie in (F,B)(F, B), and aa lies in no part because it uses the forbidden pair (rt,a(rt))(r_t, a(r_t)) of part tt. Let b≠ab \ne a be an assignment of (F,B)(F, B). On the forced rows, bb and aa agree, so they differ on some free row. Let tt be the first tt with b(rt)≠a(rt)b(r_t) \ne a(r_t). Then bb uses the forced pairs of part tt and avoids its new forbidden pair, so bb is in part tt. For s<ts < t, bb uses (rs,a(rs))(r_s, a(r_s)), which part ss forbids. For s>ts > t, part ss forces (rt,a(rt))(r_t, a(r_t)), which bb does not use. So bb is in no other part. □\square

By induction on the number of reported assignments, the subproblems in the priority queue split the set of assignments not yet reported, with no overlap. Each subproblem is stored with its best cost, so the cheapest entry of the queue holds an assignment of least cost among all those not yet reported. So the reported costs are nondecreasing, no assignment is reported twice, and none is skipped. A subproblem with no finite assignment is not pushed, which removes nothing. The constraints are applied by setting entries to ∞\infty: a forbidden pair gets ∞\infty, and a forced pair (r,c)(r, c) gets ∞\infty in the rest of row rr and of column cc. The Hungarian algorithm then returns a best assignment of the subproblem or reports that none exists.

Claim 3: keeping the best children of each parent, then the best overall, is exact

Let every hypothesis produce its MM best children by Claim 2, and keep the MM best of all of them. Then the kept log weights are the MM largest log weights over all children of all hypotheses.

Proof. Within one parent, the log weight of a child is wh+nhln⁡(1−pD)w_h + n_h \ln(1 - p_D) minus its cost, so the order by weight is the order by cost. Let cc be a child of hh among the MM best overall. Fewer than MM children of all hypotheses have a strictly larger weight, so fewer than MM children of hh do. So the weight of cc is among the MM largest weights of the children of hh, which Murty's method returns (with ties, a child of the same weight is returned instead). So the union of the lists holds MM children with the MM largest weights overall, and the final cut keeps them. □\square

With M=1M = 1, the single kept child of a single hypothesis is the best assignment of CC, which is GNN with the costs of CC.

Claim 4: the best partition of three frames into tracks is NP-hard

Consider the batch problem: given the measurements of 3 frames, a cost for every possible track (a choice of at most one measurement per frame) and a cost for every measurement left out, partition the measurements into tracks and left-out measurements at least total cost. This problem is NP-hard.

Proof. Reduce from three-dimensional matching, which Karp (1972) proved NP-complete. An instance has three sets XX, YY, ZZ of size qq and a set T⊆X×Y×ZT \subseteq X \times Y \times Z, and asks whether qq triples of TT cover every element exactly once. Make frame 1 hold one measurement per element of XX, frame 2 one per element of YY, and frame 3 one per element of ZZ. A track with one measurement in each frame, (x,y,z)(x, y, z), costs 0 if (x,y,z)∈T(x, y, z) \in T and 1 otherwise. Every other track, which misses a frame, costs q+1q + 1, and so does a left-out measurement.

Any qq disjoint full triples cover all measurements at cost at most qq, so an optimal partition costs at most qq and uses no short track and no left-out measurement. So it is a split of the measurements into qq full triples, and its cost is the number of triples not in TT. The optimum is 0 if and only if the instance has a perfect matching. The construction takes polynomial time. □\square

MHT with pruning does not solve this problem exactly. Its hypothesis of highest weight is the best among the hypotheses it kept. If no hypothesis is ever dropped, MHT is exact for its model, at a cost exponential in the number of frames.

Complexity

Per frame, each of the MM hypotheses builds a matrix with mm rows and n+2mn + 2m columns. Murty's method for MM solutions solves up to MmM m subproblems, each by the Hungarian algorithm in O(m2(n+m))O(m^2 (n + m)) time. So a frame costs O(M2m3(n+m))O(M^2 m^3 (n + m)) for the assignments and O(Mnd3)O(M n d^3) for the Kalman filters. Sorting the M2M^2 children adds O(M2log⁡M)O(M^2 \log M). The space is O(M(nd2+m(n+m)))O(M (n d^2 + m (n + m))). Practical systems cut this down: they split the measurements and tracks into clusters by the gates, run Murty's method on each cluster, and use the optimized versions of Murty's method of Miller, Stone and Cox (1997). Without pruning, the number of hypotheses grows exponentially with the number of frames.

Properties

  • Deferred decisions. A choice made in frame tt can be reversed in a later frame, as long as the other hypothesis is still kept.
  • Track initiation built in. New targets and false alarms are part of each hypothesis, so MHT starts and confirms tracks with the same scoring.
  • Approximate. Pruning to MM hypotheses can drop the right one.
  • A model of the data. The quality depends on pDp_D, βFT\beta_{FT} and βNT\beta_{NT}, which must be set or estimated.
  • Many hypotheses share tracks. Implementations store tracks once and point to them, which the simple code here does not do.

Variants and improvements

  • Track-oriented MHT. Keep a tree of possible tracks instead of a list of hypotheses, score each track by a log-likelihood ratio, and find the best global hypothesis as a set of compatible tracks by integer programming. Kurien (1990) and Blackman (2004) describe this form, and most current systems use it.
  • N-scan pruning. Fix every decision older than NN frames to the choice of the best hypothesis, which bounds the depth of the tree.
  • Multi-frame assignment. Poore and others write the last few frames as a multidimensional assignment problem and solve it with Lagrangian relaxation.
  • MHT revisited. Kim, Li, Ciptadi and Rehg (2015) added online appearance models to track-oriented MHT and obtained strong results on video benchmarks.
  • Batch alternatives. Network flow tracking solves a simpler model of the whole video exactly in polynomial time.
  • Soft alternatives. JPDA averages over the hypotheses of one frame instead of keeping them.

When to use it

Use MHT when the targets come close to each other, detections are missed, and wrong identity decisions are costly, as in air surveillance or in tracking people through crowds. It is heavier than GNN and JPDA and has more parameters, so it pays off when those simpler methods swap or lose tracks. For offline video where all frames are known, network flow tracking is a simpler choice with an exact solution of its own model.

Pitfalls

  • Too few hypotheses. With a small MM, the right hypothesis can be dropped in the frame where it is second, and it never comes back.
  • Pruning only per parent. Keeping MM children per parent without the global cut makes the number of hypotheses grow as MtM^t.
  • Weights that underflow. Probabilities of long histories become tiny. Work with log weights and normalize each frame.
  • Duplicate tracks. Different hypotheses can contain the same track. Without sharing, memory grows quickly.
  • Wrong clutter and birth densities. If βNT\beta_{NT} is too large, every clutter point starts a track. If it is too small, true new targets are called false alarms for too long.
  • Reporting a jumping answer. The best hypothesis can change from frame to frame, so the reported tracks can jump. Report decisions with a delay of a few frames if that matters.

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.

multiple_hypothesis_tracking.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-hypothesis-tracking/. The authors are listed in prov/XRTTYC.jsonl.
"""Multiple hypothesis tracking (MHT), hypothesis-oriented, after Reid (1979),
with the k-best assignments of Murty (1968) as proposed by Cox and Hingorani (1996).

A hypothesis is a full explanation of all measurements so far: a set of tracks,
each a Kalman filter, and a log weight. In each frame every hypothesis spawns
children, one per assignment of the new measurements to its tracks, to new
targets or to false alarms. The log weight of a child follows Reid's formula,
which turns into a cost matrix with one row per measurement, so the best
children of a hypothesis are the k best assignments of that matrix. The M
children of highest weight over all hypotheses are kept. Matrices are lists of
rows.
"""

import heapq
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_and_det(a):
    """Inverse and determinant of a small nonsingular matrix by Gauss-Jordan elimination."""
    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)]
    det = 1.0
    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")
        if p != c:
            m[c], m[p] = m[p], m[c]
            det = -det
        piv = m[c][c]
        det *= piv
        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], det


def hungarian(cost):
    """Least-cost assignment of the rows of an r x c matrix (r <= c) to distinct columns.

    Entries may be INF. Returns (total, row_to_col), or None if every
    assignment has an INF entry. 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 sum(cost[i][row_to_col[i]] for i in range(r)), row_to_col


def _constrained(cost, forced, forbidden):
    a = [list(row) for row in cost]
    for r, c in forbidden:
        a[r][c] = INF
    for r, c in forced:
        for k in range(len(a[0])):
            if k != c:
                a[r][k] = INF
        for k in range(len(a)):
            if k != r:
                a[k][c] = INF
    return a


def murty_k_best(cost, k):
    """The k assignments of least cost, in order of cost, by Murty's partitioning.

    Returns a list of (total, row_to_col). Each node of the search is the
    original problem with some pairs forced and some forbidden. Its best
    assignment is split into disjoint subproblems: for the t-th free row, the
    rows before it keep their columns and row t loses its column.
    """
    first = hungarian(cost)
    if first is None or k <= 0:
        return []
    tie = 0
    heap = [(first[0], tie, first[1], (), ())]
    out = []
    while heap and len(out) < k:
        total, _, sol, forced, forbidden = heapq.heappop(heap)
        out.append((total, sol))
        fixed = list(forced)
        forced_rows = {r for r, _ in forced}
        for row in range(len(cost)):
            if row in forced_rows:
                continue
            sub_forbidden = forbidden + ((row, sol[row]),)
            res = hungarian(_constrained(cost, fixed, sub_forbidden))
            if res is not None:
                tie += 1
                heapq.heappush(heap, (res[0], tie, res[1], tuple(fixed), sub_forbidden))
            fixed.append((row, sol[row]))
    return out


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 MHT:
    """Hypothesis-oriented MHT with M hypotheses, a gate, and deletion after max_misses misses in a row."""

    def __init__(self, p_d=0.9, beta_nt=0.001, beta_ft=0.01, gamma=9.21, m_best=5, q=0.01, r=0.25, p_vel=1.0, max_misses=3):
        self.p_d, self.beta_nt, self.beta_ft = p_d, beta_nt, beta_ft
        self.gamma, self.m_best, self.max_misses, self.p_vel = gamma, m_best, max_misses, p_vel
        self.model = cv_model(q, r)
        self.next_id = 0
        self.hyps = [(0.0, [])]  # (log weight, tracks); a track is (id, x, P, misses)

    def add_track(self, x, p):
        """Add a known track to every hypothesis (used to start from given targets)."""
        tid = self.next_id
        self.next_id += 1
        self.hyps = [(w, tracks + [(tid, x, p, 0)]) for w, tracks in self.hyps]
        return tid

    def _predict(self, tracks):
        f, q, h, r = self.model
        out = []
        for tid, x, p, misses in tracks:
            xp = mat_mul(f, x)
            pp = mat_add(mat_mul(mat_mul(f, p), transpose(f)), q)
            ph = mat_mul(pp, transpose(h))
            s = mat_add(mat_mul(h, ph), r)
            s_inv, det = inverse_and_det(s)
            z_hat = [row[0] for row in mat_mul(h, xp)]
            out.append((tid, xp, pp, misses, z_hat, s, s_inv, det, mat_mul(ph, s_inv)))
        return out

    def cost_matrix(self, pred, zs):
        """Rows: measurements. Columns: the n tracks, then m new-target and m false-alarm columns."""
        n, m = len(pred), len(zs)
        cost = [[INF] * (n + 2 * m) for _ in range(m)]
        for j, z in enumerate(zs):
            for i, (_, _, _, _, z_hat, s, s_inv, det, _) in enumerate(pred):
                nu = [[a - b] for a, b in zip(z, z_hat)]
                d2 = mat_mul(mat_mul(transpose(nu), s_inv), nu)[0][0]
                if d2 <= self.gamma:
                    dens = math.exp(-0.5 * d2) / math.sqrt((2 * math.pi) ** len(z) * det)
                    cost[j][i] = -math.log(self.p_d * dens / (1.0 - self.p_d))
            cost[j][n + j] = -math.log(self.beta_nt)
            cost[j][n + m + j] = -math.log(self.beta_ft)
        return cost

    def _child(self, pred, zs, row_to_col):
        h = self.model[2]
        n = len(pred)
        taken = {c: j for j, c in enumerate(row_to_col) if c < n}
        tracks, births = [], []
        for i, (tid, xp, pp, misses, z_hat, s, _, _, k) in enumerate(pred):
            if i in taken:
                z = zs[taken[i]]
                nu = [[a - b] for a, b in zip(z, z_hat)]
                x = mat_add(xp, mat_mul(k, nu))
                p = mat_sub(pp, mat_mul(mat_mul(k, s), transpose(k)))
                tracks.append((tid, x, p, 0))
            else:
                tracks.append((tid, xp, pp, misses + 1))
        for j, c in enumerate(row_to_col):
            if n <= c < n + len(zs):
                births.append(zs[j])
        return tracks, births

    def children_of(self, w, tracks, zs, k):
        """The k children of highest log weight of one hypothesis: (log weight, predicted tracks, assignment)."""
        pred = self._predict(tracks)  # @line L1
        cost = self.cost_matrix(pred, zs)  # @line L2
        out = []
        for total, row_to_col in murty_k_best(cost, k):  # @line L3
            lw = w + len(pred) * math.log(1.0 - self.p_d) - total  # @line L4
            out.append((lw, pred, row_to_col))
        return out

    def step(self, zs):
        """Process one frame. Returns {track id: (x, y)} of the best hypothesis."""
        children = []
        for w, tracks in self.hyps:
            children.extend(self.children_of(w, tracks, zs, self.m_best))
        children.sort(key=lambda c: -c[0])
        children = children[: self.m_best]  # @line L5
        top = children[0][0]
        norm = top + math.log(sum(math.exp(c[0] - top) for c in children))
        rr = self.model[3][0][0]
        new_hyps = []
        for lw, pred, row_to_col in children:
            tracks, births = self._child(pred, zs, row_to_col)
            tracks = [t for t in tracks if t[3] < self.max_misses]  # @line L6
            for z in births:
                tracks.append((self.next_id, [[z[0]], [z[1]], [0.0], [0.0]], [[rr, 0, 0, 0], [0, rr, 0, 0], [0, 0, self.p_vel, 0], [0, 0, 0, self.p_vel]], 0))
                self.next_id += 1
            new_hyps.append((lw - norm, tracks))
        self.hyps = new_hyps
        best = max(self.hyps, key=lambda h: h[0])  # @line L7
        return {t[0]: (t[1][0][0], t[1][1][0]) for t in best[1]}
test_multiple_hypothesis_tracking.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiple-hypothesis-tracking/. The authors are listed in prov/XRTTYC.jsonl.

import itertools
import math
import random

from multiple_hypothesis_tracking import INF, MHT, hungarian, murty_k_best


def all_assignments(cost):
    r = len(cost)
    c = len(cost[0]) if r else 0
    out = []
    for cols in itertools.permutations(range(c), r):
        s = sum(cost[i][j] for i, j in enumerate(cols))
        if s < INF:
            out.append((s, list(cols)))
    out.sort(key=lambda t: t[0])
    return out


def test_hungarian_and_murty_against_brute_force():
    rng = random.Random(1968)
    for _ in range(150):
        r = rng.randint(1, 4)
        c = rng.randint(r, 6)
        cost = [[INF if rng.random() < 0.3 else rng.randint(0, 30) for _ in range(c)] for _ in range(r)]
        every = all_assignments(cost)
        k = rng.randint(1, 12)
        got = murty_k_best(cost, k)
        assert len(got) == min(k, len(every))
        # the costs are the k smallest, in order; the assignments are valid and distinct
        assert [g[0] for g in got] == [e[0] for e in every[: len(got)]]
        seen = set()
        for total, sol in got:
            assert len(set(sol)) == r
            assert sum(cost[i][j] for i, j in enumerate(sol)) == total
            seen.add(tuple(sol))
        assert len(seen) == len(got)
        if every:
            assert hungarian(cost)[0] == every[0][0]
        else:
            assert hungarian(cost) is None


def reid_log_weight(mht, pred, zs, owner):
    """Reid's formula, written directly: owner[j] is a track index, 'NT' or 'FT'."""
    n = len(pred)
    lw = 0.0
    detected = 0
    for j, o in enumerate(owner):
        if o == "NT":
            lw += math.log(mht.beta_nt)
        elif o == "FT":
            lw += math.log(mht.beta_ft)
        else:
            _, _, _, _, z_hat, s, s_inv, det, _ = pred[o]
            nu = [zs[j][0] - z_hat[0], zs[j][1] - z_hat[1]]
            d2 = sum(nu[a] * s_inv[a][b] * nu[b] for a in range(2) for b in range(2))
            if d2 > mht.gamma:
                return None
            lw += math.log(mht.p_d) - 0.5 * d2 - 0.5 * math.log((2 * math.pi) ** 2 * det)
            detected += 1
    return lw + (n - detected) * math.log(1.0 - mht.p_d)


def two_track_mht():
    mht = MHT(p_d=0.8, beta_nt=0.002, beta_ft=0.02, gamma=9.21)
    mht.add_track([[0.0], [0.0], [1.0], [0.0]], [[0.3, 0, 0, 0], [0, 0.3, 0, 0], [0, 0, 0.1, 0], [0, 0, 0, 0.1]])
    mht.add_track([[0.0], [2.0], [1.0], [0.0]], [[0.3, 0, 0, 0], [0, 0.3, 0, 0], [0, 0, 0.1, 0], [0, 0, 0, 0.1]])
    return mht


def test_children_follow_reid_formula():
    mht = two_track_mht()
    zs = [(1.2, 0.3), (1.0, 1.4), (0.8, 2.2)]
    w, tracks = mht.hyps[0]
    children = mht.children_of(w, tracks, zs, 10 ** 6)
    pred = children[0][1]
    brute = []
    for owner in itertools.product([0, 1, "NT", "FT"], repeat=len(zs)):
        used = [o for o in owner if o in (0, 1)]
        if len(used) != len(set(used)):
            continue
        lw = reid_log_weight(mht, pred, zs, owner)
        if lw is not None:
            brute.append(lw)
    brute.sort(reverse=True)
    got = [c[0] for c in children]
    assert len(got) == len(brute)
    assert all(abs(a - b) < 1e-9 for a, b in zip(got, brute))
    # the best child gives z1 to track 0 and z3 to track 1, and calls z2 a false alarm
    best = children[0][2]
    assert best[0] == 0 and best[2] == 1 and best[1] == 2 + 3 + 1


def test_global_top_m_is_exact():
    rng = random.Random(42)
    for _ in range(20):
        mht = two_track_mht()
        mht.m_best = 4
        mht.step([(1.0 + rng.gauss(0, 0.5), rng.gauss(0, 0.5)), (1.0 + rng.gauss(0, 0.5), 2.0 + rng.gauss(0, 0.5))])
        zs = [(2.0 + rng.gauss(0, 0.7), rng.gauss(0, 0.7)) for _ in range(2)] + [(2.0, 2.0 + rng.gauss(0, 0.5))]
        every = []
        for w, tracks in mht.hyps:
            every.extend(c[0] for c in mht.children_of(w, tracks, zs, 10 ** 6))
        every.sort(reverse=True)
        kept = []
        for w, tracks in mht.hyps:
            kept.extend(c[0] for c in mht.children_of(w, tracks, zs, mht.m_best))
        kept.sort(reverse=True)
        assert all(abs(a - b) < 1e-9 for a, b in zip(kept[: mht.m_best], every[: mht.m_best]))


def test_weights_are_normalized():
    mht = two_track_mht()
    mht.step([(1.1, 0.1), (0.9, 2.1), (5.0, 5.0)])
    assert abs(sum(math.exp(w) for w, _ in mht.hyps) - 1.0) < 1e-12
    assert len(mht.hyps) == mht.m_best


def test_no_measurements():
    mht = two_track_mht()
    est = mht.step([])
    assert sorted(est) == [0, 1]
    assert len(mht.hyps) == 1


def poisson(rng, mean):
    limit, k, prod = math.exp(-mean), 0, rng.random()
    while prod > limit:
        k += 1
        prod *= rng.random()
    return k


def run_scene(m_best, seed):
    rng = random.Random(seed)
    starts = [(0.0, 0.0, 1.0, 0.25), (0.0, 5.0, 1.0, -0.25)]  # the paths cross at frame 10
    mht = MHT(p_d=0.85, beta_nt=0.001, beta_ft=0.01, m_best=m_best)
    for x0, y0, vx, vy in starts:
        mht.add_track([[x0], [y0], [vx], [vy]], [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.01, 0], [0, 0, 0, 0.01]])
    errs = []
    for t in range(1, 21):
        truth = [(x0 + vx * t, y0 + vy * t) for x0, y0, vx, vy in starts]
        zs = [(a + rng.gauss(0, 0.5), b + rng.gauss(0, 0.5)) for a, b in truth if rng.random() < 0.85]
        for _ in range(poisson(rng, 1.0)):
            zs.append((truth[0][0] + rng.uniform(-5, 5), 2.5 + rng.uniform(-5, 5)))
        rng.shuffle(zs)
        est = mht.step(zs)
        for tid, (a, b) in enumerate(truth):
            if tid in est:
                errs.append(math.hypot(est[tid][0] - a, est[tid][1] - b))
            else:
                errs.append(INF)
    return errs


def test_two_crossing_targets_in_clutter():
    errs = run_scene(5, 1979)
    assert max(errs) < 2.0
    assert sum(errs) / len(errs) < 0.6

History

Donald Reid published the algorithm in 1979. He gave the recursive formula for the probability of a hypothesis, track initiation inside the same framework, and the clustering of tracks that share measurements. The exponential growth of hypotheses limited the method for years. Cox and Hingorani (1996) noted that the best children of a hypothesis are the best solutions of an assignment problem and generated them with Murty's 1968 algorithm for ranking assignments, which made Reid's method fast enough for vision. The track-oriented form, described by Kurien in 1990, became the standard in radar systems, and Blackman's 2004 survey called MHT the generally preferred method for data association in modern tracking systems. In 2015, Kim, Li, Ciptadi and Rehg revisited MHT for video and showed it was competitive with newer methods on multiple object tracking benchmarks.

References

  1. Donald B. Reid, An algorithm for tracking multiple targets, IEEE Transactions on Automatic Control 24(6), 1979, 843 to 854, the whole paper (hypothesis generation, the probability of a hypothesis, track initiation and pruning)
  2. Ingemar J. Cox and Sunita L. Hingorani, An efficient implementation of Reid's multiple hypothesis tracking algorithm and its evaluation for the purpose of visual tracking, IEEE Transactions on Pattern Analysis and Machine Intelligence 18(2), 1996, 138 to 150, the whole paper (the cost matrix of a hypothesis and the k best children by Murty's algorithm)
  3. Katta G. Murty, An algorithm for ranking all the assignments in order of increasing cost, Operations Research 16(3), 1968, 682 to 687, the whole paper (the partitioning of the solution space)
  4. Samuel S. Blackman, Multiple hypothesis tracking for multiple target tracking, IEEE Aerospace and Electronic Systems Magazine 19(1), 2004, 5 to 18, the whole paper (hypothesis-oriented and track-oriented MHT, scoring and pruning)
  5. Chanho Kim, Fuxin Li, Arridhana Ciptadi and James M. Rehg, Multiple hypothesis tracking revisited, IEEE International Conference on Computer Vision (ICCV), 2015, the whole paper (track-oriented MHT with appearance models on video benchmarks)

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