Skip to content

Geo encoders

Geophysical inputs usually arrive as longitude/latitude in degrees, while downstream neural-field and GP features typically want periodic encodings or unit-sphere coordinates. The geo encoders in pyrox_nn make those preprocessing steps first-class and composable.

The canonical spherical-harmonic pipeline is:

import equinox as eqx

from pyrox_nn import (
    Cartesian3DEncoder,
    Deg2Rad,
    SphericalHarmonicEncoder,
)

encoder = eqx.nn.Sequential(
    [
        Deg2Rad(),
        Cartesian3DEncoder(input_unit="radians"),
        SphericalHarmonicEncoder(l_max=8, input_mode="cartesian"),
    ]
)
features = encoder(lonlat_deg)  # (N, 81)

Cartesian3DEncoder uses the same axis convention expected by pyrox_gp.SphericalHarmonicInducingFeatures, so the NN and GP spherical paths line up. For temporal complements, see fourier_features and seasonal_features.

Stateful encoder layers

Deg2Rad

Bases: Module

Element-wise conversion from degrees to radians.

The map is y = π x / 180. It is a stateless wrapper around jax.numpy.deg2rad with no learnable parameters.

Examples:

A vector of three angles keeps its shape:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import Deg2Rad
>>> Deg2Rad()(jnp.array([0.0, 90.0, 180.0])).shape
(3,)

A scalar converts to a scalar:

>>> Deg2Rad()(jnp.array(90.0)).shape
()

Batch with vmap over a matrix of angles:

>>> import jax
>>> jax.vmap(Deg2Rad())(jnp.zeros((2, 3))).shape
(2, 3)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
class Deg2Rad(eqx.Module):
    """Element-wise conversion from degrees to radians.

    The map is `y = π x / 180`. It is a stateless wrapper around
    `jax.numpy.deg2rad` with no learnable parameters.

    Examples:
        A vector of three angles keeps its shape:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import Deg2Rad
        >>> Deg2Rad()(jnp.array([0.0, 90.0, 180.0])).shape
        (3,)

        A scalar converts to a scalar:

        >>> Deg2Rad()(jnp.array(90.0)).shape
        ()

        Batch with `vmap` over a matrix of angles:

        >>> import jax
        >>> jax.vmap(Deg2Rad())(jnp.zeros((2, 3))).shape
        (2, 3)
    """

    def __call__(self, x: Float[Array, "..."]) -> Float[Array, "..."]:
        """Convert `x` from degrees to radians, preserving its shape.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import Deg2Rad
            >>> Deg2Rad()(jnp.zeros((4,))).shape
            (4,)
        """
        return jnp.deg2rad(x)

LonLatScale

Bases: Module

Affine-rescale a single longitude and latitude pair into [-1, 1].

The map is y = 2 (x − lo) / (hi − lo) − 1 per component, with lo and hi taken from the two ranges. Values outside the range are not clipped. The default ranges assume degrees.

Parameters:

Name Type Description Default
lon_range

(lo, hi) longitude domain, with lo < hi.

required
lat_range

(lo, hi) latitude domain, with lo < hi.

required

Raises:

Type Description
ValueError

If a range is not increasing.

Examples:

A typical pair in degrees:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import LonLatScale
>>> LonLatScale()(jnp.array([180.0, 90.0])).shape
(2,)

A regional domain, with the midpoint mapped to zero:

>>> regional = LonLatScale(lon_range=(-10.0, 10.0), lat_range=(40.0, 60.0))
>>> bool(jnp.allclose(regional(jnp.array([0.0, 50.0])), 0.0))
True

Batch with vmap over a matrix of pairs:

>>> import jax
>>> jax.vmap(LonLatScale())(jnp.zeros((5, 2))).shape
(5, 2)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
class LonLatScale(eqx.Module):
    """Affine-rescale a single longitude and latitude pair into `[-1, 1]`.

    The map is `y = 2 (x − lo) / (hi − lo) − 1` per component, with `lo` and
    `hi` taken from the two ranges. Values outside the range are not clipped.
    The default ranges assume degrees.

    Args:
        lon_range: `(lo, hi)` longitude domain, with `lo < hi`.
        lat_range: `(lo, hi)` latitude domain, with `lo < hi`.

    Raises:
        ValueError: If a range is not increasing.

    Examples:
        A typical pair in degrees:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import LonLatScale
        >>> LonLatScale()(jnp.array([180.0, 90.0])).shape
        (2,)

        A regional domain, with the midpoint mapped to zero:

        >>> regional = LonLatScale(lon_range=(-10.0, 10.0), lat_range=(40.0, 60.0))
        >>> bool(jnp.allclose(regional(jnp.array([0.0, 50.0])), 0.0))
        True

        Batch with `vmap` over a matrix of pairs:

        >>> import jax
        >>> jax.vmap(LonLatScale())(jnp.zeros((5, 2))).shape
        (5, 2)
    """

    lon_range: tuple[float, float] = eqx.field(static=True, default=(-180.0, 180.0))
    lat_range: tuple[float, float] = eqx.field(static=True, default=(-90.0, 90.0))

    def __post_init__(self) -> None:
        _validate_range(self.lon_range, name="lon_range")
        _validate_range(self.lat_range, name="lat_range")

    def __call__(self, lonlat: Num[Array, " 2"]) -> Float[Array, " 2"]:
        """Rescale a single `(2,)` longitude and latitude pair into `[-1, 1]`.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import LonLatScale
            >>> # The domain maximum maps to +1 in each component.
            >>> out = LonLatScale()(jnp.array([180.0, 90.0]))
            >>> bool(jnp.allclose(out, 1.0))
            True
        """
        # a single pair becomes a batch of one for the batched helper
        out = lonlat_scale(
            einx.id("a -> 1 a", lonlat),
            lon_range=self.lon_range,
            lat_range=self.lat_range,
        )
        return out[0]

Cartesian3DEncoder

Bases: Module

Lift a single longitude and latitude onto the unit sphere S².

The map is p = (cos ϕ cos λ, cos ϕ sin λ, sin ϕ). It is a stateless wrapper around functax.geometry.lonlat_to_unit.

Parameters:

Name Type Description Default
input_unit

Whether the input is in "degrees" or "radians".

required

Raises:

Type Description
ValueError

If input_unit is unknown.

Examples:

The point (0, 0) maps to the unit vector along x:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import Cartesian3DEncoder
>>> Cartesian3DEncoder()(jnp.array([0.0, 0.0])).shape
(3,)

Degrees and radians agree for the same point:

>>> deg = Cartesian3DEncoder(input_unit="degrees")(jnp.array([90.0, 0.0]))
>>> rad = Cartesian3DEncoder()(jnp.array([jnp.pi / 2, 0.0]))
>>> bool(jnp.allclose(deg, rad, atol=1e-6))
True

Batch with vmap over a matrix of pairs:

>>> import jax
>>> jax.vmap(Cartesian3DEncoder())(jnp.zeros((4, 2))).shape
(4, 3)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
class Cartesian3DEncoder(eqx.Module):
    """Lift a single longitude and latitude onto the unit sphere `S²`.

    The map is `p = (cos ϕ cos λ, cos ϕ sin λ, sin ϕ)`. It is a stateless
    wrapper around `functax.geometry.lonlat_to_unit`.

    Args:
        input_unit: Whether the input is in `"degrees"` or `"radians"`.

    Raises:
        ValueError: If `input_unit` is unknown.

    Examples:
        The point `(0, 0)` maps to the unit vector along `x`:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import Cartesian3DEncoder
        >>> Cartesian3DEncoder()(jnp.array([0.0, 0.0])).shape
        (3,)

        Degrees and radians agree for the same point:

        >>> deg = Cartesian3DEncoder(input_unit="degrees")(jnp.array([90.0, 0.0]))
        >>> rad = Cartesian3DEncoder()(jnp.array([jnp.pi / 2, 0.0]))
        >>> bool(jnp.allclose(deg, rad, atol=1e-6))
        True

        Batch with `vmap` over a matrix of pairs:

        >>> import jax
        >>> jax.vmap(Cartesian3DEncoder())(jnp.zeros((4, 2))).shape
        (4, 3)
    """

    input_unit: Literal["degrees", "radians"] = eqx.field(
        static=True, default="radians"
    )

    def __post_init__(self) -> None:
        _validate_input_unit(self.input_unit)

    def __call__(self, lonlat: Float[Array, " 2"]) -> Float[Array, " 3"]:
        """Map a single `(2,)` longitude and latitude pair to a `(3,)` unit vector.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import Cartesian3DEncoder
            >>> out = Cartesian3DEncoder()(jnp.array([0.0, 0.0]))
            >>> bool(jnp.allclose(out, jnp.array([1.0, 0.0, 0.0]), atol=1e-6))
            True
        """
        if lonlat.ndim != 1 or lonlat.shape[-1] != 2:
            raise ValueError(f"lonlat must be (2,); got shape {lonlat.shape}.")
        # integers are promoted to float first
        return lonlat_to_unit(_promote_to_floating(lonlat), unit=self.input_unit)

CyclicEncoder

Bases: Module

Encode a single periodic input as concatenated cosine and sine features.

The map is y = [cos θ, sin θ] for a scalar θ, and y = [cos θ, sin θ] concatenated over the D components for a vector. It is a stateless wrapper around geonnax.encoders.cyclic_encode.

Examples:

Batch with vmap over two scalar angles:

>>> import jax.numpy as jnp
>>> import jax
>>> from geonnax.encoders import CyclicEncoder
>>> jax.vmap(CyclicEncoder())(jnp.array([0.0, jnp.pi])).shape
(2, 2)

A single scalar gives two features:

>>> CyclicEncoder()(jnp.array(0.0)).shape
(2,)

A vector of three angles gives six features:

>>> CyclicEncoder()(jnp.zeros((3,))).shape
(6,)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
class CyclicEncoder(eqx.Module):
    """Encode a single periodic input as concatenated cosine and sine features.

    The map is `y = [cos θ, sin θ]` for a scalar `θ`, and `y = [cos θ, sin θ]`
    concatenated over the `D` components for a vector. It is a stateless
    wrapper around `geonnax.encoders.cyclic_encode`.

    Examples:
        Batch with `vmap` over two scalar angles:

        >>> import jax.numpy as jnp
        >>> import jax
        >>> from geonnax.encoders import CyclicEncoder
        >>> jax.vmap(CyclicEncoder())(jnp.array([0.0, jnp.pi])).shape
        (2, 2)

        A single scalar gives two features:

        >>> CyclicEncoder()(jnp.array(0.0)).shape
        (2,)

        A vector of three angles gives six features:

        >>> CyclicEncoder()(jnp.zeros((3,))).shape
        (6,)
    """

    def __call__(
        self,
        angles: Float[Array, ""] | Float[Array, " D"],
    ) -> Float[Array, " F"]:
        """Encode a scalar or `(D,)` angle vector into `[cos, sin]` features.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import CyclicEncoder
            >>> CyclicEncoder()(jnp.zeros((3,))).shape
            (6,)
        """
        promoted = jnp.atleast_1d(angles)
        # a single example becomes a batch of one for the batched helper
        out = cyclic_encode(einx.id("d -> 1 d", promoted))
        return out[0]

SphericalHarmonicEncoder

Bases: Module

Real spherical-harmonic features on the unit 2-sphere for a single point.

The features are y = Y(p) with M = (l_max + 1)² components, where p is the point on the sphere. With input_mode="cartesian" the point is given directly as p ∈ ℝ³. With input_mode="lonlat" it is given as (λ, ϕ) in radians and lifted first. The map wraps functax.basis.sphere.real_spherical_harmonics.

Parameters:

Name Type Description Default
l_max

Maximum harmonic degree l_max ≥ 0. The output has (l_max + 1)² features.

required
input_mode

"cartesian" for a (3,) unit-sphere input, or "lonlat" for a (2,) longitude and latitude pair in radians.

required

Raises:

Type Description
ValueError

If l_max < 0 or input_mode is unknown.

Examples:

A Cartesian point at l_max = 3 gives (l_max + 1)² = 16 features:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import SphericalHarmonicEncoder
>>> SphericalHarmonicEncoder(l_max=3)(jnp.array([1.0, 0.0, 0.0])).shape
(16,)

A longitude and latitude pair in radians:

>>> enc = SphericalHarmonicEncoder(l_max=2, input_mode="lonlat")
>>> enc(jnp.array([0.0, 0.0])).shape
(9,)

Batch with vmap over a matrix of Cartesian points:

>>> import jax
>>> batched = jax.vmap(SphericalHarmonicEncoder(l_max=1))(jnp.eye(3))
>>> batched.shape
(3, 4)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
class SphericalHarmonicEncoder(eqx.Module):
    """Real spherical-harmonic features on the unit 2-sphere for a single point.

    The features are `y = Y(p)` with `M = (l_max + 1)²` components, where `p`
    is the point on the sphere. With `input_mode="cartesian"` the point is
    given directly as `p ∈ ℝ³`. With `input_mode="lonlat"` it is given as
    `(λ, ϕ)` in radians and lifted first. The map wraps
    `functax.basis.sphere.real_spherical_harmonics`.

    Args:
        l_max: Maximum harmonic degree `l_max ≥ 0`. The output has
            `(l_max + 1)²` features.
        input_mode: `"cartesian"` for a `(3,)` unit-sphere input, or
            `"lonlat"` for a `(2,)` longitude and latitude pair in radians.

    Raises:
        ValueError: If `l_max < 0` or `input_mode` is unknown.

    Examples:
        A Cartesian point at `l_max = 3` gives `(l_max + 1)² = 16` features:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import SphericalHarmonicEncoder
        >>> SphericalHarmonicEncoder(l_max=3)(jnp.array([1.0, 0.0, 0.0])).shape
        (16,)

        A longitude and latitude pair in radians:

        >>> enc = SphericalHarmonicEncoder(l_max=2, input_mode="lonlat")
        >>> enc(jnp.array([0.0, 0.0])).shape
        (9,)

        Batch with `vmap` over a matrix of Cartesian points:

        >>> import jax
        >>> batched = jax.vmap(SphericalHarmonicEncoder(l_max=1))(jnp.eye(3))
        >>> batched.shape
        (3, 4)
    """

    l_max: int = eqx.field(static=True)
    input_mode: Literal["cartesian", "lonlat"] = eqx.field(
        static=True, default="cartesian"
    )

    def __post_init__(self) -> None:
        if self.l_max < 0:
            raise ValueError(f"l_max must be >= 0; got {self.l_max}.")
        if self.input_mode not in {"cartesian", "lonlat"}:
            raise ValueError(
                f"input_mode must be 'cartesian' or 'lonlat'; got {self.input_mode!r}."
            )

    @property
    def num_features(self) -> int:
        """Number of harmonic features, `M = (l_max + 1)²`.

        Examples:
            >>> from geonnax.encoders import SphericalHarmonicEncoder
            >>> SphericalHarmonicEncoder(l_max=2).num_features
            9
        """
        # degrees 0 to l_max hold Σ_l (2l + 1) = (l_max + 1)² modes
        return (self.l_max + 1) ** 2

    def __call__(
        self,
        x: Float[Array, " 3"] | Float[Array, " 2"],
    ) -> Float[Array, " M"]:
        """Evaluate the real spherical harmonics at a single point.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import SphericalHarmonicEncoder
            >>> enc = SphericalHarmonicEncoder(l_max=2, input_mode="lonlat")
            >>> enc(jnp.array([0.0, 0.0])).shape
            (9,)
        """
        if self.input_mode == "cartesian":
            if x.ndim != 1 or x.shape[-1] != 3:
                raise ValueError(
                    f"x must be (3,) when input_mode='cartesian'; got shape {x.shape}."
                )
            unit_xyz = einx.id("d -> 1 d", x)
        else:
            if x.ndim != 1 or x.shape[-1] != 2:
                raise ValueError(
                    f"x must be (2,) when input_mode='lonlat'; got shape {x.shape}."
                )
            # λ, ϕ in radians are lifted to p ∈ ℝ³ before the harmonics
            unit_xyz = lonlat_to_unit(
                _promote_to_floating(einx.id("a -> 1 a", x)), unit="radians"
            )
        return real_spherical_harmonics(unit_xyz, l_max=self.l_max)[0]

num_features: int property

Number of harmonic features, M = (l_max + 1)².

Examples:

>>> from geonnax.encoders import SphericalHarmonicEncoder
>>> SphericalHarmonicEncoder(l_max=2).num_features
9

Slepian encoders

Region-localized spherical encoders built on the Slepian concentration problem. The deterministic SlepianEncoder and HybridSphericalSlepianEncoder are re-exported from geonnax; BayesianSlepianEncoder adds NumPyro sites over the cap radius and centre.

SlepianEncoder

Bases: Module

Deterministic Slepian-cap positional encoder on S².

Slepian functions are the band-limited modes maximally concentrated inside a spherical cap. Each is a weighted sum of spherical harmonics up to l_max, with concentration eigenvalue λ_k ∈ [0, 1]. With weight_by_eigenvalue the encoder returns

φ_k(x) = √λ_k ψ_k(x),

where ψ_k is the k-th unweighted Slepian mode, so well-concentrated modes dominate.

Parameters:

Name Type Description Default
basis

The retained Slepian cap basis, with its modes ψ_k and eigenvalues λ_k.

required
input_mode

"lonlat" for (lon, lat) in radians, or "cartesian" for a unit vector (x, y, z).

required
weight_by_eigenvalue

Whether to scale mode k by √λ_k.

required

Examples:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import SlepianEncoder
>>> enc = SlepianEncoder.from_cap(
...     l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=4,
... )
>>> enc(jnp.array([0.0, 0.0])).shape == (enc.num_features,)
True

Cartesian input on the unit sphere:

>>> enc_xyz = SlepianEncoder.from_cap(
...     l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=4,
...     input_mode="cartesian",
... )
>>> enc_xyz(jnp.array([1.0, 0.0, 0.0])).shape
(4,)

Composition with vmap over a batch of points:

