Skip to content

relativity: return zero, not NaN, for deflection along the line of sight - #1159

Open
Glupozombie wants to merge 1 commit into
skyfielders:masterfrom
Glupozombie:fix-deflection-nan
Open

Glupozombie wants to merge 1 commit into
skyfielders:masterfrom
Glupozombie:fix-deflection-nan

Conversation

@Glupozombie

Copy link
Copy Markdown

What is wrong

relativity._compute_deflection returns NaN when the target lies on the line from the observer through a deflector, and when the deflector sits exactly at the observer:

    flag = abs(edotp) <= 0.99999999999

    fac1 = 2.0 * GS / (C * C * emag * AU_M * rmass)   # emag can be 0
    fac2 = 1.0 + qdote                                # can be 0

    return flag * fac1 * (pdotq * ehat - edotp * qhat) / fac2 * pmag

flag is meant to switch the correction off in exactly those geometries, but it cannot: NumPy performs the division anyway, 0 / 0 is NaN, and multiplying NaN by False gives NaN, not zero. The comment above flag says the deflection "is set to zero", and today it is not.

Measured on current master (1.55):

pe = array([1.0, 0.0, 0.0])                 # deflector relative to observer
_compute_deflection(array([-2.0, 0.0, 0.0]), pe, 1047.3486)
# [nan nan nan]   RuntimeWarning: invalid value encountered in divide

It is not only the mathematically exact case. Off the line by 1e-8 au, still NaN; by 1e-6 au, zero. So a whole cone around the alignment — the cone flag was written to cover, roughly an arcsecond — currently produces NaN instead of zero.

NaN there is not a cosmetic problem: it travels through apparent() into positions and times, and a NaN time then blows up in the caller. That is the chain reported in #1086, where Skyfield ≤ 1.53 returned a NaN setting time for Saturn on 1980-12-27 and .utc_datetime() raised:

settings found: 1 flags: [np.True_]
  flagged event tt = nan
  utc_datetime() raised OverflowError: signed integer is less than minimum
  utc_iso() raised ValueError: cannot convert float NaN to integer

#1086 itself stopped reproducing in 1.54, because find_risings() and find_settings() now call .apparent(no_deflectors) and skip deflection entirely. But the defective expression is still in relativity.py, and any direct apparent() call in that geometry still gets NaN — so this is a live defect, just no longer reachable from the almanac routines.

The change

-    fac1 = 2.0 * GS / (C * C * emag * AU_M * rmass)
-    fac2 = 1.0 + qdote
+    fac1 = 2.0 * GS / (C * C * where(emag, emag, 1.0) * AU_M * rmass)
+    fac2 = where(flag, 1.0 + qdote, 1.0)

plus a comment recording why the guards are needed. emag keeps its position in the product so the rounding is untouched. Substituting 1.0 where flag is False is safe in both directions: when fac2 is zero the numerator is zero too, so the correction genuinely is zero; and when flag is False but fac2 is not, False * x was already zero for any finite x, and was NaN for the infinite x that the old code could also produce.

Verification

No behaviour change where the old code was finite. 4000 randomized observer/target/deflector geometries, a third of them forced into near-alignment or exact anti-alignment:

trials=4000  old NaN=261  new NaN=0  differing finite results=0  max|diff|=0

Every one of the 261 geometries where the old code produced NaN now produces a finite result, and for every geometry where both are finite the two outputs are bitwise identical.

The degenerate cases now return zero, silently. With warnings.simplefilter('error') — the same posture as test-code.sh, which exports PYTHONWARNINGS=error — all of [-2,0,0], [-1,0,0], [-2,1e-8,0], [-2,1e-12,0] against pe=[1,0,0], and pe=[0,0,0], return exactly [0. 0. 0.] and raise no warning.

New test: test_deflection_along_the_line_of_sight_is_zero in skyfield/tests/test_deflection.py. On unpatched master it fails with RuntimeWarning: invalid value encountered in divide at relativity.py:162; with the change, test_deflection.py runs 7 tests and all pass.

No regressions. Running the test suite here, 187 passed, 1 failed, 165 errors against a baseline of 186 passed, 1 failed, 165 errors on unpatched master — the extra pass is the new test, and the failure and error counts are identical. They are all environmental in this container: the failure is test_stars_tycho2 needing to download tyc_main_head.dat, and the errors are test_against_novas (127), test_elementslib (26), test_against_horizons (8) and test_strs_and_reprs (4), which need the NOVAS library, Horizons access or data files I do not have. Nine further test modules were skipped because they import assay, which is not on PyPI; I could not run them.

Related

Measurements for #1086 across versions, scanning Saturn rise and set for all 367 days of 1980 at the equator with de421.bsp, are in the issue: Jun 15 divide by zero and Dec 27 invalid value plus a NaN True setting event on 1.50; Dec 27 only on 1.53; nothing on 1.54 or master. I could not pin the 1.53 NaN to a single instant — a 5-minute grid over both dates is clean even on 1.53 — so it came from one of the sub-second iterations inside the search, which is consistent with the cone described above.

_compute_deflection has two divisors that can be zero: emag, when the
deflector sits exactly at the observer, and fac2 = 1 + qdote, when the
target lies on the line from the observer through the deflector. The
`flag` that detects the second case is meant to switch the correction off,
but it cannot: NumPy performs the division anyway, 0 / 0 is NaN, and
multiplying NaN by False gives NaN rather than zero. The result is NaN
positions from apparent(), which become NaN times, which raise
OverflowError when a caller converts them to a datetime.

The failure is not confined to exact alignment. Off the line by 1e-8 au
the result is still NaN; by 1e-6 au it is zero. So the whole cone that
`flag` was written to cover, roughly an arcsecond wide, produced NaN.

Guard both divisors with where(), keeping emag in its original position in
the product so the rounding is unchanged. Substituting 1.0 where `flag` is
False is safe both ways: when fac2 is zero the numerator is zero too, so
the deflection genuinely is zero, and when `flag` is False but fac2 is
not, False * x was already zero for finite x and NaN for the infinite x
the old expression could also produce.

Across 4000 randomized geometries, a third forced into near or exact
alignment, the old code produced NaN in 261 and the new code in none,
while every geometry where both are finite agrees bitwise.

Test: test_deflection_along_the_line_of_sight_is_zero, which fails on
master with "RuntimeWarning: invalid value encountered in divide" and
passes with the change. The suite goes from 186 to 187 passing with
unchanged failure and error counts.

This is the expression behind the NaN setting times reported for Saturn
on 1980-12-27 in issue skyfielders#1086. That report stopped reproducing in 1.54,
when find_risings and find_settings began skipping deflection, but the
defect was still reachable from any direct apparent() call.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant