Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/s2fft/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
179 changes: 179 additions & 0 deletions src/s2fft/sampling/abstract_sampling.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
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, *, 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=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, *, 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=method,
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",
)
148 changes: 148 additions & 0 deletions src/s2fft/sampling/alm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
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

# 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,
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`, on the last axes of the array (any
leading axes are batch axes):

* ``"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.

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"``. Inferred from the
last axes of ``array`` when not given, then changed by the conversions.

"""

array: jax.Array
L: int
spin: int = 0
reality: bool = False
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, unchanged when already in it."""
if self.layout == "1d":
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":
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, 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, unchanged when already in it.
"""
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"""
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":
"""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"""
Rotation by the Euler angles :math:`(\alpha, \beta, \gamma)`, via
: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()
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)
19 changes: 19 additions & 0 deletions src/s2fft/sampling/clenshaw_curtis.py
Original file line number Diff line number Diff line change
@@ -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"
19 changes: 19 additions & 0 deletions src/s2fft/sampling/driscoll_healy.py
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading