Discrete Events¶
diffsol-jax solves hybrid systems: differential equations interrupted by discrete events. An event has two parts, given together when building the problem:
root(y, p, t): the event condition. An event fires when any entry of the result crosses zero.reset(y, p, t): the state jump. At the crossing time the solver replaces the state withreset(y, p, t)and continues integrating tot1.
A classic example is a dosing model: a drug concentration decays, and a new dose is added whenever it falls to a threshold.
import jax.numpy as jnp
from diffsol_jax import ODEProblem, solve
threshold, dose = 0.5, 0.7
problem = ODEProblem(
rhs=lambda y, p, t: -p[0] * y,
state=1,
params=1,
root=lambda y, p, t: y[0] - threshold,
reset=lambda y, p, t: y + dose,
)
ts = jnp.linspace(0.0, 5.0, 100)
ys = solve(problem, jnp.array([1.0]), jnp.array([1.0]), 0.0, 5.0, saveat=ts)
The root finding is exact to solver tolerance: the event does not wait for a
step boundary. saveat times before the crossing return the state before the
reset, and later times continue from the new state.
Events That Stay at the Root¶
Some resets leave the root function at zero. The bouncing ball is the standard
example: the bounce flips the velocity but the position stays on the floor,
exactly where root crosses. Numerical noise can then re-trigger the event
immediately, applying the reset again and again at one instant.
The fix is to gate the condition on its direction, so that it can only fire on the crossing you mean:
problem = ODEProblem(
rhs=lambda y, p, t: jnp.array([y[1], -p[0]]), # y = [position, velocity]
state=2,
params=2,
root=lambda y, p, t: jnp.where(y[1] < 0, y[0], 1.0), # falling and on the floor
reset=lambda y, p, t: jnp.array([y[0], -p[1] * y[1]]), # restitution bounce
)
While the ball is rising the condition is pinned at 1.0, so only downward
contacts fire.
Gradients¶
A solve with events is differentiable with respect to y0 and params,
including the dependence of the event times on them: the jump in the
sensitivities at each crossing is accounted for.
Only forward sensitivities propagate through events. For a
problem with events solve defaults to ad="forward", so jax.grad works out
of the box.
vmap¶
diffsol cannot batch an event-driven solve as lanes, so jax.vmap over a
problem with events falls back to solving the lanes one at a time. The results
are identical to a Python loop over the batch.
Limitations¶
rootandresetcome together. An event always continues the solve: a root that terminates at the crossing (as in diffrax) is not supported.- Reverse mode uses forward sensitivities.
ad="adjoint"does not support events, so gradients cost one sensitivity per parameter. vmapsolves lanes sequentially, as above.