From fa5446dae18ad1f6256aae4f18c9e1fe6ec49f8f Mon Sep 17 00:00:00 2001 From: Wassim KABALAN Date: Wed, 2 Dec 2026 11:02:34 +0000 Subject: [PATCH 1/4] Adding first layer of the s2fft refactoring --- src/s2fft/__init__.py | 11 ++ src/s2fft/sampling/abstract_sampling.py | 168 ++++++++++++++++ src/s2fft/sampling/alm.py | 125 ++++++++++++ src/s2fft/sampling/clenshaw_curtis.py | 19 ++ src/s2fft/sampling/driscoll_healy.py | 19 ++ src/s2fft/sampling/fejer2.py | 19 ++ src/s2fft/sampling/gauss_legendre.py | 19 ++ src/s2fft/sampling/healpix.py | 150 +++++++++++++++ src/s2fft/sampling/mw.py | 19 ++ src/s2fft/sampling/mwss.py | 19 ++ src/s2fft/sampling/octahedral_gaussian.py | 77 ++++++++ src/s2fft/sampling/reduced_gaussian.py | 77 ++++++++ tests/test_sampling_classes.py | 221 ++++++++++++++++++++++ 13 files changed, 943 insertions(+) create mode 100644 src/s2fft/sampling/abstract_sampling.py create mode 100644 src/s2fft/sampling/alm.py create mode 100644 src/s2fft/sampling/clenshaw_curtis.py create mode 100644 src/s2fft/sampling/driscoll_healy.py create mode 100644 src/s2fft/sampling/fejer2.py create mode 100644 src/s2fft/sampling/gauss_legendre.py create mode 100644 src/s2fft/sampling/healpix.py create mode 100644 src/s2fft/sampling/mw.py create mode 100644 src/s2fft/sampling/mwss.py create mode 100644 src/s2fft/sampling/octahedral_gaussian.py create mode 100644 src/s2fft/sampling/reduced_gaussian.py create mode 100644 tests/test_sampling_classes.py diff --git a/src/s2fft/__init__.py b/src/s2fft/__init__.py index 445f5719d..3a72a0700 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 000000000..42ce91a46 --- /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 000000000..1e7256801 --- /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 000000000..a2d2919b0 --- /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 000000000..0f531e011 --- /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 000000000..179cdc02c --- /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 000000000..9ba83cc45 --- /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 000000000..bfa2f6771 --- /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 000000000..04595635a --- /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 000000000..a5b999df6 --- /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 000000000..ced3d1a9c --- /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 000000000..2ef64522b --- /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 000000000..5d5945e06 --- /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) From 1c145029cd2cd994c2b7bf896979043d754a7584 Mon Sep 17 00:00:00 2001 From: Wassim KABALAN Date: Thu, 3 Dec 2026 14:54:12 +0000 Subject: [PATCH 2/4] Add method to the SHT methods, infer Alm layout, support batched Alm --- src/s2fft/sampling/abstract_sampling.py | 23 ++++-- src/s2fft/sampling/alm.py | 95 +++++++++++++++-------- src/s2fft/sampling/healpix.py | 21 +++-- src/s2fft/sampling/octahedral_gaussian.py | 4 +- src/s2fft/sampling/reduced_gaussian.py | 4 +- tests/test_sampling_classes.py | 80 +++++++++++++++++++ 6 files changed, 178 insertions(+), 49 deletions(-) diff --git a/src/s2fft/sampling/abstract_sampling.py b/src/s2fft/sampling/abstract_sampling.py index 42ce91a46..6b709e080 100644 --- a/src/s2fft/sampling/abstract_sampling.py +++ b/src/s2fft/sampling/abstract_sampling.py @@ -77,27 +77,38 @@ 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`.""" + def forward_sht(self, f: jnp.ndarray, *, method: str = "jax") -> Alm: + """ + Forward spin-spherical harmonic transform, via :func:`spherical.forward`. + ``method`` is ``"jax"`` or ``"jax_cuda"``. The latter changes only the HEALPix + FFT, so for an equiangular sampling it gives the result of ``"jax"``. + """ + if method not in ("jax", "jax_cuda"): + raise ValueError(f"method must be 'jax' or 'jax_cuda', got {method!r}.") flm = spherical.forward( f, self.L, spin=self.spin, sampling=self.sampling, - method="jax", + method=method, 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`.""" + def inverse_sht(self, alm: Alm, *, method: str = "jax") -> jnp.ndarray: + """ + Inverse spin-spherical harmonic transform, via :func:`spherical.inverse`. + ``method`` is ``"jax"`` or ``"jax_cuda"``, as in :meth:`forward_sht`. + """ + if method not in ("jax", "jax_cuda"): + raise ValueError(f"method must be 'jax' or 'jax_cuda', got {method!r}.") return spherical.inverse( alm.array, self.L, spin=self.spin, sampling=self.sampling, - method="jax", + method=method, reality=self.reality, L_lower=self.L_lower, ) diff --git a/src/s2fft/sampling/alm.py b/src/s2fft/sampling/alm.py index 1e7256801..0f32fcc2f 100644 --- a/src/s2fft/sampling/alm.py +++ b/src/s2fft/sampling/alm.py @@ -7,6 +7,11 @@ from s2fft.sampling import reindex from s2fft.utils import rotation +# Default of the layout field, meaning "infer it from the shape of the array". JAX +# rebuilds the pytree with the layout it stored, so __post_init__ infers it only when +# it sees this marker, at construction by the user. +LAYOUT_FROM_SHAPE = object() + @partial( jax.tree_util.register_dataclass, @@ -18,12 +23,14 @@ class Alm: r""" Spherical harmonic coefficients, the output of every ``forward_sht``. - Layouts, from :mod:`s2fft.sampling.reindex`: + Layouts, from :mod:`s2fft.sampling.reindex`, on the last axes of the array (any + leading axes are batch axes): - * ``"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. + * ``"2d"``: shape :math:`[\dots, L, 2L-1]`, indexed :math:`[\ell, L-1+m]`, with zeros + for :math:`|m| > \ell`. + * ``"1d"``: shape :math:`[\dots, L^2]`, index :math:`\ell^2 + \ell + m`. + * ``"hp"``: shape :math:`[\dots, L(L+1)/2]`, healpy order, :math:`m \geq 0` only, for + real signals. Args: array (jax.Array): Coefficients in the given layout. @@ -35,8 +42,8 @@ class Alm: 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"``. + layout (str, optional): One of ``"2d"``, ``"1d"``, ``"hp"``. Inferred from the + last axes of ``array`` when not given, then changed by the conversions. """ @@ -44,38 +51,60 @@ class Alm: L: int spin: int = 0 reality: bool = False - layout: str = "2d" + layout: str = LAYOUT_FROM_SHAPE + + def __post_init__(self): + """Infer the layout from the last axes of the array when it was not given.""" + if self.layout is LAYOUT_FROM_SHAPE: + shape = jnp.shape(self.array) + if shape[-2:] == (self.L, 2 * self.L - 1): + layout = "2d" + elif shape[-1:] == (self.L**2,): + layout = "1d" + elif shape[-1:] == (self.L * (self.L + 1) // 2,): + layout = "hp" + else: + raise ValueError( + f"Array of shape {shape} matches no layout for L={self.L}: " + f"(..., {self.L}, {2 * self.L - 1}), (..., {self.L**2}) or " + f"(..., {self.L * (self.L + 1) // 2})." + ) + object.__setattr__(self, "layout", layout) def to_2d(self) -> "Alm": - """Coefficients in the ``"2d"`` layout.""" + """Coefficients in the ``"2d"`` layout, unchanged when already in it.""" if self.layout == "1d": - return replace( - self, array=reindex.flm_1d_to_2d_fast(self.array, self.L), layout="2d" - ) + array = jnp.vectorize( + reindex.flm_1d_to_2d_fast, excluded={1}, signature="(k)->(l,m)" + )(self.array, self.L) + return replace(self, array=array, layout="2d") if self.layout == "hp": - return replace( - self, array=reindex.flm_hp_to_2d_fast(self.array, self.L), layout="2d" - ) + array = jnp.vectorize( + reindex.flm_hp_to_2d_fast, excluded={1}, signature="(k)->(l,m)" + )(self.array, self.L) + return replace(self, array=array, 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", - ) + """Coefficients in the ``"1d"`` layout, unchanged when already in it.""" + if self.layout == "1d": + return self + array = jnp.vectorize( + reindex.flm_2d_to_1d_fast, excluded={1}, signature="(l,m)->(k)" + )(self.to_2d().array, self.L) + return replace(self, array=array, layout="1d") def to_hp(self) -> "Alm": r""" Coefficients in the healpy layout, which keeps only :math:`m \geq 0` of a - real signal. + real signal, unchanged when already in it. """ - return replace( - self, - array=reindex.flm_2d_to_hp_fast(self.to_2d().array, self.L), - layout="hp", - ) + if self.layout == "hp": + return self + array = jnp.vectorize( + reindex.flm_2d_to_hp_fast, excluded={1}, signature="(l,m)->(k)" + )(self.to_2d().array, self.L) + return replace(self, array=array, layout="hp") def cl(self, other: "Alm | None" = None) -> jnp.ndarray: r""" @@ -115,11 +144,11 @@ def __mul__(self, x) -> "Alm": 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. + :func:`s2fft.utils.rotation.rotate_flms` (the angles are static there), over + any leading batch axes. 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)), - ) + array = jnp.vectorize( + rotation.rotate_flms, excluded={1, 2}, signature="(l,m)->(l,m)" + )(alm_2d.array, self.L, (alpha, beta, gamma)) + return replace(alm_2d, array=array) diff --git a/src/s2fft/sampling/healpix.py b/src/s2fft/sampling/healpix.py index bfa2f6771..06f30940f 100644 --- a/src/s2fft/sampling/healpix.py +++ b/src/s2fft/sampling/healpix.py @@ -53,33 +53,42 @@ 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: + def forward_sht(self, f: jnp.ndarray, iter: int = 0, *, method: str = "jax") -> Alm: """ Forward spin-spherical harmonic transform, via :func:`spherical.forward`, with - ``iter`` iterations of iterative refinement. + ``iter`` iterations of iterative refinement. ``method`` is ``"jax"``, or + ``"jax_cuda"`` for the HEALPix FFT of the s2fft CUDA plug-in. """ + if method not in ("jax", "jax_cuda"): + raise ValueError(f"method must be 'jax' or 'jax_cuda', got {method!r}.") flm = spherical.forward( f, self.L, spin=self.spin, nside=self.nside, sampling="healpix", - method="jax", + method=method, 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`.""" + def inverse_sht(self, alm: Alm, *, method: str = "jax") -> jnp.ndarray: + """ + Inverse spin-spherical harmonic transform, via :func:`spherical.inverse`. + ``method`` is ``"jax"``, or ``"jax_cuda"`` for the HEALPix FFT of the s2fft + CUDA plug-in. + """ + if method not in ("jax", "jax_cuda"): + raise ValueError(f"method must be 'jax' or 'jax_cuda', got {method!r}.") return spherical.inverse( alm.array, self.L, spin=self.spin, nside=self.nside, sampling="healpix", - method="jax", + method=method, reality=self.reality, L_lower=self.L_lower, ) diff --git a/src/s2fft/sampling/octahedral_gaussian.py b/src/s2fft/sampling/octahedral_gaussian.py index ced3d1a9c..0e57ca5c2 100644 --- a/src/s2fft/sampling/octahedral_gaussian.py +++ b/src/s2fft/sampling/octahedral_gaussian.py @@ -44,11 +44,11 @@ def shape(self) -> tuple[int, ...]: """Not implemented (#434).""" raise NotImplementedError(NOT_IMPLEMENTED) - def forward_sht(self, f: jnp.ndarray) -> Alm: + def forward_sht(self, f: jnp.ndarray, *, method: str = "jax") -> Alm: """Not implemented (#434).""" raise NotImplementedError(NOT_IMPLEMENTED) - def inverse_sht(self, alm: Alm) -> jnp.ndarray: + def inverse_sht(self, alm: Alm, *, method: str = "jax") -> 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 index 2ef64522b..726d5190d 100644 --- a/src/s2fft/sampling/reduced_gaussian.py +++ b/src/s2fft/sampling/reduced_gaussian.py @@ -44,11 +44,11 @@ def shape(self) -> tuple[int, ...]: """Not implemented (#434).""" raise NotImplementedError(NOT_IMPLEMENTED) - def forward_sht(self, f: jnp.ndarray) -> Alm: + def forward_sht(self, f: jnp.ndarray, *, method: str = "jax") -> Alm: """Not implemented (#434).""" raise NotImplementedError(NOT_IMPLEMENTED) - def inverse_sht(self, alm: Alm) -> jnp.ndarray: + def inverse_sht(self, alm: Alm, *, method: str = "jax") -> jnp.ndarray: """Not implemented (#434).""" raise NotImplementedError(NOT_IMPLEMENTED) diff --git a/tests/test_sampling_classes.py b/tests/test_sampling_classes.py index 5d5945e06..7c9b67992 100644 --- a/tests/test_sampling_classes.py +++ b/tests/test_sampling_classes.py @@ -71,6 +71,35 @@ def test_sht_matches_old_api(flm_generator, L, spin, sampling, reality): 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", list(equiangular_classes)) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_sht_method_jax_cuda_matches_old_api(flm_generator, L, sampling): + # jax_cuda changes only the HEALPix FFT, so on an equiangular sampling it runs on + # any device and must match the old API called with the same method. + s, nside = build_sampling(sampling, L, 0, False) + flm = flm_generator(L=s.L) + f_old = s2fft.inverse(flm, s.L, 0, nside, sampling, method="jax_cuda") + f_new = s.inverse_sht(s2fft.Alm(array=flm, L=s.L), method="jax_cuda") + np.testing.assert_array_equal(f_new, f_old) + flm_old = s2fft.forward(f_old, s.L, 0, nside, sampling, method="jax_cuda") + np.testing.assert_array_equal( + s.forward_sht(f_old, method="jax_cuda").array, flm_old + ) + + +@pytest.mark.parametrize("sampling", sampling_to_test) +def test_sht_method_rejected(sampling): + s, nside = build_sampling(sampling, 6, 0, False) + f = np.zeros(s.shape) + with pytest.raises(ValueError): + s.forward_sht(f, method="numpy") + with pytest.raises(ValueError): + s.inverse_sht( + s2fft.Alm(array=np.zeros((s.L, 2 * s.L - 1)), L=s.L), method="torch" + ) + + @pytest.mark.parametrize("L", L_to_test) @pytest.mark.parametrize("sampling", wigner_sampling_to_test) @pytest.mark.parametrize("reality", reality_to_test) @@ -173,6 +202,47 @@ def test_alm_layouts(flm_generator, L): assert alm_hp.layout == "hp" np.testing.assert_allclose(alm_hp.to_2d().array, flm_real, atol=1e-14) + # A conversion to the layout already held returns the same Alm. + assert alm.to_2d() is alm + assert alm_1d.to_1d() is alm_1d + assert alm_hp.to_hp() is alm_hp + + +@pytest.mark.parametrize("L", L_to_test) +def test_alm_layout_from_shape(flm_generator, L): + flm = flm_generator(L=L, reality=True) + flm_1d = reindex.flm_2d_to_1d_fast(flm, L) + flm_hp = reindex.flm_2d_to_hp_fast(flm, L) + assert s2fft.Alm(array=flm, L=L).layout == "2d" + assert s2fft.Alm(array=flm_1d, L=L).layout == "1d" + assert s2fft.Alm(array=flm_hp, L=L).layout == "hp" + assert s2fft.Alm(array=np.stack([flm_1d, flm_1d]), L=L).layout == "1d" + with pytest.raises(ValueError): + s2fft.Alm(array=flm[:, :-1], L=L) + + +@pytest.mark.parametrize("L", L_to_test) +def test_alm_layouts_batch(flm_generator, L): + flms = np.stack([flm_generator(L=L, reality=True) for _ in range(3)]) + alm = s2fft.Alm(array=flms, L=L, reality=True) + assert alm.layout == "2d" + + alm_1d = alm.to_1d() + assert alm_1d.array.shape == (3, L**2) + for i in range(3): + np.testing.assert_array_equal( + alm_1d.array[i], reindex.flm_2d_to_1d_fast(flms[i], L) + ) + np.testing.assert_array_equal(alm_1d.to_2d().array, flms) + + alm_hp = alm.to_hp() + assert alm_hp.array.shape == (3, L * (L + 1) // 2) + for i in range(3): + np.testing.assert_array_equal( + alm_hp.array[i], reindex.flm_2d_to_hp_fast(flms[i], L) + ) + np.testing.assert_allclose(alm_hp.to_2d().array, flms, atol=1e-14) + @pytest.mark.healpy @pytest.mark.parametrize("L", L_to_test) @@ -212,6 +282,16 @@ def test_alm_rotate(flm_generator, L): rotated.array, rotation.rotate_flms(flm, L, (0.1, 0.2, 0.3)) ) + flms = np.stack([flm_generator(L=L) for _ in range(3)]) + rotated_batch = s2fft.Alm(array=flms, L=L).rotate(0.1, 0.2, 0.3) + assert rotated_batch.array.shape == flms.shape + for i in range(3): + np.testing.assert_allclose( + rotated_batch.array[i], + rotation.rotate_flms(flms[i], L, (0.1, 0.2, 0.3)), + atol=1e-14, + ) + @pytest.mark.parametrize( "cls", [s2fft.OctahedralGaussianSampling, s2fft.ReducedGaussianSampling] From 79aa9cca328c1fafd5b145c9ff187198ac897885 Mon Sep 17 00:00:00 2001 From: Wassim KABALAN Date: Thu, 3 Dec 2026 15:05:29 +0000 Subject: [PATCH 3/4] Alm.__mul__: plain product, no layout conversion --- src/s2fft/sampling/alm.py | 10 ++-------- tests/test_sampling_classes.py | 2 +- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/s2fft/sampling/alm.py b/src/s2fft/sampling/alm.py index 0f32fcc2f..02ba36f6d 100644 --- a/src/s2fft/sampling/alm.py +++ b/src/s2fft/sampling/alm.py @@ -132,14 +132,8 @@ def __add__(self, other: "Alm") -> "Alm": 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]) + """Product of the array with ``x``, with NumPy broadcasting, in the same layout.""" + return replace(self, array=self.array * x) def rotate(self, alpha: float, beta: float, gamma: float) -> "Alm": r""" diff --git a/tests/test_sampling_classes.py b/tests/test_sampling_classes.py index 7c9b67992..97543fd1a 100644 --- a/tests/test_sampling_classes.py +++ b/tests/test_sampling_classes.py @@ -271,7 +271,7 @@ def test_alm_arithmetic(flm_generator, L): 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]) + np.testing.assert_array_equal((a * b_ell[:, None]).array, flm_a * b_ell[:, None]) @pytest.mark.parametrize("L", L_to_test) From 616fac9e98bd801177cfaac9afec1da6e14dfce5 Mon Sep 17 00:00:00 2001 From: Wassim KABALAN Date: Thu, 3 Dec 2026 16:06:30 +0000 Subject: [PATCH 4/4] Test the reduced-grid stubs and forward_cl --- tests/test_sampling_classes.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/test_sampling_classes.py b/tests/test_sampling_classes.py index 97543fd1a..4c3e90d1a 100644 --- a/tests/test_sampling_classes.py +++ b/tests/test_sampling_classes.py @@ -143,6 +143,17 @@ def test_precompute_matches_old_api(flm_generator, L, spin, sampling, reality): np.testing.assert_array_equal(s.forward_precompute(f_old).array, flm_old) +@pytest.mark.parametrize("sampling", sampling_to_test) +@pytest.mark.filterwarnings("ignore::RuntimeWarning") +def test_forward_cl_matches_old_api(flm_generator, sampling): + s, nside = build_sampling(sampling, 6, 0, False) + flm = flm_generator(L=s.L) + f = s2fft.inverse(flm, s.L, 0, nside, sampling, method="jax") + flm_old = np.asarray(s2fft.forward(f, s.L, 0, nside, sampling, method="jax")) + cl_old = np.sum(np.abs(flm_old) ** 2, axis=1) / (2 * np.arange(s.L) + 1) + np.testing.assert_allclose(s.forward_cl(f), cl_old, rtol=1e-12) + + @pytest.mark.parametrize("L", L_to_test) @pytest.mark.parametrize("sampling", sampling_to_test) def test_fields(L, sampling): @@ -299,3 +310,25 @@ def test_alm_rotate(flm_generator, L): def test_reduced_grids_not_implemented(cls): with pytest.raises(NotImplementedError): cls(L=8, N=4) + + # Construction raises, so the methods are reached on an instance made without + # __init__. + s = object.__new__(cls) + with pytest.raises(NotImplementedError): + _ = s.sampling + with pytest.raises(NotImplementedError): + _ = s.shape + with pytest.raises(NotImplementedError): + s.forward_sht(None) + with pytest.raises(NotImplementedError): + s.inverse_sht(None) + with pytest.raises(NotImplementedError): + s.forward_cl(None) + with pytest.raises(NotImplementedError): + s.forward_wigner(None, 2) + with pytest.raises(NotImplementedError): + s.inverse_wigner(None, 2) + with pytest.raises(NotImplementedError): + s.forward_precompute(None) + with pytest.raises(NotImplementedError): + s.inverse_precompute(None)