dnr_charts.html
001| '''Monthly Hi/Lo Temperature Charts.
001|
001| JSON File:
001| version: 1
001| name: "Daily High/Low Temperatures by Month"
001| url: "https://www.dnr.state.mn.us/climate/historical/lcd.html?loc=msp"
001| created-date: "Sat Jun 1 14:26:22 2024"
001| updated-date: "Thu Jun 12 09:40:40 2025"
001| months (array/dicts):
001| year (int): two-digit year (or zero to disable entry)
001| month (int): [1-12]
001| xmin (int): first day of the month
001| xmax (int): last day of the month
001| ymin (int): chart minimum temperature
001| ymax (int): chart maximum temperature
001| days (array/array/int): [day, lo, hi]
001|
001| Classes:
001| month_temperature_data (json-record)
001|
001| mlchart_month_temps (data, **kwargs)
001| mlchart_month_temps_all_years (data, **kwargs)
001| mlchart_histogram (data, **kwargs)
001|
001| Functions:
001| getmin (number_list)
001| getmax (number_list)
001| Datum (year, month, rcd)
001|
001| load_json_data (fname, fpath)
001| get_month_data (year, month, fname, fpath, verbose)
001| dispatch (cmd, **kwargs)
001|
001| Commands:
001| c:new do_all_months_chart
001| c:mon do_chart_month
001| c:all do_chart_month_all
001| c:cmp do_chart_compare_months
001| c:hist do_histogram
001| bins do_temperature_bins
001| test do_test
001|
001| TODO: command and do-function names need refactoring!
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| import matplotlib.pyplot as plt
009| import matplotlib.ticker as mlticks
010| import matplotlib.dates as mldates
011| from logger import logger,info,debug,trace, LogFilenameTimestamp
012| from goodies import KWARG
013| from facts import MonthNames
014| from files import jsonfile
015| from mlchart import mlchart
016|
017| BasePath = r'C:\CJS\prj\Python\app\weather'
018| ImgsPath = path.join(BasePath, 'img')
019| DataPath = path.join(BasePath, 'dat')
020| CurrDate = datetime.now().date()
021| FileName = 'temperatures.json'
022| Log = logger('Temps')
023|
024| CMND = ''
025| ARGS = {
026|
027|
028|
029|
030|
031|
032|
033|
034|
035|
036| 'fpath': BasePath,
037|
038|
039| }
040|
041| FirstMonth = (13, 1)
042| LastMonth = (26, 10)
043|
044| YMajorGrid = 10
045| YMinorGrid = 2
046|
047| YLockLowTemp = -30
048| YLockHighTemp = +110
049| YLockMajorGrid = 10
050| YLockMinorGrid = 5
051|
052| TempBin = lambda t:(10*(t//10))
053|
054|
055|
056| class mlchart_month_temps (mlchart):
057| """ML Chart of Monthly Hi/Lo Temps."""
058|
059| def __init__ (self, data, **kwargs):
060| """New instance."""
061| super().__init__((8.8, 4.0), **kwargs)
062| self.data = data
063| self.x_limit = kwargs['dates']
064| self.y_limit = kwargs['minmax']
065| self.x_title = 'Date'
066| self.y_title = 'Hi/Lo Temp'
067| self.x_grids = (None, None)
068| self.y_grids = kwargs['ygrid']
069| self.freezing = kwargs['show32F'] if 'show32F' in kwargs else False
070| self.averages = kwargs['showAvg'] if 'showAvg' in kwargs else False
071| self.x_tickf = '%b %d'
072| self.y_tickf = '%+4d'
073| self.x_tickr = True
074| self.x_dates = False
075| self.title_kw['fontsize'] = 16
076| self.title_kw['fontweight'] = 'bold'
077| self.x_title_kw['fontsize'] = 12
078| self.y_title_kw['fontsize'] = 12
079| self.margins = dict(left=0.085, right=0.99, bottom=0.19, top=0.92)
080|
081| def plotter (self):
082| """Plot something!"""
083|
084| if self.freezing:
085| if self.y_limit[0] < 32 < self.y_limit[1]:
086| self.ax.axhline(32, color='#7f7f7f', lw=3.0, alpha=1.0, zorder=10)
087| else:
088| Log.info('Skipping freezing line.')
089|
090|
091| xs = self.data[0]
092| ys1 = self.data[1]
093| ys2 = self.data[2]
094|
095| self.ax.fill_between(xs,ys2,ys1, color='#7f7f7f', alpha=0.50, zorder=11)
096| self.ax.plot(xs,ys1, c='#0000ff', lw=3.0, alpha=0.66, zorder=12)
097| self.ax.plot(xs,ys2, c='#ff0000', lw=3.0, alpha=0.66, zorder=13)
098|
099| if self.averages:
100|
101| avg_hi = sum(ys1) / len(ys1)
102| avg_lo = sum(ys2) / len(ys2)
103|
104| self.ax.axhline(avg_hi, color='#0000ff', lw=1.2, ls='--', alpha=1.0, zorder=10)
105| self.ax.axhline(avg_lo, color='#ff0000', lw=1.2, ls='--', alpha=1.0, zorder=10)
106|
107| def make_x_axis_spcl (self):
108| self.ax.xaxis_date()
109|
110| self.ax.xaxis.set_major_locator(mldates.DayLocator())
111|
112| self.ax.xaxis.set_major_formatter(mldates.DateFormatter(self.x_tickf))
113|
114|
115| class mlchart_month_temps_all_years (mlchart):
116| """ML Chart of Monthly Hi/Lo Temps across years."""
117|
118| def __init__ (self, data, **kwargs):
119| """New instance."""
120| super().__init__((8.8, 4.0), **kwargs)
121| self.data = data
122| self.x_title = 'Day of the Month'
123| self.y_title = 'Hi/Lo Temp'
124| self.x_tickf = '%d'
125| self.y_tickf = '%+4d'
126| self.x_tickr = True
127| self.x_dates = False
128| self.title_kw['fontsize'] = 16
129| self.title_kw['fontweight'] = 'bold'
130| self.x_title_kw['fontsize'] = 12
131| self.y_title_kw['fontsize'] = 12
132| self.margins = dict(left=0.090, right=0.995, bottom=0.15, top=0.91)
133|
134| def plotter (self):
135| """Plot something!"""
136| for year,xs,ys1,ys2 in self.data:
137| if year == LastMonth[0]:
138| self.ax.plot(xs,ys1, c='#0000ff', lw=2.0, alpha=0.66, zorder=21)
139| self.ax.plot(xs,ys2, c='#ff0000', lw=2.0, alpha=0.66, zorder=22)
140| else:
141| self.ax.plot(xs,ys1, c='#7f7fff', lw=1.0, alpha=0.66, zorder=11)
142| self.ax.plot(xs,ys2, c='#ff7f7f', lw=1.0, alpha=0.66, zorder=12)
143|
144|
145|
146| class mlchart_histogram (mlchart):
147| """ML Chart of Temp Bins Historgram."""
148|
149| def __init__ (self, data=None, **kwargs):
150| """New instance."""
151| super().__init__((8.0, 4.0), **kwargs)
152| self.data = data
153| self.x_title = 'Degrees'
154| self.y_title = '# of Days'
155| self.x_grids = (10, None)
156| self.x_tickf = '%+d'
157| self.y_tickf = '%d'
158| self.x_tickr = True
159| self.x_dates = False
160| self.title_kw['fontsize'] = 18
161| self.title_kw['fontweight'] = 'bold'
162| self.x_title_kw['fontsize'] = 16
163| self.y_title_kw['fontsize'] = 16
164|
165| def plotter (self):
166| """Plot something!"""
167| if self.data is None:
168| return
169| xs1 = self.data[0]
170| ys1 = self.data[1]
171| xs2 = self.data[2]
172| ys2 = self.data[3]
173|
174| self.ax.bar(xs1,ys1, label="Highs", width=4.0, color='#ff0000', alpha=0.85, zorder=11)
175| self.ax.bar(xs2,ys2, label="Lows" , width=4.0, color='#0000ff', alpha=0.85, zorder=12)
176|
177|
178| def _make_x_axis_spcl (self):
179| """Rotate X-axis labels 90 degrees. (Same as using x_tickr=True)"""
180| for tick in self.ax.xaxis.get_major_ticks():
181| tick.label1.set_rotation('vertical')
182| tick.label1.set_size(9)
183|
184|
185|
186| class month_temperature_data:
187| '''Month Temp Data object (from JSON record).'''
188|
189| def __init__ (self, rcd):
190| '''New Month Temp Data instance. Takes a JSON record.'''
191| self.name = MonthNames[rcd['month']]
192| self.year = 2000 + rcd['year']
193| self.month = rcd['month']
194| self.xmin = date(self.year, self.month, rcd['xmin'])
195| self.xmax = date(self.year, self.month, rcd['xmax'])
196| self.ymin = rcd['ymin']
197| self.ymax = rcd['ymax']
198| self.xlims = (self.xmin, self.xmax)
199| self.ylims = (self.ymin, self.ymax)
200| self.filename = f'temps_{self.year}-{self.month:02d}.png'
201| self.title = f'Local Hi/Lo Temps in {self.name} {self.year}'
202| self.days = [Datum(self.year,self.month,d) for d in rcd['days']]
203|
204| def __str__ (self):
205| return self.title
206|
207|
208|
209| def getmin (ns):
210| smallest = min(ns)
211| bottom = (floor(smallest / 10) * 10)
212| return (bottom if bottom < smallest else bottom-10)
213|
214| def getmax (ns):
215| biggest = max(ns)
216| top = (ceil(biggest / 10) * 10)
217| return (top if biggest < top else top+10)
218|
219|
220| def Datum (year, month, rcd):
221| '''Generate a datum from year, month, and day-record.'''
222|
223| dt = date(year, month, rcd[0])
224| lo = rcd[1] if 1 < len(rcd) else None
225| hi = rcd[2] if 2 < len(rcd) else None
226|
227|
228| return (dt, lo, hi)
229|
230|
231| def load_json_data (fname=FileName, fpath=DataPath):
232| '''Load monthly temperature data from JSON file. Return list of month objects.'''
233|
234|
235| fn = path.join(fpath, fname) if fpath else fname
236| fo = jsonfile(fn)
237| fo.load()
238|
239| Log.debug(f'JSON-Version: {fo.data["version"]}')
240| Log.debug(f'DATA-Name: {fo.data["name"]}')
241| Log.debug(f'DATA-Updated: {fo.data["updated-date"]}')
242| Log.debug()
243|
244|
245| return fo.data['months']
246|
247|
248| def get_month_data (year, month, fname=FileName, fpath=DataPath, verbose=True):
249| '''Get a given month's temperature data from the JSON file.'''
250|
251|
252|
253| data = load_json_data(fname=fname, fpath=fpath)
254|
255|
256| for item in data:
257| if (item['year']==year) and (item['month']==month):
258|
259|
260| if verbose:
261| Log.trace()
262| for t in item['days']:
263| if 3 <= len(t):
264| Log.trace(f'{t[0]:2d}: lo={t[1]:+3d}, hi={t[2]:+3d}')
265| else:
266| Log.trace(f'{t[0]:2d}: NO DATA')
267| Log.trace()
268|
269|
270| return month_temperature_data(item)
271|
272|
273| return None
274|
275|
276|
277| def do_chart_compare_months (**kwargs):
278| """CMND: Generate a Temps chart for a given month in all years."""
279| fpath = KWARG('fpath', ImgsPath, str, kwargs)
280| dpath = KWARG('dpath', DataPath, str, kwargs)
281| dname = KWARG('dname', FileName, str, kwargs)
282| month = KWARG('month', CurrDate.month, int, kwargs)
283| ylock = KWARG('ylock', 0, int, kwargs)
284| Log.info('chart-month:: %s' % str(list(kwargs.keys())))
285| Log.debug(f'{fpath=}')
286| Log.debug(f'{dpath=}')
287| Log.debug(f'{dname=}')
288| Log.debug(f'month={MonthNames[month]}')
289| Log.info()
290| temp_data = load_json_data(fname=dname, fpath=dpath)
291|
292| month_data = {}
293| for item in temp_data:
294|
295| if item['month'] != month:
296| continue
297|
298|
299| year = item['year']
300| if year in month_data:
301| raise RuntimeError(f'Duplicate year! {year}')
302|
303|
304| month_data[year] = [Datum(year,month,d) for d in item['days'] if 1<len(d)]
305|
306| month_data_list = sorted(month_data.items(), key=lambda x:x[0])
307| chart_data = []
308| xmaxs = []
309| ymins = []
310| ymaxs = []
311| for year,days in month_data_list:
312|
313| xs = [t[0].day for t in days]
314| ys1 = [t[1] for t in days]
315| ys2 = [t[2] for t in days]
316| xmaxs.append(max(xs))
317| ymins.append(min(ys1+ys2))
318| ymaxs.append(max(ys1+ys2))
319|
320| chart_data.append((year, xs, ys1, ys2))
321|
322| xmax = max(xmaxs)
323| ymin = getmin(ymins)
324| ymax = getmax(ymaxs)
325|
326| first_year = 2000+month_data_list[0][0]
327| last_year = 2000+month_data_list[-1][0]
328| props = {
329| 'title':f'Temps for {MonthNames[month]} {first_year} to {last_year}',
330| 'xmin':1, 'xmax':xmax,
331| 'ymin':ymin, 'ymax':ymax,
332| 'xgrid1':7, 'xgrid2':1,
333| 'ygrid1':10, 'ygrid2':2,
334| 'fname':f'comps_{last_year:04d}-{month:02d}.png', 'fpath':fpath
335| }
336| cht = mlchart_month_temps_all_years(chart_data, **props)
337| cht.make()
338| cht.close()
339| Log.info(f'wrote: {path.join(cht.fpath,cht.fname)}')
340| Log.info()
341| Log.info()
342| return 'Done'
343|
344|
345| def do_histogram (**kwargs):
346| """CMND: Generate a Histogram chart."""
347| fpath = KWARG('fpath', ImgsPath, str, kwargs)
348| fname = KWARG('fname', 'histogram.png', str, kwargs)
349| dpath = KWARG('dpath', DataPath, str, kwargs)
350| dname = KWARG('dname', FileName, str, kwargs)
351| start = KWARG('start', f'{FirstMonth[1]}/{FirstMonth[0]}', str, kwargs)
352| stop = KWARG('stop' , f'{LastMonth[1]}/{LastMonth[0]}', str, kwargs)
353| title = KWARG('title', 'Temp Bins', str, kwargs)
354| xmin = KWARG('xmin' , -35, int, kwargs)
355| xmax = KWARG('xmax' , 105, int, kwargs)
356| ymin = KWARG('ymin' , 0, int, kwargs)
357| ymax = KWARG('ymax' , 100, int, kwargs)
358| ydiv1 = KWARG('ydiv1', 50, int, kwargs)
359| ydiv2 = KWARG('ydiv2', 10, int, kwargs)
360| Log.info('chart-histogram:: %s' % str(list(kwargs.keys())))
361| Log.debug(f'{fpath=}')
362| Log.debug(f'{fname=}')
363| Log.debug(f'{dpath=}')
364| Log.debug(f'{dname=}')
365| Log.debug(f'{start=}')
366| Log.debug(f'{stop=}')
367| Log.debug(f'{title=}')
368| Log.debug(f'xlims=({xmin}, {xmax})')
369| Log.debug(f'ylims=({ymin}, {ymax})')
370| Log.debug(f'{ydiv1=}')
371| Log.debug(f'{ydiv2=}')
372| Log.info()
373| tstart = [int(s) for s in start.split('/')]
374| tstop = [int(s) for s in stop.split('/')]
375| start_dt = date(tstart[1], tstart[0], 1)
376| stop_dt = date(tstop [1], tstop [0], 1)
377|
378| hi_bins = {}
379| lo_bins = {}
380|
381| for item in load_json_data(fname=dname, fpath=dpath):
382|
383| year = item['year']
384| month = item['month']
385|
386| if (year==0) or (month==0):
387| continue
388|
389|
390| mon_dt = date(year, month, 1)
391| if not (start_dt <= mon_dt <= stop_dt):
392| continue
393| Log.trace(item)
394|
395| for dt,lo,hi in [Datum(year,month,d) for d in item['days']]:
396| if lo is None:
397| continue
398|
399| b = TempBin(hi)
400| if b not in hi_bins: hi_bins[b] = 0
401| hi_bins[b] += 1
402|
403| b = TempBin(lo)
404| if b not in lo_bins: lo_bins[b] = 0
405| lo_bins[b] += 1
406| Log.trace()
407|
408| hi_data = [(b+1,hi_bins[b]) for b in sorted(hi_bins, reverse=True)]
409| lo_data = [(b-1,lo_bins[b]) for b in sorted(lo_bins, reverse=True)]
410|
411| xs1 = [x for x,_ in hi_data]
412| ys1 = [y for _,y in hi_data]
413|
414| xs2 = [x for x,_ in lo_data]
415| ys2 = [y for _,y in lo_data]
416|
417| data = (xs1,ys1, xs2,ys2)
418|
419| props = dict(
420| title=title,
421| xmin=xmin, xmax=xmax,
422| ymin=ymin, ymax=ymax,
423| fname=fname, fpath=fpath,
424| ygrid1=KWARG('ygrid1', ydiv1, int, kwargs),
425| ygrid2=KWARG('ygrid2', ydiv2, int, kwargs),
426| ml=KWARG('ml', 0.08, float, kwargs),
427| mr=KWARG('mr', 0.98, float, kwargs),
428| mb=KWARG('mb', 0.18, float, kwargs),
429| mt=KWARG('mt', 0.92, float, kwargs),
430| )
431| Log.trace(props)
432|
433| cht = mlchart_histogram(data, **props)
434| cht.make()
435| Log.info(f'wrote: {path.join(cht.fpath,cht.fname)}')
436| Log.info()
437| Log.info()
438| return 'Done'
439|
440|
441| def do_temperature_bins (**kwargs):
442| """CMND: Generate temperature bin report."""
443| fpath = KWARG('fpath', BasePath, str, kwargs)
444| fname = KWARG('fname', 'bins.out', str, kwargs)
445| dpath = KWARG('dpath', DataPath, str, kwargs)
446| dname = KWARG('dname', FileName, str, kwargs)
447| start = KWARG('start', f'{FirstMonth[1]}/{FirstMonth[0]}', str, kwargs)
448| stop = KWARG('stop' , f'{LastMonth[1]}/{LastMonth[0]}', str, kwargs)
449| Log.info('temp-bins:: %s' % str(list(kwargs.keys())))
450| Log.debug(f'{fpath=}')
451| Log.debug(f'{fname=}')
452| Log.debug(f'{dpath=}')
453| Log.debug(f'{dname=}')
454| Log.debug(f'{start=}')
455| Log.debug(f'{stop=}')
456| Log.info()
457| tstart = [int(s) for s in start.split('/')]
458| tstop = [int(s) for s in stop.split('/')]
459| start_dt = date(tstart[1], tstart[0], 1)
460| stop_dt = date(tstop [1], tstop [0], 1)
461|
462| hi_bins = {}
463| lo_bins = {}
464| max_hi, min_hi = (-200, +200)
465| max_lo, min_lo = (-200, +200)
466|
467| for item in load_json_data(fname=dname, fpath=dpath):
468| year = item['year']
469| month = item['month']
470|
471|
472| if (year==0) or (month==0):
473| continue
474|
475|
476| mon_dt = date(year, month, 1)
477| if not (start_dt <= mon_dt <= stop_dt):
478| continue
479| Log.trace(item)
480|
481| for dt,lo,hi in [Datum(year,month,d) for d in item['days']]:
482| if lo is None:
483| continue
484|
485| if max_hi < hi: max_hi = hi
486| if hi < min_hi: min_hi = hi
487| if max_lo < lo: max_lo = lo
488| if lo < min_lo: min_lo = lo
489|
490| b = TempBin(hi)
491| if b not in hi_bins: hi_bins[b] = 0
492| hi_bins[b] += 1
493|
494| b = TempBin(lo)
495| if b not in lo_bins: lo_bins[b] = 0
496| lo_bins[b] += 1
497| Log.trace()
498|
499| Log.info(f'Min/Max Hi: {min_hi:+d}/{max_hi:+d}')
500| Log.info(f'Min/Max Lo: {min_lo:+d}/{max_lo:+d}')
501| Log.info()
502|
503|
504| for b in sorted(hi_bins, reverse=True):
505| Log.info('%+4d: %2d' % (b, hi_bins[b]))
506| Log.info()
507|
508| for b in sorted(lo_bins, reverse=True):
509| Log.info('%+4d: %2d' % (b, lo_bins[b]))
510| Log.info()
511| Log.info()
512| return 'Done'
513|
514|
515| def do_chart_month (**kwargs):
516| """CMND: Generate a Hi/Lo Temps chart for a given month."""
517| fpath = KWARG('fpath', ImgsPath, str, kwargs)
518| dpath = KWARG('dpath', DataPath, str, kwargs)
519| dname = KWARG('dname', FileName, str, kwargs)
520| year = KWARG('year' , CurrDate.year-2000, int, kwargs)
521| month = KWARG('month', CurrDate.month, int, kwargs)
522| ylock = KWARG('ylock', 0, int, kwargs)
523| Log.info('chart-month:: %s' % str(list(kwargs.keys())))
524| Log.debug(f'{fpath=}')
525| Log.debug(f'{dpath=}')
526| Log.debug(f'{dname=}')
527| Log.debug(f'month={MonthNames[month]} {2000+year}')
528| Log.info()
529|
530| dat = get_month_data(year, month, fname=dname, fpath=dpath)
531| if dat is None:
532| raise RuntimeError(f'Unable to find month data for {month}-{year}')
533|
534| ylims = (YLockLowTemp, YLockHighTemp) if ylock else dat.ylims
535| ygrid = (YLockMajorGrid, YLockMinorGrid) if ylock else (YMajorGrid, YMinorGrid)
536| showf = False if ylock else True
537| showa = False if ylock else True
538| props = {
539| 'title':dat.title,
540| 'dates':dat.xlims, 'minmax':ylims, 'ygrid':ygrid,
541| 'show32F':showf, 'showAvg':showa,
542| 'fname':dat.filename, 'fpath':fpath
543| }
544| xs = [t[0] for t in dat.days if t[1] is not None]
545| ys1 = [t[1] for t in dat.days if t[1] is not None]
546| ys2 = [t[2] for t in dat.days if t[2] is not None]
547|
548| cht = mlchart_month_temps((xs,ys1,ys2), **props)
549| cht.make()
550| cht.close()
551| Log.info('wrote: %s' % path.join(cht.fpath, cht.fname))
552| Log.info()
553| Log.info()
554| return 'Done'
555|
556| def do_chart_month_all (**kwargs):
557| """CMND: Generate all Hi/Lo Temps charts for months with data."""
558| Log.info('chart-month-all:: %s' % str(list(kwargs.keys())))
559| Log.info()
560|
561| dt = date(FirstMonth[0]+2000, FirstMonth[1], 1)
562| end = date(LastMonth[0]+2000, LastMonth[1] , 2)
563| Log.info(f'Start: {dt.ctime()}')
564| Log.info(f'Stop: {end.ctime()}')
565| Log.info()
566|
567| while dt < end:
568| Log.info(f'Month: {dt.ctime()}')
569|
570|
571| kwargs['year'] = dt.year-2000
572| kwargs['month'] = dt.month
573| do_chart_month(**kwargs)
574|
575|
576| if dt.month < 12:
577| dt = date(dt.year, dt.month+1, 1)
578| else:
579|
580| dt = date(dt.year+1, 1, 1)
581|
582| Log.info()
583| return 'Done'
584|
585|
586| def do_all_months_chart (**kwargs):
587| """CMND: Generate a hi/lo chart for all months in JSON file."""
588| fpath = KWARG('fpath', BasePath, str, kwargs)
589| fname = KWARG('fname', 'Temperatures 2013-2026.png', str, kwargs)
590| dpath = KWARG('dpath', DataPath, str, kwargs)
591| dname = KWARG('dname', FileName, str, kwargs)
592| Log.info('all-months-chart:: %s' % str(list(kwargs.keys())))
593| Log.debug(f'{fpath=}')
594| Log.debug(f'{fname=}')
595| Log.debug(f'{dpath=}')
596| Log.debug(f'{dname=}')
597| Log.info()
598| jdata = load_json_data(fname=dname, fpath=dpath)
599| sort_key = lambda j:(j['year'], j['month'])
600|
601| data = {}
602| for item in sorted(jdata, key=sort_key):
603|
604| year = item['year']
605| month = item['month']
606| if (year==0) or (month==0):
607| continue
608|
609| year_key = 2000 + year
610| if year_key not in data:
611| data[year_key] = ([], [])
612|
613|
614| day_data = list(filter(lambda t:len(t)==3, item['days']))
615| lows = [t[1] for t in day_data]
616| highs = [t[2] for t in day_data]
617|
618| data[year_key][0].extend(lows)
619| data[year_key][1].extend(highs)
620|
621| ns = list(sorted(data))
622| ms = [None for yk in ns]
623| xs1 = [data[yk][1] for yk in ns]
624| xs2 = [data[yk][0] for yk in ns]
625| ps1 = [1.2+n for n in range(len(ns))]
626| ps2 = [0.0+n for n in range(len(ns))]
627|
628| fig, axes = plt.subplots(nrows=2, ncols=1, squeeze=False)
629| fig.suptitle('Temperature Ranges 2013-2026', fontsize=14, fontweight='bold')
630| fig.set_figwidth(12.0)
631| fig.set_figheight(6.0)
632| fig.subplots_adjust(left=0.055, right=0.990, bottom=0.090, top=0.93)
633|
634| ax1 = axes[0][0]
635|
636| ax1.set_xlim(0.50, len(ns)+0.50)
637| ax1.xaxis.set_major_locator(mlticks.MultipleLocator(1))
638| ax1.xaxis.set_minor_locator(mlticks.NullLocator())
639| ax1.xaxis.set_major_formatter(mlticks.FormatStrFormatter('%s'))
640| ax1.xaxis.set_minor_formatter(mlticks.NullFormatter())
641|
642| ax1.set_ylabel('High Temps', fontsize=11, fontweight='bold')
643| ax1.set_ylim(-20, +110)
644| ax1.yaxis.set_major_locator(mlticks.MultipleLocator(10))
645| ax1.yaxis.set_minor_locator(mlticks.MultipleLocator(5))
646| ax1.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
647| ax1.yaxis.set_minor_formatter(mlticks.NullFormatter())
648|
649| ax1.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
650| ax1.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
651| ax1.tick_params(which='major', axis='both', direction='out', color='#000000')
652| ax1.tick_params(which='minor', axis='both', direction='out', color='#000000')
653|
654| ax1.boxplot(
655| xs1, tick_labels=ns,
656| label="Highs",
657| whis=(0,100), widths=0.333,
658| patch_artist=True,
659| showmeans=True, meanline=True,
660| boxprops=dict(facecolor='#ef7f5f'),
661| medianprops=dict(color='#000000'),
662| meanprops=dict(color='#9f9f9f'),
663| whiskerprops=dict(linewidth=2),
664| zorder=12
665| )
666|
667| ax2 = axes[1][0]
668|
669| ax2.set_xlabel('Year', fontsize=11, fontweight='bold')
670| ax2.set_xlim(0.50, len(ns)+0.50)
671| ax2.xaxis.set_major_locator(mlticks.MultipleLocator(1))
672| ax2.xaxis.set_minor_locator(mlticks.NullLocator())
673| ax2.xaxis.set_major_formatter(mlticks.FormatStrFormatter('%s'))
674| ax2.xaxis.set_minor_formatter(mlticks.NullFormatter())
675|
676| ax2.set_ylabel('Low Temps', fontsize=11, fontweight='bold')
677| ax2.set_ylim(-30, +90)
678| ax2.yaxis.set_major_locator(mlticks.MultipleLocator(10))
679| ax2.yaxis.set_minor_locator(mlticks.MultipleLocator(5))
680| ax2.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
681| ax2.yaxis.set_minor_formatter(mlticks.NullFormatter())
682|
683| ax2.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
684| ax2.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
685| ax2.tick_params(which='major', axis='both', direction='out', color='#000000')
686| ax2.tick_params(which='minor', axis='both', direction='out', color='#000000')
687|
688| ax2.boxplot(
689| xs2, tick_labels=ns,
690| label="Lows",
691| whis=(0,100), widths=0.333,
692| patch_artist=True,
693| showmeans=True, meanline=True,
694| boxprops=dict(facecolor='#3fef7f'),
695| medianprops=dict(color='#000000'),
696| meanprops=dict(color='#9f9f9f'),
697| whiskerprops=dict(linewidth=2),
698| zorder=13
699| )
700|
701| fn = path.join(fpath,fname) if fpath else fname
702| fig.savefig(fn)
703| Log.info('wrote: %s' % fn)
704| Log.info()
705|
706| return 'Done'
707|
708|
709| def do_test (**kwargs):
710| """CMND: Do a test."""
711| fpath = KWARG('fpath', BasePath, str, kwargs)
712| fname = KWARG('fname', 'temps.out', str, kwargs)
713| dpath = KWARG('dpath', DataPath, str, kwargs)
714| dname = KWARG('dname', FileName, str, kwargs)
715| Log.info('test:: %s' % str(list(kwargs.keys())))
716| Log.debug(f'{fpath=}')
717| Log.debug(f'{fname=}')
718| Log.debug(f'{dpath=}')
719| Log.debug(f'{dname=}')
720| Log.info()
721| jdata = load_json_data(fname=dname, fpath=dpath)
722|
723| month_data_all_years = {m:[1000, -1000] for m in range(1,13)}
724| for item in jdata:
725|
726| year = item['year']
727| month = item['month']
728| if (year==0) or (month==0):
729| continue
730| dt = date(2000+year, month, 1)
731|
732| day_data = list(filter(lambda t:len(t)==3, item['days']))
733| lows = [t[1] for t in day_data]
734| highs = [t[2] for t in day_data]
735| lo = min(lows)
736| hi = max(highs)
737|
738| if lo < month_data_all_years[month][0]: month_data_all_years[month][0] = lo
739| if month_data_all_years[month][1] < hi: month_data_all_years[month][1] = hi
740|
741| for month,stat in sorted(month_data_all_years.items(), key=lambda x:x[0]):
742| lo = stat[0]
743| hi = stat[1]
744| Log.info(f'{month:02d}: {lo:+3d} {hi:+4d} ({hi-lo:2d})')
745| Log.info()
746|
747| return 'Done'
748|
749| def dispatch (cmd, **kwargs):
750| """Dispatch to a module function based on CMD."""
751| Log.info('CMD: %s' % cmd)
752| for kw in kwargs:
753| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
754| Log.info()
755| if cmd == 'c:new': return do_all_months_chart(**kwargs)
756| if cmd == 'bins': return do_temperature_bins(**kwargs)
757| if cmd == 'c:hist': return do_histogram(**kwargs)
758| if cmd == 'c:cmp': return do_chart_compare_months(**kwargs)
759| if cmd == 'c:mon': return do_chart_month(**kwargs)
760| if cmd == 'c:all': return do_chart_month_all(**kwargs)
761| if cmd == 'test': return do_test(**kwargs)
762| return 'Nothing to do!'
763|
764| if __name__ == '__main__':
765| print('autorun: %s' % argv[0])
766| Log.start(path.join(BasePath,'temperatures.log'))
767| Log.level(trace())
768| Log.info(argv[0])
769| Log.info()
770| cmd = argv[1] if 1 < len(argv) else CMND
771| kwargs = ARGS
772| for a in argv[2:]:
773| nv = a.split('=', 1)
774| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
775| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
776| try:
777| print('CMD: %s' % cmd)
778| print()
779| obj = dispatch(cmd, **kwargs)
780| print()
781| print(obj)
782| Log.info()
783| Log.info(obj)
784| except:
785| etype, evalue, tb = exc_info()
786| ts = extract_tb(tb)
787| Log.error()
788| Log.error('%s: %s' % (etype.__name__,str(evalue)))
789| Log.error()
790| for t in ts[-5:]:
791| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
792| Log.error(' %s' % t[3])
793| Log.error()
794| raise
795| finally:
796| Log.end()
797|
798| '''eof'''
799|