CmdStanPy
repository·develop·Indexed 41 days ago
https://github.com/stan-dev/cmdstanpyA lightweight pure-Python interface to CmdStan that provides access to the Stan compiler and inference algorithms. It acts as a modular bridge to run compiled Stan executables, supporting HMC-NUTS sampling via `CmdStanMCMC`, maximum likelihood estimation via `CmdStanMLE`, variational inference via `CmdStanVB`, and the Pathfinder algorithm. The package includes tools for model compilation with `CmdStanModel`, result summarization, and diagnostics.
What's inside CmdStanPy
- CmdStanPy is a lightweight, pure-Python interface to CmdStan. It provides access to the Stan compiler and all inference algorithms, allowing Python users to perform Bayesian inference by wrapping the CmdStan command line interface. It uses a small set of Python classes to manage models, data, and posterior estimates.
Overview of CmdStanPy capabilities
developCmdStanPy is a lightweight Python interface to CmdStan. It provides classes and methods to perform Bayesian inference by wrapping the CmdStan file-based command line interface.
Key capabilities include:
- Compiling Stan models.
- Performing inference using various algorithms:
- Exact Bayesian estimation via the
NUTS-HMC sampler. - Approximate Bayesian estimation via
PathfinderandADVI. - MAP estimation via
optimization.
- Exact Bayesian estimation via the
- Generating new quantities of interest from existing samples.
- Managing inference outputs, including extracting information, summarizing results, and saving outputs.
Because it uses minimal memory beyond what CmdStan itself requires, it is suitable for complex models and large datasets compared to PyStan or RStan.
Explore software that uses CmdStanPy
developSeveral major Python and statistical software packages leverage CmdStanPy or Stan models for their functionality:
- Prophet: A forecasting procedure for time series data using additive models with non-linear trends and seasonality.
- ArviZ: A package for exploratory analysis of Bayesian models, providing tools for posterior analysis, data storage, model checking, comparison, and diagnostics.
- BridgeStan: Provides efficient in-memory access (via Python, Julia, and R) to Stan model methods, including log densities, gradients, Hessians, and transforms.
C++ Toolchain Requirements for CmdStan
developTo compile Stan programs, you need a modern C++ compiler and GNU-Make. Requirements vary by OS:
- Linux: Requires
g++ 4.9.3or newer. GNU-Make is usually pre-installed. - MacOS: Requires Xcode and Xcode command line tools. Install them via
xcode-select --install. - Windows: Recommended toolchain is RTools 4.0 (which includes
g++ 8andMingw). You can install this automatically viacmdstanpy.install_cmdstan(compiler=True).
Note for PyStan users: If you use the RTools toolchain, install CmdStanPy in a separate virtual environment from PyStan to avoid conflicts.
- Linux: Requires
How CmdStanPy works
developCmdStanPy is a lightweight pure-Python interface to CmdStan. It does not interface directly with C++; instead, it calls compiled CmdStan executables.
Key characteristics include:
- Development vs. Production: By default, it favors development mode by storing output files on a temporary filesystem. However, all aspects of a run can be specified for production/distributed workflows.
- Modular Design: CmdStanPy is responsible for producing MCMC samples or point estimates. It is designed to be used alongside other packages for downstream analysis and visualization.
- Low Memory Overhead: It primarily tracks CmdStan input and output files, using minimal memory beyond what the underlying CmdStan process requires.
Use CmdStanModel for inference
developThe
CmdStanModelclass is the primary interface for managing a Stan program. It handles program compilation and provides several inference methods to obtain parameter estimates or posterior samples:sample(): Runs the HMC-NUTS sampler to produce posterior draws.optimize(): Produces a penalized maximum likelihood estimate (MLE) or maximum a posteriori (MAP) estimate.laplace_sample(): Draws from a Laplace approximation centered at the posterior mode found byoptimize().pathfinder(): Runs the Pathfinder variational inference to receive approximate posterior draws.variational(): Runs CmdStan’s automatic differentiation variational inference (ADVI) algorithm.generate_quantities(): Produces additional quantities of interest based on existing samples.
import cmdstanpy # Example workflow (conceptual) model = cmdstanpy.CmdStanModel(stan_file='model.stan') fit = model.sample(data=data_dict)Install CmdStanPy
developCmdStanPy can be installed via PyPI or Conda Forge. It has minimal Python dependencies, requiring only
numpyandpandas.# Via PyPI pip install cmdstanpy # Via Conda Forge conda install -c conda-forge cmdstanpyInstall CmdStanPy via PyPI (pip)
developYou can install the CmdStanPy package using
pip. Note that if you use this method, you must manually install CmdStan afterwards (see the 'Install CmdStan' section).To install the base package:
pip install --upgrade cmdstanpyTo install with optional dependencies, such as
xarrayfor n-dimensional labeled dataset outputs:pip install --upgrade cmdstanpy[all]Jupyter Notebook Users: If you use Jupyter, install
ipywidgetsto ensure progress bars (fromtqdm) display correctly in the browser.Configure fine-grained DEBUG logging to a file
developFor debugging purposes, you can interact directly with the
cmdstanpylogger to captureDEBUGlevel logs (which are hidden by default) and redirect them to a file. This involves accessing thecmdstanpylogger via theloggingmodule, clearing existing handlers, and attaching aFileHandler.import logging cmdstanpy_logger = logging.getLogger("cmdstanpy") cmdstanpy_logger.disabled = False # remove all existing handlers cmdstanpy_logger.handlers = [] cmdstanpy_logger.setLevel(logging.DEBUG) handler = logging.FileHandler('all.log') handler.setLevel(logging.DEBUG) handler.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s', "%H:%M:%S", ) ) cmdstanpy_logger.addHandler(handler) # Now running the model will write all logs to 'all.log' fit = model.sample(data=data_file, show_progress=False)Use project templates for CmdStanPy
developTo save time when starting new Bayesian statistical analysis or Stan-based Python projects, you can use community-maintained templates:
- bibat: A batteries-included template designed specifically for Bayesian statistical analysis projects.
- cookiecutter-cmdstanpy-wrapper: A cookiecutter template for integrating Stan models into Python packages. It includes support for pre-compiling models as part of the package distribution process.
Install CmdStan using `install_cmdstan`
developIf you installed CmdStanPy via PyPI or GitHub, you must install the CmdStan backend. The recommended method is using the
install_cmdstanfunction, which downloads CmdStan from GitHub and builds the necessary utilities. By default, it installs to~/.cmdstan.From Python
import cmdstanpy # Standard installation cmdstanpy.install_cmdstan() # On Windows: installs the C++ toolchain (RTools) as well cmdstanpy.install_cmdstan(compiler=True)From the Command Line
Linux or MacOS:
install_cmdstanWindows:
install_cmdstan --compilerCLI Options
--interactiveor-i: Runs the installation in an interactive prompt.-d <directory>: Overrides the default installation directory.-v <version>: Specifies a specific CmdStan version.
Example with custom directory and version:
install_cmdstan -d my_local_cmdstan -v 2.36.0import cmdstanpy cmdstanpy.install_cmdstan(compiler=True) # compiler=True is only valid on WindowsFit a Stan model using MCMC sampling
developTo perform Bayesian inference using Hamiltonian Monte Carlo (HMC), use the
samplemethod on aCmdStanModelinstance. This method returns aCmdStanMCMCobject.Data can be provided as:
- A filepath to a JSON file.
- A Python dictionary mapping variable names to values.
By default,
sampleruns 4 sampler chains.# Using a JSON data file data_file = os.path.join('users-guide', 'examples', 'bernoulli.data.json') fit = model.sample(data=data_file)