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 |
init_fn |
Callable
|
Callable |
prior |
BasePrior
|
Gauss-Markov prior (e.g. |
ts |
tuple[float, ...]
|
Time grid, shape |
ode_params |
Any
|
The parameters |
calibration |
Calibration | CalibrationMode
|
Diffusion calibration policy or shorthand (default |
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 |
required |
data
|
ObsModel | Sequence[Measurement]
|
Observations as an |
required |
optim
|
Any
|
An Optax |
required |
steps
|
int
|
Number of optimization steps. |
200
|
Returns:
| Type | Description |
|---|---|
ODEFilter
|
Tuple |
Array
|
log-likelihood (shape |
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. |
required |
theta0
|
Any
|
Initial parameters (a pytree of arrays). |
required |
method
|
str
|
A gradient-based |
'L-BFGS-B'
|
**options
|
Any
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
SciPy's |
Raises:
| Type | Description |
|---|---|
ImportError
|
If SciPy is not installed ( |
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 |
required |
data
|
ObsModel | Sequence[Measurement] | None
|
Observations as an |
required |
model
|
InferenceProblem
|
Static |
required |
channel
|
str
|
Which evidence channel to return.
The passes without data of With adaptive steps ( |
'obs'
|
Returns:
| Type | Description |
|---|---|
Array | tuple[Array, Array]
|
A scalar, or |
Array | tuple[Array, Array]
|
to fit parameters. |
Array | tuple[Array, Array]
|
|
Array | tuple[Array, Array]
|
( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
InferenceProblem
¶
Bases: NamedTuple
Static specification mapping a parameter pytree to solver inputs.
Attributes:
| Name | Type | Description |
|---|---|---|
build |
Callable[[Any], tuple[Array, Array, BaseODEInformation]]
|
Callable |
prior |
BasePrior
|
Gauss-Markov prior (e.g. |
ts |
Array
|
Time grid, shape |
calibration |
Calibration | CalibrationMode
|
Diffusion calibration policy or shorthand. Defaults to
|
correction |
Correction | None
|
Linearization strategy (a |
prior_fn |
Callable[[Any], BasePrior] | None
|
Optional callable |
adaptive |
AdaptiveSettings | None
|
|
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; |
max_step |
ArrayLike | None
|
Upper bound on every step; |
controller |
StepSizeController | None
|
Step-size controller; |
sigma_in_error |
SigmaInError
|
The diffusion in the error estimate, |
max_steps |
int
|
Cap on the attempts per interval of |
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 |
required |
obs_model
|
ObsModel
|
The data, on the result's nodes. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
The scalar |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the result conditioned on data already (that would count
the data twice), carries no backward conditionals, or |
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 |
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 |
required |
surrogate
|
AffineSurrogate
|
The frozen linearization (one affine model per step of
|
required |
ts
|
ArrayLike
|
Time grid. |
required |
obs_model
|
ObsModel | Sequence[Measurement]
|
The data, as a sequence of |
required |
P_0_state_sqr
|
ArrayLike | None
|
Square root of the state block's initial covariance given
the input, any factor |
None
|
Returns:
| Type | Description |
|---|---|
InformationCriteria
|
The |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the shapes of the surrogate, the data or the initial law
do not match the prior, if |
InformationCriteria
¶
Bases: NamedTuple
Information about a hidden input U (in nats), at a frozen linearization.
Attributes:
| Name | Type | Description |
|---|---|---|
I_UZ |
Array
|
|
I_UY_given_Z |
Array
|
|
D |
Array
|
|
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 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 |
required |
Pz_sqr
|
ArrayLike
|
Their square-root covariances, shape |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Shape |
Array
|
Rows without data (zero mean, unit variance in |
nis
¶
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 |
residual_autocorrelation
¶
Sample autocorrelation of whitened residuals, per component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
whitened
|
ArrayLike
|
Whitened residuals, shape |
required |
max_lag
|
int
|
Largest lag. |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Shape |
Array
|
entries are close to zero, within about |
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. |
required |
H
|
ArrayLike
|
Observation matrix, shape |
required |
R_sqr
|
ArrayLike | None
|
Square root of the observation noise, |
None
|
Returns:
| Type | Description |
|---|---|
Gaussian
|
The predictive |
Gaussian
|
covariances |
Parameters¶
Real
¶
Bases: AbstractParameter
An unconstrained real parameter (identity transform).
Attributes:
| Name | Type | Description |
|---|---|---|
value |
Array
|
The (unconstrained) value, used as-is. |
PositiveReal
¶
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 ( |
NonNegativeReal
¶
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. |
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
¶
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).