Skip to content
ska2704Public

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PitWall

PitWall is a Formula 1 race simulator that replays historical grands prix lap by lap using six machine-learning models trained on real FastF1 telemetry. It lets you rewind any race from 2021 to 2025, ask "what if" questions about driver-constructor swaps, and run Monte Carlo batches to see how a race outcome distributes across ten independent simulations.

PitWall simulation results modal showing winner distribution, average finishing positions, and DNF probabilities


ML architecture

The simulation engine runs six sklearn pipelines, one per decision type. Every model is a HistGradientBoostingClassifier or HistGradientBoostingRegressor inside a CalibratedClassifierCV, trained on lap-level parquet data exported from FastF1.

Model Task Prediction Key features
Tyre degradation Regression Lap time as % over reference tyre life, compound, lap number, track temp, circuit
Pit timing Classification Probability a driver pits this lap tyre age, position, gap ahead/behind, SC status, lap %
Pit duration Regression Stationary time in seconds circuit, team, lap number, rainfall
DNF Classification Probability a driver retires team, grid position, circuit, year, rainfall
Safety car Classification Probability SC deploys this lap lap number, number of on-track battles, rainfall, circuit
Overtake Classification Probability attacker passes defender gap, tyre age delta, compound advantage, lap time delta, position

Temporal splits keep validation and test sets strictly in the future relative to training. The tyre and overtake models use a later training cutoff (train on 2021-2023, validate on 2024) because the 2022 regulation change invalidates pre-2022 lap-time patterns. All other models train on 2021, validate on 2022-2023, and test on 2024-2025.

Simulation loop

Each lap runs in this order:

  1. Tyre model predicts a degradation percentage for every active driver (one batch call)
  2. Pit timing model decides who pits (one batch call per lap)
  3. Pit duration model sets the time lost in the box
  4. Safety car model draws a deployment probability (precomputed as a 78x21 lookup table at race start to avoid 78 individual sklearn calls per run)
  5. DNF schedule is pre-drawn at race initialisation using each driver's retirement probability
  6. Overtake model evaluates all pairs within a 1-second gap window (one batch call)
  7. Rules enforcement: DRS, blue flags, two-compound regulation

Ten independent simulations run in parallel using a ThreadPoolExecutor. sklearn releases the GIL during C-level inference, so four threads give real parallelism with minimal overhead.


Data sources

All training data comes from the FastF1 Python library, which pulls lap timing, stint, weather, and race control data from the official F1 live timing API. Eighteen races are included in the default training set, spanning 2021 to 2025 across six circuits chosen to cover a range of overtaking difficulty, tyre degradation profiles, and safety car frequency.

The 2026 season tab uses projected data only. Constructor pace is computed as a weighted median of historical lap_time_pct values (30% weight on 2024, 70% on 2025, SC and pit laps filtered out). Driver skill ratings are teammate-normalised deltas averaged over all 2022-2025 races. Rookie drivers (Antonelli, Doohan, Bearman, Hadjar, Bortoleto) inherit their constructor's pace baseline.


Running locally

Prerequisites

  • Python 3.11+
  • Node.js 18+

Backend

# Install Python dependencies
pip install -r requirements.txt

# Fetch and preprocess training races (downloads from F1 live timing API, ~15 min)
python -m backend.data.bulk_fetch --no-retrain

# Train all six models (~2 min)
python -m backend.models.train

# Start the API server
uvicorn backend.main:app --reload --port 8000

The first bulk_fetch run downloads 18 races from FastF1 and caches them locally under backend/data/cache/. Subsequent runs skip races that are already cached.

Frontend

cd frontend
npm install
npm start

Opens at http://localhost:3000. The frontend proxies WebSocket connections to port 8000.

Controls

Control What it does
Year / Grand Prix dropdowns Select any processed race. 2026 shows a projected lineup.
Speed 1x streams one lap every 2 seconds. 100x skips the delay entirely.
SIMULATE Runs a single race in real time over the WebSocket.
WHAT IF Swap any driver into a different constructor before simulating. Changes feed into the DNF and pit duration models via the team feature.
RUN 10 Runs ten independent Monte Carlo simulations and shows a results modal with winner distribution (team-colored bars), average finishing positions, and DNF probabilities. Takes roughly 40 seconds.

Project layout

backend/
  api/
    routes.py       REST endpoints (/races, /races/2026, /sim/batch)
    websocket.py    WebSocket handler + circuit config table
  data/
    bulk_fetch.py   Training race list and fetch orchestration
    fetch.py        FastF1 session loader
    preprocess.py   Parquet exporter (laps, stints, results, weather)
    features.py     Shared feature loading utilities
    season_2026.py  Projected 2026 grid builder
  models/
    train.py        Training orchestrator
    tyre.py / pit.py / dnf.py / safety_car.py / overtake.py
    saved/          Trained .pkl files (not committed)
  sim/
    engine.py       Lap simulation loop
    state.py        RaceState, DriverEntry, CircuitFeatures dataclasses
    rules.py        DRS, blue flag, two-compound enforcement
frontend/
  src/
    App.jsx         Root component and state
    socket.js       WebSocket + REST client
    components/
      Controls.jsx      Race selector and action buttons
      Track.jsx         SVG circuit map with animated driver dots
      TimingTower.jsx   Live gap table
      GapGraph.jsx      Recharts gap-to-leader chart
      WhatIfModal.jsx   Driver-constructor swap configurator
      RunModal.jsx      Monte Carlo results visualisation

Adding more races

Edit TRAINING_RACES in backend/data/bulk_fetch.py, then run:

python -m backend.data.bulk_fetch

This fetches only the new sessions, skipping anything already cached, and retrains all models when done. Any newly processed race immediately appears in the year and grand prix dropdowns via the /api/races endpoint.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages