Modeling Systems of ODEs
6 min read
Current Topic: Modeling Systems of ODEs
Progress: 3/4 Subtopics Complete (just kidding, let's learn them all!)
Welcome back, numerical explorer! 🔭
In the previous lessons, we conquered scalar ODEs—equations where we tracked a single value over time, like the decay of a radioactive isotope or the cooling of a cup of coffee ☕.
But let's be real: the universe is rarely a solo act. Things interact.
- Rabbits don't just exist; they get eaten by foxes. 🦊
- Planets don't float alone; they tug on each other. 🪐
- Chemicals don't just sit there; they react to form new substances. 🧪
To model these messy, interconnected realities, we need Systems of ODEs. Instead of tracking one variable , we track a vector of variables .
Let's dive in! 🏊
1. Moving from Scalars to Arrays: Handling State Vectors
The Problem:
In a scalar equation, our state u was just a number (Float64).
If we want to track Rabbits () and Foxes () simultaneously, we can't use two separate ODEProblems because depends on and vice-versa.
The Solution:
We group all our dependent variables into a single array (or vector), usually called u.
- represents (Rabbits)
- represents (Foxes)
Consequently, our derivative function f must now calculate the rate of change for both of these variables.
The Two Ways to Define f
In Julia's DifferentialEquations.jl, there are two canonical ways to write your system function. This distinction is crucial for industry performance.
A. Out-of-Place (Good for simple scripts)
The function returns a new vector containing the derivatives.
function simple_system(u, p, t)
dx = 0.5 * u[1]
dy = -0.5 * u[2]
return [dx, dy] # Returns a NEW vector
end- Pros: Easy to read, functional style.
- Cons: Allocates memory at every single step. Slow for large systems (e.g., 100+ variables).
B. In-Place (Industry Standard 🏆)
We pass a pre-allocated vector du (derivative of u) to the function. We mutate du directly.
function efficient_system!(du, u, p, t)
# du[1] corresponds to the derivative of the first variable
du[1] = 0.5 * u[1]
# du[2] corresponds to the derivative of the second variable
du[2] = -0.5 * u[2]
# No return needed; we modified 'du' in place
end- Pros: Zero memory allocation during steps. Blazing fast. 🚀
- Cons: Slightly more verbose.
💡 Practical Tip: The
!at the end of the function name (e.g.,efficient_system!) is a Julia convention indicating the function modifies its arguments. It doesn't change how the code runs, but it helps humans read it!
2. The Lotka-Volterra Model: Simulating Predator-Prey Dynamics
Let's model the classic battle of nature: The Lotka-Volterra Equations.
The Scenario:
- Prey (): They breed naturally () but get eaten by predators ().
- Predators (): They starve naturally () but grow when they eat prey ().
The Equations:
The Code:
Let's map this to our u vector:
u[1]= Prey ()u[2]= Predator ()
using DifferentialEquations
using Plots
# Define the system
function lotka_volterra!(du, u, p, t)
# Let's extract values for clarity (optional but helpful)
rabbits = u[1]
foxes = u[2]
# Hardcoded parameters for now (we will fix this in the next section!)
α, β, γ, δ = 1.5, 1.0, 3.0, 1.0
# Equation 1: d(rabbits)/dt
du[1] = α * rabbits - β * rabbits * foxes
# Equation 2: d(foxes)/dt
du[2] = δ * rabbits * foxes - γ * foxes
end
# Initial Conditions: 1.0 rabbit, 1.0 fox
u0 = [1.0, 1.0]
# Time span: 0 to 10 seconds
tspan = (0.0, 10.0)
# Define and Solve
prob = ODEProblem(lotka_volterra!, u0, tspan)
sol = solve(prob)
# Plotting
plot(sol, title="Rabbits vs Foxes")What happened?
If you run this, you'll see two oscillating lines. As rabbits increase, foxes have more food and increase. As foxes increase, they eat too many rabbits, causing rabbits to crash. The foxes then starve, and the cycle repeats. It's the circle of life! 🦁
3. Parameterizing your ODEs: Utilizing the 'p' Argument
The Problem:
In the code above, we hardcoded α = 1.5, etc.
What if we want to see what happens if foxes become super-efficient hunters? We'd have to rewrite the function every time. This is bad practice (and annoying).
The Solution:
The p argument! This is a container (usually a Tuple, Vector, or Struct) that holds your constants. You pass it into the ODEProblem.
Refactored Code:
# 1. Update the function to use 'p'
function parametrized_lv!(du, u, p, t)
x, y = u # Unpack state
α, β, γ, δ = p # Unpack parameters - Clean and readable!
du[1] = α * x - β * x * y
du[2] = δ * x * y - γ * y
end
# 2. Define parameters outside
p = (1.5, 1.0, 3.0, 1.0) # (α, β, γ, δ)
# 3. Pass 'p' to the problem
u0 = [1.0, 1.0]
tspan = (0.0, 10.0)
prob = ODEProblem(parametrized_lv!, u0, tspan, p)
sol = solve(prob)Why is this Industry Standard?
- Optimization: You can ask libraries to "find the
pthat makes the model match my real-world data." - Sensitivity Analysis: You can easily check "Does changing
αby 1% drastically change the result?" - Cleanliness: Separates logic (the equations) from configuration (the values).
4. Visualizing Interacting Systems: Phase Space Plots
The Concept:
So far, we've plotted u[1] vs Time and u[2] vs Time.
But sometimes, time isn't the most interesting thing. We want to see how Rabbits relate directly to Foxes.
This is called a Phase Space Plot. It removes time from the axes and plots State Variable A vs State Variable B.
The "Cyclic" Signature:
For Lotka-Volterra, a phase plot of Foxes vs Rabbits creates a perfect closed loop (orbit). This proves the system is periodic and doesn't just spiral out to infinity or die off to zero.
How to do it in Julia:
The plot function in DifferentialEquations.jl (via Plots.jl) is smart. You can use the idxs (indices) argument.
# Standard Time Series (Time on X-axis)
p1 = plot(sol, title="Time Series")
# Phase Space (Rabbits on X, Foxes on Y)
# idxs=(1, 2) means: Variable 1 is X-axis, Variable 2 is Y-axis
p2 = plot(sol, idxs=(1, 2),
title="Phase Space",
xaxis="Rabbits",
yaxis="Foxes",
legend=false) # No legend needed for single line
# Show them side by side
plot(p1, p2, layout=(1, 2))👀 Look Closer: If the curve in the phase plot spirals inward, the populations are stabilizing. If it spirals outward, they are destabilizing. If it's a perfect circle/oval, they are in a stable cycle.
🧠 Fun Fact: The "Canadian Lynx and Snowshoe Hare"
This math isn't just theoretical. The Hudson's Bay Company kept pelt records for nearly 100 years (1845-1935). When mathematicians plotted the data of Lynx pelts vs Hare pelts, they saw the exact oscillating phase-space cycles we just modeled! Math works! 📉🐇🐈
📚 References & Further Reading
- Official Docs: DifferentialEquations.jl Systems of ODEs
- Performance: In-place vs Out-of-place Memory Allocations
- Plotting: Plotting Phase Space with idxs
Next Up: We will look into Stiff Equations—what happens when one variable changes a million times faster than the other! (Spoiler: standard solvers explode 💥).
Challenge
Challenge: Modeling an Epidemic with a System of ODEs
You are tasked with modeling the spread of a disease through a population using the SIR (Susceptible, Infected, Recovered) model, a classic system of ordinary differential equations.
Your goal is to set up the entire problem in Julia using DifferentialEquations.jl.
Your tasks are:
Define an in-place function named
sir_model!that calculates the derivatives for the SIR system. The function must have the standard signaturesir_model!(du, u, p, t).The SIR model is described by the following equations:
dS/dt = -β * S * I / NdI/dt = β * S * I / N - γ * IdR/dt = γ * I
Where:
- The state vector
uis[S, I, R](Susceptible, Infected, Recovered). - The parameter vector
pis[β, γ](infection rate, recovery rate). Nis the total population, which is the sum ofS,I, andR.
Define the initial conditions, time span, and parameters for the simulation:
- Initial Conditions (
u0): Start with a population of 1000, where 999 are susceptible, 1 is infected, and 0 are recovered. - Time Span (
tspan): Simulate the model fromt=0.0tot=100.0. - Parameters (
p): Use an infection rateβof0.3and a recovery rateγof0.1.
- Initial Conditions (
Construct the
ODEProblemusing your function and the defined conditions.After the
ODEProblemis defined, add a comment explaining how you would generate a phase space plot of the number of infected individuals (I) versus the number of susceptible individuals (S) from a solved problem object namedsol.
Expected result
Your final code should correctly define the sir_model! function, the problem's conditions, and the ODEProblem itself.
Specifically:
- The
sir_model!function must correctly calculate the three derivatives based on the provided equations and update theduvector elementsdu[1],du[2], anddu[3]directly. It should not have areturnstatement. - The
u0variable should be a vector like[999.0, 1.0, 0.0]. - The
tspanvariable should be a tuple(0.0, 100.0). - The
pvariable should be a vector or tuple like[0.3, 0.1]. - The
probvariable must be anODEProblemconstructed with thesir_model!,u0,tspan, andpvariables in the correct order. - The comment for the phase space plot should state that you would use the
idxskeyword argument, specificallyplot(sol, idxs=(1, 2)), to plot the second state variable (Infected) against the first (Susceptible).