Changeset 1181 in lmdz_wrf for trunk


Ignore:
Timestamp:
Oct 12, 2016, 11:49:16 AM (9 years ago)
Author:
lfita
Message:

Adding `field_stats_dim': Function to retrieve statistics from a field along dimensions

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r1179 r1181  
    2121## e.g. # nc_var.py -o pinterp -f /media/ExtDiskC_ext4/DATA/etudes/WRF_LMDZ/WaquaL_highres/short_copies/LMDZ/AR40/histins_19790101000000-19790304000000_short.nc -S 100000.:97500.:95000.:92500.:90000.:85000.:80000.:75000.:70000.:65000.:60000.:55000.:50000.:45000.:40000.:35000.:30000.:25000.:20000.:15000.:10000.:5000.:2500.:1000.:500.:250.,1,0 -v temp,ovap
    2222## e.g. # nc_var.py -o reproject -f analysis/LMDZ/AR40/hurs_histins.nc -S 'lon,lat,analysis/WRF/current/hurs_wrfout.nc,lon,lat,npp,time@time' -v hurs
     23## e.g. # nc_var.py -o field_stats_dim -f /home/lluis/PY/wrfout_d01_2001-11-11_00:00:00 -S 'full,None,None,west_east,XLONG,False' -v 'T2'
    2324
    2425from optparse import OptionParser
     
    4041  'dimToUnlimited', 'dimVar_creation',                                               \
    4142  'fattradd',                                                                        \
    42   'fdimadd', 'fgaddattr', 'field_stats', 'file_creation', 'file_oper_alongdims',     \
    43   'filter_2dim',                                                                     \
     43  'fdimadd', 'fgaddattr', 'field_stats', 'field_stats_dim', 'file_creation',         \
     44  'file_oper_alongdims', 'filter_2dim',                                              \
    4445  'flipdim', 'fvaradd', 'gaddattrk', 'gaddattr', 'get_attribute',                    \
    4546  'get_namelist_vars', 'get_Variables',                                              \
     
    177178elif oper == 'field_stats':
    178179    ncvar.field_stats(opts.values, opts.ncfile, opts.varname)
     180elif oper == 'field_stats_dim':
     181    ncvar.field_stats_dim(opts.values, opts.ncfile, opts.varname)
    179182elif oper == 'filter_2dim':
    180183    ncvar.filter_2dim(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r1180 r1181  
    4444# fdimadd: Adding dimension from another reference file
    4545# field_stats: Function to retrieve statistics from a field
     46# field_stats_dim: Function to retrieve statistics from a field along dimensions
    4647# file_creation: Operation to create a file with one variable with a given set of dimensions
    4748# file_oper_alongdims: Function to operate a file along different dimensions of a variable
     
    228229    return
    229230
     231def add_dims(oc,nc,dnames):
     232    """ Function to add dimensions from a given netCDF object to another one
     233      oc: source netcdfile object
     234      nc: netcdfile object to add dimensions
     235      dnames: list of name of dimensions to add
     236    """
     237    fname = 'add_dims'
     238
     239    for dn in dnames:
     240        print '  ' + fname + ': adding dim:',dn,' ...'
     241        if oc.dimensions[dn].isunlimited():
     242            newdim = nc.createDimension(dn, None)
     243        else:
     244            newdim = nc.createDimension(dn, len(oc.dimensions[dn]))
     245
     246    nc.sync()
     247
     248    return
     249
     250def add_vars(oc,nc,vnames):
     251    """ Function to add variables from a given netCDF object to another one
     252      oc: source netcdfile object
     253      nc: netcdfile object to add dimensions
     254      vnames: list of name of variables to add
     255    """
     256    fname = 'add_vars'
     257
     258    for vn in vnames:
     259        if not gen.searchInlist(nc.variables,vn):
     260            print '  ' + fname + ': adding var:',vn,' ...'
     261
     262            varo = oc.variables[vn]
     263            vartype = varo.dtype
     264            vardims = varo.dimensions
     265            varattrs = varo.ncattrs()
     266
     267            for vdn in vardims:
     268                if not gen.searchInlist(nc.dimensions,vdn):
     269                    print warnmsg
     270                    print '  ' + fname + ": adding dimension '" + vdn +              \
     271                      "' from variable '" + vdn + "' which is not in file !!"
     272                    add_dims(oc,nc,[vdn])
     273
     274            if gen.searchInlist(varattrs,'_FillValue'):
     275                newvar = nc.createVariable(vn, vartype, vardims,                     \
     276                  fill_value=varo.getncattr('_FillValue'))
     277            else:
     278                newvar = nc.createVariable(vn, vartype, vardims)
     279
     280            for attrn in varattrs:
     281                attrv = varo.getncattr(attrn)
     282                newattr = set_attribute(newvar, attrn, attrv)
     283
     284            newvar[:] = varo[:]
     285
     286        nc.sync()
     287
     288    return
     289
     290def add_globattrs(oc,nc,attrns):
     291    """ Function to add global attributes from a given netCDF object to another one
     292      oc: source netcdfile object
     293      nc: netcdfile object to add dimensions
     294      vnames: list of name of dimensions to add ('all', for all attributes)
     295    """
     296    fname = 'add_globattrs'
     297
     298    allfattrs = oc.ncattrs()
     299
     300    if attrns == 'all':
     301        fattrns = allfattrs
     302    else:
     303        fattrns = attrns
     304
     305    for an in fattrns:
     306        if not gen.searchInlist(allfattrs,an):
     307            print errormsg
     308            print '  ' + fname + ": file has not global attribute '" + an + "' !!"
     309            quit(-1)
     310
     311        print '  ' + fname + ': adding attr:',an,' ...'
     312       
     313        av = oc.getncattr(an)
     314        newattr = set_attribute(nc, an, av)
     315
     316    nc.sync()
     317
     318    return
     319
    230320def valmod(values, ncfile, varn):
    231321    """ Function to modify the value of a variable
     
    59686058                    varslice.append(slice(0,Ldim))
    59696059                    vardims.append(dimname)
    5970                 print fname + ';Lluis dimname:', dimname,'dimslices:',dimslices[dimname]
    5971 
    5972             print fname + '; Lluis coinc:', coinc
    5973             print fname + ' Lluis; shapes varvals:', varvals, 'varobj:', varobj.shape,'varslice:',varslice
    59746060            varvals = varobj[tuple(varslice)]
    59756061
     
    62696355            else:
    62706356                varslice.append(slice(0,len(objfile.dimensions[dimn])))
    6271                 print fname + '; Lluis here! dimn', dimn
    62726357
    62736358        if varinf.FillValue is not None:
     
    62786363
    62796364        if dimx != dimy:
    6280             print fname + '; Lluis; varslice:', varslice,'shape newvar:', newvar.shape
    62816365            newvar[:] = varobj[tuple(varslice)]
    62826366        else:
     
    63116395    for atrn in objfile.ncattrs():
    63126396        attrv = objfile.getncattr(atrn)
    6313         print fname + '; Lluis attrn, attrv, type:', atrn, attrv, type(attrv)
    63146397        newattr = set_attributek(newncobj, atrn, attrv, type(attrv))
    63156398
     
    1082210905                convals = [int(0)]
    1082310906                convalsS = ''
    10824                 print fname + '; Lluis here convals:', convals
    1082510907            statsvariable[vn] = [minv, maxv, meanv, mean2v, varv, convals[0]]
    1082610908        else:
     
    1084310925
    1084410926#field_stats('full', 'geo_em.d01.nc', 'HGT_M')
     10927
     10928def field_stats_dim(values, ncfile, varn):
     10929    """ Function to retrieve statistics from a field along dimensions
     10930    field_stats_dim(values, ncfile, varn)
     10931      [values]= [stats],[fillVals],[dimns],[vardims],[stdout]
     10932        [stats]: kind of statistics
     10933          'full': all statistics given variable (min, max, mean, mean2, variability, [countVals])
     10934        [fillVals]: ':' list of _fillValues ('None' for any)
     10935        [countVals]: ':' list of Values@cond to use to count conditions ('None' for any)
     10936        [dims]: ':', list of names of the dimension along which statistics is required
     10937        [vardims]: ':', list of names of the variable with the values for the dimension along which statistics is required
     10938        [stdout]: Whether should be printed in standard output the results ('True'/'False')
     10939      [ncfile]= name of the netCDF file to use
     10940      [varn]= variable name to use ('all' for all variables)
     10941    """
     10942    import numpy.ma as ma
     10943    fname='field_stats_dim'
     10944
     10945    if values == 'h':
     10946        print fname + '_____________________________________________________________'
     10947        print field_stats_dim.__doc__
     10948        quit()
     10949
     10950    Lstr = 100
     10951    fullstats = ['min', 'max', 'mean', 'mean2', 'variability']
     10952
     10953    arguments = '[stats],[fillVals],[coutnVals],[dims],[vardims],[stdout]'
     10954    gen.check_arguments(fname,values,arguments,',')
     10955
     10956    ofile = fname + '.nc'
     10957
     10958    stats=values.split(',')[0]
     10959    fillVals=values.split(',')[1]
     10960    countVals=values.split(',')[2]
     10961    dims=gen.str_list(values.split(',')[3],':')
     10962    vardims=gen.str_list(values.split(',')[4],':')
     10963    stdout=gen.Str_Bool(values.split(',')[5])
     10964
     10965# Fill Values
     10966    if fillVals == 'None':
     10967        fillV = None
     10968    else:
     10969        if fillVals.find(':') != -1:
     10970            fillV = fillVals.split(':')
     10971            NfillV = len(fillV)
     10972        else:
     10973            fillV = [fillVals]
     10974            NfillV = 1
     10975
     10976    # Statistics
     10977    if stats == 'full':
     10978        statns = fullstats
     10979    else:
     10980        print errormsg
     10981        print '  ' + fname + ": kind of statistics '" + stats + "' not ready!!"
     10982        print '    valid statistics: full'
     10983        quit(-1)
     10984
     10985# Count Values
     10986    if countVals == 'None':
     10987        countV = None
     10988        NcountV = 0
     10989    else:
     10990        if countVals.find(':') != -1:
     10991            countV = countVals.split(':')
     10992            NcountV = len(countV)
     10993            for cV in countV:
     10994                statns = statns.append('count_' + str(cV))
     10995        else:
     10996            countV = [countVals]
     10997            NcountV = 1
     10998            statns = statns.append('count_' + str(countV))
     10999
     11000    Nstats = len(statns)
     11001
     11002    ncobj = NetCDFFile(ncfile, 'r')
     11003    for dim in dims:
     11004        if not gen.searchInlist(ncobj.dimensions.keys(), dim):
     11005            print errormsg
     11006            print '  ' +fname+ ": file '" + ncfile + "' does not have dimension '" + \
     11007              dim + "' !!"
     11008            quit(-1)
     11009    for vardim in vardims:
     11010        if not gen.searchInlist(ncobj.variables.keys(), vardim):
     11011            print errormsg
     11012            print '  ' + fname + ": file '" + ncfile + "' does not have variable-" + \
     11013              "dimension '" + vardim + "' !!"
     11014            quit(-1)
     11015
     11016    if varn == 'all':
     11017        varstats = list(ncobj.variables)
     11018    else:
     11019        varstats = [varn]
     11020
     11021    # File creation
     11022    onewnc = NetCDFFile(ofile, 'w')
     11023
     11024    # Dimensions
     11025    stdims = {}
     11026    rundims = []
     11027    runndims = []
     11028    dimslice = {}
     11029    for dim in dims:
     11030        add_dims(ncobj,onewnc,[dim])
     11031        stdims[dim] = len(ncobj.dimensions[dim])
     11032        runndims.append(dim)
     11033        rundims.append(stdims[dim])
     11034        dimslice[dim] = 0
     11035    onewnc.createDimension('stats',Nstats)
     11036    onewnc.createDimension('Lstring',Lstr)
     11037
     11038    # Dimension variables
     11039    add_vars(ncobj,onewnc,vardims)
     11040
     11041    # Statistics var
     11042    newvar = onewnc.createVariable('stats','c',('stats','Lstring'))
     11043    vardef = basicvardef(newvar, 'stats', 'statistics along running dimensions','-')
     11044    newvals = writing_str_nc(newvar, statns, Lstr)
     11045    onewnc.sync()
     11046
     11047    for vn in varstats:
     11048        statsvariable = {}
     11049        Ntotrun = 1
     11050        if stdout:
     11051            print '  ' + fname + " file: '" + ncfile + "'..."
     11052            print '  ' + fname + '______ ______ _____ ____ ___ __ _'
     11053        for vn in varstats:
     11054            if not ncobj.variables.has_key(vn):
     11055                print errormsg
     11056                print '  ' + fname + ": file do not have variable '" + vn + "' !!"
     11057                quit(-1)
     11058   
     11059        objfield = ncobj.variables[vn]
     11060
     11061        dtype = objfield.dtype
     11062        # Dimensions to run along
     11063        runvdimns = []
     11064        runvLdims = []
     11065        for vdn in objfield.dimensions:
     11066            if gen.searchInlist(runndims,vdn):
     11067                Ntotrun = Ntotrun * stdims[vdn]
     11068                runvdimns.append(vdn)
     11069                runvLdims.append(stdims[vdn])
     11070        statsresults = np.zeros(tuple([Nstats] + runvLdims), dtype=np.float)
     11071        if len(runvLdims) == 0:
     11072            print warnmsg
     11073            print '  ' + fname + ': variable without running dimension!'
     11074            print '    computing statistics for the whole variable'
     11075            Ntotrun = 1
     11076
     11077        for idd in range(Ntotrun):
     11078            # Getting variable slice at this iteration
     11079            if len(runvLdims) > 0:
     11080                slicedims = gen.index_flatten_mat(idd,runvLdims)
     11081            else:
     11082                slicedims = []
     11083            slicevar = []
     11084            for vdn in objfield.dimensions:
     11085                runfound = False
     11086                Srundim = ''
     11087                for irvdn in range(len(runvdimns)):
     11088                    if vdn == runvdimns[irvdn]:
     11089                        slicevar.append(slicedims[irvdn])
     11090                        runfound = True
     11091                        Srundim = Srundim + vdn + ': ' + str(slicedims[irvdn]) + ' '
     11092                        break
     11093                if not runfound:
     11094                    slicevar.append(slice(0,len(ncobj.dimensions[vdn])))
     11095           
     11096            # Getting field values
     11097            field = objfield[tuple(slicevar)]
     11098           
     11099            # Computing statistics
     11100            counts = []
     11101            if countV is not None:
     11102                for icV in range(NcountV):
     11103                    cV = countV[icV].split('@')[0]
     11104                    cC = countV[icV].split('@')[1]
     11105                    countval = gen.retype(cV, dtype)
     11106                    counts.append([gen.count_cond(field, countval, cC), cC, countval])
     11107
     11108            if fillV is not None:
     11109                for ifV in range(NfillV):
     11110                    fillval = gen.retype(fillV[ifV], dtype)
     11111                    field = ma.masked_equal(field, fillval)
     11112
     11113            if stdout:
     11114                print '   ' + vn + '[' + Srundim + ']... .. .'
     11115            if stats == 'full':
     11116                minv = np.min(field)
     11117                maxv = np.max(field)
     11118                meanv = np.mean(field)
     11119                mean2v = np.mean(field*field)
     11120                varv = np.sqrt(mean2v - meanv*meanv)
     11121
     11122                if stdout:
     11123                    print '    Fstats shape:',field.shape
     11124                    print '    Fstats min:', minv
     11125                    print '    Fstats max:', maxv
     11126                    print '    Fstats mean:', meanv
     11127                    print '    Fstats mean2:', mean2v
     11128                    print '    Fstats variability:', varv
     11129
     11130                if countV is not None:
     11131                    for icV in range(NcountV):
     11132                        convals = counts[icV]
     11133                        if stdout:
     11134                            print "    Fstats N values '" + convals[1] + "'",        \
     11135                              convals[2], ':', convals[0]
     11136                        contvalsS = 'count(', + convals[1] + ',',convals[2],')'
     11137                else:
     11138                    convals = [int(0)]
     11139                    convalsS = ''
     11140                statsvariable[vn] = [minv, maxv, meanv, mean2v, varv, convals[0]]
     11141                if countV is not None:
     11142                    statsresults[tuple([slice(0,Nstats)]+list(slicedims))] = [minv,  \
     11143                      maxv, meanv, mean2v, varv, convals[0]]
     11144                else:
     11145                    statsresults[tuple([slice(0,Nstats)]+list(slicedims))] = [minv,  \
     11146                      maxv, meanv, mean2v, varv]
     11147
     11148            else:
     11149                print errormsg
     11150                print '  ' + fname + ": kind of statistics '" + stats + "' not ready!!"
     11151                print '    valid statistics: full'
     11152                quit(-1)
     11153
     11154            Sm = 'MAT:  '
     11155            if stdout:
     11156                print '  '
     11157                print Sm + 'Matrix of the statisitcs _______'
     11158                print Sm + ' '.join('{:<15}'.format(vn) for vn in statns)
     11159                for key in statsvariable.keys():
     11160                    vals = statsvariable[key]
     11161                    print Sm+'{:<15}'.format(key)+' '+' '.join('{:<15g}'.format(v) for v in vals)
     11162
     11163        newvar = onewnc.createVariable(vn + '_stats', 'f4', tuple(['stats'] +        \
     11164          runvdimns))
     11165        newvar[:] = statsresults[:]
     11166        for attrn in objfield.ncattrs():
     11167            attrv = objfield.getncattr(attrn)
     11168            newattr = set_attribute(newvar,attrn,attrv)
     11169        newattr = set_attribute(newvar,'running_stats',', '.join(runvdimns))
     11170        onewnc.sync()
     11171
     11172    # Global attributes
     11173    add_globattrs(ncobj,onewnc,'all')
     11174    onewnc.sync()
     11175
     11176    ncobj.close()
     11177    onewnc.close()
     11178
     11179    print fname + ": successfull written of file '" + ofile + "' !!"
     11180
     11181    return
     11182
     11183#field_stats_dim('full,None,None,west_east,XLONG,False', '/home/lluis/PY/wrfout_d01_2001-11-11_00:00:00', 'T2')
    1084511184
    1084611185def filter_2dim(values, ncfile, varn):
     
    1175812097
    1175912098#changevartype('i', 'test.nc', 'var')
    11760 
    11761 def add_dims(oc,nc,dnames):
    11762     """ Function to add dimensions from a given netCDF object to another one
    11763       oc: source netcdfile object
    11764       nc: netcdfile object to add dimensions
    11765       dnames: list of name of dimensions to add
    11766     """
    11767     fname = 'add_dims'
    11768 
    11769     for dn in dnames:
    11770         print '  ' + fname + ': adding dim:',dn,' ...'
    11771         if oc.dimensions[dn].isunlimited():
    11772             newdim = nc.createDimension(dn, None)
    11773         else:
    11774             newdim = nc.createDimension(dn, len(oc.dimensions[dn]))
    11775 
    11776     nc.sync()
    11777 
    11778     return
    11779 
    11780 def add_vars(oc,nc,vnames):
    11781     """ Function to add variables from a given netCDF object to another one
    11782       oc: source netcdfile object
    11783       nc: netcdfile object to add dimensions
    11784       vnames: list of name of variables to add
    11785     """
    11786     fname = 'add_vars'
    11787 
    11788     for vn in vnames:
    11789         if not gen.searchInlist(nc.variables,vn):
    11790             print '  ' + fname + ': adding var:',vn,' ...'
    11791 
    11792             varo = oc.variables[vn]
    11793             vartype = varo.dtype
    11794             vardims = varo.dimensions
    11795             varattrs = varo.ncattrs()
    11796 
    11797             for vdn in vardims:
    11798                 if not gen.searchInlist(nc.dimensions,vdn):
    11799                     print warnmsg
    11800                     print '  ' + fname + ": adding dimension '" + vdn +              \
    11801                       "' from variable '" + vdn + "' which is not in file !!"
    11802                     add_dims(oc,nc,[vdn])
    11803 
    11804             if gen.searchInlist(varattrs,'_FillValue'):
    11805                 newvar = nc.createVariable(vn, vartype, vardims,                     \
    11806                   fill_value=varo.getncattr('_FillValue'))
    11807             else:
    11808                 newvar = nc.createVariable(vn, vartype, vardims)
    11809 
    11810             for attrn in varattrs:
    11811                 attrv = varo.getncattr(attrn)
    11812                 newattr = set_attribute(newvar, attrn, attrv)
    11813 
    11814             newvar[:] = varo[:]
    11815 
    11816         nc.sync()
    11817 
    11818     return
    11819 
    11820 def add_globattrs(oc,nc,attrns):
    11821     """ Function to add global attributes from a given netCDF object to another one
    11822       oc: source netcdfile object
    11823       nc: netcdfile object to add dimensions
    11824       vnames: list of name of dimensions to add ('all', for all attributes)
    11825     """
    11826     fname = 'add_globattrs'
    11827 
    11828     allfattrs = oc.ncattrs()
    11829 
    11830     if attrns == 'all':
    11831         fattrns = allfattrs
    11832     else:
    11833         fattrns = attrns
    11834 
    11835     for an in fattrns:
    11836         if not gen.searchInlist(allfattrs,an):
    11837             print errormsg
    11838             print '  ' + fname + ": file has not global attribute '" + an + "' !!"
    11839             quit(-1)
    11840 
    11841         print '  ' + fname + ': adding attr:',an,' ...'
    11842        
    11843         av = oc.getncattr(an)
    11844         newattr = set_attribute(nc, an, av)
    11845 
    11846     nc.sync()
    11847 
    11848     return
    1184912099
    1185012100def selvar(values, ncfile, varn):
     
    1721417464
    1721517465    ncvars = ncf.variables.keys()
    17216     print fname + '; Lluis ncvars:', ncvars
    1721717466    olon2 = ncf.variables['lon2']
    1721817467    dimslon2 = olon2.dimensions
     
    1723117480    olat2 = ncf.variables['lat2']
    1723217481    dimslat2 = olat2.dimensions
    17233     print fname + '; Lluis ncvars after 1st:', ncvars, 'dimslat2:', dimslat2
    1723417482    newvar = ncf.createVariable('lat','f8',dimslat2)
    1723517483    newvar[:] = olat2[:]
Note: See TracChangeset for help on using the changeset viewer.