MCintegration package¶
Submodules¶
base module¶
- class MCintegration.base.BaseDistribution(dim, device='cpu', dtype=torch.float32)[source]¶
Bases:
Module
Base distribution class for flow-based models. This is an abstract base class that provides structure for probability distributions used in Monte Carlo integration. Parameters do not depend on target variables (unlike a VAE encoder).
- class MCintegration.base.LinearMap(A, b, device=None, dtype=torch.float32)[source]¶
Bases:
Module
Linear transformation map of the form x = u * A + b. Maps points from one space to another using a linear transformation.
- forward(u)[source]¶
Apply forward transformation: x = u * A + b.
- Parameters:
u (torch.Tensor) – Input points
- Returns:
(transformed points, log_det_jacobian)
- Return type:
tuple
- class MCintegration.base.Uniform(dim, device='cpu', dtype=torch.float32)[source]¶
Bases:
BaseDistribution
Multivariate uniform distribution over [0,1]^dim. Samples from a uniform distribution in the hypercube [0,1]^dim.
integrators module¶
- class MCintegration.integrators.Integrator(bounds, f: Callable, f_dim=1, maps=None, q0=None, batch_size=1000, device=None, dtype=None)[source]¶
Bases:
object
Base class for all integrators. This class is designed to handle integration tasks over a specified domain (bounds) using a sampling method (q0) and optional transformation maps.
- __call__(**kwargs)[source]¶
Call the integrator to perform the integration. This should be implemented by subclasses.
- Returns:
Integration result
- sample(config, **kwargs)[source]¶
Generate samples for integration.
- Parameters:
config (Configuration) – The configuration object to store samples
**kwargs – Additional parameters
- statistics(means, vars, neval=None)[source]¶
Calculate statistics of the integration results.
- Parameters:
means (torch.Tensor) – Mean values from integration
vars (torch.Tensor) – Variance values from integration
neval (int, optional) – Number of function evaluations
- Returns:
Statistics of the integration including mean, error, and chi-squared
- Return type:
tuple
- class MCintegration.integrators.MarkovChainMonteCarlo(bounds, f: Callable, f_dim: int = 1, maps=None, q0=None, proposal_dist=None, batch_size: int = 1000, nburnin: int = 10, device=None, dtype=None)[source]¶
Bases:
Integrator
Markov Chain Monte Carlo (MCMC) integration method. Uses Metropolis-Hastings algorithm to generate samples from the target distribution.
- __call__(neval, mix_rate=0.5, nblock=32, meas_freq: int = 1, verbose=-1, **kwargs)[source]¶
Perform MCMC integration.
- Parameters:
neval (int) – Number of function evaluations
mix_rate (float) – Mixing rate between previous and new samples (0-1)
nblock (int) – Number of blocks for error estimation
meas_freq (int) – Measurement frequency
verbose (int) – Verbosity level (-1: silent, 0: minimal, 1+: more details)
**kwargs – Additional parameters passed to the sample method
- Returns:
Integration results with error estimates
- Return type:
- sample(config, nsteps=1, mix_rate=0.5, **kwargs)[source]¶
Generate samples using MCMC.
- Parameters:
config (Configuration) – Configuration object to store samples
nsteps (int) – Number of MCMC steps
mix_rate (float) – Mixing rate between previous and new samples (0-1)
**kwargs – Additional parameters
- Returns:
Updated configuration with new samples
- Return type:
- class MCintegration.integrators.MonteCarlo(bounds, f: Callable, f_dim=1, maps=None, q0=None, batch_size: int = 1000, device=None, dtype=None)[source]¶
Bases:
Integrator
Plain Monte Carlo integration method. Uses uniform or importance sampling to estimate integrals.
- __call__(neval, nblock=32, verbose=-1, **kwargs)[source]¶
Perform Monte Carlo integration.
- Parameters:
neval (int) – Number of function evaluations
nblock (int) – Number of blocks for error estimation
verbose (int) – Verbosity level (-1: silent, 0: minimal, 1+: more details)
**kwargs – Additional parameters passed to the sample method
- Returns:
Integration results with error estimates
- Return type:
- MCintegration.integrators.cleanup()[source]¶
Clean up distributed processing environment. Should be called after distributed computing is no longer needed.
- MCintegration.integrators.gaussian(dim, device, dtype, u, **kwargs)[source]¶
Gaussian proposal distribution for MCMC.
- Parameters:
dim (int) – Dimensionality of the space
device (str or torch.device) – Computation device
dtype (torch.dtype) – Data type
u (torch.Tensor) – Current position
**kwargs – Additional parameters
- Returns:
Proposed new position from Gaussian distribution centered at u
- Return type:
torch.Tensor
- MCintegration.integrators.get_ip() str [source]¶
Get the current machine’s IP address. Used for distributed computing setup.
- Returns:
IP address of the current machine
- Return type:
str
- MCintegration.integrators.get_open_port() int [source]¶
Find an available open port on the current machine. Used for distributed computing setup.
- Returns:
Available port number
- Return type:
int
- MCintegration.integrators.random_walk(dim, device, dtype, u, **kwargs)[source]¶
Random walk proposal distribution for MCMC.
- Parameters:
dim (int) – Dimensionality of the space
device (str or torch.device) – Computation device
dtype (torch.dtype) – Data type
u (torch.Tensor) – Current position
**kwargs – Additional parameters
- Returns:
Proposed new position
- Return type:
torch.Tensor
- MCintegration.integrators.setup(backend='gloo')[source]¶
Set up distributed processing environment for multi-GPU/CPU computation.
- Parameters:
backend (str) – Backend to use for distributed computing (‘gloo’, ‘nccl’, etc.)
- MCintegration.integrators.uniform(dim, device, dtype, u, **kwargs)[source]¶
Uniform proposal distribution for MCMC.
- Parameters:
dim (int) – Dimensionality of the space
device (str or torch.device) – Computation device
dtype (torch.dtype) – Data type
u (torch.Tensor) – Current position (ignored)
**kwargs – Additional parameters
- Returns:
Uniformly sampled new position
- Return type:
torch.Tensor
maps module¶
- class MCintegration.maps.CompositeMap(maps, device=None, dtype=None)[source]¶
Bases:
Map
Composite transformation map that applies multiple maps sequentially. Allows for complex transformations by composing simpler ones.
- class MCintegration.maps.Configuration(batch_size, dim, f_dim, device=None, dtype=torch.float32)[source]¶
Bases:
object
Configuration class to store samples and integration results. This class holds batches of points in both the original and transformed space, along with function values and weights.
- class MCintegration.maps.Map(device=None, dtype=torch.float32)[source]¶
Bases:
Module
Base class for all transformation maps. Maps transform points from the unit hypercube to the target integration domain with potentially better sampling distribution.
- forward(u)[source]¶
Transform points from the unit hypercube to the target domain.
- Parameters:
u (torch.Tensor) – Points in the unit hypercube
- Returns:
(transformed points, log_det_jacobian)
- Return type:
tuple
- Raises:
NotImplementedError – This is an abstract method
- class MCintegration.maps.Vegas(dim, ninc=1000, device=None, dtype=torch.float32)[source]¶
Bases:
Map
VEGAS algorithm implementation as a transformation map. VEGAS adapts to the integrand by adjusting the sampling density based on the magnitude of the integrand in different regions.
- adapt(alpha=0.5)[source]¶
Adapt the grid based on accumulated training data.
Shrinks grid increments in regions where the accumulated f is large, and grows them where f is small. The adaptation speed is controlled by alpha.
- Parameters:
alpha (float, optional) – Determines the speed with which the grid adapts to training data. Large (positive) values imply rapid evolution; small values (much less than one) imply slow evolution. Typical values are of order one. Choosing
alpha<0
causes adaptation to the unmodified training data (usually not a good idea).
- adaptive_training(batch_size, f, f_dim=1, epoch=10, alpha=0.5)[source]¶
Perform adaptive training to adjust the grid based on the training function.
- Parameters:
batch_size (int) – Number of samples per batch.
f (callable) – Training function that takes x and fx as inputs.
f_dim (int, optional) – Dimension of the function f. Defaults to 1.
epoch (int, optional) – Number of training epochs. Defaults to 10.
alpha (float, optional) – Adaptation rate. Defaults to 0.5.
- add_training_data(sample)[source]¶
Add training data
f
foru
-space pointsu
.Accumulates training data for later use by
self.adapt()
. Grid increments will be made smaller in regions wheref
is larger than average, and larger wheref
is smaller than average. The grid is unchanged (converged?) whenf
is constant across the grid.- Parameters:
u (tensor) –
u
values corresponding to the training data.u
is a contiguous 2-d tensor, whereu[j, d]
is for points along directiond
.f (tensor) – Training function values.
f[j]
corresponds to pointu[j, d]
inu
-space.
- forward(u)[source]¶
Transform points from the unit hypercube to the target domain.
- Parameters:
u (torch.Tensor) – Points in the unit hypercube
- Returns:
(transformed points, log_det_jacobian)
- Return type:
tuple
- Raises:
NotImplementedError – This is an abstract method
- inverse(x)[source]¶
Inverse map from x-space to u-space.
- Parameters:
x (torch.Tensor) – Tensor of shape (batch_size, dim) representing points in x-space.
- Returns:
Tensor of shape (batch_size, dim) representing points in u-space. log_detJ (torch.Tensor): Tensor of shape (batch_size,) representing the log determinant of the Jacobian.
- Return type:
u (torch.Tensor)
utils module¶
- class MCintegration.utils.RAvg(weighted=True, itn_results=None, sum_neval=0)[source]¶
Bases:
GVar
Running Average class that extends gvar.GVar. This class maintains a running average of measurements and keeps track of errors, providing statistical analysis of the integration results.
- property Q¶
Q or p-value of weighted average’s chi**2.
- __reduce_ex__(protocol)[source]¶
Support for pickling RAvg objects.
- Parameters:
protocol (int) – The protocol version
- Returns:
Data for reconstruction
- Return type:
tuple
- add(res)[source]¶
Add a new result to the running average.
- Parameters:
res (gvar.GVar) – Result to add to the running average
- property avg_neval¶
Average number of function evaluations per iteration.
- property chi2¶
chi**2 of weighted average.
- converged(rtol, atol)[source]¶
Check if the running average has converged within tolerance.
- Parameters:
rtol (float) – Relative tolerance
atol (float) – Absolute tolerance
- Returns:
True if converged, False otherwise
- Return type:
bool
- property dof¶
Number of degrees of freedom in weighted average.
- extend(ravg)[source]¶
Merge results from another RAvg object after results currently in self.
- Parameters:
ravg (RAvg) – Another RAvg object to merge with this one
- property nitn¶
Number of iterations.