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
Metadata
Release files for MC-post 0.2.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mc_post-0.2.1.tar.gz | 243.8 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mc_post-0.2.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 311.1 kB
Release files / mc_post-0.2.1.tar.gz
| Download URL | mc_post-0.2.1.tar.gz |
|---|---|
| Size | 243.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
adb4fce39e946adb0de5e573359ca9c6bd44c703171209f8be8a5b39698e795d
|
|
BLAKE2b-256 checksum How to use checksums |
78230f718710982e676604f93539a60a6d783f7a7da2aacc2c9b0d0501c491d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 23, 2026.
Transparency logRelease files / mc_post-0.2.1-py3-none-any.whl
| Download URL | mc_post-0.2.1-py3-none-any.whl |
|---|---|
| Size | 67.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ea3a0288a70900b2e8ac625339e58381110e4b28b90ae8503ba69aa741a7c80a
|
|
BLAKE2b-256 checksum How to use checksums |
a8d1f5b067b9f326b7fbec77ab801627df579624287fc69b619f5359e3d2c12d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 23, 2026.
Transparency log