Пример #1
0
def plot_diagnostic(fileout, plot_dir, project_info, model):

    """
    ;; Arguments
    ;;    fileout: dir
    ;;          directory to save the plot
    ;;
    ;; Description
    ;;    Plot diagnostic and save .png plot
    ;;
    """
    import projects
    E = ESMValProject(project_info)
    verbosity = E.get_verbosity()

    #-------------------------
    # Read model info
    #-------------------------
    
    currProject = getattr(vars()['projects'], model.split_entries()[0])()

    start_year = currProject.get_model_start_year(model)
    end_year = currProject.get_model_end_year(model)
    model_info = model.split_entries()


    # Read code output in netCDF format
    diag_name = 'sm-pr-diag-plot'
    netcdf_file = E.get_plot_output_filename(diag_name=diag_name,
                                             variable='pr-mrsos',
                                             model=model_info[1],
                                             specifier='Taylor2012-diagnostic')
    suffix = E.get_graphic_format() + "$"
    netcdf_file = re.sub(suffix, "nc", netcdf_file)
    ncf = nc4.Dataset(os.path.join(fileout, netcdf_file), 'r')
    p_val =  ncf.variables['T12_diag'][:,:]
    ncf.close()

    mp_val = np.ma.masked_equal(p_val, -999)

    # Gridding info: Global diagnostic 5x5 deg
    LON = np.arange(-180, 185, 5)
    LAT = np.arange(-60, 65, 5)

    # Define figure

    F, ax = plt.subplots(nrows=1, ncols=1, **dict(figsize=[15, 8]))

    # Cmap
    cmap = cm.get_cmap(name='bwr_r', lut=7)
    cmaplist = [cmap(i) for i in range(cmap.N)]
    cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)
    bounds = [0., 1, 5, 10, 90, 95, 99, 100]
    norm = col.BoundaryNorm(bounds, cmap.N)
    cmap.set_bad('GainsBoro')

    # Basemap
    map_ax = Basemap(ax=ax, projection='cyl', resolution='l',
                     llcrnrlat=-60, urcrnrlat=60,
                     llcrnrlon=-180, urcrnrlon=180,
                     fix_aspect=False)
    map_ax.drawcoastlines(color='k', linewidth=.7)

    # Plot p_val on basemap
    I = map_ax.pcolormesh(LON, LAT, mp_val, cmap=cmap, norm=norm)

    # Colorbar
    cax = F.add_axes([0.94, 0.15, 0.02, 0.7])
    cbar = plt.colorbar(I, cax=cax, cmap=cmap)

    plt.suptitle('Preference for afternoon precipitation over soil moisture anomalies, ' + model_info[1] + " (" + start_year + "-" + end_year + ")",
                  fontsize = 14)

    diag_name = 'sm-pr-diag-plot'
    figure_filename = E.get_plot_output_filename(diag_name=diag_name,
                                                 variable='pr-mrsos',
                                                 model=model_info[1])

    # Save figure to fileout
    plt.savefig(os.path.join(plot_dir, figure_filename))
Пример #2
0
def main(project_info):

    # print(">>>>>>>> entering ww09_ESMValTool.py <<<<<<<<<<<<")

    # create instance of a wrapper that allows easy access to data
    E = ESMValProject(project_info)

    config_file = E.get_configfile()
    plot_dir = E.get_plot_dir()
    verbosity = E.get_verbosity()
    plot_type = E.get_graphic_format()
    diag_script = E.get_diag_script_name()

    res = E.write_references(diag_script,              # diag script name
                             ["A_will_ke"],            # authors
                             [""],                     # contributors
                             ["D_Williams09climdyn"],  # diag_references
                             ["E_isccp_d1"],           # obs_references
                             ["P_cmug"],               # proj_references
                             project_info,
                             verbosity,
                             False)

    modelconfig = ConfigParser.ConfigParser()
    modelconfig.read(config_file)

    # create list of model names (plot labels)
    models = []
    for model in E.project_info['MODELS']:
        models.append(model.split_entries()[1])

    # number of models
    nummod = len(E.project_info['MODELS'])
    crems = np.empty(nummod)

    # get filenames of preprocessed climatological mean files (all models)
    fn_alb = get_climo_filenames(E, variable='albisccp')
    fn_pct = get_climo_filenames(E, variable='pctisccp')
    fn_clt = get_climo_filenames(E, variable='cltisccp')
    fn_su  = get_climo_filenames(E, variable='rsut')
    fn_suc = get_climo_filenames(E, variable='rsutcs')
    fn_lu  = get_climo_filenames(E, variable='rlut')
    fn_luc = get_climo_filenames(E, variable='rlutcs')
    fn_snc = get_climo_filenames(E, variable='snc')
    fn_sic = get_climo_filenames(E, variable='sic')

    if not fn_snc:
        print("no data for variable snc found, using variable snw instead")
        fn_snw = get_climo_filenames(E, variable='snw')

    # loop over models and calulate CREM

    for i in range(nummod):

        if fn_snc:
            snc = fn_snc[i]
        else:
            snc = ""

        pointers = {'albisccp_nc': fn_alb[i],
                    'pctisccp_nc': fn_pct[i],
                    'cltisccp_nc': fn_clt[i],
                    'rsut_nc'    : fn_su[i],
                    'rsutcs_nc'  : fn_suc[i],
                    'rlut_nc'    : fn_lu[i],
                    'rlutcs_nc'  : fn_luc[i],
                    'snc_nc'     : snc,
                    'sic_nc'     : fn_sic[i]}

        if not fn_snc:
            pointers['snw_nc'] = fn_snw[i]

        # calculate CREM

        (CREMpd, __) = crem_calc(E, pointers)

        crems[i] = CREMpd

    print("------------------------------------")
    print(crems)
    print("------------------------------------")

    # plot results

    fig = plt.figure()
    ypos = np.arange(nummod)
    plt.barh(ypos, crems)
    plt.yticks(ypos + 0.5, models)
    plt.xlabel('Cloud Regime Error Metric')

    # draw observational uncertainties (dashed red line)
    plt.plot([0.96, 0.96], [0, nummod], 'r--')

    # if needed, create directory for plots
    if not os.path.exists(plot_dir):
        os.makedirs(plot_dir)

    plt.savefig(plot_dir + 'ww09_metric_multimodel.' + plot_type)
    print("Wrote " + plot_dir + "ww09_metric_multimodel." + plot_type)
Пример #3
0
def write_nc(fileout, xs, ys, p_vals, project_info, model):

    """ 
    ;; Arguments
    ;;    fileout: dir
    ;;          directory to save output
    ;;    xs: array [lon]
    ;;          regridding coordinates
    ;;    ys: array [lat]
    ;;          regridding coordinates
    ;;    p_vals: list
    ;;          p_values of 5x5 deg grid-boxes
    ;;
    ;; Description
    ;;    Save netCDF file with diagnostic in a regular 5x5 deg grid 
    ;;
    """
    import projects
    E = ESMValProject(project_info)
    verbosity = E.get_verbosity()

    #-------------------------
    # Read model info
    #-------------------------
    
    currProject = getattr(vars()['projects'], model.split_entries()[0])()

    model_info = model.split_entries()

       
    #------------------------------
    # Transform p_vals in 2D array
    #------------------------------
    p_val_2d = np.zeros((360/5, 120/5), dtype = 'f4')
    p_val_2d[:,:] = -999.
    i = 0    
    for x in xs:
        for y in ys:
            if p_vals[i]>-999.:
                p_val_2d[x-1, y-1] = p_vals[i]*100
            i = i+1

    #------------------------------
    # Write nc file
    #------------------------------
    diag_name = 'sm-pr-diag-plot'
    netcdf_file = E.get_plot_output_filename(diag_name=diag_name,
                                             variable='pr-mrsos',
                                             model=model_info[1],
                                             specifier='Taylor2012-diagnostic')

    suffix = E.get_graphic_format() + "$"
    netcdf_file = re.sub(suffix, "nc", netcdf_file)
    root_grp = nc4.Dataset(os.path.join(fileout, netcdf_file), 'w', format='NETCDF4')

    root_grp.description = 'Diagnostic Taylor2012: Precipitation dependance on soil moisture'

    root_grp.fillvalue = -999.0

    root_grp.createDimension('lon',360/5)
    root_grp.createDimension('lat',120/5)

    lat = root_grp.createVariable('latitude', 'f4', ('lat',))
    lon = root_grp.createVariable('longitude', 'f4', ('lon',))
    pval = root_grp.createVariable('T12_diag', 'f4', ('lat','lon'))

    lat[:] = np.arange(-60+2.5, 60, 5)
    lon[:] = np.arange(-180+2.5, 180, 5)
    pval[:,:] = np.transpose(p_val_2d)

    root_grp.close()