Skip to content

imHardik1606/Pit-Window

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🏎️ Pit Window: F1 Strategy Decision Engine

A real-time Formula 1 race strategy simulation and modeling engine designed to predict the optimal lap for a driver to pit. By combining tire degradation modeling, fuel correction curves, and a live web dashboard, Pit Window translates chaotic track telemetry into actionable pit-stop recommendations.


🎯 Project Purpose

During an F1 race, selecting the optimal lap to pit is critical. The decision requires balancing:

  1. Tire Wear: Older tires degrade, increasing lap times and leading to a "tire cliff" where performance drops exponentially.
  2. Pit Stop Loss: Pitting incurs a major time penalty (e.g., ~24.5s in Monaco).
  3. Fuel Burn: Cars become faster as fuel weight decreases (~0.05s per lap).

This engine ingests live-updating lap data, strips out the noise (like fuel burn variations), dynamically calculates tire degradation trends using linear regression, and recommends the strategy that yields the lowest overall time over a 10-lap horizon.


📂 Project Structure

  • backend/: Contains core strategy service logic.
    • backend/service.py: The FastAPI backend server. Features CORS middleware support, WebSockets for live telemetry broadcasts, and endpoint logic (/ingest, /state, /health).
    • backend/strategy_model.py: The core strategy engine containing the PitStrategyModel. Handles model updates, telemetry history, linear regression fitting for tire wear, and recommendations.
  • frontend/: A modern web dashboard built with Next.js and TypeScript. Renders live telemetry cards for each driver and flags low-confidence predictions.
  • data/: Pre-downloaded race telemetry data files for simulation.
    • data/race_data_2023_6.json: Telemetry of the 2023 Monaco GP.
    • data/race_data_2026_7.json: Telemetry of the 2026 Barcelona GP.
  • scripts/: Utility scripts for data fetching, simulation, and manual validation.
    • scripts/chaos_harness.py: A simulator that tests the engine's resilience under network stress (e.g. packet drops, duplicate values, and out-of-order logs).
    • scripts/ingest_replay.py: Interacts with the FastF1 library to pull historical telemetry data.
    • scripts/run_real_test.py: Validates predictions against real-world team strategy decisions.
    • scripts/validate_barcelona_2026.py & scripts/validate_real_race.py: Scripts for validation.
  • tests/: Suite of unit tests.
    • tests/test_strategy.py: Unit tests verifying model accuracy, causality constraints, and confidence flags.
  • docs/: Detailed math and architecture specification documents.
  • logs/: Log files generated by the service and chaos harness.

🚀 How to Run the Project

Prerequisites

  • Python 3.8+
  • Node.js 18+

Step 1: Install Python Backend Dependencies

Install FastAPI, Uvicorn, Pydantic, and FastF1:

pip install fastapi uvicorn pydantic fastf1 requests pytest

Step 2: Start the Backend Service

Start the FastAPI server:

python backend/service.py

The backend server will run on http://localhost:8000. It acts as the ingestion and recommendation engine.

Step 3: Start the Frontend Dashboard

Navigate to the frontend folder, install npm packages, and run the Next.js development server:

cd frontend
npm install
npm run dev

Open http://localhost:3000 in your web browser. You will see the Live Connection dashboard connected to the backend.

Step 4: Stream Live Race Replay Telemetry

To simulate a live race and stream telemetry into the backend (which in turn updates the dashboard in real-time), run the chaos test harness in a new terminal:

python scripts/chaos_harness.py

This feeds telemetry data from the data/ directory while injecting simulated network chaos (packet loss, duplication, and out-of-order delivery) to demonstrate system resilience.


🛠️ Testing & Validation

Running Unit Tests

Validate model constraints, lookahead verification, confidence flags, and linear regressions by running:

pytest tests/test_strategy.py

Running Offline Strategy Validation

To validate predictions against a specific driver's entire race history and print detailed lap-by-lap metrics:

  • For 2026 Barcelona GP (runs for driver "NOR" by default, or pass any 3-letter driver code):
    python scripts/validate_barcelona_2026.py NOR
  • For 2023 Monaco GP (validates Max Verstappen "VER"):
    python scripts/validate_real_race.py
  • For Quick Verification (compares Verstappen's real pit lap with predictions up to lap 20):
    python scripts/run_real_test.py

Ingesting Custom F1 Sessions

To download telemetry for a custom F1 year/round index to use as simulation data:

  1. Open scripts/ingest_replay.py and modify the year/round inside the __main__ block:
    race_data = fetch_race_data(2026, 7) # Change parameters as desired
  2. Run the script:
    python scripts/ingest_replay.py

This will fetch race telemetry using FastF1, cache raw data in fastf1_cache/, and output a structured JSON file inside the data/ directory.


📊 How the Math Works

The engine relies on three mathematical components defined in docs/STRATEGY_SPEC.md:

  1. Fuel Weight Adjustment: $$\text{LapTime}{\text{adjusted}} = \text{LapTime}{\text{observed}} + (\text{Total Laps} - \text{Lap Number}) \times \text{Fuel Burn Rate}$$
  2. Degradation Rate (Linear Regression): After $5$ laps on a compound, the model fits a line over the adjusted lap times to determine the rate of tire decay per lap ($m$).
  3. Total Projected Time ($T_{\text{scenario}}$): Projects the cumulative lap time over the next $N$ laps (default $10$): $$T_{\text{scenario}} = \sum_{i=1}^{N} \text{ProjectedLapTime}_i + (\text{Pit Loss} \text{ if pitting})$$

The engine compares the projected totals for Stay Out, Pit Now, Pit in 2 Laps, and Pit in 3 Laps, choosing the lowest outcome (applying a $0.5$s tie-breaker margin to favor staying out).

About

Pit Window is a real-time Formula 1 race strategy simulation and modeling engine. It ingests live lap telemetry, filters out fuel weight variables, and dynamically calculates tire degradation using linear regression to recommend optimal pit-stop timing (e.g., Stay Out, Pit Now, or Pit in 2/3 Laps) via a modern Next.js dashboard.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors