Appendix L — Answers to Selected Exercises

Every chapter ends with an exercise set in five parts: concepts (A), calculations (B), data and code (C), strategy and judgment (D) and mixed or research problems (M and E). Many of those problems already carry a worked solution inside a collapsible Solution or Reveal block in the chapter's own exercises.md. This appendix fills in the rest. For every chapter it gives:

  • Calculations (Part B). Where a chapter's Part B solutions are already worked in the exercises file, this appendix points you there instead of repeating them. Where they are not, it works them here, with every step of the arithmetic shown.
  • Data and code (Part C). Three or four of the problems that have no solution in the chapter. Each answer gives a short excerpt of the code, the real output and an interpretation.
  • Strategy and judgment (Part D). One or two problems without a solution in the chapter, where there are any. These are worked from numbers computed for this appendix or established in the chapters.

Concept questions (Part A) and research problems (Part E) are left to you. They are open-ended by design, and a model answer would close down exactly the thinking they are meant to start.

How the answers were verified

No number in this appendix was typed from memory. Every data answer was computed by a script in appendices/code/, with one script per chapter named answers_part1_chNN.py (Chapters 1–20) or answers_part2_chNN.py (Chapters 21–40). Each script prints a header such as == C3 for each exercise it answers, and each output block below is pasted from a real run, saved alongside as appendices/code/output/answers_part1_chNN.txt. The scripts make no network calls. They read the book's data snapshot in data/processed/ through the toolkit and the project/boxbox modules, exactly as the chapters do, and every random step is seeded (seed 42), so you should get the same numbers. Run one from the book root:

python appendices/code/answers_part1_ch13.py

Three conventions apply throughout:

  1. Your answer may differ in the last digit, and that is fine. Many exercises leave choices open, such as a smoothing window, a clean-lap filter, or whether to include the leader. Where a choice changes the answer materially, the answer says which choice it made. Match the shape of the result before you worry about the third decimal.
  2. The data sometimes disagrees with the exercise. Most data exercises state an "expected shape". Where the real output does not match it, the answer reports what the data shows and says so plainly. A mismatch between expectation and data is a result, not a mistake to paper over.
  3. Some exercises ask for more than the data can give. OpenF1 has no steering angle, no brake pressure, no tyre temperatures and no fuel load, and it has telemetry only for qualifying, sprint and race sessions. Where an exercise runs into one of these limits, the answer explains what cannot be answered and works the closest question that can.

Degradation and race-pace numbers always say which fuel correction they use, because the answer depends on it (Chapter 20). For the statistical methods behind the intervals, see Appendix E; for column definitions, see Appendix B.

Chapter 1

Chapter 1 — What Makes an F1 Car Fast? · exercises · verification script: appendices/code/answers_part1_ch01.py

Worked in the chapter. B1–B9 (all of Part B) and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

C1. Analyze this session

We load the 2026 Monaco GP qualifying session, take the pole-sitter's fastest lap, and apply the same toolkit helpers that code/01_first_speed_trace.py uses on Montreal.

s = f1data.session(2026, "monaco", "Q")
pole = f1data.results(s).sort_values("position").iloc[0].acronym
lap = telemetry.fastest_lap_telemetry(s, pole, with_location=True)
ts = telemetry.top_speed(lap)
corners = telemetry.corners_from_speed(lap)
ft = telemetry.full_throttle_share(lap)
pole ANT, lap time 72.051 s, 269 samples
sampled top speed 289 km/h; slowest corner 45 km/h; corners found 9; full throttle 52.1 % of distance
Montreal pole lap for comparison: corners found 6, full throttle 74.0 %

Antonelli's pole lap (72.051 s) reaches a sampled top speed of 289 km/h. Its slowest corner is 45 km/h (the hairpin), corners_from_speed finds 9 corners, and the car is at full throttle for 52.1% of the distance. These sit close to the book's 2026 profile values (286 km/h, 45.7 km/h, 52.6%). The small gaps are expected: the profile is a median over the top five laps, and a single lap's sampled maximum depends on where the 3.7 Hz samples happen to fall. The expected shape holds on three counts: a top speed below 300 km/h, a slowest corner below 50 km/h, and a full-throttle share near half the lap. The corner count does not quite match: 9 against Montreal's 6 is 1.5 times, not "roughly twice". corners_from_speed counts a corner only if it has a 20 km/h prominence and sits at least 120 m from the previous one. Monaco's closely spaced slow corners merge under those rules, so the count comes out lower than the profile's 11 braking zones.

C2. Compare these drivers

We run ph.lap_g_forces for each driver on one shared track line, join the longitudinal and 1 s lateral series on time_s, and summarise.

line = ph.session_line(sm)
for drv in ("HAM", "RUS"):
    r = ph.lap_g_forces(sm, driver=drv, official_m=official.get("rodriguez"), line=line)
    gg = r["lon"].merge(r["lat_w"][["time_s", "ay_g"]], on="time_s").dropna()
    gg["combined_g"] = np.hypot(gg.ax_g, gg.ay_g)
    brake = -ph.sustained_peak(r["lon"].ax_g, r["lon"].time_s, 0.5, "min")
    lat = r["lat_w"].ay_g.max();  above3 = 100 * (gg.combined_g > 3).mean()
driver  lap_s  quality_ok  frozen_s  brake_held_0p5s_g  lat_1s_peak_g  pct_time_above_3g
   HAM 76.514        True      0.84              4.020          3.721              8.868
   RUS 76.523        True      0.00              4.169          3.807             10.258
differences HAM - RUS: braking -0.15 g, lateral -0.09 g, time above 3 g -1.4 pts

Both laps pass the quality gate. Hamilton's numbers are: held braking peak 4.02 g, 1 s lateral peak 3.72 g, and 8.9% of the lap above 3 g combined. Russell's are 4.17 g, 3.81 g and 10.3%. The differences, 0.15 g and 0.09 g, are well inside the method's uncertainty: on the Canada pole lap, changing only the smoothing window from 0.5 s to 1.0 s moved the braking peak from 4.83 g to 4.02 g (Section 1.5). As expected, the two sets of numbers are indistinguishable.

A 0.009 s gap is about 0.01% of the lap. That is a few metres of distance, and far below anything a g-g comparison at 3.7 Hz can resolve. Peak g measures how hard a car is pushed at its extremes. Lap time depends on the whole speed profile, and is decided mostly by minimum corner speeds and exit speeds held over distance, so a lap with slightly lower peaks can still be faster.

C6. Build the strategy

The function scales every speed below 200 km/h by $\sqrt{1 - f}$ and recomputes $T = \oint ds/v$ on the integrated distance.

def time_lost_from_grip_loss(tel, fraction, v_cut=200.0):
    v = tel.speed.to_numpy(float)
    v_new = np.where(v < v_cut, v * np.sqrt(1 - fraction), v)
    t0 = ph.lap_time_from_trace(tel.distance_m, v)
    t1 = ph.lap_time_from_trace(tel.distance_m, v_new)
    return t0, t1, t1 - t0
monaco  ANT  integral 72.266 s -> 72.752 s  loss 0.487 s (0.67 %); 65.8 % of samples below 200 km/h
monza   RUS  integral 81.893 s -> 82.053 s  loss 0.159 s (0.19 %); 19.6 % of samples below 200 km/h

A 2% grip loss costs about 0.49 s at Monaco and 0.16 s at Monza, three times as much in absolute terms and 0.67% against 0.19% of the lap. That matches the expected shape: Monaco spends far more of its lap slow. (As a check on the arithmetic, $\sqrt{0.98} = 0.98995$, so each slow sample's time rises by about 1.0%. Two-thirds of Monaco's samples are affected but only a fifth of Monza's.)

The estimate is too low for two reasons. First, a slower apex also means a slower exit, and that deficit is carried down the following straight, past the 200 km/h cut. Holding the fast samples fixed ignores it. Second, the braking zones before slow corners are grip-limited too, and those samples are above 200 km/h. A real grip loss would also make the car brake earlier there.

C8. Data quality

We run ph.check_lap on every driver's fastest lap, list the reasons each failing lap fails, and compute the held braking peak with and without the gate.

best = lp.loc[lp.groupby("driver_number").lap_duration.idxmin()]
for _, b in best.iterrows():
    tel = telemetry.lap_telemetry(sk, int(b.driver_number), int(b.lap_number), with_location=False)
    q = ph.check_lap(tel, official.get("suzuka"))      # frozen > 2 s, gap > 1.5 s, jump > 8 g, distance
    lon = ph.longitudinal_g(tel, 0.5)
    brake = -ph.sustained_peak(lon.ax_g, lon.time_s, 0.5, "min")
driver  lap_s    ok                                            reason  brake_held_g
   ANT 88.778 False             frozen 25.89 s; distance ratio 0.9278          3.29
   RUS 89.076 False                                     frozen 3.72 s          4.21
   PIA 89.132  True                                                            3.58
   ...
   OCO 90.309 False frozen 5.96 s; jump 30.3 g; distance ratio 1.0322         10.22
   HUL 90.358 False                        frozen 6.56 s; jump 28.7 g         11.92
   COL 90.627 False  frozen 8.6 s; jump 17.1 g; distance ratio 1.0273          9.24
   ...
failures: 17 of 22
median held braking g: passing laps 3.31, failing laps 3.74

17 of 22 fastest laps fail, far more than "several". Every failure has a frozen stretch longer than 2 s. Antonelli's pole lap is the extreme case: the gate's longest repeated speed-and-RPM run is 25.9 s, and because nothing moves during the freeze, the integrated distance comes out only 92.8% of the official length. Five laps also show speed jumps of 12–30 g between consecutive samples. These happen where a frozen value snaps back to the true speed.

Without the gate, the peak-g estimates of Section 1.5 would be corrupted in both directions. A snap-back reads as a physically impossible deceleration, and the three worst laps give "held" braking peaks of 9.2–11.9 g. A freeze over a braking zone hides the stop and drags the peak down. The median over failing laps (3.74 g) is not even ordered sensibly against the median over passing laps (3.31 g). This is why Chapter 1 reports peaks only from laps that pass, and why Anchor A uses the 2025 Suzuka lap instead.

Chapter 2

Chapter 2 — The F1 Data Pipeline · exercises · verification script: appendices/code/answers_part1_ch02.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D5 (all of Part D) have full solutions or guidance in the exercises file; open the Solution, Reveal or Guidance blocks there.

C2. Analyze this session: 2024 Japanese Grand Prix, race

We load the race with RaceData, print the summary, sort laps by duration, and count laps by track status.

rd = RaceData.load(2024, "Japanese", "R")
sm = rd.summary()
top3 = rd.laps.sort_values("lap_duration", ascending=False).head(3)
(rd.laps.track_status == "RED").sum()
l3 = rd.laps[rd.laps.lap_number == 3]          # the standing-restart lap
  laps: 908
  clean_share: 0.835
  sc_periods: 0
  vsc_periods: 0
  red_flags: 1
  winner: VER
acronym  lap_number  lap_duration track_status
    ALO           2      1714.647          RED
    PIA           2      1714.222          RED
    SAI           2      1712.219          RED
laps with track_status == 'RED': 18 on lap numbers [2]
lap 3 (standing restart): median 153.011 s, statuses {'GREEN': 18}, clean 0
laps 4-10 median for comparison: 98.354 s

(a) The summary shows one red flag and no SC or VSC periods, with 908 laps and a clean share of 0.835. (b) The three longest laps all belong to lap 2: Alonso 1,714.647 s, Piastri 1,714.222 s and Sainz 1,712.219 s, all marked RED, as expected. (c) 18 laps carry RED. Every one is lap 2, the lap that contains the stoppage, for the 18 cars still running.

The restart lap (lap 3) has a median of 153.0 s, against 98.4 s for laps 4–10, yet all 18 of its laps are GREEN. Track status comes from race-control flag windows. A standing restart happens under a green light after the red-flag window has closed, so nothing marks the lap as neutralised. It is slow because it starts from rest on the grid and includes the formation run to the line. The toolkit's caveat list explains this directly: "OpenF1 gives lap 1 a date_start equal to the restart time, so lap 1's timestamps are wrong. The lap containing the stoppage (lap 2) lasts about 28 minutes, and the standing-restart lap after it is slow without being neutralised. Exclude these laps by hand in race-pace work." The clean-lap filter already rejects all 18 restart laps (0 clean), but a raw-lap analysis would not.

C3. Compare these drivers: 2026 Monaco GP qualifying, Antonelli vs Verstappen

We check both laps for frozen runs, compute the delta at three grid steps, and then match the two laps' speed minima on the rescaled distance axis.

ant = telemetry.fastest_lap_telemetry(s, "ANT"); ver = telemetry.fastest_lap_telemetry(s, "VER")
longest_frozen_run_s(ant), longest_frozen_run_s(ver)
for step in (2, 5, 10):
    d = telemetry.delta_time(ant, ver, step_m=step)
ca, cv = telemetry.corners_from_speed(ant), telemetry.corners_from_speed(ver)
cv["distance_m"] *= ant.distance_m.iloc[-1] / ver.distance_m.iloc[-1]   # delta_time's rescale
frozen runs: ANT 0.00 s, VER 0.00 s
lap times: ANT 72.051, VER 72.094; results q3: ANT 72.051, VER 72.094
step_m= 2: final delta +0.043 s, max +0.713 s at 1224 m, min -0.117 s
step_m= 5: final delta +0.043 s, max +0.714 s at 1225 m, min -0.116 s
step_m=10: final delta +0.043 s, max +0.684 s at 1230 m, min -0.116 s
 distance_m  min_speed_kmh  d_ver  v_ver  offset_m
      200.0          112.0  188.7  114.3     -11.3
      885.0          139.2  864.2  141.4     -20.8
     1115.0           76.3 1092.6   79.3     -22.4
     1235.0           44.6 1221.7   45.7     -13.3
     ...
     2865.0           60.0 2855.7   61.6      -9.3
integrated lap length: ANT 3273 m, VER 3295 m
at the max-delta point (1225 m): ANT speed 48, VER speed 48 km/h

(a) Neither lap has a frozen run. (c) The final delta is +0.043 s, which matches the results table exactly (72.094 − 72.051). (b, d) Mid-lap the delta peaks at +0.71 s, near 1,225 m. That is the hairpin, the slowest corner on the lap (about 45 km/h). The swing is not real. Even after delta_time rescales Verstappen's integrated distance to Antonelli's 3,273 m, every one of Verstappen's speed minima sits 8–22 m earlier on the shared axis. At 45 km/h, 13 m is about 1 s of travel. The delta therefore measures the misalignment, not a time difference. Both cars pass the hairpin at 48 km/h at the point of maximum delta. The swing hardly depends on the grid step (0.684–0.714 s), which shows it comes from the distance axis rather than interpolation. A 0.7 s gain and loss inside 200 m of a qualifying lap that ends 0.043 s apart is implausible. The honest reading is that only the end-point delta, and deltas between anchor points such as sector lines, can be trusted here. This is the alignment caveat the book develops in Chapters 7 and 19.

C4. Build the coverage check for a season

We build RaceData for each 2024 race, sum missing_vs_jolpica from coverage(), and add the count of untimed lap-1s and red flags.

for _, ss in f1data.sessions(2024, "R").iterrows():
    r = RaceData.from_session_key(int(ss.session_key))
    missing = int(r.coverage().missing_vs_jolpica.fillna(0).sum())
 round       circuit  missing  lap1_null  red_flags
     8        monaco       16         20          1
    17          baku        2          2          0
     5      shanghai        1          1          0
     4        suzuka        1          2          1
   ...  (11 more races with 1 missing lap)
     2       jeddah         0          0          0
   ...  (8 more races with 0)
races with >= 1 missing timed lap: 15 of 24

15 of 24 races have at least one timed lap that Jolpica has and OpenF1 does not. 2024 Monaco has the most, 16, as expected. Monaco was red-flagged on lap 1, and OpenF1 has no lap-1 time for 20 cars, and the shortfall against Jolpica is 16 laps. Every other race is short by only one or two laps. In each of those rows, the number of untimed OpenF1 lap-1s is at least as large as the shortfall, so the gaps are lap-1 times again. Lap 1 is the lap the two sources handle differently (they never agree on its time). The coverage check counts only laps Jolpica has and OpenF1 lacks. That is why Losail and Yas Marina show untimed lap-1s but no shortfall.

C5. Deleted laps in qualifying

We parse deletions, compare clean-lap counts with and without them, and compare each driver's best clean lap. We then check whether the lap number in each deletion message points to the right OpenF1 lap, because that decides which lap exclude_deleted=True removes.

rq = RaceData.load(2026, "rodriguez", "Q")
dl = rq.deleted_laps()
c_all, c_ex = rq.clean_laps(), rq.clean_laps(exclude_deleted=True)
b_all = c_all.groupby("acronym").lap_duration.min()
b_ex = c_ex.groupby("acronym").lap_duration.min()
L = rq.laps.set_index(["driver_number", "lap_number"]).lap_duration   # deleted time vs lap n and n-1
parsed deletions: 12
clean laps: 37 -> 37 with deletions excluded
drivers whose best changes: 0
  HAM msg lap 10: deleted time 83.081 | OpenF1 lap 10: 111.044 | OpenF1 lap 9: 83.081
  SAI msg lap 11: deleted time 91.549 | OpenF1 lap 11: 78.521 | OpenF1 lap 10: 91.549
2026, deletions with a time, matched to OpenF1 lap n or lap n-1:
     same_lap       previous_lap
kind  sum count          sum count
FP1     0   390          389   390
Q       0   105          105   105
R     348   349            3   349
S      52    52            0    52
SQ      0    27           27    27
clean laps with the shifted deletion: 37 -> 37
min over ALL laps, top 6: {'HAM': 76.514, 'RUS': 76.523, 'LEC': 76.633, 'VER': 76.692, 'ANT': 76.707, 'NOR': 76.728}
HAM: 20 laps, 1 clean; fastest lap 76.514 s is_clean=False

(a) There are 12 parsed deletions, including Hamilton's TIME 1:23.081 DELETED - TRACK LIMITS AT TURN 13 LAP 10, as expected. (b) Excluding them leaves the clean laps at 37: no deleted lap was clean in the first place. The deletions were 1:23–1:41 laps that the clean filter had already dropped. (c) So no driver's best clean lap changes, and the min()-over-clean-laps order is the same either way.

The lap-number check explains why exclude_deleted=True matches deletions on the deleted lap time, not on the lap number in the message. In practice, qualifying and sprint-qualifying sessions, the lap number in a race-control deletion message is one higher than OpenF1's lap_number. Every timed deletion in 2026 qualifying (105 of 105) matches OpenF1 lap n − 1, as does every one in sprint qualifying (27 of 27). In races and sprints the numbers agree (348 of 349, and 52 of 52). Hamilton's deleted 1:23.081 is OpenF1 lap 9, not lap 10, and Sainz's deleted 91.549 s is lap 10. A filter that trusted the message's lap number would remove the lap after each deletion; in Sainz's case that is his legal 78.521 s lap, and his best clean lap would wrongly become 78.699 s. Matching on the time avoids the trap; if you write your own filter for non-race sessions, shift the message lap back by one.

Even with that fixed, a min() over clean laps cannot classify qualifying. The clean-lap rules are built for races (green running, within 107% of the stint median, no in- or out-laps). In qualifying, only 37 laps pass, and Hamilton has 1 clean lap out of 20. His fastest lap, the 76.514 s that took pole, is not clean. Only 18 of the 22 drivers have a clean lap at all. A min() over all laps does reproduce the top of the session (Hamilton 76.514, Russell 76.523, Leclerc 76.633). Even that is not the classification, though: qualifying is ranked by the last part a driver reached and by stewards' decisions, and the results table is the only place that records both.

Chapter 3

Chapter 3 — Aerodynamics · exercises · verification script: appendices/code/answers_part1_ch03.py

Worked in the chapter. B1–B7 (all of Part B), C3 (hint) and D1–D4 (all of Part D) have full solutions, hints or discussions in the exercises file; open the blocks there.

The script imports the chapter's own helpers (code/ch03_common.py), so the lap-quality rule, the top-five selection and the air density match the chapter exactly.

C1. Analyze this session

We take the top five quality-checked laps, compute each lap's top speed, median corner minimum and full-throttle share, and then take the medians.

laps = cc.top_laps(sk, n=5)
for t in laps:
    c = telemetry.corners_from_speed(t)
    r.append(dict(top=t.speed.max(), corner_med=c.min_speed_kmh.median(),
                  ft=telemetry.full_throttle_share(t)))
cc.session_density(sk)
drv   top  corner_med    ft
NOR 339.0     148.817 0.775
PIA 337.0     142.998 0.791
LEC 344.0     144.099 0.789
VER 337.0     147.108 0.810
ALB 340.0     170.093 0.774
rho 1.133 kg/m^3; median of top-5: top 339 km/h, median corner 147.1 km/h, full throttle 78.9 %
Spa ranks (1 = highest): [{'top_rank': 3, 'corner_med_rank': 7, 'ft_rank': 4}]
2025 medians over circuits: top 328 km/h, corner 123.9 km/h, ft 74.4 %

The row reproduces the expected output exactly: ρ 1.133 kg/m³, top speed 339 km/h, median corner speed 147.1 km/h and full-throttle share 78.9%. Among the 22 dry 2025 sessions on the circuit map, Spa is 3rd for top speed, 4th for full-throttle share and 7th for median corner speed, all above the circuit medians (328 km/h, 74.4%, 123.9 km/h). That puts it in the upper right of ch03-fig-05, the fast-and-fast-cornering corner of the map, next to Monza and Jeddah. Albon's lap shows why we take a median of five: its corner median of 170 km/h is far from the other four (143–149 km/h).

C2. Compare these drivers

We accumulate the per-step change in delta_time and split it by Hamilton's speed at each point, using the speed_ref column the delta already carries.

dl = telemetry.delta_time(ham, rus, step_m=5)
inc = np.diff(np.r_[0.0, dl.delta_s.to_numpy()])     # per-step change; sums to the lap delta
fast = dl.speed_ref.to_numpy() >= 250
inc[fast].sum(), inc[~fast].sum()
step  5 m: lap delta +0.009 s = -0.078 (HAM >= 250 km/h, 47.0 % of distance) + +0.087 (below 250)
step 10 m: lap delta +0.009 s = -0.083 (HAM >= 250 km/h, 46.9 % of distance) + +0.092 (below 250)
cut 200 km/h: -0.131 above, +0.140 below
cut 300 km/h: -0.067 above, +0.076 below

The two parts sum to the lap delta, as they must. Russell gained 0.078 s where Hamilton was at or above 250 km/h (47% of the distance) and lost 0.087 s below it, which matches the expected run. The story holds whatever the threshold: Russell was quicker in the fast parts and slower in the slow parts at 200, 250 and 300 km/h alike. But the size of each part depends on where you cut (0.067 to 0.131 s) and slightly on the grid step. Those numbers are also of the same order as the alignment noise this book treats as unresolvable (Chapters 7 and 19 treat integrated-distance deltas under about 0.05 s as noise). Read the direction, not the decimals. The fast/slow pattern is consistent with Russell's higher trap speed (350 km/h against Hamilton's 347, Case Study 1), but the data do not tell us whether that came from trim, deployment or tow.

C6. Fade by driver

We apply the chapter's quality rule to every classified driver's fastest lap and compute the fade (peak speed minus the last full-throttle speed) on the longest full-throttle run of each lap that passes.

for _, rr in res.iterrows():
    t = telemetry.fastest_lap_telemetry(kj, int(rr.driver_number))
    ok, why = cc.lap_quality(t, off)
    if ok:
        rows.append(dict(drv=rr.acronym, **fade_longest_run(t.reset_index(drop=True))))
 pos drv     team  run_m  peak   end  fade
  19 PER cadillac   1204 329.0 271.0  58.0
  11 VER red_bull   1221 328.0 273.0  55.0
   6 HAM  ferrari   1202 319.0 265.0  54.0
   5 NOR  mclaren   1206 323.0 272.0  51.0
   3 PIA  mclaren   1212 324.0 274.0  50.0
classified drivers 22; laps passing the quality check 5; rejected 17:
   [('ANT', 'frozen 25.9 s'), ('RUS', 'frozen 3.4 s'), ('LEC', 'frozen 4.6 s'), ...]
median fade of passing laps 54.0 km/h (range 50-58)

Only 5 of 22 laps pass the check. All 17 rejections are frozen stretches, from 2.1 s up to 25.9 s on Antonelli's pole lap. The five that pass fade by 50–58 km/h (median 54) on each lap's longest full-throttle run, about 1.2 km. That is roughly three times the chapter's 2026 season median of 18.5 km/h (Section 3.7 output), so Suzuka's long run drains the 2026 cars' electrical deployment more than most.

The table can't support a ranking of drivers. Five laps from four teams is too few, the 8 km/h spread is within what one or two telemetry samples at the end of the run can move, and the sample is not random: the frozen-feed problem hit some cars' laps and not others. Whether an excluded car fades less is unknown. The right conclusion is "every car we can see faded by about 50–60 km/h", not "Cadillac fades most".

C8. Predict the race

We rebuild the chapter's 16-circuit table (dry in both seasons, pole from the classification, 2025 corner speed from the top five laps) and fit ordinary least squares with the corner speed alone. We then ask statsmodels for a prediction interval.

m = sm.OLS(D.delta_pct, sm.add_constant(D[["corner25"]])).fit()
pr = m.get_prediction(np.array([[1.0, jed]])).summary_frame(alpha=0.05)
n = 16; delta_pct = 0.265 + 0.0202 x corner25; slope 95% CI [0.0046, 0.0359]; R^2 0.35; residual SD 0.877 %
Jeddah 2025 median corner speed 177.0 km/h -> predicted change +3.85 %; 95% CI of the mean [+2.96, +4.73];
  95% prediction interval [+1.77, +5.92] %
range of corner25 in the fit: 88.4-192.8 km/h; Jeddah 2025 pole 87.294 s; Jeddah in the 2026 data: False

The fit predicts that Jeddah's 2026 pole would be 3.85% slower than 2025, with a 95% prediction interval of +1.8% to +5.9%. On Jeddah's 2025 pole of 87.294 s, that is about +3.4 s, with a range of roughly +1.5 to +5.2 s. The single-predictor slope (0.0202% per km/h) is close to the chapter's two-predictor coefficient of 0.0189.

The interval is wide for three reasons. First, with n = 16 the slope itself is uncertain: its interval runs from 0.0046 to 0.0359, a factor of eight. Second, corner speed explains only 35% of the variance, so a single new circuit carries the full residual SD of 0.88 percentage points on top of the uncertainty in the line. Suzuka (+2.06% at 162 km/h) and Albert Park (+4.56% at 157 km/h) show how far individual circuits sit from it. Third, Jeddah's 177 km/h lies near the top of the fitted range (88–193 km/h), where the line is least well pinned.

The prediction cannot be checked: Jeddah is not on the 2026 calendar in the book's data snapshot, so this is a counterfactual, not a forecast.

Chapter 4

Chapter 4 — Tires · exercises · verification script: appendices/code/answers_part1_ch04.py

Worked in the chapter. B1–B10 (all of Part B), C1, D1, D2 and D5 have full solutions in the exercises file; open the Solution, Answer or Reveal blocks there.

C2. Compare these drivers

We take each Ferrari driver's HARD stint at the 2024 Italian GP and remove the race's own fuel + track-evolution slope, which comes from metrics.estimate_fuel_effect. Then we fit metrics.degradation to each stint.

fe = metrics.estimate_fuel_effect(lp)
lp = lp.assign(lap_time_dd=lp.lap_duration - fe["s_per_lap"] * (lp.lap_number - n))
for drv in ["LEC", "SAI"]:
    d = lp[(lp.acronym == drv) & (lp.compound == "HARD")]
    for st, g in d.groupby("stint"):
        r = metrics.degradation(g, y="lap_time_dd")
race fuel + evolution slope -0.0600 s/lap, 53 laps
  LEC stint 2 HARD laps 16-53: +0.052 s/lap [+0.044, +0.059], n = 37
  SAI stint 2 HARD laps 20-53: +0.064 s/lap [+0.046, +0.082], n = 33

Sainz degraded at +0.064 s/lap (95% CI 0.046 to 0.082, n = 33) and Leclerc at +0.052 s/lap (0.044 to 0.059, n = 37). The intervals overlap: Leclerc's whole interval sits inside Sainz's. Sainz's point estimate is 0.012 s/lap higher, which over 33 laps is about 0.4 s. But one race cannot tell that difference apart from noise. Sainz's interval is also more than twice as wide, which points to a scrappier stint (traffic, a varying pace target) rather than a slower-wearing set.

So this race does not show tyre management as an individual skill. If you want to show it, you need many races and the same car, which is the driver-comparison problem of Chapter 21. Within one race, the stint's pace target (Leclerc was defending the lead) is confounded with wear.

C4. Warm-up by season

We use the chapter's warm-up variant: fit a line to stint laps ≥ 4 (default fuel correction, dry races) and take the residual on stint lap 2. For MEDIUM sets, we split that residual by season and bootstrap the median with seed 42 and 2,000 resamples.

base = c[c.stint_lap >= 4]
k = np.polyfit(base.tyre_age.astype(float), base.lap_time_fc, 1)
e = c[c.stint_lap == 2]
warm.append(dict(year=..., compound=comp,
                 pen=float(e.lap_time_fc.iloc[0] - np.polyval(k, float(e.tyre_age.iloc[0])))))
...
est, lo, hi = metrics.bootstrap_ci(g.pen, n_boot=2000)
pooled MEDIUM: n = 1028, median 0.417 [0.358, 0.483]
  2023: n =  257, median 0.487 s, 95% CI [0.396, 0.623]
  2024: n =  249, median 0.245 s, 95% CI [0.130, 0.461]
  2025: n =  302, median 0.399 s, 95% CI [0.274, 0.514]
  2026: n =  220, median 0.495 s, 95% CI [0.320, 0.660]

The pooled value reproduces the chapter's 0.417 s (0.358 to 0.483, n = 1,028).

  • No season's interval excludes 0.417. The 2023 interval (0.396–0.623) only just includes it, and 2024's (0.130–0.461) includes it too.
  • 2024 has the smallest penalty, at 0.245 s.
  • 2026 (0.495 s, 0.320–0.660) is not distinguishable from the other seasons. On this evidence, the narrower 2026 tyres have not changed the first-flying-lap penalty on MEDIUMs by a detectable amount.

The season-to-season differences are about the same size as the interval half-widths. If you rank the seasons, the ranking will not be stable.

C5. Predict the race

We fit the compound models twice. The first fit uses only laps 1–30, and its fuel + evolution slope is estimated from those laps too, because that is all the pit wall would have had at that point. The second fit uses the full race. The quantity we compare is the time lost over a 25-lap HARD stint.

for label, sub in [("laps 1-30", lp[lp.lap_number <= 30]), ("full race", lp)]:
    fe = metrics.estimate_fuel_effect(sub, total_laps=n)
    l2 = with_dd(sub, fe["s_per_lap"], n)
    cm = fit_compound_models(l2, y="lap_time_dd")
    for comp, m in cm.items():
        print(comp, m.rate, m.warmup, m.fit["n_stints"], m.stint_time_lost(25))
laps 1-30: fuel + evolution -0.0385 s/lap [-0.0568, -0.0202], n = 529 laps
   SOFT   rate +0.250 s/lap, warm-up -0.05 s, 7 stints; 25-lap stint tyre time lost +74.9 s
   MEDIUM rate +0.193 s/lap, warm-up -0.15 s, 14 stints; 25-lap stint tyre time lost +57.8 s
   HARD   rate +0.151 s/lap, warm-up +0.14 s, 19 stints; 25-lap stint tyre time lost +45.7 s
full race: fuel + evolution -0.0595 s/lap [-0.0634, -0.0555], n = 1012 laps
   SOFT   rate +0.251 s/lap, warm-up -0.07 s, 9 stints; 25-lap stint tyre time lost +75.3 s
   MEDIUM rate +0.196 s/lap, warm-up -0.10 s, 18 stints; 25-lap stint tyre time lost +58.8 s
   HARD   rate +0.138 s/lap, warm-up +0.05 s, 34 stints; 25-lap stint tyre time lost +41.4 s

The early-race HARD model says +0.151 s/lap, against +0.138 for the full race. Over a 25-lap final stint that is 45.7 s against 41.4 s of tyre time lost. The early estimate overstates the HARD's cost by about 4.3 s, roughly a fifth of this race's 23.7 s pit loss.

Two things limit that early number:

  • The fuel + evolution slope from laps 1–30 is much less certain: its CI is −0.057 to −0.020, against −0.063 to −0.056 for the full race. Every lap's correction inherits that uncertainty.
  • The early fit rests on 19 truncated HARD stints, against 34 stints for the full race.

The SOFT and MEDIUM rates barely move (within 0.003 s/lap). The compound whose stints were cut shortest by the lap-30 cutoff is the one that moved. The lesson matches the chapter's: early in a race the wear rate is roughly right, but the fuel correction and the stint count are still uncertain.

C8. Starting compounds

We take the first stint of every starter in the dry races (tyres.dry_race_keys) and compute the compound shares within each season.

keys = tyres.dry_race_keys(allr)
st = f1data.stints(kind="R")
st = st[st.session_key.isin(keys) & (st.stint_number == 1) & st.compound.isin(COMPS)]
tab = st.groupby("year").compound.value_counts(normalize=True).mul(100).unstack()
compound  SOFT  MEDIUM  HARD  starters  races
2023      23.3    65.1  11.6       378     19
2024      12.8    72.0  15.1       397     20
2025      21.1    61.2  17.8       399     20
2026      29.2    60.3  10.5       373     17
pooled: {'SOFT': 21.5, 'MEDIUM': 64.7, 'HARD': 13.8} n = 1547
sum of |share - pooled| by season (percentage points): {2023: 4.4, 2024: 17.3, 2025: 7.9, 2026: 15.4}

The pooled shares reproduce the chapter's figures (MEDIUM 64.7%, SOFT 21.5%, HARD 13.8%, from 1,547 starters).

2024 departs most from the pool (17.3 points in total). It was the most MEDIUM-heavy season (72.0%) and had the fewest SOFT starts (12.8%).

2026 is a close second (15.4 points), and it moves the other way: SOFT starts rise to 29.2% and HARD starts fall to 10.5%. This matches Figure 1, where 2026's SOFT share of all race laps (30.1%) is more than twice 2024's (6.6%). In 2026 more drivers both start on the SOFT and use it later in the race.

D3. Design the setup

The data can't tell us what a team changed on its car. What it can do is tell us what to look for after each choice. Here are three choices, each paired with the signature it should leave in the timing data:

  1. Put more energy into the tyres on the out-lap and first flying lap. This can mean a harder out-lap (more weaving and braking load) or bringing the set out as late as the rules allow. Look for a smaller stint-lap-2 residual against the stint's own line. The 2026 Las Vegas SOFT model's warm-up of +0.99 s should shrink. The check should be done in the same session against cars that did not change their approach.
  2. Choose the setup that loads the tyres harder, within what the team can change: more front-axle work to heat the fronts, and pressures toward the low end of the minimum. Look for the gap between the first flying laps and the stint's lap 4–6 pace closing in practice long runs. If the setup is working, the remaining negative slope should come from the track (it should be shared by the whole field), not from tyres coming in late.
  3. Choose the compound and run plan for heat, not for wear. At 14 °C, wear is not the constraint (the wear rate was −0.065 s/lap after correction). The softer option and longer continuous runs keep heat in. Look for the compound with the best median pace over stint laps 2–6, rather than the lowest slope, and for any graining signature: a slope that turns positive for a few laps, then recovers.

In each case the check is a within-session comparison against other cars, because on a cold, rarely used surface the track evolution (the race's fuel + evolution slope was −0.0317 s/lap) moves everyone at once.

D4. Predict the race

Neither of the remaining 2026 races (Qatar R22, Abu Dhabi R23) is in the book's data snapshot. We therefore write the prediction for Abu Dhabi from its three earlier races in the snapshot. You can check it against the stint chart once the race appears in the data.

2023 Abu Dhabi Grand Prix: 58 laps; green-flag pit loss 22.2 s; stops among classified finishers {1: 3, 2: 17}; median stint slope (default fuel) {'HARD': 0.05, 'MEDIUM': 0.069}
2024 Abu Dhabi Grand Prix: 58 laps; green-flag pit loss 24.1 s; stops among classified finishers {1: 12, 2: 4, 4: 1}; median stint slope (default fuel) {'HARD': 0.046, 'MEDIUM': 0.097, 'SOFT': 0.16}
2025 Abu Dhabi Grand Prix: 58 laps; green-flag pit loss 22.7 s; stops among classified finishers {1: 13, 2: 7}; median stint slope (default fuel) {'HARD': 0.048, 'MEDIUM': 0.087}

Reasoning. With a 58-lap race and the chapter's 20.9-lap break-even, a constant fresh-tyre advantage would only start to pay for a second stop if each stint lasted under about 20 laps. That would mean three stints of about 19 laps.

The HARD degrades at about 0.05 s/lap here (default fuel correction), which is close to the pooled HARD rate (0.048). A 30-plus-lap HARD stint therefore costs little extra. The pit loss, 22–24 s, is close to the pooled 22.5 s, so it does not push either way.

Prediction: mainly one-stop (MEDIUM → HARD). Two of the three earlier races fit that call: 2024 had 12 one-stoppers out of 17 finishers, and 2025 had 13 out of 20. 2023 did not: 17 of 20 finishers stopped twice, which is a warning that the circuit's history alone does not settle the call.

The check is the 2026 race's stint chart. Count the one-stoppers among classified finishers, and see whether the 2026 rate of SOFT use (Exercise C8) pushes teams to a SOFT start and a second stop.

Chapter 5

Chapter 5 — Advanced Tire Physics · exercises · verification script: appendices/code/answers_part1_ch05.py

Worked in the chapter. B1–B8 (all of Part B), D1, D2, D4 and D5 have full solutions in the exercises file; open the Solution or Reveal blocks there. Two of the answers below (C2 and C6) read caches written by the chapter's own scripts 06_qualifying_prep_laps.py and 03_apex_load_sensitivity.py. Run those scripts first if code/_cache/ is empty.

C2. Compare these drivers — preparation laps

We take the chapter's run table and define an extra preparation lap as two or more laps before the first push. Then we compare each 2024 driver at Bahrain and at Las Vegas.

R = pd.read_parquet(CACHE / "ch05_quali_runs.parquet")
R["extra_prep"] = (R.prep_laps >= 2).astype(int)
sub = R[(R.year == 2024) & R.circuit_ref.isin(["vegas", "bahrain"])]
t = sub.pivot_table(index=["team_ref", "acronym"], columns="circuit_ref",
                    values="extra_prep", aggfunc="mean")
sessions: {'bahrain': {'runs': 85, 'share': 0.0, 'track_c': 21.4}, 'vegas': {'runs': 73, 'share': 0.548, 'track_c': 13.9}}
team_ref     acronym  bahrain  vegas  runs_bah  runs_veg  change_pp
alpine       OCO          0.0  100.0       3.0       4.0      100.0
aston_martin ALO          0.0  100.0       4.0       1.0      100.0
williams     ALB          0.0  100.0       4.0       2.0      100.0
red_bull     PER          0.0  100.0       5.0       1.0      100.0
alpine       GAS          0.0   83.0       3.0       6.0       83.0
...
mclaren      NOR          0.0   20.0       4.0       5.0       20.0
aston_martin STR          0.0    0.0       4.0       1.0        0.0
mercedes     RUS          0.0    0.0       5.0       5.0        0.0
             HAM          0.0    0.0       6.0       4.0        0.0
sauber       BOT          0.0    0.0       2.0       2.0        0.0
team-mate gap in Las Vegas share (pp): {'alpine': 17.0, 'aston_martin': 100.0, 'ferrari': 15.0, 'haas': 47.0, 'mclaren': 20.0, 'mercedes': 0.0, 'rb': 17.0, 'red_bull': 25.0, 'sauber': 50.0, 'williams': 33.0}
median team-mate gap 22 pp; Las Vegas drivers' share IQR 20-87 %

The shape matches the exercise's expectation, and is sharper than expected. At Bahrain, not one of 85 runs used an extra preparation lap. At Las Vegas, 54.8% of 73 runs did, and the drivers' shares spread from 0% to 100% (IQR 20–87%).

  • Most change: Ocon, Alonso, Albon and Pérez went from 0% to 100%.
  • No change: Russell, Hamilton, Stroll and Bottas stayed at 0%.

Team-mates mostly behave alike:

  • The median gap between team-mates is 22 percentage points.
  • Both Mercedes drivers did zero extra preparation laps, which looks like a team-level routine.
  • Both Alpines and both Ferraris were high.
  • The large gaps (Aston Martin 100 points, Sauber 50) come from drivers with one or two runs. Alonso and Stroll each had a single Las Vegas run.

Many cells rest on fewer than five runs, so treat any single driver's percentage as a description, not a trait.

C3. Analyze this session — a stint's curvature

We take the 2024 Belgian GP stint with the most clean laps and fit the linear and quadratic models twice: on raw lap times and on the toolkit's default-fuel-corrected times.

lp = metrics.fuel_corrected(f1data.laps(s))
for y in ("lap_duration", "lap_time_fc"):
    lin = metrics.degradation(g, y=y)
    q = metrics.degradation(g, y=y, model="quadratic")
Belgian Grand Prix: 44 laps; default correction 3.0 s / 44 = 0.0682 s per lap
stint: RUS stint 2 HARD laps 11-44, 32 clean laps
  lap_duration  linear slope -0.0524 s/lap; quadratic curvature +1.813840e-03 s/lap^2
  lap_time_fc   linear slope +0.0158 s/lap; quadratic curvature +1.813840e-03 s/lap^2
slope difference +0.0682 s/lap; curvature difference +1.34e-16

The default correction adds a straight line in lap number (100 kg × 0.03 s/kg = 3.0 s spread over 44 laps). Within a stint, tyre age and lap number rise together, so the correction moves only the slope: by exactly 3.0/44 = 0.0682 s/lap. Here it turns Russell's raw −0.052 s/lap into +0.016 s/lap, and the sign flips.

The curvature (+1.81 × 10⁻³ s/lap²) is unchanged to 10⁻¹⁶, which is floating-point rounding and even smaller than the exercise's ~10⁻¹⁴. This is the result the exercise predicted. Any fuel model that is linear in lap number can change a stint's slope but never its shape.

C6. Analyze this session — the apex bend at one circuit

We filter the chapter's apex cache to Suzuka (2024–2026 pooled) and fit both lines. The chapter's session-cluster bootstrap would have only three clusters here, so we bootstrap over laps instead (seed 42, 1,000 resamples).

d = A[A.circuit == "suzuka"]
lin = smf.ols("ay_g ~ v2k", d).fit()
quad = smf.ols("ay_g ~ v2k + I(v2k**2)", d).fit()
Suzuka: 54 apexes, 3 sessions, 9 laps; years [2024, 2025, 2026]; v 73-205 km/h
  linear    1.178 + 0.979 v2k  (R² 0.823)
  quadratic 0.959 + 1.371 v2k -0.121 v2k²  (R² 0.829); OLS 95% CI [-0.305, +0.064], p = 0.195
  lap-cluster bootstrap 95% CI of v2k² term [-0.333, +0.080] (9 laps)
  apexes per lap: {'min': 6.0, '50%': 6.0, 'max': 6.0}

The data give 54 apexes, but only 6 distinct corners: every lap contributes the same six, on nine laps over three sessions. The bend term is negative (−0.121, the same sign as the pooled seasons' −0.146 to −0.295), but it is not significant. Both intervals include zero (OLS p = 0.195), as the exercise expected.

Even with unlimited laps, one circuit cannot answer the load-sensitivity question. The apex speeds are fixed by the six corners' radii, so the fit has six x-positions, all at or below 205 km/h. The curvature of a line through six points is confounded with whatever is special about each corner: camber, bumps, kerb use, and how far the averaged line misplaces that apex. More laps reduce the noise at those six points but add no new speeds. To identify the bend, you need many corners spread across speeds, which means many circuits. That is why the chapter pools 26.

C8. Build the strategy — invert the Magic Formula

Using the assumed tyre (pacejka.DEFAULT) at 4 kN, we find the peak, then invert for each share of it.

fy = pacejka.mf_lateral(alpha, 4000.0, p)          # fine grid, 0-20 deg
peak = float(fy.max())
for share in (0.60, 0.80, 0.90, 0.95, 0.99):
    a = np.degrees(pacejka.invert_lateral(share * peak, 4000.0, p))
peak lateral force 6800 N at 6.01 deg
   60% of peak =   4080 N  ->  slip angle 1.43 deg  (24% of peak slip)
   80% of peak =   5440 N  ->  slip angle 2.26 deg  (38% of peak slip)
   90% of peak =   6120 N  ->  slip angle 2.98 deg  (50% of peak slip)
   95% of peak =   6460 N  ->  slip angle 3.61 deg  (60% of peak slip)
   99% of peak =   6732 N  ->  slip angle 4.72 deg  (79% of peak slip)
ratio slip(99%) / slip(80%) = 2.09

🧪 Illustrative model: parameters are assumptions chosen to be plausible for a current F1 car, not team data.

As expected, the slip angle roughly doubles (×2.09) between 80% and 99% of peak force. The first 80% of the force arrives in the first 2.3° of slip. The last 19% needs another 2.5°, and the last 4% (95% to 99%) alone needs 1.1°.

For the driver, the curve is flattest exactly where the last few percent of grip lives. A large change in steering (and in slip, heat and wear) buys very little extra force, and the feedback through the wheel weakens there. Going past 6° loses force, so the margin between "using 99%" and "beyond the peak" is under 1.3°. This is why the limit is hard to find and expensive to sit on lap after lap.

D3. Design the setup — cold-track qualifying plan

The field's behaviour at the cold 2026 Las Vegas session comes from the run table:

2026 Las Vegas Q: 73 runs, track median 15.8 C; extra prep lap 79.5 %; >= 2 push laps 39.7 %
other 2026 dry Q: 1474 runs; extra prep lap 14.7 %; >= 2 push laps 10.2 %
Las Vegas prep laps before first push: {1: 15, 2: 53, 3: 5}

Plan for 12 minutes on one new set of SOFTs at 14 °C:

  1. Out-lap, then a second preparation lap. The second preparation lap is a choice made on data: four of five runs at the 2026 Las Vegas session took two or more preparation laps (79.5%, against 14.7% elsewhere in 2026), and two was by far the most common count (53 of 73 runs). We do not have to argue that the lap is worth it, because the field's revealed preference is strong. We should be honest, though, that the model values the lap at only 0.044 s (Section 5.5). Its weaving and wheelspin heat is invisible in our data, so we treat that number as a lower bound, not as a reason to skip the lap.
  2. First push lap. Leave the timing so that a second push is possible before the flag.
  3. Second push lap on the same set, if the first is clean. This is also a data choice: 39.7% of Las Vegas runs pushed twice, against 10.2% elsewhere. Case Study 1 found the second push a median 0.246 s faster at Las Vegas. That gain is not different from the gain at other 2026 sessions (−0.275 s), so a second push is a general tyre-and-track effect, not a cold-track special.
  4. Timing. Leave the garage early enough for out-lap + 2 prep + 2 push laps (about five laps) to finish before the flag. Add margin for traffic on the preparation laps, which is when cars are slowest and most bunched.

What rests on data: the preparation-lap and two-push shares, and the measured repeat-push gain. What rests on the 🧪 model: the size of the warm-up benefit, and the claim that surface temperature (not carcass) is what the extra lap buys. One confound matters for 2026: Section 5.8 notes that teams can use slow laps to recharge the battery as well as to warm the tyres, so some of the preparation-lap habit may be energy management rather than tyre heating.

Chapter 6

Chapter 6 — The Power Unit · exercises · verification script: appendices/code/answers_part1_ch06.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

Every answer below uses the chapter's sample: the fastest valid lap of each top-five qualifier in dry 2025 and 2026 sessions. That is 210 laps, 110 from 2025 and 100 from 2026. The script loads them through the chapter's own helper, ch06_common.top_laps_all.

C2. Compare these drivers: energy demand

For each valid top-five lap from 2026 Monza qualifying, we run power.lap_energy_check (demand against the 11 MJ budget) and power.clipping_metrics (fade).

for r in laps:
    if r["year"] == 2026 and r["circuit_ref"] == "monza":
        ec = power.lap_energy_check(r["tel"], 2026, kind="Q", round=r["round"])
        cm = power.clipping_metrics(r["tel"])
laps rejected by the quality check: [('GAS', 'frozen 4.7 s, gap 0.96 s, dist ratio 1.016')]
 pos acr  ft_s  demand_mj  budget_mj  runs_out_m  max_fade  falling_s
   2 RUS 59.68      16.07       11.0     4126.03      10.0       9.16
   3 PIA 58.61      16.39       11.0     4120.45      15.0      11.88
   4 LEC 62.56      17.96       11.0     3514.64      16.0      10.72
   5 HAM 61.85      17.62       11.0     3553.36      14.0       9.36
   6 VER 61.31      17.59       11.0     3689.84      12.0      10.44
Spearman(demand, max fade) = 0.70; Spearman(demand, full-throttle s) = 0.90

The session's first lap in classification order (Gasly's) fails the quality check: 4.7 s of frozen telemetry. The five laps we can use are therefore P2–P6.

All five demand 16.1–18.0 MJ against the 11 MJ budget, so on a naive flat-out-from-the-line strategy all five would run dry between 3,515 m and 4,126 m. Russell has both the lowest demand (16.07 MJ) and the smallest fade (10 km/h). Across the five laps, demand and fade rank together (Spearman 0.70).

But demand ranks even more closely with full-throttle time (0.90). Demand is computed as the MGU-K cap integrated over every full-throttle sample, so a lower demand mostly means less time flat out, not a better-managed lap. Piastri's lap shows this: it has the least full-throttle time (58.6 s) but the second-largest fade.

With five laps, none of these correlations is meaningful as a statistic. The point is the mechanism. Plot demand against fade and the pattern looks like good energy management, but most of it is a consequence of each lap's throttle trace.

C3. Gearing by team

We take the 8th-gear km/h per 1,000 rpm from power.gear_speed_ratios and the median rpm at full throttle above 100 km/h, then summarise both per team across the 2026 laps.

ratio8 = power.gear_speed_ratios(r["tel"]).get(8, np.nan)
ft = t[(t.throttle >= 98) & (t.speed > 100)]
gr.append(dict(team=r["team_ref"], ratio8=ratio8, ft_rpm=float(ft.rpm.median())))
tab = gr.groupby("team").agg(laps=("ratio8", "size"), kmh_per_krpm_8th=("ratio8", "median"),
                             ft_rpm=("ft_rpm", "median"))
          laps  kmh_per_krpm_8th    ft_rpm
mercedes    29             29.05  11143.00
ferrari     30             28.62  11172.50
cadillac     1             28.60  10941.00
red_bull    20             27.97  11250.00
mclaren     20             27.45  11270.25
2026 median 8th ratio 28.60; Spearman(team 8th ratio, team FT rpm) = -0.70 over 5 teams

Only five teams reach the top five often enough to appear, and Cadillac appears on a single lap. Among the teams with 20 or more laps:

  • Mercedes runs the tallest top gear: 29.05 km/h per 1,000 rpm, 1.6% above the 2026 median of 28.60.
  • McLaren runs the shortest, at 27.45.

The teams with taller gearing do run lower full-throttle rpm. The order is almost reversed: Mercedes 11,143 rpm, McLaren 11,270, with a Spearman correlation of −0.70 over the five teams. That is what you would expect if the teams cover similar speeds with different final ratios.

The rpm differences are small, about 130 rpm or 1%. They are also measured on laps from different circuits in different proportions per team, so the circuit mix is a confound we have not removed. A fairer comparison would take, for each circuit, each team's difference from that circuit's median.

C4. The Miami change

We compute ft_falling_s on every lap, take each circuit's median, and split 2026 at round 4. Then, as the exercise suggests, we compare each 2026 circuit with its own 2025 value.

c26["period"] = np.where(c26["round"] <= 3, "R1-3", "R4-21")
c25 = cl[cl.year == 2025].groupby("circuit").ft_falling_s.median().rename("y2025")
dd = c26.set_index("circuit").join(c25, how="inner")
dd["change"] = dd.ft_falling_s - dd.y2025
 round     circuit  ft_falling_s period
     1 albert_park           8.6   R1-3
     2    shanghai          12.1   R1-3
     3      suzuka          17.2   R1-3
2026 circuit medians by period: {'R1-3': {'size': 3, 'median': 12.1}, 'R4-21': {'size': 17, 'median': 6.8}}
...
median change by period: {'R1-3': {'size': 3, 'median': 10.2}, 'R4-21': {'size': 13, 'median': 4.8}}

The raw split suggests a lot less clipping after Miami: a median of 12.1 s of falling-speed time per lap before round 4, against 6.8 s after. That would fit the rule change, since the higher superclip power holds speed better. But the comparison is weak.

  • Circuit confound. Rounds 1–3 are three circuits, two of them with long full-throttle sections (Suzuka 17.2 s, Shanghai 12.1 s). Rounds 4–21 include Monaco, Hungary, Singapore and Mexico City, where little clipping is possible.
  • Same circuits, other year. The difference-in-differences against 2025 shrinks the gap but does not remove it: +10.2 s against 2025 before Miami and +4.8 s after. Still, R4–21 contains long-straight circuits with changes as large as any before Miami (Spa +19.2, Silverstone +10.9, Miami itself +10.8).
  • Sample size. With three circuits before the change, one high or low circuit sets the "before" median.

A fair test needs more than this. You would use each circuit's 2026−2025 change, regress it on a post-Miami indicator and a circuit characteristic such as the longest full-throttle run or the 2025 full-throttle time, and bootstrap over circuits. Even then you have only three pre-Miami circuits. The honest conclusion is that the data are consistent with less clipping after Miami, but the circuit mix can explain most of the raw difference.

C7. Predict the race: fuel effect by circuit

We recompute the Abu Dhabi input from the top-five qualifying laps (cap × full-throttle time), apply the chapter's 2025 cross-circuit line, and compare with the race's own data-driven fuel effect.

ft_s = np.median([power.lap_energy_check(r["tel"], 2025, kind="Q", round=r["round"])["full_throttle_s"]
                  for r in laps if r["year"] == 2025 and r["circuit_ref"] == "yas_marina"])
kg = power.fuel_burn_per_lap(ft_s, 2025)["kg"]
pred = -0.008 + 0.045 * kg
fe = metrics.estimate_fuel_effect(f1data.laps(f1data.session(2025, "yas_marina", "R")))
Q full-throttle time (median of 5 top-5 laps) 54.686 s -> flow-limited fuel 1.519 kg/lap
predicted |s per lap| = -0.008 + 0.045 x 1.519 = 0.060
measured (data-driven, 1082 clean laps): -0.0567 s/lap [-0.0611, -0.0524]
prediction - |measured| = +0.0036 s/lap

The line predicts 0.060 s per lap. The race measured −0.0567 s per lap (95% CI −0.0611 to −0.0524), so the prediction is 0.0036 s/lap too large but inside the measured interval. Over 58 laps the difference is about 0.2 s.

Two caveats:

  • Abu Dhabi 2025 was one of the 18 races used to fit the line, so this is an in-sample check, not a true prediction. To test it properly, refit without Yas Marina and predict again.
  • The measured value includes track evolution, which makes it an upper bound on the pure fuel effect (Section 6.8). The line inherits the same bias, so the agreement does not show that the effect is all fuel.

Chapter 7

Chapter 7 — Braking · exercises · verification script: none needed (no new answers)

Worked in the chapter. Every problem this appendix covers already has a solution in the exercises file, so there is nothing new to add here. That includes B1–B7 (all of Part B), C1–C8 (all of Part C) and D1–D4 (all of Part D). The Part C solutions quote the outputs of the chapter's own scripts in code/. Run them from the chapter directory to reproduce them.

Two points carry over from the chapter to every braking answer you write. First, compare braking points on the location-based track line, not on integrated distance. On integrated distance, the second car appears to brake later than the pole-sitter in 73% of stops. On the location line that figure is 35.5% [21–53%], which is not significant. Second, treat integrated-distance differences under about 20 m as noise.

Chapter 8

Chapter 8 — Suspension, Chassis, and Mechanical Grip · exercises · verification script: appendices/code/answers_part1_ch08.py

Worked in the chapter. B1–B9 (all of Part B) and D4 have full solutions in the exercises file; open the Solution or Reveal blocks there.

The answers below read the corner-speed table that the chapter's 03_team_corner_speeds.py writes (code/output/ch08_corner_speeds.csv), and Chapter 1's apex points. Run those scripts first if the files are missing.

C2. Compare these drivers

We run setup.balance_index(..., by="driver_ref") on the 2026 rows of the corner-speed table. It is the same index as the team version, but each driver is measured on their own laps, and its bootstrap runs over sessions with seed 42.

c26 = cs[cs.year == 2026]
bi = S.balance_index(c26, by="driver_ref")
t = bi[bi.driver_ref.isin(["norris", "piastri"])].set_index("driver_ref")
            sessions  slow_rel_pct  medium_rel_pct  fast_rel_pct  index  ci_low  ci_high
norris            16        -2.222          -2.754        -2.215 -1.064  -2.676   -0.098
piastri           16        -0.917          -2.685        -2.896 -2.745  -3.027   -1.343
  |difference| = 1.681 points; CIs overlap: True
leclerc           16        -2.632          -4.142        -4.408 -2.056  -3.285   -1.149
hamilton          16        -2.128          -3.602        -3.448 -0.823  -2.828    0.612
  |difference| = 1.233 points; CIs overlap: True

Both teammate differences are larger than the 2026 median teammate difference of 0.62 points. Norris and Piastri differ by 1.68 points, Leclerc and Hamilton by 1.23. Both are close to the 1.73 of random pairs. But in both pairs the CIs overlap: Norris's interval (−2.68 to −0.10) reaches into Piastri's (−3.03 to −1.34), and Hamilton's runs from −2.83 to +0.61.

The class columns show where the McLaren gap comes from. Piastri is relatively stronger in slow corners (−0.92% against Norris's −2.22%) and weaker in fast ones (−2.90% against −2.22%). That gives Piastri the more fast-corner-leaning (more negative) index.

With 16 sessions per driver, the data cannot rule out that both pairs drive the same car character. A few sessions where one driver's best lap was compromised are enough to open a gap of this size. So these pairs do not overturn the chapter's reading that the index is mainly a car property. They do show that, for an individual pair, the index is too noisy to settle the question.

C4. Test the crossover

We resample whole laps (one lap = one circuit-session's apexes) instead of individual apexes, and add a check of how much of the residual variance sits between laps.

groups = {k: x for k, x in g.groupby(["circuit", "driver"])}
pick = rng.integers(0, len(keys), len(keys))
r = pd.concat([groups[keys[i]] for i in pick])
bb, aa = np.polyfit(r.v2, r.ay_g, 1)
boots_lap.append(S.crossover_kmh(aa, bb))
2025: n = 150 apexes on 22 laps; crossover 125 km/h; apex bootstrap 105-147; lap bootstrap 104-146 km/h
      share of residual variance that is between laps: 0.20 (about 1/6.8 = 0.15 expected if apexes were independent)
2026: n = 144 apexes on 20 laps; crossover 171 km/h; apex bootstrap 123-224; lap bootstrap 123-218 km/h
      share of residual variance that is between laps: 0.18 (about 1/7.2 = 0.14 expected if apexes were independent)

The interval does not widen, contrary to the exercise's expectation. Resampling laps gives 123–218 km/h for 2026, against 123–224 km/h when we resample apexes. Our apex-bootstrap interval differs by a few km/h from the chapter's 126–227 only because the random stream is shared with the lap bootstrap.

The reason shows in the last line of each season. Only 18% of the residual variance in 2026 (20% in 2025) is between laps. If apexes were independent, lap averages of about seven apexes would carry roughly 14–15% anyway. So apexes on the same lap are only weakly correlated after the speed effect is removed. Each lap contains both slow and fast corners, so every resampled set of laps still spans the whole speed range, and the slope and intercept stay well identified.

Resampling laps is still the right default whenever data are clustered. Here it simply turns out to matter little. The crossover's real uncertainty comes from the apex g estimator itself (Chapter 1), not from which laps were sampled.

C6. Analyze this session

We run setup.practice_runs() on 2025 Mexico City FP2 and compare the long runs with the race's starting compounds.

fp2 = f1data.session(2025, "rodriguez", "FP2")
runs = S.practice_runs(f1data.laps(fp2))
lng = runs[runs.run_type == "long"]
st = f1data.stints(f1data.session(2025, "rodriguez", "R"))
Mexico City Grand Prix Practice 2: 200 runs; by type {'no-time': 142, 'push': 25, 'long': 18, 'short': 15}
long runs by compound: {'MEDIUM': 10, 'SOFT': 6, 'HARD': 2}
acronym team_ref compound  timed_laps  start_min
    COL   alpine     SOFT          11       42.4
    LEC  ferrari   MEDIUM          10       41.8
    ANT mercedes   MEDIUM          10       43.3
    GAS   alpine   MEDIUM          10       43.4
    SAI williams   MEDIUM          10       44.5
race starting compounds: {'SOFT': 12, 'MEDIUM': 6, 'HARD': 2}

The session had 18 long runs, mostly on MEDIUM (10). There were 6 on SOFT and 2 on HARD. All five of the longest started between 41.8 and 44.5 minutes into the session, close to the chapter's FP2 median start of 44.4 minutes for long runs: push laps first, race simulation second.

The comparison with the race is the interesting part. The long-run mix does not predict the start. In FP2, MEDIUM long runs outnumbered SOFT ones 10 to 6, yet 12 of 20 cars started the race on SOFT and only 6 on MEDIUM.

A plausible reading is that FP2 long runs test the compound a team expects to race for longest, not the one it will start on. A start compound is chosen for the run to Turn 1 (Mexico City has a very long run from the grid to the first braking zone) and for the stop window, which practice data alone cannot show. The two HARD long runs match the two HARD starters in number, but the run table cannot tell us whether they were the same cars.

There are also 142 "no-time" runs. At this altitude circuit, many outings in this session were short or aborted, so treat the long-run count as small.

C8. Build the strategy input

We recompute the traction proxy (apex → throttle ≥ 98%, relative to the field median at that corner) for each team's best 2026 lap, using the chapter's method. Then we split the corners between Chapter 10's low-speed cluster (Monaco, Marina Bay) and every other circuit.

tr["t_rel"] = tr.t_full - tr.groupby(["session_key", "corner"]).t_full.transform("median")
tr["group"] = np.where(tr.circuit_ref.isin(["monaco", "marina_bay"]), "low_speed", "other")
per = tr.groupby(["group", "team_ref", "session_key"]).t_rel.median().reset_index()
tab = per.groupby(["team_ref", "group"]).t_rel.agg(["median", "size"]).unstack()
slow-corner exits: 858 in 19 sessions; low-speed cluster exits 129
              median_low_speed  median_other  size_low_speed  size_other
mercedes                -0.201        -0.158               2          17
aston_martin            -0.040        -0.081               1          16
red_bull                -0.261        -0.041               2          17
mclaren                 -0.080         0.000               2          17
rb                      -0.061         0.020               2          16
ferrari                 -0.010         0.039               2          17
audi                     0.029         0.065               2          16
alpine                  -0.339         0.119               1          15
williams                 0.171         0.121               2          15
haas                     0.199         0.160               2          17
cadillac                 0.110         0.180               2          16
Spearman(team proxy at low-speed circuits, team proxy elsewhere) = 0.65 over 11 teams (low-speed values rest on 1-2 sessions per team)

The proxy is moderately stable across circuit types: the team ranks correlate at 0.65.

  • Mercedes is among the quickest to full throttle in both groups (−0.20 s and −0.16 s).
  • Haas and Williams are among the slowest in both groups.
  • Alpine is the clear exception. It is 0.34 s quicker than the field at the low-speed circuits but 0.12 s slower elsewhere. Its low-speed figure rests on a single session.

That is the caveat for the whole low-speed column. It comes from one or two sessions per team, about 129 corner exits in total, so a single good Monaco lap can move a team's value by a tenth or more. The proxy is usable as a strategy input for the "other" circuits (15–17 sessions per team). For the low-speed cluster, it should be treated as a weak prior and shrunk toward the team's overall value.

D1. Design the setup

We run the toy's grid (heave stiffness 500–6,000 N/mm, static height 16–50 mm) with Monaco's band times for each bump amplitude. Then we cross-evaluate each best setup at the other two amplitudes.

🧪 Illustrative model: parameters are assumptions chosen to be plausible for a current F1 car, not team data.

bumps 6 mm: best feasible k 5250 N/mm, static height 26 mm -> -0.566 s; feasible share 52 %
bumps 9 mm: best feasible k 5000 N/mm, static height 29 mm -> +0.311 s; feasible share 45 %
bumps 12 mm: best feasible k 3500 N/mm, static height 34 mm -> +1.406 s; feasible share 38 %
each best setup evaluated at every bump amplitude (s; 'X' = plank contact or porpoise risk):
  setup tuned for 6 mm (k 5250, h 26): 6 mm: -0.566 | 9 mm: -0.130 X | 12 mm: +0.497 X
  setup tuned for 9 mm (k 5000, h 29): 6 mm: -0.124 | 9 mm: +0.311 | 12 mm: +0.937 X
  setup tuned for 12 mm (k 3500, h 34): 6 mm: +0.484 | 9 mm: +0.863 | 12 mm: +1.406

The choice. The setup tuned for 6 mm (k 5,250, h 26) is the fastest if the road is smooth. It becomes infeasible, with plank contact or porpoising, if the bumps are 9 mm or more.

The 12 mm setup (k 3,500, h 34) is never infeasible. On a smooth road it costs 1.05 s against the 6 mm setup (+0.484 against −0.566) and 0.61 s against the 9 mm setup (against −0.124). It also costs 0.55 s against the 9 mm setup at 9 mm (+0.863 against +0.311).

The 9 mm setup (k 5,000, h 29) is the middle option. It is feasible at 6 and 9 mm and loses only 0.44 s to the best possible setup on a smooth road. It fails only if the bumps reach 12 mm.

If we have any reason to believe 12 mm bumps are possible, take the 12 mm setup into parc fermé. Otherwise take the 9 mm setup.

The argument the toy cannot make. Parc fermé locks the setup from qualifying to the race, and an "X" in the toy is not a lap-time loss. A plank worn below its limit means disqualification. Porpoising at Monaco means a car the driver cannot place within centimetres of the barrier. The cost of being infeasible is unbounded, while the cost of being cautious is a few tenths. That asymmetry argues for the conservative 12 mm setup more strongly than any expected-lap-time calculation. Practice running on the actual surface, and the plank-wear checks, are what should resolve the uncertainty about bump amplitude.

D2. Call the pit stop

We take the race's HARD wear rate from Chapter 4's model (+0.138 s/lap, data-driven fuel correction) and the green-flag pit loss of 23.7 s. Wear is linear in tyre age, so a stint of $n$ laps loses $r \cdot n(n-1)/2$ seconds.

chosen setup, HARD 0.138 s/lap (race model, data-driven fuel): one 25-lap stint loses 41.4 s; split 12 + 13 loses 19.9 s; saving 21.5 s vs pit loss 23.7 s -> net -2.2 s for the third stop
faster setup, +0.02 s/lap: one 25-lap stint loses 47.4 s; split 12 + 13 loses 22.8 s; saving 24.6 s vs pit loss 23.7 s -> net +0.9 s for the third stop
faster setup vs chosen, over one 25-lap stint: -1.00 s (break-even tyre age 10 laps)

Working.

  • One 25-lap stint: $0.138 \times 25 \times 24 / 2 = 41.4$ s.
  • Split into 12 + 13 laps: $0.138 \times (66 + 78) = 19.9$ s.
  • A green-flag third stop therefore saves 21.5 s of wear but costs 23.7 s. With the chosen setup it is 2.2 s worse.
  • With the faster-degrading setup ($r$ = 0.158), the saving becomes 24.6 s and the third stop is 0.9 s better.

So yes: the 0.02 s/lap of extra wear is just enough to flip a green-flag third stop from unattractive to marginally attractive. A VSC (pooled loss 15.7 s) would make it clearly attractive with either setup, which is what happened in the race.

The 0.2 s/lap fresh-tyre advantage cancels out of this comparison, because it applies to every lap in both plans. Against the chosen setup, though, the faster setup is ahead only while the tyres are under 10 laps old. Over a single 25-lap stint it is 1.0 s slower in total.

What the data don't contain. We do not know:

  • whether the extra wear is linear or brings a cliff earlier;
  • the warm-up cost of a fourth set;
  • whether the team had a fresh HARD set left (allocation);
  • what track position would be lost to cars that did not stop;
  • the true effect of the setup change, since a setup's wear rate is not observable before the race.

The 0.02 s/lap figure is an assumption in the question, not something we can measure from timing data.

Chapter 9

Chapter 9 — The Driver · exercises · verification script: appendices/code/answers_part1_ch09.py

Worked in the chapter. B1–B10 (all of Part B) and D1 have full solutions in the exercises file; open the Solution or What happened blocks there.

The script reads three caches written by Chapter 9's own scripts (residuals_2023_2026.parquet, throttle_profiles_2024_2026.csv, braking_workload_2025_2026.csv) and Chapter 1's peak_g_by_circuit.csv. Run those chapters' scripts first if the files are missing.

C1. Analyze this session

We build the stint residuals for the 2026 Las Vegas race, then tabulate consistency twice: once with clean-air laps only (at least 15 laps) and once with all laps (at least 10).

s = f1data.session(2026, "Las Vegas", "R")
r = driver.stint_residuals(f1data.laps(s))
ca = driver.consistency(r, min_laps=15).sort_values("robust_sd_s")
al = driver.consistency(r, min_laps=10, clean_air_only=False).sort_values("robust_sd_s")
nor = r[r.driver_ref == "norris"]
clean air only, min_laps=15:
       driver_ref   n  robust_sd_s  error_laps
0  max_verstappen  32        0.149           2
1   rafael_camara  20        0.226           1
2      hulkenberg  25        0.269           1
all laps, min_laps=10:
       driver_ref   n  robust_sd_s  error_laps
0  max_verstappen  40        0.193           2
1           sainz  40        0.242           4
2   rafael_camara  39        0.273           4
3         russell  40        0.277           2
4          hadjar  37        0.342           4
5           gasly  40        0.374           5
drivers in clean-air table: 3; in all-laps table: 21
Norris: 40 residual laps, clean-air laps 0, position_end range 2-11
all-laps rank of the clean-air drivers: {'hulkenberg': 8, 'max_verstappen': 1, 'rafael_camara': 3}

Answer. With clean air only, Verstappen has the lowest robust SD, 0.149 s over 32 laps, which matches the expected value. Only three drivers reach 15 clean-air laps in this race, so the "ranking" is really a short list. With all laps, 21 drivers qualify. Verstappen still leads (0.193 s), Sainz (0.242) and Rafael Camara (0.273) follow, and Hülkenberg drops to eighth. The order of the three drivers who appear in both tables does not change.

Norris is missing from the clean-air table because he never had a clean-air lap: 0 of his 40 residual laps had a gap of at least 2 s to the car ahead on both that lap and the previous one. He ran between P2 and P11 all race, always in someone's wake. His all-laps SD measures traffic as much as it measures him. That is exactly why the chapter's headline consistency numbers use clean air.

C2. Compare these drivers

For 2025 only, we express each lap's partial and overlap share as points relative to that session's median. Then we subtract the team mean in that session to get the within-team view. Drivers with fewer than five sessions are dropped.

T = T[T.year == 2025].copy()
for col in ["partial", "overlap"]:
    T[col + "_dev"] = 100 * (T[col] - T.groupby("session_key")[col].transform("median"))
    T[col + "_win"] = T[col + "_dev"] - T.groupby(["session_key", "team_ref"])[col + "_dev"].transform("mean")
2025 valid laps 366, sessions 22, driver rows with >= 5 sessions 21
    driver_ref     team_ref  n  partial_raw  overlap_raw  partial_win  overlap_win
      hamilton      ferrari 22         0.88         2.80         0.06         0.49
        doohan       alpine  5         2.06         2.40         1.32         0.61
          ocon         haas 14        -0.97         2.31         0.05         0.02
       leclerc      ferrari 22         0.36         2.00        -0.06        -0.49
         sainz     williams 18        -0.42         1.86        -1.07         0.63
  ...
       piastri      mclaren 22         1.68        -1.12         0.48         0.04
        norris      mclaren 22         0.41        -1.21        -0.48        -0.04
team median overlap (points vs session median): ferrari 2.51, haas 2.03, alpine 1.41 ... rb -0.74, mclaren -1.14
partial: SD across drivers raw 1.08 pts, within-team 0.71 pts; Spearman raw vs within 0.48
overlap: SD across drivers raw 1.23 pts, within-team 0.35 pts; Spearman raw vs within 0.16

Answer. The raw overlap ranking is a team ranking. Both Ferrari drivers are in the top four (Hamilton +2.80, Leclerc +2.00 points), and both McLaren drivers are at the bottom (−1.12, −1.21). Once the team mean is removed, the spread across drivers shrinks from 1.23 to 0.35 points. The two orderings are almost unrelated (Spearman 0.16).

The overlap ranking changes far more than the partial-throttle ranking. Partial throttle keeps more of its order (Spearman 0.48) and more of its spread (1.08 → 0.71 points). The reason is the chapter's between-team variance shares: overlap is 0.62 between teams, against 0.21 for partial throttle. Overlap is mostly a property of the car and its brake and throttle mapping, so taking out the teammate removes most of it. Partial throttle is more personal, so more of the raw ranking survives.

The result matches the expected shape: Ferrari near the top of the raw overlap ranking, with small differences inside the team. Our table has 21 rows rather than 20, because Doohan (5 sessions) and Colapinto (6) shared one Alpine seat during 2025.

C5. Predict the race

We take the dry clean-air laps in the residual cache and put each lap into a lap-number band. An error lap is one more than 1 s above the stint line. We compute the error rate with a Wilson interval, overall and then within running-position bands. A logistic regression with a position-band control summarises the trend.

CA["lap_band"] = pd.cut(CA.lap_number, [1, 10, 25, 40, 200], labels=["2-10", "11-25", "26-40", "41+"])
CA["pos_band"] = pd.cut(CA.position_end, [0, 3, 6, 10, 15, 30], labels=["P1-3", "P4-6", "P7-10", "P11-15", "P16+"])
CA["err"] = CA.resid_s > 1.0
tab = CA.groupby(["pos_band", "lap_band"], observed=True).err.apply(fmt).unstack()
m = smf.logit("err ~ lapc + C(pos_band)", data=CA.assign(err=CA.err.astype(int))).fit(disp=0)
dry clean-air laps 36,613, races 79
all positions:
  laps 2-10    1.5 (1.1-2.2) n=1845
  laps 11-25   1.6 (1.3-1.9) n=8600
  laps 26-40   2.9 (2.6-3.2) n=10613
  laps 41+     5.7 (5.3-6.1) n=15555
lap band x position band (error %, Wilson 95% CI, n):
                          2-10                  11-25                  26-40                      41+
P1-3       1.8 (1.1-3.0) n=831   1.0 (0.6-1.5) n=2261   1.1 (0.8-1.6) n=2471     2.4 (1.9-3.0) n=3423
P4-6       1.4 (0.5-4.0) n=217   1.0 (0.6-1.6) n=1347   1.6 (1.1-2.3) n=1770     2.2 (1.7-2.8) n=2701
P7-10      0.4 (0.1-2.4) n=231   1.1 (0.7-1.7) n=1628   1.4 (1.0-2.0) n=2234     4.1 (3.5-4.8) n=3475
P11-15     1.3 (0.4-4.6) n=153   1.1 (0.7-1.8) n=1477   3.7 (3.0-4.6) n=2055     8.4 (7.6-9.4) n=3566
P16+       1.7 (0.8-3.5) n=413   3.6 (2.8-4.5) n=1887   7.1 (6.0-8.2) n=2083  12.7 (11.4-14.1) n=2390
share of laps at P11+ by lap band: {'2-10': 0.307, '11-25': 0.391, '26-40': 0.39, '41+': 0.383}
logit, per 10 laps with position-band control: OR 1.470 [1.416, 1.526], p 2.64e-90

Answer. Error laps are more frequent late in a race, not early. The rate rises from 1.5% on laps 2–10 to 5.7% on laps 41 and later. The trend survives the position control. The share of laps run at P11 or lower is nearly flat from lap 11 onward (0.39, 0.39, 0.38), so a changing position mix cannot explain the rise. The controlled odds ratio is 1.47 per 10 laps (95% CI 1.42–1.53), slightly steeper than the uncontrolled 1.42.

The rise is steepest at the back. At P16 and lower the rate goes from 3.6% to 12.7%. At P1–3 it only goes from 1.0% to 2.4%, and that top band's increase is still clear of its interval. Early laps show no excess: the "full tanks, cold tyres" story is not visible once lap 1 and out-laps have been removed, as the residual table already does.

The data cannot say which late-race cause is at work. Back-markers being lapped (blue flags), old tyres and fatigue all grow with lap number. The front-runners' smaller rise suggests most of the effect is about lapping traffic, not drivers tiring. The Part E3 "being lapped" flag is the test that would separate them.

C9. Build the strategy

We rank the 2026 circuits by brake_min_per_race, which is seconds on the brake per qualifying lap multiplied by race laps. Then we multiply by Chapter 1's held 0.5 s braking peak for the same round.

B = pd.read_csv(CH9 / "braking_workload_2025_2026.csv"); B = B[B.year == 2026]
G = pd.read_csv(CH1 / "peak_g_by_circuit.csv"); G = G[G.year == 2026]
M = B.merge(G[["round", "brake_held_g"]], on="round")
M["impulse"] = M.brake_min_per_race * M.brake_held_g
 round   circuit_ref  race_laps  zones_per_race  brake_min_per_race  brake_held_g  impulse  rank_min  rank_imp
     6        monaco         78             936               26.73          4.10   109.49         1       1.0
    17    marina_bay         62             682               22.20          4.36    96.68         2       2.0
    19     rodriguez         71             710               21.72          4.02    87.34         3       3.0
    11   hungaroring         70             700               18.62          3.94    73.46         4       5.0
     2      shanghai         56             448               18.03          4.25    76.66         5       4.0
    15          baku         51             510               16.93          3.81    64.52         6       8.0
     5    villeneuve         68             408               16.37          4.33    70.81         7       6.0
    16       sepang         55             440               16.25          3.90    63.34         8       9.0
    18      americas         56             504               15.79          4.48    70.78         9       7.0
  ...
     9   silverstone         52             312                8.39          3.66    30.70        19      19.0
    10           spa         44             264                7.07          3.66    25.88        20      20.0
circuits with both values: 20; Spearman minutes vs impulse ranking 0.99; max rank move 2

Answer. Monaco has the most braking at 26.7 minutes per race, followed by Marina Bay (22.2) and Mexico City (21.7). Spa has the least (7.1). Weighting by braking g hardly changes the order. The Spearman correlation between the two rankings is 0.99, and no circuit moves more than two places. The small moves go the way the exercise expected: circuits with fewer but harder stops move up (Austin 9 → 7, Montreal 7 → 6, Shanghai 5 → 4), and Baku moves down (6 → 8). But the "reordering" is minor. Minutes on the brake vary about fourfold across the calendar, while the median held g varies only from 3.42 to 4.48, so minutes dominate the product.

What is measured and what is estimated. The brake-on time per lap comes from the 0/100 brake channel on one valid qualifying lap, sampled at about 3.7 Hz. Race laps come from the results. Both are measurements, but a qualifying lap stands in for every race lap, which overstates braking for laps run on heavier fuel and with lift-and-coast. The braking g is an estimate: speed is differentiated and then smoothed over a 0.5 s window. The "impulse" is a proxy for load on the driver, not a physical impulse, because it ignores how the g is distributed within each stop.

D3. Simulator policy

Recommendation: (c), per-driver models shrunk toward the field. Start with a weight of about 0.3 on the driver's own σ and about 0.15 on the driver's own error rate.

A season-to-season correlation is a direct measure of how much of one season's value is signal for the next. For lap-to-lap consistency it is 0.23–0.47, so roughly a third of a driver's deviation from the field carries over. For the position-adjusted error ratio it is −0.01 to 0.39, which in the latest season pair is almost nothing.

Option (b) treats this season's value as fully persistent. It would give a driver with a lucky clean season a simulated advantage that mostly will not reappear. Option (a) throws away the part that does persist. In a simple normal model, the best prediction is the field value plus the reliability times the driver's deviation, which is why the reliability is a sensible starting weight.

For a driver measured at σ = 0.240 s against the 2026 field's 0.290 s:

$\sigma_{\text{sim}} = 0.3 \times 0.240 + 0.7 \times 0.290 = 0.072 + 0.203 = 0.275$ s.

The error probability should be shrunk harder, with a weight of 0.1–0.2, because both its year-to-year correlation and its counts are small. Then re-estimate the weight each season from the new year-to-year correlation, and give drivers with fewer clean-air laps less weight on their own data.

Chapter 10

Chapter 10 — The Circuit · exercises · verification script: appendices/code/answers_part1_ch10.py

Worked in the chapter. B1–B8 (all of Part B) have full solutions in the exercises file. D1–D5 are covered by the Notes for Part D block at the end of Part D. Open those blocks there.

The script reads Chapter 10's saved code/output/ch10_profiles.csv and ch10_grid_finish.csv. Run that chapter's 01_circuit_profiles.py and 06_air_and_grid.py first if the files are missing.

C1. Analyze this session

We profile the Hungaroring for both seasons with circuit_profile and put the two side by side. To see whether the change is unusual, we compare it with every circuit's full-throttle change in the profile table.

for yr in (2025, 2026):
    c = C.circuit_profile(yr, "hungaroring", with_strategy=False)
    rows[yr] = {k: getattr(c, k) for k in keep}
H = pd.DataFrame(rows); H["change"] = H[2026] - H[2025]
2025 Hungarian Grand Prix (hungaroring): 4381 m, 65.8% full throttle, mean 207.8 km/h, top 319 km/h, 8 braking zones,
  corners 3 slow / 5 medium / 1 fast, longest straight 519 m, elevation range 34.6 m
                     2025   2026  change
full_throttle_pct    65.8   57.7    -8.0
braking_zones         8.0   10.0     2.0
top_speed_kmh       319.0  332.0    13.0
mean_speed_kmh      207.8  202.0    -5.8
slow_corners          3.0    5.0     2.0
medium_corners        5.0    3.0    -2.0
longest_straight_m  518.8  458.7   -60.1
same-circuit change in full-throttle share 2025->2026: median -3.31 pts over 18 circuits; Hungaroring -8.04, rank 3 of 18

Answer. The numbers match the expected values: 65.8% full throttle and 8 braking zones in 2025, against 57.7% and 10 in 2026. The drop is 8.0 points; the exercise's 8.1 is the difference of the rounded values. That drop is the third largest of 18 circuits, against a median of −3.31 points.

Case Study 2 explains why. The 2026 power unit takes a much larger share of its power from the electrical side (350 kW of MGU-K). Once the lap's deployment is spent, the car stops gaining speed even with the throttle pinned, so some drivers lift or coast earlier instead of holding a throttle that gains nothing. That removes full-throttle distance.

This is an inference from the signature in the throttle and speed traces. We have no energy or battery channel to confirm it. The two extra braking zones and the two medium corners that became slow ones fit the same picture, with more decelerations and slower apexes on a lap that also lost 5.8 km/h of mean speed.

The higher top speed (+13 km/h) is not a contradiction. The sampled maximum is a single point on the lap, while the full-throttle share depends on the whole lap.

C4. Sensitivity of the corner detector

We take the 2026 Silverstone pole-quality lap and run corner_table at three prominence settings.

laps, rej = C.top_laps(f1data.session(2026, "silverstone", "Q"), n=1)
acr, team, pos, tel = laps[0]
for prom in (10, 20, 30):
    cn = C.corner_table(tel, prominence_kmh=prom)
lap used: ANT (mercedes), qualifying P1; rejected before it: []
prominence 10 km/h:  8 corners  {'slow': 4, 'medium': 1, 'fast': 3}  min speeds 108, 87, 167, 114, 282, 219, 236, 102
prominence 20 km/h:  6 corners  {'slow': 4, 'medium': 0, 'fast': 2}  min speeds 108, 87, 114, 219, 236, 102
prominence 30 km/h:  5 corners  {'slow': 4, 'medium': 0, 'fast': 1}  min speeds 108, 87, 114, 219, 102

Answer. The detector finds 5 corners at 30 km/h prominence, 6 at 20 and 8 at 10. As expected, every corner added below 30 km/h is fast or medium: the four slow corners are found at every setting. Going from 30 to 20 adds a 236 km/h dip. Going from 20 to 10 adds a 167 km/h medium corner and a 282 km/h dip.

The 282 km/h minimum is a small lift in a flat-out sweep, worth only 10–20 km/h. It costs some time, but it does not limit speed the way a braking corner does. We would keep the 20 km/h default. It keeps the 219 and 236 km/h corners, where the car clearly slows, and drops the near-flat lift. Silverstone has 18 official corners, so even the 10 km/h setting shows that most "corners" on the official map never limit speed on a pole lap.

C7. Air density and the speed trap

For each 2025 and 2026 dry qualifying session we take the median-weather air density and the highest official speed-trap reading (st_speed) among the top five qualifiers.

order = C._quali_order(sk).head(5).driver_number.astype(int).tolist()
st = lp[lp.driver_number.isin(order)].st_speed.max()
rho = 100 * w.pressure.median() / (R_D * (w.air_temperature.median() + 273.15))
r, pv = spearmanr(t.rho, t.st_speed)
2025: n = 22  Spearman density vs speed trap -0.22 (p = 0.315); trap vs sampled top speed +0.76; highest traps: monza 352, rodriguez 351, miami 341
      without Mexico City: n = 21, Spearman -0.12 (p = 0.605)
2026: n = 20  Spearman density vs speed trap -0.34 (p = 0.139); trap vs sampled top speed +0.63; highest traps: rodriguez 350, monza 338, catalunya 336
      without Mexico City: n = 19, Spearman -0.23 (p = 0.336)

Answer. Mexico City leads the 2026 trap table (350 km/h). In 2025, however, it does not: Monza's trap (352) beat Mexico City's (351) by 1 km/h, so the expected result does not hold that year.

The density correlation has the expected sign in both years but is weak and not significant: ρ = −0.22 (n = 22, p = 0.32) in 2025 and −0.34 (n = 20, p = 0.14) in 2026. Without Mexico City it shrinks to −0.12 and −0.23. The section 10.5 version, which uses the sampled top speed, gave −0.24 and −0.55 (p = 0.011). The 2026 result therefore depends partly on which "top speed" we measure.

The trap sits at one fixed point, which may not be the end of the longest straight, and it reads a single car passing. Thin air is one input among several. Straight length, wing level and, in 2026, energy deployment matter at least as much. Mexico City is the only circuit where density is far from the rest, so the correlation is essentially a one-circuit result.

C11. Predict the race: grid power by circuit type

We join each circuit's median grid-to-finish Spearman correlation (2023–2026) to its 2026 speed type. Then we test the low-speed group against the rest by shuffling the type labels across circuits.

lab, info = C.classify_circuits(prof[prof.year == 2026], random_state=42)
per_circ = G.groupby("circuit_ref").agg(rho=("rho", "median"), races=("rho", "size")).join(types, how="inner")
obs = np.median(x[is_low]) - np.median(x[~is_low])
rng = np.random.default_rng(42)
perm = np.array([np.median(x[p]) - np.median(x[~p]) for p in (rng.permutation(is_low) for _ in range(10_000))])
                              circuits  races  median_rho
high-speed / low-drag                8     32       0.821
low-speed / traction-limited         2      8       0.845
medium-speed / mixed                10     33       0.830
low-speed circuits: {'marina_bay': {'rho': 0.807, 'races': 4}, 'monaco': {'rho': 0.882, 'races': 4}}
observed: median rho low-speed minus others = +0.016; two-sided permutation p = 0.836 (10,000 shuffles of type labels across 20 circuits, seed 42)
race-level SD of rho 0.172; races per group for 80% power at alpha 0.05 to detect 0.016: about 1785

Answer. The low-speed type has the highest median grid–finish correlation (0.845), but only just: the high-speed type has 0.821 and the medium-speed type 0.830. The two low-speed circuits disagree with each other. Monaco (0.882) is near the top of the calendar. Marina Bay (0.807) is below the overall median of 0.81.

The permutation test gives p = 0.84, so there is no evidence that low-speed circuits have more grid power. Only 2 circuits and 8 races sit in the low-speed group. Race-level correlations vary a lot (SD 0.172). A normal-approximation calculation gives about 1,800 races per group to detect a gap of 0.016 with 80% power. Even a gap ten times larger would need about 18 races per group, more than the data will ever hold for two circuits.

The honest conclusion is that this question cannot be answered with circuit types. Monaco's reputation as a grid-decides circuit fits its own number, but it cannot be generalised to its speed type.

Chapter 11

Chapter 11 — Lap-Time Simulation · exercises · verification script: appendices/code/answers_part1_ch11.py

Worked in the chapter. B1–B10 (all of Part B) and D1–D4 have full solutions in the exercises file; open the Solution or Discussion blocks there.

The script imports Chapter 11's helper module ch11_common.py and reads its cache: the track cases, the fitted parameters, sensitivity.csv and residuals_final.parquet. It also reads Chapter 7's circuit_braking.csv and Chapter 10's ch10_profiles.csv. Run those chapters' scripts first if the caches are missing.

🧪 Illustrative model: the simulated car's parameters are assumptions or fits to timing data, not team data.

C1. Analyze this session — 2026 Monaco GP qualifying

We take the 2026 Monaco case and apply the all-season 2026 fit. Then we simulate, compare with Antonelli's pole lap on the location-based line, and print SimResult.summary(). For context, we run every 2026 circuit the same way.

cases = C11.all_cases(verbose=False); fit = C11.load_fit()
c = C11.get_case(cases, 2026, "monaco")
p = C11.params_for(c, fit[2026])
sim = lapsim.simulate_lap(c["track"], p)
cmp_ = lapsim.compare_to_lap(sim, c["aligned"])
print(sim.summary())
reference lap: ANT 72.051 s
sim 72.405 s  error +0.354 s  RMS speed 20.3 km/h
summary: {'lap_time_s': 72.405, 'top_kmh': 321.0, 'min_kmh': 50.2, 'energy_mj': 10.58, 'v_clip_kmh': None,
          'deploy_frac': 1.0, 'time_corner': 0.03, 'time_brake': 0.331, 'time_traction': 0.374, 'time_power': 0.266}
deploy budget 11.678990941769136 MJ; real top sample 289 km/h
2026 circuits: 20; deploy_frac median 0.570
    circuit  deploy_frac  time_corner  time_power  energy
     monaco        1.000        0.030       0.266  10.580
  rodriguez        0.961        0.021       0.384  11.623
  ...
   baku        0.461        0.018       0.548  11.524
  vegas        0.461        0.013       0.667  11.561
    spa        0.398        0.014       0.682  11.542

Answer. With the all-season fit, the simulated lap is 72.405 s, 0.354 s slower than the pole lap, with an RMS speed error of 20.3 km/h. As the exercise expected, this is close to the out-of-sample fold (+0.539 s, 19.7 km/h). The lap time splits into:

Limiting mode Share of lap time
Traction-limited 37.4%
Braking 33.1%
Power-limited 26.6%
Steady at the corner limit 3.0%

Monaco's deployment share is 1.0, the only circuit at full deployment; the 2026 median is 0.57. The reason is that the budget never binds. The lap spends only 10.58 MJ of the 11.68 MJ available, because the straights are short and much of the "power" time is spent accelerating out of slow corners, where the MGU-K can deploy at full rate throughout. On Spa or Las Vegas, the same budget runs out on the long straights, and the simulator must spread it thinly (0.40–0.46).

One caveat: the simulated top speed is 321 km/h, against 289 km/h in the real lap's top sample. The 32 km/h overshoot through the tunnel section is part of the RMS error, and it is consistent with the real car not deploying flat out there. We cannot check that, because we have no energy channel.

C5. Build the strategy input — lap time per kg everywhere

sensitivity.csv holds an s_per_kg row for each circuit-season. We join each row to the official lap length and full-throttle share from Chapter 10's profile table, then fit linear models.

K = S[S.change == "s_per_kg"][["year", "circuit", "delta_s", "real_s"]].rename(columns={"delta_s": "s_per_kg"})
K = K.merge(prof, left_on=["year", "circuit"], right_on=["year", "circuit_ref"], how="left")
K["len_km"] = K.official_length_m / 1000
for f in ["s_per_kg ~ len_km", "s_per_kg ~ full_throttle_pct", "s_per_kg ~ len_km + full_throttle_pct + C(year)"]:
    m = smf.ols(f, data=K).fit()
rows 42; missing profile rows 0
       n  median_s_per_kg  median_per_km
2025  22          0.03303        0.00649
2026  20          0.03306        0.00592
highest: losail 2025 0.0547, suzuka 2025 0.0427, marina_bay 2025 0.042
lowest:  monaco 2026 0.0208, silverstone 2025 0.0217, rodriguez 2026 0.0226
s_per_kg ~ len_km                                  R2 0.096  len_km +0.00266 (p 0.046)
s_per_kg ~ full_throttle_pct                       R2 0.008  full_throttle_pct +0.00009 (p 0.57)
s_per_kg ~ len_km + full_throttle_pct + C(year)    R2 0.199  C(year)[T.2026] -0.00431 (p 0.0643)  len_km +0.00512 (p 0.00721)
                                                             full_throttle_pct -0.00039 (p 0.076)

Answer. The table has 42 rows. Its medians are 0.0330 s/kg (2025) and 0.0331 s/kg (2026), which match the chapter. Our per-km medians, 0.00649 and 0.00592 s/kg/km, are slightly below the expected 0.00655 and 0.00596. We divide by the official lap length; the chapter's figures appear to use a slightly different length, such as the integrated lap distance.

Lap length is the better predictor, but not a good one. On its own it explains 9.6% of the variance (+0.0027 s/kg per km, p = 0.046). Full-throttle share explains 0.8% (p = 0.57). Even together with a season term, the R² is only 0.20.

Most of the spread comes from what neither variable captures: the type of corners and where on the lap the car is grip-limited. Losail 2025, with its long fast corners, has the highest value, at 0.0547. Monaco 2026 has the lowest, at 0.0208. For a strategy model, the circuit's own simulated value is a better input than a regression on length.

C8. Compare these seasons — braking residuals

We average the final fit's residual (real − sim) over braking-phase samples, by circuit and season. Then we correlate it with Chapter 7's per-circuit braking table.

R = pd.read_parquet(C11.CACHE / "residuals_final.parquet")
B = R[R.phase == "braking"].groupby(["year", "circuit"]).resid_kmh.agg(["mean", "size"]).reset_index()
M = B.merge(pd.read_csv(CH7 / "circuit_braking.csv"), left_on=["year", "circuit"], right_on=["year", "circuit_ref"])
spearmanr(M["mean"], M["hardest_entry"])
pooled mean residual by phase (km/h):
phase  braking  full throttle  part throttle / coast
2025      13.8            2.2                   -4.3
2026       9.6            1.4                    0.3
circuit-season rows: 42
largest braking residuals: zandvoort 2025 38.2, imola 2025 37.6, jeddah 2025 31.5, zandvoort 2026 27.6, americas 2025 23.3
smallest: shanghai 2026 -17.1, vegas 2026 -7.2, shanghai 2025 -6.4
Spearman(braking residual, hardest_entry) = -0.11 (p 0.475, n 42)
Spearman(braking residual, max_peak_g) = +0.18 (p 0.258, n 42)
Spearman(braking residual, brake_time_pct) = -0.01 (p 0.961, n 42)
  2025: Spearman with hardest_entry -0.15 (p 0.500, n 22)
  2026: Spearman with hardest_entry -0.34 (p 0.137, n 20)

Answer. The table has 42 circuit-season rows, and the pooled braking-phase means are +13.8 km/h (2025) and +9.6 km/h (2026), as expected. A positive residual means the real car carries more speed through the braking phase than the simulated car: the fitted braking envelope is too conservative.

The answer to the question is no. The largest residuals do not occur at the circuits with the highest-speed stops. The Spearman correlation with the hardest stop's entry speed is −0.11 (p = 0.48, n = 42), and correlations with peak g, brake-time share and zone count are all weak and not significant.

The worst circuits are Zandvoort, Imola and Jeddah. Their braking zones run into fast, flowing or banked corners rather than hairpins. A plausible reading is that the error comes from corner entry, not from the straight-line stop. There, the simulator's 60 m curvature smoothing and its single braking envelope cannot represent trail braking into a fast corner. The Silverstone fast sequence (mean −32.7 km/h in the chapter) is the same smoothing problem with the opposite sign.

D5. Predict the race weekend

The plan. Start from the calibrated 2025 car and change it one rule group at a time, in the order mass → lateral grip → drag → braking → power unit and energy → traction. This is the same structure as Case Study 2, but without access to the 2026 data:

  1. Mass: use the rule value, 724 kg without tyres against 800 kg in 2025.
  2. Lateral grip: scale the aero term $C_LA$ by 0.70, the announced "about 30% less downforce".
  3. Drag: scale $C_DA$ by 0.45, the announced "about 55% less drag". Remove DRS and add Straight Mode as a low-drag state on the straights.
  4. Power unit: an ICE of about 400 kW and an MGU-K of 350 kW with the regulation speed curve, plus the qualifying energy budget from data/reference/regulations_2026.md.
  5. Run it: simulate every circuit on its 2025 track line and 2025 air density, and report the change from the 2025 calibrated lap with its error band (1.66 s median absolute out of sample for 2025).

The two least certain inputs:

  1. The downforce number. "About 30%" is a design target, not a regulated value. It is also the single biggest lever: in Case Study 2, the lateral-grip step alone is worth +4.94 s (forward order) or +4.49 s (reverse order) in the median.
  2. How the energy budget is spent. The power-unit step costs +0.80 s in one order and +2.18 s in the other, because the cost depends on drag. A pre-season forecast also cannot know the in-season energy changes.

How the plan compares with Case Study 2. The plan would almost certainly have forecast too large a slowdown. Applying only the downforce cut adds about 4.5–4.9 s. The real median change was +2.18 s, and the full simulated change was +2.37 s. The difference comes from offsets the plan treats crudely or misses:

Offset Effect (forward order)
Lower drag −1.65 s
Lower mass −0.94 s
Braking envelope −0.37 s
Traction −0.35 s
Higher tyre and mechanical grip partly offsets the aero cut

The calibrated 2026 fit found that its aero term was 0.68 times 2025's, close to the 30% target. It also found a higher $\mu$ intercept (the lateral envelopes cross at about 105 km/h), which no pre-season announcement would have given us.

The lesson: forecast the change with every group switched on together, report a range by running more than one ordering and a spread of downforce cuts (for example 25–35%), and refit $\mu$ and $C_LA$ as soon as the first qualifying data arrive.

Chapter 12

Chapter 12 — Race Strategy Fundamentals · exercises · verification script: appendices/code/answers_part1_ch12.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D5 (all of Part D) have full solutions in the exercises file; open the Solution, Reveal, Discussion or Guidance blocks there.

Every model below is the chapter's linear stint model from boxbox.strategy. Degradation is each compound's median stint slope in that race, fuel-corrected at the toolkit's assumed 100 kg × 0.03 s/kg, with pooled compound offsets and warm-up. These are hindsight inputs unless we say otherwise.

C1. Analyze this session

We fit the 2025 Spanish GP race, optimise up to three stops, then scale every compound's wear in steps of 0.05 until a three-stop ranks first. This is the sensitivity method of 07_rules_and_sensitivity.py.

m, inp = S.fit_race_model(f1data.session(2025, "Spanish", "R"))
print(S.best_by_stops(S.optimise(m, max_stops=3))[COLS])
for k in np.round(np.arange(1.0, 3.01, 0.05), 2):
    t = S.optimise(scaled(m, k), max_stops=3)      # every deg_s_per_lap multiplied by k
    if int(t.n_stops.iloc[0]) >= 3:
        print(f"... x{k:.2f}"); break
compound  deg_s_per_lap  n_stints
    SOFT          0.098        26
  MEDIUM          0.066        20
N = 66, race pit loss 22.182 s (n = 39)
sequence  n_stops    stop_laps  race_time_s  gap_s
     M-S        1        (38,)     5386.713  7.910
   M-S-M        2     (24, 42)     5378.803  0.000
 M-M-S-M        3 (17, 35, 48)     5387.598  8.794
Smallest wear scale (step 0.05) at which a 3-stop is optimal: x1.65
sequence  n_stops    stop_laps  race_time_s  gap_s
     M-S        1        (39,)     5440.936 29.352
   M-M-S        2     (24, 48)     5412.292  0.708
 M-M-S-M        3 (18, 36, 49)     5411.584  0.000
At measured wear, a 3-stop becomes optimal once the pit loss is <= 13.0 s
Finishers by stop count: {2: 3, 3: 12, 4: 2}
Winner: {'acronym': 'PIA', 'sequence': 'S-M-S-S', 'stop_laps': (22, 49, 55)}

The inputs table has two rows, not three. No HARD compound survives the fit's three-stint minimum, so the model works with SOFT and MEDIUM only. At the measured wear the model's best is a two-stop, M-S-M (24, 42). The best three-stop is 8.8 s slower, and the one-stop 7.9 s slower.

The wear has to be scaled by 1.65× before a three-stop wins, and even then only by 0.71 s. Holding wear at its measured value, the pit loss would have to fall to about 13 s, close to the SC price, before three stops pay. Yet 12 of 17 finishers stopped three times, and the winner, Piastri, stopped three times.

So the hindsight model would need about two-thirds more wear than the median stint slope shows. That is a large miss, and it matches the chapter's finding that all 18 model misses predict too few stops. A plausible reading is that the median slope understates wear late in stints, or that teams stopped for reasons the solo model cannot see, such as covering rivals. The data cannot tell those two apart.

C2. Compare these drivers

We price all four combinations with race_time on the 2024 Bahrain model, using a 3-lap-old starting set, against the optimum for that age.

m3 = replace(bm, first_stint_age=3)
best3 = S.optimise(m3, max_stops=3).race_time_s.iloc[0]
for lab, seq, laps in cases:                # VER/SAI actual, then the swapped pair
    print(lab, S.race_time(S.Strategy.parse(seq, laps), m3) - best3)
compound  deg_s_per_lap  n_stints
    SOFT          0.094        23
    HARD          0.092        37
N = 57, race pit loss 24.271 s
VER actual  S-H-S (17, 37)   cost vs optimum   0.00 s
SAI actual  S-H-H (14, 35)   cost vs optimum   2.19 s
S-H-H at VER laps (17, 37)   cost vs optimum   1.33 s
S-H-S at SAI laps (14, 35)   cost vs optimum   0.72 s
Total SAI - VER: 2.19 s
  route 1: compound (at VER laps) 1.33 + timing (on S-H-H) 0.86
  route 2: timing (on S-H-S) 0.72 + compound (at SAI laps) 1.47

The model puts 2.19 s between the two strategies, the same figure Case Study 1 prints. The last-stint compound accounts for 1.33–1.47 s and the stop timing for 0.72–0.86 s. The split depends on which change you make first, so quote the range rather than one number.

The compound term is mostly the soft's pooled −0.136 s/lap offset over a 20-lap stint, because the two compounds' wear rates (0.094 vs 0.092 s/lap) are almost identical. Either way, roughly 60–67% of the gap is the tyre choice and the rest the timing. Neither part is large next to the 24.3 s pit loss: the model sees both strategies as close to optimal.

C5. Predict the race

The pre-race model uses the 2025 Austrian GP's race deg, the circuit's pooled 21.28 s pit loss, and the 2026 race length of 71 laps. The hindsight model refits on the 2026 race.

m25, inp25 = S.fit_race_model(f1data.session(2025, "Austrian", "R"))
pre = replace(m25, total_laps=N26, pit_loss_s=21.28)
m26, inp26 = S.fit_race_model(f1data.session(2026, "Austrian", "R"))
hind = replace(m26, pit_loss_s=21.28)
2025 inputs:
compound  deg_s_per_lap  n_stints
    SOFT          0.029         4
  MEDIUM          0.076        25
    HARD          0.074        16
Pre-race model: N = 71, pit loss 21.28 s (circuit pooled)
sequence  n_stops    stop_laps  race_time_s  gap_s
     S-H        1        (52,)     5018.019  1.071
   S-S-H        2     (30, 60)     5016.948  0.000
 S-S-S-H        3 (21, 42, 64)     5029.328 12.380
2026 (hindsight) inputs:
compound  deg_s_per_lap  n_stints
    SOFT          0.060         8
  MEDIUM          0.094        29
    HARD          0.086        24
Hindsight model, same 21.28 s pit loss:
sequence  n_stops    stop_laps  race_time_s  gap_s
     S-H        1        (43,)     5200.392 12.203
   S-S-H        2     (27, 54)     5188.190  0.000
 S-S-S-H        3 (19, 39, 59)     5194.394  6.204
(race's own pit loss 21.282 s, n = 33)
Hindsight model, race's own pit loss:
sequence  n_stops    stop_laps  race_time_s  gap_s
     S-H        1        (43,)     5200.394 12.201
   S-S-H        2     (27, 54)     5188.194  0.000
 S-S-S-H        3 (19, 39, 59)     5194.400  6.206
Finishers by stop count: {2: 15, 3: 3} | winner: {'acronym': 'RUS', 'sequence': 'M-H-H', 'stop_laps': (19, 43)}

Both models call two stops, which matches the finishers' median of 2 (15 of 18 finishers). Hindsight did not change the call, but it changed how confident we should be in it.

Before the race, the two-stop beat the one-stop by only 1.1 s. That is a coin flip, and it rests on a 2025 SOFT rate drawn from just 4 stints. The 2026 race's wear ran higher on every compound (MEDIUM 0.094 against 0.076, HARD 0.086 against 0.074), which widened the margin to 12.2 s. The race's own pit loss (21.282 s) was the same as the pooled value, so all of the change came from wear.

The model's preferred sequence, S-S-H, leans on the soft's pooled pace offset. Russell won on M-H-H, stopping earlier than the model's preferred sequence: after laps 19 and 43, against the model's 27 and 54.

C8. Build the strategy

We cap MEDIUM at 20 laps and SOFT at 14 laps, then re-optimise with the 2026 allocation of 2 hard, 3 medium and 8 soft sets.

lim = replace(bm2, compounds={**bm2.compounds,
              "MEDIUM": replace(bm2.compounds["MEDIUM"], max_laps=20),
              "SOFT":   replace(bm2.compounds["SOFT"],   max_laps=14)})
capped = S.optimise(lim, max_stops=3, sets_available=S.ALLOCATION_2026["standard"])
Without limits:
     M-H        1        (27,)     5608.913 36.225
   M-H-H        2     (17, 41)     5572.688  0.000
 M-H-H-M        3 (13, 33, 53)     5576.673  3.985
With limits:
     M-H        1        (20,)     5615.647 42.959
   M-H-H        2     (17, 41)     5572.688  0.000
 M-M-H-H        3 (13, 26, 46)     5576.673  3.985
Time cost of the limits on the overall best: 0.000 s

The best two-stop does not change. M-H-H (17, 41) already runs its medium for only 17 laps, so a 20-lap cap never binds. The best three-stop does not get closer either: it stays 3.985 s behind. Its listed order changes from M-H-H-M to M-M-H-H, a tie at the same time, because both use two 13-lap medium stints and two 20-lap hard stints.

The one stop the cap really hurts is the one-stop. Its medium stint is forced down from 27 to 20 laps, and its deficit grows from 36.2 s to 43.0 s. The lesson is that a life limit matters only when the optimum wants a long stint on that compound. At Barcelona 2026 the wear already pushes every good plan into short stints.

Chapter 13

Chapter 13 — The Undercut and Overcut · exercises · verification script: appendices/code/answers_part1_ch13.py

Worked in the chapter. B1–B9 (all of Part B) and D1–D3 have full solutions in the exercises file; open the Solution, Reveal or A way in blocks there.

A note on column names. In boxbox.undercut's tables, B is the car behind (the attacker in an undercut) and A is the car ahead. The script renames them attacker and defender.

C1. Analyze this session

We run the situation finder on the 2024 Bahrain GP, separate the outliers, and take the race's median degradation from metrics.degradation_table with the chapter's 8-lap minimum.

s = f1data.session(2024, "Bahrain", "R")
p = UC.find_undercut_attempts(s).rename(columns={"B": "attacker", "A": "defender"})
big = p[p.gain.abs() > 50]
dt = metrics.degradation_table(s, min_laps=8)
print(dt.groupby("compound").slope_s_per_lap.agg(["median", "size"]))
(a) counts: {'undercut': 10, 'overcut': 10}
(b) rows with |gain| > 50 s:
    kind attacker defender  lap_first  lap_second    gain  stop_diff  lane_first  lane_second
undercut      SAR      MAG         10          11 -81.461    -71.362        35.7         25.9
 overcut      RIC      SAR         10          13  81.561     70.587        35.7         24.9
 overcut      SAR      ZHO          9          10 -81.297    -70.219        25.2         35.7
    overcut: success 0.300 -> 0.250 without them; median gain -1.286 -> -1.286 s; mean -1.593 -> -2.024
    undercut: success 0.500 -> 0.556 without them; median gain 1.788 -> 3.475 s; mean -5.864 -> 2.536
(c) race median toolkit deg by compound (stints with >= 8 usable laps, fuel-corrected 100 kg x 0.03 s/kg):
          median  size
HARD       0.092    37
SOFT       0.094    23

(a) There are 20 situations: 10 undercuts and 10 overcuts, the expected shape.

(b) All three ±81 s rows involve Sargeant's stop at the end of lap 10. His pit-lane time was 35.7 s, against 24.9–25.9 s for the cars he was paired with. His stop_diff of about −70 s says the whole stop cost him around 70 s more than his rival's, and most of that sits in the in-lap component (in_delta −60.8 s in the full table). The data record a very slow lap into the pits and a slow lane passage. They do not say why, so we don't guess.

These rows are not strategy contests, and their success flags are correct but uninformative. Dropping them is defensible in a success-rate study if you state the rule, e.g. "stop_diff beyond ±30 s". Their effect on the rate here is one success or failure each. For a median-gain study they matter less than you might fear. The overcut median is unchanged and the undercut median moves from 1.79 to 3.48 s only because n is small (10 → 9). But the mean swings from −5.86 to +2.54 s. That is the real argument for medians.

(c) HARD 0.092 s/lap (n = 37) and SOFT 0.094 s/lap (n = 23), fuel-corrected at the toolkit's assumed 100 kg × 0.03 s/kg. These match the expected values exactly.

C4. Analyze this session

We rerun the whole study twice, once with a 1.5 s gap window and once with $k = 1$ only, and compare with the chapter's table.

for label, kw in [("gap_max=1.5", dict(gap_max=1.5)), ("max_k=1", dict(max_k=1))]:
    pr = UC.study(**kw)
    for kind in ["undercut", "overcut"]:
        g = pr[pr.kind == kind]
        p, lo, hi = metrics.wilson_ci(int(g.success.sum()), len(g))
-- chapter (3.0 s, k<=3)
  undercut                 n= 168  success  42.9%  [ 35.6,  50.4]  median gain +0.755 s
  overcut                  n= 163  success  22.1%  [ 16.4,  29.1]  median gain -1.396 s
-- gap_max=1.5
  undercut                 n=  82  success  58.5%  [ 47.7,  68.6]  median gain +1.786 s
  overcut                  n=  95  success  29.5%  [ 21.2,  39.3]  median gain -0.643 s
-- max_k=1
  undercut                 n= 104  success  33.7%  [ 25.3,  43.2]  median gain +0.461 s
  overcut                  n=  75  success  14.7%  [  8.4,  24.4]  median gain -1.421 s

With a 1.5 s window the undercut rate rises to 58.5% [47.7, 68.6] on 82 situations, above the 42.9% headline as expected. It sits between the chapter's 2 s window (55.0%) and the 0–1 s band (78.6%). The overcut rate also rises, to 29.5%, because a close pair is easier to swap in either direction.

Restricting to $k = 1$ cuts both rates: undercut 33.7% and overcut 14.7%. That is the chapter's point about $k$. The fresh-tyre gain accumulates per lap, so a defender who covers immediately leaves the attacker only one lap of advantage. Restricting to $k = 1$ also selects the situations where the defender reacted, and those are the hardest to win.

C6. Compare these drivers

We group the 168 undercut situations by attacker team and give a Wilson interval both for the success rate and for the share where the attacker's stop was cheaper (stop_diff > 0).

u = pd.read_csv(PAIRS).query("kind == 'undercut'")
for team, g in u.groupby("B_team"):
    if len(g) >= 8:
        succ = metrics.wilson_ci(int(g.success.sum()), len(g))
        cheap = metrics.wilson_ci(int((g.stop_diff > 0).sum()), len(g))
field                    n= 168  success  42.9%  [ 35.6,  50.4]
        team  n  success  s_lo  s_hi  cheaper_stop  c_lo  c_hi  excludes_field
        haas 21    0.667 0.454 0.828         0.571 0.365 0.755            True
aston_martin 11    0.545 0.280 0.787         0.818 0.523 0.949           False
          rb 18    0.500 0.290 0.710         0.389 0.203 0.614           False
      alpine 20    0.450 0.258 0.658         0.350 0.181 0.567           False
    williams 14    0.429 0.214 0.674         0.429 0.214 0.674           False
    mercedes 23    0.391 0.222 0.592         0.609 0.408 0.778           False
      sauber  9    0.333 0.121 0.646         0.333 0.121 0.646           False
     mclaren 21    0.286 0.138 0.500         0.667 0.454 0.828           False
     ferrari 11    0.182 0.051 0.477         0.364 0.152 0.646           False
field share with stop_diff > 0: 0.488 [0.414, 0.563]
between-team SD: success 0.145, cheaper-stop share 0.170
between-team range: success 0.182-0.667, cheaper-stop 0.333-0.818

Nine teams have at least 8 situations. Only Haas's interval excludes the field's 42.9%: 66.7% on n = 21, lower bound 45.4%. It clears the field by about 2.5 points, and with nine teams tested, one marginal exclusion is roughly what chance alone would produce. So no team's undercut record is convincingly different from the field's. Ferrari (18.2%) and McLaren (28.6%) are low, but their intervals still reach 47.7% and 50.0%.

The stop-execution share varies more between teams than the success rate does: a between-team SD of 0.170 against 0.145, and a range of 33–82% against 18–67%. The two do not line up either. McLaren had the cheaper stop in 66.7% of its situations but succeeded in only 28.6%. Aston Martin had 81.8% cheaper stops and 54.5% success. Across the field, a cheaper stop happens in 48.8% of situations. It matters (73.6% of successes against 30.2% of failures, from the chapter), but it is one of four components, and the gap and the fresh-tyre step decide just as many.

C9. Predict the race

We split the undercut situations by the attacker's old compound, then by transition.

for comp in ["SOFT", "MEDIUM", "HARD"]:
    print(rate_row(f"first_old == {comp}", u[u.first_old == comp]))
for (o, nw), g in u.groupby(["first_old", "first_new"]):
    if len(g) >= 10: print(rate_row(f"{o} -> {nw}", g), g.gain.median(), g.fresh_delta.median())
first_old == SOFT        n=  40  success  52.5%  [ 37.5,  67.1]
first_old == MEDIUM      n=  86  success  39.5%  [ 29.9,  50.1]
first_old == HARD        n=  42  success  40.5%  [ 27.0,  55.5]
by transition (first_old -> first_new):
  HARD -> HARD             n=  22  success  40.9%  [ 23.3,  61.3]  median gain +0.623 s, median fresh +1.022, median defender age 22
  MEDIUM -> HARD           n=  70  success  42.9%  [ 31.9,  54.5]  median gain +0.755 s, median fresh +1.274, median defender age 16
  SOFT -> HARD             n=  18  success  61.1%  [ 38.6,  79.7]  median gain +2.492 s, median fresh +2.682, median defender age 11
  SOFT -> MEDIUM           n=  19  success  47.4%  [ 27.3,  68.3]  median gain +1.434 s, median fresh +1.976, median defender age 15

Attackers coming off SOFTs succeed in 52.5% of situations, against 39.5% from MEDIUMs and 40.5% from HARDs. The transitions match the expected values exactly: SOFT → HARD 61.1% (n = 18), MEDIUM → HARD 42.9% (n = 70), HARD → HARD 40.9% (n = 22). Every interval overlaps every other, so only the direction is worth discussing.

Why SOFT → HARD gains more: the gain over $k$ laps is roughly $k \cdot d \cdot (a - s)$, and the term that matters is the defender's wear on the old tyre. A defender still on SOFTs is on the fastest-wearing compound: 0.064 s/lap pooled and fuel-corrected, against MEDIUM 0.051 and HARD 0.048. The fresh-tyre step shows it directly. The median fresh component is 2.68 s for SOFT → HARD against 1.27 s for MEDIUM → HARD, even though the defenders' tyres are younger (a median of 11 laps against 16).

SOFT stints also tend to come early in high-wear races (Bahrain is a typical case), where every compound wears faster than the pooled rates. The fresh HARD's slower base pace (pooled offset −0.039 s/lap against the SOFT's −0.136, relative to MEDIUM) works against the attacker, but wear on the defender's softs outweighs it.

D4. When not to undercut

Here is one state where stopping first is wrong even from 0.5 s behind, with the numbers that make it wrong.

  • A neutralisation is likely soon and the gap is safe. A green-flag stop costs a pooled median of 22.512 s, and a stop under a full safety car 12.722 s, a saving of 9.79 s. At the 2023–26 full-SC hazard of 0.0115 per lap, the chance of an SC in the next 10 laps is $1 - 0.9885^{10} = 0.109$. Waiting is therefore worth about $0.109 \times 9.79 = 1.07$ s in expectation (0.55 s over 5 laps, 1.56 s over 15). The arithmetic favours waiting at circuits where the hazard is well above average, or when the race is past its high-risk opening laps but debris or weather is building. It doesn't favour waiting on an average lap of an average race. In those cases the undercut's expected gain at 0.5 s (P(success) = 0.80 on the chapter's logistic curve) is worth more.
  • You rejoin into traffic. The undercut's whole value is the out-lap and the next two laps on fresh tyres. Behind slower cars that have not stopped, the fresh component disappears, as Tsunoda found at Las Vegas 2024: his settle component was −6.590 s. If the rejoin gap to the next car on track is under about 1–2 s, stopping first converts a 0.5 s deficit into a lap stuck in traffic.
  • A team-mate is due in the same window. Stacking costs the second car a slow stop. If your team-mate is 1–2 s ahead and due to stop, your undercut costs the team either a stacked stop or a swapped order.
  • At the front, the rival will cover. Attackers in P1–P6 succeed in only 23.1% [13.7, 36.1] of undercuts (n = 52), against 51.7% for P7 and below. Front-runners cover at once ($k = 1$), and at $k = 1$ the undercut rate falls to 33.7% (C4).

A strong answer combines at least two of these. For example: "0.5 s behind in P2, team-mate due to stop next lap, rejoin into a DRS train. The 23% front-runner base rate plus a 10.9% chance of a cheap SC stop in the next 10 laps says stay out and stretch."

Chapter 14

Chapter 14 — Safety Cars, Virtual Safety Cars, and Red Flags · exercises · verification script: appendices/code/answers_part1_ch14.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D5 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

C2. Compare these drivers: 2026 Singapore GP, Race

We take each driver's clean laps over laps 42–62. Then we fit Hamilton's lap time on tyre age twice, once raw and once after the toolkit's fuel correction.

lp = f1data.laps(f1data.session(2026, "Singapore", "R"), clean=True)
w = lp[lp.lap_number.between(42, 62)]
h = w[w.acronym == "HAM"]
b, a = np.polyfit(h.tyre_age.astype(float), h.lap_duration, 1)            # raw
hf = metrics.fuel_corrected(h)
bf, _ = np.polyfit(hf.tyre_age.astype(float), hf.lap_time_fc, 1)          # 100 kg x 0.03 s/kg
  LEC: median clean lap 96.205 s (n = 21), compound SOFT, tyre age 5-25
  ANT: median clean lap 96.371 s (n = 21), compound SOFT, tyre age 5-25
  VER: median clean lap 96.606 s (n = 21), compound MEDIUM, tyre age 9-29
  HAM: median clean lap 98.579 s (n = 21), compound SOFT, tyre age 26-46
  HAM raw slope of lap time on tyre age, laps 42-62: +0.1573 s/lap (n = 21; no fuel correction)
  HAM slope after the toolkit's fuel correction (100 kg x 0.03 s/kg, column lap_time_fc): +0.2057 s/lap

The medians match the expected values exactly. Hamilton's softs were 21 laps older than Leclerc's and Antonelli's (26–46 against 5–25). He was about 2.2–2.4 s a lap slower, and the gap grew lap by lap.

His slope does not look like 0.0324 s/lap. The raw slope is 0.157 s/lap, about five times the Singapore SOFT rate from the chapter's fixed-effects model. After the fuel correction it is 0.206 s/lap, steeper still, because the burning fuel was hiding part of the wear.

The 0.0324 figure is a pooled linear rate fitted across four races, mostly on stints far shorter than 46 laps. Hamilton was running the soft well beyond the range where that linear fit was estimated, and well past the chapter's 37-lap 95th-percentile stint cap. One driver's late stint is a small, selected sample, but it is a good illustration of why a linear deg rate is a local approximation.

C3. Build the strategy: hazard by circuit type

Our street-circuit list is Monaco, Baku, Marina Bay, Jeddah, Las Vegas, Miami, Albert Park, Montreal (villeneuve) and Madring. Everything else counts as permanent. Albert Park and Montreal are parkland circuits on public roads, so including them is the judgement call.

STREET = ["monaco", "baku", "marina_bay", "jeddah", "vegas", "miami", "albert_park", "villeneuve", "madring"]
S = nz.race_summary()
for sub in (S[S.circuit_ref.isin(STREET)], S[~S.circuit_ref.isin(STREET)]):
    print(nz.hazard_by_phase(sub))
bt = stats.binomtest(29, 65, 1193 / (1193 + 2298))   # street share of middle-race events vs exposure
-- street: 32 races, races with >=1 SC/VSC/red 84.4%, with >=1 SC 53.1%
    phase  events  laps_at_risk    lam     lo     hi
    lap 1       6            32 0.1875 0.0688 0.4081
laps 2-10       9           257 0.0350 0.0160 0.0665
   middle      29          1193 0.0243 0.0163 0.0349
 final 10       5           309 0.0162 0.0053 0.0378
-- permanent: 59 races, races with >=1 SC/VSC/red 66.1%, with >=1 SC 45.8%
    phase  events  laps_at_risk    lam     lo     hi
    lap 1      10            59 0.1695 0.0813 0.3117
laps 2-10      15           487 0.0308 0.0172 0.0508
   middle      36          2298 0.0157 0.0110 0.0217
 final 10       8           562 0.0142 0.0061 0.0280
middle-race rate ratio street/permanent = 1.55; exact conditional test (street events 29 of 65, expected share 0.342): p = 0.089

The middle-race hazard is 0.0243 per lap on street circuits, with an exact Poisson interval of 0.0163–0.0349. On permanent circuits it is 0.0157 (0.0110–0.0217). The point estimates differ by a factor of 1.55, and the intervals overlap between 0.0163 and 0.0217.

Overlapping intervals are a weak test. The direct comparison, an exact conditional test of 29 street events out of 65 against an exposure share of 0.342, gives p = 0.089. So the data lean towards more incidents in the middle of street races, but four seasons cannot confirm it. The other phases differ even less; lap 1 is the riskiest lap on both kinds of circuit. At race level, 84.4% of street races had at least one SC, VSC or red flag, against 66.1% elsewhere. That is the more visible difference, because it adds up the small per-lap differences over every phase of a race. The races are about the same length: 1,791 laps at risk over 32 street races against 3,406 over 59 permanent ones.

C4. Analyze this session: VSC stops by circuit

We apply the chapter's near-field filter to its saved stop table (dry tyre changes, same-set passages excluded, lap > 1, pit lane ≤ 60 s). Then we group the VSC stops by circuit and count the distinct races behind each median.

V = P[P.tyre_change & ~P.same_set & ~P.wet & (P.in_lap > 1)
      & P.near_field_loss_s.notna() & ~(P.pit_lane_s > 60)]
vsc = V[V.status == "VSC"]
t = vsc.groupby("circuit_ref").agg(stops=("near_field_loss_s", "size"),
        races=("session_key", "nunique"), median_vsc_s=("near_field_loss_s", "median"))
all VSC stops: n = 106, median 15.67 s, races 26
               stops  races  median_vsc_s  green_median_s  ratio
madring            7      1         11.97           26.90   0.45
bahrain            6      1         12.93           23.50   0.55
red_bull_ring     14      2         13.40           21.11   0.63
spa                9      1         15.57           18.68   0.83
monza              5      1         16.25           25.50   0.64
imola              8      1         16.49           27.56   0.60
albert_park       17      2         17.14           21.37   0.80
marina_bay         8      2         22.70           26.33   0.86
pooled near-field ratios (nz.SC_RATIO): {'SC': 0.547, 'VSC': 0.645, 'RED': 0.0}
circuits kept: 8, stops 74, of which in a single race: 5 circuits

The full sample reproduces the book's VSC figure (n = 106, median 15.67 s), drawn from only 26 races. Eight circuits have at least 5 VSC stops, a little short of the "about ten" expected. Five of those eight rest on a single race, and none on more than two. Per-circuit medians run from 12.0 s (Madring) to 22.7 s (Marina Bay), and ratios to the green loss from 0.45 to 0.86.

Quote the number of races because the stops are not independent. Every car that stops under one VSC shares the same timing: how far into the VSC the call came, where the car was on the lap when the VSC began, and how long it lasted. Seventeen stops at Albert Park are really two events. A median over 7 stops at Madring describes one VSC, not Madring. For the per-race variance the effective sample size is the number of races, so a circuit-level VSC loss from one or two races should be treated as an anecdote, and the pooled ratio (0.645) used instead.

C7. Build the strategy: re-run Anchor C with k = 0.74

We rebuild the chapter's Singapore inputs exactly as 07_anchor_c_singapore.py does: fixed-effects deg, offsets, 95th-percentile caps and the 2025–26 green loss. Then we run 10,000 races at the race-control-only multiplier.

km = nz.circuit_multiplier("marina_bay", nz.HAZARD_2023_26, nz.race_summary())
k_rc = round(km["k_rc"][0], 2)                                  # 4 / 5.41 = 0.74
MC = nz.monte_carlo(10_000, 62, nz.sc_hazard(k=k_rc), tyres, pool, lib, seed=42)
print(MC.d_two.mean(), (MC.d_two < 0).mean(), MC.d_flex.mean(), (MC.d_flex < 0).mean())
deg: {'SOFT': 0.0324, 'MEDIUM': 0.0417, 'HARD': 0.0521} offsets: {'MEDIUM': 0.0, 'SOFT': -0.093, 'HARD': 0.229} caps: {'SOFT': 37, 'MEDIUM': 43, 'HARD': 47} green loss 23.866 s (n = 40)
race-control-only k = 4 / 5.41 = 0.74
-- k = 0.74: E[two-one] +9.99 (+9.86 to +10.12) s, P(two better) 6.6%; E[flex-one] -0.56 (-0.61 to -0.51) s, P(flex better) 10.4%, P(flex worse) 1.5%; races with >=1 incident 63.7%
-- k = 1.33 (chapter main): E[two-one] +9.44 (+9.29 to +9.59) s, P(two better) 10.7%; E[flex-one] -0.86 (-0.92 to -0.81) s, P(flex better) 17.6%, P(flex worse) 3.5%; races with >=1 incident 83.2%

With k = 0.74 and 10,000 races, the planned two-stop is +9.99 s slower on average (bootstrap interval +9.86 to +10.12) and better in only 6.6% of races. This matches the expected shape and the chapter's 3,000-race row (+9.97 s, 6.7%).

The flexible one-stop still wins on average, by 0.56 s (−0.61 to −0.51). It is better in 10.4% of races and worse in 1.5%. Its edge shrinks from the chapter's 0.86 s at k = 1.33 because fewer races offer a cheap neutralised stop: 63.7% have an incident, against 83.2%. Its sign does not change, because the flexible car only takes the extra stop when a neutralisation makes it pay.

This is Chapter 14's simplified Monte Carlo, in which decisions and scoring use the same point estimates. The book's headline Anchor C values come from Chapter 27's fuller model: two-stop +10.10 s, better in 18.9% of races, flexible one-stop gains 0.84 s. Quote those as the answer to the Singapore question, and this run as a sensitivity check that agrees in direction.

Chapter 15

Chapter 15 — Wet Weather Strategy · exercises · verification script: appendices/code/answers_part1_ch15.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D3 have full solutions in the exercises file; open the Solution, Reveal or Hint blocks there.

As in the chapter, no wet-weather lap time below is fuel-corrected. The wetness gauge is the intermediate median lap divided by the race's own dry reference, minus 1.

C1. Analyze this session: 2023 Monaco GP, laps 48–70

We print the tyre-class mix, the two switch tables and the per-lap class medians with min_cars=1.

s = f1data.session(2023, "Monaco", "R")
mix = wet.field_mix(s).loc[48:70]
for a, b, win in [("SLICK", "INTER", (48, 60)), ("INTER", "WET", (55, 70))]:
    print(wet.switch_table(s, a, b, win))
cp = wet.class_pace(s, min_cars=1).loc[48:70]
cp["wet_minus_inter_s"] = cp.WET_s - cp.INTER_s
cls         SLICK  INTER  WET  rain_share  status
51             20      0    0    0.000000   GREEN
52             18      2    0    0.000000   GREEN
53             15      5    0    0.400000   GREEN
54             12      7    0    0.900000  YELLOW
55              4     15    0    1.000000  YELLOW
56              1     18    0    1.000000  YELLOW
57              0     18    1    1.000000  YELLOW
60              0     16    3    1.000000  YELLOW
-- switch table SLICK -> INTER, laps (48, 60): 19 cars
    STR      51 INTERMEDIATE        15.0       16.0      24.656
    BOT      51 INTERMEDIATE        13.0       12.0      30.395
    ...
    SAI      55 INTERMEDIATE         3.0        8.0      29.300
    LEC      55 INTERMEDIATE         4.0        6.0      25.713
    VER      55 INTERMEDIATE         1.0        1.0      24.798
-- switch table INTER -> WET, laps (55, 70): 2 cars
    PER      57          WET        16.0       16.0      29.337
    HUL      59          WET        16.0       17.0      25.672
cars on WET on lap 60: ['HUL', 'MAG', 'PER']
-- class pace where both INTER and WET ran (gauge = inter_excess):
            INTER_s  n_INTER    WET_s  n_WET  wet_minus_inter_s  inter_excess
63           99.916     16.0   99.405    3.0             -0.511         0.274
64           98.693     16.0   97.628    3.0             -1.065         0.258
65           97.638     16.0   97.675    3.0              0.037         0.245
66           95.822     16.0   96.451    3.0              0.629         0.222
68           93.322     15.0   96.655    3.0              3.333         0.190

Slicks → intermediates. The rain flag appears on lap 53 (40% of laps) and covers every lap from 55. Stroll and Bottas were the pathfinders, both boxing on in-lap 51. Stroll is listed first, as expected. Nineteen cars changed by in-lap 55, and the leader, Verstappen, was among the last. On the paired laps 53–54, intermediates were still 2.8 s and 1.5 s slower than the last slick runners (94.520 vs 91.752; 98.776 vs 97.315). That is because the slick median on those laps comes from the cars still on dry pace, before the rain got heavy.

Intermediates → full wets. Only two cars made this change (Pérez on in-lap 57, Hülkenberg on 59), the expected shape. The mix shows a third car on wets: Magnussen went straight from hards to full wets on lap 57, so the INTER → WET table cannot list him.

On the paired laps, full wets were faster on every lap up to lap 64 (−1.065 s at a gauge of 25.8%). From lap 65 the intermediates were level or faster: +0.037 s at a gauge of 24.5%, then +0.63 s and +1.43 s as the track dried. The sign change falls between laps 64 and 65, at a gauge of 24.5%, which matches the chapter. Each wet median rests on two or three cars, so the exact lap of the tie is uncertain to a lap or so.

C2. Compare these drivers: Verstappen and Pérez, 2023 Dutch GP

wet.teammate_lap_gaps gives the chapter's figures. We then rebuild the paired laps by hand so that we can restrict the dry laps to 13–58.

rl = wet.representative_laps(f1data.session(2023, "Dutch", "R"))
j = (rl[rl.acronym == "PER"].set_index("lap_number")[["lap_duration", "cls"]]
     .join(rl[rl.acronym == "VER"].set_index("lap_number")[["lap_duration", "cls"]],
           lsuffix="_p", rsuffix="_v", how="inner"))
j = j[j.cls_p == j.cls_v]
j["gap_pct"] = 100 * (j.lap_duration_p - j.lap_duration_v) / ((j.lap_duration_p + j.lap_duration_v) / 2)
team_ref driver_a driver_b  wet_gap_pct  n_wet  dry_gap_pct  n_dry
red_bull      PER      VER        0.989     13        0.378     36
  all paired slick laps   : dry +0.378% (n = 36), wet +0.989% (n = 13), shift +0.611 points
  slick laps 13-58 only   : dry +0.368% (n = 35), wet +0.989% (n = 13), shift +0.621 points
  slick paired laps by lap range: 14 - 59 | laps outside 13-58: [59]
  rolling 9-lap median of the dry gap: min +0.338%, max +0.572%

The pair reproduces the chapter: Pérez is 0.989% slower on 13 wet laps and 0.378% slower on 36 slick laps, a wet shift of +0.61 points. Restricting the dry laps to 13–58 removes only one lap (59), because the representative-lap filter had already dropped the laps around the stops and the late shower. The shift barely moves, to +0.62.

The definition of "dry" is therefore not the sensitive part here. The noise in the dry gap itself is: a rolling 9-lap median of the dry gap wanders between +0.34% and +0.57%, a range of 0.23 points, more than a third of the shift. With 13 wet laps the shift is a single pair-event. That is why the chapter pools 41 race pair-events before it says anything about wet skill.

C3. Build the strategy: the shower-forecast table

We extend the checkpoint's ramp to four peaks, $w$ = 3% → $w_{\max}$ in four equal steps then flat, and run switch_decision on each grid cell with the chapter's fitted penalty model and the 2026 São Paulo dry pace.

for wmax in (0.14, 0.18, 0.22, 0.26):
    for laps_left in (20, 12, 8, 4):
        w = np.minimum(0.03 + (wmax - 0.03) / 4 * np.arange(laps_left), wmax)
        d = wet.switch_decision(M.delta_s("SLICK", "INTER", w, ref), pit_loss_s=wet.PIT_LOSS[kind])
model tie_slick 0.113, slope_slick 1.36; dry pace 76.012 s
-- GREEN pit loss 22.512 s (cell = switch with in-lap = remaining lap n, net gain s)
                   20 left          12 left 8 left 4 left
w_max 14%             stay             stay   stay   stay
w_max 18%   in-lap 3, +7.5             stay   stay   stay
w_max 22%  in-lap 2, +26.3   in-lap 2, +2.8   stay   stay
w_max 26%  in-lap 2, +45.2  in-lap 2, +13.0   stay   stay
-- SC pit loss 12.722 s (cell = switch with in-lap = remaining lap n, net gain s)
                   20 left          12 left          8 left 4 left
w_max 14%             stay             stay            stay   stay
w_max 18%  in-lap 3, +17.3   in-lap 3, +2.7            stay   stay
w_max 22%  in-lap 2, +36.1  in-lap 2, +12.6  in-lap 2, +0.9   stay
w_max 26%  in-lap 2, +55.0  in-lap 2, +22.8  in-lap 2, +6.7   stay

The 22% row reproduces the chapter's checkpoint: switch with 20 laps left (+26.3 s green, +36.1 s SC). With 8 left, stay out under green but switch under an SC (+0.9 s). With 4 left, stay out under both.

The grid shows three things.

  • A 14% shower is never worth a stop. It barely passes the model's 11.3% tie, so intermediates are only slightly faster.
  • The switch, when it comes, is early. It always falls on remaining lap 2 or 3, as soon as the gauge has crossed the tie. Waiting only adds laps on the wrong tyre.
  • An SC moves the boundary about four laps later in the race. At $w_{\max}$ = 26% a green stop stops paying between 12 and 8 laps left, but an SC stop still pays with 8 left.

The penalty model is a local linear approximation fitted on a handful of tie points (🧪), and the forecast ramp is an assumption. Treat the boundaries as ±1–2 laps.

C6. Analyze this session: the 2024 São Paulo GP red flag

We flag every car with a new stint starting on laps 25–32 (in-laps 24–31), then read positions at the end of laps 27 and 34 and the last recorded position.

st = f1data.stints(sp)
stopped = set(st[(st.lap_start - 1).between(24, 31) & (st.stint_number > 1)].acronym)
pos = lp.pivot_table(index="acronym", columns="lap_number", values="position_end", aggfunc="first")
T = pd.DataFrame({"pos_after_27": pos[27], "pos_after_34": pos[34]}).join(last.rename("pos_final"))
         stopped_24_31  pos_after_27  pos_after_34  pos_final  change_27_34
RUS               True             1             4          4             3
NOR               True             2             5          6             3
OCO              False             3             1          2            -2
TSU               True             4             8          8             4
VER              False             5             2          1            -3
GAS              False             6             3          3            -3
...
BOT              False            15            13         13            -2
COL               True            16          <NA>         16          <NA>
HUL               True            18          <NA>         18          <NA>
               median  size
stopped_24_31              
False            -2.5     4
True              1.5    14
cars starting a new stint on lap 33: 16; compounds {'INTERMEDIATE': 16}

The check values hold. Verstappen, Ocon and Gasly had not stopped. They went from P5 / P3 / P6 after lap 27 to P2 / P1 / P3 after lap 34. All 16 cars that began a new stint on lap 33 fitted intermediates during the suspension.

The data add a fourth non-stopper the exercise does not name: Bottas, P15 → P13. The median change from lap 27 to lap 34 is −2.5 places (a gain) for the 4 non-stoppers and +1.5 places (a loss) for the 14 stoppers whose lap-34 position exists. Colapinto and Hülkenberg have no lap-34 position; their "final" column is their last recorded position, not a classification.

The mechanism is the one Chapter 14 describes. The red flag gave every car a free tyre change, so the cars that had paid for a stop under green or VSC on laps 24–31 got nothing for it. Note the small group: four cars, one race.

D4. The flexible slick stint

For. If the shower arrives, a long first stint lets the switch to intermediates be your only stop. You save one whole green stop, 22.512 s, and the São Paulo 2026 one-set drivers (Russell, Leclerc, Pérez) are an example of how it can play out. Forecasts update, too. A car still on its first set at half-distance can choose late, with better information, and if a safety car comes it can take a cheap stop at the right moment (Chapter 14's flexible one-stop beats a fixed plan for exactly this reason).

Against. The option is not free: you pay for it in wear whether or not it rains. A 🧪 illustration: a 60-lap race, linear wear at the book's pooled fuel-corrected rates, and rain making intermediates necessary from lap 46. Plan A is a normal one-stop at lap 30; if it rains, it also stops for inters. Plan B stretches the first stint to lap 45, so the rain stop is its only stop. Wear cost per stint is $d \cdot s(s-1)/2$.

   d = 0.048: B - A if dry +10.80 s, if rain -0.91 s; expected at p = 0.4: +6.12 s; break-even rain probability 0.92
   d = 0.064: B - A if dry +14.40 s, if rain +6.29 s; expected at p = 0.4: +11.16 s; break-even rain probability nan

On the HARD rate (0.048 s/lap), the long stint saves only 0.91 s if it rains: the 22.5 s stop saved, less 21.6 s of extra wear. It costs 10.8 s if it stays dry. At a 40% chance of rain the expected cost is +6.1 s, and the plan only breaks even if rain is about 92% certain. At the SOFT rate (0.064) it loses even when it rains.

The Chapter 12 break-even makes the same point. A stop pays when the fresh tyre's gain repays the pit loss, and with a median fresh-tyre delta of 1.078 s/lap that takes 20.9 laps. A first stint stretched 15 laps past its optimum gives away most of that.

Verdict. Under these assumptions, a deliberately long stint is a poor bet at 40%. The better way to keep the option open is to run a normal first stint on a set that degrades slowly (HARD), and push the stop later only as the forecast firms up. The São Paulo 2026 result is three drivers in one race, not evidence for a plan. Low-wear circuits, where $d$ is small and the extra wear costs little, and races with a high SC hazard (a cheap stop is likely anyway) are the cases where the long stint gets closer to paying.

D5. When the data say "wait"

The case that the delay was right. On lap 8 the evidence was five cars on slicks, 1.2 s faster on one lap. Five cars' medians on one lap make a thin sample, and their pace depends on how long their slicks had been running and what was ahead of them on the road. A switch from inters to slicks also costs more than a dry stop, because the first slick lap is cold. One lap of a 1.2 s delta does not show that the delta will keep growing. Waiting a lap to see a second lap, as the crossover definition itself does with its two-lap confirmation, is a reasonable rule.

The case that it was wrong. On a drying track the delta grows lap after lap, so the cost of being late grows with the square of the delay (the chapter's late_switch_cost is $k b + g k(k-1)/2$). The cars that waited were not waiting for information they lacked. They were watching the same timing screens, and the slick runners' advantage was visible every lap from lap 8.

What the curve says. The chapter's quadratic for the window time has a curvature of 2.50 s/lap² and a best in-lap of 7.8. On that curve the cost of each in-lap is $2.50\,(L - 7.8)^2$:

  in-lap  8: 2.50 x (8 - 7.8)^2 =   0.1 s above the best
  in-lap  9: 2.50 x (9 - 7.8)^2 =   3.6 s above the best
  in-lap 10: 2.50 x (10 - 7.8)^2 =  12.1 s above the best
  in-lap 11: 2.50 x (11 - 7.8)^2 =  25.6 s above the best
  in-lap 12: 2.50 x (12 - 7.8)^2 =  44.1 s above the best

The curve supports the second argument. Boxing at the end of lap 8, on the first lap of evidence, cost almost nothing, and the field's median in-lap of 10 cost about 12 s. Waiting one lap for confirmation (in-lap 9) cost only 3.6 s, so the confirmation rule was cheap. Waiting two or more laps was expensive, and Pérez's in-lap 12 sits about 44 s above the best on the fitted curve.

The fit uses the finishers' window times with each car's own pace removed. It is a clear pattern, but it comes from one race. The fair verdict is "one lap of caution was justified, three were not".

Chapter 16

Chapter 16 — Qualifying Strategy · exercises · verification script: appendices/code/answers_part1_ch16.py

Worked in the chapter. B1–B9 (all of Part B) and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution, Reveal or Discussion blocks there.

C1. Analyze this session

We call the three boxbox.qualifying functions on the 2025 Italian GP qualifying session. Phase lengths come from the race-control start and chequered-flag messages.

s = f1data.session(2025, "monza", "Q")
ph = Q.phases(s)
ph["length_min"] = (ph.flag - ph.start).dt.total_seconds() / 60
dl = Q.deleted_laps(s)
for p in (None, 1):
    ev = Q.track_evolution(s, phase=p)
 phase  red_flag  length_min
     1     False        18.0
     2     False        15.0
     3     False        12.0
Deleted laps (race-control messages): 5
Track evolution, whole session: -0.0120 s/min [-0.0152, -0.0087], n = 98 laps, 19 drivers, span 59.4 min
Track evolution, Q1 only: -0.0393 s/min [-0.0568, -0.0217], n = 46 laps, 19 drivers, span 15.9 min
  • Phases. The phases ran 18, 15 and 12 minutes, the standard 2023–25 format, with no red flag.
  • Deletions. Race control deleted five laps, all for track limits: SAI, ALB, LAW and two for NOR. Two of these messages name a lap number rather than a time.
  • Evolution. Both slopes are negative, and the Q1 slope is steeper, as expected. Monza's whole-session slope (−0.012 s/min) is shallower than the chapter's median of −0.0190 s/min. So is its Q1 slope (−0.039 s/min) against the pooled Q1 median of −0.0552 s/min.
  • Caveat. With only 98 push laps, the Q1 interval is wide.

C2. Compare these drivers

theoretical_best() adds each driver's best three sectors over every lap that was not deleted.

tb = Q.theoretical_best(f1data.session(2025, "suzuka", "Q"))
tb[tb.acronym.isin(["VER", "NOR", "PIA"])][["acronym", "s1", "s2", "s3",
                                             "actual_s", "theoretical_s", "gap_s"]]
acronym     s1     s2     s3  actual_s  theoretical_s  gap_s
    VER 30.387 39.355 17.241    86.983         86.983  0.000
    NOR 30.358 39.301 17.307    86.995         86.966  0.029
    PIA 30.514 39.197 17.205    87.027         86.916  0.111
Order by theoretical lap: ['PIA', 'NOR', 'VER']
  • Who had the fastest theoretical lap? Piastri, at 86.916 s. He was slowest of the three on actual laps, but he set the best S2 and S3.
  • Verstappen strung his best three sectors together on the pole lap, so his gap is 0.000. He had the least pace on paper and converted all of it.
  • Matches the chapter. The table matches the chapter's run exactly.
  • Caveat. These are sector sums across different laps, often on different tyre sets and track states. They say who had pace available, not who "should" have had pole.

C5. Compare these drivers

We take the push-start table that 04_traffic_and_tow.py saved, keep 2025 Haas and Williams cars, and compute abort rates by gap band with Wilson intervals. To compare the two teams overall, we add a normal-approximation interval for the difference.

d = pd.read_parquet(CH16 / "code" / "push_starts_2023_2026.parquet")
d = d[(d.year == 2025) & d.team_ref.isin(["haas", "williams"])]
d["band"] = pd.cut(d.gap_ahead_s, [0, 2, 4, 8, 15, np.inf], right=False)
for (team, band), g in d.groupby(["team_ref", "band"], observed=True):
    p, lo, hi = metrics.wilson_ci(int(g.is_aborted.sum()), len(g))
    team band  n  aborted  pct       ci
    haas   <2 10        0  0.0 0.0-27.8
    haas  2-4 31        2  6.5 1.8-20.7
    haas  4-8 87        6  6.9 3.2-14.2
    haas 8-15 29        0  0.0 0.0-11.7
    haas >=15 22        0  0.0 0.0-14.9
williams   <2 25        3 12.0 4.2-30.0
williams  2-4 20        2 10.0 2.8-30.1
williams  4-8 82        3  3.7 1.3-10.2
williams 8-15 73        4  5.5 2.2-13.3
williams >=15 28        3 10.7 3.7-27.2
haas      all gaps: 8/179 = 4.5% [2.3, 8.6]
williams  all gaps: 15/228 = 6.6% [4.0, 10.6]
Difference haas - williams: -2.1 pp, 95% CI [-6.5, +2.3] (normal approximation)
  • No difference is distinguishable from zero. Overall, Haas abandoned 4.5% of its push starts and Williams 6.6%. The difference is −2.1 percentage points, with an interval of −6.5 to +2.3 that comfortably includes zero.
  • The bands are too small. Every band holds between 10 and 87 laps, so the band intervals overlap almost completely.
  • The < 2 s band. It looks dramatic (0 of 10 against 3 of 25), but Haas's own interval runs to 27.8%.
  • What would work instead. To compare teams, pool seasons, or test a single pre-chosen contrast, as here, rather than scanning ten cells for a "difference".

C7. Analyze this session

For every dry 2026 qualifying session, we take the Q3 push laps from quali_laps() and count those that began less than 4 s after another car crossed the line.

for _, s in ss.iterrows():                       # 2026 Q sessions with laps
    if Q.is_wet(s.session_key):
        continue
    lp = Q.quali_laps(s.session_key)
    q3 = lp[(lp.phase == 3) & lp.is_push & lp.gap_ahead_s.notna()]
    share = (q3.gap_ahead_s < 4).mean()
 round       circuit  q3_push_laps  under_4s  share  median_gap_s
    13         monza            18        15   83.3           2.8
    21         vegas            19        15   78.9           2.4
    15          baku            18         4   22.2           5.8
    19     rodriguez            18         3   16.7           7.2
    10           spa            17         2   11.8           6.0
   ...
     1   albert_park            15         0    0.0           9.0
     4         miami            18         0    0.0           9.7
     7     catalunya            15         0    0.0           9.5
     9   silverstone            18         0    0.0           7.8
     8 red_bull_ring            18         0    0.0           8.1
    14       madring            20         0    0.0           8.5
    18      americas            13         0    0.0           9.7
Sessions: 20; pooled share 14.3% (51/356); median session share 5.6%
  • The table. It has 20 rows, as expected. Round 16, labelled sepang, is the round the data name "Bahrain Grand Prix in Malaysia". The 2026 Brazilian GP qualifying session is not in the list because the book's rule classes it as wet.
  • Most closely spaced Q3 running: Monza. 15 of 18 push laps there began within 4 s of another car, with a median gap of 2.8 s. Las Vegas is close behind at 15 of 19.
  • Why those two. Both are long-straight, power-sensitive circuits. That fits the tow logic of Section 16.6: cars queue so that they cross the line close behind another car.
  • The rest of the calendar. Elsewhere the median session share is only 5.6%, and seven sessions have none.
  • Caveat. A cluster at Monza and Las Vegas shows that teams seek a gap there. It does not show that the tow is worth lap time. The chapter could not distinguish that effect from zero at 2–4 s.

Chapter 17

Chapter 17 — Race Start and Lap 1 · exercises

Worked in the chapter. Every problem in Parts B, C and D already has a full worked solution in the exercises file:

  • Part B: B1–B7 (launch acceleration, reaction cost, grid side, hazard arithmetic, Turn 1 break-even, reliability, shrinkage).
  • Part C: C1–C7 (the data and code problems, with their outputs).
  • Part D: D1–D4.

Open the solution blocks there. This appendix adds nothing for Chapter 17. The chapter's scripts in code/ reproduce every number in those solutions, so there is no separate verification script.

Chapter 18

Chapter 18 — The Strategy Room · exercises · verification script: appendices/code/answers_part1_ch18.py

Worked in the chapter. B1–B8 (all of Part B), D1 and D5 have full solutions in the exercises file; open the Solution or Discussion blocks there.

C4. Analyze this session: the 2026 Mexico City GP decision log

We replay the race with pitwall.run(session, Rules.v2()), keep Hamilton's rows, and set them next to his real tyre changes.

s = f1data.session(2026, "Mexico", "R")
log, feed = pw.run(s, pw.Rules.v2())
d = log.compare(feed)
box = d[(d.acronym == "HAM") & (d.call == "BOX")].sort_values("time")
hl = f1data.laps(s).query("acronym == 'HAM'").sort_values("lap_number").reset_index(drop=True)
print(hl.lap_number[pw.tyre_changes(hl).to_numpy()].tolist())
 leader_lap status trigger compound  tyre_age  stops  opp_lap                      reason  actual_box
         19  GREEN     lap     SOFT        21      0       20         set 21 laps >= 20.9       False
         20  GREEN     lap     SOFT        22      0       21         set 22 laps >= 20.9       False
        ...
         27  GREEN     lap     SOFT        29      0       28         set 29 laps >= 20.9        True
         28  GREEN     lap     SOFT        30      0       29         set 30 laps >= 20.9       False
         43     SC      SC   MEDIUM        15      1       44 SC: extra stop worth +8.7 s        True
         44     SC     lap   MEDIUM        15      1       45 SC: extra stop worth +7.9 s        True
         58     SC      SC     SOFT        16      3       59 SC: extra stop worth +0.6 s       False
HAM tyre changes at the end of laps: [28, 44, 45]
stint after 0 stops: first green BOX at leader lap 19 (set age 21, 'set 21 laps >= 20.9'), opp_lap 20; next actual tyre change at end of lap 28
  • The trigger fired once. The "set has paid" trigger fired only in Hamilton's first stint. It first fired at leader lap 19, when his SOFT set was 21 laps old. The set was already 3 laps old at the start, so this was 19 laps into the stint, close to the "about 21 laps" the exercise expects.
  • He stopped 8 laps later. He actually stopped at the end of lap 28, 8 laps after the first called opportunity (lap 20). The lag is shorter than the race-wide median of 12 laps but points the same way: real pit walls run the set past the rule's break-even.
  • Why no green call after that. The rule fires only while a stop is still owed. After the SOFT → MEDIUM stop the two-compound requirement was met, so no green trigger could fire again.
  • The later BOX calls. Every later BOX call is a safety-car call:
  • Laps 43–44: the call (+8.7 s) matched his stop under the lap-44 SC.
  • Lap 45: his tyre change at the end of lap 45 is the free change during the red flag.
  • Lap 58: the rule priced an extra stop at only +0.6 s, and he stayed out.

C5. Predict the race: a VSC rule fitted on 2023–24

We grid-search min_age_vsc from 2 to 14 with Rules.v2()'s other settings. The data are VSC openings after lap 1 in dry races, with incidents that turned red excluded. We fit on 2023–24 and score on each later season, using the same sample filter as the chapter.

for t in range(2, 15):
    d = pw.evaluate_neutralisations(races, pw.Rules.v2(min_age_vsc=t), kinds=("VSC",))
    d = d[d.dry & ~d.red_followed & (d.start_lap > 1)]
    res[t] = d                              # agreement on d[d.year <= 2024] picks t
 min_age_vsc   n  agree  box_calls
           2 287  0.683         98
           ...
           9 287  0.840         53
          10 287  0.843         52
          11 287  0.847         51
          12 287  0.847         49
          13 287  0.847         47
          14 287  0.836         26
Best threshold (first maximum): min_age_vsc = 11
  2023-24 (in sample): n = 287, actual box rate 19.2%, never-box baseline 80.8%, rule agreement 84.7%, precision 0.608, recall 0.564
  2025: n = 148, actual box rate 18.9%, never-box baseline 81.1%, rule agreement 79.7%, precision 0.458, recall 0.393
  2026: n = 368, actual box rate 21.5%, never-box baseline 78.5%, rule agreement 79.6%, precision 0.529, recall 0.456
  • The fitted threshold is 11 laps. The training curve is flat from 10 to 13 laps (84.3–84.7%), so "about 10–13" is the honest reading.
  • Out of sample, the rule barely matches the never-box baseline. In 2025 it agrees 79.7% of the time, below the never-box baseline of 81.1%. In 2026 it agrees 79.6%, against a baseline of 78.5%, so it is only 1.1 points better.
  • Precision and recall fall from 0.61/0.56 in sample to 0.46/0.39 (2025) and 0.53/0.46 (2026).
  • The conclusion. Most VSC decisions are "stay", so agreement flatters any rule that rarely boxes. A threshold read off the same seasons it is scored on looks better than it is. This is the result the exercise anticipated.

C6. Compare these drivers: team-mate passes by team

We count green-flag team-mate passes from the book's pass classification, the same cached file 06_team_orders.py reads. Adjacency is measured on every green lap end after lap 1 on which both of a team's cars had a position.

a = gp.overtaking_driver_number.map(team).to_numpy()
b = gp.overtaken_driver_number.map(team).to_numpy()
pas += list(a[a == b])                                    # team-mate passes
for (L, t), g in g2.groupby(["lap_number", "team_ref"]):
    if len(g) == 2:
        adjacent = abs(np.diff(g.position_end.to_numpy()))[0] == 1
        team  teammate_passes  laps_both_running  laps_adjacent  adj_share    adj_ci  passes_per_100_adj_laps
aston_martin               29                575            305       53.0 49.0-57.1                      9.5
    mercedes               21                991            289       29.2 26.4-32.1                      7.3
     ferrari               20                963            454       47.1 44.0-50.3                      4.4
        audi               12                825            168       20.4 17.8-23.2                      7.1
     mclaren               10                894            196       21.9 19.3-24.8                      5.1
      alpine                7                943            206       21.8 19.3-24.6                      3.4
        haas                7                861            166       19.3 16.8-22.0                      4.2
    red_bull                6                838            126       15.0 12.8-17.6                      4.8
          rb                5                916            244       26.6 23.9-29.6                      2.0
    williams                5                818            268       32.8 29.6-36.1                      1.9
    cadillac                3                564            274       48.6 44.5-52.7                      1.1
Team-mate passes 2026: 125 in 21 races, of 1132 green passes = 11.0% [9.3, 13.0]
  • The total matches the chapter. The total of 125 team-mate passes matches the chapter's figure, and seven of the eleven teams have single-digit counts.
  • How often team-mates run together varies a lot. Aston Martin, Cadillac and Ferrari cars ran nose-to-tail on about half of their shared green laps. Red Bull's did on only 15%.
  • Passes per adjacent lap is the fairer comparison. It ranges from 9.5 per 100 adjacent laps at Aston Martin to 1.1 at Cadillac. Even so, counts of 3–29 cannot separate team policy from car pace differences and circuit mix.
  • The intervals are too narrow. The Wilson intervals on adjacency treat laps as independent. Consecutive laps are strongly dependent, so the real intervals are wider than printed.

C7. Analyze this session: warning times at Baku

deployment_warning finds the first sector yellow or double yellow in the 120 s before each window opens.

for _, s in RACES[RACES.circuit_ref == "baku"].iterrows():
    w = pw.deployment_warning(s.session_key)
 year status  start_lap  warning_s  had_double
 2023     SC       11.0       82.0        True
 2024    VSC       51.0       77.0        True
 2025     SC        1.0       29.0        True
 2026     SC       31.0       87.0        True
 2026     SC       36.0       64.0        True
  • The values. Baku had four safety cars and one VSC in 2023–26, and every one was preceded by a double yellow.
  • Compared with the all-circuit median. The SC warnings were 29, 64, 82 and 87 s. Three are well above the all-circuit SC median of 29 s, and the lap-1 SC in 2025 sits exactly on it.
  • Too few to conclude. Five deployments are not enough to say Baku gives "more warning". One plausible reading is that its long street-circuit recoveries are signalled early, but a single additional quick deployment would move the median a lot. Report the five values, not a rate.

D2. Call the pit stop: 2023 Australian GP, lap 7, P2

The state 1 s after the safety car, priced with the chapter's rules (Rules.v2()), and what happened:

 position acronym compound  tyre_age  gap_to_leader  s_to_line call                    reason
        1     RUS   MEDIUM         6            0.0       54.2  BOX SC: owed stop at SC price
        2     HAM   MEDIUM         6            0.6       41.7  BOX SC: owed stop at SC price
Red flag 158 s after the SC
RUS: tyre changes at end of laps [7]; position end lap 6 = 1, end lap 9 = 7
HAM: tyre changes at end of laps [8, 55, 57]; position end lap 6 = 2, end lap 9 = 1
EV(box - stay), owed stop, p(red) = 0.159: +6.21 s
          SC ends normally  SC becomes red flag  max regret
BOX now               0.00               12.722      12.722
STAY out              9.79                0.000       9.790

The call for Hamilton on its own. - Hamilton owes a stop, his set is six laps old, and he is 41.7 s from the line, well inside the decision window. - The expected-value arithmetic says box. With p(red | SC after lap 1) = 0.159, boxing is worth (1 − 0.159) × 9.790 − 0.159 × 12.722 = +6.21 s. Boxing stays positive until p reaches 0.435.

Why a team might split its cars. - Hedging the one unknown that matters. If one car boxes and one stays, the team is certain to have one car on the right side of the red-flag gamble. Each choice's worst case is 12.722 s (box, then a red) or 9.790 s (stay, then no red). Splitting does not lower the expected regret: per car it is 5.13 s, against 2.02 s if both box. What it lowers is the chance that both cars lose together. - Stacking. Hamilton was 0.6 s behind his team-mate. If both box on the same lap, the second car waits while the first is serviced. The book's data snapshot has no measured double-stack cost, so this is reasoning, not a number. It still argues for sending only the leading car. - Track position. The car that stays out inherits the lead on the road.

What happened. Russell boxed under the safety car. The red flag came 158 s later, and the field changed tyres for free. Russell fell from P1 (end of lap 6) to P7 (end of lap 9) and later retired. Hamilton changed during the suspension, came out P1 at the end of lap 9 and finished second.

The lesson. The outcome does not change the grade. At p = 0.159, boxing was still the better expected call for a single car. The split simply guaranteed that Mercedes had a car on the winning side when the low-probability branch came true. Case Study 1 follows the rest of the field.

D4. Team orders

The arithmetic from the exercise's inputs. - P3 is 0.4 s/lap faster and 0.8 s behind, so it reaches the gearbox of P2 in about 2 laps. - If it could pass at once and freely, it would gain about 0.4 × (12 − 2) = 4.0 s over the remaining laps. - Nothing changes in the constructors' table either way, so the only stakes are the drivers' points, the risk to both cars, and the time lost to the car behind.

Risks of letting them race. - Contact. Two cars of one team racing wheel to wheel can take each other out. A collision costs far more than the 4 s at stake. - Dirty air. Following within a second costs measurable lap time (Chapter 20 measures it), so a long fight can slow both cars. That hands time to the car in P4. - Tyres. A fight uses tyres faster in the last laps. - Passing is hard between team-mates. In 2026, team-mates swapped places on track only 125 times in 21 races. They were adjacent on 29.4% of shared green laps, so a pass may simply not come.

Risks of a swap. - A swap hands a driver a result they did not earn on track. - A swap carries internal and public relations costs. The chapter's data cannot measure these. - If the faster car's pace advantage comes from a younger tyre that is about to fade, the swap may be reversed by the flag anyway.

What data you would want, and whether the book's data snapshot has it.

What you would want In the snapshot?
Each car's recent fuel-corrected pace and tyre age Yes: laps, stints
The gap behind to P4 Yes: intervals
How often passes succeed at this circuit Yes: the overtakes table, as classified in Chapter 35
Each driver's championship position Yes: standings
Any race-control investigation Yes: race control
What the team told the drivers No: the radio index has audio URLs, not transcripts, and the book does not transcribe them
Tyre temperatures, brake temperatures, energy state No
Each driver's contract terms No

A reasonable call. Let them race for a fixed number of laps with a no-contact instruction, then reassess. If P3 has not passed by then and P4 is closing, swap. Write down the decision rule before the race, not during it.

Chapter 19

Chapter 19 — Lap Time Analysis · exercises · verification script: appendices/code/answers_part1_ch19.py

Worked in the chapter. B1–B10 (all of Part B), C1, C2, C8 and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

C3. Segment colours over a session

For every dry 2025 qualifying session, we take the purple share of the pole-sitter's and P2's fastest non-deleted laps from laptime.segment_summary.

for ss, L in dry_q_sessions(2025):
    res = f1data.results(ss.session_key).sort_values("position")
    p1, p2 = res.acronym.iloc[0], res.acronym.iloc[1]
    sm = laptime.segment_summary(L, lap="fastest",
                                 exclude=laptime.deleted_lap_keys(ss.session_key)).set_index("acronym")
    rows.append(dict(pole_purple=sm.purple_share[p1], p2_purple=sm.purple_share[p2]))
 round       circuit pole  p2  pole_purple  p2_purple  n_seg  pole_higher
     1   albert_park  NOR PIA        0.143      0.227     21        False
     5        jeddah  VER PIA        0.154      0.077     26         True
     7         imola  PIA VER        0.429      0.095     21         True
     8        monaco  NOR LEC        0.095      0.286     21        False
    10    villeneuve  RUS VER        0.158      0.158     19        False
    ...
    23        losail  PIA NOR        0.217      0.583     23        False
    24    yas_marina  VER NOR        0.292      0.208     24         True
Pole lap purple share > P2's in 13 of 22 sessions = 59.1% [38.7, 76.7] (ties 1; lower 8)
Median purple share: pole 0.205, P2 0.148
  • The table has 22 rows. The 2025 Azerbaijan qualifying session has no laps in OpenF1, so it is missing.
  • The pole lap shows more purple more often than not, but not convincingly. It does in 13 of 22 sessions (59.1%). The Wilson interval, 38.7–76.7%, includes 50%. There is one tie and 8 sessions where P2's lap was purpler.
  • Why this is not a measure of pace.
  • A segment is purple only if it was the best so far in the session when it was set. A lap set early, before the track has evolved, can be purple in places that a faster lap minutes later merely matches.
  • The colour is binary. It ignores by how much a segment was won.
  • P2 can be the purpler lap and still lose, as at Monaco (0.286 against 0.095) and Losail (0.583 against 0.217). Pole is decided by the sum of times, not the count of colours.

C4. The pole-on-paper list

We read the chapter's pole_on_paper_2023_2026.csv. For each of the 15 sessions where the theoretical-best leader was not on pole, we find the lap holding the leader's best S1, S2 and S3, excluding deleted laps. We then read off that lap's phase from qualifying.quali_laps(), which assigns phases from the race-control phase messages.

lp = Q.quali_laps(sk)
d = lp[lp.acronym == r.theo_leader]
d = d[[(a, b) not in deleted for a, b in zip(d.driver_number, d.lap_number)]]
for i in (1, 2, 3):
    best = d.loc[d[f"duration_sector_{i}"].idxmin()]
    phases.append(f"Q{int(best.phase)}")
 year     circuit pole theo_leader  gap_to_pole S1 S2 S3  any_q1_q2
 2023 hungaroring  HAM         VER        0.236 Q3 Q3 Q3      False
 2023  interlagos  VER         NOR        0.830 Q2 Q2 Q2       True
 2024     bahrain  VER         LEC        0.095 Q3 Q2 Q2       True
 2025       miami  VER         NOR        0.188 Q3 Q3 Q1       True
 2025 hungaroring  LEC         PIA        0.629 Q2 Q2 Q2       True
 2025    americas  VER         NOR        0.082 Q3 Q2 Q3       True
 2026  marina_bay  VER         HAM        0.028 Q3 Q3 Q2       True
 2026   rodriguez  HAM         VER        0.107 Q2 Q3 Q3       True
 ...   (7 more rows, all Q3 Q3 Q3)
Poles on paper resting on at least one Q1/Q2 sector: 7 of 15; all three sectors from Q3: 8
2023 interlagos: fastest valid lap by phase {1: 70.34, 2: 70.021, 3: 70.727}
2025 hungaroring: fastest valid lap by phase {1: 75.211, 2: 74.89, 3: 75.372}
  • The count. 7 of the 15 "poles on paper" use at least one sector set in Q1 or Q2.
  • The two largest gaps rest entirely on Q2 laps. These are 2023 Interlagos (0.830 s) and 2025 Hungaroring (0.629 s). In both sessions the fastest Q3 lap was slower than the fastest Q2 lap (70.727 against 70.021 s, and 75.372 against 74.890 s), so the "pole on paper" compares a Q2 track with the Q3 pole time.
  • The 8 that are all-Q3. These are the better evidence of pace left on the table on the decisive runs. Even there, the best sectors may come from different Q3 laps, on different sets.
  • Caveat. 2026 Monza is in the list with GAS as the official pole-sitter. The chapter notes that his lap fails the telemetry quality check.

C5. Mini-sector count

We take the 2026 Mexico City pole pair's fastest laps (Hamilton 1:16.514, Russell 1:16.523). Both pass quality_check. We build the sector-anchored delta and cut the lap into n equal pieces.

D = laptime.delta_trace(tel["HAM"], tel["RUS"], laps=laps, align="sectors")
L = float(tel["HAM"].distance_m.iloc[-1])
for n in (5, 10, 25, 50):
    sd = laptime.segment_deltas(D, np.linspace(0, L, n + 1))
    sig = float(sd.delta_change_s.abs().median())
    print(n, sig, sig / (np.sqrt(2) * 0.027))
HAM lap 19 quality {'frozen_s': 0.44, 'max_gap_s': 1.2, 'dist_ratio': 0.986, 'ok': True}
RUS lap 21 quality {'frozen_s': 0.0, 'max_gap_s': 1.2, 'dist_ratio': 0.986, 'ok': True}
Delta at the line (RUS - HAM): +0.009 s; lap distance 4245 m
  n =   5 (  849 m): median |mini-sector delta| 0.047 s; signal / (sqrt(2) x 0.027) = 1.23
  n =  10 (  425 m): median |mini-sector delta| 0.056 s; signal / (sqrt(2) x 0.027) = 1.48
  n =  25 (  170 m): median |mini-sector delta| 0.021 s; signal / (sqrt(2) x 0.027) = 0.54
  n =  50 (   85 m): median |mini-sector delta| 0.011 s; signal / (sqrt(2) x 0.027) = 0.29
  • Where the ratio drops below 1. It falls between n = 10 and n = 25, the same place as at Suzuka (VER–NOR: 2.16 at n = 10, 0.85 at n = 25).
  • Mexico's ratios are lower at every n. The pair is closer (0.009 s over the lap), so there is less signal to find. The 2026 noise (0.027 s) is also higher than the 0.024 s used for Suzuka 2025.
  • What to use in practice. For a pair this close, ten mini-sectors of about 425 m is the finest cut worth reading. At 25 or more, most mini-sector "wins" are noise.

C6. Build the strategy

We run laptime.theoretical_best() on every dry 2026 qualifying session, excluding deleted laps and keeping consistent rows. Then we take each driver's season median of the perfect-lap gap (actual minus theoretical best).

for ss, L in dry_q_sessions(2026):
    t = laptime.theoretical_best(L, exclude=laptime.deleted_lap_keys(ss.session_key))
    rows.append(t[t.consistent])
T = pd.concat(rows)
S = T.groupby("acronym").gap_s.agg(["size", "median"])
20 dry sessions, 434 driver-sessions; drivers with >= 5 sessions: 22
         sessions  median_gap_s    p25    p75  share_under_0_01
STR            18         0.000  0.000  0.072             0.556
ALO            20         0.003  0.000  0.150             0.550
BOT            20         0.018  0.000  0.095             0.450
...
LAW            20         0.102  0.021  0.141             0.250
ALB            20         0.108  0.034  0.166             0.200
Largest median gap: ALB
Field median perfect-lap gap 2026: 0.046 s
  • The table has 22 rows. The 2026 Brazilian GP qualifying session counts as wet and is excluded.
  • Least left on the table: Stroll (0.000 s, over 18 sessions), Alonso (0.003 s) and Bottas (0.018 s).
  • Largest median gap: Albon (0.108 s), more than twice the field median of 0.046 s. His gap is above 0.1 s in 12 of 20 sessions, so this is a pattern rather than one outlier lap.

One run or two in Q3 for Albon? A large, persistent perfect-lap gap means his best sectors are spread across laps. A second Q3 attempt on fresh tyres gives him another chance to string them together, and track evolution makes later laps faster anyway. On this evidence we would plan two runs, if the tyre allocation allows it.

The limits of this reasoning. - The theoretical best mixes laps from different phases and track states. C4 shows that 7 of the 15 poles on paper rest on a Q1 or Q2 sector. - It includes sectors from laps that were later aborted. - It says nothing about whether a second run actually recovers the gap: that needs the run-by-run comparison of Chapter 16. - A small gap can mean either a consistent driver or a slow car with little to find. Pérez and Bottas lead the list, but that does not make them the quickest qualifiers.

Chapter 20

Chapter 20 — Race Pace: Fuel Correction, Traffic and Dirty Air · exercises · verification script: appendices/code/answers_part1_ch20.py

Worked in the chapter. B1–B9 (all of Part B) and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

Every pace number below names its fuel correction. "Data" means the race's own fuel + track-evolution slope from pace.fuel_effect. That slope is an upper bound on the fuel effect alone.

C1. Analyze this session: 2024 Saudi Arabian GP, Race

We reproduce the slope, refit on later laps by filtering the laps frame, and list the strategies.

s = f1data.session(2024, "jeddah", "R")
r = pace.fuel_effect(s)                                   # (a)
lp = f1data.laps(s)
r20 = pace.fuel_effect(lp[lp.lap_number >= 20])          # (b)
a = strategy.actual_strategies(s)                         # (c)
(a) all laps:      -0.1218 s/lap [-0.1324, -0.1112], n = 796 laps, 18 drivers, race laps 50
(b) laps 10+:       -0.1265 s/lap [-0.1420, -0.1111], n = 193 laps, 5 drivers
(b) laps 20+:       -0.1205 s/lap [-0.1486, -0.0923], n = 143 laps, 5 drivers
Neutralisations:
 start_lap types
       7.0    SC
(c) stints:
acronym  grid  position sequence  n_stops stop_laps   status
    VER     1         1      M-H        1      (7,) Finished
    PER     3         2      M-H        1      (7,) Finished
    ...
    NOR     6         8      M-S        1     (37,) Finished
    HAM     8         9      M-S        1     (36,) Finished
    HUL    15        10      M-H        1     (33,) Finished
    BOT    16        17    S-H-S        2   (7, 35)   Lapped
    ZHO    20        18      M-S        1     (41,)   Lapped
Clean dry laps by 10-lap block: {1: 97, 11: 180, 21: 180, 31: 172, 41: 171}
  • (a) Reproduced exactly. The slope is −0.1218 s/lap [−0.1324, −0.1112] on 796 laps.
  • (b) The late-race refit does not move towards the −0.056 median. It stays at −0.1205 s/lap. So early-race track evolution is not what makes this race steep.
  • (c) The strategies explain it.
  • Thirteen of the twenty cars made their only stop on lap 7, under the safety car, and Bottas also stopped then. From there most of the field ran one long HARD stint to the flag.
  • The estimator separates fuel from tyre wear using the tyre-age reset at stops. That needs drivers with two stints inside the sample. From lap 10 or lap 20 onwards, only 5 drivers qualify (the late stoppers NOR, HAM, HUL, ZHO and BOT), and the interval widens accordingly.
  • Over the whole race, the lap-7 resets happen almost at the start, so lap number and tyre age move together for most of the field.
  • The steep slope is an identification problem, not physics. It most plausibly absorbs tyre behaviour on those long HARD stints, plus track evolution, rather than fuel alone.
  • What to do with a race like this. Use the median slope, the "median" correction, or a stated assumption rather than this race's own "data" slope.

C2. Compare these drivers: 2026 Mexico City GP, Race

We compute the race-pace table with traffic included and excluded, using the race's data fuel correction. Then we fit pace_model and compute the HAM − VER base-pace difference, with its standard error from the full covariance matrix.

for tr in ("include", "exclude"):
    t = pace.race_pace_table(s, fuel="data", traffic=tr).set_index("acronym")
m = pace.pace_model(s)
ka, kb = "C(acronym)[HAM]", "C(acronym)[VER]"
cov = m["fit"].cov_params()
d = m["fit"].params[ka] - m["fit"].params[kb]
se = np.sqrt(cov.loc[ka, ka] + cov.loc[kb, kb] - 2 * cov.loc[ka, kb])
traffic=include: fuel correction 'data slope -0.0267 s/lap'
VER          57  79.686  79.603   79.809  0.000     1        0.018
HAM          57  79.699  79.609   79.886  0.013     2        0.281
traffic=exclude: fuel correction 'data slope -0.0267 s/lap'
VER          56  79.695  79.596   79.818  0.000     1        0.018
HAM          41  79.886  79.766   79.996  0.191     2        0.281
pace_model base pace (empty tank at the flag, new MEDIUM, clean air):
VER      79.257  0.102  0.066
HAM      79.191  0.134  0.000
HAM - VER: include +0.013 s, exclude +0.191 s, model -0.066 s (SE 0.054; 95% CI -0.172 to +0.039)
Measure HAM − VER
Clean laps, traffic included (data fuel) +0.013 s
Clean laps, traffic excluded (data fuel) +0.191 s
pace_model base pace −0.066 s [−0.172, +0.039]
  • The order is not settled. The three measures give two different answers.
  • With traffic included, the two are 0.013 s apart.
  • Dropping Hamilton's 28.1% of laps begun within a second of the car ahead widens the gap to 0.191 s. His remaining clean-air laps were not his fastest.
  • The model, which controls for compound, tyre age and traffic, puts Hamilton 0.066 s ahead. Its interval comfortably spans zero.
  • Why the measures disagree. They weight the stints differently. With one race and two cars, the honest statement is "too close to call".

C5. Compare these eras: Suzuka

We run pace.traffic_cost on Suzuka's dry races, one season at a time, clustered by driver-race as in Case Study 2.

L = pace.add_interval_start(pd.concat(suzuka_dry_laps))
L["drace"] = L.session_key * 100 + L.driver_number
for y, g in L.groupby("year"):
    tc = pace.traffic_cost(g, edges=(0.0, 1.0, 2.0, 3.0), cluster="drace").iloc[0]
seasons  coef_0_1s  ci_low  ci_high  n_close  excludes_zero
   2023      0.490   0.241    0.738      113           True
   2024      0.287   0.012    0.562      152           True
   2025      0.364   0.189    0.539      198           True
2023-25      0.366   0.199    0.533      463           True
   2026     -0.044  -0.207    0.119      335          False
  • The pooled values reproduce the case study: +0.366 s/lap for 2023–25 and −0.044 s/lap for 2026.
  • 2026 drives the change. The three DRS-era seasons are consistent with one another (+0.29 to +0.49 s/lap), and each season's interval excludes zero. 2026 is the only season whose interval includes zero.
  • The drop is a break between eras, not a drift. It fits the change from DRS to the 2026 Overtake mode and active aero. With one race per season, the timing data cannot separate those two causes.

C7. Teammates by base pace

For every dry 2025 race we fit pace_model and take Norris − Piastri. The standard error comes from the full covariance matrix, so the correlation between the two drivers' estimates is respected.

for sk in dry_2025_races:
    m = pace.pace_model(sk)
    d, se = base_diff(m, "NOR", "PIA")        # params[NOR] - params[PIA], SE from cov_params()
    rows.append(dict(nor_minus_pia=d, lo=d - 1.96 * se, hi=d + 1.96 * se))
  round 17 baku: laps completed {'NOR': 51, 'PIA': 1}
 round       circuit    NOR    PIA  nor_minus_pia    se     lo     hi  excludes_zero
     2      shanghai 93.970 93.881          0.088 0.032  0.026  0.150           True
     4       bahrain 94.533 94.265          0.268 0.049  0.173  0.363           True
     7         imola 78.160 78.251         -0.091 0.032 -0.153 -0.029           True
    14   hungaroring 78.551 78.553         -0.002 0.038 -0.075  0.072          False
    16         monza 80.844 80.977         -0.134 0.015 -0.163 -0.104           True
    18    marina_bay 94.085 94.534         -0.448 0.075 -0.596 -0.301           True
    19      americas 96.803 97.402         -0.599 0.034 -0.666 -0.532           True
    23        losail 82.709 82.521          0.187 0.025  0.139  0.236           True
   ...
Dry 2025 races with both McLarens in the model: 19; intervals excluding zero: 11 (NOR faster 5, PIA faster 6); median NOR - PIA +0.022 s
  • Hungary reproduces exactly: −0.002 s (NOR 78.551, PIA 78.553).
  • There are 19 points, not 20. 2025 has 20 dry races by the book's rule, but at Baku Piastri completed one lap, so there is no team-mate comparison there. The table above is the data for the requested chart: each point with its ±1.96 SE bar.
  • Eleven of the 19 intervals exclude zero: five favour Norris and six favour Piastri. The season median is +0.022 s (Piastri faster), close to zero.
  • Read the race-level "significance" with care.
  • The model's standard errors are clustered by driver, so each race has only about 20 clusters.
  • The base pace also absorbs everything the model leaves out: different strategies, damage, and a car managing a gap.
  • Large single-race values, such as Austin −0.599 s and Marina Bay −0.448 s, are more likely race circumstances than a change in either driver's speed.
  • The fair summary. Across a season the two were very evenly matched, and single races swing both ways.

Chapter 21

Chapter 21 — Driver Comparison · exercises · verification script: appendices/code/answers_part2_ch21.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D4 (all of Part D) have full solutions or guidance in the exercises file; open the Solution, Reveal or Guidance blocks there.

C1. Compare these drivers: a full season duel

We build the 2024 teammate gaps, take McLaren's head-to-head row, and list Norris's round-by-round gap, which is the data for the requested 24-bar chart.

g24 = ratings.teammate_gaps(years=2024)
h = ratings.head_to_head(g24)
nor = g24[(g24.team_ref == "mclaren") & (g24.driver_ref == "norris")].sort_values("round")
driver_ref teammate_ref  n  median_gap_pct  ahead  share_ahead  ci_low  ci_high
    norris      piastri 24          -0.126     20        0.833   0.641    0.933
   piastri       norris 24           0.126      4        0.167   0.067    0.359
 round   circuit_ref session  gap_pct
     1       bahrain      Q3   -0.077
     2        jeddah      Q3   +0.049
     ...
    17          baku      Q1   +0.557
    18    marina_bay      Q3   -0.477
    19      americas      Q3   -0.669
    20     rodriguez      Q1   -1.417
    21    interlagos      Q3   -1.524
    22         vegas      Q3   -0.027
    ...
rounds with |gap| > 1 %: 2; mean gap -0.273 %, median -0.126 %
  • The summary row matches the book's tables. Norris's median gap is −0.126 % and he out-qualified Piastri 20–4. The Wilson interval on his share is 64.1–93.3 %, so the head-to-head clearly favours Norris.
  • Piastri's four wins came at Jeddah, Imola, Monaco and Baku. At Baku the best common session was Q1, so one of the two cars did not set a Q2 time.
  • The mean would mislead. Two rounds exceed 1 %: Mexico City (−1.417 %, compared in Q1) and Interlagos (−1.524 %). They pull the mean to −0.273 %, more than twice the median. This is the outlier pattern of Section 21.2 and the reason the median is the canonical summary.
  • The chart. Plot the 24 gap_pct values as bars by round, in the style of Figure 2. Most bars are short and negative, and the two long bars near the end of the season are the outliers above.

C2. Analyze this session: race pace

We run ratings.teammate_race_pace on the 2026 Mexico City GP (R19) and on R20, which the data name the Brazilian Grand Prix. For each team that drops out, we count its clean dry laps and look up its result. The gaps use the toolkit's fuel-correction assumption, which nearly cancels inside a common lap window.

for name in ("Mexico", "Brazilian"):
    s = f1data.session(2026, name, "R")
    t = ratings.teammate_race_pace(s)       # a minus b; negative = a faster
--- Data: OpenF1 (2026 Mexico City Grand Prix, Race)
team_ref              a              b  gap_s  gap_pct  n_laps   compounds
  alpine      colapinto          gasly -0.484   -0.601      34 MEDIUM+SOFT
    ...
 mclaren         norris        piastri -0.586   -0.735      40        SOFT
mercedes      antonelli        russell -0.270   -0.340      47        SOFT
      rb arvid_lindblad         lawson -0.033   -0.041      41        SOFT
red_bull         hadjar max_verstappen +1.674   +2.109      37 MEDIUM+SOFT
williams          albon          sainz -0.215   -0.266      49        SOFT
  missing aston_martin: clean dry laps {'alonso': {'SOFT': 1}}; common-window laps {}; results [{'acronym': 'STR', 'position': None, 'number_of_laps': 5.0, 'jolpica_status': 'Retired'}, {'acronym': 'ALO', 'position': None, 'number_of_laps': 5.0, 'jolpica_status': 'Retired'}]
--- Data: OpenF1 (2026 Brazilian Grand Prix, Race)
    team_ref              a              b  gap_s  gap_pct  n_laps compounds
      alpine      colapinto          gasly +0.121   +0.161      37      SOFT
aston_martin         alonso         stroll -3.814   -4.998      10      SOFT
    ...
    mercedes      antonelli        russell -0.706   -0.960      35      SOFT
    ...
  missing cadillac: clean dry laps {'perez': {'SOFT': 40}}; common-window laps {}; results [{'acronym': 'PER', 'position': 18, 'number_of_laps': 69.0, 'jolpica_status': 'Lapped'}, {'acronym': 'BOT', 'position': None, 'number_of_laps': 0.0, 'jolpica_status': 'Did not start'}]
Mercedes antonelli - russell: Mexico -0.270 s (-0.340 %), Brazil -0.706 s (-0.960 %)
  • Ten of eleven teams can be compared at each race.
  • At Mexico City, Aston Martin drops out. Both cars are recorded as retired after 5 laps, leaving Alonso one clean lap and Stroll none.
  • At R20, Cadillac drops out. Bottas is recorded as "Did not start", so Pérez has no teammate to compare with.
  • Read the small-sample rows with care. Aston Martin's R20 row rests on 10 laps and gives a 5 % gap. That is not a believable pace difference between two cars of one team, and the method's five-lap minimum lets it through. Red Bull's +2.109 % at Mexico City (Hadjar slower) is also large enough to suggest that one car had a problem the timing data do not explain.
  • The Haas pairings differ. The data list a different second Haas driver at each race (ryo_hirakawa, then rafael_camara), so the two Haas rows are not the same comparison.
  • Mercedes had the same sign at both races. Antonelli was faster on the same compound at both, by 0.270 s (0.340 %) at Mexico City and 0.706 s (0.960 %) at R20, on 47 and 35 laps.

C3. Compare these drivers: Elo vs median

We run the full 1994–2026 Elo with K = 32 and keep the Mercedes duels between Antonelli and Russell.

gaps = ratings.teammate_gaps()
_, log = ratings.elo_from_duels(gaps, k=32)
d = log[(log.team_ref == "mercedes") & (log.a == "antonelli") & (log.b == "russell")]
d26 = d[d.year == 2026]                       # expected_a = Antonelli's pre-duel expected score
2025 duels: 23, Antonelli won 2; rating entering 2026: ANT 1512, RUS 1918
 round  ra_before  rb_before  expected_a  score_a winner
     1   1512.066   1917.562       0.088    0.000    RUS
     2   1509.240   1920.389       0.086    1.000    ANT
     3   1538.496   1891.132       0.116    1.000    ANT
     ...
    11   1647.790   1781.839       0.316    1.000    ANT
     ...
    17   1678.064   1751.564       0.396    1.000    ANT
    18   1697.399   1732.229       0.450    1.000    ANT
    19   1714.998   1714.631       0.501    0.000    RUS
    20   1698.981   1730.647       0.455    0.000    RUS
    21   1684.435   1745.193       0.413    1.000    ANT
2026: Antonelli won 12 of 21; first round with expected_a > 0.5 (pre-duel): 19; final ratings ANT 1703, RUS 1726
cumulative ANT wins minus losses by round: {1: -1, 2: 0, 3: 1, 4: 2, ..., 18: 4, 19: 3, 20: 2, 21: 3}
  • The table has 21 rows, as expected. Antonelli won 12 of the 21 duels, and he led the running head-to-head from round 3 onwards.
  • Elo learned the flip slowly and only partly. Antonelli entered 2026 rated 406 points below Russell (1512 against 1918), after winning only 2 of 23 duels in 2025. His expected score climbed from 0.088 to 0.450 by round 18. It first crossed 0.5 at round 19, at 0.501, which was a coin flip. He lost that duel and the next one, and the season ended with Russell still rated higher (1726 against 1703).
  • Why the two measures disagree. The median gap (Antonelli −0.241 % for 2026) uses only 2026, so it flips at once. Elo carries the whole 2025 record forward, and at K = 32 each win moves only about 20–30 points. Making up a 400-point deficit with a 12–9 record takes most of a season.
  • Which to use. Elo's slowness is a feature for prediction, since one season can be noise. It is a weakness when a real change happens, such as a second-year driver improving. Report both.

C6. Compare these drivers: the network

We list the shortest chains, read the direct 2007 teammate-season, fit the chain with Alonso as the reference, and run a 300-rep race bootstrap (seed 42). We then refit without the 2007 link to see how much the network leans on it.

ps = ratings.pair_seasons(gaps)
ratings.shortest_chains(ps, "alonso", "hamilton")
th = ratings.chain_fit(ps, ref="alonso")
B = ratings.bootstrap_chain(gaps, ref="alonso", n_boot=300, seed=42)
shortest chains: [['alonso', 'hamilton']]
 year team_ref      a        b      y  n  a_ahead
 2007  mclaren alonso hamilton +0.082 17        8
network fit (ref alonso): Hamilton - Alonso = -0.075 %
300 race bootstraps (seed 42): median -0.080 %, 95 % CI -0.192 to +0.044; Hamilton faster in 91.3 % of replicates
network fit without the 2007 link: Hamilton - Alonso = -0.074 %; shortest chains then: [['alonso', 'button', 'hamilton']]
2007 round gaps (Hamilton): n = 17, median -0.082 %, mean +0.081 %, Hamilton ahead 9
  • The direct comparison. They have one shared season, 2007, with 17 rounds. The median gap is +0.082 % to Alonso, which means Hamilton was faster, and the head-to-head was 9–8 to Hamilton.
  • The network estimate. Hamilton − Alonso is −0.075 %. The bootstrap gives a 95 % interval of −0.192 to +0.044, and Hamilton is faster in 91.3 % of replicates. This mirrors the chapter's Hamilton-referenced value (Alonso +0.075 %, −0.046 to +0.197). The small differences in the interval come from the change of reference and the bootstrap draw.
  • Why the two agree so closely. The fit weights the 2007 link by √17, but it is one of many paths between the two drivers. Removing the link entirely barely moves the answer (−0.074 %, now through Button). The rest of the network independently says almost the same thing as 2007.
  • The 2007 season alone is fragile. The mean of Hamilton's 2007 gaps is +0.081 %, which favours Alonso, while the median favours Hamilton. A 9–8 split with the sign depending on the statistic is a near-tie. The honest verdict is "Hamilton slightly ahead on the network, interval includes zero".

Chapter 22

Chapter 22 — Tire Degradation Modeling · exercises · verification script: appendices/code/answers_part2_ch22.py

Worked in the chapter. B1–B10 (all of Part B) and D1–D5 (all of Part D) have full solutions or guidance in the exercises file; open the Solution, Reveal or Guidance blocks there. C7 below reads the chapter's saved stint table, code/stints_dry_2023_2026.csv. Run the chapter's 02_fuel_lesson.py first if it is missing.

Every degradation number below names its fuel correction: raw (none), default (the toolkit's assumption of 100 kg at 0.03 s/kg) or data (the race's own fuel + track-evolution slope, an upper bound on fuel alone).

C1. Analyze this session: 2024 Bahrain Grand Prix (Race)

We build the stint table three times, once per fuel convention, and take the SOFT and HARD medians.

s = f1data.session(2024, "bahrain", "R")
for fuel in ("raw", "default", "data"):
    st = D.stint_table(f1data.laps(s), fuel)
    st[st.compound == "SOFT"].deg.median(), st[st.compound == "HARD"].deg.median()
Data: OpenF1 (2024 Bahrain Grand Prix, Race) | race fuel slope (data): -0.0713 s/lap
         median_deg              n
compound       HARD   SOFT    HARD    SOFT
fuel
raw          0.0396 0.0410 37.0000 23.0000
default      0.0922 0.0936 37.0000 23.0000
data         0.1108 0.1123 37.0000 23.0000
  raw     SOFT/HARD ratio = 1.04
  default SOFT/HARD ratio = 1.02
  data    SOFT/HARD ratio = 1.01
  • The default row reproduces the book's table: SOFT 0.094 s/lap (n = 23) and HARD 0.092 s/lap (n = 37).
  • No convention makes the soft wear "twice the hard". The ratio is 1.04 raw, 1.02 default and 1.01 data. At this race the two compounds wore at practically the same rate.
  • Why the ratio cannot be rescued by the correction. Within one race, a fuel correction adds the same constant to every stint slope: 3.0/57 = 0.0526 s/lap for the default and 0.0713 s/lap for the data slope. The difference between the compounds stays at 0.0014 s/lap under every convention, and adding a constant only pushes the ratio towards 1.
  • Where "twice" comes from. A large ratio appears only when the raw hard slope sits near zero, as in the pooled raw medians (SOFT 0.0178 against HARD −0.0019). Dividing by a number near zero produces any ratio you like. Compare compounds by differences, with the fuel correction named.

C3. Analyze this session: the fuel slope

We compute D.fuel_slope for every dry 2025 race and set it beside the default assumption's −3.0/N, where N is the leader's lap count.

for sk in tyres.dry_race_keys():                       # filtered to 2025
    N = sessions.loc[sk, "leader_laps"]
    rows.append(dict(data_slope=D.fuel_slope(int(sk)), default=-3.0 / N))
 round       circuit        N  data_slope  default  steeper
     2      shanghai +56.0000     -0.0751  -0.0536     True
     3        suzuka +53.0000     -0.0769  -0.0566     True
     ...
    11 red_bull_ring +70.0000     -0.0308  -0.0429    False
    ...
    15     zandvoort +72.0000     -0.0351  -0.0417    False
    17          baku +51.0000     -0.0808  -0.0588     True
    ...
    21    interlagos +71.0000     -0.0301  -0.0423    False
    22         vegas +50.0000     -0.0755  -0.0600     True
    23        losail +57.0000     -0.0817  -0.0526     True
    24    yas_marina +58.0000     -0.0567  -0.0517     True
dry 2025 races: 20; median data slope -0.0552 s/lap; default range -0.0600 to -0.0385; data steeper than default in 14 of 20
correlation of data slope with -3/N: r = +0.83
  • The expected shape holds. There are 20 dry races, with a median data slope of −0.0552 s/lap (the 2025 median quoted in the exercise is −0.055). The default curve runs from −0.0600 at 50 laps to −0.0385 at 78 laps.
  • The data slope is steeper than the default in 14 of 20 races. That matches the all-season pattern (48 of 76 races) and fits the slope also containing track evolution.
  • Race length explains most of the variation. The correlation with −3.0/N is +0.83. Short races such as Baku, Las Vegas and Losail have the steepest slopes, because the same fuel load is burned over fewer laps.
  • The exceptions are the races shallower than the default. The Red Bull Ring (−0.031), Interlagos (−0.030) and Zandvoort (−0.035) are all 70+ lap races, where little track evolution would show up as a per-lap slope.
  • The chart. Plot data_slope against N, and draw −3.0/N as a curve through the cloud.

C6. Analyze this session: a cliff hunt

We fit the hinge model to every 2025 Chinese GP stint with at least 8 usable laps, using default-corrected times. The hinge accepts a cliff only if the F-test gives p < 0.001 and the extra slope is at least 0.15 s/lap, with the break in the second half of the stint.

lp = D.correct_fuel(f1data.laps(s), "default")
for (dn, st), g in lp.groupby(["driver_number", "stint"]):
    f = D.fit_stint(g, model="hinge")
    rows.append(dict(rate=f.slope, cliff_age=f.cliff_age, cliff_rate=f.cliff_rate, cliff_p=f.extra["cliff_p"]))
stints fitted (>= 8 usable laps): 37
stints with a cliff accepted by the F-test: 3
acronym  stint compound  n      rate  cliff_age  cliff_rate   cliff_p
    NOR      2     HARD 40 -0.002237         36      0.9533 1.112e-12
    HUL      1   MEDIUM 15 -0.008045         11      0.3717 0.0006293
    LEC      2     HARD 40   0.01685         33      0.2162 1.658e-06
closest misses (no cliff accepted, smallest F-test p):
acronym  stint compound  n    rate  cliff_age  cliff_rate   cliff_p
    STR      1     HARD 31 0.01196        NaN           0  4.19e-07
    RUS      1   MEDIUM 10  0.1365        NaN           0 8.365e-05
    LAW      1     HARD 13 0.09019        NaN           0  0.001793
  • Norris's hard stint is the strongest cliff, as expected. It breaks at tyre age 36 with an extra +0.953 s/lap (p = 1.1 × 10⁻¹²), exactly Figure 22.5. The plot the exercise asks for is that figure.
  • Two other stints pass both tests:
  • Leclerc's 40-lap hard stint breaks at age 33 with +0.216 s/lap (p = 1.7 × 10⁻⁶).
  • Hülkenberg's 15-lap opening medium stint breaks at age 11 with +0.372 s/lap (p = 6.3 × 10⁻⁴). This is the weakest of the three, since it rests on about four laps after the break.
  • Strong p-values alone are not enough. Stroll's hard stint has p = 4.2 × 10⁻⁷ and Russell's medium p = 8.4 × 10⁻⁵, yet neither passes. Their best break fails one of the other rules (an extra slope of at least 0.15 s/lap in the second half of the stint, and not a "steep fall, then flat" shape). Lawson's p = 0.0018 misses the p threshold.
  • The conclusion. Cliffs are rare across the book's data: only 0.5 % of stints end more than 2 s above their linear fit. Shanghai 2025, with three accepted hinges in 37 stints, two of them on 40-lap hard stints, is the kind of race where a cliff shows up. Even here, a cliff should enter forecasts only as a tyre-life limit, not as a fitted slope.

C7. Compare these drivers: team deg residuals, 2026

From the chapter's stint table (default rows), each stint's residual is its slope minus the median for its race and compound. As in the chapter's script, we take each team's median per race, then the season median of those. The split-half test compares odd and even rounds.

ST["resid"] = ST.deg - ST.groupby("rc").deg.transform("median")      # rc = race x compound
TR = ST.groupby(["year", "round", "team_ref"]).resid.median().reset_index()
TR[TR.year == 2026].groupby("team_ref").resid.median()
2026 dry races in the table: 17; stints 744
              race_median  stint_median  stints  races
team_ref
audi              -0.0170       -0.0163      65     17
mercedes          -0.0107       -0.0101      74     17
red_bull          -0.0016       -0.0001      68     17
...
ferrari           +0.0062       +0.0061      79     17
haas              +0.0087       +0.0085      70     17
cadillac          +0.0198       +0.0119      61     16
split-half 2026 only: r = +0.781 (p = 0.005), n = 11 team-seasons
split-half 2023-26 team-seasons: r = +0.276 (p = 0.081), n = 41 team-seasons
  • The ranking reproduces the chapter. Audi (−0.017 s/lap) and Mercedes (−0.011) are gentlest on their tyres and Cadillac (+0.020) is the hardest. Pooling stints directly, instead of race medians first, keeps the same order at both ends but cuts Cadillac's figure to +0.012. Every team-level value is within about ±0.02 s/lap.
  • The 2026 split-half correlation is +0.781 (p = 0.005), but on only 11 points. A Fisher interval shows how loose that is: z = atanh(0.781) = 1.048, with standard error 1/√(11 − 3) = 0.354. That gives tanh(1.048 ± 1.96 × 0.354), or +0.34 to +0.94.
  • The four-season figure here is +0.276 (n = 41), against the chapter's +0.315. The chapter's sample keeps only races with a dry qualifying session, because it merges in qualifying pace. This answer uses every dry race in the table. The two are within each other's uncertainty.
  • What this says. 2026 looks more consistent than the earlier seasons. One plausible reading is that the new cars differ more in how they use their tyres. With 11 team-seasons, one season's high correlation is a reason to keep watching, not a settled trait.

Chapter 23

Chapter 23 — Telemetry Deep Dive · exercises · verification script: appendices/code/answers_part2_ch23.py

Worked in the chapter. B1–B7 (all of Part B) and D1 have full solutions in the exercises file; open the Solution or Reveal and discussion blocks there. C4 below reads the chapter's saved fingerprint table, code/output/ch23_fingerprints.csv. Run the chapter's 05_fingerprints.py first if it is missing.

C1. Analyze this session — Monza across four seasons

For each Italian GP qualifying session we take the book's top-5 laps (circuit.top_laps) and the median of each lap's pedal split and gear-time shares.

laps, rejected = circuit.top_laps(f1data.session_key(s), n=5, with_location=False)
for acr, team, pos, tel in laps:
    tp, ps = tt.throttle_profile(tel), tt.pedal_split(tel)       # distance share; exclusive % of lap time
    gu = tt.gear_usage(tel).set_index("gear")
median of the top-5 laps; full_dist = % of distance, the rest = % of lap time (exclusive pedal split)
 year  laps  full_dist  full  partial  coast  brake   g8  g1
 2023     5       83.5  74.7      8.9    2.4   12.9 44.5 0.0
 2024     5       83.2  75.4      8.6    3.7   12.4 46.7 0.0
 2025     5       83.0  74.4     10.8    1.5   12.9 46.3 0.0
 2026     5       82.5  74.3     12.0    3.2   12.0 41.0 4.5
  • Every expected value reproduces. Full throttle by distance is 83.5 / 83.2 / 83.0 / 82.5 % and by time 74.7 / 75.4 / 74.4 / 74.3 %. Partial throttle is 8.9 / 8.6 / 10.8 / 12.0 %, and eighth gear takes 44.5 / 46.7 / 46.3 / 41.0 % of the lap. First gear appears only in 2026, at 4.5 %.
  • The other two columns. Coasting stays at 1.5–3.7 % and braking at 12–13 % of lap time in every season.
  • Why full throttle barely moved but partial throttle rose. Monza's long straights are flat-out in any rule set, so the full-throttle share hardly changes. The 2026 cars take the chicanes slower and in a lower gear (first gear appears). They also ramp the throttle in for longer on the exits. That fits Section 23.8's illustrative traction model, in which the speed below which full throttle cannot be used rises from 166 to 183 km/h. That time comes out of the short corner phases, which shows up as partial throttle and does not touch the straights.

C2. Compare these drivers — Las Vegas 2026

Antonelli took pole in 93.893 s and Russell qualified third in 94.224 s. Both fastest laps pass lap_check (longest frozen runs 0.24 s and 0.52 s). We build the sector-anchored corner table, then rerun it with uniform alignment.

ant = telemetry.fastest_lap_telemetry(q, "ANT", with_location=False)
rus = telemetry.fastest_lap_telemetry(q, "RUS", with_location=False)
r = tt.compare_laps(ant, rus, laps, labels=("ANT", "RUS"))          # B-minus-A: RUS minus ANT
cu = tt.corner_table(ant, rus, None, labels=("ANT", "RUS"))         # uniform rescaling
corners found (prominence 20 km/h): 6
 corner speed_class  apex_m_ANT  segment_start_m  segment_end_m  min_speed_kmh_ANT  min_speed_kmh_RUS  brake_later_m  resolved_brake  min_speed_diff  ft_earlier_m  resolved_ft  segment_delta_s  resolution_m
      1        slow     307.188            0.000        934.501              111.0              114.0          5.865           False             3.0         3.764        False           -0.100         9.533
      2        slow    1561.815          934.501       1817.769              104.0              109.0         25.103            True             5.0        12.100         True            0.067         6.506
      3        slow    2073.724         1817.769       2138.322               89.0               96.0          1.773           False             7.0           NaN        False            0.006         9.269
      4        slow    2202.920         2138.322       2700.144               91.0               92.0         -0.409           False             1.0        10.289         True           -0.044         8.600
      5        slow    3197.368         2700.144       4168.980               96.0              100.0         17.897            True             4.0         7.326         True            0.069         5.628
      6        slow    5140.592         4168.980       6150.411               94.0               96.0         71.149            True             2.0       -48.358         True            0.333         8.652
sum of segment deltas +0.331 s; lap delta +0.331 s
top speeds: {'ANT': 351.0, 'RUS': 343.0}
delta trace (RUS - ANT) and speeds through the last segment:
    4000 m  delta -0.051 s  ANT 350.0  RUS 342.4 km/h
    4500 m  delta +0.135 s  ANT 342.6  RUS 328.0 km/h
    5000 m  delta +0.361 s  ANT 262.7  RUS 294.8 km/h
    5140 m  delta +0.073 s  ANT  94.3  RUS  99.8 km/h
    5400 m  delta +0.111 s  ANT 263.4  RUS 264.3 km/h
    5800 m  delta +0.201 s  ANT 326.0  RUS 315.0 km/h
    6150 m  delta +0.331 s  ANT 301.0  RUS 293.2 km/h
 corner  anchored  uniform  brake_anch  brake_unif  diff_s
      1    -0.100   -0.122       5.865       6.176  -0.022
      2     0.067    0.041      25.103      27.913  -0.026
      ...
      6     0.333    0.358      71.149      72.488   0.025
segments outside +/-0.05 s under uniform alignment: [1, 5, 6]
  • Only six corners, all slow (89–111 km/h), as expected for a circuit of long straights. The segments sum exactly to the lap gap, +0.331 s.
  • Four segments fall outside ±0.05 s:
  • C1 (−0.100 s, Russell gains). Russell is 3 km/h faster at the minimum. Neither the braking nor the full-throttle difference is resolved.
  • C2 (+0.067 s). Russell brakes 25 m later and carries 5 km/h more, both resolved, yet loses time over the segment.
  • C5 (+0.069 s). He brakes 18 m later and carries 4 km/h more, both resolved, and again loses time.
  • C6 (+0.333 s). This one segment holds the whole lap gap. It runs from 4,169 m to the line and covers the long straight into the last corner and the run to the flag.
  • What C6 really measures. The delta trace shows the story. Antonelli is 8 km/h faster at the top (351 against 343 km/h), and the gap grows from −0.05 s at 4,000 m to +0.13 s at 4,500 m. The swing to +0.36 s at 5,000 m and back to +0.07 s at the apex is an alignment artefact in the braking zone: Russell reads 295 km/h where Antonelli reads 263. That is the same artefact as the "71 m later" brake point. On the final straight the delta grows again, from +0.07 to +0.33 s, with Antonelli 8–11 km/h faster. The loss is straight-line speed, which in 2026 means energy deployment and drag, not cornering. The archive cannot see the cause, because it has no deployment or aero-mode channel.
  • What survives uniform alignment. Segments 1, 5 and 6 survive. C2 drops to 0.041 s and falls inside the band. Every segment moves by less than 0.05 s between the two alignments, but the C6 brake-point difference stays near 71 m under both. Sector anchoring does not fix this braking zone, so treat that brake point as unmeasured, whatever its "resolved" flag says.
  • Read across the corners. Russell carries a higher minimum speed in all six corners and brakes later in five. That pattern does not show him faster: he lost the lap on the straights. Even the "resolved" brake-point differences come from a distance axis. Chapter 7 found that integrated-distance alignment made the second-fastest qualifier look like the later braker in 73 % of zones, against a non-significant 35.5 % [21–53 %] on the location track line. So before you call Russell the later braker, rebuild these brake points on the qualifying x/y track line.

C4. Predict the race — does a fingerprint predict the next session?

From the saved fingerprint table we take every 2026 pairing with at least six sessions before round 21, predict the sign of d_partial_pct and d_brake_pct at Las Vegas from the earlier median, and score the predictions.

fp = pd.read_csv(".../code/output/ch23_fingerprints.csv")
pre, tgt = f26[f26["round"] < 21], f26[f26["round"] == 21]
for (team, pair), g in pre.groupby(["team_ref", "pair"]):
    hit = np.sign(g[m].median()) == np.sign(t[m].iloc[0])        # for m in d_partial_pct, d_brake_pct
    team    pair  n_before  d_partial_pct_med  d_partial_pct_r21  d_partial_pct_hit  d_brake_pct_med  d_brake_pct_r21  d_brake_pct_hit  gap_pct_r21
  alpine COL-GAS        15              -1.52              -0.38               True            -0.97            -1.14             True        -0.22
    audi BOR-HUL        17              +0.37              +0.65               True            -0.37            +1.46            False        -0.56
 ferrari HAM-LEC        19              +0.70              -2.44              False            -0.40            -1.78             True        -0.06
 mclaren NOR-PIA        19              +1.33              -0.64              False            +0.60            +0.24             True        +0.69
mercedes ANT-RUS        17              -0.46              -1.10               True            +0.18            -1.40            False        +0.35
      rb LAW-LIN        13              -0.19              +0.98              False            +1.45            +1.07             True        -0.44
red_bull HAD-VER        12              -1.75              -0.25               True            -0.33            -0.14             True        -0.47
williams ALB-SAI        14              -1.25              -1.43               True            +0.46            +0.75             True        -0.50
d_partial_pct: sign right 5 of 8 = 62 % [Wilson 31, 86]; one-sided binomial p vs coin = 0.363
d_brake_pct: sign right 6 of 8 = 75 % [Wilson 41, 93]; one-sided binomial p vs coin = 0.145
2026 pairings with >= 6 sessions: |median| vs session-to-session SD, and the share of sessions with the median's sign
               median   sd  same_sign
metric
d_brake_pct      0.46 1.43       0.62
d_partial_pct    0.57 2.30       0.67
  • The result matches the chapter's run: 5 of 8 partial-throttle signs and 6 of 8 brake-on signs were right.
  • Neither beats a coin toss convincingly. The one-sided binomial p-values are 0.36 and 0.15, and both Wilson intervals include 50 %. Eight pairings in one session cannot separate 60–70 % skill from luck.
  • Why a reliable season median can still predict one session badly. Split-half reliability (0.77 for brake-on, 0.64 for partial throttle in 23.7) measures whether the median over half a season repeats. Here a single session is the target, and one session is noisy. In 2026 the typical pairing's session-to-session SD is three to four times the size of its median (brake 1.43 against 0.46 points, partial 2.30 against 0.57), and a single session has the median's sign only about 62–67 % of the time. The median is a stable trait. Any one lap is that trait plus a lot of lap-specific noise: a different run plan, a tow, a scrappy corner, or a different qualifying segment.
  • The example. McLaren's Norris–Piastri pairing (partial median +1.33) is the chapter's most persistent fingerprint, and it still flipped sign at Las Vegas (−0.64).

D3. Driver coaching from a corner table

The chapter's teammate study tells us which of these three signals tends to separate the faster lap from the slower one, and how reliably each repeats. The script recomputes the three Wilson intervals and one illustrative exit calculation.

  faster lap has later median brake point: 373/774 = 48.2 % [44.7, 51.7]
  faster lap has earlier median full throttle: 447/773 = 57.8 % [54.3, 61.3]
  faster lap has higher median minimum speed: 458/664 = 69.0 % [65.4, 72.4]
  assumed exit deficit 3 km/h over 300 m at 200 km/h: dt = L dv / v^2 = 0.081 s per corner; x3 corners = 0.243 s

Priorities, in order:

  1. Corner exits in the three slow corners. Full throttle 20–30 m later, at a resolution of 5–7 m, is the one difference in his table that is clearly resolved. Earlier full throttle goes with the faster lap more often than chance (57.8 %, interval 54.3–61.3 %). Exit speed is also carried down the next straight. As an illustration with stated assumptions, an exit 3 km/h slower carried over 300 m at 200 km/h costs about 0.08 s per corner, or about 0.24 s over three corners. Work on getting the car turned earlier so the throttle can go down sooner.
  2. Minimum speed, as a check rather than a target. He is within ±1 km/h everywhere, and speed is recorded in whole km/h. There is nothing to fix here yet. Minimum speed is still the signal most associated with the faster lap (69.0 %), so watch it while he works on exits: an earlier throttle that costs apex speed is not a gain.
  3. Braking points: ignore them. Differences of 8–15 m sit inside a resolution of 12–20 m, so none of them is measured. Even resolved brake-point differences barely separate faster from slower laps (48.2 %, interval includes 50 %). The brake point is also the least repeatable fingerprint (split-half 0.27). Telling a junior to "brake later" on this evidence risks costing him apex and exit speed for nothing.

What to ignore and why. Ignore any number that is smaller than its resolution, and any single-session difference without a repeat. Confirm the exit pattern on a second session before rebuilding his corner approach around it.

Chapter 24

Chapter 24 — Team Performance Trends · exercises · verification script: appendices/code/answers_part2_ch24.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D5 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

C1. Analyze this session — 2024 Monaco Grand Prix, Qualifying

We take the round from dev.gap_to_fastest(2024) (best of Q1–Q3, faster car) and from the same call with method="q1", then compare ranks.

gb = dev.gap_to_fastest(2024)
gq = dev.gap_to_fastest(2024, method="q1")
T = gb[gb.circuit_ref == "monaco"].merge(gq[gq.circuit_ref == "monaco"], on="team_ref", suffixes=("", "_q1"))
    team_ref  time_s  gap_pct deepest  rank  gap_pct_q1  rank_q1  rank_change
     ferrari  70.270    0.000      Q3     1       0.071        3           -2
     mclaren  70.424    0.219      Q3     2       0.011        2            0
    mercedes  70.543    0.389      Q3     3       0.000        1            2
    red_bull  70.567    0.423      Q3     4       0.306        5           -1
          rb  70.858    0.837      Q3     5       0.410        8           -3
      alpine  70.896    0.891      Q3     6       0.311        6            0
    williams  70.948    0.965      Q3     7       0.183        4            3
        haas  71.440    1.665      Q2     8       0.476        9           -1
aston_martin  71.563    1.840      Q2     9       0.330        7            2
      sauber  72.512    3.191      Q1    10       1.427       10            0
  • The table has 10 rows, as expected. Ferrari is fastest (gap 0.000, Leclerc's pole time 70.270 s) and Red Bull's best-time gap is 0.423 %.
  • Seven of the ten teams change rank. On the like-for-like Q1 measure Mercedes is fastest, Williams rises from 7th to 4th, Aston Martin from 9th to 7th, and RB falls from 5th to 8th.
  • The expected shape holds only partly. The one Q1-eliminated team, Sauber, does not move: it is last on both measures, though its gap shrinks from 3.19 % to 1.43 %. The team that moves up is Aston Martin, which went out in Q2. Haas, also out in Q2, moves down.
  • The general point stands. The best-time measure credits front-runners with the track evolution and the extra push of Q3. The Q1 measure compares everyone on the same track, but in a session where the top teams are not trying to set their best lap. Monaco's Q1 order is noisy, which is why the Q1 gaps of the top seven fall within 0.41 %.

C2. Compare these drivers — Aston Martin 2026, Alonso and Stroll

For each dry 2026 round we compute each driver's own best time against the fastest team's best, then run dev.change_points() on each series. The chapter's team change point is found on the circuit-adjusted gap, so we also subtract the team's circuit-type effect from each driver's series.

q["gap_pct"] = 100 * (q.best / q["round"].map(fastest_team_time) - 1)    # best = min(Q1, Q2, Q3) per driver
W["alonso_adj"] = W.alonso - team.type_effect                             # same adjustment as gap_adj
dev.change_points(W[col].dropna().to_numpy())                             # 999 permutations, seed 42
       alonso  stroll  race_idx    circuit_ref  team_gap  team_gap_adj  alonso_adj  stroll_adj
round
1       4.395     NaN         1    albert_park     4.395         3.610       3.610         NaN
...
13      4.113   4.201        13          monza     4.113         3.328       3.328       3.416
14      3.881     NaN        14        madring     3.881         4.500       4.500         NaN
15      3.967   4.692        15           baku     3.967         4.586       4.586       5.311
16      2.197   2.561        16         sepang     2.197         2.816       2.816       3.179
17      3.119   3.910        17     marina_bay     3.119         3.166       3.166       3.958
18      1.896   2.810        18       americas     1.896         2.515       2.515       3.428
19      3.129   3.343        19      rodriguez     3.129         3.748       3.748       3.962
21      3.735   3.895        20          vegas     3.735         2.950       2.950       3.110
alonso        n = 20: change at round 7 (catalunya), 4.017 -> 5.578 (shift +1.561 pp), p = 0.014
alonso        n = 20: change at round 11 (hungaroring), 4.642 -> 3.290 (shift -1.352 pp), p = 0.017
stroll        n = 18: change at round 12 (zandvoort), 5.065 -> 3.643 (shift -1.422 pp), p = 0.007
team_gap      n = 20: change at round 7 (catalunya), 4.017 -> 5.513 (shift +1.496 pp), p = 0.014
team_gap      n = 20: change at round 11 (hungaroring), 4.616 -> 3.290 (shift -1.326 pp), p = 0.019
team_gap_adj  n = 20: change at round 16 (sepang), 4.258 -> 3.039 (shift -1.219 pp), p = 0.004
alonso_adj    n = 20: change at round 16 (sepang), 4.275 -> 3.039 (shift -1.236 pp), p = 0.005
stroll_adj    n = 18: change at round 16 (sepang), 4.794 -> 3.527 (shift -1.266 pp), p = 0.016
rounds in which each driver set the team's best: {'alonso': 18, 'stroll': 2}
  • The series. Alonso has 20 values and Stroll 18: Stroll has no time at rounds 1 and 14, and wet round 20 is excluded. Alonso set the team's best in 18 of the 20 rounds, so the team gap is almost his series.
  • On the circuit-adjusted gaps, both drivers shift at Sepang (round 16). Alonso moves −1.24 pp (p = 0.005) and Stroll −1.27 pp (p = 0.016), the same size as the team's −1.22 pp. A shift of the same size, at the same round, for both cars is what a car change looks like, not one driver's form.
  • On the raw gaps the story changes. The detector instead finds a rise at Barcelona (round 7) and a fall at Hungary (round 11) for Alonso and the team, and a fall at Zandvoort (round 12) for Stroll. The raw series mix circuit type into the gap: Aston Martin is +1.07 pp worse at high-speed circuits. Rounds 7–10 (Barcelona, Red Bull Ring, Silverstone, Spa) are four high-speed circuits in a row, followed by two medium-speed ones (Hungary, Zandvoort). That sequence alone creates a rise and a fall with nothing to do with development.
  • The lesson. The location of a change point depends on the adjustment. Here, the adjusted series for both drivers agree with each other and with the team. That agreement is the evidence. The exercise's test, whether the shift shows in both cars, is passed only after the circuit control.

C3. Build the strategy — window sensitivity

We project every 2026 team's gap one race ahead, to Qatar (a high-speed circuit in the Chapter 10 types), with window = 3, 5 and 8, and mark each team's most recent change point.

for t in teams:
    for w in (3, 5, 8):
        dev.project_gap(g, t, 2026, races_ahead=1, window=w, circuit_type_next=dev.circuit_type("losail"))
    team_ref     w3    w5  ci_low  ci_high     w8  range_pp  change_point_round
    mercedes -0.062 0.006  -0.074    0.453 -0.028     0.068                 NaN
    red_bull  0.246 0.246   0.047    0.481  0.267     0.021                 NaN
     ferrari  0.381 0.395   0.205    1.222  0.404     0.024                 NaN
     mclaren  0.438 0.438   0.295    0.818  0.400     0.038                 NaN
          rb  0.503 0.589   0.201    1.520  0.686     0.183              17.000
        audi  0.931 0.931   0.769    1.650  1.095     0.165                 NaN
      alpine  0.832 1.015   0.666    1.343  1.062     0.229              13.000
        haas  1.978 1.978   1.137    2.851  1.942     0.036                 NaN
    williams  2.379 2.379   1.792    2.681  2.327     0.052                 NaN
    cadillac  3.318 3.363   3.088    3.931  3.524     0.206                 NaN
aston_martin  3.678 3.678   3.246    4.490  3.975     0.297              16.000
teams moving > 0.2 pp across windows: ['alpine', 'cadillac', 'aston_martin']
  • The window-5 column reproduces the checkpoint, including Aston Martin at 3.678 % and Mercedes at 0.006 %.
  • Three teams move by more than 0.2 pp across windows: Aston Martin (0.297), Alpine (0.229) and Cadillac (0.206). RB (0.183) and Audi (0.165) are just under the line.
  • Teams with a recent change point are Aston Martin (round 16), RB (round 17) and Alpine (round 13). For these, use a window that stays inside the new level.
  • Aston Martin has five dry rounds since its change point (16, 17, 18, 19 and 21). With window = 8 the projection reaches back to the slower car and rises to 3.975 %. Window 5 (3.678 %) or 3 is right.
  • RB has four rounds since round 17, so use window = 3 or 4.
  • Alpine's change came eight dry rounds ago (round 13), so even window = 8 stays inside the new level. Its 0.23 pp spread across windows is within the ordinary race-to-race noise (residual SD about 0.46 pp).
  • Teams without one. A longer window averages more noise away. Window = 8 is defensible for Mercedes, Red Bull, Ferrari, McLaren, Haas and Williams, whose projections barely move (≤ 0.07 pp).
  • Cadillac is the exception. It has no change point, but its projection drifts with the window (3.32 → 3.52 %) because the longer window includes its slower early rounds. That is a steady trend rather than a step, and the development rate already carries it.

C4. Predict the race — 2026 Qatar qualifying order

We order the teams by their window-5 projection and flag adjacent pairs whose 95 % intervals overlap.

P = P.sort_values("w5")
overlap = P.ci_high.iloc[i] >= P.ci_low.iloc[i + 1]
   1. mercedes      0.006 [-0.074,  0.453]  vs  red_bull      0.246 [ 0.047,  0.481]  -> too close to call
   2. red_bull      0.246 [ 0.047,  0.481]  vs  ferrari       0.395 [ 0.205,  1.222]  -> too close to call
   3. ferrari       0.395 [ 0.205,  1.222]  vs  mclaren       0.438 [ 0.295,  0.818]  -> too close to call
   4. mclaren       0.438 [ 0.295,  0.818]  vs  rb            0.589 [ 0.201,  1.520]  -> too close to call
   5. rb            0.589 [ 0.201,  1.520]  vs  audi          0.931 [ 0.769,  1.650]  -> too close to call
   6. audi          0.931 [ 0.769,  1.650]  vs  alpine        1.015 [ 0.666,  1.343]  -> too close to call
   7. alpine        1.015 [ 0.666,  1.343]  vs  haas          1.978 [ 1.137,  2.851]  -> too close to call
   8. haas          1.978 [ 1.137,  2.851]  vs  williams      2.379 [ 1.792,  2.681]  -> too close to call
   9. williams      2.379 [ 1.792,  2.681]  vs  cadillac      3.363 [ 3.088,  3.931]  -> distinguishable
  10. cadillac      3.363 [ 3.088,  3.931]  vs  aston_martin  3.678 [ 3.246,  4.490]  -> too close to call
  11. aston_martin  3.678 [ 3.246,  4.490]
distinguishable adjacent pairs: 1 of 10
  • The predicted order matches the expected list: Mercedes, Red Bull, Ferrari, McLaren, RB, Audi, Alpine, Haas, Williams, Cadillac, Aston Martin.
  • Only 1 of the 10 adjacent pairs is distinguishable by non-overlapping intervals: Williams ahead of Cadillac. The model is confident about groups (a front four, a midfield of RB/Audi/Alpine, then Haas and Williams, and two cars at the back) but not about the order inside them.
  • Overlap is a conservative test. Two intervals can overlap while their difference is still distinguishable from zero. A sharper version would bootstrap the difference for each pair. With intervals this wide (Ferrari's runs to 1.22 %), few pairs would change.
  • No check is possible yet. Qatar is not in the data snapshot, so this is a forecast with no result to compare against.

Chapter 25

Chapter 25 — F1 Data Visualization · exercises · verification script: appendices/code/answers_part2_ch25.py

Worked in the chapter. B1–B8 (all of Part B), D1, D2 and D4 have full solutions or guidance in the exercises file; open the Solution, Reveal or Guidance blocks there. The script draws the figures the exercises ask for but does not save them; the answers below check the numbers that go on them.

C1. Analyze this session: 2024 Japanese GP, race

We list who led each lap by position_end, then measure the winner's two pursuers with viz.pair_gaps. Laps 1–2 are excluded because of the lap-1 red flag, and so are the in-laps and out-laps of the three cars.

lp = f1data.laps(s)
leaders = lp[lp.position_end == 1].groupby("lap_number").acronym.first()
gaps = viz.pair_gaps(s, win, [p2, p3])                      # gap to the winner, not to the leader
rac = g[(g.index >= 3) & ~g.index.isin(stop_laps)]          # stop_laps = in-laps and out-laps of VER/PER/SAI
  leader VER: laps 2-16
  leader LEC: laps 17-20
  leader VER: laps 21-34
  leader SAI: laps 35-35
  leader VER: laps 36-53
in-laps of the three cars: [1, 1, 1, 15, 15, 16, 33, 34, 36]
PER gap to VER, laps 3+ excluding in/out-laps: min 0.930 (lap 3), median 8.744, max 13.052, n 43
   same from lap 4 (after the standing-restart lap): min 1.064 (lap 4)
SAI gap to VER, laps 3+ excluding in/out-laps: min 2.195 (lap 3), median 15.380, max 21.260, n 43
   same from lap 4 (after the standing-restart lap): min 3.092 (lap 4)
  • When the leader was not the winner. Verstappen won, but the car leading at the line was Leclerc on laps 17–20 and Sainz on lap 35. Both runs fall inside stop cycles. On those five laps a gap-to-leader chart bends every line, including Verstappen's own, without any car gaining time on track.
  • P2 to the winner. Pérez's gap to Verstappen on racing laps was a minimum of 0.930 s, a median of 8.744 s and a maximum of 13.052 s (43 laps). The minimum falls on lap 3, the standing-restart lap, when the field was still bunched. From lap 4 it is 1.064 s. Put that choice in the source line next to "laps 1–2 excluded (lap-1 red flag)".
  • The stop window. The three cars' in-laps run from lap 15 to lap 36, so this race has no single grey stop band like Suzuka 2025's. Mark each car's in-laps on its own line instead.

C2. Compare these drivers: Piastri vs Leclerc, 2025 Japanese GP qualifying

Both fastest laps pass quality_check. We build the sector-anchored delta and count the same three things as Figure 25.7b.

d = laptime.delta_trace(pia, lec, laps=laps, align="sectors")
inside = (d.delta_s.abs() <= 0.05).mean()
sgn = np.sign(d.delta_s[d.delta_s.abs() > 0.005])
n_cross = int((sgn.diff().abs() > 0).sum())
PIA 87.027 {'frozen_s': 0.0, 'max_gap_s': 1.04, 'dist_ratio': 0.9957, 'ok': True}
LEC 87.299 {'frozen_s': np.float64(0.28), 'max_gap_s': 1.2, 'dist_ratio': 0.9952, 'ok': True}
delta LEC - PIA: end +0.272 s, max +0.276 at 5645 m, min -0.261 at 1250 m
share of the lap where |delta| <= 0.05 s: 22.2%
sign changes of the delta (|delta| > 0.005 s): 1
stretches with |delta| > 0.05: 901 of 1158 grid points; ranges (m): [(390, 2440), (2905, 2910), (2970, 3600), (3930, 5240), (5280, 5320), (5330, 5340), (5360, 5782)]
  • The three printed numbers. Only 22.2% of the trace lies inside ±0.05 s. The lead changed hands once. The delta is outside the band for most of the lap: 390–2,440 m, then almost continuously from 2,970 m to the line.
  • A title. "Leclerc led until about the hairpin, Piastri took 0.27 s after it: the lead changed hands once; 22% of the lap inside the noise band." (The trace is −0.033 s at 2,500 m and +0.070 s at 3,000 m; the hairpin is near 2,900 m.)
  • How this differs from Anchor A. The VER–NOR pair (0.012 s) changed hands 8 times with 65.1% inside the band. A 0.272 s gap is large enough that most of the trace is signal.
  • Check against the timing. Leclerc's official S1 was 0.090 s quicker (30.535 against 30.625 s), and the anchored trace passes through −0.090 s at the first sector line by construction. Inside S1 the trace dips further, to −0.261 s at 1,250 m. That stretch is between anchors, so treat the depth of the dip, but not its sign, with the alignment caution of Chapter 19.

C3. Audit a palette: VER, TSU, LAW, HAD, GAS

We take the 2025 Japanese GP driver styles and pass the five colours to viz.palette_report.

sty = plots.driver_styles(s)
per, pairs = viz.palette_report({a: sty[a]["color"] for a in ["VER", "TSU", "LAW", "HAD", "GAS"]})
{'VER': 'red_bull', 'TSU': 'red_bull', 'LAW': 'rb', 'HAD': 'rb', 'GAS': 'alpine'}
name     hex  contrast  contrast_ok
 VER #3671C6      4.85         True
 TSU #3671C6      4.85         True
 LAW #6692FF      2.95        False
 HAD #6692FF      2.95        False
 GAS #0093CC      3.47         True
  a   b  dE_normal  dE_worst       verdict
VER TSU        0.0       0.0      collides
LAW HAD        0.0       0.0      collides
HAD GAS       10.2       7.3 needs 2nd cue
LAW GAS       10.2       7.3 needs 2nd cue
TSU GAS        9.2       8.5 needs 2nd cue
...
TSU HAD       13.0      12.4 needs 2nd cue
line styles from driver_styles: {'VER': '-', 'TSU': '--', 'LAW': '--', 'HAD': '-', 'GAS': '--'}
darken LAW: #6692FF -> #6590FD
darken HAD: #6692FF -> #6590FD
  • Two pairs collide, not one. At Suzuka 2025 Tsunoda drove for Red Bull and Lawson and Hadjar for Racing Bulls (rb). So VER–TSU and LAW–HAD share a team colour, and both pairs have ΔE = 0 by construction, before you run anything.
  • Every other pair needs a second cue. All five colours are blues, so the worst-case ΔE of the remaining eight pairs runs from 7.3 to 12.4, and none reaches "ok".
  • Contrast. The Racing Bulls blue fails 3:1 on white at 2.95:1. darken_to_contrast needs only a tiny shift (#6590FD).
  • A set of cues that separates all five.
  • Line style within each team, as driver_styles already does: VER solid, TSU dashed; HAD solid, LAW dashed.
  • A marker for each team, because line style alone leaves VER and HAD both solid and TSU, LAW and GAS all dashed: no marker for Red Bull, circles for Racing Bulls, squares for Alpine.
  • Direct labels at the line ends for all five.
  • The darkened Racing Bulls colour on white backgrounds.
  • Or change the chart. A five-blue chart is a warning sign. If the story is about one or two of these drivers, focus-and-context (grey for the rest) is simpler than five cues.

C5. Predict the race: starting P1 in two eras

We take every Jolpica start from the first grid slot (actual grid) and score a car that did not finish as its own bin. "Finished" here is Jolpica's finished flag, which counts lapped cars as finishers. We do not use is_classified, which is True for some late retirements.

r = r[r.grid == 1]
pos = np.where(r.finished.astype(bool) & r.position.notna(), r.position, 21).astype(float)
fig = viz.outcome_hist(out, discrete=True, labels={21: "DNF"}, xlabel="Finishing position (21 = DNF)")
2014-19: n 121, win 63 (52.1%), podium 101 (83.5%), not finished 9 (7.4%, 95% CI 4.0-13.5)
   (not classified by is_classified: 9)
2022-26: n 113, win 66 (58.4%), podium 92 (81.4%), not finished 9 (8.0%, 95% CI 4.2-14.4)
   (not classified by is_classified: 8)
 series   n  q10  q50  q90  mean
2014-19 121  1.0  1.0  6.0  3.31
2022-26 113  1.0  1.0  6.0  3.40
all entries 2022-25 not finished: 13.8% (n 1838)
  starters only (no DNS/withdrawn): 242/1826 = 13.3%
  starters, disqualified counted as running to the flag: 232/1826 = 12.7%
grid-1 non-finishers 2022-26 by status: {'Retired': 3, 'Disqualified': 2, 'Power Unit': 1, 'Turbo': 1, 'Collision damage': 1, 'Accident': 1}
  • The DNF bars are the same height. Nine pole-sitters failed to finish in each era: 7.4% in 2014–19 and 8.0% in 2022–26 (2026 after 21 rounds). The intervals, 4.0–13.5% and 4.2–14.4%, overlap almost completely. If you predicted a clearly larger bar for the early hybrid era, the data do not support it.
  • Wins and podiums. The pole-sitter won 52.1% against 58.4% and made the podium 83.5% against 81.4%. The two histograms are nearly identical: median finish 1, 90th percentile 6.
  • Against the field rate. The book's figure is 12.8% of all starters in 2022–25. Pole-sitters fail to finish at well under that, about 8%. They start ahead of the lap-1 accidents, and the cars at the front are the most reliable.
  • Why recomputing the field rate gives 12.7–13.8%. The answer depends on who counts as a starter and how a disqualification is scored. Dropping non-starters and counting the disqualified as having run to the flag gives 232/1,826 = 12.7%, within one car of the book's 233/1,827.
  • The is_classified trap. Two of the nine 2022–26 grid-1 non-finishers were disqualified, and is_classified marks one fewer car "not classified" than finished does (8 against 9).

D3. The honesty audit

We audit Chapter 19's alignment figure (ch19-fig-07-anchor-a-alignment.png). It draws Norris's gap to Verstappen on the 2025 Suzuka pole laps twice, once with uniform distance rescaling and once anchored at the official sector lines. The script recomputes both traces and checks the two line colours.

uniform : min -0.258 at 2900 m, end +0.012, share inside +/-0.05 s 47.8%
sectors : min -0.175 at 2890 m, end +0.012, share inside +/-0.05 s 65.1%
              name     hex  contrast  contrast_ok
  uniform (orange) #EB6834      3.20         True
   anchored (blue) #2A78D6      4.42         True
                 a               b  dE_normal  dE_worst verdict
  uniform (orange) anchored (blue)       33.6      24.7      ok

Going down the chapter's seven-item checklist:

  1. Question and title. The title states a finding ("the spike at the hairpin is an artefact of integrated distance") but carries no number. Adding "−0.258 s becomes −0.175 s" would let a two-second reader take the size away too.
  2. Reference. Fixed and named on the axis ("NOR gap to VER").
  3. Zero and outliers. No bars. The zero line is drawn, and the hairpin spike, the "outlier", is annotated rather than clipped.
  4. Palette. Both colours pass 3:1 on white (3.20:1 and 4.42:1), and the pair is ΔE 24.7 apart even in the worst CVD simulation.
  5. Greyscale and deuteranopia. The pair survives the deuteranopia simulation (ΔE 24.7). But the two lines differ only in colour and slightly in width (1.3 against 1.6), not in style. A dashed uniform trace would keep them apart in greyscale without relying on colour at all.
  6. Data limits. This is the main gap. The figure has no ±0.05 s noise band. With the band drawn, the reader would see that 52% of the uniform trace, against 35% of the anchored one, sits outside it. That is the figure's whole point, made visible.
  7. Source and description. It has a source line and a described-figure paragraph.

Review for the author. This is an honest teaching chart. It shows the toolkit's own default next to the corrected method, it annotates the artefact instead of hiding it, and the physics in the annotation ("77 km/h, so a few metres of misalignment = tenths") explains the cause. Two changes would make it publication-grade: put the numbers in the title, and add Chapter 19's ±0.05 s band so that the reader can see how much of each trace is resolvable at all. A dashed uniform line would make it safe in greyscale.

Chapter 26

Chapter 26 — Predictive Modeling for F1 · exercises · verification script: appendices/code/answers_part2_ch26.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D4 (all of Part D) have full solutions or sample answers in the exercises file; open the Solution, What happened or Sample answer blocks there. The answers below read the chapter's cached feature table and walk-forward predictions (code/features_2006_2026.parquet and code/walkforward_predictions.parquet). Run 01_baselines.py and 03_race_models.py first if they are missing. Every model is walk-forward by season: trained on 2006 to Y − 1, tested on Y.

C1. Analyze this session: the 2025 Mexico City GP

We take round 20 of 2025 from the walk-forward predictions, put the gradient-boosting model next to the grid-slot baseline, and score both with predict.score(..., by=None).

g = WF[(WF.year == 2025) & (WF["round"] == 20)]
m = g[g.model == "gbm"]; b = g[g.model == "grid"]
predict.score(g[g.model == "gbm"], by=None); predict.score(g[g.model == "grid"], by=None)
round 20 Mexico City Grand Prix
abbreviation  grid  p_win  p_win_grid  p_podium  p_pod_grid  pos
         NOR   1.0  0.523       0.505     0.793       0.793  1.0
         LEC   2.0  0.204       0.248     0.527       0.668  2.0
         VER   5.0  0.172       0.022     0.402       0.200  3.0
         RUS   4.0  0.058       0.043     0.412       0.343  7.0
         HAM   3.0  0.022       0.097     0.388       0.518  8.0
         PIA   7.0  0.005       0.009     0.224       0.078  5.0
         ...   (6 rows: ALO, SAI, ANT, HAD, ALB, TSU, each p_win <= 0.003)
         BEA   9.0  0.001       0.004     0.012       0.036  4.0
         ...   (7 more rows, each p_win <= 0.001)
  gbm   Brier 0.303  winner log loss 0.649  (p(winner) = 0.523)
  grid  Brier 0.320  winner log loss 0.684  (p(winner) = 0.505)
  • The table. It has 20 rows. Norris won from pole, ahead of Leclerc (grid 2) and Verstappen (grid 5).
  • The scores. The model beats the grid table on this race: Brier 0.303 against 0.320, and winner log loss 0.649 against 0.684.
  • The departures from the grid table were in the right direction.
  • The model raised Verstappen from 2.2% to 17.2% to win and from 20.0% to 40.2% for a podium, and he finished third.
  • It cut Hamilton (grid 3) from 9.7% to 2.2% to win and from 51.8% to 38.8% for a podium, and he finished eighth.
  • It gave the winner, Norris, slightly more (52.3% against 50.5%).
  • Where it missed. Bearman, who finished fourth from ninth on the grid, got 1.2% for a podium, below the grid table's 3.6%. One race is one draw, so treat this as an illustration, not evidence.

C2. Compare these drivers: Hamilton vs Leclerc, 2026 qualifying

We refit 04_qualifying_forecast.py's gradient-boosting model for the 2026 test season (trained on 2006–2025, the same walk-forward fit the script makes) and keep its predictions. Predicted rank is the rank of the predicted gap within each round.

gbm.fit(tr[q4.QFEAT], tr.quali_gap_pct)                         # tr = 2006-2025
te["pred_rank"] = te.groupby("round").gbm.rank(method="first")
te["act_rank"] = te.groupby("round").quali_pos.rank(method="first")
right = (w.gbm.HAM < w.gbm.LEC) == (w.quali_pos.HAM < w.quali_pos.LEC)
  HAM: rounds 21, MAE |pred - actual| 2.86 places, median predicted rank 6, median actual 5
  LEC: rounds 21, MAE |pred - actual| 2.38 places, median predicted rank 5, median actual 4
  model ordered the pair correctly in 12 of 21 rounds = 0.571
  model put HAM ahead in 4 rounds; HAM actually ahead in 9
  • The two MAE values. 2.86 places for Hamilton and 2.38 for Leclerc. Both are below the model's all-driver MAE of 2.87 for 2014–2026, but they are still nearly three places off on a typical Saturday.
  • The share. The model ordered the pair correctly in 12 of 21 rounds, 0.571.
  • That is no better than a constant rule. The model put Leclerc ahead in 17 of 21 rounds. Leclerc actually out-qualified Hamilton in 12 of 21, so "always pick Leclerc" also scores 12 of 21.
  • Why it cannot do better. Chapter 21 measured the pair's median 2026 qualifying gap at 0.047% of a lap, a few hundredths of a second. The model's features (team pace, Elo, the trailing teammate gap) are the same for both drivers or move slowly. At a gap that small, the order on a given Saturday is close to a coin toss, and no pre-weekend feature can call it.

C3. Predict the race with fewer features

We run the logistic model walk-forward on three features and score it on the same 273 races as the 15-feature model. The paired bootstrap is over races (2,000 resamples, seed 42).

p3 = predict.walk_forward(F, "logit", ["grid", "team_gap_trail", "pts_share"], range(2014, 2027))
s3 = predict.score(p3, by=None)
d = s3.set_index(["year", "round"]).logloss - sl.set_index(["year", "round"]).logloss
  grid-slot baseline                 top1 0.549  podium 0.687  Brier 0.637  logloss 1.439  (n races 273)
  logit, 15 features                 top1 0.582  podium 0.683  Brier 0.602  logloss 1.292  (n races 273)
  logit, 3 features                  top1 0.542  podium 0.692  Brier 0.621  logloss 1.362  (n races 273)
  log-loss gain over grid: full 0.147, three features 0.077 = 52% of the full model's gain
  paired bootstrap, 3-feature minus 15-feature log loss: +0.070 [+0.006, +0.141]
  • The pooled line. Top-1 0.542, podium 0.692, Brier 0.621, log loss 1.362.
  • How much of the gain three features recover. The full model improves log loss over the grid baseline by 0.147 (1.439 → 1.292). Three features recover 0.077 of it, 52%.
  • The other twelve features matter, a little. The paired difference is +0.070 [+0.006, +0.141]. It excludes zero, but only just at the lower end, and the point estimate is smaller than the exercises' ±0.1 rule of thumb. Call it "modest, and probably real".
  • Top-1 tells a different story. The three-feature model picks the winner less often than the pole-sitter rule (0.542 against 0.557). It improves the probabilities, not the pick. This is why the chapter scores with log loss and Brier, not top-1 alone.

C8. The extreme leak

We add team_pos_today, the best finishing position of the driver's team in this race, and rerun the gradient-boosting walk-forward on the same 273 races.

fl["team_pos_today"] = fl.pos.groupby([fl.year, fl["round"], fl.team_ref]).transform("min")
pl = predict.walk_forward(fl, "gbm", predict.FEATURES_RACE + ["team_pos_today"], range(2014, 2027))
  gbm, honest (15 features)          top1 0.549  podium 0.680  Brier 0.605  logloss 1.304  (n races 273)
  gbm + team_pos_today               top1 0.784  podium 0.807  Brier 0.308  logloss 0.476  (n races 273)
  • The result. Top-1 jumps from 0.549 to 0.784, the Brier score halves (0.605 → 0.308), and log loss falls from 1.304 to 0.476. This is far above anything honest; the pole-sitter pick scores 0.557.
  • Why it is still not 100%. The feature says which team won, not which of its two drivers.
  • Why a subtle leak is more dangerous. A leak this big announces itself, because no one believes a 78% winner pick. The centred team trend of Section 26.5 moved log loss by only 0.062. That looks like an ordinary modelling gain, survives walk-forward validation and passes every sanity check, so it gets published.

Chapter 27

Chapter 27 — Monte Carlo Race Simulation · exercises · verification script: appendices/code/answers_part2_ch27.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D4 (all of Part D) have full solutions or discussions in the exercises file; open the Solution, Discussion or Model answer blocks there. The answers below import the chapter's code/_common.py and read its caches. Run 01_engine_ingredients.py (and case_study_02.py, for C8) first if they are missing. Every simulation is seeded with seed 42.

C1. Analyze this session: the hazard at Monza

We compute Monza's circuit multiplier from the chapter's race summary and turn it into P(≥ 1 incident) for a 53-lap race with the book's phase hazards.

S = cm.load_summary()
km = nz.circuit_multiplier("monza", nz.HAZARD_2023_26, S)
k = float(km["k_pooled"][0])
nz.p_at_least_one(nz.HAZARD_2023_26, 53, k)
monza {'circuit': 'monza', 'races_rc': 4, 'obs_rc': 2, 'exp_rc': np.float64(4.78), 'k_rc': (0.4184012886759691, np.float64(0.05067033713603586), np.float64(1.5114093152285433)), 'races_det': 15, 'obs_det': 15, 'exp_det': np.float64(17.921), 'k_pooled': (0.7488590911493667, np.float64(0.4362380169157267), np.float64(1.1989959480514958))}
  monza: k = 0.75; P(>= 1 incident in 53 laps) = 0.60
...
  marina_bay: k = 1.33; P(>= 1 incident in 62 laps) = 0.84
 year  incidents  sc  vsc  red
 2023          0   0    0    0
 ...
 2026          2   1    1    1
  • k reproduces Chapter 14: 0.75 (0.44–1.20). It pools two sources: race control 2023–26 (2 incidents against 4.78 expected, k = 0.42) and the lap-time detector for earlier seasons (15 against 17.9).
  • P(≥ 1 incident) is 0.60 for a 53-lap Monza race, against 0.84 for Singapore, as expected.
  • What the low number rests on. Monza had no neutralisation at all in 2023–25. Both of its race-control incidents came in 2026 (an SC and a VSC, plus a red flag). That is why the race-control k alone (0.42) has an interval from 0.05 to 1.51, and why pooling with the longer detector record matters.

C2. Build the strategy: Anchor C at the Hungaroring

We copy _common.singapore_inputs() for the four 2023–26 Hungarian GPs: the same fixed-effects tyre model, stint caps at the 95th percentile, the green stop pool (all four seasons, since the pit-lane rules did not change there), the SC/VSC ratio pools and Hungary's k. Then we run the same ghost comparison.

fe = smf.ols('lap_duration ~ C(yr):lap_number + C(compound, Treatment("MEDIUM")) + C(compound):age + C(dr)',
             data=D).fit(cov_type="cluster", cov_kwds={"groups": D.dr})
T = mc.decision_table(ty, 70, P, max_stops=2)
setup = mc.ghost_setup(70, ty, green, cm.ratio_pools(), nz.sc_hazard(k=k), cm.library(), POL,
                       decide_ratio={"SC": 0.632, "VSC": 0.771}, truth_draws=True)
r = mc.run_many(setup, 10_000, seed=42)
Hungaroring [2023, 2024, 2025, 2026]: FE model on 4,914 clean laps; race laps 70
  SOFT   deg 0.0473 s/lap (SE 0.0107)  offset vs MEDIUM +0.040 s  cap 31
  MEDIUM deg 0.0560 s/lap (SE 0.0047)  offset vs MEDIUM +0.000 s  cap 39
  HARD   deg 0.0677 s/lap (SE 0.0040)  offset vs MEDIUM -0.116 s  cap 41
  lap-number slopes: {'2023': -0.0492, '2024': -0.0436, '2025': -0.0552, '2026': -0.0473}
  green stop pool 2023-26: n = 141, median 21.144 s, mean 21.610 s
  k = 0.52; P(>= 1 incident in 70 laps) = 0.55
  critical deg for the first extra stop d* = 12 x 21.144 / 70^2 = 0.0518 s/lap (model wear 0.047-0.068)
  clean race one : start SOFT, stops [(31, 'MEDIUM')], tyre + pit cost 85.90 s
  clean race two : start SOFT, stops [(25, 'HARD'), (45, 'SOFT')], tyre + pit cost 83.22 s
  clean race flex: start SOFT, stops [(25, 'HARD'), (45, 'SOFT')], tyre + pit cost 83.22 s
  clean race: two-stop minus one-stop = -2.68 s
  10,000 races, seed 42: any incident 56.0%; E[two - one] -2.28 (-2.43 to -2.13), P(two better) 62.9%; E[flex - one] -2.28 (-2.43 to -2.13), P(flex better/equal/worse) 62.9%/0.0%/37.1%
  deg x 1.5: E[two - one] -13.79 s, P(two better) 96.3% (5,000 races)
  deg x 2.0: E[two - one] -25.54 s, P(two better) 99.4% (5,000 races)
  real 2023: stops per finisher {2: 17}
  real 2024: stops per finisher {1: 1, 2: 16, 3: 2}
  real 2025: stops per finisher {1: 10, 2: 9}
  real 2026: stops per finisher {1: 2, 2: 12, 3: 5}
  • Check the critical degradation first. For the first extra stop, d = 12 × 21.144 / 70² = 0.0518 s/lap. The fixed-effects wear rates straddle it: SOFT 0.047, MEDIUM 0.056 and HARD 0.068. Singapore's wear sat well below its d of 0.0745. Hungary has 70 laps, a cheap stop (21.1 s against Singapore's 23.9 s) and higher wear, so all three push towards two stops.
  • The answer flips.
  • In the clean race the two-stop (SOFT, then HARD on lap 25, then SOFT on lap 45) is 2.68 s faster than the best one-stop.
  • Over 10,000 simulated races it is 2.28 s faster on average (−2.43 to −2.13) and faster in 62.9% of them.
  • The flexible policy, capped at two stops, simply plans the two-stop from the start, so it gives the same numbers.
  • With wear 1.5 times higher, the two-stop wins 96.3% of the time.
  • The real races agree, mostly. Two stops was the majority choice in 2023, 2024 and 2026, and 2025 split 10 one-stops to 9 two-stops.
  • Hazard plays almost no part. Hungary's k is only 0.52 (P(≥ 1 incident) = 0.55), so the answer comes from tyres and pit loss, not from safety cars.
  • One oddity to report. The model makes HARD the fastest-wearing compound. This fixed-effects fit pools four seasons of very different compound allocations and absorbs fuel and track evolution into year-specific lap slopes. The book's circuit table (default fuel correction, a different method) also puts HARD highest at Hungary, at 0.076 s/lap. Treat the compound ordering as uncertain, but the overall level is what decides the stop count.

C4. Convergence for a probability: Verstappen's P(win)

We rebuild the chapter's Singapore field (_common.singapore_field(): real grid, 2026 race pace, passing calibrated to 29.5 passes per race), run the same three-policy comparison for Verstappen so the one-stop run is the chapter's, and track the running P(win) of his one-stop.

setup, sk = cm.singapore_field()
tab, rr = mc.compare_strategies(setup, "VER", POL, n_sims=10_000, seed=42)
win = (rr["one-stop"].position[:, i] == 1).astype(float)
p = win[:n].mean(); se = np.sqrt(p * (1 - p) / n)
  policy  mean_pos  p_win  p_podium  exp_points
one-stop     4.803  0.517     0.768      17.839
two-stop     6.755  0.150     0.456      11.714
flexible     4.930  0.511     0.754      17.569
  n =    100: P(win) 0.560  +/- 0.097  [0.463, 0.657]
  n =    300: P(win) 0.537  +/- 0.056  [0.480, 0.593]
  n =  1,000: P(win) 0.508  +/- 0.031  [0.477, 0.539]
  n =  3,000: P(win) 0.511  +/- 0.018  [0.493, 0.529]
  n = 10,000: P(win) 0.517  +/- 0.010  [0.507, 0.527]
  • The final estimate reproduces the chapter: P(win) = 0.517 for the one-stop, with the same table rows.
  • The band matches the expected shape: ±0.031 at n = 1,000 and ±0.010 at n = 10,000. It shrinks as 1/√n, about √10 ≈ 3.2 times narrower for ten times the races.
  • Early estimates wander. After 100 races the estimate is 0.560, four points high. That is still inside its ±0.097 band, which is why the band belongs on the convergence plot.
  • Two strategies can share a band. The flexible option's 0.511 sits inside the one-stop's 10,000-race band. Whether they differ is a paired question (A2): ask how often the two policies give Verstappen different results in the same race.

C8. Calibration by grid slot

We read Case Study 2's season file and group the 329 driver-races by grid slot.

d["slot"] = pd.cut(d.grid, [0, 1, 3, 6, 10, 99], labels=["1", "2-3", "4-6", "7-10", "11+"])
t = d.groupby("slot").agg(n=("code", "size"), sim_p_win=("p_win", "mean"), obs_win=("won", "mean"),
                          sim_p_podium=("p_podium", "mean"), obs_podium=("pod", "mean"))
15 races, 329 driver-races
        n  sim_p_win  obs_win  wins  sim_p_podium  obs_podium  podiums  grid_base_win
slot
1      15      0.390    0.667    10         0.683       0.867       13          0.536
2-3    30      0.159    0.100     3         0.482       0.400       12          0.171
4-6    45      0.077    0.022     1         0.316       0.333       15          0.028
7-10   60      0.012    0.000     0         0.084       0.050        3          0.007
11+   179      0.001    0.006     1         0.006       0.011        2          0.001
  • The under-confidence is confined to pole. The pole-sitter's mean simulated P(win) is 0.390, against 10 wins in 15 (0.667). Its podium probability is 0.683, against 13 of 15 (0.867).
  • The front row is over-confident, not under-confident. Slots 2–3 get 0.159 to win but won 3 of 30 (0.100), and 0.482 for a podium against 0.400.
  • Slots 4–6 are the clearest over-prediction of wins: 0.077 simulated against 1 win in 45, about three times the grid base rate (0.028).
  • The pattern. The engine spreads win probability too evenly from pole across the next few slots. That fits the chapter's diagnosis: one field-wide pace uncertainty lets cars behind beat the pole-sitter too often. With 15 races the slot-level counts are small, so read the direction, not the decimals.

Chapter 28

Chapter 28 — Technical Regulations · exercises · verification script: appendices/code/answers_part2_ch28.py

Worked in the chapter. B1–B10 (all of Part B) have full solutions in the exercises file; open the Solution blocks there. C3 and C7 read the chapter's caches in code/_cache/. Run 02_mass_cost.py and 07_fastest_lap_point.py first if that folder is empty.

C1. Analyze this session: the 2025 Monaco GP

We run the validator on the race, then re-run validate_strategy on each flagged sequence to print its reasons.

v = regs.validate_race(f1data.session(2025, "Monaco", "R"))
fin = v[v.finisher]
for _, r in v[~v.ok].iterrows():
    val = regs.validate_strategy(r.sequence, 2025, circuit="monaco")
finishers 18; stops min 2, median 2, max 3; finishers in breach 0
stop counts of finishers: {2: 17, 3: 1}
acronym sequence  n_stops  finisher  status  n_sets
    ALO      H-H        1     False Retired       2
    GAS      M-M        1     False Retired       2
  ALO H-H: ok=False; reasons: ['only one dry compound used (HARD-HARD); the rule needs two', '2 sets used at Monaco 2025; at least 3 required']
  GAS M-M: ok=False; reasons: ['only one dry compound used (MEDIUM-MEDIUM); the rule needs two', '2 sets used at Monaco 2025; at least 3 required']
  • (a) Finishers. There were 18 finishers: 17 made two stops and one made three. No finisher breached a rule. That is the 2025 Monaco rule (at least three sets, so at least two stops) working exactly as written.
  • (b) The flags. Two retirements are flagged, Alonso (H-H) and Gasly (M-M). Both had made one stop when they retired.
  • (c) The reasons. Each fails both tests: only one dry compound, and only two sets where three were required. Neither is a breach, because both requirements apply only to a car that takes the flag. This is the same reason the chapter found 104 flagged non-finishers and no finisher in breach.

C3. Analyze this session: price a kilogram at Monza and Bahrain, 2024

We fit metrics.estimate_fuel_effect on each race at both start fuels and set the result next to the 2025 value in the chapter's cache.

for fuel in (100.0, 110.0):
    r = metrics.estimate_fuel_effect(f1data.laps(s), start_fuel_kg=fuel)
Data: OpenF1 (2024 Italian Grand Prix, Race) | dry: True
  start 100 kg: -0.0600 s/lap, 0.0318 s/kg [0.0295, 0.0341], n 922 laps
  start 110 kg: -0.0600 s/lap, 0.0289 s/kg [0.0268, 0.0310], n 922 laps
  2025 value (100 kg): 0.0333 s/kg [0.0321, 0.0345]
Data: OpenF1 (2024 Bahrain Grand Prix, Race) | dry: True
  start 100 kg: -0.0713 s/lap, 0.0406 s/kg [0.0376, 0.0437], n 1006 laps
  start 110 kg: -0.0713 s/lap, 0.0369 s/kg [0.0342, 0.0397], n 1006 laps
  2025 value (100 kg): 0.0358 s/kg [0.0325, 0.0391]
  • Monza 2024: slope −0.0600 s/lap, giving 0.0318 s/kg [0.0295, 0.0341] at 100 kg and 0.0289 s/kg at 110 kg.
  • Bahrain 2024: −0.0713 s/lap, giving 0.0406 s/kg [0.0376, 0.0437] and 0.0369 s/kg.
  • Both inside the expected range, 0.02–0.05 s/kg at 100 kg.
  • The 110 kg figure is exactly 100/110 of the 100 kg one (0.0318 × 0.909 = 0.0289), because only the assumed kilograms per lap change. The measured slope does not.
  • Between seasons.
  • Monza moves little: 0.0318 in 2024 against 0.0333 in 2025, with overlapping intervals.
  • Bahrain is 13% higher in 2024 (0.0406 against 0.0358), and the intervals barely overlap.
  • Cars of the same rules era did not become 13% more mass-sensitive in a year. What changes from race to race is everything else the lap-number slope absorbs: track evolution as rubber goes down, and the track temperature trend over the race. Bahrain starts at dusk, so a plausible reading is that the track cools at a different rate from year to year.
  • This is why the chapter calls the number an upper bound on the pure mass effect and quotes a median over 20 races, not one circuit's value.

C6. Analyze this session: Hülkenberg at the 2026 Monaco GP

We print his OpenF1 stints, pass them to regs.race_sets, and compare a validator that counts every stint as a set with one that uses the merged sets.

st = f1data.stints(s, driver="HUL")
sets = regs.race_sets(st)                               # same compound, start age within 1 lap -> same set
regs.validate_strategy(seq, 2026, circuit="monaco", sets_by_compound=naive)       # every stint a set
regs.validate_strategy(seq, 2026, circuit="monaco", sets_by_compound=merged)      # race_sets
 stint_number compound  lap_start  lap_end  tyre_age_at_start
            1   MEDIUM          1       12                0.0
            2     HARD         13       58                0.0
            3     HARD         59       65               47.0
            4     HARD         66       67               53.0
            5     SOFT         68       78                1.0
race_sets ->
compound  first_age  end_age  laps   new
  MEDIUM          0       12    12  True
    HARD          0       55    55  True
    SOFT          1       12    11 False
validate_race HUL: sequence M-H-H-H-S, stops 3, red-flag changes 1, n_sets 3, ok True, reasons 
stints counted naively as sets: 5
2026 weekend allocation: {'HARD': 2, 'MEDIUM': 3, 'SOFT': 8}
  naive (every stint a set): sets {'HARD': 3, 'MEDIUM': 1, 'SOFT': 1} -> ok=False; reasons ['3 sets of HARD in the race; only 2 allocated for the weekend']
  race_sets: sets {'MEDIUM': 1, 'HARD': 1, 'SOFT': 1} -> ok=True; reasons []
  • Five stints, three tyre sets. The stint table has three HARD stints. The raw feed also had two zero-length stints here (a HARD on laps 59–58 and a SOFT on laps 68–67, with lap_end before lap_start); the book's processed stint table now drops them, and race_sets would drop them too.
  • What race_sets merges. The HARD stints 3 and 4 start at ages 47 and 53, each within one lap of where the previous HARD stint ended. They are the same physical set, so the three HARD stints become one set used for 55 laps. The SOFT stint 5 starts at age 1 and is kept as one set.
  • The result. Three physical sets, MEDIUM, HARD and SOFT, and a valid race (the validator also records one red-flag tyre change).
  • Why the first validator flagged him. Counting every stint as a set gives 3 HARD "sets" against a weekend allocation of 2, so it reports "3 sets of HARD in the race; only 2 allocated". The breach is an artefact of how the feed splits a stint around a stoppage, not something on the car.

C7. Compare these drivers: fastest laps and fresh tyres

We filter the chapter's per-race fastest-lap table for races whose fastest lap was set by a late green stopper.

R = pd.read_parquet(CACHE / "fastest_lap_races.parquet")
hit = R[(R.year == y) & R.fl_by_late_stopper]
2023: 7 of 22 races = 31.8%
 round   circuit_ref  race_laps      fl_driver  fl_lap  fl_tyre_age  fl_finish
     4          baku         51        russell      51            2        8.0
     8    villeneuve         70          perez      70            2        6.0
     9 red_bull_ring         71 max_verstappen      71            2        1.0
    12           spa         44       hamilton      44            2        4.0
    17        losail         57 max_verstappen      56            5        1.0
    18      americas         56        tsunoda      56            2        8.0
    21         vegas         50        piastri      47            4       10.0
  by driver: {'max_verstappen': 2, 'russell': 1, 'perez': 1, 'hamilton': 1, 'tsunoda': 1, 'piastri': 1}
2025: 1 of 24 races = 4.2%
 round circuit_ref  race_laps fl_driver  fl_lap  fl_tyre_age  fl_finish
    16       monza         53    norris      53            7        2.0
  by driver: {'norris': 1}
  • The counts match the expected shape: 7 of 22 races in 2023 (31.8%) against 1 of 24 in 2025 (4.2%).
  • Who. Verstappen appears twice in 2023 (Austria and Qatar), both times as the winner. The other five are one each, and they finished anywhere from fourth to tenth.
  • The typical 2023 case. In five of the seven, the fastest lap came on the final lap, on tyres two laps old. That is the pattern the point rewarded: a car with a big enough gap behind takes a free stop and uses the last lap.
  • 2025, without the point. The one remaining case, Norris at Monza, came on a set seven laps old.

D1. Call the pit stop: 2024 Las Vegas, properly

We read Norris's gap to the car behind from Jolpica's lap-by-lap cumulative times, and build the empirical green pit-loss distribution from every used Las Vegas stop in 2023–26. A stop on lap L is judged against the gap at the end of lap L + 1. We measure that gap up to lap 47, his last normal lap. After lap 47 we project it from the laps 40–47 trend, because his own stop contaminates the real values.

g = history.gap_to_leader_by_lap(2024, 22)
gap_behind = x.loc[i + 1, "cum_s"] - x.loc[i, "cum_s"]            # next car on the same lap
pool = np.concatenate([d[d.used].pit_loss_s for d in las_vegas_stops_2023_26])
p = (pool > gap).mean();  ev = (1 - p) * 1 + p * (-2 + 1)       # +1 FL point; P6 -> P7 costs 2 (2024 scale)
     pos  nor_lap_s behind  gap_behind ahead  gap_ahead
lap
40     6     95.843    PIA      14.562   LEC     13.425
...
45     6     96.363    PIA      20.479   LEC     10.804
46     6     96.006    PIA      21.520   VER     10.154
47     6     96.445    PIA      22.197   VER      9.863
48     6    100.900    PIA      19.144   VER     13.841
49     6    112.312    PIA       4.584   VER     29.137
50     6     94.876    PIA       7.980   VER     26.803
Las Vegas green pit losses 2023-26: n 72, median 22.427, IQR 21.59-24.57, min 15.64, max 47.48
gap to the car behind, laps 40-47: grows +1.099 s/lap
stop on lap L -> gap that matters is at the end of lap L + 1 (measured to lap 47, projected after):
  L = 45: gap  21.52 s (measured); P(loss > gap) = 0.764; E[points change] -0.53
  L = 46: gap  22.20 s (measured); P(loss > gap) = 0.569; E[points change] -0.14
  L = 47: gap  23.75 s (projected); P(loss > gap) = 0.306; E[points change] +0.39
  L = 48: gap  24.85 s (projected); P(loss > gap) = 0.236; E[points change] +0.53
  L = 49: gap  25.95 s (projected); P(loss > gap) = 0.167; E[points change] +0.67
NOR's stops (pit_loss):
 in_lap  in_lap_s  out_lap_s  pit_loss_s  used
      9   105.240    114.247      20.281  True
     30   104.646    113.261      21.492  True
     48   100.900    112.312      21.330  True
NOR result: position 6
fastest lap: NOR 94.876 s on lap 50

What the numbers say. - The car behind was Piastri, his team-mate, and the gap grew by about 1.1 s a lap. - The empirical pit-loss distribution (n = 72, median 22.427 s) has a long right tail, up to 47.5 s. So even a 24–25 s margin is not completely safe. - The risk falls fast as the gap grows: P(rejoin behind Piastri) is 0.76 for a stop on lap 45 and 0.24 for a stop on lap 48. - Lap 49 looks best on the arithmetic, but it is not a real option. Its out-lap would be lap 50, the final lap, so no flying lap on the fresh tyres would remain and the fastest-lap point would be gone. Lap 48 is the last useful lap, and the best one: expected +0.53 points under the same assumptions as B8. - What happened. He stopped at the end of lap 48 and lost 21.330 s, almost exactly the pool median. He rejoined 4.584 s ahead of Piastri, kept sixth, and set the race's fastest lap, 94.876 s, on lap 50. Adding his pit loss back to that margin gives about 25.9 s, so our projected 24.85 s was slightly cautious.

For the pit wall. Wait as long as the race allows. Every lap adds about 1.1 s of margin, and at Las Vegas the stop-loss tail is long. Box at the end of lap 48, the last lap that still leaves a flying lap. On the empirical losses, the chance of coming out behind is then about one in four, and the expected value is about +0.5 points. Because the car behind is a team-mate, there is a second safety valve: if the stop goes badly, the team can decide the order of its own cars. That changes the downside, and it is a team decision, not something the data can price.

For a TV audience. Norris had more than 22 seconds in hand over his team-mate, and a pit stop costs about that much at Las Vegas. He stayed out until the gap was big enough to make it very likely he would come back out still sixth, and stopped with just one lap left to use the new tyres. It worked: he kept sixth and set the fastest lap of the race on the very last lap, for a bonus point.

Assumptions. The fastest-lap point is treated as certain once he stops, and the gap after lap 47 is a linear projection. Stops are drawn from the four-season Las Vegas pool, including its slow tail.

Chapter 29

Chapter 29 — The 2026 Regulations in Data · exercises · verification script: appendices/code/answers_part2_ch29.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D4 (all of Part D) have full solutions or discussions in the exercises file; open the Solution, Discussion or Discussion and what happened blocks there. C1 and C7 below reuse the chapter's cache of every driver's fastest qualifying lap (code/_cache/allq_2025_2026.pkl). The chapter's ch29_common.py builds it on first use, which takes a few minutes.

C1. Analyze this session: Spa qualifying, 2025 and 2026

For every driver whose fastest lap passes circuit.lap_quality, we run regs2026.lap_clip_summary and summarise three columns.

L = [l for l in C.all_quali_laps() if l["year"] == y and l["circuit_ref"] == "spa"]
for l in L:
    if l["ok"]:
        rows.append(dict(acronym=l["acronym"], position=l["position"], **R.lap_clip_summary(l["tel"])))
2025: drivers with car_data 20, laps passing lap_quality 20
  n_events      median  2.000  range  0.000 to  3.000
  max_fade_kmh  median 12.500  range  0.000 to 34.333
  time_lost_s   median  0.054  range  0.000 to  0.082
  laps with >= 2 events: 11
2026: drivers with car_data 22, laps passing lap_quality 22
  n_events      median  3.000  range  3.000 to  4.000
  max_fade_kmh  median 46.000  range 41.333 to 60.000
  time_lost_s   median  1.568  range  1.166 to  2.134
  laps with >= 2 events: 22
acronym  position  n_events  max_fade_kmh  time_lost_s
    ANT         1         3        60.000        1.939
    VER         2         4        54.000        1.226
    NOR         3         4        45.333        1.856
    RUS         4         3        48.667        2.134
    LEC         5         3        60.000        1.968
  • 2026 matches the chapter. All 22 laps pass the gate. Every lap has three or four clip events, the median maximum fade is 46 km/h, and the median fade cost is 1.568 s, the Spa value in Figure 29.9. The cheapest 2026 lap still loses 1.17 s to fades.
  • 2025 matches on cost but not on the event count. The median fade cost is 0.054 s, as expected. But 2025 has 20 rows, not 22, and the laps are not "at most one small event": 11 of the 20 laps have two or more events, and the largest fade is 34 km/h. These 2025 events are short and late, so they cost little time (0.082 s at most). The chapter found the same pattern across the season: in 2025 the fade starts after 89% of a full-throttle run, against 65% in 2026.
  • The comparison that matters is the cost, not the count. The 2026 cost is about 29 times the 2025 cost at the same circuit.

C3. Build the season comparison: race speed trap, dry races only

for dry in (False, True):
    t, s = R.season_compare(2025, 2026, "trap_r", dry_only=dry)
dry_only=False: median change -0.5 km/h [-4.0, +6.5], n = 19
dry_only=True: median change -0.8 km/h [-4.5, +3.5], n = 16
circuits dropped as wet in either year: ['albert_park', 'interlagos', 'silverstone']
  circuit_ref  value_2025  value_2026  delta
        monza       352.0       330.0  -22.0
        vegas       337.0       315.0  -22.0
          spa       316.5       305.0  -11.5
          ...
    catalunya       338.0       349.5   11.5
         baku       328.0       341.0   13.0
  hungaroring       309.5       338.0   28.5
  • Three circuits drop out: Albert Park, Interlagos and Silverstone had a wet race in one of the two years, so n falls from 19 to 16.
  • The conclusion holds. The median change moves from −0.5 to −0.8 km/h, and the interval (−4.5 to +3.5 km/h) still includes zero. Race top speed held up in 2026.
  • The spread across circuits is large. It runs from −22 km/h (Monza, Las Vegas) to +28.5 km/h (Hungaroring). A median near zero hides real circuit-by-circuit change, and the trap's position on each lap matters as much as the rules.

C5. Analyze this session: 2026 Italian GP, Antonelli from 19th

We classify every overtakes record with regs2026.green_passes and count Antonelli's records in each class, both as the passing car and as the passed car.

o = R.green_passes(s)
gain = o[o.overtaking_driver_number == ant].cls.value_counts()
lost = o[o.overtaken_driver_number == ant].cls.value_counts()
ANT grid 19, finish 1
                                        ANT passes  ANT passed  net
lap 1                                            5           1    4
under SC/VSC/red                                 0           4   -4
pit in/out lap                                   0           0    0
retiring car                                     1           0    1
flicker (reversed <=10 s)                        2           2    0
mass change (>=4 for one car in a lap)           4           0    4
green on-track                                  13           3   10
total net +15
neutralisations: [{'status': 'SC', 'start_lap': 3.0}, {'status': 'RED', 'start_lap': 3.0}, {'status': 'VSC', 'start_lap': 28.0}]
cars that started ahead of ANT: 18; of those retired: 2 ['LEC', 'STR']
Class Net places
(a) Green on-track passes +10 (13 made, 3 suffered)
(b) Under SC/VSC/red −4
(c) Pit in/out laps 0
(d) Lap 1 +4
Mass-change records +4
A retiring car +1
Flicker 0
Total from records +15
  • 13 green on-track passes, as expected. Three cars passed him back, so the green class is worth a net +10.
  • Lap 1 was worth +4, and the neutralised period cost him 4. He lost those places while the race was neutralised (the safety car and red flag from lap 3, the VSC from lap 28). Position records in those windows reflect reshuffles, not racing.
  • Four "mass change" records belong to a lap on which one car changed places four or more times. The filter treats that as a damaged car or a timing glitch, not as four passes.
  • The records do not add up to 18. They give a net +15. Two of the cars that started ahead of him retired (Leclerc and Stroll), and one record is already classed as passing a retiring car. A record is a position change seen by the timing feed, not a complete account of places, so expect a gap of a few places between the records and grid-to-flag arithmetic.

C7. Build the strategy: the Miami comparison on high-energy circuits only

We keep the 2026 circuits whose median fade cost exceeds 0.25 s per lap and repeat the 2026-minus-2025 comparison before and after round 4.

c26 = D[D.year == 2026].groupby("circuit_ref").cost.median()
high = c26[c26 > 0.25]
P["post_miami"] = P[("rnd", 2026)] >= 4
2026 circuits with median fade cost > 0.25 s: {'miami': 0.29, 'albert_park': 0.325, 'baku': 0.373, 'shanghai': 0.419, 'vegas': 0.537, 'silverstone': 0.648, 'suzuka': 0.861, 'spa': 1.568}
            has_2025  d_fade d_cost post_miami
albert_park     True  49.000  0.325      False
baku           False     NaN    NaN       True
miami           True  18.833  0.290       True
shanghai        True  27.833  0.419      False
silverstone     True  27.667  0.362       True
spa             True  33.500  1.515       True
suzuka          True  47.667  0.789      False
vegas          False     NaN    NaN       True
post_miami=False: n = 3; median change in max fade +47.7 km/h, in fade cost +0.419 s
post_miami=True: n = 3; median change in max fade +27.7 km/h, in fade cost +0.362 s
  • Eight circuits qualify, the ones the exercise expects. Baku and Las Vegas have no dry 2025 qualifying lap set to compare with, so the post-Miami group shrinks to three (Miami, Silverstone, Spa) against three before.
  • The gap narrows but does not close. Among high-energy circuits, the jump in maximum fade is +47.7 km/h before round 4 and +27.7 km/h after. The jump in fade cost is +0.419 s against +0.362 s. That is much closer than the all-circuit comparison (+47.7 against +16.5 km/h), which confirms that most of the chapter's apparent effect was the calendar.
  • It is still not convincing. Three circuits against three cannot separate the rule change from circuit layout. Spa alone (+1.515 s) is nearly twice the next largest change (Suzuka, +0.789 s). No interval could exclude zero at this n, and only one season of 2026 data exists. The honest summary is "consistent with a modest reduction, not evidence of one".

C9. Build the strategy: passes against spread across 2026 races

We take the 21 races of 2026 and fit a Poisson regression of green passes on the race-pace spread (the slowest team's race pace as a percentage behind the fastest), with no circuit effects.

D = R.season_metric(2026, "green_passes").merge(R.season_metric(2026, "race_pace_spread"), on="circuit_ref")
m = smf.glm("passes ~ spread", data=D, family=sm.families.Poisson()).fit(cov_type="HC1")
races: 21
  circuit_ref  round  passes  spread
        vegas     21   180.0   2.343
    rodriguez     19    37.0   2.736
     americas     18    46.0   3.392
          ...
  albert_park      1    38.0   4.737
  silverstone      9    51.0   4.820
   villeneuve      5    40.0   6.158
spread coef -0.437 per % (HC1 95% CI -0.830 to -0.043); rate ratio per +1 % 0.646; Pearson dispersion 12.1
without Las Vegas (n = 20): coef -0.150 (CI -0.365 to +0.065)
Spearman rank correlation passes vs spread: -0.37
  • The sign is negative, the same as Case Study 2's within-circuit coefficient on the IQR spread (−0.384, a different spread measure). Across the 2026 races, a wider field goes with fewer passes: a rate ratio of 0.65 per percentage point.
  • It rests on one race. Las Vegas has both the most passes (180) and the smallest spread (2.34%). Without it, the coefficient falls to −0.150 and its interval includes zero. The dispersion of 12 says the Poisson intervals are too narrow anyway.
  • Why the two estimates need not agree. Across circuits, layout drives both passing and spread: a power circuit with long straights both helps passing and compresses lap-time gaps in percentage terms. Within a circuit (Case Study 2), only the season changes, so that comparison removes the layout. The between-circuit fit here mixes the two effects. Its sign happens to agree, but its size is not a causal estimate of what a wider field does to passing.

Chapter 30

Chapter 30 — Car Development · exercises · verification script: appendices/code/answers_part2_ch30.py

Worked in the chapter. B1–B10 (all of Part B), D1, D2 and D4 have full solutions or discussions in the exercises file; open the Solution, Discussion or Selected answers blocks there. C2 below reads the chapter's cached outcome table code/_cache/outcome_A.csv, written by 04_tunnel_time_test.py.

C1. Analyze this session: 2023 allowances in ATP 3 and ATP 4

t = upgrades.team_atr(2023)
w = t[t.atp.isin([3, 4])].pivot_table(index="team_ref", columns="atp",
                                      values=["position", "coefficient_pct"])
              pos_atp3   h1_c  pos_atp4   h2_c  change
team_ref                                              
red_bull           1.0   63.0       1.0   63.0     0.0
mercedes           3.0   80.0       2.0   75.0    -5.0
aston_martin       7.0  100.0       3.0   80.0   -20.0
ferrari            2.0   75.0       4.0   85.0    10.0
alpine             4.0   85.0       5.0   90.0     5.0
mclaren            5.0   90.0       6.0   95.0     5.0
alfa               6.0   95.0       7.0  100.0     5.0
haas               8.0  105.0       8.0  105.0     0.0
williams          10.0  115.0       9.0  110.0    -5.0
alphatauri         9.0  110.0      10.0  115.0     5.0
basis ATP3: 2022 final (R22) | basis ATP4: 2023 after R8
teams whose C changed: 8 of 10
  • Eight of the ten teams changed allowance at the end of ATP 3. Only Red Bull (still P1, and still under its 63% penalty) and Haas (P8 on both bases) stayed put.
  • Aston Martin fell from 100% to 80%, the largest move, as expected. The ATP 1–3 basis was the 2022 final standings, where it was seventh. The ATP 4 basis is the standings after Round 8 of 2023, where it was third. Four places up the table is 20 points of C, or 64 fewer runs per ATP.
  • Ferrari moved the other way, from 75% to 85%, because it slipped from second to fourth.

C2. Compare these teams: development rate against first-half C

We fit the slope of the de-meaned development rate (y_dm) on h1_c for the 50 team-seasons of 2022–26. For each team-season we measure how much the slope rises when that point is dropped, and remove the three with the largest effect.

b = ols_slope(A.h1_c / 10, A.y_dm)
for i in A.index:
    infl.append(ols_slope(A.drop(i).h1_c / 10, A.drop(i).y_dm) - b)
team-seasons 2022-26 with h1_c: 50; slope -0.0023 pp/race per +10 points of C
the three team-seasons that pull the slope down most (slope rises most when dropped):
 year     team_ref  h1_c    y_dm  d_slope_if_dropped
 2026     mercedes  75.0  0.0312              0.0005
 2022      ferrari  80.0  0.0366              0.0004
 2026 aston_martin 100.0 -0.0539              0.0004
slope without them (n = 47): -0.0010 pp/race per +10 points
Spearman all -0.217 (p 0.130); without the three -0.147 (p 0.324)
  • The slope reproduces the chapter: −0.0023 pp per race per +10 points of C on all 50.
  • Three points carry more than half of it. Two are low-allowance teams that lost ground during their season: Mercedes 2026 and Ferrari 2022 (positive y_dm means the gap grew). The third is a full-allowance team that gained ground fast: Aston Martin 2026. Without them the slope is −0.0010, less than half the original, and the rank correlation falls from −0.22 to −0.15 (p 0.32).
  • What this tells you. A dose-response line that loses half its slope when three of fifty points are removed is not evidence that tunnel time speeds development. It is consistent with the chapter's verdict: any effect is too small to detect with five seasons.

C4. Analyze this session: 2024 before/after at the summer split

gaps = dev.adjust_for_circuit(dev.gap_to_fastest(years=(2023, 2026), method="best", exclude_wet=True))
for t in teams_2024:
    rows.append(upgrades.before_after(gaps, t, 2024, upgrades.summer_split(2024)))
summer split round 15
    team_ref  n_before  n_after  shift_pp  ci_low  ci_high  p_welch  p_placebo  n_placebo  mds_80
      alpine        11        9    -0.355  -0.782    0.065    0.155      0.933         14   0.664
aston_martin        11        9     0.245  -0.143    0.656    0.285      0.733         14   0.630
    red_bull        11        9     0.217   0.070    0.364    0.019      0.200         14   0.215
        haas        11        9    -0.202  -0.586    0.210    0.357      0.600         14   0.570
    mercedes        11        9    -0.195  -0.438    0.051    0.155      0.733         14   0.373
     mclaren        11        9    -0.178  -0.366    0.025    0.112      0.467         14   0.293
     ferrari        11        9    -0.148  -0.466    0.194    0.402      0.533         14   0.476
          rb        11        9     0.132  -0.187    0.453    0.449      0.533         14   0.482
      sauber        11        9    -0.019  -0.567    0.582    0.951      1.000         14   0.829
    williams        11        9    -0.018  -0.296    0.247    0.905      1.000         14   0.412
min achievable placebo p with 14 placebo splits: 0.067
  • Largest absolute shift: Alpine, −0.355 pp, as expected. Its interval includes zero, and its placebo p is 0.933: 14 other split points give a shift at least as large. Nothing marks the summer break as special for Alpine.
  • Red Bull: +0.217 pp, Welch p 0.019, placebo p 0.200. It is the only team whose Welch test clears 0.05, and its gap grew after the break. The placebo test says most other splits of Red Bull's 2024 season look just as different, because its gap rose steadily through the year. A trend produces a "significant" step at almost any split.
  • The resolution limit. With 14 placebo splits, the smallest achievable placebo p is 1/15 = 0.067, so no team can reach 0.05 this way. Red Bull's minimum detectable shift (0.215 pp) is the smallest of the ten because its residual SD is the smallest.

C8. Build the strategy: cumulative tunnel runs and the 2026 order

We sum each lineage's runs over 2021–25 with upgrades.season_allocation. We then compare the total with the 2026 season-median gap to the fastest team (Chapter 24's best-of-Q1–Q3 gap, wet sessions dropped).

a = upgrades.season_allocation(range(2021, 2026))
cum = a.groupby(a.team_ref.map(dev.lineage)).runs.sum()
gap = g.groupby(g.team_ref.map(dev.lineage)).gap_pct.median()
spearmanr(cum, gap)
                      team_2026  cum_runs_2021_25  gap_2026_pct
milton_keynes_lineage      red_bull            7284.0         0.400
bar_lineage                mercedes            7752.0         0.000
ferrari                     ferrari            7920.0         0.337
mclaren                     mclaren            8160.0         0.426
jordan_lineage         aston_martin            9216.0         3.820
enstone_lineage              alpine            9264.0         1.415
minardi_lineage                  rb            9888.0         1.337
sauber_lineage                 audi           10224.0         1.538
haas                           haas           10296.0         2.239
williams                   williams           10344.0         2.483
cadillac                   cadillac               NaN         3.850
Spearman (n = 10): +0.770, p = 0.0092
2025 final position vs 2026 gap: Spearman +0.636 (p 0.0479); vs cumulative runs: +0.624 (p 0.0537)
  • The correlation is strong and positive, +0.770 (p 0.009), as expected. The four teams with the least tunnel time over 2021–25 (Red Bull 7,284 runs, Mercedes, Ferrari, McLaren) are the four fastest teams of 2026. Williams had the most (10,344 runs) and is ninth of the ten with a history. Cadillac has no allowance history and is left out.
  • This is confounding, not cause. The allowance is set by past constructors' positions, so a team gets more tunnel time because it was slow. Slow teams also tend to stay slow: budgets, staff, facilities and the power unit persist from one year to the next. Past position drives both variables. As one check, the 2025 final position alone correlates +0.64 with the 2026 gap and +0.62 with cumulative runs.
  • What a causal test needs is variation in tunnel time that is not caused by past results. The chapter's within-season comparison of development rates against the scale is closer to that, and it found no detectable effect.

D3. Incentive design

One alternative: a rolling two-year average of positions. Each team's C would come from the mean of its last four half-season positions instead of the current standings after Round 7–10.

  • (a) The competitive order. Small effect. The scale already moves C by at most 45 points between P1 and P10 (224 against 368 runs per ATP, atr_allocation). C2 above and Section 30.6 found no detectable effect of that range on development rate. Smoothing the positions changes who gets which C, not how much C matters.
  • (b) Gaming. Better. A rolling average dilutes any one race's points, so "managing" points late in ATP 3 (D1) is worth even less than the 16 runs per ATP the module prices for one place.
  • (c) Measurement. Worse. The current rule switches at a known date, which creates a sharp, dated change in C that a before/after test can use. A rolling average changes C slowly and in step with past results, so the allowance becomes even more tightly tied to the confounder seen in C8.

A lap-time-based scale (C set by the qualifying gap to the fastest team) would track car speed directly and remove the points incentive. But it creates a new one: sandbagging in qualifying. It would also tie the allowance to the outcome we would use to measure its effect, so (c) gets worse again.

D5. When to stop developing

The prices, from atr_allocation at the 2022–25 scale:

P1  C  70.0 %: 224 runs and 56 h wind-on per ATP; ATPs 4-6 = 672 runs
P5  C  90.0 %: 288 runs and 72 h wind-on per ATP; ATPs 4-6 = 864 runs
P10 C 115.0 %: 368 runs and 92 h wind-on per ATP; ATPs 4-6 = 1104 runs
minimum detectable shift, 10 races before / 10 after, sd 0.445 pp: 0.558 pp

The argument. - Diminishing returns. Runs on a mature car return less per run than runs on a new concept, because the easy gains on a car have already been found. Under a reset, next year's car is the new concept. - The scale's switch. The allowance is fixed per ATP, and the runs for ATPs 4–6 (672–1,104, depending on position) are the last of the year. Whatever is not spent on this year's car can go to next year's. - The detection limits. A typical half-season change in gap must be about 0.56 pp (roughly 0.5 s on a 90 s lap) before a before/after test can see it. If the expected gain from more work on this year's car is well below that, the team cannot even confirm the work paid off.

The rule that follows. Move all tunnel time to next year's car once the expected points from further gains this season are worth less than the expected gain on next year's car. For most teams that point arrives early in a reset year. It comes earliest for a team with no title or close position battle to fight for.

Assumptions the public data cannot check: - The real return per run on either car. - How much of a mature car's knowledge carries over to new rules. - How the team splits CFD and tunnel work. - The prize-money value of one constructors' place, beyond the figures in Chapter 33.

Chapter 31

Chapter 31 — The Cost Cap and Financial Regulations · exercises · verification script: appendices/code/answers_part2_ch31.py

Worked in the chapter. B1–B9 (all of Part B), C7 (hint with the expected values) and D1–D4 (all of Part D) have full solutions, sketches or discussions in the exercises file; open the Solution, Hint, Solution sketch or Discussion blocks there.

C1. Analyze this session: 2023 Singapore GP qualifying

We take each driver's best of q1_s, q2_s and q3_s from Jolpica and compare the two cars of each team.

q = history.qualifying(2023, 15)
q["best_s"] = q[["q1_s", "q2_s", "q3_s"]].min(axis=1)
for t, g in q.groupby("team_ref"):
    g = g.sort_values("best_s")      # faster car first; gap = slower - faster
abbreviation  quali_position   q1_s   q2_s  q3_s  best_s best_in
         VER            11.0 92.398 92.173   NaN  92.173      Q2
         PER            13.0 92.099 92.310   NaN  92.099      Q1
        team faster  best_fast slower  best_slow  gap_s positions
     ferrari    SAI     90.984    LEC     91.063  0.079       1/3
    mercedes    RUS     91.056    HAM     91.485  0.429       2/5
     mclaren    NOR     91.270    PIA     92.902  1.632      4/17
        haas    MAG     91.575    HUL     91.808  0.233       6/9
aston_martin    ALO     91.615    STR     93.397  1.782      7/20
      alpine    OCO     91.673    GAS     92.274  0.601      8/12
  alphatauri    TSU     91.991    LAW     92.166  0.175     15/10
    red_bull    PER     92.099    VER     92.173  0.074     13/11
    williams    ALB     92.668    SAR     93.252  0.584     14/18
        alfa    BOT     92.809    ZHO     93.258  0.449     16/19
median team-mate gap 0.439 s
  • It was not a one-car problem. Verstappen (11th, 1:32.173 in Q2) and Pérez (13th, 1:32.099 in Q1) were 0.074 s apart. That is the closest team-mate pair in the session, closer even than Ferrari's front-row pair (0.079 s). The median team-mate gap was 0.439 s.
  • Pérez's best time came from Q1, and he did not improve in Q2 (1:32.310). Ranked on best time alone, Pérez is the 11th fastest driver and Verstappen the 13th. Ranked by its faster car, Red Bull is eighth of ten teams.
  • Two "fast" teams did have a one-car problem: McLaren (Piastri 1.632 s off Norris) and Aston Martin (Stroll 1.782 s off Alonso). A single-session gap that large can come from traffic or an interrupted run as well as from car pace, and the timing data alone cannot tell which.

C2. Compare these drivers: the penalty window on the like-for-like Q1 gap

We rerun 06_penalty_window.py's summary with method="q1" and keep the "best" result for comparison.

for method in ("best", "q1"):
    g = dev.gap_to_fastest((2022, 2024), method=method, exclude_wet=True)
    rb = g[g.team_ref == "red_bull"].merge(dates, on=["year", "round"])
method = 'best'
                rounds  median_gap  mean_gap  fastest  share_fastest
before              19       0.098     0.148        8          0.421
penalty window      18       0.000     0.096       13          0.722
after               24       0.080     0.183        9          0.375
method = 'q1'
                rounds  median_gap  mean_gap  fastest  share_fastest
before              19       0.082     0.208        9          0.474
penalty window      18       0.000     0.178       10          0.556
after               24       0.128     0.174        9          0.375
Window Median gap, best of Q1–Q3 Median gap, Q1 Fastest team (Q1 measure)
Before (19 rounds) 0.098% 0.082% 9
Penalty window (18) 0.000% 0.000% 10
After (24) 0.080% 0.128% 9
  • The conclusion of Section 31.7 survives. On the like-for-like Q1 measure, Red Bull's median gap inside the penalty window is still 0.000%, the smallest of the three periods.
  • The margin shrinks. Red Bull was the fastest team in Q1 in 10 of 18 window sessions (56%), against 13 of 18 on the best-of measure. Q1 hides some of the Q3 advantage, because teams do not run at full pace in Q1.
  • No dip. On neither measure is there a slower period during the cut. As the chapter says, that does not show the penalty did nothing: its effect was too small to detect against a gap this variable.

C6. Results spread with sprints

We add each team's sprint points from history.sprint_results to its race points and recompute the top-three share.

race = r.groupby("team_ref").points.sum()
spr = history.sprint_results(y).groupby("team_ref").points.sum()
tot = race.add(spr, fill_value=0)
 year  sprints  sprint_points  race_only  with_sprints                 top3_race                  top3_all  change_pts
 2021        3           18.0      68.76         68.97 mercedes,red_bull,ferrari mercedes,red_bull,ferrari        0.21
 2022        3          108.0      77.52         77.79 red_bull,ferrari,mercedes red_bull,ferrari,mercedes        0.27
 2023        6          216.0      68.11         68.14 red_bull,mercedes,ferrari red_bull,mercedes,ferrari        0.04
 2024        6          216.0      71.26         71.72  mclaren,ferrari,red_bull  mclaren,ferrari,red_bull        0.45
 2025        6          216.0      66.38         66.40 mclaren,mercedes,red_bull mclaren,mercedes,red_bull        0.02
 2026        6          216.0      69.64         69.45 mercedes,ferrari,red_bull mercedes,ferrari,red_bull       -0.19
  • The change is tiny: between −0.19 and +0.45 points of share in every season. The direction is upwards in five of six seasons. Sprint points go to the top eight (top three in 2021), so they slightly favour the front teams.
  • 2026 is the exception (−0.19). Its sprint points were spread a little more widely than its race points.
  • The top three are the same teams with or without sprints in every season. Excluding sprints, as 04_results_spread.py does, costs nothing in comparability and changes none of Section 31.5's conclusions.

C8. A non-exponential world

🧪 Illustrative model: parameters are assumptions chosen to be plausible for a current F1 car, not team data.

We write a logarithmic return curve with the same a, s and m as each default area and pass it to the greedy solver.

def log_returns(area, x, atr_c=1.0):
    a = area.max_gain * (atr_c if area.aero else 1.0)
    s = area.scale * (atr_c if area.aero else 1.0)
    return 0.0 if x < area.minimum else a * np.log1p((x - area.minimum) / s)

e = budget.allocate(135.0)
l = budget.allocate(135.0, returns=log_returns)
                                   area  spend_usd_m_exp  spend_usd_m_log  change  a_over_s
Aerodynamics (CFD, tunnel, aero design)            40.75            47.75    7.00      0.06
            Chassis & mechanical design            18.40            16.65   -1.75      0.04
          Simulation & vehicle dynamics            10.60             9.45   -1.15      0.04
          Manufacturing & upgrade build            28.50            25.25   -3.25      0.03
                  Reliability & quality            17.80            18.05    0.25      0.05
                        Race operations            18.95            17.85   -1.10      0.04
exp: total gain 2.0876 %, shadow price 0.02287 %/$m
log: total gain 2.2569 %, shadow price 0.02771 %/$m
  • Aero gains $7.0m and reliability gains $0.25m. Every other area loses money, manufacturing most of all (−$3.25m).
  • Why. With $y$ the spend above the minimum, the log curve's marginal return is $a/(s + y)$. Setting it equal to the shadow price λ gives $y = a/\lambda - s$, so spend above the minimum grows linearly with the ceiling $a$. The exponential curve gives $y = s\ln(a/(s\lambda))$, which grows only with the logarithm of $a$. The log curve never saturates, so the area with the biggest ceiling (aero, $a$ = 1.6%) keeps attracting money. Check aero by hand: 1.6/0.02771 − 25 = 32.74, so $x$ = 15 + 32.74 = $47.74m, which matches the solver's $47.75m to within its $0.05m step.
  • Reliability gains because its ceiling is large for its scale ($a/s$ = 0.05, second only to aero): 0.5/0.02771 − 10 = 8.04, so $x$ = $18.04m.
  • The lesson. The total gains (2.26% against 2.09%) cannot be compared, because the curves differ. What matters is that the allocation depends on the shape of the return curve far from the minimum, which no team can measure from outside. The optimizer's ranking of areas is robust, since aero is first in both. The exact dollar split is not.

Chapter 32

Chapter 32 — F1 Through the Eras · exercises · verification script: appendices/code/answers_part2_ch32.py

Worked in the chapter. B1–B7 (all of Part B), C1, C2, C5, C7 and D1–D4 (all of Part D) have full solutions, answers from the chapter's run or discussions in the exercises file; open the blocks there.

C3. Analyze this era: Wilson intervals on the top-team win share

d = eras.dominance_index(by="team")
ci = [metrics.wilson_ci(int(k), int(n)) for k, n in zip(d.top_wins, d.races)]
d["lo"], d["hi"] = [c[1] for c in ci], [c[2] for c in ci]
pre = d[d.season < 1960]
pre["overlaps_2023"] = pre.hi >= d.loc[d.season == 2023, "lo"].iloc[0]
2023: red_bull 21/22 = 0.955 [0.782, 0.992]
 season           top  top_wins  races  win_share    lo    hi  overlaps_2023
   1950          alfa         6      7      0.857 0.487 0.974           True
   1951          alfa         5      8      0.625 0.306 0.863           True
   1952       ferrari         7      8      0.875 0.529 0.978           True
   1953       ferrari         7      9      0.778 0.453 0.937           True
   1954      mercedes         4      9      0.444 0.189 0.733          False
   1955      mercedes         5      7      0.714 0.359 0.918           True
   1956       ferrari         6      8      0.750 0.409 0.929           True
   1957      maserati         4      8      0.500 0.215 0.785           True
   1958       vanwall         6     11      0.545 0.280 0.787           True
   1959 cooper-climax         5      9      0.556 0.267 0.811           True
pre-1960 seasons overlapping 2023's interval: 9 of 10: [1950, 1951, 1952, 1953, 1955, 1956, 1957, 1958, 1959]
median interval width: before 1960 0.532; 2010-2026 0.377
  • Nine of the ten pre-1960 seasons overlap 2023's interval (78.2–99.2%). The only one that does not is 1954, when the top team won 4 of 9 rounds and its upper bound is 73.3%.
  • The intervals are much wider before 1960: a median width of 53 percentage points, against 38 for 2010–2026. A 7–11-race season simply cannot pin down a share.
  • What this means for the chart. Even 1957 (Maserati, 4 of 8) and 1951 (Alfa Romeo, 5 of 8) cannot be statistically separated from Red Bull's 21 of 22. The ranking of the 1950s seasons against modern runaways rests on point estimates alone.

C4. Build the ruler: a 10-6-4-3-2-1 scale

a = eras.rescored_champions()                              # 25-18-15-12-10-8-6-4-2-1
b = eras.rescored_champions(scale=(10, 6, 4, 3, 2, 1))
modern scale, leader != champion: [1964, 1976, 1983, 1984, 1988, 1994, 1997, 1999]
10-6-4-3-2-1 scale, leader != champion:
 season champion rescored_leader  leader_pts  champion_rescored_pts
   1958 hawthorn            moss        46.0                   46.0
   1964  surtees            hill        43.0                   42.0
   1983   piquet           prost        62.0                   62.0
   1984    lauda           prost        83.0                   77.0
   1988    senna           prost       112.0                  102.0
   2008 hamilton           massa        83.0                   80.0
   2016  rosberg        hamilton       136.0                  136.0
survive in both: [1964, 1983, 1984, 1988]
only on the modern scale: [1976, 1994, 1997, 1999]
only on 10-6-4-3-2-1: [1958, 2008, 2016]
  1958: hawthorn: wins 1, 2nds 5, 3rds 1, 4th-6th 1 | moss: wins 4, 2nds 1, 3rds 0, 4th-6th 0
  1976: hunt: wins 6, 2nds 1, 3rds 1, 4th-6th 2 | lauda: wins 5, 2nds 2, 3rds 2, 4th-6th 1
  1994: michael_schumacher: wins 8, 2nds 2, 3rds 0, 4th-6th 0 | damon_hill: wins 6, 2nds 5, 3rds 0, 4th-6th 1
  ...
  2008: hamilton: wins 5, 2nds 2, 3rds 3, 4th-6th 3 | massa: wins 6, 2nds 2, 3rds 2, 4th-6th 2
  2016: rosberg: wins 9, 2nds 5, 3rds 2, 4th-6th 3 | hamilton: wins 10, 2nds 3, 3rds 4, 4th-6th 1
  • Four of the chapter's eight survive: 1964, 1983, 1984 and 1988.
  • Four disappear: 1976, 1994, 1997 and 1999. In each, the actual champion had more wins than the modern-scale leader. Hunt had 6 wins to Lauda's 5, Schumacher 8 to Hill's 6, Villeneuve 7 to Schumacher's 5, and Häkkinen 5 to Irvine's 4. A scale that pays 10/6 = 1.67 for a win over a second, rather than 1.39, swings these close seasons back to the driver with more wins. The six-place scale also stops paying for 7th–10th places, which removes the consistency points the challengers had collected.
  • Three new seasons appear: 1958, 2008 and 2016. In each, the driver with more wins now leads. Moss had 4 wins to Hawthorn's 1, Massa 6 to Hamilton's 5, and Hamilton 10 to Rosberg's 9.
  • Ties. Two of the new seasons, and 1983, are exact ties on the new scale (1958 46–46, 1983 62–62, 2016 136–136). The "leader" there is only the module's tie order, so call them ties, not reversals. On this scale the list of disputed seasons is 7, of which 3 are ties, against 8 on the modern scale. The point of the exercise stands: the list depends on the ruler.

C6. Analyze this era: the top four teams' qualifying gaps

eras.relative_performance reports each team's median like-for-like Q1 gap to the fastest team. That is not Chapter 24's best-of-Q1–Q3 measure, so the values differ from Chapter 24's (e.g. Mercedes 2026: 0.177% here, 0.000% there).

rp = eras.relative_performance("team", years=range(2014, 2027))
P = rp[rp.team_ref.isin(top4)].pivot_table(index="season", columns="team_ref", values="q_gap_pct")
team_ref  ferrari  mclaren  mercedes  red_bull
season                                        
2014        1.217    1.066     0.000     1.322
2015        0.549    1.819     0.000     1.058
...
2020        0.899    0.801     0.000     0.444
2021        0.474    0.575     0.020     0.212
2022        0.132    1.072     0.918     0.075
2023        0.374    0.487     0.515     0.000
2024        0.207    0.310     0.443     0.117
2025        0.399    0.000     0.347     0.293
2026        0.289    0.317     0.177     0.373
reset years: (2009, 2014, 2017, 2022, 2026)
change 2021 -> 2022: {'ferrari': -0.342, 'red_bull': -0.137, 'mclaren': 0.497, 'mercedes': 0.898}
change 2025 -> 2026: {'mercedes': -0.17, 'ferrari': -0.11, 'red_bull': 0.08, 'mclaren': 0.317}
  • 2022: Mercedes changed most, +0.898 points, from 0.020% to 0.918% off the fastest team. It went from the reference team of 2014–21 to the slowest of the four. Ferrari (−0.342) and Red Bull (−0.137) both gained.
  • 2026: McLaren changed most, +0.317 points, from the fastest team of 2025 (0.000%) to 0.317%. Mercedes gained 0.170 and became the quickest of the four on this measure.
  • The pattern. At both resets the team that had been best under the old rules lost the most ground (Mercedes in 2022, McLaren in 2026). The 2017 reset is the exception in this window: Mercedes stayed at 0.000% through it. That fits Chapter 28's finding that resets usually, but not always, reshuffle the order. Still, two resets and four teams are a tiny sample, and the 2014 reset sits at the edge of the window, so it has no "before" season here.

C8. Analyze this session: 2023 Singapore GP, Verstappen and Sainz

w = metrics.gap_to_leader_by_lap(s, wide=True)
w.loc[L, "VER"] - w.loc[L, "SAI"]                          # L = 39, 41, 62
a = lp.pivot_table(index="lap_number", columns="acronym", values="lap_duration")
(a.VER - a.SAI).loc[45:62].median()
end of lap 39: VER - SAI = +14.920 s
end of lap 41: VER - SAI = +43.809 s
end of lap 62: VER - SAI = +21.380 s
laps 45-62: median VER - SAI lap time -1.166 s/lap (n = 18); mean -2.011; total -36.19 s
acronym  stint_number compound  lap_start  lap_end  tyre_age_at_start
    VER             1     HARD          1       40                0.0
    VER             2   MEDIUM         41       62                0.0
    SAI             1   MEDIUM          1       20                0.0
    SAI             2     HARD         21       62                0.0
neutralisations: [{'status': 'SC', 'start_lap': 20.0}, {'status': 'VSC', 'start_lap': 44.0}]
VER - SAI lap-time difference laps 42-50: {42: -2.23, 43: 17.11, 44: -1.05, 45: -16.39, 46: -0.34, 47: 0.42, 48: 0.13, 49: -1.14, 50: 0.37}
laps 47-62 (green, after the VSC): median -1.166 s/lap, mean -1.216, n = 16
gap recovered from end of lap 41 to end of lap 62: 22.43 s over 21 laps = 1.068 s/lap
  • The three gaps. Verstappen was 14.92 s behind Sainz at the end of lap 39, 43.81 s after his lap-40 stop (end of lap 41), and 21.38 s at the flag (end of lap 62). The stop cost him 28.9 s against Sainz, the same as the toolkit's green-flag pit loss for this race quoted in Chapter 31 (B9, D1).
  • The pace on fresh tyres. Over laps 45–62 his median lap was 1.166 s faster than Sainz's: new MEDIUMs against HARDs that were 24–41 laps old. Averaged over laps 41–62, he closed the gap at 1.068 s/lap. Both figures sit right on the book's median fresh-tyre delta of 1.078 s/lap. Singapore 2023 behaved like a typical race in this respect.
  • A timing artefact. The mean over laps 45–62 (−2.011 s/lap) is pulled by lap 45 (−16.39 s), which mirrors lap 43 (+17.11 s). The three laps 43–45 sum to −0.33 s, so one lap-boundary timestamp around the VSC is misplaced. The median and the end-to-end gap are unaffected, which is why we report those.
  • Why it was not enough. The final gap is the pre-stop deficit plus the stop, minus the fresh-tyre gain: 14.92 + 28.89 − 22.43 = 21.38 s. The fresh tyres repaid about three-quarters of the stop (22.43 / 28.89 = 0.78), and the deficit he had before stopping remained.

Chapter 33

Chapter 33 — The F1 Business · exercises · verification script: appendices/code/answers_part2_ch33.py

Worked in the chapter. B1–B7 (all of Part B), C1, C2, C5–C8 and D1–D4 (all of Part D) have full solutions, expected findings or model answers in the exercises file; open the Solution, What you should find, Reveal or One way to answer blocks there. Only C3 and C4 are left without one, and both are answered below. Every dollar figure in this section is either press-derived or illustrative, and says which.

C3. Predict the race: correlated results

We keep the chapter's inputs: the table after round 21, each team's 2026 race points by round (R1–R21, sprints excluded), two rounds left, 10,000 runs, seed 33. The independent version is economics.simulate_positions. The same-round version draws one round index per simulated race and gives every team its points from that round.

M = per.loc[teams].values.T                          # rounds x teams
picks = rng.integers(0, M.shape[0], size=(N, ROUNDS_LEFT))
add = M[picks].sum(axis=1)                           # every team's points from the same drawn rounds
final = base + add + rng.uniform(0, 1e-3, size=add.shape)
P(red_bull P3): independent 74.2%  same-round 75.8%
P(mclaren P4): independent 74.2%  same-round 75.8%
P(haas P7): independent 74.1%  same-round 70.9%
P(audi P8): independent 74.1%  same-round 70.9%
per-round points correlation red_bull-mclaren: r = -0.11; rounds both scored 18 of 21
per-round points correlation haas-audi: r = -0.19; rounds both scored 2 of 21
red_bull-mclaren two-round swing (independent): P(b gains > 9 pts) = 25.5%, sd 20.16
red_bull-mclaren two-round swing (same-round): P(b gains > 9 pts) = 23.8%, sd 21.06
haas-audi two-round swing (independent): P(b gains > 3 pts) = 22.4%, sd 4.38
haas-audi two-round swing (same-round): P(b gains > 3 pts) = 25.6%, sd 4.82
  • The independent draws reproduce the chapter: P(Red Bull P3) 74.2% and P(Haas P7) 74.1%.
  • Same-round draws move the two fights in opposite directions. Red Bull's hold on third rises slightly, to 75.8%. Haas's hold on seventh falls to 70.9%.
  • Why the Haas–Audi fight gets less certain. The two teams' points per round are negatively correlated (r = −0.19). In 2026 they both scored in only 2 of 21 rounds, so a round in which one of them scores is usually a round in which the other does not. Drawing whole rounds keeps that see-saw, so the two-round swing between them is wider (standard deviation 4.82 points against 4.38). With only 3 points between them, a wider swing helps the team behind.
  • Why the Red Bull–McLaren fight barely moves. Their correlation is weak (r = −0.11), and both teams scored in 18 of 21 rounds. Taking the rounds together changes the shape of the swing only a little. McLaren's chance of gaining more than the 9-point gap goes from 25.5% to 23.8%.
  • The limit of either version. Same-round draws capture the fact that points taken by one midfield team are not available to another, but they still treat the 21 past rounds as equally likely futures. Neither version knows anything about Qatar or Abu Dhabi as circuits. Exercise M2 asks for that.

C4. Build the strategy: the 2017 position curve

We take the Motorsport.com 2017 team estimates from f1_business.csv, subtract the special payments the exercise names and Column 1 ($36m for every team except Haas), and set the remainder against the 2016 constructors' positions from Jolpica. Every money figure here is press-derived.

special = {"Ferrari": 68, "Red Bull": 35, "Mercedes": 35, "Williams": 10}
est["remainder"] = est.total - est.team.map(special).fillna(0) - np.where(est.team == "Haas", 0, 36)
p16 = history.constructor_standings(2016, final=True).dropna(subset=["position"]).set_index("team_ref").position
 pos_2016        team  pts_2016  total  special  column1  remainder
        1    Mercedes     765.0  171.0     35.0       36      100.0
        2    Red Bull     468.0  161.0     35.0       36       90.0
        3     Ferrari     398.0  180.0     68.0       36       76.0
        4 Force India     173.0   72.0      0.0       36       36.0
        5    Williams     138.0   79.0     10.0       36       33.0
        6     McLaren      76.0   97.0      0.0       36       61.0
        7  Toro Rosso      63.0   59.0      0.0       36       23.0
        8        Haas      29.0   19.0      0.0        0       19.0
        9     Renault       8.0   52.0      0.0       36       16.0
       10      Sauber       2.0   49.0      0.0       36       13.0
remainder monotonic non-increasing in position: False
steps between adjacent positions: [10.0, 14.0, 40.0, 3.0, -28.0, 38.0, 4.0, 3.0, 3.0]
Spearman(position, remainder) = -0.964 (p = 0.0000), n = 10
2016 positions 11: team_ref  points
   manor     1.0
mean step P1-P4: 21.3; P5-P10 excluding Haas: 5.0
  • The remainder is not monotonic. It falls steadily from P1 ($100m) to P5 ($33m) and from P7 to P10, but McLaren, sixth in 2016, keeps $61m, $28m more than fifth-placed Williams and $38m more than seventh-placed Toro Rosso. The rank correlation is still strongly negative (Spearman −0.96), because only one team breaks the order.
  • The shape has two regimes. The steps between P1 and P4 average $21.3m, and the step from P3 to P4 alone is $40m. From P5 to P10 (leaving out Haas, which received no Column 1) the steps are $3–4m, about $5m on average once McLaren's jump is included.
  • What this says about the Constructors' Championship Bonus. After the named special payments and Column 1 are removed, what is left should be Column 2 (a sliding scale by 2016 position) plus any bonus. A smooth Column 2 cannot produce McLaren's $28m bump or the $40m cliff between P3 and P4. The simplest reading is that a payment not tied to the 2016 finishing order, such as the bonus the exercise mentions, sits in the remainder of McLaren and of the top three teams. The reference table does not say which teams received it or how much, so its size cannot be separated from Column 2 with these rows.
  • Caveats. All ten totals are one outlet's estimates, rounded to whole millions. Manor, eleventh in 2016, has no row, and Haas (a 2016 newcomer) was outside Column 1. The 2021–25 structure replaced this system with heritage, a ten-year success bonus and a single position-money curve, which is why the chapter's derived 2025 curve is nearly straight.

Chapter 34

Chapter 34 — Pit Stop Analytics · exercises · verification script: appendices/code/answers_part2_ch34.py

Worked in the chapter. B1–B8 (all of Part B), C1, C2, C4, C5, C8 and D1–D4 (all of Part D) have full solutions, hints or discussions in the exercises file; open the Solution, Hints, Reveal or Discussion blocks there.

Throughout, rel_s is a stop's pit-lane time minus the median of all race stops at that event, and a slow stop is rel_s > 2 s, as in the chapter.

C3. Build the table

We rebuild the Jolpica season table from ps.jolpica_stops() and add the slow share after dropping each season's top 10% of rel_s. A second loop uses OpenF1 (2023–26), the only source that knows about penalties, to see what the trimmed stops actually were.

for y, g in J.groupby("year"):
    p, lo, hi = metrics.wilson_ci(int(g.slow.sum()), len(g))
    t = g[g.rel_s <= g.rel_s.quantile(0.90)]
    rows.append(dict(year=y, slow_pct=100 * p, slow_lo=100 * lo, slow_hi=100 * hi,
                     slow_pct_trim10=100 * t.slow.mean()))
 year  stops  median_s   q25   q75  slow_pct  slow_lo  slow_hi  p90_rel  slow_pct_trim10
 2011   1113     22.37 21.15 24.50     16.17    14.13    18.45     3.35             6.79
 2012    946     22.26 20.79 24.85     14.69    12.58    17.09     3.23             5.17
 2013    944     22.87 21.48 24.59     11.65     9.76    13.86     2.40             1.77
 ...
 2020    532     24.17 22.48 28.34     11.28     8.86    14.25     2.94             1.26
 2021    688     23.65 21.62 26.96     20.64    17.78    23.82     5.09            11.79
 ...
 2025    821     23.12 21.19 24.79     16.44    14.07    19.13     4.88             7.17
 2026    766     24.07 22.08 27.73     16.58    14.11    19.38     4.24             7.26
rows: 16 ; trimmed share lower in every season: True
seasons with slow share above 10% (so trimming removes only slow stops): 16 of 16
Spearman(slow_pct, slow_pct_trim10) = 1.000
OpenF1 2023: top-10% stops 81, of which penalty 15, SC/VSC/RED 32, wet 25, no tyre change 17; penalty stops below the cut 2
OpenF1 2024: top-10% stops 77, of which penalty 21, SC/VSC/RED 28, wet 12, no tyre change 13; penalty stops below the cut 0
OpenF1 2025: top-10% stops 82, of which penalty 23, SC/VSC/RED 17, wet 6, no tyre change 5; penalty stops below the cut 0
OpenF1 2026: top-10% stops 77, of which penalty 23, SC/VSC/RED 38, wet 7, no tyre change 11; penalty stops below the cut 1
  • The table reproduces Section 34.3: 16 rows, the same medians, IQRs and Wilson intervals (2011 16.17% [14.13, 18.45] through 2026 16.58% [14.11, 19.38]).
  • The new column is lower in every season, as expected, but it is mechanical. Every season's slow share is above 10%, so the trimmed 10% always consists of slow stops. The new column is therefore roughly (slow share − 10) / 0.9: for 2011, (16.17 − 10) / 0.9 = 6.86%, against 6.79% measured. It keeps exactly the same season ranking as the original (Spearman 1.000) and adds no information.
  • Why trimming is not a fair way to remove penalties.
  • It removes the wrong stops. In OpenF1's 2023–26 races, penalty stops are only 15–23 of the 77–82 stops in each season's top 10%. The rest are stops under a safety car, VSC or red flag, wet stops, pit-lane passages with no tyre change, and genuine crew errors. Trimming deletes all of them alike, including the crew errors the slow share is meant to count.
  • It does not scale with the cause. A season with more penalties or more neutralisations has its trim fall on those, and a season with fewer on genuine slow stops. The same 10% removes different things each year.
  • It is not even complete. A few penalty stops (up to 2 a season) fall below the cut and stay in.
  • The fair method is to filter by cause. Use the race-control record of the penalty, as the crew sample does. Jolpica has no penalty or flag information, which is why the chapter's crew analyses use OpenF1 (2023–26) and the 2011–26 Jolpica table is reported unfiltered.

C6. Predict the race

We use the losail pooled green-flag pit loss from the chapter's per-stop pit-loss file (the same 27.548 s as the book's pit-loss table). For each 2026 team we fit fit_stop_mixture to its crew-sample rel_s, replace p_slow with the shrunk rate from slow_stop_risk, and draw two stops 100,000 times (seed 42).

mix = ps.fit_stop_mixture(C[(C.year == 2026) & (C.team_ref == t)].rel_s)
mix_s = dict(mix, p_slow=ps.slow_stop_risk(t, 2026)["p_shrunk"])
x = ps.sample_stop_time(t, 2026, n=2 * N, rng=np.random.default_rng(42), base_s=BASE,
                        method="mixture", mixture=mix_s).reshape(N, 2)
tot = x.sum(axis=1)
losail pooled green-flag pit loss: 27.548 s (n = 76 stops, years [2023, 2024, 2025])
        team  n  p_raw  p_shrunk  tail_mean  sigma   mean    p10    p50    p90  band
     ferrari 29  0.000     0.063      0.000  0.422 55.037 54.046 54.868 56.558 2.512
          rb 32  0.031     0.074      1.280  0.540 55.448 54.042 55.114 57.511 3.469
      alpine 32  0.062     0.088      1.390  0.534 55.554 54.056 55.137 57.858 3.802
    mercedes 26  0.038     0.081      9.631  0.428 55.791 53.112 53.968 60.798 7.686
    red_bull 30  0.067     0.091      5.668  0.593 56.001 53.584 54.789 60.115 6.531
     mclaren 35  0.114     0.111      5.308  0.575 56.152 53.533 54.738 61.003 7.469
aston_martin 23  0.130     0.116      5.278  0.438 56.600 54.182 55.107 61.434 7.252
        haas 31  0.129     0.117      1.335  0.225 56.609 55.563 56.040 58.685 3.122
        audi 31  0.129     0.117      5.998  0.571 56.910 54.111 55.320 62.166 8.055
    williams 37  0.135     0.121      7.638  0.414 57.287 54.270 55.153 63.746 9.477
    cadillac 26  0.385     0.217      1.107  0.608 57.407 55.479 57.042 59.816 4.337
2026 field mixture: p_slow 0.108, tail mean 3.908 s, n 332
  variant alpine    (slow stops 2): mean 55.994, P10 54.056, P90 59.185, band 5.129
  variant ferrari   (slow stops 0): mean 55.521, P10 54.046, P90 57.696, band 3.650
  variant mercedes  (slow stops 1): mean 54.878, P10 53.112, P90 58.255, band 5.143
  variant rb        (slow stops 1): mean 55.830, P10 54.042, P90 58.459, band 4.417
  variant red_bull  (slow stops 2): mean 55.684, P10 53.584, P90 59.132, band 5.548
widest P10-P90 band: williams 9.477 s (p_shrunk 0.121, tail mean 7.638 s)
two-stop baseline 2 x 27.548 = 55.096 s
  • The table has 11 rows, as expected. Expected two-stop totals run from 55.04 s (Ferrari) to 57.41 s (Cadillac), against a 55.10 s baseline of two median losses. That is a 2.4 s spread over a race.
  • Williams has the widest P10–P90 band: 9.5 s. The reason is the size of its slow stops, not how often they happen. Its shrunk slow rate (12.1%) is only a little above the field's, but its slow stops average 7.64 s beyond the 2 s threshold, the largest tail of any team with more than one slow stop (Mercedes's single slow stop was longer, 9.63 s, which gives Mercedes a wide band, 7.7 s, despite a low slow rate). Williams's P90 two-stop total is 63.7 s, more than 8 s above the baseline.
  • Cadillac is the opposite case. It has the highest slow rate by far (38.5% raw, 21.7% shrunk), but its slow stops are short (1.11 s beyond the threshold). That gives it the highest mean with a moderate band (4.3 s). Haas is similar on a smaller scale.
  • A flaw in using the shrunk rate alone. Shrinkage raises the slow rate of teams with few slow stops, but leaves their tail size as fitted. Ferrari had no slow stops in the 2026 crew sample, so its fitted tail is 0 s, and its shrunk 6.3% of "slow" stops cost exactly 2.0 s each. That makes Ferrari's band (2.5 s) look narrower than the data can justify. Borrowing the 2026 field tail (3.91 s) for the five teams with fewer than three slow stops gives bands of 3.7–5.5 s. Williams still has the widest band.
  • Caveat. The 27.548 s base comes from 76 stops in three races (2023–25). It shifts every row equally, so it does not change the comparison between teams.

C7. Compare these teams

We run ps.persistence on every Jolpica race stop, 2011–2026, and list the largest year-to-year changes in each lineage's median rel_s. The first rows are the data for the requested scatter (season t on the x-axis, season t + 1 on the y-axis).

P = ps.persistence(ps.jolpica_stops(), "median_rel_s")
rho, p = spearmanr(P.median_rel_s, P.median_rel_s_next)
P = P.assign(change=P.median_rel_s_next - P.median_rel_s)
P.nsmallest(3, "change")                      # biggest improvements
pairs 151; Spearman 0.763 (p = 5.4e-30); OLS slope 0.779
Three biggest improvements (t -> t+1):
 year  lineage  median_rel_s  median_rel_s_next  change
 2017   hinwil         0.971             -0.026  -0.997
 2013 williams         0.787             -0.157  -0.944
 2016     haas         0.589              0.009  -0.580
Three biggest deteriorations:
 year  lineage  median_rel_s  median_rel_s_next  change
 2019     haas         0.338              0.977   0.639
 2012 williams         0.202              0.787   0.585
 2021   hinwil         0.029              0.470   0.440
  2017->2018 hinwil: team_ref ['sauber'] -> ['sauber']
  2013->2014 williams: team_ref ['williams'] -> ['williams']
  2016->2017 haas: team_ref ['haas'] -> ['haas']
|change| > 0.5 s: 7 of 151 pairs
  • The pooled correlation reproduces the chapter: Spearman 0.763 over 151 pairs. The least-squares slope is 0.78, so the scatter has a clear positive slope with mild regression to the mean.
  • The three biggest improvements:
  • Sauber, 2017 → 2018 (the Hinwil lineage): from +0.97 s to −0.03 s, an improvement of almost a full second.
  • Williams, 2013 → 2014: from +0.79 s to −0.16 s.
  • Haas, 2016 → 2017: from +0.59 s to +0.01 s, its second season.
  • The expectation that big moves belong to new or restructured teams holds only partly. Haas 2016 → 2017 is a new team settling in, which matches Case Study 2. Sauber and Williams are long-established teams. The timing data show a step change in their pit-lane times but cannot say what caused it (people, equipment or procedure), so we do not guess.
  • Large moves are rare, and they go both ways. Only 7 of the 151 pairs change by more than 0.5 s. Williams had one of the largest deteriorations (2012 → 2013) immediately before one of the largest improvements. Haas's largest deterioration came in 2019 → 2020. A single bad season followed by a recovery looks like a big "improvement" on this chart, which is regression to the mean as much as change.

Chapter 35

Chapter 35 — Overtaking Analysis · exercises · verification script: appendices/code/answers_part2_ch35.py

Worked in the chapter. B1–B7 (all of Part B) and D1–D4 (all of Part D) have full solutions in the exercises file; open the Solution, Reveal, Discussion points, What the model says or A model answer blocks there. Part C has no solutions in the chapter. C3, C5 and C7 below read the chapter's caches in code/_cache/, so run the chapter's scripts 01–05 first if that folder is empty.

A "green pass" is the chapter's definition throughout: an overtakes record that is not a pit cycle, a lap-1 shuffle, a neutralised lap, a retiring car, a flicker or a mass change.

C1. Analyze this session

We classify every overtakes record of the two races with overtaking.classify_passes (the classifier behind pass_counts), then check which races have the fewest green passes.

for circ in ("monaco", "monza"):
    o = ov.classify_passes(f1data.session(2024, circ, "R"))
    print(o.cls.value_counts())
2024 monaco: 47 records; green passes 6
cls
lap 1             33
pit in/out lap     8
green on-track     6
2024 monza: 225 records; green passes 42
cls
pit in/out lap               149
green on-track                42
lap 1                         21
flicker (reversed <=10 s)     12
retiring car                   1
fewest green passes in the snapshot:
year  round  gp       
2024  8      Monaco GP     6
2025  23     Qatar GP      6
      8      Monaco GP     7
2026  6      Monaco GP    12
  • Monaco 2024: 6 green passes out of 47 records. The largest class is lap 1 (33 records). The race was red-flagged on lap 1 (Chapter 2), and most of the order changes that remain were logged on lap 1, so they fall outside the green-pass count.
  • Italy 2024: 42 green passes out of 225 records, and the pit in/out class is by far the largest (149 records), exactly as expected. Two of every three records at Monza are pit-cycle swaps.
  • "The fewest in the snapshot" needs a qualifier. Monaco 2024 has the fewest, but it is tied: the 2025 Qatar GP also has 6. Monaco 2025 has 7.
  • The lesson. A raw count of overtakes records says more about how many pit cycles and restarts a race had than about how much racing there was. Monza has 4.8 times Monaco's records but 7 times its green passes.

C3. Compare these drivers

We count green passes made and suffered from the chapter's classified-pass cache, passes_classified.parquet, the file ch35_common.all_passes() returns.

G = P[P.cls == "green on-track"]
g = G[G.year == yr]
made, suff = g.overtaking_driver_ref.value_counts(), g.overtaken_driver_ref.value_counts()
g[g.overtaking_driver_ref == who].overtaken_driver_ref.value_counts().head(5)
2023: green passes 899 in 22 races
  most made:     {'perez': 81, 'russell': 64, 'norris': 59}
  most suffered: {'bottas': 85, 'zhou': 73, 'hulkenberg': 72}
  perez: made 81 (rank 1), suffered 15
  perez's five most-passed drivers: {'leclerc': 7, 'alonso': 7, 'sainz': 7, 'albon': 6, 'zhou': 6}
  who passed perez most: {'max_verstappen': 3, 'sainz': 3, 'leclerc': 3}
  perez races with a green pass: 19
2026: green passes 1132 in 21 races
  most made:     {'max_verstappen': 85, 'russell': 72, 'bortoleto': 70}
  most suffered: {'alonso': 89, 'sainz': 74, 'stroll': 66}
  max_verstappen: made 85 (rank 1), suffered 29
  max_verstappen's five most-passed drivers: {'russell': 12, 'antonelli': 8, 'hamilton': 7, 'hadjar': 6, 'leclerc': 5}
  who passed max_verstappen most: {'russell': 10, 'antonelli': 8, 'leclerc': 3}
  max_verstappen races with a green pass: 16
  • The counts match the chapter. Pérez made 81 green passes in 2023, the most that season, and Verstappen 85 in 2026, also the most. The drivers who suffered most were Bottas (85) in 2023 and Alonso (89) in 2026.
  • Pérez's passes were spread across the midfield. His five most-passed drivers were Leclerc, Alonso and Sainz (7 each), then Albon and Zhou (6 each). He was passed only 15 times, and nobody passed him more than 3 times. He made a green pass in 19 of 22 races.
  • Verstappen's 2026 passes were concentrated on the front-runners. Russell (12) and Antonelli (8) head his list, with Hamilton (7) next. The same two Mercedes drivers are also the drivers who passed him most often (10 and 8), so a large part of his count is a two-way fight at the front. He was passed 29 times, about twice as often as Pérez in 2023.
  • What the counts do not measure. Passes made depend on where a driver starts as much as on how good they are at passing: a quick car starting out of position has more cars to pass. A pass count is a description of a season, not a passing-skill rating. The chapter's pass model is the place to compare drivers at equal pace and tyre offsets.

C5. Predict the race

fit_pass_model always includes an era term, which cannot be estimated on 2023–25 alone. So we fit the same logistic regression without the era and interaction terms on the 2023–25 dry-race situations, shrink the circuit effects the same way, and predict every 2026 situation. The 2026-only circuit, Madring, gets the median circuit's offset.

fit = smf.logit("passed ~ pace + tyre + compound_step + gapc + C(circuit_ref, Sum)", data=A).fit(
    disp=0, cov_type="cluster", cov_kwds={"groups": A.session_key})
pred = p(logit_B())                                          # 2023-25 coefficients, 2026 situations
pe = p(logit_B(era=PM["era2026"]))                           # + the stored model's era term
pt = p(logit_B(tyre_coef=PM["tyre_delta"] + PM["tyre_delta_2026"]))   # + its 2026 tyre slope
2023-25 fit: 10,910 situations, 1380 passes in 59 races
coefficients: {'Intercept': -3.1208, 'pace': 1.2005, 'tyre': 0.1227, 'compound_step': -0.0664, 'gapc': -5.9328}
2026 circuits with no 2023-25 dry race (offset set to the median circuit): ['madring']
2026: 2,541 situations, observed 410 passes; predicted by the 2023-25 model 375.6 (ratio obs/pred 1.09)
stored 2023-26 model: era2026 +0.4891, tyre 2023-25 +0.1216, tyre 2026 +0.0468
  + era term only:          480.3
  + 2026 tyre slope only:   325.4
  + both:                   429.8
mean tyre_delta in 2026 situations +1.21 laps; share with |tyre_delta| >= 10: 12.4%; mean tyre_delta in 2026 passes +4.12
race by race (2026 dry races):
                     sit  obs  pred  ratio
round circuit_ref                         
1     albert_park    135   24  28.0    0.9
...
6     monaco         193    1   3.6    0.3
...
9     silverstone    100   21   9.3    2.2
...
13    monza          173   47  24.3    1.9
14    madring        103    8  20.0    0.4
15    baku           132   21   8.5    2.5
...
19    rodriguez      206   16  31.1    0.5
21    vegas          239   59  53.8    1.1
races where observed > predicted: 9 of 17
  • The 2023–25 model under-predicts 2026, as expected: 375.6 passes predicted against 410 observed from 2,541 situations. That is 8% short (observed ÷ predicted = 1.09).
  • Its coefficients are almost the chapter's DRS-era ones (pace 1.201 against 1.1996, tyre 0.1227 against 0.1214, gap −5.93 against −5.70). The difference between the eras is therefore in the era and interaction terms, not in a different fit.
  • Which effect wins: the era effect. Taking the two 2026 changes from the stored 2023–26 model one at a time:
  • Adding the era term alone (+0.489 on the log-odds, odds × 1.63) raises the prediction by +104.7 passes, to 480.3.
  • Replacing the tyre slope with the 2026 one (0.0468 per lap instead of 0.1216) lowers it by −50.2 passes, to 325.4. The tyre effect matters because the cars that pass carry a real tyre advantage (+4.12 laps on average, against +1.21 for all situations).
  • Together they give 429.8. The era effect is about twice the size of the tyre effect, so the net under-prediction is only a third of the era effect on its own.
  • Race by race the errors are large in both directions. Baku (2.5×), Silverstone (2.2×) and Monza (1.9×) had far more passes than the DRS-era model expects. Monaco (1 against 3.6), Madring (8 against 20.0, with no circuit history) and Mexico City (16 against 31.1) had far fewer. Observed exceeds predicted in 9 of 17 races. This race-to-race spread is the dispersion the chapter models with its race offset (SD 0.743), and it is why a single 2026 race says little about the new rules.

C7. Compare these circuits

For each 2026 circuit we take the full-throttle share of located passes, the longest full-throttle straight on that circuit's 2026 pole lap, and the median following gain on that straight (peak speed, following within 1 s against clean air beyond 2.5 s, same driver and race), exactly as in 04_drs_tow_overtake.py.

ft = L.groupby("circuit_ref").agg(full_throttle=("state", lambda s: (s == "full throttle").mean()))
gain = pd.DataFrame(dd).groupby("circuit_ref").d_peak.median()          # per driver-race, then circuit median
T = ft.join(TS.groupby("circuit_ref").straight_m.median()).join(gain.rename("follow_gain_kmh"))
spearmanr(T.full_throttle, T.straight_m); spearmanr(T.full_throttle, T.follow_gain_kmh)
                 n  full_throttle  straight_m  follow_gain_kmh
circuit_ref                                                   
hungaroring     27          0.111     456.991            33.50
catalunya       30          0.167     688.949            17.00
marina_bay      29          0.207     596.142            12.50
...
rodriguez       29          0.345    1035.118            11.00
...
baku            34          0.559    1852.965             9.50
vegas          132          0.591    1681.685            14.50
spa             46          0.652    1852.865            11.00
monza           77          0.779     980.404             7.25
n = 21; Spearman(full-throttle share, straight length) = +0.784 (p = 0.000)
           Spearman(full-throttle share, following gain) = -0.141 (p = 0.542)
without the Hungaroring: straight +0.750, gain -0.005 (n = 20)
  • Straight length predicts "straight-line passing"; the following gain does not. Over the 21 circuits of 2026, the full-throttle share of passes correlates +0.78 (Spearman) with the length of the longest straight and −0.14 with the following gain on it. The second correlation is indistinguishable from zero (p = 0.54).
  • Spa, Las Vegas and Baku have the longest straights (1,682–1,853 m) and three of the four highest full-throttle shares (56–65%). At the other end, the Hungaroring has the shortest straight (457 m) and the lowest share (11%).
  • The Hungaroring's +33.5 km/h following gain is the artefact the chapter flags (a short run where the window alignment fails). It is the only point that makes the gain correlation negative. Without it, the correlation is −0.005 and the straight-length correlation is still +0.75.
  • Monza is the exception that shows what the length measure misses. It has the highest full-throttle share (78%), but its longest continuous full-throttle run on the pole lap is only 980 m, because the chicanes split the lap into several fast sections. What matters is how much of the lap is spent at full throttle, which one straight's length only approximates.
  • Why the gain does not help. The following gain varies little between circuits (mostly 7–17 km/h), and any car within a second gets it. Whether a pass is completed on a straight depends on whether the straight is long enough for that gain to close the gap, as B7 shows.

Chapter 36

Chapter 36 — Weather Analytics · exercises · verification script: appendices/code/answers_part2_ch36.py

Worked in the chapter. B1–B8 (all of Part B), D1 and D3 have full solutions or discussions in the exercises file; open the Solution, What the data show or Discussion blocks there. Part C has only a block of hints and partial results, so four Part C answers follow, and D2. C2, C3, C8 and D2 read the chapter's caches in code/_cache/, so run the chapter's scripts 01–03 and case_study_02.py first if that folder is empty.

Every degradation number below uses the canonical fuel correction (the toolkit's assumed 100 kg at 0.03 s/kg), except the practice-against-race comparison in D2, which uses raw slopes on both days as Case Study 2 does.

C2. Compare these drivers: the hottest and coldest races

We take the chapter's stint table (dry stints with at least 8 usable clean laps) for the two races and summarise by compound.

S = pd.read_parquet(CACHE / "stint_deg_temp.parquet").dropna(subset=["track_c"])
d = S[(S.year == 2026) & S.circuit_ref.isin(["monza", "vegas"])]
d.groupby(["compound", "circuit_ref"]).agg(deg_canonical=("deg_canonical", "median"),
                                            share_positive=("deg_canonical", lambda v: (v > 0).mean()))
                      stints  track_c  deg_canonical  deg_raw  share_positive
compound circuit_ref                                                         
HARD     monza            13   53.991          0.031   -0.025           0.846
MEDIUM   monza            12   53.727          0.037   -0.020           1.000
         vegas            15   13.574         -0.027   -0.087           0.200
SOFT     monza             3   54.950          0.089    0.032           1.000
         vegas            24   14.106         -0.037   -0.097           0.125
                  track_c  deg_canonical  stints
circuit_ref year                                
monza       2023   43.355          0.088      44
            2024   46.045          0.043      47
            2025   42.893          0.012      31
            2026   53.980          0.036      28
vegas       2023   17.761         -0.052      36
            2024   17.315          0.057      50
            2025   17.316          0.013      34
            2026   14.100         -0.028      39
temperature gap 40.2 C x within-circuit slope 0.00159 = +0.064 s/lap expected from temperature alone
  • The table. Only MEDIUM appears at both races. Monza ran MEDIUM and HARD (and three SOFT stints), and Las Vegas ran MEDIUM and SOFT, with no HARD stint long enough to pass the 8-lap filter.
  • MEDIUM: Monza +0.037 s/lap, with every stint positive. Las Vegas −0.027 s/lap, with only 20% of stints positive.
  • SOFT at Las Vegas: −0.037 s/lap, only 12.5% of stints positive. A negative canonical slope means the stint got faster by more than the assumed fuel burn explains; Las Vegas is one of the low-wear circuits in the chapter's circuit table.
  • Why the comparison says almost nothing about the within-circuit effect.
  • The gap is too big for temperature to explain. A 40.2 °C difference at the within-circuit slope (0.00159 s/lap per °C) predicts +0.064 s/lap. The observed MEDIUM difference is very close to that (0.037 − (−0.027) = 0.064 s/lap), but that agreement is a coincidence of two different circuits, not a test.
  • Each circuit's own history is noisier than its temperature. Las Vegas ran at almost the same track temperature in 2023, 2024 and 2025 (17.3–17.8 °C), yet its median canonical slope ranged from −0.052 to +0.057 s/lap. Monza's spread across 2023–26 (+0.012 to +0.088) is just as wide and does not follow its temperatures (the hottest year, 2026, is in the middle).
  • Everything else differs too. The two circuits differ in layout, surface, energy demand, compound allocation and time of day. A two-race comparison confounds all of that with temperature, which is why the chapter estimates the slope within circuits.

C3. Build the strategy: re-fit the temperature slope by season

We run the chapter's regression (canonical deg on stint track temperature, compound and circuit fixed effects, standard errors clustered by race) one season at a time. The last column is the spread of stint track temperature around each circuit's mean, which is where a fixed-effects slope gets its information.

for y, d in S.groupby("year"):
    f = smf.ols("deg_canonical ~ track_c + C(compound) + C(circuit_ref)", data=d).fit(
        cov_type="cluster", cov_kwds={"groups": pd.factorize(d.session_key)[0]})
season  per_10C      lo     hi  stints  races  within_circuit_sd_C
  2023   0.0019 -0.0675 0.0712     830     19               1.4844
  2024   0.0049 -0.0550 0.0648     832     20               1.1695
  2025  -0.0282 -0.2140 0.1576     856     20               0.7585
  2026   0.0309 -0.0435 0.1053     744     17               1.3781
pooled   0.0169  0.0077 0.0260    3262     76               5.6265
2026 minus 2023-25 slope: +0.0200 per 10 C [+0.0032, +0.0368]
  • The pooled slope reproduces the chapter: +0.0169 s/lap per 10 °C [+0.0077, +0.0260].
  • Season by season, the slope is not identified. The four estimates range from −0.028 to +0.031, and every interval spans zero by a wide margin (the 2025 interval is 0.37 s/lap wide).
  • The reason is in the last column. Within one season each circuit hosts one race, so with circuit fixed effects the slope can use only the temperature differences between stints of the same race. Those are small: a standard deviation of 0.8–1.5 °C, against 5.6 °C when the same circuit is compared across years. They are also confounded with when in the race a stint runs (fuel, track evolution, a cooling evening). The pooled estimate gets its information from the year-to-year differences at a circuit, which a single-season fit throws away. So "is +0.017 stable across seasons?" cannot be answered this way. The single-season fits are too weak to contradict it.
  • Does 2026 differ? A pooled model with a 2026 interaction says the 2026 slope is +0.020 s/lap per 10 °C steeper [+0.003, +0.037]. That is a hint that the new cars and tyres are more temperature-sensitive. But it rests on one season of 17 races, each the only 2026 race at its circuit, and the interval's lower end is close to zero. Treat it as a question for the 2027 data, not a result.

C5. Predict the race: rain at the start

For every Grand Prix we look for a rain flag in the weather records from the 60 minutes before lap 1, and for any car on intermediates or wets on lap 1. For comparison we score the weekend signal (rain or wet tyres in an earlier session) against the same outcome.

t1 = L.loc[L.lap_number == 1, "date_start"].min()
wm = w[(w.date >= t1 - pd.Timedelta(minutes=60)) & (w.date < t1) & (w.circuit_ref == r.circuit_ref)]
pre_rain = int(wm.rainfall.max())
wet_lap1 = int(L[L.lap_number == 1].compound.isin(["INTERMEDIATE", "WET"]).any())
Grands Prix: 91; races with >= 1 weather record in the 60 min before lap 1: 91; median records in the window 58
wet tyres on lap 1      0  1  All
rain in 60 min before            
0                      77  1   78
1                       6  7   13
All                    83  8   91
  pre-race rain = 1: wet lap 1 in 7/13 = 53.8% [29.1%, 76.8%]
  pre-race rain = 0: wet lap 1 in 1/78 = 1.3% [0.2%, 6.9%]
  earlier-session rain = 1: wet lap 1 in 5/37 = 13.5% [5.9%, 28.0%]
  earlier-session rain = 0: wet lap 1 in 3/54 = 5.6% [1.9%, 15.1%]
races with a wet lap 1:
                      event  pre_rain  earlier_rain  n_wet_lap1  records
           2024 Canadian GP         1             1          20        4
          2024 São Paulo GP         1             1          19       60
         2025 Australian GP         1             0          20       60
            2025 British GP         1             0          14       56
            2025 Belgian GP         1             1          20       60
           2026 Canadian GP         0             1           7       60
2026 Bahrain GP in Malaysia         1             0           9       60
          2026 São Paulo GP         1             1          22       53
  • The 2×2 table. 13 of 91 Grands Prix had rain in the hour before lap 1, and 7 of those 13 (53.8% [29.1, 76.8]) started with at least one car on wet-weather tyres. Without pre-race rain the figure is 1 of 78 (1.3% [0.2, 6.9]).
  • The pre-race signal is far stronger than the weekend signal. For the same outcome, rain earlier in the weekend gives 13.5% against 5.6%, and the two intervals overlap heavily. The chapter's 35% against 15% is for a different outcome: rain or wet tyres at any point in the race.
  • The exceptions.
  • The one wet lap 1 without pre-race rain is the 2026 Canadian GP, where 7 cars started on intermediates. The station flag was dry for the hour before the start, so a plausible reading is a track still wet from earlier rain. That is a reminder that the flag records rain falling, not water on the track.
  • In the 2026 Bahrain GP in Malaysia, rain fell in the window but stopped before the start, and 9 cars (about half the field) still started on intermediates, as the hint says.
  • The 2024 Canadian GP has only 4 records in the window, so its row rests on very little data.
  • Caveat. Eight wet starts is a small sample. The conclusion that rain in the last hour is the signal that matters is robust, but the 54% is not a precise rate.

C8. Compare these drivers: wind at Jeddah

wind_long.parquet keeps the within-group (driver × session × trap) deviations of trap speed and of the two wind components. It does not keep the session key or the time-trend term, so we identify Jeddah's sessions by (year, kind), which is unique at one circuit, and refit without the time trend. That is why the pooled value differs from the chapter's −0.68.

J["sess"] = J.year.astype(str) + "_" + J.kind
X, y = d[["A_w", "B_w"]].to_numpy(float), d.v_w.to_numpy(float)
b = np.linalg.lstsq(X, y, rcond=None)[0]                     # A = along-heading component (headwind if north-up)
# cluster bootstrap by session, 400 draws, seed 42
Jeddah: 10,083 lap-trap readings, sessions 13 (['2023_FP1', '2023_FP2', '2023_FP3', '2023_Q', '2023_R', '2024_FP1', '2024_FP2', '2024_FP3', '2024_R', '2025_FP1', '2025_FP2', '2025_FP3', '2025_R'])
        group   obs  sessions      A   A_lo   A_hi      B  wind_sd
          all 10083        13 -0.916 -2.012 -0.233  0.334    0.701
trap=i1_speed  2825        13  0.289 -0.010  0.777  0.328    0.690
trap=i2_speed  3629        13 -0.961 -3.329  0.183  0.956    0.683
trap=st_speed  3629        13 -1.600 -2.617 -0.926 -0.128    0.728
    year=2023  4208         5 -1.118 -2.637  0.255  0.059    0.706
    year=2024  3181         4 -0.710 -4.017  2.229  0.077    0.712
    year=2025  2694         4 -0.835 -2.817 -0.574  1.049    0.682
     kind=FP1  1345         3 -1.180 -2.803  2.768  0.801    0.602
     kind=FP2  1414         3 -3.947 -4.318 -2.165 -2.068    0.702
     kind=FP3   452         3  1.602 -3.676  1.909  0.181    0.746
       kind=R  6617         3 -0.572 -0.985 -0.351  0.625    0.711
chance alone, 24 circuits at 5% (two-sided): expected 1.2; P(>=1) 0.708; P(>=2) 0.339
one-sided (CI below 0 only, 2.5% each): expected 0.60; P(>=2) 0.120
  • The effect is carried by one trap. The speed trap (st_speed) gives −1.60 km/h per m/s [−2.62, −0.93]. The first intermediate trap gives +0.29 [−0.01, +0.78], and the second gives −0.96 [−3.33, +0.18]. A real wind effect should show at every trap that sits on a straight, because the along-heading component is computed from each trap's own direction. One trap carrying it points instead to that trap's location or orientation (the chapter's north-up assumption cannot be checked).
  • The seasons agree in sign but not in significance. All three are negative (−0.71 to −1.12), and only 2025's interval excludes zero.
  • The session kinds disagree. FP2 gives −3.95, FP3 +1.60, and the race −0.57. These rest on three sessions each, so their bootstrap intervals are unreliable (a cluster bootstrap with three clusters can draw only a handful of distinct samples). They should not be read as evidence either way.
  • The chance of this happening by luck is high. With 24 circuits each tested at the 5% level, the expected number of significant results is 1.2. The chance of two or more is 0.34. Counting only the negative direction (2.5% each), it is still 0.12. So two significant circuits out of 24, with one carried by a single trap, is about what noise produces.

D2. Design the setup: hot Sunday at the Hungaroring

We take the chapter's one-stop / two-stop line for the Hungaroring and shift its median degradation 10 °C cooler with conditions.temp_adjusted_deg. We then check the shift at both ends of the slope's 95% interval, and set it against what happened in the four races and Case Study 2's practice-against-race pairs.

adj = conditions.temp_adjusted_deg({"median": h.deg}, h.track, h.track - 10)
F = pd.read_parquet(CACHE / "fp2_vs_race_deg.parquet")         # Case Study 2: raw FP2 vs raw race slopes
Hungaroring: laps 70, pit loss 21.144 s, d* = 12 x pit / N^2 = 0.0518 s/lap; median canonical deg 0.0583 at median stint track 46.8 C (deg_C_needed -3.9)
temp_adjusted_deg, -10 C: 0.0424 s/lap -> margin to d* +0.0094
  slope 0.00062/C: adjusted deg 0.0521 (one-stop if below 0.0518)
  slope 0.00257/C: adjusted deg 0.0326 (one-stop if below 0.0518)
 year  finishers  stops_median  one_stoppers  two_plus
 2023         17           2.0             0        17
 2024         19           2.0             1        18
 2025         19           1.0            10         9
 2026         19           2.0             2        17
 race_sk             event compound  fp_deg  fp_track  fp_n  race_deg  race_track  race_n   err      dT   adj  err_adj
    9133 2023 Hungarian GP   MEDIUM   0.131    32.350    14    -0.010      48.340      21 0.142 -15.990 0.157    0.167
    9566 2024 Hungarian GP   MEDIUM   0.116    44.278    13     0.014      45.354      18 0.103  -1.076 0.118    0.104
    9928 2025 Hungarian GP   MEDIUM   0.099    35.950    15    -0.019      31.459      21 0.118   4.490 0.092    0.111
   11342 2026 Hungarian GP   MEDIUM   0.159    29.217    12     0.022      51.608      19 0.137 -22.391 0.195    0.172
   ...

The argument from temperature. - The Hungaroring's critical rate is d = 12 × 21.144 / 70² = 0.0518 s/lap. Its median canonical degradation, 0.0583 s/lap at a median stint track temperature of 46.8 °C, is past that line, so the chapter's model favours two stops. - A Sunday 10 °C cooler lowers the rate by 0.0159 s/lap, to 0.0424 s/lap, which is 0.0094 below the line. On the central slope, a one-stop becomes viable. - The margin is not robust. At the low end of the slope's interval (0.00062 s/lap per °C), the adjusted rate is 0.0521, a hair above the line. The one-stop case depends on the temperature effect being at least middling. - The races are consistent with this.* The coolest Hungarian GP in the data, 2025 at 31.3 °C, is the only one where most finishers one-stopped (10 of 19). In the three hot years (44–52 °C), 17–18 finishers stopped twice or more. Four races cannot isolate temperature from everything else that differed in 2025, but they point the same way.

What practice cannot tell you, from Case Study 2. - Friday's degradation is not Sunday's. At the Hungaroring, raw FP2 MEDIUM degradation overstated the race's by 0.10–0.14 s/lap in every year. That error is six to nine times the 10 °C temperature effect. Practice fuel loads are unknown, and the race is run on a rubbered-in track. - Adjusting for temperature does not fix the error. Across all of Case Study 2's pairs it made the error worse (squared error +9.6%). At the Hungaroring in 2026, practice was 22 °C cooler than the race, and adjusting for that pushed the forecast further from the race value. - What to take from practice instead. - The ranking of compounds and whether any compound grains or falls off a cliff on a long run. - The pace gap between compounds. - Whether the cooler conditions move a compound out of its operating window (Chapter 5). - What to rely on for the rate itself. The circuit's race history, shifted for the forecast temperature, is a better base than Friday's long runs.

The brief. Plan a one-stop as the base case if the forecast holds, keep the two-stop as the reaction plan, and decide after the first stint's observed degradation, not on Friday's.

Chapter 37

Chapter 37 — Reliability, Penalties, and Race Control · exercises · verification script: appendices/code/answers_part2_ch37.py

Worked in the chapter. B1–B8 (all of Part B), C1, C2, C8 and D1–D4 (all of Part D) have full solutions or expected outputs in the exercises file; open the Solution, Expected output or Reveal blocks there. C3 below reads the chapter's cached file code/_cache/penalised_starts_2023_26.csv, which 05_grid_penalties.py writes. Run that script first if the cache is empty.

C3. Build the strategy: recovery by period

We refit the chapter's recovery regression (gained ~ green_circuit + drop + quali_position, HC1 errors) on each half of the sample. For each half we also compute the smallest effect the sample could detect with 80% power at the 5% level, which is about 2.8 standard errors.

F = pd.read_csv(CH37 / "code" / "_cache" / "penalised_starts_2023_26.csv")
for lab, g in (("pooled 2023-26", F), ("2023-24", F[F.year <= 2024]), ("2025-26", F[F.year >= 2025])):
    m = smf.ols("gained ~ green_circuit + drop + quali_position", data=g).fit(cov_type="HC1")
    mde = 10 * 2.80 * m.bse["green_circuit"]          # places per 10 green passes
finishers who started >= 5 places behind qualifying or from the pit lane: 41
  pooled 2023-26  n=41  per 10 green passes +0.75 places (95% CI +0.22 to +1.28), half-width 0.53; drop coef 1.04; R^2 0.46
  2023-24         n=18  per 10 green passes +0.48 places (95% CI -0.55 to +1.51), half-width 1.03; drop coef 0.68; R^2 0.18
                  minimum detectable effect (80% power) ~ 1.47 places per 10
  2025-26         n=23  per 10 green passes +1.02 places (95% CI +0.63 to +1.41), half-width 0.39; drop coef 1.23; R^2 0.69
                  minimum detectable effect (80% power) ~ 0.56 places per 10
  • The pooled fit reproduces the chapter: +0.75 places per 10 green passes (0.22–1.28), n = 41.
  • 2023–24 (n = 18): +0.48 places per 10 green passes, with an interval of −0.55 to +1.51 that includes zero. That is the interval the exercise expected. Its half-width (1.03) is twice the pooled one, and the sample could only have detected an effect of about 1.5 places per 10 passes, twice the pooled estimate.
  • 2025–26 (n = 23): +1.02 (0.63–1.41). This is surprisingly tight for 23 cars. HC1 errors on a small sample are themselves imprecise, so do not read the narrow interval as strong evidence that the effect grew.
  • Is the coefficient stable? The two point estimates (+0.48 and +1.02) differ by about half a place per 10 passes, but the 2023–24 interval contains the 2025–26 estimate. The data cannot tell a stable effect from a changed one. With 18–23 cars per period, a split this fine mostly measures noise. The pooled estimate is the one to use.

C4. Analyze this session: a penalty timeline for the 2026 Mexico City GP

For each penalty, the function finds the first later PENALTY SERVED message for the same car and lists the driver's pit in-laps from the announcement up to that message.

def penalty_timeline(session):
    ev = rl.rc_events(session=f1data.session_key(session))
    pen = rl.penalty_table(events=ev)
    served = ev[ev.event == "penalty served"]
    lp = f1data.laps(session)
    for _, p in pen.iterrows():
        sv = served[(served.date > p.date) & served.cars.apply(lambda c: p.car in c)]
        s_lap = sv.lap_number.iloc[0] if len(sv) else np.nan
        ins = lp[(lp.driver_number == p.car) & lp.is_pit_in_lap & lp.lap_number.between(p.lap, s_lap)]
acronym pen_type                                     reason  announced_lap  served_lap pit_in_laps_between
    LEC  5s time LEAVING THE TRACK AND GAINING AN ADVANTAGE           12.0        30.0                [27]
    RUS 10s time                        CAUSING A COLLISION           13.0        37.0                [33]
    PER  5s time                   SPEEDING IN THE PIT LANE           46.0        70.0                [59]
    HUL 10s time                        CAUSING A COLLISION           51.0        70.0                [59]
  LEC: all pit in-laps [27, 45], laps completed 71
  RUS: all pit in-laps [33, 44, 45], laps completed 71
  PER: all pit in-laps [1, 30, 43, 44, 45, 59], laps completed 71
  HUL: all pit in-laps [31, 45, 59], laps completed 71
neutralised laps (any car): SC [43, 44, 45, 59, 60, 61, 62] VSC [7, 8] RED [44, 45, 46]
  • Four rows, as expected. The announced and served laps match the exercise: Leclerc 12 → 30, Russell 13 → 37, Pérez 46 → 70 and Hülkenberg 51 → 70.
  • All four were served at a stop. Each driver has exactly one pit in-lap between the announcement and the served message:
  • Leclerc's 5 s at his lap-27 stop.
  • Russell's 10 s at his lap-33 stop.
  • Pérez's 5 s and Hülkenberg's 10 s at their lap-59 stops, both under the late safety car.
  • The served message is not the stop. The message lags the stop by 3 laps (Leclerc), 4 laps (Russell) and 11 laps (Pérez, Hülkenberg). Use the pit in-lap to time the service, and the message only to confirm it.
  • A caution on the in-laps. The stops on laps 44–45 fall in the safety-car and red-flag window. Pérez's pit-lane speeding penalty was announced on lap 46, just after it, so the lap-45 stops cannot be the ones that served any of these penalties.

C5. Predict the race: simulated DNFs per race

We sample retirement laps for 10,000 races with sample_dnf and compare the count of retirements per race with the Jolpica results.

h = rl.dnf_hazard(era="2022-25 ground effect")             # and rl.dnf_hazard(years=[2026])
ret = rl.sample_dnf(57, h, n_cars=10_000 * n_cars, rng=np.random.default_rng(42)).reshape(10_000, n_cars)
k = np.isfinite(ret).sum(axis=1)                            # DNFs per simulated race
2022-25: 20 cars x 57 laps, 10,000 races: mean DNFs 2.46 (n_cars x P(DNF) = 20 x 0.123 = 2.45); var 2.14; zero-DNF share 7.0%
   observed: 92 races, mean DNFs 2.53, var 2.82, zero-DNF races 10 (10.9%), mean starters 19.9
2026: 22 cars x 57 laps, 10,000 races: mean DNFs 3.83 (n_cars x P(DNF) = 22 x 0.174 = 3.82); var 3.12; zero-DNF share 1.5%
   observed: 21 races, mean DNFs 3.95, var 2.75, zero-DNF races 0 (0.0%), mean starters 21.6
  • The means match. For 2022–25 the simulation gives 2.46 DNFs per race, against 20 × P(DNF) = 2.45 and an observed 2.53. For 2026 (22 cars) it gives 3.83, against 3.82 and an observed 3.95. The exercise's "about 3.5" for 2026 assumed 20 cars. With the actual 22-car fields the answer is 3.8.
  • The zero-DNF share comes out the other way round from the expected shape. For 2022–25 the simulation gives zero DNFs in 7.0% of races, fewer than the 10.9% (10 of 92) observed. Clustering explains it, but it works in the opposite direction from the exercise's guess:
  • When retirements cluster (one crash takes out two cars), the count per race has a larger variance than independent sampling gives. The observed variance is 2.82 against the simulated 2.14.
  • With the same mean, a more spread-out count puts more weight on both tails: more clean races and more carnage races. So real data show more zero-DNF races, not fewer.
  • 2026 cannot test it. No 2026 race was free of retirements (0 of 21), and the simulation's 1.5% predicts only 0.3 such races in 21. The 2026 observed variance (2.75) is even below the simulated value, which 21 races cannot distinguish from chance.
  • What independent sampling misses. Lap-1 multi-car incidents and debris that causes a second failure make retirements depend on each other. A simulator that needs realistic race-to-race variation should sample some incidents that remove two cars at once.

C6. Compare these drivers: in-race penalties by team

We attach each penalty from penalty_table (GPs 2023–26) to its team through the session's results, count car-races per team, and compare the counts with a common rate using a chi-square goodness-of-fit test.

pen = pen.merge(res.rename(columns={"driver_number": "car"}), on=["session_key", "car"])
T = pd.concat([res.groupby("team_ref").size().rename("car_races"),
               pen.groupby("team_ref").size().rename("penalties")], axis=1)
T["expected"] = T.penalties.sum() / T.car_races.sum() * T.car_races
chi2, p = stats.chisquare(T.penalties, T.expected)
penalties 204 (unmatched to a team 0); car-races 1859; overall 0.110 per car per race
              car_races  penalties  per_car_race  expected
team_ref
williams            181         26         0.144    19.862
audi                 42          6         0.143     4.609
red_bull            182         26         0.143    19.972
alpine              182         25         0.137    19.972
...
ferrari             182         14         0.077    19.972
mclaren             182         13         0.071    19.972
sauber               96          4         0.042    10.535
alfa                 44          1         0.023     4.828
chi-square = 18.62, df = 13, p = 0.135
teams with >= 100 car-races only (9): chi-square = 10.06, df = 8, p = 0.261
  • The overall rate is 0.110 penalties per car per race, which reproduces the chapter's PenaltyRisk (0.111). There are 14 team refs because the renames are kept separate (alfa → sauber → audi, alphatauri → rb, plus cadillac in 2026).
  • Most and least penalised. Williams and Red Bull (26 each, 0.14 per car-race) are at the top, with Alpine (25) close behind. McLaren (13, 0.071) and Ferrari (14, 0.077) are at the bottom among the full-time teams, and Sauber (4 in 96) and Alfa Romeo (1 in 44) have the lowest rates of all.
  • The spread is about what chance produces. The chi-square statistic is 18.62 on 13 degrees of freedom (p = 0.135). Restricted to the nine teams with at least 100 car-races, it is 10.06 on 8 (p = 0.261).
  • The verdict. The data give no evidence that some teams are penalised more often than a common Poisson rate would produce. A team-level penalty multiplier in a simulator would be fitting noise. Use the field rate.

Chapter 38

Chapter 38 — F1 Betting Analytics · exercises · verification script: appendices/code/answers_part2_ch38.py

Worked in the chapter. B1–B10 (all of Part B) and D1 have full solutions in the exercises file; open the Solution or Reveal blocks there.

Every price below is hypothetical. The book's data contain no historical odds, so each book is built with betting.hypothetical_book() from model probabilities plus a stated margin. The model probabilities are Chapter 26's walk-forward predictions. C7 and C9 read the chapter's cached tables fastest_laps_2014_2026.csv and h2h_2014_2026.csv, which 07_markets.py writes.

C1. Analyze this session: a hypothetical book for the 2026 Mexico City GP

We copy the United States GP block of 01_odds_math.py and change the round to 19. The book is the three-model consensus (grid baseline, logit and GBM) with an 18% margin, using the power method, rounded down to a ladder.

race = w[(w.year == 2026) & (w["round"] == 19) & w.model.isin(["grid", "logit", "gbm"])]
piv = race.pivot_table(index="abbreviation", columns="model", values="p_win")
piv["consensus"] = piv[["grid", "logit", "gbm"]].mean(axis=1); piv["consensus"] /= piv.consensus.sum()
odds = pd.Series(betting.hypothetical_book(piv.consensus.to_numpy(), 0.18, "power"), index=piv.index)
rep = betting.edge_report(piv.gbm, odds, method="power", min_edge=0.05, kelly_fraction=0.25, cap=0.05)
race: Mexico City Grand Prix; booksum 119.2%
              grid  finish    odds  implied  multiplicative  additive  power   shin  consensus    gbm
HAM            1.0     2.0    2.60    38.46           32.27     34.40  34.59  34.48      34.70  30.75
RUS            2.0     6.0    3.25    30.77           25.81     27.36  26.99  27.36      26.92  36.00
LEC            3.0     4.0    5.70    17.54           14.72     15.26  14.46  15.12      14.38  13.58
VER            5.0     1.0    7.60    13.16           11.04     11.24  10.50  11.07      10.48  10.11
ANT            4.0     3.0    9.80    10.20            8.56      8.54   7.92   8.35       7.99   5.67
NOR            6.0     5.0   28.00     3.57            3.00      2.47   2.47   2.33       2.43   2.13
HAD            7.0     9.0   60.00     1.67            1.40      0.73   1.06   0.76       1.05   1.14
HUL           10.0    14.0  140.00     0.71            0.60      0.00   0.41   0.17       0.41   0.06
...
              grid   pos    odds  implied   fair  p_model     ev  stake    bet
RUS            2.0   6.0    3.25    30.77  26.99    36.00  16.99   1.89   True
HAM            1.0   2.0    2.60    38.46  34.59    30.75 -20.06   0.00  False
...
bets clearing +5%: ['RUS']
  • The methods agree at the top and split on long shots, as expected. For the top five, the four methods are within about 2 points of one another. For Hülkenberg at 140.0, they range from 0.00% (additive) to 0.60% (multiplicative). The power method again tracks the consensus most closely, since the book was built with it.
  • One bet clears +5%. The GBM puts Russell at 36.0% against a power-fair 27.0% at 3.25, an EV of +17.0% and a quarter-Kelly stake of 1.89% of the bankroll.
  • The result. Russell started second and finished sixth, so the bet lost. Verstappen won from fifth on the grid. He was priced at 7.60 with a GBM probability of 10.1% (EV −23%), so no rule in this chapter would have backed him.
  • What to take from it. One race says nothing about whether the Russell edge was real. The GBM's disagreement with the consensus (36.0% against 26.9%) is the kind of edge the §38.9 backtest says to distrust until it has been tested against a market that includes the GBM's own information.

C2. Calibration by era

We bin the GBM's walk-forward win probabilities with the chapter's bins, separately for each era.

g["bin"] = pd.cut(g.p_win, [0, 0.01, 0.03, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 1.0], include_lowest=True)
for era, m in (("2014-2021", g.year <= 2021), ("2022-2026", g.year >= 2022)):
    t = g[m].groupby("bin", observed=True).agg(n=("win", "size"), pred=("p_win", "mean"),
                                               exp_wins=("p_win", "sum"), wins=("win", "sum"))
2014-2021: 160 GPs
                   n    pred     obs  exp_wins  wins
(-0.001, 0.01]  2547  0.0009  0.0043    2.2426    11
(0.01, 0.03]     206  0.0182  0.0243    3.7576     5
(0.03, 0.1]      137  0.0572  0.0949    7.8358    13
...
(0.5, 0.65]       71  0.5689  0.4366   40.3928    31
  forecasts < 10%: n 2890, expected wins 13.8, actual 29; < 1%: expected 2.2, actual 11
2022-2026: 113 GPs
                   n    pred     obs  exp_wins  wins
(-0.001, 0.01]  1648  0.0013  0.0000    2.0919     0
(0.01, 0.03]     182  0.0185  0.0220    3.3685     4
(0.03, 0.1]      188  0.0589  0.0426   11.0694     8
...
(0.5, 0.65]       52  0.5673  0.6346   29.4979    33
  forecasts < 10%: n 2018, expected wins 16.5, actual 12; < 1%: expected 2.1, actual 0
  • The eras add up to the chapter's totals. Below 10%, 13.8 + 16.5 = 30.3 expected wins (30.4 unrounded) against 29 + 12 = 41 actual.
  • The long-shot under-forecasting is entirely a 2014–2021 effect. In that era, forecasts below 10% won 29 times against 13.8 expected, and forecasts below 1% won 11 times against 2.2. In 2022–2026 the same forecasts won fewer races than predicted (12 against 16.5), and the sub-1% bin produced no winners at all.
  • The favourites mirror it. In 2014–2021, forecasts of 0.5–0.65 won 43.7% of the time against 56.9% predicted. In 2022–2026 they won 63.5%. The 2014–21 races had more upsets than the model expected, and the 2022–26 races had fewer.
  • What it means for a bettor. Any long-shot "value" the pooled table suggests came from the earlier era. Do not carry it into current prices.

C7. Fastest lap by team, 2019–2024

We attach each fastest-lap setter's team from history.results and compute the share of each team's fastest laps that followed a pit stop in the last 10 laps.

F = F.merge(r.rename(columns={"driver_ref": "driver"}), on=["year", "round", "driver"])
P = F[F.year.between(2019, 2024)]
t = P.groupby("team_ref").agg(n=("late_stop", "size"), late=("late_stop", "sum"))
2019-24 fastest laps: 127, late-stop 48 (37.8%)
               n  late  share            wilson_95
mercedes      43    16  0.372    37.2% (24.4-52.1)
red_bull      39    13  0.333    33.3% (20.6-49.0)
mclaren       17     5  0.294    29.4% (13.3-53.1)
ferrari       15     4  0.267    26.7% (10.9-52.0)
aston_martin   3     2  0.667    66.7% (20.8-93.9)
alfa           2     2  1.000  100.0% (34.2-100.0)
alphatauri     2     2  1.000  100.0% (34.2-100.0)
haas           2     2  1.000  100.0% (34.2-100.0)
alpine         1     1  1.000  100.0% (20.7-100.0)
rb             1     1  1.000  100.0% (20.7-100.0)
renault        2     0  0.000      0.0% (0.0-65.8)
  • The overall figure reproduces the chapter: 48 of 127 (37.8%).
  • Most late stops by count. Mercedes (16 of 43) and Red Bull (13 of 39) made the most. Their shares (37% and 33%) are close to the overall rate, and the four front-running teams all sit between 27% and 37% with overlapping intervals.
  • The midfield teams' shares are near 100%, but the counts are tiny. Aston Martin, Alfa Romeo, AlphaTauri, Haas, Alpine and RB set only one to three fastest laps each, and nearly all of them followed a late stop. That fits the logic of the rule: a midfield car can take the point only with a free stop and new soft tyres. With n ≤ 3, though, the intervals run from about 20% to 100%.
  • The honest summary. The data cannot rank teams by appetite for the late stop. They can say that a midfield fastest lap in this era almost always came from a late stop.

C9. H2H calibration by era

We refit the chapter's H2H logistic (grid order, qualifying gap and prior-share logit) on 2014–2018 and test it on each later period.

tr = h[h.year <= 2018]
lr = LogisticRegression(C=1.0).fit(X(tr), tr.a_ahead)
for lab, te in (("2019-2021", h[h.year.between(2019, 2021)]), ("2022-2026", h[h.year >= 2022])):
    te["p"] = lr.predict_proba(X(te))[:, 1]
train 2014-18 n 1021: coef grid-ahead +0.221, quali gap -0.512 per %, prior share logit +0.238
test 2019-2021 n 596: accuracy 0.680; better qualifier ahead 0.668; Brier 0.2181
                 n   pred    obs    k          wilson_95
(0.35, 0.5]    208  0.409  0.332   69  33.2% (27.1-39.8)
(0.5, 0.65]    194  0.579  0.644  125  64.4% (57.5-70.8)
(0.65, 0.8]     51  0.691  0.765   39  76.5% (63.2-86.0)
...
test 2022-2026 n 1121: accuracy 0.699; better qualifier ahead 0.685; Brier 0.2105
                 n   pred    obs    k          wilson_95
(0.35, 0.5]    321  0.413  0.386  124  38.6% (33.5-44.1)
(0.5, 0.65]    475  0.585  0.682  324  68.2% (63.9-72.2)
(0.65, 0.8]    154  0.699  0.870  134  87.0% (80.8-91.4)
...
  • Accuracy. The model is right 68.0% of the time in 2019–21 and 69.9% in 2022–26. The "back the better qualifier" rule scores 66.8% and 68.5%, so the model adds about 1.3 points in each period.
  • The under-confidence is not specific to the ground-effect era. It shows in 2019–21 too: pairs rated 0.58 went 0.64, and pairs rated 0.69 went 0.77 (63–86%).
  • But it is stronger after 2022. There, pairs rated 0.70 went 0.87 (81–91%), an interval that sits well above the prediction.
  • The reading. Qualifying order has become steadily more decisive for the race H2H since the 2014–18 training years, and most of all in 2022–26. A model fitted on older seasons will under-price the better qualifier, and more so the newer the season.

D3. The specialist tip

The tip is a −0.8% team-circuit residual last year. §38.8 measured how much of such a residual carries into the next year: the year-to-year slope is 0.109 over all pairs, 0.106 under stable rules and 0.123 across a rules reset.

  all pairs       slope 0.109: expected carry-over of a -0.80% residual = -0.087% of lap
  stable rules    slope 0.106: expected carry-over of a -0.80% residual = -0.085% of lap
  across a reset  slope 0.123: expected carry-over of a -0.80% residual = -0.098% of lap
  on an assumed 80 s lap: tip -0.80% = 0.640 s; expected carry-over 0.070 s; residual SD 0.676% = 0.541 s
  • The expected carry-over is 0.109 × 0.8% ≈ 0.09% of a lap. On an 80 s lap (an assumption, used only for scale) that is 0.07 s, against a year-to-year residual spread of 0.54 s.
  • Should it move your price? Only by a hair. In the chapter's stable-rules sample, residuals of at least 0.30% kept their sign the next year only 55.7% of the time, and kept 59% of their size on average among those large cases.
  • What would make the tip more trustworthy:
  • The same residual for several years in a row at this circuit, rather than one season. Repeated values average away the noise that dominates a single year.
  • A physical reason that persists, such as a car concept that suits the circuit's corner mix (Chapter 10's circuit profiles), with no rules reset in between.
  • The residual holding up in the weekend's own practice long runs. That is fresh information the market may not yet price.

D4. Four models, one race

A procedure fixed in advance: choose pooling weights that minimise the winner log loss of a linear mixture on 2014–2025 walk-forward predictions, then freeze them for 2026. The script searches a 0.1 grid over the three models with 2014–2025 walk-forward predictions.

  grid   winner log loss 2014-25: 1.4549
  logit  winner log loss 2014-25: 1.2961
  gbm    winner log loss 2014-25: 1.3273
  equal-weight average: 1.2692
  best linear pool on a 0.1 grid: grid 0.0, logit 0.6, gbm 0.4 -> 1.2524
  GPs in the fit: 252
  • The fitted pool is 0.6 logit + 0.4 GBM, with no weight on the grid baseline. Its log loss, 1.252, beats each model alone (logit 1.296, GBM 1.327) and the equal-weight average (1.269).
  • The fourth model cannot be weighted this way. The Chapter 27 Monte Carlo has no 2014–2025 walk-forward record in the book's data; its calibration file covers fifteen 2026 races. The procedure must either leave it out or give it a small weight fixed in advance. Its record in Chapter 38 (it under-rates pole-sitters, and its "phantom edges" returned −73%) argues for zero.
  • Why choosing after the edge reports is biased. Once you see which model shows an edge at the prices, picking that model selects on the gap between the model and the market. That gap is largest exactly where a model's error happens to be largest. The chosen "edge" is then inflated by construction, the same winner's curse as reporting the best of several backtests. Fixing the weights from past log loss, before any price is seen, removes the choice from the data you are about to bet on.

Chapter 39

Chapter 39 — Other Motorsport Analytics · exercises · verification script: appendices/code/answers_part2_ch39.py

Worked in the chapter. B1–B8 (all of Part B) and D1–D5 (all of Part D) have full solutions in the exercises file; open the Solution or Reveal blocks there.

The oval and refuelling profiles in boxbox.series are 🧪 illustrative: their parameters are assumptions, not data from any series. Only the F1-2026 profile is calibrated from the book's data snapshot. Conclusions below that rest on a 🧪 profile say so.

C1. Analyze this session: the last refuelling season against the first without

We apply the chapter's stop detector (a lap more than 7 s slower than the field median plus the driver's usual offset) to 2009, 2010 and 2011, using the chapter's finisher filter (classified, at least 90% of the winner's laps).

inferred = pd.concat([infer_stops(lp) for _, lp in L.groupby(["year", "round"])])
fin = fin[fin.is_classified & (fin.laps_completed >= 0.9 * fin.win_laps)]
f = fin.join(inferred.groupby(["year", "round", "driver_ref"]).size().rename("stops"),
             on=["year", "round", "driver_ref"]).fillna({"stops": 0})
 year  races  finishers  mean_stops  zero_stop  three_plus  stint_median  stint_q25  stint_q75  n_stints
 2009     17        278       2.047      0.007       0.162         0.333      0.240      0.418       839
 2010     19        344       1.599      0.073       0.186         0.327      0.207      0.554       889
 2011     19        374       2.925      0.000       0.626         0.250      0.192      0.318      1460
2011 recorded stops per finisher (Jolpica pit table): 2.69 (inferred 2.93)
Season Mean stops 0-stop share Stint share: median (IQR)
2009 (refuelling) 2.05 0.7% 0.333 (0.240–0.418)
2010 (no refuelling) 1.60 7.3% 0.327 (0.207–0.554)
  • The season means reproduce the chapter: 2.05 and 1.60.
  • The middle of the stint distribution barely moved. The median stint was a third of the race in both seasons. What changed is the spread: the 2010 upper quartile is over half a race (0.554 against 0.418). Freed from the fuel tank, one stint could run very long.
  • Read the 2010 zero-stop share with care. It jumps from 0.7% to 7.3%. Part of that is the detector, which cannot see a stop that does not stand out from the field. A stop made under a safety car, when the whole field is slow, does not stand 7 s above the field median, and Jolpica has no pit records before 2011 to check against. Treat the 0-stop column as a detector property as much as a race fact.
  • Why 2010 had fewer stops than 2011 (2.93). Both seasons banned refuelling, so the difference is the tyres. The single supplier changed from Bridgestone (2007–2010) to Pirelli (2011 onwards) (data/reference/champions_context.csv). In 2011 the median stint fell to a quarter of the race, and 63% of finishers made three or more stops. Tyre life, not fuel, set the stop count once refuelling was gone, so a change of tyre was enough to almost double it.
  • A check on the detector. The detector over-counts 2011 slightly: it finds 2.93 stops per finisher against 2.69 recorded in the Jolpica pit table.

C3. Build the strategy: a rule-profile sweep

We calibrate the 2026 profile exactly as 04_rule_profiles.py does, then call series.best_plan across degradation rates under 2026 rules and with refuelling allowed.

for dg in np.arange(0.02, 0.201, 0.02):
    a = series.best_plan(series.adapt(p26, deg_s_per_lap=dg), 6)
    b = series.best_plan(series.adapt(pref, deg_s_per_lap=dg), 6)
calibrated: pit lane 20.31 s + tyre change 2.9 s; deg 0.052 s/lap; 57 laps; tyre life 40; cliff 0.02
  deg  stops_2026    laps_2026  stops_refuel  laps_refuel
0.020           1         [28]             1         [29]
0.040           1         [28]             2     [19, 38]
0.052           1         [28]             2     [19, 38]
0.060           1         [28]             2     [19, 38]
0.080           1         [28]             2     [19, 38]
0.100           2     [19, 38]             2     [19, 38]
0.120           2     [19, 38]             3 [14, 28, 43]
...
0.180           3 [14, 28, 43]             3 [14, 28, 43]
0.200           3 [14, 28, 43]             3 [14, 28, 43]
  • The known answer reproduces. At the chapter's 0.052 s/lap, the best plan is one stop (lap 28) under 2026 rules and two stops (laps 19, 38) with refuelling.
  • Where the 2026 line steps up. It goes to two stops between 0.08 and 0.10 s/lap, and to three between 0.16 and 0.18.
  • Where the refuelling line steps up. It goes to two stops between 0.02 and 0.04 s/lap, and to three between 0.10 and 0.12.
  • The gap between the lines. Each refuelling step comes about 0.06 s/lap earlier in degradation. That matches the 0.061 s/lap of fuel "degradation" in B2: refuelling adds the fuel penalty to the tyre penalty, so the same stop count is reached at a lower tyre wear rate.
  • What holds and what does not. The positions of the steps depend on the 🧪 fuel burn, fuel effect and refuel rate. The ordering, with refuelling always calling for at least as many stops, does not.

C4. Predict the race: the window threshold

We rerun the paired Monte Carlo at a caution hazard of 0.02 per lap. The fixed plan is held constant, and the opportunistic policy's window_open varies. window_open = 0.7 means "pit under a caution only if the tank is below 30%". The seed and run count are the chapter's (seed 7, 1,500 paired runs).

p = series.adapt(series.OVAL, caution_rate=0.02)
fx = series.simulate_cautions(p, "fixed", n_runs=1500, seed=7)
for wo in (0.5, 0.6, 0.7, 0.8, 0.9):
    d = series.simulate_cautions(p, "opportunistic", window_open=wo, n_runs=1500, seed=7) - fx
OVAL profile: 200 laps, tank 60.0 kg, 1.1 kg/lap -> max green stint 55 laps; fixed mean 9024.9 s
 window_open tank_below  diff_mean  diff_p10  diff_p90  opp_wins
         0.5        50%     -4.137   -23.041    15.180     0.653
         0.6        40%     -8.043   -24.820     7.624     0.772
         0.7        30%    -10.077   -25.625     5.019     0.833
         0.8        20%     -9.102   -25.277     8.800     0.829
         0.9        10%     -6.185   -23.941    10.820     0.786
  • The known answer reproduces. At 0.7 the result is −10.08 s, with the opportunistic policy winning 0.833 of paired runs.
  • There is an interior optimum, near 0.7. The gain is −4.1 s at 0.5, peaks at −10.1 s at 0.7, and falls back to −6.2 s at 0.9.
  • A threshold that is too low hurts. Opening the window with half a tank left means pitting under cautions that come early in a stint. That adds stops: the car throws away fuel range it has already paid for and then needs another stop later.
  • A threshold that is too high hurts too. Waiting until the tank is below 10% means most cautions arrive while the window is still shut. The car then has to make its green-flag stop anyway, so the policy rarely gets a cheap stop.
  • What survives a change of assumptions. The location of the optimum depends on the 🧪 tank size, fuel burn and caution length. The shape, with a cost at both ends, follows from the trade-off itself.

C6. Analyze this session: the tow at Monza by rule set

We run the method of 06_slipstream_speed_trap.py on Monza only, splitting by rule set. The method takes clean, dry race laps (leaving out the race leader, whose interval of 0 means no car ahead) and measures each lap's trap speed against the same driver's clean-air median in that race (laps more than 3 s behind).

m = d[d.circuit_ref == "monza"]
m["band"] = pd.cut(m.gap_start, [0, 0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0], right=False)
for band, gg in g.groupby("band"):
    est, lo, hi = metrics.bootstrap_ci(gg.gain.values, stat=np.mean, n_boot=2000)
Monza 2023-2025: 3 races, 1919 laps; median clean-air trap 320 km/h; 1.0-2.5 s tow 3.06 km/h (n = 474)
 band   n  mean_gain_kmh    lo    hi
0-0.5 175          18.29 16.32 20.35
0.5-1 371          12.53 11.74 13.33
1-1.5 188           4.04  3.26  4.82
1.5-2 150           2.90  2.19  3.59
  2-3 215           1.88  1.14  2.59
  3-5 276           1.02  0.48  1.58
 5-10 384           0.60  0.10  1.09
Monza 2026: 1 races, 700 laps; median clean-air trap 308 km/h; 1.0-2.5 s tow 7.72 km/h (n = 181)
 band   n  mean_gain_kmh    lo    hi
0-0.5  73          13.33 11.04 15.38
0.5-1 132          12.46 11.29 13.70
1-1.5  84          10.15  8.96 11.38
1.5-2  54           5.68  4.34  6.89
  2-3  78           4.57  3.79  5.35
  3-5  89           0.73 -0.21  1.49
 5-10 123          -0.86 -2.68  0.22
  • The case-study levels reproduce: a 1.0–2.5 s tow of 3.06 km/h (2023–25) and 7.72 km/h (2026).
  • 2023–25: a cliff at 1 s. The gain is 18.3 km/h at 0–0.5 s and 12.5 km/h at 0.5–1 s, then drops to 4.0 km/h at 1–1.5 s. That is DRS switching off at its 1 s threshold. Beyond it, a small tow decays smoothly towards zero.
  • 2026: the curve's shape changes, not just its level. There is no cliff at 1 s. The gain is 12.5 km/h at 0.5–1 s and still 10.2 km/h at 1–1.5 s, 5.7 km/h at 1.5–2 s and 4.6 km/h at 2–3 s, before vanishing beyond 3 s. The effect fades gradually across 1–3 s instead of switching off at the DRS threshold.
  • Why the shape might change. The 2026 cars have no DRS, so there is no step at 1 s. The Overtake mode is triggered within 1 s at the detection point, but its extra deployment can carry into the next lap's trap, which would blur the edge. That is an inference: the data have no energy channel to confirm it.
  • The sample is thin. 2026 is a single Monza race (700 laps, about 50–130 per band), against three races for 2023–25. Clean-air trap speeds are also lower in 2026 (308 against 320 km/h). Read the 2026 curve as one race's evidence.

Chapter 40

Chapter 40 — Capstone: Your F1 Race Strategy Simulator · exercises · verification script: appendices/code/answers_part2_ch40.py

Worked in the chapter. A1–A10 (answers to Part A), B1–B9 (all of Part B), D1, D2 and M1 have full solutions in the exercises file; open the Answers, Solution, What happened or Answer blocks there.

The answers below reuse the chapter's cached Box Box runs rather than drawing new random numbers:

  • C2 and C3 read the pre-race inputs from the validation simulations in code/output/val_*.pkl, which 03_validation_suite.py writes.
  • C7 and D5 read code/output/pole_calibration.csv (1,500 races per race, seed 42), which 04_known_weaknesses.py writes.

Run those two scripts first if the files are missing.

C2. Compare these drivers: the 2026 Singapore GP top six

For each of the top six we take the actual strategy from cli.actual_strategies. We then ask cli.clean_optimum for the best stop laps for that car's own sequence and starting set, and add the one-stop 1-second window where there is one.

a = cli.actual_strategies(I.ctx.race_key).sort_values("position").head(6)
for r in a.itertuples():
    t = cli.clean_optimum(I, start_compound=r.compounds[0], start_age=int(r.first_set_age), max_stops=r.n_stops)
    best = t[t.sequence == r.sequence].stop_laps.iloc[0]
    if r.n_stops == 1:
        win = cli.one_stop_window(I, r.compounds[0], r.compounds[1], start_age=int(r.first_set_age))["window_1s"]
pit loss used: 24.43 s; deg S/M/H 0.038 / 0.023 / 0.035
 pos acronym  grid sequence  start_age stop_laps         status model_best                    window  inside
   1     VER     1      S-M          0     (32,)       (GREEN,)      (26,)                     20-31   False
   2     LEC     2    S-M-S          3  (24, 39)   (GREEN, VSC)   (16, 42) (each stop within 3 laps)   False
   3     ANT     4    S-M-S          3  (23, 39)   (GREEN, VSC)   (16, 42) (each stop within 3 laps)   False
   4     NOR     5      S-M          0     (32,)       (GREEN,)      (26,)                     20-31   False
   5     PIA     6    S-M-S          0  (33, 41) (GREEN, GREEN)   (19, 43) (each stop within 3 laps)   False
   6     HAM     3      M-S          0     (18,)       (GREEN,)      (36,)                     31-42   False
  • Verstappen reproduces. His best lap is 26 with a window of 20–31, and he stopped on lap 32. Norris, on the same new SOFT, made the same call on the same lap.
  • No car in the top six stopped inside the model's window. The one-stoppers went late: Verstappen and Norris stopped one lap after the window closed. Hamilton went very early on the reverse M-S sequence, on lap 18 against a model best of 36.
  • The two-stoppers did not follow the model's plan. Leclerc, Antonelli and Piastri ran S-M-S, but the model would have split those stints at 16/42 (19/43 for Piastri's new set). Leclerc and Antonelli stopped later the first time (24 and 23) and earlier the second time, on lap 39. That second stop was taken under the VSC on lap 39, the cheap option B2 prices.
  • What it says about the model. Singapore's pre-race wear inputs are low (0.023 s/lap on the MEDIUM), so the cost curves are flat and a few laps either way cost little. The model's timing is not wrong so much as indifferent. The real calls were driven by track position and a neutralisation, neither of which a clean-race optimum sees.

C3. Build the strategy: the fuel switch at the 2026 Barcelona GP

We refit the pre-race degradation on raw, default-corrected and data-corrected stint tables, as in 04_known_weaknesses.py. Then we add a fourth row that scales each compound's pre-race deg by the ratio of the race's own deg (strategy.fit_race_model) to the pre-race deg.

dm = dg.DegModel(use_temp=False).fit(T[T.date_start < I.ctx.date])            # T = raw / default / data table
_, hin = st.fit_race_model(I.ctx.race_key, pit_loss_s=I.pit_loss_s)
ratio = {c: race_deg[c] / I.deg[c] for c in cli.COMPS}
best = cli.clean_optimum(replace(I, deg={c: I.deg[c] * ratio[c] for c in cli.COMPS})).iloc[0]
pre-race (default) deg used by simulate: 0.067 / 0.058 / 0.050
race / pre-race ratio by compound: S 3.54, M 3.15, H 2.48
         version                   deg         best  n_stops
             raw 0.024 / 0.010 / 0.005       S-H 15        1
         default 0.067 / 0.058 / 0.050       S-H 29        1
            data 0.074 / 0.065 / 0.061 S-H-H 20, 43        2
hindsight-scaled 0.237 / 0.182 / 0.124 M-H-H 17, 41        2
cli.hindsight_optimum: M-H-H 17, 41
winner HAM: S-H-M-H stops (11, 27, 41) ('GREEN', 'GREEN', 'VSC')
  • The three fuel corrections reproduce the expected calls:
  • raw: one stop, S-H on lap 15
  • default: one stop, S-H on lap 29
  • data: two stops, S-H-H on laps 20 and 43
  • The hindsight-scaled row lands exactly on the hindsight optimum, M-H-H on laps 17 and 41. That is by construction. Scaling each compound's pre-race deg by race/pre-race simply replaces it with the race's own deg, 2.5 to 3.5 times higher, and the pit loss and rules are unchanged.
  • Even hindsight gives too few stops. Hamilton won with three stops (S-H-M-H on laps 11, 27 and 41), and the last was under a VSC. The model's best plan has two.
  • What decides the call here. The fuel correction moves the plan from one stop to two. But all three pre-race versions underestimate this race's wear by a factor of about three. The size of the degradation input, not the correction method, is what made Barcelona the suite's one MISS.

C5. Analyze this session: phantom stints at the 2025 Australian GP

We compare the stop counts of strategy.actual_strategies and the adapter's cli.actual_strategies, then print the raw OpenF1 stints for one car.

a = st.actual_strategies(s).set_index("acronym")
b = cli.actual_strategies(s).set_index("acronym")
ch = d[d.raw_stops != d.fixed_stops]
sts = f1data.stints(s, driver="NOR")
driver-races whose stop count changes: 15 of 20
         raw_stops  fixed_stops  phantom_stints
acronym
OCO              4            3               0
VER              3            2               0
NOR              3            2               0
ANT              3            2               0
ALB              3            2               0
HUL              3            2               0
...
BOR              3            2               0
ALO              1            0               0
raw OpenF1 stints for NOR:
 stint_number     compound  lap_start  lap_end  tyre_age_at_start
            1 INTERMEDIATE          1        2                0.0
            2 INTERMEDIATE          3       34                3.0
            3         HARD         35       44                1.0
            4 INTERMEDIATE         45       57                0.0
zero-length stints at this race: 0, by lap_start {}
ALO: 32 laps, status Retired; stints: [['INTERMEDIATE', 1, 2], ['INTERMEDIATE', 3, 32]]
  • No zero-length stint is left. The book's data build now drops them (132 across every session), so the phantom_stints column is 0 for every car, and 04_known_weaknesses.py finds none in any of the 91 Grands Prix.
  • The adapter still changes 15 of 20 counts. Norris's raw stints show why. His first INTERMEDIATE stint covers laps 1–2 from new, and the next begins on lap 3 on the same compound at a start age of 3: the set simply carried on. The build kept the two stints apart; the adapter merges them, because the compound matches and the start age is within 2 laps of where the previous stint ended.
  • Norris's real race: INTERMEDIATE to lap 34, HARD from lap 35 to lap 44, then INTERMEDIATE again. That is two stops, not three.
  • Why a whole field is affected. The same early-lap boundary appears for almost every car, so one race accounts for 15 of the 37 driver-races the adapter still changes in 2023–26.
  • Alonso's case. He drops from 1 stop to 0. He retired after 32 laps on his first INTERMEDIATE set, so his only "stop" was a stint boundary on the same set.
  • Which rule to trust. The adapter's 2-lap tolerance treats a set whose age carries on as the same set, which matches what happened on track here. A stricter rule needs the ages to match exactly and misses cases like these.

C7. Compare these drivers: the gradient-boosting model against the simulator

We add cli.gbm_probabilities for the grid-1 car to the chapter's pole-calibration runs.

P1 = P[P.scale == 1.0].set_index("round")
for rnd, r in P1.iterrows():
    g = cli.gbm_probabilities(cli.resolve_race(2026, int(rnd)))
    pg = g.set_index("code").p_win.get(r.grid1)
 round          race grid1  won   sim  sim_half_sd   gbm
     4         Miami   ANT    1 0.484        0.588 0.593
     6        Monaco   ANT    1 0.468        0.489 0.628
     7     Barcelona   RUS    0 0.395        0.511 0.548
...
    13       Italian   GAS    0 0.388        0.442 0.238
...
    19   Mexico City   HAM    0 0.203        0.208 0.307
    21     Las Vegas   VER    1 0.211        0.243 0.659
observed: grid-1 won 9/14 = 0.643
  sim          mean P(win) 0.395; Brier (grid-1 car only) 0.261
  sim_half_sd  mean P(win) 0.478; Brier (grid-1 car only) 0.224
  gbm          mean P(win) 0.518; Brier (grid-1 car only) 0.183
  • The gradient-boosting model is closer to the observed 9 of 14 (0.643). Its mean P(win) for the grid-1 car is 0.518, against 0.395 for the simulator and 0.478 for the simulator at half the pace SD.
  • It also scores best on this binary question. Its Brier score is 0.183, against 0.261 and 0.224.
  • All three under-rate the grid-1 car. The gradient-boosting model is the least biased.
  • Where they disagree most. At Las Vegas the simulator gave Verstappen 0.211 and the gradient-boosting model 0.659, and he won. At Monza the gradient-boosting model was the more sceptical (0.238 for Gasly, whose official pole lap fails the telemetry quality check in Chapter 19), and Gasly did not win.
  • Too few races to rank the models. Fourteen races cannot separate them with confidence, but the direction matches Chapter 26 and Section 40.6: history knows that the front of the grid wins, and the simulator's wide pace uncertainty spreads that probability too thinly.

D5. When the model and the base rate disagree

We score four candidate numbers for the grid-1 car's P(win) on the same 14 dry 2026 races:

  • the simulator as run;
  • the simulator at half the pace SD;
  • the 2023–26 pole-to-win base rate, 62.6%;
  • a 50/50 blend of the simulator and the base rate.
  simulator (SD x 1)             mean p 0.395; Brier 0.261; log loss 0.719
  simulator (SD x 0.5)           mean p 0.478; Brier 0.224; log loss 0.641
  base rate 0.626                mean p 0.626; Brier 0.230; log loss 0.652
  50/50 blend, sim + base rate   mean p 0.511; Brier 0.229; log loss 0.650
  observed 9/14; Las Vegas R21 simulator P(win, grid 1) = 0.211

The scores. - The raw simulator scores worst on both measures. - The base rate (0.230 Brier) and the blend (0.229) beat it. - The half-SD simulator scores best (0.224 and 0.641), but the "half" was chosen after seeing Chapter 27's finding, so its edge is partly fitted. - The base rate is not fully out of sample either: the 62.6% includes these 2026 races. - The differences between the last three rows are well inside what 14 races can resolve.

What we would publish. Not 20.9%. Every piece of evidence says the simulator under-rates the front of the grid: - the pole calibration of Section 40.6 (mean 0.395 against 9 of 14 won); - the C7 comparison above; - Chapter 26's finding that no model beat "pole wins" by a margin that excludes zero.

A defensible single number shrinks the simulator towards the base rate. The 50/50 blend gives 0.5 × 0.211 + 0.5 × 0.626 ≈ 0.42 for Verstappen at Las Vegas. Publish it with the statement that the simulator's own figure was 21% and that its pole-sitter probabilities are known to run low. The simulator's value lies in comparing strategies (the policy table and the stop window), not in the absolute win probability of the favourite.