I am trying to write a function that can calculate Approximate Bayesian Computation using the Population Monte Carlo method. However, I ran into some troubles with my R code with the following error.
>head(ABC_PMC(2,5000,1,observedData,observedSummary))
Error in while (prior == 0) { : missing value where TRUE/FALSE needed
In addition: Warning message:
In log(importance.sample[2]) : NaNs produced
The code doesn't have a problem when I run it with one iteration, t=1. The issue lies with the second iteration and I think it is the assignment of importance.sammpling step. But I can't figure out what is the error as I tried to run the code manually and it works.
Any and all help will be appreciated.
# initialise variables:
set.seed(12345)
n=5000
weight = rep(1,n)
theta = matrix(NA, nrow = n, ncol = 2)
for (i in 1:n) {
fit = c(runif(1,-2,2), runif(1,0,4))
theta[i,] = fit
}
#Calculate importance density for current t to use in next iteration
old.prop.weight = weight / sum(weight)
old.theta = theta
Kernel.mean = cbind(old.theta[,1],old.theta[,2])
Kernel.cov = cov(old.theta)
Main loop:
for (i in 1:n) {
prior=0
while (prior==0) {
#Loop to test is prior=0
choice = sample(1:n, size = 1, prob = old.prop.weight)
importance.sample = rmvnorm(1,mean = Kernel.mean[choice,], sigma = Kernel.cov)
#logsigma to ensure theta2 are all nonnegative
if (importance.sample[2] != 0)
importance.sample[2] = log(importance.sample[2])
fit = c(importance.sample[1],importance.sample[2])
}
prior = as.numeric(dunif(fit[1],min = -2,max = 2) * dunif(exp(fit[2]),min = 0,max = 4))
}
theta[i,] = fit
##End of step 2 loop
}
Edit: Tried to make the code into a reproducible example.