### Install fgivenx from source Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst Installs fgivenx by cloning the repository and running the setup script. This method is useful for developers or when the latest changes are needed. ```bash git clone https://github.com/handley-lab/fgivenx cd fgivenx python setup.py install --user ``` -------------------------------- ### Install and run fgivenx tests Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst Installs necessary testing tools and runs the fgivenx test suite. Ensure the MPLBACKEND environment variable is set to 'Agg' for tests that generate plots. ```bash pip install pytest pytest-runner pytest-mpl export MPLBACKEND=Agg pytest ``` ```bash git clone https://github.com/handley-lab/fgivenx cd fgivenx python setup.py test ``` -------------------------------- ### Install fgivenx using pip Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst Installs the fgivenx package and its dependencies using pip. This is the recommended method for most users. ```bash pip install fgivenx ``` -------------------------------- ### Build local fgivenx documentation Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst Builds a local HTML copy of the fgivenx documentation. Requires Sphinx to be installed. ```bash cd docs make html ``` -------------------------------- ### Install optional fgivenx dependencies Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst Installs optional dependencies for fgivenx, including joblib for parallelisation, tqdm for progress bars, and getdist for reading getdist compatible files. Pillow is also recommended on some systems for handling images. ```bash pip install joblib tqdm getdist ``` ```bash pip install -r requirements.txt ``` -------------------------------- ### Plot GetDist Chains with fgivenx Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst This example shows how to plot results from GetDist chains using fgivenx. It utilizes the samples_from_getdist_chains function to load samples and weights, and then plot_contours to visualize a function based on these weighted samples. Dependencies include numpy, matplotlib, and fgivenx. ```python import numpy import matplotlib.pyplot as plt from fgivenx import plot_contours, samples_from_getdist_chains file_root = './plik_HM_TT_lowl/base_plikHM_TT_lowl' samples, weights = samples_from_getdist_chains(['logA', 'ns'], file_root) def PPS(k, theta): logA, ns = theta return logA + (ns - 1) * numpy.log(k) k = numpy.logspace(-4,1,100) cbar = plot_contours(PPS, k, samples, weights=weights) cbar = plt.colorbar(cbar,ticks=[0,1,2,3]) cbar.set_ticklabels(['',r'$1\sigma$',r'$2\sigma$',r'$3\sigma$']) plt.xscale('log') plt.ylim(2,4) plt.ylabel(r'$\ln\left(10^{10}\mathcal{P}_\mathcal{R}\right)$') plt.xlabel(r'$k / {\rm Mpc}^{-1}$') plt.tight_layout() plt.savefig('planck.png') ``` -------------------------------- ### Load Samples from GetDist Chains (Python) Source: https://context7.com/handley-lab/fgivenx/llms.txt Extracts parameter samples and weights from getdist-formatted chain files, compatible with CosmoMC and other inference tools. Requires the 'getdist' library and existing chain files. It takes parameter names and a file root as input, returning samples, weights, and LaTeX labels. Error handling for missing 'getdist' or files is included. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import samples_from_getdist_chains, plot_contours # Load samples from getdist chain files # Assumes files like 'planck_base.txt' and 'planck_base.paramnames' exist file_root = './chains/planck_base' params = ['logA', 'ns'] # Parameter names to extract try: samples, weights, latex_labels = samples_from_getdist_chains( params, file_root, latex=True, settings={'ignore_rows': 0.3} # Burn-in removal ) # Define primordial power spectrum model def primordial_power_spectrum(k, theta): logA, ns = theta # P(k) = A * (k/k_pivot)^(ns-1) return logA + (ns - 1) * np.log(k) # Create plot k = np.logspace(-4, 1, 200) # Wavenumber range fig, ax = plt.subplots(figsize=(8, 6)) cbar = plot_contours(primordial_power_spectrum, k, samples, weights=weights, ax=ax, cache='cache/planck') cb = plt.colorbar(cbar, ticks=[0, 1, 2, 3]) cb.set_ticklabels(['', r'$1\sigma$', r'$2\sigma$', r'$3\sigma$']) ax.set_xscale('log') ax.set_xlabel(r'$k / \mathrm{Mpc}^{-1}$') ax.set_ylabel(latex_labels[0]) # Use latex label from chains ax.set_title('Planck CMB Constraints') plt.tight_layout() plt.savefig('planck_spectrum.png') except ImportError: print("getdist not installed. Install with: pip install getdist") except FileNotFoundError: print(f"Chain files not found at {file_root}") ``` -------------------------------- ### Complete Multi-Panel Analysis Workflow (Python) Source: https://context7.com/handley-lab/fgivenx/llms.txt Demonstrates a comprehensive analysis workflow for characterizing posterior-prior relationships. It integrates contour plots, line plots, and KL divergence calculations using functions from the fgivenx library. This is useful for detailed model evaluation. Inputs include model definitions and prior/posterior samples. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import plot_contours, plot_lines, plot_dkl # Define model def power_law_model(x, theta): normalization, index = theta return normalization * x**index # Generate prior and posterior samples np.random.seed(2024) nsamples = 1500 ``` -------------------------------- ### Create Comprehensive Analysis Figure with fgivenx in Python Source: https://context7.com/handley-lab/fgivenx/llms.txt This code utilizes fgivenx and matplotlib to create a comprehensive 2x2 figure visualizing Bayesian inference results. It includes parameter space plots, function samples, posterior contours, and KL divergence, comparing prior and posterior distributions. ```python import matplotlib.pyplot as plt from fgivenx.plot import plot_lines, plot_contours, plot_dkl # Assuming power_law_model, x, nsamples, prior_samples, posterior_samples are defined x = np.logspace(-1, 1, 100) # Create comprehensive figure fig, axes = plt.subplots(2, 2, figsize=(12, 10)) # Panel 1: Parameter space ax_params = axes[0, 0] ax_params.scatter(prior_samples[:, 0], prior_samples[:, 1], alpha=0.3, s=1, c='blue', label='Prior') ax_params.scatter(posterior_samples[:, 0], posterior_samples[:, 1], alpha=0.3, s=1, c='red', label='Posterior') ax_params.set_xlabel('Normalization') ax_params.set_ylabel('Index') ax_params.legend() ax_params.set_title('Parameter Space') # Panel 2: Function samples ax_lines = axes[0, 1] plot_lines(power_law_model, x, prior_samples, ax=ax_lines, color='blue', alpha=0.1, downsample=100, cache='cache/prior_lines') plot_lines(power_law_model, x, posterior_samples, ax=ax_lines, color='red', alpha=0.1, downsample=100, cache='cache/post_lines') ax_lines.set_xscale('log') ax_lines.set_yscale('log') ax_lines.set_xlabel(r'$x$') ax_lines.set_ylabel(r'$y(x)$') ax_lines.set_title('Representative Functions') # Panel 3: Posterior contours ax_contours = axes[1, 1] plot_contours(power_law_model, x, prior_samples, ax=ax_contours, colors=plt.cm.Blues_r, lines=False, cache='cache/prior_pmf') cbar = plot_contours(power_law_model, x, posterior_samples, ax=ax_contours, colors=plt.cm.Reds_r, cache='cache/post_pmf') ax_contours.set_xscale('log') ax_contours.set_yscale('log') ax_contours.set_xlabel(r'$x$') ax_contours.set_ylabel(r'$y(x)$') ax_contours.set_title('Predictive Posterior') # Panel 4: KL divergence ax_dkl = axes[1, 0] plot_dkl(power_law_model, x, posterior_samples, prior_samples, ax=ax_dkl, color='darkgreen', linewidth=2.5, cache='cache/post_dkl', prior_cache='cache/prior_dkl') ax_dkl.set_xscale('log') ax_dkl.set_xlabel(r'$x$') ax_dkl.set_ylabel(r'$D_{mathrm{KL}}(x)$') ax_dkl.set_title('Information Gain') ax_dkl.set_ylim(bottom=0) ax_dkl.grid(alpha=0.3) plt.tight_layout() plt.savefig('complete_analysis.png', dpi=150) plt.show() ``` -------------------------------- ### Plot User-Generated Samples with fgivenx Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst This snippet demonstrates how to plot user-generated MCMC posterior and prior samples using fgivenx. It shows how to define a model function, generate samples, and then use fgivenx's plot_lines and plot_contours functions to visualize the results. Dependencies include numpy and matplotlib. ```python import numpy import matplotlib.pyplot as plt from fgivenx import plot_contours, plot_lines, plot_dkl # Model definitions # ================= # Define a simple straight line function, parameters theta=(m,c) def f(x, theta): m, c = theta return m * x + c numpy.random.seed(1) # Posterior samples nsamples = 1000 ms = numpy.random.normal(loc=-5, scale=1, size=nsamples) cs = numpy.random.normal(loc=2, scale=1, size=nsamples) samples = numpy.array([(m, c) for m, c in zip(ms, cs)]).copy() # Prior samples ms = numpy.random.normal(loc=0, scale=5, size=nsamples) cs = numpy.random.normal(loc=0, scale=5, size=nsamples) prior_samples = numpy.array([(m, c) for m, c in zip(ms, cs)]).copy() # Set the x range to plot on xmin, xmax = -2, 2 nx = 100 x = numpy.linspace(xmin, xmax, nx) # Set the cache cache = 'cache/test' prior_cache = cache + '_prior' # Plotting # ======== fig, axes = plt.subplots(2, 2) # Sample plot # ----------- ax_samples = axes[0, 0] ax_samples.set_ylabel(r'$c$') ax_samples.set_xlabel(r'$m$') ax_samples.plot(prior_samples.T[0], prior_samples.T[1], 'b.') ax_samples.plot(samples.T[0], samples.T[1], 'r.') # Line plot # --------- ax_lines = axes[0, 1] ax_lines.set_ylabel(r'$y = m x + c$') ax_lines.set_xlabel(r'$x$') plot_lines(f, x, prior_samples, ax_lines, color='b', cache=prior_cache) plot_lines(f, x, samples, ax_lines, color='r', cache=cache) # Predictive posterior plot # ------------------------- ax_fgivenx = axes[1, 1] ax_fgivenx.set_ylabel(r'$P(y|x)$') ax_fgivenx.set_xlabel(r'$x$') cbar = plot_contours(f, x, prior_samples, ax_fgivenx, colors=plt.cm.Blues_r, lines=False, cache=prior_cache) cbar = plot_contours(f, x, samples, ax_fgivenx, cache=cache) # DKL plot # -------- ax_dkl = axes[1, 0] ax_dkl.set_ylabel(r'$D_\mathrm{KL}$') ax_dkl.set_xlabel(r'$x$') ax_dkl.set_ylim(bottom=0, top=2.0) plot_dkl(f, x, samples, prior_samples, ax_dkl, cache=cache, prior_cache=prior_cache) ax_lines.sharex(ax_fgivenx) ax_dkl.sharex(ax_fgivenx) ax_lines.sharey(ax_fgivenx) ax_fgivenx.sharey(ax_samples) fig.tight_layout() fig.savefig('plot.png') ``` -------------------------------- ### Plot KL Divergence with fgivenx Source: https://context7.com/handley-lab/fgivenx/llms.txt Computes and visualizes the KL divergence D_KL(x) between posterior and prior distributions for a given model and x-values. This quantifies the information gain from data across the function domain. It requires the model, x-values, posterior samples, and prior samples. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import plot_dkl def exponential_model(x, theta): amplitude, decay = theta return amplitude * np.exp(-decay * x) # Prior samples (broad, uninformative) np.random.seed(456) nsamples = 1500 prior_amps = np.random.uniform(0.5, 3.0, size=nsamples) prior_decays = np.random.uniform(0.1, 2.0, size=nsamples) prior_samples = np.column_stack([prior_amps, prior_decays]) # Posterior samples (informed by data) post_amps = np.random.normal(loc=2.0, scale=0.2, size=nsamples) post_decays = np.random.normal(loc=0.8, scale=0.1, size=nsamples) posterior_samples = np.column_stack([post_amps, post_decays]) x = np.linspace(0, 5, 100) # Plot KL divergence fig, ax = plt.subplots() plot_dkl(exponential_model, x, posterior_samples, prior_samples, ax=ax, color='darkred', linewidth=2, cache='cache/post', prior_cache='cache/prior') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$D_{\mathrm{KL}}(x)$') ax.set_title('Information Gain vs Position') ax.set_ylim(bottom=0) ax.grid(alpha=0.3) plt.savefig('kl_divergence.png') ``` -------------------------------- ### Compute Function Samples with Caching and Parallelization (Python) Source: https://context7.com/handley-lab/fgivenx/llms.txt Evaluates a function f(x;θ) across all x values and posterior samples, with options for sample trimming, result caching, and parallel execution. This enhances efficiency for large datasets. It takes a model function, x-values, and samples as input. Outputs are the computed function samples, with parallel and cache options for performance tuning. ```python import numpy as np from fgivenx import compute_samples def complex_model(x, theta): """Model with expensive computation""" a, b, c, d = theta result = (a * np.sin(b * x) + c * np.cos(d * x)) / (1 + x**2) return result # Generate large sample set np.random.seed(321) nsamples = 5000 samples = np.random.randn(nsamples, 4) # 4 parameters x = np.linspace(-5, 5, 300) # Compute with parallel processing and caching # First run: performs computation fsamps = compute_samples( complex_model, x, samples, parallel=True, # Enable multiprocessing cache='cache/complex_model', # Cache results for reuse ntrim=2000, # Downsample to 2000 samples tqdm_kwargs={'desc': 'Computing samples'} ) print(f"Function samples shape: {fsamps.shape}") # (300, 2000) print(f"Mean at x=0: {fsamps[150].mean():.3f}") print(f"Std at x=0: {fsamps[150].std():.3f}") # Second run: loads from cache instantly fsamps_cached = compute_samples( complex_model, x, samples, cache='cache/complex_model', ntrim=2000 ) assert np.allclose(fsamps, fsamps_cached), "Cache consistency check" ``` -------------------------------- ### Generate Prior and Posterior Samples in Python Source: https://context7.com/handley-lab/fgivenx/llms.txt This snippet generates samples for prior and posterior distributions using NumPy. The prior uses uniform distributions for 'norm' and 'indices', while the posterior uses normal distributions. These samples are then combined into arrays for further analysis. ```python import numpy as np nsamples = 10000 # Prior: broad uniform distributions prior_norms = np.random.uniform(0.5, 5.0, size=nsamples) prior_indices = np.random.uniform(-2.0, 1.0, size=nsamples) prior_samples = np.column_stack([prior_norms, prior_indices]) # Posterior: data-informed narrow distributions post_norms = np.random.normal(loc=2.5, scale=0.4, size=nsamples) post_indices = np.random.normal(loc=-0.5, scale=0.2, size=nsamples) posterior_samples = np.column_stack([post_norms, post_indices]) ``` -------------------------------- ### Compute Probability Mass Function (Python) Source: https://context7.com/handley-lab/fgivenx/llms.txt Calculates the probability mass function (PMF) on a 2D grid for a given model and samples. It returns y-values and the corresponding mass array, suitable for custom visualization or analysis. Dependencies include numpy, matplotlib, and fgivenx.compute_pmf. Input is a model function, x-values, and posterior samples. Output is a tuple of y-values and the PMF array. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import compute_pmf def sinusoidal_model(x, theta): amplitude, frequency, phase = theta return amplitude * np.sin(frequency * x + phase) # Generate samples np.random.seed(789) nsamples = 1200 amplitudes = np.random.gamma(shape=4, scale=0.5, size=nsamples) frequencies = np.random.normal(loc=2.0, scale=0.3, size=nsamples) phases = np.random.uniform(-np.pi, np.pi, size=nsamples) samples = np.column_stack([amplitudes, frequencies, phases]) x = np.linspace(0, 2*np.pi, 120) # Compute PMF with custom y-range y, pmf = compute_pmf(sinusoidal_model, x, samples, ny=150, cache='cache/sine', parallel=False) # Custom visualization fig, ax = plt.subplots(figsize=(10, 6)) # Convert pmf to sigmas for display from scipy.special import erfinv sigma_levels = np.sqrt(2) * erfinv(1 - pmf) im = ax.contourf(x, y, sigma_levels.T, levels=20, cmap='viridis') plt.colorbar(im, ax=ax, label='Sigma level') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') ax.set_title('Custom PMF Visualization') plt.savefig('custom_pmf.png') ``` -------------------------------- ### Overlay Posterior Function Samples with fgivenx Source: https://context7.com/handley-lab/fgivenx/llms.txt Overlays a subset of function evaluations from posterior samples as semi-transparent lines. This provides a visual representation of the function space consistent with the data. It requires the function, x-values, posterior samples, and a matplotlib Axes object. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import plot_lines def polynomial_model(x, theta): a, b, c = theta return a * x**2 + b * x + c # Generate posterior samples for polynomial coefficients np.random.seed(123) nsamples = 2000 a_samples = np.random.normal(loc=1.5, scale=0.3, size=nsamples) b_samples = np.random.normal(loc=-2.0, scale=0.5, size=nsamples) c_samples = np.random.normal(loc=1.0, scale=0.4, size=nsamples) samples = np.column_stack([a_samples, b_samples, c_samples]) x = np.linspace(-3, 3, 150) # Plot function samples fig, ax = plt.subplots() plot_lines(polynomial_model, x, samples, ax=ax, color='blue', alpha=0.05, downsample=200, cache='cache/poly') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y = ax^2 + bx + c$') ax.set_title('Posterior Function Samples') plt.savefig('function_lines.png') ``` -------------------------------- ### fgivenx BibTeX Entry Source: https://github.com/handley-lab/fgivenx/blob/master/README.rst This is the BibTeX entry for the fgivenx paper, providing citation details such as authors, title, journal, and publication year. ```bibtex @article{fgivenx, doi = {10.21105/joss.00849}, url = {http://dx.doi.org/10.21105/joss.00849}, year = {2018}, month = {Aug}, publisher = {The Open Journal}, volume = {3}, number = {28}, author = {Will Handley}, title = {fgivenx: Functional Posterior Plotter}, journal = {The Journal of Open Source Software} } ``` -------------------------------- ### Plot Predictive Posterior Contours with fgivenx Source: https://context7.com/handley-lab/fgivenx/llms.txt Generates filled contour plots of the probability mass function P(y|x) for a parameterized function. It displays credible regions as sigma-level contours and requires posterior samples and a defined function. The output is a matplotlib Axes object with an associated colorbar. ```python import numpy as np import matplotlib.pyplot as plt from fgivenx import plot_contours # Define a linear model f(x; theta) where theta = (m, c) def linear_model(x, theta): m, c = theta return m * x + c # Generate posterior samples (e.g., from MCMC) np.random.seed(42) nsamples = 1000 ms = np.random.normal(loc=-5, scale=1, size=nsamples) cs = np.random.normal(loc=2, scale=1, size=nsamples) samples = np.array([(m, c) for m, c in zip(ms, cs)]) # Define x range x = np.linspace(-2, 2, 100) # Create contour plot fig, ax = plt.subplots() cbar = plot_contours(linear_model, x, samples, ax=ax, cache='cache/linear') # Add colorbar with sigma labels cb = plt.colorbar(cbar, ticks=[0, 1, 2, 3]) cb.set_ticklabels(['', r'$1\sigma$', r'$2\sigma$', r'$3\sigma$']) ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y = mx + c$') plt.savefig('contours.png') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.