Parameter Estimation and Inverse Problems

8 min read

1. Introduction to Data Fitting in the SciML Ecosystem

The Concept:
In previous sections, we solved the Forward Problem: you have a model (physics/math rules) and parameters (constants), and you calculate the outcome.

Parameter Estimation is the Inverse Problem: you have the outcome (real-world data) and the model structure, but you don't know the parameters. You have to work backward to find the constants that make your model match reality.

The Problem:
Imagine you are a detective arriving at a crime scene (the data). You know the laws of physics (the ODE model), but you don't know exactly how hard the villain threw the vase (the parameter). You have to simulate different throwing speeds until one matches the shatter pattern on the floor.

In the industry, this is everywhere:

  • Pharmacology: You know how a drug generally decays (Exponential), but you don't know the patient's specific metabolic rate.
  • Battery Management: You know the circuit equivalent model, but you need to estimate the internal resistance in real-time.

The Solution:
The SciML (Scientific Machine Learning) ecosystem in Julia treats the differential equation solver as just another mathematical function. Because the solver is written in pure Julia, it is differentiable. This means we can use gradient-based optimization to "tune" our parameters automatically.


2. Creating a Custom Loss Function around solve

Before we can optimize, we need a way to score how "bad" our current guess is. This is called a Loss Function (or Cost Function).

The Concept:
A loss function takes a set of parameters, runs the simulation, compares the simulation to the data, and returns a single number (scalar). The lower the number, the better the fit.

The Problem:
Computers don't understand "looks close enough." They need a math equation to minimize.

The Solution:
We typically use the L2 Loss (Sum of Squared Errors). We square the difference between the prediction and the data so that negative and positive errors don't cancel each other out.

🧪 Hands-On: Setting up the Scenario

Let's imagine a chemical reaction where substance A turns into substance B.
Model: dAdt=−kA\frac{dA}{dt} = -k A
True parameter k=1.5k = 1.5. We will generate "fake data" first so we know the answer, then try to find it back.

julia
using DifferentialEquations, Plots

# 1. Define the Dynamics (The Forward Model)
# u[1] is the concentration of A
function reaction!(du, u, p, t)
    k = p[1]
    du[1] = -k * u[1]
end

u0 = [1.0]      # Initial concentration
tspan = (0.0, 3.0)
p_true = [1.5]  # The secret number we want to find

# 2. Generate "Synthetic Data" (The Truth)
prob = ODEProblem(reaction!, u0, tspan, p_true)
sol_true = solve(prob, Tsit5(), saveat=0.1)

# Extract data to arrays (Imagine this came from an Excel sheet)
t_data = sol_true.t
data_values = Array(sol_true)[1, :] # Keep only the first variable

# Add some noise because real life is messy 📉
data_values_noisy = data_values + 0.05 * randn(length(data_values))

scatter(t_data, data_values_noisy, label="Noisy Data", title="Lab Results", xlabel="Time", ylabel="Concentration")

🛠️ Building the Cost Function

Now, we write a function that takes a guess for kk and returns the error.

Industry Standard Alert:
When fitting data, always use the saveat keyword in solve. If your data was recorded at t=1.0t=1.0 and t=2.0t=2.0, your solver must output values exactly at those times for comparison. Do not rely on interpolation if you can avoid it; forcing steps or saving at points is more robust.

julia
# The Loss Function
function loss_function(p_guess)
    # 1. Remake the problem with the new parameter guess
    # 'remake' is safer than creating a new ODEProblem every time
    new_prob = remake(prob, p=p_guess)
    
    # 2. Solve the ODE
    # We use saveat=t_data so the solution points align with our data points
    prediction = solve(new_prob, Tsit5(), saveat=t_data, verbose=false)
    
    # 3. Handle solver failures
    # Sometimes the optimizer guesses a parameter that causes the ODE to blow up.
    # We return infinity so the optimizer runs away from this spot.
    if prediction.retcode != :Success
        return Inf
    end
    
    # 4. Calculate Sum of Squared Error
    # prediction[1, :] gets the first variable (Concentration A)
    predicted_values = prediction[1, :]
    loss = sum(abs2, predicted_values .- data_values_noisy)
    
    return loss
end

# Test it with a bad guess
println("Loss with k=0.5: ", loss_function([0.5])) 
# Test it with a good guess
println("Loss with k=1.5: ", loss_function([1.5])) 

Note: We check retcode. In industry models, parameters can sometimes become negative physically (like negative friction), causing the solver to crash. Always handle failures gracefully in your loss function!


3. Using Optim.jl for Local Optimization of Parameters

The Concept:
Local Optimization is like walking down a misty mountain. You look at the ground, find the steepest slope downward, and take a step. You repeat this until the ground is flat (you are at the bottom).

The Problem:
We have a loss_function, but manually plugging in numbers (Guess 1... Guess 2...) takes forever.

The Solution:
We use Optim.jl. It contains algorithms like BFGS (Broyden–Fletcher–Goldfarb–Shanno). BFGS is the workhorse of parameter estimation. It uses derivatives to find the bottom of the valley very quickly.

💻 Implementation

julia
using Optim

# 1. Define an initial guess (The starting point on the mountain)
p_guess = [0.5] # Way off from our true 1.5

# 2. Run the optimizer
# We pass the function, the start guess, and the algorithm (BFGS)
result = Optim.optimize(loss_function, p_guess, BFGS())

