Where Am I? Kalman, EKF and UKF

A robot that only counts wheel turns drifts further off every lap. Give it range and bearing to four known landmarks, and an extended Kalman filter holds its pose to a few centimetres.

Choose what the robot can see. Watch the purple estimate and its ellipse against the teal true robot. Then we build, piece by piece, the belief, the Kalman gain, the matrix filter, the EKF that drives this robot and the UKF that needs no derivatives.

You need what a bell curve is, a derivative and a little Python. We build the rest from zero.

Lesson 13 of 15 in our follow-along of Stanford AA 274A, Principles of Robot Autonomy I. Every idea is re-taught here in our own words and devices. Before: Lesson 12, Occupancy Maps. Next: Lesson 14, Particle Filters.

Give a lost robot something to see

Illustrative toy in a 10 m by 6 m room. The robot drives a 3 m circle at 0.6 m/s and its wheels slip a few percent. Readings come 3.3 times a second from landmarks within 4.6 m, with 8 cm range noise and 0.03 rad bearing noise. The ellipse holds 95% of the belief.

Chapter 0

A Robot Never Knows Exactly Where It Is

Drive thirty robots blind and watch their errors spread

You tell a TurtleBot to roll forward 1 m. One wheel slips on dust. The motor overshoots a little. The robot moves 1.02 m and believes it moved 1.00 m.

Tracking the pose by counting wheel turns is dead reckoning. Each step adds a small error, and nothing takes it away. This growth of error is drift.

Drive thirty robots blind

Each teal line is one robot's true error after it drives 400 steps of 1 m by counting wheel turns. The purple band is the spread the math predicts. Set the step error, add a bias, then press Drive.

2.0 cm

Illustrative toy. Each step adds a random error with the set standard deviation; the bias adds 1 cm to every 1 m step.

Work the number. Each 1 m step has a random error with a standard deviation of 2 cm. Random errors partly cancel, so their variances (the squared spreads) add. After n steps the spread is 0.02 × √n m. After 400 steps that is 0.02 × 20 = 0.40 m. A 1% bias does not cancel: 400 × 0.01 = 4.0 m.

StepsDistanceSpread (one standard deviation)
11 m2 cm
2525 m10 cm
100100 m20 cm
400400 m40 cm

A sensor gives an outside reference. A laser reads the distance to a known landmark. But each reading is noisy too, so a pose taken from readings alone jumps every time.

So the robot has two witnesses. Motion says where it should be, and drifts. The sensor says where the landmarks are, and jitters. A filter blends the two, each weighted by how much it deserves trust. It also tracks how unsure the blend is.

The failure, as symptom, measurement and fix

The symptom is a robot that ends a long run in the wrong room. To measure it, drive a known loop and compare the end pose with the start. The fix is an outside reference, fused by a filter.

The road

  1. Belief: the Bayes filter, worked on a three-cell hallway.
  2. The Kalman filter: a bell curve, a predict, a gain and an update.
  3. The gain: how the trust slider tunes itself.
  4. Vectors: a position sensor that finds velocity.
  5. EKF predict: a turning robot and its Jacobian.
  6. EKF update: one landmark's range and bearing.
  7. The UKF: push sigma points through the curve.
  8. The showcase: the hero's robot with every knob (its full version).
  9. The field guide: terms, numbers, code and links onward.
Why can a robot not trust dead reckoning alone?

Chapter 1

Belief: The Bayes Filter in Three Cells

Move a belief, then sharpen it with one reading, by hand

A filter does not store one guess. It stores a belief: a probability for every place the robot might be. The Bayes filter updates it in two steps. Predict moves the belief with the motion model. Update reweights it with a reading.

Take a hallway of three cells, A, B and C. The belief is [0.5, 0.3, 0.2]. The robot moves right one cell: 80% of the time it moves, 20% it stalls. At C the wall stops it. A door stands at B.

Move a belief, then sense a door

Purple bars are the belief. Press Predict to move right, then Update to see the door. Blue bars show how likely a door reading is from each cell.

0.80

Illustrative toy. Door reading likelihoods: 0.1 at A, 0.6 at B, 0.3 at C.

