1 | # -*- coding: iso-8859-15 -*- |
---|
2 | # Generic program to transfrom ASCII observational data in columns to a netcdf |
---|
3 | # L. Fita, LMD February 2015 |
---|
4 | ## e.g. # create_OBSnetcdf.py -c '#' -d ACAR/description.dat -e space -f ACAR/2012/10/ACAR_121018.asc -g true -t 19491201000000,seconds -k trajectory |
---|
5 | |
---|
6 | import numpy as np |
---|
7 | from netCDF4 import Dataset as NetCDFFile |
---|
8 | import os |
---|
9 | import re |
---|
10 | from optparse import OptionParser |
---|
11 | |
---|
12 | # version |
---|
13 | version=1.1 |
---|
14 | |
---|
15 | # Filling values for floats, integer and string |
---|
16 | fillValueF = 1.e20 |
---|
17 | fillValueI = -99999 |
---|
18 | fillValueS = '---' |
---|
19 | |
---|
20 | # Length of the string variables |
---|
21 | StringLength = 200 |
---|
22 | |
---|
23 | # Size of the map for the complementary variables/maps |
---|
24 | Ndim2D = 100 |
---|
25 | |
---|
26 | main = 'create_OBSnetcdf.py' |
---|
27 | errormsg = 'ERROR -- error -- ERROR -- error' |
---|
28 | warnmsg = 'WARNING -- warning -- WARNING -- warning' |
---|
29 | |
---|
30 | fillValue = 1.e20 |
---|
31 | |
---|
32 | def searchInlist(listname, nameFind): |
---|
33 | """ Function to search a value within a list |
---|
34 | listname = list |
---|
35 | nameFind = value to find |
---|
36 | >>> searInlist(['1', '2', '3', '5'], '5') |
---|
37 | True |
---|
38 | """ |
---|
39 | for x in listname: |
---|
40 | if x == nameFind: |
---|
41 | return True |
---|
42 | return False |
---|
43 | |
---|
44 | def set_attribute(ncvar, attrname, attrvalue): |
---|
45 | """ Sets a value of an attribute of a netCDF variable. Removes previous attribute value if exists |
---|
46 | ncvar = object netcdf variable |
---|
47 | attrname = name of the attribute |
---|
48 | attrvalue = value of the attribute |
---|
49 | """ |
---|
50 | import numpy as np |
---|
51 | from netCDF4 import Dataset as NetCDFFile |
---|
52 | |
---|
53 | attvar = ncvar.ncattrs() |
---|
54 | if searchInlist(attvar, attrname): |
---|
55 | attr = ncvar.delncattr(attrname) |
---|
56 | |
---|
57 | attr = ncvar.setncattr(attrname, attrvalue) |
---|
58 | |
---|
59 | return ncvar |
---|
60 | |
---|
61 | def basicvardef(varobj, vstname, vlname, vunits): |
---|
62 | """ Function to give the basic attributes to a variable |
---|
63 | varobj= netCDF variable object |
---|
64 | vstname= standard name of the variable |
---|
65 | vlname= long name of the variable |
---|
66 | vunits= units of the variable |
---|
67 | """ |
---|
68 | attr = varobj.setncattr('standard_name', vstname) |
---|
69 | attr = varobj.setncattr('long_name', vlname) |
---|
70 | attr = varobj.setncattr('units', vunits) |
---|
71 | |
---|
72 | return |
---|
73 | |
---|
74 | def remove_NONascii(string): |
---|
75 | """ Function to remove that characters which are not in the standard 127 ASCII |
---|
76 | string= string to transform |
---|
77 | >>> remove_NONascii('LluÃs') |
---|
78 | Lluis |
---|
79 | """ |
---|
80 | fname = 'remove_NONascii' |
---|
81 | |
---|
82 | newstring = string |
---|
83 | |
---|
84 | RTFchar= ['á', 'é', 'Ã', 'ó', 'ú', 'à ', 'Ú', 'ì', 'ò', 'ù', 'â', 'ê', 'î', 'ÃŽ', \ |
---|
85 | 'û', 'À', 'ë', 'ï', 'ö', 'ÃŒ', 'ç', 'ñ','Ê', 'Å', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', \ |
---|
86 | 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã', 'Ã',\ |
---|
87 | 'Ã', 'Å', '\n', '\t'] |
---|
88 | ASCchar= ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', \ |
---|
89 | 'u', 'a', 'e', 'i', 'o', 'u', 'c', 'n','ae', 'oe', 'A', 'E', 'I', 'O', 'U', 'A', \ |
---|
90 | 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'A', 'E', 'I', 'O', 'U', 'C', 'N',\ |
---|
91 | 'AE', 'OE', '', ' '] |
---|
92 | |
---|
93 | Nchars = len(RTFchar) |
---|
94 | for ichar in range(Nchars): |
---|
95 | foundchar = string.find(RTFchar[ichar]) |
---|
96 | if foundchar != -1: |
---|
97 | newstring = newstring.replace(RTFchar[ichar], ASCchar[ichar]) |
---|
98 | |
---|
99 | return newstring |
---|
100 | |
---|
101 | def read_description(fdobs, dbg): |
---|
102 | """ reads the description file of the observational data-set |
---|
103 | fdobs= descriptive observational data-set |
---|
104 | dbg= boolean argument for debugging |
---|
105 | * Each station should have a 'description.dat' file with: |
---|
106 | institution=Institution who creates the data |
---|
107 | department=Department within the institution |
---|
108 | scientists=names of the data producers |
---|
109 | contact=contact of the data producers |
---|
110 | description=description of the observations |
---|
111 | acknowledgement=sentence of acknowlegement |
---|
112 | comment=comment for the measurements |
---|
113 | |
---|
114 | MissingValue='|' list of ASCII values for missing values within the data |
---|
115 | (as they appear!) |
---|
116 | comment=comments |
---|
117 | |
---|
118 | varN='|' list of variable names |
---|
119 | varLN='|' list of long variable names |
---|
120 | varU='|' list units of the variables |
---|
121 | varBUFR='|' list BUFR code of the variables |
---|
122 | varTYPE='|' list of variable types ('D', 'F', 'I', 'I64', 'S') |
---|
123 | |
---|
124 | NAMElon=name of the variable with the longitude (x position) |
---|
125 | NAMElat=name of the variable with the latitude (y position) |
---|
126 | NAMEheight=ind_alt |
---|
127 | NAMEtime=name of the varibale with the time |
---|
128 | FMTtime=format of the time (as in 'C', 'CFtime' for already CF-like time) |
---|
129 | |
---|
130 | """ |
---|
131 | fname = 'read_description' |
---|
132 | |
---|
133 | descobj = open(fdobs, 'r') |
---|
134 | desc = {} |
---|
135 | |
---|
136 | namevalues = [] |
---|
137 | |
---|
138 | for line in descobj: |
---|
139 | if line[0:1] != '#' and len(line) > 1 : |
---|
140 | descn = remove_NONascii(line.split('=')[0]) |
---|
141 | descv = remove_NONascii(line.split('=')[1]) |
---|
142 | namevalues.append(descn) |
---|
143 | if descn[0:3] != 'var': |
---|
144 | if descn != 'MissingValue': |
---|
145 | desc[descn] = descv |
---|
146 | else: |
---|
147 | desc[descn] = [] |
---|
148 | for dn in descv.split('|'): desc[descn].append(dn) |
---|
149 | print ' ' + fname + ': missing values found:',desc[descn] |
---|
150 | elif descn[0:3] == 'var': |
---|
151 | desc[descn] = descv.split('|') |
---|
152 | elif descn[0:4] == 'NAME': |
---|
153 | desc[descn] = descv |
---|
154 | elif descn[0:3] == 'FMT': |
---|
155 | desc[descn] = descv |
---|
156 | |
---|
157 | if dbg: |
---|
158 | Nvars = len(desc['varN']) |
---|
159 | print ' ' + fname + ": description content of '" + fdobs + "'______________" |
---|
160 | for varn in namevalues: |
---|
161 | if varn[0:3] != 'var': |
---|
162 | print ' ' + varn + ':',desc[varn] |
---|
163 | elif varn == 'varN': |
---|
164 | print ' * Variables:' |
---|
165 | for ivar in range(Nvars): |
---|
166 | varname = desc['varN'][ivar] |
---|
167 | varLname = desc['varLN'][ivar] |
---|
168 | varunits = desc['varU'][ivar] |
---|
169 | if desc.has_key('varBUFR'): |
---|
170 | varbufr=[ivar] |
---|
171 | print ' ', ivar, varname + ':',varLname,'[',varunits, \ |
---|
172 | ']','bufr code:',varbufr |
---|
173 | else: |
---|
174 | print ' ', ivar, varname + ':',varLname,'[',varunits,']' |
---|
175 | |
---|
176 | descobj.close() |
---|
177 | |
---|
178 | return desc |
---|
179 | |
---|
180 | def value_fmt(val, miss, fmt): |
---|
181 | """ Function to transform an ASCII value to a given format |
---|
182 | val= value to transform |
---|
183 | miss= list of possible missing values |
---|
184 | fmt= format to take: |
---|
185 | 'D': float double precission |
---|
186 | 'F': float |
---|
187 | 'I': integer |
---|
188 | 'I64': 64-bits integer |
---|
189 | 'S': string |
---|
190 | >>> value_fmt('9876.12', '-999', 'F') |
---|
191 | 9876.12 |
---|
192 | """ |
---|
193 | |
---|
194 | fname = 'value_fmt' |
---|
195 | |
---|
196 | fmts = ['D', 'F', 'I', 'I64', 'S'] |
---|
197 | Nfmts = len(fmts) |
---|
198 | |
---|
199 | if not searchInlist(miss,val): |
---|
200 | if not searchInlist(fmts, fmt): |
---|
201 | print errormsg |
---|
202 | print ' ' + fname + ": format '" + fmt + "' not ready !!" |
---|
203 | quit(-1) |
---|
204 | else: |
---|
205 | if fmt == 'D': |
---|
206 | newval = np.float32(val) |
---|
207 | elif fmt == 'F': |
---|
208 | newval = np.float(val) |
---|
209 | elif fmt == 'I': |
---|
210 | newval = int(val) |
---|
211 | elif fmt == 'I64': |
---|
212 | newval = np.int64(val) |
---|
213 | elif fmt == 'S': |
---|
214 | newval = val |
---|
215 | else: |
---|
216 | newval = None |
---|
217 | |
---|
218 | return newval |
---|
219 | |
---|
220 | def read_datavalues(dataf, comchar, colchar, fmt, miss, varns, dbg): |
---|
221 | """ Function to read from an ASCII file values in column |
---|
222 | dataf= data file |
---|
223 | comchar= list of the characters indicating comment in the file |
---|
224 | colchar= character which indicate end of value in the column |
---|
225 | dbg= debug mode or not |
---|
226 | fmt= list of kind of values to be found |
---|
227 | miss= missing value |
---|
228 | varns= list of name of the variables to find |
---|
229 | """ |
---|
230 | |
---|
231 | fname = 'read_datavalues' |
---|
232 | |
---|
233 | ofile = open(dataf, 'r') |
---|
234 | Nvals = len(fmt) |
---|
235 | |
---|
236 | finalvalues = {} |
---|
237 | |
---|
238 | iline = 0 |
---|
239 | for line in ofile: |
---|
240 | line = line.replace('\n','').replace(chr(13),'') |
---|
241 | if not searchInlist(comchar,line[0:1]) and len(line) > 1: |
---|
242 | values0 = line.split(colchar) |
---|
243 | # Removing no-value columns |
---|
244 | values = [] |
---|
245 | for iv in values0: |
---|
246 | if len(iv) > 0: values.append(iv) |
---|
247 | |
---|
248 | Nvalues = len(values) |
---|
249 | # Checkings for wierd characters at the end of lines (use it to check) |
---|
250 | # if values[Nvalues-1][0:4] == '-999': |
---|
251 | # print line,'last v:',values[Nvalues-1],'len:',len(values[Nvalues-1]) |
---|
252 | # for ic in range(len(values[Nvalues-1])): |
---|
253 | # print ic,ord(values[Nvalues-1][ic:ic+1]) |
---|
254 | # quit() |
---|
255 | |
---|
256 | if len(values[Nvalues-1]) == 0: |
---|
257 | Nvalues = Nvalues - 1 |
---|
258 | |
---|
259 | if Nvalues != Nvals: |
---|
260 | print warnmsg |
---|
261 | print ' ' + fname + ': number of formats:',Nvals,' and number of ', \ |
---|
262 | 'values:',Nvalues,' with split character *' + colchar + \ |
---|
263 | '* does not coincide!!' |
---|
264 | print ' * what is found is ________' |
---|
265 | if Nvalues > Nvals: |
---|
266 | Nshow = Nvals |
---|
267 | for ivar in range(Nshow): |
---|
268 | print ' ',varns[ivar],'fmt:',fmt[ivar],'value:',values[ivar] |
---|
269 | print ' missing formats for:',values[Nshow:Nvalues+1] |
---|
270 | print ' values not considered, continue' |
---|
271 | else: |
---|
272 | Nshow = Nvalues |
---|
273 | for ivar in range(Nshow): |
---|
274 | print ' ',varns[ivar],'fmt:',fmt[ivar],'value:',values[ivar] |
---|
275 | print ' excess of formats:',fmt[Nshow:Nvals+1] |
---|
276 | quit(-1) |
---|
277 | |
---|
278 | # Reading and transforming values |
---|
279 | if dbg: print ' ' + fname + ': values found _________' |
---|
280 | |
---|
281 | for ivar in range(Nvals): |
---|
282 | if dbg: |
---|
283 | print iline, varns[ivar],'value:',values[ivar],miss,fmt[ivar] |
---|
284 | |
---|
285 | if iline == 0: |
---|
286 | listvals = [] |
---|
287 | listvals.append(value_fmt(values[ivar], miss, fmt[ivar])) |
---|
288 | finalvalues[varns[ivar]] = listvals |
---|
289 | else: |
---|
290 | listvals = finalvalues[varns[ivar]] |
---|
291 | listvals.append(value_fmt(values[ivar], miss, fmt[ivar])) |
---|
292 | finalvalues[varns[ivar]] = listvals |
---|
293 | else: |
---|
294 | # First line without values |
---|
295 | if iline == 0: iline = -1 |
---|
296 | |
---|
297 | iline = iline + 1 |
---|
298 | |
---|
299 | ofile.close() |
---|
300 | |
---|
301 | return finalvalues |
---|
302 | |
---|
303 | def writing_str_nc(varo, values, Lchar): |
---|
304 | """ Function to write string values in a netCDF variable as a chain of 1char values |
---|
305 | varo= netCDF variable object |
---|
306 | values = list of values to introduce |
---|
307 | Lchar = length of the string in the netCDF file |
---|
308 | """ |
---|
309 | |
---|
310 | Nvals = len(values) |
---|
311 | for iv in range(Nvals): |
---|
312 | stringv=values[iv] |
---|
313 | charvals = np.chararray(Lchar) |
---|
314 | Lstr = len(stringv) |
---|
315 | charvals[Lstr:Lchar] = '' |
---|
316 | |
---|
317 | for ich in range(Lstr): |
---|
318 | charvals[ich] = stringv[ich:ich+1] |
---|
319 | |
---|
320 | varo[iv,:] = charvals |
---|
321 | |
---|
322 | return |
---|
323 | |
---|
324 | def Stringtimes_CF(tvals, fmt, Srefdate, tunits, dbg): |
---|
325 | """ Function to transform a given data in String formats to a CF date |
---|
326 | tvals= string temporal values |
---|
327 | fmt= format of the the time values |
---|
328 | Srefdate= reference date in [YYYY][MM][DD][HH][MI][SS] format |
---|
329 | tunits= units to use ('weeks', 'days', 'hours', 'minutes', 'seconds') |
---|
330 | dbg= debug |
---|
331 | >>> Stringtimes_CF(['19760217082712','20150213101837'], '%Y%m%d%H%M%S', |
---|
332 | '19491201000000', 'hours', False) |
---|
333 | [229784.45333333 571570.31027778] |
---|
334 | """ |
---|
335 | import datetime as dt |
---|
336 | |
---|
337 | fname = 'Stringtimes' |
---|
338 | |
---|
339 | dimt = len(tvals) |
---|
340 | |
---|
341 | yrref = int(Srefdate[0:4]) |
---|
342 | monref = int(Srefdate[4:6]) |
---|
343 | dayref = int(Srefdate[6:8]) |
---|
344 | horref = int(Srefdate[8:10]) |
---|
345 | minref = int(Srefdate[10:12]) |
---|
346 | secref = int(Srefdate[12:14]) |
---|
347 | refdate = dt.datetime( yrref, monref, dayref, horref, minref, secref) |
---|
348 | |
---|
349 | cftimes = np.zeros((dimt), dtype=np.float) |
---|
350 | |
---|
351 | Nfmt=len(fmt.split('%')) |
---|
352 | |
---|
353 | if dbg: print ' ' + fname + ': fmt=',fmt,'refdate:',Srefdate,'uits:',tunits, \ |
---|
354 | 'date dt_days dt_time deltaseconds CFtime _______' |
---|
355 | for it in range(dimt): |
---|
356 | |
---|
357 | # Removing excess of mili-seconds (up to 6 decimals) |
---|
358 | if fmt.split('%')[Nfmt-1] == 'f': |
---|
359 | tpoints = tvals[it].split('.') |
---|
360 | if len(tpoints[len(tpoints)-1]) > 6: |
---|
361 | milisec = '{0:.6f}'.format(np.float('0.'+tpoints[len(tpoints)-1]))[0:7] |
---|
362 | newtval = '' |
---|
363 | for ipt in range(len(tpoints)-1): |
---|
364 | newtval = newtval + tpoints[ipt] + '.' |
---|
365 | newtval = newtval + str(milisec)[2:len(milisec)+1] |
---|
366 | else: |
---|
367 | newtval = tvals[it] |
---|
368 | tval = dt.datetime.strptime(newtval, fmt) |
---|
369 | else: |
---|
370 | tval = dt.datetime.strptime(tvals[it], fmt) |
---|
371 | |
---|
372 | deltatime = tval - refdate |
---|
373 | deltaseconds = deltatime.days*24.*3600. + deltatime.seconds + \ |
---|
374 | deltatime.microseconds/100000. |
---|
375 | if tunits == 'weeks': |
---|
376 | deltat = 7.*24.*3600. |
---|
377 | elif tunits == 'days': |
---|
378 | deltat = 24.*3600. |
---|
379 | elif tunits == 'hours': |
---|
380 | deltat = 3600. |
---|
381 | elif tunits == 'minutes': |
---|
382 | deltat = 60. |
---|
383 | elif tunits == 'seconds': |
---|
384 | deltat = 1. |
---|
385 | else: |
---|
386 | print errormsg |
---|
387 | print ' ' + fname + ": time units '" + tunits + "' not ready !!" |
---|
388 | quit(-1) |
---|
389 | |
---|
390 | cftimes[it] = deltaseconds / deltat |
---|
391 | if dbg: |
---|
392 | print ' ' + tvals[it], deltatime, deltaseconds, cftimes[it] |
---|
393 | |
---|
394 | return cftimes |
---|
395 | |
---|
396 | def adding_complementary(onc, dscn, okind, dvalues, tvals, refCFt, CFtu, Nd, dbg): |
---|
397 | """ Function to add complementary variables as function of the observational type |
---|
398 | onc= netcdf objecto file to add the variables |
---|
399 | dscn= description dictionary |
---|
400 | okind= observational kind |
---|
401 | dvalues= values |
---|
402 | tvals= CF time values |
---|
403 | refCFt= reference time of CF time (in [YYYY][MM][DD][HH][MI][SS]) |
---|
404 | CFtu= CF time units |
---|
405 | Nd= size of the domain |
---|
406 | dbg= debugging flag |
---|
407 | """ |
---|
408 | import numpy.ma as ma |
---|
409 | |
---|
410 | fname = 'adding_complementary' |
---|
411 | |
---|
412 | # Kind of observations which require de integer lon/lat (for the 2D map) |
---|
413 | map2D=['multi-points', 'trajectory'] |
---|
414 | |
---|
415 | SrefCFt = refCFt[0:4] +'-'+ refCFt[4:6] +'-'+ refCFt[6:8] + ' ' + refCFt[8:10] + \ |
---|
416 | ':'+ refCFt[10:12] +':'+ refCFt[12:14] |
---|
417 | |
---|
418 | if dscn['NAMElon'] == '-' or dscn['NAMElat'] == '-': |
---|
419 | print errormsg |
---|
420 | print ' ' + fname + ": to complement a '" + okind + "' observation kind " + \ |
---|
421 | " a given longitude ('NAMElon':",dscn['NAMElon'],") and latitude ('" + \ |
---|
422 | "'NAMElat:'", dscn['NAMElat'],') from the data has to be provided and ' + \ |
---|
423 | 'any are given !!' |
---|
424 | quit(-1) |
---|
425 | |
---|
426 | if not dvalues.has_key(dscn['NAMElon']) or not dvalues.has_key(dscn['NAMElat']): |
---|
427 | print errormsg |
---|
428 | print ' ' + fname + ": observations do not have 'NAMElon':", \ |
---|
429 | dscn['NAMElon'],"and/or 'NAMElat:'", dscn['NAMElat'],' !!' |
---|
430 | print ' available data:',dvalues.keys() |
---|
431 | quit(-1) |
---|
432 | |
---|
433 | if okind == 'trajectory': |
---|
434 | if dscn['NAMEheight'] == '-': |
---|
435 | print warnmsg |
---|
436 | print ' ' + fname + ": to complement a '" + okind + "' observation " + \ |
---|
437 | "kind a given height ('NAMEheight':",dscn['NAMEheight'],"') might " + \ |
---|
438 | 'be provided and any is given !!' |
---|
439 | quit(-1) |
---|
440 | |
---|
441 | if not dvalues.has_key(dscn['NAMEheight']): |
---|
442 | print errormsg |
---|
443 | print ' ' + fname + ": observations do not have 'NAMEtime':", \ |
---|
444 | dscn['NAMEtime'],' !!' |
---|
445 | print ' available data:',dvalues.keys() |
---|
446 | quit(-1) |
---|
447 | |
---|
448 | if searchInlist(map2D, okind): |
---|
449 | # A new 2D map with the number of observation will be added for that 'NAMElon' |
---|
450 | # and 'NAMElat' are necessary. A NdxNd domain space size will be used. |
---|
451 | objfile.createDimension('lon2D',Nd) |
---|
452 | objfile.createDimension('lat2D',Nd) |
---|
453 | lonvals = ma.masked_equal(dvalues[dscn['NAMElon']], None) |
---|
454 | latvals = ma.masked_equal(dvalues[dscn['NAMElat']], None) |
---|
455 | |
---|
456 | minlon = min(lonvals) |
---|
457 | maxlon = max(lonvals) |
---|
458 | minlat = min(latvals) |
---|
459 | maxlat = max(latvals) |
---|
460 | |
---|
461 | blon = (maxlon - minlon)/(Nd-1) |
---|
462 | blat = (maxlat - minlat)/(Nd-1) |
---|
463 | |
---|
464 | newvar = onc.createVariable( 'lon2D', 'f8', ('lon2D')) |
---|
465 | basicvardef(newvar, 'longitude', 'longitude map observations','degrees_East') |
---|
466 | newvar[:] = minlon + np.arange(Nd)*blon |
---|
467 | newattr = set_attribute(newvar, 'axis', 'X') |
---|
468 | |
---|
469 | newvar = onc.createVariable( 'lat2D', 'f8', ('lat2D')) |
---|
470 | basicvardef(newvar, 'latitude', 'latitude map observations', 'degrees_North') |
---|
471 | newvar[:] = minlat + np.arange(Nd)*blat |
---|
472 | newattr = set_attribute(newvar, 'axis', 'Y') |
---|
473 | |
---|
474 | if dbg: |
---|
475 | print ' ' + fname + ': minlon=',minlon,'maxlon=',maxlon |
---|
476 | print ' ' + fname + ': minlat=',minlat,'maxlat=',maxlat |
---|
477 | print ' ' + fname + ': precission on x-axis=', blon*(Nd-1), 'y-axis=', \ |
---|
478 | blat*(Nd-1) |
---|
479 | |
---|
480 | if okind == 'multi-points': |
---|
481 | map2D = np.ones((Nd, Nd), dtype=np.float)*fillValueI |
---|
482 | |
---|
483 | dimt = len(tvals) |
---|
484 | Nlost = 0 |
---|
485 | for it in range(dimt): |
---|
486 | lon = dvalues[dscn['NAMElon']][it] |
---|
487 | lat = dvalues[dscn['NAMElat']][it] |
---|
488 | if lon is not None and lat is not None: |
---|
489 | ilon = int((Nd-1)*(lon - minlon)/(maxlon - minlon)) |
---|
490 | ilat = int((Nd-1)*(lat - minlat)/(maxlat - minlat)) |
---|
491 | |
---|
492 | if map2D[ilat,ilon] == fillValueI: |
---|
493 | map2D[ilat,ilon] = 1 |
---|
494 | else: |
---|
495 | map2D[ilat,ilon] = map2D[ilat,ilon] + 1 |
---|
496 | if dbg: print it, lon, lat, ilon, ilat, map2D[ilat,ilon] |
---|
497 | |
---|
498 | newvar = onc.createVariable( 'mapobs', 'f4', ('lat2D', 'lon2D'), \ |
---|
499 | fill_value = fillValueI) |
---|
500 | basicvardef(newvar, 'map_observations', 'number of observations', '-') |
---|
501 | newvar[:] = map2D |
---|
502 | newattr = set_attribute(newvar, 'coordinates', 'lon2D lat2D') |
---|
503 | |
---|
504 | elif okind == 'trajectory': |
---|
505 | # A new 2D map with the trajectory 'NAMElon' and 'NAMElat' and maybe 'NAMEheight' |
---|
506 | # are necessary. A NdxNdxNd domain space size will be used. Using time as |
---|
507 | # reference variable |
---|
508 | if dscn['NAMEheight'] == '-': |
---|
509 | # No height |
---|
510 | map2D = np.ones((Nd, Nd), dtype=np.float)*fillValueI |
---|
511 | |
---|
512 | dimt = len(tvals) |
---|
513 | Nlost = 0 |
---|
514 | if dbg: print ' time-step lon lat ix iy passes _______' |
---|
515 | for it in range(dimt): |
---|
516 | lon = dvalues[dscn['NAMElon']][it] |
---|
517 | lat = dvalues[dscn['NAMElat']][it] |
---|
518 | if lon is not None and lat is not None: |
---|
519 | ilon = int((Nd-1)*(lon - minlon)/(maxlon - minlon)) |
---|
520 | ilat = int((Nd-1)*(lat - minlat)/(maxlat - minlat)) |
---|
521 | |
---|
522 | if map2D[ilat,ilon] == fillValueI: |
---|
523 | map2D[ilat,ilon] = 1 |
---|
524 | else: |
---|
525 | map2D[ilat,ilon] = map2D[ilat,ilon] + 1 |
---|
526 | if dbg: print it, lon, lat, ilon, ilat, map2D[ilat,ilon] |
---|
527 | |
---|
528 | newvar = onc.createVariable( 'trjobs', 'i', ('lat2D', 'lon2D'), \ |
---|
529 | fill_value = fillValueI) |
---|
530 | basicvardef(newvar, 'trajectory_observations', 'number of passes', '-' ) |
---|
531 | newvar[:] = map2D |
---|
532 | newattr = set_attribute(newvar, 'coordinates', 'lon2D lat2D') |
---|
533 | |
---|
534 | else: |
---|
535 | ivn = 0 |
---|
536 | for vn in dscn['varN']: |
---|
537 | if vn == dscn['NAMEheight']: |
---|
538 | zu = dscn['varU'][ivn] |
---|
539 | break |
---|
540 | ivn = ivn + 1 |
---|
541 | |
---|
542 | objfile.createDimension('z2D',Nd) |
---|
543 | zvals = ma.masked_equal(dvalues[dscn['NAMEheight']], None) |
---|
544 | minz = min(zvals) |
---|
545 | maxz = max(zvals) |
---|
546 | |
---|
547 | bz = (maxz - minz)/(Nd-1) |
---|
548 | |
---|
549 | newvar = onc.createVariable( 'z2D', 'f8', ('z2D')) |
---|
550 | basicvardef(newvar, 'z2D', 'z-coordinate map observations', zu) |
---|
551 | newvar[:] = minz + np.arange(Nd)*bz |
---|
552 | newattr = set_attribute(newvar, 'axis', 'Z') |
---|
553 | |
---|
554 | if dbg: |
---|
555 | print ' ' + fname + ': zmin=',minz,zu,'zmax=',maxz,zu |
---|
556 | print ' ' + fname + ': precission on z-axis=', bz*(Nd-1), zu |
---|
557 | |
---|
558 | map3D = np.ones((Nd, Nd, Nd), dtype=int)*fillValueI |
---|
559 | dimt = len(tvals) |
---|
560 | Nlost = 0 |
---|
561 | if dbg: print ' time-step lon lat z ix iy iz passes _______' |
---|
562 | for it in range(dimt): |
---|
563 | lon = dvalues[dscn['NAMElon']][it] |
---|
564 | lat = dvalues[dscn['NAMElat']][it] |
---|
565 | z = dvalues[dscn['NAMEheight']][it] |
---|
566 | if lon is not None and lat is not None and z is not None: |
---|
567 | ilon = int((Nd-1)*(lon - minlon)/(maxlon - minlon)) |
---|
568 | ilat = int((Nd-1)*(lat - minlat)/(maxlat - minlat)) |
---|
569 | iz = int((Nd-1)*(z - minz)/(maxz - minz)) |
---|
570 | |
---|
571 | if map3D[iz,ilat,ilon] == fillValueI: |
---|
572 | map3D[iz,ilat,ilon] = 1 |
---|
573 | else: |
---|
574 | map3D[iz,ilat,ilon] = map3D[iz,ilat,ilon] + 1 |
---|
575 | if dbg: print it, lon, lat, z, ilon, ilat, iz, map3D[iz,ilat,ilon] |
---|
576 | |
---|
577 | newvar = onc.createVariable( 'trjobs', 'i', ('z2D', 'lat2D', 'lon2D'), \ |
---|
578 | fill_value = fillValueI) |
---|
579 | basicvardef(newvar, 'trajectory_observations', 'number of passes', '-') |
---|
580 | newvar[:] = map3D |
---|
581 | newattr = set_attribute(newvar, 'coordinates', 'lon2D lat2D z2D') |
---|
582 | |
---|
583 | onc.sync() |
---|
584 | return |
---|
585 | |
---|
586 | def adding_station_desc(onc,stdesc): |
---|
587 | """ Function to add a station description in a netCDF file |
---|
588 | onc= netCDF object |
---|
589 | stdesc= station description lon, lat, height |
---|
590 | """ |
---|
591 | fname = 'adding_station_desc' |
---|
592 | |
---|
593 | newdim = onc.createDimension('nst',1) |
---|
594 | |
---|
595 | if onc.variables.has_key('lon'): |
---|
596 | print warnmsg |
---|
597 | print ' ' + fname + ": variable 'lon' already exist !!" |
---|
598 | print " renaming it as 'lonst'" |
---|
599 | lonname = 'lonst' |
---|
600 | else: |
---|
601 | lonname = 'lon' |
---|
602 | |
---|
603 | newvar = objfile.createVariable( lonname, 'f4', ('nst')) |
---|
604 | basicvardef(newvar, lonname, 'longitude', 'degrees_West' ) |
---|
605 | newvar[:] = stdesc[0] |
---|
606 | |
---|
607 | if onc.variables.has_key('lat'): |
---|
608 | print warnmsg |
---|
609 | print ' ' + fname + ": variable 'lat' already exist !!" |
---|
610 | print " renaming it as 'latst'" |
---|
611 | latname = 'latst' |
---|
612 | else: |
---|
613 | latname = 'lat' |
---|
614 | |
---|
615 | newvar = objfile.createVariable( latname, 'f4', ('nst')) |
---|
616 | basicvardef(newvar, lonname, 'latitude', 'degrees_North' ) |
---|
617 | newvar[:] = stdesc[1] |
---|
618 | |
---|
619 | if onc.variables.has_key('height'): |
---|
620 | print warnmsg |
---|
621 | print ' ' + fname + ": variable 'height' already exist !!" |
---|
622 | print " renaming it as 'heightst'" |
---|
623 | heightname = 'heightst' |
---|
624 | else: |
---|
625 | heightname = 'height' |
---|
626 | |
---|
627 | newvar = objfile.createVariable( heightname, 'f4', ('nst')) |
---|
628 | basicvardef(newvar, heightname, 'height above sea level', 'm' ) |
---|
629 | newvar[:] = stdesc[2] |
---|
630 | |
---|
631 | return |
---|
632 | |
---|
633 | ####### ###### ##### #### ### ## # |
---|
634 | |
---|
635 | strCFt="Refdate,tunits (CF reference date [YYYY][MM][DD][HH][MI][SS] format and " + \ |
---|
636 | " and time units: 'weeks', 'days', 'hours', 'miuntes', 'seconds')" |
---|
637 | |
---|
638 | kindobs=['multi-points', 'single-station', 'trajectory'] |
---|
639 | strkObs="kind of observations; 'multi-points': multiple individual punctual obs " + \ |
---|
640 | "(e.g., lightning strikes), 'single-station': single station on a fixed position,"+\ |
---|
641 | "'trajectory': following a trajectory" |
---|
642 | |
---|
643 | parser = OptionParser() |
---|
644 | parser.add_option("-c", "--comments", dest="charcom", |
---|
645 | help="':', list of characters used for comments", metavar="VALUES") |
---|
646 | parser.add_option("-d", "--descriptionfile", dest="fdesc", |
---|
647 | help="description file to use", metavar="FILE") |
---|
648 | parser.add_option("-e", "--end_column", dest="endcol", |
---|
649 | help="character to indicate end of the column ('space', for ' ')", metavar="VALUE") |
---|
650 | parser.add_option("-f", "--file", dest="obsfile", |
---|
651 | help="observational file to use", metavar="FILE") |
---|
652 | parser.add_option("-g", "--debug", dest="debug", |
---|
653 | help="whther debug is required ('false', 'true')", metavar="VALUE") |
---|
654 | parser.add_option("-k", "--kindObs", dest="obskind", type='choice', choices=kindobs, |
---|
655 | help=strkObs, metavar="FILE") |
---|
656 | parser.add_option("-s", "--stationLocation", dest="stloc", |
---|
657 | help="longitude, latitude and height of the station (only for 'single-station')", |
---|
658 | metavar="FILE") |
---|
659 | parser.add_option("-t", "--CFtime", dest="CFtime", help=strCFt, metavar="VALUE") |
---|
660 | |
---|
661 | (opts, args) = parser.parse_args() |
---|
662 | |
---|
663 | ####### ####### |
---|
664 | ## MAIN |
---|
665 | ####### |
---|
666 | |
---|
667 | ofile='OBSnetcdf.nc' |
---|
668 | |
---|
669 | if opts.charcom is None: |
---|
670 | print warnmsg |
---|
671 | print ' ' + main + ': No list of comment characters provided!!' |
---|
672 | print ' assuming no need!' |
---|
673 | charcomments = [] |
---|
674 | else: |
---|
675 | charcomments = opts.charcom.split(':') |
---|
676 | |
---|
677 | if opts.fdesc is None: |
---|
678 | print errormsg |
---|
679 | print ' ' + main + ': No description file for the observtional data provided!!' |
---|
680 | quit(-1) |
---|
681 | |
---|
682 | if opts.endcol is None: |
---|
683 | print warnmsg |
---|
684 | print ' ' + main + ': No list of comment characters provided!!' |
---|
685 | print " assuming 'space'" |
---|
686 | endcol = ' ' |
---|
687 | else: |
---|
688 | if opts.endcol == 'space': |
---|
689 | endcol = ' ' |
---|
690 | else: |
---|
691 | endcol = opts.endcol |
---|
692 | |
---|
693 | if opts.obsfile is None: |
---|
694 | print errormsg |
---|
695 | print ' ' + main + ': No observations file provided!!' |
---|
696 | quit(-1) |
---|
697 | |
---|
698 | if opts.debug is None: |
---|
699 | print warnmsg |
---|
700 | print ' ' + main + ': No debug provided!!' |
---|
701 | print " assuming 'False'" |
---|
702 | debug = False |
---|
703 | else: |
---|
704 | if opts.debug == 'true': |
---|
705 | debug = True |
---|
706 | else: |
---|
707 | debug = False |
---|
708 | |
---|
709 | if not os.path.isfile(opts.fdesc): |
---|
710 | print errormsg |
---|
711 | print ' ' + main + ": description file '" + opts.fdesc + "' does not exist !!" |
---|
712 | quit(-1) |
---|
713 | |
---|
714 | if not os.path.isfile(opts.obsfile): |
---|
715 | print errormsg |
---|
716 | print ' ' + main + ": observational file '" + opts.obsfile + "' does not exist !!" |
---|
717 | quit(-1) |
---|
718 | |
---|
719 | if opts.CFtime is None: |
---|
720 | print warnmsg |
---|
721 | print ' ' + main + ': No CFtime criteria are provided !!' |
---|
722 | print " either time is already in CF-format ('timeFMT=CFtime') in '" + \ |
---|
723 | opts.fdesc + "'" |
---|
724 | print " or assuming refdate: '19491201000000' and time units: 'hours'" |
---|
725 | referencedate = '19491201000000' |
---|
726 | timeunits = 'hours' |
---|
727 | else: |
---|
728 | referencedate = opts.CFtime.split(',')[0] |
---|
729 | timeunits = opts.CFtime.split(',')[1] |
---|
730 | |
---|
731 | if opts.obskind is None: |
---|
732 | print warnmsg |
---|
733 | print ' ' + main + ': No kind of observations provided !!' |
---|
734 | print " assuming 'single-station': single station on a fixed position at 0,0,0" |
---|
735 | obskind = 'single-station' |
---|
736 | stationdesc = [0.0, 0.0, 0.0] |
---|
737 | else: |
---|
738 | obskind = opts.obskind |
---|
739 | if obskind == 'single-station': |
---|
740 | if opts.stloc is None: |
---|
741 | print errornmsg |
---|
742 | print ' ' + main + ': No station location provided !!' |
---|
743 | quit(-1) |
---|
744 | else: |
---|
745 | stationdesc = [np.float(opts.stloc.split(',')[0]), \ |
---|
746 | np.float(opts.stloc.split(',')[1]), np.float(opts.stloc.split(',')[2])] |
---|
747 | else: |
---|
748 | obskind = opts.obskind |
---|
749 | |
---|
750 | # Reading description file |
---|
751 | ## |
---|
752 | description = read_description(opts.fdesc, debug) |
---|
753 | |
---|
754 | Nvariables=len(description['varN']) |
---|
755 | formats = description['varTYPE'] |
---|
756 | |
---|
757 | if len(formats) != Nvariables: |
---|
758 | print errormsg |
---|
759 | print ' ' + main + ': number of formats:',len(formats),' and number of ' + \ |
---|
760 | 'variables', Nvariables,' does not coincide!!' |
---|
761 | print ' * what is found is _______' |
---|
762 | if Nvariables > len(formats): |
---|
763 | Nshow = len(formats) |
---|
764 | for ivar in range(Nshow): |
---|
765 | print ' ',description['varN'][ivar],':', description['varLN'][ivar],\ |
---|
766 | '[', description['varU'][ivar], '] fmt:', formats[ivar] |
---|
767 | print ' missing values for:', description['varN'][Nshow:Nvariables+1] |
---|
768 | else: |
---|
769 | Nshow = Nvariables |
---|
770 | for ivar in range(Nshow): |
---|
771 | print ' ',description['varN'][ivar],':', description['varLN'][ivar],\ |
---|
772 | '[', description['varU'][ivar], '] fmt:', formats[ivar] |
---|
773 | print ' excess of formats for:', formats[Nshow:len(formats)+1] |
---|
774 | |
---|
775 | quit(-1) |
---|
776 | |
---|
777 | # Reading values |
---|
778 | ## |
---|
779 | datavalues = read_datavalues(opts.obsfile, charcomments, endcol, formats, |
---|
780 | description['MissingValue'], description['varN'], debug) |
---|
781 | |
---|
782 | # Total number of values |
---|
783 | Ntvalues = len(datavalues[description['varN'][0]]) |
---|
784 | print main + ': total temporal values found:',Ntvalues |
---|
785 | |
---|
786 | objfile = NetCDFFile(ofile, 'w') |
---|
787 | |
---|
788 | # Creation of dimensions |
---|
789 | ## |
---|
790 | objfile.createDimension('time',None) |
---|
791 | objfile.createDimension('StrLength',StringLength) |
---|
792 | |
---|
793 | # Creation of variables |
---|
794 | ## |
---|
795 | for ivar in range(Nvariables): |
---|
796 | varn = description['varN'][ivar] |
---|
797 | print " including: '" + varn + "' ... .. ." |
---|
798 | |
---|
799 | if formats[ivar] == 'D': |
---|
800 | newvar = objfile.createVariable(varn, 'f32', ('time'), fill_value=fillValueF) |
---|
801 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
802 | description['varU'][ivar]) |
---|
803 | newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn]) |
---|
804 | elif formats[ivar] == 'F': |
---|
805 | newvar = objfile.createVariable(varn, 'f', ('time'), fill_value=fillValueF) |
---|
806 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
807 | description['varU'][ivar]) |
---|
808 | newvar[:] = np.where(datavalues[varn] is None, fillValueF, datavalues[varn]) |
---|
809 | elif formats[ivar] == 'I': |
---|
810 | newvar = objfile.createVariable(varn, 'i', ('time'), fill_value=fillValueI) |
---|
811 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
812 | description['varU'][ivar]) |
---|
813 | # Why is not wotking with integers? |
---|
814 | vals = np.array(datavalues[varn]) |
---|
815 | for iv in range(Ntvalues): |
---|
816 | if vals[iv] is None: vals[iv] = fillValueI |
---|
817 | newvar[:] = vals |
---|
818 | elif formats[ivar] == 'S': |
---|
819 | newvar = objfile.createVariable(varn, 'c', ('time','StrLength')) |
---|
820 | basicvardef(newvar, varn, description['varLN'][ivar], \ |
---|
821 | description['varU'][ivar]) |
---|
822 | writing_str_nc(newvar, datavalues[varn], StringLength) |
---|
823 | |
---|
824 | # Extra variable descriptions/attributes |
---|
825 | if description.has_key('varBUFR'): |
---|
826 | set_attribute(newvar,'bufr_code',description['varBUFR'][ivar]) |
---|
827 | |
---|
828 | objfile.sync() |
---|
829 | |
---|
830 | # Time variable in CF format |
---|
831 | ## |
---|
832 | if description['FMTtime'] == 'CFtime': |
---|
833 | timevals = datavalues[description['NAMEtime']] |
---|
834 | iv = 0 |
---|
835 | for ivn in description['varN']: |
---|
836 | if ivn == description['NAMEtime']: |
---|
837 | tunits = description['varU'][iv] |
---|
838 | break |
---|
839 | iv = iv + 1 |
---|
840 | else: |
---|
841 | # Time as a composition of different columns |
---|
842 | tcomposite = description['NAMEtime'].find('@') |
---|
843 | if tcomposite != -1: |
---|
844 | timevars = description['NAMEtime'].split('@') |
---|
845 | |
---|
846 | print warnmsg |
---|
847 | print ' ' + main + ': time values as combination of different columns!' |
---|
848 | print ' combining:',timevars,' with a final format: ',description['FMTtime'] |
---|
849 | |
---|
850 | timeSvals = [] |
---|
851 | if debug: print ' ' + main + ': creating times _______' |
---|
852 | for it in range(Ntvalues): |
---|
853 | tSvals = '' |
---|
854 | for tvar in timevars: |
---|
855 | tSvals = tSvals + datavalues[tvar][it] + ' ' |
---|
856 | |
---|
857 | timeSvals.append(tSvals[0:len(tSvals)-1]) |
---|
858 | if debug: print it, '*' + timeSvals[it] + '*' |
---|
859 | |
---|
860 | timevals = Stringtimes_CF(timeSvals, description['FMTtime'], referencedate, \ |
---|
861 | timeunits, debug) |
---|
862 | else: |
---|
863 | timevals = Stringtimes_CF(datavalues[description['NAMEtime']], \ |
---|
864 | description['FMTtime'], referencedate, timeunits, debug) |
---|
865 | |
---|
866 | CFtimeRef = referencedate[0:4] +'-'+ referencedate[4:6] +'-'+ referencedate[6:8] + \ |
---|
867 | ' ' + referencedate[8:10] +':'+ referencedate[10:12] +':'+ referencedate[12:14] |
---|
868 | tunits = timeunits + ' since ' + CFtimeRef |
---|
869 | |
---|
870 | if objfile.variables.has_key('time'): |
---|
871 | print warnmsg |
---|
872 | print ' ' + main + ": variable 'time' already exist !!" |
---|
873 | print " renaming it as 'CFtime'" |
---|
874 | timeCFname = 'CFtime' |
---|
875 | newdim = objfile.renameDimension('time','CFtime') |
---|
876 | newvar = objfile.createVariable( timeCFname, 'f8', ('CFtime')) |
---|
877 | basicvardef(newvar, timeCFname, 'time', tunits ) |
---|
878 | else: |
---|
879 | timeCFname = 'time' |
---|
880 | newvar = objfile.createVariable( timeCFname, 'f8', ('time')) |
---|
881 | basicvardef(newvar, timeCFname, 'time', tunits ) |
---|
882 | |
---|
883 | set_attribute(newvar, 'calendar', 'standard') |
---|
884 | newvar[:] = timevals |
---|
885 | |
---|
886 | # Global attributes |
---|
887 | ## |
---|
888 | for descn in description.keys(): |
---|
889 | if descn[0:3] != 'var' and descn[0:4] != 'NAME' and descn[0:3] != 'FMT': |
---|
890 | set_attribute(objfile, descn, description[descn]) |
---|
891 | |
---|
892 | set_attribute(objfile,'author_nc','Lluis Fita') |
---|
893 | set_attribute(objfile,'institution_nc','Laboratoire de Meteorology Dynamique, ' + \ |
---|
894 | 'LMD-Jussieu, UPMC, Paris') |
---|
895 | set_attribute(objfile,'country_nc','France') |
---|
896 | set_attribute(objfile,'script_nc','create_OBSnetcdf.py') |
---|
897 | set_attribute(objfile,'version_script',version) |
---|
898 | set_attribute(objfile,'information', \ |
---|
899 | 'http://www.lmd.jussieu.fr/~lflmd/ASCIIobs_nc/index.html') |
---|
900 | |
---|
901 | objfile.sync() |
---|
902 | |
---|
903 | # Adding new variables as function of the observational type |
---|
904 | ## 'multi-points', 'single-station', 'trajectory' |
---|
905 | |
---|
906 | if obskind != 'single-station': |
---|
907 | adding_complementary(objfile, description, obskind, datavalues, timevals, \ |
---|
908 | referencedate, timeunits, Ndim2D, debug) |
---|
909 | else: |
---|
910 | # Adding three variables with the station location, longitude, latitude and height |
---|
911 | adding_station_desc(objfile,stationdesc) |
---|
912 | |
---|
913 | objfile.sync() |
---|
914 | objfile.close() |
---|
915 | |
---|
916 | print main + ": Successfull generation of netcdf observational file '" + ofile + "' !!" |
---|