Self-Driving Cars
Topic 17 · Part 3: Knowing where you are · ⏱ about 3.5 h

Sensor Fusion and Mapping

Fuse GPS, motion sensors and landmark sightings in one filter, then let the car build its own map with a 2D lidar: occupancy grids and log-odds, why a map is only as good as the positions used to build it, and how SLAM and loop closure solve both at once.

Softmaxima Simulator StudioWrite your car in Python, with as many files and trained networks as it needs, and watch it drive. In your browser, nothing to install.Open
Show:
In this topic
Beginner

In plain words

Every sensor has its own weakness, so the car combines them all into one best estimate. And with a laser scanner it can draw its own map of everything around it, as long as it knows where it was standing for each scan; get that wrong and the map smears.

By the end of this topic you will be able to combine several sensors into one position, and build a map of the area around the road.

Start with: the demo Try it: a map is only as good as its positions.

Beginner

Going deeper

The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.

Intermediate · Maths

Fusing everything in one filter

The Kalman filter's update step does not care what kind of sensor a measurement comes from. Each sensor just needs its measurement function h(x)h(\mathbf{x}), its Jacobian HH and its noise RR. For a pole at (px,py)(p_x, p_y), with dx=px−xd_x = p_x - x, dy=py−yd_y = p_y - y and q=dx2+dy2q = d_x^2 + d_y^2:

h(x)=(qatan2⁡(dy,dx)−θ),H=(−dx/q−dy/q0dy/q−dx/q−1) h(\mathbf{x}) = \begin{pmatrix} \sqrt{q} \\ \operatorname{atan2}(d_y, d_x) - \theta \end{pmatrix}, \qquad H = \begin{pmatrix} -d_x/\sqrt{q} & -d_y/\sqrt{q} & 0 \\ d_y/q & -d_x/q & -1 \end{pmatrix}

Each measurement is applied as it arrives, whatever its rate: wheel speed and gyro every step, poles five times a second, GPS once a second. This is sensor fusion. Two details matter: the bearing difference must be wrapped to ±180°, and the timestamps must be right; a measurement applied at the wrong moment is a wrong measurement.

Try it

Try it: GPS plus poles

The same lap as before, now with the poles as a second kind of measurement. Compare the error with and without Use the poles too, and in the tunnel. Landmarks measured to half a metre beat GPS to three metres, and they work where GPS does not.

Interactive: this part runs in your browser.

Beginner

Occupancy grids

So far the map (the poles) was given. Often the car must make its own map of what is around it: where are the walls, parked cars and trees? The simplest useful map is an occupancy grid (Elfes, 1989): divide the ground into cells, and keep for each cell the probability that something solid is there.

A lidar sends out laser beams and measures how far each one travels before it hits something. Each beam says two things: the cells it passed through are probably free, and the cell where it stopped is probably occupied. Cells nobody has seen stay unknown, which is different from free.

Intermediate · Maths

Occupancy grids: the maths

Combining many beams is easiest with log-odds: ℓ=log⁡p1−p\ell = \log \frac{p}{1 - p}. Then each beam just adds a number to each cell it touches:

ℓcell←ℓcell+{ℓoccthe beam ended hereℓfreethe beam passed through,p=11+e−ℓ \ell_\text{cell} \leftarrow \ell_\text{cell} + \begin{cases} \ell_\text{occ} & \text{the beam ended here} \\ \ell_\text{free} & \text{the beam passed through} \end{cases},\qquad p = \frac{1}{1 + e^{-\ell}}

Capping ℓ\ell stops the map from becoming completely certain, so it can still change when a parked car leaves.

Code

Code: build an occupancy grid

The car drives along a road, scanning with a 90-beam lidar every 2 m. The map is printed as text: # occupied, . free, blank unknown. Notice the unknown area behind the wall, and the shadows behind the trees.

Python · NumPy
import numpy as np

rng = np.random.default_rng(4)
CELL, W, H = 1.0, 60, 24                      # a 60 m × 24 m area in 1 m cells
# The world (unknown to the car): a parked car, a wall and two trees beside a straight road (y = 12).
def solid(x, y):
    car = (x >= 20) & (x <= 24.5) & (y >= 6.5) & (y <= 8.5)
    wall = (x >= 30) & (x <= 52) & (y >= 19) & (y <= 20)
    trees = (np.hypot(x - 10, y - 18) < 1.5) | (np.hypot(x - 42, y - 5) < 1.2)
    return car | wall | trees

def scan(px, py, n=90, max_r=15.0):
    """A 2D lidar: n beams all round; each returns the distance to the first solid point (or max_r)."""
    angles = np.linspace(-np.pi, np.pi, n, endpoint=False)
    r = np.arange(0.2, max_r, 0.1)
    hit = solid(px + r * np.cos(angles)[:, None], py + r * np.sin(angles)[:, None])   # n beams × every 10 cm
    first = np.where(hit.any(1), hit.argmax(1), -1)
    ranges = np.where(first >= 0, r[first] + rng.normal(0, 0.05, n), max_r)
    return angles, ranges

L_FREE, L_OCC = -0.4, 0.85                    # how much one beam changes our belief, in log-odds
logodds = np.zeros((H, W))
for px in np.arange(2, 58, 2.0):              # the car drives along the road, scanning every 2 m
    py = 12.0
    for a, r in zip(*scan(px, py)):
        for d in np.arange(0, min(r, 15.0) - 0.5, 0.5):        # cells the beam passed through: free
            cx, cy = int((px + d * np.cos(a)) / CELL), int((py + d * np.sin(a)) / CELL)
            if 0 <= cx < W and 0 <= cy < H:
                logodds[cy, cx] += L_FREE
        if r < 15.0:                                          # the cell where it stopped: occupied
            cx, cy = int((px + r * np.cos(a)) / CELL), int((py + r * np.sin(a)) / CELL)
            if 0 <= cx < W and 0 <= cy < H:
                logodds[cy, cx] += L_OCC
    logodds = logodds.clip(-4, 4)             # never become completely certain: the world can change

p = 1 / (1 + np.exp(-logodds))                # log-odds back to probability
for row in p[::-1]:                           # print with north at the top
    print("".join("#" if v > 0.7 else "." if v < 0.3 else " " for v in row))
print("# occupied   . free   (blank) unknown")
Open in playground ↗
Try it

Try it: a map is only as good as its positions

The car maps the area beside the track with a 72-beam lidar. Each scan is drawn at the position the car believes it is at. Build the map from the true position, then from dead reckoning: the same objects appear twice, smeared and bent. Then try the Kalman filters. Tick Show the real objects to compare.

Interactive: this part runs in your browser.

Advanced

SLAM: mapping and localising at once

To build a map, you need to know where you are. To know where you are, you need a map. Doing both at once is SLAM: simultaneous localisation and mapping. It is one of the classic problems of robotics.

The modern approach is the pose graph (graph-based SLAM). Each position the car passed is a node. Odometry adds an edge between consecutive nodes: "pose 8 is 2 m ahead of pose 7". The key extra edge is a loop closure: when the car recognises a place it has been before (by matching a lidar scan or an image), it adds an edge saying "pose 40 is at the same place as pose 0". Then all the positions are adjusted together to best agree with every edge, by least squares. The accumulated drift is spread back along the whole path, and the map snaps into shape.

Wrong loop closures are disastrous (two different car parks that look alike would fold the map), so real systems check them carefully and use robust losses that can ignore a bad edge.

Code

Code: a pose graph with one loop closure

Positions only, so the least-squares problem is linear and one call to lstsq solves it. Real SLAM also estimates headings, which makes the problem nonlinear and needs repeated linearisation (Gauss–Newton), as in libraries such as g2o, GTSAM and Ceres.

Python · NumPy
import numpy as np

rng = np.random.default_rng(5)
# The truth: 40 poses round a 20 m × 20 m block, ending back at the start.
corners = np.array([[0, 0], [20, 0], [20, 20], [0, 20], [0, 0]], float)
truth = np.vstack([corners[i] + (corners[i + 1] - corners[i]) * t for i in range(4) for t in np.arange(10) / 10] + [corners[:1]])
n = len(truth)                                         # 41 poses; the last is at the same place as the first

# Odometry: each step's movement, measured with noise and a small steady error (wheels slip a little sideways).
steps = np.diff(truth, axis=0)
odo = steps * 1.02 + [0.03, 0.05] + rng.normal(0, 0.05, (n - 1, 2))
dead = np.vstack([[0, 0], np.cumsum(odo, 0)])         # chaining odometry: errors add up

# The pose graph. Unknowns: every pose's x and y (pose 0 is fixed at the origin).
# Each edge says "pose j minus pose i should equal this measurement", with a weight (1 / its noise).
edges = [(i, i + 1, odo[i], 1.0) for i in range(n - 1)]
edges.append((0, n - 1, np.array([0.0, 0.0]), 10.0))  # loop closure: "I recognise this place: I am back at the start"

A = np.zeros((2 * len(edges) + 2, 2 * n))
b = np.zeros(2 * len(edges) + 2)
for e, (i, j, z, wgt) in enumerate(edges):
    for d in range(2):
        A[2 * e + d, 2 * j + d], A[2 * e + d, 2 * i + d], b[2 * e + d] = wgt, -wgt, wgt * z[d]
A[-2, 0] = A[-1, 1] = 100.0                            # anchor pose 0 at (0, 0)
poses = np.linalg.lstsq(A, b, rcond=None)[0].reshape(n, 2)

err = lambda P: np.hypot(*(P - truth).T)
print(f"odometry only: {err(dead).mean():.2f} m off on average, {err(dead)[-1]:.2f} m off at the end")
print(f"with the loop closure: {err(poses).mean():.2f} m off on average, {err(poses)[-1]:.2f} m off at the end")
Open in playground ↗
Beginner

How real cars do it

  • Many self-driving companies build detailed HD maps in advance with specially equipped cars and SLAM: lane lines, kerbs, signs and traffic lights to within centimetres. The car then localises against this map with its lidar or cameras, as in the particle-filter topic.
  • Others rely less on prior maps and build the local map live from cameras, which is cheaper to scale to new cities but harder.
  • Either way, a Kalman-style filter fuses GPS, IMU, wheel odometry and the map match into one smooth, fast estimate: the position that every later part of the car (prediction, planning and control) uses.

Part 4 uses this position and the perception from Part 2 to decide where to go: planning paths, handling other road users, and learning to drive by trial and error.

Check yourself

Quiz

1. What does a lidar beam tell an occupancy grid?

2. Why use log-odds for occupancy grids?

3. A map is built with dead-reckoning positions. What happens?

4. What is a loop closure?

5. Why must the bearing difference be wrapped in the update?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready