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

root/raw2proc/tags/raw2proc-1.0/proc_jpier_ascii_met.py

Revision 320 (checked in by haines, 14 years ago)

catch-up trunk to production code running on cromwell

Line 
1 #!/usr/bin/env python
2 # Last modified:  Time-stamp: <2009-12-15 08:40:54 haines>
3 """
4 how to parse data, and assert what data and info goes into
5 creating and updating monthly netcdf files
6
7 Texas Weather Instruments - Weather Processing System (WPS) met data
8         delimited ASCII file like:
9         year mon day hhmm       epoch  tmean hmean wsmean wdmean barom   dewPt wchill rrmean rday rmonth rterm
10
11 parser : output delimited ASCII file from onsite perl script
12 creator : lat, lon, time, air_temp, humidity, wspd, wdir, air_pressure,
13                   dew_temp, wchill, rainfall_rate, rainfall_day, rainfall_month, rainfall_term
14 updater : time, air_temp, humidity, wspd, wdir, air_pressure,
15                   dew_temp, wchill, rainfall_rate, rainfall_day, rainfall_month, rainfall_term
16
17 Examples
18 --------
19
20 >> (parse, create, update) = load_processors('proc_jpier_ascii_met')
21 or
22 >> si = get_config(cn+'.sensor_info')
23 >> (parse, create, update) = load_processors(si['met']['proc_module'])
24
25 >> lines = load_data(filename)
26 >> data = parse(platform_info, sensor_info, lines)
27 >> create(platform_info, sensor_info, data) or
28 >> update(platform_info, sensor_info, data)
29
30 """
31
32 from raw2proc import *
33 from procutil import *
34 from ncutil import *
35 import time
36
37 now_dt = datetime.utcnow()
38 now_dt.replace(microsecond=0)
39
40 def parser(platform_info, sensor_info, lines):
41         """
42         parse and assign met data from JPIER TWS WPS text file
43
44         """
45  
46         i = 0
47
48         # drop header row from incoming lines list
49         if lines[0].startswith('year',0,5):
50                 # print "... Header row present, skipping ..."
51                 del lines[0]
52        
53          
54         # sort file by fields 0-5
55         lines.sort()
56            
57    
58         for line in lines:
59                 # split line and parse float and integers
60                 tws = []
61                 # data row looks like:
62                 # 2008  1  1 0000 1199163600  17.2  84.8   0.00 0  1015.10  14.4  17.2 1729.1   0.0     0.0 1031.5
63       
64                 sw = re.split('\s+', line)
65                 for s in sw:
66                         m = re.search(REAL_RE_STR, s)
67                         if m:
68                                 tws.append(float(m.groups()[0]))
69                 # assign specific fields
70                 n = len(tws)
71
72                 # get sample datetime in UTC from data
73                 # use epoch tws[4] to get time in UTC
74                 sample_str = '%04d-%02d-%02d %02d:%02d:00' % tuple(time.gmtime(float(tws[4]))[0:5])
75                 sample_dt = scanf_datetime(sample_str, fmt='%Y-%m-%d %H:%M:%S')
76
77                 air_temp = tws[5]          # Air Temperature (deg F)
78                 humidity = tws[6]               # Humidity (%)
79                 dew_temp = tws[10]       # Dew Point (deg F)   
80                 air_pressure = tws[9]   # Air Pressure (Tmean, sec)
81                 wspd = tws[7]    # Mean Wind Speed (knots)
82                 wdir = tws[8]      # Mean Wind Direction (deg from N)
83                 wchill = tws[11]        # Wind Chill (deg F)
84                 rainfall_rate = tws[12]  # Rainfall Rate ()
85                 rainfall_day = tws[13]   # Rainfall amount last 24 hours (in)
86                 rainfall_month = tws[14] # Rainfall amount last month (in)
87                 rainfall_term = tws[15]  # Rainfall amount since installation (in)
88
89                 # set up dict of data if first line
90                 if i==0:
91                         data = {
92                                 'dt' : numpy.array(numpy.ones((len(lines),), dtype=object)*numpy.nan),
93                                 'time' : numpy.array(numpy.ones((len(lines),), dtype=long)*numpy.nan),
94                                 'air_temp' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
95                                 'humidity' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
96                                 'dew_temp' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
97                                 'air_pressure' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
98                                 'wspd' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
99                                 'wdir' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
100                                 'wchill' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
101                                 'rainfall_rate' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
102                                 'rainfall_day' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
103                                 'rainfall_month' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
104                                 'rainfall_term' : numpy.array(numpy.ones((len(lines)), dtype=float)*numpy.nan),
105                                 }
106                
107                 data['dt'][i] = sample_dt # sample datetime
108                 data['time'][i] = dt2es(sample_dt) # sample time in epoch seconds
109                 data['air_temp'][i] = air_temp
110                 data['humidity'][i] = humidity
111                 data['dew_temp'][i] = dew_temp
112                 data['air_pressure'][i] =  air_pressure
113                 data['wspd'][i] =  wspd
114                 data['wdir'][i] = wdir
115                 data['wchill'][i] = wchill
116                 data['rainfall_rate'][i] = rainfall_rate
117                 data['rainfall_day'][i] =  rainfall_day
118                 data['rainfall_month'][i] =  rainfall_month
119                 data['rainfall_term'][i] = rainfall_term
120                 i = i+1
121
122         return data
123
124 def creator(platform_info, sensor_info, data):
125         #
126         #
127         title_str = sensor_info['description']+' at '+ platform_info['location']
128         global_atts = {
129                 'title' : title_str,
130                 'institution' : 'University of North Carolina at Chapel Hill (UNC-CH)',
131                 'institution_url' : 'http://nccoos.org',
132                 'institution_dods_url' : 'http://nccoos.org',
133                 'metadata_url' : 'http://nccoos.org',
134                 'references' : 'http://nccoos.org',
135                 'contact' : 'Jesse Cleary (jcleary@email.unc.edu)',
136                 #
137                 'source' : 'TWS Met station observation',
138                 'history' : 'raw2proc using ' + sensor_info['process_module'],
139                 'comment' : 'File created using pycdf'+pycdfVersion()+' and numpy '+pycdfArrayPkg(),
140                 # conventions
141                 'Conventions' : 'CF-1.0; SEACOOS-CDL-v2.0',
142                 # SEACOOS CDL codes
143                 'format_category_code' : 'fixed-point',
144                 'institution_code' : platform_info['institution'],
145                 'platform_code' : platform_info['id'],
146                 'package_code' : sensor_info['id'],
147                 # institution specific
148                 'project' : 'North Carolina Coastal Ocean Observing System (NCCOOS)',
149                 'project_url' : 'http://nccoos.org',
150                 # timeframe of data contained in file yyyy-mm-dd HH:MM:SS
151                 'start_date' : data['dt'][0].strftime("%Y-%m-%d %H:%M:%S"),
152                 'end_date' : data['dt'][-1].strftime("%Y-%m-%d %H:%M:%S"),
153                 'release_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
154                 #
155                 'creation_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
156                 'modification_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
157                 'process_level' : 'level1',
158                 #
159                 # must type match to data (e.g. fillvalue is real if data is real)
160                 '_FillValue' : -99999.,
161                 }
162
163         var_atts = {
164                 # coordinate variables
165                 'time' : {'short_name': 'time',
166                                   'long_name': 'Sample Time',
167                                   'standard_name': 'time',
168                                   'units': 'seconds since 1970-1-1 00:00:00 -0', # UTC
169                                   'axis': 'T',
170                                   },
171                 'lat' : {'short_name': 'lat',
172                                  'long_name': 'Latitude in Decimal Degrees',
173                                  'standard_name': 'latitude',
174                                  'reference':'geographic coordinates',
175                                  'units': 'degrees_north',
176                                  'valid_range':(-90.,90.),
177                                  'axis': 'Y',
178                                  },
179                 'lon' : {'short_name': 'lon',
180                                  'long_name': 'Longitude in Decimal Degrees',
181                                  'standard_name': 'longitude',
182                                  'reference':'geographic coordinates',
183                                  'units': 'degrees_east',
184                                  'valid_range':(-180.,180.),
185                                  'axis': 'Y',
186                                  },
187                 'z' : {'short_name': 'z',
188                                 'long_name': 'Height',
189                                 'standard_name': 'height',
190                                 'reference':'zero at sea-surface',
191                                 'positive': 'up',
192                                 'units': 'm',
193                                 'axis': 'Z',
194                                 },
195                 # data variables
196                 
197                 'air_temp' :    {'short_name': 'air_temp',
198                                                 'long_name': 'Air Temperature',
199                                                 'standard_name': 'air_temperature',
200                                                 'units': 'degrees_Celsius',
201                                                 },
202                 'humidity' :    {'short_name': 'humidity',
203                                                 'long_name': 'Humidity',
204                                                 'standard_name': 'humidity',
205                                                 'units': '%',
206                                                 },
207                 'dew_temp' :    {'short_name': 'dew_temp',
208                                                 'long_name': 'Dew Temperature',
209                                                 'standard_name': 'dew_temp',                                             
210                                                 'units': 'degrees_Celsius',
211                                                 },
212                 'air_pressure' : {'short_name': 'air_pressure',
213                                                 'long_name': 'Air Pressure at Barometer Height',
214                                                 'standard_name': 'air_pressure',                                                 
215                                                 'units': 'hPa',
216                                                 },
217                 'wspd' :        {'short_name': 'wspd',
218                                                 'long_name': 'Wind Speed',
219                                                 'standard_name': 'wind_speed',
220                                                 'units': 'm s-1',
221                                                 'can_be_normalized': 'no',
222                                                 },
223                 'wdir' :        {'short_name': 'wdir',
224                                                 'long_name': 'Wind Direction from',
225                                                 'standard_name': 'wind_from_direction',
226                                                 'reference': 'clockwise from True North',
227                                                 'valid_range': '0., 360',
228                                                 'units': 'degrees',
229                                                 },
230                 'wchill' :      {'short_name': 'wchill',
231                                                 'long_name': 'Wind Chill',
232                                                 'standard_name': 'wind_chill',
233                                                 'units': 'degrees_Celsius',
234                                                 },
235                 'rainfall_rate' :       {'short_name': 'rR',
236                                                 'long_name': 'Rainfall Rate',
237                                                 'standard_name': 'rainfall_rate',
238                                                 'units': 'mm hr-1',
239                                                 },
240                 'rainfall_day' : {'short_name': 'rD',
241                                                 'long_name': 'Rainfall Day',
242                                                 'standard_name': 'rainfall_day',
243                                                 'units': 'mm',
244                                                 },
245                 'rainfall_month' : {'short_name': 'rM',
246                                                 'long_name': 'Rainfall Month',
247                                                 'standard_name': 'rainfall_month',
248                                                 'units': 'mm',
249                                                 },
250                 'rainfall_term' : {'short_name': 'rT',
251                                                 'long_name': 'Rainfall Term',
252                                                 'standard_name': 'rainfall_term',
253                                                 'units': 'mm',
254                                                 },
255         }
256
257         # dimension names use tuple so order of initialization is maintained
258         dim_inits = (
259                 ('ntime', NC.UNLIMITED),
260                 ('nlat', 1),
261                 ('nlon', 1),
262                 ('nz', 1)
263                 )
264
265         # using tuple of tuples so order of initialization is maintained
266         # using dict for attributes order of init not important
267         # use dimension names not values
268         # (varName, varType, (dimName1, [dimName2], ...))
269         var_inits = (
270                 # coordinate variables
271                 ('time', NC.INT, ('ntime',)),
272                 ('lat', NC.FLOAT, ('nlat',)),
273                 ('lon', NC.FLOAT, ('nlon',)),
274                 ('z',  NC.FLOAT, ('nz',)),
275                 # data variables
276                 ('air_temp', NC.FLOAT, ('ntime',)),
277                 ('humidity', NC.FLOAT, ('ntime',)),
278                 ('dew_temp', NC.FLOAT, ('ntime',)),
279                 ('air_pressure', NC.FLOAT, ('ntime',)),
280                 ('wspd', NC.FLOAT, ('ntime',)),
281                 ('wdir', NC.FLOAT, ('ntime',)),
282                 ('wchill', NC.FLOAT, ('ntime',)),
283                 ('rainfall_rate', NC.FLOAT, ('ntime',)),
284                 ('rainfall_day', NC.FLOAT, ('ntime',)),
285                 ('rainfall_month', NC.FLOAT, ('ntime',)),
286                 ('rainfall_term', NC.FLOAT, ('ntime',)),
287                 )
288
289         # subset data only to month being processed (see raw2proc.process())
290         i = data['in']
291
292         # var data
293         var_data = (
294                 ('lat',  platform_info['lat']),
295                 ('lon', platform_info['lon']),
296                 ('z', 6),
297                 #
298                 ('time', data['time'][i]),
299                 ('air_temp', data['air_temp'][i]),
300                 ('humidity', data['humidity'][i]),
301                 ('dew_temp', data['dew_temp'][i]),
302                 ('air_pressure', data['air_pressure'][i]),
303                 ('wspd', data['wspd'][i]),
304                 ('wdir', data['wdir'][i]),
305                 ('wchill', data['wchill'][i]),
306                 ('rainfall_rate', data['rainfall_rate'][i]),
307                 ('rainfall_day', data['rainfall_day'][i]),
308                 ('rainfall_month', data['rainfall_month'][i]),
309                 ('rainfall_term', data['rainfall_term'][i]),
310                 )
311                
312         return (global_atts, var_atts, dim_inits, var_inits, var_data)
313
314 def updater(platform_info, sensor_info, data):
315         #
316         global_atts = {
317                 # update times of data contained in file (yyyy-mm-dd HH:MM:SS)
318                 # last date in monthly file
319                 'end_date' : data['dt'][-1].strftime("%Y-%m-%d %H:%M:%S"),
320                 'release_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
321                 #
322                 'modification_date' : now_dt.strftime("%Y-%m-%d %H:%M:%S"),
323                 }
324
325         # data variables
326         # update any variable attributes like range, min, max
327         var_atts = {}
328         # var_atts = {
329         #       'u': {'max': max(data.u),
330         #                 'min': min(data.v),
331         #                 },
332         #       'v': {'max': max(data.u),
333         #                 'min': min(data.v),
334         #                 },
335         #       }
336         
337         # subset data only to month being processed (see raw2proc.process())
338         i = data['in']
339
340         # data
341         var_data = (
342                 ('time', data['time'][i]),
343                 ('air_temp', data['air_temp'][i]),
344                 ('humidity', data['humidity'][i]),
345                 ('dew_temp', data['dew_temp'][i]),
346                 ('air_pressure', data['air_pressure'][i]),
347                 ('wspd', data['wspd'][i]),
348                 ('wdir', data['wdir'][i]),
349                 ('wchill', data['wchill'][i]),
350                 ('rainfall_rate', data['rainfall_rate'][i]),
351                 ('rainfall_day', data['rainfall_day'][i]),
352                 ('rainfall_month', data['rainfall_month'][i]),
353                 ('rainfall_term', data['rainfall_term'][i]),
354                 )
355
356         return (global_atts, var_atts, var_data)
357
358 #
359
Note: See TracBrowser for help on using the browser.