AnyLearn
All lessons
Roboticsadvanced

SLAM: Simultaneous Localization and Mapping

The chicken-and-egg problem of robot autonomy: to localise you need a map; to build a map you need a pose. Covers front-end matching, back-end pose-graph optimisation, loop closure, and visual vs LiDAR SLAM systems.

Not signed in โ€” your progress and quiz score won't be saved.
Lesson progress1 / 9

The chicken-and-egg problem

To localise, a robot needs a map. To build a map, it needs to know where it is. This circularity is the SLAM problem โ€” Simultaneous Localization and Mapping. It was considered intractable until Smith, Self, and Cheeseman (1986) showed that joint estimation of all poses and landmarks in a probabilistic framework is consistent.

Formally: given a sequence of control inputs u1:t\mathbf{u}_{1:t} and observations z1:t\mathbf{z}_{1:t}, compute the joint posterior over all robot poses x1:t\mathbf{x}_{1:t} and the map M\mathcal{M}:

p(x1:t,Mโˆฃz1:t,u1:t)p(\mathbf{x}_{1:t}, \mathcal{M} \mid \mathbf{z}_{1:t}, \mathbf{u}_{1:t})

This joint posterior is far too large to represent exactly โ€” a 1 km trajectory with a dense 3D map has millions of variables. All practical SLAM systems approximate it, with a key architectural split between the front end (data association) and the back end (optimisation).

Full lesson text

All 9 steps on one page โ€” for reading, reference, and search.

Show

1. The chicken-and-egg problem

To localise, a robot needs a map. To build a map, it needs to know where it is. This circularity is the SLAM problem โ€” Simultaneous Localization and Mapping. It was considered intractable until Smith, Self, and Cheeseman (1986) showed that joint estimation of all poses and landmarks in a probabilistic framework is consistent.

Formally: given a sequence of control inputs u1:t\mathbf{u}_{1:t} and observations z1:t\mathbf{z}_{1:t}, compute the joint posterior over all robot poses x1:t\mathbf{x}_{1:t} and the map M\mathcal{M}:

p(x1:t,Mโˆฃz1:t,u1:t)p(\mathbf{x}_{1:t}, \mathcal{M} \mid \mathbf{z}_{1:t}, \mathbf{u}_{1:t})

This joint posterior is far too large to represent exactly โ€” a 1 km trajectory with a dense 3D map has millions of variables. All practical SLAM systems approximate it, with a key architectural split between the front end (data association) and the back end (optimisation).

2. Front end: odometry and data association

The front end ingests raw sensor data and produces relative pose constraints between frames. For visual SLAM: detect features โ†’\rightarrow match across frames โ†’\rightarrow estimate relative pose via the essential matrix or PnP. For LiDAR SLAM: downsample โ†’\rightarrow register scans via ICP or NDT.

The critical output is a keyframe graph: a sparse set of frames (selected when robot motion exceeds a threshold) connected by relative pose edges T^ij\hat{T}_{ij} with associated covariance ฮฃij\Sigma_{ij}. Front-end quality determines everything downstream โ€” a wrong data association creates a spurious edge that the back end cannot fully correct.

Data association is hardest at revisit: when the robot returns to a previously seen place, it must recognise it (loop closure) without confusing it with a superficially similar location (perceptual aliasing). A corridor of identical doors is the canonical failure scenario.

3. Back end: pose-graph optimisation

The back end takes the keyframe graph and finds robot poses {Ti}\{T_i\} that are maximally consistent with all edge constraints. This is a nonlinear least-squares problem:

minโก{Ti}โˆ‘(i,j)โˆˆEโˆฅlogโก(T^ijโˆ’1โ‹…Tiโˆ’1Tj)โˆฅฮฃijโˆ’12\min_{\{T_i\}} \sum_{(i,j) \in \mathcal{E}} \left\| \log\left(\hat{T}_{ij}^{-1} \cdot T_i^{-1} T_j\right) \right\|_{\Sigma_{ij}^{-1}}^2

where logโก(โ‹…)\log(\cdot) maps a SE(3)SE(3) transform to its Lie algebra se(3)\mathfrak{se}(3) (a 6-vector), and โˆฅโ‹…โˆฅฮฃโˆ’12\|\cdot\|_{\Sigma^{-1}}^2 is the Mahalanobis norm weighting by edge confidence. Standard solvers: g2o, GTSAM, Ceres. All exploit the sparsity of the Hessian (each pose only connects to a few neighbours) via sparse Cholesky factorisation or incremental QR. A 1000-keyframe graph optimises in milliseconds. The back end is the glue that prevents drift: without it, odometry errors compound linearly; with it, a loop closure can globally correct the entire trajectory.

4. Loop closure: detecting revisited places

