Algorithm Search⌘K

Algorithmadvanced

Joint probabilistic data association

Also called JPDA, JPDA filter.

Update each track with a weighted mix of all gated measurements, the weights being posterior probabilities summed over all joint feasible assignments.

Time
O(E n + n m p² + n (p³ + d³)) worst · average · best
Space
O(n m + n d²) extra
Where
E = the number of joint events; d = the dimension of a state; m = the number of measurements; n = the number of tracks; p = the dimension of a measurement
Properties
deterministicnot exactnot iterativenot localonline
Origin
Thomas E. Fortmann, Yaakov Bar Shalom, Molly Scheffe, 1983

Joint probabilistic data association, or JPDA, updates a fixed set of tracks when several measurements fall into the gates of several tracks and some of the measurements are clutter. It does not pick one assignment. It lists every joint event, an assignment in which each track takes at most one measurement in its gate and each measurement goes to at most one track, and it computes the probability of each event under a Gaussian measurement model and a Poisson clutter model. The probability βij\beta_{ij} that measurement jj comes from track ii is the sum of the probabilities of the events that contain the pair. Each track is then updated with all its gated measurements at once, each weighted by βij\beta_{ij}, as in the probabilistic data association (PDA) filter for one target. Fortmann, Bar-Shalom and Scheffe published it in 1983. JPDA assumes that the number of targets is known. It does not start or delete tracks, which is the work of the track management around it.

In plain words

Two dogs run close together in a park, and a camera sees three dark spots. One spot is surely the first dog, one is surely the second dog, and the middle spot could be either dog or a bush. Instead of betting on one story, JPDA writes down every story that makes sense: the middle spot is the first dog, or the second dog, or a bush, or one of the dogs was not seen at all. It scores each story by how well the spots fit where the dogs should be. Then each dog moves its estimate toward every spot it could own, more strongly toward the spots that the likely stories give it. If the stories disagree, the dog also becomes less sure of its position.

The problem

The input of one frame is nn tracks, each with a predicted state x^i\hat x_i, a covariance P^i\hat P_i, a predicted measurement z^i\hat z_i and an innovation covariance SiS_i from a Kalman filter, and mm measurements z1,…,zmz_1, \ldots, z_m. The model is:

  • each target is detected with probability pDp_D, and a detection falls in its gate with probability pGp_G;
  • a detection of target ii is Gaussian with mean z^i\hat z_i and covariance SiS_i, so its likelihood is Lij=N(zj;z^i,Si)L_{ij} = \mathcal N(z_j; \hat z_i, S_i);
  • the clutter is a Poisson point process with constant density λ\lambda per unit of measurement space, so the number of false measurements has a Poisson distribution and each is uniform;
  • each measurement comes from at most one target, and each target gives at most one measurement.

A joint event θ\theta is a set of pairs (i,j)(i, j) with jj in the gate of ii, with no track and no measurement used twice. The output is the updated state and covariance of each track.

The algorithm

  1. JPDA-STEP(the tracks, the measurements z_1..z_m, p_D, p_G, λ, the gate γ)
  2. 1for each track i: predict x̂_i, P̂_i, then ẑ_i, S_i and the gain K_i
  3. 2for each pair (i, j) with d²_ij ≤ γ: L_ij ← N(z_j; ẑ_i, S_i)
  4. 3for each joint event θ (each track at most one gated measurement, each measurement at most one track) do
  5. 4w(θ) ← Π_{(i,j) ∈ θ} p_D L_ij / λ × Π_{i not in θ} (1 - p_D p_G)
  6. 5c ← Σ_θ w(θ); β_ij ← Σ_{θ ∋ (i,j)} w(θ) / c; β_i0 ← 1 - Σ_j β_ij
  7. 6for each track i: ν_ij ← z_j - ẑ_i; ν_i ← Σ_j β_ij ν_ij; x_i ← x̂_i + K_i ν_i
  8. 7P_i ← β_i0 P̂_i + (1 - β_i0)(P̂_i - K_i S_i K_iᵀ) + K_i (Σ_j β_ij ν_ij ν_ijᵀ - ν_i ν_iᵀ) K_iᵀ

The code enumerates the events of line L3 by depth-first search over the tracks: track ii is either missed, or takes one unused measurement in its gate. Line L7 has three parts. The first two are the covariance with no update and the covariance of a normal Kalman update, mixed by the probability that the track has a measurement. The third part is the spread of the innovations, which grows when the weights split between measurements that disagree.

Example

Three measurements, two tracks. Track A gates z1z_1 and z2z_2, track B gates z2z_2 and z3z_3. The likelihoods are LA1=LB3=0.10L_{A1} = L_{B3} = 0.10 and LA2=LB2=0.05L_{A2} = L_{B2} = 0.05, with pD=0.9p_D = 0.9, pG=1p_G = 1 and λ=0.01\lambda = 0.01. A pair contributes pDL/λp_D L / \lambda, which is 9 for a likelihood of 0.10 and 4.5 for 0.05, and a missed track contributes 1−pD=0.11 - p_D = 0.1. There are 8 joint events:

Event Weight
both missed 0.1⋅0.1=0.010.1 \cdot 0.1 = 0.01
A-z1z_1, B missed 9⋅0.1=0.99 \cdot 0.1 = 0.9
A-z2z_2, B missed 0.45
A missed, B-z2z_2 0.45
A missed, B-z3z_3 0.9
A-z1z_1, B-z2z_2 9⋅4.5=40.59 \cdot 4.5 = 40.5
A-z1z_1, B-z3z_3 9⋅9=819 \cdot 9 = 81
A-z2z_2, B-z3z_3 40.5

The sum is c=164.71c = 164.71. For track A, βA1=(0.9+40.5+81)/164.71=0.743\beta_{A1} = (0.9 + 40.5 + 81) / 164.71 = 0.743, βA2=(0.45+40.5)/164.71=0.249\beta_{A2} = (0.45 + 40.5) / 164.71 = 0.249 and βA0=1.36/164.71=0.008\beta_{A0} = 1.36 / 164.71 = 0.008. By symmetry B has the same numbers with z3z_3 in place of z1z_1. The single best event, A-z1z_1 and B-z3z_3, has probability only 81/164.71=0.4981 / 164.71 = 0.49. GNN would commit to it. JPDA lets the shared measurement z2z_2 pull both tracks a little.

Two crossing targets. In the code, two targets move with velocity (1,±0.3)(1, \pm 0.3) and cross at frame 10. Each is detected with probability 0.9 and noise of standard deviation 0.5, and about one clutter point per frame falls in a 10×1010 \times 10 window around them. Over 25 frames the largest position error of the two tracks is 1.03 and the mean is 0.38. With the paths parallel and 2 units apart for 40 frames, the gap between the two estimates wanders between about 1 and 2.5, and in one of six runs it falls to 0.36 by the last frame. This is the coalescence described under Pitfalls.

Correctness

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

  • Theorem: the event probabilities. Under the model of the page, the posterior probability of a joint event given the measurements is w(θ)/cw(\theta) / c.
  • Theorem: the update. The marginal posterior of a track is a mixture of one Kalman update per gated measurement and the prediction, with the weights βij\beta_{ij} and βi0\beta_{i0}. Lines L6 and L7 give the exact mean and covariance of this mixture.
  • Theorem: one track is PDA. For n=1n = 1, βj=Lj/(b+∑kLk)\beta_j = L_j / (b + \sum_k L_k) with b=λ(1−pDpG)/pDb = \lambda (1 - p_D p_G) / p_D, the weights of the PDA filter.
  • Theorem: the normalizer is a permanent. With pD=pG=1p_D = p_G = 1 and n=mn = m, c=per⁡(L)/λnc = \operatorname{per}(L) / \lambda^n. So computing cc exactly is #P-hard, and no polynomial algorithm is known for it.
  • Theorem: the number of events. If every measurement is in every gate, there are ∑k=0min⁡(n,m)(nk)(mk)k!\sum_{k=0}^{\min(n,m)} \binom{n}{k} \binom{m}{k} k! joint events.

The approximation is that each track is kept as one Gaussian after the update, and that the tracks are treated as independent in the next frame. Neither is exact, and the tracking quality over many frames is not proved.

Proof: Why the JPDA event weights are posterior probabilities, why the update has the mean and covariance of the track mixture, and why the normalizer is a permanentfull

Notation as on the page. There are nn tracks and mm measurements in a region of volume VV. A joint event θ\theta is a set of pairs (i,j)(i, j), each with jj in the gate of ii, in which no track and no measurement appears twice. Its weight is

w(θ)=∏(i,j)∈θpDLijλ∏i∉θ(1−pDpG),w(\theta) = \prod_{(i, j) \in \theta} \frac{p_D L_{ij}}{\lambda} \prod_{i \notin \theta} (1 - p_D p_G),

and c=∑θw(θ)c = \sum_\theta w(\theta).

Claim 1: the posterior probability of a joint event

Assume the model of the page. Each target is detected inside its gate with probability pDpGp_D p_G, independently of the others. A detection of target ii inside the gate has the density Lij/pGL_{ij} / p_G there, the Gaussian density truncated to the gate. The number ϕ\phi of clutter points is Poisson with mean λV\lambda V, and each is uniform on the region. The mm measurements are listed in a uniformly random order. Then Pr⁡(θ∣z1,…,zm)=w(θ)/c\Pr(\theta \mid z_1, \ldots, z_m) = w(\theta) / c.

Proof. Fix θ\theta with kk pairs, so ϕ=m−k\phi = m - k measurements are clutter. The joint density of the measurements and the event is a product of four factors.

  • The detection pattern: the tracks in θ\theta are detected in their gates, the others are not, with probability ∏i∈θpDpG∏i∉θ(1−pDpG)\prod_{i \in \theta} p_D p_G \prod_{i \notin \theta} (1 - p_D p_G).
  • The positions: the detections have the density ∏(i,j)∈θLij/pG\prod_{(i,j) \in \theta} L_{ij} / p_G, and the clutter the density V−ϕV^{-\phi}.
  • The clutter count: e−λV(λV)ϕ/ϕ!e^{-\lambda V} (\lambda V)^\phi / \phi!.
  • The order: the probability that the kk detections land in the given kk positions of the list of mm is ϕ!/m!\phi! / m!.

The product is

∏(i,j)∈θpDLij∏i∉θ(1−pDpG)⋅e−λVλϕm!=e−λVλmm! w(θ),\prod_{(i,j) \in \theta} p_D L_{ij} \prod_{i \notin \theta} (1 - p_D p_G) \cdot e^{-\lambda V} \frac{\lambda^\phi}{m!} = \frac{e^{-\lambda V} \lambda^m}{m!} \, w(\theta),

because λϕ=λmλ−k\lambda^\phi = \lambda^m \lambda^{-k} and each of the kk pairs takes one factor λ−1\lambda^{-1}. The factor in front does not depend on θ\theta. By Bayes' theorem, the posterior of θ\theta is w(θ)w(\theta) divided by the sum over all events, which is w(θ)/cw(\theta) / c. An assignment with a pair outside a gate has density 0 under the truncated model, so the sum runs exactly over the joint events. □\square

It follows that βij=∑θ∋(i,j)w(θ)/c\beta_{ij} = \sum_{\theta \ni (i,j)} w(\theta) / c is the posterior probability that measurement jj comes from track ii, and βi0=1−∑jβij\beta_{i0} = 1 - \sum_j \beta_{ij} is the probability that track ii has no measurement, since the events in which ii has a measurement are disjoint by measurement.

Claim 2: the mean and covariance of the update

Assume the prior of each track is Gaussian with mean x^i\hat x_i and covariance P^i\hat P_i, independent of the other tracks. Given an event with the pair (i,j)(i, j), the posterior of track ii is the Kalman update with mean xij=x^i+Kiνijx_{ij} = \hat x_i + K_i \nu_{ij} and covariance Pic=P^i−KiSiKiTP^c_i = \hat P_i - K_i S_i K_i^{\mathsf T}. Given an event where ii is missed, take the posterior to be the prediction (x^i,P^i)(\hat x_i, \hat P_i). Then the marginal posterior of track ii is the mixture βi0N(x^i,P^i)+∑jβijN(xij,Pic)\beta_{i0} \mathcal N(\hat x_i, \hat P_i) + \sum_j \beta_{ij} \mathcal N(x_{ij}, P^c_i), and its mean and covariance are lines L6 and L7.

Proof. The marginal is the sum over events of the posterior probability of the event times the posterior of track ii given the event. The posterior of track ii depends only on what the event gives to ii, so grouping the events by that gives the mixture. Write βj\beta_j for βij\beta_{ij}, β0\beta_0 for βi0\beta_{i0}, KK for KiK_i, and ν=∑jβjνij\nu = \sum_j \beta_j \nu_{ij}. The mean is β0x^+∑jβj(x^+Kνij)=x^+Kν\beta_0 \hat x + \sum_j \beta_j (\hat x + K \nu_{ij}) = \hat x + K \nu, which is line L6. The covariance of a mixture is the mean of the component covariances plus the spread of the component means:

P=β0P^+(1−β0)Pc+β0(x^−x)(x^−x)T+∑jβj(xij−x)(xij−x)T.P = \beta_0 \hat P + (1 - \beta_0) P^c + \beta_0 (\hat x - x)(\hat x - x)^{\mathsf T} + \sum_j \beta_j (x_{ij} - x)(x_{ij} - x)^{\mathsf T}.

Here x^−x=−Kν\hat x - x = -K \nu and xij−x=K(νij−ν)x_{ij} - x = K (\nu_{ij} - \nu). With ∑jβj=1−β0\sum_j \beta_j = 1 - \beta_0,

∑jβj(νij−ν)(νij−ν)T+β0ννT=∑jβjνijνijT−2ννT+(1−β0)ννT+β0ννT=∑jβjνijνijT−ννT.\sum_j \beta_j (\nu_{ij} - \nu)(\nu_{ij} - \nu)^{\mathsf T} + \beta_0 \nu \nu^{\mathsf T} = \sum_j \beta_j \nu_{ij} \nu_{ij}^{\mathsf T} - 2 \nu \nu^{\mathsf T} + (1 - \beta_0) \nu \nu^{\mathsf T} + \beta_0 \nu \nu^{\mathsf T} = \sum_j \beta_j \nu_{ij} \nu_{ij}^{\mathsf T} - \nu \nu^{\mathsf T}.

Multiplying by KK on the left and KTK^{\mathsf T} on the right gives line L7. □\square

Two approximations remain and are not claimed exact. With pG<1p_G < 1, a missed track has a posterior that is the prediction with the gate cut out, not the prediction itself. And the next frame treats the tracks as independent Gaussians, while the true joint posterior couples them.

Claim 3: one track gives the PDA weights

For n=1n = 1 the events are "missed", of weight 1−pDpG1 - p_D p_G, and "measurement jj", of weight pDLj/λp_D L_j / \lambda. Multiplying the numerator and the denominator by λ/pD\lambda / p_D gives βj=Lj/(b+∑kLk)\beta_j = L_j / (b + \sum_k L_k) and β0=b/(b+∑kLk)\beta_0 = b / (b + \sum_k L_k) with b=λ(1−pDpG)/pDb = \lambda (1 - p_D p_G) / p_D. These are the weights of the PDA filter of Bar-Shalom and Tse. □\square

Claim 4: the normalizer is a permanent, and computing it is #P-hard

Let pD=pG=1p_D = p_G = 1 and n=mn = m, and put Lij=0L_{ij} = 0 for pairs outside the gates. Then c=per⁡(L)/λnc = \operatorname{per}(L) / \lambda^n.

Proof. A missed track gives the factor 1−pDpG=01 - p_D p_G = 0, so only events in which every track has a measurement have positive weight. With n=mn = m these are the permutations σ\sigma, with weight ∏iLiσ(i)/λn\prod_i L_{i \sigma(i)} / \lambda^n, which is 0 if some pair is outside a gate. The sum over all permutations is the permanent divided by λn\lambda^n. □\square

Valiant (1979) proved that the permanent of a 0-1 matrix is #P-complete to compute. Given a 0-1 matrix AA, take the table with the gate holding exactly the pairs with aij=1a_{ij} = 1, Lij=1L_{ij} = 1 there and λ=1\lambda = 1. Then c=per⁡(A)c = \operatorname{per}(A). So computing cc exactly from a table of likelihoods and gates is #P-hard. This does not rule out good approximations: for nonnegative matrices the permanent has a randomized approximation scheme, and practical trackers use cheaper approximations.

Claim 5: the number of joint events

If every measurement is in every gate, the number of joint events is ∑k=0min⁡(n,m)(nk)(mk)k!\sum_{k=0}^{\min(n,m)} \binom{n}{k} \binom{m}{k} k!.

Proof. An event with kk pairs is fixed by the set of kk detected tracks, the set of kk used measurements and a bijection between them. These choices are independent, and different choices give different events. □\square

The depth-first search of the code visits each event once: at track ii it branches on "missed" and on each unused gated measurement, and a leaf at depth nn is exactly one event.

Complexity

The likelihoods cost O(nmp2)O(n m p^2) after one inverse of SiS_i per track, and the predictions and updates O(n(p3+d3))O(n (p^3 + d^3)). The enumeration visits each of the EE joint events once and adds its weight to at most nn sums, so it costs O(En)O(E n). In the worst case, every measurement in every gate, EE is the count above. For n=m=3n = m = 3 this is 1+9+18+6=341 + 9 + 18 + 6 = 34, for n=m=6n = m = 6 it is 13,327, and for n=m=10n = m = 10 it is 234,662,231, so the time is exponential in the number of tracks in a cluster. Gating keeps clusters small in practice: tracks with no shared measurement are split into independent clusters, and each cluster is enumerated alone. The space is O(nm)O(n m) for the likelihoods and the sums, plus the covariances, and the depth-first search needs only O(n+m)O(n + m) more.

Properties

  • Soft decisions. A track never takes a wrong measurement outright. A doubtful measurement gets a small weight.
  • Fixed number of targets. JPDA itself does not create or delete tracks.
  • Exact marginals, approximate filter. The βij\beta_{ij} are exact under the model. The Gaussian kept after the update is an approximation of a mixture.
  • Exponential cost in the cluster size. Close targets with shared measurements make the enumeration large.
  • Honest covariance. The spread term makes the track less certain when the association is in doubt.

Variants and improvements

  • PDA. The case of one track, by Bar-Shalom and Tse (1975), with the closed form of the weights above.
  • Nonparametric JPDA. If the clutter density is not known, replace λ\lambda by the number of measurements in the gates divided by the gate volume.
  • Cheap JPDA and other approximations. Approximate the βij\beta_{ij} from the likelihoods directly, without enumeration, at a loss of accuracy.
  • k-best JPDA. Sum only over the kk events of highest weight, found with Murty's method, as in MHT.
  • Belief propagation. Williams and Lau (2014) approximate the marginals by loopy belief propagation on a graph of tracks and measurements, at a cost per iteration proportional to the number of gated pairs.
  • Coalescence avoidance. JPDA* of Blom and Bloem (2000) prunes the events so that close tracks do not merge.
  • JIPDA. Joint integrated PDA adds a probability that each target exists, so the filter can confirm and end tracks.
  • Random finite sets. The PHD filter avoids the events altogether by tracking the density of targets.

When to use it

Use JPDA when the number of targets is known or managed by other logic, the targets come close to each other for some frames, and the clutter is moderate. It is a standard method in radar and sonar tracking, and it is used in vision for people and cells when detections can be missed or false. If the targets are well apart, GNN gives almost the same result at a lower cost. If the targets stay close for a long time and identity matters, MHT can defer the decision, while JPDA tends to merge the tracks.

Pitfalls

  • Coalescence. When two targets move close and parallel for many frames, the shared measurements pull both tracks toward the middle, and the tracks can merge onto one target.
  • Exponential enumeration. A large cluster makes the number of events explode. Split clusters by gating, and fall back to an approximation when a cluster is too large.
  • Underflow. Products of many small densities can underflow. Scale the likelihoods, or work with logarithms and subtract the largest before taking exponentials.
  • A wrong clutter density. If λ\lambda is too small, clutter gets a high weight. If it is too large, the tracks ignore their true measurements.
  • Measurements outside every gate. They have no effect on JPDA, so new targets need a separate initiation rule.
  • A non-symmetric covariance. Rounding in line L7 can break the symmetry of PiP_i. Symmetrize it after the update.

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.

joint_probabilistic_data_association.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-probabilistic-data-association/. The authors are listed in prov/GVT723.jsonl.
"""Joint probabilistic data association (JPDA), the parametric form.

A known set of n tracks is updated with the m measurements of one frame. A
joint event gives each track at most one measurement inside its gate and each
measurement at most one track; the other measurements are clutter. The weight
of an event is the product of pD L_ij / lam over its pairs and of (1 - pD pG)
over its missed tracks, where L_ij is the Gaussian density of the innovation,
lam the clutter density, pD the detection probability and pG the gate
probability. The marginal probability beta_ij that measurement j belongs to
track i is the normalized sum of the weights of the events that hold the pair.
Each track is then updated with the PDA formulas. The events are enumerated, so
the cost grows exponentially with the size of a cluster of close tracks.
Matrices are lists of rows.
"""

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 mat_scale(a, f):
    return [[f * x for x in r] for r in a]


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 gaussian_density(nu, s):
    """Density of N(0, s) at the vector nu, and the squared Mahalanobis distance."""
    s_inv, det = inverse_and_det(s)
    col = [[x] for x in nu]
    d2 = mat_mul(mat_mul(transpose(col), s_inv), col)[0][0]
    return math.exp(-0.5 * d2) / math.sqrt((2 * math.pi) ** len(nu) * det), d2


def jpda_betas(lik, p_d, p_g, lam):
    """Association probabilities of JPDA by enumeration of the joint events (lines L3 to L5).

    lik[i][j] is the likelihood L_ij of measurement j for track i, or None
    outside the gate. Returns (beta, beta0, c, events): beta[i][j] is the
    probability that measurement j is from track i, beta0[i] the probability
    that track i has no measurement, c the sum of the event weights, and
    events the number of joint events.
    """
    n = len(lik)
    m = len(lik[0]) if n else 0
    miss = 1.0 - p_d * p_g
    acc = [[0.0] * m for _ in range(n)]
    total = [0.0]
    count = [0]
    chosen = [-1] * n
    used = [False] * m

    def visit(i, w):
        if i == n:
            total[0] += w
            count[0] += 1
            for t in range(n):
                if chosen[t] >= 0:
                    acc[t][chosen[t]] += w
            return
        chosen[i] = -1
        visit(i + 1, w * miss)  # track i is missed
        for j in range(m):  # @line L3
            if lik[i][j] is not None and not used[j]:
                used[j], chosen[i] = True, j
                visit(i + 1, w * p_d * lik[i][j] / lam)  # @line L4
                used[j], chosen[i] = False, -1

    visit(0, 1.0)
    c = total[0]  # @line L5
    beta = [[a / c for a in row] for row in acc]
    beta0 = [1.0 - sum(row) for row in beta]
    return beta, beta0, c, count[0]


def pda_update(x_pred, p_pred, z_hat, s, k, zs, beta_row, beta0):
    """PDA state and covariance update of one track (lines L6 and L7)."""
    nus = [[[z[a] - z_hat[a]] for a in range(len(z))] for z in zs]
    nu = [[0.0] for _ in z_hat]
    for b, v in zip(beta_row, nus):
        nu = mat_add(nu, mat_scale(v, b))
    x = mat_add(x_pred, mat_mul(k, nu))  # @line L6
    spread = mat_scale(mat_mul(nu, transpose(nu)), -1.0)
    for b, v in zip(beta_row, nus):
        spread = mat_add(spread, mat_scale(mat_mul(v, transpose(v)), b))
    kskt = mat_mul(mat_mul(k, s), transpose(k))
    p_c = mat_sub(p_pred, kskt)
    p = mat_add(mat_add(mat_scale(p_pred, beta0), mat_scale(p_c, 1.0 - beta0)), mat_mul(mat_mul(k, spread), transpose(k)))  # @line L7
    return x, p


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


def jpda_step(tracks, zs, model, p_d, p_g, lam, gamma):
    """One frame of JPDA for a fixed set of tracks, each a pair (x, P). Returns the new tracks."""
    f, q, h, r = model
    pred = []
    for x, p in tracks:  # @line L1
        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, _ = inverse_and_det(s)
        z_hat = [row[0] for row in mat_mul(h, xp)]
        pred.append((xp, pp, z_hat, s, mat_mul(ph, s_inv)))
    lik = []
    for xp, pp, z_hat, s, k in pred:  # @line L2
        row = []
        for z in zs:
            dens, d2 = gaussian_density([a - b for a, b in zip(z, z_hat)], s)
            row.append(dens if d2 <= gamma else None)
        lik.append(row)
    beta, beta0, _, _ = jpda_betas(lik, p_d, p_g, lam)
    out = []
    for i, (xp, pp, z_hat, s, k) in enumerate(pred):
        out.append(pda_update(xp, pp, z_hat, s, k, zs, beta[i], beta0[i]))
    return out
test_joint_probabilistic_data_association.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/joint-probabilistic-data-association/. The authors are listed in prov/GVT723.jsonl.

import itertools
import math
import random

from joint_probabilistic_data_association import (
    cv_model,
    gaussian_density,
    inverse_and_det,
    jpda_betas,
    jpda_step,
    mat_add,
    mat_mul,
    mat_sub,
    pda_update,
    transpose,
)


def random_lik(rng, n, m, p_gate):
    return [[rng.uniform(0.01, 1.0) if rng.random() < p_gate else None for _ in range(m)] for _ in range(n)]


def brute_betas(lik, p_d, p_g, lam):
    """Measurement-oriented enumeration: each measurement picks clutter (-1) or a track, tracks used at most once."""
    n, m = len(lik), len(lik[0])
    acc = [[0.0] * m for _ in range(n)]
    c = 0.0
    events = 0
    for owner in itertools.product(range(-1, n), repeat=m):
        taken = [t for t in owner if t >= 0]
        if len(taken) != len(set(taken)):
            continue
        if any(t >= 0 and lik[t][j] is None for j, t in enumerate(owner)):
            continue
        w = 1.0
        for j, t in enumerate(owner):
            if t >= 0:
                w *= p_d * lik[t][j] / lam
        w *= (1.0 - p_d * p_g) ** (n - len(taken))
        c += w
        events += 1
        for j, t in enumerate(owner):
            if t >= 0:
                acc[t][j] += w
    return [[a / c for a in row] for row in acc], c, events


def test_enumeration_matches_brute_force():
    rng = random.Random(11)
    for _ in range(200):
        n, m = rng.randint(1, 3), rng.randint(1, 4)
        lik = random_lik(rng, n, m, 0.7)
        p_d, p_g, lam = rng.uniform(0.5, 0.99), rng.choice([1.0, 0.99]), rng.uniform(0.01, 0.5)
        beta, beta0, c, events = jpda_betas(lik, p_d, p_g, lam)
        b2, c2, e2 = brute_betas(lik, p_d, p_g, lam)
        assert events == e2
        assert abs(c - c2) <= 1e-9 * c2
        for i in range(n):
            for j in range(m):
                assert abs(beta[i][j] - b2[i][j]) < 1e-12
            assert beta0[i] >= -1e-12
            assert abs(beta0[i] + sum(beta[i]) - 1.0) < 1e-12
        # a measurement is used by at most one track in total probability
        for j in range(m):
            assert sum(beta[i][j] for i in range(n)) <= 1.0 + 1e-12


def test_single_track_is_pda():
    rng = random.Random(5)
    for _ in range(100):
        m = rng.randint(1, 6)
        lik = [[rng.uniform(0.01, 1.0) for _ in range(m)]]
        p_d, p_g, lam = rng.uniform(0.5, 0.99), 0.99, rng.uniform(0.01, 0.5)
        beta, beta0, _, _ = jpda_betas(lik, p_d, p_g, lam)
        b = lam * (1.0 - p_d * p_g) / p_d
        den = b + sum(lik[0])
        for j in range(m):
            assert abs(beta[0][j] - lik[0][j] / den) < 1e-12
        assert abs(beta0[0] - b / den) < 1e-12


def permanent(a):
    n = len(a)
    return sum(math.prod(a[i][s[i]] for i in range(n)) for s in itertools.permutations(range(n)))


def test_normalizer_is_a_permanent():
    rng = random.Random(8)
    for n in range(1, 6):
        lik = [[rng.uniform(0.1, 1.0) for _ in range(n)] for _ in range(n)]
        lam = 0.3
        _, _, c, _ = jpda_betas(lik, 1.0, 1.0, lam)
        assert abs(c - permanent(lik) / lam ** n) <= 1e-9 * c


def test_number_of_events():
    for n in range(0, 4):
        for m in range(0, 5):
            lik = [[1.0] * m for _ in range(n)]
            if n == 0:
                continue
            if m == 0:
                lik = [[] for _ in range(n)]
            events = jpda_betas(lik, 0.9, 1.0, 1.0)[3]
            formula = sum(math.comb(n, k) * math.comb(m, k) * math.factorial(k) for k in range(min(n, m) + 1))
            assert events == formula
    # the page example: 3 tracks and 3 measurements all in every gate give 34 events
    assert jpda_betas([[1.0] * 3] * 3, 0.9, 1.0, 1.0)[3] == 34


def test_page_example():
    # two tracks share the middle measurement
    lik = [[0.10, 0.05, None], [None, 0.05, 0.10]]
    beta, beta0, c, events = jpda_betas(lik, 0.9, 1.0, 0.01)
    assert events == 8
    # pD L / lam is 9 for a likelihood 0.1 and 4.5 for 0.05, and a missed track gives 0.1
    w = {"0": 0.01, "a1": 0.9, "a2": 0.45, "b2": 0.45, "b3": 0.9, "a1b2": 40.5, "a1b3": 81.0, "a2b3": 40.5}
    total = sum(w.values())
    assert abs(total - 164.71) < 1e-9
    assert abs(c - total) < 1e-9
    assert abs(beta0[0] - 1.36 / 164.71) < 1e-12
    assert abs(beta[0][0] - (w["a1"] + w["a1b2"] + w["a1b3"]) / total) < 1e-12
    assert abs(beta[0][1] - (w["a2"] + w["a2b3"]) / total) < 1e-12
    assert abs(beta[1][1] - (w["b2"] + w["a1b2"]) / total) < 1e-12


def test_update_tends_to_kalman():
    f, q, h, r = cv_model(0.05, 0.25)
    x = [[1.0], [2.0], [0.5], [-0.3]]
    p = [[1.0, 0, 0, 0], [0, 1.0, 0, 0], [0, 0, 0.5, 0], [0, 0, 0, 0.5]]
    z = (1.7, 1.6)
    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)
    k = mat_mul(ph, inverse_and_det(s)[0])
    xk = mat_add(xp, mat_mul(k, [[z[0] - xp[0][0]], [z[1] - xp[1][0]]]))
    pk = mat_sub(pp, mat_mul(mat_mul(k, s), transpose(k)))
    (xj, pj), = jpda_step([(x, p)], [z], (f, q, h, r), 0.999999, 1.0, 1e-9, 9.21)
    assert max(abs(a[0] - b[0]) for a, b in zip(xj, xk)) < 1e-6
    assert max(abs(a - b) for ra, rb in zip(pj, pk) for a, b in zip(ra, rb)) < 1e-6


def test_no_measurement_keeps_prediction():
    f, q, h, r = cv_model(0.05, 0.25)
    x = [[0.0], [0.0], [1.0], [1.0]]
    p = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
    (xj, pj), = jpda_step([(x, p)], [], (f, q, h, r), 0.9, 1.0, 0.01, 9.21)
    pp = mat_add(mat_mul(mat_mul(f, p), transpose(f)), q)
    assert [a[0] for a in xj] == [1.0, 1.0, 1.0, 1.0]
    assert max(abs(a - b) for ra, rb in zip(pj, pp) for a, b in zip(ra, rb)) < 1e-12


