Example #1
0
    def plot_sensitivity_map(self, salib_si='S1', **kwargs):
        """
        Plot a map of the largest sensitivity index in each exposure point

        Requires the uncertainty distribution for eai_exp.

        Parameters
        ----------
        salib_si : str, optional
            The name of the sensitivity index to plot.
            The default is 'S1'.
        kwargs :
            Keyword arguments passed on to
            climada.util.plot.geo_scatter_categorical

        Raises
        ------
        ValueError :
            If no sensitivity data is found, raise error.

        Returns
        -------
        ax: matplotlib.pyplot.axes
            The axis handle of the plot.

        See Also
        --------
        climada.util.plot.geo_scatter_categorical :
            geographical plot for categorical variable

        """

        eai_max_si_df = self.get_largest_si(salib_si, metric_list=['eai_exp'])

        plot_val = eai_max_si_df['param']
        coord = np.array([self.coord_df.latitude,
                          self.coord_df.longitude]).transpose()
        if 'var_name' not in kwargs:
            kwargs['var_name'] = 'Input parameter with largest ' + salib_si
        if 'title' not in kwargs:
            kwargs['title'] = ''
        if 'figsize' not in kwargs:
            kwargs['figsize'] = (8, 6)
        if 'cmap' not in kwargs:
            labels = np.unique(plot_val)
            n = np.where(labels == 'None')[0]
            if len(n) > 0:
                n = n[0]
                cmap = mpl.colors.ListedColormap(
                    plt.get_cmap(MAP_CMAP).colors[:len(labels)])
                colors = list(cmap.colors)
                colors[n] = tuple(np.repeat(0.93, 3))
                cmap.colors = tuple(colors)
                kwargs['cmap'] = cmap
        ax = u_plot.geo_scatter_categorical(plot_val, coord, **kwargs)

        return ax
    def test_geo_scatter_categorical(self):
        """Plots ones with geo_scatteR_categorical"""
        # test default with one plot
        values = np.array([1, 2.0, 1, 'a'])
        coord = np.array([[26, 0], [26, 1], [28, 0], [29, 1]])
        u_plot.geo_scatter_categorical(values,
                                       coord,
                                       'value',
                                       'test plot',
                                       pop_name=True)
        plt.close()

        #test multiple plots with non default kwargs
        values = np.array([[1, 2.0, 1, 'a'], [0, 0, 0, 0]])
        coord = np.array([[26, 0], [26, 1], [28, 0], [29, 1]])
        u_plot.geo_scatter_categorical(values,
                                       coord,
                                       'value',
                                       'test plot',
                                       cat_name={
                                           0: 'zero',
                                           1: 'int',
                                           2.0: 'float',
                                           'a': 'string'
                                       },
                                       pop_name=False,
                                       cmap=plt.get_cmap('Set1'))
        plt.close()

        #test colormap warning
        values = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11],
                           [12, 13, 14, 15]])
        coord = np.array([[26, 0], [26, 4], [28, 0], [29, 1]])
        u_plot.geo_scatter_categorical(values,
                                       coord,
                                       'value',
                                       'test plot',
                                       pop_name=False,
                                       cmap='viridis')

        plt.close()

        #test colormap warning with 256 colors
        values = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11],
                           [12, 13, 14, 15]])
        coord = np.array([[26, 0], [26, 1], [28, 0], [29, 1]])
        u_plot.geo_scatter_categorical(values,
                                       coord,
                                       'value',
                                       'test plot',
                                       pop_name=False,
                                       cmap='tab20c')
        plt.close()
    def plot_sensitivity_map(self, exp=None, salib_si='S1', figsize=(8, 6)):
        """
        Plot a map of the largest sensitivity index in each exposure point

        Parameters
        ----------
        exp : climada.exposure
            The exposure from which to take the coordinates
        salib_si : str, optional
            The name of the sensitivity index to plot.
            The default is 'S1'.
        figsize: tuple(int or float, int or float), optional
            The figsize argument of matplotlib.pyplot.subplots()
            The default is (8, 6)

        Raises
        ------
        ValueError
            If no sensitivity data is found, raise error.

        Returns
        -------
        ax: matplotlib.pyplot.axes
            The axis handle of the plot.

        """

        try:
            si_eai = self.sensitivity['eai_exp']
            eai_max_si_idx = [
                np.argmax(si_dict[salib_si]) for si_dict in si_eai.values()
            ]

        except KeyError as verr:
            raise ValueError(
                "No sensitivity indices found for"
                " impact.eai_exp. Please compute sensitivity first using"
                " UncImpact.calc_sensitivity(calc_eai_exp=True)") from verr

        if exp is None:
            exp_input_vals = self.samples_df.loc[0][
                self.unc_vars['exp'].labels].to_dict()
            exp = self.unc_vars['exp'].uncvar_func(**exp_input_vals)

        plot_val = np.array([eai_max_si_idx]).astype(float)
        coord = np.array([exp.gdf.latitude, exp.gdf.longitude]).transpose()
        ax = u_plot.geo_scatter_categorical(
            plot_val,
            coord,
            var_name='Largest sensitivity index ' + salib_si,
            title='Sensitivity map',
            cat_name=self.param_labels,
            figsize=figsize)

        return ax