Anesthetic
by fundamental-physics
Use this skill when the user asks to "create corner plots", "visualize posteriors", "plot chains", "analyze nested sampling output", "plot marginal distributions", "compare prior and posterior", "make triangle plots", or work with posterior samples from PolyChord, MultiNest, UltraNest, Cobaya, or other Bayesian inference tools. Provides complete guidance for creating publication-quality posterior visualizations from nested sampling or MCMC chains.
Skill Details
Repository Files
7 files in this skill directory
name: anesthetic description: Use this skill when the user asks to "create corner plots", "visualize posteriors", "plot chains", "analyze nested sampling output", "plot marginal distributions", "compare prior and posterior", "make triangle plots", or work with posterior samples from PolyChord, MultiNest, UltraNest, Cobaya, or other Bayesian inference tools. Provides complete guidance for creating publication-quality posterior visualizations from nested sampling or MCMC chains.
Anesthetic
Overview
Anesthetic is a Python package for visualizing and analyzing posterior samples from Bayesian inference. It creates publication-quality corner plots, 1D/2D marginal distributions, and computes Bayesian statistics (evidence, KL divergence) from nested sampling or MCMC chains.
Key capabilities:
- Load chains from PolyChord, MultiNest, UltraNest, Cobaya, GetDist formats
- Create corner/triangle plots with KDE, histogram, or scatter representations
- Compare prior vs posterior distributions
- Compute log-evidence, KL divergence, model dimensionality
- Built on pandas DataFrames for easy parameter manipulation
Workflow position: This skill provides component (4) Visualization in the physics workflow.
Installation
First, ensure anesthetic is installed in your environment:
# Using uv (recommended)
uv pip install anesthetic
# Or using pip
pip install anesthetic
# Or using conda
conda install -c conda-forge anesthetic
Optional for faster KDE: uv pip install fastkde
Quick Start
from anesthetic import read_chains, make_2d_axes
import matplotlib.pyplot as plt
# Load posterior chains (auto-detects format)
samples = read_chains('path/to/chains_root')
# Create corner plot (two-step process)
fig, axes = make_2d_axes(['x0', 'x1', 'x2']) # Create axes first
samples.plot_2d(axes) # Then plot onto them
fig.savefig('corner.png')
plt.close(fig)
Important: Always create axes first with make_2d_axes() or make_1d_axes(), then pass them to plot_2d() or plot_1d(). The plot methods return axes, not (fig, axes) tuples.
Core Workflow
- Load chains -
read_chains()auto-detects format, or use format-specific readers - Select parameters - Choose which parameters to plot
- Create axes -
make_1d_axes()ormake_2d_axes() - Plot -
samples.plot_1d()orsamples.plot_2d() - Customize - Labels, colors, reference lines
Reference Documentation
Detailed documentation is split by topic:
- Loading data: See
references/loading-chains.mdfor all supported formats and creating samples from arrays - Plotting: See
references/plotting-guide.mdfor 1D/2D plots, plot kinds, and multi-chain comparisons - Customization: See
references/customization.mdfor labels, colors, axes, legends, and reference values - Statistics: See
references/statistics.mdfor Bayesian evidence, KL divergence, and MCMC diagnostics - Full API: See
references/api-reference.mdfor complete function signatures and options
Common Patterns
Basic Corner Plot
from anesthetic import read_chains, make_2d_axes
samples = read_chains('chains/run')
fig, axes = make_2d_axes(['param1', 'param2', 'param3'])
samples.plot_2d(axes, kind='kde')
fig.savefig('corner.png')
Prior vs Posterior Comparison
samples = read_chains('chains/run') # NestedSamples
prior = samples.prior()
fig, axes = make_2d_axes(['x0', 'x1', 'x2'])
prior.plot_2d(axes, kind='kde', label='Prior', alpha=0.5)
samples.plot_2d(axes, kind='kde', label='Posterior')
axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes)/2, len(axes)), loc='lower center')
Multiple Chain Comparison
samples1 = read_chains('chains/model1')
samples2 = read_chains('chains/model2')
fig, axes = make_2d_axes(['x0', 'x1'])
samples1.plot_2d(axes, kind='kde', label='Model 1')
samples2.plot_2d(axes, kind='kde', label='Model 2')
axes.iloc[-1, 0].legend()
Compute Bayesian Evidence
samples = read_chains('chains/run') # Must be NestedSamples
print(f"log(Z) = {samples.logZ():.2f}")
print(f"D_KL = {samples.D_KL():.2f}")
# With uncertainties
stats = samples.stats(nsamples=1000)
print(f"log(Z) = {stats['logZ'].mean():.2f} +/- {stats['logZ'].std():.2f}")
Plot Bayesian Statistics
# stats is a Samples object, so use anesthetic's plot_2d
stats = samples.stats(nsamples=1000)
fig, axes = make_2d_axes(['logZ', 'D_KL', 'd_G'])
stats.plot_2d(axes)
fig.savefig('stats_corner.png')
Add Truth Values
fig, axes = make_2d_axes(['x0', 'x1', 'x2'])
samples.plot_2d(axes)
truth = {'x0': 0.3, 'x1': 0.8, 'x2': 0.7}
axes.axlines(truth, color='red', linestyle='--')
axes.scatter(truth, marker='*', s=100, c='red')
Runnable Example
A complete example script is available at scripts/example_plots.py. Run it with:
python scripts/example_plots.py path/to/chains_root
This creates corner_plot.png, 1d_marginals.png, and prior_posterior.png.
Related Skills
Dbt Transformation Patterns
Master dbt (data build tool) for analytics engineering with model organization, testing, documentation, and incremental strategies. Use when building data transformations, creating data models, or implementing analytics engineering best practices.
Anndata
This skill should be used when working with annotated data matrices in Python, particularly for single-cell genomics analysis, managing experimental measurements with metadata, or handling large-scale biological datasets. Use when tasks involve AnnData objects, h5ad files, single-cell RNA-seq data, or integration with scanpy/scverse tools.
Xlsx
Spreadsheet toolkit (.xlsx/.csv). Create/edit with formulas/formatting, analyze data, visualization, recalculate formulas, for spreadsheet processing and analysis.
Tensorboard
Visualize training metrics, debug models with histograms, compare experiments, visualize model graphs, and profile performance with TensorBoard - Google's ML visualization toolkit
Deeptools
NGS analysis toolkit. BAM to bigWig conversion, QC (correlation, PCA, fingerprints), heatmaps/profiles (TSS, peaks), for ChIP-seq, RNA-seq, ATAC-seq visualization.
Scvi Tools
This skill should be used when working with single-cell omics data analysis using scvi-tools, including scRNA-seq, scATAC-seq, CITE-seq, spatial transcriptomics, and other single-cell modalities. Use this skill for probabilistic modeling, batch correction, dimensionality reduction, differential expression, cell type annotation, multimodal integration, and spatial analysis tasks.
Statsmodels
Statistical modeling toolkit. OLS, GLM, logistic, ARIMA, time series, hypothesis tests, diagnostics, AIC/BIC, for rigorous statistical inference and econometric analysis.
Scikit Survival
Comprehensive toolkit for survival analysis and time-to-event modeling in Python using scikit-survival. Use this skill when working with censored survival data, performing time-to-event analysis, fitting Cox models, Random Survival Forests, Gradient Boosting models, or Survival SVMs, evaluating survival predictions with concordance index or Brier score, handling competing risks, or implementing any survival analysis workflow with the scikit-survival library.
Neurokit2
Comprehensive biosignal processing toolkit for analyzing physiological data including ECG, EEG, EDA, RSP, PPG, EMG, and EOG signals. Use this skill when processing cardiovascular signals, brain activity, electrodermal responses, respiratory patterns, muscle activity, or eye movements. Applicable for heart rate variability analysis, event-related potentials, complexity measures, autonomic nervous system assessment, psychophysiology research, and multi-modal physiological signal integration.
Statistical Analysis
Statistical analysis toolkit. Hypothesis tests (t-test, ANOVA, chi-square), regression, correlation, Bayesian stats, power analysis, assumption checks, APA reporting, for academic research.
