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

Behaviour Planning and Predicting Other Road Users

Decide what to do in traffic: follow the car ahead at a safe time gap with the Intelligent Driver Model, choose when a lane change is worth it and safe with MOBIL, organise decisions with a state machine, predict where other cars will be, and brake in an emergency using time to collision.

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

In traffic you keep a safe gap to the car ahead, overtake when the next lane is faster and clear, and slam on the brakes if someone pulls in front of you. The car does the same, with simple rules for each: how big a gap to keep, when a lane change is worth it and safe, and when to brake hard. It also guesses where every other car will be in the next few seconds.

By the end of this topic you will be able to explain how a self-driving car follows, changes lanes and reacts to a car cutting in.

Start with: the demo Try it: a three-lane road, then press A car cuts in.

Beginner

What behaviour planning decides

The behaviour planner sits between perception and motion planning. Several times a second it looks at the tracked objects (Part 2), the car's position (Part 3) and the route, and picks a manoeuvre: keep the lane and follow, prepare a lane change, change lane, stop at the line, yield, or brake hard. The motion planner then turns that choice into an exact path and speed.

Behaviour has to be predictable to other people, as well as safe. A car that brakes for no visible reason, or changes lanes back and forth, is dangerous even if it never touches anyone.

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

Following: the Intelligent Driver Model

The Intelligent Driver Model (IDM) (Treiber, Hennecke and Helbing, 2000) is a single formula for a car's acceleration that produces realistic following, approaching and stopping:

a=amax[1−(vv0)4−(s∗s)2],s∗=s0+vT+v Δv2amax b a = a_\text{max}\left[1 - \left(\frac{v}{v_0}\right)^4 - \left(\frac{s^*}{s}\right)^2\right], \qquad s^* = s_0 + vT + \frac{v\,\Delta v}{2\sqrt{a_\text{max}\, b}}

vv is the car's speed, v0v_0 the speed it wants, ss the gap to the car ahead and Δv\Delta v how much faster we are than it. The wanted gap s∗s^* has three parts: a minimum gap s0s_0, a time gap TT (cover the gap in TT seconds at the current speed), and an extra term that grows when we are closing in fast. On an empty road the first two terms bring the car smoothly up to v0v_0; behind a slower car, the last term holds it back.

The time gap is the key safety setting. Many driving guides recommend at least 2 seconds; adaptive cruise control systems typically let the driver pick about 1 to 2.5 seconds.

Code

Code: how much time gap is enough?

Our car follows a lead car at 72 km/h. The lead car brakes hard. Our car reacts half a second late, as a real system does after perception and planning. Which time gaps survive?

Python · NumPy
import numpy as np

def idm(v, v_lead, gap, v0=25.0, T=1.5, a_max=1.5, b=2.0, s0=2.0):
    """The Intelligent Driver Model: acceleration for a car at speed v, following a car at v_lead, gap metres ahead.
    v0: desired speed, T: time gap to keep, a_max: comfortable acceleration, b: comfortable braking, s0: gap when stopped."""
    s_star = s0 + max(0.0, v * T + v * (v - v_lead) / (2 * np.sqrt(a_max * b)))   # the gap we would like
    return a_max * (1 - (v / v0) ** 4 - (s_star / max(gap, 0.1)) ** 2)

def drive(T, delay=0.5, brake_hard_at=20.0, seconds=40.0, dt=0.05):
    """We follow a lead car at 20 m/s. At 20 s it brakes at 8 m/s² to a stop.
    Our car sees everything "delay" seconds late: perception and planning take time."""
    x, v, xl, vl = 0.0, 20.0, 40.0, 20.0
    seen = [(40.0 - 4.5, 20.0)] * int(delay / dt + 1)      # what we observed, oldest first
    min_gap, min_ttc = np.inf, np.inf
    for k in range(int(seconds / dt)):
        t = k * dt
        al = -8.0 if t >= brake_hard_at else 0.0
        vl = max(0.0, vl + al * dt)
        xl += vl * dt
        seen.append((xl - x - 4.5, vl))
        old_gap, old_vl = seen.pop(0)                    # act on the old observation
        a = max(-9.0, idm(v, old_vl, old_gap, T=T))      # brakes cannot do more than 9 m/s²
        v = max(0.0, v + a * dt)
        x += v * dt
        gap = xl - x - 4.5                               # 4.5 m: the length of the lead car
        if gap <= 0:
            return gap, 0.0                              # collision
        min_gap = min(min_gap, gap)
        if v > vl:
            min_ttc = min(min_ttc, gap / (v - vl))
    return min_gap, min_ttc

for T in (0.5, 1.0, 1.5, 2.0):
    g, ttc = drive(T)
    print(f"time gap {T} s: " + ("CRASH" if g <= 0 else f"closest {g:.1f} m, shortest time to collision {ttc:.1f} s"))
Open in playground ↗

Try delay=0.0: every gap survives, which is why reaction time is so important. Try delay=1.0, closer to a human driver's reaction time: now every gap crashes, even though a 2 s gap leaves room to stop. IDM is a comfort model that brakes gently, and on late information that is not enough. That is why cars add a separate emergency braking rule, below.

Intermediate · Maths

Lane changes: MOBIL

MOBIL ("minimising overall braking induced by lane changes", Kesting, Treiber and Helbing, 2007) decides lane changes with the same IDM accelerations. A change to a neighbouring lane is made only if two tests pass:

  • Safety: the car that would be behind us in the new lane must not have to brake harder than a safe limit (here 4 m/s²).
  • Incentive: our gain in acceleration, plus a politeness factor pp times the change for the new follower, must beat a threshold:
    (a~me−ame)+p (a~new follower−anew follower)>Δath (\tilde a_\text{me} - a_\text{me}) + p\,(\tilde a_\text{new follower} - a_\text{new follower}) > \Delta a_\text{th}

With p=0p = 0 the car is selfish and cuts in whenever it gains; with p=1p = 1 it counts others' braking as much as its own. The threshold stops it from changing lanes for tiny gains.

Beginner

A state machine for behaviour

A simple, testable way to organise behaviour is a finite state machine: a few named states, and clear rules for moving between them. Our car uses:

  • KEEP LANE: follow with IDM. Every half second, check MOBIL for both neighbouring lanes.
  • PREPARE: MOBIL says a change is worth it. Signal for half a second, then check again: if it is no longer safe or worth it, go back to keep lane.
  • CHANGING LEFT / RIGHT: move across smoothly over 3 seconds.
  • EMERGENCY BRAKE: from any state, if the time to collision with the car ahead drops below 1.5 s, brake as hard as possible.

Real systems have many more states (merging, junctions, pedestrians at crossings, giving way to emergency vehicles) and often use more flexible structures: behaviour trees, or scoring many candidate trajectories by cost.

Beginner

Predicting other road users

Planning needs to know not where others are, but where they will be over the next few seconds. Three levels of prediction:

  • Physics: assume each car keeps its speed and heading (constant velocity) or its turning rate. Good for a second or two.
  • Manoeuvres: recognise what the car is doing (following its lane, turning, changing lane: the indicator, the drift towards the line) and predict along that manoeuvre using the map.
  • Learned, multi-modal: neural networks trained on millions of recorded situations output several possible futures with probabilities, for example "60% goes straight, 40% turns left". Planners must be safe against all likely ones.

Prediction and planning affect each other: if we start to merge, the car behind may slow down to let us in. Modelling this interaction is one of the hardest open problems in self-driving.

Try it

Try it: a three-lane road

Our car (purple) follows with IDM and changes lanes with MOBIL; the others do the same with their own speeds. Faint boxes are the constant-velocity predictions 1, 2 and 3 seconds ahead. Shorten the time gap and raise or lower the politeness. Then press A car cuts in: a car swerves in close ahead and slows down. Watch the state change to emergency braking, and the shortest time to collision.

Interactive: this part runs in your browser.

Check yourself

Quiz

1. In the IDM, what does the time gap T control?

2. MOBIL refuses a lane change when…

3. What does a politeness factor of 0 mean in MOBIL?

4. Why does reaction delay matter so much in following?

5. Why do modern systems predict several possible futures for each car?

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