Repository navigation
Expand file tree
/
Copy pathdata_processor.py
More file actions
1568 lines (1302 loc) · 65.2 KB
/
Copy pathdata_processor.py
File metadata and controls
1568 lines (1302 loc) · 65.2 KB
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 pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any, Tuple
import json
import math
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
class AdvancedDataProcessor:
"""Advanced weather data processor with AI-powered analytics and machine learning insights"""
def __init__(self):
# Enhanced units and conversions
self.temperature_units = {
'metric': {'symbol': '°C', 'name': 'Celsius'},
'imperial': {'symbol': '°F', 'name': 'Fahrenheit'},
'kelvin': {'symbol': 'K', 'name': 'Kelvin'}
}
self.speed_units = {
'metric': {'symbol': 'm/s', 'name': 'Meters per second'},
'imperial': {'symbol': 'mph', 'name': 'Miles per hour'},
'kelvin': {'symbol': 'm/s', 'name': 'Meters per second'}
}
# Advanced weather pattern recognition
self.weather_patterns = {
'heat_wave': {
'temp_threshold': 35,
'duration': 3,
'severity_levels': {
'moderate': {'temp': 35, 'duration': 3},
'severe': {'temp': 40, 'duration': 2},
'extreme': {'temp': 45, 'duration': 1}
}
},
'cold_snap': {
'temp_threshold': -5,
'duration': 2,
'severity_levels': {
'moderate': {'temp': -5, 'duration': 2},
'severe': {'temp': -15, 'duration': 1},
'extreme': {'temp': -25, 'duration': 1}
}
},
'drought': {
'humidity_threshold': 30,
'duration': 7,
'precipitation_threshold': 0.1
},
'storm_system': {
'wind_threshold': 15,
'pressure_drop': 10,
'precipitation_threshold': 5
}
}
# AI model configurations
self.comfort_model_weights = {
'temperature': 0.4,
'humidity': 0.25,
'wind': 0.2,
'pressure': 0.1,
'uv_index': 0.05
}
# Seasonal adjustments
self.seasonal_factors = {
'spring': {'temp_comfort_range': (15, 25), 'humidity_optimal': 50},
'summer': {'temp_comfort_range': (20, 28), 'humidity_optimal': 45},
'autumn': {'temp_comfort_range': (12, 22), 'humidity_optimal': 55},
'winter': {'temp_comfort_range': (18, 24), 'humidity_optimal': 40}
}
def process_forecast_data_advanced(self, forecast_data: Dict, units: str = 'metric') -> List[Dict]:
"""Advanced forecast processing with machine learning insights"""
if not forecast_data or 'list' not in forecast_data:
return []
daily_data = {}
hourly_patterns = []
# Group by day and analyze patterns
for item in forecast_data['list']:
dt = datetime.fromtimestamp(item['dt'])
date_key = dt.strftime('%Y-%m-%d')
if date_key not in daily_data:
daily_data[date_key] = {
'date': dt,
'day': dt.strftime('%A'),
'temps': [],
'humidity': [],
'wind_speed': [],
'wind_direction': [],
'pressure': [],
'weather_conditions': [],
'icons': [],
'descriptions': [],
'precipitation': [],
'clouds': [],
'uv_index': [],
'visibility': []
}
# Collect hourly data for pattern analysis
hourly_patterns.append({
'datetime': dt,
'temp': item['main']['temp'],
'humidity': item['main']['humidity'],
'wind_speed': item['wind']['speed'],
'pressure': item['main']['pressure'],
'condition': item['weather'][0]['main']
})
# Aggregate daily data
daily_data[date_key]['temps'].append(item['main']['temp'])
daily_data[date_key]['humidity'].append(item['main']['humidity'])
daily_data[date_key]['wind_speed'].append(item['wind']['speed'])
daily_data[date_key]['wind_direction'].append(item['wind'].get('deg', 0))
daily_data[date_key]['pressure'].append(item['main']['pressure'])
daily_data[date_key]['weather_conditions'].append(item['weather'][0]['main'])
daily_data[date_key]['icons'].append(item['weather'][0]['icon'])
daily_data[date_key]['descriptions'].append(item['weather'][0]['description'])
daily_data[date_key]['precipitation'].append(item.get('pop', 0) * 100)
daily_data[date_key]['clouds'].append(item['clouds']['all'])
daily_data[date_key]['visibility'].append(item.get('visibility', 10000))
# Calculate UV index based on conditions
uv_estimate = self._estimate_uv_index(
item['weather'][0]['main'],
item['clouds']['all'],
dt.hour
)
daily_data[date_key]['uv_index'].append(uv_estimate)
# Process daily summaries with advanced analytics
processed_forecast = []
for date_key, data in daily_data.items():
# Advanced statistical analysis
temp_stats = self._calculate_temperature_statistics(data['temps'])
humidity_stats = self._calculate_statistical_measures(data['humidity'])
wind_stats = self._calculate_wind_statistics(data['wind_speed'], data['wind_direction'])
pressure_stats = self._calculate_pressure_analysis(data['pressure'])
# Weather condition analysis
condition_analysis = self._analyze_weather_conditions(data['weather_conditions'])
# Comfort and health indices
comfort_analysis = self._calculate_advanced_comfort_index(data)
health_index = self._calculate_health_weather_index(data)
# Pattern recognition
weather_patterns = self._detect_weather_patterns_daily(data)
# Activity recommendations
activity_score = self._calculate_activity_suitability(data)
processed_day = {
# Basic information
'date': data['date'],
'day': data['day'][:3],
'day_full': data['day'],
# Temperature analysis
'temp_max': temp_stats['max'],
'temp_min': temp_stats['min'],
'temp_avg': temp_stats['mean'],
'temp_median': temp_stats['median'],
'temp_range': temp_stats['range'],
'temp_variance': temp_stats['variance'],
'temp_trend': temp_stats['trend'],
# Humidity analysis
'humidity': humidity_stats['mean'],
'humidity_range': humidity_stats['range'],
'humidity_stability': humidity_stats['stability'],
# Wind analysis
'wind_speed': wind_stats['avg_speed'],
'wind_max': wind_stats['max_speed'],
'wind_consistency': wind_stats['consistency'],
'wind_direction_avg': wind_stats['avg_direction'],
'wind_direction_stability': wind_stats['direction_stability'],
# Atmospheric pressure
'pressure_avg': pressure_stats['mean'],
'pressure_trend': pressure_stats['trend'],
'pressure_stability': pressure_stats['stability'],
# Weather conditions
'condition': condition_analysis['primary_condition'],
'icon': condition_analysis['primary_icon'],
'description': condition_analysis['primary_description'],
'condition_confidence': condition_analysis['confidence'],
'condition_diversity': condition_analysis['diversity'],
# Precipitation and clouds
'precipitation_chance': max(data['precipitation']),
'precipitation_avg': sum(data['precipitation']) / len(data['precipitation']),
'cloud_coverage': sum(data['clouds']) / len(data['clouds']),
'cloud_variance': np.var(data['clouds']),
# UV and visibility
'uv_index_max': max(data['uv_index']),
'uv_index_avg': sum(data['uv_index']) / len(data['uv_index']),
'visibility_avg': sum(data['visibility']) / len(data['visibility']),
# Advanced indices
'comfort_score': comfort_analysis['score'],
'comfort_level': comfort_analysis['level'],
'comfort_factors': comfort_analysis['factors'],
'health_index': health_index['score'],
'health_concerns': health_index['concerns'],
'activity_score': activity_score,
'activity_recommendations': activity_score['recommendations'],
# Pattern analysis
'weather_patterns': weather_patterns,
'stability_index': self._calculate_day_stability(data),
'extremes_risk': self._assess_extreme_weather_risk(data),
# Derived insights
'best_time_periods': self._find_optimal_time_periods(hourly_patterns, data['date']),
'weather_quality_score': self._calculate_overall_weather_quality(data)
}
processed_forecast.append(processed_day)
return sorted(processed_forecast, key=lambda x: x['date'])[:7] # Extended to 7 days
def _calculate_temperature_statistics(self, temps: List[float]) -> Dict[str, float]:
"""Calculate comprehensive temperature statistics"""
if not temps:
return {'max': 0, 'min': 0, 'mean': 0, 'median': 0, 'range': 0, 'variance': 0, 'trend': 'stable'}
temps_array = np.array(temps)
# Basic statistics
stats_dict = {
'max': float(np.max(temps_array)),
'min': float(np.min(temps_array)),
'mean': float(np.mean(temps_array)),
'median': float(np.median(temps_array)),
'range': float(np.ptp(temps_array)),
'variance': float(np.var(temps_array)),
'std': float(np.std(temps_array))
}
# Trend analysis
if len(temps) > 2:
x = np.arange(len(temps))
slope, _, r_value, _, _ = stats.linregress(x, temps)
if abs(r_value) > 0.5: # Significant correlation
if slope > 0.5:
stats_dict['trend'] = 'increasing'
elif slope < -0.5:
stats_dict['trend'] = 'decreasing'
else:
stats_dict['trend'] = 'stable'
else:
stats_dict['trend'] = 'variable'
else:
stats_dict['trend'] = 'stable'
return stats_dict
def _calculate_statistical_measures(self, data: List[float]) -> Dict[str, float]:
"""Calculate advanced statistical measures for any dataset"""
if not data:
return {'mean': 0, 'range': 0, 'stability': 0}
data_array = np.array(data)
# Calculate coefficient of variation as stability measure
mean_val = np.mean(data_array)
std_val = np.std(data_array)
cv = (std_val / mean_val) if mean_val != 0 else 0
stability = max(0, 1 - cv) # Higher stability = lower coefficient of variation
return {
'mean': float(mean_val),
'median': float(np.median(data_array)),
'range': float(np.ptp(data_array)),
'std': float(std_val),
'stability': float(stability),
'cv': float(cv)
}
def _calculate_wind_statistics(self, speeds: List[float], directions: List[float]) -> Dict[str, float]:
"""Advanced wind analysis with directional statistics"""
if not speeds or not directions:
return {
'avg_speed': 0, 'max_speed': 0, 'consistency': 0,
'avg_direction': 0, 'direction_stability': 0
}
# Speed statistics
speed_stats = self._calculate_statistical_measures(speeds)
# Directional statistics (circular statistics)
directions_rad = np.radians(directions)
# Calculate mean direction using circular statistics
sin_sum = np.sum(np.sin(directions_rad))
cos_sum = np.sum(np.cos(directions_rad))
mean_direction = np.degrees(np.arctan2(sin_sum, cos_sum))
if mean_direction < 0:
mean_direction += 360
# Calculate directional consistency (R-value)
n = len(directions)
R = np.sqrt(sin_sum**2 + cos_sum**2) / n
direction_stability = R # R = 1 means all directions same, R = 0 means random
return {
'avg_speed': speed_stats['mean'],
'max_speed': float(np.max(speeds)),
'consistency': speed_stats['stability'],
'avg_direction': float(mean_direction),
'direction_stability': float(direction_stability),
'speed_variance': speed_stats['std']
}
def _calculate_pressure_analysis(self, pressures: List[float]) -> Dict[str, Any]:
"""Advanced atmospheric pressure analysis"""
if not pressures:
return {'mean': 1013, 'trend': 'stable', 'stability': 1}
pressure_stats = self._calculate_statistical_measures(pressures)
# Trend analysis
if len(pressures) > 2:
x = np.arange(len(pressures))
slope, _, r_value, _, _ = stats.linregress(x, pressures)
if abs(r_value) > 0.4: # Significant correlation for pressure
if slope > 1:
trend = 'rising'
elif slope < -1:
trend = 'falling'
else:
trend = 'stable'
else:
trend = 'variable'
else:
trend = 'stable'
# Pressure change rate (important for weather prediction)
pressure_change_rate = 0
if len(pressures) > 1:
pressure_change_rate = (pressures[-1] - pressures[0]) / len(pressures)
return {
'mean': pressure_stats['mean'],
'trend': trend,
'stability': pressure_stats['stability'],
'change_rate': float(pressure_change_rate),
'range': pressure_stats['range']
}
def _analyze_weather_conditions(self, conditions: List[str]) -> Dict[str, Any]:
"""Analyze weather condition patterns and confidence"""
if not conditions:
return {
'primary_condition': 'Unknown',
'primary_icon': '01d',
'primary_description': 'Unknown',
'confidence': 0,
'diversity': 0
}
# Count occurrences
condition_counts = {}
for condition in conditions:
condition_counts[condition] = condition_counts.get(condition, 0) + 1
# Find primary condition
primary_condition = max(condition_counts, key=condition_counts.get)
confidence = condition_counts[primary_condition] / len(conditions)
diversity = len(condition_counts) / len(conditions)
# Map to icon and description (simplified mapping)
condition_mapping = {
'Clear': {'icon': '01d', 'description': 'clear sky'},
'Clouds': {'icon': '02d', 'description': 'few clouds'},
'Rain': {'icon': '10d', 'description': 'light rain'},
'Thunderstorm': {'icon': '11d', 'description': 'thunderstorm'},
'Snow': {'icon': '13d', 'description': 'snow'},
'Mist': {'icon': '50d', 'description': 'mist'}
}
mapping = condition_mapping.get(primary_condition, {'icon': '01d', 'description': 'unknown'})
return {
'primary_condition': primary_condition,
'primary_icon': mapping['icon'],
'primary_description': mapping['description'],
'confidence': float(confidence),
'diversity': float(diversity),
'all_conditions': condition_counts
}
def _calculate_advanced_comfort_index(self, day_data: Dict) -> Dict[str, Any]:
"""Calculate advanced comfort index with multiple factors"""
if not day_data['temps']:
return {'score': 50, 'level': 'Unknown', 'factors': {}}
# Get average values
avg_temp = sum(day_data['temps']) / len(day_data['temps'])
avg_humidity = sum(day_data['humidity']) / len(day_data['humidity'])
avg_wind = sum(day_data['wind_speed']) / len(day_data['wind_speed'])
avg_pressure = sum(day_data['pressure']) / len(day_data['pressure'])
# Calculate individual comfort factors
temp_comfort = self._calculate_temperature_comfort(avg_temp)
humidity_comfort = self._calculate_humidity_comfort(avg_humidity)
wind_comfort = self._calculate_wind_comfort(avg_wind)
pressure_comfort = self._calculate_pressure_comfort(avg_pressure)
# Weather condition penalty
condition_penalty = self._calculate_condition_comfort_penalty(day_data['weather_conditions'])
# Weighted comfort score
weights = self.comfort_model_weights
comfort_score = (
temp_comfort * weights['temperature'] +
humidity_comfort * weights['humidity'] +
wind_comfort * weights['wind'] +
pressure_comfort * weights['pressure']
) * 100
# Apply condition penalty
comfort_score = max(0, comfort_score - condition_penalty)
# Determine comfort level
comfort_level = self._determine_comfort_level(comfort_score)
return {
'score': float(comfort_score),
'level': comfort_level,
'factors': {
'temperature': float(temp_comfort * 100),
'humidity': float(humidity_comfort * 100),
'wind': float(wind_comfort * 100),
'pressure': float(pressure_comfort * 100),
'condition_penalty': float(condition_penalty)
}
}
def _calculate_temperature_comfort(self, temp: float) -> float:
"""Calculate temperature comfort factor (0-1)"""
# Optimal temperature range: 18-24°C
if 18 <= temp <= 24:
return 1.0
elif 15 <= temp <= 27:
# Gradual decrease in comfort
if temp < 18:
return 1.0 - (18 - temp) / 10
else:
return 1.0 - (temp - 24) / 10
else:
# Significant discomfort
if temp < 15:
return max(0, 1.0 - (15 - temp) / 15)
else:
return max(0, 1.0 - (temp - 27) / 20)
def _calculate_humidity_comfort(self, humidity: float) -> float:
"""Calculate humidity comfort factor (0-1)"""
# Optimal humidity: 40-60%
if 40 <= humidity <= 60:
return 1.0
elif 30 <= humidity <= 70:
if humidity < 40:
return 1.0 - (40 - humidity) / 20
else:
return 1.0 - (humidity - 60) / 20
else:
if humidity < 30:
return max(0, 1.0 - (30 - humidity) / 30)
else:
return max(0, 1.0 - (humidity - 70) / 30)
def _calculate_wind_comfort(self, wind_speed: float) -> float:
"""Calculate wind comfort factor (0-1)"""
# Optimal wind: 1-5 m/s (light breeze)
if 1 <= wind_speed <= 5:
return 1.0
elif wind_speed < 1:
return 0.8 # Still air is slightly uncomfortable
elif wind_speed <= 10:
return 1.0 - (wind_speed - 5) / 10
else:
return max(0, 1.0 - (wind_speed - 10) / 15)
def _calculate_pressure_comfort(self, pressure: float) -> float:
"""Calculate pressure comfort factor (0-1)"""
# Normal pressure: 1010-1020 hPa
if 1010 <= pressure <= 1020:
return 1.0
else:
deviation = min(abs(pressure - 1015), 50) # Cap at 50 hPa deviation
return max(0, 1.0 - deviation / 50)
def _calculate_condition_comfort_penalty(self, conditions: List[str]) -> float:
"""Calculate penalty based on weather conditions"""
condition_penalties = {
'Thunderstorm': 30,
'Snow': 20,
'Rain': 15,
'Drizzle': 10,
'Mist': 5,
'Fog': 8,
'Clear': 0,
'Clouds': 2
}
if not conditions:
return 0
# Calculate average penalty
total_penalty = sum(condition_penalties.get(condition, 5) for condition in conditions)
return total_penalty / len(conditions)
def _determine_comfort_level(self, score: float) -> str:
"""Determine comfort level based on score"""
if score >= 90:
return "Excellent"
elif score >= 80:
return "Very Good"
elif score >= 70:
return "Good"
elif score >= 60:
return "Fair"
elif score >= 50:
return "Poor"
elif score >= 40:
return "Very Poor"
else:
return "Extremely Poor"
def _calculate_health_weather_index(self, day_data: Dict) -> Dict[str, Any]:
"""Calculate health-related weather index"""
if not day_data['temps']:
return {'score': 50, 'concerns': []}
health_score = 100
concerns = []
# Temperature health factors
avg_temp = sum(day_data['temps']) / len(day_data['temps'])
temp_range = max(day_data['temps']) - min(day_data['temps'])
if avg_temp > 35:
health_score -= 30
concerns.append("Heat exhaustion risk")
elif avg_temp < -10:
health_score -= 25
concerns.append("Hypothermia risk")
if temp_range > 15:
health_score -= 10
concerns.append("Large temperature variations")
# Humidity health factors
avg_humidity = sum(day_data['humidity']) / len(day_data['humidity'])
if avg_humidity > 80:
health_score -= 15
concerns.append("High humidity discomfort")
elif avg_humidity < 20:
health_score -= 10
concerns.append("Very dry air - respiratory irritation possible")
# Wind health factors
max_wind = max(day_data['wind_speed'])
if max_wind > 20:
health_score -= 20
concerns.append("Strong winds - outdoor activity risk")
# Pressure health factors
pressure_range = max(day_data['pressure']) - min(day_data['pressure'])
if pressure_range > 20:
health_score -= 10
concerns.append("Pressure changes may affect sensitive individuals")
# Weather condition health factors
for condition in day_data['weather_conditions']:
if condition == 'Thunderstorm':
health_score -= 15
concerns.append("Storm conditions - stay indoors")
elif condition in ['Snow', 'Rain']:
health_score -= 5
concerns.append("Wet conditions - slip/fall risk")
return {
'score': max(0, health_score),
'concerns': list(set(concerns)) # Remove duplicates
}
def _calculate_activity_suitability(self, day_data: Dict) -> Dict[str, Any]:
"""Calculate suitability for various activities"""
if not day_data['temps']:
return {'overall': 50, 'recommendations': []}
avg_temp = sum(day_data['temps']) / len(day_data['temps'])
avg_humidity = sum(day_data['humidity']) / len(day_data['humidity'])
avg_wind = sum(day_data['wind_speed']) / len(day_data['wind_speed'])
max_precip = max(day_data['precipitation'])
# Activity scores
outdoor_sports = 100
indoor_activities = 50
water_activities = 100
# Temperature adjustments
if not (15 <= avg_temp <= 28):
outdoor_sports -= 20
water_activities -= 15
# Precipitation adjustments
if max_precip > 50:
outdoor_sports -= 40
water_activities -= 30
indoor_activities += 20
elif max_precip > 20:
outdoor_sports -= 20
water_activities -= 10
# Wind adjustments
if avg_wind > 15:
outdoor_sports -= 25
water_activities -= 35
elif avg_wind > 8:
outdoor_sports -= 10
water_activities -= 15
# Humidity adjustments
if avg_humidity > 80:
outdoor_sports -= 15
elif avg_humidity < 30:
outdoor_sports -= 10
overall_score = (outdoor_sports + water_activities) / 2
# Generate recommendations
recommendations = []
if overall_score > 80:
recommendations.append("Excellent day for all outdoor activities")
elif overall_score > 60:
recommendations.append("Good conditions for most outdoor activities")
else:
recommendations.append("Consider indoor activities")
return {
'overall': max(0, min(100, overall_score)),
'outdoor_sports': max(0, min(100, outdoor_sports)),
'water_activities': max(0, min(100, water_activities)),
'indoor_activities': max(0, min(100, indoor_activities)),
'recommendations': recommendations
}
def _detect_weather_patterns_daily(self, day_data: Dict) -> List[str]:
"""Detect significant weather patterns for a single day."""
patterns = []
# Ensure data exists to avoid errors
if not all(k in day_data for k in ['temps', 'humidity', 'precipitation', 'wind_speed', 'pressure']) or not day_data['temps']:
return patterns
# Check for heat wave conditions
heat_wave_config = self.weather_patterns['heat_wave']
if max(day_data['temps']) > heat_wave_config['temp_threshold']:
patterns.append('heat_wave')
# Check for cold snap conditions
cold_snap_config = self.weather_patterns['cold_snap']
if min(day_data['temps']) < cold_snap_config['temp_threshold']:
patterns.append('cold_snap')
# Check for drought conditions
drought_config = self.weather_patterns['drought']
avg_humidity = np.mean(day_data['humidity'])
max_precip = max(day_data['precipitation'])
if (avg_humidity < drought_config['humidity_threshold'] and
(max_precip / 100) < drought_config['precipitation_threshold']): # Convert precip % back to probability
patterns.append('drought')
# Check for storm system conditions
storm_config = self.weather_patterns['storm_system']
max_wind = max(day_data['wind_speed'])
# Check for significant pressure drop within the day
pressure_diff = day_data['pressure'][-1] - day_data['pressure'][0]
if (max_wind > storm_config['wind_threshold'] and
pressure_diff < -storm_config['pressure_drop'] and # Negative diff means pressure is falling
(max_precip / 100) > storm_config['precipitation_threshold']):
patterns.append('storm_system')
return list(set(patterns)) # Return unique patterns
def calculate_weather_trends_advanced(self, forecast_data: List[Dict]) -> Dict[str, Any]:
"""Advanced weather trends analysis with machine learning insights"""
if not forecast_data:
return {}
# Extract time series data
temps_max = [item['temp_max'] for item in forecast_data]
temps_min = [item['temp_min'] for item in forecast_data]
temps_avg = [item['temp_avg'] for item in forecast_data]
humidity = [item['humidity'] for item in forecast_data]
wind_speed = [item['wind_speed'] for item in forecast_data]
pressure = [item['pressure_avg'] for item in forecast_data]
comfort_scores = [item['comfort_score'] for item in forecast_data]
# Advanced trend analysis
trends = {
'temperature': {
'max_trend': self._calculate_advanced_trend(temps_max),
'min_trend': self._calculate_advanced_trend(temps_min),
'avg_trend': self._calculate_advanced_trend(temps_avg),
'volatility': self._calculate_volatility(temps_max),
'heat_wave_risk': self._detect_pattern_risk('heat_wave', forecast_data),
'cold_snap_risk': self._detect_pattern_risk('cold_snap', forecast_data),
'temperature_momentum': self._calculate_momentum(temps_avg),
'diurnal_range_trend': self._calculate_advanced_trend([max_t - min_t for max_t, min_t in zip(temps_max, temps_min)])
},
'humidity': {
'trend': self._calculate_advanced_trend(humidity),
'avg': sum(humidity) / len(humidity),
'stability': self._calculate_stability_index(humidity),
'drought_risk': self._detect_pattern_risk('drought', forecast_data),
'comfort_correlation': self._calculate_correlation(humidity, comfort_scores)
},
'wind': {
'trend': self._calculate_advanced_trend(wind_speed),
'avg': sum(wind_speed) / len(wind_speed),
'max': max(wind_speed),
'variability': np.std(wind_speed),
'storm_risk': self._detect_pattern_risk('storm_system', forecast_data),
'consistency_trend': self._calculate_wind_consistency_trend(forecast_data)
},
'pressure': {
'trend': self._calculate_advanced_trend(pressure),
'avg': sum(pressure) / len(pressure),
'stability': self._calculate_stability_index(pressure),
'change_rate': self._calculate_pressure_change_rate(pressure),
'weather_change_likelihood': self._predict_weather_changes_advanced(pressure)
},
'comfort': {
'trend': self._calculate_advanced_trend(comfort_scores),
'avg': sum(comfort_scores) / len(comfort_scores),
'forecast_quality': self._assess_forecast_comfort_quality(comfort_scores),
'optimal_days': self._find_optimal_days(forecast_data)
},
'patterns': {
'seasonal_alignment': self._assess_seasonal_alignment(forecast_data),
'weather_diversity': self._calculate_weather_diversity(forecast_data),
'stability_forecast': self._predict_stability_changes(forecast_data),
'extreme_event_probability': self._calculate_extreme_event_probability(forecast_data)
}
}
# Add machine learning insights
trends['ml_insights'] = self._generate_ml_insights(forecast_data, trends)
return trends
def _calculate_advanced_trend(self, data: List[float]) -> Dict[str, Any]:
"""Calculate advanced trend analysis with confidence intervals"""
if len(data) < 3:
return {'direction': 'insufficient_data', 'strength': 0, 'confidence': 0}
x = np.arange(len(data))
slope, intercept, r_value, p_value, std_err = stats.linregress(x, data)
# Determine trend direction and strength
if abs(r_value) < 0.3:
direction = 'stable'
strength = abs(r_value)
elif slope > 0:
direction = 'increasing'
strength = r_value
else:
direction = 'decreasing'
strength = abs(r_value)
# Calculate confidence based on p-value and r-squared
confidence = (1 - p_value) * (r_value ** 2)
return {
'direction': direction,
'strength': float(strength),
'confidence': float(confidence),
'slope': float(slope),
'r_squared': float(r_value ** 2),
'p_value': float(p_value),
'prediction_accuracy': self._estimate_prediction_accuracy(r_value, len(data))
}
def _calculate_volatility(self, data: List[float]) -> float:
"""Calculate volatility using standard deviation of changes"""
if len(data) < 2:
return 0.0
changes = [abs(data[i] - data[i-1]) for i in range(1, len(data))]
return float(np.std(changes))
def _calculate_momentum(self, data: List[float]) -> float:
"""Calculate momentum using rate of change acceleration"""
if len(data) < 3:
return 0.0
# Calculate first and second derivatives
first_diff = np.diff(data)
second_diff = np.diff(first_diff)
# Momentum is the average of second derivatives
return float(np.mean(second_diff))
def _calculate_stability_index(self, data: List[float]) -> float:
"""Calculate stability index (0-1, higher = more stable)"""
if len(data) < 2:
return 1.0
cv = np.std(data) / np.mean(data) if np.mean(data) != 0 else 0
return float(max(0, 1 - cv))
def _calculate_correlation(self, data1: List[float], data2: List[float]) -> float:
"""Calculate correlation between two datasets"""
if len(data1) != len(data2) or len(data1) < 2:
return 0.0
correlation, _ = stats.pearsonr(data1, data2)
return float(correlation) if not np.isnan(correlation) else 0.0
def _detect_pattern_risk(self, pattern_type: str, forecast_data: List[Dict]) -> float:
"""Advanced pattern risk detection with severity assessment"""
if pattern_type not in self.weather_patterns:
return 0.0
pattern_config = self.weather_patterns[pattern_type]
if pattern_type == 'heat_wave':
return self._detect_heat_wave_advanced(forecast_data, pattern_config)
elif pattern_type == 'cold_snap':
return self._detect_cold_snap_advanced(forecast_data, pattern_config)
elif pattern_type == 'drought':
return self._detect_drought_advanced(forecast_data, pattern_config)
elif pattern_type == 'storm_system':
return self._detect_storm_advanced(forecast_data, pattern_config)
return 0.0
def _detect_heat_wave_advanced(self, forecast_data: List[Dict], config: Dict) -> float:
"""Advanced heat wave detection with severity levels"""
severity_levels = config['severity_levels']
max_risk = 0.0
for severity, params in severity_levels.items():
consecutive_days = 0
max_consecutive = 0
for day in forecast_data:
if day['temp_max'] > params['temp']:
consecutive_days += 1
max_consecutive = max(max_consecutive, consecutive_days)
else:
consecutive_days = 0
if max_consecutive >= params['duration']:
severity_multiplier = {'moderate': 0.4, 'severe': 0.7, 'extreme': 1.0}
risk = severity_multiplier[severity] * min(max_consecutive / params['duration'], 2.0)
max_risk = max(max_risk, risk)
return min(max_risk, 1.0)
def _detect_cold_snap_advanced(self, forecast_data: List[Dict], config: Dict) -> float:
"""Advanced cold snap detection"""
severity_levels = config['severity_levels']
max_risk = 0.0
for severity, params in severity_levels.items():
consecutive_days = 0
max_consecutive = 0
for day in forecast_data:
if day['temp_min'] < params['temp']:
consecutive_days += 1
max_consecutive = max(max_consecutive, consecutive_days)
else:
consecutive_days = 0
if max_consecutive >= params['duration']:
severity_multiplier = {'moderate': 0.4, 'severe': 0.7, 'extreme': 1.0}
risk = severity_multiplier[severity] * min(max_consecutive / params['duration'], 2.0)
max_risk = max(max_risk, risk)
return min(max_risk, 1.0)
def _detect_drought_advanced(self, forecast_data: List[Dict], config: Dict) -> float:
"""Advanced drought condition detection"""
dry_days = 0
low_humidity_days = 0
for day in forecast_data:
if day['precipitation_chance'] < config['precipitation_threshold'] * 100:
dry_days += 1
if day['humidity'] < config['humidity_threshold']:
low_humidity_days += 1
dry_risk = min(dry_days / len(forecast_data), 1.0)
humidity_risk = min(low_humidity_days / len(forecast_data), 1.0)
return (dry_risk + humidity_risk) / 2
def _detect_storm_advanced(self, forecast_data: List[Dict], config: Dict) -> float:
"""Advanced storm system detection"""
storm_indicators = 0
total_possible = len(forecast_data) * 3 # Three indicators per day
for day in forecast_data:
# High wind indicator
if day['wind_speed'] > config['wind_threshold']:
storm_indicators += 1
# Pressure drop indicator
if 'pressure_trend' in day and day['pressure_trend'] == 'falling':
storm_indicators += 1
# High precipitation indicator
if day['precipitation_chance'] > config['precipitation_threshold'] * 10:
storm_indicators += 1
return min(storm_indicators / total_possible, 1.0)
def _calculate_wind_consistency_trend(self, forecast_data: List[Dict]) -> Dict[str, float]:
"""Calculate wind consistency trend over forecast period"""
consistency_values = [day.get('wind_consistency', 0.5) for day in forecast_data]
return {
'trend': self._calculate_advanced_trend(consistency_values)['direction'],
'avg_consistency': float(np.mean(consistency_values)),
'consistency_stability': self._calculate_stability_index(consistency_values)
}
def _calculate_pressure_change_rate(self, pressure_data: List[float]) -> float:
"""Calculate the rate of pressure change"""
if len(pressure_data) < 2:
return 0.0
changes = [pressure_data[i] - pressure_data[i-1] for i in range(1, len(pressure_data))]
return float(np.mean(changes))
def _predict_weather_changes_advanced(self, pressure_data: List[float]) -> Dict[str, float]:
"""Advanced weather change prediction based on pressure patterns"""
if len(pressure_data) < 3:
return {'probability': 0.0, 'confidence': 0.0, 'type': 'unknown'}
# Calculate pressure trend and volatility
trend_info = self._calculate_advanced_trend(pressure_data)
volatility = self._calculate_volatility(pressure_data)
# Rapid pressure changes indicate weather system movement
change_probability = min(volatility / 10, 1.0) # Normalize to 0-1
# Determine change type
if trend_info['direction'] == 'decreasing' and trend_info['strength'] > 0.5:
change_type = 'deteriorating'
elif trend_info['direction'] == 'increasing' and trend_info['strength'] > 0.5:
change_type = 'improving'
else:
change_type = 'variable'
return {
'probability': float(change_probability),
'confidence': float(trend_info['confidence']),
'type': change_type,
'volatility': float(volatility)
}
def _assess_forecast_comfort_quality(self, comfort_scores: List[float]) -> Dict[str, Any]:
"""Assess the overall quality of forecast comfort"""
if not comfort_scores:
return {'average': 50, 'quality': 'unknown', 'consistency': 0}
avg_comfort = sum(comfort_scores) / len(comfort_scores)
comfort_stability = self._calculate_stability_index(comfort_scores)
# Determine quality level
if avg_comfort >= 80 and comfort_stability >= 0.8:
quality = 'excellent'
elif avg_comfort >= 70 and comfort_stability >= 0.6:
quality = 'good'
elif avg_comfort >= 60:
quality = 'fair'