Lab 1 · Phantom Jams on Your Laptop

Practice · reproduce the 1959 GM experiment · local and string stability · when a platoon collides

▶︎ Start this lab in your browser: nothing to install.

  • New to notebooks? Read How to do a lab: 5 minutes, with pictures.
  • Nothing to submit. Save your notebook: you may want to come back to it.
  • Every task has a level: 🌶 Core, in class, everyone; 🌶🌶 Extend, optional, at home, with hints; 🌶🌶🌶 Challenge, optional and open-ended, for the curious.

In 1959, four researchers at General Motors asked: if every driver matches the speed of the car ahead, after a short reaction time, is traffic stable? Their answer explained phantom jams sixty years before anyone filmed one.

Predict first (not graded). Nine sensible drivers follow a leader who taps the brakes for two seconds. Nobody is distracted or reckless. Can that end in a crash? Write down yes or no, and why.

import sys
if sys.platform == "emscripten":                  # on the course website: install the course package
    import micropip, js
    await micropip.install(js.location.origin + "/lite/wheels/trafficlab-0.3.0-py3-none-any.whl")

import numpy as np
import matplotlib.pyplot as plt
def brake_pulse(t):
    """The leader brakes at 1 m/s² for 2 s, then accelerates back for 2 s."""
    return -1.0 if t < 2 else (1.0 if t < 4 else 0.0)

A1 · The model 🌶 Core

After a reaction time T, car n+1 accelerates in proportion to its speed difference with car n:

\ddot x_{n+1}(t) = \lambda\,\big[\dot x_n(t-T) - \dot x_{n+1}(t-T)\big].

  • Everything depends on one number, C = \lambda T.
  • u_n(t) is each car’s speed change from cruising speed.
  • Step forward with Euler’s method: u(t+\Delta t) = u(t) + a\,\Delta t, where a uses speeds from T seconds ago.

Do: complete simulate, then run the check below it.

def simulate(C, n_cars=8, T=1.0, dt=0.01, t_end=50.0, leader_accel=brake_pulse):
    """Speed change of each car behind a leader, for the 1959 GM model.

    C is one number for everyone, or a list with one value per follower.
    Returns (t, u): t has shape (steps + 1,), and u has shape (n_cars + 1, steps + 1).
    Row 0 of u is the leader; row n is the n-th follower. All speed changes start at 0.

    Follower n's acceleration at step k uses speeds from `lag = round(T / dt)` steps earlier:
        a_n = lam[n-1] * (u[n-1, k-1-lag] - u[n, k-1-lag])     (and 0 while k-1-lag < 0)
    """
    lam = np.broadcast_to(np.asarray(C, float) / T, (n_cars,))   # one lambda per follower
    lag = round(T / dt)
    steps = round(t_end / dt)
    t = np.arange(steps + 1) * dt
    u = np.zeros((n_cars + 1, steps + 1))
    # YOUR CODE HERE: step through time with Euler's method.
    # At each step k = 1, 2, ...: update the leader with leader_accel(t[k]), then each follower from the
    # speeds lag steps earlier (step k - 1 - lag).
    return None
r = simulate(0.5, n_cars=2, t_end=10)
assert r is not None, "complete simulate() first"
t, u = r
assert u.shape == (3, 1001) and abs(u[0, -1]) < 0.02, "the leader ends back at cruising speed (to one Euler step)"
assert u[1, 99] == 0 and u[1, 400] < 0, "the follower reacts only after T = 1 s, then slows down"
print("simulate: checks passed")

A2 · One follower: local stability 🌶 Core

Do: run the cell. Five drivers, five values of C.

Cs = [0.3, 1 / np.e, 1.0, np.pi / 2, 1.7]
fig, axes = plt.subplots(1, len(Cs), figsize=(16, 3), sharey=True)
for ax, C in zip(axes, Cs):
    t, u = simulate(C, n_cars=1, t_end=40)
    ax.plot(t, u[0], "k--", lw=1, label="leader")
    ax.plot(t, u[1], color="#57068c", lw=2, label="follower")
    ax.set_title(f"C = {C:.3f}"); ax.set_xlabel("Time (s)"); ax.set_ylim(-4, 4)
axes[0].set_ylabel("Speed change (m/s)"); axes[0].legend(); plt.tight_layout()

Theory: the follower’s response is smooth for C \le 1/e, oscillates but settles for 1/e < C < \pi/2, and grows for C > \pi/2. Check: do your five plots agree?

A3 · A line of cars: string stability 🌶 Core

A disturbance can fade or grow as it passes down a line of cars. Amplification = the last car’s largest speed change ÷ the first follower’s.

Do: run the two cells below. Then find the C (to 0.01) where the amplification crosses 1: try values between C_a and C_b, or halve the interval again and again (bisection).

def amplification(C, n_cars=8):
    _, u = simulate(C, n_cars=n_cars, t_end=60)
    peak = np.abs(u).max(axis=1)
    return peak[-1] / peak[1]
n_cars, C_a, C_b = 8, 0.40, 0.80   # try other values
amp_a = amplification(C_a, n_cars=n_cars)
amp_b = amplification(C_b, n_cars=n_cars)
print(f"line of {n_cars} cars: amplification {amp_a:.3f} at C = {C_a}, {amp_b:.2f} at C = {C_b}")

C_cross = None   # YOUR CODE HERE: the C (to 0.01) at which amplification(C, n_cars=n_cars) crosses 1
assert C_cross is not None, "find C_cross first"
assert C_a < C_cross < C_b, "C_cross should lie between C_a and C_b"
assert abs(amplification(C_cross, n_cars=n_cars) - 1) < 0.05, "at C_cross the amplification should be 1"
print("C_cross: checks passed")

Watch it. Run the cell. Each row is one car, the leader at the top. Left: the brake tap fades as it travels back. Right: the same tap grows into a jam.

fig, axes = plt.subplots(1, 2, figsize=(14, 5), sharey=True)
for ax, C in zip(axes, [0.4, 0.8]):
    t, u = simulate(C, n_cars=8, t_end=40)
    for n in range(u.shape[0]):
        ax.plot(t, u[n] - 4 * n, color=plt.cm.tab10((n - 1) % 10) if n else "k", lw=1.5)
        ax.text(40.5, -4 * n, "leader" if n == 0 else f"car {n}", va="center", fontsize=8)
    ax.set(title=f"C = {C}", xlabel="Time (s)", yticks=[])
axes[0].set_ylabel("Speed change, one row per car"); plt.tight_layout()

Think. Theory says a long line of cars is stable only when C < 1/2. Your crossing is not exactly 1/2. Why might that be?

B1 · When does a platoon crash? 🌶🌶 Extend

Now give every car a real position: cruising at 20 m/s, 5 m long, 30 m apart from front bumper to front bumper. That leaves a gap of 25 m, or 1.25 s: normal on a busy freeway.

Do: complete first_collision, then find when this platoon crashes. Hint: position = start + the running sum of (cruising speed + speed change) × dt; a crash is when the bumper-to-bumper gap reaches 0.

def first_collision(C, n_cars=9, spacing=30.0, speed=20.0, car_length=5.0, **kw):
    """Time (s) of the first collision in the platoon, or None if nobody collides.

    Every car starts at `speed` m/s with `spacing` metres from front bumper to front bumper.
    Hint: position = initial position + integral of (speed + u) dt. A collision happens when
    the gap to the car ahead, minus car_length, reaches 0.
    """
    # YOUR CODE HERE
    return "not implemented"
assert first_collision(0.4) != "not implemented", "complete first_collision first"
assert first_collision(0.4) is None, "a stable platoon (C = 0.4) should never collide: check your gaps"
C_crash, spacing = 0.9, 30.0
t_crash = first_collision(C_crash, spacing=spacing)
print(f"C = {C_crash:g}, {spacing:g} m apart: first collision at t = {t_crash} s")

Check your prediction from the top: nine sensible drivers, one gentle brake tap. Did you say crash?

Think. Every driver in this platoon follows a sensible rule. Who is to blame for the collision? What does that mean for automated vehicles that follow each other closely?

B2 · Game: save the platoon 🌶🌶 Extend

Your nine drivers, all at C = 0.9, crash. You may swap one of them for a calm driver (C = 0.3). simulate takes a list with one C per car, as in the cell below.

Predict first (not graded). Which seat should the calm driver take: right behind the leader, in the middle, or at the back? Can one calm driver save everyone?

Do: run the cell (it uses your first_collision from B1). It tries every seat.

assert first_collision(0.4) != "not implemented", "complete first_collision in B1 first"
for seat in range(1, 10):
    C = [0.9] * 9
    C[seat - 1] = 0.3
    t_hit = first_collision(C)
    result = "no crash" if t_hit is None else f"crash at {t_hit:.1f} s"
    print(f"calm driver in seat {seat}: {result}")
print(f"nobody calm: crash at {first_collision(0.9):.1f} s")

Think. Which seats saved everyone, and which did not? Why is a calm driver near the back too late? Plot the gaps to find out.

B3 · Going further 🌶🌶🌶 Challenge

Do: pick one of the three and find the answer with simulate and your first_collision.

  • Fewest calm drivers. How many calm drivers make the platoon crash-free, and which seats work? With 15 cars, no single seat is enough: bragging rights for the fewest that save all 15.

  • Order does not matter? Put the calm driver in seat 2, then in seat 6, and plot the last car’s speed change both times. The two curves are identical. Why? Hint: the model is linear.

  • Faster reactions. Keep \lambda fixed and halve T: what happens to C, and to the crash? What does that suggest for automated cars that react in 0.1 s?