Automatic formatting of stan code

Hi,

Has anyone written some utility that takes a complete stan code file and formats (or at least indents) it according to the guidelines? I have code with a lot of includes, because I want to use the same chunks in several models (and possibly at different levels of indentation). The final stan code is often difficult to read because I cannot indent the includes. According to https://mc-stan.org/docs/2_22/reference-manual/includes-section.html it is possible to add whitespace before includes but when I do it, stanc does not find the file that is supposed to be included.

2 Likes

Do you use R or Python interface?

I added a small utility function to reformat stan code to remove the indents for includes.

pattern = r"(?<=\n)\s*(#include)\s*(\S+)\s*(?=\n)"
model_code, n = re.subn(pattern, r"\1 \2", model_code)

I use rstan. So I meant that if I create an object of class stanmodel using

model <- rstan::stan_model(file = 'stan_file_which_includes_other_stan_files.stan')

then model@model_code will be a string that describes a complete model without any includes. But the parts that are coming from an #include statement are not indented as I would like. So I was asking for something that formats that.

And I was about to write that kind of formatting utility myself but just asking if it is already done :D

But what I would really like is to be able to write a main.stan like this

model{
  for(i in 1:3){
    #include chunk.stan
  }
}

where chunk.stan is this:

for(j in 1:3){
   // do a thing
 }

and have that result in model@model_code which looks like this

model{
  for(i in 1:3){
    for(j in 1:3){
      // do a thing
    }
  }
}

instead of this

model{
  for(i in 1:3){
for(j in 1:3){
  // do a thing
}
  }
}
3 Likes

There is an emacs mode that handles indentation pretty well! (But… it requires emacs.)

https://github.com/stan-dev/stan-mode

1 Like