Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Add clip limits to Nightshade floating point calculations #1989

Merged
merged 1 commit into from
Jan 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions lib/cartopy/feature/nightshade.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,12 @@ def __init__(self, date=None, delta=0.1, refraction=-0.83,

# Solve the generalized equation for omega0, which is the
# angle of sunrise/sunset from solar noon
omega0 = np.rad2deg(np.arccos(np.sin(np.deg2rad(refraction)) /
np.cos(np.deg2rad(y))))
# We need to clip the input to arccos to [-1, 1] due to floating
# point precision and arccos creating nans for values outside
# of the domain
arccos_tmp = np.clip(np.sin(np.deg2rad(refraction)) /
np.cos(np.deg2rad(y)), -1, 1)
omega0 = np.rad2deg(np.arccos(arccos_tmp))

# Fill the longitude values from the offset for midnight.
# This needs to be a closed loop to fill the polygon.
Expand Down
11 changes: 10 additions & 1 deletion lib/cartopy/tests/feature/test_nightshade.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import pytest

from cartopy.feature.nightshade import _julian_day, _solar_position
from cartopy.feature.nightshade import _julian_day, _solar_position, Nightshade


def test_julian_day():
Expand Down Expand Up @@ -44,3 +44,12 @@ def test_solar_position(dt, true_lat, true_lon):
lat, lon = _solar_position(dt)
assert pytest.approx(true_lat, 0.1) == lat
assert pytest.approx(true_lon, 0.1) == lon


def test_nightshade_floating_point():
# Smoke test for clipping nightshade floating point values
date = datetime(1999, 12, 31, 12)

# This can cause an error with floating point precision if it is
# set to exactly -6 and arccos input is not clipped to [-1, 1]
Nightshade(date, refraction=-6.0, color='none')