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

root/raw2proc/trunk/raw2proc/proc_mini_andi_system.py

Revision 375 (checked in by cbc, 14 years ago)

Process and config modules for Spongenet.

Line 
1 """
2 Parse data and assert what data creates and updates monthly NetCDF files.
3
4 Spongenet mini_andi system parameters sponge data.
5 """
6
7 import math
8 import numpy as n
9 import pycdf
10 import datetime
11 import procutil
12 from spongenet.parse import Data
13
14 nowDt = datetime.datetime.utcnow().replace(microsecond=0)
15
16 def parser(platform_info, sensor_info, lines):
17     """
18     Parse and assign sponge data from XML file.
19     """
20    
21     _data = Data(''.join(lines))
22    
23     # Each Device tag represents a time sample.
24     num_samples = len(_data.devices)
25    
26     data = {
27         'dt'       : n.array(n.ones((num_samples,)) * n.nan, dtype=object),
28         'time'     : n.array(n.ones((num_samples,)) * n.nan, dtype=long),
29         'pdt'      : n.array(n.ones((num_samples,)) * n.nan, dtype=object),
30         'ptime'    : n.array(n.ones((num_samples,)) * n.nan, dtype=long),
31         'ds'       : n.array(n.ones((num_samples,)) * n.nan, dtype=object),
32         'session'  : n.array(n.ones((num_samples,)) * n.nan, dtype=long),
33         'pds'      : n.array(n.ones((num_samples,)) * n.nan, dtype=object),
34         'psession' : n.array(n.ones((num_samples,)) * n.nan, dtype=long),
35         'record'   : n.array(n.ones((num_samples,)) * n.nan, dtype=int),
36         'status'   : n.array(n.ones((num_samples,)) * n.nan, dtype=int),
37         'pstatus'  : n.array(n.ones((num_samples,)) * n.nan, dtype=int),
38         'voltage'  : n.array(n.ones((num_samples,)) * n.nan, dtype=float),
39         'memory'   : n.array(n.ones((num_samples,)) * n.nan, dtype=int),
40         'interval' : n.array(n.ones((num_samples,)) * n.nan, dtype=int),
41            }
42    
43     for (sample_index, sample) in enumerate(_data.devices):
44         # sample time at the platform
45         dt = {'month' : int(sample['time'][5:7]),
46               'day'   : int(sample['time'][8:10]),
47               'year'  : int(sample['time'][0:4]),
48               'hour'  : int(sample['time'][11:13]),
49               'min'   : int(sample['time'][14:16]),
50               'sec'   : int(sample['time'][17:19]),
51              }
52         dt = '%(month)02d-%(day)02d-%(year)04d %(hour)02d:%(min)02d:%(sec)02d' \
53              % dt
54         dt = procutil.scanf_datetime(dt, fmt='%m-%d-%Y %H:%M:%S')
55         if sensor_info['utc_offset']:
56             dt = dt + datetime.timedelta(hours=sensor_info['utc_offset'])
57         data['dt'][sample_index] = dt       
58         data['time'][sample_index] = procutil.dt2es(dt)
59
60         # sample time at the package
61         package_dt = {'month' : int(sample['data_time'][5:7]),
62                       'day'   : int(sample['data_time'][8:10]),
63                       'year'  : int(sample['data_time'][0:4]),
64                       'hour'  : int(sample['data_time'][11:13]),
65                       'min'   : int(sample['data_time'][14:16]),
66                       'sec'   : int(sample['data_time'][17:19]),
67                      }
68         package_dt = ('%(month)02d-%(day)02d-%(year)04d ' +
69                       '%(hour)02d:%(min)02d:%(sec)02d') \
70                      % package_dt
71         package_dt = procutil.scanf_datetime(package_dt, fmt='%m-%d-%Y %H:%M:%S')
72         if sensor_info['utc_offset']:
73             package_dt = package_dt + \
74                         datetime.timedelta(hours=sensor_info['utc_offset'])
75         data['pdt'][sample_index] = package_dt
76         data['ptime'][sample_index] = procutil.dt2es(package_dt)
77
78         # platform session time
79         ds = {'month' : int(sample['sessionid'][14:16]),
80               'day'   : int(sample['sessionid'][17:19]),
81               'year'  : int(sample['sessionid'][9:13]),
82               'hour'  : int(sample['sessionid'][20:22]),
83               'min'   : int(sample['sessionid'][23:25]),
84               'sec'   : int(sample['sessionid'][26:28]),
85              }
86         ds = '%(month)02d-%(day)02d-%(year)04d %(hour)02d:%(min)02d:%(sec)02d' \
87              % ds
88         ds = procutil.scanf_datetime(ds, fmt='%m-%d-%Y %H:%M:%S')
89         if sensor_info['utc_offset']:
90             ds = ds + datetime.timedelta(hours=sensor_info['utc_offset'])
91         data['ds'][sample_index] = ds       
92         data['session'][sample_index] = procutil.dt2es(ds)
93
94         # package session time
95         package_ds = {'month' : int(sample['data_sessionid'][5:7]),
96                       'day'   : int(sample['data_sessionid'][8:10]),
97                       'year'  : int(sample['data_sessionid'][0:4]),
98                       'hour'  : int(sample['data_sessionid'][11:13]),
99                       'min'   : int(sample['data_sessionid'][14:16]),
100                       'sec'   : int(sample['data_sessionid'][17:19]),
101                      }
102         package_ds = ('%(month)02d-%(day)02d-%(year)04d ' +
103                       '%(hour)02d:%(min)02d:%(sec)02d') \
104                      % package_ds
105         package_ds = procutil.scanf_datetime(package_ds, fmt='%m-%d-%Y %H:%M:%S')
106         if sensor_info['utc_offset']:
107             package_ds = package_ds + \
108                         datetime.timedelta(hours=sensor_info['utc_offset'])
109         data['pds'][sample_index] = package_ds
110         data['psession'][sample_index] = procutil.dt2es(package_ds)
111
112         # platform variables
113         try:
114             data['record'][sample_index] = int(sample["recordnumber"])
115         except KeyError:
116             pass
117
118         try:
119             data['status'][sample_index] = int(sample["status"].
120                                                partition(":")[0])
121         except (KeyError, AttributeError, ):
122             pass
123
124         # package variables
125         try:
126             data['pstatus'][sample_index] = int(sample.sensors
127                                                 [sensor_info["id_number"]]
128                                                 ["status"].
129                                                 partition(":")[0])
130         except (KeyError, AttributeError, ):
131             pass
132
133         try:
134             data['voltage'][sample_index] = float(sample.sensors
135                                                   [sensor_info["id_number"]].
136                                                   points[sensor_info
137                                                          ["voltage_description"]]
138                                                   ["value"])
139         except (KeyError, AttributeError, ):
140             pass
141
142         try:
143             data['memory'][sample_index] = int(sample.sensors
144                                                [sensor_info["id_number"]].
145                                                points[sensor_info
146                                                       ["memory_description"]]
147                                                ["value"])
148         except (KeyError, AttributeError, ):
149             pass
150
151         try:
152             data['interval'][sample_index] = int(sample.sensors
153                                                  [sensor_info["id_number"]].
154                                                  points[sensor_info
155                                                         ["interval_description"]]
156                                                  ["value"])
157         except (KeyError, AttributeError, ):
158             pass
159
160     return data
161
162 def creator(platform_info, sensor_info, data):
163     #
164     #
165     title_str = sensor_info['description']+' at '+ sensor_info['location']
166     global_atts = {
167         # Required
168         'title' : title_str,
169         'institution' : platform_info['institution'],
170         'institution_url' : platform_info['institution_url'],
171         'institution_dods_url' : platform_info['institution_dods_url'],
172         'contact' : platform_info['contact'],
173         'Conventions' : platform_info['conventions'],
174         # Required by Scout
175         'format_category_code' : platform_info['format_category_code'],
176         'institution_code' : platform_info['institution_code'],
177         'platform_code' : platform_info['id'],
178         'package_code' : sensor_info['id'],
179         # Required by Version tracking
180         'format' : platform_info['format'],
181         'seacoos_rt_version' : platform_info['seacoos_rt_version'],
182         # Recommended
183         '_FillValue' : n.nan,
184         'missing_value' : n.nan,
185         'source' : platform_info['source'],
186         'references' : platform_info['references'],
187         'metadata_url' : platform_info['metadata_url'],
188         'history' : 'raw2proc using ' + sensor_info['process_module'],
189         'comment' : 'File created using pycdf ' + \
190                     pycdf.pycdfVersion() + ' and ' + \
191                     pycdf.pycdfArrayPkg() + ' ' + \
192                     n.__version__,
193         'project' : platform_info['project'],
194         'project_url' : platform_info['project_url'],
195         # timeframe of data contained in file yyyy-mm-dd HH:MM:SS
196         # first date in monthly file
197         'start_date' : data['dt'][0].strftime("%Y-%m-%d %H:%M:%S"),
198         # last date in monthly file
199         'end_date' : data['dt'][-1].strftime("%Y-%m-%d %H:%M:%S"),
200         'release_date' : nowDt.strftime("%Y-%m-%d %H:%M:%S"),
201         'creation_date' : nowDt.strftime("%Y-%m-%d %H:%M:%S"),
202         'modification_date' : nowDt.strftime("%Y-%m-%d %H:%M:%S"),
203         'process_level' : 'level1',
204         # Custom
205         'id_number' : platform_info['id_number'],
206         'description' : platform_info['description'],
207         'serial_number' : platform_info['serial_number'],
208         'product_number' : platform_info['product_number'],
209         'product_name' : platform_info['product_name'],
210         'type' : platform_info['type'],
211         'protocol_version' : platform_info['protocol_version'],
212         'xmlns' : platform_info['xmlns'],
213         'location' : platform_info['location'],
214         'vertical_position': platform_info['vertical_position'],
215         'owner' : platform_info['owner'],
216         'package_id_number' : sensor_info['id_number'],
217         'package_description' : sensor_info['description'],
218         'package_serial_number' : sensor_info['serial_number'],
219         'package_product_number' : sensor_info['product_number'],
220         'package_product_name' : sensor_info['product_name'],
221         'package_adr' : sensor_info['adr'],
222         'package_protocol_version' : sensor_info['protocol_version'],
223         'package_vertical_position' : sensor_info['vertical_position'],
224         }
225    
226     var_atts = {
227         # coordinate variables
228         'time' : {'short_name': 'time',
229                   'long_name': 'Time',
230                   'standard_name': 'time',
231                   'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
232                   'axis': 'T',
233                  },
234         'lat' : {'short_name': 'lat',
235                  'long_name': 'Latitude',
236                  'standard_name': 'latitude',
237                  'reference':'geographic coordinates',
238                  'units': 'degrees_north',
239                  'valid_range':(-90.,90.),
240                  'axis': 'Y',
241                 },
242         'lon' : {'short_name': 'lon',
243                  'long_name': 'Longtitude',
244                  'standard_name': 'longtitude',
245                  'reference':'geographic coordinates',
246                  'units': 'degrees_east',
247                  'valid_range':(-180.,180.),
248                  'axis': 'Y',
249                 },
250         'z' : {'short_name': 'z',
251                'long_name': 'Height',
252                'standard_name': 'height',
253                'reference':'zero at sea-surface',
254                'positive' : 'up',
255                'units': 'meters',
256                'axis': 'Z',
257               },
258         # data variables
259         'ptime' : {'short_name': 'ptime',
260                    'long_name': 'Package Time',
261                    'standard_name': 'none',
262                    'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
263                  },
264         'session' : {'short_name': 'session',
265                      'long_name': 'Session ID',
266                      'standard_name': 'none',
267                      'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
268                  },
269         'psession' : {'short_name': 'ptime',
270                       'long_name': 'Package Session ID',
271                       'standard_name': 'none',
272                       'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
273                  },
274         'record' : {'short_name': 'record',
275                     'long_name': 'Record Number',
276                     'standard_name': 'none',
277                     'units' : 'none',
278                  },
279         'status': {'short_name' : 'status',
280                    'long_name': 'Platform Status Code',
281                    'standard_name': 'none',
282                    'units' : 'none',
283                    'value_map' : platform_info['status_map'],
284                   },
285         'pstatus': {'short_name' : 'pstatus',
286                     'long_name': 'Package Status Code',
287                     'standard_name': 'none',
288                     'units' : 'none',
289                     'value_map' : sensor_info['status_map'],
290                   },
291         'voltage': {'short_name' : 'voltage',
292                     'long_name': sensor_info['voltage_description'],
293                     'standard_name': 'none',
294                     'units': 'volts',
295                     'id_number' : sensor_info['voltage_id'],
296                     'type' : sensor_info['voltage_type'],
297                     'format' : sensor_info['voltage_format'],
298                     'non_standard_units' : sensor_info['voltage_units'],
299                     'range_min' : sensor_info['voltage_range_min'],
300                     'range_max' : sensor_info['voltage_range_max'],
301                    },
302         'memory': {'short_name' : 'memory',
303                    'long_name': sensor_info['memory_description'],
304                    'standard_name': 'none',
305                    'units' : 'none',
306                    'id_number' : sensor_info['memory_id'],
307                    'type' : sensor_info['memory_type'],
308                    'format' : sensor_info['memory_format'],
309                    'non_standard_units' : sensor_info['memory_units'],
310                    'range_min' : sensor_info['memory_range_min'],
311                    'range_max' : sensor_info['memory_range_max'],
312                   },
313         'interval': {'short_name' : 'interval',
314                      'long_name': 'Averaging Interval',
315                      'standard_name': 'averaging_interval',
316                      'units': 'seconds/1000',
317                      'id_number' : sensor_info['interval_id'],
318                      'type' : sensor_info['interval_type'],
319                      'format' : sensor_info['interval_format'],
320                      'non_standard_units' : sensor_info['interval_units'],
321                      'range_min' : sensor_info['interval_range_min'],
322                      'range_max' : sensor_info['interval_range_max'],
323                     },
324         }
325    
326     # dimension names use tuple so order of initialization is maintained
327     dim_inits = (
328         ('ntime', pycdf.NC.UNLIMITED),
329         ('nlat', 1),
330         ('nlon', 1),
331         ('nz', 1),
332         )
333    
334     # using tuple of tuples so order of initialization is maintained
335     # using dict for attributes order of init not important
336     # use dimension names not values
337     # (varName, varType, (dimName1, [dimName2], ...))
338     var_inits = (
339         # coordinate variables
340         ('time',  pycdf.NC.INT,   ('ntime',)),
341         ('lat',   pycdf.NC.FLOAT, ('nlat',)),
342         ('lon',   pycdf.NC.FLOAT, ('nlon',)),
343         ('z',     pycdf.NC.FLOAT, ('nz',)),
344         # data variables
345         ('ptime',    pycdf.NC.INT, ('ntime',)),
346         ('session',  pycdf.NC.INT, ('ntime',)),
347         ('psession', pycdf.NC.INT, ('ntime',)),
348         ('record',   pycdf.NC.INT, ('ntime',)),
349         ('status',   pycdf.NC.INT, ('ntime',)),
350         ('pstatus',  pycdf.NC.INT, ('ntime',)),
351         ('voltage',  pycdf.NC.FLOAT, ('ntime',)),
352         ('memory',   pycdf.NC.INT, ('ntime',)),
353         ('interval', pycdf.NC.INT, ('ntime',)),
354                 )
355    
356     # subset data only to month being processed (see raw2proc.process())
357     i = data['in']
358    
359     # var data
360     var_data = (
361         ('time',     data['time'][i]),
362         ('lat',      sensor_info['lat']),
363         ('lon',      sensor_info['lat']),
364         ('z',        sensor_info['elevation']),
365         ('ptime',    data['ptime'][i]),
366         ('session',  data['session'][i]),
367         ('psession', data['psession'][i]),
368         ('record',   data['record'][i]),
369         ('status',   data['status'][i]),
370         ('pstatus',  data['pstatus'][i]),
371         ('voltage',  data['voltage'][i]),
372         ('memory',   data['memory'][i]),
373         ('interval', data['interval'][i]),
374         )
375    
376     return (global_atts, var_atts, dim_inits, var_inits, var_data)
377
378 def updater(platform_info, sensor_info, data):
379     #
380     global_atts = {
381         # update times of data contained in file (yyyy-mm-dd HH:MM:SS)
382         # last date in monthly file
383         'end_date' : data['dt'][-1].strftime("%Y-%m-%d %H:%M:%S"),
384         'release_date' : nowDt.strftime("%Y-%m-%d %H:%M:%S"),
385         #
386         'modification_date' : nowDt.strftime("%Y-%m-%d %H:%M:%S"),
387         }
388    
389     # data variables
390     # update any variable attributes like range, min, max
391     var_atts = {}
392    
393     # subset data only to month being processed (see raw2proc.process())
394     i = data['in']
395    
396     # data
397     var_data = (
398         ('time',     data['time'][i]),
399         ('ptime',    data['ptime'][i]),
400         ('session',  data['session'][i]),
401         ('psession', data['psession'][i]),
402         ('record',   data['record'][i]),
403         ('status',   data['status'][i]),
404         ('pstatus',  data['pstatus'][i]),
405         ('voltage',  data['voltage'][i]),
406         ('memory',   data['memory'][i]),
407         ('interval', data['interval'][i]),
408         )
409    
410     return (global_atts, var_atts, var_data)
411
Note: See TracBrowser for help on using the browser.