Parser failed badly

Hello, I am an “R” and “Stan” newbie trying to run a very simple stan model from R. The stan model is in the same directory as my R script. Here is the code in the model file (mnl.stan):

data {

	int<lower=2> C; // # of alternatives (choices) in each scenario
	int<lower=1> N;	// # of observations
	int<lower=1> K; // # of covariates
	int<lower=1,upper=C> Y[N]; // observed choices
	matrix[C,K] X[N]; // matrix of attributes for each obs

parameters {
	vector[K] beta;

model {
  # priors
	// beta ~ normal(0,3); // often used in Gibbs sampling
	beta ~ cauchy(0, 2.5);  // better
	# model
	for (i in 1:N)
		Y[i] ~ categorical_logit(X[i]*beta);

I am using the following R script to parse the above model:

# ========== Load libraries and set options ==========

# writes a compiled Stan program to the disk to avoid recompiling
# allows Stan chains to run in parallel on multiprocessor machines
options(mc.cores = parallel::detectCores())

# ========== Test Stan with synthetic data ============

# function to generate mnl data
generate_hmnl_data <- function(R=100, S=30, C=3, 
                               Theta=matrix(rep(1, 8), nrow=2), 
                               Sigma=diag(0.1, 4)){
  K <- ncol(Theta)
  G <- nrow(Theta)
  Y <- array(dim=c(R, S))
  X <- array(rnorm(R*S*C*K), dim=c(R, S, C, K)) # normal covariates
  Z <- array(dim=c(G, R))
  Z[1,] <- 1  # intercept
  if (G > 1) {
    Z[2:G,] <- rnorm(R*(G-1)) # normal covariates
  Beta <- array(dim=c(K, R))
  for (r in 1:R) {
    Beta[,r] <- mvrnorm(n=1, mu=Z[,r]%*%Theta, Sigma=Sigma)
    for (s in 1:S)
      Y[r,s] <- sample(x=C, size=1, prob=exp(X[r,s,,]%*%Beta[,r])) # logit formula
  list(R=R, S=S, C=C, K=K, G=G, Y=Y, X=X, Z=Z, 
       beta.true=beta, Theta.true=Theta, Sigma.true=Sigma)

d1 <- generate_hmnl_data()

test.stan <- stan(file="hmnl.stan", data=d1, iter=1000, chains=4)

The last line is not executed and I get the following error:

Error in stanc(file = file, model_code = model_code, model_name = model_name, :
parser failed badly

Try removing all # from your model, there’s an issue with how they’re handled in the rstan parser at the moment


Thank you so much @andrjohns, it was a great help!