Type at least 2 letters. Enter opens the first result, Esc closes.

    learn.mohebi.ai

    Tracking with the Kalman filter

    Follow a moving object through noisy sensor readings. Watch the Kalman filter predict, compare its prediction with each measurement and correct itself, and see when a particle filter does better.

    A Kalman filter estimates the hidden state of a system that changes over time (here: the position and velocity of a moving object) from noisy measurements. It keeps a Gaussian belief about the state: a mean x^\hat x (the best guess) and a covariance PP (how unsure it is). Two steps repeat for every new measurement:

    In the first simulation you track a target with a position sensor and see both steps, the Kalman gain and the errors live. In the second one the sensor measures distance and angle, so the problem becomes nonlinear, and you compare the extended Kalman filter with a particle filter. At the end we connect all of this to data assimilation, the method that starts every weather forecast.

    1. The tracking simulation #

    Interactive figure: loading…

    Press Play and watch the two steps. The black dot (white in dark mode) is the true target, the orange dots are the noisy measurements zz. Violet, dashed: the prediction x^−\hat x^- and its 95% ellipse. Blue: the estimate x^\hat x after the update and its 95% ellipse. The orange dashed arrow is the innovation ν=z−Hx^−\nu = z - H\hat x^- (how much the measurement surprised the filter); the blue arrow is the correction KνK\nu. Pick slow, or press Next, to see predict and update one at a time. The charts show the last 10 seconds.

    2. Try this #

    1. Trust the model or trust the sensor? With the circle target, set the process noise qq to its smallest value, then to its largest. Question: which setting gives a smooth track that falls behind the target in the turn, and which one gives a track that jumps with every measurement? What to see: with small qq the gain K11K_{11} drops to about 0.120.12 and the blue track cuts inside the circle (its RMSE becomes larger than the sensor's). With large qq the gain rises to about 0.70.7 and the track copies the noise. Near q=1q = 1 the filter error is about half the sensor error.
    2. The gain does not look at the data. Press Next a few times. Question: after the predict step, before the measurement is used, is the gain KK already known? What to see: yes. KK depends only on P−P^- and RR, not on the value of zz. After a few seconds it stops changing: the filter reaches a steady state.
    3. Losing the signal. Set Measurements to no-signal zone. Question: inside the grey band, what happens to the ellipse, and what does the gain do at the first measurement after the band? What to see: with no updates the ellipse only grows, and the prediction flies straight on while the target turns. At the first new measurement K11K_{11} jumps close to 11: the filter trusts the sensor almost completely, because its own prediction is now very uncertain.
    4. A wrong noise model. Set the sensor noise σ\sigma to 11 and the filter's rr to 0.10.1, so the filter believes the sensor is ten times better than it is. Question: what do the innovation chart and the readout innovations inside the 95% region show? What to see: the innovations jump far outside the violet ±2S\pm 2\sqrt S band and the readout drops far below 95%. The filter is overconfident. Press set r = σ and watch it recover. (Try also qq very small with the back and forth target.)

    3. How the filter works #

    The model #

    The state is x=(px,py,vx,vy)x = (p_x, p_y, v_x, v_y): position and velocity. Between two measurements, Δt\Delta t seconds apart, the target moves with constant velocity plus a random acceleration. The sensor sees only the position:

    xk=Fxk−1+wk,wk∼N(0,Q),zk=Hxk+vk,vk∼N(0,R),\begin{aligned} x_k &= F x_{k-1} + w_k, & w_k &\sim \mathcal N(0, Q), \\ z_k &= H x_k + v_k, & v_k &\sim \mathcal N(0, R), \end{aligned}
    F=(IΔt I0I),Q=q(Δt33IΔt22IΔt22IΔt I),F = \begin{pmatrix} I & \Delta t\, I \\ 0 & I \end{pmatrix},\qquad Q = q \begin{pmatrix} \tfrac{\Delta t^3}{3} I & \tfrac{\Delta t^2}{2} I \\ \tfrac{\Delta t^2}{2} I & \Delta t\, I \end{pmatrix},
    H=(I0),R=r2I.H = \begin{pmatrix} I & 0 \end{pmatrix},\qquad R = r^2 I .

    Here II is the 2×22 \times 2 identity. This is the constant-velocity model. The number qq (the process noise) says how strongly the velocity can change; rr (the measurement noise) says how noisy the sensor is. In the simulation Δt=0.1\Delta t = 0.1 s.

    Where the matrix QQ comes from

    Assume the acceleration is white noise a(t)a(t) with spectral density qq. Over one step, the position changes by ∫0Δts a(tk−s) ds\int_0^{\Delta t} s\, a(t_k - s)\, ds and the velocity by ∫0Δta(tk−s) ds\int_0^{\Delta t} a(t_k - s)\, ds (on top of the constant-velocity motion). The covariance of (s,1) a(s, 1)\,a integrated over [0,Δt][0, \Delta t] is q∫0Δt(s2ss1)ds=q(Δt3/3Δt2/2Δt2/2Δt)q \int_0^{\Delta t} \begin{pmatrix} s^2 & s \\ s & 1 \end{pmatrix} ds = q \begin{pmatrix} \Delta t^3/3 & \Delta t^2/2 \\ \Delta t^2/2 & \Delta t \end{pmatrix}, one block for each axis.

    Predict #

    Push the mean and the covariance through the model:

    x^k−=Fx^k−1,Pk−=FPk−1F⊤+Q.\hat x^-_k = F \hat x_{k-1}, \qquad P^-_k = F P_{k-1} F^\top + Q .

    FPF⊤FPF^\top moves and stretches the ellipse (position uncertainty grows with velocity uncertainty), and + Q+\,Q makes it larger. This is the growing violet ellipse.

    Update #

    Compare the measurement with the predicted measurement Hx^k−H\hat x^-_k, then correct:

    νk=zk−Hx^k−innovationSk=HPk−H⊤+Rinnovation covarianceKk=Pk−H⊤Sk−1Kalman gainx^k=x^k−+Kkνk,Pk=(I−KkH)Pk−.\begin{aligned} \nu_k &= z_k - H \hat x^-_k && \text{innovation} \\ S_k &= H P^-_k H^\top + R && \text{innovation covariance} \\ K_k &= P^-_k H^\top S_k^{-1} && \text{Kalman gain} \\ \hat x_k &= \hat x^-_k + K_k \nu_k, \qquad P_k = (I - K_k H) P^-_k . \end{aligned}

    For a linear model with Gaussian noise, this gives the exact posterior: p(xk∣z1,…,zk)p(x_k \mid z_1, \dots, z_k) is Gaussian with mean x^k\hat x_k and covariance PkP_k. So x^k\hat x_k is the estimate with the smallest mean squared error. (The widget computes PkP_k in the equivalent "Joseph form" (I−KH)P−(I−KH)⊤+KRK⊤(I - KH)P^-(I-KH)^\top + KRK^\top, which stays symmetric and positive definite with rounding errors.)

    Why the gain balances model and data #

    Look at one coordinate with a direct position sensor (H=1H = 1). Then S=P−+RS = P^- + R and

    K=P−P−+R,x^=(1−K) x^−+Kz=R x^−+P−zP−+R,1P=1P−+1R.K = \frac{P^-}{P^- + R}, \qquad \hat x = (1 - K)\,\hat x^- + K z = \frac{R\,\hat x^- + P^- z}{P^- + R}, \qquad \frac{1}{P} = \frac{1}{P^-} + \frac{1}{R} .

    The update is a weighted average of the prediction and the measurement. Each one gets a weight proportional to the other's variance, so the more certain source counts more. The precisions (inverse variances) add, so the result is more certain than either source alone.

    Multiplying qq, r2r^2 and the starting PP by the same number multiplies every covariance by that number and leaves KK unchanged. The steady state does not depend on the starting PP, so the steady-state gain depends only on the ratio q/r2q / r^2: "how much do I trust the model compared with the sensor".

    Small example. Prediction x^−=10\hat x^- = 10 with P−=3P^- = 3, measurement z=14z = 14 with R=1R = 1. Then K=3/4K = 3/4, x^=10+0.75⋅(14−10)=13\hat x = 10 + 0.75 \cdot (14 - 10) = 13 and P=(1−0.75)⋅3=0.75P = (1 - 0.75) \cdot 3 = 0.75. The new variance 0.750.75 is smaller than both 33 and 11.

    Quick check

    A filter predicts x^−=2\hat x^- = 2 with P−=1P^- = 1. The sensor reads z=5z = 5 with R=2R = 2. What is the updated estimate x^\hat x?

    The filter can check itself #

    If the model is right, the innovations are Gaussian with mean 00 and covariance SkS_k, and they are independent over time. So about 95% of them should lie in the 95% region νk⊤Sk−1νk≤5.99\nu_k^\top S_k^{-1} \nu_k \le 5.99 (the 95% quantile of χ2\chi^2 with 2 degrees of freedom). The readout innovations inside the 95% region counts exactly this. Far fewer than 95% means the filter is overconfident (qq or rr too small); 100% for a long time means it is too cautious. The same test is used to monitor real trackers and weather models.

    Quick check

    The target enters the no-signal zone and no measurements arrive for 2 seconds. What happens to the covariance PP during this time?

    4. A nonlinear sensor: EKF and particle filter #

    A radar does not measure xx and yy. It measures the range ρ\rho (distance) and the bearing θ\theta (angle) of the target:

    z=h(x)+v,h(x)=(px2+py2atan2⁡(py,px)),v∼N ⁣(0,diag⁡(σρ2,σθ2)).z = h(x) + v, \qquad h(x) = \begin{pmatrix} \sqrt{p_x^2 + p_y^2} \\ \operatorname{atan2}(p_y, p_x) \end{pmatrix}, \qquad v \sim \mathcal N\!\big(0, \operatorname{diag}(\sigma_\rho^2, \sigma_\theta^2)\big).

    The positions that fit one measurement form a curved band: a piece of a ring. A Gaussian cannot have this shape, so the Kalman filter is no longer exact. Two standard fixes:

    Hk=(px/ρpy/ρ00−py/ρ2px/ρ200).H_k = \begin{pmatrix} p_x/\rho & p_y/\rho & 0 & 0 \\ -p_y/\rho^2 & p_x/\rho^2 & 0 & 0 \end{pmatrix}.

    The angle part of the innovation must be wrapped to (−π,π](-\pi, \pi].

    Interactive figure: loading…

    Watch the particles bend into an arc, then pick other examples under Try. The yellow triangle is the radar. The orange band holds the positions that fit the current measurement (range ±2σρ\pm 2\sigma_\rho, bearing ±2σθ\pm 2\sigma_\theta). Violet: the EKF estimate and its 95% ellipse. Aqua: the particles (bigger dots have larger weights) and their mean (ring). Both filters get the same measurements. The table compares their errors, how often their 95% ellipse contains the truth (for the particle filter: the ellipse of the particles' mean and covariance, not drawn), and the cost. Try wrong first guess: the EKF needs one or two seconds to find the target; the particles find it at once.

    1. The banana. Start with banana (selected when the page opens): the range is very precise (σρ=0.03\sigma_\rho = 0.03) but the bearing is poor (σθ=20°\sigma_\theta = 20°). Question: what shape does the particle cloud take, and does the EKF ellipse contain the truth about 95% of the time? What to see: the particles form a thin arc around the radar. The EKF ellipse is a straight, flat approximation of that arc. In our one-minute runs it contained the truth only about 35–55% of the time, and its error was about 1.5 times the particle filter's. The particle filter stays near 90–95%. (The table uses only the last 10 s, so its numbers move up and down; watch them for a while.)
    2. How many particles? Pick few particles (N=30N = 30), then move NN up to a few thousand. Question: what happens to the effective sample size, the error and the time per step? What to see: with few particles the cloud collapses to a handful of points after each resampling and can lose the target. More particles give a smoother cloud and a smaller error, but the error stops improving at some point (the measurements limit it), while the cost keeps growing in proportion to NN.
    Quick check

    Why does the EKF ellipse often miss the truth in the banana example?

    5. From tracking to weather forecasting #

    Weather forecasting solves the same problem at a huge scale. The state xx is the whole atmosphere on a grid (temperature, wind, pressure and humidity at every point): hundreds of millions of numbers or more. The measurements are tens of millions of observations a day from satellites, weather stations, balloons, aircraft and ships. Combining a model forecast with observations is called data assimilation, and it uses the same words:

    Kalman filter Data assimilation
    prediction x^−\hat x^-, covariance P−P^- background (first guess) xbx_b, background error covariance BB
    measurement zz, matrix HH observations yy, observation operator H\mathcal H
    innovation z−Hx^−z - H\hat x^- innovation, "observation minus background"
    update x^\hat x analysis xax_a
    predict step forecast with the weather model, until the next cycle (every 6 or 12 hours)

    The difficulty is size. With n≈109n \approx 10^9 state variables, PP would have 101810^{18} entries: it cannot be stored, let alone multiplied by FF. Two families of methods avoid this:

    J(x0)=12(x0−xb)⊤B−1(x0−xb)+12∑k(yk−Hk(xk))⊤Rk−1(yk−Hk(xk)),\begin{aligned} J(x_0) = {} & \tfrac12 (x_0 - x_b)^\top B^{-1} (x_0 - x_b) \\ & + \tfrac12 \sum_k \big(y_k - \mathcal H_k(x_k)\big)^\top R_k^{-1} \big(y_k - \mathcal H_k(x_k)\big), \end{aligned}

    where xkx_k is the model forecast from x0x_0. The gradient comes from the adjoint model (reverse-mode differentiation of the forecast model). For a linear model with Gaussian errors and no model error, 4D-Var gives the same estimate at the end of the window as the Kalman filter.

    Why not a particle filter? In high dimension the weights collapse: one particle gets almost all the weight. The number of particles needed grows exponentially with the effective dimension of the problem (Snyder and co-authors, 2008), so pure particle filters are not used for global weather models. In the widget above you can see the start of this problem with N=30N = 30 in only 4 dimensions.

    Quick check

    A weather model has n=109n = 10^9 state variables. Why can the forecast centre not run the Kalman filter equations exactly?