How a Robot Senses: LiDAR, IMU and ICP

Wheels and gyros count motion, and their small errors add up with no limit. A laser scan of the walls, matched to a map, pulls the estimate back. In the toy below, a 0.5% wheel error leaves the estimate 0.6 m off after one lap. With scan matching, it stays about 1 cm off.

Pick wheels only or scan matching, set the wheel error, and watch the purple estimate against the teal robot. Then we build each piece: the error model, encoders, the IMU, LiDAR, point clouds, line fitting, ICP and fusion.

You need a little trigonometry and a little Python. We build the rest from zero.

Lesson 7 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 6, Trajectory Tracking. Next: Lesson 8, Camera Models.

Drive laps and watch the estimate

0.5%

Illustrative toy: a 10 m by 6 m room and a 17.4 m loop. The robot drives the loop exactly; only its estimate drifts. Odometry assumes the nominal wheel radius and adds 0.4% random slip. Scan matching runs real ICP once a second on 72 beams against a map of the walls.

Chapter 0

Every Sensor Lies a Little

Fire a range sensor at a wall and split its error into two parts

A robot points a laser at a wall 2.00 m away. It reads 2.03 m. Then 1.96 m, then 2.11 m. No reading is the truth, and the robot never sees the truth directly.

Every fact the robot holds enters through a sensor: a device that turns a physical quantity into a number. That number carries two kinds of error, and they need different cures.

Call the true distance v and the reading m. A bias, b, is a fixed offset that is the same on every reading. Noise, ε (epsilon), is a random jitter that changes on every reading. Its typical size is the standard deviation σ (sigma).

Say it aloud

m equals v plus b plus epsilon, where epsilon is drawn from a normal distribution with mean zero and variance sigma squared.

m
m the measurement: the number the sensor reports, in metres.
v
v the true value: here the real distance to the wall.
b
b the bias: the same offset on every reading. Calibration can find it.
ε
epsilon the noise: a fresh random number on each reading.
~ N(0, σ2)
is drawn from a normal with mean zero and variance sigma squared a bell curve centred on zero; sigma sets its width.
In plain words

Start from the true value v. Add the same bias b every time. Add a new random noise epsilon every time. The sum is the reading m.

With numbers

With made-up numbers: v = 2.00 m, b = +0.05 m, and this time ε = −0.02 m. Then m = 2.00 + 0.05 − 0.02 = 2.03 m.

Fire readings at one wall

Press Stream for 30 readings. Raise the noise and the dots spread. Raise the bias and the whole cloud slides away from the pink truth.

0.12 m
+0.05 m

Illustrative sensor. The noise is Gaussian; real sensors can have one-sided errors, such as sonar echoes off a slanted wall.

Work the number. Average 100 readings with σ = 0.12 m. The noise left in the average is 0.12 / √100 = 0.012 m. The bias stays at 0.05 m for any number of readings. Averaging beats noise. Only an outside reference beats bias.

WordMeansSet by
Accuratethe average sits on the truthsmall bias b
Precisereadings cluster tightlysmall noise σ

The failure, as symptom, measurement and fix

The symptom is a robot that stops 5 cm short of every wall. To measure it, put a target at a taped distance, take 100 readings and compare their mean with the tape. The fix is to subtract that bias in software, and to check it again when the temperature changes.

The road

  1. The sensor zoo: two questions that sort every sensor.
  2. Encoders and odometry: counting wheel turns, and why the count drifts.
  3. The IMU: a gyro bias that grows into a wrong heading.
  4. LiDAR: timing light, and turning a scan into points.
  5. Point clouds: shrink the cloud, then find the nearest point.
  6. Line extraction: fit walls with split-and-merge.
  7. ICP, one iteration: centroids, the SVD, R and t, by hand.
  8. ICP, live: the hero's scan matcher, step by step, and how it fails.
  9. Fusion: trust each sensor by its variance.
  10. The field guide: terms, numbers, code and the credit.
A range sensor reads 2.20 m every time; the wall is at 2.00 m. Will averaging many readings fix it?

Chapter 1

The Sensor Zoo: Two Questions

Drop each sensor into a two-by-two grid and read its typical failure

A delivery robot might carry wheel encoders, a gyro, a laser scanner and two cameras. Two questions sort all of them.

  1. What does it measure: me, or the world? A proprioceptive sensor measures the robot itself: wheel turns, rotation rate, battery voltage. An exteroceptive sensor measures the world: the distance to a wall, the light from a scene.
  2. Does it listen, or does it shout? A passive sensor takes in energy that is already there, like a camera taking in light. An active sensor sends out its own energy and measures what comes back, like a laser timing its echo.

Sort a sensor into the grid

Tap a sensor. It lights in its cell, and the read-out says what it measures and how it usually fails.

Teal chips measure the robot; blue chips measure the world. The cell is where most textbooks put the common version of each sensor.

The split predicts the error. A proprioceptive sensor works in a clean, known place, so its errors are mostly bias, and calibration removes them. An exteroceptive sensor faces a messy world, so it needs interpretation (is this blob a wall?) and carries more random error.

One camera fact matters now. A plain camera measures the direction to a point, not its distance: one pixel stands for a whole ray. An RGB-D camera adds a depth value to every pixel with an active trick, a projected pattern or a small time-of-flight ranger. Lesson 8 builds the camera model.

Datasheets add a few more words. Resolution is the smallest change a sensor can tell apart. Bandwidth is how many readings it gives per second. Work the number: a LiDAR at 10 Hz on a robot at 2 m/s gives one scan every 2 / 10 = 0.2 m of travel. The robot is blind between scans.

The failure, as symptom, measurement and fix

The symptom is a heading that jumps each time the robot passes a steel shelf. This is cross-sensitivity: the compass also responds to nearby iron. To measure it, log the compass and the gyro heading side by side along the aisle. The fix is to give the compass low weight indoors, or drop it.

A LiDAR fires a laser pulse and times the echo. Where does it go in the grid?

Chapter 2

Wheel Encoders and Odometry

Count wheel turns, add them up, and watch a 1% error bend the path

The cheapest way for a wheeled robot to know where it is: count how far each wheel turned. A wheel encoder does the counting. An optical encoder shines its own small light through slits in a disc on the axle, and a detector counts the flashes. Adding the counts into a pose is odometry, also called dead reckoning.

Say the disc has 2,000 slits. A second detector, offset by a quarter slit, gives the direction of turn and four countable edges per slit. This is quadrature: 8,000 counts per turn. With a wheel of radius 0.05 m, one turn rolls 2π × 0.05 = 0.314 m, so one count is 0.314 / 8,000 = 0.039 mm. A step of 400 counts is 1.57 cm.

A differential-drive robot has two driven wheels on one axle. Call the distance the right wheel rolls in one step ΔsR, the left one ΔsL, and the distance between the wheels L. The robot's forward step is the average of the two. Its turn, Δθ, comes from their difference.

Say it aloud

Delta theta equals delta s R minus delta s L, all divided by L.

Δθ
delta theta the change in heading over one step, in radians. Positive turns left.
ΔsR
delta s R how far the right wheel rolled this step, in metres: counts times distance per count.
ΔsL
delta s L how far the left wheel rolled this step.
L
L the wheelbase: the distance between the two wheels, in metres.
In plain words

Take how much farther the right wheel rolled than the left, delta s R minus delta s L. Divide by the wheelbase L. The result is the turn delta theta. Then move the pose forward by the average roll along the heading.

With numbers

With made-up numbers: ΔsR = 0.0160 m, ΔsL = 0.0154 m, L = 0.30 m. Δθ = 0.0006 / 0.30 = 0.002 rad, or 0.11° to the left. The forward step is 0.0157 m.

Drive a square on odometry

The robot steers by its own estimate, so the purple estimate stays on the warm plan. Press Drive and watch where the teal robot truly goes.

1.0%
1.0%

Illustrative toy: a 3 m square, wheelbase 0.30 m, steps of 1 cm. The wheel error and the slip apply to the true motion; the estimate assumes perfect wheels.

Why does it bend? Take only the 1% wheel error, L = 0.30 m, and a robot that believes it drives straight. Each metre, the right wheel rolls 1 cm more than the robot thinks, so the true heading turns 0.01 / 0.30 = 0.033 rad, or 1.9°. The heading error feeds the position error, and it compounds:

Believed distanceHeading errorSideways error
1 m1.9°0.02 m
3 m5.7°0.15 m
5 m9.5°0.42 m

The failure, as symptom, measurement and fix

The symptom is a robot that ends a closed loop far from where it started, sure that it is home. To measure it, drive a taped square both ways and measure the gap at the end. The fix has two parts: calibrate the wheel radii and the wheelbase, then correct the pose with an outside reference, such as a LiDAR scan.

Why does odometry error grow without limit, even with a near-perfect encoder?

Chapter 3

The IMU: Fast, Self-Contained, Drifting

Leave a still robot with a biased gyro and watch its heading walk away

An inertial measurement unit (IMU) is the chip that knows your phone turned. It holds two kinds of sensor. A gyroscope measures the rate of turn, in degrees per second. An accelerometer measures acceleration. Both are proprioceptive, need nothing outside, and report hundreds of times a second.

A gyro gives a rate, not an angle. To get a heading, the robot adds up rate × time, again and again. That is integration, and it keeps every error.

Picture a robot parked on a table. Its true rate of turn is zero. The gyro has a constant bias b, in degrees per second. Call the starting heading θ0 and the heading estimate after t seconds θ(t).

Say it aloud

Theta of t equals theta zero plus b times t.

θ(t)
theta of t the heading the robot believes after t seconds, in degrees.
θ0
theta zero the heading at the start, which was correct.
b
b the gyro bias: the rate it reports when nothing turns, in degrees per second.
t
t the time since the start, in seconds.
In plain words

Each second, the integration adds the bias b to the heading. After t seconds it has added b times t. The error grows in a straight line with time and never stops.

With numbers

With a made-up b = 0.5°/s: after t = 60 s the error is 0.5 × 60 = 30°. After 360 s it is 180°. The parked robot thinks it faces backwards.

Integrate a biased gyro

Press Run to let six minutes pass in a few seconds. The purple estimate creeps away from the teal truth at exactly bias × time. Choose Turn to add a real rotation.

0.5°/s

Illustrative bias values; a real gyro's bias also wanders slowly and changes with temperature. Simulated time runs 60 times faster than real time.

The accelerometer has its own trap. At rest it reads 9.81 m/s² upward: it feels the table pushing against gravity. To get the robot's motion, the robot must subtract gravity, so it must know its tilt. Tilt comes from the gyro. Work the number: a tilt error of 1° leaves 9.81 × sin 1° = 0.17 m/s² of false acceleration. Integrated twice, that is ½ × 0.17 × 10² = 8.6 m of position error after 10 s.

So gyro error grows in a straight line, and position error from tilt grows with time squared. The IMU and Inertial Navigation lesson builds the full strapdown chain. Here, take the lesson: an IMU is right over short times and wrong over long times.

The failure, as symptom, measurement and fix

The symptom is a heading that creeps while the robot sits parked. To measure it, log the gyro for 60 s at rest: the average reading is the bias. The fix is to measure and subtract the bias at every start, then correct the heading with an absolute source (Chapter 9).

A parked robot's gyro has a constant bias of 1°/s. How far off is the integrated heading after 30 s?

Chapter 4

LiDAR: Painting the Room With Light

Time a pulse, sweep the beam, and turn ranges and angles into points

The IMU says "I think I turned." A LiDAR (light detection and ranging) says "a wall is 2.00 m away at this angle." It measures the world directly, so its error does not pile up over time.

