Skip to content

Inference

The inference layer fits ODE parameters by maximizing the marginal log-likelihood of external observations under the ODE-constrained Gauss-Markov model. It consists of ODEFilter, fit, fit_scipy, marginal_loglik and InferenceProblem, and of the parameter wrappers Real, PositiveReal and NonNegativeReal. fit minimizes the negative log-likelihood with an Optax optimizer supplied by the caller. fit_scipy minimizes it with SciPy's quasi-Newton methods (L-BFGS-B by default), which on low-dimensional problems usually need fewer evaluations. The diagnostics check a fitted model against its data.

marginal_loglik takes the data as a list of Measurement objects, which it converts with prepare_observations(data, prior.E0_state, ts), or as an ObsModel for InferenceProblem.ts. It solves on the fixed grid ts by default. Data between the grid nodes become data-only nodes, where the filter conditions on the data without an update on the ODE information, and every channel works with them. With InferenceProblem(..., adaptive=AdaptiveSettings(atol=..., rtol=...)) it runs gaussian_filter_adaptive with ts as the save grid, which lands on the data times as well. The channels "obs", "ode", "both" and "fenrir" are available there, and the result is differentiable in the parameters.

fenrir_loglik takes the data as an ObsModel from prepare_observations and a pass without data, and conditional_loglik takes a pass with and one without data. With data-only nodes the pass without data must run on the same timeline as the data: pass obs_model=obs_model.without_data() to the solver, which keeps the timeline and drops every row. information_criteria takes the data like marginal_loglik and runs its passes with the data over the timeline as well.

Parameter inference

ODEFilter

Bases: Module

A fittable first-order probabilistic ODE solver.

Attributes:

Name Type Description
vf Callable

Vector field vf(x, params, *, t) -> dx/dt (params is the differentiable parameter pytree, ode_params).

init_fn Callable

Callable params -> (m_0, P_0_sqr) producing the initial Gaussian (square-root covariance). May ignore params for a fixed initial condition.

prior BasePrior

Gauss-Markov prior (e.g. IWP); fixed during fit.

ts tuple[float, ...]

Time grid, shape [K]; stored as a tuple, so it is static configuration rather than a trainable leaf.

ode_params Any

The parameters fit trains.

calibration Calibration | CalibrationMode

Diffusion calibration policy or shorthand (default "none").

loglik

loglik(data: ObsModel | Sequence[Measurement]) -> Array

Data marginal log-likelihood at the current parameters.

data is an ObsModel for ts or a sequence of Measurement objects, as in marginal_loglik.

fit

fit(
    model: ODEFilter,
    data: ObsModel | Sequence[Measurement],
    optim: Any,
    *,
    steps: int = 200,
) -> tuple[ODEFilter, Array]

Fit an ODEFilter by maximizing the data marginal log-likelihood.

Parameters:

Name Type Description Default
model ODEFilter

Initial ODEFilter.

required
data ObsModel | Sequence[Measurement]

Observations as an ObsModel or a sequence of Measurement objects (see marginal_loglik).

required
optim Any

An Optax GradientTransformation (anything exposing init / update); the library does not import Optax itself.

required
steps int

Number of optimization steps.

200

Returns:

Type Description
ODEFilter

Tuple (fitted_model, losses) where losses is the per-step negative

Array

log-likelihood (shape [steps]).

fit_scipy

fit_scipy(
    objective: Callable[[Any], Array],
    theta0: Any,
    *,
    method: str = "L-BFGS-B",
    **options: Any,
) -> tuple[Any, Any]

Minimize objective(theta) with SciPy, using JAX gradients.

A two-tier alternative to the Optax fit: quasi-Newton methods such as L-BFGS-B converge in far fewer evaluations on the smooth, low-dimensional objectives of hyperparameter selection. theta may be any pytree of arrays (it is flattened for SciPy and unflattened for the objective); the objective and its gradient are jitted once.

Parameters:

Name Type Description Default
objective Callable[[Any], Array]

Scalar function to minimize, e.g. lambda th: -marginal_loglik(th, data, model=problem).

required
theta0 Any

Initial parameters (a pytree of arrays).

required
method str

A gradient-based scipy.optimize.minimize method.

'L-BFGS-B'
**options Any

Passed to scipy.optimize.minimize (e.g. bounds, tol, options).

{}

Returns:

Type Description
Any

(theta_hat, result): the minimizer as a pytree like theta0, and

Any

SciPy's OptimizeResult.

Raises:

Type Description
ImportError

If SciPy is not installed (pip install ode-filters[inference]).

marginal_loglik

marginal_loglik(
    theta: Any,
    data: ObsModel | Sequence[Measurement],
    *,
    model: InferenceProblem,
    channel: Literal["obs", "fenrir", "dalton"] = ...,
) -> Array
marginal_loglik(
    theta: Any,
    data: ObsModel | Sequence[Measurement] | None,
    *,
    model: InferenceProblem,
    channel: Literal["ode"],
) -> Array
marginal_loglik(
    theta: Any,
    data: ObsModel | Sequence[Measurement],
    *,
    model: InferenceProblem,
    channel: Literal["both"],
) -> tuple[Array, Array]
marginal_loglik(
    theta: Any,
    data: ObsModel | Sequence[Measurement] | None,
    *,
    model: InferenceProblem,
    channel: str = "obs",
) -> Array | tuple[Array, Array]

Marginal log-likelihood for gradient-based ODE-parameter inference.

Parameters:

Name Type Description Default
theta Any

Differentiable parameter pytree, consumed by model.build (and by model.prior_fn, if set). May contain PositiveReal / Real wrappers, which are unwrapped automatically.

required
data ObsModel | Sequence[Measurement] | None

Observations as an ObsModel for model.ts (e.g. from prepare_observations), whose measured values live in data.c_seq, or as a sequence of Measurement objects. These are converted with prepare_observations(data, prior.E0_state, model.ts), where prior is model.prior or model.prior_fn(theta). Data between the nodes of model.ts become data-only nodes. Required unless channel="ode", which needs no observations and so accepts None.

required
model InferenceProblem

Static InferenceProblem (closed over, not traced).

required
channel str

Which evidence channel to return.

  • "obs" (default): FilterResult.log_likelihood_obs, the data evidence of the sequential filter. A scalar.
  • "ode": the ODE-defect (residual) marginal log-likelihood. A scalar; does not require observations. With data-only nodes it is the evidence of the ODE information at the grid nodes, given the data before each of them.
  • "both": the tuple (ll_ode, ll_obs). The two channels are sums over different numbers of terms, N filter steps and K observations respectively. Choose their weights explicitly when combining them, because in the unweighted sum the influence of the residual channel grows with the grid density.
  • "fenrir": the conditional evidence log p(Y | Z) by Fenrir: one pass without data, then fenrir_loglik.
  • "dalton": log p(Y | Z) by Dalton: a pass with and one without data, then conditional_loglik. With one-shot linearizations it differs from Fenrir's value (see ode_filters.inference.evidence).

The passes without data of "fenrir" and "dalton" run on the nodes of the data, data.without_data(), which include any data-only nodes.

With adaptive steps (model.adaptive), the ODE information Z lives on the steps the solver chooses, and "ode" sums over those steps. "fenrir" runs the pass without data with smoother=True and filters the data backwards through its backward conditionals, one per interval between landing points. "dalton" raises: the passes with and without data choose different steps, so their ODE evidences condition on ODE information at different times, and their difference is not log p(Y | Z).

'obs'

Returns:

Type Description
Array | tuple[Array, Array]

A scalar, or (ll_ode, ll_obs) for channel="both". Maximize over theta (or minimize the negative)

Array | tuple[Array, Array]

to fit parameters. jax.jit / jax.grad / jax.vmap over

Array | tuple[Array, Array]

theta are all supported. An adaptive solve that misses a save time

Array | tuple[Array, Array]

(max_steps reached) or has a non-finite evidence returns NaN.

Raises:

Type Description
ValueError

If channel is unknown, if data is None or empty for a channel that needs observations, for invalid measurement times, or for channel="dalton" with adaptive steps.

InferenceProblem

Bases: NamedTuple

Static specification mapping a parameter pytree to solver inputs.

Attributes:

Name Type Description
build Callable[[Any], tuple[Array, Array, BaseODEInformation]]

Callable theta -> (m_0, P_0_sqr, measure) constructing the (differentiable) initial Gaussian and measurement model from the parameters. This is the single problem-specific bridge; everything else is static.

prior BasePrior

Gauss-Markov prior (e.g. IWP).

ts Array

Time grid, shape [K], for which the data are prepared. With adaptive, the save grid of the adaptive solver, which steps between its nodes.

calibration Calibration | CalibrationMode

Diffusion calibration policy or shorthand. Defaults to "none" (fixed diffusion), the recommended setting for parameter inference.

correction Correction | None

Linearization strategy (a Correction); None defaults to EK1. Use e.g. TaylorCorrection(order=0) or IteratedTaylorCorrection() to fit with EK0 / IEKF.

prior_fn Callable[[Any], BasePrior] | None

Optional callable theta -> prior, for fitting the hyperparameters of the prior (diffusion scale, length scale) instead of or in addition to parameters of the vector field. When given it takes precedence over the static prior, and the prior is built inside the traced region so its hyperparameters are differentiated. When None (the default) the static prior is used unchanged.

adaptive AdaptiveSettings | None

None (the default) solves on the fixed grid ts with gaussian_filter. AdaptiveSettings solve with gaussian_filter_adaptive and these settings, with ts as the save grid; the solver also lands on the data times between its nodes. The channel "dalton" is not available on this path.

AdaptiveSettings

Bases: NamedTuple

Options of gaussian_filter_adaptive for marginal_loglik.

In InferenceProblem.adaptive, they make marginal_loglik run gaussian_filter_adaptive with save_at=model.ts. The solver chooses its steps between the nodes of model.ts, lands on each node and on each data time between them, and conditions on the data there. Each field is passed on as the solver's argument of the same name, and the defaults are the solver's. The tolerances set the accuracy of the likelihood.

Attributes:

Name Type Description
atol ArrayLike

Absolute tolerance of the local-error estimate.

rtol ArrayLike

Relative tolerance of the local-error estimate.

h_init ArrayLike | None

First trial step; None is (ts[-1] - ts[0]) / 100.

max_step ArrayLike | None

Upper bound on every step; None leaves the next node of model.ts as the only bound.

controller StepSizeController | None

Step-size controller; None is PIController(order=prior.q).

sigma_in_error SigmaInError

The diffusion in the error estimate, "per_step" or "running_mean".

max_steps int

Cap on the attempts per interval of model.ts. A solve that reaches it fails, and marginal_loglik returns NaN.

Conditional evidence and information criteria

See Selecting hyperparameters from data.

fenrir_loglik

fenrir_loglik(
    data_free: FilterResult, obs_model: ObsModel
) -> Array

log p(Y | Z) by Fenrir: the data filtered backwards through a data-free pass.

The pass conditioned on the ODE information alone defines a backward Markov chain x_n | x_{n+1}. A Kalman filter runs it from the last node to the first and updates on the data where they are present, summing the evidence of each update (Tronarp, Bosch & Hennig 2022, Prop. 3.1). Observation step i of obs_model lives at node i + 1; node 0 has none.

With data-only nodes the pass without data must run on the timeline of obs_model: pass obs_model=obs_model.without_data() to the solver. Its backward conditionals then reach the data-only nodes, while its ODE information is that of the grid.

Parameters:

Name Type Description Default
data_free FilterResult

A FilterResult conditioned on the ODE information only, with backward conditionals: gaussian_filter or affine_filter without data, or with obs_model=obs_model.without_data().

required
obs_model ObsModel

The data, on the result's nodes.

required

Returns:

Type Description
Array

The scalar log p(Y | Z).

Raises:

Type Description
ValueError

If the result conditioned on data already (that would count the data twice), carries no backward conditionals, or obs_model is on another grid.

conditional_loglik

conditional_loglik(
    data: FilterResult, data_free: FilterResult
) -> Array

log p(Y | Z) = log p(Z, Y) - log p(Z) from a pass with and one without data.

