NCCOOS Trac Projects: Top | Web | Platforms | Processing | Viz | Sprints | Sandbox | (Wind)

root/raw2proc/trunk/raw2proc/proc_cr1000_met.py

Revision 488 (checked in by haines, 12 years ago)

removed test_ and scr_ files not necessary for SVN

Line 
1 #!/usr/bin/env python
2 # Last modified:  Time-stamp: <2012-04-23 14:12:38 haines>
3 """
4 how to parse data, and assert what data and info goes into
5 creating and updating monthly netcdf files
6
7 parse data met data collected on Campbell Scientific DataLogger (loggernet) (csi)
8
9 parser : sample date and time,
10
11 creator : lat, lon, z, time,
12 updator : time,
13
14
15 Examples
16 --------
17
18 >> (parse, create, update) = load_processors('proc_csi_adcp_v2')
19 or
20 >> si = get_config(cn+'.sensor_info')
21 >> (parse, create, update) = load_processors(si['adcp']['proc_module'])
22
23 >> lines = load_data(filename)
24 >> data = parse(platform_info, sensor_info, lines)
25 >> create(platform_info, sensor_info, data) or
26 >> update(platform_info, sensor_info, data)
27
28 """
29
30
31 from raw2proc import *
32 from procutil import *
33 from ncutil import *
34
35 now_dt = datetime.utcnow()
36 now_dt.replace(microsecond=0)
37
38 def parser(platform_info, sensor_info, lines):
39     """
40     Example met data
41
42     "TOA5","CR1000_B1","CR1000","37541","CR1000.Std.21","CPU:NCWIND_12_Buoy_All.CR1","58723","AMet_6Min"
43     "TIMESTAMP","RECORD","Baro_mbar_Avg","RHumidity_Avg","RHumidity_Std","AirTempC_Avg","AirTempC_Std","Rain","Psp_Avg","Psp_Std","Pir_Wm2_Avg","Pir_Wm2_Std"
44     "TS","RN","","","","","","","","","",""
45     "","","Avg","Avg","Std","Avg","Std","Smp","Avg","Std","Avg","Std"
46     "2011-11-01 00:00:59",4590,14.3792,75.59,0.579,15.67,0.05,-22.35,1197.037,45.58967,371.5126,0.9030571
47     "2011-11-01 00:06:59",4591,14.37995,74.96,0.912,16.61,0.048,-21,-1071.813,129.5147,381.2539,0.2076943
48     "2011-11-01 00:12:59",4592,14.3792,72.71,2.677,17.29,0.032,-15.58,-2056.658,0,381.1828,0.1402813
49     "2011-11-01 00:18:59",4593,14.3791,72.63,0.928,17.67,0.041,-19.64,-1895.86,9.866026,381.0333,0.2442325
50    
51     """
52
53     import numpy
54     from datetime import datetime
55     from time import strptime
56
57     # get sample datetime from filename
58     fn = sensor_info['fn']
59     sample_dt_start = filt_datetime(fn)
60
61     # how many samples (don't count header 4 lines)
62     nsamp = len(lines[4:])
63
64     N = nsamp
65     data = {
66         'dt' : numpy.array(numpy.ones((N,), dtype=object)*numpy.nan),
67         'time' : numpy.array(numpy.ones((N,), dtype=long)*numpy.nan),
68         'air_press' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
69         'rh' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
70         'rh_std' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
71         'air_temp' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
72         'air_temp_std' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
73         'rain' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
74         'psp' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
75         'psp_std' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
76         'pir' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
77         'pir_std' : numpy.array(numpy.ones((N,), dtype=float)*numpy.nan),
78         }
79
80     # sample count
81     i = 0
82
83     for line in lines[4:]:
84         csi = []
85         # split line
86         sw = re.split(',', line)
87         if len(sw)<=0:
88             print ' ... skipping line %d ' % (i,)
89             continue
90
91         # replace any "NAN" text with a number
92         for index, s in enumerate(sw):
93             m = re.search(NAN_RE_STR, s)
94             if m:
95                 sw[index] = '-99999'
96
97         # parse date-time, and all other float and integers
98         for s in sw[1:]:
99             m = re.search(REAL_RE_STR, s)
100             if m:
101                 csi.append(float(m.groups()[0]))
102
103         if  sensor_info['utc_offset']:
104             sample_dt = scanf_datetime(sw[0], fmt='"%Y-%m-%d %H:%M:%S"') + \
105                         timedelta(hours=sensor_info['utc_offset'])
106         else:
107             sample_dt = scanf_datetime(sw[0], fmt='"%Y-%m-%d %H:%M:%S"')
108
109         data['dt'][i] = sample_dt # sample datetime
110         data['time'][i] = dt2es(sample_dt) # sample time in epoch seconds
111        
112         if len(csi)==11:
113             #
114             # data['samplenum'][i] = csi[0] # sample number assigned by datalogger in table
115             data['air_press'][i] = csi[1] # Heise Barometer (mbar)
116             data['rh'][i] = csi[2] # relative humidity avg (60 samples for 1 min)
117             data['rh_std'][i] = csi[3] # relative humidity std
118             data['air_temp'][i] = csi[4] # air temperature avg (deg C)
119             data['air_temp_std'][i] = csi[5] # air temperature std (deg C)
120             data['rain'][i] = csi[6] # precip gauge cummulative
121             data['psp'][i] = csi[7] # PSP avg
122             data['psp_std'][i] = csi[8] # PSP std
123             data['pir'][i] = csi[9] # PIR avg (W m-2)
124             data['pir_std'][i] = csi[10] # PIR std (W m-2)
125             i=i+1
126         else:
127             print ' ... skipping line %d -- %s ' % (i,line)
128             continue
129
130         # if re.search
131     # for line
132
133
134     # check that no data[dt] is set to Nan or anything but datetime
135     # keep only data that has a resolved datetime
136     keep = numpy.array([type(datetime(1970,1,1)) == type(dt) for dt in data['dt'][:]])
137     if keep.any():
138         for param in data.keys():
139             data[param] = data[param][keep]
140
141     return data
142  
143
144 def creator(platform_info, sensor_info, data):
145     #
146     #
147     # subset data only to month being processed (see raw2proc.process())
148     i = data['in']
149
150     title_str = sensor_info['description']+' at '+ platform_info['location']
151     global_atts = {
152         'title' : title_str,
153         'institution' : platform_info['institution'],
154         'institution_url' : platform_info['institution_url'],
155         'institution_dods_url' : platform_info['institution_dods_url'],
156         'metadata_url' : platform_info['metadata_url'],
157         'references' : platform_info['references'],
158         'contact' : platform_info['contact'],
159         #
160         'source' : platform_info['source']+' '+sensor_info['source'],
161         'history' : 'raw2proc using ' + sensor_info['process_module'],
162         'comment' : 'File created using pycdf'+pycdfVersion()+' and numpy '+pycdfArrayPkg(),
163         # conventions
164         'Conventions' : platform_info['conventions'],
165         # SEACOOS CDL codes
166         'format_category_code' : platform_info['format_category_code'],
167         'institution_code' : platform_info['institution_code'],
168         'platform_code' : platform_info['id'],
169         'package_code' : sensor_info['id'],
170         # institution specific
171         'project' : platform_info['project'],
172         'project_url' : platform_info['project_url'],
173         # timeframe of data contained in file yyyy-mm-dd HH:MM:SS
174         # first date in monthly file
175         'start_date' : data['dt'][i][0].strftime("%Y-%m-%d %H:%M:%S"),
176         # last date in monthly file
177         'end_date' : data['dt'][i][-1].strftime("%Y-%m-%d %H:%M:%S"),
178         'release_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
179         #
180         'creation_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
181         'modification_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
182         'process_level' : 'level1',
183         #
184         # must type match to data (e.g. fillvalue is real if data is real)
185         '_FillValue' : -99999.,
186         }
187
188     var_atts = {
189         # coordinate variables
190         'time' : {'short_name': 'time',
191                   'long_name': 'Time',
192                   'standard_name': 'time',
193                   'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
194                   'axis': 'T',
195                   },
196         'lat' : {'short_name': 'lat',
197                  'long_name': 'Latitude',
198                  'standard_name': 'latitude',
199                  'reference':'geographic coordinates',
200                  'units': 'degrees_north',
201                  'valid_range':(-90.,90.),
202                  'axis': 'Y',
203                  },
204         'lon' : {'short_name': 'lon',
205                  'long_name': 'Longitude',
206                  'standard_name': 'longitude',
207                  'reference':'geographic coordinates',
208                  'units': 'degrees_east',
209                  'valid_range':(-180.,180.),
210                  'axis': 'Y',
211                  },
212         'z' : {'short_name': 'z',
213                'long_name': 'Altitude',
214                'standard_name': 'altitude',
215                'reference':'zero at mean sea level',
216                'positive' : 'up',
217                'units': 'm',
218                'axis': 'Z',
219                },
220         # data variables
221         'air_press': {'short_name': 'air_press',
222                   'long_name': 'Air Pressure',
223                   'standard_name': 'air_pressure',                         
224                   'units': 'mbar',
225                   'z': sensor_info['barometer_height'],
226                   'z_units' : 'meter',
227                   },
228         'air_temp': {'short_name': 'air_temp',
229                   'long_name': 'Air Temperature',
230                   'standard_name': 'air_temperature',                         
231                   'units': 'degC',
232                   'z': sensor_info['temperature_height'],
233                   'z_units' : 'meter',
234                   },
235         'air_temp_std': {'short_name': 'air_temp_std',
236                   'long_name': 'Standard Deviation of Air Temperature',
237                   'standard_name': 'air_temperature',                         
238                   'units': 'degC',
239                   },
240         'rh': {'short_name': 'rh',
241                   'long_name': 'Relative Humidity',
242                   'standard_name': 'relative_humidity',                         
243                   'units': '%',
244                   'z': sensor_info['temperature_height'],
245                   'z_units' : 'meter',
246                   },
247         'rh_std': {'short_name': 'rh_std',
248                   'long_name': 'Standard Deviation of Relative Humidity',
249                   'standard_name': 'relative_humidity',                         
250                   'units': '%',
251                   },
252         'rain': {'short_name': 'rain',
253                  'long_name': '6-Minute Rain',
254                  'standard_name': 'rain',                         
255                  'units': 'inches',
256                   },
257         'psp': {'short_name': 'psp',
258                   'long_name': 'Short-wave Radiation',
259                   'standard_name': 'downwelling_shortwave_irradiance',                         
260                   'units': 'W m-2',
261                   },
262         'psp_std': {'short_name': 'psp_std',
263                   'long_name': 'Standard Deviation of Short-wave Radiation',
264                   'standard_name': 'shortwave_radiation',                         
265                   'units': 'W m-2',
266                   },
267         'pir': {'short_name': 'pir',
268                   'long_name': 'Long-wave Radiation',
269                   'standard_name': 'longwave_radiation',                         
270                   'units': 'W m-2',
271                   },
272         'pir_std': {'short_name': 'pir_std',
273                   'long_name': 'Standard Deviation of Long-wave Radiation',
274                   'standard_name': 'longwave_radiation',                         
275                   'units': 'W m-2',
276                   },
277         }
278
279     # dimension names use tuple so order of initialization is maintained
280     dim_inits = (
281         ('ntime', NC.UNLIMITED),
282         ('nlat', 1),
283         ('nlon', 1),
284         ('nz', 1),
285         )
286    
287     # using tuple of tuples so order of initialization is maintained
288     # using dict for attributes order of init not important
289     # use dimension names not values
290     # (varName, varType, (dimName1, [dimName2], ...))
291     var_inits = (
292         # coordinate variables
293         ('time', NC.INT, ('ntime',)),
294         ('lat', NC.FLOAT, ('nlat',)),
295         ('lon', NC.FLOAT, ('nlon',)),
296         ('z',  NC.FLOAT, ('nz',)),
297         # data variables
298         ('air_press', NC.FLOAT, ('ntime',)),
299         ('rh', NC.FLOAT, ('ntime',)),
300         ('rh_std', NC.FLOAT, ('ntime',)),
301         ('air_temp', NC.FLOAT, ('ntime',)),
302         ('air_temp_std', NC.FLOAT, ('ntime',)),
303         ('rain', NC.FLOAT, ('ntime',)),
304         ('psp', NC.FLOAT, ('ntime',)),
305         ('psp_std', NC.FLOAT, ('ntime',)),
306         ('pir', NC.FLOAT, ('ntime',)),
307         ('pir_std', NC.FLOAT, ('ntime',)),
308         )
309
310     # subset data only to month being processed (see raw2proc.process())
311     i = data['in']
312    
313     # var data
314     var_data = (
315         ('lat',  platform_info['lat']),
316         ('lon', platform_info['lon']),
317         ('z', platform_info['altitude']),
318         #
319         ('time', data['time'][i]),
320         #
321         ('air_press', data['air_press'][i]),
322         ('rh', data['rh'][i]),
323         ('rh_std', data['rh_std'][i]),
324         ('air_temp', data['air_temp'][i]),
325         ('air_temp_std', data['air_temp_std'][i]),
326         ('rain', data['rain'][i]),
327         ('psp', data['psp'][i]),
328         ('psp_std', data['psp_std'][i]),
329         ('pir', data['pir'][i]),
330         ('pir_std', data['pir_std'][i]),
331         )
332
333     return (global_atts, var_atts, dim_inits, var_inits, var_data)
334
335 def updater(platform_info, sensor_info, data):
336     #
337     # subset data only to month being processed (see raw2proc.process())
338     i = data['in']
339
340     global_atts = {
341         # update times of data contained in file (yyyy-mm-dd HH:MM:SS)
342         # last date in monthly file
343         'end_date' : data['dt'][i][-1].strftime("%Y-%m-%d %H:%M:%S"),
344         'release_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
345         #
346         'modification_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
347         }
348
349     # data variables
350     # update any variable attributes like range, min, max
351     var_atts = {}
352     # var_atts = {
353     #    'wtemp': {'max': max(data.u),
354     #          'min': min(data.v),
355     #          },
356     #    'cond': {'max': max(data.u),
357     #          'min': min(data.v),
358     #          },
359     #    }
360    
361     # data
362     var_data = (
363         ('time', data['time'][i]),
364         #
365         ('air_press', data['air_press'][i]),
366         ('rh', data['rh'][i]),
367         ('rh_std', data['rh_std'][i]),
368         ('air_temp', data['air_temp'][i]),
369         ('air_temp_std', data['air_temp_std'][i]),
370         ('rain', data['rain'][i]),
371         ('psp', data['psp'][i]),
372         ('psp_std', data['psp_std'][i]),
373         ('pir', data['pir'][i]),
374         ('pir_std', data['pir_std'][i]),
375         )
376
377     return (global_atts, var_atts, var_data)
378 #
Note: See TracBrowser for help on using the browser.