Intended behavior of vector[array_idx] += vector?

Stan allows us to index each element of a vector multiple times, and allows us to assign that indexed element some values. Using this toy syntax below, I intend to increment an element five times, but it occurs only once. I would expect element LHS[1] == 5 or get a syntax error.

What is the intended behavior of this syntax?

test.stan:

generated quantities {
  vector[5] LHS = rep_vector(0, 5);
  {
  array[5] int idx = {1, 1, 1, 1, 1};
  LHS[idx] += rep_vector(1, 5);
  }
}

In R,

library(cmdstanr)
m <- cmdstan_model('test.stan')
f <- m$sample(fixed_param = TRUE)

Stan pretty strictly interprets a += b as equivalent to a = a + b. When combined with value semantics, the code you posted is treated like:

LHS[idx] = copy(LHS[idx]) + rep_vector(1, 5);

Which means that only the “last” assignment stays around.

If you wrote something where the element changed based on the ordering, this becomes a bit more obvious:

generated quantities {
  vector[5] LHS = rep_vector(0, 5);
  {
  array[5] int idx = {1, 1, 1, 1, 1};
  LHS[idx] += linspaced_vector(5,1,5);
  }
  print(LHS);
}

LHS[1] will contain 5, not 15 (=1+2+3+4+5)

This seems to match how numpy in Python handles similar operations, but it might not necessarily be the most intuitive

1 Like