Registry / ai-ml / pystan

pystan

JSON →
library3.10.1pypypi✓ verified 24d ago

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 pystan
INSTALL
IMPORT
SIG · PYSTAN
P
pystan
ai-mlpythonv3.10.1
Install
11.7s avg
Import
1602ms
Disk
366MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.10.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
build_error
glibc
py 3.103.95 runs
installs and imports cleanly · install 11.7s · import 1.602s · 358MB
366MB installed
● package 366MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

stan
import stan
import pystan
PyStan 3 uses 'import stan' instead of 'import pystan' (used in v2.x) to align with other Stan interfaces.

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.

import stan import numpy as np schools_code = """ data { int<lower=0> J; // number of schools array[J] real y; // estimated treatment effects array[J] real<lower=0> sigma; // standard error of effect estimates } parameters { real mu; // population treatment effect real<lower=0> tau; // standard deviation in treatment effects vector[J] eta; // unscaled deviation from mu by school } transformed parameters { vector[J] theta = mu + tau * eta; // school treatment effects } model { target += normal_lpdf(eta | 0, 1); // prior log-density target += normal_lpdf(y | theta, sigma); // log-likelihood } """ schools_data = { "J": 8, "y": [28, 8, -3, 7, -1, 1, 18, 12], "sigma": [15, 10, 16, 11, 9, 11, 10, 18], } # Build the model (compiles Stan code to C++ and then to executable) posterior = stan.build(schools_code, data=schools_data, random_seed=1) # Sample from the posterior distribution fit = posterior.sample(num_chains=4, num_samples=1000) # Extract samples for a parameter mu_samples = fit["mu"] print(f"Mean of mu samples: {np.mean(mu_samples)}") # To get a pandas DataFrame (requires pandas installed): # import pandas as pd # df = fit.to_frame() # print(df.head())
Debug
Known issues
breakingPyStan 3 is a complete rewrite and introduces numerous backwards-incompatible changes from PyStan 2.x. Key API changes include `pystan.StanModel()` becoming `stan.build()`, `fit.sampling()` becoming `fit.sample()`, and `iter` parameter changing to `num_samples`.
fix
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`).
affects: 3.0.0 and later
breakingMicrosoft Windows is no longer officially supported for PyStan 3.x installations. Users on Windows are advised to use Windows Subsystem for Linux 2 (WSL2) to run PyStan, or consider alternative Stan interfaces like CmdStanPy.
fix
Install and configure WSL2, then install PyStan within the Linux environment. Alternatively, use CmdStanPy or another Stan interface that supports Windows directly.
affects: 3.0.0 and later
breakingIn PyStan 3.x, data and `random_seed` must be passed during the `stan.build()` step (compile time), not during the `fit.sample()` step (sampling time), unlike PyStan 2.x.
fix
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)`.
affects: 3.0.0 and later
breakingPyStan 3.x significantly reduces its scope. Variational inference, maximization algorithms (e.g., LBFGS), and samplers other than the default HMC sampler are no longer supported. The `stansummary` display and `check_hmc_diagnostics` functions have also been removed.
fix
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.
affects: 3.0.0 and later
gotchaPyStan requires a C++ compiler to be available both during installation and at runtime for compiling Stan models. Lack of a properly configured compiler is a common cause of installation and runtime errors.
fix
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.
affects: All versions
gotchaWhen running PyStan 3.x in Jupyter notebooks or other environments that manage their own `asyncio` event loops, `RuntimeError: asyncio.run() cannot be called from a running event loop` may occur.
fix
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.
affects: 3.0.0 and later
Errors
Common errors & fixes
Microsoft Visual C++ 14.0 or greater is required. Get it with 'Microsoft C++ Build Tools': https://visualstudio.microsoft.com/visual-cpp-build-tools/
PyStan requires a C++ compiler to build Stan models, and a compatible Visual C++ compiler is not installed or configured on Windows systems.
fix
Download and install the 'Desktop development with C++' workload from the Visual Studio Build Tools, ensuring the C++ CMake tools are selected.
error: command 'gcc' failed with exit status 1
PyStan needs a C++ compiler (like g++ or clang) to build Stan models, but it's either not installed or not correctly configured in the system's PATH on Linux or macOS.
fix
On Debian/Ubuntu, run `sudo apt-get install build-essential`. On macOS, install Xcode Command Line Tools by running `xcode-select --install`.
AttributeError: module 'pystan' has no attribute 'stan'
This error occurs when attempting to use the PyStan 2 API (e.g., `pystan.stan()`) with a PyStan 3 installation, which has a significantly different API.
fix
Update your code to use the PyStan 3 API, primarily `pystan.build()` to compile the model and `fit.sample()` to draw samples.
RuntimeError: Couldn't find a default C++ compiler.
PyStan failed to locate any compatible C++ compiler on the system, which is required to compile Stan models, possibly due to it not being installed or incorrectly configured.
fix
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.
Upgrade
Version history
3.10.1latest on PyPI · released Mar 12, 2026
Audit
Dependencies
C++ compiler (e.g., gcc >=9.0 or clang >=10.0)requiredRequired for compiling Stan models during installation and runtime. Often needs to be installed separately from Python.
NumPyrequiredFundamental for numerical operations and data handling.
CythonrequiredUsed for generating C extensions for performance.
pandasoptionalOptional, but recommended for convenient data manipulation and extracting fit results into DataFrames using `to_frame()`.
arvizoptionalRecommended for post-sampling analysis, diagnostics, and plotting, as some summary/diagnostic functions (e.g., `stansummary`, `check_hmc_diagnostics`) were removed from PyStan 3.
nest-asynciooptionalRequired for running PyStan 3 within environments like Jupyter notebooks that use asyncio event loops.
Agent activity
19 hits · last 30 days
node
14
OpenAI (training)
1
Resources
pystan — pip install pystan · libregistry