Exemplo n.º 1
0
def load_det_cape_cin(datadir, date, t, return_array=False):
    topdir = datadir + '/' + date + '/'
    gribfn = gribpref + t + precsuf
    detfn = topdir + 'det/' + gribfn
    capefobj = getfobj(detfn, fieldn='CAPE_ML_S')
    cinfobj = getfobj(detfn, fieldn='CIN_ML_S')
    # Minus one hour
    # gribfnm1 = gribpref + ddhhmmss(ddhhmmss_strtotime(t) -
    # timedelta(hours = 1)) + precsuf
    # detfnm1 = topdir + 'det/' + gribfnm1
    # detfobjm1 = getfobj(detfnm1, fieldn = 'TOT_PREC')
    # detfobj.data = detfobj.data - detfobjm1.data
    if return_array:
        return capefobj.data, cinfobj.data
    else:
        return capefobj, cinfobj
Exemplo n.º 2
0
def load_det_da(datadir, t, return_array=False):
    detfn = datadir + gribpref_da + t + precsuf_da + '.det'
    detfobj = getfobj(detfn, fieldn='TOT_PREC_S')
    if return_array:
        return detfobj.data
    else:
        return detfobj
Exemplo n.º 3
0
def load_det(datadir, date, t, return_array=False):
    topdir = datadir + '/' + date + '/'
    gribfn = gribpref + t + precsuf
    detfn = topdir + 'det/' + gribfn
    detfobj = getfobj(detfn, fieldn='PREC_PERHOUR')
    # Minus one hour
    # gribfnm1 = gribpref + ddhhmmss(ddhhmmss_strtotime(t) -
    # timedelta(hours = 1)) + precsuf
    # detfnm1 = topdir + 'det/' + gribfnm1
    # detfobjm1 = getfobj(detfnm1, fieldn = 'TOT_PREC')
    # detfobj.data = detfobj.data - detfobjm1.data
    if return_array:
        return detfobj.data
    else:
        return detfobj
Exemplo n.º 4
0
def _calc_cape(obj):
    """
    TODO
    make type of Cosmo file clever!
    """
    
    outint = 60
    HH = cu.derive.hl_to_fl(pwg.getfobj(obj.cfile, 'HH').data)
    #P0 = cosmo_ref_p(HH) / 100.   # hPa
    
    # Create new filelist
    newlist = []
    for trjfn in [obj.trjfiles[0]]:
        newfn = trjfn.rstrip('.nc') + '_CAPE' + '.nc'
        newlist.append(newfn)
        os.system('cp ' + trjfn + ' ' + newfn)
    
    for fn in [newlist[0]]:
        print 'Open file:', fn 
        rootgrp = nc.Dataset(fn, 'a')
        tarray = rootgrp.variables['time'][:]
        lonmat = rootgrp.variables['longitude'][:, :]
        latmat = rootgrp.variables['latitude'][:, :]
        pmat = rootgrp.variables['P'][:, :]
        tempmat = rootgrp.variables['T'][:, :]
        qvmat = rootgrp.variables['QV'][:, :]
        
        newcape = rootgrp.createVariable('CAPE', 'f4', ('time', 'id'))
        newcin = rootgrp.createVariable('CIN', 'f4', ('time', 'id'))
        
        # Retrieve trajectory start time
        trjstart = rootgrp.variables['time'][0] / 60   # In mins
        for t in range(tarray.shape[0]):
            # Only interpolate if outint
            if (rootgrp.variables['time'][t] / 60) % outint == 0:
                # Get COSMO Index
                icosmo = int((t * obj.dtrj + trjstart) / obj.dacosmo)
                print obj.afiles[icosmo]
                # Retrieve COSMO fields
                print 'get cosmo vars'
                T = pwg.getfobj(obj.afiles[icosmo], 'T')
                clons = T.rlons[0, :]
                clats = T.rlats[:, 0]
                TC = T.data - 273.15   # Convert to Celcius
                #try:
                PS = pwg.getfobj(obj.afiles[icosmo], 'PS').data / 100. # hPa
                #PP = pwg.getfobj(obj.afiles[icosmo], 'PP').data / 100.  # hPa
                #PS = P0 + PP
                print 'calc td'
                QV = pwg.getfobj(obj.afiles[icosmo], 'QV')
                e  = cu.thermodyn.MixR2VaporPress(QV.data, PS * 100.)
                TD = cu.thermodyn.DewPoint(e)    
                TD = np.nan_to_num(TD) # nan to zero
                TD = np.where(TD == 0., -150., TD)  # zero to -150 C   
                
                # Filter COSMO fields
                
                for itrj in range(lonmat.shape[1]):
                    print itrj
                    # Get parcel variables
                    lontrj = lonmat[t, itrj]
                    lattrj = latmat[t, itrj]
                    ptrj = pmat[t, itrj]
                    temptrj = tempmat[t, itrj] - 273.15
                    qvtrj = qvmat[t, itrj]
                    etrj = cu.thermodyn.MixR2VaporPress(qvtrj, ptrj * 100.)
                    tempdtrj = cu.thermodyn.DewPoint(etrj)
                    
                    # Get closest lat lon from cosmo
                    lonid = np.abs(clons - lontrj).argmin()
                    latid = np.abs(clats - lontrj).argmin()
                    
                    mydata = dict(zip(('hght','pres','temp','dwpt'),
                                      (HH[:, latid, lonid], 
                                       PS[:, latid, lonid],
                                       TC[:, latid, lonid], 
                                       TD[:, latid, lonid])))
                    

                    # Initialize sounding
                    S = SkewT.Sounding(soundingdata=mydata)
                    
                    # calculate CAPE and CIN
                    try:
                        trjparcel = (ptrj, temptrj, tempdtrj, 'parcel')
                        P_lcl, P_lfc, P_el, CAPE, CIN = S.get_cape(*trjparcel)
                    except AssertionError:
                        print ptrj, temptrj, tempdtrj
                        print mydata
                        x = breakbreak
                    #print mydata
                    print ptrj, temptrj, tempdtrj
                    print P_lcl, P_lfc, P_el, CAPE, CIN
                    
                    # Write new value
                    newcape[t, itrj] = CAPE
                    newcin[t, itrj] = CIN
                    
            else:
                newcape[t, :] = np.nan
                newcin[t, :] = np.nan
        rootgrp.close()
    return newlist
