fix(spherical): θ-derivative in `SphericalDerivative2D` is wrong for odd zonal wavenumber m, with O(1) error that does not converge — breaks gradient, divergence, curl, vorticity/divergence inversion and Helmholtz decomposition

Open
#97 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
40/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

The bug is in spectraldiffx/_src/spherical/operators.py lines 330-334, 379-381, 430, and the derivative matrix in lines 172-202. Start by reading the theory in docs/theory/spherical.md §6 to understand the spectral derivative formula. The fix involves implementing a derivative table using the recurrence for associated Legendre polynomials. Test with the provided reproduction script and the acceptance criteria, focusing on odd-m spherical harmonics. Check the existing tests in test_spherical_deriv2d to see why they missed the bug.

Written by the indexing model from the issue text.

Description

bug

Part of #81.

Summary

SphericalDerivative2D.gradient, .divergence and .curl compute ∂/∂θ by expanding each longitude column u(θ, φ_k) in ordinary Legendre polynomials (m = 0 basis, via SphericalDerivative1D) and using dP_l/dθ = sqrt(l(l+1)) P_l^1. That is exact only when the column is a polynomial in cos θ, i.e. for even zonal wavenumber m. A column with odd m contains the factor sqrt(1−μ²), which is not smooth at the poles; its Legendre expansion converges only algebraically and its derivative does not converge in max-norm at the pole-most node. The error is O(1) and independent of resolution.

Downstream: advection_scalar, SphericalVorticityInversionSolver, SphericalDivergenceInversionSolver, SphericalHelmholtzDecomposition, and the three sphere models in the model-zoo epic (#9, #11, #13).

Reproduction

import jax; jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp, numpy as np
from spectraldiffx import SphericalGrid2D, SphericalDerivative2D
for Ny in (16, 64):
    g = SphericalGrid2D.from_N_L(Nx=2*Ny, Ny=Ny, Lx=2*np.pi, Ly=np.pi)
    d = SphericalDerivative2D(g)
    th = g.y[:, None]; ph = g.x[None, :]
    for name, u, exact in (("sin(th)cos(ph)   m=1", jnp.sin(th)*jnp.cos(ph),       jnp.cos(th)*jnp.cos(ph)),
                           ("sin²(th)cos(2ph) m=2", jnp.sin(th)**2*jnp.cos(2*ph), 2*jnp.sin(th)*jnp.cos(th)*jnp.cos(2*ph))):
        gt, gp = d.gradient(u)
        print(f"Ny={Ny} {name}: max|d/dtheta err| = {float(jnp.abs(gt-exact).max()):.2e}")
Ny=16 sin(th)cos(ph)   m=1: max|d/dtheta err| = 1.82e-01
Ny=16 sin²(th)cos(2ph) m=2: max|d/dtheta err| = 1.81e-14
Ny=64 sin(th)cos(ph)   m=1: max|d/dtheta err| = 1.78e-01
Ny=64 sin²(th)cos(2ph) m=2: max|d/dtheta err| = 3.49e-13

Sweep over Re Y_lm, max |∂θ error|:

(l, m) Ny=16 Ny=32 Ny=64 Ny=128
(1, 0) 3e-13 5e-12 2e-11 2e-09
(1, 1) 6.3e-02 6.2e-02 6.1e-02 6.1e-02
(2, 1) 1.4e-01 1.4e-01 1.4e-01 1.4e-01
(4, 1) 3.6e-01 3.4e-01 3.4e-01 3.4e-01
(2, 2) 7e-15 7e-14 1e-13 8e-13
(3, 3) 2.6e-03 6.3e-04 1.6e-04 4.0e-05

Consequences measured: |div(grad u) − laplacian(u)| for (2,1) is 1.2 / 3.1 / 6.9 at Ny = 16 / 32 / 64 (grows with resolution; |lap| ≈ 2.3). Vorticity inversion of ψ = Y_2^1 + 0.7 Y_3^2 + 0.3 Y_4^1: ψ error 1e-15, V_θ error 1e-14, V_φ error 0.25 (|V|max 1.4). Helmholtz decomposition of a generic field at Ny = 64: |V_rot + V_div − V| = 0.15, and decompose(V_rot) again changes V_rot by 0.09 (not idempotent). Even-m-only control: ψ error 6e-14.

Why the tests do not see it

curl(grad u) = (1/(R² sin θ)) [D_θ ∂φ u − ∂φ D_θ u] vanishes for any column-wise linear D_θ, because it commutes with the longitude FFT. So test_spherical_deriv2d_div_of_curl_zero and test_spherical_deriv2d_curl_of_gradient_zero are identities (measured |curl grad| = 5.7e-14 for a field whose gradient is wrong by 0.14). All other operator and solver tests use zonal or even-m fields (cos θ, sin²θ cos φ, sin 2θ cos φ), whose θ-columns are polynomials. solvers.py:351-361 describes the discrepancy as a "small truncation error".

Root cause

spectraldiffx/_src/spherical/operators.py:330-334 (du_dtheta = jax.vmap(self.deriv_theta.gradient, in_axes=1, out_axes=1)(u_phys)), :379-381, :430; the m = 0 derivative matrix in :172-202.

Proposed fix

Differentiate in spectral space per m, which is what docs/theory/spherical.md §6 already describes:

sin θ · dP̃_l^m/dθ = −l · ε_{l+1,m} · P̃_{l+1}^m + (l+1) · ε_{l,m} · P̃_{l−1}^m,
ε_{l,m} = sqrt((l² − m²) / (4l² − 1))

so ∂θ u needs one extra synthesis with a "derivative table" (sin θ · dP̃/dθ evaluated at the nodes, divided by sin θ, which is non-zero at Gauss–Legendre nodes). Divergence and curl are then computed spectrally from (V_θ sin θ, V_φ sin θ) with the same identity, avoiding any pole division. This is the standard approach (SHTns, torch-harmonics, pyspharm). It also removes SphericalDerivative1D and its m = 0 matrix from the 2D hot path.

Build the derivative table with the same stable recurrence as the ALP table (companion issue in this epic).

Acceptance criteria

  • Test: u = sin θ cos φ → ∂θ u = cos θ cos φ to 1e-12 at Ny = 16 and 64.
  • Test: sweep over Re Y_lm for l ≤ 6, all m, against analytic θ-derivatives (the audit's ylm.py helper has them, cross-checked against finite differences to 1e-10): max error < 1e-10.
  • Test: div(grad u) == laplacian(u) to 1e-10 for an odd-m field.
  • Test: Helmholtz decomposition round trip V_rot + V_div == V and idempotence to 1e-10 on a generic field with ψ ∈ {Y_2^1, Y_3^2}, χ ∈ {Y_3^1, Y_4^3}.
  • Test: vorticity inversion recovers V_φ to 1e-10 for ψ = Y_2^1.
  • solvers.py:351-361 comment removed; docstrings for curl sign (operators.py:23, :280) corrected to match the code and :400.
Dominant language
Python
Stars
2
Forks
0
Avg merge
8h 13m
Merged PRs (30d)
8

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from jejjohnson/spectraldiffx

All issues in jejjohnson/spectraldiffx

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.