pyastroweatherio 0.62.0.dev20__tar.gz → 0.62.0.dev22__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 (16) hide show
  1. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/PKG-INFO +1 -1
  2. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/client.py +90 -504
  3. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/dataclasses.py +0 -24
  4. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/errors.py +8 -0
  5. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/helper_functions.py +29 -1
  6. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio.egg-info/PKG-INFO +1 -1
  7. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/setup.py +1 -1
  8. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/LICENSE +0 -0
  9. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/README.md +0 -0
  10. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/__init__.py +0 -0
  11. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio/const.py +0 -0
  12. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio.egg-info/SOURCES.txt +0 -0
  13. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio.egg-info/dependency_links.txt +0 -0
  14. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio.egg-info/requires.txt +0 -0
  15. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/pyastroweatherio.egg-info/top_level.txt +0 -0
  16. {pyastroweatherio-0.62.0.dev20 → pyastroweatherio-0.62.0.dev22}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyastroweatherio
3
- Version: 0.62.0.dev20
3
+ Version: 0.62.0.dev22
4
4
  Summary: Python Wrapper for 7Timer and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -5,21 +5,24 @@ import json
5
5
  import logging
6
6
  import math
7
7
  import os.path
8
+ import socket
8
9
  from datetime import UTC, datetime, timedelta, timezone
9
10
  from json.decoder import JSONDecodeError
10
11
  from pprint import pprint as pp
11
12
  from typing import Any, Dict, List, Optional
12
13
 
13
14
  import aiofiles
14
- from aiohttp import ClientSession, ClientTimeout
15
- from aiohttp.client_exceptions import ClientError
16
- from typeguard import typechecked
17
15
 
18
- import openmeteo_requests
16
+ # from aiohttp.client import ClientError, ClientResponseError, ClientSession
17
+ import numpy as np # from retry_requests import retry
19
18
 
19
+ # import openmeteo_requests
20
20
  # import requests_cache
21
21
  import pandas as pd
22
- # from retry_requests import retry
22
+ from aiohttp import ClientSession, ClientTimeout
23
+ from aiohttp.client import ClientResponseError, ClientSession
24
+ from aiohttp.client_exceptions import ClientError
25
+ from typeguard import typechecked
23
26
 
24
27
  from pyastroweatherio.const import (
25
28
  BASE_URL_MET,
@@ -48,8 +51,8 @@ from pyastroweatherio.const import (
48
51
  WIND10M_MAX,
49
52
  )
50
53
  from pyastroweatherio.dataclasses import (
51
- AtmosphereData,
52
- AtmosphereDataModel,
54
+ # AtmosphereData,
55
+ # AtmosphereDataModel,
53
56
  ConditionData,
54
57
  ConditionDataModel,
55
58
  ForecastData,
@@ -69,7 +72,7 @@ from pyastroweatherio.dataclasses import (
69
72
  UpTonightDSOData,
70
73
  UpTonightDSODataModel,
71
74
  )
72
- from pyastroweatherio.errors import RequestError
75
+ from pyastroweatherio.errors import OpenMeteoConnectionError, OpenMeteoError, RequestError
73
76
  from pyastroweatherio.helper_functions import (
74
77
  AstronomicalRoutines,
75
78
  AtmosphericRoutines,
@@ -80,14 +83,6 @@ _LOGGER = logging.getLogger(__name__)
80
83
  _NOT_AVAILABLE = -9999
81
84
 
82
85
 
83
- class OpenMeteoError(Exception):
84
- """Generic OpenMeteo exception."""
85
-
86
-
87
- class OpenMeteoConnectionError(OpenMeteoError):
88
- """OpenMeteo connection exception."""
89
-
90
-
91
86
  class AstroWeather:
92
87
  """AstroWeather Communication Client."""
93
88
 
@@ -117,10 +112,6 @@ class AstroWeather:
117
112
  elevation,
118
113
  timezone_info,
119
114
  )
120
- self._weather_data_seventimer = []
121
- self._weather_data_seventimer_init = ""
122
- self._weather_data_metno = []
123
- self._weather_data_metno_init = ""
124
115
  self._weather_data_uptonight = {}
125
116
  self._weather_data_uptonight_bodies = {}
126
117
  self._weather_data_uptonight_comets = {}
@@ -141,6 +132,11 @@ class AstroWeather:
141
132
 
142
133
  # DataFrame
143
134
  self._weather_df = None
135
+ # Open-Meteo
136
+ # DWD Germany: icon_seamless
137
+ # Met.no: metno_seamless
138
+ # NOAA U.S.: gfs_seamless
139
+ # ECMWF: ecmwf_ifs025
144
140
  self._openmeteo_forecast = "icon_seamless"
145
141
 
146
142
  # Astro Routines
@@ -182,6 +178,17 @@ class AstroWeather:
182
178
  # #########################################################################
183
179
  # Private functions
184
180
  # #########################################################################
181
+ async def _calculate_dew_point(self, df):
182
+ tasks = [
183
+ self._atmosphere.calculate_dew_point(
184
+ temp2m=row["air_temperature"],
185
+ rh2m=row["relative_humidity"],
186
+ )
187
+ for _, row in df.iterrows()
188
+ ]
189
+ results = await asyncio.gather(*tasks)
190
+ return results
191
+
185
192
  async def _calculate_seeing(self, df):
186
193
  tasks = [
187
194
  self._atmosphere.calculate_seeing(
@@ -235,15 +242,17 @@ class AstroWeather:
235
242
 
236
243
  weather_df_metno = await self._retrieve_data_metno()
237
244
  weather_df_seventimer = await self._retrieve_data_seventimer()
238
- weather_df_openmeteo = await self._retrieve_data_openmeteo()
239
245
  await self._retrieve_data_uptonight()
240
246
 
241
- # Merge the dataframes of metno, seventimer, and openmeteo
242
- self._weather_df = weather_df_metno.merge(weather_df_seventimer, on="time", how="left").merge(
243
- weather_df_openmeteo, on="time", how="left"
244
- )
245
-
246
247
  if self._openmeteo_forecast is not None:
248
+ weather_df_openmeteo = await self._retrieve_data_openmeteo()
249
+
250
+ # Merge the dataframes of metno, seventimer, and openmeteo
251
+ self._weather_df = weather_df_metno.merge(weather_df_seventimer, on="time", how="left").merge(
252
+ weather_df_openmeteo, on="time", how="left"
253
+ )
254
+
255
+ # Overwrite met.no forecast with open-meteo forcast
247
256
  self._weather_df["cloud_area_fraction"] = self._weather_df["openmeteo_cloud_cover"]
248
257
  self._weather_df["cloud_area_fraction_high"] = self._weather_df["openmeteo_cloud_cover_high"]
249
258
  self._weather_df["cloud_area_fraction_medium"] = self._weather_df["openmeteo_cloud_cover_mid"]
@@ -269,8 +278,11 @@ class AstroWeather:
269
278
  ],
270
279
  axis=1,
271
280
  )
281
+ else:
282
+ # Merge the dataframes of metno and seventimer
283
+ self._weather_df = weather_df_metno.merge(weather_df_seventimer, on="time", how="left")
272
284
 
273
- # Clean up
285
+ # Clean up rows with missing values
274
286
  self._weather_df = self._weather_df.dropna(subset=["air_temperature"])
275
287
  self._weather_df = self._weather_df.dropna(subset=["next_6h_symbol_code"])
276
288
 
@@ -281,14 +293,22 @@ class AstroWeather:
281
293
  self._weather_df = self._weather_df.loc[: cutoff_index - 1]
282
294
  self._weather_df = self._weather_df.drop(columns=["time_diff"])
283
295
 
284
- print(self._weather_df)
285
- self._weather_df.to_csv("output.csv", sep=";", index=False)
296
+ # Check if we got dew point temperatures. If not calculate them.
297
+ has_nan_or_none = self._weather_df["dew_point_temperature"].isnull().any()
298
+ if has_nan_or_none:
299
+ _LOGGER.warning(
300
+ f"Column 'dew_point_temperature' has NaN or None: {has_nan_or_none}. Calculating dew points."
301
+ )
302
+ self._weather_df["dew_point_temperature"] = await self._calculate_dew_point(self._weather_df)
286
303
 
304
+ # Should we try to calculate seeing, transparency, and lifted_index?
287
305
  if self._experimental_features:
306
+ # Calculate atmosphere
288
307
  self._weather_df["seeing"] = await self._calculate_seeing(self._weather_df)
289
308
  self._weather_df["transparency"] = await self._calculate_transparency(self._weather_df)
290
309
  self._weather_df["lifted_index"] = await self._calculate_lifted_index(self._weather_df)
291
310
  else:
311
+ # 7Timer delivers three hourly data only, so we fill the missing data here
292
312
  self._weather_df["seeing"] = self._weather_df["seeing"].ffill()
293
313
  self._weather_df["transparency"] = self._weather_df["transparency"].ffill()
294
314
  self._weather_df["lifted_index"] = self._weather_df["lifted_index"].ffill()
@@ -297,6 +317,9 @@ class AstroWeather:
297
317
  self._weather_df["lifted_index"] = self._weather_df["lifted_index"].bfill()
298
318
 
299
319
  now = datetime.now(UTC).replace(tzinfo=None).strftime("%Y-%m-%d %H:00:00+00:00")
320
+
321
+ # self._weather_df.to_csv("output.csv", sep=";", index=False)
322
+ print(self._weather_df)
300
323
  print(self._weather_df.loc[self._weather_df["time"] == now].iloc[0])
301
324
  else:
302
325
  _LOGGER.debug("Using cached data")
@@ -327,211 +350,16 @@ class AstroWeather:
327
350
  _LOGGER.error(ve)
328
351
  return None
329
352
 
330
- # @typechecked
331
- # async def _get_atmosphere(self, details_seventimer, details_metno) -> AtmosphereData | None:
332
- # """Returns a validated Atmospherical Conditions data object"""
333
-
334
- # atmosphere = {}
335
-
336
- # seeing = 0
337
- # if details_seventimer["seeing"] == _NOT_AVAILABLE:
338
- # seeing = await self._atmosphere.calculate_seeing(
339
- # temperature=details_metno.get("air_temperature"),
340
- # humidity=details_metno.get("relative_humidity"),
341
- # dew_point_temperature=details_metno.get("dew_point_temperature"),
342
- # wind_speed=details_metno.get("wind_speed"),
343
- # cloud_cover=details_metno.get("cloud_area_fraction"),
344
- # altitude=self._location_data.elevation,
345
- # air_pressure_at_sea_level=details_metno.get("air_pressure_at_sea_level"),
346
- # )
347
- # else:
348
- # seeing = SEEING[max(0, min(7, int(details_seventimer["seeing"] - 1)))]
349
-
350
- # transparency = 0
351
- # if details_seventimer["transparency"] == _NOT_AVAILABLE:
352
- # transparency = await self._atmosphere.magnitude_degradation(
353
- # temperature=details_metno.get("air_temperature"),
354
- # humidity=details_metno.get("relative_humidity"),
355
- # dew_point_temperature=details_metno.get("dew_point_temperature"),
356
- # wind_speed=details_metno.get("wind_speed"),
357
- # cloud_cover=details_metno.get("cloud_area_fraction"),
358
- # altitude=self._location_data.elevation,
359
- # air_pressure_at_sea_level=details_metno.get("air_pressure_at_sea_level"),
360
- # )
361
- # else:
362
- # transparency = TRANSPARENCY[max(0, min(7, int(details_seventimer["transparency"] - 1)))]
363
-
364
- # lifted_index = 0
365
- # if details_seventimer["lifted_index"] == _NOT_AVAILABLE:
366
- # lifted_index = await self._atmosphere.calculate_lifted_index(
367
- # temperature=details_metno.get("air_temperature"),
368
- # dew_point_temperature=details_metno.get("dew_point_temperature"),
369
- # altitude=self._location_data.elevation,
370
- # air_pressure_at_sea_level=details_metno.get("air_pressure_at_sea_level"),
371
- # )
372
- # else:
373
- # lifted_index = LIFTED_INDEX_7TIMER_MAPPING[details_seventimer["lifted_index"]]
374
-
375
- # atmosphere = AtmosphereDataModel(
376
- # {
377
- # "seeing": seeing,
378
- # "transparency": transparency,
379
- # "lifted_index": lifted_index,
380
- # }
381
- # )
382
-
383
- # try:
384
- # return AtmosphereData(data=atmosphere)
385
- # except TypeError as ve:
386
- # _LOGGER.error(f"Failed to parse atmosphere data: {atmosphere}")
387
- # _LOGGER.error(ve)
388
- # return None
389
-
390
- # @typechecked
391
- # async def _get_atmosphere1(self, time) -> AtmosphereData | None:
392
- # """Returns a validated Atmospherical Conditions data object"""
393
-
394
- # # Return row from dataframe
395
- # now = time.replace(tzinfo=None).strftime("%Y-%m-%d %H:00:00+00:00")
396
- # row = self._weather_df.loc[self._weather_df["time"] == now].iloc[0]
397
-
398
- # atmosphere = {}
399
-
400
- # seeing = 0
401
- # transparency = 0
402
- # lifted_index = 0
403
-
404
- # if self._experimental_features:
405
- # seeing = await self._atmosphere.calculate_seeing(
406
- # temperature=row["air_temperature"],
407
- # humidity=row["relative_humidity"],
408
- # dew_point_temperature=row["dew_point_temperature"],
409
- # wind_speed=row["wind_speed"],
410
- # cloud_cover=row["cloud_area_fraction"],
411
- # altitude=self._location_data.elevation,
412
- # air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
413
- # )
414
- # transparency = await self._atmosphere.magnitude_degradation(
415
- # temperature=row["air_temperature"],
416
- # humidity=row["relative_humidity"],
417
- # dew_point_temperature=row["dew_point_temperature"],
418
- # wind_speed=row["wind_speed"],
419
- # cloud_cover=row["cloud_area_fraction"],
420
- # altitude=self._location_data.elevation,
421
- # air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
422
- # )
423
- # lifted_index = await self._atmosphere.calculate_lifted_index(
424
- # temperature=row["air_temperature"],
425
- # dew_point_temperature=row["dew_point_temperature"],
426
- # altitude=self._location_data.elevation,
427
- # air_pressure_at_sea_level=row["air_pressure_at_sea_level"],
428
- # )
429
- # else:
430
- # seeing = row["seeing"]
431
- # transparency = row["transparency"]
432
- # lifted_index = row["lifted_index"]
433
-
434
- # atmosphere = AtmosphereDataModel(
435
- # {
436
- # "seeing": seeing,
437
- # "transparency": transparency,
438
- # "lifted_index": lifted_index,
439
- # }
440
- # )
441
-
442
- # try:
443
- # return AtmosphereData(data=atmosphere)
444
- # except TypeError as ve:
445
- # _LOGGER.error(f"Failed to parse atmosphere data: {atmosphere}")
446
- # _LOGGER.error(ve)
447
- # return None
448
-
449
- # @typechecked
450
- # async def _get_condition(
451
- # self,
452
- # details_metno,
453
- # details_metno_next_1_hours,
454
- # details_metno_next_6_hours,
455
- # seeing,
456
- # transparency,
457
- # lifted_index,
458
- # ) -> ConditionData | None:
459
- # """Returns a validated Weather Conditions data object"""
460
-
461
- # cloudcover = details_metno.get("cloud_area_fraction")
462
- # cloud_area_fraction = details_metno.get("cloud_area_fraction")
463
- # cloudcover_high = details_metno.get("cloud_area_fraction_high")
464
- # cloudcover_medium = details_metno.get("cloud_area_fraction_medium")
465
- # cloudcover_low = details_metno.get("cloud_area_fraction_low")
466
- # fog = details_metno.get("fog_area_fraction")
467
- # rh2m = details_metno.get("relative_humidity")
468
- # wind_speed = details_metno.get("wind_speed")
469
- # wind_from_direction = details_metno.get("wind_from_direction")
470
- # temp2m = details_metno.get("air_temperature")
471
- # dewpoint2m = details_metno.get("dew_point_temperature")
472
- # weather = details_metno_next_1_hours.get("summary", {}).get("symbol_code")
473
- # weather6 = details_metno_next_6_hours.get("summary", {}).get("symbol_code")
474
- # precipitation_amount = details_metno_next_1_hours.get("details", {}).get("precipitation_amount")
475
- # precipitation_amount6 = details_metno_next_6_hours.get("details", {}).get("precipitation_amount")
476
-
477
- # if self._experimental_features:
478
- # # Calculate Fog Density
479
- # fog2m = await self._atmosphere.calculate_fog_density(temp2m, rh2m, dewpoint2m, wind_speed) * 100
480
- # else:
481
- # fog2m = fog
482
-
483
- # condition = ConditionDataModel(
484
- # {
485
- # "cloudcover": cloudcover,
486
- # "cloud_area_fraction": cloud_area_fraction,
487
- # "cloud_area_fraction_high": cloudcover_high,
488
- # "cloud_area_fraction_low": cloudcover_low,
489
- # "cloud_area_fraction_medium": cloudcover_medium,
490
- # "fog_area_fraction": max(fog, fog2m),
491
- # "fog2m": fog2m,
492
- # "seeing": seeing,
493
- # "transparency": transparency,
494
- # "lifted_index": lifted_index,
495
- # "condition_percentage": await self._calc_condition_percentage(
496
- # cloudcover_high=cloudcover_high,
497
- # cloudcover_medium=cloudcover_medium,
498
- # cloudcover_low=cloudcover_low,
499
- # fog=fog,
500
- # fog2m=fog2m,
501
- # seeing=seeing,
502
- # transparency=transparency,
503
- # wind_speed=wind_speed,
504
- # precipitation_amount=precipitation_amount,
505
- # ),
506
- # "rh2m": rh2m,
507
- # "wind_speed": wind_speed,
508
- # "wind_from_direction": wind_from_direction,
509
- # "temp2m": temp2m,
510
- # "dewpoint2m": dewpoint2m,
511
- # "weather": weather,
512
- # "weather6": weather6,
513
- # "precipitation_amount": precipitation_amount,
514
- # "precipitation_amount6": precipitation_amount6,
515
- # }
516
- # )
517
-
518
- # try:
519
- # return ConditionData(data=condition)
520
- # except TypeError as ve:
521
- # _LOGGER.error(f"Failed to parse condition data: {condition}")
522
- # _LOGGER.error(ve)
523
- # return None
524
-
525
353
  @typechecked
526
- async def _get_condition1(
354
+ async def _get_condition(
527
355
  self,
528
356
  time,
529
357
  ) -> ConditionData | None:
530
358
  """Returns a validated Weather Conditions data object"""
531
359
 
532
360
  # Return row from dataframe
533
- now = time.replace(tzinfo=None).strftime("%Y-%m-%d %H:00:00+00:00")
534
- row = self._weather_df.loc[self._weather_df["time"] == now].iloc[0]
361
+ timestamp = time.replace(tzinfo=None).strftime("%Y-%m-%d %H:00:00+00:00")
362
+ row = self._weather_df.loc[self._weather_df["time"] == timestamp].iloc[0]
535
363
 
536
364
  cloudcover = row["cloud_area_fraction"]
537
365
  cloud_area_fraction = row["cloud_area_fraction"]
@@ -689,70 +517,15 @@ class AstroWeather:
689
517
  forecast_time = self._test_datetime.replace(minute=0, second=0, microsecond=0)
690
518
  _LOGGER.debug("Forecast time: %s", str(forecast_time))
691
519
 
692
- if len(self._weather_data_metno) == 0:
693
- _LOGGER.error("Met.no data not available")
694
- return []
695
-
696
- # Met.no
697
- metno_index = 0
698
- seventimer_index = 0
699
-
700
- # Met.no: Search for start index
701
- for metno_index, datapoint in enumerate(self._weather_data_metno):
702
- if forecast_time == datetime.strptime(datapoint.get("time"), "%Y-%m-%dT%H:%M:%SZ"):
703
- break
704
- if metno_index > len(self._weather_data_metno):
705
- _LOGGER.error("Met.no start index not found")
520
+ if len(self._weather_df) == 0:
521
+ _LOGGER.error("Weather data not available")
706
522
  return []
707
- _LOGGER.debug("Met.no start index: %s", str(metno_index))
708
-
709
- details_metno = self._weather_data_metno[metno_index].get("data", {}).get("instant", {}).get("details", {})
710
- details_metno_next_1_hours = self._weather_data_metno[metno_index].get("data", {}).get("next_1_hours", {})
711
- details_metno_next_6_hours = self._weather_data_metno[metno_index].get("data", {}).get("next_6_hours", {})
712
-
713
- # Break condition
714
- if details_metno_next_1_hours is None:
715
- # No more hourly data
716
- _LOGGER.debug(
717
- "No more hourly data at %s",
718
- self._weather_data_metno[metno_index].get("time", {}),
719
- )
720
- return None
721
- if details_metno_next_6_hours is None:
722
- # No more 6-hourly data
723
- _LOGGER.debug(
724
- "No more 6-hourly data at %s",
725
- self._weather_data_metno[metno_index].get("time", {}),
726
- )
727
- return None
728
523
 
729
- # 7Timer: Search for start index
730
- seventimer_init = await cnv.anchor_timestamp(self._weather_data_seventimer_init)
731
- for row7 in self._weather_data_seventimer:
732
- if seventimer_init + timedelta(hours=row7["timepoint"]) > now:
733
- break
734
- seventimer_index += 1
735
- if seventimer_index < len(self._weather_data_seventimer):
736
- _LOGGER.debug("7Timer start index: %s", str(seventimer_index))
737
- details_seventimer = self._weather_data_seventimer[seventimer_index]
738
- else:
739
- details_seventimer = {
740
- "timepoint": 0,
741
- "seeing": _NOT_AVAILABLE,
742
- "transparency": _NOT_AVAILABLE,
743
- "lifted_index": _NOT_AVAILABLE,
744
- }
745
-
746
- # atmosphere_data = await self._get_atmosphere1(now)
524
+ data_index = int((self._weather_df["time"] == now.strftime("%Y-%m-%d %H:00:00+00:00")).idxmax())
525
+ _LOGGER.debug("Data index: %s", str(data_index))
747
526
 
748
527
  time_data = TimeDataModel(
749
528
  {
750
- # seventimer_init is "init" of 7timer astro data
751
- "seventimer_init": seventimer_init,
752
- # seventimer_timepoint is "timepoint" of 7timer astro data and defines the data for init + timepoint
753
- "seventimer_timepoint": details_seventimer["timepoint"],
754
- # Forecast_time is the actual datetime for the forecast data onwards in UTC
755
- # Corresponds to "time" in met data
756
529
  "forecast_time": forecast_time.replace(microsecond=0, tzinfo=timezone.utc),
757
530
  }
758
531
  )
@@ -770,7 +543,7 @@ class AstroWeather:
770
543
  # Time shift to UTC
771
544
  "time_shift": await self._astro_routines.time_shift(),
772
545
  # Remaining forecast data point in met.no data
773
- "forecast_length": (len(self._weather_data_metno) - metno_index),
546
+ "forecast_length": (len(self._weather_df) - data_index),
774
547
  # Location
775
548
  "location_data": self._location_data,
776
549
  # Astronomical routines
@@ -779,16 +552,7 @@ class AstroWeather:
779
552
  "darkness_data": await self._astro_routines.darkness_data(),
780
553
  "night_duration_astronomical": await self._astro_routines.night_duration_astronomical(),
781
554
  "deepsky_forecast": await self._get_deepsky_forecast(),
782
- # Met.no
783
- # "condition_data": await self._get_condition(
784
- # details_metno,
785
- # details_metno_next_1_hours,
786
- # details_metno_next_6_hours,
787
- # atmosphere_data.seeing,
788
- # atmosphere_data.transparency,
789
- # atmosphere_data.lifted_index,
790
- # ),
791
- "condition_data": await self._get_condition1(now),
555
+ "condition_data": await self._get_condition(now),
792
556
  # Uptonight objects
793
557
  "uptonight": await self._get_deepsky_objects(),
794
558
  "uptonight_bodies": await self._get_bodies(),
@@ -825,89 +589,22 @@ class AstroWeather:
825
589
  )
826
590
  _LOGGER.debug("Forecast time: %s", str(forecast_time))
827
591
 
828
- # 7Timer: Search for start index
829
- seventimer_init = await cnv.anchor_timestamp(self._weather_data_seventimer_init)
830
-
831
- # Anchor timestamp
832
- init_ts = await cnv.anchor_timestamp(self._weather_data_seventimer_init)
833
-
834
592
  utc_to_local_diff = self._astro_routines.utc_to_local_diff()
835
593
  _LOGGER.debug("UTC to local diff: %s", str(utc_to_local_diff))
836
594
 
837
- if len(self._weather_data_metno) == 0:
838
- _LOGGER.error("Met.no data not available")
595
+ if len(self._weather_df) == 0:
596
+ _LOGGER.error("Weather data not available")
839
597
  return []
840
598
 
841
- last_forecast_time = forecast_time
842
- for metno_index, datapoint in enumerate(self._weather_data_metno):
843
- datapoint_time = datetime.strptime(datapoint.get("time"), "%Y-%m-%dT%H:%M:%SZ").replace(
844
- microsecond=0, tzinfo=timezone.utc
845
- )
846
- if forecast_time > datapoint_time:
847
- continue
848
-
849
- if datapoint_time - last_forecast_time > timedelta(hours=1):
850
- break
851
-
852
- last_forecast_time = datapoint_time
853
- details_metno = datapoint.get("data", {}).get("instant", {}).get("details")
854
-
855
- if not self._test_data(
856
- details_metno,
857
- [
858
- "air_pressure_at_sea_level",
859
- "air_temperature",
860
- "cloud_area_fraction",
861
- "cloud_area_fraction_high",
862
- "cloud_area_fraction_low",
863
- "cloud_area_fraction_medium",
864
- "dew_point_temperature",
865
- "fog_area_fraction",
866
- "relative_humidity",
867
- "ultraviolet_index_clear_sky",
868
- "wind_from_direction",
869
- "wind_speed",
870
- ],
871
- ):
872
- _LOGGER.error("Missing Met.no data")
873
- break
599
+ data_index = int((self._weather_df["time"] == now.strftime("%Y-%m-%d %H:00:00+00:00")).idxmax())
600
+ _LOGGER.debug("Data index: %s", str(data_index))
874
601
 
875
- details_seventimer = self._get_data_seventimer_timer(
876
- seventimer_init,
877
- datetime.strptime(datapoint.get("time"), "%Y-%m-%dT%H:%M:%SZ"),
878
- )
879
- details_metno_next_1_hours = self._weather_data_metno[metno_index].get("data", {}).get("next_1_hours")
880
- details_metno_next_6_hours = self._weather_data_metno[metno_index].get("data", {}).get("next_6_hours")
881
-
882
- # Break condition
883
- if details_metno_next_1_hours is None:
884
- # No more hourly data
885
- _LOGGER.debug(
886
- "No more hourly data at %s",
887
- self._weather_data_metno[metno_index].get("time", {}),
888
- )
889
- break
890
- if details_metno_next_6_hours is None:
891
- # No more 6-hourly data
892
- _LOGGER.debug(
893
- "No more 6-hourly data at %s",
894
- self._weather_data_metno[metno_index].get("time", {}),
895
- )
896
- break
897
-
898
- forecast_time = datetime.strptime(datapoint.get("time"), "%Y-%m-%dT%H:%M:%SZ").replace(
899
- microsecond=0, tzinfo=timezone.utc
900
- )
901
- # atmosphere_data = await self._get_atmosphere1(forecast_time)
602
+ last_forecast_time = forecast_time
603
+ for index, row in self._weather_df.iterrows():
604
+ forecast_time = row["time"].replace(microsecond=0, tzinfo=timezone.utc)
902
605
 
903
606
  td = TimeDataModel(
904
607
  {
905
- # seventimer_init is "init" of 7timer astro data
906
- "seventimer_init": init_ts,
907
- # seventimer_timepoint is "timepoint" of 7timer astro data and defines the data for init + timepoint
908
- "seventimer_timepoint": details_seventimer["timepoint"],
909
- # Forecast_time is the actual datetime for the forecast data onwards in UTC
910
- # Corresponds to "time" in met data
911
608
  "forecast_time": forecast_time, # timestamp
912
609
  }
913
610
  )
@@ -918,22 +615,13 @@ class AstroWeather:
918
615
  _LOGGER.error(f"Failed to parse location data model data: {time_data}")
919
616
  _LOGGER.error(ve)
920
617
 
618
+ print(forecast_time)
921
619
  item = ForecastDataModel(
922
620
  {
923
621
  # Time data
924
622
  "time_data": time_data,
925
- "hour": datetime.strptime(
926
- datapoint.get("time"), "%Y-%m-%dT%H:%M:%SZ"
927
- ).hour, # forecast_time.hour % 24,
928
- # "condition_data": await self._get_condition(
929
- # details_metno,
930
- # details_metno_next_1_hours,
931
- # details_metno_next_6_hours,
932
- # atmosphere_data.seeing,
933
- # atmosphere_data.transparency,
934
- # atmosphere_data.lifted_index,
935
- # ),
936
- "condition_data": await self._get_condition1(forecast_time),
623
+ "hour": row["time"].hour, # forecast_time.hour % 24,
624
+ "condition_data": await self._get_condition(row["time"]),
937
625
  }
938
626
  )
939
627
 
@@ -963,16 +651,9 @@ class AstroWeather:
963
651
  if self._forecast_data is None:
964
652
  await self._get_forecast_data(FORECAST_TYPE_HOURLY, 72)
965
653
 
966
- # Anchor timestamp
967
- init_ts = await cnv.anchor_timestamp(self._weather_data_seventimer_init)
968
-
969
654
  utc_to_local_diff = self._astro_routines.utc_to_local_diff()
970
655
  _LOGGER.debug("UTC to local diff: %s", str(utc_to_local_diff))
971
656
 
972
- # if self._forecast_data is None:
973
- # _LOGGER.error("Met.no forecast data not available")
974
- # return []
975
-
976
657
  # Create forecast
977
658
  forecast_dayname = ""
978
659
  start_forecast_hour = 0
@@ -1037,7 +718,6 @@ class AstroWeather:
1037
718
  if details_forecast.forecast_time.hour == sun_next_rising.hour or index >= (forecast_data_len - 1):
1038
719
  item = NightlyConditionsDataModel(
1039
720
  {
1040
- "seventimer_init": init_ts,
1041
721
  "dayname": forecast_dayname,
1042
722
  "hour": start_forecast_hour,
1043
723
  "nightly_conditions": interval_points,
@@ -1334,27 +1014,14 @@ class AstroWeather:
1334
1014
 
1335
1015
  # Convert to DataFrame
1336
1016
  weather_df_seventimer = pd.DataFrame(records)
1337
-
1338
- self._weather_data_seventimer = astro_dataseries
1339
- self._weather_data_seventimer_init = json_data_astro.get("init")
1340
1017
  else:
1341
1018
  # Fake 7timer weather data if service is broken
1342
1019
  # This eliminates consideration of seeing, transparency, and lifted_index
1343
1020
  # and switches automatically to experimental functions.
1344
- self._weather_data_seventimer_init = datetime.now(UTC).replace(tzinfo=None).strftime("%Y%m%d%H")
1345
- self._weather_data_seventimer = []
1346
1021
  records = []
1347
1022
  now = datetime.now(UTC)
1348
1023
 
1349
1024
  for index in range(0, 20):
1350
- self._weather_data_seventimer.append(
1351
- {
1352
- "timepoint": index * 3,
1353
- "seeing": _NOT_AVAILABLE,
1354
- "transparency": _NOT_AVAILABLE,
1355
- "lifted_index": _NOT_AVAILABLE,
1356
- }
1357
- )
1358
1025
  time = (now + timedelta(hours=index * 3)).replace(
1359
1026
  minute=0, second=0, microsecond=0, tzinfo=timezone.utc
1360
1027
  )
@@ -1373,7 +1040,7 @@ class AstroWeather:
1373
1040
  # Convert to DataFrame
1374
1041
  weather_df_seventimer = pd.DataFrame(records)
1375
1042
 
1376
- print(weather_df_seventimer)
1043
+ # print(weather_df_seventimer)
1377
1044
  return weather_df_seventimer
1378
1045
 
1379
1046
  @typechecked
@@ -1425,26 +1092,6 @@ class AstroWeather:
1425
1092
  if not use_running_session:
1426
1093
  await session.close()
1427
1094
 
1428
- @typechecked
1429
- def _get_data_seventimer_timer(self, anchor_timestamp, datetime) -> Dict[str, Any]:
1430
- """Return 7Timer datapoint of interest."""
1431
-
1432
- seventimer_index = 0
1433
- for index, row7 in enumerate(self._weather_data_seventimer):
1434
- if anchor_timestamp + timedelta(hours=row7["timepoint"]) > datetime:
1435
- seventimer_index = index - 1
1436
- break
1437
- # index += 1
1438
- if seventimer_index >= len(self._weather_data_seventimer):
1439
- return {
1440
- "timepoint": row7["timepoint"],
1441
- "seeing": _NOT_AVAILABLE,
1442
- "transparency": _NOT_AVAILABLE,
1443
- "lifted_index": _NOT_AVAILABLE,
1444
- }
1445
- else:
1446
- return self._weather_data_seventimer[seventimer_index]
1447
-
1448
1095
  # #########################################################################
1449
1096
  # Met.no
1450
1097
  # #########################################################################
@@ -1496,12 +1143,6 @@ class AstroWeather:
1496
1143
  # Convert to DataFrame
1497
1144
  weather_df_metno = pd.DataFrame(records)
1498
1145
 
1499
- print(weather_df_metno)
1500
- if dataseries is not None:
1501
- if len(dataseries) > 0:
1502
- self._weather_data_metno = dataseries
1503
- self._weather_data_metno_init = dataseries[0].get("time")
1504
-
1505
1146
  return weather_df_metno
1506
1147
 
1507
1148
  @typechecked
@@ -1564,10 +1205,6 @@ class AstroWeather:
1564
1205
 
1565
1206
  _LOGGER.debug("Updating data from Open-Meteo")
1566
1207
 
1567
- import socket
1568
- from aiohttp.client import ClientError, ClientResponseError, ClientSession
1569
- import numpy as np
1570
-
1571
1208
  use_running_session = self._session and not self._session.closed
1572
1209
 
1573
1210
  if use_running_session:
@@ -1575,14 +1212,6 @@ class AstroWeather:
1575
1212
  else:
1576
1213
  session = ClientSession(timeout=ClientTimeout(total=DEFAULT_TIMEOUT))
1577
1214
 
1578
- # Setup the Open-Meteo API client with cache and retry on error
1579
- # cache_session = requests_cache.CachedSession(".cache", expire_after=3600)
1580
- # retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
1581
- # openmeteo = openmeteo_requests.Client(session=retry_session)
1582
- # openmeteo = openmeteo_requests.Client()
1583
-
1584
- # Make sure all required weather variables are listed here
1585
- # The order of variables in hourly or daily is important to assign them correctly below
1586
1215
  url = "https://api.open-meteo.com/v1/forecast"
1587
1216
  params = {
1588
1217
  "latitude": self._location_data.latitude,
@@ -1600,16 +1229,11 @@ class AstroWeather:
1600
1229
  "wind_direction_10m",
1601
1230
  ],
1602
1231
  "timezone": self._location_data.timezone_info,
1603
- # "temperature_unit": "celcius",
1232
+ # "temperature_unit": "C",
1604
1233
  "precipitation_unit": "mm",
1605
1234
  "wind_speed_unit": "ms",
1606
1235
  "models": self._openmeteo_forecast,
1607
1236
  }
1608
- # DWD Germany: icon_seamless
1609
- # Met.no: metno_seamless
1610
- # NOAA U.S.: gfs_seamless
1611
- # ECMWF: ecmwf_ifs025
1612
- # responses = openmeteo.weather_api(url, params=params)
1613
1237
 
1614
1238
  try:
1615
1239
  # async with asyncio.timeout(self.request_timeout):
@@ -1644,65 +1268,27 @@ class AstroWeather:
1644
1268
  {"Content-Type": content_type, "response": text},
1645
1269
  )
1646
1270
 
1647
- # Process first location. Add a for-loop for multiple locations or weather models
1648
- # response = responses[0]
1649
-
1650
- # Process hourly data. The order of variables needs to be the same as requested.
1271
+ # Process hourly data
1651
1272
  data = await response.json()
1652
- hourly = data.get("hourly") # response[0].Hourly()
1653
- # print(hourly)
1654
-
1655
- # pp(hourly.get("hourly"))
1656
- # hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy()
1657
- # hourly_relative_humidity_2m = hourly.Variables(1).ValuesAsNumpy()
1658
- # hourly_dew_point_2m = hourly.Variables(2).ValuesAsNumpy()
1659
- # hourly_precipitation = hourly.Variables(3).ValuesAsNumpy()
1660
- # hourly_cloud_cover = hourly.Variables(4).ValuesAsNumpy()
1661
- # hourly_cloud_cover_low = hourly.Variables(5).ValuesAsNumpy()
1662
- # hourly_cloud_cover_mid = hourly.Variables(6).ValuesAsNumpy()
1663
- # hourly_cloud_cover_high = hourly.Variables(7).ValuesAsNumpy()
1664
- # hourly_wind_speed_10m = hourly.Variables(8).ValuesAsNumpy()
1665
- # hourly_wind_direction_10m = hourly.Variables(9).ValuesAsNumpy()
1666
- hourly_temperature_2m = np.array(hourly.get("temperature_2m"))
1667
- hourly_relative_humidity_2m = np.array(hourly.get("relative_humidity_2m"))
1668
- hourly_dew_point_2m = np.array(hourly.get("dew_point_2m"))
1669
- hourly_precipitation = np.array(hourly.get("precipitation"))
1670
- hourly_cloud_cover = np.array(hourly.get("cloud_cover"))
1671
- hourly_cloud_cover_low = np.array(hourly.get("cloud_cover_low"))
1672
- hourly_cloud_cover_mid = np.array(hourly.get("cloud_cover_mid"))
1673
- hourly_cloud_cover_high = np.array(hourly.get("cloud_cover_high"))
1674
- hourly_wind_speed_10m = np.array(hourly.get("wind_speed_10m"))
1675
- hourly_wind_direction_10m = np.array(hourly.get("wind_direction_10m"))
1676
- hourly_time = np.array(hourly.get("time"))
1677
-
1678
- # print(hourly)
1679
- # print(hourly.get("time"))
1680
- # print(hourly_temperature_2m)
1681
- # print(hourly_time)
1682
- # hourly_data = {
1683
- # "time": pd.date_range(
1684
- # start=pd.to_datetime(hourly.Time(), unit="s", utc=True),
1685
- # end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True),
1686
- # freq=pd.Timedelta(seconds=hourly.Interval()),
1687
- # inclusive="left",
1688
- # )
1689
- # }
1690
- hourly_data = {}
1691
- hourly_data["time"] = hourly_time
1692
- hourly_data["openmeteo_temperature_2m"] = hourly_temperature_2m
1693
- hourly_data["openmeteo_relative_humidity_2m"] = hourly_relative_humidity_2m
1694
- hourly_data["openmeteo_dew_point_2m"] = hourly_dew_point_2m
1695
- hourly_data["openmeteo_precipitation"] = hourly_precipitation
1696
- hourly_data["openmeteo_cloud_cover"] = hourly_cloud_cover
1697
- hourly_data["openmeteo_cloud_cover_low"] = hourly_cloud_cover_low
1698
- hourly_data["openmeteo_cloud_cover_mid"] = hourly_cloud_cover_mid
1699
- hourly_data["openmeteo_cloud_cover_high"] = hourly_cloud_cover_high
1700
- hourly_data["openmeteo_wind_speed_10m"] = hourly_wind_speed_10m
1701
- hourly_data["openmeteo_wind_direction_10m"] = hourly_wind_direction_10m
1273
+ hourly = data.get("hourly")
1274
+
1275
+ hourly_data = {
1276
+ "time": np.array(hourly.get("time")),
1277
+ "openmeteo_temperature_2m": np.array(hourly.get("temperature_2m")),
1278
+ "openmeteo_relative_humidity_2m": np.array(hourly.get("relative_humidity_2m")),
1279
+ "openmeteo_dew_point_2m": np.array(hourly.get("dew_point_2m")),
1280
+ "openmeteo_precipitation": np.array(hourly.get("precipitation")),
1281
+ "openmeteo_cloud_cover": np.array(hourly.get("cloud_cover")),
1282
+ "openmeteo_cloud_cover_low": np.array(hourly.get("cloud_cover_low")),
1283
+ "openmeteo_cloud_cover_mid": np.array(hourly.get("cloud_cover_mid")),
1284
+ "openmeteo_cloud_cover_high": np.array(hourly.get("cloud_cover_high")),
1285
+ "openmeteo_wind_speed_10m": np.array(hourly.get("wind_speed_10m")),
1286
+ "openmeteo_wind_direction_10m": np.array(hourly.get("wind_direction_10m")),
1287
+ }
1702
1288
 
1703
1289
  weather_df_openmeteo = pd.DataFrame(data=hourly_data)
1704
1290
  weather_df_openmeteo["time"] = pd.to_datetime(weather_df_openmeteo["time"])
1705
1291
  weather_df_openmeteo["time"] = weather_df_openmeteo["time"].dt.tz_localize("UTC")
1706
1292
 
1707
- print(weather_df_openmeteo)
1293
+ # print(weather_df_openmeteo)
1708
1294
  return weather_df_openmeteo
@@ -29,8 +29,6 @@ from pyastroweatherio.const import (
29
29
  class TimeDataModel(TypedDict):
30
30
  """Model for time data"""
31
31
 
32
- seventimer_init: datetime
33
- seventimer_timepoint: int
34
32
  forecast_time: datetime
35
33
 
36
34
 
@@ -39,8 +37,6 @@ class TimeData:
39
37
  """A representation of the time data of forecasts."""
40
38
 
41
39
  def __init__(self, *, data: TimeDataModel):
42
- self.seventimer_init = data["seventimer_init"]
43
- self.seventimer_timepoint = data["seventimer_timepoint"]
44
40
  self.forecast_time = data["forecast_time"]
45
41
 
46
42
 
@@ -64,24 +60,6 @@ class GeoLocationData:
64
60
  self.timezone_info = data["timezone_info"]
65
61
 
66
62
 
67
- class AtmosphereDataModel(TypedDict):
68
- """Model for atmosperic conditions"""
69
-
70
- seeing: float
71
- transparency: float
72
- lifted_index: float
73
-
74
-
75
- @typechecked
76
- class AtmosphereData:
77
- """A representation of atmospheric condition base class."""
78
-
79
- def __init__(self, *, data: AtmosphereDataModel):
80
- self.seeing = data["seeing"]
81
- self.transparency = data["transparency"]
82
- self.lifted_index = data["lifted_index"]
83
-
84
-
85
63
  class SunDataModel(TypedDict):
86
64
  """Model for Sun data"""
87
65
 
@@ -1138,7 +1116,6 @@ class ForecastData:
1138
1116
  class NightlyConditionsDataModel(TypedDict):
1139
1117
  """Model for nightly conditions data"""
1140
1118
 
1141
- seventimer_init: datetime
1142
1119
  dayname: str
1143
1120
  hour: int
1144
1121
  nightly_conditions: list
@@ -1151,7 +1128,6 @@ class NightlyConditionsData:
1151
1128
  """A representation of nights Sky Quality Data."""
1152
1129
 
1153
1130
  def __init__(self, *, data: NightlyConditionsDataModel):
1154
- self.seventimer_init = data["seventimer_init"]
1155
1131
  self.dayname = data["dayname"]
1156
1132
  self.hour = data["hour"]
1157
1133
  self.nightly_conditions = data["nightly_conditions"]
@@ -17,3 +17,11 @@ class ResultError(AstroWeatherError):
17
17
  """Define an error related to the result returned from a request."""
18
18
 
19
19
  pass
20
+
21
+
22
+ class OpenMeteoError(Exception):
23
+ """Generic OpenMeteo exception."""
24
+
25
+
26
+ class OpenMeteoConnectionError(OpenMeteoError):
27
+ """OpenMeteo connection exception."""
@@ -342,7 +342,6 @@ class AtmosphericRoutines:
342
342
  # Ensure fog density is within the valid range [0, 1]
343
343
  adjusted_fog_density = max(0, min(1, adjusted_fog_density))
344
344
 
345
- # print(temp2m, rh2m, dewpoint2m, wind_speed, humidity_factor, temp_dew_diff, fog_density, adjusted_fog_density)
346
345
  return float(adjusted_fog_density)
347
346
 
348
347
  # @typechecked
@@ -362,6 +361,35 @@ class AtmosphericRoutines:
362
361
 
363
362
  # return fog2m
364
363
 
364
+ # #####################################################
365
+ # Calculate dew point at 2m
366
+ # #####################################################
367
+ @typechecked
368
+ async def calculate_dew_point(self, temp2m, rh2m) -> float:
369
+ """
370
+ Calculate the dew point temperature given air temperature and relative humidity
371
+ using Magnus formula.
372
+
373
+ Parameters:
374
+ temp (float): Air temperature in °C.
375
+ humidity (float): Relative humidity in % (0-100).
376
+
377
+ Args:
378
+ - temp2m: Surface temperature in Celsius.
379
+ - rh2m: Humidity in Percent.
380
+
381
+ Returns:
382
+ - float: Dew point temperature in °C.
383
+ """
384
+ # Constants
385
+ a = 17.62
386
+ b = 243.12
387
+
388
+ # Calculate alpha
389
+ alpha = math.log(rh2m / 100) + (a * temp2m) / (b + temp2m)
390
+
391
+ return (b * alpha) / (a - alpha)
392
+
365
393
  # #####################################################
366
394
  # Atmospheric calculations
367
395
  # #####################################################
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyastroweatherio
3
- Version: 0.62.0.dev20
3
+ Version: 0.62.0.dev22
4
4
  Summary: Python Wrapper for 7Timer and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -3,7 +3,7 @@ from setuptools import setup
3
3
  setup(
4
4
  name="pyastroweatherio",
5
5
  packages=["pyastroweatherio"],
6
- version="0.62.0.dev20",
6
+ version="0.62.0.dev22",
7
7
  license="MIT",
8
8
  description="Python Wrapper for 7Timer and Met.no REST API",
9
9
  long_description=" ".join(