Rstan compile error line number doesn't match with text file

I’m using rstan, with my codes saved in a “.stan” file. I usually use the following codes to compile the model

mod1 <- stan_model(file = "xxxx.stan")

However, I noticed that in the error message, the line numbers don’t match with what I have in my stan file at all. I have to guess which line exactly has got the error and try to fix them through trial and errors. This is really frustrating. I’d like to ask how rstan counts line number? I’ve searched the forum, and saw a few posts. But none of them could solve my question, so I decided to ask again.

Here’s a list of past posts I saw:

No reply for this one: Stan Runtime Error Line Number
A similar question here but later it seems that’s not an issue after all: New line reference system for errors seems confusing

In this post, it’s said that rstan counts line number in the same way as a usual text editor. However, this definitely isn’t what I’m seeing. How does Stan count lines

Can you share a stan model that exhibits this behavior for you?

Hi! I just updated my rstan to the latest version. I can see that in this version, although the line numbers still don’t match up, it’s at least showing the part of the code which it’s complaining. So it’s ok for now. Thanks!

The issue involving line numbers was recently discussed and solved here: Stan error messages - #8 by WardBrian

1 Like

Thanks so much for letting me know! I just read through that threads … so it seems: 1. for now we can try to remove all empty lines in the stan file if we want to try to match the line numbers in the compiler; 2. stan team is working on it so hopefully it’ll be corrected in later versions of rstan?

Yes, correct. You might keep the empty lines in your Stan file, then to find the line numbers that rstan reports: read the Stan file in R, remove empty lines, and look at the resulting line numbers. For example, I think something like this should work:

stanmod <- readLines('my_file.stan')
stanmod <- stanmod[stanmod != ""]

## what rstan calls line 25:
stanmod[25]
1 Like