Skip to content

H7Dev/F1-Simulator-Python

Repository files navigation

F1 Simulator - Formula 1 Season Simulator

A comprehensive Python-based Formula 1 season simulator that models qualifying sessions, races, championships, and generates detailed reports.

Overview

The F1 Simulator provides:

  • Qualifying Simulations: Dynamic qualifying sessions with driver skill variation
  • Race Simulations: Full race simulations with pit stops, weather conditions, and reliability
  • Championship Tracking: Driver and team championship calculations
  • HTML Reports: Detailed browseable race results and standings
  • REST API: HTTP server for running simulations programmatically
  • Deterministic Runs: Seed-based reproducible simulations
  • Multi-Environment: Development and test configurations

Project Structure

F1-Simulator-Python/
├── src/                      # Core simulation modules
│   ├── models.py            # Data models and records
│   ├── loader.py            # CSV/JSON data loaders
│   ├── validator.py         # Data validation
│   ├── qualifying.py        # Qualifying session logic
│   ├── race.py              # Race simulation logic
│   ├── simulator.py         # Main orchestrator
│   ├── runtime_config.py    # Configuration management
│   └── component.py         # Component definitions
├── tests/                    # Test suite (96 tests)
├── data/                     # Simulation data
│   ├── drivers.csv          # Driver attributes
│   ├── cars.csv             # Car specifications
│   ├── tracks.json          # Track configurations
│   └── points.json          # Championship points system
├── config/                   # Environment configurations
│   ├── dev.json             # Development config
│   └── test.json            # Test config
├── server.py                # REST API server
├── Dockerfile               # Docker containerization
├── Jenkinsfile              # CI/CD pipeline
├── requirements.txt         # Python dependencies
└── README.md                # This file

Quick Start

Prerequisites

  • Python 3.11+
  • pip (Python package manager)
  • Docker (optional, for containerized deployment)
  • Jenkins (optional, for CI/CD)

Installation

  1. Clone the repository

    git clone <repository-url>
    cd F1-Simulator-Python
  2. Create a virtual environment (recommended)

    python -m venv venv
    
    # Windows
    venv\Scripts\activate
    
    # macOS/Linux
    source venv/bin/activate
  3. Install dependencies

    pip install -r requirements.txt

Usage

Running Tests

Execute the full test suite (96 tests):

# Run all tests with verbose output
python -m pytest tests/ -v

# Run with short traceback format
python -m pytest tests/ -v --tb=short

# Run specific test file
python -m pytest tests/test_simulator_integration.py -v

# Run with coverage report (if coverage installed)
pytest tests/ --cov=src

Running the Simulator

Command-line Simulation

Run a single F1 season simulation:

# Basic simulation (dev environment, random seed)
python -m src.simulator

# Test environment with fixed seed for reproducibility
python -m src.simulator --env test --seed 42

# Specify output directory
python -m src.simulator --output-dir output/season_2026

# Export results to JSON and CSV
python -m src.simulator --export-json --export-csv --output-dir output

# Combined example
python -m src.simulator --env test --seed 123 --output-dir results --export-json --export-csv

Output: Generates race_results.html with complete season report

Starting the REST API Server

Launch the HTTP server for programmatic access:

# Start server on default port 8080
python server.py

# Or use the module approach
python -m http.server 8080

Available Endpoints:

  • GET /health - Health check
  • GET /metrics - Simulation metrics
  • POST /simulate - Run simulation with custom data

Example API Usage:

# Health check
curl http://localhost:8080/health

# Get metrics
curl http://localhost:8080/metrics

# Run simulation (POST request with JSON payload)
curl -X POST http://localhost:8080/simulate \
  -H "Content-Type: application/json" \
  -d @simulation_config.json

Configuration

Environment Variables

# Set runtime environment
set ENV=test              # Windows
export ENV=test           # macOS/Linux

# Set random seed
set SEED=42              # Windows
export SEED=42           # macOS/Linux

Config Files

  • config/dev.json - Development configuration

    • Debug enabled
    • Hot reload enabled
    • Higher log verbosity
    • Max 100 simulations
  • config/test.json - Test configuration

    • Debug disabled
    • Fixed seed: 42
    • Max 10 simulations
    • Output to output/ directory

Data Files

  • data/drivers.csv - Driver specifications (qualifying_skill, race_skill, consistency, etc.)
  • data/cars.csv - Vehicle specifications (engine_power, aero_efficiency, etc.)
  • data/tracks.json - Track configurations (laps, weather, overtaking_difficulty, etc.)
  • data/points.json - Championship points system (1st place: 25 points, etc.)

Docker Deployment

Building the Docker Image

# Build with latest tag
docker build -t f1-simulator:latest .

# Build with version tag
docker build -t f1-simulator:1.0 .

# Build and tag for registry
docker build -t localhost:5000/f1-simulator:latest .

Running in Docker

# Run with default settings (server mode)
docker run -d -p 8080:8080 --name f1-sim f1-simulator:latest

# Run simulator inside container
docker run --rm -v $(pwd)/output:/app/output f1-simulator:latest \
  python -m src.simulator --output-dir output

# Interactive terminal
docker run -it f1-simulator:latest /bin/bash

# Run tests in container
docker run --rm f1-simulator:latest python -m pytest tests/ -v

Docker Compose (Optional)

Create a docker-compose.yml if needed:

version: '3'
services:
  f1-simulator:
    build: .
    ports:
      - "8080:8080"
    environment:
      - ENV=test
      - SEED=42
    volumes:
      - ./output:/app/output
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3

Run with: docker-compose up

Jenkins CI/CD Pipeline

Pipeline Stages

The Jenkins pipeline (Jenkinsfile) includes:

  1. Checkout - Clone source code
  2. Setup Environment - Install Python and dependencies
  3. Run Tests - Execute pytest with JUnit reporting
  4. Code Quality Check - Compile Python code
  5. Build Docker Image - Create Docker image
  6. Test Docker Container - Validate container health
  7. Run Simulator - Execute F1 simulation
  8. Generate Reports - Produce simulation results
  9. Cleanup - Remove temporary resources

Running the Pipeline

# Trigger pipeline build
curl -X POST http://<jenkins-url>/job/F1-Simulator/build

# View pipeline execution
# Jenkins UI: http://<jenkins-url>/job/F1-Simulator/

Pipeline Environment Variables

  • DOCKER_IMAGE_NAME: f1-simulator
  • DOCKER_REGISTRY: localhost:5000
  • PYTHON_VERSION: 3.11
  • PYTEST_REPORT: reports/pytest.xml

Jenkins Setup Requirements

  1. Install Jenkins plugins:

    • Pipeline Plugin
    • Docker Pipeline Plugin
    • JUnit Plugin
  2. Configure Jenkins agent:

    • Python 3.11+ installed
    • Docker installed and accessible
    • Git client installed
  3. Create pipeline job:

    • Pipeline script from SCM (Git)
    • Repository URL: <your-repo-url>
    • Branch: */main
    • Script path: Jenkinsfile

Test Coverage

The project includes 96 comprehensive tests covering:

  • Data Loading (test_loader.py) - CSV/JSON parsing, validation
  • Validation (test_validator.py) - Data integrity checks
  • Qualifying (test_qualifying.py) - Qualifying session logic
  • Race Simulation (test_race.py) - Race physics and outcomes
  • Integration (test_simulator_integration.py) - End-to-end simulation
  • Season (test_simulator_season.py) - Full season championship
  • Server (test_server.py) - HTTP API endpoints

Run all tests:

python -m pytest tests/ -v --tb=short

Data Format Examples

drivers.csv

driver_id,name,team,qualifying_skill,race_skill,consistency,aggression,tyre_management,wet_skill,car_id
D01,Max Verstappen,Red Bull,95,95,90,85,88,80,C01
D02,Lewis Hamilton,Mercedes,92,93,88,70,92,88,C02

cars.csv

car_id,team,engine_power,aero_efficiency,braking,mechanical_grip,reliability,pit_stop_speed,team_color
C01,Red Bull,95,90,88,92,90,95,#00008F
C02,Mercedes,92,92,90,90,92,90,#00D2BE

tracks.json

[
  {
    "track_name": "Bahrain",
    "circuit_type": "permanent",
    "laps": 57,
    "base_lap_time": 95.5,
    "weather": "dry",
    "top_speed_rating": 80,
    "high_speed_corners": 40,
    "low_speed_corners": 30,
    "overtaking_difficulty": 6,
    "pit_stop_delta": 23.0,
    "drs_zones": 2
  }
]

points.json

{
  "1": 25,
  "2": 18,
  "3": 15,
  "4": 12,
  "5": 10,
  "6": 8,
  "7": 6,
  "8": 4,
  "9": 2,
  "10": 1
}

Output Files

After running the simulator, generated files include:

  • race_results.html - Interactive race results and standings (main deliverable)
  • final_standings.json - Driver and team championship data (if --export-json used)
  • final_standings.csv - Championship results in CSV format (if --export-csv used)

Troubleshooting

Issue: Module not found errors

# Ensure you're in the project directory
cd F1-Simulator-Python

# Install dependencies
pip install -r requirements.txt

# Try running with explicit path
python -m src.simulator

Issue: Data files not found

# Verify data directory exists
dir data/

# Verify required files
# data/drivers.csv
# data/cars.csv
# data/tracks.json
# data/points.json

Issue: Docker build fails

# Rebuild without cache
docker build --no-cache -t f1-simulator:latest .

# Check Docker installation
docker --version

# Verify Python dependencies
pip list

Issue: Tests fail

# Run single test for debugging
python -m pytest tests/test_loader.py::test_load_drivers_valid -v

# Run with full traceback
python -m pytest tests/ -v --tb=long

# Show print statements during tests
python -m pytest tests/ -v -s

Performance Optimization

  • Use --seed for reproducible, faster simulations
  • Docker for isolated, portable runs
  • Parallel test execution: pytest -n auto (requires pytest-xdist)
  • Environment-specific configs for different workloads

Contributing

  1. Write tests for new features
  2. Ensure all tests pass: pytest tests/ -v
  3. Code should be type-hinted where possible
  4. Use descriptive commit messages

License

[Add your license here]

Support

For issues or questions:

  1. Check test output: python -m pytest tests/ -v
  2. Review configuration: cat config/dev.json
  3. Check logs from simulator run
  4. Consult Docker logs: docker logs f1-simulator

Version History

  • v1.0 - Initial release with full season simulation, REST API, Docker support, and Jenkins CI/CD

Related Commands

# Development workflow
python -m pytest tests/ -v              # Run tests
python -m src.simulator --seed 42       # Test simulation
docker build -t f1-sim:latest .        # Build image
docker run -p 8080:8080 f1-sim:latest  # Run container

# Debugging
python -c "import src.simulator; print('Module loads successfully')"
python -m py_compile src/simulator.py

# CI/CD
python -m pytest tests/ --junit-xml=reports/pytest.xml
docker push localhost:5000/f1-simulator:latest

# Production
ENV=test python -m src.simulator --seed 42 --output-dir /var/output

Architecture

User/CI System
      ↓
Jenkinsfile (CI/CD Pipeline)
      ↓
[Checkout → Test → Docker Build → Validate]
      ↓
Docker Image (f1-simulator:latest)
      ↓
[Server Container OR Simulator Container]
      ↓
HTTP API or HTML Reports/Metrics

Key Components

  • simulator.py - Main orchestrator, runs full season
  • qualifying.py - Qualifying session algorithms
  • race.py - Race simulation with pit stops and reliability
  • loader.py - Data file I/O (CSV/JSON)
  • validator.py - Data integrity validation
  • models.py - Type-safe data records
  • server.py - HTTP API server
  • runtime_config.py - Configuration management

Last Updated: May 16, 2026
Status: ✓ All 96 tests passing
Docker: ✓ Production-ready image
CI/CD: ✓ Full Jenkins pipeline

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors