Changeset 2281 in lmdz_wrf for trunk


Ignore:
Timestamp:
Jan 23, 2019, 9:02:40 PM (6 years ago)
Author:
lfita
Message:

Adding:

  • `ovar_reducedims': Function to reduce a variable removing some of its dimensions
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r2280 r2281  
    133133# operdim: Function to operate along a series of dimensions
    134134# ovar_onc: Function to copy an object variable to a nother netcdf object
     135# ovar_reducedims: Function to reduce a variable removing some of its dimensions
    135136# Partialmap_Entiremap: Function to transform from a partial global map (e.g.: only land points) to an entire one Coincidence of points is done throughout a first guess from fractions of the total domain of search
    136137# Partialmap_EntiremapFor: Function to transform from a partial global map (e.g.: only land points) to an entire one usinf Fortran code
     
    2769027691#area_weighted('yes:min,max,mean,stddev',fvals,'ct_values')
    2769127692
     27693def ovar_reducedims(ovar, dimns):
     27694    """ Function to reduce a variable removing some of its dimensions
     27695      ovar: Object variable to reduce
     27696      dimns: list of dimensions to remove from the variable
     27697    """
     27698    fname = 'ovar_reducedims'
     27699 
     27700    dimv = ovar.dimensions
     27701   
     27702    slicevar = []
     27703    dimvar = []
     27704    shapevar = []
     27705    iid = 0
     27706    for idn in dimv:
     27707        if gen.searchInlist(dimns,idn): slicevar.append(0)
     27708        else:
     27709            ldim = ovar.shape[iid]
     27710            slicevar.append(slice(0,ldim))
     27711            dimvar.append(idn)
     27712            shapevar.append(ldim)
     27713        iid = iid + 1
     27714
     27715    newvar = ovar[tuple(slicevar)]
     27716
     27717    return newvar, dimvar, shapevar
     27718
    2769227719def compute_slices_stats_areaweighted(values, ncfile, variable):
    2769327720    """ Function to compute stats of variables of a file splitting variables by
    2769427721        slices along sets of ranges for a series of variables weighting by the area
    2769527722        covered by each grid (defined as polygon) within the slice
    27696       values=[slicevarsinf]@[dimvars]@[slicestatsdim]
     27723      values=[slicevarsinf]@[dimvars]@[sliceremovedim]@[slicebndsdim]@[slicestatsdim]
    2769727724        [slicevarsinf] ';' separated list of [varn1],[minvar1],[maxvar1],
    2769827725          [slcevar1]; ...;[varnN],[minvarN],[maxvarN],[slcevarN]
     
    2770927736          be able to compute the area-weights or it will be assumed that dimension
    2771027737          has no extension
     27738        [sliceremovedim]: ',' list of dimensions to remove from the slicing variables
     27739          ('None' for any)
     27740        [slicebndsdim]: ',' [dimn]|[dimbnd] list of dimensions and their associated
     27741          bounds variables from the slicing variables ('None' for any)
    2771127742        [slicestatsdim]: ',' list of name of dimensions to do not use for computing
    2771227743          statistics of variables at each slice ('any' for not leaving any
     
    2772227753        quit()
    2772327754
    27724     expectargs = '[slicevarsinf]@[dimvars]@[slicestatsdim]'
     27755    expectargs = '[slicevarsinf]@[dimvars]@[sliceremovedim]@[slicebndsdim]@' +       \
     27756      '[slicestatsdim]'
    2772527757    gen.check_arguments(fname, values, expectargs, '@')
    2772627758
    2772727759    varvalues0 = values.split('@')[0]
    2772827760    dimvars0 = values.split('@')[1]
    27729     slicestatsdim = values.split('@')[2]
     27761    sliceremovedim = values.split('@')[2]
     27762    slicebndsdim0 = values.split('@')[2]
     27763    slicestatsdim = values.split('@')[4].split(',')
    2773027764
    2773127765    varvalues = varvalues0.split(';')
     27766
     27767    if sliceremovedim != 'None':
     27768        sliceremovedim = gen.str_list(sliceremovedim, ',')
     27769    else:
     27770        sliceremovdim = None
     27771    if slicebndsdim0 != 'None':
     27772        slicebndsdim0 = gen.str_list(slicebndsdim0, ',')
     27773        slicebndsdim = {}
     27774        for slcn in slicebndsdim0:
     27775            dn = slcn.split('|')[0]
     27776            bndn = slcn.split('|')[1]
     27777            slicebndsdim[dn] = bndn
     27778    else:
     27779        sliceremovdim = None
    2773227780
    2773327781    varvals = {}
     
    2777227820    # Dictionary with the result of slicing a dimension-variable with bounds
    2777327821    vardimbndslice = {}
     27822    # Dimension variables of 2D
     27823    dimvar2D = []
    2777427824
    2777527825    # Preparing slices and output file
     
    2780627856        slcvalsc = np.zeros((Nslices), dtype=np.float)
    2780727857        slcvals = np.zeros((Nslices,2), dtype=np.float)
    27808         varv = ovar[:]
     27858
     27859        # Removing undesired dimensions from slicing variable
     27860        if sliceremovedim is not None:
     27861            varv, rmdims, rmshape = ovar_reducedims(ovar, sliceremovedim)
     27862        else:
     27863            varv = ovar[:]
     27864            rmdims = dimnv
     27865            rmshape = list(ovar.shape)
     27866
    2780927867        for islc in range(Nslices):
    2781027868            slcvalsc[islc] = slices[islc]
     
    2781427872            #slcvar[islc,] = ma.masked_inside(varv, slcvals[islc,0], slcvals[islc,1]).mask
    2781527873            slcvar[islc,] = ma.masked_outside(varv, slcvals[islc,0], slcvals[islc,1]).mask
     27874            print islc, ':', slcvals[islc,:], '=', np.sum(~slcvar[islc,])
    2781627875
    2781727876        slicesinf[varn] = [Nslices, dimnv, slcvar, slcvalsc, slcvals]
     
    2784227901          'variable ' + varn, vu)
    2784327902
    27844         slcdims = ['slice_'+varn] + dimnv
    27845         slcshape = [Nslices] + list(ovar.shape)
     27903        slcdims = ['slice_'+varn] + rmdims
     27904        slcshape = [Nslices] + rmshape
    2784627905        slcv = np.zeros(tuple(slcshape), dtype=int)
    2784727906        for islc in range(Nslices):
     
    2785627915        # Looking for boundaries
    2785727916        varbnds = []
     27917#        dn = dimvars[varn]
    2785827918        dn = varn
    2785927919        vdarattrs = ovar.ncattrs()
     
    2786327923            boundsv = ovar.getncattr('bounds')
    2786427924            print '    ' + infmsg
    27865             print '    ' +fname+ ": slicing variable '" +dn+ "' with bounds !!"
     27925            print '    ' +fname+ ": slicing variable '"+varn+ "' with dimension '" + \
     27926              dn + "' bounds !!"
    2786627927            print '      bounds found:', boundsv
    2786727928            print '      getting them to retrieve the slices'
     
    2791727978                    dyget = 1
    2791827979
     27980                elif len(dv.shape) == 2:
     27981                    dimvar2D.append(dn)
     27982                    continue
     27983                # Issue with WRF's XLONG(time, sout_north, west_east) ....
    2791927984                else:
    2792027985                    print errormsg
    2792127986                    print '  '+fname+": rank ", dv.shape, " of slicing varibale '" + \
    2792227987                      dn + "' not ready !!"
    27923                     print '    function only works with 1D slicing variables'
     27988                    print '    function only works with 1D and 2D slicing variables'
    2792427989                    quit(-1)
    2792527990
     
    2795128016            print '    directly using grid point values'
    2795228017
     28018            #if len(varv.shape) > 1:
     28019            #    print errormsg
     28020            #    print '  ' + fname + ": wrong shape for slicing vriable '" + varn + "' !!"
     28021            #    print '    function only ready to slice 1D varables and it has:',        \
     28022            #      varv.shape
     28023            #    quit(-1)
     28024
    2795328025            Ngridsin = np.zeros((1,Nslices), dtype=int)           
    2795428026            for islc in range(Nslices):
     
    2796028032            for islc in range(Nslices):
    2796128033                unmasked = slcvar[islc,]
    27962                 indices = gen.multi_index_mat(unmasked,False)
     28034                unma = np.where(unmasked, 0., 1.)
     28035                unmat = unma.transpose()
     28036                if (len(unma.shape) == 1):
     28037                  indices = gen.multi_index_mat(unmat,1.)
     28038                  Nt = len(indices)
     28039                elif (len(unma.shape) == 2):
     28040                    drng = unma.shape[0]*unma.shape[1]
     28041                    Nt,indices=fsci.module_scientific.multi_index_mat2drk(d12=drng,  \
     28042                      mat=unmat, value=1., d1=unma.shape[1], d2=unma.shape[0])
     28043                elif (len(unma.shape) == 3):
     28044                    drng = unma.shape[0]*unma.shape[1]*unma.shape[2]
     28045                    Nt,indices=fsci.module_scientific.multi_index_mat3drk(d123=drng, \
     28046                      mat=unmat, value=1., d1=unma.shape[2], d2=unma.shape[1],       \
     28047                      d3=unma.shape[0])
     28048                elif (len(unma.shape) == 4):
     28049                    drng = unma.shape[0]*unma.shape[1]*unma.shape[2]*unma.shape[3]
     28050                    Nt,indices=fsci.module_scientific.multi_index_mat4drk(d1234=drng,\
     28051                      mat=unmat, value=1., d1=unma.shape[3], d2=unma.shape[2],       \
     28052                      d3=unma.shape[1], d4=unma.shape[0])
     28053                else:
     28054                  rS = str(len(unma.shape))
     28055                  print errormsg
     28056                  print '  ' + fname + ": 'multi_index_mat" + rS + "drk' not ready !!"
     28057                  quit(-1)
     28058
    2796328059                ainds = np.array(indices)
    2796428060                if Ngridsin[0,islc] > 0:
    27965                     gridsin[0,0:Ngridsin[0,islc],0,islc] = ainds[:,0]
    27966                     gridsin[1,0:Ngridsin[0,islc],0,islc] = ainds[:,1]
     28061                    gridsin[0,0:Ngridsin[0,islc],0,islc] = ainds[0,0:Nt]
     28062                    gridsin[1,0:Ngridsin[0,islc],0,islc] = ainds[1,0:Nt]
    2796728063                    percens[0:Ngridsin[0,islc],0,islc] = 1.
    2796828064
     
    2800228098                pnewvar[0:Ngridsin[j,i],i]= percens[0:Ngridsin[j,i],j,i]
    2800328099        onewnc.sync()
     28100
     28101#    # Slicing 2D dimension-variables
     28102#    if len(dimvar2D) != 0:
     28103#        ovar = onc.variables[varn]
     28104#        vu = ovar.units
     28105#        dimnv = list(ovar.dimensions)
     28106
     28107#        varbndns = []
     28108#        dimvals = {}
     28109#        dimslcs = {}
     28110#        for dn in dimnv:
     28111#            # Looking for boundaries
     28112#            varbnds = []
     28113#            dn = varn
     28114#            vdarattrs = ovar.ncattrs()
     28115#            dv = ovar[:]
     28116
     28117#            if gen.searchInlist(vdarattrs,'bounds'):
     28118#                boundsv = ovar.getncattr('bounds')
     28119#                print '    ' + infmsg
     28120#                print '    ' +fname+ ": slicing variable '" +dn+ "' with bounds !!"
     28121#                print '      bounds found:', boundsv
     28122#                print '      getting them to retrieve the slices'
     28123#                bndvarns = boundsv.replace(' ','').split(',')
     28124
     28125#                for vn in bndvarns:
     28126#                    if not gen.searchInlist(varbnds, vn): varbnds.append(vn)
     28127               
     28128#        # Slicing following boundaries
     28129#        if gen.searchInlist(slcvarns, dn) and not vardimbndslice.has_key(dn):
     28130#            print infmsg
     28131#            print '    ' + fname + ": slicing dimension '" + dn + "' ... "
     28132#            varslcv = slicesinf[dn]
     28133#            Nslices = varslcv[0]
     28134#            ovardims = varslcv[1]
     28135#            slcvar = varslcv[2]
     28136#            slcvalsc = varslcv[3]
     28137#            slcvals = varslcv[4]
     28138#            dimslcs[dn] = slcvals       
     28139
     28140#         if len(varbndns) != 0:
     28141#             for boundsv in varbnds:
     28142#                ovarbnds = onc.variables[boundsv]
     28143#                varbnds = ovarbnds[:]
     28144#                dimvals[
     28145
     28146
    2800428147
    2800528148    for varn in varns:
     
    2830628449    return
    2830728450
    28308 values='lon,286.,323.6,4.;lat,-63.,19.,4.;orog,250.,7000.,500.@time|time:lon|lon:lat|lat@time'
    28309 compute_slices_stats_areaweighted(values, '/media/lluis/ExtDiskC_ext3/DATA/estudios/Andes/DATA/concatenated/historical/tasmin/tasmin_Amon_ACCESS1-0_historical_r1i1p1_185001-200512_Andes_19600101000000-19900101000000.nc', 'tasmin')
     28451#values='lon,286.,323.6,4.;lat,-63.,19.,4.;orog,250.,7000.,500.@time|time:lon|lon:lat|lat@time'
     28452#compute_slices_stats_areaweighted(values, '/media/lluis/ExtDiskC_ext3/DATA/estudios/Andes/DATA/concatenated/historical/tasmin/tasmin_Amon_ACCESS1-0_historical_r1i1p1_185001-200512_Andes_19600101000000-19900101000000.nc', 'tasmin')
     28453values='XLONG,-74.,-36.4,4.;XLAT,-63.,19.,4.;HGT,250.,7000.,500.@Time|WRFtime:' +    \
     28454  'west_east|XLONG:south_north|XLAT@south_north|lat_bnds,west_east|lon_bnds@Time@Time'
     28455compute_slices_stats_areaweighted(values, '/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'T2')
    2831028456
    2831128457#quit()
Note: See TracChangeset for help on using the changeset viewer.