source: lmdz_wrf/trunk/tools/read_ISD.py @ 505

Last change on this file since 505 was 499, checked in by lfita, 10 years ago

Changing object file inside the function

File size: 24.6 KB
Line 
1# -*- coding: iso-8859-15 -*-
2# Python reader of ISD files
3## e.g. # read_ISD.py -c '#' -f 722317-13970-2005 -d description.dat -g true -t 19491201000000,seconds -s 'Baton Rouge METRO R,30.537,-91.147,23.2'
4import numpy as np
5from optparse import OptionParser
6import os
7from netCDF4 import Dataset as NetCDFFile
8
9main = 'read_ISD.py'
10errormsg = 'ERROR -- error -- ERROR -- error'
11warnmsg = 'WARNING -- warning -- WARNING -- warning'
12
13# version
14version=1.1
15
16# Filling values for floats, integer and string
17fillValueF = 1.e20
18fillValueI = -99999
19fillValueS = '---'
20
21# Length of the string variables
22StringLength = 200
23
24####### Different fixed tabuled values
25
26quality_vals = ['Passed gross limits check', 'Passed all quality control checks',    \
27  'Suspect', 'Erroneous',                                                            \
28  'Passed gross limits check , data originate from an NCDC data source',             \
29  'Passed all quality control checks, data originate from an NCDC data source',      \
30  'Suspect, data originate from an NCDC data source',                                \
31  'Erroneous, data originate from an NCDC data source',                              \
32  'Passed gross limits check if element is present' ]
33
34def searchInlist(listname, nameFind):
35    """ Function to search a value within a list
36    listname = list
37    nameFind = value to find
38    >>> searInlist(['1', '2', '3', '5'], '5')
39    True
40    """
41    for x in listname:
42      if x == nameFind:
43        return True
44    return False
45
46def set_attribute(ncvar, attrname, attrvalue):
47    """ Sets a value of an attribute of a netCDF variable. Removes previous attribute value if exists
48    ncvar = object netcdf variable
49    attrname = name of the attribute
50    attrvalue = value of the attribute
51    """
52    import numpy as np
53    from netCDF4 import Dataset as NetCDFFile
54
55    attvar = ncvar.ncattrs()
56    if searchInlist(attvar, attrname):
57        attr = ncvar.delncattr(attrname)
58
59    attr = ncvar.setncattr(attrname, attrvalue)
60
61    return ncvar
62
63def basicvardef(varobj, vstname, vlname, vunits):
64    """ Function to give the basic attributes to a variable
65    varobj= netCDF variable object
66    vstname= standard name of the variable
67    vlname= long name of the variable
68    vunits= units of the variable
69    """
70    attr = varobj.setncattr('standard_name', vstname)
71    attr = varobj.setncattr('long_name', vlname)
72    attr = varobj.setncattr('units', vunits)
73
74    return
75
76def remove_NONascii(string):
77    """ Function to remove that characters which are not in the standard 127 ASCII
78      string= string to transform
79    >>> remove_NONascii('Lluís')
80    Lluis
81    """
82    fname = 'remove_NONascii'
83
84    newstring = string
85
86    RTFchar= ['á', 'é', 'í', 'ó', 'ú', 'à', 'Ú', 'ì', 'ò', 'ù', 'â', 'ê', 'î', 'ÃŽ',  \
87      'û', 'À', 'ë', 'ï', 'ö', 'ÃŒ', 'ç', 'ñ','Ê', 'œ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'À', \
88      'È', 'Ì', 'Ò', 'Ù', 'Â', 'Ê', 'Î', 'Ô', 'Û', 'Ä', 'Ë', 'Ï', 'Ö', 'Ü', 'Ç', 'Ñ',\
89      'Æ', 'Œ', '\n', '\t']
90    ASCchar= ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o',  \
91      'u', 'a', 'e', 'i', 'o', 'u', 'c', 'n','ae', 'oe', 'A', 'E', 'I', 'O', 'U', 'A', \
92      'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'C', 'N',\
93      'AE', 'OE', '', ' ']
94
95    Nchars = len(RTFchar)
96    for ichar in range(Nchars):
97        foundchar = string.find(RTFchar[ichar])
98        if foundchar != -1:
99            newstring = newstring.replace(RTFchar[ichar], ASCchar[ichar])
100
101    return newstring
102
103def read_description(fdobs, dbg):
104    """ reads the description file of the observational data-set
105    fdobs= descriptive observational data-set
106    dbg= boolean argument for debugging
107    * Each station should have a 'description.dat' file with:
108      institution=Institution who creates the data
109      department=Department within the institution
110      scientists=names of the data producers
111      contact=contact of the data producers
112      description=description of the observations
113      acknowledgement=sentence of acknowlegement
114      comment=comment for the measurements
115
116      MissingValue='|' list of ASCII values for missing values within the data
117        (as they appear!)
118      comment=comments
119
120      varN='|' list of variable names
121      varLN='|' list of long variable names
122      varU='|' list units of the variables
123      varBUFR='|' list BUFR code of the variables
124      varTYPE='|' list of variable types ('D', 'F', 'I', 'I64', 'S')
125      varL='|' list of length of the sections for each variable within a given line (Fortran-like)
126
127      NAMElon=name of the variable with the longitude (x position)
128      NAMElat=name of the variable with the latitude (y position)
129      NAMEheight=ind_alt
130      NAMEtime=name of the varibale with the time
131      FMTtime=format of the time (as in 'C', 'CFtime' for already CF-like time)
132
133    """
134    fname = 'read_description'
135
136    descobj = open(fdobs, 'r')
137    desc = {}
138
139    namevalues = []
140
141    for line in descobj:
142        if line[0:1] != '#' and len(line) > 1 :
143            descn = remove_NONascii(line.split('=')[0])
144            descv = remove_NONascii(line.split('=')[1])
145            namevalues.append(descn)
146            if descn[0:3] != 'var':
147                if descn != 'MissingValue':
148                    desc[descn] = descv
149                else:
150                    desc[descn] = []
151                    for dn in descv.split('|'): desc[descn].append(dn)
152                    print '  ' + fname + ': missing values found:',desc[descn]
153            elif descn[0:3] == 'var':
154                desc[descn] = descv.split('|')
155            elif descn[0:4] == 'NAME':
156                desc[descn] = descv
157            elif descn[0:3] == 'FMT':
158                desc[descn] = descv
159
160    if dbg:
161        Nvars = len(desc['varN'])
162        print '  ' + fname + ": description content of '" + fdobs + "'______________"
163        for varn in namevalues:
164            if varn[0:3] != 'var':
165                print '    ' + varn + ':',desc[varn]
166            elif varn == 'varN':
167                print '    * Variables:'
168                for ivar in range(Nvars):
169                    varname = desc['varN'][ivar]
170                    varLname = desc['varLN'][ivar]
171                    varunits = desc['varU'][ivar]
172                    varsec = int(desc['varL'][ivar])
173                    if desc.has_key('varBUFR'): 
174                        varbufr=[ivar]
175                        print '      ', ivar, varname + ':',varLname,'[',varunits,   \
176                          ']','bufr code:',varbufr, 'L:', varsec
177                    else:
178                        print '      ', ivar, varname + ':',varLname,'[',varunits,   \
179                          '] L:',varsec
180
181    descobj.close()
182
183    return desc
184
185def value_fmt(val, miss, fmt):
186    """ Function to transform an ASCII value to a given format
187      val= value to transform
188      miss= list of possible missing values
189      fmt= format to take:
190        'D': float double precission
191        'F': float
192        'I': integer
193        'I64': 64-bits integer
194        'S': string
195    >>> value_fmt('9876.12', '-999', 'F')
196    9876.12
197    """
198
199    fname = 'value_fmt'
200
201    fmts = ['D', 'F', 'I', 'I64', 'S']
202    Nfmts = len(fmts)
203
204    if not searchInlist(miss,val):
205        if not searchInlist(fmts, fmt):
206            print errormsg
207            print '  ' + fname + ": format '" + fmt + "' not ready !!"
208            quit(-1)
209        else:
210            if fmt == 'D':
211                newval = np.float32(val)
212            elif fmt == 'F':
213                newval = np.float(val)
214            elif fmt == 'I':
215                newval = int(val)
216            elif fmt == 'I64':
217                newval = np.int64(val)
218            elif fmt == 'S':
219                newval = val
220    else:
221        newval = None
222
223    return newval
224
225def writing_str_nc(varo, values, Lchar):
226    """ Function to write string values in a netCDF variable as a chain of 1char values
227    varo= netCDF variable object
228    values = list of values to introduce
229    Lchar = length of the string in the netCDF file
230    """
231
232    Nvals = len(values)
233    for iv in range(Nvals):   
234        stringv=values[iv] 
235        charvals = np.chararray(Lchar)
236        Lstr = len(stringv)
237        charvals[Lstr:Lchar] = ''
238
239        for ich in range(Lstr):
240            charvals[ich] = stringv[ich:ich+1]
241
242        varo[iv,:] = charvals
243
244    return
245
246def Stringtimes_CF(tvals, fmt, Srefdate, tunits, dbg):
247    """ Function to transform a given data in String formats to a CF date
248      tvals= string temporal values
249      fmt= format of the the time values
250      Srefdate= reference date in [YYYY][MM][DD][HH][MI][SS] format
251      tunits= units to use ('weeks', 'days', 'hours', 'minutes', 'seconds')
252      dbg= debug
253    >>> Stringtimes_CF(['19760217082712','20150213101837'], '%Y%m%d%H%M%S',
254      '19491201000000', 'hours', False)
255    [229784.45333333  571570.31027778]
256    """
257    import datetime as dt
258
259    fname = 'Stringtimes'
260
261    dimt = len(tvals)
262
263    yrref = int(Srefdate[0:4])
264    monref = int(Srefdate[4:6])
265    dayref = int(Srefdate[6:8])
266    horref = int(Srefdate[8:10])
267    minref = int(Srefdate[10:12])
268    secref = int(Srefdate[12:14])
269    refdate = dt.datetime( yrref, monref, dayref, horref, minref, secref)
270
271    cftimes = np.zeros((dimt), dtype=np.float)
272
273    Nfmt=len(fmt.split('%'))
274
275    if dbg: print '  ' + fname + ': fmt=',fmt,'refdate:',Srefdate,'uits:',tunits,    \
276      'date dt_days dt_time deltaseconds CFtime _______'
277    for it in range(dimt):
278
279# Removing excess of mili-seconds (up to 6 decimals)
280        if fmt.split('%')[Nfmt-1] == 'f':
281            tpoints = tvals[it].split('.')
282            if len(tpoints[len(tpoints)-1]) > 6:
283                milisec = '{0:.6f}'.format(np.float('0.'+tpoints[len(tpoints)-1]))[0:7]
284                newtval = ''
285                for ipt in range(len(tpoints)-1):
286                    newtval = newtval + tpoints[ipt] + '.'
287                newtval = newtval + str(milisec)[2:len(milisec)+1]
288            else:
289                newtval = tvals[it]
290            tval = dt.datetime.strptime(newtval, fmt)
291        else:
292            tval = dt.datetime.strptime(tvals[it], fmt)
293
294        deltatime = tval - refdate
295        deltaseconds = deltatime.days*24.*3600. + deltatime.seconds +                \
296          deltatime.microseconds/100000.
297        if tunits == 'weeks':
298            deltat = 7.*24.*3600.
299        elif tunits == 'days':
300            deltat = 24.*3600.
301        elif tunits == 'hours':
302            deltat = 3600.
303        elif tunits == 'minutes':
304            deltat = 60.
305        elif tunits == 'seconds':
306            deltat = 1.
307        else:
308            print errormsg
309            print '  ' + fname + ": time units '" + tunits + "' not ready !!"
310            quit(-1)
311
312        cftimes[it] = deltaseconds / deltat
313        if dbg:
314            print '  ' + tvals[it], deltatime, deltaseconds, cftimes[it]
315
316    return cftimes
317
318def additional_vars(string):
319    """ Function for the additional variables
320      string: sectino of the file line which has to be evaluated
321    """
322    fname = 'additional_vars'
323
324    Lstring=len(string)
325
326# Generic list of additional variables '-' for range of values
327    addvars0 = ['AA1-4', 'AB1', 'AC1', 'AD1', 'AE1', 'AG1', 'AH1-6', 'AI1-6', 'AJ1', \
328      'AK1', 'AL1-4', 'AM1', 'AN1', 'AO1-4', 'AP1-4', 'HPD', 'AU1-9', 'AW1-4',       \
329      'AX1-6', 'AY1-2', 'AZ1-2', 'CB1-2', 'CF1-3', 'CG1-3', 'CH1-2', 'CI1', 'CN1-4', \
330      'CO1-9', 'CR1', 'CT1-3', 'CU1-3', 'CV1-3', 'CW1-3', 'CX1-3', 'ED1', 'GA1-6',   \
331      'GE1', 'GF1', 'GG1-6', 'GH1', 'GJ1', 'GK1', 'GM1', 'GN1', 'GO1', 'GP1', 'GQ1', \
332      'GR1', 'HL1', 'IA1-2', 'IB1-2', 'IC1', 'KA1-4', 'KB1-3', 'KC1-2', 'KD1-2',     \
333      'KE1', 'KF1', 'KG1-2', 'MA1', 'MD1', 'ME1', 'MF1', 'MG1', 'MH1', 'MK1',        \
334      'MV1-7', 'MW1-7', 'OA1-3', 'OB1-2', 'OC1', 'OD1-3', 'OE1-3', 'RH1-3', 'SA1',   \
335      'ST1', 'UA1', 'UG1-2', 'WA1', 'WD1', 'WG1', 'WJ1', 'REM', 'EQD', 'N01-99',     \
336      'QNN']
337
338    addvars = []
339    for avar in addvars0:
340        if avar.find('-') == -1:
341            addvars.append(avar)
342        else:
343            totrange=avar.split('-')
344            erange = totrange[1]
345
346            if len(erange) > 1:
347                irange = totrange[0][1:3]
348            else:
349                irange = totrange[0][2:3]
350         
351            for ir in range(int(irange), int(erange)+1):
352                if len(erange) > 1:
353                    addvars.append(avar[0:1] + str(ir).zfill(2))
354                else:
355                    addvars.append(avar[0:2] + str(ir))
356
357#    print addvars
358# Looking for the variables
359    ichar=0
360
361    additionals = []
362    while ichar <= Lstring:
363        sec3 = string[ichar:ichar+3]
364        if searchInlist(addvars, sec3):
365            additionals.append(sec3)
366#            print '  ' , sec3, 'Additional!!'
367            ichar = ichar + 2
368
369        ichar = ichar + 1
370
371    return additionals
372
373def read_datavalues_conline(dataf, comchar, fmt, Lv, miss, varns, dbg):
374    """ Function to read from an ASCII file values in ISH format (continuos line)
375      dataf= data file
376      comchar= list of the characters indicating comment in the file
377      dbg= debug mode or not
378      fmt= list of kind of values to be found
379      Lv= length of the value section
380      miss= missing value
381      varns= list of name of the variables to find
382    """
383    fname = 'read_datavalues_conline'
384
385    ofile = open(dataf, 'r')
386    Nvals = len(fmt)
387
388    finalvalues = {}
389
390    iline = 0
391    for line in ofile:
392        line = line.replace('\n','').replace(chr(13),'')
393        Lline = len(line)
394        if not searchInlist(comchar,line[0:1]) and len(line) > 1:
395# Removing no-value columns
396            values = []
397
398            for ivar in range(Nvals):
399                if ivar == 0:
400                    isec = 0
401                else:
402                    isec = int(Lv[ivar-1])
403
404                esec = int(Lv[ivar])
405                val = line[isec:esec]
406
407                values.append(val)
408                if dbg: 
409                    print iline, varns[ivar],'value:',values[ivar],miss,fmt[ivar]
410
411                if iline == 0:
412                    listvals = []
413                    listvals.append(value_fmt(values[ivar], miss, fmt[ivar]))
414                    finalvalues[varns[ivar]] = listvals
415                else:
416                    listvals = finalvalues[varns[ivar]]
417                    listvals.append(value_fmt(values[ivar], miss, fmt[ivar]))
418                    finalvalues[varns[ivar]] = listvals
419# Additional variables
420            if Lline > esec and line[esec:esec+3] == 'ADD':
421                if iline == 0: print '  ' + fname + ': Additional variables!!'
422                ichar=esec+3
423                print '    ', additional_vars(line[esec+4:Lline+1])
424
425        else:
426# First line without values
427            if iline == 0: iline = -1
428   
429        iline = iline + 1
430
431    ofile.close()
432
433    return finalvalues
434
435def adding_station_desc(onc,stdesc):
436    """ Function to add a station description in a netCDF file
437      onc= netCDF object
438      stdesc= station description lon, lat, height
439    """
440    fname = 'adding_station_desc'
441
442    newvar = onc.createVariable( 'station', 'c', ('StrLength'))
443    newvar[0:len(stdesc[0])] = stdesc[0]
444
445    newdim = onc.createDimension('nst',1)
446
447    if onc.variables.has_key('lon'):
448        print warnmsg
449        print '  ' + fname + ": variable 'lon' already exist !!"
450        print "    renaming it as 'lonst'"
451        lonname = 'lonst'
452    else:
453        lonname = 'lon'
454
455    newvar = onc.createVariable( lonname, 'f4', ('nst'))
456    basicvardef(newvar, lonname, 'longitude', 'degrees_West' )
457    newvar[:] = stdesc[1]
458
459    if onc.variables.has_key('lat'):
460        print warnmsg
461        print '  ' + fname + ": variable 'lat' already exist !!"
462        print "    renaming it as 'latst'"
463        latname = 'latst'
464    else:
465        latname = 'lat'
466
467    newvar = onc.createVariable( latname, 'f4', ('nst'))
468    basicvardef(newvar, lonname, 'latitude', 'degrees_North' )
469    newvar[:] = stdesc[2]
470
471    if onc.variables.has_key('height'):
472        print warnmsg
473        print '  ' + fname + ": variable 'height' already exist !!"
474        print "    renaming it as 'heightst'"
475        heightname = 'heightst'
476    else:
477        heightname = 'height'
478
479    newvar = onc.createVariable( heightname, 'f4', ('nst'))
480    basicvardef(newvar, heightname, 'height above sea level', 'm' )
481    newvar[:] = stdesc[3]
482
483    return
484
485####### ###### ##### #### ### ## #
486
487strCFt="Refdate,tunits (CF reference date [YYYY][MM][DD][HH][MI][SS] format and " +  \
488  " and time units: 'weeks', 'days', 'hours', 'miuntes', 'seconds')"
489
490parser = OptionParser()
491parser.add_option("-c", "--comments", dest="charcom",
492  help="':', list of characters used for comments", metavar="VALUES")
493parser.add_option("-d", "--descriptionfile", dest="fdesc",
494  help="description file to use", metavar="FILE")
495parser.add_option("-f", "--file", dest="obsfile",
496  help="observational file to use", metavar="FILE")
497parser.add_option("-g", "--debug", dest="debug",
498  help="whther debug is required ('false', 'true')", metavar="VALUE")
499parser.add_option("-s", "--stationLocation", dest="stloc", 
500  help="',' list with Name, longitude, latitude and height of the station", metavar="VALUES")
501parser.add_option("-t", "--CFtime", dest="CFtime", help=strCFt, metavar="VALUE")
502(opts, args) = parser.parse_args()
503
504#######    #######
505## MAIN
506    #######
507
508ofile='ISD.nc'
509
510if opts.charcom is None:
511    print warnmsg
512    print '  ' + main + ': No list of comment characters provided!!'
513    print '    assuming no need!'
514    charcomments = []
515else:
516    charcomments = opts.charcom.split(':')   
517
518if opts.fdesc is None:
519    print errormsg
520    print '  ' + main + ': No description file for the observtional data provided!!'
521    quit(-1)
522
523if opts.obsfile is None:
524    print errormsg
525    print '  ' + main + ': ISD file not provided !!'
526    quit(-1)
527
528if opts.debug is None:
529    print warnmsg
530    print '  ' + main + ': No debug provided!!'
531    print "    assuming 'False'"
532    debug = False
533else:
534    if opts.debug == 'true':
535        debug = True
536    else:
537        debug = False
538
539if not os.path.isfile(opts.fdesc):
540    print errormsg
541    print '   ' + main + ": description file '" + opts.fdesc + "' does not exist !!"
542    quit(-1)
543
544if not os.path.isfile(opts.obsfile):
545    print errormsg
546    print '   ' + main + ": observational file '" + opts.obsfile + "' does not exist !!"
547    quit(-1)
548
549if opts.CFtime is None:
550    print warnmsg
551    print '  ' + main + ': No CFtime criteria are provided !!'
552    print "    either time is already in CF-format ('timeFMT=CFtime') in '" +        \
553      opts.fdesc + "'"
554    print "    or assuming refdate: '19491201000000' and time units: 'hours'"
555    referencedate = '19491201000000'
556    timeunits = 'hours'
557else:
558    referencedate = opts.CFtime.split(',')[0]
559    timeunits = opts.CFtime.split(',')[1]
560
561if opts.stloc is None:
562    print errornmsg
563    print '  ' + main + ': No station location provided !!'
564    quit(-1)
565else:
566    stationdesc = [opts.stloc.split(',')[0], np.float(opts.stloc.split(',')[1]),     \
567      np.float(opts.stloc.split(',')[2]), np.float(opts.stloc.split(',')[3])]
568
569# Reading description file
570##
571description = read_description(opts.fdesc, debug)
572
573Nvariables=len(description['varN'])
574formats = description['varTYPE']
575
576if len(formats) != Nvariables: 
577    print errormsg
578    print '  ' + main + ': number of formats:',len(formats),' and number of ' +     \
579      'variables', Nvariables,' does not coincide!!'
580    print '    * what is found is _______'
581    if Nvariables > len(formats):
582        Nshow = len(formats)
583        for ivar in range(Nshow):
584            print '      ',description['varN'][ivar],':', description['varLN'][ivar],\
585               '[', description['varU'][ivar], '] fmt:', formats[ivar]
586        print '      missing values for:', description['varN'][Nshow:Nvariables+1]
587    else:
588        Nshow = Nvariables
589        for ivar in range(Nshow):
590            print '      ',description['varN'][ivar],':', description['varLN'][ivar],\
591               '[', description['varU'][ivar], '] fmt:', formats[ivar]
592        print '      excess of formats for:', formats[Nshow:len(formats)+1]
593
594    quit(-1)
595
596# Reading values
597##
598datavalues = read_datavalues_conline(opts.obsfile, charcomments, formats,            \
599  description['varL'], description['MissingValue'], description['varN'], debug)
600
601# Total number of values
602Ntvalues = len(datavalues[description['varN'][0]])
603print main + ': total temporal values found:',Ntvalues
604
605objfile = NetCDFFile(ofile, 'w')
606
607# Creation of dimensions
608##
609objfile.createDimension('time',None)
610objfile.createDimension('StrLength',StringLength)
611
612# Creation of variables
613##
614for ivar in range(Nvariables):
615    varn = description['varN'][ivar]
616    print "  including: '" + varn + "' ... .. ."
617
618    if formats[ivar] == 'D':
619        newvar = objfile.createVariable(varn, 'f32', ('time'), fill_value=fillValueF)
620        basicvardef(newvar, varn, description['varLN'][ivar],                        \
621          description['varU'][ivar])
622        newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn])
623    elif formats[ivar] == 'F':
624        newvar = objfile.createVariable(varn, 'f', ('time'), fill_value=fillValueF)
625        basicvardef(newvar, varn, description['varLN'][ivar],                        \
626          description['varU'][ivar])
627        newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn])
628    elif formats[ivar] == 'I':
629        newvar = objfile.createVariable(varn, 'i', ('time'), fill_value=fillValueI)
630        basicvardef(newvar, varn, description['varLN'][ivar],                        \
631          description['varU'][ivar])
632# Why is not wotking with integers?
633        vals = np.array(datavalues[varn])
634        for iv in range(Ntvalues):
635            if vals[iv] is None: vals[iv] = fillValueI
636        newvar[:] = vals
637    elif formats[ivar] == 'S':
638        newvar = objfile.createVariable(varn, 'c', ('time','StrLength'))
639        basicvardef(newvar, varn, description['varLN'][ivar],                        \
640          description['varU'][ivar])
641        writing_str_nc(newvar, datavalues[varn], StringLength)
642
643# Time variable in CF format
644##
645if description['FMTtime'] == 'CFtime':
646    timevals = datavalues[description['NAMEtime']]
647    iv = 0
648    for ivn in description['varN']:
649        if ivn == description['NAMEtime']:
650            tunits = description['varU'][iv]
651            break
652        iv = iv + 1
653else:
654    # Time as a composition of different columns
655    tcomposite = description['NAMEtime'].find('@')
656    if tcomposite != -1:
657        timevars = description['NAMEtime'].split('@')
658
659        print warnmsg
660        print '  ' + main + ': time values as combination of different columns!'
661        print '    combining:',timevars,' with a final format: ',description['FMTtime']
662
663        timeSvals = []
664        if debug: print '  ' + main + ': creating times _______'
665        for it in range(Ntvalues):
666            tSvals = ''
667            for tvar in timevars:
668                tSvals = tSvals + datavalues[tvar][it] + ' '
669
670            timeSvals.append(tSvals[0:len(tSvals)-1])
671            if debug: print it, '*' + timeSvals[it] + '*'
672
673        timevals = Stringtimes_CF(timeSvals, description['FMTtime'], referencedate,      \
674          timeunits, debug)
675    else:
676        timevals = Stringtimes_CF(datavalues[description['NAMEtime']],                   \
677          description['FMTtime'], referencedate, timeunits, debug)
678
679    CFtimeRef = referencedate[0:4] +'-'+ referencedate[4:6] +'-'+ referencedate[6:8] +   \
680      ' ' + referencedate[8:10] +':'+ referencedate[10:12] +':'+ referencedate[12:14]
681    tunits = timeunits + ' since ' + CFtimeRef
682
683if objfile.variables.has_key('time'):
684    print warnmsg
685    print '  ' + main + ": variable 'time' already exist !!"
686    print "    renaming it as 'CFtime'"
687    timeCFname = 'CFtime'
688    newdim = objfile.renameDimension('time','CFtime')
689    newvar = objfile.createVariable( timeCFname, 'f8', ('CFtime'))
690    basicvardef(newvar, timeCFname, 'time', tunits )
691else:
692    timeCFname = 'time'
693    newvar = objfile.createVariable( timeCFname, 'f8', ('time'))
694    basicvardef(newvar, timeCFname, 'time', tunits )
695
696set_attribute(newvar, 'calendar', 'standard')
697newvar[:] = timevals
698
699# Global attributes
700##
701for descn in description.keys():
702    if descn[0:3] != 'var' and descn[0:4] != 'NAME' and descn[0:3] != 'FMT':
703        set_attribute(objfile, descn, description[descn])
704
705set_attribute(objfile,'author_nc','Lluis Fita')
706set_attribute(objfile,'institution_nc','Laboratoire de Meteorology Dynamique, ' +    \
707  'LMD-Jussieu, UPMC, Paris')
708set_attribute(objfile,'country_nc','France')
709set_attribute(objfile,'script_nc',main)
710set_attribute(objfile,'version_script',version)
711
712# Adding three variables with the station location, longitude, latitude and height
713adding_station_desc(objfile,stationdesc)
714
715objfile.sync()
716objfile.close()
717
718print main + ": Successfull generation of netcdf observational file '" + ofile + "' !!"
Note: See TracBrowser for help on using the repository browser.