Name the parts of the predict step. Call the belief in a start cell x′ bel(x′). Call the chance that the move takes the robot from x′ to x p(x | u, x′), where u is the command. Call the new belief bel̄(x); the bar means "before the reading".

Say it aloud

bel-bar of x equals the sum over x-prime of p of x given u and x-prime, times bel of x-prime.

bel̄(x)
bel-bar of x the predicted belief that the robot is in cell x, after the move.
Σx′
the sum over x-prime add one term for every cell the robot could have started in.
p(x | u, x′)
p of x given u and x-prime the motion model: the chance that command u takes the robot from x-prime to x.
bel(x′)
bel of x-prime the belief in start cell x-prime, before the move.
In plain words

For each end cell x, go through every start cell x-prime. Multiply the belief in x-prime by the chance that the move lands in x. Add the products.

With numbers

bel-bar(B) = 0.5 × 0.8 + 0.3 × 0.2 = 0.46. For all three cells the result is [0.10, 0.46, 0.44]. The peak at A is gone: moving lost knowledge.

Now the robot sees a door. Call the chance of a door reading z from cell x p(z | x): 0.1 at A, 0.6 at B, 0.3 at C.

Say it aloud

bel of x equals eta, times p of z given x, times bel-bar of x.

bel(x)
bel of x the corrected belief in cell x, after the reading.
η
eta one over the total of the products, so the new beliefs add up to 1.
p(z | x)
p of z given x the measurement model: the chance of reading z if the robot is in x.
bel̄(x)
bel-bar of x the predicted belief from the step before.
In plain words

Multiply each cell's predicted belief bel-bar by the chance p of this reading from that cell. Divide every product by their total. That division is eta.

With numbers

The products are 0.010, 0.276 and 0.132. They total 0.418, so eta = 1 / 0.418 = 2.39. The belief becomes [0.024, 0.660, 0.316]. The door pulled the belief onto B.

With three cells this is easy. A real pose (x, y, θ) has infinitely many cells, and the sum becomes an integral with no closed form. The next chapter makes the belief a bell curve, and the integral goes away.

The failure, as symptom, measurement and fix

The symptom is a belief stuck on a wrong cell. To measure it, count the cells with a belief of exactly zero. The fix: never let the motion model or the likelihood give an exact zero to a possible cell.

In the Bayes filter, which step makes the belief less certain, and which makes it more certain?

Chapter 2

Two Numbers: The 1-D Kalman Filter

Shift a bell curve, then pull it toward a reading by one fraction

Store the belief as a Gaussian, a bell curve. Two numbers describe it: the mean μ, the best guess, and the variance σ², the width. A Gaussian stays a Gaussian when you shift it, add Gaussian noise to it or multiply it by another Gaussian. Those are the only steps the Bayes filter needs. So the filter only updates μ and σ²: this is the Kalman filter.

The robot drives along a corridor. Its state is its position, in metres. Call the commanded move u. Call the variance of the motion error R. A bar marks a value before the reading.

Say it aloud

mu-bar equals mu plus u; sigma-bar squared equals sigma squared plus R.

μ̄
mu-bar the predicted position, in metres.
μ
mu the position estimate before the move.
u
u the commanded move, in metres.
σ̄²
sigma-bar squared the predicted variance, in square metres.
σ²
sigma squared the variance before the move.
R
R the motion noise: the variance of the error in one move.
In plain words

Shift the mean mu by the move u. Widen the variance by R, because no move is exact.

With numbers

With made-up numbers: mu = 2.0 m, sigma squared = 0.40, u = 1.0 m, R = 0.20. Then mu-bar = 3.0 m and sigma-bar squared = 0.60. The robot is less sure than before it moved.

Now the sensor reads the position z = 3.6 m. Call the variance of the sensor noise Q. How far toward z should the estimate move? Call that fraction the Kalman gain K.

Say it aloud

K equals sigma-bar squared over sigma-bar squared plus Q.

K
K the Kalman gain: the fraction of the gap to the reading that the estimate moves, from 0 to 1.
σ̄²
sigma-bar squared the variance of the prediction.
Q
Q the variance of the sensor noise.
In plain words

