-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeatherForecast.py
More file actions
2052 lines (1732 loc) Β· 86.2 KB
/
Copy pathWeatherForecast.py
File metadata and controls
2052 lines (1732 loc) Β· 86.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
#!/usr/bin/env python3
"""
Weather Forecast Window for Cosmos Collection
Displays astrophotography-relevant weather data from Open-Meteo API
"""
import sys
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any, Tuple
import matplotlib
matplotlib.use('QtAgg')
# Suppress matplotlib font_manager debug messages
logging.getLogger('matplotlib.font_manager').setLevel(logging.WARNING)
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
# Set dark theme for matplotlib
plt.style.use('dark_background')
import requests
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import EarthLocation, AltAz, get_sun, get_body
from PySide6.QtCore import Qt, QThread, Signal, QSettings, QTimer, QUrl
from PySide6.QtWidgets import (
QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QPushButton,
QLabel, QGroupBox, QMessageBox, QProgressBar, QScrollArea,
QFrame, QGridLayout, QDialog, QTableWidget, QTableWidgetItem,
QHeaderView, QApplication, QSplitter, QCheckBox, QComboBox, QSizePolicy
)
from PySide6.QtGui import QColor
from DatabaseManager import DatabaseManager
from WindowPositionManager import WindowPositionMixin
from Theme import COLORS
from TimeFormatHelper import format_time, format_datetime, get_time_format_24h
from UrlOpener import open_url
# Set up logging
logger = logging.getLogger(__name__)
# Cache for weather data (persists across window instances)
CACHE_MAX_AGE_MINUTES = 15
def _get_openweather_signature() -> Tuple[bool, str]:
"""Return (enabled, api_key) reflecting the current OpenWeather integration
settings. Used to detect when cached weather data was fetched under a
different OpenWeather configuration (e.g. the user just enabled the
integration and added an API key) so a stale cache doesn't hide the change."""
settings = QSettings("CosmosCollection", "CosmosCollection")
enabled = settings.value("openweather_integration_enabled", False, type=bool)
api_key = settings.value("openweather_api_key", "", type=str)
return (enabled, api_key)
def test_openweather_key(api_key: str, timeout: int = 10) -> Tuple[bool, str]:
"""Test whether an OpenWeather API key is valid via a lightweight current-weather
request. Used by the Settings dialog's "Test API Key" button.
Returns:
tuple: (success: bool, message: str)
"""
api_key = (api_key or "").strip()
if not api_key:
return False, "Please enter an API key first."
try:
# Any fixed coordinates work here - we only care whether the key is accepted.
url = f"https://api.openweathermap.org/data/2.5/weather?lat=51.5074&lon=-0.1278&appid={api_key}"
verify = not getattr(sys, 'frozen', False)
response = requests.get(url, timeout=timeout, verify=verify)
if response.status_code == 401:
return False, (
"Invalid API key. Please double-check your key.\n\n"
"Note: newly created OpenWeather keys can take a few minutes to activate."
)
response.raise_for_status()
response.json() # confirm the response is valid JSON
return True, "Connection successful! Your OpenWeather API key is valid."
except requests.exceptions.Timeout:
return False, "Connection timed out. Please check your network connection."
except requests.exceptions.RequestException as e:
return False, f"Connection failed: {str(e)}"
except Exception as e:
return False, f"Error testing API key: {str(e)}"
class WeatherCache:
"""Simple cache for weather data to reduce API calls"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(WeatherCache, cls).__new__(cls)
cls._instance._data = None
cls._instance._timestamp = None
cls._instance._location = None
cls._instance._openweather_signature = None
cls._instance._update_callbacks = []
return cls._instance
def get(self, lat: float, lon: float) -> Optional[List]:
"""Get cached data if valid and for the same location"""
if self._data is None or self._timestamp is None:
return None
# Check if location matches (within small tolerance for float comparison)
if self._location is None:
return None
cached_lat, cached_lon = self._location
if abs(cached_lat - lat) > 0.01 or abs(cached_lon - lon) > 0.01:
logger.debug("Weather cache miss: location changed")
return None
# Check if cache is still valid
age = datetime.now() - self._timestamp
if age > timedelta(minutes=CACHE_MAX_AGE_MINUTES):
logger.debug(f"Weather cache miss: data is {age.seconds // 60} minutes old")
return None
# Check if OpenWeather integration settings changed since this data was
# fetched (e.g. user just enabled it / added an API key) - if so, the
# cached data doesn't reflect the current configuration, so treat it as stale.
if self._openweather_signature != _get_openweather_signature():
logger.debug("Weather cache miss: OpenWeather integration settings changed")
return None
logger.debug(f"Weather cache hit: data is {age.seconds // 60} minutes old")
return self._data
def set(self, lat: float, lon: float, data: List):
"""Store data in cache and notify callbacks"""
self._data = data
self._timestamp = datetime.now()
self._location = (lat, lon)
self._openweather_signature = _get_openweather_signature()
logger.debug("Weather data cached")
# Notify all registered callbacks
for callback in self._update_callbacks:
try:
callback(data)
except Exception as e:
logger.debug(f"Weather cache callback error: {e}")
def get_age_str(self) -> Optional[str]:
"""Get a human-readable string of cache age"""
if self._timestamp is None:
return None
age = datetime.now() - self._timestamp
minutes = age.seconds // 60
if minutes < 1:
return "just now"
elif minutes == 1:
return "1 minute ago"
else:
return f"{minutes} minutes ago"
def clear(self):
"""Clear the cache"""
self._data = None
self._timestamp = None
self._location = None
self._openweather_signature = None
def add_update_callback(self, callback):
"""Register a callback to be called when weather data is updated.
Args:
callback: A callable that accepts a list of DailyWeatherSummary objects
"""
if callback not in self._update_callbacks:
self._update_callbacks.append(callback)
def remove_update_callback(self, callback):
"""Remove a previously registered callback."""
if callback in self._update_callbacks:
self._update_callbacks.remove(callback)
def get_cached_data(self) -> Optional[List]:
"""Get the cached data without location/age checks (for tray updates)."""
return self._data
@dataclass
class MoonPhaseData:
"""Moon phase information for a date"""
phase_angle: float # 0-180 degrees (elongation from sun)
illumination: float # 0-100 percentage
phase_name: str # "New Moon", "Waxing Crescent", etc.
phase_emoji: str # Moon phase emoji
@dataclass
class HourlyWeatherData:
"""Dataclass for hourly weather data"""
time: datetime
cloud_cover: float # Total cloud cover %
cloud_cover_low: float
cloud_cover_mid: float
cloud_cover_high: float
temperature: float # Celsius
dew_point: float # Celsius
humidity: float # %
wind_speed: float # km/h
precipitation_probability: float # %
wind_gusts: float = 0.0 # km/h β peak gust in the hour
visibility: Optional[float] = None # meters
surface_pressure: Optional[float] = None # hPa
openweather_blended: bool = False # True if this hour was averaged with OpenWeather data
@dataclass
class DailyWeatherSummary:
"""Dataclass for daily aggregated weather data"""
date: datetime
hourly_data: List[HourlyWeatherData]
avg_cloud_cover: float
min_cloud_cover: float
max_cloud_cover: float
avg_temperature: float
min_temperature: float
max_temperature: float
avg_humidity: float
avg_wind_speed: float
max_wind_speed: float
avg_precipitation_prob: float
tonight_avg_cloud_cover: float # avg cloud cover for dark hours only (sun_alt < -12Β°)
astro_score: int # 0-100
seeing_estimate: str # Excellent/Good/Moderate/Poor
moon_phase: Optional[MoonPhaseData] = None
dark_hours_start: Optional[datetime] = None # First dark hour (sun_alt < -12Β°)
dark_hours_end: Optional[datetime] = None # Last dark hour (sun_alt < -12Β°)
openweather_blended: bool = False # True if any hour this day was blended with OpenWeather data
class WeatherWorker(QThread):
"""QThread worker for fetching weather data from Open-Meteo API"""
weather_loaded = Signal(list) # List of DailyWeatherSummary
error_occurred = Signal(str)
progress = Signal(str)
def __init__(self, lat: float, lon: float, timezone: str = None):
super().__init__()
self.lat = lat
self.lon = lon
self.timezone = timezone
# Set by _fetch_openweather_data() when OpenWeather is enabled but a fetch
# attempt fails (bad key, network error, etc.) - None otherwise, including
# when the integration is simply disabled/unconfigured (not an error).
self.openweather_error: Optional[str] = None
def run(self):
"""Fetch weather data from Open-Meteo API"""
try:
self.progress.emit("Connecting to Open-Meteo API...")
# Build API URL
url = (
f"https://api.open-meteo.com/v1/forecast?"
f"latitude={self.lat}&longitude={self.lon}&"
f"hourly=cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,"
f"temperature_2m,dew_point_2m,relative_humidity_2m,"
f"wind_speed_10m,wind_gusts_10m,precipitation_probability,visibility,surface_pressure&"
f"forecast_days=7&timezone=auto"
)
# Handle SSL for PyInstaller frozen builds
verify = not getattr(sys, 'frozen', False)
self.progress.emit("Downloading weather forecast data...")
response = requests.get(url, timeout=30, verify=verify)
response.raise_for_status()
data = response.json()
# Optionally supplement with OpenWeather data (opt-in, requires API key).
# Returns None if disabled/unconfigured/unavailable, in which case the
# forecast falls back to Open-Meteo data only, exactly as before.
openweather_data = self._fetch_openweather_data()
self.progress.emit("Processing weather data...")
daily_summaries = self._process_weather_data(data, openweather_data)
self.weather_loaded.emit(daily_summaries)
except requests.exceptions.RequestException as e:
self.error_occurred.emit(f"Network error: {str(e)}")
except Exception as e:
logger.error(f"Error fetching weather data: {str(e)}", exc_info=True)
self.error_occurred.emit(f"Error: {str(e)}")
def _fetch_openweather_data(self) -> Optional[Dict[datetime, Dict[str, Optional[float]]]]:
"""Fetch supplemental forecast data from OpenWeather's free 5 day / 3 hour
forecast API, if the integration is enabled and an API key is configured.
Returns a dict keyed by forecast timestamp -> field values, or None if the
integration is disabled/unconfigured (not an error - self.openweather_error
stays None) or the request fails for any reason such as a bad key, network
error, or rate limit (self.openweather_error is set to a short reason so
callers can surface it, e.g. in the Weather Forecast window's status line).
Either way, callers should treat None as "no supplemental data available"
and fall back to Open-Meteo-only data.
"""
self.openweather_error = None
try:
enabled, api_key = _get_openweather_signature()
if not enabled or not api_key:
return None
url = (
f"https://api.openweathermap.org/data/2.5/forecast?"
f"lat={self.lat}&lon={self.lon}&units=metric&appid={api_key}"
)
verify = not getattr(sys, 'frozen', False)
response = requests.get(url, timeout=20, verify=verify)
if response.status_code == 401:
self.openweather_error = "invalid API key"
logger.warning("OpenWeather fetch failed: invalid API key")
return None
response.raise_for_status()
data = response.json()
result: Dict[datetime, Dict[str, Optional[float]]] = {}
for entry in data.get("list", []):
dt = datetime.fromtimestamp(entry["dt"])
main = entry.get("main", {})
wind = entry.get("wind", {})
wind_speed = wind.get("speed")
wind_gust = wind.get("gust")
pop = entry.get("pop")
result[dt] = {
"cloud_cover": entry.get("clouds", {}).get("all"),
"temperature": main.get("temp"),
"humidity": main.get("humidity"),
"surface_pressure": main.get("pressure"),
"wind_speed": wind_speed * 3.6 if wind_speed is not None else None, # m/s -> km/h
"wind_gusts": wind_gust * 3.6 if wind_gust is not None else None, # m/s -> km/h
"precipitation_probability": pop * 100 if pop is not None else None,
"visibility": entry.get("visibility"),
}
return result
except requests.exceptions.Timeout:
self.openweather_error = "request timed out"
logger.warning("OpenWeather fetch failed: timed out")
return None
except requests.exceptions.RequestException as e:
self.openweather_error = "network error"
logger.warning(f"OpenWeather fetch failed: network error: {e}")
return None
except Exception as e:
self.openweather_error = "unexpected error"
logger.warning(f"OpenWeather fetch failed, continuing with Open-Meteo only: {e}")
return None
def _process_weather_data(
self,
data: Dict[str, Any],
openweather_data: Optional[Dict[datetime, Dict[str, Optional[float]]]] = None
) -> List[DailyWeatherSummary]:
"""Process raw API data into daily summaries, optionally blending in
supplemental OpenWeather data (simple average per overlapping field)."""
hourly = data.get("hourly", {})
times = hourly.get("time", [])
if not times:
return []
def blend(om_value, ow_match: Optional[Dict[str, Optional[float]]], field: str):
"""Average an Open-Meteo value with the matching OpenWeather value,
if one was found for this hour and the field is present."""
if ow_match is None:
return om_value, False
ow_value = ow_match.get(field)
if ow_value is None:
return om_value, False
return (om_value + ow_value) / 2, True
def find_openweather_match(dt: datetime, tolerance_minutes: int = 90):
"""Find the nearest OpenWeather 3-hour forecast entry to an Open-Meteo
hourly timestamp, within a tolerance window."""
if not openweather_data:
return None
best_match = None
best_diff = None
for ow_dt, values in openweather_data.items():
diff = abs((ow_dt - dt).total_seconds())
if diff <= tolerance_minutes * 60 and (best_diff is None or diff < best_diff):
best_match = values
best_diff = diff
return best_match
# Parse hourly data
hourly_records: List[HourlyWeatherData] = []
for i, time_str in enumerate(times):
try:
dt = datetime.fromisoformat(time_str)
ow_match = find_openweather_match(dt)
cloud_cover, blended_1 = blend(hourly.get("cloud_cover", [0] * len(times))[i] or 0, ow_match, "cloud_cover")
temperature, blended_2 = blend(hourly.get("temperature_2m", [0] * len(times))[i] or 0, ow_match, "temperature")
humidity, blended_3 = blend(hourly.get("relative_humidity_2m", [0] * len(times))[i] or 0, ow_match, "humidity")
wind_speed, blended_4 = blend(hourly.get("wind_speed_10m", [0] * len(times))[i] or 0, ow_match, "wind_speed")
wind_gusts, blended_5 = blend(hourly.get("wind_gusts_10m", [0] * len(times))[i] or 0, ow_match, "wind_gusts")
precip_prob, blended_6 = blend(
hourly.get("precipitation_probability", [0] * len(times))[i] or 0, ow_match, "precipitation_probability"
)
visibility_om = hourly.get("visibility", [None] * len(times))[i]
visibility, blended_7 = blend(visibility_om or 0, ow_match, "visibility") if visibility_om is not None else (visibility_om, False)
pressure_om = hourly.get("surface_pressure", [None] * len(times))[i]
surface_pressure, blended_8 = blend(pressure_om or 0, ow_match, "surface_pressure") if pressure_om is not None else (pressure_om, False)
hourly_records.append(HourlyWeatherData(
time=dt,
cloud_cover=cloud_cover,
cloud_cover_low=hourly.get("cloud_cover_low", [0] * len(times))[i] or 0,
cloud_cover_mid=hourly.get("cloud_cover_mid", [0] * len(times))[i] or 0,
cloud_cover_high=hourly.get("cloud_cover_high", [0] * len(times))[i] or 0,
temperature=temperature,
dew_point=hourly.get("dew_point_2m", [0] * len(times))[i] or 0,
humidity=humidity,
wind_speed=wind_speed,
precipitation_probability=precip_prob,
wind_gusts=wind_gusts,
visibility=visibility,
surface_pressure=surface_pressure,
openweather_blended=any([blended_1, blended_2, blended_3, blended_4, blended_5, blended_6, blended_7, blended_8])
))
except (ValueError, IndexError) as e:
logger.warning(f"Error parsing hourly data at index {i}: {e}")
continue
# Group by date
daily_data: Dict[datetime.date, List[HourlyWeatherData]] = {}
for record in hourly_records:
date = record.time.date()
if date not in daily_data:
daily_data[date] = []
daily_data[date].append(record)
# Calculate sun altitudes for all hourly records (vectorized for efficiency)
all_times = [record.time for record in hourly_records]
sun_altitudes = calculate_sun_altitudes(self.lat, self.lon, all_times, self.timezone)
sun_alt_map = dict(zip(all_times, sun_altitudes))
# Create daily summaries
sorted_dates = sorted(daily_data.keys())
daily_summaries: List[DailyWeatherSummary] = []
for date_idx, date in enumerate(sorted_dates):
hours = daily_data[date]
if not hours:
continue
# Calculate aggregates for all hours (used for display)
cloud_covers = [h.cloud_cover for h in hours]
temps = [h.temperature for h in hours]
humidities = [h.humidity for h in hours]
winds = [h.wind_speed for h in hours]
precip_probs = [h.precipitation_probability for h in hours]
avg_cloud = sum(cloud_covers) / len(cloud_covers)
avg_humidity = sum(humidities) / len(humidities)
avg_wind = sum(winds) / len(winds)
avg_precip = sum(precip_probs) / len(precip_probs)
# Build "tonight" hours: evening dark hours of this day + morning dark hours of next day
evening_dark = [h for h in hours if h.time.hour >= 12 and sun_alt_map.get(h.time, 0) < -12]
morning_dark = []
if date_idx + 1 < len(sorted_dates):
next_date = sorted_dates[date_idx + 1]
next_hours = daily_data[next_date]
morning_dark = [h for h in next_hours if h.time.hour < 12 and sun_alt_map.get(h.time, 0) < -12]
tonight_hours = evening_dark + morning_dark
# Determine dark hours start and end times
dark_start = tonight_hours[0].time if tonight_hours else None
dark_end = tonight_hours[-1].time if tonight_hours else None
# Calculate astro score as the average of individual hourly scores
if tonight_hours:
hourly_scores = [
calculate_astro_score(h.cloud_cover, h.humidity, h.wind_speed,
h.precipitation_probability, h.visibility,
h.wind_gusts)
for h in tonight_hours
]
astro_score = int(sum(hourly_scores) / len(hourly_scores))
else:
# No dark hours (e.g., polar summer) - score is 0
astro_score = 0
# Calculate tonight's average cloud cover (dark hours only)
if tonight_hours:
tonight_avg_cloud = sum(h.cloud_cover for h in tonight_hours) / len(tonight_hours)
else:
tonight_avg_cloud = avg_cloud # Fallback to full day average
# Estimate seeing based on tonight's hours
if tonight_hours:
night_humidity = sum(h.humidity for h in tonight_hours) / len(tonight_hours)
night_wind = sum(h.wind_speed for h in tonight_hours) / len(tonight_hours)
night_gusts = max(h.wind_gusts for h in tonight_hours)
night_temp_dew_spread = sum(h.temperature - h.dew_point for h in tonight_hours) / len(tonight_hours)
# Average surface pressure for tonight (filter out None values)
pressure_values = [h.surface_pressure for h in tonight_hours if h.surface_pressure is not None]
night_pressure = sum(pressure_values) / len(pressure_values) if pressure_values else None
else:
night_humidity = avg_humidity
night_wind = avg_wind
night_gusts = max(h.wind_gusts for h in hours)
night_temp_dew_spread = sum(h.temperature - h.dew_point for h in hours) / len(hours)
pressure_values = [h.surface_pressure for h in hours if h.surface_pressure is not None]
night_pressure = sum(pressure_values) / len(pressure_values) if pressure_values else None
seeing = estimate_seeing(night_humidity, night_wind, night_temp_dew_spread, night_pressure, night_gusts)
# Calculate moon phase for this date
moon_phase = calculate_moon_phase(datetime.combine(date, datetime.min.time()), self.timezone)
summary = DailyWeatherSummary(
date=datetime.combine(date, datetime.min.time()),
hourly_data=hours,
avg_cloud_cover=avg_cloud,
min_cloud_cover=min(cloud_covers),
max_cloud_cover=max(cloud_covers),
avg_temperature=sum(temps) / len(temps),
min_temperature=min(temps),
max_temperature=max(temps),
avg_humidity=avg_humidity,
avg_wind_speed=avg_wind,
max_wind_speed=max(winds),
avg_precipitation_prob=avg_precip,
tonight_avg_cloud_cover=tonight_avg_cloud,
astro_score=astro_score,
seeing_estimate=seeing,
moon_phase=moon_phase,
dark_hours_start=dark_start,
dark_hours_end=dark_end,
openweather_blended=any(h.openweather_blended for h in hours)
)
daily_summaries.append(summary)
return daily_summaries
def calculate_astro_score(cloud_cover: float, humidity: float, wind_speed: float,
precip_prob: float, visibility: Optional[float] = None,
wind_gusts: float = 0.0) -> int:
"""
Calculate an astrophotography suitability score (0-100).
Cloud cover is the dominant factor - high cloud cover caps the maximum possible score
since you cannot do astrophotography through clouds regardless of other conditions.
Score caps based on cloud cover:
- >80% clouds: max score 30 (Poor)
- >60% clouds: max score 50 (Moderate)
- >40% clouds: max score 70 (Good)
Score caps based on wind gusts (applied after cloud caps):
- >40 km/h gusts: max score 35 (severe β tracking essentially impossible)
- >25 km/h gusts: max score 60 (moderate β long exposures degraded)
Base scoring weights:
- Cloud cover (40%): lower is better
- Transparency/Visibility (15%): higher is better (affects deep sky objects)
- Humidity (15%): ideal 30-50%, affects transparency and dew risk
- Wind speed (15%): under 15 km/h is good for tracking/guiding
- Precipitation (15%): 0% is ideal
Args:
cloud_cover: Cloud cover percentage (0-100)
humidity: Relative humidity percentage (0-100)
wind_speed: Wind speed in km/h
precip_prob: Precipitation probability percentage (0-100)
visibility: Visibility in meters (None if unavailable)
wind_gusts: Peak wind gust speed in km/h (gusts weighted 75% β intermittent)
"""
# Cloud cover score (0-100, lower clouds = higher score)
cloud_score = max(0, 100 - cloud_cover)
# Visibility/Transparency score (0-100, higher visibility = better transparency)
# Open-Meteo returns visibility in meters
# Excellent: > 40km, Good: 20-40km, Moderate: 10-20km, Poor: < 10km
if visibility is not None:
visibility_km = visibility / 1000.0
if visibility_km >= 40:
visibility_score = 100
elif visibility_km >= 20:
# Linear interpolation from 70 to 100 between 20-40km
visibility_score = 70 + (visibility_km - 20) * 1.5
elif visibility_km >= 10:
# Linear interpolation from 40 to 70 between 10-20km
visibility_score = 40 + (visibility_km - 10) * 3
else:
# Below 10km, score drops more steeply
visibility_score = max(0, visibility_km * 4)
else:
# If visibility data unavailable, use a neutral score
visibility_score = 70
# Humidity score (0-100, ideal around 40%)
# High humidity reduces transparency and increases dew risk
if humidity < 30:
humidity_score = 70 + humidity # Slightly penalize very dry
elif humidity <= 50:
humidity_score = 100 # Ideal range
elif humidity <= 70:
humidity_score = 100 - (humidity - 50) * 2 # 50-100 as humidity goes from 50-70
else:
humidity_score = max(0, 60 - (humidity - 70)) # Penalize high humidity
# Wind score (0-100, under 15 km/h is good)
# Gusts are intermittent so weighted at 75%; effective_wind >= sustained speed
effective_wind = max(wind_speed, wind_gusts * 0.75)
if effective_wind <= 10:
wind_score = 100
elif effective_wind <= 15:
wind_score = 100 - (effective_wind - 10) * 4 # 80-100 range
elif effective_wind <= 25:
wind_score = 80 - (effective_wind - 15) * 4 # 40-80 range
else:
wind_score = max(0, 40 - (effective_wind - 25) * 2)
# Precipitation score (0-100, 0% is ideal)
precip_score = max(0, 100 - precip_prob * 2)
# Weighted average
total_score = (
cloud_score * 0.40 +
visibility_score * 0.15 +
humidity_score * 0.15 +
wind_score * 0.15 +
precip_score * 0.15
)
# Apply cloud cover caps - high clouds should hard-limit the score
# since astrophotography is impossible through heavy cloud cover
if cloud_cover > 80:
total_score = min(total_score, 30) # Cap at Poor
elif cloud_cover > 60:
total_score = min(total_score, 50) # Cap at low Moderate
elif cloud_cover > 40:
total_score = min(total_score, 70) # Cap at Good
# Apply wind gust caps β severe gusts ruin tracking regardless of sky clarity
if wind_gusts > 40:
total_score = min(total_score, 35) # Severe gusts β tracking essentially impossible
elif wind_gusts > 25:
total_score = min(total_score, 60) # Moderate gusts β long exposures degraded
return int(min(100, max(0, total_score)))
def estimate_seeing(humidity: float, wind_speed: float, temp_dew_spread: float,
surface_pressure: Optional[float] = None,
wind_gusts: float = 0.0) -> str:
"""
Estimate seeing quality based on atmospheric conditions.
Seeing (atmospheric turbulence) is affected by:
- Humidity: High humidity can indicate atmospheric instability
- Wind: High winds cause turbulence, but moderate wind can indicate stable laminar flow
- Temperature-dew spread: Indicates moisture content and potential for ground-level turbulence
- Surface pressure: High, stable pressure generally means better seeing;
low pressure systems bring unstable air masses
Args:
humidity: Relative humidity %
wind_speed: Wind speed in km/h
temp_dew_spread: Temperature minus dew point (larger = less moisture)
surface_pressure: Surface pressure in hPa (None if unavailable)
Returns:
Seeing quality string: Excellent/Good/Moderate/Poor
"""
score = 100
# Humidity factor (lower is better for seeing)
if humidity > 80:
score -= 30
elif humidity > 65:
score -= 15
elif humidity > 50:
score -= 5
# Wind factor (calm to light is best, strong winds cause turbulence)
# However, very calm conditions can lead to ground-layer turbulence
# Use the worse of sustained speed or gusts for seeing penalty
gust_wind = max(wind_speed, wind_gusts)
if gust_wind > 30:
score -= 40 # Very high winds - severe turbulence
elif gust_wind > 25:
score -= 30
elif gust_wind > 15:
score -= 15
elif gust_wind > 10:
score -= 5
elif wind_speed < 3:
score -= 5 # Very calm - potential ground layer issues
# Dew risk factor (larger spread = better, also indicates drier air column)
if temp_dew_spread < 2:
score -= 25 # High dew risk and moist air
elif temp_dew_spread < 5:
score -= 10
elif temp_dew_spread > 15:
score += 10 # Very dry air column - excellent
elif temp_dew_spread > 10:
score += 5 # Very safe from dew
# Surface pressure factor
# High pressure (>1020 hPa) typically indicates stable air mass = better seeing
# Low pressure (<1000 hPa) indicates unstable weather systems = worse seeing
# Normal range is roughly 980-1040 hPa
if surface_pressure is not None:
if surface_pressure >= 1025:
score += 15 # Strong high pressure - excellent stability
elif surface_pressure >= 1015:
score += 10 # High pressure - good stability
elif surface_pressure >= 1005:
score += 0 # Normal pressure - neutral
elif surface_pressure >= 995:
score -= 10 # Lowish pressure - some instability
else:
score -= 20 # Low pressure system - unstable air
if score >= 80:
return "Excellent"
elif score >= 60:
return "Good"
elif score >= 40:
return "Moderate"
else:
return "Poor"
def get_rating_color(score: int) -> str:
"""Get color based on astro score"""
if score >= 80:
return COLORS['success'] # Green
elif score >= 60:
return COLORS['info'] # Blue
elif score >= 40:
return COLORS['warning'] # Yellow
else:
return COLORS['error'] # Red
def get_rating_label(score: int) -> str:
"""Get label based on astro score"""
if score >= 80:
return "Excellent"
elif score >= 60:
return "Good"
elif score >= 40:
return "Moderate"
else:
return "Poor"
def calculate_sun_altitudes(lat: float, lon: float, times: List[datetime], timezone: str = None) -> List[float]:
"""
Calculate sun altitude for each time point.
Args:
lat: Observer latitude in degrees
lon: Observer longitude in degrees
times: List of datetime objects for each hour (in local time)
timezone: Optional timezone string (e.g., 'America/New_York') for converting local times to UTC
Returns:
List of sun altitudes in degrees for each time point
"""
if not times:
return []
# Convert naive local times to UTC if timezone is provided
if timezone:
try:
import pytz
local_tz = pytz.timezone(timezone)
utc_times = []
for t in times:
if t.tzinfo is None:
local_dt = local_tz.localize(t)
utc_dt = local_dt.astimezone(pytz.UTC)
utc_times.append(utc_dt.replace(tzinfo=None)) # astropy works with naive UTC
else:
utc_times.append(t)
times = utc_times
except Exception as e:
logger.warning(f"Could not convert times to UTC: {e}")
location = EarthLocation(lat=lat * u.deg, lon=lon * u.deg)
astropy_times = Time([t.isoformat() for t in times])
altaz_frame = AltAz(obstime=astropy_times, location=location)
sun_altaz = get_sun(astropy_times).transform_to(altaz_frame)
return sun_altaz.alt.deg.tolist()
def _get_moon_phase_name(phase_angle: float, is_waxing: bool) -> tuple:
"""
Map phase angle (elongation) to moon phase name and emoji.
Args:
phase_angle: Elongation from sun in degrees (0-180)
is_waxing: True if moon is waxing (getting brighter), False if waning
Returns:
Tuple of (phase_name, phase_emoji)
"""
if phase_angle < 22.5:
return ("New Moon", "π")
elif phase_angle < 67.5:
if is_waxing:
return ("Waxing Crescent", "π")
else:
return ("Waning Crescent", "π")
elif phase_angle < 112.5:
if is_waxing:
return ("First Quarter", "π")
else:
return ("Last Quarter", "π")
elif phase_angle < 157.5:
if is_waxing:
return ("Waxing Gibbous", "π")
else:
return ("Waning Gibbous", "π")
else:
return ("Full Moon", "π")
def calculate_moon_phase(date: datetime, timezone: str = None) -> MoonPhaseData:
"""
Calculate moon phase information for a given date.
Args:
date: The date to calculate moon phase for (naive datetime in local time)
timezone: Timezone string (e.g., 'America/New_York') for converting to UTC
Returns:
MoonPhaseData with phase angle, illumination, name, and emoji
"""
import numpy as np
from astropy.coordinates import GeocentricTrueEcliptic
# Convert local midnight to UTC if timezone is provided
if timezone:
try:
import pytz
local_tz = pytz.timezone(timezone)
if date.tzinfo is None:
local_dt = local_tz.localize(date)
utc_dt = local_dt.astimezone(pytz.UTC)
date = utc_dt.replace(tzinfo=None) # astropy works with naive UTC
except Exception as e:
logger.warning(f"Could not convert moon phase time to UTC: {e}")
# Use midnight of the date for calculation
obs_time = Time(date.isoformat())
# Get sun and moon positions
sun = get_sun(obs_time)
moon = get_body('moon', obs_time)
# Calculate elongation (angular separation between sun and moon)
elongation = sun.separation(moon)
phase_angle = elongation.deg
# Calculate illumination fraction
# Illumination = (1 - cos(elongation)) / 2
# This gives 0% at new moon (0Β°) and 100% at full moon (180Β°)
illumination = (1 - np.cos(elongation.rad)) / 2 * 100
# Determine if waxing or waning by comparing ecliptic longitudes
# Moon is waxing when its ecliptic longitude is ahead of (greater than) the sun's
sun_ecliptic = sun.transform_to(GeocentricTrueEcliptic(equinox=obs_time))
moon_ecliptic = moon.transform_to(GeocentricTrueEcliptic(equinox=obs_time))
sun_lon = sun_ecliptic.lon.deg
moon_lon = moon_ecliptic.lon.deg
# Calculate the difference (moon - sun), normalized to 0-360
lon_diff = (moon_lon - sun_lon) % 360
# If difference is 0-180, moon is ahead of sun = waxing
# If difference is 180-360, moon is behind sun = waning
is_waxing = lon_diff < 180
# Get phase name and emoji
phase_name, phase_emoji = _get_moon_phase_name(phase_angle, is_waxing)
return MoonPhaseData(
phase_angle=phase_angle,
illumination=illumination,
phase_name=phase_name,
phase_emoji=phase_emoji
)
class DayWeatherCard(QFrame):
"""Clickable card widget for displaying daily weather summary"""
clicked = Signal(object) # Emits DailyWeatherSummary
def __init__(self, summary: DailyWeatherSummary, parent=None):
super().__init__(parent)
self.summary = summary
self.setFrameShape(QFrame.Box)
self.setFrameShadow(QFrame.Raised)
self.setLineWidth(1)
self.setCursor(Qt.PointingHandCursor)
self.setMinimumWidth(100)
self.setMaximumWidth(130)
# Set background and border
rating_color = get_rating_color(summary.astro_score)
self.setStyleSheet(f"""
DayWeatherCard {{
background-color: {COLORS['background_light']};
border: 2px solid {rating_color};
border-radius: 8px;
padding: 5px;
}}
DayWeatherCard:hover {{
background-color: {COLORS['background_hover']};
border: 2px solid {rating_color};
}}
""")
self._setup_ui()
def _setup_ui(self):
"""Set up the card UI"""
layout = QVBoxLayout(self)
layout.setSpacing(4)
layout.setContentsMargins(8, 8, 8, 8)
# Day name
day_name = self.summary.date.strftime("%a")
day_label = QLabel(day_name)
day_label.setAlignment(Qt.AlignCenter)
day_label.setStyleSheet("font-weight: bold; font-size: 12pt;")
layout.addWidget(day_label)
# Date
date_str = self.summary.date.strftime("%m/%d")
date_label = QLabel(date_str)
date_label.setAlignment(Qt.AlignCenter)
date_label.setStyleSheet(f"color: {COLORS['text_secondary']}; font-size: 10pt;")
layout.addWidget(date_label)
layout.addSpacing(5)
# Rating
rating_color = get_rating_color(self.summary.astro_score)
rating_label = get_rating_label(self.summary.astro_score)
rating_text = QLabel(rating_label)
rating_text.setAlignment(Qt.AlignCenter)
rating_text.setStyleSheet(f"color: {rating_color}; font-weight: bold; font-size: 12pt;")
layout.addWidget(rating_text)
# Score
score_label = QLabel(f"({self.summary.astro_score})")
score_label.setAlignment(Qt.AlignCenter)
score_label.setStyleSheet(f"color: {COLORS['text_secondary']}; font-size: 10pt;")
score_label.setToolTip("Astro Score")
layout.addWidget(score_label)
layout.addSpacing(5)
cloud_text = QLabel("Clouds")
cloud_text.setAlignment(Qt.AlignCenter)
cloud_text.setStyleSheet(f"color: {COLORS['text_secondary']}; font-size: 12pt;")
cloud_text.setToolTip("Average cloud cover for dark hours (sun altitude < -12Β°)")
layout.addWidget(cloud_text)
# Cloud cover (tonight's average - dark hours only)
cloud_label = QLabel(f"{self.summary.tonight_avg_cloud_cover:.0f}%")
cloud_label.setAlignment(Qt.AlignCenter)
cloud_label.setStyleSheet("font-size: 10pt; font-weight: bold;")
layout.addWidget(cloud_label)
layout.addSpacing(5)
# Moon phase (compact display)