def plot_percen(irma_tc, exp, if_exp, axs): """ Plot irma damage in %. """ # south extent = u_plot._get_borders(exp.coord) extent = ([ extent[0] - BUFFER_DEG, extent[1] + BUFFER_DEG, extent[2] - BUFFER_DEG, extent[3] + BUFFER_DEG ]) axs.set_extent((extent)) u_plot.add_shapes(axs) imp_irma = Impact() imp_irma.calc(exp, if_exp, irma_tc) imp_irma.eai_exp[exp.value > 0] = \ imp_irma.eai_exp[exp.value > 0]/exp.value[exp.value > 0]*100 imp_irma.eai_exp[exp.value == 0] = 0. sel_exp = imp_irma.eai_exp > 0 im = axs.hexbin(exp.coord[sel_exp, 1], exp.coord[sel_exp, 0], C=imp_irma.eai_exp[sel_exp], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, cmap='YlOrRd', vmin=0, vmax=50) axs.set_title('') axs.grid(False) scale_bar(axs, (0.90, 0.90), 10) return im
def plot_left(exp, data_irma, tc_irma, ax, scale_pos, cntour_loc, label_loc): """ Plot exposed value, irma track and irma wind field. """ extent = u_plot._get_borders(exp.coord) extent = ([extent[0] - BUFFER_DEG, extent[1] + BUFFER_DEG, extent[2] -\ BUFFER_DEG, extent[3] + BUFFER_DEG]) ax.set_extent((extent)) u_plot.add_shapes(ax) sel_pos = np.argwhere(exp.value > 0)[:, 0] ax.hexbin(exp.coord[sel_pos, 1], exp.coord[sel_pos, 0], C=exp.value[sel_pos], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, norm=LogNorm(vmin=MIN_VAL, vmax=MAX_VAL), cmap='YlOrRd', vmin=1.0e2, vmax=MAX_VAL) ax.set_title('') ax.grid(False) scale_bar(ax, scale_pos, 10) track = data_irma.data[0] ax.plot(track.lon.values, track.lat.values, linestyle='solid', transform=ccrs.PlateCarree(), lw=2, color='k') leg_lines = [ Line2D([0], [0], color='k', lw=2), Line2D([0], [0], color='grey', lw=1, ls=':') ] leg_names = ['Irma track', 'wind field (kn)'] if 'bbox' in label_loc: ax.legend(leg_lines, leg_names, bbox_to_anchor=label_loc['bbox'], loc=label_loc['loc']) else: ax.legend(leg_lines, leg_names, loc=label_loc['loc']) tc_irma.intensity *= MS2KN grid_x, grid_y = np.mgrid[tc_irma.centroids.coord[:, 1].min() : \ tc_irma.centroids.coord[:, 1].max() : complex(0, 2000), \ tc_irma.centroids.coord[:, 0].min() : \ tc_irma.centroids.coord[:, 0].max() : complex(0, 2000)] grid_im = griddata( (tc_irma.centroids.coord[:, 1], tc_irma.centroids.coord[:, 0]), np.array(tc_irma.intensity[0].todense()).squeeze(), (grid_x, grid_y)) cs = ax.contour(grid_x, grid_y, grid_im, linewidths=1.0, linestyles=':', \ levels=[60, 80, 100, 120], colors=['grey', 'grey', 'grey', 'grey', 'grey']) ax.clabel(cs, inline=1, fontsize=10, manual=cntour_loc, rotation=-20, fmt='%1.0f') tc_irma.intensity /= MS2KN
def plot_right(irma_tc, exp, ax, scale_pos, plot_line=False): """ Plot irma damage in USD. """ if_exp = ImpactFuncSet() if_em = IFTropCyclone() if_em.set_emanuel_usa() if_exp.add_func(if_em) imp_irma = Impact() imp_irma.calc(exp, if_exp, irma_tc) extent = u_plot._get_borders(exp.coord) extent = ([ extent[0] - BUFFER_DEG, extent[1] + BUFFER_DEG, extent[2] - BUFFER_DEG, extent[3] + BUFFER_DEG ]) ax.set_extent((extent)) u_plot.add_shapes(ax) sel_pos = np.argwhere(imp_irma.eai_exp > 0)[:, 0] hex_bin = ax.hexbin(imp_irma.coord_exp[sel_pos, 1], imp_irma.coord_exp[sel_pos, 0], C=imp_irma.eai_exp[sel_pos], reduce_C_function=np.average, transform=ccrs.PlateCarree(), gridsize=2000, norm=LogNorm(vmin=MIN_VAL, vmax=MAX_VAL), cmap='YlOrRd', vmin=MIN_VAL, vmax=MAX_VAL) ax.set_title('') ax.grid(False) add_cntry_names(ax, extent) scale_bar(ax, scale_pos, 10) if plot_line: x1, y1 = [-64.57, -64.82], [18.28, 18.47] ax.plot(x1, y1, linewidth=1.0, color='grey', linestyle='--') return hex_bin
def _plot_warn( self, run_datetime, thresholds, decision_level, decision_dict, polygon_file, polygon_file_crs, title, proj=ccrs.PlateCarree(), figsize=(9, 13), adapt_fontsize=True, ): """plotting the warning level of each warning region based on thresholds""" # select hazard with run_datetime # pylint: disable=protected-access if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] kwargs = dict() kwargs["cmap"] = CMAP_WARNPROB kwargs["s"] = 5 kwargs["marker"] = "," kwargs["norm"] = BoundaryNorm(np.linspace(0, 1, 11), CMAP_WARNPROB.N, clip=True) # Generate each subplot fig, axis, _fontsize = u_plot.make_map(1, proj=proj, figsize=figsize, adapt_fontsize=adapt_fontsize) if isinstance(axis, np.ndarray): axis = axis[0] tit = title fig.set_size_inches(9, 8) # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs(polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) # checking the decision dict and define the corresponding functions if not (isinstance(decision_dict["probability_aggregation"], float) & isinstance(decision_dict["area_aggregation"], float)): ValueError(" If decision_level is 'exposure_point'," + "parameters probability_aggregation and " + "area_aggregation of " + "Forecast.plot_warn_map() must both be " + "floats between [0..1]. Which each " + "specify quantiles.") decision_dict_functions = decision_dict.copy() for aggregation in decision_dict: if isinstance(decision_dict[aggregation], float): decision_dict_functions[aggregation] = np.percentile elif decision_dict[aggregation] == "sum": decision_dict_functions[aggregation] = np.sum elif decision_dict[aggregation] == "mean": decision_dict_functions[aggregation] = np.mean else: raise ValueError("Parameter area_aggregation of " + "Forecast.plot_warn_map() must eiter be " + "a float between [0..1], which " + "specifys a quantile. or 'sum' or 'mean'.") for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) in_geom = u_coord.coord_on_land( lat=self._impact[haz_ind].coord_exp[:, 0], lon=self._impact[haz_ind].coord_exp[:, 1], land_geom=geom2, ) if not in_geom.any(): continue # decide warning level warn_level = 0 for ind_i, warn_thres_i in enumerate(thresholds): if decision_level == "exposure_point": # decision at each grid_point probabilities = np.squeeze( np.asarray((self._impact[haz_ind].imp_mat >= warn_thres_i).sum(axis=0) / self._impact[haz_ind].event_id.size)) # quantiles over probability area = (probabilities[in_geom] >= decision_dict["probability_aggregation"]).sum() # quantiles over area if area >= (in_geom.sum() * decision_dict["area_aggregation"]): warn_level = ind_i + 1 elif decision_level == "polygon": # aggregation over area if isinstance(decision_dict["area_aggregation"], float): value_per_member = decision_dict_functions[ "area_aggregation"]( self._impact[haz_ind].imp_mat[:, in_geom].todense( ), decision_dict["area_aggregation"], axis=1, ) else: value_per_member = decision_dict_functions[ "area_aggregation"](self._impact[haz_ind]. imp_mat[:, in_geom].todense(), axis=1) # aggregation over members/probability if isinstance(decision_dict["probability_aggregation"], float): value_per_region = decision_dict_functions[ "probability_aggregation"]( value_per_member, decision_dict["probability_aggregation"]) else: value_per_region = decision_dict_functions[ "probability_aggregation"](value_per_member) # warn level decision if value_per_region >= warn_thres_i: warn_level = ind_i + 1 else: raise ValueError( "Parameter decision_level of " + "Forecast.plot_warn_map() must eiter be " + "'exposure_point' or 'polygon'.") # plot warn_region with specific color (dependent on warning level) axis.add_geometries( [geom2], crs=ccrs.PlateCarree(), facecolor=COLORS_WARN[warn_level, :], edgecolor="gray", ) # Create legend in this axis hazard_levels = [ "1: Minimal or no hazard", "2: Moderate hazard", "3: Significant hazard", "4: Severe hazard", "5: Very severe hazard", ] legend_elements = [ Patch(facecolor=COLORS_WARN[n, :], edgecolor="gray", label=hazard_level) for n, hazard_level in enumerate(hazard_levels) ] axis.legend( handles=legend_elements, loc="upper center", framealpha=0.5, bbox_to_anchor=(0.5, -0.02), ncol=3, ) title_position = { "model_text": [0.02, 0.91], "explain_text": [0.02, 0.87], "event_day": [0.98, 0.91], "run_start": [0.98, 0.87], } left_right = { "model_text": "left", "explain_text": "left", "event_day": "right", "run_start": "right", } color = { "model_text": "k", "explain_text": "k", "event_day": "r", "run_start": "k", } for t_i in tit: plt.figtext( title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize="xx-large", color=color[t_i], ha=left_right[t_i], ) extent = u_plot._get_borders(self._impact[haz_ind].coord_exp) axis.set_extent((extent), ccrs.PlateCarree()) fig.tight_layout() return fig, axis
def _plot_exc_prob( self, run_datetime, threshold, title, cbar_label, proj=ccrs.PlateCarree(), polygon_file=None, polygon_file_crs="epsg:4326", mask=None, figsize=(9, 13), adapt_fontsize=True, ): """plot the probability of reaching a threshold""" # select hazard with run_datetime # pylint: disable=protected-access if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] extend = "neither" value = np.squeeze( np.asarray( (self._impact[haz_ind].imp_mat > threshold).sum(axis=0) / self._impact[haz_ind].event_id.size)) if mask is not None: value[np.invert(mask)] = np.nan coord = self._impact[haz_ind].coord_exp # Generate array of values used in each subplot array_sub = value shapes = True if not polygon_file: shapes = False var_name = cbar_label geo_coord = coord num_im, list_arr = u_plot._get_collection_arrays(array_sub) list_tit = to_list(num_im, title, "title") list_name = to_list(num_im, var_name, "var_name") list_coord = to_list(num_im, geo_coord, "geo_coord") kwargs = dict() kwargs["cmap"] = CMAP_WARNPROB kwargs["s"] = 5 kwargs["marker"] = "," kwargs["norm"] = BoundaryNorm(np.linspace(0, 1, 11), CMAP_WARNPROB.N, clip=True) # Generate each subplot fig, axis_sub, _fontsize = u_plot.make_map( num_im, proj=proj, figsize=figsize, adapt_fontsize=adapt_fontsize) if not isinstance(axis_sub, np.ndarray): axis_sub = np.array([[axis_sub]]) fig.set_size_inches(9, 8) for array_im, axis, tit, name, coord in zip(list_arr, axis_sub.flatten(), list_tit, list_name, list_coord): if coord.shape[0] != array_im.size: raise ValueError("Size mismatch in input array: %s != %s." % (coord.shape[0], array_im.size)) hex_bin = axis.scatter(coord[:, 1], coord[:, 0], c=array_im, transform=ccrs.PlateCarree(), **kwargs) if shapes: # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs( polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) axis.add_geometries( [geom2], crs=ccrs.PlateCarree(), facecolor="none", edgecolor="gray", ) # Create colorbar in this axis cbax = make_axes_locatable(axis).append_axes("bottom", size="6.5%", pad=0.3, axes_class=plt.Axes) cbar = plt.colorbar(hex_bin, cax=cbax, orientation="horizontal", extend=extend) cbar.set_label(name) title_position = { "model_text": [0.02, 0.94], "explain_text": [0.02, 0.9], "event_day": [0.98, 0.94], "run_start": [0.98, 0.9], } left_right = { "model_text": "left", "explain_text": "left", "event_day": "right", "run_start": "right", } color = { "model_text": "k", "explain_text": "k", "event_day": "r", "run_start": "k", } for t_i in tit: plt.figtext( title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize="xx-large", color=color[t_i], ha=left_right[t_i], ) extent = u_plot._get_borders(coord) axis.set_extent((extent), ccrs.PlateCarree()) fig.tight_layout() return fig, axis_sub
def _plot_imp_map( self, run_datetime, title, cbar_label, polygon_file=None, polygon_file_crs="epsg:4326", proj=ccrs.PlateCarree(), figsize=(9, 13), adapt_fontsize=True, ): # select hazard with run_datetime # pylint: disable=protected-access if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] # tryout new plot with right projection extend = "neither" value = self._impact[haz_ind].eai_exp # value[np.invert(mask)] = np.nan coord = self._impact[haz_ind].coord_exp # Generate array of values used in each subplot array_sub = value shapes = True if not polygon_file: shapes = False var_name = cbar_label geo_coord = coord num_im, list_arr = u_plot._get_collection_arrays(array_sub) list_tit = to_list(num_im, title, "title") list_name = to_list(num_im, var_name, "var_name") list_coord = to_list(num_im, geo_coord, "geo_coord") kwargs = dict() kwargs["cmap"] = CMAP_IMPACT kwargs["s"] = 5 kwargs["marker"] = "," kwargs["norm"] = BoundaryNorm( np.append( np.append([0], [10**x for x in np.arange(0, 2.9, 2.9 / 9)]), [10**x for x in np.arange(3, 7, 4 / 90)], ), CMAP_IMPACT.N, clip=True, ) # Generate each subplot fig, axis_sub, _fontsize = u_plot.make_map( num_im, proj=proj, figsize=figsize, adapt_fontsize=adapt_fontsize) if not isinstance(axis_sub, np.ndarray): axis_sub = np.array([[axis_sub]]) fig.set_size_inches(9, 8) for array_im, axis, tit, name, coord in zip(list_arr, axis_sub.flatten(), list_tit, list_name, list_coord): if coord.shape[0] != array_im.size: raise ValueError("Size mismatch in input array: %s != %s." % (coord.shape[0], array_im.size)) # Binned image with coastlines extent = u_plot._get_borders(coord) axis.set_extent((extent), ccrs.PlateCarree()) hex_bin = axis.scatter(coord[:, 1], coord[:, 0], c=array_im, transform=ccrs.PlateCarree(), **kwargs) if shapes: # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs( polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) axis.add_geometries( [geom2], crs=ccrs.PlateCarree(), facecolor="none", edgecolor="gray", ) else: # add country boundaries u_plot.add_shapes(axis) # Create colorbar in this axis cbax = make_axes_locatable(axis).append_axes("bottom", size="6.5%", pad=0.3, axes_class=plt.Axes) cbar = plt.colorbar(hex_bin, cax=cbax, orientation="horizontal", extend=extend) cbar.set_label(name) cbar.formatter.set_scientific(False) cbar.set_ticks([0, 1000, 10000, 100000, 1000000]) cbar.set_ticklabels( ["0", "1 000", "10 000", "100 000", "1 000 000"]) title_position = { "model_text": [0.02, 0.85], "explain_text": [0.02, 0.81], "event_day": [0.98, 0.85], "run_start": [0.98, 0.81], } left_right = { "model_text": "left", "explain_text": "left", "event_day": "right", "run_start": "right", } color = { "model_text": "k", "explain_text": "k", "event_day": "r", "run_start": "k", } for t_i in tit: plt.figtext( title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize="xx-large", color=color[t_i], ha=left_right[t_i], ) fig.tight_layout() fig.subplots_adjust(top=0.8) return fig, axis_sub
def _plot_exc_prob(self, run_datetime, threshold, title, cbar_label, proj=ccrs.PlateCarree(), polygon_file=None, polygon_file_crs='epsg:4326', mask=None, figsize=(9, 13)): """ plot the probability of reaching a threshold """ # select hazard with run_datetime if run_datetime is None: run_datetime = self.run_datetime[0] haz_ind = np.argwhere(np.isin(self.run_datetime, run_datetime))[0][0] extend = 'neither' value = np.squeeze( np.asarray( (self._impact[haz_ind].imp_mat > threshold).sum(axis=0) / self._impact[haz_ind].event_id.size)) if mask is not None: value[np.invert(mask)] = np.nan coord = self._impact[haz_ind].coord_exp # Generate array of values used in each subplot array_sub = value shapes = True if not polygon_file: shapes = False var_name = cbar_label geo_coord = coord num_im, list_arr = u_plot._get_collection_arrays(array_sub) list_tit = to_list(num_im, title, 'title') list_name = to_list(num_im, var_name, 'var_name') list_coord = to_list(num_im, geo_coord, 'geo_coord') kwargs = dict() kwargs['cmap'] = CMAP_WARNPROB kwargs['s'] = 5 kwargs['marker'] = ',' kwargs['norm'] = BoundaryNorm(np.linspace(0, 1, 11), CMAP_WARNPROB.N, clip=True) # Generate each subplot fig, axis_sub = u_plot.make_map(num_im, proj=proj, figsize=figsize) if not isinstance(axis_sub, np.ndarray): axis_sub = np.array([[axis_sub]]) fig.set_size_inches(9, 8) for array_im, axis, tit, name, coord in zip(list_arr, axis_sub.flatten(), list_tit, list_name, list_coord): if coord.shape[0] != array_im.size: raise ValueError("Size mismatch in input array: %s != %s." % \ (coord.shape[0], array_im.size)) hex_bin = axis.scatter(coord[:, 1], coord[:, 0], c=array_im, \ transform=ccrs.PlateCarree(), **kwargs) if shapes: # add warning regions shp = shapereader.Reader(polygon_file) transformer = pyproj.Transformer.from_crs( polygon_file_crs, self._impact[haz_ind].crs, always_xy=True) for geometry, _ in zip(shp.geometries(), shp.records()): geom2 = shapely.ops.transform(transformer.transform, geometry) axis.add_geometries([geom2], crs=ccrs.PlateCarree(), facecolor='', \ edgecolor='gray') # Create colorbar in this axis cbax = make_axes_locatable(axis).append_axes('bottom', size="6.5%", \ pad=0.3, axes_class=plt.Axes) cbar = plt.colorbar(hex_bin, cax=cbax, orientation='horizontal', extend=extend) cbar.set_label(name) title_position = { 'model_text': [0.02, 0.94], 'explain_text': [0.02, 0.9], 'event_day': [0.98, 0.94], 'run_start': [0.98, 0.9] } left_right = { 'model_text': 'left', 'explain_text': 'left', 'event_day': 'right', 'run_start': 'right' } color = { 'model_text': 'k', 'explain_text': 'k', 'event_day': 'r', 'run_start': 'k' } for t_i in tit: plt.figtext(title_position[t_i][0], title_position[t_i][1], tit[t_i], fontsize='xx-large', color=color[t_i], ha=left_right[t_i]) extent = u_plot._get_borders(coord) axis.set_extent((extent), ccrs.PlateCarree()) return fig, axis_sub