Hi Rowenna,
I wrote some more simulation code and slicked out the function just a bit after you described exactly what you wanted to do.
Perry, thanks for the help and catching my coding errors. I need to slow down a bit here :)
I've included an example that compiles and runs the MCMC:
Hopefully this solves your problem:
y1 = runif(200, 0, 1000)
pts = SpatialPoints(cbind(x1, y1))
rast = raster(xmn = 0, xmx = 1000, ymn = 0, ymx = 1000, res = 100)
rast[] = rpois(ncell(rast), 20)
rast1 = rast
rast1[] = rpois(ncell(rast), 20)
rast2 = rast
rast2[] = rpois(ncell(rast), 20)
#covariate function
covVals2 <- nimbleFunction(
run = function(y = double(1),
S = double(2),
cov1= double(1),
cov2 = double(1),
cov3 = double(1)) {
dist <- sqrt(((y[1] - S[1:dim(S)[1], 1]) ^2) + ((y[2] - S[1:dim(S)[1], 2]) ^2)) #calculate nearest
# now loop over locations to get covariate ids
id = which(dist == min(dist))
x1.val <- cov1[id]
x2.val <- cov2[id]
x3.val <- cov3[id]
cov.vals <- c(x1.val, x2.val, x3.val)
return(cov.vals)
returnType(double(1))
}
)
# test the function with first point
covVals2(y = coordinates(pts)[1,], S = coordinates(rast), cov1 = rast@data@values, cov2 = rast1@data@values,cov3 = rast2@data@values)
# to simulate the problem in compilied code
nimcode <- nimbleCode({
for(i in 1:nLocs){
y[i,1] ~ dunif(0, 1000)
y[i,2] ~ dunif(0, 1000)
}
for(i in 2:nLocs){
covs[1:3,i] <- covVals2(y=y[i-1,],S=rast.coords[1:nRast,1:2], cov1 = v1[1:nRast], cov2 = v2[1:nRast], cov3 = v3[1:nRast])
}
})
nimData = list(rast.coords = coordinates(rast),v1 = rast@data@values, v2 = rast1@data@values,v3 = rast2@data@values, covs = matrix(0, nrow=3, ncol=200))
constants = list(nLocs = 200, nRast = prod(dim(rast)[1:2]))
testR <- nimbleModel(nimcode,data = nimData, constants = constants, inits = list(y = matrix(runif(constants$nLocs*2),ncol=2)))
# complete initialization of model
testR$calculate()
testR$initializeInfo()
# compile model
testC <- compileNimble(testR, showCompilerOutput = FALSE)
# MCMC sampler configurations
mcmcspec<-configureMCMC(testR, monitors=c("y","covs"))
# build the MCMC specifications
testMCMC <- buildMCMC(mcmcspec)
# complile the code
CtestMCMC <- compileNimble(testMCMC, project = testR,resetFunctions = TRUE)
# run MCMC
tic()
samples <- runMCMC(CtestMCMC, niter = 10000, nburnin=1000,thin=1,nchains=1)
toc()
colNames <- grep("covs\\[",colnames(samples))
(covs <- samples[1,colNames]) # look at the first iteration