Python interface to CmdStan that provides comprehensive access to the Stan compiler and all Bayesian inference algorithms.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Functions for compiling and formatting Stan programs, with support for custom compiler options and automatic dependency management. These functions handle the translation of Stan code into executable binaries.
Compile a Stan program file into an executable, with automatic dependency checking and custom compiler options.
def compile_stan_file(
src,
force=False,
stanc_options=None,
cpp_options=None,
user_header=None
):
"""
Compile a Stan program file to executable.
Parameters:
- src (str or PathLike): Path to Stan source file (.stan)
- force (bool): Force recompilation even if executable is up-to-date
- stanc_options (dict, optional): Options passed to stanc compiler
- cpp_options (dict, optional): Options passed to C++ compiler
- user_header (str or PathLike, optional): Path to user header file
Returns:
str: Path to compiled executable
Raises:
CompilerError: If compilation fails
FileNotFoundError: If source file not found
"""Usage Example:
import cmdstanpy as csp
# Basic compilation
exe_path = csp.compile_stan_file("my_model.stan")
# Force recompilation with optimization
exe_path = csp.compile_stan_file(
"my_model.stan",
force=True,
stanc_options={"O1": True},
cpp_options={"STAN_THREADS": True}
)
print(f"Compiled to: {exe_path}")Auto-format Stan code using the stanc formatter, with options for canonical syntax and line length control.
def format_stan_file(
stan_file,
overwrite_file=False,
canonicalize=False,
max_line_length=78,
backup=True,
stanc_options=None
):
"""
Format Stan program using stanc auto-formatter.
Parameters:
- stan_file (str or PathLike): Path to Stan file to format
- overwrite_file (bool): Save formatted code back to original file
- canonicalize (bool, str, or list): Canonicalize syntax elements
- True: canonicalize all supported elements
- str: specific element to canonicalize
- list: list of elements to canonicalize
- max_line_length (int): Maximum line length for wrapping
- backup (bool): Create backup file before overwriting (when overwrite_file=True)
- stanc_options (dict, optional): Additional stanc options
Returns:
None
Raises:
RuntimeError: If formatting fails
FileNotFoundError: If source file not found
"""Usage Example:
import cmdstanpy as csp
# Format file and print to console
csp.format_stan_file("messy_model.stan")
# Format and save back to file with backup
csp.format_stan_file(
"messy_model.stan",
overwrite_file=True,
canonicalize=True,
max_line_length=100,
backup=True
)
# Canonicalize specific syntax elements
csp.format_stan_file(
"model.stan",
canonicalize=["parentheses", "braces"]
)Options passed to the Stan compiler (stanc) that control parsing, optimization, and code generation.
Common stanc options:
"O" (bool): Enable all optimizations"O0" (bool): Disable optimizations"O1" (bool): Enable basic optimizations"Oexperimental" (bool): Enable experimental optimizations"warn-pedantic" (bool): Enable pedantic warnings"warn-uninitialized" (bool): Warn about uninitialized variables"auto-format" (bool): Apply auto-formatting"max-line-length" (int): Maximum line length for formatting"canonicalize" (str or list): Elements to canonicalizeExample:
stanc_opts = {
"O1": True,
"warn-pedantic": True,
"warn-uninitialized": True
}
exe_path = csp.compile_stan_file("model.stan", stanc_options=stanc_opts)Options passed to the C++ compiler that control binary optimization and feature flags.
Common C++ options:
"STAN_THREADS" (bool): Enable threading support"STAN_MPI" (bool): Enable MPI support"STAN_OPENCL" (bool): Enable OpenCL support"USER_HEADER" (str): Path to user header fileExample:
cpp_opts = {
"STAN_THREADS": True,
"USER_HEADER": "my_functions.hpp"
}
exe_path = csp.compile_stan_file("model.stan", cpp_options=cpp_opts)Include custom C++ functions in Stan models using user headers.
# my_functions.hpp
"""
#include <stan/math.hpp>
namespace my_model_namespace {
template <typename T0>
inline T0 my_custom_function(const T0& x) {
return stan::math::exp(x) / (1.0 + stan::math::exp(x));
}
}
"""
# Compile with user header
exe_path = csp.compile_stan_file(
"model_with_custom_functions.stan",
user_header="my_functions.hpp"
)Enable within-chain threading for models with reduce_sum or map_rect operations.
# Compile with threading support
exe_path = csp.compile_stan_file(
"parallel_model.stan",
cpp_options={"STAN_THREADS": True}
)Control Stan compiler optimizations for different use cases.
# Debug build (no optimization, faster compilation)
debug_exe = csp.compile_stan_file(
"model.stan",
stanc_options={"O0": True}
)
# Production build (full optimization)
prod_exe = csp.compile_stan_file(
"model.stan",
stanc_options={"O": True}
)
# Experimental optimizations (may be unstable)
experimental_exe = csp.compile_stan_file(
"model.stan",
stanc_options={"Oexperimental": True}
)Compile multiple models with consistent settings.
import os
from pathlib import Path
models_dir = Path("./stan_models")
exe_dir = Path("./executables")
exe_dir.mkdir(exist_ok=True)
compile_options = {
"stanc_options": {"O1": True, "warn-pedantic": True},
"cpp_options": {"STAN_THREADS": True}
}
for stan_file in models_dir.glob("*.stan"):
print(f"Compiling {stan_file.name}...")
exe_path = csp.compile_stan_file(stan_file, **compile_options)
# Move executable to organized directory
exe_name = stan_file.stem + (".exe" if os.name == "nt" else "")
os.rename(exe_path, exe_dir / exe_name)Install with Tessl CLI
npx tessl i tessl/pypi-cmdstanpy