-
Hi everyone, thanks for Gen.jl! I've been having fun with it. I've been trying to get my head around the SMC example, and applying it to my problem. Can anyone give any pointers? Code using Metropolis Hastings is below; you can also find a hand-coded particle filter here for reference. using OrdinaryDiffEq
using SciMLSensitivity
using Distributions
using Gen
using GenDistributions
# Define the Gen model
@gen function bayes_sir_markov(l::Int=40,
N::Int=1000,
c::Float64=10.0,
γ::Float64=0.25,
δt::Float64=1.0)
i₀ ~ uniform_discrete(1, 100)
β ~ uniform(0.01, 0.1)
S = N - i₀
I = i₀
for i in 1:l
ifrac = 1-exp(-β*c*I/N*δt)
rfrac = 1-exp(-γ*δt)
infection = {(:y, i)} ~ binom(S,ifrac)
recovery = {(:z, i)} ~ binom(I,rfrac)
S = S-infection
I = I+infection-recovery
end
nothing
end
# Set the true parameters and solve the model
p = Gen.choicemap()
p[:β] = 0.05
p[:i₀] = 10
l = 40
(sol, _) = Gen.generate(bayes_sir_markov, (l,), p)
# Generate observations
Y = [sol[(:y, i)] for i=1:l]
observations = Gen.choicemap()
for (i, y) in enumerate(Y)
observations[(:y, i)] = y
end
## Metropolis-Hastings
const truncated_normal = DistributionsBacked((mu,std,lb,ub) -> Distributions.Truncated(Normal(mu, std), lb, ub),
(true,true,false,false),
true,
Float64)
@gen function sir_proposal(current_trace)
β ~ truncated_normal(current_trace[:β], 0.01, 0.0, Inf)
i₀ ~ uniform_discrete(current_trace[:i₀]-1, current_trace[:i₀]+1)
end
n_iter = 110000
burnin = 10000
thin = 10
β_mh = Vector{Real}(undef, (n_iter - burnin) ÷ thin)
i₀_mh = Vector{Int}(undef, (n_iter - burnin) ÷ thin)
(tr,) = Gen.generate(bayes_sir_markov, (l,), merge(observations, p))
for i in 1:n_iter
(tr, _) = Gen.mh(tr, sir_proposal, ())
if i <= burnin
continue
end
if i % thin == 0
β_mh[(i - burnin) ÷ thin] = tr[:β]
i₀_mh[(i - burnin) ÷ thin] = tr[:i₀]
end
end
# Posterior mean estimates
mean(β_mh) # cf 0.05
mean(i₀_mh) # cf 10 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 15 replies
-
Do you already have a partial implementation of SMC for this model? In addition to what's in the docs and the Gen tutorial on particle filtering, you might be interested in using this SMC extension package for Gen called GenParticleFilters.jl -- there's an example in the README for that package that is pretty similar to your hand-coded particle filter. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the tips @ztangent! I guess my main question is that for the model implementation above, my model doesn't return anything. In the SMC case, what (if anything) do I have to return? |
Beta Was this translation helpful? Give feedback.
Here is my example to date - I want to show packages in their best light, so suggestions to improve are much appreciated!