### Use Fast-F1 SignalR Client Source: https://docs.fastf1.dev/gen_modules/examples_gallery/example_fastf1_signalrclient.html Demonstrates how to initialize and start the SignalRClient from the Fast-F1 library. This client is used for live timing data. It requires the 'fastf1' library to be installed. The output is logged to a specified file and debug messages are enabled. ```python import logging from fastf1.livetiming.client import SignalRClient log = logging.getLogger() log.setLevel(logging.DEBUG) client = SignalRClient(filename="output.txt", debug=True) client.start() ``` -------------------------------- ### Accessing Session Start Time Source: https://docs.fastf1.dev/time_explanation.html Demonstrates how to retrieve the session start time as a string representation of SessionTime. This is a basic example of accessing session data. ```python str(session.session_start_time) ``` -------------------------------- ### Initialize Session and Retrieve Driver Data Source: https://docs.fastf1.dev/_sources/examples/index.rst.txt Demonstrates how to load a specific Formula 1 session using FastF1 and access individual driver information. This snippet shows the basic setup required to interact with session data. ```python import fastf1 session = fastf1.get_session(2019, 'Monza', 'Q') session.load(telemetry=False, laps=False, weather=False) vettel = session.get_driver('VET') print(f"Pronto {vettel['FirstName']}?") ``` -------------------------------- ### Python Logging Setup and Usage in FastF1 Source: https://docs.fastf1.dev/contributing/contributing.html Demonstrates how to set up and use the FastF1 logging system, which is based on Python's standard logging library. It shows how to get a logger for a module and emit messages at different levels (info, debug). ```python from fastf1.logger import get_logger # set up the logger once (!) logger = get_logger(__name__) # code logger.info('Here is some information') logger.debug('Here is some more detailed information') # more code ``` -------------------------------- ### Access and Inspect Session Laps (Python) Source: https://docs.fastf1.dev/getting_started/basics.html Demonstrates how to load a session and access its laps, which are provided as a pandas DataFrame. It also shows how to view the available columns within the laps data. ```python >>> session = fastf1.get_session(2021, 'French Grand Prix', 'Q') >>> session.load() >>> session.laps Time Driver ... FastF1Generated IsAccurate 0 0 days 00:17:35.479000 GAS ... False False 1 0 days 00:27:42.702000 GAS ... False False 2 0 days 00:30:15.038000 GAS ... False False 3 0 days 00:31:46.936000 GAS ... False True 4 0 days 00:34:20.695000 GAS ... False False .. ... ... ... ... ... 265 0 days 00:54:22.881000 GIO ... False True 266 0 days 01:00:32.369000 GIO ... False False 267 0 days 01:03:24.940000 GIO ... False False 268 0 days 01:04:56.753000 GIO ... False True 269 0 days 01:06:42.885000 GIO ... False False [270 rows x 31 columns] >>> session.laps.columns Index(['Time', 'Driver', 'DriverNumber', 'LapTime', 'LapNumber', 'Stint', 'PitOutTime', 'PitInTime', 'Sector1Time', 'Sector2Time', 'Sector3Time', 'Sector1SessionTime', 'Sector2SessionTime', 'Sector3SessionTime', 'SpeedI1', 'SpeedI2', 'SpeedFL', 'SpeedST', 'IsPersonalBest', 'Compound', 'TyreLife', 'FreshTyre', 'Team', 'LapStartTime', 'LapStartDate', 'TrackStatus', 'Position', 'Deleted', 'DeletedReason', 'FastF1Generated', 'IsAccurate'], dtype='object') ``` -------------------------------- ### Loading F1 Events and Sessions by Name or Location Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Demonstrates how to retrieve event or session objects using fuzzy string matching for names or specific geographic locations. Note that fuzzy matching is not always precise and should be verified. ```python import fastf1 # Load event by name event = fastf1.get_event(2021, 'French Grand Prix') # Fuzzy search by partial name event = fastf1.get_event(2021, 'Spain') # Load session by location and session type session = fastf1.get_session(2021, 'Silverstone', 'Q') ``` -------------------------------- ### Retrieving and Filtering Season Event Schedules Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Shows how to load a full season schedule as a pandas DataFrame and filter it to find specific events by round number or name. ```python import fastf1 # Get full schedule for a season schedule = fastf1.get_event_schedule(2021) # Filter by round number gp_12 = schedule.get_event_by_round(12) # Filter by name gp_austin = schedule.get_event_by_name('Austin') ``` -------------------------------- ### Load F1 Events and Sessions by Name or Location Source: https://docs.fastf1.dev/getting_started/basics.html Demonstrates how to fetch event or session objects using fuzzy string matching for names or locations. Note that search results should be verified as the matching algorithm is not a full-featured search engine. ```python import fastf1 # Load by event name event = fastf1.get_event(2021, 'French Grand Prix') # Load by partial name event = fastf1.get_event(2021, 'Spain') # Load by specific location and session type session = fastf1.get_session(2021, 'Silverstone', 'Q') ``` -------------------------------- ### Accessing Session Start Time Source: https://docs.fastf1.dev/data_reference/time_explanation.html Demonstrates how to access and display the session start time as a string. This is a basic utility for understanding session timing. ```python >>> str(session.session_start_time) '0:33:28.079000' ``` -------------------------------- ### Start FastF1 Live Timing Client Stream Source: https://docs.fastf1.dev/livetiming.html The `start()` method of the `SignalRClient` class connects to the data stream and begins writing received data to the configured output file. An asynchronous version, `async_start()`, is available for use within an existing event loop, though `start()` is generally recommended for most use cases. ```python client = SignalRClient(filename='timing_data.txt') # Synchronous start client.start() # Asynchronous start (within an event loop) # import asyncio # async def run_client(): # await client.async_start() # asyncio.run(run_client()) ``` -------------------------------- ### Select Fastest Lap (Python) Source: https://docs.fastf1.dev/getting_started/basics.html Illustrates how to use the `pick_fastest()` method on the `Laps` object to easily find the fastest lap of a session and retrieve its details, such as lap time and driver. ```python >>> fastest_lap = session.laps.pick_fastest() >>> fastest_lap['LapTime'] Timedelta('0 days 00:01:29.990000') >>> fastest_lap['Driver'] 'VER' ``` -------------------------------- ### Retrieve and Query F1 Event Schedules Source: https://docs.fastf1.dev/getting_started/basics.html Shows how to load a full season schedule as a pandas DataFrame and use built-in helper methods to filter by round number or event name. ```python import fastf1 # Load full schedule schedule = fastf1.get_event_schedule(2021) # Filter by round or name gp_12 = schedule.get_event_by_round(12) gp_austin = schedule.get_event_by_name('Austin') ``` -------------------------------- ### Load Formula 1 Session and Event Data with FastF1 Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Demonstrates how to initialize a specific race session using fastf1.get_session and how to access associated event metadata. The event object behaves like a pandas Series, allowing for standard index-based data retrieval. ```python import fastf1 # Load a specific session (e.g., Qualifying, 2021, Round 7) session = fastf1.get_session(2021, 7, 'Q') print(session.name) print(session.date) # Access event information from the session print(session.event) # Access specific event attributes using pandas Series indexing event_name = session.event['EventName'] # Load an event directly event = fastf1.get_event(2021, 7) ``` -------------------------------- ### Setup Matplotlib for FastF1 Plotting Source: https://docs.fastf1.dev/_sources/gen_modules/examples_gallery/plot_driver_styling.rst.txt Initializes Matplotlib for FastF1 plotting, enabling support for timedelta values and applying the 'fastf1' dark color scheme. This is a prerequisite for most FastF1 plotting functions. ```Python from matplotlib import pyplot as plt import fastf1 from fastf1 import plotting # Enable Matplotlib patches for plotting timedelta values and load # FastF1's dark color scheme fastf1.plotting.setup_mpl(mpl_timedelta_support=True, color_scheme='fastf1') ``` -------------------------------- ### Initialize and Start Fast-F1 SignalRClient (Python) Source: https://docs.fastf1.dev/_downloads/1dfee3a290b9b94a083593b6e84f28ed/example_fastf1_signalrclient.ipynb This code snippet demonstrates how to initialize and start the SignalRClient from the Fast-F1 library. It sets up basic logging to capture debug information and specifies an output file for the live timing data. The client is then started to begin receiving data. ```python import logging from fastf1.livetiming.client import SignalRClient log = logging.getLogger() log.setLevel(logging.DEBUG) client = SignalRClient(filename="output.txt", debug=True) client.start() ``` -------------------------------- ### Access Session Time References Source: https://docs.fastf1.dev/_sources/time_explanation.rst.txt Retrieves the session start date and the session start time offset. These values are essential for synchronizing session data with absolute time. ```python >>> session.t0_date Timestamp('2020-09-06 12:40:00.196000') >>> session.session_start_time datetime.timedelta(seconds=2008, microseconds=79000) >>> str(session.session_start_time) '0:33:28.079000' ``` -------------------------------- ### GET /api/drivers Source: https://docs.fastf1.dev/api_reference/api_autogen/fastf1.ergast.Ergast.html Retrieve a list of drivers with their basic information. ```APIDOC ## GET /api/drivers ### Description Retrieve a list of drivers with their basic information. ### Method GET ### Endpoint /api/drivers ### Parameters #### Query Parameters - **season** (Union[`Literal`[`'current'`], `int`, `None`]) - Optional - Select a season by its year (default: all, oldest first). - **round** (Union[`Literal`[`'last'`], `int`, `None`]) - Optional - Select a round by its number (default: all). - **circuit** (str | `None`) - Optional - Select a circuit by its circuit id (default: all). - **constructor** (str | `None`) - Optional - Select a constructor by its constructor id (default: all). - **driver** (str | `None`) - Optional - Select a driver by its driver id (default: all). - **grid_position** (`int` | `None`) - Optional - Select a grid position by its number (default: all). - **results_position** (`int` | `None`) - Optional - Select a finishing result by its position (default: all). - **fastest_rank** (`int` | `None`) - Optional - Select fastest by rank number (default: all). - **status** (str | `None`) - Optional - Select by finishing status (default: all). - **result_type** (Optional[`Literal`[`'pandas'`, `'raw'`]]) - Optional - Overwrites the default result type. - **auto_cast** (`bool` | `None`) - Optional - Overwrites the default value for `auto_cast`. - **limit** (`int` | `None`) - Optional - Overwrites the default value for `limit`. - **offset** (`int` | `None`) - Optional - An offset into the result set for response paging. Defaults to 0 if not set. ### Response #### Success Response (200) - **driverId** (str) - The unique ID of the driver. - **permanentNumber** (int) - The permanent racing number of the driver. - **code** (str) - The three-letter code for the driver. - **url** (str) - URL to the driver's Wikipedia page. - **givenName** (str) - The first name of the driver. - **familyName** (str) - The last name of the driver. - **dateOfBirth** (datetime.datetime | None) - The date of birth of the driver. - **nationality** (str) - The nationality of the driver. #### Response Example { "example": "[\n {\n \"driverId\": \"hamilton\",\n \"permanentNumber\": 44,\n \"code\": \"HAM\",\n \"url\": \"http://en.wikipedia.org/wiki/Lewis_Hamilton\",\n \"givenName\": \"Lewis\",\n \"familyName\": \"Hamilton\",\n \"dateOfBirth\": \"1985-01-07\",\n \"nationality\": \"British\"\n }\n]" } ``` -------------------------------- ### Manage Client Lifecycle Source: https://docs.fastf1.dev/_modules/fastf1/livetiming/client.html Provides the main entry point for starting the client and handling clean shutdowns via KeyboardInterrupt. ```python def start(self): self.logger.info(f"Starting FastF1 live timing client [v{fastf1.__version__}]") self._run() try: self._supervise() except KeyboardInterrupt: self.logger.info("Exiting...") self._exit() ``` -------------------------------- ### Configure and Enable FastF1 Cache Source: https://docs.fastf1.dev/fastf1.html Demonstrates how to initialize the FastF1 session and enable the cache directory. The cache directory must exist before calling the enable method. ```python import fastf1 from fastf1 import Cache # Enable cache in a specific directory Cache.enable_cache('/path/to/empty/directory') # Initialize session session = fastf1.get_session(2021, 5, 'Q') ``` -------------------------------- ### POST /SignalRClient/start Source: https://docs.fastf1.dev/api_reference/api_autogen/fastf1.livetiming.client.SignalRClient.html Initializes the SignalR client connection and begins streaming live F1 data to a specified local file. ```APIDOC ## POST SignalRClient.start() ### Description Connects to the F1 live timing data stream via SignalR and begins writing the incoming data to the file specified during class initialization. ### Method POST ### Endpoint SignalRClient.start() ### Parameters #### Request Body - **filename** (str) - Required - The path/filename where the raw stream data will be saved. - **filemode** (str) - Optional - 'w' for overwrite or 'a' for append mode. - **debug** (bool) - Optional - If true, saves the complete SignalR message structure. - **timeout** (int) - Optional - Seconds to wait for data before auto-exiting. - **no_auth** (bool) - Optional - Attempt connection without authentication. ### Request Example { "filename": "session_data.txt", "filemode": "w", "debug": false } ### Response #### Success Response (200) - **status** (string) - Indicates the stream has started successfully. #### Response Example { "status": "connected", "message": "Streaming data to session_data.txt" } ``` -------------------------------- ### Visualize Driver Telemetry with Matplotlib Source: https://docs.fastf1.dev/_sources/examples/index.rst.txt Shows how to load full session data, extract a specific driver's fastest lap telemetry, and plot speed over time using Matplotlib. It utilizes FastF1's plotting utilities to ensure consistent styling. ```python from matplotlib import pyplot as plt import fastf1 import fastf1.plotting fastf1.plotting.setup_mpl(color_scheme='fastf1') session = fastf1.get_session(2019, 'Monza', 'Q') session.load() fast_leclerc = session.laps.pick_drivers('LEC').pick_fastest() lec_car_data = fast_leclerc.get_car_data() t = lec_car_data['Time'] vCar = lec_car_data['Speed'] fig, ax = plt.subplots() ax.plot(t, vCar, label='Fast') ax.set_xlabel('Time') ax.set_ylabel('Speed [Km/h]') ax.set_title('Leclerc is') ax.legend() plt.show() ``` -------------------------------- ### Get Session Start Time Offset (Python) Source: https://docs.fastf1.dev/data_reference/time_explanation.html Retrieves the 'session_start_time' attribute from the session object. This attribute indicates the time difference between the session's official start and the zero point of SessionTime. ```python >>> session.session_start_time datetime.timedelta(seconds=2008, microseconds=79000) ``` -------------------------------- ### GET /session_status Source: https://docs.fastf1.dev/api.html Fetches session status data to track the start and end of sessions. ```APIDOC ## GET /session_status ### Description Fetches and parses session status data, indicating when a session starts and ends. ### Method GET ### Endpoint fastf1.api.session_status_data(path, response=None, livedata=None) ### Parameters #### Path Parameters - **path** (str) - Required - API path base string ### Response #### Success Response (200) - **Time** (datetime.timedelta) - Session timestamp - **Status** (str) - Status message ### Response Example { "Time": "0:00:00", "Status": "Started" } ``` -------------------------------- ### Get Seasons with Pagination (Python) Source: https://docs.fastf1.dev/api_reference/jolpica.html Demonstrates how to retrieve a limited list of seasons using the Ergast API and then utilize pagination features to check for completeness, get the total number of results, and fetch the next page of results. This example assumes the 'ergast' object is already initialized. ```python >>> seasons = ergast.get_seasons(limit=3) >>> seasons season seasonUrl 0 1950 https://en.wikipedia.org/wiki/1950_Formula_One... 1 1951 https://en.wikipedia.org/wiki/1951_Formula_One... 2 1952 https://en.wikipedia.org/wiki/1952_Formula_One... >>> seasons.is_complete False >>> seasons.total_results 74 >>> seasons.get_next_result_page() season seasonUrl 0 1953 https://en.wikipedia.org/wiki/1953_Formula_One... 1 1954 https://en.wikipedia.org/wiki/1954_Formula_One... 2 1955 https://en.wikipedia.org/wiki/1955_Formula_One... ``` -------------------------------- ### Get FastF1 and Python Versions Source: https://docs.fastf1.dev/contributing/contributing.html This snippet shows how to retrieve the installed FastF1 version and the Python version using the respective libraries. This is useful for bug reporting to provide context. ```python >>> import fastf1 >>> fastf1.__version__ '2.2.1' >>> import platform >>> platform.python_version() '3.9.2' ``` -------------------------------- ### Initialize and Start SignalR Connection Source: https://docs.fastf1.dev/_modules/fastf1/livetiming/client.html Configures the SignalR connection using the HubConnectionBuilder, performs header negotiation for authentication, and establishes the data stream subscription. ```python def _run(self): self._output_file = open(self.filename, self.filemode) r = requests.options(self._negotiate_url, headers=self.headers) self.headers.update({"Cookie": f"AWSALBCORS={r.cookies['AWSALBCORS']}"}) options = { "verify_ssl": True, "access_token_factory": None if self._no_auth else get_auth_token, "headers": self.headers } self._connection = HubConnectionBuilder() \ .with_url(self._connection_url, options=options) \ .configure_logging(logging.INFO) \ .build() self._connection.on_open(self._on_connect) self._connection.on_close(self._on_close) self._connection.on('feed', self._on_message) self._connection.start() while not self._is_connected: time.sleep(0.1) self._connection.send("Subscribe", [self.topics], on_invocation=self._on_message) ``` -------------------------------- ### Instantiate and Load Session Data - Python Source: https://docs.fastf1.dev/core.html Demonstrates how to instantiate a Session object and load various types of session data. This is crucial as most attributes are only populated after calling `load()`. ```python import fastf1 # Enable the cache or set a cache folder fastf1.Cache.enable_cache('/path/to/cache') # Get a session object for a specific event and session session = fastf1.get_session(2023, 'Monaco', 'R') # Load session data (laps, telemetry, weather, etc.) session.load(laps=True, telemetry=True, weather=True) # Now you can access session attributes like session.laps, session.telemetry, etc. ``` -------------------------------- ### Record and Load Live Timing Data Source: https://docs.fastf1.dev/livetiming.html Demonstrates how to record live timing data from the command line and subsequently load that data into a FastF1 session within a Python script. ```bash python -m fastf1.livetiming save saved_data.txt ``` ```python import fastf1 from fastf1.livetiming.data import LiveTimingData livedata = LiveTimingData('saved_data.txt') session = fastf1.get_testing_session(2021, 1, 1) session.load(livedata=livedata) ``` -------------------------------- ### Inspect Session Results Columns - Python Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Displays the available columns within the session results DataFrame. This helps in understanding the type of data that can be extracted, such as driver information, lap times, and points. ```python import fastf1 session = fastf1.get_session(2021, 'French Grand Prix', 'Q') session.load() print(session.results.columns) ``` -------------------------------- ### Load Session Data and Access Results - Python Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Loads a Formula 1 session and accesses the results, which are provided as a pandas DataFrame. This allows for easy inspection of driver performance and session outcomes. ```python import fastf1 session = fastf1.get_session(2021, 'French Grand Prix', 'Q') session.load() print(session.results) ``` -------------------------------- ### Example Usage of Weather Data Retrieval Source: https://docs.fastf1.dev/_modules/fastf1/core.html Demonstrates how to load a session and fetch weather data for the fastest lap using the FastF1 API. ```python session = fastf1.get_session(2019, 'Monza', 'Q') session.load(telemetry=False) lap = session.laps.pick_fastest() lap.get_weather_data() ``` -------------------------------- ### Record and Load Live Timing Data Source: https://docs.fastf1.dev/api_reference/livetiming.html Demonstrates how to capture live F1 timing data to a file using the command line or Python script, and subsequently load that data into a FastF1 session for analysis. ```bash python -m fastf1.livetiming save saved_data.txt ``` ```python from fastf1.livetiming.client import SignalRClient client = SignalRClient(filename="saved_data.txt") client.start() ``` ```python import fastf1 from fastf1.livetiming.data import LiveTimingData # Load recorded data into a session livedata = LiveTimingData('saved_data.txt') session = fastf1.get_testing_session(2021, 1, 1) session.load(livedata=livedata) # Loading from multiple files livedata_multi = LiveTimingData('saved_data_1.txt', 'saved_data_2.txt') ``` -------------------------------- ### Get Driver Standings from Ergast Source: https://docs.fastf1.dev/_downloads/b3cffd299c94d9412d7f1a34f2cc20c5/plot_who_can_still_win_wdc.ipynb Fetches the current driver standings for a given season and round using the Ergast API. It returns the content of the standings, which includes driver names, teams, and current points. ```python def get_drivers_standings(): ergast = Ergast() standings = ergast.get_driver_standings(season=SEASON, round=ROUND) return standings.content[0] ``` -------------------------------- ### Instantiate Ergast with Pandas and Auto-Casting Source: https://docs.fastf1.dev/ergast.html This example demonstrates how to instantiate the Ergast API client, configuring it to return results as Pandas DataFrames and automatically cast data types. This is a common setup for data analysis with FastF1. ```python from fastf1.ergast import Ergast ergast = Ergast(result_type='pandas', auto_cast=True) ``` -------------------------------- ### Initialize FastF1 Core Dependencies Source: https://docs.fastf1.dev/_modules/fastf1/core.html This snippet demonstrates the standard import block for the FastF1 core module. It includes essential type hinting, data handling libraries, and internal FastF1 submodules required for telemetry and circuit data processing. ```python import collections import re import warnings from collections.abc import ( Callable, Iterable ) from functools import cached_property from typing import ( Any, Literal, Optional, Union ) import numpy as np import pandas as pd import fastf1 from fastf1 import _api as api from fastf1 import ( ergast, exceptions ) from fastf1.internals.pandas_base import ( BaseDataFrame, BaseSeries ) from fastf1.livetiming.data import LiveTimingData from fastf1.logger import ( get_logger, soft_exceptions ) from fastf1.mvapi import ( CircuitInfo, get_circuit_info ) from fastf1.utils import to_timedelta ``` -------------------------------- ### Display Top Drivers and Q3 Times - Python Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Extracts and displays the abbreviations and Q3 lap times for the top ten drivers. The results are sorted by finishing position, making it straightforward to identify the fastest drivers. ```python import fastf1 session = fastf1.get_session(2021, 'French Grand Prix', 'Q') session.load() print(session.results.iloc[0:10].loc[:, ['Abbreviation', 'Q3']]) ``` -------------------------------- ### Manage Live Timing Cache Source: https://docs.fastf1.dev/livetiming.html Shows how to configure a custom cache directory for live timing data and how to force a cache refresh when input data files are modified. ```python fastf1.Cache.enable_cache('path/to/cache/directory') # Force refresh if input data changes fastf1.Cache.enable_cache('path/to/cache/directory', force_renew=True) ``` -------------------------------- ### Initialize Telemetry Object Source: https://docs.fastf1.dev/core.html Demonstrates how to instantiate a Telemetry object by passing session and driver information. This object acts as a container for time-series data including speed, RPM, and position coordinates. ```python from fastf1.core import Telemetry # Initialize telemetry for a specific driver in a session telemetry = Telemetry(session=session_obj, driver="44") ``` -------------------------------- ### Get and Convert Driver Abbreviations - Python Source: https://docs.fastf1.dev/_sources/gen_modules/examples_gallery/plot_strategy.rst.txt Retrieves a list of driver numbers from the session and then converts these numbers into their three-letter abbreviations. This is useful for labeling data and plots with driver names. It uses session.drivers and session.get_driver() for this conversion. ```Python drivers = session.drivers drivers = [session.get_driver(driver)[ "Abbreviation"] for driver in drivers] ``` -------------------------------- ### FastF1 CLI Commands Source: https://docs.fastf1.dev/api_reference/livetiming.html Overview of the command-line interface for saving live timing data or extracting messages from debug-mode recordings. ```bash # Save live timing data python -m fastf1.livetiming save output_file.json # Extract messages from debug-mode data python -m fastf1.livetiming extract input_debug.json output_data.json ``` -------------------------------- ### Setup Matplotlib for Fast-F1 Plotting Source: https://docs.fastf1.dev/_modules/fastf1/plotting/_plotting.html Configures matplotlib for use with Fast-F1, optionally enabling timedelta support and applying the Fast-F1 color scheme. Requires 'matplotlib' and optionally 'timple' to be installed. Handles backward compatibility for deprecated arguments. ```python import warnings try: from matplotlib import cycler from matplotlib import pyplot as plt except ImportError: warnings.warn("Failed to import optional dependency 'matplotlib'!" "Plotting functionality will be unavailable!", RuntimeWarning) try: import timple except ImportError: warnings.warn("Failed to import optional dependency 'timple'!" "Plotting of timedelta values will be restricted!", RuntimeWarning) from fastf1.logger import get_logger _logger = get_logger(__package__) _COLOR_PALETTE: list[str] = ['#FF79C6', '#50FA7B', '#8BE9FD', '#BD93F9', '#FFB86C', '#FF5555', '#F1FA8C'] # The default color palette for matplotlib plot lines in fastf1's color scheme [docs] def setup_mpl( mpl_timedelta_support: bool = True, color_scheme: str | None = None, *args, **kwargs # for backwards compatibility, do not use in new code ): """Setup matplotlib for use with fastf1. This is optional but, at least partly, highly recommended. Parameters: mpl_timedelta_support (bool): Matplotlib itself offers very limited functionality for plotting timedelta values. (Lap times, sector times and other kinds of time spans are represented as timedelta.) Enabling this option will patch some internal matplotlib functions and register converters, formatters and locators for tick formatting. The heavy lifting for this is done by an external package called 'Timple'. See https://github.com/theOehrly/Timple if you wish to customize the tick formatting for timedelta. color_scheme (str, None): This enables the Fast-F1 color scheme that you can see in all example images. Valid color scheme names are: ['fastf1', None] """ if args or 'misc_mpl_mods' in kwargs: warnings.warn( "The `misc_mpl_mods` argument was dropped from `.setup_mpl()` in " "version 3.6.0 and has no effect anymore. It will be removed in a " "future version of FastF1.", FutureWarning ) if mpl_timedelta_support: _enable_timple() if color_scheme == 'fastf1': _enable_fastf1_color_scheme() def _enable_timple(): # use external package timple to patch matplotlib # this adds converters, locators and formatters for # plotting timedelta values tick_formats = [ "%d %day", "%H:00", "%H:%m", "%M:%s.0", "%M:%s.%ms" ] tmpl = timple.Timple(converter='concise', formatter_args={'show_offset_zero': False, 'formats': tick_formats}) tmpl.enable() def _enable_fastf1_color_scheme(): plt.rcParams['figure.facecolor'] = '#292625' plt.rcParams['axes.edgecolor'] = '#2d2928' plt.rcParams['xtick.color'] = '#f1f2f3' plt.rcParams['ytick.color'] = '#f1f2f3' plt.rcParams['axes.labelcolor'] = '#F1f2f3' plt.rcParams['axes.facecolor'] = '#1e1c1b' # plt.rcParams['axes.facecolor'] = '#292625' plt.rcParams['axes.titlesize'] = 'x-large' # plt.rcParams['font.family'] = 'Gravity' plt.rcParams['font.weight'] = 'medium' plt.rcParams['text.color'] = '#F1F1F3' plt.rcParams['axes.titlesize'] = '19' plt.rcParams['axes.titlepad'] = '12' plt.rcParams['axes.titleweight'] = 'light' plt.rcParams['axes.prop_cycle'] = cycler('color', _COLOR_PALETTE) plt.rcParams['legend.fancybox'] = False plt.rcParams['legend.facecolor'] = (0.1, 0.1, 0.1, 0.7) plt.rcParams['legend.edgecolor'] = (0.1, 0.1, 0.1, 0.9) plt.rcParams['savefig.transparent'] = False plt.rcParams['axes.axisbelow'] = True ``` -------------------------------- ### Setup and Load F1 Session Data Source: https://docs.fastf1.dev/gen_modules/examples_gallery/lap_times/plot_laptimes_distribution.html Initializes the FastF1 plotting environment and loads a specific race session. This is the prerequisite step for all subsequent data analysis and visualization tasks. ```python import seaborn as sns from matplotlib import pyplot as plt import fastf1 import fastf1.plotting # Enable Matplotlib patches for plotting timedelta values and load # FastF1's dark color scheme fastf1.plotting.setup_mpl(mpl_timedelta_support=True, color_scheme='fastf1') # Load the race session race = fastf1.get_session(2023, "Azerbaijan", 'R') race.load() ``` -------------------------------- ### Load Session Data and Access Laps - Python Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Loads a Formula 1 session and accesses the individual lap data, which is also provided as a pandas DataFrame. This enables detailed analysis of lap performance throughout the session. ```python import fastf1 session = fastf1.get_session(2021, 'French Grand Prix', 'Q') session.load() print(session.laps) ``` -------------------------------- ### LiveTimingData Class Methods Source: https://docs.fastf1.dev/api_reference/api_autogen/fastf1.livetiming.data.LiveTimingData.html Provides examples of using the core methods of the LiveTimingData class: `load` to parse data, `get` to retrieve category data, `has` to check for category existence, and `list_categories` to see all available data categories. ```python # Load data (usually called automatically) livedata.load() # Get data for a specific category telemetry_data = livedata.get('timing-app-data') # Check if a category exists if livedata.has('timing-app-data'): print('Timing app data is available.') # List all available categories all_categories = livedata.list_categories() print(all_categories) ``` -------------------------------- ### Initialize and Load Session Data in Python Source: https://docs.fastf1.dev/api_reference/session.html Demonstrates how to instantiate a Session object for a specific event and session name, followed by the required load() method to fetch data from the F1 API. ```python import fastf1 # Initialize the session for the 2023 British Grand Prix Race session = fastf1.get_session(2023, 'British Grand Prix', 'R') # Load the session data (laps, telemetry, etc.) session.load() # Access session attributes print(f"Session Name: {session.name}") print(f"Drivers: {session.drivers}") ``` -------------------------------- ### Inspect Session Results Columns - FastF1 Source: https://docs.fastf1.dev/getting_started/basics.html Displays the column names available in the session results DataFrame. This allows you to understand the structure of the data and identify which information can be extracted, such as driver details, team information, and lap times. ```python >>> session.results.columns ``` -------------------------------- ### Inspect Session Laps Columns - Python Source: https://docs.fastf1.dev/_sources/examples/basics.rst.txt Lists all available data columns for individual laps within a session. This includes timing information, driver details, tyre data, and track status, facilitating in-depth lap analysis. ```python import fastf1 session = fastf1.get_session(2021, 'French Grand Prix', 'Q') session.load() print(session.laps.columns) ``` -------------------------------- ### Retrieve and Join Weather Data with FastF1 Source: https://docs.fastf1.dev/core.html Demonstrates how to load a Formula 1 session, extract weather data mapped to specific laps, and prepare the resulting DataFrames for merging using pandas. ```python import fastf1 import pandas as pd # Load session data session = fastf1.get_session(2019, 'Monza', 'Q') session.load(telemetry=False) # Retrieve weather data for laps weather_data = session.laps.get_weather_data() print(weather_data) # Prepare data for joining laps = session.laps.reset_index(drop=True) weather_data = weather_data.reset_index(drop=True) ``` -------------------------------- ### Initialize Class with Arguments Source: https://docs.fastf1.dev/_modules/fastf1/_api.html This Python snippet shows the constructor for a class, initializing it with arguments and calling the parent class's constructor. It's a standard pattern for class inheritance in Python. ```python def __init__(self, *args): super().__init__(*args) ```