translating spatial loop to nimblefunction fails at compilation

12 views
Skip to first unread message

Thomas Keller

unread,
Nov 25, 2025, 11:40:14 AMNov 25
to nimble-users
Hi,

I'm trying to convert a spatial loop in a disease model to a nimblefunction as the compilation takes an increasing length of time as the number of sites in the model grows.

I have tried converting the loop to a nimblefunction as suggested for a different problem that also had a bunch of temporary variables (https://groups.google.com/g/nimble-users/c/DaidiPd7o0Q).

The original loop:

for (k in 1:J){
          IN.tmp_Pf[i,j,k]<-q*(RC_Pf[i,k]*exp(-gamma*D[j,k]))
          w[i,j,k]<-exp(-gamma*D[j,k])      
        }
        #cant have empty indices, need to make explicit
        IN_Pf[i,j]<-sum(IN.tmp_Pf[i,j,1:J])/sum(w[i,j,1:J])

The function I made:

betacalc2 <- nimbleFunction(    
  run = function(w = double(1),adj=integer(1),weights=double(1),num=integer(1),wstart=integer(0),wend=integer(0),wi=integer(0), gamma = double(0),RC=double(1),q=double(0)) {
    returnType(double(0))
   
    result=0.0
    for(ji in wstart:wend){
      j=adj[ji]
      result=result+(q*(RC[j]*exp(-gamma*weights[ji])))
    }
    result=result/w[wi] #sum(result)/ sum(w[j,neighbors])
    result=log(result) # beta0_Pf/Pv
    return(result)

  })

I then call it as:

beta0_Pf[i,j]<- betacalc2(w[1:J],adj[1:L],weights[1:L],num[1:J],wstart[j],wend[j],j,gamma,RC_Pf[i,1:J],q)

However, this fails at compilation.

I've attached the error log. If anyone has suggestions, I'd greatly appreciate it. I can add the full model code if that would help.


spat_err.txt

Chris Paciorek

unread,
Nov 26, 2025, 11:57:00 AMNov 26
to Thomas Keller, nimble-users
Hi Thomas,

While `adj` and `num` are integer-valued, nimble treats model variables as doubles. So try changing your nimblefunction to use `double(1)` instead of `int(1)`:

run = function(w = double(1),adj=double(1),weights=double(1),num=double(1),wstart=integer(0),wend=integer(0),wi=integer(0), gamma = double(0),RC=double(1),q=double(0)) {

As far as the `integer(0)` cases, I think we handle the conversion of scalars gracefully, but if you still get an error when using the above, you could try changing `integer(0)` to `double(0)`.

Let us know if that doesn't work (ideally sharing a reproducible example that is as simplified as readily possible).

-chris

--
You received this message because you are subscribed to the Google Groups "nimble-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nimble-users...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/nimble-users/1d8b8284-dc5b-4ed8-b925-7e185705bbabn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages