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' |
---|
4 | import numpy as np |
---|
5 | from optparse import OptionParser |
---|
6 | import os |
---|
7 | from netCDF4 import Dataset as NetCDFFile |
---|
8 | |
---|
9 | main = 'read_ISD.py' |
---|
10 | errormsg = 'ERROR -- error -- ERROR -- error' |
---|
11 | warnmsg = 'WARNING -- warning -- WARNING -- warning' |
---|
12 | |
---|
13 | # version |
---|
14 | version=1.1 |
---|
15 | |
---|
16 | # Filling values for floats, integer and string |
---|
17 | fillValueF = 1.e20 |
---|
18 | fillValueI = -99999 |
---|
19 | fillValueS = '---' |
---|
20 | |
---|
21 | # Length of the string variables |
---|
22 | StringLength = 200 |
---|
23 | |
---|
24 | ####### Different fixed tabuled values |
---|
25 | |
---|
26 | quality_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 | |
---|
34 | def 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 | |
---|
46 | def 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 | |
---|
63 | def 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 | |
---|
76 | def 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 | |
---|
103 | def 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 | varOPER='|' list of operations to do to the variables to meet their units ([oper],[val]) |
---|
126 | [oper]=-,sumc,subc,mulc,divc (nothing, add, rest, multiply and divide) |
---|
127 | varL='|' list of length of the sections for each variable within a given line (Fortran-like) |
---|
128 | |
---|
129 | NAMElon=name of the variable with the longitude (x position) |
---|
130 | NAMElat=name of the variable with the latitude (y position) |
---|
131 | NAMEheight=ind_alt |
---|
132 | NAMEtime=name of the varibale with the time |
---|
133 | FMTtime=format of the time (as in 'C', 'CFtime' for already CF-like time) |
---|
134 | |
---|
135 | """ |
---|
136 | fname = 'read_description' |
---|
137 | |
---|
138 | descobj = open(fdobs, 'r') |
---|
139 | desc = {} |
---|
140 | |
---|
141 | namevalues = [] |
---|
142 | |
---|
143 | for line in descobj: |
---|
144 | if line[0:1] != '#' and len(line) > 1 : |
---|
145 | descn = remove_NONascii(line.split('=')[0]) |
---|
146 | descv = remove_NONascii(line.split('=')[1]) |
---|
147 | namevalues.append(descn) |
---|
148 | if descn[0:3] != 'var': |
---|
149 | if descn != 'MissingValue': |
---|
150 | desc[descn] = descv |
---|
151 | else: |
---|
152 | desc[descn] = [] |
---|
153 | for dn in descv.split('|'): desc[descn].append(dn) |
---|
154 | print ' ' + fname + ': missing values found:',desc[descn] |
---|
155 | elif descn[0:3] == 'var': |
---|
156 | desc[descn] = descv.split('|') |
---|
157 | elif descn[0:4] == 'NAME': |
---|
158 | desc[descn] = descv |
---|
159 | elif descn[0:3] == 'FMT': |
---|
160 | desc[descn] = descv |
---|
161 | |
---|
162 | if dbg: |
---|
163 | Nvars = len(desc['varN']) |
---|
164 | print ' ' + fname + ": description content of '" + fdobs + "'______________" |
---|
165 | for varn in namevalues: |
---|
166 | if varn[0:3] != 'var': |
---|
167 | print ' ' + varn + ':',desc[varn] |
---|
168 | elif varn == 'varN': |
---|
169 | print ' * Variables:' |
---|
170 | for ivar in range(Nvars): |
---|
171 | varname = desc['varN'][ivar] |
---|
172 | varLname = desc['varLN'][ivar] |
---|
173 | varunits = desc['varU'][ivar] |
---|
174 | varsec = int(desc['varL'][ivar]) |
---|
175 | if desc.has_key('varBUFR'): |
---|
176 | varbufr = desc['varBUFR'][ivar] |
---|
177 | else: |
---|
178 | varbufr = None |
---|
179 | if desc['varOPER'] is not None: |
---|
180 | opv = desc['varOPER'][ivar] |
---|
181 | else: |
---|
182 | opv = None |
---|
183 | print ' ', ivar, varname+':',varLname,'[',varunits, \ |
---|
184 | ']','bufr code:',varbufr,'oper:',opv |
---|
185 | |
---|
186 | descobj.close() |
---|
187 | |
---|
188 | return desc |
---|
189 | |
---|
190 | def value_fmt(val, miss, op, fmt): |
---|
191 | """ Function to transform an ASCII value to a given format |
---|
192 | val= value to transform |
---|
193 | miss= list of possible missing values |
---|
194 | op= operation to perform to the value |
---|
195 | fmt= format to take: |
---|
196 | 'D': float double precission |
---|
197 | 'F': float |
---|
198 | 'I': integer |
---|
199 | 'I64': 64-bits integer |
---|
200 | 'S': string |
---|
201 | >>> value_fmt('9876.12', '-999', 'F') |
---|
202 | 9876.12 |
---|
203 | """ |
---|
204 | |
---|
205 | fname = 'value_fmt' |
---|
206 | |
---|
207 | aopers = ['sumc','subc','mulc','divc'] |
---|
208 | |
---|
209 | fmts = ['D', 'F', 'I', 'I64', 'S'] |
---|
210 | Nfmts = len(fmts) |
---|
211 | |
---|
212 | if not searchInlist(miss,val): |
---|
213 | if searchInlist(miss,'empty') and len(val) == 0: |
---|
214 | newval = None |
---|
215 | else: |
---|
216 | if op != '-': |
---|
217 | opern = op.split(',')[0] |
---|
218 | operv = np.float(op.split(',')[1]) |
---|
219 | |
---|
220 | if not searchInlist(aopers,opern): |
---|
221 | print errormsg |
---|
222 | print ' ' + fname + ": operation '" + opern + "' not ready!!" |
---|
223 | print ' availables:',aopers |
---|
224 | quit(-1) |
---|
225 | else: |
---|
226 | opern = 'sumc' |
---|
227 | operv = 0. |
---|
228 | |
---|
229 | if not searchInlist(fmts, fmt): |
---|
230 | print errormsg |
---|
231 | print ' ' + fname + ": format '" + fmt + "' not ready !!" |
---|
232 | quit(-1) |
---|
233 | else: |
---|
234 | if fmt == 'D': |
---|
235 | opv = np.float32(operv) |
---|
236 | if opern == 'sumc': newval = np.float32(val) + opv |
---|
237 | elif opern == 'subc': newval = np.float32(val) - opv |
---|
238 | elif opern == 'mulc': newval = np.float32(val) * opv |
---|
239 | elif opern == 'divc': newval = np.float32(val) / opv |
---|
240 | elif fmt == 'F': |
---|
241 | opv = np.float(operv) |
---|
242 | if opern == 'sumc': newval = np.float(val) + opv |
---|
243 | elif opern == 'subc': newval = np.float(val) - opv |
---|
244 | elif opern == 'mulc': newval = np.float(val) * opv |
---|
245 | elif opern == 'divc': newval = np.float(val) / opv |
---|
246 | elif fmt == 'I': |
---|
247 | opv = int(operv) |
---|
248 | if opern == 'sumc': newval = int(val) + opv |
---|
249 | elif opern == 'subc': newval = int(val) - opv |
---|
250 | elif opern == 'mulc': newval = int(val) * opv |
---|
251 | elif opern == 'divc': newval = int(val) / opv |
---|
252 | elif fmt == 'I64': |
---|
253 | opv = np.int64(operv) |
---|
254 | if opern == 'sumc': newval = np.int64(val) + opv |
---|
255 | elif opern == 'subc': newval = np.int64(val) - opv |
---|
256 | elif opern == 'mulc': newval = np.int64(val) * opv |
---|
257 | elif opern == 'divc': newval = np.int64(val) / opv |
---|
258 | elif fmt == 'S': |
---|
259 | newval = val |
---|
260 | else: |
---|
261 | newval = None |
---|
262 | |
---|
263 | return newval |
---|
264 | |
---|
265 | def writing_str_nc(varo, values, Lchar): |
---|
266 | """ Function to write string values in a netCDF variable as a chain of 1char values |
---|
267 | varo= netCDF variable object |
---|
268 | values = list of values to introduce |
---|
269 | Lchar = length of the string in the netCDF file |
---|
270 | """ |
---|
271 | |
---|
272 | Nvals = len(values) |
---|
273 | for iv in range(Nvals): |
---|
274 | if values[iv] is None: |
---|
275 | stringv = 'None' |
---|
276 | else: |
---|
277 | stringv = values[iv] |
---|
278 | charvals = np.chararray(Lchar) |
---|
279 | Lstr = len(stringv) |
---|
280 | charvals[Lstr:Lchar] = '' |
---|
281 | |
---|
282 | for ich in range(Lstr): |
---|
283 | charvals[ich] = stringv[ich:ich+1] |
---|
284 | |
---|
285 | varo[iv,:] = charvals |
---|
286 | |
---|
287 | return |
---|
288 | |
---|
289 | def Stringtimes_CF(tvals, fmt, Srefdate, tunits, dbg): |
---|
290 | """ Function to transform a given data in String formats to a CF date |
---|
291 | tvals= string temporal values |
---|
292 | fmt= format of the the time values |
---|
293 | Srefdate= reference date in [YYYY][MM][DD][HH][MI][SS] format |
---|
294 | tunits= units to use ('weeks', 'days', 'hours', 'minutes', 'seconds') |
---|
295 | dbg= debug |
---|
296 | >>> Stringtimes_CF(['19760217082712','20150213101837'], '%Y%m%d%H%M%S', |
---|
297 | '19491201000000', 'hours', False) |
---|
298 | [229784.45333333 571570.31027778] |
---|
299 | """ |
---|
300 | import datetime as dt |
---|
301 | |
---|
302 | fname = 'Stringtimes' |
---|
303 | |
---|
304 | dimt = len(tvals) |
---|
305 | |
---|
306 | yrref = int(Srefdate[0:4]) |
---|
307 | monref = int(Srefdate[4:6]) |
---|
308 | dayref = int(Srefdate[6:8]) |
---|
309 | horref = int(Srefdate[8:10]) |
---|
310 | minref = int(Srefdate[10:12]) |
---|
311 | secref = int(Srefdate[12:14]) |
---|
312 | refdate = dt.datetime( yrref, monref, dayref, horref, minref, secref) |
---|
313 | |
---|
314 | cftimes = np.zeros((dimt), dtype=np.float) |
---|
315 | |
---|
316 | Nfmt=len(fmt.split('%')) |
---|
317 | |
---|
318 | if dbg: print ' ' + fname + ': fmt=',fmt,'refdate:',Srefdate,'uits:',tunits, \ |
---|
319 | 'date dt_days dt_time deltaseconds CFtime _______' |
---|
320 | for it in range(dimt): |
---|
321 | |
---|
322 | # Removing excess of mili-seconds (up to 6 decimals) |
---|
323 | if fmt.split('%')[Nfmt-1] == 'f': |
---|
324 | tpoints = tvals[it].split('.') |
---|
325 | if len(tpoints[len(tpoints)-1]) > 6: |
---|
326 | milisec = '{0:.6f}'.format(np.float('0.'+tpoints[len(tpoints)-1]))[0:7] |
---|
327 | newtval = '' |
---|
328 | for ipt in range(len(tpoints)-1): |
---|
329 | newtval = newtval + tpoints[ipt] + '.' |
---|
330 | newtval = newtval + str(milisec)[2:len(milisec)+1] |
---|
331 | else: |
---|
332 | newtval = tvals[it] |
---|
333 | tval = dt.datetime.strptime(newtval, fmt) |
---|
334 | else: |
---|
335 | tval = dt.datetime.strptime(tvals[it], fmt) |
---|
336 | |
---|
337 | deltatime = tval - refdate |
---|
338 | deltaseconds = deltatime.days*24.*3600. + deltatime.seconds + \ |
---|
339 | deltatime.microseconds/100000. |
---|
340 | if tunits == 'weeks': |
---|
341 | deltat = 7.*24.*3600. |
---|
342 | elif tunits == 'days': |
---|
343 | deltat = 24.*3600. |
---|
344 | elif tunits == 'hours': |
---|
345 | deltat = 3600. |
---|
346 | elif tunits == 'minutes': |
---|
347 | deltat = 60. |
---|
348 | elif tunits == 'seconds': |
---|
349 | deltat = 1. |
---|
350 | else: |
---|
351 | print errormsg |
---|
352 | print ' ' + fname + ": time units '" + tunits + "' not ready !!" |
---|
353 | quit(-1) |
---|
354 | |
---|
355 | cftimes[it] = deltaseconds / deltat |
---|
356 | if dbg: |
---|
357 | print ' ' + tvals[it], deltatime, deltaseconds, cftimes[it] |
---|
358 | |
---|
359 | return cftimes |
---|
360 | |
---|
361 | def additional_vars(string): |
---|
362 | """ Function for the additional variables |
---|
363 | string: sectino of the file line which has to be evaluated |
---|
364 | """ |
---|
365 | fname = 'additional_vars' |
---|
366 | |
---|
367 | Lstring=len(string) |
---|
368 | |
---|
369 | # Generic list of additional variables '-' for range of values |
---|
370 | addvars0 = ['AA1-4', 'AB1', 'AC1', 'AD1', 'AE1', 'AG1', 'AH1-6', 'AI1-6', 'AJ1', \ |
---|
371 | 'AK1', 'AL1-4', 'AM1', 'AN1', 'AO1-4', 'AP1-4', 'HPD', 'AU1-9', 'AW1-4', \ |
---|
372 | 'AX1-6', 'AY1-2', 'AZ1-2', 'CB1-2', 'CF1-3', 'CG1-3', 'CH1-2', 'CI1', 'CN1-4', \ |
---|
373 | 'CO1-9', 'CR1', 'CT1-3', 'CU1-3', 'CV1-3', 'CW1-3', 'CX1-3', 'ED1', 'GA1-6', \ |
---|
374 | 'GE1', 'GF1', 'GG1-6', 'GH1', 'GJ1', 'GK1', 'GM1', 'GN1', 'GO1', 'GP1', 'GQ1', \ |
---|
375 | 'GR1', 'HL1', 'IA1-2', 'IB1-2', 'IC1', 'KA1-4', 'KB1-3', 'KC1-2', 'KD1-2', \ |
---|
376 | 'KE1', 'KF1', 'KG1-2', 'MA1', 'MD1', 'ME1', 'MF1', 'MG1', 'MH1', 'MK1', \ |
---|
377 | 'MV1-7', 'MW1-7', 'OA1-3', 'OB1-2', 'OC1', 'OD1-3', 'OE1-3', 'RH1-3', 'SA1', \ |
---|
378 | 'ST1', 'UA1', 'UG1-2', 'WA1', 'WD1', 'WG1', 'WJ1', 'REM', 'EQD', 'N01-99', \ |
---|
379 | 'QNN'] |
---|
380 | |
---|
381 | addvars = [] |
---|
382 | for avar in addvars0: |
---|
383 | if avar.find('-') == -1: |
---|
384 | addvars.append(avar) |
---|
385 | else: |
---|
386 | totrange=avar.split('-') |
---|
387 | erange = totrange[1] |
---|
388 | |
---|
389 | if len(erange) > 1: |
---|
390 | irange = totrange[0][1:3] |
---|
391 | else: |
---|
392 | irange = totrange[0][2:3] |
---|
393 | |
---|
394 | for ir in range(int(irange), int(erange)+1): |
---|
395 | if len(erange) > 1: |
---|
396 | addvars.append(avar[0:1] + str(ir).zfill(2)) |
---|
397 | else: |
---|
398 | addvars.append(avar[0:2] + str(ir)) |
---|
399 | |
---|
400 | # print addvars |
---|
401 | # Looking for the variables |
---|
402 | ichar=0 |
---|
403 | |
---|
404 | additionals = [] |
---|
405 | while ichar <= Lstring: |
---|
406 | sec3 = string[ichar:ichar+3] |
---|
407 | if searchInlist(addvars, sec3): |
---|
408 | additionals.append(sec3) |
---|
409 | # print ' ' , sec3, 'Additional!!' |
---|
410 | ichar = ichar + 2 |
---|
411 | |
---|
412 | ichar = ichar + 1 |
---|
413 | |
---|
414 | return additionals |
---|
415 | |
---|
416 | def read_datavalues_conline(dataf, comchar, fmt, oper, Lv, miss, varns, dbg): |
---|
417 | """ Function to read from an ASCII file values in ISH format (continuos line) |
---|
418 | dataf= data file |
---|
419 | comchar= list of the characters indicating comment in the file |
---|
420 | dbg= debug mode or not |
---|
421 | fmt= list of kind of values to be found |
---|
422 | oper= list of operations to perform |
---|
423 | Lv= length of the value section |
---|
424 | miss= missing value |
---|
425 | varns= list of name of the variables to find |
---|
426 | """ |
---|
427 | fname = 'read_datavalues_conline' |
---|
428 | |
---|
429 | ofile = open(dataf, 'r') |
---|
430 | Nvals = len(fmt) |
---|
431 | |
---|
432 | if oper is None: |
---|
433 | opers = [] |
---|
434 | for ioper in range(Nvals): |
---|
435 | opers.append('-') |
---|
436 | else: |
---|
437 | opers = oper |
---|
438 | |
---|
439 | finalvalues = {} |
---|
440 | |
---|
441 | iline = 0 |
---|
442 | for line in ofile: |
---|
443 | line = line.replace('\n','').replace(chr(13),'') |
---|
444 | Lline = len(line) |
---|
445 | if not searchInlist(comchar,line[0:1]) and len(line) > 1: |
---|
446 | # Removing no-value columns |
---|
447 | values = [] |
---|
448 | |
---|
449 | for ivar in range(Nvals): |
---|
450 | if ivar == 0: |
---|
451 | isec = 0 |
---|
452 | else: |
---|
453 | isec = int(Lv[ivar-1]) |
---|
454 | |
---|
455 | esec = int(Lv[ivar]) |
---|
456 | val = line[isec:esec] |
---|
457 | |
---|
458 | values.append(val) |
---|
459 | if dbg: |
---|
460 | print iline, varns[ivar],'value:',values[ivar],miss,opers[ivar], \ |
---|
461 | fmt[ivar] |
---|
462 | |
---|
463 | if iline == 0: |
---|
464 | listvals = [] |
---|
465 | listvals.append(value_fmt(values[ivar], miss, opers[ivar], \ |
---|
466 | fmt[ivar])) |
---|
467 | finalvalues[varns[ivar]] = listvals |
---|
468 | else: |
---|
469 | listvals = finalvalues[varns[ivar]] |
---|
470 | listvals.append(value_fmt(values[ivar], miss, opers[ivar], \ |
---|
471 | fmt[ivar])) |
---|
472 | finalvalues[varns[ivar]] = listvals |
---|
473 | # Additional variables |
---|
474 | if Lline > esec and line[esec:esec+3] == 'ADD': |
---|
475 | if iline == 0: print ' ' + fname + ': Additional variables!!' |
---|
476 | ichar=esec+3 |
---|
477 | print ' ', additional_vars(line[esec+4:Lline+1]) |
---|
478 | |
---|
479 | else: |
---|
480 | # First line without values |
---|
481 | if iline == 0: iline = -1 |
---|
482 | |
---|
483 | iline = iline + 1 |
---|
484 | |
---|
485 | ofile.close() |
---|
486 | |
---|
487 | return finalvalues |
---|
488 | |
---|
489 | def adding_station_desc(onc,stdesc): |
---|
490 | """ Function to add a station description in a netCDF file |
---|
491 | onc= netCDF object |
---|
492 | stdesc= station description lon, lat, height |
---|
493 | """ |
---|
494 | fname = 'adding_station_desc' |
---|
495 | |
---|
496 | newvar = onc.createVariable( 'station', 'c', ('StrLength')) |
---|
497 | newvar[0:len(stdesc[0])] = stdesc[0].replace('!', ' ') |
---|
498 | |
---|
499 | newdim = onc.createDimension('nst',1) |
---|
500 | |
---|
501 | newvar = objfile.createVariable( 'lonstGDM', 'c', ('nst','StrLength')) |
---|
502 | Gv = int(stdesc[1]) |
---|
503 | Dv = int((stdesc[1] - Gv)*60.) |
---|
504 | Mv = int((stdesc[1] - Gv - Dv/60.)*3600.) |
---|
505 | writing_str_nc(newvar, [str(Gv)+"d" + str(Dv)+"m" + str(Mv)+'s'], StringLength) |
---|
506 | |
---|
507 | if onc.variables.has_key('lon'): |
---|
508 | print warnmsg |
---|
509 | print ' ' + fname + ": variable 'lon' already exist !!" |
---|
510 | print " renaming it as 'lonst'" |
---|
511 | lonname = 'lonst' |
---|
512 | else: |
---|
513 | lonname = 'lon' |
---|
514 | |
---|
515 | newvar = onc.createVariable( lonname, 'f4', ('nst')) |
---|
516 | basicvardef(newvar, lonname, 'longitude', 'degrees_West' ) |
---|
517 | newvar[:] = stdesc[1] |
---|
518 | |
---|
519 | newvar = objfile.createVariable( 'latstGDM', 'c', ('nst','StrLength')) |
---|
520 | Gv = int(stdesc[2]) |
---|
521 | Dv = int((stdesc[2] - Gv)*60.) |
---|
522 | Mv = int((stdesc[2] - Gv - Dv/60.)*3600.) |
---|
523 | writing_str_nc(newvar, [str(Gv)+"d" + str(Dv)+"m" + str(Mv)+'s'], StringLength) |
---|
524 | |
---|
525 | if onc.variables.has_key('lat'): |
---|
526 | print warnmsg |
---|
527 | print ' ' + fname + ": variable 'lat' already exist !!" |
---|
528 | print " renaming it as 'latst'" |
---|
529 | latname = 'latst' |
---|
530 | else: |
---|
531 | latname = 'lat' |
---|
532 | |
---|
533 | newvar = onc.createVariable( latname, 'f4', ('nst')) |
---|
534 | basicvardef(newvar, lonname, 'latitude', 'degrees_North' ) |
---|
535 | newvar[:] = stdesc[2] |
---|
536 | |
---|
537 | if onc.variables.has_key('height'): |
---|
538 | print warnmsg |
---|
539 | print ' ' + fname + ": variable 'height' already exist !!" |
---|
540 | print " renaming it as 'heightst'" |
---|
541 | heightname = 'heightst' |
---|
542 | else: |
---|
543 | heightname = 'height' |
---|
544 | |
---|
545 | newvar = onc.createVariable( heightname, 'f4', ('nst')) |
---|
546 | basicvardef(newvar, heightname, 'height above sea level', 'm' ) |
---|
547 | newvar[:] = stdesc[3] |
---|
548 | |
---|
549 | return |
---|
550 | |
---|
551 | ####### ###### ##### #### ### ## # |
---|
552 | |
---|
553 | strCFt="Refdate,tunits (CF reference date [YYYY][MM][DD][HH][MI][SS] format and " + \ |
---|
554 | " and time units: 'weeks', 'days', 'hours', 'miuntes', 'seconds')" |
---|
555 | |
---|
556 | parser = OptionParser() |
---|
557 | parser.add_option("-c", "--comments", dest="charcom", |
---|
558 | help="':', list of characters used for comments", metavar="VALUES") |
---|
559 | parser.add_option("-d", "--descriptionfile", dest="fdesc", |
---|
560 | help="description file to use", metavar="FILE") |
---|
561 | parser.add_option("-f", "--file", dest="obsfile", |
---|
562 | help="observational file to use", metavar="FILE") |
---|
563 | parser.add_option("-g", "--debug", dest="debug", |
---|
564 | help="whther debug is required ('false', 'true')", metavar="VALUE") |
---|
565 | parser.add_option("-s", "--stationLocation", dest="stloc", |
---|
566 | help="',' list with Name, longitude, latitude and height of the station", metavar="VALUES") |
---|
567 | parser.add_option("-t", "--CFtime", dest="CFtime", help=strCFt, metavar="VALUE") |
---|
568 | (opts, args) = parser.parse_args() |
---|
569 | |
---|
570 | ####### ####### |
---|
571 | ## MAIN |
---|
572 | ####### |
---|
573 | |
---|
574 | ofile='ISD.nc' |
---|
575 | |
---|
576 | if opts.charcom is None: |
---|
577 | print warnmsg |
---|
578 | print ' ' + main + ': No list of comment characters provided!!' |
---|
579 | print ' assuming no need!' |
---|
580 | charcomments = [] |
---|
581 | else: |
---|
582 | charcomments = opts.charcom.split(':') |
---|
583 | |
---|
584 | if opts.fdesc is None: |
---|
585 | print errormsg |
---|
586 | print ' ' + main + ': No description file for the observtional data provided!!' |
---|
587 | quit(-1) |
---|
588 | |
---|
589 | if opts.obsfile is None: |
---|
590 | print errormsg |
---|
591 | print ' ' + main + ': ISD file not provided !!' |
---|
592 | quit(-1) |
---|
593 | |
---|
594 | if opts.debug is None: |
---|
595 | print warnmsg |
---|
596 | print ' ' + main + ': No debug provided!!' |
---|
597 | print " assuming 'False'" |
---|
598 | debug = False |
---|
599 | else: |
---|
600 | if opts.debug == 'true': |
---|
601 | debug = True |
---|
602 | else: |
---|
603 | debug = False |
---|
604 | |
---|
605 | if not os.path.isfile(opts.fdesc): |
---|
606 | print errormsg |
---|
607 | print ' ' + main + ": description file '" + opts.fdesc + "' does not exist !!" |
---|
608 | quit(-1) |
---|
609 | |
---|
610 | if not os.path.isfile(opts.obsfile): |
---|
611 | print errormsg |
---|
612 | print ' ' + main + ": observational file '" + opts.obsfile + "' does not exist !!" |
---|
613 | quit(-1) |
---|
614 | |
---|
615 | if opts.CFtime is None: |
---|
616 | print warnmsg |
---|
617 | print ' ' + main + ': No CFtime criteria are provided !!' |
---|
618 | print " either time is already in CF-format ('timeFMT=CFtime') in '" + \ |
---|
619 | opts.fdesc + "'" |
---|
620 | print " or assuming refdate: '19491201000000' and time units: 'hours'" |
---|
621 | referencedate = '19491201000000' |
---|
622 | timeunits = 'hours' |
---|
623 | else: |
---|
624 | referencedate = opts.CFtime.split(',')[0] |
---|
625 | timeunits = opts.CFtime.split(',')[1] |
---|
626 | |
---|
627 | if opts.stloc is None: |
---|
628 | print errornmsg |
---|
629 | print ' ' + main + ': No station location provided !!' |
---|
630 | quit(-1) |
---|
631 | else: |
---|
632 | print opts.stloc.split(',') |
---|
633 | stationdesc = [opts.stloc.split(',')[0], np.float(opts.stloc.split(',')[1]), \ |
---|
634 | np.float(opts.stloc.split(',')[2]), np.float(opts.stloc.split(',')[3])] |
---|
635 | |
---|
636 | # Reading description file |
---|
637 | ## |
---|
638 | description = read_description(opts.fdesc, debug) |
---|
639 | |
---|
640 | Nvariables=len(description['varN']) |
---|
641 | formats = description['varTYPE'] |
---|
642 | |
---|
643 | if len(formats) != Nvariables: |
---|
644 | print errormsg |
---|
645 | print ' ' + main + ': number of formats:',len(formats),' and number of ' + \ |
---|
646 | 'variables', Nvariables,' does not coincide!!' |
---|
647 | print ' * what is found is _______' |
---|
648 | if Nvariables > len(formats): |
---|
649 | Nshow = len(formats) |
---|
650 | for ivar in range(Nshow): |
---|
651 | print ' ',description['varN'][ivar],':', description['varLN'][ivar],\ |
---|
652 | '[', description['varU'][ivar], '] fmt:', formats[ivar] |
---|
653 | print ' missing values for:', description['varN'][Nshow:Nvariables+1] |
---|
654 | else: |
---|
655 | Nshow = Nvariables |
---|
656 | for ivar in range(Nshow): |
---|
657 | print ' ',description['varN'][ivar],':', description['varLN'][ivar],\ |
---|
658 | '[', description['varU'][ivar], '] fmt:', formats[ivar] |
---|
659 | print ' excess of formats for:', formats[Nshow:len(formats)+1] |
---|
660 | |
---|
661 | quit(-1) |
---|
662 | |
---|
663 | # Reading values |
---|
664 | ## |
---|
665 | datavalues = read_datavalues_conline(opts.obsfile, charcomments, formats, \ |
---|
666 | description['varOPER'], description['varL'], description['MissingValue'], \ |
---|
667 | description['varN'], debug) |
---|
668 | |
---|
669 | # Total number of values |
---|
670 | Ntvalues = len(datavalues[description['varN'][0]]) |
---|
671 | print main + ': total temporal values found:',Ntvalues |
---|
672 | |
---|
673 | objfile = NetCDFFile(ofile, 'w') |
---|
674 | |
---|
675 | # Creation of dimensions |
---|
676 | ## |
---|
677 | objfile.createDimension('time',None) |
---|
678 | objfile.createDimension('StrLength',StringLength) |
---|
679 | |
---|
680 | # Creation of variables |
---|
681 | ## |
---|
682 | for ivar in range(Nvariables): |
---|
683 | varn = description['varN'][ivar] |
---|
684 | print " including: '" + varn + "' ... .. ." |
---|
685 | |
---|
686 | if formats[ivar] == 'D': |
---|
687 | newvar = objfile.createVariable(varn, 'f32', ('time'), fill_value=fillValueF) |
---|
688 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
689 | description['varU'][ivar]) |
---|
690 | vals = np.array(datavalues[varn]) |
---|
691 | for iv in range(Ntvalues): |
---|
692 | if vals[iv] is None: vals[iv] = fillValueF |
---|
693 | newvar[:] = vals |
---|
694 | # newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn]) |
---|
695 | elif formats[ivar] == 'F': |
---|
696 | newvar = objfile.createVariable(varn, 'f', ('time'), fill_value=fillValueF) |
---|
697 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
698 | description['varU'][ivar]) |
---|
699 | vals = np.array(datavalues[varn]) |
---|
700 | for iv in range(Ntvalues): |
---|
701 | if vals[iv] is None: vals[iv] = fillValueF |
---|
702 | newvar[:] = vals |
---|
703 | # newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn]) |
---|
704 | elif formats[ivar] == 'I': |
---|
705 | newvar = objfile.createVariable(varn, 'i', ('time'), fill_value=fillValueI) |
---|
706 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
707 | description['varU'][ivar]) |
---|
708 | # Why is not wotking with integers? |
---|
709 | vals = np.array(datavalues[varn]) |
---|
710 | for iv in range(Ntvalues): |
---|
711 | if vals[iv] is None: vals[iv] = fillValueI |
---|
712 | newvar[:] = vals |
---|
713 | elif formats[ivar] == 'S': |
---|
714 | newvar = objfile.createVariable(varn, 'c', ('time','StrLength')) |
---|
715 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
716 | description['varU'][ivar]) |
---|
717 | writing_str_nc(newvar, datavalues[varn], StringLength) |
---|
718 | |
---|
719 | # Time variable in CF format |
---|
720 | ## |
---|
721 | if description['FMTtime'] == 'CFtime': |
---|
722 | timevals = datavalues[description['NAMEtime']] |
---|
723 | iv = 0 |
---|
724 | for ivn in description['varN']: |
---|
725 | if ivn == description['NAMEtime']: |
---|
726 | tunits = description['varU'][iv] |
---|
727 | break |
---|
728 | iv = iv + 1 |
---|
729 | else: |
---|
730 | # Time as a composition of different columns |
---|
731 | tcomposite = description['NAMEtime'].find('@') |
---|
732 | if tcomposite != -1: |
---|
733 | timevars = description['NAMEtime'].split('@') |
---|
734 | |
---|
735 | print warnmsg |
---|
736 | print ' ' + main + ': time values as combination of different columns!' |
---|
737 | print ' combining:',timevars,' with a final format: ',description['FMTtime'] |
---|
738 | |
---|
739 | timeSvals = [] |
---|
740 | if debug: print ' ' + main + ': creating times _______' |
---|
741 | for it in range(Ntvalues): |
---|
742 | tSvals = '' |
---|
743 | for tvar in timevars: |
---|
744 | tSvals = tSvals + datavalues[tvar][it] + ' ' |
---|
745 | |
---|
746 | timeSvals.append(tSvals[0:len(tSvals)-1]) |
---|
747 | if debug: print it, '*' + timeSvals[it] + '*' |
---|
748 | |
---|
749 | timevals = Stringtimes_CF(timeSvals, description['FMTtime'], referencedate, \ |
---|
750 | timeunits, debug) |
---|
751 | else: |
---|
752 | timevals = Stringtimes_CF(datavalues[description['NAMEtime']], \ |
---|
753 | description['FMTtime'], referencedate, timeunits, debug) |
---|
754 | |
---|
755 | CFtimeRef = referencedate[0:4] +'-'+ referencedate[4:6] +'-'+ referencedate[6:8] + \ |
---|
756 | ' ' + referencedate[8:10] +':'+ referencedate[10:12] +':'+ referencedate[12:14] |
---|
757 | tunits = timeunits + ' since ' + CFtimeRef |
---|
758 | |
---|
759 | if objfile.variables.has_key('time'): |
---|
760 | print warnmsg |
---|
761 | print ' ' + main + ": variable 'time' already exist !!" |
---|
762 | print " renaming it as 'CFtime'" |
---|
763 | timeCFname = 'CFtime' |
---|
764 | newdim = objfile.renameDimension('time','CFtime') |
---|
765 | newvar = objfile.createVariable( timeCFname, 'f8', ('CFtime')) |
---|
766 | basicvardef(newvar, timeCFname, 'time', tunits ) |
---|
767 | else: |
---|
768 | timeCFname = 'time' |
---|
769 | newvar = objfile.createVariable( timeCFname, 'f8', ('time')) |
---|
770 | basicvardef(newvar, timeCFname, 'time', tunits ) |
---|
771 | |
---|
772 | set_attribute(newvar, 'calendar', 'standard') |
---|
773 | newvar[:] = timevals |
---|
774 | |
---|
775 | # Global attributes |
---|
776 | ## |
---|
777 | for descn in description.keys(): |
---|
778 | if descn[0:3] != 'var' and descn[0:4] != 'NAME' and descn[0:3] != 'FMT': |
---|
779 | string='' |
---|
780 | for sval in description[descn]: |
---|
781 | string = string + str(sval) + ', ' |
---|
782 | set_attribute(objfile, descn, string) |
---|
783 | |
---|
784 | set_attribute(objfile,'author_nc','Lluis Fita') |
---|
785 | set_attribute(objfile,'institution_nc','Laboratoire de Meteorology Dynamique, ' + \ |
---|
786 | 'LMD-Jussieu, UPMC, Paris') |
---|
787 | set_attribute(objfile,'country_nc','France') |
---|
788 | set_attribute(objfile,'script_nc',main) |
---|
789 | set_attribute(objfile,'version_script',version) |
---|
790 | |
---|
791 | # Adding three variables with the station name, location, longitude, latitude and height |
---|
792 | adding_station_desc(objfile,stationdesc) |
---|
793 | |
---|
794 | objfile.sync() |
---|
795 | objfile.close() |
---|
796 | |
---|
797 | print main + ": Successfull generation of netcdf observational file '" + ofile + "' !!" |
---|