Skip to content

Fitting a predator-prey model

This example fits the parameters of a Lotka-Volterra model to noisy observations by gradient descent: generate data from known parameters, then recover them by minimising a least-squares loss with Optax. It also shows a pytree of parameters -- an Equinox module with named fields -- in place of a flat array.

import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import optax
from diffsol_jax import ODEProblem, solve
from tqdm import trange

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

The parameters are a module with one field per rate constant, and rhs refers to them by name.

class LotkaVolterraParams(eqx.Module):
    alpha: jax.Array
    beta: jax.Array
    gamma: jax.Array
    delta: jax.Array


def rhs(x, p, t):
    prey, predator = x
    return jnp.array(
        [
            p.alpha * prey - p.beta * predator * prey,
            p.gamma * prey * predator - p.delta * predator,
        ]
    )

params= takes the module as a template: its float-array leaves declare the parameter shapes. The problem is built once and reused for every solve below, whatever the parameter values.

key = jr.key(0)
t_eval = jnp.linspace(0.0, 5.0, num=100)
y0 = 5.0 * jr.uniform(key=key, shape=(2,))

p_true = LotkaVolterraParams(
    alpha=jnp.asarray(1.3),
    beta=jnp.asarray(0.9),
    gamma=jnp.asarray(0.8),
    delta=jnp.asarray(1.8),
)
problem = ODEProblem(rhs, state=2, params=p_true)


def trajectory(p):
    return solve(problem, y0, p, t_eval[0], t_eval[-1], saveat=t_eval)


ys_true = trajectory(p_true)
ys_data = ys_true + 0.05 * jr.normal(key=key, shape=ys_true.shape)

The training loop is ordinary JAX: jax.value_and_grad of the loss (the gradient runs the diffsol adjoint underneath), Adam from Optax, and a jitted step.

p = LotkaVolterraParams(
    alpha=jnp.asarray(1.1),
    beta=jnp.asarray(1.0),
    gamma=jnp.asarray(0.5),
    delta=jnp.asarray(1.6),
)

opt = optax.adam(1e-2)
opt_state = opt.init(p)


def loss_fn(p):
    return jnp.sum((trajectory(p) - ys_data) ** 2)


@jax.jit
def step(p, opt_state):
    loss_val, grads = jax.value_and_grad(loss_fn)(p)
    updates, opt_state = opt.update(grads, opt_state, p)
    return optax.apply_updates(p, updates), opt_state, loss_val


pbar = trange(200, desc="fit")
for _ in pbar:
    p, opt_state, loss_val = step(p, opt_state)
    pbar.set_postfix(loss=f"{loss_val:.4f}")

print(jax.tree.leaves(p))
ys_fit = trajectory(p)

fig, axes = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
for ax, name, i in zip(axes, ["prey", "predator"], range(2)):
    ax.plot(t_eval, ys_data[:, i], "o", ms=3, color="black", label="data")
    ax.plot(t_eval, ys_true[:, i], "--", color="gray", label="true")
    ax.plot(t_eval, ys_fit[:, i], "-", label="fit")
    ax.set_ylabel(name)
    ax.legend(fontsize="small")
axes[-1].set_xlabel("t")
fig.tight_layout()
fig.savefig("fitting-a-predator-prey-model.png")

the fitted trajectories