예제 #1
0
def lineplot_scenarios(incubes, outpath, region):
    """
    Line plot showing how the metric evolves over the years for all models and all scenarios combined
   :param incubes: wildcard path to all tseries multi-model cubes
   :param outpath: the path where the plot is saved
   :param region: the region dictionary as defined in constants
   :return: plot
   """
    ano_list = glob.glob(incubes + '_tseries.nc')
    ano_list = atlas_utils.order(ano_list)[::-1]

    f = plt.figure(figsize=(8, 5), dpi=300)
    ax = f.add_subplot(111)

    colors = ['gray', 'gold', 'green', 'mediumblue'][::-1]
    tag = cnst.SCENARIO[::-1]
    scenarios = []

    for ano, co, ta in zip(ano_list, colors, tag):

        fdict = atlas_utils.split_filename_path(ano)
        scen = fdict['scenario']
        metric = fdict['metric']
        variable = fdict['variable']
        season = fdict['season']
        bc = fdict['bc_res']
        scenarios.append(scen)

        cube = iris.load_cube(ano)
        time = cube.coord('year').points
        cube = cube.data

        ax.plot(time[0], 0, color=co, label=ta)
        for nb in range(cube.shape[0]):
            ax.plot(time, cube[nb, :], color=co, alpha=0.5, lw=0.75)

    bottom, top = ax.get_ylim()
    plt.vlines(2005, bottom, top, linestyle='--', linewidth=1.5, zorder=10)
    plt.ylabel(lblr.getYlab(metric, variable, anom=""))
    plt.title(lblr.getTitle(metric,
                            variable,
                            season,
                            scenarios,
                            bc,
                            region[1],
                            anom=''),
              fontsize=10)
    plt.legend()
    plt.savefig(outpath + os.sep + fdict['metric'] + '_' + fdict['variable'] +
                '_' + fdict['bc_res'] + '_' + fdict['season'] + '_' +
                region[0] + '_lineplot_allscen_' + '.png')
    plt.close(f)
예제 #2
0
def nbModels_histogram_scenarios(incubes, outpath, region, anomaly=False):
    """
       Histogram plot showing the number of models within different ranges of the metric (anomaly) value for ALL scenarios
      :param incubes: wildcard path to all tseries multi-model cubes
      :param outpath: the path where the plot is saved
      :param region: the region dictionary as defined in constants
      :param anomaly: boolean, switch for anomaly calculation
      :return: plot
      """

    fname = incubes + '_tseries.nc'
    fdict = atlas_utils.split_filename_path(fname)

    if fdict['aggregation'] not in cnst.METRIC_AGGS[fdict['metric']]:
        return

    ano_list = glob.glob(fname)
    ano_list = atlas_utils.order(ano_list)

    ldata = []
    scen = []
    perc = []

    for ano in ano_list:

        toplot = None

        fdict = atlas_utils.split_filename_path(ano)
        scenario = fdict['scenario']
        metric = fdict['metric']
        variable = fdict['variable']
        season = fdict['season']
        bc = fdict['bc_res']

        if (anomaly == True) & (fdict['scenario'] == 'historical'):
            continue

        vname = cnst.VARNAMES[fdict['variable']]
        cube = iris.load_cube(ano)
        cube = atlas_utils.time_slicer(cube, fdict['scenario'])

        cube = cube.collapsed('year', iris.analysis.MEDIAN)

        if anomaly:
            ano_hist = ano.replace(fdict['scenario'], 'historical')
            hist = iris.load_cube(ano_hist)
            hist = atlas_utils.time_slicer(hist, 'historical')
            hist = hist.collapsed('year', iris.analysis.MEDIAN)

            data = atlas_utils.anomalies(hist, cube, percentage=False)
            data_perc = atlas_utils.anomalies(hist, cube, percentage=True)

            data = data.data
            data_perc = data_perc.data

            hhisto, bi = np.histogram(data,
                                      bins=np.linspace(data.min(), data.max(),
                                                       10))
            try:
                hhistop, bip = np.histogram(data_perc,
                                            bins=np.linspace(
                                                data_perc.min(),
                                                data_perc.max(), 10))
            except:
                continue

            an = 'anomaly'
            ylabel = lblr.getYlab(metric, variable, anom="anomaly")

            an_p = 'percentageAnomaly'
            ylabel_p = lblr.getYlab(metric, variable, anom="percentageAnomaly")

            ldata.append((hhisto, bi))
            perc.append((hhistop, bip))

        else:
            cube = cube.data
            hhisto, bi = np.histogram(cube,
                                      bins=np.linspace(cube.min(), cube.max(),
                                                       10))
            ldata.append((hhisto, bi))
            ylabel = lblr.getYlab(metric, variable, anom="")
            an = 'scenarios'

        scen.append(fdict['scenario'])

        plot_dic1 = {
            'data': ldata,
            'ftag': an,
            'ylabel': ylabel,
        }

        toplot = [plot_dic1]

        if anomaly and not 'tas' in variable:
            plot_dic2 = {
                'data': perc,
                'ftag': an_p,
                'ylabel': ylabel_p,
            }

            toplot = [plot_dic1, plot_dic2]

    if toplot:
        # This will only fail if both the historical and future are zero
        for p in toplot:

            if len(p['data']) < 4:
                xp = len(p['data'])
                yp = 1
                xx = 8
                yy = 6
            else:
                xp = 2
                yp = 2
                xx = 9
                yy = 5

            f = plt.figure(figsize=(xx, yy))

            for id in range(len(p['data'])):
                ax = f.add_subplot(xp, yp, id + 1)

                bin = p['data'][id][1]
                ax.bar(bin[0:-1] + ((bin[1::] - bin[0:-1]) / 2),
                       p['data'][id][0],
                       edgecolor='black',
                       width=(bin[1::] - bin[0:-1]),
                       align='edge',
                       color='darkseagreen')

                ax.set_xlabel(p['ylabel'])
                if cnst.LANGUAGE == 'ENGLISH':
                    ax.set_ylabel('Number of models')
                else:
                    ax.set_ylabel(u'Nombre de modèles')

                ax.set_title(lblr.getTitle(metric,
                                           variable,
                                           season,
                                           scenario,
                                           bc,
                                           region[1],
                                           anom=p['ftag']),
                             fontsize=10)

            plt.tight_layout()

            plt.savefig(outpath + os.sep + fdict['metric'] + '_' +
                        fdict['variable'] + '_' + fdict['bc_res'] + '_' +
                        fdict['season'] + '_' + region[0] +
                        '_MultiNbModelHistogram_' + p['ftag'] + '.png')

            plt.close(f)
예제 #3
0
def barplot_scenarios(incubes, outpath, region, anomaly=False):
    """
       Barplot showing the average of the (anomaly) metric over the climatological period for all
       individual models and scenarios.
       :param incubes: wildcard path to all tseries multi-model cubes
       :param outpath: the path where the plot is saved
       :param region: the region dictionary as defined in constants
       :param anomaly: boolean, switch for anomaly calculation
       :return: plot
       """

    fname = incubes + '_tseries.nc'
    fdict = atlas_utils.split_filename_path(fname)

    if fdict['aggregation'] not in cnst.METRIC_AGGS[fdict['metric']]:
        return

    # This creates a list of '*allModels_tseries.nc' files, one element for each scenario
    ano_list = glob.glob(fname)
    ano_list = atlas_utils.order(ano_list)

    ldata = []
    scen = []
    perc = []
    lmodels = []
    for ano in ano_list:

        fdict = atlas_utils.split_filename_path(ano)
        scenario = fdict['scenario']
        metric = fdict['metric']
        variable = fdict['variable']
        season = fdict['season']
        bc = fdict['bc_res']

        if (anomaly == True) & (fdict['scenario'] == 'historical'):
            continue

        cube = iris.load_cube(ano)
        cube = atlas_utils.time_slicer(cube, fdict['scenario'])
        cube = cube.collapsed('year', iris.analysis.MEDIAN)
        lmodels.append(np.ndarray.tolist(cube.coord('model_name').points))

        if anomaly:
            ano_hist = ano.replace(fdict['scenario'], 'historical')
            hist = iris.load_cube(ano_hist)
            hist = atlas_utils.time_slicer(hist, 'historical')
            hist = hist.collapsed('year', iris.analysis.MEDIAN)

            data = atlas_utils.anomalies(hist, cube, percentage=False)
            data_perc = atlas_utils.anomalies(hist, cube, percentage=True)

            an = 'anomaly'
            ylabel = lblr.getYlab(metric, variable, anom="anomaly")

            an_p = 'percentageAnomaly'
            ylabel_p = lblr.getYlab(metric, variable, anom="percentageAnomaly")
            dat_perc = np.ndarray.tolist(data_perc.data)
            perc.append(dat_perc)

        else:
            data = cube
            an = 'scenarios'
            ylabel = lblr.getYlab(metric, variable, anom="")

        dat = data.data
        dat = np.ndarray.tolist(dat)
        ldata.append(dat)

        scen.append(scenario)

    plot_dic1 = {
        'data': ldata,
        'xlabel': scen,
        'ftag': an,
        'ylabel': ylabel,
        'models': lmodels
    }

    toplot = [plot_dic1]

    if anomaly and not 'tas' in variable:
        plot_dic2 = {
            'data': perc,
            'xlabel': scen,
            'ftag': an_p,
            'ylabel': ylabel_p,
            'models': lmodels
        }

        toplot = [plot_dic1, plot_dic2]

    for p in toplot:

        if len(p['data']) < 4:
            xp = len(p['data'])
            yp = 1
            xx = 8
            yy = 7
        else:
            xp = 2
            yp = 2
            xx = 13
            yy = 8

        f = plt.figure(figsize=(xx, yy))

        for id in range(len(p['data'])):
            ax = f.add_subplot(xp, yp, id + 1)

            b = plt.bar(range(len(p['models'][id])),
                        p['data'][id],
                        align='edge',
                        label=p['models'][id],
                        color='darkseagreen')

            # plt.subplots_adjust(bottom=0.8)
            xticks_pos = [
                0.65 * patch.get_width() + patch.get_xy()[0] for patch in b
            ]

            plt.xticks(xticks_pos, p['models'][id], ha='right', rotation=45)

            plt.ylabel(p['ylabel'])
            plt.title(p['xlabel'][id])

        plt.tight_layout(h_pad=0.2, rect=(0, 0, 1, 0.92))
        plt.suptitle(lblr.getTitle(metric,
                                   variable,
                                   season,
                                   scen,
                                   bc,
                                   region[1],
                                   anom=p['ftag']),
                     fontsize=10)

        plt.savefig(outpath + os.sep + fdict['metric'] + '_' +
                    fdict['variable'] + '_' + fdict['bc_res'] + '_' +
                    fdict['season'] + '_' + region[0] + '_allModelHisto_' +
                    p['ftag'] + '.png')

        plt.close(f)
예제 #4
0
def boxplot_scenarios(incubes, outpath, region, anomaly=False):
    """
       Produces a boxplot with a box for each scenario, indicating the model spread.
       :param incubes: wildcard path to all tseries multi-model cubes
       :param outpath: the path where the plot is saved
       :param region: the region dictionary as defined in constants
       :param anomaly: boolean, switch for anomaly calculation
       :return: plot
       """

    fname = incubes + '_tseries.nc'
    fdict = atlas_utils.split_filename_path(fname)

    if fdict['aggregation'] not in cnst.METRIC_AGGS[fdict['metric']]:
        return

    ano_list = glob.glob(fname)
    ano_list = atlas_utils.order(ano_list)

    ldata = []
    scen = []
    perc = []

    for ano in ano_list:
        print ano
        fdict = atlas_utils.split_filename_path(ano)
        metric = fdict['metric']
        variable = fdict['variable']
        season = fdict['season']
        scenario = fdict['scenario']
        bc = fdict['bc_res']

        if (anomaly == True) & (fdict['scenario'] == 'historical'):
            continue

        cube = iris.load_cube(ano)
        cube = atlas_utils.time_slicer(cube, fdict['scenario'])
        cube = cube.collapsed('year', iris.analysis.MEDIAN)

        if anomaly:
            ano_hist = ano.replace(fdict['scenario'], 'historical')
            hist = iris.load_cube(ano_hist)
            hist = atlas_utils.time_slicer(hist, 'historical')
            hist = hist.collapsed('year', iris.analysis.MEDIAN)

            data = atlas_utils.anomalies(hist, cube, percentage=False)

            data_perc = atlas_utils.anomalies(hist, cube, percentage=True)

            an = 'anomaly'
            ylabel = lblr.getYlab(metric, variable, anom='absolute')

            an_p = 'percentageAnomaly'
            ylabel_p = lblr.getYlab(metric, variable, anom='percentage')
            dat_perc = np.ndarray.tolist(data_perc.data)
            perc.append(dat_perc)

        else:
            data = cube
            an = 'scenarios'
            ylabel = lblr.getYlab(metric, variable, anom=None)

        dat = data.data
        dat = np.ndarray.tolist(dat)
        ldata.append(dat)

        scen.append(fdict['scenario'])

    plot_dic1 = {'data': ldata, 'xlabel': scen, 'ftag': an, 'ylabel': ylabel}

    toplot = [plot_dic1]

    if anomaly and not 'tas' in variable:
        plot_dic2 = {
            'data': perc,
            'xlabel': scen,
            'ftag': an_p,
            'ylabel': ylabel_p
        }

        toplot = [plot_dic1, plot_dic2]

    for p in toplot:

        f = plt.figure(figsize=(8, 7))

        try:
            bp = plt.boxplot(p['data'],
                             labels=p['xlabel'],
                             sym='',
                             patch_artist=True,
                             notch=False,
                             zorder=9,
                             whis=[10, 90])
        except ValueError:
            print('Boxplot data has a problem, please check. Cannot continue')
            pdb.set_trace()

        plt.title(lblr.getTitle(metric,
                                variable,
                                season,
                                scenario,
                                bc,
                                region[1],
                                anom=p['ftag']),
                  fontsize=10)

        if cnst.LANGUAGE == 'ENGLISH':
            plt.xlabel('Scenario')
            plt.ylabel(p['ylabel'])
        else:
            plt.xlabel(u'Scénario')
            plt.ylabel(p['ylabel'])

        for median, box, lab in zip(bp['medians'], bp['boxes'], p['xlabel']):
            box.set(facecolor='none')
            median.set(linewidth=0)  #, color='steelblue')

        for id, d in enumerate(p['data']):
            try:
                plt.scatter([id + 1] * len(d),
                            d,
                            marker='_',
                            color='firebrick',
                            s=60,
                            zorder=9)
            except:
                pdb.set_trace()

        if np.nanmax(d) - np.nanmin(d) > np.nanmax(d):
            plt.hlines(0, 0, len(d), linestyle='dashed', color='grey')

        plt.savefig(outpath + os.sep + fdict['metric'] + '_' +
                    fdict['variable'] + '_' + fdict['bc_res'] + '_' +
                    fdict['season'] + '_' + region[0] + '_allModelBoxplot_' +
                    p['ftag'] + '.png')

        plt.close(f)