A robot that maps a building from its own wheel counts drifts: after one loop it can end metres from where it started. One recognised place, solved as a factor graph, pulls the whole path back to within centimetres.
Pick a method and set the drift. Watch the robot drive a loop, recognise its start, and correct. Then we build, piece by piece, the two models, the filter, the factor graph, the Gauss-Newton step and the loop closure.
You need what a probability is, a 2 by 2 matrix and a little Python. We build the rest from zero.
Lesson 11 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 10, Learning-Based Perception. Next: Lesson 12, Occupancy Mapping.
Method
Illustrative toy: a 6 m square, 24 steps of 1 m, heading error of about the set drift per metre. The filter keeps only the current pose, so the closure can move only that pose. The factor graph runs Gauss-Newton on all 25 poses.
Chapter 0
Drive a robot on its wheel counts alone and watch its map bend with it
Wake a robot in a building it has never seen. There is no GPS indoors and nobody gave it a map. It has wheels that count their turns and a laser that measures the distance to walls. Ask it to drive around and come back knowing where it went and what the building looks like.
To place a wall on the map, the robot must know where it stood when it saw the wall. To know where it stands, it must compare what it sees with the map. Each answer needs the other. SLAM (simultaneous localization and mapping) estimates the robot's path and the map at the same time, from its own motion and its measurements.
The easy way out is to trust the wheels. Dead reckoning adds up each measured step to get the position. It needs no map. It also fails, because each step has a small error and the errors add up.
The pink square is the true path; the pink dots are the true landmarks. Purple is what the robot believes. Set the drift and press Drive.
Illustrative toy: the robot places each landmark relative to where it believed it was at the first sighting. Drift is a heading error per metre, with a small random part.
Work the number. A gyro drifts 1° for every metre driven. The robot drives 20 m in a straight line. Its heading is off by 1°, then 2°, up to 20°. Add up the sideways part of each step: sin 1° + sin 2° + … + sin 20° = 3.6 m. A 1° error per metre puts the robot 3.6 m off after 20 m.
The map is hung on that drifting path, so every wall drifts with it. Two ideas break the cycle. First, fuse each motion with measurements of landmarks (Chapter 3). Second, recognise a place you have been and correct the whole path with that one fact (Chapters 5 to 8).
The symptom is a corridor that appears twice, side by side, after a loop. To measure it, drive a closed loop and record the gap between the start and the end estimate. The fix is a loop closure, solved over the whole path.
Chapter 1
Add time steps and count what each kind of SLAM must keep
Every method in this lesson estimates the same thing. There are two unknowns and two streams of data.
Everything is noisy, so SLAM finds a probability over all answers, the posterior, and reports its peak. Call the poses from step 1 to step t x1:t and the map m. Call the measurements z1:t and the controls u1:t.
p of x one to t and m, given z one to t and u one to t.
Take all the data, z and u. Score every possible path x one to t and map m by how well it explains the data. The best-scoring pair is the SLAM answer.
With made-up numbers: 100 planar poses and 20 landmarks. The unknowns are 100 × 3 + 20 × 2 = 340 numbers, all scored together.
That is full SLAM, also called smoothing. Online SLAM, or filtering, keeps only the current pose: p(xt, m | z1:t, u1:t). The filter folds the past poses into the current belief and deletes them. That folding is called marginalization.
Circles are unknowns: teal poses, purple landmarks. Blue boxes are data. Choose a kind of SLAM, then press Add a step.
Illustrative: 3 landmarks; each pose sees the landmarks above it. A planar pose is 3 numbers, a landmark 2.
| Online (filter) | Full (smoother) | |
|---|---|---|
| Keeps | xt and m | x1:t and m |
| Memory | fixed | grows with t |
| Can fix a past pose | no | yes |
The symptom is a robot that sees its start again and still cannot straighten its old path. To measure it, check whether past poses still exist as variables. The fix is full SLAM: keep them, so a later fact can move them.
Chapter 2
Drag a robot and a landmark and read the range and bearing the sensor should report
Every SLAM method starts from two statements: how the robot moves, and what it sees. Both are a guess plus a blur.
First, motion. Call the pose at the last step xt−1 and the odometry reading ut. A function g applies the reading to the pose: turn, then drive forward (the unicycle model from Lesson 2). Wheels slip, so we add a random nudge εt.
x-t equals g of u-t and x-t-minus-one, plus epsilon-t, and epsilon-t comes from a normal with mean zero and covariance R-t.
Apply the reading u-t to the old pose with g. Then allow a random error epsilon-t whose size is R-t. A bigger R-t means you trust the wheels less.
With made-up numbers: the robot is at (0 m, 0 m, 0°) and reads "forward 1 m". g gives (1 m, 0 m, 0°). With a standard deviation of 0.05 m, the true pose is probably within 0.1 m of that.
Second, measurement. The robot at pose (x, y, θ) sees a landmark at (mx, my). Call the gaps Δx = mx − x and Δy = my − y. The sensor reports the range r, the distance, and the bearing φ, the angle from the robot's heading.
r equals the square root of delta-x squared plus delta-y squared, and phi equals atan-two of delta-y and delta-x, minus theta.
Subtract the robot's position from the landmark's. Pythagoras on delta-x and delta-y gives the range r. atan2 gives the world direction; subtract the heading theta to get the bearing phi.
Robot at (2, 1) facing 30°, landmark at (5, 5). Δx = 3 and Δy = 4, so r = √25 = 5.0 m. Then atan2(4, 3) = 53.1°, so φ = 53.1° − 30° = 23.1°, to the robot's left.
Drag the teal robot or the purple landmark. Turn the robot with the slider: the range stays, the bearing changes.
Noise-free prediction h(x, m). A real sensor adds noise with covariance Q; the gap between a reading and this prediction is the residual.
Stack range and bearing into one function h and add sensor noise with covariance Q. If the sensor returns (5.2 m, 21°) for the example, the residual z − h is (+0.2 m, −2.1°). Every SLAM method works by making residuals small.
The symptom is landmarks that spin around the robot when it turns. To measure it, turn in place and check whether the mapped landmarks move. The fix is the minus θ in the bearing.
Chapter 3
Drive a filter that tracks the pose and every landmark, and watch one sighting tighten them all
The first SLAM method took the extended Kalman filter (EKF) and widened its state. The state is no longer only the pose. It is the pose and every landmark, stacked in one column: the augmented state. With N landmarks it holds 3 + 2N numbers.
The filter keeps a mean μ, its best guess of every number, and a covariance Σ. The covariance also holds correlations: "if the pose is 10 cm off to the left, this landmark is too." That is the chicken and the egg, written as a matrix.
The filter repeats two steps, as in the Kalman filter. Predict: the robot moves, so its uncertainty grows; landmarks do not move. Update: the robot sees a landmark and corrects. How much to correct is the Kalman gain K. Call the predicted covariance Σ̄, the measurement Jacobian H (how the predicted reading changes with each state number) and the sensor noise Q.
K equals Sigma-bar H-transpose, times the inverse of H Sigma-bar H-transpose plus Q.
Sigma-bar H-transpose says how each state number co-varies with the predicted reading. Divide by the reading's total uncertainty, H Sigma-bar H-transpose plus Q. The result K moves every correlated number, not only the landmark seen. Then the mean moves by K times the residual.
With made-up numbers, on a line: pose variance 0.01, landmark variance 100, no correlation. The sensor reads landmark minus pose = 10, with Q = 1, so H = [−1, 1]. Σ̄H⊤ = [−0.01, 100]; the bracket is 0.01 + 100 + 1 = 101.01. K = [−0.0001, 0.990].
| After the update | Before | After |
|---|---|---|
| landmark mean | 0 | 9.90 |
| landmark variance | 100 | 1.00 |
| pose–landmark correlation | 0 | 0.0099 |
One reading turned "no idea" into "within about 1 m", and tied the landmark to the pose. From now on, a correction to the pose drags this landmark with it.
Purple ellipses are the filter's uncertainty (two standard deviations): one for the pose, one for each landmark. Pink dots are the true landmarks. Set the sensor range and press Drive.
A real EKF-SLAM on toy numbers: 6 landmarks, steps of 0.25 m, range noise 0.08 m, bearing noise 1.5°, known data association.
Watch the pose ellipse grow between sightings and shrink when the robot sees its first landmark again. The price is size. With N = 1,000 landmarks the state has 2,003 numbers and Σ has about 4 million entries. Every update touches all of them: double the landmarks, four times the work.
The symptom is a filter that slows down as the map grows, then stalls. To measure it, time one update against the number of landmarks. The fix is to stop keeping one dense covariance, which the rest of this lesson does.
Chapter 4
Delete old poses one by one and watch new links fill the gap
A filter keeps its memory fixed by deleting each past pose after it uses it. The pose's information stays. The filter moves it into links between everything the pose touched. Deleting a pose this way is marginalization.
Picture the links. Pose x2 has links to x1, to x3 and to the landmarks it saw. Delete x2, and each pair among those neighbours gets a direct link. Delete the next pose, and the links spread further. Soon every landmark has a link to every other one. That is the dense covariance of Chapter 3.
Teal circles are poses; purple circles are landmarks; grey lines are measurements. Press Forget to marginalize the oldest pose. Dashed purple lines are the new links. Then press Loop closure.
Illustrative graph. Marginalizing a variable links all of its neighbours to each other; the counts are exact for this graph.
Count it. The graph starts with 5 odometry links and 8 measurement links: 13. Forget x1, which saw all three landmarks: the graph still has 13 links, 4 of them new. Forget x2 too: 12 links on 2 fewer unknowns, 6 of them new. All three landmarks are now linked to each other: this corner of the graph is dense.
Forgetting has two more costs.
The symptom is a loop closure that kinks the path at the closing point. To measure it, look for a jump between the last two poses after a closure. The fix is to keep the past poses, so the correction can spread over them.
Chapter 5
Switch factor types on and off and watch the sum of penalties change
A factor graph draws the optimization problem, and solvers store it as their data structure. It has two kinds of node, and links only join one kind to the other.
| Factor | Touches | Says |
|---|---|---|
| Prior | one pose | "the first pose is the origin" |
| Odometry | two poses in a row | "the motion between them matches the wheels" |
| Observation | a pose and a landmark | "the range and bearing match the sensor" |
| Loop closure | two far-apart poses | "these two poses are the same place" |
Teal circles are poses, purple circles landmarks, squares factors. Switch a type off and read what the graph can no longer pin down.
Illustrative graph: 5 poses, 2 landmarks, 1 prior, 4 odometry factors, 4 observations, 1 loop closure.
Each factor scores one residual e: the measurement minus what the variables predict. The best answer makes the total score smallest. With Gaussian noise, the negative log of the posterior is a sum of weighted squares. Call factor i's residual ei and its information matrix Ωi, the inverse of its noise covariance.
x-star equals the arg-min over x of the sum over i of e-i transpose, Omega-i, e-i.
For each factor, square its residual e-i and weight it by Omega-i. Add all the weighted squares. Move the variables x until the total is as small as it can be.
With made-up numbers: an odometry factor is off by 0.1 m, and its standard deviation is 0.1 m. So Ω = 100 and it costs 100 × 0.1² = 1.0. A loop closure is off by 0.4 m with Ω = 1: it costs 0.16. The odometry error costs six times more, even though it is smaller.
The MAP estimate (maximum a posteriori) is the most probable answer. Here it is a weighted nonlinear least squares problem. A GPS reading or an IMU is one more factor type in the same sum.
The symptom is a solver that fails or returns a map that slides and turns from run to run. To measure it, check the graph for a factor that fixes the frame. The fix is a prior on the first pose.
Chapter 6
Take one Gauss-Newton step on three poses and watch the loop error spread back
The residuals contain square roots and arctangents, so one formula cannot solve the sum. Gauss-Newton repeats three moves.
Near the guess x, a small step Δ changes residual ei by about JiΔ. Ji is the Jacobian of factor i: how its residual changes with each variable. It is zero except in the columns of the variables the factor touches. Put the straight-line residuals into the sum and set its slope to zero.
The sum over i of J-i transpose Omega-i J-i, times delta, equals minus the sum over i of J-i transpose Omega-i e-i.
Build the matrix on the left, called H, from each factor's J-i and Omega-i. Build the right side, called b, from each residual e-i. Solve H delta = b, add delta to x, and repeat until delta is tiny.
The three-pose example below, with every Ω = 1. H = [[3, −1, −1], [−1, 2, −1], [−1, −1, 2]] and b = [0.4, 0, −0.4]. Solving gives Δ = (0, −0.133, −0.267).
The example. Three poses on a line start where odometry put them: x = (0, 1, 2). Four factors act on them.
| Factor | Wants | Jacobian row | Residual at (0, 1, 2) |
|---|---|---|---|
| prior | x1 = 0 | [1, 0, 0] | 0 |
| odometry 1 to 2 | x2 − x1 = 1 | [−1, 1, 0] | 0 |
| odometry 2 to 3 | x3 − x2 = 1 | [0, −1, 1] | 0 |
| loop closure 1 to 3 | x3 − x1 = 1.6 | [−1, 0, 1] | 0.4 |
Each row times itself, added up, gives H. Only the loop residual feeds b. The step moves x2 by −0.133 and x3 by −0.267: the 0.4 m disagreement spreads back over the chain. The new x = (0, 0.867, 1.733) cuts the total cost from 0.16 to 0.053. These factors are linear, so one step is exact.
Purple dots are the estimated poses. Blue arcs are the factors; their numbers are residuals. Set how much you trust the loop closure, then press Step.
This device makes the prior stiff, so x1 stays at 0. With Ω = 1 for the prior instead, the answer is the same, because its residual is zero.
Python, from the table:
python import numpy as np J = np.array([[1,0,0],[-1,1,0],[0,-1,1],[-1,0,1]], float) # one row per factor e = np.array([0, 0, 0, 0.4]) # residuals at x = (0, 1, 2) Om = np.eye(4) # information of each factor H = J.T @ Om @ J # [[3,-1,-1],[-1,2,-1],[-1,-1,2]] b = -J.T @ Om @ e # [0.4, 0, -0.4] delta = np.linalg.solve(H, b) # [0, -0.133, -0.267] x = np.array([0., 1., 2.]) + delta # [0, 0.867, 1.733]
The symptom is a map bent badly by one wrong reading. To measure it, list the largest weighted residuals after solving. The fix is a robust cost such as Huber, which counts a large residual less than its square.
Chapter 7
Reorder the unknowns and count how many numbers the solver must store
An odometry factor between x5 and x6 has a Jacobian that is zero outside those two columns. So its J⊤ΩJ fills only the four cells where x5 and x6 meet. Add up all factors and the rule is exact: cell (a, b) of H is non-zero only if some factor touches both a and b. H has the shape of the factor graph.
A robot at pose 500 does not see a landmark it saw at pose 3. So most cells of H are zero: H is sparse. A chain of 1,000 poses has 1,000 × 1,000 = 1 million cells, but its band holds about 3,000 non-zeros. Filtering made the covariance dense by marginalizing (Chapter 4). Smoothing refuses to marginalize, so H stays sparse.
To solve HΔ = b, the solver splits H into L L⊤, with L lower-triangular. This is the Cholesky factorization. It can create new non-zeros in L, called fill-in. The order of the unknowns decides how much.
Eight poses in a chain all see one landmark L. Left: the non-zeros of H. Right: the non-zeros of its Cholesky factor L; outlined cells are fill-in. Change the order and add a loop closure.
Counts are the lower triangle with the diagonal, computed by symbolic elimination and checked with numpy.
Read the counts. H has 24 non-zeros in its lower half. With the landmark last, L also has 24: no fill-in.
With the landmark first, eliminating it links every pose to every other one, and L fills completely: 45 non-zeros. A loop closure adds 5 fill-in cells in the good order. Solvers find good orders with tools such as COLAMD. That is how GTSAM and g2o solve tens of thousands of poses quickly.
The same idea runs backwards in the information filter: there, H is the inverse covariance, and you can watch marginalization fill it in.
The symptom is a solver that is fast on one map and slow on a similar one. To measure it, count the non-zeros of L against those of H. The fix is a fill-reducing order.
Chapter 8
Drive, close the loop, step Gauss-Newton yourself, then try a wrong closure
A loop closure is the robot saying "I have been here before." In the graph it is one more factor between two poses. Odometry links only neighbours. A loop closure links pose 24 straight back to pose 0.
Before the closure, only a long chain of noisy odometry ties the end to the start. The closure is a short, strong link. When Gauss-Newton solves the graph, the whole chain bends to agree with it. Each pose moves a little, and the map moves with the poses.
Press Drive. Then Close the loop, and press Step to run one Gauss-Newton iteration at a time. The bars (right, or below on a phone) are the total cost after each step, on a log scale. Then choose Wrong place and close again.
A real SE(2) pose graph on toy numbers: 25 poses, 24 odometry factors and one closure, Gauss-Newton with numeric Jacobians. Landmarks are hung on the pose that first saw them; they move when that pose moves.
Read the cost bars. Before the closure, the odometry agrees with itself and the cost is near zero. The closure adds one huge residual: at 2°/m the cost jumps to about 171,000. Three Gauss-Newton steps bring it down to about 27, and it stays there. The end gap goes from 3.3 m to 0.0 m, and the average pose error from 1.45 m to 0.04 m.
Spotting the place is the hard part. Deciding which current reading matches which old place is data association (see Data Association).
The symptom is a map folded into a confident, wrong shape. That is a false loop closure: choose Wrong place above and watch. To measure it, compare the final cost with each closure. At 1°/m the wrong closure leaves a cost of about 277, ten times the true one. The fix is geometric checks before adding the factor, and a robust cost after.
Chapter 9
Knock cameras and points out of place and let Gauss-Newton pull the rays back together
Swap the laser for a camera and the same machine becomes bundle adjustment (BA). The variables are camera poses and 3-D points. The data are pixel positions: where each point appeared in each image. It refines structure from motion (Lesson 9) and the back end of visual SLAM.
Call the pixel where point j appeared in image i zij. A projection function π takes a camera pose and a 3-D point. It returns the pixel where the point should appear (the pinhole model of Lesson 8).
e-i-j equals z-i-j minus pi of C-i and P-j.
Project the estimated point P-j through the estimated camera C-i with pi. Subtract that pixel from the pixel z-i-j you saw. The gap e-i-j is one residual; BA makes the weighted sum of their squares smallest.
With made-up numbers: focal length 500 px, image centre (320, 240). A point at (0.2, 0.1, 2.0) m in the camera frame lands at (320 + 500 × 0.1, 240 + 500 × 0.05) = (370, 265). It was seen at (372, 263), so e = (2, −2) px. With a 1 px noise, the cost is 2² + 2² = 8.
A flat world: each teal camera sees each point as one angle (a one-row image). Blue rays are what the cameras saw; purple dots are the estimated points. Press Perturb, then Step.
Illustrative 2-D BA with 32 bearing readings and 23 unknowns. The first camera and the position of the second are held fixed: they set the frame and the scale.
The structure helps again. Points do not see points and cameras do not see cameras; each factor links one camera to one point. So the point-to-point block of H is block-diagonal. The solver removes all points in one cheap step, the Schur complement, and solves a small system for the cameras alone. Ten cameras and 10,000 points leave a 60 by 60 camera system.
The symptom is a reconstruction that is the right shape at the wrong size, or slowly drifts in scale. To measure it, check what fixes the frame and the scale. The fix is to hold a reference camera and a known distance, or add another sensor such as an IMU.
Chapter 10
Keep the terms, the numbers, the code and the next steps in one place
SLAM estimates the path and the map together. A filter keeps one dense Gaussian and forgets the past. A factor graph keeps every pose, writes each reading as a weighted squared residual, and solves the sum with Gauss-Newton on a sparse matrix. A loop closure then pulls the whole path straight.
| Term | Meaning | Number to remember |
|---|---|---|
| Dead reckoning | add up measured steps | 1°/m over 20 m: 3.6 m off |
| Full SLAM | p(x1:t, m | z1:t, u1:t) | 100 poses, 20 landmarks: 340 unknowns |
| Range, bearing | r = √(Δx² + Δy²), φ = atan2(Δy, Δx) − θ | (2, 1, 30°) to (5, 5): 5.0 m, 23.1° |
| EKF-SLAM | one Gaussian over 3 + 2N numbers | N = 1,000: about 4 million covariance entries |
| MAP objective | min Σ ei⊤Ωiei | 0.1 m at Ω = 100 costs 1.0 |
| Gauss-Newton | solve HΔ = b, repeat | 3 poses: Δ = (0, −0.133, −0.267) |
| Sparsity | H non-zero only where a factor links two variables | landmark first: 45 non-zeros in L, last: 24 |
| Loop closure | one factor between far-apart poses | toy loop: 3.3 m gap to 0.0 m |
| Reprojection | e = z − π(C, P) | (372, 263) seen, (370, 265) predicted: cost 8 |
python def solve_graph(x, factors, iters=10): for _ in range(iters): H = zeros((len(x), len(x))); b = zeros(len(x)) for f in factors: # prior, odometry, observation, loop e, J, idx = f.residual(x) # J: only the columns f touches H[ix_(idx, idx)] += J.T @ f.Omega @ J b[idx] -= J.T @ f.Omega @ e delta = sparse_cholesky_solve(H, b) # with a fill-reducing order x = x + delta if norm(delta) < 1e-6: break return x
Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's lesson on SLAM in our own words, devices and toy numbers.
Now press Present or Teach and explain from memory: drift, the two models, the EKF gain, the factor graph sum, the Gauss-Newton step and sparsity. Then go back to the loop, set the drift to 5°/m, and say why only the factor graph closes it.