LiDAR is an active, time-of-flight sensor. It fires a short laser pulse and times the echo. Call the speed of light c and the round-trip time t. The light goes out and back, so the distance d is half the path.

Say it aloud

d equals c times t, divided by two.

d
d the distance to the surface, in metres.
c
c the speed of light: about 3 × 108 m/s, or 0.3 m per nanosecond.
t
t the round-trip time of the pulse, in seconds.
In plain words

Multiply the speed of light c by the echo time t to get the whole path. Halve it, because the pulse went out and came back. That is the distance d.

With numbers

A wall 3 m away: t = 2 × 3 / (3 × 108) = 20 ns. A timing error of 1 ns gives a range error of 0.3 / 2 = 0.15 m. LiDAR must time to a small fraction of a nanosecond.

Sound is much slower. Sonar at 343 m/s needs 17.5 ms for the same 3 m round trip, about 870,000 times longer.

A 2D LiDAR spins and fires beams at equal angle steps. Each beam returns a range ρ (rho) at a bearing θ (theta), measured from the robot's forward axis. A full sweep is a scan: a list of (ρ, θ) pairs. Maps use x and y, so each pair becomes a point (x, y) in the robot's frame.

Say it aloud

x equals rho times cos theta, and y equals rho times sine theta.

x
x how far ahead of the robot the hit lies, in metres.
y
y how far to the left of the robot the hit lies.
ρ
rho the range the beam measured, in metres.
cos θ, sin θ
cos theta, sine theta the forward and sideways shares of a beam at bearing theta.
In plain words

Walk rho metres along the beam's bearing theta. The forward part of that walk is x; the sideways part is y.

With numbers

A beam reads ρ = 2.50 m at θ = 30°. x = 2.50 × 0.866 = 2.165 m; y = 2.50 × 0.500 = 1.250 m. The hit is 2.17 m ahead and 1.25 m to the left.

Sweep a LiDAR around a room

Drag the teal robot. Each beam stops at the first wall it hits. Look for the shadows behind the boxes, then lower the maximum range.

72
5.0 m

Illustrative 10 m by 6 m room, with no range noise in this view. A real scanner also loses beams on black or glass surfaces.

The failure, as symptom, measurement and fix

The symptom is a map with a hole where a glass door stands: the beams pass through or scatter, and no echo returns. To measure it, count the no-return beams at each bearing. The fix is to store a no-return as "unknown", never "free", and to cover glass with another sensor, such as sonar.

A beam reads ρ = 4.0 m at θ = 90°. Where is the hit in the robot's frame?

Chapter 5

Point Clouds: Shrink, Then Search

Thin a cloud with a voxel grid, then ask which point is nearest

Convert every beam and you get a point cloud: a list of N points, each an (x, y) pair. In code it is an N × 2 array (N × 3 in 3D). It makes no claims about walls or objects. It is only where echoes came from.

Two facts make clouds hard. They are big: one 3D sweep can hold hundreds of thousands of points. And they are unordered: point 5 in this scan and point 5 in the next scan are different places.

The first fix is downsampling with a voxel grid. Cut space into square cells, called voxels. Replace all the points in a cell with their average. A flat wall then keeps one point per cell.

The second tool is the nearest-neighbour query. Call the query point q and the cloud's points pj, numbered by j. We want the number j* of the closest one.

Say it aloud

j star equals the argmin over j of the squared length of q minus p-j.

j*
j star the index of the nearest point.
argminj
the argmin over j try every j and keep the one that makes the value smallest.
q
q the query point, for example one point of a new scan.
pj
p-j point number j of the cloud we search.
‖ · ‖2
the squared length dx squared plus dy squared, with no square root.
In plain words

For each point p-j, take dx and dy to the query q, square them and add. Keep the j with the smallest sum. The square root is not needed, because the order of the sums is the order of the distances.

With numbers

With made-up points: q = (1, 1).

