Changeset 2478 in lmdz_wrf


Ignore:
Timestamp:
Apr 29, 2019, 4:28:40 PM (6 years ago)
Author:
lfita
Message:

Adding:

  • `fill_varNCfile': Function to fill up a variable from a netCDF file

Updating:

  • `add_global_PyNCplot': Taking into account when it was already in the file
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r2470 r2478  
    7676## e.g. # nc_var.py -o CFfile_creation -S 'lon|360,lat|180,time|None@20:global' -v 'tas#time;lat;lon#f#None,time#time#f8#units|seconds!since!1949-12-01!00:00:00|S' -f newCF.nc
    7777## e.g. # nc_var.py -o CFfile_fixTime -f tasmin_Amon_BNU-ESM_historical_r1i1p1_185001-200512_lonlatbox.nc -S 'setCalendar;setRefDate,19491201000000' -v time
     78## e.g. # nc_var.py -o fill_varNCfile -S 'random,0.,10.' -f CFtest.nc -v tas
    7879
    7980from optparse import OptionParser
     
    136137# file_creation: Operation to create a file with one variable with a given set of dimensions
    137138# file_oper_alongdims: Function to operate a file along different dimensions of a variable
     139# fill_varNCfile: Function to fill up a variable from a netCDF file
    138140# filter_2dim: Function to filter along 2 dimensions (moving grid-box means of a given size) values of the netCDF file
    139141# flipdim: flips the value following one dimension
     
    246248  'except_fillValue', 'fattradd',                                                    \
    247249  'fdimadd', 'fgaddattr', 'field_stats', 'field_stats_dim', 'file_creation',         \
    248   'file_oper_alongdims', 'filter_2dim',                                              \
     250  'file_oper_alongdims', 'fill_varNCfile', 'filter_2dim',                            \
    249251  'flipdim', 'fvaradd', 'gaddattrk', 'gaddattr', 'get_attribute',                    \
    250252  'get_point', 'get_time', 'get_namelist_vars', 'get_Variables',                     \
     
    435437elif oper == 'field_stats_dim':
    436438    ncvar.field_stats_dim(opts.values, opts.ncfile, opts.varname)
     439elif oper == 'fill_varNCfile':
     440    ncvar.fill_varNCfile(opts.values, opts.ncfile, opts.varname)
    437441elif oper == 'filter_2dim':
    438442    ncvar.filter_2dim(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r2468 r2478  
    8989# file_oper_alongdims: Function to operate a file along different dimensions of a variable
    9090# fill_ncvariable_lastdims: Function to fill the last [Nlastdims] dimensions of a variable [varn] from a netCDF object at the other dimensions at [prevdims]
     91# fill_varNCfile: Function to fill up a variable from a netCDF file
    9192# filter_2dim: Function to filter along 2 dimensions (moving grid-box means of a given size) values of the netCDF file
    9293# flipdim: flips the value following one dimension [Nflipdim]
     
    11891190    fname = 'add_global_PyNCplot'
    11901191
    1191     # Global values
    1192     ObjFile.setncattr('author', 'L. Fita')
    1193     #newattr = set_attributek(ObjFile, 'institution', unicode('Laboratoire ' +        \
    1194     # 'de M' + unichr(233) + 't' + unichr(233) + 'orologie Dynamique'), 'U')
    1195     #ObjFile.setncattr('university', 'Pierre et Marie Curie - Jussieu, Paris 06')
    1196     #ObjFile.setncattr('center', 'Centre National de Recherches Scientifiques')
    1197     #ObjFile.setncattr('city', 'Paris')
    1198     #ObjFile.setncattr('country', 'France')
    1199     newattr = set_attributek(ObjFile, 'institution', unicode('Centro de ' +          \
    1200      'Investigaciones del Mar y la Atm' + unichr(243) + 'sfera (CIMA)'), 'U')
    1201     newattr = set_attributek(ObjFile, 'institution2', unicode('Instituto Franco-' +  \
    1202       'Argentino sobre Estudios de Clima y sus Impactos (CNRS, UMI-3351-IFAECI'), 'U')
    1203     newattr = set_attributek(ObjFile, 'center', unicode('Consejo Nacional de ' +     \
    1204       'Investigaciones Cient' + unichr(237) + 'ficas y T' + unichr(233) +            \
    1205       'cnicas (CONICET)'), 'U')
    1206     ObjFile.setncattr('university', 'Universidad de Buenos Aires (UBA)')
    1207     ObjFile.setncattr('city', 'C. A. Buenos Aires')
    1208     ObjFile.setncattr('country', 'Argentina')
    1209     ObjFile.setncattr('tool', 'PyNCplot')
    1210     ObjFile.setncattr('url', 'http://www.xn--llusfb-5va.cat/python/PyNCplot')
    1211     ObjFile.setncattr('script', pyscript)
    1212     if funcname is not None:
    1213         ObjFile.setncattr('function', funcname)
    1214     ObjFile.setncattr('version', version)
    1215 
     1192
     1193    gattrs = ObjFile.ncattrs()
     1194    if gen.searchInlist(gattrs, 'tool'):
     1195        attrv = ObjFile.getncattr('tool')
     1196    else:
     1197        attrv = None
     1198
     1199    if attrv == 'PyNCplot':
     1200        attrscript = ObjFile.getncattr('function')
     1201        attrvers = ObjFile.getncattr('version')
     1202
     1203        attrsc = attrscript.split(';')
     1204        attrsv = attrvers.split(';')
     1205
     1206        funcnameS = attrscript
     1207        versionS = attrvers
     1208
     1209        if funcname is not None:
     1210            attrsc = attrsc + [funcname]
     1211            attrsv = attrsv + [version]
     1212            funcnameS = ';'.join(attrsc)
     1213            versionS = ';'.join(attrsv)
     1214
     1215        ObjFile.setncattr('function', funcnameS)
     1216        ObjFile.setncattr('version', versionS)
     1217       
     1218    else:
     1219        # Global values
     1220        ObjFile.setncattr('author', 'L. Fita')
     1221        #newattr = set_attributek(ObjFile, 'institution', unicode('Laboratoire ' +    \
     1222        # 'de M' + unichr(233) + 't' + unichr(233) + 'orologie Dynamique'), 'U')
     1223        #ObjFile.setncattr('university', 'Pierre et Marie Curie - Jussieu, Paris 06')
     1224        #ObjFile.setncattr('center', 'Centre National de Recherches Scientifiques')
     1225        #ObjFile.setncattr('city', 'Paris')
     1226        #ObjFile.setncattr('country', 'France')
     1227        newattr = set_attributek(ObjFile, 'institution', unicode('Centro de ' +      \
     1228         'Investigaciones del Mar y la Atm' + unichr(243) + 'sfera (CIMA)'), 'U')
     1229        newattr = set_attributek(ObjFile, 'institution2', unicode('Instituto ' +     \
     1230          'Franco-Argentino sobre Estudios de Clima y sus Impactos (CNRS, UMI-' +    \
     1231           '3351-IFAECI'), 'U')
     1232        newattr = set_attributek(ObjFile, 'center', unicode('Consejo Nacional de ' + \
     1233          'Investigaciones Cient' + unichr(237) + 'ficas y T' + unichr(233) +        \
     1234          'cnicas (CONICET)'), 'U')
     1235        ObjFile.setncattr('university', 'Universidad de Buenos Aires (UBA)')
     1236        ObjFile.setncattr('city', 'C. A. Buenos Aires')
     1237        ObjFile.setncattr('country', 'Argentina')
     1238        ObjFile.setncattr('tool', 'PyNCplot')
     1239        ObjFile.setncattr('url', 'http://www.xn--llusfb-5va.cat/python/PyNCplot')
     1240        ObjFile.setncattr('script', pyscript)
     1241        if funcname is not None:
     1242            ObjFile.setncattr('function', funcname)
     1243        ObjFile.setncattr('version', version)
     1244   
    12161245    ObjFile.sync() 
    12171246
     
    3150431533#CFfile_creation(values, 'CFtest.nc', varsS)
    3150531534
     31535def fill_varNCfile(values,ncfile,variable):
     31536    """ Function to fill up a variable from a netCDF file
     31537      values= [method]
     31538        [method]: Method to fill the variable
     31539          'random',[minv],[maxv]: Random values from between minv, maxv
     31540          'centeredevol',[timedimn],[minv],[maxv]: centered to the center of the
     31541             space of the variable within range [minv,maxv] evolving in time
     31542             being [dimt]: name of the time-dimension
     31543      ncfile= name of the netCDF file
     31544      variable= variable to fill up
     31545    """
     31546    fname = 'fill_varNCfile'
     31547
     31548    availoperation = ['random,[minv],[maxv]', 'centeredevol,[timedimn],[minv],' +    \
     31549      '[maxv],[dt]']
     31550
     31551    if values == 'h':
     31552        print fname + '_____________________________________________________________'
     31553        print ill_varNCfile.__doc__
     31554        quit()
     31555
     31556    expectargs = '[operation]'
     31557 
     31558    gen.check_arguments(fname,values,expectargs,':')
     31559    operationN = values.split(':')[0]
     31560
     31561    onc = NetCDFFile(ncfile,'a')
     31562
     31563    varinfile(onc, ncfile, errormsg, '', variable)
     31564    ovar = onc.variables[variable]
     31565
     31566    ovarshape = ovar.shape
     31567
     31568    operation = operationN.split(',')
     31569    if operation[0] == 'centeredevol':
     31570        refop = 'centeredevol,[timedimn],[minv],[maxv]'
     31571        Nopreq = len(refop.split(','))
     31572        if len(operation) != Nopreq:
     31573            print errormsg
     31574            print '  ' + fname + ": wrong number of terms for operation '" +         \
     31575              operation[0] + "' !!"
     31576            print '    it requires:', Nopreq, 'and', len(operation), 'were passed !'
     31577            print "    requested terms for the operation: '" + refop + "'"
     31578            quit(-1)
     31579        if not gen.searchInlist(ovar.dimensions,operation[1]):
     31580            print errormsg
     31581            print '  ' + fname + ": variable '" + variable + "' does not have time " +\
     31582              "dimension named '" + operation[1] + "' !!"
     31583            print '    available ones:', ovar.dimensions
     31584            quit(-1)
     31585        idimt = ovar.dimensions.index[operation[1]]
     31586        dimt = ovarshape[idimt]
     31587        slices = provide_slices(ovar.dimensions, ovarshape, [operation[1]])
     31588        minv = gen.typemod(operation[2], ovar.dtype)
     31589        maxv = gen.typemod(operation[3], ovar.dtype)
     31590
     31591        # First centered values
     31592        shapecirc = list(ovarshape)
     31593        shapecirc = shapecirc.pop(idimt)
     31594        circ = np.zeros(tuple(shapecirc), dtype=ovar.dtype)
     31595        if shapecirc == 2:
     31596            ccircx = circ.shape[1]/2.
     31597            ccircy = circ.shape[0]/2.
     31598            norm = np.sqrt(ccircx**2 + ccircy**2)
     31599            for iy in range(dimy):
     31600                for ix in range(dimx):
     31601                    circ[iy,ix] = np.sqrt((ix*1.-ccircx)**2 + (iy*1.-ccircy)**2)/norm
     31602        elif shapecirc == 3:
     31603            ccircx = circ.shape[2]/2.
     31604            ccircy = circ.shape[1]/2.
     31605            ccircz = circ.shape[0]/2.
     31606            norm = np.sqrt(ccircx**2 + ccircy**2 + ccircz**2)
     31607            for iz in range(dimz):
     31608                for iy in range(dimy):
     31609                    for ix in range(dimx):
     31610                        circ[iz,iy,ix]=np.sqrt((ix*1.-ccircx)**2 + (iy*1.-ccircy)**2+\
     31611                          + (iz*1.-ccircz)**2)/norm
     31612        else:
     31613            print errormsg
     31614            print '  ' + fname + ": shape of variable without time:", circ.shape, +  \
     31615              'not ready !!'
     31616            print '   available ones: 2D, 3D'
     31617            quit(-1)
     31618
     31619        rangev = maxv - minv
     31620        dt = rangev/(dimt-1)
     31621        if dt > 0:
     31622            rangev = np.arange(minv, maxv+dt, dt)
     31623        else:
     31624            rangev = np.arange(maxv, minv-dt, dt)
     31625
     31626        vals = np.zeros(varshape, dtype=ovar.dtype)
     31627
     31628        for it in range(dimt):
     31629            vals[tuple(slices)] = circ*rangev[it]
     31630        ovar[:] = vals
     31631
     31632    elif operation[0] == 'random':
     31633        import random
     31634        refop = 'random,minv,maxv'
     31635        Nopreq = len(refop.split(','))
     31636        if len(operation) != Nopreq:
     31637            print errormsg
     31638            print '  ' + fname + ": wrong number of terms for operation '" +         \
     31639              operation[0] + "' !!"
     31640            print '    it requires:', Nopreq, 'and', len(operation), 'were passed !'
     31641            print "    requested terms for the operation: '" + refop + "'"
     31642            quit(-1)
     31643        totsize = np.prod(ovarshape)
     31644        randvals = np.zeros((totsize), dtype=ovar.dtype)
     31645        minv = gen.typemod(operation[1], ovar.dtype)
     31646        maxv = gen.typemod(operation[2], ovar.dtype)
     31647        for iv in range(totsize): randvals[iv] = random.uniform(minv,maxv) + 0.
     31648        vals = randvals.reshape(ovarshape)
     31649        ovar[:] = vals
     31650    else:
     31651        print errormsg
     31652        print '  ' + fname + ": operation '" + operation[0] + "' not ready !!"
     31653        print '    avaialbe ones:', availoperation
     31654        quit(-1)
     31655
     31656    onc.sync()
     31657    ovar.setncattr(fname + '_filled', operationN)
     31658
     31659    add_global_PyNCplot(onc, 'nc_var_tools', fname, '1.0')
     31660    onc.sync()
     31661    onc.close()
     31662
     31663    print fname + ": Successful filling of variable '" + variable + "' !!"
     31664
     31665    return
     31666
    3150631667def CFfile_fixTime(values, ncfile, variable):
    3150731668    """ Operation to fix a netCDF file with a time axis folowing CF-conventions, but
     
    3158331744            newtimv = gen.change_CFcalendar(timevs, tunits, origcal)
    3158431745            newtunits = tunits + ''
     31746            otime.setncattr('calendar', 'gregorian')
    3158531747
    3158631748        # Fixing reference date
     
    3164031802    # Changing values in file
    3164131803    otime[:] = timevs
    31642     otime.setncattr('units', tunits)
     31804    otime.setncattr('units', newtunits)
    3164331805
    3164431806    onc.sync()
     
    3165431816    return
    3165531817
    31656 #timesv = [56649.5, 56680, 56710.5, 56741, 56771.5, 56802.5, 56833, 56863.5, 56894, 56924.5]
    31657 #dimt = len(timesv)
    31658 #values='lon|360,lat|180,time|None@' + str(dimt) + ':global'
    31659 #varsS='tas#time;lat;lon#f#None,time#time#f8#units|days!since!1850-01-01!00:00:00|S'
    31660 #CFfile_creation(values, 'CFtest.nc', varsS)
    31661 #fname = 'timev1850-2005.dat'
    31662 #of = open(fname, 'w')
    31663 #for tv in timesv:
    31664 #    of.write(str(tv) + '\n')
    31665 #of.close()
    31666 #setvar_asciivalues(fname, 'CFtest.nc', 'time')
    31667 #values="setCalendar;setRefDate,19491201000000;setTunits,hours"
    31668 #varaddattr('calendar|noleap', 'CFtest.nc', 'time')
    31669 #CFfile_fixTime(values, 'CFtest.nc', 'time')
     31818timesv = [56649.5, 56680, 56710.5, 56741, 56771.5, 56802.5, 56833, 56863.5, 56894, 56924.5]
     31819dimt = len(timesv)
     31820values='lon|360,lat|180,time|None@' + str(dimt) + ':global'
     31821varsS='tas#time;lat;lon#f#None,time#time#f8#units|days!since!1850-01-01!00:00:00|S'
     31822CFfile_creation(values, 'CFtest.nc', varsS)
     31823fname = 'timev1850-2005.dat'
     31824of = open(fname, 'w')
     31825for tv in timesv:
     31826    of.write(str(tv) + '\n')
     31827of.close()
     31828setvar_asciivalues(fname, 'CFtest.nc', 'time')
     31829fill_varNCfile('random,0.,10.','CFtest.nc','tas')
     31830
     31831values="setCalendar;setRefDate,19491201000000;setTunits,hours"
     31832varaddattr('calendar|noleap', 'CFtest.nc', 'time')
     31833CFfile_fixTime(values, 'CFtest.nc', 'time')
    3167031834
    3167131835#quit()
Note: See TracChangeset for help on using the changeset viewer.