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 u′=f(u,p,t)u' = f(u,p,t) 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).

  1. 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.
  2. 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 4.000000000014.00000000001 equal to 44? 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 (u′=−0.5uu' = -0.5u). We will inject a new dose at t=10t=10 and t=20t=20.

julia
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 10−1410^{-14}), 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 (uu), 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 x=0x = 0. We don't know when that is until we simulate it.

The Mechanism: Root Finding

You define a function g(u,t)g(u, t). The event triggers when g(u,t)=0g(u, t) = 0.
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.

  • v′=−9.8v' = -9.8 (Gravity)
  • x′=vx' = v (Velocity)
  • Event: When x=0x=0 (hits ground), velocity flips (v=−v×0.8v = -v \times 0.8).
julia
# 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 u=0u = 0 and your affect! sets u=0u = 0, 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 t=2.0t=2.0.

julia
# 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:

  1. Controller logic (Discrete: runs at 100Hz).
  2. Physical limits (Continuous: joint stops moving when it hits a wall).
  3. Sensor noise updates (Discrete).

Summary & Best Practices

  1. Use PresetTimeCallback for known times. It handles stepping exactly to the time point for you.
  2. Use ContinuousCallback for state-dependent events. Remember, this involves root-finding, so it is computationally heavier than discrete callbacks.
  3. Mutate, don't replace. In affect!(integrator), always modify integrator.u[i] = .... Do not do integrator.u = ... (that creates a new array and breaks the link to the solver).
  4. 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:

  • T is the room's temperature (u[1])
  • k is the heat transfer coefficient (p[1])
  • T_out is the constant outside temperature, fixed at 10.0°C.
  • H is the power from the heater (p[2])

Your goal is to implement two different event-handling mechanisms using callbacks:

  1. A Thermostat (Continuous Events):

    • The heater should turn ON (set H to 10.0) when the room temperature T drops to 18.0°C.
    • The heater should turn OFF (set H to 0.0) when the room temperature T rises to 22.0°C.
  2. An Open Window (Discrete Event):

    • At exactly t = 500.0, a window is opened, which doubles the heat transfer coefficient k.

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:

  1. A ContinuousCallback for turning the heater on.
    • The condition function must evaluate to zero when u[1] is 18.0 (e.g., u[1] - 18.0).
    • The affect_on! function must mutate the integrator's parameters to set the heater power p[2] to 10.0.
  2. A second ContinuousCallback for turning the heater off.
    • The condition function must evaluate to zero when u[1] is 22.0 (e.g., u[1] - 22.0).
    • The affect_off! function must mutate integrator.p[2] to 0.0.
  3. A PresetTimeCallback for 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 coefficient integrator.p[1].
  4. A CallbackSet that correctly combines the three individual callbacks (cb_on, cb_off, and cb_window).
  5. A call to solve that passes the ODEProblem and the created CallbackSet using the callback keyword argument.
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.