{"id":6615,"library":"emcee","title":"emcee","description":"emcee is an MIT licensed pure-Python implementation of Goodman & Weare's Affine Invariant Markov chain Monte Carlo (MCMC) Ensemble sampler. It is a widely used toolkit for Bayesian parameter estimation in scientific fields, particularly astronomy, and maintains an active release cadence with minor updates and bug fixes. [3, 6, 9]","status":"active","version":"3.1.6","language":"python","source_language":"en","source_url":"https://github.com/dfm/emcee","tags":["MCMC","sampling","Bayesian inference","statistics","astronomy","physics"],"install":[{"cmd":"pip install emcee","lang":"bash","label":"Install stable release"}],"dependencies":[{"reason":"Required for numerical operations and array handling.","package":"numpy","optional":false},{"reason":"Often used for optimization and statistical functions, and some internal fixes relate to SciPy compatibility (e.g., kstest).","package":"scipy","optional":true}],"imports":[{"symbol":"emcee","correct":"import emcee"},{"symbol":"EnsembleSampler","correct":"from emcee import EnsembleSampler"}],"quickstart":{"code":"import numpy as np\nimport emcee\n\n# Define the logarithm of the posterior probability density function\ndef log_prob(x, mu, cov):\n    diff = x - mu\n    return -0.5 * np.dot(diff, np.linalg.solve(cov, diff))\n\n# Set up the problem dimensions and parameters\nndim = 2  # Number of dimensions\nnwalkers = 32 # Number of MCMC walkers\n\n# True mean and covariance for the Gaussian\nnp.random.seed(42)\nmu_true = np.array([0.5, -0.2])\ncov_true = np.array([[1.0, 0.5], [0.5, 1.5]])\n\n# Initialize walkers in a small ball around the true mean\np0 = mu_true + 1e-3 * np.random.randn(nwalkers, ndim)\n\n# Instantiate the sampler\nsampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, args=(mu_true, cov_true))\n\n# Run the MCMC production chain\nstate = sampler.run_mcmc(p0, 100)\n# After burn-in, reset and run for more steps\nsampler.reset()\nstate = sampler.run_mcmc(state, 1000)\n\n# Get the chain of samples\nsamples = sampler.get_chain(flat=True)\n\nprint(f\"Mean acceptance fraction: {np.mean(sampler.acceptance_fraction):.3f}\")\nprint(f\"First 5 samples:\\n{samples[:5]}\")","lang":"python","description":"This quickstart demonstrates how to use `emcee` to sample a 2-dimensional Gaussian distribution. It defines a `log_prob` function for the posterior, initializes walkers, runs a burn-in phase, resets the sampler, and then runs the main MCMC chain to obtain samples. [2]"},"warnings":[{"fix":"Consult the `emcee` v3 documentation for the `EnsembleSampler` constructor and the `Moves` and `Parallelization` sections to adapt your code. For parallelization, use a `pool` object (e.g., from `multiprocessing`). [8]","message":"When upgrading from `emcee` v2.x to v3.x, several arguments to `EnsembleSampler` related to proposal control (`a`, `live_dangerously`) and parallelization (`threads`) were deprecated. These functionalities are now managed via the `moves` interface and the `pool` argument, respectively. [8]","severity":"breaking","affected_versions":"Upgrading from <3.0 to >=3.0"},{"fix":"Ensure your `log_prob_fn` includes both the log-prior and log-likelihood terms. For parameter values outside valid physical bounds, explicitly return `-np.inf` from `log_prob_fn`. [11]","message":"The `log_prob_fn` passed to `EnsembleSampler` must return the natural logarithm of the *posterior probability*, not just the likelihood. It should also return `-np.inf` if the parameters are unphysical or lead to a probability of zero. [2, 11]","severity":"gotcha","affected_versions":"All versions"},{"fix":"Initialize walkers by drawing from a small Gaussian ball around a reasonable guess (e.g., a maximum likelihood estimate) or from a broad, valid prior distribution. Ensure all initial positions have finite `log_prob` values. [11]","message":"Poor initialization of walkers can lead to slow convergence, biased results, or errors (e.g., 'Too few points to create valid contours' or math warnings). Walkers should be initialized in a region of non-zero probability. [15, 17, 18]","severity":"gotcha","affected_versions":"All versions"},{"fix":"If encountering unexpected behavior related to numerical operations or statistical tests, check `emcee`'s release notes for dependency-specific fixes and ensure your `numpy` and `scipy` versions are compatible with your `emcee` version. Upgrading all libraries to their latest stable versions is generally recommended.","message":"Specific versions of `emcee` have included compatibility fixes for `numpy` and `scipy`. For example, v3.1.6 fixed compatibility with older NumPy versions, and v3.1.4 addressed the updated `kstest` interface in SciPy 1.10. [12]","severity":"gotcha","affected_versions":"Potentially specific minor versions of `emcee` with older/newer `numpy`/`scipy` versions."}],"env_vars":null,"search_vec":"'3':51 '6':52 '9':53 'activ':42 'affin':15 'astronomi':38,59 'bayesian':31,56 'bug':49 'cadenc':44 'carlo':20 'chain':18 'emce':1,2 'ensembl':22 'estim':33 'field':36 'fix':50 'goodman':12 'implement':10 'infer':57 'invari':16 'licens':6 'maintain':40 'markov':17 'mcmc':21,54 'minor':46 'mit':5 'mont':19 'paramet':32 'particular':37 'physic':60 'pure':8 'pure-python':7 'python':9 'releas':43 'sampl':55 'sampler':23 'scientif':35 'statist':58 'toolkit':29 'updat':47 'use':28 'wear':13 'wide':27","created_at":"2026-04-15T18:35:31.222582+00:00","updated_at":"2026-04-16T14:48:40.867411+00:00","problems":[{"fix":"Initialize `emcee.EnsembleSampler` with `nwalkers` (number of walkers) greater than or equal to `2 * dim` (number of dimensions/parameters).","cause":"The `emcee` ensemble sampler requires the number of walkers to be at least twice the number of dimensions (parameters) in the problem being sampled for its affine-invariant algorithm to function correctly. [7, 10]","error":"ValueError: The number of walkers must be at least twice the dimension of the problem"},{"fix":"Move your `log_prob_fn` definition to the global scope of your Python script or module. If running on Windows, ensure your main execution block is guarded by `if __name__ == '__main__':`.","cause":"When using `emcee` with multiprocessing, the `log_prob_fn` (or `lnprob` in older examples) must be defined as a top-level, pickleable function in a module, particularly on Windows, where child processes cannot easily access functions defined within other functions or methods. [16]","error":"AttributeError: 'module' object has no attribute 'log_prob_fn' (or similar for 'lnprob')"},{"fix":"Replace calls to `sampler.run(...)` with `sampler.run_mcmc(...)` to start the sampling process.","cause":"The `emcee.EnsembleSampler` object does not have a method named `run`. The correct method to perform MCMC sampling is `run_mcmc`.","error":"AttributeError: 'EnsembleSampler' object has no attribute 'run'"},{"fix":"Manually set the multiprocessing context to 'spawn' before creating the pool. For example: `import multiprocessing; with multiprocessing.get_context('spawn').Pool() as pool: sampler = emcee.EnsembleSampler(..., pool=pool)`.","cause":"On certain systems or with complex models, the default 'fork' multiprocessing context can cause `emcee`'s `EnsembleSampler` to hang or stall when a `pool` is used for parallel execution. [12]","error":"emcee sampler stalls indefinitely with multiprocessing"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"3.1.6","cli_name":"","cli_version":null,"type":"library","homepage":"https://emcee.readthedocs.io","github":"https://github.com/dfm/emcee","docs":null,"changelog":null,"pypi":"https://pypi.org/project/emcee/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["data","ai-ml"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":null}}