p1 = (2, 1) gives 1 + 0 = 1. p2 = (1.5, 1.5) gives 0.25 + 0.25 = 0.5. p3 = (0, 3) gives 1 + 4 = 5. So j* = 2.

Thin a cloud, then query it

Turn the grid on and watch the count fall while the shape stays. Tap anywhere to find the nearest point.

0.25 m

Illustrative cloud: walls of the same 10 m by 6 m room sampled every 2.5 cm, with 1 cm of noise.

Why shrink first? With made-up sizes: matching two clouds of 20,000 points by brute force checks 20,000 × 20,000 = 4 × 108 pairs. After a grid leaves 400 points each, it checks 160,000 pairs: 2,500 times fewer. A k-d tree cuts the search further, to about log N steps per query.

The failure, as symptom, measurement and fix

The symptom is a thin pillar that vanishes and corners that round off. The voxel is larger than the features. To measure it, overlay the thinned cloud on the raw cloud and look at corners. The fix is a voxel smaller than the smallest thing the robot must see.

Why compare squared distances when you search for the nearest point?

Chapter 6

Line Extraction: From Dots to Walls

Fit a line, find the worst point, split there, and repeat

A planner wants "a wall runs from here to there", not 300 dots. Rooms are mostly straight edges, so 2D LiDAR perception often fits straight segments to the scan. This is line extraction.

The form y = mx + c fails for a vertical wall: the slope is infinite. Use two other numbers instead. Call the shortest distance from the robot to the line r, and the angle of that shortest path α (alpha). For a scan point (xi, yi), call its signed distance to the line di.

Say it aloud

d-i equals x-i cos alpha plus y-i sine alpha, minus r.

di
d-i how far point i sits off the line, in metres. Zero means on the line.
xi, yi
x-i, y-i scan point number i, in the robot's frame.
cos α, sin α
cos alpha, sine alpha the direction that points straight at the wall.
r
r the shortest distance from the robot to the line.
In plain words

Measure how far point i reaches in the direction alpha. Subtract r. The rest is d-i, its distance off the line. The best line picks alpha and r so the sum of all the d-i squared is smallest. This is least squares.

With numbers

Five made-up points near a wall at x = 2: (2.02, −1), (1.98, −0.5), (2.01, 0), (1.99, 0.5), (2.00, 1). Try α = 0 and r = 2.00: the di are 0.02, −0.02, 0.01, −0.01, 0. Their squares sum to 0.0010 m². The exact best fit tilts α to 0.34° and lowers the sum to 0.00091.

One line fits one wall. A scan sees many walls. Split-and-merge cuts the scan into one group per wall:

  1. Join the segment's first and last points with a line.
  2. Find the point farthest from that line.
  3. If it is farther than a threshold, split the segment at that point and repeat on each half.
  4. If not, fit the segment by least squares and keep that line.
  5. At the end, merge neighbouring lines that turn out to be one wall.

Run split-and-merge one step at a time

Press Step. Each step joins a segment's end points with a dashed line, rings the worst point, then splits or keeps it. Lower the threshold and watch the walls break into more pieces.

0.10 m
0.015 m

Illustrative scan of three walls, 60 points. This is the end-point form of split-and-merge. Kept lines are perpendicular least-squares fits; segments under 5 points are dropped.

The lab below fits one wall with the slope form, on a tilted wall where the slope stays finite. The polar form above handles every angle.

The failure, as symptom, measurement and fix

The symptom is a fitted wall that tilts toward one stray return, such as a reflection. Squaring makes a far point count a lot. To measure it, compare the worst point's distance with the typical distance. The fix is to split or drop that point, or to use RANSAC, which fits to the points that agree (Lesson 9).

In split-and-merge, what makes a segment split in two?

Chapter 7

ICP: One Iteration by Hand

Pair the points, centre both clouds, rotate with the SVD, then shift

The robot holds a model cloud: a map, or its last scan. It moves and scans again. Both clouds show the same walls, turned and shifted by a motion that odometry knows only roughly.

