traffic.core.Traffic

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

Bases: traffic.core.mixins.HBoxMixin, traffic.core.mixins.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

In the following example, lazy_t is not evaluated:

>>> lazy_t = t.filter().resample('10s')
>>> type(t_lazy)
traffic.core.lazy.LazyTraffic
LazyTraffic.eval(max_workers: int = 1, desc: Optional[str] = None, cache_file: Optional[Union[str, pathlib.Path]] = None)Optional[Traffic]

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

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: str, default: None

If not None, a tqdm progressbar is displayed with this parameter.

cache_file: str, Path, default: None

If not None, store the results in cache_file and load the results from the file if it exists.

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

agg_latlon(resolution: Optional[Dict[str, float]] = None, **kwargs)pandas.DataFrame

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:

  • 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)traffic.core.lazy.LazyTraffic

Aggregate features on time windows.

The following is performed:

  • 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: Optional[Dict[str, float]], projection: Optional[Union[pyproj.Proj, crs.Projection]] = None, **kwargs)pandas.DataFrame

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

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, …).

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.

The returned pandas DataFrame is 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()Optional[traffic.core.traffic.Traffic]

Returns the airborne part of the Traffic.

The airborne part is determined by an onground flag or null values in the altitude column.

Note

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

aircraft

Return all the different icao24 aircraft ids in the DataFrame

aircraft_data()traffic.core.traffic.Traffic

Add registration and aircraft typecode based on the aircraft database.

all(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

Example usage:

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

Warning

This method will be stacked for lazy evaluation.

apply_time(*args, **kwargs)traffic.core.lazy.LazyTraffic

Apply features on time windows.

The following is performed:

  • 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("10T", 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)traffic.core.mixins.T

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

assign_id(*args, **kwargs)traffic.core.lazy.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 and an incremented index.

Warning

This method will be stacked for lazy evaluation.

callsigns

Return all the different callsigns in the DataFrame

centroid(nb_samples: Optional[int], features: Optional[List[str]] = None, projection: Union[None, crs.Projection, pyproj.Proj] = None, transformer: Optional[TransformerProtocol] = None, max_workers: int = 1, *args, **kwargs)Flight

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

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.pdist

clean_invalid(threshold: int = 10)traffic.core.traffic.Traffic

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
        [...]
clip(*args, **kwargs)traffic.core.lazy.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.

Warning

Altitudes are not taken into account.

Warning

This method will be stacked for lazy evaluation.

closest_point_of_approach(lateral_separation: float, vertical_separation: float, projection: Optional[Union[pyproj.Proj, crs.Projection]] = None, round_t: str = 'd', max_workers: int = 4)Optional[CPA]

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.

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: ClusteringProtocol, nb_samples: Optional[int], features: Optional[List[str]] = None, *args, projection: Union[None, crs.Projection, pyproj.Proj] = None, transform: Optional[TransformerProtocol] = None, max_workers: int = 1, return_traffic: bool = True)traffic.algorithms.clustering.Clustering

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

The method:

  • 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 traffic.core.projection 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_wind(*args, **kwargs)traffic.core.lazy.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.

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: Optional[Union[pyproj.Proj, crs.Projection]] = None)traffic.core.mixins.T

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 centered on the data inside the dataframe.

Other valid projections are available:

  • as pyproj.Proj objects;

  • as cartopy.crs.Projection objects.

cumulative_distance(*args, **kwargs)traffic.core.lazy.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.

Warning

This method will be stacked for lazy evaluation.

diff(*args, **kwargs)traffic.core.lazy.LazyTraffic

Assign differential versions of features to new columns.

>>> 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)traffic.core.lazy.LazyTraffic

Computes the distance from a Flight to another entity.

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

  • 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, “1T”) before calling the method.

Warning

This method will be stacked for lazy evaluation.

drop(*args, **kwargs)traffic.core.mixins.T

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

drop_duplicates(*args, **kwargs)traffic.core.mixins.T

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

end_time

Returns the latest timestamp in the DataFrame.

feature_gt(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

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

>>> 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)traffic.core.lazy.LazyTraffic

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

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

>>> 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)traffic.core.mixins.T

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

filter(*args, **kwargs)traffic.core.lazy.LazyTraffic

Filters the trajectory given features with a median filter.

The method first applies a median filter on each feature of the DataFrame. A default kernel size is applied for a number of features (resp. latitude, longitude, altitude, track, groundspeed, IAS, TAS) but other kernel values may be passed as kwargs parameters.

Rather than returning averaged values, the method computes thresholds on sliding windows (as an average of squared differences) and replace unacceptable values with NaNs.

Then, a strategy may be applied to fill the NaN values, by default a forward/backward fill. Other strategies may be passed, for instance do nothing: None; or interpolate: lambda x: x.interpolate().

Note

This method if often more efficient when applied several times with different kernel values.Kernel values may be passed as integers, or list/tuples of integers for cascade of filters:

# this cascade of filters appears to work well on altitude
flight.filter(altitude=17).filter(altitude=53)

# this is equivalent to the default value
flight.filter(altitude=(17, 53))

Warning

This method will be stacked for lazy evaluation.

first(*args, **kwargs)traffic.core.lazy.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:

>>> 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: Union[pathlib.Path, str], **kwargs)Optional[traffic.core.traffic.TrafficTypeVar]

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.

  • .pkl and .pkl.gz dispatch to pandas.read_pickle;

  • .parquet and .parquet.gz dispatch to pandas.read_parquet;

  • .json and .json.gz dispatch to pandas.read_json;

  • .csv and .csv.gz dispatch to pandas.read_csv;

  • .h5 dispatch to pandas.read_hdf.

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

Example usage:

>>> t = Traffic.from_file("data/sample_opensky.pkl")
classmethod from_flights(flights: Iterable[Optional[traffic.core.flight.Flight]])Optional[traffic.core.traffic.Traffic]

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

geoencode(*args, **kwargs)

Danger

This method is not implemented.

groupby(*args, **kwargs)

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

has(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

Example usage:

>>> 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: Union[traffic.core.mixins.ShapelyMixin, shapely.geometry.base.BaseGeometry, Tuple[float, float, float, float]])Optional[traffic.core.airspace.T]

Returns the part of the DataFrame with coordinates located within the bounding box of the shape passed in parameter.

The bounds parameter can be:

  • an Airspace,

  • a shapely Geometry,

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

Note

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

iterate(by: Optional[Union[str, pandas.DataFrame]] = None, nb_flights: Optional[int] = None)Iterator[traffic.core.flight.Flight]

Iterates over Flights contained in the Traffic structure.

Default iteration calls this method with default arguments:

>>> 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.

iterate_lazy(iterate_kw: Optional[Dict[str, Any]] = None, tqdm_kw: Optional[Dict[str, Any]] = None)traffic.core.lazy.LazyTraffic

Triggers a lazy iteration on the Traffic structure.

Default iteration calls this method with default arguments:

>>> 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)traffic.core.lazy.LazyTraffic

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

This method will be stacked for lazy evaluation.  
last(*args, **kwargs)traffic.core.lazy.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:

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

Warning

This method will be stacked for lazy evaluation.

longer_than(*args, **kwargs)traffic.core.lazy.LazyTraffic

Returns True if flight duration is longer than value. .. warning:

This method will be stacked for lazy evaluation.  
max_split(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

Example usage:

>>> 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)traffic.core.mixins.T

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

next(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

>>> 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.

pipe(func: Callable[[...], traffic.core.mixins.T], *args, **kwargs)traffic.core.mixins.T

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

plot(ax: GeoAxesSubplot, nb_flights: Optional[int] = None, **kwargs)None

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:

>>> from traffic.drawing import EuroPP
>>> fig, ax = plt.subplots(1, subplot_kw=dict(projection=EuroPP()))
>>> t.plot(ax, alpha=.5)
plot_wind(ax: GeoAxesSubplot, resolution: Optional[Dict[str, float]] = None, threshold: int = 10, filtered: bool = False, **kwargs)List[Artist]

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:

  • 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 traffic.drawing 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: str, *args, **kwargs)Optional[traffic.core.mixins.T]

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

query_ehs(*args, **kwargs)traffic.core.lazy.LazyTraffic

Extends data with extra columns from EHS messages.

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

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)traffic.core.lazy.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.

Note

Read more about access to the OpenSky Network database here

Warning

This method will be stacked for lazy evaluation.

rename(*args, **kwargs)traffic.core.mixins.T

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

resample(*args, **kwargs)traffic.core.lazy.LazyTraffic

Resample the trajectory at a given frequency or number of points.

If the rule is a string representing a pandas time series frequency is passed, then the data is resampled along the timestamp axis, then interpolated.

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

Warning

This method will be stacked for lazy evaluation.

reset_index(*args, **kwargs)traffic.core.mixins.T

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

shorter_than(*args, **kwargs)traffic.core.lazy.LazyTraffic

Returns True if flight duration is shorter than value. .. warning:

This method will be stacked for lazy evaluation.  
simplify(*args, **kwargs)traffic.core.lazy.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.

  • By default, a 2D version 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 unless you specify return_mask=True.

Warning

This method will be stacked for lazy evaluation.

sort_values(by: str, **kwargs)traffic.core.mixins.T

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

start_time

Returns the earliest timestamp in the DataFrame.

summary(attributes: List[str], iterate_kw: Optional[Dict[str, Any]] = None)pandas.DataFrame

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

Example usage:

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

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

takeoff_from(*args, **kwargs)traffic.core.lazy.LazyTraffic

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

This method will be stacked for lazy evaluation.  
to_csv(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to CSV format.

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

Read more about export formats in the Exporting and Storing data section

to_czml(filename: Union[str, pathlib.Path], minimum_time: Optional[Union[str, numbers.Real, datetime.datetime, pandas.Timestamp]] = None)None

Generates a CesiumJS scenario file.

to_excel(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to Excel format.

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

Read more about export formats in the Exporting and Storing data section

to_hdf(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to HDF format.

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

Read more about export formats in the Exporting and Storing data section

to_json(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to JSON format.

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

Read more about export formats in the Exporting and Storing data section

to_parquet(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to parquet format.

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

Read more about export formats in the Exporting and Storing data section

to_pickle(filename: Union[str, pathlib.Path], *args, **kwargs)None

Exports to pickle format.

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

Read more about export formats in the Exporting and Storing data section

unwrap(*args, **kwargs)traffic.core.lazy.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.

Warning

This method will be stacked for lazy evaluation.