Divide the prediction's variance by the sum of both variances. A sharp sensor (small Q) gives K near 1. A sharp prediction gives K near 0.

With numbers

K = 0.60 / (0.60 + 0.10) = 0.857. The sensor is six times sharper than the prediction, so it gets most of the weight.

The gap between the reading and the prediction, z − μ̄, is the innovation: the surprise.

Say it aloud

mu equals mu-bar plus K times z minus mu-bar; sigma squared equals one minus K, times sigma-bar squared.

μ
mu the corrected position estimate.
μ̄
mu-bar the predicted position.
K
K the Kalman gain.
z
z the sensor reading, in metres.
σ²
sigma squared the corrected variance.
σ̄²
sigma-bar squared the predicted variance.
In plain words

Move the estimate from mu-bar toward z by the fraction K of the surprise. Shrink the variance by the factor one minus K.

With numbers

The surprise is 3.6 − 3.0 = 0.6 m. mu = 3.0 + 0.857 × 0.6 = 3.514 m. sigma squared = 0.143 × 0.60 = 0.086. That is smaller than both 0.60 and 0.10.

Blend a prediction and a reading

Dashed purple is the prediction; blue is the reading. Solid purple is the fused belief. Drag the two variances and watch where it lands.

0.60
0.10

Illustrative toy, fixed at mu-bar = 3.0 m and z = 3.6 m, the worked example. The default sliders give the numbers above.

The failure, as symptom, measurement and fix

The symptom is an estimate that ignores good readings. To measure it, log K: it sits near 0. The fix: R is too small, so the filter trusts its own motion too much. Raise R.

Why is this weight the best possible one? The Kalman Filter in our Sensor Fusion series derives it in full.

In the update μ = μ̄ + K(z − μ̄), what is z − μ̄?

Chapter 3

The Gain Tunes Itself

Step a parked robot's filter and watch K settle to one value

You never set K by hand. The filter computes it each tick from the two variances. After a long blind stretch the prediction is wide, so K is near 1 and the next reading pulls the estimate into place. Once the estimate is sharp, K shrinks and sensor jitter barely moves it.

Park the robot: u = 0, R = 0.04, Q = 0.25. Start vague, with σ² = 4.0. Each tick predicts, then updates.

Step the gain to its steady value

Top: the gain K at each tick. Bottom: the variance, which rises at each predict and drops at each update. Press Step, or change R and Q.

0.040
0.25

Illustrative numbers. The steady value is found by running the two steps until nothing changes.

Work tick 1. Predict: σ̄² = 4.00 + 0.04 = 4.04. Gain: K = 4.04 / (4.04 + 0.25) = 0.942. Update: σ² = (1 − 0.942) × 4.04 = 0.235. The first reading does almost all the work.

Tickσ̄² after predictKσ² after update
14.0400.9420.235
20.2750.5240.131
30.1710.4060.102
40.1420.3620.090
Steady0.1220.3280.082

At the steady state, the growth from R at each predict equals the shrink at each update. Then K depends only on the ratio R / Q. Double both noises and K stays 0.328. So tuning a Kalman filter means tuning one ratio.

The failure, as symptom, measurement and fix

The symptom is an estimate that chases jitter, or one that lags every change. To measure it, log the steady K. Near 1 means R / Q is too large; near 0 means it is too small. The fix is to tune that ratio.

Now build it. The lab below filters 120 noisy readings of a creeping robot with the four lines you just worked.

The prediction is very uncertain and the sensor is very precise. What does K do?

Chapter 4

Vectors: A Position Sensor That Finds Velocity

Grow a link between two errors, then watch a position reading fix the speed

Let the state hold two numbers: position p and velocity v. The mean becomes a vector, μ = [p, v]. The variance becomes a 2 by 2 covariance matrix Σ. Its diagonal holds the two variances. Its corner holds the covariance: how an error in p goes with an error in v. Drawn as an ellipse, the variances set its size and the covariance tilts it.

In each step of 1 s, the position gains the velocity and the velocity stays. A matrix F does this; the sensor reads position only, through H:

F = 1101,   H = 10

Call the covariance of the motion error R, as before.

Say it aloud

Sigma-bar equals F times Sigma times F-transpose, plus R.

Σ̄
Sigma-bar the predicted covariance, before the reading.
F
F the motion matrix: new state = F times old state.
Σ
Sigma the covariance before the move.
F⊤
F-transpose F flipped across its diagonal. A covariance is a squared quantity, so F acts on it from both sides.
R
R the motion noise covariance: the spread the model cannot explain.
In plain words

Push the old ellipse Sigma through the motion F, from both sides. Then add R.

With numbers

With made-up numbers: Sigma has variances 1 and covariance 0, and R = 0.01 on the diagonal. F Sigma F-transpose = [[2, 1], [1, 1]], so Sigma-bar = [[2.01, 1.00], [1.00, 1.01]]. A covariance of 1.00 appears: a position error now comes with a velocity error.

Call the covariance of the sensor noise Q. The gain is chapter 2's fraction, written with matrices.

Say it aloud

K equals Sigma-bar H-transpose, times the inverse of H Sigma-bar H-transpose plus Q.

K
K the gain matrix: one row per state number, one column per reading.
Σ̄
Sigma-bar the predicted covariance.
H⊤
H-transpose H flipped; Sigma-bar H-transpose says how each state number moves with the reading.
H
H the sensor matrix: what the sensor sees of the state.
Q
Q the sensor noise covariance.
( )−1
the inverse of the matrix form of "divide by". The bracket, called S, is the usual size of the surprise.
In plain words

Take how each state number moves with the reading, Sigma-bar H-transpose. Divide it by S, how big the surprise usually is. The result K maps a surprise onto every state number.

With numbers

With Q = 0.5: S = 2.01 + 0.5 = 2.51. Sigma-bar H-transpose is Sigma-bar's first column, [2.01, 1.00], so K = [0.801, 0.398]. The prior mean [0, 1] predicts to [1, 1]. A reading of 1.2 gives a surprise of 0.2, so the mean becomes [1.160, 1.080].

The covariance update is chapter 2's (1 − K)σ̄² with matrices: Σ = (I − KH)Σ̄, where I is the identity matrix.

The reveal. The sensor never saw velocity. The velocity estimate still rose, from 1 to 1.08, because the covariance carried the position surprise into it.

Track a robot from position fixes alone

Teal is the true robot, blue dots are noisy position fixes, purple is the estimate with its ellipse and velocity arrow. Press Run, then change the noises.

0.60 m
0.200

Illustrative toy: state [x, y, vx, vy], a constant-velocity model, a fix every 0.5 s. The true robot turns slowly, which the model does not know.

The failure, as symptom, measurement and fix

The symptom is an estimate that lags every turn. To measure it, watch the surprise: it stays on one side through a turn. The fix: raise R, the budget for the robot to break the constant-velocity model.

The sensor measures only position. Why does the velocity estimate change after an update?

Chapter 5

EKF Predict: A Robot That Turns

Bend a cloud of poses into a banana, then fit it with a tangent

Our robot's pose has three numbers: x, y and the heading θ. Lesson 2 gave its motion over a short time Δt at forward speed V and turn rate ω. Call this motion model g:

x′ = x + VΔt cos θ,   y′ = y + VΔt sin θ,   θ′ = θ + ωΔt

The cos and sin bend the motion. A bell curve pushed through g comes out curved, so it is no longer a bell curve.

Bend a belief into a banana

Each purple dot is one possible pose, driven straight ahead. The ring is the EKF's ellipse; the cross is the true average. Raise the heading doubt and the distance.

30°
4.0 m

Illustrative toy: 400 samples, start position known to 5 cm, heading doubt as set, no other noise.

The extended Kalman filter (EKF) keeps the curve for the mean: μ̄ = g(u, μ). For the covariance it replaces g by its tangent at the mean. For a function of three numbers, the tangent is the Jacobian G. It is a 3 by 3 table of how each output moves when you nudge each input.

G = 10−VΔt sin θ01VΔt cos θ001

Only the last column is new. It says how a heading error moves the position: by VΔt, sideways to the motion. The predict step is then chapter 4's equation with G in the place of F: Σ̄ = GΣG⊤ + R.

Work a step, with made-up numbers. μ = (0.5, 2.0, 0), V = 0.5 m/s, Δt = 1 s, so μ̄ = (1.0, 2.0, 0). G's last column is (0, 0.5, 1). With Σ = diag(0.20, 0.20, 0.08) and R = diag(0.05, 0.05, 0.02):

Σ̄ = 0.250000.270.0400.040.10

The y variance gained 0.5² × 0.08 = 0.02 from heading doubt. The y and θ errors are now linked by 0.04.

The failure, as symptom, measurement and fix

The symptom is an EKF that is sure and wrong. To measure it, push many samples through g and compare their mean with μ̄. Take a heading doubt of 30° (0.52 rad) and a 4 m drive. The EKF says 4.00 m ahead. The samples average 4 × e−0.137 = 3.49 m. The fix: update often to keep the doubt small, or use the UKF of chapter 7.

More on linearization error and the EKF's equations: The Extended Kalman Filter in our Sensor Fusion series.

How does the EKF predict step treat the curved motion model g?

Chapter 6

EKF Update: One Landmark Sighting

Compare the reading you got with the one you expected, and slide the pose

The map lists landmarks at known places. The sensor returns the range r, the distance to a landmark, and the bearing φ, its angle from the robot's heading. The update compares this reading with the reading the robot expected from its predicted pose.

Call the landmark's position (mx, my). The measurement model h gives the expected reading from a pose (x, y, θ).

Say it aloud

h equals: the square root of m-x minus x, squared, plus m-y minus y, squared; and atan-two of m-y minus y and m-x minus x, minus theta.

h
h the expected reading: a range in metres and a bearing in radians.
√(…)
the square root of the straight-line distance from the robot at (x, y) to the landmark at (m-x, m-y).
atan2(…)
atan-two the direction of the arrow from the robot to the landmark, measured from the x axis, in the right quadrant.
mx, my
m-x, m-y the landmark's known position on the map, in metres.
x, y
x, y the robot's position, in metres.
θ
theta the robot's heading; subtracting it gives the angle the robot sees.
In plain words

The range is the distance from the robot to the landmark. The bearing is the direction to the landmark, minus the direction theta the robot faces.

With numbers

Predicted pose (1, 2, 0), landmark (4, 6). The differences are 3 and 4, so the expected range is 5.0 m and the bearing is atan2(4, 3) − 0 = 0.927 rad, about 53°.

The covariance step needs h's tangent, the Jacobian H. Let q = 3² + 4² = 25 be the squared range:

H = −3/5−4/504/25−3/25−1 = −0.6−0.800.16−0.12−1

Read the rows. Step toward the landmark and the range drops. Turn left by 0.1 rad and the bearing drops by 0.1 rad. The update is chapter 4's, with h in the surprise: μ = μ̄ + K(z − h(μ̄)).

Work it. The sensor reads z = (4.6 m, 0.95 rad), so the surprise is (−0.40, +0.023): the landmark is closer than expected. Take Σ̄ from chapter 5 and Q = diag(0.04, 0.01). The pose moves to (1.229, 2.260, −0.012), toward the landmark. The heading's standard deviation falls from 0.32 to 0.12 rad.

Correct a pose with one sighting

Dashed purple is the predicted pose; solid purple is the corrected one. The blue arc and ray are the reading. Move the reading, or use only one channel.

4.60 m
0.95 rad

The worked example's numbers: predicted pose (1, 2, 0) with the chapter 5 covariance, landmark (4, 6), range sd 0.2 m, bearing sd 0.1 rad. Ellipses hold 95% of the position belief.

The failure, as symptom, measurement and fix

The symptom is an EKF that diverges after you edit h. To measure it, nudge each state number by 10−6 and compare the change in h with your H. The fix is to correct H: a wrong Jacobian is the most common EKF bug. Also wrap the bearing surprise into −π to π.

