Exception: mismatch in number dimensions declared and found in context

I am trying to use a self-defined distribution in Stan to get the parameter posterior distributions. Everything works out well except when the vector has the length 1, Stan will not work. I found some similar topics, but I don’t really understand the reason why Stan does not work in this condition. Here are my Stan code and some sample data:

plpstan11 = '
  real nhpp_log(vector t, real beta, real theta, real tau){
    real loglikelihood;
      vector[num_elements(t)] loglik_part;
      for (i in 1:num_elements(t)){
        loglik_part[i] = log(beta) - beta*log(theta) + (beta - 1)*log(t[i]);
      loglikelihood = sum(loglik_part) - (tau/theta)^beta;
    return loglikelihood;
data {
  int<lower=0> n; //total # of obs
  real<lower=0> tau;//truncated time
  vector<lower=0>[n] t; //failure time
  real<lower=0> beta;
  real<lower=0> theta;
  t ~ nhpp(beta, theta, tau);
  beta ~ gamma(1, 1);
  theta ~ gamma(1, 0.01);

stan_yes = list(n = 6, tau = 657, t = c(251, 397, 406, 451, 465, 593))
stan_no = list(n = 1, tau = 657, t = 253))

fitplp <- stan(
  model_code=plpstan11, model_name="NHPP", data=stan_no, 
  iter=1000,warmup = 500, chains=1, seed = 123

The stan code will work out well if the length of t is more than 1 (using the data stan_yes). However, Stan will report the following error message only if t is a vector with length 1 (using the data stan_no):

Error in new_CppObject_xp(fields$.module, fields$.pointer, …) :
Exception: mismatch in number dimensions declared and found in context; processing stage=data initialization; variable name=t; dims declared=(1); dims found=() (in ‘model352055946207_NHPP’ at line 16)
failed to create the sampler; sampling not done

I found two similar posts here:

But from my limited understanding, none of them clearly explain the mechanism behind this error. Could anyone explain this error? Thank you!

1 Like

You probably just need to do as.array(t) when you construct the list of data in R when t is of length 1.

1 Like

Thanks Ben! That works. I’ve seen similar answers in the two links I posted.
Is there any reason why as.array(t) works?

If I inspect into the data list, there seems to no difference before and after as.array()

Stan will interpret t as a scalar if you do not do as.array, leading to the error message you saw.

Got it. Thanks Ben!

why only “t” since both “n” and “tau” have length 1?

Those are declared as vectors that happen to have a size of 1, rather than scalars.