Pit-Lane-Project / backend /data /compressor.py
Interact-ai's picture
Upload folder using huggingface_hub
267266e verified
Raw History Blame Contribute Delete
33.4 kB
# ============================================================ # F1 LAP-LEVEL COMPRESSION + WINNER TARGET # # INPUT: # Raw merged telemetry CSV # WITHOUT Winner column # # OUTPUT: # 1 row = 1 Race + 1 Driver + 1 Lap # # Example: # 50 laps × 10 drivers = 500 rows # # Winner: # 1 = driver eventually won that race # 0 = driver did not win # # IMPORTANT: # Drivers are NEVER hardcoded. # They are taken directly from the input CSV. # ============================================================ # ============================================================ # 1. INSTALL / IMPORT # ============================================================ # In Colab, uncomment this if FastF1 is not installed: # !pip install -q fastf1 import json import os from pathlib import Path import fastf1 import numpy as np import pandas as pd # ============================================================ # 2. CONFIGURATION # ============================================================ YEAR = 2026 INPUT_FILE = "C:\\Users\\Admin\\Desktop\\PitLane\\cleaned_data_sidh.csv" OUTPUT_FILE = "F1_2026_compressed_training_data_SIDH.csv" SCHEMA_FILE = "F1_2026_compression_schema_SIDH.json" CACHE_DIR = "fastf1_cache" # Number of raw telemetry rows processed at a time. # # This prevents the entire raw dataset from having to live # in memory during compression. CHUNK_SIZE = 250_000 # ============================================================ # 3. FASTF1 CACHE # ============================================================ Path(CACHE_DIR).mkdir( parents=True, exist_ok=True ) fastf1.Cache.enable_cache( CACHE_DIR ) # ============================================================ # 4. INPUT VALIDATION # ============================================================ if not Path(INPUT_FILE).exists(): raise FileNotFoundError( f"\nInput file not found:\n{INPUT_FILE}" ) # ============================================================ # 5. COLUMNS # ============================================================ # These columns describe the instantaneous telemetry stream. # # We compress them using statistical summaries over the # entire lap. MEAN_COLUMNS = [ "RPM", "Speed", "nGear", "Throttle", "Brake", "DRS", "X", "Y", "Z", "DistanceToDriverAhead", "AirTemp", "TrackTemp", "Humidity", "Pressure", "WindDirection", "WindSpeed" ] # For these we want the state at the END of the completed lap. LAST_COLUMNS = [ "Date", "SessionTime", "Time", "Distance", "RelativeDistance", "DriverAhead", "TrackStatus", "Driver", "DriverNumber", "Team", "LapNumber", "Stint", "Compound", "TyreLife", "FreshTyre", "LapTime", "Sector1Time", "Sector2Time", "Sector3Time", "Sector1SessionTime", "Sector2SessionTime", "Sector3SessionTime", "SpeedI1", "SpeedI2", "SpeedFL", "SpeedST", "IsPersonalBest", "Position", "PitInTime", "PitOutTime", "LapStartTime", "LapStartDate" ] # Rainfall is a state/event indicator. # Maximum is effectively "did rain occur during this lap?" RAIN_COLUMN = "Rainfall" # DifferentialDistance represents incremental distance. # Summing it over a lap gives the distance accumulated. SUM_COLUMNS = [ "DifferentialDistance" ] # ============================================================ # 6. COLUMNS REQUIRED FROM THE RAW DATA # ============================================================ REQUIRED_COLUMNS = [ "Date", "Driver", "DriverNumber", "LapNumber" ] # ============================================================ # 7. HELPER FUNCTIONS # ============================================================ def last_valid(series): """ Return the last non-null value in a group. """ valid = series.dropna() if len(valid) == 0: return np.nan return valid.iloc[-1] def first_valid(series): """ Return the first non-null value in a group. """ valid = series.dropna() if len(valid) == 0: return np.nan return valid.iloc[0] def safe_numeric(series): return pd.to_numeric( series, errors="coerce" ) # ============================================================ # 8. PREPARE A CHUNK # ============================================================ def prepare_chunk(chunk): chunk = chunk.copy() # -------------------------------------------------------- # Date # -------------------------------------------------------- chunk["Date"] = pd.to_datetime( chunk["Date"], errors="coerce" ) # Race date = calendar date of the race. chunk["_RaceDate"] = ( chunk["Date"] .dt.normalize() ) # -------------------------------------------------------- # Numeric conversion # -------------------------------------------------------- numeric_columns = list( set( MEAN_COLUMNS + SUM_COLUMNS + [ "DriverNumber", "LapNumber", "Stint", "TyreLife", "Position" ] ) ) for column in numeric_columns: if column in chunk.columns: chunk[column] = safe_numeric( chunk[column] ) # -------------------------------------------------------- # Boolean conversion # -------------------------------------------------------- boolean_columns = [ "Brake", "FreshTyre", "IsPersonalBest", "Rainfall" ] for column in boolean_columns: if column not in chunk.columns: continue if pd.api.types.is_bool_dtype( chunk[column] ): chunk[column] = ( chunk[column] .astype(float) ) else: chunk[column] = ( chunk[column] .astype(str) .str.strip() .str.lower() .map({ "true": 1, "false": 0, "1": 1, "0": 0 }) ) # -------------------------------------------------------- # Driver # -------------------------------------------------------- chunk["Driver"] = ( chunk["Driver"] .fillna("UNKNOWN") .astype(str) ) # -------------------------------------------------------- # Sort chronological # -------------------------------------------------------- sort_columns = [ "_RaceDate", "Driver", "LapNumber" ] for column in [ "SessionTime", "Time", "Date" ]: if column in chunk.columns: sort_columns.append(column) chunk = chunk.sort_values( sort_columns, kind="stable" ) return chunk # ============================================================ # 9. COMPRESS ONE CHUNK # ============================================================ def compress_chunk(chunk): chunk = prepare_chunk( chunk ) group_columns = [ "_RaceDate", "Driver", "LapNumber" ] grouped = chunk.groupby( group_columns, sort=False, dropna=False ) compressed_parts = [] # -------------------------------------------------------- # Base information # -------------------------------------------------------- base = grouped.size().rename( "TelemetryRecords" ).reset_index() compressed_parts.append( base ) # -------------------------------------------------------- # MEAN FEATURES # -------------------------------------------------------- for column in MEAN_COLUMNS: if column not in chunk.columns: continue result = ( grouped[column] .mean() .rename( f"{column}_Mean" ) .reset_index() ) compressed_parts.append( result ) # -------------------------------------------------------- # SUM FEATURES # -------------------------------------------------------- for column in SUM_COLUMNS: if column not in chunk.columns: continue result = ( grouped[column] .sum( min_count=1 ) .rename( f"{column}_Sum" ) .reset_index() ) compressed_parts.append( result ) # -------------------------------------------------------- # LAST VALUE FEATURES # -------------------------------------------------------- for column in LAST_COLUMNS: if column not in chunk.columns: continue result = ( grouped[column] .agg(last_valid) .rename( f"{column}_Last" ) .reset_index() ) compressed_parts.append( result ) # -------------------------------------------------------- # RAINFALL # -------------------------------------------------------- if RAIN_COLUMN in chunk.columns: result = ( grouped[RAIN_COLUMN] .max() .rename( "Rainfall_Any" ) .reset_index() ) compressed_parts.append( result ) # -------------------------------------------------------- # Merge partial compressed pieces # -------------------------------------------------------- result = compressed_parts[0] for part in compressed_parts[1:]: result = result.merge( part, on=group_columns, how="left" ) return result # ============================================================ # 10. MERGE PARTIAL CHUNKS # ============================================================ def merge_compressed_chunks( partial_results ): """ A single race/lap may cross CSV chunk boundaries. Therefore we compress each chunk first, then recompute the final aggregation from those partial results. """ if not partial_results: return pd.DataFrame() df = pd.concat( partial_results, ignore_index=True ) group_columns = [ "_RaceDate", "Driver", "LapNumber" ] final_rows = [] for group_key, group in df.groupby( group_columns, sort=False, dropna=False ): row = { "_RaceDate": group_key[0], "Driver": group_key[1], "LapNumber": group_key[2] } # ---------------------------------------------------- # Number of telemetry records # ---------------------------------------------------- if "TelemetryRecords" in group: row["TelemetryRecords"] = ( group["TelemetryRecords"] .sum() ) # ---------------------------------------------------- # MEAN COLUMNS # # Weighted average using raw record counts. # ---------------------------------------------------- for column in MEAN_COLUMNS: mean_column = ( f"{column}_Mean" ) if mean_column not in group.columns: continue weights = ( group["TelemetryRecords"] .fillna(0) ) values = ( pd.to_numeric( group[mean_column], errors="coerce" ) ) valid = ( values.notna() & (weights > 0) ) if valid.any(): row[ mean_column ] = np.average( values[valid], weights=weights[valid] ) else: row[ mean_column ] = np.nan # ---------------------------------------------------- # SUM COLUMNS # ---------------------------------------------------- for column in SUM_COLUMNS: sum_column = ( f"{column}_Sum" ) if sum_column in group.columns: row[ sum_column ] = ( group[sum_column] .sum( min_count=1 ) ) # ---------------------------------------------------- # LAST COLUMNS # # The raw CSV is chronological; sort by race/lap and # then choose the latest non-null value. # ---------------------------------------------------- for column in LAST_COLUMNS: last_column = ( f"{column}_Last" ) if last_column not in group.columns: continue row[ last_column ] = last_valid( group[last_column] ) # ---------------------------------------------------- # Rain # ---------------------------------------------------- if "Rainfall_Any" in group.columns: row[ "Rainfall_Any" ] = group[ "Rainfall_Any" ].max() final_rows.append( row ) return pd.DataFrame( final_rows ) # ============================================================ # 11. COMPRESS ENTIRE DATASET # ============================================================ def compress_dataset(): print("=" * 80) print("STARTING LAP-LEVEL COMPRESSION") print("=" * 80) partial_results = [] total_raw_rows = 0 chunk_number = 0 # -------------------------------------------------------- # Read CSV in chunks # -------------------------------------------------------- reader = pd.read_csv( INPUT_FILE, chunksize=CHUNK_SIZE, low_memory=False ) for chunk in reader: chunk_number += 1 total_raw_rows += len( chunk ) print( f"\nProcessing chunk " f"{chunk_number}: " f"{len(chunk):,} raw rows" ) # ---------------------------------------------------- # Validate columns on first chunk # ---------------------------------------------------- if chunk_number == 1: missing = [ column for column in REQUIRED_COLUMNS if column not in chunk.columns ] if missing: raise ValueError( "Missing required columns:\n" + "\n".join(missing) ) print( f"Raw columns detected: " f"{len(chunk.columns)}" ) # ---------------------------------------------------- # Compress this chunk # ---------------------------------------------------- compressed = compress_chunk( chunk ) print( f"Compressed to " f"{len(compressed):,} " f"partial lap groups" ) partial_results.append( compressed ) # Free the chunk immediately del chunk print("\n") print("=" * 80) print("COMBINING COMPRESSED CHUNKS") print("=" * 80) compressed_df = ( merge_compressed_chunks( partial_results ) ) del partial_results print( f"\nRaw telemetry rows: " f"{total_raw_rows:,}" ) print( f"Compressed rows: " f"{len(compressed_df):,}" ) return compressed_df # ============================================================ # 12. GET FASTF1 RACE SCHEDULE # ============================================================ def get_schedule(): print("\n") print("=" * 80) print("LOADING FASTF1 SCHEDULE") print("=" * 80) schedule = fastf1.get_event_schedule( YEAR ) schedule = schedule[ schedule["RoundNumber"] > 0 ].copy() schedule["EventDate"] = pd.to_datetime( schedule["EventDate"], errors="coerce" ) schedule["_RaceDate"] = ( schedule["EventDate"] .dt.normalize() ) return schedule # ============================================================ # 13. FETCH WINNERS # ============================================================ def get_winners( compressed_df, schedule ): print("\n") print("=" * 80) print("FETCHING RACE WINNERS FROM FASTF1") print("=" * 80) race_dates = ( compressed_df["_RaceDate"] .dropna() .drop_duplicates() .sort_values() .tolist() ) winner_records = [] for race_date in race_dates: race_date = pd.Timestamp( race_date ).normalize() print("\n") print("-" * 70) print( f"Race date: " f"{race_date.date()}" ) # ---------------------------------------------------- # Match race date to schedule # ---------------------------------------------------- matches = schedule[ schedule["_RaceDate"] == race_date ] if matches.empty: print( "WARNING: No FastF1 race " "matched this date." ) continue event = matches.iloc[0] round_number = int( event["RoundNumber"] ) event_name = event["EventName"] print( f"Round: {round_number}" ) print( f"Race : {event_name}" ) # ---------------------------------------------------- # Load race results # ---------------------------------------------------- try: session = fastf1.get_session( YEAR, round_number, "R" ) session.load( telemetry=False, weather=False ) except Exception as e: print( f"ERROR loading results: {e}" ) continue # ---------------------------------------------------- # Results # ---------------------------------------------------- if ( session.results is None or session.results.empty ): print( "WARNING: No results found." ) continue results = session.results.copy() results["Position"] = pd.to_numeric( results["Position"], errors="coerce" ) results["DriverNumber"] = pd.to_numeric( results["DriverNumber"], errors="coerce" ) winner_rows = results[ results["Position"] == 1 ] if winner_rows.empty: print( "WARNING: No P1 driver found." ) continue winner = winner_rows.iloc[0] winner_number = winner[ "DriverNumber" ] winner_abbreviation = winner.get( "Abbreviation", "UNKNOWN" ) winner_name = winner.get( "FullName", "UNKNOWN" ) print( f"Winner: #{int(winner_number)} " f"{winner_abbreviation} " f"({winner_name})" ) winner_records.append( { "_RaceDate": race_date, "WinningDriverNumber": winner_number, "WinningDriver": winner_abbreviation, "WinningDriverName": winner_name, "RoundNumber": round_number, "EventName": event_name } ) winners_df = pd.DataFrame( winner_records ) if winners_df.empty: raise RuntimeError( "No race winners were successfully retrieved." ) return winners_df # ============================================================ # 14. ADD WINNER TARGET # ============================================================ def add_winner_column( compressed_df, winners_df ): print("\n") print("=" * 80) print("ADDING WINNER TARGET") print("=" * 80) compressed_df[ "DriverNumber" ] = pd.to_numeric( compressed_df[ "DriverNumber_Last" ], errors="coerce" ) winners_df[ "WinningDriverNumber" ] = pd.to_numeric( winners_df[ "WinningDriverNumber" ], errors="coerce" ) # -------------------------------------------------------- # Merge race winner information # -------------------------------------------------------- compressed_df = compressed_df.merge( winners_df[ [ "_RaceDate", "WinningDriverNumber", "WinningDriver", "WinningDriverName", "RoundNumber", "EventName" ] ], on="_RaceDate", how="left" ) # -------------------------------------------------------- # Winner target # # Only drivers actually present in the CSV exist here, # so no hardcoded driver is added. # -------------------------------------------------------- compressed_df["Winner"] = ( compressed_df["DriverNumber"] == compressed_df["WinningDriverNumber"] ).astype(int) return compressed_df # ============================================================ # 15. FINAL CLEANUP / COLUMN ORDER # ============================================================ def final_cleanup( compressed_df ): # -------------------------------------------------------- # Sort # -------------------------------------------------------- compressed_df = ( compressed_df .sort_values( [ "_RaceDate", "Driver", "LapNumber" ], kind="stable" ) .reset_index( drop=True ) ) # -------------------------------------------------------- # Put useful identifiers at the front # -------------------------------------------------------- preferred_front = [ "_RaceDate", "Driver", "DriverNumber", "LapNumber", "TelemetryRecords", "Winner" ] remaining_columns = [ column for column in compressed_df.columns if column not in preferred_front ] compressed_df = compressed_df[ [ column for column in preferred_front if column in compressed_df.columns ] + remaining_columns ] # -------------------------------------------------------- # Remove technical winner metadata from model dataset # # They have already served their purpose. # -------------------------------------------------------- compressed_df = compressed_df.drop( columns=[ "WinningDriverNumber", "WinningDriver", "WinningDriverName", "RoundNumber", "EventName" ], errors="ignore" ) # -------------------------------------------------------- # Rename internal race date # -------------------------------------------------------- compressed_df = ( compressed_df .rename( columns={ "_RaceDate": "RaceDate" } ) ) return compressed_df # ============================================================ # 16. CREATE COMPRESSION SCHEMA # ============================================================ def create_schema( compressed_df ): model_candidate_columns = [ column for column in compressed_df.columns if column not in [ "RaceDate", "Winner" ] ] categorical_candidates = [ "Driver", "DriverNumber", "LapNumber", "TrackStatus_Last", "DriverAhead_Last", "Team_Last", "Compound_Last" ] categorical_candidates = [ column for column in categorical_candidates if column in compressed_df.columns ] schema = { "description": "One row per Race + Driver + LapNumber", "input_file": INPUT_FILE, "output_file": OUTPUT_FILE, "target": "Winner", "row_definition": "One completed lap of one driver in one race", "grouping_columns": [ "RaceDate", "Driver", "LapNumber" ], "aggregation_rules": { "mean": MEAN_COLUMNS, "sum": SUM_COLUMNS, "last_non_null": LAST_COLUMNS, "rainfall_any": [RAIN_COLUMN] }, "model_candidate_features": model_candidate_columns, "categorical_candidates": categorical_candidates, "total_output_columns": len(compressed_df.columns), "total_model_candidate_features": len(model_candidate_columns) } return schema # ============================================================ # 17. VALIDATE RESULT # ============================================================ def validate_result( df ): print("\n") print("=" * 80) print("VALIDATING COMPRESSED DATASET") print("=" * 80) # -------------------------------------------------------- # Duplicate race/driver/lap check # -------------------------------------------------------- duplicates = df.duplicated( subset=[ "RaceDate", "Driver", "LapNumber" ] ).sum() print( f"\nDuplicate Race+Driver+Lap rows: " f"{duplicates}" ) if duplicates != 0: raise RuntimeError( "Compression produced duplicate " "Race + Driver + Lap rows." ) # -------------------------------------------------------- # Winner check per race # -------------------------------------------------------- winner_counts = ( df.groupby("RaceDate")["Winner"] .sum() ) invalid = winner_counts[ winner_counts != 1 ] if invalid.empty: print( "Winner validation: PASSED" ) else: print( "\nWARNING: These races do not have " "exactly one Winner=1:" ) print( invalid ) # -------------------------------------------------------- # Rows per race # -------------------------------------------------------- race_summary = ( df.groupby( "RaceDate" ) .agg( Drivers=( "Driver", "nunique" ), Laps=( "LapNumber", "nunique" ), Rows=( "Winner", "size" ) ) .reset_index() ) race_summary[ "ExpectedMaximumRows" ] = ( race_summary["Drivers"] * race_summary["Laps"] ) print( "\nRace compression summary:" ) print( race_summary .to_string( index=False ) ) # -------------------------------------------------------- # Winner distribution # -------------------------------------------------------- print( "\nWinner distribution:" ) print( df["Winner"] .value_counts( dropna=False ) .sort_index() ) # ============================================================ # 18. MAIN # ============================================================ def main(): print("\n") print("=" * 80) print("F1 LAP-LEVEL TRAINING DATA CREATOR") print("=" * 80) # -------------------------------------------------------- # Step 1 # -------------------------------------------------------- compressed_df = compress_dataset() # -------------------------------------------------------- # Step 2 # -------------------------------------------------------- schedule = get_schedule() # -------------------------------------------------------- # Step 3 # -------------------------------------------------------- winners_df = get_winners( compressed_df, schedule ) # -------------------------------------------------------- # Step 4 # -------------------------------------------------------- compressed_df = add_winner_column( compressed_df, winners_df ) # -------------------------------------------------------- # Step 5 # -------------------------------------------------------- compressed_df = final_cleanup( compressed_df ) # -------------------------------------------------------- # Step 6 # -------------------------------------------------------- validate_result( compressed_df ) # -------------------------------------------------------- # Step 7 # -------------------------------------------------------- schema = create_schema( compressed_df ) # -------------------------------------------------------- # Step 8 # -------------------------------------------------------- compressed_df.to_csv( OUTPUT_FILE, index=False ) with open( SCHEMA_FILE, "w", encoding="utf-8" ) as file: json.dump( schema, file, indent=4 ) # -------------------------------------------------------- # Final output # -------------------------------------------------------- print("\n") print("=" * 80) print("COMPRESSION COMPLETE") print("=" * 80) print( f"\nRaw input:" f" {INPUT_FILE}" ) print( f"Raw telemetry rows:" f" {len(compressed_df):,} compressed rows" ) print( f"Final rows:" f" {len(compressed_df):,}" ) print( f"Final columns:" f" {len(compressed_df.columns)}" ) print( f"\nOutput:" f" {OUTPUT_FILE}" ) print( f"Schema:" f" {SCHEMA_FILE}" ) print( "\nRow meaning:" ) print( "ONE ROW = ONE DRIVER + ONE LAP + ONE RACE" ) print( "\nExample:" ) print( "50 laps × 10 drivers = 500 rows" ) # ============================================================ # RUN # ============================================================ if __name__ == "__main__": main()
# ============================================================
# F1 LAP-LEVEL COMPRESSION + WINNER TARGET
#
# INPUT:
# Raw merged telemetry CSV
# WITHOUT Winner column
#
# OUTPUT:
# 1 row = 1 Race + 1 Driver + 1 Lap
#
# Example:
# 50 laps × 10 drivers = 500 rows
#
# Winner:
# 1 = driver eventually won that race
# 0 = driver did not win
#
# IMPORTANT:
# Drivers are NEVER hardcoded.
# They are taken directly from the input CSV.
# ============================================================
# ============================================================
# 1. INSTALL / IMPORT
# ============================================================
# In Colab, uncomment this if FastF1 is not installed:
# !pip install -q fastf1
import json
import os
from pathlib import Path
import fastf1
import numpy as np
import pandas as pd
# ============================================================
# 2. CONFIGURATION
# ============================================================
YEAR = 2026
INPUT_FILE = "C:\\Users\\Admin\\Desktop\\PitLane\\cleaned_data_sidh.csv"
OUTPUT_FILE = "F1_2026_compressed_training_data_SIDH.csv"
SCHEMA_FILE = "F1_2026_compression_schema_SIDH.json"
CACHE_DIR = "fastf1_cache"
# Number of raw telemetry rows processed at a time.
#
# This prevents the entire raw dataset from having to live
# in memory during compression.
CHUNK_SIZE = 250_000
# ============================================================
# 3. FASTF1 CACHE
# ============================================================
Path(CACHE_DIR).mkdir(
parents=True,
exist_ok=True
)
fastf1.Cache.enable_cache(
CACHE_DIR
)
# ============================================================
# 4. INPUT VALIDATION
# ============================================================
if not Path(INPUT_FILE).exists():
raise FileNotFoundError(
f"\nInput file not found:\n{INPUT_FILE}"
)
# ============================================================
# 5. COLUMNS
# ============================================================
# These columns describe the instantaneous telemetry stream.
#
# We compress them using statistical summaries over the
# entire lap.
MEAN_COLUMNS = [
"RPM",
"Speed",
"nGear",
"Throttle",
"Brake",