Skip to content

Robertson problem

The Robertson chemical kinetics problem is a classic stiff benchmark: three species with rate constants spanning nine orders of magnitude. This example solves it in two forms -- as an ODE, and as a DAE with the conservation law \(x + y + z = 1\) in place of the third rate equation -- and checks that the two agree, on the trajectory and on the gradients.

from functools import partial

import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from diffsol_jax import ODEProblem, solve

jax.config.update("jax_enable_x64", True)

TOL = {"rtol": 1e-10, "atol": 1e-12}

The ODE form integrates all three rate equations. The DAE form replaces the third with the conservation law, written as an algebraic residual and marked with algebraic=1 (the last row of the state).

def rober_ode(y, k, t):
    return jnp.array(
        [
            -k[0] * y[0] + k[1] * y[1] * y[2],
            k[0] * y[0] - k[1] * y[1] * y[2] - k[2] * y[1] ** 2,
            k[2] * y[1] ** 2,
        ]
    )


def rober_dae(y, k, t):
    return jnp.array(
        [
            -k[0] * y[0] + k[1] * y[1] * y[2],
            k[0] * y[0] - k[1] * y[1] * y[2] - k[2] * y[1] ** 2,
            jnp.sum(y) - 1.0,
        ]
    )


k = jnp.array([0.04, 1e4, 3e7])
y0 = jnp.array([1.0, 0.0, 0.0])
t_eval = jnp.linspace(0.0, 1000.0, num=100)

prob_ode = ODEProblem(rober_ode, state=3, params=3)
prob_dae = ODEProblem(rober_dae, state=3, params=3, algebraic=1)

Both use bdf, the default solver, which handles the stiffness. The two trajectories agree to around the solver tolerances.

ys_ode = solve(prob_ode, y0, k, t_eval[0], t_eval[-1], saveat=t_eval, **TOL)
ys_dae = solve(prob_dae, y0, k, t_eval[0], t_eval[-1], saveat=t_eval, **TOL)
print(jnp.abs(ys_ode - ys_dae).max())  # ~4e-10
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
for ax, ys, title in zip(axes, [ys_ode, ys_dae], ["ODE form", "DAE form"]):
    for i, name in enumerate(["x", "y", "z"]):
        scale = 1e4 if name == "y" else 1.0
        label = name if scale == 1.0 else f"{name} x 1e4"
        ax.plot(t_eval, scale * ys[:, i], label=label)
    ax.set_title(title)
    ax.legend(fontsize="small")
axes[-1].plot(t_eval, jnp.abs(ys_ode - ys_dae), label=["x", "y", "z"])
axes[-1].set_yscale("log")
axes[-1].set_title("|ODE - DAE|")
axes[-1].legend(fontsize="small")
for ax in axes:
    ax.set_xlabel("t")
fig.tight_layout()
fig.savefig("robertson-problem.png")

the two forms and their difference

Gradients

Take the loss \(z(T)\), the third species at the final time, and differentiate it with respect to \(\log k\) (scaling by \(k\) keeps the three components comparable despite the nine orders of magnitude). jax.grad uses the adjoint, jax.jacfwd uses forward sensitivities, and both forms of the problem give the same answer.

def z_end(prob, y0, k, scale):
    return solve(prob, y0, scale * k, t_eval[0], t_eval[-1], saveat=t_eval, **TOL)[
        -1, 2
    ]


one = jnp.ones(3)
for prob in (prob_ode, prob_dae):
    z = partial(z_end, prob, y0, k)
    adjoint = jax.grad(z)(one)
    forward = jax.jacfwd(z)(one)
    print(adjoint, forward)

Gradients with respect to the initial state need one caveat in the DAE form. diffsol projects an inconsistent y0 onto the constraint before solving, and the gradient accounts for the projection: here z at t0 is solved from \(x + y + z = 1\), so a perturbation that changes the total is projected away. The two forms only agree along directions that keep the total fixed.

g_ode = jax.grad(lambda y: z_end(prob_ode, y, k, one))(y0)
g_dae = jax.grad(lambda y: z_end(prob_dae, y, k, one))(y0)

v = jnp.array([-1.0, 0.0, 1.0])  # keeps x + y + z fixed
print(g_ode @ v, g_dae @ v)  # equal
print(g_ode.sum(), g_dae.sum())  # not equal: the DAE projects this away