Kalman Filter
Harddifficulty
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.
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 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.
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 with . 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 and . The gain is . The measurement is 0.2 above the prediction, so move toward it: . Then . Carrying on:
| Loop | prediction | gain | corrected | corrected |
|---|---|---|---|---|
| 1 | 1.000 | 0.556 | 1.111 | 2.222 |
| 2 | 2.111 | 0.446 | 2.106 | 1.785 |
| 3 | 3.106 | 0.410 | 3.022 | 1.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.
What does become when is much bigger than ? When is much bigger than ? Now picture a
robot that runs With the gain approaches 1 and : the filter drops its own estimate and believes the
sensor. With the gain approaches 0 and the measurement barely matters. Between tags, predict at 50 Hz from odometry but only runs correct when an AprilTag is in view.
What happens to during a long stretch without a tag, and to the gain when a tag finally shows up?Show solution
predict
adds every loop, so keeps growing. The longer the robot goes without a tag, the bigger 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.
The low-pass filter and this one both compute Call the steady predicted variance . Staying the same means , which
rearranges to , so With and that's and , 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
just came from your noise numbers instead of a guess. With , nothing ever makes grow again, so and 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.estimate + gain * (measurement - estimate). The only
difference is where the gain comes from. With and held constant, what does settle to after many
loops? (Look for the value of the predicted that stays the same from one loop to the next.) Then try
.Show solution
Set from the standard deviation you measured in Signals & Noise: it's that number squared. 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:
reshapes the existing uncertainty as the state moves, and is added on top. With one state and , this is just from the code above.
Correct with a measurement :
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. is the sensor's noise, and is the identity matrix. With one state and , the gain is again, and the matrix inverse is ordinary division.
The update reads the same way as before. is how surprised the filter is by the measurement, 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 ) gives a small , so the estimate stays smooth. An uncertain prediction (large ) gives a large , 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 , and the filter's matches it. The other slider sets , how much random acceleration the filter assumes. For each axis the demo uses with s. The bubble's radius is twice the estimated position standard deviation, as a picture of the uncertainty rather than a guaranteed boundary.
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
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 and , 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:
The estimate follows the real motion. The uncertainty still needs a matrix, so each loop the EKF finds the best straight-line approximation of and around the current estimate. Those are the Jacobians:
Then the familiar equations come back with and in place of and :
Kou and Haggenmiller's FTC paper, linked below, uses an EKF on a mecanum robot with this state:
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.
The Jacobians are only accurate close to the current estimate. Long time steps, a bad starting estimate, strongly nonlinear motion, biased sensors, or unrealistic and 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 KF | Extended KF |
|---|---|
| nonlinear | |
| nonlinear | |
| fixed | Jacobians at the current estimate |
| optimal under its assumptions | an 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.
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.
- Kou, E., & Haggenmiller, A. (2023), Extended Kalman Filter State Estimation for Autonomous Competition Robots — download the paper PDF or open the arXiv record. Sections III-B and IV cover the Jacobians and the mecanum state model; VI and VII cover limitations.
- WPILib State Observers and Pose Estimators — maintained FRC implementations of observers and pose estimators.
- R. E. Kalman, A New Approach to Linear Filtering and Prediction Problems — the original paper.