SLAM and Factor Graphs

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.

Close one loop three ways

Method

2.0°/m

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

The Chicken and the Egg

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.

Drive a loop on wheel counts alone

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.

2.0°/m

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 failure, as symptom, measurement and fix

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.

The road

  1. The problem: what SLAM estimates, online or full.
  2. Two models: how the robot moves and what it sees.
  3. EKF-SLAM: one big Gaussian over pose and map (the hero's filter).
  4. Forgetting: what a filter loses when it drops the past.
  5. Factor graphs: every measurement as a penalty in one sum.
  6. Gauss-Newton: the step that minimises the sum.
  7. Sparsity: why thousands of poses solve fast.
  8. Loop closure: the hero's correction, step by step, and a wrong one.
  9. Bundle adjustment: the same machine for cameras.
  10. The field guide: terms, numbers, code and links.
Why does dead reckoning give a badly wrong map after a long drive?

Chapter 1

Stating SLAM Precisely

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.

  1. The trajectory: the robot's pose at each step. A pose is position plus heading, (x, y, θ).
  2. The map: here a set of landmarks, fixed points such as corners and poles, each with an (x, y).
  3. The controls: the motion the robot measured at each step, from odometry. "Forward 1 m, turn 10°."
  4. The measurements: what the sensor saw at each step. "A landmark 3 m away, 20° to the right."

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.

Say it aloud

p of x one to t and m, given z one to t and u one to t.

p( )
p of the probability of what is inside, before the bar.
x1:t
x one to t every pose from step 1 to step t: the whole path.
m
m the map: the positions of all landmarks.
|
given the data after the bar is known.
z1:t
z one to t every sensor measurement so far.
u1:t
u one to t every odometry reading so far.
In plain words

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 numbers

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.

Add steps and count what each kind keeps

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)
Keepsxt and mx1:t and m
Memoryfixedgrows with t
Can fix a past posenoyes

The failure, as symptom, measurement and fix

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.

What separates full SLAM from online SLAM?

Chapter 2

Two Models: Motion and Measurement

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.

Say it aloud

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.

xt
x-t the new pose (x, y, θ).
g
g the motion function: apply the turn and the drive to the old pose.
ut
u-t the odometry reading for this step.
xt−1
x-t-minus-one the pose one step ago.
εt
epsilon-t the process noise: a random nudge from slip.
N(0, Rt)
normal, zero, R-t a bell curve centred on zero; R-t, a covariance matrix, sets its size in each direction.
In plain words

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 numbers

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.

Say it aloud

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.

r
r the range: the straight-line distance to the landmark, in metres.
√
the square root of Pythagoras turns the two gaps into one distance.
Δx, Δy
delta-x, delta-y landmark position minus robot position, along x and along y.
φ
phi the bearing: the angle to the landmark, measured from where the robot faces.
atan2
atan-two the arctangent that knows the quadrant: the world direction to the landmark.
θ
theta the robot's heading, subtracted so the angle is in the robot's own frame.
In plain words

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.

With numbers

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 robot and the landmark

Drag the teal robot or the purple landmark. Turn the robot with the slider: the range stays, the bearing changes.

30°

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 failure, as symptom, measurement and fix

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.

A robot at (0, 0) faces 90° (straight up). A landmark sits at (3, 0), to its right. What bearing does it report?

Chapter 3

EKF-SLAM: One Big Gaussian

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.

Say it aloud

K equals Sigma-bar H-transpose, times the inverse of H Sigma-bar H-transpose plus Q.

K
K the gain: how far each state number moves per unit of residual.
Σ̄
Sigma-bar the predicted covariance of pose and landmarks, with all correlations.
H, H⊤
H, H-transpose the measurement Jacobian, and the same matrix flipped.
Q
Q the sensor noise covariance.
( )−1
the inverse of divide by the total uncertainty of the predicted reading.
In plain words

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 numbers

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 updateBeforeAfter
landmark mean09.90
landmark variance1001.00
pose–landmark correlation00.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.

Drive the filter and watch the ellipses

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.

3.5 m

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 failure, as symptom, measurement and fix

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.

In EKF-SLAM, why does seeing one landmark also improve the pose and the other landmarks?

Chapter 4

Why Filters Forget, and What It Costs

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.

Forget the oldest pose

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.

  1. No past pose can be fixed. If the robot learns at step 100 that step 5 was wrong, step 5 no longer exists.
  2. Linearization is frozen. The EKF straightens g and h once, at its guess at that moment. If the guess was off, the error stays in for good.
The turn. Stop filtering and start optimizing. Keep every pose and landmark as an unknown. Treat every reading as a constraint. Find the values that satisfy all constraints best, all at once.

The failure, as symptom, measurement and fix

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.

