pyastroweatherio 0.76.0.dev2__tar.gz → 0.76.0.dev4__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.dev2 → pyastroweatherio-0.76.0.dev4}/PKG-INFO +1 -1
  2. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/client.py +205 -108
  3. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/const.py +17 -15
  4. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/dataclasses.py +6 -0
  5. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/helper_functions.py +54 -303
  6. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio.egg-info/PKG-INFO +1 -1
  7. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/setup.py +1 -1
  8. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/tests/test_calculations.py +14 -108
  9. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/LICENSE +0 -0
  10. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/README.md +0 -0
  11. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/__init__.py +0 -0
  12. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio/errors.py +0 -0
  13. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio.egg-info/SOURCES.txt +0 -0
  14. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio.egg-info/dependency_links.txt +0 -0
  15. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio.egg-info/requires.txt +0 -0
  16. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/pyastroweatherio.egg-info/top_level.txt +0 -0
  17. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/setup.cfg +0 -0
  18. {pyastroweatherio-0.76.0.dev2 → pyastroweatherio-0.76.0.dev4}/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.dev2
3
+ Version: 0.76.0.dev4
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__)
@@ -152,7 +152,7 @@ class AstroWeather:
152
152
 
153
153
  if self._experimental_features:
154
154
  _LOGGER.debug(
155
- "Using experimental features for Seeing, Magnitude Degradation, Lifted Index, and Fog Density"
155
+ "experimental_features is set but no longer has any effect — improved calculations are now always active"
156
156
  )
157
157
 
158
158
  # Testing
@@ -198,76 +198,48 @@ class AstroWeather:
198
198
  return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Dew point calculation failed: %s", r) or float("nan")) for r in results]
199
199
 
200
200
  async def _calculate_seeing(self, df):
201
- if self._experimental_features:
202
- has_pbl = "gfs_boundary_layer_height" in df.columns
203
- tasks = [
204
- self._atmosphere.calculate_seeing_11(
205
- temperature=row["air_temperature"],
206
- humidity=row["relative_humidity"],
207
- dew_point_temperature=row["dew_point_temperature"],
208
- wind_speed=row["wind_speed"],
209
- cloud_cover=row["cloud_area_fraction"],
210
- altitude=self._location_data.elevation,
211
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
212
- boundary_layer_height=row["gfs_boundary_layer_height"] if has_pbl else None,
213
- )
214
- for _, row in df.iterrows()
215
- ]
216
- else:
217
- tasks = [
218
- self._atmosphere.calculate_seeing(
219
- temperature=row["air_temperature"],
220
- humidity=row["relative_humidity"],
221
- dew_point_temperature=row["dew_point_temperature"],
222
- wind_speed=row["wind_speed"],
223
- cloud_cover=row["cloud_area_fraction"],
224
- altitude=self._location_data.elevation,
225
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
226
- )
227
- for _, row in df.iterrows()
228
- ]
201
+ has_pbl = "gfs_boundary_layer_height" in df.columns
202
+ tasks = [
203
+ self._atmosphere.calculate_seeing(
204
+ temperature=row["air_temperature"],
205
+ humidity=row["relative_humidity"],
206
+ dew_point_temperature=row["dew_point_temperature"],
207
+ wind_speed=row["wind_speed"],
208
+ cloud_cover=row["cloud_area_fraction"],
209
+ altitude=self._location_data.elevation,
210
+ air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
211
+ boundary_layer_height=row["gfs_boundary_layer_height"] if has_pbl else None,
212
+ )
213
+ for _, row in df.iterrows()
214
+ ]
229
215
  results = await asyncio.gather(*tasks, return_exceptions=True)
230
216
  return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Seeing calculation failed: %s", r) or float("nan")) for r in results]
231
217
 
232
218
  async def _calculate_transparency(self, df):
233
- if self._experimental_features:
234
- tasks = [
235
- self._atmosphere.magnitude_degradation_11(
236
- temperature=row["air_temperature"],
237
- humidity=row["relative_humidity"],
238
- dew_point_temperature=row["dew_point_temperature"],
239
- wind_speed=row["wind_speed"],
240
- cloud_cover=row["cloud_area_fraction"],
241
- altitude=self._location_data.elevation,
242
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
243
- )
244
- for _, row in df.iterrows()
245
- ]
246
- else:
247
- tasks = [
248
- self._atmosphere.magnitude_degradation(
249
- temperature=row["air_temperature"],
250
- humidity=row["relative_humidity"],
251
- dew_point_temperature=row["dew_point_temperature"],
252
- wind_speed=row["wind_speed"],
253
- cloud_cover=row["cloud_area_fraction"],
254
- altitude=self._location_data.elevation,
255
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
256
- )
257
- for _, row in df.iterrows()
258
- ]
219
+ tasks = [
220
+ self._atmosphere.magnitude_degradation(
221
+ temperature=row["air_temperature"],
222
+ humidity=row["relative_humidity"],
223
+ dew_point_temperature=row["dew_point_temperature"],
224
+ wind_speed=row["wind_speed"],
225
+ cloud_cover=row["cloud_area_fraction"],
226
+ altitude=self._location_data.elevation,
227
+ air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
228
+ )
229
+ for _, row in df.iterrows()
230
+ ]
259
231
  results = await asyncio.gather(*tasks, return_exceptions=True)
260
232
  return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Transparency calculation failed: %s", r) or float("nan")) for r in results]
261
233
 
262
234
  async def _calculate_lifted_index(self, df):
263
- if self._experimental_features and "gfs_lifted_index" in df.columns:
264
- # Use NWP model output from GFS; fall back to Bolton approximation for any missing values
235
+ # Prefer GFS NWP output; Bolton _11 approximation fills any missing slots.
236
+ if "gfs_lifted_index" in df.columns:
265
237
  results = []
266
238
  fallback_idx = [i for i, (_, row) in enumerate(df.iterrows()) if pd.isna(row["gfs_lifted_index"])]
267
239
  if fallback_idx:
268
240
  fallback_rows = df.iloc[fallback_idx]
