pysolar
pysolar copied to clipboard
OverflowError: math range error when calculating get_radiation_direct at sunrise.
Hi, I came across a bug where, at first glance, there seems to be a problem calculating the direct radiation right around sunrise and sunset.
Here's the error message.
2022-03-29 06:36:32 - collector.elevation - INFO - Going up.
Exception in thread Collector:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "/home/balta/git/Hepa/collector/collector.py", line 537, in run
self.update_sun_position()
File "/home/balta/git/Hepa/collector/collector.py", line 519, in update_sun_position
self.sun.update(
File "/home/balta/git/Hepa/collector/collector.py", line 95, in update
rad = radiation.get_radiation_direct(date, self.elevation)
File "/home/balta/git/Hepa/venv/lib/python3.9/site-packages/pysolar/radiation.py", line 50, in get_radiation_direct
return flux * math.exp(-1 * optical_depth * air_mass_ratio) * is_daytime
OverflowError: math range error
I'm using pysolar==0.10.
Yeah, that looks like a bug.
Could you post the inputs that produced the error?
Sorry for the wait. My logging was insufficient to reproduce the bug with the info I had.
Here's a snippet that should help you reproduce the bug.
import datetime
import pytz
from math import isfinite
from pysolar.solar import (
get_position as get_sun_position,
radiation,
)
latitude = 45.4924
longitude = -72.3150
date = datetime.datetime(2022, 4, 3, 10, 27, 15, 830398, tzinfo=datetime.timezone.utc)
azymuth, elevation = get_sun_position(latitude, longitude, date)
rad = radiation.get_radiation_direct(date, elevation)
In get_radiation_direct radiation.py:50
we have this code return flux * math.exp(-1 * optical_depth * air_mass_ratio) * is_daytime
air_mass_ratio: -961255.0150425568
altitude_deg: -5.960518136860493e-05
day: 93
flux=1159.3544752333482
is_daytime: False
optical_depth: 0.16979271842852264
when: datetime
then math.exp(-1 * optical_depth * air_mass_ratio)
is yielding OverflowError: math range error
.
I'm wondering why bother do that math.exp()
if we then multiply it by False
which is 0
?
Unfortunately, I'm not knowledgeable enough in the math behind computing the sun's radiation to properly solve this.
That’s trying to calculate roughly e^100000, which is around 10^43000, so that’s where the overflow is happening.
I suspect the right solution is to alter get_air_mass_ratio() so that it is restricted to a reasonable range.
Patches welcome, if anyone wants to think that through.