I’ve been working on improving the workflow of using stan from within the Python ecosystem. My latest effort involves two extensions for iPython and JupyterLab which allow you to easily edit and run stan programs as part of a notebook file.
The first, cmdstanjupyter, is an iPython extension which adds the ability to use the magic command %%stan
and create/compile a CmdStanPy object from text directly in the notebook. This is done by creating a hidden folder called .stan and placing files in there, so you still ultimately have the models saved on disk.
The second, jupyterlab-stan-highlight provides a CodeMirror syntax highlight for stan and enables it in both .stan files and %%stan
magic cells. This basically turns a %%stan
cell into a tiny stan IDE - indentation with C-[ and C-], comment toggling with C-/, and bracket matching are all available.
The end result of using both is shown in this quick demo which runs an example from McElreath’s Statistical Rethinking:
How to install and use:
Assuming you already have JupyterLab and cmdstanpy installed, you only need to run two commands:
pip install cmdstanjupyter
jupyter labextension install jupyterlab-stan-highlight
(this command may require you to have nodejs installed)
You can then open any notebook and run %load_ext cmdstanjupyter
and make your %%stan
cells!
Note: you may need to select a different cell and then click back on the %%stan cell to recieve highlighting when you first create it. This is still a work in progress!
R Users:
Anyone using R in Jupyter through IRKernel can use the syntax highlighting plugin for .stan files, but unfortunately magic commands are not (and will never be) supported by IRKernel, so the %%stan cells are python-only.