dnr_json_data.html


001| ####################################################################################################
002| from os import path
003| from datetime import date, datetime
004| import matplotlib.pyplot as plt
005| import matplotlib.ticker as mlticks
006| import matplotlib.dates as mldates
007| from matplotlib.patches import Patch
008| from goodies import KWARG, typename, makefilename, str2int,str2float
009| from files import jsonfile
010| from facts import MonthNames
011| from temperatures import load_json_data
012| ####################################################################################################
013| BasePath = r'C:\CJS\prj\Python\app\weather'
014| ImgsPath = path.join(BasePath, 'img')
015| DataPath = path.join(BasePath, 'dat')
016| CurrDate = datetime.now().date()
017| FileName = 'temperatures.json'
018| 
019| tempbin = lambda t:(10*(t//10))
020| 
021| ##================================================================================================##
022| def print_json_data ():
023|     '''List the JSON data to console.'''
024| 
025|     dat = load_json_data()
026|     print(f'records-found: {len(dat)}')
027|     print()
028| 
029|     # Go over all months...
030|     temp_min = +500
031|     temp_max = -500
032| 
033|     for rcd in dat:
034|         if rcd["month"] == 0:
035|             continue
036|         mon = rcd["month"]
037|         year = rcd["year"]
038|         tmin = rcd["ymin"]
039|         tmax = rcd["ymax"]
040|         dif = tmax - tmin
041| 
042|         # Go over all the days in the month...
043|         t_min = +500
044|         t_max = -500
045|         for day in rcd['days']:
046|             if len(day) == 1:
047|                 continue
048| 
049|             if day[1] < t_min: t_min = day[1]
050|             if t_max < day[2]: t_max = day[2]
051|         t_dif = t_max - t_min
052| 
053|         if t_min < temp_min: temp_min = t_min
054|         if temp_max < t_max: temp_max = t_max
055| 
056|         print(f'Month: {mon:02d}-{year+2000} lo:{t_min:+4d} hi:{t_max:+4d} ({t_dif:2d}) [lo:{tmin:+4d} hi:{tmax:+4d} ({dif:2d})]')
057|     print()
058| 
059|     print(f'# Months: {len(dat)} ({len(dat)/12:.1f} years)')
060|     print(f'Max Temp: {temp_max:+4d}')
061|     print(f'Min Temp: {temp_min:+4d}')
062|     print(f'Temp Dif: {temp_max-temp_min:4d}')
063|     print()
064| 
065| ##================================================================================================##
066| def days_below_freezing_and_zero ():
067|     '''Report on days-below-freezing and days-below-zero in winter.'''
068| 
069|     dat = load_json_data()
070|     print(f'records-found: {len(dat)}')
071|     print()
072| 
073|     color_32 = '#0000ff'
074|     color_20 = '#00cc7f'
075|     color_10 = '#bf7f00'
076|     color_00 = '#ff0000'
077| 
078|     days_below_32 = {}
079|     days_below_20 = {}
080|     days_below_10 = {}
081|     days_below_00 = {}
082| 
083|     for rcd in dat:
084|         if rcd["month"] == 0:
085|             continue
086|         mon = rcd["month"]
087|         year = rcd["year"]
088|         tmin = rcd["ymin"]
089|         tmax = rcd["ymax"]
090|         dif = tmax - tmin
091|         key = (year,mon)
092| 
093|         if key not in days_below_32: days_below_32[key] = 0
094|         if key not in days_below_20: days_below_20[key] = 0
095|         if key not in days_below_10: days_below_10[key] = 0
096|         if key not in days_below_00: days_below_00[key] = 0
097| 
098|         # Go over all the days in the month...
099|         for day in rcd['days']:
100|             if len(day) == 1:
101|                 continue
102| 
103|             # Test the max temp for the day...
104|             if day[2] < 32: days_below_32[key] += 1
105|             if day[2] < 20: days_below_20[key] += 1
106|             if day[2] < 10: days_below_10[key] += 1
107|             if day[2] <  0: days_below_00[key] += 1
108| 
109|     xs, xlabels = [], []
110|     ys32, ys20, ys10, ys00 = [], [], [], []
111| 
112|     tmp_32 = 0
113|     tmp_10 = 0
114|     tmp_20 = 0
115|     tmp_00 = 0
116|     tmp_year = 0
117| 
118|     def print_totals ():
119|         print('-----------------------------')
120|         print(f'{tmp_year}/{tmp_year+1}: {tmp_32:2d} days <32 {tmp_20:2d} days <20 {tmp_10:2d} days <10 {tmp_00:2d} days <0')
121|         print()
122|         xs.append(tmp_year)
123|         xlabels.append(f'{tmp_year}/{tmp_year+1}')
124|         ys32.append(tmp_32)
125|         ys20.append(tmp_20)
126|         ys10.append(tmp_10)
127|         ys00.append(tmp_00)
128| 
129|     for key in sorted(days_below_32):
130|         year,mon = key
131|         if mon in [4,5,6,7,8,9]:
132|             continue
133|         db_32 = days_below_32[key]
134|         db_20 = days_below_20[key]
135|         db_10 = days_below_10[key]
136|         db_00 = days_below_00[key]
137|         tmp_32 += db_32
138|         tmp_20 += db_20
139|         tmp_10 += db_10
140|         tmp_00 += db_00
141|         if tmp_year == 0:
142|             tmp_year = year
143| 
144|         print(f'{year}-{mon:2d}: {db_32:2d} days <32 {db_20:2d} days <20 {db_10:2d} days <10 {db_00:2d} days <0')
145| 
146|         if mon == 3:
147|             print_totals()
148|             tmp_32 = 0
149|             tmp_20 = 0
150|             tmp_10 = 0
151|             tmp_00 = 0
152|             tmp_year = 0
153| 
154|     if tmp_year:
155|         print_totals()
156| 
157|     filename = makefilename(BasePath, f'dbf-and-dbz.png')
158| 
159|     fig, ax = plt.subplots()
160|     fig.suptitle('Days Below Freezing, Ten & Zero', fontsize=14, fontweight='bold')
161|     fig.set_figwidth(8.8)
162|     fig.set_figheight(3.5)
163|     fig.subplots_adjust(left=0.072, right=0.996, bottom=0.14, top=0.90)
164| 
165|     ax.set_xlabel('Winter of', fontsize=11, fontweight='bold')
166|     ax.set_xlim(xs[0]-0.5, xs[-1]+0.5)
167|     ax.xaxis.set_major_locator(mlticks.FixedLocator(xs))
168|     ax.xaxis.set_minor_locator(mlticks.NullLocator())
169|     ax.xaxis.set_major_formatter(mlticks.FixedFormatter(xlabels))
170|     ax.xaxis.set_minor_formatter(mlticks.NullFormatter())
171| 
172|     #for tick in ax.xaxis.get_major_ticks():
173|     # tick.label1.set_rotation('vertical')
174|     # tick.label1.set_size(9)
175| 
176|     ax.set_ylabel('Number of Days', fontsize=11, fontweight='bold')
177|     ax.set_ylim(0, 100)
178|     ax.yaxis.set_major_locator(mlticks.MultipleLocator(10))
179|     ax.yaxis.set_minor_locator(mlticks.MultipleLocator(5))
180|     ax.yaxis.set_major_formatter(mlticks.FormatStrFormatter('%d'))
181|     ax.yaxis.set_minor_formatter(mlticks.NullFormatter())
182| 
183|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
184|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
185|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
186|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
187| 
188|     ax.bar(xs,ys32, color=color_32, width=0.7, alpha=1.00, zorder=11)
189|     ax.bar(xs,ys20, color=color_20, width=0.7, alpha=1.00, zorder=12)
190|     ax.bar(xs,ys10, color=color_10, width=0.7, alpha=1.00, zorder=12)
191|     ax.bar(xs,ys00, color=color_00, width=0.7, alpha=1.00, zorder=13)
192| 
193|     # Define legend...
194|     patchs = [
195|         Patch(facecolor=color_32, edgecolor='#000000', lw=0.75),
196|         Patch(facecolor=color_20, edgecolor='#000000', lw=0.75),
197|         Patch(facecolor=color_10, edgecolor='#000000', lw=0.75),
198|         Patch(facecolor=color_00, edgecolor='#000000', lw=0.75),
199|     ]
200|     labels = ['Days below +32', 'Days below +20', 'Days below +10', 'Days below 0']
201|     fig.legend(
202|         patchs, labels,
203|         ncols=1, fontsize=10,
204|         loc='upper right',
205|         bbox_to_anchor=(1.00,1.00),
206|         shadow=True
207|     )
208| 
209|     fig.savefig(filename)
210|     print('wrote: %s' % filename)
211|     print()
212|     print()
213| 
214| ##================================================================================================##
215| def main ():
216|     #print_json_data()
217|     days_below_freezing_and_zero()
218| ####################################################################################################
219| if __name__ == '__main__':
220|     print()
221|     main()
222|     print()
223| ####################################################################################################
224| '''eof'''
225|