{"id":1425,"library":"cmdstanpy","title":"CmdStanPy","description":"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.","status":"active","version":"1.3.0","language":"en","source_language":"en","source_url":"https://github.com/stan-dev/cmdstanpy","tags":["stan","bayesian-statistics","mcmc","statistical-modeling","probabilistic-programming"],"install":[{"cmd":"pip install cmdstanpy","lang":"bash","label":"Install CmdStanPy Python package"}],"dependencies":[{"reason":"CmdStanPy 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.","package":"CmdStan","optional":false}],"imports":[{"symbol":"CmdStanModel","correct":"from cmdstanpy import CmdStanModel"},{"note":"Used to automatically download and set up the CmdStan C++ library.","symbol":"install_cmdstan","correct":"from cmdstanpy import install_cmdstan"},{"note":"Used to explicitly point CmdStanPy to an existing CmdStan installation.","symbol":"set_cmdstan_path","correct":"from cmdstanpy import set_cmdstan_path"}],"quickstart":{"code":"import os\nimport shutil\nfrom cmdstanpy import CmdStanModel, install_cmdstan, set_cmdstan_path\n\n# --- Step 1: Ensure CmdStan is installed and path is set ---\n# This is crucial. If CMDSTAN_PATH environment variable is not set,\n# CmdStanPy will attempt to download and install CmdStan to '~/.cmdstan'.\n# You can also manually set the path via set_cmdstan_path().\ntry:\n    set_cmdstan_path(os.environ.get('CMDSTAN_PATH', ''))\nexcept ValueError:\n    print(\"CmdStan path not explicitly set or found. Attempting automatic installation...\")\n    install_cmdstan()\n    print(f\"CmdStan installed to: {os.path.join(os.path.expanduser('~'), '.cmdstan')}\")\n\n# --- Step 2: Define a Stan model ---\nstan_code = \"\"\"\ndata {\n  int<lower=0> N;\n  array[N] int<lower=0,upper=1> y;\n}\nparameters {\n  real<lower=0,upper=1> theta;\n}\nmodel {\n  y ~ bernoulli(theta);\n}\n\"\"\"\nstan_filepath = \"bernoulli.stan\"\nwith open(stan_filepath, \"w\") as f:\n    f.write(stan_code)\n\ntry:\n    # --- Step 3: Compile the Stan model ---\n    # This creates an executable that CmdStanPy will call.\n    model = CmdStanModel(stan_file=stan_filepath)\n    print(f\"Stan model compiled to: {model.exe_file}\")\n\n    # --- Step 4: Prepare data for the model ---\n    data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}\n\n    # --- Step 5: Fit the model using MCMC sampling ---\n    print(\"Starting MCMC sampling...\")\n    fit = model.sample(data=data, chains=2, iter_sampling=500, iter_warmup=500, seed=42)\n    print(\"MCMC sampling complete.\")\n\n    # --- Step 6: Summarize and inspect results ---\n    print(\"\\nPosterior summary statistics:\")\n    print(fit.summary())\n\n    # Access posterior draws as a pandas DataFrame\n    # print(\"\\nFirst 5 rows of posterior draws:\")\n    # print(fit.draws_pd().head())\n\nexcept Exception as e:\n    print(f\"An error occurred during CmdStanPy execution: {e}\")\nfinally:\n    # --- Step 7: Clean up generated files ---\n    if os.path.exists(stan_filepath):\n        os.remove(stan_filepath)\n    # CmdStan installation is usually kept, so no cleanup for it here.\n    print(\"Cleanup complete.\")","lang":"python","description":"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."},"warnings":[{"fix":"Consult CmdStanPy documentation for current deprecations (e.g., replace `output_basename` with `output_dir`) and update code accordingly.","message":"CmdStanPy 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.","severity":"breaking","affected_versions":"All 1.x versions (pre-2.0)"},{"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()`.","message":"CmdStanPy 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()`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Replace `output_basename='my_output'` with `output_dir='path/to/output'` (which defaults to a temporary directory if not specified).","message":"The `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.","severity":"deprecated","affected_versions":"Introduced in 1.x, will be removed in 2.0"},{"fix":"Upgrade CmdStanPy to version 1.2.4 or newer to ensure compatibility with CmdStan 2.35 and later versions.","message":"Versions 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.","severity":"gotcha","affected_versions":"<1.2.4"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}