traffic.core.flight
- class traffic.core.Flight(data, *args, **kwargs)
Bases:
HBoxMixin
,GeographyMixin
,ShapelyMixin
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) orsquawk
.Tip
Read more about:
sample flights provided for testing purposes in the module
traffic.data.samples
Abridged contents:
properties:
callsign()
,flight_id()
,icao24()
,number()
,start()
,stop()
,time related methods:
after()
,at()
,at_ratio()
,before()
,between()
,first()
,last()
,skip()
,shorten()
geometry related methods:
airborne()
,clip()
,compute_wind()
,compute_xy()
,distance()
,inside_bbox()
,intersects()
,project_shape()
,unwrap()
filtering and resampling methods:
filter()
,resample()
,simplify()
,navigation related events:
aligned()
,landing()
,takeoff()
,holding_pattern()
,point_merge()
,go_around()
airborne events:
emergency()
,phases()
,thermals()
ground trajectory methods:
aligned()
,movement()
,parking_position()
,pushback()
performance estimation methods:
fuelflow()
,emission()
metadata inference methods:
infer_airport()
,infer_flightplan()
,prediction methods:
predict()
visualisation with altair:
chart()
,geoencode()
visualisation with leaflet:
map_leaflet()
visualisation with plotly:
line_map()
and othersvisualisation with Matplotlib:
plot()
,plot_time()
- Scattergeo(**kwargs)
Create a Scattergeo with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Scattergeo
- Scattermap(**kwargs)
Create a Scattermap with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Scattermap
- abs(features=None, **kwargs)
Assign absolute versions of features to new columns.
- Return type:
>>> flight.abs("track")
The two following commands are equivalent:
>>> flight.abs(["track", "heading"]) >>> flight.abs(track="track_abs", heading="heading_abs")
- after(time, strict=True)
Returns the part of the trajectory flown after a given timestamp. :rtype:
Optional
[Flight
]time
can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.
- agg_time(freq='1 min', merge=True, **kwargs)
Aggregate features on time windows.
The following is performed are performed in order. :rtype:
Flight
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, 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 Flight.
The airborne part is determined by an
onground
flag or null values in the altitude column.
- aligned(*args, method='default', **kwargs)
Detects a geometric alignment with aeronautical infrastructure.
- Parameters:
method (
Union
[Literal
['default'
,'beacon'
,'ils'
,'runway'
],ApplyIteratorBase
]) – By default, the method checks a geometric alignment with a navigational beacon (navaid).- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding landing detection class.
The following table summarizes the available methods and their corresponding classes:
"beacon"
(default) usesBeaconTrackBearingAlignment
and compares the track angle of the aircraft with the bearing to a given point."ils"
usesLandingAlignedOnILS
and detects segments on trajectory aligned with the ILS of a given airport."runway"
usesRunwayAlignment
and detects segments aligned with one of the documented runways.
Usage: Check the corresponding classes which are properly documented.
- all(method, flight_id=None)
Returns the concatenation of segments returned by flight.method().
Example usage:
>>> flight.all("go_around") >>> flight.all("runway_change") >>> flight.all('aligned_on_ils("LFBO")') >>> flight.all(lambda f: f.aligned_on_ils("LFBO"))
- apply_time(freq='1 min', merge=True, **kwargs)
Apply features on time windows.
The following is performed are performed in order. :rtype:
Flight
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.
- 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)
Applies the Pandas
assign()
method to the underlying pandas DataFrame and get the result back in the same structure.- Return type:
Self
- assign_id(name='{self.callsign}_{idx:>03}', idx=0)
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.
- Return type:
- at(time=None)
Returns the position in the trajectory at a given timestamp. :rtype:
Optional
[Position
]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
resample()
- at_ratio(ratio=0.5)
Returns a position on the trajectory.
This method is convenient to place a marker on the trajectory in visualisation output. :rtype:
Optional
[Position
]Flight.at_ratio(0)
is the first point in the trajectory.Flight.at_ratio(1)
is the last point of the trajectory (equivalent toFlight.at()
)
- before(time, strict=True)
Returns the part of the trajectory flown before a given timestamp. :rtype:
Optional
[Flight
]time
can be passed as a string, an epoch, a Python datetime, or a Pandas timestamp.
- between(start, stop, strict=True)
Returns the part of the trajectory flown between start and stop. :rtype:
Optional
[Flight
]start
andstop
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: str | Set[str] | None
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.
- chart(*features)
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)") ), )
- Return type:
Note
See also
plot_time()
for the Matplotlib equivalent.
- clip(shape, strict=True)
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:
Optional
[Flight
]Warning
Altitudes are not taken into account.
- closest_point(points)
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"
- Return type:
Series
- compute_DME_NSE(dme, column_name='NSE')
Adds the DME/DME Navigation System Error.
Computes the max Navigation System Error using DME-DME navigation. The obtained NSE value corresponds to the 2 \(\sigma\) (95%) requirement in nautical miles.
Source: EUROCONTROL Guidelines for RNAV 1 Infrastructure Assessment
- Parameters:
dme (
Union
[Navaids
,Tuple
[Navaid
,Navaid
]]) –when the parameter is of type Navaids, only the pair of Navaid giving the smallest NSE are used;
when the parameter is of type tuple, the NSE is computed using only the pair of specified Navaid.
column_name (
str
) – (default:"NSE"
), the name of the new column containing the computed NSE
- Return type:
- compute_TAS()
Computes the wind triangle for each timestamp.
This method requires
groundspeed
,track
,wind_u
andwind_v
(in knots) to compute true airspeed (TAS
), andheading
features. The groundspeed and the track angle are usually available in ADS-B messages; wind information may be included from a GRIB file using theinclude_grib()
method.- Return type:
- 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()
Computes the wind triangle for each timestamp.
This method requires
groundspeed
,track
, true airspeed (TAS
), andheading
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:Flight
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=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(compute_gs=True, compute_track=True, *, reverse=False, **kwargs)
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 additionalcompute_gs
is also added. This value can be compared with the decodedgroundspeed
value in ADSB messages.When the
compute_track
flag is set to True (default), an additionalcompute_track
is also added. This value can be compared with the decodedtrack
value in ADSB messages.- Return type:
- property destination: str | Set[str] | None
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=None, **kwargs)
Assign differential versions of features to new columns.
- Return type:
>>> flight.diff("track")
The two following commands are equivalent:
>>> flight.diff(["track", "heading"]) >>> flight.diff(track="track_diff", heading="heading_diff")
- distance(other=None, column_name='distance')
Computes the distance from a Flight to another entity.
The behaviour is different according to the type of the second element: :rtype:
Union
[None
,float
,Flight
,DataFrame
]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.
- property diverted: str | Set[str] | None
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)
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
- property duration: Timedelta
Returns the duration of the flight.
- emergency()
Iterates on emergency segments of trajectory.
An emergency is defined with a 7700 squawk code.
- Return type:
- emission(*args, method='default', **kwargs)
Estimate the pollutants emitted by the aircraft based on its trajectory.
- Parameters:
method (
Union
[Literal
['default'
,'openap'
],EstimatorBase
]) – At the moment, only the OpenAP implementation is available, and is the default implementation.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding fuel flow class.
- property extent: tuple[float, float, float, float]
Returns the extent of the (bounding box of the) shape.
Note
When plotting with Matplotlib and Cartopy, the extent property is convenient in the following use case:
>>> ax.set_extent(obj.extent)
- Returns:
Extent is given in the following order in the origin crs: (west, east, south, north)
- feature_gt(feature, value, strict=True)
Returns True if feature(flight) is greater than value.
This is fully equivalent to f.longer_than(“1 minute”):
- Return type:
>>> 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, value, strict=True)
Returns True if feature(flight) is less than value.
This is fully equivalent to f.shorter_than(“1 minute”):
- Return type:
>>> 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)
Applies the Pandas
fillna()
method to the underlying pandas DataFrame and get the result back in the same structure.- Return type:
Self
- filter(filter='default', strategy=<function Flight.<lambda>>, **kwargs)
Filters a trajectory with predefined methods.
- Parameters:
filter (
Union
[Literal
['default'
,'aggressive'
],FilterBase
]) – (default:FilterAboveSigmaMedian
) is one of the filters predefined in traffic.algorithms.filters or any filter implementing theFilter
protocol. Use “aggressive” for an experimental filter by @krumjanstrategy (
Optional
[Callable
[[DataFrame
],DataFrame
]]) –(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:
More filters are available on the traffic.algorithms.filters page
- final(method)
Returns the final (last) segment of trajectory yielded by flight.method()
>>> flight.final("go_around") >>> flight.final("runway_change") >>> flight.final(lambda f: f.aligned_on_ils("LFBO"))
- first(value=None, **kwargs)
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:
>>> flight.first(minutes=10) >>> flight.first("1h") >>> flight.first(10) # seconds by default
- property flight_id: str | Set[str] | None
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 aflight_id
and separate flights.
- 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. :rtype:Self
.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 underlyingpandas.read_*
method with the kwargs argument.Example usage:
>>> from traffic.core import Flight >>> t = Flight.from_file("example_flight.csv")
- classmethod from_readsb(filename)
Parses data in readsb format.
Reference: https://github.com/wiedehopf/readsb/blob/dev/README-json.md#trace-jsons
- fuelflow(*args, method='default', **kwargs)
Estimate the mass and fuel flow of the aircraft based on its trajectory.
- Parameters:
method (
Union
[Literal
['default'
,'openap'
],EstimatorBase
]) – At the moment, only the OpenAP implementation is available, and is the default implementation.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding fuel flow class.
- geoencode(**kwargs)
Returns an altair encoding of the shape to be composed in an interactive visualization. Specific plot features, such as line widths, can be passed with the kwargs argument. See documentation.
- Return type:
- geojson()
Returns the GeoJSON representation of the shape as a Dict. The transformation is delegated to shapely
mapping
method.
- go_around(*args, method='default', **kwargs)
Detects go-around situations in a trajectory.
Usage: See: How to select go-arounds from a set of trajectories?
- Return type:
- groupby(*args, **kwargs)
Applies the Pandas
groupby()
method to the underlying pandas DataFrame.- Return type:
DataFrameGroupBy
- has(method)
Returns True if flight.method() returns a non-empty iterator.
Example usage:
- Return type:
>>> flight.has("go_around") >>> flight.has("runway_change") >>> flight.has(lambda f: f.aligned_on_ils("LFBO"))
- holding_pattern(*args, method='default', **kwargs)
Detects holding patterns in a trajectory.
Usage: See How to detect holding patterns in aircraft trajectories?
- Return type:
- property icao24: str | Set[str] | None
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’.
- infer_airport(method, **kwargs)
Infers the takeoff or landing airport from the trajectory data.
- Parameters:
method (
Union
[Literal
['takeoff'
,'landing'
],AirportInferenceBase
]) – selects the detection method- Return type:
"landing"
usesLandingAirportInference
"takeoff"
usesTakeoffAirportInference
Usage:
>>> flight.infer_airport("takeoff") >>> flight.infer_airport("landing")
Check the documentation of the classes for more options.
- infer_flightplan(*args, method='default', **kwargs)
Infers a possible flight-plan from the trajectory data.
- Parameters:
method (
Union
[Literal
['default'
],FlightPlanBase
]) – selects the detection method- Return type:
None
|DataFrame
The only available (default) method is
FlightPlanInference
. Check the documentation there for more details.Check the documentation of the class for more options.
- 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.
- intersects(shape)
Returns True if the trajectory is inside the given shape. :rtype:
bool
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.
- label(method, **kwargs)
Returns the same flight with extra information from iterators.
Every keyword argument will be used to create a new column in the Flight dataframe, filled by default with None values: :rtype:
Flight
if the passed value is True, the default one is False
- if the passed value is a string:
“{i}” will be replaced by the index of the segment;
“{segment}” will be replaced by the current piece of trajectory;
“{self}” will be replaced by the current flight instance
If a function is passed it will be evaluated with:
the current piece of trajectory (segment) if the function or the lambda has one argument;
the index and the segment if the function or the lambda has two arguments;
the index, the segment and the flight if the function or the lamdba has three arguments;
Before returning, the dataframe applies
convert_dtypes()
and so None values maybe replaced by NaT or NaN values.Example usage:
Add a column holding which is True when the trajectory follows a holding pattern
flight.label(holding_pattern, holding=True)
Add a column index to enumerate holding patterns:
flight.label(holding_pattern, index="{i}")
More complicated enriching:
flight.label( "aligned_on_ils('LSZH')", aligned=True, label="{self.flight_id}_{i}", index=lambda i, segment: i, start=lambda segment: segment.start, altitude_max=lambda segment: segment.altitude_max )
- landing(*args, method='default', **kwargs)
Detects the landing phase in a trajectory.
- Parameters:
method (
Union
[Literal
['default'
,'aligned_on_ils'
,'any'
,'runway_change'
],ApplyIteratorBase
]) – By default, the method detects segments on trajectory aligned with the ILS of a given airport.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding landing detection class.
The following table summarizes the available methods and their corresponding classes:
"aligned_on_ils"
(default) usesLandingAlignedOnILS
and detects segments on trajectory aligned with the ILS of a given airport."anywhere"
usesLandingAnyAttempt
and detects the most plausible landing airport for all pieces of trajectories below a threshold altitude."runway_change"
usesLandingWithRunwayChange
and detects a specific subset of situations where aircraft are aligned on several runways during one landing phase.
Usage:
All the following calls are equivalent:
>>> flight.landing("EHAM") # returns a flight iterator >>> flight.landing("EHAM", method="default") >>> flight.landing(airport="EHAM", method="default") >>> flight.landing(method=LandingAlignedOnILS(airport="EHAM"))
As with other
FlightIterator
, we can:check whether an aircraft is landing at a given airport:
>>> flight.landing("EHAM").has() >>> flight.has("landing('EHAM')")
get the first landing attempt:
>>> flight.landing("EHAM").next() >>> flight.next("landing('EHAM')")
More details in the specific documentation for each class.
- landing_at(airport)
Returns True if the flight lands at the given airport.
- last(value=None, **kwargs)
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:
>>> flight.last(minutes=10) >>> flight.last("1h") >>> flight.last(10) # seconds by default
- leaflet(**kwargs)
Returns a Leaflet layer to be directly added to a Map.
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(flight) >>> m.add(flight.leaflet(color='red')) >>> m
- line_geo(**kwargs)
Create a line plot with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Figure
- line_map(map_style='carto-positron', **kwargs)
Create a line plot with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Figure
- longer_than(value, strict=True)
Returns True if flight duration is longer than value.
- Return type:
- map_leaflet(*, zoom=7, highlight=None, airport=None, **kwargs)
Returns an ipyleaflet Map with a trajectory inside.
- Parameters:
airport (
Union
[None
,str
,Airport
]) – centers the map on the airport and highlights the runwayshighlight (
Optional
[Dict
[str
,Union
[str
,Flight
,Callable
[[Flight
],Optional
[Flight
]]]]]) – is a dictionary mapping a color (the key) to a piece of the trajectory; the selection can be made with a Flight, a function returning a Flight, a function returning a FlightIterator or a string describing the function (e.g."holding_pattern"
or"landing('EHAM')"
)zoom (
int
) – initializes the zoom level.
- Return type:
See also: Visualize trajectories with Leaflet
- max(feature)
Returns the maximum value of given feature.
- Return type:
>>> flight.max('altitude') # dummy example 35000
- max_split(value='10 min', unit=None, key='duration')
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)
Returns the average value of given feature.
- Return type:
>>> flight.mean('vertical_rate') # dummy example -1000
- 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
- min(feature)
Returns the minimum value of given feature.
- Return type:
>>> flight.min('altitude') # dummy example 24000
- movement(*args, method='default', **kwargs)
Detects when the aircraft starts moving on the surface.
The only available (default) method is
StartMoving
. Check the documentation there for more details.
- next(method)
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: str | Set[str] | None
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.
- property origin: str | Set[str] | None
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)
- parking_position(*args, method='default', **kwargs)
Detects pieces of trajectory matching documented parking positions.
The only available (default) method,
ParkingPositionGeometricIntersection
, looks at the intersection between the trajectory and a buffered version of the parking positions.Check the documentation of the corresponding class for more details.
- Return type:
- phases(*args, method='default', **kwargs)
Label phases in flight trajectories.
An extra
"phase"
column is added to the DataFrame.The only available (default) method is provided by OpenAP.
Usage: See: How to find flight phases on a trajectory?
- Return type:
- pipe(func, *args, **kwargs)
Applies func to the object. :rtype:
None
|Flight
|bool
Warning
The logic is similar to that of
pipe()
method, but the function applies on T, not on the DataFrame.
- plot(ax, **kwargs)
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 cartes.crs import Mercator fig, ax = plt.subplots(1, subplot_kw=dict(projection=Mercator()) flight.plot(ax, alpha=.5)
- Return type:
List
[Artist
]
Note
See also
geoencode()
for the altair equivalent.
- plot_time(ax, y, secondary_y=None, **kwargs)
Plots the given features according to time.
The method ensures: :rtype:
None
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_time(ax, 'altitude') # or with several comparable features and twin axes flight.plot_time( ax, ['altitude', 'groundspeed', 'IAS', 'TAS'], secondary_y=['altitude'] )
Note
See also
chart()
for the altair equivalent.
- plot_wind(ax, resolution='5 min', 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
]None for a raw plot;
an integer or a string to pass to a
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 cartes.crs 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) )
- point_merge(*args, method, **kwargs)
Detects point-merge structures in trajectories.
Usage: See How to implement point-merge detection?
- Return type:
- predict(*args, method='default', **kwargs)
Predicts the future trajectory based on the past data points.
- Parameters:
method (
Union
[Literal
['default'
,'straight'
,'flightplan'
],PredictBase
]) – By default, the method propagates the trajectory in a straight line.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding prediction class.
The following table summarizes the available methods and their corresponding classes:
straight
(default) usesStraightLinePredict
flightplan
usesFlightPlanPredict
Example usage:
>>> flight.predict(minutes=10, method="straight") >>> flight.before("2018-12-24 23:55").predict(minutes=10) # Merry XMas!
- project_shape(projection=None)
Returns a projected representation of the shape.
- Parameters:
projection (None | pyproj.Proj | ‘crs.Projection) – By default (None), an equivalent projection is applied. Equivalent projections locally respect areas, which is convenient for the area attribute.
- Return type:
base.BaseGeometry
- pushback(*args, method='default', **kwargs)
Detects the push-back phase of the trajectory.
- Parameters:
method (
Union
[Literal
['default'
,'parking_area'
,'parking_position'
],ApplyOptionalBase
]) – By default, the method identifies the start of the movement, the parking_position and the moment the aircraft suddenly changes direction the computed track angle.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding landing detection class.
The following table summarizes the available methods and their corresponding classes:
"parking_area"
(default) usesParkingAreaBasedPushback
and identifies the start of the movement, an intersection with a documented apron area and the moment the aircraft suddenly changes direction in the computed track angle"parking_position"
(default) usesParkingPositionBasedPushback
and identifies the start of the movement, the parking_position and the moment the aircraft suddenly changes direction in the computed track angle.
Usage:
>>> flight.pushback(airport="LSZH", method="default")
- 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(data=None, failure_mode='info', **kwargs)
Extends data with extra columns from EHS messages.
By default, raw messages are requested from the OpenSky Network database. :rtype:
Flight
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.
The data parameter expect three columns:
icao24
,rawmsg
andmintime
, in conformance with the OpenSky API.
- query_opensky(**kwargs)
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
andicao24
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.
- 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(rule='1s', how='interpolate', interpolate_kw={}, projection=None)
Resample the trajectory at a given frequency or for a target number of samples.
- Parameters:
rule (str | int) –
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 (None | str | dict[str, Iterable[str]]) –
(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 (dict[str, Any]) –
(default:
{}
)A dictionary with keyword arguments that will be passed to the pandas interpolate method.
Example usage: To specify a fifth-degree polynomial interpolation, you can pass the following dictionary:
interpolate_kw = {"method": "polynomial", "order": 5}
projection (None | str | pyproj.Proj | ‘crs.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:
Flight
- 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
- scatter_geo(**kwargs)
Create a scatter plot with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Figure
- scatter_map(map_style='carto-positron', **kwargs)
Create a scatter plot with Plotly.
Requires the plotly package (optional dependency).
- Return type:
Figure
- shorten(value=None, **kwargs)
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, strict=True)
Returns True if flight duration is shorter than value.
- Return type:
- simplify(tolerance, altitude=None, z_factor=3.048)
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:
Flight
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 specifyreturn_mask=True
.
- skip(value=None, **kwargs)
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
- 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
- split(value=10, unit=None, condition=None)
Iterates on legs of a Flight based on the distribution 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: :rtype:
FlightIterator
in the NumPy style:
Flight.split(10, 'm')
(seenp.timedelta64
);in the pandas style:
Flight.split('10 min')
(seepd.Timedelta
)
If the condition parameter is set, the flight is split between two segments only if condition(f1, f2) is verified.
Example:
def no_split_below_5000ft(f1, f2): first = f1.data.iloc[-1].altitude >= 5000 second = f2.data.iloc[0].altitude >= 5000 return first or second # would yield many segments belevingsvlucht.query('altitude > 2000').split('1 min') # yields only one segment belevingsvlucht.query('altitude > 2000').split( '1 min', condition = no_split_below_5000ft )
- 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: Timestamp
Returns the minimum value of timestamp.
- property stop: Timestamp
Returns the maximum value of timestamp.
- sum(method)
Returns the number of segments returned by flight.method().
Example usage:
- Return type:
>>> flight.sum("go_around") >>> flight.sum("runway_change") >>> flight.sum(lambda f: f.aligned_on_ils("LFBO"))
- summary(attributes)
Returns a summary of the current Flight 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 dictionary.
- takeoff(*args, method='default', **kwargs)
Detects the takeoff phase in a trajectory.
- Parameters:
method (
Union
[Literal
['default'
,'polygon_based'
,'track_based'
],ApplyIteratorBase
]) – By default, the method detects segments on trajectory maximizing their intersection with a trapeze shape with a small base at runway threshold.- Return type:
If the method argument is passed as a string, then all args and kwargs argument of the landing method are passed to the constructor of the corresponding landing detection class.
The following table summarizes the available methods and their corresponding classes:
"polygon_based"
(default) usesPolygonBasedRunwayDetection
and detects segments on trajectory maximizing their intersection with a trapeze shape with a small base at runway threshold. This method performs better when trajectory data point is scarce at surface level."track_based"
usesTrackBasedRunwayDetection
and detects pieces of trajectory with a strong acceleration that is colinear to a documented runway. This method performs better when data is rich at surface level, with less false positive labelled with the wrong runway.
Usage:
>>> flight.takeoff("EHAM") # returns a flight iterator >>> flight.takeoff("EHAM", method="default") >>> flight.takeoff(airport="EHAM", method="default") >>> flight.takeoff(PolygonBasedRunwayDetection(airport="EHAM"))
More details in the specific documentation for each class.
- takeoff_from(airport)
Returns True if the flight takes off from the given airport.
- Return type:
- thermals()
Detects pieces of trajectory where gliders are in thermals.
The logic implemented detects trajectory ascending and turning at the same time.
Usage:
- Return type:
>>> flight_iterator = flight.thermals()
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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: