Example #1
0
def plot_region(regname,ptype='nh',axis=None,latlim=None,limsdict=None): 
    """ plot_region(regname,ptype='nh',axis=None,latlim=None,limsdict=None):
                     Given a region name, plot it for reference.

                     latlims is unused right now
                     if passing limsdict (to override regname), set regname='other'
    """

    if regname=='other':
        reglims=limsdict
    else:
        reglims = con.get_regionlims(regname)

    latlims = reglims['latlims']
    lonlims = reglims['lonlims']

    dummy = con.get_t63landmask()
    lat = con.get_t63lat()
    lon = con.get_t63lon()

    lons,lats = np.meshgrid(lon,lat)

    reglatsbool = np.logical_and(lat>latlims[0],lat<latlims[1])
    reglonsbool = np.logical_and(lon>lonlims[0],lon<lonlims[1])

    # mask everything but the region of interest
    regmask = np.logical_or( 
                            np.logical_or(lats<latlims[0],lats>latlims[1]), 
                            np.logical_or(lons<lonlims[0],lons>lonlims[1]))
    dummym = ma.masked_where(regmask,dummy)

    plt.figure()
    kemmap(dummym,lat,lon,ptype=ptype,axis=axis,latlim=latlim,suppcb=1,
           cmin=-11,cmax=2,cmap='blue2blue_w10',drawgrid=True)
Example #2
0
def plot_regions(regions, ptype='nh', colors='k', latlim=None, drawgrid=False):
    """ plot multiple region boundaries on one map

           regions: tuple of region names

           default color = black
           colors can be a tuple of color specifications. 
                index will wrap if not enough

    """

    dummy = con.get_t63landmask()
    lat = con.get_t63lat()
    lon = con.get_t63lon()

    lons,lats = np.meshgrid(lon,lat)
    dummy = dummy*np.nan

    plt.figure()
    bm,pc = kemmap(dummy,lat,lon,ptype=ptype,latlim=latlim,suppcb=1,
                   drawgrid=drawgrid, lmask=True)
    
    for ii,reg in enumerate(regions):

        if len(colors)==1: clr=colors
        else:
            if ii==len(colors): ii=0 # wrap index
            clr=colors[ii]

        add_regionpolym(reg,bm, ec=clr)
Example #3
0
def plot_allregions(ptype='nh'):
    """ plot_allregions(ptype='nh'): plot all defined regions
    """

    regdict = con.get_regiondict()
    nreg = len(regdict)
    rem = np.mod(nreg,2)
    rows = 2
    
    if rem==0:
        cols = nreg/rows
    else:
        cols = nreg/rows + rem # rem will always be 1 if dividing by 2

    if cols>8: 
        rows = 3
        cols = nreg/rows + np.mod(nreg,rows)/2

    print 'nrows: ' + str(rows) + ' ncols: ' + str(cols) # @@@
    
    lat = con.get_t63lat()
    lon = con.get_t63lon()
    
    fig,spax = plt.subplots(rows,cols)
    fig.set_size_inches(cols*2,rows*3)
    
    for aii,ax in enumerate(spax.flat):

        dummy = con.get_t63landmask() # dummy data
        
        regkey = regdict.keys()[aii]
        limsdict = regdict[regkey]
        # mask the dummy data
        dummym,dmask = cutl.mask_region(dummy,lat,lon,regkey,limsdict=limsdict)
                
        kemmap(dummym,lat,lon,ptype=ptype,axis=ax,suppcb=1,cmin=-11,cmax=2,cmap='blue2blue_w10')        
        ax.set_title(regkey)
        ax.set_xlabel(str(limsdict['latlims']) + ',' +str(limsdict['lonlims']) )
        
        if aii==nreg-1: break # get out of loop if done with regions
Example #4
0
seacycylim=None
infodict ={'cmapclimo': 'Spectral_r','leglocs': None,
           'seacycylim': None, 'savestr': savestr,
           'model': model, 'sigtype': sigtype, 'sigoff': sigoff,
           'pct': pct, 'seacyclatlim': seacyclatlim, 'region': region,
           'shadeens': shadeens, 'corrlim': corrlim, 'figtrans':figtrans,
           'ptype': projtype,'contclr': '0.3', 'contthk': 1, 'contstl': None} # random other info. projtype for maps only

fdict,pparams=ld.loadfldmeta(field,infodict,plottype,ptparams,level=level)

if addcont: # overlay map with another field in contours
    # start with just anomaly contours. @@later add option for climo
    fdict2,pparams2=ld.loadfldmeta(field2,infodict,plottype,ptparams,level=level2)


coords = {'lev': con.get_t63lev(), 'lat': con.get_t63lat(), 'lon': con.get_t63lon()}
## infodict['savestr'] = savestr
## infodict['leglocs'] = leglocs
## infodict['seacycylim'] = seacycylim
## fdict['isflux'] = isflux
## fdict['threed'] = threed
## ###################### end copy to load_fldmeta.py

# do an if elif elif ....
if plottype=='seasonalvert':
    infodict['screen']=screen
else:
    infodict['screen'] = None
        
if plottype in ('seasonalmap','seasonalvert'):
Example #5
0
def pattcorr_ensemble(ename, field, latlim=60):
    # @@@@@@@@@@@@ is this fully implemented? Don't think so. 12/2/14
    
    if ename=='ANT':
        ename='HistIC'
    elif ename=='TOT':
        ename='HistBC'

    enssims = con.build_ensemblesims(ename)
    ensnum=len(enssims)

    # ======= copied from Canam4_BCpatterncorr-Copy0.py ===========

    #ensnum=5
    diffdict = {}
    pcmeandict = {} # fldp-fldc pattern corr compared to mean BC
    pchaddict = {} # fldp-fldc pattern corr compared to hadisst
    seadiffdict = {} # seasonal mean
    pcseameandict = {}
    pcsea2meandict = {} # to test the other pattern corr calc
    pcsea2pvalmeandict = {} # to test the other pattern corr calc

    # generate weights for the pattern corr
    lat = con.get_t63lat()
    lon = con.get_t63lon()

    areas = cutl.calc_cellareas(lat,lon)
    areas = areas[lat>latlim,:]
    weights = areas / np.sum(np.sum(areas,axis=1),axis=0)

    #for eii in range(1,ensnum+1):
    for skey in enssims:

        #skey = etype + str(eii)
        #casenamec = bcasenamec + skey
        #casenamep = bcasenamep + skey
        #fnamec = basepath + casenamec+ subdir + casenamec + '_' + field + '_001-121_ts.nc'
        #fnamep = basepath + casenamep+ subdir + casenamep + '_' + field + '_001-121_ts.nc'
        fnamec,fnamep = con.build_filepathpair(skey,field)

        # monthly calc
        fldc = cnc.getNCvar(fnamec,ncfield,timesel=timesel)*conv
        fldp = cnc.getNCvar(fnamep,ncfield,timesel=timesel)*conv
        fldd = fldp-fldc

        # take the pattern correlation
        flddclimo,flddstd = cutl.climatologize(fldd) # climo first (don't need to do for BCs technically)
        flddcclimo,flddcstd = cutl.climatologize(flddc) # climo first. baseline diff data

        diffdict[skey] = flddclimo

        # for each month, compute pattern corr
        pc = np.zeros((12))
        for mii,mon in enumerate(con.get_mon()):
            tmp = np.squeeze(flddclimo[mii,lat>latlim,...])
            tmpcmp = np.squeeze(flddcclimo[mii,lat>latlim,...])
            pc[mii] = cutl.pattcorr(tmp.flatten()*weights.flatten(),tmpcmp.flatten()*weights.flatten())

        pcmeandict[skey] = pc # monthly

        # seasonal calc    
        fldcsea = np.zeros((4,len(lat),len(lon)))
        fldpsea = np.zeros((4,len(lat),len(lon)))
        flddsea = np.zeros((4,len(lat),len(lon)))
        pcsea = np.zeros((4))
        pcsea2 = np.zeros((4)) # test pattcorr_pearson() @@
        pcsea2pval = np.zeros((4)) # test pattcorr_pearson()

        for seaii,sea in enumerate(seasons):
            fldcsea[seaii,...] = np.mean(cnc.getNCvar(fnamec,ncfield,timesel=timesel,seas=sea)*conv,axis=0)
            fldpsea[seaii,...] = np.mean(cnc.getNCvar(fnamep,ncfield,timesel=timesel,seas=sea)*conv,axis=0)
            flddsea[seaii,...] = fldpsea[seaii,...]-fldcsea[seaii,...]

            tmp = np.squeeze(flddsea[seaii,lat>latlim,...])
            tmpcmp = np.squeeze(flddcsea[seaii,lat>latlim,...])
            pcsea[seaii] = cutl.pattcorr(tmp.flatten()*weights.flatten(),
                                         tmpcmp.flatten()*weights.flatten())
            pcsea2[seaii],pcsea2pval[seaii] = cutl.pattcorr_pearson(tmp.flatten()*weights.flatten(),
                                                                    tmpcmp.flatten()*weights.flatten())


        seadiffdict[skey] = flddsea        
        pcseameandict[skey] = pcsea
        pcsea2meandict[skey] = pcsea2
        pcsea2pvalmeandict[skey] = pcsea2pval
Example #6
0
def pattcorr_withinensemble(ename,fdict,latlim=60,timesel='0002-01-01,0121-12-31'):
    """ pattcorr_withinensemble(ename,field,latlim=60)
            pattern corr each member of ensemble with each other one

            return pctable, pctablesea (DataFrames)
    """
    # @@ need diffdict

    field=fdict['field']
    ncfield=fdict['ncfield']
    conv=fdict['conv']
    
    seasons=('SON','DJF','MAM','JJA')
    
    
    if ename=='ANT':
        ename='histIC'
    elif ename=='TOT':
        ename='histBC'

    enssims = con.build_ensemblesims(ename)
    ensnum=len(enssims)

    print 'ENSSIMS: ' # @@@
    print enssims # @@
    
    # generate weights for the pattern corr
    lat = con.get_t63lat()
    lon = con.get_t63lon()

    areas = cutl.calc_cellareas(lat,lon)
    areas = areas[lat>latlim,:]
    weights = areas / np.sum(np.sum(areas,axis=1),axis=0)

    # ========= create diffdict first =====
    diffdict={}
    seadiffdict={}
    for skey in enssims:
        fnamec,fnamep = con.build_filepathpair(skey,field)

        # monthly calc
        fldc = cnc.getNCvar(fnamec,ncfield,timesel=timesel)*conv
        fldp = cnc.getNCvar(fnamep,ncfield,timesel=timesel)*conv
        fldd = fldp-fldc

        # Monthly
        flddclimo,flddstd = cutl.climatologize(fldd) # climo first (don't need to do for BCs technically)
        #flddcclimo,flddcstd = cutl.climatologize(flddc) # climo first. baseline diff data

        diffdict[skey] = flddclimo
        print skey + ' ' + str(flddclimo.shape) # @@@

        # Seasonal
        flddsea = np.zeros((4,len(lat),len(lon)))

        for seaii,sea in enumerate(seasons):
            fldcsea = np.mean(cnc.getNCvar(fnamec,ncfield,timesel=timesel,seas=sea)*conv,axis=0)
            fldpsea = np.mean(cnc.getNCvar(fnamep,ncfield,timesel=timesel,seas=sea)*conv,axis=0)
            flddsea[seaii,...] = fldpsea-fldcsea

        seadiffdict[skey] = flddsea

    # ======= Now do pattern corrs within ensemble ====

    # ======= copied from Canam4_BCpatterncorr-Copy0.py ===========

    outterdict= dict.fromkeys(enssims)

    for skey1 in enssims:

        outfld = diffdict[skey1]

        innerdict = dict.fromkeys(enssims)

        for skey2 in enssims:
            #print skey1 + ' compared to ' + skey2

            infld = diffdict[skey2]

            # for each month, compute pattern corr
            pc = np.zeros((12))
            for mii,mon in enumerate(con.get_mon()):
                tmp = np.squeeze(infld[mii,lat>latlim,...])
                tmpcmp = np.squeeze(outfld[mii,lat>latlim,...])
                pc[mii] = cutl.pattcorr(tmp.flatten()*weights.flatten(),
                                        tmpcmp.flatten()*weights.flatten())

            innerdict[skey2] = pc

        outterdict[skey1] = innerdict

    pctable = pd.DataFrame(outterdict) # 5x5

    # seasonal 
    outterdictsea= dict.fromkeys(enssims)

    for skey1 in enssims:

        outfld = seadiffdict[skey1]

        innerdictsea = dict.fromkeys(enssims)

        for skey2 in enssims:    

            #print skey1 + ' compared to ' + skey2

            infld = seadiffdict[skey2]

            # for each season, compute pattern corr
            pcsea = np.zeros((4))
            for seaii,sea in enumerate(seasons):
                tmp = np.squeeze(infld[seaii,lat>latlim,...])
                tmpcmp = np.squeeze(outfld[seaii,lat>latlim,...])
                pcsea[seaii] = cutl.pattcorr(tmp.flatten()*weights.flatten(),
                                        tmpcmp.flatten()*weights.flatten())

            innerdictsea[skey2] = pcsea

        outterdictsea[skey1] = innerdictsea

    pctablesea = pd.DataFrame(outterdictsea) # 5x5

    return pctable, pctablesea
timesel='2922-01-01,2931-12-31'



Cp=1004 # specific heat at const pressure (J/K/kg)
Lv=2.5e6 # specific heat of condensation (latent heat of vapo) at 0C(?@@) (J/kg)
erad = con.get_earthrad() # m
grav = con.get_g() # m/s2

# 1 cal = 4.186J
# convert to cal / day
# J/s -> cal/day
W2calperday = (60*60*24)/4.186

lat = con.get_t63lat()
lon = con.get_t63lon()
#lev = con.get_t63lev() # 37 levs
fname=basepath + casename + '_u_' + timeper + '_ts.nc' # 22 levs!!
lev = cnc.getNCvar(fname,'plev')
dp = np.diff(lev)
nlon = len(lon)-1 # removing extra lon

# get surface pressure to do vert avg and int here
fname=basepath + casename + '_ps_' + timeper + '_ts.nc'
sfcp = cnc.getNCvar(fname,'PS',timesel=timesel)*100 # into Pa

def clear_belowsfc(fld, sfcp, lev):

    #levt=np.tile(lev,((sfcp.shape)+(1,)))
    #levt = np.transpose(levt,(3,0,1,2)) # lev x time x lat x lon (for now)
    
                  title=ttl2,suppcb=True,
                  panellab='b',lcol='0.2')

bm.contour(lons,lats,fldsp2onfldr2,levels=conts,
           colors='0.5',linewidths=1,latlon=True)

cplt.add_colorbar(fig,pc,orientation='horizontal')

if printtofile:
    fig.savefig(fieldsp + '_' + fieldsp2 + seasp + \
                '_regresson_' + fieldr+regionr + '_' + fieldr2 + regionr2 + sear + '.pdf') 


# ========== AGCM

alat=con.get_t63lat(); alon=con.get_t63lon()
alons, alats = np.meshgrid(alon,alat)

cmlen=15.
incra = (cmaxsp2a-cminsp2a) / (cmlen)
contsa = np.arange(cminsp2a,cmaxsp2a+incra,incra)


fig,axs=plt.subplots(1,2)
fig.set_size_inches(10,5)
fig.subplots_adjust(wspace=0.05)
ax=axs[0]
bm,pc=cplt.kemmap(asponfldr,alat,alon,ptype='nheur',axis=ax,cmin=cminspa,cmax=cmaxspa,
                  title=ttl1,suppcb=True,
                  panellab='a',lcol='0.2')
bm.contour(alons,alats,asp2onfldr,levels=contsa,
meta = {'gt': gt, 'sicn': sicn, 'sic': sic}
ylabs = {0: 'OBS', 1: 'E1', 2: 'E2', 3: 'E3', 4: 'E4', 5:'E5'} 
convdt = {'gt': 1, 'sicn': 100, 'sic': 1/np.float(deni)}


# === load one year for seasonal cycle:
#flddat,fldcdat,fldpdat,sicnpdat = load_BCs(fields, season=None, timesel=timesel)




# ============== PLOT ==============
printtofile=False
lat = con.get_t63lat() #cnc.getNCvar(fnamec,'lat')
lon = con.get_t63lon() #cnc.getNCvar(fnamep,'lon')

fsz=16
fliptohoriz=True
latlim=57
pparams = {'lcol':'0.9', 'coastres': 'c', 'coastwidth': 0.5, 
           'area_thresh':70000,'lmask':True}

fields=('sicn','sic','gt')
fields=('sicn',)
tlabs = {'gt': '$\Delta$ SST ($^\circ$C)', 'sicn': '$\Delta$ SIC (%)', 'sic': '$\Delta$ SIT (m)'}

if fliptohoriz:
    psuff='_horizor'+str(len(fields))+'b' # horizontal orientation
    # rows are fields and cols are sims
    if len(fields)==1: