Costs, Priors & Solvers¶
The functional core under the model classes: pure cost functions that score a candidate state against observations and prior, prior modules that supply the regularisation term, and the inner-loop solver functions that drive the 4DVarNet iteration. The model classes are thin, stateful-looking wrappers over these pieces — drop down to this layer when building custom methods or instrumenting the optimisation.
Cost functions¶
The variational cost \(J(x) = J_\text{obs}(x) + J_\text{prior}(x)\) and its
gradient, with the observation and prior terms also available separately
(decomposed_loss returns them unsummed for logging). The _1d / _2d
suffixes match the Batch1D / Batch2D carriers. See
3DVar and
strong-constraint 4DVar for the math each term
implements.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
variational_cost
¶
variational_cost(
x: Float[Array, ...],
batch: Batch1D,
prior_fn: Callable[..., Any],
alpha_obs: float = 0.5,
alpha_prior: float = 0.5,
) -> Float[Array, ""]
Compute the variational cost \(U(x)\).
with \(J_o = \operatorname{mean}\big((m \odot (x - y))^2\big)\) and \(J_p = \operatorname{mean}\big((x - \varphi(x))^2\big)\).
Algorithm
- Form the masked departure \(m \odot (x - y)\) from the batch.
- Form the prior departure \(x - \varphi(x)\) with
prior_fn. - Return the weighted sum of the two mean squares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Array, ...]
|
Current state estimate. |
required |
batch
|
Batch1D
|
Observed data batch with |
required |
prior_fn
|
Callable[..., Any]
|
Callable |
required |
alpha_obs
|
float
|
Weight for the observation term (default |
0.5
|
alpha_prior
|
float
|
Weight for the prior term (default |
0.5
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar cost value. |
Examples:
With the trivial IdentityPrior the
prior term vanishes, leaving the weighted observation MSE.
>>> import jax.numpy as jnp, vardax
>>> batch = vardax.Batch1D(input=jnp.zeros((1, 2, 4)), mask=jnp.ones((1, 2, 4)))
>>> x = jnp.ones((1, 2, 4))
>>> float(vardax.variational_cost(x, batch, vardax.IdentityPrior()))
0.5
Setting alpha_obs=0 removes the observation term.
>>> cost = vardax.variational_cost(
... x, batch, vardax.IdentityPrior(), alpha_obs=0.0
... )
>>> float(cost)
0.0
The gradient has the shape of the state.
>>> import jax
>>> g = jax.grad(vardax.variational_cost)(x, batch, vardax.IdentityPrior())
>>> g.shape
(1, 2, 4)
Source code in src/vardax/_src/costs.py
variational_cost_grad
¶
variational_cost_grad(
x: Float[Array, ...],
batch: Batch1D,
prior_fn: Callable[..., Any],
alpha_obs: float = 0.5,
alpha_prior: float = 0.5,
) -> Float[Array, ...]
Gradient of variational_cost w.r.t. x.
Algorithm
- Differentiate
variational_costwith respect to its first argumentx. - Return the resulting array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Array, ...]
|
Current state estimate. |
required |
batch
|
Batch1D
|
Observed data batch. |
required |
prior_fn
|
Callable[..., Any]
|
Callable |
required |
alpha_obs
|
float
|
Weight for the observation term. |
0.5
|
alpha_prior
|
float
|
Weight for the prior term. |
0.5
|
Returns:
| Type | Description |
|---|---|
Float[Array, ...]
|
The gradient \(\nabla_x U(x)\), shaped like |
Examples:
>>> import jax.numpy as jnp, vardax
>>> batch = vardax.Batch1D(input=jnp.zeros((1, 2, 4)), mask=jnp.ones((1, 2, 4)))
>>> x = jnp.ones((1, 2, 4))
>>> g = vardax.variational_cost_grad(x, batch, vardax.IdentityPrior())
>>> g.shape
(1, 2, 4)
It matches jax.grad of the cost.
>>> import jax
>>> ref = jax.grad(vardax.variational_cost)(x, batch, vardax.IdentityPrior())
>>> bool(jnp.allclose(g, ref))
True
Source code in src/vardax/_src/costs.py
obs_cost_1d
¶
obs_cost_1d(
state: Float[Array, "B T N"],
obs: Float[Array, "B T N"],
mask: Float[Array, "B T N"],
nan_to_num: bool = False,
) -> Float[Array, ""]
Observation cost for 1-D data.
Computes the masked mean-squared error between the state and observations:
with state \(x\), observations \(y\) and observation mask \(m\) (1 where
observed, 0 elsewhere). The mean runs over all elements, so it is
the masked squared error divided by the total element count, not by
the number of observed locations.
Algorithm
- Optionally replace
NaNentries ofobsby zero. - Form the masked departure \(m \odot (x - y)\).
- Return the mean of its square.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Float[Array, 'B T N']
|
Current state estimate \(x\). |
required |
obs
|
Float[Array, 'B T N']
|
Observations \(y\). |
required |
mask
|
Float[Array, 'B T N']
|
Binary observation mask \(m\).
A value of |
required |
nan_to_num
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar observation cost. |
Examples:
>>> import jax.numpy as jnp
>>> from vardax import obs_cost_1d
>>> state = jnp.ones((1, 1, 4))
>>> obs = jnp.zeros((1, 1, 4))
>>> mask = jnp.ones((1, 1, 4))
>>> float(obs_cost_1d(state, obs, mask))
1.0
Masked-out locations do not contribute, even when the observation
there is NaN (with nan_to_num=True).
>>> obs = jnp.array([[[0.0, jnp.nan, 0.0, 0.0]]])
>>> mask = jnp.array([[[1.0, 0.0, 1.0, 1.0]]])
>>> float(obs_cost_1d(state, obs, mask, nan_to_num=True))
0.75
The cost is differentiable in the state.
Source code in src/vardax/_src/costs.py
obs_cost_2d
¶
obs_cost_2d(
state: Float[Array, "B T H W"],
obs: Float[Array, "B T H W"],
mask: Float[Array, "B T H W"],
nan_to_num: bool = False,
) -> Float[Array, ""]
Observation cost for 2-D data.
Computes the masked mean-squared error between the state and observations:
with state \(x\), observations \(y\) and observation mask \(m\) (1 where
observed, 0 elsewhere), as in obs_cost_1d.
Algorithm
- Optionally replace
NaNentries ofobsby zero. - Form the masked departure \(m \odot (x - y)\).
- Return the mean of its square.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Float[Array, 'B T H W']
|
Current state estimate \(x\). |
required |
obs
|
Float[Array, 'B T H W']
|
Observations \(y\). |
required |
mask
|
Float[Array, 'B T H W']
|
Binary observation mask \(m\). |
required |
nan_to_num
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar observation cost. |
Examples:
>>> import jax.numpy as jnp
>>> from vardax import obs_cost_2d
>>> state = jnp.ones((1, 1, 2, 2))
>>> obs = jnp.zeros((1, 1, 2, 2))
>>> float(obs_cost_2d(state, obs, jnp.ones((1, 1, 2, 2))))
1.0
With nothing observed the cost is zero.
Source code in src/vardax/_src/costs.py
prior_cost
¶
prior_cost(
state: Float[Array, ...],
prior_reconstruction: Float[Array, ...],
) -> Float[Array, ""]
Prior cost based on learned autoencoder reconstruction.
Computes the mean-squared error between the state and its reconstruction through the learned prior (autoencoder):
Algorithm
- Take the reconstruction \(\varphi(x)\) of the state.
- Return the mean squared difference \(x - \varphi(x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Float[Array, ...]
|
Current state estimate \(x\). |
required |
prior_reconstruction
|
Float[Array, ...]
|
Autoencoder reconstruction \(\varphi(x)\) of the state. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar prior cost. |
Examples:
>>> import jax.numpy as jnp
>>> from vardax import prior_cost
>>> x = jnp.ones((2, 3))
>>> float(prior_cost(x, x))
0.0
A reconstruction that is off by two everywhere costs four.
Source code in src/vardax/_src/costs.py
decomposed_loss
¶
decomposed_loss(
x: Float[Array, ...],
batch: Batch1D,
prior_fn: Callable[..., Any],
alpha_obs: float = 0.5,
alpha_prior: float = 0.5,
) -> dict[str, Float[Array, ""]]
Compute the decomposed variational loss.
Returns individual observation and prior components alongside the
total, matching the ModelLoss pattern from the legacy codebase.
with \(J_o = \operatorname{mean}\big((m \odot (x - y))^2\big)\) and
\(J_p = \operatorname{mean}\big((x - \varphi(x))^2\big)\) as in
variational_cost.
Algorithm
- Compute the weighted observation term.
- Compute the weighted prior term.
- Return both and their sum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Array, ...]
|
Current state estimate. |
required |
batch
|
Batch1D
|
Observed data batch. |
required |
prior_fn
|
Callable[..., Any]
|
Callable |
required |
alpha_obs
|
float
|
Weight for the observation term. |
0.5
|
alpha_prior
|
float
|
Weight for the prior term. |
0.5
|
Returns:
| Type | Description |
|---|---|
dict[str, Float[Array, '']]
|
Dictionary with keys |
Examples:
>>> import jax.numpy as jnp, vardax
>>> batch = vardax.Batch1D(input=jnp.zeros((1, 2, 4)), mask=jnp.ones((1, 2, 4)))
>>> x = jnp.ones((1, 2, 4))
>>> parts = vardax.decomposed_loss(x, batch, vardax.IdentityPrior())
>>> sorted(parts)
['obs', 'prior', 'total']
>>> float(parts["obs"]), float(parts["prior"])
(0.5, 0.0)
The total equals variational_cost.
>>> total = vardax.variational_cost(x, batch, vardax.IdentityPrior())
>>> bool(jnp.allclose(parts["total"], total))
True
Source code in src/vardax/_src/costs.py
strong_variational_cost
¶
strong_variational_cost(
initial_state: Float[Array, ...],
ts: Float[Array, " T"],
batch: Batch1D,
forward_fn: Callable[..., Any],
*,
background: Float[Array, ...] | None = None,
alpha_obs: float = 0.5,
alpha_bg: float = 0.5,
nan_to_num: bool = False,
) -> Float[Array, ""]
Strong-constraint variational cost \(U(x_0)\).
with \(J_o = \operatorname{mean}\big((m \odot (\varphi(x_0) - y))^2\big)\) and \(J_b = \operatorname{mean}\big((x_0 - x_b)^2\big)\).
The dynamical model is enforced as a hard constraint: the initial
state initial_state is propagated through the dynamics
forward_fn(initial_state, ts)
and only the resulting trajectory is scored against the observations.
This differs from the weak / soft-constraint
variational_cost, where the model appears
as an additive prior penalty and the whole state field is free.
Ported from mfourdvar's StrongVarCost, adapted to a functional
form that mirrors variational_cost.
Algorithm
- Propagate \(x_0\) through
forward_fn(initial_state, ts)to get the trajectory \(\varphi(x_0)\). - Score the trajectory against the observations with the mask.
- Add the background term, defaulting to zero when
backgroundis omitted. - Return the weighted sum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
Float[Array, ...]
|
Initial state \(x_0\) (the control variable), whatever
|
required |
ts
|
Float[Array, ' T']
|
Time coordinates \(t\) passed to |
required |
batch
|
Batch1D
|
Observed data batch supplying |
required |
forward_fn
|
Callable[..., Any]
|
Callable |
required |
background
|
Float[Array, ...] | None
|
Background state for the background term. Defaults to
|
None
|
alpha_obs
|
float
|
Weight for the observation term (default |
0.5
|
alpha_bg
|
float
|
Weight for the background term (default |
0.5
|
nan_to_num
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar strong-constraint variational cost. |
Examples:
A persistence model repeats the initial state over the window.
>>> import jax.numpy as jnp, vardax
>>> ts = jnp.arange(3.0)
>>> forward = lambda x0, ts: jnp.broadcast_to(x0[:, None], (1, 3, 4))
>>> batch = vardax.Batch1D(input=jnp.zeros((1, 3, 4)), mask=jnp.ones((1, 3, 4)))
>>> x0 = jnp.ones((1, 4))
>>> float(vardax.strong_variational_cost(x0, ts, batch, forward))
0.5
A background away from initial_state adds the background term.
>>> cost = vardax.strong_variational_cost(
... x0, ts, batch, forward, background=x0 - 1.0
... )
>>> float(cost)
1.0
The cost is differentiable in the control.
>>> import jax
>>> g = jax.grad(vardax.strong_variational_cost)(x0, ts, batch, forward)
>>> g.shape
(1, 4)
Source code in src/vardax/_src/costs.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | |
background_cost
¶
background_cost(
initial_state: Float[Array, ...],
background: Float[Array, ...],
) -> Float[Array, ""]
Background cost \(\operatorname{mean}\big((x_0 - x_b)^2\big)\).
Penalises departure of the initial state \(x_0\) (the control variable in strong-constraint 4DVar) from the background / first guess \(x_b\). Uses the same mean-squared convention as the other functional costs in this module.
Algorithm
- Form the departure \(x_0 - x_b\).
- Return the mean of its square.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
initial_state
|
Float[Array, ...]
|
Initial state estimate \(x_0\). |
required |
background
|
Float[Array, ...]
|
Background state \(x_b\). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar background cost. |
Examples:
>>> import jax.numpy as jnp
>>> from vardax import background_cost
>>> x0 = jnp.ones(4)
>>> float(background_cost(x0, x0))
0.0
A uniform departure of 0.5 costs a quarter.
Source code in src/vardax/_src/costs.py
Physics residual penalty¶
ResidualPenalty adds a PDE as a weak constraint on a continuous field
(a neural field, or any differentiable callable of one point): the
residual \(\mathcal N[f]\) is evaluated by autodiff at collocation points,
fixed or redrawn from a key on every call, and scored as
\(\frac{\lambda}{2 N_c}\sum_j \lVert \mathcal N[f](c_j) \rVert^2\).
Residuals are plain callables (field, s) -> (R,) built on
geonnax.diffops; vardax ships two references in vardax.examples,
2-D advection–diffusion and 2-D incompressible Navier–Stokes in
vorticity form (the field gives the streamfunction \(\psi\), with
\(u = \nabla^\perp\psi\) and \(\omega = \Delta\psi\)).
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
ResidualPenalty
¶
Bases: Module
PDE residual of a continuous field at collocation points, as a cost.
For a field \(f_\theta\) (a callable of one point, e.g. a neural field),
a PDE operator \(\mathcal N\) supplied as residual_fn and collocation
points \(c_1, \dots, c_{N_c}\),
Added to an observation cost it imposes the physics as a weak
constraint, without a time-stepping model. Residuals are callables built
on geonnax.diffops (see vardax.examples for advection–diffusion and
vorticity-form Navier–Stokes); vardax does not import a PDE library.
With a sampler, the points are redrawn from a key on every call. If
each point is drawn from a distribution \(p\), the resampled cost is an
unbiased estimate of
\(\tfrac{\lambda}{2}\,\mathbb E_{c \sim p} \lVert \mathcal N[f_\theta](c) \rVert^2\),
so its gradient is a stochastic gradient of that expected penalty.
The field must be smooth enough for the derivatives the residual takes
(twice differentiable for advection–diffusion, four times for the
streamfunction form of Navier–Stokes) at every collocation point. A raw
jnp.linalg.norm or jnp.sqrt of a quantity that vanishes at a point
gives NaN gradients there; guard it with the double-where idiom
(jnp.where(sq > 0, jnp.sqrt(jnp.where(sq > 0, sq, 1.0)), 0.0)).
residual_fn and sampler are static fields, so they must be
hashable (functions and closures are); collocation and weight
are array leaves, so changing the weight (e.g. annealing \(\lambda\))
does not recompile a jitted cost.
Algorithm
- Obtain the points \(c_j\), from
collocationor by callingsampler(key). - Evaluate the residual \(\mathcal N[f_\theta](c_j)\) at every point.
- Return \(\lambda / (2 N_c)\) times the sum of squared residuals.
Raises:
| Type | Description |
|---|---|
MissingInputError
|
If neither |
ShapeError
|
If |
ConfigurationError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
residual_fn |
Callable[..., Float[Array, ' R']]
|
|
collocation |
Float[Array, 'N D'] | None
|
Fixed collocation points of shape |
weight |
Float[Array, '']
|
Penalty weight \(\lambda \ge 0\), stored as a 0-d array. |
sampler |
Callable[[PRNGKeyArray], Float[Array, 'N D']] | None
|
Optional |
Examples:
A residual that is the field itself gives \(J = \tfrac{\lambda}{2} \lVert f \rVert^2\) for a constant field:
>>> import jax.numpy as jnp
>>> import vardax
>>> pen = vardax.ResidualPenalty(
... residual_fn=lambda f, s: f(s),
... collocation=jnp.zeros((5, 3)),
... weight=0.5,
... )
>>> float(pen(lambda s: jnp.array([1.0, 2.0])))
1.25
With a sampler, pass a key on every call:
>>> import jax
>>> pen = vardax.ResidualPenalty(
... residual_fn=lambda f, s: f(s),
... collocation=None,
... weight=1.0,
... sampler=lambda key: jax.random.uniform(key, (64, 3)),
... )
>>> float(pen(lambda s: s[:1], key=jax.random.PRNGKey(0))) > 0
True
A penalty with neither collocation points nor a sampler is rejected.
>>> vardax.ResidualPenalty(
... residual_fn=lambda f, s: f(s), collocation=None, weight=1.0
... )
Traceback (most recent call last):
...
MissingInputError: ResidualPenalty needs collocation points or a sampler.
Source code in src/vardax/_src/costs.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | |
Public vardax.examples API surface — demo helpers and reference residuals.
Re-exports from vardax._src.examples (the notebook training loop, not
part of the library API proper; see that module's docstring) and from
vardax._src.utils.residuals (reference PDE residuals for
ResidualPenalty).
advection_diffusion_2d
¶
advection_diffusion_2d(
velocity: tuple[float, float] | Float[Array, " 2"],
diffusivity: float,
) -> Residual
Residual of 2-D advection–diffusion with constant coefficients.
For a scalar tracer \(u(t, x, y)\) advected by a constant velocity \(c = (c_x, c_y)\) and diffused with diffusivity \(\kappa \ge 0\),
with \(\nabla\) and \(\Delta\) acting on \((x, y)\) only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
velocity
|
tuple[float, float] | Float[Array, ' 2']
|
Constant advecting velocity \((c_x, c_y)\). |
required |
diffusivity
|
float
|
Diffusivity \(\kappa \ge 0\). |
required |
The field must be twice differentiable in \((x, y)\) and once in \(t\) at
every collocation point; a raw jnp.sqrt or jnp.linalg.norm that
vanishes there gives NaN derivatives, so guard it with the double-where
idiom.
Returns:
| Type | Description |
|---|---|
Residual
|
|
Residual
|
tracer is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
A Gaussian bump translated by \(c\) and spread by diffusion solves the equation exactly:
>>> import jax.numpy as jnp
>>> from vardax.examples import advection_diffusion_2d
>>> c, kappa = jnp.array([1.0, 0.5]), 0.1
>>> def bump(s):
... var = 0.04 + 2 * kappa * s[0]
... r2 = jnp.sum((s[1:] - c * s[0]) ** 2)
... return jnp.array([0.04 / var * jnp.exp(-r2 / (2 * var))])
>>> res = advection_diffusion_2d(c, kappa)
>>> r = res(bump, jnp.array([0.3, 0.25, 0.2]))
>>> r.shape, bool(jnp.abs(r[0]) < 1e-4)
((1,), True)
Source code in src/vardax/_src/utils/residuals.py
navier_stokes_vorticity_2d
¶
navier_stokes_vorticity_2d(
viscosity: float,
forcing: Callable[
[Float[Array, " 3"]], Float[Array, ""]
]
| None = None,
) -> Residual
Residual of 2-D incompressible Navier–Stokes in vorticity form.
The field provides the streamfunction \(\psi(t, x, y)\) (its first output); velocity and vorticity are derived from it,
and the residual is the vorticity equation
Deriving \(u\) from \(\psi\) makes the flow divergence-free and the Poisson relation \(\Delta\psi = \omega\) hold exactly, so one residual component is enough. The price is fourth derivatives of the field (\(\Delta\omega = \Delta^2\psi\)), computed by nested automatic differentiation; for a field that returns \((\omega, \psi)\) separately, add \(\Delta\psi - \omega\) as a second residual instead.
The streamfunction must be four times differentiable in \((x, y)\) (and
\(\Delta\psi\) once in \(t\)) at every collocation point; a raw jnp.sqrt
or jnp.linalg.norm that vanishes there gives NaN derivatives, so guard
it with the double-where idiom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
viscosity
|
float
|
Kinematic viscosity \(\nu \ge 0\). |
required |
forcing
|
Callable[[Float[Array, ' 3']], Float[Array, '']] | None
|
Optional vorticity forcing \(F(s)\), a scalar function of
|
None
|
Returns:
| Type | Description |
|---|---|
Residual
|
|
Residual
|
streamfunction is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
The decaying Taylor–Green vortex \(\psi = \sin x \sin y\, e^{-2\nu t}\) solves the unforced equation exactly:
>>> import jax.numpy as jnp
>>> from vardax.examples import navier_stokes_vorticity_2d
>>> nu = 0.1
>>> def tg(s):
... return jnp.array(
... [jnp.sin(s[1]) * jnp.sin(s[2]) * jnp.exp(-2 * nu * s[0])]
... )
>>> res = navier_stokes_vorticity_2d(nu)
>>> r = res(tg, jnp.array([0.5, 0.3, 1.1]))
>>> r.shape, bool(jnp.abs(r[0]) < 1e-5)
((1,), True)
Source code in src/vardax/_src/utils/residuals.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
Priors¶
Implementations of the Prior Protocol. IdentityPrior
gives plain Tikhonov regularisation; L63Prior / L96Prior encode Lorenz
dynamics as a model-consistency penalty; the autoencoder priors (MLP,
convolutional, and bilinear variants in 1D, 2D, and 2D-multivariate) are
learned priors that penalise distance from a trained reconstruction
manifold.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
IdentityPrior
¶
Bases: Module
Trivial identity prior: \(\varphi(x) = x\).
Zero parameters. Useful as a pure obs-driven baseline (the prior cost vanishes everywhere) and as a sanity-check building block in the linear-Gaussian agreement tests.
Examples:
>>> import jax.numpy as jnp
>>> from vardax import IdentityPrior
>>> prior = IdentityPrior()
>>> x = jnp.arange(6.0).reshape(1, 2, 3)
>>> bool(jnp.all(prior(x) == x))
True
The prior cost \(\|x - \varphi(x)\|^2\) is therefore zero, for any shape:
It satisfies the Prior protocol:
Source code in src/vardax/_src/priors.py
L63Prior
¶
Bases: Module
Learned prior for the Lorenz-63 system.
A simple MLP autoencoder designed for the 3-dimensional Lorenz-63
attractor, \(\varphi(x) = D(E(x))\). The state is treated as a flat vector of
length 3.
Algorithm
- Encode with a tanh hidden layer and a linear map to the latent code.
- Decode with a tanh hidden layer and a linear map back to the state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_dim
|
int
|
Dimensionality of the latent code. |
3
|
hidden_dim
|
int
|
Hidden layer width. |
32
|
state_dim
|
int
|
Dimensionality of the state vector. |
3
|
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import L63Prior
>>> prior = L63Prior(key=jax.random.PRNGKey(0))
>>> prior(jnp.ones((5, 3))).shape
(5, 3)
The latent and hidden widths are free parameters:
>>> small = L63Prior(latent_dim=2, hidden_dim=4, key=jax.random.PRNGKey(0))
>>> small(jnp.zeros((1, 3))).shape
(1, 3)
Source code in src/vardax/_src/priors.py
L96Prior
¶
Bases: Module
Learned prior for the Lorenz-96 system.
A simple MLP autoencoder designed for the N-dimensional Lorenz-96
attractor, \(\varphi(x) = D(E(x))\). The state is treated as a flat vector of
length N.
Algorithm
- Encode with a tanh hidden layer and a linear map to the latent code.
- Decode with a tanh hidden layer and a linear map back to the state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_dim
|
int
|
Dimensionality of the latent code. |
16
|
hidden_dim
|
int
|
Hidden layer width. |
64
|
state_dim
|
int
|
Dimensionality of the state vector. |
40
|
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import L96Prior
>>> prior = L96Prior(state_dim=8, latent_dim=4, key=jax.random.PRNGKey(0))
>>> prior(jnp.ones((3, 8))).shape
(3, 8)
The defaults target the standard 40-variable system:
Source code in src/vardax/_src/priors.py
MLPAEPrior1D
¶
Bases: Module
MLP autoencoder prior for 1-D data.
A two-layer MLP encoder and decoder around a latent code,
\(\varphi(x) = D(E(x))\), applied to the flattened (T, N) window.
Algorithm
- Flatten each sample over time and space.
- Encode with a ReLU hidden layer and a linear map to the latent code.
- Decode with a ReLU hidden layer and a linear map back, then reshape
to
(T, N).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dim
|
int
|
Spatial size of the input ( |
required |
latent_dim
|
int
|
Dimensionality of the latent code. |
required |
hidden_dim
|
int
|
Hidden layer width. |
64
|
n_time
|
int
|
Number of time steps ( |
1
|
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import MLPAEPrior1D
>>> prior = MLPAEPrior1D(
... state_dim=4,
... latent_dim=2,
... hidden_dim=8,
... n_time=3,
... key=jax.random.PRNGKey(0),
... )
>>> prior(jnp.ones((2, 3, 4))).shape
(2, 3, 4)
A single time step is the default:
>>> flat = MLPAEPrior1D(state_dim=4, latent_dim=2, key=jax.random.PRNGKey(0))
>>> flat(jnp.ones((5, 1, 4))).shape
(5, 1, 4)
Source code in src/vardax/_src/priors.py
ConvAEPrior1D
¶
Bases: Module
Convolutional autoencoder prior for 1-D spatially-structured data.
Uses circular (periodic) padding suitable for systems with periodic boundary conditions such as Lorenz-96, \(\varphi(x) = D(E(x))\) with convolutional \(E\) and \(D\).
Algorithm
- Pad the spatial axis periodically and apply the encoder convolution.
- Apply a ReLU.
- Pad periodically again and apply the decoder convolution back to
n_timechannels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_channels
|
int
|
Number of channels in the latent representation. |
16
|
kernel_size
|
int
|
Convolution kernel size (must be a positive odd integer). |
3
|
n_time
|
int
|
Number of time steps |
1
|
key
|
PRNGKeyArray
|
PRNG key for the convolution weights. |
required |
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If |
ShapeError
|
On call, if the input's time dimension differs from
|
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import ConvAEPrior1D
>>> prior = ConvAEPrior1D(n_time=3, key=jax.random.PRNGKey(0))
>>> prior(jnp.ones((2, 3, 10))).shape
(2, 3, 10)
Periodic padding makes the prior shift-equivariant on the ring:
>>> x = jax.random.normal(jax.random.PRNGKey(1), (1, 3, 10))
>>> shifted = prior(jnp.roll(x, 2, axis=-1))
>>> bool(jnp.allclose(shifted, jnp.roll(prior(x), 2, axis=-1), atol=1e-5))
True
An even kernel is rejected:
>>> ConvAEPrior1D(
... kernel_size=4, key=jax.random.PRNGKey(0)
... )
Traceback (most recent call last):
...
ConfigurationError: kernel_size must be a positive odd integer, got 4.
Source code in src/vardax/_src/priors.py
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
BilinAEPrior1D
¶
Bases: Module
Bilinear autoencoder prior for 1-D data.
The encoder maps the input to a low-dimensional latent code; the decoder reconstructs the original space, \(\varphi(x) = D(E(x))\). The prior cost is \(\|x - \varphi(x)\|^2\).
Algorithm
- Flatten each sample over time and space.
- Encode with the bilinear block \(\mathrm{relu}(Ax) \odot \tanh(Bx)\).
- Decode with a dense layer and reshape to
(T, N).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dim
|
int
|
Spatial size of the input ( |
required |
latent_dim
|
int
|
Dimensionality of the latent code. |
required |
n_time
|
int
|
Number of time steps ( |
1
|
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import BilinAEPrior1D
>>> prior = BilinAEPrior1D(
... state_dim=4, latent_dim=2, n_time=3, key=jax.random.PRNGKey(0)
... )
>>> prior(jnp.ones((2, 3, 4))).shape
(2, 3, 4)
The latent code is low-dimensional, and decoding it is the same as calling the prior:
>>> x = jnp.ones((2, 3, 4))
>>> prior.encode(x).shape
(2, 2)
>>> bool(jnp.allclose(prior.decode(prior.encode(x)), prior(x), atol=1e-6))
True
Used as prior_fn of a solver step, with a pass-through modulator:
>>> import vardax as vdx
>>> batch = vdx.Batch1D(input=x, mask=jnp.ones_like(x))
>>> state = vdx.init_solver_state_1d(batch, hidden_dim=5)
>>> passthrough = lambda grad, state, lstm: (grad, lstm)
>>> vdx.solver_step_1d(state, batch, prior, passthrough).x.shape
(2, 3, 4)
Source code in src/vardax/_src/priors.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
encode
¶
Encode input to latent space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Array, 'B T N']
|
State window to encode. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'B Z']
|
Latent code \(E(x)\) of dimension |
Source code in src/vardax/_src/priors.py
decode
¶
Decode latent code to state space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
Float[Array, 'B Z']
|
Latent code \(z\). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T N']
|
Decoded state window \(D(z)\). |
Source code in src/vardax/_src/priors.py
BilinAEPrior2D
¶
Bases: Module
Bilinear autoencoder prior for 2-D data.
The window is flattened, encoded with the bilinear block \(\mathrm{relu}(Ax) \odot \tanh(Bx)\) and decoded by a dense layer, \(\varphi(x) = D(E(x))\).
Algorithm
- Flatten each sample over time and both spatial axes.
- Encode with the bilinear block.
- Decode with a dense layer and reshape to
(T, H, W).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_dim
|
int
|
Dimensionality of the latent code. |
required |
n_time
|
int
|
Number of time steps ( |
required |
height
|
int
|
Spatial height |
required |
width
|
int
|
Spatial width |
required |
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import BilinAEPrior2D
>>> prior = BilinAEPrior2D(
... latent_dim=2, n_time=3, height=4, width=5, key=jax.random.PRNGKey(0)
... )
>>> prior(jnp.ones((1, 3, 4, 5))).shape
(1, 3, 4, 5)
It is the prior inside FourDVarNet2D:
>>> import vardax as vdx
>>> model = vdx.FourDVarNet2D(
... n_time=3, height=4, width=5, key=jax.random.PRNGKey(0)
... )
>>> type(model.prior).__name__
'BilinAEPrior2D'
Source code in src/vardax/_src/priors.py
BilinAEPrior2DMultivar
¶
Bases: Module
Bilinear autoencoder prior for 2-D multivariate data.
The window is flattened over time, channels and space, encoded with the bilinear block \(\mathrm{relu}(Ax) \odot \tanh(Bx)\) and decoded by a dense layer, \(\varphi(x) = D(E(x))\).
Algorithm
- Flatten each sample over time, channel and both spatial axes.
- Encode with the bilinear block.
- Decode with a dense layer and reshape to
(T, C, H, W).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latent_dim
|
int
|
Dimensionality of the latent code. |
required |
n_time
|
int
|
Number of time steps ( |
required |
n_channels
|
int
|
Number of channels |
required |
height
|
int
|
Spatial height |
required |
width
|
int
|
Spatial width |
required |
key
|
PRNGKeyArray
|
PRNG key for the layer weights. |
required |
Examples:
>>> import jax, jax.numpy as jnp
>>> from vardax import BilinAEPrior2DMultivar
>>> prior = BilinAEPrior2DMultivar(
... latent_dim=2,
... n_time=3,
... n_channels=2,
... height=4,
... width=5,
... key=jax.random.PRNGKey(0),
... )
>>> prior(jnp.ones((1, 3, 2, 4, 5))).shape
(1, 3, 2, 4, 5)
The batch axis is free, so a larger batch works unchanged:
Source code in src/vardax/_src/priors.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |
Dynamical priors¶
ODE-based temporal priors ported from mfourdvar (Decision D18):
DynIncrements scores one-step increments, DynTrajectory scores the
full rollout from the initial state. Both satisfy the
TemporalPrior protocol; bind(ts) adapts either to
the static Prior seam, and as_forward_model(dt)
adapts the wrapped ODE to pipekit_cycle.ForwardModel.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
DynamicalPrior
¶
Bases: Module
Base class for ODE-based dynamical priors.
Wraps a diffrax diffeqsolve around an ODE right-hand side
\(\mathrm{d}x/\mathrm{d}t = f(t, x; \theta)\) with pluggable solver, step-size
controller, and adjoint strategy. The adjoint choice trades memory against
speed for reverse-mode differentiation through the solve (relevant for long
windows).
Concrete subclasses implement __call__ (the integration) and
loss (the dynamical residual). Instantiating DynamicalPrior
directly and calling it raises NotImplementedError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Callable
|
Diffrax-compatible ODE right-hand side |
required |
params
|
PyTree | None
|
Optional default |
None
|
solver
|
Solver | None
|
Diffrax solver (default :class: |
None
|
stepsize
|
StepSizeController | None
|
Diffrax step-size controller. Defaults to an adaptive
:class: |
None
|
adjoint
|
Adjoint | None
|
Diffrax adjoint strategy (default
:class: |
None
|
Examples:
The concrete subclasses share the constructor; the step-size controller follows the solver:
>>> import diffrax as dfx
>>> import vardax as vdx
>>> def decay(t, y, args):
... return -y
>>> type(vdx.DynTrajectory(model=decay).stepsize).__name__
'PIDController'
>>> euler = vdx.DynTrajectory(model=decay, solver=dfx.Euler())
>>> type(euler.stepsize).__name__
'ConstantStepSize'
The base class itself has no integration to run:
>>> import jax.numpy as jnp
>>> vdx.DynamicalPrior(model=decay)(
... jnp.ones(2), jnp.array([0.0, 1.0])
... )
Traceback (most recent call last):
...
NotImplementedError
Source code in src/vardax/_src/priors_dynamical.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
reconstruct
¶
Dynamics-consistent reconstruction of a state sequence.
Returns an array of the same shape as x such that
\(\|x - \mathrm{reconstruct}(x, t_s)\|^2\) is the prior's dynamical residual,
the temporal analogue of the autoencoder reconstruction used by the
static Prior seam (Decision D18).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
State sequence. |
required |
ts
|
Array
|
Time coordinates \(t_s\) of the sequence. |
required |
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The dynamics-consistent sequence, with the shape of |
Source code in src/vardax/_src/priors_dynamical.py
bind
¶
Bind a time grid, yielding a one-argument Prior adapter.
The returned callable satisfies the static
Prior protocol (__call__(x) -> x_prior) by
closing over ts, so a dynamical prior can be used anywhere a
static prior is expected, e.g. as the prior_fn of
variational_cost, turning the prior
term into a weak-constraint dynamical residual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ts
|
Array
|
Time coordinates \(t_s\) to close over. |
required |
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
_BoundTemporalPrior
|
A |
Examples:
>>> import jax.numpy as jnp
>>> from vardax import DynTrajectory, IdentityPrior, Prior
>>> def decay(t, y, args):
... return -y
>>> ts = jnp.linspace(0.0, 0.5, 6)
>>> bound = DynTrajectory(model=decay).bind(ts)
>>> isinstance(bound, Prior)
True
>>> traj = DynTrajectory(model=decay)(jnp.ones(3), ts)
>>> bool(jnp.allclose(bound(traj), traj, atol=1e-4))
True
A sequence that violates the dynamics is pulled back onto the flow, so its reconstruction differs from it:
Source code in src/vardax/_src/priors_dynamical.py
as_forward_model
¶
Adapt this prior's dynamics to pipekit_cycle.ForwardModel.
The returned adapter exposes step(state, dt), dt, and
state_signature, so the wrapped ODE can drive anything that
consumes the pipekit forward-model seam,
StrongFourDVar, pipekit_cycle.DACycle,
etc. (Decisions D8/D18). step integrates the ODE over
\([0, \Delta t]\); the dynamics are therefore treated as autonomous
(time-shift invariant), which holds for the standard testbeds
(Lorenz-63/96) and any RHS that ignores t.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
Default integration step \(\Delta t\) advertised as the adapter's |
required |
Returns:
| Type | Description |
|---|---|
_DynamicalForwardModel
|
A |
Examples:
One step of exponential decay matches the closed form:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> def decay(t, y, args):
... return -y
>>> fwd = vdx.DynTrajectory(model=decay).as_forward_model(0.1)
>>> fwd.dt, fwd.state_signature
(0.1, None)
>>> x = jnp.array([1.0, 2.0])
>>> bool(jnp.allclose(fwd.step(x, 0.1), x * jnp.exp(-0.1), atol=1e-4))
True
A zero step leaves the state alone:
Source code in src/vardax/_src/priors_dynamical.py
DynIncrements
¶
Bases: DynamicalPrior
One-step-increment dynamical prior.
The loss integrates each state a single step forward and compares it to the next observed state, so the dynamics act locally in time:
Algorithm
- Split the time grid into consecutive pairs
\((t_t, t_{t+1})\) with
time_patches. - Propagate every state \(u_t\) one step with the ODE solver, in parallel over \(t\).
- Sum the squared differences to the next states.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Callable
|
Diffrax-compatible ODE right-hand side |
required |
params
|
PyTree | None
|
Optional default |
None
|
solver
|
Solver | None
|
Diffrax solver (default :class: |
None
|
stepsize
|
StepSizeController | None
|
Diffrax step-size controller (adaptive by default for adaptive solvers). |
None
|
adjoint
|
Adjoint | None
|
Diffrax adjoint strategy. |
None
|
Raises:
| Type | Description |
|---|---|
ShapeError
|
From |
Examples:
A consistent trajectory (produced by rolling out the same model) has (near-)zero increment loss.
>>> import jax.numpy as jnp
>>> from vardax import DynIncrements, DynTrajectory
>>> def decay(t, y, args):
... return -y
>>> ts = jnp.linspace(0.0, 0.5, 6)
>>> x0 = jnp.array([1.0, 2.0, -1.0])
>>> traj = DynTrajectory(model=decay)(x0, ts)
>>> bool(DynIncrements(model=decay).loss(traj, ts) < 1e-3)
True
A perturbed trajectory is penalised:
A time grid that does not match the sequence is rejected:
>>> DynIncrements(model=decay).loss(
... traj[:3], ts
... )
Traceback (most recent call last):
...
ShapeError: Size mismatch for DynIncrements.loss: expected ...
Source code in src/vardax/_src/priors_dynamical.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | |
loss
¶
One-step-increment dynamical loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
State sequence whose entries are the sources for the one-step predictions. |
required |
ts
|
Array
|
Time coordinates of the sequence. |
required |
x_gt
|
Array | None
|
Target state sequence. Defaults to |
None
|
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Scalar dynamical residual \(\sum_t \|\varphi(u_t) - u_{t+1}\|^2\). |
Raises:
| Type | Description |
|---|---|
ShapeError
|
If |
Source code in src/vardax/_src/priors_dynamical.py
reconstruct
¶
One-step-increment reconstruction.
reconstruct(x, ts)[t+1] is the one-step propagation
\(\varphi_{\Delta t}(x_t)\) and reconstruct(x, ts)[0] = x[0], so
\(\|x - \text{reconstruct}(x, t_s)\|^2\) equals the increment
residual of loss (the \(t=0\) term vanishes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
State sequence. |
required |
ts
|
Array
|
Time coordinates \(t_s\) of the sequence. |
required |
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The sequence \([x_0, \varphi(x_0), \dots, \varphi(x_{T-2})]\). |
Examples:
The residual of the reconstruction is the increment loss:
>>> import jax.numpy as jnp
>>> from vardax import DynIncrements
>>> def decay(t, y, args):
... return -y
>>> prior = DynIncrements(model=decay)
>>> ts = jnp.linspace(0.0, 0.5, 6)
>>> x = jnp.ones((6, 2)) * jnp.arange(6.0)[:, None]
>>> rec = prior.reconstruct(x, ts)
>>> rec.shape == x.shape, bool(jnp.all(rec[0] == x[0]))
(True, True)
>>> bool(
... jnp.allclose(jnp.sum((x - rec) ** 2), prior.loss(x, ts), rtol=1e-4)
... )
True
Source code in src/vardax/_src/priors_dynamical.py
DynTrajectory
¶
Bases: DynamicalPrior
Full-rollout dynamical prior.
The loss integrates the initial state across the whole window and compares the resulting trajectory to the target sequence, enforcing the dynamics as a global (strong) constraint:
This is the propagation used by strong-constraint 4DVar, see
strong_variational_cost.
Algorithm
- Integrate the ODE from the initial state \(u_0\), saving the state at
every time in
ts. - Sum the squared differences between the saved trajectory and the target sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Callable
|
Diffrax-compatible ODE right-hand side |
required |
params
|
PyTree | None
|
Optional default |
None
|
solver
|
Solver | None
|
Diffrax solver (default :class: |
None
|
stepsize
|
StepSizeController | None
|
Diffrax step-size controller (adaptive by default for adaptive solvers). |
None
|
adjoint
|
Adjoint | None
|
Diffrax adjoint strategy. |
None
|
Examples:
Roll out exponential decay from an initial condition:
>>> import jax.numpy as jnp
>>> from vardax import DynTrajectory
>>> def decay(t, y, args):
... return -y
>>> ts = jnp.linspace(0.0, 0.5, 6)
>>> prior = DynTrajectory(model=decay)
>>> traj = prior(jnp.array([1.0, 2.0]), ts)
>>> traj.shape
(6, 2)
>>> bool(
... jnp.allclose(traj[-1], jnp.array([1.0, 2.0]) * jnp.exp(-0.5), atol=1e-3)
... )
True
A trajectory generated by the model has (near-)zero loss, and a shifted one does not:
>>> bool(prior.loss(traj, ts) < 1e-6)
True
>>> bool(prior.loss(traj + 1.0, ts, x_gt=traj) > 1.0)
True
Through bind it plugs into the static
prior seam:
Source code in src/vardax/_src/priors_dynamical.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | |
loss
¶
Full-trajectory dynamical loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
State sequence; the initial condition |
required |
ts
|
Array
|
Time coordinates of the sequence. |
required |
x_gt
|
Array | None
|
Target trajectory. Defaults to |
None
|
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
Scalar dynamical residual \(\sum_t \|\varphi_t(u_0) - u_t\|^2\). |
Source code in src/vardax/_src/priors_dynamical.py
reconstruct
¶
Full-rollout reconstruction: the trajectory from x[0].
\(\|x - \text{reconstruct}(x, t_s)\|^2\) equals the trajectory
residual of loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Array
|
State sequence; |
required |
ts
|
Array
|
Time coordinates \(t_s\) of the sequence. |
required |
params
|
PyTree | None
|
ODE |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The rolled-out trajectory, same shape as |
Source code in src/vardax/_src/priors_dynamical.py
Reduced bases¶
Control-variable transforms: a ReducedBasis parameterises the analysis
increment in a lower-dimensional space, so the inner solve runs over basis
coefficients rather than grid points. The constructors build the common
families; CompositeBasis concatenates several.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
LinearBasis
¶
Bases: Module
Generic linear reduced basis with a diagonal-\(Q\) prior.
Build via :func:linear_basis (or a family constructor:
:func:vardax.rbf_basis, :func:vardax.fourier_basis,
:func:vardax.wavelet_basis, :func:vardax.eof_basis); direct
instantiation expects the precomputed design_matrix (N, M) matrix,
variance (M,), and the grid output_shape with
prod(output_shape) == N.
Satisfies vardax.protocols.ReducedBasis (operg / prior_inv /
nbasis). Stationary: operg ignores the t argument.
Examples:
A hand-built design matrix with a non-unit prior variance:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> basis = vdx.linear_basis(
... jnp.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]), variance=2.0
... )
>>> basis.operg(0.0, jnp.array([1.0, 2.0])).shape
(3,)
>>> bool(jnp.allclose(basis.prior_inv(jnp.ones(2)), 0.5))
True
An output_shape reshapes the increment onto a grid:
>>> gridded = vdx.linear_basis(jnp.eye(4), output_shape=(2, 2))
>>> gridded.operg(0.0, jnp.ones(4)).shape
(2, 2)
Source code in src/vardax/_src/basis/linear.py
operg
¶
operg(
t: float,
coefficients: Float[Array, " M"],
state: Float[Array, ...] | None = None,
) -> Float[Array, ...]
Apply \(\Phi X\) and return the increment on output_shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float
|
Time; ignored because the basis is stationary. |
required |
coefficients
|
Float[Array, ' M']
|
Coefficient vector. |
required |
state
|
Float[Array, ...] | None
|
Current state; ignored by this basis. |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, ...]
|
State increment \(\Phi X\) reshaped onto |
Source code in src/vardax/_src/basis/linear.py
prior_inv
¶
Apply \(Q^{-1} X\) with diagonal \(Q = \mathrm{diag}(\sigma^2)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coefficients
|
Float[Array, ' M']
|
Coefficient vector. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, ' M']
|
The vector \(X / \sigma^2\). |
Source code in src/vardax/_src/basis/linear.py
CompositeBasis
¶
Bases: Module
Concatenate several reduced bases into one control vector.
Satisfies vardax.protocols.ReducedBasis. nbasis is the sum of
component sizes; operg slices coefficients, applies each component,
sums the per-grid increments; prior_inv slices coefficients and
concatenates the per-component blocks. Components may mix families
(e.g. a broad rbf_basis layer plus a wavelet_basis detail
layer), provided their operg outputs share one grid shape.
Algorithm
- Split \(X\) at the cumulative component sizes (
splits). operg: apply each component to its slice and sum the grid increments.prior_inv: apply each component'sprior_invto its slice and concatenate the blocks.
Examples:
Two linear bases on a 3-point grid, stacked into one control vector:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> b1 = vdx.linear_basis(jnp.eye(3)[:, :2], variance=2.0)
>>> b2 = vdx.linear_basis(jnp.ones((3, 1)), variance=0.5)
>>> basis = vdx.composite_basis(b1, b2)
>>> basis.nbasis
3
>>> basis.operg(0.0, jnp.array([1.0, 2.0, 3.0])).shape
(3,)
The prior is block-diagonal, so prior_inv divides each block by
its own variance:
Source code in src/vardax/_src/basis/composite.py
linear_basis
¶
linear_basis(
design_matrix: Float[ArrayLike, "N M"],
*,
variance: float | Float[ArrayLike, " M"] = 1.0,
output_shape: tuple[int, ...] | None = None,
) -> LinearBasis
Build a LinearBasis from an arbitrary precomputed design matrix.
The escape hatch for basis families without a dedicated constructor:
any design matrix (spherical harmonics, Slepian, Gabor frames,
hand-rolled …) becomes a ReducedBasis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
design_matrix
|
Float[ArrayLike, 'N M']
|
Design matrix \(\Phi\) mapping coefficients to the flattened state. |
required |
variance
|
float | Float[ArrayLike, ' M']
|
Scalar or per-coefficient prior variance. |
1.0
|
output_shape
|
tuple[int, ...] | None
|
Grid shape the increment is reshaped to; must
satisfy |
None
|
Returns:
| Type | Description |
|---|---|
LinearBasis
|
Configured |
Raises:
| Type | Description |
|---|---|
ShapeError
|
If |
ConfigurationError
|
If |
Examples:
Wrap a matrix; the default grid shape is (N,):
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> basis = vdx.linear_basis(jnp.ones((3, 2)))
>>> basis.nbasis, basis.output_shape
(2, (3,))
A mismatched grid shape is rejected:
>>> vdx.linear_basis(
... jnp.ones((3, 2)), output_shape=(2, 2)
... )
Traceback (most recent call last):
...
ShapeError: prod(output_shape)=4 does not match design_matrix rows N=3.
Source code in src/vardax/_src/basis/linear.py
composite_basis
¶
composite_basis(*components: Any) -> CompositeBasis
Build a CompositeBasis from a sequence of ReducedBasis components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*components
|
Any
|
Reduced bases to concatenate, in control-vector order.
Their |
()
|
Returns:
| Type | Description |
|---|---|
CompositeBasis
|
The composite basis, with |
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If no component is given. |
Examples:
Composing two bases and checking the control-vector size:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> a = vdx.linear_basis(jnp.eye(2))
>>> b = vdx.linear_basis(jnp.ones((2, 1)))
>>> vdx.composite_basis(a, b).nbasis
3
An empty call is rejected:
>>> vdx.composite_basis()
Traceback (most recent call last):
...
ConfigurationError: composite_basis requires at least one component.
Source code in src/vardax/_src/basis/composite.py
eof_basis
¶
eof_basis(
data: Float[ArrayLike, "T N"],
n_modes: int,
*,
center: bool = True,
variance: float
| Float[ArrayLike, " M"]
| str = "explained",
output_shape: tuple[int, ...] | None = None,
) -> LinearBasis
Data-driven EOF (PCA) reduced basis from a sample matrix.
The leading n_modes empirical orthogonal functions of data
become the columns of \(\Phi\). With variance="explained" the
prior variance of mode \(a\) is its sample variance
\(\sigma_a^2 / (T - 1)\), so the background term matches the
climatology of the training samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Float[ArrayLike, 'T N']
|
Sample matrix, |
required |
n_modes
|
int
|
Number of leading EOFs to keep. |
required |
center
|
bool
|
Subtract the per-point sample mean before the SVD. |
True
|
variance
|
float | Float[ArrayLike, ' M'] | str
|
|
'explained'
|
output_shape
|
tuple[int, ...] | None
|
Grid shape to reshape increments to; must satisfy
|
None
|
Algorithm
- Optionally subtract the per-point sample mean of
data. - Take the SVD and keep the leading
n_modesright singular vectors as \(\Phi\) with singular values \(\sigma_a\). - Set the prior variance to \(\sigma_a^2 / (T - 1)\) when
variance="explained", otherwise usevariance.
Returns:
| Type | Description |
|---|---|
LinearBasis
|
|
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If |
DataError
|
If |
Examples:
Two leading EOFs of ten snapshots over four grid points:
>>> import jax
>>> import vardax as vdx
>>> data = jax.random.normal(jax.random.PRNGKey(0), (10, 4))
>>> basis = vdx.eof_basis(data, 2)
>>> basis.design_matrix.shape, basis.variance.shape
((4, 2), (2,))
A single snapshot cannot give an explained variance:
>>> vdx.eof_basis(data[:1], 1)
Traceback (most recent call last):
...
DataError: variance="explained" needs at least 2 samples (T >= 2); got T=1.
Source code in src/vardax/_src/basis/constructors.py
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
fourier_basis
¶
fourier_basis(
grid_coords: Sequence[Float[ArrayLike, " _"]],
num_modes: int | tuple[int, ...],
*,
boundary_scale: float = 1.25,
variance: float | Float[ArrayLike, " M"] = 1.0,
spectral_density: Callable[
[Float[Array, " M"]], Float[Array, " M"]
]
| None = None,
) -> LinearBasis
Laplacian-eigenfunction (Dirichlet/HSGP) reduced basis on a box.
Tensor-product sine eigenfunctions of \(-\Delta\) on the (recentred,
slightly enlarged) grid bounding box. Passing spectral_density
evaluates it at the Laplacian eigenvalues \(\lambda_j\) and scales it
by variance — supply a kernel's spectral density to obtain the
Hilbert-space GP (HSGP) approximation of that kernel's prior with
amplitude variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_coords
|
Sequence[Float[ArrayLike, ' _']]
|
Per-axis 1-D coordinate arrays; any dimension
|
required |
num_modes
|
int | tuple[int, ...]
|
Number of 1-D modes per axis; an |
required |
boundary_scale
|
float
|
Domain half-widths are the grid half-spans
times this factor ( |
1.25
|
variance
|
float | Float[ArrayLike, ' M']
|
Scalar or per-coefficient prior variance;
with |
1.0
|
spectral_density
|
Callable[[Float[Array, ' M']], Float[Array, ' M']] | None
|
Optional callable mapping the eigenvalues \(\lambda_j\) to per-mode prior power (HSGP prior). |
None
|
Algorithm
- Flatten the grid, recentre it, and enlarge the half-spans by
boundary_scale. - Build the tensor-product Dirichlet eigenfunctions \(\Phi\) and
eigenvalues \(\lambda\) with
num_modesmodes per axis. - Set the prior variance to
varianceor, with a spectral density, tovariance * spectral_density(lambda).
Returns:
| Type | Description |
|---|---|
LinearBasis
|
|
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If |
GridError
|
If an axis is empty, not 1-D, or has zero span. |
Examples:
Four sine modes on a 1-D grid:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> x = jnp.linspace(0.0, 1.0, 6)
>>> basis = vdx.fourier_basis([x], 4)
>>> basis.nbasis, basis.output_shape
(4, (6,))
A spectral density turns the prior into an HSGP prior with decaying variance:
>>> hsgp = vdx.fourier_basis(
... [x], 4, spectral_density=lambda lam: 1.0 / (1.0 + lam)
... )
>>> bool(hsgp.variance[0] > hsgp.variance[-1])
True
A shrinking boundary scale is rejected:
>>> vdx.fourier_basis(
... [x], 4, boundary_scale=0.5
... )
Traceback (most recent call last):
...
ConfigurationError: boundary_scale must be >= 1, got 0.5.
Source code in src/vardax/_src/basis/constructors.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
rbf_basis
¶
rbf_basis(
grid_coords: Sequence[Float[ArrayLike, " _"]],
centers: Float[ArrayLike, "M d"],
*,
widths: float | Float[ArrayLike, " M"],
kernel: Literal[
"gaussian", "wendland_c2", "wendland_c4"
] = "gaussian",
variance: float | Float[ArrayLike, " M"] = 1.0,
) -> LinearBasis
Placeable radial-basis reduced basis (Gaussian or Wendland kernels).
Column \(a\) of \(\Phi\) is
\(\varphi_a(g) = K(\lVert g - c_a \rVert / \ell_a)\)
evaluated on the flattened grid. kernel="gaussian" reproduces the
MASSH stationary Gaussian-RBF basis; the compactly supported
"wendland_c2" / "wendland_c4" kernels give columns
that are exactly zero past their width.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_coords
|
Sequence[Float[ArrayLike, ' _']]
|
Per-axis 1-D coordinate arrays, e.g. |
required |
centers
|
Float[ArrayLike, 'M d']
|
Atom centre locations \(c_a\), one row per atom with \(d\) columns. |
required |
widths
|
float | Float[ArrayLike, ' M']
|
Scalar or per-atom width \(\ell_a\) (Gaussian length scale, or Wendland support radius); must be positive. |
required |
kernel
|
Literal['gaussian', 'wendland_c2', 'wendland_c4']
|
|
'gaussian'
|
variance
|
float | Float[ArrayLike, ' M']
|
Scalar or per-coefficient prior variance. |
1.0
|
Algorithm
- Flatten the grid axes into points \(g\).
- Evaluate \(K(\lVert g - c_a \rVert / \ell_a)\) for every atom.
- Wrap the design matrix with the diagonal prior
variance.
Returns:
| Type | Description |
|---|---|
LinearBasis
|
|
LinearBasis
|
|
Raises:
| Type | Description |
|---|---|
GridError
|
If an axis of |
ShapeError
|
If |
ConfigurationError
|
If a width is not strictly positive. |
Examples:
Three Gaussian bumps on a 1-D grid of five points:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> x = jnp.linspace(0.0, 1.0, 5)
>>> basis = vdx.rbf_basis([x], jnp.array([[0.0], [0.5], [1.0]]), widths=0.3)
>>> basis.nbasis, basis.output_shape
(3, (5,))
A 2-D grid gives increments on the grid shape:
>>> y = jnp.linspace(0.0, 1.0, 3)
>>> b2 = vdx.rbf_basis([y, x], jnp.array([[0.5, 0.5]]), widths=0.4)
>>> b2.operg(0.0, jnp.ones(1)).shape
(3, 5)
A non-positive width is rejected:
>>> vdx.rbf_basis(
... [x], jnp.zeros((1, 1)), widths=0.0
... )
Traceback (most recent call last):
...
ConfigurationError: widths must be strictly positive; got min=0.0.
Source code in src/vardax/_src/basis/constructors.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
wavelet_basis
¶
wavelet_basis(
grid_shape: int | tuple[int, ...],
*,
wavelet: str = "haar",
levels: int | None = None,
variance: float | Float[ArrayLike, " M"] = 1.0,
) -> LinearBasis
Orthonormal wavelet (DWT) reduced basis on a periodic grid.
Haar / Daubechies synthesis basis: complete (\(M = N\)) and
orthonormal (\(\Phi^\top \Phi = I\)), so it is a multiscale
re-parameterisation of the grid — per-coefficient variance
is the natural place to encode scale-dependent prior power.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid_shape
|
int | tuple[int, ...]
|
|
required |
wavelet
|
str
|
|
'haar'
|
levels
|
int | None
|
Decomposition levels; defaults to the full cascade. |
None
|
variance
|
float | Float[ArrayLike, ' M']
|
Scalar or per-coefficient prior variance. |
1.0
|
Algorithm
- Build the 1-D or 2-D synthesis matrix \(\Phi\) for the chosen wavelet and number of levels.
- Wrap it with the diagonal prior
variance.
Returns:
| Type | Description |
|---|---|
LinearBasis
|
|
LinearBasis
|
|
Raises:
| Type | Description |
|---|---|
UnsupportedInputError
|
If |
Examples:
A Haar basis on 8 points is complete and orthonormal:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> basis = vdx.wavelet_basis(8)
>>> basis.nbasis
8
>>> bool(
... jnp.allclose(
... basis.design_matrix.T @ basis.design_matrix, jnp.eye(8), atol=1e-5
... )
... )
True
A 2-D grid flattens to ny * nx coefficients:
A 3-D grid is rejected:
>>> vdx.wavelet_basis((2, 2, 2))
Traceback (most recent call last):
...
UnsupportedInputError: wavelet_basis supports 1-D or 2-D grids; ...
Source code in src/vardax/_src/basis/constructors.py
State parameterizations¶
Implementations of the StateParameterization protocol,
accepted as parameterization= by ThreeDVar, StrongFourDVar,
WeakFourDVar and ReducedBasisFourDVar: the control becomes any pytree
\(\theta\), the state \(\psi(\theta)\), and \(\mathrm{pen}(\theta)\) replaces
the background term. LinearParameterization adapts any reduced basis
(\(\psi(X) = x_b + \Phi X\)); NeuralFieldParameterization makes the state
a coordinate network on the grid, with weight decay as its penalty.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
LinearParameterization
¶
Bases: Module
Adapter from a ReducedBasis to a parameterization.
\(\psi(X) = x_b + \Phi(t) X\) (with \(t = 0\) when not given) and
\(\mathrm{pen}(X) = \tfrac12 X^\top Q^{-1} X\), so a model built with
parameterization=LinearParameterization(basis, background) minimises the
same cost as ReducedBasisFourDVar(basis=basis) with prior_mean=x_b.
Algorithm
decodeapplies the basis to the coefficients and adds \(x_b\).penaltyapplies \(Q^{-1}\) through the basis.init_controlreturns the zero coefficient vector.
Attributes:
| Name | Type | Description |
|---|---|---|
basis |
Any
|
The |
background |
Float[Array, ...]
|
Background state the increment is added to. |
Examples:
>>> import jax.numpy as jnp, vardax
>>> basis = vardax.linear_basis(jnp.eye(4)[:, :2], variance=2.0)
>>> param = vardax.LinearParameterization(basis, background=jnp.ones(4))
>>> X = param.init_control()
>>> X.shape
(2,)
>>> param.decode(jnp.array([1.0, -1.0]))
Array([2., 0., 1., 1.], dtype=float32)
>>> float(param.penalty(jnp.array([1.0, -1.0]))) # ½ (1 + 1) / 2
0.5
The initial control decodes to the background, whatever the basis.
It satisfies the StateParameterization
protocol.
Source code in src/vardax/_src/parameterization.py
decode
¶
Return the state \(x_b + \Phi(t) X\), shaped like background.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theta
|
Float[Array, ' M']
|
Coefficient vector \(X\). |
required |
t
|
float | None
|
Time at which the basis is evaluated; |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The decoded state. |
Source code in src/vardax/_src/parameterization.py
penalty
¶
Return \(\tfrac12 X^\top Q^{-1} X\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theta
|
Float[Array, ' M']
|
Coefficient vector \(X\). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar penalty. |
Source code in src/vardax/_src/parameterization.py
init_control
¶
Return the zero coefficient vector (the background).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray | None
|
Unused; the start is deterministic. |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The zero coefficient vector \(X = 0\). |
Source code in src/vardax/_src/parameterization.py
NeuralFieldParameterization
¶
Bases: Module
A coordinate network evaluated on the grid as the state.
The control is the array half of the field,
$\theta = $ eqx.filter(field, eqx.is_inexact_array); the rest of
the module (activations, sizes) is fixed. The state is the field at
the grid coordinates,
\(\psi(\theta) = [f_\theta(s_j)]_{j=1}^{N}\), of shape (N,) for a
scalar field and (N, C) for a C-channel one. With a time t
the field is evaluated at \((s_j, t)\), so a space-time field takes
D + 1 inputs. The penalty is weight decay,
\(\mathrm{pen}(\theta) = \tfrac{\alpha}{2} \sum_i \theta_i^2\).
Algorithm
init_controlextracts the array leaves offieldselected byfilter_specas \(\theta\).decoderecombines \(\theta\) with the fixed part offieldand evaluates it at every grid coordinate.penaltyreturns the weight decay of \(\theta\).
Raises:
| Type | Description |
|---|---|
ShapeError
|
If |
ConfigurationError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
field |
Module
|
Single-example network |
coords |
Float[Array, 'N D']
|
Grid coordinates \(s_j\), shape |
weight_decay |
float
|
\(\alpha \ge 0\). |
filter_spec |
Any
|
Which leaves of |
Frozen arrays: geonnax (and equinox) keep fixed arrays — random Fourier
frequencies, precomputed tables — as ordinary leaves read through
jax.lax.stop_gradient. The default filter would make them controls,
and the weight decay would shrink them to zero. Exclude them with
filter_spec, e.g.
eqx.tree_at(lambda f: f.B, jax.tree.map(eqx.is_inexact_array, field), False);
they then stay fixed and outside the penalty.
Examples:
>>> import jax, jax.numpy as jnp, geonnax, vardax
>>> angle = 2 * jnp.pi * jnp.arange(40) / 40
>>> coords = jnp.stack([jnp.cos(angle), jnp.sin(angle)], axis=-1)
>>> siren = geonnax.SIREN.init(2, 16, 1, depth=3, key=jax.random.PRNGKey(0))
>>> param = vardax.NeuralFieldParameterization(siren, coords, 1e-4)
>>> theta = param.init_control()
>>> param.decode(theta).shape
(40,)
>>> bool(param.penalty(theta) > 0)
True
With a time, the field takes D + 1 inputs.
>>> st = geonnax.SIREN.init(3, 16, 1, depth=3, key=jax.random.PRNGKey(1))
>>> st_param = vardax.NeuralFieldParameterization(st, coords, 0.0)
>>> st_param.decode(st_param.init_control(), t=0.5).shape
(40,)
Negative weight decay is rejected.
>>> vardax.NeuralFieldParameterization(
... siren, coords, -1.0
... )
Traceback (most recent call last):
...
ConfigurationError: weight_decay must be >= 0, got -1.0.
Source code in src/vardax/_src/parameterization.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
as_field
¶
The field with parameters theta, as a callable s -> (C,).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theta
|
PyTree[Array]
|
Control, the array half of the field. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Array], Array]
|
The field with |
Source code in src/vardax/_src/parameterization.py
decode
¶
Evaluate the field with parameters theta on the grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theta
|
PyTree[Array]
|
Control, the array half of the field. |
required |
t
|
float | None
|
Time appended to every coordinate; |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The field values at the grid coordinates. |
Source code in src/vardax/_src/parameterization.py
penalty
¶
Return \(\tfrac{\alpha}{2} \lVert \theta \rVert^2\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theta
|
PyTree[Array]
|
Control, the array half of the field. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar weight-decay penalty. |
Source code in src/vardax/_src/parameterization.py
init_control
¶
Return the field's current parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray | None
|
Unused; the start is the field's own parameters. |
None
|
Returns:
| Type | Description |
|---|---|
PyTree[Array]
|
The array half of the field selected by |
Source code in src/vardax/_src/parameterization.py
Minimisers¶
Implementations of the Minimiser protocol, accepted as
minimiser= by ThreeDVar, StrongFourDVar, WeakFourDVar and
ReducedBasisFourDVar. OptimistixMinimiser wraps an optimistix solver
(the models' default, BFGS); OptaxMinimiser runs a first-order optax
optimiser with early stopping for controls too large for BFGS, and
reports the final gradient norm the implicit adjoint relies on. Both
return a MinimiseResult from run.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
OptaxMinimiser
¶
Bases: Module
First-order minimisation with an optax optimiser.
with \(u_k\) the optimizer update from \(g_k\). The loop is a
jax.lax.while_loop (so the whole minimisation is jit-able) and
stops at the first of:
max_stepssteps;- a small gradient, \(\lVert g_k \rVert_2 \le \mathrm{gtol}\);
step_patienceconsecutive small steps, \(\lVert u_k \rVert_2 \le \mathrm{atol} + \mathrm{rtol}\,\lVert \theta_k \rVert_2\) (one small step is not enough: a learning-rate schedule starting at zero gives a zero first update);patienceconsecutive steps whose cost exceeds the lowest cost seen by more than float round-off.
There is deliberately no relative cost-change test: with a large irreducible misfit, \(J_k - J_{k-1}\) rounds to zero in float32 long before \(\theta\) converges. For the same reason a step counts as an improvement when \(J_k \le J_\text{best} + 8\,\varepsilon\,|J_\text{best}|\) (\(\varepsilon\) the machine epsilon of \(J\)), so a cost that is flat to round-off does not exhaust the patience. At a small gradient the loop stops before applying the update, so stored momentum cannot carry a stationary iterate away. It returns the best iterate seen: the lowest cost, with ties within round-off broken by the smaller gradient norm.
With polish, a second loop of at most polish_steps steps of that
optimiser (for example optax.lbfgs()) starts from there, with its
own, tight, tolerances (polish_gtol, polish_rtol,
polish_atol, polish_patience; by default it stops only on
polish_steps or step_patience exactly zero steps). The optimisers are called
with the extra arguments value, grad and value_fn, so
line-search optimisers such as optax.lbfgs work unchanged.
The implicit adjoint used to differentiate through the minimum assumes
\(\nabla J(\theta^\star) = 0\), which a first-order optimiser stopped
early does not guarantee: check
MinimiseResult.grad_norm from run.
Algorithm
- Evaluate the cost and gradient at the iterate \(\theta_k\).
- Stop if the gradient norm is below
gtol; otherwise apply theoptimizerupdate. - Track the best iterate, and count consecutive small steps and steps without improvement.
- Repeat until a stopping rule above fires; keep the best iterate.
- With
polish, repeat steps 1-4 from the best iterate with the polish optimiser and tolerances.
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If a step cap or |
Attributes:
| Name | Type | Description |
|---|---|---|
optimizer |
GradientTransformation
|
The |
max_steps |
int
|
Step cap of the main loop. |
gtol |
float
|
Gradient-norm tolerance of the main loop; |
rtol |
float
|
Relative step tolerance of the main loop. |
atol |
float
|
Absolute step tolerance of the main loop; with |
step_patience |
int
|
Consecutive small steps needed to stop (both loops). |
patience |
int | None
|
Steps without improvement before stopping; |
polish |
GradientTransformation | None
|
Optional second optimiser, run after the main loop. |
polish_steps |
int
|
Step cap of the polish loop. |
polish_gtol |
float
|
As |
polish_rtol |
float
|
As |
polish_atol |
float
|
As |
polish_patience |
int | None
|
As |
Examples:
Adam on \(J(x) = \tfrac12 \lVert x - m \rVert^2\), polished by L-BFGS, reaches the closed-form minimum \(x^\star = m\).
>>> import jax.numpy as jnp, optax, vardax
>>> m = jnp.array([1.0, -2.0, 0.5])
>>> minimiser = vardax.OptaxMinimiser(
... optimizer=optax.adam(1e-1), max_steps=500, polish=optax.lbfgs()
... )
>>> result = minimiser.run(
... lambda x, m: 0.5 * jnp.sum((x - m) ** 2), jnp.zeros(3), m
... )
>>> bool(jnp.allclose(result.value, m, atol=1e-5))
True
>>> bool(result.grad_norm < 1e-5)
True
Calling the minimiser returns only the minimiser, and any pytree is a valid control.
>>> adam = vardax.OptaxMinimiser(optax.adam(1e-1), max_steps=300)
>>> x = adam(
... lambda p, m: 0.5 * jnp.sum((p["a"] - m) ** 2), {"a": jnp.zeros(3)}, m
... )
>>> bool(jnp.allclose(x["a"], m, atol=1e-2))
True
An invalid tolerance is rejected.
>>> vardax.OptaxMinimiser(gtol=-1.0)
Traceback (most recent call last):
...
ConfigurationError: gtol must be >= 0, got -1.0.
References
Kingma, D. P. and Ba, J. (2015). Adam: a method for stochastic optimization. ICLR.
Source code in src/vardax/_src/minimisers.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | |
run
¶
run(
cost_fn: Callable[[Any, Any], Float[Array, ""]],
x0: PyTree[Array],
batch: Any = None,
*,
adjoint: AbstractAdjoint | None = None,
) -> MinimiseResult
Minimise cost_fn(x, batch) from x0, with diagnostics.
result.cost is differentiable: by the envelope theorem
\(\mathrm{d}J^\star/\mathrm{d}\phi = \partial J/\partial\phi\) at
\(\theta^\star\) for any parameter \(\phi\) of the cost.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_fn
|
Callable[[Any, Any], Float[Array, '']]
|
Scalar cost |
required |
x0
|
PyTree[Array]
|
Initial guess, any pytree of arrays (for a network, the
array half of |
required |
batch
|
Any
|
Passed as the second argument of |
None
|
adjoint
|
AbstractAdjoint | None
|
How to differentiate through the minimum. Default
|
None
|
Returns:
| Type | Description |
|---|---|
MinimiseResult
|
Examples:
>>> import jax.numpy as jnp, optax, vardax
>>> minimiser = vardax.OptaxMinimiser(optax.adam(1e-1), max_steps=200)
>>> result = minimiser.run(
... lambda x, m: 0.5 * jnp.sum((x - m) ** 2), jnp.zeros(2), jnp.ones(2)
... )
>>> result.num_steps > 0
Array(True, dtype=bool)
Source code in src/vardax/_src/minimisers.py
OptimistixMinimiser
¶
Bases: Module
An optimistix minimiser behind the Minimiser protocol.
OptimistixMinimiser() is the models' default made explicit:
optx.BFGS(rtol=1e-6, atol=1e-6) with max_steps=200 and
throw=False, so a model built with it returns exactly what the
default model returns.
Algorithm
- Hand
cost_fn(x, batch), the solver andx0tooptimistix.minimise, capped atmax_stepsiterations. - Return the minimiser;
runalso reports the cost, the gradient norm and the step count at the solution.
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
solver |
AbstractMinimiser
|
The |
max_steps |
int
|
Iteration cap. |
throw |
bool
|
Passed to |
Examples:
A quadratic \(J(x) = \tfrac12 \lVert x - m \rVert^2\) has its minimum at \(m\).
>>> import jax.numpy as jnp, vardax
>>> m = jnp.array([1.0, -2.0, 0.5])
>>> minimiser = vardax.OptimistixMinimiser()
>>> x = minimiser(lambda x, m: 0.5 * jnp.sum((x - m) ** 2), jnp.zeros(3), m)
>>> bool(jnp.allclose(x, m, atol=1e-5))
True
The minimiser can return diagnostics, and any pytree is a valid control.
>>> result = minimiser.run(
... lambda p, m: 0.5 * jnp.sum((p["a"] - m) ** 2) + 0.5 * p["b"] ** 2,
... {"a": jnp.zeros(3), "b": jnp.ones(())},
... m,
... )
>>> sorted(result.value)
['a', 'b']
An invalid iteration cap is rejected.
>>> vardax.OptimistixMinimiser(max_steps=0)
Traceback (most recent call last):
...
ConfigurationError: max_steps must be >= 1, got 0.
Source code in src/vardax/_src/minimisers.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
run
¶
run(
cost_fn: Callable[[Any, Any], Float[Array, ""]],
x0: PyTree[Array],
batch: Any = None,
*,
adjoint: AbstractAdjoint | None = None,
) -> MinimiseResult
Minimise cost_fn(x, batch) from x0, with diagnostics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cost_fn
|
Callable[[Any, Any], Float[Array, '']]
|
Scalar cost |
required |
x0
|
PyTree[Array]
|
Initial guess, any pytree of arrays. |
required |
batch
|
Any
|
Passed as the second argument of |
None
|
adjoint
|
AbstractAdjoint | None
|
How to differentiate through the minimum. Default
|
None
|
Returns:
| Type | Description |
|---|---|
MinimiseResult
|
Examples:
>>> import jax.numpy as jnp, vardax
>>> result = vardax.OptimistixMinimiser().run(
... lambda x, m: 0.5 * jnp.sum((x - m) ** 2), jnp.zeros(2), jnp.ones(2)
... )
>>> bool(jnp.allclose(result.value, 1.0, atol=1e-5))
True
Source code in src/vardax/_src/minimisers.py
MinimiseResult
¶
Bases: Module
Outcome of a minimisation.
Attributes:
| Name | Type | Description |
|---|---|---|
value |
PyTree[Array]
|
The minimiser \(\theta^\star\), with the structure of |
cost |
Float[Array, '']
|
The cost \(J(\theta^\star)\). |
grad_norm |
Float[Array, '']
|
\(\lVert \nabla J(\theta^\star) \rVert_2\) over all leaves of \(\theta\). The implicit adjoint is exact only when this is (close to) zero. |
num_steps |
Int[Array, '']
|
Number of optimiser steps taken (both phases, for
|
converged |
Bool[Array, ''] | None
|
Whether the minimiser met its own convergence test:
optimistix's |
Examples:
The result carries the minimum and its diagnostics.
>>> import jax.numpy as jnp, vardax
>>> m = jnp.array([1.0, -2.0])
>>> result = vardax.OptimistixMinimiser().run(
... lambda x, m: 0.5 * jnp.sum((x - m) ** 2), jnp.zeros(2), m
... )
>>> type(result).__name__
'MinimiseResult'
>>> bool(jnp.allclose(result.value, m, atol=1e-5))
True
At a minimum the gradient norm is near zero and the run converged.
Source code in src/vardax/_src/minimisers.py
4DVarNet inner-loop solvers¶
The unrolled (and fixed-point) inner loop of 4DVarNet, exposed as pure
functions over an explicit SolverState: initialise with
init_solver_state_*, advance one modulated-gradient step with
solver_step_* (or fp_solver_step_1d for the fixed-point formulation),
or run the whole loop with solve_4dvarnet_*. The one_step_* variants
pair with OneStepAdjoint for memory-frugal training.
vardax — Modular variational data assimilation with learned components.
All public symbols are re-exported from the private _src subpackage so
that user code imports from the top-level namespace:
SolverState1D
¶
Bases: Module
Carry of the 1-D solver loop: iterate, ConvLSTM memory and step counter.
The state is the triple \((u_k, (h_k, c_k), k)\) threaded through the unrolled iteration \(u_{k+1} = u_k - \alpha\, \mathcal{G}(\nabla J(u_k), u_k, h_k, c_k)\).
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Float[Array, 'B T N']
|
Current state estimate \(u_k\). |
lstm |
LSTMState1D
|
Current LSTM hidden/cell state \((h_k, c_k)\) of the gradient modulator. |
step |
int
|
Current iteration index \(k\). |
Examples:
A state built by hand:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> state = vdx.SolverState1D(
... x=jnp.zeros((2, 3, 4)), lstm=vdx.LSTMState1D.zeros(2, 5, 4), step=0
... )
>>> state.x.shape, state.lstm.hidden.shape, state.step
((2, 3, 4), (2, 5, 4), 0)
It is an Equinox module, so it is a pytree (x, hidden, cell and the step counter):
Source code in src/vardax/_src/solver.py
SolverState2D
¶
Bases: Module
Carry of the 2-D solver loop: iterate, ConvLSTM memory and step counter.
The state is the triple \((u_k, (h_k, c_k), k)\) threaded through the unrolled iteration \(u_{k+1} = u_k - \alpha\, \mathcal{G}(\nabla J(u_k), u_k, h_k, c_k)\).
Attributes:
| Name | Type | Description |
|---|---|---|
x |
Float[Array, 'B T H W']
|
Current state estimate \(u_k\). |
lstm |
LSTMState2D
|
Current LSTM hidden/cell state \((h_k, c_k)\) of the gradient modulator. |
step |
int
|
Current iteration index \(k\). |
Examples:
A state built by hand:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> state = vdx.SolverState2D(
... x=jnp.zeros((1, 3, 4, 5)),
... lstm=vdx.LSTMState2D.zeros(1, 2, 4, 5),
... step=0,
... )
>>> state.x.shape, state.lstm.cell.shape
((1, 3, 4, 5), (1, 2, 4, 5))
Source code in src/vardax/_src/solver.py
init_solver_state_1d
¶
init_solver_state_1d(
batch: Batch1D, hidden_dim: int
) -> SolverState1D
Initialise a 1-D solver state from a batch.
The iterate starts at the masked observations, \(u_0 = m \odot y\), with a zero ConvLSTM memory and step counter zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch1D
|
Input batch \((y, m)\). The initial state is set to the masked input (zeros where unobserved). |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
Returns:
| Type | Description |
|---|---|
SolverState1D
|
Initial |
SolverState1D
|
state and |
Examples:
A typical call, with everything observed:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.ones((2, 3, 4)))
>>> state = vdx.init_solver_state_1d(batch, hidden_dim=5)
>>> state.x.shape == (2, 3, 4), state.step
(True, 0)
Unobserved entries start at zero:
>>> empty = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.zeros((2, 3, 4)))
>>> bool(jnp.all(vdx.init_solver_state_1d(empty, hidden_dim=5).x == 0))
True
Source code in src/vardax/_src/solver.py
init_solver_state_2d
¶
init_solver_state_2d(
batch: Batch2D, hidden_dim: int
) -> SolverState2D
Initialise a 2-D solver state from a batch.
The iterate starts at the masked observations, \(u_0 = m \odot y\), with a zero ConvLSTM memory and step counter zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch2D
|
Input batch \((y, m)\). The initial state is set to the masked input (zeros where unobserved). |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
Returns:
| Type | Description |
|---|---|
SolverState2D
|
Initial |
SolverState2D
|
state and |
Examples:
A typical call, with everything observed:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.ones((1, 3, 4, 5))
... )
>>> state = vdx.init_solver_state_2d(batch, hidden_dim=5)
>>> state.x.shape == (1, 3, 4, 5), state.step
(True, 0)
Unobserved entries start at zero:
>>> empty = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.zeros((1, 3, 4, 5))
... )
>>> bool(jnp.all(vdx.init_solver_state_2d(empty, hidden_dim=5).x == 0))
True
Source code in src/vardax/_src/solver.py
solver_step_1d
¶
solver_step_1d(
solver_state: SolverState1D,
batch: Batch1D,
prior_fn: Any,
grad_mod_fn: Any,
alpha: float = 1.0,
prior_weight: float = 1.0,
) -> SolverState1D
Perform a single 1-D solver iteration.
With the variational cost
one iteration moves the state along the learned, modulated gradient, \(u \leftarrow u - \alpha\, \mathcal{G}(\nabla J(u), u, h)\).
Algorithm
- Evaluate the observation term \(\|m \odot (u - y)\|^2\) and the prior term \(\lambda \|u - \varphi(u)\|^2\) at the current state.
- Differentiate the sum with
jax.gradto obtain \(\nabla J(u)\). - Pass \((\nabla J, u, h)\) through
grad_mod_fnto get the update and the new LSTM state. - Set \(u \leftarrow u - \alpha \cdot \text{update}\) and increment
step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solver_state
|
SolverState1D
|
Current solver state \((u, h, c, k)\). |
required |
batch
|
Batch1D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
prior_weight
|
float
|
Weighting factor \(\lambda\) for the prior cost term. |
1.0
|
Returns:
| Type | Description |
|---|---|
SolverState1D
|
Updated |
SolverState1D
|
and |
Examples:
With an identity prior and a pass-through modulator, one step with
alpha=0.5 moves a zero state halfway to the observations (the
observation gradient is \(-2\)):
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.ones((2, 3, 4)))
>>> state = vdx.SolverState1D(
... x=jnp.zeros((2, 3, 4)), lstm=vdx.LSTMState1D.zeros(2, 5, 4), step=0
... )
>>> passthrough = lambda grad, x, lstm: (grad, lstm)
>>> new = vdx.solver_step_1d(
... state, batch, vdx.IdentityPrior(), passthrough, alpha=0.5
... )
>>> bool(jnp.allclose(new.x, 1.0)), new.step
(True, 1)
Where nothing is observed and the prior is the identity there is no gradient, so the state does not move:
>>> blind = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.zeros((2, 3, 4)))
>>> new = vdx.solver_step_1d(state, blind, vdx.IdentityPrior(), passthrough)
>>> bool(jnp.allclose(new.x, 0.0))
True
Source code in src/vardax/_src/solver.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
solver_step_2d
¶
solver_step_2d(
solver_state: SolverState2D,
batch: Batch2D,
prior_fn: Any,
grad_mod_fn: Any,
alpha: float = 1.0,
prior_weight: float = 1.0,
) -> SolverState2D
Perform a single 2-D solver iteration.
With the variational cost
one iteration moves the state along the learned, modulated gradient, \(u \leftarrow u - \alpha\, \mathcal{G}(\nabla J(u), u, h)\).
Algorithm
- Evaluate the observation term \(\|m \odot (u - y)\|^2\) and the prior term \(\lambda \|u - \varphi(u)\|^2\) at the current state.
- Differentiate the sum with
jax.gradto obtain \(\nabla J(u)\). - Pass \((\nabla J, u, h)\) through
grad_mod_fnto get the update and the new LSTM state. - Set \(u \leftarrow u - \alpha \cdot \text{update}\) and increment
step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solver_state
|
SolverState2D
|
Current solver state \((u, h, c, k)\). |
required |
batch
|
Batch2D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
prior_weight
|
float
|
Weighting factor \(\lambda\) for the prior cost term. |
1.0
|
Returns:
| Type | Description |
|---|---|
SolverState2D
|
Updated |
SolverState2D
|
and |
Examples:
With an identity prior and a pass-through modulator, one step with
alpha=0.5 moves a zero state halfway to the observations (the
observation gradient is \(-2\)):
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.ones((1, 3, 4, 5))
... )
>>> state = vdx.SolverState2D(
... x=jnp.zeros((1, 3, 4, 5)),
... lstm=vdx.LSTMState2D.zeros(1, 2, 4, 5),
... step=0,
... )
>>> passthrough = lambda grad, x, lstm: (grad, lstm)
>>> new = vdx.solver_step_2d(
... state, batch, vdx.IdentityPrior(), passthrough, alpha=0.5
... )
>>> bool(jnp.allclose(new.x, 1.0)), new.step
(True, 1)
Where nothing is observed and the prior is the identity there is no gradient, so the state does not move:
>>> blind = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.zeros((1, 3, 4, 5))
... )
>>> new = vdx.solver_step_2d(state, blind, vdx.IdentityPrior(), passthrough)
>>> bool(jnp.allclose(new.x, 0.0))
True
Source code in src/vardax/_src/solver.py
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
fp_solver_step_1d
¶
fp_solver_step_1d(
x: Float[Array, "B T N"], batch: Batch1D, prior_fn: Any
) -> Float[Array, "B T N"]
Perform a single 1-D fixed-point projection step.
Applies the prior projection then re-inserts observations at observed locations:
Algorithm
- Project the state with the prior, \(\varphi(x)\).
- Overwrite observed entries with the data and keep the projection elsewhere, \(m \odot y + (1 - m) \odot \varphi(x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Array, 'B T N']
|
Current state estimate \(x\). |
required |
batch
|
Batch1D
|
Observed data batch containing |
required |
prior_fn
|
Any
|
Callable |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T N']
|
Updated state estimate \(m \odot y + (1 - m) \odot \varphi(x)\). |
Examples:
Observed entries are reinserted, unobserved ones come from the prior:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch1D(
... input=jnp.ones((1, 2, 3)),
... mask=jnp.array([[[1.0, 0.0, 1.0], [0.0, 0.0, 1.0]]]),
... )
>>> prior = lambda x: 5.0 * jnp.ones_like(x)
>>> out = vdx.fp_solver_step_1d(jnp.zeros((1, 2, 3)), batch, prior)
>>> out[0].tolist()
[[1.0, 5.0, 1.0], [5.0, 5.0, 1.0]]
A fully observed batch returns the data whatever the prior says:
>>> full = vdx.Batch1D(input=jnp.ones((1, 2, 3)), mask=jnp.ones((1, 2, 3)))
>>> bool(jnp.all(vdx.fp_solver_step_1d(jnp.zeros((1, 2, 3)), full, prior) == 1))
True
Source code in src/vardax/_src/solver.py
solve_4dvarnet_1d
¶
solve_4dvarnet_1d(
batch: Batch1D,
prior_fn: Any,
grad_mod_fn: Any,
n_steps: int,
hidden_dim: int,
alpha: float = 1.0,
) -> Float[Array, "B T N"]
Run the full 1-D 4DVarNet solver for n_steps iterations.
Unrolls \(u_{k+1} = u_k - \alpha\, \mathcal{G}(\nabla J(u_k), u_k, h_k)\) from
\(u_0 = m \odot y\), with \(J\) the variational cost of
solver_step_1d.
Algorithm
- Initialise the state with
init_solver_state_1d. - Repeat
n_stepstimes: applysolver_step_1dto the state. - Return the final iterate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch1D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
n_steps
|
int
|
Number of gradient-descent steps to unroll. |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T N']
|
Final state estimate \(u_{n}\) after |
Examples:
Fully observed data is already a minimiser for an identity prior, so the solver returns it unchanged:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.ones((2, 3, 4)))
>>> passthrough = lambda grad, x, lstm: (grad, lstm)
>>> out = vdx.solve_4dvarnet_1d(
... batch,
... vdx.IdentityPrior(),
... passthrough,
... n_steps=3,
... hidden_dim=5,
... alpha=0.5,
... )
>>> out.shape == (2, 3, 4), bool(jnp.allclose(out, 1.0))
(True, True)
With n_steps=0 the result is the masked input:
>>> out = vdx.solve_4dvarnet_1d(
... batch, vdx.IdentityPrior(), passthrough, n_steps=0, hidden_dim=5
... )
>>> bool(jnp.allclose(out, batch.input * batch.mask))
True
The learned pieces of a FourDVarNet1D plug in
directly and reproduce its unrolled forward pass:
>>> import jax
>>> model = vdx.FourDVarNet1D(
... state_dim=4,
... n_time=3,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=2,
... alpha=0.2,
... key=jax.random.PRNGKey(0),
... )
>>> out = vdx.solve_4dvarnet_1d(
... batch,
... model.prior,
... model.grad_mod,
... n_steps=2,
... hidden_dim=3,
... alpha=0.2,
... )
>>> bool(jnp.allclose(out, model(batch), atol=1e-5))
True
Source code in src/vardax/_src/solver.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
solve_4dvarnet_2d
¶
solve_4dvarnet_2d(
batch: Batch2D,
prior_fn: Any,
grad_mod_fn: Any,
n_steps: int,
hidden_dim: int,
alpha: float = 1.0,
) -> Float[Array, "B T H W"]
Run the full 2-D 4DVarNet solver for n_steps iterations.
Unrolls \(u_{k+1} = u_k - \alpha\, \mathcal{G}(\nabla J(u_k), u_k, h_k)\) from
\(u_0 = m \odot y\), with \(J\) the variational cost of
solver_step_2d.
Algorithm
- Initialise the state with
init_solver_state_2d. - Repeat
n_stepstimes: applysolver_step_2dto the state. - Return the final iterate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch2D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
n_steps
|
int
|
Number of gradient-descent steps to unroll. |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T H W']
|
Final state estimate \(u_{n}\) after |
Examples:
Fully observed data is already a minimiser for an identity prior, so the solver returns it unchanged:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.ones((1, 3, 4, 5))
... )
>>> passthrough = lambda grad, x, lstm: (grad, lstm)
>>> out = vdx.solve_4dvarnet_2d(
... batch,
... vdx.IdentityPrior(),
... passthrough,
... n_steps=3,
... hidden_dim=5,
... alpha=0.5,
... )
>>> out.shape == (1, 3, 4, 5), bool(jnp.allclose(out, 1.0))
(True, True)
With n_steps=0 the result is the masked input:
>>> out = vdx.solve_4dvarnet_2d(
... batch, vdx.IdentityPrior(), passthrough, n_steps=0, hidden_dim=5
... )
>>> bool(jnp.allclose(out, batch.input * batch.mask))
True
The learned pieces of a FourDVarNet2D plug in
directly and reproduce its unrolled forward pass:
>>> import jax
>>> model = vdx.FourDVarNet2D(
... n_time=3,
... height=4,
... width=5,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=2,
... alpha=0.2,
... key=jax.random.PRNGKey(0),
... )
>>> out = vdx.solve_4dvarnet_2d(
... batch,
... model.prior,
... model.grad_mod,
... n_steps=2,
... hidden_dim=3,
... alpha=0.2,
... )
>>> bool(jnp.allclose(out, model(batch), atol=1e-5))
True
Source code in src/vardax/_src/solver.py
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | |
solve_4dvarnet_1d_fixedpoint
¶
solve_4dvarnet_1d_fixedpoint(
batch: Batch1D, prior_fn: Any, n_fp_steps: int
) -> Float[Array, "B T N"]
Run n_fp_steps fixed-point projection steps using jax.lax.scan.
Iterates \(x_{k+1} = m \odot y + (1 - m) \odot \varphi(x_k)\) from the masked observations, the projection used by the implicit-adjoint path.
Algorithm
- Initialise \(x_0 = m \odot y\).
- Scan
fp_solver_step_1dforn_fp_stepssteps. - Return the final iterate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch1D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
n_fp_steps
|
int
|
Number of fixed-point iterations. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T N']
|
Final state estimate \(x_{n}\) after |
Examples:
With an identity prior the unobserved entries stay at zero:
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> batch = vdx.Batch1D(
... input=jnp.ones((1, 2, 3)),
... mask=jnp.array([[[1.0, 0.0, 1.0], [0.0, 0.0, 1.0]]]),
... )
>>> out = vdx.solve_4dvarnet_1d_fixedpoint(batch, vdx.IdentityPrior(), 4)
>>> bool(jnp.allclose(out, batch.input * batch.mask))
True
Zero steps return the masked input, and a constant prior fills the gaps after one step:
>>> zero = vdx.solve_4dvarnet_1d_fixedpoint(batch, vdx.IdentityPrior(), 0)
>>> bool(jnp.allclose(zero, batch.input * batch.mask))
True
>>> out = vdx.solve_4dvarnet_1d_fixedpoint(batch, lambda x: 2 + 0 * x, 1)
>>> out[0, 0].tolist()
[1.0, 2.0, 1.0]
Source code in src/vardax/_src/solver.py
one_step_solve_4dvarnet_1d
¶
one_step_solve_4dvarnet_1d(
batch: Batch1D,
prior_fn: Any,
grad_mod_fn: Any,
n_steps: int,
hidden_dim: int,
alpha: float = 1.0,
prior_weight: float = 1.0,
k: int = 1,
) -> Float[Array, "B T N"]
Solve 4DVarNet-1D using k-step differentiation (Bolte et al., 2023).
Runs the same iteration as solve_4dvarnet_1d,
\(u_{j+1} = u_j - \alpha\, \mathcal{G}(\nabla J(u_j), u_j, h_j)\), but
only the last k steps carry gradients. This gives O(k) memory cost
(k=1 matches implicit differentiation) while being as simple to
implement as unrolled backprop.
Algorithm
- Initialise the state from the masked observations.
- Run
n_steps - kwarm-up steps and applyjax.lax.stop_gradientto the iterate and LSTM state (skipped when there is no warm-up). - Run the remaining
ksteps through which gradients flow. - Return the final iterate.
References
Bolte, Pauwels & Vaiter (NeurIPS 2023). "One-step differentiation of iterative algorithms." https://arxiv.org/abs/2305.13768
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch1D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
n_steps
|
int
|
Total number of solver iterations (warmup = n_steps - k, then k differentiable steps). |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
prior_weight
|
float
|
Weighting factor \(\lambda\) for the prior cost term. |
1.0
|
k
|
int
|
Number of trailing differentiable steps (clipped to n_steps). |
1
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T N']
|
Final state estimate after |
Examples:
The forward value equals the fully unrolled solve; only the gradient path differs:
>>> import jax
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> model = vdx.FourDVarNet1D(
... state_dim=4,
... n_time=3,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=3,
... alpha=0.2,
... key=jax.random.PRNGKey(0),
... )
>>> batch = vdx.Batch1D(input=jnp.ones((2, 3, 4)), mask=jnp.ones((2, 3, 4)))
>>> kwargs = dict(n_steps=3, hidden_dim=3, alpha=0.2)
>>> full = vdx.solve_4dvarnet_1d(batch, model.prior, model.grad_mod, **kwargs)
>>> one = vdx.one_step_solve_4dvarnet_1d(
... batch, model.prior, model.grad_mod, k=1, **kwargs
... )
>>> bool(jnp.allclose(full, one, atol=1e-5))
True
k >= n_steps disables the warm-up, so the solve is the same
value again:
>>> big = vdx.one_step_solve_4dvarnet_1d(
... batch, model.prior, model.grad_mod, k=10, **kwargs
... )
>>> bool(jnp.allclose(full, big, atol=1e-5))
True
It is what FourDVarNet1D runs under a
OneStepAdjoint:
>>> fast = vdx.FourDVarNet1D(
... state_dim=4,
... n_time=3,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=3,
... alpha=0.2,
... solver_adjoint=vdx.OneStepAdjoint(),
... key=jax.random.PRNGKey(0),
... )
>>> bool(jnp.allclose(fast(batch), one, atol=1e-5))
True
Source code in src/vardax/_src/solver.py
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 | |
one_step_solve_4dvarnet_2d
¶
one_step_solve_4dvarnet_2d(
batch: Batch2D,
prior_fn: Any,
grad_mod_fn: Any,
n_steps: int,
hidden_dim: int,
alpha: float = 1.0,
prior_weight: float = 1.0,
k: int = 1,
) -> Float[Array, "B T H W"]
Solve 4DVarNet-2D using k-step differentiation (Bolte et al., 2023).
Runs the same iteration as solve_4dvarnet_2d,
\(u_{j+1} = u_j - \alpha\, \mathcal{G}(\nabla J(u_j), u_j, h_j)\), but
only the last k steps carry gradients. This gives O(k) memory cost
(k=1 matches implicit differentiation) while being as simple to
implement as unrolled backprop.
Algorithm
- Initialise the state from the masked observations.
- Run
n_steps - kwarm-up steps and applyjax.lax.stop_gradientto the iterate and LSTM state (skipped when there is no warm-up). - Run the remaining
ksteps through which gradients flow. - Return the final iterate.
References
Bolte, Pauwels & Vaiter (NeurIPS 2023). "One-step differentiation of iterative algorithms." https://arxiv.org/abs/2305.13768
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Batch2D
|
Observed data batch \((y, m)\). |
required |
prior_fn
|
Any
|
Callable |
required |
grad_mod_fn
|
Any
|
Callable |
required |
n_steps
|
int
|
Total number of solver iterations (warmup = n_steps - k, then k differentiable steps). |
required |
hidden_dim
|
int
|
Hidden dimension of the ConvLSTM gradient modulator. |
required |
alpha
|
float
|
Step-size scaling factor \(\alpha\). |
1.0
|
prior_weight
|
float
|
Weighting factor \(\lambda\) for the prior cost term. |
1.0
|
k
|
int
|
Number of trailing differentiable steps (clipped to n_steps). |
1
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'B T H W']
|
Final state estimate after |
Examples:
The forward value equals the fully unrolled solve; only the gradient path differs:
>>> import jax
>>> import jax.numpy as jnp
>>> import vardax as vdx
>>> model = vdx.FourDVarNet2D(
... n_time=3,
... height=4,
... width=5,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=3,
... alpha=0.2,
... key=jax.random.PRNGKey(0),
... )
>>> batch = vdx.Batch2D(
... input=jnp.ones((1, 3, 4, 5)), mask=jnp.ones((1, 3, 4, 5))
... )
>>> kwargs = dict(n_steps=3, hidden_dim=3, alpha=0.2)
>>> full = vdx.solve_4dvarnet_2d(batch, model.prior, model.grad_mod, **kwargs)
>>> one = vdx.one_step_solve_4dvarnet_2d(
... batch, model.prior, model.grad_mod, k=1, **kwargs
... )
>>> bool(jnp.allclose(full, one, atol=1e-5))
True
k >= n_steps disables the warm-up, so the solve is the same
value again:
>>> big = vdx.one_step_solve_4dvarnet_2d(
... batch, model.prior, model.grad_mod, k=10, **kwargs
... )
>>> bool(jnp.allclose(full, big, atol=1e-5))
True
It is what FourDVarNet2D runs under a
OneStepAdjoint:
>>> fast = vdx.FourDVarNet2D(
... n_time=3,
... height=4,
... width=5,
... latent_dim=2,
... hidden_dim=3,
... n_solver_steps=3,
... alpha=0.2,
... solver_adjoint=vdx.OneStepAdjoint(),
... key=jax.random.PRNGKey(0),
... )
>>> bool(jnp.allclose(fast(batch), one, atol=1e-5))
True
Source code in src/vardax/_src/solver.py
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 | |