269
241
  fallback_tasks = [
270
- self._atmosphere.calculate_lifted_index_11(
242
+ self._atmosphere.calculate_lifted_index(
271
243
  temperature=row["air_temperature"],
272
244
  dew_point_temperature=row["dew_point_temperature"],
273
245
  altitude=self._location_data.elevation,
@@ -286,26 +258,15 @@ class AstroWeather:
286
258
  r = fallback_map.get(i)
287
259
  results.append(r if not isinstance(r, BaseException) else float("nan"))
288
260
  return results
289
- if self._experimental_features:
290
- tasks = [
291
- self._atmosphere.calculate_lifted_index_11(
292
- temperature=row["air_temperature"],
293
- dew_point_temperature=row["dew_point_temperature"],
294
- altitude=self._location_data.elevation,
295
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
296
- )
297
- for _, row in df.iterrows()
298
- ]
299
- else:
300
- tasks = [
301
- self._atmosphere.calculate_lifted_index(
302
- temperature=row["air_temperature"],
303
- dew_point_temperature=row["dew_point_temperature"],
304
- altitude=self._location_data.elevation,
305
- air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
306
- )
307
- for _, row in df.iterrows()
308
- ]
261
+ tasks = [
262
+ self._atmosphere.calculate_lifted_index(
263
+ temperature=row["air_temperature"],
264
+ dew_point_temperature=row["dew_point_temperature"],
265
+ altitude=self._location_data.elevation,
266
+ air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
267
+ )
268
+ for _, row in df.iterrows()
269
+ ]
309
270
  results = await asyncio.gather(*tasks, return_exceptions=True)
310
271
  return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Lifted index calculation failed: %s", r) or float("nan")) for r in results]
311
272
 
@@ -324,11 +285,12 @@ class AstroWeather:
324
285
  if weather_df_metno is None:
325
286
  _LOGGER.warning("Could not retrieve Met.no data. Using existing data.")
326
287
  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(
288
+ # Fetch uptonight (local I/O), Open-Meteo primary, GFS, and CAMS AOD in parallel
289
+ uptonight_result, openmeteo_result, gfs_result, aod_result = await asyncio.gather(
329
290
  self._retrieve_data_uptonight(),
330
291
  self._retrieve_data_openmeteo(),
331
292
  self._retrieve_data_gfs(),
293
+ self._retrieve_data_aod(),
332
294
  return_exceptions=True,
333
295
  )
334
296
 
@@ -343,6 +305,12 @@ class AstroWeather:
343
305
  else:
344
306
  weather_df_gfs = gfs_result
345
307
 
308
+ if isinstance(aod_result, BaseException):
309
+ _LOGGER.warning("Could not retrieve CAMS AOD data: %s", aod_result)
310
+ weather_df_aod = None
311
+ else:
312
+ weather_df_aod = aod_result
313
+
346
314
  # Merge the dataframes of metno and openmeteo
347
315
  self._weather_df = weather_df_metno.merge(weather_df_openmeteo, on="time", how="left")
348
316
 
@@ -380,6 +348,12 @@ class AstroWeather:
380
348
  for col in ("gfs_lifted_index", "gfs_cape", "gfs_boundary_layer_height", "gfs_visibility"):
381
349
  self._weather_df[col] = float("nan")
382
350
 
351
+ # Merge CAMS AOD data (aerosol optical depth)
352
+ if weather_df_aod is not None:
353
+ self._weather_df = self._weather_df.merge(weather_df_aod, on="time", how="left")
354
+ else:
355
+ self._weather_df["aerosol_optical_depth"] = float("nan")
356
+
383
357
  # Clean up rows with missing values
384
358
  self._weather_df = self._weather_df.dropna(subset=["air_temperature"])
385
359
  self._weather_df = self._weather_df.dropna(subset=["next_6h_symbol_code"])
@@ -468,18 +442,30 @@ class AstroWeather:
468
442
  transparency = float(row["transparency"])
469
443
  lifted_index = float(row["lifted_index"])
470
444
 
471
- # Calculate Fog Density
472
- if self._experimental_features:
473
- gfs_vis = row.get("gfs_visibility", float("nan"))
474
- gfs_vis = float(gfs_vis) if gfs_vis is not None else float("nan")
475
- if not math.isnan(gfs_vis):
476
- # Map GFS visibility (m) to fog density [0, 1]: 0 m = dense fog, ≥10 km = clear
477
- fog2m = max(0.0, min(100.0, (1.0 - gfs_vis / 10000.0) * 100.0))
478
- else:
479
- fog2m = await self._atmosphere.calculate_fog_density_11(temp2m, rh2m, dewpoint2m, wind_speed) * 100
445
+ # Incorporate CAMS AOD into transparency (Bouguer-Lambert at zenith).
446
+ # AOD drives the effective transparency when aerosols cause more extinction
447
+ # than the modelled value from humidity/seeing/etc.
448
+ raw_aod = row.get("aerosol_optical_depth", float("nan"))
449
+ aod = float(raw_aod) if raw_aod is not None and not (isinstance(raw_aod, float) and math.isnan(raw_aod)) else float("nan")
450
+ if not math.isnan(aod):
451
+ aod_mag = min(aod * AOD_TO_MAG_FACTOR, MAG_DEGRATION_MAX)
452
+ transparency = max(transparency, aod_mag)
453
+ aerosol_optical_depth = aod if not math.isnan(aod) else 0.0
454
+
455
+ # Calculate Fog Density: GFS visibility takes priority when available.
456
+ gfs_vis = row.get("gfs_visibility", float("nan"))
457
+ gfs_vis = float(gfs_vis) if gfs_vis is not None else float("nan")
458
+ if not math.isnan(gfs_vis):
459
+ # Map GFS visibility (m) to fog density [0, 1]: 0 m = dense fog, ≥10 km = clear
460
+ fog2m = max(0.0, min(100.0, (1.0 - gfs_vis / 10000.0) * 100.0))
480
461
  else:
481
462
  fog2m = await self._atmosphere.calculate_fog_density(temp2m, rh2m, dewpoint2m, wind_speed) * 100
482
463
 
464
+ # Moon position at this specific forecast timestamp (not "now")
465
+ forecast_dt = ts.to_pydatetime().replace(tzinfo=None)
466
+ moon_altitude = self._astro_routines.moon_altitude_at(forecast_dt)
467
+ moon_illuminance = self._astro_routines.moon_illuminance_at(forecast_dt)
468
+
483
469
  condition = ConditionDataModel(
484
470
  {
485
471
  "cloudcover": cloudcover,
@@ -512,6 +498,9 @@ class AstroWeather:
512
498
  "weather6": weather6,
513
499
  "precipitation_amount": precipitation_amount,
514
500
  "precipitation_amount6": precipitation_amount6,
501
+ "moon_altitude": moon_altitude,
502
+ "moon_illuminance": moon_illuminance,
503
+ "aerosol_optical_depth": aerosol_optical_depth,
515
504
  }
516
505
  )
517
506
 
@@ -537,8 +526,20 @@ class AstroWeather:
537
526
  ) -> int:
538
527
  """Return condition based on cloud cover, fog, seeing, transparency, wind speed, and precipitation."""
539
528
 
529
+ # Guard against NaN from failed atmospheric calculations.
530
+ # Seeing and transparency use worst-case so a data gap never produces an
531
+ # optimistic score; fog defaults to 0 (unknown ≠ foggy).
532
+ if math.isnan(seeing):
533
+ seeing = SEEING_MAX
534
+ if math.isnan(transparency):
535
+ transparency = MAG_DEGRATION_MAX
536
+ if math.isnan(fog):
537
+ fog = 0.0
538
+ if math.isnan(fog2m):
539
+ fog2m = 0.0
540
+
540
541
  # Seeing is something in between 0 and 2.5 arcsecs
541
- seeing = seeing * 100 / SEEING_MAX # arcsecs up to 2.5
542
+ seeing = seeing * 100 / SEEING_MAX # arcsecs up to 4.0
542
543
  # transparency = int(transparency * 40) # mag degration up to 2.5
543
544
  transparency = transparency * 100 / MAG_DEGRATION_MAX # mag degration up to MAG_DEGRATION_MAX
544
545
  # Wind speed is something in between 0 and 16.5 m/s
@@ -546,28 +547,39 @@ class AstroWeather:
546
547
  wind_speed = WIND10M_MAX
547
548
  wind_speed_value = int(wind_speed * (100 / WIND10M_MAX)) # m/s up to 16.5
548
549
 
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)
550
+ # Combined opacity of independent cloud layers: 1 - product of transmittances.
551
+ # Weakening factors (0–1) reduce each layer's effective blocking fraction.
552
+ ch = cloudcover_high * self._cloudcover_high_weakening / 100
553
+ cm = cloudcover_medium * self._cloudcover_medium_weakening / 100
554
+ cl = cloudcover_low * self._cloudcover_low_weakening / 100
555
+ combined_cloudcover = (1 - (1 - ch) * (1 - cm) * (1 - cl)) * 100
556
+
557
+ # Precipitation penalty: capped at PRECIP_MAX (1 mm/h = fully bad) so
558
+ # heavy rain cannot push the score below 0 before the final clamp.
559
+ precip_penalty = min(precipitation_amount / PRECIP_MAX, 1.0) * 100
560
+
561
+ total_weight = (
562
+ self._cloudcover_weight
563
+ + self._fog_weight
564
+ + self._seeing_weight
565
+ + self._transparency_weight
566
+ + self._calm_weight
567
+ )
568
+ if total_weight == 0:
569
+ _LOGGER.warning("All condition weights are zero; returning 0")
570
+ return 0
553
571
 
554
572
  condition = int(
555
573
  100
556
574
  - (
557
- self._cloudcover_weight * max(cloudcover)
575
+ self._cloudcover_weight * combined_cloudcover
558
576
  + self._fog_weight * max(fog, fog2m) # Use whatever is higher
559
577
  + self._seeing_weight * seeing
560
578
  + self._transparency_weight * transparency
561
579
  + self._calm_weight * wind_speed_value
562
580
  )
563
- / (
564
- self._cloudcover_weight
565
- + self._fog_weight
566
- + self._seeing_weight
567
- + self._transparency_weight
568
- + self._calm_weight
569
- )
570
- - precipitation_amount * 100
581
+ / total_weight
582
+ - precip_penalty
571
583
  )
572
584
 
573
585
  # _LOGGER.debug(
@@ -1402,3 +1414,88 @@ class AstroWeather:
1402
1414
  weather_df_gfs["time"] = pd.to_datetime(weather_df_gfs["time"]).dt.tz_localize("UTC")
1403
1415
 
1404
1416
  return weather_df_gfs
1417
+
1418
+ async def _retrieve_data_aod(self) -> pd.DataFrame:
1419
+ """Fetch hourly aerosol optical depth (AOD) from CAMS via Open-Meteo Air Quality API.
1420
+
1421
+ AOD at 550 nm is a direct measure of column aerosol loading: Saharan dust,
1422
+ wildfire smoke, and volcanic ash all elevate AOD and reduce transparency.
1423
+ The value is converted to magnitude extinction via the Bouguer-Lambert law
1424
+ (mag ≈ AOD × 1.086 at zenith) in _get_condition and used to floor the
1425
+ effective transparency when aerosols cause more extinction than the
1426
+ modelled estimate from humidity / seeing / etc.
1427
+
1428
+ No API key is required; the endpoint is rate-limited for reasonable use.
1429
+ Failure is non-fatal — the AOD column is filled with NaN and the existing
1430
+ transparency model is used unchanged.
1431
+ """
1432
+ _LOGGER.debug("Updating aerosol data from CAMS via Open-Meteo AQ API")
1433
+
1434
+ use_running_session = self._session and not self._session.closed
1435
+ if use_running_session:
1436
+ session = self._session
1437
+ else:
1438
+ session = ClientSession(timeout=ClientTimeout(total=DEFAULT_TIMEOUT))
1439
+
1440
+ params = {
1441
+ "latitude": self._location_data.latitude,
1442
+ "longitude": self._location_data.longitude,
1443
+ "hourly": ["aerosol_optical_depth"],
1444
+ "timezone": "UTC",
1445
+ }
1446
+
1447
+ try:
1448
+ _LOGGER.debug(f"Query url (CAMS AOD): {BASE_URL_OPENMETEO_AQ}")
1449
+ response = await session.get(BASE_URL_OPENMETEO_AQ, params=params)
1450
+ except asyncio.TimeoutError as exception:
1451
+ _LOGGER.error(f"Timeout occurred while connecting to the Open-Meteo AQ API: {exception}")
1452
+ raise OpenMeteoConnectionError(exception) from exception
1453
+ except (
1454
+ ClientError,
1455
+ ClientResponseError,
1456
+ socket.gaierror,
1457
+ ) as exception:
1458
+ _LOGGER.error(f"Error occurred while communicating with Open-Meteo AQ API: {exception}")
1459
+ raise OpenMeteoConnectionError(exception) from exception
1460
+ finally:
1461
+ if not use_running_session:
1462
+ await session.close()
1463
+
1464
+ content_type = response.headers.get("Content-Type", "")
1465
+
1466
+ if (response.status // 100) in [4, 5]:
1467
+ if "application/json" in content_type:
1468
+ data = await response.json()
1469
+ response.close()
1470
+ if data.get("error") is True and (reason := data.get("reason")):
1471
+ raise OpenMeteoError(reason)
1472
+ raise OpenMeteoError(response.status, data)
1473
+ contents = await response.read()
1474
+ response.close()
1475
+ raise OpenMeteoError(response.status, {"message": contents.decode("utf8")})
1476
+
1477
+ text = await response.text()
1478
+ if "application/json" not in content_type:
1479
+ raise OpenMeteoError(
1480
+ "Unexpected response from the Open-Meteo AQ API",
1481
+ {"Content-Type": content_type, "response": text},
1482
+ )
1483
+
1484
+ data = await response.json()
1485
+ if self._test_mode:
1486
+ json_string = json.dumps(data)
1487
+ with open("debug/openmeteo_aod.json", "w") as outfile:
1488
+ outfile.write(json_string)
1489
+
1490
+ response.close()
1491
+ hourly = data.get("hourly")
1492
+
1493
+ hourly_data = {
1494
+ "time": np.array(hourly.get("time")),
1495
+ "aerosol_optical_depth": np.array(hourly.get("aerosol_optical_depth")),
1496
+ }
1497
+
1498
+ weather_df_aod = pd.DataFrame(data=hourly_data)
1499
+ weather_df_aod["time"] = pd.to_datetime(weather_df_aod["time"]).dt.tz_localize("UTC")
1500
+
1501
+ 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
 
@@ -45,18 +46,18 @@ ASTRONOMICAL_DUSK_DAWN = -18
45
46
  # #####################################################
46
47
  # Seeing
47
48
  # #####################################################
48
- SEEING = [0.25, 0.625, 0.875, 1.125, 1.375, 1.75, 2.25, 2.5]
49
+ SEEING = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
49
50
  # SEEING_PLAIN = [
50
51
  # 'Below 0.5"',
51
- # '0.5 to 0.75"',
52
- # '0.75 to 1"',
53
- # '1 to 1.25"',
54
- # '1.25 to 1.5"',
55
- # '1.5 to 2"',
56
- # '2 to 2.5"',
57
- # 'Over 2.5"',
52
+ # '0.5 to 1.0"',
53
+ # '1.0 to 1.5"',
54
+ # '1.5 to 2.0"',
55
+ # '2.0 to 2.5"',
56
+ # '2.5 to 3.0"',
57
+ # '3.0 to 3.5"',
58
+ # 'Over 3.5"',
58
59
  # ]
59
- SEEING_MAX = 2.5
60
+ SEEING_MAX = 4.0
60
61
 
61
62
  # #####################################################
62
63
  # Transparency
@@ -159,14 +160,16 @@ 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
165
168
  # #####################################################
166
169
  DEFAULT_CONDITION_CLOUDCOVER_WEIGHT = 3
167
- DEFAULT_CONDITION_CLOUDCOVER_HIGH_WEAKENING = 1
168
- DEFAULT_CONDITION_CLOUDCOVER_MEDIUM_WEAKENING = 1
169
- DEFAULT_CONDITION_CLOUDCOVER_LOW_WEAKENING = 1
170
+ DEFAULT_CONDITION_CLOUDCOVER_HIGH_WEAKENING = 0.40 # cirrus is largely transparent
171
+ DEFAULT_CONDITION_CLOUDCOVER_MEDIUM_WEAKENING = 0.70 # altocumulus is semi-opaque
172
+ DEFAULT_CONDITION_CLOUDCOVER_LOW_WEAKENING = 1.00 # stratus/fog blocks fully
170
173
  DEFAULT_CONDITION_FOG_WEIGHT = 3
171
174
  DEFAULT_CONDITION_SEEING_WEIGHT = 2
172
175
  DEFAULT_CONDITION_TRANSPARENCY_WEIGHT = 1
@@ -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,
@@ -117,56 +116,6 @@ class AtmosphericRoutines:
117
116
  @typechecked
118
117
  async def calculate_lifted_index(
119
118
  self, temperature, altitude, dew_point_temperature, air_pressure_at_sea_level
120
- ) -> None | float:
121
- """Calculate atmospheric lifted index."""
122
- # https://en.wikipedia.org/wiki/Lifted_index
123
-
124
- values = {
125
- "temperature": temperature,
126
- "altitude": altitude,
127
- "dew_point_temperature": dew_point_temperature,
128
- "air_pressure_at_sea_level": air_pressure_at_sea_level,
129
- }
130
-
131
- missing = [name for name, val in values.items() if val is None or (isinstance(val, float) and math.isnan(val))]
132
-
133
- if missing:
134
- _LOGGER.warning(f"calculate_lifted_index: The following variables are None or NaN: {', '.join(missing)}")
135
- return None
136
-
137
- env_temp_500mb = -20.0 # °C, approximate environmental temperature at 500 hPa
138
-
139
- # Calculate saturation vapor pressure at surface temperature
140
- # Checked with https://www.weather.gov/epz/wxcalc_vaporpressure
141
- # es = self._calculate_vapor_pressure(temperature)
142
-
143
- # Calculate actual Vapor Pressure at surface
144
- # Checked with https://www.weather.gov/epz/wxcalc_vaporpressure
145
- e = self._calculate_vapor_pressure(dew_point_temperature)
146
-
147
- # Calculate Mixing Ratio at Surface in grams per kilogram
148
- # Checked with https://www.weather.gov/epz/wxcalc_mixingratio
149
- w = self._calculate_mixing_ratio(e, air_pressure_at_sea_level)
150
-
151
- # Calculate Lifting Condensation Level
152
- lcl = self._calculate_lifting_condensation_level(w, air_pressure_at_sea_level)
153
-
154
- # Calculate temperature of lifted parcel at 500 mb level
155
- lifted_temp_500mb = (
156
- env_temp_500mb + (temperature - lcl) * 0.5
157
- ) # Assumption: 500 mb is halfway through the troposphere
158
-
159
- # Calculate Lifted Index
160
- lifted_index = (env_temp_500mb - lifted_temp_500mb) * 2 + 7
161
-
162
- # Ensure lifted index is within the valid range [-7, 7]
163
- lifted_index = max(-7, min(7, lifted_index))
164
-
165
- return lifted_index
166
-
167
- @typechecked
168
- async def calculate_lifted_index_11(
169
- self, temperature, altitude, dew_point_temperature, air_pressure_at_sea_level
170
119
  ) -> None | float:
171
120
  """
172
121
  Returns a rough Lifted Index (LI) proxy in °C, clamped to [-7, +7].
@@ -251,92 +200,10 @@ class AtmosphericRoutines:
251
200
  return LI
252
201
 
253
202
  # #####################################################
254
- # Calculate magniture degradation based on transparency
255
- #
256
- # Version _11:
257
- # Extinction coefficient k (mag/airmass)
258
- # Use pressure-scaled Rayleigh and an aerosol term
203
+ # Calculate magnitude degradation based on transparency
259
204
  # #####################################################
260
205
  @typechecked
261
206
  async def magnitude_degradation(
262
- self,
263
- temperature,
264
- humidity,
265
- cloud_cover,
266
- wind_speed,
267
- altitude,
268
- dew_point_temperature,
269
- air_pressure_at_sea_level,
270
- ) -> None | float:
271
- """
272
- Calculates the magnitude_degradation of the atmosphere.
273
- This algorithm first calculates the lifted index and the seeing and uses them to calculate
274
- the transparency from which the magnitude degradation is derived from.
275
-
276
- Args:
277
- - temperature: Surface temperature in Celsius.
278
- - humidity: Humidity in Percent.
279
- - dew_point_temperature: Dew point temperature in Celsius.
280
- - wind_speed: Wind speed in meters per second.
281
- - altitude: Altitude in meters.
282
- - air_pressure_at_sea_level: Air pressure at sea level.
283
- - cloud_cover: Cloud cover in Percent.
284
- - lifted_index:
285
- - seeing:
286
-
287
- Returns:
288
- - magnitude_degradation: In magnitude
289
- """
290
-
291
- values = {
292
- "temperature": temperature,
293
- "humidity": humidity,
294
- "cloud_cover": cloud_cover,
295
- "wind_speed": wind_speed,
296
- "altitude": altitude,
297
- "dew_point_temperature": dew_point_temperature,
298
- "air_pressure_at_sea_level": air_pressure_at_sea_level,
299
- }
300
-
301
- missing = [name for name, val in values.items() if val is None or (isinstance(val, float) and math.isnan(val))]
302
-
303
- if missing:
304
- _LOGGER.warning(f"magnitude_degradation: The following variables are None or NaN: {', '.join(missing)}")
305
- return None
306
-
307
- lifted_index = await self.calculate_lifted_index(
308
- temperature, altitude, dew_point_temperature, air_pressure_at_sea_level
309
- )
310
- seeing = await self.calculate_seeing(
311
- temperature,
312
- humidity,
313
- dew_point_temperature,
314
- wind_speed,
315
- cloud_cover,
316
- altitude,
317
- air_pressure_at_sea_level,
318
- )
319
-
320
- # Calculate transparency
321
- transparency = self._calculate_transparency(
322
- humidity,
323
- temperature,
324
- cloud_cover,
325
- wind_speed,
326
- altitude,
327
- dew_point_temperature,
328
- air_pressure_at_sea_level,
329
- lifted_index,
330
- seeing,
331
- )
332
-
333
- # Convert transparency to magnitude degradation
334
- magnitude_degradation = self._transparency_to_magnitude_degradation(transparency)
335
-
336
- return magnitude_degradation
337
-
338
- @typechecked
339
- async def magnitude_degradation_11(
340
207
  self, temperature, humidity, cloud_cover, wind_speed, altitude, dew_point_temperature, air_pressure_at_sea_level
341
208
  ) -> None | float:
342
209
  """
@@ -434,88 +301,9 @@ class AtmosphericRoutines:
434
301
 
435
302
  # #####################################################
436
303
  # Calculate atmospheric seeing
437
- #
438
- # Version _11:
439
- # A more physical way is to estimate optical turbulence C2,n(z)
440
- # with the Hufnagel–Valley 5/7 profile, integrate to get r0,
441
- # then ϵ≈0.98λ/r.
442
304
  # #####################################################
443
305
  @typechecked
444
306
  async def calculate_seeing(
445
- self,
446
- temperature,
447
- humidity,
448
- dew_point_temperature,
449
- wind_speed,
450
- cloud_cover,
451
- altitude,
452
- air_pressure_at_sea_level,
453
- ) -> None | float:
454
- """
455
- Calculated seeing of the atmosphere. This algorithm first calculates the seeing factor based on temperature,
456
- humidity, wind speed and altitude above sea level. The seeing factor is then used to calculate the astronomical
457
- seeing in arcseconds. The empirical relationship used here states that the seeing in arcseconds is approximately
458
- equal to the reciprocal of the seeing factor multiplied by a conversion factor of 0.98.
459
-
460
- Used by: magnitude degradation
461
-
462
- Args:
463
- - temperature: Surface temperature in Celsius.
464
- - humidity: Humidity in Percent.
465
- - dew_point_temperature: Dew point temperature in Celsius.
466
- - wind_speed: Wind speed in meters per second.
467
- - cloud_cover: Cloud cover in Percent.
468
- - altitude: Altitude in meters.
469
- - air_pressure_at_sea_level: Air pressure at sea level.
470
-
471
- Returns:
472
- - seeing: In arcsecs
473
-
474
- Flow:
475
- - _calculate_water_vapor_pressure
476
- - adjusted_pressure
477
- - relative_pressure
478
- - seeing_factor
479
- - seeing
480
- """
481
-
482
- values = {
483
- "temperature": temperature,
484
- "humidity": humidity,
485
- "dew_point_temperature": dew_point_temperature,
486
- "wind_speed": wind_speed,
487
- "cloud_cover": cloud_cover,
488
- "altitude": altitude,
489
- "air_pressure_at_sea_level": air_pressure_at_sea_level,
490
- }
491
-
492
- missing = [name for name, val in values.items() if val is None or (isinstance(val, float) and math.isnan(val))]
493
-
494
- if missing:
495
- _LOGGER.warning(f"calculate_seeing: The following variables are None or NaN: {', '.join(missing)}")
496
- return None
497
-
498
- # Constants
499
- C = 6.5 # 1.7
500
-
501
- water_vapor_pressure = self._calculate_water_vapor_pressure(dew_point_temperature, humidity)
502
-
503
- # adjusted_pressure = air_pressure_at_sea_level * math.exp(-0.00012 * altitude)
504
- adjusted_pressure = self._calculate_adjusted_pressure(air_pressure_at_sea_level, altitude)
505
- relative_pressure = adjusted_pressure / air_pressure_at_sea_level
506
-
507
- if wind_speed == 0:
508
- wind_speed = 0.01
509
- seeing_factor = C * (water_vapor_pressure / 10) ** 0.25 * (wind_speed / 10) ** 0.75 * relative_pressure
510
- seeing = 0.98 / seeing_factor
511
-
512
- if seeing > SEEING_MAX:
513
- seeing = SEEING_MAX # max out seeing
514
-
515
- return seeing
516
-
517
- @typechecked
518
- async def calculate_seeing_11(
519
307
  self, temperature, humidity, dew_point_temperature, wind_speed, cloud_cover, altitude, air_pressure_at_sea_level,
520
308
  boundary_layer_height=None,
521
309
  ) -> None | float:
@@ -651,66 +439,9 @@ class AtmosphericRoutines:
651
439
 
652
440
  # #####################################################
653
441
  # Calculate fog density at 2m
654
- #
655
- # Version _11:
656
- # Tie to physics and aviation practice, estimate meteorological visibility
657
- # V and then map it to a “fog density” in [0,1].
658
- # anchor the metric to visibility vs extinction, a standard framework (Koschmieder).
659
- # It’s still simple but behaves correctly near saturation and with wind
660
- # Uses Koschmieder law: V = 3.912/betaext where betaext is the extinction coefficient
661
442
  # #####################################################
662
443
  @typechecked
663
444
  async def calculate_fog_density(self, temp2m, rh2m, dewpoint2m, wind_speed) -> float:
664
- """
665
- To calculate fog density, one can use a method based on the Liquid Water Content (LWC)
666
- in fog, which depends on the difference between air temperature and dew point, relative
667
- humidity, and wind speed. While there is no universally agreed-upon formula for fog
668
- density, the implemented approximate method can provide a rough measure.
669
- Note that actual fog density can be influenced by more complex microclimatic factors,
670
- so this approach serves as a simplified approximation.
671
-
672
- Args:
673
- - temp2m: Surface temperature in Celsius.
674
- - rh2m: Humidity in Percent.
675
- - dewpoint2m: Dew point temperature in Celsius.
676
- - wind_speed: Wind speed in meters per second.
677
-
678
- Returns:
679
- - adjusted_fog_density
680
- """
681
-
682
- # Constants
683
- # A normalizing constant chosen empirically to scale the fog density to a reasonable
684
- # range. Adjust this based on the desired scale of output (e.g., 0.1 for very light
685
- # fog, 1 for dense fog).
686
- k = 0.50
687
-
688
- # Controls how sensitive the density calculation is to the temperature-dew point
689
- # difference. Smaller values of a make fog density increase faster as the temperature
690
- # approaches the dew point.
691
- a = 1.5
692
-
693
- # Dampening constant for wind speed. This value ensures a gradual decay in fog density
694
- # as wind speed increases, which reflects that moderate wind disperses fog.
695
- b = 10
696
-
697
- # Calculate initial fog density based on temperature and humidity
698
- humidity_factor = rh2m / 100 # Relative humidity as a fraction
699
- temp_dew_diff = temp2m - dewpoint2m
700
-
701
- # Calculate fog density
702
- fog_density = k * humidity_factor * math.exp(-temp_dew_diff / a)
703
-
704
- # Adjust for wind speed
705
- adjusted_fog_density = fog_density * math.exp(-wind_speed / b)
706
-
707
- # Ensure fog density is within the valid range [0, 1]
708
- adjusted_fog_density = max(0, min(1, adjusted_fog_density))
709
-
710
- return float(adjusted_fog_density)
711
-
712
- @typechecked
713
- async def calculate_fog_density_11(self, temp2m, rh2m, dewpoint2m, wind_speed) -> float:
714
445
  """
715
446
  Estimate fog likelihood as a dimensionless density in [0, 1].
716
447
 
@@ -1454,49 +1185,69 @@ class AstronomicalRoutines:
1454
1185
  except (ephem.AlwaysUpError, ephem.NeverUpError):
1455
1186
  return None, None
1456
1187
 
1457
- # Function to check Moon conditions for the whole night
1458
- def _is_moon_dark_whole_night(self, night_start, night_end) -> bool:
1188
+ @staticmethod
1189
+ def _moon_illuminance(alt_rad: float, phase_pct: float) -> float:
1190
+ """Return lunar illuminance proxy: phase_fraction × max(0, sin(altitude)).
1191
+
1192
+ Combines phase and altitude into a single value on [0, 1]:
1193
+ - 0 → moon invisible (below horizon or new moon)
1194
+ - 1 → full moon directly overhead
1195
+ A value below DARK_NIGHT_MAX_ILLUMINANCE indicates negligible sky glow.
1459
1196
  """
1460
- Test if Moon phase is less than 5% and/or maximum Moon altitide during
1461
- astronomical darkness is less than 5°.
1197
+ return (phase_pct / 100.0) * max(0.0, math.sin(alt_rad))
1462
1198
 
1463
- Args:
1464
- - night_start: Sun set -18°
1465
- - night_end: Sun rise -18°
1199
+ def moon_illuminance_at(self, dt: datetime) -> float:
1200
+ """Return the lunar illuminance proxy at an arbitrary UTC datetime.
1466
1201
 
1467
- Returns:
1468
- - dark_night: True, if Moon is within constraints.
1202
+ Intended for per-hour forecast calculations so that the moon's actual
1203
+ position at each forecast timestamp drives the score, not its position
1204
+ at the time the coordinator last ran.
1469
1205
  """
1470
- current_time = night_start
1206
+ if self._moon_observer is None:
1207
+ self._moon_observer = self._get_moon_observer()
1208
+ if self._moon is None:
1209
+ self._moon = ephem.Moon()
1210
+ self._moon_observer.date = dt.replace(tzinfo=None)
1211
+ self._moon.compute(self._moon_observer)
1212
+ return self._moon_illuminance(float(self._moon.alt), self._moon.phase)
1471
1213
 
1472
- moon_alts = []
1473
- moon_phases = []
1474
- dark_night = True
1214
+ def moon_altitude_at(self, dt: datetime) -> float:
1215
+ """Return moon altitude in degrees at an arbitrary UTC datetime."""
1216
+ if self._moon_observer is None:
1217
+ self._moon_observer = self._get_moon_observer()
1218
+ if self._moon is None:
1219
+ self._moon = ephem.Moon()
1220
+ self._moon_observer.date = dt.replace(tzinfo=None)
1221
+ self._moon.compute(self._moon_observer)
1222
+ return deg(float(self._moon.alt))
1223
+
1224
+ # Function to check Moon conditions for the whole night
1225
+ def _is_moon_dark_whole_night(self, night_start, night_end) -> bool:
1226
+ """Return True if the night qualifies as a dark night.
1227
+
1228
+ Uses an integrated lunar illuminance proxy instead of independent
1229
+ phase / altitude thresholds. The proxy is:
1230
+ illuminance = (phase / 100) × max(0, sin(altitude_radians))
1231
+ A night is dark when the peak illuminance over the whole night stays
1232
+ below DARK_NIGHT_MAX_ILLUMINANCE, which avoids the edge cases of the
1233
+ previous approach (e.g. a full moon 3° above the horizon being accepted
1234
+ because its altitude was below the 5° threshold).
1235
+ """
1236
+ current_time = night_start
1237
+ peak_illuminance = 0.0
1475
1238
 
1476
1239
  while current_time <= night_end:
1477
1240
  self._moon_observer.date = current_time
1478
1241
  moon = ephem.Moon(self._moon_observer)
1479
-
1480
- moon_alt = moon.alt
1481
- moon_alts.append(moon_alt)
1482
- moon_phase = moon.phase # Moon phase in percentage
1483
- moon_phases.append(moon_phase)
1484
-
1485
- # If at any point the Moon is above horizon and > 10% illuminated, return False
1486
- if moon_alt > ephem.degrees(DARK_NIGHT_MAX_MOON_ALT): # and moon_phase >= DARK_NIGHT_MAX_MOON_PHASE * 10:
1487
- dark_night = False
1488
- break
1489
-
1490
- # Step in time (e.g., every 15 minutes)
1242
+ illuminance = self._moon_illuminance(float(moon.alt), moon.phase)
1243
+ if illuminance > peak_illuminance:
1244
+ peak_illuminance = illuminance
1491
1245
  current_time += timedelta(minutes=5)
1492
1246
 
1493
- moon_phases_avg = sum(moon_phases) / len(moon_phases)
1494
- if dark_night or moon_phases_avg <= DARK_NIGHT_MAX_MOON_PHASE * 10:
1495
- _LOGGER.debug(
1496
- 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}%"
1497
- )
1498
- else:
1499
- dark_night = False
1247
+ dark_night = peak_illuminance <= DARK_NIGHT_MAX_ILLUMINANCE
1248
+ _LOGGER.debug(
1249
+ f"Night {night_start.strftime('%Y-%m-%d')}: peak illuminance {peak_illuminance:.4f} → dark_night={dark_night}"
1250
+ )
1500
1251
  return dark_night
1501
1252
 
1502
1253
  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.dev2
3
+ Version: 0.76.0.dev4
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.dev2",
14
+ version="0.76.0.dev4",
15
15
  license="MIT",
16
16
  description="Python Wrapper for OpenMeteo and Met.no REST API",
17
17
  long_description=" ".join(
@@ -1,7 +1,6 @@
1
1
  """Unit tests for atmospheric calculations in AtmosphericRoutines."""
2
2
 
3
3
  import asyncio
4
- import math
5
4
  import unittest
6
5
 
7
6
  from pyastroweatherio.helper_functions import AtmosphericRoutines
@@ -97,27 +96,6 @@ class TestAtmosphericCalculations(unittest.TestCase):
97
96
  ))
98
97
  self.assertIsNone(result)
99
98
 
100
- # ---------------------------------------------------------------
101
- # calculate_lifted_index_11
102
- # ---------------------------------------------------------------
103
- def test_lifted_index_11_in_range(self):
104
- c = self.clear
105
- result = asyncio.run(self.atm.calculate_lifted_index_11(
106
- temperature=c["temperature"], altitude=c["altitude"],
107
- dew_point_temperature=c["dew_point_temperature"],
108
- air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
109
- ))
110
- self.assertIsNotNone(result)
111
- self.assertGreaterEqual(result, -7.0)
112
- self.assertLessEqual(result, 7.0)
113
-
114
- def test_lifted_index_11_returns_none_on_missing(self):
115
- result = asyncio.run(self.atm.calculate_lifted_index_11(
116
- temperature=None, altitude=500.0,
117
- dew_point_temperature=5.0, air_pressure_at_sea_level=1013.25,
118
- ))
119
- self.assertIsNone(result)
120
-
121
99
  # ---------------------------------------------------------------
122
100
  # calculate_seeing
123
101
  # ---------------------------------------------------------------
@@ -131,40 +109,17 @@ class TestAtmosphericCalculations(unittest.TestCase):
131
109
  ))
132
110
  self.assertIsNotNone(result)
133
111
  self.assertGreater(result, 0.0)
134
- self.assertLessEqual(result, 2.5)
112
+ self.assertLessEqual(result, 4.0)
135
113
 
136
- def test_seeing_returns_none_on_missing(self):
137
- result = asyncio.run(self.atm.calculate_seeing(
138
- temperature=None, humidity=50.0, dew_point_temperature=5.0,
139
- wind_speed=2.0, cloud_cover=0.0, altitude=500.0,
140
- air_pressure_at_sea_level=1013.25,
141
- ))
142
- self.assertIsNone(result)
143
-
144
- # ---------------------------------------------------------------
145
- # calculate_seeing_11
146
- # ---------------------------------------------------------------
147
- def test_seeing_11_clear_in_range(self):
148
- c = self.clear
149
- result = asyncio.run(self.atm.calculate_seeing_11(
150
- temperature=c["temperature"], humidity=c["humidity"],
151
- dew_point_temperature=c["dew_point_temperature"],
152
- wind_speed=c["wind_speed"], cloud_cover=c["cloud_cover"],
153
- altitude=c["altitude"], air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
154
- ))
155
- self.assertIsNotNone(result)
156
- self.assertGreater(result, 0.0)
157
- self.assertLessEqual(result, 2.5)
158
-
159
- def test_seeing_11_worse_overcast(self):
114
+ def test_seeing_worse_overcast(self):
160
115
  c, o = self.clear, self.overcast
161
- r_clear = asyncio.run(self.atm.calculate_seeing_11(
116
+ r_clear = asyncio.run(self.atm.calculate_seeing(
162
117
  temperature=c["temperature"], humidity=c["humidity"],
163
118
  dew_point_temperature=c["dew_point_temperature"],
164
119
  wind_speed=c["wind_speed"], cloud_cover=c["cloud_cover"],
165
120
  altitude=c["altitude"], air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
166
121
  ))
167
- r_overcast = asyncio.run(self.atm.calculate_seeing_11(
122
+ r_overcast = asyncio.run(self.atm.calculate_seeing(
168
123
  temperature=o["temperature"], humidity=o["humidity"],
169
124
  dew_point_temperature=o["dew_point_temperature"],
170
125
  wind_speed=o["wind_speed"], cloud_cover=o["cloud_cover"],
@@ -173,8 +128,8 @@ class TestAtmosphericCalculations(unittest.TestCase):
173
128
  # Larger arcsec value = worse seeing
174
129
  self.assertGreater(r_overcast, r_clear)
175
130
 
176
- def test_seeing_11_returns_none_on_missing(self):
177
- result = asyncio.run(self.atm.calculate_seeing_11(
131
+ def test_seeing_returns_none_on_missing(self):
132
+ result = asyncio.run(self.atm.calculate_seeing(
178
133
  temperature=None, humidity=50.0, dew_point_temperature=5.0,
179
134
  wind_speed=2.0, cloud_cover=0.0, altitude=500.0,
180
135
  air_pressure_at_sea_level=1013.25,
@@ -194,22 +149,9 @@ class TestAtmosphericCalculations(unittest.TestCase):
194
149
  result = asyncio.run(self.atm.calculate_fog_density(10.0, 99.0, 9.8, 0.5))
195
150
  self.assertGreater(result, 0.3)
196
151
 
197
- # ---------------------------------------------------------------
198
- # calculate_fog_density_11
199
- # ---------------------------------------------------------------
200
- def test_fog_density_11_clear_is_low(self):
201
- result = asyncio.run(self.atm.calculate_fog_density_11(15.0, 50.0, 4.6, 2.0))
202
- self.assertGreaterEqual(result, 0.0)
203
- self.assertLessEqual(result, 1.0)
204
- self.assertLess(result, 0.3)
205
-
206
- def test_fog_density_11_saturated_is_high(self):
207
- result = asyncio.run(self.atm.calculate_fog_density_11(10.0, 99.0, 9.8, 0.5))
208
- self.assertGreater(result, 0.3)
209
-
210
- def test_fog_density_11_wind_disperses_fog(self):
211
- result_calm = asyncio.run(self.atm.calculate_fog_density_11(10.0, 99.0, 9.8, 0.0))
212
- result_windy = asyncio.run(self.atm.calculate_fog_density_11(10.0, 99.0, 9.8, 15.0))
152
+ def test_fog_density_wind_disperses_fog(self):
153
+ result_calm = asyncio.run(self.atm.calculate_fog_density(10.0, 99.0, 9.8, 0.0))
154
+ result_windy = asyncio.run(self.atm.calculate_fog_density(10.0, 99.0, 9.8, 15.0))
213
155
  self.assertGreater(result_calm, result_windy)
214
156
 
215
157
  # ---------------------------------------------------------------
@@ -227,51 +169,15 @@ class TestAtmosphericCalculations(unittest.TestCase):
227
169
  self.assertGreaterEqual(result, 0.0)
228
170
  self.assertLessEqual(result, 1.0)
229
171
 
230
- def test_magnitude_degradation_overcast_is_high(self):
231
- o = self.overcast
232
- result = asyncio.run(self.atm.magnitude_degradation(
233
- temperature=o["temperature"], humidity=o["humidity"],
234
- cloud_cover=o["cloud_cover"], wind_speed=o["wind_speed"],
235
- altitude=o["altitude"], dew_point_temperature=o["dew_point_temperature"],
236
- air_pressure_at_sea_level=o["air_pressure_at_sea_level"],
237
- ))
238
- self.assertIsNotNone(result)
239
- self.assertGreaterEqual(result, 0.5)
240
-
241
- def test_magnitude_degradation_returns_none_on_missing(self):
242
- c = self.clear
243
- result = asyncio.run(self.atm.magnitude_degradation(
244
- temperature=None, humidity=c["humidity"],
245
- cloud_cover=c["cloud_cover"], wind_speed=c["wind_speed"],
246
- altitude=c["altitude"], dew_point_temperature=c["dew_point_temperature"],
247
- air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
248
- ))
249
- self.assertIsNone(result)
250
-
251
- # ---------------------------------------------------------------
252
- # magnitude_degradation_11
253
- # ---------------------------------------------------------------
254
- def test_magnitude_degradation_11_clear_in_range(self):
255
- c = self.clear
256
- result = asyncio.run(self.atm.magnitude_degradation_11(
257
- temperature=c["temperature"], humidity=c["humidity"],
258
- cloud_cover=c["cloud_cover"], wind_speed=c["wind_speed"],
259
- altitude=c["altitude"], dew_point_temperature=c["dew_point_temperature"],
260
- air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
261
- ))
262
- self.assertIsNotNone(result)
263
- self.assertGreaterEqual(result, 0.0)
264
- self.assertLessEqual(result, 1.0)
265
-
266
- def test_magnitude_degradation_11_worse_overcast(self):
172
+ def test_magnitude_degradation_worse_overcast(self):
267
173
  c, o = self.clear, self.overcast
268
- r_clear = asyncio.run(self.atm.magnitude_degradation_11(
174
+ r_clear = asyncio.run(self.atm.magnitude_degradation(
269
175
  temperature=c["temperature"], humidity=c["humidity"],
270
176
  cloud_cover=c["cloud_cover"], wind_speed=c["wind_speed"],
271
177
  altitude=c["altitude"], dew_point_temperature=c["dew_point_temperature"],
272
178
  air_pressure_at_sea_level=c["air_pressure_at_sea_level"],
273
179
  ))
274
- r_overcast = asyncio.run(self.atm.magnitude_degradation_11(
180
+ r_overcast = asyncio.run(self.atm.magnitude_degradation(
275
181
  temperature=o["temperature"], humidity=o["humidity"],
276
182
  cloud_cover=o["cloud_cover"], wind_speed=o["wind_speed"],
277
183
  altitude=o["altitude"], dew_point_temperature=o["dew_point_temperature"],
@@ -279,9 +185,9 @@ class TestAtmosphericCalculations(unittest.TestCase):
279
185
  ))
280
186
  self.assertGreater(r_overcast, r_clear)
281
187
 
282
- def test_magnitude_degradation_11_returns_none_on_missing(self):
188
+ def test_magnitude_degradation_returns_none_on_missing(self):
283
189
  c = self.clear
284
- result = asyncio.run(self.atm.magnitude_degradation_11(
190
+ result = asyncio.run(self.atm.magnitude_degradation(
285
191
  temperature=None, humidity=c["humidity"],
286
192
  cloud_cover=c["cloud_cover"], wind_speed=c["wind_speed"],
287
193
  altitude=c["altitude"], dew_point_temperature=c["dew_point_temperature"],