Exemplo n.º 5
0
def _interpolate_3d(obj, varname, outint = 60):
    """
    TODO
    """
    
    # Get rotated lon/lat and height fields for interpolation
    hhobj = pwg.getfobj(obj.cfile, 'HH')
    clons = hhobj.rlons[0, :]
    clats = hhobj.rlats[:, 0]
    chhfield = hhobj.data
    hlevhh = []
    
    # Use cu.derive.hl_to_fl
    for lev in range(chhfield.shape[0]-1):
        hlevhh.append((chhfield[lev] + chhfield[lev+1]) / 2)
    hlevhh = np.array(hlevhh)
    
    # Create new filelist
    newlist = []
    for trjfn in obj.trjfiles:
        newfn = trjfn.rstrip('.nc') + '_' + varname + '.nc'
        newlist.append(newfn)
        os.system('cp ' + trjfn + ' ' + newfn)
        
    # Iterate over trajectory files
    for fn in newlist:
        print 'Opening file:', fn
        
        # Open Trajectory file
        rootgrp = nc.Dataset(fn, 'a')
        
        # Read position matrices
        lon = rootgrp.variables['longitude'][:, :]
        lat = rootgrp.variables['latitude'][:, :]
        z = rootgrp.variables['z'][:, :]
        
        # Allocate new netCDF array
        newvar = rootgrp.createVariable(varname, 'f4', ('time', 'id'))
        
        # Retrieve trajectory start time
        trjstart = rootgrp.variables['time'][0] / 60   # In mins       
        
        # Iterate over trj times
        for itrj in range(lon.shape[0]):
            # Only interpolate if outint
            if (rootgrp.variables['time'][itrj] / 60) % outint == 0:
                
                # Get cosmo index
                icosmo = int((itrj * obj.dtrj + trjstart) / obj.dacosmo)
                print icosmo, itrj, rootgrp.variables['time'][itrj] / 60,obj.afiles[icosmo]
                field = pwg.getfield(obj.afiles[icosmo], varname)

                
                # Iterate over individual trajectories
                for trjid in range(lon.shape[1]):
                    # NOTE: Nearest Neighbor method!
                    ilon = lon[itrj, trjid]
                    ilat = lat[itrj, trjid]
                    iz = z[itrj, trjid]
                    
                    # Get nearest lat, lon
                    lonid = np.abs(clons - ilon).argmin()
                    latid = np.abs(clats - ilat).argmin()
                    
                    # Get closest vertical coordinate
                    zid = np.abs(hlevhh[:, latid, lonid] - iz).argmin()
                    # Get nearest neighbor 
                    newvar[itrj, trjid] = field[zid, latid, lonid]
            else:
                newvar[itrj, :] = np.nan
        
        # Clean up
        rootgrp.close()

    return newlist
Exemplo n.º 6
0
    'PSP_TL500': 'orange',
    'DA_REF': 'blue',
    'DA_REF_TL500': 'cyan',
    'DA_PSP_TL500': 'red',
    'DA_PSPv2_TL500': 'magenta',
    'DA_PSP': 'maroon',
}
expid_str = ''
for i, expid in enumerate(args.expid):
    expid_str += expid + '_'
    print 'Expid:', expid

    # Load precipitation
    print 'Load precipitation'
    precfn = datadir + expid + '/' + args.date + '/det/' + gribpref + t + precsuf
    precfobj = getfobj(precfn, fieldn='PREC_PERHOUR')

    maskfobj = deepcopy(precfobj)
    maskfobj.data = mask

    # Plot precipitation plus box
    print 'Plot precipitation'
    plt.sca(axmat1[0, i])
    cf, tmp = ax_contourf(
        axmat1[0, i],
        precfobj,
        Basemap_drawrivers=False,
        npars=0,
        nmers=0,
        colors=cmPrec,
        pllevels=levelsPrec,