Boundary Value Problems (BVPs)

6 min read

Welcome back! πŸ‘‹ You’ve mastered Initial Value Problems (IVPs) where you tell the code: "Here is where I am, and here is how fast I'm moving. Tell me where I'll be in 10 seconds."

But what if you know where you start and where you need to end, but you don't know how to get there?

Imagine you are an architect designing a bridge. You know where the bridge starts (the left bank) and where it ends (the right bank). You can't just build from the left and hope it lands exactly on the right side. You have constraints at both boundaries.

This is a Boundary Value Problem (BVP). In this module, we will learn how to describe these constraints to Julia's DifferentialEquations.jl and solve them efficiently.


1. Initial Value Problems vs. Boundary Value Problems

The Definition

Before writing code, let's distinguish the two mathematically.

  • Initial Value Problem (IVP): You have a differential equation and the state of the system at the start time (t0t_0). The solver marches forward in time.
    • Analogy: Throwing a paper airplane. You control the angle and speed of the throw (initial conditions), and physics determines where it lands.
  • Boundary Value Problem (BVP): You have a differential equation, but the conditions are specified at different times (usually the boundaries, tstartt_{start} and tendt_{end}).
    • Analogy: Hanging a hammock. You attach one end to a tree (tstartt_{start}) and the other end to a pole (tendt_{end}). The shape of the hammock is determined by gravity and these two fixed points.

The Problem

Why can't we just use standard IVP solvers like Tsit5?
Because Tsit5 needs to know everything about the state at t=0t=0. In a BVP, you might know the position at t=0t=0 but not the velocity. If you don't know the velocity, Tsit5 cannot take the first step.

The Solution

We need solvers that view the problem globally rather than stepping blindly forward. We define a "Residual Function" that calculates the error at the boundaries, and the solver adjusts the solution until that error is zero.


2. Defining a BVPProblem and Setting Boundary Conditions

In DifferentialEquations.jl, setting up a BVP looks very similar to an ODE, with one major addition: The Boundary Condition Function.

Step 1: The ODE Function

This is identical to what you are used to. Let's model a simple Second Order Harmonic Oscillator: x¨+x=0\ddot{x} + x = 0.
We rewrite this as a system of two first-order equations:

  1. xΛ™=v\dot{x} = v
  2. vΛ™=βˆ’x\dot{v} = -x
julia
using DifferentialEquations, Plots

function harmonic_oscillator!(du, u, p, t)
    # u[1] is position (x)
    # u[2] is velocity (v)
    du[1] = u[2]
    du[2] = -u[1]
end

Step 2: The Boundary Condition (BC) Function

This is new! πŸ†•
Instead of giving u0 (initial state), we define a function that tells Julia what the conditions are at the start and end.

The signature is bc!(residual, ua, ub, p, t).

  • residual: An array where you store the error (must be 0 when solved).
  • ua: The state vector at time tstartt_{start}.
  • ub: The state vector at time tendt_{end}.

The Scenario: We want the particle to start at position 0 (x(0)=0x(0) = 0) and end at position 1 (x(Ο€/2)=1x(\pi/2) = 1).

julia
function bc1!(residual, ua, ub, p, t)
    # Condition 1: Position at start (ua[1]) must be 0
    # Math: ua[1] = 0  ->  Residual: ua[1] - 0
    residual[1] = ua[1] 

    # Condition 2: Position at end (ub[1]) must be 1
    # Math: ub[1] = 1  ->  Residual: ub[1] - 1
    residual[2] = ub[1] - 1.0
end

Note: If your system has 2 ODEs, you generally need 2 boundary conditions to find a unique solution.

Step 3: Constructing the BVPProblem

We use BVPProblem (not ODEProblem).

  • Initial Guess: BVPs are hard. Solvers usually need a "guess" of what the solution looks like to start iterating. We usually provide a constant array or a function as a guess.
julia
tspan = (0.0, Ο€/2)

# Initial guess: We guess the system stays at [0,0] the whole time.
# The solver will bend this guess to fit the physics and boundaries.
u0_guess = [0.0, 0.0] 

bvp_prob = BVPProblem(harmonic_oscillator!, bc1!, u0_guess, tspan)

3. Understanding the Solvers: Shooting Methods and Finite Differences

When solving IVPs, you default to Tsit5(). For BVPs, the defaults are different. There are two main industry-standard approaches.

Approach A: Shooting Method (Shooting)

Imagine you are playing Angry Birds. You want to hit a target. You pull the slingshot back (guess initial velocity), fire, see where it lands, and adjust your aim.

  1. The solver guesses the missing initial values.
  2. It runs a standard IVP solver (like Tsit5).
  3. It checks if the end state matches ub.
  4. If not, it uses Newton's method to adjust the guess and fires again.

When to use: Good for simple problems where you have a decent guess.
Downside: Can be unstable if the system is chaotic (the "Butterfly Effect" makes it hard to aim).

julia
# We tell it to use Shooting method, wrapping an IVP solver (Tsit5)
sol_shooting = solve(bvp_prob, Shooting(Tsit5()))

Approach B: Finite Differences / Collocation (MIRK4)

Instead of shooting from one side, imagine laying a chain on the ground and tweaking the whole chain at once until it satisfies the equation and the endpoints.

It discretizes the time into a grid (mesh) and solves a massive system of algebraic equations simultaneously.

When to use: Industry Standard. It is generally more robust and stable than shooting methods for stiff or sensitive problems.
The Solver: MIRK4 (Mono-Implicit Runge-Kutta order 4).

julia
# This is usually the preferred method for general BVPs
sol_mirk = solve(bvp_prob, MIRK4())

πŸ’‘ Fun Fact: "MIRK" sounds like a generic sci-fi villain name, but it actually stands for Mono-Implicit Runge-Kutta. It's extremely efficient for these specific boundary problems.


4. Extracting and Analyzing Solutions

The solution object sol behaves almost exactly like an IVP solution.

Interpolation

Just like with ODEs, the solution comes with free interpolation. You can ask for the state at any time t.

julia
# What is the state at t = 0.5?
state_at_05 = sol_mirk(0.5)
println("Position at t=0.5: ", state_at_05[1])

Visualization

Plotting works out of the box.

julia
plot(sol_mirk, title="Harmonic Oscillator BVP", label=["Position (x)" "Velocity (v)"])

Checking Convergence

BVPs are finicky. Sometimes they don't converge (e.g., if you ask a bridge to be 10km long but only give it 1kg of steel). Always check the return code.

julia
if sol_mirk.retcode == :Success
    println("Solution found! πŸŽ‰")
else
    println("Solver failed. Try a better initial guess or a different solver.")
end

Summary of Workflow

  1. Define ODE function f(du, u, p, t).
  2. Define Boundary function bc!(res, ua, ub, p, t).
  3. Provide u0 (initial guess).
  4. Create BVPProblem.
  5. Solve using MIRK4() (recommended) or Shooting().

πŸ“š References & Resources

Challenge

You are tasked with solving a classic boundary value problem: determining the trajectory of a projectile.

A projectile is fired from the ground at time t=0 and is subject only to the force of gravity (g = 9.81 m/sΒ²). The governing equation is y''(t) = -g, where y(t) is the vertical position.

Your goal is to find the required initial velocity y'(0) such that the projectile reaches a height of 50 meters at exactly t=10 seconds.

Your Tasks:

  1. Represent the second-order ODE y''(t) = -g as a system of two first-order ODEs. Use u[1] for the position y(t) and u[2] for the velocity y'(t).
  2. Implement the ODE function projectile_ode!.
  3. Implement the boundary condition function projectile_bc!. The boundary conditions are:
    • y(0) = 0 (starts at ground level)
    • y(10) = 50 (reaches the target height at the final time)
  4. Provide an initial guess for the solution vector u. A simple constant vector like [0.0, 0.0] will suffice.
  5. Construct the BVPProblem using your defined functions, initial guess, and the provided tspan.
  6. Solve the problem using the robust MIRK4() collocation method.

Expected result

Your final code should correctly set up and solve the boundary value problem. The submitted code must contain the following completed components:

  1. projectile_ode! function:

    julia
    function projectile_ode!(du, u, p, t)
        du[1] = u[2]
        du[2] = -g
    end
  2. projectile_bc! function:

    julia
    function projectile_bc!(residual, u, p, t)
        residual[1] = u[1][1] - 0.0
        residual[2] = u[end][1] - y_final
    end
  3. u0_guess: An initial guess for the two states (position and velocity).

    julia
    u0_guess = [0.0, 0.0]
  4. BVPProblem constructor:

    julia
    bvp = BVPProblem(projectile_ode!, projectile_bc!, u0_guess, tspan)
  5. solve call:

    julia
    sol = solve(bvp, MIRK4())
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.