# Bayesian Inference on a Pendulum using Turing.jl

### Set up simple pendulum problem

using DiffEqBayes, OrdinaryDiffEq, RecursiveArrayTools, Distributions, Plots, StatsPlots


Let's define our simple pendulum problem. Here our pendulum has a drag term ω and a length L. We get first order equations by defining the first term as the velocity and the second term as the position, getting:

function pendulum(du,u,p,t)
ω,L = p
x,y = u
du = y
du = - ω*y -(9.8/L)*sin(x)
end

u0 = [1.0,0.1]
tspan = (0.0,10.0)
prob1 = ODEProblem(pendulum,u0,tspan,[1.0,2.5])

ODEProblem with uType Array{Float64,1} and tType Float64. In-place: true
timespan: (0.0, 10.0)
u0: [1.0, 0.1]


### Solve the model and plot

To understand the model and generate data, let's solve and visualize the solution with the known parameters:

sol = solve(prob1,Tsit5())
plot(sol) It's the pendulum, so you know what it looks like. It's periodic, but since we have not made a small angle assumption it's not exactly sin or cos. Because the true dampening parameter ω is 1, the solution does not decay over time, nor does it increase. The length L determines the period.

### Create some dummy data to use for estimation

We now generate some dummy data to use for estimation

t = collect(range(1,stop=10,length=10))
randomized = VectorOfArray([(sol(t[i]) + .01randn(2)) for i in 1:length(t)])
data = convert(Array,randomized)

2×10 Array{Float64,2}:
0.0897692  -0.384041  0.127196  …  -0.010888   0.00915108  0.00419951
-1.21799     0.345539  0.317598     -0.0182295  0.0326702   0.00312608


Let's see what our data looks like on top of the real solution

scatter!(data') This data captures the non-dampening effect and the true period, making it perfect to attempting a Bayesian inference.

### Perform Bayesian Estimation

Now let's fit the pendulum to the data. Since we know our model is correct, this should give us back the parameters that we used to generate the data! Define priors on our parameters. In this case, let's assume we don't have much information, but have a prior belief that ω is between 0.1 and 3.0, while the length of the pendulum L is probably around 3.0:

priors = [Uniform(0.1,3.0), Normal(3.0,1.0)]

2-element Array{Distributions.Distribution{Distributions.Univariate,Distrib
utions.Continuous},1}:
Distributions.Uniform{Float64}(a=0.1, b=3.0)
Distributions.Normal{Float64}(μ=3.0, σ=1.0)


Finally let's run the estimation routine from DiffEqBayes.jl using the Turing.jl backend

bayesian_result = turing_inference(prob1,Tsit5(),t,data,priors;num_samples=10_000,
syms = [:omega,:L])

Object of type Chains, with data of type 9000×15×1 Array{Union{Missing, Rea
l},3}

Iterations        = 1:9000
Thinning interval = 1
Chains            = 1
Samples per chain = 9000
internals         = acceptance_rate, hamiltonian_energy, hamiltonian_energy
_error, is_accept, log_density, lp, max_hamiltonian_energy_error, n_steps,
nom_step_size, numerical_error, step_size, tree_depth
parameters        = L, omega, σ1

2-element Array{MCMCChains.ChainDataFrame,1}

Summary Statistics
. Omitted printing of 2 columns
│ Row │ parameters │ mean     │ std       │ naive_se    │ mcse        │
│     │ Symbol     │ Float64  │ Float64   │ Float64     │ Float64     │
├─────┼────────────┼──────────┼───────────┼─────────────┼─────────────┤
│ 1   │ L          │ 2.52287  │ 0.212534  │ 0.0022403   │ 0.0033968   │
│ 2   │ omega      │ 1.06778  │ 0.21067   │ 0.00222066  │ 0.00440209  │
│ 3   │ σ1         │ 0.159801 │ 0.0381733 │ 0.000402382 │ 0.000557789 │

Quantiles

│ Row │ parameters │ 2.5%     │ 25.0%    │ 50.0%    │ 75.0%    │ 97.5%    │
│     │ Symbol     │ Float64  │ Float64  │ Float64  │ Float64  │ Float64  │
├─────┼────────────┼──────────┼──────────┼──────────┼──────────┼──────────┤
│ 1   │ L          │ 2.10001  │ 2.39511  │ 2.51869  │ 2.64803  │ 2.95861  │
│ 2   │ omega      │ 0.760319 │ 0.929671 │ 1.03743  │ 1.1611   │ 1.56466  │
│ 3   │ σ1         │ 0.103615 │ 0.132854 │ 0.154144 │ 0.180043 │ 0.249208 │


Notice that while our guesses had the wrong means, the learned parameters converged to the correct means, meaning that it learned good posterior distributions for the parameters. To look at these posterior distributions on the parameters, we can examine the chains:

plot(bayesian_result) As a diagnostic, we will also check the parameter chains. The chain is the MCMC sampling process. The chain should explore parameter space and converge reasonably well, and we should be taking a lot of samples after it converges (it is these samples that form the posterior distribution!)

plot(bayesian_result, colordim = :parameter)