# 🏎️ F1 race simulator

## 📌 Overview

This project develops a **real-time Formula 1 race strategy simulator** that uses **Transformer-based AI models** to predict and adapt race strategy decisions dynamically. It integrates historical and live data to recommend **optimal pit stop windows and tyre compound choices**, making it a valuable tool for engineers, strategists and motorsport data scientists.

By combining **mathematical rigor**, **software engineering** and **modern AI**, the simulator bridges the gap between theoretical machine learning and practical motorsport strategy.

---

## 🎯 Objectives
- Build Transformer models to predict:
  - Best **pit stop timing**.
  - Ideal **tyre compound** under current/future race conditions.
- Ingest and process real-time F1 data from official APIs.
- Provide dynamic, low-latency strategic recommendations during a race.
- Test and validate the simulator using real Grand Prix scenarios.

---

## 🏗️ Architecture

Two custom Transformer models are deployed:

1. **PitStopTransformer**  
   Predicts the most advantageous lap to execute a pit stop by learning from sequential race data such as tyre wear, gap deltas and SC/VSC windows.

2. **CompoundTransformer**  
   Recommends the most suitable tyre compound based on current race context, car performance trends, track evolution and weather conditions.

These models leverage:
- **Self-attention mechanisms** to model long-range dependencies.
- **Positional encodings** to understand temporal sequence.
- **Feed-forward layers** to reason over nonlinear strategies.

---

## 🧱 Data Pipeline

- **Historical Data**: Via [FastF1 API](https://docs.fastf1.dev/)
- **Real-Time Telemetry**: Using [OpenF1 API](https://openf1.org/)
- **PostgreSQL Database**: For structured storage of lap-by-lap, car and session data
- **TensorFlow Pipelines**: For streaming, training and serving ML models

---

## 🧠 AI Models

- **Framework**: TensorFlow  
- **Model Type**: Custom Transformers  
- **Input Features**:
  - Lap times, tyre compound, stint length
  - Weather conditions
  - Gap to car ahead/behind
  - Fuel load estimates
  - Race incidents (SC, VSC, Red Flag)
- **Output**:
  - Next 5-lap **reward functions** guiding decisions
  - Strategy classification: undercut, overcut, go-long, react to FCY, etc.

---

## 🏁 Use Cases

- Executing **real-world race simulations** to evaluate model decisions in live scenarios:
  - **Max Verstappen at Suzuka**  
    Demonstrated high accuracy in pit window prediction and compound selection on a high-speed, high-degradation track. The model correctly suggested a medium-to-hard strategy and reassessed pit stop timing in real-time to match evolving conditions.

  - **Oscar Piastri at Imola**  
    Excelled in precise compound switching with minimal noise. The simulator identified optimal tyre changes exactly at the zero-crossing point, showing strong alignment between predicted and ideal strategy on a track where undercut timing is critical.

  - **Lando Norris at Shanghai**  
    Validated the simulator's robustness in adapting to street-circuit-like conditions. The model correctly filtered out unsuitable compounds, responded to short-term prediction uncertainty and settled into a stable medium-to-hard strategy with high confidence.

  Together, these cases demonstrate the simulator’s capacity to replicate realistic and adaptive strategy behavior in highly dynamic race environments.

- **Visualization of strategy insights**  
  Each simulation includes lap-by-lap graphs tracking tyre compound predictions and optimal pit windows, enabling comparison with real-world team decisions.

---

## 🔧 Tech Stack

- **Programming Language**: Python  
- **ML Framework**: TensorFlow + Keras  
- **Data Handling**: NumPy, Pandas  
- **Visualization**: Matplotlib, Seaborn  
- **APIs**: FastF1, OpenF1  
- **Database**: PostgreSQL with SQLAlchemy + psycopg2  
- **Dev Tools**: Jupyter Notebooks, tqdm, dotenv

---

## 📈 Results

- The simulator produces competitive, real-time strategies under varying race conditions.
- Demonstrated effectiveness in simulated races with strategic wins.
- Validated adaptability to high-degradation vs. wet-weather scenarios using real-world case studies.

---

## ⚙️ Installation & Requirements

To run the simulator locally, make sure the following components are properly installed and configured:

### 🗄️ Database Setup
- **PostgreSQL** must be installed and accessible via **pgAdmin** (or any PostgreSQL client).
- Configure your **`.env` file** with the correct credentials and connection details (host, port, user, password, database name).

### 📦 Python Dependencies
Install the required Python packages using pip:

```bash
pip install tensorflow keras pandas numpy matplotlib seaborn scikit-learn tqdm python-dotenv sqlalchemy psycopg2 fastf1 pymupdf pillow
```

**Note**: The simulator requires access to the FastF1 and OpenF1 APIs for data retrieval. Ensure your environment is connected to the internet and that API rate limits are respected.

---

## 📎 Thesis Reference

This simulator is the result of the bachelor’s thesis **“F1 Race Simulator”** by David Díez, University of Barcelona, 2025. It contributes to the growing field of AI in motorsport, offering real-time race analytics driven by Transformer-based sequence modeling.