Changeset 900 in lmdz_wrf


Ignore:
Timestamp:
Jun 19, 2016, 6:09:01 PM (9 years ago)
Author:
lfita
Message:

Adding `pinterp': Function to vertically interpolate using subroutines from the p_interp.F90 NCAR program

Location:
trunk/tools
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/module_ForInterpolate.F90

    r899 r900  
    923923
    924924
    925  SUBROUTINE interp (data_out, data_in, pres_field, interp_levels, psfc, ter, tk, qv, ix, iy, iz, it, &
    926                      num_metgrid_levels, LINLOG, extrapolate, GEOPT, MISSING)
     925 SUBROUTINE interp (data_in, pres_field, interp_levels, psfc, ter, tk, qv, LINLOG, extrapolate,      &
     926                     GEOPT, MISSING, data_out, ix, iy, iz, it, num_metgrid_levels)
    927927! Interpolation subroutine from the p_interp.F90 NCAR program
    928928!  Program to read wrfout data and interpolate to pressure levels
     
    930930!  November 2007 - Cindy Bruyere
    931931!
    932      INTEGER                                          :: ix, iy, iz, it
    933      INTEGER                                          :: num_metgrid_levels, LINLOG
    934      REAL, DIMENSION(ix, iy, num_metgrid_levels, it)  :: data_out
    935      REAL, DIMENSION(ix, iy, iz, it)                  :: data_in, pres_field, tk, qv
    936      REAL, DIMENSION(ix, iy, it)                      :: psfc
    937      REAL, DIMENSION(ix, iy)                          :: ter
    938      REAL, DIMENSION(num_metgrid_levels)              :: interp_levels
    939 
    940      INTEGER                                          :: i, j, itt, k, kk, kin
    941      REAL, DIMENSION(num_metgrid_levels)              :: data_out1D
    942      REAL, DIMENSION(iz)                              :: data_in1D, pres_field1D
    943      INTEGER                                          :: extrapolate
    944      REAL                                             :: MISSING
    945      REAL, DIMENSION(ix, iy, num_metgrid_levels, it)  :: N
    946      REAL                                             :: sumA, sumN, AVE_geopt
    947      LOGICAL                                          :: GEOPT
     932     INTEGER, INTENT(IN)                                 :: ix, iy, iz, it
     933     INTEGER, INTENT(IN)                                 :: num_metgrid_levels, LINLOG
     934     REAL, DIMENSION(ix,iy,iz,it), INTENT(IN)            :: data_in, pres_field, tk, qv
     935     REAL, DIMENSION(ix,iy,it), INTENT(IN)               :: psfc
     936     REAL, DIMENSION(ix,iy), INTENT(IN)                  :: ter
     937     REAL, DIMENSION(num_metgrid_levels), INTENT(IN)     :: interp_levels
     938     INTEGER, INTENT(IN)                                 :: extrapolate
     939     REAL, INTENT(IN)                                    :: MISSING
     940     LOGICAL, INTENT(IN)                                 :: GEOPT
     941     REAL, DIMENSION(ix,iy,num_metgrid_levels,it),                                                    &
     942       INTENT(OUT)                                       :: data_out
     943
     944! Local
     945     INTEGER                                             :: i, j, itt, k, kk, kin
     946     REAL, DIMENSION(num_metgrid_levels)                 :: data_out1D
     947     REAL, DIMENSION(iz)                                 :: data_in1D, pres_field1D
     948     REAL, DIMENSION(ix, iy, num_metgrid_levels, it)     :: N
     949     REAL                                                :: sumA, sumN, AVE_geopt
    948950
    949951!!!!!!! Variables
     
    11721174 END SUBROUTINE int1D
    11731175
     1176 FUNCTION virtual (tmp,rmix)
     1177!      This function returns virtual temperature in K, given temperature
     1178!      in K and mixing ratio in kg/kg.
     1179
     1180     real                              :: tmp, rmix, virtual
     1181
     1182     virtual=tmp*(0.622+rmix)/(0.622*(1.+rmix))
     1183
     1184 END FUNCTION virtual
     1185
    11741186END MODULE module_ForInterpolate
  • trunk/tools/nc_var.py

    r870 r900  
    4141  'ncreplace', 'ncstepdiff', 'netcdf_concatenation', 'netcdf_fold_concatenation',    \
    4242  'Partialmap_Entiremap', 'Partialmap_EntiremapFor', 'Partialmap_EntiremapForExact', \
    43   'remapnn',                                                                         \
     43  'pinterp', 'remapnn',                                                              \
    4444  'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'selvar', 'setvar_asciivalues',     \
    4545  'sorttimesmat', 'spacemean', 'SpatialWeightedMean', 'statcompare_files',           \
     
    218218elif oper == 'opersvarsfiles':
    219219    ncvar.compute_opersvarsfiles(opts.values, opts.varname)
     220elif oper == 'pinterp':
     221    ncvar.pinterp(opts.values, opts.ncfile, opts.varname)
    220222elif oper == 'remapnn':
    221223    ncvar.remapnn(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r897 r900  
    8181# Partialmap_EntiremapFor: Function to transform from a partial global map (e.g.: only land points) to an entire one usinf Fortran code
    8282# Partialmap_EntiremapForExact: Function to transform from a partial global map (e.g.: only land points) to an entire one using Fortran code with exact location
     83# pinterp: Function to vertically interpolate using subroutines from the p_interp.F90 NCAR program
    8384# put_variable_slice: Function to add a variable from a netcdf object to a new one following a slice
    8485# remapnn: Function to remap to the nearest neightbor a variable using projection from another file
     
    1579315794    return
    1579415795
     15796def pinterp(values, ncfile, variables):
     15797    """ Function to vertically interpolate using subroutines from the p_interp.F90 NCAR program
     15798      Using fortran codes: module_generic.F90
     15799      foudre: f2py -m module_ForInterpolate --f90exec=/usr/bin/gfortran-4.7 -c module_generic.F90 module_ForInterpolate.F90  >& run_f2py.log
     15800      ciclad: f2py --f90flags="-fPIC" -L/opt/canopy-1.3.0/Canopy_64bit/System/lib/ -L/usr/lib64/ -L/opt/canopy-1.3.0/Canopy_64bit/System/lib/ -m module_ForInterpolate -c module_generic.F90 module_ForInterpolate.F90
     15801      values= [interplevs],[linloginterp],[extrap]
     15802        [interplevs]: ':' separated list of pressure values to interpolate [hPa] (decreassing in hPa)
     15803        [linloginterp]: kind of linear interpolation
     15804          1: linear interp in pressure
     15805          2: linear interp in ln(pressure)
     15806        [extrap]: whether to set to missing value below/above model ground and top (0), or extrapolate (1)
     15807      ncfile= WRF file to use
     15808      variables = ',' separated list of names of variables to interpolate ('all', fo all 4D-atmospheric variables)
     15809        'WRFght': for WRF geopotential height
     15810        'WRFrh': for WRF relative humidity
     15811        'WRFt': for WRF temperature
     15812    """
     15813    import module_ForInterpolate as fin
     15814    fname = 'pinterp'
     15815
     15816    if values == 'h':
     15817        print fname + '_____________________________________________________________'
     15818        print pinterp.__doc__
     15819        quit()
     15820
     15821    arguments = '[interplevs],[linloginterp],[extrap]'
     15822    gen.check_arguments(fname, values, arguments, ',')
     15823
     15824    interplevs = np.array(values.split(',')[0].split(':'), dtype=np.float64)
     15825    linloginterp = np.int32(values.split(',')[1])
     15826    extrap = np.int32(values.split(',')[2])
     15827
     15828    ofile = 'pinterp.nc'
     15829
     15830    onc = NetCDFFile(ncfile, 'r')
     15831
     15832    # Variables to interpolate
     15833    WRFdims = ['Time', 'bottom_top', 'south_north', 'west_east']
     15834    newWRFdims = ['Time', 'pres', 'south_north', 'west_east']
     15835    notCHK = ['WRFght', 'WRFt', 'WRFrh']
     15836
     15837    varns = gen.str_list(variables, ',')
     15838    if variables == 'all':
     15839        varns = []
     15840        for vn in onc.variables:
     15841            ovn = onc.variables[vn]
     15842            coincdims = set(WRFdims) & set(ovn.dimensions)
     15843           
     15844            if len(WRFdims) == len(ovn.dimensions) and len(coincdims) == len(WRFdims):
     15845                varns.append(vn)
     15846        varns = varns + notCHK
     15847       
     15848    for vn in varns:
     15849        if not gen.searchInlist(onc.variables, vn) and                               \
     15850          not gen.searchInlist(notCHK, vn):
     15851            print errormsg
     15852            print '  ' + fname + "': WRF file '" + ncfile +                          \
     15853              "' does not have variable '" + vn + "' !!"
     15854            quit(-1)
     15855
     15856    # looking for WRF required variables
     15857    WRFvarrequired = ['P', 'PB', 'PSFC', 'PH', 'PHB', 'HGT', 'T', 'QVAPOR', 'XLONG', \
     15858      'XLAT', 'Times' , 'P_TOP']
     15859    for var in WRFvarrequired:
     15860        if not gen.searchInlist(onc.variables, var):
     15861            print errormsg
     15862            print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +\
     15863              var + "' !!"
     15864            quit(-1)
     15865
     15866# Computing necessary variables
     15867    # pressure
     15868    ovar1 = onc.variables['P']
     15869    ovar2 = onc.variables['PB']
     15870
     15871    pres = (ovar1[:] + ovar2[:]).astype('float64')
     15872
     15873    dimx = pres.shape[3]
     15874    dimy = pres.shape[2]
     15875    dimz = pres.shape[1]
     15876    dimt = pres.shape[0]
     15877
     15878    # sfc pressure
     15879    ovar1 = onc.variables['PSFC']
     15880    psfc = ovar1[:].astype('float64')
     15881
     15882    # geopotential height
     15883    ovar1 = onc.variables['PH']
     15884    ovar2 = onc.variables['PHB']
     15885    geop0 = ovar1[:] + ovar2[:]
     15886    unstg = list(geop0.shape)
     15887    unstg[1] = unstg[1] - 1
     15888    geop = np.zeros(tuple(unstg), dtype=np.float)
     15889    geop = 0.5*(geop0[:,1:dimz,:,:] + geop0[:,0:dimz-1,:,:]).astype('float64')
     15890
     15891    # terrain height
     15892    ovar1 = onc.variables['HGT']
     15893    hgt = ovar1[0,:,:].astype('float64')
     15894
     15895    # water vapour micing ratio
     15896    ovar1 = onc.variables['QVAPOR']
     15897    qv = ovar1[:].astype('float64')
     15898
     15899    # temperature
     15900    Rd = 287.04
     15901    Cp = 7.*Rd/2.
     15902    RCP = Rd/Cp
     15903    p0 = 100000.
     15904    ovar1 = onc.variables['T']
     15905    temp = ((ovar1[:]+300.)*(pres[:]/p0)**RCP).astype('float64')
     15906
     15907    onewnc = NetCDFFile(ofile, 'w')
     15908# Creation of dimensions
     15909    newdim = onewnc.createDimension('west_east', dimx)
     15910    newdim = onewnc.createDimension('south_north', dimy)
     15911    newdim = onewnc.createDimension('pres', len(interplevs))
     15912    newdim = onewnc.createDimension('Time', None)
     15913
     15914# Creation of variable dimensions
     15915    WRFvardims = ['XLONG', 'XLAT', 'Times']
     15916    for var in WRFvardims:
     15917        ovar = onc.variables[var]
     15918        varinf = variable_inf(ovar)
     15919        for vd in varinf.dimns:
     15920            if not gen.searchInlist(onewnc.dimensions, vd):
     15921                newdim = onewnc.createDimension(vd, len(onc.dimensions[vd]))
     15922        newvar = onewnc.createVariable(var, nctype(varinf.dtype),                    \
     15923          tuple(varinf.dimns))
     15924        newvar[:] = ovar[:]
     15925        for attrn in ovar.ncattrs():
     15926            attrv = ovar.getncattr(attrn)
     15927            attr = set_attribute(newvar, attrn, attrv)   
     15928
     15929    # Creation of pressure variable dimension
     15930    newvar = onewnc.createVariable('pres', 'f8', ('pres'))
     15931    newvar[:] = interplevs * 100.
     15932    basicvardef(newvar, 'pressure', 'Pressure', 'Pa')
     15933    attr = set_attribute(newvar, 'positive', 'down')
     15934    attr = set_attribute(newvar, 'axis', 'Z')
     15935
     15936    print '  ' + fname + ' interpolating at pressure levels _______'
     15937    print '     ', interplevs
     15938    for vn in varns:
     15939        print '  ' + fname + ": interpolaion of '" + vn + "' ..."
     15940        newvarattr = {}
     15941        varin = None
     15942
     15943        if gen.searchInlist(notCHK, vn):
     15944            if vn == 'WRFght':
     15945                varin = geop
     15946                isgeopt = True
     15947                varattrs = gen.variables_values('WRFght')
     15948                CFvn = varattrs[0]
     15949                newvarattr['standard_name'] = varattrs[1]
     15950                newvarattr['long_name'] = varattrs[4].replace('|',' ')
     15951                newvarattr['units'] = varattrs[5]
     15952            elif vn == 'WRFrh':
     15953                # relative humidity
     15954                ovar1 = 10.*0.6112*exp(17.67*(temp-273.16)/(temp-29.65))
     15955                ovar2 = 0.622*ovar1/(0.01*pres-(1.-0.622)*ovar1)
     15956                varin = 100.*qv/ovar2
     15957                isgeop = False
     15958                varattrs = gen.variables_values('WRFrh')
     15959                CFvn = varattrs[0]
     15960                newvarattr['standard_name'] = varattrs[1]
     15961                newvarattr['long_name'] = varattrs[4].replace('|',' ')
     15962                newvarattr['units'] = varattrs[5]
     15963            elif vn == 'WRFt':
     15964                varin = temp
     15965                isgeop = False
     15966                varattrs = gen.variables_values('WRFt')
     15967                CFvn = varattrs[0]
     15968                newvarattr['standard_name'] = varattrs[1]
     15969                newvarattr['long_name'] = varattrs[4].replace('|',' ')
     15970                newvarattr['units'] = varattrs[5]
     15971        elif not gen.searchInlist(WRFvarrequired, vn) or vn == 'QVAPOR':
     15972            ovarin = onc.variables[vn]
     15973            varinf = variable_inf(ovarin)
     15974            varin = ovarin[:]
     15975            isgeop = False
     15976            varattrs = gen.variables_values(vn)
     15977            CFvn = varattrs[0]
     15978            newvarattr['standard_name'] = varattrs[1]
     15979            newvarattr['long_name'] = varattrs[4].replace('|',' ')
     15980            newvarattr['units'] = varattrs[5]
     15981            for attrn in ovarin.ncattrs():
     15982                attrv = ovarin.getncattr(attrn)
     15983                newvarattr[attrn] = attrv
     15984
     15985        if varin is not None:
     15986            varint = varin.transpose()
     15987            prest = pres.transpose()
     15988            psfct = psfc.transpose()
     15989            hgtt = hgt.transpose()
     15990            tempt = temp.transpose()
     15991            qvt = qv.transpose()
     15992            varinterp = fin.module_forinterpolate.interp( data_in=varint,            \
     15993              pres_field=prest, interp_levels=interplevs, psfc=psfct,                \
     15994              ter=hgtt, tk=tempt, qv=qvt, linlog=linloginterp,                       \
     15995              extrapolate=extrap, geopt=isgeop, missing=gen.fillValueF)
     15996
     15997            newvar = onewnc.createVariable(CFvn, 'f4', tuple(newWRFdims),            \
     15998              fill_value=gen.fillValueF)
     15999            newvar[:] = varinterp.transpose()
     16000
     16001            for attrn in newvarattr.keys():
     16002                attr = set_attribute(newvar, attrn, newvarattr[attrn])
     16003            onewnc.sync()
     16004
     16005    # Global attributes
     16006
     16007    onewnc.setncattr('author', 'L. Fita')
     16008    newattr = set_attributek(onewnc, 'institution', unicode('Laboratoire de M' +     \
     16009      unichr(233) + 't' + unichr(233) + 'orologie Dynamique'), 'U')
     16010    onewnc.setncattr('university', 'Pierre Marie Curie - Jussieu')
     16011    onewnc.setncattr('center', 'Centre National de Recherches Scientifiques')
     16012    onewnc.setncattr('city', 'Paris')
     16013    onewnc.setncattr('country', 'France')
     16014    onewnc.setncattr('script', 'nc_var_tools.py')
     16015    onewnc.setncattr('function', 'pinterp')
     16016    onewnc.setncattr('version', '1.0')
     16017    onewnc.setncattr('oringal', 'Interpolation using p_interp.F90 subroutines')
     16018    newattr = set_atributek(onewnc, 'original_subroutines_author', unicode('Cindy ' +\
     16019      'Bruy' + unichr(232) + 're'), 'U')
     16020    onewnc.setncattr('original_subroutines_date', 'November 2007')
     16021
     16022    for attrn in onc.ncattrs():
     16023        attrv = onc.getncattr(attrn)
     16024        attr = set_attribute(onewnc, attrn, attrv)   
     16025
     16026    onewnc.sync()
     16027    onewnc.close()
     16028
     16029    print fname + ": successfull written of '" + ofile + "' !!"
     16030
     16031    return
     16032
    1579516033#quit()
Note: See TracChangeset for help on using the changeset viewer.