### Install LiveF1 from Source Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/installation.md After cloning the repository, navigate to the project directory and install dependencies and the package itself. ```bash cd LiveF1 ``` ```bash pip install -r requirements.txt ``` ```bash pip install . ``` -------------------------------- ### Complete Real-Time Client Example Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/realtime_data.md A comprehensive example demonstrating the initialization of RealF1Client with multiple topics and a log file, along with defining and registering two distinct asynchronous handlers for telemetry and track status data. ```python from livef1.adapters.realtime_client import RealF1Client import datetime import json # Initialize client client = RealF1Client( topics=["CarData.z", "SessionInfo", "TrackStatus"], log_file_name="session_data.json" ) # Define multiple handlers @client.callback("process_telemetry") async def handle_telemetry(records): # Process car telemetry data telemetry_data = records.get("CarData.z") if telemetry_data: for record in telemetry_data: process_telemetry_data(record) # this is a placeholder for your code @client.callback("track_status") async def handle_track_status(records): # Monitor track conditions track_data = records.get("TrackStatus") if track_data: for record in track_data: update_track_status(record) # this is a placeholder for your code # Start the client client.run() ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/goktugocal/livef1/blob/main/README.md Install project dependencies required for development, including testing tools. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install LiveF1 via pip Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/installation.md Use this command to install the latest stable version of LiveF1 from PyPI. ```bash pip install livef1 ``` -------------------------------- ### Example Usage with Debug Logging Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/logging_config.md Demonstrates how to enable debug logging and use the logger within a client callback. This is useful for detailed troubleshooting. ```python from livef1.adapters.realtime_client import RealF1Client from livef1.utils.logger import logger, set_log_level import logging # Enable debug logging set_log_level('DEBUG') # Initialize client client = RealF1Client(topics=["CarData.z"]) @client.callback("logging_example") async def handle_data(records): logger.debug(f"Received {len(records)} records") logger.info("Processing new data batch") try: # Process records process_records(records) except Exception as e: logger.error(f"Error processing records: {e}") ``` -------------------------------- ### Run Real-Time Client Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/realtime_data.md Start the RealF1Client to begin receiving and processing real-time data. This call initiates the connection and data streaming. ```python client.run() # Starts the client and begins receiving data ``` -------------------------------- ### Get Meeting by Key Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Retrieve a meeting object using its unique meeting key. Ensure the 'livef1' library is imported. ```python >>> import livef1 as livef1 >>> meeting = livef1.get_meeting(season=2024, meeting_key=1242) >>> type(meeting) >>> meeting | | Season Year | Meeting Location | Session Type | Meeting Code | Meeting Key | Meeting Number | Meeting Offname | Meeting Name | Meeting Country Key | Meeting Country Code | Meeting Country Name | Meeting Circuit Key | Meeting Circuit Shortname | Session Key | Session Name | Session Startdate | Session Enddate | Gmtoffset | Path | |---:|--------------:|:-------------------|:---------------|:---------------|--------------:|-----------------:|:----------------------------------------|:-------------------|----------------------:|:-----------------------|:-----------------------|----------------------:|:----------------------------|--------------:|:---------------|:--------------------|:--------------------|:------------|:----------------------------------------------------------| ``` -------------------------------- ### Import Libraries for Race Analysis Source: https://github.com/goktugocal/livef1/blob/main/docs/source/examples/pipelines/race_analysis.md Imports necessary libraries for data manipulation, plotting, and the livef1 library. Ensure these are installed before running the pipeline. ```python import livef1 import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from datetime import timedelta ``` -------------------------------- ### Import LiveF1 Library Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Import the LiveF1 library into your Python script to start using its functionalities. ```python import livef1 as livef1 ``` -------------------------------- ### Add Custom Log Handler Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/logging_config.md Extend the default logging behavior by adding custom handlers. This example adds a stream handler with a custom format. ```python from livef1.utils.logger import logger import logging # Create custom handler custom_handler = logging.StreamHandler() custom_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s')) logger.addHandler(custom_handler) ``` -------------------------------- ### Clone LiveF1 Repository Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/installation.md Clone the official GitHub repository to get the latest development version or to contribute to the project. ```bash git clone https://github.com/goktugocal/LiveF1.git ``` -------------------------------- ### Analyze Average Lap Times by Driver Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md This example shows how to load session data, generate Silver tables, calculate average lap times per driver, and visualize the results using matplotlib. ```python import livef1 import pandas as pd import matplotlib.pyplot as plt # Get the session session = livef1.get_session( season=2024, meeting_identifier="Spa", session_identifier="Race" ) # Generate silver tables session.generate(silver=True) # Get lap times data df = session.laps # Calculate average lap times per driver avg_lap_times = df.groupby('DriverNo')['lap_time'].mean() # Visualize the results plt.figure(figsize=(12, 6)) avg_lap_times.plot(kind='bar') plt.title('Average Lap Times by Driver') plt.xlabel('Driver Number') plt.ylabel('Average Lap Time (seconds)') plt.grid(True) plt.tight_layout() plt.show() ``` -------------------------------- ### Get Meeting by Identifier Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Retrieve a meeting object using its location name. Ensure the 'livef1' library is imported. ```python >>> import livef1 as livef1 >>> meeting = livef1.get_meeting(season=2024, meeting_identifier="Spa") >>> type(meeting) >>> meeting | | Season Year | Meeting Location | Session Type | Meeting Code | Meeting Key | Meeting Number | Meeting Offname | Meeting Name | Meeting Country Key | Meeting Country Code | Meeting Country Name | Meeting Circuit Key | Meeting Circuit Shortname | Session Key | Session Name | Session Startdate | Session Enddate | Gmtoffset | Path | |---:|--------------:|:-------------------|:---------------|:---------------|--------------:|-----------------:|:----------------------------------------|:-------------------|----------------------:|:-----------------------|:-----------------------|----------------------:|:----------------------------|--------------:|:---------------|:--------------------|:--------------------|:------------|:----------------------------------------------------------| | 0 | 2024 | Spa-Francorchamps | Practice 1 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9567 | Practice 1 | 2024-07-26 13:30:00 | 2024-07-26 14:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_1/ | | 1 | 2024 | Spa-Francorchamps | Practice 2 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9568 | Practice 2 | 2024-07-26 17:00:00 | 2024-07-26 18:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_2/ | | 2 | 2024 | Spa-Francorchamps | Practice 3 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9569 | Practice 3 | 2024-07-27 12:30:00 | 2024-07-27 13:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Practice_3/ | | 3 | 2024 | Spa-Francorchamps | Qualifying | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9570 | Qualifying | 2024-07-27 16:00:00 | 2024-07-27 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Qualifying/ | | 4 | 2024 | Spa-Francorchamps | Race | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9574 | Race | 2024-07-28 15:00:00 | 2024-07-28 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-28_Race/ | ``` -------------------------------- ### Get Session Data and Process Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_models.md Retrieve data for a specific F1 session (Practice, Qualifying, Race). Load raw data, generate processed tables, and access lap or telemetry data. ```python # Get specific session session = livef1.get_session( season=2024, meeting_identifier="Monaco", session_identifier="Race" ) # Load raw data telemetry = session.get_data("CarData.z") # Generate processed tables session.generate(silver=True) # Access processed data laps = session.laps telemetry = session.carTelemetry ``` -------------------------------- ### Get Meeting by Identifier Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Retrieve a meeting object using its season year and a unique meeting key. This is useful when you know the specific key for the event you are interested in. ```python import livef1 as livef1 meeting = livef1.get_meeting( season=2024, meeting_key=1242 ) print(meeting) ``` -------------------------------- ### Fetch Single Topic Data - Position Source: https://context7.com/goktugocal/livef1/llms.txt Fetches a single topic, 'Position.z', and returns it as a pandas DataFrame. Use this to get specific data points like driver positions. ```python position_df = session.get_data("Position.z") print(position_df.head()) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Change your current directory to the cloned LiveF1 project folder. ```bash cd LiveF1 ``` -------------------------------- ### Initialize Real-Time Client Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/realtime_data.md Instantiate the RealF1Client to connect to the active F1 session and stream data. Optionally, specify a log file to record incoming data. ```python from livef1.adapters.realtime_client import RealF1Client client = RealF1Client( topics=["CarData.z", "SessionInfo"], log_file_name="./output.json" # Optional: log incoming data ) ``` -------------------------------- ### Generate Silver and Gold Layer Tables Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/medallion_architecture.md Demonstrates creating a silver layer table 'SectorDiff' sourced from a default silver table 'laps', and a gold layer table 'SectorLeaders' sourced from 'SectorDiff'. The 'session.generate(silver=True, gold=True)' command triggers the generation of both layers. ```python import livef1 session = livef1.get_session( 2024, "Belgian", "Qualifying" ) @session.create_silver_table( table_name = "SectorDiff", source_tables = ["laps"], # This time we source from a default silver table to create a silver table. include_session = True ) def sector_diff(session, laps): df = laps.groupby("DriverNo")[["Sector1_Time","Sector2_Time","Sector3_Time"]].min().reset_index() df["sector1_diff"] = (df["Sector1_Time"] - df["Sector1_Time"].min()).dt.total_seconds() df["sector2_diff"] = (df["Sector2_Time"] - df["Sector2_Time"].min()).dt.total_seconds() df["sector3_diff"] = (df["Sector3_Time"] - df["Sector3_Time"].min()).dt.total_seconds() df["DriverName"] = df["DriverNo"].map(lambda x: session.drivers[x].FullName) return df @session.session.create_gold_table( table_name = "SectorLeaders", source_tables = ["SectorDiff"], # This time we source from a newly registered silver table to create a gold table. include_session = True ) def sector_diff(session, SectorDiff): return SectorDiff.iloc[SectorDiff[["sector1_diff","sector2_diff","sector3_diff"]].idxmin().values] # Generate all tables session.generate(silver=True, gold=True) # We should set gold as True. ``` -------------------------------- ### Initialize Session and Load Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_objects.md Initializes a Session object with Season and Meeting context, then retrieves topic names and loads specific data. Ensure Season and Meeting objects are valid. ```python from livef1.models.session import Session # Initialize a session session = Session(season=season_2023, meeting=meeting, name="Practice 1") # Get topic names topic_names = session.get_topic_names() # Load data for a specific topic data = session.load_data(dataName="Car_Data") ``` -------------------------------- ### Access Laps Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Access the generated Silver tables as attributes of the Session object. For example, the laps data can be accessed via session.laps. ```python laps_data = session.laps print(laps_data) ``` -------------------------------- ### Register Callback Decorator Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/realtime_data.md Demonstrates the syntax for registering a callback function using the @client.callback decorator. This associates a handler with a specific name. ```python @client.callback("handler_name") ``` -------------------------------- ### Get Season Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_models.md Retrieve all data for a specific Formula 1 season. Access aggregated meeting tables or individual Meeting objects. ```python import livef1 # Get a season season = livef1.get_season(2024) # Access meetings print(season.meetings_table) # View all meetings print(season.meetings) # Access Meeting objects # Get specific meeting monaco_gp = [m for m in season.meetings if m.location == "Monaco"][0] ``` -------------------------------- ### Session.get_data(dataNames, level, parallel, force) Source: https://context7.com/goktugocal/livef1/llms.txt Fetches raw data topics for a session from the F1 Live Timing archive. Data is cached after the first fetch. ```APIDOC ## Session.get_data(dataNames, level, parallel, force) ### Description Loads one or more data topics from the F1 Live Timing archive for the session. Data is cached in the Bronze layer after first fetch. Accepts single topic names or lists, with optional parallel loading. ### Parameters #### Path Parameters - **dataNames** (str or list) - Required - The name(s) of the data topic(s) to fetch. - **level** (str) - Optional - The data layer to fetch from (e.g., 'bronze', 'silver'). Defaults to 'bronze'. - **parallel** (bool) - Optional - Whether to fetch data in parallel. Defaults to False. - **force** (bool) - Optional - Whether to force a re-fetch even if data is cached. Defaults to False. ### Request Example ```python import livef1 session = livef1.get_session(2024, "Spa", "Race") # Fetch car data car_data = session.get_data(dataNames="Car_Data") # Fetch position and telemetry data in parallel telemetry_data = session.get_data(dataNames=["Position", "Telemetry"] , parallel=True) ``` ### Response #### Success Response (Data) - Returns the requested data in a format appropriate for the data topic (e.g., DataFrame, list of records). #### Response Example ```json { "example": "[Data for the requested topic(s)]" } ``` ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/goktugocal/livef1/blob/main/README.md Run tests using pytest and generate a coverage report, highlighting missing lines. ```bash pytest tests/ -v --cov=livef1 --cov-report=term-missing ``` -------------------------------- ### Get Driver Object by TLA Abbreviation Source: https://context7.com/goktugocal/livef1/llms.txt Retrieves a Driver object using their three-letter abbreviation (TLA). Useful for looking up drivers when only their abbreviation is known. ```python # By TLA abbreviation driver = session.get_driver("VER") print(driver.FullName) # Max Verstappen ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/goktugocal/livef1/blob/main/README.md Execute the project's test suite using pytest. Use the -v flag for verbose output. ```bash pytest tests/ -v ``` -------------------------------- ### Get Meeting by Key Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Retrieve a meeting object using its unique meeting key. This is an alternative method to fetch meeting data when the key is known. ```APIDOC ## Get Meeting by Key ### Description Retrieves a meeting object using its unique meeting key. ### Method Signature `livef1.get_meeting(season: int, meeting_key: int)` ### Parameters #### Path Parameters - **season** (int) - Required - The year of the season. - **meeting_key** (int) - Required - The unique key for the meeting. ### Request Example ```python import livef1 as livef1 meeting = livef1.get_meeting(season=2024, meeting_key=1242) print(meeting) ``` ### Response #### Success Response Returns a `livef1.models.meeting.Meeting` object containing meeting and session details. ``` -------------------------------- ### Get Meeting Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_models.md Retrieve data for a specific Grand Prix meeting within a season. Access session tables or individual Session objects. ```python # Get specific meeting meeting = livef1.get_meeting( season=2024, meeting_identifier="Monaco" ) # Access sessions print(meeting.sessions_table) # View all sessions # Get specific session race = [s for s in meeting.sessions if s.type == "Race"][0] ``` -------------------------------- ### Get Car Telemetry Data Source: https://context7.com/goktugocal/livef1/llms.txt Retrieves the Silver layer car telemetry DataFrame and prints its column names. Useful for inspecting available telemetry data. ```python # Get car telemetry telemetry = session.get_car_telemetry() if telemetry is not None: # Inspect columns print(telemetry.columns.tolist()) ``` -------------------------------- ### Initialize and Load Meeting Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_objects.md Initializes a Meeting object linked to a Season and loads its data. Requires a valid Season object and meeting details. ```python from livef1.models.meeting import Meeting # Initialize a meeting meeting = Meeting(season=season_2023, year=2023, location="Monaco") # Load the meeting data meeting.load() # Access the sessions sessions = meeting.sessions ``` -------------------------------- ### Get Laps Data with Filtering Source: https://context7.com/goktugocal/livef1/llms.txt Retrieves the Silver layer laps DataFrame and filters it for a specific driver's valid laps to find the fastest lap. ```python import livef1 import pandas as pd session = livef1.get_session(2024, "Spa", "Race") session.generate(silver=True) # Get laps data laps = session.get_laps() if laps is not None: # Filter valid laps with a recorded time for a specific driver driver_laps = laps[(laps["DriverNo"] == 16) & (laps["lap_time"].notna())] fastest = driver_laps.loc[driver_laps["lap_time"].idxmin()] print(f"Fastest lap: {fastest['lap_time']}, Lap {fastest['lap_number']}") ``` -------------------------------- ### Real-time Data Storage Handler Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/realtime_data.md This Python code snippet demonstrates a callback function for handling real-time data records. It extracts a timestamp, topic, and driver number from each record and inserts it into a database. Ensure the F1Database class and client callbacks are properly initialized. ```python db = F1Database() @client.callback("database_handler") async def handle_database_storage(records): for record in records: timestamp = datetime.now().isoformat() # Extract topic and driver number if available topic = next(iter(record.keys())) # Get the first key as topic driver_number = record.get(topic, {}).get('DriverNumber', 0) # Store in database db.insert_data( timestamp=timestamp, topic=topic, driver_number=driver_number, data=record ) ``` -------------------------------- ### Get Meeting by Identifier Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/index_old.md Retrieve a meeting object by its identifier, such as a location name. This function returns a Meeting object containing details about the specified meeting and its sessions. ```APIDOC ## Get Meeting by Identifier ### Description Retrieves a meeting object by its identifier (e.g., a location name). ### Method Signature `livef1.get_meeting(season: int, meeting_identifier: str)` ### Parameters #### Path Parameters - **season** (int) - Required - The year of the season. - **meeting_identifier** (str) - Required - The identifier for the meeting (e.g., "Spa"). ### Request Example ```python import livef1 as livef1 meeting = livef1.get_meeting(season=2024, meeting_identifier="Spa") print(meeting) ``` ### Response #### Success Response Returns a `livef1.models.meeting.Meeting` object containing meeting and session details. ``` -------------------------------- ### Get Meeting by Identifier Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Retrieve a meeting object and its sessions using a meeting identifier, such as a location name. The function returns a detailed table of the meeting's sessions. ```APIDOC ## Get Meeting by Identifier ### Description Retrieve a meeting object and its sessions using a meeting identifier, such as a location name. The function returns a detailed table of the meeting's sessions. ### Method Signature ```python livef1.get_meeting(season: int, meeting_identifier: str) ``` ### Parameters - **season** (int) - Required - The year of the season. - **meeting_identifier** (str) - Required - The identifier for the meeting (e.g., location name). ### Request Example ```python import livef1 as livef1 meeting = livef1.get_meeting( season=2024, meeting_identifier="Spa" ) print(meeting) ``` ### Response Example ```none | | Season Year | Meeting Location | Session Type | Meeting Code | Meeting Key | Meeting Number | Meeting Offname | Meeting Name | Meeting Country Key | Meeting Country Code | Meeting Country Name | Meeting Circuit Key | Meeting Circuit Shortname | Session Key | Session Name | Session Startdate | Session Enddate | Gmtoffset | Path | |---:|--------------:|:-------------------|:---------------|:---------------|--------------:|-----------------:|:----------------------------------------|:-------------------|----------------------:|:-----------------------|:-----------------------|----------------------:|:----------------------------|--------------:|:---------------|:--------------------|:--------------------|:------------|:----------------------------------------------------------| | 0 | 2024 | Spa-Francorchamps | Practice 1 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9567 | Practice 1 | 2024-07-26 13:30:00 | 2024-07-26 14:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_1/ | | 1 | 2024 | Spa-Francorchamps | Practice 2 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9568 | Practice 2 | 2024-07-26 17:00:00 | 2024-07-26 18:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_2/ | | 2 | 2024 | Spa-Francorchamps | Practice 3 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9569 | Practice 3 | 2024-07-27 12:30:00 | 2024-07-27 13:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Practice_3/ | | 3 | 2024 | Spa-Francorchamps | Qualifying | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9570 | Qualifying | 2024-07-27 16:00:00 | 2024-07-27 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Qualifying/ | | 4 | 2024 | Spa-Francorchamps | Race | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9574 | Race | 2024-07-28 15:00:00 | 2024-07-28 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-28_Race/ | ``` ``` -------------------------------- ### Generate Silver and Gold Tables Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/accessing_data.md Process raw data to create higher-level tables. Use 'silver=True' to generate silver tables and 'gold=True' to generate gold tables. ```python session.generate(silver=True, gold=False) # Generate silver tables only ``` ```python session.generate(silver=True, gold=True) # Generate both silver and gold tables (not implemented yet) ``` -------------------------------- ### Register Custom Silver Table Source: https://context7.com/goktugocal/livef1/llms.txt Demonstrates registering a custom function as a Silver table generator using the @session.create_silver_table decorator. The function must return a DataFrame and will be executed during session.generate(). ```python import livef1 session = livef1.get_session(2025, "British", "Qualifying") ``` -------------------------------- ### Get Meeting by Key Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Retrieve a meeting object and its sessions using the meeting's unique key. The function returns a detailed table of the meeting's sessions. ```APIDOC ## Get Meeting by Key ### Description Retrieve a meeting object and its sessions using the meeting's unique key. The function returns a detailed table of the meeting's sessions. ### Method Signature ```python livef1.get_meeting(season: int, meeting_key: int) ``` ### Parameters - **season** (int) - Required - The year of the season. - **meeting_key** (int) - Required - The unique key identifying the meeting. ### Request Example ```python import livef1 as livef1 meeting = livef1.get_meeting( season=2024, meeting_key=1242 ) print(meeting) ``` ### Response Example ```none | | Season Year | Meeting Location | Session Type | Meeting Code | Meeting Key | Meeting Number | Meeting Offname | Meeting Name | Meeting Country Key | Meeting Country Code | Meeting Country Name | Meeting Circuit Key | Meeting Circuit Shortname | Session Key | Session Name | Session Startdate | Session Enddate | Gmtoffset | Path | |---:|--------------:|:-------------------|:---------------|:---------------|--------------:|-----------------:|:----------------------------------------|:-------------------|----------------------:|:-----------------------|:-----------------------|----------------------:|:----------------------------|--------------:|:---------------|:--------------------|:--------------------|:------------|:----------------------------------------------------------| | 0 | 2024 | Spa-Francorchamps | Practice 1 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9567 | Practice 1 | 2024-07-26 13:30:00 | 2024-07-26 14:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_1/ | | 1 | 2024 | Spa-Francorchamps | Practice 2 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9568 | Practice 2 | 2024-07-26 17:00:00 | 2024-07-26 18:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-26_Practice_2/ | | 2 | 2024 | Spa-Francorchamps | Practice 3 | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9569 | Practice 3 | 2024-07-27 12:30:00 | 2024-07-27 13:30:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Practice_3/ | | 3 | 2024 | Spa-Francorchamps | Qualifying | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9570 | Qualifying | 2024-07-27 16:00:00 | 2024-07-27 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-27_Qualifying/ | | 4 | 2024 | Spa-Francorchamps | Race | BEL02012 | 1242 | 14 | FORMULA 1 ROLEX BELGIAN GRAND PRIX 2024 | Belgian Grand Prix | 16 | BEL | Belgium | 7 | Spa-Francorchamps | 9574 | Race | 2024-07-28 15:00:00 | 2024-07-28 17:00:00 | 02:00:00 | 2024/2024-07-28_Belgian_Grand_Prix/2024-07-28_Race/ | ``` ``` -------------------------------- ### Get and Process Historical Race Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/historical_data.md Fetches a specific race session and generates processed data for analysis. Ensure you have the correct season, meeting, and session identifiers. ```python import livef1 # Get a specific race session race = livef1.get_session( season=2023, meeting_identifier="Monaco", session_identifier="Race" ) # Generate processed data race.generate() # Get lap times and telemetry laps_data = race.laps telemetry = race.carTelemetry ``` -------------------------------- ### Initialize and Load Season Data Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/data_objects.md Initializes a Season object for a specific year and loads its data. Ensure the year is correctly specified. ```python from livef1.models.season import Season # Initialize a season for the year 2023 season_2023 = Season(year=2023, meetings=[]) # Load the season data season_2023.load() # Access the meetings meetings = season_2023.meetings ``` -------------------------------- ### Get Specific Session Directly Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/historical_data.md Retrieve a specific historical F1 session using season, meeting, and session identifiers. Ensure you have the correct identifiers for the desired race. ```python import livef1 # Get specific session directly race = livef1.get_session( season=2024, meeting_identifier="Spa", # Circuit/Location name session_identifier="Race" # Session type ) ``` -------------------------------- ### Stream Live F1 Data with RealF1Client Source: https://context7.com/goktugocal/livef1/llms.txt Connects to the F1 Live Timing SignalR endpoint to stream live data. Supports multiple handlers for different data topics and optional file logging. ```python from livef1.adapters.realtime_client import RealF1Client import datetime import sqlite3 import json # Initialize the client with topics and optional file logging client = RealF1Client( topics=["CarData.z", "Position.z", "SessionInfo", "TrackStatus"], log_file_name="session_data.json", # Automatically logs all records to file log_file_mode="w" ) # Handler 1: print telemetry records as they arrive @client.callback("telemetry_handler") async def handle_telemetry(records): car_data = records.get("CarData.z") if car_data: for record in car_data: print(f"[{datetime.datetime.now().isoformat()}] {record}") # Handler 2: monitor track status changes @client.callback("track_status_handler") async def handle_track_status(records): track_data = records.get("TrackStatus") if track_data: for record in track_data: print(f"Track status update: {record}") # Handler 3: store data in SQLite conn = sqlite3.connect("f1_live.db") conn.execute(""" CREATE TABLE IF NOT EXISTS live_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts TEXT, topic TEXT, data TEXT ) """) @client.callback("db_handler") async def store_to_db(records): ts = datetime.datetime.now().isoformat() for topic, rows in records.items(): for row in rows: conn.execute( "INSERT INTO live_data (ts, topic, data) VALUES (?,?,?)", (ts, topic, json.dumps(row)) ) conn.commit() # Start streaming — blocks until KeyboardInterrupt client.run() ``` -------------------------------- ### Load Specific Data by Name Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Load the contents of a specific data feed using its name with the get_data method. For example, to load 'Car_Data'. The output is typically a table-like structure. ```python data = session.get_data(dataName="Car_Data") print(data) ``` -------------------------------- ### Fetch Raw Data Topics for a Session Source: https://context7.com/goktugocal/livef1/llms.txt Load one or more data topics from the F1 Live Timing archive for a given session. Data is cached in the Bronze layer after the first fetch. Supports single topic names or lists, with optional parallel loading. ```python import livef1 session = livef1.get_session(2024, "Spa", "Race") ``` -------------------------------- ### Print Head of SectorLeaders Table Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/medallion_architecture.md Prints the first few rows of the 'SectorLeaders' gold layer table to the console. This allows for quick verification of the generated gold layer data. ```python print(session.SectorLeaders.head()) ``` -------------------------------- ### Retrieve F1 Season Data Source: https://context7.com/goktugocal/livef1/llms.txt Get a Season object for a given year, which contains all meetings and sessions. This also provides a summary DataFrame and allows access to the race schedule. ```python import livef1 # Retrieve the 2024 F1 season season = livef1.get_season(season=2024) # Print summary table of all meetings and sessions print(season) # Output (truncated): # | meeting_key | season_year | meeting_location | meeting_name | session_name | session_startDate | # |-------------|-------------|------------------|----------------------|--------------|---------------------| # | 1217 | 2024 | Sakhir | Bahrain Grand Prix | Practice 1 | 2024-02-29 11:30:00 | # | 1217 | 2024 | Sakhir | Bahrain Grand Prix | Race | 2024-03-02 15:00:00 | # ... # Access the race schedule from formula1.com schedule = season.get_schedule() print(schedule) # Iterate over meetings for meeting in season.meetings: print(meeting.name, meeting.location) ``` -------------------------------- ### Load Multiple Data Topics Source: https://github.com/goktugocal/livef1/blob/main/docs/source/getting_started/quick_start.md Load multiple data topics simultaneously by passing a list of topic names to the get_data method. You can choose to load them in parallel (default) or sequentially. ```python # Load multiple topics in parallel (default) data = session.get_data(["Car_Data", "Position", "SessionStatus"]) # Load multiple topics sequentially data = session.get_data(["Car_Data", "Position"], parallel=False) ``` -------------------------------- ### Get Driver Object by Last Name Source: https://context7.com/goktugocal/livef1/llms.txt Retrieves a Driver object using their last name. Allows for flexible driver lookups when the full name or racing number is not readily available. ```python # By last name driver = session.get_driver("hamilton") print(driver.RacingNumber) # 44 ``` -------------------------------- ### Get Historical Race Session Data Source: https://github.com/goktugocal/livef1/blob/main/README.md Access historical race data by specifying the season, meeting identifier, and session identifier. This function retrieves a specific race session for analysis. ```python import livef1 # Get a specific race session session = livef1.get_session( season=2024, meeting_identifier="Spa", session_identifier="Race" ) # Load position data position_data = session.get_data( dataNames="Position.z" ) print(position_data.head()) ``` -------------------------------- ### Stream Real-Time Race Data Source: https://github.com/goktugocal/livef1/blob/main/README.md Initialize the RealF1Client to subscribe to specific data topics and optionally log data to a file. Define a callback function to handle incoming records. ```python from livef1.adapters import RealF1Client # Initialize client with topics to subscribe client = RealF1Client( topics=["CarData.z", "Position.z"], log_file_name="race_data.json" # Optional: log data to file ) # Define callback for incoming data @client.callback("telemetry_handler") async def handle_data(records): for record in records: print(record) # Process incoming data # Start receiving data client.run() ``` -------------------------------- ### Print Head of SectorDiff Table Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/medallion_architecture.md Prints the first few rows of the 'SectorDiff' silver layer table to the console. This is useful for inspecting the data after it has been generated. ```python print(session.SectorDiff.head()) ``` -------------------------------- ### Load Raw Timing Data to Bronze Lake Source: https://github.com/goktugocal/livef1/blob/main/docs/source/user_guide/medallion_architecture.md Loads raw timing data for a specific session and stores it in the Bronze Lake. Ensure the session details (year, track, type) are correct. ```python # Get raw timing data session = livef1.get_session(2024, "Spa", "Race") raw_data = session.get_data("TimingData") # Loads data and puts to Bronza Lake print(raw_data.head()) ``` -------------------------------- ### Get Driver Object by Racing Number Source: https://context7.com/goktugocal/livef1/llms.txt Retrieves a Driver object using their racing number. Provides access to driver details like first name, last name, TLA, and racing number. ```python import livef1 session = livef1.get_session(2024, "Spa", "Race") # By racing number driver = session.get_driver("16") print(driver.FirstName, driver.LastName) # Charles Leclerc print(driver.Tla) # LEC print(driver.RacingNumber) # 16 ``` -------------------------------- ### Retrieve Specific F1 Session Data Source: https://context7.com/goktugocal/livef1/llms.txt Get a Session object for a specific race weekend session (Practice, Qualifying, Sprint, Race). This object is ready for data fetching and provides session metadata. ```python import livef1 # By meeting identifier and session name session = livef1.get_session( season=2024, meeting_identifier="Spa", session_identifier="Race" ) # By numeric keys (faster, no fuzzy search) session = livef1.get_session( season=2024, meeting_key=1242, session_key=9574 ) # Inspect session metadata print(session.name) # "Race" print(session.startdate) # "2024-07-28T15:00:00" print(session.key) # 9574 # List all available data topics session.print_topic_names() # Output: # Session_Info : # Details about the current session. # Car_Data : # Car sensor data (speed, throttle, brake, gear, RPM, DRS). # Position : # Position data of cars (X, Y, Z coordinates). # Track_Status : # Current conditions and status of the track. # ... ``` -------------------------------- ### Generate Silver and Gold Tables Source: https://context7.com/goktugocal/livef1/llms.txt Generates both Silver and Gold layer tables by setting both 'silver' and 'gold' parameters to True in the session.generate() method. ```python # Generate both Silver and Gold session.generate(silver=True, gold=True) ```