### Creating a Flight Subset for Altair Visualization Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Creates a specific subset of flight trajectories from the `quickstart` collection, which will be used for subsequent Altair visualizations. This allows focusing on a smaller, relevant data set for charting examples. ```python subset = quickstart[["TVF22LK", "EJU53MF", "TVF51HP", "TVF78YY", "VLG8030"]] ``` -------------------------------- ### Import Sample Traffic Object from traffic.data Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Imports the 'quickstart' sample Traffic object, which represents a collection of multiple trajectories. This object is used for demonstrating functionalities of the Traffic class. ```python from traffic.data.samples import quickstart ``` -------------------------------- ### Initial Plot of Low-Altitude Trajectories Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet provides an initial visualization of the `quickstart` dataset, which contains low-altitude trajectories. It sets up a matplotlib figure with the Lambert93 projection and plots all trajectories from the dataset with a transparency of 0.7, offering a first look at the traffic patterns. ```Python with plt.style.context("traffic"): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) quickstart.plot(ax, alpha=.7) ``` -------------------------------- ### Select Full Trajectories Landing on Runway 06 from One Minute Before (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet defines a function to identify flights landing on runway 06 at LFPO and returns the full trajectory from one minute before the landing segment. It then applies this function to a lazy iteration of quickstart data and plots the results. ```Python import pandas as pd def last_minute_with_taxi(flight: "Flight") -> "None | Flight": for segment in flight.landing("LFPO"): if segment.ILS_max == "06": return flight.after(segment.stop - pd.Timedelta("1 min")) t3 = quickstart.iterate_lazy().pipe(last_minute_with_taxi).eval() with plt.style.context('traffic'): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) t3.plot(ax, color="#f58518", zorder=3) airports['LFPO'].plot(ax, labels=dict(fontsize=11)) ax.spines['geo'].set_visible(False) ``` -------------------------------- ### Coloring Trajectories by Vertical Rate Mean Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet demonstrates how to color flight trajectories based on their average vertical rate. It iterates through each flight in the `quickstart` dataset, checks for valid vertical rate data, and assigns a color (blue for descending, orange for ascending, green for others) to visualize landing, take-off, or level flight patterns. This provides a more meaningful representation of traffic organization. ```Python import pandas as pd with plt.style.context("traffic"): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) for flight in quickstart: if pd.isna(flight.vertical_rate_mean): continue if flight.vertical_rate_mean < -500: flight.plot(ax, color="#4c78a8", alpha=0.5) # blue elif flight.vertical_rate_mean > 1000: flight.plot(ax, color="#f58518", alpha=0.5) # orange else: flight.plot(ax, color="#54a24b", alpha=0.5) # green ``` -------------------------------- ### Import Sample Flight Object from traffic.data Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Imports the 'belevingsvlucht' sample flight trajectory from the traffic library's sample data module. This object is used throughout the documentation for demonstrations and examples. ```python from traffic.data.samples import belevingsvlucht ``` -------------------------------- ### Install Traffic for Contribution using uv Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst These commands clone the traffic repository and install development dependencies using 'uv sync'. This ensures a reproducible environment with frozen dependency versions, which is crucial for continuous integration and maintaining consistency when contributing to the project. ```bash git clone --depth 1 https://github.com/xoolive/traffic cd traffic/ uv sync --dev --all-extras ``` -------------------------------- ### Install Pre-Commit Hooks with uv Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst This command installs pre-commit hooks using 'uv run', ensuring that a minimum set of sanity checks are performed automatically before commits. This helps contributors fix issues early in the development cycle and prevents continuous integration failures on GitHub Actions. ```bash uv run pre-commit install ``` -------------------------------- ### Access Flight Start and Stop Timestamps Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Retrieves the start and stop timestamps of the Flight object, which correspond to the first and last recorded samples. All timestamps are by default set to Universal Time (UTC). ```python (belevingsvlucht.start, belevingsvlucht.stop) ``` -------------------------------- ### Install Traffic Development Version from GitHub Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst These commands clone the traffic repository from GitHub and install the development version using pip. This method is suitable for users who want the most recent, unreleased features or intend to contribute directly to the project's codebase. ```bash git clone --depth 1 https://github.com/xoolive/traffic cd traffic/ pip install . ``` -------------------------------- ### Collect Landing Trajectories with Traffic.from_flights Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This example defines a generator function `select_landing` to identify flights landing at a specific airport based on altitude, vertical rate, and intersection. It then uses `Traffic.from_flights` to robustly collect these flight objects into a `Traffic` collection, handling potential `None` values. ```python from traffic.core import Traffic def select_landing(airport: "Airport"): for flight in quickstart: if low_alt := flight.query("altitude < 3000"): if not pd.isna(v_mean := low_alt.vertical_rate_mean) and v_mean < -500: if low_alt.intersects(airport): if low_alt.landing(airport).has(): yield low_alt.last("10 min") # Traffic.from_flights is more robust than sum() as the function may yield some None values Traffic.from_flights(select_landing(airports["LFPO"])) ``` -------------------------------- ### Generating Basic Altair Chart for a Single Flight Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Triggers an initial Altair visualization for the first flight in the `subset` collection using the `chart()` method. This provides a default representation that can be further refined with additional Altair encoding and configuration. ```python subset[0].chart() ``` -------------------------------- ### Select First N Minutes of Flight Trajectory Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Selects the initial 30 minutes of the flight trajectory, returning a new Flight object containing only the data from that specific period. This is useful for focusing on specific phases of a flight. ```python belevingsvlucht.first(minutes=30) ``` -------------------------------- ### Install Traffic Library with Conda Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst This command creates a new conda environment named 'traffic' with Python 3.10 and installs the traffic library from the conda-forge channel. It's recommended for a fresh installation to ensure dependency isolation and a clean setup. ```bash conda create -n traffic -c conda-forge python=3.10 traffic conda activate traffic ``` -------------------------------- ### Dockerfile for Simple traffic Library Installation Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/docker.rst A Dockerfile example for installing the traffic library and its dependencies directly into a `jupyter/minimal-notebook` base image. It includes a necessary environment variable setting for PROJ to ensure proper functionality. ```dockerfile FROM jupyter/minimal-notebook USER jovyan RUN mamba install -c conda-forge traffic # manually set environment variable for PROJ when running in base environment ENV PROJ_LIB=/opt/conda/share/proj ``` -------------------------------- ### Pretty Print Flight Object with Rich Library Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Uses the 'rich' library's pprint function to display an enhanced, colorized representation of the Flight object. This improves readability and provides a more structured view of the object's contents. ```python from rich.pretty import pprint pprint(belevingsvlucht) ``` -------------------------------- ### Print Flight Object Using Rich Console Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Demonstrates using the 'rich' Console object to print the Flight object. This method offers more granular control over output formatting and styling, useful for complex console applications. ```python # the console is not necessary if you ran pretty.install() from rich.console import Console console = Console() console.print(belevingsvlucht) ``` -------------------------------- ### Selecting Subset of Flights with a List of Identifiers Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Illustrates how to select a specific subset of trajectories from a Traffic collection by providing a list of flight identifiers (callsigns or ICAO24s). This allows for targeted analysis of multiple known flights. ```python quickstart[['AFR83HQ', 'AFR83PX', 'AFR84UW', 'AFR91QD']] ``` -------------------------------- ### Visualizing Aircraft Airborne Status with Altair Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Demonstrates how to create a meaningful Altair visualization to show when aircraft are airborne, even without plotting physical features on the y-channel. It uses `callsign` on the Y-axis and colors by callsign to represent individual flight timelines. ```python import altair as alt # necessary line if you see an error about a maximum number of rows alt.data_transformers.disable_max_rows() alt.layer( *( flight.chart().encode( alt.Y("callsign", sort="x", title=None), alt.Color("callsign", legend=None), ) for flight in subset ) ).configure_line(strokeWidth=4) ``` -------------------------------- ### Select Flight Data After Specific Timestamp Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Filters the flight data to include only samples recorded after '2018-05-30 19:00' UTC. The 'strict=False' parameter ensures that samples exactly at the specified time are also included. ```python belevingsvlucht.after("2018-05-30 19:00", strict=False) ``` -------------------------------- ### Print Basic Representation of Flight Object Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Displays the default string representation of a Flight object in a Python interpreter. This provides a quick, concise overview of the flight's key characteristics. ```python print(belevingsvlucht) ``` -------------------------------- ### Filter and Plot Last 10 Minutes of LFPO Landings (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet filters trajectories that landed at LFPO airport within the last 10 minutes. It then plots these trajectories on a map, highlighting the LFPO airport and its runways. ```Python t1 = ( quickstart .has("landing('LFPO')") .last('10 min') .eval(max_workers=4) ) with plt.style.context('traffic'): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) t1.plot(ax, color="#f58518") airports['LFPO'].plot( ax, footprint=False, runways=dict(linewidth=1, color='black', zorder=3) ) ax.spines['geo'].set_visible(False) ``` -------------------------------- ### Quick Interactive Map with Leaflet Widget Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst For quick interactive representations with a small number of elements, this snippet demonstrates using the Leaflet widget. It calls the `map_leaflet` method on a subset of traffic data to generate an interactive map centered with a specified zoom level. ```Python subset.map_leaflet(zoom=8) ``` -------------------------------- ### Visualizing Flight Data with Matplotlib Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Demonstrates how to plot flight trajectories over time using Matplotlib, applying the 'traffic' style context for consistent styling. It shows plotting altitude and groundspeed with dual Y-axes and custom date formatting for the X-axis. ```python import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter with plt.style.context("traffic"): fig, ax = plt.subplots(figsize=(10, 7)) ( belevingsvlucht .between("2018-05-30 19:00", "2018-05-30 20:00") .plot_time( ax=ax, y=["altitude", "groundspeed"], secondary_y=["groundspeed"] ) ) ax.set_xlabel("") ax.tick_params(axis='x', labelrotation=0) ax.xaxis.set_major_formatter(DateFormatter("%H:%M")) ``` -------------------------------- ### Refining Altair Charts with Customization Options Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Shows how to apply advanced customizations to Altair charts, including formatting the X-axis for time, setting Y-axis scale and title, configuring legend orientation, and styling the chart title for enhanced readability and presentation. ```python chart = ( alt.layer( *( flight.chart().encode( alt.X( "utcdayhoursminutesseconds(timestamp)", axis=alt.Axis(format="%H:%M"), title=None, ), alt.Y("altitude", title=None, scale=alt.Scale(domain=(0, 18000))), alt.Color("callsign"), ) for flight in subset ) ) .properties(title="altitude (in ft)") # "trick" to display the y-axis title horizontally .configure_legend(orient="bottom") .configure_title(anchor="start", font="Lato", fontSize=16) ) chart ``` -------------------------------- ### Plotting Physical Quantities with Altair Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Illustrates how to plot physical quantities like altitude on the Y-channel using Altair. It layers charts for multiple flights, encoding altitude on the Y-axis and coloring by callsign to differentiate trajectories. ```python alt.layer( *( flight.chart().encode( alt.Y("altitude"), alt.Color("callsign"), ) for flight in subset ) ) ``` -------------------------------- ### Select Flight Data Between Timestamps and Access DataFrame Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Filters the flight data to include samples between '2018-05-30 19:00' and '2018-05-30 20:00' UTC. It then accesses the underlying pandas DataFrame for direct manipulation and analysis. ```python belevingsvlucht.between("2018-05-30 19:00", "2018-05-30 20:00").data ``` -------------------------------- ### Enable Matplotlib Inline Display in Jupyter Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This command enables inline plotting for Matplotlib in a Jupyter environment. It ensures that plots are displayed directly within the notebook output, facilitating interactive data visualization. ```python %matplotlib inline ``` -------------------------------- ### Install Traffic Library with Poetry Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Installs the Traffic library using Poetry, recommended for development. This ensures consistent dependency versions across different environments, crucial for continuous integration. ```bash poetry install ``` -------------------------------- ### Interactive Trajectory Visualization with Altair Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This code generates an interactive visualization of landing trajectories using Altair. It layers individual flight trajectories, encoding them by callsign color, and sets properties for the chart title, legend, and view configuration. This method is suitable for displaying a moderate number of elements interactively. ```Python from traffic.data import airports chart = ( alt.layer( *(flight.geoencode().encode(alt.Color("callsign:N")) for flight in subset) ) .properties(title="Landing trajectories at Paris–Orly airport") .configure_legend(orient="bottom") .configure_view(stroke=None) .configure_title(anchor="start", font="Lato", fontSize=16) ) chart ``` -------------------------------- ### Traffic Library Core Classes and Methods API Reference Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This section provides an API reference for key classes and methods from the `traffic` library, detailing their purpose and usage in flight trajectory processing, including `Flight` objects, `Traffic` collections, and methods for collecting and evaluating trajectories. ```APIDOC traffic.core.Flight: Description: Represents a single flight trajectory. Usage: - Base object for trajectory processing. - Methods returning Optional[Flight] or boolean can be stacked for lazy iteration. - Most methods can be stacked on Traffic structures. traffic.core.Traffic: Description: A collection of Flight objects. Methods: from_flights(iterable_of_flights): Description: Builds a Traffic object from an iterable of Flight objects. Parameters: iterable_of_flights: An iterable structure containing Flight objects. Returns: A new Traffic object. Notes: More robust than sum() as it ignores None objects. traffic.core.Flight.landing(airport: "Airport"): Description: A method to determine if a flight is landing at a specified airport. Usage: Can be used as part of a stacked operation for trajectory selection. .eval(max_workers: int = 1, desc: str = None): Description: Triggers the evaluation of all stacked methods on a Traffic object. Parameters: max_workers: Number of cores to use for multiprocessing (defaults to 1). desc: Argument to create a progress bar. Returns: A new Traffic object with evaluated flights. Notes: Starts a single iteration applying all stacked methods. Discards flights if a method returns False or None. ``` -------------------------------- ### Activate Conda Environment for Traffic Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst This command activates the previously created 'traffic' conda environment. It must be run each time you intend to use the traffic library to ensure all its dependencies are correctly loaded and accessible. ```bash conda activate traffic ``` -------------------------------- ### Install traffic with Plotly dependency Source: https://github.com/xoolive/traffic/blob/master/docs/visualize/plotly.rst Instructions on how to install the 'traffic' library with Plotly support. This can be done by specifying the 'plotly' or 'full' extra at installation time using pip or poetry, or by manually installing Plotly. ```bash # at install time pip install traffic[plotly] # or full # with poetry poetry install traffic -E plotly # or -E full # or simply manually pip install plotly conda install -c conda-forge plotly ``` -------------------------------- ### Install traffic library with Leaflet support Source: https://github.com/xoolive/traffic/blob/master/docs/visualize/leaflet.rst Instructions on how to install the `traffic` library with `leaflet` optional dependency using pip, poetry, or by manually installing `ipyleaflet` and `ipywidgets`. ```bash pip install traffic[leaflet] # or full poetry install traffic -E leaflet # or -E full pip install ipyleaflet ipywidgets conda install -c conda-forge ipyleaflet ipywidgets ``` -------------------------------- ### Display Flight Object in Jupyter Notebook Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Shows the default rich representation of a Flight object when it is the last expression in a Jupyter notebook cell. This provides an interactive and visually appealing display of the flight data. ```python belevingsvlucht ``` -------------------------------- ### Declarative Landing Trajectory Selection with Lazy Evaluation Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This Python code showcases the lazy evaluation capabilities of the traffic library. It chains multiple flight methods like `query`, `feature_lt`, `intersects`, and `has` which are stacked and only evaluated in a single pass when `.eval()` is called, optionally using multiprocessing. ```python ( quickstart.query("altitude < 3000") # Lazy iteration is triggered here by the .feature_lt method .feature_lt("vertical_rate_mean", -500) .intersects(airports["LFPO"]) .has('landing("LFPO")') .last("10 min") # Now evaluation is triggered on 4 cores .eval(max_workers=4) ) ``` -------------------------------- ### Advanced Flight Phase Visualization with Cartes and Matplotlib Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This code generates a multi-subplot visualization of flight descent and climb phases across multiple Paris airports (LFPO, LFPG, LFPB). It incorporates geographical background elements like the Greater Paris Area and Seine river using `cartes` and plots flight trajectories based on time thresholds, providing insights into traffic organization during different configurations. ```Python from cartes.atlas import france from cartes.crs import Lambert93, PlateCarree from cartes.osm import Nominatim # background elements paris_area = france.data.query("ID_1 == 1000") seine_river = ( Nominatim.search("Seine river, France") .shape.intersection( paris_area.union_all().buffer(0.1) ) ) with plt.style.context("traffic"): fig, ax = plt.subplots( 3, 2, figsize=(10, 15), subplot_kw=dict(projection=Lambert93()) ) airport_codes = ["LFPO", "LFPG", "LFPB"] for flight in quickstart: phases = flight.phases() if phases.query('phase == "DESCENT"'): # Determine on which ax to plot based on detected airport for airport_index, airport in enumerate(airport_codes): if segment := flight.landing(airport).next(): # Determine on which column to plot based on time time_index = int(segment.stop <= pd.Timestamp("2021-10-07 13:20Z")) flight.plot( ax[airport_index, time_index], color="#4c78a8", alpha=0.4 ) break elif phases.query('phase == "CLIMB"'): # Determine on which ax to plot based on detected airport for airport_index, airport in enumerate(airport_codes): if segment := flight.takeoff(airport).next(): # Determine on which column to plot based on time time_index = int(segment.start <= pd.Timestamp("2021-10-07 13:20Z")) flight.plot( ax[airport_index, time_index], color="#f58518", alpha=0.4 ) break ``` -------------------------------- ### Visualizing Flight Landing ILS Data with Altair Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This code generates an Altair chart to visualize the ILS (Instrument Landing System) values against the stop time for flights, grouped by airport. It uses a square mark and custom axis/header configurations to display runway configuration changes over time. ```Python chart = ( alt.Chart(stats) .encode( alt.X("utcdayhoursminutesseconds(stop)", axis=alt.Axis(format="%H:%M"), title=None), alt.Y("ILS", title=None), alt.Color("ILS", legend=None), alt.Row("airport", title=None), ) .mark_square(size=80) .resolve_scale(y="independent") .configure_header( labelOrient="top", labelAnchor="start", labelFont="Lato", labelFontWeight="bold", labelFontSize=16, ) .configure_axis(labelFontSize=13) .properties(width=600) ) chart ``` -------------------------------- ### Indexing Traffic Collection by Position or Slice Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Shows how to retrieve flights from a Traffic collection based on their numerical position or a slice. Indexing with an integer returns a single Flight object, while a slice returns a Traffic collection containing multiple trajectories. ```python quickstart[0] # return type: Flight, the first trajectory in the collection quickstart[:10] # return type: Traffic, the 10 first trajectories in the collection ``` -------------------------------- ### Accessing Flight Properties (Start Time, Callsign, Duration) Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Illustrates how to retrieve basic properties of a Flight object, including its start time, callsign, and total duration. These attributes provide quick insights into the trajectory. ```python g.start ``` ```python g.callsign ``` ```python g.duration ``` -------------------------------- ### Filter and Plot Last Minute of Runway 06 Alignment at LFPO (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This code selects the last minute of trajectory segments that are aligned with runway 06 at LFPO airport. The filtered trajectories are then plotted, showing their path relative to the airport. ```Python t2 = ( quickstart .next('landing("LFPO")') .query("ILS == '06'") .last("1 min") .eval(max_workers=4) ) with plt.style.context('traffic'): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) t2.plot(ax, color="#f58518") airports['LFPO'].plot(ax, labels=dict(fontsize=11)) ax.spines['geo'].set_visible(False) ``` -------------------------------- ### Filtering Traffic Collection with Pandas-like Query Method Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Demonstrates using the `query` method, similar to pandas, to filter the Traffic collection based on conditions applied to flight attributes, such as callsign patterns. This provides a flexible way to select data based on complex criteria. ```python quickstart.query('callsign.str.startswith("AFR")') ``` -------------------------------- ### Activate Jupyter Notebook Widget Extensions Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Enables the necessary Jupyter Notebook extensions for widgets to display correctly, specifically 'widgetsnbextension' and 'ipyleaflet', using the system-wide prefix. ```bash jupyter nbextension enable --py --sys-prefix widgetsnbextension jupyter nbextension enable --py --sys-prefix ipyleaflet ``` -------------------------------- ### Extracting Flight Landing Information with Pandas Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet iterates through flight data, identifies landing segments at specific Paris airports (LFPO, LFPG, LFPB), and collects details such as callsign, ICAO24, airport, stop time, and ILS maximum. The collected data is then converted into a pandas DataFrame for further analysis. ```Python import pandas as pd from tqdm.rich import tqdm information = list() for flight in tqdm(quickstart): if landing := flight.landing("LFPO").next(): information.append( { "callsign": flight.callsign, "icao24": flight.icao24, "airport": "LFPO", "stop": landing.stop, "ILS": landing.ILS_max, } ) elif landing := flight.landing("LFPG").next(): information.append( { "callsign": flight.callsign, "icao24": flight.icao24, "airport": "LFPG", "stop": landing.stop, "ILS": landing.ILS_max, } ) elif landing := flight.landing("LFPB").next(): information.append( { "callsign": flight.callsign, "icao24": flight.icao24, "airport": "LFPB", "stop": landing.stop, "ILS": landing.ILS_max, } ) stats = pd.DataFrame.from_records(information) stats ``` -------------------------------- ### Install Traffic Library with Pip Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Installs the Traffic library using pip. Users are responsible for managing non-Python dependencies when using this method. ```bash pip install traffic ``` -------------------------------- ### Activate Jupyter Lab Widget Extensions Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Installs and activates the necessary Jupyter Lab extensions for widgets to display correctly, specifically '@jupyter-widgets/jupyterlab-manager' and 'jupyter-leaflet'. ```bash jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install jupyter-leaflet ``` -------------------------------- ### Identify and Visualize Trajectories with Multiple Runway Alignments at LFPG (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This code defines a function to detect flights with more than one runway alignment at LFPG airport. It then processes these flights and generates an Altair chart visualizing the flight path, including different runway alignment segments and a forward projection. ```Python def more_than_one_alignment(flight: "Flight") -> "None | Flight": segments = flight.landing("LFPG") if first := next(segments, None): if second := next(segments, None): return flight.after(first.start - pd.Timedelta('90s')) t4 = quickstart.iterate_lazy().pipe(more_than_one_alignment).eval() flight = t4[0] segments = flight.landing("LFPG") first = next(segments) forward = first.first("70s").forward(minutes=4) chart = ( alt.layer( airports["LFPG"].geoencode( footprint=False, runways=dict(strokeWidth=1), labels=dict(fontSize=10) ), flight.geoencode().mark_line(stroke="#bab0ac"), forward.geoencode(stroke="#79706e", strokeDash=[7, 3], strokeWidth=0.8), first.geoencode().encode(alt.Color("ILS")), next(segments).geoencode().encode(alt.Color("ILS")) ) .properties( title=f"Runway change at LFPG airport with {flight.callsign}", width=600 ) .configure_view(stroke=None) .configure_legend(orient="bottom") .configure_title(font="Lato", fontSize=16, anchor="start") ) chart ``` -------------------------------- ### Install Traffic Library with Anaconda Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Installs the Traffic library using Anaconda, which is the recommended and simplest method. It creates a new conda environment named 'traffic' with Python 3.9 and installs the library from the conda-forge channel. ```bash conda create -n traffic -c conda-forge python=3.9 traffic ``` -------------------------------- ### Filtering Trajectories by Airport Intersection Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet refines trajectory selection by checking if the first or last five minutes of a flight intersect with a specific airport's geographical shape (LFPO). It plots landing trajectories (descending) if their end intersects the airport, and take-off trajectories (ascending) if their beginning intersects. This method helps focus on traffic directly associated with a particular airport. ```Python from traffic.data import airports with plt.style.context("traffic"): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) for flight in quickstart: if pd.isna(flight.vertical_rate_mean): continue if flight.vertical_rate_mean < -500: if flight.last("5 min").intersects(airports["LFPO"]): flight.plot(ax, color="#4c78a8", alpha=0.5) elif flight.vertical_rate_mean > 1000: if flight.first("5 min").intersects(airports["LFPO"]): flight.plot(ax, color="#f58518", alpha=0.5) ``` -------------------------------- ### Slicing Flight Trajectory by Duration (First N Minutes) Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Shows how to extract a specific segment from a flight trajectory, for example, the first 10 minutes. This is useful for focusing on particular phases of a flight. ```python g.first('10 min') ``` -------------------------------- ### Run GitHub traffic Jupyter Docker Container Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/docker.rst Command to start an interactive Docker container from the pre-built GitHub image, mapping port 8888 to access the Jupyter notebook via a web browser. ```bash docker run -it -p 8888:8888 ghcr.io/xoolive/traffic/jupyter ``` -------------------------------- ### Update Traffic Library in Conda Environment Source: https://github.com/xoolive/traffic/blob/master/docs/installation.rst This command updates the traffic library to its latest version within the specified 'traffic' conda environment. It fetches updates from the conda-forge channel, ensuring your installation is current and benefits from the latest features and bug fixes. ```bash conda update -n traffic -c conda-forge traffic ``` -------------------------------- ### Visualizing Trajectory with Navaids and Multiple Highlights Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Demonstrates how to load navigation aid (navaids) data and visualize a flight trajectory on a Leaflet map. It also shows how to highlight multiple detected events, such as landing and alignment with a VOR, using different colors. ```python from traffic.data import navaids m = g.last('30 min').map_leaflet( zoom=10, highlight={ "red": 'landing("EGLL")', "#f58518": 'aligned("OCK")' } ) ``` -------------------------------- ### API Reference: traffic.core.Traffic Class Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst The core class for representing collections of trajectories. All trajectories are flattened into a single pandas DataFrame, providing methods for indexing and iterating over individual flights. ```APIDOC traffic.core.Traffic: Description: Core class for collections of trajectories, flattened into a single pandas.DataFrame. Features: - Indexing on all contained flights. - Iteration on all contained flights. Flight Identification: - Uses a customizable 'flight_id' or other heuristics to separate trajectories. ``` -------------------------------- ### API Reference: traffic.core.Flight Class Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst The core class for representing single aircraft trajectories. It wraps a pandas DataFrame and provides natural methods and attributes for trajectory manipulation and analysis. ```APIDOC traffic.core.Flight: Description: Core class for single trajectories, wrapped around a pandas.DataFrame. Data Sources: - Sample trajectory set - OpenSky Impala shell (ADS-B data) - Tabular files (csv, json, parquet) - Raw ADS-B signals Attributes/Properties: - start: Timestamp of the first recorded sample (UTC). - stop: Timestamp of the last recorded sample (UTC). Methods: - first(minutes: int): Selects the first N minutes of the flight. - after(timestamp: str, strict: bool = False): Selects data after a specific timestamp. 'strict=False' includes the timestamp. - between(start_ts: str, end_ts: str): Selects data between two timestamps. - data: Accesses the underlying pandas.DataFrame. ``` -------------------------------- ### Display Traffic Object in Jupyter Notebook Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Shows the default summary representation of a Traffic object when it is the last expression in a Jupyter notebook cell. This provides an overview of the contained trajectories and their sample counts. ```python quickstart ``` -------------------------------- ### Loading Airport Data from OpenStreetMap Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Demonstrates how to load airport data, including details like parking positions, from the OpenStreetMap database using the 'traffic.data.airports' module. This data is crucial for ground-based trajectory analysis. ```python from traffic.data import airports airports['LFBO'] ``` -------------------------------- ### Convert Flight Object to Dictionary Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Converts the Flight object into a dictionary, allowing direct access to its underlying attributes and properties as key-value pairs. This is useful for inspecting or manipulating the flight's metadata. ```python dict(belevingsvlucht) ``` -------------------------------- ### Query FIR Airspaces in France Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/airspaces.rst Filters the `nm_airspaces` GeoDataFrame to select all 'FIR' type airspaces whose designator starts with 'LF' (France). This example shows how pandas query syntax can be used for complex subsetting. ```python france_fir = nm_airspaces.query('type == "FIR" and designator.str.startswith("LF")') france_fir.head(10) ``` -------------------------------- ### Detecting Aircraft Pushback from Parking Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Shows how to use the built-in 'pushback' detection method to identify when an aircraft is performing a pushback maneuver from a parking position at a given airport. This method leverages the parking position detection. ```python g.first('10 min').pushback('LFBO') ``` -------------------------------- ### Indexing Traffic Collection by Callsign or ICAO24 Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Demonstrates how to access individual Flight objects from a Traffic collection using either an aircraft's callsign or its ICAO24 identifier. This method provides direct access to specific flight trajectories. ```python quickstart["TAR722"] # return type: Flight, based on callsign quickstart["39b002"] # return type: Flight, based on icao24 ``` -------------------------------- ### Loading Traffic Data from JSONL Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Demonstrates how to load flight data from a compressed JSONL file into a Traffic object using the 'traffic.core.Traffic.from_file()' method. This is the initial step for working with flight trajectories. ```python from traffic.core import Traffic t = Traffic.from_file("tutorial.jsonl.gz") t ``` -------------------------------- ### Load Belevingsvlucht Sample Trajectory (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/samples.rst Demonstrates how to load the 'Belevingsvlucht' sample trajectory, a test flight conducted to assess noise exposure near Lelystad Airport, from the `traffic.data.samples` module. ```Python from traffic.data.samples import belevingsvlucht belevingsvlucht ``` -------------------------------- ### Configure Matplotlib Axes for Airport Visualization Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This Python snippet iterates through airport codes to set individual subplot titles and adds geographical elements like the Seine river and Paris area boundaries to each axis for context in a flight visualization. ```python for i, airport in enumerate(airport_codes): ax[i, 0].set_title(f"{airport}", loc="left", y=0.8) for ax_ in ax.ravel(): # Background map ax_.add_geometries( [seine_river], crs=PlateCarree(), facecolor="none", edgecolor="#9ecae9", linewidth=1.5, ) paris_area.set_crs(4326).to_crs(2154).plot( ax=ax_, facecolor="none", edgecolor="#bab0ac", linestyle="dotted", ) ax_.set_extent((0.78, 4.06, 47.7, 49.7)) fig.suptitle( "West and East configurations in Paris airports", fontsize=16, x=0.1, y=0.9, ha="left", ) ``` -------------------------------- ### Resampling Flight Trajectory to Regular Intervals Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Shows how to resample a Flight object to a regular time interval, such as every 1 second. This process generates proper state vectors, which is often a comfortable starting point for further analysis and ensures consistent data density. ```python g = f.resample('1s') g ``` -------------------------------- ### Assigning Flight Identifiers to Trajectories Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst Shows the most common way to assign a unique flight identifier to trajectories within the Traffic collection using the `assign_id()` method. The `.eval()` method is then used to trigger immediate computation and evaluation of the assigned IDs. ```python quickstart.assign_id().eval() ``` -------------------------------- ### Accessing Parking Positions at an Airport Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Illustrates how to access specific attributes of an airport structure, such as parking positions, which are returned as a GeoDataFrame. This allows for detailed analysis of ground infrastructure. ```python airports['LFBO'].parking_position ``` -------------------------------- ### Dockerfile for Jupyter with Custom Conda Environment Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/docker.rst A Dockerfile example for integrating an existing Conda environment (defined in `traffic.yml`) into a `jupyter/minimal-notebook` container. It copies the environment file, installs `nb_conda` for Jupyter integration, and creates the specified Conda environment. ```dockerfile FROM jupyter/minimal-notebook # copy conda environment file to image COPY traffic.yml traffic.yml # install nb_conda into the base python to allow the user to choose the # environment in the jupyter notebook and install environment USER jovyan RUN mamba install -y nb_conda RUN mamba env create -f traffic.yml ``` -------------------------------- ### Plotting Flight Trajectories by Time and Segment Type Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet visualizes flight paths on a map using Matplotlib, distinguishing between landing and takeoff segments at LFPO. It applies a time-based filter to plot trajectories on different subplots, suggesting a coordinated runway configuration change. ```Python with plt.style.context("traffic"): fig, ax = plt.subplots(1, 2, subplot_kw=dict(projection=Lambert93())) for flight in quickstart: if segment := flight.landing("LFPO").next(): index = int(flight.stop <= pd.Timestamp("2021-10-07 13:30Z")) flight.plot(ax[index], color="#4c78a8", alpha=0.5) elif segment := flight.takeoff("LFPO").next(): index = int(segment.start <= pd.Timestamp("2021-10-07 13:20Z")) flight.plot(ax[index], color="#f58518", alpha=0.5) ``` -------------------------------- ### Index Traffic Collections by Position or Callsign Source: https://github.com/xoolive/traffic/blob/master/docs/user_guide/arithmetics.rst The `[]` (bracket) operator provides flexible indexing for Traffic collections, allowing retrieval of one or many trajectories. This example demonstrates how to get the first trajectory, the first ten trajectories using slicing, and a specific trajectory by its callsign. ```python # The first trajectory in the dataset switzerland[0] # The ten first trajectories in the dataset switzerland[:10] # The trajectory assigned with callsign ``EZY12VJ`` switzerland['EZY12VJ'] ``` -------------------------------- ### Load Airbus Tree Sample Trajectory (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/samples.rst Demonstrates how to load the 'Airbus tree' sample trajectory, a test flight that traced the outline of a Christmas tree, from the `traffic.data.samples` module. ```Python from traffic.data.samples import airbus_tree airbus_tree ``` -------------------------------- ### List Available Sample Trajectory Categories (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/samples.rst Shows how to list the different categories under which sample trajectories are organized within the `traffic.data.samples` module using Python's `pkgutil`. ```Python from pkgutil import iter_modules # one of Python inspection modules from traffic.data import samples list(category.name for category in iter_modules(samples.__path__)) ``` -------------------------------- ### Load Sample Trajectory with traffic.data.samples Source: https://github.com/xoolive/traffic/blob/master/docs/user_guide/simplify.rst Demonstrates how to load a sample ADS-B trajectory, `texas_longhorn`, from the `traffic.data.samples` module for further processing and analysis. ```Python from traffic.data.samples import texas_longhorn texas_longhorn ``` -------------------------------- ### API Documentation for Take-off Detection Module Source: https://github.com/xoolive/traffic/blob/master/docs/api_reference/traffic.algorithms.navigation.rst Documents the `traffic.algorithms.navigation.takeoff` module, which provides functionalities for detecting take-off events in aviation traffic data. This entry specifies that all public members of this module are documented. ```APIDOC Module: traffic.algorithms.navigation.takeoff Members: All public classes, functions, and variables. ``` -------------------------------- ### Determining Landing Stop Time from First Landing Segment Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Shows how to use the 'next()' method on a FlightIterator (resulting from 'landing()') to get the first landing segment and then extract its stop time. This stop time serves as a proxy for the actual landing time. ```python g.landing('EGLL').next().stop ``` -------------------------------- ### Plotting Landing Trajectories at Paris–Orly Airport with Lambert93 Projection Source: https://github.com/xoolive/traffic/blob/master/docs/quickstart.rst This snippet demonstrates how to plot landing trajectories at Paris–Orly airport using the Lambert93 projection. It initializes a matplotlib figure with the specified projection, plots the airport footprint and runways, and then overlays individual flight trajectories. The plot is titled to indicate its content. ```Python from cartes.crs import Lambert93 from traffic.data import airports with plt.style.context("traffic"): fig, ax = plt.subplots(subplot_kw=dict(projection=Lambert93())) airports["LFPO"].plot(ax, footprint=False, runways=dict(linewidth=1)) for flight in subset: flight.plot(ax, linewidth=2) ax.set_title("Landing trajectories at Paris–Orly airport") ``` -------------------------------- ### Detecting Landing Runway for a Flight Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst Explains how to use the 'landing' method to detect the landing runway for a flight at a specified airport. This method often relies on Instrument Landing System (ILS) data for precise alignment. ```python g.landing('EGLL') ``` -------------------------------- ### Load Dreamliner Air France Sample Trajectories (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/samples.rst Shows how to load the 'Dreamliner Air France' sample trajectories, which include a Boeing 787 and a Socata TBM 900, from the `traffic.data.samples` module. ```Python from traffic.data.samples import dreamliner_airfrance dreamliner_airfrance ``` -------------------------------- ### Importing Airways and Navaids Data in Python Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/navigation.rst This snippet demonstrates how to import the `airways` and `navaids` datasets from the `traffic.data` module. These datasets provide basic information about air navigation elements, which can be augmented by configuring additional data sources for improved accuracy. ```python from traffic.data import airways, navaids ``` -------------------------------- ### Charting Flight Phases with Resampling Source: https://github.com/xoolive/traffic/blob/master/docs/tutorial.rst This snippet illustrates how to resample flight phase data to 10-second intervals and then generate an interactive chart. The 'phase' attribute is used for both the y-axis and color encoding, providing a visual representation of flight phases. ```python # resample first to limit the size of the javascript g.phases().resample('10s').chart('phase').encode(y="phase", color='phase').mark_point() ``` -------------------------------- ### Create Traffic Object from Sample Flights (Python) Source: https://github.com/xoolive/traffic/blob/master/docs/data_sources/samples.rst Illustrates how to create a `Traffic` object by combining multiple flights, which is equivalent to summing them, using `Traffic.from_flights`. ```Python from traffic.core import Traffic t_surveys = Traffic.from_flights( # actually, this is equivalent to sum(...) ) ``` -------------------------------- ### Install Cartopy and Shapely with Conda Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Installs Cartopy and Shapely using conda. This is the recommended approach for resolving issues related to plotting crashes, as these libraries depend on 'geos' and 'proj'. ```bash conda install cartopy shapely ``` -------------------------------- ### Traffic Library Core API Reference for Go-Arounds Source: https://github.com/xoolive/traffic/blob/master/docs/navigation/go_around.rst Reference documentation for key classes and methods in the `traffic` library related to detecting, analyzing, and querying go-around events in flight trajectories. ```APIDOC traffic.core.Flight: go_around(airport_icao: str) -> traffic.core.FlightIterator Description: Detects go-around situations for a flight at a specified airport. Parameters: airport_icao: The ICAO code of the airport (e.g., "LSZH"). Returns: A FlightIterator containing segments identified as go-arounds. landing(airport_icao: str) -> traffic.core.FlightIterator Description: Identifies landing attempts for a flight at a specified airport. Parameters: airport_icao: The ICAO code of the airport (e.g., "LSZH"). Returns: A FlightIterator containing landing segments. has(method_call: str | Callable[..., traffic.core.FlightIterator]) -> bool Description: Checks if a Flight object satisfies a condition. Parameters: method_call: A function returning a FlightIterator or a string representing a Flight method call (e.g., 'go_around("LSZH")'). Returns: True if the condition is met (iterator is not empty), False otherwise. traffic.core.FlightIterator: has() -> bool Description: Checks if the FlightIterator is not empty. Returns: True if the iterator contains elements, False otherwise. traffic.core.lazy.LazyTraffic: Description: A class designed to stack operations efficiently on flight data, often used with the 'has' method for filtering. ``` -------------------------------- ### Disable Conda Channel Priority to Resolve Slow Installation Source: https://github.com/xoolive/traffic/blob/master/docs/troubleshooting/installation.rst Disables the channel_priority option in conda configuration. This can help resolve issues with slow installation or conda stalling during the dependency resolution process. ```bash conda config --set channel_priority disabled ``` -------------------------------- ### API Documentation for Flight Phase Detection Module Source: https://github.com/xoolive/traffic/blob/master/docs/api_reference/traffic.algorithms.navigation.rst Documents the `traffic.algorithms.navigation.phases` module, which provides functionalities for detecting various flight phases in aviation traffic data. This entry specifies that all public members of this module are documented. ```APIDOC Module: traffic.algorithms.navigation.phases Members: All public classes, functions, and variables. ``` -------------------------------- ### API Reference: traffic.algorithms.generation.Generation Class Source: https://github.com/xoolive/traffic/blob/master/docs/statistical/generation.rst Provides detailed API documentation for the `Generation` class, which is designed for creating synthetic traffic data. It outlines the constructor parameters and key methods (`fit()` and `sample()`) for interacting with generative models. ```APIDOC class traffic.algorithms.generation.Generation: __init__(generation, features, scaler=None) generation: Any object implementing `fit()` and `sample()` methods. It defines the generative model to use. features: The list of the features to represent a trajectory. scaler: An optional scaler to make sure each feature weights the same during the fitting part. fit(traffic_object) Fits the generative model to a `Traffic` object. sample(num_samples, projection=None) Generates new `Traffic` data by sampling from the fitted model. ```