mesonet_hourly.html


001| """Hourly Temperature data from mesonet.agron.iastate.edu.
001| 
001| URL:
001|     https://mesonet.agron.iastate.edu/cgi-bin/request/asos.py?
001|         network     =MN_ASOS
001|         station     =MSP
001|         data        =tmpf
001|         data        =dwpf
001|         data        =relh
001|         data        =p01i
001|         year1       =<date.from.year>   [inclusive]
001|         month1      =<date.from.month>
001|         day1        =<date.from.day>
001|         year2       =<date.end.year>    [exclusive]
001|         month2      =<date.end.month>
001|         day2        =<date.end.day>
001|         tz          =America%2FChicago
001|         format      =onlytdf
001|         latlon      =no
001|         elev        =no
001|         missing     =M
001|         trace       =T
001|         direct      =yes
001|         report_type =3
001|         report_type =4
001| 
001| Alternate:
001|     https://mrcc.purdue.edu/CLIMATE/hourly/station/subdaily
001| 
001| Classes:
001|     MesonetQuery                                    ~query object
001| 
001| Commands:
001|     chart       do_hourly_temps_dewpoints_chart     ~create the hourly temperatures/dew-points chart
001|     get         do_get_data_file                    ~download the hourly temperatures/dew-points data
001|     test        do_test                             ~test
001| 
001| """

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| import datetime as dttm
007| import math
008| import requests as rqst
009| import matplotlib.pyplot as plt
010| import matplotlib.ticker as mlticks
011| import matplotlib.dates as mldates
012| from logger import logger,info,debug,trace
013| from goodies import KWARG, typename
014| ####################################################################################################
015| BasePath = r'C:\CJS\prj\Python\app\weather'
016| DataPath = path.join(BasePath, 'dat')
017| ImgsPath = path.join(BasePath, 'img')
018| Log = logger('mesonet')
019| 
020| CMND = 'chart'
021| ARGS = {
022|     'from': '2026-11-01',
023|     'to'  : '2026-12-01',
024|     #'dpath': BasePath,
025|     'fpath': BasePath,
026|     #'fname': 'mesonet.dat',
027| }
028| 
029| 
030| ##------------------------------------------------------------------------------------------------##
031| DataFilenameTemplate  = 'TC {year}-{month:02} Hourly Temps.tab'
032| ChartFilenameTemplate = '{year}-{month:02} Hourly Temps.png'
033| 
034| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
035| class MesonetQuery (list):
036|     '''Query mesonet for hourly weather data and populate list with results.
036| 
036| Properties:
036|     .start              ~date: data begin date (inclusive)
036|     .final              ~date: data end date (exclusive)
036|     .params             ~str: query parameter string
036|     .url                ~str: query url + parameters
036|     .query              ~request: query object
036| 
036| Methods:
036|     .save               ~save data to a filename
036| 
036| '''

037| 
038|     ServerUrl = r'https://mesonet.agron.iastate.edu/cgi-bin/request/asos.py'
039| 
040|     def __init__ (self, start:str, final:str):
041|         '''Initialize new object.
041| 
041| Create query URL and request data from mesonet based on start and final dates.
041| (Important! The start date is inclusive; the final date is exclusive.)
041| Input dates must be strings in either "YYYY-MM-DD" or "YYYY/MM/DD" format.
041| 
041| '''

042|         if ('-' in start) and ('-' in final):
043|             # Split YYYY-MM-DD text into parts...
044|             year1,month1,day1 = start.split('-')
045|             year2,month2,day2 = final.split('-')
046|         elif ('/' in start) and ('/' in final):
047|             # Split YYYY/MM/DD text into parts...
048|             year1,month1,day1 = start.split('/')
049|             year2,month2,day2 = final.split('/')
050|         else:
051|             raise ValueError(f'Invalid date: {start}, {final}')
052| 
053|         Log.debug(f'First Date: {year1}-{month1}-{day1}')
054|         Log.debug(f'Final Date: {year2}-{month2}-{day2}')
055|         Log.debug()
056|         self.start = dttm.date(int(year1), int(month1), int(day1))
057|         self.final = dttm.date(int(year2), int(month2), int(day2))
058| 
059|         parameters = {
060|             'network': 'MN_ASOS',
061|             'station': 'MSP',
062|             'data': ['tmpf', 'dwpf', 'relh', 'p01i'],
063|             'year1':year1, 'month1':month1, 'day1':day1,
064|             'year2':year2, 'month2':month2, 'day2':day2,
065|             'tz': 'America%2FChicago',
066|             'format': 'onlytdf',
067|             'latlon': 'no',
068|             'elev': 'no',
069|             'missing': 'M',
070|             'trace': 'T',
071|             'direct': 'yes',
072|             'report_type': ['3', '4'],
073|         }
074| 
075|         # Generate the URL parameters for the query...
076|         buf = []
077|         for name,valu in parameters.items():
078|             if isinstance(valu, list):
079|                 for item in valu:
080|                     buf.append(f'{name}={item}')
081|             else:
082|                 buf.append(f'{name}={valu}')
083| 
084|         self.params = '&'.join(buf)
085| 
086|         # Query mesonet and get data...
087|         self.url = str(self)
088|         self.query = rqst.get(self.url)
089|         Log.info(f'query result: {self.query.status_code}')
090|         Log.info()
091|         for nam,val in self.query.headers.items():
092|             Log.debug(f'{nam}: {val}')
093|         Log.info()
094| 
095|         # Process the data...
096|         if self.query.status_code == 200:
097|             for line in self.query.text.split('\n'):
098|                 self.append(line.rstrip())
099| 
100|             Log.info(f'Got {len(self)} rows of data.')
101|             Log.info()
102| 
103|     def save (self, fname, fpath=''):
104|         '''Save data to file.'''
105|         fn = path.join(fpath,fname) if fpath else fname
106|         fp = open(fn, mode='w', encoding='utf-8')
107|         try:
108|             for row in self:
109|                 print(row, file=fp)
110| 
111|             Log.info(f'wrote: {fn}')
112|             Log.info()
113| 
114|         except:
115|             raise
116|         finally:
117|             fp.close()
118| 
119|     def __str__ (self):
120|         '''Printable string version is full query URL.'''
121|         return f'{self.ServerUrl}?{self.params}'
122| 
123|     def __repr__ (self):
124|         '''Debug string version.'''
125|         return f'<{typename(self)} @{id(self):012x}>'
126| 
127| 
128| ##================================================================================================##
129| def do_get_data_file (**kwargs):
130|     '''CMND: Download the hourly temps and dew points data file.'''
131|     dpath = KWARG('dpath', DataPath, str, kwargs)
132|     dname = KWARG('dname', DataFilenameTemplate, str, kwargs)
133|     start = KWARG('from', '2026-1-1', str, kwargs)
134|     final = KWARG('to'  , '2026-2-1', str, kwargs) #NOTE: to is exclusive!
135|     Log.info(f'get-hourly-data-file:: {list(kwargs.keys())}' )
136|     Log.debug(f'{dpath=}')
137|     Log.debug(f'{dname=}')
138|     Log.debug(f'{start=}')
139|     Log.debug(f'{final=}')
140|     Log.info()
141| 
142|     # Query mesonet for the hourly data...
143|     query = MesonetQuery(start, final)
144|     Log.debug(query)
145|     Log.debug()
146| 
147|     # Save data to file...
148|     dname = dname.format(year=yr1, month=mn1)
149|     query.save(dname, dpath)
150| 
151|     Log.info()
152|     return 'Done'
153| 
154| ##================================================================================================##
155| def do_hourly_temps_dewpoints_chart (**kwargs):
156|     '''CMND: Create a chart of hourly temperatures and dew points.'''
157|     dpath = KWARG('dpath', DataPath, str, kwargs)
158|     dname = KWARG('dname', DataFilenameTemplate, str, kwargs)
159|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
160|     fname = KWARG('fname', ChartFilenameTemplate, str, kwargs)
161|     start = KWARG('from', '2026-1-1', str, kwargs)
162|     final = KWARG('to'  , '2026-2-1', str, kwargs) #NOTE: to is exclusive!
163|     Log.info(f'create-hourly-temps-and-dewpoints-chart:: {list(kwargs.keys())}' )
164|     Log.debug(f'{dpath=}')
165|     Log.debug(f'{dname=}')
166|     Log.debug(f'{fpath=}')
167|     Log.debug(f'{fname=}')
168|     Log.debug(f'{start=}')
169|     Log.debug(f'{final=}')
170|     Log.info()
171|     margin = dttm.timedelta(0.25)
172| 
173|     # Query mesonet for the hourly data...
174|     query = MesonetQuery(start, final)
175|     Log.debug(query)
176|     Log.debug()
177| 
178|     # Save data to file...
179|     dname = dname.format(year=query.start.year, month=query.start.month)
180|     query.save(dname, dpath)
181| 
182|     # Need the month name for the chart...
183|     month_name = query.start.strftime('%B')
184| 
185|     # Scan the data into a list for the chart...
186|     xs, ys1, ys2, ys3 = [], [], [], []
187| 
188|     for fields in [row.split('\t') for row in query[1:]]: #NOTE: skip the header row!
189|         if len(fields) < 2:
190|             continue
191|         if (fields[2] == 'M') or (fields[3] == 'M') or (fields[4] == 'M'):
192|             continue
193|         Log.trace(fields)
194|         xs.append(dttm.datetime.strptime(fields[1], '%Y-%m-%d %H:%M'))
195|         ys1.append(float(fields[2]))
196|         ys2.append(float(fields[3]))
197|         ys3.append(float(fields[4])) #NOTE: not using in this chart.
198|     Log.trace()
199| 
200|     for x,y1,y2,y3 in zip(xs,ys1,ys2,ys3):
201|         Log.trace(f'{x:%b %d %H:%M} {y1-y2:2.0f} {y1:2.0f} {y2:2.0f} ({y3:5.2f})')
202|     Log.trace()
203| 
204|     ymax = float(math.ceil(max(ys1)/10) * 10)
205|     ymin = float(math.floor(min(ys2)/10) * 10)
206| 
207|     # Create the chart...
208|     fig, ax = plt.subplots()
209|     fig.suptitle(f'Hourly Temps for {month_name} {query.start.year}', fontsize=14, fontweight='bold')
210|     fig.set_figwidth(15.0)
211|     fig.set_figheight(5.0)
212|     fig.subplots_adjust(left=0.045, right=0.993, bottom=0.14, top=0.93)
213| 
214|     ax.xaxis_date()
215|     ax.set_xlabel('Date/Hour', fontsize=11, fontweight='bold')
216|     ax.set_xlim(xs[0]-margin, xs[-1]+margin)
217|     ax.xaxis.set_major_locator(mldates.DayLocator())
218|     ax.xaxis.set_minor_locator(mlticks.NullLocator())
219|     ax.xaxis.set_major_formatter(mldates.DateFormatter('%m-%d'))
220|     ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
221| 
222|     for tick in ax.xaxis.get_major_ticks():
223|         tick.label1.set_rotation('vertical')
224|         tick.label1.set_size(9)
225| 
226|     ax.set_ylabel('Temp', fontsize=11, fontweight='bold')
227|     ax.set_ylim(ymin, ymax)
228|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(10.0))
229|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(1.0))
230|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%.0f'))
231|     ax.yaxis.set_minor_formatter(mlticks.NullFormatter())
232| 
233|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
234|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
235|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
236|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
237| 
238|     ax.plot(xs,ys1, label='Air Temp' , color='#ff0000', lw=2.0, alpha=0.75, zorder=12)
239|     ax.plot(xs,ys2, label='Dew Point', color='#0000ff', lw=2.0, alpha=0.75, zorder=11)
240| 
241|     ax.fill_between(xs,ys1,ys2, color='#9f9f9f', lw=0, alpha=0.50, zorder=10)
242| 
243|     fig.legend(ncols=1, fontsize=10, loc='upper right', bbox_to_anchor=(0.99,0.93))
244| 
245|     # Save the chart image...
246|     fname = fname.format(year=query.start.year, month=query.start.month)
247|     chartname = path.join(fpath,fname) if fpath else fname
248| 
249|     fig.savefig(chartname)
250|     Log.info('wrote: %s' % chartname)
251|     Log.info()
252|     return chartname
253| 
254| ##================================================================================================##
255| def do_test (**kwargs):
256|     '''CMND: Do a test.'''
257|     dpath = KWARG('dpath', DataPath, str, kwargs)
258|     dname = KWARG('dname', DataFilenameTemplate, str, kwargs)
259|     fpath = KWARG('fpath', BasePath, str, kwargs)
260|     fname = KWARG('fname', 'test.out', str, kwargs)
261|     Log.info(f'test:: {list(kwargs.keys())}' )
262|     Log.debug(f'{dpath=}')
263|     Log.debug(f'{dname=}')
264|     Log.debug(f'{fpath=}')
265|     Log.debug(f'{fname=}')
266|     Log.info()
267|     Log.info()
268|     return 'Done'
269| ####################################################################################################
270| def dispatch (cmd, **kwargs):
271|     '''Dispatch to a module function based on CMD.'''
272|     Log.info(f'CMD: {cmd}')
273|     for kw in kwargs:
274|         Log.debug(f'argument[{kw}]: {kwargs[kw]}')
275|     Log.info()
276|     if cmd == 'get': return do_get_data_file(**kwargs)
277|     if cmd == 'chart': return do_hourly_temps_dewpoints_chart(**kwargs)
278|     if cmd == 'test': return do_test(**kwargs)
279|     return 'Nothing to do!'
280| ####################################################################################################
281| if __name__ == '__main__':
282|     print(f'autorun: {argv[0]}')
283|     Log.start(path.join(BasePath,'mesonet_hourly.log'))
284|     Log.level(trace())
285|     Log.info(argv[0])
286|     cmd = argv[1] if 1 < len(argv) else CMND
287|     kwargs = ARGS
288|     for a in argv[2:]:
289|         nv = a.split('=', 1)
290|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
291|         Log.debug(f'{nv[0]}: "{kwargs[nv[0]]}"')
292|     Log.info()
293|     try:
294|         print(f'CMD: {cmd}')
295|         print()
296|         obj = dispatch(cmd, **kwargs)
297|         print(obj)
298|         print()
299|         Log.info(obj)
300|         Log.info()
301|     except:
302|         etype, evalue, tb = exc_info()
303|         ts = extract_tb(tb)
304|         Log.error()
305|         Log.error(f'{etype.__name__}: {evalue!s}')
306|         Log.error()
307|         for t in ts[-5:]:
308|             Log.error(f'[{t[1]}] {t[2]} ({t[0]})')
309|             Log.error(f' {t[3]}')
310|             Log.error()
311|         raise
312|     finally:
313|         Log.info()
314|         Log.end()
315| ####################################################################################################
316| '''eof'''
317|