Exemple #1
0
    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
Exemple #2
0
    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
Exemple #3
0
    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