def plot_region_map(category_prob, lon, lat, prob_levs, clim_prob, var_name,
                    category_name, category_desc, region_name, fcst_start_name,
                    fcst_season_name, fcst_season_desc, first):
    if region_name == 'Africa':
        map_bounds = [-35, -20, 45, 65]
    if region_name == 'Asia':
        map_bounds = [-15, 40, 60, 180]
    if region_name == 'Global':
        map_bounds = [-90, -180, 90, 180]

    cfp.setvars(file='dfid_maps_forecast_' + fcst_start_name + '.' +
                region_name + '_' + var_name + '_' + fcst_season_name + '_' +
                category_name + '.png',
                axis_label_fontsize=18,
                text_fontsize=18)
    cfp.gopen()
    cfp.mapset(lonmin=map_bounds[1],
               lonmax=map_bounds[3],
               latmin=map_bounds[0],
               latmax=map_bounds[2])
    #cfp.plotvars.plot.axis.add_feature(cartopy.feature.BORDERS)
    cfp.plotvars.mymap.readshapefile(
        '/gws/nopw/j04/klingaman/datasets/GADM/ISO3Code_2014', 'countries')
    cfp.levs(manual=np.array(prob_levs))
    cfp.cscale(cmap='nrl_sirkes', ncols=len(prob_levs) + 1)
    cfp.con(
        f=category_prob,
        y=lat,
        x=lon,
        ptype=1,
        title='Probability of ' + category_desc + ' for ' + fcst_season_desc,
        colorbar_title='Forecast probability (climatological probability = ' +
        clim_prob + ' )',
        lines=False,
        line_labels=False,
        colorbar=True,
        blockfill=1)
    cfp.gclose(view=True)
    plt.show()
Example #2
0
def plot_autocorr(time_correlations,time_max,dt=None,model_dict=None,colors=None,legend_names=None,set_desc=None,legend=True,legend_location='lower left'):

    """
    Plots correlations as a function of physical time from one or several datasets,
    using lagged auto-correlation data from compute_autocorr.  The output is a line graph.
    See Fig. 3b in Klingaman et al. (2017) for an example.

    Note that the lag-0 correlation is not plotted, as this is 1.0 by definition.

    Arguments:
    * time_correlations (n_datasets,max_timesteps) or (max_timesteps):
        Composite correlations as a function of physical time, averaged over all points
        in the analysis region, as output from compute_autocorr.  If a 2D array, then
        the routine assumes that the input contains > 1 sets of composite correlations
        from multiple datasets.
    * time_max (n_datasets) or scalar:
        The longest lag for which the data is time_correlations is valid, as output from
        compute_autocorr.  If a 1D array, then the routine assumes that the input contains
        > 1 sets of values from multiple datasets.

    Arguments that may be required (see below):
    * model_dict:
        The dictionary containing information about this dataset.  Required only if plotting
        data for one dataset.
    * dt (n_datasets):
        An array containing the temporal sampling frequency for each input dataset.  Required
        only if plotting data for more than one dataset.
    * colors (n_datasets):
        A list of line colors for each dataset.  Required only if plotting data for more than
        one dataset.
    * legend_names (n_datasets):
        A list of legend names for each dataset.  Required only if plotting data for more than
        one dataset.
    * set_desc:
        A string containing a description for this set of datasets.  Used in output plot filename.
        Required only if plotting data for more than one dataset.

    Optional arguments:
    * legend:
        If set to True, include a legend on the graph.  Default is True.
    * legend_location
        Location for the legend on the graph (e.g., 'lower left', 'upper right').  Default is 'lower left'.
    """

    print('--> Plotting correlations vs. time for all models.')

    if time_correlations.ndim == 1:
        if model_dict == None:
            raise Exception('You are plotting correlations for only one dataset, but you have not specified a dataset dictionary with the model_dict option to plot_autocorr.')
        else:
            colors=model_dict['color']
            if legend == True:
                legend_names=model_dict['legend_names']
            set_desc=model_dict['name']
            dt = model_dict['dt']
            nmodels=1
    elif time_correlations.ndim == 2:
        nmodels=time_correlations.shape[0]
        if colors == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a list of plot colors with the colors option to plot_autocorr.')
        if legend_names == None and legend == True:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a list of legend names with the legend_names option to plot_autocorr.')
        if set_desc == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a description for this dataset with the set_desc option to plot_autocorr.')
        if dt.all() == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified an array of temporal sampling intervals with the dt option to plot_autocorr.')
    else:
        raise Exception('plot_autocorr expects the time_correlations argument to be either a one-dimensional (for only one dataset) or two-dimensional (for multiple datasets).')

    cfp.setvars(file='asop_coherence.'+set_desc+'_precip_temporal_correlations.ps',text_fontsize=20,axis_label_fontsize=20,legend_text_size=18)
    cfp.gopen()
    if np.amax(dt) >= 86400:
        dt_min = dt/86400.0
        t_units='days'
    else:
        dt_min = dt/60
        t_units='minutes'
    tmax=np.amax((time_max-1)*dt_min)
    xmax=tmax+np.amax(dt_min)*0.5
    cfp.gset(xmin=0,xmax=xmax,ymin=-0.5,ymax=1.0)

    if time_correlations.ndim == 2:
        for model in range(nmodels):
            xpts=(np.arange(time_max[model]))*dt_min[model]
            ypts=time_correlations[model,0:time_max[model]]
            print(xpts,ypts)
            if model == nmodels-1 and legend:
                cfp.lineplot(x=xpts[1:],y=ypts[1:],linestyle=':',marker='o',color=colors[model],markersize=8,label=legend_names[model],
                             xticks=np.arange(11)*tmax//10,yticks=np.round(np.arange(12)*0.1-0.1,1),legend_location=legend_location)
            else:
                cfp.lineplot(x=xpts[1:],y=ypts[1:],linestyle=':',marker='o',color=colors[model],markersize=8,label=legend_names[model],
                             xticks=np.arange(11)*tmax//10,yticks=np.round(np.arange(12)*0.1-0.1,1))
    elif time_correlations.ndim == 1:
        xpts=(np.arange(time_max))*dt_min
        ypts=time_correlations[0:time_max]
        cfp.lineplot(x=xpts[1:],y=ypts[1:],linestyle=':',marker='o',color=colors,markersize=8,label=legend_names,
                     xticks=np.arange(11)*tmax//10,yticks=np.round(np.arange(12)*0.1-0.1,1))

    cfp.plotvars.plot.plot([0,xmax],[0,0],linestyle=':',color='black')
    cfp.plotvars.plot.set_xticklabels(np.arange(11)*tmax//10,fontsize=16)
    cfp.plotvars.plot.set_yticklabels(np.round(np.arange(12)*0.1-0.1,1),fontsize=16)
    cfp.plotvars.plot.set_xlabel('Time ('+t_units+')',fontsize=20)
    cfp.plotvars.plot.set_ylabel('Auto-correlation (mean of all points)',fontsize=20)
    cfp.gclose()
Example #3
0
def plot_equalarea_corr(distance_correlations,distance_ranges,distance_max,model_dict=None,colors=None,legend_names=None,set_desc=None,legend=True,legend_location='lower left'):

    """
    Plots correlations as a function of physical distance from one or several datasets,
    using correlation data from compute_equalarea_corr.  The output is a line graph.
    See Fig. 3a in Klingaman et al. (2017) for an example.

    Note that the correlation at the central point (0 km) is not plotted, as this is 1.0 by definition.

    Arguments:
    * distance_correlations (n_datasets,max_box_distance) or (max_box_distance):
        Composite correlations as a function of physical distance, averaged over
        all sub-regions, as output from compute_equalarea_corr.  If a 2D array, then
        the routine assumes that the input contains > 1 sets of composite correlations
        from multiple datasets.
    * distance_ranges (n_datasets,3,max_box_distance) or (3,max_distance) :
        For each bin of physical distance, the minimum, median and maximum distance
        of points that fall into that bin, as output from compute_equalarea_corr.  If
        a 3D array, then the routine assumes that the input contains > 1 sets of
        range values from multiple datasets.
    * distance_max (n_datasets) or scalar:
        The furthest distance bin for which the data in distance_corelations and
        distance_ranges is valid, as output from compute_equalarea_corr.  If a 1D
        array, then the routine assumes that the input contains > 1 set of values
        from multiple datasets.

    Arguments that may be required (see below):
    * model_dict:
        The dictionary containing information about this dataset.  Required only if plotting
        data for one dataset.
    * colors (n_datasets):
        A list of line colors for each dataset.  Required only if plotting data for more than
        one dataset.
    * legend_names (n_datasets):
        A list of legend names for each dataset.  Required only if plotting data for more than
        one dataset.
    * set_desc:
        A string containing a description for this set of datasets.  Used in output plot filename.
        Required only if plotting data for more than one dataset.

    Optional arguments:
        * legend:
        If set to True, include a legend on the graph.  Default is True.
        * legend_location
        Location for the legend on the graph (e.g., 'lower left', 'upper right').  Default is 'lower left'.
    """

    print('--> Plotting correlations vs. distance for all models.')
    max_box_distance,max_boxes,max_timesteps = parameters()

    if distance_correlations.ndim == 1:
        if model_dict == None:
            raise Exception('You are plotting correlations for only one dataset, but you have not specified a dataset dictionary with the model_dict option to plot_equalarea_corr.')
        else:
            colors=model_dict['color']
            legend_names=model_dict['legend_names']
            set_desc=model_dict['name']
            nmodels=1
    elif distance_correlations.ndim == 2:
        nmodels=distance_correlations.shape[0]
        if colors == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a list of plot colors with the colors option to plot_equalarea_corr.')
        if legend_names == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a list of legend names with the legend_names option to plot_equalarea_corr.')
        if set_desc == None:
            raise Exception('You are plotting correlations for more than one dataset, but you have not specified a description for this dataset with the set_desc option to plot_equalarea_corr.')
    else:
        raise Exception('plot_equalarea_corr expects the distance_correlations argument to be either a one-dimensional (for only one dataset) or two-dimensional (for multiple datasets).')

    cfp.setvars(file='asop_coherence.'+set_desc+'_precip_spatial_correlations.ps',text_fontsize=20,axis_label_fontsize=20,legend_text_size=18)
    cfp.gopen()

    if distance_correlations.ndim == 2:
        dmax=np.amax(distance_ranges[:,2,:])
        print(dmax)
        xmax=dmax*1.05
        cfp.gset(xmin=0,xmax=xmax,ymin=-0.5,ymax=1.0)
        for model in range(nmodels):
            xpts=distance_ranges[model,1,1:distance_max[model]].flatten()
            ypts=distance_correlations[model,1:distance_max[model]].flatten()
            print(xpts,ypts)
            if model == nmodels-1 and legend:
                cfp.lineplot(x=xpts,y=ypts,linestyle=':',marker='o',color=colors[model],markersize=8,label=legend_names[model],legend_location=legend_location,xticks=np.arange(0,dmax+1,dmax//10),yticks=np.round(np.arange(12)*0.1-0.1,1))
            else:
                cfp.lineplot(x=xpts,y=ypts,linestyle=':',marker='o',color=colors[model],markersize=8,label=legend_names[model],xticks=np.arange(0,dmax+1,dmax//10),yticks=np.round(np.arange(12)*0.1-0.1,1))
            for dist in range(1,distance_max[model]):
                xpts=[distance_ranges[model,0,dist],distance_ranges[model,2,dist]]
                ypts=[distance_correlations[model,dist],distance_correlations[model,dist]]
                cfp.plotvars.plot.plot(xpts,ypts,linewidth=2,color=colors[model])
    elif distance_correlations.ndim == 1:
        dmax=np.amax(distance_ranges[2,:])
        xmax=dmax*1.05
        cfp.gset(xmin=0,xmax=xmax,ymin=-0.5,ymax=1.0)
        xpts=distance_ranges[1,1:distance_max].flatten()
        ypts=distance_correlations[1:distance_max].flatten()
        if legend:
            cfp.lineplot(x=xpts,y=ypts,linestyle=':',marker='o',color=colors,markersize=8,label=legend_names,legend_location=legend_location,
                         xticks=np.arange(0,dmax+1,dmax//10),yticks=np.round(np.arange(12)*0.1-0.1,1))
        else:
            cfp.lineplot(x=xpts,y=ypts,linestyle=':',marker='o',color=colors,markersize=8,label=legend_names,legend_location=legend_location,
                         xticks=np.arange(0,dmax+1,dmax//10),yticks=np.round(np.arange(12)*0.1-0.1,1))
        for dist in range(1,distance_max):
            xpts=[distance_ranges[0,dist],distance_ranges[2,dist]]
            ypts=[distance_correlations[dist],distance_correlations[dist]]
            cfp.plotvars.plot.plot(xpts,ypts,linewidth=2,color=colors)

    cfp.plotvars.plot.plot([0,xmax],[0,0],linestyle=':',color='black')
#    cfp.plotvars.plot.set_xticks(np.arange(0,xmax,max_box_size/10))
    cfp.plotvars.plot.set_xticklabels(np.arange(0,dmax+1,dmax//10),fontsize=16)
#    cfp.plotvars.plot.set_yticks(np.arange(12)*0.1-0.1)
    cfp.plotvars.plot.set_yticklabels(np.round(np.arange(12)*0.1-0.1,1),fontsize=16)
    cfp.plotvars.plot.set_xlabel('Distance from central gridpoint (km)',fontsize=20)
    cfp.plotvars.plot.set_ylabel('Lag=0 correlation (mean of sub-regions)',fontsize=20)
    cfp.gclose()
Example #4
0
def plot_equalgrid_corr(corr_map,lag_vs_distance,autocorr,npts,model_dict,title=True,colorbar=True):

    """
    Plots correlations as functions of space and time, which were first computed
    using compute_equalgrid_corr.

    Two types of plots are created:

        1. For each lag (from 0 to lag_length defined in model_dict), a 2D map
        of the composite correlations against the central point (at lag 0) for all
        points in the region (of length region_size).

        2. A single lag vs. distance plot showing the composite correlations against
        the central point (at lag 0), averaged over all points in each region in each
        distance bin (in steps of dx starting at 0.5dx), as well as the auto-correlation
        at the central point.

    See Fig. 2 in Klingaman et al. (2017, GMD, doi:10.5194/gmd-10-57-2017) for examples
    of these diagrams.

    Arguments:
      * corr_map (lag_length,region_size,region_size):
         Composite maps of correlations at each lag, returned from compute_equalgrid_corr
      * lag_vs_distance (lag_length,region_size):
         Composite correlations over all regions in the domain, expressed as a function of
         time (lag) and distance from the central point, returned from compute_equalgrid_corr
      * autocorr (lag_length):
         The composite auto-correlation of precipitation at the central point, averaged over
         all regions in the domain.
      * npts (lag_length,region_size):
         The number of gridpoints in each distance bin of the lag_vs_distance array.  Used to
         to determine whether there are any points in each distance bin.

    Optional arguments:
      * title:
         Include a title on the plot
      * colorbar:
         Include a colorbar on the plot

    Returns:
      None
    """

    region_size = model_dict['region_size']
    lag_length = model_dict['lag_length']

    print('---> Plotting correlation maps for '+str(region_size)+'x'+str(region_size)+' sub-regions')
    corr_con_levs=[0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95]

    # Plot correlation maps at each lag
    for lag in range(lag_length):
        plot_name='asop_coherence.'+model_dict['name']
        if 'grid_type' in model_dict:
            plot_name=plot_name+'_'+model_dict['grid_type']
        if 'time_type' in model_dict:
            plot_name=plot_name+'_'+model_dict['time_type']
        if 'region_name' in model_dict:
            plot_name=plot_name+'_'+model_dict['region_name']
        plot_name=plot_name+'_precip_'+str(region_size)+'x'+str(region_size)+'maps_lag'+str(lag)+'.ps'
        cfp.setvars(file=plot_name,text_fontsize=18,axis_label_fontsize=18,colorbar_fontsize=18)
        cfp.gopen(figsize=[8,8])
        cfp.gset(xmin=0,xmax=region_size,ymin=0,ymax=region_size)
        cfp.levs(manual=np.array(corr_con_levs))
        cfp.cscale(cmap='parula',reverse=1,ncols=len(corr_con_levs)+1,white=0)
        #cfp.axes(xticks=np.arange(region_size)+0.5,yticks=np.arange(region_size)+0.5,
        #         xticklabels=np.arange(region_size)-region_size//2,yticklabels=np.arange(region_size)-region_size//2)           
        if title == True:
            title_string = 'Correlation map for '+model_dict['legend_name']
            if 'time_desc' in model_dict:
                title_string = title_string + ' - ' +model_dict['time_desc']
            if 'grid_desc' in model_dict:
                title_string = title_string + ' - ' +model_dict['grid_desc']
            if 'region_desc' in model_dict:
                title_string = title_string+' - '+model_dict['region_desc']
            title_string = title_string + ' - Lag '+str(lag)
        else:
            title_string = ''
        if colorbar == True:
            cfp.con(f=corr_map[lag,:,:],x=np.arange(region_size)+0.5,y=np.arange(region_size)+0.5,blockfill=1,
                    lines=False,line_labels=False,ptype=0,colorbar=1,colorbar_title='Correlation with (0,0) at lag 0, mean over all sub-regions',
                    title=title_string, colorbar_text_up_down=True,
                    xlabel='$\Delta$x (approximately '+str(model_dict['dx'])+' km)',
                    ylabel='$\Delta$y (approximately '+str(model_dict['dy'])+' km)',
                    xticks=np.arange(region_size)+0.5,yticks=np.arange(region_size)+0.5,
                    xticklabels=np.arange(region_size)-region_size//2,yticklabels=np.arange(region_size)-region_size//2)
        else:
            cfp.con(f=corr_map[lag,:,:],x=np.arange(region_size)+0.5,y=np.arange(region_size)+0.5,blockfill=1,
                    lines=False,line_labels=False,ptype=0,colorbar=0,title=title_string, 
                    xlabel='$\Delta$x (approximately '+str(model_dict['dx'])+' km)',
                    ylabel='$\Delta$y (approximately '+str(model_dict['dy'])+' km)',
                    xticks=np.arange(region_size)+0.5,yticks=np.arange(region_size)+0.5,
                    xticklabels=np.arange(region_size)-region_size//2,yticklabels=np.arange(region_size)-region_size//2)
        for region_x in range(region_size):
            for region_y in range(region_size):
                if corr_map[lag,region_y,region_x] > 0.5:
                    cfp.plotvars.plot.text(region_x+0.5,region_y+0.5,str(corr_map[lag,region_y,region_x])[0:4],
                                           horizontalalignment='center',color='white',fontsize=20)
                elif corr_map[lag,region_y,region_x] < 0.0:
                    cfp.plotvars.plot.text(region_x+0.5,region_y+0.5,str(corr_map[lag,region_y,region_x])[0:5],
                                           horizontalalignment='center',color='black',fontsize=20)
                else:
                    cfp.plotvars.plot.text(region_x+0.5,region_y+0.5,str(corr_map[lag,region_y,region_x])[0:4],
                                           horizontalalignment='center',color='black',fontsize=20)
        cfp.gclose()

    # Plot correlation vs. distance diagram
    print('---> Plotting lag vs. distance diagram')
    plot_name='asop_coherence.'+model_dict['name']
    if 'grid_type' in model_dict:
        plot_name=plot_name+'_'+model_dict['grid_type']
    if 'time_type' in model_dict:
        plot_name=plot_name+'_'+model_dict['time_type']
    if 'region_name' in model_dict:
        plot_name=plot_name+'_'+model_dict['region_name']
    plot_name=plot_name+'_precip_'+str(region_size)+'x'+str(region_size)+'_lag'+str(lag_length)+'.ps'
    cfp.setvars(file=plot_name,text_fontsize=20,axis_label_fontsize=18)
    cfp.gopen(figsize=[9,8])
    ticklabels=['Centre','0.5']
    max_dist=0
    for dist in range(2,region_size):
        if npts[0,dist] > 0 :
            ticklabels.append(str(dist-0.5))
            max_dist=dist
    ticklabels.append(str(max_dist+0.5))
    ticklabels.append(str(max_dist+1.5))
    lag_vs_distance=np.insert(lag_vs_distance,0,autocorr,1)
    cfp.gset(xmin=0,xmax=max_dist+1,ymin=0,ymax=lag_length)
    cfp.levs(manual=np.array(corr_con_levs))
    cfp.cscale(cmap='parula',reverse=1,ncols=len(corr_con_levs)+1,white=0)
    xtickvals=np.arange(max_dist+1)+2.0
    xtickvals=np.insert(xtickvals,0,[0.5,1.0])
    cfp.axes(xticks=xtickvals,yticks=np.arange(lag_length)+0.5,xticklabels=ticklabels,yticklabels=np.arange(lag_length),
             xlabel='$\Delta$x bins ($\Delta$x approximately '+str(model_dict['dx'])+' km at the equator)',ylabel='Lag')

    if title == True:
        title_string = 'Correlation map for '+model_dict['legend_name']
        if 'time_desc' in model_dict:
            title_string = title_string + ' - ' +model_dict['time_desc']
        if 'grid_desc' in model_dict:
            title_string = title_string + ' - ' +model_dict['grid_desc']
        if 'region_name' in model_dict:
            title_string = title_string+' - '+model_dict['region_name']
    else:
        title_string = ''
    if colorbar == True:
        cfp.con(f=lag_vs_distance[:,0:max_dist+2],x=np.arange(max_dist+2)+0.5,y=np.arange(lag_length)+0.5,blockfill=1,
                lines=False,line_labels=False,ptype=0,colorbar_title='Correlation with centre at lag=0, mean over all sub-regions',
                title=title_string)

    else:
        cfp.con(f=lag_vs_distance[:,0:max_dist+2],x=np.arange(max_dist+2)+0.5,y=np.arange(lag_length)+0.5,blockfill=1,
                lines=False,line_labels=False,ptype=0,colorbar=0,title=title_string)

    for dist in range(max_dist+2):
        for lag in range(lag_length):
            if lag_vs_distance[lag,dist] == -999:
                print('-999')
            #                cfp.plotvars.plot.text(dist+0.5,lag+0.5,'XXX',horizontalalignment='center',color='black',fontsize=20,verticalalignment='center')
            elif lag_vs_distance[lag,dist] > 0.5:
                cfp.plotvars.plot.text(dist+0.5,lag+0.5,str(lag_vs_distance[lag,dist])[0:4],
                                       horizontalalignment='center',color='white',fontsize=20)
            elif lag_vs_distance[lag,dist] < 0.0:
                cfp.plotvars.plot.text(dist+0.5,lag+0.5,str(lag_vs_distance[lag,dist])[0:5],
                                       horizontalalignment='center',color='black',fontsize=20)
            else:
                cfp.plotvars.plot.text(dist+0.5,lag+0.5,str(lag_vs_distance[lag,dist])[0:4],
                                       horizontalalignment='center',color='black',fontsize=20)
    cfp.gclose()
f = cf.read('testdata/ggap.nc')[1]
cfp.gopen(rows=2, columns=2, bottom=0.2)
cfp.gpos(1)
cfp.con(f.subspace(pressure=500), lines=False, colorbar=None)
cfp.gpos(2)
cfp.mapset(proj='moll')
cfp.con(f.subspace(pressure=500), lines=False, colorbar=None)
cfp.gpos(3)
cfp.mapset(proj='npstere', boundinglat=30, lon_0=180)
cfp.con(f.subspace(pressure=500), lines=False, colorbar=None)
cfp.gpos(4)
cfp.mapset(proj='spstere', boundinglat=-30, lon_0=0)
cfp.con(f.subspace(pressure=500),
        lines=False,
        colorbar_position=[0.1, 0.1, 0.8, 0.02],
        colorbar_orientation='horizontal')
cfp.gclose()

for png in pngs:
    if not os.path.isfile(png):
        raise Exception(f'PNG not written: {png}')

    os.system(f'display {png} &')

resp = input('Did you see 3 images? ')

print('Please close the images')

if not resp.lower().startswith('y'):
    raise Exception('cfplot tests failed.')