Algorithm Search⌘K

Algorithmresearch

Probability hypothesis density filter

Also called PHD filter, GM-PHD filter.

Propagate the first moment of the random finite set of targets, not each track. With linear Gaussian models, constant p_D and p_S and Gaussian mixture birth, the Gaussian mixture form is closed.

Time
O(J² (m + 1)² d² + J (m + 1) d³ + J p³) worst · averageO(J (m + 1) (d³ + log(J (m + 1))) + J p³) best
Space
O(J (m + 1) d²) extra
Where
J = the number of components after the prediction and the birth; d = the dimension of a state; m = the number of measurements; p = the dimension of a measurement with p ≤ d
Properties
deterministicnot exactnot iterativenot localonline
Origin
Ronald P. S. Mahler, 2003

The probability hypothesis density filter, or PHD filter, tracks an unknown and changing number of targets in clutter without assigning measurements to tracks. It treats the set of all targets as one random object, a random finite set, and it does not propagate the full distribution of that set, which is too large to handle. It propagates only its first moment, the PHD D(x)D(x), a density on the state space of one target. The integral of DD over a region is the expected number of targets in that region. Ronald Mahler derived the prediction and update equations of the PHD in 2003. In general they have no closed form. Vo and Ma showed in 2006 that if the motion and measurement models are linear and Gaussian, the probabilities of detection pDp_D and survival pSp_S are constant, and the birth intensity is a Gaussian mixture, then a PHD that is a Gaussian mixture stays a Gaussian mixture. This Gaussian mixture PHD filter, or GM-PHD, is the form on this page. It runs one Kalman filter update per component and measurement, and it keeps the number of components small by pruning and merging.

In plain words

Picture a map of a harbor covered with sand. Where boats are likely to be, the sand is piled high, and the total amount of sand is the number of boats you expect. Each time step, every pile slides along with the current and loses a little sand for boats that may leave. New small piles appear where boats usually enter. Then the radar gives a set of blips. Each pile keeps some of its sand in case its boat was not seen. For each blip, sand is copied to the spot near that blip, in proportion to how well each pile explains it. A blip that no pile explains well is taken as noise and adds little sand. Small piles are swept away, and piles that sit on top of each other are joined. Wherever about one boat's worth of sand is gathered, you report a boat.

The problem

The state of the scene at time kk is a finite set XkX_k of target states in Rd\mathbb R^d, and the measurements form a finite set ZkZ_k in Rp\mathbb R^p. The model is:

  • a target with state x′x' survives with probability pSp_S and moves to xx with density N(x;Fx′,Q)\mathcal N(x; F x', Q);
  • new targets appear as a Poisson point process with intensity γ(x)=∑bwb N(x;mb,Pb)\gamma(x) = \sum_b w_b \, \mathcal N(x; m_b, P_b);
  • a target with state xx is detected with probability pDp_D, and its measurement has density N(z;Hx,R)\mathcal N(z; H x, R);
  • the clutter is a Poisson point process with intensity κ(z)\kappa(z), independent of the targets.

The PHD of XkX_k given Z1,…,ZkZ_1, \ldots, Z_k is the density DkD_k with ∫ADk(x) dx=E ∣Xk∩A∣\int_A D_k(x) \, dx = E\,|X_k \cap A| for every region AA. The PHD filter computes DkD_k from Dk−1D_{k-1} and ZkZ_k by Mahler's equations, with spawning left out:

Dk∣k−1(x)=∫pS N(x;Fx′,Q) Dk−1(x′) dx′+γ(x),D_{k|k-1}(x) = \int p_S \, \mathcal N(x; F x', Q) \, D_{k-1}(x') \, dx' + \gamma(x),
Dk(x)=(1−pD)Dk∣k−1(x)+∑z∈ZkpD N(z;Hx,R) Dk∣k−1(x)κ(z)+∫pD N(z;Hy,R) Dk∣k−1(y) dy.D_k(x) = (1 - p_D) D_{k|k-1}(x) + \sum_{z \in Z_k} \frac{p_D \, \mathcal N(z; H x, R) \, D_{k|k-1}(x)}{\kappa(z) + \int p_D \, \mathcal N(z; H y, R) \, D_{k|k-1}(y) \, dy}.

The update is exact when the predicted set of targets is a Poisson point process. In general it is an approximation. The output in each frame is the expected number of targets N^k=∫Dk\hat N_k = \int D_k and a set of state estimates.

The algorithm

The PHD is kept as a mixture ∑kwk N(x;mk,Pk)\sum_k w_k \, \mathcal N(x; m_k, P_k).

  1. GM-PHD-STEP(the components (w_k, m_k, P_k), the measurements Z, F, Q, H, R, p_S, p_D, κ, the birth components)
  2. 1for each component: w_k ← p_S w_k; m_k ← F m_k; P_k ← F P_k Fᵀ + Q
  3. 2append the birth components (w_b, m_b, P_b)
  4. 3for each component k: η_k ← H m_k; S_k ← H P_k Hᵀ + R; K_k ← P_k Hᵀ S_k⁻¹; P⁺_k ← (I - K_k H) P_k
  5. 4the missed terms: keep each component with the weight (1 - p_D) w_k
  6. 5for each z in Z: q_k ← N(z; η_k, S_k); add (p_D w_k q_k / (κ(z) + Σ_l p_D w_l q_l), m_k + K_k (z - η_k), P⁺_k) for each k
  7. 6drop the components with w_k < T; merge each heaviest component with those within distance U; keep the J_max heaviest
  8. 7N̂ ← Σ_k w_k; report m_k round(w_k) times for each component with w_k > 0.5

Line L6 follows Vo and Ma. Take the component jj of largest weight, and collect the components ii with (mi−mj)TPi−1(mi−mj)≤U(m_i - m_j)^\mathsf{T} P_i^{-1} (m_i - m_j) \le U. Replace them by one component with the sum of their weights, their weighted mean, and the covariance that keeps the second moment. Repeat with the rest. The code uses T=10−5T = 10^{-5}, U=4U = 4 and Jmax⁡=100J_{\max} = 100.

Example

One update in one dimension. Two predicted components have weight 1, means 0 and 10, and variance 0.75, so with R=0.25R = 0.25 each has S=1S = 1 and K=0.75K = 0.75. Let pD=0.9p_D = 0.9 and κ=0.01\kappa = 0.01, and let the measurements be 0.50.5, 99 and 44.

Term Weight Mean
missed, component at 0 0.10.1 0
missed, component at 10 0.10.1 10
z=0.5z = 0.5 0.9⋅0.352/(0.01+0.317)=0.9690.9 \cdot 0.352 / (0.01 + 0.317) = 0.969 0.375
z=9z = 9 0.9⋅0.242/(0.01+0.218)=0.9560.9 \cdot 0.242 / (0.01 + 0.218) = 0.956 9.25
z=4z = 4 1.2⋅10−4/(0.01+1.2⋅10−4)=0.0121.2 \cdot 10^{-4} / (0.01 + 1.2 \cdot 10^{-4}) = 0.012 3.0

The other three terms, each measurement paired with the far component, have weights below 10−1510^{-15}. The total weight is N^=2.137\hat N = 2.137, the expected number of targets. The measurement at 4 fits neither component, and the clutter term κ\kappa takes almost all of its share, so it adds only 0.012 targets. After pruning and merging there are three components, with weights 1.069, 1.056 and 0.012 and means 0.34, 9.32 and 3.0, and the filter reports two targets, at 0.34 and 9.32.

A scene in the plane. In the test, three targets with constant velocity are born at frames 0, 0 and 8 near three birth components of weight 0.05, and one of them dies at frame 25. Each is detected with probability 0.95 and noise of standard deviation 0.5, and on average 5 clutter points per frame fall in a 60×6060 \times 60 window. Over 40 frames, leaving out the three frames after each birth or death, the filter reports the right number of targets, each within 1.5 of a true one, in 28 of 31 frames. Most of the errors come from a missed detection, after which the weight of the target falls to about 1−pD1 - p_D for one frame.

Correctness

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

  • Theorem: the mixture is closed. If Dk−1D_{k-1} is a Gaussian mixture, lines L1 and L2 give exactly the predicted PHD Dk∣k−1D_{k|k-1}, and lines L3 to L5 give exactly the updated PHD DkD_k of the equations above.
  • Theorem: the expected number. The weights after line L5 sum to (1−pD)N^k∣k−1+∑z∈Zρ(z)(1 - p_D) \hat N_{k|k-1} + \sum_{z \in Z} \rho(z), where N^k∣k−1=pSN^k−1+∑bwb\hat N_{k|k-1} = p_S \hat N_{k-1} + \sum_b w_b and ρ(z)=∑lpDwlql/(κ(z)+∑lpDwlql)\rho(z) = \sum_l p_D w_l q_l / (\kappa(z) + \sum_l p_D w_l q_l) lies in [0,1)[0, 1). So each measurement adds less than one expected target, and with no measurements the count is (1−pD)(pSN^k−1+∑bwb)(1 - p_D)(p_S \hat N_{k-1} + \sum_b w_b).
  • Theorem: merging keeps the moments. A merge in line L6 keeps the total weight, the weighted mean and the weighted second moment of the components it joins.

Pruning and merging change the density, so the filter as a whole is an approximation of the PHD recursion, and the PHD recursion is itself an approximation of the full multi-target Bayes filter. The quality of the state estimates is not proved.

Proof: Why the Gaussian mixture PHD recursion is exact under linear Gaussian models, constant detection and survival probabilities and Gaussian mixture birth, and what pruning and merging keepfull

Notation as on the page. N(x;m,P)\mathcal N(x; m, P) is the Gaussian density with mean mm and a symmetric positive definite covariance PP. The matrices QQ and RR are positive definite, and κ(z)>0\kappa(z) > 0 for every zz. The PHD recursion is Mahler's prediction and update, as written on the page. This file proves that lines L1 to L5 compute it exactly when the PHD of the previous frame is a Gaussian mixture, and states what lines L6 and L7 keep.

Two facts about Gaussians

Lemma A. ∫N(x;Fx′,Q) N(x′;m,P) dx′=N(x;Fm,FPFT+Q)\int \mathcal N(x; F x', Q) \, \mathcal N(x'; m, P) \, dx' = \mathcal N(x; F m, F P F^\mathsf{T} + Q).

Proof. Let x′x' have the density N(x′;m,P)\mathcal N(x'; m, P) and let x=Fx′+vx = F x' + v, with vv independent of x′x' and with density N(v;0,Q)\mathcal N(v; 0, Q). Given x′x', the density of xx is N(x;Fx′,Q)\mathcal N(x; F x', Q), so by the law of total probability the left side is the density of xx. A linear function of the independent Gaussian vectors x′x' and vv is Gaussian, with mean FmF m and covariance FPFT+QF P F^\mathsf{T} + Q. This covariance is positive definite because QQ is. □\square

Lemma B. Let η=Hm\eta = H m, S=HPHT+RS = H P H^\mathsf{T} + R, K=PHTS−1K = P H^\mathsf{T} S^{-1} and P+=(I−KH)PP^+ = (I - K H) P. Then

N(z;Hx,R) N(x;m,P)=N(z;η,S) N(x;m+K(z−η),P+).\mathcal N(z; H x, R) \, \mathcal N(x; m, P) = \mathcal N(z; \eta, S) \, \mathcal N(x; m + K (z - \eta), P^+).

Proof. Let xx have the density N(x;m,P)\mathcal N(x; m, P) and let z=Hx+wz = H x + w, with ww independent of xx and with density N(w;0,R)\mathcal N(w; 0, R). The left side is the joint density of (x,z)(x, z). The pair is jointly Gaussian with mean (m,η)(m, \eta) and covariance with the blocks PP, PHTP H^\mathsf{T}, HPH P and SS. The matrix SS is positive definite because RR is. A joint density is the marginal density of zz, which is N(z;η,S)\mathcal N(z; \eta, S), times the conditional density of xx given zz. For a jointly Gaussian pair this conditional density is Gaussian with mean m+PHTS−1(z−η)=m+K(z−η)m + P H^\mathsf{T} S^{-1} (z - \eta) = m + K (z - \eta) and covariance P−PHTS−1HP=(I−KH)PP - P H^\mathsf{T} S^{-1} H P = (I - K H) P, by the standard formula for Gaussian conditioning (the Schur complement). □\square

Lemma B is the measurement update of the Kalman filter, with the normalizing constant N(z;η,S)\mathcal N(z; \eta, S) kept.

Claim 1: the mixture is closed, and lines L1 to L5 are exact

Let Dk−1(x)=∑jwj N(x;mj,Pj)D_{k-1}(x) = \sum_j w_j \, \mathcal N(x; m_j, P_j). Then the predicted PHD is the mixture of lines L1 and L2, and the updated PHD is the mixture of lines L4 and L5.

Proof. The prediction is linear in Dk−1D_{k-1}, and pSp_S is a constant, so it can be taken out of the integral:

Dk∣k−1(x)=∑jpSwj∫N(x;Fx′,Q) N(x′;mj,Pj) dx′+γ(x)=∑jpSwj N(x;Fmj,FPjFT+Q)+∑bwb N(x;mb,Pb)D_{k|k-1}(x) = \sum_j p_S w_j \int \mathcal N(x; F x', Q) \, \mathcal N(x'; m_j, P_j) \, dx' + \gamma(x) = \sum_j p_S w_j \, \mathcal N(x; F m_j, F P_j F^\mathsf{T} + Q) + \sum_b w_b \, \mathcal N(x; m_b, P_b)

by Lemma A. This is line L1 for the surviving components and line L2 for the birth components, since the birth intensity is a Gaussian mixture.

Write the predicted PHD as ∑kwk N(x;mk,Pk)\sum_k w_k \, \mathcal N(x; m_k, P_k) and let ηk\eta_k, SkS_k, KkK_k and Pk+P^+_k be as in line L3, with qk=N(z;ηk,Sk)q_k = \mathcal N(z; \eta_k, S_k). The missed term of the update is (1−pD)Dk∣k−1(x)=∑k(1−pD)wk N(x;mk,Pk)(1 - p_D) D_{k|k-1}(x) = \sum_k (1 - p_D) w_k \, \mathcal N(x; m_k, P_k), which is line L4. For a measurement zz, because pDp_D is a constant, Lemma B gives

pD N(z;Hx,R) Dk∣k−1(x)=∑kpDwkqk N(x;mk+Kk(z−ηk),Pk+).p_D \, \mathcal N(z; H x, R) \, D_{k|k-1}(x) = \sum_k p_D w_k q_k \, \mathcal N(x; m_k + K_k (z - \eta_k), P^+_k).

