Skip to content

Compute the Gauss–Legendre angles and weights in θ - #433

Open
jasonmcewen wants to merge 2 commits into
mainfrom
fix/gl-nodes-weights
Open

jasonmcewen wants to merge 2 commits into
mainfrom
fix/gl-nodes-weights

Conversation

@jasonmcewen

Copy link
Copy Markdown
Contributor

Summary

s2fft's Gauss–Legendre (GL) sample angles and quadrature weights lose accuracy near the poles, by an amount that grows quickly with L. At L = 2048 the polar angles are 3e-14 rad from the exact nodes, and the polar weights are wrong by 7e-11 (relative).

This PR computes both from one routine: Newton's method in θ, with the last step and the weights in double-double arithmetic. Against binary128, every angle and every weight is correctly rounded in every case tested. That is every node of every L from 1 to 4096, and of L = 8191, 8192, 8193, 16383 and 16384.

When the angles and the weights are both needed, as in the forward transform, it is also faster than now from L ≈ 1024, and much faster at large L. No public function or signature changes.

Fixes #432.

The problem

The angles.

  • s2_samples.thetas(L, "gl") takes np.arccos of numpy's leggauss roots.
  • Near x = ±1, arccos amplifies any error δx in a root by 1/sin θ:
    $$\delta\theta \approx \frac{\delta x}{\sin\theta}.$$
  • The first node is at θ ≈ 2.4/L. So even roots correct to the rounding level of x ≈ 1 give polar angles whose error, in ulps of θ, grows roughly as L².

The weights.

  • quadrature.quad_weights_gl_theta_only, and its JAX copy, find their own nodes by Newton's method in x. They stop when |Δx| ≤ 1e-14, and evaluate P_L′ at the previous iterate.
  • The weights are therefore less accurate than they could be, and they belong to slightly different nodes from the sample angles.

Measured against binary128 nodes and weights, on main (d7afe6d):

L max angle error in ulps of θ angles correctly rounded max weight error (relative), numpy / JAX
64 9.4e-16 rad 119 66% 9.3e-14 / 5.1e-14
512 2.2e-15 rad (at 0.62°) 1,926 71% 2.2e-13 / 6.0e-13
1024 4.8e-15 rad 7,433 71% 2.2e-12 / 1.8e-12
2048 3.2e-14 rad (at 179.93°) 147,254 70% 7.0e-11 / 5.2e-11
4096 6.2e-14 rad (at 0.03°) 573,980 70% 6.7e-11 / 2.0e-10

In every case the largest errors are in the first three rings from a pole.

Effect on the transforms.

  • Synthesis evaluates the field at s2fft's angles. A band-limited field of amplitude |f| changes near a pole at a rate of up to about L·|f| per radian, so an angle error δθ can cost up to about L·|f|·δθ. At L = 4096, with δθ = 6.2e-14 rad, that is about 2.5e-10 for a field of unit amplitude: an order-of-magnitude estimate, not a measurement.
  • Analysis multiplies each ring by its weight, so each polar ring carries its weight's error: 2e-12 to 2e-10 for L = 1024 to 4096.

The fix

A new private module, s2fft/sampling/_gauss_legendre.py, computes the angles and the weights together.

  1. Newton's method in θ.
    • With s = sin²(θ/2) and D_ℓ = P_ℓ − P_{ℓ−1}, the three-term recurrence becomes
      $$(\ell+1),D_{\ell+1} = \ell,D_\ell - 2s(2\ell+1),P_\ell,\qquad P_{\ell+1} = P_\ell + D_{\ell+1}.$$
      s enters only multiplicatively. No rounded x = 1 − 2s is formed, so its relative accuracy is kept near the poles.
    • The derivative is
      $$\frac{dP_L}{d\theta} = \frac{L,(D_L - 2sP_L)}{2\sqrt{s(1-s)}}.$$
    • The iteration starts from θ_k = π(4k − 1)/(4L + 2), for the northern half, and stops within a few ulps.
  2. One last Newton step in double-double arithmetic. It uses Dekker's two-sum and two-product, with sin(θ/2) from its Taylor series in double-double. The new value is then the root to about 1e-30, and it is rounded once.
    • The southern nodes are π − θ, with a double-double π.
    • For odd L, the middle node is fl(π/2).
  3. The weights at the same nodes, also in double-double:
    $$w = \frac{2}{\left(dP_L/d\theta\right)^2} = \frac{8s(1-s)}{L^2,(D_L - 2sP_L)^2}.$$
    • They are evaluated at the last iterate θ, from the same double-double P_L and D_L as the last Newton step.
    • They are carried to the root θ + δ by Legendre's equation, which gives P_L″ = −cot θ · P_L′ at a zero. To second order in δ:
      $$w(\theta + \delta) = w(\theta)\left[1 + 2\delta\cot\theta + \left(\cot^2\theta - 1 - L(L+1)\right)\delta^2\right].$$
      Then they are rounded once.
    • For odd L, the middle weight is evaluated at s = ½ exactly, on the same path.
  4. Where it is used.
    • s2_samples.thetas(L, "gl"), quadrature.quad_weights_gl_theta_only and quadrature_jax.quad_weights_gl_theta_only now call it. The JAX function stays jitted, and its weights are constants at trace time. The torch weights wrap the JAX ones.
    • The result is cached per L (lru_cache, 16 entries). L goes through operator.index first. The cached arrays are read-only, and callers get copies.
    • L < 1 raises ValueError, as before.

Design choices.

  • Correct rounding needs the double-double steps. Newton's method in θ in float64 alone is about 30 lines of code instead of about 110. It gives angles within 5.5 ulp and weights within 5e-14 up to L = 4096, far better than now but not correctly rounded, so it was set aside.
  • Correct rounding is observed, not proved. The double-double values are accurate to about 1e-30, so a value within about 1e-14 ulp of a rounding midpoint could round the wrong way. Among the northern angles for L ≤ 4096, the closest to a midpoint is 1e-7 ulp from it.
  • The cache is there because thetas and the weights are called on every NumPy transform. Concurrent first calls for the same L may compute it twice, with equal results.

Results

Accuracy against binary128 (Newton in x with the three-term recurrence, then arccos). Every node of every L from 1 to 4096 was checked, and of L = 8191, 8192, 8193, 16383 and 16384: 8.4 million nodes in all.

  • Every angle and every weight is correctly rounded.
  • The numpy and JAX weights are identical.
  • The rounded weights sum to 2 to within 1.2e-16, not exactly.
L 64 512 1024 2048 4096
max angle error, main → this PR (ulp) 119 → 0.50 1,926 → 0.50 7,433 → 0.50 147,254 → 0.50 573,980 → 0.50
max weight error (relative), main → this PR 9.3e-14 → 1.0e-16 2.2e-13 → 1.0e-16 2.2e-12 → 1.1e-16 7.0e-11 → 1.0e-16 6.7e-11 → 1.1e-16

Time for a first call, single-threaded on one core of an aarch64 host. Later calls are cached.

L 64 512 1024 2048 4096
main: angles (leggauss) and weights 0.8 ms 19 ms 97 ms 0.70 s 6.8 s
main: weights alone 0.3 ms 3.1 ms 7.4 ms 18 ms 47 ms
this PR: angles and weights 2.2 ms 19 ms 45 ms 0.11 s 0.29 s

This PR computes the angles and weights together, so a first call costs the same whether it is for the angles, the weights or both. A first call for the weights alone is therefore slower than now: about 6 times at L = 4096. On main the angles alone cost about as much as leggauss, which solves an O(L³) eigenvalue problem; Newton's method in θ is O(L²).

Tests

  • New tests, in test_quadrature.py.
    • test_gl_angles_and_weights_against_mpmath compares the angles and weights, for exact equality, with 40-digit Newton iterations in x using mpmath.legendre, an independent route.
      • It checks all nodes for L = 1, 2, 3, 4, 7, 8, 16, 33 and 64. For L = 1001 and 2049, it checks the three nodes nearest each pole, the middle one and one at L/4.
      • It runs in numpy and JAX, and its 22 cases take about 1.5 s.
      • On main, 19 of the 22 cases fail: only L = 1 (numpy and JAX) and L = 2 (JAX) pass.
    • test_gl_angles_and_weights_inputs_and_copies checks that a zero-dimensional integer array works as L, and that changing a returned array does not change later results.
    • mpmath comes through torch's sympy dependency, and the test uses pytest.importorskip. It could also be listed in the test extras.
  • Existing tests. No tolerance changes.
    • Locally, with JAX on the CPU, the full suite gives 5398 passed, 1535 skipped and 0 failed.
    • The skips are the suite's unsupported parameter combinations: 846 for reality with spin ≠ 0, 512 for GPU distribution with a method other than JAX, 72 for Price–McEwen above |spin| = 6, and 95 others. 10 more skipped tests need a GPU, so the CUDA kernels and the GPU path were not exercised.
    • On main, run the same way, the only failures are the new test's 19 cases.
  • ruff and pre-commit pass.

Compatibility

  • No public API change. The same functions with the same signatures; quadrature_jax.quad_weights_gl_theta_only is still a jitted function.
  • The values move by about the old errors. These are largest near the poles: up to 6.2e-14 rad for the angles and 2e-10 (relative) for the weights, at L = 4096.
  • JAX without 64-bit precision. The JAX weights are now the accurate float64 values converted to float32. Main computed them by a Newton iteration in float32, whose 1e-14 tolerance float32 cannot reach. At L = 8, 64 and 512 it did not finish within 15 s.
  • Inputs. L < 1 raises ValueError, as before, with a new message. np.int64 works as before. Zero-dimensional integer arrays work for the weights as before, and now also for thetas.
  • One new private module (sampling/_gauss_legendre.py: about 110 lines of code, 200 with comments and docstrings), plus the tests.

Relation to #430

The two PRs are independent. Each applies to main on its own, and they touch no file in common.

Together they remove the excess GL error near the poles. The measurement is at L = 512 on GL, with JAX on the CPU, against exact samples at the exact nodes, with complex Gaussian coefficients and a binary128 reference. The synthesis columns give the RMS error over the samples within 1° of the poles and at 20–160°, and the largest error with its ring's angle. The analysis column is the forward transform of the exact samples.

polar RMS (< 1°) mid-latitude RMS (20–160°) polar / mid max synthesis error analysis error (relative ℓ₂)
main 6.6e-12 8.5e-13 7.7 3.0e-11, at 179.0° 3.07e-12
this PR alone 5.7e-12 8.5e-13 6.6 2.5e-11, at 173.4° 3.08e-12
#430 alone 9.6e-14 1.4e-14 6.9 2.8e-13, at 0.62° 4.98e-14
#430 and this PR 1.1e-14 1.4e-14 0.8 6.9e-14, at 115.8° 4.73e-14

On main, the recursions' own errors are larger than the effect of the angles at every latitude, so at L = 512 this PR alone barely changes the transforms' errors. With #430, the angles account for the excess near the poles in this test, and this PR removes it; what remains is transform round-off, at the mid-latitude level.

🤖 Generated with Claude Code

https://claude.ai/code/session_01W95ivh57fecWLC2t6f5L57

s2_samples.thetas took the GL angles as arccos of numpy's leggauss
roots, and quad_weights_gl_theta_only (with its JAX copy) found its own
nodes by Newton's method in x, stopping at |dx| <= 1e-14 and taking the
derivative at the previous iterate. Near the poles, arccos amplifies the
rounding of x = cos(theta) by 1/sin(theta). Against binary128, the polar
angles were off by 2.2e-15 rad (1926 ulp) at L = 512 and 6.2e-14 rad at
L = 4096, and the polar weights by 2.2e-13 and up to 2e-10. With the
pole fix of #430, these angles account for the excess GL synthesis
error near the poles in a test at L = 512, where it was about 7 times
its mid-latitude value.

Compute both from one routine, in a new private module,
sampling/_gauss_legendre.py. It uses Newton's method in theta, with P_L
evaluated through the differences P_l - P_{l-1} in s = sin^2(theta/2),
so that no rounded x is formed, and one last step in double-double
arithmetic, rounded once. The weights 2 / (dP_L/dtheta)^2 come from the
same double-double P_L at the last iterate, carried to the final node
by Legendre's equation to second order and rounded once; the middle
weight of an odd L is computed at s = 1/2 exactly, on the same path.
The JAX weights reuse them. The result is cached per L, after
operator.index, so zero-dimensional integer arrays still work. L < 1
still raises ValueError.

Against binary128, every angle and every weight is correctly rounded
for every node of every L from 1 to 4096 and of L = 8191 to 8193, 16383
and 16384; this is observed, not proved. A first call takes 19 ms at
L = 512 and 0.29 s at 4096, against 19 ms and 6.8 s for main's angles
and weights, but a first call for the weights alone is slower than on
main (0.29 s against 47 ms at 4096). On top of #430, the polar to
mid-latitude ratio of the GL synthesis error at L = 512 falls from 6.9
to 0.8. New tests check the angles and weights exactly against 40-digit
mpmath values (all nodes up to L = 64, and polar and equatorial nodes
at L = 1001 and 2049), and a zero-dimensional L; 19 of the 22 reference
cases fail on main. The full suite passes with JAX on the CPU (5398
passed, 1535 skipped: unsupported combinations and 10 GPU-only tests).

Harness: Claude Code 2.1.312
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01SoYPKjWF4i5SQv5WmzhHgC

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.13043% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 97.00%. Comparing base (72dd21a) to head (ad7f295).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/s2fft/sampling/_gauss_legendre.py 99.08% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #433      +/-   ##
==========================================
+ Coverage   96.98%   97.00%   +0.02%     
==========================================
  Files          36       37       +1     
  Lines        3577     3640      +63     
==========================================
+ Hits         3469     3531      +62     
- Misses        108      109       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@matt-graham matt-graham added the enhancement New feature or request label Nov 18, 2026
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
@@ -1,5 +1,7 @@
import numpy as np

from s2fft.sampling import _gauss_legendre

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
from s2fft.sampling import _gauss_legendre
# To be folded into class during refactoring for s2fft v1.6, see
# https://github.com/astro-informatics/s2fft/blob/develop/design/DESIGN.md
from s2fft.sampling import _gauss_legendre

Comment thread src/s2fft/utils/quadrature_jax.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment thread src/s2fft/sampling/_gauss_legendre.py Resolved
Comment on lines +9 to +12
:math:`s = \sin^2(\theta/2)`, so that no rounded :math:`x = 1 - 2s` is formed. A last
Newton step and the weights :math:`2/(dP_L/d\theta)^2` at the final nodes are evaluated in
double-double arithmetic and rounded once to float64. In every case tested, the angles and
the weights are then correctly rounded.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docstring of the float64 version.

Suggested change
:math:`s = \sin^2(\theta/2)`, so that no rounded :math:`x = 1 - 2s` is formed. A last
Newton step and the weights :math:`2/(dP_L/d\theta)^2` at the final nodes are evaluated in
double-double arithmetic and rounded once to float64. In every case tested, the angles and
the weights are then correctly rounded.
:math:`s = \sin^2(\theta/2)`, so that no rounded :math:`x = 1 - 2s` is formed. The
weights are :math:`2/(dP_L/d\theta)^2` at the final nodes, in float64.

Comment on lines +16 to +18
from fractions import Fraction
from functools import lru_cache
from math import factorial

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fraction and factorial only build the double-double constants.

Suggested change
from fractions import Fraction
from functools import lru_cache
from math import factorial
from functools import lru_cache

Comment on lines +21 to +90

# Double-double arithmetic (Dekker 1971): a value is the unevaluated sum hi + lo.
_SPLIT = 134217729.0 # 2**27 + 1


def _two_sum(a, b):
s = a + b
bb = s - a
return s, (a - (s - bb)) + (b - bb)


def _fast_two_sum(a, b):
s = a + b
return s, b - (s - a)


def _two_prod(a, b):
p = a * b
a_hi = _SPLIT * a
a_hi = a_hi - (a_hi - a)
b_hi = _SPLIT * b
b_hi = b_hi - (b_hi - b)
a_lo, b_lo = a - a_hi, b - b_hi
return p, ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo


def _dd_add(x, y):
s, e = _two_sum(x[0], y[0])
return _fast_two_sum(s, e + (x[1] + y[1]))


def _dd_mul(x, y):
p, e = _two_prod(x[0], y[0])
return _fast_two_sum(p, e + (x[0] * y[1] + x[1] * y[0]))


def _dd_scale(x, c):
p, e = _two_prod(x[0], c)
return _fast_two_sum(p, e + x[1] * c)


def _dd_div(x, c):
q = x[0] / c
p, e = _two_prod(q, c)
return _fast_two_sum(q, ((x[0] - p) - e + x[1]) / c)


def _dd_div_dd(x, y):
q = x[0] / y[0]
r = _dd_add(x, _dd_scale(y, -q))
return _fast_two_sum(q, r[0] / y[0])


def _dd_const(value: Fraction) -> tuple[float, float]:
hi = float(value)
return hi, float(value - Fraction(hi))


_PI = _dd_const(Fraction("3.14159265358979323846264338327950288419716939937510582097"))
# Taylor coefficients (-1)^n / (2n + 1)! of sin t / t, enough for |t| <= pi/4
_SIN_COEFFS = [_dd_const(Fraction((-1) ** n, factorial(2 * n + 1))) for n in range(18)]


def _dd_sin(t: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""sin(t) in double-double, for float64 t with |t| <= pi/4."""
t2 = _two_prod(t, t)
acc = (np.full_like(t, _SIN_COEFFS[-1][0]), np.full_like(t, _SIN_COEFFS[-1][1]))
for c_hi, c_lo in reversed(_SIN_COEFFS[:-1]):
acc = _dd_add(_dd_mul(acc, t2), (np.full_like(t, c_hi), np.full_like(t, c_lo)))
return _dd_scale(acc, t)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plain float64: the double-double primitives (_two_sum, _fast_two_sum, _two_prod, _dd_*), the constants _SPLIT, _PI, _SIN_COEFFS and _dd_sin are then unused.

Suggested change
# Double-double arithmetic (Dekker 1971): a value is the unevaluated sum hi + lo.
_SPLIT = 134217729.0 # 2**27 + 1
def _two_sum(a, b):
s = a + b
bb = s - a
return s, (a - (s - bb)) + (b - bb)
def _fast_two_sum(a, b):
s = a + b
return s, b - (s - a)
def _two_prod(a, b):
p = a * b
a_hi = _SPLIT * a
a_hi = a_hi - (a_hi - a)
b_hi = _SPLIT * b
b_hi = b_hi - (b_hi - b)
a_lo, b_lo = a - a_hi, b - b_hi
return p, ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo
def _dd_add(x, y):
s, e = _two_sum(x[0], y[0])
return _fast_two_sum(s, e + (x[1] + y[1]))
def _dd_mul(x, y):
p, e = _two_prod(x[0], y[0])
return _fast_two_sum(p, e + (x[0] * y[1] + x[1] * y[0]))
def _dd_scale(x, c):
p, e = _two_prod(x[0], c)
return _fast_two_sum(p, e + x[1] * c)
def _dd_div(x, c):
q = x[0] / c
p, e = _two_prod(q, c)
return _fast_two_sum(q, ((x[0] - p) - e + x[1]) / c)
def _dd_div_dd(x, y):
q = x[0] / y[0]
r = _dd_add(x, _dd_scale(y, -q))
return _fast_two_sum(q, r[0] / y[0])
def _dd_const(value: Fraction) -> tuple[float, float]:
hi = float(value)
return hi, float(value - Fraction(hi))
_PI = _dd_const(Fraction("3.14159265358979323846264338327950288419716939937510582097"))
# Taylor coefficients (-1)^n / (2n + 1)! of sin t / t, enough for |t| <= pi/4
_SIN_COEFFS = [_dd_const(Fraction((-1) ** n, factorial(2 * n + 1))) for n in range(18)]
def _dd_sin(t: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""sin(t) in double-double, for float64 t with |t| <= pi/4."""
t2 = _two_prod(t, t)
acc = (np.full_like(t, _SIN_COEFFS[-1][0]), np.full_like(t, _SIN_COEFFS[-1][1]))
for c_hi, c_lo in reversed(_SIN_COEFFS[:-1]):
acc = _dd_add(_dd_mul(acc, t2), (np.full_like(t, c_hi), np.full_like(t, c_lo)))
return _dd_scale(acc, t)

Comment on lines +108 to +142


def _legendre_by_differences_dd(s, L: int):
""":math:`P_L` and :math:`D_L` as in :func:`_legendre_by_differences`, in double-double."""
two_s = (2 * s[0], 2 * s[1])
neg_two_s = (-two_s[0], -two_s[1])
p = _dd_add((np.ones_like(s[0]), np.zeros_like(s[0])), neg_two_s)
d = neg_two_s
for ell in range(1, L):
b = _dd_scale(_dd_mul(two_s, p), float(2 * ell + 1))
d = _dd_div(_dd_add(_dd_scale(d, float(ell)), (-b[0], -b[1])), float(ell + 1))
p = _dd_add(p, d)
return p, d


def _weights_dd(s, p, d, delta, L: int) -> np.ndarray:
r"""
The weights :math:`2/(dP_L/d\theta)^2` at :math:`\theta + \delta`, rounded once to
float64, from :math:`s`, :math:`P_L` and :math:`D_L` at :math:`\theta` in double-double.

At a zero of :math:`P_L`, Legendre's equation gives
:math:`d^2P_L/d\theta^2 = -\cot\theta \, dP_L/d\theta`, and differentiating it once more
gives the third derivative, so the small step :math:`\delta` to the zero multiplies the
weight by :math:`1 + 2\delta\cot\theta + (\cot^2\theta - 1 - L(L+1))\delta^2`, to second
order.
"""
one = (np.ones_like(s[0]), np.zeros_like(s[0]))
# sin(theta) dP_L/dtheta = L (D_L - 2s P_L), and 2 sin^2(theta) = 8s (1 - s)
sin_dpdt = _dd_scale(_dd_add(d, _dd_scale(_dd_mul(s, p), -2.0)), float(L))
two_sin2 = _dd_scale(_dd_mul(s, _dd_add(one, (-s[0], -s[1]))), 8.0)
w = _dd_div_dd(two_sin2, _dd_mul(sin_dpdt, sin_dpdt))
cot = (1 - 2 * s[0]) / (2 * np.sqrt(s[0] * (1 - s[0])))
scale = 2 * delta * cot + (cot * cot - 1 - L * (L + 1)) * delta * delta
w = _dd_add(w, (scale * w[0], np.zeros_like(w[0])))
return w[0] + w[1]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_legendre_by_differences_dd and _weights_dd are then unused.

Suggested change
def _legendre_by_differences_dd(s, L: int):
""":math:`P_L` and :math:`D_L` as in :func:`_legendre_by_differences`, in double-double."""
two_s = (2 * s[0], 2 * s[1])
neg_two_s = (-two_s[0], -two_s[1])
p = _dd_add((np.ones_like(s[0]), np.zeros_like(s[0])), neg_two_s)
d = neg_two_s
for ell in range(1, L):
b = _dd_scale(_dd_mul(two_s, p), float(2 * ell + 1))
d = _dd_div(_dd_add(_dd_scale(d, float(ell)), (-b[0], -b[1])), float(ell + 1))
p = _dd_add(p, d)
return p, d
def _weights_dd(s, p, d, delta, L: int) -> np.ndarray:
r"""
The weights :math:`2/(dP_L/d\theta)^2` at :math:`\theta + \delta`, rounded once to
float64, from :math:`s`, :math:`P_L` and :math:`D_L` at :math:`\theta` in double-double.
At a zero of :math:`P_L`, Legendre's equation gives
:math:`d^2P_L/d\theta^2 = -\cot\theta \, dP_L/d\theta`, and differentiating it once more
gives the third derivative, so the small step :math:`\delta` to the zero multiplies the
weight by :math:`1 + 2\delta\cot\theta + (\cot^2\theta - 1 - L(L+1))\delta^2`, to second
order.
"""
one = (np.ones_like(s[0]), np.zeros_like(s[0]))
# sin(theta) dP_L/dtheta = L (D_L - 2s P_L), and 2 sin^2(theta) = 8s (1 - s)
sin_dpdt = _dd_scale(_dd_add(d, _dd_scale(_dd_mul(s, p), -2.0)), float(L))
two_sin2 = _dd_scale(_dd_mul(s, _dd_add(one, (-s[0], -s[1]))), 8.0)
w = _dd_div_dd(two_sin2, _dd_mul(sin_dpdt, sin_dpdt))
cot = (1 - 2 * s[0]) / (2 * np.sqrt(s[0] * (1 - s[0])))
scale = 2 * delta * cot + (cot * cot - 1 - L * (L + 1)) * delta * delta
w = _dd_add(w, (scale * w[0], np.zeros_like(w[0])))
return w[0] + w[1]

Comment on lines +156 to +157
# Stop within a few ulps: rounding sets a floor there, and the double-double
# step below converges quadratically from it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment of the float64 version: no double-double step follows.

Suggested change
# Stop within a few ulps: rounding sets a floor there, and the double-double
# step below converges quadratically from it.
# Stop within a few ulps: rounding sets a floor there.

Comment on lines +167 to +168
delta = -(p[0] / dpdt)
north = _two_sum(theta, delta)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_two_sum(theta, delta): the float64 loop above already stops within 64 ulps, so no last step.

Suggested change
delta = -(p[0] / dpdt)
north = _two_sum(theta, delta)

Comment on lines +169 to +172
south = _dd_add(
(np.full_like(theta, _PI[0]), np.full_like(theta, _PI[1])),
(-north[0], -north[1]),
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_dd_add with the double-double π: np.pi - theta.

Suggested change
south = _dd_add(
(np.full_like(theta, _PI[0]), np.full_like(theta, _PI[1])),
(-north[0], -north[1]),
)
south = np.pi - theta

(np.full_like(theta, _PI[0]), np.full_like(theta, _PI[1])),
(-north[0], -north[1]),
)
weights = _weights_dd(s, p, d, delta, L)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_weights_dd: 2/(dP_L/dθ)² at the final angles.

Suggested change
weights = _weights_dd(s, p, d, delta, L)
weights = 2 / dpdt**2

Comment on lines +177 to +179
s = (np.array([0.5]), np.array([0.0]))
p, d = _legendre_by_differences_dd(s, L)
mid_theta, mid_weight = np.array([_PI[0] / 2]), _weights_dd(s, p, d, 0.0, L)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Middle node: _legendre_by_differences_dd and _weights_dd at s = 1/2, in float64.

Suggested change
s = (np.array([0.5]), np.array([0.0]))
p, d = _legendre_by_differences_dd(s, L)
mid_theta, mid_weight = np.array([_PI[0] / 2]), _weights_dd(s, p, d, 0.0, L)
_, _, dpdt_mid = _legendre_by_differences(np.array([0.5]), L)
mid_theta, mid_weight = np.array([np.pi / 2]), 2 / dpdt_mid**2

else:
mid_theta, mid_weight = np.array([]), np.array([])

thetas = np.concatenate([north[0], mid_theta, (south[0] + south[1])[::-1]])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

north[0] and south[0] + south[1]: theta and south.

Suggested change
thetas = np.concatenate([north[0], mid_theta, (south[0] + south[1])[::-1]])
thetas = np.concatenate([theta, mid_theta, south[::-1]])

@ASKabalan

Copy link
Copy Markdown
Collaborator

@jasonmcewen Simplifying the code and removing the double-double rounding operators makes the code slightly faster yet slightly less accurate. The suggestions in my review above, applied together, give this file (float64 only, 86 lines against 205):

src/s2fft/sampling/_gauss_legendre.py, float64 only
r"""
Gauss-Legendre nodes, as polar angles, and weights.

The nodes :math:`\theta_k` are the zeros of :math:`P_L(\cos\theta)`. Taking them as
:math:`\arccos` of the roots :math:`x_k` loses accuracy near the poles: there a rounding of
:math:`x_k` near :math:`\pm 1` moves :math:`\theta_k` by about :math:`u/\sin\theta_k`.
Here the nodes are found by Newton's method in :math:`\theta` instead, with :math:`P_L`
evaluated through the differences :math:`D_\ell = P_\ell - P_{\ell-1}` in
:math:`s = \sin^2(\theta/2)`, so that no rounded :math:`x = 1 - 2s` is formed. The
weights are :math:`2/(dP_L/d\theta)^2` at the final nodes, in float64.
"""

import operator
from functools import lru_cache

import numpy as np


def _legendre_by_differences(s: np.ndarray, L: int):
    r"""
    :math:`P_L(1 - 2s)`, :math:`D_L = P_L - P_{L-1}` and :math:`dP_L/d\theta`, in float64.

    With :math:`x = 1 - 2s`, the three-term recurrence becomes
    :math:`(\ell + 1) D_{\ell+1} = \ell D_\ell - 2s(2\ell + 1) P_\ell`, in which :math:`s`
    enters only multiplicatively, so its relative accuracy is kept near the poles.
    """
    p, d = 1 - 2 * s, -2 * s
    for ell in range(1, L):
        d = (ell * d - 2 * s * (2 * ell + 1) * p) / (ell + 1)
        p = p + d
    # dP_L/dtheta = -sin(theta) P_L'(x), with x P_L - P_{L-1} = D_L - 2s P_L
    dpdt = L * (d - 2 * s * p) / (2 * np.sqrt(s * (1 - s)))
    return p, d, dpdt


@lru_cache(maxsize=16)
def _nodes_and_weights(L: int) -> tuple[np.ndarray, np.ndarray]:
    if L < 1:
        raise ValueError(f"Gauss-Legendre quadrature needs at least one node, not {L}.")
    m = L // 2  # Nodes in the open northern hemisphere
    k = np.arange(1, m + 1)
    theta = np.pi * (4 * k - 1) / (4 * L + 2)
    for _ in range(50):
        p, _, dpdt = _legendre_by_differences(np.sin(theta / 2) ** 2, L)
        step = p / dpdt
        theta = theta - step
        # Stop within a few ulps: rounding sets a floor there.
        if np.all(np.abs(step) <= 64 * np.spacing(theta)):
            break

    # The weights 2 / (dP_L/dtheta)^2 at the final angles
    s = np.sin(theta / 2) ** 2
    _, _, dpdt = _legendre_by_differences(s, L)
    south = np.pi - theta
    weights = 2 / dpdt**2

    if L % 2:
        # The middle node is pi/2, where s = 1/2 exactly
        _, _, dpdt_mid = _legendre_by_differences(np.array([0.5]), L)
        mid_theta, mid_weight = np.array([np.pi / 2]), 2 / dpdt_mid**2
    else:
        mid_theta, mid_weight = np.array([]), np.array([])

    thetas = np.concatenate([theta, mid_theta, south[::-1]])
    weights = np.concatenate([weights, mid_weight, weights[::-1]])
    thetas.setflags(write=False)
    weights.setflags(write=False)
    return thetas, weights


def nodes_and_weights(L: int) -> tuple[np.ndarray, np.ndarray]:
    r"""
    Gauss-Legendre nodes as polar angles, in ascending order, and their weights.

    Args:
        L (int): Number of nodes, the harmonic band-limit for GL sampling.

    Returns:
        Tuple[np.ndarray, np.ndarray]: The angles :math:`\theta_k`, the zeros of
        :math:`P_L(\cos\theta)`, and the weights :math:`w_k` of the quadrature on
        :math:`x = \cos\theta \in [-1, 1]`, in float64.

    """
    thetas, weights = _nodes_and_weights(operator.index(L))
    return thetas.copy(), weights.copy()

Measured on a Colab VM with an NVIDIA L4 (NumPy on its CPU), median of three first calls. The angle and weight errors are against this PR's values, which are correctly rounded (its tests, and a check against 40-digit mpmath at eight nodes of L = 2048).

L first call (s): this PR / float64 / main angles, max error (ulp): float64 / main weights, max relative error: float64 / main quadrature error max|G − I|: this PR / float64 / main
64 0.00745 / 0.00221 / 0.00280 1 / 119 1.8e-15 / 9.3e-14 2.1e-15 / 4.2e-15 / 6.9e-15
128 0.0146 / 0.00482 / 0.00601 1 / 709 3.7e-15 / 3.4e-13 2.9e-15 / 9.5e-15 / 1.6e-14
256 0.0291 / 0.0177 / 0.0226 2 / 709 4.9e-15 / 6.9e-13 5.3e-15 / 1.9e-14 / 1.9e-14
512 0.0675 / 0.0383 / 0.0556 2 / 1,926 7.0e-15 / 2.2e-13 8.2e-15 / 4.6e-14 / 3.3e-14
1024 0.163 / 0.0526 / 0.162 2 / 7,433 1.7e-14 / 2.2e-12 1.2e-14 / 8.2e-14 / 5.2e-14
2048 0.400 / 0.121 / 0.508 5 / 147,254 2.4e-14 / 7.0e-11 1.8e-14 / 1.6e-13 / 1.2e-13

The quadrature error is that of the Gram matrix $\sum_k w_k \bar P_\ell(x_k) \bar P_m(x_k)$ of the orthonormal Legendre polynomials, evaluated in long double at the rounded nodes, so that it measures the rounding of the nodes and weights alone (all $\ell, m &lt; L$ up to L = 1024, $|\ell - m| \le 2$ at L = 2048).

Is this complexity / error trade-off worth it?

@ASKabalan

Copy link
Copy Markdown
Collaborator

The same comparison in float32, as with jax_enable_x64 off. "This PR" and "main" are their float64 values rounded to float32 (quadrature_jax converts the weights with jnp.asarray); "float32" is the simplified algorithm above run in float32 (NumPy). Same Colab VM with an NVIDIA L4, median of three first calls. The errors are against this PR's values rounded to float32.

L first call (s): this PR / float32 / main angles, max error (float32 ulp): float32 / main weights, max relative error: float32 / main quadrature error max|G − I|: this PR / float32 / main
64 0.00731 / 0.00182 / 0.00289 1 / 0 1.2e-06 / 0.0e+00 1.0e-06 / 2.8e-06 / 1.0e-06
128 0.0142 / 0.00900 / 0.00979 2 / 0 2.3e-06 / 0.0e+00 1.5e-06 / 5.4e-06 / 1.5e-06
256 0.0290 / 0.0132 / 0.0222 2 / 0 2.9e-06 / 0.0e+00 2.8e-06 / 1.4e-05 / 2.8e-06
512 0.0682 / 0.0274 / 0.0561 2 / 0 5.5e-06 / 0.0e+00 5.8e-06 / 3.3e-05 / 5.8e-06
1024 0.165 / 0.0362 / 0.167 2 / 0 6.6e-06 / 0.0e+00 1.2e-05 / 5.7e-05 / 1.2e-05
2048 0.405 / 0.0788 / 0.558 2 / 0 9.0e-06 / 0.0e+00 2.4e-05 / 1.1e-04 / 2.4e-05

The quadrature error is that of the same Gram matrix as above, evaluated in long double at the float32 nodes and weights.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gauss–Legendre sample angles and weights are inaccurate near the poles

3 participants