traffic Python Library

repository·master·Indexed 19 days ago

https://github.com/xoolive/traffic

A Python toolbox for manipulating and analysing air traffic data, focusing on trajectories, airspaces, and ADS-B data sources like the OpenSky Network. It provides core abstractions such as Flight, Traffic, and Sector for GIS operations, as well as algorithms for trajectory filtering (including 6D Kalman filters), ground movement detection, and airport metadata inference.

Tokens
63.2K
Snippets
216
Records
276
Agent score
65%

What's inside traffic

  1. Overview of the traffic library

    master

    The traffic library is a toolbox for processing and analysing air traffic data, specifically designed for trajectories and airspaces.

    Key Capabilities:

    • Data Access: Provides methods for analyzing trajectories and airspaces. When specific analysis methods are not used, you can access the underlying data directly via a pandas dataframe attribute.
    • Data Sources: Parses and accesses ADS-B traffic from sources like the OpenSky Network or Eurocontrol DDR files. It is designed to be extensible to other sources.
    • Visualization:
      • Static: Exports images via Matplotlib and Cartopy.
      • Dynamic (Jupyter): Supports ipyleaflet and altair.
      • Other Formats: Supports exports to CesiumJS and Google Earth.
  2. Explore the traffic visualization example gallery

    master

    The traffic project provides a gallery of visualization examples demonstrating various ways to process and analyze air traffic data. You can use these examples as inspiration for visualizing:

    • Aircraft trajectory patterns: Commercial aviation, calibration flights (including SAVAN trajectories), special events like the Tour de France, and zero gravity flights.
    • Air traffic control: Controller activities, landing configurations, landing sequences, and in-flight emergencies (e.g., squawk 7700).
    • Air traffic density: Heatmaps and the impact of global events (like COVID-19) or regional flight bans (like the Russian flight ban affecting Kaliningrad).
    • Environmental impacts: Geomagnetic declination, Mode S based windfields, and sun elevation effects on trajectories.

    For community-driven use cases, refer to third-party examples such as 'Thunderbolts and lightning' or 'Flight Information Regions' on Spatial Awareness and ObservableHQ.

  3. How to choose a map projection

    master

    When plotting trajectories on a map, you must transform spherical coordinates (latitude/longitude) onto a 2D plane using a projection. The choice depends on your data and the area being visualized:

    • PlateCarree(): The most basic projection (plotting latitude on the y-axis and longitude on the x-axis).
    • Mercator(): Distorts latitude so that lines of constant bearing appear straight. Good for general use if you are unsure.
    • Conformal Projections: Useful for smaller areas (like specific countries) as they preserve distances locally.
    • Regional/Official Projections: Many countries use specific projections like Lambert93() (France), GaussKruger() (Germany), Amersfoort() (Netherlands), or OSGB() (British Islands).
    • EuroPP(): A decent choice when plotting trajectories specifically over Western Europe.

    The cartes library (which traffic uses for visualization) provides these projections for use with Matplotlib and Altair.

  4. Use Kalman filters for 6D state smoothing

    master

    The KalmanFilter6D and KalmanSmoother6D classes apply filtering to a 6D state vector consisting of: latitude, longitude, altitude, track angle, groundspeed, and vertical rate.

    Important: Coordinate Projection

    Because these filters operate on a 6D state vector, they require the flight data to be projected into a Cartesian (x, y) coordinate system first. You must call .compute_xy() on your Flight object before applying these filters.

    • KalmanFilter6D: A standard Kalman filter applied to the 6D state.
    • KalmanSmoother6D: A two-pass Kalman smoother that averages the error covariance from both sides of a data point, resulting in smoother trajectories.
    from traffic.algorithms.filters.kalman import KalmanFilter6D, KalmanSmoother6D
    from cartes.crs import EuroPP
    
    # 1. Project to x, y (e.g., using EuroPP projection)
    # 2. Apply the filter
    filtered_kalman = noisy_landing.compute_xy(EuroPP()).filter(KalmanFilter6D())
    
    # Alternatively, using the smoother
    smoother = noisy_landing.compute_xy(EuroPP()).filter(KalmanSmoother6D())
  5. Improve fuel flow estimation accuracy

    master

    Several factors influence the accuracy of the OpenAP fuel flow estimation. You can improve results by addressing the following:

    1. Mass Accuracy

    Providing a more accurate initial_mass helps. If the aircraft weight is known along the trajectory, you can pass the maximum weight to the method.

    openap = resampled.fuelflow(typecode="A320", initial_mass=resampled.weight_max)

    2. Engine Specification

    Engine types have a serious impact on estimation. If the specific engine model is known, pass it via the engine parameter.

    openap = resampled.fuelflow(typecode="A320", engine="CFM56-5B5")

    3. Wind Compensation

    Wind affects True Air Speed (TAS) calculations. To account for wind:

    • Use Extended Mode S data where available via Traffic.query_ehs.
    • Interpolate wind from GRIB files provided by Meteorological Agencies to compute TAS.

    4. Sampling Rate

    While changing the sampling rate (e.g., using .resample("20s")) can accelerate processing, it has little impact on the final estimation accuracy.

  6. Use Sector objects to define airspace boundaries

    master

    A Sector object defines a volume of airspace. It is composed of ShapelyMixin objects (geographic shapes) associated with a specific altitude range (lower and upper altitude).

    Primary Use Case: Sectors are used as spatial filters for Flight objects. You can use a Sector to:

    • Intersect: Determine if a Flight trajectory passes through the sector.
    • Clip: Extract only the portion of a Flight trajectory that exists within the sector's boundaries.
  7. Use Flight objects for trajectory analysis and GIS operations

    master

    A Flight object represents a single aircraft trajectory. It expects a pandas.DataFrame containing latitude, longitude, altitude, and timestamp.

    Capabilities:

    • Metadata Access: Retrieve start/end dates, aircraft registration, and other flight-specific attributes.
    • GIS Operations: Perform spatial analysis such as checking for intersections with a Sector or clipping a trajectory within a Sector.
    • Exporting: Save flight data to multiple formats including csv, hdf5, matplotlib, kml, and czml.
  8. Understand the core Flight and Traffic abstractions

    master

    The traffic library is built around two primary data structures, both of which are backed by pandas.DataFrame objects:

    1. Flight: Represents a single trajectory. It provides methods for time-based slicing, attribute access, and visualization. You can access the underlying DataFrame using the .data property.
    2. Traffic: Represents a collection of trajectories. In a Traffic object, all trajectories are flattened into a single pandas.DataFrame. The object uses heuristics (like flight_id, icao24, or timestamp + icao24) to identify and separate individual flights.

    Trajectories can be imported from sample sets, downloaded from OpenSky, loaded from tabular files (CSV, JSON, Parquet), or decoded from raw ADS-B signals.

    from traffic.data.samples import belevingsvlucht
    # belevingsvlucht is a Flight object
    print(belevingsvlucht)
    
    from traffic.data.samples import quickstart
    # quickstart is a Traffic object
    print(quickstart)
  9. Core abstractions in the traffic library

    master

    The traffic library is built around three primary core classes designed for different levels of air traffic data handling:

    • traffic.core.Flight: Represents a single aircraft trajectory. It is a wrapper around a pandas.DataFrame providing specialized methods for trajectory analysis.
    • traffic.core.Traffic: Represents a collection of aircraft trajectories. Like Flight, it wraps a pandas.DataFrame and provides efficient methods for analyzing multiple trajectories simultaneously.
    • traffic.core.Airspace: Represents airspaces and sectors. It uses shapely geometries to enable geometrical analysis of spatial regions.
  10. Concatenate multiple flights using the `|` operator

    master

    The | (or or_) operator in traffic is used to concatenate Jupyter representations of eligible objects. You can use functools.reduce to apply this operator across a collection of flights to create a single combined representation.

    from functools import reduce
    from operator import or_
    
    # If t_surveys is a Traffic object containing multiple flights:
    # This will do surveys.flight1 | surveys.flight2 | surveys.flight3 | etc.
    combined_view = reduce(or_, t_surveys)
  11. Understanding radio-navigation systems (VOR, DME, ILS)

    master

    Calibration trajectories are used to verify the accuracy of several radio-navigation systems:

    • VOR (VHF Omnidirectional Range): Ground stations send an omnidirectional signal and a directional signal. Aircraft measure the phase difference to determine the bearing from the station.
    • DME (Distance Measuring Equipment): Often co-located with VORs. The aircraft sends a signal that the ground station repeats after a 50 μs delay. The aircraft measures the time delay to estimate distance.
    • ILS (Instrument Landing System): Provides lateral guidance (Localizer/LOC) and vertical guidance (Glide Slope/GS) for landing.

    Aircraft perform periodic checks by flying circles at defined distances and along specific radials to ensure these systems meet strict accuracy thresholds.