A robot drives one lap of a 4 m square, and its odometry turns 1.5° too far at every step. It ends 1.13 m from home. One loop closure lets a smoother pull the whole path back to 0.12 m RMS error. A filter threw the past away, so it can fix only the pose it is in now.
Drag the drift, close the loop, then switch between the filter and the smoother. Then we build, one piece at a time, the matrix the smoother solves, what forgetting costs, and the solver that keeps it fast.
You need matrix times vector, the idea of least squares and a little Python. We build the rest from zero.
Lesson 7 of the Robotics Engineering track. Before: Lesson 6, The SLAM Frontend. Next: Lesson 8, Drift, Loop Closure and Relocalization. Lesson 6 turned images into tracks and relative poses. This lesson turns those measurements into one consistent path. The theory from first principles: VNAV Lecture 9 (least squares), Lecture 10 (optimisation on manifolds) and Lecture 13 (factor graphs).
Illustrative robot, our seeded simulation: 16 steps of 1 m around a 4 m square, odometry noise 3 cm and 0.5° per step, plus the drift you set. The backend assumes odometry σ of 5 cm and 1°, and loop-closure σ of 2 cm and 0.5°. The smoother is Gauss-Newton on all 17 poses. The filter is an EKF that keeps only the current pose.
Chapter 0
Count what a filter keeps and what a smoother keeps, and see which matrix each one carries
A warehouse robot drives one lap of an aisle loop. Its wheels report each 1 m step, but the heading reads 1.5° too far every time. After 16 steps it believes it stopped 1.13 m from where it started. Then the camera recognises the start. That loop closure says: you are back at pose 0.
What can the software do with that one fact? It depends on what it kept. An EKF (extended Kalman filter) keeps only the current state, as a mean and a covariance. Every past pose has been marginalised: folded into the current one, then dropped. So the loop closure can move the current pose. The 15 poses before it are gone.
A smoother keeps every pose and every measurement. When the loop closes, it solves for all 17 poses at once, and the error spreads back along the path. In the hero, the filter's RMS error stays at 0.52 m. The smoother's falls to 0.12 m.
Keeping everything sounds expensive. It is not, and the reason is one matrix. A filter carries the covariance Σ: how every pair of unknowns varies together. A smoother carries the information matrix Λ, the inverse of Σ. Σ is dense, because the same drifting robot observes every landmark. Λ is sparse: an entry is nonzero only if one measurement involves both unknowns.
Left: the filter's covariance, one cell per block of unknowns. Right: the smoother's information matrix, poses first, then landmarks. A filled cell holds nonzero numbers. Drag the landmark count.
Illustrative 2-D map: a pose is 3 numbers (x, y, heading), a landmark 2. The smoother keeps one keyframe per 3 landmarks, and each landmark is seen from 4 keyframes. Counts are exact for that structure; the grids are drawn at most 160 cells across.
At 500 landmarks the filter's state has 3 + 2 × 500 = 1,003 numbers. Its covariance holds 1,003² = 1,006,009 doubles: 8.05 MB, and every update touches all of them. The smoother also keeps 167 poses, so its matrix is bigger, 1,501 by 1,501. Yet only 30,491 entries are nonzero, 1.35%. The bigger problem stores 33 times fewer numbers.
Symptom: the time per filter update grows with the square of the map, and the robot falls behind its sensors.
Measure: plot update time against landmark count on log-log axes. A slope of 2 is the dense covariance.
Fix: move mapping to a smoother. Keep a filter only where the state stays small, such as odometry with no map.
Chapter 1
Scatter each measurement into a matrix, and see why its zeros stay zero
Take the smallest problem that shows everything: three poses on a line, x₀, x₁ and x₂, in metres. A prior says x₀ is near 0 with σ = 1 m. Two odometry readings say each step is about 1 m, with σ = 0.5 m.
Each measurement becomes a factor: a residual r that should be zero, plus a weight. Odometry from pose i to pose j has the residual r = (xj − xi) − u, where u is the reading. Its weight is w = 1/σ², so the prior has w = 1 and each odometry factor has w = 4. The Jacobian J of a residual lists how it changes with each unknown. For odometry, J = [−1, +1] over (xi, xj), and zero for every other pose.
Least squares minimises the sum of the weighted squared residuals (Lesson 3 and VNAV Lecture 9 derive it). The curvature of that sum is the information matrix Λ. Call a factor's Jacobian Jf and its weight Wf:
Lambda equals the sum over factors f of J-f transpose, times W-f, times J-f.
For each factor, multiply J-f transposed by W-f and by J-f. The product is nonzero only in the rows and columns of the unknowns that factor touches. Add these small blocks into Lambda.
With made-up numbers: odometry 0 to 1 gives 4 × [−1, +1]T[−1, +1] = [[4, −4], [−4, 4]] in rows and columns 0 and 1. Add the prior's 1 at (0, 0) and the second odometry block at rows 1 and 2. Lambda = [[5, −4, 0], [−4, 8, −4], [0, −4, 4]]. Entry (0, 2) is exactly 0, because no factor touches both x₀ and x₂.
Each button adds one measurement. Left: Λ, entry by entry. Right: its inverse Σ, once Λ can be inverted. Watch which entries are zero in each.
Exact arithmetic on the three-pose example above. Prior σ = 1 m; odometry and loop σ = 0.5 m.
With the prior and both odometry factors, Σ = Λ−1 = [[1, 1, 1], [1, 1.25, 1.25], [1, 1.25, 1.5]]: nine nonzeros out of nine. The zero is gone, and correctly. x₀ and x₂ are correlated through x₁. Correlation passes along a chain; direct coupling does not. That is why Σ fills in and Λ does not.
Symptom: the solver stops with “matrix is not positive definite” on a graph with correct factors.
Measure: count the directions no factor pins down. Relative measurements never fix the whole map's position: a 2-D pose graph has 3 such directions (x, y, heading), so Λ has 3 zero eigenvalues.
Fix: add a prior on the first pose. Turn off the prior in the device and Σ disappears.
Chapter 2
Solve the normal equations on a drifting chain, and watch a loop closure share its error by trust
Six poses should sit at 0, 1, 2, 3, 4 and 5 m. The odometry reads each step 1 to 4 cm long, so dead reckoning ends at 5.12 m. A loop closure measures pose 5 as 4.99 m from pose 0, with σ = 2 cm. Odometry has σ = 10 cm. A tight prior holds pose 0 at the origin.
Gauss-Newton improves a guess by a step δ. It replaces each residual by its straight-line model r + Jδ, then picks the δ that minimises the weighted sum of squares. Setting the derivative to zero gives the normal equations. Call the residual of factor f at the current guess rf:
Lambda times delta equals eta, where eta is minus the sum over factors f of J-f transpose, W-f, r-f.
Evaluate every residual r-f at the current guess. Weight it, multiply by J-f transposed, add them all and flip the sign: that is eta. Solve Lambda delta = eta. Add delta to the guess, and repeat until delta is tiny.
The loop residual is (0 − 5.12) − (−4.99) = −0.13 m, with weight 1/0.02² = 2,500. One solve moves pose 5 to 4.9910 m. Each odometry edge now reads 0.0258 m short, and the loop edge 0.0010 m short. RMS error falls from 0.0718 m to 0.0085 m.
Every residual here is linear, so one step is exact. The edges share the total loop error e = 0.13 m in proportion to each edge's variance σ²:
sharek = e × σk² / Σm σm² → odometry 0.13 × 0.01 / (5 × 0.01 + 0.0004) = 0.0258 m; loop 0.13 × 0.0004 / 0.0504 = 0.0010 m
The loop closure is 25 times more trusted, so it bends least. Drag its σ and watch the shares move.
Top: pink true poses, blue dead-reckoned poses, purple after the step. Bottom: how much of the 0.13 m loop error each edge absorbs. Set the loop's σ, then press the step.
The Code Lab's chain: odometry 1.02, 1.03, 1.01, 1.04, 1.02 m with σ = 0.10 m; prior σ = 0.01 m on pose 0. Shares from our NumPy solve; they match the variance-share law to 10⁻¹⁵.
Now build it. The lab's starter adds a factor's weight to the two diagonal entries only. Run it and the “optimised” chain equals the odometry chain.
Symptom: after the solve, every pose sits exactly where dead reckoning put it.
Measure: print Λ. If it is diagonal, no factor coupled two poses.
Fix: a between-factor adds +w on both diagonals and −w at (i, j) and (j, i). The off-diagonal entry is the edge of the graph.
Chapter 3
Remove a variable with a Schur complement, and count the couplings it leaves behind
A robot cannot keep every variable forever. Removing one while keeping what it taught is marginalisation. Split the unknowns in two: a, the ones to drop, and b, the ones to keep. Λ splits into four blocks, Λaa, Λab, Λba and Λbb. Integrate a out of the Gaussian by completing the square, and a new information matrix for b remains. It is the Schur complement:
Lambda-prime equals Lambda-b-b minus Lambda-b-a, times Lambda-a-a inverse, times Lambda-a-b.
Take the kept block Lambda-b-b. Subtract a correction: the coupling to a, divided by a's own information, times the coupling back. The correction is an outer product over a's neighbours, so every pair of them becomes coupled.
Drop x₁ from Chapter 1's chain. Lambda-a-a = 8, Lambda-b-a = (−4, −4), Lambda-b-b = [[5, 0], [0, 4]]. The correction is (1/8) × [[16, 16], [16, 16]] = [[2, 2], [2, 2]]. So Lambda-prime = [[3, −2], [−2, 2]]. The entry for x₀ and x₂ was 0. It is now −2.
Was anything lost? Take Chapter 1's Σ, keep the rows and columns of x₀ and x₂, [[1, 1], [1, 1.5]], and invert: [[3, −2], [−2, 2]]. The same numbers. For a linear system, marginalisation is exact. With means (0.1, 1.1, 2.1), the reduced system returns 0.1 and 2.1 to the last digit.
The cost is structure. Eliminating a variable with d neighbours couples all d(d − 1)/2 pairs of them. A landmark seen from 4 otherwise unlinked poses turns 13 nonzeros into 16. Seen from 50 poses, it creates 1,225 pairs.
Left: teal poses, the pink landmark, blue measurement links. Right: the pose block of Λ. Choose how many poses saw the landmark, then marginalise it.
The Code Lab's graph: odometry weight 25, landmark weight 4, prior weight 100 on pose 0. Entries from our NumPy Schur complement.
In the lab, write the two lines of the Schur complement. The starter deletes the landmark's row and column instead.
Symptom: after the window drops old states, the estimate drifts away from a full re-solve of the same log.
Measure: solve one recorded bag both ways and compare the kept poses.
Fix: never delete rows and columns of Λ: that throws information away. Schur-complement them. (Deleting rows and columns of Σ is correct, because Σ is the other form.)
Chapter 4
Use the arrowhead shape of Λ to solve a 60,600-unknown problem as a 600-unknown one
Bundle adjustment refines camera poses and 3-D points together, from every pixel observation. Order the unknowns cameras first, then points. Λ takes an arrowhead shape:
V is block-diagonal because no single measurement involves two points. So V−1 is one small inverse per point. Eliminate the points first with Chapter 3's formula, and a small system over the cameras remains, the reduced camera system S:
S equals U minus W, times V inverse, times W transpose.
Invert each point's small block V. For each point, couple every pair of cameras that saw it, and subtract that from U. Solve the small system S for the camera steps. Then recover each point's step on its own.
With illustrative numbers: 100 cameras and 20,000 points, each seen by 4 cameras. The full system has 6 × 100 + 3 × 20,000 = 60,600 unknowns, and a dense Cholesky costs 60,600³/3 = 7.4 × 10¹³ flops. Building S costs about 7.8 × 10⁷ flops and factoring the 600 by 600 S costs 7.2 × 10⁷. At 10 GFLOP/s, that is 2.1 hours against 15 ms.
Left: the arrowhead, cameras then points; the warm block is S after the points are eliminated. Right: flops for each route, on a log scale. Move the sliders.
Illustrative flop model: direct = n³/3; Schur = forming S (108k + 216k² flops per point) plus factoring S, (6C)³/3. Times assume 10 GFLOP/s, a single embedded core. Our counts, not a benchmark.
Ceres names this choice in one option: linear_solver_type = DENSE_SCHUR, SPARSE_SCHUR or ITERATIVE_SCHUR. For thousands of cameras, even S is too big to factor, so ITERATIVE_SCHUR solves it with conjugate gradients and a SCHUR_JACOBI preconditioner. Visual SLAM systems run a small local bundle adjustment often and a pose graph (Chapter 2) after a loop closure.
Symptom: bundle adjustment runs at 50 cameras and stalls at 500.
Measure: the solver's timing report: the linear solve, not the Jacobians, takes the time.
Fix: pick a Schur solver, which eliminates the points first; above about a thousand cameras, the iterative Schur solver.
Chapter 5
Price the dense prior a window leaves behind, and watch one frozen slope go wrong
A visual-inertial odometry system cannot keep every keyframe either. It keeps a sliding window of the last few, say 10, and marginalises the oldest when a new one arrives. Chapter 3 says its information survives, as a prior on the states that touched it. That prior is dense. A keyframe that saw 30 landmarks, plus its 2 neighbours, couples 32 states: 32 × 31/2 = 496 pairs.
The bigger price is hidden. The prior is a fixed quadratic, built from Jacobians evaluated at the estimate of that moment. Its measurements are gone, so nothing can relinearise it. A filter does this on every update.
How much can one frozen slope cost? A robot on a track measures its range to a beacon 3 m to the side. The robot is at x = 4 m, so the range is 5 m, and the sensor reads z = 5 m with σ = 0.2 m. The guess is x̂ = 1 m.
h(x) = √(x² + 9); slope J = x / √(x² + 9). At x̂ = 1: h = 3.162, J = 0.316, residual r = h − z = −1.838.
A filter takes one step with that slope: δ = −r/J = 5.81, so x̂ = 6.81 m. It reports σ = 1/√(J²/0.2²) = 0.63 m. The truth is 2.81 m away, 4.5 of its own σ. A smoother keeps z and relinearises: 6.811, 4.142, 4.001, then 4.000 m. At the answer the slope is 0.8, so σ = 0.25 m.
The curve is the range h(x). The yellow line is the measurement. The warm line is the straight-line model at the current linearisation point. Pick a backend and step it.
Illustrative 1-D example: beacon 3 m off the track, z = 5 m, σ = 0.2 m, first guess 1 m, no prior. The filter re-uses the slope from the first guess; the smoother evaluates it at each new estimate.
Frozen slopes do worse in SLAM. Jacobians evaluated at different estimates let the linearised system believe it can see the global heading, which no relative measurement can see. Huang, Mourikis and Roumeliotis (IJRR 2010) showed this is why EKF SLAM becomes overconfident. Their fix, first-estimates Jacobians (FEJ), evaluates every Jacobian of a state at its first estimate, so the blind directions stay blind.
Symptom: after many laps, the filter reports a heading σ far smaller than its true heading error.
Measure: the rank of the stacked Jacobian. A 2-D SLAM problem must leave 3 directions free (x, y, heading). If only 2 are free, the heading is being “measured”.
Fix: FEJ, or a smoother that relinearises. Raising the process noise cannot fix a rank error.
Chapter 6
Watch Gauss-Newton overshoot by ten thousand times, then damp the step and check it before keeping it
Gauss-Newton trusts its straight-line model completely. Far from the answer, that can be a disaster. Take one residual r(x) = x² − 4, with the answer at x = 2, and start at x = 0.1. There the slope is J = 0.2, so the model says: move 3.99/0.2 = 19.95. The new x is 20.05, and the cost ½r² rises from 7.96 to 79,203.
Levenberg-Marquardt (LM) adds damping and checks each step before keeping it. Call the damping strength λ, and the diagonal of Λ D:
Lambda plus lambda D, times delta, equals eta.
Solve the damped system for delta and try the step. If the cost falls, keep it and divide small lambda by 10. If the cost rises, throw the step away, multiply small lambda by 10, and solve again from the same point.
At x = 0.1 with small lambda = 100: delta = 0.798 / (0.04 × 101) = 0.1975. The cost falls from 7.960 to 7.650, so the step is kept and small lambda drops to 10. After five kept steps, x = 1.99994.
The curve is the cost ½(x² − 4)². The purple dot is the estimate, the warm arrow the proposed step. Pick a method and step it.
Exact arithmetic on the one-unknown example: r(x) = x² − 4, start x = 0.1, λ starts at 100 and moves by factors of 10.
With small λ the step is pure Gauss-Newton, fast near the answer. With large λ it is a short step downhill: slow, but it cannot overshoot. Ceres and GTSAM both offer LM. Both also offer Powell's dogleg, which keeps a trust radius instead; a rejected dogleg step needs no new factorisation, only a smaller radius.
Symptom: the cost explodes on the first iteration of a fresh map.
Measure: the iteration log: cost before and after each step, and how often steps are rejected.
Fix: use LM or dogleg, and start from a better guess, such as the dead-reckoned chain.
Chapter 7
Let a wrong loop closure bend the map, then weight it down by the size of its residual
Loop closures come from place recognition (Lesson 8), and some are wrong. Two aisles can look alike. A false closure with σ = 2 cm is a confident lie, and least squares believes it. In the device, one false link between poses 2 and 10 bends the hero's lap to 2.49 m RMS error.
A robust kernel gives each loop factor a weight that falls as its residual grows (Lesson 3 compares the kernels). Measure the residual in units of its σ and square it: call that s, so s = rTWr. Call the kernel scale c. The Cauchy kernel weights the factor by:
w equals one over one plus s over c squared.
At the current guess, find each loop factor's residual in units of its σ and square it: that is s. Compute w. Multiply the factor's contribution to Lambda and eta by w. Recompute every w at the next iteration.
From our simulation at c = 3: the true closure ends with s = 0.53, so w = 1/(1 + 0.53/9) = 0.94. The false closure ends with w = 0.0001, because its residual is metres against σ = 2 cm. RMS error 0.124 m, the same as with no false closure at all.
Pink is the true lap, purple the solved one. The blue link is the true closure; the false link turns red if the solver believes it. Pick a kernel scale.
The hero's seeded lap at 1.5° of drift per step, solved live with iteratively reweighted Gauss-Newton from the dead-reckoned guess. The kernel acts on loop factors only.
The scale c is a trade, and the device shows both ends. At c = 1 the true closure starts 1.13 m off, so it also gets w = 0.0002, and the map stays drifted at 0.57 m. At c = 100 the false closure keeps w = 0.94 and the map bends to 2.48 m. A kernel needs a decent first guess. Switchable constraints and graduated non-convexity widen the safe range (VNAV Lecture 14).
Symptom: one new loop closure warps the whole map.
Measure: after solving, each loop factor's whitened residual √s. A false closure sits tens of σ out while every odometry factor sits near 1.
Fix: a Cauchy or Huber kernel on loop factors, with a scale of a few σ, and a geometric check of each closure before it enters the graph.
Chapter 8
Sum the IMU samples once, in the frame of the first keyframe, and reuse the sum from any start
An IMU reports acceleration at 200 Hz; keyframes come at about 4 Hz. So 50 samples sit between two keyframes. One state per sample would turn a 10-keyframe window into 500 states of 15 numbers: 7,500 unknowns instead of 150.
So the IMU should give one factor between keyframes. But integrating from keyframe i needs its position, velocity and orientation, and the optimiser changes those at every iteration.
Preintegration writes the sum in the body frame of keyframe i, so the state of i factors out of it. Lupton and Sukkarieh introduced it (IEEE T-RO, 2012); Forster et al. put it on the rotation manifold (RSS 2015). In one dimension, with no rotation and no gravity, call an accelerometer sample ak, the bias b and the sample period Δt:
Delta-v equals the sum over k of a-k minus b, times delta-t. Delta-p equals the sum over k of delta-v-k times delta-t, plus one half of a-k minus b, times delta-t squared.
Subtract the bias b from each sample. Add up acceleration times delta-t: that is delta-v. For delta-p, each step adds the velocity gained so far times delta-t, plus half its acceleration times delta-t squared.
With made-up samples 1.00, 1.20, 0.80 and 1.00 m/s², b = 0.10 and delta-t = 0.01 s: delta-v = 3.60 × 0.01 = 0.036 m/s, and delta-p = 0.00074 m. From p₀ = 5.0 m and v₀ = 2.0 m/s, the end position is 5.0 + 2.0 × 0.04 + 0.00074 = 5.08074 m. Direct integration gives the same.
Neither delta contains p₀ or v₀, so the optimiser can move keyframe i freely. Only the bias is inside. When the optimiser changes it by δb, a first-order correction replaces re-integration. Over the window T = 0.04 s, ∂Δv/∂b = −T = −0.04 and ∂Δp/∂b = −T²/2 = −0.0008. For δb = 0.02, Δv = 0.0352 and Δp = 0.000724, equal to re-integrating.
Left: the four blue samples and the yellow bias line. Right: the position over the window from your start. Blue dots integrate the raw samples; the purple ring is the one-line answer. Move the start, then the bias.
Illustrative samples from the Code Lab, 100 Hz. In one dimension the bias enters linearly, so the first-order correction is exact here; on rotations it is approximate.
In the lab, write the four accumulation lines.
Symptom: visual-inertial scale drifts on a long straight road at constant speed.
Measure: the spread of the measured acceleration over the window. Near zero means no excitation.
Fix: at constant velocity, a scale error and an accelerometer bias produce the same measurements. Accelerate or turn, or add wheel odometry or GNSS for scale.
Chapter 9
Choose an elimination order and watch the fill-in, then add a loop closure and count what must be redone
A real backend solves Λδ = η with a sparse Cholesky factorisation, Λ = LLT, where L is lower-triangular. The answer does not depend on the order in which unknowns are eliminated. The cost does. Each elimination couples its remaining neighbours (Chapter 3), and those new entries, the fill-in, land in L. A fill-reducing ordering, such as AMD or COLAMD, eliminates low-degree unknowns first.
The second idea is incremental solving. When a new loop closure arrives, only some columns of L change. They are the columns of the two linked poses and the columns that depend on them. iSAM (Kaess and colleagues, 2008) and iSAM2 (2012) update just those. iSAM2 also relinearises a variable only when its estimate has moved past a threshold.
The inspector builds a pose graph. A robot drives laps of 20 poses, and a loop closure links a pose to the same place one lap earlier. Pick the size, the closures and the order. Then add one more closure and count the columns that change.
Left: the graph, teal poses, grey odometry, blue loop closures. Right: the factor L, purple where Λ had an entry, warm for fill-in. Turn on the new closure to see which columns change.
Illustrative graph, one scalar per pose so each cell is one entry. Fill-in and changed columns are computed live by a dense Cholesky on the permuted Λ; our NumPy port gives the same counts. Minimum degree breaks ties by the lower index; the random order is seeded. Work is the sum of squared column counts of L.
Take 120 poses and a closure every 5. Time order gives 619 nonzeros in L and 3,369 units of work. Minimum degree gives 386 and 1,306. A random order gives 860 and 10,726. A new closure 20 poses back changes 21 columns in time order, at any map size. The update cost tracks how far back the loop reaches, not how big the map is.
The same holds at scale. On our laptop, a 7,200-unknown pose graph took 442 ms with a dense Cholesky and 20 ms with scipy's sparse LU. The two answers agreed to 3.5 × 10−10. A 5,000-pose 3-D graph with 800 closures has 597,528 nonzeros among 9 × 108 cells: 0.066%.
Symptom: the solve went from 20 ms to several seconds, and the answer is identical.
Measure: the nonzero count of L and the ordering method in the solver's log.
Fix: restore a fill-reducing ordering. A changed config or a new variable key order fed to a natural ordering causes this.
Chapter 10
Keep the backend table, the core code and the checks in one place
A smoother keeps the past, and it can afford to because its information matrix is as sparse as its measurements. Each factor deposits four blocks. Gauss-Newton solves Λδ = η and shares a loop error by variance. Marginalisation is an exact Schur complement that fills in among the dropped variable's neighbours and freezes a linearisation. LM damps the step, and a robust kernel weights down false closures. Preintegration turns fifty IMU samples into one factor, and a good ordering keeps the factorisation sparse.
| Backend | Keeps | Relinearises | Where it wins |
|---|---|---|---|
| EKF SLAM | current pose and all landmarks, dense Σ | never | teaching, and small maps |
| MSCKF filter | a short window of cloned poses; landmarks used and dropped at once | no; FEJ keeps the blind directions blind | low-power odometry without loop closures (OpenVINS) |
| Fixed-lag smoother | the last K keyframes plus a dense marginalisation prior | inside the window | visual-inertial odometry (VINS-Mono, OKVIS) |
| Full smoother | every pose and landmark | yes, where estimates moved (iSAM2) | mapping, anything that revisits |
python import numpy as np def add_between(Lam, eta, x, i, j, meas, sigma): """1-D factor r = (x_j - x_i) - meas. J = [-1, +1]: four entries of Lam, two of eta.""" w = 1.0 / sigma ** 2; r = (x[j] - x[i]) - meas Lam[i, i] += w; Lam[j, j] += w; Lam[i, j] -= w; Lam[j, i] -= w eta[i] += w * r; eta[j] -= w * r def marginalize(Lam, eta, drop): """Schur complement: exact for the linear system; fills in among drop's neighbours.""" keep = [i for i in range(len(eta)) if i not in drop] Laa, Lba = Lam[np.ix_(drop, drop)], Lam[np.ix_(keep, drop)] X = np.linalg.solve(Laa, Lam[np.ix_(drop, keep)]) # never form an inverse y = np.linalg.solve(Laa, eta[drop]) return Lam[np.ix_(keep, keep)] - Lba @ X, eta[keep] - Lba @ y def lm_step(Lam, eta, lam): """Levenberg-Marquardt: damp by lam times the diagonal of Lam.""" return np.linalg.solve(Lam + lam * np.diag(np.diag(Lam)), eta) def cauchy_weight(r, sigma, c): """Weight for a loop factor: s is the residual in sigma units, squared.""" s = np.sum((np.asarray(r) / sigma) ** 2) return 1.0 / (1.0 + s / c ** 2) def preintegrate(acc, b, dt): """1-D deltas and their bias Jacobians, one pass, independent of the start state.""" dv = dp = Jv = Jp = 0.0 for a in acc: f = a - b dp += dv * dt + 0.5 * f * dt * dt; Jp += Jv * dt - 0.5 * dt * dt dv += f * dt; Jv -= dt return dv, dp, Jv, Jp
We ran every function above on this lesson's examples:
| Library | Model | Reach for it when |
|---|---|---|
| GTSAM | factor graphs on Lie groups; iSAM2 and the Bayes tree | the problem grows over time and you want marginals |
| Ceres | general nonlinear least squares; Schur solvers; automatic derivatives | batch problems such as bundle adjustment |
| g2o | graph optimisation with block solvers (ICRA 2011) | compact pose graphs and BA embedded in a SLAM system |
Now teach it: press Present or Teach and explain why a filter cannot fix pose 8 after the loop closes, and why a smoother can afford to. Then go back to the lap, set the drift to 3°, and predict the filter's error before you switch.