traffic.core.Flight

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

Bases: traffic.core.mixins.HBoxMixin, traffic.core.mixins.GeographyMixin, traffic.core.mixins.ShapelyMixin, traffic.algorithms.navigation.NavigationFeatures, traffic.algorithms.phases.FuzzyLogic

Flight is the most basic class associated to a trajectory. Flights are the building block of all processing methods, built on top of pandas DataFrame. The minimum set of required features are:

  • icao24: the ICAO transponder ID of an aircraft;

  • callsign: an identifier which may be associated with the registration of an aircraft, with its mission (VOR calibration, firefighting) or with a route (for a commercial aircraft);

  • timestamp: timezone aware timestamps are preferable. Some methods may work with timezone naive timestamps but the behaviour is not guaranteed;

  • latitude, longitude: in degrees, WGS84 (EPSG:4326);

  • altitude: in feet.

Note

The flight_id (identifier for a trajectory) may be used in place of a pair of (icao24, callsign). More features may also be provided for further processing, e.g. groundspeed, vertical_rate, track, heading, IAS (indicated airspeed) or squawk.

Note

All navigation related methods are described more in depth on a dedicated page.

Abridged contents:

Tip

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

abs(features: Union[str, List[str]], **kwargs)traffic.core.flight.Flight

Assign absolute versions of features to new columns.

>>> flight.abs("track")

The two following commands are equivalent:

>>> flight.abs(["track", "heading"])
>>> flight.abs(track="track_abs", heading="heading_abs")
after(time: Union[str, numbers.Real, datetime.datetime, pandas.Timestamp], strict: bool = True)Optional[traffic.core.flight.Flight]

Returns the part of the trajectory flown after a given timestamp.

  • time can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.

agg_time(freq: str = '1T', merge: bool = True, **kwargs)traffic.core.flight.Flight

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.

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.flight.Flight]

Returns the airborne part of the Flight.

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

aligned_on_ils(airport: Union[None, str, Airport])traffic.core.iterator.FlightIterator

Iterates on all segments of trajectory aligned with the ILS of the given airport. The runway number is appended as a new ILS column.

Example usage:

>>> aligned = belevingsvlucht.aligned_on_ils('EHAM').next()
>>> f"ILS {aligned.max('ILS')} until {aligned.stop:%H:%M}"
'ILS 06 until 20:17'

Be aware that all segments are not necessarily yielded in order. Consider using max(..., key=attrgetter('start')) if you want the last landing attempt, or sorted(..., key=attrgetter('start')) for an ordered list

>>> for aligned in belevingsvlucht.aligned_on_ils('EHLE'):
...     print(aligned.start)
2018-05-30 16:50:44+00:00
2018-05-30 18:13:02+00:00
2018-05-30 16:00:55+00:00
2018-05-30 17:21:17+00:00
2018-05-30 19:05:22+00:00
2018-05-30 19:42:36+00:00

>>> from operator import attrgetter
>>> last_aligned = max(
...     belevingsvlucht.aligned_on_ils("EHLE"),
...     key=attrgetter('start')
... )
aligned_on_navpoint(points: Union[PointMixin, Iterable[PointMixin], FlightPlan], angle_precision: int = 1, time_precision: str = '2T', min_time: str = '30s', min_distance: int = 80)traffic.core.iterator.FlightIterator

Iterates on segments of trajectories aligned with one of the given navigational beacons passed in parameter.

The name of the navigational beacon is assigned in a new column navaid.

aligned_on_runway(airport: Union[str, Airport])traffic.core.iterator.FlightIterator

Iterates on all segments of trajectory matching a runway of the given airport.

Example usage:

>>> sum(1 for _ in belevingsvlucht.aligned_on_runway("EHAM"))
2
all(method: Union[str, Callable[[traffic.core.flight.Flight], Iterator[traffic.core.flight.Flight]]])Optional[traffic.core.flight.Flight]

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"))
apply_time(freq: str = '1T', merge: bool = True, **kwargs)traffic.core.flight.Flight

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.

property area: float

Returns the area of the shape, in square meters. The shape is projected to an equivalent local projection before computing a value.

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(name: str = '{self.callsign}_{idx:>03}', idx: int = 0)traffic.core.flight.Flight

Assigns a flight_id to a Flight.

This method is more generally used by the corresponding Traffic and LazyTraffic methods but works fine on Flight as well.

at(time: Optional[Union[str, numbers.Real, datetime.datetime, pandas.Timestamp]] = None)Optional[traffic.core.flight.Position]

Returns the position in the trajectory at a given timestamp.

  • time can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.

  • If no time is passed (default), the last know position is returned.

  • If no position is available at the given timestamp, None is returned. If you expect a position at any price, consider Flight.resample

at_ratio(ratio: float = 0.5)Optional[traffic.core.flight.Position]

Returns a position on the trajectory.

This method is convenient to place a marker on the trajectory in visualisation output.

  • Flight.at_ratio(0) is the first point in the trajectory.

  • Flight.at_ratio(1) is the last point of the trajectory (equivalent to Flight.at())

before(time: Union[str, numbers.Real, datetime.datetime, pandas.Timestamp], strict: bool = True)Optional[traffic.core.flight.Flight]

Returns the part of the trajectory flown before a given timestamp.

  • time can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.

between(start: Union[str, numbers.Real, datetime.datetime, pandas.Timestamp], stop: Union[str, numbers.Real, datetime.datetime, pandas.Timestamp, datetime.timedelta], strict: bool = True)Optional[traffic.core.flight.Flight]

Returns the part of the trajectory flown between start and stop.

  • start and stop can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.

  • stop can also be passed as a timedelta.

property bounds: Tuple[float, float, float, float]

Returns the bounds of the (bounding box of the) shape. Bounds are given in the following order in the origin crs: (west, south, east, north)

property callsign: Optional[Union[str, Set[str]]]

Returns the unique callsign value(s) associated to the Flight.

A callsign is an identifier sent by an aircraft during its flight. It may be associated with the registration of an aircraft, its mission or with a route for a commercial aircraft.

property centroid: shapely.geometry.Point

Returns the centroid of the shape as a shapely Point.

chart(*features)alt.Chart

Initializes an altair Chart based on Flight data.

The features passed in parameters are dispatched to allow plotting multiple features on the same graph.

Example usage:

# Most simple usage
flight.chart().encode(alt.Y("altitude"))

# With some configuration
flight.chart().encode(
    alt.X(
        "utcyearmonthdatehoursminutes(timestamp)",
        axis=alt.Axis(title=None, format="%H:%M"),
    ),
    alt.Y("altitude", title="altitude (in ft)"),
    alt.Color("callsign")
)

For a more complex graph plotting similar physical quantities on the same graph, and other quantities on a different graph, the following snippet may be of use.

# More advanced with several plots on the same graph
base = (
    flight.chart("altitude", "groundspeed", "IAS")
    .encode(
        alt.X(
            "utcyearmonthdatehoursminutesseconds(timestamp)",
            axis=alt.Axis(title=None, format="%H:%M"),
        )
    )
    .properties(height=200)
)

alt.vconcat(
    base.transform_filter('datum.variable != "altitude"').encode(
        alt.Y(
            "value:Q",
            axis=alt.Axis(title="speed (in kts)"),
            scale=alt.Scale(zero=False),
        )
    ),
    base.transform_filter('datum.variable == "altitude"').encode(
        alt.Y("value:Q", title="altitude (in ft)")
    ),
)

Note

See also plot_time() for the Matplotlib equivalent.

clip(shape: Union[traffic.core.mixins.ShapelyMixin, shapely.geometry.base.BaseGeometry])Optional[traffic.core.flight.Flight]

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.

closest_point(points: Union[List[PointMixin], PointMixin])pandas.Series

Selects the closest point of the trajectory with respect to a point or list of points.

The pd.Series returned by the function is enriched with two fields: distance (in meters) and point (containing the name of the closest point to the trajectory)

Example usage:

>>> item = belevingsvlucht.between(
...     "2018-05-30 16:00", "2018-05-30 17:00"
... ).closest_point(  # type: ignore
...     [
...         airports["EHLE"],  # type: ignore
...         airports["EHAM"],  # type: ignore
...         navaids["NARAK"],  # type: ignore
...     ]
... )
>>> f"{item.point}, {item.distance:.2f}m"
"Lelystad Airport, 49.11m"
comet(**kwargs)traffic.core.flight.Flight

Computes a comet for a trajectory.

The method uses the last position of a trajectory (method at()) and uses the track (in degrees), groundspeed (in knots) and vertical_rate (in ft/min) values to interpolate the trajectory in a straight line.

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

Example usage:

flight.comet(minutes=10)
flight.before("2018-12-24 23:55").comet(minutes=10)  # Merry XMas!
compute_navpoints(navaids: Optional[Navaids] = None, buffer: float = 0.1)Optional[pandas.DataFrame]

