Event Handling and Callbacks
7 min read
Welcome to the logic gate of the simulation world! 🧠
Up until now, our differential equations have been smooth, continuous, and predictable—like a perfectly paved highway. But the real world is chaotic. Balls bounce, patients take pills at specific times, and thermostats click on when the temperature drops.
In DifferentialEquations.jl, these interruptions are handled by the Callback System.
If you thought solving was cool, wait until you learn how to pause time, rewrite the laws of physics for a microsecond, and then let time resume. It’s like being a Time Lord, but with more Julia syntax. ⏳
1. Introduction to the DifferentialEquations Callback System
The Definition
A Callback is a mechanism that allows the solver (the "integrator") to execute custom code when specific conditions are met during the integration process. It allows you to modify the state (u) or parameters (p) of the system discontinuously.
The Problem
Standard ODE solvers assume solutions are smooth (differentiable).
- Discontinuities: If you suddenly change a value (like adding a dose of medicine), the derivative becomes infinite. A standard solver trying to approximate a curve will choke, crash, or give massive errors if it steps over a cliff it didn't see coming.
- Unknown Timing: Sometimes you don't know when an event happens, only where (e.g., "stop when the rocket hits the ground").
The Solution
The Callback System acts as a supervisor. It monitors the simulation at every step.
- Check: "Did an event happen?"
- Interrupt: If yes, stop the solver precisely at that moment.
- Affect: Apply the change (the "Callback").
- Restart: Reset the solver's internal error checks and resume simulation.
2. DiscreteCallbacks: Time-Triggered Events
The Concept
A DiscreteCallback applies to events that happen at known, specific time points (or specific steps), regardless of the system's state.
Think: Taking a pill every 6 hours, turning off a light at 10 PM, or depositing money into an account annually.
Industry Standard: PresetTimeCallback
While you can write a condition that checks if t == 4.0, floating-point comparisons are dangerous (is equal to ? The computer says no).
For events happening at specific times, DifferentialEquations.jl provides a specialized, optimized tool: PresetTimeCallback.
Hands-on: The Pharmacokinetics Model (Dosing)
Let's simulate a drug decaying in the body (). We will inject a new dose at and .
using DifferentialEquations, Plots
# 1. Define the Physics (Exponential Decay)
function decay_dynamics(du, u, p, t)
du[1] = -0.5 * u[1]
end
u0 = [10.0] # Initial dose
tspan = (0.0, 30.0)
prob = ODEProblem(decay_dynamics, u0, tspan)
# 2. Define the Event (The Dose)
# We want to add +10 to the concentration at t=10 and t=20
dosetimes = [10.0, 20.0]
# The affect! function modifies the 'integrator'
# 'integrator' is the object holding the current state of the simulation
function affect!(integrator)
integrator.u[1] += 10.0
end
# 3. Create the Callback
cb = PresetTimeCallback(dosetimes, affect!)
# 4. Solve with the Callback
# notice tstops: helps the solver land EXACTLY on the dose times
sol = solve(prob, Tsit5(), callback=cb, tstops=dosetimes)
# 5. Visualize
plot(sol, title="Medication Dosing (Discrete Callback)", label="Concentration")What happened under the hood?
The solver marched forward. It saw tstops at 10.0. It adjusted its step size to land exactly on 10.0. It paused, ran affect!, increased u, and then recalculated the next step based on the new, higher value.
Fun Fact: If you didn't use a callback and just tried to hack the function to jump, the solver acts like a confused GPS. It sees the jump as a massive error and shrinks the time step to near zero (like ), trying to trace the vertical line. Your simulation would take forever! 🐢
3. ContinuousCallbacks: State-Triggered Events
The Concept
A ContinuousCallback is used when the event depends on the state variables (), not just the clock. The solver must mathematically hunt for the exact moment the event occurs.
Think: A bouncing ball hitting the floor. The event happens when height . We don't know when that is until we simulate it.
The Mechanism: Root Finding
You define a function . The event triggers when .
The solver monitors this function. If it detects the sign changed from positive to negative (or vice versa) between steps, it backtracks and performs a "root-finding" operation (like bisection) to find the exact millisecond the crossing happened.
Hands-on: The Bouncing Ball
Let's simulate a ball dropping.
- (Gravity)
- (Velocity)
- Event: When (hits ground), velocity flips ().
# 1. Physics
function ball_dynamics(du, u, p, t)
du[1] = u[2] # dx/dt = v
du[2] = -9.81 # dv/dt = g
end
# u[1] = height (x), u[2] = velocity (v)
u0 = [50.0, 0.0] # Start at 50m height, stationary
tspan = (0.0, 15.0)
prob = ODEProblem(ball_dynamics, u0, tspan)
# 2. The Condition (When does it happen?)
# trigger when u[1] (height) == 0
function condition(u, t, integrator)
return u[1]
end
# 3. The Affect (What happens?)
function affect!(integrator)
# Flip velocity and lose energy (restitution coefficient 0.8)
integrator.u[2] = -integrator.u[2] * 0.8
end
# 4. Create ContinuousCallback
# nothing: what to do if crossing 0 from negative to positive (we don't care here)
# affect!: what to do if crossing 0 from positive to negative (falling down)
cb = ContinuousCallback(condition, nothing, affect!)
# 5. Solve
sol = solve(prob, Tsit5(), callback=cb)
plot(sol, title="Bouncing Ball (Continuous Callback)", label=["Height" "Velocity"])Critical Practice: VectorContinuousCallback
If you have multiple independent events (like a ball bouncing off 4 different walls), use VectorContinuousCallback. However, for simple setups, standard ContinuousCallback is sufficient.
Warning: Be careful with your condition function. If your event triggers at and your
affect!sets , the solver might get stuck in an infinite loop triggering the event over and over. This is called "Zeno's Paradox" behavior in simulations.
4. Callback Sets: Combining Multiple Events
The Concept
Real systems are messy. A patient might take a pill every 12 hours (Discrete) AND have a heart attack if their blood pressure hits a certain threshold (Continuous).
You can combine as many callbacks as you want using CallbackSet.
Hands-on: The "Pinball" Simulation
Let's combine the Bouncing Ball with a "Wind Gust" that hits at exactly .
# 1. Re-use ball physics and bouncing callback from previous step
# (Assuming ball_dynamics and continuous_cb are defined as above)
# 2. Create the Wind Gust (Discrete Event)
# At t=2, wind adds horizontal velocity (let's pretend u[2] gets a boost)
function wind_affect!(integrator)
println("Whoosh! Wind gust at t=$(integrator.t) 🌬️")
integrator.u[2] += 20.0 # Huge updraft
end
discrete_cb = PresetTimeCallback([2.0], wind_affect!)
# 3. Create the Set
cb_set = CallbackSet(cb, discrete_cb)
# 4. Solve with the Set
sol = solve(prob, Tsit5(), callback=cb_set)
plot(sol, title="Bouncing Ball with Wind Gust", label=["Height" "Velocity"])Why this matters
In complex implementations (like Robotics or Biology), you will often have a CallbackSet containing:
- Controller logic (Discrete: runs at 100Hz).
- Physical limits (Continuous: joint stops moving when it hits a wall).
- Sensor noise updates (Discrete).
Summary & Best Practices
- Use
PresetTimeCallbackfor known times. It handles stepping exactly to the time point for you. - Use
ContinuousCallbackfor state-dependent events. Remember, this involves root-finding, so it is computationally heavier than discrete callbacks. - Mutate, don't replace. In
affect!(integrator), always modifyintegrator.u[i] = .... Do not dointegrator.u = ...(that creates a new array and breaks the link to the solver). - Floating Points: Never compare
if u == 0. Always look for zero-crossings using the ContinuousCallback logic.
You have now mastered the art of interrupting the space-time continuum of your simulation. Go forth and create chaos! 📉📈
References & Further Reading
Challenge
Thermostat and Window Simulation
You are tasked with simulating the temperature of a room that is controlled by a thermostat and is affected by an external event. The room's temperature dynamics are governed by the following ordinary differential equation:
dT/dt = -k * (T - T_out) + H
Where:
Tis the room's temperature (u[1])kis the heat transfer coefficient (p[1])T_outis the constant outside temperature, fixed at10.0°C.His the power from the heater (p[2])
Your goal is to implement two different event-handling mechanisms using callbacks:
A Thermostat (Continuous Events):
- The heater should turn ON (set
Hto10.0) when the room temperatureTdrops to 18.0°C. - The heater should turn OFF (set
Hto0.0) when the room temperatureTrises to 22.0°C.
- The heater should turn ON (set
An Open Window (Discrete Event):
- At exactly
t = 500.0, a window is opened, which doubles the heat transfer coefficientk.
- At exactly
Complete the provided initial code by creating the necessary ContinuousCallback and PresetTimeCallback objects and then combining them into a CallbackSet to solve the ODEProblem.
Expected result
Your final code should correctly implement and combine three callbacks to solve the ODE problem. The solution must contain:
- A
ContinuousCallbackfor turning the heater on.- The
conditionfunction must evaluate to zero whenu[1]is18.0(e.g.,u[1] - 18.0). - The
affect_on!function must mutate the integrator's parameters to set the heater powerp[2]to10.0.
- The
- A second
ContinuousCallbackfor turning the heater off.- The
conditionfunction must evaluate to zero whenu[1]is22.0(e.g.,u[1] - 22.0). - The
affect_off!function must mutateintegrator.p[2]to0.0.
- The
- A
PresetTimeCallbackfor the window event.- It must be configured to trigger at
t = 500.0. - The
affect_window!function must double the value of the heat transfer coefficientintegrator.p[1].
- It must be configured to trigger at
- A
CallbackSetthat correctly combines the three individual callbacks (cb_on,cb_off, andcb_window). - A call to
solvethat passes theODEProblemand the createdCallbackSetusing thecallbackkeyword argument.