Bayesian Inference: Biochemical Oxygen Demand (BOD) Example
This example demonstrates Bayesian parameter estimation for a biochemical oxygen demand model using transport maps. The problem comes from environmental engineering and was originally presented in [13] and later used as a benchmark in transport map applications [3].
The model describes the evolution of biochemical oxygen demand (BOD) in a river system using an exponential growth model with two uncertain parameters controlling growth and decay rates.
using TransportMaps
using CairoMakie
using LaTeXStrings
using DistributionsThe Forward Model
The BOD model is given by:
where the parameters
The parameters
In order to describe the input parameters in an unbounded space, we transform them into a space with standard normal prior distributions
We define the forward model as a function of
function forward_model(t, θ)
A = 0.4 + (1.2 - 0.4) * cdf(Normal(), θ[1])
B = 0.01 + (0.31 - 0.01) * cdf(Normal(), θ[2])
return A * (1 - exp(-B * t))
endExperimental Data
We have BOD measurements at five time points:
t = [1, 2, 3, 4, 5]
D = [0.18, 0.32, 0.42, 0.49, 0.54]
σ = sqrt(1.0e-3)Let's visualize the data along with model predictions for different parameter values:
realizations_fig = Figure(size = (600, 650))
realizations_ax = Axis(realizations_fig[1, 1]; xlabel = L"Time $t$", ylabel = L"Biochemical Oxygen Demand $D$")
scatter!(realizations_ax, t, D; label = "Data", color = theme(:textcolor))
# Plot model output for some parameter values.
t_values = range(0, 5, length = 100)
for θ₁ in [-0.5, 0, 0.5]
for θ₂ in [-0.5, 0, 0.5]
lines!(
realizations_ax, t_values, [forward_model(ti, [θ₁, θ₂]) for ti in t_values];
label = L"(\theta_1 = %$θ₁,\; \theta_2 = %$θ₂)", linestyle = :dash
)
end
end
Legend(realizations_fig[2, 1], realizations_ax; orientation = :horizontal, nbanks = 5)Bayesian Inference Setup
We define the posterior distribution using a standard normal prior on both parameters and a Gaussian likelihood for the observations. In this likelihood,
function logposterior(θ)
# Calculate the likelihood
likelihood = sum([logpdf(Normal(forward_model(t[k], θ), σ), D[k]) for k in 1:5])
# Calculate the prior
prior = logpdf(Normal(), θ[1]) + logpdf(Normal(), θ[2])
return prior + likelihood
end
target = MapTargetDensity(x -> logposterior(x))MapTargetDensity(backend=ADTypes.AutoForwardDiff())Creating and Optimizing the Transport Map
We use a 2-dimensional polynomial transport map with degree 3 and Softplus rectifier:
M = PolynomialMap(2, 3, :normal, Softplus(), LinearizedHermiteBasis())PolynomialMap:
Dimensions: 2
Total coefficients: 14
Reference density: Distributions.Normal{Float64}(μ=0.0, σ=1.0)
Maximum degree: 3
Basis: LinearizedHermiteBasis
Rectifier: Softplus
Components:
Component 1: 4 basis functions
Component 2: 10 basis functions
Coefficients: min=0.0, max=0.0, mean=0.0Set up Gauss-Hermite quadrature for optimization:
quadrature = GaussHermiteWeights(3, M)TensorProductWeights:
Number of points: 81
Dimensions: 2
Knots: GaussHermiteKnots(0.0, 1.0)Optimize the map coefficients:
res = optimize!(M, target, quadrature)
println("Optimization result: ", res)Optimization result: * Status: success
* Candidate solution
Final objective value: -9.066855e+00
* Found with
Algorithm: L-BFGS
* Convergence measures
|x - x'| = 6.89e-09 ≰ 0.0e+00
|x - x'|/|x'| = 4.24e-09 ≰ 0.0e+00
|f(x) - f(x')| = 0.00e+00 ≤ 0.0e+00
|f(x) - f(x')|/|f(x')| = 0.00e+00 ≤ 0.0e+00
|g(x)| = 8.77e-08 ≰ 1.0e-08
* Work counters
Seconds run: 0 (vs limit Inf)
Iterations: 150
f(x) calls: 179
∇f(x) calls: 179
∇f(x)ᵀv calls: 0Generating Posterior Samples
Generate samples from the standard normal distribution and map them to the posterior:
samples_z = randn(1000, 2)1000×2 Matrix{Float64}:
0.808288 1.29539
-1.12207 -0.0401347
-1.10464 0.875608
-0.416993 0.585995
0.287588 -0.927587
0.229819 -0.414203
-0.421769 -0.0856216
-1.35559 -0.570313
0.0694591 -0.242781
-0.117323 -3.05756
⋮
-0.905438 -1.73076
1.84802 0.432257
-1.29846 0.183927
0.596723 1.55975
0.431956 1.60559
-0.797097 0.723346
-0.0625319 0.474741
-1.25053 -0.0100866
-0.34637 -1.01294Map the samples through our transport map:
mapped_samples = evaluate(M, samples_z)1000×2 Matrix{Float64}:
0.25002 0.562535
-0.303123 1.5101
-0.300447 1.84926
-0.171568 1.26648
0.0293041 0.57388
0.00921 0.674558
-0.17265 1.10626
-0.33675 1.44649
-0.042756 0.791002
-0.0968985 0.485108
⋮
-0.268057 0.99402
1.00811 -0.011117
-0.328884 1.68373
0.150949 0.744991
0.0830027 0.874751
-0.248911 1.57125
-0.081677 1.00283
-0.322111 1.58653
-0.155185 0.883277Quality Assessment
Compute the variance diagnostic to assess the quality of our approximation:
var_diag = variance_diagnostic(M, target, samples_z)
println("Variance Diagnostic: ", var_diag)Variance Diagnostic: 0.019056052503026548Visualization
Plot the mapped samples along with contours of the true posterior density:
θ₁ = range(-0.5, 1.5, length = 100)
θ₂ = range(-0.5, 3, length = 100)
posterior_values = [pdf(target, [θ₁, θ₂]) for θ₁ in θ₁, θ₂ in θ₂]
samples_fig, samples_ax, plt = sampleplot(
mapped_samples; color = (:steelblue, 0.5),
axis = (; xlabel = L"\theta_1", ylabel = L"\theta_2"),
)
contour!(samples_ax, θ₁, θ₂, posterior_values; colormap = :viridis)Finally, we can compute the pullback density to visualize how well our transport map approximates the posterior:
posterior_pullback = [pullback(M, [θ₁, θ₂]) for θ₁ in θ₁, θ₂ in θ₂]
pullback_fig = Figure(size = (600, 420))
pullback_ax = Axis(pullback_fig[1, 1]; xlabel = L"\theta_1", ylabel = L"\theta_2")
levels = 0.2:0.2:0.8
contour!(
pullback_ax, θ₁, θ₂, posterior_values ./ maximum(posterior_values);
levels, color = :steelblue, label = "Target"
)
contour!(
pullback_ax, θ₁, θ₂, posterior_pullback ./ maximum(posterior_pullback);
levels, color = :orange, linestyle = :dash, label = "Pullback"
)
axislegend(pullback_ax)We can also visually observe a good agreement between the true posterior and the TM approximation.
Conditional Density and Samples
We can compute conditional densities and generate conditional samples using the transport map. For a product reference, the first two components give [3, 5]:
To sample, invert the fixed
We can use the conditional_sample function to generate samples from the conditional distribution. We draw fresh standard-normal values for
θ₁ = 0.0
conditional_samples = conditional_sample(M, θ₁, randn(10_000))For a numerical reference conditional density, hold
θ_range = 0:0.01:2
conditional_normalizer = gaussquadrature(ξ -> pdf(target, [θ₁, ξ]), 1000, -10.0, 10.0)
reference_conditional(θ₂) = pdf(target, [θ₁, θ₂]) / conditional_normalizer
conditional_reference = reference_conditional.(θ_range)Evaluate the fitted conditional density for comparison:
conditional_mapped = conditional_density(M, θ_range, θ₁)Finally, we plot the results:
conditional_fig, conditional_ax, plt = hist(
conditional_samples; bins = 50, normalization = :pdf, color = (:steelblue, 0.5),
label = "Conditional Samples", axis = (; xlabel = L"\theta_2", ylabel = L"\pi(\theta_2 \mid \theta_1 = %$θ₁)"),
)
lines!(conditional_ax, θ_range, conditional_reference; linewidth = 2, color = :orange, label = "Numerical Reference PDF")
lines!(conditional_ax, θ_range, conditional_mapped; linewidth = 2, color = :seagreen, label = "TM Conditional PDF")
axislegend(conditional_ax)This page was generated using Literate.jl.