Self-Driving Cars
Topic 18 · Part 4: Deciding what to do · ⏱ about 3.5 h

Path Planning: A*, Hybrid A* and Parking

How a car finds a way from here to there around obstacles: search on a grid with Dijkstra and A*, why heuristics make it fast, why grid paths are not drivable, and hybrid A*, the planner that parked Stanford's car in the DARPA Urban Challenge, finding real manoeuvres with reversing into a bay and parallel parking.

Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the traffic world project, ready to run.Open
Show:
In this topic
Beginner

In plain words

Finding a route is like finding your way through a maze: try paths, prefer the ones that head towards the goal, and stop at the first one that gets there. A car cannot move sideways, though, so for parking it searches with moves it can really make: forward or back, with the wheels turned left, right or straight.

By the end of this topic you will be able to explain how planners search for paths, and watch one park a car in a bay and parallel park.

Start with: the demo Try it: park the car.

Beginner

Three levels of planning

Planning is usually split into three levels, from slow and big to fast and small:

  • Route planning: which roads to take across the city, like a satnav. A shortest-path search over the road network, run rarely.
  • Behaviour planning: what to do next: follow, change lane, stop for a pedestrian, wait at a junction. The next topic.
  • Motion planning: the exact path and speed for the next few seconds, avoiding obstacles, that the car can physically drive. The controllers from Part 1 then follow it.

This topic is about searching for paths: first on a grid, then for a real car.

Beginner

Search on a grid: Dijkstra and A*

Divide the area into cells, free or blocked, and treat each free cell as a node connected to its neighbours. Finding the shortest path is then a graph search.

  • Dijkstra's algorithm always expands the cell with the lowest cost so far, g(n)g(n). It spreads out evenly in every direction like a ripple, and finds the shortest path, but examines a lot of cells that lead away from the goal.
  • Greedy best-first expands the cell that looks closest to the goal, by an estimate h(n)h(n). Fast, but it can walk into dead ends and return a poor path.
  • A* (Hart, Nilsson and Raphael, 1968) combines both: it expands the lowest f(n)=g(n)+h(n)f(n) = g(n) + h(n), the cost so far plus the estimated cost to go.

If the estimate never overestimates the true remaining cost (it is admissible), A* is guaranteed to find the shortest path, and the better the estimate, the fewer cells it examines. Straight-line distance is admissible, because no path is shorter than a straight line. Multiplying the estimate by a factor above 1 (weighted A*) makes the search much faster, at the price of paths that may be slightly longer than the best.

Try it

Try it: Dijkstra, greedy and A*

Purple cells are the ones each method examined. Compare how many cells each needs, and the path lengths. Draw a wall that makes the straight-line estimate misleading, and watch greedy search get lost while A* still finds the shortest way.

Interactive: this part runs in your browser.

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.

Code

Code: A* on a car park

This runs in your browser. The estimate is the straight-line distance; set use_heuristic=False to get Dijkstra. Notice the rule against cutting diagonally past a corner: a car is not a point.

Python · NumPy
import heapq
import numpy as np

# A car park as a grid: 1 = blocked (parked cars, kerbs), 0 = free. Each cell is 1 m.
grid = np.zeros((20, 40), int)
grid[:, 8] = grid[:, 20] = grid[:, 32] = 1            # three rows of parked cars ...
grid[9:11, 8] = grid[2:4, 20] = grid[15:17, 32] = 0   # ... each with a 2 m gap to drive through
start, goal = (10, 1), (10, 38)

