Appendix B — Data Dictionary and Toolkit Reference

This appendix is the reference you keep open while you write code. It has five parts:

  1. The data dictionary (§B.1–B.4): every processed table, every column, its type, what it means, and how complete it is season by season.
  2. The canonical definitions (§B.5): the exact rules behind "clean lap", "pit loss", "degradation" and the other quantities every chapter shares.
  3. The toolkit reference (§B.6): every public function in toolkit/, with its signature and one line on what it does.
  4. The known data caveats (§B.7): every quirk, gap and trap found while writing the book, with the evidence for each in this snapshot.
  5. The Box Box reference (§B.8): every module of the progressive project in project/boxbox/, with its public functions.

Most of the tables below are generated, not typed. The script appendices/code/build_appendix_b.py reads the processed parquet files, introspects the toolkit and the Box Box package, computes the caveat evidence, and rewrites the generated blocks of this file. After you rebuild the data for a new race (Appendix J §J.7), run it again and this appendix describes your snapshot instead of ours:

python appendices/code/build_appendix_b.py

For a gentler introduction to the same tables, start with Appendix A, and for the story of how they were built, with Chapter 2.


B.1 The snapshot and how the tables fit together

OpenF1 processed build: 2026-11-25 22:22 UTC (469 sessions with laps). Jolpica history: Jolpica-F1 CSV dump (delayed) dated 2026-11-09 + API top-up, snapshot 2026-11-23. Generated by python appendices/code/build_appendix_b.py.

The book's data come in three layers:

layer where what
raw data/raw/openf1/, data/raw/jolpica/ the downloaded JSON files and the Jolpica CSV dump, untouched
processed data/processed/openf1/*.parquet, data/processed/history/*.parquet tidy tables built by scripts/build_openf1.py and scripts/build_jolpica.py
reference data/reference/*.csv, *.md sourced facts: regulations, tyres, records, business figures, circuits (§B.4)

Keys. Every OpenF1 table carries five key columns, which the per-table listings below omit to save space:

column type meaning
session_key int OpenF1's id for one session (FP1, qualifying, the race, a testing day). Joins every OpenF1 table.
meeting_key int OpenF1's id for the race weekend (or test) the session belongs to.
year int season
round int (nullable) Jolpica round number, matched by date (the Jolpica race within ±3 days of the OpenF1 race session), never by name. NA for testing.
kind text R, Q, S (sprint), SQ (sprint qualifying or shootout), FP1–FP3, T1–T3 (testing days)

Driver-level tables add driver_number (the car number in that session) and driver_ref (Jolpica's driver id). Within OpenF1, join on session_key + driver_number. Across sources, join on year, round and driver_ref, which the build maps for every OpenF1 driver. Team-level joins use team_ref, which is a Jolpica team id for that season: the Faenza team is alphatauri in 2023 and rb from 2024, the Hinwil team alfa in 2023, sauber in 2024–25 and audi in 2026.

Reading the coverage columns. In the OpenF1 tables, the four right-hand columns give the share of rows in that season (in %) where the column is not null; the (rows) line gives the row count. In the Jolpica tables the same columns are grouped by era: 1950–93, 1994–2005 (qualifying times arrive), 2006–10 (three-part knockout qualifying), 2011–22 (pit stops arrive) and 2023–26 (the OpenF1 years). "100" means complete; "0" means the column is empty for that period; "<1" means a handful of rows.


B.2 OpenF1 tables (data/processed/openf1/, 2023 → 2026 R21)

Load any of these through f1data: f1data.laps(session), f1data.stints(session) and so on, or the whole table with f1data.table(name). The laps table is the enriched one: the build attaches the stint, compound, tyre age, pit flags, track status, end-of-lap position and gaps, and weather to every lap, so you rarely need to join the other tables yourself.

championship: 3,623 rows

column type meaning 2023 2024 2025 2026
(rows) 844 950 922 907
entity text 'driver' or 'team' 100 100 100 100
driver_number float car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 67 68 67 67
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 66 63 65 65
team_name text team name (team rows) 33 32 33 33
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 99 95 98 98
position_start text championship position before the session (text) 96 97 97 100
position_current int position after the session 100 100 100 100
points_start float points before the session 100 100 100 100
points_current float points after the session 100 100 100 100

drivers: 9,605 rows

column type meaning 2023 2024 2025 2026
(rows) 2,252 2,457 2,455 2,441
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
acronym text three-letter driver code, e.g. VER 100 100 100 100
full_name text OpenF1 full name (surname in capitals, e.g. 'Kimi ANTONELLI') 100 100 100 100
first_name text given name 100 100 100 100
last_name text family name 100 100 100 100
broadcast_name text name as shown on the TV graphics, e.g. 'M VERSTAPPEN' 100 100 100 100
team_name text team name as entered that season 100 100 100 100
team_colour text team colour hex code (no '#') 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100
country_code text three-letter country code 100 100 0 0
headshot_url text OpenF1 link to a driver photo 96 95 95 97

intervals: 2,406,060 rows

column type meaning 2023 2024 2025 2026
(rows) 565,729 613,428 633,624 593,279
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
gap_to_leader_s float gap to the leader (s) 93 90 93 84
laps_behind_leader float laps down (0 on the lead lap) 99 99 99 100
interval_s float gap to the car ahead (s); 0.0 for the leader 99 99 99 99
interval_laps float laps to the car ahead when the interval was '+N LAP(S)', else 0 99 99 99 99

laps: 268,783 rows

column type meaning 2023 2024 2025 2026
(rows) 63,015 67,794 68,821 69,153
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100
acronym text three-letter driver code, e.g. VER 100 100 100 100
lap_number int lap number (race-control and overtakes: the leader's lap at that moment) 100 100 100 100
date_start timestamp (UTC) UTC time the lap started (imputed from the previous lap's end when null) 100 100 100 100
date_end timestamp (UTC) date_start + lap_duration, or the next lap's start when the duration is null 99 99 99 99
date_start_imputed bool True when date_start was filled in by the build 100 100 100 100
lap_duration float lap time (s); null for some lap 1s, aborted/out laps and untimed laps 96 96 96 96
duration_sector_1 float sector 1 time (s) 91 91 91 91
duration_sector_2 float sector 2 time (s) 99 99 99 99
duration_sector_3 float sector 3 time (s) 97 98 98 98
i1_speed float speed at intermediate 1 (km/h) 91 91 91 92
i2_speed float speed at intermediate 2 (km/h) 99 99 98 99
st_speed float speed-trap speed (km/h), one fixed point per lap 93 93 93 94
segments_sector_1 list[int] list of mini-sector status codes in sector 1 (OpenF1 codes, e.g. 2064 = pit lane) 98 100 99 100
segments_sector_2 list[int] mini-sector status codes, sector 2 98 100 99 100
segments_sector_3 list[int] mini-sector status codes, sector 3 98 100 99 100
stint int stint number from OpenF1 stints (boundary-corrected) 98 100 100 100
compound text SOFT, MEDIUM, HARD, INTERMEDIATE, WET (UNKNOWN / TEST_UNKNOWN occur) 98 100 100 100
tyre_age int laps already done on the set when this lap began (0 on a new set's first lap) 98 100 100 100
stint_lap int 1 on the first lap of the stint 98 100 100 100
is_pit_out_lap bool lap leaves the pit lane 100 100 100 100
is_pit_in_lap bool lap ends in the pit lane (the pit stop's lap number) 100 100 100 100
pit_lane_s float on in-laps: pit-lane time, entry line to exit line (s) 7 10 11 2
track_status text GREEN, or '|'-joined SC / VSC / RED / YELLOW overlapping the lap; UNKNOWN without timestamps 100 100 100 100
track_status_known bool the lap had timestamps to test against the flag windows 100 100 100 100
is_sc bool an SC window overlaps the lap 100 100 100 100
is_vsc bool a VSC window overlaps the lap 100 100 100 100
is_red bool a red-flag window overlaps the lap 100 100 100 100
is_yellow bool a yellow or double-yellow window overlaps the lap 100 100 100 100
is_restart bool 100 100 100 100
position_end int position at the lap's end (timing-screen order in practice and qualifying) 99 99 99 99
gap_to_leader float gap to the leader at the lap's end (s), races and sprints only 39 38 37 32
interval float gap to the car ahead at the lap's end (s); 0.0 for the leader 41 42 40 38
laps_behind_leader float laps down: 0 on the lead lap, N when the stream gave '+N LAP(S)' (the gap is then NaN) 42 42 40 38
air_temperature float °C, nearest weather record to the lap start 100 99 99 100
track_temperature float °C (a few 0.0 dropouts) 100 99 99 100
humidity float % 100 99 99 100
rainfall float 0/1 rain flag at the weather station 100 99 99 100
wind_speed float m/s 100 99 99 100
wind_direction float degrees 100 99 99 100
pressure float air pressure (hPa) 100 99 99 100
is_green bool track_status == 'GREEN' 100 100 100 100
is_clean bool the canonical clean lap (see the definitions section) 100 100 100 100

overtakes: 25,310 rows

column type meaning 2023 2024 2025 2026
(rows) 6,971 5,969 6,382 5,988
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
lap_number int lap number (race-control and overtakes: the leader's lap at that moment) 99 99 99 100
overtaking_driver_number int car gaining the position 100 100 100 100
overtaking_driver_ref text its Jolpica id 100 100 100 100
overtaken_driver_number int car losing it 100 100 100 100
overtaken_driver_ref text its Jolpica id 100 100 100 100
position int the position the overtaking car moved into 100 100 100 100

pit: 26,337 rows

column type meaning 2023 2024 2025 2026
(rows) 5,774 8,942 9,602 2,019
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100
acronym text three-letter driver code, e.g. VER 100 100 100 100
lap_number int the in-lap 100 100 100 100
date timestamp (UTC) OpenF1 pit timestamp (falls inside the out-lap; NaT for Jolpica rows) 96 100 100 100
pit_lane_s float pit-lane time (s): lane_duration, else pit_duration, else Jolpica duration_s 76 77 77 84
stop_s float stationary time (s), where OpenF1 publishes it 0 2 8 31
pit_duration float OpenF1 pit_duration (s) 76 77 77 84
lane_duration float OpenF1 lane_duration (s) 73 77 77 84
stop_duration float OpenF1 stop_duration (s) 0 2 8 31
source text 'openf1', or 'jolpica' (race stops filled from Jolpica: 2023 rounds 1–6) 100 100 100 100

positions: 346,969 rows

column type meaning 2023 2024 2025 2026
(rows) 87,186 90,095 93,228 76,460
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
position int running position at that moment (pre-start rows give the qualifying order) 100 100 100 100

race_control: 27,572 rows

column type meaning 2023 2024 2025 2026
(rows) 5,369 5,316 6,646 10,241
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
lap_number float lap number (race-control and overtakes: the leader's lap at that moment) 41 45 39 43
category text Flag, Other, SessionStatus, Drs, SafetyCar, CarEvent 100 100 100 100
flag text GREEN, YELLOW, DOUBLE YELLOW, CLEAR, RED, BLUE, CHEQUERED, BLACK AND WHITE (NA for most 'Other') 42 46 51 55
scope text Track, Sector or Driver 42 46 51 55
sector float mini-sector number for sector-scoped flags 23 22 34 36
driver_number float car the message concerns, if any 12 14 8 13
qualifying_phase float 1, 2 or 3 in qualifying 15 13 17 11
message text the message text, e.g. 'SAFETY CAR DEPLOYED' 100 100 100 100

results: 9,542 rows

column type meaning 2023 2024 2025 2026
(rows) 2,244 2,441 2,451 2,406
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100
acronym text three-letter driver code, e.g. VER 100 100 100 100
position int OpenF1 classified position (NaN for retired cars; status strings go to position_text) 97 98 97 94
number_of_laps float laps completed 100 100 100 100
dnf bool did not finish 100 100 100 100
dns bool did not start 100 100 100 100
dsq bool disqualified 100 100 100 100
points float points scored (R and S) 25 25 24 25
duration_s float race time (R/S) or best lap (Q/practice), s 92 91 93 88
gap_to_leader_s float gap to the winner or the session's fastest (s) 92 91 93 88
laps_behind_leader float laps down 95 96 97 94
q1_s float best Q1 time (s) 25 24 24 24
q2_s float best Q2 time (s) 18 18 18 18
q3_s float best Q3 time (s) 12 12 12 11
grid_position float starting grid from OpenF1 (qualifying order; R and S rows) 25 25 24 25
grid_quali_lap_s float qualifying lap time attached to the grid slot (s) 24 24 23 24
jolpica_grid int Jolpica actual grid (after penalties; 0 = pit-lane start) 25 25 24 25
jolpica_position int Jolpica classified position (every car) 25 25 24 25
jolpica_status text Jolpica status text 25 25 24 25
jolpica_points float Jolpica points 25 25 24 25
position_text text status string OpenF1 put in position, e.g. 'RT' 0 0 0 <1

sessions: 470 rows

column type meaning 2023 2024 2025 2026
(rows) 113 123 123 111
session_key int OpenF1 session id (one per FP1, Q, Race, ...); joins every OpenF1 table 100 100 100 100
meeting_key int OpenF1 meeting (race weekend or test) id 100 100 100 100
year int season 100 100 100 100
round int Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds 97 98 98 95
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas 97 98 98 95
gp_name text Grand Prix name from the Jolpica calendar (e.g. 'Bahrain Grand Prix in Malaysia', 2026 R16) 100 100 100 100
meeting_name text OpenF1 meeting name (can differ from gp_name) 100 100 100 100
meeting_official_name text full sponsored event name 100 100 100 100
location text town or city 100 100 100 100
country_name text country 100 100 100 100
circuit_short_name text OpenF1 circuit name 100 100 100 100
circuit_key int OpenF1 circuit id 100 100 100 100
session_name text OpenF1 session name ('Race', 'Sprint Shootout', 'Day 1', ...) 100 100 100 100
session_type text OpenF1 session type ('Race', 'Qualifying', 'Practice') 100 100 100 100
kind text session kind: R, Q, S, SQ, FP1, FP2, FP3, T1–T3 100 100 100 100
date_start timestamp (UTC) scheduled session start (UTC) 100 100 100 100
date_end timestamp (UTC) scheduled session end (UTC) 100 100 100 100
gmt_offset text local time offset, e.g. '-06:00:00' 100 100 100 100
is_testing bool pre-season testing day 100 100 100 100
is_sprint_weekend bool the meeting has a sprint 100 100 100 100
leader_laps int laps completed by the classified winner (R and S) 100 100 100 99
has_laps bool the laps table has rows for this session (False: 2025 Azerbaijan Q, cancelled events) 100 100 100 100

stints: 38,010 rows

column type meaning 2023 2024 2025 2026
(rows) 8,550 9,483 10,204 9,773
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100
acronym text three-letter driver code, e.g. VER 100 100 100 100
stint_number int 1, 2, 3, ... per driver per session 100 100 100 100
compound text tyre compound of the set 100 100 100 100
lap_start int first lap of the stint (after the boundary fix) 100 100 100 100
lap_end int last lap of the stint 100 100 100 100
n_laps int lap_end − lap_start + 1 100 100 100 100
lap_start_raw int OpenF1's original lap_start 100 100 100 100
boundary_shifted bool the build moved lap_start one lap later (in-lap kept on the old set) 100 100 100 100
same_set_passages int 100 100 100 100
tyre_age_at_start float laps already on the set when the stint began 100 100 100 100

team_radio: 17,696 rows

column type meaning 2023 2024 2025 2026
(rows) 6,965 7,716 1,740 1,275
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
driver_number int car number in that session (numbers change between seasons, e.g. VER 1 → 3 in 2026) 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100
recording_url text link to the audio clip (no transcripts exist in the data) 100 100 100 100

track_periods: 4,915 rows

column type meaning 2023 2024 2025 2026
(rows) 721 672 1,312 2,210
status text SC, VSC, RED, YELLOW or DOUBLE_YELLOW 100 100 100 100
start timestamp (UTC) window start (UTC) 100 100 100 100
end timestamp (UTC) window end (UTC) 100 100 100 100
start_lap float leader's lap when the window opened 34 32 29 35
end_rule text which rule closed the window 100 100 100 100
sector float mini-sector for yellow windows 86 89 92 94
duration_s float end − start (s) 100 100 100 100

weather: 52,954 rows

column type meaning 2023 2024 2025 2026
(rows) 12,799 12,847 13,665 13,643
date timestamp (UTC) UTC timestamp of the record 100 100 100 100
air_temperature float °C 100 100 100 100
track_temperature float °C (0.0 = sensor dropout) 100 100 100 100
humidity float % 100 100 100 100
rainfall int 0/1 rain flag 100 100 100 100
wind_speed float m/s 100 100 100 100
wind_direction int degrees 100 100 100 100
pressure float hPa 100 100 100 100

B.3 Telemetry files (data/raw/openf1/car_data/, location/)

Telemetry is not a processed table. It stays in the raw archive as one gzip-compressed JSON file per driver per session, named <session_key>_<driver_number>.json.gz, and the telemetry module loads it on demand. Car data (speed, RPM, gear, throttle, brake, DRS) exists for race, qualifying, sprint and sprint-qualifying sessions; location (x, y, z) for qualifying-type sessions only. Practice and testing have no telemetry.

year kind car_data files location files
2023 Q 440 440
2023 SQ 120 120
2023 S 119 n/a
2023 R 439 n/a
2024 Q 479 479
2024 SQ 120 120
2024 S 120 n/a
2024 R 479 n/a
2025 Q 480 480
2025 SQ 120 120
2025 S 120 n/a
2025 R 479 n/a
2026 Q 462 462
2026 SQ 132 132
2026 S 132 n/a
2026 R 462 n/a

Files on disk: car_data 4,703, location 2,353 (one file per driver per session).

Columns of telemetry.lap_telemetry() (example: 2025 Japanese GP Q, VER's fastest lap, 325 samples):

column meaning
date UTC timestamp of the sample (about 3.7–4 samples per second, irregular)
session_key session id
n_gear gear, 0–8
driver_number car number
drs DRS code: 0/1 off, 8 eligible but closed, 10/12/14 open (null in 2026: no DRS)
rpm engine speed (rev/min)
brake 0 or 100: on/off only, not pressure
speed km/h (integer)
throttle 0–100 % (values of 104 clipped to 100 by the toolkit)
drs_open toolkit-derived: drs in (10, 12, 14)
time_s toolkit-derived: seconds since the lap start
distance_m toolkit-derived: speed integrated over time (m); runs ~0.5–1 % short
x track position, decimetres
y decimetres
z decimetres (elevation)

The channels teams have and we don't are part of the lesson: there is no steering angle, no brake pressure, no tyre or brake temperatures, no ERS or battery state, no fuel load, no ride height and no g-sensor. Distance is integrated from speed and acceleration has to be differentiated from it, so both are estimates. Chapters that need one of the missing channels say so and either infer it, labelled as an inference, or use an illustrative model.


B.4 Jolpica history tables (data/processed/history/, 1950 → 2026 R21) and reference tables

Load these through history: history.results(year, round), history.qualifying(year), history.laps(year, round) and so on. Driver, team and circuit arguments are Jolpica refs (max_verstappen, red_bull, monza).

circuits: 78 rows

column type meaning non-null %
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas 100
circuit_name text circuit name 100
locality text town 100
country text country 100
latitude float degrees 100
longitude float degrees 100
altitude int metres 100
wikipedia text Wikipedia link 100

constructor_standings: 14,667 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 7,012 2,250 985 2,594 1,826
year int season 100 100 100 100 100
round_number int round after which the standings apply 100 100 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100 100
team_name text team name as entered that season 100 100 100 100 100
points float points 100 100 100 100 100
position float championship position (NaN for some excluded entries) 62 81 97 99 99
win_count int wins so far 100 100 100 100 100
is_eligible text 't'/'f' (text) 100 100 100 100 100
session_number int session within the round (sprint weekends have two) 100 100 100 100 100

driver_standings: 37,065 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 20,769 5,005 2,076 5,417 3,798
year int season 100 100 100 100 100
round_number int round after which the standings apply 100 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100 100
driver_name text full name with accents, e.g. Sergio Pérez 100 100 100 100 100
points float points 100 100 100 100 100
position float championship position (NaN for some excluded entries) 43 69 96 97 99
win_count int wins so far 100 100 100 100 100
is_eligible text 't'/'f' (text) 100 100 100 100 100
session_number int session within the round (sprint weekends have two) 100 100 100 100 100

drivers: 885 rows

column type meaning non-null %
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100
driver_name text full name with accents, e.g. Sergio Pérez 100
forename text given name(s) 100
surname text family name 100
abbreviation text three-letter code (missing for many pre-2000s drivers) 12
nationality text nationality 98
country_code text country code 100
date_of_birth text YYYY-MM-DD 98
permanent_car_number float permanent number (2014 onward) 7
wikipedia text Wikipedia link 98

laps: 647,986 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 0 170,155 98,658 269,441 109,732
session_type text 'R' (race) or 'SR' (sprint) – 100 100 100 100
year int season – 100 100 100 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds – 100 100 100 100
race_name text Grand Prix name as Jolpica gives it for that season – 100 100 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas – 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources – 100 100 100 100
driver_name text full name with accents, e.g. Sergio Pérez – 100 100 100 100
abbreviation text three-letter code (missing for many pre-2000s drivers) – 60 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi – 100 100 100 100
team_name text team name as entered that season – 100 100 100 100
car_number float car number (0 appears as a real number in some early seasons) – 100 100 100 100
lap float lap number – 100 100 100 100
position float position at the end of the lap – 100 100 100 100
lap_time_s float lap time (s) – 100 100 100 100
is_deleted bool lap deleted (rarely set in race data) – 100 100 100 100

pitstops: 13,052 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 0 0 0 9,634 3,418
session_type text 'R' (races only in this table) – – – 100 100
year int season – – – 100 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds – – – 100 100
race_name text Grand Prix name as Jolpica gives it for that season – – – 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas – – – 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources – – – 100 100
driver_name text full name with accents, e.g. Sergio Pérez – – – 100 100
abbreviation text three-letter code (missing for many pre-2000s drivers) – – – 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi – – – 100 100
team_name text team name as entered that season – – – 100 100
car_number float car number (0 appears as a real number in some early seasons) – – – 100 100
stop int 1st, 2nd, ... stop of the driver – – – 100 100
lap float the in-lap – – – 100 100
local_timestamp text local time of day of the stop (text) – – – 100 100
duration_s float pit-lane time (s), entry to exit; NOT stationary time – – – 100 100

qualifying: 11,430 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 0 2,604 1,934 5,037 1,855
year int season – 100 100 100 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds – 100 100 100 100
race_name text Grand Prix name as Jolpica gives it for that season – 100 100 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas – 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources – 100 100 100 100
driver_name text full name with accents, e.g. Sergio Pérez – 100 100 100 100
abbreviation text three-letter code (missing for many pre-2000s drivers) – 49 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi – 100 100 100 100
team_name text team name as entered that season – 100 100 100 100
car_number float car number (0 appears as a real number in some early seasons) – 100 100 100 100
quali_position float official qualifying position – 100 100 100 100
q1_s float best Q1 time (s), 2006 onward – 0 99 99 99
q2_s float best Q2 time (s) – 0 72 73 73
q3_s float best Q3 time (s) – 0 45 46 48
qa_s float aggregate-format time (s), 2005 only – 4 0 0 0
qbest_s float single-session best (s), 1994–2005 only – 93 0 0 0

results: 26,335 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 13,087 4,397 1,934 5,057 1,860
year int season 100 100 100 100 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds 100 100 100 100 100
race_name text Grand Prix name as Jolpica gives it for that season 100 100 100 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas 100 100 100 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources 100 100 100 100 100
driver_name text full name with accents, e.g. Sergio Pérez 100 100 100 100 100
abbreviation text three-letter code (missing for many pre-2000s drivers) <1 49 100 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100 100 100 100 100
team_name text team name as entered that season 100 100 100 100 100
car_number int car number (0 appears as a real number in some early seasons) 100 100 100 100 100
grid int actual starting slot (0 = pit lane) 100 100 100 100 100
position int classified order (every car gets one) 100 100 100 100 100
is_classified bool Jolpica's classified flag: NOT a finish flag (late retirements are True) 100 100 100 100 100
points float points scored 100 100 100 100 100
laps_completed int laps completed 100 100 100 100 100
time_s float driver's elapsed race time (s) 19 28 47 50 97
status_text text 'Finished', '+1 Lap', 'Retired', 'Collision', ... 100 100 100 100 100
fastest_lap_rank float rank of the driver's fastest lap <1 16 95 100 98
status_code float Jolpica status category code 100 100 100 100 99
finished bool derived: status is Finished, '+N Lap(s)' or Lapped. Use this for finishes 100 100 100 100 100

rounds: 1,173 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 548 202 89 240 94
round_id int Jolpica internal round id 100 100 100 100 100
year int season 100 100 100 100 100
round float round number (NaN for cancelled rounds) 100 100 100 100 99
race_name text Grand Prix name as Jolpica gives it for that season 100 100 100 100 100
date text race date (YYYY-MM-DD) 100 100 100 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas 100 100 100 100 100
circuit_name text circuit name 100 100 100 100 100
locality text town 100 100 100 100 100
country text country 100 100 100 100 100
is_cancelled text 't' or 'f' (text) 100 100 100 100 100

sprint_pitstops: 174 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 0 0 0 0 174
session_type text 'SR' (sprint stops) – – – – 100
year int season – – – – 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds – – – – 100
race_name text Grand Prix name as Jolpica gives it for that season – – – – 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas – – – – 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources – – – – 100
driver_name text full name with accents, e.g. Sergio Pérez – – – – 100
abbreviation text three-letter code (missing for many pre-2000s drivers) – – – – 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi – – – – 100
team_name text team name as entered that season – – – – 100
car_number float car number (0 appears as a real number in some early seasons) – – – – 100
stop int 1st, 2nd, ... stop of the driver – – – – 100
lap float the in-lap – – – – 100
local_timestamp text local time of day of the stop (text) – – – – 100
duration_s float pit-lane time (s), entry to exit; NOT stationary time – – – – 100

sprint_results: 612 rows

column type meaning 1950–93 1994–05 2006–10 2011–22 2023–26
(rows) 0 0 0 120 492
year int season – – – 100 100
round float Jolpica round number, matched by date (±3 days); NaN/NA for testing and cancelled rounds – – – 100 100
race_name text Grand Prix name as Jolpica gives it for that season – – – 100 100
circuit_ref text Jolpica circuit id, e.g. monza, vegas, americas – – – 100 100
driver_ref text Jolpica driver id, e.g. max_verstappen; the key for joins across sources – – – 100 100
driver_name text full name with accents, e.g. Sergio Pérez – – – 100 100
abbreviation text three-letter code (missing for many pre-2000s drivers) – – – 100 100
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi – – – 100 100
team_name text team name as entered that season – – – 100 100
car_number int car number (0 appears as a real number in some early seasons) – – – 100 100
grid int actual starting slot (0 = pit lane) – – – 100 100
position int classified order (every car gets one) – – – 100 100
is_classified bool Jolpica's classified flag: NOT a finish flag (late retirements are True) – – – 100 100
points float points scored – – – 100 100
laps_completed int laps completed – – – 100 100
time_s float driver's elapsed race time (s) – – – 95 96
status_text text 'Finished', '+1 Lap', 'Retired', 'Collision', ... – – – 100 100
fastest_lap_rank float rank of the driver's fastest lap – – – 0 77
status_code float Jolpica status category code – – – 100 100
finished bool derived: status is Finished, '+N Lap(s)' or Lapped. Use this for finishes – – – 100 100

teams: 214 rows

column type meaning non-null %
team_ref text Jolpica team id for that season, e.g. red_bull, rb, sauber, audi 100
team_name text team name as entered that season 100
nationality text nationality 100
country_code text country code 100
wikipedia text Wikipedia link 100

Reference tables (data/reference/)

These are small, hand-built tables of sourced facts. Every CSV row carries its source name, the source URL and the date it was retrieved; values that could not be confirmed are written NOT FOUND. Quote them with their source, and never fill a NOT FOUND from memory. Appendix J §J.5 describes the sources behind them.

file rows columns
calendar_2026.csv 25 round, grand_prix, circuit, date, sprint_weekend, status, source_name, source_url, retrieved, notes
champions_context.csv 42 year, end_year, category, milestone, value, source_name, source_type, source_url, retrieved, notes
circuits_2023_2026.csv 253 circuit_id, circuit_name, grand_prix, seasons_used, attribute, value, unit, source_name, source_url, retrieved, notes
cost_cap.csv 84 topic, season, parameter, value, unit, source_name, source_url, retrieved, notes
dhl_pitstops.csv 215 season, round, race, team, driver, stationary_time_s, source_name, source_url, retrieved, notes
engineering_reference.csv 178 topic, item, circuit_or_context, value, unit, authority, source_name, source_url, retrieved, notes
f1_business.csv 220 category, item, year, value, unit, source_name, source_type, source_url, retrieved, notes
records.csv 81 category, item, year, value, unit, team, driver, race, source_name, source_type, source_url, retrieved, notes
regulations_by_season.csv 225 season, parameter, value, unit, source_name, source_url, retrieved, notes
tyres.csv 64 topic, season, parameter, value, unit, source_name, source_url, retrieved, notes
business_notes.md text, 1,906 words sourced notes
history_eras.md text, 785 words sourced notes
notable_races.md text, 2,062 words sourced notes
README_business_history.md text, 601 words sourced notes
README_regulations.md text, 742 words sourced notes
regulations_2026.md text, 2,482 words sourced notes
regulations_notes.md text, 1,647 words sourced notes

B.5 Canonical definitions

These are the definitions every chapter uses. The toolkit implements them, and a chapter that departs from one says so. Thresholds are the toolkit's current values (the constants table at the end of §B.6).

📐 Definition: clean lap (is_clean, metrics.clean_laps, f1data.laps(..., clean=True)). A green, representative lap. All five must hold: 1. it is not lap 1; 2. it is not a pit in-lap or out-lap; 3. its track_status is GREEN for the whole lap: no SC, VSC, red-flag or yellow window overlaps the lap's [date_start, date_end] interval by any amount; 4. lap_duration is not null; 5. lap_duration is at most 107 % of the same driver's median green lap (rules 1–4) in the same stint.

In this build 56 % of all laps and 83 % of race laps are clean.

📐 Definition: tyre age (tyre_age). The laps already completed on the set when the lap began: tyre_age_at_start + (lap_number − stint lap_start). It is 0 on the first lap of a new set. Sets used earlier in the weekend start the race with an age above 0.

📐 Definition: stint lap (stint_lap). 1 on the first lap of a stint. Not the same as tyre age.

📐 Definition: pit in-lap and out-lap (is_pit_in_lap, is_pit_out_lap). A stop's lap number is the in-lap (the lap that ends in the pit lane) in both OpenF1 and Jolpica. A lap is an in-lap when the next lap is an out-lap or the pit table lists it. A lap is an out-lap when OpenF1 says so, when it follows a pit-table in-lap, or when it is the first lap of stint 2 onward.

📐 Definition: track status windows (track_periods). Built from race-control messages. - SC: from SAFETY CAR DEPLOYED until the leader starts the lap after the SAFETY CAR IN THIS LAP message (fallbacks: the first track-wide TRACK CLEAR/GREEN; a red flag closes it early). - VSC: from VIRTUAL SAFETY CAR DEPLOYED (or VSC DEPLOYED, the 2026 wording) to the first track-wide TRACK CLEAR/GREEN within 60 s of the ENDING message, else ENDING + 15 s. - RED: from the red-flag message to the next SESSION STARTED/RESUMED. - YELLOW / DOUBLE YELLOW: from the sector flag to the matching CLEAR, a track-wide CLEAR/GREEN, a new flag in the sector or the chequered flag, capped at 120 s. A yellow anywhere flags the lap for every car whose lap overlaps it.

📐 Definition: SC/VSC laps. For 2023 onward, from track_periods (race control). For 1996–2022, from the lap-time detector metrics.neutralised_laps_history: lap L is flagged when the field-median lap time (excluding in- and out-laps) exceeds 1.10 × the race's median (1.20 × on lap 1) and 1.08 × the centred 21-lap rolling median (the rain guard). It cannot tell SC, VSC and red flag apart. Its measured precision and recall against race control are in toolkit/README.md §4 (for example 0.94 and 0.86 on the 2024–2025 hold-out set). Always say which source you used.

📐 Definition: fuel correction (metrics.fuel_corrected). Fuel burns linearly; the mass on lap L is taken at mid-lap, $m_L = m_0 (1 - (L - 0.5)/N)$, and lap_time_fc = lap_duration − $k\,m_L$, the lap time with an empty tank. Assumptions: $m_0$ = 100 kg and $k$ = 0.03 s per kg per lap by default; $N$ = the laps the leader completed. A 110 kg race-fuel limit is sourced for 2019–2021 only, and the 2026 rules limit energy flow rather than fuel mass. The data-driven alternative is metrics.estimate_fuel_effect, an OLS fixed-effects fit whose lap-number slope also contains track evolution (treat it as an upper bound). Every pace or degradation number must say which correction it used.

📐 Definition: degradation rate (metrics.degradation). For one stint: drop stint lap 1 (the warm-up lap), keep clean laps, and regress fuel-corrected lap time (or raw lap time if not corrected) on tyre age by OLS. Report the slope in s/lap with its 95 % t-interval and n. Raw lap time understates wear. degradation_table(session) runs it for every stint with at least 6 usable laps.

📐 Definition: green-flag pit loss (metrics.pit_loss). Per stop: (in-lap + out-lap) − 2 × the driver's median clean lap within ±5 laps (widening to ±10, then the whole race, if fewer than 3 laps qualify). The circuit figure is the median across stops, with its IQR and n. Excluded: lap-1 stops, stops with the in- or out-lap under SC/VSC/red, stops without a tyre change, wet stops, and pit-lane times over 60 s. Not the same as pit-lane time (pit_lane_s, entry line to exit line) or stationary time (stop_s, wheels stopped).

📐 Definition: race pace (metrics.race_pace). The median fuel-corrected clean lap, per driver or per team, with the gap to the best. It does not control for compound mix.

📐 Definition: teammate qualifying gap (metrics.teammate_quali_gap). On the best common session (the latest of Q3, Q2 and Q1 in which both set a time, or the single-session format before 2006): gap_pct = 100 × (t − t_mate) / mean(t, t_mate). Negative means faster. Summarise a season with the median.

📐 Definition: gap to leader (metrics.gap_to_leader_by_lap). From line crossings. reference="leader" gives the time behind the first car to complete lap L; reference="winner_mean" (the race trace) gives elapsed time minus L × the winner's mean lap. For 1996 onward from Jolpica: history.gap_to_leader_by_lap.

📐 Definition: lap-1 gain (metrics.position_changes_lap1). Grid slot minus position at the end of lap 1; positive means places gained. Pit-lane starters count as starting behind the last grid slot.

📐 Definition: green on-track overtake. Not a toolkit column. The OpenF1 overtakes table logs every change of position the timing saw. The book classifies each record in priority order (lap 1; under SC/VSC/red; either car on an in- or out-lap; a retiring car; a swap reversed within 10 s; one car involved in four or more otherwise-green records on one lap) and keeps the rest as green on-track passes. Chapter 35 and boxbox.overtaking.classify_passes implement it.

📐 Definition: uncertainty. Proportions get the Wilson score interval (metrics.wilson_ci(k, n), which returns (p, low, high)). Medians and differences get the percentile bootstrap (metrics.bootstrap_ci(x), which returns (estimate, low, high), 10,000 resamples, seed 42). Always give n.

📐 Definition: finished (history.results.finished). The Jolpica status text is "Finished", "+N Lap(s)" or "Lapped". Use this, not is_classified, for finishes and DNF rates (§B.7).


B.6 Toolkit reference (toolkit/)

Five modules, imported together with from toolkit import f1data, metrics, plots, telemetry, history. Every OpenF1 loader takes the same filters: session (a session_key, a row from f1data.session(), or a (year, gp, kind) tuple), year, kind and driver (a car number, an acronym such as "VER", or a Jolpica driver_ref). Missing tables, sessions or drivers raise f1data.DataMissingError with a message that says why; tables that can legitimately be empty for a session (pit, race_control, track_periods, overtakes) return an empty frame instead.

The signatures and one-line descriptions below are generated from the source, so they match the code you have. For worked examples see toolkit/README.md and Appendix A.

toolkit.f1data (24 public functions and classes)

function what it does
class DataMissingError(...) Raised when the requested table, session or driver is not in the processed data.
reload() Forget cached tables (use after rebuilding the parquet files).
table(name: str) -> pd.DataFrame Return a whole processed table (cached).
norm_kind(kind) Normalise a session-kind name ('Race', 'Sprint Shootout', 'Q', ...) to R/Q/S/SQ/FP1-3/T1-3.
sessions(year=None, kind=None, include_testing: bool = False) -> pd.DataFrame All sessions (one row each), optionally filtered by year and kind.
session(year: int, gp_or_round, kind: str = 'R') -> pd.Series Return one session row.
session_key(sess) -> int Normalise any session spec (int, Series/dict row, (year, gp, kind) tuple) to a session_key.
session_info(sess) -> pd.Series The sessions-table row for any session spec.
source_note(sess, source: str = 'OpenF1') -> str Footnote text for charts, e.g. 'Data: OpenF1 (2026 Las Vegas Grand Prix, Race)'.
laps(session=None, *, year=None, kind=None, driver=None, clean: bool = False) -> pd.DataFrame Enriched laps: one row per (session, driver, lap).
stints(session=None, *, year=None, kind=None, driver=None) Stints (one row per driver per set), boundary-corrected.
pit(session=None, *, year=None, kind=None, driver=None) Pit-lane records, with Jolpica-filled rows for 2023 rounds 1-6.
race_control(session=None, *, year=None, kind=None, category=None) Race-control messages, optionally filtered by category.
track_periods(session=None, *, year=None, kind=None, status=None) SC / VSC / RED / YELLOW / DOUBLE_YELLOW windows derived from race control (see README).
weather(session=None, *, year=None, kind=None) Weather records (about one a minute).
results(session=None, *, year=None, kind=None, driver=None) Session classification, plus the starting grid and Jolpica cross-reference for R and S.
drivers(session=None, *, year=None, kind=None, driver=None) Drivers in a session, mapped to Jolpica driver_ref and team_ref.
overtakes(session=None, *, year=None, kind=None) OpenF1 overtake records (NOT clean on-track passes; see the caveats).
positions(session=None, *, year=None, kind=None, driver=None) Position stream (one row per position change).
intervals(session=None, *, year=None, kind=None, driver=None) Gap-to-leader and interval stream (races and sprints).
team_radio(session=None, *, year=None, kind=None, driver=None) Index of team-radio clips (URLs only; the audio is not downloaded).
championship(session=None, *, year=None, entity=None) Championship standings after each race (entity 'driver' or 'team').
driver_number(sess, driver) -> int Resolve a driver (number / acronym / driver_ref) to the car number used in that session.
team_colors(sess, by: str = 'acronym') -> dict {key: '#rrggbb'} from OpenF1 team colours for one session.

toolkit.metrics (16 public functions and classes)

function what it does
clean_laps(df: pd.DataFrame) -> pd.DataFrame Canonical CLEAN lap (green, representative).
fuel_corrected(df: pd.DataFrame, total_laps: int \| None = None, start_fuel_kg: float = 100.0, s_per_kg: float = 0.03, col: str = 'lap_duration') -> pd.DataFrame Add fuel_kg and lap_time_fc (fuel-corrected lap time, i.e. the time the lap would have taken with an EMPTY tank).
estimate_fuel_effect(laps_df: pd.DataFrame, start_fuel_kg: float = 100.0, total_laps=None, conf: float = 0.95) -> dict Data-driven fuel effect from race laps (one race or several).
degradation(stint_laps: pd.DataFrame, warmup_laps: int = 1, model: str = 'linear', y: str \| None = None, clean_only: bool = True, conf: float = 0.95) -> dict Tyre degradation of ONE stint (one driver, one set of tyres): slope of lap time vs tyre age.
degradation_table(session, min_laps: int = 6, warmup_laps: int = 1, fuel_correct: bool = True, model: str = 'linear') -> pd.DataFrame degradation() for every stint of a session with >= min_laps usable laps (one row per driver-stint).
pit_loss(session, per_stop: bool = False, window: int = 5, max_lane_s: float = 60.0) Canonical GREEN-FLAG PIT LOSS for one race.
pit_loss_table(year=None) -> pd.DataFrame pit_loss() for every race (kind R) in the processed data (optionally one season), one row per race.
neutralised_laps_history(year: int, round: int, threshold: float = 1.1, lap1_extra: float = 0.1, local_window: int \| None = 21, local_threshold: float = 1.08) -> pd.DataFrame Lap-time-based SC/VSC/red-flag detector for Jolpica races (1996+), where no race-control feed exists.
openf1_neutralised_truth(session, min_share: float = 0.5) -> pd.DataFrame Lap-level truth from OpenF1: lap L is neutralised when >= min_share of the cars that completed lap L had an SC, VSC or red-flag window overlapping that lap (laps.is_sc | is_vsc | is_red).
validate_neutralised_detector(years=(2023, 2024, 2025), threshold: float = 1.1, lap1_extra: float = 0.1, **kw) -> tuple[dict, pd.DataFrame] Compare neutralised_laps_history() with OpenF1 truth for every race available in both sources.
teammate_quali_gap(year: int, summary: bool = False) -> pd.DataFrame Team-mate qualifying gap (Jolpica qualifying, 1994+).
race_pace(session, by: str = 'driver', total_laps=None, start_fuel_kg: float = 100.0, s_per_kg: float = 0.03) -> pd.DataFrame Canonical RACE PACE: the median FUEL-CORRECTED CLEAN lap time.
gap_to_leader_by_lap(session, wide: bool = False, reference: str = 'leader') -> pd.DataFrame Gap at the end of each lap, from lap-end timestamps (OpenF1).
position_changes_lap1(year: int \| None = None, round: int \| None = None, session=None) -> pd.DataFrame Places gained on lap 1 = grid position - position at the end of lap 1 (positive = gained).
wilson_ci(k: int, n: int, conf: float = 0.95) -> tuple[float, float, float] Wilson score interval for a proportion k/n.
bootstrap_ci(x, stat=median, n_boot: int = 10000, conf: float = 0.95, seed: int = 42) Percentile bootstrap CI of stat(x).

toolkit.history (17 public functions and classes)

function what it does
table(name: str) -> pd.DataFrame Return a whole processed Jolpica table (cached).
rounds(year=None, include_cancelled: bool = False) The calendar: one row per round (cancelled rounds excluded unless asked).
results(year=None, round=None, driver=None, team=None) Race classification.
sprint_results(year=None, round=None, driver=None, team=None) Sprint classification, 2021 onward.
qualifying(year=None, round=None, driver=None, team=None) Qualifying (1994+): quali_position, q1_s, q2_s, q3_s (2006+), qbest_s / qa_s for single-session formats.
laps(year=None, round=None, driver=None, session_type: str = 'R') Race laps 1996+: lap, position (at the end of the lap), lap_time_s.
pitstops(year=None, round=None, driver=None) Pit stops 2011+: stop number, lap (the in-lap), duration_s = pit-lane time (entry to exit).
driver_standings(year=None, round=None, final: bool = False) Drivers' standings after each round; final=True gives the last round of each season.
constructor_standings(year=None, round=None, final: bool = False) Constructors' standings after each round; final=True gives the season's end.
drivers() Every driver Jolpica knows (name, nationality, date of birth).
teams() Every team Jolpica knows.
circuits() Every circuit Jolpica knows (location, coordinates).
teammate_pairs(year, by_round: bool = False) -> pd.DataFrame Team-mate pairs from race entries.
eras() -> pd.DataFrame The book's era table (start/end year inclusive).
era_of(year: int) -> str The book's era label for a season.
season_summary(year: int) -> pd.Series Headline facts for one season from Jolpica: rounds run, champion(s), winners, pole sitters.
gap_to_leader_by_lap(year: int, round: int) -> pd.DataFrame Cumulative race time gap to the leader at the end of each lap (1996+), from Jolpica lap times.

toolkit.telemetry (15 public functions and classes)

function what it does
class TelemetryMissingError(...) Raised when a telemetry file is not on disk or is empty (a DataMissingError).
car_data(session, driver, allow_fetch: bool = False) -> pd.DataFrame Whole-session car telemetry for one driver: date, speed (km/h), rpm, n_gear, throttle (%), brake (0/100), drs (code), drs_open (bool).
location(session, driver, allow_fetch: bool = False) -> pd.DataFrame Whole-session x/y/z positions for one driver (qualifying-type sessions only in this archive).
available(endpoint: str = 'car_data') -> pd.DataFrame Which telemetry files are on disk: session_key, driver_number, size_kb.
add_distance(tel: pd.DataFrame, t0=None) -> pd.DataFrame Add time_s (from t0, default first sample) and distance_m (trapezoid integral of speed) columns.
slice_lap(tel: pd.DataFrame, start, end) -> pd.DataFrame Cut a whole-session telemetry frame to [start, end] and insert interpolated samples exactly at the lap boundaries, then compute time_s and distance_m from the lap start.
lap_telemetry(session, driver, lap: int, allow_fetch: bool = False, with_location: bool = True) -> pd.DataFrame Telemetry for one lap: date, time_s, distance_m, speed, rpm, n_gear, throttle, brake, drs, drs_open (+ x, y, z where location exists).
fastest_lap(session, driver) The driver's fastest timed lap (row of the laps table) in the session.
fastest_lap_telemetry(session, driver, allow_fetch: bool = False, with_location: bool = True) -> pd.DataFrame lap_telemetry() of the driver's fastest timed lap (lap_number in .attrs).
resample_on_distance(tel: pd.DataFrame, step_m: float = 5.0, length_m: float \| None = None) -> pd.DataFrame Re-sample a lap on a regular distance grid (0, step, 2*step, ...).
delta_time(ref: pd.DataFrame, cmp: pd.DataFrame, step_m: float = 5.0, normalise: bool = True) -> pd.DataFrame Time delta of lap cmp relative to lap ref as a function of distance along the ref lap.
corners_from_speed(tel: pd.DataFrame, prominence_kmh: float = 20.0, min_gap_m: float = 120.0, step_m: float = 5.0) -> pd.DataFrame Corners as local speed minima (scipy find_peaks on -speed after resampling on distance).
full_throttle_share(tel: pd.DataFrame, threshold: float = 98.0) -> float Share of lap DISTANCE (not samples) covered with throttle >= threshold %, using each sample's value for the interval up to the next sample.
braking_zones(tel: pd.DataFrame, min_duration_s: float = 0.0) -> pd.DataFrame Contiguous runs of brake ON: start/end distance & time, duration, entry speed (at the first brake-on sample), minimum speed in the zone.
top_speed(tel: pd.DataFrame) -> dict Maximum sampled speed (km/h) and where it occurred.

toolkit.plots (13 public functions and classes)

function what it does
use_style() Apply the house style (call once at the top of a chapter script).
add_source(fig, text: str) Footnote with the data source, bottom-left, outside the plot area.
savefig(fig, chapter_dir, name: str, close: bool = True) -> str Save to <chapter_dir>/images/<name>.png at 150 dpi; return the path relative to chapter_dir ("images/<name>.png") for use in Markdown.
team_color(team_ref: str \| None = None, session=None, default: str = '#777777') -> str Team colour: OpenF1's colour for that session when given, else TEAM_FALLBACK, else default.
driver_styles(session) -> dict {acronym: {"color": team colour, "linestyle": "-" or "--"}}; the team's second driver (higher car number) is dashed so team-mates are distinguishable without a new hue.
compound_color(c) -> str The fixed house colour for a tyre compound.
shade_neutralised(ax, session, min_share: float = 0.5) Shade laps where >= min_share of the field was under SC / VSC / red flag (x axis = lap number).
speed_trace(tels, labels=None, colors=None, title=None, source=None, corners=None, with_delta: bool = None, figsize=(10, 5.5)) Speed vs distance for one or more laps (from telemetry.lap_telemetry).
track_map(tel, color_by: str = 'speed', ax=None, title=None, source=None, corners=None, cmap=None, figsize=(7.5, 7)) Track outline from location x/y, coloured by a channel ('speed', 'n_gear', 'throttle', 'brake').
position_chart(session, drivers=None, title=None, source='auto', figsize=(11, 6.5)) Spaghetti plot: position at the end of every lap (laps.position_end), P1 at the top, team colours, team-mates dashed, driver labels at both ends, SC/VSC/red laps shaded.
gap_chart(session, drivers=None, title=None, source='auto', figsize=(11, 6), max_gap_s: float \| None = None, reference: str = 'leader') Gap (s) at the end of each lap, from metrics.gap_to_leader_by_lap(reference=...).
stint_chart(session, title=None, source='auto', figsize=(10, 7)) Tyre strategy: one horizontal bar per driver (finishing order, winner at top), one segment per stint, coloured by compound (HARD white with a dark edge), segments separated by a thin gap.
deg_plot(laps_df, by: str = 'acronym', y: str \| None = None, warmup_laps: int = 1, title=None, source=None, ax=None, figsize=(9, 5)) Lap time vs tyre age for one or more stints, with the metrics.degradation() linear fit per stint.

Module constants (the thresholds and assumptions behind the definitions in §B.5):

constant value
metrics.START_FUEL_KG 100.0
metrics.S_PER_KG 0.03
metrics.NEUTRAL_THRESHOLD 1.1
metrics.LAP1_EXTRA 0.1
metrics.LOCAL_WINDOW 21
metrics.LOCAL_THRESHOLD 1.08
telemetry.SAMPLE_HZ 3.7
telemetry.MIN_FETCH_GAP_S 2.1
plots.INK #1f1f1f
plots.INK_2 #555555
plots.GRID #e4e4e4
plots.SURFACE #ffffff

B.7 Known data caveats

Every analysis in the book rests on two free sources that were built for other purposes: OpenF1 for live fans and app developers, Jolpica for historical results. Both are excellent, and both have quirks. This section collects every quirk found while the book was written, grouped by what it affects. Each entry says what happens, why it matters, and what to do. The evidence table at the end gives the number behind each caveat in this snapshot, recomputed by the build script, so you can check whether a rebuild has changed it.

Counting things that aren't what they seem

The overtakes table is not a list of clean passes. OpenF1 logs every change of race position the timing system saw: about 253 records per Grand Prix. Most are not overtakes. They come from pit-stop cycles, reshuffles under the safety car, cars slowing to retire, loop-to-loop "flicker" where two cars swap and swap back within seconds, and timing glitches where one car swaps with the whole field. After the classification in §B.5, about 40 per race (15.9 % of records) are green-flag on-track passes. Quoting the raw count as "overtakes" overstates passing roughly six-fold. Use the filtered count from Chapter 35. Position changes caused by pit stops are not overtakes.

is_classified is not a finish flag. Jolpica marks a driver classified when they completed enough of the distance (in practice about 90 %), even if they retired. Lando Norris at the 2025 Canadian GP (66 laps, "Retired", classified 18th) and Carlos Sainz at the 2025 Mexico City GP (67 laps, "Retired", classified 17th) are both is_classified == True. Treating that flag as "finished" once made a championship simulation give Piastri 97.8 % for the 2025 title with five races left. For finishes, DNFs and reliability, use the derived finished column, which reads the status text.

Stints minus one is not always the number of stops. - Phantom stints. OpenF1 sometimes inserts an empty stint (lap_end < lap_start) when a car passes through the pit lane, and its tyre_age_at_start can jump by two. The 2025 Canadian GP is the clearest case (laps 67–68). Drop zero-length stints and merge consecutive stints on the same set before counting. - Jolpica duplicates at the same race. Jolpica lists most of the 2025 Canadian GP field as stopping on consecutive laps 66–69 (about 18 s each). These are not tyre stops; drop stops within two laps of another stop by the same driver. - Red-flag tyre changes. Teams may change tyres during a red-flag suspension, and OpenF1 starts a new stint. The book's rule: a red-flag tyre change is not a stop. The 2026 Monaco GP is the extreme case, with red-flag and safety-car changes giving twelve drivers four "stops"; count stops there from pit-table rows with a pit-lane time under 60 s. - Used sets reported as new. OpenF1's tyre_age_at_start occasionally reports a used set as 0 (for example Albon's qualifying stints at 2025 round 3), which pushes a few weekend set counts over the allocation.

history.pitstops is race stops only; sprint stops are in sprint_pitstops. The Jolpica dump mixes sprint pit stops into the same file as race stops. An earlier version of the build kept them together, which put 174 sprint stops across 15 weekends into the race table (the 2025 Miami GP showed 38 stops: 18 race plus 20 sprint). The build now splits them. If you see older numbers quoting 13,226 Jolpica pit stops, that is the mixed table; the race-only table has 13,052.

Pre-race and red-flag pit rows. Some pit rows are not pit stops at all. The 2026 Mexico City GP has pit rows on "lap 1" stamped about an hour before the start for nine drivers, which sets is_pit_in_lap on their lap 1. Red-flag suspensions in the pit lane appear as pit-lane times of half an hour or more: in Jolpica's pre-2023 data the whole field "stops" during a suspension (Brazil 2016, Hungary 2021), and in OpenF1 the 2026 Italian GP's lap-3 stoppage shows as roughly 1,840 s. The pit-loss definition's 60 s cap removes them; any other stop count should apply the same cap.

Flags and neutralisations

2026 red flags are posted as "Other" messages. In 2026, race control writes RED FLAG - RACE SUSPENDED with category "Other" and no flag value, instead of a message with flag == "RED". An earlier build missed all four 2026 race red flags (Monaco, Dutch, Italian and Mexico City). The build now treats any message starting RED FLAG (excluding "RED FLAG INFRINGEMENT" penalties) as a red flag, so track_periods and is_red are correct: 14 race red flags in 91 Grands Prix, 2023–2026, or 0.154 per race. If you parse race control yourself, do the same. Suspended start procedures appear only as "STARTING PROCEDURE SUSPENDED", also category "Other". The 2026 wording also changed for the VSC ("VSC DEPLOYED", "VSC ENDING"); both forms are parsed.

Some restart laps carry GREEN status. After a red flag, the standing-restart lap and some laps around the stoppage can be very slow and still show track_status == "GREEN" (2026 Italian GP for the whole field, 2024 Japanese GP, 2023 Mexico City GP). The 107 % stint rule removes most of them from clean laps, but analyses that keep slow laps (error rates, "green lap" counts) should add a field-slow filter, as Box Box's driver module does.

A red flag on lap 1 breaks the lap-1 timestamps. At the 2024 Japanese GP, OpenF1 gives lap 1 a date_start equal to the restart time, so lap 1's timestamps are wrong and the lap containing the stoppage lasts about 28 minutes. At the 2024 Monaco GP (also a lap-1 red flag) all twenty OpenF1 lap-1 times are null. Exclude these laps by hand in race-pace work.

Race-control lap_number is the leader's lap. A message's lap is not the lap of the car it concerns. The 2026 Dutch GP shows the effect: an incident on the first lap is logged at the leader's lap 2, so it is not a lap-1 neutralisation under the book's rule.

race_control.flag contains NA. Most "Other" messages have no flag. A test such as rc.flag != "RED" raises "boolean value of NA is ambiguous"; use rc.flag.fillna("").eq("RED").

The historical detector has known misses. For 1996–2022 the SC/VSC laps come from lap times, not messages. Its errors are measured (toolkit/README.md §4), and they are systematic: false positives are mostly wet laps and the slow restart lap after a red flag; false negatives are laps where a neutralisation began late or ended early. The rain guard costs it most of Brazil 2016's opening safety-car laps. Say "detected" for pre-2023 neutralisations.

Laps and timing

2025 Miami GP: OpenF1 is missing laps 2–24. OpenF1 has only 559 laps for the race (556 timed) against Jolpica's 1,002, with nothing for laps 2–24 and only part of lap 25, and its stint boundaries are wrong for 15 of 18 drivers. Don't use this race for stint, degradation or overtaking work from OpenF1. Jolpica's lap times are complete if you need the race trace.

Lap 1 is timed differently in the two sources. From lap 2 onward OpenF1 and Jolpica agree to the millisecond on 99.991 % of race laps. On lap 1 they never agree: OpenF1's lap-1 time is a median 0.389 s longer, because the two sources start the clock differently. Lap 1 is excluded from clean laps anyway, but don't mix lap-1 times from the two sources.

The phantom final lap. OpenF1 gives the race winner an extra lap N + 1 that starts at the chequered flag and has no duration. The build drops these laps (50 of them), so race laps never exceed the winner's lap count.

Stint boundaries off by one. OpenF1 sometimes starts a new stint on the pit in-lap instead of the out-lap: almost always at Albert Park, Monaco and Montréal, where the timing line lies inside the pit lane, and in about 14 % of race stint starts overall. The build moves the boundary one lap later so the in-lap stays on the old tyres; stints.lap_start_raw and stints.boundary_shifted record the change. Before the fix, pit loss at those circuits came out several seconds too low. At Monaco the pit-lane time also lands in the in-lap.

Null lap times. lap_duration is null on about 9.5 % of qualifying laps and 12.3 % of sprint-qualifying laps (aborted laps and out-laps) but only 0.3 % of race laps. In practice sessions the out-lap's lap_duration includes garage time, while date_start is the pit exit.

Positions in practice and qualifying are timing-screen order. position_end there is the order by best lap, not the order on track. In races, the positions stream's pre-start rows give the qualifying order including non-starters, so positions can exceed the number of starters in a few races.

The leader's interval is 0.0, not NaN. A naive "interval under 1 s means in traffic" test labels the leader as in traffic on every lap. Exclude position_end == 1.

Ambiguous session names. f1data.session() matches names by substring. "United States" in 2026 matches Miami, Austin and Las Vegas; "Qatar" is ambiguous in 2023 and 2025. "bahrain" in 2026 resolves to round 16, held at Sepang and named "Bahrain Grand Prix in Malaysia" in Jolpica; check circuit_ref before any same-circuit comparison. Pass the round number or the Jolpica circuit ref ("americas").

2025 Azerbaijan GP qualifying has no laps. The session is listed but OpenF1 has no lap data for it, so f1data.laps() raises DataMissingError. Filter loops with sessions().has_laps.

Qualifying (Jolpica)

qbest_s is empty from 2006, including all of 2025. The column holds the best time of the single-session qualifying formats of 1994–2005. From 2006 the knockout format's times are in q1_s, q2_s and q3_s, and qbest_s is entirely empty. A script that uses qbest_s as "best time" silently gets nothing for modern seasons. Compute the best as min(q1_s, q2_s, q3_s). (qa_s is the 2005 aggregate format and is empty in every other season.)

quali_position was fixed. In the Jolpica dump each knockout session has its own position, and an earlier build took the minimum across sessions, which gave a driver who was P1 in Q1 but P12 overall the position 1. The build now takes the position from the last session the driver took part in (Q3 over Q2 over Q1). No round now has two P1s; a handful of rounds still have one duplicated lower position (see the evidence table). Pole sitters can be read from quali_position == 1, but check the times when a round matters.

Corrupt times. A few source times are impossible (one over 1,000 s); the build sets any qualifying time over 300 s to NaN. metrics.teammate_quali_gap does not apply further cleaning; Box Box's ratings.clean_qualifying does.

2025 Miami qualifying has no times in Jolpica (20 rows, all NaN).

Pit data

OpenF1 has no pit data for 2023 rounds 1–6 (Bahrain to Monaco). The build fills race stops for those weekends from Jolpica (pit.source == "jolpica", 219 rows). Practice and qualifying pit rows for those weekends do not exist, though in- and out-laps are still flagged from the stints.

Stationary time is partial, rounded and not DHL's. stop_s is populated for 0 % of 2023 race pit rows, 18.1 % in 2024, 85.5 % in 2025 and 71.1 % in 2026 (5.7 % of all pit rows, because practice and qualifying rows rarely have it). Where it exists it is OpenF1's figure, not the DHL timing used for the official fastest-stop award: at the 2025 Qatar GP OpenF1's minimum is 1.8 s while DHL's fastest stop was 2.08 s. Never quote an OpenF1 stop_s as a record. DHL's published fastest stops are in data/reference/dhl_pitstops.csv.

OpenF1 pit date semantics are undocumented. The timestamp falls inside the out-lap. Double-stacked stops less than 4 s apart show no cost to the second car, which is implausible; treat pit timestamps as approximate.

Pit coverage of 2026 practice and qualifying is thin: about 1,100 OpenF1 rows against about 8,000 in 2025. Race coverage is complete.

Pit loss can rest on very few stops. Some races have one or two green-flag stops (2026 Las Vegas: 1; Monza and Baku 2026: 2 each), and wet races none. Always quote n_stops, and pool several seasons per circuit.

Telemetry

Frozen telemetry. Some laps contain stretches where speed, RPM, throttle and gear all stop changing while the car is moving: the feed froze. About 9.4 % of the fastest 2026 qualifying laps have a frozen stretch longer than 2 s. The 2026 Japanese GP pole lap (Antonelli) is frozen for its last 24.7 s, which is why the book's Suzuka speed-trace example uses 2025. Check any lap before trusting it with boxbox.data.longest_frozen_run_s(tel) (flag anything over 2 s) or boxbox.physics.check_lap. Some laps also have gaps in the car data (the 2026 Italian GP qualifying fastest lap is missing about 2 s around 1,700–2,250 m) that slicing interpolates as a flat line.

Distance-alignment artefacts. distance_m is integrated from speed and runs about 0.5–1 % short of the official lap length, and two laps drift by different amounts. telemetry.delta_time (and therefore plots.speed_trace with two laps) rescales them uniformly, which manufactures time differences in slow corners: with uniform rescaling, the second-fastest qualifier appeared to brake later than the pole-sitter in 73 % of braking zones, a difference that was not significant (35.5 % [21–53 %]) on the location-based track line (Chapter 7). For braking points and corner-by-corner work, align on the x/y track line where location exists, or anchor on the sector lines (boxbox.laptime.delta_trace(align="sectors")). Treat integrated-distance deltas under about 0.05 s, or under about 20 m, as noise.

Resolution. Sampling is irregular at about 3.7–4.2 Hz (median interval 0.24 s). At 330 km/h that is about 22 m between samples, and held peak deceleration reads about 0.5 g low. The brake flag can lag the speed channel by a sample. Repeated speed values mid-stop create false deceleration wiggles.

DRS codes. The toolkit treats codes 10, 12 and 14 as open. Code 9 also appears (on 9–18 % of pole-sitters' samples in a session) and is treated as shut. In 2026 there is no DRS: drs is null and drs_open always False.

Location. x, y, z are in decimetres. Timestamps jitter by about ±0.1 s and the path has consistent sharp kinks, so lateral g from location is biased upward at high speed. One 2026 Australian GP qualifying file has 3,008 samples at x = y = 0. Location exists only for qualifying-type sessions.

Speed trap versus sampled top speed. st_speed is measured at one fixed point and sits a median 13 km/h below the sampled maximum on 2026 pole laps. Neither is "the" top speed; say which you used.

Weather

Track-temperature dropouts. 44 weather records have track_temperature == 0.0, mostly in 2026 from round 15 on. Treat values ≤ 0 °C as missing. rainfall is a 0/1 flag at the weather station, not a measure of track wetness: check the compounds in use before calling a race wet.

Jolpica in general

2026 standings stop after round 20 in the dump; compute later standings from results.

Retirement causes stop after 2022. Jolpica's status text from 2023 does not give retirement causes, so mechanical failures can't be counted from it. Never assert a cause beyond what the status or race-control messages say.

Final constructor standings contain NaN positions for some older seasons (excluded entries); astype(int) fails until you drop them. Sprint seasons have several standings rows per round (session_number); take the last.

Merging results onto laps creates _x/_y columns, because history.laps() already carries team_ref and abbreviation. Filter instead of merging.

Red-flag "stops" and positions in old races. In pre-2023 races, red-flag suspensions appear as whole-field pit stops lasting 20–35 minutes, and the lap containing a suspension can carry artefact positions (2021 Hungary, lap 3).

Team radio is an index, not transcripts. team_radio holds links to audio clips only. Coverage collapsed after 2024, from a median of 126–128 clips per race to about 30, and four 2026 races have none. Any radio-based measure must stay within one season.

Toolkit quirks

  • metrics.bootstrap_ci returns three values (estimate, low, high); it uses np.apply_along_axis, which is slow on arrays much larger than about 1,000 values.
  • metrics.race_pace gives no confidence interval; bootstrap the fuel-corrected clean laps yourself.
  • metrics.degradation_table with the default fuel correction can give negative median slopes at low-wear, high-evolution events (2026 Las Vegas: −0.027 s/lap). That is the assumption showing, not tyres improving.
  • tyre_age is a nullable Int64; cast to float before statsmodels.
  • f1data.source_note() already starts with "Data:"; don't add it again.
  • f1data.session() doesn't accept a bare session key; pass the key to the loaders directly.
  • The house font can't draw emoji; write words in chart text.
  • plots.position_chart and plots.gap_chart can overlap end labels when cars finish close together; plots.stint_chart's legend can collide with a source note on short figures (Box Box's viz.source_below handles it); calling ax.legend() after plots.deg_plot replaces its legend.
  • In qualifying, OpenF1's own is_pit_out_lap is unreliable (push laps flagged as out-laps after an untimed out-lap).
  • Box Box's telemetry_tools.corner_table stores a DataFrame in .attrs; clear attrs before pd.concat.
  • Importing a module as C breaks C(...) categorical terms in statsmodels formulas.

Evidence in this snapshot

Each row is recomputed by build_appendix_b.py from the processed tables.

check value in this snapshot
overtakes Grand Prix records 23,029 in 91 races = 253.1 per race (raw)
is_classified rows with is_classified True but finished False: 691 (1950–2026), 48 in 2022–2026; e.g. 2025 Canadian Grand Prix NOR 66 laps 'Retired' P18; 2025 Dutch Grand Prix NOR 64 laps 'Retired' P18; 2025 Mexico City Grand Prix SAI 67 laps 'Retired' P17; 2025 Qatar Grand Prix STR 55 laps 'Retired' P17
red flags race-control 'Other' messages starting 'RED FLAG': 24 (years [2026]); race RED windows by season 2023: 6, 2024: 3, 2025: 1, 2026: 4; total 14 in 91 GPs = 0.154 per race
phantom stints stints with lap_end < lap_start: 0 (race: 0); by season 2023: 0, 2024: 0, 2025: 0, 2026: 0
stint boundary fix race stints with boundary_shifted: 396 of 5,019 (7.9%)
2025 Miami OpenF1 race laps 559 (timed 556) vs Jolpica 1,002 (timed 1,002); lap numbers absent from OpenF1: 2–24
frozen telemetry 2026 Japanese GP Q, ANT fastest lap (88.778 s): longest frozen stretch 24.7 s
lap-1 timing matched race laps 101,637; laps 2+: 99.991% agree to 0.5 ms; lap 1 (n = 1,761): 0.0% agree, median OpenF1 − Jolpica +0.389 s
qbest_s non-null share 1994–2004 min 0.94; 2005 0.65; 2006–2026 max 0.00; 2025 0.00
quali_position rounds 2006–2026 with any duplicated quali_position: 6 of 420 (by season: 2023: 1, 2024: 3, 2025: 1, 2026: 1); rounds with more than one P1: 0
sprint_pitstops 174 sprint stops, by season 2023: 11, 2024: 40, 2025: 46, 2026: 77; race stops in pitstops: 13,052
stop_s share of race pit rows with stationary time: 2023: 0.0%, 2024: 18.1%, 2025: 85.5%, 2026: 71.1%; all pit rows 5.7%
pit source race pit rows from Jolpica fallback: 219
long pit-lane times race pit rows with pit_lane_s > 60 s: 251; > 600 s: 227; longest 2486 s
2025 Canada stops Jolpica stops on laps 66–69: 53 by 17 drivers (median pit-lane 18.3 s)
track temperature weather rows with track_temperature == 0.0: 44 of 52,954
leader interval intervals rows with interval_s == 0.0: 6,429 (0.3%)
team radio radio clips per race, median by season: 2023: 128, 2024: 126, 2025: 30, 2026: 29; 2026 races with none: 4
null lap times lap_duration null share by kind: R 0.3%, S 0.5%, Q 9.5%, SQ 12.3%, FP1 5.4%
2025 Baku Q 2025 Q sessions 24, with laps 23; missing: Azerbaijan Grand Prix
pre-race pit rows 2026 Mexico City GP pit rows dated before the session start: 9 (lap numbers [1])
standings Jolpica 2026 driver standings: last round 20
constructor NaN final constructor-standing rows with NaN position: 212
positions races where the positions stream exceeds the entry count: 4 of 91

B.8 Box Box module reference (project/boxbox/)

Box Box is the race-strategy simulator the book builds, one module per chapter (Chapter 40 assembles it). The list below is generated by importing every module on disk and listing its public functions and classes (names that don't start with an underscore), with each one's signature and the first sentence of its docstring. Classes also list their methods and properties. Parameters in …Params dataclasses are illustrative assumptions chosen to be plausible for a current car, not team data; the chapter that owns each module says how it was calibrated.

import sys; sys.path.insert(0, r"C:\books\formula-one-analytics\project")
from boxbox.data import RaceData
rd = RaceData.load(2025, "Mexico City", "R")

41 modules on disk in project/boxbox/ at the time of writing.

module chapter public functions and classes
physics Chapter 1 25
data Chapter 2 4
aero Chapter 3 12
tyres Chapter 4 4
pacejka Chapter 5 16
power Chapter 6 17
brakes Chapter 7 16
setup Chapter 8 18
driver Chapter 9 11
circuit Chapter 10 18
lapsim Chapter 11 16
strategy Chapter 12 19
undercut Chapter 13 10
neutralisation Chapter 14 23
wet Chapter 15 19
qualifying Chapter 16 13
start Chapter 17 12
pitwall Chapter 18 17
laptime Chapter 19 15
pace Chapter 20 10
ratings Chapter 21 15
degradation Chapter 22 13
telemetry_tools Chapter 23 14
development Chapter 24 17
viz Chapter 25 17
predict Chapter 26 14
montecarlo Chapter 27 19
regs Chapter 28 12
regs2026 Chapter 29 12
upgrades Chapter 30 8
budget Chapter 31 10
eras Chapter 32 15
economics Chapter 33 12
pitstops Chapter 34 16
overtaking Chapter 35 15
conditions Chapter 36 18
reliability Chapter 37 21
betting Chapter 38 13
series Chapter 39 12
cli Chapter 40 24
report Chapter 40 6

boxbox.physics (Chapter 1)

Box Box - physics.py (Chapter 1: What Makes an F1 Car Fast?)

  • class CarParams(mass_kg: float = 780.0, cl_a: float = field(default_factory=...), cd_a: float = 1.3, mu: float = 1.6, rho: float = 1.225, power_kw: float = 700.0, label: str = 'illustrative 2026-style car (assumed...): Point-mass car parameters.
  • methods and properties: weight_n, with_
  • air_density(pressure_hpa: float, temp_c: float) -> float: Dry-air density from the ideal-gas law, rho = p / (R T).
  • downforce_n(v_kmh, p: CarParams): Aerodynamic downforce F_L = 1/2 rho ClA v^2 (N).
  • drag_n(v_kmh, p: CarParams): Aerodynamic drag F_D = 1/2 rho CdA v^2 (N).
  • forces(v_kmh, p: CarParams) -> pd.DataFrame: Weight, downforce, drag, normal load and maximum tyre force (mu x normal load) at each speed.
  • speed_where_downforce_equals_weight(p: CarParams) -> float: km/h at which 1/2 rho ClA v^2 = m g.
  • top_speed_kmh(p: CarParams) -> float: Speed where drag power equals the assumed wheel power, P = 1/2 rho CdA v^3 (no rolling resistance, no energy-deployment limits).
  • max_corner_speed(radius_m, p: CarParams, with_downforce: bool = True): Grip-limited steady cornering speed (km/h) on a flat corner of radius R.
  • flat_out_radius(p: CarParams) -> float: Radius (m) above which the point-mass model says a corner never reaches the grip limit: R* = 2 m / (mu rho ClA).
  • lateral_limit_g(v_kmh, p: CarParams): Maximum lateral acceleration (g) at a speed: mu (1 + F_L / m g).
  • traction_circle(v_kmh: float, p: CarParams, n: int = 361, brake_scale: float = 1.0, drive_limit_g: float | None = None) -> pd.DataFrame: Boundary of the friction circle at one speed, as (ax_g, ay_g) points.
  • grip_utilisation(ax_g, ay_g, limit_g): Share of the grip budget in use: sqrt(ax^2 + ay^2) / limit (1.0 = on the circle).
  • lap_time_from_trace(distance_m, speed_kmh) -> float: T = closed integral ds / v(s), by the trapezoid rule on 1/v.
  • time_by_speed_band(distance_m, speed_kmh, bands=(0, 100, 150, 200, 250, 300, 400)) -> pd.DataFrame: Share of lap distance and of lap time spent in each speed band, and the time saved by +1 km/h everywhere in that band (dT = -ds / v^2 x dv).
  • check_lap(tel: pd.DataFrame, official_m: float | None = None, max_frozen_s: float = 2.0, max_gap_s: float = 1.5, max_jump_g: float = 8.0) -> dict: Quality gate for one lap of car_data: longest stretch where speed AND rpm repeat while moving ('frozen' channel), largest sample gap, the largest speed jump between consecutive samples (as an implied acceleration in g...
  • longitudinal_g(tel: pd.DataFrame, window_s: float = 1.0, dt: float = 0.05) -> pd.DataFrame: Longitudinal acceleration (g) from speed: resample speed on a uniform time grid, smooth with a Savitzky-Golay filter of window_s (order 2) and differentiate.
  • lap_xy(loc: pd.DataFrame, date_start, date_end) -> pd.DataFrame: Slice a whole-session location frame to one lap; x, y in metres (OpenF1 units are decimetres).
  • reference_line(paths: list[pd.DataFrame], step_m: float = 2.0, base_window_m: float = 120.0, window_m: float = 40.0) -> pd.DataFrame: A smooth track line and its curvature from many laps' position samples.
  • lateral_g(tel: pd.DataFrame, xy: pd.DataFrame, line: pd.DataFrame) -> pd.DataFrame: Lateral acceleration estimate a_y = v^2 |kappa| for one lap (g), plus the line position s.
  • lateral_g_windowed(lat: pd.DataFrame, window_s: float = 1.0, dt: float = 0.05) -> pd.DataFrame: Window-average lateral acceleration a_y = v x (heading change / time), in g.
  • sustained_peak(values, time_s, window_s: float = 1.0, how: str = 'max') -> float: Peak of a rolling MEDIAN over window_s: the largest value held for about that long.
  • session_line(session, max_ratio: float = 1.07, window_m: float = 40.0) -> pd.DataFrame: reference_line() from every driver's fastest lap within max_ratio of the session best (qualifying-type sessions only: location is archived for Q and SQ).
  • lap_g_forces(session, driver=None, official_m: float | None = None, line: pd.DataFrame | None = None, lon_window_s: float = 0.5, lat_window_s: float = 1.0) -> dict: Estimated g-forces for one fastest lap.
  • params_from_apex_fit(intercept_g: float, slope_g_per_ms2: float, mass_kg: float = 780.0, rho: float = 1.225, **kw) -> CarParams: CarParams implied by a straight-line fit of apex lateral g on v^2 (v in m/s):
  • official_lengths() -> dict: {toolkit circuit_ref: official lap length in metres} from data/reference/circuits_2023_2026.csv (formula1.com event pages).

boxbox.data (Chapter 2)

Box Box - data: one object that holds everything we know about a session (Chapter 2).

  • team_lineage(team_ref: str | None) -> str | None: Stable id for a team across rebrands (e.g. 'alphatauri' and 'rb' -> 'faenza'); unchanged otherwise.
  • parse_deleted_laps(race_control: pd.DataFrame) -> pd.DataFrame: Parse 'DELETED' race-control messages into one row per deletion.
  • longest_frozen_run_s(tel: pd.DataFrame, min_speed: float = 30.0) -> float: Longest stretch (s) in which speed, rpm, throttle and gear are ALL unchanged sample to sample while the car is moving.
  • class RaceData(session: pd.Series, laps: pd.DataFrame, stints: pd.DataFrame, pits: pd.DataFrame, flags: pd.DataFrame, race_control: pd.DataFrame, weather: pd.DataFrame, results: pd.DataFrame, _cache: dict = field(default_factory=...)): Everything the processed archive holds for one session (race, sprint, qualifying, practice).
  • methods and properties: load, from_session_key, session_key, year, round, kind, label, driver, deleted_laps, clean_laps, neutralised_laps, history_laps, coverage, summary

boxbox.aero (Chapter 3)

Box Box - aero: downforce, drag, air density, straight-line speed and drag-reduction gains (Chapter 3).

  • class AeroParams(ClA: float = 7.5, CdA: float = 1.59, CdA_drs_open: float = 1.2, mass_kg: float = 810.0, power_kw: float = 621.0, crr: float = 0.012): Illustrative point-mass car for straight-line and cornering aero (2025-spec defaults).
  • methods and properties: with_
  • air_density(pressure_hpa, temp_c, humidity_pct=None): Air density (kg/m^3) from station pressure (hPa = mbar) and air temperature (C).
  • downforce(v, ClA, rho=1.18): Downforce (N) at speed v (m/s): 1/2 rho ClA v^2.
  • drag(v, CdA, rho=1.18): Aerodynamic drag (N) at speed v (m/s): 1/2 rho CdA v^2.
  • lift_to_drag(ClA, CdA): Aerodynamic efficiency L/D (dimensionless; the speed and density cancel).
  • speed_where_downforce_equals_weight(ClA, mass_kg, rho=1.18): Speed (km/h) at which downforce equals the car's weight m g.
  • corner_speed(radius_m, mu, params=None, rho=1.18, with_downforce=True): Maximum steady cornering speed (km/h) on a flat corner of radius r with friction coefficient mu.
  • accel(v, params=None, rho=1.18, CdA=None, grade=0.0): Full-throttle, power-limited longitudinal acceleration (m/s^2) at speed v (m/s).
  • effective_cda(v, a, rho, params=None, grade=0.0): Invert the straight-line equation for CdA (m^2), sample by sample.
  • top_speed(power_kw, CdA, rho=1.18, mass_kg=810.0, crr=0.012, ClA=7.5, eta=1.0): Terminal speed (km/h) on an infinitely long flat straight: solves eta P = v [1/2 rho (CdA + crr ClA) v^2 + crr m g] for v (one positive real root).
  • straight_exit(v0_kmh, length_m, params=None, rho=1.18, drs_from_m=None, CdA_open=None, step_m=1.0, grade=0.0): Integrate a full-throttle run along a straight of length_m starting at v0_kmh.
  • drag_reduction_gain(length_m, v0_kmh, delta_cda, params=None, rho=1.18, open_from_m=0.0): Time and speed gained on a straight by cutting the drag area by delta_cda (m^2) from open_from_m.

boxbox.tyres (Chapter 4)

Box Box - tyres: the compound table and a three-phase tyre model fitted from real stints (Chapter 4).

  • class TyreModel(warmup: float, rate: float, cliff_age: float | None = None, cliff_rate: float = 0.0, warmup_decay: float = 0.4, compound: str | None = None, fit: dict = field(default_factory=...)): Three-phase tyre model: warm-up, linear wear, optional cliff.
  • methods and properties: delta, stint_deltas, stint_time_lost, laps_until_loss
  • fit_tyre_model(stint_laps: pd.DataFrame, y: str | None = None, min_laps: int = 8, cliff_p: float = 0.001, cliff_min_extra: float = 0.15, min_after: int = 4) -> TyreModel: Fit a TyreModel to ONE stint (one driver, one set of tyres).
  • fit_compound_models(laps: pd.DataFrame, y: str | None = None, min_laps: int = 8) -> dict: One TyreModel per dry compound for a session (or any set of laps): fit every stint with fit_tyre_model, then take the MEDIAN warm-up and rate across stints (robust to one odd stint).
  • dry_race_keys(laps: pd.DataFrame | None = None) -> list[int]: Session keys of races with no INTERMEDIATE/WET lap and no rainfall flag (the book's 'dry race' filter).

boxbox.pacejka (Chapter 5)

Box Box - pacejka: the Magic Formula, combined slip, load sensitivity and a 2-node thermal tyre (Chapter 5).

  • magic_formula(slip, B: float, C: float, D: float, E: float, Sh: float = 0.0, Sv: float = 0.0): Pacejka's Magic Formula.
  • mf_peak(B: float, C: float, E: float, x_max: float = 1.0, n: int = 20001) -> tuple[float, float]: Slip at the peak of the (D = 1) curve and the peak value, found on a fine grid in [0, x_max].
  • cornering_stiffness(B: float, C: float, D: float) -> float: Initial slope of the curve, dy/dx at x = 0: B x C x D (N/rad for a lateral force).
  • class TyreParams(Fz0: float = 4000.0, mu0: float = 1.7, load_sens: float = -0.15, By: float = 19.8, Cy: float = 1.4, Ey: float = 0.0, Bx: float = 14.0, Cx: float = 1.65, Ex: float = 0.0, stiff_load_exp: float = 0.8, Bxa: float = 20.0, Cxa: float = 1.0, Byk: float = 16.0, Cyk: float = 1.0, label: str = 'illustrative 2026-style slick (assum...): 🧪 ILLUSTRATIVE slick coefficients.
  • methods and properties: with_
  • mu_at_load(Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...): Peak friction coefficient at normal load Fz (N): mu0 (1 + load_sens (Fz - Fz0)/Fz0), floored at 0.2.
  • mf_lateral(alpha_rad, Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...): Pure-slip lateral force (N) at slip angle alpha (rad) and load Fz (N).
  • mf_longitudinal(kappa, Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...): Pure-slip longitudinal force (N) at slip ratio kappa and load Fz (N).
  • combined_slip(alpha_rad, kappa, Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_..., method: str = 'cosine'): Forces (Fx, Fy) in N when the tyre slips in both directions at once.
  • friction_ellipse(fx_max: float, fy_max: float, n: int = 361) -> pd.DataFrame: Boundary of the friction ellipse (Fx/fx_max)^2 + (Fy/fy_max)^2 = 1 as n points (any units).
  • invert_lateral(Fy, Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...): Slip angle (rad) that produces lateral force Fy at load Fz on the stable (pre-peak) side; NaN if |Fy| exceeds the peak.
  • invert_longitudinal(Fx, Fz, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...): Slip ratio that produces longitudinal force Fx at load Fz (pre-peak side); NaN beyond the peak.
  • slip_power(Fx, Fy, kappa, alpha_rad, v_mps): Power (W) dissipated in the contact patch: |Fx x kappa x v| + |Fy x v x sin(alpha)|.
  • axle_lateral_capacity(Fz_axle: float, dFz: float, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_...) -> dict: Peak lateral force of an axle whose total load Fz_axle is split (Fz_axle/2 + dFz, Fz_axle/2 - dFz) by lateral load transfer dFz.
  • tyre_forces_from_motion(speed_kmh, ax_g, ay_g, mass_kg: float = 780.0, cl_a: float = 7.5, cd_a: float = 1.3, rho: float = 1.18) -> pd.DataFrame: Per-tyre load and forces for an AVERAGE tyre (each quantity / 4).
  • class ThermalTyre(c_surface: float = 900.0, c_carcass: float = 9000.0, g_sc: float = 45.0, g_air0: float = 4.0, g_air1: float = 0.3, g_road: float = 8.0, g_rim: float = 15.0, tyre_share: float = 0.5, share_s: float = 0.8, c_flex: float = 0.004, t_opt: float = 95.0, width: float = 30.0, drop: float = 0.1, f_min: float = 0.7, w_s: float = 0.6, k_wear: float = 2e-09, theta_wear: float = 30.0, t_blister: float = 125.0, t_grain: float = 70.0, p_grain: float = 8000.0, t_start_c: float = 70.0): Two-node lumped thermal tyre with a temperature window and a wear state.
  • methods and properties: reset, step, t_eff, temp_factor, grip_factor, run
  • lap_trace_power(speed_kmh, ax_g, ay_g, time_s, p: TyreParams = TyreParams(Fz0=4000.0, mu0=1.7, load_..., **car) -> pd.DataFrame: Representative-tyre slip power along a lap from (estimated) accelerations: forces from tyre_forces_from_motion, slip from the inverse Magic Formula (capped at the peak slip when the demand exceeds the model tyre's pea...

boxbox.power (Chapter 6)

Box Box - power: the power unit as an energy budget (Chapter 6).

  • class ERSBudget(era: str, year: int, ice_kw: float, mgu_k_kw: float, deploy_mj_per_lap: float | None, harvest_mj_per_lap: float, soc_window_mj: float, mgu_h: bool, fuel_limit: float, fuel_limit_unit: str, race_fuel_kg: float | None, source: str): One era's power-unit limits.
  • methods and properties: lap_deploy_mj, as_dict
  • ers_budget(year: int, kind: str = 'R', round: int | None = None) -> ERSBudget: The PU limits that applied in year for a session kind ("R", "S", "Q", "SQ").
  • deploy_time(energy_mj: float, power_kw: float) -> float: Seconds an MGU-K can deliver power_kw from energy_mj: t = E / P (MJ / kW * 1000).
  • mgu_k_power_limit(v_kmh, year: int, overtake: bool = False, power_limited: bool = False): MGU-K power cap (kW) at speed v_kmh (scalar or array).
  • fuel_flow_limit(rpm, year: int): Maximum fuel flow at engine speed rpm.
  • fuel_power_kw(year: int, rpm=None, lhv_mj_per_kg: float = 43.0) -> float: Chemical power entering the ICE at the flow limit (kW).
  • thermal_efficiency(brake_kw: float, fuel_kw: float) -> float: Brake thermal efficiency = shaft power out / chemical power in.
  • fuel_burn_per_lap(full_throttle_s: float, year: int, part_throttle_s: float = 0.0, part_flow_frac: float = 0.0, lhv_mj_per_kg: float = 43.0) -> dict: Flow-limited fuel per lap: the cap x time at full throttle (+ an optional part-throttle share).
  • race_fuel_per_lap(race_fuel_kg: float, race_laps: int) -> float: Average kg per lap if a race load is burned evenly (e.g. 110 kg / 53 laps).
  • deployment_demand(tel: pd.DataFrame, year: int, threshold: float = 98.0, overtake: bool = False) -> pd.DataFrame: Energy the MGU-K would need to deploy its full speed-dependent cap at every full-throttle sample.
  • lap_energy_check(tel: pd.DataFrame, year: int, kind: str = 'Q', round: int | None = None) -> dict: Compare a lap's full-deployment demand with the era's per-lap budget.
  • clipping_metrics(tel: pd.DataFrame, min_len_m: float = 400.0, thr: float = 98.0) -> dict: The energy-limited ('clipping') signature on one lap: speed falling while the throttle is pinned.
  • gear_speed_ratios(tel: pd.DataFrame, min_rpm: float = 8000.0) -> pd.Series: km/h per 1000 rpm in each gear (median over samples with rpm >= min_rpm and no gear change either side).
  • upshift_rpm(tel: pd.DataFrame) -> pd.DataFrame: rpm at the last sample before each upshift (the shift point, to within one ~0.27 s sample).
  • time_loss_by_phase(ref: pd.DataFrame, cmp: pd.DataFrame, step_m: float = 5.0, thr: float = 98.0) -> pd.DataFrame: Split the lap-time difference (cmp - ref) by what the CMP car is doing at each point of the lap.
  • power_limited_speed(power_kw: float, CdA: float, rho: float = 1.18, mass_kg: float = 810.0, crr: float = 0.012, ClA: float = 7.5, eta: float = 0.92) -> float: Terminal speed (km/h) where wheel power = drag + rolling resistance (an infinitely long straight).
  • simulate_straight(v0_kmh: float, length_m: float, year: int, CdA: float, mass_kg: float = 780.0, energy_mj: float | None = None, ice_kw: float | None = None, ClA: float = 7.5, crr: float = 0.012, rho: float = 1.18, eta: float = 0.92, harvest_kw: float = 0.0, overtake: bool = False, step_m: float = 1.0) -> dict: Integrate a full-throttle run with the era's MGU-K speed cap and a finite battery.

boxbox.brakes (Chapter 7)

Box Box - brakes.py (Chapter 7: Braking)

  • braking_zones(tel: pd.DataFrame, min_duration_s: float = 0.3, min_drop_kmh: float = 20.0, merge_gap_samples: int = 1, window_s: float = 0.5, onset_g: float = 2.0) -> pd.DataFrame: Every real stop on one lap of car_data.
  • decel_profile(tel: pd.DataFrame, zones: pd.DataFrame | None = None, window_s: float = 0.5, dt: float = 0.05) -> pd.DataFrame: Smoothed deceleration sample by sample inside each braking zone (from the middle of the brake-point window to the speed minimum).
  • lap_braking_summary(tel: pd.DataFrame, zones: pd.DataFrame | None = None) -> dict: One lap's braking in numbers: zones, time and distance with the brake on (and their share of the lap), and the hardest stop (largest speed drop).
  • sample_spacing(tel: pd.DataFrame) -> pd.DataFrame: Distance (m) and time (s) between consecutive samples, with the speed at each: the resolution of any position-like quantity (a brake point, a throttle point) on this lap.
  • class DecelModel(A_g: float, B_g: float, label: str = '', onset_s: float = 0.0): Maximum deceleration as a function of speed, a(v) = A + B v^2 (A in g, B in g per (m/s)^2).
  • methods and properties: from_car, fit, fit_peaks, with_onset, decel_g, speed_for_g
  • braking_distance(v0_kmh: float, v1_kmh: float, params) -> dict: Distance and time to brake from v0 to v1 (km/h) at the limit a(v) = A + B v^2.
  • braking_trace(v0_kmh: float, v1_kmh: float, params, n: int = 200) -> pd.DataFrame: Speed, deceleration and elapsed time against distance for a limit stop from v0 to v1 (km/h), using the closed forms of braking_distance on a grid of intermediate speeds.
  • harvest_share(v_kmh, decel_g, mass_kg: float, harvest_kw: float, cd_a: float = 1.3, rho: float = 1.2): Share of the BRAKING force (total retarding force minus drag) that an MGU-K limited to harvest_kw could supply at each speed: min(1, (P / v) / F_brake).
  • stop_energy(v0_kmh: float, v1_kmh: float, mass_kg: float, params=None, cd_a: float = 1.3, rho: float = 1.2, harvest_kw: float = 0.0, n: int = 400) -> dict: Energy budget of one limit stop from v0 to v1 along the a(v) envelope params.
  • lap_braking_energy(tel: pd.DataFrame, mass_kg: float, cd_a: float = 1.3, rho: float = 1.2, harvest_kw: float = 0.0, window_s: float = 0.5, dt: float = 0.05) -> dict: Braking energy on one telemetry lap.
  • class BalanceParams(wheelbase_m: float = 3.4, cog_height_m: float = 0.3, front_static: float = 0.45, aero_front: float = 0.4, mass_kg: float = 780.0, cl_a: float = 5.9, rho: float = 1.2, label: str = 'illustrative 2026-style car (assumed...): 🧪 Assumed geometry for the brake-balance model, not team data.
  • axle_loads(v_kmh, decel_g, p: BalanceParams) -> pd.DataFrame: Front and rear normal loads (N) while braking: static weight split + longitudinal load transfer (m a h / L) + downforce split by the aero balance.
  • ideal_front_share(v_kmh, decel_g, p: BalanceParams | None = None): Front share of the total braking force at which both axles reach the same friction coefficient (the 'ideal' brake balance): N_front / (N_front + N_rear).
  • friction_front_share(ideal_front, harvest_force_n, total_brake_force_n): Front share of the FRICTION braking once the MGU-K supplies harvest_force_n at the rear axle.
  • align_on_line(tel: pd.DataFrame, xy: pd.DataFrame, line: pd.DataFrame, window: int = 15) -> pd.DataFrame: Replace a lap's integrated distance with its position along a common track line.
  • compare_brake_points(tel_a: pd.DataFrame, tel_b: pd.DataFrame, label_a: str = 'A', label_b: str = 'B', min_drop_kmh: float = 40.0, match_m: float = 80.0, rescale: bool = True, measure: str = 'flag') -> pd.DataFrame: Zone-by-zone brake points of two laps of the same circuit.

boxbox.setup (Chapter 8)

Box Box - setup: load transfer, balance, a ride-height toy model and setup scoring (Chapter 8).

  • class ChassisParams(mass_kg: float = 780.0, wheelbase_m: float = 3.4, track_front_m: float = 1.6, track_rear_m: float = 1.55, cg_height_m: float = 0.28, weight_front: float = 0.45, cl_a: float = 5.86, aero_front: float = 0.42, rho: float = 1.153, lltd_front: float = 0.5, label: str = 'illustrative 2026-style chassis (ass...): 🧪 ILLUSTRATIVE chassis values for a 2026-style car.
  • methods and properties: with_
  • static_axle_loads(speed_kmh, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas...): Front and rear axle loads (N) from weight and downforce, before any load transfer.
  • longitudinal_transfer_n(ax_g, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas...): Load moved from the rear axle to the front (N) at longitudinal acceleration ax (g).
  • lateral_transfer_n(ay_g, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas..., lltd_front: float | None = None): (front, rear) load moved from inside to outside wheels (N) at lateral acceleration ay (g).
  • load_transfer(ax_g, ay_g, speed_kmh, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas..., lltd_front: float | None = None, turn_sign=None) -> pd.DataFrame: Wheel loads (N) for measured or modelled accelerations.
  • grip_split(speed_kmh, mu: float, slope: float) -> pd.DataFrame: Split of the lateral limit a/g = mu + slope v^2 (v in m/s; Chapter 1's apex fit) into the part that needs no airflow (mechanical: mu) and the part that downforce adds (slope v^2).
  • crossover_kmh(mu: float, slope: float) -> float: Speed (km/h) where downforce's share of lateral grip equals the mechanical share: v = sqrt(mu/slope).
  • axle_limits(speed_kmh: float, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas..., lltd_front: float | None = None, tyre=None) -> dict: Steady-state cornering limit of each axle (in g) with a load-sensitive tyre (Chapter 5's pacejka).
  • balance_sweep(speeds, lltds, p: ChassisParams = ChassisParams(mass_kg=780.0, wheelbas..., tyre=None) -> pd.DataFrame: axle_limits over a grid of speeds and front LLTD shares.
  • corner_min_speeds(ref_tel: pd.DataFrame, laps: dict, window_m: float = 60.0, prominence_kmh: float = 20.0) -> pd.DataFrame: Apex (minimum) speed of every lap at every corner of a reference lap.
  • relative_apex_deficits(corner_table: pd.DataFrame, max_abs_pct: float = 15.0, max_spread: float = 0.1) -> pd.DataFrame: Add rel_pct = 100 x (field-median apex speed at the corner - this lap's) / field median.
  • balance_index(corner_table: pd.DataFrame, by: str = 'team_ref', min_corners: int = 4, min_range_kmh: float = 60.0, n_boot: int = 1000, seed: int = 42) -> pd.DataFrame: Corner-speed character per team (or driver): the mechanical-vs-aero balance PROXY.
  • practice_runs(laps: pd.DataFrame, fast_ratio: float = 1.1, push_ratio: float = 1.02, long_min: int = 5) -> pd.DataFrame: One row per RUN (a garage-to-garage outing) in a practice session.
  • class PlatformParams(h_static_mm: float = 45.0, cla_ref: float = 5.86, h_ref_mm: float = 30.0, gain: float = 0.3, h_stall_mm: float = 15.0, stall_drop: float = 0.6, k_tyre_n_mm: float = 600.0, bump_mm: float = 3.0, mu0: float = 1.7, load_sens: float = -0.15, fz_wheel_n: float = 6000.0, rho: float = 1.153, label: str = 'illustrative ground-effect platform ...): 🧪 ILLUSTRATIVE ground-effect platform.
  • methods and properties: with_
  • cla_at_height(h_mm, pp: PlatformParams = PlatformParams(h_static_mm=45.0, cla_...): Toy ground-effect curve: ClA rises linearly as the floor lowers until h_stall, then falls.
  • ride_height_at_speed(speed_kmh, k_n_per_mm: float, pp: PlatformParams = PlatformParams(h_static_mm=45.0, cla_...) -> pd.DataFrame: Equilibrium ride height (mm) where the spring force k (h_static - h) balances the downforce q ClA(h).
  • bump_grip_loss(k_n_per_mm: float, pp: PlatformParams = PlatformParams(h_static_mm=45.0, cla_...) -> float: Fraction of mean tyre grip lost to load fluctuation over bumps (toy).
  • setup_score(k_n_per_mm: float, band_time_s: dict, pp: PlatformParams = PlatformParams(h_static_mm=45.0, cla_..., mu_mech: float = 1.51, mass_kg: float = 780.0, plank_penalty_s: float = 1.0) -> dict: Lap-time change (s) of a heave stiffness k on a circuit, relative to the same car with the toy floor at its reference height and perfectly smooth tyres (🧪 every input is an assumption).

boxbox.driver (Chapter 9)

Box Box: driver.py (Chapter 9, The Driver).

  • stint_residuals(laps: pd.DataFrame, min_clean: int = 8, warmup_laps: int = 1, clean_air_s: float = 2.0) -> pd.DataFrame: Residuals of every green racing lap around its stint's robust (Theil-Sen) line.
  • robust_sd(x) -> float: 1.4826 x median absolute deviation: an SD that ignores a few wild values.
  • consistency(laps: pd.DataFrame, min_laps: int = 30, clean_air_only: bool = True, error_threshold_s: float = 1.0, by: str = 'driver_ref') -> pd.DataFrame: Per-driver consistency from a residual table (stint_residuals) or a raw laps table.
  • error_laps(residuals: pd.DataFrame, threshold_s: float = 1.0, clean_air_only: bool = True) -> pd.DataFrame: The unforced slow laps: green racing laps whose residual exceeds threshold_s (in clean air by default).
  • lag1_autocorr(residuals: pd.DataFrame, max_abs_s: float = 1.0) -> float: Pooled lag-1 autocorrelation of residuals on consecutive laps of the same stint (error laps removed).
  • class DriverNoise(sigma_s: float, rho: float = 0.0, p_error: float = 0.0, error_mean_s: float = 2.0, error_threshold_s: float = 1.0, label: str = 'field'): Lap-time noise for one driver (or a field average), in seconds.
  • methods and properties: sample
  • driver_noise_model(residuals: pd.DataFrame, driver: str | None = None, error_threshold_s: float = 1.0, min_laps: int = 30, clean_air_only: bool = True) -> DriverNoise: Fit a DriverNoise from a residual table: sigma = robust SD of the core laps (|resid| <= threshold), rho = their lag-1 autocorrelation, p_error and error_mean_s from the laps above the threshold.
  • noise_table(residuals: pd.DataFrame, by: str = 'driver_ref', error_threshold_s: float = 1.0, min_laps: int = 150) -> pd.DataFrame: driver_noise_model for every driver with enough clean-air laps, with Wilson CIs on p_error.
  • throttle_profile(tel: pd.DataFrame, full: float = 98.0, coast: float = 1.0) -> dict: Shares of lap DISTANCE by pedal state for one lap of car_data (telemetry.lap_telemetry).
  • braking_workload(tel: pd.DataFrame, race_laps: int, min_duration_s: float = 0.4) -> dict: Braking events and time on the brake per lap, scaled to a race distance.
  • teammate_deg_pairs(session, min_laps: int = 8, max_start_offset: int = 3) -> pd.DataFrame: Teammates on the SAME compound in stints that started within max_start_offset laps of each other (a proxy for "the same strategy"), each with >= min_laps usable laps.

boxbox.circuit (Chapter 10)

Box Box - circuit: what kind of track is this, measured from the data (Chapter 10).

  • reference_attributes(circuit_ref: str, year: int | None = None) -> dict: Official facts for a circuit from data/reference/circuits_2023_2026.csv: lap length (km), corners, race laps, DRS zones, with the source of each.
  • lap_quality(tel: pd.DataFrame, official_km: float | None = None) -> dict: Quality check for one lap of car_data.
  • straights(tel: pd.DataFrame, min_len_m: float = 400.0, thr: float = 98.0) -> pd.DataFrame: Full-throttle, brake-off runs at least min_len_m long: start/end distance, length, entry, peak and end speed.
  • corner_table(tel: pd.DataFrame, prominence_kmh: float = 20.0) -> pd.DataFrame: Corners as speed minima (telemetry.corners_from_speed) with a speed class: slow / medium / fast.
  • elevation_profile(tel: pd.DataFrame, smooth: int = 7) -> pd.DataFrame: Height along the lap from location z (decimetres -> metres), relative to the lowest point, smoothed with a centred rolling median of smooth samples.
  • lap_profile(tel: pd.DataFrame) -> dict: Profile features of one qualifying lap (definitions in the module docstring).
  • top_laps(session, n: int = 5, with_location: bool = False): Fastest laps of the top-n classified drivers that have car_data on disk and pass lap_quality().
  • session_is_wet(session) -> bool: > 20 % of the session's laps on INTERMEDIATE/WET or with the rainfall flag.
  • circuit_pit_loss(circuit_ref: str, years=(2023, 2024, 2025, 2026)) -> dict: Canonical green-flag pit loss pooled over every used stop at the circuit (median, bootstrap 95 % CI, IQR, n stops, n races).
  • race_is_dry(session) -> bool: No INTERMEDIATE/WET lap and no rainfall flag anywhere in the race.
  • race_stint_slopes(session, min_laps: int = 8) -> pd.DataFrame: Per-stint degradation slopes for one dry race: canonical (fuel-corrected with the toolkit's assumption) and data-corrected (raw slope minus the race's fuel + track-evolution slope).
  • circuit_deg_index(circuit_ref: str, years=(2023, 2024, 2025, 2026), correction: str = 'data') -> dict: Degradation index: median stint slope (s/lap) over dry-compound stints (>= 8 usable clean laps) in the circuit's dry races.
  • class Circuit(circuit_ref: str, year: int, gp_name: str, official_length_m: float, official_corners: float, race_laps: float, n_laps_used: int, drivers: list = field(default_factory=...), wet_session: bool = False, full_throttle_pct: float = nan, top_speed_kmh: float = nan, mean_speed_kmh: float = nan, braking_zones: float = nan, braking_per_km: float = nan, corners_detected: float = nan, slow_corners: float = nan, medium_corners: float = nan, fast_corners: float = nan, min_corner_kmh: float = nan, median_corner_kmh: float = nan, max_corner_kmh: float = nan, longest_straight_m: float = nan, elevation_range_m: float = nan, lap_distance_m: float = nan, pit_loss_s: float = nan, pit_loss_n: int = 0, deg_index: float = nan, deg_n: int = 0, rejected: list = field(default_factory=...)): One circuit, one season: telemetry profile (median of top-n qualifying laps) + strategy geography.
  • methods and properties: as_dict, summary
  • circuit_profile(year: int, gp, n_top: int = 5, with_strategy: bool = True, with_location: bool = True, strategy_years=(2023, 2024, 2025, 2026)) -> Circuit: Build the Circuit profile from the season's qualifying session (median of the top-n quality laps) and, if with_strategy, the pooled pit loss and degradation index at the venue over strategy_years.
  • profile_table(years=(2025, 2026), n_top: int = 5, with_strategy: bool = False, with_location: bool = True, verbose: bool = False) -> pd.DataFrame: circuit_profile() for every qualifying session of years with car_data on disk; one row each.
  • classify_circuits(table: pd.DataFrame, k: int | None = None, features=['full_throttle_pct', 'top_speed_kmh'..., random_state: int = 42): k-means speed types on standardised per-circuit medians of features (dry sessions only).
  • similar_circuits(circuit_ref: str, table: pd.DataFrame, n: int = 3, features=['full_throttle_pct', 'top_speed_kmh'...) -> pd.DataFrame: The n circuits nearest to circuit_ref in standardised feature space (Euclidean distance on z-scores of the per-circuit medians).
  • track_map(year: int, gp, driver=None, color_by: str = 'speed', corners: bool = True, title=None): Track map of a qualifying lap (pole lap by default) coloured by color_by, with detected corners numbered in lap order.

boxbox.lapsim (Chapter 11)

Box Box - lapsim: a quasi-steady-state point-mass lap simulator (Chapter 11).

  • class SimParams(year: int = 2026, mass_kg: float = 780.0, mu: float = 1.51, cl_a: float = 5.86, cd_a: float = 1.27, cd_a_low: float | None = None, rho: float = 1.153, crr: float = 0.012, ice_kw: float = 400.0, ers_kw: float = 350.0, eta: float = 0.92, deploy_mj: float | None = 11.0, drive_share: float = 0.55, brake_A_g: float = 0.84, brake_mu: float = 1.48, brake_onset_s: float = 0.172, energy_policy: str = 'spread', brake_exp: float = 2.0, overtake: bool = False, label: str = 'illustrative 2026 car (assumed / fit...): Point-mass car for the lap simulator.
  • methods and properties: with_, lat_B, brake_B_g
  • preset(year: int, round: int | None = None) -> SimParams: The book's best estimate of a 2025 or 2026 qualifying car, assembled from earlier chapters.
  • round_(x, nd=3)
  • class Track(s: np.ndarray, kappa: np.ndarray, grade: np.ndarray, low_drag: np.ndarray, x: np.ndarray, y: np.ndarray, length_m: float, step_m: float, label: str = '', meta: dict = field(default_factory=...)): A closed lap on a uniform distance grid.
  • methods and properties: radius_m
  • curvature_from_xy(x, y, step_m: float = 2.0, window_m: float = 40.0) -> pd.DataFrame: Curvature of a closed path from position samples (metres).
  • track_from_line(line: pd.DataFrame, step_m: float = 4.0, length_m: float | None = None, ref: pd.DataFrame | None = None, grade_window_m: float = 150.0, label: str = '') -> Track: Turn a reference line (s, x, y, kappa) into a Track on a step_m grid.
  • reference_lap(session, n_candidates: int = 3): The fastest lap of the session's top qualifiers that passes Chapter 10's lap_quality gate and Chapter 1's speed-jump test, with its location path.
  • align_lap(tel: pd.DataFrame, xy: pd.DataFrame, line: pd.DataFrame) -> pd.DataFrame: The lap's telemetry with distance_m replaced by its position along line (Chapter 7's brakes.align_on_line).
  • track_from_session(session, step_m: float = 4.0, window_m: float = 40.0, line: pd.DataFrame | None = None): Build a Track for a qualifying session: the multi-car averaged line (physics.session_line) rescaled to the reference lap's integrated distance, with grade and DRS zones from that lap.
  • corner_limit(track: Track, params: SimParams, v_cap_kmh: float = 400.0) -> np.ndarray: Cornering-limited speed (m/s) at each grid point: v_max^2 = mu g / (|kappa| - mu rho ClA / 2m), capped at v_cap where the corner is flat out (|kappa| <= mu rho ClA / 2m).
  • class SimResult(lap_time_s: float, trace: pd.DataFrame, energy_mj: float, v_clip_kmh: float, params: SimParams, track: Track, deploy_frac: float = 1.0): SimResult(lap_time_s: 'float', trace: 'pd.DataFrame', energy_mj: 'float', v_clip_kmh: 'float', params: 'SimParams', track: 'Track', deploy_frac: 'float' = 1.0)
  • methods and properties: summary
  • simulate_lap(track: Track, params: SimParams, energy: str = 'auto', v_clip_kmh: float | None = None, tol_mj: float = 0.02) -> SimResult: Simulate one flying lap.
  • compare_to_lap(result: SimResult, aligned: pd.DataFrame, lap_time_s: float | None = None) -> dict: Score a simulated lap against a real one ALIGNED on the same line (track_from_session's second output, which carries s_track).
  • sensitivity(track: Track, params: SimParams, changes: dict | None = None) -> pd.DataFrame: Lap-time change (s, negative = faster) for each parameter change.
  • lap_time_per_kg(track: Track, params: SimParams, dm_kg: float = 10.0) -> float: Lap-time sensitivity to mass (s per kg), by central difference +-dm_kg/2.
  • fit_params(cases, base: SimParams, fields, x0, bounds, objective: str = 'rms', maxiter: int = 200): Calibrate parameters on real laps.

boxbox.strategy (Chapter 12)

Box Box - strategy: the race-strategy optimiser at the core of the simulator (Chapter 12).

  • class CompoundParams(deg_s_per_lap: float, offset_s: float = 0.0, warmup_s: float = 0.0, curvature_s_per_lap2: float = 0.0, max_laps: int | None = None): Lap-time behaviour of one compound, relative to the base lap.
  • class RaceModel(total_laps: int, pit_loss_s: float, compounds: dict, base_lap_s: float = 0.0, fuel_start_penalty_s: float = 3.0, first_stint_age: int = 0, label: str = ''): Everything the optimiser needs to price a strategy for one race.
  • methods and properties: fuel_time
  • class Strategy(compounds: tuple, stop_laps: tuple = field(default_factory=...)): A compound sequence and the in-laps of the stops: Strategy(("MEDIUM", "HARD"), (24,)) = start on MEDIUM, pit at the end of lap 24, run HARD to the flag.
  • methods and properties: parse, n_stops, sequence, stint_lengths, describe
  • is_legal(strategy: Strategy, total_laps: int, dry: bool = True, min_compounds: int = 2, min_sets: int | None = None, sets_available: dict | None = None, min_stint: int = 1, compounds: dict | None = None) -> bool: Sporting legality plus practical limits.
  • stint_time(p: CompoundParams, n_laps: int, start_age: int = 0, new_set: bool = True) -> float: Tyre time of one stint relative to the base lap: sum over its laps of offset + degage + curvage^2, plus the warm-up penalty if the set is fitted at a stop (new_set=True).
  • race_time_breakdown(strategy: Strategy, model: RaceModel) -> dict: Race time split into its parts (s): base, fuel, tyres (offset + wear), warm-up, pit loss, and total.
  • race_time(strategy: Strategy, model: RaceModel) -> float: Total race time (s) of a strategy under the linear stint model.
  • lap_times(strategy: Strategy, model: RaceModel, pit_in_share: float = 0.19099995635284361) -> np.ndarray: Predicted time of every lap (s).
  • enumerate_strategies(total_laps: int, compounds=('SOFT', 'MEDIUM', 'HARD'), max_stops: int = 3, min_stint: int = 5, dry: bool = True, min_compounds: int = 2, sets_available: dict | None = None, min_sets: int | None = None, start_compound: str | None = None, step: int = 1, min_stops: int = 1) -> Iterator[Strategy]: Yield every legal strategy: each compound sequence with min_stops..max_stops stops, each combination of in-laps on a grid of step laps, every stint >= min_stint laps.
  • optimise(model: RaceModel, max_stops: int = 3, min_stint: int = 5, dry: bool = True, min_compounds: int = 2, sets_available: dict | None = None, min_sets: int | None = None, start_compound: str | None = None, min_stops: int = 1, compounds=None) -> pd.DataFrame: Search every legal strategy (exhaustive over in-laps for each compound sequence) and return one row per compound sequence with its best in-laps, ranked by race time.
  • best_by_stops(table: pd.DataFrame) -> pd.DataFrame: From an optimise table, the best strategy for each stop count.
  • one_stop_curve(model: RaceModel, c1: str, c2: str, min_stint: int = 5) -> pd.DataFrame: Race time of the one-stop c1 -> c2 for every in-lap (columns stop_lap, race_time_s, delta_s to the best).
  • optimal_one_stop_lap(model: RaceModel, c1: str, c2: str) -> float: Closed-form optimum of the one-stop c1 -> c2 under linear degradation (continuous stop lap s): s* = (d2 * N + o2 - o1 + (d1 - d2) / 2 - d1 * a0) / (d1 + d2) where d = deg rate, o = offset, a0 = age of the starting set.
  • break_even_laps(pit_loss_s: float, fresh_tyre_delta_s: float) -> float: Laps needed for a constant fresh-tyre advantage (s/lap) to repay one pit loss (s).
  • extra_stop_gain(deg_s_per_lap: float, total_laps: int, n_stops: int) -> float: Wear time saved by going from n_stops to n_stops + 1 with equal stints on one compound (continuous approximation): d * N^2 / (2 (n+1)(n+2)).
  • critical_deg(pit_loss_s: float, total_laps: int, n_stops: int = 1, warmup_s: float = 0.0) -> float: Degradation rate (s/lap per lap of age) at which n_stops + 1 stops ties n_stops stops: d* = 2 (n+1)(n+2) (pit loss + warm-up) / N^2.
  • is_dry_race(session) -> bool: The book's dry-race filter: no INTERMEDIATE/WET lap and no rainfall flag on any lap of the race (the lap's nearest weather record; rain reported before the start or after the flag does not count).
  • actual_strategies(session) -> pd.DataFrame: One row per driver: what they actually did, from OpenF1 stints.
  • fit_race_model(session, pit_loss_s: float | None = None, offsets='pooled', warmup='pooled', min_laps: int = 8, first_stints_only: bool = False, first_stint_age: int = 0, min_stints: int = 3) -> tuple[RaceModel, pd.DataFrame]: Build a RaceModel for one race from its own timing data.

boxbox.undercut (Chapter 13)

Box Box - undercut: what pit-stop timing does to track position between two cars (Chapter 13).

  • simulate_pair(old_age_b: int, old_age_a: int | None = None, k: int = 1, deg_s_per_lap: float = 0.051, deg_new_s_per_lap: float | None = None, old_compound: str = 'MEDIUM', new_compound: str = 'HARD', offset_old_s: float = 0.0, offset_new_s: float = 0.0, warmup: dict | None = None, settle_laps: int = 2, in_lap_excess_s: float = 4.372, out_lap_excess_s: float = 18.534, stop_delta_s: float = 0.0, defender_in_lap_bonus_s: float = 0.0, attacker_traffic_s: float = 0.0, old_compound_a: str | None = None, deg_old_a_s_per_lap: float | None = None, offset_old_a_s: float | None = None) -> pd.DataFrame: Lap-by-lap times of attacker B (stops first, lap 0 = B's in-lap) and defender A (stops k laps later).
  • undercut_gain(old_age: int, k: int = 1, deg_s_per_lap: float = 0.051, settle_laps: int = 2, **kw) -> dict: Predicted gain to the car that pits first (s), measured settle_laps laps after the defender's out-lap, split the same way as the measured decomposition.
  • required_gap(old_age: int, k: int = 1, deg_s_per_lap: float = 0.051, p_success: float | None = None, residual_sd_s: float | None = None, **kw) -> float: The largest gap (s) the undercut is expected to close.
  • predict_pair(row, degs: dict | None = None) -> float: The two-car model's predicted gain to the attacker B for one measured situation (a row of study()).
  • find_undercut_attempts(session, gap_max: float = 3.0, max_k: int = 3, settle_laps: int = 2, kinds=('undercut', 'overcut')) -> pd.DataFrame: Every undercut and overcut situation in one race (definitions in the module docstring).
  • study(sessions=None, **kw) -> pd.DataFrame: find_undercut_attempts over many races (default: every OpenF1 race in the processed data).
  • summarise(pairs: pd.DataFrame, by=None) -> pd.DataFrame: Success rate (Wilson 95 % CI) and median gain (bootstrap 95 % CI, seed 42) per group.
  • decompose(pairs: pd.DataFrame, by='kind') -> pd.DataFrame: Mean and median of each component (in, out, fresh, settle) and of the gain; the means add up exactly.
  • success_curve(pairs: pd.DataFrame, kind: str = 'undercut', extra=()): Logistic regression of success on the gap before the stop (plus optional extra columns).
  • pair_gap(session, attacker, defender) -> pd.DataFrame: Gap between two cars at the end of every lap both completed: gap_s = attacker's line time - defender's (positive = attacker behind), with each car's lap time, compound, tyre age and pit flags.

boxbox.neutralisation (Chapter 14)

Box Box - neutralisation: safety cars, virtual safety cars and red flags (Chapter 14).

  • red_flag_windows(session) -> pd.DataFrame: RED windows from race control, reading both the 2023-25 wording (category Flag, flag RED) and the 2026 wording ("RED FLAG - RACE SUSPENDED", category Other).
  • windows(session) -> pd.DataFrame: All SC, VSC and RED windows of a race: SC/VSC from f1data.track_periods, RED from red_flag_windows (which also catches the 2026 wording).
  • incidents(session, tol_s: float = 30.0) -> pd.DataFrame: Group windows into incidents: a window that starts while the previous one is open (or within tol_s of its end) joins it.
  • lap_status(session, min_share: float = 0.5) -> pd.DataFrame: Per race lap: the share of cars completing it whose lap overlapped an SC / VSC / RED window, and the flags sc_lap, vsc_lap, red_lap and neutral (>= min_share of the field).
  • phase_of(lap: int, n_laps: int) -> str: Race phase of a lap: 'lap 1', 'laps 2-10', 'middle' (11 to N-10) or 'final 10'.
  • races(years=(2023, 2024, 2025, 2026)) -> pd.DataFrame: Grand Prix race sessions with lap data (sprints excluded), in calendar order.
  • race_summary(sessions: pd.DataFrame | None = None) -> pd.DataFrame: One row per race: laps, deployments (sc, vsc, red), incidents, SC/VSC/red/neutral laps, first incident lap, and the incident start laps and kinds (for hazard work).
  • detector_periods(year: int, rnd: int) -> pd.DataFrame: Runs of consecutive laps flagged by metrics.neutralised_laps_history (1996-2022): start_lap, end_lap, length.
  • poisson_ci(k: int, exposure: float, level: float = 0.95) -> tuple[float, float]: Exact (Garwood) interval for a Poisson rate k / exposure.
  • hazard_by_phase(summary: pd.DataFrame, kinds=('SC', 'VSC', 'RED')) -> pd.DataFrame: Per-lap hazard by phase from race_summary rows (or detector rows with the same columns): events = incident start laps of the given kinds, exposure = laps at risk.
  • p_at_least_one(hazard: dict, n_laps: int, k: float = 1.0) -> float: P(>= 1 incident in an n-lap race) when each lap carries hazard k x lambda(phase), assuming every lap is at risk: 1 - exp(-sum of the per-lap hazards).
  • expected_incidents(hazard: dict, n_laps: int, neutral: set = frozenset(), starts: set = frozenset()) -> float: Incidents expected in one race from the phase hazards, over its laps at risk.
  • circuit_multiplier(circuit_ref: str, hazard: dict | None = None, rc_summary: pd.DataFrame | None = None, detector_years=range(2008, 2023)) -> dict: Circuit hazard multiplier k = observed incidents / incidents expected from the all-circuit phase hazards over that circuit's laps at risk, with an exact Poisson interval.
  • sc_hazard(circuit: str | None = None, k: float | None = None, hazard: dict | None = None) -> dict: Per-lap incident hazard by phase for a circuit: k x the all-circuit phase hazard.
  • incident_library(summary: pd.DataFrame) -> pd.DataFrame: Kind and length (in laps) of every incident in race_summary rows.
  • near_field_pit_loss(session, near_s: float = 15.0, min_comp: int = 2) -> pd.DataFrame: Per stop: the 'near-field pit loss' = (in-lap + out-lap of the pitting car) - median(lap L + lap L+1) of the cars that started lap L within +-near_s seconds of it and pitted on neither lap.
  • sc_pit_loss(green_loss_s: float, kind: str = 'SC', definition: str = 'field') -> float: Expected pit loss under a neutralisation: green loss x the measured ratio (SC_RATIO[definition][kind]).
  • neutralised_stop_gain(deg_s_per_lap: float, tyre_age: int, laps_left: int, stop_loss_s: float, new_set_offset_s: float = 0.0, new_set_deg_s_per_lap: float | None = None) -> float: Closed form for an EXTRA stop under SC/VSC with linear wear: time saved over the remaining laps by a new set, minus the stop's cost.
  • class TyreSet(deg: tuple, offset: tuple, cap: tuple): Linear tyre model for one race.
  • methods and properties: from_dicts, d
  • clean_race_plan(tyres: TyreSet, n_laps: int, n_stops: int, loss_g: float) -> tuple: Best plan with exactly n_stops (1 or 2) in a race with no neutralisation: (start compound, plan, cost).
  • sample_neutralisations(n_laps: int, hazard: dict, rng: np.random.Generator, library: pd.DataFrame) -> np.ndarray: One simulated race's lap statuses ('' green, 'SC', 'VSC', 'RED').
  • simulate_car(status: np.ndarray, start: str, plan: tuple, smin: int, smax: int, tyres: TyreSet, loss_model: dict, realised: dict) -> tuple[float, list]: Drive one car through a race.
  • monte_carlo(n_sim: int, n_laps: int, hazard: dict, tyres: TyreSet, green_pool: np.ndarray, library: pd.DataFrame, ratio: dict | None = None, seed: int = 42) -> pd.DataFrame: Simulate n_sim races for three policies on common random numbers: one = exactly one stop (its timing may move into an SC/VSC), two = exactly two stops (same freedom), flex = plan one stop, allow a second only when a n...

boxbox.wet (Chapter 15)

Box Box - wet: slick / intermediate / wet crossovers and the wet lap-time penalty (Chapter 15).

  • tyre_class(compound) -> str | None: SOFT/MEDIUM/HARD -> 'SLICK', INTERMEDIATE -> 'INTER', WET -> 'WET', anything else -> None.
  • wet_sessions(years=(2023, 2024, 2025, 2026), kinds=('R',)) -> pd.DataFrame: Sessions with any INTERMEDIATE or WET lap: counts of laps per class and drivers on wet-weather tyres.
  • field_mix(session) -> pd.DataFrame: Per lap: number of cars on each tyre class (all laps, pit laps included), the share on each class, the share of laps with a rainfall flag and the modal track status.
  • representative_laps(session, max_ratio: float = 1.4, dry_ref: float | None = None, allow_yellow: bool = True) -> pd.DataFrame: Laps that measure pace in changing conditions (definition in the module docstring).
  • dry_reference(session, min_slick_share: float = 0.9) -> dict: The race's own dry pace: median representative slick lap on fully dry laps (module docstring).
  • class_pace(session, min_cars: int = 2, dry_ref: float | None = None) -> pd.DataFrame: Per lap and tyre class: median representative lap (s), cars, and the median as a ratio of dry pace.
  • crossover_lap(session, from_cls: str = 'INTER', to_cls: str = 'SLICK', laps=None, min_cars: int = 1, confirm: int = 2) -> dict: The measured crossover between two tyre classes (definition in the module docstring).
  • switch_table(session, from_cls: str, to_cls: str, laps) -> pd.DataFrame: One row per driver who changed from from_cls to to_cls inside laps = (first, last): the in-lap of the change (the last lap on the old tyres), position before and after, and the pit-lane time.
  • window_time(session, laps) -> pd.Series: Each driver's summed lap time over laps (first..last), for drivers who completed all of them.
  • class WetPenaltyModel(tie_slick: float, slope_slick: float, tie_wet: float, slope_wet: float, n_ties_slick: int = 0, n_ties_wet: int = 0, n_slope_slick: int = 0, n_slope_wet: int = 0): Lap-time penalty over dry pace (a fraction) for each tyre class as a function of the WETNESS GAUGE w.
  • methods and properties: penalty, lap_time, crossover, best_class, delta_s
  • paired_laps(sessions, min_cars: int = 1) -> pd.DataFrame: Laps on which tyre classes ran side by side: one row per (session, lap) with each class's median representative lap as an excess over that race's dry pace.
  • tie_points(pairs: pd.DataFrame, other: str = 'SLICK') -> pd.DataFrame: Every sign change of (other - INTER) between two consecutive paired laps of one session, with the gauge interpolated linearly to the tie.
  • slick_rate_ratio(pairs: pd.DataFrame, min_laps: int = 4, min_inter_rate: float = 0.002) -> pd.DataFrame: How much faster slicks gain (or lose) time than intermediates as conditions change: in every run of >= min_laps consecutive paired laps, the per-lap OLS slope of the slick excess divided by that of the inter excess.
  • wet_slope(pairs: pd.DataFrame) -> tuple: WLS slope, its SE and n for the full-wet excess on the inter excess over laps where both ran (weight = the smaller car count).
  • wet_penalty_model(pairs: pd.DataFrame) -> WetPenaltyModel: Build the WetPenaltyModel from paired_laps output.
  • late_switch_cost(g_s_per_lap2: float, k_laps: float, b_s_per_lap: float = 0.0) -> float: Time lost by switching k laps after the crossover when the delta between the classes grows by g s/lap each lap (and starts at b s on the crossover lap): sum_{j=0}^{k-1} (b + g j) = k b + g k(k-1)/2.
  • switch_decision(delta_s, pit_loss_s: float = 22.512, must_stop: bool = False) -> dict: Choose when to change tyre class over the remaining laps.
  • worth_switching(laps_left: int, delta_s_per_lap: float, kind: str = 'GREEN', green_loss_s: float | None = None) -> bool: Is a switch worth it with laps_left laps to go at a constant advantage of delta_s_per_lap? Uses the Chapter 12 break-even (strategy.break_even_laps).
  • teammate_lap_gaps(session, cls_wet=('INTER', 'WET')) -> pd.DataFrame: Per team-mate pair in one race: median paired gap (% of lap time) on laps where BOTH ran wet-weather tyres, and on laps where both ran slicks.

boxbox.qualifying (Chapter 16)

Box Box: qualifying.py (Chapter 16, Qualifying Strategy).

  • n_advancing(year: int, phase: int) -> int: Cars that go through from phase 1 (Q1) or phase 2 (Q2), per the sporting regulations.
  • is_wet(session) -> bool: Wet session rule used across the book: > 20 % of laps on INTERMEDIATE/WET or with the rain flag.
  • phases(session) -> pd.DataFrame: Phase windows from race control: one row per phase (1, 2, 3) with start (first SESSION STARTED of the phase), flag (first track CHEQUERED FLAG of the phase, NaT if the message is missing) and red_flag (a r...
  • deleted_laps(session) -> pd.DataFrame: Laps deleted by race control: driver_number, lap_time_s (when the message gives a time), lap_number (when it names a lap), reason.
  • quali_laps(session) -> pd.DataFrame: All laps of a Qualifying / Sprint Qualifying session with Saturday-specific tags:
  • track_evolution(session, phase: int | None = None, min_laps: int = 2) -> dict: Within-session track evolution: OLS of push-lap time on minutes elapsed, with a fixed effect per driver (each driver is compared only with themselves) and a control for tyre age on the lap.
  • cut_trajectory(session, phase: int = 1, step_s: float = 15.0) -> pd.DataFrame: The running elimination line of phase 1 or 2: at each moment, the k-th best of the drivers' best valid (not deleted) lap times completed so far, where k = cars that go through.
  • official_cut(session, phase: int = 1) -> float: The official cut line from the session classification (OpenF1 results q1/q2): the k-th best time.
  • cut_drop_table(sessions, phases_=(1, 2), minutes=(10, 8, 6, 5, 4, 3, 2, 1, 0)) -> pd.DataFrame: History for the cut-line predictor: for each session and phase, the running cut at m minutes before the flag and how much it still fell (drop_s = cut at m - final cut, >= 0).
  • cut_line_prediction(current_cut_s: float, minutes_to_flag: float, history: pd.DataFrame, phase: int = 1, lap_time_s: float | None = None, quantiles=(0.1, 0.5, 0.9)) -> dict: Predict the final cut line from the running cut minutes_to_flag minutes before the flag, using the empirical distribution of relative drops in history (cut_drop_table) at the nearest tabulated minute.
  • theoretical_best(session) -> pd.DataFrame: Per driver: best S1 + best S2 + best S3 over all laps of the session that were not deleted (a sector set on an abandoned lap still counts) vs the fastest valid lap.
  • class RunTiming(out_lap_s: float = 130.0, push_lap_s: float = 90.0, cool_lap_s: float = 125.0, garage_turnaround_s: float = 240.0, safety_margin_s: float = 20.0): Lap components for planning a qualifying run (seconds).
  • run_plan(phase_min: float, timing: RunTiming = RunTiming(out_lap_s=130.0, push_lap_s..., sets: int = 2, pushes_per_set: int = 1) -> dict: How many runs fit in a phase and the latest moment to leave the garage for the final run.

boxbox.start (Chapter 17)

Box Box: start.py (Chapter 17, Race Start and Lap 1).

  • slot_label(grid, pit_lane_start) -> str: Grid-slot bucket used in every table: "1".."20", "21+" (old 22-26 car fields) or "pit lane".
  • lap1_table(years=range(1996, 2027), cache: str | Path | None = None) -> pd.DataFrame: Lap-1 gains for every driver-start that completed lap 1 (Jolpica, 1996 onward).
  • slot_outcomes(years=range(1996, 2027)) -> pd.DataFrame: Every starter on a real grid slot (grid >= 1): year, round, grid, lap1_position (NaN = retired on lap 1).
  • lap1_retirements(years=range(1996, 2027)) -> pd.DataFrame: One row per race: starters, lap-1 retirements (0 laps completed, DNF status) and who they were.
  • gain_by_slot(table: pd.DataFrame, n_boot: int = 2000) -> pd.DataFrame: Mean lap-1 gain per grid slot (bootstrap 95 % CI, seed 42) and the gained/held/lost shares.
  • lap1_gain_distribution(grid_slot, era: str | None = None, table: pd.DataFrame | None = None, years=None, min_n: int = 150, max_width: int = 3) -> pd.Series: Empirical P(lap-1 gain = k) for a grid slot, optionally within one era.
  • pole_hold_rate(table: pd.DataFrame, era: str | None = None, years=None) -> dict: Share of pole-sitters leading at the end of lap 1, with a Wilson 95 % interval.
  • odd_even_pairs(table: pd.DataFrame) -> pd.DataFrame: Row-mates: for each race and row k, the odd-slot car (2k-1) and the even-slot car (2k) one slot back on the other side.
  • driver_start_ratings(table: pd.DataFrame, since: int = 2014, until: int | None = None, min_starts: int = 60, n_boot: int = 2000) -> pd.DataFrame: Each driver's mean lap-1 gain minus the mean gain for his grid slot in that era (bootstrap 95 % CI).
  • lap1_retirement_prob(retirements: pd.DataFrame, era: str | None = None, years=None) -> float: Lap-1 retirements per starter in an era (or a list of years).
  • sample_lap1(grid, era: str, n_sims: int = 1, method: str = 'race', table: pd.DataFrame | None = None, p_retire: float | None = None, retirements: pd.DataFrame | None = None, seed: int = 42) -> pd.DataFrame: Simulate the order at the end of lap 1 for a whole field.
  • simulate_slot_summary(sims: pd.DataFrame) -> pd.DataFrame: Per grid slot: P(retire), mean gain of survivors, P(lead) and P(lose >= 3) from sample_lap1 output.

boxbox.pitwall (Chapter 18)

Box Box - pitwall: an event-driven, lap-by-lap decision loop for the pit wall (Chapter 18).

  • cover_gap_s(p: float = 0.5, logit: tuple = (2.171, -1.597)) -> float: Gap (s) at which the Ch 13 logistic curve gives P(undercut works) = p.
  • classify_message(msg: str) -> str: One race-control message -> an event kind (see _EVENT_PATTERNS); OTHER when nothing matches.
  • event_stream(session) -> pd.DataFrame: The race-control feed of one session as typed events, in time order.
  • deployment_warning(session, lookback_s: float = 120.0) -> pd.DataFrame: For each SC / VSC / red-flag window: how many seconds before it the first sector yellow or double yellow of the same episode appeared (searching back lookback_s).
  • tyre_changes(laps: pd.DataFrame) -> pd.Series: True on a lap at whose end the car changed to a different tyre set: the next lap's compound differs, or its tyre age does not keep counting up (+1, or +2 across an empty OpenF1 stint).
  • class RaceState(session_key: int, time: pd.Timestamp, leader_lap: int, total_laps: int, status: str, cars: pd.DataFrame, events: pd.DataFrame, trigger: str = 'lap', dry: bool = True): What the pit wall knows at one instant.
  • methods and properties: laps_left, car, summary
  • class RaceFeed(session, lead_s: float = 10.0): Replays one race as a live feed.
  • methods and properties: status_at, leader_lap_at, state_at, step, ticks, actual_pit
  • class Rules(pit_loss: dict = field(default_factory=...), deg: dict = field(default_factory=...), lead_s: float = 10.0, min_laps_left: int = 5, green_age: float = field(default_factory=...), cover_gap_s: float = field(default_factory=...), margin_s: float = 0.0, min_age_sc: int = 2, min_age_vsc: int = 2, vsc_extra_stops: bool = True): The pit wall's rule book.
  • methods and properties: v2
  • needs_stop(compounds_used, dry: bool = True) -> bool: True when the two-compound rule still forces a stop (dry race, fewer than two dry compounds used).
  • choose_compound(compounds_used, laps_left: int, dry: bool = True) -> str: A simple, stated compound rule for a stop: SOFT for <= 20 laps, MEDIUM for <= 35, otherwise HARD; if the two-compound rule is still open, never refit the only compound used so far.
  • decide(state: RaceState, rules: Rules | None = None) -> pd.DataFrame: One call per running car: BOX / STAY / CHANGE, with the reason and the estimated gain (s, positive = the call is worth that much against the alternative).
  • class DecisionLog(rows: list = field(default_factory=...)): Every call the loop made, with the state it was made in.
  • methods and properties: record, to_frame, calls, compare
  • run(session, rules: Rules | None = None, events: bool = True, laps: tuple | None = None): Replay a whole race: tick at every leader line crossing (and every SC/VSC/red window change if events), decide, log.
  • ev_box_under_sc(p_red: float, owed: bool = True, green_s: float = 22.512, sc_s: float = 12.722) -> float: Expected time gained by boxing now under an SC instead of staying out, when the SC turns into a red flag (a free tyre change for everyone still out) with probability p_red.
  • regret_table(green_s: float = 22.512, sc_s: float = 12.722) -> pd.DataFrame: Time cost (s) of each action in each outcome, measured against the best action in that outcome, for a car that still owes a stop when an SC is deployed.
  • wait_for_sc_value(laps_waited: int, hazard_per_lap: float, saving_s: float, fresh_delta_s: float = 1.078) -> float: Expected net gain (s) of delaying a green-flag stop by laps_waited laps in the hope that a neutralisation arrives: P(at least one in the window) x saving - laps x fresh-tyre delta.
  • evaluate_neutralisations(sessions, rules: Rules | None = None, kinds=('SC', 'VSC'), window: int = 1) -> pd.DataFrame: Rule vs reality at the opening of every SC and VSC incident: the state 1 s after the deployment, the call for every running car, and whether that car pitted at its first or second opportunity (window = 1).

boxbox.laptime (Chapter 19)

Box Box - laptime: sectors, mini-sectors, the theoretical best lap and the delta trace (Chapter 19).

  • segment_colours(lap_row) -> list[str]: Colour names for every timing segment of one lap (sector 1, then 2, then 3).
  • segment_summary(laps: pd.DataFrame, lap: str = 'fastest', exclude=None) -> pd.DataFrame: Count segment colours per driver, on each driver's fastest lap (lap='fastest') or over every timed lap of the session (lap='all').
  • deleted_lap_keys(session) -> set: (driver_number, lap_number) pairs that race control deleted (track limits etc.).
  • sector_table(laps: pd.DataFrame, drivers=None, exclude=None) -> pd.DataFrame: Each driver's fastest lap split into the official sectors, with speed traps and the deficit of every sector to the best of the drivers shown.
  • theoretical_best(laps: pd.DataFrame, exclude=None, max_gap_s: float = 3.0) -> pd.DataFrame: Per driver: best S1 + best S2 + best S3 over all their timed sectors, against their actual best lap.
  • ultimate_lap(laps: pd.DataFrame, exclude=None) -> pd.DataFrame: The field's best time in each sector, who set it, and the sum (an 'ultimate lap' no single car drove).
  • quality_check(tel: pd.DataFrame, official_m: float | None = None) -> dict: Is this lap of car_data fit for a delta trace? frozen_s = longest stretch where speed AND rpm repeat while moving (> 50 km/h): a stalled feed.
  • sector_line_distances(tel: pd.DataFrame, s1: float, s2: float) -> tuple[float, float]: Where (in integrated metres) this lap crossed the two sector lines, from its official S1 and S2 times.
  • align_on_sectors(ref: pd.DataFrame, cmp: pd.DataFrame, ref_sectors, cmp_sectors) -> pd.DataFrame: Warp cmp's integrated distance piecewise-linearly so that its start line, two sector lines and finish line land on ref's.
  • delta_trace(ref: pd.DataFrame, cmp: pd.DataFrame, laps: pd.DataFrame | None = None, align: str = 'sectors', step_m: float = 5.0) -> pd.DataFrame: Time delta of lap cmp against lap ref along ref's distance: delta_s > 0 means cmp is BEHIND.
  • minisector_times(tel: pd.DataFrame, n: int = 25, length_m: float | None = None) -> pd.DataFrame: Split the lap into n equal-distance mini-sectors and return the time spent in each (s), plus the mean speed.
  • compare_minisectors(tels: dict, n: int = 25) -> pd.DataFrame: Mini-sector times for several laps on one grid (the first lap's length).
  • composite_best(tels: dict, n: int = 25) -> dict: The lap you would get by stitching together the fastest of these laps in every mini-sector.
  • corner_cuts(tel: pd.DataFrame, prominence_kmh: float = 10.0) -> tuple[pd.DataFrame, np.ndarray]: Corners as local speed minima (toolkit) and cut points midway between consecutive minima, so each segment = approach + corner + exit.
  • segment_deltas(delta: pd.DataFrame, cuts) -> pd.DataFrame: Change of a delta trace between consecutive cut points (s; > 0 = the compared lap lost time there).

boxbox.pace (Chapter 20)

Box Box - pace: the fuel- and traffic-corrected race-pace estimator (Chapter 20).

  • fuel_effect(session_or_laps, start_fuel_kg: float = 100.0) -> dict: Data-driven fuel + track-evolution slope for one race (or several pooled).
  • fuel_corrected_pace(laps: pd.DataFrame, method: str = 'data', s_per_lap: float | None = None, start_fuel_kg: float = 100.0, s_per_kg: float = 0.03, total_laps=None) -> pd.DataFrame: Add lap_time_fc, the lap time expressed at the END-of-race (empty-tank) state, and fuel_method.
  • add_interval_start(laps: pd.DataFrame) -> pd.DataFrame: Add the gap to the car ahead at the START of each lap.
  • traffic_flag(laps: pd.DataFrame, close_s: float = 1.0, clean_s: float = 3.0) -> pd.DataFrame: Label each lap by the gap to the car ahead when it began.
  • traffic_cost(laps: pd.DataFrame, edges=(0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0), ref_min_s: float = 3.0, y: str = 'lap_duration', cluster: str = 'session_key', conf: float = 0.95) -> pd.DataFrame: Extra lap time when following, by gap bin, against clean air (gap > ref_min_s or leading).
  • race_pace_table(session, fuel: str = 'data', traffic: str = 'exclude', close_s: float = 1.0, min_laps: int = 5, **fuel_kw) -> pd.DataFrame: Race pace per driver: the median fuel-corrected clean lap (the book's canonical definition), with options for the fuel correction and for traffic.
  • pace_model(session, close_s: float = 1.0, min_laps: int = 5) -> dict: One explicit model of a race's clean laps:
  • fp2_long_runs(session, min_laps: int = 5, max_pct_of_best: float = 112.0, band: float = 0.02, return_laps: bool = False): Long runs in a practice session (FP2 by default in the book; works for FP1/FP3).
  • long_run_pace(session, min_laps: int = 5, **kw) -> pd.DataFrame: Per driver: the median of all usable long-run laps (fp2_long_runs), whatever the compound.
  • simulator_inputs(session, close_s: float = 1.0) -> dict: What strategy.RaceModel needs from this chapter, measured on one race: base_lap_s (per driver, from pace_model: empty-tank, new reference compound, clean air), fuel_s_per_lap (the model's lap-number slope; fuel + evol...

boxbox.ratings (Chapter 21)

Box Box - ratings: teammate gaps and driver ratings (Chapter 21).

  • clean_qualifying(max_ratio: float = 1.25) -> pd.DataFrame: Jolpica qualifying (1994 onward) with corrupt times removed.
  • teammate_gaps(q: pd.DataFrame | None = None, years=None) -> pd.DataFrame: Canonical teammate qualifying gap for every team-round with exactly two qualifiers.
  • pair_seasons(gaps: pd.DataFrame, stat: str = 'median', min_n: int = 3, trim: float | None = None) -> pd.DataFrame: One row per teammate-season: y = stat of a's gap to b over the rounds (median by default), n = rounds, a_ahead = rounds in which a was faster.
  • head_to_head(gaps: pd.DataFrame, years=None, min_n: int = 1) -> pd.DataFrame: One row per driver-season-team: median gap %, rounds, rounds ahead, share ahead with a Wilson 95 % CI.
  • connected_component(ps: pd.DataFrame, start: str) -> tuple[set, dict]: Drivers reachable from start through teammate links in ps (breadth-first search), plus the adjacency dict {driver: set(teammates)}.
  • chain_fit(ps: pd.DataFrame, ref: str = 'hamilton', weighted: bool = True, drivers=None) -> pd.Series: Teammate-chain rating.
  • bootstrap_chain(gaps: pd.DataFrame, ref: str = 'hamilton', n_boot: int = 1000, seed: int = 42, stat: str = 'median', min_n: int = 3, weighted: bool = True, trim: float | None = None, min_pair_n: int | None = None, drivers=None) -> pd.DataFrame: Bootstrap the chain fit by resampling RACES (year-round pairs, with replacement): every teammate-season summary and the fit are recomputed in each replicate.
  • shortest_chains(ps: pd.DataFrame, a: str, b: str) -> list[list[str]]: Every shortest path of teammate links from driver a to driver b (breadth-first search).
  • elo_from_duels(gaps: pd.DataFrame, k: float = 16.0, init: float = 1500.0, scale: float = 400.0) -> tuple[pd.Series, pd.DataFrame]: Elo rating from teammate qualifying duels, processed in date order (year, round).
  • elo_log_loss(log: pd.DataFrame, from_year: int = 2006) -> float: Mean log loss of the pre-duel expected scores for duels from from_year on (ties dropped).
  • driver_car_regression(q: pd.DataFrame | None = None, years=(2014, 2026), session: str = 'q1_s', alpha: float = 1.0, max_pct: float = 5.0) -> dict: Qualifying pace = driver effect + car-season effect + noise, fitted by ridge regression.
  • variance_shares(reg: dict, min_rounds: int = 5) -> pd.DataFrame: Per season: how the spread of predicted pace (driver + car) splits between the cars, the drivers and their covariance (good drivers sitting in good cars).
  • teammate_race_pace(session, min_laps: int = 5) -> pd.DataFrame: Race pace vs the teammate on the SAME compound in the SAME part of the race.
  • lap_consistency(session, min_laps: int = 10) -> pd.DataFrame: Lap-time consistency per driver: the standard deviation of clean, fuel-corrected laps around a straight line fitted to each stint (so tyre wear and fuel burn are not counted as inconsistency).
  • pct_to_seconds(pct: float, lap_s: float = 90.0) -> float: Convert a gap in % of lap time to seconds on a lap of lap_s seconds.

boxbox.degradation (Chapter 22)

Box Box - degradation: measuring tyre degradation and predicting it for a race (Chapter 22).

  • correct_fuel(laps: pd.DataFrame, fuel: str = 'default', slopes: dict | None = None, col: str = 'lap_duration') -> pd.DataFrame: Add lap_time_deg, the lap time used to measure degradation, under the named fuel correction.
  • class StintFit(slope: float, ci_low: float, ci_high: float, n: int, intercept: float = nan, curvature: float = 0.0, cliff_age: float | None = None, cliff_rate: float = 0.0, model: str = 'linear', y: str = 'lap_time_deg', compound: str | None = None, extra: dict = field(default_factory=...)): Degradation of one stint.
  • methods and properties: predict
  • fit_stint(stint_laps: pd.DataFrame, model: str = 'linear', y: str = 'lap_time_deg', warmup_laps: int = 1) -> StintFit: Fit one stint (one driver, one set).
  • stint_table(laps: pd.DataFrame, fuel: str = 'default', min_laps: int = 8, slopes: dict | None = None, model: str = 'linear') -> pd.DataFrame: One row per usable stint: a single dry compound and >= min_laps clean laps after stint lap 1.
  • race_cells(stints: pd.DataFrame, min_stints: int = 3) -> pd.DataFrame: Aggregate a stint table to one row per race x compound: median deg, n stints, mean track temperature.
  • practice_long_runs(meeting_key: int, fuel_s_per_lap: float = -0.056, min_laps: int = 8, raw_window: tuple = (-0.3, 0.6), kinds=('FP2', 'FP3')) -> pd.DataFrame: Practice long runs of one weekend (Anchor B's rule): every FP2/FP3 stint on one dry compound with >= min_laps clean laps after the out-lap and a RAW slope inside raw_window (outside it the run had a mode change or...
  • race_early_deg(session, min_laps: int = 8, min_first: int = 3) -> dict: Degradation from a race's OPENING stints (what is knowable by the first stops): canonical deg (default fuel correction) of every driver's first stint with >= min_laps usable laps, median by compound.
  • mixed_deg(laps: pd.DataFrame, compound: str, y: str = 'lap_time_deg', warmup_laps: int = 1) -> dict: Mixed model for one compound in one session (or several): y ~ tyre_age with a random intercept AND a random tyre-age slope per driver-stint (statsmodels MixedLM, REML).
  • class DegModel(k_circuit: float = 4.0, k_cell: float = 4.0, use_temp: bool = True, use_season: bool = False, k_season: float = 8.0): Predict a race's typical degradation for a compound from its circuit and track temperature.
  • methods and properties: fit, predict, predict_frame, describe
  • stint_time(deg: float, n_laps: int, start_age: int = 0, offset: float = 0.0, curvature: float = 0.0) -> float: Tyre time of an n-lap stint relative to a new set's base lap: sum over its laps of offset + deg * age + curvature * age^2, with age = start_age, start_age + 1, ...
  • to_race_model(deg: dict, total_laps: int, pit_loss_s: float, first_stint_age: int = 0, offsets: dict | None = None, warmup: dict | None = None, label: str = ''): Build a boxbox.strategy.RaceModel from {compound: deg} (or {compound: (deg, n, source)}).
  • call_one_stop(model, c1: str, c2: str, flat: float = 0.01, min_stint: int = 5) -> dict: Ask the model for the single stop c1 -> c2: the optimal in-lap, the stop laps within 1 s of it, the full curve, and whether the call is DEGENERATE (a deg input below flat s/lap, or the optimum on the search boundary...
  • pooled_pit_loss(circuit_ref: str, exclude_session: int | None = None, min_stops: int = 5) -> tuple: Canonical green-flag pit loss for a circuit, pooled over its races in the data EXCEPT exclude_session (what a team could know before the race).

boxbox.telemetry_tools (Chapter 23)

Box Box - telemetry_tools: every channel we have, two laps on one distance axis, corner by corner (Chapter 23).

  • sampling_stats(tel: pd.DataFrame) -> dict: Sampling of one lap: number of samples, median / 95th-percentile / max interval (s), rate (Hz) and the median and 95th-percentile distance travelled between samples (m).
  • frozen_stretches(tel: pd.DataFrame, min_s: float = 0.5, moving_kmh: float = 50.0) -> pd.DataFrame: Runs of samples where speed AND rpm repeat exactly while the car is moving: the feed stalled and repeated its last value.
  • lap_check(tel: pd.DataFrame, official_m: float | None = None) -> dict: The book's lap quality check (Ch 19 / Ch 10): frozen <= 2 s, gaps <= 1.5 s, 97-102 % length.
  • align(tel_a: pd.DataFrame, tel_b: pd.DataFrame, laps: pd.DataFrame | None = None, step_m: float = 5.0) -> pd.DataFrame: Both laps on one regular grid of lap A's distance.
  • throttle_profile(tel: pd.DataFrame, full: float = 98.0, off: float = 10.0) -> dict: How the lap is spent on the pedals, as shares of lap DISTANCE (*_pct) and TIME (*_time_pct): full (throttle >= 98 %), partial (between), off (< 10 %), brake (brake on), coast (off throttle, brake off), overlap (br...
  • pedal_split(tel: pd.DataFrame, full: float = 98.0, off: float = 10.0) -> dict: Exclusive pedal states as % of lap TIME, summing to 100: brake (brake on, any throttle), full (>= 98 %, brake off), partial (10-98 %, brake off) and coast (< 10 %, brake off).
  • gear_usage(tel: pd.DataFrame) -> pd.DataFrame: Time and distance in each gear (interval-weighted), with shares (%).
  • drs_runs(tel: pd.DataFrame, min_len_m: float = 50.0) -> pd.DataFrame: Runs with the DRS flap open (drs codes 10/12/14): start/end distance, length, speed at opening, peak and closing speed.
  • corner_events(tel: pd.DataFrame, apexes_m=None, prominence_kmh: float = 20.0, search_m: float = 60.0) -> pd.DataFrame: Per corner of one lap: apex (raw-sample speed minimum), min speed, gear at the apex, brake point, entry speed and length of the braking run, lift point, pick-up (throttle > 20 %) and full-throttle point after the apex...
  • corner_table(tel_a: pd.DataFrame, tel_b: pd.DataFrame, laps: pd.DataFrame | None = None, labels=('A', 'B'), prominence_kmh: float = 20.0) -> pd.DataFrame: The corner-by-corner comparison of two laps, on lap A's distance axis (lap B sector-anchored when laps is given).
  • phase_split(grid: pd.DataFrame, who: str = 'b', full: float = 98.0) -> pd.DataFrame: Split an align() grid's delta into what lap who ('a' or 'b') is doing at each step: braking (brake on), full throttle (>= 98 %, brake off) or corner / part throttle.
  • compare_laps(tel_a: pd.DataFrame, tel_b: pd.DataFrame, laps: pd.DataFrame | None = None, labels=('A', 'B')) -> dict: Everything about two laps in one call: lap delta, the align() grid, the phase split, both throttle profiles and gear usages, top speeds, the corner table and a few plain-language summary lines.
  • style_metrics(tel: pd.DataFrame) -> dict: Lap-level style features: throttle shares (distance), coasting and brake/throttle overlap, number of full-throttle runs, gear shifts per km, lowest gear used, and median upshift rpm.
  • fingerprint(tel_a: pd.DataFrame, tel_b: pd.DataFrame, laps: pd.DataFrame | None = None) -> dict: B-minus-A style differences for one pair of laps: median per-corner brake_later_m, min_speed_diff and ft_earlier_m (over corners where both laps have the event), the within-pair 'V vs U' correlation (Spearman of brake...

boxbox.development (Chapter 24)

Box Box - development: which teams are getting faster, which are falling behind (Chapter 24).

  • circuit_type(circuit_ref: str) -> str: Chapter 10 speed type of a circuit, or 'unclassified' if it was never profiled.
  • lineage(team_ref: str) -> str: The entry lineage a team_ref belongs to (the team_ref itself if it was never renamed).
  • wet_rounds(years) -> set: (year, round) of wet qualifying sessions, 2023 onward (OpenF1 rule: > 20 % of laps on INTERMEDIATE/WET or with rainfall).
  • team_bests(years, method: str = 'best') -> pd.DataFrame: One row per (year, round, team): the team's best qualifying time under method.
  • gap_to_fastest(years=(2023, 2026), method: str = 'best', exclude_wet: bool = True, reference: str = 'fastest', min_teams: int = 8) -> pd.DataFrame: Per-race gap of every team to the fastest team, in % of the fastest time (0 = fastest team).
  • adjust_for_circuit(gaps: pd.DataFrame, value: str = 'gap_pct') -> pd.DataFrame: Remove each team-season's circuit-type effect from value.
  • smooth(gaps: pd.DataFrame, value: str = 'gap_adj', window: int = 5) -> pd.DataFrame: Centred rolling median of value within each team-season (min 3 races), as <value>_smooth.
  • trend(gaps: pd.DataFrame, value: str = 'gap_pct', control: bool = True, n_boot: int = 1000, seed: int = 42, by=('year', 'team_ref')) -> pd.DataFrame: Development rate of each team-season: the OLS slope of value on race_idx (percentage points per race; negative = closing on the reference), with circuit-type dummies when control=True.
  • split_profile(y, min_size: int = 4) -> pd.DataFrame: The split statistic at every candidate position: a flat profile means the location is uncertain.
  • change_points(y, min_size: int = 4, alpha: float = 0.05, n_perm: int = 999, max_cp: int = 3, seed: int = 42) -> pd.DataFrame: Binary segmentation for shifts in the mean of a series, with a permutation test at every split.
  • team_change_points(gaps: pd.DataFrame, value: str = 'gap_adj', **kw) -> pd.DataFrame: change_points() for every team-season; adds year, team, the round and circuit where the new level starts.
  • detection_power(n: int = 22, sd: float = 0.25, shifts=(0.0, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0), n_sim: int = 300, at: float = 0.5, seed: int = 42, **kw) -> pd.DataFrame: How often change_points() fires on simulated series of n Gaussian races (noise sd, in pp) with a single step of each size at fraction at of the season.
  • project_gap(gaps: pd.DataFrame, team_ref: str, year: int, races_ahead: int = 1, window: int = 5, circuit_type_next: str | None = None, n_boot: int = 1000, seed: int = 42) -> dict: A team's expected gap to the fastest team at a coming race, for the simulator's base pace.
  • team_spread(gaps: pd.DataFrame) -> pd.DataFrame: Per round: slowest team's gap (team spread), median team's gap and the number of teams.
  • season_order(gaps: pd.DataFrame, value: str = 'gap_pct') -> pd.DataFrame: Median gap per team-season and its rank (1 = fastest), with the lineage key for cross-season links.
  • order_persistence(order: pd.DataFrame) -> pd.DataFrame: Spearman correlation between consecutive seasons' team order (linked by lineage), plus the mean absolute rank change and whether the fastest team changed.
  • race_pace_gaps(years=(2023, 2026), exclude_wet: bool = True) -> pd.DataFrame: Canonical team race pace (metrics.race_pace(by='team'): median fuel-corrected clean lap, toolkit ASSUMPTION fuel defaults) per race, as % gap to the fastest team.

boxbox.viz (Chapter 25)

Box Box - viz: honest, legible, accessible charts for real races and for simulator output (Chapter 25).

  • hex_to_rgb(h: str) -> np.ndarray
  • contrast_ratio(c1: str, c2: str = '#ffffff') -> float: WCAG 2.x contrast ratio between two colours: (L_hi + 0.05) / (L_lo + 0.05), from 1 to 21.
  • simulate_cvd(h: str, kind: str = 'deutan') -> str: The colour as simulated for protanopia ('protan'), deuteranopia ('deutan') or tritanopia ('tritan').
  • oklab_lightness(h: str) -> float
  • delta_e(c1: str, c2: str, kind: str | None = None) -> float: Colour difference as Euclidean distance in OKLab x 100, optionally after a CVD simulation.
  • palette_report(colors: dict, surface: str = '#ffffff') -> tuple[pd.DataFrame, pd.DataFrame]: For {name: hex}: (1) per colour: contrast vs surface, OKLab L, pass/fail at 3:1; (2) every pair: Delta E under normal vision, deuteranopia and protanopia, the worst of the three and a verdict ('ok' >= 8, 'needs 2nd cu...
  • cmap_lightness(cmap, n: int = 256) -> np.ndarray: OKLab lightness along a colormap.
  • focus_lines(ax, data: pd.DataFrame, x: str, y: str, key: str, focus, styles: dict | None = None, context_color: str = '#c9c9c9', label_ends: bool = True, lw_focus: float = 2.0, markers: dict | None = None, min_label_gap=None): Draw every key group of data as a line: groups in focus in their style (team colour, line style), the rest thin and grey underneath.
  • clip_view(ax, x, y, lo: float, hi: float, label_fmt='{:.1f}', color='#555555', max_labels: int = 6, inverted: bool = False): Set the y window to [lo, hi] WITHOUT dropping data: points above hi are drawn as up-arrows on the top edge (labelled with their true value), points below lo as down-arrows on the bottom edge.
  • pair_gaps(session, ref: str, others) -> pd.DataFrame: Gap (s) of each car in others to car ref at the end of every lap, from line crossings (metrics.gap_to_leader_by_lap differences, so a change of leader cancels out).
  • race_trace(session, focus=None, reference: str = 'winner_mean', ax=None, title=None, source: str | None = 'auto', figsize=(10, 5.8), max_gap_s=None, mark_stops: bool = True): Race trace with focus and context.
  • stints_from_strategies(strategies: dict, total_laps: int) -> pd.DataFrame: {label: boxbox.strategy.Strategy} -> rows (acronym=label, stint_number, compound, lap_start, lap_end, tyre_age_at_start=0) that strategy_chart can draw.
  • strategy_chart(stints, order=None, total_laps=None, ax=None, title=None, source=None, label_laps: bool = True, figsize=(10, 6), used_hatch: bool = True, annotate: dict | None = None): Stint bars, one row per car (or simulated strategy), coloured by compound with a letter on every bar long enough to hold it (so the chart still reads in greyscale or with CVD), the in-lap number at each boundary, and...
  • source_below(fig, text: str, artist=None): Source footnote placed under artist (e.g. a legend hung below the axes) so the two never overlap; without an artist it behaves like toolkit.plots.add_source.
  • outcome_hist(samples, unit: str = 's', discrete: bool = False, bins=40, ax=None, title=None, source=None, colors=None, xlabel=None, figsize=(9, 5), quantiles=(0.1, 0.5, 0.9), labels=None): Distribution of outcomes: one step histogram per series (simulated race times, finishing positions, pit losses...), drawn as density (or share of runs for discrete outcomes) on ONE common x scale.
  • simulate_figure(fig, kind: str = 'deutan', dpi: int = 110) -> np.ndarray: Render a matplotlib figure and return its pixels (H x W x 3, 0-1) as seen with the given colour-vision deficiency, so a chart can be checked by eye the way a colour-blind reader will see it.
  • darken_to_contrast(h: str, surface: str = '#ffffff', target: float = 3.0, step: float = 0.005) -> str: The same hue, made darker in OKLab lightness (hue angle kept, chroma kept where the sRGB gamut allows) until it reaches target contrast against surface.

boxbox.predict (Chapter 26)

Box Box - predict: qualifying and race outcome prediction, and the championship simulation (Chapter 26).

  • qualifying_table(years=(2006, 2026)) -> pd.DataFrame: One row per driver per round: best qualifying time, gap to the fastest driver (%), qualifying rank.
  • is_dnf(results: pd.DataFrame) -> pd.Series: True for a starter who did not take the chequered flag (Jolpica finished is False), excluding disqualifications and non-starters.
  • is_starter(results: pd.DataFrame) -> pd.Series: True for every entry that started the race (not 'Did not start' / 'Withdrew').
  • standings_after(year: int, rnd: int) -> tuple[pd.DataFrame, pd.DataFrame]: Drivers' and constructors' standings after round rnd of year, from GP + sprint results.
  • build_features(years=(2006, 2026), elo_k: float = 32.0) -> pd.DataFrame: One row per driver per Grand Prix with pre-race features and outcome targets.
  • train(df: pd.DataFrame, model: str = 'gbm', features=['grid', 'quali_gap_pct', 'quali_pos'...) -> dict: Fit a win model and a podium model (or one ordinal model) on the rows of df.
  • predict_race(fitted: dict, df_race: pd.DataFrame) -> pd.DataFrame: Add p_win (sums to 1 per race), p_podium (sums to 3, capped at 1) and pred_rank (1 = favourite).
  • walk_forward(df: pd.DataFrame, model: str = 'gbm', features=['grid', 'quali_gap_pct', 'quali_pos'..., test_years=range(2014, 2027), min_train_year: int = 2006) -> pd.DataFrame: Time-respecting validation: for each test season Y, train on seasons min_train_year..Y-1 and predict Y.
  • baselines(df: pd.DataFrame, test_years=range(2014, 2027), min_train_year: int = 2006) -> pd.DataFrame: No-model forecasts.
  • score(pred: pd.DataFrame, p_col: str = 'p_win', by: str | None = 'year') -> pd.DataFrame: Per-race scores aggregated by by: top1 (favourite won), podium_hit (share of the 3 podium picks that finished on the podium), brier (sum over drivers of (p - won)^2, per race), logloss (-ln p of the actual winner),...
  • reliability(pred: pd.DataFrame, p_col: str = 'p_win', bins=(0, 0.02, 0.05, 0.1, 0.2, 0.3, 0.45, ...) -> pd.DataFrame: Calibration table: in each probability bin, mean predicted probability vs observed win share.
  • pl_order_logprob(order_scores: np.ndarray) -> float: Log-probability of an observed finishing order under Plackett-Luce, given the log-strengths of the finishers in finishing order: sum_k [ s_k - log sum_{j>=k} exp(s_j) ].
  • fit_strengths(results: pd.DataFrame, half_life: float | None = 6.0, ridge: float = 0.05) -> pd.Series: Recency-weighted Plackett-Luce log-strengths from finishing orders.
  • simulate_championship(drivers: pd.DataFrame, strengths: pd.Series, p_dnf: pd.Series | float, n_races: int, n_sims: int = 10000, seed: int = 42, points=array([25., 18., 15., 12., 10., 8., ..., constructors: pd.DataFrame | None = None, strength_draws: np.ndarray | None = None) -> dict: Play the remaining n_races Grands Prix n_sims times.

boxbox.montecarlo (Chapter 27)

Box Box - montecarlo: the Monte Carlo race engine (Chapter 27).

  • class TyreModel(deg: dict, offset: dict, cap: dict, warmup: dict = field(default_factory=...), deg_se: dict = field(default_factory=...), offset_se: dict = field(default_factory=...), fuel: str = 'unstated'): Linear tyre model of one race.
  • methods and properties: arr
  • class Policy(min_stops: int = 1, max_stops: int = 2, name: str = 'flex'): How many stops a car may make.
  • class Car(code: str, grid: int, team: str = '', pace_s: float = 0.0, pace_sd_s: float = 0.0, p_dnf: float = 0.0, policy: Policy = Policy(min_stops=1, max_stops=2, name..., start_compound: str | None = None, start_age: int = 0, plan: tuple | None = None): One entry.
  • class RaceSetup(n_laps: int, cars: list, tyres: TyreModel, green_pool: np.ndarray, sc_ratio: dict, hazard: dict, library: pd.DataFrame, base_lap_s: float = 90.0, fuel_s_per_lap: float = 0.0, name: str = '', traffic: bool = True, dirty_air_s: float = 0.44, min_gap_s: float = 0.3, pass_threshold_s: float = 0.6, pass_width_s: float = 0.25, lap1: str = 'sampler', lap1_era: str = 'Ground-effect hybrid era', lap1_gap_s: float = 0.65, lap1_link: bool = True, noise: DriverNoise | None = field(default_factory=...), sc_gap_floor_s: float = 0.44, sc_gap_keep: float = 0.61, compress: bool = True, sc_lap_factor: float = 1.43, vsc_lap_factor: float = 1.16, red_counts_as_stop: bool = True, truth_draws: bool = True, common_draws: bool = False, decide_ratio: dict | None = None): Everything one race needs.
  • class SimResult(codes: list, position: np.ndarray, finished: np.ndarray, time_s: np.ndarray, stops: np.ndarray, neutral_stops: np.ndarray, first_stop: np.ndarray, passes: np.ndarray, n_incidents: np.ndarray, status: np.ndarray, lap_times: np.ndarray | None = None, meta: dict = field(default_factory=...)): Output of a batch of simulated races.
  • methods and properties: n_sims
  • points_for(position) -> np.ndarray: 2010+ points (25-18-15-12-10-8-6-4-2-1) for positions; 0 outside the top 10 and for NaN.
  • decision_table(tyres: TyreModel, n_laps: int, loss_g: float, max_stops: int = 3) -> dict: Bellman tables for the green-race continuation cost, computed backwards from the flag.
  • best_start(table: dict, policy: Policy, start_age: int = 0, start_compound: str | None = None) -> tuple: Best starting compound for a policy and the clean-race tyre + pit cost of following it (s).
  • clean_plan(table: dict, policy: Policy, start_age: int = 0, start_compound: str | None = None) -> tuple: Follow the Bellman policy through a race with no neutralisation: (start, [(in_lap, new_compound)], cost).
  • sample_timelines(n: int, n_laps: int, hazard: dict, library: pd.DataFrame, rng: np.random.Generator, p_lap1: np.ndarray | None = None) -> np.ndarray: (n, n_laps) lap statuses.
  • lap1_matrix(era: str = 'Ground-effect hybrid era', max_slot: int = 20) -> np.ndarray: Real lap-1 fates from Chapter 17's data: one row per historical race of the era with slots 1..max_slot all accounted for, one column per grid slot, value = position after lap 1 (NaN = retired on lap 1).
  • simulate_race(setup: RaceSetup, n_sims: int = 1, seed: int = 42, timeline: np.ndarray | None = None, keep_laps: bool = False, table: dict | None = None, lap1_F: np.ndarray | None = None) -> SimResult: Simulate n_sims races of setup, vectorised over races.
  • run_many(setup: RaceSetup, n_sims: int = 10000, seed: int = 42, batch: int = 2000, keep_laps: bool = False, timeline: np.ndarray | None = None) -> SimResult: Run n_sims races in batches of batch (batch b uses seed + b, so results are reproducible and identical for any setup with the same number of cars and laps: common random numbers across strategies).
  • summarise(res: SimResult) -> pd.DataFrame: Per car: P(win), P(podium), P(points), P(DNF), mean / median / 10th-90th percentile finishing position, expected points, mean stops.
  • compare_strategies(setup: RaceSetup, focal: str, policies: dict, n_sims: int = 10000, seed: int = 42, batch: int = 2000, starts: dict | None = None, timeline: np.ndarray | None = None) -> tuple: Run the same simulated races (common random numbers) once per policy for the car focal; every other car keeps its own policy.
  • ghost_setup(n_laps: int, tyres: TyreModel, green_pool, sc_ratio: dict, hazard: dict, library: pd.DataFrame, policies: dict, decide_ratio: dict | None = None, truth_draws: bool = True, **kw) -> RaceSetup: Single-car-vs-clock mode (the book's Anchor C model): one identical 'ghost' car per policy, no traffic, no noise, no lap-1 shuffle, no DNF, and shared stop-loss draws (common random numbers), so the time difference be...
  • calibrate_passing(setup: RaceSetup, target_passes: float, n_sims: int = 400, seed: int = 7, lo: float = -1.0, hi: float = 4.0, iters: int = 12) -> tuple: Bisection on pass_threshold_s so that the mean simulated green on-track passes per race equal target_passes (a circuit's measured value).
  • convergence(x, kind: str = 'mean', checkpoints=None) -> pd.DataFrame: Running estimate of a mean (kind="mean") or a share (kind="share", x boolean) with its Monte Carlo standard error SD/sqrt(n) (or sqrt(p(1-p)/n)) and a normal 95 % band, at the given run counts.
  • field_relative_stop_losses(session, min_others: int = 3) -> pd.DataFrame: Per dry tyre-change stop (lap > 1, pit lane <= 60 s, no red flag on the two laps): the 'field-relative' loss = (in-lap + out-lap of the pitting car) - median(same two laps) of the cars that did not pit within a lap an...

boxbox.regs (Chapter 28)

Box Box - regs: the rulebook as data, season by season (Chapter 28).

  • class RuleSet(year: int): The technical and sporting rules of one season, from the sourced reference tables.
  • methods and properties: as_dict, describe
  • season_table(years=None) -> pd.DataFrame: One row per season with the headline parameters (default 2014-2026).
  • compare(y0: int, y1: int) -> pd.DataFrame: The parameters whose values differ between two seasons.
  • rules_era(year: int) -> str: Technical era label used in this book's tables.
  • pu_allocation(year: int) -> dict: Power-unit elements each driver may use in the season without a grid penalty (reference table; most seasons also allow +1 for a new manufacturer's first season, not encoded here).
  • pu_penalty_elements(year: int, used: dict) -> dict: Elements whose count exceeds the season allocation: {element: units over}.
  • points(position, year: int, sprint: bool = False, fastest_lap: bool = False, final_round: bool = False) -> float: Championship points for a classified finishing position (full-distance race scale).
  • class Validation(ok: bool, reasons: list = field(default_factory=...), rules: list = field(default_factory=...)): Validation(ok: 'bool', reasons: 'list' = field(default_factory=...), rules: 'list' = field(default_factory=...))
  • min_stops(year: int, dry: bool = True, circuit: str | None = None) -> int: Stops the sporting rules force on a dry race: 1 (two-compound rule), 2 at Monaco in 2025 (three sets); 0 if the race is wet (intermediates or wets used).
  • validate_strategy(strategy, year: int, circuit: str | None = None, total_laps: int | None = None, stop_laps=None, sprint_weekend: bool = False, sets_used_weekend: int | None = None, race_kind: str = 'R', sets_by_compound: dict | None = None) -> Validation: Check a race plan against the season's sporting rules.
  • race_sets(stints: pd.DataFrame, tol_laps: int = 1) -> list: Distinct physical tyre sets one driver used, from his OpenF1 stints in one session.
  • validate_race(session) -> pd.DataFrame: Validate every driver's actual race strategy in an OpenF1 race session (2023 onward).

boxbox.regs2026 (Chapter 29)

Box Box - regs2026: the 2026 rulebook, measured and turned into simulator adjustments (Chapter 29).

  • pu_supplier(team_ref: str, year: int = 2026) -> str | None: Power-unit manufacturer of a 2026 team (None for other years: not encoded here).
  • energy_clip_detector(tel: pd.DataFrame, min_len_m: float = 300.0, thr: float = 98.0, min_fade_kmh: float = 5.0, smooth: int = 3) -> pd.DataFrame: Find the energy-limited ('clipping') signature on one lap of car_data, event by event.
  • lap_clip_summary(tel: pd.DataFrame, **kw) -> dict: One lap's clip events rolled up: n_events, max and total fade (km/h), metres and seconds spent fading, time lost vs holding peak speed (s), and the median peak speed at which the fades began (km/h).
  • green_passes(session, flicker_s: float = 10.0, mass: int = 4) -> pd.DataFrame: Classify every OpenF1 overtakes record of a race; only cls == 'green on-track' is an on-track pass.
  • overtake_power_gain_kw(v_kmh): Extra MGU-K power (kW) that Overtake allows over the normal curve at speed v (C26 C5.2.8).
  • overtake_straight_gain(v0_kmh: float, length_m: float, CdA: float = 1.27, mass_kg: float = 780.0, energy_mj: float = 2.0, extra_mj: float = 0.5, cda_tow_factor: float = 1.0) -> dict: 🧪 Exit-speed and time gain of Overtake on one straight, from boxbox.power.simulate_straight.
  • overtake_eligible(intervals, laps, restart_laps=(), gap_s: float = 1.0) -> np.ndarray: Is Overtake armed on the NEXT lap? (B26 B7.2.3-B7.2.4, simplified for a lap-level simulator.)
  • is_dnf(results: pd.DataFrame) -> pd.Series: DNF flag for Jolpica result rows (starters): status is a retirement, i.e. not Finished, not '+N Lap(s)' or 'Lapped', not disqualified.
  • season_compare(y0: int, y1: int, metric: str, same_circuits: bool = True, dry_only: bool = True, pct: bool = False) -> tuple[pd.DataFrame, dict]: Compare a metric between two seasons, circuit by circuit.
  • class Regime(year: int, drs: bool, overtake_mode: bool, detection_gap_s: float, overtake_extra_mj: float, follow_speed_gain_kmh: float, green_passes_per_race: float, pit_loss_delta_s: float, dnf_rate: float, source: str): Era-level adjustments a race simulator needs.
  • methods and properties: as_dict
  • regime(year: int) -> Regime: The simulator adjustments for a season, from the book's data snapshot (2023-2026 R21).
  • dnf_hazard_per_lap(p_dnf: float, race_laps: int) -> float: Constant per-lap retirement hazard h with 1 - (1 - h)^N = p_dnf (a simplification: real hazard is front-loaded on lap 1 and differs by team).

boxbox.upgrades (Chapter 30)

Box Box - upgrades: tunnel-time allocations and honest before/after upgrade estimates (Chapter 30).

  • atr_scale(year: int) -> dict: Coefficient C (% of baseline) by constructors' position for year, read from cost_cap.csv.
  • atr_allocation(position: int, period, penalty_pct: float = 0.0) -> dict: One team's allowance PER ATP for a constructors' position (1-10; >= 10 and new teams get the P10 value) in period (a year, e.g. 2025).
  • atp_calendar(year: int) -> pd.DataFrame: ATP 1: 1 Jan to the end of week 9; ATPs 2, 3, 5: 8 weeks; ATP 4: 10 weeks; ATP 6: to 31 Dec (cost_cap.csv).
  • team_atr(year: int, penalties=None) -> pd.DataFrame: One row per team and ATP of year: the constructors' position the allowance is based on, C and the allowance per ATP.
  • season_allocation(years) -> pd.DataFrame: Team-season summary: total runs, wind-on hours and CFD geometries over the six ATPs, and the mean C in each half (h1_c: ATPs 1-3, h2_c: ATPs 4-6).
  • summer_split(year: int) -> int: Round number of the first race after the longest gap between consecutive races that starts in July or August (the summer shutdown).
  • min_detectable_shift(n_before: int, n_after: int, sd: float, alpha: float = 0.05, power: float = 0.8) -> float: Smallest true shift in the mean (same units as sd) that a two-sample comparison of n_before and n_after independent races would detect with the given power: (z_(1-alpha/2) + z_power) x sd x sqrt(1/n1 + 1/n2).
  • before_after(gaps: pd.DataFrame, team_ref: str, year: int, split_round: int, value: str = 'gap_adj', window: int | None = None, n_boot: int = 2000, min_side: int = 3, seed: int = 42) -> dict: Did team_ref's gap move across split_round in year? The upgrade-effect estimator.

boxbox.budget (Chapter 31)

Box Box - budget: the cost cap as an operations-research problem (Chapter 31).

  • cap_table(path: str | Path | None = None) -> pd.DataFrame: Base cost cap per season (USD m) from cost_cap.csv: 145 (2021), 140 (2022), 135 (2023-25), 215 (2026).
  • race_adjusted_cap(year: int, races: int, cap: float | None = None) -> float: Base cap adjusted for the number of races, USD m, BEFORE Indexation (illustrative arithmetic).
  • atr_coefficient(position: int, year: int = 2025, penalty: float = 0.0) -> float: ATR Coefficient C (fraction of the baseline) for a constructors' position.
  • atr_allocation(position: int, year: int = 2025, penalty: float = 0.0) -> dict: Per Aerodynamic Testing Period allowance (six periods a year).
  • class Area(name: str, max_gain: float, scale: float, minimum: float, aero: bool = False): One development/operations area.
  • exp_returns(area: Area, x: float, atr_c: float = 1.0) -> float: Diminishing-returns gain (% of lap time) of spending x USD m on area.
  • allocate(budget: float, areas: Sequence[Area] | None = None, returns: Callable[[Area, float, float], float] | None = None, step: float = 0.05, atr_c: float = 1.0) -> pd.DataFrame: Greedy marginal allocation of budget (USD m) across areas.
  • water_fill(budget: float, areas: Sequence[Area] | None = None, atr_c: float = 1.0) -> pd.DataFrame: Exact optimum for the exponential family (KKT): x_i = m_i + s_i ln(a_i / (s_i lambda)) where positive.
  • marginal_gain(budget: float, areas: Sequence[Area] | None = None, returns: Callable[[Area, float, float], float] | None = None, delta: float = 1.0, atr_c: float = 1.0, step: float = 0.05) -> dict: What delta more USD m is worth, re-optimised: total gain at budget + delta minus at budget, and the area that receives most of the extra money.
  • allocation_uncertainty(budget: float, areas: Sequence[Area] | None = None, n: int = 500, cv: float = 0.3, seed: int = 31, atr_c: float = 1.0) -> pd.DataFrame: Re-solve the allocation with every area's max_gain and scale drawn lognormally around the assumed value (coefficient of variation cv).

boxbox.eras (Chapter 32)

Box Box - eras: cross-era normalisation, dominance indices and relative performance (Chapter 32).

  • eras_table() -> pd.DataFrame: The book's era table (toolkit.history.eras()); 2026's open end is capped at 2026.
  • race_results(years=None, include_indy: bool = True) -> pd.DataFrame: Jolpica race results with era, is_indy, category, started and dnf columns.
  • champions(years=None) -> pd.DataFrame: Drivers' and constructors' champions per season from the FINAL standings (never from memory).
  • hhi(counts) -> float: Herfindahl-Hirschman index of a set of counts: sum of squared shares (1 = one entity won everything; 1/k = k entities won equally).
  • dominance_index(by: str = 'team', years=None, include_indy: bool = True) -> pd.DataFrame: Season-level dominance of the most successful team (by="team") or driver (by="driver").
  • team_round_gaps(years=range(1994, 2027), min_cars: int = 12, basis: str = 'like_for_like') -> pd.DataFrame: Per round and team: the team's best qualifying time vs the fastest team's, in %.
  • relative_performance(entity: str = 'team', years=None) -> pd.DataFrame: Era-proof performance per team-season (entity="team") or driver-season (entity="driver").
  • pace_margin(years=range(1994, 2027), min_rounds: int = 5, basis: str = 'best') -> pd.DataFrame: Per season: fastest team by median qualifying gap (default basis "best", i.e. each team's fastest lap of the day), the second-fastest, and the margin between them (percentage points of lap time).
  • points_scale(year: int) -> dict: Points actually awarded per finishing position in year (the modal value among classified cars).
  • rescore(years=None, scale=(25, 18, 15, 12, 10, 8, 6, 4, 2, 1), include_indy: bool = False) -> pd.DataFrame: Every driver-season re-scored with ONE scale: position p (classified) earns scale[p-1].
  • rescored_champions(years=None, scale=(25, 18, 15, 12, 10, 8, 6, 4, 2, 1)) -> pd.DataFrame: Actual champion (final standings) vs the leader under one common points scale, per season.
  • teammate_grid_h2h(driver: str | None = None, years=None) -> pd.DataFrame: Grid head-to-head against teammates, per driver-season-teammate.
  • dnf_table(years=None) -> pd.DataFrame: DNF rate per starter by season (Wilson 95 %), with mechanical / accident shares of starters.
  • race_format(years=None) -> pd.DataFrame: Per season: races, mean starters per race, the winner's median laps and race duration (hours), points-paying places and points for a win (modal awarded values; see points_scale).
  • shade_eras(ax, years=None, alpha: float = 0.08, labels: bool = True, fontsize: int = 7) -> None: Alternate light bands for the book's eras on an axis whose x is the season, with short era names staggered on two rows just above the plot area.

boxbox.economics (Chapter 33)

Box Box - economics: what is a constructors' championship position worth? (Chapter 33)

  • load_business(path: str | Path | None = None) -> pd.DataFrame: The business reference table (one row per sourced figure; see its source_* columns).
  • f1_financials(biz: pd.DataFrame | None = None) -> pd.DataFrame: Formula 1 company accounts by year, USD m (2017 is pro forma).
  • success_bonus_points(first: int = 2015, last: int = 2024) -> pd.Series: Previous-success bonus points by team_ref: 3/2/1 for constructors' P1/P2/P3 in each season of the window (the structure The Race described for the 2021-25 agreement), from Jolpica final standings.
  • prize_curve(biz: pd.DataFrame | None = None) -> pd.DataFrame: Per-position decomposition of the 2025 payments (on 2024 results).
  • constructor_table(year: int, after_round: int | None = None) -> pd.DataFrame: Constructors' table (team_ref, team_name, points, position).
  • points_gap_table(years=range(2014, 2026), partial: dict[int, int] | None = None, max_position: int = 10) -> pd.DataFrame: Adjacent-position gaps: one row per (year, k) with gap = points(P_k) - points(P_k+1).
  • class ValueAssumptions(curve_slope: float | None = None, curve_intercept: float | None = None, bonus_per_point: float = 4.22, bonus_years: int = 10, discount_rate: float = 0.08, n_teams: int = 10): Illustrative assumptions for position_value().
  • position_value(position: int, assumptions: ValueAssumptions | None = None, include_bonus: bool = True) -> dict: Illustrative value (USD m) of one season's constructors' finish in position.
  • position_step_values(assumptions: ValueAssumptions | None = None, include_bonus: bool = True) -> pd.Series: Value (USD m) of finishing one place higher, indexed by the lower position k+1 (k = 1..n-1).
  • marginal_point_value(extra_points: float, gaps: pd.DataFrame, steps: pd.Series | None = None, pairs: range = range(4, 10)) -> float: Expected USD m from scoring extra_points more, for a team in the midfield.
  • simulate_positions(table: pd.DataFrame, per_round: dict[str, np.ndarray], rounds_left: int, n_sims: int = 10000, seed: int = 33) -> pd.DataFrame: Monte Carlo of the final constructors' positions.
  • sponsorship_value(on_screen_s_per_race: float, avg_viewers_m: float, races: int, cpm_usd: float, quality: float = 1.0) -> float: Media-equivalent value (USD m) of a logo: exposure x audience x price of attention (illustrative).

boxbox.pitstops (Chapter 34)

Box Box - pitstops: pit-lane time distributions by team, slow-stop risk and stop-time sampling (Chapter 34).

  • jolpica_stops(years=None, max_lane_s: float = 60.0) -> pd.DataFrame: Jolpica race pit stops 2011-2026 (sprint stops live in sprint_pitstops and are not used), pit-lane time <= max_lane_s, with the event median, the event-relative time rel_s and the slow flag.
  • penalties(kinds=('R',)) -> pd.DataFrame: Penalties issued in race-control messages: one row per penalty with its type and seconds.
  • openf1_stops(years=None) -> pd.DataFrame: OpenF1 race pit stops 2023-2026, pit-lane time <= 60 s, one row per stop, with: circuit_ref, gp_name; pit_lane_s, stop_s (partial), event_median_s, rel_s, slow; flag (GREEN / SC / VSC / RED on the in- or out-lap; yell...
  • crew_sample(stops: pd.DataFrame) -> pd.DataFrame: Stops that measure the pit crew: tyre change, dry, green on both laps, in-lap > 1, no pending time penalty.
  • pitlane_distribution(team=None, year=None, source: str = 'openf1', relative: bool = True, stops: pd.DataFrame | None = None) -> dict: Summary of a team's (or the field's) pit-lane times: n, median with bootstrap 95% CI, IQR, P90, P95, share of slow stops with a Wilson CI, and the values themselves (values).
  • slow_stop_risk(team=None, year=None, threshold_s: float = 2.0, source: str = 'openf1', stops: pd.DataFrame | None = None, prior_n: float = 40.0) -> dict: P(slow stop) for a team-season: the raw share with a Wilson CI, and a shrunk estimate that pulls small samples toward the field rate for the same season(s) (beta-binomial with a prior worth prior_n stops).
  • fit_stop_mixture(rel_s, threshold_s: float = 2.0) -> dict: Two-part model of event-relative pit-lane time: a normal CORE (median and MAD-based sigma of the stops at or below the threshold) and an exponential SLOW TAIL above it (probability p_slow, mean excess tail_mean_s).
  • sample_stop_time(team=None, year=None, n: int = 1, rng: np.random.Generator | None = None, base_s: float = 0.0, method: str = 'empirical', stops: pd.DataFrame | None = None, source: str = 'openf1', mixture: dict | None = None) -> np.ndarray: Draw n pit-stop times for the simulator: base_s + an event-relative pit-lane draw.
  • team_consistency(stops: pd.DataFrame, min_stops: int = 20) -> pd.DataFrame: Per season and team: n, median rel_s, IQR width (q75 - q25, the spread of an ordinary stop), P90, slow share with Wilson CI, and ranks (1 = best) on median, IQR and slow share; consistency_rank is the mean of the IQ...
  • persistence(stops: pd.DataFrame, metric: str = 'median_rel_s', min_stops: int = 10) -> pd.DataFrame: Team metric in season t and t+1, with teams followed across rebrands (boxbox.data.team_lineage).
  • double_stacks(stops: pd.DataFrame) -> pd.DataFrame: One row per same-lap team-mate pair (from openf1_stops): flag, both drivers, the pit-timestamp gap, each car's rel_s and stop_s, and second_extra_s = second car's rel_s - first car's rel_s (the queueing cost).
  • pit_lane_incidents(kinds=('R', 'S')) -> pd.DataFrame: Pit-lane offences recorded by race control, one row per incident: category, cars, first and final message, and the final outcome IN THE FEED ("WILL BE INVESTIGATED AFTER THE RACE" means the decision is not in our data).
  • dhl_reference() -> pd.DataFrame: The DHL fastest-stop table: one row per race and team holding that race's fastest stationary time (a tie gives two rows for one race; tie marks them, so de-duplicate on season/round before per-race statistics), with...
  • dhl_vs_openf1(stops: pd.DataFrame | None = None) -> pd.DataFrame: For each 2024-2026 race: DHL's fastest stationary time and team vs the fastest OpenF1 stop_s in that race (any stop, tyre change), the OpenF1 team of that stop, and the OpenF1 coverage (share of stops with stop_s).
  • places_lost_to_delay(stops: pd.DataFrame) -> pd.DataFrame: For each stop with rel_s > 0: how many cars on the same lap crossed the line at the end of the pitter's out-lap (lap L+1) within rel_s seconds BEFORE the pitter did.
  • position_cost(stops: pd.DataFrame, horizon: str = 'pos_after') -> dict: Places lost per extra second of pit-lane time.

boxbox.overtaking (Chapter 35)

Box Box - overtaking: where passes happen, how likely a pass is, and how to count them honestly (Chapter 35).

  • classify_passes(session) -> pd.DataFrame: Every OpenF1 overtakes record of a race with its class (cls) and is_pass (cls == 'green on-track').
  • pass_counts(session) -> dict: Counts of overtakes records by class for one race, plus raw and green.
  • reference_line(year: int, circuit_ref: str, fallback_years=(2026, 2025, 2024, 2023), n_try: int = 6): The fastest quality-checked qualifying lap with location at a circuit: the reference line.
  • drs_zones(ref: pd.DataFrame, min_len_m: float = 200.0) -> pd.DataFrame: DRS-open runs on the reference lap (qualifying 2023-25: the flap may be opened in every zone).
  • time_fraction_to_distance(frac_t, ref: pd.DataFrame): Turn a fraction of a race lap's TIME into a fraction of the lap's DISTANCE using the reference lap's time-distance curve.
  • ref_xy(frac_d, ref: pd.DataFrame): x, y (OpenF1 units, ~decimetres) on the reference line at a distance fraction.
  • on_road_gap(session, attacker, defender, lap: int, n: int = 2001, _cache=None) -> pd.DataFrame: The on-road time gap between two cars along one lap, from race car_data.
  • locate_passes(session, ref: pd.DataFrame | None = None, telemetry_: bool = True, max_lag_frac: float = 0.35, tol_m: float = 150.0) -> pd.DataFrame: Every green on-track pass of a race, located on the lap two ways.
  • overtake_map(located: pd.DataFrame, ref: pd.DataFrame, ax=None, which: str = 'rec', color_by=None, title=None, s=40, palette=None, zones: pd.DataFrame | None = None): Draw passes on the circuit outline from the reference line.
  • following_situations(session, gap_s: float = 1.0) -> pd.DataFrame: One row per lap a car BEGAN within gap_s of the car directly ahead in the race order.
  • fit_pass_model(sit: pd.DataFrame, gap_centre: float = 0.6, clip_pace: float = 2.0, dry_only: bool = True, shrink: bool = True) -> dict: Fit the pass model with standard errors clustered by race:
  • sample_race_offset(rng=None, sd: float = 0.743) -> float: One race's 'passing weather': a logit offset ~ N(0, sd).
  • pass_probability(delta_pace, tyre_delta=0.0, circuit=None, gap_s: float = 0.6, compound_step: float = 0.0, year: int = 2026, model: dict | None = None, race_offset: float = 0.0): Probability that a car which begins a lap gap_s behind the car ahead passes it (green flag) on that lap.
  • flip_proxy(year: int, rnd: int, pit_gap_s: float = 10.0) -> dict | None: Jolpica order-flip proxy for one race (the book's 1996-2026 overtaking proxy).
  • race_action(session) -> dict: Per-race action metrics used to separate processional races from thrillers: green passes (total, per racing lap), lead changes on track (green passes for P1), the share of the field that finished within 2 places of it...

boxbox.conditions (Chapter 36)

Box Box - conditions: weather as a simulator input (Chapter 36).

  • clean_weather(session=None) -> pd.DataFrame: OpenF1 weather (one session, or the whole table) with track-temperature dropouts set to NaN, a track_dropout flag, track_excess = track - air (C) and local_hour (circuit clock time).
  • session_conditions(session) -> dict: Median air / track temperature, humidity, pressure and wind of a session, the rain share of records and the dropout count.
  • track_temp_effect(delta_c: float, stint_laps: int | None = None, deg_per_c: float = 0.00159) -> dict: Effect of a track-temperature change of delta_c (C) on wear: the change in degradation rate (s/lap per lap of tyre age) and, for a stint of stint_laps laps on a new set, the extra stint time (s) = d_deg * sum of a...
  • temp_adjusted_deg(base_deg: dict, base_track_c: float, forecast_track_c: float, deg_per_c: float = 0.00159) -> dict: Shift every compound's deg rate {compound: s/lap} from the temperature it was measured at to a forecast.
  • wind_component(wind_speed, wind_from_deg, heading_deg) -> tuple: Split a wind (speed, direction it blows FROM, compass degrees) into components relative to a car heading (compass degrees): (headwind, crosswind).
  • heading_from_xy(x0, y0, x1, y1, north_up: bool = True, rotation_deg: float = 0.0) -> float: Direction of travel from (x0, y0) to (x1, y1).
  • locate_speed_traps(session, max_laps: int = 12, grid_n: int = 2001) -> pd.DataFrame: Where are OpenF1's i1 / i2 / st speed traps? For the fastest lap of up to max_laps drivers (within 103 % of the session best) the speed trace is put on a normalised distance grid; each trap sits where the median |tr...
  • rain_markov(p_rain_given_dry: float = 0.0055, p_rain_given_rain: float = 0.8899) -> np.ndarray: Per-minute transition matrix [[P(dry|dry), P(rain|dry)], [P(dry|rain), P(rain|rain)]] of the station flag.
  • nowcast(raining_now: bool, minutes: int, P: np.ndarray | None = None) -> float: P(station flags rain in minutes) under the two-state chain.
  • dry_gauge(model: wet.WetPenaltyModel = WetPenaltyModel(tie_slick=0.113, slop...) -> float: The wetness gauge at which a slick has zero penalty (a dry track): w0 = tie - tie / slope.
  • class WeatherScenario(rain: np.ndarray, gauge: np.ndarray, onset: int | None, stop: int | None, peak: float): One simulated race's weather, lap by lap: rain[L-1] is True on laps with rain falling; gauge[L-1] is the wetness gauge w (the intermediate's excess over dry pace, Chapter 15); onset / stop are the first rain lap and t...
  • sample_weather_scenario(n_laps: int, p_rain: float, rng: np.random.Generator, window: tuple = (1, None), shower_laps=(4.6, 4.7, 5.3, 5.5, 5.9, 5.9, 6.3, 6..., peak=(0.077, 0.132, 0.216), up_laps: float = 2.0, down_laps=(6.0, 16.0), model: wet.WetPenaltyModel = WetPenaltyModel(tie_slick=0.113, slop...) -> WeatherScenario: Draw one race's weather.
  • wet_lap_penalty_s(cls: str, gauge, dry_ref_s: float, model: wet.WetPenaltyModel = WetPenaltyModel(tie_slick=0.113, slop...): Lap-time penalty (s) of tyre class cls at wetness gauge w over a SLICK on a dry track, for a circuit with dry pace dry_ref_s.
  • early_switch_ev(p_rain: float, gain_if_rain_s: float, cost_if_dry_s: float) -> dict: Expected value (s, positive = good) of an early switch that gains gain_if_rain_s if the rain comes and costs cost_if_dry_s if it does not.
  • class DryTyres(deg: dict, offset: dict, cap: dict): Linear dry tyre model: deg (s/lap per lap of age) and offset vs MEDIUM (s/lap), longest stint cap.
  • methods and properties: stint, best_finish
  • sample_neutralisations(n_laps: int, lam: np.ndarray, rng: np.random.Generator, library: pd.DataFrame) -> np.ndarray: Lap statuses ('' green, 'SC', 'VSC', 'RED') with a per-lap hazard array (wet laps raise it).
  • drive(plan: tuple, policy: str, scen: WeatherScenario, status: np.ndarray, tyres: DryTyres, dry_ref_s: float, loss: dict, sc_window: int = 0, model: wet.WetPenaltyModel = WetPenaltyModel(tie_slick=0.113, slop...) -> tuple[float, int]: Race time (s, relative to an all-dry no-wear race) of one car.
  • simulate_weather_race(n_sim: int, n_laps: int, p_rain: float, plans: dict, policies=('react',), tyres: DryTyres = None, dry_ref_s: float = 90.0, hazard: dict | None = None, library: pd.DataFrame | None = None, loss: dict | None = None, window: tuple = (1, None), wet_ratio: float = 2.38, sc_window: int = 8, seed: int = 42) -> pd.DataFrame: Monte Carlo of one car over n_sim races with common random numbers: each race draws a weather scenario (sample_weather_scenario) and, with a hazard raised by wet_ratio on wet laps, its SC/VSC/red periods.

boxbox.reliability (Chapter 37)

Box Box — reliability.py (Chapter 37): DNF hazards, race-control penalties and the price of a penalty.

  • categorise_status(status, laps_completed=None) -> str: finished / lapped / mechanical / accident-collision / other / disqualified / did-not-start.
  • era_label(year: int) -> str
  • results_table(years=None, starters_only: bool = True) -> pd.DataFrame: Jolpica results with category, started, dnf, era, race_laps (winner's laps) and dist_frac.
  • dnf_rate(df: pd.DataFrame, by=None) -> pd.DataFrame: DNF rate (DNFs / starters) with a Wilson 95 % interval, overall or grouped by column(s) by.
  • survival_curve(df: pd.DataFrame, grid=array([0. , 0.01, 0.02, 0.03, 0.04, ...) -> pd.DataFrame: Kaplan-Meier probability that a starter is still running at each fraction of race distance.
  • dnf_hazard(years=None, era: str | None = None, team: str | None = None, df: pd.DataFrame | None = None, exclude_lap1: bool = False) -> dict: Per-lap DNF hazard by race phase (lap 1, laps 2-10, middle, final 10) from Jolpica results.
  • team_dnf_shrunk(year: int, df: pd.DataFrame | None = None) -> pd.DataFrame: Empirical-Bayes (beta-binomial, method of moments) shrinkage of team DNF rates within one season.
  • sample_dnf(n_laps: int, hazard: dict, n_cars: int = 1, rng: np.random.Generator | None = None, multiplier=1.0) -> np.ndarray: Sample a retirement lap for each car (NaN = finishes) from a phase hazard dict (dnf_hazard output).
  • hazard_to_p(hazard: dict, n_laps: int, multiplier: float = 1.0) -> float: P(DNF) over a race of n_laps under a phase hazard: 1 - prod(1 - h_L).
  • reason_group(reason) -> str: Coarse offence group from the reason text race control gives ('' -> 'not stated').
  • parse_message(msg: str) -> dict: Classify one race-control message.
  • rc_events(years=(2023, 2024, 2025, 2026), kinds=('R',), session=None) -> pd.DataFrame: Every stewarding / track-limits message, parsed (one row per message).
  • penalty_table(years=(2023, 2024, 2025, 2026), kinds=('R',), events: pd.DataFrame | None = None) -> pd.DataFrame: One row per (car, penalty) announced in the feed: pen_type, pen_s, reason, group, lap, served (a matching PENALTY SERVED message later in the session).
  • investigations(events: pd.DataFrame) -> pd.DataFrame: Link messages into incidents and give each its final visible outcome.
  • deletions(events: pd.DataFrame) -> pd.DataFrame: Deleted lap times (one row per deletion): car, acronym, location (turn), deleted_lap, reason.
  • track_limit_strikes(events: pd.DataFrame) -> pd.DataFrame: For every driver-race: running count of track-limits deletions when the black-and-white flag was shown and when a track-limits penalty was announced.
  • grid_drops(years=range(2014, 2027)) -> pd.DataFrame: Jolpica starting grid vs qualifying position for every starter.
  • penalty_cost(penalty_s: float, years=(2023, 2024, 2025, 2026), max_pos: int = 20) -> pd.DataFrame: Counterfactual price of a time penalty added at the flag: for each classified finisher on the lead lap (Jolpica race time), count cars behind on the same lap that finished within penalty_s.
  • class PenaltyRisk(per_car_race: float, share_5s: float, share_10s: float, share_other: float, n_penalties: int, n_car_races: int): Per-race stewarding risk for the simulator: expected in-race time penalties per car, the share that are 5 s vs 10 s, and the mean drive-through/stop-go share (counts from the race-control feed).
  • methods and properties: sample
  • penalty_risk(pen: pd.DataFrame, n_car_races: int) -> PenaltyRisk: Build a PenaltyRisk from penalty_table output and the number of car-races it covers.
  • retirement_traces(session) -> pd.DataFrame: What race control says about each retirement of one race (never a cause): for each OpenF1 result with dnf/dns/dsq, the last completed lap, whether an INCIDENT/COLLISION message names the car within [-1, +2] leader lap...

boxbox.betting (Chapter 38)

Box Box - betting: odds <-> probabilities, overround removal, edge, expected value and Kelly sizing (Chapter 38).

  • decimal_from_fractional(text: str) -> float: Decimal odds from a fractional price: "5/2" -> 3.5, "evens" -> 2.0, "1/3" -> 1.333...
  • decimal_from_american(a: float) -> float: Decimal odds from an American (moneyline) price: +250 -> 3.5, -150 -> 1.667.
  • implied_prob(odds): Implied probability 1/odds for decimal odds (scalar, array or Series).
  • overround(odds, n_winners: int = 1) -> float: Booksum minus the number of winners: 0.12 means the implied probabilities add to 112 % of a winner market.
  • remove_overround(odds, method: str = 'multiplicative', n_winners: int = 1): Turn a book's prices into probabilities that sum to n_winners.
  • hypothetical_book(p, margin: float = 0.15, method: str = 'power', round_to_ladder: bool = True, max_odds: float = 1001.0, n_winners: int = 1): ILLUSTRATIVE decimal odds built from probabilities p with a stated overround margin.
  • expected_value(p, odds): Expected profit per unit staked: p * odds - 1 (0.05 = +5 %).
  • kelly(p, odds, fraction: float = 1.0, cap: float | None = None): Kelly (1956) stake for a binary bet as a share of bankroll: f = (po - 1)/(o - 1), floored at 0.
  • kelly_exclusive(p, odds): Kelly stakes for mutually exclusive outcomes (one winner), e.g. backing several drivers in one race.
  • log_growth(f, p: float, odds: float): Expected log growth per bet when staking a share f of bankroll on a binary bet.
  • simulate_bankroll(p_true, p_belief, odds, fraction: float = 1.0, n_paths: int = 1000, seed: int = 42, start: float = 1.0, cap: float | None = None) -> np.ndarray: Bankroll paths for a sequence of independent binary bets.
  • edge_report(p_model: pd.Series, odds: pd.Series, method: str = 'power', min_edge: float = 0.05, kelly_fraction: float = 0.25, n_winners: int = 1, cap: float | None = 0.05) -> pd.DataFrame: One row per runner: price, implied and fair probability, model probability, edge, Kelly stake, verdict.
  • shrink_rates(k, n) -> tuple[np.ndarray, float, float]: Empirical-Bayes beta-binomial shrinkage of rates k/n towards the pooled rate.

boxbox.series (Chapter 39)

Box Box: rule profiles for other series (Chapter 39).

  • class RuleProfile(name: str, race_laps: int, base_lap_s: float, pit_lane_loss_s: float, tyre_change_s: float, deg_s_per_lap: float, tyre_life_laps: int = 10000, cliff_s_per_lap2: float = 0.02, fuel_per_lap_kg: float = 1.8, s_per_kg: float = 0.035, refuel: bool = False, refuel_rate_kg_s: float = 12.0, tank_kg: float | None = None, min_stops: int = 0, max_stint_laps: int | None = None, driver_change_s: float = 0.0, parallel_service: bool = True, caution_rate: float = 0.0, caution_laps: int = 4, caution_lap_factor: float = 1.6, caution_fuel_factor: float = 0.4, caution_pit_factor: float = 0.45, stage_ends: tuple = (), notes: str = ''): Rules plus the few physics parameters a race-time model needs.
  • methods and properties: fuel_total_kg
  • adapt(profile: RuleProfile, name: str | None = None, **changes) -> RuleProfile: Return a copy of profile with some rules or parameters changed, e.g. adapt(F1_2026, refuel=True) or adapt(OVAL, caution_rate=0.05).
  • lap_times(p: RuleProfile, stop_laps, tyre_change=None) -> pd.DataFrame: Lap-by-lap times (no stop costs) for a plan.
  • stop_costs(p: RuleProfile, stop_laps, tyre_change=None, driver_change=None) -> list[float]: Time cost of each stop: pit-lane loss + stationary time.
  • feasible(p: RuleProfile, stop_laps) -> bool: Plan respects min stops, tank size and max stint length.
  • race_time(p: RuleProfile, stop_laps, tyre_change=None, driver_change=None) -> float: Total race time (s) of a plan, or inf if the plan breaks the rules.
  • even_stops(race_laps: int, n_stops: int) -> list[int]: Stop laps that split the race into n_stops + 1 near-equal stints.
  • optimise(p: RuleProfile, max_stops: int = 6, tyre_every: int = 1, polish: bool = True) -> pd.DataFrame: Best plan for each stop count: start from even stints, then nudge each stop +-1..3 laps while it helps.
  • best_plan(p: RuleProfile, max_stops: int = 6, tyre_every: int = 1) -> dict: The single best row of optimise as a dict.
  • simulate_cautions(p: RuleProfile, policy: str = 'fixed', planned_stops=None, window_open: float = 0.7, n_runs: int = 2000, seed: int = 42) -> np.ndarray: Monte Carlo race times under random full-course cautions (plus scheduled stage-end cautions).
  • energy_plan(n_laps: int, budget: float, e_free: float, k_s_per_unit2: float, cheap_laps=(), e_cheap: float | None = None) -> pd.DataFrame: Allocate a fixed energy budget over a race when using less than e_free on a lap costs k * (e_free - e)^2 seconds (lift-and-coast makes the cost convex; see Chapter 39).
  • compare_profiles(profiles, max_stops: int = 6) -> pd.DataFrame: Best stop count and time for each profile (one row per profile).

boxbox.cli (Chapter 40)

Box Box - cli: the command line, and the thin adapter layer that assembles the modules (Chapter 40).

  • class RaceContext(year: int, round: int, gp_name: str, circuit: str, n_laps: int, date: pd.Timestamp, race_key: int | None, quali_key: int | None, sprint_weekend: bool, meeting_key: int | None = None): One Grand Prix as the simulator sees it.
  • methods and properties: label, has_race
  • resolve_race(year: int, gp) -> RaceContext: Find a Grand Prix by round number, Jolpica circuit_ref ("vegas", "rodriguez", "marina_bay") or a name substring ("Las Vegas").
  • races_table(year: int) -> pd.DataFrame: The Grands Prix of a season in the data: round, circuit_ref (the --gp key), name, laps, race data?
  • actual_strategies(session) -> pd.DataFrame: What every driver did, as strategy.actual_strategies (stop = change to a different set, stop lap = the in-lap, red-flag tyre changes counted apart), but with phantom zero-length stints removed first.
  • quali_best(quali_key: int) -> pd.Series: Each driver's best lap of the Grand Prix qualifying session (min of Q1/Q2/Q3), s.
  • quali_to_race(year: int, before_round: int, min_races: int = 3) -> dict: Race gap % (pace.race_pace_table: data fuel, traffic excluded) = b x qualifying gap % in the season's earlier dry races (Chapter 27's link).
  • class Inputs(ctx: RaceContext, field: pd.DataFrame, base_lap_s: float, pace_sd_s: float, q2r: dict, deg: dict, deg_source: dict, cap: dict, pit_pool: np.ndarray, pit_note: str, hazard: dict, k: float, k_ci: tuple, library: pd.DataFrame, sc_ratio: dict, dnf: dict, dnf_field: float, lap1_dnf: float, pass_target: float, pass_note: str, weather: dict, min_stops: int, allocation: dict | None, notes: list = field(default_factory=...)): Inputs(ctx: 'RaceContext', field: 'pd.DataFrame', base_lap_s: 'float', pace_sd_s: 'float', q2r: 'dict', deg: 'dict', deg_source: 'dict', cap: 'dict', pit_pool: 'np.ndarray', pit_note: 'str', hazard: 'dict', k: 'float'...
  • methods and properties: pit_loss_s, tyre_model
  • build_inputs(ctx: RaceContext, pace_sd_scale: float = 1.0) -> Inputs: Every input of the simulation from information available before the race.
  • race_model(I: Inputs, first_stint_age: int = 0) -> st.RaceModel
  • clean_optimum(I: Inputs, start_compound: str | None = None, start_age: int = 0, max_stops: int = 3) -> pd.DataFrame: Chapter 12's exhaustive optimiser under the season's rules (minimum stops, 2026 tyre allocation), each row checked with regs.validate_strategy.
  • one_stop_window(I: Inputs, c1: str, c2: str, start_age: int = 0) -> dict: The single stop c1 -> c2: optimal in-lap, 1-s window, curve, degenerate flag (degradation.call_one_stop).
  • policies(I: Inputs) -> dict
  • race_setup(I: Inputs, calibrate: bool = True, calib_sims: int = 300, hazard_scale: float = 1.0) -> tuple: The montecarlo.RaceSetup of the field.
  • ghost_compare(I: Inputs, n_sims: int = 10000, seed: int = 42, hazard_scale: float = 1.0) -> dict: Anchor C's clock-only comparison: identical cars, no traffic, the same races for every policy.
  • simulate(ctx: RaceContext, n_sims: int = 10000, compare_sims: int = 5000, focal: str | None = None, seed: int = 42, calibrate: bool = True, pace_sd_scale: float = 1.0, with_gbm: bool = True, wet_sensitivity: bool = True, verbose: bool = True) -> dict: The whole pipeline for one Grand Prix.
  • gbm_probabilities(ctx: RaceContext) -> pd.DataFrame | None: Chapter 26's gradient-boosting race model, trained on seasons before this one (walk-forward), for this race.
  • validate(sim: dict) -> dict: Score a simulation against the race: the winner's strategy vs the clean-race optimum, the stop lap vs the model's best lap for the winner's own tyres, and the probabilities vs the result.
  • hindsight_optimum(ctx: RaceContext, I: Inputs) -> dict: The clean-race optimum on the race's OWN degradation (strategy.fit_race_model: median canonical stint slope per compound, default fuel correction), the same pit loss and rules.
  • opt_rank(table: pd.DataFrame, sequence: str): (rank, gap_s) of a compound sequence in an optimiser table, or None.
  • print_simulation(sim: dict) -> None
  • print_validation(v: dict) -> None
  • build_parser() -> argparse.ArgumentParser
  • run(args) -> dict
  • main(argv=None) -> int

boxbox.report (Chapter 40)

Box Box - report: charts and a self-contained HTML report of one simulation (Chapter 40).

  • strategy_figure(sim: dict, validation: dict | None = None, n: int = 6): The n fastest compound sequences of the clean-race optimum, each with its modelled cost, plus the winner's actual plan priced by the same model when a validation is given.
  • probability_figure(sim: dict, validation: dict | None = None, n: int = 10): P(win) and P(podium) for the top n cars by expected position, with the GBM P(win) as a marker and the actual finishing position written on the right when a validation is given.
  • position_figure(sim: dict): Finishing-position distribution of the focal car under each policy (same simulated races).
  • ghost_figure(sim: dict): Clock-only comparison (Anchor C's measure): time of each multi-stop policy minus the minimum-stop plan.
  • curve_figure(sim: dict, validation: dict | None = None): Race time vs stop lap for the best one-stop compound pair; the 1-s window shaded; the winner's actual stop (validation) marked.
  • write_report(sim: dict, validation: dict | None, path) -> Path: Write the HTML report and return its path.