Skip to main content

Models API Reference

The models module provides a comprehensive, object-oriented interface for working with Formula 1 data. These classes extend pandas DataFrame and Series objects with domain-specific methods tailored for F1 analysis, making it intuitive to filter, analyze, and visualize racing data with minimal code.

Overview

All model classes in tif1 are built on top of pandas data structures, providing familiar DataFrame and Series interfaces while adding specialized methods for F1 data manipulation. This design philosophy allows you to leverage the full power of pandas operations alongside tif1-specific functionality, creating a seamless development experience.

Key Features

  • Lazy Loading: Data is loaded on-demand for optimal performance and memory efficiency
  • Method Chaining: Fluent API design enables expressive, readable code
  • FastF1 Compatibility: Drop-in replacement for FastF1 with minimal code changes
  • Type Hints: Full type annotation support for enhanced IDE autocomplete and type checking
  • Automatic Validation: Built-in data validation and error handling
  • Dual Backend Support: Works with both pandas and polars backends (where applicable)
  • Zero-Copy Operations: Optimized for performance with minimal data duplication
  • Thread-Safe Caching: Internal caching mechanisms for repeated access patterns

Model Hierarchy

The tif1 models form a logical hierarchy that mirrors the structure of F1 data:
  • Laps (DataFrame) → Collection of lap timing data for multiple laps/drivers
  • Lap (Series) → Single lap with telemetry access and timing information
  • Driver (Series) → Driver metadata with access to all their laps
  • Telemetry (DataFrame) → High-frequency sensor data (speed, throttle, brake, etc.)
  • SessionResults (DataFrame) → Race results and final standings
  • DriverResult (Series) → Individual driver’s race result
  • CircuitInfo (Dataclass) → Circuit layout information and track markers

Design Philosophy

The models are designed with the following principles:
  1. Intuitive Access Patterns: Natural property access (e.g., lap.telemetry, driver.laps)
  2. Consistent Filtering: All filtering methods follow the pick_* naming convention
  3. Graceful Degradation: Methods return empty DataFrames instead of raising exceptions when data is unavailable
  4. Session Context: All models maintain a reference to their parent session for seamless data access
  5. Performance First: Optimized for speed with vectorized operations and intelligent caching

Laps

The Laps class represents a collection of lap timing data and is the primary interface for filtering and analyzing multiple laps. It inherits from pandas.DataFrame, providing all standard DataFrame operations plus specialized F1-specific filtering methods. This is the most commonly used class in tif1, serving as the entry point for most lap-based analysis.

Class Overview

Inheritance: pandas.DataFrameLaps Module: tif1.models (re-exported from tif1.core) Thread Safety: Read operations are thread-safe; write operations should be synchronized externally

Common Access Patterns

The Laps class can be accessed through multiple pathways depending on your analysis needs:

Data Structure

Each row in a Laps DataFrame represents a single lap with comprehensive timing and metadata. The DataFrame contains the following column categories:

Core Identity Columns

  • Driver (str): 3-letter driver code (e.g., “VER”, “HAM”, “LEC”)
  • DriverNumber (str): Car racing number (e.g., “1”, “44”, “16”)
  • Team (str): Full team name (e.g., “Red Bull Racing”, “Mercedes”)
  • LapNumber (float): Sequential lap number within the session

Timing Columns (timedelta64[ns])

All timing columns are stored as pandas timedelta objects for precise time arithmetic:
  • LapTime: Total lap time from start line to start line
  • LapStartTime: Session time when the lap started
  • Time: Session time when the lap was completed
  • Sector1Time, Sector2Time, Sector3Time: Individual sector times
  • Sector1SessionTime, Sector2SessionTime, Sector3SessionTime: Session times at sector completion
  • PitInTime: Session time when entering pit lane (NaT if no pit stop)
  • PitOutTime: Session time when exiting pit lane (NaT if no pit stop)

Speed Trap Columns (float64, km/h)

  • SpeedI1: Speed at intermediate 1 timing point
  • SpeedI2: Speed at intermediate 2 timing point
  • SpeedFL: Speed at finish line
  • SpeedST: Speed at speed trap location

Tire Information

  • Compound (str): Tire compound (“SOFT”, “MEDIUM”, “HARD”, “INTERMEDIATE”, “WET”)
  • TyreLife (float): Number of laps completed on this tire set
  • FreshTyre (bool): Whether this is a fresh (unused) tire set
  • Stint (float): Stint number within the session

Lap Metadata

  • TrackStatus (str): Track condition code (“1”=Green, “2”=Yellow, “4”=Safety Car, “5”=Red Flag, “6”=VSC, “7”=VSC Ending)
  • Position (float): Track position at lap completion
  • IsPersonalBest (bool): Whether this is the driver’s fastest lap
  • Deleted (bool): Whether the lap time was deleted by race control
  • DeletedReason (str): Reason for lap deletion (if applicable)
  • IsAccurate (bool): Whether the lap has accurate timing data
  • FastF1Generated (bool): Internal flag for data source tracking

Qualifying-Specific

  • QualifyingSession (str): Which qualifying session (“Q1”, “Q2”, “Q3”)

Derived Columns

  • LapTimeSeconds (float): Lap time in seconds (derived from LapTime for convenience)

Weather Data (per-lap)

When weather data is available, each lap includes:
  • WeatherTime (timedelta): Weather observation time
  • AirTemp (float): Air temperature in °C
  • TrackTemp (float): Track surface temperature in °C
  • Humidity (float): Relative humidity percentage
  • Pressure (float): Atmospheric pressure in mbar
  • WindSpeed (float): Wind speed in km/h
  • WindDirection (int): Wind direction in degrees
  • Rainfall (bool): Whether it’s raining

Properties

Session
Reference to the parent Session object. This provides access to session-level data and methods, enabling operations like telemetry loading and driver information lookup. The session reference is automatically propagated when filtering or slicing Laps objects, ensuring that derived objects maintain full context.Usage:

Core Filtering Methods

The Laps class provides a comprehensive set of filtering methods that can be chained together for complex queries. All filtering methods return new Laps objects, preserving the original data (immutable operations). These methods are optimized for performance using pandas’ vectorized operations.

pick_driver(identifier)

Filter laps to a single driver using flexible identifier matching. This is one of the most commonly used methods in tif1.
Parameters:
  • identifier: Can be one of several formats for maximum flexibility:
    • str: 3-letter driver code (e.g., “VER”, “HAM”, “LEC”) - most common usage
    • int: Driver racing number (e.g., 1, 44, 16)
    • dict: Dictionary containing driver info with keys like “driver”, “dn”, “RacingNumber”, “Abbreviation”
    • Object: Any object with a driver or Abbreviation attribute
Returns:
  • Laps object containing only laps from the specified driver. Returns empty Laps if driver not found.
Behavior Details:
  • Case-sensitive for driver codes (must use uppercase: “VER” not “ver”)
  • Automatically normalizes various identifier formats to internal representation
  • Returns empty Laps if driver not found (no exception raised) - allows graceful handling
  • Preserves session reference in returned object for continued data access
  • Uses vectorized pandas operations for O(n) performance even with large datasets
Performance Characteristics:
  • Time Complexity: O(n) where n is the number of laps
  • Space Complexity: O(m) where m is the number of matching laps
  • Optimized with pandas boolean indexing (no Python loops)
Example Usage:
Common Patterns:
Error Handling:

pick_drivers(identifiers)

Filter laps to multiple drivers simultaneously. Useful for comparing performance between specific drivers or analyzing battles.
Parameters:
  • identifiers: List of driver identifiers (same formats as pick_driver). Can mix different identifier types in the same list.
Returns:
  • Laps object containing laps from all specified drivers. Returns empty Laps if no matching drivers found.
Behavior Details:
  • Accepts mixed identifier types in the same list (e.g., ["VER", 44, {"driver": "LEC"}])
  • Order of drivers in result matches original lap chronological order, not identifier order
  • Duplicate identifiers are automatically deduplicated
  • Returns empty Laps if no matching drivers found
  • Preserves all lap metadata and session context
Performance Characteristics:
  • Time Complexity: O(n) where n is the number of laps
  • More efficient than multiple pick_driver calls combined with concatenation
  • Uses pandas’ isin() method for vectorized filtering
Example Usage:
Use Cases:
  • Comparing performance between specific drivers
  • Analyzing battles between teammates or rivals
  • Creating visualizations with selected drivers
  • Team-level analysis (all drivers from specific teams)
  • Qualifying session analysis (top 10 drivers)
Common Patterns:

pick_fastest(only_by_time=False)

Get the single fastest lap from the collection. This is a convenience method that returns a Lap object (pandas Series) rather than a Laps DataFrame.
Parameters:
  • only_by_time (bool, default=False): Reserved for future use. Currently has no effect. In FastF1, this parameter controls whether to consider only lap time or also track status. In tif1, only lap time is considered.
Returns:
  • Lap object representing the fastest lap, or None if no valid laps found
Behavior Details:
  • Only considers laps with valid lap times (non-null, non-NaN)
  • Returns the lap with the minimum LapTime value
  • Returns None if the collection is empty or has no valid lap times
  • Preserves session context in the returned Lap object
  • If multiple laps have identical fastest times, returns the first occurrence
Performance Characteristics:
  • Time Complexity: O(n) for finding minimum
  • Efficient pandas vectorized operation
Example Usage:
Common Patterns:
Error Handling:

pick_quicklaps(threshold=1.07)

Filter laps within a percentage of the fastest lap time. This is useful for analyzing competitive laps and excluding outliers or slow laps affected by traffic, pit stops, or incidents.
Parameters:
  • threshold (float, default=1.07): Percentage multiplier for the fastest lap time. Default is 1.07 (107%), which is the F1 qualifying 107% rule. Must be >= 1.0.
Returns:
  • Laps object containing only laps within the threshold. Returns empty Laps if no laps meet the criteria.
Behavior Details:
  • Calculates the fastest lap time in the collection
  • Returns all laps where LapTime <= fastest_time * threshold
  • Only considers laps with valid lap times (non-null, non-NaN)
  • Returns empty Laps if no valid lap times exist
  • Preserves session context and all lap metadata
Performance Characteristics:
  • Time Complexity: O(n) - one pass to find minimum, one pass to filter
  • Efficient pandas vectorized operations
Example Usage:
Use Cases:
  • Filtering out slow laps affected by traffic or incidents
  • Analyzing competitive pace without outliers
  • Implementing F1’s 107% qualifying rule
  • Tire degradation analysis with consistent pace
  • Race pace analysis excluding pit laps and safety car periods
Common Patterns:

pick_tyre(compound) / pick_compounds(compounds)

Filter laps by tire compound. Essential for tire strategy analysis and understanding performance characteristics of different compounds.
Parameters:
  • compound (str): Single tire compound name. Valid values: “SOFT”, “MEDIUM”, “HARD”, “INTERMEDIATE”, “WET”, “UNKNOWN”, “TEST_UNKNOWN”
  • compounds (list[str]): List of tire compound names for pick_compounds
Returns:
  • Laps object containing only laps on the specified compound(s)
Behavior Details:
  • Compound names are case-sensitive (use uppercase)
  • Returns empty Laps if no laps match the compound
  • pick_tyre is a convenience wrapper for pick_compounds with a single compound
  • Preserves all lap metadata and session context
Example Usage:

pick_lap(lap_number) / pick_laps(laps)

Filter by specific lap number(s). Useful for analyzing specific moments in a race or comparing performance at the same point in different stints.
Parameters:
  • lap_number (int): Single lap number to filter
  • laps: Can be:
    • int: Single lap number
    • list[int]: Multiple specific lap numbers
    • slice: Range of laps (e.g., slice(10, 20) for laps 10-20 inclusive)
Returns:
  • Laps object containing only the specified lap(s)
Behavior Details:
  • Lap numbers are 1-indexed (first lap is lap 1)
  • Returns empty Laps if lap number doesn’t exist
  • pick_lap is a convenience wrapper for pick_laps with a single lap
  • Slice ranges are inclusive on both ends
  • Preserves all driver data (returns laps from all drivers at that lap number)
Example Usage:
Use Cases:
  • Analyzing race starts (lap 1)
  • Comparing performance at specific race stages
  • Identifying key moments (safety car laps, pit stop windows)
  • Studying tire warm-up (first few laps of a stint)
  • End-of-race analysis (final laps)

pick_team(name) / pick_teams(names)

Filter laps by team name. Useful for team-level analysis and comparing constructor performance.
Parameters:
  • name (str): Full team name (e.g., “Red Bull Racing”, “Mercedes”, “Ferrari”)
  • names (list[str]): List of team names for pick_teams
Returns:
  • Laps object containing only laps from the specified team(s)
Behavior Details:
  • Team names must match exactly (case-sensitive)
  • Returns empty Laps if team not found
  • pick_team is a convenience wrapper for pick_teams with a single team
  • Includes all drivers from the specified team(s)
Example Usage:

pick_track_status(status, how="equals")

Filter by track status (green flag, yellow flag, safety car, etc.). Essential for analyzing race conditions and their impact on lap times.
Parameters:
  • status (str): Track status code:
    • “1” = Green flag (normal racing)
    • “2” = Yellow flag
    • “4” = Safety Car
    • “5” = Red Flag
    • “6” = Virtual Safety Car (VSC)
    • “7” = VSC Ending
  • how (str): Matching mode:
    • “equals” (default): Exact match
    • “contains”: Partial match (useful for complex status codes)
Returns:
  • Laps object containing only laps with the specified track status
Example Usage:

pick_wo_box() / pick_box_laps(which="both")

Filter laps by pit stop activity. Critical for race strategy analysis and understanding pit stop impact.
Parameters:
  • which (str): For pick_box_laps:
    • “both” (default): Laps with either pit in or pit out
    • “in”: Only laps where driver entered pits
    • “out”: Only laps where driver exited pits
Returns:
  • Laps object filtered by pit activity
Behavior Details:
  • pick_wo_box() returns laps without any pit activity (neither PitInTime nor PitOutTime)
  • pick_box_laps() returns laps with pit activity
  • Useful for excluding slow pit laps from pace analysis
  • Returns empty Laps if columns don’t exist
Example Usage:

pick_not_deleted() / pick_accurate()

Filter for valid and accurate laps. Essential for ensuring data quality in analysis.
Returns:
  • pick_not_deleted(): Laps that weren’t deleted by race control
  • pick_accurate(): Laps with accurate timing data
Behavior Details:
  • pick_not_deleted() filters out laps where Deleted == True
  • pick_accurate() filters for laps where IsAccurate == True
  • Often used together for high-quality data analysis
  • Returns all laps if the respective column doesn’t exist
Example Usage:

Telemetry Access Methods

get_telemetry() / telemetry property

Access high-frequency telemetry data for the laps in the collection. This is one of the most powerful features of tif1, enabling detailed analysis of driver inputs and car behavior.
Returns:
  • Telemetry DataFrame with high-frequency sensor data
Behavior Details:
  • Single-driver requirement: Only works when all laps are from the same driver
  • Raises ValueError if laps contain multiple drivers
  • get_telemetry() includes driver-ahead channels (DriverAhead, DistanceToDriverAhead)
  • telemetry property provides basic telemetry without driver-ahead data
  • Returns empty Telemetry if no data available
  • Automatically concatenates telemetry from all laps in the collection
  • Preserves session context for continued analysis
Performance Characteristics:
  • Lazy-loaded on first access
  • Cached for subsequent accesses
  • May trigger network requests if not cached
Example Usage:
Error Handling:
Use Cases:
  • Detailed lap analysis (speed traces, braking points, throttle application)
  • Driver comparison (racing lines, braking techniques)
  • Car setup analysis (gear ratios, DRS effectiveness)
  • Overtaking analysis (with driver-ahead data)
  • Track mapping (X, Y, Z coordinates)

get_car_data() / get_pos_data()

FastF1 compatibility aliases for telemetry access. These methods provide the same functionality as telemetry property but with FastF1-compatible naming.
Returns:
  • Telemetry DataFrame (same as telemetry property)
Behavior Details:
  • get_car_data() returns full telemetry data
  • get_pos_data() returns position data (same as car data in tif1)
  • Both methods accept **kwargs for FastF1 compatibility (ignored in tif1)
  • For multi-driver laps, concatenates telemetry from all laps
Example Usage:

get_weather_data()

Get weather data for the laps. Returns session-level weather information.
Returns:
  • DataFrame with weather data from the session
Behavior Details:
  • Returns session-level weather data (not lap-specific)
  • Returns empty DataFrame if weather data unavailable
  • Weather data includes: AirTemp, TrackTemp, Humidity, Pressure, WindSpeed, WindDirection, Rainfall
Example Usage:

Iteration Methods

iterlaps(require=None)

Iterate over laps with optional required columns. This is the recommended way to iterate over laps when you need to process each lap individually.
Parameters:
  • require (list[str] | None): List of column names that must have non-null values. Laps with null values in these columns are skipped. Default is ["LapTime", "Driver"].
Yields:
  • _IterLapResult: Tuple-like object with:
    • index: DataFrame index of the lap
    • lap: Lap object (pandas Series) with lap data
Behavior Details:
  • Skips laps with null values in required columns
  • Removes null columns from each lap before yielding
  • Preserves session context in yielded Lap objects
  • Raises KeyError if a required column doesn’t exist in the DataFrame
Example Usage:
Use Cases:
  • Processing each lap individually
  • Calculating custom statistics
  • Filtering with complex logic
  • Accessing telemetry for each lap
  • Building custom data structures

Qualifying-Specific Methods

split_qualifying_sessions()

Split qualifying laps into Q1, Q2, and Q3 sessions. Note: tif1 doesn’t split by session internally, so this returns copies for FastF1 compatibility.
Returns:
  • tuple[Laps, Laps, Laps]: (Q1 laps, Q2 laps, Q3 laps)
Behavior Details:
  • Returns three Laps objects representing Q1, Q2, and Q3
  • In tif1, this returns copies of the same data for compatibility
  • Each returned Laps object preserves session context
  • If QualifyingSession column exists, attempts to split by that column
Example Usage:

DataFrame Operations

The Laps class inherits all pandas DataFrame operations, so you can use standard pandas methods:
Important: When using pandas operations that return DataFrames, the result may be a plain pandas DataFrame rather than a Laps object. Use the tif1-specific methods (pick_*) to maintain the Laps type and session context.

Lap

The Lap class represents a single lap with comprehensive timing data and access to high-frequency telemetry. It inherits from pandas.Series, making it a row-like object with named fields that can be accessed like a dictionary or via attribute access.

Class Overview

Inheritance: pandas.SeriesLap Module: tif1.models (re-exported from tif1.core) Common Access Patterns:

Data Structure

A Lap object is a pandas Series containing all the lap data columns described in the Laps section. You can access any column value using dictionary-style or attribute-style access:

Properties

int
The lap number extracted from the LapNumber column. This is a convenience property that returns the lap number as an integer.Usage:
Note: Returns None if LapNumber column is missing or null.
str
The 3-letter driver code extracted from the Driver column. This identifies which driver completed this lap.Usage:
Note: Returns None if Driver column is missing or null.
Telemetry
High-frequency telemetry data for this lap. This property provides lazy-loaded access to detailed sensor data including speed, throttle, brake, gear, DRS, and position information.Behavior:
  • Loaded lazily on first access (not fetched until you access this property)
  • Cached after first load for performance
  • Returns empty Telemetry DataFrame if data not found or unavailable
  • Automatically handles network requests and caching
  • Preserves session context for continued analysis
Performance:
  • First access may trigger network request (~50-200ms depending on connection)
  • Subsequent accesses are instant (cached in memory)
  • Telemetry data is typically 1000-3000 samples per lap
Usage:
Error Handling:
Session
Reference to the parent Session object. This maintains the connection to the session that created this lap, enabling access to session-level data and methods.Usage:

Methods

get_telemetry()

Explicitly load telemetry data with driver-ahead channels. This method is similar to accessing the telemetry property but includes additional channels for analyzing car-to-car interactions.
Returns:
  • Telemetry DataFrame with all telemetry channels including:
    • Standard channels: Time, Speed, RPM, nGear, Throttle, Brake, DRS, Distance, X, Y, Z
    • Driver-ahead channels: DriverAhead, DistanceToDriverAhead
Behavior Details:
  • Includes DriverAhead and DistanceToDriverAhead columns (if available)
  • Useful for analyzing overtaking opportunities and battles
  • Same lazy-loading and caching behavior as telemetry property
  • Returns empty Telemetry if data not available
Example Usage:
Use Cases:
  • Overtaking analysis
  • Battle analysis between drivers
  • Gap analysis during racing
  • Understanding traffic impact on lap times

get_car_data(**kwargs) / get_pos_data(**kwargs)

FastF1 compatibility aliases for telemetry access. These methods provide the same functionality as the telemetry property but with FastF1-compatible naming conventions.
Parameters:
  • **kwargs: Accepts any keyword arguments for FastF1 compatibility (ignored in tif1)
Returns:
  • Telemetry DataFrame with telemetry data
Behavior Details:
  • get_car_data() returns full telemetry data (same as telemetry property)
  • get_pos_data() returns position data (in tif1, same as car data)
  • Both methods are provided for FastF1 compatibility
  • No functional difference between the two in tif1
Example Usage:
Migration from FastF1:

get_weather_data()

Get weather data for this lap. Currently returns an empty Series as lap-specific weather data is included in the lap’s columns.
Returns:
  • Series: Empty pandas Series (weather data is in lap columns)
Behavior Details:
  • Provided for FastF1 compatibility
  • Weather data is already available in lap columns (AirTemp, TrackTemp, Humidity, etc.)
  • Returns empty Series in current implementation
Example Usage:
Accessing Weather Data:

Common Usage Patterns

Analyzing a Single Lap

Comparing Two Laps

Finding Personal Best Lap



Driver

The Driver class represents a driver’s participation in a session, providing access to their metadata, all their laps, and convenience methods for analyzing their performance. It inherits from pandas.Series, making it a dictionary-like object with driver information.

Class Overview

Inheritance: pandas.SeriesDriver Module: tif1.models (re-exported from tif1.core) Common Access Patterns:

Data Structure

A Driver object is a pandas Series containing driver metadata. The data is stored in the Series itself and can be accessed using dictionary-style or attribute-style access: Available Fields (in Series data):
  • DriverNumber (str): Racing number (e.g., “1”, “44”, “16”)
  • Abbreviation (str): 3-letter driver code (e.g., “VER”, “HAM”, “LEC”)
  • TeamName (str): Full team name (e.g., “Red Bull Racing”, “Mercedes”)
  • TeamColor (str): Team color hex code (e.g., “#3671C6”)
  • FirstName (str): Driver’s first name (e.g., “Max”, “Lewis”)
  • LastName (str): Driver’s last name (e.g., “Verstappen”, “Hamilton”)
  • FullName (str): Driver’s full name (e.g., “Max Verstappen”)
  • HeadshotUrl (str): URL to driver headshot image
Access Examples:

Properties

str
The 3-letter driver code (e.g., “VER”, “HAM”, “LEC”). This is stored as an attribute (not in the Series data) and provides quick access to the driver identifier.Usage:
Note: This is the primary identifier for the driver and is used throughout tif1 for filtering and lookups.
Session
Reference to the parent Session object. This maintains the connection to the session, enabling access to session-level data and methods.Usage:
Laps | DataFrame
All laps completed by this driver in the session. This property provides lazy-loaded access to the driver’s lap data.Type: Returns Laps (pandas backend) or DataFrame (polars backend)Behavior:
  • Loaded lazily on first access (not fetched until you access this property)
  • Cached after first load for performance
  • Returns empty DataFrame if no laps found
  • Automatically filters session laps to this driver
  • Preserves session context in returned Laps object
Performance:
  • First access may trigger network request if not cached (~50-200ms)
  • Subsequent accesses are instant (cached in memory)
  • Efficient filtering using pandas/polars vectorized operations
Usage:
Common Patterns:

Methods

get_lap(lap_number)

Get a specific lap by number. This is the primary method for accessing individual laps from a driver.
Parameters:
  • lap_number (int): The lap number to retrieve. Must be a positive integer.
Returns:
  • Lap object for the specified lap
Raises:
  • LapNotFoundError: If the lap doesn’t exist for this driver
  • ValueError: If lap_number is invalid (negative, zero, or not an integer)
Behavior Details:
  • Uses optimized O(1) lookup with internal lap index map
  • Validates lap number before lookup
  • Returns a Lap object with full lap data and telemetry access
  • Preserves session context in returned Lap object
  • Raises specific exceptions for better error handling
Performance Characteristics:
  • Time Complexity: O(1) after first call (builds index map on first access)
  • Space Complexity: O(n) for index map where n is number of laps
  • Subsequent calls are extremely fast (dictionary lookup)
Example Usage:
Error Handling:
Use Cases:
  • Analyzing specific race moments (lap 1, pit stop laps, final lap)
  • Comparing performance at different race stages
  • Telemetry analysis for specific laps
  • Incident investigation
  • Tire warm-up analysis (first lap of stint)

get_fastest_lap()

Get this driver’s fastest lap as a single-row DataFrame. This is a convenience method for quickly accessing the driver’s best performance.
Returns:
  • DataFrame: Single-row DataFrame containing the fastest lap data. Returns empty DataFrame if no valid laps found.
Behavior Details:
  • Filters to laps with valid lap times (non-null, non-NaN)
  • Returns the lap with minimum LapTime value
  • Returns empty DataFrame (not None) if no valid laps exist
  • Result is a DataFrame (not a Lap object) for consistency with FastF1
  • Includes all lap columns
Performance Characteristics:
  • Time Complexity: O(n) where n is number of driver’s laps
  • Efficient pandas vectorized operation
  • May use cached lap data if already loaded
Example Usage:
Common Patterns:

get_fastest_lap_tel()

Get telemetry from this driver’s fastest lap. This is a convenience method that combines finding the fastest lap and loading its telemetry in one call.
Returns:
  • DataFrame: Telemetry DataFrame for the fastest lap. Returns empty DataFrame if not found.
Behavior Details:
  • Automatically identifies the fastest lap
  • Loads telemetry for that lap
  • Returns empty DataFrame if no fastest lap or no telemetry available
  • More efficient than calling get_fastest_lap() then loading telemetry separately
  • Uses internal optimization to avoid redundant lookups
Performance Characteristics:
  • Optimized to minimize data fetching
  • May use cached telemetry if available
  • Single method call for convenience
Example Usage:
Use Cases:
  • Quick access to best performance telemetry
  • Driver comparison visualizations
  • Optimal racing line analysis
  • Braking point identification
  • Gear shift analysis
  • DRS effectiveness study

Common Usage Patterns

Complete Driver Analysis

Comparing Drivers



Telemetry

The Telemetry class represents high-frequency data recorded throughout a lap or multiple laps. It inherits from pandas.DataFrame with additional slicing and analysis methods specifically designed for telemetry data. This is one of the most powerful classes in tif1, enabling detailed analysis of driver inputs, car behavior, and racing lines.

Class Overview

Inheritance: pandas.DataFrameTelemetry Module: tif1.models (re-exported from tif1.core) Sampling Rate: Typically 10-20 Hz (10-20 samples per second), resulting in 1000-3000 samples per lap Common Access Patterns:

Properties

Session
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.
str
Driver code for this telemetry data (e.g., “VER”, “HAM”). May be None if telemetry is from multiple drivers.

Available Columns

Telemetry DataFrames contain high-frequency sensor data with the following columns:

Time and Distance

Speed and Engine

Driver Inputs

Position (3D Coordinates)

Lap Context

Driver-Ahead Data (when available)

Note: Not all columns are always present. Use if "ColumnName" in tel.columns to check availability.

Core Methods

slice_by_time(start_time, end_time, pad=0, pad_side="both", interpolate_edges=False)

Slice telemetry by time window. Essential for analyzing specific sections of a lap or comparing the same time window across different laps.
Parameters:
  • start_time: Start time (timedelta, float seconds, or int seconds)
  • end_time: End time (same format as start_time)
  • pad (int, default=0): Number of samples to include before/after the slice
  • pad_side (str, default=“both”): Where to apply padding (“both”, “before”, “after”)
  • interpolate_edges (bool, default=False): Whether to interpolate at slice boundaries (reserved for future use)
Returns:
  • Telemetry DataFrame containing only the specified time window
Behavior Details:
  • Time values can be provided as timedelta, float (seconds), or int (seconds)
  • Automatically adjusts Time column to be zero-based relative to start_time
  • Padding adds extra samples for context
  • Returns empty Telemetry if time window doesn’t exist
Example Usage:

slice_by_lap(ref_laps, pad=0, pad_side="both", interpolate_edges=False)

Slice telemetry by lap reference. Useful for extracting telemetry for specific laps from a larger telemetry dataset.
Parameters:
  • ref_laps: Lap or Laps object to use as reference
  • pad (int, default=0): Number of samples to include before/after
  • pad_side (str, default=“both”): Where to apply padding
  • interpolate_edges (bool, default=False): Whether to interpolate at boundaries
Returns:
  • Telemetry DataFrame for the specified lap(s)
Behavior Details:
  • Extracts telemetry based on lap start/end times or lap numbers
  • Raises ValueError if ref_laps contains multiple drivers
  • Returns empty Telemetry if lap not found
Example Usage:

slice_by_mask(mask, pad=0, pad_side="both")

Slice telemetry using a boolean mask. Powerful for custom filtering based on any condition.
Parameters:
  • mask: Boolean array/Series matching telemetry length
  • pad (int, default=0): Number of samples to include before/after
  • pad_side (str, default=“both”): Where to apply padding
Returns:
  • Telemetry DataFrame containing only masked samples
Raises:
  • ValueError: If mask length doesn’t match telemetry length
Example Usage:

Distance and Position Methods

add_distance() / integrate_distance()

Calculate distance from speed and time. Essential when Distance column is missing.
Returns:
  • add_distance(): Telemetry with Distance column added
  • integrate_distance(): Series with calculated distances
Behavior Details:
  • Integrates speed over time to calculate distance
  • Converts speed from km/h to m/s internally
  • Returns original telemetry if Distance already exists
  • integrate_distance() returns Series without modifying telemetry
Example Usage:

add_relative_distance()

Add normalized distance column (0-1 scale). Useful for comparing laps of different lengths.
Returns:
  • Telemetry with RelativeDistance column (0 = start, 1 = finish)
Example Usage:

Driver-Ahead Methods

add_driver_ahead() / calculate_driver_ahead()

Add driver-ahead information for analyzing battles and overtaking.
Returns:
  • add_driver_ahead(): Telemetry with DriverAhead and DistanceToDriverAhead columns
  • calculate_driver_ahead(): Tuple of (driver_ahead_array, distance_array) or (driver_ahead, distance, reference_tel)
Behavior Details:
  • Currently returns placeholder data (not fully implemented in tif1)
  • Provided for FastF1 compatibility
  • Future versions will include actual driver-ahead calculations
Example Usage:

Data Processing Methods

fill_missing()

Interpolate missing values in numeric columns. Useful for cleaning telemetry data.
Returns:
  • Telemetry with interpolated values
Behavior Details:
  • Interpolates all numeric columns
  • Uses linear interpolation
  • Fills in both directions (forward and backward)
Example Usage:

merge_channels(other, **kwargs)

Merge telemetry from another source using time-based alignment.
Parameters:
  • other: Another Telemetry or DataFrame to merge
  • **kwargs: Additional arguments (for compatibility)
Returns:
  • Telemetry with merged channels
Behavior Details:
  • Uses time-based alignment (merge_asof)
  • Aligns on Time column
  • Adds suffix “_other” to conflicting columns
Example Usage:

resample_channels(rule="1S", **kwargs)

Resample telemetry to a different frequency. Useful for reducing data size or standardizing sampling rates.
Parameters:
  • rule (str, default=“1S”): Resampling frequency (e.g., “1S” = 1 second, “100ms” = 100 milliseconds)
  • **kwargs: Additional arguments (for compatibility)
Returns:
  • Telemetry resampled to specified frequency
Behavior Details:
  • Resamples numeric columns using mean aggregation
  • Interpolates missing values after resampling
  • Useful for reducing data size or aligning different telemetry sources
Example Usage:

Common Usage Patterns

Basic Telemetry Analysis

Comparing Two Laps

Finding Braking Points



SessionResults

The SessionResults class contains race results and final standings for a session. It inherits from pandas.DataFrame, providing a tabular view of how drivers finished the session.

Class Overview

Inheritance: pandas.DataFrameSessionResults Module: tif1.models (re-exported from tif1.core) Common Access Patterns:

Properties

Session
Reference to the parent Session object. Maintains connection to the session for accessing session-level data.

Available Columns

The SessionResults DataFrame typically contains the following columns: Note: Column availability depends on session type and data source.

Usage Examples

Basic Results Access

Analyzing Results


DriverResult

The DriverResult class represents an individual driver’s race result. It inherits from pandas.Series, making it a single row from the SessionResults DataFrame.

Class Overview

Inheritance: pandas.SeriesDriverResult Module: tif1.models (re-exported from tif1.core) Common Access Patterns:

Properties

Session
Reference to the parent Session object.
int/float
Final position (available in Series data). Access via driver_result['Position'].
str
Driver code (available in Series data). Access via driver_result['Driver'].
int/float
Points earned (available in Series data). Access via driver_result['Points'].
str
Finish status (available in Series data). Access via driver_result['Status'].
bool
Whether the driver did not finish (computed property). Returns True if status indicates DNF, retirement, or disqualification.Behavior:
  • Returns True if status is NOT one of: “Finished”, “+1 Lap”, “+2 Laps”, “Not classified”
  • Returns False otherwise
  • Case-insensitive comparison
Usage:

Usage Examples


CircuitInfo

The CircuitInfo class holds information about the circuit layout, including corner locations and track markers. This is a dataclass (not a pandas object) that provides circuit-specific data.

Class Overview

Type: Dataclass Module: tif1.models (re-exported from tif1.core) Common Access Patterns:

Properties

DataFrame
Location of corners on the circuit. DataFrame with columns: X, Y, Number, Letter, Angle, Distance.Columns:
  • X (float): X coordinate of corner
  • Y (float): Y coordinate of corner
  • Number (int): Corner number
  • Letter (str): Corner letter designation (if applicable)
  • Angle (float): Corner angle in degrees
  • Distance (float): Distance along track (populated after add_marker_distance())
Usage:
DataFrame
Location of marshal lights (always empty in tif1 - not available in source data). Provided for FastF1 compatibility.Note: This data is not available through the tif1 data source. The DataFrame will always be empty but maintains the correct column schema.
DataFrame
Location of marshal sectors (always empty in tif1 - not available in source data). Provided for FastF1 compatibility.Note: This data is not available through the tif1 data source. The DataFrame will always be empty but maintains the correct column schema.
float
Rotation of the circuit in degrees. Default is 0.0.Usage:

Methods

add_marker_distance(reference_lap)

Compute the Distance value for each track marker using telemetry from a reference lap. This method populates the Distance column in the corners DataFrame.
Parameters:
  • reference_lap (Lap): A Lap object whose telemetry contains X, Y, and Distance columns
Behavior Details:
  • Uses best-fit approach to match marker positions with telemetry samples
  • For each marker, finds the telemetry sample with minimum squared XY error
  • Assigns that sample’s Distance value to the marker
  • Modifies the corners DataFrame in-place
  • Logs warnings if telemetry is unavailable or missing required columns
  • Requires valid X, Y, and Distance data in the reference lap’s telemetry
Algorithm:
  1. Loads telemetry from reference lap
  2. Filters to samples with valid X, Y, Distance values
  3. For each marker, calculates squared Euclidean distance to all telemetry samples
  4. Assigns the Distance from the closest telemetry sample
Example Usage:
Use Cases:
  • Mapping corner locations to lap distance
  • Analyzing speed through specific corners
  • Comparing corner performance between drivers
  • Visualizing racing lines with corner markers
  • Sector analysis based on corner positions
Error Handling:

Complete Usage Examples

Example 1: Comprehensive Race Analysis

Example 2: Telemetry Comparison Visualization

Example 3: Tire Degradation Analysis



Type Hints

All models support type hints for better IDE integration.

Summary

The models module provides:
  • Object-oriented interface for F1 data
  • Lazy loading for performance
  • Convenient methods for common operations
  • Type hints for IDE support
  • DataFrame-based data access
Use these classes to write clean, maintainable F1 analysis code.

Core API

Session and Driver

Types

Type definitions

Data Schema

Data structure

Examples

Usage examples

Type Hints and IDE Support

All models support comprehensive type hints for better IDE integration, autocomplete, and type checking. This makes development faster and reduces errors.

Type Annotations


Performance Considerations

Lazy Loading

All models use lazy loading for optimal performance:

Efficient Filtering

Use tif1’s filtering methods instead of pandas operations for better performance:

Best Practices

1. Check for Empty Data

Always check if data is available before processing:

2. Use Method Chaining

Chain filtering methods for readable code:

3. Handle Exceptions Properly

Use specific exception types for better error handling:

Summary

The models module provides a comprehensive, intuitive API for F1 data analysis:

Key Takeaways

  1. Laps: Primary interface for lap timing data with powerful filtering methods
  2. Lap: Single lap with telemetry access and timing information
  3. Driver: Driver metadata with access to all their laps
  4. Telemetry: High-frequency sensor data with slicing and analysis methods
  5. SessionResults: Race results and final standings
  6. DriverResult: Individual driver’s race result
  7. CircuitInfo: Circuit layout information and track markers

Core Principles

  • Lazy Loading: Data loaded on-demand for performance
  • Method Chaining: Fluent API for readable code
  • Type Safety: Full type hints for IDE support
  • FastF1 Compatible: Easy migration from FastF1
  • Pandas-Based: Familiar DataFrame/Series interface
  • Performance Optimized: Vectorized operations and intelligent caching

Core API

Session and data loading methods

Types

Type definitions and schemas

Data Schema

Complete data structure reference

Examples

Real-world usage examples
Last modified on May 8, 2026