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 u(t)u(t), we track a vector of variables u(t)\mathbf{u}(t).

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 (xx) and Foxes (yy) simultaneously, we can't use two separate ODEProblems because xx depends on yy and vice-versa.

The Solution:
We group all our dependent variables into a single array (or vector), usually called u.

  • u[1]u[1] represents xx (Rabbits)
  • u[2]u[2] represents yy (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.

julia
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.

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

  1. Prey (xx): They breed naturally (αx\alpha x) but get eaten by predators (−βxy-\beta x y).
  2. Predators (yy): They starve naturally (−γy-\gamma y) but grow when they eat prey (+δxy+\delta x y).

The Equations:

dxdt=αx−βxy\frac{dx}{dt} = \alpha x - \beta x ydydt=δxy−γy\frac{dy}{dt} = \delta x y - \gamma y

The Code:
Let's map this to our u vector:

  • u[1] = Prey (xx)
  • u[2] = Predator (yy)
julia
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:

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

  1. Optimization: You can ask libraries to "find the p that makes the model match my real-world data."
  2. Sensitivity Analysis: You can easily check "Does changing α by 1% drastically change the result?"
  3. 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.

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

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:

  1. Define an in-place function named sir_model! that calculates the derivatives for the SIR system. The function must have the standard signature sir_model!(du, u, p, t).

    The SIR model is described by the following equations:

    • dS/dt = -β * S * I / N
    • dI/dt = β * S * I / N - γ * I
    • dR/dt = γ * I

    Where:

    • The state vector u is [S, I, R] (Susceptible, Infected, Recovered).
    • The parameter vector p is [β, γ] (infection rate, recovery rate).
    • N is the total population, which is the sum of S, I, and R.
  2. 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 from t=0.0 to t=100.0.
    • Parameters (p): Use an infection rate β of 0.3 and a recovery rate γ of 0.1.
  3. Construct the ODEProblem using your function and the defined conditions.

  4. After the ODEProblem is 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 named sol.

Expected result

Your final code should correctly define the sir_model! function, the problem's conditions, and the ODEProblem itself.

Specifically:

  1. The sir_model! function must correctly calculate the three derivatives based on the provided equations and update the du vector elements du[1], du[2], and du[3] directly. It should not have a return statement.
  2. The u0 variable should be a vector like [999.0, 1.0, 0.0].
  3. The tspan variable should be a tuple (0.0, 100.0).
  4. The p variable should be a vector or tuple like [0.3, 0.1].
  5. The prob variable must be an ODEProblem constructed with the sir_model!, u0, tspan, and p variables in the correct order.
  6. The comment for the phase space plot should state that you would use the idxs keyword argument, specifically plot(sol, idxs=(1, 2)), to plot the second state variable (Infected) against the first (Susceptible).
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.