Skip to content

Estimator API

The pyrox_nn.api subpackage exposes sklearn-style immutable estimator facades. Each estimator wraps a pyrox_nn model + the inference runners in pyrox.inference behind a one-call fit/predict ergonomic.

Base contracts

EstimatorBase

Bases: Module

Immutable configuration for a probabilistic regression model.

Attributes:

Name Type Description
feature_cols tuple[str, ...]

Names of the input columns, in the order they should be packed into the design matrix.

target_col str

Name of the target column.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
class EstimatorBase(eqx.Module):
    """Immutable configuration for a probabilistic regression model.

    Attributes:
        feature_cols: Names of the input columns, in the order they
            should be packed into the design matrix.
        target_col: Name of the target column.
    """

    feature_cols: tuple[str, ...] = eqx.field(static=True)
    target_col: str = eqx.field(static=True)

    def fit(self, df: pd.DataFrame, *, seed: PRNGKeyArray | int) -> FittedEstimator:
        """Fit and return a new `FittedEstimator`.

        Subclasses override; ``EstimatorBase.fit`` raises.
        """
        raise NotImplementedError(
            f"{type(self).__name__}.fit must be implemented by subclasses"
        )

fit(df: pd.DataFrame, *, seed: PRNGKeyArray | int) -> FittedEstimator

Fit and return a new FittedEstimator.

Subclasses override; EstimatorBase.fit raises.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
def fit(self, df: pd.DataFrame, *, seed: PRNGKeyArray | int) -> FittedEstimator:
    """Fit and return a new `FittedEstimator`.

    Subclasses override; ``EstimatorBase.fit`` raises.
    """
    raise NotImplementedError(
        f"{type(self).__name__}.fit must be implemented by subclasses"
    )

FittedEstimator

Bases: Module

Output of EstimatorBase.fit.

Subclasses store fitted parameters as equinox.Module fields and implement predict. The base class enforces only the immutable-PyTree contract.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
class FittedEstimator(eqx.Module):
    """Output of `EstimatorBase.fit`.

    Subclasses store fitted parameters as `equinox.Module`
    fields and implement ``predict``. The base class enforces only
    the immutable-PyTree contract.
    """

    config: EstimatorBase

    def predict(
        self,
        df: pd.DataFrame,
        *,
        quantiles: Sequence[float] | None = None,
    ) -> Float[Array, " N"] | tuple[Float[Array, " N"], tuple[Float[Array, " N"], ...]]:
        """Predict targets for ``df``.

        Subclasses override; ``FittedEstimator.predict`` raises.

        Args:
            df: Inputs (must contain ``feature_cols``).
            quantiles: If given, return ``(mean, (q1, q2, ...))`` where
                ``q_i`` is the per-row predictive quantile at level
                ``quantiles[i]``. If ``None``, return only the mean.
        """
        raise NotImplementedError(
            f"{type(self).__name__}.predict must be implemented by subclasses"
        )

predict(df: pd.DataFrame, *, quantiles: Sequence[float] | None = None) -> Float[Array, ' N'] | tuple[Float[Array, ' N'], tuple[Float[Array, ' N'], ...]]

Predict targets for df.

Subclasses override; FittedEstimator.predict raises.

Parameters:

Name Type Description Default
df DataFrame

Inputs (must contain feature_cols).

required
quantiles Sequence[float] | None

If given, return (mean, (q1, q2, ...)) where q_i is the per-row predictive quantile at level quantiles[i]. If None, return only the mean.

None
Source code in packages/pyrox-nn/src/pyrox_nn/api/_estimator.py
def predict(
    self,
    df: pd.DataFrame,
    *,
    quantiles: Sequence[float] | None = None,
) -> Float[Array, " N"] | tuple[Float[Array, " N"], tuple[Float[Array, " N"], ...]]:
    """Predict targets for ``df``.

    Subclasses override; ``FittedEstimator.predict`` raises.

    Args:
        df: Inputs (must contain ``feature_cols``).
        quantiles: If given, return ``(mean, (q1, q2, ...))`` where
            ``q_i`` is the per-row predictive quantile at level
            ``quantiles[i]``. If ``None``, return only the mean.
    """
    raise NotImplementedError(
        f"{type(self).__name__}.predict must be implemented by subclasses"
    )

Bayesian Neural Field family

BNFEstimator

Bases: EstimatorBase

MAP-fit Bayesian Neural Field estimator.

Composes the BNF layer (pyrox_nn.BayesianNeuralField) with pandas-side preprocessing (pyrox_nn.preprocessing.fit_spatiotemporal) and an ensemble-MAP inference loop (pyrox.inference.ensemble_map).

Attributes:

Name Type Description
feature_cols tuple[str, ...]

Input columns (first one is time).

target_col str

Target column.

width int

Hidden MLP width.

depth int

Hidden MLP depth.

observation_model ObservationModel

"NORMAL" (currently only this is fully implemented). "NB" and "ZINB" raise NotImplementedError until gaussx.mixture_quantile ships.

seasonality_periods tuple[float, ...]

Periods for seasonal features. Empty ⇒ no seasonal features.

num_seasonal_harmonics tuple[int, ...]

Harmonics per period.

fourier_degrees tuple[int, ...]

Per-input dyadic Fourier degrees. Length must match feature_cols (or empty ⇒ no Fourier features).

interactions tuple[tuple[int, int], ...]

Pair-index list for interaction features.

encoder Callable[[Array], Array] | None

Optional single-example encoder (C,) -> (E,) whose output enters the network as one extra gated feature block (see pyrox_nn.BayesianNeuralField), for example geonnax.SphericalHarmonicEncoder(l_max=10, input_mode="lonlat"). It receives encoder_cols in the DataFrame's own units: the estimator undoes its standardization of those columns first (the time column arrives encoded, as in the design matrix).

encoder_cols tuple[int, ...] | None

Indices into feature_cols fed to encoder, in order; required exactly when encoder is given.

timetype Literal['int', 'datetime']

"int" or "datetime".

freq str | None

Optional unit string for datetime time columns.

noise NoiseModel

"fixed" (default) keeps the noise scale \(\sigma_0\) at sigma_obs; "learned" infers it through the sample site log_sigma_obs \(= \log \sigma_0 \sim \mathcal N(\log \sigma_{\text{obs}}, 1)\), which the MAP and VI ensembles treat like any other latent. With prior_weight=0 (MLE) and no sigma_col nothing bounds \(\sigma_0\) below, so that combination raises ValueError.

sigma_obs float

Observation noise std \(\sigma_0\) when noise="fixed" (with sigma_col, a floor for representativeness error), or the prior median of \(\sigma_0\) when noise="learned".

sigma_col str | None

Optional column of per-row noise stds \(\sigma_i > 0\), in target units. Each row's likelihood is \(\mathcal N(f(x_i), \sigma_i^2 + \sigma_0^2)\). The target is not rescaled by the estimator, so \(\sigma_i\) is used as given.

ensemble_size int

Number of MAP ensemble members.

num_epochs int

SGD-MAP iterations per member.

learning_rate float

Adam learning rate.

prior_weight float

1 ⇒ MAP, 0 ⇒ MLE, fractional ⇒ tempered.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
class BNFEstimator(EstimatorBase):
    r"""MAP-fit Bayesian Neural Field estimator.

    Composes the BNF layer (`pyrox_nn.BayesianNeuralField`) with
    pandas-side preprocessing (`pyrox_nn.preprocessing.fit_spatiotemporal`)
    and an ensemble-MAP inference loop
    (`pyrox.inference.ensemble_map`).

    Attributes:
        feature_cols: Input columns (first one is time).
        target_col: Target column.
        width: Hidden MLP width.
        depth: Hidden MLP depth.
        observation_model: ``"NORMAL"`` (currently only this is fully
            implemented). ``"NB"`` and ``"ZINB"`` raise
            ``NotImplementedError`` until ``gaussx.mixture_quantile``
            ships.
        seasonality_periods: Periods for seasonal features. Empty ⇒
            no seasonal features.
        num_seasonal_harmonics: Harmonics per period.
        fourier_degrees: Per-input dyadic Fourier degrees. Length must
            match ``feature_cols`` (or empty ⇒ no Fourier features).
        interactions: Pair-index list for interaction features.
        encoder: Optional single-example encoder ``(C,) -> (E,)`` whose
            output enters the network as one extra gated feature block (see
            `pyrox_nn.BayesianNeuralField`), for example
            ``geonnax.SphericalHarmonicEncoder(l_max=10, input_mode="lonlat")``.
            It receives ``encoder_cols`` in the DataFrame's own units: the
            estimator undoes its standardization of those columns first (the
            time column arrives encoded, as in the design matrix).
        encoder_cols: Indices into ``feature_cols`` fed to ``encoder``, in
            order; required exactly when ``encoder`` is given.
        timetype: ``"int"`` or ``"datetime"``.
        freq: Optional unit string for ``datetime`` time columns.
        noise: ``"fixed"`` (default) keeps the noise scale $\sigma_0$ at
            ``sigma_obs``; ``"learned"`` infers it through the sample site
            ``log_sigma_obs`` $= \log \sigma_0 \sim \mathcal N(\log
            \sigma_{\text{obs}}, 1)$, which the MAP and VI ensembles treat
            like any other latent. With ``prior_weight=0`` (MLE) and no
            ``sigma_col`` nothing bounds $\sigma_0$ below, so that
            combination raises ``ValueError``.
        sigma_obs: Observation noise std $\sigma_0$ when ``noise="fixed"``
            (with ``sigma_col``, a floor for representativeness error), or
            the prior median of $\sigma_0$ when ``noise="learned"``.
        sigma_col: Optional column of per-row noise stds $\sigma_i > 0$, in
            target units. Each row's likelihood is
            $\mathcal N(f(x_i), \sigma_i^2 + \sigma_0^2)$. The target is not
            rescaled by the estimator, so $\sigma_i$ is used as given.
        ensemble_size: Number of MAP ensemble members.
        num_epochs: SGD-MAP iterations per member.
        learning_rate: Adam learning rate.
        prior_weight: ``1`` ⇒ MAP, ``0`` ⇒ MLE, fractional ⇒ tempered.
    """

    width: int = eqx.field(static=True, default=64)
    depth: int = eqx.field(static=True, default=4)
    observation_model: ObservationModel = eqx.field(static=True, default="NORMAL")
    seasonality_periods: tuple[float, ...] = eqx.field(static=True, default=())
    num_seasonal_harmonics: tuple[int, ...] = eqx.field(static=True, default=())
    fourier_degrees: tuple[int, ...] = eqx.field(static=True, default=())
    interactions: tuple[tuple[int, int], ...] = eqx.field(static=True, default=())
    encoder: Callable[[Array], Array] | None = None
    encoder_cols: tuple[int, ...] | None = eqx.field(static=True, default=None)
    timetype: Literal["int", "datetime"] = eqx.field(static=True, default="int")
    freq: str | None = eqx.field(static=True, default=None)
    noise: NoiseModel = eqx.field(static=True, default="fixed")
    sigma_obs: float = eqx.field(static=True, default=0.1)
    sigma_col: str | None = eqx.field(static=True, default=None)
    ensemble_size: int = eqx.field(static=True, default=16)
    num_epochs: int = eqx.field(static=True, default=2000)
    learning_rate: float = eqx.field(static=True, default=5e-3)
    prior_weight: float = eqx.field(static=True, default=1.0)
    inference_kind: InferenceKind = eqx.field(static=True, default="map")
    standardize_columns: tuple[str, ...] | None = eqx.field(static=True, default=None)
    # Optional guide factory for the VI path. Takes the numpyro model
    # function and returns a guide. Defaults to AutoNormal at fit-time
    # (mean-field). Pass `AutoLowRankMultivariateNormal`, `AutoIAFNormal`,
    # `AutoBNAFNormal`, or any other AutoGuide constructor for richer
    # variational families that can represent posterior weight
    # correlations the mean-field guide cannot.
    guide_factory: Callable[[Callable], Any] | None = eqx.field(
        static=True, default=None
    )

    def fit(self, df: pd.DataFrame, *, seed: PRNGKeyArray | int) -> FittedBNF:
        if self.observation_model != "NORMAL":
            raise NotImplementedError(
                f"observation_model={self.observation_model!r} requires "
                "gaussx.mixture_quantile (tracked as gaussx#121). Use "
                "observation_model='NORMAL' for now."
            )
        if self.noise not in ("fixed", "learned"):
            # A BayesianNeuralField returns the field alone, so it cannot be
            # heteroscedastic.
            raise ValueError(f"noise must be 'fixed' or 'learned'; got {self.noise!r}.")
        # sigma_obs, the inference kind and learned noise under MLE are
        # validated by NeuralFieldEstimator.fit, after the preprocessing.
        # 1. Pandas-side preprocessing → SpatiotemporalFit bundle.
        fit_bundle = fit_spatiotemporal(
            df,
            feature_cols=self.feature_cols,
            target_col=self.target_col,
            timetype=self.timetype,
            freq=self.freq,
            seasonality_periods=self.seasonality_periods,
            num_seasonal_harmonics=self.num_seasonal_harmonics,
            fourier_degrees=self.fourier_degrees,
            interactions=self.interactions,
            standardize=self.standardize_columns,
        )
        # 2. Build the BNF layer template + design matrix.
        bnf = _build_bnf(
            fit_bundle, self.width, self.depth, self.encoder, self.encoder_cols
        )
        x_train = _df_to_design(df, fit_bundle, timetype=self.timetype, freq=self.freq)
        y_train = jnp.asarray(df[self.target_col].to_numpy(), dtype=jnp.float32)
        sigma_i = None
        if self.sigma_col is not None:
            sigma_i = _sigma_column(df, self.sigma_col)
        # 3. Run ensemble inference: a NeuralFieldEstimator on the BNF.
        fitted = NeuralFieldEstimator(
            model_fn=lambda: bnf,
            noise=self.noise,
            sigma_obs=self.sigma_obs,
            ensemble_size=self.ensemble_size,
            inference=self.inference_kind,
            num_epochs=self.num_epochs,
            learning_rate=self.learning_rate,
            prior_weight=self.prior_weight,
            guide_factory=self.guide_factory,
        ).fit(x_train, y_train, sigma=sigma_i, seed=seed)
        return FittedBNF(
            config=self,
            fit_bundle=fit_bundle,
            params=fitted.params,
            losses=fitted.losses,
            bnf_template=bnf,
        )

BNFEstimatorMLE

Bases: BNFEstimator

BNF estimator with prior_weight=0 (MLE).

Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
class BNFEstimatorMLE(BNFEstimator):
    """BNF estimator with `prior_weight=0` (MLE)."""

    prior_weight: float = eqx.field(static=True, default=0.0)

BNFEstimatorVI

Bases: BNFEstimator

BNF estimator using mean-field VI via ensemble_vi.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
class BNFEstimatorVI(BNFEstimator):
    """BNF estimator using mean-field VI via `ensemble_vi`."""

    inference_kind: InferenceKind = eqx.field(static=True, default="vi")

FittedBNF

Bases: FittedEstimator

Output of BNFEstimator.fit.

Attributes:

Name Type Description
config EstimatorBase

The BNFEstimator that produced this fit.

fit_bundle SpatiotemporalFit

Pandas-side preprocessing record.

params Any

Stacked per-ensemble-member parameter dict (each leaf has a leading (E,) axis for MAP, or an AutoNormal-shaped variational-parameter dict for VI).

losses Float[Array, 'E T']

Per-member loss history, shape (E, num_epochs).

bnf_template BayesianNeuralField

The BayesianNeuralField layer instance used for inference (identical across members).

Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
class FittedBNF(FittedEstimator):
    """Output of `BNFEstimator.fit`.

    Attributes:
        config: The `BNFEstimator` that produced this fit.
        fit_bundle: Pandas-side preprocessing record.
        params: Stacked per-ensemble-member parameter dict (each leaf
            has a leading ``(E,)`` axis for MAP, or an
            ``AutoNormal``-shaped variational-parameter dict for VI).
        losses: Per-member loss history, shape ``(E, num_epochs)``.
        bnf_template: The `BayesianNeuralField` layer instance
            used for inference (identical across members).
    """

    fit_bundle: SpatiotemporalFit
    params: Any
    losses: Float[Array, "E T"]
    bnf_template: BayesianNeuralField

    def predict(
        self,
        df: pd.DataFrame,
        *,
        quantiles: Sequence[float] | None = None,
        predict_seed: int = 0,
        num_posterior_samples: int = 32,
    ) -> Float[Array, " N"] | tuple[Float[Array, " N"], tuple[Float[Array, " N"], ...]]:
        r"""Posterior-predictive mean (and optional quantiles).

        For MAP fits the per-member predictions are point estimates;
        for VI fits we draw ``num_posterior_samples`` weight samples
        per member from the variational guide.

        The quantiles are those of the latent field plus the noise scale
        $\sigma_0$ (the fixed ``sigma_obs``, or each member's or draw's
        learned value): an equal-weight mixture of
        $\mathcal N(f_m(x), \sigma_{0,m}^2)$. Per-row $\sigma_i$ from
        ``sigma_col`` are not known at new points, so they are not added;
        add $\sigma_i^2$ yourself where you know it.

        Args:
            df: Inputs.
            quantiles: Optional levels. Returns ``(mean, (q_1, ..., q_K))``.
            predict_seed: PRNG seed for VI posterior sampling and
                quantile MC.
            num_posterior_samples: Per-member posterior draws used for
                VI predictive moments and quantile MC.
        """
        cfg = self.config
        assert isinstance(cfg, BNFEstimator)
        x_pred = _df_to_design(
            df, self.fit_bundle, timetype=cfg.timetype, freq=cfg.freq
        )
        return _predict(
            self.params,
            self.bnf_template,
            x_pred,
            encoder=None,
            noise=cfg.noise,
            sigma_obs=cfg.sigma_obs,
            has_sigma=cfg.sigma_col is not None,
            inference=cfg.inference_kind,
            guide_factory=cfg.guide_factory,
            quantiles=quantiles,
            predict_seed=predict_seed,
            num_posterior_samples=num_posterior_samples,
            # The BNF estimator keeps its published 200-draw floor, so its
            # quantiles are unchanged; NeuralFieldEstimator uses 2000.
            min_quantile_samples=200,
        )

predict(df: pd.DataFrame, *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Float[Array, ' N'] | tuple[Float[Array, ' N'], tuple[Float[Array, ' N'], ...]]

Posterior-predictive mean (and optional quantiles).

For MAP fits the per-member predictions are point estimates; for VI fits we draw num_posterior_samples weight samples per member from the variational guide.

The quantiles are those of the latent field plus the noise scale \(\sigma_0\) (the fixed sigma_obs, or each member's or draw's learned value): an equal-weight mixture of \(\mathcal N(f_m(x), \sigma_{0,m}^2)\). Per-row \(\sigma_i\) from sigma_col are not known at new points, so they are not added; add \(\sigma_i^2\) yourself where you know it.

Parameters:

Name Type Description Default
df DataFrame

Inputs.

required
quantiles Sequence[float] | None

Optional levels. Returns (mean, (q_1, ..., q_K)).

None
predict_seed int

PRNG seed for VI posterior sampling and quantile MC.

0
num_posterior_samples int

Per-member posterior draws used for VI predictive moments and quantile MC.

32
Source code in packages/pyrox-nn/src/pyrox_nn/api/_bnf.py
def predict(
    self,
    df: pd.DataFrame,
    *,
    quantiles: Sequence[float] | None = None,
    predict_seed: int = 0,
    num_posterior_samples: int = 32,
) -> Float[Array, " N"] | tuple[Float[Array, " N"], tuple[Float[Array, " N"], ...]]:
    r"""Posterior-predictive mean (and optional quantiles).

    For MAP fits the per-member predictions are point estimates;
    for VI fits we draw ``num_posterior_samples`` weight samples
    per member from the variational guide.

    The quantiles are those of the latent field plus the noise scale
    $\sigma_0$ (the fixed ``sigma_obs``, or each member's or draw's
    learned value): an equal-weight mixture of
    $\mathcal N(f_m(x), \sigma_{0,m}^2)$. Per-row $\sigma_i$ from
    ``sigma_col`` are not known at new points, so they are not added;
    add $\sigma_i^2$ yourself where you know it.

    Args:
        df: Inputs.
        quantiles: Optional levels. Returns ``(mean, (q_1, ..., q_K))``.
        predict_seed: PRNG seed for VI posterior sampling and
            quantile MC.
        num_posterior_samples: Per-member posterior draws used for
            VI predictive moments and quantile MC.
    """
    cfg = self.config
    assert isinstance(cfg, BNFEstimator)
    x_pred = _df_to_design(
        df, self.fit_bundle, timetype=cfg.timetype, freq=cfg.freq
    )
    return _predict(
        self.params,
        self.bnf_template,
        x_pred,
        encoder=None,
        noise=cfg.noise,
        sigma_obs=cfg.sigma_obs,
        has_sigma=cfg.sigma_col is not None,
        inference=cfg.inference_kind,
        guide_factory=cfg.guide_factory,
        quantiles=quantiles,
        predict_seed=predict_seed,
        num_posterior_samples=num_posterior_samples,
        # The BNF estimator keeps its published 200-draw floor, so its
        # quantiles are unchanged; NeuralFieldEstimator uses 2000.
        min_quantile_samples=200,
    )

Neural fields on arrays and xarray

NeuralFieldEstimator fits any Bayesian neural field, a callable that maps (encoded) coordinates to a field while registering its weights as NumPyro sites (BayesianSIREN, SphericalHarmonicFeatures, BayesianNeuralField, …), with pyrox.inference.ensemble_map or ensemble_vi. It takes plain arrays with optional per-row noise and a validity mask, so padded batches fit exactly like their valid rows, or an xarray Dataset (fit_xarray, pip install pyrox-nn[xarray]) whose missing cells are masked; datetimes become days since the first timestamp (or time_origin=), and FittedNeuralField.predict_xarray maps a Dataset's grid the same way. Under MAP, pyrox_param sites and constrained latents (e.g. a LogNormal prior) are optimised in unconstrained space against the constrained-space density (no Jacobian), and fields that draw numpyro.prng_key() are rejected (use inference="vi"). The BNF estimators above are this estimator on a BayesianNeuralField.

import geonnax
from pyrox_nn import BayesianSIREN
from pyrox_nn.api import NeuralFieldEstimator

est = NeuralFieldEstimator(
    model_fn=lambda: BayesianSIREN.init(441, 128, 1, depth=4, first_omega=1.0),
    encoder=geonnax.SphericalHarmonicEncoder(l_max=20, input_mode="lonlat"),
    noise="learned", ensemble_size=8, num_epochs=2000,
)
fitted = est.fit(X, y, sigma=sig, valid=mask, seed=0)  # X (N, 2) lon/lat in radians
mean, (q05, q95) = fitted.predict(X_new, quantiles=(0.05, 0.95))

NeuralFieldEstimator

Bases: Module

Fit any Bayesian neural field with ensemble MAP or VI.

The field is built by model_fn(): a callable mapping a batch of (encoded) coordinates (N, D_enc) to the field (N,) or (N, 1) while registering its weights as NumPyro sample sites, usually a PyroxModule such as pyrox_nn.BayesianSIREN, pyrox_nn.SphericalHarmonicFeatures or pyrox_nn.BayesianNeuralField. Each ensemble member maximises (MAP) or approximates (VI) the posterior of

\[ y_i \sim \mathcal N\bigl(f_\theta(\gamma(x_i)),\ \sigma_i^2 + \sigma_0^2\bigr), \]

where \(\gamma\) is encoder (identity when None), \(\sigma_i\) the optional per-row noise passed to fit and \(\sigma_0\) set by noise. Rows with valid[i] = False contribute nothing to the log joint or its gradient, so padded batches fit exactly like their valid rows alone.

Sites: the field's own, plus log_sigma_obs with noise="learned"; the likelihood site y and the deterministic sites f (and log_sigma_f with noise="heteroscedastic").

Attributes:

Name Type Description
model_fn Callable[[], Callable[[Array], Any]]

Zero-argument factory returning the field. Called once per fit; the returned module's sites must not depend on the data.

encoder Callable[[Array], Array] | None

Optional deterministic single-row encoder \(\gamma: (D,) \to (D_\mathrm{enc},)\) applied to every row before the field (vmapped), e.g. geonnax.SphericalHarmonicEncoder(l_max=20, input_mode="lonlat") (lon/lat in radians).

noise NoiseModel

"fixed" keeps \(\sigma_0\) at sigma_obs; "learned" infers it through the site log_sigma_obs \(= \log\sigma_0 \sim \mathcal N(\log\sigma_\mathrm{obs}, 1)\); "heteroscedastic" uses the field's own input-dependent scale: the field must return (mu, log_sigma), e.g. a trunk followed by pyrox_nn.GaussianRegressionHead, and \(\sigma_0 = \sigma(x_i)\). MAP members start from prior draws, and the head clips \(\log\sigma\) to \([-7, 3]\) with zero gradient outside, so keep its log_scale_prior_std small (the default 0.1): with 1.0 and a SIREN trunk, members start past the clip and never leave it. With prior_weight=0 (MLE), "learned" and no sigma, nothing bounds \(\sigma_0\) below, so fit raises.

sigma_obs float

\(\sigma_0\) for noise="fixed", or the prior median of \(\sigma_0\) for noise="learned"; unused when heteroscedastic.

ensemble_size int

Number of ensemble members \(E\).

inference InferenceKind

"map" (pyrox.inference.ensemble_map) or "vi" (pyrox.inference.ensemble_vi with guide_factory).

num_epochs int

Optimiser steps per member (full batch).

learning_rate float

Adam learning rate.

prior_weight float

1 ⇒ MAP, 0 ⇒ MLE, fractional ⇒ tempered (MAP only).

guide_factory Callable[[Callable], Any] | None

VI guide constructor taking the model function; None ⇒ AutoNormal.

Examples:

>>> import jax.numpy as jnp
>>> import geonnax.encoders
>>> from pyrox_nn import BayesianSIREN
>>> from pyrox_nn.api import NeuralFieldEstimator
>>> enc = geonnax.encoders.SphericalHarmonicEncoder(
...     l_max=3, input_mode="lonlat"
... )
>>> est = NeuralFieldEstimator(
...     model_fn=lambda: BayesianSIREN.init(16, 32, 1, depth=3),
...     encoder=enc, ensemble_size=2, num_epochs=10,
... )
>>> lonlat = jnp.stack([jnp.linspace(-3, 3, 20), jnp.zeros(20)], -1)
>>> fitted = est.fit(lonlat, jnp.sin(lonlat[:, 0]), seed=0)
>>> mean, (lo, hi) = fitted.predict(lonlat, quantiles=(0.05, 0.95))
>>> mean.shape, lo.shape
((20,), (20,))
Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
class NeuralFieldEstimator(eqx.Module):
    r"""Fit any Bayesian neural field with ensemble MAP or VI.

    The field is built by ``model_fn()``: a callable mapping a batch of
    (encoded) coordinates ``(N, D_enc)`` to the field ``(N,)`` or
    ``(N, 1)`` while registering its weights as NumPyro sample sites,
    usually a `PyroxModule` such as `pyrox_nn.BayesianSIREN`,
    `pyrox_nn.SphericalHarmonicFeatures` or
    `pyrox_nn.BayesianNeuralField`. Each ensemble member maximises (MAP) or
    approximates (VI) the posterior of

    $$
    y_i \sim \mathcal N\bigl(f_\theta(\gamma(x_i)),\
        \sigma_i^2 + \sigma_0^2\bigr),
    $$

    where $\gamma$ is ``encoder`` (identity when ``None``), $\sigma_i$ the
    optional per-row noise passed to ``fit`` and $\sigma_0$ set by
    ``noise``. Rows with ``valid[i] = False`` contribute nothing to the log
    joint or its gradient, so padded batches fit exactly like their valid
    rows alone.

    Sites: the field's own, plus ``log_sigma_obs`` with
    ``noise="learned"``; the likelihood site ``y`` and the deterministic
    sites ``f`` (and ``log_sigma_f`` with ``noise="heteroscedastic"``).

    Attributes:
        model_fn: Zero-argument factory returning the field. Called once per
            ``fit``; the returned module's sites must not depend on the data.
        encoder: Optional deterministic single-row encoder
            $\gamma: (D,) \to (D_\mathrm{enc},)$ applied to every row before
            the field (vmapped), e.g.
            ``geonnax.SphericalHarmonicEncoder(l_max=20, input_mode="lonlat")``
            (lon/lat in radians).
        noise: ``"fixed"`` keeps $\sigma_0$ at ``sigma_obs``; ``"learned"``
            infers it through the site ``log_sigma_obs`` $= \log\sigma_0 \sim
            \mathcal N(\log\sigma_\mathrm{obs}, 1)$; ``"heteroscedastic"``
            uses the field's own input-dependent scale: the field must
            return ``(mu, log_sigma)``, e.g. a trunk followed by
            `pyrox_nn.GaussianRegressionHead`, and $\sigma_0 = \sigma(x_i)$.
            MAP members start from prior draws, and the head clips
            $\log\sigma$ to $[-7, 3]$ with zero gradient outside, so keep its
            ``log_scale_prior_std`` small (the default 0.1): with 1.0 and a
            SIREN trunk, members start past the clip and never leave it.
            With ``prior_weight=0`` (MLE), ``"learned"`` and no ``sigma``,
            nothing bounds $\sigma_0$ below, so ``fit`` raises.
        sigma_obs: $\sigma_0$ for ``noise="fixed"``, or the prior median of
            $\sigma_0$ for ``noise="learned"``; unused when heteroscedastic.
        ensemble_size: Number of ensemble members $E$.
        inference: ``"map"`` (``pyrox.inference.ensemble_map``) or ``"vi"``
            (``pyrox.inference.ensemble_vi`` with ``guide_factory``).
        num_epochs: Optimiser steps per member (full batch).
        learning_rate: Adam learning rate.
        prior_weight: ``1`` ⇒ MAP, ``0`` ⇒ MLE, fractional ⇒ tempered
            (MAP only).
        guide_factory: VI guide constructor taking the model function;
            ``None`` ⇒ ``AutoNormal``.

    Examples:
        >>> import jax.numpy as jnp
        >>> import geonnax.encoders
        >>> from pyrox_nn import BayesianSIREN
        >>> from pyrox_nn.api import NeuralFieldEstimator
        >>> enc = geonnax.encoders.SphericalHarmonicEncoder(
        ...     l_max=3, input_mode="lonlat"
        ... )
        >>> est = NeuralFieldEstimator(
        ...     model_fn=lambda: BayesianSIREN.init(16, 32, 1, depth=3),
        ...     encoder=enc, ensemble_size=2, num_epochs=10,
        ... )
        >>> lonlat = jnp.stack([jnp.linspace(-3, 3, 20), jnp.zeros(20)], -1)
        >>> fitted = est.fit(lonlat, jnp.sin(lonlat[:, 0]), seed=0)
        >>> mean, (lo, hi) = fitted.predict(lonlat, quantiles=(0.05, 0.95))
        >>> mean.shape, lo.shape
        ((20,), (20,))
    """

    model_fn: Callable[[], Callable[[Array], Any]] = eqx.field(static=True)
    encoder: Callable[[Array], Array] | None = None
    noise: NoiseModel = eqx.field(static=True, default="fixed")
    sigma_obs: float = eqx.field(static=True, default=0.1)
    ensemble_size: int = eqx.field(static=True, default=16)
    inference: InferenceKind = eqx.field(static=True, default="map")
    num_epochs: int = eqx.field(static=True, default=2000)
    learning_rate: float = eqx.field(static=True, default=5e-3)
    prior_weight: float = eqx.field(static=True, default=1.0)
    guide_factory: Callable[[Callable], Any] | None = eqx.field(
        static=True, default=None
    )

    def fit(
        self,
        X: Float[ArrayLike, "N D"],
        y: Float[ArrayLike, " N"],
        *,
        sigma: Float[ArrayLike, " N"] | None = None,
        valid: ArrayLike | None = None,
        seed: PRNGKeyArray | int,
    ) -> FittedNeuralField:
        r"""Fit the ensemble on arrays.

        Args:
            X: Coordinates of shape ``(N, D)`` (the encoder's input units).
            y: Targets of shape ``(N,)``.
            sigma: Optional per-row noise stds $\sigma_i$ of shape ``(N,)``,
                finite and > 0 on valid rows, in target units.
            valid: Optional boolean mask of shape ``(N,)``; rows with
                ``False`` (padding) are ignored, whatever their values.
            seed: PRNG key or integer seed.

        Returns:
            The fitted ensemble.

        Raises:
            ValueError: On a bad configuration, mismatched shapes, a mask
                with no valid row, or non-finite values (or $\sigma_i \le 0$)
                on a valid row.
        """
        _check_config(
            noise=self.noise,
            sigma_obs=self.sigma_obs,
            inference=self.inference,
            prior_weight=self.prior_weight,
            has_sigma=sigma is not None,
        )
        x_train, y_train = _pack_data(X, y, sigma, valid)
        if isinstance(seed, int):
            seed = jr.PRNGKey(seed)
        field = self.model_fn()
        model_fn = _field_model(
            _make_forward(field, self.encoder),
            self.sigma_obs,
            noise=self.noise,
            has_sigma=sigma is not None,
            has_valid=valid is not None,
        )
        params, losses = _fit_ensemble(
            model_fn,
            x_train,
            y_train,
            inference=self.inference,
            ensemble_size=self.ensemble_size,
            num_epochs=self.num_epochs,
            learning_rate=self.learning_rate,
            prior_weight=self.prior_weight,
            guide_factory=self.guide_factory,
            seed=seed,
        )
        return FittedNeuralField(
            config=self,
            field=field,
            params=params,
            losses=losses,
            has_sigma=sigma is not None,
        )

    def fit_xarray(
        self,
        ds: Any,
        *,
        coords: Sequence[str],
        target: str,
        sigma: str | None = None,
        time_origin: Any = None,
        seed: PRNGKeyArray | int,
    ) -> FittedNeuralField:
        r"""Fit on an xarray Dataset (``pip install pyrox-nn[xarray]``).

        Every variable named in ``coords``, ``target`` and ``sigma`` (a
        dimension, coordinate or data variable) is broadcast against the
        others and flattened, in the target's dimension order, to one row
        per grid point; ``coords`` become the columns of ``X`` in the order
        given. Rows where any of them is missing (NaN, NaT) are masked out,
        so a gappy grid needs no reshaping.

        A datetime coordinate becomes float days since ``time_origin``
        (default: its earliest timestamp), so the column starts near 0
        instead of at ~2·10⁴ days since 1970, which float32 would resolve
        only to minutes and a SIREN would see as a huge frequency. A
        timedelta coordinate becomes float days. The origins are stored on
        the fit; `FittedNeuralField.predict_xarray` applies the same
        mapping, and ``predict`` on arrays expects the same units.

        Args:
            ds: An ``xarray.Dataset``.
            coords: Names of the input variables, e.g. ``("lon", "lat", "time")``.
            target: Name of the target variable.
            sigma: Optional name of the per-row noise std variable.
            time_origin: Optional reference time for every datetime
                coordinate (anything ``numpy.datetime64`` accepts).
            seed: PRNG key or integer seed.

        Returns:
            The fitted ensemble, which remembers ``coords`` and the time
            origins.

        Raises:
            ImportError: If xarray is not installed.
            ValueError: If a name is not a variable of ``ds``, or as `fit`.
        """
        xr = _require_xarray("fit_xarray")
        names = [*coords, target, *([sigma] if sigma is not None else [])]
        _check_names(ds, names)
        # Flatten in the target's dimension order (C order), whatever the
        # order of ``coords``.
        arrays = xr.broadcast(*(ds[name] for name in names))
        dims = (
            *ds[target].dims,
            *(d for d in arrays[0].dims if d not in ds[target].dims),
        )
        arrays = [a.transpose(*dims) for a in arrays]
        origins = tuple(_time_origin(ds[name].values, time_origin) for name in coords)
        cols = [
            _numeric_column(a.values.ravel(), origin)
            for a, origin in zip(
                arrays, (*origins, *([None] * (len(names) - len(coords)))), strict=True
            )
        ]
        X = np.stack(cols[: len(coords)], axis=-1)
        valid = np.isfinite(np.stack(cols, axis=-1)).all(axis=-1)
        fitted = self.fit(
            X,
            cols[len(coords)],
            sigma=None if sigma is None else cols[-1],
            valid=valid,
            seed=seed,
        )
        return FittedNeuralField(
            config=fitted.config,
            field=fitted.field,
            params=fitted.params,
            losses=fitted.losses,
            has_sigma=fitted.has_sigma,
            xarray_coords=tuple(coords),
            time_origins=origins,
        )

fit(X: Float[ArrayLike, 'N D'], y: Float[ArrayLike, ' N'], *, sigma: Float[ArrayLike, ' N'] | None = None, valid: ArrayLike | None = None, seed: PRNGKeyArray | int) -> FittedNeuralField

Fit the ensemble on arrays.

Parameters:

Name Type Description Default
X Float[ArrayLike, 'N D']

Coordinates of shape (N, D) (the encoder's input units).

required
y Float[ArrayLike, ' N']

Targets of shape (N,).

required
sigma Float[ArrayLike, ' N'] | None

Optional per-row noise stds \(\sigma_i\) of shape (N,), finite and > 0 on valid rows, in target units.

None
valid ArrayLike | None

Optional boolean mask of shape (N,); rows with False (padding) are ignored, whatever their values.

None
seed PRNGKeyArray | int

PRNG key or integer seed.

required

Returns:

Type Description
FittedNeuralField

The fitted ensemble.

Raises:

Type Description
ValueError

On a bad configuration, mismatched shapes, a mask with no valid row, or non-finite values (or \(\sigma_i \le 0\)) on a valid row.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
def fit(
    self,
    X: Float[ArrayLike, "N D"],
    y: Float[ArrayLike, " N"],
    *,
    sigma: Float[ArrayLike, " N"] | None = None,
    valid: ArrayLike | None = None,
    seed: PRNGKeyArray | int,
) -> FittedNeuralField:
    r"""Fit the ensemble on arrays.

    Args:
        X: Coordinates of shape ``(N, D)`` (the encoder's input units).
        y: Targets of shape ``(N,)``.
        sigma: Optional per-row noise stds $\sigma_i$ of shape ``(N,)``,
            finite and > 0 on valid rows, in target units.
        valid: Optional boolean mask of shape ``(N,)``; rows with
            ``False`` (padding) are ignored, whatever their values.
        seed: PRNG key or integer seed.

    Returns:
        The fitted ensemble.

    Raises:
        ValueError: On a bad configuration, mismatched shapes, a mask
            with no valid row, or non-finite values (or $\sigma_i \le 0$)
            on a valid row.
    """
    _check_config(
        noise=self.noise,
        sigma_obs=self.sigma_obs,
        inference=self.inference,
        prior_weight=self.prior_weight,
        has_sigma=sigma is not None,
    )
    x_train, y_train = _pack_data(X, y, sigma, valid)
    if isinstance(seed, int):
        seed = jr.PRNGKey(seed)
    field = self.model_fn()
    model_fn = _field_model(
        _make_forward(field, self.encoder),
        self.sigma_obs,
        noise=self.noise,
        has_sigma=sigma is not None,
        has_valid=valid is not None,
    )
    params, losses = _fit_ensemble(
        model_fn,
        x_train,
        y_train,
        inference=self.inference,
        ensemble_size=self.ensemble_size,
        num_epochs=self.num_epochs,
        learning_rate=self.learning_rate,
        prior_weight=self.prior_weight,
        guide_factory=self.guide_factory,
        seed=seed,
    )
    return FittedNeuralField(
        config=self,
        field=field,
        params=params,
        losses=losses,
        has_sigma=sigma is not None,
    )

fit_xarray(ds: Any, *, coords: Sequence[str], target: str, sigma: str | None = None, time_origin: Any = None, seed: PRNGKeyArray | int) -> FittedNeuralField

Fit on an xarray Dataset (pip install pyrox-nn[xarray]).

Every variable named in coords, target and sigma (a dimension, coordinate or data variable) is broadcast against the others and flattened, in the target's dimension order, to one row per grid point; coords become the columns of X in the order given. Rows where any of them is missing (NaN, NaT) are masked out, so a gappy grid needs no reshaping.

A datetime coordinate becomes float days since time_origin (default: its earliest timestamp), so the column starts near 0 instead of at ~2·10⁴ days since 1970, which float32 would resolve only to minutes and a SIREN would see as a huge frequency. A timedelta coordinate becomes float days. The origins are stored on the fit; FittedNeuralField.predict_xarray applies the same mapping, and predict on arrays expects the same units.

Parameters:

Name Type Description Default
ds Any

An xarray.Dataset.

required
coords Sequence[str]

Names of the input variables, e.g. ("lon", "lat", "time").

required
target str

Name of the target variable.

required
sigma str | None

Optional name of the per-row noise std variable.

None
time_origin Any

Optional reference time for every datetime coordinate (anything numpy.datetime64 accepts).

None
seed PRNGKeyArray | int

PRNG key or integer seed.

required

Returns:

Type Description
FittedNeuralField

The fitted ensemble, which remembers coords and the time

FittedNeuralField

origins.

Raises:

Type Description
ImportError

If xarray is not installed.

ValueError

If a name is not a variable of ds, or as fit.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
def fit_xarray(
    self,
    ds: Any,
    *,
    coords: Sequence[str],
    target: str,
    sigma: str | None = None,
    time_origin: Any = None,
    seed: PRNGKeyArray | int,
) -> FittedNeuralField:
    r"""Fit on an xarray Dataset (``pip install pyrox-nn[xarray]``).

    Every variable named in ``coords``, ``target`` and ``sigma`` (a
    dimension, coordinate or data variable) is broadcast against the
    others and flattened, in the target's dimension order, to one row
    per grid point; ``coords`` become the columns of ``X`` in the order
    given. Rows where any of them is missing (NaN, NaT) are masked out,
    so a gappy grid needs no reshaping.

    A datetime coordinate becomes float days since ``time_origin``
    (default: its earliest timestamp), so the column starts near 0
    instead of at ~2·10⁴ days since 1970, which float32 would resolve
    only to minutes and a SIREN would see as a huge frequency. A
    timedelta coordinate becomes float days. The origins are stored on
    the fit; `FittedNeuralField.predict_xarray` applies the same
    mapping, and ``predict`` on arrays expects the same units.

    Args:
        ds: An ``xarray.Dataset``.
        coords: Names of the input variables, e.g. ``("lon", "lat", "time")``.
        target: Name of the target variable.
        sigma: Optional name of the per-row noise std variable.
        time_origin: Optional reference time for every datetime
            coordinate (anything ``numpy.datetime64`` accepts).
        seed: PRNG key or integer seed.

    Returns:
        The fitted ensemble, which remembers ``coords`` and the time
        origins.

    Raises:
        ImportError: If xarray is not installed.
        ValueError: If a name is not a variable of ``ds``, or as `fit`.
    """
    xr = _require_xarray("fit_xarray")
    names = [*coords, target, *([sigma] if sigma is not None else [])]
    _check_names(ds, names)
    # Flatten in the target's dimension order (C order), whatever the
    # order of ``coords``.
    arrays = xr.broadcast(*(ds[name] for name in names))
    dims = (
        *ds[target].dims,
        *(d for d in arrays[0].dims if d not in ds[target].dims),
    )
    arrays = [a.transpose(*dims) for a in arrays]
    origins = tuple(_time_origin(ds[name].values, time_origin) for name in coords)
    cols = [
        _numeric_column(a.values.ravel(), origin)
        for a, origin in zip(
            arrays, (*origins, *([None] * (len(names) - len(coords)))), strict=True
        )
    ]
    X = np.stack(cols[: len(coords)], axis=-1)
    valid = np.isfinite(np.stack(cols, axis=-1)).all(axis=-1)
    fitted = self.fit(
        X,
        cols[len(coords)],
        sigma=None if sigma is None else cols[-1],
        valid=valid,
        seed=seed,
    )
    return FittedNeuralField(
        config=fitted.config,
        field=fitted.field,
        params=fitted.params,
        losses=fitted.losses,
        has_sigma=fitted.has_sigma,
        xarray_coords=tuple(coords),
        time_origins=origins,
    )

FittedNeuralField

Bases: Module

Output of NeuralFieldEstimator.fit.

Attributes:

Name Type Description
config NeuralFieldEstimator

The NeuralFieldEstimator that produced this fit.

field Any

The field returned by model_fn() (identical across members; the weights live in params).

params Any

Stacked per-member parameters: a dict of the field's sites with a leading (E,) axis for MAP, or the guide's variational parameters for VI.

losses Float[Array, 'E T']

Per-member loss history, shape (E, num_epochs).

has_sigma bool

Whether per-row \(\sigma_i\) were given at fit time.

xarray_coords tuple[str, ...] | None

The coords of fit_xarray (None after fit).

time_origins tuple[str | None, ...] | None

Per coordinate, the reference time of a datetime coordinate as an ISO string (None for the others), from fit_xarray.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
class FittedNeuralField(eqx.Module):
    """Output of `NeuralFieldEstimator.fit`.

    Attributes:
        config: The `NeuralFieldEstimator` that produced this fit.
        field: The field returned by ``model_fn()`` (identical across
            members; the weights live in ``params``).
        params: Stacked per-member parameters: a dict of the field's sites
            with a leading ``(E,)`` axis for MAP, or the guide's
            variational parameters for VI.
        losses: Per-member loss history, shape ``(E, num_epochs)``.
        has_sigma: Whether per-row $\\sigma_i$ were given at fit time.
        xarray_coords: The ``coords`` of ``fit_xarray`` (``None`` after
            ``fit``).
        time_origins: Per coordinate, the reference time of a datetime
            coordinate as an ISO string (``None`` for the others), from
            ``fit_xarray``.
    """

    config: NeuralFieldEstimator
    field: Any
    params: Any
    losses: Float[Array, "E T"]
    has_sigma: bool = eqx.field(static=True, default=False)
    xarray_coords: tuple[str, ...] | None = eqx.field(static=True, default=None)
    time_origins: tuple[str | None, ...] | None = eqx.field(static=True, default=None)

    def predict(
        self,
        X: Float[ArrayLike, "N D"],
        *,
        quantiles: Sequence[float] | None = None,
        predict_seed: int = 0,
        num_posterior_samples: int = 32,
    ) -> Prediction:
        r"""Posterior-predictive mean (and optional quantiles).

        MAP members give one prediction each; VI members give
        ``num_posterior_samples`` guide draws each. The quantiles are those
        of the equal-weight mixture of $\mathcal N(f_m(x), \sigma_{0,m}^2)$
        over members (or draws), estimated by Monte Carlo, with
        $\sigma_{0,m}$ the fixed ``sigma_obs``, the member's learned value,
        or its $\sigma_m(x)$ when heteroscedastic. Per-row $\sigma_i$ are not
        known at new points, so they are not added.

        Args:
            X: Coordinates of shape ``(N, D)``, in the units used to fit.
            quantiles: Optional levels; then returns
                ``(mean, (q_1, ..., q_K))``.
            predict_seed: PRNG seed for VI posterior draws and quantile MC.
            num_posterior_samples: Per-member draws for VI predictions and
                quantile MC.

        Returns:
            The mean of shape ``(N,)``, or ``(mean, quantiles)``.
        """
        cfg = self.config
        return _predict(
            self.params,
            self.field,
            _floating(X),
            encoder=cfg.encoder,
            noise=cfg.noise,
            sigma_obs=cfg.sigma_obs,
            has_sigma=self.has_sigma,
            inference=cfg.inference,
            guide_factory=cfg.guide_factory,
            quantiles=quantiles,
            predict_seed=predict_seed,
            num_posterior_samples=num_posterior_samples,
        )

    def predict_xarray(
        self,
        ds: Any,
        *,
        quantiles: Sequence[float] | None = None,
        predict_seed: int = 0,
        num_posterior_samples: int = 32,
    ) -> Any:
        """Predict on the grid of an xarray Dataset, as fitted by ``fit_xarray``.

        The fitted ``coords`` are read from ``ds``, broadcast against each
        other and mapped to the fit's units (datetimes as days since the
        stored origins); the result has their broadcast shape and
        coordinates. A grid point with a missing coordinate predicts NaN.

        Args:
            ds: An ``xarray.Dataset`` holding the fitted ``coords``.
            quantiles: Optional levels, as in `predict`.
            predict_seed: As in `predict`.
            num_posterior_samples: As in `predict`.

        Returns:
            The mean as an ``xarray.DataArray``, or ``(mean, quantiles)``
            with one ``DataArray`` per level.

        Raises:
            ValueError: If this fit did not come from ``fit_xarray``, or a
                coordinate is not a variable of ``ds``.
        """
        if self.xarray_coords is None or self.time_origins is None:
            raise ValueError("predict_xarray needs a fit from fit_xarray.")
        xr = _require_xarray("predict_xarray")
        _check_names(ds, self.xarray_coords)
        arrays = xr.broadcast(*(ds[name] for name in self.xarray_coords))
        template = arrays[0]
        cols = [
            _numeric_column(a.transpose(*template.dims).values.ravel(), origin)
            for a, origin in zip(arrays, self.time_origins, strict=True)
        ]
        X = np.stack(cols, axis=-1)
        rows = np.asarray(np.isfinite(X).all(axis=-1))
        out = self.predict(
            np.where(rows[:, None], X, 0.0),
            quantiles=quantiles,
            predict_seed=predict_seed,
            num_posterior_samples=num_posterior_samples,
        )

        def as_grid(values: Any) -> Any:
            grid = np.where(rows, np.asarray(values), np.nan).reshape(template.shape)
            return xr.DataArray(grid, coords=template.coords, dims=template.dims)

        if quantiles is None:
            return as_grid(out)
        mean, qs = out
        return as_grid(mean), tuple(as_grid(q) for q in qs)

predict(X: Float[ArrayLike, 'N D'], *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Prediction

Posterior-predictive mean (and optional quantiles).

MAP members give one prediction each; VI members give num_posterior_samples guide draws each. The quantiles are those of the equal-weight mixture of \(\mathcal N(f_m(x), \sigma_{0,m}^2)\) over members (or draws), estimated by Monte Carlo, with \(\sigma_{0,m}\) the fixed sigma_obs, the member's learned value, or its \(\sigma_m(x)\) when heteroscedastic. Per-row \(\sigma_i\) are not known at new points, so they are not added.

Parameters:

Name Type Description Default
X Float[ArrayLike, 'N D']

Coordinates of shape (N, D), in the units used to fit.

required
quantiles Sequence[float] | None

Optional levels; then returns (mean, (q_1, ..., q_K)).

None
predict_seed int

PRNG seed for VI posterior draws and quantile MC.

0
num_posterior_samples int

Per-member draws for VI predictions and quantile MC.

32

Returns:

Type Description
Prediction

The mean of shape (N,), or (mean, quantiles).

Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
def predict(
    self,
    X: Float[ArrayLike, "N D"],
    *,
    quantiles: Sequence[float] | None = None,
    predict_seed: int = 0,
    num_posterior_samples: int = 32,
) -> Prediction:
    r"""Posterior-predictive mean (and optional quantiles).

    MAP members give one prediction each; VI members give
    ``num_posterior_samples`` guide draws each. The quantiles are those
    of the equal-weight mixture of $\mathcal N(f_m(x), \sigma_{0,m}^2)$
    over members (or draws), estimated by Monte Carlo, with
    $\sigma_{0,m}$ the fixed ``sigma_obs``, the member's learned value,
    or its $\sigma_m(x)$ when heteroscedastic. Per-row $\sigma_i$ are not
    known at new points, so they are not added.

    Args:
        X: Coordinates of shape ``(N, D)``, in the units used to fit.
        quantiles: Optional levels; then returns
            ``(mean, (q_1, ..., q_K))``.
        predict_seed: PRNG seed for VI posterior draws and quantile MC.
        num_posterior_samples: Per-member draws for VI predictions and
            quantile MC.

    Returns:
        The mean of shape ``(N,)``, or ``(mean, quantiles)``.
    """
    cfg = self.config
    return _predict(
        self.params,
        self.field,
        _floating(X),
        encoder=cfg.encoder,
        noise=cfg.noise,
        sigma_obs=cfg.sigma_obs,
        has_sigma=self.has_sigma,
        inference=cfg.inference,
        guide_factory=cfg.guide_factory,
        quantiles=quantiles,
        predict_seed=predict_seed,
        num_posterior_samples=num_posterior_samples,
    )

predict_xarray(ds: Any, *, quantiles: Sequence[float] | None = None, predict_seed: int = 0, num_posterior_samples: int = 32) -> Any

Predict on the grid of an xarray Dataset, as fitted by fit_xarray.

The fitted coords are read from ds, broadcast against each other and mapped to the fit's units (datetimes as days since the stored origins); the result has their broadcast shape and coordinates. A grid point with a missing coordinate predicts NaN.

Parameters:

Name Type Description Default
ds Any

An xarray.Dataset holding the fitted coords.

required
quantiles Sequence[float] | None

Optional levels, as in predict.

None
predict_seed int

As in predict.

0
num_posterior_samples int

As in predict.

32

Returns:

Type Description
Any

The mean as an xarray.DataArray, or (mean, quantiles)

Any

with one DataArray per level.

Raises:

Type Description
ValueError

If this fit did not come from fit_xarray, or a coordinate is not a variable of ds.

Source code in packages/pyrox-nn/src/pyrox_nn/api/_field.py
def predict_xarray(
    self,
    ds: Any,
    *,
    quantiles: Sequence[float] | None = None,
    predict_seed: int = 0,
    num_posterior_samples: int = 32,
) -> Any:
    """Predict on the grid of an xarray Dataset, as fitted by ``fit_xarray``.

    The fitted ``coords`` are read from ``ds``, broadcast against each
    other and mapped to the fit's units (datetimes as days since the
    stored origins); the result has their broadcast shape and
    coordinates. A grid point with a missing coordinate predicts NaN.

    Args:
        ds: An ``xarray.Dataset`` holding the fitted ``coords``.
        quantiles: Optional levels, as in `predict`.
        predict_seed: As in `predict`.
        num_posterior_samples: As in `predict`.

    Returns:
        The mean as an ``xarray.DataArray``, or ``(mean, quantiles)``
        with one ``DataArray`` per level.

    Raises:
        ValueError: If this fit did not come from ``fit_xarray``, or a
            coordinate is not a variable of ``ds``.
    """
    if self.xarray_coords is None or self.time_origins is None:
        raise ValueError("predict_xarray needs a fit from fit_xarray.")
    xr = _require_xarray("predict_xarray")
    _check_names(ds, self.xarray_coords)
    arrays = xr.broadcast(*(ds[name] for name in self.xarray_coords))
    template = arrays[0]
    cols = [
        _numeric_column(a.transpose(*template.dims).values.ravel(), origin)
        for a, origin in zip(arrays, self.time_origins, strict=True)
    ]
    X = np.stack(cols, axis=-1)
    rows = np.asarray(np.isfinite(X).all(axis=-1))
    out = self.predict(
        np.where(rows[:, None], X, 0.0),
        quantiles=quantiles,
        predict_seed=predict_seed,
        num_posterior_samples=num_posterior_samples,
    )

    def as_grid(values: Any) -> Any:
        grid = np.where(rows, np.asarray(values), np.nan).reshape(template.shape)
        return xr.DataArray(grid, coords=template.coords, dims=template.dims)

    if quantiles is None:
        return as_grid(out)
    mean, qs = out
    return as_grid(mean), tuple(as_grid(q) for q in qs)