pyastroweatherio 0.75.0.dev3__tar.gz → 0.76.0.dev2__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.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/PKG-INFO +1 -1
  2. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/README.md +1 -1
  3. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/client.py +183 -35
  4. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/const.py +9 -0
  5. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/dataclasses.py +1 -2
  6. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/helper_functions.py +283 -598
  7. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio.egg-info/PKG-INFO +1 -1
  8. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio.egg-info/SOURCES.txt +3 -1
  9. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/setup.py +1 -1
  10. pyastroweatherio-0.76.0.dev2/tests/test_calculations.py +294 -0
  11. pyastroweatherio-0.76.0.dev2/tests/test_client.py +550 -0
  12. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/LICENSE +0 -0
  13. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/__init__.py +0 -0
  14. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio/errors.py +0 -0
  15. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio.egg-info/dependency_links.txt +0 -0
  16. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio.egg-info/requires.txt +0 -0
  17. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/pyastroweatherio.egg-info/top_level.txt +0 -0
  18. {pyastroweatherio-0.75.0.dev3 → pyastroweatherio-0.76.0.dev2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyastroweatherio
3
- Version: 0.75.0.dev3
3
+ Version: 0.76.0.dev2
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
@@ -56,5 +56,5 @@ twine upload dist/*
56
56
  ## Test
57
57
 
58
58
  ```sh
59
- python -m unittest -v tests/client.py
59
+ python -m unittest -v tests/test_client.py
60
60
  ```
@@ -8,19 +8,14 @@ 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 pprint import pprint as pp
12
11
  from typing import Any, Dict, List, Optional
13
12
 
14
13
  import aiofiles
15
14
 
16
- # from aiohttp.client import ClientError, ClientResponseError, ClientSession
17
- import numpy as np # from retry_requests import retry
18
-
19
- # import openmeteo_requests
20
- # import requests_cache
15
+ import numpy as np
21
16
  import pandas as pd
22
17
  from aiohttp import ClientSession, ClientTimeout
23
- from aiohttp.client import ClientResponseError, ClientSession
18
+ from aiohttp.client import ClientResponseError
24
19
  from aiohttp.client_exceptions import ClientError
25
20
  from typeguard import typechecked
26
21
 
@@ -103,6 +98,13 @@ class AstroWeather:
103
98
  experimental_features=False,
104
99
  forecast_model=None,
105
100
  ):
101
+ if not -90 <= latitude <= 90:
102
+ raise ValueError(f"Latitude must be between -90 and 90, got {latitude}")
103
+ if not -180 <= longitude <= 180:
104
+ raise ValueError(f"Longitude must be between -180 and 180, got {longitude}")
105
+ if not -500 <= elevation <= 9000:
106
+ raise ValueError(f"Elevation must be between -500 and 9000 meters, got {elevation}")
107
+
106
108
  self._session: ClientSession = session
107
109
  self._location_data = self._get_location(
108
110
  latitude,
@@ -192,11 +194,12 @@ class AstroWeather:
192
194
  )
193
195
  for _, row in df.iterrows()
194
196
  ]
195
- results = await asyncio.gather(*tasks)
196
- return results
197
+ results = await asyncio.gather(*tasks, return_exceptions=True)
198
+ return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Dew point calculation failed: %s", r) or float("nan")) for r in results]
197
199
 
198
200
  async def _calculate_seeing(self, df):
199
201
  if self._experimental_features:
202
+ has_pbl = "gfs_boundary_layer_height" in df.columns
200
203
  tasks = [
201
204
  self._atmosphere.calculate_seeing_11(
202
205
  temperature=row["air_temperature"],
@@ -206,6 +209,7 @@ class AstroWeather:
206
209
  cloud_cover=row["cloud_area_fraction"],
207
210
  altitude=self._location_data.elevation,
208
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,
209
213
  )
210
214
  for _, row in df.iterrows()
211
215
  ]
@@ -222,8 +226,8 @@ class AstroWeather:
222
226
  )
223
227
  for _, row in df.iterrows()
224
228
  ]
225
- results = await asyncio.gather(*tasks)
226
- return results
229
+ results = await asyncio.gather(*tasks, return_exceptions=True)
230
+ return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Seeing calculation failed: %s", r) or float("nan")) for r in results]
227
231
 
228
232
  async def _calculate_transparency(self, df):
229
233
  if self._experimental_features:
@@ -252,10 +256,36 @@ class AstroWeather:
252
256
  )
253
257
  for _, row in df.iterrows()
254
258
  ]
255
- results = await asyncio.gather(*tasks)
256
- return results
259
+ results = await asyncio.gather(*tasks, return_exceptions=True)
260
+ return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Transparency calculation failed: %s", r) or float("nan")) for r in results]
257
261
 
258
262
  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
265
+ results = []
266
+ fallback_idx = [i for i, (_, row) in enumerate(df.iterrows()) if pd.isna(row["gfs_lifted_index"])]
267
+ if fallback_idx:
268
+ fallback_rows = df.iloc[fallback_idx]
269
+ fallback_tasks = [
270
+ self._atmosphere.calculate_lifted_index_11(
271
+ temperature=row["air_temperature"],
272
+ dew_point_temperature=row["dew_point_temperature"],
273
+ altitude=self._location_data.elevation,
274
+ air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
275
+ )
276
+ for _, row in fallback_rows.iterrows()
277
+ ]
278
+ fallback_computed = await asyncio.gather(*fallback_tasks, return_exceptions=True)
279
+ fallback_map = dict(zip(fallback_idx, fallback_computed))
280
+ else:
281
+ fallback_map = {}
282
+ for i, (_, row) in enumerate(df.iterrows()):
283
+ if not pd.isna(row["gfs_lifted_index"]):
284
+ results.append(float(row["gfs_lifted_index"]))
285
+ else:
286
+ r = fallback_map.get(i)
287
+ results.append(r if not isinstance(r, BaseException) else float("nan"))
288
+ return results
259
289
  if self._experimental_features:
260
290
  tasks = [
261
291
  self._atmosphere.calculate_lifted_index_11(
@@ -276,10 +306,10 @@ class AstroWeather:
276
306
  )
277
307
  for _, row in df.iterrows()
278
308
  ]
279
- results = await asyncio.gather(*tasks)
280
- return results
309
+ results = await asyncio.gather(*tasks, return_exceptions=True)
310
+ return [r if not isinstance(r, BaseException) else (_LOGGER.warning("Lifted index calculation failed: %s", r) or float("nan")) for r in results]
281
311
 
282
- async def _retrive_data(self) -> None:
312
+ async def _retrieve_data(self) -> None:
283
313
  """Retrieves current data from all data sources."""
284
314
  async with self._lock:
285
315
  if ((datetime.now() - self._weather_data_timestamp).total_seconds()) > DEFAULT_CACHE_TIMEOUT:
@@ -294,13 +324,24 @@ class AstroWeather:
294
324
  if weather_df_metno is None:
295
325
  _LOGGER.warning("Could not retrieve Met.no data. Using existing data.")
296
326
  return None
297
- await self._retrieve_data_uptonight()
327
+ # Fetch uptonight (local I/O), Open-Meteo primary, and GFS supplementary in parallel
328
+ uptonight_result, openmeteo_result, gfs_result = await asyncio.gather(
329
+ self._retrieve_data_uptonight(),
330
+ self._retrieve_data_openmeteo(),
331
+ self._retrieve_data_gfs(),
332
+ return_exceptions=True,
333
+ )
298
334
 
299
- try:
300
- weather_df_openmeteo = await self._retrieve_data_openmeteo()
301
- except OpenMeteoConnectionError:
302
- _LOGGER.warning("Could not retrieve OpenMeteo data. Using existing data.")
335
+ if isinstance(openmeteo_result, BaseException):
336
+ _LOGGER.warning("Could not retrieve Open-Meteo data. Using existing data.")
303
337
  return None
338
+ weather_df_openmeteo = openmeteo_result
339
+
340
+ if isinstance(gfs_result, BaseException):
341
+ _LOGGER.warning("Could not retrieve GFS supplementary data: %s", gfs_result)
342
+ weather_df_gfs = None
343
+ else:
344
+ weather_df_gfs = gfs_result
304
345
 
305
346
  # Merge the dataframes of metno and openmeteo
306
347
  self._weather_df = weather_df_metno.merge(weather_df_openmeteo, on="time", how="left")
@@ -332,6 +373,13 @@ class AstroWeather:
332
373
  axis=1,
333
374
  )
334
375
 
376
+ # Merge GFS supplementary data (lifted_index, cape, boundary_layer_height, visibility)
377
+ if weather_df_gfs is not None:
378
+ self._weather_df = self._weather_df.merge(weather_df_gfs, on="time", how="left")
379
+ else:
380
+ for col in ("gfs_lifted_index", "gfs_cape", "gfs_boundary_layer_height", "gfs_visibility"):
381
+ self._weather_df[col] = float("nan")
382
+
335
383
  # Clean up rows with missing values
336
384
  self._weather_df = self._weather_df.dropna(subset=["air_temperature"])
337
385
  self._weather_df = self._weather_df.dropna(subset=["next_6h_symbol_code"])
@@ -357,6 +405,7 @@ class AstroWeather:
357
405
  self._weather_df["transparency"] = await self._calculate_transparency(self._weather_df)
358
406
  self._weather_df["lifted_index"] = await self._calculate_lifted_index(self._weather_df)
359
407
 
408
+ self._weather_df = self._weather_df.set_index("time")
360
409
  self._test_weather_df()
361
410
  else:
362
411
  _LOGGER.debug("Using cached data")
@@ -395,8 +444,10 @@ class AstroWeather:
395
444
  """Returns a validated Weather Conditions data object"""
396
445
 
397
446
  # Return row from dataframe
398
- timestamp = time.replace(tzinfo=None).strftime("%Y-%m-%d %H:00:00+00:00")
399
- row = self._weather_df.loc[self._weather_df["time"] == timestamp].iloc[0]
447
+ ts = pd.Timestamp(time).replace(minute=0, second=0, microsecond=0)
448
+ if ts.tzinfo is None:
449
+ ts = ts.tz_localize("UTC")
450
+ row = self._weather_df.loc[ts]
400
451
 
401
452
  cloudcover = float(row["cloud_area_fraction"])
402
453
  cloud_area_fraction = float(row["cloud_area_fraction"])
@@ -418,9 +469,16 @@ class AstroWeather:
418
469
  lifted_index = float(row["lifted_index"])
419
470
 
420
471
  # Calculate Fog Density
421
- fog2m = await self._atmosphere.calculate_fog_density(temp2m, rh2m, dewpoint2m, wind_speed) * 100
422
472
  if self._experimental_features:
423
- fog2m = await self._atmosphere.calculate_fog_density_11(temp2m, rh2m, dewpoint2m, wind_speed) * 100
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
480
+ else:
481
+ fog2m = await self._atmosphere.calculate_fog_density(temp2m, rh2m, dewpoint2m, wind_speed) * 100
424
482
 
425
483
  condition = ConditionDataModel(
426
484
  {
@@ -560,7 +618,7 @@ class AstroWeather:
560
618
 
561
619
  items = []
562
620
 
563
- await self._retrive_data()
621
+ await self._retrieve_data()
564
622
 
565
623
  now = datetime.now(UTC).replace(tzinfo=None)
566
624
 
@@ -581,7 +639,8 @@ class AstroWeather:
581
639
  _LOGGER.error("Weather data not available")
582
640
  return []
583
641
 
584
- data_index = int((self._weather_df["time"] == now.strftime("%Y-%m-%d %H:00:00+00:00")).idxmax())
642
+ now_ts = pd.Timestamp(now).tz_localize("UTC").replace(minute=0, second=0, microsecond=0)
643
+ data_index = self._weather_df.index.get_loc(now_ts) if now_ts in self._weather_df.index else 0
585
644
  _LOGGER.debug("Data index: %s", str(data_index))
586
645
 
587
646
  time_data = TimeDataModel(
@@ -634,7 +693,7 @@ class AstroWeather:
634
693
 
635
694
  items = []
636
695
 
637
- await self._retrive_data()
696
+ await self._retrieve_data()
638
697
 
639
698
  now = datetime.now(UTC).replace(tzinfo=None)
640
699
 
@@ -653,11 +712,12 @@ class AstroWeather:
653
712
  _LOGGER.error("Weather data not available")
654
713
  return []
655
714
 
656
- data_index = int((self._weather_df["time"] == now.strftime("%Y-%m-%d %H:00:00+00:00")).idxmax())
715
+ now_ts = pd.Timestamp(now).tz_localize("UTC").replace(minute=0, second=0, microsecond=0)
716
+ data_index = self._weather_df.index.get_loc(now_ts) if now_ts in self._weather_df.index else 0
657
717
  _LOGGER.debug("Data index: %s", str(data_index))
658
718
 
659
- for index, row in self._weather_df.iterrows():
660
- forecast_time = row["time"].replace(microsecond=0, tzinfo=timezone.utc)
719
+ for ts, row in self._weather_df.iterrows():
720
+ forecast_time = ts.replace(microsecond=0)
661
721
 
662
722
  td = TimeDataModel(
663
723
  {
@@ -676,13 +736,13 @@ class AstroWeather:
676
736
  item = ForecastDataModel(
677
737
  {
678
738
  "time_data": time_data, # Time data
679
- "hour": row["time"].hour, # forecast_time.hour % 24,
680
- "condition_data": await self._get_condition(row["time"]),
739
+ "hour": ts.hour, # forecast_time.hour % 24,
740
+ "condition_data": await self._get_condition(ts),
681
741
  }
682
742
  )
683
743
  except KeyError as ke:
684
744
  _LOGGER.error(f"Failed to parse location data model data: {ke}")
685
- _LOGGER.error(row["time"])
745
+ _LOGGER.error(ts)
686
746
 
687
747
  try:
688
748
  if item is not None:
@@ -1183,8 +1243,9 @@ class AstroWeather:
1183
1243
  # "temperature_unit": "C",
1184
1244
  "precipitation_unit": "mm",
1185
1245
  "wind_speed_unit": "ms",
1186
- "models": self._forecast_model,
1187
1246
  }
1247
+ if self._forecast_model is not None:
1248
+ params["models"] = self._forecast_model
1188
1249
 
1189
1250
  try:
1190
1251
  _LOGGER.debug(f"Query url: {BASE_URL_OPENMETEO}")
@@ -1254,3 +1315,90 @@ class AstroWeather:
1254
1315
  weather_df_openmeteo["time"] = weather_df_openmeteo["time"].dt.tz_localize("UTC")
1255
1316
 
1256
1317
  return weather_df_openmeteo
1318
+
1319
+ async def _retrieve_data_gfs(self) -> pd.DataFrame:
1320
+ """Fetch atmospheric stability variables from GFS via Open-Meteo.
1321
+
1322
+ Always uses gfs_seamless regardless of the user's primary forecast model,
1323
+ because lifted_index, cape, boundary_layer_height, and visibility are only
1324
+ available for GFS in the Open-Meteo API.
1325
+ """
1326
+ _LOGGER.debug("Updating supplementary data from GFS")
1327
+
1328
+ use_running_session = self._session and not self._session.closed
1329
+ if use_running_session:
1330
+ session = self._session
1331
+ else:
1332
+ session = ClientSession(timeout=ClientTimeout(total=DEFAULT_TIMEOUT))
1333
+
1334
+ params = {
1335
+ "latitude": self._location_data.latitude,
1336
+ "longitude": self._location_data.longitude,
1337
+ "hourly": [
1338
+ "lifted_index",
1339
+ "cape",
1340
+ "boundary_layer_height",
1341
+ "visibility",
1342
+ ],
1343
+ "timezone": "UTC",
1344
+ "models": "gfs_seamless",
1345
+ }
1346
+
1347
+ try:
1348
+ _LOGGER.debug(f"Query url (GFS): {BASE_URL_OPENMETEO}")
1349
+ response = await session.get(BASE_URL_OPENMETEO, params=params)
1350
+ except asyncio.TimeoutError as exception:
1351
+ _LOGGER.error(f"Timeout occurred while connecting to the Open-Meteo GFS API: {exception}")
1352
+ raise OpenMeteoConnectionError(exception) from exception
1353
+ except (
1354
+ ClientError,
1355
+ ClientResponseError,
1356
+ socket.gaierror,
1357
+ ) as exception:
1358
+ _LOGGER.error(f"Error occurred while communicating with Open-Meteo GFS API: {exception}")
1359
+ raise OpenMeteoConnectionError(exception) from exception
1360
+ finally:
1361
+ if not use_running_session:
1362
+ await session.close()
1363
+
1364
+ content_type = response.headers.get("Content-Type", "")
1365
+
1366
+ if (response.status // 100) in [4, 5]:
1367
+ if "application/json" in content_type:
1368
+ data = await response.json()
1369
+ response.close()
1370
+ if data.get("error") is True and (reason := data.get("reason")):
1371
+ raise OpenMeteoError(reason)
1372
+ raise OpenMeteoError(response.status, data)
1373
+ contents = await response.read()
1374
+ response.close()
1375
+ raise OpenMeteoError(response.status, {"message": contents.decode("utf8")})
1376
+
1377
+ text = await response.text()
1378
+ if "application/json" not in content_type:
1379
+ raise OpenMeteoError(
1380
+ "Unexpected response from the Open-Meteo GFS API",
1381
+ {"Content-Type": content_type, "response": text},
1382
+ )
1383
+
1384
+ data = await response.json()
1385
+ if self._test_mode:
1386
+ json_string = json.dumps(data)
1387
+ with open("debug/openmeteo_gfs.json", "w") as outfile:
1388
+ outfile.write(json_string)
1389
+
1390
+ response.close()
1391
+ hourly = data.get("hourly")
1392
+
1393
+ hourly_data = {
1394
+ "time": np.array(hourly.get("time")),
1395
+ "gfs_lifted_index": np.array(hourly.get("lifted_index")),
1396
+ "gfs_cape": np.array(hourly.get("cape")),
1397
+ "gfs_boundary_layer_height": np.array(hourly.get("boundary_layer_height")),
1398
+ "gfs_visibility": np.array(hourly.get("visibility")),
1399
+ }
1400
+
1401
+ weather_df_gfs = pd.DataFrame(data=hourly_data)
1402
+ weather_df_gfs["time"] = pd.to_datetime(weather_df_gfs["time"]).dt.tz_localize("UTC")
1403
+
1404
+ return weather_df_gfs
@@ -177,6 +177,15 @@ DEEP_SKY_THRESHOLD = 75
177
177
  DARK_NIGHT_MAX_MOON_PHASE = 0.05
178
178
  DARK_NIGHT_MAX_MOON_ALT = "5:0:0"
179
179
 
180
+ # #####################################################
181
+ # Astronomical constants
182
+ # #####################################################
183
+ AU_TO_KM = 149_597_870.7 # km per AU (IAU 2012)
184
+ MOON_MEAN_DISTANCE_KM = 384_400 # mean Moon–Earth distance (km)
185
+ MOON_MEAN_ANGULAR_SIZE_DEG = 0.5181 # mean lunar angular diameter (°)
186
+ LUNAR_MONTH_DAYS = 29.33 # mean synodic month (days)
187
+ KELVIN_OFFSET = 273.15 # °C to K conversion
188
+
180
189
  # #####################################################
181
190
  # Forecast
182
191
  # #####################################################
@@ -3,7 +3,6 @@
3
3
  import math
4
4
  from dataclasses import dataclass
5
5
  from datetime import datetime
6
- from pprint import pprint as pp
7
6
  from typing import TypedDict
8
7
 
9
8
  from typeguard import typechecked
@@ -1010,7 +1009,7 @@ class ForecastData:
1010
1009
  def deep_sky_view(self) -> bool:
1011
1010
  """Return True if Deep Sky should be possible."""
1012
1011
 
1013
- if self.condition_percentage <= DEEP_SKY_THRESHOLD:
1012
+ if self.condition_percentage >= DEEP_SKY_THRESHOLD:
1014
1013
  return True
1015
1014
  return False
1016
1015