db_charts.html


001| '''Weather Database Charts.
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from datetime import date, datetime, timedelta
007| from math import floor, ceil
008| from logger import logger, info, debug, trace
009| from goodies import KWARG
010| from facts import MonthNames
011| from dates import CST
012| from mlchart import mlchart
013| from db_weather import dbWeather, FirstYear, LastYear
014| import matplotlib.pyplot as plt
015| from matplotlib.ticker import MultipleLocator, NullFormatter, FormatStrFormatter
016| from matplotlib.dates import DayLocator, DateFormatter
017| ####################################################################################################
018| BasePath = r'C:\CJS\prj\Python\app\weather'
019| DataPath = path.join(BasePath, 'dat')
020| Log = logger('dbCharts')
021| 
022| ##------------------------------------------------------------------------------------------------##
023| 
024| ##================================================================================================##
025| def getmin (ns):
026|     smallest = min(ns)
027|     bottom = (floor(smallest / 10) * 10)
028|     return (bottom if bottom < smallest else bottom-10)
029| 
030| def getmax (ns):
031|     biggest = max(ns)
032|     top = (ceil(biggest / 10) * 10)
033|     return (top if biggest < top else top+10)
034| 
035| def nextmonth (dt):
036|     if dt.month == 12:
037|         return date(dt.year+1, 1, 1)-timedelta(1)
038|     return date(dt.year, dt.month+1, 1)-timedelta(1)
039| 
040| ##------------------------------------------------------------------------------------------------##
041| SQL = '''
041| SELECT
041|     "line_date", "line_type", "hourly_temp"
041| FROM "%s"
041| WHERE ("line_type" = 'SAO')
041|     OR (substr("line_type",1,2) = 'FM')
041|     OR (substr("line_type",1,2) = 'SY')
041| ORDER BY "line_date"
041| '''

042| ##================================================================================================##
043| def do_span_chart (**kwargs):
044|     fpath = KWARG('fpath', BasePath, str, kwargs)
045|     fname = KWARG('fname', 'temperatures.png', str, kwargs)
046|     Log.info('span-chart:: %s' % str(list(kwargs.keys())))
047|     Log.info()
048| 
049|     # Query for data...
050|     tbl = dbWeather()
051|     rs = tbl.db_query(SQL % tbl.name)
052|     if not rs: Log.warn('No data!'); return 'No records found.'
053| 
054|     Log.debug()
055|     Log.debug(f'query returned {len(rs)} records')
056| 
057|     daily = {}
058|     for r in rs:
059|         stemp = r[2]
060|         if (len(stemp) == 0) or (stemp == '*'):
061|             continue
062|         dt = datetime.fromisoformat(r[0])
063|         temp = int(stemp[:-1] if stemp.endswith('s') else stemp)
064|         key = date(dt.year, dt.month, dt.day)
065|         if key not in daily:
066|             daily[key] = (temp, temp)
067|         else:
068|             hi = max(temp, daily[key][1])
069|             lo = min(temp, daily[key][0])
070|             daily[key] = (lo, hi)
071| 
072|     dat = sorted(daily.items(), key=lambda x:x[0])
073|     Log.debug(f'generated {len(dat)} daily records')
074|     Log.debug(f'first item: {dat[0]}')
075|     Log.debug(f'last item: {dat[-1]}')
076|     Log.debug()
077| 
078|     dotd = lambda dt: (dt-date(int(dt.year/10)*10,1,1)).days
079| 
080|     hi1960 = [(dotd(d[0]), d[1][1]) for d in dat if 1960 <= d[0].year <= 1969]
081|     lo1960 = [(dotd(d[0]), d[1][0]) for d in dat if 1960 <= d[0].year <= 1969]
082|     xs1960hi = [d[0] for d in hi1960]
083|     ys1960hi = [d[1] for d in hi1960]
084|     xs1960lo = [d[0] for d in lo1960]
085|     ys1960lo = [d[1] for d in lo1960]
086| 
087|     hi1970 = [(dotd(d[0]), d[1][1]) for d in dat if 1970 <= d[0].year <= 1979]
088|     lo1970 = [(dotd(d[0]), d[1][0]) for d in dat if 1970 <= d[0].year <= 1979]
089|     xs1970hi = [d[0] for d in hi1970]
090|     ys1970hi = [d[1] for d in hi1970]
091|     xs1970lo = [d[0] for d in lo1970]
092|     ys1970lo = [d[1] for d in lo1970]
093| 
094|     hi1980 = [(dotd(d[0]), d[1][1]) for d in dat if 1980 <= d[0].year <= 1979]
095|     lo1980 = [(dotd(d[0]), d[1][0]) for d in dat if 1980 <= d[0].year <= 1979]
096|     xs1980hi = [d[0] for d in hi1980]
097|     ys1980hi = [d[1] for d in hi1980]
098|     xs1980lo = [d[0] for d in lo1980]
099|     ys1980lo = [d[1] for d in lo1980]
100| 
101|     hi1990 = [(dotd(d[0]), d[1][1]) for d in dat if 1990 <= d[0].year <= 1979]
102|     lo1990 = [(dotd(d[0]), d[1][0]) for d in dat if 1990 <= d[0].year <= 1979]
103|     xs1990hi = [d[0] for d in hi1990]
104|     ys1990hi = [d[1] for d in hi1990]
105|     xs1990lo = [d[0] for d in lo1990]
106|     ys1990lo = [d[1] for d in lo1990]
107| 
108|     hi2020 = [(dotd(d[0]), d[1][1]) for d in dat if 2020 <= d[0].year <= 2029]
109|     lo2020 = [(dotd(d[0]), d[1][0]) for d in dat if 2020 <= d[0].year <= 2029]
110|     xs2020hi = [d[0] for d in hi2020]
111|     ys2020hi = [d[1] for d in hi2020]
112|     xs2020lo = [d[0] for d in lo2020]
113|     ys2020lo = [d[1] for d in lo2020]
114| 
115|     xmax = max(len(xs1960hi),len(xs1970hi),len(xs1980hi),len(xs1990hi),len(xs2020hi))
116| 
117|     class ml_span_chart (mlchart):
118|         def __init__ (self, data, **kwargs):
119|             """New instance."""
120|             super().__init__((16.0, 6.0), **kwargs)
121|             self.data = data
122|             self.title = 'Temperatures (1960s-2020s)'
123|             self.x_limit = (0, xmax)
124|             self.y_limit = (-40.0, 110.0)
125|             self.x_title = 'Day of the Decade'
126|             self.y_title = 'Temperature'
127|             self.x_grids = (360, 30)
128|             self.y_grids = (20.0, 2.0)
129|             self.x_tickf = '%d'
130|             self.y_tickf = '%+.1f'
131|             self.x_tickr = True         # rotate X axis
132|             self.x_dates = False        # use make_x_date_axis instead
133|             self.title_kw['fontsize'] = 16
134|             self.title_kw['fontweight'] = 'bold'
135|             self.x_title_kw['fontsize'] = 12
136|             self.y_title_kw['fontsize'] = 12
137|             self.margins = dict(left=0.060, right=0.995, bottom=0.110, top=0.940)
138| 
139|         def plotter (self):
140|             """Plot something!"""
141|             self.ax.plot(xs1960lo,ys1960lo, color='#dfdfdf', label='1960 Lo', lw=0.70, zorder=11, alpha=0.85)
142|             self.ax.plot(xs1970lo,ys1970lo, color='#bfbfbf', label='1970 Lo', lw=0.70, zorder=12, alpha=0.85)
143|             self.ax.plot(xs1980lo,ys1980lo, color='#9f9f9f', label='1980 Lo', lw=0.70, zorder=13, alpha=0.85)
144|             self.ax.plot(xs1990lo,ys1990lo, color='#7f7f7f', label='1990 Lo', lw=0.70, zorder=14, alpha=0.85)
145|             self.ax.plot(xs2020lo,ys2020lo, color='#0000ff', label='2020 Lo', lw=1.00, zorder=15, alpha=0.85)
146| 
147|             self.ax.plot(xs1960hi,ys1960hi, color='#dfdfdf', label='1960 Hi', lw=0.70, zorder=11, alpha=0.85)
148|             self.ax.plot(xs1970hi,ys1970hi, color='#bfbfbf', label='1970 Hi', lw=0.70, zorder=12, alpha=0.85)
149|             self.ax.plot(xs1980hi,ys1980hi, color='#9f9f9f', label='1980 Hi', lw=0.70, zorder=13, alpha=0.85)
150|             self.ax.plot(xs1990hi,ys1990hi, color='#7f7f7f', label='1990 Hi', lw=0.70, zorder=14, alpha=0.85)
151|             self.ax.plot(xs2020hi,ys2020hi, color='#ff0000', label='2020 Hi', lw=1.00, zorder=15, alpha=0.85)
152|             self.ax.legend(loc='lower left', ncol=5)
153| 
154|     cht = ml_span_chart(None, fname=fname, fpath=fpath)
155|     cht.make()
156|     Log.info(f'wrote: {path.join(cht.fpath, cht.fname)}')
157|     Log.info()
158|     return 'Done'
159| 
160| ##================================================================================================##
161| def do_month_compare (**kwargs):
162|     Log.info('month-compare:: %s' % str(list(kwargs.keys())))
163|     fpath = KWARG('fpath', BasePath, str, kwargs)
164|     fname = KWARG('fname', 'months_%02d.png', str, kwargs)
165|     month = KWARG('month', 1, int, kwargs)
166|     tbl = dbWeather()
167|     sql = 'SELECT line_date,line_type,hourly_temp FROM %s ORDER BY line_date'
168| 
169|     class ml_month_compare (mlchart):
170|         def __init__ (self, plotdata, **kwargs):
171|             """New instance."""
172|             super().__init__((16.0, 6.0), **kwargs)
173|             self.plotdata = plotdata
174|             self.x_title = 'Day of the Month'
175|             self.y_title = 'High/Low Temperatures'
176|             self.x_limit = kwargs['xlimit']
177|             self.x_grids = (1, None)
178|             self.y_grids = (10.0, 2.0)
179|             self.x_tickf = '%d'
180|             self.y_tickf = '%+.1f'
181|             self.x_tickr = True         # rotate X axis
182|             self.x_dates = False        # use make_x_date_axis instead
183|             self.title_kw['fontsize'] = 16
184|             self.title_kw['fontweight'] = 'bold'
185|             self.x_title_kw['fontsize'] = 12
186|             self.y_title_kw['fontsize'] = 12
187|             self.margins = dict(left=0.055, right=0.995, bottom=0.090, top=0.940)
188| 
189|         def plotter (self):
190|             """Plot something!"""
191|             for ix,item in enumerate(sorted(self.plotdata.items(), key=lambda t:t[0])):
192|                 year,data = item
193|                 xs = [t[0] for t in data]
194|                 ys = [t[1] for t in data]
195|                 if year == LastYear:
196|                     self.ax.plot(xs,ys, c='#ff0000', lw=2.0, alpha=0.66, zorder=201)
197|                     continue
198|                 if year == (LastYear-1):
199|                     self.ax.plot(xs,ys, c='#ff003f', lw=1.5, alpha=0.66, zorder=101)
200|                     continue
201|                 # Default...
202|                 self.ax.plot(xs,ys, c='#7f7f7f', lw=1.0, alpha=0.66, zorder=(11+ix))
203| 
204|         def make_x_axis_spcl (self):
205|             self.ax.xaxis_date()
206|             # Axis tick marks...
207|             self.ax.xaxis.set_major_locator(DayLocator())
208|             # Axis tick labels...
209|             self.ax.xaxis.set_major_formatter(DateFormatter(self.x_tickf))
210| 
211|     # Query for data...
212|     tbl = dbWeather()
213|     rs = tbl.db_query(sql % tbl.name)
214|     if not rs: Log.warn('No data!'); return 'No records found.'
215| 
216|     Log.debug()
217|     Log.debug(f'query returned {len(rs)} records')
218| 
219|     month_data = {}
220|     for rcd in rs:
221|         if rcd[1] not in ['SAO', 'FM-12', 'FM-15', 'FM-16', 'SY-SA', 'SY-MT']:
222|             continue
223| 
224|         if len(rcd[2]) == 0:
225|             continue
226| 
227|         dttm = datetime.fromisoformat(rcd[0])
228|         if dttm.month != month:
229|             continue
230| 
231|         if dttm.year not in month_data:
232|             month_data[dttm.year] = []
233| 
234|         try:
235|             temp = int(rcd[2][:-1] if rcd[2].endswith('s') else rcd[2])
236|         except:
237|             Log.error(f'Invalid temperature: {rcd[2]}')
238| 
239|         datum = (dttm.replace(year=LastYear), temp)
240|         month_data[dttm.year].append(datum)
241| 
242|     xmaxs = []
243|     ymaxs = []
244|     ymins = []
245|     for year,data in month_data.items():
246|         xs = [t[0] for t in data]
247|         ys = [t[1] for t in data]
248|         xmaxs.append(len(xs))
249|         ymaxs.append(getmax(ys))
250|         ymins.append(getmin(ys))
251|     xmax = max(xmaxs)
252|     ymin = min(ymins)
253|     ymax = max(ymaxs)
254| 
255|     dt = date(LastYear,month,1)
256|     props = {
257|         'title':f'Temperatures for {MonthNames[month]} ({FirstYear}-{LastYear})',
258|         'fname':fname%month, 'fpath':fpath,
259|         'xlimit':(dt, nextmonth(dt)),
260|         'ymin':ymin, 'ymax':ymax,
261|     }
262|     cht = ml_month_compare(month_data, **props)
263|     cht.make()
264|     Log.info(f'wrote: {path.join(cht.fpath, cht.fname)}')
265|     Log.info()
266|     return 'Done'
267| 
268| ##================================================================================================##
269| def do_test (**kwargs):
270|     Log.info('test:: %s' % str(list(kwargs.keys())))
271|     fpath = KWARG('fpath', BasePath, str, kwargs)
272|     fname = KWARG('fname', 'test.list', str, kwargs)
273|     tbl = dbWeather()
274| 
275|     Log.info()
276|     return 'Done'
277| ####################################################################################################
278| def dispatch (cmd, **kwargs):
279|     Log.info('command: %s' % cmd)
280|     for kw in kwargs:
281|         Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
282|     Log.info()
283|     if cmd == 'span': return do_span_chart(**kwargs)
284|     if cmd == 'comp': return do_month_compare(**kwargs)
285|     if cmd == 'test': return do_test(**kwargs)
286|     return 'Nothing to do!'
287| ####################################################################################################
288| if __name__ == '__main__':
289|     print('autorun: %s' % argv[0])
290|     Log.start(path.join(BasePath,'db_charts.log'))
291|     Log.level(trace())
292|     cmd = argv[1] if 1 < len(argv) else '' ##CMD##
293|     kwargs = {}
294|     for a in argv[2:]:
295|         nv = a.split('=', 1)
296|         kwargs[nv[0]] = nv[1] if 1 < len(nv) else ''
297|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
298|     try:
299|         obj = dispatch(cmd, **kwargs)
300|         print(obj)
301|         Log.info(obj)
302|     except:
303|         etype, evalue, tb = exc_info()
304|         ts = extract_tb(tb)
305|         Log.error()
306|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
307|         for t in ts[-5:]:
308|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
309|             Log.error(' %s' % t[3])
310|         raise
311|     finally:
312|         Log.end()
313| ####################################################################################################
314| '''eof'''
315|