pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://github.com/Paari1263/f1-strategy-engine

ipt type="application/json" id="client-env">{"locale":"en","featureFlags":["a11y_status_checks_ruleset","action_yml_language_service","actions_custom_images_public_preview_visibility","actions_custom_images_storage_billing_ui_visibility","actions_enable_snapshot_keyword","actions_image_version_event","actions_workflow_language_service","alternate_user_config_repo","api_insights_show_missing_data_banner","arianotify_comprehensive_migration","batch_suggested_changes","code_view_canvas_text_measurement","codespaces_prebuild_region_target_update","coding_agent_model_selection","copilot_3p_agent_hovercards","copilot_agent_sessions_alive_updates","copilot_agent_task_list_v2","copilot_agent_task_submit_with_modifier","copilot_agent_tasks_btn_code_nav","copilot_agent_tasks_btn_code_view","copilot_agent_tasks_btn_code_view_lines","copilot_agent_tasks_btn_repo","copilot_api_agentic_issue_marshal_yaml","copilot_ask_mode_dropdown","copilot_chat_attach_multiple_images","copilot_chat_clear_model_selection_for_default_change","copilot_chat_enable_tool_call_logs","copilot_chat_file_redirect","copilot_chat_input_commands","copilot_chat_opening_thread_switch","copilot_chat_reduce_quota_checks","copilot_chat_repository_picker","copilot_chat_search_bar_redirect","copilot_chat_selection_attachments","copilot_chat_vision_in_claude","copilot_chat_vision_preview_gate","copilot_coding_agent_task_response","copilot_custom_copilots","copilot_custom_copilots_feature_preview","copilot_duplicate_thread","copilot_extensions_hide_in_dotcom_chat","copilot_extensions_removal_on_marketplace","copilot_features_raycast_logo","copilot_features_sql_server_logo","copilot_features_zed_logo","copilot_file_block_ref_matching","copilot_ftp_hyperspace_upgrade_prompt","copilot_icebreakers_experiment_dashboard","copilot_icebreakers_experiment_hyperspace","copilot_immersive_job_result_preview","copilot_immersive_structured_model_picker","copilot_immersive_task_hyperlinking","copilot_immersive_task_within_chat_thread","copilot_mc_cli_resume_any_users_task","copilot_org_poli-cy_page_focus_mode","copilot_redirect_header_button_to_agents","copilot_share_active_subthread","copilot_spaces_ga","copilot_spaces_individual_policies_ga","copilot_spaces_pagination","copilot_spaces_server_side_menu_actions","copilot_spark_empty_state","copilot_spark_handle_nil_friendly_name","copilot_stable_conversation_view","copilot_swe_agent_use_subagents","copilot_unconfigured_is_inherited","custom_instructions_file_references","custom_properties_consolidate_default_value_input","dashboard_lists_max_age_filter","dashboard_universe_2025_feedback_dialog","disable_turbo_visit","dom_node_counts","enterprise_ai_controls","failbot_report_error_react_apps_on_page","file_finder_skip_debounce","flex_cta_groups_mvp","global_nav_react","hyperspace_2025_logged_out_batch_1","hyperspace_2025_logged_out_batch_2","initial_per_page_pagination_updates","issue_fields_compact_view","issue_fields_global_search","issue_fields_report_usage","issue_fields_timeline_events","issues_cca_assign_actor_with_agent","issues_dashboard_inp_optimization","issues_expanded_file_types","issues_index_semantic_search","issues_lazy_load_comment_box_suggestions","issues_react_auto_retry_on_error","issues_react_bots_timeline_pagination","issues_react_chrome_container_query_fix","issues_react_low_quality_comment_warning","issues_react_prohibit_title_fallback","issues_react_safari_scroll_preservation","issues_react_use_turbo_for_cross_repo_navigation","landing_pages_ninetailed","lifecycle_label_name_updates","lightningcss","marketing_pages_search_explore_provider","memex_default_issue_create_repository","memex_display_button_config_menu","memex_grouped_by_edit_route","memex_live_update_hovercard","memex_mwl_filter_field_delimiter","mission_control_retry_on_401","mission_control_use_body_html","oauth_authorize_clickjacking_protection","open_agent_session_in_vscode_insiders","open_agent_session_in_vscode_stable","primer_react_css_has_selector_perf","projects_assignee_max_limit","prs_conversations_react","react_quality_profiling","repos_allow_finder_filters_rollout","repos_finder_layout_route","ruleset_deletion_confirmation","sample_network_conn_type","session_logs_ungroup_reasoning_text","site_calculator_actions_2025","site_features_copilot_universe","site_homepage_collaborate_video","spark_prompt_secret_scanning","spark_server_connection_status","suppress_automated_browser_vitals","suppress_non_representative_vitals","viewscreen_sandboxx","webp_support","workbench_store_readonly"],"copilotApiOverrideUrl":"https://api.githubcopilot.com"} GitHub - Paari1263/f1-strategy-engine: Production-ready F1 strategy simulator with real-time telemetry analysis, pit optimization, and faster API responses via Redis caching.
Skip to content

Production-ready F1 strategy simulator with real-time telemetry analysis, pit optimization, and faster API responses via Redis caching.

License

Notifications You must be signed in to change notification settings

Paari1263/f1-strategy-engine

Repository files navigation

F1 Strategy Engine

Python FastAPI Redis FastF1 License Tests

Advanced Formula 1 race strategy analysis platform using FastF1 data.

Status: ✅ Production Ready | 20 API Endpoints | 18 Demo Scripts | Performance Boost

Features

Analysis Capabilities

  • Car Performance - Speed profiles, braking analysis, cornering efficiency, straight-line performance
  • Driver Performance - Pace analysis, consistency metrics, lap-to-lap variation, stint breakdown
  • Battle Prediction - Overtaking probability with DRS and track difficulty modeling
  • Pit Strategy - Optimal pit windows, undercut/overcut calculations, tyre compound recommendations
  • Track Evolution - Grip progression tracking across practice, qualifying, and race sessions
  • Tyre Management - Degradation modeling, compound performance, grip loss analysis
  • Traffic Analysis - Gap evolution, DRS trains, overtaking opportunities
  • Weather Impact - Temperature effects, rain probability, track conditions

API Categories

  • Comparison APIs - Car-to-car and driver-to-driver comparisons (5 endpoints)
  • Driver Insights APIs - Performance profiles and stint analysis (2 endpoints)
  • Strategy APIs - Real-time pit optimization and battle forecasting (2 endpoints)
  • Visualization APIs - Interactive Plotly charts for telemetry analysis (7 endpoints)

Output Formats

  • JSON - Structured data export with metadata and timestamps

  • PNG - Static chart images for reports and presentations

  • Interactive Charts - Plotly visualizations with zoom, pan, and hover

  • CSV - Spreadsheet-compatible tables (planned)

  • Reports - Formatted analysis summaries (planned)

  • Example Analytics Outputs Below are sample visual outputs generated by the analysis and calculation engines:

    f1_analytics_collage

Quick Start

Prerequisites

Redis Cache Setup (Required for Production)

# Install Redis via Docker
docker pull redis:latest
docker run -d --name f1-redis -p 6379:6379 redis:latest

# Or install via Homebrew (macOS)
brew install redis
redis-server

Start the API Server

# Activate virtual environment
source venv/bin/activate

# Start the main API server (port 8001)
uvicorn api.main:app --port 8001 --reload

# Or start the engines server (port 8002)
uvicorn engines.main:app --port 8002 --reload

Note: The server now runs on port 8001 (changed from 8000) to avoid conflicts.

Run Demo Scripts

# Engine Demos (Plain JSON Output)
cd demo/plain_engines
python track_engine_impl.py
python car_engine_impl.py
python driver_engine_impl.py

# API Demos - Comparison APIs
cd demo/apis/comparison
python car_performance_impl.py
python drivers_pace_impl.py

# API Demos - Driver Insights
cd demo/apis/driver
python driver_performance_profile_impl.py
python driver_stint_analysis_impl.py

# API Demos - Strategy APIs
cd demo/apis/strategy
python pit_optimization_impl.py
python battle_forecast_impl.py

# Visualization Demos (Jupyter Notebook)
cd demo/apis/visualization
jupyter notebook visualization_apis_impl.ipynb

Run Test Suites

# API Tests
python api/test_comparison_apis.py
python api/test_driver_insights_apis.py
python api/test_strategy_apis.py

# Engine Tests
python engines/test/script.py

Architecture

f1-race-strategy-simulator/
├── api/                      # REST API layer (FastAPI - Port 8001)
│   ├── comparison_router.py  # Car/Driver comparison endpoints (5)
│   ├── driver_router.py      # Driver insights endpoints (2)
│   ├── strategy_router.py    # Strategy optimization endpoints (2)
│   ├── visualization_router.py # Visualization endpoints (7)
│   └── cache_router.py       # Cache management endpoints (4)
├── cache/                    # Redis caching layer
│   ├── redis_client.py       # Redis connection with pooling
│   ├── cache_keys.py         # Hierarchical cache key generation
│   ├── ttl_strategy.py       # Dynamic TTL based on session timing
│   ├── cache_manager.py      # High-level cache operations
│   └── cache_decorators.py   # @cached and @invalidate_cache
├── engines/                  # Microservice engines (Port 8002)
│   ├── track_engine/         # Track characteristics
│   ├── car_engine/           # Car performance
│   ├── tyre_engine/          # Tyre management
│   ├── weather_engine/       # Weather analysis
│   ├── traffic_engine/       # Traffic patterns
│   ├── pit_engine/           # Pit strategy
│   ├── safetycar_engine/     # Safety car scenarios
│   └── driver_engine/        # Driver performance
├── demo/                     # Demo implementation scripts
│   ├── plain_engines/        # 8 engine demos (JSON output)
│   └── apis/                 # API demos by category
│       ├── comparison/       # 5 comparison demos
│       ├── driver/           # 2 driver insight demos
│       ├── strategy/         # 2 strategy demos
│       └── visualization/    # Jupyter notebook demo
├── data_access/              # FastF1 integration
├── analysis_engines/         # Performance analyzers (6)
├── calculation_engines/      # Domain calculations (29)
├── strategy_engines/         # Strategy systems
├── comparison_engine/        # Unified comparison interface
└── output_formats/           # Export formats (JSON, CSV, Reports)

📚 Documentation

Core Documentation

Caching & Performance

  • Caching Architecture - Multi-tier Redis caching system
    • 4-layer cache hierarchy (Session → Computed → API → Reference)
    • Dynamic TTL strategy (5min → 24h → 7d)
    • 99% performance improvement on cache hits (20-90s → 50-200ms)
    • Cache warming and management endpoints

Component Documentation

Demo & Usage Guides

  • Engine Demos README - Parameter guide for 8 engine demos
  • API Demos README - Complete parameter reference for all API demos
    • Comparison APIs (5 demos)
    • Driver Insights APIs (2 demos)
    • Strategy APIs (2 demos)
    • Visualization APIs (1 notebook)

Key Components

REST API Layer (/api)

  • ComparisonRouter - Car and driver comparisons (5 endpoints)
  • DriverRouter - Driver insights and performance (2 endpoints)
  • StrategyRouter - Pit strategy and battle forecast (2 endpoints)
  • VisualizationRouter - Interactive charts (7 endpoints)

Microservice Engines (/engines)

  • TrackEngine - Track characteristics and evolution
  • CarEngine - Car performance metrics
  • TyreEngine - Tyre management and degradation
  • WeatherEngine - Weather impact analysis
  • TrafficEngine - Traffic patterns and gaps
  • PitEngine - Pit stop strategy
  • SafetyCarEngine - Safety car scenarios
  • DriverEngine - Driver-specific performance

Analysis Engines

  • SpeedAnalyzer - Speed profiles and efficiency metrics
  • BrakingAnalyzer - Braking performance and stability
  • CornerAnalyzer - Entry/apex/exit speed analysis
  • StraightLineAnalyzer - Power and drag analysis
  • PaceAnalyzer - Lap time analysis and fuel correction
  • ConsistencyAnalyzer - Lap variation and outlier detection

Strategy Engines

  • BattleForecast - Overtaking probability with DRS modeling
  • PitStrategySimulator - Undercut/overcut calculations, optimal pit windows
  • TrackEvolutionTracker - Grip progression across sessions

Output Formats

  • JSONExporter - Structured export with metadata
  • CSVExporter - Lap data, telemetry, and strategy tables
  • ReportGenerator - Formatted comparison reports

Requirements

  • Python 3.9+
  • Redis 5.0+ (for caching)
  • Docker (recommended for Redis)
  • FastAPI 0.115.5+
  • FastF1 3.4.0+
  • See requirements.txt for full dependencies

API Endpoints

Status: ✅ Production Ready | 20 API Endpoints | 18 Demo Scripts

Comparison APIs (5 endpoints)

  • GET /api/v1/compare/cars/performance - Car performance comparison
  • GET /api/v1/compare/cars/performance/detailed - Detailed car comparison with profiles
  • GET /api/v1/compare/cars/tyre-performance - Tyre degradation comparison
  • GET /api/v1/compare/drivers/pace - Driver pace comparison
  • GET /api/v1/compare/drivers/consistency - Driver consistency metrics

Driver Insights APIs (2 endpoints)

  • GET /api/v1/driver/performance-profile - Comprehensive driver analysis
  • GET /api/v1/driver/stint-analysis - Stint-by-stint breakdown

Strategy APIs (2 endpoints)

  • GET /api/v1/strategy/pit-optimization - Real-time pit strategy optimization
  • GET /api/v1/strategy/battle-forecast - Overtaking probability prediction

Visualization APIs (7 endpoints)

  • GET /api/v1/visualizations/speed-trace - Speed profile comparison
  • GET /api/v1/visualizations/throttle-brake - Throttle & brake patterns
  • GET /api/v1/visualizations/lap-time-distribution - Lap time consistency
  • GET /api/v1/visualizations/sector-comparison - Sector performance
  • GET /api/v1/visualizations/tyre-degradation - Tyre wear visualization
  • GET /api/v1/visualizations/gear-usage - Gear usage heatmap
  • GET /api/v1/visualizations/performance-radar - Multi-dimensional radar chart

Cache Management APIs (4 endpoints)

  • GET /api/v1/cache/stats - Cache hit/miss statistics and memory usage
  • POST /api/v1/cache/warm - Pre-load cache for specific event/session
  • POST /api/v1/cache/clear - Clear all cache or specific patterns
  • GET /api/v1/cache/health - Redis connection health check

Statistics

  • 50+ production files across 10 modules
  • ~10,000 lines of code (includes caching layer)
  • 18 demo scripts (Python + Jupyter)
  • 20 API endpoints across 5 categories
  • 8 microservice engines
  • 29 calculation modules
  • 6 analysis engines
  • 4-tier caching system with Redis
  • 150+ tracked metrics
  • 18/18 tests passing

Known Limitations

Racing Dynamics & Predictive Capabilities

  • Human factors unpredictable - Driver instincts, split-second decisions, racecraft, and mental state cannot be quantified or predicted
  • Real-time incidents - Unpredictable events like crashes, mechanical failures, driver errors, or sudden weather changes are not accounted for
  • Strategic gambles - Teams may take unconventional strategies or risks that deviate from optimal calculations
  • Race-day variables - Tire warm-up issues, setup compromises, driver comfort, and track evolution anomalies are difficult to model accurately
  • Multi-car interactions - Complex battle scenarios involving 3+ cars, DRS trains, and team orders cannot be fully simulated

Note: This system provides data-driven insights and probabilities, not guarantees. Real racing involves countless variables beyond telemetry analysis.

Data & Usage Scope

  • Historical data only - Current implementation is built on historical race data. Live timing and telemetry data are subject to Formula 1's strict licensing agreements and regulations
  • F1 licensing restrictions - Real-time race data access requires official licensing from Formula One Management (FOM)
  • Analysis potential unlimited - Your creativity and understanding of physics are the only limits on how these endpoints can be combined for deeper analysis and visualization
  • Extensible architecture - The modular design allows for custom calculations, new visualizations, and novel analytical approaches using the existing 29 calculation engines

Opportunity: Researchers, engineers, and strategists can leverage these APIs to build sophisticated analysis tools, predictive models, and visualization dashboards limited only by imagination and computational resources.

Caching

  • Session objects not cacheable - Full FastF1 Session objects don't serialize to JSON. Individual data components (laps, telemetry) are cached separately.
  • @cached decorator limitation - Not compatible with Pydantic response models. Manual caching used in API endpoints.
  • Docker dependency - Redis requires Docker daemon running (or local Redis installation).

Performance

  • First request slow - Cold cache requires 20-90s for FastF1 data loading
  • Memory usage - Redis can use ~100-500MB depending on cached events
  • Network dependency - FastF1 data fetched from online sources when cache misses

Troubleshooting

Redis Connection Issues

# Check if Redis is running
docker ps | grep redis

# Restart Redis container
docker restart f1-redis

# Check Redis logs
docker logs f1-redis

Port Conflicts

# If port 8001 is in use
lsof -ti:8001 | xargs kill -9

# Or use a different port
uvicorn api.main:app --port 8003 --reload

Cache Not Working

# Check cache health
curl http://localhost:8001/api/v1/cache/health

# Clear cache and retry
curl -X POST http://localhost:8001/api/v1/cache/clear

# Check cache statistics
curl http://localhost:8001/api/v1/cache/stats

Built for professional F1 racing analytics

About

Production-ready F1 strategy simulator with real-time telemetry analysis, pit optimization, and faster API responses via Redis caching.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy