Differential-Algebraic Equations (DAEs)

7 min read

Welcome back! 🧪 Today, we are stepping out of the comfortable world where everything moves smoothly and entering the gritty reality of Differential-Algebraic Equations (DAEs).

If standard Ordinary Differential Equations (ODEs) are like driving a car (you press the gas, velocity changes), DAEs are like driving a car that is chained to a wall. You can press the gas all you want, but the chain (the algebraic constraint) says, "You aren't going anywhere past 5 meters."

In industry—from robotics to electrical grids—systems rarely move freely. They are constrained by conservation laws, mechanical linkages, or Kirchhoff's laws.

Let's learn how to simulate these constrained realities in Julia.


1. What is a DAE? Introducing Algebraic Constraints to Dynamics

The Problem

In a standard ODE, we usually look at a system like this:

dudt=f(u,t)\frac{du}{dt} = f(u, t)

This says: "The change in my state depends on my current state." Every variable has a derivative.

However, in the real world, some variables don't have derivatives. They just exist to balance the equation.

Imagine a Pendulum.

  1. Differential part: Gravity accelerates the bob (change in velocity).
  2. Algebraic part: The rod is rigid. The distance from the pivot to the bob must remain constant.

If you try to model a pendulum using only xx and yy coordinates without enforcing the rod length, the bob might drift away due to numerical error. You need an equation that acts as a strict rule.

The Solution: DAEs

A DAE is written in the fully implicit form:

F(dudt,u,t)=0F(\frac{du}{dt}, u, t) = 0

Here, uu contains both your dynamic variables (like position) and your algebraic variables (like tension in the rod or voltage at a node).

💡 Fun Fact: If you accidentally violate an algebraic constraint in a simulation, it's called "drift." In simulation terms, your rigid steel rod just became a rubber band. That’s bad engineering.

Key Concept: The "Index"

We won't go deep into math theory, but you need to know this term. The Index is a measure of how "hard" the DAE is to solve.

  • Index 0: Just a standard ODE.
  • Index 1: Standard DAEs (most engineering problems).
  • Index 2+: High-Index DAEs. These are nightmares. Avoid them or reduce them mathematically if possible.

We will focus on Index-1 DAEs, which are the industry standard for chemical kinetics and electrical circuits.


2. Using Mass Matrices to Constrain standard ODEProblems

Before we jump into the heavy machinery of DAEProblem, there is a "cheat code" in DifferentialEquations.jl widely used in industry: The Mass Matrix.

The Concept

A linear implicit ODE looks like this:

M⋅dudt=f(u,p,t)M \cdot \frac{du}{dt} = f(u, p, t)

If MM (the mass matrix) is the identity matrix (1s on the diagonal), this is a normal ODE.
However, if we set some rows of the mass matrix to Zero, the equation for that row becomes:

0⋅duidt=fi(u,p,t)  ⟹  0=fi(u,p,t)0 \cdot \frac{du_i}{dt} = f_i(u, p, t) \implies 0 = f_i(u, p, t)

Boom! You just turned a differential equation into an algebraic equation.

Industry Scenario: Chemical Reaction (Robertson)

Three chemicals react. y1y_1 turns into y2y_2, which turns into y3y_3.
But, mass must be conserved: y1+y2+y3=1y_1 + y_2 + y_3 = 1.

Instead of calculating y3′y_3' (derivative), we just force y3y_3 to be whatever is left over.

Hands-on Code

julia
using DifferentialEquations, LinearAlgebra

# 1. Define the system
function robertson_f(du, u, p, t)
  y1, y2, y3 = u
  k1, k2, k3 = p
  
  # Differential parts (standard chemical kinetics)
  du[1] = -k1*y1 + k3*y2*y3
  du[2] =  k1*y1 - k3*y2*y3 - k2*y2^2
  
  # Algebraic part: The sum must equal 1 (Conservation of Mass)
  # This implies: y1 + y2 + y3 - 1 = 0
  du[3] =  y1 + y2 + y3 - 1
end

# 2. Define the Mass Matrix
# 1s on diagonal imply differential variables.
# 0 on diagonal implies algebraic variable.
M = [1.0 0.0 0.0
     0.0 1.0 0.0
     0.0 0.0 0.0] # <--- The magic row. No derivative for y3.

# 3. Create the Function with the Mass Matrix
f = ODEFunction(robertson_f, mass_matrix=M)

# 4. Set up problem
u0 = [1.0, 0.0, 0.0]
tspan = (0.0, 1e5)
p = [0.04, 3e7, 1e4]

# 5. Solve using a solver that supports Mass Matrices
# Rodas5P is excellent for Stiff ODEs and DAEs.
prob = ODEProblem(f, u0, tspan, p)
sol = solve(prob, Rodas5P())

using Plots
plot(sol, xscale=:log10, layout=(3,1), label=["y1" "y2" "y3"])

Why do this?
It is often much faster and more stable than a fully implicit solver. If your constraint can be written as 0=…0 = \dots, use a Mass Matrix.


3. Defining a Fully Implicit DAEProblem

Sometimes, you cannot separate your variables easily. You have a complex mess where derivatives and variables are tangled inside a function.

F(u˙,u,p,t)=0F(\dot{u}, u, p, t) = 0

For this, we use the DAEProblem.

The Scenario

Imagine a simple control system or an electrical circuit loop where the relationship is implicit.
Let's model a simple implicit system:

  1. dxdt+x+y=0\frac{dx}{dt} + x + y = 0
  2. x+y=1x + y = 1 (Algebraic Constraint)

Hands-on Code

julia
# The signature is DIFFERENT from ODEs.
# It takes (out, du, u, p, t)
# out: The "residual". The solver tries to make this Zero.
# du: derivative estimate
# u:  current state

function implicit_system(out, du, u, p, t)
    x, y = u
    dx, dy = du # The solver proposes these derivatives

    # Equation 1: dx + x + y = 0
    out[1] = dx + x + y
    
    # Equation 2: x + y - 1 = 0
    # Note: This equation does not depend on dy (derivatives)!
    out[2] = x + y - 1
end

# Initial guess for derivatives (du0) and state (u0)
u0 = [0.5, 0.5]  # x=0.5, y=0.5 (Notice 0.5 + 0.5 = 1, so it fits Eq 2)
du0 = [-1.0, 0.0] # dx = -(x+y) = -1. 

tspan = (0.0, 10.0)

# We must tell Julia which variables are differential
# var 1 (x) is differential? true
# var 2 (y) is differential? false (it's algebraic)
differential_vars = [true, false]

prob = DAEProblem(implicit_system, du0, u0, tspan, differential_vars=differential_vars)

# DFBDF is a solid native Julia solver for DAEs
sol = solve(prob, DFBDF())

plot(sol)

⚠️ Important: notice out. You are not returning the derivative. You are calculating the error. The solver guesses a du and u, plugs them in, and checks if out is zero. If not, it tries again.


4. Initializing DAEs: The Importance of Consistent Initial Conditions

Here is the biggest headache in DAEs.

In an ODE, if I say "The car is at position 0," that's fine.
In a DAE, if I say "The car is at position 0, and the chain length is 5 meters, and the wall is at position 10"... Physics breaks.

If your u0 (initial state) and du0 (initial derivative) do not perfectly satisfy your algebraic equations (F(du0,u0,t0)=0F(du_0, u_0, t_0) = 0), the solver will crash immediately.

The Problem

You usually know your states (uu), but you might not know the derivatives (dudu) that balance the forces at time t=0t=0.

The Solution: Initialization Helpers

When you define differential_vars, DifferentialEquations.jl attempts to adjust your initial conditions to make them consistent before starting the simulation.

Imagine you set up the previous example with bad initial values:

julia
# BAD INITIALIZATION
u0_bad = [0.8, 0.8] # 0.8 + 0.8 = 1.6 ... NOT 1.0! Equation 2 violated.
du0_guess = [0.0, 0.0]

prob_bad = DAEProblem(implicit_system, du0_guess, u0_bad, tspan, differential_vars=[true, false])

# When you run solve(), Julia runs an initialization algorithm 
# (like BrownFullBasicInit) to find the "closest" valid u0 and du0.
sol = solve(prob_bad, DFBDF())

# Check what the solver actually used:
println("Fixed u0: ", sol[1]) 

Industry Practice:

  1. BrownFullBasicInit: The default. Adjusts algebraic variables and derivatives to satisfy constraints.
  2. ShampineCollocationInit: Used when the default fails for high-index problems.

To enforce specific initialization logic, you pass it to solve:

julia
solve(prob, DFBDF(), initializealg = BrownFullBasicInit())

🔥 Pro Tip: If your DAE solver fails at t=0 or dt < dtmin, 99% of the time your Initial Conditions are inconsistent. Trust the differential_vars array; it tells the optimizer which variables it is allowed to tweak to satisfy the constraints.


Summary

  1. DAEs mix movement (derivatives) with strict rules (algebraic constraints).
  2. Mass Matrix (M) is the preferred way to solve DAEs if constraints are explicit (0=…0 = \dots). Use ODEFunction(f, mass_matrix=M).
  3. DAEProblem is for fully implicit systems (F(du,u,t)=0F(du, u, t) = 0).
  4. Consistency is Key: You cannot pick arbitrary start points. The initial state must satisfy the algebraic constraints, or the solver will reject it.

References

Challenge

Challenge: Modeling a Pendulum with a DAEProblem

Your task is to define a fully implicit Differential-Algebraic Equation (DAE) system for a simple pendulum using Julia's DifferentialEquations.jl conventions.

System Description:

A point mass m is attached to a rigid, massless rod of length L. The system is subject to gravity g acting in the negative y-direction.

State Vector:

The state of the system is described by the vector u:
u = [x, y, vx, vy, T]
where:

  • x, y: The Cartesian coordinates of the mass.
  • vx, vy: The velocity components of the mass.
  • T: The tension in the rod (an algebraic variable).

Governing Equations:

The system's dynamics and constraints are defined by the following five equations:

  1. dx/dt = vx
  2. dy/dt = vy
  3. m * d(vx)/dt = -T * (x/L)
  4. m * d(vy)/dt = -T * (y/L) - m*g
  5. x² + y² - L² = 0 (The algebraic constraint for the rod length)

Your Tasks:

  1. Complete the Julia function pendulum_dae!(out, du, u, p, t). This function must calculate the residual for each of the five governing equations and store the results in the out array. The solver works to drive these residuals to zero, so you must rearrange each equation into the form f(...) = 0.
  2. Define the differential_vars boolean vector. This vector must correctly specify which elements of the state vector u are differential variables (have a corresponding derivative du) and which are algebraic.

Expected result

1. The pendulum_dae! function

The function should implement the five governing equations in residual form, rearranged to equal zero. The order must match the state vector definition.

julia
function pendulum_dae!(out, du, u, p, t)
    m, L, g = p
    x, y, vx, vy, T = u
    dx, dy, dvx, dvy, dT = du

    # Equation 1: dx/dt - vx = 0
    out[1] = dx - vx
    # Equation 2: dy/dt - vy = 0
    out[2] = dy - vy
    # Equation 3: m*dvx/dt + T*x/L = 0
    out[3] = m*dvx + T*x/L
    # Equation 4: m*dvy/dt + T*y/L + m*g = 0
    out[4] = m*dvy + T*y/L + m*g
    # Equation 5: x^2 + y^2 - L^2 = 0
    out[5] = x^2 + y^2 - L^2
end

2. The differential_vars Vector

The differential_vars vector indicates which state variables have derivatives that appear in the system equations.

  • x, y, vx, and vy are differential variables because their derivatives (dx/dt, dy/dt, dvx/dt, dvy/dt) are part of the model.
  • T (tension) is an algebraic variable. It is determined by the constraint, and its derivative dT/dt does not appear anywhere in the equations.

Therefore, the correct boolean vector is:

julia
differential_vars = [true, true, true, true, false]
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.