Scatter 2,000 guesses of the robot's pose over a known map. Each laser scan removes the guesses that disagree, and the cloud closes on the robot. Pick the robot up and put it down elsewhere: plain MCL stays lost, augmented MCL finds it again in a few scans.
Watch the cloud find the robot, then press Kidnap. Try it with plain and with augmented MCL. Then we build, piece by piece, the particle loop, the motion model, two sensor models, resampling, the recovery trick and the adaptive sample size.
You need what a probability is, the Bayes filter idea (predict, then correct) and a little Python. We build the rest from zero.
Lesson 14 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. Previous: Lesson 13, Kalman, EKF and UKF.
Illustrative toy: a 12 m by 7 m office, 12 laser beams, the beam sensor model, 2,000 particles. The purple ring is the estimate: green when it is within 0.3 m and 20° of the robot, red when it is lost. The map matches the true walls exactly.
Chapter 0
Add identical doors to a corridor and watch the single Gaussian give up
Switch a robot on in a long office corridor. Its laser sees a door on the left. The corridor has four identical doors. Where is the robot?
The honest answer: at one of four places, with no reason yet to prefer one. That belief has four peaks. It is multimodal: it has more than one peak.
Lesson 13's Kalman filters carry belief as one Gaussian, a bell with one mean and one spread. A bell has one peak. Ask it to hold four doors and it smears one wide bell over all of them.
The robot sees a door. Purple is the honest belief: one bump at each door. Set the door count, then switch on the best single Gaussian.
Illustrative toy. Each bump has a spread of 0.4 m. The Gaussian has the same mean and variance as the purple belief, which is the best one bell can do.
Work the number for two doors, at 5 m and 15 m. The bell's mean is (5 + 15) / 2 = 10 m. The robot is 5 m from that point, whichever door it is at. The mean names the one place the robot cannot be.
A particle filter drops the bell. It keeps a cloud of guesses, and the cloud can take any shape. Monte Carlo localization (MCL) is a particle filter that finds a robot's pose on a known map.
The symptom is an estimate that jumps to the middle of nowhere when the scene repeats. To measure it, plot the belief over the map, not only its mean. The fix is a belief that can hold several peaks.
Chapter 1
Draw more particles and watch the cloud copy the belief
A particle is one full guess of the robot's state. On a floor, that is a pose: x and y in metres, and the heading θ. The filter keeps M particles, often a few hundred to a few thousand.
Where particles crowd, the belief is high. Where there are none, the belief is zero. The filter never writes a formula for the belief. The cloud is the belief.
The purple line is a two-door belief. The dots are M particles drawn from it; the bars are their histogram. Drag M, then press New draw.
Illustrative toy. The error is half the summed gap between the histogram and the curve: 0 is a perfect copy, 1 shares nothing.
The copy gets better slowly. Sampling error shrinks like 1 / √M: four times the particles halves the error. Every step touches every particle, so cost grows like M.
How do you read one pose off the cloud? Give each particle i a weight: a number that says how much it counts. The weights add to 1. Call particle i's pose x[i] and its weight w[i]. The estimate x̂ is the weighted mean.
x-hat equals the sum over i of w-i times x-i.
Multiply each pose x-i by its weight w-i. Add the M products. With equal weights, x-hat is the plain average.
With made-up numbers: six particles of weight 1/6 at 1.8, 2.0, 2.2, 7.9, 8.0 and 8.1 m. x-hat = 30 / 6 = 5.0 m. The nearest particle is 2.8 m away, so the mean is a lie here.
The symptom is a reported pose in empty space while the cloud looks fine. To measure it, count the particles near the estimate. The fix is to report the heaviest clump: take the weighted mean only of particles near the densest cell. Every map toy on this page does that.
Chapter 2
Step three particles through one full loop and do every number by hand
MCL is the Bayes filter run on a cloud. Each cycle has three beats.
Three particles sit at 2, 5 and 8 m. Press the three beats in order. The blue bell is the reading "near 6.0 m".
Illustrative toy. The first loop uses the noise draws +0.3, −0.2 and +0.1 m so the numbers match the text; later loops draw fresh noise.
The weight is the heart of it. Name the parts. Call the scan at time t zt. Call particle i's pose after the predict step x̄t[i]. Call the map m.
w-i equals p of z-t given x-bar-t-i and m.
Put the robot at particle i's pose x-bar on map m. Ask how likely the real scan z-t is from there. That likelihood is the weight w-i. Chapters 4 and 5 compute it.
With made-up numbers: predicted particles at 3.3, 5.8 and 9.1 m; the reading says 6.0 m with a spread of 1.0 m. Weights e−d²/2 for gaps d of 2.7, 0.2, 3.1: 0.026, 0.980, 0.008. Divide by their sum, 1.015: 0.026, 0.966, 0.008.
Resampling then draws three new particles with those odds. Almost surely all three are copies of the particle at 5.8 m. The cloud has moved to the reading.
The symptom is a cloud that slides as one rigid block and never spreads. To measure it, print the spread of the cloud before and after predict. The cause is one noise draw shared by all particles. The fix is M independent draws.
Chapter 3
Send 300 particles through one wheel reading and watch the banana form
The wheel encoders report odometry: how far the robot thinks it drove and turned. Wheels slip, so the report is close but wrong. The predict step must spread each particle by about as much as the report can be wrong.
The odometry motion model splits any move into three parts: turn, drive straight, turn. Call the first turn δrot1, the distance δtrans and the last turn δrot2. Each particle draws its own noisy copy of each part, written with a hat: δ̂.
x-prime equals x plus delta-hat-trans times the cosine of theta plus delta-hat-rot-one. y-prime is the same with the sine. theta-prime equals theta plus delta-hat-rot-one plus delta-hat-rot-two.
Turn the particle by its own first turn delta-hat-rot-one. Drive it its own distance delta-hat-trans along that heading. Turn it by its own last turn delta-hat-rot-two.
With made-up numbers: a particle at (2.0, 1.0, 0); odometry says turn 0.3 rad, drive 1.0 m, turn −0.1 rad. With no noise, x′ = 2 + 1.0 × cos 0.3 = 2.955 m, y′ = 1 + 1.0 × sin 0.3 = 1.296 m, θ′ = 0.2 rad.
How big is the noise? Four numbers set it, α1 to α4: how much error each kind of motion adds. The distance error has variance σtrans²:
σtrans² = α3 δtrans² + α4 (δrot1² + δrot2²)
Take α3 = 0.04 and α4 = 0.01 for the move above. The variance is 0.04 × 1 + 0.01 × (0.09 + 0.01) = 0.041, so the distance is off by about √0.041 = 0.20 m. The turns use α1 and α2 the same way. Big moves add big noise.
All 300 particles start at the teal pose. Pick a move, set the two noise knobs, then press Move again to chain moves.
Illustrative toy with α2 = 0.02 and α4 = 0.01 fixed. The warm arrow is where the odometry says the robot went.
Turn noise bends the cloud into a banana: an arc around the start. A small heading error grows into a big sideways error the farther the robot drives.
The symptom is a cloud that loses the robot on a slippery floor. To measure it, drive a known square and compare the odometry end pose with the truth. If the truth falls outside the banana, the αs are too small. The fix is to raise them until the true pose sits inside the cloud.
Chapter 4
Move a reading along one beam and see which part of the model catches it
One laser beam leaves a particle's pose. On the map, it should hit a wall at the expected range z*. The filter finds z* by ray casting: it walks the beam across the map until it meets a wall.
A real reading is not always near z*. A person steps in front, so the beam returns short. Glass swallows the beam, so it reports the maximum range. A plain bell around z* would score these readings near zero and kill a correct particle.
The beam model mixes four shapes. Call the reading on beam k zk. Call each shape's share c; the four shares add to 1.
p of z-k given x and m equals c-hit times p-hit, plus c-short times p-short, plus c-max times p-max, plus c-rand times p-rand.
Ray cast to get z*. Score the reading z-k with each of the four shapes. Mix the four scores by their shares c. Multiply over all beams for the particle's weight.
With made-up numbers: z* = 4.0 m, σhit = 0.2 m, λ = 0.5 per m, zmax = 8 m, shares 0.80, 0.10, 0.05, 0.05. A reading of 4.1 m: phit = 1.760, prand = 0.125, total 0.80 × 1.760 + 0.05 × 0.125 = 1.41. A person at 2.0 m: phit is about 4 × 10−22, pshort = 0.213, total 0.10 × 0.213 + 0.05 × 0.125 = 0.028.
The good reading counts 51 times more than the person, but the person does not zero the particle. One stray beam out of twelve costs a factor, not the whole weight.
The purple line is the expected range from the map. The height axis is logarithmic. Move the blue reading and the expected range, then switch to Bell only.
Illustrative shares and spreads, the same as the worked numbers. We draw the spike at 8 m as a bar; in code it is a narrow box.
The symptom is a filter that loses the robot whenever people walk past. To measure it, log the weight of the best particle per scan; it crashes when a person enters. The fix is a real cshort and crand, often learned from logged scans.
Chapter 5
Shift a particle off the true pose and watch its beam endpoints leave the walls
Ray casting is slow: 1,000 particles times 12 beams is 12,000 walks across the map, every scan. The likelihood field model skips the walk.
It places each beam's endpoint from the particle's pose, at the measured range. If the particle is right, the endpoints land on walls. Before the robot moves, the filter fills a distance table: for every map cell, the distance to the nearest wall. Scoring an endpoint is then one table lookup.
Call the distance from beam k's endpoint to the nearest wall dk. Call the pose's score q.
q equals the product over k of: c-hit times N of d-k with spread sigma, plus c-rand over z-max.
For each beam, place the endpoint and look up its distance d-k to the nearest wall. Score it with the bell, plus the floor. Multiply the factors; in code, add their logs so the product never rounds to zero.
With made-up numbers: σ = 0.2 m, three endpoints at 0.05, 0.10 and 0.80 m from walls. Factors 1.753, 1.597, 0.0131; q = 0.037. Three endpoints at 0.05 m give q = 5.38, 147 times more. On the far endpoint the floor does the work: the bell alone gives 0.0006, twenty times less.
Purple shading is the distance table: bright on walls, dark in open space. The filter places the real scan at the purple particle's pose. Shift and turn it, and watch the endpoints.
Illustrative toy: 12 beams, σ = 0.2 m, chit = 0.9, crand = 0.1, a 0.1 m distance table. Solid dots score well; hollow dots sit in open space.
The price: the field ignores what lies between the robot and the endpoint. A beam that passes through a wall on the map still scores well if it ends near another wall. In our toy office we kidnapped the robot in 20 seeded runs, with augmented MCL. The field found it again within 40 scans in 15 runs; the beam model did in all 20.
The symptom is a confident cloud in the wrong room of a building with repeated rooms. To measure it, compare the scores of the true pose and the mirror pose. The fix is the beam model for global localization, or more beams.
Chapter 6
Sweep a comb over the weights, then count how many particles still matter
Five particles predict the range to the wall ahead: 4.2, 3.5, 5.5, 4.0 and 1.0 m. The laser reads 4.0 m, with a spread of 1.0 m.
| Particle | Predicted range | Raw weight | Normalized |
|---|---|---|---|
| 1 | 4.2 m | 0.980 | 0.307 |
| 2 | 3.5 m | 0.882 | 0.276 |
| 3 | 5.5 m | 0.325 | 0.101 |
| 4 | 4.0 m | 1.000 | 0.313 |
| 5 | 1.0 m | 0.011 | 0.003 |
Each raw weight is e−d²/2 for the gap d. Raw weights are likelihoods; they sum to 3.198, not 1. Normalizing divides each by the sum, so the weights become chances that add to 1. Resampling needs chances.
Low-variance resampling lays the normalized weights end to end on a ruler of length 1. It draws one random start r between 0 and 1/M, then places M comb teeth 1/M apart. Each tooth copies the particle whose segment it lands in.
Each segment of the ruler is one particle's weight. Press Resample a few times in each mode and compare the copy counts.
The five weights are the table's. The comb gives each particle either the whole number below or above M times its weight. Independent draws can give any count.
With r = 0.12 and M = 5, the teeth fall at 0.12, 0.32, 0.52, 0.72 and 0.92. The running sums are 0.307, 0.582, 0.684, 0.997 and 1. The new cloud is particles 1, 2, 2, 4, 4. Particle 5 is gone.
Resampling also destroys variety: copies are not new guesses. So resample only when the weights are lopsided. The effective sample size Neff counts how many particles carry the belief.
N-eff equals one over the sum over i of w-i squared.
Square each normalized weight w-i. Add the squares. One over that sum is N-eff. Resample only when N-eff falls below M / 2.
The table's weights: 0.307² + 0.276² + 0.101² + 0.313² + 0.003² = 0.278. N-eff = 1 / 0.278 = 3.6, above M / 2 = 2.5. An adaptive filter skips this resample. Weights 0.92, 0.05, 0.02, 0.01, 0 give N-eff = 1.18: resample.
The symptom is a cloud of a few clones that cannot follow the robot. To measure it, log N-eff and the count of distinct poses. The fix is to resample only below M / 2. The predict step's noise then pulls the clones apart again.
Chapter 7
Kidnap the robot and watch the lost alarm decide how many fresh guesses to inject
The course splits localization into three problems.
| Problem | Start pose | Right filter |
|---|---|---|
| Position tracking | known; small drift | a Gaussian filter is enough (Lesson 13) |
| Global localization | unknown | MCL, with particles scattered over the whole map |
| Kidnapped robot | known, then silently wrong | MCL plus a way to recover |
Plain MCL fails the third. After it converges, every particle sits at the old pose. Someone carries the robot away. Resampling can only copy poses the cloud already holds, so it copies the wrong cluster forever.
Augmented MCL replaces some resampled particles with random poses. It decides how many with a lost alarm. Call the average raw weight of this scan wavg. The filter keeps a slow average wslow and a fast average wfast of it, with rates αslow < αfast:
wslow ← wslow + αslow (wavg − wslow), and wfast the same with αfast
p-inject equals the max of zero and one minus w-fast over w-slow.
Divide the recent score w-fast by the usual score w-slow. If recent scans score as usual, the ratio is about 1 and nothing is injected. If they score far worse, inject random poses in proportion.
With made-up numbers: αfast = 0.1, αslow = 0.001, both averages at 0.020. A kidnap drops wavg to 0.002. After one scan wfast = 0.0182 and wslow = 0.0200: p-inject = 0.09. After ten scans, 0.0083 and 0.0198: p-inject = 0.58.
Press Run and let the cloud converge, then Kidnap. The strip below plots w-fast (solid), w-slow (dashed) and p-inject (purple area).
Illustrative toy with faster rates, αfast = 0.5 and αslow = 0.05, so the alarm fits a short demo. The averages use the per-beam likelihood.
We ran our office toy 20 times with 2,000 particles and the beam model. Augmented MCL found the kidnapped robot every time, within 1 to 16 scans. Plain MCL found it in none of them within 40 scans.
The symptom is a confident estimate while every scan disagrees with the map. To measure it, watch w-fast against w-slow. The fix is augmented MCL; tune αfast so one person walking past does not fire the alarm.
Chapter 8
Let the cloud count its own occupied cells and choose how many particles it needs
A lost robot needs thousands of particles to cover the map. A found robot needs a hundred or two. A fixed M wastes work for most of the run. KLD sampling picks M fresh at every resample.
The idea: chop the pose space into bins, here 0.5 m by 0.5 m by 45°. Draw particles one at a time. Count the bins that hold at least one particle; call that count k. The more bins the belief covers, the more particles it needs. Stop when the count n reaches a bound.
Two knobs set the bound. ε is the error you accept between the sampled and the true belief. δ is the chance you allow of missing that target. z1−δ is the matching point of the standard bell: 2.326 for δ = 0.01.
n equals k minus one over two epsilon, times the cube of: one, minus two over nine times k minus one, plus the square root of two over nine times k minus one, times z-one-minus-delta.
Each time a new particle opens a new bin, raise k and recompute n. Keep drawing until the draw count reaches n. For large k, n grows about like k / (2 epsilon).
With ε = 0.05 and z = 2.326: k = 10 bins gives n = 217. k = 100 gives n = 1,347. k = 1,000 gives n = 11,059.
Shaded squares hold at least one particle. Press Run, then Kidnap, and watch n in the strip. Change ε to move the bound.
Illustrative toy: augmented MCL plus KLD sampling, at least 150 and at most 2,400 particles, the beam model. The bins on the map ignore heading; the count uses all three axes.
In our toy a found robot holds about 2 to 10 bins, so n sits at or near the floor of 150. A kidnap fills hundreds of bins with injected guesses, and n jumps toward the 2,400 cap.
The symptom is a cloud that shrinks to the floor and then loses the robot on the next turn. To measure it, log n and k per scan. The fix is a higher floor or a smaller bin; a coarse bin makes k tiny and n too small.
Chapter 9
Drive the robot yourself with every part of the lesson switched on or off
Every part now runs in one loop. The odometry model predicts and a sensor model weights. The comb resamples when N-eff drops. Augmented MCL watches for a kidnap, and KLD sampling can size the cloud. Drive the robot and break things.
Drive with the arrows, or press Auto. Switch the sensor model, add a person the map does not know, then kidnap the robot.
Illustrative toy. The robot's wheels report odometry with small errors; the motion knob scales the filter's αs. The person walks the corridor and is not on the map. M applies on Scatter when KLD is off.
Things to try, each tied to a chapter:
The real thing is the same loop. The ROS amcl package is adaptive MCL: it uses KLD sampling and the augmented recovery, on an occupancy grid with a laser.
Chapter 10
Keep the terms, the numbers, the code and the next steps in one place
MCL keeps a cloud of poses on a known map. Each scan it predicts with the odometry model, weights with a sensor model, and resamples when N-eff drops. Augmented MCL injects random poses when scans stop matching, and KLD sampling sizes the cloud.
| Term | Meaning | Number to remember |
|---|---|---|
| Particle | one guess of the pose (x, y, θ) | error falls like 1 / √M |
| Estimate | x̂ = Σ w[i] x[i], of the heaviest clump | two clumps at 2 and 8 m: mean 5 m, wrong |
| Weight | w[i] = p(zt | x̄t[i], m) | 3.3, 5.8, 9.1 vs 6.0: 0.026, 0.966, 0.008 |
| Odometry model | turn, drive, turn, each with own noise | 1 m move: distance off by about 0.20 m |
| Beam model | hit + short + max + rand mixture | 4.1 m read: 1.41; person at 2.0 m: 0.028 |
| Likelihood field | score endpoints by distance to wall | 0.05, 0.10, 0.80 m: q = 0.037 |
| Neff | 1 / Σ w²; resample below M / 2 | table weights: 3.6 of 5 |
| Augmented MCL | pinject = max(0, 1 − wfast / wslow) | ten bad scans: 0.58 |
| KLD sampling | n from the occupied bin count k | ε 0.05: 10 bins 217, 100 bins 1,347 |
| Property | Kalman, EKF, UKF | MCL |
|---|---|---|
| Belief shape | one bell | any shape, many peaks |
| Global localization | no | yes |
| Kidnap recovery | no | yes, with injection |
| Cost | small matrices, fixed | grows with M |
| State size | scales to many dimensions | a few: 3 for a floor pose; cost grows about 10 times per extra dimension at a fixed spacing |
python def mcl_step(P, logw, odom, scan, grid): # w_slow, w_fast kept between calls P = sample_odometry(P, odom, alpha) # predict: own noise per particle logw = logw + scan_loglik(P, scan, grid) # weight: beam or likelihood field top = logw.max(); w = np.exp(logw - top) # subtract the max: no underflow w_avg = np.exp(top) * w.mean() # average raw likelihood, for the alarm w /= w.sum() # normalize w_slow += a_slow * (w_avg - w_slow); w_fast += a_fast * (w_avg - w_fast) if 1 / np.sum(w**2) < len(P) / 2: # N_eff gate P = low_variance_resample(P, w) p_inj = max(0.0, 1 - w_fast / w_slow) # augmented MCL lost = np.random.rand(len(P)) < p_inj P[lost] = random_free_poses(lost.sum(), grid) logw = np.full(len(P), -np.log(len(P))) return P, logw
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's particle filter and Monte Carlo localization lesson in our own words, devices and toy numbers. The motion and sensor models, augmented MCL and KLD sampling follow Thrun, Burgard and Fox, Probabilistic Robotics (2005), and Fox, "Adapting the Sample Size in Particle Filters Through KLD-Sampling" (2003).
Now press Present or Teach and explain from memory: the three beats, the banana, the four parts of the beam model and the lost alarm. Then go back to the hero, kidnap the robot with plain MCL, and say why it stays lost.