A Sphinx extension for documentation Stan code

As part of developing the package for Scalable Gaussian process inference, I wrote a reasonable amount of interface documentation. To avoid scattering documentation across different documents (e.g., Stan code and markdown or reStructuredText), there is a small extension for Sphinx that can autogenerate documentation from inline comments.

For example, consider the following Stan file.

* Raise a matrix to a power.
* @param X Matrix to raise to a power.
* @param y Power.
* @return :math:`X^y`
* @throws An error if there's a problem.
matrix mat_pow(matrix X, real y) {
    return rep_matrix(0, 1, 1);  // Not the correct value, of course.

Using the Stan-domain autodoc directive in Sphinx, automatically generates the documentation below.

.. stan:autodoc:: example.stan

The extension also supports cross-references, i.e., one can use :stan:func:`mat_pow ` to generate a clickable reference within the documentation. E.g., here’s the background section for Fourier-based GPs with links to the interface documentation.

There are a few additional features (such explicit function documentation in .rst, documenting only a subset of functions defined in a .stan file, and support for both doxygen syntax and standard Sphinx-style rst).

Maybe others will also find it useful for documenting their Stan code. Instructions on how to get started are here. Disclaimer: It’s still pretty rough around the edges.


This is awesome. When working on BridgeStan’s documentation I explored how to use Sphinx on a whole bunch of languages (Python, Julia, R, C++) but funnily enough never Stan.

Do you know how feasible it would be to add links to the source to the autodoc’d methods? E.g. the [source] link on the right here

It looks like this might be possible with sphinx.ext.linkcode – Add external links to source code — Sphinx documentation, but I’ve not yet tried it.

1 Like