>>> import jax
>>> jax.vmap(enc)(jnp.zeros((5, 2))).shape
(5, 4)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_slepian.py
class SlepianEncoder(eqx.Module):
    """Deterministic Slepian-cap positional encoder on `S²`.

    Slepian functions are the band-limited modes maximally concentrated inside
    a spherical cap. Each is a weighted sum of spherical harmonics up to
    `l_max`, with concentration eigenvalue `λ_k ∈ [0, 1]`. With
    `weight_by_eigenvalue` the encoder returns

    φ_k(x) = √λ_k ψ_k(x),

    where `ψ_k` is the k-th unweighted Slepian mode, so well-concentrated modes
    dominate.

    Args:
        basis: The retained Slepian cap basis, with its modes `ψ_k` and
            eigenvalues `λ_k`.
        input_mode: `"lonlat"` for `(lon, lat)` in radians, or `"cartesian"`
            for a unit vector `(x, y, z)`.
        weight_by_eigenvalue: Whether to scale mode `k` by `√λ_k`.

    Examples:
        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import SlepianEncoder
        >>> enc = SlepianEncoder.from_cap(
        ...     l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=4,
        ... )
        >>> enc(jnp.array([0.0, 0.0])).shape == (enc.num_features,)
        True

        Cartesian input on the unit sphere:

        >>> enc_xyz = SlepianEncoder.from_cap(
        ...     l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=4,
        ...     input_mode="cartesian",
        ... )
        >>> enc_xyz(jnp.array([1.0, 0.0, 0.0])).shape
        (4,)

        Composition with `vmap` over a batch of points:

        >>> import jax
        >>> jax.vmap(enc)(jnp.zeros((5, 2))).shape
        (5, 4)
    """

    basis: SlepianCapBasis
    input_mode: Literal["cartesian", "lonlat"] = eqx.field(
        static=True, default="lonlat"
    )
    weight_by_eigenvalue: bool = eqx.field(static=True, default=True)

    def __post_init__(self) -> None:
        if self.input_mode not in {"cartesian", "lonlat"}:
            raise ValueError(
                f"input_mode must be 'cartesian' or 'lonlat'; got {self.input_mode!r}."
            )

    @classmethod
    def from_cap(
        cls,
        *,
        l_max: int,
        cap_radius_deg: float,
        cap_centre_lonlat_deg: tuple[float, float],
        eig_threshold: float = 0.05,
        n_modes: int | None = None,
        input_mode: Literal["cartesian", "lonlat"] = "lonlat",
        weight_by_eigenvalue: bool = True,
    ) -> SlepianEncoder:
        """Construct an encoder from cap geometry specified in degrees.

        Args:
            l_max: Maximum spherical-harmonic degree of the Slepian modes.
            cap_radius_deg: Cap radius in degrees.
            cap_centre_lonlat_deg: Cap centre `(lon, lat)` in degrees.
            eig_threshold: Keep only modes with `λ_k` above this value.
            n_modes: Maximum number of modes to keep, or `None` for all above
                the threshold.
            input_mode: `"lonlat"` or `"cartesian"`, the input convention of
                `__call__`.
            weight_by_eigenvalue: Whether to scale mode `k` by `√λ_k`.

        Returns:
            A new `SlepianEncoder` with the cap basis solved.

        Examples:
            >>> from geonnax.encoders import SlepianEncoder
            >>> enc = SlepianEncoder.from_cap(
            ...     l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=4,
            ... )
            >>> enc.num_features
            4
        """
        # the public API takes degrees; the basis solver works in radians
        basis = slepian_cap_basis(
            l_max=l_max,
            cap_radius=math.radians(cap_radius_deg),
            n_modes=n_modes,
            eig_threshold=eig_threshold,
            lonlat_centre=jnp.radians(jnp.asarray(cap_centre_lonlat_deg)),
        )
        return cls(
            basis=basis,
            input_mode=input_mode,
            weight_by_eigenvalue=weight_by_eigenvalue,
        )

    @property
    def num_features(self) -> int:
        """Number of output features (retained Slepian modes).

        Examples:
            >>> from geonnax.encoders import SlepianEncoder
            >>> enc = SlepianEncoder.from_cap(
            ...     l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=4,
            ... )
            >>> enc.num_features
            4
        """
        return self.basis.num_modes

    def __call__(
        self,
        x: Float[Array, " 3"] | Float[Array, " 2"],
    ) -> Float[Array, " K"]:
        """Evaluate the `K` retained Slepian modes at a single point.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import SlepianEncoder
            >>> enc = SlepianEncoder.from_cap(
            ...     l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=4,
            ... )
            >>> enc(jnp.array([0.0, 0.0])).shape
            (4,)
        """
        # a (2,) lon/lat or (3,) Cartesian input becomes a unit vector on S²
        unit_xyz = _unit_xyz(x, self.input_mode)
        # a batch axis of one, so the basis evaluates it as a list of points
        features = self.basis.evaluate(einx.id("d -> 1 d", unit_xyz))[0]
        if self.weight_by_eigenvalue:
            # φ_k = √λ_k ψ_k
            features = features * jnp.sqrt(self.basis.eigenvalues)
        return features

num_features: int property

Number of output features (retained Slepian modes).

Examples:

>>> from geonnax.encoders import SlepianEncoder
>>> enc = SlepianEncoder.from_cap(
...     l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=4,
... )
>>> enc.num_features
4

from_cap(*, l_max: int, cap_radius_deg: float, cap_centre_lonlat_deg: tuple[float, float], eig_threshold: float = 0.05, n_modes: int | None = None, input_mode: Literal['cartesian', 'lonlat'] = 'lonlat', weight_by_eigenvalue: bool = True) -> SlepianEncoder classmethod

Construct an encoder from cap geometry specified in degrees.

Parameters:

Name Type Description Default
l_max int

Maximum spherical-harmonic degree of the Slepian modes.

required
cap_radius_deg float

Cap radius in degrees.

required
cap_centre_lonlat_deg tuple[float, float]

Cap centre (lon, lat) in degrees.

required
eig_threshold float

Keep only modes with λ_k above this value.

0.05
n_modes int | None

Maximum number of modes to keep, or None for all above the threshold.

None
input_mode Literal['cartesian', 'lonlat']

"lonlat" or "cartesian", the input convention of __call__.

'lonlat'
weight_by_eigenvalue bool

Whether to scale mode k by √λ_k.

True

Returns:

Type Description
SlepianEncoder

A new SlepianEncoder with the cap basis solved.

Examples:

>>> from geonnax.encoders import SlepianEncoder
>>> enc = SlepianEncoder.from_cap(
...     l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=4,
... )
>>> enc.num_features
4
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_slepian.py
@classmethod
def from_cap(
    cls,
    *,
    l_max: int,
    cap_radius_deg: float,
    cap_centre_lonlat_deg: tuple[float, float],
    eig_threshold: float = 0.05,
    n_modes: int | None = None,
    input_mode: Literal["cartesian", "lonlat"] = "lonlat",
    weight_by_eigenvalue: bool = True,
) -> SlepianEncoder:
    """Construct an encoder from cap geometry specified in degrees.

    Args:
        l_max: Maximum spherical-harmonic degree of the Slepian modes.
        cap_radius_deg: Cap radius in degrees.
        cap_centre_lonlat_deg: Cap centre `(lon, lat)` in degrees.
        eig_threshold: Keep only modes with `λ_k` above this value.
        n_modes: Maximum number of modes to keep, or `None` for all above
            the threshold.
        input_mode: `"lonlat"` or `"cartesian"`, the input convention of
            `__call__`.
        weight_by_eigenvalue: Whether to scale mode `k` by `√λ_k`.

    Returns:
        A new `SlepianEncoder` with the cap basis solved.

    Examples:
        >>> from geonnax.encoders import SlepianEncoder
        >>> enc = SlepianEncoder.from_cap(
        ...     l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=4,
        ... )
        >>> enc.num_features
        4
    """
    # the public API takes degrees; the basis solver works in radians
    basis = slepian_cap_basis(
        l_max=l_max,
        cap_radius=math.radians(cap_radius_deg),
        n_modes=n_modes,
        eig_threshold=eig_threshold,
        lonlat_centre=jnp.radians(jnp.asarray(cap_centre_lonlat_deg)),
    )
    return cls(
        basis=basis,
        input_mode=input_mode,
        weight_by_eigenvalue=weight_by_eigenvalue,
    )

HybridSphericalSlepianEncoder

Bases: Module

Concatenate low-bandwidth global SHs with local Slepian cap modes.

The output is φ(x) = [Y_ℓᵐ(x) | ψ_k(x)], global structure from spherical harmonics followed by localized detail from the cap.

Parameters:

Name Type Description Default
sh_encoder

Spherical-harmonic encoder giving the global block Y_ℓᵐ.

required
slepian_encoder

Slepian cap encoder giving the local block ψ_k.

required

Examples:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import HybridSphericalSlepianEncoder
>>> enc = HybridSphericalSlepianEncoder.from_cap(
...     sh_l_max=1,
...     slepian_l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=2,
... )
>>> enc(jnp.array([0.0, 0.0])).shape == (enc.num_features,)
True

Degree zero gives a single spherical harmonic:

>>> enc_l0 = HybridSphericalSlepianEncoder.from_cap(
...     sh_l_max=0,
...     slepian_l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=2,
... )
>>> enc_l0(jnp.array([0.0, 0.0])).shape
(3,)

Composition with vmap over a batch of points:

>>> import jax
>>> jax.vmap(enc)(jnp.zeros((5, 2))).shape
(5, 6)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_slepian.py
class HybridSphericalSlepianEncoder(eqx.Module):
    """Concatenate low-bandwidth global SHs with local Slepian cap modes.

    The output is `φ(x) = [Y_ℓᵐ(x) | ψ_k(x)]`, global structure from spherical
    harmonics followed by localized detail from the cap.

    Args:
        sh_encoder: Spherical-harmonic encoder giving the global block `Y_ℓᵐ`.
        slepian_encoder: Slepian cap encoder giving the local block `ψ_k`.

    Examples:
        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import HybridSphericalSlepianEncoder
        >>> enc = HybridSphericalSlepianEncoder.from_cap(
        ...     sh_l_max=1,
        ...     slepian_l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=2,
        ... )
        >>> enc(jnp.array([0.0, 0.0])).shape == (enc.num_features,)
        True

        Degree zero gives a single spherical harmonic:

        >>> enc_l0 = HybridSphericalSlepianEncoder.from_cap(
        ...     sh_l_max=0,
        ...     slepian_l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=2,
        ... )
        >>> enc_l0(jnp.array([0.0, 0.0])).shape
        (3,)

        Composition with `vmap` over a batch of points:

        >>> import jax
        >>> jax.vmap(enc)(jnp.zeros((5, 2))).shape
        (5, 6)
    """

    sh_encoder: SphericalHarmonicEncoder
    slepian_encoder: SlepianEncoder

    @classmethod
    def from_cap(
        cls,
        *,
        sh_l_max: int,
        slepian_l_max: int,
        cap_radius_deg: float,
        cap_centre_lonlat_deg: tuple[float, float],
        eig_threshold: float = 0.05,
        n_modes: int | None = None,
        input_mode: Literal["cartesian", "lonlat"] = "lonlat",
    ) -> HybridSphericalSlepianEncoder:
        """Construct the hybrid encoder used by Slepian positional encodings.

        Args:
            sh_l_max: Maximum degree `ℓ` of the global spherical harmonics.
            slepian_l_max: Maximum spherical-harmonic degree of the Slepian modes.
            cap_radius_deg: Cap radius in degrees.
            cap_centre_lonlat_deg: Cap centre `(lon, lat)` in degrees.
            eig_threshold: Keep only Slepian modes with `λ_k` above this value.
            n_modes: Maximum number of Slepian modes, or `None` for all above
                the threshold.
            input_mode: `"lonlat"` or `"cartesian"`, shared by both encoders.

        Returns:
            A new `HybridSphericalSlepianEncoder`.

        Examples:
            >>> from geonnax.encoders import HybridSphericalSlepianEncoder
            >>> enc = HybridSphericalSlepianEncoder.from_cap(
            ...     sh_l_max=1,
            ...     slepian_l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=2,
            ... )
            >>> # sh_l_max=1 gives (1 + 1)^2 = 4 SH features, plus 2 Slepian modes.
            >>> enc.num_features
            6
        """
        return cls(
            sh_encoder=SphericalHarmonicEncoder(l_max=sh_l_max, input_mode=input_mode),
            slepian_encoder=SlepianEncoder.from_cap(
                l_max=slepian_l_max,
                cap_radius_deg=cap_radius_deg,
                cap_centre_lonlat_deg=cap_centre_lonlat_deg,
                eig_threshold=eig_threshold,
                n_modes=n_modes,
                input_mode=input_mode,
            ),
        )

    @property
    def num_features(self) -> int:
        """Number of concatenated output features (SH modes + Slepian modes).

        Examples:
            >>> from geonnax.encoders import HybridSphericalSlepianEncoder
            >>> enc = HybridSphericalSlepianEncoder.from_cap(
            ...     sh_l_max=1,
            ...     slepian_l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=2,
            ... )
            >>> enc.num_features
            6
        """
        return self.sh_encoder.num_features + self.slepian_encoder.num_features

    def __call__(
        self,
        x: Float[Array, " 3"] | Float[Array, " 2"],
    ) -> Float[Array, " F"]:
        """Concatenate SH and Slepian features for a single point.

        Examples:
            >>> import jax.numpy as jnp
            >>> from geonnax.encoders import HybridSphericalSlepianEncoder
            >>> enc = HybridSphericalSlepianEncoder.from_cap(
            ...     sh_l_max=1,
            ...     slepian_l_max=3,
            ...     cap_radius_deg=20.0,
            ...     cap_centre_lonlat_deg=(0.0, 0.0),
            ...     eig_threshold=0.0,
            ...     n_modes=2,
            ... )
            >>> enc(jnp.array([0.0, 0.0])).shape
            (6,)
        """
        # the SH block comes first, then the Slepian block
        return einx.id("a, b -> (a + b)", self.sh_encoder(x), self.slepian_encoder(x))

num_features: int property

Number of concatenated output features (SH modes + Slepian modes).

Examples:

>>> from geonnax.encoders import HybridSphericalSlepianEncoder
>>> enc = HybridSphericalSlepianEncoder.from_cap(
...     sh_l_max=1,
...     slepian_l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=2,
... )
>>> enc.num_features
6

from_cap(*, sh_l_max: int, slepian_l_max: int, cap_radius_deg: float, cap_centre_lonlat_deg: tuple[float, float], eig_threshold: float = 0.05, n_modes: int | None = None, input_mode: Literal['cartesian', 'lonlat'] = 'lonlat') -> HybridSphericalSlepianEncoder classmethod

Construct the hybrid encoder used by Slepian positional encodings.

Parameters:

Name Type Description Default
sh_l_max int

Maximum degree ℓ of the global spherical harmonics.

required
slepian_l_max int

Maximum spherical-harmonic degree of the Slepian modes.

required
cap_radius_deg float

Cap radius in degrees.

required
cap_centre_lonlat_deg tuple[float, float]

Cap centre (lon, lat) in degrees.

required
eig_threshold float

Keep only Slepian modes with λ_k above this value.

0.05
n_modes int | None

Maximum number of Slepian modes, or None for all above the threshold.

None
input_mode Literal['cartesian', 'lonlat']

"lonlat" or "cartesian", shared by both encoders.

'lonlat'

Returns:

Type Description
HybridSphericalSlepianEncoder

A new HybridSphericalSlepianEncoder.

Examples:

>>> from geonnax.encoders import HybridSphericalSlepianEncoder
>>> enc = HybridSphericalSlepianEncoder.from_cap(
...     sh_l_max=1,
...     slepian_l_max=3,
...     cap_radius_deg=20.0,
...     cap_centre_lonlat_deg=(0.0, 0.0),
...     eig_threshold=0.0,
...     n_modes=2,
... )
>>> # sh_l_max=1 gives (1 + 1)^2 = 4 SH features, plus 2 Slepian modes.
>>> enc.num_features
6
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_slepian.py
@classmethod
def from_cap(
    cls,
    *,
    sh_l_max: int,
    slepian_l_max: int,
    cap_radius_deg: float,
    cap_centre_lonlat_deg: tuple[float, float],
    eig_threshold: float = 0.05,
    n_modes: int | None = None,
    input_mode: Literal["cartesian", "lonlat"] = "lonlat",
) -> HybridSphericalSlepianEncoder:
    """Construct the hybrid encoder used by Slepian positional encodings.

    Args:
        sh_l_max: Maximum degree `ℓ` of the global spherical harmonics.
        slepian_l_max: Maximum spherical-harmonic degree of the Slepian modes.
        cap_radius_deg: Cap radius in degrees.
        cap_centre_lonlat_deg: Cap centre `(lon, lat)` in degrees.
        eig_threshold: Keep only Slepian modes with `λ_k` above this value.
        n_modes: Maximum number of Slepian modes, or `None` for all above
            the threshold.
        input_mode: `"lonlat"` or `"cartesian"`, shared by both encoders.

    Returns:
        A new `HybridSphericalSlepianEncoder`.

    Examples:
        >>> from geonnax.encoders import HybridSphericalSlepianEncoder
        >>> enc = HybridSphericalSlepianEncoder.from_cap(
        ...     sh_l_max=1,
        ...     slepian_l_max=3,
        ...     cap_radius_deg=20.0,
        ...     cap_centre_lonlat_deg=(0.0, 0.0),
        ...     eig_threshold=0.0,
        ...     n_modes=2,
        ... )
        >>> # sh_l_max=1 gives (1 + 1)^2 = 4 SH features, plus 2 Slepian modes.
        >>> enc.num_features
        6
    """
    return cls(
        sh_encoder=SphericalHarmonicEncoder(l_max=sh_l_max, input_mode=input_mode),
        slepian_encoder=SlepianEncoder.from_cap(
            l_max=slepian_l_max,
            cap_radius_deg=cap_radius_deg,
            cap_centre_lonlat_deg=cap_centre_lonlat_deg,
            eig_threshold=eig_threshold,
            n_modes=n_modes,
            input_mode=input_mode,
        ),
    )

BayesianSlepianEncoder

Bases: Parameterized

Slepian encoder with NumPyro sites for cap radius and centre.

Truncation is controlled by n_modes only. eig_threshold is not exposed because filtering by concentration ratio under tracing would require a data-dependent output size (jnp.nonzero needs a static size), which breaks JIT and downstream shape contracts.

Source code in packages/pyrox-nn/src/pyrox_nn/_slepian.py
class BayesianSlepianEncoder(Parameterized):
    """Slepian encoder with NumPyro sites for cap radius and centre.

    Truncation is controlled by ``n_modes`` only. ``eig_threshold`` is not
    exposed because filtering by concentration ratio under tracing would
    require a data-dependent output size (``jnp.nonzero`` needs a static
    ``size``), which breaks JIT and downstream shape contracts.
    """

    l_max: int = eqx.field(static=True)
    init_cap_radius_deg: float = eqx.field(static=True)
    init_cap_centre_lonlat_deg: tuple[float, float] = eqx.field(static=True)
    n_modes: int | None = eqx.field(static=True, default=None)
    input_mode: Literal["cartesian", "lonlat"] = eqx.field(
        static=True, default="lonlat"
    )
    weight_by_eigenvalue: bool = eqx.field(static=True, default=True)
    pyrox_name: str | None = eqx.field(static=True, default=None)

    def setup(self) -> None:
        if self.l_max < 0:
            raise ValueError(f"l_max must be >= 0; got {self.l_max}.")
        if self.input_mode not in {"cartesian", "lonlat"}:
            raise ValueError(
                f"input_mode must be 'cartesian' or 'lonlat'; got {self.input_mode!r}."
            )
        self.register_param(
            "cap_radius",
            jnp.asarray(math.radians(self.init_cap_radius_deg)),
            constraint=dist.constraints.interval(0.0, math.pi),
        )
        self.register_param(
            "cap_centre",
            jnp.radians(jnp.asarray(self.init_cap_centre_lonlat_deg)),
            constraint=dist.constraints.real_vector,
        )

    @pyrox_method
    def __call__(
        self,
        x: Float[Array, "N 3"] | Float[Array, "N 2"],
    ) -> Float[Array, "N K"]:
        radius = self.get_param("cap_radius")
        centre = self.get_param("cap_centre")
        basis = slepian_cap_basis(
            self.l_max,
            radius,
            n_modes=self.n_modes,
            eig_threshold=None,
            lonlat_centre=centre,
        )
        features = basis.evaluate(_unit_xyz(x, self.input_mode))
        if self.weight_by_eigenvalue:
            features = features * jnp.sqrt(basis.eigenvalues)[None, :]
        return features

Pure-JAX helper functions

lonlat_scale(lonlat: Num[Array, 'N 2'], *, lon_range: tuple[float, float] = (-180.0, 180.0), lat_range: tuple[float, float] = (-90.0, 90.0)) -> Float[Array, 'N 2']

Affine-rescale longitude and latitude columns into [-1, 1].

The affine map is y = 2 (x − lo) / (hi − lo) − 1 per column, so the range [lo, hi] maps onto [-1, 1]. Values outside the range are not clipped and map linearly outside [-1, 1]. The default ranges assume degrees; pass matching lon_range and lat_range for another unit.