Loop closure is the event that resets drift. The robot returns to a previously mapped region and recognises it, adding a long-range edge to the pose graph. The back-end re-optimises and the trajectory snaps into global consistency.

For visual SLAM, loop closure uses bag-of-words (BoW) retrieval: a vocabulary tree of visual words (quantised SIFT/ORB descriptors) indexes all keyframes; query the current frame, find candidates above a similarity threshold, verify geometrically with RANSAC. DBoW2 and FBoW are standard libraries. For LiDAR SLAM, histogram-based descriptors (SCAN-CONTEXT, intensity-scan-context) encode the 3D structure compactly for fast retrieval.

False positives are catastrophic: a wrong loop closure introduces a large incorrect edge; the optimiser distorts the entire map. Always gate with a geometric verification step (essential matrix or ICP check) before inserting a loop edge. A conservative policy (miss some loops, accept no false ones) is safer for production robots.

5. Filter-based vs graph-based SLAM

Two historical approaches:

PropertyFilter-based (EKF-SLAM)Graph-based SLAM
State representationJoint Gaussian over all poses and landmarksSparse pose graph + loop closure edges
Update complexityO(n2)O(n^2) per update (nn = landmarks)O(k)O(k) front end, O(n)O(n) to O(n1.5)O(n^{1.5}) back end
Loop closureHard โ€” re-linearises the whole stateNatural โ€” add an edge, re-optimise
MemoryFull covariance matrix grows with n2n^2Sparse; scales to millions of nodes
AccuracyLinearisation error accumulates, inconsistent at scaleIterative nonlinear solvers more accurate

EKF-SLAM was the dominant method in the 1990s-2000s (indoor, small maps). Graph-based SLAM (Grisetti et al., 2010) took over for large-scale autonomy and is now the industry standard. Filter methods survive in tightly coupled IMU-SLAM pipelines where their predict step integrates naturally.

6. SLAM pipeline: front end to back end

How raw sensor data becomes a consistent global map.

flowchart TD
  S["Sensor data camera or LiDAR"]
  FE["Front end: odometry and feature matching"]
  KF["Keyframe selection"]
  PG["Pose graph: nodes and odometry edges"]
  LC["Loop closure detection BoW or ScanContext"]
  GV["Geometric verification RANSAC or ICP"]
  LE["Loop edge added to graph"]
  BE["Back end: nonlinear least squares g2o or GTSAM"]
  MAP["Globally consistent map and trajectory"]
  S --> FE
  FE --> KF
  KF --> PG
  KF --> LC
  LC --> GV
  GV --> LE
  LE --> PG
  PG --> BE
  BE --> MAP

7. Visual SLAM: ORB-SLAM3

ORB-SLAM3 (Campos et al., 2021) is the most widely-used visual SLAM system in robotics research. Architecture:

  • Tracking thread: estimates camera pose frame-by-frame using ORB feature matching against local map points and motion-only BA (bundle adjustment).
  • Local mapping thread: adds new keyframes, triangulates new map points, runs local BA over the active window.
  • Loop and map merging thread: detects loop closures via DBoW3, verifies with essential matrix, adds loop edges, and triggers Essential Graph optimisation โ€” a sparse subgraph of strong edges for fast global correction.
  • Atlas: supports multiple maps that can be merged when previously disconnected sessions are revisited.

ORB-SLAM3 supports monocular, stereo, RGB-D, and IMU modes. Key limitation: it struggles in low-texture environments (white walls, outdoor fields) and fails catastrophically when the number of tracked features drops below ~15. It is not robust to fast motion blur.

8. LiDAR SLAM: Cartographer and LOAM

Two dominant LiDAR SLAM systems:

Google Cartographer (Hess et al., 2016): 2D/3D LiDAR + IMU. Front end uses scan-to-submap matching via branch-and-bound scan matching. Back end: pose-graph with loop closure using histogram-based scan descriptors. Landmark paper for warehouse robots and building mapping. Very robust in structured indoor environments.

LOAM / LeGO-LOAM (Zhang & Singh, 2014): extracts edge and planar feature points from LiDAR scans based on local curvature, registers edges-to-edges and planes-to-planes. The feature factorisation is the key to robustness in degenerate environments. LeGO-LOAM adds ground segmentation and runs on embedded hardware. LIO-SAM extends this with IMU preintegration and loop closure.

# Pseudo-code: LOAM feature extraction
for ring in scan.rings:
    curvature = compute_curvature(ring)          # second difference
    edge_pts  = ring[curvature > thresh_high]    # sharp features
    plane_pts = ring[curvature < thresh_low]     # smooth features
    register_edges_and_planes(edge_pts, plane_pts, local_map)

Comparison: Cartographer wins indoors; LOAM variants win outdoors and in autonomous driving.

9. Drift, failure modes, and production reality

SLAM is not a solved problem. Honest failure modes:

Failure modeCauseMitigation
Unbounded driftNo loop closure, open-ended trajectoryAccept drift or add GPS
Wrong loop closurePerceptual aliasing (identical-looking places)Conservative BoW threshold + geometric verification
Map inconsistencyDynamics (moving people, cars) treated as staticDynamic object filtering, SLAM with dynamics
Tracking lossTexture-less / dark environment, rapid motionIMU integration, active illumination
Scale drift (monocular)Scale unobservable from bearing aloneFuse IMU or use stereo

For production deployment: (1) always fuse SLAM with a localisation layer (map matching against a prior HD map); (2) monitor SLAM health with covariance trace and inlier count; (3) degrade gracefully โ€” a robot that knows it is lost and stops is safer than one that confidently navigates to the wrong place. The best SLAM systems fail loudly.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. The SLAM back end minimises a sum of squared Mahalanobis errors over pose-graph edges. Why is sparse Cholesky factorisation the key to making this tractable?
    • Sparse Cholesky avoids computing the loop closure descriptors by reusing cached factorised subgraphs.
    • The Hessian of the pose-graph cost is sparse because each pose connects to only a few neighbours, so sparse factorisation scales nearly linearly with graph size.
    • Sparse Cholesky converts the SE(3) optimisation into a convex problem that has a unique global minimum.
    • Cholesky factorisation is required to compute the Kalman gain inside the back-end filter.
  2. Perceptual aliasing in loop closure detection refers to:
    • Sensor time-stamps being misaligned, causing false keyframe associations.
    • Two geometrically distinct places looking similar, causing the loop closure detector to add a wrong edge.
    • The BoW vocabulary being too small to distinguish visual words from different environments.
    • The robot revisiting a place at a different time of day, causing illumination-based descriptor mismatch.
  3. ORB-SLAM3 loses tracking and reinitialises. The most likely cause in an indoor office environment is:
    • The pose-graph has exceeded 10,000 keyframes and g2o optimisation is too slow.
    • The number of tracked ORB features drops below the minimum threshold, typically due to a textureless surface or rapid motion blur.
    • The DBoW3 vocabulary tree has not been trained on office images.
    • Loop closure inserted a wrong edge that moved all keyframes out of the camera frustum.
  4. Why did graph-based SLAM replace EKF-SLAM for large-scale mapping?
    • Graph-based SLAM avoids any linearisation of the state equations, making it exact.
    • EKF-SLAM requires storing a full $n \times n$ joint covariance that grows quadratically with the number of landmarks, making it impractical at scale.
    • Graph-based SLAM uses Gaussian process regression instead of Bayes filters, which is asymptotically unbiased.
    • EKF-SLAM cannot incorporate loop closures because the filter formulation does not allow adding new constraints.
  5. LOAM extracts edge and plane features from LiDAR scans rather than running raw ICP. What is the main advantage?
    • Feature extraction reduces the point cloud to a range image, enabling 2D convolutions.
    • Matching geometrically distinct features avoids the flat-floor degeneracy that makes raw ICP fail in open outdoor scenes.
    • BoW retrieval of edge features enables faster loop closure than scan-context histograms.
    • Edge features are invariant to LiDAR beam divergence and therefore require no intensity calibration.

Related lessons

Robotics
beginner

Sensors: How Robots Perceive

A robot is only as good as what it can measure. Explore the full sensor toolkit โ€” encoders, IMUs, ultrasonic rangefinders, LiDAR, cameras, and force/torque sensors โ€” and learn the four metrics that determine whether a sensor is fit for purpose: resolution, range, noise, and sampling rate.

10 stepsยท~15 minยทaudio
AI
advanced

Reinforcement Learning in 2026: Where It Ships and Where It Stalls

An honest map of RL in 2026 โ€” the domains where it actually reaches production (LLM post-training, robotics policies, ad bidding, RLHF, reasoning models) and the places where it still cannot reliably cross the lab-to-deployment gap.

12 stepsยท~18 minยทaudio
Robotics
beginner

Closing the Loop: Microcontrollers and Feedback

Open-loop control is a guess; closed-loop control is a conversation. Learn why feedback transforms an unreliable robot into a reliable one, how the read-compute-actuate cycle works, what microcontrollers and single-board computers each do best, and why loop timing is just as critical as the algorithm running inside it.

10 stepsยท~15 minยทaudio
Robotics
beginner

What Is a Robot? Anatomy and the Sense-Plan-Act Loop

Strip any robot to its bones and you find three things: sensors that gather data, a controller that thinks, and actuators that move. Learn how these pieces fit together through the Sense-Plan-Act paradigm, why reactive control sometimes beats planning, and what makes a Roomba and a welding arm both qualify as robots.

10 stepsยท~15 minยทaudio