This functions recomputes the most probable alignments on navigational points on the trajectory.

By default, all navaids of the default database are considered, but limited to a buffered bounding box around the trajectory.

Once computed, the following Altair snippet may be useful to display the trajectory as a succession of segments:

import altair as alt

df = flight.compute_navpoints()

segments = (
    alt.Chart(df.drop(columns="duration")).encode(
        alt.X("start", title=None),
        alt.X2("stop"),
        alt.Y("navaid", sort="x", title=None),
        alt.Color("type", title="Navigational point"),
        alt.Tooltip(["navaid", "distance", "shift_mean"]),
    )
    .mark_bar(size=10)
    .configure_legend(
        orient="bottom",
        labelFontSize=14, titleFontSize=14, labelFont="Ubuntu"
    )
    .configure_axis(labelFontSize=14, labelFont="Ubuntu")
)
compute_wind()traffic.core.flight.Flight

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.

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(compute_gs: bool = True, compute_track: bool = True, *, reverse: bool = False, **kwargs)traffic.core.flight.Flight

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.

property destination: Optional[Union[str, Set[str]]]

Returns the unique destination value(s), None if not available in the DataFrame.

The destination airport is usually represented as a ICAO or a IATA code.

The ICAO code of an airport is represented by 4 letters (e.g. EHAM for Amsterdam Schiphol International Airport) and the IATA code is represented by 3 letters and more familiar to the public (e.g. AMS for Amsterdam)

diff(features: Union[str, List[str]], **kwargs)traffic.core.flight.Flight

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")
distance(other: None = None, column_name: str = 'distance')float
distance(other: Union[Airspace, Polygon, PointMixin], column_name: str = 'distance')traffic.core.flight.Flight
distance(other: traffic.core.flight.Flight, column_name: str = 'distance')Optional[pandas.DataFrame]

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.

diversion()Optional[Flight]

Returns the segment of trajectory after a possible decision of diversion.

The method relies on the destination parameter to identify the intended destination.

property diverted: Optional[Union[str, Set[str]]]

Returns the unique diverted value(s), None if not available in the DataFrame.

The diverted airport is usually represented as a ICAO or a IATA code.

The ICAO code of an airport is represented by 4 letters (e.g. EHAM for Amsterdam Schiphol International Airport) and the IATA code is represented by 3 letters and more familiar to the public (e.g. AMS for Amsterdam)

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.

property duration: pandas.Timedelta

Returns the duration of the flight.

emergency()traffic.core.iterator.FlightIterator

Iterates on emergency segments of trajectory.

An emergency is defined with a 7700 squawk code.

encode(**kwargs)

DEPRECATED: Use Flight.chart() method instead.

property extent: Tuple[float, float, float, float]

Returns the extent of the (bounding box of the) shape. Extent is given in the following order in the origin crs: (west, east, south, north)

Note

When plotting with Matplotlib and Cartopy, the extent property is convenient in the following use case:

>>> ax.set_extent(obj.extent)
feature_gt(feature: Union[str, Callable[[traffic.core.flight.Flight], Any]], value: Any, strict: bool = True)bool

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.

feature_lt(feature: Union[str, Callable[[traffic.core.flight.Flight], Any]], value: Any, strict: bool = True)bool

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.

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(strategy: Optional[Callable[[pandas.DataFrame], pandas.DataFrame]] = <function Flight.<lambda>>, **kwargs)traffic.core.flight.Flight

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))
first(value: Union[None, str, numbers.Real, datetime.timedelta, pandas.Timedelta] = None, **kwargs)Optional[traffic.core.flight.Flight]

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
property flight_id: Optional[Union[str, Set[str]]]

Returns the unique flight_id value(s) of the DataFrame.

Neither the icao24 (the aircraft) nor the callsign (the route) is a reliable way to identify trajectories. You can either use an external source of data to assign flight ids (for example DDR files by Eurocontrol, identifiers by FlightRadar24, etc.) or assign a flight_id by yourself (see Flight.assign_id(name: str) method).

The Traffic.assign_id() method uses a heuristic based on the timestamps associated to callsign/icao24 pairs to automatically assign a flight_id and separate flights.

classmethod from_file(filename: Union[pathlib.Path, str], **kwargs)Optional[traffic.core.flight.T]

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 = Flight.from_file("example_flight.csv")
geoencode(**kwargs)alt.Chart

Returns an altair encoding of the shape to be composed in an interactive visualization. Specific plot features, such as line widths, can be passed via **kwargs. See documentation.

geojson()

Returns the GeoJSON representation of the shape as a Dict. The transformation is delegated to shapely mapping method.

go_around(airport: Optional[Union[str, Airport]] = None, dataset: Optional[Airports] = None)traffic.core.iterator.FlightIterator

Detects go-arounds.

The method yields pieces of trajectories with exactly two landing attempts (aligned on one runway) on the same airport separated by exactly one climbing phase.

groupby(*args, **kwargs)

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

has(method: Union[str, Callable[[traffic.core.flight.Flight], Iterator[traffic.core.flight.Flight]]])bool

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"))
holding_pattern(min_altitude=7000, turning_threshold=0.5, low_limit=pandas.Timedelta, high_limit=pandas.Timedelta, turning_limit=pandas.Timedelta)traffic.core.iterator.FlightIterator

Iterates on parallel segments candidates for identifying a holding pattern.

Warning

This API is not stable yet. The interface may change in a near future.

property holes: int

Returns the number of ‘holes’ in a trajectory.

property icao24: Optional[Union[str, Set[str]]]

Returns the unique icao24 value(s) of the DataFrame.

icao24 (ICAO 24-bit address) is a unique identifier associated to a transponder. These identifiers correlate to the aircraft registration.

For example icao24 code ‘ac82ec’ is associated to ‘N905NA’.

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.

intersects(shape: Union[traffic.core.mixins.ShapelyMixin, shapely.geometry.base.BaseGeometry])bool

Returns True if the trajectory is inside the given shape.

  • If an Airspace is passed, the 3D trajectory is compared to each layers constituting the airspace, with corresponding altitude limits.

  • If a shapely Geometry is passed, the 2D trajectory alone is

considered.

is_from_inertial(freq_threshold=0.05)bool

Returns True if ground trajectory data looks noisy.

Warning

This method is still experimental and tries to catch trajectories based on the inertial system rather than the GPS. It catches zig-zag patterns but fails to get trajectories driving between taxiways.

landing_airport(**kwargs)Airport

Returns the most probable landing airport based on the last location in the trajectory.

>>> belevingsvlucht.landing_airport()
EHAM/AMS: Amsterdam  Schiphol

When data is missing near the ground, it may be relevant to specify a subset of airports as a keyword parameter.

>>> missing_data = belevingsvlucht.before("2018-05-30 20:00")
>>> missing_data.landing_airport()
NL-0024/nan: Middenmeer Aerodrome

>>> large_airports = airports.query("type == 'large_airport'")
>>> missing_data.landing_airport(dataset=large_airports)
EHAM/AMS: Amsterdam  Schiphol
landing_at(airport: Union[str, Airport])bool

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

landing_attempts(dataset: Optional[Airports] = None)traffic.core.iterator.FlightIterator

Iterates on all landing attempts for current flight.

First, candidates airports are identified in the neighbourhood of the segments of trajectory below 10,000 ft. By default, the full airport database is considered but it is possible to restrict it and pass a smaller database with the dataset parameter.

If no runway information is available for the given airport, no trajectory segment will be provided.

Warning

This API is not stable yet. The interface may change in a near future.

last(value: Union[None, str, numbers.Real, datetime.timedelta, pandas.Timedelta] = None, **kwargs)Optional[traffic.core.flight.Flight]

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
leaflet(**kwargs)Optional[ipyleaflet.Polyline]

Returns a Leaflet layer to be directly added to a Map.

Warning

This is only available if the Leaflet plugin is activated. (true by default)

The elements passed as kwargs as passed as is to the PolyLine constructor.

Example usage:

>>> from ipyleaflet import Map
>>> # Center the map near the landing airport
>>> m = Map(center=flight.at().latlon, zoom=7)
>>> m.add_layer(flight)  # this works as well with default options
>>> m.add_layer(flight.leaflet(color='red'))
>>> m
longer_than(value: Union[str, datetime.timedelta, pandas.Timedelta], strict: bool = True)bool

Returns True if flight duration is longer than value.

max(feature: str)

Returns the maximum value of given feature.

>>> flight.max('altitude')  # dummy example
35000
max_split(value: Union[int, str] = '10T', unit: Optional[str] = None, key: Callable[[Optional[traffic.core.flight.Flight]], Any] = operator.attrgetter('duration'))Optional[traffic.core.flight.Flight]

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.

mean(feature: str)

Returns the average value of given feature.

>>> flight.mean('vertical_rate')  # dummy example
-1000
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.

min(feature: str)

Returns the minimum value of given feature.

>>> flight.min('altitude')  # dummy example
24000
moving(speed_threshold: float = 2, time_threshold: str = '30s', filter_dict={'compute_gs': 3}, resample_rule: str = '5s')Optional[Flight]

Returns the part of the trajectory after the aircraft starts moving.

Warning

This method has been extensively tested on aircraft taxiing before take-off. It should be adapted/taken with extra care for trajectories after landing.

next(method: Union[str, Callable[[traffic.core.flight.Flight], Iterator[traffic.core.flight.Flight]]])Optional[traffic.core.flight.Flight]

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"))
property number: Optional[Union[str, Set[str]]]

Returns the unique number value(s) associated to the Flight.

This field is reserved for the commercial number of the flight, prefixed by the two letter code of the airline. For instance, AFR292 is the callsign and AF292 is the flight number.

Callsigns are often more complicated as they are designed to limit confusion on the radio: hence DLH02X can be the callsign associated to flight number LH1100.

on_parking_position(airport: Union[str, Airport], buffer_size: float = 0.0001)traffic.core.iterator.FlightIterator

Generates possible parking positions at a given airport.

Example usage:

>>> parking = flight.on_parking_position('LSZH').max()
# returns the most probable parking position in terms of duration

Warning

This method has been well tested for aircraft taking off, but should be double checked for landing trajectories.

on_runway(airport: Union[str, Airport])Optional[Flight]

Returns the longest segment of trajectory which perfectly matches a runway at given airport.

>>> landing = belevingsvlucht.last(minutes=30).on_runway("EHAM")
>>> landing.mean("altitude")
-26.0

>>> takeoff = belevingsvlucht.first(minutes=30).on_runway("EHAM")
>>> takeoff.mean("altitude")
437.27272727272725
property origin: Optional[Union[str, Set[str]]]

Returns the unique origin value(s), None if not available in the DataFrame.

The origin airport is usually represented as a ICAO or a IATA code.

The ICAO code of an airport is represented by 4 letters (e.g. EHAM for Amsterdam Schiphol International Airport) and the IATA code is represented by 3 letters and more familiar to the public (e.g. AMS for Amsterdam)

phases(twindow: int = 60)Flight

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

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, **kwargs)List[Artist]

Plots the trajectory on a Matplotlib axis.

The 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 Mercator
fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator())
flight.plot(ax, alpha=.5)

Note

See also geoencode() for the altair equivalent.

plot_time(ax: Axes, y: Union[str, List[str]], secondary_y: Union[None, str, List[str]] = None, **kwargs)None

Plots the given features according to time.

The method ensures:

  • only non-NaN data are displayed (no gap in the plot);

  • the timestamp is naively converted to UTC if not localized.

Example usage:

ax = plt.axes()
# most simple version
flight.plot(ax, 'altitude')
# or with several comparable features and twin axes
flight.plot(
    ax, ['altitude', 'groundspeed, 'IAS', 'TAS'],
    secondary_y=['altitude']
)

Note

See also chart() for the altair equivalent.

plot_wind(ax: GeoAxesSubplot, resolution: Optional[Union[int, str, Dict[str, float]]] = '5T', 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:

  • None for a raw plot;

  • an integer or a string to pass to a Flight.resample() method as a preprocessing before plotting;

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

Example usage:

from traffic.drawing import Mercator
fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator()))
(
    flight
    .resample("1s")
    .query('altitude > 10000')
    .compute_wind()
    .plot_wind(ax, alpha=.5)
)
project_shape(projection: Optional[Union[pyproj.Proj, crs.Projection]] = None)shapely.geometry.base.BaseGeometry

Returns a projected representation of the shape.

By default, an equivalent projection is applied. Equivalent projections locally respect areas, which is convenient for the area attribute.

Other valid projections are available:

  • as pyproj.Proj objects;

  • as cartopy.crs.Projection objects.

pushback(airport: Union[str, Airport], filter_dict={'compute_gs': 21, 'compute_track': 21, 'compute_track_unwrapped': 21}, track_threshold: float = 90)Optional[Flight]

Returns the pushback part of the trajectory on ground.

The method identifies the start of the movement, the parking_position and the moment the aircraft suddenly changes direction the computed track angle.

Warning

The method has poor performance when trajectory point on ground are lacking. This is often the case for data recorded from locations far from the airport.

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(data: Union[None, pandas.DataFrame, RawData] = None, failure_mode: str = 'warning', progressbar: Union[bool, Callable[[Iterable], Iterable]] = True)Flight

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

query_opensky(**kwargs)Optional[traffic.core.flight.Flight]

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

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(rule: Union[str, int] = '1s')traffic.core.flight.Flight

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.

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.

runway_change(airport: Optional[Union[str, Airport]] = None, dataset: Optional[Airports] = None)traffic.core.iterator.FlightIterator

Detects runway changes.

The method yields pieces of trajectories with exactly two runway alignments on the same airport not separated by a climbing phase.

In each piece of yielded trajectory, the ILS column contains the name of the runway targetted by the aircraft at each instant.

shorten(value: Union[None, str, numbers.Real, datetime.timedelta, pandas.Timedelta] = None, **kwargs)Optional[traffic.core.flight.Flight]

Removes 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.shorten(minutes=10)
>>> flight.shorten("1H")
>>> flight.shorten(10)  # seconds by default
shorter_than(value: Union[str, datetime.timedelta, pandas.Timedelta], strict: bool = True)bool

Returns True if flight duration is shorter than value.

simplify(tolerance: float, altitude: Optional[str] = None, z_factor: float = 3.048, return_mask: bool = False)Union[numpy.ndarray, traffic.core.flight.Flight]

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.

skip(value: Union[None, str, numbers.Real, datetime.timedelta, pandas.Timedelta] = None, **kwargs)Optional[traffic.core.flight.Flight]

Removes 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.skip(minutes=10)
>>> flight.skip("1H")
>>> flight.skip(10)  # seconds by default
slow_taxi(min_duration: Union[None, str, numbers.Real, datetime.timedelta, pandas.Timedelta] = '60s', max_diameter: float = 150)traffic.core.iterator.FlightIterator

Holding segments are part of a trajectory where the aircraft stays more than min_duration (in s) within a circle of diameter max_diameter (in m)

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.

split(value: int, unit: str)traffic.core.iterator.FlightIterator
split(value: str, unit: None = None)traffic.core.iterator.FlightIterator

Iterates on legs of a Flight based on the distrution of timestamps.

By default, the method stops a flight and yields a new one after a gap of 10 minutes without data.

The length of the gap (here 10 minutes) can be expressed:

  • in the NumPy style: Flight.split(10, 'm') (see np.timedelta64);

  • in the pandas style: Flight.split('10T') (see pd.Timedelta)

property squawk: Set[str]

Returns all the unique squawk values in the trajectory.

A squawk code is a four-digit number assigned by ATC and set on the transponder. Some squawk codes are reserved for specific situations and emergencies, e.g. 7700 for general emergency, 7600 for radio failure or 7500 for hijacking.

property start: pandas.Timestamp

Returns the minimum value of timestamp.

property stop: pandas.Timestamp

Returns the maximum value of timestamp.

sum(method: Union[str, Callable[[traffic.core.flight.Flight], Iterator[traffic.core.flight.Flight]]])int

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

Example usage:

>>> flight.sum("go_around")
>>> flight.sum("runway_change")
>>> flight.sum(lambda f: f.aligned_on_ils("LFBO"))
takeoff_airport(**kwargs)Airport

Returns the most probable takeoff airport based on the first location in the trajectory.

>>> belevingsvlucht.takeoff_airport()
EHAM/AMS: Amsterdam  Schiphol

When data is missing near the ground, it may be relevant to specify a subset of airports as a keyword parameter.

>>> missing_data = belevingsvlucht.after("2018-05-30 15:30")
>>> missing_data.takeoff_airport()
NL-0015/nan: Universitair Medisch Centrum Utrecht Heliport

>>> large_airports = airports.query("type == 'large_airport'")
>>> missing_data.takeoff_airport(dataset=large_airports)
EHAM/AMS: Amsterdam  Schiphol
takeoff_from(airport: Union[str, Airport])bool

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

takeoff_from_runway(airport: Union[str, Airport], threshold_alt: int = 2000, zone_length: int = 6000, little_base: int = 50, opening: float = 5)traffic.core.iterator.FlightIterator

Identifies the take-off runway for trajectories.

Iterates on all segments of trajectory matching a zone around a runway of the given airport. The takeoff runway number is appended as a new runway column.

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_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(features: Union[None, str, List[str]] = None)traffic.core.flight.Flight

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.