Integer inputs are promoted to float32 first, so the division is not done in integer arithmetic (which would round the output to -1, 0 or 1).

Parameters:

Name Type Description Default
lonlat Num[Array, 'N 2']

Longitude and latitude matrix x ∈ ℝ^(N×2).

required
lon_range tuple[float, float]

(lo, hi) longitude domain, with lo < hi.

(-180.0, 180.0)
lat_range tuple[float, float]

(lo, hi) latitude domain, with lo < hi.

(-90.0, 90.0)

Returns:

Type Description
Float[Array, 'N 2']

The rescaled matrix y ∈ ℝ^(N×2).

Raises:

Type Description
ValueError

If lonlat is not (N, 2), or a range is not increasing.

Examples:

Typical case, a batch of three points:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import lonlat_scale
>>> lonlat = jnp.array([[-180.0, -90.0], [0.0, 0.0], [180.0, 90.0]])
>>> lonlat_scale(lonlat).shape
(3, 2)

The midpoint of each range maps exactly to zero:

>>> bool((lonlat_scale(jnp.array([[0.0, 0.0]]))[0] == 0.0).all())
True

A regional grid in degrees, with its own domain:

>>> lonlat_scale(
...     jnp.array([[0.0, 50.0]]),
...     lon_range=(-10.0, 10.0),
...     lat_range=(40.0, 60.0),
... ).shape
(1, 2)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
def lonlat_scale(
    lonlat: Num[Array, "N 2"],
    *,
    lon_range: tuple[float, float] = (-180.0, 180.0),
    lat_range: tuple[float, float] = (-90.0, 90.0),
) -> Float[Array, "N 2"]:
    """Affine-rescale longitude and latitude columns into `[-1, 1]`.

    The affine map is `y = 2 (x − lo) / (hi − lo) − 1` per column, so the
    range `[lo, hi]` maps onto `[-1, 1]`. Values outside the range are not
    clipped and map linearly outside `[-1, 1]`. The default ranges assume
    degrees; pass matching `lon_range` and `lat_range` for another unit.

    Integer inputs are promoted to `float32` first, so the division is not
    done in integer arithmetic (which would round the output to `-1`, `0`
    or `1`).

    Args:
        lonlat: Longitude and latitude matrix `x ∈ ℝ^(N×2)`.
        lon_range: `(lo, hi)` longitude domain, with `lo < hi`.
        lat_range: `(lo, hi)` latitude domain, with `lo < hi`.

    Returns:
        The rescaled matrix `y ∈ ℝ^(N×2)`.

    Raises:
        ValueError: If `lonlat` is not `(N, 2)`, or a range is not increasing.

    Examples:
        Typical case, a batch of three points:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import lonlat_scale
        >>> lonlat = jnp.array([[-180.0, -90.0], [0.0, 0.0], [180.0, 90.0]])
        >>> lonlat_scale(lonlat).shape
        (3, 2)

        The midpoint of each range maps exactly to zero:

        >>> bool((lonlat_scale(jnp.array([[0.0, 0.0]]))[0] == 0.0).all())
        True

        A regional grid in degrees, with its own domain:

        >>> lonlat_scale(
        ...     jnp.array([[0.0, 50.0]]),
        ...     lon_range=(-10.0, 10.0),
        ...     lat_range=(40.0, 60.0),
        ... ).shape
        (1, 2)
    """
    _validate_lonlat_shape(lonlat)
    _validate_range(lon_range, name="lon_range")
    _validate_range(lat_range, name="lat_range")

    lonlat = _promote_to_floating(lonlat)
    lower = jnp.asarray([lon_range[0], lat_range[0]], dtype=lonlat.dtype)
    upper = jnp.asarray([lon_range[1], lat_range[1]], dtype=lonlat.dtype)
    # y = 2 (x − lo) / (hi − lo) − 1
    return 2.0 * (lonlat - lower) / (upper - lower) - 1.0

lonlat_to_cartesian3d(lonlat: Float[Array, 'N 2'], *, input_unit: Literal['degrees', 'radians'] = 'radians') -> Float[Array, 'N 3']

Lift lon/lat coordinates onto the unit sphere.

functax.geometry.lonlat_to_unit with pyrox-nn's default unit: geonnax served this name until it moved to functax (jejjohnson/geonnax#158).

Parameters:

Name Type Description Default
lonlat Float[Array, 'N 2']

Longitude and latitude, shape (N, 2).

required
input_unit Literal['degrees', 'radians']

Whether lonlat is in "degrees" or "radians".

'radians'

Returns:

Type Description
Float[Array, 'N 3']

Unit vectors (x, y, z), shape (N, 3).

Examples:

>>> import jax.numpy as jnp
>>> from pyrox_nn import lonlat_to_cartesian3d
>>> lonlat = jnp.array([[0.0, 90.0]])  # the north pole, in degrees
>>> lonlat_to_cartesian3d(lonlat, input_unit="degrees").shape
(1, 3)
Source code in packages/pyrox-nn/src/pyrox_nn/_geonnax.py
def lonlat_to_cartesian3d(
    lonlat: Float[Array, "N 2"],
    *,
    input_unit: Literal["degrees", "radians"] = "radians",
) -> Float[Array, "N 3"]:
    """Lift lon/lat coordinates onto the unit sphere.

    `functax.geometry.lonlat_to_unit` with pyrox-nn's default unit: geonnax
    served this name until it moved to functax (jejjohnson/geonnax#158).

    Args:
        lonlat: Longitude and latitude, shape ``(N, 2)``.
        input_unit: Whether ``lonlat`` is in ``"degrees"`` or ``"radians"``.

    Returns:
        Unit vectors ``(x, y, z)``, shape ``(N, 3)``.

    Examples:
        >>> import jax.numpy as jnp
        >>> from pyrox_nn import lonlat_to_cartesian3d
        >>> lonlat = jnp.array([[0.0, 90.0]])  # the north pole, in degrees
        >>> lonlat_to_cartesian3d(lonlat, input_unit="degrees").shape
        (1, 3)
    """
    return lonlat_to_unit(lonlat, unit=input_unit)

cyclic_encode(angles: Float[Array, ' N'] | Float[Array, 'N D']) -> Float[Array, 'N F']

Encode periodic inputs as concatenated cosine and sine features.

Each angle θ is embedded on the unit circle as [cos θ, sin θ]. A vector of N angles gives two features per point. A matrix of N rows and D columns gives 2 D features, with the cosines first.

Parameters:

Name Type Description Default
angles Float[Array, ' N'] | Float[Array, 'N D']

Angles in radians, θ ∈ ℝ^N or θ ∈ ℝ^(N×D).

required

Returns:

Type Description
Float[Array, 'N F']

The features y ∈ ℝ^(N×2) for a vector input, or y ∈ ℝ^(N×2D)

Float[Array, 'N F']

for a matrix input, laid out as `[cos θ₀, …, cos θ_{D−1}, sin θ₀, …,

Float[Array, 'N F']

sin θ_{D−1}]`.

Raises:

Type Description
ValueError

If angles is neither rank 1 nor rank 2.

Examples:

A vector of two angles gives two [cos, sin] pairs:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import cyclic_encode
>>> cyclic_encode(jnp.array([0.0, jnp.pi])).shape
(2, 2)

A matrix input encodes each column independently:

>>> cyclic_encode(jnp.zeros((3, 2))).shape
(3, 4)

Composition with jax.jit:

>>> import jax
>>> jax.jit(cyclic_encode)(jnp.zeros(4)).shape
(4, 2)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
def cyclic_encode(
    angles: Float[Array, " N"] | Float[Array, "N D"],
) -> Float[Array, "N F"]:
    """Encode periodic inputs as concatenated cosine and sine features.

    Each angle `θ` is embedded on the unit circle as `[cos θ, sin θ]`. A
    vector of `N` angles gives two features per point. A matrix of `N` rows
    and `D` columns gives `2 D` features, with the cosines first.

    Args:
        angles: Angles in radians, `θ ∈ ℝ^N` or `θ ∈ ℝ^(N×D)`.

    Returns:
        The features `y ∈ ℝ^(N×2)` for a vector input, or `y ∈ ℝ^(N×2D)`
        for a matrix input, laid out as `[cos θ₀, …, cos θ_{D−1}, sin θ₀, …,
        sin θ_{D−1}]`.

    Raises:
        ValueError: If `angles` is neither rank 1 nor rank 2.

    Examples:
        A vector of two angles gives two `[cos, sin]` pairs:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import cyclic_encode
        >>> cyclic_encode(jnp.array([0.0, jnp.pi])).shape
        (2, 2)

        A matrix input encodes each column independently:

        >>> cyclic_encode(jnp.zeros((3, 2))).shape
        (3, 4)

        Composition with `jax.jit`:

        >>> import jax
        >>> jax.jit(cyclic_encode)(jnp.zeros(4)).shape
        (4, 2)
    """
    if angles.ndim == 1:
        # (N,) becomes (N, 1) so both ranks share one code path
        promoted = einx.id("n -> n 1", angles)
    elif angles.ndim == 2:
        promoted = angles
    else:
        raise ValueError(f"angles must be (N,) or (N, D); got shape {angles.shape}.")
    # y = [cos θ, sin θ], concatenated along the feature axis
    return einx.id("... a, ... b -> ... (a + b)", jnp.cos(promoted), jnp.sin(promoted))

spherical_harmonic_encode(lonlat: Float[Array, 'N 2'], l_max: int, *, input_unit: Literal['degrees', 'radians'] = 'radians') -> Float[Array, 'N M']

Lift longitude and latitude to the unit sphere S² and evaluate Y_l^m.

The point is mapped to p = (cos ϕ cos λ, cos ϕ sin λ, sin ϕ), and the real spherical harmonics Y_l^m(p) are evaluated for every degree l ≤ l_max.

Parameters:

Name Type Description Default
lonlat Float[Array, 'N 2']

Longitude λ and latitude ϕ, x ∈ ℝ^(N×2).

required
l_max int

Maximum harmonic degree l_max.

required
input_unit Literal['degrees', 'radians']

Whether lonlat is in "degrees" or "radians".

'radians'

Returns:

Type Description
Float[Array, 'N M']

The features y ∈ ℝ^(N×M) with M = (l_max + 1)².

Raises:

Type Description
ValueError

If lonlat is not (N, 2), or input_unit is unknown.

Examples:

Typical case, two points at l_max = 3:

>>> import jax.numpy as jnp
>>> from geonnax.encoders import spherical_harmonic_encode
>>> lonlat = jnp.array([[0.0, 0.0], [1.5707964, 0.0]])
>>> spherical_harmonic_encode(lonlat, l_max=3).shape
(2, 16)

Degree zero keeps only the constant mode Y_0^0:

>>> spherical_harmonic_encode(lonlat, l_max=0).shape
(2, 1)

Composition with jax.jit, with l_max held static:

>>> import jax
>>> encode = jax.jit(spherical_harmonic_encode, static_argnames="l_max")
>>> encode(lonlat, l_max=3).shape
(2, 16)
Source code in .venv/lib/python3.12/site-packages/geonnax/_src/encoders/_coordinates.py
def spherical_harmonic_encode(
    lonlat: Float[Array, "N 2"],
    l_max: int,
    *,
    input_unit: Literal["degrees", "radians"] = "radians",
) -> Float[Array, "N M"]:
    """Lift longitude and latitude to the unit sphere `S²` and evaluate `Y_l^m`.

    The point is mapped to `p = (cos ϕ cos λ, cos ϕ sin λ, sin ϕ)`, and the
    real spherical harmonics `Y_l^m(p)` are evaluated for every degree
    `l ≤ l_max`.

    Args:
        lonlat: Longitude `λ` and latitude `ϕ`, `x ∈ ℝ^(N×2)`.
        l_max: Maximum harmonic degree `l_max`.
        input_unit: Whether `lonlat` is in `"degrees"` or `"radians"`.

    Returns:
        The features `y ∈ ℝ^(N×M)` with `M = (l_max + 1)²`.

    Raises:
        ValueError: If `lonlat` is not `(N, 2)`, or `input_unit` is unknown.

    Examples:
        Typical case, two points at `l_max = 3`:

        >>> import jax.numpy as jnp
        >>> from geonnax.encoders import spherical_harmonic_encode
        >>> lonlat = jnp.array([[0.0, 0.0], [1.5707964, 0.0]])
        >>> spherical_harmonic_encode(lonlat, l_max=3).shape
        (2, 16)

        Degree zero keeps only the constant mode `Y_0^0`:

        >>> spherical_harmonic_encode(lonlat, l_max=0).shape
        (2, 1)

        Composition with `jax.jit`, with `l_max` held static:

        >>> import jax
        >>> encode = jax.jit(spherical_harmonic_encode, static_argnames="l_max")
        >>> encode(lonlat, l_max=3).shape
        (2, 16)
    """
    _validate_lonlat_shape(lonlat)
    _validate_input_unit(input_unit)
    # p = (cos ϕ cos λ, cos ϕ sin λ, sin ϕ), then y = Y_l^m(p)
    unit_xyz = lonlat_to_unit(_promote_to_floating(lonlat), unit=input_unit)
    return real_spherical_harmonics(unit_xyz, l_max=l_max)