Introduction
diffsol is a Rust library that solves ordinary differential equations (ODEs) and semi-explicit differential algebraic equations (DAEs) of the form
\[ M \frac{dy}{dt} = f(t, y, p), \quad y(t_0) = y_0(t_0, p), \]
where \(M\) is an optional mass matrix (it can be singular), \(y\) is the state vector, \(t\) is the time and \(p\) is a vector of parameters.
You can give the equations to diffsol in one of these forms:
- Rust closures, which you give to the
OdeBuilder. - The DiffSL domain-specific language. diffsol compiles DiffSL equations at runtime, and it calculates the Jacobians with automatic differentiation.
- Your own types that implement the diffsol traits.
The README lists the features of diffsol, and tells you how to install it.
How to use this book
- Modelling with diffsol is a primer on ODE modelling. Each section introduces a type of model (first-order and higher-order ODEs, events, DAEs, PDEs and sensitivity analysis), and gives examples that you can run.
- Specifying ODE problems shows the three ways to give your equations to diffsol: the builder with closures, DiffSL, and the diffsol traits.
- Creating a solver and Solving the problem show how to make a solver and how to get the solution, the sensitivities and the gradients.
- Performance gives advice about how to make your solves fast.
- Using diffsol from other languages shows how to use diffsol from Python, C and WebAssembly.
- Benchmarks compares diffsol with other ODE solvers.
The API documentation on docs.rs gives the full API.
The code for all the examples is in the examples folder of the diffsol repository.
Modelling with diffsol
Ordinary Differential Equations (ODEs) are a powerful tool for modelling a wide range of physical systems. Unlike purely data-driven models, ODEs are based on the underlying physics, biology, or chemistry of the system being modelled. This makes them particularly useful for predicting the behaviour of a system under conditions that have not been observed. In this section, we will introduce the basics of ODE modelling, and illustrate their use with a series of examples written using the diffsol crate.
The topics covered in this section are:
-
First Order ODEs: First order ODEs are the simplest type of ODE. Any ODE system can be written as a set of first order ODEs, so libraries like diffsol are designed such that the user provides their equations in this form.
- Example: Population Dynamics: A simple example of a first order ODE system, modelling the interaction of predator and prey populations.
-
Higher Order ODEs: Higher order ODEs are equations that involve derivatives of order greater than one. These can be converted to a system of first order ODEs, which is the form that diffsol expects.
- Example: Spring-mass systems: A simple example of a higher order ODE system, modelling the motion of a damped spring-mass system.
-
Discrete Events: Discrete events are events that occur at specific times or when the system is in a particular state, rather than continuously. These can be modelled by treating the events as changes in the ODE system's state. diffsol provides an API to detect and handle these events.
- Example: Compartmental models of Drug Delivery: Pharmacokinetic models describe how a drug is absorbed, distributed, metabolised, and excreted by the body. They are a common example of systems with discrete events, as the drug is often administered at discrete times.
- Example: Bouncing Ball: A simple example of a system where the discrete event occurs when the ball hits the ground, instead of at a specific time.
-
Hybrid ODEs: Hybrid ODEs have more than one mode of behaviour, and a discrete model index selects the mode that is active. Events can change the model index, so that the equations change during the solve.
- Example: Dosing Protocols: The drug delivery model from the compartmental models example, with a three-dose protocol in which the model index selects the level of each dose.
- Example: Epidemic SIR with policy switching: An SIR epidemic model in which the transmission rate changes when a public-health policy switches on or off.
-
DAEs via the Mass Matrix: Differential Algebraic Equations (DAEs) are a generalisation of ODEs that include algebraic equations as well as differential equations. diffsol can solve DAEs by treating them as ODEs with a mass matrix. This section explains how to use the mass matrix to solve DAEs.
- Example: Electrical Circuits: Electrical circuits are a common example of DAEs, here we will model a simple low-pass LRC filter circuit.
-
PDEs: Partial Differential Equations (PDEs) are a generalisation of ODEs that involve derivatives with respect to more than one variable (e.g. a spatial variable). diffsol can be used to solver PDEs using the method of lines, where the spatial derivatives are discretised to form a system of ODEs.
- Example: Heat Equation: The heat equation describes how heat diffuses in a domain over time. We will solve the heat equation in a 1D domain with Dirichlet boundary conditions.
- Example: Physics-based Battery Simulation: A more complex example of a PDE system, modelling the charge and discharge of a lithium-ion battery. For this example we will use the PyBaMM library to form the ODE system, and diffsol to solve it.
-
Forward Sensitivity Analysis: Sensitivity analysis is a technique used to determine how the output of a model changes with respect to changes in the model parameters. Forward sensitivity analysis calculates the sensitivity of the model output with respect to the parameters by solving the ODE system and the sensitivity equations simultaneously.
- Example: Fitting a predator-prey model to data: An example of fitting a predator-prey model to synthetic data using forward sensitivity analysis.
-
Backwards Sensitivity Analysis: Backwards sensitivity analysis calculates the sensitivity of a loss function with respect to the parameters by first solving the ODE system and then the adjoint equations backwards in time. This is useful if your model has a high number of parameters, as it can be more efficient than forward sensitivity analysis.
- Example: Fitting a spring-mass model to data: An example of fitting a spring-mass model to synthetic data using backwards sensitivity analysis.
- Example: Weather prediction using neural ODEs: An example of fitting a neural ODE to weather data using backwards sensitivity analysis.
Explicit First Order ODEs
Ordinary Differential Equations (ODEs) are often called rate equations because they describe how the rate of change of a system depends on its current state. For example, lets assume we wish to model the growth of a population of cells within a petri dish. We could define the state of the system as the concentration of cells in the dish, and assign this state to a variable \(c\). The rate of change of the system would then be the rate at which the concentration of cells changes with time, which we could denote as \(\frac{dc}{dt}\). We know that our cells will grow at a rate proportional to the current concentration of cells, so this can be written as:
\[ \frac{dc}{dt} = k c \]
where \(k\) is a constant that describes the growth rate of the cells. This is a first order ODE, because it involves only the first derivative of the state variable \(c\) with respect to time.
We can extend this further to solve multiple equations simultaineously, in order to model the rate of change of more than one quantity. For example, say we had two populations of cells in the same dish that grow with different rates. We could define the state of the system as the concentrations of the two cell populations, and assign these states to variables \(c_1\) and \(c_2\). could then write down both equations as:
\[ \begin{align*} \frac{dc_1}{dt} &= k_1 c_1 \\ \frac{dc_2}{dt} &= k_2 c_2 \end{align*} \]
and then combine them in a vector form as:
\[ \begin{bmatrix} \frac{dc_1}{dt} \\ \frac{dc_2}{dt} \end{bmatrix} = \begin{bmatrix} k_1 c_1 \\ k_2 c_2 \end{bmatrix} \]
By defining a new vector of state variables \(\mathbf{y} = [c_1, c_2]\) and a vector valued function \(\mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} k_1 c_1 \\ k_2 c_2 \end{bmatrix}\), we are left with the standard form of a explicit first order ODE system:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
This is an explicit equation for the derivative of the state, \(\frac{d\mathbf{y}}{dt}\), as a function of the state variables \(\mathbf{y}\) and of time \(t\).
We need one more piece of information to solve this system of ODEs: the initial conditions for the populations at time \(t = 0\). For example, if we started with a concentration of 10 for the first population and 5 for the second population, we would write:
\[ \mathbf{y}(0) = \begin{bmatrix} 10 \\ 5 \end{bmatrix} \]
Many ODE solver libraries, like diffsol, require users to provide their ODEs in the form of a set of explicit first order ODEs. Given both the system of ODEs and the initial conditions, the solver can then integrate the equations forward in time to find the solution \(\mathbf{y}(t)\). This is the general process for solving ODEs, so it is important to know how to translate your problem into a set of first order ODEs, and thus to the general form of a explicit first order ODE system shown above. In the next two sections, we will look at an example of a first order ODE system in the area of population dynamics, and then solve it using diffsol.
Population Dynamics - Predator-Prey Model
In this example, we will model the population dynamics of a predator-prey system using a set of first order ODEs. The Lotka-Volterra equations are a classic example of a predator-prey model, and describe the interactions between two species in an ecosystem. The first species is a prey species, which we will call \(x\), and the second species is a predator species, which we will call \(y\).
The rate of change of the prey population is governed by two terms: growth and predation. The growth term represents the natural increase in the prey population in the absence of predators, and is proportional to the current population of prey. The predation term represents the rate at which the predators consume the prey, and is proportional to the product of the prey and predator populations. The rate of change of the prey population can be written as:
\[ \frac{dx}{dt} = a x - b x y \]
where \(a\) is the growth rate of the prey population, and \(b\) is the predation rate.
The rate of change of the predator population is also governed by two terms: death and growth. The death term represents the natural decrease in the predator population in the absence of prey, and is proportional to the current population of predators. The growth term represents the rate at which the predators reproduce, and is proportional to the product of the prey and predator populations, since the predators need to consume the prey to reproduce. The rate of change of the predator population can be written as:
\[ \frac{dy}{dt} = c x y - d y \]
where \(c\) is the reproduction rate of the predators, and \(d\) is the death rate.
The Lotka-Volterra equations are a simple model of predator-prey dynamics, and make several assumptions that may not hold in real ecosystems. For example, the model assumes that the prey population grows exponentially in the absence of predators, that the predator population decreases linearly in the absence of prey, and that the spatial distribution of the species has no effect. Despite these simplifications, the Lotka-Volterra equations capture some of the essential features of predator-prey interactions, such as oscillations in the populations and the dependence of each species on the other. When modelling with ODEs, it is important to consider the simplest model that captures the behaviour of interest, and to be aware of the assumptions that underlie the model.
Putting the two equations together, we have a system of two first order ODEs:
\[ \frac{dx}{dt} = a x - b x y \\ \frac{dy}{dt} = c x y - d y \]
which can be written in vector form as:
\[ \begin{bmatrix} \frac{dx}{dt} \\ \frac{dy}{dt} \end{bmatrix} = \begin{bmatrix} a x - b x y \\ c x y - d y \end{bmatrix} \]
or in the general form of a first order ODE system:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
where
\[\mathbf{y} = \begin{bmatrix} x \\ y \end{bmatrix} \]
and
\[\mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} a x - b x y \\ c x y - d y \end{bmatrix}\]
We also have initial conditions for the populations at time \(t = 0\). We can set both populations to 1 at the start like so:
\[ \mathbf{y}(0) = \begin{bmatrix} 1 \\ 1 \end{bmatrix} \]
Let's solve this system of ODEs using the diffsol crate. First we will define a few types to set our matrix type (dense nalgebra with f64),
the linear solver type (nalgebra LU, only used for the BDF solver below), and our DiffSL JIT backend (cranelift, only used for the DiffSL problem definition).
type M = diffsol::NalgebraMat<f64>;
type LS = diffsol::NalgebraLU<f64>;
type CG = CraneliftJitModule;
The equations can be specified with either the DiffSL domain-specific language or Rust closures. For the rust closure examples, we will defined a varient that is suitable for the implicit solvers (need to provide the Jacobian vector product), and one that is only suitable for explicit solvers. All definitions expose \(y_0\) as their single input parameter, which sets both initial populations. We'll use this input later on to generate a phase plane plot.
OdeBuilder::<M>::new()
.p([y0])
.build_from_diffsl::<CG>(
"
in { y0 = 1.0 }
a { 2.0/3.0 } b { 4.0/3.0 } c { 1.0 } d { 1.0 }
u_i {
y1 = y0,
y2 = y0,
}
F_i {
a * y1 - b * y1 * y2,
c * y1 * y2 - d * y2,
}
",
)
.unwrap()
The DiffSL and implicit Rust-closure definitions can use a BDF solver, whereas the explicit Rust-closure definition must use the TSIT45 solver, which uses an explicit runge-kutta method. Note that the BDF solver also requires a linear solver type (LS).
let mut solver = problem.bdf::<LS>().unwrap();
let (ys, ts, _stop_reason) = solver.solve(40.0).unwrap();
let prey: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let predator: Vec<_> = ys.inner().row(1).into_iter().copied().collect();
let time: Vec<_> = ts.into_iter().collect();
let prey = Scatter::new(time.clone(), prey)
.mode(Mode::Lines)
.name("Prey");
let predator = Scatter::new(time, predator)
.mode(Mode::Lines)
.name("Predator");
let mut plot = Plot::new();
plot.add_trace(prey);
plot.add_trace(predator);
let layout = Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new().title("population"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("prey-predator"));
fs::write("book/src/primer/images/prey-predator.html", plot_html)
.expect("Unable to write file");
A phase plane plot of the predator-prey system is a useful visualisation of the dynamics of the system. This plot shows the prey population on the x-axis and the predator population on the y-axis. Trajectories in the phase plane represent the evolution of the populations over time. Lets reframe the equations to introduce a new parameter \(y_0\) which is the initial predator and prey population. We can then plot the phase plane for different values of \(y_0\) to see how the system behaves for different initial conditions.
Our initial conditions are now:
\[ \mathbf{y}(0) = \begin{bmatrix} y_0 \\ y_0 \end{bmatrix} \]
so we can solve this system for different values of \(y_0\) and plot the phase plane for each case. We will use similar code as above, but we will introduce our new parameter and loop over different values of \(y_0\)
let mut plot = Plot::new();
for y0 in (1..6).map(f64::from) {
let p = NalgebraVec::from_element(1, y0, *problem.context());
problem.eqn_mut().set_params(&p);
let mut solver = problem.bdf::<LS>().unwrap();
let (ys, _ts, _stop_reason) = solver.solve(40.0).unwrap();
let prey: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let predator: Vec<_> = ys.inner().row(1).into_iter().copied().collect();
let phase = Scatter::new(prey, predator)
.mode(Mode::Lines)
.name(format!("y0 = {y0}"));
plot.add_trace(phase);
}
let layout = Layout::new()
.x_axis(Axis::new().title("x"))
.y_axis(Axis::new().title("y"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("prey-predator2"));
fs::write("book/src/primer/images/prey-predator2.html", plot_html)
.expect("Unable to write file");
Higher Order ODEs
The order of an ODE is the highest derivative that appears in the equation. So far, we have only looked at first order ODEs, which involve only the first derivative of the state variable with respect to time. However, many physical systems are described by higher order ODEs, which involve second or higher derivatives of the state variable. A simple example of a second order ODE is the motion of a mass under the influence of gravity. The equation of motion for the mass can be written as:
\[ \frac{d^2x}{dt^2} = -g \]
where \(x\) is the position of the mass, \(t\) is time, and \(g\) is the acceleration due to gravity. This is a second order ODE because it involves the second derivative of the position with respect to time.
Higher order ODEs can always be rewritten as a system of first order ODEs by introducing new variables. For example, we can rewrite the second order ODE above as a system of two first order ODEs by introducing a new variable for the velocity of the mass:
\[ \begin{align*} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= -g \end{align*} \]
where \(v = \frac{dx}{dt}\) is the velocity of the mass. This is a system of two first order ODEs, which can be written in vector form as:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
where
\[ \mathbf{y} = \begin{bmatrix} x \\ v \end{bmatrix} \]
and
\[ \mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} v \\ -g \end{bmatrix} \]
In the next section, we'll look at another example of a higher order ODE system: the spring-mass system, and solve this using diffsol.
Example: Spring-mass systems
We will model a damped spring-mass system using a second order ODE. The system consists of a mass \(m\) attached to a spring with spring constant \(k\), and a damping force proportional to the velocity of the mass with damping coefficient \(c\).
The equation of motion for the mass can be written as:
\[ m \frac{d^2x}{dt^2} = -k x - c \frac{dx}{dt} \]
where \(x\) is the position of the mass, \(t\) is time, and the negative sign on the right hand side indicates that the spring force and damping force act in the opposite direction to the displacement of the mass.
We can convert this to a system of two first order ODEs by introducing a new variable for the velocity of the mass:
\[ \begin{align*} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= -\frac{k}{m} x - \frac{c}{m} v \end{align*} \]
where \(v = \frac{dx}{dt}\) is the velocity of the mass.
We can specify the equations with either DiffSL or Rust closures. Both variants use the same solver and plotting code.
OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(
"
k { 1.0 } m { 1.0 } c { 0.1 }
u_i {
x = 1,
v = 0,
}
F_i {
v,
-k/m * x - c/m * v,
}
",
)
.unwrap()
Once we have defined our problem, we can create a solver, solve and then plot the solution.
let mut solver = problem.bdf::<LS>().unwrap();
let (ys, ts, _stop_reason) = solver.solve(40.0).unwrap();
let x: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let time: Vec<_> = ts.into_iter().collect();
let x_line = Scatter::new(time.clone(), x).mode(Mode::Lines);
let mut plot = Plot::new();
plot.add_trace(x_line);
let layout = Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new().title("x"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("sping-mass-system"));
fs::write("book/src/primer/images/spring-mass-system.html", plot_html)
.expect("Unable to write file");
Discrete Events
ODEs describe the continuous evolution of a system over time, but many systems also involve discrete events that occur at specific times. For example, in a compartmental model of drug delivery, the administration of a drug is a discrete event that occurs at a specific time. In a bouncing ball model, the collision of the ball with the ground is a discrete event that changes the state of the system. It is normally difficult to model these events using ODEs alone, as they require a different approach to handle the discontinuities in the system. While we can represent discrete events mathematically using delta functions, many ODE solvers are not designed to handle discontinuities, and may produce inaccurate results or fail to converge during the integration.
diffsol provides two ways to model discrete events in a system of ODEs:
- Use the event handling feature to detect when a discrete event occurs, and then manually update the state of the system in Rust. This is a straightforward procedural approach, but if you want to calculate sensitivities with respect to the parameters, you need to propagate the event correction yourself.
- Use the DiffSL language to specify the
stopconditions andresetactions that occur when a discrete event happens. This is a declarative approach that allows you to describe mathematically when a discrete event occurs and what happens when it does. For ordinary forward solves,solveandsolve_densewill then apply the reset automatically and continue the integration.
Procedural Approach
diffsol allows you to manipulate the internal state of each solver during the time-stepping. Each solver has an internal state that holds information such as the current time \(t\), the current state of the system \(\mathbf{y}\), and other solver-specific information. When a discrete event occurs, the user can update the internal state of the solver to reflect the change in the system, and then continue the integration of the ODE as normal.
diffsol also provides a way to stop the integration of the ODEs, either at a specific time or when a specific condition is met, by defining a function \(s\) that is equal to zero when the event occurs. This can be useful for modelling systems with discrete events, as it allows the user to control the integration of the ODEs and to handle the events in a flexible way.
\[ s(\mathbf{y}, t, \mathbf{p}) = 0 \]
In DiffSL, the stop tensor is used to define the event function \(s\). The Solving the Problem and Root Finding sections provide an introduction to the API for solving ODEs and detecting events with diffsol.
Declarative Approach
Rather than writing the event logic directly in Rust, it is also possible to write down the mathematical conditions for when an event occurs and what happens when it does. To define when an event occurs, we re-introduce a stop condition that triggers when the following condition is met:
\[ s(\mathbf{y}, t_e, \mathbf{p}) = 0 \]
We can then specify that, when this condition is met, the state of the system should be updated according to a reset function:
\[ \mathbf{y}^+ = \mathbf{r}(\mathbf{y}^-, t_e, \mathbf{p}) \]
In DiffSL, the stop tensor stores one or more event functions, while the reset tensor stores the post-event state. The reset tensor must have the same shape as the state tensor u, while the stop tensor can contain any number of scalar event conditions.
When a stop condition fires, diffsol first locates the event time accurately. For forward solves with solve, solve_dense, or solve_dense_sensitivities, if a reset tensor is present then the reset is applied automatically and the integration continues. Manual time-stepping with step and the staged solve APIs expose the event to the caller, so you can handle the event yourself. The checkpointed solves (solve_with_checkpointing and solve_dense_with_checkpointing) apply the reset automatically, and the continuous adjoint applies the adjoint of the reset during the backward solve. The discrete gradients (solve_dense_vjp and the related methods) do not support roots, so you cannot use them with events.
In the next two sections, we revisit compartmental models of drug delivery and bouncing-ball dynamics and show both the procedural and declarative versions side by side.
Example: Compartmental models of Drug Delivery
The field of Pharmacokinetics (PK) provides a quantitative basis for describing the delivery of a drug to a patient, the diffusion of that drug through the plasma/body tissue, and the subsequent clearance of the drug from the patient's system. PK is used to ensure that there is sufficient concentration of the drug to maintain the required efficacy of the drug, while ensuring that the concentration levels remain below the toxic threshold. Pharmacokinetic (PK) models are often combined with Pharmacodynamic (PD) models, which model the positive effects of the drug, such as the binding of a drug to the biological target, and/or undesirable side effects, to form a full PKPD model of the drug-body interaction. This example will only focus on PK, neglecting the interaction with a PD model.

PK enables the following processes to be quantified:
- Absorption
- Distribution
- Metabolism
- Excretion
These are often referred to as ADME, and taken together describe the drug concentration in the body when medicine is prescribed. These ADME processes are typically described by zeroth-order or first-order rate reactions modelling the dynamics of the quantity of drug \(q\), with a given rate parameter \(k\), for example:
\[ \frac{dq}{dt} = -k^*, \]
\[ \frac{dq}{dt} = -k q. \]
The body itself is modelled as one or more compartments, each of which is defined as a kinetically homogeneous unit (these compartments do not relate to specific organs in the body, unlike Physiologically based pharmacokinetic, PBPK, modeling). There is typically a main central compartment into which the drug is administered and from which the drug is excreted from the body, combined with zero or more peripheral compartments to which the drug can be distributed to/from the central compartment (See Fig 2). Each peripheral compartment is only connected to the central compartment.
The following example PK model describes the two-compartment model shown diagrammatically in the figure above. The time-dependent variables to be solved are the drug quantity in the central and peripheral compartments, \(q_c\) and \(q_{p1}\) (units: [ng]) respectively.
\[ \frac{dq_c}{dt} = \text{Dose}(t) - \frac{q_c}{V_c} CL - Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ), \]
\[ \frac{dq_{p1}}{dt} = Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ). \]
This model describes an intravenous bolus dosing protocol, with a linear clearance from the central compartment (non-linear clearance processes are also possible, but not considered here). The dose function \(\text{Dose}(t)\) will consist of instantaneous doses of \(X\) ng of the drug at one or more time points. The other input parameters to the model are:
- \(V_c\) [mL], the volume of the central compartment
- \(V_{p1}\) [mL], the volume of the first peripheral compartment
- \(CL\) [mL/h], the clearance/elimination rate from the central compartment
- \(Q_{p1}\) [mL/h], the transition rate between central compartment and peripheral compartment 1
We will solve this system of ODEs using the diffsol crate. Rather than trying to write down the dose function as a smooth mathematical function, we will treat each bolus dose as a discrete event. We first do this procedurally by stopping the solver at each dose time in Rust, then rewrite the same model declaratively using DiffSL stop and reset tensors.
First lets write down the equations in the standard form of a first order ODE system:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
where
\[ \mathbf{y} = \begin{bmatrix} q_c \\ q_{p1} \end{bmatrix} \]
and
\[ \mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} - \frac{q_c}{V_c} CL - Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ) \\ Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ) \end{bmatrix} \]
We will also need to specify the initial conditions for the system:
\[ \mathbf{y}(0) = \begin{bmatrix} 0 \\ 0 \end{bmatrix} \]
For the dose function, we will specify a dose of 1000 ng at regular intervals of 6 hours, at \(t = 0\), \(6\), \(12\) and \(18\) hours. The simulation ends at \(t = 24\) hours. We will also specify the other parameters of the model:
\[ V_c = 1000 \text{ mL}, \quad V_{p1} = 1000 \text{ mL}, \quad CL = 100 \text{ mL/h}, \quad Q_{p1} = 50 \text{ mL/h} \]
Procedural approach
To implement the discrete dose events procedurally, we set a stop time for the simulation at each dose event using the OdeSolverMethod::set_stop_time method. During time-stepping we can check the return value of the OdeSolverMethod::step method to see if the solver has reached the stop time. If it has, we apply the dose directly to the state and continue the simulation. After the last dose, we solve to the final time of 24 hours.
use diffsol::{CraneliftJitModule, OdeBuilder, OdeSolverMethod, OdeSolverStopReason};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(
"
Vc { 1000.0 } Vp1 { 1000.0 } CL { 100.0 } Qp1 { 50.0 }
u_i {
centralamount = 0,
peripheralamount = 0,
}
F_i {
- centralamount / Vc * CL - Qp1 * (centralamount / Vc - peripheralamount / Vp1),
Qp1 * (centralamount / Vc - peripheralamount / Vp1),
}
",
)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let doses = vec![(0.0, 1000.0), (6.0, 1000.0), (12.0, 1000.0), (18.0, 1000.0)];
let mut central_amount = Vec::new();
let mut peripheral_amount = Vec::new();
let mut time = Vec::new();
// apply the first dose and save the initial state
solver.state_mut().y[0] = doses[0].1;
central_amount.push(solver.state().y[0]);
peripheral_amount.push(solver.state().y[1]);
time.push(0.0);
// solve to each remaining dose time and apply the dose,
// then solve to the final time (a zero dose at t = 24 h)
let final_time = 24.0;
let segments = doses
.into_iter()
.skip(1)
.chain(std::iter::once((final_time, 0.0)));
for (t, dose) in segments {
solver.set_stop_time(t).unwrap();
loop {
let ret = solver.step();
central_amount.push(solver.state().y[0]);
peripheral_amount.push(solver.state().y[1]);
time.push(solver.state().t);
match ret {
Ok(OdeSolverStopReason::InternalTimestep) => continue,
Ok(OdeSolverStopReason::TstopReached) => break,
_ => panic!("unexpected solver error"),
}
}
solver.state_mut().y[0] += dose;
}
let mut plot = Plot::new();
let central_amount = Scatter::new(time.clone(), central_amount)
.mode(Mode::Lines)
.name("central_amount");
let peripheral_amount = Scatter::new(time, peripheral_amount)
.mode(Mode::Lines)
.name("peripheral_amount");
plot.add_trace(central_amount);
plot.add_trace(peripheral_amount);
let layout = Layout::new()
.x_axis(Axis::new().title("t [h]"))
.y_axis(Axis::new().title("amount [ng]"));
plot.set_layout(layout);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/drug-delivery.html");
let plot_html = plot.to_inline_html(Some("drug-delivery"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
Declarative approach
The same dosing schedule can also be encoded directly in DiffSL. Here the initial condition includes the first dose at \(t=0\), the stop tensor contains the later dosing times \(t = 6\), \(12\), and \(18\) hours, and the reset tensor adds the bolus amount to the central compartment whenever any of those stop conditions fires.
Because the model supplies both stop and reset, the high-level solve method now applies each declarative dose automatically and continues through the full 24 hour simulation.
use diffsol::{CraneliftJitModule, MatrixCommon, OdeBuilder, OdeSolverMethod};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let model = "
Vc { 1000.0 } Vp1 { 1000.0 } CL { 100.0 } Qp1 { 50.0 } dose { 1000.0 }
u_i {
qc = dose,
qp1 = 0,
}
F_i {
-qc / Vc * CL - Qp1 * (qc / Vc - qp1 / Vp1),
Qp1 * (qc / Vc - qp1 / Vp1),
}
stop_i {
t - 6.0,
t - 12.0,
t - 18.0,
}
reset_i {
qc + dose,
qp1,
}
";
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(model)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let final_time = 24.0;
let (ys, time, _stop_reason) = solver.solve(final_time).unwrap();
let q_c: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let q_p1: Vec<_> = ys.inner().row(1).into_iter().copied().collect();
let mut plot = Plot::new();
plot.add_trace(
Scatter::new(time.clone(), q_c)
.mode(Mode::Lines)
.name("q_c"),
);
plot.add_trace(Scatter::new(time, q_p1).mode(Mode::Lines).name("q_p1"));
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("t [h]"))
.y_axis(Axis::new().title("amount [ng]")),
);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/drug-delivery-declarative.html");
let plot_html = plot.to_inline_html(Some("drug-delivery-declarative"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
Adjoints through declarative dose events
The automatic reset handling provided by the declarative approach is useful when the reset itself depends on an input parameter. In the drug-delivery model, we can make the bolus dose an input parameter by putting dose in the DiffSL in tensor. The initial condition uses the same dose for the dose at \(t=0\), and the reset tensor adds dose to the central compartment at later dosing times.
In this example we will integrate the output of the central-compartment concentration squared, \(AUC2 = \int_0^{24} (q_c / V_c)^2 dt\), and then use diffsol's adjoint capabilities to calculate the gradient of this integral with respect to the dose parameter. The integral of the squared concentration would not typically be of interest, but this example is slightly contrived so that the final gradient is not constant and the plots are non-trivial.
We solve the model forwards in time using checkpointing and extract AUC2 from the final solution, and then create the adjoint equations using the checkpoints and integrate backwards in time to the starting time point. The gradient of AUC2 with respect to dose is then extracted from sg on the final solver state. Repeating this for several dose levels gives the dose-response curve and its gradient.
DiffSL currently needs the LLVM backend for sensitivity-aware reset/root operators in this example.
use diffsol::{
AdjointOdeSolverMethod, DenseMatrix, LlvmModule, MatrixCommon, OdeBuilder, OdeEquations,
OdeSolverMethod, OdeSolverState, Op, Vector, VectorView,
};
use plotly::{common::AxisSide, common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type V = diffsol::NalgebraVec<f64>;
type CG = LlvmModule;
type LS = diffsol::NalgebraLU<f64>;
pub fn main() {
let model = r#"
in_i { dose = 1000.0 }
Vc { 1000.0 } Vp1 { 1000.0 } CL { 100.0 } Qp1 { 50.0 }
u_i {
qc = dose,
qp1 = 0,
}
F_i {
-qc / Vc * CL - Qp1 * (qc / Vc - qp1 / Vp1),
Qp1 * (qc / Vc - qp1 / Vp1),
}
stop_i {
t - 6.0,
t - 12.0,
t - 18.0,
}
reset_i {
qc + dose,
qp1,
}
out_i {
pow(qc / Vc, 2),
}
"#;
let final_time = 24.0;
let dose_levels = (0..=12)
.map(|i| 250.0 + f64::from(i) * 125.0)
.collect::<Vec<_>>();
let mut problem = OdeBuilder::<M>::new()
.p([dose_levels[0]])
.sens_atol([1e-8])
.sens_rtol(1e-8)
.out_atol([1e-8])
.out_rtol(1e-8)
.integrate_out(true)
.build_from_diffsl::<CG>(model)
.unwrap();
let mut aucs = Vec::with_capacity(dose_levels.len());
let mut auc_grads = Vec::with_capacity(dose_levels.len());
for &dose in &dose_levels {
let ctx = *problem.eqn().context();
problem.eqn_mut().set_params(&V::from_vec(vec![dose], ctx));
let mut solver = problem.bdf::<LS>().unwrap();
let (checkpoints, integrated_output, _output_times, _stop_reason) =
solver.solve_with_checkpointing(final_time, None).unwrap();
let auc = integrated_output.get_index(0, integrated_output.ncols() - 1);
let adjoint_solver = problem
.bdf_solver_adjoint::<LS, _>(checkpoints, Some(solver), None)
.unwrap();
let (adjoint_state, _) = adjoint_solver
.solve_adjoint_backwards_pass(&[], &[])
.unwrap();
aucs.push(auc);
auc_grads.push(adjoint_state.as_ref().sg.get_batch(0).get_index(0));
}
let mut plot = Plot::new();
plot.add_trace(
Scatter::new(dose_levels.clone(), aucs)
.mode(Mode::LinesMarkers)
.name("AUC2"),
);
plot.add_trace(
Scatter::new(dose_levels, auc_grads)
.mode(Mode::LinesMarkers)
.name("dAUC2/ddose")
.y_axis("y2"),
);
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("dose [ng]"))
.y_axis(Axis::new().title("AUC2 [ng^2 h / mL^2]"))
.y_axis2(
Axis::new()
.title("dAUC2/ddose [ng h / mL^2]")
.overlaying("y")
.side(AxisSide::Right)
.position(1.0),
),
);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/drug-delivery-dose-sensitivity.html");
let plot_html = plot.to_inline_html(Some("drug-delivery-dose-sensitivity"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
Example: Bouncing Ball
Modelling a bouncing ball is a simple and intuitive example of a system with discrete events. The ball is dropped from a height \(h\) and bounces off the ground with a coefficient of restitution \(e\). When the ball hits the ground, its velocity is reversed and scaled by the coefficient of restitution, and the ball rises and then continues to fall until it hits the ground again. This process repeats until halted.
The second order ODE that describes the motion of the ball is given by:
\[ \frac{d^2x}{dt^2} = -g \]
where \(x\) is the position of the ball, \(t\) is time, and \(g\) is the acceleration due to gravity. We can rewrite this as a system of two first order ODEs by introducing a new variable for the velocity of the ball:
\[ \begin{align*} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= -g \end{align*} \]
where \(v = \frac{dx}{dt}\) is the velocity of the ball. This is a system of two first order ODEs, which can be written in vector form as:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
where
\[ \mathbf{y} = \begin{bmatrix} x \\ v \end{bmatrix} \]
and
\[ \mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} v \\ -g \end{bmatrix} \]
The initial conditions for the ball, including the height from which it is dropped and its initial velocity, are given by:
\[ \mathbf{y}(0) = \begin{bmatrix} h \\ 0 \end{bmatrix} \]
When the ball hits the ground, we need to update the velocity of the ball according to the coefficient of restitution, which is the ratio of the velocity after the bounce to the velocity before the bounce. The velocity after the bounce \(v'\) is given by:
\[ v' = -e v \]
where \(e\) is the coefficient of restitution. We will first implement this using diffsol's procedural event-handling API, then rewrite the same event declaratively using the DiffSL stop and reset tensors.
Procedural approach
To implement the bounce in Rust, we need to detect when the ball hits the ground. We can do this by using diffsol's event handling feature, which allows us to specify a function that is equal to zero when the event occurs, i.e. when the ball hits the ground. This function \(s(\mathbf{y}, t)\) is called an event or root function, and for our bouncing ball problem, it is given by:
\[ s(\mathbf{y}, t) = x \]
where \(x\) is the position of the ball. When the ball hits the ground, the event function will be zero and diffsol will stop the integration, and we can update the velocity of the ball accordingly.
In code, the bouncing ball problem can be solved using diffsol as follows:
use diffsol::{CraneliftJitModule, OdeBuilder, OdeSolverMethod, OdeSolverStopReason, Vector};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::fs;
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let e = 0.8;
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(
"
g { 9.81 } h { 10.0 }
u_i {
position = h,
velocity = 0,
}
F_i {
velocity,
-g,
}
stop {
position,
}
",
)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let mut position = Vec::new();
let mut velocity = Vec::new();
let mut t = Vec::new();
let final_time = 10.0;
// save the initial state
position.push(solver.state().y[0]);
velocity.push(solver.state().y[1]);
t.push(0.0);
// solve until the final time is reached
solver.set_stop_time(final_time).unwrap();
loop {
match solver.step() {
Ok(OdeSolverStopReason::InternalTimestep) => (),
Ok(OdeSolverStopReason::RootFound(t, _idx)) => {
// get the state when the event occurred
let mut y = solver.interpolate(t).unwrap();
// update the velocity of the ball
y[1] *= -e;
// make sure the ball is above the ground
y[0] = y[0].max(f64::EPSILON);
// set the state to the updated state
solver.state_mut().y.copy_from(&y);
solver.state_mut().dy[0] = y[1];
*solver.state_mut().t = t;
}
Ok(OdeSolverStopReason::TstopReached) => break,
Err(_) => panic!("unexpected solver error"),
}
position.push(solver.state().y[0]);
velocity.push(solver.state().y[1]);
t.push(solver.state().t);
}
let mut plot = Plot::new();
let position = Scatter::new(t.clone(), position)
.mode(Mode::Lines)
.name("position");
let velocity = Scatter::new(t, velocity).mode(Mode::Lines).name("velocity");
plot.add_trace(position);
plot.add_trace(velocity);
let layout = Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new());
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("bouncing-ball"));
fs::write("../src/primer/images/bouncing-ball.html", plot_html).expect("Unable to write file");
}
Declarative approach
In DiffSL, we can move the event definition into the model itself. The stop tensor declares that an event occurs when x = 0, and the reset tensor declares the post-impact state. In this version we also reset the position to a very small positive value so that the next step starts just above the ground and does not immediately retrigger the same event.
Because the model provides both stop and reset, the high-level solve call now handles each bounce automatically. The example can therefore solve straight to the final time and read the returned trajectory directly.
use diffsol::{CraneliftJitModule, MatrixCommon, OdeBuilder, OdeSolverMethod};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let model = "
restitution { 0.8 } xeps { 1e-12 }
g { 9.81 } h { 10.0 }
u_i {
position = h,
velocity = 0,
}
F_i {
velocity,
-g,
}
stop_i {
position,
}
reset_i {
xeps,
-restitution * velocity,
}
";
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(model)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let final_time = 10.0;
let (ys, t, _stop_reason) = solver.solve(final_time).unwrap();
let x: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let v: Vec<_> = ys.inner().row(1).into_iter().copied().collect();
let mut plot = Plot::new();
plot.add_trace(Scatter::new(t.clone(), x).mode(Mode::Lines).name("x"));
plot.add_trace(Scatter::new(t, v).mode(Mode::Lines).name("v"));
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new()),
);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/bouncing-ball-declarative.html");
let plot_html = plot.to_inline_html(Some("bouncing-ball-declarative"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
Hybrid ODEs
Thus far we have considered ODEs that have a single behaviour over time and have introduced discrete events as a way to model systems that have sudden changes in behaviour. However, many systems have multiple modes of behaviour that are active at different times, which we will refer to as hybrid ODEs. These modes could be different discrete events (e.g. dosing protocols) or could be entirely different ODE dynamics (e.g. an epidemic model with policy switching).
In order to model these systems, we will extend our first order ODE formulation to encompass a set of ODEs that are indexed by a discrete variable \(N\). This variable can be thought of as a "model index" that determines which ODE is active at any given time. The dynamics of the system are then governed by the following equations:
\[ \begin{align*} \frac{d\mathbf{y}}{dt} &= \mathbf{f}_N(\mathbf{y}, t, \mathbf{p}) \\ \mathbf{y}(0) &= \mathbf{y}_0 \end{align*} \]
with stopping and reset conditions defined by the functions \(\mathbf{r}_N\) and \(\mathbf{s}_N\) as follows:
\[ \mathbf{y}^+ = \mathbf{r}_N(\mathbf{y}^-, t_e, \mathbf{p}), \quad \text{when} \quad 0 = \mathbf{s}_N(\mathbf{y}, t_e, \mathbf{p}) \]
With this in place, we only have to decide on the rules for switching between the different ODEs using the model index \(N\). There are many ways to do this, and diffsol is flexible enough to allow users to implement their own switching rules. However, one approach (which is the approach used in diffsol wrappers like diffsol-c and pydiffsol), is to start (i.e. at time \(t=0\)) with \(N=0\) and then to switch to the next ODE (i.e. \(N=i\)) based on the index of the stopping condition that is satisfied (note that \(\mathbf{s}_N\) is a vector of stopping conditions). This process is repeated until we have reached the end of the time interval of interest.
To illustrate this using some concrete diffsl examples, we will consider a few examples of hybrid ODEs in the next sections, including a simple dosing protocol and an epidemic model with policy switching.
Example: Dosing Protocols
In compartmental models of drug delivery we introduced a simple two-compartment model of drug delivery. The model consists of a central compartment and a peripheral compartment. Transitions between the two compartments and the elimination of the drug from the central compartment are governed by the following equations:
\[ \frac{dq_c}{dt} = \text{Dose}(t) - \frac{q_c}{V_c} CL - Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ), \]
\[ \frac{dq_{p1}}{dt} = Q_{p1} \left ( \frac{q_c}{V_c} - \frac{q_{p1}}{V_{p1}} \right ). \]
We want to use a hybrid model with stopping conditions and a reset condition to model a three dose protocol, where each dose has a different level. The doses are given at times \(t_0 = 0\), \(t_1 = 6\) and \(t_2 = 12\) hours, and the dose levels are \(d_0 = 1000\), \(d_1 = 500\) and \(d_2 = 2000\) ng. The simulation ends at \(t = 24\) hours. To do this, we can encode the stopping conditions as follows:
\[ \mathbf{s}(\mathbf{y}, t) = \begin{bmatrix} 1 \\ t - t_1 \\ t - t_2 \end{bmatrix} \]
The model starts at \(t_0\) with the model index \(N = 0\). The first stopping condition is never satisfied, because we never want to transition to \(N=0\) (this is the starting value). The other stopping conditions are satisfied at \(t_1\) and \(t_2\). When a stopping condition is satisfied, we set \(N\) to the index of that condition (the root index). The reset condition is then:
\[ \mathbf{r}(\mathbf{y}) = \begin{bmatrix} q_c + \mathbf{d}N \\ q{p1} \end{bmatrix} \]
where \(\mathbf{d} = [d_0, d_1, d_2]\) is the vector of dose levels, and \(\mathbf{d}_N\) is the dose level with index \(N\). Thus at \(t_1\) the reset adds \(d_1\), and at \(t_2\) the reset adds \(d_2\), to the amount of drug in the central compartment. The amount of drug in the peripheral compartment does not change.
The initial conditions include the first dose \(d_0\):
\[ \mathbf{y}(0) = \begin{bmatrix}\mathbf{d}_0 \\ 0 \end{bmatrix} \]
To implement this in diffsol we will use the diffsl language to write down the ODE equations, stop conditions and reset functions. Then we will use the Solution and solve_soln methods to step through the segments of the hybrid model.
Solution is a struct for iteratively building up a solution from multiple segments, and solve_soln is the method that (a) runs a solve for each segment, and (b) appends the solve result to the Solution arg. After each segment we move out the internal state of the solver. This drops the solver, which contains a reference to the problem, so that we can then mutate the problem by setting the new model index based on the index of the root found in the previous call to solve_soln. Then we can apply our reset condition to the state, and create another solver with this state in order to continue the iteration.
Note that we could have mutated other aspects of the problem/solver at each stage if we wished, setting parameters, changing solver methods or tolerances, based on how we wanted to implement our hybrid model. In this case our only rule is that N is to be set to the index of the previous found root, before the reset is applied.
use diffsol::{
CraneliftJitModule, MatrixCommon, OdeBuilder, OdeEquations, OdeSolverMethod, OdeSolverState,
OdeSolverStopReason, Solution,
};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let model = "
Vc { 1000.0 } Vp1 { 1000.0 } CL { 100.0 } Qp1 { 50.0 }
doses_i { 1000.0, 500.0, 2000.0}
u_i {
qc = doses_i[0],
qp1 = 0,
}
F_i {
-qc / Vc * CL - Qp1 * (qc / Vc - qp1 / Vp1),
Qp1 * (qc / Vc - qp1 / Vp1),
}
stop_i {
1.0,
t - 6.0,
t - 12.0,
}
reset_i {
qc + doses_i[N],
qp1,
}
";
let mut problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(model)
.unwrap();
let final_time = 24.0;
let mut soln = Solution::new(final_time);
let mut state = problem.bdf_state::<LS>().unwrap();
while !soln.is_complete() {
state = problem
.bdf_solver::<LS>(state)
.unwrap()
.solve_soln(&mut soln)
.unwrap()
.into_state();
if let Some(OdeSolverStopReason::RootFound(_t_root, root_idx)) = soln.stop_reason {
problem.eqn_mut().set_model_index(root_idx);
state
.as_mut()
.apply_reset_with_mass::<LS, _>(&problem)
.unwrap();
}
}
let time = soln.ts.clone();
let q_c: Vec<_> = soln.ys.inner().row(0).into_iter().copied().collect();
let q_p1: Vec<_> = soln.ys.inner().row(1).into_iter().copied().collect();
let mut plot = Plot::new();
plot.add_trace(
Scatter::new(time.clone(), q_c)
.mode(Mode::Lines)
.name("q_c"),
);
plot.add_trace(Scatter::new(time, q_p1).mode(Mode::Lines).name("q_p1"));
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("t [h]"))
.y_axis(Axis::new().title("amount [ng]")),
);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/drug-delivery-hybrid.html");
let plot_html = plot.to_inline_html(Some("drug-delivery-hybrid"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
Example: Epidemic SIR with policy switching
The SIR model is a simple epidemic model that divides a population into susceptible, infected, and recovered compartments. In this example we will use it to illustrate a hybrid model where the transmission rate changes when a public-health policy switches on or off.
Let
\[ \mathbf{y} = \begin{bmatrix} S \\ I \\ R \end{bmatrix} \]
where \(S\) is the susceptible population, \(I\) is the infected population, and \(R\) is the recovered population. For a population of size \(P\), recovery rate \(\gamma\), and transmission rate \(\beta\), the standard SIR equations are
\[ \begin{align} \frac{dS}{dt} &= -\beta \frac{SI}{P}, \\ \frac{dI}{dt} &= \beta \frac{SI}{P} - \gamma I, \\ \frac{dR}{dt} &= \gamma I. \end{align} \]
To model policy switching, we will make \(\beta\) depend on a discrete model index \(N\). The open-policy mode has a larger transmission rate, and the lockdown mode has a smaller transmission rate:
\[ \beta_N = \begin{cases} \beta_\text{open}, & N = 0, \\ \beta_\text{lockdown}, & N = 1. \end{cases} \]
The policy uses hysteresis so that lockdown is not switched on and off at the same threshold. Starting in the open-policy mode, lockdown starts when the infected population rises above a high threshold \(I_\text{high}\). Once lockdown is active, it remains active until the infected population falls below a lower threshold \(I_\text{low}\):
\[ N^+ = \begin{cases} 1, & N^- = 0 \text{ and } I = I_\text{high}, \\ 0, & N^- = 1 \text{ and } I = I_\text{low}. \end{cases} \]
We encode this with a vector of two stopping conditions. Both conditions are active in both modes:
\[ \mathbf{s}(\mathbf{y}, t) = \begin{bmatrix} I - I_\text{low} \\ I - I_\text{high} \end{bmatrix} \]
When a stopping condition is satisfied, we set \(N\) to the index of that condition (the root index). Thus \(I = I_\text{low}\) (index 0) sets the open-policy mode, and \(I = I_\text{high}\) (index 1) sets the lockdown mode. If the infected population crosses a threshold that gives the current mode, \(N\) does not change. This gives the hysteresis above.
The example uses \(P = 1000\), \(\gamma = 0.1\), \(\beta_\text{open} = 0.3\), \(\beta_\text{lockdown} = 0.08\), \(I_\text{low} = 20\) and \(I_\text{high} = 100\). The initial state is \(S = 999\), \(I = 1\) and \(R = 0\), and the simulation ends at \(t = 300\) days.
In DiffSL we write the two transmission rates and two thresholds as vectors. The transmission rate uses the index N. As for the dosing model, we use a Solution struct and solve_soln methods to step through the different segments of the hybrid model. After each segment, we use the root index found (root_idx) to set the value for \(N\).
use diffsol::{
CraneliftJitModule, MatrixCommon, OdeBuilder, OdeEquations, OdeSolverMethod,
OdeSolverStopReason, Solution,
};
use plotly::{
common::{AxisSide, Line, LineShape, Mode},
layout::{Axis, Layout},
Plot, Scatter,
};
use std::{fs, path::PathBuf};
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let model = "
population { 1000.0 }
gamma { 0.1 }
beta_i {
0.3,
0.08,
}
threshold_i {
20.0,
100.0,
}
u_i {
S = 999.0,
I = 1.0,
R = 0.0,
}
F_i {
-beta_i[N] * S * I / population,
beta_i[N] * S * I / population - gamma * I,
gamma * I,
}
stop_i {
I - threshold_i,
}
";
let mut problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(model)
.unwrap();
let final_time = 300.0;
let mut soln = Solution::new(final_time);
let mut state = problem.bdf_state::<LS>().unwrap();
let mut switch_times = vec![(0.0, 0)];
while !soln.is_complete() {
state = problem
.bdf_solver::<LS>(state)
.unwrap()
.solve_soln(&mut soln)
.unwrap()
.into_state();
if let Some(OdeSolverStopReason::RootFound(t_root, root_idx)) = soln.stop_reason {
switch_times.push((t_root, root_idx));
problem.eqn_mut().set_model_index(root_idx);
}
}
let time = soln.ts.clone();
let susceptible: Vec<_> = soln.ys.inner().row(0).into_iter().copied().collect();
let infected: Vec<_> = soln.ys.inner().row(1).into_iter().copied().collect();
let recovered: Vec<_> = soln.ys.inner().row(2).into_iter().copied().collect();
let lockdown: Vec<_> = time
.iter()
.map(|t| {
switch_times
.iter()
.rev()
.find(|(switch_time, _)| switch_time <= t)
.map(|(_, index)| *index as f64)
.unwrap_or(0.0)
})
.collect();
let mut plot = Plot::new();
plot.add_trace(
Scatter::new(time.clone(), susceptible)
.mode(Mode::Lines)
.name("S"),
);
plot.add_trace(
Scatter::new(time.clone(), infected)
.mode(Mode::Lines)
.name("I"),
);
plot.add_trace(
Scatter::new(time.clone(), recovered)
.mode(Mode::Lines)
.name("R"),
);
plot.add_trace(
Scatter::new(time, lockdown)
.mode(Mode::Lines)
.name("lockdown")
.line(Line::new().shape(LineShape::Hv))
.y_axis("y2"),
);
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("t [days]"))
.y_axis(Axis::new().title("people"))
.y_axis2(
Axis::new()
.title("lockdown")
.range(vec![-0.05, 1.05])
.overlaying("y")
.side(AxisSide::Right)
.position(1.0),
),
);
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/sir-policy-switching.html");
let plot_html = plot.to_inline_html(Some("sir-policy-switching"));
fs::write(output_path, plot_html).expect("Unable to write file");
}
DAEs via the Mass Matrix
Differential-algebraic equations (DAEs) are a generalisation of ordinary differential equations (ODEs) that include algebraic equations, or equations that do not involve derivatives. Algebraic equations can arise in many physical systems and often are used to model constraints on the system, such as conservation laws or other relationships between the state variables. For example, in an electrical circuit, the current flowing into a node must equal the current flowing out of the node, which can be written as an algebraic equation.
DAEs can be written in the general implicit form:
\[ \mathbf{F}(\mathbf{y}, \mathbf{y}', t) = 0 \]
where \(\mathbf{y}\) is the vector of state variables, \(\mathbf{y}'\) is the vector of derivatives of the state variables, and \(\mathbf{F}\) is a vector-valued function that describes the system of equations. However, for the purposes of this primer and the capabilities of diffsol, we will focus on a specific form of DAEs called index-1 or semi-explicit DAEs, which can be written as a combination of differential and algebraic equations. We split the state variables into differential variables \(\mathbf{x}\) and algebraic variables \(\mathbf{z}\):
\[ \begin{align*} \frac{d\mathbf{x}}{dt} &= \mathbf{f}(\mathbf{x}, \mathbf{z}, t) \\ 0 &= \mathbf{g}(\mathbf{x}, \mathbf{z}, t) \end{align*} \]
where \(\mathbf{f}\) is the vector-valued function that describes the differential equations and \(\mathbf{g}\) is the vector-valued function that describes the algebraic equations. The key difference between DAEs and ODEs is that DAEs include algebraic equations that must be satisfied at each time step, in addition to the differential equations that describe the rate of change of the state variables. The system is index-1 when the Jacobian \(\partial \mathbf{g} / \partial \mathbf{z}\) is non-singular. Then the algebraic equations give a unique \(\mathbf{z}\) for each \(\mathbf{x}\) and \(t\).
How does this relate to the standard form of an explicit ODE that we have seen before? Recall that an explicit ODE can be written as:
\[ \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
Lets update this equation to include a matrix \(\mathbf{M}\) that multiplies the derivative term:
\[ M \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
When \(M\) is the identity matrix (i.e. a matrix with ones along the diagonal), this reduces to the standard form of an explicit ODE. However, when \(M\) has diagonal entries that are zero, this introduces algebraic equations into the system and it reduces to the semi-explicit DAE equations shown above. The matrix \(M\) is called the mass matrix.
Thus, we now have a general form of a set of differential equations, that includes both ODEs and semi-explicit DAEs. This general form is used by diffsol to allow users to specify a wide range of problems, from simple ODEs to more complex DAEs. In the next section, we will look at an example of a DAE and how to solve it using diffsol and a mass matrix.
Example: Electrical Circuits
Lets consider the following low-pass LRC filter circuit:
+---L---+---C---+
| | |
V_s = R |
| | |
+-------+-------+
The circuit consists of a resistor \(R\), an inductor \(L\), and a capacitor \(C\) connected to a voltage source \(V_s\). The voltage across the resistor \(V\) is given by Ohm's law:
\[ V = R i_R \]
where \(i_R\) is the current flowing through the resistor. The voltage across the inductor is \(V_s - V\), so the equation for an ideal inductor is:
\[ L \frac{di_L}{dt} = V_s - V \]
where \(di_L/dt\) is the rate of change of current with respect to time. The voltage across the capacitor is the same as the voltage across the resistor and the equation for an ideal capacitor is:
\[ \frac{dV}{dt} = \frac{i_C}{C} \]
where \(i_C\) is the current flowing through the capacitor. The sum of the currents flowing into and out of the top-center node of the circuit must be zero according to Kirchhoff's current law:
\[ i_L = i_R + i_C \]
Thus we have a system of two differential equations and two algebraic equations that describe the evolution of the currents through the resistor, inductor, and capacitor; and the voltage across the resistor. We can write these equations in the general form:
\[ M \frac{d\mathbf{y}}{dt} = \mathbf{f}(\mathbf{y}, t) \]
where
\[ \mathbf{y} = \begin{bmatrix} i_R \\ i_L \\ i_C \\ V \end{bmatrix} \]
and
\[ \mathbf{f}(\mathbf{y}, t) = \begin{bmatrix} V - R i_R \\ \frac{V_s - V}{L} \\ i_L - i_R - i_C \\ \frac{i_C}{C} \end{bmatrix} \]
The mass matrix \(M\) has one on the diagonal for the differential equations and zero for the algebraic equations.
\[ M = \begin{bmatrix} 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix} \]
Instead of providing the mass matrix explicitly, the DiffSL language specifies the multiplication of the mass matrix with the derivative term, \(M \frac{d\mathbf{y}}{dt}\), which is given by:
\[ M \frac{d\mathbf{y}}{dt} = \begin{bmatrix} 0 \\ \frac{di_L}{dt} \\ 0 \\ \frac{dV}{dt} \end{bmatrix} \]
The initial conditions for the system are:
\[ \mathbf{y}(0) = \begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \end{bmatrix} \]
The voltage source \(V_s\) acts as a forcing function for the system, and we can specify this as sinusoidal function of time.
\[ V_s(t) = V_0 \sin(\omega t) \]
where \(V_0\) is the amplitude and \(\omega\) is the angular frequency of the source. The example uses \(R = 100\), \(L = 1\), \(C = 10^{-3}\), \(V_0 = 10\) and \(\omega = 100\). The cut-off frequency of this filter is approximately \(1/\sqrt{LC} \approx 31.6\) rad/s. The source frequency is higher than the cut-off frequency, so the circuit filters the source signal.
We can solve this system of equations using diffsol and plot the current \(i_R\) through the resistor as a function of time.
use diffsol::{CraneliftJitModule, MatrixCommon, OdeBuilder, OdeSolverMethod};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::fs;
type M = diffsol::NalgebraMat<f64>;
type CG = CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(
"
R { 100.0 } L { 1.0 } C { 0.001 } V0 { 10 } omega { 100.0 }
Vs { V0 * sin(omega * t) }
u_i {
iR = 0,
iL = 0,
iC = 0,
V = 0,
}
dudt_i {
diRdt = 0,
diLdt = 0,
diCdt = 0,
dVdt = 0,
}
M_i {
0,
diLdt,
0,
dVdt,
}
F_i {
V - R * iR,
(Vs - V) / L,
iL - iR - iC,
iC / C,
}
out_i {
iR,
}
",
)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let (ys, ts, _stop_reason) = solver.solve(1.0).unwrap();
let ir: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let t: Vec<_> = ts.into_iter().collect();
let ir = Scatter::new(t.clone(), ir).mode(Mode::Lines);
let mut plot = Plot::new();
plot.add_trace(ir);
let layout = Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new().title("current"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("electrical-circuit"));
fs::write("../src/primer/images/electrical-circuit.html", plot_html)
.expect("Unable to write file");
}
Partial Differential Equations (PDEs)
diffsol is an ODE solver, but it can also solve PDEs. The idea is to discretize the PDE in space only, and then solve the resulting system of ODEs. This is called the method of lines.
Discretizing a PDE is a large topic, and there are many ways to do it. Common methods include finite difference, finite volume, finite element, and spectral methods. Finite difference methods are the simplest to understand and implement, so some of the examples in this book will demonstrate this method to give you a flavour of how to solve PDEs with diffsol. However, in general we recommend that you use another package to discretise your PDE, and then import the resulting ODE system into diffsol for solving.
Some useful packages
There are many packages in the Python and Julia ecosystems that can help you discretise your PDE. Here are a few, but there are many more out there:
Python
- FEniCS: A finite element package. Uses the Unified Form Language (UFL) to specify PDEs.
- Firedrake: A finite element package, uses the same UFL as FEniCS.
- FiPy: A finite volume package.
- scikit-fdiff: A finite difference package.
Julia:
- MethodOfLines.jl: A finite difference package.
- Gridap.jl: A finite element package.
Example: Heat equation
Lets consider a simple example, the heat equation. The heat equation is a PDE that describes how the temperature of a material changes over time. In one dimension, the heat equation is
\[ \frac{\partial u}{\partial t} = D \frac{\partial^2 u}{\partial x^2} \]
where \(u(x, t)\) is the temperature of the material at position \(x\) and time \(t\), and \(D\) is the thermal diffusivity of the material. To solve this equation, we discretise it in space only. We can use a finite difference method to discretise the spatial derivative, and then solve the resulting system of ODEs using diffsol.
Finite difference method
The finite difference method is a numerical method for discretising a spatial derivative like \(\frac{\partial^2 u}{\partial x^2}\). It approximates this continuous term by a discrete term, in this case the multiplication of a matrix by a vector. We can use this discretisation method to convert the heat equation into a system of ODEs suitable for diffsol.
We will not go into the details of the finite difference method here but merely derive a single finite difference approximation for the term \(\frac{\partial^2 u}{\partial x^2}\), or \(u_{xx}\) using more compact notation.
The central FD approximation of \(u_{xx}\) is:
\[ u_{xx} \approx \frac{u(x + h) - 2u(x) + u(x-h)}{h^2} \]
where \(h\) is the spacing between points along the x-axis.
We will discretise \(u_{xx}\) at \(N\) regular points along \(x\) from 0 to 1, given by \(x_1\), \(x_2\), ...
+----+----+----------+----+> x
0 x_1 x_2 ... x_N 1
Using this set of points and the discrete approximation, this gives a set of \(N\) equations at each interior point on the domain:
\[ \frac{v_{i+1} - 2v_i + v_{i-1}}{h^2} \text{ for } i = 1...N \]
where \(v_i \approx u(x_i)\)
We will need additional equations at \(x=0\) and \(x=1\), known as the boundary conditions. For this example we will use \(u(x) = g(x)\) at \(x=0\) and \(x=1\) (also known as a Dirichlet bc), so that \(v_0 = g(0)\), and \(v_{N+1} = g(1)\), and the equation at \(x_1\) becomes:
\[ \frac{v_2 - 2v_1 + g(0)}{h^2} \]
and the equation at \(x_N\) becomes:
\[ \frac{g(1) - 2v_N + v_{N-1}}{h^2} \]
We can therefore represent the final \(N\) equations in matrix form like so:
\[ \frac{1}{h^2} \begin{bmatrix} -2 & 1 & & & \\ 1 & -2 & 1 & & \\ &\ddots & \ddots & \ddots &\\ & & 1 & -2 & 1 \\ & & & 1 & -2 \end{bmatrix} \begin{bmatrix} v_1 \\ v_2 \\ \vdots \\ v_{N-1}\\ v_{N} \end{bmatrix} + \frac{1}{h^2} \begin{bmatrix} g(0) \\ 0 \\ \vdots \\ 0 \\ g(1) \end{bmatrix} \]
The relevant sparse matrix here is \(A\), given by
\[ A = \begin{bmatrix} -2 & 1 & & & \\ 1 & -2 & 1 & & \\ &\ddots & \ddots & \ddots &\\ & & 1 & -2 & 1 \\ & & & 1 & -2 \end{bmatrix} \]
As you can see, the number of non-zero elements grows linearly with the size \(N\), so a sparse matrix format is much preferred over a dense matrix holding all \(N^2\) elements! The additional vector that encodes the boundary conditions is \(b\), given by
\[ b = \begin{bmatrix} g(0) \\ 0 \\ \vdots \\ 0 \\ g(1) \end{bmatrix} \]
Method of Lines Approximation
We can use our FD approximation of the spatial derivative to convert the heat equation into a system of ODEs. Starting from our original definition of the heat equation:
\[ \frac{\partial u}{\partial t} = D \frac{\partial^2 u}{\partial x^2} \]
and using our finite difference approximation and definition of the sparse matrix \(A\) and vector \(b\), this becomes:
\[ \frac{du}{dt} = \frac{D}{h^2} (A u + b) \]
where \(u\) is a vector of temperatures at each point in space. This is a system of ODEs that we can solve using diffsol.
Problem parameters
The example below uses \(D = 0.1\) and \(N = 21\) interior points. The boundaries are at \(x = 0\) and \(x = 1\), so the spacing is \(h = 1/(N+1) = 1/22\). The boundary value is \(g = 0\) at both ends, which is a homogeneous Dirichlet bc. Thus the vector \(b\) is zero in this example, but the code keeps it to show the general form.
The initial condition is a "top-hat" function. The temperature is \(g + m = 1\) at the middle points \(x_6, \ldots, x_{15}\) and \(g = 0\) at all other points. Diffusion then smooths the top-hat and the heat flows out through the boundaries.
diffsol Implementation
use diffsol::{
CraneliftJitModule, FaerSparseLU, FaerSparseMat, MatrixCommon, OdeBuilder, OdeSolverMethod,
};
use plotly::{
layout::{Axis, Layout},
Plot, Surface,
};
use std::{fs, path::PathBuf};
type M = FaerSparseMat<f64>;
type LS = FaerSparseLU<f64>;
type CG = CraneliftJitModule;
fn main() {
let problem = OdeBuilder::<M>::new()
.build_from_diffsl::<CG>(
"
D { 0.1 }
h { 1.0 / 22.0 }
g { 0.0 }
m { 1.0 }
A_ij {
(0..20, 1..21): 1.0,
(0..21, 0..21): -2.0,
(1..21, 0..20): 1.0,
}
b_i {
(0): g,
(1:20): 0.0,
(20): g,
}
u_i {
(0:5): g,
(5:15): g + m,
(15:21): g,
}
heat_i { A_ij * u_j }
F_i {
D * (heat_i + b_i) / (h * h)
}",
)
.unwrap();
let times = (0..100).map(|i| i as f64 / 100.0).collect::<Vec<f64>>();
let mut solver = problem.bdf::<LS>().unwrap();
let (sol, _stop_reason) = solver.solve_dense(×).unwrap();
let x = (1..=21).map(|i| i as f64 / 22.0).collect::<Vec<f64>>();
let y = times;
let z = sol
.inner()
.col_iter()
.map(|v| v.iter().copied().collect::<Vec<f64>>())
.collect::<Vec<Vec<f64>>>();
let trace = Surface::new(z).x(x).y(y);
let mut plot = Plot::new();
plot.add_trace(trace);
let layout = Layout::new()
.x_axis(Axis::new().title("x"))
.y_axis(Axis::new().title("t"))
.z_axis(Axis::new().title("u"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("heat-equation"));
let output_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../book/src/primer/images/heat-equation.html");
fs::write(output_path, plot_html).expect("Unable to write file");
}
Physics-based Battery Simulation
Traditional battery models are based on equivalent circuit models, similar to the circuit modelled in section Electrical Circuits. These models are simple and computationally efficient, but they lack the ability to capture all of the complex electrochemical processes that occur in a battery. Physics-based models, on the other hand, are based on the electrochemical processes that occur in the battery, and can provide a more detailed description of the battery's behaviour. They are parameterized by physical properties of the battery, such as the diffusion coefficients of lithium ions in the electrodes, the reaction rate constants, and the surface area of the electrodes, and can be used to predict the battery's performance under different operating conditions, once these parameters are known.
The Single Particle Model (SPM) is a physics-based model of a lithium-ion battery. It describes the diffusion of lithium ions in the positive and negative electrodes of the battery over a 1D radial domain, assuming that the properties of the electrodes are uniform across the thickness of the electrode. Here we will describe the equations that govern the SPM, and show how to solve them at different current rates to calculate the terminal voltage of the battery.
The Single Particle Model state equations
The SPM model only needs to solve for the concentration of lithium ions in the positive and negative electrodes, \(c_n\) and \(c_p\). The diffusion of lithium ions in each electrode particle \(c_i\) is given by:
\[ \frac{\partial c_i}{\partial t} = \nabla \cdot (D_i \nabla c_i) \]
subject to the following boundary and initial conditions:
\[ \left.\frac{\partial c_i}{\partial r}\right\vert_{r=0} = 0, \quad \left.\frac{\partial c_i}{\partial r}\right\vert_{r=R_i} = -j_i, \quad \left.c_i\right\vert_{t=0} = c^0_i \]
where \(c_i\) is the concentration of lithium ions in the negative (\(i=n\)) or positive (\(i=p\)) electrode, \(D_i\) is the diffusion coefficient, \(j_i\) is the interfacial current density, and \(c^0_i\) is the initial concentration.
The fluxes of lithium ions in the positive and negative electrodes \(j_i\) are dependent on the applied current \(I\):
\[ j_n = \frac{I}{a_n \delta_n F \mathcal{A}}, \qquad j_p = \frac{-I}{a_p \delta_p F \mathcal{A}}, \]
where \(a_i = 3 \epsilon_i / R_i\) is the specific surface area of the electrode, \(\epsilon_i\) is the volume fraction of active material, \(\delta_i\) is the thickness of the electrode, \(F\) is the Faraday constant, and \(\mathcal{A}\) is the electrode surface area.
Output variables for the Single Particle Model
Now that we have defined the equations to solve, we turn to the output variables that we need to calculate from the state variables \(c_n\) and \(c_p\). The terminal voltage of the battery is given by:
\[ V = U_p(x_p^s) - U_n(x_n^s) + \eta_p - \eta_n \]
where \(U_i\) is the open circuit potential (OCP) of the electrode, \(x_i^s = c_i(r=R_i) / c_i^{max}\) is the surface stoichiometry, and \(\eta_i\) is the overpotential.
Assuming Butler-Volmer kinetics and \(\alpha_i = 0.5\), the overpotential is given by:
\[ \eta_i = \frac{2RT}{F} \sinh^{-1} \left( \frac{j_i F}{2i_{0,i}} \right) \]
where the exchange current density \(i_{0,i}\) is given by:
\[ i_{0,i} = k_i F \sqrt{c_e} \sqrt{c_i(r=R_i)} \sqrt{c_i^{max} - c_i(r=R_i)} \]
where \(c_e\) is the concentration of lithium ions in the electrolyte, and \(k_i\) is the reaction rate constant.
Stopping conditions
We wish to terminate the simulation if the terminal voltage exceeds an upper threshold \(V_{\text{max}}\) or falls below a lower threshold \(V_{\text{min}}\). diffsol uses a root-finding algorithm to detect when the terminal voltage crosses these thresholds, using the following stopping conditions:
\[ V_{\text{max}} - V = 0, \qquad V - V_{\text{min}} = 0, \]
Solving the Single Particle Model using diffsol
The equations above describe the Single Particle Model of a lithium-ion battery, but they are relatively complex and difficult to discretise compared with the simple heat equation PDE that we saw in the Heat Equation section.
Rather than derive and write down the discretised equations ourselves, we will instead rely on the PyBaMM library to generate the equations for us. PyBaMM is a Python library that can generate a wide variety of physics-based battery models, using different parameterisations, physics and operating conditions. Combined with a tool that takes a PyBaMM model and writes it out in the DiffSL language, we can generate a DiffSL file that can be used to solve the equations of the SPM model described above. We can then use the diffsol crate to solve the model and calculate the terminal voltage of the battery over a range of current rates.
The code below reads in the DiffSL file, compiles it, and then solves the equation for different current rates. We wish to stop the simulation when either the final time is reached, or when one of the stopping conditions is met. We will output the terminal voltage of the battery at regular intervals during the simulation, because the terminal voltage can change more rapidly than the state variables \(c_n\) and \(c_p\), particularly during the "knee" of the discharge curve.
The discretised equations result in sparse matrices, so we use the sparse matrix and linear solver modules provided by the faer crate to solve the equations efficiently.
use diffsol::{
CraneliftJitModule, FaerSparseLU, FaerSparseMat, FaerVec, NonLinearOp, OdeBuilder,
OdeEquations, OdeSolverMethod, OdeSolverStopReason, Vector,
};
use plotly::{common::Mode, layout::Axis, layout::Layout, Plot, Scatter};
use std::fs;
type M = FaerSparseMat<f64>;
type V = FaerVec<f64>;
type LS = FaerSparseLU<f64>;
type CG = CraneliftJitModule;
fn main() {
let file = std::fs::read_to_string("../src/primer/src/spm.ds").unwrap();
let mut problem = OdeBuilder::<M>::new()
.p([1.0])
.build_from_diffsl::<CG>(&file)
.unwrap();
let currents = vec![0.6, 0.8, 1.0, 1.2, 1.4];
let final_time = 3600.0;
let delta_t = 3.0;
let mut plot = Plot::new();
for current in currents {
problem
.eqn
.set_params(&V::from_vec(vec![current], *problem.context()));
let mut solver = problem.bdf::<LS>().unwrap();
let mut v = Vec::new();
let mut t = Vec::new();
// save the initial output
let mut out = problem
.eqn
.out()
.unwrap()
.call(solver.state().y, solver.state().t);
v.push(out[0]);
t.push(0.0);
// solve until the final time is reached
// or we reach the stop condition
solver.set_stop_time(final_time).unwrap();
let mut next_output_time = delta_t;
let mut finished = false;
while !finished {
let curr_t = match solver.step() {
Ok(OdeSolverStopReason::InternalTimestep) => solver.state().t,
Ok(OdeSolverStopReason::RootFound(t, _idx)) => {
finished = true;
t
}
Ok(OdeSolverStopReason::TstopReached) => {
finished = true;
final_time
}
Err(_) => panic!("unexpected solver error"),
};
while curr_t > next_output_time {
let y = solver.interpolate(next_output_time).unwrap();
problem
.eqn
.out()
.unwrap()
.call_inplace(&y, next_output_time, &mut out);
v.push(out[0]);
t.push(next_output_time);
next_output_time += delta_t;
}
}
let voltage = Scatter::new(t, v)
.mode(Mode::Lines)
.name(format!("current = {current} A"));
plot.add_trace(voltage);
}
let layout = Layout::new()
.x_axis(Axis::new().title("t [sec]"))
.y_axis(Axis::new().title("voltage [V]"));
plot.set_layout(layout);
let plot_html = plot.to_inline_html(Some("battery-simulation"));
fs::write("../src/primer/images/battery-simulation.html", plot_html)
.expect("Unable to write file");
}
Forward Sensitivity Analysis
Recall our general ODE system (we'll define it without the mass matrix for now):
\[ \begin{align*} \frac{dy}{dt} &= f(t, y, p) \\ y(t_0) &= y_0 \end{align*} \]
Solving this system gives us the solution \(y(t)\) for a given set of parameters \(p\). However, we often want to know how the solution changes with respect to the parameters (e.g. for model fitting). This is where forward sensitivity analysis comes in. If we take the derivative of the ODE system with respect to the parameters, we get the sensitivity equations:
\[ \begin{align*} \frac{d}{dt} \frac{dy}{dp} &= \frac{\partial f}{\partial y} \frac{dy}{dp} + \frac{\partial f}{\partial p} \\ \frac{dy}{dp}(t_0) &= \frac{dy_0}{dp} \end{align*} \]
Here, \(\frac{dy}{dp}\) is the sensitivity of the solution with respect to the parameters. The sensitivity equations are solved alongside the ODE system to give us the solution and the sensitivity of the solution with respect to the parameters. The equations above are the continuous sensitivity equations. diffsol does not solve them with a separate discretisation. Instead, diffsol differentiates the discrete steps of the solver, in the same way as forward-mode automatic differentiation. These are the same steps that the reverse-mode gradients differentiate (see Backwards Sensitivity Analysis). For implicit solvers, the sensitivities are solved to the derivative_solve_tolerance of the solver options. For explicit solvers, no solve is necessary, so the sensitivities are exact to floating point error.
By default, the sensitivities are not included in the error control. Thus they do not change the step sizes of the forward solve. To include the sensitivities in the error control, set both the sens_rtol and sens_atol tolerances on the OdeBuilder.
Forward sensitivity analysis and forward-mode automatic differentiation have the same scaling properties as the number of parameters increases: each additional parameter requires one additional solve, so the method is not efficient for large numbers of parameters (>100). In this case, adjoint sensitivity analysis is often preferred.
To use forward sensitivity analysis in diffsol, more equations need to be specified that calculate the gradients with respect to the parameters. If you are using the OdeBuilder struct and rust closures, you need to supply additional closures that calculate the gradient of the right-hand side, and the gradient of the initial state vector with respect to the parameters. You can see an example of this in the Forward Sensitivity API section. If you are using the DiffSL language, these gradients are calculated automatically and you don't need to worry about them. An example of using forward sensitivity analysis in DiffSL is given in the Fitting a Predator-Prey Model to Data section next.
Fitting a Predator-Prey Model to data
In this example we will again use the Lotka-Volterra equations, which are described in more detail in the Population Dynamics - Predator-Prey Model example.
The equations are
\[ \frac{dx}{dt} = a x - b x y \\ \frac{dy}{dt} = c x y - d y \]
We also have initial conditions for the populations at time \(t = 0\).
\[ x(0) = x0 \\ y(0) = y0 \]
This model has six parameters, \(a, b, c, d, x0, y0\). For the purposes of this example, we'll fit two of these parameters \(b, d)\) to some synthetic data. We'll use the model itself to generate the synthetic data, so we'll know the true values of the parameters to verify the fitting process.
We'll use the argmin crate to perform the optimisation. This is a popular rust crate that contains a number of optimisation algorithms. It does have some limitations, such as the lack of support for constraints, so it may not be suitable for many real ODE fitting problems as the solver can easily fail to converge if the parameter vector moves into a difficult region (e.g. the Lotka-Volterra model only makes sense for positive values of the parameters). However, it will be sufficient for this example to demonstrate the sensitivity analysis capabilities of diffsol.
First of all we will need to implement some of the argmin traits to specify the optimisation problem. We'll create a struct Problem and implement the CostFunction and Gradient traits for it. The Problem struct will hold our synthetic data (held by the ys_data and ts_data fields) and the OdeSolverProblem that we'll use to solve the ODEs. We'll also create some type aliases for the nalgebra and diffsol types we'll be using.
Note that the problem field of the Problem struct is wrapped in a RefCell so that we can mutate it in the cost and gradient methods. Setting the parameters of the ODE solver problem is a mutable operation (i.e. you are changing the equations), so we need to use RefCell and interior mutability to do this.
use argmin::{
core::{observers::ObserverMode, CostFunction, Executor, Gradient},
solver::{linesearch::MoreThuenteLineSearch, quasinewton::LBFGS},
};
use argmin_observer_slog::SlogLogger;
use diffsol::{
DiffSl, MatrixCommon, OdeBuilder, OdeEquations, OdeSolverMethod, OdeSolverProblem, Op,
SensitivitiesOdeSolverMethod, Vector,
};
use std::cell::RefCell;
type M = diffsol::NalgebraMat<f64>;
type V = diffsol::NalgebraVec<f64>;
type T = f64;
type LS = diffsol::NalgebraLU<f64>;
type CG = diffsol::LlvmModule;
type Eqn = DiffSl<M, CG>;
struct Problem {
ys_data: M,
ts_data: Vec<T>,
problem: RefCell<OdeSolverProblem<Eqn>>,
}
The argmin CostFunction trait requires an implementation of the cost method, which will calculate the sum-of-squares difference between the synthetic data and the model output. Since the argmin crate does not support constraints, we'll return a large value if the ODE solver fails to converge.
impl CostFunction for Problem {
type Output = T;
type Param = Vec<T>;
fn cost(&self, param: &Self::Param) -> Result<Self::Output, argmin_math::Error> {
let mut problem = self.problem.borrow_mut();
let ctx = *problem.eqn().context();
problem
.eqn_mut()
.set_params(&V::from_vec(param.clone(), ctx));
let mut solver = problem.bdf::<LS>().unwrap();
let ys = match solver.solve_dense(&self.ts_data) {
Ok((ys, _stop_reason)) => ys,
Err(_) => return Ok(f64::MAX / 1000.),
};
let loss = ys
.inner()
.column_iter()
.zip(self.ys_data.inner().column_iter())
.map(|(a, b)| (a - b).norm_squared())
.sum::<f64>();
Ok(loss)
}
}
The argmin Gradient trait requires an implementation of the gradient method, which will calculate the gradient of the cost function with respect to the parameters. Our sum-of-squares cost function can be written as
\[ \text{loss} = \sum_i (y_i(p) - \hat{y}_i)^2 \]
where \(y_i(p)\) is the model output as a function of the parameters \(p\), and \(\hat{y}_i\) is the observed data at time index \(i\). Threrefore, the gradient of this cost function with respect to the parameters is
\[ \frac{\partial \text{loss}}{\partial p} = 2 \sum_i (y_i(p) - \hat{y}_i) \cdot \frac{\partial y_i}{\partial p} \]
where \(\frac{\partial y_i}{\partial p}\) is the sensitivity of the model output with respect to the parameters. We can calculate this sensitivity using the solve_dense_sensitivities method of the ODE solver. The gradient of the cost function is then the sum of the dot product of the residuals and the sensitivities for each time point. Again, if the ODE solver fails to converge, we'll return a large value for the gradient.
impl Gradient for Problem {
type Gradient = Vec<T>;
type Param = Vec<T>;
fn gradient(&self, param: &Self::Param) -> Result<Self::Gradient, argmin_math::Error> {
let mut problem = self.problem.borrow_mut();
let ctx = *problem.eqn().context();
problem
.eqn_mut()
.set_params(&V::from_vec(param.clone(), ctx));
let mut solver = problem.bdf_sens::<LS>().unwrap();
let (ys, sens) = match solver.solve_dense_sensitivities(&self.ts_data) {
Ok((ys, sens, _stop_reason)) => (ys, sens),
Err(_) => return Ok(vec![f64::MAX / 1000.; param.len()]),
};
let dlossdp = sens
.into_iter()
.map(|s| {
s.inner()
.column_iter()
.zip(
ys.inner()
.column_iter()
.zip(self.ys_data.inner().column_iter()),
)
.map(|(si, (yi, di))| 2.0 * (yi - di).dot(&si))
.sum::<f64>()
})
.collect::<Vec<f64>>();
Ok(dlossdp)
}
}
With these implementation out of the way, we can now perform the fitting problem. We'll generate some synthetic data using the Lotka-Volterra equations with some true parameters, and then fit the model to this data. We'll use the LBFGS solver from the argmin crate, which is a quasi-Newton method that uses the Broyden-Fletcher-Goldfarb-Shanno (BFGS) update formula. We'll also use the SlogLogger observer to log the progress of the optimisation.
We'll initialise the optimizer a short distance away from the true parameter values, and then check the final optimised parameter values against the true values.
pub fn main() {
let code = "
in_i { b = 4.0/3.0, d = 1.0 }
a { 2.0/3.0 } c { 1.0 } x0 { 1.0 } y0 { 1.0 }
u_i {
y1 = x0,
y2 = y0,
}
F_i {
a * y1 - b * y1 * y2,
c * y1 * y2 - d * y2,
}
";
let (b_true, d_true) = (4.0 / 3.0, 1.0);
let t_data = (0..101)
.map(|i| f64::from(i) * 40. / 100.)
.collect::<Vec<f64>>();
let problem = OdeBuilder::<M>::new()
.p([b_true, d_true])
.sens_atol([1e-6])
.sens_rtol(1e-6)
.build_from_diffsl(code)
.unwrap();
let ys_data = {
let mut solver = problem.bdf::<LS>().unwrap();
solver.solve_dense(&t_data).unwrap().0
};
let cost = Problem {
ys_data,
ts_data: t_data,
problem: RefCell::new(problem),
};
let init_param = vec![b_true - 0.1, d_true - 0.1];
let linesearch = MoreThuenteLineSearch::new().with_c(1e-4, 0.9).unwrap();
let solver = LBFGS::new(linesearch, 7);
let res = Executor::new(cost, solver)
.configure(|state| state.param(init_param))
.add_observer(SlogLogger::term(), ObserverMode::Always)
.run()
.unwrap();
// print result
println!("{}", res);
// Best parameter vector
let best = res.state().best_param.as_ref().unwrap();
println!("Best parameter vector: {:?}", best);
println!("True parameter vector: {:?}", vec![b_true, d_true]);
}
Feb 03 13:16:44.604 INFO L-BFGS
Feb 03 13:16:44.842 INFO iter: 0, cost: 21.574177406963013, best_cost: 21.574177406963013, cost_count: 6, gradient_count: 7, gamma: 1, time: 0.238573908
Feb 03 13:16:44.920 INFO iter: 1, cost: 0.6811721224055488, best_cost: 0.6811721224055488, cost_count: 8, gradient_count: 10, time: 0.077082344, gamma: 0.00036901099013336356
Feb 03 13:16:44.969 INFO iter: 2, cost: 0.6478536174002669, best_cost: 0.6478536174002669, cost_count: 9, gradient_count: 12, time: 0.049218286, gamma: 0.00017983731521908368
Feb 03 13:16:45.018 INFO iter: 3, cost: 0.5515637814971768, best_cost: 0.5515637814971768, cost_count: 10, gradient_count: 14, time: 0.049264513, gamma: 0.00013404417466199433
Feb 03 13:16:45.069 INFO iter: 4, cost: 0.2889819270908579, best_cost: 0.2889819270908579, cost_count: 11, gradient_count: 16, time: 0.050718659, gamma: 0.00019004425867568796
Feb 03 13:16:45.120 INFO iter: 5, cost: 0.06441855702549167, best_cost: 0.06441855702549167, cost_count: 12, gradient_count: 18, gamma: 0.0005522578375180803, time: 0.05102388
Feb 03 13:16:45.172 INFO iter: 6, cost: 0.001969603423448309, best_cost: 0.001969603423448309, cost_count: 13, gradient_count: 20, time: 0.051874014, gamma: 0.002084311472606979
Feb 03 13:16:45.224 INFO iter: 7, cost: 0.00018682781933202676, best_cost: 0.00018682781933202676, cost_count: 14, gradient_count: 22, gamma: 0.00020342834067043386, time: 0.051705468
Feb 03 13:16:45.276 INFO iter: 8, cost: 0.0000004145187755175781, best_cost: 0.0000004145187755175781, cost_count: 15, gradient_count: 24, time: 0.052326582, gamma: 0.00013653160933392906
Feb 03 13:16:45.328 INFO iter: 9, cost: 0.00000019683422285908518, best_cost: 0.00000019683422285908518, cost_count: 16, gradient_count: 26, time: 0.05250708, gamma: 0.0002897867622209216
Feb 03 13:16:45.381 INFO iter: 10, cost: 0.00000018573267264008743, best_cost: 0.00000018573267264008743, cost_count: 17, gradient_count: 28, time: 0.052503364, gamma: 0.0006940640307853263
Feb 03 13:16:47.047 INFO iter: 11, cost: 0.0000001857326722089365, best_cost: 0.0000001857326722089365, cost_count: 74, gradient_count: 86, gamma: 0.00012163138683631344, time: 1.665703414
Feb 03 13:16:47.531 INFO iter: 12, cost: 0.00000018573267291060315, best_cost: 0.0000001857326722089365, cost_count: 90, gradient_count: 103, gamma: 0.000001225820261527594, time: 0.484634742
Feb 03 13:16:49.078 INFO iter: 13, cost: 0.000000185732672314337, best_cost: 0.0000001857326722089365, cost_count: 143, gradient_count: 157, time: 1.5466635069999999, gamma: 0.00000005014738728081247
Feb 03 13:16:49.562 INFO iter: 14, cost: 0.00000018573267355654775, best_cost: 0.0000001857326722089365, cost_count: 159, gradient_count: 174, gamma: 0.00000386732692846693, time: 0.483722743
Feb 03 13:16:51.051 INFO iter: 15, cost: 0.0000001857326728225398, best_cost: 0.0000001857326722089365, cost_count: 210, gradient_count: 226, time: 1.489475966, gamma: -0.00000029042697044185633
Feb 03 13:16:51.880 INFO iter: 16, cost: 0.00000018573267387423262, best_cost: 0.0000001857326722089365, cost_count: 238, gradient_count: 255, time: 0.828862625, gamma: 0.0000014262616055754604
Feb 03 13:16:53.202 INFO iter: 17, cost: 0.00000018573267376814762, best_cost: 0.0000001857326722089365, cost_count: 283, gradient_count: 301, gamma: 0.00000006448722374243354, time: 1.32160584
OptimizationResult:
Solver: L-BFGS
param (best): [1.3333663799297248, 1.0000008551827637]
cost (best): 0.0000001857326722089365
iters (best): 11
iters (total): 18
termination: Solver converged
time: 8.62392681s
Best parameter vector: [1.3333663799297248, 1.0000008551827637]
True parameter vector: [1.3333333333333333, 1.0]
So, we've successfully fitted the Lotka-Volterra model to some synthetic data and recovered the original true parameters. This is a simple example and could easily be improved. For example, you will note from the output that the argmin crate is calling both the cost and gradient functions, and this is often done using the exact same parameter vector. Ideally we'd like to cache the results of the solve_dense_sensitivities method and reuse them in both the cost and gradient functions.
Backwards Sensitivity Analysis
Backwards sensitivity analysis, as the name suggests, starts from a given cost or loss function that you want to minimise, and derives the gradient of this function with respect to the parameters of the ODE systems using a lagrangian multiplier approach.
diffsol supports two different classes of loss functions, the first being an integral of a model output function \(g(t, u)\) over time,
\[ G(p) = \int_0^{t_f} g(t, u) dt \]
The second being a sum of \(n\) discrete functions \(h_i(t, u)\) at time points \(t_i\),
\[ G(p) = \int_0^{t_f} \sum_{i=1}^n h_i(t_i, u) \delta(t - t_i) dt \]
Note that the \(h_i\) functions can be a combination of the (continuous) model output function \(g\) and a user-defined discrete function, such as the sum of squares difference between the model output and some observed data.
There are two main approaches to calculate the gradient of the loss function with respect to the parameters, \(\frac{dG}{dp}\). The first approach starts from the continuous ODE equations, and gives the adjoint equations. A standard ODE solver method then solves the adjoint equations backwards in time. The second approach starts from the discrete steps of a given solver method, and applies reverse-mode automatic differentiation directly to these steps. This gives the gradient of the numerical solution that the solver calculated. diffsol supports both of these approaches. The sections below describe them.
Continuous adjoint equations
The derivation below is modified from that given in (Rackauckas et al. 2021), and uses the first form of the cost function, but the same approach can be used for the second form.
Lagrangian Multiplier Approach
We wish to minimise the cost function \(G(p)\) with respect to the parameters \(p\), and subject to the constraints of the ODE system of equations,
\[ M \frac{du}{dt} = f(t, u, p) \]
where \(M\) is the mass matrix, \(u\) is the state vector, and \(f\) is the right-hand side function. We can write the lagrangian as
\[ L(u, \lambda, p) = G(p) - \int_0^{t_f} \lambda^T \left(M \frac{du}{dt} - f(t, u, p)\right) dt \]
where \(\lambda\) is the lagrangian multiplier. We already know we can generate a solution to the ODE system \(u(t)\) that will satisfy the constraint such that the last term in the lagrangian is zero, meaning that the gradient of the lagrangian is equal to the gradient of the cost function. Therefore, we can write the gradient of the cost function as
\[ \frac{dG}{dp} = \int_0^{t_f} (g_p + g_u u_p) dt - \int_0^{t_f} \lambda^T (M \frac{du_p}{dt} - f_u u_p - f_p) dt \]
where \(g_p\) and \(g_u\) are the partial derivatives of the output function \(g\) with respect to the parameters and state variables, respectively, and \(u_p\) is the partial derivative of the state vector with respect to the parameters, also known as the sensitivities.
This equation can be simplified by using integration by parts, and requiring that the adjoint ODE system is satisfied, which is given by
\[ \begin{aligned} M^T \frac{d \lambda}{dt} &= -f_u^T \lambda - g_u^T \\ \lambda(t_f) &= 0 \end{aligned} \]
giving the gradient of the cost function as
\[ \frac{dG}{dp} = \lambda^T(0) M u_p(0) + \int_0^{t_f} (g_p + \lambda^T f_p) dt \]
Solving the Adjoint ODE System
Solving the adjoint ODE system is done in two stages. First, we solve the forward ODE system to get the state vector \(u(t)\). We require this solution to be valid the entire time interval \([0, t_f]\), so we use a checkpointing system to store the state vector at regular intervals and interpolate between them to get the state vector at any time point. The second stage is to solve the adjoint ODE system backwards in time, starting from the final time point \(t_f\) and using the interpolated state vector to supply \(u(t)\) as needed.
The gradient \(\frac{dG}{dp}\) can be calculated by performing a quadrature over the time interval \([0, t_f]\) to calculate the last term in the equation above. Special consideration needs to be taken for the second form of the cost function above, where the discrete functions are evaluated at specific time points. In this case, the solver will need to be stopped at each time point and the contribution \(M^{-T} g_u^T\) added to the state vector \(\lambda\), and the contribution \(g_p\) added to the gradient \(\frac{dG}{dp}\).
In the case that \(M\) is singular, but can be divided into an invertible block and zero blocks like so:
\[ M = \begin{bmatrix} M_{dd} & 0 \\ 0 & 0 \end{bmatrix} \]
where \(M_{dd}\) is invertible. The subscript \(d\) refers to the differential variables and the subscript \(a\) refers to the algebraic variables. The corresponding block decomposition of the adjoint Jacobian and the partial derivative of the output function can be written as
\[ f_u^T = \begin{bmatrix} f_{dd} & f_{da} \\ f_{ad} & f_{aa} \end{bmatrix} \]
and
\[ g_u^T = \begin{bmatrix} g_{d} \\ g_{a} \end{bmatrix}. \]
The algebraic part of the adjoint equation has no time derivative. Thus the discrete function also changes \(\lambda_a\) at the time point, and this changes the contribution to \(\lambda_d\). The contribution to the differential part of \(\lambda\) is
\[ \lambda_d \mathrel{+}= M_{dd}^{-T} \left(g_{d} - f_{da} f_{aa}^{-1} g_{a}\right) \]
The contribution to the gradient also has an extra term. Let \(f_{p,a}\) be the rows of \(f_p\) for the algebraic variables. The contribution to the gradient is
\[ \left(\frac{dG}{dp}\right)^T \mathrel{+}= g_p^T - f_{p,a}^T f_{aa}^{-1} g_{a} \]
Specifying the discrete functions
Here we consider the second form of the cost function. If we have a model output function \(m(t, u)\), and a set of discrete functions \(h_i(t, u)\) which only depend on the model output (i.e. \(h_i(t, u) = h_i(m(t, u))\)), then the partial derivatives of the cost function \(g\) with respect to the parameters can be calculated as
\[ \begin{aligned} g_u &= g_m m_u \\ g_p &= g_m m_p \end{aligned} \]
where \(m_u\) and \(m_p\) are the partial derivatives of the model output function with respect to the state variables and parameters, respectively. Therefore, a user only has to supply \(g_m\) at each of the time points \(t_i\) and diffsol will be able to calculate the correct gradients as part of the backwards solution of the adjoint ODE system.
Discrete gradients
An ODE solver method calculates the solution as a sequence of steps. Each step is a function \(\Phi\) that maps the solver state \(s_i\) at step \(i\) to the solver state at the next step:
\[ s_{i+1} = \Phi(s_i, p) \]
The solver state \(s_i\) contains the time \(t_i\), the state vector \(u_i\) and the other data that the method needs, for example the history of a BDF method or the stages of a Runge-Kutta method. The output at a time point \(t\) is not usually at the end of a step. Thus there is also an interpolation function \(h\). If \(t_i < t \le t_{i+1}\), then \(h\) uses the solver state at the end of the step to calculate the solution at \(t\):
\[ u(t) = h(s_{i+1}, t) \]
Reverse-mode automatic differentiation
The diffsol code calculates the step function \(\Phi\) with:
- a sequence of linear algebra operations on the solver state, and
- control flow that uses the error estimate to select a step size that satisfies the tolerances. This includes the decision to accept or reject a step, and (for BDF) the selection of the order.
Reverse-mode automatic differentiation gives the gradient of (1). We ignore (2), because the forward solve already gives the step sizes, the orders and the accepted steps. We keep these as fixed values.
Reverse-mode automatic differentiation uses the chain rule from the output back to the input. Each step has a cotangent \(\bar{s}_{i+1} = \left(\frac{\partial G}{\partial s_{i+1}}\right)^T\), which is the gradient of the loss with respect to the solver state at the end of the step. The vector-Jacobian product (VJP) of the step moves this cotangent back to the start of the step, and adds the contribution of the step to the parameter gradient \(\bar{p}\):
\[ \begin{aligned} \bar{s}_i &= \left(\frac{\partial \Phi}{\partial s_i}\right)^T \bar{s}_{i+1} \\ \bar{p} &\mathrel{+}= \left(\frac{\partial \Phi}{\partial p}\right)^T \bar{s}_{i+1} \end{aligned} \]
The VJP does not make the Jacobians \(\frac{\partial \Phi}{\partial s_i}\) or \(\frac{\partial \Phi}{\partial p}\). Each operation of the step has a VJP, and the step VJP applies these in the opposite order. Thus the cost of the step VJP is approximately the cost of one step, and it does not increase with the number of parameters. The VJP needs the solver state at each step, so the forward solve keeps a copy of the solver state after each step.
For explicit solvers this process is simple. We do not use an automatic differentiation library. For each solver, we know the sequence of operations of the step, so we write down the operations of its VJP directly. The VJP of an explicit step is exact to floating point error.
Implicit solvers must solve a nonlinear system of equations at each step, and this is the main problem for reverse-mode automatic differentiation. At each step (or at each stage of a Runge-Kutta method), the solver finds the value \(z\) that solves
\[ F(z, s_i, p) = 0 \]
The Implicit Function Theorem gives the derivatives of the solution \(z\) without differentiating the iterations of the nonlinear solver. This needs a linear solve with the transposed Jacobian of the ODE equations. During the forward solve, we usually have only a factorisation of an approximate Jacobian, because the Newton iteration does not update the Jacobian at each step. To calculate and factorise the exact Jacobian at each reverse step is expensive. Instead, we use an iterative method (a Richardson iteration) for the linear solve, and we use the approximate Jacobian as a preconditioner \(P\).
The iterative method stops when it satisfies its tolerance, derivative_solve_tolerance (see OdeSolverOptions). The maximum number of iterations is derivative_solve_max_iter. Thus, for implicit solvers, the gradient of each step is accurate only to this tolerance. For explicit solvers, the gradient of each step is exact to floating point error. The forward sensitivities of diffsol differentiate the same steps in the same way, with the same linear solves and the same tolerance. Thus the forward and reverse-mode gradients of an implicit solver agree to this tolerance.
Discrete gradient of the loss function
Here we use the second form of the cost function, a sum of functions \(g_j\) of the output at the time points \(t_j\):
\[ G(p) = \sum_{j=1}^{n} g_j(u(t_j)), \qquad u(t_j) = h(s_{k(j)}, t_j) \]
where \(k(j)\) is the step that reaches \(t_j\). The VJPs of \(\Phi\) and \(h\) give \(\frac{dG}{dp}\) in three stages:
- Forward pass. Solve the ODE from \(t_0\) to \(t_n\). Keep a copy of the solver state \(s_i\) after each step, and record the step \(k(j)\) that reaches each time point \(t_j\). Calculate the outputs \(u(t_j)\) and the loss gradients \(\frac{\partial g_j}{\partial u}\).
- Backward pass. Start with \(\bar{s}_N = 0\) at the last step \(N\), and \(\bar{p} = 0\). For each step \(i = N, N-1, \dots, 1\):
- for each time point \(t_j\) in the step (\(k(j) = i\)), add the VJP of the interpolation: \(\bar{s}_i \mathrel{+}= \left(\frac{\partial h}{\partial s_i}\right)^T \left(\frac{\partial g_j}{\partial u}\right)^T\)
- use the VJP of the step to calculate \(\bar{s}_{i-1}\), and add the contribution of the step to \(\bar{p}\).
- Initial state. The initial state \(s_0\) also depends on the parameters: \(u_0\) comes from the initial condition, and the solver calculates \(\frac{du_0}{dt}\) from \(f(t_0, u_0, p)\) (or, for a DAE, it solves for consistent initial conditions). Add the last contribution \(\bar{p} \mathrel{+}= \left(\frac{\partial s_0}{\partial p}\right)^T \bar{s}_0\).
At the end, \(\bar{p} = \left(\frac{dG}{dp}\right)^T\). If the model has an output function \(m(t, u)\), as in the section above, the user supplies \(\frac{\partial g_j}{\partial m}\), and diffsol uses the chain rule through \(m_u\) and \(m_p\).
This is the gradient of the loss that the solver actually calculates, with fixed step sizes, orders and interpolation weights. It is not an approximation of the gradient of the exact solution, as the continuous adjoint is. Thus the gradient agrees with the loss that an optimiser sees. There are some limits:
- The mass matrix \(M\) must not depend on the parameters, because diffsol does not differentiate this term.
- The cost function must be the second form, a sum of functions at time points. The discrete gradients do not support the first form, an integral of the output (
integrate_out). - The solve must not stop at roots of a root function. A step that finds a root gives an error. Thus the discrete gradients do not support resets.
If any of these limitations affect you, please open an issue on the repository.
The continuous adjoint method supports resets. The checkpointed forward solve applies each reset and splits the checkpoints at the reset. At each reset, the backward solve then updates \(\lambda\) and the gradient \(\frac{dG}{dp}\) with the adjoint of the reset. The adjoint of a reset does not support a mass matrix.
Example: Fitting a spring-mass model to data
In this example we'll fit a damped spring-mass system to some synthetic data (using the model to generate the data). The system consists of a mass \(m\) attached to a spring with spring constant \(k\), and a damping force proportional to the velocity of the mass with damping coefficient \(c\).
\[ \begin{align*} \frac{dx}{dt} &= v \\ \frac{dv}{dt} &= -\frac{k}{m} x - \frac{c}{m} v \end{align*} \]
where \(v = \frac{dx}{dt}\) is the velocity of the mass.
We'll use the argmin crate to perform the optimisation. To hold the synthetic data and the model, we'll create a struct Problem like so
use argmin::{
core::{CostFunction, Executor, Gradient, State},
solver::{linesearch::MoreThuenteLineSearch, quasinewton::LBFGS},
};
use diffsol::{
AdjointOdeSolverMethod, DenseMatrix, DiffSl, Matrix, MatrixCommon, NalgebraMat, NalgebraVec,
OdeBuilder, OdeEquations, OdeSolverMethod, OdeSolverProblem, OdeSolverState, Op, Scale,
StepVjp, Vector, VectorView, VectorViewMut,
};
use std::cell::RefCell;
use std::time::{Duration, Instant};
type M = NalgebraMat<f64>;
type V = NalgebraVec<f64>;
type T = f64;
type LS = diffsol::NalgebraLU<f64>;
type CG = diffsol::LlvmModule;
type Eqn = DiffSl<M, CG>;
#[derive(Clone, Copy, Debug)]
enum GradientMethod {
ContinuousAdjoint,
DiscreteAdjoint,
}
struct Problem {
ys_data: M,
ts_data: Vec<T>,
problem: RefCell<OdeSolverProblem<Eqn>>,
method: GradientMethod,
}
To use argmin we need to specify traits giving the loss function and its gradient. In this case we'll define a loss function equal to the sum of squares error between the model output and the synthetic data.
$$ \text{loss} = \sum_i (y_i(p) - \hat{y}_i)^2 $$
where \(y_i(p)\) is the model output as a function of the parameters \(p\), and \(\hat{y}_i\) is the observed data at time index \(i\).
impl CostFunction for Problem {
type Output = T;
type Param = Vec<T>;
fn cost(&self, param: &Self::Param) -> Result<Self::Output, argmin_math::Error> {
let mut problem = self.problem.borrow_mut();
let context = *problem.eqn().context();
problem
.eqn_mut()
.set_params(&V::from_vec(param.clone(), context));
let mut solver = problem.bdf::<LS>().unwrap();
let ys = match solver.solve_dense(&self.ts_data) {
Ok((ys, _stop_reason)) => ys,
Err(_) => return Ok(f64::MAX / 1000.),
};
let loss = ys
.inner()
.column_iter()
.zip(self.ys_data.inner().column_iter())
.map(|(a, b)| (a - b).norm_squared())
.sum::<f64>();
Ok(loss)
}
}
The gradient of this cost function with respect to the model outputs \(y_i\) is
$$ \frac{\partial \text{loss}}{\partial y_i} = 2 (y_i(p) - \hat{y}_i) $$
Diffsol gives two methods to calculate the gradient of the loss with respect to the parameters \(p\). Both use reverse mode, so the cost does not increase with the number of parameters.
Method 1: continuous adjoint
The continuous adjoint method ("optimise-then-discretise") first derives the adjoint ODE equations, and then solves them backwards in time with an ODE solver. First we solve the forwards problem, which gives a checkpointing struct. We then use the forward solution to calculate \(\frac{\partial \text{loss}}{\partial y_i}\) at each time point, and give this to the adjoint backwards pass. The backwards pass calculates the gradient of the loss with respect to the parameters.
fn gradient_continuous(&self, param: &[T]) -> Vec<T> {
let mut problem = self.problem.borrow_mut();
let context = *problem.eqn().context();
problem
.eqn_mut()
.set_params(&V::from_vec(param.to_vec(), context));
let mut solver = problem.bdf::<LS>().unwrap();
let (c, ys, _stop_reason) = match solver.solve_dense_with_checkpointing(&self.ts_data, None)
{
Ok(ys) => ys,
Err(_) => return vec![f64::MAX / 1000.; param.len()],
};
let g_m = self.dloss_dy(&ys);
let adjoint_solver = problem
.bdf_solver_adjoint::<LS, _>(c, Some(solver), Some(1))
.unwrap();
match adjoint_solver.solve_adjoint_backwards_pass(self.ts_data.as_slice(), &[&g_m]) {
Ok((soln, _)) => soln.as_ref().sg.get_batch(0).into_owned().clone_as_vec(),
Err(_) => vec![f64::MAX / 1000.; param.len()],
}
}
The dloss_dy helper gives the matrix of \(\frac{\partial \text{loss}}{\partial y_i}\), with one column for each time point.
Method 2: reverse-mode AD of the solver steps
The second method ("discretise-then-optimise") uses the StepVjp trait. It does not solve an adjoint ODE. Instead, it pulls the loss gradient back through each step that the forward solver took, in reverse order. The step sizes, the orders and the accept/reject decisions of the forward solve are kept fixed. Thus the result is the gradient of the numerical solution, not an approximation of the gradient of the exact solution.
The code has the same shape as the continuous method. solve_dense_vjp_fwd solves the forwards problem and keeps the state after each step in a tape. We calculate \(\frac{\partial \text{loss}}{\partial y_i}\) as before. Then solve_dense_vjp_bkwd uses the tape to calculate the gradient with respect to the parameters.
fn gradient_discrete(&self, param: &[T]) -> Vec<T> {
let mut problem = self.problem.borrow_mut();
let context = *problem.eqn().context();
problem
.eqn_mut()
.set_params(&V::from_vec(param.to_vec(), context));
let mut solver = problem.bdf::<LS>().unwrap();
let (ys, tape) = match solver.solve_dense_vjp_fwd(&self.ts_data) {
Ok(res) => res,
Err(_) => return vec![f64::MAX / 1000.; param.len()],
};
let g_m = self.dloss_dy(&ys);
match solver.solve_dense_vjp_bkwd(&tape, &g_m) {
Ok(grad) => grad.clone_as_vec(),
Err(_) => vec![f64::MAX / 1000.; param.len()],
}
}
The Gradient trait for argmin selects one of the two methods:
impl Gradient for Problem {
type Gradient = Vec<T>;
type Param = Vec<T>;
fn gradient(&self, param: &Self::Param) -> Result<Self::Gradient, argmin_math::Error> {
Ok(match self.method {
GradientMethod::ContinuousAdjoint => self.gradient_continuous(param),
GradientMethod::DiscreteAdjoint => self.gradient_discrete(param),
})
}
}
Comparing the two methods
In our main function we make the model and generate some synthetic data. Then we compare the two methods in two ways:
- We calculate the gradient at the initial parameters 1000 times with each method, and measure the mean time for one gradient.
- We use argmin's L-BFGS solver to fit the model to the data with each method, and measure the time for the full fit.
fn build_problem(k: T, c: T) -> OdeSolverProblem<Eqn> {
OdeBuilder::<M>::new()
.p([k, c])
.sens_atol([1e-6])
.sens_rtol(1e-6)
.out_atol([1e-6])
.out_rtol(1e-6)
.build_from_diffsl(
"
in_i { k = 1.0, c = 0.1 }
m { 1.0 }
u_i {
x = 1,
v = 0,
}
F_i {
v,
-k/m * x - c/m * v,
}
",
)
.unwrap()
}
/// The mean wall time of one call to `f`, over `n` calls after one warm-up call.
fn time_per_call(n: u32, mut f: impl FnMut()) -> Duration {
f();
let start = Instant::now();
for _ in 0..n {
f();
}
start.elapsed() / n
}
pub fn main() {
let (k_true, c_true) = (1.0, 0.1);
let t_data = (0..101)
.map(|i| f64::from(i) * 40. / 100.)
.collect::<Vec<f64>>();
let ys_data = {
let problem = build_problem(k_true, c_true);
let mut solver = problem.bdf::<LS>().unwrap();
solver.solve_dense(&t_data).unwrap().0
};
let make_cost = |method| Problem {
ys_data: ys_data.clone(),
ts_data: t_data.clone(),
problem: RefCell::new(build_problem(k_true, c_true)),
method,
};
let init_param = vec![k_true - 0.1, c_true - 0.01];
let methods = [
GradientMethod::ContinuousAdjoint,
GradientMethod::DiscreteAdjoint,
];
// benchmark one gradient evaluation at the initial parameters
println!("Gradient at {init_param:?}:");
let n = 1000;
let mut times = Vec::new();
let mut grads = Vec::new();
for method in methods {
let cost = make_cost(method);
let time = time_per_call(n, || {
cost.gradient(&init_param).unwrap();
});
let grad = cost.gradient(&init_param).unwrap();
println!(" {method:?}: {grad:?}, {time:?} per gradient");
times.push(time);
grads.push(grad);
}
let rel_diff = grads[0]
.iter()
.zip(&grads[1])
.map(|(a, b)| ((a - b) / b).abs())
.fold(0.0, f64::max);
println!(" Largest relative difference: {rel_diff:.2e}");
println!(
" Speed-up of discrete over continuous: {:.2}x",
times[0].as_secs_f64() / times[1].as_secs_f64()
);
// benchmark a full fit with each method
for method in methods {
let linesearch = MoreThuenteLineSearch::new().with_c(1e-4, 0.9).unwrap();
let solver = LBFGS::new(linesearch, 7);
let start = Instant::now();
let res = Executor::new(make_cost(method), solver)
.configure(|state| state.param(init_param.clone()).counting(true))
.run()
.unwrap();
let time = start.elapsed();
let state = res.state();
let counts = state.get_func_counts();
println!("\nFit with {method:?}:");
println!(" time: {time:?}");
println!(" iterations: {}", state.get_iter());
println!(" cost evals: {}", counts["cost_count"]);
println!(" gradient evals: {}", counts["gradient_count"]);
println!(" best cost: {:e}", state.get_best_cost());
println!(" best params: {:?}", state.get_best_param().unwrap());
println!(" termination: {}", state.get_termination_status());
}
println!("\nTrue parameters: {:?}", vec![k_true, c_true]);
}
Run the example in release mode, because timings of a debug build are not useful:
cargo run --release -p mass-spring-fitting-adjoint --features diffsl-llvm17
The output is:
Gradient at [0.9, 0.09000000000000001]:
ContinuousAdjoint: [-169.961431321948, -106.83268194215616], 2.031135ms per gradient
DiscreteAdjoint: [-169.96068853944487, -106.80930261280977], 218.84µs per gradient
Largest relative difference: 2.19e-4
Speed-up of discrete over continuous: 9.28x
Fit with ContinuousAdjoint:
time: 104.769459ms
iterations: 13
cost evals: 27
gradient evals: 40
best cost: 7.179238912566991e-25
best params: [0.9999999999999731, 0.10000000000000907]
termination: Solver converged
Fit with DiscreteAdjoint:
time: 24.460875ms
iterations: 12
cost evals: 29
gradient evals: 41
best cost: 1.6127427301319806e-20
best params: [1.000000000003015, 0.09999999999754586]
termination: Solver converged
True parameters: [1.0, 0.1]
The times depend on your machine, but the ratio between the two methods is a better guide. For this problem, one gradient with reverse-mode AD of the steps is approximately 9 times faster than one gradient with the continuous adjoint. The continuous adjoint must solve a second ODE backwards in time, with its own adaptive steps and error control. Reverse-mode AD of the steps does not take new steps: it goes back through the steps of the forward solve that it kept in the tape. The full fit is approximately 4 times faster. The speed-up is smaller because the fit also calculates the loss, which costs the same for the two methods.
The two gradients agree to approximately \(2 \times 10^{-4}\) relative error. This difference comes from (a) the continuous adjoint method: it approximates the gradient of the exact ODE solution to the solver tolerances and (b) the discrete gradient method: we use an implicit solver so the linear solve for each VJP is only solved to the tolerances (an explicit solver will give an exact gradient up to floating point precision). The two fits converge to the true parameters, and they use a similar number of iterations.
Example: Weather prediction using Neural ODEs
If we wish to train a neural network to predict the weather or any other time series dataset, we can use a Neural ODE. A Neural ODE replaces the rhs of an ODE with a neural network.
\[ \frac{dy}{dt} = f(y, p) \]
Here, \(y(t)\) is the state of the system at time \(t\), and \(f\) is a neural network with parameters \(p\). The neural network is trained to predict the derivative of the state, and the ODE solver is used to integrate the state forward in time, and to calculate gradients of the loss function with respect to the parameters of the neural network.
In this example, we will duplicate the weather prediction example from the excellent blog post by Sebastian Callh, but instead using diffsol as the solver. We'll skip over some of the details, but you can read more details about the problem setup in the original blog post, and see the full code in the diffsol repository.
First we'll need a neural network model, and we'll use Equinox and JAX for this. We'll define a simple neural network with 3 layers like so
class NeuralNetwork(eqx.Module):
layers: list
def __init__(self, data_dim, key):
key1, key2, key3 = jax.random.split(key, 3)
self.layers = [
eqx.nn.Linear(data_dim, 64, key=key1),
eqx.nn.Linear(64, 32, key=key2),
eqx.nn.Linear(32, data_dim, key=key3),
]
def __call__(self, x):
x = jax.nn.silu(self.layers[0](x)) # Swish = SiLU
x = jax.nn.silu(self.layers[1](x))
x = self.layers[2](x)
return x
We will then create four JAX functions that will allow us to calculate:
- the rhs function \(f(y, p)\) of the Neural ODE, where \(y\) is the state of the system and \(p\) are the parameters.
- the Jacobian-vector product of the rhs function with respect to the state \(y\).
- the negative vector-Jacobian product of the rhs function with respect to the state \(y\).
- the negative vector-Jacobian product of the rhs function with respect to the parameters \(p\).
We will need all four of these to define the ODE problem and to solve it using diffsol.
def rhs(p, y):
params = unravel_params(p)
model = eqx.combine(params, static)
return model(y)
def rhs_jac_mul(p, y, v):
return jax.jvp(ft.partial(rhs, p), (y,), (v,))[1]
def rhs_jac_transpose_mul(p, y, v):
return -jax.vjp(ft.partial(rhs, p), y)[1](v)[0]
def rhs_sens_transpose_mul(p, y, v):
return -jax.vjp(ft.partial(rhs, y=y), p)[1](v)[0]
Finally, we can export all four of these JAX functions to ONNX, which will allow us to use them within rust.
def to_onnx(model, inputs, filename):
sig = [tf.TensorSpec(inpt[0].shape, inpt[0].dtype, name=inpt[1]) for inpt in inputs]
inference_tf = jax2tf.convert(model, enable_xla=False)
inference_tf = tf.function(inference_tf, autograph=False)
inference_onnx = tf2onnx.convert.from_function(inference_tf, input_signature=sig)
model_proto, _external_tensor_storage = inference_onnx
with open(filename, "wb") as f:
f.write(model_proto.SerializeToString())
return model_proto
Within rust now, we can define a diffsol system of equations by creating a struct NeuralOde. We'll use the ort crate and the ONNX Runtime to load the ONNX models that we made in Python.
struct NeuralOde {
rhs: RefCell<Session>,
rhs_jac_mul: RefCell<Session>,
rhs_jac_transpose_mul: RefCell<Session>,
rhs_sens_transpose_mul: RefCell<Session>,
input_y: RefCell<Array1<f32>>,
input_v: RefCell<Array1<f32>>,
input_p: Array1<f32>,
y0: V,
}
NeuralOde implements the OdeEquations trait. Its right-hand side operator implements the NonLinearOp, NonLinearOpJacobian, NonLinearOpAdjoint and NonLinearOpSensAdjoint traits, and its initial condition operator implements the ConstantOp and ConstantOpSensAdjoint traits. Together, these traits make NeuralOde satisfy the OdeEquationsImplicitAdjoint trait. This allows us to use the adjoint method to calculate gradients of our loss function with respect to the parameters of the neural network. As an example, here is the implementation of the NonLinearOp trait:
impl NonLinearOp for Rhs<'_> {
fn call_inplace(&self, x: &Self::V, _t: Self::T, y: &mut Self::V) {
let mut y_input = self.0.input_y.borrow_mut();
y_input
.iter_mut()
.zip(x.inner().iter())
.for_each(|(y, x)| *y = *x as f32);
let p_slice = self.0.input_p.as_slice().unwrap();
let y_slice = y_input.as_slice().unwrap();
let mut rhs = self.0.rhs.borrow_mut();
let outputs = rhs
.run(inputs![
"p" => TensorRef::from_array_view(([p_slice.len()], p_slice)).unwrap(),
"y" => TensorRef::from_array_view(([y_slice.len()], y_slice)).unwrap(),
])
.unwrap();
let (_shape, y_data) = outputs["Identity_1:0"].try_extract_tensor::<f32>().unwrap();
y.inner_mut()
.iter_mut()
.zip(y_data.iter())
.for_each(|(y, x)| *y = *x as f64);
}
}
We'll also need an optimiser, so we'll write an AdamW algorithm using the definition in the PyTorch documentation as a guide:
struct AdamW {
lr: T,
betas: (T, T),
eps: T,
m: V,
m_hat: V,
v: V,
v_hat: V,
grads2: V,
lambda: T,
t: i32,
}
impl AdamW {
fn new(nparams: usize, ctx: C) -> Self {
let lr = 1e-2;
let betas = (0.9, 0.999);
let eps = 1e-8;
let m = V::zeros(nparams, ctx);
let m_hat = V::zeros(nparams, ctx);
let v = V::zeros(nparams, ctx);
let v_hat = V::zeros(nparams, ctx);
let grads2 = V::zeros(nparams, ctx);
let lambda = 1e-2;
Self {
lr,
betas,
eps,
m,
m_hat,
v,
v_hat,
lambda,
grads2,
t: 0,
}
}
fn step(&mut self, params: &mut V, grads: &V) {
self.t += 1;
params.mul_assign(Scale(1.0 - self.lr * self.lambda));
self.m.axpy(1.0 - self.betas.0, grads, self.betas.0);
self.grads2.copy_from(grads);
self.grads2.component_mul_assign(grads);
self.v.axpy(1.0 - self.betas.1, &self.grads2, self.betas.1);
self.m_hat = &self.m * Scale(1.0 / (1.0 - self.betas.0.powi(self.t)));
self.v_hat = &self.v * Scale(1.0 / (1.0 - self.betas.1.powi(self.t)));
params
.inner_mut()
.iter_mut()
.zip(self.v_hat.inner().iter())
.zip(self.m_hat.inner().iter())
.for_each(|((params_i, v_hat_i), m_hat_i)| {
*params_i -= self.lr * m_hat_i / (v_hat_i.sqrt() + self.eps)
});
}
}
We'll then define our loss function, which will return the sum of squared errors between the solution and the data points, along with the gradients of the loss function with respect to the parameters. Since the size of the parameter vector is quite large (>2000), we'll use the adjoint method to calculate the gradients.
fn loss_fn(
problem: &mut OdeSolverProblem<NeuralOde>,
p: &V,
ts_data: &[T],
ys_data: &M,
g_m: &mut M,
) -> Result<(T, V), DiffsolError> {
problem.eqn.set_params(p);
let mut solver = problem.bdf::<LS>()?;
let (c, ys, _stop_reason) = solver.solve_dense_with_checkpointing(ts_data, None)?;
let mut loss = 0.0;
for j in 0..g_m.ncols() {
let delta = ys.column(j) - ys_data.column(j);
loss += delta.inner().dot(delta.inner());
let g_m_i = delta * Scale(2.0);
g_m.column_mut(j).copy_from(&g_m_i);
}
let adjoint_solver = problem
.bdf_solver_adjoint::<LS, _>(c, Some(solver), Some(1))
.unwrap();
let (soln, _) = adjoint_solver.solve_adjoint_backwards_pass(ts_data, &[&*g_m])?;
Ok((loss, soln.into_common().sg.pop().unwrap()))
}
Finally, we can train the neural network to predict the weather. Following the example given in the linked blog post above, we'll train in stages by increasing the number of datapoints by four each time. Each time we'll train for 150 steps using the AdamW optimiser.
fn train_one_round(
problem: &mut OdeSolverProblem<NeuralOde>,
ts_data: &[T],
ys_data: &M,
p: &mut V,
) {
let mut gm = M::zeros(problem.eqn.nout(), ts_data.len(), *problem.context());
let mut adam = AdamW::new(problem.eqn.nparams(), *problem.context());
for _ in 0..150 {
match loss_fn(problem, p, ts_data, ys_data, &mut gm) {
Ok((loss, g)) => {
println!("loss: {loss}");
adam.step(p, &g)
}
Err(e) => {
panic!("{}", e);
}
};
}
}
To give an indication of the results, we'll plot the results after we've used the first 20 data-points to train the model, and we'll predict the model solution to the entire dataset.
This seems to work well, and is good at matching the data points a long way into the future. This has been a whirlwind description of both Neural ODEs and this particular analysis. For a more detailed explanation, please refer to the original blog post by Sebastian Callh. We've also skipped over many more boring parts of the code, and you can see the full code for this example in the diffsol repository.
diffsol APIs for specifying problems
Most of the diffsol user-facing API revolves around specifying the problem you want to solve, thus a large part of this book will be dedicated to explaining how to specify a problem. All the examples presented in the primer used the DiffSL DSL to specify the problem, but diffsol also provides a pure Rust API for specifying problems. This API is sometimes more verbose than the DSL, but is more flexible, more performant, and easier to use if you have a model already written in Rust or another language that you can easily port or call from Rust.
ODE equations
The class of ODE equations that diffsol can solve are of the form
\[M(p, t) \frac{dy}{dt} = f(y, p, t),\] \[y(t_0) = y_0(p, t_0),\] \[z(t) = g(y, p, t),\]
where:
- \(f(y, p, t)\) is the right-hand side of the ODE,
- \(y\) is the state vector,
- \(p\) are the parameters,
- \(t\) is the time.
- \(y_0(p, t_0)\) is the initial state vector at time \(t_0\).
- \(M(p, t)\) is the mass matrix (this is optional, and is implicitly the identity matrix if not specified),
- \(g(y, p, t)\) is an output function that can be used to calculate additional outputs from the state vector (this is optional, and is implicitly \(g(y, p, t) = y\) if not specified).
The user can also optionally specify a root function \(s(y, p, t)\) that can be used to find the time at which a root occurs.
diffsol problem APIs
Specifying a problem in diffsol is done via the OdeBuilder struct, using the OdeBuilder::new method to create a new builder, and then chaining methods to set the equations to be solved, initial time, initial step size, relative & absolute tolerances, and parameters, or leaving them at their default values. Then, call a build method to create a new problem.
Users can specify the equations to be solved via three main APIs, ranging from the simplest to the most complex (but also the most flexible):
- The
DiffSlstruct allows users to specify the equations above using the DiffSL Domain Specific Language (DSL). This API is behind a feature flag (diffsl-craneliftif you want to use the slower cranelift backend,diffsl-llvm*if you want to use the faster LLVM backend). This is the easiest API to use as it can use automatic differentiation to calculate the necessary gradients, and is the best API if you want to use DiffSL from a higher-level language like Python or R while still having similar performance to Rust. - The
OdeBuilderstruct also has methods to set the equations using rust closures (see e.g. OdeBuilder::rhs_implicit). This API is convenient if you want to stick to pure rust code without using DiffSL and the JIT compiler, but requires you to calculate the gradients of the equations yourself. - Implementing the
OdeEquationstrait allows users to implement the equations on their own structs. This API is the most flexible as it allows users to use custom data structures and code that might not fit within theOdeBuilderAPI. However, it is the most verbose API and requires users to be more familiar with the various diffsol traits.
The builder
The simplest way to create a new problem is to use the OdeBuilder struct.
You can set many configuration options such as:
- initial time (
OdeBuilder::t0), - initial step size (
OdeBuilder::h0) - relative tolerance (
OdeBuilder::rtol) - absolute tolerance (
OdeBuilder::atol) - parameters (
OdeBuilder::p) - equations (
OdeBuilder::rhs,OdeBuilder::init,OdeBuilder::massetc.)
or leave them at their default values. Then, call the OdeBuilder::build method to create a OdeSolverProblem.
type M = NalgebraMat<f64>;
let _problem = OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.rhs(|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]))
.init(|_p, _t, y| y.fill(0.1), 1)
.build()
.unwrap();
Note that the OdeBuilder struct has a generic parameter M, which defines the matrix type to use when solving the problem.
This matrix type must satisfy the trait Matrix, and could be
one of the matrix types included with diffsol:
NalgebraMat, this is a thin wrapper around thenalgebracrate dense matrix.FaerMat, this is a thin wrapper around thefaercrate dense matrix.FaerSparseMat, this is a thin wrapper around thefaersparse matrix.OxideMat, this is diffsol's CUDA matrix type (requires thecuda-oxidefeature)CudaMat, this is diffsol's deprecated C CUDA matrix type (requires thecudafeature), useOxideMatinstead
Each matrix type is parameterised by a scalar type that satisfies the Scalar trait,
each matrix type also has an associated type that defines its corresponding vector type (bounded by the Vector trait).
So whenever you create a builder you are also defining what matrix, vector and scalar types to use for the problem that you will create using that builder.
Tolerances
All the solvers in diffsol aim to keep the Local Truncation Error (LTE) (the error accumulated during a single step) below a certain threshold, using the tolerances that have been set for that particular problem.
The particular error norm that diffsol uses is a weighted mean squared error
\[ |\delta| = \frac{1}{n} \sum_i^n \left ( \frac{\delta_i}{|y_i| \cdot rtol + atol_i} \right) ^2 \]
So that the relative tolerance rtol defines the error tolerance relative to the current size of the state, and the absolute tolerance atol takes over when the state approaches zero.
Note that atol is a vector since the scales of different state values might vary, but in practice it is common to set all the elements of atol to the same value,
so the builder method OdeBuilder::atol will accept a one-element collection, such as [1e-6]. If you do not set the tolerances, the builder uses the default values rtol = 1e-6 and atol = [1e-6].
Output error control
When integrating an output function over time, as well as the ODE state, diffsol allows you to set the step size based on both the error in the states and output integrals. The same norm is used for the output error as the states, and the final error is calculated as the maximum of the two individual contributions.
To enable output integrals, you need to provide an output function
using one of the OdeBuilder::out* methods, and set OdeBuilder::integrate_out to true.
To enable output error control, you need to set the output error tolerances using OdeBuilder::out_rtol
and OdeBuilder::out_atol.
If these tolerances have previously been set and you wish to turn off the output error control you can use OdeBuilder::turn_off_output_error_control
Forward sensitivity error control
There are n_p sets of forward sensitivity equations to be integrated, where n_p is the number of parameters, with each set being composed of n_y equations.
If forward sensitivity error control is enabled, a separate error norm is calculated for each set,
and these are combined so that the final error is the maximum over the error norms for the base equations, the n_p sets of sensitivity equations, and
any other error norms active.
To enable forward sensitivity error control, you need to set the appropriate error tolerances OdeBuilder::sens_rtol
and OdeBuilder::sens_atol. You can turn it off
using OdeBuilder::turn_off_sensitivities_error_control.
It is possible that the scale of different parameters could vary strongly across the parameter vector, in which case it would be beneficial
to have a separate sens_atol for each of the n_p sets of sensitivity equations. In this case you can set appropriate scales
for each of the parameters using the OdeBuilder::param_scales builder method, and
each sens_atol for that parameter will be divided by the absolute value of the scale that is set.
Adjoint sensitivity error control
Calculating the adjoint sensitivities requires both a forward pass, where only the base ODE equations are being solved, and a backwards
pass where the adjoint equations are being solved and, if it is a continuous loss function, a set of parameter gradient functions of length n_p are also being integrated.
During the forward pass the base error norm and output error control are active, as described above.
The adjoint state has the units of the loss divided by those of the state, so its natural scale depends on the scale of the loss.
The adjoint equations are error-controlled using OdeBuilder::adjoint_rtol
and OdeBuilder::adjoint_atol.
If adjoint_rtol is not set, the standard rtol is used. If adjoint_atol is not set and the backwards pass is given the loss gradients dgdu,
the standard atol is multiplied by the largest magnitude of dgdu (for each loss function), which makes the error control of the backwards pass
independent of the scale of the loss. Otherwise (for a continuous loss function) the standard atol is used.
The linear solves in the reverse-mode step derivatives (StepVjp::step_vjp), whose right-hand sides are cotangents, are similarly
normalised by the largest magnitude of their right-hand side.
During the backwards pass, a separate set of tolerances, OdeBuilder::param_rtol
and OdeBuilder::param_atol are used for the parameter gradients.
As with the other types of error control, if param_rtol and param_atol are not set, then the parameter gradient equations do not
contribute to the error control.
Global errors
The LTE is a measure of the error accumulated during a single step of the method. Most importantly, it is not a global error, so you might find that over the duration of a solve the error between your numerical solution and some analytical solution has grown larger than the tolerances that you set for the problem. Reducing the tolerances, however, will generally also reduce the global error, so you can continue reducing the tolerances until you achieve the global error that you are aiming for.
DiffSL
Many ODE libraries allow you to specify your ODE system using the host language, for example an ODE library written in C might allow you to write a C function for your RHS equations. However, this has limitations if you want to wrap this library in a higher level language like Python or R, how then do you provide the RHS functions?
For this usecase we have designed a Domain Specific Language (DSL) called DiffSL that can be used to specify the problem. DiffSL is not a general purpose language but is tightly constrained to the specification of a system of ordinary differential equations. It features a relatively simple syntax that consists of writing a series of tensors (dense or sparse) that represent the equations of the system.
DiffSL syntax
For more detail on the syntax of DiffSL see the DiffSL book. This section will focus on how to use DiffSL to specify a problem in diffsol.
Creating a DiffSL problem
To create a DiffSL problem, use the build_from_diffsl::<CG> method on the OdeBuilder struct, and give it a &str that contains the DiffSL code. The DiffSL code is then parsed and compiled into native machine code using either the LLVM or Cranelift backends. The CG type parameter specifies the backend that you want to use to compile the DiffSL code. The CraneliftJitModule backend is behind the diffsl-cranelift feature flag. The faster LlvmModule backend is behind one of the diffsl-llvm* feature flags (diffsl-llvm15 to diffsl-llvm21, see the diffsol Cargo.toml for the full list), depending on the version of LLVM you have installed. Each of these features also has a -prefer-dynamic variant (e.g. diffsl-llvm18-prefer-dynamic).
For example, here is an example of specifying a simple logistic equation using DiffSL:
use diffsol::{OdeBuilder, OdeSolverMethod};
type M = diffsol::NalgebraMat<f64>;
type CG = diffsol::CraneliftJitModule;
type LS = diffsol::NalgebraLU<f64>;
fn main() {
let problem = OdeBuilder::<M>::new()
.rtol(1e-6)
.p([1.0, 10.0])
.build_from_diffsl::<CG>(
"
in_i { r = 1.0, k = 1.0 }
u { 0.1 }
F { r * u * (1.0 - u / k) }
",
)
.unwrap();
let mut solver = problem.bdf::<LS>().unwrap();
let t = 0.4;
let (_ys, _ts, _stop_reason) = solver.solve(t).unwrap();
}
Rust closures
To create a new ode problem, use the OdeBuilder struct. You can create a builder using the OdeBuilder::new method, and then chain methods to set the equations to be solved, initial time, initial step size, relative & absolute tolerances, and parameters, or leave them at their default values. Then, call the build method to create a new problem.
Explicit vs implicit methods
diffsol contains a variety of methods for solving ODEs, including both explicit and implicit methods. An example of an explicit method is the euler method, which is a simple first-order method that uses the current state to calculate the next state. The only information needed to use this method is the right-hand side of the ODE, which is provided by the user. An example of an implicit method is the backward euler method, which uses the current state and the next state to calculate the next state, by solving an implicit non-linear equation. This method requires the user to provide the right-hand side of the ODE, as well as the jacobian of the right-hand side with respect to the state vector.
diffsol uses the Rust type system to distinguish between user-provided systems of equations that are either explicit or implicit. Any system of equations that is suitable for an explicit method implements the OdeEquations trait, whereas a system of equations that is suitable for an implicit method implements the OdeEquationsImplicit trait. If you are using the rust closures API, this is largely hidden from you, but you still need to be aware of these traits when specifying your own functions or structs.
An explicit example
Below is an example of how to create an explicit ODE problem using the OdeBuilder struct. This type of problem is suitable only for explicit solver methods.
The specific problem we will solve is the logistic equation
\[\frac{dy}{dt} = r y (1 - y/K),\]
where \(r\) is the growth rate and \(K\) is the carrying capacity. To specify the problem, we need to provide the \(dy/dt\) function \(f(y, p, t)\),
\[f(y, p, t) = r y (1 - y/K),\]
and the initial state
\[y_0(p, t) = 0.1\]
This can be done using the following code:
use diffsol::{MatrixCommon, OdeBuilder};
use diffsol::{NalgebraMat, OdeEquations, OdeSolverProblem};
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
type C = <M as MatrixCommon>::C;
type T = <M as MatrixCommon>::T;
pub fn problem_explicit() -> OdeSolverProblem<impl OdeEquations<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.rhs(|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]))
.init(|_p, _t, y| y.fill(0.1), 1)
.build()
.unwrap()
}
The return type of this function, OdeSolverProblem<impl OdeEquations<M=M, V=V, T=T, C=C>> details the type of problem that we are returning. The OdeSolverProblem struct contains our equations, which are of type impl OdeEquations<M=M, V=V, T=T, C=C>, where M is the matrix type, V is the vector type, T is the scalar type, and C is the context type. We need to specify the matrix, vector, scalar and context types as these are used for the underlying linear algebra containers and operations. The OdeEquations trait specifies that this system of equations is only suitable for explicit solver methods.
The rhs method is used to specify the \(f(y, p, t)\) function, whereas the init method is used to specify the initial state vector \(y_0(p, t)\).
An implicit example
We will now create an implicit ODE problem, again using the logistic equation as an example. This problem can be used in both the explicit and implicit diffsol solvers.
\[\frac{dy}{dt} = r y (1 - y/K),\]
where \(r\) is the growth rate and \(K\) is the carrying capacity. To specify the problem, we need to provide the \(dy/dt\) function \(f(y, p, t)\), and the jacobian of \(f\) multiplied by a vector \(v\) function, which we will call \(f'(y, p, t, v)\). That is
\[f(y, p, t) = r y (1 - y/K),\] \[f'(y, p, t, v) = rv (1 - 2y/K),\]
and the initial state
\[y_0(p, t) = 0.1\]
This can be done using the following code:
use diffsol::{MatrixCommon, OdeBuilder};
use diffsol::{NalgebraMat, OdeEquationsImplicit, OdeSolverProblem};
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
type C = <M as MatrixCommon>::C;
type T = <M as MatrixCommon>::T;
pub fn problem_implicit() -> OdeSolverProblem<impl OdeEquationsImplicit<M = M, V = V, T = T, C = C>>
{
OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.rhs_implicit(
|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]),
|x, p, _t, v, y| y[0] = p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]),
)
.init(|_p, _t, y| y.fill(0.1), 1)
.build()
.unwrap()
}
The rhs_implicit method is used to specify the \(f(y, p, t)\) and \(f'(y, p, t, v)\) functions, whereas the init method is used to specify the initial state vector \(y_0(p, t)\).
Mass matrix
In some cases, it is necessary to include a mass matrix in the problem, such that the problem is of the form
\[M(p, t) \frac{dy}{dt} = f(y, p, t).\]
A mass matrix is useful for PDE discretisations that lead to a non-identity mass matrix, or for DAE problems that can be transformed into ODEs with a singular mass matrix. diffsol can handle singular and non-singular mass matrices, and the mass matrix can be time-dependent.
Example
To illustrate the addition of a mass matrix to a problem, we will once again take the logistic equation, but this time we will add an additional variable that is set via an algebraic equation. This system is written as
\[\frac{dy}{dt} = r y (1 - y/K),\] \[0 = y - z,\]
where \(z\) is the additional variable with a solution \(z = y\). When this system is put in the form \(M(p, t) \frac{dy}{dt} = f(y, p, t)\), the mass matrix is
\[M(p, t) = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}.\]
Like the Jacobian, the diffsol builder does not require the full mass matrix, instead users can provide a function that gives a GEMV (General Matrix-Vector) product of the mass matrix with a vector.
\[m(\mathbf{v}, \mathbf{p}, t, \beta, \mathbf{y}) = M(p, t) \mathbf{v} + \beta \mathbf{y}. \]
Thus, to specify this problem using diffsol, we can use the OdeBuilder struct and provide the functions:
\[f(\mathbf{y}, \mathbf{p}, t) = \begin{bmatrix} r y_0 (1 - y_0/K) \\ y_0 - y_1 \end{bmatrix},\] \[f'(\mathbf{y}, \mathbf{p}, t, \mathbf{v}) = \begin{bmatrix} r v_0 (1 - 2 y_0/K) \\ v_0 - v_1 \end{bmatrix},\] \[m(\mathbf{v}, \mathbf{p}, t, \beta, \mathbf{y}) = \begin{bmatrix} v_0 + \beta y_0 \\ \beta y_1 \end{bmatrix}.\]
where \(f\) is the right-hand side of the ODE, \(f'\) is the Jacobian of \(f\) multiplied by a vector, and \(m\) is the mass matrix multiplied by a vector.
use diffsol::{MatrixCommon, OdeBuilder};
use diffsol::{NalgebraMat, OdeEquationsImplicit, OdeSolverProblem};
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
type C = <M as MatrixCommon>::C;
type T = <M as MatrixCommon>::T;
pub fn problem_mass() -> OdeSolverProblem<impl OdeEquationsImplicit<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.t0(0.0)
.rtol(1e-6)
.atol([1e-6])
.p(vec![1.0, 10.0])
.rhs_implicit(
|x, p, _t, y| {
y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]);
y[1] = x[0] - x[1];
},
|x, p, _t, v, y| {
y[0] = p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]);
y[1] = v[0] - v[1];
},
)
.mass(|v, _p, _t, beta, y| {
y[0] = v[0] + beta * y[0];
y[1] *= beta;
})
.init(|_p, _t, y| y.fill(0.1), 2)
.build()
.unwrap()
}
Root finding
Root finding is the process of finding the values of the variables that make a set of equations equal to zero. This is a common problem where you want to stop the solver or perform some action when a certain condition is met.
Specifying the root finding function
Using the logistic example, we can add a root finding function \(s(y, p, t)\) that will stop the solver when the value of \(y\) is such that \(s(y, p, t) = 0\). For this example we'll use the root finding function \(s(y, p, t) = y - 0.5\), which will stop the solver when the value of \(y\) is 0.5.
\[\frac{dy}{dt} = r y (1 - y/K),\] \[s(y, p, t) = y - 0.5,\]
This can be done using the OdeBuilder via the following code:
use diffsol::{MatrixCommon, OdeBuilder};
use diffsol::{NalgebraMat, OdeEquationsImplicit, OdeSolverProblem};
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
type C = <M as MatrixCommon>::C;
type T = <M as MatrixCommon>::T;
pub fn problem_root() -> OdeSolverProblem<impl OdeEquationsImplicit<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.t0(0.0)
.rtol(1e-6)
.atol([1e-6])
.p(vec![1.0, 10.0])
.rhs_implicit(
|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]),
|x, p, _t, v, y| y[0] = p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]),
)
.init(|_p, _t, y| y[0] = 0.1, 1)
.root(|x, _p, _t, y| y[0] = x[0] - 0.5, 1)
.build()
.unwrap()
}
here we have added the root finding function \(s(y, p, t) = y - 0.5\), and also let diffsol know that we have one root function by passing 1 as the last argument to the root method.
If we had specified more than one root function, the solver would stop when any of the root functions are zero.
Detecting roots during the solve
To detect the root during the solve, we can use the return type on the step method of the solver.
If successful the step method returns an OdeSolverStopReason enum that contains the reason the solver stopped.
use diffsol::{OdeEquations, OdeSolverMethod, OdeSolverStopReason};
pub fn solve_match_step<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations<T = f64> + 'a,
{
solver.set_stop_time(10.0).unwrap();
loop {
match solver.step() {
Ok(OdeSolverStopReason::InternalTimestep) => continue,
Ok(OdeSolverStopReason::TstopReached) => break,
Ok(OdeSolverStopReason::RootFound(_t, _idx)) => break,
Err(e) => panic!("Solver failed to converge: {e}"),
}
}
println!("Solver stopped at time: {}", solver.state().t);
}
Forward Sensitivity
In this section we will discuss how to compute the forward sensitivity of the solution of an ODE problem. The forward sensitivity is the derivative of the solution with respect to the parameters of the problem. This is useful for many applications, such as parameter estimation, optimal control, and uncertainty quantification.
Specifying the sensitivity problem
We will again use the example of the logistic growth equation, but this time we will compute the sensitivity of the solution \(y\) with respect to the parameters \(r\) and \(K\) (i.e. \(\frac{dy}{dr}\) and \(\frac{dy}{dK}\)). The logistic growth equation is:
\[\frac{dy}{dt} = r y (1 - y/K),\] \[y(0) = 0.1\]
Recall from Implicit that we also need to provide the jacobian of the right hand side of the ODE with respect to the state vector \(y\) and the gradient vector \(v\), which we will call \(J\). This is:
\[J v = \begin{bmatrix} r v (1 - 2 y/K) \end{bmatrix}.\]
Using the logistic growth equation above, we can compute the partial derivative of the right hand side of the ODE with respect to the vector \([r, K]\) multiplied by a vector \(v = [v_r, v_K]\), which we will call \(J_p v\). This is:
\[J_p v = v_r y (1 - y/K) + v_K r y^2 / K^2 .\]
We also need the partial derivative of the initial state vector with respect to the parameters multiplied by a vector \(v\), which we will call \(J_{y_0} v\). Since the initial state vector is constant, this is just zero
\[J_{y_0} v = 0.\]
We can then use the OdeBuilder struct to specify the sensitivity problem. The rhs_sens_implicit and init_sens methods are used to create a new problem that includes the sensitivity equations.
use crate::{C, M, T, V};
use diffsol::{OdeBuilder, OdeEquationsImplicitSens, OdeSolverProblem};
pub fn problem_fwd_sens(
) -> OdeSolverProblem<impl OdeEquationsImplicitSens<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.rhs_sens_implicit(
|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]),
|x, p, _t, v, y| y[0] = p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]),
|x, p, _t, v, y| {
y[0] = v[0] * x[0] * (1.0 - x[0] / p[1]) + v[1] * p[0] * x[0] * x[0] / (p[1] * p[1])
},
)
.init_sens(|_p, _t, y| y[0] = 0.1, |_p, _t, _v, y| y[0] = 0.0, 1)
.build()
.unwrap()
}
Solving the sensitivity problem
Once the sensitivity problem has been specified, we can solve it using the OdeSolverMethod trait.
Let's imagine we want to solve the sensitivity problem up to a time \(t_o = 5\). We can use the OdeSolverMethod trait to solve the problem as normal, stepping forward in time until we reach \(t_o\).
use diffsol::{Context, OdeEquationsImplicitSens, OdeSolverMethod, Vector, VectorView};
pub fn solve_fwd_sens_step<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquationsImplicitSens<T = f64> + 'a,
{
let t_o = 5.0;
while solver.state().t < t_o {
solver.step().unwrap();
}
// the sensitivities hold one parameter per batch lane
let sens_at_t_o = solver.interpolate_sens(t_o).unwrap();
let sens_at_internal_step = solver.state().s;
for p in 0..sens_at_t_o.context().nbatch() {
println!(
"sensitivity wrt parameter {p} at t_o: {:?}",
sens_at_t_o.get_batch(p).into_owned()
);
println!(
"sensitivity wrt parameter {p} at internal step: {:?}",
sens_at_internal_step.get_batch(p).into_owned()
);
}
}
We can then obtain the sensitivity vectors at time \(t_o\) using the interpolate_sens method on the OdeSolverMethod trait.
This method returns a single vector holding one sensitivity per parameter in its batch lanes: lane \(b \cdot n_p + i\) is the sensitivity wrt parameter \(i\) for batch \(b\) of the problem, so for an unbatched problem sens.get_batch(i) is the sensitivity wrt parameter \(i\) at time \(t_o\).
If we need the sensitivity at the current internal time step, we can get this from the s field of the StateRef struct that solver.state() returns.
Adjoint Sensitivity
Adjoint sensitivity analysis efficiently computes the gradient of a scalar objective with respect to many parameters. For an implicit solver, you need to specify:
- the right-hand side together with its state Jacobian-vector product and the two negative-transpose products used by the backward adjoint solver.
- the initial condition together with the parameter sensitivity negative-transpose product.
For the logistic equation
\[\frac{dy}{dt} = r y (1 - y/K),\]
the state Jacobian-vector product is
\[Jv = r v (1 - 2y/K),\]
and the adjoint closure must return \(-J^T v\):
\[-J^T v = -r v (1 - 2y/K).\]
The parameter-adjoint closure similarly returns \(-J_p^T v\):
\[-J_p^T v = \begin{bmatrix} -v y (1-y/K) \\ -v r y^2/K^2 \end{bmatrix}.\]
Use rhs_adjoint_implicit for these four right-hand-side operations and
init_adjoint for the initial state and its negative parameter transpose. The
logistic initial state below is constant, so its parameter-adjoint product is
zero.
use crate::{C, M, T, V};
use diffsol::{OdeBuilder, OdeEquationsImplicitAdjoint, OdeSolverProblem};
pub fn problem_adjoint_sens(
integrate_out: bool,
) -> OdeSolverProblem<impl OdeEquationsImplicitAdjoint<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.rhs_adjoint_implicit(
|x, p, _t, y| y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]),
|x, p, _t, v, y| y[0] = p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]),
|x, p, _t, v, y| y[0] = -p[0] * v[0] * (1.0 - 2.0 * x[0] / p[1]),
|x, p, _t, v, y| {
y[0] = -v[0] * x[0] * (1.0 - x[0] / p[1]);
y[1] = -v[0] * p[0] * x[0] * x[0] / (p[1] * p[1]);
},
)
.init_adjoint(
|_p, _t, y| y[0] = 0.1,
|_p, _t, _v, y| {
y[0] = 0.0;
y[1] = 0.0;
},
1,
)
.integrate_out(integrate_out)
.build()
.unwrap()
}
The function takes the value of
integrate_out
as an argument. An adjoint solve with a cost function that is the integral of
the output needs integrate_out(true), and a cost function that is a sum over
data times does not.
The resulting problem implements OdeEquationsImplicitAdjoint. You can use it
to make an adjoint solver after a checkpointed forward solve, see
Adjoint Sensitivities.
Automatic differentiation
With the autodiff feature, Diffsol can generate the Jacobian-vector and
negative-transpose products needed by adjoint sensitivity analysis from ordinary
Rust closures. This avoids manually writing rhs_jac, rhs_adjoint,
rhs_sens_adjoint, and the initial-condition parameter-adjoint closure.
As in the previous closure examples, consider the logistic equation
\[\frac{dy}{dt} = r y (1 - y/K),\]
with the parameterized initial state
\[y(0) = y_0.\]
The parameter vector is \(p = [r, K, y_0]\), so the right-hand side is
\[f(y, p, t) = p_0 y (1 - y/p_1),\]
and the initial-condition function is
\[y_0(p, t) = p_2.\]
Using the autodiff feature, we can simply supply these equations, and std::autodiff will
automatically generate the required gradients for any type of solver in diffsol.
use super::{C, M, T, V};
use diffsol::{OdeBuilder, OdeEquationsImplicitAdjoint, OdeSolverProblem};
pub fn problem_autodiff(
r: f64,
k: f64,
y0: f64,
) -> OdeSolverProblem<impl OdeEquationsImplicitAdjoint<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.p([r, k, y0])
.rhs_autodiff(|x: &[T], p: &[T], _t, y: &mut [T]| {
y[0] = p[0] * x[0] * (1.0 - x[0] / p[1]);
})
.init_autodiff(
|p: &[T], _t, y: &mut [T]| {
y[0] = p[2];
},
1,
)
.build()
.unwrap()
}
Compiling standalone programs
Autodiff requires nightly Rust, the Enzyme backend, and fat LTO. Install the backend once for the nightly toolchain:
rustup +nightly component add enzyme
You must also enable the autodiff feature of diffsol in your Cargo.toml, because the autodiff builder methods (e.g. rhs_autodiff) are only available with this feature:
[dependencies]
diffsol = { version = "0.20", features = ["autodiff"] }
You can then enable autodiff for a single crate with RUSTFLAGS:
CARGO_PROFILE_RELEASE_LTO=fat \
RUSTFLAGS="-Zautodiff=Enable" \
cargo +nightly run --release
For more details on installing and using std::autodiff please consult the
internal and
user docs
Compiling workspaces
RUSTFLAGS applies to every crate that Cargo compiles, including dependencies.
When compiling the diffsol tests, we found that some of our dependencies
can fail to compile with -Zautodiff=Enable. If you run into a similar problem, a rustc wrapper can
append the flag only for crates that use autodiff. This repository's wrapper is
an example:
#!/bin/sh
rustc="$1"
shift
case "$2" in
diffsol|logistic_autodiff)
exec "$rustc" "$@" -Zautodiff=Enable
;;
esac
exec "$rustc" "$@"
Use it when building the logistic-autodiff workspace example:
CARGO_PROFILE_RELEASE_LTO=fat \
RUSTC_WRAPPER="$PWD/.github/scripts/autodiff-rustc-wrapper.sh" \
cargo +nightly run -p logistic-autodiff --features autodiff --release
Sparse problems
Let's consider a large system of equations that have a jacobian matrix that is sparse. For simplicity we will start with the logistic equation from the "Implicit" section, but we will duplicate this equation 10 times to create a system of 10 equations. This system will have a jacobian matrix that is a diagonal matrix with 10 diagonal elements, and all other elements are zero.
Since this system is sparse, we choose a sparse matrix type to represent the jacobian matrix. We will use the diffsol::FaerSparseMat<T> type, which is a thin wrapper around faer's SparseColMat type, a compressed sparse column (CSC) matrix.
use diffsol::{FaerSparseMat, MatrixCommon, OdeBuilder};
use diffsol::{OdeEquationsImplicit, OdeSolverProblem};
type M = FaerSparseMat<f64>;
type V = <M as MatrixCommon>::V;
type C = <M as MatrixCommon>::C;
type T = <M as MatrixCommon>::T;
pub fn problem_sparse() -> OdeSolverProblem<impl OdeEquationsImplicit<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.t0(0.0)
.rtol(1e-6)
.atol([1e-6])
.p(vec![1.0, 10.0])
.rhs_implicit(
|x, p, _t, y| {
for i in 0..10 {
y[i] = p[0] * x[i] * (1.0 - x[i] / p[1]);
}
},
|x, p, _t, v, y| {
for i in 0..10 {
y[i] = p[0] * v[i] * (1.0 - 2.0 * x[i] / p[1]);
}
},
)
.init(|_p, _t, y| y.fill(0.1), 10)
.build()
.unwrap()
}
Note that we have not specified the jacobian itself, but instead we have specified the jacobian multiplied by a vector function \(f'(y, p, t, v)\). diffsol will use this function to generate a jacobian matrix, and since we have specified a sparse matrix type, diffsol will attempt to guess the sparsity pattern of the jacobian matrix and use this to efficiently generate the jacobian matrix.
To illustrate this, we can calculate the jacobian matrix from the rhs function contained in the problem object:
use diffsol::{ConstantOp, Matrix, NonLinearOpJacobian, OdeEquationsImplicit, OdeSolverProblem};
pub fn print_jacobian(problem: &OdeSolverProblem<impl OdeEquationsImplicit>) {
let t0 = problem.t0;
let y0 = problem.eqn.init().call(t0);
let jacobian = problem.eqn.rhs().jacobian(&y0, t0);
let (idx, vals) = jacobian.triplet_iter();
for ((i, j), v) in idx.zip(vals) {
println!("({i}, {j}) = {v}");
}
}
which will print the jacobian matrix in triplet format:
(0, 0) = 0.98
(1, 1) = 0.98
(2, 2) = 0.98
(3, 3) = 0.98
(4, 4) = 0.98
(5, 5) = 0.98
(6, 6) = 0.98
(7, 7) = 0.98
(8, 8) = 0.98
(9, 9) = 0.98
diffsol attempts to guess the sparsity pattern of your jacobian matrix by calling the \(f'(y, p, t, v)\) function repeatedly with different one-hot vectors \(v\)
with a NaN value at each hot index. The output of this function (i.e. which elements are 0 and which are NaN) is then used to determine the sparsity pattern of the jacobian matrix.
Due to the fact that for IEEE 754 floating point numbers, NaN is propagated through most operations, this method is able to detect which output elements are dependent on which input elements.
However, this method is not foolproof, and it may fail to detect the correct sparsity pattern in some cases, particularly if values of v are used in control-flow statements.
If diffsol does not detect the correct sparsity pattern, you can manually specify the jacobian. To do this, you need to use a custom struct that implements the OdeEquations trait,
This is described in more detail in the "OdeEquations trait" section.
OdeEquations trait
While the OdeBuilder struct is a convenient way to specify the problem, it may not be suitable in all cases.
Often users will want to provide their own structs that can hold custom data structures and methods for evaluating the right-hand side of the ODE, the jacobian, and other functions.
Traits
To create your own structs for the ode system, the final goal is to implement the OdeEquations trait.
When you have done this, you can use the build_from_eqn method on the OdeBuilder struct to create the problem.
For each function in your system of equations, you will need to implement the appropriate trait for each function.
- Non-linear functions (rhs, out, root). In this case the
NonLinearOptrait needs to be implemented. - Linear functions (mass). In this case the
LinearOptrait needs to be implemented. - Constant functions (init). In this case the
ConstantOptrait needs to be implemented.
Additionally, each function needs to implement the base operation trait Op.
Once you have implemented the appropriate traits for your custom struct, you can use the OdeBuilder struct to specify the problem.
Non-linear functions
To illustrate how to implement a custom problem struct, we will take the familar logistic equation:
\[\frac{dy}{dt} = r y (1 - y/K),\]
Our goal is to implement a custom struct that can evaluate the rhs function \(f(y, p, t)\) and the jacobian multiplied by a vector \(f'(y, p, t, v)\).
To start with, lets define a few linear algebra types that we will use in our function. We need four types:
Tis the scalar type (e.g.f64)Vis the vector type (e.g.NalgebraVec<T>)Mis the matrix type (e.g.NalgebraMat<T>)Cis the context type for the rest (e.g.NalgebraContext)
use diffsol::{NalgebraContext, NalgebraMat, NalgebraVec};
pub type T = f64;
pub type V = NalgebraVec<T>;
pub type M = NalgebraMat<T>;
pub type C = NalgebraContext;
Next, we'll define a struct that we'll use to calculate our RHS equations \(f(y, p, t)\). We'll pretend that this struct has a reference to a parameter vector \(p\) that we'll use to calculate the rhs function. This makes sense since we'll have multiple functions that make up our systems of equations, and they will probably share some parameters.
use crate::V;
pub struct MyRhs<'a> {
pub p: &'a V,
}
Now we will implement the base Op trait for our struct. The Op trait specifies the types of the vectors and matrices that will be used, as well as the number of states and outputs in the rhs function.
use crate::{MyRhs, C, M, T, V};
use diffsol::{Op, Vector};
impl Op for MyRhs<'_> {
type T = T;
type V = V;
type M = M;
type C = C;
fn nstates(&self) -> usize {
1
}
fn nout(&self) -> usize {
1
}
fn nparams(&self) -> usize {
2
}
fn context(&self) -> &Self::C {
self.p.context()
}
}
Next we implement the NonLinearOp and NonLinearOpJacobian trait for our struct. These traits specify the functions that evaluate the rhs function and the Jacobian multiplied by a vector. The parameter vector is \(p = [r, K]\), so the rhs is \(f(y, p, t) = r y (1 - y/K)\) and the Jacobian-vector product is \(J v = r (1 - 2y/K) v\).
use crate::{MyRhs, T, V};
use diffsol::{NonLinearOp, NonLinearOpJacobian};
impl NonLinearOp for MyRhs<'_> {
fn call_inplace(&self, x: &V, _t: T, y: &mut V) {
let (r, k) = (self.p[0], self.p[1]);
y[0] = r * x[0] * (1.0 - x[0] / k);
}
}
impl NonLinearOpJacobian for MyRhs<'_> {
fn jac_mul_inplace(&self, x: &V, _t: T, v: &V, y: &mut V) {
let (r, k) = (self.p[0], self.p[1]);
y[0] = r * v[0] * (1.0 - 2.0 * x[0] / k);
}
}
There we go, all done! This demonstrates how to implement a custom struct to specify a rhs function.
Constant functions
Now we've implemented the rhs function, but how about the initial condition? We can implement the ConstantOp trait to specify the initial condition. Since this is quite similar to the NonLinearOp trait, we will do it all in one go.
use crate::{C, M, T, V};
use diffsol::{ConstantOp, Op, Vector};
pub struct MyInit<'a> {
pub p: &'a V,
}
impl Op for MyInit<'_> {
type T = T;
type V = V;
type M = M;
type C = C;
fn nstates(&self) -> usize {
1
}
fn nout(&self) -> usize {
1
}
fn nparams(&self) -> usize {
0
}
fn context(&self) -> &Self::C {
self.p.context()
}
}
impl ConstantOp for MyInit<'_> {
fn call_inplace(&self, _t: T, y: &mut V) {
y[0] = 0.1;
}
}
Linear functions
Naturally, we can also implement the LinearOp trait if we want to include a mass matrix in our model. A common use case for implementing this trait is to represent the mass matrix with a custom struct. The gemv_inplace method must calculate \(y = M x + \beta y\). In this example, the mass matrix is the \(1 \times 1\) identity matrix:
use crate::{C, M, T, V};
use diffsol::{LinearOp, Op, Vector};
pub struct MyMass<'a> {
pub p: &'a V,
}
impl Op for MyMass<'_> {
type T = T;
type V = V;
type M = M;
type C = C;
fn nstates(&self) -> usize {
1
}
fn nout(&self) -> usize {
1
}
fn nparams(&self) -> usize {
0
}
fn context(&self) -> &Self::C {
self.p.context()
}
}
impl LinearOp for MyMass<'_> {
fn gemv_inplace(&self, x: &V, _t: T, beta: T, y: &mut V) {
y[0] = x[0] + beta * y[0];
}
}
ODE systems
So far we've focused on using custom structs to specify individual equations, now we need to put these together to specify the entire system of equations.
Implementing the OdeEquations trait
To specify the entire system of equations, you need to implement the Op, OdeEquations
and OdeEquationsRef traits for your struct.
Getting all your traits in order
The OdeEquations trait requires methods that return objects corresponding to the right-hand side function, mass matrix, root function, initial condition, and output functions.
Therefore, you need to already have structs that implement the NonLinearOp, LinearOp, and ConstantOp traits for these functions. For the purposes of this example, we will assume that
you have already implemented these traits for your structs.
Often, the structs that implement these traits will have to use data defined in the struct that implements the OdeEquations trait. For example, they might wish to have a reference to the same parameter vector p. Therefore, you will often need to define lifetimes for these structs to ensure that they can access the data they need.
Note that these structs will need to be lightweight and should not contain a significant amount of data. The data should be stored in the struct that implements the OdeEquations trait. This is because these structs will be created and destroyed many times during the course of the simulation (e.g. every time the right-hand side function is called).
My custom ode equations
We'll define a central struct MyEquations that will hold the data for the entire system of equations. In this example, MyEquations will own a parameter vector p that is used by all the equations.
use crate::{C, V};
use diffsol::Vector;
pub struct MyEquations {
pub p: V,
}
impl MyEquations {
pub fn new() -> Self {
MyEquations {
p: V::from_vec(vec![1.0, 10.0], C::default()),
}
}
}
As with individual functions, we also need to implement the Op trait for this struct.
use crate::{MyEquations, C, M, T, V};
use diffsol::{Op, Vector};
impl Op for MyEquations {
type T = T;
type V = V;
type M = M;
type C = C;
fn nstates(&self) -> usize {
1
}
fn nout(&self) -> usize {
1
}
fn nparams(&self) -> usize {
2
}
fn context(&self) -> &Self::C {
self.p.context()
}
}
Implementing the OdeEquations traits
OdeEquations and OdeEquationsRef are a pair of traits that together define the system of equations using the individual function structs that we defined earlier. The OdeEquationsRef trait is designed to allow individual function structs to be able to reference the data in the main OdeEquations struct, allowing them to share data.
The OdeEquationsRef trait only defines the associated types of the function structs. The methods that return these structs are on the OdeEquations trait. Some of these methods are optional: root, out and reset have default implementations that return None, so you only need to implement the ones that are relevant for your problem. You must still supply an associated type in OdeEquationsRef for each function that you do not use. For these, use UnitCallable<M> as a placeholder. For example, if your problem does not have a reset function, set type Reset = UnitCallable<M> and do not implement the reset method.
use crate::{MyEquations, MyInit, MyMass, MyOut, MyRhs, MyRoot, M, V};
use diffsol::{OdeEquations, OdeEquationsRef, UnitCallable, Vector};
impl<'a> OdeEquationsRef<'a> for MyEquations {
type Rhs = MyRhs<'a>;
type Mass = MyMass<'a>;
type Init = MyInit<'a>;
type Root = MyRoot<'a>;
type Out = MyOut<'a>;
type Reset = UnitCallable<M>;
}
impl OdeEquations for MyEquations {
fn rhs(&self) -> <MyEquations as OdeEquationsRef<'_>>::Rhs {
MyRhs { p: &self.p }
}
fn mass(&self) -> Option<<MyEquations as OdeEquationsRef<'_>>::Mass> {
Some(MyMass { p: &self.p })
}
fn init(&self) -> <MyEquations as OdeEquationsRef<'_>>::Init {
MyInit { p: &self.p }
}
fn root(&self) -> Option<<MyEquations as OdeEquationsRef<'_>>::Root> {
Some(MyRoot { p: &self.p })
}
fn out(&self) -> Option<<MyEquations as OdeEquationsRef<'_>>::Out> {
Some(MyOut { p: &self.p })
}
fn reset(&self) -> Option<<MyEquations as OdeEquationsRef<'_>>::Reset> {
None
}
fn set_params(&mut self, p: &V) {
self.p.copy_from(p);
}
fn get_params(&self, p: &mut Self::V) {
p.copy_from(&self.p);
}
}
Creating the problem
Now that we have our custom OdeEquations struct, we can use it in an OdeBuilder to create the problem.
use crate::{MyEquations, M};
use diffsol::OdeBuilder;
pub fn build() {
OdeBuilder::<M>::new()
.p(vec![1.0, 10.0])
.build_from_eqn(MyEquations::new())
.unwrap();
}
Parameters
The fundamental trait that diffsol uses to specify a mathematical operation is Op.
This trait defines the number of parameters in your ODE model via Op::nparams.
When specifying your parameters with DiffSL or Rust closures, you are largely tied into
a specific notion of a parameter being any input parameter of your model that you want to
change between solves.
However, if you use a custom struct and the OdeEquations trait, you have much more
flexibility about defining and changing the parameters of your model, as we'll explore
below.
What is a "parameter"
A parameter of your model does not continuously vary with time, like the state variables, but is instead constant over the duration of an individual solve. If you were writing your equations using a custom struct, you might have one or more model parameters as fields on that struct, for example:
struct MyModel {
pub parameter_a: f64,
pub parameter_b: f64,
}
These parameters could then be used in your implementation of NonLinearOp, or any other diffsol trait. However,
it is entirely up to you if you report these to diffsol as parameters or not. You could
return 2 from nparams in the Op trait
and implement the set_params and get_params methods of the OdeEquations trait to set/get both parameter_a and
parameter_b, or you can return 0 from nparams and just set parameter_a and parameter_b manually
via their pub fields on the struct, it's up to you. This also gives you flexibility to
use parameter types that aren't supported by diffsol, for example int, bool, or arbitrary structs.
struct MyModel {
pub parameter_a: f64,
pub parameter_b: HashMap<String, f64>,
}
When to tell diffsol about a parameter
There are a few cases where you do need to report your parameter to diffsol, these are:
- You want to exclusively set/get parameters via the
OdeEquationstrait methodsset_paramsandget_params. For example you might want to write generic code that can work over any set of equations. - You want to calculate the gradient of your solution with respect to that parameter using a forward sensitivity solver.
- You want to calculate the gradient of a loss function with respect to that parameter using an adjoint sensitivity solver.
This decision can be made on a per-parameter basis. You can select which parameters of your model
you want to tell diffsol about, and which parameters you don't. Just make sure you are
consistent on the number and ordering of the parameters that you are reporting to diffsol, when you implement
get/set_params and the *Sens traits.
Varying parameters
The rust borrow checker governs any change to your model. Any change in a parameter of your model, whether it's a parameter you have reported to diffsol or otherwise, requires a mutation of your OdeEquations struct. Each solver that you create takes a reference to
OdeSolverProblem, and therefore to your custom OdeEquations struct, so you won't
be able to mutate it until you drop all the solvers with that reference. Given any instance of OdeSolverProblem, you can get a mutable reference to your custom OdeEquations struct using
OdeSolverProblem::eqn_mut.
Batching
All the matrix and vector traits in diffsol are implemented using batching, similar to the batching that you might be used to in several machine learning frameworks. This allows diffsol to solve nbatch ODEs in lockstep, which is particularly useful for solving many ODEs in parallel on the GPU.
This section covers configuring batches with OdeBuilder and working with batched vectors.
Builder
Each vector, matrix or operation in diffsol has its own context, which is used to configure the number of batches (as well as other backend-specific information). You can create a new context with a set number of batches using the with_nbatch method of the context type (e.g. NalgebraContext::with_nbatch).
let context = NalgebraContext::with_nbatch(NBATCH);
Give this context to the OdeBuilder::context method to create a new OdeSolverProblem with the specified number of batches. When you set the parameters, give a vector of values of length nparams * nbatch. Diffsol splits this vector into nbatch blocks of length nparams, one block for each batch lane.
Note that you can ignore batching when specifying your rhs, init and other equation closures. Each closure will be called once for each batch lane and will handle the specific broadcasting rules used by diffsol. The input arguments for each closure are &[T] slices that correspond to a single batch lane. Each closure does not return a value. It writes its result into a mutable &mut [T] output slice argument for the same batch lane.
let problem = OdeBuilder::<M>::new()
.context(context)
// Two parameters per lane. Parameter blocks are stored end to end:
// [lane 0 p0, lane 0 p1, lane 1 p0, lane 1 p1, ...].
.p([1.0, 10.0, 2.0, 20.0, 3.0, 30.0])
.rhs(|y: &[f64], p: &[f64], _t: f64, dy: &mut [f64]| {
// y, p, and dy are slices for one batch lane.
dy[0] = p[0] * y[0] + p[1];
})
.init(|p: &[f64], _t: f64, y: &mut [f64]| y[0] = p[1], 1)
.build()
.unwrap();
assert_eq!(problem.context().nbatch(), NBATCH);
let mut solver = problem.tsit45().unwrap();
solver.step().unwrap();
Vector Traits
While diffsol aims to hide the specifics of batching from the user as much as possible, it is sometimes necessary to work with batched vectors directly. The Vector trait provides a set of methods for working with batched vectors, including methods for accessing the number of batch lanes, the inner representation of the vector, and methods for iterating over batch lanes and elements.
For the trivial case of a single batch lane for a vector living on the host, the standard Index and IndexMut traits are implemented and can be used to access the elements of the vector. Note that these will panic if the vector has more than one batch lane, so they should only be used for single-batch vectors.
A batched Vector
To create a batched vector with NBATCH = 3 batches, you can create a Context with the number of batches and create a new vector with that specific context. The Vector::from_vec method takes a vector of length NBATCH * N and splits it into NBATCH separate vectors of length N.
let context = NalgebraContext::with_nbatch(NBATCH);
let x = V::from_vec(vec![1.0, 2.0, 10.0, 20.0, 100.0, 200.0], context);
All the backends store the batches as columns in a matrix type defined by that backend. For example we are using the nalgebra backend, which stores the vector using a DMatrix type, which you can obtain by using the VectorCommon::inner method.
assert_eq!(x.inner().nrows(), 2);
assert_eq!(x.inner().ncols(), NBATCH);
"for each" operations
Typically when you are using a vector you don't want to have to worry about the specifics of the number of batches. This is particularly the case if you are working with more than one vector with different numbers of batches, where broadcasting rules become important.
To mitigate this, the Vector trait provides a set of methods for working with individual batches/elements without worrying about batching. The Vector::for_each_batch method allows you to provide a closure that is executed for each batch lane, while vectors with a lesser (but compatible) number of batches will be broadcast to match the output vector, which must have the largest number of batches.
let mut z = V::zeros(2, *x.context());
z.for_each_batch([&x], |z, [x], _lane| {
z[0] = x[0] + x[1];
z[1] = x[0] - x[1];
});
So that it can be executed on a GPU device (if applicable), the closure passed to for_each_batch must be of type Fn and be both Copy and Send. If this is too restrictive and you don't care about solving on the GPU, you can instead use the Vector::for_each_batch_host method, which allows you to pass a closure of type FnMut that is not required to be either Copy or Send.
let mut y = V::zeros(2, *x.context());
y.for_each_batch_host([&x], |y, [x], lane| {
y[0] = x[0] + lane as f64;
y[1] = x[1] * 2.0;
});
Unless your ODE system is very small, when executing on the GPU you typically want to use one thread for each state vector element, rather than one thread for each batch lane. The Vector::for_each_elem method allows you to provide a closure that is executed for each element of the vector.
let mut scaled = V::zeros(2, *x.context());
scaled.for_each_elem([&x], |value, [x], _lane, i| {
*value = 10.0 * x[i];
});
Reductions
The Vector trait also has a couple of generic reduction methods for vectors. The Vector::reduce_elem method allows you to reduce over the elements of a vector for each batch lane, giving a final vector with N = 1 elements and NBATCH batch lanes.
let mut lane_max = V::zeros(1, *x.context());
V::reduce_elem(&mut lane_max, [&x], 0.0, |[x], _lane, i| x[i], f64::max);
assert_eq!(lane_max.clone_as_vec(), vec![2.0, 20.0, 200.0]);
The Vector::reduce_batch method allows you to reduce over the batch lanes of a vector, giving a final vector with N elements and NBATCH = 1 batch lanes.
let mut batch_max = V::zeros(2, NalgebraContext::default());
V::reduce_batch(&mut batch_max, [&x], 0.0, |[x], _lane, i| x[i], f64::max);
assert_eq!(batch_max.clone_as_vec(), vec![100.0, 200.0]);
Creating a solver
Once you have defined the problem, you need to create a solver to solve the problem. The available solvers are:
diffsol::Bdf: A Backwards Difference Formulae solver, suitable for stiff problems. It supports mass matrices, including singular mass matrices (DAEs).diffsol::Sdirk: A Singly Diagonally Implicit Runge-Kutta (SDIRK or ESDIRK) solver, suitable for stiff problems. It supports mass matrices, including singular mass matrices (DAEs). You can define your own Butcher tableau usingTableauor use one of the pre-defined tableaus.diffsol::ExplicitRk: An explicit Runge-Kutta solver, suitable for non-stiff problems. It does not support a mass matrix: if the problem has a mass matrix, creating the solver returns aMassMatrixNotSupportederror. You can define your own Butcher tableau usingTableauor use one of the pre-defined tableaus.
For the implicit solvers (BDF and SDIRK), you will need to specify the linear solver type to use. The explicit Runge-Kutta solver does not use a linear solver. The available linear solvers are:
diffsol::NalgebraLU: A LU decomposition solver using the nalgebra crate.diffsol::FaerLU: A LU decomposition solver using the faer crate.diffsol::FaerSparseLU: A sparse LU decomposition solver using thefaercrate.
Each solver can be created directly, but it is generally easier to use the methods on the OdeSolverProblem struct to create the solver.
For example:
use crate::{problem_implicit, LS};
pub fn create_solvers() {
let problem = problem_implicit();
// Create a BDF solver
let _bdf = problem.bdf::<LS>().unwrap();
// Create tr_bdf2 and esdirk34 solvers (both are SDIRK solvers with different tableaus)
let _tr_bdf2 = problem.tr_bdf2::<LS>();
let _esdirk34 = problem.esdirk34::<LS>();
// Create a TSIT45 solver (a ERK method), this does not require a linear solver
let _tsit45 = problem.tsit45();
}
Initialisation
Each solver has an internal state that holds information like the current state vector, the gradient of the state vector, the current time, and the current step size. When you create a solver using the bdf, tr_bdf2 or esdirk34 methods on the OdeSolverProblem struct, the solver will be initialised with an initial state based on the initial conditions of the problem as well as satisfying any algebraic constraints. The rk_state_and_consistent and bdf_state methods also create a consistent state. The rk_state method does not solve for the algebraic constraints, so the state is not consistent if the problem has a mass matrix. The tsit45 method also does not make the state consistent, but this is not necessary because the explicit Runge-Kutta solver does not support a mass matrix. An initial time step will also be chosen based on your provided equations.
Each solver's state struct implements the OdeSolverState trait, and if you wish to manually create and setup a state, you can use the methods on this trait to do so.
For example, say that you wish to bypass the initialisation of the state as you already have the algebraic constraints and so don't need to solve for them. You can use the new_without_initialise method on the OdeSolverState trait to create a new state without initialising it. You can then use the as_mut method to get a mutable reference to the state and set the values manually.
use crate::{problem_implicit, LS};
use diffsol::{BdfState, OdeSolverState, RkState};
pub fn create_solvers_uninit() {
let problem = problem_implicit();
// Create a non-initialised state and manually set the values before
// creating the solver
let mut state = RkState::new_without_initialise(&problem).unwrap();
// ... set the state values manually
state.as_mut().y[0] = 0.1;
let _solver = problem.tr_bdf2_solver::<LS>(state);
// Do the same for a BDF solver
let mut state = BdfState::new_without_initialise(&problem).unwrap();
state.as_mut().y[0] = 0.1;
let _solver = problem.bdf_solver::<LS>(state);
}
Note that each state struct has a as_ref and as_mut methods that return a StateRef or StateRefMut struct respectively. These structs provide a solver-independent way to access the state values so you can use the same code with different solvers.
Butcher Tableau
The Butcher tableau is a way of representing the coefficients of a Runge-Kutta method (see the wikipedia page). diffsol uses the Tableau struct to represent the tableau, and this is used to create any of the SDIRK or ERK solvers. diffsol has a few inbuilt tableaus that you can use, otherwise you can create your own by constructing an instance of Tableau.
To create an SDIRK or ERK solver using a pre-defined tableau, you can use methods on the OdeSolverProblem struct like so:
use crate::{problem_implicit, LS, M};
use diffsol::Tableau;
pub fn create_solvers_tableau() {
let problem = problem_implicit();
// Create a SDIRK solver with a pre-defined tableau
let tableau = Tableau::tr_bdf2();
let state = problem.rk_state(&tableau).unwrap();
let _solver = problem.sdirk_solver::<LS, M>(state, tableau);
// Create an ERK solver with a pre-defined tableau
let tableau = Tableau::tsit45();
let state = problem.rk_state(&tableau).unwrap();
let _solver = problem.explicit_rk_solver::<M>(state, tableau);
}
The rk_state method in this example does not make the initial state consistent with any algebraic constraints. If your problem has a mass matrix, use rk_state_and_consistent instead to create the state for an SDIRK solver. The explicit Runge-Kutta solver does not support a mass matrix.
Solver options
The default options are suitable for most problems. You can change them at two levels:
- The problem. The fields
ode_options(OdeSolverOptions) andic_options(InitialConditionSolverOptions) of theOdeSolverProblemapply to all the solvers that you create from the problem. Set them before you create a solver. - The solver. When you create a solver, it copies its limits from
ode_optionsinto its config:BdfConfig,SdirkConfigorExplicitRkConfig. Usesolver.config_mut()to change the limits of one solver after you create it.
The tolerances are not in these options. See Tolerances.
use crate::{problem_implicit, LS};
use diffsol::OdeSolverMethod;
pub fn solver_options() {
let mut problem = problem_implicit();
// options for every solver that you create from this problem
problem.ode_options.max_number_timesteps = 10_000;
problem.ode_options.max_nonlinear_solver_iterations = 5;
problem.ic_options.max_newton_iterations = 20;
let mut solver = problem.bdf::<LS>().unwrap();
// limits for this solver only, after you create it
solver.config_mut().maximum_timestep_growth = 5.0;
let (_ys, _ts, _stop_reason) = solver.solve(10.0).unwrap();
let stats = solver.get_statistics();
println!(
"steps: {}, error test failures: {}, nonlinear iterations: {}, linear solver setups: {}",
stats.number_of_steps,
stats.number_of_error_test_failures,
stats.number_of_nonlinear_solver_iterations,
stats.number_of_linear_solver_setups,
);
}
ODE solver options
These are the main fields of OdeSolverOptions. The API documentation describes all the fields, including the step-size controller.
| Field | Default | Description |
|---|---|---|
max_number_timesteps | 5000 | The maximum number of steps. All the solve* calls with the same solver share this limit. |
min_timestep | machine epsilon | The minimum step size. |
max_error_test_failures | 40 | The maximum number of rejected attempts in one step. |
max_nonlinear_solver_failures | 10 | The maximum number of Newton failures in one step (implicit solvers only). |
max_nonlinear_solver_iterations | 10 | The maximum number of Newton iterations in one nonlinear solve (implicit solvers only). |
nonlinear_solver_tolerance | 0.2 | A scale factor for the Newton convergence test. A smaller value gives a tighter tolerance. |
derivative_solve_tolerance | 0.2 | A scale factor for the convergence test of the linear solves of the forward sensitivities and the discrete adjoint (BDF and SDIRK only). |
max_timestep_growth | 2 | The maximum increase of the step size in one step, as a ratio. |
min_timestep_shrink | 0.5 | The maximum decrease of the step size in one step, as a ratio. |
update_jacobian_after_steps | 20 | The maximum number of steps between two setups of the linear solver. |
update_rhs_jacobian_after_steps | 50 | The maximum number of steps between two calculations of the Jacobian of the right-hand side. |
fixed_step | false | Turn off error control and take steps of a constant size. You can use this only with manual time-stepping, and you cannot set a stop time. |
Initial condition options
If the problem has a singular mass matrix, the implicit solvers solve for the algebraic variables when you create the solver (see Initialisation). ic_options controls this Newton solve:
| Field | Default | Description |
|---|---|---|
use_linesearch | true | Use a backtracking line search. |
max_linesearch_iterations | 10 | The maximum number of line-search iterations. |
max_newton_iterations | 10 | The maximum number of Newton iterations. |
max_linear_solver_setups | 4 | The maximum number of setups of the linear solver. |
step_reduction_factor | 0.5 | The factor that decreases the step in the line search. |
armijo_constant | 1e-4 | The Armijo constant of the line search. |
If this solve does not converge, the solver constructor returns an InitialConditionDidNotConverge error.
Statistics
solver.get_statistics() returns an OdeSolverStatistics struct, which counts what the solver did. The example above prints some of its fields:
number_of_steps: the number of steps.number_of_error_test_failures: the number of rejected attempts.number_of_nonlinear_solver_iterationsandnumber_of_nonlinear_solver_fails: the Newton iterations and failures.number_of_linear_solver_setups: the number of Jacobian and LU setups. Other fields give the cause of each setup.
Use these values to find why a solve is slow, or to compare solvers. For example, if there are many error test failures, the problem is possibly stiff, and an implicit solver can be better than an explicit solver (see Stiff vs Non-Stiff).
Solving the problem
Each solver implements the OdeSolverMethod trait, which provides a number of high-level methods to solve the problem.
solve- solve the problem from an initial state up to a specified time, returning the solution at all the internal timesteps used by the solver.solve_dense- solve the problem from an initial state, returning the solution at aVecof times provided by the user.
If the equations define both a root function and a reset operator, these two methods apply the reset automatically and continue the forward solve.
The following example shows how to solve a simple ODE problem up to \(t=10\) using the solve method on the OdeSolverMethod trait. The solve method returns a tuple (ys, ts, stop_reason): the solution at all the internal timesteps used by the solver (_ys), the timesteps used by the solver (_ts), and the reason that the solver stopped (_stop_reason). The solution is returned as a matrix whose columns are the solution at each timestep.
use crate::{T, V};
use diffsol::{OdeEquations, OdeSolverMethod};
pub fn solve<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations<T = T, V = V> + 'a,
{
let (_ys, _ts, _stop_reason) = solver.solve(10.0).unwrap();
}
solve_dense will solve a problem from an initial state. It returns a tuple (ys, stop_reason), where ys is a matrix whose columns are the solution at each timestep in times. If a root is found and the equations do not define a reset operator, the solver stops at the root. In this case, the last column of ys is the solution at the root time, and the columns for the remaining times in times are removed. See Stopping for more information.
use crate::{T, V};
use diffsol::{OdeEquations, OdeSolverMethod};
pub fn solve_dense<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations<T = T, V = V> + 'a,
{
let times = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let _soln = solver.solve_dense(×).unwrap();
}
Manual time-stepping
The fundamental method to step the solver through a solution is the step method on the OdeSolverMethod trait, which steps the solution forward in time by a single step, with a step size chosen by the solver in order to satisfy the error tolerances in the problem struct. The step method returns a Result<OdeSolverStopReason<T>, DiffsolError>. If the step is successful, the OdeSolverStopReason tells you why the step stopped:
InternalTimestep: the solver took a normal internal step.RootFound(t, idx): the root function with indexidxchanged sign at timet.TstopReached: the solver reached the stop time set withset_stop_time.
The step method does not return the new state. Use solver.state() to get the current time, state vector and other state values after the step. See Stopping for how to use the stop reason.
use diffsol::OdeSolverMethod;
pub fn solve_step<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: diffsol::OdeEquations<T = f64> + 'a,
{
while solver.state().t < 10.0 {
if solver.step().is_err() {
break;
}
}
}
The step method returns an error if:
- the solver has already taken
ode_options.max_number_timestepssteps (TooManyTimesteps). The default is 5000. The step count is not reset between calls, so successivesolve*calls with the same solver share this limit. - the step size becomes smaller than
ode_options.min_timestep(StepSizeTooSmall). - the error test fails more than
ode_options.max_error_test_failurestimes in one step (TooManyErrorTestFailures). - the nonlinear solver fails to converge more than
ode_options.max_nonlinear_solver_failurestimes in one step (TooManyNonlinearSolverFailures, implicit solvers only).
See Error handling for how to handle these errors, and Solver options for how to change the limits.
Interpolation
Often you will want to get the solution at a specific time \(t_o\), which is probably different to the internal timesteps chosen by the solver. To do this, you can use the step method to first step the solver forward in time until you are just beyond \(t_o\), and then use the interpolate method to get the solution at \(t_o\).
use crate::{T, V};
use diffsol::{OdeEquations, OdeSolverMethod};
pub fn solve_interpolate<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations<V = V, T = T> + 'a,
{
let t_o = 10.0;
while solver.state().t < t_o {
solver.step().unwrap();
}
let _soln = solver.interpolate(t_o).unwrap();
}
Stopping
You can stop the solver at a specific time, or when a certain event occurs (a root of the root function). How you do this depends on whether you use the high-level solve methods or manual time-stepping.
Stopping with high-level solve methods
The high-level solve and solve_dense methods stop the solver when either the final time tfinal is reached, or when one of the elements of the root function returns a value that changes sign. The internal state of the solver (t, y, dy etc.) is set to the time that the zero-crossing occurred.
If a reset function is also defined, solve and solve_dense apply the reset automatically at the root time and continue integrating to the requested final time or final evaluation point. In solve_dense, any user-specified evaluation time that lands exactly on the event receives the pre-reset state.
The public solve_dense_sensitivities method also applies resets automatically when the equations provide sensitivity-aware root and reset operators. The checkpointing methods used for adjoint sensitivities, solve_with_checkpointing and solve_dense_with_checkpointing, also apply the reset and continue. They split the checkpoints into segments at each reset, and the backwards adjoint solve applies the reset to the adjoint state at the boundary between segments.
The lower-level step method and the staged solves solve_soln, solve_soln_sensitivities and solve_soln_with_checkpointing do not apply resets. They stop at a root and return RootFound, so that the caller can decide how to resume.
Manual time-stepping
Stopping at a specific time is straightforward, as you can use the set_stop_time method on the OdeSolverMethod trait and then just check if the return value of the step method is Ok(OdeSolverStopReason::TstopReached)
Stopping at a certain event requires you to set a root function in your system of equations, see Root Finding for more information. During time-stepping, you can check if the solver has discovered a root by checking if the return value of the step method is Ok(OdeSolverStopReason::RootFound). RootFound holds the time at which the root was found, and the index of the root that was found. You can use the interpolate method to obtain the solution at the root time.
use diffsol::{OdeEquations, OdeSolverMethod, OdeSolverStopReason};
pub fn solve_match_step<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations<T = f64> + 'a,
{
solver.set_stop_time(10.0).unwrap();
loop {
match solver.step() {
Ok(OdeSolverStopReason::InternalTimestep) => continue,
Ok(OdeSolverStopReason::TstopReached) => break,
Ok(OdeSolverStopReason::RootFound(_t, _idx)) => break,
Err(e) => panic!("Solver failed to converge: {e}"),
}
}
println!("Solver stopped at time: {}", solver.state().t);
}
Forward Sensitivities
The SensitivitiesOdeSolverMethod trait provides a way to compute the forward sensitivities of the solution of an ODE problem, using its solve_dense_sensitivities method.
This method computes both the solution and the sensitivities at the same time, at the time-points provided by the user. These are returned as a tuple with three items:
- A matrix of the solution at each time-point, where each column corresponds to a time-point and each row corresponds to a state variable.
- a
Vecof matrices containing the sensitivities at each time-point. Each element of the outer vector corresponds to the sensitivities for each parameter, and each column of the inner matrix corresponds to a time-point. - the reason that the solver stopped (an
OdeSolverStopReason), see Stopping.
use crate::{M, T, V};
use diffsol::{OdeEquationsImplicitSens, SensitivitiesOdeSolverMethod};
pub fn solve_fwd_sens<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: SensitivitiesOdeSolverMethod<'a, Eqn>,
Eqn: OdeEquationsImplicitSens<T = T, V = V, M = M> + 'a,
{
let t_evals = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let (y, sens, _stop_reason) = solver
.solve_dense_sensitivities(t_evals.as_slice())
.unwrap();
println!("solution: {y:?}");
for (i, dydp_i) in sens.iter().enumerate() {
println!("sens wrt parameter {i}: {dydp_i:?}");
}
}
Adjoint Sensitivities
Adjoint sensitivity analysis calculates the gradient of a scalar cost function \(G\) with respect to the parameters \(p\). The cost of the backwards pass does not increase much with the number of parameters, so adjoints are a good choice for models with many parameters. The Backwards Sensitivity Analysis section of the primer gives the theory.
diffsol has two adjoint methods:
- The continuous adjoint ("optimise-then-discretise") solves the adjoint equations backwards in time with an ODE solver. The gradient is an approximation of the gradient of the exact solution, with an error that the solver tolerances control.
- The discrete adjoint ("discretise-then-optimise") differentiates the steps that the forward solver took, in reverse order. The gradient is the gradient of the numerical solution, with the step sizes held constant. It agrees with the gradient from the forward sensitivities.
We generally recommend the discrete adjoint. It does not solve a second ODE, so it is usually faster. Its gradient is also the exact gradient of the forward solve. With an implicit solver, the gradient is exact only to the tolerance of the linear solves in the backwards pass. The continuous adjoint is useful in the cases that the discrete adjoint does not support at the moment:
- the forward solve stops at root events.
- the cost function is the integral of the output.
- the forward solve has so many steps that the tape of the discrete adjoint uses too much memory.
For both methods, the problem must implement OdeEquationsImplicitAdjoint. For a problem made from closures, see Adjoint Sensitivity. A problem made from DiffSL implements this trait automatically.
The continuous adjoint
A continuous adjoint solve has two passes:
-
The forward pass. Solve the problem forwards in time with a checkpointed solve. This saves checkpoints of the solver state, so that the backwards pass can get the forward solution at any time.
solve_with_checkpointingsolves to a final time, likesolve.solve_dense_with_checkpointingsolves at the times that you give, likesolve_dense.
The second argument of both methods is the maximum number of steps between two checkpoints. If it is
None, the value is 500. -
The backwards pass. Make an adjoint solver from the checkpoints, then call
solve_adjoint_backwards_pass. This method solves the adjoint equations backwards in time, from the end of the forward pass to the start, and returns the final adjoint state. The fieldsgof this state holds the gradient \(dG/dp\).
Each solver has a method that makes its adjoint solver: bdf_solver_adjoint, tr_bdf2_solver_adjoint, esdirk34_solver_adjoint and tsit45_solver_adjoint. These methods take three arguments:
- the checkpoints from the forward pass.
- an optional copy of the forward solver. The adjoint solver uses this copy to solve again between two checkpoints when it needs the forward solution at more times. You can use
Noneonly if the checkpoints already contain all the forward solution that the backwards pass needs. - an optional number of adjoint outputs. Use
Noneto use the number of outputs of the problem.
The adjoint solver can use a different method from the forward solver. For example, you can use a BDF solver for the forward pass and a TR-BDF2 solver for the backwards pass.
Cost function: the integral of the output
If you give no data to the backwards pass, the cost function is the integral of the problem output \(u(y)\) over the solve:
\[ G = \int_{t_0}^{t_f} u(y(t)) \, dt. \]
If the problem has no output function, the output is the state. For this cost function, the problem must set integrate_out to true. If it does not, the gradient is zero.
There is one cost function for each output, so sg holds one gradient for each output.
use crate::{C, LS, M, T, V};
use diffsol::{
AdjointOdeSolverMethod, OdeEquationsImplicitAdjoint, OdeSolverMethod, OdeSolverState, Vector,
};
pub fn solve_adjoint_sens<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquationsImplicitAdjoint<T = T, V = V, C = C, M = M> + 'a,
{
// forward pass: solve to t = 10 and save checkpoints
let (checkpointing, _soln, _times, _stop_reason) =
solver.solve_with_checkpointing(10.0, None).unwrap();
// backward pass: G is the integral of the output (the problem must set integrate_out)
let adjoint_solver = solver
.problem()
.bdf_solver_adjoint::<LS, _>(checkpointing, Some(solver.clone()), None)
.unwrap();
let (final_state, _) = adjoint_solver
.solve_adjoint_backwards_pass(&[], &[])
.unwrap();
println!("dG/dp = {:?}", final_state.as_ref().sg.clone_as_vec());
}
Cost function: a sum over data times
A cost function that compares the solution with data is often a sum of functions \(g_i\) at the data times \(t_i\):
\[ G = \sum_{i} g_i(u(y(t_i))). \]
For example, the sum of squared errors uses \(g_i = (u(y(t_i)) - d_i)^2\), where \(d_i\) is the data at \(t_i\).
For this cost function, give the backwards pass the data times t_eval and the gradients \(dg_i/du\). Each item of the slice dgdu_eval is a dense matrix with one row for each output and one column for each data time. Column \(i\) is \(dg_i/du\) at \(t_i\). You can calculate it from the solution of the forward pass. Each matrix in the slice gives one cost function, so the number of adjoint outputs must be equal to the number of matrices.
In this example, the logistic problem is compared with data that comes from the same model with a different growth rate:
use crate::{C, LS, M, T, V};
use diffsol::{
AdjointOdeSolverMethod, DenseMatrix, Matrix, OdeEquationsImplicitAdjoint, OdeSolverMethod,
OdeSolverState, Vector,
};
pub fn solve_adjoint_sens_sum_squares<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquationsImplicitAdjoint<T = T, V = V, C = C, M = M> + 'a,
{
// measured data d_i at times t_i (here the logistic solution with r = 1.2)
let t_data = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let y_data = [0.1, 0.3245, 1.0019, 2.699, 5.5104, 8.0296];
// forward pass: solve at the data times and save checkpoints
let (checkpointing, soln, _stop_reason) = solver
.solve_dense_with_checkpointing(&t_data, None)
.unwrap();
// G = sum_i (u(t_i) - d_i)^2, so column i of dgdu is 2 (u(t_i) - d_i)
let mut dgdu = M::zeros(1, t_data.len(), *solver.problem().eqn().context());
for (i, d) in y_data.iter().enumerate() {
dgdu.set_index(0, i, 2.0 * (soln.get_index(0, i) - d));
}
// backward pass: one set of g_i functions, so nout_override = 1
let adjoint_solver = solver
.problem()
.bdf_solver_adjoint::<LS, _>(checkpointing, Some(solver.clone()), Some(1))
.unwrap();
let (final_state, _) = adjoint_solver
.solve_adjoint_backwards_pass(&t_data, &[&dgdu])
.unwrap();
println!("dG/dp = {:?}", final_state.as_ref().sg.clone_as_vec());
}
Tolerances
The adjoint equations and the parameter gradient have their own tolerances. See Tolerances.
Events
If the forward pass stops at roots and applies resets, the checkpoints are split at each reset. The backwards pass applies the related correction to the adjoint state at each reset automatically.
The discrete adjoint
The StepVjp trait gives the discrete adjoint. The BDF, SDIRK and explicit Runge-Kutta solvers implement it.
The cost function is a sum over data times, as above:
\[ G = \sum_{i} g_i(u(y(t_i))). \]
The solve_dense_vjp method does the full calculation in one call. It solves forwards to the times t_eval and saves the solver state after each step. Then it goes back through the steps in reverse order, and returns the cost function \(G\) and the gradient \(dG/dp\). It takes these arguments:
t_eval: the data times \(t_i\).ndirections: the number of cost functions. One backwards pass can calculate the gradients of more than one cost function.g: a closure that adds \(g_i(u_i)\) to the cost function. Its arguments are(i, t_i, u_i, out).dgdu: a closure that writes \(dg_i/du_i\). Its arguments are also(i, t_i, u_i, out).
This example uses the same problem and data as the continuous adjoint example above. It does not need a separate adjoint solver or checkpoints:
use crate::{C, M, T, V};
use diffsol::{OdeEquationsImplicitAdjoint, StepVjp, Vector};
pub fn solve_discrete_adjoint_sens<'a, Solver, Eqn>(solver: &mut Solver)
where
Solver: StepVjp<'a, Eqn>,
Eqn: OdeEquationsImplicitAdjoint<T = T, V = V, C = C, M = M> + 'a,
{
// measured data d_i at times t_i (here the logistic solution with r = 1.2)
let t_data = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0];
let y_data = [0.1, 0.3245, 1.0019, 2.699, 5.5104, 8.0296];
// G = sum_i (u(t_i) - d_i)^2, with one loss (ndirections = 1)
let (loss, dgdp) = solver
.solve_dense_vjp(
&t_data,
1,
// add g_i(u_i) to the loss
|i, _t, u, g| g[0] += (u[0] - y_data[i]).powi(2),
// write dg_i/du_i
|i, _t, u, dgdu| dgdu[0] = 2.0 * (u[0] - y_data[i]),
)
.unwrap();
println!("G = {}, dG/dp = {:?}", loss[0], dgdp.clone_as_vec());
}
If you want to calculate \(dg_i/du\) yourself, or use one forward solve for more than one cost function, use the two halves of solve_dense_vjp:
solve_dense_vjp_fwdsolves forwards and returns the solution and a tape of the steps.solve_dense_vjp_bkwdtakes the tape and a matrix of \(dg_i/du\) (the same asdgdu_evalfor the continuous adjoint), and returns \(dG/dp\). The tape does not change, so you can use it again for a different cost function.
The spring-mass fitting example uses these two methods, and compares them with the continuous adjoint. For full control, step_vjp and interpolate_vjp differentiate one step and one interpolation.
The discrete adjoint has these limits:
- The forward solve must not stop at a root, and the problem must not set
integrate_out. A cost function that is the integral of the output is not available. - The tape holds the solver state after every step, so its memory increases with the number of steps. The continuous adjoint saves a checkpoint only every 500 steps (by default).
- If the mass matrix depends on the parameters, the gradient does not include that term.
Error handling
All the diffsol methods that can fail return a Result<_, DiffsolError>. DiffsolError implements std::error::Error, so you can use the ? operator in a function that returns a Result<_, Box<dyn std::error::Error>>.
DiffsolError has these variants:
| Variant | Cause |
|---|---|
OdeSolverError | The ODE solver failed, or you used it incorrectly. It holds an OdeSolverError, see below. |
NonLinearSolverError | A Newton solve failed, for example the initial condition solve (InitialConditionDidNotConverge). |
LaError | A linear algebra operation failed, for example an LU factorisation. |
DiffslParserError, DiffslCompilerError | The DiffSL code has an error. |
Other | Any other error. |
Errors during a solve
These OdeSolverError variants tell you that the solver could not continue. The Solver options page gives the options that control each limit.
TooManyTimesteps: the solver tookmax_number_timestepssteps (default 5000). Increase the limit. If the problem is stiff, use an implicit solver, which takes fewer steps.StepSizeTooSmall: the step size became smaller thanmin_timestep. The solution possibly has a singularity or a discontinuity. For a singularity, check the equations and the parameters. For a discontinuity, stop the solver at the discontinuity, then continue the solve (see Discrete Events).TooManyErrorTestFailures: one step was rejected more thanmax_error_test_failurestimes. Frequent causes are discontinuities, or functions that are not smooth, in the solution or in the right-hand side. Stop the solver at each discontinuity, then continue the solve.TooManyNonlinearSolverFailures: the Newton solve failed more thanmax_nonlinear_solver_failurestimes in one step. Check the Jacobian. An incorrect Jacobian is a frequent cause of Newton failures.
Each of these errors gives the time time at which the solver stopped.
Errors from incorrect use
Other OdeSolverError variants tell you that the solver was used incorrectly. Some examples are:
StopTimeBeforeCurrentTimeandStopTimeAtCurrentTime: the stop time must be after the current time.InvalidTEval: the times given tosolve_densemust increase, and they must not be before the current time.InterpolationTimeAfterCurrentTimeandInterpolationTimeOutsideCurrentStep: you can interpolate only inside the last step.MassMatrixNotSupported: the explicit Runge-Kutta solver does not support a mass matrix.FailedToGetMutableReference: a solver still borrows the problem. Drop the solver, or calltake_state(), before you change the problem.
Example: continue after too many steps
A solver keeps the state of its last step after a TooManyTimesteps error. In this example, the limit is too small. The code matches on the error, increases the limit with config_mut(), and continues the solve from the last step:
use crate::{problem_implicit, LS};
use diffsol::{error::OdeSolverError, DiffsolError, OdeSolverMethod};
pub fn solve_error_handling() {
let mut problem = problem_implicit();
problem.ode_options.max_number_timesteps = 10;
let mut solver = problem.bdf::<LS>().unwrap();
match solver.solve(10.0) {
Ok((_ys, ts, _stop_reason)) => println!("solved to t = {}", ts.last().unwrap()),
Err(DiffsolError::OdeSolverError(OdeSolverError::TooManyTimesteps { time, num_steps })) => {
println!("stopped after {num_steps} steps at t = {time}");
// the solver keeps the state of its last step: increase the limit and continue
solver.config_mut().maximum_number_timesteps = 5000;
let (_ys, ts, _stop_reason) = solver.solve(10.0).unwrap();
println!(
"continued from t = {} to t = {}",
ts.first().unwrap(),
ts.last().unwrap()
);
}
Err(e) => panic!("solve failed: {e}"),
}
}
Performance
This section collects a number of tips and advice on the various configuration options, solvers, backends available in diffsol, focusing on optimising the performance (wall-time / memory / parallelism) of the solvers.
Stiff vs Non-Stiff
ODE problems are often categorised as being either stiff or non-stiff. These categories are loosely defined, but some of the characteristics of stiff problems are:
- widely separate timescales or fast/slow modes, for example a problem that exhibits modes with decay rates of \(1\) and \(10^6\).
- a Jacobian \(J(t, y) = \frac{\partial f}{\partial y}\) that has eigenvalues with large negative real parts. This indicates rapidly decaying modes with short timescales.
- solving with explicit solvers leads to very small steps. The solution may look smooth and slowly varying, but tiny explicit steps are required.
- small perturbations to a slowly varying solution decay very rapidly.
Note that just because a solution rapidly changes, this does not mean that it is stiff. For example the problem
$$ \frac{dy}{dt}=\cos(1000t) $$
requires very small steps to maintain accuracy, but this does not mean that the problem is stiff. On the other hand, a slowly changing solution can be stiff
$$ \frac{dy}{dt}=-1000(y-\cos t)-\sin t. $$
After an initial fast transient, the solution stays close to the slow solution \(y = \cos t\), but explicit methods will still be constrained by the first term and take very small steps.
diffsol has a few solvers, both explicit and implicit, for solving ODE problems. Choosing a solver is balanced by a few characteristics of the problem, one of which is how stiff the problem is. Explicit methods such as Tsitouras 4(5) (Tsit45) are a good fit for non-stiff problems. They have inexpensive steps and can choose their step sizes primarily from the requested accuracy. Implicit methods such as the backward differentiation formula (BDF) do more work per step, including solving nonlinear systems, but can take much larger stable steps on stiff problems.
The performance-solver-comparison example solves two different problems, one non-stiff and the other stiff, using an explicit solver (Tsit45) and an implicit solver (BDF). It uses dense nalgebra vectors and matrices, with an LU linear solver for BDF:
type M = NalgebraMat<f64>;
type LS = NalgebraLU<f64>;
Non-stiff Logistic Growth
The logistic equation is smooth and has one natural timescale:
$$ \begin{align} y'(t) &= 2y(t)\left(1 - \frac{y(t)}{10}\right), \\ \qquad y(0) &= 0.5, \\ \qquad 0 &\leq t \leq 5. \end{align} $$
Its exact solution is
$$ y(t) = \frac{10}{1 + 19e^{-2t}}. $$
There is no fast transient forcing the solver to use a small stable step. Tsit45 can therefore solve this problem using fewer steps than BDF. BDF remains accurate, but its nonlinear solves are unnecessary overhead for this problem, and it may even end up taking many more steps than Tsit45 because it is, by necessity, conservative about changing its step size so as to reduce the number of times the Jacobian must be factorised.
The explicit definition supplies only the right-hand side; BDF needs the implicit definition, which additionally supplies the Jacobian-vector product.
OdeBuilder::<M>::new()
.rtol(RTOL)
.atol([ATOL])
.rhs(|y, _p, _t, dy| dy[0] = 2.0 * y[0] * (1.0 - y[0] / 10.0))
.init(|_p, _t, y| y[0] = 0.5, 1)
.build()
.unwrap()
Stiff Rapid Relaxation
The second problem has a fast transient and a slow long-term solution:
$$ \begin{align} y'(t) &= -1000\bigl(y(t) - \cos t\bigr) - \sin t, \\ \qquad y(0) &= 0, \\ \qquad 0 &\leq t \leq 10. \end{align} $$
Its exact solution is
$$ y(t) = \cos t - e^{-1000t}. $$
The \(e^{-1000t}\) component decays almost immediately, leaving the slowly varying \(\cos t\) solution. Despite that slow solution, an explicit method remains limited by the fast eigenvalue for stability and must take steps of roughly \(0.003\) or smaller. BDF is stable at much larger steps, which lets it follow the slow solution efficiently after the transient.
The explicit and implicit definitions follow the same pattern as logistic growth. The implicit version provides the constant Jacobian-vector product \(Jv = -1000v\) required by BDF.
OdeBuilder::<M>::new()
.rtol(RTOL)
.atol([ATOL])
.rhs(|y, _p, t, dy| dy[0] = -1000.0 * (y[0] - t.cos()) - t.sin())
.init(|_p, _t, y| y[0] = 0.0, 1)
.build()
.unwrap()
Running The Comparison
The example runs all four combinations and records the elapsed solve time, final value, time steps, rejected steps, and right-hand-side evaluations. The solve routines differ only in their solver construction: Tsit45 accepts an explicit problem, while BDF accepts an implicit problem and needs the linear-solver type.
let mut solver = problem.tsit45().unwrap();
let started = Instant::now();
let (solution, _) = solver.solve_dense(&[final_time]).unwrap();
let elapsed = started.elapsed();
let value = solution.column(0)[0];
let solver_stats = solver.get_statistics();
let equation_stats = solver.problem().eqn.statistics();
RunResult {
problem: problem_name,
solver: "Tsit45",
elapsed,
value,
steps: solver_stats.number_of_steps,
error_test_failures: solver_stats.number_of_error_test_failures,
rhs_evals: equation_stats.number_of_calls,
}
Results
The example writes the results of its latest run to this table:
| Problem | Solver | Time (ms) | Final | Steps | Rejects | RHS evals |
|---|---|---|---|---|---|---|
| logistic | Tsit45 | 0.256 | 9.99138061 | 24 | 2 | 158 |
| logistic | BDF | 1.015 | 9.99137659 | 94 | 4 | 149 |
| rapid relaxation | Tsit45 | 27.027 | -0.83907087 | 3181 | 5 | 19118 |
| rapid relaxation | BDF | 2.228 | -0.83907164 | 235 | 14 | 301 |
Wall-clock times depend on the machine and build profile, but they should always show similar trends, and the number of steps and RHS evals should be stable. For logistic growth, the explicit solver needs far fewer steps than BDF, likely because the BDF solver is conservative when adapting its step size for a given problem. Each step takes roughly the same wall time for the two solvers. BDF must solve a nonlinear problem at each step, but it reuses the factorisation of the Jacobian over many steps. Because this nonlinear problem is simple, BDF needs only a small number of RHS evaluations per step. In this run, the total number of RHS evaluations is similar for the two solvers (158 for Tsit45 and 149 for BDF), so BDF uses slightly fewer evaluations even though it takes approximately four times as many steps.
For rapid relaxation, Tsit45 needs significantly more stability-limited steps and RHS evaluations, leading to an order of magnitude difference in the wall-times between the two solvers.
The take home message of this example is: use an explicit solver for smooth non-stiff systems, and prefer BDF when fast and slow timescales make the system stiff.
We have used the BDF solver in this example, but there are other implicit solvers in diffsol that are also suitable for stiff systems, including TR-BDF2 and ESDIRK34.
However, BDF tends to be a consistently high-performing solver, so it is usually beneficial to try this one first and fallback to TR-BDF2 or ESDIRK34 if needed.
The BDF solver is a multistep solver, so it uses a history of the past n steps to take the next one. This normally works well, but its performance can be reduced
for problems involving discrete events.
Events and Multistep Solvers
Repeated discontinuities can change which stiff solver is most efficient. A multistep method such as BDF uses solution history to achieve high order. A state jump invalidates that history, so BDF must restart at first order. A one-step method such as ESDIRK34 has no multistep history to discard and can continue with its fixed third-order formula after an event. This may mean that BDF performs poorly in comparison with a one-step method, but this depends on many factors, even with the restart BDF might perform significantly better between events, so it is always worth trying both methods to see which is better.
The
performance-solver-events
example constructs a simple example that highlights the slowdown effect that can affect the BDF solver.
It compares BDF with ESDIRK34 using dense nalgebra vectors and matrices and an LU linear solver:
type M = NalgebraMat<f64>;
type LS = NalgebraLU<f64>;
A Stiff Slow Manifold
The model is a stiff system with a slowly varying solution. We will perturb the system at regular events in such a way as to introduce discontinuities while maintaining a slowly varying solution (previous versions of this problem showed that the BDF solver did better at fast transients after the event, reducing the effect we are trying to demonstrate).
$$ \begin{aligned} y_1' &= -y_1, \\ y_2' &= 999y_1 - 1000y_2, \end{aligned} $$
with \(y(0)=(1,1)^T\). Its eigenvalues are \(-1\) and \(-1000\), giving a stiffness ratio of \(1000\). The vector \((1,1)^T\) is the slow eigenvector.
At the event times
$$ t_k = 0.05k, \qquad k=1,\ldots,100, $$
the example applies the jump
$$ y(t_k^+) = y(t_k^-) + \begin{pmatrix}1\\1\end{pmatrix}. $$
Each jump stays on the slow eigenspace so we don't have any large fast transients. This is done so the benchmark is dominated by the cost of BDF's history restart, rather than the cost of repeatedly resolving the fast transients.
The model definition is:
OdeBuilder::<M>::new()
.rtol(RTOL)
.atol([ATOL, ATOL])
.rhs_implicit(
|y, _p, _t, dy| {
dy[0] = -LAMBDA_SLOW * y[0];
dy[1] = (LAMBDA_FAST - LAMBDA_SLOW) * y[0] - LAMBDA_FAST * y[1];
},
|_y, _p, _t, v, jv| {
jv[0] = -LAMBDA_SLOW * v[0];
jv[1] = (LAMBDA_FAST - LAMBDA_SLOW) * v[0] - LAMBDA_FAST * v[1];
},
)
.init(
|_p, _t, y| {
y[0] = 1.0;
y[1] = 1.0;
},
2,
)
.build()
.unwrap()
Restarting
After every event, the example updates both the state and its derivative. This keeps the solver state consistent before BDF reconstructs its first-order history. The loop stops exactly at each event, applies the jump, and then continues:
let mut solver = problem.esdirk34::<LS>().unwrap();
let started = Instant::now();
for event_index in 1..NUM_EVENTS {
solver
.set_stop_time(EVENT_INTERVAL * event_index as f64)
.unwrap();
while !matches!(solver.step().unwrap(), OdeSolverStopReason::TstopReached) {}
let state = solver.state_mut();
state.y[0] += 1.0;
state.y[1] += 1.0;
state.dy[0] = -LAMBDA_SLOW * state.y[0];
state.dy[1] = (LAMBDA_FAST - LAMBDA_SLOW) * state.y[0] - LAMBDA_FAST * state.y[1];
}
let elapsed = started.elapsed();
let statistics = solver.get_statistics();
#[cfg(test)]
let state = solver.state();
RunResult {
solver: "ESDIRK34",
elapsed,
steps: statistics.number_of_steps,
rejected_steps: statistics.number_of_error_test_failures,
rhs_evals: solver.problem().eqn.statistics().number_of_calls,
#[cfg(test)]
final_state: [state.y[0], state.y[1]],
}
Results
The benchmark warms up both solvers and performs eleven timed runs of each. The example writes its most recent comparison to this table:
| Solver | Median time (ms) | Steps | Rejects | RHS evals |
|---|---|---|---|---|
| BDF | 1.155 | 2512 | 592 | 4490 |
| ESDIRK34 | 0.369 | 559 | 74 | 2732 |
Wall-clock times depend on the machine, but this problem should show ESDIRK34 requiring substantially fewer steps than BDF at tight tolerances. BDF must repeatedly climb from order one after each jump instead of preserving high-order history over the full solve. However, it is not a general rule that one-step methods always beat BDF for event-driven stiff systems: repeatedly exciting a large fast mode can favour BDF instead, as we found for another version of this same problem.
Solving Many ODEs in Parallel
In areas such as model fitting, uncertainty quantification, and population models it is often necessary to solve many ODEs in parallel. Here the goal is to use the parallelism available in your computer to solve many ODEs simultaneously, rather than solving them one after the other. This can be done on both CPUs and GPUs, and the following sections will explore how to achieve this with diffsol
CPU Parallelism
In this section we demonstrate how to use the popular rayon crate to solve many ODEs in parallel on the CPU. The example is a simple population dynamics model: we solve the same ODE with different values of the growth parameter in parallel. To generate the growth parameters, we use rand_chacha::ChaCha12Rng to generate random values according to a log-normal distribution.
First, let's define the types and constants that we use. We use the nalgebra dense matrix type for the linear algebra backend, and define:
- the number of ODEs we want to solve in parallel (
N_SAMPLES), - the number of time points we want to solve for (
N_TIMES), - the final time point we want to solve to (
T_FINAL), - the carrying capacity parameter for the population dynamics model (
K), - an initial value for the population (
Y0), and - the random seed for the random number generator (
SEED).
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
const N_SAMPLES: usize = 1000;
const N_TIMES: usize = 101;
const T_FINAL: f64 = 20.0;
const K: f64 = 10.0;
const Y0: f64 = 0.1;
const SEED: u64 = 42;
Now we define an ensemble function that draws the random growth rates and solves the ensemble of ODEs in parallel. Once the ensemble has been solved, we reduce the results, also in parallel, to the 5%, 50%, and 95% quantiles at each evaluation time. The function returns the quantile bands; the evaluation times are passed in by the caller.
Both the solve and reduce stages run on the Rayon thread pool. A single random number generator cannot be shared across threads, but ChaCha12Rng offers independent streams from one seed, so each sample uses the stream matching its index.
Similarly, the diffsol Problem cannot be shared across threads as it needs to be mutated in order to set the growth rate for each sample. It also uses a RefCell to store operator statistics, so in Rust terms it is Send but not Sync (please raise an issue on the repo if Sync is required for your work). So that the Problem is not shared between worker threads, we use a ThreadLocal from the thread_local crate to give each worker thread its own problem. A thread builds its problem the first time it needs one, then reuses it for all the samples it solves. The problem is wrapped in a RefCell so that the thread can mutate it.
fn ensemble(n_samples: usize, t_eval: &[f64]) -> Vec<[f64; 3]> {
// one problem for each worker thread, built the first time that thread needs it
let problems = ThreadLocal::new();
let solutions: Vec<M> = (0..n_samples)
.into_par_iter()
.map(|i| {
let mut problem = problems
.get_or(|| {
RefCell::new(
OdeBuilder::<M>::new()
.p([1.0, K])
.rhs(|y, p, _t, dy| dy[0] = p[0] * y[0] * (1.0 - y[0] / p[1]))
.init(|_p, _t, y| y[0] = Y0, 1)
.build()
.unwrap(),
)
})
.borrow_mut();
let mut rng = ChaCha12Rng::seed_from_u64(SEED);
rng.set_stream(i as u64);
let r = LogNormal::new(0.5_f64.ln(), 0.3).unwrap().sample(&mut rng);
let p = V::from_vec(vec![r, K], *problem.eqn.context());
problem.eqn_mut().set_params(&p);
let mut solver = problem.tsit45().unwrap();
solver.solve_dense(t_eval).unwrap().0
})
.collect();
(0..t_eval.len())
.into_par_iter()
.map(|i| {
let mut ys: Vec<f64> = solutions.iter().map(|s| s.column(i)[0]).collect();
ys.sort_by(f64::total_cmp);
[quantile(&ys, 0.05), quantile(&ys, 0.5), quantile(&ys, 0.95)]
})
.collect()
}
/// Quantile of an ascending slice, linearly interpolating between order statistics.
fn quantile(sorted: &[f64], q: f64) -> f64 {
let pos = q * (sorted.len() - 1) as f64;
let (lo, hi) = (pos.floor() as usize, pos.ceil() as usize);
sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo as f64)
}
Once we have called ensemble and obtained the results, we can plot the quantiles using Plotly. The following code creates a plot of the 5%, 50%, and 95% quantiles of the population dynamics model, shown below:
/// Plot the median with a shaded 5%-95% band. The band is drawn by filling the 95% trace
/// down to the 5% trace that precedes it.
fn plot_bands(t_eval: &[f64], bands: &[[f64; 3]]) -> Plot {
let t: Vec<f64> = t_eval.to_vec();
let lower: Vec<f64> = bands.iter().map(|b| b[0]).collect();
let median: Vec<f64> = bands.iter().map(|b| b[1]).collect();
let upper: Vec<f64> = bands.iter().map(|b| b[2]).collect();
let mut plot = Plot::new();
plot.add_trace(
Scatter::new(t.clone(), lower)
.mode(Mode::Lines)
.line(Line::new().width(0.0))
.name("5%"),
);
plot.add_trace(
Scatter::new(t.clone(), upper)
.mode(Mode::Lines)
.line(Line::new().width(0.0))
.fill(Fill::ToNextY)
.fill_color("rgba(31, 119, 180, 0.25)")
.name("95%"),
);
plot.add_trace(Scatter::new(t, median).mode(Mode::Lines).name("median"));
plot.set_layout(
Layout::new()
.x_axis(Axis::new().title("t"))
.y_axis(Axis::new().title("y")),
);
plot
}
Thread Scaling
Now we can examine how effective the parallelism is by varying the number of threads used in the rayon thread pool. The following code will run the ensemble with different numbers of threads, and record the time taken for each run. We will repeat each run a few times and then take the median to reduce benchmark noise.
fn thread_scaling(t_eval: &[f64]) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
ensemble(BENCH_SAMPLES, t_eval); // warm up the pool and the allocator
let mut threads = Vec::new();
let mut elapsed = Vec::new();
for n in 1..=rayon::current_num_threads() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(n)
.build()
.unwrap();
// use the median of a few runs to avoid outliers
let mut runs: Vec<f64> = (0..BENCH_REPEATS)
.map(|_| {
let start = Instant::now();
let bands = pool.install(|| ensemble(BENCH_SAMPLES, t_eval));
assert_eq!(bands.len(), t_eval.len());
start.elapsed().as_secs_f64()
})
.collect();
runs.sort_by(f64::total_cmp);
elapsed.push(runs[runs.len() / 2]);
threads.push(n as f64);
}
let speedup = elapsed.iter().map(|t| elapsed[0] / t).collect();
(threads, elapsed, speedup)
}
We use Plotly to plot the results and compare them against a reference line indicating ideal linear scaling.
Ideal speed-up would be linear with the number of threads, but several factors reduce the measured scaling below the ideal line:
- reducing the solutions: This requires
N_TIMESsorts which areO(N log N)each. - memory bandwidth: here we need to allocate, write then read
N_SAMPLESsolution trajectories. - scheduling overhead: Rayon uses a thread pool and schedules work across it, this creates more work at higher thread counts.
- simple ODE: The logistic growth ODE is trivial to solve, so the linear portion is relatively cheap, increasing the weighting of the other factors above.
GPU Parallelism
The model used in this example represents nbuses electrical generators, each tied to all the others through a network of transmission lines. Each generator bus is described by the swing equation, a second-order ODE describing the dynamics of the generator's rotor angle and frequency. The implementation writes this as a system of first-order ODEs.
We introduce uncertainty into the model by adding an uncertain additional demand at bus 0, drawn from a normal distribution. The goal is to solve many instances of the model and obtain the maximum frequency deviation (Hz) for each ensemble member.
We will solve this ensemble of models in parallel on both the GPU and the CPU. The GPU version uses diffsol's batching features with the cuda-oxide backend, and solves all samples in one batched solve. The CPU version uses the nalgebra backend and the rayon crate, and solves one unbatched problem per sample.
The swing equation is a non-linear ODE, and is given by:
$$ \begin{align} \frac{d\delta_i}{dt} &= \omega_i \\ M \frac{d\omega_i}{dt} &= -D\omega_i - B\sum_{j=0}^{n-1} \sin(\delta_i-\delta_j) - d\ \mathbf{1}_{i=0} \end{align} $$
where:
- \(\delta_i\): rotor angle at bus \(i\) in the reference frame, radians
- \(\omega_i\): speed deviation at bus \(i\) from the reference frame, radians per second
- \(B\): pairwise line susceptance (how strongly each transmission line transfers power between two buses)
- \(d\): uncertain additional demand at bus \(0\)
- \(\mathbf{1}_{i=0}\): equals \(1\) at bus \(0\), otherwise \(0\)
First, we write the model using diffsol's OdeEquations trait. We cannot use the easier builder and closures API because it is not supported for GPU models.
We will define the generator inertia M, damping D and per-line susceptance B:
pub const INERTIA: f64 = 4.0;
pub const DAMPING: f64 = 0.6;
pub const SUSCEPTANCE: f64 = 0.25;
Then we define the swing equations over a batched ensemble using a single SwingEqn struct with one demand value per batch lane. We hold the demand values in a vector demand on the struct. The network has nbuses generators, each tied to every other. State i < nbuses is the rotor angle of bus i, and state nbuses + g is the speed deviation of bus g, so each state vector holds 2 * nbuses states.
We define the equations using the for_each_elem method, which is called for each element i of the state vector in each batch lane. Since the rotor angles are in the first half of the state vector and the speed deviations are in the second, we can use the index i to determine which equation to evaluate.
We will not show much of the boilerplate code here, but the full code is available in the examples/performance-gpu-ensemble directory of the diffsol repository.
pub struct SwingEqn<M: Matrix> {
ctx: M::C,
demand: M::V,
nbuses: usize,
inertia: M::T,
damping: M::T,
susceptance: M::T,
}
impl<M: Matrix> SwingEqn<M> {
pub fn new(nbuses: usize, ctx: M::C) -> Self {
assert!(
nbuses >= 3 && nbuses.is_multiple_of(2),
"need an even network of 4+ buses"
);
// one parameter per lane; the builder fills it from `OdeBuilder::p`
let demand = M::V::zeros(1, ctx.clone());
Self {
ctx,
demand,
nbuses,
inertia: M::T::from_f64(INERTIA).unwrap(),
damping: M::T::from_f64(DAMPING).unwrap(),
susceptance: M::T::from_f64(SUSCEPTANCE).unwrap(),
}
}
}
pub struct SwingRhs<'a, M: Matrix> {
eqn: &'a SwingEqn<M>,
}
pub struct SwingInit<'a, M: Matrix> {
eqn: &'a SwingEqn<M>,
}
impl<M: Matrix> NonLinearOp for SwingRhs<'_, M> {
fn call_inplace(&self, x: &M::V, _t: M::T, y: &mut M::V) {
// captured by value so the closure stays `Copy + Send`
// and compiles for the device
let n = self.eqn.nbuses;
let (m, d, b) = (self.eqn.inertia, self.eqn.damping, self.eqn.susceptance);
y.for_each_elem(
[x, &self.eqn.demand],
move |y: &mut M::T, [x, demand]: [&[M::T]; 2], _lane: usize, i: usize| {
if i < n {
// rotor angle: d(delta)/dt = omega
*y = x[n + i];
} else {
let g = i - n;
// every bus is tied to every other, as a dense admittance matrix.
let mut flow = M::T::zero();
for j in 0..n {
flow += (x[g] - x[j]).sin();
}
let flow = b * flow;
// the uncertain load at bus 0 drives the system
let inj = if g == 0 { -demand[0] } else { M::T::zero() };
*y = (inj - d * x[n + g] - flow) / m;
}
},
);
}
}
impl<M: Matrix> ConstantOp for SwingInit<'_, M> {
fn call_inplace(&self, _t: M::T, y: &mut M::V) {
// the nominal grid is balanced, so it starts at rest
y.for_each_elem(
[],
|y: &mut M::T, _: [&[M::T]; 0], _lane: usize, _i: usize| *y = M::T::zero(),
);
}
}
Once we have defined our equations, we can create an OdeSolverProblem using the builder. To set up the batches on the GPU, we create a vector of N_SAMPLES demand values drawn from a normal distribution with DEMAND_MEAN = 0.3 and DEMAND_SD = 0.08, then pass them to the builder through the demands argument.
/// One problem holding `demands.len()` independent grids, one per batch lane.
#[allow(clippy::type_complexity)]
pub fn swing_problem<M: Matrix + 'static>(
nbuses: usize,
demands: &[f64],
rtol: f64,
atol: f64,
) -> OdeSolverProblem<impl OdeEquations<M = M, V = M::V, T = M::T, C = M::C>> {
let ctx = M::C::default().clone_with_nbatch(demands.len()).unwrap();
OdeBuilder::<M>::new()
.context(ctx.clone())
// one value per lane, so the parameter vector is `nparams * nbatch` long
.p(demands.iter().copied())
.rtol(rtol)
.atol([atol])
.build_from_eqn(SwingEqn::new(nbuses, ctx))
.unwrap()
}
We can then solve the ensemble of ODEs on the GPU using the standard diffsol solve API. Under the hood, diffsol solves nbatch ODEs in lockstep on the GPU using the cuda-oxide backend.
/// Every grid in one batched solve, in precision `T`.
fn solve_gpu<T: ScalarCuda>(
nbuses: usize,
demands: &[f64],
t_final: f64,
rtol: f64,
atol: f64,
) -> Vec<f64> {
use diffsol::OxideMat;
let problem = swing_problem::<OxideMat<T>>(nbuses, demands, rtol, atol);
let mut solver = problem.tsit45().unwrap();
max_deviation_hz(&mut solver, nbuses, t_final)
}
We want to display the distribution of the maximum frequency deviation across the ensemble of ODEs, so we use the lower-level step API to advance the equations in time. At each time step, reduce_elem computes one maximum speed deviation per batch lane, avoiding the need to hold the entire trajectory in memory. At the end, we convert each value from radians per second to a frequency deviation in Hz.
/// Worst speed deviation of any generator over the whole run, one value per grid.
fn max_deviation_hz<'a, Solver, Eqn>(solver: &mut Solver, nbuses: usize, t_final: f64) -> Vec<f64>
where
Solver: OdeSolverMethod<'a, Eqn>,
Eqn: OdeEquations + 'a,
{
let ctx = solver.problem().context().clone();
let mut worst = Eqn::V::zeros(1, ctx.clone());
let mut next = Eqn::V::zeros(1, ctx);
// find the maximum speed deviation (rad/s) across all generators
fn fold<V: Vector>(y: &V, worst: &mut V, next: &mut V, nbuses: usize) {
V::reduce_elem(
next,
[y, worst],
V::T::zero(),
move |[x, w], _lane, i| {
if i >= nbuses {
x[i].abs().max(w[0])
} else {
w[0]
}
},
|a: V::T, b: V::T| a.max(b),
);
std::mem::swap(worst, next);
}
solver
.set_stop_time(Eqn::T::from_f64(t_final).unwrap())
.unwrap();
loop {
fold(solver.state().y, &mut worst, &mut next, nbuses);
match solver.step() {
Ok(OdeSolverStopReason::TstopReached) => break,
Ok(_) => (),
Err(e) => panic!("solver failed: {e}"),
}
}
fold(solver.state().y, &mut worst, &mut next, nbuses);
worst
.clone_as_vec()
.into_iter()
// rad/s in the rotating frame, so Hz is omega / 2*pi
.map(|w| w.to_f64().unwrap() / (2.0 * PI))
.collect()
}
We can then plot the histogram of the maximum frequency deviation (Hz) across the ensemble, which is shown below:
GPU versus CPU
It is useful to compare the GPU batch solves against a CPU parallel implementation using the rayon crate. The CPU version uses a ThreadLocal to give each worker thread its own SwingEqn problem, then solves one ODE per sample in parallel using the thread pool. Each thread builds its problem once and reuses it for all of its samples.
/// One solve per grid, spread over rayon's threads.
fn solve_cpu<T: NalgebraScalar>(
nbuses: usize,
demands: &[f64],
t_final: f64,
rtol: f64,
atol: f64,
) -> Vec<f64> {
// one problem for each worker thread, built the first time that thread needs it
let problems = ThreadLocal::new();
demands
.par_iter()
.map(|&d| {
let mut problem = problems
.get_or(|| {
RefCell::new(swing_problem::<NalgebraMat<T>>(nbuses, &[0.0], rtol, atol))
})
.borrow_mut();
let d = T::from_f64(d).unwrap();
let p = NalgebraVec::from_vec(vec![d], *problem.eqn.context());
problem.eqn_mut().set_params(&p);
let mut solver = problem.tsit45().unwrap();
max_deviation_hz(&mut solver, nbuses, t_final)[0]
})
.collect()
}
To show the relative performance, we loop over different ensemble sizes and, for each size, time the GPU and CPU solves. We take the median of 15 runs to reduce noise. The plot below shows the results for both double precision (f64) and single precision (f32).
Double precision
Below an ensemble size of 100, fixed costs such as kernel launches, allocation, and setup dominate, so GPU execution time is approximately flat for this workload. Between 100 and 500 samples, computation becomes a larger part of the runtime. At 1000 samples, the timing is approximately linear. In this case, the GPU appears to reach its throughput limit before all of its theoretical resident threads are occupied, GPU profiling would be required to confirm the limiting factor here. CPU scaling becomes linear at smaller ensemble sizes because the CPU has fewer workers available for parallel work. Once both CPU and GPU are in the linear regime, the GPU is about twice as fast as the CPU. The A40's relatively low FP64 peak rate, approximately 1/64 of its FP32 rate, is one factor that limits its advantage, others include memory access, kernel structure, and launch overhead.
Single precision
Here we run the solves with looser tolerances that can be resolved using f32 (rtol = 1e-4 and atol = 1e-6 for f32 versus rtol = 1e-6 and atol = 1e-8 for f64), so the solver takes fewer steps and is faster than the f64 results for both CPU and GPU. Below an ensemble size of 50 the relative performance of both hardware is similar, but above this value the CPUs are saturated and the scaling moves into the linear regime. The GPU is able to maintain its flat profile at significantly higher ensemble sizes than with f64, and so when it transitions to the linear regime it is almost an order of magnitude faster than the CPU solves, reflecting the A40's much higher FP32 throughput.
Parallel-in-Time (DEER)
Here we will illustrate the application of diffsol to a parallel-in-time method for solving a nonlinear ODE. The method is based on the DEER algorithm introduced in Lim et al.. DEER linearises the ODE at each time step of the discretised solution, but the DEER-style method in this example applies Newton's method only to the states at the boundaries of time chunks (multiple shooting), and uses an ODE solver with forward sensitivities in each chunk. In both methods, a parallel scan solves the resulting linear recurrence. The example will use the forced Duffing oscillator, a nonlinear second order ODE, and solve it in parallel across multiple time chunks using CPU threads and the rayon crate.
First we will define a few types, we will use the nalgebra backend and matrix/vector types, and a f64 scalar type.
type M = NalgebraMat<f64>;
type V = <M as MatrixCommon>::V;
type T = <M as MatrixCommon>::T;
type C = <M as MatrixCommon>::C;
The problem
The example used is the forced Duffing oscillator, a nonlinear second order ODE given by the equation
\[ \ddot{x} + \delta \dot{x} + x + x^3 = \gamma \cos(\omega t), \]
which, writing \(\mathbf{y} = (x, v)^T\) with \(v = \dot{x}\), is the first order system
\[ \begin{aligned} \frac{dx}{dt} &= v, \\ \frac{dv}{dt} &= -\delta v - x - x^3 + \gamma \cos(\omega t), \end{aligned} \]
or \(\dot{\mathbf{y}} = \mathbf{f}(\mathbf{y}, t)\), with \(\delta = 0.5\), \(\gamma = 0.5\), \(\omega = 1\) and \(\mathbf{y}(0) = (1, 0)^T\). The Jacobian of the right-hand side is
\[ \frac{\partial \mathbf{f}}{\partial \mathbf{y}} = \begin{pmatrix} 0 & 1 \\ -1 - 3x^2 & -\delta \end{pmatrix}. \]
The parameters are the initial state, \(\mathbf{p} = \mathbf{y}(t_0)\), so the right-hand side does not depend on them and the initial condition is the identity map:
\[ \frac{\partial \mathbf{f}}{\partial \mathbf{p}} = \begin{pmatrix} 0 & 0 \\ 0 & 0 \end{pmatrix}, \quad \frac{\partial \mathbf{y}(t_0)}{\partial \mathbf{p}} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}. \]
const DELTA: f64 = 0.5;
const GAMMA: f64 = 0.5;
const OMEGA: f64 = 1.0;
const Y0: [f64; 2] = [1.0, 0.0];
fn problem(
rtol: f64,
atol: f64,
) -> OdeSolverProblem<impl OdeEquationsImplicitSens<M = M, V = V, T = T, C = C>> {
OdeBuilder::<M>::new()
.rtol(rtol)
.atol([atol])
.p(Y0)
.rhs_sens_implicit(
|y, _p, t, dy| {
dy[0] = y[1];
dy[1] = -DELTA * y[1] - y[0] - y[0] * y[0] * y[0] + GAMMA * (OMEGA * t).cos();
},
|y, _p, _t, v, jv| {
jv[0] = v[1];
jv[1] = -(1.0 + 3.0 * y[0] * y[0]) * v[0] - DELTA * v[1];
},
|_y, _p, _t, _v, jv| jv.fill(0.0),
)
.init_sens(
|p, _t, y| y.copy_from_slice(p),
|_p, _t, v, y| y.copy_from_slice(v),
2,
)
.build()
.unwrap()
}
The DEER iteration
The time interval \([0, T]\) is split into \(N\) chunks, and each chunk is integrated independently, in parallel, from a guess of the state at its start time:
The states at the chunk boundaries \(\mathbf{y}_k \approx \mathbf{y}(t_k)\) satisfy the nonlinear recurrence
\[ \mathbf{y}_{k+1} = \boldsymbol{\phi}_k(\mathbf{y}_k), \quad k = 0, \dots, N - 1, \quad \mathbf{y}_0 = \mathbf{y}(0). \]
Linearising about the current iterate \(\mathbf{y}_k^{(i)}\) gives Newton's method for all boundary states at once,
\[ \mathbf{y}_{k+1}^{(i+1)} = \boldsymbol{\phi}_k(\mathbf{y}_k^{(i)}) + J_k \left( \mathbf{y}_k^{(i+1)} - \mathbf{y}_k^{(i)} \right), \quad J_k = \frac{\partial \boldsymbol{\phi}_k}{\partial \mathbf{y}} \left( \mathbf{y}_k^{(i)} \right), \]
which is a linear (affine) recurrence
\[ \mathbf{y}_{k+1}^{(i+1)} = J_k \mathbf{y}_k^{(i+1)} + \mathbf{b}_k, \quad \mathbf{b}_k = \boldsymbol{\phi}_k(\mathbf{y}_k^{(i)}) - J_k \mathbf{y}_k^{(i)}. \]
Each step of the recurrence is an affine map \(\mathbf{y} \mapsto A \mathbf{y} + \mathbf{b}\), fully described by the pair \((A, \mathbf{b})\). Applying step 0 and then step 1 gives
\[ \mathbf{y}_2 = J_1 (J_0 \mathbf{y}_0 + \mathbf{b}_0) + \mathbf{b}_1 = (J_1 J_0) \mathbf{y}_0 + (J_1 \mathbf{b}_0 + \mathbf{b}_1), \]
which is again an affine map. Writing this composition as an operator on pairs (read right to left, so the right-hand map is applied first),
\[ (A_2, \mathbf{b}_2) \bullet (A_1, \mathbf{b}_1) = (A_2 A_1, A_2 \mathbf{b}_1 + \mathbf{b}_2). \]
Like any composition of functions, this operator is associative, \((f \bullet g) \bullet h = f \bullet (g \bullet h)\), and it has the identity \((I, \mathbf{0})\), the map that leaves \(\mathbf{y}\) unchanged. Associativity means the steps can be grouped in any order, so different threads can combine different groups of steps at the same time. The prefix \((P_k, \mathbf{c}_k)\) is the single affine map equal to applying steps \(0, 1, \dots, k\) in order,
\[ (P_k, \mathbf{c}_k) = (J_k, \mathbf{b}_k) \bullet (J_{k-1}, \mathbf{b}_{k-1}) \bullet \dots \bullet (J_0, \mathbf{b}_0), \]
which takes \(\mathbf{y}_0\) straight to \(\mathbf{y}_{k+1}\). A sequential loop would build each prefix from the previous one, but a parallel scan computes all \(N\) prefixes in \(O(\log N)\) rounds of combining (given enough threads). Each new boundary state then depends only on \(\mathbf{y}_0\), so they can all be evaluated in parallel:
\[ \mathbf{y}_{k+1}^{(i+1)} = P_k \mathbf{y}_0 + \mathbf{c}_k. \]
The iteration stops when
\[ \max_k \left\Vert \mathbf{y}_k^{(i+1)} - \mathbf{y}_k^{(i)} \right\Vert_\infty < \text{tol}. \]
const RTOL: f64 = 1e-10;
const ATOL: f64 = 1e-12;
const JAC_TOL: f64 = 1e-4;
const MAX_ITERS: usize = 50;
const NEWTON_TOL: f64 = 1e-6;
fn deer() -> Vec<Vec<Vector2<f64>>> {
let y0 = Vector2::from(Y0);
let mut x = coarse();
let mut iterates = vec![x.clone()];
for _ in 0..MAX_ITERS {
let maps: Vec<(Matrix2<f64>, Vector2<f64>)> = x[..N_CHUNKS]
.par_iter()
.enumerate()
.map_init(
|| (problem(RTOL, ATOL), problem(JAC_TOL, JAC_TOL)),
|problems, (k, x_k)| {
let (f_k, j_k) = propagate(problems, k, x_k);
(j_k, f_k - j_k * x_k)
},
)
.collect();
let prefixes: Vec<(Matrix2<f64>, Vector2<f64>)> = maps
.into_par_iter()
.scan(
|(a1, b1), (a2, b2)| (a2 * a1, a2 * b1 + b2),
(Matrix2::identity(), Vector2::zeros()),
)
.collect();
let mut x_new = vec![y0];
x_new.par_extend(prefixes.par_iter().map(|(a, b)| a * y0 + b));
let delta = max_error(&x, &x_new);
x = x_new;
iterates.push(x.clone());
if delta < NEWTON_TOL {
break;
}
}
iterates
}
Solving a single chunk
Let \(\boldsymbol{\phi}_k(\mathbf{y})\) be the flow map of chunk \(k\), the solution at \(t_{k+1}\) of
\[ \dot{\mathbf{y}} = \mathbf{f}(\mathbf{y}, t), \quad \mathbf{y}(t_k) = \mathbf{y}. \]
Its Jacobian \(J_k = \partial \boldsymbol{\phi}_k / \partial \mathbf{y}\) is given by the forward sensitivities \(S(t) = \partial \mathbf{y}(t) / \partial \mathbf{y}(t_k)\), which satisfy
\[ \dot{S} = \frac{\partial \mathbf{f}}{\partial \mathbf{y}} S, \quad S(t_k) = I, \quad J_k = S(t_{k+1}). \]
Newton's method still converges to the solution of the nonlinear recurrence if the \(J_k\) are only approximate, so we can use a much cheaper solve with loose tolerances and forward sensitivities to compute \(J_k\).
const T_FINAL: f64 = 3000.0;
const N_CHUNKS: usize = 96;
const DT_CHUNK: f64 = T_FINAL / N_CHUNKS as f64;
fn propagate(
problems: &mut (
OdeSolverProblem<impl OdeEquationsImplicitSens<M = M, V = V, T = T, C = C>>,
OdeSolverProblem<impl OdeEquationsImplicitSens<M = M, V = V, T = T, C = C>>,
),
k: usize,
y_start: &Vector2<f64>,
) -> (Vector2<f64>, Matrix2<f64>) {
let (accurate, loose) = problems;
let (t0, t1) = (k as f64 * DT_CHUNK, (k + 1) as f64 * DT_CHUNK);
let p = V::from_vec(vec![y_start[0], y_start[1]], *accurate.eqn.context());
accurate.eqn_mut().set_params(&p);
accurate.t0 = t0;
let mut solver = accurate.tsit45().unwrap();
solver.set_stop_time(t1).unwrap();
while !matches!(solver.step().unwrap(), OdeSolverStopReason::TstopReached) {}
let y = Vector2::from_fn(|i, _| solver.state().y.get_index(i));
loose.eqn_mut().set_params(&p);
loose.t0 = t0;
let mut solver = loose.tsit45_sens().unwrap();
solver.set_stop_time(t1).unwrap();
while !matches!(solver.step().unwrap(), OdeSolverStopReason::TstopReached) {}
let s = solver.state().s;
let jac = Matrix2::from_fn(|i, j| s.get_batch(j).get_index(i));
(y, jac)
}
Initial guess
The initial guess \(\mathbf{y}_k^{(0)}\), \(k = 0, \dots, N\) also only needs to be approximate, so we use a cheap sequential solve of \(\dot{\mathbf{y}} = \mathbf{f}(\mathbf{y}, t)\) with loose tolerances, evaluated at the chunk boundaries \(t_k\).
const COARSE_TOL: f64 = 1e-3;
fn coarse() -> Vec<Vector2<f64>> {
let t: Vec<f64> = (0..=N_CHUNKS).map(|k| k as f64 * DT_CHUNK).collect();
let (ys, _) = problem(COARSE_TOL, COARSE_TOL)
.tsit45()
.unwrap()
.solve_dense(&t)
.unwrap();
(0..t.len())
.map(|k| Vector2::new(ys.column(k)[0], ys.column(k)[1]))
.collect()
}
Convergence
With a reasonable initial guess the Newton iteration converges in a few iterations, and the final solution is accurate to the tolerance of the chunk solves.
Thread Scaling
We do not expect perfect linear scaling with the number of threads, since:
- the parallel scan requires \(O(\log N)\) rounds of combining
- the initial coarse solve is serial
- each chunk solve is an adaptive solve, so slower solves will hold up the faster ones
The plot below shows the speedup compared to a sequential solve, and compared to the same method on 1 thread. With a total of 96 chunks, the maximum speedup compared to the sequential solve is approximately 5.2x with 30 threads (and approximately 4.8x with 24 threads). On 1 thread, the method is approximately 2.5 times slower than the sequential solve, because it solves every chunk at each Newton iteration and also computes the sensitivities. Some possible improvements that we could make to this example are:
- We are not getting much advantage out of the parallel scan, since it's only 96 compositions of 2x2 matrices. A more expensive composition (more states or more chunks) could help here.
- The coarse solve is serial, so it limits the speedup. We could try an even looser tolerance. Or, if the solve was more expensive (see first point), we could remove the coarse solve and rely on more Newton iterations.
- We solve every chunk at each newton iteration, but the chunks that have already converged could be skipped in later iterations (e.g. the first chunk is always exact)
- Each chunk solve creates a new solver, but we could reuse the solvers between iterations and reset them to the new initial condition, which would save some setup time.
- Could reuse the first iteration's jacobians, since these only need to be approximate.
Using diffsol from other languages
diffsol is a Rust library, but it can be used from other languages through various means. Three aspects that enable the portability of diffsol are:
- The
diffsol-ccrate: A companion crate providing a dynamic dispatch API and a C FFI that allows diffsol to be called from C, Python (viacffi/ctypes), and other languages with C bindings. Runtime configuration enums let you choose the solver method, matrix backend, scalar type, and linear solver without compile-time generic types. - The DiffSL DSL: The DiffSL Domain Specific Language (DSL) allows users to specify ODEs, DAEs, and discretised PDEs in a way that is independent of the Rust language, but still can be JIT compiled to efficient native code.
- WebAssembly: As with many Rust libraries, diffsol can be easily compiled to WebAssembly (Wasm), allowing it to be used in web applications or other environments that support Wasm.
Note that the DiffSL JIT compiler cannot run inside WebAssembly, due to the complexity of compiling LLVM or Cranelift to Wasm. You can still use DiffSL from a Wasm application if a server does the JIT compilation, see WebAssembly with JIT.
Python
There is now a dedicated Python package for diffsol called
pydiffsol. It wraps the
diffsol-c dynamic dispatch API (described in the dynamic dispatch
API page) in a clean, Pythonic interface — no Rust knowledge
required. You can install it with:
pip install pydiffsol
For usage and API documentation, see the pydiffsol docs.
The dynamic dispatch API
The diffsol-c crate has two APIs that let you use
diffsol from other languages:
- The dynamic dispatch API, which this page describes. It is a Rust API. It wraps the core
diffsolsolver in types that select their implementation at runtime. Thus you can select the matrix backend, the scalar type, the linear solver, the ODE solver method and the JIT backend at runtime, not at compile time. - The C API. It gives the dynamic dispatch API as
extern "C"functions, so that C code, or a language that can call C, can use it. See The C API.
Key types
The central type is
OdeWrapper. It keeps
the solver state in an Arc<Mutex<...>>, so that threads and FFI code can share it safely. Its
methods create, configure, solve and serialize the solver.
You configure the solver with these runtime enum types:
- OdeSolverType: the ODE integration method.
- MatrixType: the linear algebra backend.
- ScalarType: the floating-point precision of the solver.
- LinearSolverType: the linear solver of the implicit methods.
- JitBackendType: the JIT compilation backend for DiffSL code.
A solve returns a
SolutionWrapper.
From it, you can get the time points, the state values and the sensitivities as
Tensor
objects. A Tensor shares the data of the solution, with no copy, and keeps the solution alive,
so it stays valid after the SolutionWrapper is dropped.
The inputs of the solve methods, for example the parameters and the times t_eval, are
TensorView objects.
A TensorView borrows the data of the caller, with no copy. It is small and only on the stack,
and it has at most 3 axes. Make one from a slice with TensorView::from_slice, or from a
Tensor with Tensor::view.
The values on the first axis of a tensor or a view are always adjacent (column-major, or Fortran,
order), so each column [:, j, k] is one slice: column and columns give these slices with no
copy. A view of a row-major array is not possible: make a column-major copy first, for example
with numpy.asfortranarray.
The arrays use the column-major order of diffsol, and the last axis of an array of lanes is the
lane. For example, the parameters are an nparams x nlanes
array, and the state values of a solution are an nout x nt x nbatch array.
You can give the equations as DiffSL code (OdeWrapper::new_jit, new_external and
new_external_dynamic), or as C callbacks (OdeWrapper::new_callbacks, see
The C API).
Example: the logistic equation
This example uses the dynamic dispatch API to solve the logistic ODE
\(dy/dt = r \cdot y \cdot (1 - y)\) from Rust. All of the solver configuration occurs at
runtime, with the OdeWrapper API.
The DiffSL code of the logistic equation:
let code = r#"
in_i { r = 2.0 }
u_i { y = 0.1 }
dudt_i { dydt = 0 }
F_i { (r * y) * (1 - y) }
out_i { y }
"#;
Create the OdeWrapper with the Cranelift JIT backend, f64 precision and the BDF solver:
let ode = OdeWrapper::new_jit(
code,
JitBackendType::Cranelift,
ScalarType::F64,
MatrixType::NalgebraDense,
LinearSolverType::Default,
OdeSolverType::Bdf,
)
.unwrap();
Set the solver tolerances:
ode.set_rtol(1e-6).unwrap();
ode.set_atol(1e-8).unwrap();
Solve on a fixed time grid:
let times = vec![0.0, 0.25, 0.5, 0.75, 1.0];
// the inputs are views of Rust slices, with no copy
// params is a `[nparams, nlanes]` array: here one lane with one parameter
let params = TensorView::from_slice(&[2.0], &[1, 1]);
// t_eval is a `[nt]` array
let t_eval = TensorView::from_slice(×, &[times.len()]);
let solution = ode.solve_dense(params, t_eval).unwrap();
Get the solution data from the SolutionWrapper:
// ys is a `[nout, nt, nbatch]` array; ts is a `[nt]` array that all lanes share.
let ys = solution.get_ys().unwrap();
let ts = solution.get_ts().unwrap();
The full example is in examples/diffsol-c-logistic.
The C API
The diffsol-c crate wraps the
dynamic dispatch API as extern "C" functions so that they can be called from C code.
A language that can call C functions (for example with ctypes, cffi or a foreign
function interface) can also be used.
Install the Debian packages
On Debian 12 (bookworm) and 13 (trixie), and on Ubuntu 22.04 (jammy) and 24.04 (noble), for amd64 and arm64, you can install the library with apt. You do not need Rust. There are two packages:
libdiffsol<soversion>, for examplelibdiffsol0.9for diffsol-c 0.9.x: the shared librarylibdiffsol.so. Before version 1.0, the soversion is the major and minor version of diffsol-c. The library has the Cranelift and LLVM JIT backends, and it can load DiffSL code that was compiled before. It uses the LLVM library of the distribution:libllvm19on Debian 12, Debian 13 and Ubuntu 24.04, andlibllvm15on Ubuntu 22.04. apt installs it as a dependency.libdiffsol-dev: the headerdiffsol.h, the pkg-config filediffsol.pc, and the link to the shared library. Install this package to compile programs.
Add the APT repository of diffsol, then install the development package:
curl -1sLf 'https://dl.cloudsmith.io/public/martinjrobins/diffsol/setup.deb.sh' | sudo -E bash
sudo apt install libdiffsol-dev
You can also get the packages from the assets of the diffsol-c
GitHub release. There are packages for each
distribution: the codename of the distribution is part of the package version, for example
libdiffsol0.9_0.9.0-1~noble_amd64.deb. Install the two packages of your distribution and
architecture, for example on Ubuntu 24.04:
sudo apt install ./libdiffsol0.9_*~noble_amd64.deb ./libdiffsol-dev_*~noble_amd64.deb
Then compile and link a program with pkg-config:
cc main.c $(pkg-config --cflags --libs diffsol) -lm -o main
The packages install the library as libdiffsol.so, so a program links with -ldiffsol. A
library that you build with Cargo has the name libdiffsol_c.so (see below), so a program links
with -ldiffsol_c. The header and the functions are the same.
Build the library
Build the crate with Cargo. By default the ODE equations can be supplied as C callbacks. You can also supply the equations using DiffSL via the additional features:
diffsl-cranelift: compile DiffSL code at runtime with the Cranelift JIT backend.diffsl-llvm15todiffsl-llvm21: compile DiffSL code at runtime with LLVM. LLVM of that version must be on the build machine. These features link LLVM statically.diffsl-llvm15-prefer-dynamictodiffsl-llvm21-prefer-dynamic: the same, but link the shared LLVM library (libLLVM) if it is available. Use these to depend on the LLVM package of a Linux distribution. The library is then much smaller, but the LLVM library must be installed where the program runs.diffsl-external-dynamic(default): load DiffSL code that was compiled before, from a dynamic library.suitesparse: add the KLU sparse linear solver.
cargo build -p diffsol-c --release --features diffsl-cranelift
The build makes these files in target/release:
| File | Description |
|---|---|
include/diffsol.h | The C header. |
libdiffsol_c.so (Linux), libdiffsol_c.dylib (macOS) | The dynamic library. |
diffsol_c.dll and diffsol_c.dll.lib (Windows) | The dynamic library and its import library. |
The build script makes the header with cbindgen. The
header agrees with the features of the build. It defines a macro for each enabled feature, for
example DIFFSOL_DIFFSL_CRANELIFT. The functions of a feature are only in the header when the
macro of that feature is defined. Thus C code can use #ifdef to find which features the
library has.
Compile and link a C program
Link with the dynamic library. On Linux and macOS:
cc main.c -I target/release/include -L target/release -ldiffsol_c -lm \
-Wl,-rpath,$PWD/target/release -o main
The -rpath option tells the program where to find the library at runtime. You can also put
the library in a directory that the system searches, or use LD_LIBRARY_PATH (Linux) or
DYLD_LIBRARY_PATH (macOS).
On Windows, with MSVC:
cl main.c /I target\release\include target\release\diffsol_c.dll.lib
At runtime, diffsol_c.dll must be in the same directory as the program, or in a directory in
PATH.
Static library
A static library is made only on request. This command makes it, and lists the system libraries that a program must also link with:
cargo rustc -p diffsol-c --release --lib --features diffsl-cranelift --crate-type staticlib \
-- --print native-static-libs
The static library is target/release/libdiffsol_c.a (diffsol_c.lib on Windows). Link it,
and the system libraries that the command lists. For example, on macOS:
cc main.c -I target/release/include target/release/libdiffsol_c.a -lc++ -liconv -lm -o main
How to use the API
All C API functions use the same rules:
- A function that can fail returns an
int32_tstatus:DIFFSOL_OK(0) on success, or a negative value (DIFFSOL_ERR,DIFFSOL_BAD_ARG) on failure. A constructor returnsNULLon failure. - After a failure,
diffsol_last_error_message()gives a description of the error. The error is kept for each thread. - The library owns each object that it returns, for example an
OdeWrapper, aSolutionWrapperor aTensor. Free each object with its free function, for examplediffsol_ode_free. - The enum values are
int32_tconstants in the header, for exampleDIFFSOL_MATRIX_TYPE_NALGEBRA_DENSE,DIFFSOL_LINEAR_SOLVER_TYPE_DEFAULT,DIFFSOL_ODE_SOLVER_TYPE_BDFandDIFFSOL_JIT_BACKEND_TYPE_CRANELIFT. - A solution array (
Tensor) gives a pointer to its data, its dimensions and its strides. The strides are in bytes. ATensorshares the data of the solution, with no copy, and stays valid after you free theSolutionWrapper. - The arrays use the column-major order of diffsol: the first axis changes fastest.
- An ODE has
nbatchlanes. The last axis of an array of lanes is always the lane, also whennbatchis 1. A state or a parameter vector is ann x nbatcharray. The solution valuesysare annout x nt x nbatcharray. The timestsare anntarray, because all the lanes use the same times. - A function that takes lanes of values (for example
params) takes a pointer, the number of values in each lane and the number of lanes. The values are a column-majorlen x lanesarray: laneb, valuekis at indexb * len + k. The number of lanes is thenbatchof the ODE, or 1. One lane is used for all the lanes of the ODE.
The functions are in these modules of the crate documentation:
- ode_c: configure, solve and
free
OdeWrapperhandles. - ode_callbacks_c:
create an
OdeWrapperfrom equations that C callbacks give. - ode_diffsl_c: create an
OdeWrapperfrom DiffSL code (JIT) or from DiffSL code that was compiled before. - solution_wrapper_c:
get the solution data, and free
SolutionWrapperhandles. - ode_options_c and initial_condition_options_c: get and set the solver options.
- matrix_type_c, scalar_type_c, linear_solver_type_c, ode_solver_type_c and jit_c: the enum values, their names, and their checks.
- tensor_c: read and
free
Tensordata. - error_c: get and clear the error of the thread.
- string_c: allocate and free strings that Rust owns.
Example: equations from C callbacks
The example logistic_callbacks.c solves the logistic equation \(dy/dt = r \cdot y \cdot (1 - y)\), with equations that C functions give. It does not need DiffSL.
The library calls each callback one time for all the lanes of the ODE. Each callback gets its
inputs as const TensorView * views, writes its output through a TensorViewMut * view y,
and returns 0 on success. Its last argument is the user_data pointer of the descriptor.
Each view has the fields ptr, dtype, ndim, shape and strides (in bytes), and the shape
[n, P, B]. Element i of lane (k, b) is at ptr + i * strides[0] + k * strides[1] + b * strides[2]. B is the number of lanes of the ODE (nbatch). P is 1, except in
sensitivity and adjoint solves, where the solver can calculate more than one product for each
lane in one call. An input that has the same values for all k (or all lanes) has a stride of
0 on that axis, so a callback that uses the strides does not need to know which inputs are
broadcast. The views show the data of the solver with no copy.
The
ode_callbacks module
gives the value of n for each argument of each callback, the sign conventions of the adjoint
callbacks, and the ownership rules of user_data.
/* The library calls each callback one time for all the lanes. Each vector is a view with the
* shape [n, P, B]: element i of lane (k, b) is at ptr + i * strides[0] + k * strides[1]
* + b * strides[2], in bytes. B is the number of lanes of the ODE (nbatch). P is 1, except in
* sensitivity and adjoint solves. A stride can be 0: then the lanes on that axis share their
* values. These two functions give the address of a value. */
static const double *at(const TensorView *v, size_t i, size_t k, size_t b) {
return (const double *)(v->ptr + i * v->strides[0] + k * v->strides[1] + b * v->strides[2]);
}
static double *at_mut(TensorViewMut *v, size_t i, size_t k, size_t b) {
return (double *)(v->ptr + i * v->strides[0] + k * v->strides[1] + b * v->strides[2]);
}
/* rhs: y = r x (1 - x). x and y have nstates values in each lane, p has nparams values. */
static int32_t rhs(const TensorView *x, const TensorView *p, double t, TensorViewMut *y,
void *user_data) {
(void)t;
((UserData *)user_data)->rhs_calls += 1;
for (size_t b = 0; b < y->shape[2]; b++) {
for (size_t k = 0; k < y->shape[1]; k++) {
double xi = *at(x, 0, k, b);
*at_mut(y, 0, k, b) = *at(p, 0, k, b) * xi * (1.0 - xi);
}
}
return 0; /* 0 is success; a different value tells the solver that the callback failed */
}
/* rhs_jac: y = J v, with J = dF/dx = r (1 - 2 x). The implicit solvers (for example BDF) need it. */
static int32_t rhs_jac(const TensorView *x, const TensorView *p, double t, const TensorView *v,
TensorViewMut *y, void *user_data) {
(void)t;
(void)user_data;
for (size_t b = 0; b < y->shape[2]; b++) {
for (size_t k = 0; k < y->shape[1]; k++) {
*at_mut(y, 0, k, b) = *at(p, 0, k, b) * (1.0 - 2.0 * *at(x, 0, k, b)) * *at(v, 0, k, b);
}
}
return 0;
}
/* init: the initial state y0(p, t). */
static int32_t init(const TensorView *p, double t, TensorViewMut *y, void *user_data) {
(void)p;
(void)t;
(void)user_data;
for (size_t b = 0; b < y->shape[2]; b++) {
for (size_t k = 0; k < y->shape[1]; k++) {
*at_mut(y, 0, k, b) = 0.1;
}
}
return 0;
}
Put the callbacks in a DiffsolOdeCallbacksF64 descriptor, and create the solver. Only rhs
and init are necessary for an explicit solver like Tsit45. A NULL callback is not given. If a solve needs a callback that is
not given, the solve returns an error that gives the name of the callback. For example, the
implicit methods (such as BDF) need rhs_jac.
/* Set all fields to zero first: a NULL callback means that it is not given. */
DiffsolOdeCallbacksF64 callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.nstates = 1;
callbacks.nparams = 1;
callbacks.user_data = &data; /* data stays valid until the solver is freed */
callbacks.free_user_data = NULL; /* the program owns data, so the library does not free it */
callbacks.rhs = rhs;
callbacks.rhs_jac = rhs_jac;
callbacks.init = init;
/* The last argument is nbatch, the number of lanes (copies of the system) to solve. */
OdeWrapper *ode = diffsol_ode_new_callbacks_f64(&callbacks, DIFFSOL_MATRIX_TYPE_NALGEBRA_DENSE,
DIFFSOL_LINEAR_SOLVER_TYPE_DEFAULT,
DIFFSOL_ODE_SOLVER_TYPE_BDF, 1);
if (ode == NULL) {
return fail("diffsol_ode_new_callbacks_f64");
}
Solve, and read the solution:
const double params[] = {2.0}; /* r */
const double t_eval[] = {0.0, 0.5, 1.0, 2.0, 4.0};
const size_t n_eval = sizeof(t_eval) / sizeof(t_eval[0]);
/* params has 1 lane of 1 value. All the lanes of the ODE use a single lane of params. */
SolutionWrapper *solution = NULL;
if (diffsol_ode_solve_dense(ode, params, 1, 1, t_eval, n_eval, &solution) != DIFFSOL_OK) {
diffsol_ode_free(ode);
return fail("diffsol_ode_solve_dense");
}
/* ys is an (nout x n_eval x nbatch) array. Read it with its strides, which are in bytes. */
Tensor *ys = NULL;
if (diffsol_solution_wrapper_get_ys(solution, &ys) != DIFFSOL_OK) {
diffsol_solution_wrapper_free(solution);
diffsol_ode_free(ode);
return fail("diffsol_solution_wrapper_get_ys");
}
const uint8_t *data_ptr = diffsol_tensor_ptr(ys);
const size_t col_stride = diffsol_tensor_stride(ys, 1);
int status = 0;
printf("%8s %14s %14s\n", "t", "y", "exact");
for (size_t j = 0; j < diffsol_tensor_dim(ys, 1); j++) {
const double y = *(const double *)(data_ptr + j * col_stride);
const double expected = exact(params[0], t_eval[j]);
printf("%8.3f %14.8f %14.8f\n", t_eval[j], y, expected);
if (fabs(y - expected) > 1e-5) {
status = 1;
}
}
printf("rhs was called %d times\n", data.rhs_calls);
diffsol_tensor_free(ys);
diffsol_solution_wrapper_free(solution);
diffsol_ode_free(ode);
Example: DiffSL code with the JIT
The example
logistic_diffsl_jit.c
solves the same equation from DiffSL code. The library compiles the code at runtime. Thus the
library must have a JIT backend (diffsl-cranelift or diffsl-llvm*).
/* The model in DiffSL. `in_i` are the parameters, `u_i` the state, `F_i` the right-hand side
* and `out_i` the output. */
static const char *CODE = "in_i { r = 1 }\n"
"u_i { y = 0.1 }\n"
"F_i { r * y * (1 - y) }\n"
"out_i { y }\n";
Select a JIT backend that the library has, and create the solver:
/* Use Cranelift if the library has it, otherwise LLVM. The environment variable
* DIFFSOL_JIT_BACKEND can select a different backend. */
#if defined(DIFFSOL_DIFFSL_CRANELIFT)
int32_t backend = DIFFSOL_JIT_BACKEND_TYPE_CRANELIFT;
#else
int32_t backend = DIFFSOL_JIT_BACKEND_TYPE_LLVM;
#endif
const char *requested = getenv("DIFFSOL_JIT_BACKEND");
if (requested != NULL && strcmp(requested, "llvm") == 0) {
backend = DIFFSOL_JIT_BACKEND_TYPE_LLVM;
} else if (requested != NULL && strcmp(requested, "cranelift") == 0) {
backend = DIFFSOL_JIT_BACKEND_TYPE_CRANELIFT;
}
printf("JIT backend: %s\n", diffsol_jit_backend_type_name(backend));
OdeWrapper *ode = diffsol_ode_new_jit(CODE, backend, DIFFSOL_MATRIX_TYPE_NALGEBRA_DENSE,
DIFFSOL_LINEAR_SOLVER_TYPE_DEFAULT,
DIFFSOL_ODE_SOLVER_TYPE_BDF);
if (ode == NULL) {
return fail("diffsol_ode_new_jit");
}
The DiffSL constructors (diffsol_ode_new_jit, diffsol_ode_new_external and diffsol_ode_new_external_dynamic) do not have a scalar type argument. They always use f64.
The solve is the same as in the callbacks example.
Run the examples
Build the library, then compile and run an example. On Linux and macOS:
cargo build -p diffsol-c --features diffsl-cranelift
cc examples/diffsol-c-logistic/c/logistic_diffsl_jit.c -I target/debug/include \
-L target/debug -ldiffsol_c -lm -Wl,-rpath,$PWD/target/debug -o logistic_diffsl_jit
./logistic_diffsl_jit
The script examples/diffsol-c-logistic/c/run_examples.sh compiles and runs the examples
against a Cargo build. It runs the JIT example only if the library has a JIT backend, and also
runs it with LLVM if the library has LLVM. The CI runs it on Linux, macOS and Windows (in Git
Bash, with MSVC).
cargo build -p diffsol-c --features diffsl-cranelift
examples/diffsol-c-logistic/c/run_examples.sh target/debug
The JIT example uses Cranelift if the library has it. To select the backend, set the environment
variable DIFFSOL_JIT_BACKEND to cranelift or llvm.
WebAssembly
Most of diffsol can be compiled to WebAssembly, allowing it to be used in web applications in the browser or other environments that support Wasm.
The main limitation is that JIT compilation of the DiffSL DSL is not yet supported in Wasm. This means you must use rust closures or the OdeEquations trait to specify your problems, rather than using the DiffSL DSL. To use DiffSL from Wasm, you need a server to do the JIT compilation, see WebAssembly with JIT.
An example Yew app
To demonstrate using diffsol in a WebAssembly application, we will create a simple Yew app that simulates a population dynamics model. The app will allow users to move sliders to adjust the parameters of the model and see the results in real-time using a plotly chart.
A demo built from this example is available online.
Getting started
First, you need to add the wasm32-unknown-unknown target to your Rust toolchain:
rustup target add wasm32-unknown-unknown
We'll use trunk to build our Yew app, so you need to install it if you haven't already:
cargo install trunk
Then, create a new Yew app:
cargo new example-yew-diffsol
And add the necessary dependencies to your Cargo.toml:
[dependencies]
yew = { version = "0.21.0", features = ["csr"] }
diffsol = { version = "0.20", features = [] }
nalgebra = "0.35"
yew-plotly = "0.3.0"
web-sys = "0.3.77"
getrandom = { version = "0.3", features = ["wasm_js"] }
The getrandom crate needs to know which source of random numbers to use in the browser. Enable the wasm_js backend with a .cargo/config.toml file in the root of your crate:
[target.wasm32-unknown-unknown]
rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
Trunk also needs an index.html file in the root of your crate. The app uses a plotly chart, so this file must load the plotly JavaScript library:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
<script src="https://cdn.plot.ly/plotly-2.16.1.min.js"></script>
</head>
<body></body>
</html>
The Yew app
We'll keep it simple and create a single component that will handle the population dynamics simulation. This will consist of the following:
- A
problemof typeOdeSolverProblemthat we'll create when the component is mounted, and keep wrapped in ause_mut_refhook so we can modify it when the parameters change. - The initial parameters for the problem held in
params, which will be stored in ause_statehook. - An
onchangecallback that will update the parameters of the problem when the user changes the sliders. - A
Plotlycomponent that will display the results of the simulation. - Two sliders for the user to adjust two out of the four parameters of the model.
use diffsol::{MatrixCommon, NalgebraVec, OdeBuilder, OdeEquations, OdeSolverMethod, Op, Vector};
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yew_plotly::{
plotly::{common::Mode, layout::Axis, Layout, Plot, Scatter},
Plotly,
};
type M = diffsol::NalgebraMat<f64>;
#[function_component]
fn App() -> Html {
let problem = use_mut_ref(|| {
OdeBuilder::<M>::new()
.rhs(|x, p, _t, y| {
y[0] = p[0] * x[0] - p[1] * x[0] * x[1];
y[1] = p[2] * x[0] * x[1] - p[3] * x[1];
})
.init(|_p, _t, y| y.fill(1.0), 2)
.p(vec![2.0 / 3.0, 4.0 / 3.0, 1.0, 1.0])
.build()
.unwrap()
});
let params = use_state(|| {
NalgebraVec::from_vec(
vec![2.0 / 3.0, 4.0 / 3.0, 1.0, 1.0],
*problem.borrow().eqn.context(),
)
});
let onchange = |i: usize| {
let params = params.clone();
let problem = problem.clone();
Callback::from(move |e: InputEvent| {
let input: HtmlInputElement = e.target_unchecked_into();
let value = input.value().parse::<f64>().unwrap();
let mut new_params = NalgebraVec::clone(¶ms);
new_params[i] = value;
let mut problem = problem.borrow_mut();
problem.eqn.set_params(&new_params);
params.set(new_params);
})
};
let oninput_a: Callback<InputEvent> = onchange(0);
let oninput_b: Callback<InputEvent> = onchange(1);
let (ys, ts, _stop_reason) = {
let problem = problem.borrow();
let mut solver = problem.tsit45().unwrap();
solver.solve(40.0).unwrap()
};
let prey: Vec<_> = ys.inner().row(0).into_iter().copied().collect();
let predator: Vec<_> = ys.inner().row(1).into_iter().copied().collect();
let time: Vec<_> = ts.into_iter().collect();
let prey = Scatter::new(time.clone(), prey)
.mode(Mode::Lines)
.name("Prey");
let predator = Scatter::new(time, predator)
.mode(Mode::Lines)
.name("Predator");
let mut plot = Plot::new();
plot.add_trace(prey);
plot.add_trace(predator);
let layout = Layout::new()
.x_axis(Axis::new().title("t".into()))
.y_axis(Axis::new().title("population".into()));
plot.set_layout(layout);
let a_str = format!("{}", params.get_index(0));
let b_str = format!("{}", params.get_index(1));
html! {
<div>
<h1>{ "Population Dynamics: Prey-Predator Model" }</h1>
<Plotly plot={plot}/>
<ul>
<li>
<input oninput={oninput_a} type="range" id="a" name="a" min="0.1" max="3" step="0.1" value={a_str} />
<label for="a">{"a"}</label>
</li>
<li>
<input oninput={oninput_b} type="range" id="b" name="b" min="0.1" max="3" step="0.1" value={b_str} />
<label for="b">{"b"}</label>
</li>
</ul>
</div>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
Building and running the app
You can build and run the app using trunk:
trunk serve
WebAssembly with JIT
It is possible to use diffsol from WebAssembly with JIT compilation, but this requires a bit more work and a backend server to perform the actual JIT compilation. If you are interested in using diffsol in this way, please get in touch. In the meantime, you can try out the interactive diffsol solver below:
Loading interactive solver…
Benchmarks
The goal of this chapter is to compare the performance of the diffsol implementation with other similar ode solver libraries.
The libraries we will compare against are:
- Sundials: A suite of advanced numerical solvers for ODEs and DAEs, implemented in C.
- Diffrax: A Python library for solving ODEs and SDEs implemented using JAX.
- Casadi: A C++ library with Python and MATLAB bindings, for solving ODEs and DAEs, nonlinear optimisation and algorithmic differentiation.
The comparison with Sundials will be done in Rust by wrapping C functions and comparing them to Rust implementations. The comparison with the Python libraries (Diffrax and Casadi) will be done by wrapping diffsol in Python using the PyO3 library, and comparing the performance of the wrapped functions. As well as benchmarking the diffsol solvers, this also serves as an example of how to wrap and use diffsol in other languages.
Sundials Benchmarks
To begin with we have focused on comparing against the popular Sundials solver suite, developed by the Lawrence Livermore National Laboratory.
Test Problems
To choose the test problems we have used several of the examples provided in the Sundials library. The problems are:
robertson: A stiff DAE system with 3 equations (2 differential and 1 algebraic). In Sundials this is part of the IDA examples and is contained in the fileida/serial/idaRoberts_dns.c. In Sundials the problem is solved using the Sundials dense linear solver andSUNMatrix_Dense, in diffsol we use the dense LU linear solver, dense matrices and vectors from the nalgebra library.robertson_ode: The same problem asrobertsonbut in the form of an ODE. This problem has a variable size implemented by duplicating the 3 original equations \(n^2\) times, where \(n\) is the size input parameter. In Sundials the problem is solved using the KLU sparse linear solver and theSUNMatrix_Sparsematrix. For the results below (diffsol v0.13.0), diffsol used the faer sparse matrix and LU solver. The current benchmark code (crates/diffsol/benches/ode_solvers.rs) is different: it solves the \(n^2\) copies of the 3 equations as independent batch lanes, with the denseNalgebraMatmatrix and theNalgebraLUlinear solver. This example is part of the Sundials CVODE examples and is contained in the filecvode/serial/cvRoberts_block_klu.c.heat2d: A 2D heat DAE problem with boundary conditions imposed via algebraic equations. The size \(n\) input parameter sets the number of grid points along each dimension, so the total number of equations is \(n^2\). This is part of the IDA examples and is contained in the fileida/serial/idaHeat2D_klu.c. In Sundials this problem is solved using the KLU sparse linear solver and theSUNMatrix_Sparsematrix, and in diffsol we use the faer sparse matrix and LU solver.foodweb: A predator-prey problem with diffusion on a 2D grid. The size \(n\) input parameter sets the number of grid points along each dimension and we have 2 species, so the total number of equations is \(2n^2\) This is part of the IDA examples and is contained in the fileida/serial/idaFoodWeb_bnd.c. In Sundials the problem is solved using a banded linear solver and theSUNMatrix_Bandmatrix. diffsol does not have a banded linear solver, so we use the faer sparse matrix and LU solver.
Method
In each case we have taken the example files from the Sundials library at version 6.7.0 and made minimal
modifications to the files, removing all printf output and changing the main functions to named functions to allow
them to be called from rust. We have also made some minor edits to compile and link these examples to the v7.7.0 version
of Sundials, which is the version used for all the benchmarks presented below. We have then implemented the same
problem in Rust using the diffsol library, porting the residual functions defined in the Sundials examples to
diffsol-compatible functions representing the RHS, mass matrix and jacobian multiplication functions for the problem. We
have used the outputs published in the Sundials examples as the reference outputs for the tests to ensure that the
implementations are equivalent. The relative and absolute tolerances for the solvers were set to the same values in both
implementations.
All of the benchmarks discussed in this section, for both diffsol and Sundials, are serial and don't use any
parallelism. All rayon and openmp parallelism was turned off by setting RAYON_NUM_THREADS=1 and OMP_NUM_THREADS=1 in
the environment variables.
There are a number of differences between the Sundials and diffsol implementations that may affect the performance of the solvers. The main differences are:
- The Sundials IDA solver has the problem defined as a general DAE system, while the diffsol solver has access to the
RHS and mass matrix functions separately. The Sundials CVODE solver has the problem defined as an ODE system and the
mass is implicitly an identity matrix, and this is the same for the diffsol implementation for the
robertson_odeproblem. - In the Sundials examples that use a user-defined jacobian (
robertson,robertson_ode,heat2d), the jacobian is provided as a sparse or dense matrix. In diffsol the jacobian is provided as a function that multiplies the jacobian by a vector, so diffsol needs to do additional work to generate a jacobian matrix from this function. - Generally the types of matrices and linear solver are matched between the two implementations (see details in the
"Test Problems" section above). However, the
foodwebproblem is slightly different in that it is solved in Sundials using a banded linear solver and banded matrices and the jacobian is calculated using finite differences. In diffsol we use the faer sparse LU solver and sparse matrices, and the jacobian is calculated using the jacobian function provided by the user. - The Sundials implementations make heavy use of indexing into arrays, as do the diffsol implementations. In Rust this indexing is bounds checked, which affects performance slightly but was not found to be a significant factor.
Finally, we have also implemented the robertson, heat2d and foodweb problems in the DiffSl language. For the
heat2d and foodweb problems we wrote out the diffusion matrix and mass matrix from the Rust implementations and
wrote the rest of the model by hand. For the robertson problem we wrote the entire model by hand.
Results
These results were generated using diffsol v0.13.0, and were run on a Dell PowerEdge R7525 2U rack server, with dual AMD EPYC 7343 3.2Ghz 16C CPU and 128GB Memory.
The performance of each implementation was timed and includes all setup and solve time. The exception to this is for the DiffSl implementations, where the JIT compilation for the model was not included in the timings (since the compilation time for the C and Rust code was also not included). We have presented the results in the following graphs, where the x-axis is the size of the problem \(n\) and the y-axis is the time taken to solve the problem relative to the time taken by the Sundials implementation (so \(10^0\) is the same time as Sundials, \(10^1\) is 10 times slower etc.)
Bdf solver
The BDF solver is the same method as that used by the Sundials IDA and CVODE solvers so we expect the performance to be largely similar, and this is generally the case. There are differences due to the implementation details for each library, and the differences in the implementations for the linear solvers and matrices as discussed above.
For the small, dense, stiff robertson problem the diffsol implementation is very close and only slightly faster than
Sundials (about 0.9).
For the sparse heat2d problem the diffsol implementation is slower than Sundials for smaller problems (about 1.5) but
the performance improves significantly for larger problems until it is at about 0.6. Since this improvement for larger
systems is not seen in foodweb or robertson_ode problems, it is likely due to the fact that the heat2d problem has
a constant jacobian matrix and the diffsol implementation has an advantage in this case.
For the foodweb problem the diffsol implementation is roughly 2 times slower than Sundials. It is interesting that
when the problem is implemented in the DiffSl language (see benchmark below) the slowdown reduces slightly to 1.6,
indicating that much of the performance difference is likely due to the implementation details of the Rust code for the
rhs, jacobian and mass matrix functions.
The diffsol implementation of the robertson_ode problem ranges between 1.5 - 1.9 times slower than Sundials over the
problem range, performing slightly worse for larger problems.
tr_bdf2 & esdirk34 solvers (SDIRK)
The low-order tr_bdf2 solver is slower than the Sundials bdf solver for all the problems, perhaps due to the
generally tight tolerances used. robertson and robertson_ode use rtol = 1e-4 with a vector atol
(1e-8, 1e-6, 1e-6 for robertson, and 1e-8, 1e-14, 1e-6 for robertson_ode in the current code), heat2d uses
rtol = atol = 1e-7 and foodweb uses rtol = atol = 1e-5. The esdirk34 solver is similar, still slower than sundials but improved over the tr_bdf2
solver.
Bdf + DiffSl
The main difference between this plot and the previous for the Bdf solver is the use of the DiffSl language for the
equations, rather than Rust closures. The trends in each case are mostly the same, and the DiffSl implementation has
similar speed to rust closures for most problems. For some, such as foodweb, the DiffSl implementation is actually
faster than the Rust closure implementation. This may be due to the fact that the rust closures bound-check the array
indexing, while the DiffSl implementation does not.
This plot demonstrates that a DiffSL implementation can be comparable in speed to a hand-written Rust or C implementation, but much more easily wrapped and used from a high-level language like Python or R, where the equations can be passed down to the rust solver as a simple string and then JIT compiled at runtime.
Python (Diffrax & Casadi)
Diffrax is a Python library for solving ODEs and SDEs implemented using JAX. Casadi is a C++ library with Python and MATLAB bindings for solving ODE and nonlinear optimisation problems. In this benchmark we compare the performance of the diffsol implementation with the Diffrax and Casadi libraries.
As well as demonstrating the performance of the diffsol library, this benchmark also serves as an example of how to wrap and use diffsol in other languages. The code for this benchmark can be found here. The maturin library was used to generate a template for the Python bindings and the CI/CD pipeline necessary to build the wheels ready for distribution on PyPI. The pyo3 library was used to wrap the diffsol library in Python.
Problem setup
We will use the robertson_ode problem for this benchmark. This is a stiff ODE system with 3 equations and 3 unknowns, and is a common benchmark problem. To illustrate the performance over a range of problem sizes, the Robertson equations were duplicated a factor of ngroups, so the total number of equations solved is 3 * ngroups.
The Diffrax implementation was based on the example in the Diffrax documentation, which was further extended to include the ngroups parameter. As is already used in the example, the Kvaerno5 method was used for the solver. You can see the final implementation of the model here.
The Casadi implementation was written from scratch using Casadi's python API. You can see the final implementation of the model here.
The diffsol implementation of the model written using the DiffSL language, you can see the final implementation of the model here.
The full implementation of the benchmark presented below can be seen here. The diffsol benchmark is performed using the bdf solver. For ngroups < 20 it uses the nalgebra dense matrix and LU solver, and for ngroups >= 20 the faer sparse matrix and LU solver are used.
Differences between implementations
There are a few key differences between the Diffrax, Casadi and diffsol implementations that may affect the performance of the solvers. The main differences are:
- The Casadi implementation uses sparse matrices, whereas the diffsol implementation uses dense matrices for
ngroups< 20, and sparse matrices forngroups>= 20. This will provide an advantage for diffsol for smaller problems. - I'm unsure if the Diffrax implementation uses sparse or dense matrices, but it is most likely dense as JAX only has experimental support for sparse matrices. Treating the Jacobian as dense will be a disadvantage for Diffrax for larger problems as the Jacobian is very sparse.
- The Diffrax implementation uses the
Kvaerno5method (a 5th order implicit Runge-Kutta method). This is different from the BDF method used by both the Casadi and diffsol implementations. - Each library was allowed to use multiple threads according to their default settings. The only part of the diffsol implementation that takes advantage of multiple threads is the
faersparse LU solver and matrix. Both thenalgebraLU solver, matrix, and the DiffSL generated code are all single-threaded. Diffrax uses JAX, which takes advantage of multiple threads (CPU only, no GPUs were used in these benchmarks). The Casadi implementation also uses multiple threads.
Results
The benchmarks were run on a Dell PowerEdge R7525 2U rack server, with dual AMD EPYC 7343 3.2Ghz 16C CPU and 128GB Memory. Each benchmark was run using both a tight (1e-8) and a loose (1e-4) tolerance for both rtol and atol. Casadi and diffsol were run with ngroups between 1 and 10,000, and Diffrax was run with ngroups between 1 and 100. The values of ngroups used were 1, 10, 20, 40, 70, 100, 200, 400, 700, 1000, 5000 and 10,000, so there are no results between ngroups = 1 and ngroups = 10. The results are presented in the following graph, where the x-axis is the size of the problem ngroups and the y-axis is the time taken to solve the problem relative to the time taken by the diffsol implementation (so 10^0 is the same time as diffsol, 10^1 is 10 times slower etc.).
diffsol is faster than Diffrax for all the problem sizes and tolerances tested. diffsol is faster than Casadi for all problem sizes with the loose tolerance (1e-4), and up to ngroups = 1000 with the tight tolerance, but the Casadi and diffsol implementations converge to be similar for larger problems (ngroups > 100). At ngroups = 5000 and 10,000 with the tight tolerance (1e-8), Casadi is faster than diffsol (diffsol takes approximately 1.1 times as long as Casadi).
The diffsol implementation outperforms the other implementations significantly for the smallest problem size. At ngroups = 1, Casadi and Diffrax are between approximately 4 and 38 times slower than diffsol. At these small problem sizes, the dense matrix and solver used by diffsol provide an advantage over the sparse solver used by Casadi. Casadi also has additional overhead to evaluate each function evaluation, as it needs to traverse a graph of operations to calculate each rhs or jacobian evaluation, whereas the DiffSL JIT compiler will compile to native code using the LLVM backend, along with low-level optimisations that are not available to Casadi. Diffrax is also significantly slower than diffsol for smaller problems, this might be due to (a) Diffrax being a ML library and not optimised for solving stiff ODEs, or (b) double precision is used, which again is not a common use case for ML libraries, or (c) perhaps the different solver methods (Kvaerno5 vs BDF) are causing the difference.
As the problem sizes get larger, the performance of Diffrax and Casadi improve rapidly relative to diffsol. At ngroups = 10 with the tight tolerance, Diffrax is only slightly slower than diffsol (approximately 1.07 times). After ngroups = 10, the performance of Diffrax drops off again, probably due to JAX not taking advantage of the sparse structure of the problem. The performance of Casadi continues to improve, and for ngroups > 100 it is comparable to diffsol (within approximately 1.4 times). At ngroups = 10,000, Casadi and diffsol take approximately the same time with the loose tolerance, and Casadi takes approximately 12% less time than diffsol with the tight tolerance.