### JAX Compiled Integrand Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/compiled_integrands.rst.txt Example of a compiled integrand using JAX for potential GPU acceleration. Ensure JAX is installed and configured for your hardware. ```python import vegas import jax.numpy as jnp @vegas.rbatchintegrand def _jridge(x): N = 1000 x0 = jnp.linspace(0.25, 0.75, N) dx2 = 0.0 for xd in x: dx2 += (xd[None,:] - x0[:, None]) ** 2 return jnp.sum(jnp.exp(-100. * dx2), axis=0) * (100. / jnp.pi) ** (len(x) / 2.) / N @vegas.rbatchintegrand def ridge(x): return _jridge(jnp.array(x)) integ = vegas.Integrator(4 * [[0, 1]], gpu_pad=True) integ(ridge, nitn=10, neval=2e5) result = integ(ridge, nitn=10, neval=2e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### Vegas Integration Output Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Example output from Vegas integration showing iteration progress, integral estimates, and quality metrics. This output is generated when adapt=False is used for final iterations. ```text itn integral wgt average chi2/dof Q ------------------------------------------------------- 1 0.75(43) 0.75(43) 0.00 1.00 2 0.506(58) 0.510(58) 0.32 0.57 3 0.80(21) 0.530(56) 1.02 0.36 4 0.76(11) 0.576(50) 1.81 0.14 5 1.27(29) 0.596(49) 2.74 0.03 6 1.10(19) 0.629(48) 3.56 0.00 7 0.802(73) 0.681(40) 3.63 0.00 8 2.8(2.0) 0.681(40) 3.27 0.00 9 0.907(90) 0.719(36) 3.52 0.00 10 1.07(16) 0.736(35) 3.65 0.00 ``` ```text itn integral average chi2/dof Q ------------------------------------------------------- 1 1.13(14) 1.13(14) 0.00 1.00 2 1.064(96) 1.095(86) 0.13 0.72 3 1.03(10) 1.072(67) 0.19 0.83 4 0.924(94) 1.035(55) 0.58 0.63 5 0.858(71) 1.000(46) 1.08 0.37 6 0.97(11) 0.995(43) 0.84 0.52 7 0.924(69) 0.985(38) 0.84 0.54 8 1.19(16) 1.010(39) 1.01 0.42 9 1.74(73) 1.092(88) 1.01 0.42 10 0.942(89) 1.077(80) 1.02 0.42 ``` -------------------------------- ### Example Output for Precision Adjustment Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Shows the output when adjusting 'nitn' and 'neval' parameters to observe the impact on integration results and Q-value. ```text larger nitn => 1.0003(13) Q = 0.79 larger neval => 0.99981(53) Q = 0.28 ``` -------------------------------- ### Basic Vegas Integration Setup Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Sets up a Vegas integrator and defines a batch integrand for simultaneous integration. Use this for initial integration attempts before optimizing with Jacobian. ```python import vegas import numpy as np integ = vegas.Integrator(2 * [(0., np.pi/2.)]) @vegas.rbatchintegrand def f(x): Ia_num = np.exp(-1e2 * np.sin(x[1])) / ((x[0] - x[1])**2 + 0.01) Ia_den = np.exp(-1e2 * np.sin(x[1])) / (np.pi/2) Ib = 1 / (x[0]**2 + 0.01) / (np.pi/2) return dict(Ia_num=Ia_num, Ia_den=Ia_den, Ib=Ib) w = integ(f, neval=20000, nitn=10) r = integ(f, neval=20000, nitn=5) print(r.summary(True)) print('Ia =', r['Ia_num'] / r['Ia_den'], 'Ia - Ib =', r['Ia_num'] / r['Ia_den'] - r['Ib']) ``` -------------------------------- ### AdaptiveMap Training Example Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Demonstrates training an AdaptiveMap object for a 2D integral. It samples the integrand, computes training data based on Jacobian and integrand values, and iteratively adapts the map. ```python import vegas import numpy as np def f(x): return x[0] * x[1] ** 2 m = vegas.AdaptiveMap([[0, 1], [0, 1]], ninc=5) ny = 1000 y = np.random.uniform(0., 1., (ny, 2)) # 1000 random y's x = np.empty(y.shape, float) # work space jac = np.empty(y.shape[0], float) f2 = np.empty(y.shape[0], float) print('intial grid:') print(m.settings()) for itn in range(5): # 5 iterations to adapt m.map(y, x, jac) # compute x's and jac for j in range(ny): # compute training data f2[j] = (jac[j] * f(x[j])) ** 2 m.add_training_data(y, f2) # adapt m.adapt(alpha=1.5) print('iteration %d:' % itn) print(m.settings()) ``` -------------------------------- ### Initializing AdaptiveMap with Uniform Increments Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Demonstrates creating an AdaptiveMap with a specified number of uniform increments per dimension. This is a common starting point before training the map with data. ```python m = AdaptiveMap([[0, 1], [-1, 1]], ninc=1000) ``` -------------------------------- ### MLX Compiled Integrand Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/compiled_integrands.rst.txt Example of a compiled integrand using MLX, suitable for Apple Silicon GPUs. This version is significantly faster than the pure Python or JAX versions on compatible hardware. ```python import vegas import mlx.core as mx @mx.compile def _mridge(x): N = 1000 x0 = mx.linspace(0.25, 0.75, N) dx2 = 0.0 for xd in x: dx2 += (xd[None,:] - x0[:, None]) ** 2 return mx.sum(mx.exp(-100. * dx2), axis=0) * (100. / mx.pi) ** (len(x) / 2.) / N @vegas.rbatchintegrand def ridge(x): return _mridge(mx.array(x)) integ = vegas.Integrator(4 * [[0, 1]], gpu_pad=True) integ(ridge, nitn=10, neval=2e5) result = integ(ridge, nitn=10, neval=2e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### GPU-Accelerated Batch Integrand with JAX Source: https://context7.com/gplepage/vegas/llms.txt Demonstrates GPU acceleration for batch integrands using JAX. Setting gpu_pad=True is required for GPU JIT compilers to ensure constant batch sizes. This example shows a significant speedup on GPUs compared to CPU execution. ```python import vegas import jax jnp = jax.numpy @jax.jit def _jridge(x): N = 1000 x0 = jnp.linspace(0.25, 0.75, N) dx2 = 0.0 for xd in x: dx2 += (xd[None, :] - x0[:, None]) ** 2 # broadcast over batch return jnp.sum(jnp.exp(-100. * dx2), axis=0) * (100. / jnp.pi) ** (len(x) / 2.) / N @vegas.rbatchintegrand def ridge(x): return _jridge(jnp.array(x)) # gpu_pad=True ensures constant batch size for GPU efficiency integ = vegas.Integrator(4 * [[0, 1]], gpu_pad=True) integ(ridge, nitn=10, neval=2e5) result = integ(ridge, nitn=10, neval=2e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### Using Compiled Pythran Integrand with Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/compiled_integrands.rst.txt Example of using a Pythran-compiled integrand with vegas. The integrand needs to be wrapped with vegas.lbatchintegrand after importing. ```python import vegas from pythran_ridge import ridge ridge = vegas.lbatchintegrand(ridge) integ = vegas.Integrator(4 * [[0, 1]]) integ(ridge, nitn=10, neval=2e5) result = integ(ridge, nitn=10, neval=2e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### PDF Integrator Output Summary Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Example output from the PDFIntegrator, showing iteration details, results, calculated mean and standard deviation, and PDF norm. ```text itn integral average chi2/dof Q ------------------------------------------------------- 1 0.9995(11) 0.9995(11) 0.00 1.00 2 1.0011(11) 1.00030(78) 0.36 0.78 3 1.0013(12) 1.00062(65) 0.31 0.93 4 1.0003(10) 1.00055(55) 0.24 0.99 5 1.0000(11) 1.00044(50) 0.45 0.94 results = [5.9996(54) 50.09(15)] fmean = 5.9996(54) fsdev = 3.755(13) Gaussian approx'n for fp = 5.0(3.8) PDF norm = 1.00044(50) ``` -------------------------------- ### Parallel Integration with MPI using Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/html/tutorial.html This example shows how to configure `vegas` for multi-processor integration using MPI. The integrator is initialized with `mpi=True`. The script should be run using `mpirun`. ```python import vegas # Assuming the ridge function and main are defined in ridge.py # ... (ridge function definition) integ = vegas.Integrator(4 * [[0, 1]], mpi=True) ``` -------------------------------- ### Integrate Multiple Integrands Simultaneously in Python Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Example demonstrating how to integrate multiple related functions simultaneously using Vegas. This approach leverages correlated sampling for improved accuracy in ratios or differences. ```python import vegas import math import gvar as gv def f(x): dx2 = 0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 f = math.exp(-200 * dx2) return [f, f * x[0], f * x[0] ** 2] integ = vegas.Integrator(4 * [[0, 1]]) # adapt grid training = integ(f, nitn=10, neval=2000) # final analysis result = integ(f, nitn=10, neval=10000) print('I[0] =', result[0], ' I[1] =', result[1], ' I[2] =', result[2]) ``` -------------------------------- ### Basic Usage of PDFIntegrator Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Illustrates the basic setup and usage of the PDFIntegrator for estimating expectation values. It involves defining a gvar object, creating a PDFIntegrator instance, and performing the integration with a specified number of evaluations. ```python import gvar as gv import vegas g = gv.gvar(dict(a='1.0(5)', b='2(1)')) * gv.gvar('1.0(5)') g_ev = vegas.PDFIntegrator(g) g_ev(neval=10000) # adapt the integrator to the PDF ``` -------------------------------- ### Vegas Integration with Dictionary Results Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt This example demonstrates using Vegas with an integrand that returns a dictionary. This approach can make code more readable by using descriptive keys for results. The integration results are then accessed using these keys. ```python import vegas import math import gvar as gv def f(x): dx2 = 0.0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 f = math.exp(-200 * dx2) return {'1':f, 'x':f * x[0], 'x**2':f * x[0] ** 2} integ = vegas.Integrator(4 * [[0, 1]]) # adapt grid training = integ(f, nitn=10, neval=2000) # final analysis result = integ(f, nitn=10, neval=10000) print(result) print('Q = %.2f\n' % result.Q) print(' =', result['x'] / result['1']) print( 'sigma_x**2 = - **2 =', result['x**2'] / result['1'] - (result['x'] / result['1']) ** 2 ) ``` -------------------------------- ### Using Compiled Cython Integrand with Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/compiled_integrands.rst.txt Example of importing and using a compiled Cython integrand with the vegas library. Ensure the Cython file is compiled first. ```python import vegas from cython_ridge import ridge integ = vegas.Integrator(4 * [[0, 1]]) integ(ridge, nitn=10, neval=2e5) result = integ(ridge, nitn=10, neval=2e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### Integrate Function with Two Peaks using Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/html/background.html This example demonstrates integrating a function with two Gaussian peaks using the Vegas library. It shows how to initialize the integrator, perform an initial integration, and then a more refined one. The grid visualization highlights Vegas's concentration on peak regions. ```python import vegas import math def f2(x): dx2 = 0 for d in range(4): dx2 += (x[d] - 1/3.) ** 2 ans = math.exp(-dx2 * 100.) * 1013.2167575422921535 dx2 = 0 for d in range(4): dx2 += (x[d] - 2/3.) ** 2 ans += math.exp(-dx2 * 100.) * 1013.2167575422921535 return ans / 2. integ = vegas.Integrator(4 * [[0, 1]]) integ(f2, nitn=10, neval=4e4) result = integ(f2, nitn=30, neval=4e4) print('result = %s Q = %.2f' % (result, result.Q)) ``` ```python integ.map.show_grid(70) ``` -------------------------------- ### Vegas Integration Output Summary Source: https://github.com/gplepage/vegas/blob/main/doc/source/compiled_integrands.md Example output from the vegas integrator showing the progress of the integration over multiple iterations. The 'integral' column shows the estimated value and its uncertainty. ```text itn integral wgt average chi2/dof Q ------------------------------------------------------- 1 4.1(2.1) 4.1(2.1) 0.00 1.00 2 7.403(42) 7.401(42) 2.52 0.11 3 7.366(27) 7.376(23) 1.51 0.22 4 7.4041(73) 7.4014(70) 1.48 0.22 5 7.4046(36) 7.4039(32) 1.15 0.33 6 7.4003(23) 7.4015(19) 1.09 0.37 7 7.4036(20) 7.4025(14) 1.01 0.42 8 7.4017(16) 7.4022(10) 0.89 0.52 9 7.4010(14) 7.40174(83) 0.84 0.57 10 7.4017(13) 7.40174(70) 0.74 0.67 itn integral wgt average chi2/dof Q ------------------------------------------------------- 1 7.4016(12) 7.4016(12) 0.00 1.00 2 7.4030(11) 7.40239(81) 0.79 0.37 3 7.4020(10) 7.40224(63) 0.44 0.64 4 7.40249(92) 7.40232(52) 0.31 0.82 5 7.40258(86) 7.40239(44) 0.25 0.91 6 7.40093(81) 7.40205(39) 0.70 0.62 7 7.40228(76) 7.40210(35) 0.60 0.73 8 7.40276(72) 7.40222(31) 0.61 0.75 9 7.40181(71) 7.40216(29) 0.57 0.80 10 7.40178(70) 7.40210(27) 0.53 0.85 ``` -------------------------------- ### PDFIntegrator Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Demonstrates calculating an expectation value using PDFIntegrator. The first print statement shows the Vegas estimate of the mean, while the second shows the standard deviation evaluated with respect to a Gaussian distribution. ```python g = gvar.gvar(['1(1)', '10(10)']) g_ev = vegas.PDFIntegrator(g) def f(p): return p[0] * p[1] print(g_ev(f)) print(g_ev.stats(f)) ``` -------------------------------- ### Vegas Integration Output Summary Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md This is an example output from the vegas integration. It shows the progress of the integral estimation over multiple iterations, including the estimated integral value, weighted average, chi-squared per degree of freedom, and the Q-value (p-value). ```text itn integral wgt average chi2/dof Q ------------------------------------------------------- 1 2.6(1.4) 2.6(1.4) 0.00 1.00 2 1.32(25) 1.36(25) 0.75 0.39 3 0.909(96) 0.968(89) 1.79 0.17 4 1.039(69) 1.012(55) 1.32 0.26 5 0.929(34) 0.952(29) 1.41 0.23 6 1.003(26) 0.980(19) 1.47 0.20 7 0.994(18) 0.988(13) 1.27 0.27 8 0.998(14) 0.9922(98) 1.13 0.34 9 1.020(12) 1.0035(75) 1.39 0.20 10 1.011(12) 1.0057(64) 1.27 0.25 result = 1.0057(64) Q = 0.25 ``` -------------------------------- ### Initializing AdaptiveMap with Explicit Grid Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Shows how to create an AdaptiveMap instance by explicitly defining the grid nodes for each dimension. This allows for precise control over the initial mapping. ```python m = AdaptiveMap([[0, 0.1, 1], [-1, 0, 1]]) ``` -------------------------------- ### Vegas Right-Batch Integrand Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Example of a right-batch integrand using NumPy arrays for vectorized operations. The batch index is in the last/rightmost position. ```python def f_rbatch(x): dx2 = 0.0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 f = np.exp(-200 * dx2) return [f, f * x[0], f * x[0] ** 2] ``` -------------------------------- ### Vegas Left-Batch Integrand Example Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Example of a left-batch integrand where the batch index is the first/leftmost index. Requires explicit handling of the batch index for array operations. ```python @vegas.lbatchintegrand def f_lbatch(x): dx2 = 0.0 for d in range(4): dx2 += (x[:, d] - 0.5) ** 2 f = np.exp(-200 * dx2) ans = np.empty((x.shape[0], 3), float) for n in range(3): ans[:, n] = f * x[:, 0] ** n return ans ``` -------------------------------- ### Get Statistics for Array of Expectation Values with PDFIntegrator Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Use `PDFIntegrator.stats` to get statistical information for an array of expectation values. The uncertainties are the standard deviations with respect to the Gaussian distribution of `g`, combined with Vegas errors. ```python >>> g = gvar.gvar(['1(1)', '10(10)']) >>> g_ev = vegas.PDFIntegrator(g) >>> def f(p): ... return [p[0], p[1], p[0] * p[1]] >>> print(g_ev.stats(f)) [1.0(1.0) 10(10) 10(17)] ``` -------------------------------- ### PDF Integrator Initialization (Arbitrary PDF) Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Creates a PDFIntegrator for calculating expectation values with respect to an arbitrary probability density function 'pdf(p)', using 'g' to define and optimize the parameter space. ```python pdf_ev = vegas.PDFIntegrator(param=g, pdf=pdf) ``` -------------------------------- ### Define Array-Valued Integrand in Vegas Source: https://github.com/gplepage/vegas/blob/main/CHANGES.txt Example of defining an array-valued integrand by deriving from vegas.VecIntegrand. Ensure a __call__ method is defined. ```python class fv(vegas.VecIntegrand): def __call__(self, x): return x[:, 0] ** 2 + x[:, 1] ** 4 ``` -------------------------------- ### Integrate with Frozen Adaptation and Auto-Saving Source: https://context7.com/gplepage/vegas/llms.txt Shows how to perform a training pass with slow adaptation, followed by a production pass with adaptation frozen (`adapt=False`) for an unweighted average. Results are automatically saved to a pickle file and can be loaded later. It also demonstrates recomputing a weighted average from specific iterations. ```python import vegas import math import pickle def f(x): dx2 = 0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 return math.exp(-dx2 * 100.) * 1013.2118364296088 integ = vegas.Integrator([[-2, 2], [0, 2], [0, 2], [0, 2]]) # Training pass with slow adaptation (alpha=0.1) for peaky integrand integ(f, nitn=10, neval=1000, alpha=0.1) # Production pass: adaptation frozen, unweighted average, auto-save result = integ(f, nitn=10, neval=1000, adapt=False, save='result.pkl') print('result = %s Q = %.2f' % (result, result.Q)) # Load saved result later with open('result.pkl', 'rb') as ifile: saved = pickle.load(ifile) print(saved.summary()) # Recompute weighted average discarding first 5 iterations result2 = vegas.ravg(result.itn_results[5:]) print('trimmed = %s Q = %.2f' % (result2, result2.Q)) ``` -------------------------------- ### Initialize Vegas Integrator and Perform Integration Source: https://github.com/gplepage/vegas/blob/main/doc/html/tutorial.html Initializes the Vegas integrator with specified bounds and performs a warmup and volume calculation. Prints the integrator settings and the calculated volume. ```python integ = vegas.Integrator(dict( r=(0,1), phi=(DIM - 2) * [(0, np.pi)] + [(0, 2 * np.pi)] )) warmup = integ(f, neval=1000, nitn=10) volume = integ(f, neval=1000, nitn=10) print(integ.settings(), '\n') print(f'volume(dim={DIM}) = {volume}') ``` -------------------------------- ### Get AdaptiveMap Grid Settings Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Generate a string detailing the grid node locations. Control the maximum number of nodes displayed. ```python map.settings(ngrid=5) ``` -------------------------------- ### Initialize PDFIntegrator and Perform Integration Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Demonstrates typical usage of PDFIntegrator by defining parameters and a function, then performing the integration. The PDF is derived from the Gaussian distribution of the 'param' argument. ```python import vegas import gvar as gv import numpy as np g = gv.BufferDict() g['a'] = gv.gvar([10., 2.], [[1, 1.4], [1.4, 2]]) g['fb(b)'] = gv.BufferDict.uniform('fb', 2.9, 3.1) g_ev = vegas.PDFIntegrator(g) def f(p): a = p['a'] b = p['b'] return a[0] + np.fabs(a[1]) ** b result = g_ev(f, neval=10_000, nitn=5) print(' =', result) ``` -------------------------------- ### Get Expectation Values with PDFIntegrator Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Use PDFIntegrator to calculate expectation values of a function. The quoted errors represent integration uncertainties. ```python import vegas import gvar g = gvar.gvar(['1(1)', '10(10)']) g_ev = vegas.PDFIntegrator(g) def f(p): return dict(p=p, prod=p[0] * p[1]) print(g_ev(f)) ``` -------------------------------- ### Left-Aligned Batch Integrand with NumPy Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Use @vegas.lbatchintegrand for integrands where the batch index should be the first/leftmost index. This example demonstrates explicit indexing for batch processing. ```python import numpy as np import vegas @vegas.lbatchintegrand def f_lbatch(x): dx2 = 0.0 for d in range(4): dx2 += (x[:, d] - 0.5) ** 2 f = np.exp(-200 * dx2) ans = np.empty((x.shape[0], 3), float) for n in range(3): ans[:, n] = f * x[:, 0] ** n return ans ``` -------------------------------- ### Initialize and Use vegas.Integrator Source: https://context7.com/gplepage/vegas/llms.txt Demonstrates creating a 4D integrator, performing a training pass to adapt the map, and a production pass to obtain results. The summary and key statistics of the result are then printed. ```python import vegas import math def f(x): dx2 = 0 for d in range(4): dx2 += (x[d] - 0.5) ** 2 return math.exp(-dx2 * 100.) * 1013.2118364296088 # Create integrator for 4D volume [-1,1] x [0,1]^3 integ = vegas.Integrator([[-1, 1], [0, 1], [0, 1], [0, 1]]) # Step 1: training pass — adapt the map, discard results integ(f, nitn=10, neval=1000) # Step 2: production pass — map is adapted, keep results result = integ(f, nitn=10, neval=1000) print(result.summary()) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### Initial Grid Settings Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Displays the initial configuration of the AdaptiveMap grid before any training iterations. ```text initial grid: grid[ 0] = [ 0. 0.2 0.4 0.6 0.8 1. ] grid[ 1] = [ 0. 0.2 0.4 0.6 0.8 1. ] ``` -------------------------------- ### JAX GPU-accelerated Ridge Integrand Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/compiled_integrands.rst.txt An example of an integrand adapted for GPUs using JAX. This code snippet is incomplete and requires further definition for the loop body. ```python import vegas import jax jnp = jax.numpy @jax.jit def _jridge(x): N = 1000 x0 = jnp.linspace(0.25, 0.75, N) dx2 = 0.0 for xd in x: ``` -------------------------------- ### Integrator with MPI Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Configure a Vegas integrator for multi-processor evaluation using MPI. Ensure mpi4py is installed separately. Set mpi=True in the Integrator constructor. ```python import vegas integ = vegas.Integrator(4 * [[0, 1]], mpi=True) ``` -------------------------------- ### Perform Integration and Print Summary Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md After adapting the grid, perform the actual integration and print a summary of the results. This ensures the final result is reliable. ```python # step 2 -- integ has adapted to f; keep results result = integ(f, nitn=10, neval=1000) print(result.summary()) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### vegas.Integrator Initialization and Usage Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Demonstrates how to initialize and use the vegas.Integrator for Monte Carlo integration. The integrator adapts to the integrand over multiple iterations. ```APIDOC ## vegas.Integrator ### Description Adaptive multidimensional Monte Carlo integration. [`vegas.Integrator`](#vegas.Integrator) objects make Monte Carlo estimates of multidimensional functions `f(x)` where `x[d]` is a point in the integration volume. ### Parameters #### Path Parameters * **map** (array, dictionary, [`vegas.AdaptiveMap`](#vegas.AdaptiveMap) or [`vegas.Integrator`](#vegas.Integrator)) - Required - The integration region is specified by an array `map[d, i]` where `d` is the direction and `i=0,1` specify the lower and upper limits of integration in direction `d`. Integration points `x` are packaged as arrays `x[d]` when passed to the integrand `f(x)`. More generally, the integrator packages integration points in multidimensional arrays `x[d1, d2...dn]` when the integration limits are specified by `map[d1, d2...dn, i]` with `i=0,1`. These arrays can have any shape. Alternatively, the integration region can be specified by a dictionary whose values `map[key]` are either 2-tuples or arrays of 2-tuples corresponding to the lower and upper integration limits for the corresponding variables. Then integration points `xd` are packaged as dictionaries having the same structure as `map` but with the integration limits replaced by the values of the variables: for example, ```default map = dict(r=(0, 1), phi=[(0, np.pi), (0, 2 * np.pi)]) ``` indicates a three-dimensional integral over variables `r` (from `0` to `1`), `phi[0]` (from `0` to `np.pi`), and `phi[1]` (from `0` to `2*np.pi`). In this case integrands `f(xd)` have dictionary arguments `xd` where `xd['r']`, `xd['phi'][0]`, and `xd['phi'][1]` correspond to the integration variables. Finally `map` could be the integration map from another [`vegas.Integrator`](#vegas.Integrator), or that [`vegas.Integrator`](#vegas.Integrator) itself. In this case the grid is copied from the existing integrator. #### Query Parameters * **uses_jac** (*bool*) - Optional - Setting `uses_jac=True` causes [`vegas`](#module-vegas) to call the integrand with two arguments: `fcn(x, jac=jac)`. The second argument is the Jacobian `jac[d] = dx[d]/dy[d]` of the [`vegas`](#module-vegas) map. The integral over `x[d]` of `1/jac[d]` equals 1 (exactly). The default setting is `uses_jac=False`. * **nitn** (*positive int*) - Optional - The maximum number of iterations used to adapt to the integrand and estimate its value. The default value is 10; typical values range from 10 to 20. * **neval** (*positive int*) - Optional - Approximate number of integrand evaluations in each iteration of the [`vegas`](#module-vegas) algorithm. Increasing `neval` increases the precision: statistical errors should ### Method __call__ ### Endpoint N/A (Python Class Method) ### Request Example ```python integ = vegas.Integrator(integration_region) result = integ(f, nitn=10, neval=10000) ``` ### Response * **result** ([`RAvg`](#vegas.RAvg)) - The weighted average of all `nitn` estimates, together with an estimate of the statistical (Monte Carlo) uncertainty in that estimate of the integral. The result is an object of type [`RAvg`](#vegas.RAvg) (which is derived from `gvar.GVar`). ``` -------------------------------- ### Iterating with Jacobian in Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Processes batches of random numbers from the integrator, yielding hypercubes and integrand values. This example shows how to incorporate Jacobian information from the integrand. ```python for x, y, wgt, hcube in integ.random_batch(yield_hcube=True, yield_y=True): wgt_fx = wgt * batch_f(x, jac=integ.map.jac1d(y)) ``` -------------------------------- ### Batch Integration with Vegas Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Use the @vegas.rbatchintegrand decorator to integrate functions that operate on batches of points. This example demonstrates re-casting a sum as an integral for efficient computation. ```python import vegas import numpy as np @vegas.rbatchintegrand def ridge(x): """ Ridge of N Gaussians distributed along part of the diagonal. Gaussians are at points x0[d] = 0.25 + 0.5 * i /(N-1) for all directions d and Gaussians i=0...N-1. """ dim = len(x) - 1 N = 1000 norm = (100. / np.pi) ** (dim / 2.) x0 = 0.25 + 0.5 * np.floor(x[-1] * N) / (N - 1) dx2 = (x[0] - x0) ** 2 for d in range(1, dim): dx2 += (x[d] - x0) ** 2 return np.exp(-100. * dx2) * norm integ = vegas.Integrator(5 * [[0, 1]]) warmup = integ(ridge, nitn=10, neval=8e5) result = integ(ridge, nitn=10, neval=8e5, adapt=False) print('result = %s Q = %.2f' % (result, result.Q)) ``` -------------------------------- ### Initializing vegas.PDFIntegrator for Bayesian Integration Source: https://github.com/gplepage/vegas/blob/main/doc/html/outliers.html Shows how to initialize PDFIntegrator with a prior and a modified PDF. The integrator adapts to the modified PDF and can then be used to evaluate expectation values of functions of the fit parameters. ```python expval = gv.integrator.PDFIntegrator(prior, mod_pdf, nstrata=(100, 100, 10, 10)) ``` -------------------------------- ### Redefine Integration Volume for Peaky Integrands Source: https://github.com/gplepage/vegas/blob/main/doc/html/_sources/tutorial.rst.txt Modify the integration volume to handle more difficult, peaky integrands. This example redefines the integration bounds to a larger volume. ```python integ = vegas.Integrator([[-2, 2], [0, 2], [0, 2], [0., 2]]) ``` -------------------------------- ### Integrator.settings Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Assembles a summary of the integrator's current settings into a string. ```APIDOC ## Integrator.settings ### Description Assemble summary of integrator settings into string. ### Parameters * **ngrid** (*int*) – Number of grid nodes in each direction to include in summary. The default is 0. ### Returns * **str** – String containing the settings. ``` -------------------------------- ### Get Statistics with PDFIntegrator Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Use PDFIntegrator.stats to obtain statistical information about a function's distribution. Uncertainties include Vegas errors and Gaussian standard deviations. ```python import vegas import gvar g = gvar.gvar(['1(1)', '10(10)']) g_ev = vegas.PDFIntegrator(g) def f(p): return dict(p=p, prod=p[0] * p[1]) print(g_ev.stats(f)) ``` -------------------------------- ### Training and Adapting AdaptiveMap Source: https://github.com/gplepage/vegas/blob/main/doc/html/vegas.html Illustrates the process of adding training data (y, f) to an AdaptiveMap and then calling the adapt method to adjust the internal grid based on the provided data. ```python m.add_training_data(y, f) m.adapt(alpha=1.5) ``` -------------------------------- ### Vegas Integration with Adapt=False (Improved Results) Source: https://github.com/gplepage/vegas/blob/main/doc/source/tutorial.md Shows the output of the Vegas integrator after applying the improved two-step strategy with `adapt=False` for the final integration. This demonstrates the corrected and more accurate results, particularly for 'I' and 'sum(dI/I)'. ```default itn integral average chi2/dof Q ------------------------------------------------------- 1 0.85113(11) 0.85113(11) 0.00 1.00 2 0.85113(12) 0.851130(81) 0.99 0.50 3 0.85124(11) 0.851166(65) 1.08 0.21 4 0.85129(11) 0.851197(56) 1.04 0.31 5 0.85105(12) 0.851168(51) 0.99 0.54 6 0.85120(11) 0.851173(46) 0.99 0.57 7 0.85114(11) 0.851169(43) 0.98 0.63 8 0.85107(11) 0.851156(40) 1.03 0.29 9 0.85114(11) 0.851154(37) 1.04 0.19 10 0.85110(11) 0.851149(36) 1.02 0.31 I = 0.851149(36) dI/I = [0.00034(24) 0.00067(34) 0.00067(34) 0.00185(49) 0.00101(39)...] sum(dI/I) = 1.000000000000(37) ``` -------------------------------- ### Statistical Analysis with PDFIntegrator Source: https://github.com/gplepage/vegas/blob/main/doc/source/vegas.md Example of using PDFIntegrator to perform statistical analysis on a function, including calculating means and variances. The `@vegas.rbatchintegrand` decorator is used for batch processing of the function. ```python import gvar as gv import vegas g = gv.gvar(dict(a='1.0(5)', b='2(1)')) * gv.gvar('1.0(5)') g_ev = vegas.PDFIntegrator(g) g_ev(neval=10_000) # adapt the integrator to the PDF @vegas.rbatchintegrand def f(p): fp = dict(a=p['a'], b=p['b']) fp['a**2 * b'] = p['a']**2 * p['b'] return fp r = g_ev.stats(f) print(r) print(r.vegas_mean['a**2 * b']) print(r.vegas_cov['a**2 * b', 'a**2 * b'] ** 0.5) ```