Particle Filters: Localising Against a Map
When the car could be in several places at once, a single bell curve is not enough. Represent the belief with thousands of guesses, move them, weigh them by how well they explain what the car sees, and resample. Localise from scratch against a map of known poles, and recover when the car is "kidnapped".
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.OpenIn plain words
Imagine waking up somewhere unknown with a map. You make thousands of guesses of where you could be, then look around: a lamp post 12 m ahead and a bin to the left. Guesses that match what you see survive, the rest are dropped, and soon all the guesses gather in one place. That is a particle filter.
By the end of this topic you will be able to explain how a car finds itself on a map from scratch, and recovers when it gets lost.
Start with: the demo Try it: localise from scratch.
When one bell curve is not enough
The Kalman filter assumes the belief is one bell curve: one best guess with some spread. That breaks in situations that matter:
- Global localisation: the car is switched on and has no idea where it is. The belief should be spread over the whole map.
- Ambiguity: two junctions look alike. The belief should have two peaks until something tells them apart.
- Recovery: the estimate is badly wrong (the "kidnapped robot" problem). A Kalman filter that is sure of the wrong place will never consider the right one.
A particle filter represents the belief with many samples, called particles. Each particle is one full guess, . Where particles are dense, the car is likely to be. Any shape of belief is possible, including several peaks. Used for localisation, it is called Monte Carlo localisation (Dellaert, Fox, Burgard and Thrun, 1999).
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.
Move, weigh, resample
- Move: apply the measured motion to every particle, each with its own random noise. The cloud spreads, like the predict step.
- Weigh: when the sensors see something, ask each particle: "if the car were here, how likely is this observation?" A particle that would see the pole 12 m ahead, when the sensor says 12 m, gets a high weight; one that would see it 40 m away gets almost none. With range and bearing measured, and what particle expects:
- Resample: draw a new set of particles, picking each with probability proportional to its weight. Good guesses are copied; bad ones die out. This is natural selection for guesses.
Practical details that make it work:
- Work in logarithms: multiplying many small likelihoods underflows to zero; add log-weights instead.
- Resample only when needed: the effective number of particles, (with weights summing to 1), says how many particles really carry weight. Resample when it drops below half.
- Systematic resampling: one random number and evenly spaced picks; less random than drawing each particle independently.
- Particle deprivation: after resampling, all particles may be copies of a few, near the wrong place. A little jitter after resampling, a slightly wider sensor model than the real one, and a few fresh random particles let it recover.
Landmarks and data association
Our car sees poles with known positions on its map: the range and bearing to each pole within 30 m. In this simulator each pole has an ID, so the car knows which pole it sees. Real landmarks are not labelled: matching each observation to a map landmark is the data association problem, and a wrong match can be worse than no measurement. Real cars localise by matching a whole lidar scan or camera image against a detailed prior map (for example with ICP or NDT scan matching), which avoids matching single landmarks.
Notice why the poles stand at uneven distances from the road. If every stretch of road looked the same, no sensor could tell the stretches apart, and the particles would rightly stay spread over all of them.
Try it: localise from scratch
Pink dots are particles, white squares the poles, and the lines show which poles the car sees. Start with anywhere on the roads and watch the cloud collapse onto the car within a few seconds. Then press Kidnap the car. With random particles switched off, the filter may stay sure of the wrong place; with them on, it recovers. Try 200 particles too.
Interactive: this part runs in your browser.
Code: a particle filter
The car drives round a circle among eight poles, starting with no idea where it is. Watch the printout: it can lock onto the wrong place for a while, then the random particles find the truth.
import numpy as np
rng = np.random.default_rng(3)
dt, steps, N = 0.1, 300, 5000 # 30 seconds, 5000 particles
SR, SB = 1.5, 0.1 # the noise we *assume* in weighting: wider than the real sensor (0.5 m, 0.03 rad), so that
# particles that are close, but not exact, survive
# The truth: a car going round a 40 m circle. Poles with known positions stand around it.
th_true = np.arange(steps) * dt * 10 / 40 + np.pi / 2
xy_true = np.stack([40 * np.cos(th_true - np.pi / 2), 40 * np.sin(th_true - np.pi / 2)], 1)
poles = np.array([[52, 5], [30, 45], [-8, 54], [-47, 30], [-55, -12], [-25, -50], [12, -58], [45, -32]]) # irregular: a
# perfectly symmetric layout would look the same from several places
def observe(x, y, a):
"""Range and bearing to every pole within 30 m (the bearing is measured from the car's heading)."""
d = poles - [x, y]
r = np.hypot(d[:, 0], d[:, 1])
b = np.arctan2(d[:, 1], d[:, 0]) - a
seen = np.where(r < 30)[0]
return [(j, r[j] + rng.normal(0, 0.5), b[j] + rng.normal(0, 0.03)) for j in seen]
# We have no idea where we start: particles anywhere in a 140 m square, facing any way.
p = np.column_stack([rng.uniform(-70, 70, N), rng.uniform(-70, 70, N), rng.uniform(-np.pi, np.pi, N)])
logw = np.zeros(N)
w = np.ones(N) / N
for k in range(steps):
# 1. move every particle with the measured speed and yaw rate, plus its own random noise
v = 10 + rng.normal(0, 0.3, N)
om = 0.25 + rng.normal(0, 0.03, N)
p[:, 0] += v * np.cos(p[:, 2]) * dt
p[:, 1] += v * np.sin(p[:, 2]) * dt
p[:, 2] += om * dt
# 2. weigh each particle by how well it explains what the car sees (5 times a second)
if k % 2 == 0:
for j, r, b in observe(*xy_true[k], th_true[k]):
d = poles[j] - p[:, :2]
pr = np.hypot(d[:, 0], d[:, 1])
pb = np.arctan2(d[:, 1], d[:, 0]) - p[:, 2]
db = np.angle(np.exp(1j * (pb - b))) # angle difference, wrapped to ±π
logw += -0.5 * ((pr - r) / SR) ** 2 - 0.5 * (db / SB) ** 2
w = np.exp(logw - logw.max()) # work in logs: products of tiny numbers underflow to 0
w /= w.sum()
# 3. resample when most of the weight sits on a few particles
if 1 / np.sum(w ** 2) < N / 2:
pos = (rng.random() + np.arange(N)) / N # systematic resampling
p = p[np.searchsorted(np.cumsum(w), pos).clip(0, N - 1)]
p += rng.normal(0, [0.2, 0.2, 0.01], (N, 3)) # a little jitter, so copies of one particle spread out
m = N // 50 # and 2% fresh random guesses, so that a filter that
p[:m] = np.column_stack([rng.uniform(-70, 70, m), rng.uniform(-70, 70, m), rng.uniform(-np.pi, np.pi, m)])
# locked onto the wrong place can still recover
logw = np.zeros(N)
w = np.ones(N) / N
if k + 1 in (5, 10, 30, 100, 300):
mean = np.average(p[:, :2], 0, w)
spread = np.sqrt(np.average(((p[:, :2] - mean) ** 2).sum(1), weights=w))
print(f"after {(k + 1) * dt:4.1f} s: estimate {np.hypot(*(mean - xy_true[k])):5.1f} m from the truth, particles spread ±{spread:.1f} m")Kalman or particles?
- Kalman filters are cheap (a few small matrices), smooth and exact for one-peaked beliefs. Most cars use them, or their relatives, to fuse GPS, IMU and odometry.
- Particle filters handle any belief and any sensor model, including "does this lidar scan match the map here?". The cost grows with the number of particles, and in many dimensions you need impossibly many.
- Many systems combine them: a particle filter or scan matcher finds where the car is on the map, and a Kalman filter fuses that with the fast motion sensors.
Quiz
1. What does each particle represent?
2. What does resampling do?
3. Why add a few random particles after resampling?
4. Weights are 0.5, 0.5, 0, 0 (four particles). What is the effective number of particles?
5. Why can a Kalman filter not do global localisation well?
📚 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.
- Dellaert, Fox, Burgard & Thrun (1999): Monte Carlo Localization for Mobile Robots ↗ the particle filter for localisation
- Thrun, Burgard & Fox: Probabilistic Robotics (MIT Press) ↗ the standard textbook on Kalman filters, particle filters and SLAM