Changeset 2684 in lmdz_wrf for trunk


Ignore:
Timestamp:
Jul 26, 2019, 4:19:04 AM (5 years ago)
Author:
lfita
Message:

Adding

  • Jumping of lines from file (not working?)
  • Addition of new extra descriptive variables
Location:
trunk/tools
Files:
5 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/create_OBSnetcdf.py

    r1955 r2684  
    611611    return values
    612612
    613 def read_datavalues(dataf, comchar, colchar, fmt, oper, miss, varns, dbg):
     613def read_datavalues(dataf, comchar, colchar, fmt, jBl, oper, miss, varns, dbg):
    614614    """ Function to read from an ASCII file values in column
    615615      dataf= data file
     
    618618      dbg= debug mode or not
    619619      fmt= list of kind of values to be found
     620      jBl= number of lines to jump from the beginning of file
    620621      oper= list of operations to perform
    621622      miss= missing value
     
    640641    for line in ofile:
    641642        line = line.replace('\n','').replace(chr(13),'')
    642         if not searchInlist(comchar,line[0:1]) and len(line) > 1:
     643        print iline, 'jBl', jBl
     644        if not searchInlist(comchar,line[0:1]) and len(line) > 1 and iline > jBl-1:
    643645            # Getting values
    644646            if colchar[0:4] != 'None':
     
    687689            for ivar in range(Nvals):
    688690                if dbg:
    689                     print iline, varns[ivar],'value:',values[ivar],miss,opers[ivar], \
    690                       fmt[ivar]
     691                    print iline, ',', ivar, '  ', varns[ivar],'value:',values[ivar], \
     692                      miss,opers[ivar], fmt[ivar]
    691693
    692694                if iline == 0:
     
    12031205    return
    12041206
     1207def EXTRAcodevar(unitsn, onc, Lstrcode=1024):
     1208    """ Function to add a variabe providing description of a units based on an extra
     1209        code
     1210      unitsn= name of the units (all codes derived units must be labelled as
     1211        'extra_code_[ref]' associated to a file valled extra_[ref].code)
     1212      onc= netCDF object file to add the description
     1213      Lstrcode= length of description of codes
     1214
     1215      extra_[ref].code must have the structure: ('#' for comments)
     1216        reference|web page, document reference with the code
     1217        short_description|main description of the code
     1218        long_description|long description of the code
     1219        codeTYPE|type of the code (andy of 'D', 'F', 'I', 'S')
     1220        @| Values line giving the start of the values
     1221        [val1]|[meaning of first value]
     1222        (...)
     1223        [valN]|[meaning of last value]
     1224    """
     1225    fname = 'EXTRAcodevar'
     1226
     1227# From http://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python
     1228    folder = os.path.dirname(os.path.realpath(__file__))
     1229
     1230    code = unitsn.split('_')[2]
     1231
     1232    infile = folder + '/extra_' + code +'.code'
     1233
     1234    if not os.path.isfile(infile):
     1235        print warnmsg
     1236        print '  ' + fname + ": EXTRA code file '" + infile + "' does not exist !!"
     1237        return
     1238    # main expected values
     1239    descvals = ['reference', 'short_description', 'long_description',    \
     1240      'codeTYPE', '@']
     1241
     1242    availcodetype = ['D', 'F', 'I', 'S']
     1243
     1244    codevalues = {}
     1245    ocode = open(infile, 'r')
     1246    inivals = False
     1247    codvals = []
     1248    codmeanings = []
     1249    for line in ocode:
     1250        if len(line) > 1 and line[0:1] != '#':
     1251            linev = line.replace('\n','').replace('\t','    ').replace('\r','')
     1252            if not inivals:
     1253                Sv = linev.split('|')[0]
     1254                Vv = linev.split('|')[1]
     1255                if searchInlist(descvals, Sv):
     1256                    if Sv != '@': codevalues[Sv] = Vv
     1257                    else: inivals = True
     1258            else:
     1259                Svv = linev.split('|')[0]
     1260                Vvv = linev.split('|')[1]
     1261                codvals.append(Svv)
     1262                codmeanings.append(Vvv)
     1263                       
     1264    # Creating variable
     1265    if not searchInlist(onc.dimensions, 'Lstringcode'):
     1266        print '  ' + fname + ": Adding string length dimension 'Lstringcode' for " + \
     1267          " code descriptions"
     1268        newdim = onc.createDimension('Lstringcode', Lstrcode)
     1269    Ncodes = len(codvals)
     1270    codedimn = 'extra_code_' + str(code)
     1271    if not searchInlist(onc.dimensions, codedimn):
     1272        print '  ' + fname + ": Adding '" + codedimn + "' dimension for code " +     \
     1273          "description"
     1274        newdim = onc.createDimension(codedimn, Ncodes)
     1275    onc.sync()
     1276
     1277    # Variable with the value of the code
     1278    if not onc.variables.has_key(codedimn):
     1279        if codevalues['codeTYPE'] == 'D':
     1280            newvar = onc.createVariable(codedimn, 'f8', (codedimn))
     1281            for iv in range(Ncodes): newvar[iv] = np.float64(codvals[iv])
     1282        elif codevalues['codeTYPE'] == 'F':
     1283            newvar = onc.createVariable(codedimn, 'f', (codedimn))
     1284            for iv in range(Ncodes): newvar[iv] = np.float(codvals[iv])
     1285        elif codevalues['codeTYPE'] == 'I':
     1286            newvar = onc.createVariable(codedimn, 'i', (codedimn))
     1287            for iv in range(Ncodes): newvar[iv] = int(codvals[iv])
     1288        elif codevalues['codeTYPE'] == 'S':
     1289            newvar = onc.createVariable(codedimn, 'c', (codedimn, 'Lstringcode'))
     1290            writing_str_nc(newvar, codvals, Lstrcode)
     1291        else:
     1292            print errormsg
     1293            print '  ' + fname + ": codeTYPE '" + codevalues['codeTYPE'] + "' not" + \
     1294              " ready !!"
     1295            print '   available ones:', availcodetype
     1296            quit(-1)
     1297
     1298        for descv in descvals:
     1299            if descv != '@' and descv != 'codeTYPE':
     1300                newvar.setncattr(descv, codevalues[descv])
     1301    # Variable with the meaning of the code
     1302    if not onc.variables.has_key(codedimn+'_meaning'):
     1303        print '  '+fname+": Adding '" + codedimn + "_meaning' variable for code " +  \
     1304          "description"
     1305        newvar = onc.createVariable(codedimn+'_meaning','c',(codedimn,'Lstringcode'))
     1306        writing_str_nc(newvar, codmeanings, Lstrcode)
     1307        newvar.setncattr('description', 'meaning of EXTRA code ' + str(code))
     1308
     1309    onc.sync()
     1310
     1311    return
     1312
    12051313def add_global_PyNCplot(ObjFile, pyscript, funcname, version):
    12061314    """ Function to add global attributes from 'PyNCplot' to a given netCDF
     
    12531361parser.add_option("-f", "--file", dest="obsfile",
    12541362  help="observational file to use", metavar="FILE")
     1363parser.add_option("-j", "--jumpBlines", dest="jumpBlines",
     1364  help="number of lines to jump from the beggining of file", metavar="VALUE")
    12551365parser.add_option("-g", "--debug", dest="debug",
    1256   help="whther debug is required ('false', 'true')", metavar="VALUE")
     1366  help="whether debug is required ('false', 'true')", metavar="VALUE")
    12571367parser.add_option("-k", "--kindObs", dest="obskind", type='choice', choices=kindobs,
    12581368  help=strkObs, metavar="VALUE")
     
    12771387else:
    12781388    charcomments = opts.charcom.split(':')   
     1389
     1390if opts.jumpBlines is None:
     1391    print warnmsg
     1392    print '  ' + main + ': No number of lines to jump from beggining of file provided!!'
     1393    print '    assuming no need!'
     1394    jumpBlines = 0
     1395else:
     1396    jumpBlines = int(opts.jumpBlines)
     1397
    12791398
    12801399if opts.fdesc is None:
     
    13421461    if obskind == 'single-station':
    13431462        if opts.stloc is None:
    1344             print errornmsg
     1463            print errormsg
    13451464            print '  ' + main + ': No station location provided !!'
    13461465            quit(-1)
     
    13671486        Nshow = len(formats)
    13681487        for ivar in range(Nshow):
    1369             print '      ',description['varN'][ivar],':', description['varLN'][ivar],\
     1488            print ivar,'      ',description['varN'][ivar],':', description['varLN'][ivar],\
    13701489               '[', description['varU'][ivar], '] fmt:', formats[ivar]
    13711490        print '      missing values for:', description['varN'][Nshow:Nvariables+1]
     
    13731492        Nshow = Nvariables
    13741493        for ivar in range(Nshow):
    1375             print '      ',description['varN'][ivar],':', description['varLN'][ivar],\
     1494            print ivar,'      ',description['varN'][ivar],':', description['varLN'][ivar],\
    13761495               '[', description['varU'][ivar], '] fmt:', formats[ivar]
    13771496        print '      excess of formats for:', formats[Nshow:len(formats)+1]
     
    13811500# Reading values
    13821501##
    1383 datavalues = read_datavalues(opts.obsfile, charcomments, endcol, formats,
     1502datavalues = read_datavalues(opts.obsfile, charcomments, endcol, formats, jumpBlines,
    13841503  description['varOPER'], description['MissingValue'], description['varN'], debug)
    13851504
     
    14431562    if description['varU'][ivar][0:8] == 'wmo_code':
    14441563        WMOcodevar(description['varU'][ivar], objfile)
     1564    # Getting new variables to describe certain units as codeEXTRA_[ref] from an
     1565    #   external file
     1566    if description['varU'][ivar][0:10] == 'extra_code':
     1567        EXTRAcodevar(description['varU'][ivar], objfile)
    14451568
    14461569# Extra variable descriptions/attributes
Note: See TracChangeset for help on using the changeset viewer.