Self-Driving Cars
Topic 15 · Part 3: Knowing where you are · ⏱ about 4 h

Kalman Filters: Combining Uncertain Sensors

A car must know where it is to within a few tens of centimetres, but GPS is metres off and dead reckoning drifts. Learn how the Kalman filter combines a motion prediction with noisy measurements, step by step from one dimension to the extended Kalman filter, and use it to track the car around the course, through a tunnel with no GPS.

Softmaxima Simulator StudioWrite your car in Python, with as many files and trained networks as it needs, and watch it drive. In your browser, nothing to install.Open
Show:
In this topic
Beginner

In plain words

Your phone's map knows roughly where you are from GPS, but GPS can be several metres off. Your car also knows how fast it is going and how much it is turning. A Kalman filter combines the two: it predicts where you should be from your movement, then corrects that guess a little each time GPS reports in, trusting whichever is more reliable at that moment. Two settings say how much to trust each: Q (how unreliable the movement guess is) and R (how noisy GPS is).

By the end of this topic you will be able to explain how a car keeps track of where it is, even through a tunnel with no GPS.

Start with: the demo Try it: through the tunnel.

Beginner

Why "where am I?" is hard

Until now the simulator has told the car exactly where it is. A real car has to work it out, and it needs to be accurate: a lane is about 3.5 m wide, so an error of one metre can put a wheel on the line. The sensors available:

  • GPS (more generally GNSS): a position anywhere on Earth, but typically several metres off, only a few times a second, and blocked or bounced in tunnels, under bridges and between tall buildings. Corrected GPS (RTK) can reach centimetres, but only with a good view of the sky.
  • Wheel odometry: speed from the wheel sensors. Smooth and fast, but slightly wrong when tyres wear or slip.
  • IMU (inertial measurement unit): a gyroscope for turning rate and accelerometers. Very fast, but with small biases.

Adding up wheel speed and turning rate over time is dead reckoning. It is smooth and never jumps, but every small error is added up forever, so it drifts: on our tracks it is tens of metres off after one lap. GPS never drifts, but it is noisy and sometimes missing. The two have opposite weaknesses, so combining them gives something better than either. The Kalman filter is the standard way to do it.

Beginner

Beliefs as bell curves

A filter does not keep one position; it keeps a belief: a best guess plus how unsure it is. A Kalman filter uses a Gaussian (bell curve) with mean xx and variance PP. Then it repeats two steps:

  • Predict: move the belief using the motion (from odometry). Moving adds uncertainty, so the bell curve gets wider.
  • Update: when a measurement arrives, combine it with the prediction. Combining two pieces of information makes the curve narrower.
Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Intermediate · Maths

Beliefs as bell curves: the maths

In one dimension, with motion uu over a step, process noise QQ and a measurement zz with noise RR:

predict:x←x+u Δt,P←P+Q \text{predict:}\quad x \leftarrow x + u\,\Delta t, \qquad P \leftarrow P + Q
update:K=PP+R,x←x+K (z−x),P←(1−K) P \text{update:}\quad K = \frac{P}{P + R}, \qquad x \leftarrow x + K\,(z - x), \qquad P \leftarrow (1 - K)\,P

The Kalman gain KK is the heart of it. If the prediction is very unsure (P≫RP \gg R), KK is close to 1 and the filter mostly believes the measurement. If the measurement is very noisy (R≫PR \gg P), KK is close to 0 and it mostly keeps its prediction. The new estimate is a weighted average, weighted by how much each source can be trusted. Under the filter's assumptions (linear motion, Gaussian noise) no other method does better.

Try it

Try it: one dimension

A car drives along a straight road. Its wheel-speed sensor is noisy and reads 2% high; a GPS fix arrives once a second. The top chart shows each method's error and the filter's own idea of its uncertainty (±2σ). Make Q tiny and the filter becomes too sure of itself: its error leaves the dashed band, and it ignores GPS. Make it large and it follows every noisy GPS fix.

Interactive: this part runs in your browser.

Code

Code: a Kalman filter in one dimension

This runs in your browser. Try setting the 0.2 in Q to 0.01: the filter claims ±0.4 m while really being several metres off. A filter that is overconfident is dangerous, because the planner trusts it.

Python · NumPy
import numpy as np

rng = np.random.default_rng(1)
dt, steps = 0.1, 600                       # 60 seconds, 10 updates per second

# The truth: a car on a straight road that speeds up and slows down.
true_v = 12 + 3 * np.sin(np.arange(steps) * dt / 6)
true_x = np.cumsum(true_v * dt)

# The sensors: wheel speed every step (noisy, and 2% high: worn tyres), GPS once a second (noisy, no drift).
odo_v = true_v * 1.02 + rng.normal(0, 0.5, steps)
gps = {k: true_x[k] + rng.normal(0, 4.0, 1)[0] for k in range(9, steps, 10)}

x, P = 0.0, 1.0                            # our belief: position x, with variance P (we start at 0, nearly sure)
Q = (0.5 * dt) ** 2 + 0.2 ** 2           # variance added per step: the speed noise, plus room for errors we cannot model
R = 4.0 ** 2                               # GPS variance
dead, est, gps_only, last_gps = 0.0, [], [], 0.0
for k in range(steps):
    x = x + odo_v[k] * dt                   # predict: move by the measured speed ...
    P = P + Q                               # ... and become less sure
    dead += odo_v[k] * dt                   # dead reckoning: the same prediction, but never corrected
    if k in gps:
        K = P / (P + R)                     # Kalman gain: between 0 (ignore GPS) and 1 (believe only GPS)
        x = x + K * (gps[k] - x)            # update: move part of the way towards the measurement
        P = (1 - K) * P                     # and become more sure
        last_gps = gps[k]
    est.append(x)
    gps_only.append(last_gps)

err = lambda a: np.sqrt(np.mean((np.array(a) - true_x) ** 2))
print(f"dead reckoning: error {err(np.cumsum(odo_v * dt)):.1f} m (and {abs(dead - true_x[-1]):.1f} m at the end)")
print(f"GPS only:       error {err(gps_only):.1f} m")
print(f"Kalman filter:  error {err(est):.1f} m")
print(f"final gain K = {K:.2f}, final uncertainty ±{np.sqrt(P):.1f} m")
Open in playground ↗
Intermediate · Maths

More dimensions, and curves: the extended Kalman filter

The car's state has three numbers, x=(x,y,θ)\mathbf{x} = (x, y, \theta), and the uncertainty is a 3 × 3 covariance matrix PP (the off-diagonal terms say how errors are linked: a heading error soon becomes a sideways position error). The equations keep the same shape, with matrices:

predict:x←f(x,u),P←FPF⊤+Q \text{predict:}\quad \mathbf{x} \leftarrow f(\mathbf{x}, \mathbf{u}),\qquad P \leftarrow F P F^\top + Q
update:K=PH⊤(HPH⊤+R)−1,x←x+K (z−h(x)),P←(I−KH) P \text{update:}\quad K = P H^\top (H P H^\top + R)^{-1},\qquad \mathbf{x} \leftarrow \mathbf{x} + K\,(\mathbf{z} - h(\mathbf{x})),\qquad P \leftarrow (I - K H)\,P

The motion of a car is not linear: x←x+vcos⁡θ Δtx \leftarrow x + v\cos\theta\,\Delta t contains a cosine. The extended Kalman filter (EKF) handles this by using the exact nonlinear function to move the estimate, and its Jacobian (the matrix of first derivatives) to move the uncertainty:

F=∂f∂x=(10−vsin⁡θ Δt01vcos⁡θ Δt001) F = \frac{\partial f}{\partial \mathbf{x}} = \begin{pmatrix} 1 & 0 & -v\sin\theta\,\Delta t \\ 0 & 1 & v\cos\theta\,\Delta t \\ 0 & 0 & 1 \end{pmatrix}

GPS measures xx and yy but not the heading, so H=(100010)H = \begin{pmatrix}1&0&0\\0&1&0\end{pmatrix}. Yet the filter still corrects the heading: through the off-diagonal terms of PP it learns that "I keep ending up to the left of the GPS" means "my heading is off". Nobody measures heading directly; the filter infers it.

The EKF works well when the uncertainty is small enough for the curve to look straight over it. When it is not, the unscented Kalman filter (which pushes a few sample points through the exact function) or the particle filter of the next topic do better.

Try it

Try it: through the tunnel

The car drives a lap with the autopilot while a filter estimates its position from noisy wheel speed, a biased gyroscope and GPS. The ring around the estimate is the filter's ±2σ uncertainty. Watch it grow in the tunnel, where only dead reckoning is possible, and snap back when GPS returns. The grey line is pure dead reckoning.

Interactive: this part runs in your browser.

Code

Code: an EKF with a GPS outage

The same filter in Python, on a car driving circles. Try removing the tunnel, or doubling the gyroscope bias.

Python · NumPy
import numpy as np

rng = np.random.default_rng(2)
dt, steps = 0.1, 900                                  # 90 seconds