# 3. Extract the results
p_estimated = Optim.minimizer(result)
println("The estimated parameter k is: ", p_estimated[1])
println("The true parameter k was: ", p_true[1])

Visualizing the Result:
Always verify visually. A low loss score might still look weird if your model is fundamentally wrong.

julia
# Plot the fit
final_prob = remake(prob, p=p_estimated)
final_sol = solve(final_prob, Tsit5(), saveat=0.1)

scatter(t_data, data_values_noisy, label="Data")
plot!(final_sol, label="Fitted Model", linewidth=3)

Fun Fact: BFGS is so effective that for many "smooth" problems, it converges quadratically. That means once it gets close, the number of accurate digits roughly doubles with every step. It's the "homing missile" of optimization.


4. Ensuring Automatic Differentiation Compatibility for Gradients

The Concept:
Optimization algorithms like BFGS need to know the Gradient (the slope). They need to know: "If I increase kk by 0.0001, does the error go up or down?"

The Problem:
There are two ways to get this slope:

  1. Finite Differences: Calculate loss(k), then loss(k+0.001), subtract them, and divide. This is slow and prone to rounding errors.
  2. Automatic Differentiation (AD): The compiler looks at your code and mathematically proves the derivative. It's exact and fast.

The Catch:
DifferentialEquations.jl is AD-compatible, but only if you write your code carefully. The most common error in SciML is Type Instability.

If you define u0 = [1.0] (Float64), and an AD library like ForwardDiff tries to pass a Dual number (a special number type that carries derivative info), your code might crash if you forced types to be Float64.

The Solution:

  1. Avoid ::Float64 annotations in your ODE functions. Use generic types or ::Real.
  2. Use remake.
  3. Let Optim use ForwardDiff.

🚀 Making it AD-Ready

To make Optim use Automatic Differentiation (autodiff), we just flip a switch. Optim.jl handles the heavy lifting, provided your ODE function is generic.

julia
# Notice we rely on autodiff=:forward
# This tells Optim: "Don't poke the function to find the slope. 
# Use ForwardDiff.jl to calculate the exact gradient through the ODE solver."

result_ad = Optim.optimize(loss_function, p_guess, BFGS(), 
                           autodiff = :forward)

println("Estimated with AD: ", Optim.minimizer(result_ad)[1])

Under the Hood (What just happened?):
When you set autodiff = :forward, Julia actually passed a strange number type looks like 0.5 + 1ε into your ODE solver.

  1. It ran the entire ODE solver using these "Dual numbers".
  2. It calculated the loss using "Dual numbers".
  3. The final result returned LossValue + GradientValue * ε.

This is a superpower of Julia. In other languages, you often have to write a separate "adjoint" equation manually to get gradients. Here, the language does it for you.

🚧 Common Pitfall: The "Buffer" Array

If you use intermediate arrays in your ODE function, you must be careful.

Bad Practice:

julia
function bad_physics(du, u, p, t)
    temp = zeros(Float64, 2) # ❌ ERROR! Forces Float64, kills AD.
    temp[1] = u[1] * p[1]
    du[1] = -temp[1]
end

Good Practice (Industry Standard):

julia
function good_physics(du, u, p, t)
    # eltype(u) asks: "What type of number is u holding?" 
    # If u holds Dual numbers, temp will hold Dual numbers.
    temp = zeros(eltype(u), 2) 
    temp[1] = u[1] * p[1]
    du[1] = -temp[1]
end

Summary

  1. Define Model: Write your ODE.
  2. Loss Function: remake the problem with new parameters, solve with saveat, calculate squared error.
  3. Optimize: Use Optim.optimize with BFGS().
  4. AD Compatibility: Keep types generic inside the ODE function so ForwardDiff can work its magic.

🔗 References & Further Reading

Challenge

You are tasked with fitting a Lotka-Volterra predator-prey model to a set of observed data. The complete setup, including the ODE function, the ODEProblem, and the dataset, is provided.

Your goal is to implement the loss(p) function. This function is crucial for the optimization process as it quantifies how well a given set of parameters p makes the model's output match the observed data.

Requirements:

  1. The function must accept a single argument, p, which is a vector of the parameters being tested ([α, β, γ, δ]).
  2. Inside the function, create a new version of the ODEProblem using the remake function, passing in the new parameters p via the p keyword argument.
  3. Solve the new problem using solve(). Crucially, you must ensure the solution is only saved at the time points where data is available. Use the saveat keyword argument with the provided t_points for this.
  4. The ODE solver might fail for certain parameter values. Add a check for the solution's retcode. If it is not equal to :Success, the loss function must immediately return Inf.
  5. If the solution is successful, calculate the L2 Loss (also known as the sum of squared errors). This is the sum of the squared differences between the data and the solver's output (sol). Return this scalar value.

Expected result

Your completed code should feature a fully implemented loss function that follows all the specified requirements. The function will correctly remake the ODE problem with new parameters, solve it efficiently using saveat, handle potential solver failures by checking the retcode, and finally compute and return the L2 loss.

A correct implementation would look like this:

julia
function loss(p)
    # 1. Remake the problem with new parameters
    prob_new = remake(prob, p = p)

    # 2. Solve the problem, saving only at data points
    #    Use a simple algorithm like Tsit5() and suppress verbose output
    sol = solve(prob_new, Tsit5(), saveat = t_points, verbose=false)

    # 3. Handle solver failures
    if sol.retcode != :Success
        return Inf
    end

    # 4. Calculate and return the L2 loss
    return sum(abs2, data .- sol)
end
julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.