MCPost: Monte Carlo Post-analysis Package
MCPost is a comprehensive Python package for post-analysis of Monte Carlo samples, providing tools for global sensitivity analysis (GSA) and Monte Carlo integration with modern packaging standards and extensive documentation.
Features
Global Sensitivity Analysis
- Multiple sensitivity metrics: Mutual Information, Distance Correlation, Permutation Importance
- Gaussian Process surrogates with Automatic Relevance Determination (ARD)
- Sobol' indices for variance-based sensitivity analysis
- Partial Dependence Plots for interpretable results
- Robust preprocessing with automatic constant column detection
Monte Carlo Integration
- Standard Monte Carlo integration with importance sampling
- Automatic integration with adaptive sampling strategies
- Flexible PDF specification for target and sampling distributions
Modern Package Features
- Type hints and comprehensive documentation
- Modular design with clean public APIs
- Optional dependencies for visualization and development
- Extensive testing with property-based tests
- Performance optimizations for large datasets
Installation
MCPost supports multiple installation methods to suit different use cases:
Basic Installation
For core functionality (GSA and integration without plotting):
pip install MC-post
Installation from Source
For the latest development version:
pip install git+https://github.com/zzhang0123/mcpost.git
Development Installation
For contributors and developers:
# Clone the repository
git clone https://github.com/mcpost/mcpost.git
cd mcpost
# Install in development mode with all dependencies
pip install -e .[dev]
# Run tests to verify installation
pytest
Quick Start
Global Sensitivity Analysis
MCPost provides comprehensive GSA capabilities with multiple sensitivity metrics:
import numpy as np
from mcpost import gsa_pipeline
# Define a simple test function
def polynomial_function(X):
"""
Simple polynomial: f(x1, x2, x3) = x1^2 + 2*x2 + 0.1*x3
We expect x2 to be most influential, x1 moderately influential,
and x3 to have minimal influence.
"""
x1, x2, x3 = X[:, 0], X[:, 1], X[:, 2]
return x1**2 + 2*x2 + 0.1*x3
# Generate parameter samples
n_samples = 1000
X = np.random.uniform(-1, 1, (n_samples, 3)) # 3 parameters in [-1, 1]
# Evaluate function
y = polynomial_function(X)
Y = y.reshape(-1, 1) # GSA expects 2D array
# Run comprehensive GSA analysis
# Run GSA analysis
param_names = ["x1", "x2", "x3"]
feature_names = ["polynomial"]
print("Running GSA analysis...")
results = gsa_pipeline(
X, Y,
param_names=param_names,
feature_names=feature_names,
scaler="minmax",
enable_sobol=True,
enable_gp=True,
enable_perm=True,
make_pdp=False, # Skip PDPs for this simple example
N_sobol=2048
)
# Display results
sensitivity_table = results["results"]["polynomial"]["table"]
print("\nSensitivity Analysis Results:")
print(sensitivity_table)
Reading the results: built-in sanity checks
MCPost's dangerous failure mode is not a crash but a plausible-looking wrong number, so every GSA run reports whether its own output can be trusted:
table, extras = gsa_for_target(X, y)
extras["surrogate_collapsed"] # True -> the Sobol indices are meaningless
extras["surrogate_pred_std"] # spread of the GP over the Saltelli design
extras["target_std"] # spread of the training target, for scale
extras["log_marginal_likelihood"] # how good the GP fit actually is
extras["ard_at_bounds"] # length scales resting on an optimisation bound
extras["sobol_out_of_range"] # True -> 0 <= S1 <= ST <= 1 was violated
A collapsed surrogate predicts a constant, so its variance decomposition reports
S1 = ST = 0 for every parameter. That reads as "nothing matters" and is
indistinguishable from a real result unless you check. MCPost warns; pass
on_surrogate_collapse="raise" to make it an error instead.
Length scales pinned to a bound are also flagged, at both ends. A parameter
reported at the maximum length scale is the GP saying "at least this
irrelevant" -- the derived 1/ARD_LS column (which feeds AggRank) then
reflects the bound rather than the data, and should not be quoted as a
measurement.
Monte Carlo Integration
Integration with Custom Distributions
# Define integration problem: E[x^2] where x ~ N(0,1)
# Analytical solution: 1.0
def integrand(theta):
"""Function to integrate: f(x) = x^2"""
return theta[:, 0]**2
def target_pdf(theta):
"""Standard normal PDF"""
return np.exp(-0.5 * theta[:, 0]**2) / np.sqrt(2 * np.pi)
print("Integration Problem: E[X^2] where X ~ N(0,1)")
print("Analytical solution: 1.0")
print()
# Method 1: Standard Monte Carlo
n_samples = 5000
theta_samples = np.random.normal(0, 1, (n_samples, 1))
f_values = integrand(theta_samples)
mc_result = monte_carlo_integral(theta_samples, f_values, target_pdf)
print("Standard Monte Carlo:")
print(f" Integral estimate: {mc_result['integral'][0]:.6f}")
print(f" Uncertainty: {mc_result['uncertainty'][0]:.6f}")
print(f" Effective sample size: {mc_result['effective_sample_size']:.0f}")
print(f" Error: {abs(mc_result['integral'][0] - 1.0):.6f}")
Documentation and Resources
Complete Documentation
- Getting Started Tutorial: Your first MCPost analysis
- GSA Deep Dive: Advanced sensitivity analysis
- Extension Guide: Creating custom methods
Numerical correctness
- CHANGELOG: v0.2.0 corrects several estimators that returned wrong numbers silently. Read the Numerical changes table before upgrading.
- Mutation-testing log: every guard is verified by breaking the implementation and confirming the test turns red, including the two mutations that stay green and why.
- Paper-products review: a worked audit of a published analysis built on MCPost -- which numbers survived, which were boundary or unseeded artefacts.
Quick References
Learning Resources
- Getting Started Tutorial: Your first MCPost analysis
- GSA Deep Dive: Advanced sensitivity analysis
Example Applications
- Climate Modeling: GSA for climate model parameters
- Integration Comparison: Monte Carlo integration examples
Requirements
Core Dependencies
- Python 3.8+
- NumPy
- Pandas >= 1.3.0
- Scikit-learn >= 1.0.0
- SciPy >= 1.7.0
- SALib >= 1.4.0
Optional Dependencies
- Visualization: matplotlib >= 3.5.0
- Development: pytest, hypothesis, black, mypy
- Documentation: sphinx, jupyter, nbsphinx
Development Setup
git clone https://github.com/zzhang0123/mcpost.git
cd mcpost
pip install -e .[dev]
pytest
Testing
MCPost includes a comprehensive test suite:
# Run all tests
pytest tests/
# Run specific test categories
pytest tests/test_gsa/ # GSA functionality tests
pytest tests/test_integration/ # Integration tests
pytest tests/test_utils/ # Utility tests
# Run property-based tests
pytest tests/ -k "property"
# Run with coverage
pytest tests/ --cov=mcpost --cov-report=html
License
This project is licensed under the MIT License - see the LICENSE file for details.
Citation
MCPost was developed for the following work. If you use MCPost in your research, please cite:
@ARTICLE{2026MNRAS.547ag509Z,
author = {{Zhang}, Zheng and {Chluba}, Jens and {Cepeda-Arroita}, Roke and {Rubi{\~n}o-Mart{\'\i}n}, Jos{\'e} Alberto},
title = "{Spectral signatures of spinning dust from grain ensembles in diverse environments: a combined theoretical and observational study}",
journal = {\mnras},
keywords = {methods: statistical, cosmic background radiation, radio continuum: ISM, Astrophysics of Galaxies, Cosmology and Nongalactic Astrophysics},
year = 2026,
month = apr,
volume = {547},
number = {4},
eid = {stag509},
pages = {stag509},
doi = {10.1093/mnras/stag509},
archivePrefix = {arXiv},
eprint = {2601.06270},
primaryClass = {astro-ph.GA},
adsurl = {https://ui.adsabs.harvard.edu/abs/2026MNRAS.547ag509Z},
adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}
Acknowledgments
MCPost builds upon several excellent open-source libraries:
- Scikit-learn for machine learning algorithms
- SALib for Sobol' sensitivity analysis
- SciPy for scientific computing (including distance correlation)
- NumPy for numerical computing
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mc_post-0.2.0.tar.gz.
File metadata
- Download URL: mc_post-0.2.0.tar.gz
- Upload date:
- Size: 240.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
40d91948f8b72b9ced3c9a9ebac6cbe110b3b50bae84a27e9c3486517cd5f5b5
|
|
| MD5 |
810de433d07b542befe14ab379c85b39
|
|
| BLAKE2b-256 |
615c7f8bfaacc533bb70b0a27cd1cfe108068b4281c2c43d9aa8744726726a33
|
Provenance
The following attestation bundles were made for mc_post-0.2.0.tar.gz:
Publisher:
release.yml on zzhang0123/mcpost
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mc_post-0.2.0.tar.gz -
Subject digest:
40d91948f8b72b9ced3c9a9ebac6cbe110b3b50bae84a27e9c3486517cd5f5b5 - Sigstore transparency entry: 2570194093
- Sigstore integration time:
-
Permalink:
zzhang0123/mcpost@e217e9d4ac83e184c26b2b4beea10325d079fb62 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/zzhang0123
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e217e9d4ac83e184c26b2b4beea10325d079fb62 -
Trigger Event:
push
-
Statement type:
File details
Details for the file mc_post-0.2.0-py3-none-any.whl.
File metadata
- Download URL: mc_post-0.2.0-py3-none-any.whl
- Upload date:
- Size: 66.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
75c34c6f7d8655acc44ecbba5e51359407df090a8f06d0ee7c6230463e94715c
|
|
| MD5 |
e85eee77bdfee6fa8eab50f7665b0d63
|
|
| BLAKE2b-256 |
b2cf4863a9e9dd956500f0b1f0b652777c7af90a953f254385e99ecc54a30e5f
|
Provenance
The following attestation bundles were made for mc_post-0.2.0-py3-none-any.whl:
Publisher:
release.yml on zzhang0123/mcpost
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mc_post-0.2.0-py3-none-any.whl -
Subject digest:
75c34c6f7d8655acc44ecbba5e51359407df090a8f06d0ee7c6230463e94715c - Sigstore transparency entry: 2570194417
- Sigstore integration time:
-
Permalink:
zzhang0123/mcpost@e217e9d4ac83e184c26b2b4beea10325d079fb62 -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/zzhang0123
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e217e9d4ac83e184c26b2b4beea10325d079fb62 -
Trigger Event:
push
-
Statement type: