pyABC: Distributed Likelihood-Free ABC-SMC Inference

repository·main·Indexed 42 days ago

https://github.com/icb-dcm/pyabc

A scalable ABC-SMC (Approximate Bayesian Computation - Sequential Monte Carlo) framework for likelihood-free parameter estimation in complex stochastic models. It supports parallel and distributed execution, integration with R and Julia, and features robust distance functions like AdaptivePNormDistance and PCMAD for handling outliers.

Tokens
24.9K
Snippets
79
Records
103
Agent score
53%

What's inside pyABC

  1. Overview of pyABC

    main
    pyABC is a massively parallel, distributed, and scalable ABC-SMC (Approximate Bayesian Computation - Sequential Monte Carlo) framework designed for parameter estimation of complex stochastic models. It implements state-of-the-art algorithms for efficient, accurate, and robust likelihood-free inference. While written in Python, it supports integration with R and Julia.
  2. What is pyABC and when to use it

    main

    pyABC is a package for Approximate Bayesian Computation (ABC) using a Sequential Monte Carlo (SMC) scheme. It is designed for likelihood-free parameter inference in scenarios where you have a forward simulator (a parametrized stochastic model) but cannot or do not want to explicitly define a likelihood function $p(data|parameter)$.

    Use pyABC when:

    • You have a parametrized stochastic simulator (e.g., a function using a random number generator).
    • You have observed experimental data or synthetically generated data.
    • You cannot analytically or efficiently calculate the likelihood function.
    • You need to perform Bayesian posterior estimation.

    Do NOT use pyABC when:

    • You are able to write down and efficiently calculate the likelihood function. In such cases, using the likelihood with a different inference technique is generally a better approach.
  3. What is pyABC?

    main

    pyABC is a framework designed for distributed, likelihood-free inference.

    It is used when you have a model and observed data and want to estimate the posterior distribution over the model parameters (i.e., determining the probability that specific parameters explain the observed data).

    Key Features:

    • Likelihood-Free: You do not need to analytically calculate the likelihood function. You only need a way to numerically draw samples from your model given a set of parameters.
    • Model Inversion: pyABC automates the process of 'inverting' your model to identify which parameters match the observed data.
    • Scalability: It is optimized to run efficiently on both multi-core local machines and distributed cluster setups.
    • Extensibility: The framework is designed to be easily extended for custom workflows.
  4. Overview of pyABC: Approximate Bayesian Computation

    main

    pyABC is a Python framework for Approximate Bayesian Computation (ABC), a likelihood-free parameter inference method. It is particularly useful when evaluating the likelihood function of a complex stochastic model is computationally infeasible.

    Core Functionality:

    • ABC-SMC Scheme: Implements a Sequential Monte-Carlo (SMC) algorithm that gradually reduces acceptance thresholds to improve posterior approximations.
    • Scalability: Provides efficient parallelization for multi-core and distributed systems, including dynamic scheduling for improved wall-time efficiency.
    • Modularity: Designed to be highly extensible, allowing users to plug in different simulators, distance metrics, and summary statistics.
    • Interoperability: Supports models written in Python, R, and Julia, as well as biochemical models in SBML/COPASI format and the PEtab inference standard (specifically for the AMICI ODE simulator).
  5. Advanced ABC Algorithms in pyABC

    main

    pyABC (v0.12+) includes several advanced algorithmic features to handle complex inference problems:

    Distance Metrics and Robustness

    • Adaptive Distance Scaling: Iteratively updates distance weights to normalize contributions from data points that vary on different scales.
    • Outlier Robustness: Implements methods to identify and reduce the impact of measurement errors (outliers) that the model does not account for.
    • Wasserstein Distances: Implements optimal transport-based distances, which can potentially circumvent the need for manual summary statistics.

    Summary Statistics and Data Informativeness

    • Regression-based Statistics: Uses inverse regression models (interfaced via scikit-learn) to identify informative data points. This includes support for linear regression, neural networks, and Gaussian processes.
    • Sensitivity Weights: Uses regression models to inform robust sensitivity weights that account for the informativeness of data.

    Inference Refinement

    • Handling Measurement Noise: Provides an exact inference scheme for ABC-SMC in the presence of measurement noise.
    • Predictive Acceptance Thresholds: Uses importance sampling to predict acceptance rate curves, helping to avoid local optima in the acceptance threshold sequence.
  6. Optimize serialization with cloudpickle

    main

    pyABC uses cloudpickle to serialize objects (including lambda functions) for transmission to remote workers.

    Warning for Developers: Large objects can significantly increase serialization time and memory usage. When defining functions to be run remotely, ensure they do not capture unnecessary large state from their parent scope. Instead of capturing a whole class instance, capture only the specific small attributes required for the computation.

    import cloudpickle as pickle
    import numpy as np
    
    class A:
       def __init__(self):
          self.big_arr = np.eye(10000)
          self.small_arr = np.zeros(2)
    
       def costly_function(self):
          # This captures the entire 'self' object, including big_arr
          def fun(x):
             print(self.small_arr, x)
          return fun
    
       def efficient_function(self):
          # This captures only the specific small attribute needed
          small_arr = self.small_arr
          def fun(x):
             print(small_arr, x)
          return fun
    
    a = A()
    
    # 'costly_function' results in a massive serialized object
    print(len(pickle.dumps(a.costly_function()))) 
    
    # 'efficient_function' results in a very small serialized object
    print(len(pickle.dumps(a.efficient_function()))) 
  7. Choose a sampling strategy in pyABC

    main

    pyABC provides several samplers to handle the computationally expensive parts of ABC (simulation, statistics, and distance calculation). Samplers are categorized by their execution environment and scheduling strategy:

    Scheduling Strategies

    • Static Scheduling (STAT): Minimizes total execution time. Used by ParticleParallel samplers, MappingSampler, and RedisStaticSampler.
    • Dynamic Scheduling (DYN): Minimizes wall-time and generally finishes faster. Used by EvalParallel samplers, DaskDistributedSampler, and ConcurrentFutureSampler.

    Sampler Types

    • Single-core: Use SingleCoreSampler for debugging or deterministic purposes. It executes sequentially.
    • Multi-core (Local):
      • MulticoreEvalParallelSampler: Implements DYN strategy. This is the default sampler. Highly efficient via forking (not recommended for Windows).
      • MulticoreParticleParallelSampler: Implements STAT strategy.
    • Distributed:
      • RedisEvalParallelSampler: Low overhead, supports "look-ahead mode" for proactive sampling. Best for fast function evaluations.
      • RedisStaticSampler: Implements STAT strategy for distributed settings.
      • DaskDistributedSampler: Better at handling worker failures/terminations, but has higher communication overhead. Not suitable for simulations running < 100ms.
    • Extensible/Generic:
      • MappingSampler: Uses a provided map implementation (e.g., multiprocessing.Pool.map or pyabc.sge.SGE.map).
      • ConcurrentFutureSampler: Uses any python.concurrent.futures.Executor (e.g., ProcessPoolExecutor or Dask).
  8. Supported execution environments in pyABC

    main

    pyABC is designed for high performance in parallel computing environments. It supports:

    • Multicore execution.
    • Distributed environments, including scientific computing clusters (e.g., SGE environments) and cloud deployments.

    Under the hood, pyABC can utilize several backend modes for distributed computing, such as:

    • Dask.distributed
    • Redis based brokers
    • IPython parallel
  9. Manual upload to PyPI

    main

    While PyPI uploads are automated via GitHub Actions upon publishing a new release tag, you can manually upload a version using setup.py to create a wheel and twine to upload it.

    1. Generate a wheel archive: python setup.py bdist_wheel
    2. Upload the resulting wheel using twine: twine upload dist/pyabc-x.y.z-py3-non-any.wheel (replace x.y.z with your actual version number).
    python setup.py bdist_wheel
    twine upload dist/pyabc-x.y.z-py3-non-any.wheel
  10. Cite pyABC (legacy versions)

    main

    For pyABC version < 0.8 or functionality not introduced in later versions, use the following BibTeX entry for the Klinger et al. (2018) paper.

    @article{klinger2018pyabc,
       title = {pyABC: distributed, likelihood-free inference},
       author = {Klinger, Emmanuel and Rickert, Dennis and Hasenauer, Jan},
       journal = {Bioinformatics},
       volume = {34},
       number = {20},
       pages = {3591--3593},
       year = {2018},
       publisher={Oxford University Press},
     }
  11. Migrate pyABC data stores using Alembic

    main

    When changing the storage format, you must increment the dataformat version in pyabc/storage/version.py and provide migration routines using Alembic.

    1. Install migration dependencies:

      pip install pyabc[migrate]
    2. Create a migration revision: Navigate to the pyabc.storage folder and run:

      alembic revision --rev-id VERSION -m 'SHORT CHANGE DESCRIPTION'
       Replace `VERSION` with the new version number from `pyabc/storage/version.py`.
    
       This creates a new file in `pyabc/storage/migrations/versions/` containing `upgrade()` and `downgrade()` functions which you must manually implement.
    
    3. **Apply migrations**:
       Users migrate their databases using the `abc-migrate` command, which wraps `alembic upgrade head` via `pyabc/storage/migrate.py:migrate`.
    
    pip install pyabc[migrate]
    alembic revision --rev-id VERSION -m 'SHORT CHANGE DESCRIPTION'
  12. Install pyABC for Jupyter notebooks

    main

    To run pyABC example notebooks locally, you need an installation of jupyter (pip install jupyter). If you are running notebooks online (e.g., on Google Colab), you must install pyabc within the environment.

    Note: Ensure your Python version is >= 3.8, as many pyABC features require it. If using Google Colab, be aware that environment constraints may affect compatibility.

    # install if not done yet
    !pip install pyabc --quiet