Registry / data / emcee
library3.1.6pypypi✓ verified 86d ago

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]

pip install emcee
INSTALL
IMPORT
SIG · EMCEE
E
emcee
datapythonv3.1.6
Install
3.6s avg
Import
292ms
Disk
89MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.1.6 · 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.920 runs
installs and imports cleanly · install 0.0s · import 0.291s · 89.8MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.6s · import 0.292s · 86MB
89MB installed
● package 89MB
Code
Verified usage

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

emcee
import emcee
EnsembleSampler
from emcee import EnsembleSampler

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]

import numpy as np import emcee # Define the logarithm of the posterior probability density function def log_prob(x, mu, cov): diff = x - mu return -0.5 * np.dot(diff, np.linalg.solve(cov, diff)) # Set up the problem dimensions and parameters ndim = 2 # Number of dimensions nwalkers = 32 # Number of MCMC walkers # True mean and covariance for the Gaussian np.random.seed(42) mu_true = np.array([0.5, -0.2]) cov_true = np.array([[1.0, 0.5], [0.5, 1.5]]) # Initialize walkers in a small ball around the true mean p0 = mu_true + 1e-3 * np.random.randn(nwalkers, ndim) # Instantiate the sampler sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, args=(mu_true, cov_true)) # Run the MCMC production chain state = sampler.run_mcmc(p0, 100) # After burn-in, reset and run for more steps sampler.reset() state = sampler.run_mcmc(state, 1000) # Get the chain of samples samples = sampler.get_chain(flat=True) print(f"Mean acceptance fraction: {np.mean(sampler.acceptance_fraction):.3f}") print(f"First 5 samples:\n{samples[:5]}")
Debug
Known issues
breakingWhen 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]
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]
affects: Upgrading from <3.0 to >=3.0
gotchaThe `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]
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]
affects: All versions
gotchaPoor 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]
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]
affects: All versions
gotchaSpecific 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]
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.
affects: Potentially specific minor versions of `emcee` with older/newer `numpy`/`scipy` versions.
Errors
Common errors & fixes
ValueError: The number of walkers must be at least twice the dimension of the problem
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]
fix
Initialize `emcee.EnsembleSampler` with `nwalkers` (number of walkers) greater than or equal to `2 * dim` (number of dimensions/parameters).
AttributeError: 'module' object has no attribute 'log_prob_fn' (or similar for 'lnprob')
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]
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__':`.
AttributeError: 'EnsembleSampler' object has no attribute 'run'
The `emcee.EnsembleSampler` object does not have a method named `run`. The correct method to perform MCMC sampling is `run_mcmc`.
fix
Replace calls to `sampler.run(...)` with `sampler.run_mcmc(...)` to start the sampling process.
emcee sampler stalls indefinitely with multiprocessing
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]
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)`.
Upgrade
Version history
3.1.6latest on PyPI · released Apr 19, 2024
Audit
Dependencies
numpyrequiredRequired for numerical operations and array handling.
scipyoptionalOften used for optimization and statistical functions, and some internal fixes relate to SciPy compatibility (e.g., kstest).
Agent activity
29 hits · last 30 days
node
26
Meta
1
Amazon
1
OpenAI (training)
1
Resources
emcee — pip install emcee · libregistry