def test_covariance_stays_symmetric_positive():
    rng = random.Random(3)
    f, q, h, r = cv_model(0.05, 0.25)
    for _ in range(50):
        x = [[rng.uniform(-1, 1)] for _ in range(4)]
        p = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
        zs = [(rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(rng.randint(1, 4))]
        (xj, pj), = jpda_step([(x, p)], zs, (f, q, h, r), 0.9, 1.0, 0.05, 9.21)
        assert all(abs(pj[i][j] - pj[j][i]) < 1e-12 for i in range(4) for j in range(4))
        assert inverse_and_det(pj)[1] > 0
        assert all(pj[i][i] > 0 for i in range(4))


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


def test_two_close_targets_in_clutter():
    rng = random.Random(1983)
    model = cv_model(0.01, 0.25)
    # the two paths cross at frame 10
    starts = [(0.0, 0.0, 1.0, 0.3), (0.0, 6.0, 1.0, -0.3)]
    tracks = []
    for x0, y0, vx, vy in starts:
        p = [[0.25, 0, 0, 0], [0, 0.25, 0, 0], [0, 0, 0.01, 0], [0, 0, 0, 0.01]]
        tracks.append(([[x0], [y0], [vx], [vy]], p))
    lam = 0.01  # clutter per unit area
    errs = []
    for t in range(1, 26):
        truth = [(x0 + vx * t, y0 + vy * t) for x0, y0, vx, vy in starts]
        zs = []
        for a, b in truth:
            if rng.random() < 0.9:
                zs.append((a + rng.gauss(0, 0.5), b + rng.gauss(0, 0.5)))
        cx, cy = truth[0][0], 3.0
        for _ in range(poisson(rng, lam * 100)):  # a 10 x 10 window around the targets
            zs.append((cx + rng.uniform(-5, 5), cy + rng.uniform(-5, 5)))
        rng.shuffle(zs)
        tracks = jpda_step(tracks, zs, model, 0.9, 0.99, lam, 9.21)
        for (x, _), (a, b) in zip(tracks, truth):
            errs.append(math.hypot(x[0][0] - a, x[1][0] - b))
    assert max(errs) < 2.0
    assert sum(errs) / len(errs) < 0.6


def test_gaussian_density():
    d, d2 = gaussian_density([1.0, 0.0], [[1.0, 0.0], [0.0, 1.0]])
    assert abs(d2 - 1.0) < 1e-12
    assert abs(d - math.exp(-0.5) / (2 * math.pi)) < 1e-12

History

Bar-Shalom and Tse introduced the probabilistic data association filter for one target in clutter in 1975. Fortmann, Bar-Shalom and Scheffe extended it to several targets in a conference paper in 1980 and in the IEEE Journal of Oceanic Engineering in 1983, with passive sonar as the application. The method became a standard part of the tracking books of Bar-Shalom and Fortmann (1988) and Blackman and Popoli (1999). The cost of the enumeration led to many approximations. Collins and Uhlmann (1992) studied efficient gating, which keeps the clusters small, and Williams and Lau (2014) noted that the exact marginals are closely related to the matrix permanent and are believed to be #P-complete, then gave a belief propagation method. In computer vision, JPDA was used for tracking people, cells and features in video.

References

  1. Thomas E. Fortmann, Yaakov Bar-Shalom and Molly Scheffe, Sonar tracking of multiple targets using joint probabilistic data association, IEEE Journal of Oceanic Engineering 8(3), 1983, 173 to 184, the whole paper (joint events, their probabilities and the state update)
  2. Yaakov Bar-Shalom and Edison Tse, Tracking in a cluttered environment with probabilistic data association, Automatica 11(5), 1975, 451 to 460, the whole paper (the PDA filter for one target)
  3. Yaakov Bar-Shalom and Thomas E. Fortmann, Tracking and Data Association, Academic Press, 1988, the chapters on the PDA and JPDA filters
  4. Jason L. Williams and Roslyn A. Lau, Approximate evaluation of marginal association probabilities with belief propagation, IEEE Transactions on Aerospace and Electronic Systems 50(4), 2014, 2942 to 2959, the introduction (the link of the marginal probabilities to the permanent) and the belief propagation method
  5. Joseph B. Collins and Jeffrey K. Uhlmann, Efficient gating in data association with multivariate Gaussian distributed states, IEEE Transactions on Aerospace and Electronic Systems 28(3), 1992, 909 to 916, the whole paper (gating with search trees, which keeps the clusters and the joint events few)

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