Registry / ai-ml / cmdstanpy

cmdstanpy

JSON →
library1.3.0pypypi✓ verified 26d ago

CmdStanPy is the official Python interface to CmdStan, a command-line program for fitting statistical models written in Stan. It facilitates compiling Stan models, running MCMC, optimization, and variational inference, and processing the results. Currently at version 1.3.0, it follows a regular release cadence with minor updates every few months, and a major 2.0 release planned to remove existing deprecations.

pip install cmdstanpy
INSTALL
IMPORT
SIG · CMDSTANPY
C
cmdstanpy
ai-mlpythonv1.3.0
Install
8.1s avg
Import
1207ms
Disk
166MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.3.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
installs and imports cleanly · install 0.0s · import 1.254s · 166MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 8.1s · import 1.160s · 159MB
166MB installed
● package 166MB
Code
Verified usage

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

CmdStanModel
from cmdstanpy import CmdStanModel
install_cmdstan
from cmdstanpy import install_cmdstan
Used to automatically download and set up the CmdStan C++ library.
set_cmdstan_path
from cmdstanpy import set_cmdstan_path
Used to explicitly point CmdStanPy to an existing CmdStan installation.

This quickstart demonstrates how to define, compile, and fit a simple Bernoulli model using CmdStanPy. It includes essential steps to ensure the underlying CmdStan C++ program is available, either by setting its path or by automatically installing it. The example compiles a Stan file, provides data, runs MCMC sampling, and prints a summary of the results.

import os import shutil from cmdstanpy import CmdStanModel, install_cmdstan, set_cmdstan_path # --- Step 1: Ensure CmdStan is installed and path is set --- # This is crucial. If CMDSTAN_PATH environment variable is not set, # CmdStanPy will attempt to download and install CmdStan to '~/.cmdstan'. # You can also manually set the path via set_cmdstan_path(). try: set_cmdstan_path(os.environ.get('CMDSTAN_PATH', '')) except ValueError: print("CmdStan path not explicitly set or found. Attempting automatic installation...") install_cmdstan() print(f"CmdStan installed to: {os.path.join(os.path.expanduser('~'), '.cmdstan')}") # --- Step 2: Define a Stan model --- stan_code = """ data { int<lower=0> N; array[N] int<lower=0,upper=1> y; } parameters { real<lower=0,upper=1> theta; } model { y ~ bernoulli(theta); } """ stan_filepath = "bernoulli.stan" with open(stan_filepath, "w") as f: f.write(stan_code) try: # --- Step 3: Compile the Stan model --- # This creates an executable that CmdStanPy will call. model = CmdStanModel(stan_file=stan_filepath) print(f"Stan model compiled to: {model.exe_file}") # --- Step 4: Prepare data for the model --- data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]} # --- Step 5: Fit the model using MCMC sampling --- print("Starting MCMC sampling...") fit = model.sample(data=data, chains=2, iter_sampling=500, iter_warmup=500, seed=42) print("MCMC sampling complete.") # --- Step 6: Summarize and inspect results --- print("\nPosterior summary statistics:") print(fit.summary()) # Access posterior draws as a pandas DataFrame # print("\nFirst 5 rows of posterior draws:") # print(fit.draws_pd().head()) except Exception as e: print(f"An error occurred during CmdStanPy execution: {e}") finally: # --- Step 7: Clean up generated files --- if os.path.exists(stan_filepath): os.remove(stan_filepath) # CmdStan installation is usually kept, so no cleanup for it here. print("Cleanup complete.")
cmdstanpy --version
Debug
Known issues
breakingCmdStanPy 2.0 (the next major non-bugfix release) is announced to remove all existing deprecations. Users should update their code to address current deprecation warnings before migrating to 2.0 to avoid breaking changes.
fix
Consult CmdStanPy documentation for current deprecations (e.g., replace `output_basename` with `output_dir`) and update code accordingly.
affects: All 1.x versions (pre-2.0)
gotchaCmdStanPy is a Python wrapper for the CmdStan C++ program. You must have CmdStan installed on your system. It can be manually installed and its path set via `cmdstanpy.set_cmdstan_path()`, or automatically downloaded and installed to your home directory (`~/.cmdstan`) using `cmdstanpy.install_cmdstan()`.
fix
Before using CmdStanPy, either run `cmdstanpy.install_cmdstan()` once, or install CmdStan manually and set the `CMDSTAN_PATH` environment variable or call `cmdstanpy.set_cmdstan_path()`.
affects: All versions
deprecatedThe `output_basename` argument in `sample()`, `optimize()`, `variational()`, `generate_quantities()`, and `pathfinder()` methods is deprecated and will be removed in CmdStanPy 2.0. Users should use the `output_dir` argument instead.
fix
Replace `output_basename='my_output'` with `output_dir='path/to/output'` (which defaults to a temporary directory if not specified).
affects: Introduced in 1.x, will be removed in 2.0
gotchaVersions of CmdStanPy prior to 1.2.4 could fail to load output files from CmdStan 2.35+ due to changes in CmdStan's output format.
fix
Upgrade CmdStanPy to version 1.2.4 or newer to ensure compatibility with CmdStan 2.35 and later versions.
affects: <1.2.4
gotchaCmdStanPy requires the `make` utility to be installed in the environment for building CmdStan (if using automatic installation) and compiling Stan models. Without `make`, CmdStanPy cannot complete these fundamental operations.
fix
Ensure `make` is installed in your environment. For Alpine Linux (like `python:3.13-alpine`), this can typically be done with `apk add make`. For other distributions, use their respective package managers (e.g., `apt-get install make` on Debian/Ubuntu, `yum install make` on CentOS/RHEL).
affects: All versions
Errors
Common errors & fixes
ValueError: Unable to compile Stan model file: /path/to/your/model.stan
This error occurs when CmdStanPy fails to compile the Stan model into an executable, often due to an incorrectly configured or incompatible C++ toolchain (compiler, linker, make utility), or issues with precompiled headers (PCH).
fix
Ensure a compatible C++ toolchain is installed (e.g., Xcode command line tools on macOS, RTools 4.0 with g++ 8 on Windows, or `g++` on Linux). If issues persist, try rebuilding CmdStan using `cmdstanpy.rebuild_cmdstan()` to address potential PCH file corruption. Verify that the necessary environment variables for your toolchain are correctly set.
ValueError: No CmdStan installation found, run command "install_cmdstan" or (re)activate your conda environment!
CmdStanPy cannot locate the CmdStan executable because it is either not installed, the `CMDSTAN` environment variable pointing to its location is not set, or the conda environment where it was installed is not active.
fix
To resolve this, install CmdStan by running `cmdstanpy.install_cmdstan()` in Python. If installed via conda, ensure your environment is activated (`conda activate your_env_name`). If CmdStan is installed in a non-default location, explicitly set the `CMDSTAN` environment variable (e.g., `os.environ['CMDSTAN'] = '/path/to/cmdstan'`).
RuntimeError: Error during sampling: Command and output files: RunSet: chains=4, chain_ids=[1, 2, 3, 4], num_processes=4 cmd (chain 1): [...] retcodes=[3221225781, 3221225781, 3221225781, 3221225781]
This indicates a failure during the model sampling process by the underlying CmdStan executable, often stemming from model issues (e.g., invalid initializations, severe divergences), insufficient system memory, or C++ runtime errors.
fix
First, re-run the sampling with `show_console=True` in the `model.sample()` call to view direct CmdStan output. Check model diagnostics (`fit.diagnose()` after a successful run, if possible). Review model initializations and consider adjusting sampler parameters like `adapt_delta` or `max_treedepth`. Ensure sufficient system resources (RAM) are available.
SyntaxError: invalid syntax (e.g., related to 'walrus operator' := in stanio/csv.py)
This error typically occurs when a Python interpreter with an older version (e.g., Python 3.7 or earlier) attempts to run code that uses syntax features introduced in newer Python versions (e.g., the walrus operator `:=` in Python 3.8+), which can happen if CmdStanPy or its dependencies were installed for a newer Python version.
fix
Ensure your Python environment is running a version compatible with CmdStanPy's requirements (typically Python 3.8 or newer for features like the walrus operator). It is recommended to create a fresh virtual environment with an appropriate Python version and reinstall `cmdstanpy` and its dependencies there.
Upgrade
Version history
1.3.0latest on PyPI · released Oct 20, 2025
Audit
Dependencies
CmdStanrequiredCmdStanPy is a Python interface to the CmdStan command-line program. CmdStan (the underlying C++ program) must be installed separately or via `cmdstanpy.install_cmdstan()`. If not installed, CmdStanPy will fail to compile or run models.
Agent activity
26 hits · last 30 days
node
22
OpenAI (training)
1
Resources