# The truth: a car driving round a 40 m circle at 10 m/s, then a gentler bend.
w_true = np.where(np.arange(steps) < 450, 10 / 40, -10 / 80)       # yaw rate (rad/s)
th = np.cumsum(w_true * dt)
xy = np.cumsum(np.stack([10 * np.cos(th), 10 * np.sin(th)], 1) * dt, 0)

# The sensors. Wheel speed: noisy, 2% high. Gyro: noisy, with a small constant bias.
v_meas = 10 * 1.02 + rng.normal(0, 0.3, steps)
w_meas = w_true + 0.01 + rng.normal(0, 0.02, steps)
# GPS once a second, ±3 m, but nothing from 30 s to 45 s (a tunnel).
gps = {k: xy[k] + rng.normal(0, 3.0, 2) for k in range(9, steps, 10) if not 300 <= k < 450}

def predict(s, P, v, w):
    x, y, a = s
    s_new = np.array([x + v * np.cos(a) * dt, y + v * np.sin(a) * dt, a + w * dt])
    F = np.array([[1, 0, -v * np.sin(a) * dt],      # how a small error in each state grows in one step
                  [0, 1,  v * np.cos(a) * dt],
                  [0, 0, 1]])
    Q = np.diag([0.08, 0.08, 0.005]) ** 2           # what our motion model gets wrong in one step
    return s_new, F @ P @ F.T + Q

H = np.array([[1.0, 0, 0], [0, 1.0, 0]])            # GPS measures x and y, not the heading
R = np.eye(2) * 3.0 ** 2

s, P = np.array([0.0, 0.0, 0.0]), np.diag([1.0, 1.0, 0.01])
dr = s.copy()
err_ekf, err_dr, sd = [], [], []
for k in range(steps):
    s, P = predict(s, P, v_meas[k], w_meas[k])
    dr, _ = predict(dr, P, v_meas[k], w_meas[k])     # dead reckoning: predictions only
    if k in gps:
        y = gps[k] - H @ s                           # the innovation: how far the GPS is from our guess
        S = H @ P @ H.T + R
        K = P @ H.T @ np.linalg.inv(S)
        s = s + K @ y
        P = (np.eye(3) - K @ H) @ P
    err_ekf.append(np.hypot(*(s[:2] - xy[k])))
    err_dr.append(np.hypot(*(dr[:2] - xy[k])))
    sd.append(np.sqrt(P[0, 0] + P[1, 1]))

e, d, sd = np.array(err_ekf), np.array(err_dr), np.array(sd)
print(f"dead reckoning after 90 s: {d[-1]:.1f} m off")
gps_err = np.mean([np.hypot(*(g - xy[k])) for k, g in gps.items()])
print(f"before the tunnel: EKF {e[:300].mean():.1f} m on average; a single GPS fix is {gps_err:.1f} m off on average")
print(f"in the tunnel: worst {e[300:450].max():.1f} m; the filter's own uncertainty grew to ±{sd[449]:.1f} m")
print(f"10 s after the tunnel: {e[550]:.1f} m")
Open in playground ↗

Challenge: the gyroscope bias makes the heading drift in the tunnel. Add the bias as a fourth state, bb, with θ←θ+(ω−b) Δt\theta \leftarrow \theta + (\omega - b)\,\Delta t and b←bb \leftarrow b. Work out the new 4 × 4 Jacobian. The filter will learn the bias while GPS is available and use it in the tunnel. Real cars estimate many such biases this way.

Advanced

Tuning: Q and R

  • R is how noisy the measurements are. It can usually be measured: park the car and look at how the GPS wanders.
  • Q is how wrong the motion model is in one step. It covers everything the model leaves out: slip, bumps, biases. It is harder to know and is usually tuned.
  • The test of a good tuning is consistency: the real error should fall inside the filter's ±2σ about 95% of the time. If it is outside much more often, the filter is overconfident and will ignore good measurements.
  • Bad measurements happen (a GPS fix bounced off a building). Filters check each measurement against the prediction first, and reject it if it is too unlikely (gating).
  • Rounding errors can make PP invalid (negative variances) over many updates; real code uses a more stable form of the update (the Joseph form), as the simulator does.
Check yourself

Quiz

1. What happens to the uncertainty in the predict step?

2. If the measurement noise R is much larger than the prediction's uncertainty P, the Kalman gain is…

3. Why does dead reckoning drift?

4. What does the "extended" in extended Kalman filter handle?

5. GPS measures only position. How does the filter correct the heading?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready