A robot that maps on odometry alone drifts. After one 28 m loop at 1° of heading error per metre, it draws the same rack twice, 0.85 m apart. One verified loop closure pulls the map to within 3 cm. One false closure folds it.
Pick what the robot does when it gets back to its dock, and set the drift. Watch the two copies of the middle rack. Then we build it piece by piece: drift, what a loop can fix, how a robot recognises a place, and how it rejects a lie.
You need what a pose is (position plus heading), the idea of least squares and a little Python. We build the rest from zero.
Lesson 8 of the Robotics Engineering track. Before: Lesson 7, SLAM Backend. Next: Lesson 9, Downstream Perception. The pose-graph solver itself is taught in SLAM and Factor Graphs.
Back at the dock, the robot
Illustrative toy: a 10 m by 4 m loop in 28 steps of 1 m, a heading bias you set plus small seeded noise. Each step on a long aisle sees the middle rack 2 m to its left. Closing runs Gauss-Newton on all 29 poses with pose 0 anchored. The false loop claims the dock is the far corner.
Chapter 0
Size how fast a tiny heading error grows into a doubled rack
A warehouse robot leaves its dock and maps as it drives. The first two aisles look perfect. By the far wall, the map shows one rack twice, a metre apart. No sensor failed and no log shows an error.
The cause is drift: the slow growth of position error when a robot adds up its own relative motion. Each step carries a small, honest error. The next step starts from the wrong place, so the errors add instead of cancel.
Put a number on it. Call the heading error per metre b, the distance driven L, and the sideways error at the end y. After L metres the heading is off by b times L. Each metre then adds a sideways step of the sine of that heading.
y of L equals one minus cos of b-L, all over b, which is about one half b L squared.
Add b to the heading for every metre. Add the sine of the heading to the sideways error for every metre. The total after L metres is y. Heading is a sum of the bias, and position is a sum of the heading, so y grows with L squared.
With a made-up bias of b = 0.00349 rad/m and L = 40 m: b L = 0.140 rad, or 8°. 1 − cos(0.140) = 0.00973. Divide by 0.00349: y = 2.79 m. The small-angle form gives 2.79 m too.
The orange curve is the sideways error. The pink line is half the 1.2 m shelf pitch: past it, a human sees the rack twice. Drag the bias.
The curve is the exact formula above. The 1.2 m pitch and the biases are illustrative values for a warehouse.
| Distance L | Heading error | Sideways error y |
|---|---|---|
| 10 m | 2° | 0.17 m |
| 20 m | 4° | 0.70 m |
| 40 m | 8° | 2.79 m |
| 60 m | 12° | 6.26 m |
At 0.2°/m the rack passes half a pitch after 18.5 m. So the robot needs a correction about every 18 m. Halve the bias and the safe distance grows by √2, not by 2, because y grows with L squared.
The same law holds for any sensor that adds up a bias. Only the thing that accumulates changes.
| Source | Bias adds up per | Bias per metre |
|---|---|---|
| Wheel odometry | metre | b |
| Gyro | second | ω / v (bias per second over speed) |
| Scan matcher | keyframe | δθ / d (bias per keyframe over keyframe spacing) |
The symptom is a doubled rack while every local check is green. To measure it, drive a closed loop and log the gap between the start and end estimates. The fix is a constraint that ties the end of the path back to its start: a loop closure.
Chapter 1
Slide a whole pose chain and see which errors no relative measurement can feel
Four poses sit on a line. Odometry says each step is 1 m. Put the poses at 0, 1, 2 and 3. Every odometry residual is zero. Now move all four by 5 m, to 5, 6, 7 and 8. Every residual is still zero.
The measurements cannot tell the two answers apart. A direction the measurements can feel is observable. A direction they cannot feel is unobservable. Moving the whole map at once is the gauge: the free choice of where the map sits.
Linear algebra finds these directions. Write one row per measurement: −1 under the older pose and +1 under the newer one. That stack is the Jacobian A. Put each measurement's weight in a diagonal matrix W. The information matrix Λ says how strongly the data pins each direction.
Lambda equals A transpose, W, A.
For each measurement row of A, multiply the row by itself and by its weight W. Add these up to get Lambda. Any direction that Lambda sends to zero is a direction no measurement can see.
Three odometry rows with weight 1 give the matrix below. Each row of Lambda adds to zero, so Lambda times (1, 1, 1, 1) is (0, 0, 0, 0). Its eigenvalues are 0, 0.586, 2 and 3.414. The single 0 is the gauge.
Teal dots are poses, orange springs are odometry. Slide every pose at once. Then add a loop closure, an anchor, or both, and slide again. The bars are the eigenvalues of Lambda.
A 1-D toy with unit weights. The page computes the eigenvalues live from Lambda.
Add the loop closure 3 to 0. The eigenvalues become 0, 2, 2 and 4. The smallest non-zero one rises from 0.586 to 2: the softest bend of the chain is now pinned 3.4 times harder. That is the loop fixing drift. The zero stays, because a loop closure is one more relative measurement.
Only an anchor lifts the zero: a prior that says where one pose is. With the anchor the smallest eigenvalue is 0.121 on the chain and 0.186 with the loop.
| Error | Lives in | Fixed by |
|---|---|---|
| Drift, a bent shape | the observable part | a loop closure |
| Absolute position and heading | the gauge | an anchor: GPS, a known landmark, or fixing pose 0 |
| Monocular scale | another gauge | a metric sensor (Chapter 6) |
With a camera and an IMU, four directions stay free: three of position and one of heading about gravity. Gravity pins roll and pitch (Hesch et al., 2014).
The symptom is a solver that fails on a singular matrix, or a map that lands somewhere new each run. To measure it, compare the rank of Lambda with the number of unknowns. The fix is a prior on the first pose.
Chapter 2
Turn an image into a weighted word count and rank the stored places
The robot holds one image and ten thousand stored keyframes. Comparing pixels is too slow, and it fails when the light or the angle changes.
Place recognition finds the stored keyframe that shows the same place. The classic method summarises each image as a bag of words. A detector finds feature points and describes each one. Each descriptor snaps to its nearest visual word: one entry in a vocabulary built offline by clustering many descriptors. The image becomes a count of each word, with the order thrown away.
The word "floor" fires in every image, so it says nothing about where you are. A striped pillar fires in one place, so it says a lot. TF-IDF weights each word by how often it fires here and how rare it is overall (Sivic and Zisserman, 2003). Call the count of word i in this image ni and the total count n. Call the number of stored places N, and the number that contain word i Ni.
w-i equals n-i over n, times the log of N over N-i.
Find the share of this image's features that are word i: n-i over n. Multiply it by the log of N over N-i. A word in every place gets log 1 = 0 and drops out. Then scale the weights to length 1 and compare images by the dot product, the cosine similarity.
With made-up counts: the query has 13 features, 2 of them on the pillar word. The pillar is in 1 of N = 3 places, so log(3/1) = 1.099. w = 2/13 × 1.099 = 0.169. The floor is in all 3 places, so its weight is 0.
Yellow bars are the query's word weights. The rows below score each stored place. The robot stands at the pillar corner. Switch the weighting, then add floor to the view.
Illustrative counts over four words: floor, shelf, door and pillar. Aisle (8, 4, 0, 0); dock (4, 0, 4, 0); pillar corner (4, 2, 1, 3); query (floor, 2, 1, 2).
With raw counts the aisle wins, 0.942 against 0.919, because both images are mostly floor. TF-IDF drops the floor and the pillar corner wins, 0.992 against 0.341. For speed, an inverted index lists, for each word, the places that contain it, so a query visits only those lists.
| Bag of words (DBoW2) | Learned descriptor (NetVLAD) | |
|---|---|---|
| Built by | clustering binary descriptors offline | a network trained on same-place and different-place pairs |
| Output | a sparse word count | one dense vector per image |
| Strong at | fast lookups inside real-time SLAM | day against night, season against season |
| Source | Gálvez-López and Tardós, 2012; used in ORB-SLAM | Arandjelović et al., 2016; trained on Google Street View Time Machine |
The symptom is a confident match between two different aisles with identical shelves. This is perceptual aliasing. To measure it, log the gap between the best and second-best scores; aliased scenes have several places tied near the top. The fix is a geometric check before you trust the match.
Chapter 3
Ask whether one rigid motion explains the matches, and count how many tries that takes
The place recogniser hands over a candidate. Now match features between the query and the candidate: point p here matches point q there. If the loop is real, one rigid motion (a rotation and a shift) carries most p onto their q. If it is an alias, no single motion explains the matches.
Some matches are wrong even for a real loop. Those wrong matches drag a least-squares fit off. RANSAC (random sample consensus; Fischler and Bolles, 1981) works around the wrong ones:
How many tries? Call the share of correct matches w, the sample size s, the confidence you want P, and the number of tries k.
k equals the log of one minus P, over the log of one minus w to the s.
One sample is all correct with chance w to the s. It fails with chance one minus that. k samples all fail with that chance raised to the k. Set that equal to one minus P and solve for k.
With w = 0.6 and s = 2: w to the s is 0.36. log(0.01) = −4.605 and log(0.64) = −0.446. k = 10.3, so 11 tries. With s = 4, k = 33.2, so 34 tries.
Purple dots are the candidate's features. Teal crosses are the query's features moved by the best motion so far. Green links are inliers. Pick a candidate, set the tolerance, press Run.
Illustrative: 30 matches in a 4 m patch. The real loop has 18 correct matches (w = 0.6) under a 25° turn and a shift, with 3 cm noise. The look-alike's matches are random. Accept at 12 inliers or more.
The tries grow fast as w falls, so cleaner matches are worth more than a faster loop.
| Correct share w | w² | Tries k (s = 2, P = 0.99) |
|---|---|---|
| 0.5 | 0.25 | 17 |
| 0.6 | 0.36 | 11 |
| 0.8 | 0.64 | 5 |
The symptom is a look-alike aisle accepted as a loop. In the device, push τ to 1.2 m and run the look-alike: random matches start to count. To measure it, log the inlier counts of rejected and accepted candidates and look for overlap. The fix is a tight τ from the sensor noise and a firm inlier minimum.
Chapter 4
Weigh a missed loop against a false one, and gate each closure by its own uncertainty
Go back to the hero and press Closes a false loop. The solver obeys the bad constraint and bends 28 m of path to meet it. At 1°/m the mean pose error goes from 1.02 m on odometry alone to 2.67 m. The true closure brings it to 0.03 m.
The costs are not equal. A missed loop leaves the drift you already had. A false loop welds two places together and folds the map. So loop acceptance is precision first: reject anything you are not sure of.
One more check is cheap. The graph already predicts where the candidate should put the robot. The gap between that prediction and the candidate is the residual r, here an (x, y) error in metres. Whether 20 cm is large depends on how much error you expected, which is the covariance Σ. Measured in its own standard deviations, the residual gives the Mahalanobis distance d.
d squared equals r transpose, Sigma inverse, r.
Divide each part of the residual r by its standard deviation, square it, and add. That is d squared. Compare it with a chi-squared threshold for 2 numbers: 5.99 keeps 95% of true closures. Above it, reject.
With made-up numbers: r = (0.18, 0.10) m and standard deviations 0.1 m and 0.2 m. d² = 0.18²/0.01 + 0.10²/0.04 = 3.24 + 0.25 = 3.49. That is below 5.99: accept. A residual of (0.30, 0.45) gives 9.00 + 5.06 = 14.06: reject.
The ellipse is the gate: wide where you expect a large error. The dot is the residual. Move it with the sliders.
Illustrative standard deviations: 0.1 m in x and 0.2 m in y. The thresholds are the 95% and 99% points of a chi-squared distribution with 2 degrees of freedom.
Real systems stack more checks. ORB-SLAM accepts a loop only after three consecutive candidates agree with each other (Mur-Artal et al., 2015). A robust back end gives each loop factor a switch. The solver turns the switch down when that factor disagrees with everything else. Two versions are switchable constraints (Sünderhauf and Protzel, 2012) and dynamic covariance scaling (Agarwal et al., 2013).
The symptom is a total cost that jumps at one closure and stays high. In the hero toy at 1°/m it settles near 10,000 with the false loop and near 110 with the true one. To measure it, list each factor's residual after the solve; the false loop is the tallest. The fix is to remove it, or let a robust kernel shrink its weight.
Chapter 5
Close a loop on a chain of edges and see each edge take its share by variance
A verified loop says the chain should close. The odometry says it ends 1 m past the start. That 1 m is the loop error e. Someone has to absorb it. The solver does not snap the last pose back; it shares the error over every edge of the loop.
Which edge takes how much? Call the standard deviation of edge k σk and the correction it absorbs δk. Least squares spends the loop error where it costs least. It minimises the sum of each correction squared over its variance. The corrections must add to e.
delta-k equals e times sigma-k squared, over the sum over m of sigma-m squared.
Add up the variances of all edges in the loop. Each edge k takes the fraction of the loop error e that its own variance is of that total. A shaky edge moves a lot; a confident edge barely moves.
With made-up numbers: six edges with σ = 1, 1, 1, 3, 1, 1 and e = 1 m. The variances add to 1 + 1 + 1 + 9 + 1 + 1 = 14. Edge 3 takes 9/14 = 0.643 m. Each other edge takes 1/14 = 0.071 m. Check: 0.643 + 5 × 0.071 = 1.00 m.
Where does that form come from? Set the derivative of the penalized sum to zero for each δk. Each correction comes out proportional to its variance. The full pose-graph version, with angles and a sparse matrix, is the Gauss-Newton step in SLAM and Factor Graphs and in SLAM Backend.
Top row: odometry, ending 1 m past the start marker. Bottom row: after the loop closes. Make edge 3 shakier and watch it take more of the correction.
A 1-D toy: six edges of 1 m measured as 1 m plus their share of the 1 m error. The other five edges keep σ = 1.
Squaring makes the split lopsided. With σ = 2 on edge 1 and 3 on edge 3, the variances add to 17. Edge 3 takes 9/17 = 0.529 m and edge 1 takes 4/17 = 0.235 m. A 1.5 times larger σ takes 2.25 times the correction.
The symptom is a closed loop with one visible kink. One edge with a too-loose covariance soaked up most of the error. To measure it, plot each edge's correction after the solve. The fix is to set each covariance from measured noise, not from habit.
Chapter 6
Separate a map that agrees with itself from a map that agrees with the world
A map is consistent when it agrees with itself: the rack seen going out lands on the rack seen coming back. A map is accurate when it agrees with the world. A loop closure buys consistency. It buys accuracy only for errors the measurements can see.
Pink dashes are the true ring. The solid ring is the map. Pick an error, then switch on the fixes one at a time.
Illustrative: a 12-pose ring of radius 3 m. Drift curls the ring open; the offset moves and turns the whole map; the scale error is 1.4 times. Each fix removes only what it can observe.
Scale is the famous case. A single camera sees directions, not lengths. Call the map's scale factor s, two pose positions pi and pj, and the loop measurement between them z. The loop residual is r.
r of s equals s times, p-j minus p-i, minus s times z, which equals s times r.
Stretch the map by s. The poses stretch by s and so does the loop measurement z. Stretching multiplies the residual r by s, so a zero residual stays zero at every size.
With made-up numbers: a 10 m aisle built at s = 1.5 reads 15 m. The loop residual is 0 at s = 1 and 0 at s = 1.5. The solver cannot prefer the true size.
| Error | Does a loop fix it? |
|---|---|
| Drift, the doubled rack | Yes. This is its job. |
| Where the whole map sits | No. Needs an anchor. |
| Monocular scale | No. Needs a metric sensor: IMU, stereo, wheels or a known length. |
| A bias the loop measurement shares, such as a wrong camera mount angle | Partly. The seam closes; what every sensor got wrong stays wrong. |
A plain heading bias is the good case. The loop measurement does not share it, so the solver removes it. In the hero toy at 1°/m, the mean error drops from 1.02 m to 0.03 m.
The symptom is a monocular map with clean loops and healthy residuals that is 30% too small. To measure it, compare one known distance with the map. The fix is a metric sensor in the graph.
Chapter 7
Snap a fresh session into yesterday's map, and keep the map from growing forever
The robot reboots in the morning. It has no history, so it starts a new path from its own origin. Relocalization is a loop closure against a saved map: "am I somewhere I mapped before?" It also rescues a robot that someone carried somewhere new: the kidnapped robot.
The snap is one product of poses. Call the saved keyframe's pose in the map Tmap,kf and the current camera's pose relative to that keyframe Tkf,cur.
T map-cur equals T map-kf times T kf-cur.
Take the offset in T kf-cur. Turn it by the keyframe's heading. Add the keyframe's position from T map-kf. Add the two headings. The result is T map-cur.
With made-up numbers: the keyframe is at (3.0, 1.0) m, heading 30°. The camera is at (0.4, −0.2) m and −10° from it. x = 3.0 + 0.4 cos 30° + 0.2 sin 30° = 3.446 m. y = 1.0 + 0.4 sin 30° − 0.2 cos 30° = 1.027 m. Heading 20°.
Purple squares are saved keyframes. The orange trail is this morning's session, in its own frame. Pick the matched keyframe and press Snap. Then lower the inlier minimum.
Illustrative: 24 matches per candidate; the right keyframe yields 17 inliers, the look-alike 2. The snap uses the composition above.
Why 6? Say a random wrong match lands inside the tolerance 5% of the time. With 24 matches, the chance of 5 or more lucky inliers is 0.006; of 6 or more, 0.00096. So "at least 6" makes a false snap rarer than 1 in 1,000. Finding a clean 3-match sample at a 50% correct share takes k = 35 tries.
Then the map must stay bounded. A keyframe holds about 1,000 features of 52 bytes each: a 32-byte descriptor, a 2-D keypoint and a 3-D point. That is about 52 KB.
An 8-hour shift at 1 m/s with a keyframe every 0.5 m adds 57,600 keyframes, about 3 GB a day. ORB-SLAM deletes a keyframe when at least three other keyframes see 90% of its map points (Mur-Artal et al., 2015). The map then grows with new space, not with time. For appearance change, an experience map stores a new version of a place only when no stored one matches (Churchill and Newman, 2013).
The symptom is a robot that reports a good relocalization and plans into a rack: it snapped to a look-alike aisle. To measure it, log the inlier count of every snap and its jump from the dead-reckoned guess. The fix is a firm inlier minimum, with new experiences for regions whose look changed.
Chapter 8
Drive, recognise, verify and close on one loop, and break each step on purpose
Here is the hero with every step exposed. At the dock the place recogniser returns two candidates. The look-alike far corner scores higher on appearance, 0.86 against 0.81. Only the geometric check tells them apart: 38 inliers of 60 for the dock, 7 for the far corner.
Press Drive, then Close. The panel below the map shows both candidates: yellow is the appearance score, green the inliers against your minimum.
The same toy pose graph as the hero. The scores and inlier counts are illustrative. With the check on, the robot takes the best-scoring candidate that clears the minimum; with it off, it takes the best score.
Try these in order:
Chapter 9
Keep the terms, the numbers, the code and the next steps in one place
Drift grows with distance squared. A loop closure fixes the map's shape, never where it sits or its scale. Recognise the place with weighted words, verify it with geometry, gate it by its covariance, and let the solver spread the error by variance.
| Term | Meaning | Number to remember |
|---|---|---|
| Drift | y = (1 − cos bL)/b ≈ ½ b L² | 0.2°/m over 40 m: 2.79 m |
| Gauge | a direction no relative measurement feels | 4-pose chain: eigenvalues 0, 0.586, 2, 3.414 |
| TF-IDF | w = (ni/n) · log(N/Ni) | 2 of 13, in 1 of 3 places: 0.169 |
| RANSAC tries | k = log(1 − P)/log(1 − ws) | w = 0.6, s = 2: 11 |
| Chi-squared gate | d² = r⊤Σ−1r | 2 numbers, 95%: 5.99 |
| Error spreading | δk = e · σk2/Σ σm2 | σ = 3 among five 1s: 64% |
| Relocalization | Tmap,cur = Tmap,kf · Tkf,cur | at least 6 of 24 inliers: false snap under 0.1% |
| Keyframe culling | drop if 90% of points seen by 3 other keyframes | raw: about 3 GB per 8-hour shift |
python def try_loop_closure(query, db, graph, min_inliers=15, gate=5.99): q = tfidf(query.words) # unit vector over the vocabulary for cand in db.top_k(q, k=5): # inverted-index lookup T, inliers = ransac_rigid(query.feats, cand.feats) # best motion + inlier count if len(inliers) < min_inliers: continue # looks alike, geometry disagrees r = graph.predict(cand.pose, query.pose) - T # residual against the graph if r @ inv(graph.cov(cand.pose, query.pose)) @ r > gate: continue # chi-squared gate graph.add_between(cand.pose, query.pose, T, robust=True) return graph.solve() # Gauss-Newton spreads the error return None
Lesson 8 of the Robotics Engineering track. All toy numbers on this page are illustrative. Sources named on the page:
Now press Present or Teach and explain from memory: the drift law, the gauge, TF-IDF, RANSAC's tries, the chi-squared gate and the spreading rule. Then go back to the warehouse, close the false loop, and say why the map folds.