pyastroweatherio 0.76.0.dev1__tar.gz → 0.76.0.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/PKG-INFO +1 -1
  2. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/client.py +135 -13
  3. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/const.py +5 -3
  4. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/dataclasses.py +6 -0
  5. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/helper_functions.py +63 -37
  6. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio.egg-info/PKG-INFO +1 -1
  7. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/setup.py +1 -1
  8. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/LICENSE +0 -0
  9. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/README.md +0 -0
  10. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/__init__.py +0 -0
  11. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio/errors.py +0 -0
  12. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio.egg-info/SOURCES.txt +0 -0
  13. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio.egg-info/dependency_links.txt +0 -0
  14. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio.egg-info/requires.txt +0 -0
  15. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/pyastroweatherio.egg-info/top_level.txt +0 -0
  16. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/setup.cfg +0 -0
  17. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/tests/test_calculations.py +0 -0
  18. {pyastroweatherio-0.76.0.dev1 → pyastroweatherio-0.76.0.dev3}/tests/test_client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyastroweatherio
3
- Version: 0.76.0.dev1
3
+ Version: 0.76.0.dev3
4
4
  Summary: Python Wrapper for OpenMeteo and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -8,7 +8,7 @@ import os.path
8
8
  import socket
9
9
  from datetime import UTC, datetime, timedelta, timezone
10
10
  from json.decoder import JSONDecodeError
11
- from typing import Any, Dict, List, Optional
11
+ from typing import Dict, List, Optional
12
12
 
13
13
  import aiofiles
14
14
 
@@ -20,8 +20,10 @@ from aiohttp.client_exceptions import ClientError
20
20
  from typeguard import typechecked
21
21
 
22
22
  from pyastroweatherio.const import (
23
+ AOD_TO_MAG_FACTOR,
23
24
  BASE_URL_MET,
24
25
  BASE_URL_OPENMETEO,
26
+ BASE_URL_OPENMETEO_AQ,
25
27
  DEFAULT_CACHE_TIMEOUT,
26
28
  DEFAULT_CONDITION_CALM_WEIGHT,
27
29
  DEFAULT_CONDITION_CLOUDCOVER_HIGH_WEAKENING,
@@ -39,9 +41,8 @@ from pyastroweatherio.const import (
39
41
  FORECAST_TYPE_HOURLY,
40
42
  HEADERS,
41
43
  MAG_DEGRATION_MAX,
42
- SEEING,
44
+ PRECIP_MAX,
43
45
  SEEING_MAX,
44
- TRANSPARENCY,
45
46
  WIND10M_MAX,
46
47
  )
47
48
  from pyastroweatherio.dataclasses import (
@@ -64,11 +65,10 @@ from pyastroweatherio.dataclasses import (
64
65
  UpTonightDSOData,
65
66
  UpTonightDSODataModel,
66
67
  )
67
- from pyastroweatherio.errors import OpenMeteoConnectionError, OpenMeteoError, MetnoConnectionError, MetnoError
68
+ from pyastroweatherio.errors import OpenMeteoConnectionError, OpenMeteoError, MetnoConnectionError
68
69
  from pyastroweatherio.helper_functions import (
69
70
  AstronomicalRoutines,
70
71
  AtmosphericRoutines,
71
- ConversionFunctions,
72
72
  )
73
73
 
74
74
  _LOGGER = logging.getLogger(__name__)
@@ -324,11 +324,12 @@ class AstroWeather:
324
324
  if weather_df_metno is None:
325
325
  _LOGGER.warning("Could not retrieve Met.no data. Using existing data.")
326
326
  return None
327
- # Fetch uptonight (local I/O), Open-Meteo primary, and GFS supplementary in parallel
328
- uptonight_result, openmeteo_result, gfs_result = await asyncio.gather(
327
+ # Fetch uptonight (local I/O), Open-Meteo primary, GFS, and CAMS AOD in parallel
328
+ uptonight_result, openmeteo_result, gfs_result, aod_result = await asyncio.gather(
329
329
  self._retrieve_data_uptonight(),
330
330
  self._retrieve_data_openmeteo(),
331
331
  self._retrieve_data_gfs(),
332
+ self._retrieve_data_aod(),
332
333
  return_exceptions=True,
333
334
  )
334
335
 
@@ -343,6 +344,12 @@ class AstroWeather:
343
344
  else:
344
345
  weather_df_gfs = gfs_result
345
346
 
347
+ if isinstance(aod_result, BaseException):
348
+ _LOGGER.warning("Could not retrieve CAMS AOD data: %s", aod_result)
349
+ weather_df_aod = None
350
+ else:
351
+ weather_df_aod = aod_result
352
+
346
353
  # Merge the dataframes of metno and openmeteo
347
354
  self._weather_df = weather_df_metno.merge(weather_df_openmeteo, on="time", how="left")
348
355
 
@@ -380,6 +387,12 @@ class AstroWeather:
380
387
  for col in ("gfs_lifted_index", "gfs_cape", "gfs_boundary_layer_height", "gfs_visibility"):
381
388
  self._weather_df[col] = float("nan")
382
389
 
390
+ # Merge CAMS AOD data (aerosol optical depth)
391
+ if weather_df_aod is not None:
392
+ self._weather_df = self._weather_df.merge(weather_df_aod, on="time", how="left")
393
+ else:
394
+ self._weather_df["aerosol_optical_depth"] = float("nan")
395
+
383
396
  # Clean up rows with missing values
384
397
  self._weather_df = self._weather_df.dropna(subset=["air_temperature"])
385
398
  self._weather_df = self._weather_df.dropna(subset=["next_6h_symbol_code"])
@@ -468,6 +481,16 @@ class AstroWeather:
468
481
  transparency = float(row["transparency"])
469
482
  lifted_index = float(row["lifted_index"])
470
483
 
484
+ # Incorporate CAMS AOD into transparency (Bouguer-Lambert at zenith).
485
+ # AOD drives the effective transparency when aerosols cause more extinction
486
+ # than the modelled value from humidity/seeing/etc.
487
+ raw_aod = row.get("aerosol_optical_depth", float("nan"))
488
+ aod = float(raw_aod) if raw_aod is not None and not (isinstance(raw_aod, float) and math.isnan(raw_aod)) else float("nan")
489
+ if not math.isnan(aod):
490
+ aod_mag = min(aod * AOD_TO_MAG_FACTOR, MAG_DEGRATION_MAX)
491
+ transparency = max(transparency, aod_mag)
492
+ aerosol_optical_depth = aod if not math.isnan(aod) else 0.0
493
+
471
494
  # Calculate Fog Density
472
495
  if self._experimental_features:
473
496
  gfs_vis = row.get("gfs_visibility", float("nan"))
@@ -480,6 +503,11 @@ class AstroWeather:
480
503
  else:
481
504
  fog2m = await self._atmosphere.calculate_fog_density(temp2m, rh2m, dewpoint2m, wind_speed) * 100
482
505
 
506
+ # Moon position at this specific forecast timestamp (not "now")
507
+ forecast_dt = ts.to_pydatetime().replace(tzinfo=None)
508
+ moon_altitude = self._astro_routines.moon_altitude_at(forecast_dt)
509
+ moon_illuminance = self._astro_routines.moon_illuminance_at(forecast_dt)
510
+
483
511
  condition = ConditionDataModel(
484
512
  {
485
513
  "cloudcover": cloudcover,
@@ -512,6 +540,9 @@ class AstroWeather:
512
540
  "weather6": weather6,
513
541
  "precipitation_amount": precipitation_amount,
514
542
  "precipitation_amount6": precipitation_amount6,
543
+ "moon_altitude": moon_altitude,
544
+ "moon_illuminance": moon_illuminance,
545
+ "aerosol_optical_depth": aerosol_optical_depth,
515
546
  }
516
547
  )
517
548
 
@@ -546,15 +577,21 @@ class AstroWeather:
546
577
  wind_speed = WIND10M_MAX
547
578
  wind_speed_value = int(wind_speed * (100 / WIND10M_MAX)) # m/s up to 16.5
548
579
 
549
- cloudcover = []
550
- cloudcover.append(cloudcover_high * self._cloudcover_high_weakening)
551
- cloudcover.append(cloudcover_medium * self._cloudcover_medium_weakening)
552
- cloudcover.append(cloudcover_low * self._cloudcover_low_weakening)
580
+ # Combined opacity of independent cloud layers: 1 - product of transmittances.
581
+ # Weakening factors (0–1) reduce each layer's effective blocking fraction.
582
+ ch = cloudcover_high * self._cloudcover_high_weakening / 100
583
+ cm = cloudcover_medium * self._cloudcover_medium_weakening / 100
584
+ cl = cloudcover_low * self._cloudcover_low_weakening / 100
585
+ combined_cloudcover = (1 - (1 - ch) * (1 - cm) * (1 - cl)) * 100
586
+
587
+ # Precipitation penalty: capped at PRECIP_MAX (1 mm/h = fully bad) so
588
+ # heavy rain cannot push the score below 0 before the final clamp.
589
+ precip_penalty = min(precipitation_amount / PRECIP_MAX, 1.0) * 100
553
590
 
554
591
  condition = int(
555
592
  100
556
593
  - (
557
- self._cloudcover_weight * max(cloudcover)
594
+ self._cloudcover_weight * combined_cloudcover
558
595
  + self._fog_weight * max(fog, fog2m) # Use whatever is higher
559
596
  + self._seeing_weight * seeing
560
597
  + self._transparency_weight * transparency
@@ -567,7 +604,7 @@ class AstroWeather:
567
604
  + self._transparency_weight
568
605
  + self._calm_weight
569
606
  )
570
- - precipitation_amount * 100
607
+ - precip_penalty
571
608
  )
572
609
 
573
610
  # _LOGGER.debug(
@@ -1402,3 +1439,88 @@ class AstroWeather:
1402
1439
  weather_df_gfs["time"] = pd.to_datetime(weather_df_gfs["time"]).dt.tz_localize("UTC")
1403
1440
 
1404
1441
  return weather_df_gfs
1442
+
1443
+ async def _retrieve_data_aod(self) -> pd.DataFrame:
1444
+ """Fetch hourly aerosol optical depth (AOD) from CAMS via Open-Meteo Air Quality API.
1445
+
1446
+ AOD at 550 nm is a direct measure of column aerosol loading: Saharan dust,
1447
+ wildfire smoke, and volcanic ash all elevate AOD and reduce transparency.
1448
+ The value is converted to magnitude extinction via the Bouguer-Lambert law
1449
+ (mag ≈ AOD × 1.086 at zenith) in _get_condition and used to floor the
1450
+ effective transparency when aerosols cause more extinction than the
1451
+ modelled estimate from humidity / seeing / etc.
1452
+
1453
+ No API key is required; the endpoint is rate-limited for reasonable use.
1454
+ Failure is non-fatal — the AOD column is filled with NaN and the existing
1455
+ transparency model is used unchanged.
1456
+ """
1457
+ _LOGGER.debug("Updating aerosol data from CAMS via Open-Meteo AQ API")
1458
+
1459
+ use_running_session = self._session and not self._session.closed
1460
+ if use_running_session:
1461
+ session = self._session
1462
+ else:
1463
+ session = ClientSession(timeout=ClientTimeout(total=DEFAULT_TIMEOUT))
1464
+
1465
+ params = {
1466
+ "latitude": self._location_data.latitude,
1467
+ "longitude": self._location_data.longitude,
1468
+ "hourly": ["aerosol_optical_depth"],
1469
+ "timezone": "UTC",
1470
+ }
1471
+
1472
+ try:
1473
+ _LOGGER.debug(f"Query url (CAMS AOD): {BASE_URL_OPENMETEO_AQ}")
1474
+ response = await session.get(BASE_URL_OPENMETEO_AQ, params=params)
1475
+ except asyncio.TimeoutError as exception:
1476
+ _LOGGER.error(f"Timeout occurred while connecting to the Open-Meteo AQ API: {exception}")
1477
+ raise OpenMeteoConnectionError(exception) from exception
1478
+ except (
1479
+ ClientError,
1480
+ ClientResponseError,
1481
+ socket.gaierror,
1482
+ ) as exception:
1483
+ _LOGGER.error(f"Error occurred while communicating with Open-Meteo AQ API: {exception}")
1484
+ raise OpenMeteoConnectionError(exception) from exception
1485
+ finally:
1486
+ if not use_running_session:
1487
+ await session.close()
1488
+
1489
+ content_type = response.headers.get("Content-Type", "")
1490
+
1491
+ if (response.status // 100) in [4, 5]:
1492
+ if "application/json" in content_type:
1493
+ data = await response.json()
1494
+ response.close()
1495
+ if data.get("error") is True and (reason := data.get("reason")):
1496
+ raise OpenMeteoError(reason)
1497
+ raise OpenMeteoError(response.status, data)
1498
+ contents = await response.read()
1499
+ response.close()
1500
+ raise OpenMeteoError(response.status, {"message": contents.decode("utf8")})
1501
+
1502
+ text = await response.text()
1503
+ if "application/json" not in content_type:
1504
+ raise OpenMeteoError(
1505
+ "Unexpected response from the Open-Meteo AQ API",
1506
+ {"Content-Type": content_type, "response": text},
1507
+ )
1508
+
1509
+ data = await response.json()
1510
+ if self._test_mode:
1511
+ json_string = json.dumps(data)
1512
+ with open("debug/openmeteo_aod.json", "w") as outfile:
1513
+ outfile.write(json_string)
1514
+
1515
+ response.close()
1516
+ hourly = data.get("hourly")
1517
+
1518
+ hourly_data = {
1519
+ "time": np.array(hourly.get("time")),
1520
+ "aerosol_optical_depth": np.array(hourly.get("aerosol_optical_depth")),
1521
+ }
1522
+
1523
+ weather_df_aod = pd.DataFrame(data=hourly_data)
1524
+ weather_df_aod["time"] = pd.to_datetime(weather_df_aod["time"]).dt.tz_localize("UTC")
1525
+
1526
+ return weather_df_aod
@@ -4,6 +4,7 @@
4
4
  # Requests
5
5
  # #####################################################
6
6
  BASE_URL_OPENMETEO = "https://api.open-meteo.com/v1/forecast"
7
+ BASE_URL_OPENMETEO_AQ = "https://air-quality-api.open-meteo.com/v1/air-quality"
7
8
  BASE_URL_MET = "https://api.met.no/weatherapi/locationforecast/2.0/complete"
8
9
  HEADERS = {"User-Agent": "AstroWeather github.com/mawinkler/astroweather"}
9
10
 
@@ -159,6 +160,8 @@ WIND10M_PLAIN = [
159
160
  "Moderate gale",
160
161
  ]
161
162
  WIND10M_MAX = 16.5
163
+ PRECIP_MAX = 1.0 # mm/h at which precipitation fully degrades condition
164
+ AOD_TO_MAG_FACTOR = 1.086 # Bouguer-Lambert: mag extinction ≈ AOD × 1.086 at zenith
162
165
 
163
166
  # #####################################################
164
167
  # Condition
@@ -174,8 +177,7 @@ DEFAULT_CONDITION_CALM_WEIGHT = 2
174
177
  CONDITION_PLAIN = ["excellent", "good", "fair", "poor", "bad"]
175
178
  CONDITION = ["█", "▆", "▄", "▂", "▁"]
176
179
  DEEP_SKY_THRESHOLD = 75
177
- DARK_NIGHT_MAX_MOON_PHASE = 0.05
178
- DARK_NIGHT_MAX_MOON_ALT = "5:0:0"
180
+ DARK_NIGHT_MAX_ILLUMINANCE = 0.05 # max (phase_fraction × sin(altitude)) for a dark night
179
181
 
180
182
  # #####################################################
181
183
  # Astronomical constants
@@ -183,7 +185,7 @@ DARK_NIGHT_MAX_MOON_ALT = "5:0:0"
183
185
  AU_TO_KM = 149_597_870.7 # km per AU (IAU 2012)
184
186
  MOON_MEAN_DISTANCE_KM = 384_400 # mean Moon–Earth distance (km)
185
187
  MOON_MEAN_ANGULAR_SIZE_DEG = 0.5181 # mean lunar angular diameter (°)
186
- LUNAR_MONTH_DAYS = 29.33 # mean synodic month (days)
188
+ LUNAR_MONTH_DAYS = 29.53059 # mean synodic month (days)
187
189
  KELVIN_OFFSET = 273.15 # °C to K conversion
188
190
 
189
191
  # #####################################################
@@ -190,6 +190,9 @@ class ConditionDataModel(TypedDict):
190
190
  weather6: str
191
191
  precipitation_amount: float
192
192
  precipitation_amount6: float
193
+ moon_altitude: float
194
+ moon_illuminance: float
195
+ aerosol_optical_depth: float
193
196
 
194
197
 
195
198
  @typechecked
@@ -217,6 +220,9 @@ class ConditionData:
217
220
  self._weather6 = data["weather6"]
218
221
  self.precipitation_amount = data["precipitation_amount"]
219
222
  self.precipitation_amount6 = data["precipitation_amount6"]
223
+ self.moon_altitude = data["moon_altitude"]
224
+ self.moon_illuminance = data["moon_illuminance"]
225
+ self.aerosol_optical_depth = data["aerosol_optical_depth"]
220
226
 
221
227
  # #########################################################################
222
228
  # Condition
@@ -15,8 +15,7 @@ from pyastroweatherio.const import (
15
15
  ASTRONOMICAL_DUSK_DAWN,
16
16
  AU_TO_KM,
17
17
  CIVIL_DUSK_DAWN,
18
- DARK_NIGHT_MAX_MOON_ALT,
19
- DARK_NIGHT_MAX_MOON_PHASE,
18
+ DARK_NIGHT_MAX_ILLUMINANCE,
20
19
  KELVIN_OFFSET,
21
20
  LUNAR_MONTH_DAYS,
22
21
  MAG_DEGRATION_MAX,
@@ -529,6 +528,11 @@ class AtmosphericRoutines:
529
528
  on the log-scale, centred at 600 m:
530
529
  pbl_pen = sigmoid((log10(pbl) − log10(600)) / 0.35)
531
530
 
531
+ Wind weight is intentionally reduced to 5 % in this path because PBL
532
+ height already captures boundary-layer stability; keeping the full
533
+ surface-wind penalty would double-count the same physics and
534
+ over-penalise moderate winds (e.g. 6–8 m/s) on otherwise stable nights.
535
+
532
536
  Without PBL data the function falls back to a surface-only heuristic:
533
537
 
534
538
  Penalty Weight Model
@@ -617,10 +621,12 @@ class AtmosphericRoutines:
617
621
  pass
618
622
 
619
623
  if pbl is not None:
620
- # PBL-aware path: boundary layer height dominates (60 %), surface
621
- # corrections for wind and humidity provide the remaining 40 %.
624
+ # PBL-aware path: boundary layer height dominates (60 %).
625
+ # Wind weight is reduced to 5 % because PBL height already encodes
626
+ # boundary-layer stability — the surface wind penalty would otherwise
627
+ # double-count the same physics and over-penalise moderate winds.
622
628
  pbl_pen = self._sigmoid((math.log10(pbl) - math.log10(600.0)) / 0.35)
623
- quality = 1.0 - 0.60 * pbl_pen - 0.15 * wind_pen - 0.15 * humid_pen - 0.10 * cloud_pen
629
+ quality = 1.0 - 0.60 * pbl_pen - 0.05 * wind_pen - 0.25 * humid_pen - 0.10 * cloud_pen
624
630
  else:
625
631
  # Surface-only fallback
626
632
  quality = 1.0 - 0.35 * wind_pen - 0.25 * humid_pen - 0.10 * cloud_pen - 0.20 * dry_pen
@@ -1447,49 +1453,69 @@ class AstronomicalRoutines:
1447
1453
  except (ephem.AlwaysUpError, ephem.NeverUpError):
1448
1454
  return None, None
1449
1455
 
1450
- # Function to check Moon conditions for the whole night
1451
- def _is_moon_dark_whole_night(self, night_start, night_end) -> bool:
1456
+ @staticmethod
1457
+ def _moon_illuminance(alt_rad: float, phase_pct: float) -> float:
1458
+ """Return lunar illuminance proxy: phase_fraction × max(0, sin(altitude)).
1459
+
1460
+ Combines phase and altitude into a single value on [0, 1]:
1461
+ - 0 → moon invisible (below horizon or new moon)
1462
+ - 1 → full moon directly overhead
1463
+ A value below DARK_NIGHT_MAX_ILLUMINANCE indicates negligible sky glow.
1452
1464
  """
1453
- Test if Moon phase is less than 5% and/or maximum Moon altitide during
1454
- astronomical darkness is less than 5°.
1465
+ return (phase_pct / 100.0) * max(0.0, math.sin(alt_rad))
1455
1466
 
1456
- Args:
1457
- - night_start: Sun set -18°
1458
- - night_end: Sun rise -18°
1467
+ def moon_illuminance_at(self, dt: datetime) -> float:
1468
+ """Return the lunar illuminance proxy at an arbitrary UTC datetime.
1459
1469
 
1460
- Returns:
1461
- - dark_night: True, if Moon is within constraints.
1470
+ Intended for per-hour forecast calculations so that the moon's actual
1471
+ position at each forecast timestamp drives the score, not its position
1472
+ at the time the coordinator last ran.
1462
1473
  """
1463
- current_time = night_start
1474
+ if self._moon_observer is None:
1475
+ self._moon_observer = self._get_moon_observer()
1476
+ if self._moon is None:
1477
+ self._moon = ephem.Moon()
1478
+ self._moon_observer.date = dt.replace(tzinfo=None)
1479
+ self._moon.compute(self._moon_observer)
1480
+ return self._moon_illuminance(float(self._moon.alt), self._moon.phase)
1481
+
1482
+ def moon_altitude_at(self, dt: datetime) -> float:
1483
+ """Return moon altitude in degrees at an arbitrary UTC datetime."""
1484
+ if self._moon_observer is None:
1485
+ self._moon_observer = self._get_moon_observer()
1486
+ if self._moon is None:
1487
+ self._moon = ephem.Moon()
1488
+ self._moon_observer.date = dt.replace(tzinfo=None)
1489
+ self._moon.compute(self._moon_observer)
1490
+ return deg(float(self._moon.alt))
1464
1491
 
1465
- moon_alts = []
1466
- moon_phases = []
1467
- dark_night = True
1492
+ # Function to check Moon conditions for the whole night
1493
+ def _is_moon_dark_whole_night(self, night_start, night_end) -> bool:
1494
+ """Return True if the night qualifies as a dark night.
1495
+
1496
+ Uses an integrated lunar illuminance proxy instead of independent
1497
+ phase / altitude thresholds. The proxy is:
1498
+ illuminance = (phase / 100) × max(0, sin(altitude_radians))
1499
+ A night is dark when the peak illuminance over the whole night stays
1500
+ below DARK_NIGHT_MAX_ILLUMINANCE, which avoids the edge cases of the
1501
+ previous approach (e.g. a full moon 3° above the horizon being accepted
1502
+ because its altitude was below the 5° threshold).
1503
+ """
1504
+ current_time = night_start
1505
+ peak_illuminance = 0.0
1468
1506
 
1469
1507
  while current_time <= night_end:
1470
1508
  self._moon_observer.date = current_time
1471
1509
  moon = ephem.Moon(self._moon_observer)
1472
-
1473
- moon_alt = moon.alt
1474
- moon_alts.append(moon_alt)
1475
- moon_phase = moon.phase # Moon phase in percentage
1476
- moon_phases.append(moon_phase)
1477
-
1478
- # If at any point the Moon is above horizon and > 10% illuminated, return False
1479
- if moon_alt > ephem.degrees(DARK_NIGHT_MAX_MOON_ALT): # and moon_phase >= DARK_NIGHT_MAX_MOON_PHASE * 10:
1480
- dark_night = False
1481
- break
1482
-
1483
- # Step in time (e.g., every 15 minutes)
1510
+ illuminance = self._moon_illuminance(float(moon.alt), moon.phase)
1511
+ if illuminance > peak_illuminance:
1512
+ peak_illuminance = illuminance
1484
1513
  current_time += timedelta(minutes=5)
1485
1514
 
1486
- moon_phases_avg = sum(moon_phases) / len(moon_phases)
1487
- if dark_night or moon_phases_avg <= DARK_NIGHT_MAX_MOON_PHASE * 10:
1488
- _LOGGER.debug(
1489
- f"Next dark night: {night_start.strftime("%Y-%m-%d")}, Altidudes min/max: {min(moon_alts)}/{max(moon_alts)}, Phase mix/max: {min(moon_phases):.2f}/{max(moon_phases):.2f}%"
1490
- )
1491
- else:
1492
- dark_night = False
1515
+ dark_night = peak_illuminance <= DARK_NIGHT_MAX_ILLUMINANCE
1516
+ _LOGGER.debug(
1517
+ f"Night {night_start.strftime('%Y-%m-%d')}: peak illuminance {peak_illuminance:.4f} → dark_night={dark_night}"
1518
+ )
1493
1519
  return dark_night
1494
1520
 
1495
1521
  def _next_dark_night(self) -> None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyastroweatherio
3
- Version: 0.76.0.dev1
3
+ Version: 0.76.0.dev3
4
4
  Summary: Python Wrapper for OpenMeteo and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -11,7 +11,7 @@ if os.path.isfile(requirement_path):
11
11
  setup(
12
12
  name="pyastroweatherio",
13
13
  packages=["pyastroweatherio"],
14
- version="0.76.0.dev1",
14
+ version="0.76.0.dev3",
15
15
  license="MIT",
16
16
  description="Python Wrapper for OpenMeteo and Met.no REST API",
17
17
  long_description=" ".join(