Skip to content

diffsol_jax

ODEProblem

ODEProblem(rhs: Callable, state: int | PyTree, params: int | PyTree = None, *, out: Callable | None = None, mass: Callable | None = None, algebraic: int | Sequence[bool] | PyTree | None = None, root: Callable | None = None, reset: Callable | None = None, solver: Solver = 'bdf', linear_solver: LinearSolver = 'default', matrix_type: MatrixType = 'nalgebra_dense', max_checkpoints: int = 8, dtype: DTypeLike | None = None)

An ODE, or a semi-explicit index-1 DAE, together with the diffsol solver for it.

The state and the parameters are pytrees, declared by state= and params=. Each is either an int n, meaning one flat array of shape (n,), or a template pytree whose float-array leaves give the shapes and dtypes.

Building a problem builds the equations and the diffsol solver, so build it once and reuse it across solves. To solve the same equations with different options, use ODEProblem.replace.

Parameters:

Name Type Description Default
rhs Callable

the vector field, rhs(y, p, t) -> y-like. y and the result are in the state structure, p is in the params structure, and t is a scalar.

required
state int | PyTree

the layout of the state: an int, or a template whose every leaf is a float array.

required
params int | PyTree

the layout of the parameters: an int, None for no parameters, or a template whose float-array leaves are the parameters. Any other leaf is a constant that the equations capture, with its value taken from the template.

None
out Callable | None

out(y, p, t) -> pytree, an output to return in place of the state. ys comes back in its structure.

None
mass Callable | None

the mass matrix action mass(v, p, t) -> M(t) v, with v in the state structure. Must be linear in v and must not use p.

None
algebraic int | Sequence[bool] | PyTree | None

a mass shortcut for a semi-explicit DAE, marking the rows of rhs that are algebraic constraints: an int (the last entries of the flat state), a sequence of nstates bools, or a pytree of bools matching state.

None
root Callable | None

the event condition root(y, p, t) -> pytree, with y in the state structure. An event fires when any entry of the result crosses zero, and the solver applies reset to the state at the crossing time. Give root and reset together. If the reset leaves the root function at zero (a bouncing ball, whose position stays on the floor), numerical noise can re-trigger the event: gate the condition on its direction, for example jnp.where(v < 0, x, 1.0).

None
reset Callable | None

the state jump at an event, reset(y, p, t) -> y-like: the state the solve continues from after a root of root.

None
solver Solver

the diffsol solver: "bdf", "esdirk34", "tr_bdf2", or "tsit45" (explicit, so not for a DAE).

'bdf'
linear_solver LinearSolver

"default", "lu", or "klu".

'default'
matrix_type MatrixType

"nalgebra_dense", "faer_dense", or "faer_sparse".

'nalgebra_dense'
max_checkpoints int

how many adjoint checkpoints to keep alive at once.

8
dtype DTypeLike | None

the scalar type the solver works in: float32 or float64. Defaults to float32, or float64 when jax_enable_x64 is on.

None
Source code in python/diffsol_jax/_problem.py
def __init__(
    self,
    rhs: Callable,
    state: int | PyTree,
    params: int | PyTree = None,
    *,
    out: Callable | None = None,
    mass: Callable | None = None,
    algebraic: int | Sequence[bool] | PyTree | None = None,
    root: Callable | None = None,
    reset: Callable | None = None,
    solver: Solver = "bdf",
    linear_solver: LinearSolver = "default",
    matrix_type: MatrixType = "nalgebra_dense",
    max_checkpoints: int = 8,
    dtype: DTypeLike | None = None,
):
    if not callable(rhs):
        raise DiffsolJaxError("rhs must be a function rhs(y, p, t) -> y-like")
    if mass is not None and algebraic is not None:
        raise DiffsolJaxError("give mass or algebraic, not both")
    if (root is None) != (reset is None):
        raise DiffsolJaxError(
            "give root and reset together: a root without a reset would end the "
            "solve before t1, and a reset alone has nothing to trigger it"
        )
    if max_checkpoints < 1:
        raise DiffsolJaxError("max_checkpoints must be at least 1")
    # the arguments as given, so that `replace` can rebuild the problem
    self._declared = {
        "rhs": rhs,
        "state": state,
        "params": params,
        "out": out,
        "mass": mass,
        "algebraic": algebraic,
        "root": root,
        "reset": reset,
        "solver": solver,
        "linear_solver": linear_solver,
        "matrix_type": matrix_type,
        "max_checkpoints": max_checkpoints,
        "dtype": dtype,
    }
    self.solver, self.linear_solver = solver, linear_solver
    self.matrix_type, self.max_checkpoints = matrix_type, max_checkpoints

    self.dtype = solver_dtype(dtype)
    if self.dtype == F64 and not jax.config.read("jax_enable_x64"):
        raise DiffsolJaxError("dtype=float64 needs jax_enable_x64")

    self.state = Layout(state, "state", self.dtype, constants=False)
    self.params = Layout(params, "params", self.dtype)
    if self.state.n < 1:
        raise DiffsolJaxError("state must have at least one entry")
    self.nstates, self.nparams = self.state.n, self.params.n
    # what `ys` comes back in: the state, or whatever `out` returns
    self.solution = _equations.solution_layout(
        out, self.state, self.params, self.dtype
    )
    self.nout = 0 if out is None else self.solution.n
    self.nsolution = self.solution.n

    flat_mass = self._flat_mass(mass, algebraic)
    if flat_mass is not None and solver == "tsit45":
        raise DiffsolJaxError(
            "a problem with a mass matrix (a DAE) needs an implicit solver: "
            "solver='bdf', 'esdirk34' or 'tr_bdf2'"
        )
    self.nroots = 0
    flat_root = flat_reset = None
    if root is not None:
        roots = _equations.traced_layout(
            root, "root", self.state, self.params, self.dtype
        )
        if roots.n < 1:
            raise DiffsolJaxError("root must have at least one entry")
        self.nroots = roots.n
        flat_root = _equations.over_flat(
            root, "root", self.state, self.params, roots
        )
        flat_reset = _equations.over_flat(
            reset, "reset", self.state, self.params, self.state
        )
    self.eq = _equations.build(
        rhs,
        out,
        flat_mass,
        flat_root,
        flat_reset,
        self.nroots,
        self.state,
        self.params,
        self.solution,
        self.dtype,
    )
    self._model = Model(
        self.eq,
        solver=solver,
        linear_solver=linear_solver,
        matrix_type=matrix_type,
        max_checkpoints=max_checkpoints,
    )

callback_stats

callback_stats(nbatch: int, reset: bool = False)

The callback counters (ncalls, nstaged, nviews) for the given batch size.

Source code in python/diffsol_jax/_problem.py
def callback_stats(self, nbatch: int, reset: bool = False):
    """The callback counters `(ncalls, nstaged, nviews)` for the given batch size."""
    return self._model.callback_stats(nbatch, reset)

clear_checkpoints

clear_checkpoints()

Frees the adjoint checkpoints currently kept alive.

Source code in python/diffsol_jax/_problem.py
def clear_checkpoints(self):
    """Frees the adjoint checkpoints currently kept alive."""
    self._model.clear_checkpoints()

num_checkpoints

num_checkpoints() -> int

The number of adjoint checkpoints currently kept alive.

Source code in python/diffsol_jax/_problem.py
def num_checkpoints(self) -> int:
    """The number of adjoint checkpoints currently kept alive."""
    return self._model.num_checkpoints()

num_recomputes

num_recomputes() -> int

How many backward solves had to re-run their forward solve, because the checkpoint had been evicted.

Source code in python/diffsol_jax/_problem.py
def num_recomputes(self) -> int:
    """How many backward solves had to re-run their forward solve, because the
    checkpoint had been evicted."""
    return self._model.num_recomputes()

replace

replace(**changes) -> ODEProblem

Returns a new problem with the given constructor arguments replaced.

For example, problem.replace(solver="tsit45"). The new problem has its own diffsol solver; the original is unchanged.

Source code in python/diffsol_jax/_problem.py
def replace(self, **changes) -> "ODEProblem":
    """Returns a new problem with the given constructor arguments replaced.

    For example, `problem.replace(solver="tsit45")`. The new problem has its own
    diffsol solver; the original is unchanged.
    """
    unknown = set(changes) - set(self._declared)
    if unknown:
        raise DiffsolJaxError(f"replace got unknown arguments: {sorted(unknown)}")
    return ODEProblem(**{**self._declared, **changes})

solve

solve(problem: ODEProblem, y0: PyTree, params: PyTree, t0: float, t1: float, *, saveat: ArrayLike | None = None, rtol: float | None = None, atol: float | None = None, max_steps: int = 10000, ad: Ad | None = None) -> PyTree

Solves problem from the state y0 at t0 to t1.

Works under jax.jit, jax.grad, jax.jacfwd and jax.vmap, and is differentiable with respect to both y0 and params.

Parameters:

Name Type Description Default
problem ODEProblem required
y0 PyTree

the state at t0, in the problem's state structure.

required
params PyTree

the parameter values, in the problem's params structure, or None.

required
t0 float

the initial time.

required
t1 float

the final time.

required
saveat ArrayLike | None

the times to return the solution at: shape [nt], increasing, each in [t0, t1]. The default returns the solution at t1 alone.

None
rtol float | None

the relative tolerance of the solver. Defaults to 1e-6 for a float64 problem and 1e-4 for float32.

None
atol float | None

the absolute tolerance of the solver, with the same default as rtol.

None
max_steps int

the most steps the solver may take to reach the last time it returns.

10000
ad Ad | None

how to take the reverse-mode derivative: "adjoint", the diffsol adjoint with checkpointing, or "forward", the transpose of the forward sensitivities. See Computing gradients. Defaults to "adjoint", or "forward" for a problem with events, which the adjoint does not support.

None

Returns:

Type Description
PyTree

ys, the solution at the times saveat, in the problem's output structure (its

PyTree

state, or what out returns). Each leaf has shape [nt, *leaf_shape].

Source code in python/diffsol_jax/_solve.py
def solve(
    problem: ODEProblem,
    y0: PyTree,
    params: PyTree,
    t0: float,
    t1: float,
    *,
    saveat: ArrayLike | None = None,
    rtol: float | None = None,
    atol: float | None = None,
    max_steps: int = 10_000,
    ad: Ad | None = None,
) -> PyTree:
    """Solves `problem` from the state `y0` at `t0` to `t1`.

    Works under `jax.jit`, `jax.grad`, `jax.jacfwd` and `jax.vmap`, and is differentiable
    with respect to both `y0` and `params`.

    Args:
        problem: an [`ODEProblem`][diffsol_jax.ODEProblem].
        y0: the state at `t0`, in the problem's `state` structure.
        params: the parameter values, in the problem's `params` structure, or `None`.
        t0: the initial time.
        t1: the final time.
        saveat: the times to return the solution at: shape `[nt]`, increasing, each in
            `[t0, t1]`. The default returns the solution at `t1` alone.
        rtol: the relative tolerance of the solver. Defaults to `1e-6` for a `float64`
            problem and `1e-4` for `float32`.
        atol: the absolute tolerance of the solver, with the same default as `rtol`.
        max_steps: the most steps the solver may take to reach the last time it returns.
        ad: how to take the reverse-mode derivative: `"adjoint"`, the diffsol adjoint with
            checkpointing, or `"forward"`, the transpose of the forward sensitivities.
            See [Computing gradients][computing-gradients-page]. Defaults to `"adjoint"`,
            or `"forward"` for a problem with events, which the adjoint does not support.

    Returns:
        `ys`, the solution at the times `saveat`, in the problem's output structure (its
        `state`, or what `out` returns). Each leaf has shape `[nt, *leaf_shape]`.
    """
    if ad is None:
        ad = "forward" if problem.nroots else "adjoint"
    if ad not in ("adjoint", "forward"):
        raise DiffsolJaxError("ad must be 'adjoint' or 'forward'")
    if ad == "adjoint" and problem.nroots:
        raise DiffsolJaxError(
            "ad='adjoint' does not support a problem with events (root and reset): "
            "the diffsol step VJP cannot cross a reset; use ad='forward'"
        )

    default_tol = DEFAULT_TOL[problem.dtype]
    rtol = default_tol if rtol is None else rtol
    atol = default_tol if atol is None else atol

    max_steps = operator.index(max_steps)
    if max_steps < 1:
        raise DiffsolJaxError(f"max_steps must be at least 1, got {max_steps}")

    t0 = jnp.asarray(t0, problem.dtype)
    t1 = jnp.asarray(t1, problem.dtype)

    if t0.ndim != 0 or t1.ndim != 0:
        raise DiffsolJaxError("t0 and t1 must be scalars")

    t_eval = t1[None] if saveat is None else jnp.asarray(saveat, problem.dtype)

    if t_eval.ndim != 1:
        raise DiffsolJaxError("saveat must have one axis")
    if t_eval.shape[0] < 1:
        raise DiffsolJaxError("saveat must have at least one time")

    _check_times(_concrete(t0), _concrete(t1), _concrete(t_eval))

    flat = problem._pack(y0, params)
    prim_cls = _primitives.SolveAdjoint if ad == "adjoint" else _primitives.SolveForward
    prim = prim_cls(
        jax.typeof(flat),
        jax.typeof(t0),
        jax.typeof(t_eval),
        problem=problem,
        rtol=float(rtol),
        atol=float(atol),
        max_steps=max_steps,
    )
    return problem._unpack(prim(flat, t0, t_eval))