On one shared linear-Gaussian model, with both passes affine_filter runs of the same AffineSurrogate, this is exact and equals fenrir_loglik of the data-free pass. With one-shot filters (gaussian_filter) each pass linearizes at its own predictions, so the two terms belong to different linearizations: that difference is Dalton's estimator (Wu & Lysy 2024), which generally differs from Fenrir's.

Parameters:

Name Type Description Default
data FilterResult

A pass conditioned on the ODE information and the data.

required
data_free FilterResult

A pass conditioned on the ODE information only.

required

Returns:

Type Description
Array

The scalar ``data.log_likelihood + data.log_likelihood_obs -

Array

data_free.log_likelihood``.

Raises:

Type Description
ValueError

If data carries no data evidence, or data_free does.

information_criteria

information_criteria(
    m_0: ArrayLike,
    P_0_sqr: ArrayLike,
    prior: JointPrior,
    surrogate: AffineSurrogate,
    ts: ArrayLike,
    obs_model: ObsModel | Sequence[Measurement],
    *,
    P_0_state_sqr: ArrayLike | None = None,
) -> InformationCriteria

Mutual and directed informations of the ODE information and data about U.

At a frozen linearization everything is jointly Gaussian and the means drop out of the informations:

I(U; Z)     = 1/2 [log|Cov(Z)|    - log|Cov(Z | U)|]
I(U; Y, Z)  = 1/2 [log|Cov(Z, Y)| - log|Cov(Z, Y | U)|]
I(U; Y | Z) = I(U; Y, Z) - I(U; Z)
D           = 1/2 sum_n [log|S^obs_n| - log|S^obs_n given U|]

Each log-determinant is a sum of innovation log-determinants along a filter pass, so four passes give them all: the joint model and the state block alone (given U), each without and with the data. The innovation covariances do not depend on the means, so each pass carries only a square-root factor of the covariance, with one QR per prediction and per update. The updated factors stay untriangularized until the next prediction, so the gradients are finite also when the ODE information has no noise, which makes every updated covariance singular. This is valid because the joint prior's block-diagonal transition makes the state block evolve independently given U, and a frozen surrogate is affine in U, so conditioning on U only shifts the residual means. The same holds for the dependence of the data on U, which is why the data rows can be restricted to the state's columns.

Parameters:

Name Type Description Default
m_0 ArrayLike

Initial mean of the joint state.

required
P_0_sqr ArrayLike

Square root of the joint initial covariance.

required
prior JointPrior

The JointPrior of state and input.

required
surrogate AffineSurrogate

The frozen linearization (one affine model per step of ts).

required
ts ArrayLike

Time grid.

required
obs_model ObsModel | Sequence[Measurement]

The data, as a sequence of Measurement objects, which are converted with prepare_observations(obs_model, prior.E0_state, ts), or as an ObsModel for the same grid. With data-only nodes the passes with the data run over the timeline, with the ODE information at the grid nodes only, as in affine_filter.

required
P_0_state_sqr ArrayLike | None

Square root of the state block's initial covariance given the input, any factor F with F.T @ F the covariance, also one with more rows than columns. Defaults to the Schur complement of P_0 (conditional_state_cov_sqr).

None

Returns:

Type Description
InformationCriteria

The InformationCriteria.

Raises:

Type Description
TypeError

If prior is not a JointPrior, or if measurement times are traced.

ValueError

If the shapes of the surrogate, the data or the initial law do not match the prior, if obs_model was built for another grid, if it is an empty sequence, or for invalid measurement times.

InformationCriteria

Bases: NamedTuple

Information about a hidden input U (in nats), at a frozen linearization.

Attributes:

Name Type Description
I_UZ Array

I(U; Z), what the ODE information says about the input.

I_UY_given_Z Array

I(U; Y | Z), what the data add to it.

D Array

sum_n I(U; y_n | z_<=n, y_<n), the directed information of the data about the input, as the filter sees it.

Diagnostics and predictives

Under a consistent model the whitened data innovations of a filter pass (result.mz_obs, result.Pz_obs_sqr) are independent standard normal.

whitened_residuals

whitened_residuals(
    mz: ArrayLike, Pz_sqr: ArrayLike
) -> Array

Whitened innovations L^-1 mz per step, with L the Cholesky factor.

A square-root factor is unique only up to the signs of its rows, and the QR decompositions that produce Pz_sqr leave them arbitrary, so Pz_sqr^-T mz would flip the sign of a component from step to step. The factor is therefore taken with a non-negative diagonal (L = Pz_sqr.T with its columns' signs fixed). This makes the residuals comparable across steps, as residual_autocorrelation requires.

Parameters:

Name Type Description Default
mz ArrayLike

Innovation means, shape [N, k] (e.g. result.mz_obs).

required
Pz_sqr ArrayLike

Their square-root covariances, shape [N, k, k].

required

Returns:

Type Description
Array

Shape [N, k]; independent standard normal under a consistent model.

Array

Rows without data (zero mean, unit variance in mz_obs) are zero.

nis

nis(mz: ArrayLike, Pz_sqr: ArrayLike) -> Array

Normalized innovation squared per step, mz.T Pz^-1 mz.

Chi-squared with k degrees of freedom under a consistent model (k the number of rows with data at that step; rows without data contribute zero).

Returns:

Type Description
Array

Shape [N].

residual_autocorrelation

residual_autocorrelation(
    whitened: ArrayLike, max_lag: int
) -> Array

Sample autocorrelation of whitened residuals, per component.

Parameters:

Name Type Description Default
whitened ArrayLike

Whitened residuals, shape [N, k] (whitened_residuals).

required
max_lag int

Largest lag.

required

Returns:

Type Description
Array

Shape [max_lag, k]: lags 1..max_lag. Under a consistent model the

Array

entries are close to zero, within about 2 / sqrt(N).

observation_predictive

observation_predictive(
    marginals: Gaussian,
    H: ArrayLike,
    R_sqr: ArrayLike | None = None,
) -> Gaussian

Predictive distribution of linear observations y = H x + v.

Parameters:

Name Type Description Default
marginals Gaussian

State marginals, stacked (e.g. rts_smoother(result) for the posterior predictive, or interpolate(...) at any times).

required
H ArrayLike

Observation matrix, shape [k, D].

required
R_sqr ArrayLike | None

Square root of the observation noise, [k, k]; None for the noise-free prediction of H x.

None

Returns:

Type Description
Gaussian

The predictive Gaussian per marginal: means [M, k], square-root

Gaussian

covariances [M, k, k].

Parameters

Real

Real(value: Any)

Bases: AbstractParameter

An unconstrained real parameter (identity transform).

Attributes:

Name Type Description
value Array

The (unconstrained) value, used as-is.

unwrap

unwrap() -> Array

Return the value unchanged.

PositiveReal

PositiveReal(value: Any)

Bases: AbstractParameter

A strictly-positive parameter, stored via the softplus bijection.

Construct it with the constrained (positive) value; it stores the corresponding unconstrained value and returns the positive value from unwrap.

Attributes:

Name Type Description
unconstrained Array

The stored unconstrained value (softplus_inv(value)).

unwrap

unwrap() -> Array

Return softplus(unconstrained).

NonNegativeReal

NonNegativeReal(value: Any)

Bases: AbstractParameter

A non-negative parameter (e.g. a noise floor), via softplus.

Like PositiveReal, but construction at exactly zero is allowed: it starts at the smallest value softplus represents usefully (about 2e-9), so the optimizer can move the parameter away from the boundary or towards it.

Attributes:

Name Type Description
unconstrained Array

The stored unconstrained value.

unwrap

unwrap() -> Array

Return softplus(unconstrained).

AbstractParameter

Bases: Module

A parameter stored in unconstrained space.

Subclasses hold the raw (unconstrained) value as their array leaf and map it to the constrained value in unwrap. Being an equinox.Module they are registered pytrees, so the unconstrained leaf is what jax.grad and Optax see.

unwrap abstractmethod

unwrap() -> Array

Return the constrained value.

unwrap

unwrap(tree: Any) -> Any

Replace every AbstractParameter in a pytree with its value.

Identity on leaves that are not AbstractParameter, so it is safe to call on any theta (plain arrays pass through unchanged).