CmdStanPy - read Stan model from Github

Hi all,

The below code let’s me read a Stan file in R

model <- url("GitHub_page") |>
  readLines() |>
  cmdstanr::write_stan_file() |>
  cmdstanr::cmdstan_model()

Is it possible to do this in Python too, using CmdStanPy?

Kind Regards,
Dom

I would check either urllib (urllib3?) or request modules. Then it is just text processing.

1 Like

Hi Ari,

Thanks for getting back to me (again)!

I am able to read the text from the page, but as far as I know, there is no write_stan_file() equivalent in CmdStanPy, so I don’t know how it can be read by CmdStanModel().

What do you think?

Dom

Writing the code to a file can be done in normal python code with something like

with open(‘mymodel.stan’, ‘w’) as f:
    f.writelines(contents)

I believe all the R function does besides this is generate a unique name for the model each time

1 Like

Hi ,

Apologies if I am missing something obvious, and if this is not purely a Stan-related matter…

…but to clarify: I would like to read a Stan file that is saved on Github, and, without saving a local copy or creating any new files, use this as an input to cmdstanpy.CmdStanModel().

@ahartikainen - what text processing would be required to do this?

@WardBrian - I believe the code you proposed required an existing, locally saved file, ‘my model.stan’?

write_stan_file is creating a file, just by default it is in a hidden temporary directory

If you want this behavior in Python you can use the built in tempfile library. We considered adding a similar function to cmdstanpy recently, but decided against it since we felt it would encourage storing code in strings when it belongs in its own file

1 Like

Thanks @WardBrian!

That’s interesting to hear. The reason I do not want to save a local file is because I want to share the Stan model with a large number of colleagues in a notebook. I would like for them to be able to run the model, without needing to save new files.

Your suggestions were very helpful though, and for anyone who is interested, the below works for me:

import cmdstanpy, requests, os, tempfile

url = "Github_page"

new_file, filename = tempfile.mkstemp()
filename = filename + ".stan"

f = open(filename, "w"); f.write(requests.get(url).text)

strength_model = cmdstanpy.CmdStanModel(stan_file = filename)

Not nearly as nice as the R syntax, and I’m sure the Stan team could do much better, but this is good enough for me at the moment.

Thank you both for your time!