Find the rotation R and the shift t that lay the new scan onto the model. That pair is the robot's motion, read from the walls. Iterative closest point (ICP) repeats four steps:

  1. Pair. For each scan point, take its nearest model point (Chapter 5).
  2. Centre. Subtract each cloud's average point. Only rotation is left to solve.
  3. Rotate. Build a 2 × 2 matrix from the pairs and read R from its SVD.
  4. Shift. Line up the averages with t. Apply R and t, then pair again.

Call the paired scan points pi and model points qi. Call their averages p̄ and q̄ (p-bar, q-bar). The centred points are p′i = pi − p̄ and q′i = qi − q̄. The cross-covariance H adds up how the pairs line up.

Say it aloud

H equals the sum over i of p-prime-i times q-prime-i transposed.

H
H the cross-covariance: a 2 by 2 matrix in 2D.
Σi
the sum over i add one term for each pair.
p′i
p-prime-i scan point i minus the scan's average, a column of two numbers.
q′i⊤
q-prime-i transposed its model partner minus the model's average, laid as a row.
In plain words

For each pair, multiply the column p-prime-i by the row q-prime-i to get a 2 by 2 table. Add the tables for all pairs. The total is H.

With numbers

For the three pairs in the table below: H11 = −0.111 + 0.222 + 0.222 = 0.333, H12 = 0.667, H21 = −0.667, H22 = −0.333.

The singular value decomposition (SVD) splits any matrix into a rotation, a stretch and a rotation: H = UΣV⊤. The best rotation keeps the two turns and drops the stretch.

Say it aloud

R equals V times U transposed, and t equals q-bar minus R times p-bar.

R
R the best rotation: a 2 by 2 matrix that turns the scan onto the model.
V
V the right-hand rotation from the SVD of H.
U⊤
U transposed the left-hand rotation from the SVD, undone.
t
t the shift, in metres, applied after the rotation.
q̄
q-bar the average model point.
p̄
p-bar the average scan point.
In plain words

Take the SVD of H. Multiply V by U transposed to get R. If R has determinant minus one, it is a mirror: flip the sign of V's last column and multiply again. Then turn the scan's average p-bar by R and shift it onto the model's average q-bar. The shift is t.

With numbers

For the H above, R = [[0, −1], [1, 0]], with determinant +1: a turn of +90°. R p̄ = R(1.333, 0.333) = (−0.333, 1.333), which equals q̄, so t = (0, 0).

PairModel qScan pq′ = q − q̄p′ = p − p̄
1(0, 1)(1, 0)(0.333, −0.333)(−0.333, −0.333)
2(0, 2)(2, 0)(0.333, 0.667)(0.667, −0.333)
3(−1, 1)(1, 1)(−0.667, −0.333)(−0.333, 0.667)

Averages: q̄ = (−0.333, 1.333) and p̄ = (1.333, 0.333). The scan is the model turned by −90°, so ICP must find +90°. In 2D the SVD answer reduces to one angle, and this page's devices use that shortcut:

angle = atan2(Σ(p′xq′y − p′yq′x), Σ(p′xq′x + p′yq′y)) = atan2(1.333, 0) = 90°

Step through one iteration

Press Next to run the four steps on the three pairs of the table. Watch the blue scan land on the purple model.

Here the table gives the pairs by index; in a real scan, step 1 finds them by nearest neighbour.

The failure, as symptom, measurement and fix

The symptom is a scan that lands mirrored. Plain V U⊤ can return a reflection, which no robot makes. To measure it, check det(R): +1 is a rotation, −1 a mirror. The fix is the flip of V's last column.

Why does ICP subtract each cloud's average point before it builds H?

Chapter 8

ICP Live: Snap a Scan Into Place

Run the loop to convergence, then turn the scan so far that ICP locks on wrong

Now the whole loop, on a real-sized cloud. The purple model is the room corner the robot already has. The blue scan is a fresh sweep, turned and shifted by the motion the robot does not know, with noise. They show the same walls but do not line up.

Run ICP on two scans

Press Step: grey lines show each scan point's partner, then the scan moves. Press Run to finish. Then raise the starting turn past about 45° and run again.

35°
0.010 m

Illustrative clouds. The scan samples the walls at other spots than the model, as a real second scan would. Point-to-point ICP with the 2D closed-form rotation.

Watch the rhythm: pair, move, smaller error, repeat. The alignment error is the average distance from each scan point to its partner. Early iterations make big moves; later ones polish. Stop when the error stops falling, or after a set number of iterations.

With the default 35° turn, ICP lands within a degree of the true motion in about 20 iterations. That recovered turn and shift is a measurement of motion that does not drift. Feed it to localization and it pulls odometry back, as in the hero. Stack many such matches and you have a map, which Lesson 11 builds.

A common upgrade is point-to-line ICP. It measures each scan point's distance to the model's wall, not to one model point. Sliding along a wall then costs nothing, which matches the geometry, and it needs fewer iterations in rooms.

The failure, as symptom, measurement and fix

The symptom is a confident wrong answer: the error settles low, but the pose is wrong. ICP only finds a local minimum: the best answer near its start. To measure it, compare the result with the odometry guess, and count pairs closer than 5 cm. The fix is to start ICP from the odometry guess, which is why we keep the wheels and the IMU.

ICP converged with a low error, but the robot's pose jumped 90° from the odometry guess. What is the likely cause?

Chapter 9

Sensor Fusion: Trust by Variance

Weight two readings by how sure each sensor is, and blend fast with absolute

A LiDAR says the wall is 5.00 m away. A sonar says 5.40 m. A plain average, 5.20 m, trusts the coarse sonar as much as the sharp LiDAR. Sensor fusion combines readings so the result beats each sensor alone.

The rule: weight each reading by how sure its sensor is. Call the readings m1 and m2, and their noise variances σ12 and σ22 (sigma one squared, sigma two squared). Call the fused estimate m̂ (m-hat).

Say it aloud

m-hat equals sigma two squared times m one, plus sigma one squared times m two, all over sigma one squared plus sigma two squared.

m̂
m-hat the fused estimate, in metres.
m1
m one the LiDAR reading.
m2
m two the sonar reading.
σ12
sigma one squared the LiDAR's noise variance, in square metres. Small means sure.
σ22
sigma two squared the sonar's noise variance.
In plain words

Weight each reading by the other sensor's variance, so the surer sensor counts more. Divide by the total weight. The fused variance, the product of the variances over their sum, is smaller than either.

With numbers

With made-up numbers: m1 = 5.00, σ12 = 0.01; m2 = 5.40, σ22 = 0.09. m̂ = (0.09 × 5.00 + 0.01 × 5.40) / 0.10 = 5.04 m. Fused variance = 0.0009 / 0.10 = 0.009, below both 0.01 and 0.09.

Fuse two range readings

Set how noisy each sensor is. The purple fused bell leans toward the narrower blue one, and it is narrower than both.

0.10 m
0.30 m

Readings fixed at 5.00 m and 5.40 m, made-up. The device treats both sensors as unbiased, with Gaussian noise.

Fast and absolute sensors pair the same way over time. A complementary filter follows the gyro over short times and leans gently on an absolute heading, such as a LiDAR scan match. Call the last estimate θ̂prev, the gyro rate ω (omega), the time step Δt, the absolute heading θabs, and the blend weight a, just under 1.

Say it aloud

Theta-hat equals a times, theta-hat previous plus omega delta t, plus one minus a, times theta absolute.

θ̂
theta-hat the new heading estimate.
a
a the blend weight, such as 0.98: how much to follow the gyro.
θ̂prev
theta-hat previous the estimate one step ago.
ω Δt
omega delta t the gyro rate times the time step: the turn the gyro saw.
θabs
theta absolute a heading that does not drift but jitters, such as a scan match.
In plain words

Move the last estimate by the gyro's turn. Keep the share a of that. Take the small share 1 minus a from the absolute heading. Each step pulls the drift back a little.

With numbers

With made-up numbers: the gyro path says 30.0°, the absolute heading says 28.0°, a = 0.98. θ̂ = 0.98 × 30.0 + 0.02 × 28.0 = 29.96°. At 100 Hz with a 0.5°/s gyro bias, the error settles at 0.25° and stops growing.

The Kalman filter of Lesson 13 replaces the fixed weight a with the best weight at each step. The complementary filters lesson covers the IMU case.

The failure, as symptom, measurement and fix

The symptom is a fused estimate that follows a bad sensor whose stated variance is too small. To measure it, compare each sensor with a reference and compute the real spread. The fix is to set each variance from measured data.

LiDAR variance 0.01, sonar variance 0.09. Where does the fused estimate land?

Chapter 10

Field Guide

Keep the terms, the numbers, the code and the next steps in one place

Every reading is truth plus bias plus noise. Wheels and gyros integrate, so their errors grow without limit. LiDAR measures the world, and ICP turns two scans into a motion that does not drift. Fusion weights each source by how sure it is.

TermMeaningNumber to remember
Error modelm = v + b + ε100 readings: noise 0.12 to 0.012 m, bias unchanged
Sensor classesself or world; listens or shoutsLiDAR: exteroceptive, active
Odometry turnΔθ = (ΔsR − ΔsL) / L1% wheel error, L = 0.30 m: 0.42 m off after 5 m
Gyro driftθ(t) = θ0 + b t0.5°/s: 30° in a minute
Time of flightd = c t / 23 m: 20 ns; 1 ns error: 0.15 m
Scan to pointsx = ρ cos θ, y = ρ sin θ2.50 m at 30°: (2.165, 1.250)
Line fitminimise Σ di25 points near x = 2: sum 0.00091 m²
ICP rotationH = Σ p′q′⊤, R = V U⊤, t = q̄ − R p̄3-point example: +90°, t = 0
Fusionweight by the other variance5.00 and 5.40: 5.04 m, variance 0.009

Checklist for a robot's sensing

The core, in code

python
import numpy as np

def best_fit_transform(P, Q):            # P, Q: N x 2, paired by row
    pbar, qbar = P.mean(0), Q.mean(0)        # averages
    H = (P - pbar).T @ (Q - qbar)              # 2 x 2 cross-covariance
    U, S, Vt = np.linalg.svd(H)
    R = Vt.T @ U.T                             # R = V U^T
    if np.linalg.det(R) < 0:                   # a mirror: flip V's last column
        Vt[-1] *= -1; R = Vt.T @ U.T
    return R, qbar - R @ pbar                 # t = qbar - R pbar

def icp(scan, model, iters=20, tol=1e-5):
    src, last = scan.copy(), np.inf
    for _ in range(iters):
        d2 = ((src[:, None, :] - model[None]) ** 2).sum(-1)   # all squared distances
        j = d2.argmin(1)                          # nearest model point per scan point
        err = np.sqrt(d2[np.arange(len(src)), j]).mean()
        if last - err < tol: break             # stopped improving
        R, t = best_fit_transform(src, model[j])
        src, last = src @ R.T + t, err
    return src, err

Keep going

Based on Stanford AA 274A, Principles of Robot Autonomy I. This page re-teaches the course's sensors lesson in our own words, devices and toy numbers.

The takeaway. Integrating sensors are fast and drift; world sensors are slower and do not. Match scans to turn the world into a motion measurement, and weight every source by how sure it is.

Now press Present or Teach. Explain from memory: bias and noise, why wheels and gyros drift, time of flight, one ICP iteration and the fusion weights. Then go back to the laps, switch scan matching on and off, and say why one estimate stays put.

Principles of Robot Autonomy I · Stanford AA 274A · Lesson 7: Robot Sensors, LiDAR, IMU and ICP
Next: Camera Models and Calibration · Back to Gleams