Thanks for asking about this.
Here is another workaround that is somewhat more general. If you write a user-provided function to do the nested indexing with a model variable as the index, it will work. Here is a simple example that I think captures what you need:
## begin example
library(nimble)
modelCode <- nimbleCode({
for(i in 1:3) {
s[i] ~ dcat(probs[1:3])
d[i] <- myCalculation(grid[1:3], s[i]) ## User-provided function that will do whatever indexing and other stuff you need
}
})
## see section 5.2.5 of User Manual
myCalculation <- nimbleFunction(
run = function(grid = double(1), index = double()) { ## index could be int() but model variables are represented as double anyway
return(grid[index])
returnType(double(0))
})
model <- nimbleModel(modelCode, data = list(probs = c(.2,.3,.5)), constants = list(grid = as.numeric(c(10, 20, 30))))
## Either of these could be data or constants, or stochastic variables in your model
compiledModel <- compileNimble(model)
## check that the calculation works:
simulate(compiledModel)
compiledModel$s
compiledModel$d
## The values of d should be 10, 20 or 30 according to s
testMcmc <- buildMCMC(model)
compiledMCMC <- compileNimble(testMcmc, project = model)
testMcmc$run(100)
testMcmc$mvSamples$s
## that seems to work.
## end example
There is a potential inefficiency because each element of d will depend on all elements of grid[]. So in a situation where grid is dynamic (changing during the course of the MCMC), then every time any value of grid[] changes, each value of d[i] would be recalculated, even if it turns out to be give the same answer. But I think in your example grid[] is fixed and you just need the stochastic indexing.
Let us know how it works.
Perry