A robot in a hallway of identical doors cannot place itself from one reading. Fuse nine noisy door-or-wall readings over time, and its belief in the true cell climbs from 1 in 16 to 0.94.
Press Step and watch the bars gather on the robot. Then switch to Latest reading only and see that guess stay spread out. Then we build, piece by piece, the belief, the predict step, the update step, and the loop inside every filter you will meet.
You need what a probability is and a little Python. We build the rest from zero.
Lesson 4 of 22 in Sensor Fusion: Classical to Modern. The filter follows Thrun, Burgard and Fox, Probabilistic Robotics (2005), Chapter 2. Next: The Kalman Filter.
Illustrative toy: a looped hallway of 16 cells with 7 doors. The detector is right 90% of the time, and the motion model allows a 5% slip and a 5% overshoot. In this demo the robot never slips and the detector never lies, so the run repeats exactly.
Chapter 0
See why one reading cannot place the robot, and why a sequence of readings can
A robot rolls along a hallway that loops back on itself. The hallway has 16 cells, and 7 of them have a doorway. The doors all look the same. The robot carries one sensor that looks sideways and reports "door" or "wall".
Someone switched it on somewhere. Where is it? One reading cannot say: "door" fits all 7 door cells. The robot must combine readings taken at different places, and it moves between them.
Teal cells are where the robot could be now. Press Step: the robot moves one cell and reads. Every start that would have given a different reading drops out.
Illustrative toy with a perfect sensor and perfect wheels. The same 16-cell map as the hero.
Start the robot at cell 3 and it reads door, wall, wall, door, door. After five readings only one start fits. The pattern of doors works like a fingerprint. But a real sensor lies and real wheels slip, so crossing out is too harsh. The tempting shortcuts fail too:
| Shortcut | Why it fails | What the filter does |
|---|---|---|
| Trust the latest reading | "door" fits 7 cells, and one lie sends you anywhere | keeps a probability for every cell |
| Average the readings | the robot moved between readings, and "door" is not a number | moves the probabilities with each step |
| Score every path | 3 possible moves a step gives 3 to the 30, about 2 × 1014, paths after 30 steps | folds all history into 16 numbers |
The recursive Bayes filter keeps one probability per cell and updates them each time the robot moves or reads. Every filter in this series, Kalman and particle included, runs this loop with a different way to store the numbers.
Chapter 1
Store what the robot knows as a list of numbers that add to 1
The filter does not store one guess. It stores a belief: one probability for every cell the robot could be in. Call the belief for cell x bel(x). The shape of the list tells you what the robot knows.
| Shape | Means | Example over 8 cells |
|---|---|---|
| Flat | no idea where it is | 0.125 in every cell |
| One spike | sure of one cell | 0.9 on cell 2, 0.1 on cell 3 |
| Several peaks | a few candidates, cannot decide | 0.4 on cell 1, 0.4 on cell 4, 0.2 on cell 6 |
One rule always holds. The robot is in some cell, so the probabilities of all cells add to exactly 1.
The sum over x of bel of x equals one.
Read the probability bel(x) of every cell x and add them. If the total is not 1, the list is not a belief.
With made-up numbers over six cells: 0.05, 0.05, 0.60, 0.20, 0.05, 0.05. The total is 1.00, so it is a belief. The best guess is cell 2 at 0.60, and cell 3 is the runner-up at 0.20.
To repair a list that does not add to 1, normalize it. Add the numbers to get a total S, then divide each number by S. The bars keep their ratios.
Tap a cell to add 0.05 to it. Switch to Remove to take 0.05 away. Watch the total, then press Normalize.
Nothing here forces the rule. The device only shows the total, so you can see a valid list and a broken one.
A single best guess cannot say "cell 1 or cell 4, not elsewhere". A belief can. In a hallway of identical doors that honest ambiguity is the normal state for the first few steps.
The failure: storing only the best guess. Symptom: the robot's position jumps from door to door with full confidence. Measure: ask the estimator how sure it is; a single number cannot answer. Fix: keep the whole list.
Chapter 2
Shift the belief with each move, and spread it because wheels slip
The robot is told "forward one cell". The wheels slip a little, so it does not always move exactly one cell. Counting many real moves gives the motion model: the chance of each real move after one command.
| Real move | Chance | Name |
|---|---|---|
| 0 cells | 0.1 | slip |
| 1 cell | 0.8 | as commanded |
| 2 cells | 0.1 | overshoot |
Start sure of cell 3. After the move, 0.8 of that certainty lands in cell 4, 0.1 stays in cell 3 and 0.1 reaches cell 5. The spike became a hill: the best guess moved forward, and the peak fell from 1.0 to 0.8.
Now the general case. Call the cell the robot came from x′ (x-prime) and the command u. Call the chance that command u takes the robot from x′ to x P(x | x′, u). The belief after the move, before any reading, gets a bar: bel̄(x).
bel-bar of x equals the sum over x-prime of P of x given x-prime and u, times bel of x-prime.
To fill cell x, list every route into it. For each start cell x-prime, multiply the old belief bel(x′) by the chance P(x | x′, u) of that move. Add the routes.
Start from the hill 0.1, 0.8, 0.1 on cells 3, 4, 5 and move again. Cell 5 gets 0.1 × 0.1 from cell 5, 0.8 × 0.8 from cell 4 and 0.1 × 0.1 from cell 3. That is 0.01 + 0.64 + 0.01 = 0.66. The peak fell again, from 0.8 to 0.66.
Pick a start, set how often the wheels slip or overshoot, and press Predict a few times. The faint outline is the belief before the last move.
Illustrative toy. The hallway is a loop of 8 cells: past cell 7 comes cell 0.
Moving shifts the belief and blurs it. Keep moving without a reading and the belief flattens toward 0.125 in every cell: the robot is lost again. This is the drift of Lesson 1, told in probabilities. Each cell hands all of its probability onward, so the total stays 1.
The failure: a motion model sharper than the real wheels. Symptom: the belief stays narrow while the robot drifts away from it. Measure: command 100 known moves and count where the robot lands. Fix: use the counted frequencies, and round toward more blur.
Build the predict step yourself below. The Code Lab uses a straight hallway with an end wall, so probability that overshoots piles up in the last cell.
Chapter 3
Multiply each cell by how well it explains the reading, then rescale the list to 1
Now the robot looks. The door detector makes mistakes, and counting them against known doors and walls gives the measurement model:
| Truth | Says "door" | Says "wall" |
|---|---|---|
| Door cell | 0.8 | 0.2 (missed it) |
| Wall cell | 0.3 (false alarm) | 0.7 |
Take a small loop hallway of 8 cells with doors at cells 1, 4 and 5. The robot knows nothing: 0.125 in each cell. It reads "door". Door cells explain that reading better, so they should gain.
Call the reading z. Call the chance of reading z if the robot were in cell x the likelihood, P(z | x). The belief before the reading is bel̄(x) and the belief after it is bel(x). One rescaling number η (eta) makes the result add to 1.
bel of x equals eta, times P of z given x, times bel-bar of x.
Multiply each cell's belief bel̄(x) by its likelihood P(z | x). Then multiply every product by the same eta, so the list adds to 1.
Reading "door" from the flat 0.125. Door cells: 0.125 × 0.8 = 0.100. Wall cells: 0.125 × 0.3 = 0.0375. With eta = 2.05, door cells end at 0.205 and wall cells at 0.077.
This multiply-then-rescale rule is Bayes' rule. Eta itself comes from the products:
eta equals one over the sum over x of P of z given x times bel-bar of x.
Add the products of all cells to get a total S. Eta is one over S.
Three door cells give 3 × 0.100 = 0.300. Five wall cells give 5 × 0.0375 = 0.1875. S = 0.4875, so eta = 1 / 0.4875 = 2.05. Check: 3 × 0.205 + 5 × 0.077 = 1.00.
Purple cells are doors. Pick a reading and press Update. The dashed outline shows each product before rescaling; the filled bars show the result.
Illustrative toy with the measurement model above. The robot does not move here, so each update reuses the same cells.
Read "wall" from the flat belief instead and the wall cells win: 0.171 each, the doors 0.049 each. A door cell keeps some belief because the detector misses a door 20% of the time.
The failure: the missing divide. Symptom: the total shrinks with every reading, and after many steps the numbers underflow to 0. Measure: assert abs(bel.sum() - 1) < 1e-9 after every step. Fix: divide by S; with many cells and tiny likelihoods, add logarithms instead.
Chapter 4
Measure how far one reading can move the belief, and see why a flaky sensor barely moves it
Take two cells, one door and one wall, with equal belief. How far does one "door" reading move it? The answer depends on the gap between the two likelihoods.
Call the odds of the door cell its belief divided by the wall cell's belief: odds of 1 mean 50/50. Call the odds before the reading Obefore and after it Oafter.
O-after equals P of z given door over P of z given wall, times O-before.
Divide the two likelihoods to get the ratio, and multiply the old odds by it. Eta cancels in a ratio, so there is nothing to rescale. To get a probability back, divide the odds by the odds plus 1.
Our detector's ratio for "door" is 0.8 / 0.3 = 2.67. From odds 1, one reading gives odds 2.67, so the door cell holds 2.67 / 3.67 = 0.727. A flaky detector with 0.55 and 0.45 has ratio 1.22, and the door cell reaches only 0.55.
Set how often the detector says "door" at a door and at a wall. Press Read door a few times and watch the door cell's share.
Illustrative toy. The robot does not move, so each reading is about the same pair of cells.
Each reading multiplies the odds, so evidence stacks up fast. Three "door" readings from our detector give odds 2.67 × 2.67 × 2.67 = 19, a share of 0.950. Three from the flaky detector give 0.646.
If the two likelihoods are equal, the ratio is 1 and the reading moves nothing. The arithmetic ignores a useless sensor with no special case. This is the cousin of weighting by precision in Lesson 3.
The failure: a measurement model surer than the sensor. Symptom: the belief jumps to 0.99 after two readings, then one lie throws it to a wrong cell. Measure: point the detector at 100 known doors and 100 known walls, and count. Fix: use those counts, never the best case on the datasheet.
Chapter 5
Feed each new belief back in, so every past reading lives in one array
Predict on every move. Update on every reading. The belief that comes out of one step goes into the next. That feedback is what recursive means.
Index the steps by t. Call the command at step t ut and the reading zt. Put both steps in one line:
bel-t of x equals eta, times P of z-t given x, times the sum over x-prime of P of x given x-prime and u-t, times bel-t-minus-one of x-prime.
Take last step's belief. Push it through the motion model: that is the inner sum. Multiply by the likelihood of the new reading and rescale with eta. The result is the next step's input.
On the 8-cell loop with doors at 1, 4 and 5: after one "door", door cells hold 0.205. Move: cell 5 collects 0.164 from cell 4, 0.021 from itself and 0.008 from cell 3, so 0.192. Read "door" again: 0.192 × 0.8 = 0.154, the total is S = 0.486, and cell 5 ends at 0.317. Cells 1 and 4 hold 0.148 each.
Only the pair 4 then 5 gives "door, door", so cell 5 pulls ahead by about 2 to 1. The first reading set up the candidates. The second reading, after the move, split them.
Predict moves the robot and blurs the bars. Update reads and sharpens them. The trace under the hallway records the belief on the robot's true cell after each half step.
Illustrative toy: the hero's map, a detector right 90% of the time, and a motion model of 0.1, 0.8, 0.1. The robot never slips and the detector never lies here.
The failure: one half of the loop left out. Symptom: a predict-only filter washes out to flat; an update-only filter forgets the robot moved and keeps belief on cells it has left. Measure: log which step ran at each tick. Fix: call predict on every move and update on every reading, in time order.
Chapter 6
Check the promise that makes one array enough memory, and see it match scoring every path
Why is the current belief enough memory? Because of a promise about the world: once you know the robot's cell now, its earlier path tells you nothing more about the next step. This promise is the Markov assumption.
Call the cell at step t xt. Call the earlier cells x0 to xt−1, and the commands so far u1 to ut.
P of x-t given x-zero through x-t-minus-one and u-one through u-t equals P of x-t given x-t-minus-one and u-t.
Write the chance of the next cell given the whole history. Cross out everything but the last cell x-t-minus-one and the last command u-t. The chance does not change. Readings obey the same rule: a reading depends only on the current cell.
The robot reached cell 4 by two paths, one through cell 2 and one through cell 3. Under the assumption its next move is the same either way: 0.1 to stay in cell 4, 0.8 to cell 5, 0.1 to cell 6.
Slide the number of readings. The outline bars score every start and every slip sequence. The teal bars run the recursive filter. Compare the shapes and the work.
Illustrative toy: the 8-cell loop with doors at 1, 4 and 5, with the models of Chapters 2 and 3. The readings are the ones a robot starting in cell 4 would get.
The two answers match to every digit. Under the Markov assumption the sum over all paths splits into one step at a time. The path count grows 3 times per step; the recursive work grows by the same small amount each step.
The failure: a hidden cause the state leaves out. Say the wheels have a bias, so the robot covers a little more than one cell each move. The next move then depends on that bias, not only on the cell. Symptom: errors with a pattern that tuning does not remove. Measure: check if the gap between each reading and its prediction shows a pattern from step to step. Fix: add the hidden quantity to the state, as the Kalman filter of Lesson 5 adds velocity.
Chapter 7
Fuse a second sensor by running one more update on the same belief
Give the robot a second sensor: a light detector that reads "bright" near a window. It needs no new machinery. Each update multiplies by a likelihood, so two sensors means two multiplications.
Take four cells. The doors are at cells 1 and 3, and only cell 3 has a window. The light detector says "bright" with chance 0.9 at the window and 0.2 elsewhere. Call the two readings zdoor and zlight.
bel of x equals eta, times P of z-light given x, times P of z-door given x, times bel-bar of x.
Multiply each cell's belief by the door likelihood and by the light likelihood. Rescale once with eta. The order of the two multiplications does not matter.
Flat belief 0.25. After "door": 0.364 on cells 1 and 3, 0.136 on cells 0 and 2. After "bright": products 0.027, 0.073, 0.027 and 0.327, total 0.455. Cell 3 ends at 0.72 and cell 1 at 0.16.
Purple cells are doors; the pink mark is the window. Switch each reading on, then swap the order.
Illustrative toy. We assume the two detectors fail on their own, so their likelihoods multiply.
Each update fuses the belief so far, which holds every past reading, with one new reading. That is the two-sensor fuse of Lesson 3, with one sensor replaced by all of history. One operation fuses across sensors within a step and across time between steps.
The failure: two readings that share a cause. If both detectors use one camera, a glare fools both, and the product counts one piece of evidence twice. Symptom: the belief is surer than its hit rate. Measure: compare the claimed probability with how often the best guess is right. Fix: model the shared cause, or use a rule that does not assume independence (Lesson 11).
Chapter 8
Run the whole filter with noisy wheels and a lying sensor, then kidnap the robot
Everything runs at once here. Now the robot slips and the detector lies, at the rates you set. The filter uses the same rates in its two models.
Drive runs one move and one reading. Auto keeps driving. The trace shows the belief on the robot's true cell over the last 60 steps.
Illustrative toy on the hero's map. Random slips and lies come from a fixed seed, so Reset replays the same run.
Try these four runs:
The two sliders are the two halves of the loop pulling against each other. Motion noise is the strength of predict; sensor quality is the strength of update. When sharpening wins, the robot stays found.
Chapter 9
Choose how to store the belief, calibrate both models, and catch the classic bugs
A real filter needs three choices: how to store the belief, the motion model and the measurement model. The storage choice names the filter.
| Storage | Shapes it can hold | Cost | Named |
|---|---|---|---|
| Grid of cells (this lesson) | any shape, many peaks | cells to the power of the dimensions: 100 per axis in 6-D is 1012 | histogram filter, grid localization, HMM forward algorithm |
| One Gaussian bump | one peak only | a mean and a covariance | Kalman filter, EKF, UKF |
| A cloud of samples | any shape | grows with the number of samples | particle filter, Monte Carlo localization |
Ask first: can the belief have more than one peak? A robot switched on in a building of identical rooms can be in any of them, so one Gaussian cannot hold its belief. Calibrate both models from counts, and round toward more noise.
The worst bug looks healthy. Say the belief is 0.9999 on cell 3 and 0.0001 on cell 4, and 0 elsewhere. The robot is in cell 7. A reading has likelihood 0.05 at cells 3 and 4 and 0.8 at cell 7. The products are 0.049995, 0.000005 and 0 × 0.8 = 0.
After rescaling, cell 3 still holds 0.9999. A cell at exactly 0 stays at 0: no likelihood can lift it.
The belief starts sure of cell 3, but the robot is in cell 11. Pick a design and press Run. The red mark is a sure, wrong belief.
Illustrative toy on the hero's map with a detector right 90% of the time. "Perfect wheels" assumes no slip. "Honest blur" allows 5% slip and 5% overshoot. The last design also mixes 1% of a flat belief into every step.
With perfect wheels the belief never leaves one cell, so no reading can move it. Honest blur leaks tiny belief to other cells, and the filter recovers after 32 readings. Mixing in 1% of a flat belief recovers after 11.
| Bug | Symptom | Measure | Fix |
|---|---|---|---|
| Missing divide | total drifts from 1, then underflows | assert the sum is 1 after every step | divide by S; use logarithms |
| Wrong motion model | peak runs ahead of or behind the robot | plot peak against logged ground truth | recount real moves |
| Overconfidence lock | sure, wrong, and readings do not move it | many readings in a row with low likelihood | honest blur, no likelihood of 0, a little uniform mix |
| Not Markov | patterned errors that tuning cannot remove | correlation of reading gaps over time | add the hidden quantity to the state |
Chapter 10
Keep the numbers, the terms, the checks and the core code of the lesson on one page
A belief is one probability per cell, adding to 1. Predict shifts and blurs it with the motion model. Update multiplies it by the likelihood of the reading and rescales it. The loop feeds each belief into the next step, and the Markov assumption makes that one array enough memory. A second sensor is one more update.
| What | Number | Why it matters |
|---|---|---|
| Predict from a spike | peak 1.00, then 0.80, then 0.66 | moving without reading leaks certainty |
| Update "door", flat over 8 | S = 0.4875; doors 0.205, walls 0.077 | multiply, then divide by S |
| Likelihood ratio | 0.8 / 0.3 = 2.67; flaky 0.55 / 0.45 = 1.22 | the gap sets how far a reading moves you |
| Three "door" readings | 0.950 good; 0.646 flaky | odds multiply |
| Door, move, door | cell 5: 0.205, 0.192, then 0.317 | a sequence splits the candidates |
| Paths vs loop, 8 readings | 17,496 paths vs 15 small steps | same answer, Markov |
| Two sensors, 4 cells | 0.06, 0.16, 0.06, 0.72 | one more update fuses a sensor |
| Breaking a lock | never; 32 readings; 11 readings | keep every cell above 0 |
| Term | Meaning |
|---|---|
| Belief | One probability per state, adding to 1. |
| Motion model | The chance of each real move after a command. |
| Measurement model | The chance of each reading in each state. |
| Likelihood | The chance of the reading you got, if the robot were in a given cell. |
| Normalize | Divide every number by their total, so they add to 1. |
| Likelihood ratio | How many times more likely a reading is in one state than another. |
| Recursive | Each step's output belief is the next step's input. |
| Markov assumption | Given the current state, the past adds nothing about the next step. |
pythonimport numpy as np DOORS = {1, 4, 5} # the 8-cell loop hallway MOTION = {0: 0.1, 1: 0.8, 2: 0.1} # slip, as commanded, overshoot SAYS_DOOR = {True: 0.8, False: 0.3} # P("door" | door cell?) def predict(bel): # motion blurs N = len(bel); out = np.zeros(N) for src in range(N): for k, p in MOTION.items(): out[(src + k) % N] += bel[src] * p # the loop wraps around return out def update(bel, reading): # a reading sharpens p_door = np.array([SAYS_DOOR[x in DOORS] for x in range(len(bel))]) like = p_door if reading == 'door' else 1 - p_door post = bel * like return post / post.sum() # eta = 1 / S bel = np.full(8, 1 / 8) bel = update(bel, 'door') # doors 0.205, walls 0.077 bel = update(predict(bel), 'door') # cell 5: 0.317 assert abs(bel.sum() - 1) < 1e-9
Now press Present or Teach. Explain from memory the belief, the predict sum, the update with eta, and why the loop needs only one array. Then go back to the hallway, press Step nine times, and say why the bars gather on the robot.