Skip to main content

Kalman Filter

Harddifficulty

Before you start

You don't need a probability course. Signals & Noise covers the average and the standard deviation, which is enough, and the Complementary Filter introduces the predict-then-correct idea with a fixed blend. The matrix section later in the lesson is optional; get the one-number filter working first. If you want more background on variance and the bell curve, kalmanfilter.net has a good introduction.

The complementary filter blends two sources with a weight you pick once. A Kalman filter works out the weight itself, every loop, from how uncertain each source is right now. Under the right conditions (a linear model, and noise that's random, bell-shaped, and not correlated from one loop to the next), that weight is the best possible one.

The last condition is the one real sensors break most often. A camera on a bent mount, or a tag measured in the wrong place, is off by the same amount every time. That's a bias, not random noise, and a Kalman filter will settle confidently on the biased answer. Calibrate the sensor first.

How much should you trust the camera?​

Say your robot tracks its position with odometry, which is smooth but drifts, and sometimes sees an AprilTag, which gives a noisy but absolute position. Right after a good tag sighting, odometry is very trustworthy. After ten seconds without seeing a tag, it's much less so. A fixed blend weight can't tell those situations apart, and it can't tell you how confident the result is.

Math explorerKalman gain: covariance decides who gets believed
state valuerelative probabilitypredictionmeasurementestimate
Kalman gain K = P/(P+R): 0.68innovation z − Hx: -1.80estimate = prediction + K·innovation: -0.13 = 1.10 + 0.68 × -1.80posterior variance (1−K)·P: 0.24
model predictionsensor measurementcorrected estimate

The graph shows one dimension. The blue curve is the prediction, the pink curve is the measurement, and the green curve is the combined estimate. A wide curve means that source is uncertain, and a narrow one means it's confident. Change the widths and watch the estimate move toward whichever curve is narrower.

A one-number Kalman filter​

Track one number, say the robot's xx position. The filter keeps two things: the estimate xHat, and its variance P, which is how uncertain the estimate is (the standard deviation squared). Each loop it does two steps.

Predict. Move the estimate by the measured motion delta, and add Q to P, because every prediction adds some uncertainty.

Correct, whenever a measurement z arrives. Work out a gain K between 0 and 1 from how uncertain the prediction is (P) compared with the sensor (R). Move the estimate that fraction of the way toward the measurement, and shrink P, since you now know more.

FTCPersistent scalar predict/correct loop
private double xHat; // the estimate; start at your best guess
private double P; // its variance; start LARGE if the guess is poor
private double Q; // process noise: how far truth drifts per loop
private double R; // measurement noise: how much the sensor lies

// Every loop, from a measured displacement.
void predict(double delta) {
xHat += delta;
P += Q;
}

// Only when a validated measurement exists.
void correct(double z) {
double K = P / (P + R); // the Kalman gain
xHat += K * (z - xHat); // (z - xHat) is the innovation
P = (1 - K) * P;
}

Run it by hand. Start at x^=0\hat x = 0 with P=4P = 4. Each loop the robot moves delta = 1, with Q = 1 and R = 4, and the measurements are 1.2, 2.1, and 2.9.

Loop 1: predict x^=1\hat x = 1 and P=4+1=5P = 4 + 1 = 5. The gain is 5/(5+4)=0.5565 / (5 + 4) = 0.556. The measurement is 0.2 above the prediction, so move 0.556×0.2=0.1110.556 \times 0.2 = 0.111 toward it: x^=1.111\hat x = 1.111. Then P=(1−0.556)×5=2.222P = (1 - 0.556) \times 5 = 2.222. Carrying on:

Loopprediction x^−\hat x^-gain KKcorrected x^\hat xcorrected PP
11.0000.5561.1112.222
22.1110.4462.1061.785
33.1060.4103.0221.642

The gain starts high, because the starting guess was poor, and settles lower as the filter becomes more confident. If you can trace a loop like this and explain why a bigger P gives a bigger gain, you understand the Kalman filter. Everything else is the same idea with more numbers.

ExerciseThe two extremes of the gain

What does x^\hat x become when PP is much bigger than RR? When RR is much bigger than PP? Now picture a robot that runs predict at 50 Hz from odometry but only runs correct when an AprilTag is in view. What happens to PP during a long stretch without a tag, and to the gain when a tag finally shows up?

Show solution

With P≫RP \gg R the gain approaches 1 and x^→z\hat x \to z: the filter drops its own estimate and believes the sensor. With R≫PR \gg P the gain approaches 0 and the measurement barely matters. Between tags, predict adds QQ every loop, so PP keeps growing. The longer the robot goes without a tag, the bigger PP is when one appears, and the harder the estimate snaps to it. That's what you want, and it's also why one tag seen from a bad angle can yank the pose.

ExerciseWhere the low-pass α came from

The low-pass filter and this one both compute estimate + gain * (measurement - estimate). The only difference is where the gain comes from. With QQ and RR held constant, what does KK settle to after many loops? (Look for the value of the predicted PP that stays the same from one loop to the next.) Then try Q=0Q = 0.

Show solution

Call the steady predicted variance pp. Staying the same means p=Rpp+R+Qp = \frac{Rp}{p+R} + Q, which rearranges to p2−Qp−QR=0p^2 - Qp - QR = 0, so

p=Q+Q2+4QR2,K∞=pp+R.p = \frac{Q + \sqrt{Q^2 + 4QR}}{2}, \qquad K_\infty = \frac{p}{p + R}.

With Q=1Q = 1 and R=4R = 4 that's p=2.562p = 2.562 and K∞=0.390K_\infty = 0.390, which is where the table above was heading (0.556, 0.446, 0.410). Once it settles, this Kalman filter is a low-pass filter. Its α\alpha just came from your noise numbers instead of a guess.

With Q=0Q = 0, nothing ever makes PP grow again, so 1/Pk=1/P0+k/R1/P_k = 1/P_0 + k/R and KK keeps shrinking toward zero. Each new measurement counts for less and less. That's right for something that truly never changes, but it makes the filter slower and slower to notice anything the model didn't expect. It never quite stops updating, though; the gain only approaches zero.

Set RR from the standard deviation you measured in Signals & Noise: it's that number squared. QQ is the harder one to pick. Start from how much drift you actually see between corrections and adjust from there.

More than one number (optional)​

A robot's state is usually more than one number, for example position and velocity together. The matrix version tracks all of them at once, along with how their uncertainties are related. The steps are the same.

Predict the state with a model, and grow the uncertainty:

x^−=Ax^+Bu,P−=APA⊤+Q\hat{x}^- = A\hat{x} + Bu, \qquad P^- = A P A^\top + Q

APA⊤APA^\top reshapes the existing uncertainty as the state moves, and QQ is added on top. With one state and A=1A = 1, this is just P+QP + Q from the code above.

Correct with a measurement zz:

K=P−H⊤(HP−H⊤+R)−1,x^=x^−+K (z−Hx^−),P=(I−KH)P−K = P^- H^\top (H P^- H^\top + R)^{-1}, \qquad \hat{x} = \hat{x}^- + K\,(z - H\hat{x}^-), \qquad P = (I - KH)P^-

HH turns a state into what the sensor would report, because the sensor often doesn't measure the state directly. A camera might see position but not velocity, for example. RR is the sensor's noise, and II is the identity matrix. With one state and H=1H = 1, the gain is P−/(P−+R)P^-/(P^- + R) again, and the matrix inverse is ordinary division.

The update reads the same way as before. z−Hx^−z - H\hat{x}^- is how surprised the filter is by the measurement, KK decides how much of that surprise to believe, and the new estimate is the prediction plus that much of the surprise. A noisy sensor (large RR) gives a small KK, so the estimate stays smooth. An uncertain prediction (large P−P^-) gives a large KK, so the estimate jumps toward the measurement.

In the demo, a target follows a curved path and is only reported as noisy dots. The filter recovers a smooth track and an uncertainty bubble around it. The sensor slider sets the noise's standard deviation σ\sigma, and the filter's R=σ2R = \sigma^2 matches it. The other slider sets qq, how much random acceleration the filter assumes. For each axis the demo uses Q=q[Δt4/4Δt3/2Δt3/2Δt2]Q = q\begin{bmatrix}\Delta t^4/4 & \Delta t^3/2 \\\Delta t^3/2 & \Delta t^2\end{bmatrix} with Δt=0.06\Delta t = 0.06 s. The bubble's radius is twice the estimated position standard deviation, as a picture of the uncertainty rather than a guaranteed boundary.

Live demo2-D Kalman tracking
True targetNoisy measurementsKalman estimateUncertainty
Sets both simulated sensor noise and the filter's R = σ².
Low = "moves predictably" (smoother, lags turns) · High = "could do anything"
Raw blip error: —Kalman error: —Improvement: —
Warn
Q and R are the tuning

Set Q very low and the estimate lags on sharp turns, because you've told the filter its model is nearly perfect. Set it high and it chases every noisy dot. Q is how much you distrust the model, so raising it makes the filter trust the sensor more. Picking Q and R to match the real process and sensor is most of the work of using a Kalman filter.

The Extended Kalman Filter​

This section uses partial derivatives

It uses partial derivatives and Jacobian matrices. Khan Academy covers partial derivatives and the Jacobian. You can skip it. The linear filter above is complete on its own.

A robot's motion on the field involves sin⁡θ\sin\theta and cos⁡θ\cos\theta, because moving forward means different things at different headings. That makes the model nonlinear, and the linear filter can't use it directly. An Extended Kalman Filter (EKF) handles it by predicting with the real nonlinear functions:

x^k−=f(x^k−1,uk),z^k=h(x^k−).\hat{\mathbf x}^{-}_k=f(\hat{\mathbf x}_{k-1},\mathbf u_k), \qquad \hat{\mathbf z}_k=h(\hat{\mathbf x}^{-}_k).

The estimate follows the real motion. The uncertainty still needs a matrix, so each loop the EKF finds the best straight-line approximation of ff and hh around the current estimate. Those are the Jacobians:

Fk=∂f∂x∣x^k−1,Hk=∂h∂x∣x^k−.F_k=\left.\frac{\partial f}{\partial\mathbf x}\right|_{\hat{\mathbf x}_{k-1}}, \qquad H_k=\left.\frac{\partial h}{\partial\mathbf x}\right|_{\hat{\mathbf x}^{-}_k}.

Then the familiar equations come back with FkF_k and HkH_k in place of AA and HH:

Pk−=FkPk−1Fk⊤+Q,P^-_k=F_kP_{k-1}F_k^\top+Q, Kk=Pk−Hk⊤(HkPk−Hk⊤+R)−1,K_k=P^-_kH_k^\top(H_kP^-_kH_k^\top+R)^{-1}, x^k=x^k−+Kk(zk−h(x^k−)).\hat{\mathbf x}_k=\hat{\mathbf x}^{-}_k+K_k(\mathbf z_k-h(\hat{\mathbf x}^{-}_k)).

Kou and Haggenmiller's FTC paper, linked below, uses an EKF on a mecanum robot with this state:

x=[x, y, θ, vxbody, vybody, ω]⊤.\mathbf x=[x,\ y,\ \theta,\ v_x^{body},\ v_y^{body},\ \omega]^\top.

Velocity is tracked in the robot's frame and rotated into the field frame during prediction, which is where the nonlinearity comes from. Odometry gives frequent velocity measurements, and landmark sightings give occasional absolute positions, so the EKF can predict through the gaps and remove drift when a landmark comes back.

Warn
An EKF is an approximation

The Jacobians are only accurate close to the current estimate. Long time steps, a bad starting estimate, strongly nonlinear motion, biased sensors, or unrealistic QQ and RR can make the uncertainty wrong or make the filter diverge. The paper found its approximation got worse with longer update intervals. Recompute the Jacobians every loop, keep timestamps accurate, wrap angle differences, and reject bad vision readings before correcting.

Linear KFExtended KF
Ax+BuA\mathbf x+B\mathbf unonlinear f(x,u)f(\mathbf x,\mathbf u)
HxH\mathbf xnonlinear h(x)h(\mathbf x)
fixed A,HA,HJacobians Fk,HkF_k,H_k at the current estimate
optimal under its assumptionsan approximation

For an FTC robot, use a maintained localization library unless building and testing an EKF is itself the goal. Read the paper once you can follow the matrix equations above.

Using it on the robot​

For the one-number filter, create it once when the OpMode starts and keep it for the whole OpMode. Call predict(deltaX) every loop with the latest motion from your pose source, and call correct(tagX) only when a vision reading passes your timestamp, calibration, and geometry checks. Don't create a new filter inside the loop, or it forgets its estimate and uncertainty every time.

Check your pose source against the Pose Estimation Contract first: frame, units, update rate, and freshness.

Tip
More than smoothing

In the demo, the Kalman estimate's error is usually a fraction of the raw measurement error. It's combining the model and the measurement, not just averaging, which is why the same idea shows up in GPS, drones, and robot localization.

Full field localization is nonlinear, so for that, use a maintained library's pose estimate. Use this lesson's filter for one-dimensional signals you combine yourself.

Sources and further reading