-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1471 lines (1257 loc) · 59.7 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
import json
import re
import time
from datetime import datetime, timedelta
import pytz
from azure.storage.blob import BlobServiceClient
import logging
def writeblob(blob_name, blob_input, container_name, func_account_url, default_credential):
'''Write blob to Azure Storage
Args:
blob_name (str) : name of blob to write
blob_input (str) : input to write
container_name (str) : name of container to write
account_url (str) : URL for Azure Storage account
default_credential (obj) : default credential for Azure Storage account
Returns:
None
'''
try:
# Create a blob service client
blob_service_client = BlobServiceClient(account_url=func_account_url, credential=default_credential)
# Create blob client using local file name as blob name
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
# Upload the created file
blob_client.upload_blob(blob_input, overwrite=True)
except Exception as e:
logging.info(f'\n\nERROR: {e}\n\n')
return None
def readblob(blob_name, container_name, func_account_url, default_credential):
'''Read blob from Azure Storage
Args:
blob_name (str) : name of blob to read
container_name (str) : name of container to read
account_url (str) : URL for Azure Storage account
default_credential (obj) : default credential for Azure Storage account
Returns:
None
'''
try:
# Create a blob service client
blob_service_client = BlobServiceClient(account_url=func_account_url, credential=default_credential)
# Create blob client with blob name
blob_client = blob_service_client.get_blob_client(container=container_name, blob=blob_name)
# Download the blob
blob = blob_client.download_blob()
blob_output = blob.readall()
except Exception as e:
logging.info(f'\n\nERROR: {e}\n\n')
return blob_output
def assign_time_groups(current_time, dt):
'''Assign time group to a datetime object.
Args:
ref_dt (datetime): Datetime object from reference.
dt (datetime): Datetime object from forecast.
Returns:
time_group (str): Time group.
'''
# Convert current_time and dt to Pacific Time
pacific = pytz.timezone('US/Pacific')
current_time = current_time.astimezone(pacific)
ref_dt = datetime.strptime(f'{current_time.date()}T06:00:00-08:00', '%Y-%m-%dT%H:%M:%S%z')
delta = dt - ref_dt
if dt.day == ref_dt.day and dt.hour >= 6:
time_group = 'day0'
elif (delta).days == 0 and delta != 0 and dt.hour < 6:
time_group = 'day0'
elif (delta).days == 1:
time_group = 'day1'
elif (delta).days == 2:
time_group = 'day2'
elif (delta).days == 3:
time_group = 'day3'
elif (delta).days == 4:
time_group = 'day4'
elif (delta).days == 5:
time_group = 'day5'
elif (delta).days == 6:
time_group = 'day6'
elif dt.day == ref_dt.day and dt.hour < 6:
time_group = None
else:
time_group = None
return time_group
def get_avg_value(values):
"""Get average value from a list of values.
Args:
values (list): List of values.
Returns:
avg (float): Average value.
"""
avg = sum(values) / len(values)
return avg
def get_max_tuple(times, values):
"""Get max tuple from a list of times and values.
Args:
times (list): List of times.
values (list): List of values.
Returns:
max_tup (tuple): Max tuple, (time, value).
"""
max_tup = (times[values.index(max(values))], max(values))
return max_tup
def get_min_tuple(times, values):
"""Get min tuple from a list of times and values.
Args:
times (list): List of times.
values (list): List of values.
Returns:
min_tup (tuple): Min tuple, (time, value).
"""
min_tup = (times[values.index(min(values))], min(values))
return min_tup
def get_sum(values):
"""Get sum of values from a list of values.
Args:
values (list): List of values.
Returns:
amount (float): Sum of values.
"""
amount = sum(values)
return amount
def convert_units(value, property, units):
"""Convert units of a value.
Args:
value (float): Value to convert.
property (str): Property of value.
units (str): Units of value.
Returns:
tuple (str, float): units_new, converted value.
"""
if property == 'temperature':
if units == 'degC':
value = (value * 9/5) + 32
units_new = 'degF'
elif units == 'degF':
value = (value - 32) * 5/9
units_new = 'degC'
if property == 'windDirection':
if units == 'degree_(angle)':
units_new = 'cardinal'
if value >= 348.75 or value < 11.25:
value = 'N'
elif value >= 11.25 and value < 33.75:
value = 'NNE'
elif value >= 33.75 and value < 56.25:
value = 'NE'
elif value >= 56.25 and value < 78.75:
value = 'ENE'
elif value >= 78.75 and value < 101.25:
value = 'E'
elif value >= 101.25 and value < 123.75:
value = 'ESE'
elif value >= 123.75 and value < 146.25:
value = 'SE'
elif value >= 146.25 and value < 168.75:
value = 'SSE'
elif value >= 168.75 and value < 191.25:
value = 'S'
elif value >= 191.25 and value < 213.75:
value = 'SSW'
elif value >= 213.75 and value < 236.25:
value = 'SW'
elif value >= 236.25 and value < 258.75:
value = 'WSW'
elif value >= 258.75 and value < 281.25:
value = 'W'
elif value >= 281.25 and value < 303.75:
value = 'WNW'
elif value >= 303.75 and value < 326.25:
value = 'NW'
elif value >= 326.25 and value < 348.75:
value = 'NNW'
elif units == 'cardinal':
units_new = 'degree_(angle)'
if value == 'N':
value = 0
elif value == 'NNE':
value = 22.5
elif value == 'NE':
value = 45
elif value == 'ENE':
value = 67.5
elif value == 'E':
value = 90
elif value == 'ESE':
value = 112.5
elif value == 'SE':
value = 135
elif value == 'SSE':
value = 157.5
elif value == 'S':
value = 180
elif value == 'SSW':
value = 202.5
elif value == 'SW':
value = 225
elif value == 'WSW':
value = 247.5
elif value == 'W':
value = 270
elif value == 'WNW':
value = 292.5
elif value == 'NW':
value = 315
elif value == 'NNW':
value = 337.5
if property == 'skyCover':
if units == 'percent':
units_new = 'condition'
if value >= 88:
value = 'Overcast'
elif value >= 70 and value < 88:
value = 'Considerable Cloudiness'
elif value >= 51 and value < 70:
value = 'Mostly Cloudy'
elif value >= 26 and value < 51:
value = 'Partly Cloudy'
elif value >= 6 and value < 26:
value = 'Mostly Clear'
elif value < 6:
value = 'Clear'
elif units == 'condition':
units_new = 'percent'
if value == 'Overcast':
value = 100
elif value == 'Considerable Cloudiness':
value = 87
elif value == 'Mostly Cloudy':
value = 69
elif value == 'Partly Cloudy':
value = 49
elif value == 'Mostly Clear':
value = 25
elif value == 'Clear':
value = 5
if property == 'windSpeed':
if units == 'km_h-1':
value = value * 0.621371
units_new = 'mph'
elif units == 'mph':
value = value * 1.60934
units_new = 'km_h-1'
if property == 'windGust':
if units == 'km_h-1':
value = value * 0.621371
units_new = 'mph'
elif units == 'mph':
value = value * 1.60934
units_new = 'km_h-1'
if property == 'probabilityOfPrecipitation':
if units == 'percent':
units_new = 'probability'
if value <= 10:
value = 'unlikely'
elif value > 10 and value < 30:
value = 'slight chance'
elif value >= 30 and value <= 50:
value = 'chance'
elif value > 50 and value <= 70:
value = 'likely'
elif value > 70:
value = 'very likely'
elif units == 'probability':
units_new = 'percent'
if value == 'unlikely':
value = 10
elif value == 'slight chance':
value = 29
elif value == 'chance':
value = 50
elif value == 'likely':
value = 70
elif value == 'very likely':
value = 99
if property == 'quantitativePrecipitation':
if units == 'mm':
value = value * 0.0393701
units_new = 'in'
elif units == 'in':
value = value * 25.4
units_new = 'mm'
if property == 'snowfallAmount':
if units == 'mm':
value = value * 0.0393701
units_new = 'in'
elif units == 'in':
value = value * 25.4
units_new = 'mm'
if property == 'snowLevel':
if units == 'm':
value = value * 3.28084
units_new = 'ft'
elif units == 'ft':
value = value * 0.3048
units_new = 'm'
return (units_new, value)
def check_status(property, data, elev):
"""Check assign status based on property parameters.
Args:
property (str): Property.
data (dict): Dictionary of processed data,
e.g., {'max': (time, value), 'min': (time, value), 'avg': value, 'sum': value}
or {'data': ([times], [values])}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if property == 'temperature':
status = check_temperature(data)
elif property == 'skyCover':
status = check_sky_cover(data)
elif property == 'windDirection':
status = check_wind_direction(data)
elif property == 'windSpeed':
status = check_wind_speed(data)
elif property == 'windGust':
status = check_wind_gust(data)
elif property == 'weather':
status = check_weather(data)
elif property == 'probabilityOfPrecipitation':
status = check_probability_of_precipitation(data)
elif property == 'quantitativePrecipitation':
status = check_quantitative_precipitation(data)
elif property == 'snowfallAmount':
status = check_snowfall_amount(data)
elif property == 'snowLevel':
status = check_snow_level(data, elev)
return status
def check_temperature(dict):
"""Check temperature values, assign status
Args:
dict (dict): Dictionary of processed temperature values,
e.g., {'max': (time, value), 'min': (time, value), 'avg': value}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['max'][1] >= 35 or dict['min'][1] < 10:
status = 1
elif (dict['max'][1] > 33 and dict['max'][1] < 35 and dict['min'][1] >= 10) or (dict['min'][1] < 15 and dict['min'][1] >= 10 and dict['max'][1] < 35):
status = 2
elif dict['max'][1] <= 33 and dict['min'][1] >= 15:
status = 3
return status
def check_sky_cover(dict):
"""Check sky cover values, assign status
Args:
dict : Dictionary of processed quantitative precipitation values,
e.g., {'avg': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
status = 3
if type(dict['avg']) == float:
if dict['avg'] >= 88:
status = 3
elif dict['avg'] < 88:
status = 3
if type(dict['avg']) == str:
if dict['avg'] == 'Overcast':
status = 3
elif dict['avg'] != 'Overcast':
status = 3
return status
def check_wind_direction(dict):
"""Check wind direction values, assign status
Args:
dict : Dictionary of processed quantitative precipitation values,
e.g., {'avg': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['avg'] == 'NNW' or dict['avg'] == 'NW' or dict['avg'] == 'avg' or dict['avg'] == 'N' or dict['avg'] == 'NNE' or dict['avg'] == 'NE':
status = 3
elif dict['avg'] == 'ENE' or dict['avg'] == 'E' or dict['avg'] == 'ESE' or dict['avg'] == 'SE' or dict['avg'] == 'SSE' or dict['avg'] == 'S' or dict['avg'] == 'SSW' or dict['avg'] == 'SW' or dict['avg'] == 'WSW' or dict['avg'] == 'W' or dict['avg'] == 'WNW':
status = 3
else:
print(dict['avg'])
return status
def check_wind_speed(dict):
"""Check wind speed values, assign status
Args:
dict : Dictionary of processed quantitative precipitation values,
e.g., {'avg': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['avg'] >= 35:
status = 1
elif dict['avg'] < 35 and dict['avg'] >= 20:
status = 2
elif dict['avg'] < 20:
status = 3
return status
def check_wind_gust(dict):
"""Check wind gust values, assign status
Args:
dict (dict): Dictionary of processed wind gust values,
e.g., {'max': (time, value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['max'][1] >= 45:
status = 1
elif dict['max'][1] < 45 and dict['max'][1] >= 35:
status = 2
elif dict['max'][1] < 35:
status = 3
return status
def check_weather(dict):
"""Check weather values, assign status
Args:
dict (dict): Dictionary of processed weather values,
e.g., {'name': (str), 'data': [(times, [values])]}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
rain = False
snow = False
for i in range(len(dict['data'])):
for j in range(len(dict['data'][i][1])):
if 'rain' in dict['data'][i][1][j]:
rain = True
if 'snow' in dict['data'][i][1][j]:
snow = True
if rain == False and snow == True:
status = 3
elif rain == False and snow == False:
status = 3
elif rain == True and snow == True:
status = 2
elif rain == True and snow == False:
status = 1
return status
def check_probability_of_precipitation(dict):
"""Check probability of precipitation values, assign status
Args:
dict : Dictionary of processed quantitative precipitation values,
e.g., {'avg': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['avg'] >= 50:
status = 3
elif dict['avg'] >= 50 and dict['avg'] < 70:
status = 3
elif dict['avg'] <50:
status = 3
return status
def check_quantitative_precipitation(dict):
"""Check quantitative precipitation values, assign status
Args:
dict (dict): Dictionary of processed quantitative precipitation values,
e.g., {'sum': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['sum'] >= 0.5:
status = 3
elif dict['sum'] < 0.5 and dict['sum'] >= 0.1:
status = 3
elif dict['sum'] < 0.1:
status = 3
return status
def check_snowfall_amount(dict):
"""Check snowfall amount values, assign status
Args:
dict (dict): Dictionary of processed snowfall amount values,
e.g., {'sum': (value)}
Returns:
status (int): status, e.g., 1, 2, 3.
"""
if dict['sum'] >= 3:
status = 3
elif dict['sum'] < 3 and dict['sum'] >= 1.1:
status = 3
elif dict['sum'] < 1.1:
status = 2
return status
def check_snow_level(dict, elev):
"""Check snow level values, assign status
Args:
dict (dict): Dictionary of processed snow level values,
e.g., {'min': (time, value), 'max': (time, value)}
location (str): Location name
Returns:
status (int): status, e.g., 1, 2, 3.
"""
base = elev[0]
summit = elev[1]
if dict['max'][1] < base:
status = 3
elif dict['max'][1] < summit and dict['max'][1] >= base:
status = 2
elif dict['max'][1] > summit:
status = 1
return status
class APIEndpoints:
'''NOAA API endpoints for ski area locations'''
def __init__(self, locations, metadata_url, header, forecast_type, container_name, blob_name):
'''Initialize APIEndpoints object
Get API endpoints for each location in locations, write endpoints to file
Args:
locations (dict) : {location name: [(lat, long), (base elev., summit elev.), (ski area url,)]}
metadata_url (str) : API url for location metadata
header (dict) : header for requests
forecast_type (str) : 'forecast', 'forecastHourly', or 'forecastGridData'
container_name (str) : container for blob
blob_name (str) : blob_name to write
Returns:
endpoints (dict) : {location_name: {forecast_type: endpoint}}
'''
self._locations = locations
self._metadata_url = metadata_url
self._header = header
self._forecast_type = forecast_type
self._container_name = container_name
self._blob_name = blob_name
self._endpoints = {}
self._status = None
#try:
for location in self._locations.keys():
response = None # Clear variables from previous iteration
response_text = None
endpoint = {}
# Get location metadata
lat_long_str = f'{str(self._locations[location][0][0])},{str(self._locations[location][0][1])}'
url = self._metadata_url+lat_long_str
try:
response = requests.get(url, headers = self._header)
response.raise_for_status()
response_text = response.json()
# Extract location forecastGridData endpoint, append to locations_endpoints dictionary
endpoint = response_text['properties'][self._forecast_type]
self._endpoints[location] = endpoint
# Limit calls to 4 per second
time.sleep(0.25)
except Exception as e:
logging.info(f'\n\nError in APIEndpoints.__init__: \n{location}\n{e}\n\n')
def get_endpoints(self):
'''Return endpoints'''
return self._endpoints
class GridData:
'''Forecast data for ski area locations'''
def __init__(self, location, location_details, endpoint, header):
'''Initialize GridData object
Get forecastGridData for each location in locations, write data to file
Args:
location (str) : location name
locations (dict) : {location name: [(lat, long), (base elev., summit elev.), (ski area url,)]}
endpoints (dict) : {location: endpoint}
header (dict) : header for requests
container_name (str) : container for blob
blob_name (str) : blob_name to write
Returns:
None
'''
self._location = location
self._location_details = location_details
self._endpoint = endpoint
self._header = header
#self._data = None
self._blob = None
self._response_status = None
self._request_error = False
def get_forecast(self):
'''Write forecast data to file'''
data = {}
response = None
response_status = None
response_text = None
try:
# Get forecastGridData
url = self._endpoint
response = requests.get(url, headers = self._header)
self._response_status = response.status_code
response.raise_for_status()
response_text = response.json()
# Extract forecast data, append to locations_data dictionary
data = {'lat_long' : self._location_details[0],
'elev': self._location_details[1],
'href': self._location_details[2],
'data' : response_text}
#self._data = data
self._blob = json.dumps(data, sort_keys=False, indent=4)
# Limit calls to 1 every 1 seconds
time.sleep(1)
except Exception as e:
logging.info(f'\n\nError in GridData.__init__: \n{self._location}\n{e}\n\n')
self._request_error = True
return self._blob
def get_status(self):
'''Return status'''
return (self._response_status, self._request_error)
class Table:
'''Table object
Args:
None
Returns:
None
'''
def __init__(self):
'''Initialize Table object
Args:
None
Returns:
None
'''
self._columns = [['Location', 'Lat., Long.']]
self._rows = []
self._table = {'columns': self._columns, 'rows': self._rows}
return None
def get_columns(self):
'''Return columns'''
return self._columns
def get_rows(self):
'''Return rows'''
return self._rows
def get_table(self):
'''Return table'''
return self._table
def create_columns(self, time):
'''Create columns for table
Args:
time (datetime) : current time
Returns:
columns (list) : [column1, column2, ...]
'''
for i in range(0,7):
date = time.date() + timedelta(days=i)
if i == 0:
day = 'Today'
if i == 1:
day = 'Tomorrow'
elif i > 1:
day = date.strftime('%A')
date = date.strftime('%Y-%m-%d')
self._columns.append([day, date])
return None
def append_row(self, row):
'''Add row to table
Args:
row (list) : [cell1, cell2, ...]
Returns:
None
'''
self._rows.append(row)
return None
class TableData:
'''Table data for ski area locations'''
def __init__(self, time, location, time_periods, properties):
'''Initialize TableData object
Args:
time (datetime) : current time
location (str) : location name
time_periods (dict) : {day: [time_period1, time_period2, ...]}
properties (dict) : {property: {'units': units, 'calculations': [calculation1, calculation2, ...]}}
container_name (str) : container storing data
forecast_blob (str) : forecast_blob to read
Returns:
None
'''
self._time = time
self._location = location
self._time_periods = time_periods
self._properties = properties
self._forecast = {}
self._table_data = {}
def parse_forecast(self, blob_data):
'''Parse forecast data
Parses forecastGridData for a location
Args:
None
Returns:
forecast (dict) : {'lat_long': [lat, long],
'elev': [base elev., summit elev.],
'href': [ski area url],
'predictions': {property: {'units': units, 'data': {day: [(date, value)]}}}}
'''
predictions = {} # Initialize predictions dictionary for this location
forecast = {'lat_long': blob_data['lat_long'],
'elev': blob_data['elev'],
'href': blob_data['href'],
'predictions': predictions} # Initialize forecast dictionary for this location
self._elev = blob_data['elev']
for property in self._properties.keys():
try:
data = blob_data['data']['properties'][property]
property_data = {property: {'units': None, 'data': None}} # Initialize property dictionary
daily_data = {'day0': None, 'day1': None, 'day2': None, 'day3': None, 'day4': None, 'day5': None, 'day6': None} # Initialize daily data dictionary for this property
except KeyError:
continue
if property != 'weather':
units = str.replace(data['uom'], 'wmoUnit:', '')
property_data[property]['units'] = units
times_values = data['values']
elif property == 'weather':
units = 'text'
property_data[property]['units'] = units
times_values = []
for i in range(len(data['values'])):
time = data['values'][i]['validTime']
value = []
for j in range(len(data['values'][i]['value'])):
coverage = data['values'][i]['value'][j]['coverage']
weather = data['values'][i]['value'][j]['weather']
intensity = data['values'][i]['value'][j]['intensity']
value.append([weather, intensity, coverage])
time_value = {'validTime' : time, 'value' : value}
times_values.append(time_value)
# Group data by day
current_time_group = None
values = [] # list of time:value pairs assigned to a time group
for _ in times_values:
valid_time = _['validTime']
valid_time = re.sub(r"/[a-zA-Z0-9]+", '', valid_time)
dt = datetime.strptime(valid_time, '%Y-%m-%dT%H:%M:%S%z')
dt = dt.astimezone(pytz.timezone('US/Pacific'))
dt_str = dt.strftime('%Y-%m-%dT%H:%M:%S')
value = _['value']
time_group = assign_time_groups(self._time, dt) # Assign time group
if time_group == None: continue
if time_group == None and current_time_group == None: continue
if time_group != None and current_time_group == None: current_time_group = time_group
if time_group == current_time_group:
tup = (dt_str, value)
values.append(tup)
if time_group != current_time_group: # If time group changes, add values to dates_values
daily_data[current_time_group] = values
current_time_group = time_group
values = [] # Clear values list
tup = (dt_str, value)
values.append(tup) # Insert first value in new list
if current_time_group == 'day6':
daily_data[current_time_group] = values
# Add daily data to property data and predictions
property_data[property]['data'] = daily_data
predictions[property] = property_data[property]
# Add property data to forecast
forecast['predictions'] = predictions
self._forecast = forecast
return self._forecast
def calculate_table_data(self, parsed_forecast):
'''Process forecast data to calculate table row data
Args:
parsed_forecast (dict) : {'lat_long': [lat, long],
'elev': [base elev., summit elev.],
'href': [ski area url],
'predictions': {property: {'units': units, 'data': {day: [(date, value)]}}}}
Returns:
table_data (dict) : {'lat_long': [lat, long],
'elev': [base elev., summit elev.],
'href': [ski area url],
'predictions': {property: {'units': units, 'data': {day: [(date, value)]}}}}'''
self._forecast = parsed_forecast
results = {'day0': {}, 'day1': {}, 'day2': {}, 'day3': {}, 'day4': {}, 'day5': {}, 'day6': {}}
date_strings = {'day0': None, 'day1': None, 'day2': None, 'day3': None, 'day4': None, 'day5': None, 'day6': None}
for day in self._time_periods.keys():
daily_results = {}
for time_period in self._time_periods[day]:
time_period_results = {}
time_period_status = {}
overall_status = 3
try:
for property in self._forecast['predictions'].keys():
max = None
min = None
avg = None
sum = None
conv = None
date = None
current_units = self._forecast['predictions'][property]['units']
new_units = self._properties[property]['units']
# Get datetime object for this day, extract date and day of week
try:
dt_0 = datetime.strptime(self._forecast['predictions'][property]['data'][day][0][0], '%Y-%m-%dT%H:%M:%S')
date = dt_0.date()
day_of_week = date.strftime('%A')
date_str = date.strftime('%Y-%m-%d')
if date_strings.get(day) == None:
date_strings[day] = date_str
except TypeError:
if time_period == '24h':
dt_0 = datetime.strptime(date_strings[day]+'T06:00:00', '%Y-%m-%dT%H:%M:%S')
date = dt_0.date()
day_of_week = date.strftime('%A')
date_str = date_strings[day]
if property == 'weather':
self._forecast['predictions'][property]['data'][day] = [(dt_0.strftime('%Y-%m-%dT%H:%M:%S'), [[None, None, None]])]
if property == 'snowLevel':
self._forecast['predictions'][property]['data'][day] = [(dt_0.strftime('%Y-%m-%dT%H:%M:%S'), None)]
if time_period == 'am':
dt_0 = datetime.strptime(date_strings[day]+'T06:00:00', '%Y-%m-%dT%H:%M:%S')
date = dt_0.date()
day_of_week = date.strftime('%A')
date_str = date_strings[day]
if time_period == 'pm':
dt_0 = datetime.strptime(date_strings[day]+'T12:00:00', '%Y-%m-%dT%H:%M:%S')
date = dt_0.date()
day_of_week = date.strftime('%A')
date_str = date_strings[day]
if time_period == 'overnight':
dt_0 = datetime.strptime(date_strings[day]+'T18:00:00', '%Y-%m-%dT%H:%M:%S')
date = dt_0.date()
day_of_week = date.strftime('%A')
date_str = date_strings[day]
pass
# Collect property values for this day
try:
times_values = self._forecast['predictions'][property]['data'][day]
if times_values == None:
if property == 'weather':
self._forecast['predictions'][property]['data'][day] = [(dt_0.strftime('%Y-%m-%dT%H:%M:%S'), [[None, None, None]])]
if property == 'snowLevel':
self._forecast['predictions'][property]['data'][day] = [(dt_0.strftime('%Y-%m-%dT%H:%M:%S'), None)]
continue
except:
logging.info(f'\n\nEXCEPT: {property}: {times_values}\n\n')
pass
# Initialize lists for 24h, am, pm, and overnight values
times = []
values = []
_24h_times = []
_24h_values = []
am_times = []
am_values = []
pm_times = []
pm_values = []
overnight_times = []
overnight_values = []
# Sort values for 24h, am, pm, and overnight values
for _ in range(len(times_values)):
_24h_times.append(times_values[_][0])
_24h_values.append(times_values[_][1])
dt = datetime.strptime(times_values[_][0], '%Y-%m-%dT%H:%M:%S')
if dt.day == dt_0.day and dt.hour < 12:
am_times.append(times_values[_][0])
am_values.append(times_values[_][1])
elif dt.day == dt_0.day and 12 <= dt.hour < 18:
pm_times.append(times_values[_][0])
pm_values.append(times_values[_][1])
elif dt.day == dt_0.day and 18 <= dt.hour:
overnight_times.append(times_values[_][0])