Each Gaussian on the right integrates to 1, so the integral in the denominator of the update is ∑lpDwlql\sum_l p_D w_l q_l. Dividing by κ(z)+∑lpDwlql\kappa(z) + \sum_l p_D w_l q_l gives the components of line L5, one for each kk, with the weights pDwkqk/(κ(z)+∑lpDwlql)p_D w_k q_k / (\kappa(z) + \sum_l p_D w_l q_l). The update is the sum of the missed term and of these terms over all z∈Zz \in Z, which is the mixture that lines L4 and L5 build. □\square

Each hypothesis is used. If pDp_D depended on xx, the product pD(x) N(x;m,P)p_D(x) \, \mathcal N(x; m, P) would not be a Gaussian in general. If pSp_S depended on xx, the same would hold in the prediction. If the models were not linear Gaussian, Lemmas A and B would not apply. If the birth intensity were not a Gaussian mixture, line L2 would not add Gaussian components.

Claim 2: the expected number of targets

The weights after line L5 sum to (1−pD)N^k∣k−1+∑z∈Zρ(z)(1 - p_D) \hat N_{k|k-1} + \sum_{z \in Z} \rho(z), where N^k∣k−1=pSN^k−1+∑bwb\hat N_{k|k-1} = p_S \hat N_{k-1} + \sum_b w_b and ρ(z)=A(z)/(κ(z)+A(z))\rho(z) = A(z) / (\kappa(z) + A(z)) with A(z)=∑lpDwlqlA(z) = \sum_l p_D w_l q_l. Each ρ(z)\rho(z) lies in [0,1)[0, 1).

Proof. The integral of a mixture is the sum of its weights, since each Gaussian integrates to 1. By the property of the PHD on the page, this integral is the expected number of targets. The weights of line L1 sum to pSN^k−1p_S \hat N_{k-1}, and line L2 adds ∑bwb\sum_b w_b. Line L4 gives (1−pD)N^k∣k−1(1 - p_D) \hat N_{k|k-1}. For one zz, the weights of line L5 sum to ∑kpDwkqk/(κ(z)+A(z))=ρ(z)\sum_k p_D w_k q_k / (\kappa(z) + A(z)) = \rho(z). Since A(z)≥0A(z) \ge 0 and κ(z)>0\kappa(z) > 0, 0≤ρ(z)<10 \le \rho(z) < 1. With ZZ empty the sum is (1−pD)(pSN^k−1+∑bwb)(1 - p_D)(p_S \hat N_{k-1} + \sum_b w_b). □\square

Claim 3: what line L6 keeps

Let a merge join the components i∈Gi \in G into (w~,m~,P~)(\tilde w, \tilde m, \tilde P) with w~=∑i∈Gwi\tilde w = \sum_{i \in G} w_i, m~=∑i∈Gwimi/w~\tilde m = \sum_{i \in G} w_i m_i / \tilde w and P~=∑i∈Gwi(Pi+(m~−mi)(m~−mi)T)/w~\tilde P = \sum_{i \in G} w_i (P_i + (\tilde m - m_i)(\tilde m - m_i)^\mathsf{T}) / \tilde w. Then the merged component has the same integral, the same first moment and the same second moment as the part of the mixture it replaces, and P~\tilde P is positive definite. Pruning a set of components of total weight δ\delta changes the PHD by exactly δ\delta in the L1L^1 norm. The merge loop stops after at most as many rounds as there are components.

Proof. The part ∑i∈Gwi N(x;mi,Pi)\sum_{i \in G} w_i \, \mathcal N(x; m_i, P_i) has integral ∑wi=w~\sum w_i = \tilde w, first moment ∫x∑wiNi=∑wimi=w~m~\int x \sum w_i \mathcal N_i = \sum w_i m_i = \tilde w \tilde m, and second moment ∑wi(Pi+mimiT)\sum w_i (P_i + m_i m_i^\mathsf{T}). The merged component has the integral w~\tilde w, the first moment w~m~\tilde w \tilde m and the second moment w~(P~+m~m~T)\tilde w (\tilde P + \tilde m \tilde m^\mathsf{T}). Expanding,

w~P~=∑wiPi+w~m~m~T−m~(∑wimi)T−(∑wimi)m~T+∑wimimiT=∑wi(Pi+mimiT)−w~m~m~T,\tilde w \tilde P = \sum w_i P_i + \tilde w \tilde m \tilde m^\mathsf{T} - \tilde m \Big(\sum w_i m_i\Big)^\mathsf{T} - \Big(\sum w_i m_i\Big) \tilde m^\mathsf{T} + \sum w_i m_i m_i^\mathsf{T} = \sum w_i (P_i + m_i m_i^\mathsf{T}) - \tilde w \tilde m \tilde m^\mathsf{T},

since ∑wimi=w~m~\sum w_i m_i = \tilde w \tilde m. So the second moments agree. The matrix P~\tilde P is a positive combination of positive definite matrices and positive semidefinite matrices, so it is positive definite.

Every component is a nonnegative function, so removing components of total weight δ\delta removes a nonnegative function with integral δ\delta, and the L1L^1 distance is δ\delta. The same holds for the cap Jmax⁡J_{\max}, which removes the lightest components. In each round of merging, the heaviest component jj is at distance 0 from itself, so it is in the group and is removed, and the number of remaining components falls by at least one. □\square

Line L7 reads the expected number from the weights by Claim 2. The rule that reports a mean for each weight above 0.5 is a heuristic of Vo and Ma, not a consequence of the recursion. The PHD recursion is itself an approximation of the multi-target Bayes filter. So these claims prove that the mixture is the exact PHD before line L6, and they do not prove that the reported states are close to the true states.

Complexity

After the prediction there are JJ components. Line L3 costs O(J(d3+p3))O(J (d^3 + p^3)), and line L5 costs O(Jm(p2+dp))O(J m (p^2 + d p)) for the likelihoods and the new means, and makes J(m+1)J (m + 1) components. Merging needs the inverse of each covariance, O(J(m+1)d3)O(J (m + 1) d^3), and each round scans the remaining components at O(d2)O(d^2) each. In the worst case each round removes one component, so merging costs O(J2(m+1)2d2)O(J^2 (m + 1)^2 d^2). In the best case one round removes all, and the sort for the cap Jmax⁡J_{\max} costs O(J(m+1)log⁡(J(m+1)))O(J (m + 1) \log(J (m + 1))). The space is O(J(m+1)d2)O(J (m + 1) d^2) for the covariances. The cost is polynomial in the number of targets and measurements, and there is no enumeration of assignments. The cap Jmax⁡J_{\max} keeps JJ bounded from frame to frame.

Properties

  • No explicit association. Every measurement updates every component, and the weights do the work that assignments do in other trackers.
  • Varying number of targets. Births, deaths, misses and clutter are all in the model, so tracks start and end without extra logic.
  • No identities. The PHD is a density, not a set of labeled tracks. The estimates of two frames are not linked.
  • Closed form only under the stated model. Linear Gaussian models, constant pDp_D and pSp_S, and a Gaussian mixture birth intensity.
  • Polynomial cost. The work is about JmJ m Kalman updates per frame.
  • Noisy count. The expected number N^\hat N has a high variance when the number of targets is large, and a single miss drops the weight of a target to about 1−pD1 - p_D.

Variants and improvements

  • Particle PHD. Vo, Singh and Doucet (2005) represent the PHD by weighted particles, as in sequential Monte Carlo, for nonlinear and non-Gaussian models. The estimates then need clustering of the particles.
  • Nonlinear Gaussian models. Vo and Ma (2006) replace the Kalman update of each component by an extended or unscented Kalman update. The result is no longer exact.
  • Spawning. Targets that split off from other targets add a further linear Gaussian term to the prediction, and the mixture stays closed.
  • Cardinalized PHD. The CPHD filter of Mahler (2007) propagates the full distribution of the number of targets with the PHD. Its count is much more stable, at a cost cubic in the number of measurements.
  • Labeled filters. Filters built on labeled random finite sets give each target an identity, so the output is a set of tracks.
  • Track labels as a post step. A simple fix is to tag each component and pass the tag to the components it creates, then read the tags of the extracted estimates.

When to use it

Use the GM-PHD filter when many targets appear and disappear, the clutter is heavy, and an estimate of the number of targets and their positions in each frame is the main output. It was designed for radar and sonar, and in vision it is used for people, vehicles and cells seen by a detector. When the motion is nonlinear, use the extended or unscented form, or the particle form. If each target must keep one identity over the whole video, add labels or use a tracker that keeps identities, such as MHT. If the number of targets is known and small, JPDA or GNN is simpler.

Pitfalls

  • A model outside the closed form. A detection probability that depends on the state, or nonlinear models, break the exact recursion. The usual approximations work but are no longer exact.
  • A birth model that misses the entry points. The filter can only start a target where the birth intensity has weight. A birth weight that is too large makes clutter turn into targets.
  • Missed detections. One miss multiplies the weight of a target by 1−pD1 - p_D. With pD=0.95p_D = 0.95 the target falls below the threshold of 0.5 for that frame.
  • Close targets. Two targets closer than the merge distance UU become one component, of weight about 2. The extraction reports the same mean twice.
  • A wrong clutter intensity. If κ\kappa is too small, clutter adds targets. If it is too large, true measurements are discounted.
  • Pruning too hard. A large threshold TT removes the weak components that a target needs to recover after a miss.
  • Loss of symmetry. Rounding in Pk+P^+_k can make it non-symmetric. The code symmetrizes 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.

phd_filter.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phd-filter/. The authors are listed in prov/9HR0MT.jsonl.
"""The Gaussian mixture probability hypothesis density filter (Vo and Ma, 2006).

The PHD D(x) of a multi-target state is a density on the single-target state
space whose integral over a region is the expected number of targets in it.
With linear Gaussian motion and measurement models, constant survival and
detection probabilities pS and pD, and a Gaussian mixture birth intensity, a
Gaussian mixture PHD stays a Gaussian mixture after the prediction and the
update. A component is a triple (w, m, P) of a weight, a mean (a list) and a
covariance (a list of rows). The clutter intensity kappa(z) is a function of
the measurement. Pruning and merging keep the number of components bounded.
"""

import math


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_vec(a, v):
    return [sum(x * y for x, y in zip(r, v)) 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 quad(v, a_inv):
    """The quadratic form v^T A^-1 v."""
    return sum(v[i] * sum(a_inv[i][j] * v[j] for j in range(len(v))) for i in range(len(v)))


def gaussian(z, mean, cov):
    """The density N(z; mean, cov)."""
    inv, det = inverse_and_det(cov)
    nu = [a - b for a, b in zip(z, mean)]
    return math.exp(-0.5 * quad(nu, inv)) / math.sqrt((2 * math.pi) ** len(z) * det)


def predict(comps, f, q, p_s, birth):
    """Prediction of a Gaussian mixture PHD (lines L1 and L2)."""
    out = []
    ft = transpose(f)
    for w, m, p in comps:  # @line L1
        out.append((p_s * w, mat_vec(f, m), mat_add(mat_mul(mat_mul(f, p), ft), q)))
    out.extend(birth)  # @line L2
    return out


def update(comps, zs, h, r, p_d, kappa):
    """Update of a Gaussian mixture PHD with the measurements zs (lines L3 to L5)."""
    ht = transpose(h)
    d = len(comps[0][1]) if comps else 0
    parts = []
    for w, m, p in comps:  # @line L3
        ph = mat_mul(p, ht)
        s = mat_add(mat_mul(h, ph), r)
        s_inv, s_det = inverse_and_det(s)
        k = mat_mul(ph, s_inv)
        kh = mat_mul(k, h)
        p_upd = mat_add(p, [[-x for x in row] for row in mat_mul(kh, p)])
        p_upd = [[0.5 * (p_upd[i][j] + p_upd[j][i]) for j in range(d)] for i in range(d)]
        parts.append((mat_vec(h, m), s_inv, s_det, k, p_upd))
    out = [((1.0 - p_d) * w, m, p) for (w, m, p) in comps]  # @line L4
    for z in zs:  # @line L5
        terms = []
        for (w, m, p), (eta, s_inv, s_det, k, p_upd) in zip(comps, parts):
            nu = [a - b for a, b in zip(z, eta)]
            lik = math.exp(-0.5 * quad(nu, s_inv)) / math.sqrt((2 * math.pi) ** len(z) * s_det)
            terms.append((p_d * w * lik, [a + b for a, b in zip(m, mat_vec(k, nu))], p_upd))
        denom = kappa(z) + sum(t[0] for t in terms)
        out.extend((wz / denom, mz, pz) for wz, mz, pz in terms)
    return out


def prune_and_merge(comps, threshold=1e-5, merge_dist=4.0, max_comps=100):
    """Drop the components with a small weight, merge close ones, keep the largest (line L6)."""
    rest = [c for c in comps if c[0] > threshold]
    invs = [inverse_and_det(c[2])[0] for c in rest]
    alive = list(range(len(rest)))
    merged = []
    while alive:
        j = max(alive, key=lambda i: rest[i][0])
        mj = rest[j][1]
        group = [i for i in alive if quad([a - b for a, b in zip(rest[i][1], mj)], invs[i]) <= merge_dist]
        wt = sum(rest[i][0] for i in group)
        d = len(mj)
        mean = [sum(rest[i][0] * rest[i][1][a] for i in group) / wt for a in range(d)]
        cov = [[0.0] * d for _ in range(d)]
        for i in group:
            w, m, p = rest[i]
            dm = [a - b for a, b in zip(mean, m)]
            for a in range(d):
                for b in range(d):
                    cov[a][b] += w * (p[a][b] + dm[a] * dm[b])
        cov = [[x / wt for x in row] for row in cov]
        merged.append((wt, mean, cov))
        gs = set(group)
        alive = [i for i in alive if i not in gs]
    merged.sort(key=lambda c: -c[0])
    return merged[:max_comps]


def extract(comps):
    """The expected number of targets and the state estimates (line L7)."""
    n_hat = sum(c[0] for c in comps)  # @line L7
    states = []
    for w, m, _ in comps:
        if w > 0.5:
            states.extend([list(m)] * int(round(w)))
    return n_hat, states


def phd_step(comps, zs, model, p_s, p_d, kappa, birth, threshold=1e-5, merge_dist=4.0, max_comps=100):
    """One frame of the GM-PHD filter. Returns (components, expected number, state estimates)."""
    f, q, h, r = model
    comps = predict(comps, f, q, p_s, birth)
    comps = update(comps, zs, h, r, p_d, kappa)
    comps = prune_and_merge(comps, threshold, merge_dist, max_comps)  # @line L6
    n_hat, states = extract(comps)
    return comps, n_hat, states


def phd_density(comps, x):
    """The value of the Gaussian mixture PHD at the state x."""
    return sum(w * gaussian(x, m, p) for w, m, p in comps)


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
test_phd_filter.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phd-filter/. The authors are listed in prov/9HR0MT.jsonl.

import math
import random

from phd_filter import cv_model, extract, gaussian, phd_density, phd_step, predict, prune_and_merge, update


def normal_1d(x, m, v):
    return math.exp(-0.5 * (x - m) ** 2 / v) / math.sqrt(2 * math.pi * v)


def test_matches_a_grid_phd_recursion_in_1d():
    # 1D model: x' = x + noise(0.5), z = x + noise(0.3)
    f, q, h, r = [[1.0]], [[0.5]], [[1.0]], [[0.3]]
    p_s, p_d, kap = 0.95, 0.8, 0.05
    birth = [(0.1, [0.0], [[4.0]])]
    comps = [(1.0, [-3.0], [[1.0]]), (0.7, [4.0], [[0.5]])]
    step = 0.1
    grid = [-15.0 + step * i for i in range(301)]
    mix_1d = lambda cs, x: sum(w * normal_1d(x, m[0], p[0][0]) for w, m, p in cs)
    dens = [mix_1d(comps, x) for x in grid]
    assert abs(dens[150] - phd_density(comps, [0.0])) < 1e-15
    for zs in ([[-2.5], [4.3], [8.0]], [[-1.8], [5.0]]):
        # the PHD recursion on the grid, with sums in place of the integrals
        pred = []
        for x in grid:
            s = sum(normal_1d(x, y, 0.5) * dy for y, dy in zip(grid, dens)) * step
            pred.append(p_s * s + 0.1 * normal_1d(x, 0.0, 4.0))
        new = [(1.0 - p_d) * v for v in pred]
        for (z,) in zs:
            g = [p_d * normal_1d(z, x, 0.3) * v for x, v in zip(grid, pred)]
            denom = kap + sum(g) * step
            new = [a + b / denom for a, b in zip(new, g)]
        dens = new
        comps = update(predict(comps, f, q, p_s, birth), zs, h, r, p_d, lambda z: kap)
        gm = [mix_1d(comps, x) for x in grid]
        assert max(abs(a - b) for a, b in zip(gm, dens)) < 1e-6
        assert abs(sum(c[0] for c in comps) - sum(dens) * step) < 1e-6


def test_no_measurements():
    model = cv_model(0.1, 0.25)
    comps = [(0.9, [0.0, 0.0, 1.0, 0.0], [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)])]
    birth = [(0.2, [5.0, 5.0, 0.0, 0.0], [[2.0 if i == j else 0.0 for j in range(4)] for i in range(4)])]
    out = update(predict(comps, model[0], model[1], 0.98, birth), [], model[2], model[3], 0.9, lambda z: 0.01)
    assert abs(sum(c[0] for c in out) - (1 - 0.9) * (0.98 * 0.9 + 0.2)) < 1e-12
    assert out[0][1] == [1.0, 0.0, 1.0, 0.0]


def test_each_measurement_adds_at_most_one_target():
    rng = random.Random(2006)
    f, q, h, r = cv_model(0.1, 0.25)
    for _ in range(20):
        comps = [(rng.uniform(0.1, 1.5), [rng.uniform(-5, 5), rng.uniform(-5, 5), 0.0, 0.0],
                  [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]) for _ in range(4)]
        zs = [[rng.uniform(-6, 6), rng.uniform(-6, 6)] for _ in range(rng.randint(0, 5))]
        kap = rng.uniform(0.001, 0.1)
        out = update(comps, zs, h, r, 0.9, lambda z: kap)
        w = sum(c[0] for c in comps)
        # the weights of one measurement sum to its share p_D Σ w q / (κ + p_D Σ w q) < 1
        per_z = []
        for z in zs:
            s = sum(0.9 * c[0] * gaussian(z, c[1][:2], [[c[2][0][0] + 0.25, c[2][0][1]], [c[2][1][0], c[2][1][1] + 0.25]]) for c in comps)
            per_z.append(s / (kap + s))
        assert all(0.0 <= p < 1.0 for p in per_z)
        assert abs(sum(c[0] for c in out) - ((1 - 0.9) * w + sum(per_z))) < 1e-9


def test_merge_keeps_weight_mean_and_second_moment():
    comps = [(0.6, [0.0, 0.0], [[1.0, 0.0], [0.0, 1.0]]), (0.3, [0.5, -0.2], [[0.8, 0.1], [0.1, 1.2]]),
             (0.2, [0.1, 0.4], [[1.0, 0.0], [0.0, 1.0]]), (0.4, [20.0, 0.0], [[1.0, 0.0], [0.0, 1.0]]),
             (1e-7, [5.0, 5.0], [[1.0, 0.0], [0.0, 1.0]])]
    out = prune_and_merge(comps, threshold=1e-5, merge_dist=4.0)
    assert len(out) == 2
    w, m, p = out[0]
    group = comps[:3]
    assert abs(w - 1.1) < 1e-12
    for a in range(2):
        assert abs(m[a] - sum(c[0] * c[1][a] for c in group) / 1.1) < 1e-12
        for b in range(2):
            second = sum(c[0] * (c[2][a][b] + c[1][a] * c[1][b]) for c in group) / 1.1
            assert abs(p[a][b] + m[a] * m[b] - second) < 1e-12
    assert out[1][0] == 0.4 and out[1][1] == [20.0, 0.0]
    n_hat, states = extract(out)
    assert abs(n_hat - 1.5) < 1e-12 and len(states) == 1


def poisson(rng, lam):
    k, p, limit = 0, 1.0, math.exp(-lam)
    while True:
        p *= rng.random()
        if p < limit:
            return k
        k += 1


def test_scene_with_births_deaths_and_clutter():
    rng = random.Random(2003)
    model = cv_model(0.01, 0.25)
    # (birth frame, death frame, start state)
    targets = [(0, 40, [0.0, 0.0, 1.0, 0.5]), (0, 25, [0.0, 20.0, 1.0, -0.3]), (8, 40, [30.0, 0.0, -0.5, 1.0])]
    birth_cov = [[4.0, 0, 0, 0], [0, 4.0, 0, 0], [0, 0, 1.0, 0], [0, 0, 0, 1.0]]
    birth = [(0.05, [x, y, 0.0, 0.0], birth_cov) for x, y in ((0.0, 0.0), (0.0, 20.0), (30.0, 0.0))]
    area, rate = 60.0 * 60.0, 5.0
    kappa = lambda z: rate / area
    comps = []
    good, counted = 0, 0
    for k in range(40):
        zs, truth = [], []
        for i, (b, d, s0) in enumerate(targets):
            if b <= k < d:
                t = k - b
                x = [s0[0] + t * s0[2], s0[1] + t * s0[3]]
                truth.append(x)
                if rng.random() < 0.95:
                    zs.append([x[0] + rng.gauss(0, 0.5), x[1] + rng.gauss(0, 0.5)])
        for _ in range(poisson(rng, rate)):
            zs.append([rng.uniform(-10, 50), rng.uniform(-10, 50)])
        rng.shuffle(zs)
        comps, n_hat, est = phd_step(comps, zs, model, 0.99, 0.95, kappa, birth)
        assert len(comps) <= 100
        if k in (0, 1, 2, 8, 9, 10, 25, 26, 27):
            continue  # a few frames to settle after a birth or a death
        counted += 1
        if len(est) == len(truth) and all(min(math.dist(x, e[:2]) for e in est) < 1.5 for x in truth):
            good += 1
    assert good >= 0.8 * counted

History

Mahler developed finite set statistics in the 1990s as a way to treat multi-target tracking as Bayesian filtering of a random finite set. The full multi-target Bayes filter needs integrals over sets of every size, which cannot be computed for more than a few targets. In 2003 Mahler proposed to propagate only the first moment, the PHD, and derived its prediction and update equations, by analogy with the use of the mean in place of the full density. Vo, Singh and Doucet gave the first general implementation by sequential Monte Carlo in 2005. Vo and Ma found the closed Gaussian mixture form in 2006, together with the pruning, merging and extraction steps used on this page. In 2007 Mahler introduced the cardinalized PHD filter to fix the unstable count of the PHD filter and collected the theory in a book. Later filters on labeled random finite sets gave the targets identities.

References

  1. Ronald P. S. Mahler, Multitarget Bayes filtering via first-order multitarget moments, IEEE Transactions on Aerospace and Electronic Systems 39(4), 2003, 1152 to 1178, the whole paper (the PHD as the first moment of a random finite set, and the prediction and update equations of the PHD filter)
  2. Ba-Ngu Vo and Wing-Kin Ma, The Gaussian mixture probability hypothesis density filter, IEEE Transactions on Signal Processing 54(11), 2006, 4091 to 4104, the whole paper (the closed form Gaussian mixture recursion and its assumptions, the pruning, merging and state extraction steps, and the extension to nonlinear models)
  3. Ba-Ngu Vo, Sumeetpal Singh and Arnaud Doucet, Sequential Monte Carlo methods for multitarget filtering with random finite sets, IEEE Transactions on Aerospace and Electronic Systems 41(4), 2005, 1224 to 1245, the whole paper (the particle form of the PHD filter)
  4. Ronald Mahler, PHD filters of higher order in target number, IEEE Transactions on Aerospace and Electronic Systems 43(4), 2007, 1523 to 1543, the whole paper (the cardinalized PHD filter)
  5. Ronald P. S. Mahler, Statistical Multisource-Multitarget Information Fusion, Artech House, 2007, the chapters on random finite sets and on the PHD and CPHD filters

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