def plan(grid, start, goal, use_heuristic=True):
    """A* search on an 8-connected grid. Returns the path and how many cells it had to examine."""
    h = lambda c: np.hypot(c[0] - goal[0], c[1] - goal[1]) if use_heuristic else 0.0   # straight-line distance
    frontier = [(h(start), 0.0, start)]              # (cost so far + estimate to go, cost so far, cell)
    came_from, cost = {start: None}, {start: 0.0}
    expanded = 0
    while frontier:
        _, g, cell = heapq.heappop(frontier)
        if g > cost[cell]:
            continue                                  # an old, worse entry for this cell
        expanded += 1
        if cell == goal:
            break
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nxt = (cell[0] + dr, cell[1] + dc)
                if (dr, dc) == (0, 0) or not (0 <= nxt[0] < grid.shape[0] and 0 <= nxt[1] < grid.shape[1]) or grid[nxt]:
                    continue
                if dr and dc and (grid[cell[0] + dr, cell[1]] or grid[cell[0], cell[1] + dc]):
                    continue                          # no cutting diagonally past the corner of a parked car
                new = g + np.hypot(dr, dc)            # diagonal steps cost √2
                if new < cost.get(nxt, np.inf):
                    cost[nxt], came_from[nxt] = new, cell
                    heapq.heappush(frontier, (new + h(nxt), new, nxt))
    path, c = [], goal
    while c is not None:
        path.append(c)
        c = came_from.get(c)
    return path[::-1], expanded, cost.get(goal)

for name, use_h in (("Dijkstra (no heuristic)", False), ("A* (straight-line heuristic)", True)):
    path, expanded, length = plan(grid, start, goal, use_h)
    print(f"{name}: path {length:.1f} m, examined {expanded} cells")

show = grid.astype(object)
show[show == 1], show[show == 0] = "█", "·"
for r, c in path:
    show[r, c] = "o"
show[start], show[goal] = "S", "G"
print("\n".join("".join(row) for row in show))
Open in playground ↗
Beginner

Why a grid path is not a drivable path

The grid path turns 45° in a single step and moves sideways freely. A car cannot: it can only move in the direction it is pointing, and it turns along arcs no tighter than its minimum turning radius, Rmin=L/tan⁡δmaxR_\text{min} = L / \tan\delta_\text{max} (about 4.4 m for our car). Constraints like this, on how you can move rather than where you can be, are called nonholonomic.

Two common answers:

  • Search in the car's own state, (x,y,θ)(x, y, \theta), with moves the car can really make. That is hybrid A*, below.
  • Plan along the road: in the Frenet frame (distance along the lane, and offset from it) many candidate trajectories are generated and the cheapest safe one is chosen. On roads this is the most common approach. Sampling planners such as RRT* are another family, popular in robotics.

Obstacles are handled by checking the car's whole body, not a point. A fast trick, used in the demo below, is to cover the car with three overlapping circles: a pose is free if each circle's centre is further than its radius from every obstacle, which is one lookup in a precomputed distance map.

Advanced

Hybrid A*

Hybrid A* (Dolgov, Thrun, Montemerlo and Diebel, 2008) was developed for Stanford's car Junior, which finished second in the 2007 DARPA Urban Challenge and parked itself in car parks. It keeps the A* idea but changes what a "neighbour" is:

  • From each pose, the car tries a few motion primitives: drive 1 m forward or backward with the steering full left, half left, straight, half right or full right. Each gives a new, exactly drivable pose.
  • Poses are stored with their exact continuous values, but two poses that fall in the same cell of a coarse 3D grid (0.5 m × 0.5 m × 5° here) count as the same, so the search does not repeat itself. This mix of continuous and discrete is the "hybrid".
  • The cost adds the distance driven, with extra for reversing, changing between forward and reverse, and steering a lot. That is what makes the result comfortable.
  • The estimate is the shortest distance around the obstacles for a point that can move freely (worked out once, backwards from the goal), plus a term for how far the heading still has to turn. The demo multiplies it by 1.5 (weighted A*), which makes the search several times faster.

The found path is then smoothed and handed to a controller to follow. The real Junior also tried, at each step, to connect to the goal directly with an exact shortest car path (a Reeds–Shepp curve), which finds the final manoeuvre much faster.

Try it

Try it: park the car

The planner searches from the car in the aisle to the green goal. Purple dots are poses it examined; orange path is forward, pink is reverse. Try both spaces: parallel parking needs more gear changes and a much bigger search, because the gap leaves little room.

Interactive: this part runs in your browser.

Check yourself

Quiz

1. What does A* expand next?

2. When is A* guaranteed to find the shortest path?

3. Why can a car not follow a grid path directly?

4. In hybrid A*, what are the neighbours of a pose?

5. The car's wheelbase is 2.7 m and its maximum steering angle is 0.55 rad. About what is its tightest turning radius?

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