The range reading is shorter than the expected range. Which way does the update move the position?

Chapter 7

The UKF: Push Points, Not Tangents

Send three sigma points through the curve and fit a bell to where they land

The EKF replaces the curve by a straight line at one point. The unscented Kalman filter (UKF) keeps the curve and simplifies the belief instead. It picks a few sigma points that carry the belief's mean and spread. It pushes each one through the true function and fits a bell curve to where they land. No derivatives.

A belief with n numbers gets 2n + 1 sigma points. Call the spread knob λ (lambda). In one dimension, with mean μ and variance σ²:

Say it aloud

chi-zero equals mu; chi plus-or-minus equals mu plus or minus the square root of n plus lambda, times sigma squared.

χ0
chi-zero the centre sigma point.
χ±
chi plus-or-minus the two side sigma points, one on each side of the mean.
μ
mu the mean of the belief.
√( )
the square root of turns a variance into a distance; in more dimensions it is a matrix square root.
n
n how many numbers the state has: 1 here, 3 for a pose.
λ
lambda the spread knob; n + lambda = 3 is the usual choice for a bell curve.
σ²
sigma squared the variance of the belief.
In plain words

Put one point at mu. Put one on each side, the square root of n plus lambda standard deviations out. Give the centre weight lambda / (n + lambda) and each side 1 / (2(n + lambda)). Push all three through the function; their weighted mean and weighted spread are the new bell curve.

With numbers

Push x with mean 2 and variance 1 through y = x², with n = 1 and lambda = 2. The points are 2 and 2 ± 1.732, with weights 2/3, 1/6, 1/6. Outputs 4, 13.93 and 0.07 give mean 5.0 and variance 18.0. The true values are 5 and 18. The EKF's tangent says 4 and 16.

Push three points through a curve

The purple bell is the input belief; its three dots climb the curve. Compare the three output means on the right. Move the belief where the curve bends.

2.00
1.00

Exact maths: n = 1, lambda = 2. The true mean and variance come from closed forms (for x squared: mean mu² + sigma², variance 4mu²sigma² + 2sigma⁴).

For y = x² with n + λ = 3, the UKF is exact for every mean and spread. For sin x it is close, not exact. In the update, the UKF also pushes its points through h. The cross-covariance of the state points and their readings replaces Σ̄H⊤ in the gain.

FilterCurve handled byCost per step (pose, n = 3)Belief
EKFJacobians G and H at the mean1 call of g, plus derivativesone bell curve
UKF7 sigma points through the true g and h7 calls of g, no derivativesone bell curve

The failure, as symptom, measurement and fix

The symptom is a crash in the matrix square root. To measure it, log the smallest eigenvalue of Σ each tick; it drifts below zero. The fix: make Σ symmetric each tick, and choose λ ≥ 0 so no weight is negative.

Full UKF update and weight choices: The Unscented Kalman Filter in our Sensor Fusion series.

What is the core difference between the EKF and the UKF?

Chapter 8

Showcase: The Robot Localizes Itself

Run the hero's robot with every knob, then break it

This is the hero's robot with the controls exposed. Each tick runs the EKF localization loop:

  1. Predict. Push the pose through g with the odometry command; grow Σ with G and R.
  2. Expect. For each landmark in range, compute h(μ̄) and its Jacobian H.
  3. Gate. Check that the reading is plausible.
  4. Update. Apply the correction, one landmark at a time.

The gate uses the Mahalanobis distance d²: the surprise measured in its own standard deviations, with S as the yardstick. For a two-number reading, a real landmark gives d² above 9.21 only 1% of the time. A larger d² likely means a person's leg, not the landmark, so the filter drops the reading. Chapter 6's reading had d² = 0.56: well inside.

Localize, then break it

Teal is the true robot; purple is the estimate and its ellipse. Blue beams are accepted readings, grey are gated out, red are bad readings that got in. Press Run and try each knob.

1.0×
1.0×

Illustrative toy, the hero's room. Bad readings: the toy swaps 15% of readings for a short range at a wrong angle. The gate rejects d² above 9.21.

Things to try:

The failure, as symptom, measurement and fix

The symptom is a truth that sits outside the ellipse. To measure it, count how often the true pose falls outside the 95% ellipse; it should be about 5%. The fix: raise R or Q until the count is right, because a filter that is too sure ignores the readings it needs.

What does the validation gate do in EKF localization?

Chapter 9

Field Guide

Keep the terms, the numbers, the code and the family in one place

A filter keeps a belief and runs two steps forever. Predict pushes it through the motion model and widens it. Update pulls it toward a reading by the gain K and narrows it. The Kalman filter does this for bell curves and straight-line models. The EKF bends it with Jacobians; the UKF with sigma points.

TermMeaningNumber to remember
Driftrandom error grows as √n2 cm a step: 40 cm after 400 steps
Bayes filterpredict by a sum, update by a product and eta[0.5, 0.3, 0.2] to [0.024, 0.660, 0.316]
Kalman gainK = σ̄² / (σ̄² + Q)0.60 and 0.10: K = 0.857
Updateμ = μ̄ + K(z − μ̄)3.0 and 3.6: 3.514, variance 0.086
Steady gainset by R / Q onlyR 0.04, Q 0.25: K = 0.328
Matrix predictΣ̄ = FΣF⊤ + Rcovariance 1.00 appears
Hidden velocityK = Σ̄H⊤S−1K = [0.801, 0.398]
Range, bearingh(x) and its 2 by 3 Jacobian H5.0 m, 0.927 rad
BananaEKF mean bias under heading doubt30°, 4 m: 4.00 vs 3.49 m
Sigma points2n + 1 points, n + λ = 3x² of N(2, 1): 5 and 18
Gatedrop a reading with d² above the limit9.21 for two numbers, at 1%

Checklist for a localization filter

The core, in code

python
import numpy as np
def ekf_step(mu, Sig, V, w, dt, readings, landmarks, R, Q, gate=9.21):
    x, y, th = mu
    # predict: mean along the real curve g, covariance along its tangent G
    mu = np.array([x + V*dt*np.cos(th), y + V*dt*np.sin(th), th + w*dt])
    G = np.array([[1, 0, -V*dt*np.sin(th)], [0, 1, V*dt*np.cos(th)], [0, 0, 1]])
    Sig = G @ Sig @ G.T + R
    # update: one landmark at a time
    for j, z in readings:
        dx, dy = landmarks[j] - mu[:2]
        q = dx*dx + dy*dy; r = np.sqrt(q)
        zhat = np.array([r, np.arctan2(dy, dx) - mu[2]])
        H = np.array([[-dx/r, -dy/r, 0], [dy/q, -dx/q, -1]])
        nu = z - zhat
        nu[1] = (nu[1] + np.pi) % (2*np.pi) - np.pi     # wrap the bearing
        S = H @ Sig @ H.T + Q
        if nu @ np.linalg.solve(S, nu) > gate:     # Mahalanobis gate
            continue
        K = Sig @ H.T @ np.linalg.inv(S)
        mu = mu + K @ nu
        Sig = (np.eye(3) - K @ H) @ Sig
    return mu, Sig

The family

FilterHandlesUse it when
Bayes filterany belief, in principlethe state is small and discrete
Kalman filterstraight-line models, one bell curveconstant-velocity tracking
EKFgentle curves, one bell curvelandmark localization with a good start
UKFsharper curves, one bell curvethe Jacobian is hard, or the doubt is wide
Particle filterany curve, several peaksglobal localization, a kidnapped robot

Keep going

Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's lesson on Kalman, EKF and UKF localization in our own words, devices and toy numbers.

The takeaway. Never pick between motion and sensing. Blend them by the gain, keep the covariance honest, and the robot knows where it is and how sure it is.

Now press Present or Teach and explain from memory: the two Bayes steps, the gain, the hidden velocity, G and H, and the sigma points. Then go back to the lost robot, choose one landmark, and say which way its ellipse stretches and why.

Principles of Robot Autonomy I · Stanford AA 274A · Lesson 13: Kalman, EKF and UKF
Next: Particle Filters · Back to Gleams