def create_map(self, projection: Union[str, Projection] = "EuroPP()") -> None: if isinstance(projection, str): if not projection.endswith(")"): projection = projection + "()" projection = eval(projection) self.projection = projection self.trajectories.clear() with plt.style.context("traffic"): self.fig.clear() self.ax = self.fig.add_subplot(111, projection=self.projection) projection_name = projection.__class__.__name__.split(".")[-1] self.ax.add_feature( countries(scale="10m" if projection_name not in ["Mercator", "Orthographic"] else "110m")) if projection_name in ["Lambert93", "GaussKruger", "Amersfoort"]: # Hardcoded projection list?! :o/ self.ax.add_feature(rivers()) self.fig.set_tight_layout(True) self.ax.background_patch.set_visible(False) self.ax.outline_patch.set_visible(False) self.ax.format_coord = lambda x, y: "" self.ax.set_global() self.draw()
def plot_trajs(t, sector, proj=Lambert93()): n_clusters_ = int(1 + t.data.cluster.max()) # -- dealing with colours -- color_cycle = cycle( ["#377eb8", "#ff7f00", "#4daf4a", "#f781bf"] + ["#a65628", "#984ea3", "#999999", "#e41a1c", "#dede00"]) colors = list(islice(color_cycle, n_clusters_)) colors.append("#aaaaaa") # color for outliers, if any # -- dealing with the grid -- nb_cols = 5 nb_lines = (1 + n_clusters_) // nb_cols + (( (1 + n_clusters_) % nb_cols) > 0) def ax_iter(axes): if len(axes.shape) == 1: yield from axes if len(axes.shape) == 2: for ax_ in axes: yield from ax_ with plt.style.context("traffic"): fig, ax = plt.subplots( nb_lines, nb_cols, subplot_kw=dict(projection=proj), figsize=(15, 25), ) for cluster, ax_ in tqdm( zip(range(t.data.cluster.min(), n_clusters_), ax_iter(ax))): ax_.add_feature(countries()) ax_.add_feature(rivers()) tc = t.query(f"cluster == {cluster}") len_tc = len(tc) tc = tc[sample(tc.flight_ids, min(50, len(tc)))] tc.plot(ax_, color=colors[cluster]) vr = tc.data.vertical_rate.mean() alt = tc.data.altitude.mean() // 100 evolution = "=" if abs(vr) < 200 else "↗" if vr > 0 else "↘" ax_.set_title(f"{alt:.0f}FL{evolution}\nlen cluster:{len_tc}") if sector is not None: ax_.set_extent(sector) sector.plot(ax_, lw=2)
def plot_trajs(tc, sector): n_clusters_ = int(1 + tc.data.cluster.max()) # -- dealing with colours -- color_cycle = cycle( ["#377eb8", "#ff7f00", "#4daf4a", "#f781bf"] + ["#a65628", "#984ea3", "#999999", "#e41a1c", "#dede00"]) colors = list(islice(color_cycle, n_clusters_)) colors.append("#aaaaaa") # color for outliers, if any # -- dealing with the grid -- nb_cols = 3 nb_lines = (1 + n_clusters_) // nb_cols + (( (1 + n_clusters_) % nb_cols) > 0) def ax_iter(axes): if len(axes.shape) == 1: yield from axes if len(axes.shape) == 2: for ax_ in axes: yield from ax_ with plt.style.context("traffic"): fig, ax = plt.subplots(nb_lines, nb_cols, subplot_kw=dict(projection=Lambert93())) for cluster, ax_ in zip(range(-1, n_clusters_), ax_iter(ax)): ax_.add_feature(countries()) ax_.add_feature(rivers()) tc.query(f"cluster == {cluster}").plot(ax_, color=colors[cluster]) ax_.set_extent(sector) sector.plot(ax_, lw=2)
def plot_data(flights: Traffic, airport: Airport, output: Path, arrival: int=1): fig = plt.figure(figsize=(10, 10)) ax = plt.axes(projection=UTM((airport.lon + 180) // 6, southern_hemisphere=(airport.lat > 0))) ax.add_feature(countries(scale='50m')) ax.add_feature(rivers(scale='50m')) ax.add_feature(lakes(scale='50m')) ax.gridlines() ax.set_extent(airport.extent) try: from cartotools.osm import request, tags request(f'{airport.icao} airport', **tags.airport).plot(ax) except Exception: pass fd = flights.data fd = fd[fd.longitude > airport.lon - 1] fd = fd[fd.longitude < airport.lon + 1] fd = fd[fd.latitude > airport.lat - 1] fd = fd[fd.latitude < airport.lat + 1] fd = fd.groupby('callsign').filter( lambda f: arrival * f.vertical_rate[:-100].mean() < -10) for flight in Traffic(fd): flight.plot(ax) fig.suptitle(f"{airport.name}") fig.set_tight_layout(True) logging.info(f"Image saved as {output}") fig.savefig(output.as_posix())
def plot_latent_and_trajs_outliers( t, lat, outliers, savefig, nb_top_outliers=10, airport="LSZH", runway=None, plot_callsigns=True, re_or_score="re", ): outliers = outliers.query("initial_flow != 'N/A'") if outliers is None: return if runway is not None: subset = t.query(f"runway == '{runway}' and initial_flow != 'N/A'") else: subset = t.query("initial_flow != 'N/A'") df = pd.DataFrame.from_records([{ "flight_id": id_, "x": x, "y": y } for (id_, x, y) in zip( list(f.flight_id for f in t), lat[:, 0], lat[:, 1], )]) top_outliers = ( outliers.query("initial_flow != 'N/A'").groupby("flight_id").agg({ re_or_score: np.mean }).sort_values( re_or_score, ascending=(re_or_score == "score")).head(nb_top_outliers)) print("\n\ntop outliers\n", top_outliers) cols = ["flight_id", "simple", "initial_flow", "cluster"] subset = df.merge(subset.data[cols].drop_duplicates()) subset_o = df.merge(outliers.data, on="flight_id") subset_o = top_outliers.merge(subset_o, on="flight_id") with plt.style.context("traffic"): text_style = dict( verticalalignment="top", horizontalalignment="right", fontname="Ubuntu", fontsize=18, bbox=dict(facecolor="white", alpha=0.6, boxstyle="round"), ) colors = [ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf", ] fig = plt.figure(figsize=(30, 15)) ax = fig.add_subplot(121) m = fig.add_subplot(122, projection=EuroPP()) m.add_feature( countries(edgecolor="white", facecolor="#d9dadb", alpha=1, linewidth=2, zorder=-2)) m.outline_patch.set_visible(False) m.background_patch.set_visible(False) airports[airport].point.plot( m, shift=dict(units="dots", x=-15, y=-15), marker=atc_tower, s=300, zorder=5, text_kw={**text_style}, ) subset.plot.scatter( x="x", y="y", ax=ax, color="#aaaaaa", alpha=0.4, ) for (flow, d), color in zip(subset_o.groupby("cluster"), colors): d.plot.scatter(x="x", y="y", ax=ax, color=color, label=flow, alpha=0.4, s=100) for f in Traffic(d): f.plot( m, linewidth=3, label=f"{f.callsign}, {f.stop:%b %d}", color=color, ) if plot_callsigns: point = subset_o.query( f'flight_id == "{f.flight_id}"').iloc[0] ax.text( point.x + 0.5, point.y + 0.5, f"{f.callsign}, {f.stop:%b %d}", **{ **text_style, **dict(horizontalalignment="left", fontsize=15), }, ) # ax.legend(prop=dict(family="Ubuntu", size=18)) ax.grid(linestyle="solid", alpha=0.5, zorder=-2) ax.set_xlabel("1st component on latent space", labelpad=10) ax.set_ylabel("2nd component on latent space", labelpad=10) fig.savefig(savefig)
def plot_latent_and_trajs(t, lat, savefig, plot_clusters=False, airport="LSZH", runway=None): if runway is not None: subset = t.query(f"runway == '{runway}' and initial_flow != 'N/A'") else: subset = t.query("initial_flow != 'N/A'") df = pd.DataFrame.from_records([{ "flight_id": id_, "x": x, "y": y } for (id_, x, y) in zip( list(f.flight_id for f in t), lat[:, 0], lat[:, 1], )]) cols = ["flight_id", "simple", "initial_flow"] if plot_clusters: cols += ["cluster"] stasts = df.merge(subset.data[cols].drop_duplicates()) with plt.style.context("traffic"): text_style = dict( verticalalignment="top", horizontalalignment="right", fontname="Ubuntu", fontsize=18, bbox=dict(facecolor="white", alpha=0.6, boxstyle="round"), ) colors = [ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf", ] fig = plt.figure(figsize=(15, 7.5)) ax = fig.add_subplot(121) m = fig.add_subplot(122, projection=EuroPP()) m.add_feature( countries(edgecolor="white", facecolor="#d9dadb", alpha=1, linewidth=2, zorder=-2)) m.outline_patch.set_visible(False) m.background_patch.set_visible(False) airports[airport].point.plot( m, shift=dict(units="dots", x=-15, y=-15), marker=atc_tower, s=300, zorder=5, text_kw={**text_style}, ) if plot_clusters: gb = "cluster" else: gb = "initial_flow" for (flow, d), color in zip(stasts.groupby(gb), colors): d.plot.scatter(x="x", y="y", ax=ax, color=color, label=flow, alpha=0.4) subset.query(f'{gb} == "{flow}"')[:50].plot(m, color=color, linewidth=1.5, alpha=0.5) ax.legend(prop=dict(family="Ubuntu", size=18)) ax.grid(linestyle="solid", alpha=0.5, zorder=-2) # ax3.xaxis.set_tick_params(pad=20) ax.set_xlabel("1st component on latent space", labelpad=10) ax.set_ylabel("2nd component on latent space", labelpad=10) fig.savefig(savefig)
def clusters_plot2d( sector, t, nb_samples, projection, scaler=None, plot_trajs=False, plot_clust=None, ): with plt.style.context("traffic"): fig, ax = plt.subplots(subplot_kw=dict(projection=projection)) ax.add_feature(countries()) ax.add_feature(rivers()) ax.set_extent( tuple(x - 0.5 + (0 if i % 2 == 0 else 1) for i, x in enumerate(sector.extent))) sector.plot(ax, lw=5) clust_ids = sorted(t.data.cluster.unique()) if plot_clust is None: plot_clust = clust_ids for cid in plot_clust: tc = t.query(f"cluster=={cid}") if plot_trajs: for flight in tc: lat = list(flight.data["latitude"]) lon = list(flight.data["longitude"]) if cid != -1: ax.plot( lon, lat, color=C[cid], transform=PlateCarree(), lw=1, alpha=0.5, ) else: ax.plot( lon, lat, color="grey", transform=PlateCarree(), lw=0.5, alpha=0.5, ) if cid != -1: cent = tc.centroid(nb_samples, projection=projection, transformer=scaler).data lat = list(cent["latitude"]) lon = list(cent["longitude"]) ax.plot(lon, lat, color=C[cid], transform=PlateCarree(), lw=5) ax.arrow( lon[-5], lat[-5], lon[-1] - lon[-5], lat[-1] - lat[-5], color=C[cid], transform=PlateCarree(), lw=3, head_width=0.1, head_length=0.1, )
import matplotlib.pyplot as plt from traffic.drawing import countries, rivers, lakes, ocean, TransverseMercator from traffic.data import eurofirs fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(111, projection=TransverseMercator(10, 45)) ax.set_extent((-20, 45, 30, 70)) ax.add_feature(countries(scale="50m")) ax.add_feature(rivers(scale="50m")) ax.add_feature(lakes(scale="50m")) ax.add_feature(ocean(scale="50m")) for key, fir in eurofirs.items(): fir.plot(ax, edgecolor="#3a3aaa", lw=2, alpha=.5) if key not in ["ENOB", "LPPO", "GCCC"]: fir.annotate( ax, s=key, ha="center", color="#3a3aaa", fontname="Ubuntu", fontsize=13, ) fig.savefig("eurofirs.png", bbox_inches="tight", pad_inches=0, dpi=200)
flight4 = quickstart["HOP87DJ"] #task 2 with plt.style.context("traffic"): fig = plt.figure() ax0 = fig.add_subplot(111, projection=Lambert93()) ax1 = fig.add_subplot(111, projection=Lambert93()) ax2 = fig.add_subplot(111, projection=Lambert93()) ax3 = fig.add_subplot(111, projection=Lambert93()) ax4 = fig.add_subplot(111, projection=Lambert93()) #print(flight1.data['timestamp'].describe()) ax0.add_feature(countries()) # Maximum extent for the map ax0.set_global() # Remove border and set transparency for background ax0.outline_patch.set_visible(False) ax0.background_patch.set_visible(False) flight1.plot(ax1, label='flight 1') flight2.plot(ax2, label='flight 2') flight3.plot(ax3, label='flight 3') flight4.plot(ax4, label='flight 4') plt.legend() #plt.show() with plt.style.context("traffic"): fig, ax = plt.subplots(figsize=(10, 7))