### Install anesthetic from GitHub Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Installs the anesthetic library directly from its GitHub repository. This involves cloning the repository and then installing it using a Python setup script. ```bash git clone https://github.com/handley-lab/anesthetic cd anesthetic python -m pip install . ``` -------------------------------- ### Install anesthetic test suite Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Installs the necessary packages to run the test suite for anesthetic. This includes installing anesthetic with its test dependencies. ```bash export MPLBACKEND=Agg # only necessary for OSX users python -m pip install "[test]" python -m pytest flake8 anesthetic tests pydocstyle --convention=numpy anesthetic ``` -------------------------------- ### Import anesthetic and Load Samples Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Imports necessary functions from the anesthetic library and loads sample data for plotting. Requires the 'anesthetic' library to be installed and example data to be accessible. ```python from anesthetic import read_chains, make_1d_axes, make_2d_axes samples = read_chains("../../tests/example_data/pc") ``` -------------------------------- ### Build local documentation Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Builds a local copy of the anesthetic documentation. This requires Sphinx and numpydoc to be installed, and involves running make commands in the docs directory. ```bash python -m pip install "[all,docs]" cd docs make html ``` -------------------------------- ### Install anesthetic via pip Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Installs the anesthetic library using pip, the standard Python package installer. This is a common method for installing Python packages. ```bash pip install anesthetic ``` -------------------------------- ### Plotting Marginalized 2D Posteriors with Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/quickstart.rst Creates a plot visualizing marginalized 2D posteriors and their prior distributions. It reads chain data, calculates the prior, defines parameters, generates 2D axes, and plots both the prior and posterior distributions. Requires the 'anesthetic' library. Input is the file path to chain data and parameter names. Output is a matplotlib figure displaying 2D posterior and prior plots. ```python from anesthetic import read_chains, make_2d_axes samples = read_chains("../../tests/example_data/pc_250") prior = samples.prior() params = ['x0', 'x1', 'x2', 'x3', 'x4'] fig, axes = make_2d_axes(params, figsize=(6, 6), facecolor='w') prior.plot_2d(axes, alpha=0.9, label="prior") samples.plot_2d(axes, alpha=0.9, label="posterior") axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes)/2, len(axes)), loc='lower center', ncols=2) ``` -------------------------------- ### Install anesthetic via conda Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Installs the anesthetic library using conda, a package and environment management system. This command installs from the handley-lab channel. ```bash conda install -c handley-lab anesthetic ``` -------------------------------- ### Clone anesthetic Repository Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst This command clones the anesthetic Git repository from GitHub. It is a prerequisite for downloading example data. ```console git clone https://github.com/handley-lab/anesthetic.git ``` -------------------------------- ### Plotting Marginalized 1D Posteriors with Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/quickstart.rst Generates a plot showing marginalized 1D posteriors using both KDE and histogram representations. It reads chain data, defines parameters, creates 1D axes, and plots the distributions. Dependencies include 'anesthetic' library. Inputs are file paths to chain data and parameter names. Outputs a matplotlib figure with 1D posterior plots. ```python from anesthetic import read_chains, make_1d_axes samples = read_chains("../../tests/example_data/pc") params = ['x0', 'x1', 'x2', 'x3', 'x4'] fig, axes = make_1d_axes(params, figsize=(6, 1.8), facecolor='w', ncol=5) samples.plot_1d(axes, label="default: kind='kde_1d'") samples.plot_1d(axes, kind='hist_1d', color='C0', alpha=0.5, zorder=0, label="kind='hist_1d'") axes['x0'].legend(bbox_to_anchor=(2.5, 1), loc='lower center', ncol=2) ``` -------------------------------- ### Calculating and Plotting Nested Sampling Statistics with Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/quickstart.rst Computes and plots key Bayesian statistics from nested sampling data, including log evidence, KL divergence, and Gaussian model dimensionality. It reads two sets of chain data, calculates their respective statistics, defines the statistics parameters, creates 2D axes, and plots the results for comparison. Requires the 'anesthetic' library. Inputs are file paths to chain data. Outputs a matplotlib figure with comparative statistics plots. ```python from anesthetic import read_chains, make_2d_axes samples1 = read_chains("../../tests/example_data/pc") samples2 = read_chains("../../tests/example_data/pc_250") stats1 = samples1.stats(nsamples=2000) stats2 = samples2.stats(nsamples=2000) params = ['logZ', 'D_KL', 'logL_P', 'd_G'] fig, axes = make_2d_axes(params, figsize=(6, 6), facecolor='w', upper=False) stats1.plot_2d(axes, label="model 1") stats2.plot_2d(axes, label="model 2") axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes), len(axes)), loc='upper right') ``` -------------------------------- ### Split MCMC Chains using Groupby Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Illustrates how to split MCMC samples into individual chains using the `groupby` method on the 'chain' parameter. This is useful for analyzing correlations and potential differences between parallel MCMC runs. It demonstrates getting specific groups and resetting indices. ```python from anesthetic import read_chains, make_2d_axes mcmc_samples = read_chains("../../tests/example_data/cb") chains = mcmc_samples.groupby(('chain', '$n_\mathrm{chain}$'), group_keys=False) chain1 = chains.get_group(1) chain2 = chains.get_group(2).reset_index(drop=True) ``` -------------------------------- ### Plot MCMC Samples Before and After Burn-in Removal Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Visualizes the effect of burn-in removal on MCMC samples. This example plots the 2D projections of MCMC chains before and after removing burn-in samples, highlighting the difference in convergence indicated by the Gelman-Rubin statistic. ```python from anesthetic import read_chains, make_2d_axes nested_samples = read_chains("../../tests/example_data/pc") nested_samples['y'] = nested_samples['x1'] * nested_samples['x0'] nested_samples.set_label('y', '$y=x_0 \cdot x_1$') ``` -------------------------------- ### Launch Anesthetic GUI from Console Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/gui.rst Launches the Anesthetic GUI by specifying the path to a nested sampling run file. Ensure the file follows a structure compatible with PolyChord, MultiNest, or UltraNest. ```console $ anesthetic ``` -------------------------------- ### Launch Anesthetic GUI Programmatically with Python Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/gui.rst Launches the Anesthetic GUI by programmatically loading nested sampling data using the NestedSamples class from the anesthetic library. This method requires manual specification of data, logL, and logL_birth arrays. ```python import numpy as np import matplotlib.pyplot as plt from anesthetic import NestedSamples # Set up `data`, `logL`, and `logL_birth` file_path = "../../tests/example_data/pc_dead-birth.txt" file_data = np.loadtxt(file_path) data, logL, logL_birth = np.split(file_data, [-2, -1], axis=1) samples = NestedSamples(data=data, logL=logL, logL_birth=logL_birth) samples.gui() plt.show() ``` -------------------------------- ### Launch Nested Sampling GUI (Python) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Launches an interactive plot (GUI) that allows replaying a nested sampling run after the fact. This function is part of the anesthetic.samples.NestedSamples class and provides a visual interface for exploring the sampling process. ```python nested_samples.gui() ``` -------------------------------- ### Read and Prepare Nested Sampling Chains Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Illustrates how to read MCMC chains for nested sampling analysis using `anesthetic.read_chains`. It also demonstrates how to create derived parameters and set labels for them, preparing the data for further analysis and plotting. ```python prior_samples = nested_samples.prior() ``` -------------------------------- ### Launch Interactive GUI for Chains in Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Launches an interactive graphical user interface for exploring nested sampling or MCMC chains using the anesthetic library. Allows dynamic plotting and parameter selection. Can specify parameters to explore. ```python from anesthetic import read_chains samples = read_chains('chains/nested_run') # Launch interactive GUI plotter = samples.gui() # Opens matplotlib window with parameter selection and dynamic plotting # Specify parameters to explore plotter = samples.gui(params=['x0', 'x1', 'x2', 'x3']) # Command-line usage (equivalent) # $ anesthetic chains/nested_run ``` -------------------------------- ### Execute Python GUI Script from Console Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/gui.rst Executes a Python script that programmatically launches the Anesthetic GUI. This is useful for custom data loading and visualization. ```console $ python my_anesthetic_gui_script.py ``` -------------------------------- ### Create Derived Parameters in Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Shows how to create a new derived parameter ('y') by performing element-wise multiplication of two existing parameters ('x0' and 'x1') within an anesthetic Samples object. It also demonstrates setting a LaTeX-formatted label for the new parameter and plotting it. ```python samples['y'] = samples['x1'] * samples['x0'] samples.set_label('y', '$y=x_0 \cdot x_1$') samples.plot_2d(['x0', 'x1', 'y']) ``` -------------------------------- ### Pass Data Directly to anesthetic Samples Class Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Creates an anesthetic.samples.Samples object by passing data, weights, and column names directly. This is useful for custom or pre-processed data. ```python import numpy as np from scipy.stats import multivariate_normal as mvn from anesthetic.samples import Samples num_samples = 1000 # number of samples num_dim = 2 # number of parameters/dimensions params = ['a', 'b'] data = np.random.uniform(-5, 5, size=(num_samples, num_dim)) weights = mvn.pdf(data, mean=[0, 0], cov=np.diag([1, 1])) samples = Samples(data, weights=weights, columns=params) ``` -------------------------------- ### Define and Plot New Parameters with Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst This snippet demonstrates how to load samples using `anesthetic.read_chains`, define a new parameter by transforming an existing one (omegabh2 to omegab), and then create a 1D plot of the new parameter. It requires the `anesthetic` library and assumes samples are loaded from a file root. ```python from anesthetic import read_chains samples = read_chains(file_root) # Load the samples label = 'omegab' tex = '$\\Omega_b$' h = (samples.H0/100) samples[(label, tex)] = samples.omegabh2/h**2 # Define omegab samples.plot_1d('omegab') # Simple 1D plot ``` -------------------------------- ### Read PolyChord Chain Files with anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Reads PolyChord chain files into an anesthetic.samples.NestedSamples object. Assumes the path provided points to the root directory of the PolyChord output. ```python from anesthetic import read_chains samples = read_chains("anesthetic/tests/example_data/pc") ``` -------------------------------- ### Read Cobaya Chain Files with anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Reads Cobaya chain files into an anesthetic.samples.MCMCSamples object and removes burn-in. Assumes the path provided points to the root directory of the Cobaya output. ```python from anesthetic import read_chains samples = read_chains("anesthetic/tests/example_data/cb").remove_burn_in(burn_in=0.1) ``` -------------------------------- ### Read UltraNest Chain Files with anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Reads UltraNest chain files into an anesthetic.samples.NestedSamples object. Assumes the path provided points to the root directory of the UltraNest output. ```python from anesthetic import read_chains samples = read_chains("anesthetic/tests/example_data/un") ``` -------------------------------- ### Convert anesthetic Samples to GetDist Format Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Converts anesthetic NestedSamples or MCMCSamples objects to a format compatible with GetDist for use in other plotting pipelines. Requires importing anesthetic.convert.to_getdist. ```python from anesthetic.convert import to_getdist getdist_samples = to_getdist(samples) ``` -------------------------------- ### Read NestedFit Chain Files with anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Reads NestedFit chain files into an anesthetic.samples.NestedSamples object. Assumes the path provided points to the root directory of the NestedFit output. ```python from anesthetic import read_chains samples = read_chains("anesthetic/tests/example_data/nf") ``` -------------------------------- ### Plot MCMC Chains for Burn-in Analysis Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Visualizes the 'x0' parameter from two separate MCMC chains ('chain1' and 'chain2') as line plots to highlight the initial burn-in phase. This helps in identifying and assessing the convergence of the MCMC runs. ```python fig, ax = plt.subplots(figsize=(5, 3)) ax = chain1.x0.plot.line(alpha=0.7, label="Chain 1") ax = chain2.x0.plot.line(alpha=0.7, label="Chain 2") ax.set_ylabel(chain1.get_label('x0')) ax.set_xlabel("sample") ax.legend() ``` -------------------------------- ### Anesthetic Project Command-Line Usage Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst This command-line snippet shows how to search for words containing 'nest' within the system's dictionary file. This is presented as a lighthearted way to explain the origin of the 'anesthetic' project name, not as a core functionality of the library itself. ```bash grep nest /usr/share/dict/words ``` -------------------------------- ### Read Chains Data with Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Reads MCMC chains from a specified file path using the `anesthetic.read_chains` function. This function is essential for loading data into the `anesthetic` framework for further analysis. It returns an `anesthetic.samples.Samples` object. ```python from anesthetic import read_chains, make_2d_axes samples = read_chains("../../tests/example_data/pc_250") ``` -------------------------------- ### Run anesthetic script Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst This command-line script allows for an interactive view of a nested sampling run. It takes the root name of the nested sampling file as an argument. ```bash $ anesthetic ``` -------------------------------- ### Calculate and Plot Summary Statistics Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Demonstrates the calculation of various summary statistics (median, mean, std, min, quantile) for parameters within an anesthetic Samples object. It then visualizes these statistics alongside the parameter distributions using `anesthetic.samples.Samples.plot_2d` and custom line/span annotations. ```python x0_median = samples.x0.median() x1_mean = samples.x1.mean() x1_std = samples.x1.std() x2_min = samples.x2.min() x2_95percentile = samples.x2.quantile(q=0.95) fig, axes = make_2d_axes(['x0', 'x1', 'x2'], upper=False) samples.plot_2d(axes, label=None) axes.axlines({'x0': x0_median}, c='C1', label="median") axes.axlines({'x1': x1_mean}, c='C2', label="mean") axes.axspans({'x1': (x1_mean-x1_std, x1_mean+x1_std)}, c='C2', alpha=0.3, label="mean+-std") axes.axspans({'x2': (x2_min, x2_95percentile)}, c='C3', alpha=0.3, label="95 percentile") axes.iloc[0, 0].legend(bbox_to_anchor=(1, 1), loc='lower right') axes.iloc[1, 1].legend(bbox_to_anchor=(1, 1), loc='lower right') axes.iloc[2, 2].legend(bbox_to_anchor=(1, 1), loc='lower right') ``` -------------------------------- ### Load anesthetic Samples from CSV Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Loads previously saved anesthetic samples from a CSV file into the appropriate anesthetic class (Samples, MCMCSamples, or NestedSamples). Requires using pandas.read_csv. ```python from pandas import read_csv from anesthetic import Samples # or MCMCSamples, or NestedSamples samples = Samples(read_csv("filename.csv")) ``` -------------------------------- ### Plot Prior and Posterior Distributions Together Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Demonstrates plotting both prior and posterior distributions from nested sampling results on the same axes. This visualization helps in understanding how the sampling process has explored the parameter space, including derived parameters with potentially non-uniform priors. -------------------------------- ### Calculate Gelman-Rubin Statistic for MCMC Convergence Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Shows how to compute the modified Gelman-Rubin statistic (R-1) to assess MCMC convergence. It supports calculating the statistic for all parameters or on a per-parameter basis using `per_param='par'` or `per_param='cov'`. The statistic helps identify chains that have not converged. ```python fig, axes = make_2d_axes(['x0', 'x1'], figsize=(5, 5)) mcmc_samples.plot_2d(axes, alpha=0.7, label="Before burn-in removal, $R-1=%.3f$" % Rminus1_old) mcmc_burnout.plot_2d(axes, alpha=0.7, label="After burn-in removal, $R-1=%.3f$" % Rminus1_new) axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes)/2, len(axes)), loc='lower center') ``` -------------------------------- ### Load anesthetic Samples from HDF5 Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Loads previously saved anesthetic samples from an HDF5 file using anesthetic.read_hdf. It's crucial to use this function instead of pandas.read_hdf to preserve functionality. ```python from anesthetic import read_hdf samples = read_hdf("filename.h5", "samples") ``` -------------------------------- ### Calculate Prior Distribution from Nested Samples Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Shows how to compute the prior distribution from nested sampling results using the `.prior()` method. This is useful for comparing the prior and posterior distributions, especially for derived parameters. The `.prior()` method is a shorthand for `.set_beta(beta=0)`. ```python fig, axes = make_2d_axes(['x0', 'x1', 'y']) prior_samples.plot_2d(axes, label="prior") nested_samples.plot_2d(axes, label="posterior") axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes)/2, len(axes)), loc='lower center', ncol=2) ``` -------------------------------- ### Save and Load Samples in HDF5/CSV with Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Exports and imports sample data using HDF5 and CSV formats with the anesthetic library. HDF5 preserves metadata, weights, and labels, while CSV is suitable for interoperability with other tools. Supports saving statistics. ```python from anesthetic import read_chains, read_hdf samples = read_chains('chains/nested_run') # Save to HDF5 (preserves all metadata, weights, labels) samples.to_hdf('output.h5', key='nested_samples') # Load from HDF5 loaded = read_hdf('output.h5', key='nested_samples') print(type(loaded)) # print(f"logZ preserved: {loaded.logZ():.2f}") # Save multiple datasets to same HDF5 file samples.to_hdf('output.h5', key='run1') samples.to_hdf('output.h5', key='run2', mode='a') # mode='a' for append # Export to CSV (for use with other tools) samples.to_csv('samples.csv') # Read CSV (can specify sample type) from anesthetic import read_csv csv_samples = read_csv('samples.csv') # Save statistics stats = samples.stats(nsamples=1000) stats.to_csv('statistics.csv') stats.to_hdf('output.h5', key='statistics') ``` -------------------------------- ### Plotting Parameters on Log-Scale in Anesthetic (1D) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Illustrates how to plot individual parameters on a logarithmic scale for 1D plots in Anesthetic. This is controlled by the 'logx' keyword argument in 'make_1d_axes' or 'plot_1d', enabling the visualization of data spanning several orders of magnitude. It requires a list of parameter names and a Samples object. ```python fig, axes = make_1d_axes(['x0', 'x1', 'x2', 'x3'], logx=['x2']) samples.plot_1d(axes, label="'x2' on log-scale") axes['x2'].legend() ``` -------------------------------- ### 2D Plotting with Different Kinds in Anesthetic Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Demonstrates how to create 2D plots using anesthetic.samples.Samples.plot_2d with varying 'kinds' for diagonal, lower, and upper triangle plots. This allows for different visualizations like KDE and histograms on different parts of the plot. It requires a Samples object and a DataFrame of Axes. ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2', 'x3', 'x4']) samples.plot_2d(axes.iloc[0:2], kinds=dict(diagonal='kde_1d', lower='kde_2d', upper='kde_2d')) samples.plot_2d(axes.iloc[2:4], kinds=dict(diagonal='hist_1d', lower='hist_2d', upper='hist_2d'), bins=20) samples.plot_2d(axes.iloc[4: ], kinds=dict(diagonal='kde_1d', lower='scatter_2d', upper='scatter_2d')) ``` -------------------------------- ### Generate Synthetic Data with Perfect Nested Sampling Generators Source: https://context7.com/handley-lab/anesthetic/llms.txt Generates synthetic datasets using various perfect nested sampling generators from the anesthetic library, including Gaussian, correlated Gaussian, wedding cake, and Planck-like posteriors. Demonstrates how to calculate logZ, D_KL, and d_G, and create 2D posterior plots. ```python from anesthetic.examples.perfect_ns import gaussian, correlated_gaussian, wedding_cake, planck_gaussian import numpy as np # Gaussian likelihood with uniform prior in n-ball samples = gaussian(nlive=500, ndims=5, sigma=0.1, R=1.0) print(f"logZ = {samples.logZ():.2f}") print(f"D_KL = {samples.D_KL():.2f}") print(f"d_G = {samples.d_G():.2f}") # Correlated Gaussian with custom covariance mean = np.array([0.5, 0.5, 0.5]) cov = np.array([ [0.01, 0.005, 0], [0.005, 0.01, 0.002], [0, 0.002, 0.01] ]) bounds = np.array([[0, 1], [0, 1], [0, 1]]) samples = correlated_gaussian(nlive=500, mean=mean, cov=cov, bounds=bounds) # Wedding cake (nested plateaus for testing) samples = wedding_cake(nlive=500, ndims=4, sigma=0.01, alpha=0.5) # Planck-like cosmological posterior samples = planck_gaussian(nlive=1000) # Parameters: omegabh2, omegach2, theta, tau, logA, ns print(samples.columns) # Use for validation from anesthetic import make_2d_axes import matplotlib.pyplot as plt fig, axes = make_2d_axes(['x0', 'x1', 'x2']) samples.plot_2d(axes) plt.savefig('perfect_ns_test.png') ``` -------------------------------- ### Plot 2D Parameter Distributions for MCMC Chains Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Generates 2D scatter plots for MCMC chains ('chain1' and 'chain2') to visualize the joint posterior distributions of 'x0' and 'x1'. This plot aids in understanding parameter correlations and the impact of burn-in on the overall distribution. ```python fig, axes = make_2d_axes(['x0', 'x1'], figsize=(5, 5)) chain1.plot_2d(axes, alpha=0.7, label="Chain 1") chain2.plot_2d(axes, alpha=0.7, label="Chain 2") axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes)/2, len(axes)), loc='lower center', ncol=2) ``` -------------------------------- ### Triangle Plot (KDE) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates a triangle plot with Kernel Density Estimation (KDE) for specified parameters. This function requires anesthetic samples and a list of parameter names. The 'kinds' argument can specify 'kde'. ```python samples.plot_2d(['x0', 'x1', 'x2'], kinds='kde') ``` -------------------------------- ### Regenerate documentation files Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst Regenerates the automatic RST files for the anesthetic documentation. This command is used with Sphinx to update documentation structure. ```bash sphinx-apidoc -fM -t docs/templates/ -o docs/source/ anesthetic/ ``` -------------------------------- ### Plotting Parameters on Log-Scale in Anesthetic (2D) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Demonstrates plotting parameters on logarithmic scales for both x and y axes in 2D plots using Anesthetic. The 'logx' and 'logy' keywords in 'make_2d_axes' or 'plot_2d' facilitate the visualization of data with wide dynamic ranges. It requires a list of parameter names, a Samples object, and potentially 'levels' for contour plots. ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2', 'x3'], logx=['x2'], logy=['x2']) samples.plot_2d(axes, label="'x2' on log-scale") axes.iloc[-1, 0].legend(bbox_to_anchor=(len(axes), len(axes)), loc='lower right') ``` ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2', 'x3'], logx=['x2']) ``` -------------------------------- ### Anesthetic citation (BibTeX) Source: https://github.com/handley-lab/anesthetic/blob/master/README.rst BibTeX entry for citing the anesthetic library in publications. This provides structured metadata for academic referencing. ```bibtex @article{anesthetic, doi = {10.21105/joss.01414}, url = {http://dx.doi.org/10.21105/joss.01414}, year = {2019}, month = {Jun}, publisher = {The Open Journal}, } ``` -------------------------------- ### Save anesthetic Samples to HDF5 Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Saves anesthetic NestedSamples or MCMCSamples objects to an HDF5 file for faster reading and writing. This format efficiently handles pandas.MultiIndex. ```python samples.to_hdf("filename.h5", "samples") ``` -------------------------------- ### Triangle Plot (Scatter and KDE) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates a triangle plot with scatter plots on the left and KDE plots elsewhere. This function requires anesthetic samples and a list of parameter names. ```python samples.plot_2d(['x0', 'x1', 'x2']) ``` -------------------------------- ### Define and Plot Derived Parameters - Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Demonstrates how to define new parameters from existing ones within an Anesthetic samples object and then plot these derived parameters. This includes single-step, multi-step, and conditional derivations. Requires Anesthetic, NumPy, and Matplotlib. ```python from anesthetic import read_chains, make_1d_axes import matplotlib.pyplot as plt import numpy as np # samples = read_chains('chains/cosmo_run') # Create derived parameter with label # h = samples.H0 / 100 # samples[('h', r'$h$')] = h # Multi-step derivation # omegabh2 = samples[('omegabh2', r'$Omega_b h^2$')] # samples[('omegab', r'$Omega_b$')] = omegabh2 / h**2 # Conditional derivation # samples[('sigma8_scaled', r'$sigma_8 sqrt{Omega_m/0.3}$')] = ( # samples.sigma8 * np.sqrt(samples.omegam / 0.3) # ) # Plot derived parameter # fig, axes = make_1d_axes(['omegab', 'sigma8_scaled']) # samples.plot_1d(axes) # plt.savefig('derived_params.png') # Access via parameter name or label # print(samples['omegab'].mean()) # print(samples[r'$Omega_b$'].mean()) # Same result ``` -------------------------------- ### 2D KDE Plot with Custom Levels Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates a 2D KDE plot with custom contour levels specified by the 'levels' argument. Requires anesthetic samples and axes objects from make_2d_axes. ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2'], upper=False) samples.plot_2d(axes, kinds='kde', levels=[0.99994, 0.99730, 0.95450, 0.68269]) ``` -------------------------------- ### Flexible Rectangle Plot Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Demonstrates the flexibility of rectangle plots by plotting different parameter combinations in rows. Requires anesthetic samples and a list of lists defining parameter groupings. ```python samples.plot_2d([['x0', 'x1', 'x2'], ['x2', 'x1']]) ``` -------------------------------- ### 2D KDE Plot with Levels Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates a 2D KDE plot with specified contour levels. Requires anesthetic samples, axes objects from make_2d_axes, and 'kde_2d' or 'kde' as the kind. The 'levels' argument controls the contour lines. ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2'], upper=False) samples.plot_2d(axes, kinds=dict(diagonal='kde_1d', lower='kde_2d'), label="KDE") axes.iloc[-1, 0].legend(loc='upper right', bbox_to_anchor=(len(axes), len(axes))) ``` -------------------------------- ### Remove Burn-in Samples from MCMC Chains Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Demonstrates how to remove burn-in samples from MCMC chains using the `remove_burn_in` functionality. It handles both positive and negative burn-in values, interpreting them as samples to remove or keep, respectively. Fractions are also supported. This functionality is crucial for accurate convergence assessment. ```python Rminus1_old = mcmc_samples.Gelman_Rubin() Rminus1_new = mcmc_burnout.Gelman_Rubin() Rminus1_par = mcmc_burnout.Gelman_Rubin(per_param='par') ``` -------------------------------- ### Multiple 1D Posterior Plots Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates 1D marginalized posterior plots for multiple parameters. This function takes a list of parameter names as input and requires anesthetic samples to be loaded. ```python samples.plot_1d(['x0', 'x1', 'x2', 'x3', 'x4']) ``` -------------------------------- ### 1D KDE Plot Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Generates a 1D Kernel Density Estimation (KDE) plot. This function requires anesthetic samples, axes objects created by make_1d_axes, and specifies 'kde_1d' as the kind. ```python fig, axes = make_1d_axes(['x0', 'x1'], figsize=(5, 3)) samples.plot_1d(axes, kind='kde_1d', label="KDE") axes.iloc[0].legend(loc='upper right', bbox_to_anchor=(1, 1)) ``` -------------------------------- ### Save anesthetic Samples to CSV Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/reading_writing.rst Saves anesthetic NestedSamples or MCMCSamples objects to a CSV file. This method is human-readable and supports various saving options from pandas.to_csv. ```python samples.to_csv("filename.csv") ``` -------------------------------- ### Compare Prior vs. Posterior Distributions - Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Compares the prior and posterior distributions for given parameters in a 1D plot. This helps in understanding how the data has influenced the parameter estimates. It requires the Anesthetic library and Matplotlib. ```python from anesthetic import make_1d_axes import matplotlib.pyplot as plt # Assuming 'samples' is an Anesthetic object and 'params' is a list of parameters # prior = samples.prior() # fig, axes = make_1d_axes(params) # prior.plot_1d(axes, label='prior', alpha=0.7) # samples.plot_1d(axes, label='posterior', alpha=0.7) # axes['x0'].legend() # plt.savefig('prior_vs_posterior.png') ``` -------------------------------- ### Remove Burn-in Phase from MCMC Samples Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Demonstrates the usage of the `remove_burn_in` method in `anesthetic.samples.MCMCSamples` to discard the initial portion of MCMC samples. This is a crucial step for analyzing converged MCMC chains, specified by the `burn_in` fraction. ```python mcmc_burnout = mcmc_samples.remove_burn_in(burn_in=0.1) ``` -------------------------------- ### Merge Nested Sampling and MCMC Runs in Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Combines multiple nested sampling or MCMC runs using anesthetic. Supports both equal-weight merging for nested samples and weighted merging for general samples, including custom weights. Requires anesthetic and matplotlib. ```python from anesthetic import read_chains from anesthetic.samples import merge_nested_samples, merge_samples_weighted # Read multiple runs run1 = read_chains('chains/run1') run2 = read_chains('chains/run2') run3 = read_chains('chains/run3') # Merge nested sampling runs (equal weight) merged = merge_nested_samples([run1, run2, run3]) print(f"Combined samples: {len(merged)} = {len(run1)} + {len(run2)} + {len(run3)}") print(f"Merged logZ: {merged.logZ():.2f}") # Weighted merging using evidences (automatic for NestedSamples) weighted_merge = merge_samples_weighted([run1, run2, run3]) # Uses exp(logZ) as weights automatically # Weighted merging with custom weights custom_merge = merge_samples_weighted( [run1, run2, run3], weights=[0.5, 0.3, 0.2], label='custom merge' ) # Merge MCMC runs with explicit weights mcmc1 = read_chains('chains/mcmc1') mcmc2 = read_chains('chains/mcmc2') merged_mcmc = merge_samples_weighted( [mcmc1, mcmc2], weights=[1.0, 1.0], label='merged MCMC' ) # Compare merged vs individual from anesthetic import make_2d_axes import matplotlib.pyplot as plt fig, axes = make_2d_axes(['x0', 'x1']) run1.plot_2d(axes, label='run 1', alpha=0.6) run2.plot_2d(axes, label='run 2', alpha=0.6) merged.plot_2d(axes, label='merged', alpha=0.8, color='black') axes.iloc[-1, 0].legend() plt.savefig('merged_runs.png') ``` -------------------------------- ### Highlighting Points and Ranges in Anesthetic Plots Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/plotting.rst Illustrates the use of AxesDataFrame convenience methods for highlighting specific elements in parameter space plots. '.scatter()' highlights points, '.axlines()' separates parameter space along lines, and '.axspans()' highlights ranges. These methods enhance the interpretability of complex posterior distributions. It requires a Samples object and a DataFrame of Axes. ```python fig, axes = make_2d_axes(['x0', 'x1', 'x2']) samples.plot_2d(axes, label="posterior samples") axes.scatter({'x0': 0, 'x1': 0, 'x2': 0}, marker='*', c='r', label="some truth") axes.axlines({'x2': 0.3}, ls=':', c='k', label="some threshold") axes.axspans({'x0': (-0.1, 0.1)}, c='0.5', alpha=0.3, upper=False, label="some range") axes.iloc[-1, 0].legend(loc='lower center', bbox_to_anchor=(len(axes)/2, len(axes))) ``` -------------------------------- ### Calculate Weighted Quantiles and Posterior/Prior Points Source: https://context7.com/handley-lab/anesthetic/llms.txt Calculates weighted quantiles for a given set of samples, prints formatted results. Also demonstrates setting custom weights, dropping weights for equal weighting, and extracting posterior and prior points from weighted samples. ```python # Weighted quantiles q = samples.x0.quantile([0.16, 0.5, 0.84]) print(f"x0 = {q[0.5]:.3f} +{q[0.84]-q[0.5]:.3f} -{q[0.5]-q[0.16]:.3f}") # Set custom weights import numpy as np new_weights = np.exp(-samples.logL / 2) # Tempered weights samples.set_weights(new_weights, inplace=True) # Drop weights (equal weighting) unweighted = samples.drop_weights() print(unweighted.get_weights()) # All 1.0 # Compress samples to equal weights equal_weighted = samples.compress('equal') print(f"Compressed to {len(equal_weighted)} equal-weighted samples") # Posterior points (equal-weighted samples at beta=1) posterior = samples.posterior_points() print(f"Equal-weighted posterior: {len(posterior)} samples") # Prior points (equal-weighted samples at beta=0) prior = samples.prior_points() print(f"Equal-weighted prior: {len(prior)} samples") ``` -------------------------------- ### Gelman-Rubin Convergence Diagnostic - Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Calculates the Gelman-Rubin statistic (R-1) to assess the convergence of MCMC chains. A value close to zero indicates that the chains have converged. Can be calculated for all parameters or specific ones. Requires the Anesthetic library. ```python from anesthetic import read_chains # Assuming 'chains_burned' is an Anesthetic object after burn-in removal # Total R-1 # R_minus_1 = chains_burned.Gelman_Rubin() # print(f"Total R-1 = {R_minus_1:.4f}") # Per-parameter convergence # R_minus_1_total, R_minus_1_per_param = chains_burned.Gelman_Rubin( # params=['x0', 'x1', 'x2'], # per_param=True # ) # print(R_minus_1_per_param) # Check convergence for all parameters # R_minus_1_all = chains_burned.Gelman_Rubin(per_param='par') # print(R_minus_1_all) # if (R_minus_1_all < 0.01).all().values[0]: # print("All chains converged!") ``` -------------------------------- ### Compute Bayesian Statistics DataFrame (Python) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Computes Bayesian statistics from nested samples and returns a DataFrame containing samples reflecting the underlying distributions. The 'nsamples' parameter specifies the number of samples to generate for each statistic. This is useful for inspecting correlations between inferences. ```python nsamples = 2000 bayesian_stats = nested_samples.stats(nsamples) ``` -------------------------------- ### Plot 2D KDE Contours - Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Specifically generates a 2D triangle plot using Kernel Density Estimation (KDE) contours, which is the default plotting method for `plot_2d`. Requires Anesthetic and Matplotlib. ```python from anesthetic import read_chains, make_2d_axes import matplotlib.pyplot as plt # samples = read_chains('chains/nested_run') # params = ['x0', 'x1', 'x2', 'x3'] # fig, axes = make_2d_axes(params) # samples.plot_2d(axes, kind='kde') # KDE contours (default) # plt.savefig('triangle_kde.png') ``` -------------------------------- ### Plot 2D Bayesian Statistics Distributions (Python) Source: https://github.com/handley-lab/anesthetic/blob/master/docs/source/samples.rst Plots the 2D distributions of Bayesian statistics, allowing for the inspection of correlations between inferences. This function uses matplotlib axes and an anesthetic.samples.Samples object. It also customizes axis titles to display the mean and standard deviation of each statistic. ```python fig, axes = make_2d_axes(['logZ', 'D_KL', 'logL_P', 'd_G'], upper=False) bayesian_stats.plot_2d(axes) for y, row in axes.iterrows(): for x, ax in row.items(): if x == y: ax.set_title("%s$ = %.2g \pm %.1g$" % (bayesian_stats.get_label(x), bayesian_stats[x].mean(), bayesian_stats[x].std()), fontsize='small') ``` -------------------------------- ### Auto-detect and load chain files with anesthetic Source: https://context7.com/handley-lab/anesthetic/llms.txt This function automatically detects and loads chain files from various nested sampling formats (PolyChord, MultiNest, UltraNest, etc.) or MCMC outputs. It returns a NestedSamples object for nested sampling chains or an MCMCSamples object for MCMC chains. The sample data can be accessed as a pandas DataFrame, and parameter labels can be retrieved using get_label(). ```python from anesthetic import read_chains # Automatically detects format (PolyChord, MultiNest, UltraNest, etc.) samples = read_chains('path/to/chain_root') # Returns NestedSamples for nested sampling chains print(type(samples)) # # Returns MCMCSamples for MCMC chains mcmc_samples = read_chains('path/to/mcmc_chain') print(type(mcmc_samples)) # # Access sample data as pandas DataFrame print(samples.head()) # x0 x1 x2 x3 x4 logL # 0 0.123456 0.234567 0.345678 0.456789 0.567890 -123.45 # 1 0.234567 0.345678 0.456789 0.567890 0.678901 -122.34 # Parameter labels available via get_label() print(samples.get_label('x0')) # '$x_0$' (LaTeX format) ``` -------------------------------- ### Extract Live and Dead Points in Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Extracts live and dead points from nested sampling runs at specific likelihood contours or iteration numbers using the anesthetic library. It supports visualizing these points and truncating runs. Requires anesthetic and matplotlib. ```python from anesthetic import read_chains import matplotlib.pyplot as plt samples = read_chains('chains/nested_run') # Get final live points live = samples.live_points() print(f"Number of live points: {len(live)}") print(live) # Get live points at specific log-likelihood live_at_logL = samples.live_points(logL=-100.0) print(f"Live points at logL=-100: {len(live_at_logL)}") # Get live points at iteration number live_at_iter = samples.live_points(1000) # Get dead points (all samples below contour) dead = samples.dead_points() print(f"Number of dead points: {len(dead)}") # Dead points at specific contour dead_at_logL = samples.dead_points(logL=-100.0) # Truncate run at contour (dead + live points at that contour) truncated = samples.truncate(logL=-50.0) print(f"Truncated samples: {len(truncated)} / {len(samples)}") print(f"Truncated logZ: {truncated.logZ():.2f}") # Visualize live points from anesthetic import make_2d_axes fig, axes = make_2d_axes(['x0', 'x1']) samples.plot_2d(axes, label='all samples', alpha=0.5) live.plot_2d(axes, kind='scatter', label='live points', color='red', s=20) axes.iloc[-1, 0].legend() plt.savefig('live_points.png') ``` -------------------------------- ### Perform Weighted Operations in Python Source: https://context7.com/handley-lab/anesthetic/llms.txt Utilizes weights in statistical computations for nested sampling or MCMC runs using the anesthetic library. Supports accessing current weights and calculating weighted means and covariances for selected parameters. Requires anesthetic. ```python from anesthetic import read_chains samples = read_chains('chains/nested_run') # Get current weights weights = samples.get_weights() print(f"Weight range: {weights.min():.6f} to {weights.max():.6f}") # Weighted mean (automatic) mean = samples[['x0', 'x1', 'x2']].mean() print(mean) # x0 0.501234 # x1 0.498765 # x2 0.502345 # Weighted covariance cov = samples[['x0', 'x1', 'x2']].cov() print(cov) # x0 x1 x2 # x0 0.010234 0.000123 -0.000045 # x1 0.000123 0.009876 0.000234 ```