summing a vector of changing lengths

8 views
Skip to first unread message

EN Pete

unread,
Jul 17, 2024, 12:02:15 PM (5 days ago) Jul 17
to nimble-users
Hi All-

I have a model where I want to sum components within a vector that changes length based on on state s. For example, in the below code I want to sum gamma_rt for region r year t within state s. For every state the number of regions changes, so I include a region index region_s which gives which regions are included in state s. nregions_s is the total number of regions in state s which changes by state. 
I can show the whole model if helpful, but this is really the only line that needs help. 
When I try to run this, I get the error related to vector indexes within a function and that it requires a scalar. 

Can anyone help me on how I would execute this in Nimble?


sum(gamma_rt[regions_s[s,2:nregions_s[s]],t])

Chris Paciorek

unread,
Jul 17, 2024, 7:57:39 PM (5 days ago) Jul 17
to EN Pete, nimble-users
I think you'll need to write a short nimbleFunction to do the summation. Something like this:

```
summation <- nimbleFunction(
  run = function(gamma = double(1), regions = double(1), nregions = double(0)) {
     returnType(double(0))
     return(sum(gamma[regions[2:nregions]]))
}
```

and in your model:

```
sum(gamma_rt[1:M, t], regions_s[s,1:P], nregions_s[s])
```

where M and P are what they need to be to indicate the extent of the relevant dimensions.

Let me know if that doesn't do it and we can iterate as needed.

-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 on the web visit https://groups.google.com/d/msgid/nimble-users/75b65c1d-cb76-4db5-8a0c-af3863bf80dcn%40googlegroups.com.

Daniel Turek

unread,
Jul 18, 2024, 4:59:08 AM (5 days ago) Jul 18
to EN Pete, paci...@stat.berkeley.edu, nimble-users
One comment, in the model code, I think Chris means you'd use the (custom-written) "summation" function, rather than regular old "sum".

So, the model code part would be a bit more like:

some_model_variable[s,t] <- summation(gamma_rt[1:M, t], regions_s[s,1:P], nregions_s[s])



Chris Paciorek

unread,
Jul 18, 2024, 10:41:50 AM (4 days ago) Jul 18
to Daniel Turek, EN Pete, nimble-users
Yes, thanks for noticing my omission, Daniel. One needs to use `summation` in the model.

-Chris
Reply all
Reply to author
Forward
0 new messages