diff --git a/design/DESIGN.md b/design/DESIGN.md new file mode 100644 index 00000000..c7b2412c --- /dev/null +++ b/design/DESIGN.md @@ -0,0 +1,389 @@ +# S2FFT 2.0: a pytree-based rewrite + +Design document, draft of 8 November 2026. +Diagrams are `assets/*.drawio.svg` and open for editing in draw.io. The plots in `assets/*.png` are rendered by the scripts in `assets/`. + +## 1. Timeline + +The rewrite follows the three open milestones of [astro-informatics/s2fft](https://github.com/astro-informatics/s2fft/milestones). + +| Milestone | Due | Scope | Issues and the part of the design that closes them | +|---|---|---|---| +| v1.6 | 15 Dec 2026 | Rework; old API kept with `DeprecationWarning` | #340 grid modularization: sampling classes. #341 CUDA plug-in: `s2fft-cuda`. #406 `L x 2L` regular Gaussian: `RegularGaussian`. #353 modular `conftest.py`: one fixture per sampling class. | +| v1.7 | 31 Jan 2027 | Features | #434 reduced grids: `ReducedGaussian`, `OctahedralGaussian`, `StretchedSampling`. #435 PyTorch: `jax2torch`. #436 multi-node / multi-GPU: `.shard()` / `.replicate()`. `forward_cl` on every sampling. | +| v2.0 | 31 Mar 2027 | Old API removed | #349 remove backend-specific variants (`forward_jax`, `forward_numpy`, `forward_torch`, `method=`). #339 Array API refactor: superseded by the JAX-only core (TODO: confirm with the maintainers). | + +## 2. S2FFT and upstream infrastructure + +![S2FFT and upstream infrastructure](assets/packages.drawio.svg) + +- `s2fft` is JAX only. The numpy and torch backends are removed. +- The compiled kernels move to two plug-ins that register XLA FFI targets when imported (#341): + - `s2fft-cuda` (part of [PR #442](https://github.com/astro-informatics/s2fft/pull/442)): CUDA and cuFFT kernels. It starts with the HEALPix ring FFT that lives today in `lib/` and `utils/healpix_ffts.py`. + - `s2fft-tbb`: CPU kernels with oneTBB (new). +- The plug-ins depend on `s2fft`; `s2fft` never imports them eagerly. +- Kernels for DISCO transforms? (TODO) + +## 3. S2FFT v2.0 internals + +![Class structure](assets/s2fft_structure.drawio.svg) + +Today sampling is dispatched by `if sampling.lower() == ...` branches spread over `transforms/spherical.py`, `utils/quadrature.py` and `sampling/s2_samples.py`. Each branch becomes a method of a class. + +- `SphericalSampling` (abstract base, pytree) + - meta fields: `L`, `spin`, `reality`, `sharding` + - geometry: `thetas()`, `phis()`, `quadrature_weights()`, `shape` + - `forward_ftm` / `inverse_ftm` (step 1a) + - `forward_legendre` / `inverse_legendre` (step 2) + - `forward_sht` / `inverse_sht`, `forward_cl` + - `shard(sharding)`, `replicate()`: v1.7 (#436) +- `EquiangularSampling(variant=...)`: MW, MWSS, DH, CC, F2 +- `GaussianSampling` + - `RegularGaussian`: GL ($2L-1$ points) and F$_N$ ($4N$ points, #406) + - `ReducedGaussian`: N$_N$ (#434) + - `OctahedralGaussian`: O$_N$ (#434) +- `HealpixSampling` +- `StretchedSampling(base=..., c, target_lat, target_lon)`: wraps any of the above +- `Alm`: the common output of every `forward_sht` + +### 3.1 Equiangular + +![Equiangular samplings](assets/equiangular.png) + +Rings equally spaced in $\theta$. In `sampling/s2_samples.py:t2theta`, MW, MWSS, DH, CC and F2 are all linear in the ring index $t$. Weights come from `quad_weights_{mw,mwss,dh,cc,f2}` in `utils/quadrature_jax.py`. + +```python +eq = s2fft.EquiangularSampling(L=256, variant="mw") +ftm = eq.forward_ftm(f) # step 1a +alm = eq.forward_legendre(ftm) # step 2 +alm = eq.forward_sht(f) # both +f = eq.inverse_sht(alm) +cl = eq.forward_cl(f) +``` + +### 3.2 Gaussian, regular + +![Regular Gaussian samplings](assets/gaussian_regular.png) + +Rings at the roots of $P_n$ and the same number of points on every ring. + +- GL: $L$ rings, $2L-1$ points (the current `"gl"`). +- F$_N$: $2N$ rings, $4N$ points (#406). Step 1a drops the Nyquist order. + +```python +gl = s2fft.RegularGaussian(L=256) # 2L - 1 points +fn = s2fft.RegularGaussian.from_N(N=128) # 4N points +alm = fn.forward_sht(f) +``` + +### 3.3 Gaussian, reduced and octahedral + +![Reduced Gaussian samplings](assets/gaussian_reduced.png) + +Same Gauss rings, fewer points towards the poles (#434). The N$_N$ panel is illustrative: its ring sizes follow $4N\sin\theta$, not the ECMWF table. + +- O$_N$: ring $i$ from the pole has $4i+16$ points. +- N$_N$: ring sizes from a stored table; step 1a keeps $m \le$ NMEN$_t$. +- `nphi` becomes a per-ring array, so `forward_ftm` runs one rFFT per ring (TODO: padded batched FFT vs ragged loop). + +```python +on = s2fft.OctahedralGaussian(N=1280) +nn = s2fft.ReducedGaussian(N=320) # table bundled with s2fft +``` + +### 3.4 HEALPix + +![HEALPix sampling](assets/healpix.png) + +The rings are not Gauss rings, so one pass is not exact. `forward_sht` keeps the iterative refinement of `utils/iterative_refinement.py`. + +- Step 1a: FFT, alias and phase shift per ring (`utils/healpix_ffts.py`). +- The CUDA ring FFT moves to `s2fft-cuda`. + +```python +hp = s2fft.HealpixSampling(nside=512, L=1024) +alm = hp.forward_sht(m, iter=3) +``` + +### 3.5 Stretched + +![Stretched GL sampling](assets/stretched.png) + +The Schmidt map $\tan(\vartheta/2) = \tan(\theta/2)/c$ is followed by a rotation of the pole to the target. It acts on points, so it wraps any base sampling. + +- The SHT runs in computational coordinates on the base grid. +- `thetas()` / `phis()` return the Earth positions. The weights get the area factor $A(\theta)$. + +```python +st = s2fft.StretchedSampling( + base=s2fft.RegularGaussian(L=512), + c=2.4, target_lat=51.5, target_lon=-0.13) +alm = st.forward_sht(f) # base.forward_sht in computational frame +``` + +## 4. The separable SHT as methods + +![SHT pipeline](assets/sht_pipeline.drawio.svg) + +The steps follow the ring-grid study (`sht_schmidt_so3_study.pdf`, section 1): + +| Step | Content | Method | +|---|---|---| +| 0 | grid: ring latitudes $\theta_t$, points $\phi_p$, weights $q_t$ | constructor, `quadrature_weights()` | +| 1a | one FFT per ring gives $f_{tm}$ | `forward_ftm` | +| 2 | $f_{\ell m} = \sum_t q_t \lambda_{\ell m}(\theta_t) f_{tm}$ | `forward_legendre` | + +`forward_sht = forward_legendre ∘ forward_ftm` and `forward_cl = Alm.cl ∘ forward_sht`. + +Step 1a per grid (study, section 7): + +| | GL | F$_N$ | O$_N$ | N$_N$ | HEALPix | +|---|---|---|---|---|---| +| step 1a | 2D rFFT | 2D rFFT, drop Nyquist | rFFT per ring | rFFT, keep $m \le$ NMEN$_t$ | FFT, alias, phase | +| one pass | exact | exact | exact on O8 | $\sim 10^{-6}$ | $\sim 10^{-2}$, iterate | + +## 5. Pytree layout + +![Pytree fields](assets/pytree_fields.drawio.svg) + +```python +@jax.tree_util.register_dataclass +@dataclasses.dataclass(frozen=True) +class GaussianSampling(SphericalSampling): + thetas: jax.Array # data field + weights: jax.Array # data field + L: int = jax.tree.static() # meta field (JAX >= 0.9) + sharding: jax.sharding.Sharding | None = jax.tree.static(default=None) +``` + +- Data fields (arrays: `thetas`, `weights`, `nphi`) are leaves and go through `jit`, `grad` and `vmap`. +- Meta fields (`L`, `spin`, `reality`, variant, `N`, `nside`, `sharding`) are static and part of the `jit` cache key, so a new sharding retraces. +- The sharding is stored as a static field, following `field_sharding` in jax-fli `_core.py`. jax-fli uses `eqx.field(static=True)`; here `register_dataclass` is used with no Equinox dependency. +- The snippet above was checked with JAX 0.11.2. `jax.tree.static()` needs JAX ≥ 0.9, but `pyproject.toml` pins `jax>=0.5`; there the form is `dataclasses.field(metadata=dict(static=True))` (TODO). + +## 6. A common `Alm` class + +Every `forward_sht` returns an `Alm` pytree, whatever the sampling. The layouts reuse `sampling/reindex.py`. The 2D layout stores zeros for $|m| > \ell$, and the HEALPix layout keeps only $m \ge 0$ of a real signal (`flm_2d_to_hp_fast` docstring). Rotation reuses `rotate_flms` from `utils/rotation.py`. + +```python +from dataclasses import dataclass, replace +from typing import Literal, Self +import jax +import jax.numpy as jnp +from jax import Array +from jax.sharding import Sharding +from jax.tree import static +from s2fft.sampling import reindex + +Layout = Literal["2d", "1d", "hp"] + +@jax.tree_util.register_dataclass +@dataclass(frozen=True) +class Alm: + """Output of every forward_sht.""" + + array: Array # data field, (L, 2L-1) in "2d" + L: int = static() + spin: int = static(default=0) + reality: bool = static(default=False) + layout: Layout = static(default="2d") + sharding: Sharding | None = static(default=None) + + # layouts, from sampling/reindex.py + def to_2d(self) -> Self: ... # flm_*_to_2d_fast + def to_1d(self) -> Self: ... # flm_2d_to_1d_fast + def to_hp(self) -> Self: ... # real only, m >= 0 + + # spectra ("2d" stores zeros for |m| > l) + def cl(self, other: Self | None = None) -> Array: + a = self.to_2d().array + b = a if other is None else other.to_2d().array + nm = 2 * jnp.arange(self.L) + 1 + return (a * b.conj()).real.sum(-1) / nm + + # arithmetic: same L, spin, layout + def __add__(self, o: Self) -> Self: + return replace(self, array=self.array + o.array) + def __mul__(self, x) -> Self: ... # scalar or b_ell + + # rotation, from utils/rotation.py (rotate_flms) + def rotate(self, alpha, beta, gamma) -> Self: ... + + # distribution (v1.7) + def shard(self, sharding: Sharding) -> Self: ... + def replicate(self) -> Self: ... +``` + +```python +alm = gl.forward_sht(f) # Alm, layout "2d" +cl = alm.cl() # auto-spectrum +xcl = alm.cl(hp.forward_sht(m)) # cross-spectrum +f_hp = hp.inverse_sht(alm) # any sampling +``` + +## 7. Quadrature and $C_\ell$ + +- One `quadrature_weights()` per class replaces the `if sampling.lower() == ...` chain in `quad_weights_transform` (`utils/quadrature_jax.py`). The `quad_weights_*` functions are reused as they are. +- `forward_cl(f)` is `forward_sht(f).cl()` on every sampling, including reduced and stretched grids. +- Steps 1a and 2 are also exposed on their own: `forward_ftm` / `inverse_ftm` and `forward_legendre` / `inverse_legendre` (from `transforms/otf_recursions.py`). + +Today (excerpt of `utils/quadrature_jax.py`): + +```python +def quad_weights_transform(L, sampling="mwss", nside=0): + if sampling.lower() == "mwss": + return (quad_weights_mwss_theta_only(2 * L) + * 2 * jnp.pi / samples.nphi_equiang(L, "mwss")) + elif sampling.lower() == "dh": + return quad_weights_dh(L) + elif sampling.lower() == "gl": + return quad_weights_gl(L) + elif sampling.lower() == "healpix": + return quad_weights_hp(nside) + ... +``` + +In the rewrite: + +```python +class RegularGaussian(GaussianSampling): + def quadrature_weights(self) -> Array: + return quad_weights_gl(self.L) # reused as is + +w = gl.quadrature_weights() # (nrings,) +cl = gl.forward_cl(f) # = gl.forward_sht(f).cl() +ftm = gl.forward_ftm(f) # step 1a only +alm = gl.forward_legendre(ftm) # step 2 only +``` + +![Ring weights](assets/quadrature_weights.png) + +Ring weights (per-pixel weight times points per ring) from s2fft's `quad_weights` and `quad_weights_hp`, divided by their mean. Each set sums to $4\pi$. + +## 8. Parts that do not move yet + +| Module | Today | In the rewrite | Milestone | +|---|---|---|---| +| `transforms/wigner.py` | `sampling=` string; loops the spherical transform over $n$ | `SO3Sampling(base=...)` wrapping an S² sampling | TODO | +| `recursions/` (Price-McEwen, Risbo, Turok) | free functions | unchanged, called by `forward_legendre` | TODO | +| `precompute_transforms/` | kernel builders + transforms | TODO | TODO | +| `utils/rotation.py` | `rotate_flms` | `Alm.rotate` | TODO | +| `utils/signal_generator.py` | `generate_flm` | returns `Alm` | TODO | +| `utils/iterative_refinement.py` | wraps forward / inverse | used by `HealpixSampling.forward_sht` | TODO | +| `base_transforms/` (numpy reference) | numpy only | kept in tests as reference, out of the public API | TODO | + +All of them take the sampling pytree instead of the `sampling=`, `nside=` and `L=` arguments: + +```python +s2fft.wigner.forward(f, L, N, sampling="mw") # today +SO3Sampling(base=eq, N=N).forward(f) # TODO +``` + +## 9. Build and backends + +Where the compiled code goes: + +```text +today rewrite +s2fft/ s2fft/ pure JAX +├── CMakeLists.txt └── src/s2fft/ +├── lib/ +│ ├── include/ 7 hdr s2fft-cuda/ from lib/, PR #442 +│ └── src/ 5 .cc/.cu ├── lib/ CUDA, cuFFT +└── src/s2fft/ └── pyproject.toml + + s2fft-tbb/ new lib/ + ├── lib/ C++, oneTBB + └── pyproject.toml +``` + +- `lib/` and `CMakeLists.txt` move to `s2fft-cuda` (part of [PR #442](https://github.com/astro-informatics/s2fft/pull/442)); a new `lib/` is written for `s2fft-tbb`. +- The stub `_s2fft` built without CUDA is no longer needed. +- Location of the plug-ins: a separate path in the s2fft repo, or their own repos in astro-informatics (TODO: to be discussed). + +Packaged, one command each: + +```bash +pip install s2fft # JAX only +pip install "s2fft[cuda]" # + s2fft-cuda +pip install "s2fft[tbb]" # + s2fft-tbb +``` + +- Prebuilt wheels on PyPI, built with cibuildwheel (already used by s2fft). +- No compiler or CUDA toolkit on the user side. + +```python +s2fft.config.update("S2FFT_BACKEND", "jax") +s2fft.config.update("S2FFT_BACKEND", "cuda") +s2fft.config.update("S2FFT_BACKEND", "tbb") +``` + +- `"jax"` is the default backend. No config exists today: dispatch goes through `method=` strings. +- TODO: an `S2FFT_BACKEND` environment variable and a context manager. +- TODO: raise an error or fall back to `"jax"` when the plug-in is missing. + +## 10. Compute examples + +```python +import jax, s2fft +jax.config.update("jax_enable_x64", True) + +gl = s2fft.RegularGaussian(L=512) +f = jax.random.normal(jax.random.key(0), gl.shape) + +alm = gl.forward_sht(f) # Alm +w = gl.quadrature_weights() # (nrings,) +cl = gl.forward_cl(f) # (L,) +ftm = gl.forward_ftm(f) # step 1a only +alm2 = gl.forward_legendre(ftm) # step 2 only + +loss = lambda f: (gl.forward_cl(f) ** 2).sum() +g = jax.grad(loss)(f) # differentiable end to end + +# TODO (v1.7): distributed +mesh = jax.make_mesh((4,), ("rings",)) +gl_sh = gl.shard(jax.NamedSharding(mesh, jax.P("rings"))) +alm = jax.jit(gl_sh.forward_sht)(f) +``` + +## 11. PyTorch through `jax2torch` + +- The torch backend is removed; torch users wrap the JAX methods. +- The wrapper builds on the existing `utils/torch_wrapper.py`: DLPack conversion, a `torch.autograd.Function` around `jax.vjp`, and conjugation of complex gradients. +- Torch is imported lazily, only when the wrapper is called. + +```python +from s2fft.torch import jax2torch +gl = s2fft.RegularGaussian(L=256) +sht = jax2torch(gl.forward_sht) # returns a torch-callable +alm = sht(torch_tensor) # torch.Tensor in, torch.Tensor out, autograd works +``` + +TODO: to be decided. Keep `wrap_as_torch_function` as is, or return `Alm` as a tensor plus metadata. + +## 12. Deprecation path + +```python +# v1.6: old call still works +flm = s2fft.forward(f, L, sampling="gl", method="jax") +# DeprecationWarning: use s2fft.RegularGaussian(L).forward_sht(f) +``` + +- v1.6: `s2fft.forward` / `s2fft.inverse` become shims that build the sampling object and call the method. +- v1.6: `method="numpy"` and `method="torch"` warn and run the JAX path. +- v1.6: `method="jax_cuda"` warns and maps to `S2FFT_BACKEND="cuda"`. +- `method="jax_healpy"` (the healpy wrapper) is removed as an option, closing [PR #440](https://github.com/astro-informatics/s2fft/pull/440): the CUDA kernels in the private CUDA PR are faster. +- v2.0: the shims, `*_numpy`, `*_jax`, `*_torch` and `method=` are removed (#349). + +## 13. TODO + +- [ ] Class names: `RegularGaussian` vs `GaussianSampling(variant=...)`; `EquiangularSampling(variant=...)` vs one class per scheme. +- [ ] Static-field syntax for the pinned JAX version (`jax.tree.static()` needs JAX ≥ 0.9). +- [ ] Sharding axis: rings for step 1a, $m$ for step 2, and the transpose between them. +- [ ] Scope of the `s2fft-tbb` kernels (ring FFT only, or Legendre too). +- [ ] Kernels for DISCO transforms in `s2fft-cuda` / `s2fft-tbb`? +- [ ] Final form of `jax2torch`. +- [ ] Wigner / SO(3) migration: `SO3Sampling(base=...)`. +- [ ] Ragged rings (reduced, octahedral, HEALPix): padded batched FFT vs per-ring loop (WIP in private CUDA PR). +- [ ] Reduced Gaussian $N_N$ ring-size table: source and licence. +- [ ] Status of the Array API refactor (#339) under a JAX-only core. diff --git a/design/assets/equiangular.png b/design/assets/equiangular.png new file mode 100644 index 00000000..3a736e65 Binary files /dev/null and b/design/assets/equiangular.png differ diff --git a/design/assets/gaussian_reduced.png b/design/assets/gaussian_reduced.png new file mode 100644 index 00000000..44f4ace9 Binary files /dev/null and b/design/assets/gaussian_reduced.png differ diff --git a/design/assets/gaussian_regular.png b/design/assets/gaussian_regular.png new file mode 100644 index 00000000..8414583b Binary files /dev/null and b/design/assets/gaussian_regular.png differ diff --git a/design/assets/healpix.png b/design/assets/healpix.png new file mode 100644 index 00000000..abfa435e Binary files /dev/null and b/design/assets/healpix.png differ diff --git a/design/assets/packages.drawio.svg b/design/assets/packages.drawio.svg new file mode 100644 index 00000000..c304ce1e --- /dev/null +++ b/design/assets/packages.drawio.svg @@ -0,0 +1,35 @@ + + +s2fft +pure JAX, pip install s2fft + +• samplings (pytree dataclasses) +• Alm, quadrature, Cℓ +• recursions, Wigner / SO(3), rotation +• FFI call sites + backend config +• jax2torch (lazy torch import) + + +s2fft-cuda +pip install s2fft-cuda +part of PR #442 + +• CUDA + cuFFT kernels (XLA FFI) +• HEALPix ring FFT (existing, lib/) +• Legendre step (v1.7) +• kernels for DISCO transforms? + + +s2fft-tbb +pip install s2fft-tbb + +• C++ / oneTBB kernels (XLA FFI) +• HEALPix ring FFT +• Legendre step +• kernels for DISCO transforms? + + +registers FFI targets +registers FFI targets +plug-ins depend on s2fft +s2fft never imports them eagerly diff --git a/design/assets/pytree_fields.drawio.svg b/design/assets/pytree_fields.drawio.svg new file mode 100644 index 00000000..7296c154 --- /dev/null +++ b/design/assets/pytree_fields.drawio.svg @@ -0,0 +1,18 @@ + +GaussianSampling(L=512) + +data fields (traced, leaves) +thetas (nrings,) +weights (nrings,) +nphi (nrings,) + +meta fields (static, hashable) +L, spin, reality +variant / N / nside +sharding: NamedSharding | None +backend (resolved at call time) + + +go through jit, grad, vmap +part of the jit cache key; +a new sharding retraces diff --git a/design/assets/quadrature_data.py b/design/assets/quadrature_data.py new file mode 100644 index 00000000..28a263d2 --- /dev/null +++ b/design/assets/quadrature_data.py @@ -0,0 +1,32 @@ +# Ring weights of four samplings, computed with s2fft's own numpy quadrature functions. +# Run with the s2fft environment: ../../.venv/bin/python quadrature_data.py +# Writes quadrature_weights.npz, read by quadrature_plot.py. +import numpy as np + +from s2fft.sampling import s2_samples as samples +from s2fft.utils import quadrature + +L, NSIDE = 32, 16 +out = {} +for s in ("gl", "dh", "cc"): + w = np.asarray(quadrature.quad_weights(L, s)) # per pixel, one value per ring + out[f"{s}_theta"] = samples.thetas(L, s) + out[f"{s}_ring"] = w * samples.nphi_equiang(L, s) # summed over the ring +w = np.asarray(quadrature.quad_weights(sampling="healpix", nside=NSIDE)) +nphi = np.array( + [ + samples.nphi_ring(t, NSIDE) + for t in range(samples.ntheta(sampling="healpix", nside=NSIDE)) + ] +) +out["healpix_theta"] = samples.thetas(sampling="healpix", nside=NSIDE) +out["healpix_ring"] = w * nphi +for s in ("gl", "dh", "cc", "healpix"): + print( + s, + out[f"{s}_theta"].shape, + out[f"{s}_ring"].shape, + "sum / 4pi =", + out[f"{s}_ring"].sum() / (4 * np.pi), + ) +np.savez("quadrature_weights.npz", **out) diff --git a/design/assets/quadrature_plot.py b/design/assets/quadrature_plot.py new file mode 100644 index 00000000..50aa075f --- /dev/null +++ b/design/assets/quadrature_plot.py @@ -0,0 +1,27 @@ +# Ring weights against colatitude for GL, DH, CC and HEALPix, from quadrature_weights.npz. +# Run: uv run --no-project --with numpy --with matplotlib python quadrature_plot.py +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +d = np.load("quadrature_weights.npz") +style = { + "gl": ("#C2560A", "o", "GL, L = 32"), + "dh": ("#3B6FB6", "s", "DH, L = 32"), + "cc": ("#2E2E2E", "^", "CC, L = 32"), + "healpix": ("#521463", "D", "HEALPix, nside = 16"), +} +fig, ax = plt.subplots(figsize=(5.2, 5.6)) +for s, (c, m, lab) in style.items(): + th, w = d[f"{s}_theta"], d[f"{s}_ring"] + ax.plot(np.degrees(th), w / w.mean(), m, ms=3.5, color=c, label=lab, lw=0) +ax.set_xlabel(r"colatitude $\theta$ (deg)") +ax.set_ylabel("ring weight / mean ring weight") +ax.set_xlim(0, 180) +ax.legend(frameon=False, fontsize=9) +for side in ("top", "right"): + ax.spines[side].set_visible(False) +fig.tight_layout() +fig.savefig("quadrature_weights.png", dpi=200, transparent=True) diff --git a/design/assets/quadrature_weights.png b/design/assets/quadrature_weights.png new file mode 100644 index 00000000..07b3a8e3 Binary files /dev/null and b/design/assets/quadrature_weights.png differ diff --git a/design/assets/s2fft_structure.drawio.svg b/design/assets/s2fft_structure.drawio.svg new file mode 100644 index 00000000..c609a191 --- /dev/null +++ b/design/assets/s2fft_structure.drawio.svg @@ -0,0 +1,60 @@ + +SphericalSampling (ABC, pytree) +• meta: L, spin, reality, sharding +• thetas(), phis(), quadrature_weights() +• forward_ftm / inverse_ftm step 1a +• forward_legendre / inverse_legendre step 2 +• forward_sht / inverse_sht, forward_cl +• shard(sharding), replicate() v1.7 + +EquiangularSampling +• variant: MW, MWSS, DH, CC, F2 +• rings equally spaced in θ + +GaussianSampling +• rings at roots of Pn +• nphi per ring (array) + +HealpixSampling +• meta: nside +• FFT + alias + phase +• iterative refinement + +StretchedSampling +• data: base (any sampling) +• meta: c, target lat/lon +• SHT in computational frame + + + + + + + +RegularGaussian +• GL: 2L−1 points +• FN: 4N points (#406) + +ReducedGaussian +• NN: table of ring sizes +• issue #434 + +OctahedralGaussian +• ON: 4i+16 points +• issue #434 + + + + + + +Alm (pytree) +• data: array +• meta: L, spin, layout +• to_1d / to_2d / to_hp, cl() + +Cℓ + +forward_sht returns + +.cl() diff --git a/design/assets/samplings.py b/design/assets/samplings.py new file mode 100644 index 00000000..c6d3a85a --- /dev/null +++ b/design/assets/samplings.py @@ -0,0 +1,135 @@ +# Node layouts of the samplings discussed in the design doc, drawn on an orthographic globe. +# Run: uv run --with numpy --with matplotlib python samplings.py +# Writes one PNG per sampling family next to this script. +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +INK = "#2E2E2E" +KW = "#C2560A" +KW2 = "#521463" +BLUE = "#3B6FB6" + +VIEW_LAT, VIEW_LON = np.radians(25.0), np.radians(-20.0) + + +def ortho(theta, phi, lat0=VIEW_LAT, lon0=VIEW_LON): + """Orthographic projection of colatitude/longitude; returns x, y and a front-side mask.""" + lat = np.pi / 2 - theta + x = np.cos(lat) * np.sin(phi - lon0) + y = np.cos(lat0) * np.sin(lat) - np.sin(lat0) * np.cos(lat) * np.cos(phi - lon0) + front = ( + np.sin(lat0) * np.sin(lat) + np.cos(lat0) * np.cos(lat) * np.cos(phi - lon0) > 0 + ) + return x, y, front + + +def rings(thetas, nphis, offsets=None): + """Flatten ring grids: thetas[t] with nphis[t] equally spaced longitudes.""" + th, ph = [], [] + for t, (theta, n) in enumerate(zip(thetas, nphis, strict=False)): + off = 0.0 if offsets is None else offsets[t] + th.append(np.full(n, theta)) + ph.append(2 * np.pi * (np.arange(n) + off) / n) + return np.concatenate(th), np.concatenate(ph) + + +def gauss_thetas(nlat): + mu, _ = np.polynomial.legendre.leggauss(nlat) + return np.arccos(mu)[::-1] + + +def healpix(nside): + """Ring latitudes, ring sizes and half-pixel offsets of HEALPix.""" + th, n, off = [], [], [] + for i in range(1, 4 * nside): + if i < nside: + z = 1 - i**2 / (3 * nside**2) + npix, o = 4 * i, 0.5 + elif i <= 3 * nside: + z = 4 / 3 - 2 * i / (3 * nside) + npix, o = 4 * nside, 0.5 if (i - nside) % 2 == 0 else 0.0 + else: + j = 4 * nside - i + z = -(1 - j**2 / (3 * nside**2)) + npix, o = 4 * j, 0.5 + th.append(np.arccos(z)) + n.append(npix) + off.append(o) + return th, n, off + + +def schmidt(theta, phi, c, lat0, lon0): + """Schmidt stretch towards (lat0, lon0): tan(theta_E/2) = tan(theta_c/2)/c, then rotate pole to target.""" + th = 2 * np.arctan(np.tan(theta / 2) / c) + v = np.stack([np.sin(th) * np.cos(phi), np.sin(th) * np.sin(phi), np.cos(th)]) + t = np.array( + [np.cos(lat0) * np.cos(lon0), np.cos(lat0) * np.sin(lon0), np.sin(lat0)] + ) + e = np.cross([0.0, 0.0, 1.0], t) + e /= np.linalg.norm(e) + n = np.cross(t, e) + u = np.stack([e, n, t], axis=1) @ v + return np.arccos(np.clip(u[2], -1, 1)), np.arctan2(u[1], u[0]) + + +def draw(ax, theta, phi, color, title, size=4): + circle = plt.Circle((0, 0), 1, facecolor="#faf7f0", edgecolor=INK, lw=1.0) + ax.add_patch(circle) + x, y, front = ortho(theta, phi) + ax.scatter(x[front], y[front], s=size, color=color, lw=0) + ax.set_xlim(-1.05, 1.05) + ax.set_ylim(-1.05, 1.05) + ax.set_aspect("equal") + ax.axis("off") + ax.set_title(title, color=INK, fontsize=11) + + +def save(panels, name): + """Write {name}.png (panels side by side, for DESIGN.md) and {name}_v.png (stacked, for the slides).""" + n = len(panels) + for suffix, shape, size in ( + ("", (1, n), (3.2 * n, 3.4)), + ("_v", (n, 1), (3.4, 3.6 * n)), + ): + fig, axes = plt.subplots(*shape, figsize=size) + axes = np.atleast_1d(axes) + for ax, (theta, phi, color, title) in zip(axes, panels, strict=False): + draw(ax, theta, phi, color, title) + fig.tight_layout() + fig.savefig(f"{name}{suffix}.png", dpi=200, transparent=True) + plt.close(fig) + + +L = 24 + +# Equiangular: MW rings at (2t+1)pi/(2L-1), 2L-1 points; MWSS rings at t pi/L, 2L points. +mw = rings((2 * np.arange(L) + 1) * np.pi / (2 * L - 1), [2 * L - 1] * L) +mwss = rings(np.arange(L + 1) * np.pi / L, [2 * L] * (L + 1)) +save([(*mw, BLUE, "MW"), (*mwss, BLUE, "MWSS")], "equiangular") + +# Gaussian family. +N = 12 +gl = rings(gauss_thetas(L), [2 * L - 1] * L) +fn = rings(gauss_thetas(2 * N), [4 * N] * (2 * N)) +# Octahedral O_N: ring i from the pole has 4i + 16 points. +o_n = [4 * i + 16 for i in range(1, N + 1)] +on = rings(gauss_thetas(2 * N), o_n + o_n[::-1]) +# Reduced N_N: illustrative only, ring sizes follow 4N sin(theta) (the ECMWF table is not reproduced). +th_n = gauss_thetas(2 * N) +nn = rings(th_n, [max(8, int(np.ceil(4 * N * np.sin(t) / 4)) * 4) for t in th_n]) +save([(*gl, KW, "GL (2L-1)"), (*fn, KW, "Regular F$_N$ (4N)")], "gaussian_regular") +save( + [(*on, KW, "Octahedral O$_N$"), (*nn, KW, "Reduced N$_N$ (illustrative)")], + "gaussian_reduced", +) + +# HEALPix. +hp = rings(*healpix(8)) +save([(*hp, KW2, "HEALPix, nside 8")], "healpix") + +# Stretched GL towards London with c = 2.4. +st = schmidt(*gl, 2.4, np.radians(51.5), np.radians(-0.13)) +save([(*gl, KW, "GL, c = 1"), (*st, KW, "GL, c = 2.4 (London)")], "stretched") diff --git a/design/assets/sht_pipeline.drawio.svg b/design/assets/sht_pipeline.drawio.svg new file mode 100644 index 00000000..0e21a5a6 --- /dev/null +++ b/design/assets/sht_pipeline.drawio.svg @@ -0,0 +1,31 @@ + +f(θt, φp) +map on rings + +ftm +Fourier per ring + +fℓm +Alm + +Cℓ + +step 1a +forward_ftm + +step 2 +forward_legendre + +Alm.cl() + +step 0 grid: θt, φp, qt +constructor, quadrature_weights() + + + + +forward_sht = forward_legendre ∘ forward_ftm + + + +forward_cl diff --git a/design/assets/stretched.png b/design/assets/stretched.png new file mode 100644 index 00000000..5317175f Binary files /dev/null and b/design/assets/stretched.png differ diff --git a/src/s2fft/__init__.py b/src/s2fft/__init__.py index 445f5719..3a72a070 100644 --- a/src/s2fft/__init__.py +++ b/src/s2fft/__init__.py @@ -8,6 +8,17 @@ generate_precomputes_wigner, generate_precomputes_wigner_jax, ) +from .sampling.abstract_sampling import AbstractSampling +from .sampling.alm import Alm +from .sampling.clenshaw_curtis import ClenshawCurtisSampling +from .sampling.driscoll_healy import DriscollHealySampling +from .sampling.fejer2 import Fejer2Sampling +from .sampling.gauss_legendre import GaussLegendreSampling +from .sampling.healpix import HealpixSampling +from .sampling.mw import MWSampling +from .sampling.mwss import MWSSSampling +from .sampling.octahedral_gaussian import OctahedralGaussianSampling +from .sampling.reduced_gaussian import ReducedGaussianSampling from .transforms import wigner from .transforms.spherical import ( forward, diff --git a/src/s2fft/sampling/abstract_sampling.py b/src/s2fft/sampling/abstract_sampling.py new file mode 100644 index 00000000..42ce91a4 --- /dev/null +++ b/src/s2fft/sampling/abstract_sampling.py @@ -0,0 +1,168 @@ +import abc +from dataclasses import dataclass + +import jax +import jax.numpy as jnp + +from s2fft.precompute_transforms import spherical as precompute_spherical +from s2fft.sampling import s2_samples +from s2fft.sampling.alm import Alm +from s2fft.transforms import spherical, wigner +from s2fft.utils import quadrature_jax + +# Default of the thetas and weights fields, meaning "compute them from L". JAX rebuilds +# pytrees with stand-in leaves (tracers, None, placeholder objects), so __post_init__ +# computes the fields only when it sees this marker, never on any other value. +NOT_GIVEN = object() + + +@dataclass(frozen=True, kw_only=True) +class AbstractSampling(abc.ABC): + r""" + Sampling scheme on the sphere, as a JAX pytree. + + The data fields are the arrays ``thetas`` and ``weights``. The meta fields + (``L``, ``spin``, ``reality``, ``L_lower``) are static: they are part of the treedef, + so a new value retraces a jitted function. + + The methods call the existing transforms (:mod:`s2fft.transforms.spherical`, + :mod:`s2fft.transforms.wigner`, :mod:`s2fft.precompute_transforms.spherical`) with + ``method="jax"`` and the ``sampling`` string of the subclass. Those transforms + compute their own grid, so they do not read the ``thetas`` and ``weights`` fields. + + Args: + L (int): Harmonic band-limit. + + spin (int, optional): Harmonic spin. Defaults to 0. + + reality (bool, optional): Whether the signal on the sphere is real. Defaults to + False. + + L_lower (int, optional): Harmonic lower-bound. Defaults to 0. + + thetas (jax.Array, optional): :math:`\theta` samples. Computed from ``L`` with + :func:`s2fft.sampling.s2_samples.thetas` when not given. + + weights (jax.Array, optional): Quadrature weights per :math:`\theta` ring. + Computed from ``L`` with :func:`s2fft.utils.quadrature_jax.quad_weights` + when not given. + + """ + + L: int + spin: int = 0 + reality: bool = False + L_lower: int = 0 + thetas: jax.Array = NOT_GIVEN + weights: jax.Array = NOT_GIVEN + + @property + @abc.abstractmethod + def sampling(self) -> str: + """Sampling string of the existing API, e.g. ``"gl"``.""" + + def __post_init__(self): + """Compute thetas and weights from L when they were not given.""" + if self.thetas is NOT_GIVEN: + object.__setattr__( + self, "thetas", jnp.asarray(s2_samples.thetas(self.L, self.sampling)) + ) + if self.weights is NOT_GIVEN: + object.__setattr__( + self, "weights", quadrature_jax.quad_weights(self.L, self.sampling) + ) + + @property + def shape(self) -> tuple[int, ...]: + """Shape of a signal on this sampling.""" + return s2_samples.f_shape(self.L, self.sampling) + + def forward_sht(self, f: jnp.ndarray) -> Alm: + """Forward spin-spherical harmonic transform, via :func:`spherical.forward`.""" + flm = spherical.forward( + f, + self.L, + spin=self.spin, + sampling=self.sampling, + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + return Alm(array=flm, L=self.L, spin=self.spin, reality=self.reality) + + def inverse_sht(self, alm: Alm) -> jnp.ndarray: + """Inverse spin-spherical harmonic transform, via :func:`spherical.inverse`.""" + return spherical.inverse( + alm.array, + self.L, + spin=self.spin, + sampling=self.sampling, + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def forward_cl(self, f: jnp.ndarray) -> jnp.ndarray: + """Angular power spectrum of a signal, ``forward_sht(f).cl()``.""" + return self.forward_sht(f).cl() + + def forward_wigner(self, f: jnp.ndarray, N: int) -> jnp.ndarray: + """Forward Wigner transform, via :func:`wigner.forward`.""" + return wigner.forward( + f, + self.L, + N, + sampling=self.sampling, + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def inverse_wigner(self, flmn: jnp.ndarray, N: int) -> jnp.ndarray: + """Inverse Wigner transform, via :func:`wigner.inverse`.""" + return wigner.inverse( + flmn, + self.L, + N, + sampling=self.sampling, + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def forward_precompute( + self, f: jnp.ndarray, kernel: jnp.ndarray | None = None + ) -> Alm: + """ + Forward transform with a precomputed kernel, via + :func:`s2fft.precompute_transforms.spherical.forward`. The kernel is built + when not given. ``L_lower`` is not used: the precompute transforms take none. + """ + flm = precompute_spherical.forward( + f, + self.L, + spin=self.spin, + kernel=kernel, + sampling=self.sampling, + reality=self.reality, + method="jax", + ) + return Alm(array=flm, L=self.L, spin=self.spin, reality=self.reality) + + def inverse_precompute( + self, alm: Alm, kernel: jnp.ndarray | None = None + ) -> jnp.ndarray: + """ + Inverse transform with a precomputed kernel, via + :func:`s2fft.precompute_transforms.spherical.inverse`. The kernel is built + when not given. ``L_lower`` is not used: the precompute transforms take none. + """ + return precompute_spherical.inverse( + alm.array, + self.L, + spin=self.spin, + kernel=kernel, + sampling=self.sampling, + reality=self.reality, + method="jax", + ) diff --git a/src/s2fft/sampling/alm.py b/src/s2fft/sampling/alm.py new file mode 100644 index 00000000..1e725680 --- /dev/null +++ b/src/s2fft/sampling/alm.py @@ -0,0 +1,125 @@ +from dataclasses import dataclass, replace +from functools import partial + +import jax +import jax.numpy as jnp + +from s2fft.sampling import reindex +from s2fft.utils import rotation + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["array"], + meta_fields=["L", "spin", "reality", "layout"], +) +@dataclass(frozen=True, kw_only=True) +class Alm: + r""" + Spherical harmonic coefficients, the output of every ``forward_sht``. + + Layouts, from :mod:`s2fft.sampling.reindex`: + + * ``"2d"``: shape :math:`[L, 2L-1]`, indexed :math:`[\ell, L-1+m]`, with zeros for + :math:`|m| > \ell`. + * ``"1d"``: shape :math:`[L^2]`, index :math:`\ell^2 + \ell + m`. + * ``"hp"``: healpy order, :math:`m \geq 0` only, for real signals. + + Args: + array (jax.Array): Coefficients in the given layout. + + L (int): Harmonic band-limit. + + spin (int, optional): Harmonic spin. Defaults to 0. + + reality (bool, optional): Whether the signal on the sphere is real. Defaults to + False. + + layout (str, optional): One of ``"2d"``, ``"1d"``, ``"hp"``. Defaults to + ``"2d"``. + + """ + + array: jax.Array + L: int + spin: int = 0 + reality: bool = False + layout: str = "2d" + + def to_2d(self) -> "Alm": + """Coefficients in the ``"2d"`` layout.""" + if self.layout == "1d": + return replace( + self, array=reindex.flm_1d_to_2d_fast(self.array, self.L), layout="2d" + ) + if self.layout == "hp": + return replace( + self, array=reindex.flm_hp_to_2d_fast(self.array, self.L), layout="2d" + ) + return self + + def to_1d(self) -> "Alm": + """Coefficients in the ``"1d"`` layout.""" + return replace( + self, + array=reindex.flm_2d_to_1d_fast(self.to_2d().array, self.L), + layout="1d", + ) + + def to_hp(self) -> "Alm": + r""" + Coefficients in the healpy layout, which keeps only :math:`m \geq 0` of a + real signal. + """ + return replace( + self, + array=reindex.flm_2d_to_hp_fast(self.to_2d().array, self.L), + layout="hp", + ) + + def cl(self, other: "Alm | None" = None) -> jnp.ndarray: + r""" + Angular power spectrum :math:`C_\ell = \sum_m a_{\ell m} b_{\ell m}^* / (2\ell+1)`, + the auto-spectrum when ``other`` is None, the cross-spectrum otherwise. + """ + a = self.to_2d().array + b = a if other is None else other.to_2d().array + nm = 2 * jnp.arange(self.L) + 1 + return (a * b.conj()).real.sum(-1) / nm + + def __add__(self, other: "Alm") -> "Alm": + """Sum of two Alm with the same L, spin, reality and layout.""" + if (self.L, self.spin, self.reality, self.layout) != ( + other.L, + other.spin, + other.reality, + other.layout, + ): + raise ValueError( + "Alm addition needs the same L, spin, reality and layout, got " + f"{(self.L, self.spin, self.reality, self.layout)} and " + f"{(other.L, other.spin, other.reality, other.layout)}." + ) + return replace(self, array=self.array + other.array) + + def __mul__(self, x) -> "Alm": + r""" + Product with a scalar, or with a :math:`b_\ell` of shape ``(L,)`` applied to + the rows of the ``"2d"`` layout (the result is in that layout). + """ + if jnp.ndim(x) == 0: + return replace(self, array=self.array * x) + alm_2d = self.to_2d() + return replace(alm_2d, array=alm_2d.array * x[:, None]) + + def rotate(self, alpha: float, beta: float, gamma: float) -> "Alm": + r""" + Rotation by the Euler angles :math:`(\alpha, \beta, \gamma)`, via + :func:`s2fft.utils.rotation.rotate_flms` (the angles are static there). The + result is in the ``"2d"`` layout. + """ + alm_2d = self.to_2d() + return replace( + alm_2d, + array=rotation.rotate_flms(alm_2d.array, self.L, (alpha, beta, gamma)), + ) diff --git a/src/s2fft/sampling/clenshaw_curtis.py b/src/s2fft/sampling/clenshaw_curtis.py new file mode 100644 index 00000000..a2d2919b --- /dev/null +++ b/src/s2fft/sampling/clenshaw_curtis.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class ClenshawCurtisSampling(AbstractSampling): + """Clenshaw-Curtis (CC): ``sampling="cc"`` in the existing API.""" + + sampling: ClassVar[str] = "cc" diff --git a/src/s2fft/sampling/driscoll_healy.py b/src/s2fft/sampling/driscoll_healy.py new file mode 100644 index 00000000..0f531e01 --- /dev/null +++ b/src/s2fft/sampling/driscoll_healy.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class DriscollHealySampling(AbstractSampling): + """Driscoll & Healy (DH): ``sampling="dh"`` in the existing API.""" + + sampling: ClassVar[str] = "dh" diff --git a/src/s2fft/sampling/fejer2.py b/src/s2fft/sampling/fejer2.py new file mode 100644 index 00000000..179cdc02 --- /dev/null +++ b/src/s2fft/sampling/fejer2.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class Fejer2Sampling(AbstractSampling): + """Fejér's second rule (F2): ``sampling="f2"`` in the existing API.""" + + sampling: ClassVar[str] = "f2" diff --git a/src/s2fft/sampling/gauss_legendre.py b/src/s2fft/sampling/gauss_legendre.py new file mode 100644 index 00000000..9ba83cc4 --- /dev/null +++ b/src/s2fft/sampling/gauss_legendre.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class GaussLegendreSampling(AbstractSampling): + """Gauss-Legendre (GL): ``sampling="gl"`` in the existing API.""" + + sampling: ClassVar[str] = "gl" diff --git a/src/s2fft/sampling/healpix.py b/src/s2fft/sampling/healpix.py new file mode 100644 index 00000000..bfa2f677 --- /dev/null +++ b/src/s2fft/sampling/healpix.py @@ -0,0 +1,150 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax +import jax.numpy as jnp + +from s2fft.precompute_transforms import spherical as precompute_spherical +from s2fft.sampling import s2_samples +from s2fft.sampling.abstract_sampling import NOT_GIVEN, AbstractSampling +from s2fft.sampling.alm import Alm +from s2fft.transforms import spherical, wigner +from s2fft.utils import quadrature_jax + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "nside", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class HealpixSampling(AbstractSampling): + """ + HEALPix: ``sampling="healpix"`` in the existing API. + + Each method makes the call of :class:`AbstractSampling` with ``nside`` added. + + Args: + nside (int): HEALPix Nside resolution parameter. + + """ + + sampling: ClassVar[str] = "healpix" + nside: int + + def __post_init__(self): + """Compute thetas and weights from L when they were not given.""" + if self.thetas is NOT_GIVEN: + object.__setattr__( + self, + "thetas", + jnp.asarray(s2_samples.thetas(self.L, "healpix", self.nside)), + ) + if self.weights is NOT_GIVEN: + object.__setattr__( + self, + "weights", + quadrature_jax.quad_weights(self.L, "healpix", self.nside), + ) + + @property + def shape(self) -> tuple[int, ...]: + """Shape of a signal on this sampling, :math:`(12 N_{side}^2,)`.""" + return s2_samples.f_shape(self.L, "healpix", self.nside) + + def forward_sht(self, f: jnp.ndarray, iter: int = 0) -> Alm: + """ + Forward spin-spherical harmonic transform, via :func:`spherical.forward`, with + ``iter`` iterations of iterative refinement. + """ + flm = spherical.forward( + f, + self.L, + spin=self.spin, + nside=self.nside, + sampling="healpix", + method="jax", + reality=self.reality, + L_lower=self.L_lower, + iter=iter, + ) + return Alm(array=flm, L=self.L, spin=self.spin, reality=self.reality) + + def inverse_sht(self, alm: Alm) -> jnp.ndarray: + """Inverse spin-spherical harmonic transform, via :func:`spherical.inverse`.""" + return spherical.inverse( + alm.array, + self.L, + spin=self.spin, + nside=self.nside, + sampling="healpix", + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def forward_wigner(self, f: jnp.ndarray, N: int) -> jnp.ndarray: + """Forward Wigner transform, via :func:`wigner.forward`.""" + return wigner.forward( + f, + self.L, + N, + nside=self.nside, + sampling="healpix", + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def inverse_wigner(self, flmn: jnp.ndarray, N: int) -> jnp.ndarray: + """Inverse Wigner transform, via :func:`wigner.inverse`.""" + return wigner.inverse( + flmn, + self.L, + N, + nside=self.nside, + sampling="healpix", + method="jax", + reality=self.reality, + L_lower=self.L_lower, + ) + + def forward_precompute( + self, f: jnp.ndarray, kernel: jnp.ndarray | None = None + ) -> Alm: + """ + Forward transform with a precomputed kernel, via + :func:`s2fft.precompute_transforms.spherical.forward`. The kernel is built + when not given. ``L_lower`` is not used: the precompute transforms take none. + """ + flm = precompute_spherical.forward( + f, + self.L, + spin=self.spin, + kernel=kernel, + sampling="healpix", + reality=self.reality, + method="jax", + nside=self.nside, + ) + return Alm(array=flm, L=self.L, spin=self.spin, reality=self.reality) + + def inverse_precompute( + self, alm: Alm, kernel: jnp.ndarray | None = None + ) -> jnp.ndarray: + """ + Inverse transform with a precomputed kernel, via + :func:`s2fft.precompute_transforms.spherical.inverse`. The kernel is built + when not given. ``L_lower`` is not used: the precompute transforms take none. + """ + return precompute_spherical.inverse( + alm.array, + self.L, + spin=self.spin, + kernel=kernel, + sampling="healpix", + reality=self.reality, + method="jax", + nside=self.nside, + ) diff --git a/src/s2fft/sampling/mw.py b/src/s2fft/sampling/mw.py new file mode 100644 index 00000000..04595635 --- /dev/null +++ b/src/s2fft/sampling/mw.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class MWSampling(AbstractSampling): + """McEwen & Wiaux (MW): ``sampling="mw"`` in the existing API.""" + + sampling: ClassVar[str] = "mw" diff --git a/src/s2fft/sampling/mwss.py b/src/s2fft/sampling/mwss.py new file mode 100644 index 00000000..a5b999df --- /dev/null +++ b/src/s2fft/sampling/mwss.py @@ -0,0 +1,19 @@ +from dataclasses import dataclass +from functools import partial +from typing import ClassVar + +import jax + +from s2fft.sampling.abstract_sampling import AbstractSampling + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class MWSSSampling(AbstractSampling): + """McEwen & Wiaux Symmetric Sampling (MWSS): ``sampling="mwss"`` in the existing API.""" + + sampling: ClassVar[str] = "mwss" diff --git a/src/s2fft/sampling/octahedral_gaussian.py b/src/s2fft/sampling/octahedral_gaussian.py new file mode 100644 index 00000000..ced3d1a9 --- /dev/null +++ b/src/s2fft/sampling/octahedral_gaussian.py @@ -0,0 +1,77 @@ +from dataclasses import dataclass +from functools import partial + +import jax +import jax.numpy as jnp + +from s2fft.sampling.abstract_sampling import AbstractSampling +from s2fft.sampling.alm import Alm + +NOT_IMPLEMENTED = "Octahedral Gaussian sampling is not implemented yet (#434)." + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "N", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class OctahedralGaussianSampling(AbstractSampling): + """ + Octahedral Gaussian sampling (#434). Not implemented: every + method raises NotImplementedError, construction included. + + O_N: ring i from the pole has 4i+16 points. + + Args: + N (int): Resolution number of the grid, the N of O_N. + + """ + + N: int + + @property + def sampling(self) -> str: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def __post_init__(self): + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + @property + def shape(self) -> tuple[int, ...]: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_sht(self, f: jnp.ndarray) -> Alm: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_sht(self, alm: Alm) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_cl(self, f: jnp.ndarray) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_wigner(self, f: jnp.ndarray, N: int) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_wigner(self, flmn: jnp.ndarray, N: int) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_precompute( + self, f: jnp.ndarray, kernel: jnp.ndarray | None = None + ) -> Alm: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_precompute( + self, alm: Alm, kernel: jnp.ndarray | None = None + ) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) diff --git a/src/s2fft/sampling/reduced_gaussian.py b/src/s2fft/sampling/reduced_gaussian.py new file mode 100644 index 00000000..2ef64522 --- /dev/null +++ b/src/s2fft/sampling/reduced_gaussian.py @@ -0,0 +1,77 @@ +from dataclasses import dataclass +from functools import partial + +import jax +import jax.numpy as jnp + +from s2fft.sampling.abstract_sampling import AbstractSampling +from s2fft.sampling.alm import Alm + +NOT_IMPLEMENTED = "Reduced Gaussian sampling is not implemented yet (#434)." + + +@partial( + jax.tree_util.register_dataclass, + data_fields=["thetas", "weights"], + meta_fields=["L", "N", "spin", "reality", "L_lower"], +) +@dataclass(frozen=True, kw_only=True) +class ReducedGaussianSampling(AbstractSampling): + """ + Reduced Gaussian sampling (#434). Not implemented: every + method raises NotImplementedError, construction included. + + N_N: ring sizes from a stored table; step 1a keeps m <= NMEN_t. + + Args: + N (int): Resolution number of the grid, the N of N_N. + + """ + + N: int + + @property + def sampling(self) -> str: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def __post_init__(self): + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + @property + def shape(self) -> tuple[int, ...]: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_sht(self, f: jnp.ndarray) -> Alm: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_sht(self, alm: Alm) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_cl(self, f: jnp.ndarray) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_wigner(self, f: jnp.ndarray, N: int) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_wigner(self, flmn: jnp.ndarray, N: int) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def forward_precompute( + self, f: jnp.ndarray, kernel: jnp.ndarray | None = None + ) -> Alm: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) + + def inverse_precompute( + self, alm: Alm, kernel: jnp.ndarray | None = None + ) -> jnp.ndarray: + """Not implemented (#434).""" + raise NotImplementedError(NOT_IMPLEMENTED) diff --git a/tests/test_sampling_classes.py b/tests/test_sampling_classes.py new file mode 100644 index 00000000..5d5945e0 --- /dev/null +++ b/tests/test_sampling_classes.py @@ -0,0 +1,221 @@ +import jax +import numpy as np +import pytest + +import s2fft +from s2fft.precompute_transforms import spherical as precompute_spherical +from s2fft.sampling import reindex, s2_samples +from s2fft.transforms import wigner +from s2fft.utils import quadrature_jax, rotation + +jax.config.update("jax_enable_x64", True) + +L_to_test = [6, 7] +spin_to_test = [-2, 0, 1] +reality_to_test = [False, True] +sampling_to_test = ["mw", "mwss", "dh", "gl", "cc", "f2", "healpix"] +wigner_sampling_to_test = ["mw", "mwss", "dh", "gl", "healpix"] + +equiangular_classes = { + "mw": s2fft.MWSampling, + "mwss": s2fft.MWSSSampling, + "dh": s2fft.DriscollHealySampling, + "gl": s2fft.GaussLegendreSampling, + "cc": s2fft.ClenshawCurtisSampling, + "f2": s2fft.Fejer2Sampling, +} + + +def build_sampling(sampling: str, L: int, spin: int, reality: bool): + """ + Sampling object and its nside (None for equiangular schemes). HEALPix needs + L >= 2 nside (healpix_ifft), so it takes nside 4 and 5 with L = 2 nside, the nside + values of test_spherical_transform.py. + """ + if sampling == "healpix": + nside = {6: 4, 7: 5}[L] + return s2fft.HealpixSampling( + L=2 * nside, nside=nside, spin=spin, reality=reality + ), nside + return equiangular_classes[sampling](L=L, spin=spin, reality=reality), None + + +@pytest.mark.parametrize("L", L_to_test) +@pytest.mark.parametrize("spin", spin_to_test) +@pytest.mark.parametrize("sampling", sampling_to_test) +@pytest.mark.parametrize("reality", reality_to_test) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_sht_matches_old_api(flm_generator, L, spin, sampling, reality): + if reality and spin != 0: + pytest.skip("generate_flm does not give a real signal at spin != 0.") + s, nside = build_sampling(sampling, L, spin, reality) + flm = flm_generator(L=s.L, spin=spin, reality=reality) + + f_old = s2fft.inverse( + flm, s.L, spin, nside, sampling, method="jax", reality=reality + ) + f_new = s.inverse_sht(s2fft.Alm(array=flm, L=s.L, spin=spin, reality=reality)) + np.testing.assert_array_equal(f_new, f_old) + + flm_old = s2fft.forward( + f_old, s.L, spin, nside, sampling, method="jax", reality=reality + ) + alm = s.forward_sht(f_old) + assert (alm.L, alm.spin, alm.reality, alm.layout) == (s.L, spin, reality, "2d") + np.testing.assert_array_equal(alm.array, flm_old) + + if sampling == "healpix": + flm_old_iter = s2fft.forward( + f_old, s.L, spin, nside, sampling, method="jax", reality=reality, iter=2 + ) + np.testing.assert_array_equal(s.forward_sht(f_old, iter=2).array, flm_old_iter) + + +@pytest.mark.parametrize("L", L_to_test) +@pytest.mark.parametrize("sampling", wigner_sampling_to_test) +@pytest.mark.parametrize("reality", reality_to_test) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_wigner_matches_old_api(flmn_generator, L, sampling, reality): + N = 2 + s, nside = build_sampling(sampling, L, 0, reality) + flmn = flmn_generator(L=s.L, N=N, reality=reality) + + f_old = wigner.inverse(flmn, s.L, N, nside, sampling, method="jax", reality=reality) + np.testing.assert_array_equal(s.inverse_wigner(flmn, N), f_old) + + flmn_old = wigner.forward( + f_old, s.L, N, nside, sampling, method="jax", reality=reality + ) + np.testing.assert_array_equal(s.forward_wigner(f_old, N), flmn_old) + + +@pytest.mark.parametrize("L", L_to_test) +@pytest.mark.parametrize("spin", spin_to_test) +@pytest.mark.parametrize("sampling", sampling_to_test) +@pytest.mark.parametrize("reality", reality_to_test) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_precompute_matches_old_api(flm_generator, L, spin, sampling, reality): + if reality and spin != 0: + pytest.skip("generate_flm does not give a real signal at spin != 0.") + s, nside = build_sampling(sampling, L, spin, reality) + flm = flm_generator(L=s.L, spin=spin, reality=reality) + + f_old = precompute_spherical.inverse( + flm, s.L, spin, None, sampling, reality, "jax", nside + ) + f_new = s.inverse_precompute( + s2fft.Alm(array=flm, L=s.L, spin=spin, reality=reality) + ) + np.testing.assert_array_equal(f_new, f_old) + + flm_old = precompute_spherical.forward( + f_old, s.L, spin, None, sampling, reality, "jax", nside + ) + np.testing.assert_array_equal(s.forward_precompute(f_old).array, flm_old) + + +@pytest.mark.parametrize("L", L_to_test) +@pytest.mark.parametrize("sampling", sampling_to_test) +def test_fields(L, sampling): + s, nside = build_sampling(sampling, L, 0, False) + np.testing.assert_array_equal(s.thetas, s2_samples.thetas(s.L, sampling, nside)) + np.testing.assert_array_equal( + s.weights, quadrature_jax.quad_weights(s.L, sampling, nside) + ) + assert s.shape == s2_samples.f_shape(s.L, sampling, nside) + + +@pytest.mark.parametrize("sampling", sampling_to_test) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_pytree(flm_generator, sampling): + s, nside = build_sampling(sampling, 6, 0, False) + + leaves, treedef = jax.tree.flatten(s) + assert len(leaves) == 2 + assert leaves[0] is s.thetas + assert leaves[1] is s.weights + + # Unflatten passes the leaves as they are: __post_init__ does not recompute them. + rebuilt = jax.tree.unflatten(treedef, leaves) + assert type(rebuilt) is type(s) + assert rebuilt.thetas is s.thetas + assert rebuilt.weights is s.weights + assert (rebuilt.L, rebuilt.spin, rebuilt.reality, rebuilt.L_lower) == ( + s.L, + s.spin, + s.reality, + s.L_lower, + ) + + # Stand-in leaves such as None stay as they are. + stand_in = jax.tree.map(lambda x: None, s) + assert stand_in.thetas is None + assert stand_in.weights is None + + flm = flm_generator(L=s.L) + f = s2fft.inverse(flm, s.L, 0, nside, sampling, method="jax") + flm_jit = jax.jit(lambda s, f: s.forward_sht(f).array)(s, f) + np.testing.assert_allclose(flm_jit, s.forward_sht(f).array, atol=1e-14) + + +@pytest.mark.parametrize("L", L_to_test) +def test_alm_layouts(flm_generator, L): + flm = flm_generator(L=L) + alm = s2fft.Alm(array=flm, L=L) + alm_1d = alm.to_1d() + assert alm_1d.layout == "1d" + np.testing.assert_array_equal(alm_1d.array, reindex.flm_2d_to_1d_fast(flm, L)) + np.testing.assert_array_equal(alm_1d.to_2d().array, flm) + + flm_real = flm_generator(L=L, reality=True) + alm_real = s2fft.Alm(array=flm_real, L=L, reality=True) + alm_hp = alm_real.to_hp() + assert alm_hp.layout == "hp" + np.testing.assert_allclose(alm_hp.to_2d().array, flm_real, atol=1e-14) + + +@pytest.mark.healpy +@pytest.mark.parametrize("L", L_to_test) +def test_alm_cl_matches_healpy(flm_generator, L): + import healpy + + a = s2fft.Alm(array=flm_generator(L=L, reality=True), L=L, reality=True) + b = s2fft.Alm(array=flm_generator(L=L, reality=True), L=L, reality=True) + a_hp = np.asarray(a.to_hp().array) + b_hp = np.asarray(b.to_hp().array) + np.testing.assert_allclose(a.cl(), healpy.alm2cl(a_hp, lmax=L - 1), rtol=1e-12) + np.testing.assert_allclose( + a.cl(b), healpy.alm2cl(a_hp, b_hp, lmax=L - 1), rtol=1e-12 + ) + + +@pytest.mark.parametrize("L", L_to_test) +def test_alm_arithmetic(flm_generator, L): + flm_a = flm_generator(L=L) + flm_b = flm_generator(L=L) + a = s2fft.Alm(array=flm_a, L=L) + b = s2fft.Alm(array=flm_b, L=L) + np.testing.assert_array_equal((a + b).array, flm_a + flm_b) + with pytest.raises(ValueError): + a + s2fft.Alm(array=flm_b, L=L, spin=1) + + np.testing.assert_array_equal((a * 2.5).array, flm_a * 2.5) + b_ell = np.arange(1, L + 1, dtype=np.float64) + np.testing.assert_array_equal((a * b_ell).array, flm_a * b_ell[:, None]) + + +@pytest.mark.parametrize("L", L_to_test) +def test_alm_rotate(flm_generator, L): + flm = flm_generator(L=L) + rotated = s2fft.Alm(array=flm, L=L).rotate(0.1, 0.2, 0.3) + np.testing.assert_array_equal( + rotated.array, rotation.rotate_flms(flm, L, (0.1, 0.2, 0.3)) + ) + + +@pytest.mark.parametrize( + "cls", [s2fft.OctahedralGaussianSampling, s2fft.ReducedGaussianSampling] +) +def test_reduced_grids_not_implemented(cls): + with pytest.raises(NotImplementedError): + cls(L=8, N=4)