PyStan is a Python interface to Stan, a powerful platform for Bayesian inference and high-performance statistical computation. It allows users to define statistical models using Stan's probabilistic programming language and fit them using Hamiltonian Monte Carlo (HMC) methods. Currently at version 3.10.1, PyStan focuses on providing a reliable HMC sampler, with a development cadence that sees frequent updates to minor versions.
pip install pystanVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a Stan model, provide data, build the model, sample from the posterior distribution using HMC, and extract results for analysis. It uses the classic 'Eight Schools' hierarchical model. The `stan.build()` step compiles the model, which can take some time. `posterior.sample()` then runs the MCMC chains.
Consult the 'Upgrading to Newer Releases' section in the official documentation. Update import statements (`import stan`), function calls (`build`, `sample`), and parameter names (`num_samples`).
Install and configure WSL2, then install PyStan within the Linux environment. Alternatively, use CmdStanPy or another Stan interface that supports Windows directly.
Ensure that your data dictionary and `random_seed` argument are passed to `stan.build()` when initializing your model, e.g., `posterior = stan.build(model_code, data=my_data, random_seed=123)`.
For these features, consider using alternative Stan interfaces (like CmdStanPy or RStan) or other probabilistic programming libraries (e.g., PyMC, JAX, PyTorch for VI/maximization). For diagnostics, use the ArviZ library.
Ensure you have a compatible C++ compiler installed (e.g., gcc >=9.0 or clang >=10.0 on Linux/macOS). On Debian-based systems, `apt-get install build-essential` often suffices. For Windows, WSL2 is the recommended approach.
Install and use `nest-asyncio` by adding `import nest_asyncio; nest_asyncio.apply()` at the beginning of your notebook or script to allow nested event loops.
Download and install the 'Desktop development with C++' workload from the Visual Studio Build Tools, ensuring the C++ CMake tools are selected.
On Debian/Ubuntu, run `sudo apt-get install build-essential`. On macOS, install Xcode Command Line Tools by running `xcode-select --install`.
Update your code to use the PyStan 3 API, primarily `pystan.build()` to compile the model and `fit.sample()` to draw samples.
Install a C++ compiler appropriate for your operating system (e.g., Visual C++ Build Tools on Windows, `build-essential` on Linux, Xcode Command Line Tools on macOS) and ensure it's accessible in your system's PATH.