library(truncnorm) # draw or evaluate according to a truncated normal dist
pmc <- function (params = NULL,
x0 = NULL, # initial values
y = NULL, # observation
npart = 1000, # number of particles
niter = 10, # iterations
tend = 100, # to control the number of daily y to be fitted
dt = 0.1, # dt for the ODE integration
prior_mean = 0.5,
prior_sd = 2,
prior_lb = 0,
prior_ub = 2) {
# makes it easy to use truncated normal distribution
nstate <- length(x0) # number of state variables (i.e., S, I, R, CI)
# initial betas are sampled according to the prior distribution
beta0 <- rtruncnorm(npart, a=prior_lb, b=prior_ub, mean=prior_mean, sd=prior_sd)
beta <- matrix(NA, ncol=npart, nrow=niter) # to store the samples for beta
beta[1,] <- beta0 # the initial values for the first row
# proposal for the next iteration, which is then resampled according to the weight
sd = sd(beta[1,]) # scale for the proposal is adapted according to the current sample
beta[2,] = rtruncnorm(npart, a=prior_lb, b=prior_ub, mean=beta[1,], sd=sd)
lik <- matrix(NA, ncol = npart, nrow = niter) # likelihood
proposal_prob <- matrix(NA, ncol = npart, nrow = niter)
wt <- matrix(NA, ncol = npart, nrow = niter) # weight
W <- matrix(NA, ncol = npart, nrow = niter) # normalized weights
A <- matrix(NA, ncol = npart, nrow = niter) # Resample according to the normalized weight
# initial value
proposal_prob[1,] <- 1
wt[1,] <- 1 / npart # initial weights
W[1,] <- wt[1,]
for (i in 2:niter) {
# cat("i =", i, "\n")
# tend increases by 1 accounts for the initial values
X <- array(0, dim = c(npart, tend+1, nstate),
dimnames = list(NULL, NULL, names(x0)))
for (nm in names(x0)) {# starting values for each particle
X[, 1, nm] <- x0[[nm]]
}
# run process model (i.e., SIR model)
x_1_tend <-
process_model(params = params,
x = X,
dt = dt,
beta = beta[i,])
# calculate weights (likelihood)
lik[i,] <- assign_weights(x = x_1_tend, y = y[1:tend])
# normalize particle weights
proposal_prob[i,] = dtruncnorm(beta[i,], beta[i-1,], a=prior_lb, b=prior_ub, sd=sd)
prior_prob = dtruncnorm(beta[i,], a=prior_lb, b=prior_ub, mean=prior_mean, sd=prior_sd)
wt[i,] <- lik[i,] * prior_prob / proposal_prob[i,]
W[i,] <- wt[i,] / sum(wt[i,])
# resample particles by sampling parent particles according to normalized weights
A[i,] <- sample(1:npart, prob=W[i,], replace=T)
beta[i,] <- beta[i, A[i,]] # resampled beta according to the normalized weight
# sd for the proposal can be adapted in various other ways, but we use the sd of the current sample
sd = sd(beta[i,])
# generate proposals for the next iteration
if (i < niter) {
beta[i+1,] <- rtruncnorm(npart, a=prior_lb, b=prior_ub, mean=beta[i,], sd=sd)
}
} # end iteration
return (list(theta=beta, lik=lik, W=W, A=A))
}