Cmdstanr Gives Compiling Error Despite "Syntactically Correct" Message

Hey all!

Full disclosure, I am very new to cmdstanr, and stan in general so I suspect this has an obvious solution, but I haven’t been able to find it and thought I might ask here!

I’m trying to write a model to test an interaction between a continuous predictor (x) and a binary categorical variable (cnd) on a continuous outcome y. My stan model looks like this:

data {
  int<lower=1> n; //sample si     
  vector[n] y; //outcome variable
  vector[n] x; //continuous x
  int cnd[n]; //binary experimental condition
} 

transformed data {
  vector[n] x_std = (x - mean(x))/sd(x);
}

parameters {
  //terms
  vector[2] a;   //intercepts
  vector[2] b;   //slopes
  real<lower=0> sigma; //residual
}

transformed parameters {
  vector[n] mu;                    
  for (i in 1:n) {
    mu[i] = a[cnd[i]] + b[cnd[i]]*(x_std[i]);
  }
}

model {
  //likelihood
  y ~ normal(mu, sigma);
  //priors
  a ~ normal(5, 2);
  b ~ normal(0, 1);
}

generated quantities {
  matrix[n, 2] yhat;
  for (i in 1:n) {
    for (j in 1:2) {
      yhat[i, j] = a[j] + b[j]*x_std[i];
    }
  }
}

When I check whether the code is syntactically correct, I get the model_interactioneffect.stan is syntactically correct. message. Then, I go to compile the cmdstanr model in rmarkdown as:


mod2 <- cmdstan_model("model_interactioneffect.stan")

And get the following error:

Compiling Stan program...
Syntax error in '/var/folders/75/s_t9tmgj27b2dxgbt5_9hswr0000gn/T/Rtmpd3cwOO/model-dbb173defdf9.stan', line 5, column 9 to column 10, parsing error:
   -------------------------------------------------
     3:    vector[n] y; //outcome variable
     4:    vector[n] x; //continuous x
     5:    int cnd[n]; //binary experimental condition
                  ^
     6:  } 
     7:  
   -------------------------------------------------

";" expected after variable declaration.

I’ve reinstalled cmdstanr, but that didn’t work, so hoping someone might know!

Thanks in advance. :)

This is likely because your model is using the old array syntax.

Statements like:

   int cnd[n]; //binary experimental condition

Should instead be:

   array[n] int cnd; //binary experimental condition

The next version of CmdStan will have more informative error messages for this as well.

When I check whether the code is syntactically correct, I get the model_interactioneffect.stan is syntactically correct. message.

How are you checking correctness here? If you’re using the RStudio syntax editor, then this is because RStudio is using rstan for checking syntax, which is a few versions behind and still supports the old syntax

1 Like

Thank you! That worked. :) I was checking correctness in the syntax editor, so I think you’re right that it was a difference between rstan and cmdstanr syntax.