pyastroweatherio 0.75.0.dev1__tar.gz → 0.75.0.dev3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (16) hide show
  1. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/PKG-INFO +1 -1
  2. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/helper_functions.py +398 -131
  3. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio.egg-info/PKG-INFO +1 -1
  4. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/setup.py +1 -1
  5. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/LICENSE +0 -0
  6. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/README.md +0 -0
  7. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/__init__.py +0 -0
  8. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/client.py +0 -0
  9. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/const.py +0 -0
  10. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/dataclasses.py +0 -0
  11. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio/errors.py +0 -0
  12. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio.egg-info/SOURCES.txt +0 -0
  13. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio.egg-info/dependency_links.txt +0 -0
  14. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio.egg-info/requires.txt +0 -0
  15. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/pyastroweatherio.egg-info/top_level.txt +0 -0
  16. {pyastroweatherio-0.75.0.dev1 → pyastroweatherio-0.75.0.dev3}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyastroweatherio
3
- Version: 0.75.0.dev1
3
+ Version: 0.75.0.dev3
4
4
  Summary: Python Wrapper for OpenMeteo and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -59,6 +59,30 @@ class AtmosphericRoutines:
59
59
  # Air pressure at sea level in hPa
60
60
  # aerosol_density in kg/m^3
61
61
 
62
+ # ---------- small internal helpers ----------
63
+ @staticmethod
64
+ def _is_missing(values: dict) -> list[str]:
65
+ return [name for name, val in values.items() if val is None or (isinstance(val, float) and math.isnan(val))]
66
+
67
+ @staticmethod
68
+ def _svp_hpa_magnus(Tc: float) -> float:
69
+ """
70
+ Saturation vapor pressure over water (hPa), Magnus-Tetens.
71
+ Good for typical near-surface temps.
72
+ """
73
+ return 6.112 * math.exp((17.62 * Tc) / (243.12 + Tc))
74
+
75
+ @staticmethod
76
+ def _mixing_ratio_gpkg(e_hpa: float, p_hpa: float) -> float:
77
+ """Mixing ratio (g/kg) from vapor pressure e (hPa) and pressure p (hPa)."""
78
+ eps = 621.97 # g/kg * (hPa/hPa)
79
+ denom = max(1e-6, (p_hpa - e_hpa))
80
+ return eps * (e_hpa / denom)
81
+
82
+ @staticmethod
83
+ def _sigmoid(x: float) -> float:
84
+ return 1.0 / (1.0 + math.exp(-x))
85
+
62
86
  # #####################################################
63
87
  # Calculate lifted index
64
88
  # #####################################################
@@ -120,55 +144,105 @@ class AtmosphericRoutines:
120
144
  return lifted_index
121
145
 
122
146
  # _11
123
- def _tlcl_bolton(self, T, Td):
124
- # T, Td in Kelvin. Bolton (1980) eqn 15 surrogate:
125
- return 1.0 / (1.0 / (Td - 56.0) + math.log(T / Td) / 800.0) + 56.0 # K
126
-
127
- def _moist_adiabat_to(self, T_lcl, p_lcl, p_target):
128
- # Bolton moist-adiabatic approximation via equivalent potential temp (θe)
129
- # For brevity, use a simple iterative moist lapse (Γ_m) integrator; step dp.
130
- T = T_lcl
131
- p = p_lcl
132
- dp = -5.0 # hPa step upward
133
- while p + dp >= p_target:
134
- # Γ_m ~ g*(1 + Lq/(Rd T)) / (cp + (L^2 q ε)/(R_d T^2)) [approx]
135
- # keep it simple or use Bolton’s formulas if you prefer
136
- gamma_m = 4.5 # K/km crude; replace with proper Γ_m(T,p)
137
- dz = 8.0 * abs(dp) # ~8 m/hPa
138
- T -= gamma_m * (dz / 1000.0)
139
- p += dp
140
- return T
147
+ # def _tlcl_bolton(self, T, Td):
148
+ # # T, Td in Kelvin. Bolton (1980) eqn 15 surrogate:
149
+ # return 1.0 / (1.0 / (Td - 56.0) + math.log(T / Td) / 800.0) + 56.0 # K
150
+
151
+ # def _moist_adiabat_to(self, T_lcl, p_lcl, p_target):
152
+ # # Bolton moist-adiabatic approximation via equivalent potential temp (θe)
153
+ # # For brevity, use a simple iterative moist lapse (Γ_m) integrator; step dp.
154
+ # T = T_lcl
155
+ # p = p_lcl
156
+ # dp = -5.0 # hPa step upward
157
+ # while p + dp >= p_target:
158
+ # # Γ_m ~ g*(1 + Lq/(Rd T)) / (cp + (L^2 q ε)/(R_d T^2)) [approx]
159
+ # # keep it simple or use Bolton’s formulas if you prefer
160
+ # gamma_m = 4.5 # K/km crude; replace with proper Γ_m(T,p)
161
+ # dz = 8.0 * abs(dp) # ~8 m/hPa
162
+ # T -= gamma_m * (dz / 1000.0)
163
+ # p += dp
164
+ # return T
141
165
 
142
166
  @typechecked
143
167
  async def calculate_lifted_index_11(
144
168
  self, temperature, altitude, dew_point_temperature, air_pressure_at_sea_level
145
169
  ) -> None | float:
146
- if any(
147
- x is None or (isinstance(x, float) and math.isnan(x))
148
- for x in (temperature, altitude, dew_point_temperature, air_pressure_at_sea_level)
149
- ):
170
+ """
171
+ Returns a rough Lifted Index (LI) proxy in °C.
172
+
173
+ Real LI requires an environmental temperature profile (a sounding).
174
+ With only surface data, we:
175
+ - Estimate station pressure from sea-level pressure + altitude.
176
+ - Estimate LCL temperature using a common approximation.
177
+ - Estimate parcel temperature at 500 hPa via:
178
+ dry-adiabatic to LCL, then a simplified moist-adiabatic adjustment.
179
+ - Estimate environmental temperature at 500 hPa using a standard lapse proxy.
180
+
181
+ Output is clamped to [-7, +7].
182
+ """
183
+ values = {
184
+ "temperature": temperature,
185
+ "altitude": altitude,
186
+ "dew_point_temperature": dew_point_temperature,
187
+ "air_pressure_at_sea_level": air_pressure_at_sea_level,
188
+ }
189
+ missing = self._is_missing(values)
190
+ if missing:
191
+ _LOGGER.warning(f"calculate_lifted_index: None/NaN inputs: {', '.join(missing)}")
150
192
  return None
151
193
 
152
- T = temperature + 273.15
153
- Td = dew_point_temperature + 273.15
154
- p_sfc = air_pressure_at_sea_level # hPa
194
+ T = float(temperature) # °C
195
+ Td = float(dew_point_temperature)
196
+ alt = float(altitude)
197
+ p0 = float(air_pressure_at_sea_level) # hPa
198
+
199
+ # Estimate station pressure at altitude (use your existing helper)
200
+ # (This uses a standard-atmosphere-like relationship and is good enough here.)
201
+ p_sfc = float(self._calculate_adjusted_pressure(p0, alt))
202
+
203
+ # --- LCL temperature approximation (Bolton-style quick form) ---
204
+ # Use Kelvin
205
+ Tk = T + 273.15
206
+ Tdk = Td + 273.15
207
+ # Prevent nonsense
208
+ Tdk = min(Tk, max(180.0, Tdk))
209
+
210
+ # Approx LCL temperature (K)
211
+ # This is a widely used approximation; stable and simple.
212
+ Tlcl = 1.0 / (1.0 / (Tdk - 56.0) + math.log(Tk / Tdk) / 800.0) + 56.0
213
+
214
+ # Approx LCL pressure using Poisson (dry adiabatic) relation
215
+ # p_lcl = p_sfc * (Tlcl/Tk)^(cp/Rd) with cp/Rd ≈ 3.5
216
+ p_lcl = p_sfc * (Tlcl / Tk) ** 3.5
217
+
218
+ # Parcel temperature at 500 hPa:
219
+ p_target = 500.0
220
+ if p_lcl <= p_target:
221
+ # LCL above 500 hPa: parcel stays unsaturated to 500
222
+ T_parcel_500 = Tk * (p_target / p_sfc) ** (2.0 / 7.0) # κ ≈ 0.286
223
+ else:
224
+ # Dry-adiabatic to LCL, then “moist-ish” to 500 hPa.
225
+ # Very simplified moist-adiabatic cooling: use a reduced exponent.
226
+ # κ_moist ~ 0.12–0.18 depending on moisture; use RH proxy via Td depression.
227
+ dT = max(0.0, min(20.0, T - Td))
228
+ k_moist = 0.12 + 0.06 * self._sigmoid((5.0 - dT) / 1.5) # wetter air => smaller cooling exponent
229
+ T_parcel_500 = Tlcl * (p_target / p_lcl) ** k_moist
155
230
 
156
- # LCL (Bolton or Romps)
157
- T_lcl = self._tlcl_bolton(T, Td)
158
- # p_lcl from Poisson eqn dry-adiabatic: θ = T (1000/p)^(R/cp) constant
159
- Rd_cp = 0.2854
160
- theta = T * (1000.0 / p_sfc) ** Rd_cp
161
- p_lcl = 1000.0 / ((theta / T_lcl) ** (1.0 / Rd_cp))
231
+ # Environmental temperature at 500 hPa:
232
+ # Without a sounding, use a lapse-rate estimate from surface temperature.
233
+ # 500 hPa height is typically ~5.5 km; use (5.5km - altitude) thickness.
234
+ z500 = 5500.0
235
+ dz = max(0.0, z500 - alt) # meters
236
+ env_lapse = 6.5 / 1000.0 # K/m (standard-ish)
237
+ T_env_500 = (T + 273.15) - env_lapse * dz
162
238
 
163
- # Lift moist-adiabatically to 500 hPa
164
- T_parcel_500 = self._moist_adiabat_to(T_lcl, p_lcl, 500.0)
239
+ # LI = T_env(500) - T_parcel(500), in °C
240
+ LI = T_env_500 - T_parcel_500
165
241
 
166
- # Get environmental T at 500 hPa (best: supply it!)
167
- # Fallback: standard atmosphere lapse from 850→500
168
- T_env_500 = -20.0 + 273.15 # placeholder: expose as parameter for real data
242
+ # Clamp like your current implementation
243
+ LI = max(-7.0, min(7.0, float(LI)))
169
244
 
170
- LI = T_env_500 - T_parcel_500 # K
171
- return float(max(-7.0, min(7.0, LI)))
245
+ return LI
172
246
 
173
247
  # #####################################################
174
248
  # Calculate magniture degradation based on transparency
@@ -253,53 +327,100 @@ class AtmosphericRoutines:
253
327
  # Convert transparency to magnitude degradation
254
328
  magnitude_degradation = self._transparency_to_magnitude_degradation(transparency)
255
329
 
256
- # _LOGGER.debug(
257
- # "Magnitude Degradation: {:.2f} mag (".format(magnitude_degradation)
258
- # + "Lifted Index (LI): {:.2f} °C, ".format(lifted_index)
259
- # + "Seeing: {:.2f} arcsec, ".format(seeing)
260
- # + "Estimated Atmospheric Transparency: {:.2f})".format(transparency)
261
- # )
262
-
263
330
  return magnitude_degradation
264
331
 
265
332
  # _11
266
- def _airmass_kasten_young(self, zenith_deg):
267
- z = math.radians(zenith_deg)
268
- return 1.0 / (math.cos(z) + 0.50572 * (96.07995 - zenith_deg) ** (-1.6364))
333
+ # def _airmass_kasten_young(self, zenith_deg):
334
+ # z = math.radians(zenith_deg)
335
+ # return 1.0 / (math.cos(z) + 0.50572 * (96.07995 - zenith_deg) ** (-1.6364))
269
336
 
270
- def _extinction_components(self, pressure_hpa, rh, vis_km):
271
- # Rayleigh ~0.106 mag/airmass at sea level (V band), scale with pressure
272
- k_R = 0.106 * (pressure_hpa / 1013.25)
337
+ # def _extinction_components(self, pressure_hpa, rh, vis_km):
338
+ # # Rayleigh ~0.106 mag/airmass at sea level (V band), scale with pressure
339
+ # k_R = 0.106 * (pressure_hpa / 1013.25)
273
340
 
274
- # Aerosol from visibility: tau ≈ 3.912/Vis; convert to mag/airmass: k = 1.086*tau
275
- tau_a = 3.912 / max(1.0, vis_km)
276
- k_a = 1.086 * tau_a * 0.6 # 0.6 factor so "haze" vis isn’t overly punitive; tune
341
+ # # Aerosol from visibility: tau ≈ 3.912/Vis; convert to mag/airmass: k = 1.086*tau
342
+ # tau_a = 3.912 / max(1.0, vis_km)
343
+ # k_a = 1.086 * tau_a * 0.6 # 0.6 factor so "haze" vis isn’t overly punitive; tune
277
344
 
278
- # Ozone & water vapor: small constants unless you have columns
279
- k_O3 = 0.03
280
- k_H2O = 0.00 # set >0 in NIR or humid site with strong bands
345
+ # # Ozone & water vapor: small constants unless you have columns
346
+ # k_O3 = 0.03
347
+ # k_H2O = 0.00 # set >0 in NIR or humid site with strong bands
281
348
 
282
- return k_R, k_a, k_O3, k_H2O
349
+ # return k_R, k_a, k_O3, k_H2O
283
350
 
284
351
  @typechecked
285
352
  async def magnitude_degradation_11(
286
353
  self, temperature, humidity, cloud_cover, wind_speed, altitude, dew_point_temperature, air_pressure_at_sea_level
287
354
  ) -> None | float:
288
- # Estimate visibility from RH (section 1), cap by cloud cover (simple screen)
289
- vis_km = self._visibility_koschmieder(humidity)
290
- if cloud_cover is not None:
291
- # Reduce effective vis as clouds rise; linear knockdown
292
- vis_km /= 1.0 + 3.0 * (cloud_cover / 100.0)
355
+ """
356
+ Returns a "magnitude degradation" (mag) proxy.
357
+
358
+ Improvements vs old version:
359
+ - Transparency -> mag uses a physically meaningful transform:
360
+ mag_loss ≈ -2.5 * log10(transparency)
361
+ - Uses improved LI + seeing as modifiers.
362
+ - Keeps output bounded by MAG_DEGRATION_MAX.
363
+ """
364
+ values = {
365
+ "temperature": temperature,
366
+ "humidity": humidity,
367
+ "cloud_cover": cloud_cover,
368
+ "wind_speed": wind_speed,
369
+ "altitude": altitude,
370
+ "dew_point_temperature": dew_point_temperature,
371
+ "air_pressure_at_sea_level": air_pressure_at_sea_level,
372
+ }
373
+ missing = self._is_missing(values)
374
+ if missing:
375
+ _LOGGER.warning(f"magnitude_degradation: None/NaN inputs: {', '.join(missing)}")
376
+ return None
377
+
378
+ # Compute ingredients
379
+ lifted_index = await self.calculate_lifted_index(
380
+ temperature, altitude, dew_point_temperature, air_pressure_at_sea_level
381
+ )
382
+ seeing = await self.calculate_seeing(
383
+ temperature,
384
+ humidity,
385
+ dew_point_temperature,
386
+ wind_speed,
387
+ cloud_cover,
388
+ altitude,
389
+ air_pressure_at_sea_level,
390
+ )
391
+
392
+ if lifted_index is None or seeing is None:
393
+ return None
394
+
395
+ rh = max(0.0, min(100.0, float(humidity)))
396
+ cc = max(0.0, min(100.0, float(cloud_cover)))
397
+ ws = max(0.0, float(wind_speed))
398
+ alt = max(0.0, float(altitude))
399
+
400
+ # Base transparency from simple, bounded components
401
+ # (weights are chosen for stable behavior)
402
+ hum_pen = self._sigmoid((rh - 75.0) / 10.0) # humidity haze risk
403
+ cloud_pen = (cc / 100.0) ** 1.2 # clouds dominate quickly
404
+ wind_pen = self._sigmoid((ws - 6.0) / 2.5) * 0.4 # blowing aerosols
405
+ li_pen = self._sigmoid((-lifted_index - 1.0) / 2.0) * 0.35 # unstable air -> more haze/cloud risk
406
+ seeing_pen = self._sigmoid((seeing - 2.0) / 0.8) * 0.25 # poor seeing correlates w/ bad transparency sometimes
293
407
 
294
- k_R, k_a, k_O3, k_H2O = self._extinction_components(air_pressure_at_sea_level, humidity, vis_km)
295
- k_total = k_R + k_a + k_O3 + k_H2O
408
+ # altitude improves transparency a bit (less column)
409
+ alt_gain = 1.0 - 0.12 * (1.0 - math.exp(-alt / 1800.0))
296
410
 
297
- # If you know target altitude, compute zenith angle; otherwise assume X~1.2 median
298
- X = 1.2
299
- delta_m = k_total * X
411
+ # Combine into transparency 0..1
412
+ penalty = 0.18 * hum_pen + 0.50 * cloud_pen + 0.12 * wind_pen + 0.10 * li_pen + 0.10 * seeing_pen
413
+ transparency = max(0.02, min(1.0, (1.0 - penalty) * alt_gain))
300
414
 
301
- # Optionally clamp
302
- return float(min(MAG_DEGRATION_MAX, max(0.0, delta_m)))
415
+ # Convert transparency to mag loss (extinction-like)
416
+ mag_loss = -2.5 * math.log10(transparency)
417
+
418
+ # Clamp to global max
419
+ mag_loss = min(float(MAG_DEGRATION_MAX), float(mag_loss))
420
+ if mag_loss < 0.0:
421
+ mag_loss = 0.0
422
+
423
+ return float(mag_loss)
303
424
 
304
425
  # #####################################################
305
426
  # Calculate atmospheric seeing
@@ -378,58 +499,180 @@ class AtmosphericRoutines:
378
499
  seeing_factor = C * (water_vapor_pressure / 10) ** 0.25 * (wind_speed / 10) ** 0.75 * relative_pressure
379
500
  seeing = 0.98 / seeing_factor
380
501
 
381
- # _LOGGER.debug(
382
- # "Seeing: {:.2f} arcsec (".format(seeing)
383
- # + "Water Vapor Pressure: {:.2f} mbar, ".format(water_vapor_pressure)
384
- # + "Wind Speed: {:.2f} m/s, ".format(wind_speed)
385
- # + "Relative Pressure: {:.2f} mbar, ".format(relative_pressure)
386
- # + "Seeing Factor: {:.2f})".format(seeing_factor)
387
- # )
388
-
389
502
  if seeing > SEEING_MAX:
390
503
  seeing = SEEING_MAX # max out seeing
391
504
 
392
505
  return seeing
393
506
 
394
507
  # Seeing with Hufnagel–Valley 5/7 profile
395
- def _hv57_cn2(self, z, A=1.7e-14, v=20.0):
396
- term1 = 0.00594 * (v / 27.0) ** 2 * (1e-5 * z) ** 10 * math.exp(-z / 1000.0)
397
- term2 = 2.7e-16 * math.exp(-z / 1500.0)
398
- term3 = A * math.exp(-z / 100.0)
508
+ # def _hv57_cn2(self, z, A=1.7e-14, v=20.0):
509
+ # term1 = 0.00594 * (v / 27.0) ** 2 * (1e-5 * z) ** 10 * math.exp(-z / 1000.0)
510
+ # term2 = 2.7e-16 * math.exp(-z / 1500.0)
511
+ # term3 = A * math.exp(-z / 100.0)
399
512
 
400
- return term1 + term2 + term3
513
+ # return term1 + term2 + term3
401
514
 
402
- def _seeing_from_hv57(self, wavelength_m=5.5e-7, v=20.0, A=1.7e-14, zmax=20000.0):
403
- # integrate Cn^2 dz (simple Riemann sum)
404
- dz = 25.0
405
- z = 0.0
406
- integral = 0.0
515
+ # def _seeing_from_hv57(self, wavelength_m=5.5e-7, v=20.0, A=1.7e-14, zmax=20000.0):
516
+ # # integrate Cn^2 dz (simple Riemann sum)
517
+ # dz = 25.0
518
+ # z = 0.0
519
+ # integral = 0.0
407
520
 
408
- while z <= zmax:
409
- integral += self._hv57_cn2(z, A=A, v=v) * dz
410
- z += dz
411
- k = 2.0 * math.pi / wavelength_m
412
- r0 = (0.423 * k * k * integral) ** (-3.0 / 5.0)
413
- beta_rad = 0.98 * wavelength_m / r0
521
+ # while z <= zmax:
522
+ # integral += self._hv57_cn2(z, A=A, v=v) * dz
523
+ # z += dz
524
+ # k = 2.0 * math.pi / wavelength_m
525
+ # r0 = (0.423 * k * k * integral) ** (-3.0 / 5.0)
526
+ # beta_rad = 0.98 * wavelength_m / r0
414
527
 
415
- return beta_rad * (180.0 / math.pi) * 3600.0 # arcsec
528
+ # return beta_rad * (180.0 / math.pi) * 3600.0 # arcsec
416
529
 
417
530
  @typechecked
418
531
  async def calculate_seeing_11(
419
532
  self, temperature, humidity, dew_point_temperature, wind_speed, cloud_cover, altitude, air_pressure_at_sea_level
420
533
  ) -> None | float:
421
- # Map your measured 10 m wind to a free-atmosphere proxy v (cap 10–35 m/s)
422
- v_free = max(10.0, min(35.0, 2.0 * wind_speed + 10.0))
423
-
424
- # Strengthen ground layer at low altitudes / high RH:
425
- A = (
426
- 1.7e-14
427
- * (1.0 + 0.5 * max(0.0, (humidity - 70.0) / 30.0))
428
- * (1.0 + 0.3 * max(0.0, (500.0 - altitude) / 500.0))
429
- )
430
- seeing = self._seeing_from_hv57(v=v_free, A=A)
534
+ """
535
+ Seeing estimate in arcseconds (lower = better), tuned to behave more like
536
+ common forecast products (e.g., meteoblue) in terms of directionality.
431
537
 
432
- return min(SEEING_MAX, seeing)
538
+ Still a heuristic: with only surface inputs you cannot model free-atmosphere seeing.
539
+ """
540
+ values = {
541
+ "temperature": temperature,
542
+ "humidity": humidity,
543
+ "dew_point_temperature": dew_point_temperature,
544
+ "wind_speed": wind_speed,
545
+ "cloud_cover": cloud_cover,
546
+ "altitude": altitude,
547
+ "air_pressure_at_sea_level": air_pressure_at_sea_level,
548
+ }
549
+ missing = self._is_missing(values)
550
+ if missing:
551
+ _LOGGER.warning(f"calculate_seeing: None/NaN inputs: {', '.join(missing)}")
552
+ return None
553
+
554
+ T = float(temperature)
555
+ Td = float(dew_point_temperature)
556
+ rh = max(0.0, min(100.0, float(humidity)))
557
+ ws = max(0.0, float(wind_speed))
558
+ cc = max(0.0, min(100.0, float(cloud_cover)))
559
+ alt = max(0.0, float(altitude))
560
+
561
+ # --- proxies ---
562
+ # Dewpoint depression: very small dT => near-saturation / stable layer; can be good or bad.
563
+ # We use it gently: extremes (very large dT) can correlate with strong radiative cooling + BL turbulence.
564
+ dT = max(0.0, min(25.0, T - Td))
565
+
566
+ # Wind: best seeing often with light breeze (mixes BL), worse with dead calm or strong wind
567
+ # U-shaped penalty centered near ~3 m/s.
568
+ wind_opt = 3.0
569
+ wind_sigma = 2.5
570
+ wind_pen = 1.0 - math.exp(-((ws - wind_opt) ** 2) / (2.0 * wind_sigma ** 2)) # 0 near optimum, ->1 away
571
+
572
+ # Humidity: very high RH often accompanies haze/fog layers and BL issues; moderate is fine.
573
+ humid_pen = self._sigmoid((rh - 85.0) / 7.0) # ramps above ~85%
574
+
575
+ # Clouds: weak proxy for turbulence aloft. Keep influence small.
576
+ cloud_pen = (cc / 100.0) ** 1.5
577
+
578
+ # Altitude: generally helps a bit.
579
+ alt_gain = 1.0 - 0.12 * (1.0 - math.exp(-alt / 1800.0)) # ~1.0 sea level -> ~0.88 high alt
580
+
581
+ # Very large dT (very dry) can mean strong surface cooling at night => local turbulence.
582
+ # Mild penalty that only kicks in past ~8°C depression.
583
+ dry_pen = self._sigmoid((dT - 8.0) / 2.5)
584
+
585
+ # --- combine into a "quality" score (higher = better) ---
586
+ # Start near 1.0, subtract penalties.
587
+ quality = 1.0
588
+ quality -= 0.35 * wind_pen
589
+ quality -= 0.25 * humid_pen
590
+ quality -= 0.10 * cloud_pen
591
+ quality -= 0.20 * dry_pen
592
+
593
+ # Apply altitude improvement
594
+ quality *= alt_gain
595
+
596
+ # Clamp quality to sane range
597
+ quality = max(0.05, min(0.98, quality))
598
+
599
+ # Map to seeing arcsec: better quality => smaller FWHM
600
+ # Choose a realistic range for forecasts (tunable):
601
+ best = 0.7 # arcsec
602
+ worst = 4.0 # arcsec
603
+ seeing = worst - (worst - best) * quality
604
+
605
+ # Clamp to your global max (if you have one)
606
+ seeing = max(0.4, min(float(SEEING_MAX), seeing))
607
+
608
+ # _LOGGER.debug(float(seeing))
609
+ return float(seeing)
610
+
611
+ # """
612
+ # Returns a rough seeing estimate in arcseconds.
613
+
614
+ # Improvements vs old version:
615
+ # - Avoids unit-mismatch water-vapor-pressure math.
616
+ # - Uses stable, bounded mapping driven by:
617
+ # * wind (mechanical turbulence),
618
+ # * dewpoint depression & RH (near-surface stability / saturation),
619
+ # * cloud cover (proxy for active layers),
620
+ # * altitude (usually helps boundary-layer seeing).
621
+ # """
622
+ # values = {
623
+ # "temperature": temperature,
624
+ # "humidity": humidity,
625
+ # "dew_point_temperature": dew_point_temperature,
626
+ # "wind_speed": wind_speed,
627
+ # "cloud_cover": cloud_cover,
628
+ # "altitude": altitude,
629
+ # "air_pressure_at_sea_level": air_pressure_at_sea_level,
630
+ # }
631
+ # missing = self._is_missing(values)
632
+ # if missing:
633
+ # _LOGGER.warning(f"calculate_seeing: None/NaN inputs: {', '.join(missing)}")
634
+ # return None
635
+
636
+ # T = float(temperature)
637
+ # Td = float(dew_point_temperature)
638
+ # rh = max(0.0, min(100.0, float(humidity)))
639
+ # ws = max(0.0, float(wind_speed))
640
+ # cc = max(0.0, min(100.0, float(cloud_cover)))
641
+ # alt = max(0.0, float(altitude))
642
+
643
+ # # Boundary-layer proxies
644
+ # dT = max(-5.0, min(25.0, T - Td)) # dewpoint depression
645
+ # wind_term = math.log1p(ws) # grows slowly, stable
646
+ # cloud_term = (cc / 100.0) ** 0.7 # more sensitive at low-mid cloud
647
+ # humid_term = self._sigmoid((rh - 80.0) / 8.0) # ramps up beyond ~80%
648
+
649
+ # # Altitude often helps (thinner BL, less heat shimmer).
650
+ # # Don’t overdo it; this is a mild improvement curve.
651
+ # altitude_gain = 0.85 + 0.15 * math.exp(-alt / 1800.0) # ~1.0 at sea lvl -> ~0.85 at high alt
652
+
653
+ # # Base seeing floor and contributions (tunable constants)
654
+ # seeing = (
655
+ # (
656
+ # 0.75
657
+ # + 0.55 * wind_term
658
+ # + 0.65 * cloud_term
659
+ # + 0.45 * humid_term
660
+ # + 0.35
661
+ # * self._sigmoid(
662
+ # (dT - 4.0) / 1.8
663
+ # ) # very dry air often correlates with better seeing aloft, but BL can still shimmer; this keeps it moderate
664
+ # )
665
+ # * altitude_gain
666
+ # )
667
+
668
+ # # Clamp
669
+ # if seeing > SEEING_MAX:
670
+ # seeing = SEEING_MAX
671
+ # if seeing < 0.4:
672
+ # seeing = 0.4
673
+
674
+ # _LOGGER.debug(float(seeing))
675
+ # return float(seeing)
433
676
 
434
677
  # #####################################################
435
678
  # Calculate fog density at 2m
@@ -492,36 +735,60 @@ class AtmosphericRoutines:
492
735
  return float(adjusted_fog_density)
493
736
 
494
737
  # Visibility via Koschmieder
495
- def _visibility_koschmieder(self, rh, base_beta=0.02):
496
- """
497
- Crude RH→extinction: beta_ext = base_beta * f(RH).
498
- base_beta ~0.02 1/km is a hazy baseline; ramp up sharply near saturation.
499
- Returns visibility (km).
500
- """
501
- # Sigmoid that explodes as RH→100%
502
- f = 1.0 + 20.0 / (1.0 + math.exp(-(rh - 95.0) / 1.5)) # ~1 below 90–92%, jumps past 95%
503
- beta = base_beta * f # 1/km
504
-
505
- return 3.912 / beta # km
738
+ # def _visibility_koschmieder(self, rh, base_beta=0.02):
739
+ # """
740
+ # Crude RH→extinction: beta_ext = base_beta * f(RH).
741
+ # base_beta ~0.02 1/km is a hazy baseline; ramp up sharply near saturation.
742
+ # Returns visibility (km).
743
+ # """
744
+ # # Sigmoid that explodes as RH→100%
745
+ # f = 1.0 + 20.0 / (1.0 + math.exp(-(rh - 95.0) / 1.5)) # ~1 below 90–92%, jumps past 95%
746
+ # beta = base_beta * f # 1/km
747
+
748
+ # return 3.912 / beta # km
506
749
 
507
750
  @typechecked
508
751
  async def calculate_fog_density_11(self, temp2m, rh2m, dewpoint2m, wind_speed) -> float:
509
- # Favor calm, near-saturated, small (T-Td)
510
- vis_km = self._visibility_koschmieder(rh2m)
511
-
512
- # Penalize higher winds (disperse fog): halve “density” per ~5 m/s
513
- wind_factor = math.exp(-wind_speed / 5.0)
752
+ """
753
+ Returns a 0..1 "fog likelihood/density" proxy.
514
754
 
515
- # Map visibility to density: 0..1 over 0–5 km range
516
- dens_from_vis = max(0.0, min(1.0, (5.0 - min(vis_km, 5.0)) / 5.0))
755
+ Improvements vs old version:
756
+ - Uses dewpoint depression (T - Td) + RH with a logistic curve (stable).
757
+ - Stronger penalty for wind mixing (fog dispersal).
758
+ - Handles edge cases (negative RH, etc.) safely.
759
+ """
760
+ # Validate
761
+ values = {"temp2m": temp2m, "rh2m": rh2m, "dewpoint2m": dewpoint2m, "wind_speed": wind_speed}
762
+ missing = self._is_missing(values)
763
+ if missing:
764
+ _LOGGER.warning(f"calculate_fog_density: None/NaN inputs: {', '.join(missing)}")
765
+ return 0.0
766
+
767
+ rh = max(0.0, min(100.0, float(rh2m)))
768
+ T = float(temp2m)
769
+ Td = float(dewpoint2m)
770
+ ws = max(0.0, float(wind_speed))
771
+
772
+ # Dewpoint depression in °C
773
+ dT = max(-5.0, min(30.0, T - Td))
774
+
775
+ # Core saturation term:
776
+ # - Fog becomes likely when RH is high AND dewpoint depression is small.
777
+ # - Map into 0..1 smoothly.
778
+ sat_score = (
779
+ 2.2 * (rh - 92.0) / 8.0 # RH ~92% begins to matter strongly
780
+ - 2.6 * (dT - 1.2) / 1.8 # dT <~ 1–2°C drives fog likelihood
781
+ )
782
+ sat = self._sigmoid(sat_score)
517
783
 
518
- # Add a (T-Td) pinch
519
- td_spread = max(0.0, min(1.0, 1.0 - abs(temp2m - dewpoint2m) / 3.0))
784
+ # Wind dispersal: calm helps fog; moderate wind destroys it.
785
+ # This is a smooth decay; tune the 2.5–4.0 range if you want.
786
+ wind_decay = math.exp(-ws / 3.0)
520
787
 
521
- density = dens_from_vis * 0.7 + td_spread * 0.3
522
- density *= wind_factor
788
+ # Final, clipped
789
+ fog = sat * wind_decay
523
790
 
524
- return float(max(0.0, min(1.0, density)))
791
+ return float(max(0.0, min(1.0, fog)))
525
792
 
526
793
  # #####################################################
527
794
  # Calculate dew point at 2m
@@ -561,7 +828,7 @@ class AtmosphericRoutines:
561
828
  Calculate the adjusted pressure at a given altitude above sea level.
562
829
  """
563
830
 
564
- lapse_rate = -0.0065 # Temperature lapse rate in K/m
831
+ lapse_rate = 0.0065 # Temperature lapse rate in K/m
565
832
  temperature_sea_level = 288.15 # Temperature at sea level in K
566
833
  gravity = 9.80665 # Acceleration due to gravity in m/s^2
567
834
  molar_mass_air = 0.02896 # Molar mass of Earth's air in kg/mol
@@ -613,7 +880,7 @@ class AtmosphericRoutines:
613
880
  # B = 265.5
614
881
 
615
882
  # Calculate vapor pressure using Magnus-Tetens formula
616
- e = 0.61078 * math.exp((A * temperature) / (temperature + B))
883
+ e = 6.1078 * math.exp((A * temperature) / (temperature + B))
617
884
 
618
885
  return e
619
886
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyastroweatherio
3
- Version: 0.75.0.dev1
3
+ Version: 0.75.0.dev3
4
4
  Summary: Python Wrapper for OpenMeteo and Met.no REST API
5
5
  Home-page: https://github.com/mawinkler/pyastroweatherio
6
6
  Author: Markus Winkler
@@ -11,7 +11,7 @@ if os.path.isfile(requirement_path):
11
11
  setup(
12
12
  name="pyastroweatherio",
13
13
  packages=["pyastroweatherio"],
14
- version="0.75.0.dev1",
14
+ version="0.75.0.dev3",
15
15
  license="MIT",
16
16
  description="Python Wrapper for OpenMeteo and Met.no REST API",
17
17
  long_description=" ".join(