Why does keeping all poses help with loop closure?

Chapter 5

Factor Graphs: The Problem as a Picture

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.

FactorTouchesSays
Priorone pose"the first pose is the origin"
Odometrytwo poses in a row"the motion between them matches the wheels"
Observationa pose and a landmark"the range and bearing match the sensor"
Loop closuretwo far-apart poses"these two poses are the same place"

Switch factor types on and off

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.

Say it aloud

x-star equals the arg-min over x of the sum over i of e-i transpose, Omega-i, e-i.

x*
x-star the best values of every pose and landmark: the MAP estimate.
arg minx
the arg-min over x the x that makes what follows smallest.
Σi
the sum over i add one term for each factor.
ei(x)
e-i of x factor i's residual: measured minus predicted, for these values of x.
Ωi
Omega-i the information: one over the noise variance. A precise sensor has a large Omega.
In plain words

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 numbers

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 failure, as symptom, measurement and fix

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.

An observation factor links which nodes?

Chapter 6

Solving It: Gauss-Newton

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.

  1. Pretend each residual is a straight line near the current guess.
  2. Jump to the bottom of the bowl that this makes.
  3. Start again from there.

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.

Say it aloud

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.

Σi
the sum over i one term for each factor.
Ji
J-i factor i's Jacobian: the change of its residual per unit change of each variable.
Ωi
Omega-i factor i's information: its weight.
Δ
delta the step to add to every variable.
ei
e-i factor i's residual at the current guess.
In plain words

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.

With numbers

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.

FactorWantsJacobian rowResidual at (0, 1, 2)
priorx1 = 0[1, 0, 0]0
odometry 1 to 2x2 − x1 = 1[−1, 1, 0]0
odometry 2 to 3x3 − x2 = 1[0, −1, 1]0
loop closure 1 to 3x3 − 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.

Take one Gauss-Newton step

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.

1

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 failure, as symptom, measurement and fix

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.

In the normal equations, what is the matrix H = Σ Ji⊤ΩiJi?

Chapter 7

Sparsity: Why Big Graphs Solve Fast

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.

Reorder the unknowns

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 failure, as symptom, measurement and fix

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.

Why is the information matrix H of graph SLAM sparse?

Chapter 8

Loop Closure: Collapse the Drift

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.

Drive, close, solve

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.

2.0°/m

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).

  1. Match features. Compare descriptors of what the robot sees now with the map (Lesson 9).
  2. Recognise the place. Summarise each place as a compact vector and search for the nearest one.
  3. Check the geometry. Confirm the match with RANSAC before you add the factor.

The failure, as symptom, measurement and fix

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.

Why is a false loop closure so dangerous?

Chapter 9

Bundle Adjustment: The Same Machine for Cameras

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).

Say it aloud

e-i-j equals z-i-j minus pi of C-i and P-j.

eij
e-i-j the reprojection error: a 2-D gap in pixels.
zij
z-i-j the pixel where point j was seen in image i.
π
pi the projection: move the point into the camera's frame, divide by depth, scale by the focal length.
Ci
C-i the pose of camera i.
Pj
P-j the 3-D position of point j.
In plain words

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 numbers

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.

Pull the rays back together

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 failure, as symptom, measurement and fix

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.

What is the reprojection error?

Chapter 10

Field Guide

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.

TermMeaningNumber to remember
Dead reckoningadd up measured steps1°/m over 20 m: 3.6 m off
Full SLAMp(x1:t, m | z1:t, u1:t)100 poses, 20 landmarks: 340 unknowns
Range, bearingr = √(Δx² + Δy²), φ = atan2(Δy, Δx) − θ(2, 1, 30°) to (5, 5): 5.0 m, 23.1°
EKF-SLAMone Gaussian over 3 + 2N numbersN = 1,000: about 4 million covariance entries
MAP objectivemin Σ ei⊤Ωiei0.1 m at Ω = 100 costs 1.0
Gauss-Newtonsolve HΔ = b, repeat3 poses: Δ = (0, −0.133, −0.267)
SparsityH non-zero only where a factor links two variableslandmark first: 45 non-zeros in L, last: 24
Loop closureone factor between far-apart posestoy loop: 3.3 m gap to 0.0 m
Reprojectione = z − π(C, P)(372, 263) seen, (370, 265) predicted: cost 8

Checklist for any SLAM back end you build

The core, in code

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

Keep going

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.

The takeaway. Keep the past, write every reading as a weighted residual, and solve the sparse sum. One trustworthy loop closure then removes the drift of a whole loop.

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.

Principles of Robot Autonomy I · Stanford AA 274A · Lesson 11: SLAM and Factor Graphs
Next: Occupancy Mapping · Back to Gleams