traffic.core.traffic

class traffic.core.Traffic(data, *args, **kwargs)

Bases: HBoxMixin, GeographyMixin

Traffic is the abstraction representing a collection of Flights. When Flight objects are summed up, the resulting structure is a Traffic.

Data is all flattened into one single pandas DataFrame and methods are provided to properly access (with the bracket notation) and iterate on each Flight in the structure.

On top of basic methods and properties (aircraft, callsigns, flight_ids, start_time, end_time) and data preprocessing (most methods available on Flight), more complex algorithms like closest point of approach and clustering (more to come) are available.

Note

When methods need to be chained on each trajectory contained in the collection, lazy iteration and evaluation is in place. This means that applying such a method on a Traffic structure will only stack operations without evaluating them.

class LazyTraffic(wrapped_t, stacked_ops, iterate_kw=None, tqdm_kw=None)

In the following example, lazy_t is not evaluated:

>>> lazy_t = t.filter().resample('10s')
>>> type(t_lazy)
traffic.core.lazy.LazyTraffic

You need to call the .eval() method for that.

LazyTraffic.eval(max_workers=1, desc=None, cache_file=None)

The result can only be accessed after a call to eval().

Parameters:
  • max_workers (int) – (default: 1) Multiprocessing is usually worth it. However, a sequential processing is triggered by default. Keep the value close to the number of cores of your processor. If memory becomes a problem, stick to the default.

  • desc (None | str) – (default: None) If not None, a tqdm progressbar is displayed with this parameter.

  • cache_file (str | Path | None) – (default: None) If not None, store the results in cache_file and load the results from the file if it exists.

Return type:

None | ‘Traffic

Example usage:

The following call

>>> t_lazy.eval(max_workers=4, desc="preprocessing")

is equivalent to the multiprocessed version of

>>> Traffic.from_flights(
...     flight.filter().resample("10s")
...     for flight in tqdm(t, desc="preprocessing")
... )

When many operations are stacked, this call is more efficient, esp. on large structures, than as many full iterations on the Traffic structure.

Backward compatibility is ensured by an automatic call to eval() with default options.

>>> t_lazy.to_pickle("output_file.pkl")
WARNING:root:.eval() has been automatically appended for you.
Check the documentation for more options.

Tip

Sample traffic structures are provided for testing purposes in module traffic.data.samples

Scattergeo(**kwargs)

Create a Scattermapbox with Plotly.

Requires the plotly package (optional dependency).

Return type:

Scattergeo

Scattermapbox(**kwargs)

Create a Scattermapbox with Plotly.

Requires the plotly package (optional dependency).

Return type:

Scattermapbox

agg_latlon(resolution=None, **kwargs)

Aggregates values of a traffic over a grid of lat/lon.

The resolution of the grid is passed as a dictionary parameter. By default, the grid is made by rounding latitudes and longitudes to the nearest integer values. dict(latitude=2, longitude=4) will take 2 values per integer latitude intervals (43, 43.5, 44, …) and 4 values per integer longitude intervals (1, 1.25, 1.5, 1.75, …).

The kwargs specifies how to aggregate values: :rtype: DataFrame

  • altitude="mean" would average all values in the given cell;

  • timestamp="count" would return the number of samples per cell;

  • icao24="nunique" would return the number of different aircraft int the given cell.

The returned pandas DataFrame is indexed over latitude and longitude values. It is conveniently chainable with the .to_xarray() method in order to plot density heatmaps.

Example usage:

switzerland.agg_latlon(
    resolution=dict(latitude=10, longitude=10),
    vertical_rate="mean",
    timestamp="count"
)

See how to make flight density heatmaps

agg_time(*args, **kwargs: Any) LazyTraffic

Aggregate features on time windows.

The following is performed: :rtype: LazyTraffic

  • a new column rounded rounds the timestamp at the given rate;

  • the groupby/agg is operated with parameters passed in kwargs;

  • if merge is True, the new column in merged into the Flight, otherwise a pd.DataFrame is returned.

For example:

>>> f.agg_time('3T', groundspeed='mean')

returns a Flight with a new column groundspeed_mean with groundspeed averaged per intervals of 3 minutes.

Warning

This method will be stacked for lazy evaluation.

agg_xy(resolution, projection=None, **kwargs)

Aggregates values of a traffic over a grid of x/y, with x and y computed by compute_xy().

Parameters:
  • resolution (None | dict[str, float]) – The resolution of the grid is passed as a dictionary parameter. By default, the grid is made by rounding x and y to the lower ten kilometer values. dict(x=5000, y=3000) will take 1 value per 5000 meters for x (10000, 15000, 20000, …) and 1 value per 3000 meters for y (9000, 12000, 15000, 18000, 20000, …).

  • projection (None | pyproj.Proj | ‘crs.Projection) – is used to compute the x and y values.

The kwargs specifies how to aggregate values:

  • altitude="mean" would average all values in the given cell;

  • timestamp="count" would return the number of samples per cell;

  • icao24="nunique" would return the number of different aircraft int the given cell.

Return type:

pd.DataFrame

Returns:

a DataFrame indexed over x and y values. It is conveniently chainable with the .to_xarray() method in order to plot density heatmaps.

Example usage:

belevingsvlucht.agg_xy(
    resolution=dict(x=3e3, y=3e3),
    vertical_rate="mean",
    timestamp="count"
)
airborne()

Returns the airborne part of the Traffic.

The airborne part is determined by an onground flag or null values in the altitude column. :rtype: Optional[Traffic]

Note

This method will use the :class:Flight implementation when stacked for lazy evaluation.

aircraft_data()

Add registration and aircraft typecode based on the aircraft database.

Return type:

Traffic

all(*args, **kwargs) LazyTraffic

Returns the concatenation of segments returned by flight.method().

Example usage:

Return type:

LazyTraffic

>>> flight.all("go_around")
>>> flight.all("runway_change")
>>> flight.all('aligned_on_ils("LFBO")')
>>> flight.all(lambda f: f.aligned_on_ils("LFBO"))

Warning

This method will be stacked for lazy evaluation.

apply_time(*args, **kwargs: Any) LazyTraffic

Apply features on time windows.

The following is performed: :rtype: LazyTraffic

  • a new column rounded rounds the timestamp at the given rate;

  • the groupby/apply is operated with parameters passed in apply;

  • if merge is True, the new column in merged into the Flight, otherwise a pd.DataFrame is returned.

For example:

>>> f.agg_time("10 min", straight=lambda df: Flight(df).distance())

returns a Flight with a new column straight with the great circle distance between points sampled every 10 minutes.

Warning

This method will be stacked for lazy evaluation.

assign(*args, **kwargs)

Applies the Pandas assign() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

assign_id(*args, **kwargs) LazyTraffic

Assigns a flight_id to trajectories present in the structure.

The heuristics with iterate on flights based on flight_id (if the feature is present) or of icao24, callsign and intervals of time without recorded data.

The flight_id is created according to a pattern passed in parameter, by default based on the callsign (if any) and an incremented index.

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.

callsigns

Return all the different callsigns in the DataFrame

centroid(nb_samples, features=None, projection=None, transformer=None, max_workers=1, *args, **kwargs)

Returns the trajectory in the Traffic that is the closest to all other trajectories. :rtype: Flight

Warning

Remember the time and space complexity of this method is in O(n^2).

*args and **kwargs are passed as is to scipy.spatial.distance.pdist()

clean_invalid(threshold=10)

Removes irrelevant data from the Traffic DataFrame.

Data that has been downloaded from the OpenSky Impala shell often contains faulty data, esp. because of faulty callsigns (wrongly decoded? faulty crc?) and of automatically repeated positions (see last_position).

This methods is an attempt to automatically clean this data.

Data uncleaned could result in the following count of messages associated to aircraft icao24 02008b which could be easily removed.

                       count
icao24  callsign
02008b  0  221         8
        2AM2R1         4
        2N D           1
        3DYCI          1
        3N    I8       1
        3Q G9 E        1
        6  V X         1
        [...]
Return type:

Traffic

clip(*args, **kwargs) LazyTraffic

Clips the trajectory to a given shape.

For a shapely Geometry, the first time of entry and the last time of exit are first computed before returning the part of the trajectory between the two timestamps.

Most of the time, aircraft do not repeatedly come out and in an airspace, but computation errors may sometimes give this impression. As a consequence, the clipped trajectory may have points outside the shape. :rtype: LazyTraffic

Warning

Altitudes are not taken into account.

Warning

This method will be stacked for lazy evaluation.

closest_point_of_approach(lateral_separation, vertical_separation, projection=None, round_t='d', max_workers=4)

Computes a Closest Point of Approach (CPA) dataframe for all pairs of trajectories candidates for being separated by less than lateral_separation in vertical_separation.

The problem of iterating over pairs of trajectories is of unreasonable complexity O(n**2). Therefore, instead of computing the CPA between all pairs of trajectory, we do it for all pairs of trajectories coming closer than a given lateral_separation and vertical_separation.

Return type:

Optional[CPA]

lateral_separation: float (in meters)

Depending on your application, you could start with 10 * 1852 (for 10 nautical miles)

vertical_separation: float (in ft)

Depending on your application, you could start with 1500 (feet)

projection: pyproj.Proj, crs.Projection, None

a first filtering is applied on the bounding boxes of trajectories, expressed in meters. You need to provide a decent projection able to approximate distances by Euclide formula. By default, EuroPP() projection is considered, but a non explicit argument will raise a warning.

round_t: str

an additional column will be added in the DataFrame to group trajectories by relevant time frames. Distance computations will be considered only between trajectories flown in the same time frame. By default, the ‘d’ pandas freq parameter is considered, to group trajectories by day, but other ways of splitting (‘h’) may be more relevant and impact performance.

max_workers: int

distance computations are spread over a given number of processors.

Returns a CPA DataFrame wrapper.

clustering(clustering, nb_samples, features=None, *args, projection=None, transform=None, max_workers=1, return_traffic=True)

Computes a clustering of the trajectories, add labels in a column cluster.

The method: :rtype: Clustering

  • resamples all trajectories with the same number of samples nb_samples (no default value);

  • if need be, computes x and y coordinates based on projection through a call to compute_xy() (no default value);

  • if need be, apply a transformer to the resulting X matrix. You may want to consider StandardScaler();

  • generates the appropriate structure for a call to the usual sklearn API that is a class with a fit() method and a predict() method or a labels_ attribute;

  • returns a Clustering object, on which to call fit(), predict() or fit_predict() methods. Predicting methods return the original Traffic DataFrame with an additional cluster column.

Example usage:

>>> from cartes.crs import EuroPP
>>> from sklearn.cluster import DBSCAN
>>> from sklearn.preprocessing import StandardScaler
>>>
>>> t_dbscan = traffic.clustering(
...     nb_samples=15,
...     projection=EuroPP(),
...     clustering=DBSCAN(eps=1.5, min_samples=10),
...     transform=StandardScaler(),
... ).fit_predict()
>>> t_dbscan.groupby(["cluster"]).agg({"flight_id": "nunique"})
            flight_id
cluster
-1          15
0           29
1           13
2           24
3           24
compute_latlon_from_xy(projection)

Enrich a DataFrame with new longitude and latitude columns computed from x and y columns. :rtype: Self

Warning

Make sure to use as source projection the one used to compute 'x' and 'y' columns in the first place.

compute_wind(*args, **kwargs) LazyTraffic

Computes the wind triangle for each timestamp.

This method requires groundspeed, track, true airspeed (TAS), and heading features. The groundspeed and the track angle are usually available in ADS-B messages; the heading and the true airspeed may be decoded in EHS messages. :rtype: LazyTraffic

Note

Check the query_ehs() method to find a way to enrich your flight with such features. Note that this data is not necessarily available depending on the location.

Warning

This method will be stacked for lazy evaluation.

compute_xy(projection=None)

Enrich the structure with new x and y columns computed through a projection of the latitude and longitude columns.

The source projection is WGS84 (EPSG 4326). The default destination projection is a Lambert Conformal Conical projection centred on the data inside the dataframe.

Other valid projections are available: :rtype: Self

  • as pyproj.Proj objects;

  • as cartopy.crs.Projection objects.

convert_dtypes(*args, **kwargs)

Applies the Pandas convert_dtypes() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

cumulative_distance(*args, **kwargs: Any) LazyTraffic

Enrich the structure with new cumdist column computed from latitude and longitude columns.

The first cumdist value is 0, then distances are computed (in nautical miles) and summed between consecutive positions. The last value is the total length of the trajectory.

When the compute_gs flag is set to True (default), an additional compute_gs is also added. This value can be compared with the decoded groundspeed value in ADSB messages.

When the compute_track flag is set to True (default), an additional compute_track is also added. This value can be compared with the decoded track value in ADSB messages.

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.

diff(*args, **kwargs: Any) LazyTraffic

Assign differential versions of features to new columns.

Return type:

LazyTraffic

>>> flight.diff("track")

The two following commands are equivalent:

>>> flight.diff(["track", "heading"])
>>> flight.diff(track="track_diff", heading="heading_diff")

Warning

This method will be stacked for lazy evaluation.

distance(*args, **kwargs) LazyTraffic

Computes the distance from a Flight to another entity.

The behaviour is different according to the type of the second element: :rtype: LazyTraffic

  • if the other element is None (i.e. flight.distance()), the method returns a distance in nautical miles between the first and last recorded positions in the DataFrame.

  • if the other element is a Flight, the method returns a pandas DataFrame with corresponding data from both flights, aligned with their timestamps, and two new columns with lateral and vertical distances (resp. in nm and ft) separating them.

  • otherwise, the same Flight is returned enriched with a new column (by default, named “distance”) with the distance of each point of the trajectory to the geometrical element.

Warning

  • An Airspace is (currently) considered as its flattened representation

  • Computing a distance to a polygon is quite slow at the moment. Consider a strict resampling (e.g. one point per minute, “1 min”) before calling the method.

Warning

This method will be stacked for lazy evaluation.

drop(*args, **kwargs)

Applies the Pandas drop() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

drop_duplicates(*args, **kwargs)

Applies the Pandas drop_duplicates() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

end_time

Returns the latest timestamp in the DataFrame.

feature_gt(*args, **kwargs) LazyTraffic

Returns True if feature(flight) is greater than value.

This is fully equivalent to f.longer_than(“1 minute”):

Return type:

LazyTraffic

>>> f.feature_gt("duration", pd.Timedelta('1 minute'))
True

This is equivalent to f.max(‘altitude’) > 35000:

>>> f.feature_gt(lambda f: f.max("altitude"), 35000)
True

The second one can be useful for stacking operations during lazy evaluation.

Warning

This method will be stacked for lazy evaluation.

feature_lt(*args, **kwargs) LazyTraffic

Returns True if feature(flight) is less than value.

This is fully equivalent to f.shorter_than(“1 minute”):

Return type:

LazyTraffic

>>> f.feature_lt("duration", pd.Timedelta('1 minute'))
True

This is equivalent to f.max(‘altitude’) < 35000:

>>> f.feature_lt(lambda f: f.max("altitude"), 35000)
True

The second one can be useful for stacking operations during lazy evaluation.

Warning

This method will be stacked for lazy evaluation.

fillna(*args, **kwargs)

Applies the Pandas fillna() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

filter(*args, **kwargs: int | tuple[int]) LazyTraffic

Filters a trajectory with predefined methods.

Parameters:
  • filter – (default: FilterAboveSigmaMedian) is one of the filters predefined in traffic.algorithms.filters or any filter implementing the Filter protocol. Use “aggressive” for an experimental filter by @krumjan

  • strategy

    (default: backward fill followed by forward fill) is applied after the filter to deal with resulting NaN values.

    • Explicitely specify to None if NaN values should be left as is.

    • lambda x: x.interpolate() may be a smart strategy

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.

final(*args, **kwargs) LazyTraffic

Returns the final (last) segment of trajectory yielded by flight.method()

Return type:

LazyTraffic

>>> flight.final("go_around")
>>> flight.final("runway_change")
>>> flight.final(lambda f: f.aligned_on_ils("LFBO"))

Warning

This method will be stacked for lazy evaluation.

first(*args, **kwargs: Any) LazyTraffic

Returns the first n days, hours, minutes or seconds of the Flight.

The elements passed as kwargs as passed as is to the datetime.timedelta constructor.

Example usage:

Return type:

LazyTraffic

>>> flight.first(minutes=10)
>>> flight.first("1h")
>>> flight.first(10)  # seconds by default

Warning

This method will be stacked for lazy evaluation.

flight_ids

Return all the different flight_id in the DataFrame

classmethod from_file(filename, **kwargs)

Read data from various formats.

This class method dispatches the loading of data in various format to the proper pandas.read_* method based on the extension of the filename. Potential compression of the file is inferred by pandas itself based on the extension. :rtype: Self

Other extensions return None. Specific arguments may be passed to the underlying pandas.read_* method with the kwargs argument.

Example usage:

>>> from traffic.core import Traffic
>>> t = Traffic.from_file(filename)
classmethod from_flights(flights)

Creates a Traffic structure from all flights passed as an iterator or iterable.

Return type:

Optional[Traffic]

classmethod from_fr24(metadata, trajectories)

Parses data as usually provided by FlightRadar24.

When FlightRadar24 provides data excerpts from their database, they usually provide:

Parameters:
  • metadata (str | Path) – a CSV file with metadata

  • trajectories (str | Path) – a zip file containing one file per flight with trajectory information.

Return type:

Traffic

Returns:

a regular Traffic object.

generation(generation, features=None, scaler=None)

Fits a generative model on the traffic.

Return type:

Generation

The method:
  • extracts features in underlying Traffic DataFrame to define an X matrix.

  • if need be, apply a scaler to the resulting X matrix. You may want to consider StandardScaler();

  • returns a Generation object with a generation model fitted on X. You can call sample() on this returned object to generate new trajectories.

geoencode(*args, **kwargs)
Return type:

NoReturn

Danger

This method is not implemented.

groupby(*args, **kwargs)

Applies the Pandas groupby() method to the underlying pandas DataFrame.

Return type:

DataFrameGroupBy

has(*args, **kwargs) LazyTraffic

Returns True if flight.method() returns a non-empty iterator.

Example usage:

Return type:

LazyTraffic

>>> flight.has("go_around")
>>> flight.has("runway_change")
>>> flight.has(lambda f: f.aligned_on_ils("LFBO"))

Warning

This method will be stacked for lazy evaluation.

icao24

Return all the different icao24 aircraft ids in the DataFrame

inside_bbox(bounds)

Returns the part of the DataFrame with coordinates located within the bounding box of the shape passed in parameter. :rtype: Optional[TypeVar(T, bound= GeographyMixin)]

The bounds parameter can be:

  • an Airspace,

  • a shapely Geometry,

  • a tuple of floats (west, south, east, north)

Note

This method will use the :class:Flight implementation when stacked for lazy evaluation.

iterate(on=['icao24', 'callsign'], by=None, nb_flights=None)

Iterates over Flights contained in the Traffic structure.

Default iteration calls this method with default arguments:

Return type:

Iterator[Flight]

>>> for flight in t:
...     pass

is equivalent to:

>>> for flight in t.iterate():
...     pass

However the it may be beneficial to specify the by parameter:

  • as a pandas DataFrame with callsign and or icao24 columns, it defines a subset of Flights to select.

  • as a a string, by defines the minimum time range without data for a flight.

If the callsign shouldn’t be used for iteration, you may specify it using the on keyword argument.

iterate_lazy(iterate_kw=None, tqdm_kw=None)

Triggers a lazy iteration on the Traffic structure.

Default iteration calls this method with default arguments:

Return type:

LazyTraffic

>>> t.filter()

is equivalent to:

>>> t.iterate_lazy().filter()

However the it may be beneficial to specify the by parameter:

  • as a pandas DataFrame with callsign and or icao24 columns, it defines a subset of Flights to select.

  • as a a string, by defines the minimum time range without data for a flight.

You may also select parameters to pass to a tentative tqdm progressbar.

landing_at(*args, **kwargs) LazyTraffic

Returns True if the flight lands at the given airport. :rtype: LazyTraffic

Warning

This method will be stacked for lazy evaluation.

last(*args, **kwargs: Any) LazyTraffic

Returns the last n days, hours, minutes or seconds of the Flight.

The elements passed as kwargs as passed as is to the datetime.timedelta constructor.

Example usage:

Return type:

LazyTraffic

>>> flight.last(minutes=10)
>>> flight.last("1h")
>>> flight.last(10)  # seconds by default

Warning

This method will be stacked for lazy evaluation.

line_geo(**kwargs)

Create a line plot with Plotly.

Requires the plotly package (optional dependency).

Return type:

Figure

line_mapbox(mapbox_style='carto-positron', **kwargs)

Create a line plot with Plotly.

Requires the plotly package (optional dependency).

Return type:

Figure

longer_than(*args, **kwargs) LazyTraffic

Returns True if flight duration is longer than value. :rtype: LazyTraffic

Warning

This method will be stacked for lazy evaluation.

max_split(*args, **kwargs) LazyTraffic

Returns the biggest (by default, longest) part of trajectory.

Example usage:

Return type:

LazyTraffic

>>> from traffic.data.samples import elal747
>>> elal747.query("altitude < 15000").max_split()
Flight ELY1747
aircraft: 738043 · 🇮🇱 4X-ELC (B744)
origin: LIRF (2019-11-03 12:14:40+00:00)
destination: LLBG (2019-11-03 14:13:00+00:00)

In this example, the fancy part of the trajectory occurs below 15,000 ft. The command extracts the plane pattern.

Warning

This method will be stacked for lazy evaluation.

merge(*args, **kwargs)

Applies the Pandas merge() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

next(*args, **kwargs) LazyTraffic

Returns the first segment of trajectory yielded by flight.method()

Return type:

LazyTraffic

>>> flight.next("go_around")
>>> flight.next("runway_change")
>>> flight.next(lambda f: f.aligned_on_ils("LFBO"))

Warning

This method will be stacked for lazy evaluation.

phases(*args, **kwargs) LazyTraffic

Assign a flight phase to each timestamp of a flight using OpenAP phase detection fuzzy logic method.

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.

pipe(*args: Any, **kwargs: Any) LazyTraffic

Applies func to the object. :rtype: LazyTraffic

Warning

The logic is similar to that of pipe() method, but the function applies on T, not on the DataFrame.

Warning

This method will be stacked for lazy evaluation.

plot(ax, nb_flights=None, **kwargs)

Plots each trajectory on a Matplotlib axis.

Each Flight supports Cartopy axis as well with automatic projection. If no projection is provided, a default PlateCarree is applied.

Example usage:

Return type:

None

>>> from cartes.crs import EuroPP
>>> fig, ax = plt.subplots(1, subplot_kw=dict(projection=EuroPP()))
>>> t.plot(ax, alpha=.5)
plot_wind(ax, resolution=None, threshold=10, filtered=False, **kwargs)

Plots the wind field seen by the aircraft on a Matplotlib axis.

The Flight supports Cartopy axis as well with automatic projection. If no projection is provided, a default PlateCarree is applied.

The resolution argument may be: :rtype: List[Artist]

  • a dictionary, e.g dict(latitude=4, longitude=4), if you want a grid with a resolution of 4 points per latitude and longitude degree.

  • None (default) for dict(latitude=1, longitude=1)

Example usage:

>>> from cartes.crs import Mercator
>>> fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator()))
>>> (
...     traffic
...     .resample("1s")
...     .query('altitude > 10000')
...     .compute_wind()
...     .eval()
...     .plot_wind(ax, alpha=.5)
... )
query(query_str, *args, **kwargs)

Applies the Pandas query() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Optional[Self]

query_ehs(*args, **kwargs: Any) LazyTraffic

Extends data with extra columns from EHS messages.

By default, raw messages are requested from the OpenSky Network database. :rtype: LazyTraffic

Warning

Making a lot of small requests can be very inefficient and may look like a denial of service. If you get the raw messages using a different channel, you can provide the resulting dataframe as a parameter. See the page about OpenSky Impala access

The data parameter expect three columns: icao24, rawmsg and mintime, in conformance with the OpenSky API.

Note

Read more about access to the OpenSky Network database here

Warning

This method will be stacked for lazy evaluation.

query_opensky(*args, **kwargs: Any) LazyTraffic

Returns data from the same Flight as stored in OpenSky database.

This may be useful if you write your own parser for data from a different channel. The method will use the callsign and icao24 attributes to build a request for current Flight in the OpenSky Network database.

The kwargs argument helps overriding arguments from the query, namely start, stop, callsign and icao24.

Returns None if no data is found. :rtype: LazyTraffic

Note

Read more about access to the OpenSky Network database here

Warning

This method will be stacked for lazy evaluation.

rename(*args, **kwargs)

Applies the Pandas rename() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

replace(*args, **kwargs)

Applies the Pandas replace() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

resample(*args, **kwargs) LazyTraffic

Resample the trajectory at a given frequency or for a target number of samples.

Parameters:
  • rule

    • If the rule is a string representing Offset aliases for time frequencies is passed, then the data is resampled along the timestamp axis, then interpolated (according to the how parameter).

    • If the rule is an integer, the trajectory is resampled to the given number of evenly distributed points per trajectory.

  • how

    (default: "interpolate")

    • When the parameter is a string, the method applies to all columns

    • When the parameter is a dictionary with keys as methods (e.g. "interpolate", "ffill") and names of columns as values. Columns not included in any value are left as is.

  • interpolate_kw

    (default: {})

    • A dictionary with keyword arguments that will be passed to the pandas :py:method:`pandas.Series.interpolate` method.

      Example usage: To specify a fifth-degree polynomial interpolation, you can pass the following dictionary:

      
      

      interpolate_kw = {“method”: “polynomial”, “order”: 5}

  • projection

    (default: None)

    • By default, lat/lon are resampled with a linear interpolation;

    • If a projection is passed, the linear interpolation is applied on the x and y dimensions, then lat/lon are reprojected back;

    • If the projection is a string parameter, e.g. "lcc", a projection is created on the fly, centred on the trajectory. This approach is helpful to fill gaps along a great circle.

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.

reset_index(*args, **kwargs)

Applies the Pandas reset_index() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

sample(n=None)

Returns a random sample of traffic data.

Parameters:
  • self – An instance of the Traffic class.

  • n (Optional[int]) – An integer specifying the number of samples to take from the dataset. Default is None, in which case a single value is returned.

Return type:

None | Traffic

Returns:

A Traffic of n random sampled flights.

scatter_geo(**kwargs)

Create a scatter plot with Plotly.

Requires the plotly package (optional dependency).

Return type:

Figure

scatter_mapbox(mapbox_style='carto-positron', **kwargs)

Create a scatter plot with Plotly.

Requires the plotly package (optional dependency).

Return type:

Figure

shorter_than(*args, **kwargs) LazyTraffic

Returns True if flight duration is shorter than value. :rtype: LazyTraffic

Warning

This method will be stacked for lazy evaluation.

simplify(*args, **kwargs) LazyTraffic

Simplifies a trajectory with Douglas-Peucker algorithm.

The method uses latitude and longitude, projects the trajectory to a conformal projection and applies the algorithm. If x and y features are already present in the DataFrame (after a call to compute_xy for instance) then this projection is taken into account.

The tolerance parameter must be defined in meters. :rtype: LazyTraffic

  • By default, a 2D version of the algorithm is called, unless you pass a column name for altitude.

  • You may scale the z-axis for more relevance (z_factor). The default value works well in most situations.

The method returns a Flight or a 1D mask if you specify return_mask=True.

See also: How to simplify or resample a trajectory?

Warning

This method will be stacked for lazy evaluation.

sort_values(by, **kwargs)

Applies the Pandas sort_values() method to the underlying pandas DataFrame and get the result back in the same structure.

Return type:

Self

start_time

Returns the earliest timestamp in the DataFrame.

summary(*args, **kwargs) LazyTraffic

Returns a summary of the current Flight structure containing featured attributes.

Example usage:

Return type:

LazyTraffic

>>> t.summary(['icao24', 'start', 'stop', 'duration'])

Consider monkey-patching properties to the Flight class if you need more information in your summary dictionary.

Warning

This method will be stacked for lazy evaluation.

takeoff_from(*args, **kwargs) LazyTraffic

Returns True if the flight takes off from the given airport. :rtype: LazyTraffic

Warning

This method will be stacked for lazy evaluation.

to_csv(filename, *args, **kwargs)

Exports to CSV format.

Options can be passed to pandas.DataFrame.to_csv() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_excel(filename, *args, **kwargs)

Exports to Excel format.

Options can be passed to pandas.DataFrame.to_excel() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_feather(filename, *args, **kwargs)

Exports to feather format.

Options can be passed to pandas.DataFrame.to_feather() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_hdf(filename, *args, **kwargs)

Exports to HDF format.

Options can be passed to pandas.DataFrame.to_hdf() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_json(filename, *args, **kwargs)

Exports to JSON format.

Options can be passed to pandas.DataFrame.to_json() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_parquet(filename, *args, **kwargs)

Exports to parquet format.

Options can be passed to pandas.DataFrame.to_parquet() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

to_pickle(filename, *args, **kwargs)

Exports to pickle format.

Options can be passed to pandas.DataFrame.to_pickle() as args and kwargs arguments.

Read more: How to export and store trajectory and airspace data?

Return type:

None

unwrap(*args, **kwargs) LazyTraffic

Unwraps angles in the DataFrame.

All features representing angles may be unwrapped (through Numpy) to avoid gaps between 359° and 1°.

The method applies by default to features track and heading. More or different features may be passed in parameter.

Return type:

LazyTraffic

Warning

This method will be stacked for lazy evaluation.