Integrators

namespace integrator

Aliases & Traits

template<typename ...Args>
using point_t = Point<typename kakuhen::util::num_traits_of<Args...>::type>

Helper alias to create a Point type from variadic arguments.

Example: point_t<double> creates Point<NumericTraits<double, ...>>.

Template Parameters:

Args – Arguments passed to num_traits_of.

Header Utilities

inline IntegratorHeader parse_header(std::istream &in)

Parses an integrator header from an input stream.

This function reads a kakuhen file header from a stream and returns an IntegratorHeader struct containing the integrator’s ID and type information. It is independent of the specific integrator type.

Parameters:

in – The input stream to read from.

Throws:

std::runtime_error – if the file signature is invalid.

Returns:

An IntegratorHeader struct.

inline IntegratorHeader parse_header(const std::filesystem::path &filepath)

Parses an integrator header from a file.

This is a convenience wrapper around the stream version of parse_header.

Parameters:

filepath – The path to the file.

Throws:

std::ios_base::failure – if the file cannot be opened.

Returns:

An IntegratorHeader struct.

Enums

enum class IntegratorId : uint8_t

Identifiers for the different available integrators.

Values:

enumerator PLAIN

Plain Monte Carlo integrator.

enumerator VEGAS

VEGAS adaptive integrator.

enumerator BASIN

BASIN adaptive integrator.

Functions

template<typename T, typename U>
inline IntegralAccumulator<T, U> make_integral_accumulator(const T &value, const T &error, const U &n)

Factory function to create an IntegralAccumulator from value, error, and count.

This function reconstructs an IntegralAccumulator object given a mean value, its error, and the number of samples. This is useful for initializing an accumulator from summary statistics.

Template Parameters:
  • T – The value type.

  • U – The count type.

Parameters:
  • value – The mean value of the integral.

  • error – The error (standard deviation) of the integral.

  • n – The number of samples.

Returns:

An IntegralAccumulator object initialized with the provided data.

constexpr std::string_view to_string(IntegratorId id) noexcept

Converts an IntegratorId to its string representation.

Parameters:

id – The IntegratorId to convert.

Returns:

A string view of the integrator name.

template<typename NT = util::num_traits_t<>, typename RNG = typename IntegratorDefaults<NT>::rng_type, typename DIST = typename IntegratorDefaults<NT>::dist_type>
class Basin : public kakuhen::integrator::IntegratorBase<Basin<util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>, util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>
#include <basin.h>

An integrator based on Blockwise Adaptive Sampling with Interdimensional Nesting (BASIN).

This class implements a sophisticated adaptive Monte Carlo integration algorithm that models correlations between integration dimensions. It uses a nested grid structure where each dimension’s grid is conditioned on the value of another, allowing it to adapt to complex integrand shapes.

The algorithm first adapts one-dimensional marginal grids and then uses the Earth Mover’s Distance (EMD) to score the correlations between dimensions, determining an optimal sampling order for subsequent iterations. This can significantly improve efficiency for integrands with strong inter-dimensional dependencies.

Template Parameters:
  • NT – The numeric traits for the integrator.

  • RNG – The random number generator to use.

  • DIST – The random number distribution to use.

Integration Implementation

template<typename I>
inline int_acc_type integrate_impl(I &&integrand, U neval)

Implementation of the integration loop for a single iteration.

Template Parameters:

I – The type of the integrand function.

Parameters:
  • integrand – The function to integrate.

  • neval – The number of evaluations to perform.

Returns:

An int_acc_type containing the accumulated results for this iteration.

inline void reset()

Resets the grid and all accumulators to their initial state.

inline void adapt()

Adapts the nested grids based on the accumulated data.

This method performs the core logic of the BASIN algorithm. It refines the diagonal (1D) and off-diagonal (2D) grids based on the variance of the integrand and then determines the optimal sampling order for the next iteration based on dimension correlations.

inline void clear_data()

Clears accumulated integration data.

Utilities

inline void print_grid(const std::string &prefix = "") const

Prints the current grid structure to standard output.

Parameters:

prefix – A string prefix to prepend to each line of output.

inline void nest_grid(const kakuhen::ndarray::NDView<T, S> &grid1, const kakuhen::ndarray::NDView<T, S> &grid2) const

Debug helper to visualize nested grids.

Parameters:
  • grid1 – The first 1D grid view.

  • grid2 – The second 1D grid view.

Output & Serialization Implementation

template<typename P>
inline void print_state(P &prt) const

Prints the internal state of the integrator.

Template Parameters:

P – The printer type.

Parameters:

prt – The printer object.

inline void write_state_stream(std::ostream &out) const

Writes the internal state to a stream.

Parameters:

out – The output stream.

inline void read_state_stream(std::istream &in)

Reads the internal state from a stream.

Parameters:

in – The input stream.

inline void write_data_stream(std::ostream &out) const

Writes accumulated data to a stream.

Parameters:

out – The output stream.

inline void read_data_stream(std::istream &in)

Reads accumulated data from a stream.

Parameters:

in – The input stream.

inline void accumulate_data_stream(std::istream &in)

Accumulates data from a stream into the current integrator.

Parameters:

in – The input stream.

Public Functions

inline explicit Basin(S ndim, S ndiv1 = 8, S ndiv2 = 16)

Construct a new Basin object.

Parameters:
  • ndim – The number of dimensions of the integration.

  • ndiv1 – The number of divisions for the coarse grid along each dimension.

  • ndiv2 – The number of divisions for the fine grid along each dimension.

inline explicit Basin(const std::filesystem::path &filepath)

Construct a new Basin object by loading its state from a file.

Parameters:

filepath – The path to the file containing the integrator’s state.

inline S ndiv1() const noexcept

Get the number of grid divisions in the first dimension.

Returns:

The value of the number of grid divisions for dim 1.

inline S ndiv2() const noexcept

Get the number of grid divisions in the second dimension.

Returns:

The value of the number of grid divisions for dim 2.

inline S ndiv0() const noexcept

Get the number of grid divisions in the diagonal dimension.

Returns:

The value of the number of grid divisions for projections.

inline void set_alpha(const T &alpha) noexcept

Set the alpha parameter for grid adaptation.

Parameters:

alpha – The new value for the alpha parameter.

inline T alpha() const noexcept

Get the alpha parameter for grid adaptation.

Returns:

The current value of the alpha parameter.

inline void set_weight_smooth(const T &weight_smooth) noexcept

Set the weight for smoothing the grid adaptation.

Parameters:

weight_smooth – The new value for the weight smoothing parameter.

inline T weight_smooth() const noexcept

Get the weight for smoothing the grid adaptation.

Returns:

The current value of the weight smoothing parameter.

inline void set_min_score(const T &min_score) noexcept

Set the minimum score for dimension correlation.

Parameters:

min_score – The new value for the minimum score.

inline T min_score() const noexcept

Get the minimum score for dimension correlation.

Returns:

The current value of the minimum score.

inline kakuhen::util::Hash hash() const

Computes a hash of the current grid state.

Returns:

A kakuhen::util::Hash object representing the state of the grid.

inline std::string prefix(bool with_hash = false) const noexcept

Generates a prefix string for filenames.

Parameters:

with_hash – If true, the hash of the grid is included in the prefix.

Returns:

A prefix string for filenames.

Public Members

size_type ndim_

The number of dimensions for the integration.

options_type opts_

The persistent options for the integrator.

template<typename T, typename U>
struct GridAccumulator
#include <grid_accumulator.h>

Accumulates values for a grid cell.

Todo:

Should maybe consider DOD design for better cache alignment?

This struct is used to accumulate a sum of values and a count of contributions for a specific cell within a grid, typically used in adaptive integration algorithms like VEGAS to store information about the integrand’s behavior in different regions.

Template Parameters:
  • T – The value type to accumulate (e.g., double).

  • U – The count type for the number of accumulations (e.g., uint64_t).

State Manipulation

inline void accumulate(const T &x) noexcept

Accumulate a single value.

Adds the given value to the accumulator and increments the count.

Parameters:

x – The value to accumulate.

inline void accumulate(const GridAccumulator<T, U> &other) noexcept

Accumulate values from another GridAccumulator.

Adds the accumulated value and count from another GridAccumulator object to this one.

Parameters:

other – The other GridAccumulator to accumulate from.

inline void reset() noexcept

Resets the accumulator to its initial state (zero value, zero count).

inline void reset(const T &acc, const U &n) noexcept

Resets the accumulator with specific pre-calculated values.

Parameters:
  • acc – The new accumulated value.

  • n – The new number of accumulations.

Operators

inline GridAccumulator &operator+=(const T &x) noexcept

Adds a value to the accumulator.

Parameters:

x – The value to add.

Returns:

A reference to this accumulator.

inline GridAccumulator &operator+=(const GridAccumulator<T, U> &other) noexcept

Adds another accumulator’s data to this one.

Parameters:

other – The other accumulator.

Returns:

A reference to this accumulator.

Queries

inline U count() const noexcept

Get the total number of accumulated values.

Returns:

The count of accumulated values.

inline T value() const noexcept

Get the accumulated value.

Returns:

The current accumulated sum.

Serialization

inline void serialize(std::ostream &out, bool with_type = false) const noexcept

Serializes the accumulator to an output stream.

Parameters:
  • out – The output stream.

  • with_type – Whether to include type information.

inline void deserialize(std::istream &in, bool with_type = false)

Deserializes the accumulator from an input stream.

Parameters:
  • in – The input stream.

  • with_type – Whether to verify type information.

Public Members

T acc_ = T(0)

The accumulated value.

U n_ = U(0)

The number of times a value has been accumulated.

template<typename T, typename U>
struct IntegralAccumulator
#include <integral_accumulator.h>

Accumulates integral values and their squares for statistical analysis.

Todo:

Also write an accum function add(f) and add(f,f2)

This struct is used to accumulate function values and their squares during Monte Carlo integration. It provides methods to calculate the mean, variance, and error of the integral.

Note

considered switching to Welford algo: Decided against it as division is 10x-20x slower than addition and compensated summation is more performant and provides the necessry precision

Template Parameters:
  • T – The value type for the integral (e.g., double).

  • U – The count type for the number of evaluations (e.g., uint64_t).

State Manipulation

inline void accumulate(const T &f) noexcept

Accumulate a single function value.

Adds f to the sum of function values and f*f to the sum of squared function values. Increments the sample count.

Parameters:

f – The function value to accumulate.

inline void accumulate(const T &f, const T &f2) noexcept

Accumulate a function value and its square.

Adds f to the sum of function values and f2 to the sum of squared function values. Increments the sample count.

Parameters:
  • f – The function value to accumulate.

  • f2 – The squared function value to accumulate.

inline void accumulate(const IntegralAccumulator<T, U> &other) noexcept

Accumulate values from another IntegralAccumulator.

Adds the accumulated sums and counts from another IntegralAccumulator object to this one.

Parameters:

other – The other IntegralAccumulator to accumulate from.

inline void reset() noexcept

Resets the accumulator to its initial state (zero sums, zero count).

inline void reset(const T &f, const T &f2, const U &n) noexcept

Resets the accumulator with specific pre-calculated values.

Parameters:
  • f – The new sum of function values.

  • f2 – The new sum of squared function values.

  • n – The new number of accumulated samples.

Statistics

inline U count() const noexcept

Get the total number of accumulated samples.

Returns:

The number of samples.

inline T value() const noexcept

Calculate the mean value of the accumulated function values.

Returns:

The mean value.

inline T variance() const noexcept

Calculate the variance of the mean value.

This is the variance of the expectation value, not the variance of the underlying distribution.

Returns:

The variance of the mean value. Returns 0 if n_ <= 1.

inline T error() const noexcept

Calculate the standard deviation (error) of the mean value.

Returns:

The standard deviation of the mean value.

Serialization

inline void serialize(std::ostream &out, bool with_type = false) const noexcept

Serializes the accumulator to an output stream.

Parameters:
  • out – The output stream.

  • with_type – Whether to include type information.

inline void deserialize(std::istream &in, bool with_type = false)

Deserializes the accumulator from an input stream.

Parameters:
  • in – The input stream.

  • with_type – Whether to verify type information.

Throws:

std::runtime_error – if type information mismatches.

Public Members

acc_type f_ = {}

Accumulator for the sum of function values.

acc_type f2_ = {}

Accumulator for the sum of squared function values.

U n_ = 0

Number of accumulated samples.

template<typename Derived, typename NT = util::num_traits_t<>, typename RNG = typename IntegratorDefaults<NT>::rng_type, typename DIST = typename IntegratorDefaults<NT>::dist_type>
class IntegratorBase
#include <integrator_base.h>

Base class for all integrators using CRTP.

This class provides the common infrastructure for all Monte Carlo integrators in the kakuhen library. It handles the main integration loop, options management, result accumulation, and state serialization. The Curiously Recurring Template Pattern (CRTP) is used to achieve static polymorphism, allowing for compile-time dispatch to the specific integrator’s implementation.

Template Parameters:
  • Derived – The derived integrator class (e.g., Vegas, Plain).

  • NT – The numeric traits for the integrator, defining value_type, size_type, and count_type.

  • RNG – The random number generator to use.

  • DIST – The random number distribution to use.

Subclassed by kakuhen::integrator::Basin< NT, RNG, DIST >, kakuhen::integrator::Plain< NT, RNG, DIST >, kakuhen::integrator::Vegas< NT, RNG, DIST >

Options & Configuration

inline void set_options(const options_type &opts)

Set the persistent options for the integrator.

These options will be used for all subsequent integration calls, unless they are temporarily overridden by the options passed to the integrate method.

Parameters:

opts – The options to set.

Throws:

std::invalid_argument – if an option is incompatible with the integrator’s features.

inline void set_seed(seed_type seed) noexcept

Sets the seed for the random number generator.

Parameters:

seed – The seed value.

inline void set_seed()

Sets a new seed for the random number generator.

If a seed has been set before, it increments the seed by one.

inline seed_type seed() const noexcept

Gets the current seed of the random number generator.

Returns:

The current seed value.

inline void set_user_data(void *user_data = nullptr) noexcept

Sets the user data pointer.

Parameters:

user_data – A pointer to user-defined data.

inline void *user_data() const noexcept

Gets the user data pointer.

Returns:

The user data pointer.

Integration

template<typename I, typename ...Keys>
inline result_type integrate(I &&integrand, const Keys&... keys)

The main integration routine, using keyword-style options.

This overload allows for setting integration options using a more readable, keyword-argument-like syntax.

Example: integrate(func, keys::neval = 1000, keys::niter = 5)

Template Parameters:
  • I – The type of the integrand function.

  • Keys – A parameter pack of option setters.

Parameters:
  • integrand – The function to integrate.

  • keys – A comma-separated list of option setters.

Returns:

A result_type object containing the result of the integration.

template<typename I>
inline result_type integrate(I &&integrand, const options_type &opts)

The main integration routine.

This method performs the numerical integration of the given function. It iterates a number of times, and in each iteration, it calls the integrate_impl method of the derived integrator class. The results of each iteration are accumulated, and a final result is returned.

Template Parameters:

I – The type of the integrand function.

Parameters:
  • integrand – The function to integrate. It should take a point_type as input and return a value_type.

  • opts – The options for this integration call. These are temporary overrides for the persistent options of the integrator.

Throws:

std::invalid_argument – if required options like neval or niter are missing.

Returns:

A result_type object containing the result of the integration.

Output & Serialization

template<typename P>
inline void print(P &prt) const

Prints the state of the integrator using a specified printer.

This method serializes the integrator’s configuration and state (if supported) to a structured format (e.g., JSON) using the provided printer object.

Template Parameters:

P – The type of the printer, which must conform to the PrinterBase interface.

Parameters:

prt – The printer object to use for output.

template<typename D = Derived>
inline void save(const std::filesystem::path &filepath) const

Save the state of the integrator to a file.

This method serializes the internal state of the integrator to the specified file. This allows the integration to be resumed later.

Note

Available only if the derived type models detail::HasStateStream.

Parameters:

filepath – The path to the file where the state should be saved.

template<typename D = Derived>
inline std::filesystem::path save() const

Save the state of the integrator to the default state file.

Returns:

The path to the saved state file.

template<typename D = Derived>
inline void load(const std::filesystem::path &filepath)

Load the state of the integrator from a file.

This method deserializes the internal state of the integrator from the specified file. This allows the integration to be resumed from a previous state.

Note

Available only if the derived type models detail::HasStateStream.

Parameters:

filepath – The path to the file from which the state should be loaded.

template<typename D = Derived>
inline std::filesystem::path load()

Load the state of the integrator from the default state file.

Returns:

The path to the loaded state file.

template<typename D = Derived>
inline void save_data(const std::filesystem::path &filepath) const

Save accumulated data of the integrator to a file.

This method is for integrators that support data accumulation. It serializes the accumulated sample data to the specified file.

Note

Available only if the derived type models detail::HasDataStream.

Parameters:

filepath – The path to the file where the data should be saved.

template<typename D = Derived>
inline std::filesystem::path save_data() const

Save accumulated data of the integrator to the default data file.

Returns:

The path to the saved data file.

template<typename D = Derived>
inline void append_data(const std::filesystem::path &filepath)

Append accumulated data from a file to the integrator.

This method deserializes accumulated sample data from a file and adds it to the integrator’s internal data accumulator, allowing for the combination of data from multiple independent runs.

Note

Available only if the derived type models detail::HasDataStream.

Parameters:

filepath – The path to the file from which to append the data.

template<typename D = Derived>
inline std::filesystem::path append_data()

Append accumulated data from the default data file to the integrator.

Returns:

The path to the appended data file.

inline void write_rng_state_stream(std::ostream &out) const

Writes the state of the random number generator to a stream.

inline void read_rng_state_stream(std::istream &in)

Reads the state of the random number generator from a stream.

inline void save_rng_state(const std::filesystem::path &filepath) const

Saves the random number generator state to a file.

inline void load_rng_state(const std::filesystem::path &filepath)

Loads the random number generator state from a file.

Public Functions

inline explicit IntegratorBase(size_type ndim = 0, const options_type &opts = {})

Constructs an integrator base.

Parameters:
  • ndim – The number of dimensions for the integration.

  • opts – Initial options for the integrator.

inline constexpr IntegratorId id() const noexcept

Get the unique ID of the integrator.

Returns:

The IntegratorId of the derived class.

inline size_type ndim() const noexcept

Gets the number of dimensions for the integration.

Returns:

The number of dimensions.

Public Static Functions

static inline constexpr IntegratorId class_id() noexcept

Get the unique ID of the integrator type.

Returns:

The compile-time IntegratorId of the derived class.

template<typename NT = util::num_traits_t<>>
struct IntegratorDefaults
#include <integrator_base.h>

Default type definitions for integrator template parameters.

struct IntegratorHeader
#include <integrator_base.h>

Header structure returned by parse_header containing integrator metadata.

Public Members

IntegratorId id

The unique ID of the integrator.

kakuhen::util::type::TypeId value_type_id

Type ID for the integration value type.

kakuhen::util::type::TypeId size_type_id

Type ID for the size type.

kakuhen::util::type::TypeId count_type_id

Type ID for the count type.

template<typename T, typename U, typename R>
struct Options
#include <options.h>

Configuration options for integrators.

This struct defines a set of optional parameters that can be used to configure the behavior of the integrators. All options are std::optional to allow for default values to be used when an option is not explicitly set.

It supports designated initializers (C++20) for easy configuration: Options{.neval = 1000, .seed = 42}

Template Parameters:
  • T – The value type for integral results (e.g., double).

  • U – The count type for the number of evaluations (e.g., uint64_t).

  • R – The seed type for the random number generator (e.g., uint64_t).

Public Functions

inline void set(const Options &opts)

Sets options from another Options object.

Only non-empty optional values from the input opts will overwrite the current object’s corresponding optional values.

Parameters:

opts – The Options object to take values from.

inline void apply(Options &opts) const noexcept

Applies the current options to another Options object.

This is a convenience method that calls opts.set(*this).

Parameters:

opts – The Options object to apply values to.

Public Members

std::optional<count_type> neval

Number of evaluations for an integration step.

std::optional<count_type> niter

Number of iterations for an integration run.

std::optional<bool> adapt

Whether to run adaptation after integration.

std::optional<bool> frozen

Whether to freeze grids (disable adaptation + data collection).

std::optional<seed_type> seed

Seed of the random number generator.

std::optional<value_type> rel_tol

Relative precision goal for convergence.

std::optional<value_type> abs_tol

Absolute precision goal for convergence.

std::optional<int> verbosity

Verbosity level of output messages.

std::optional<void*> user_data

Pointer to user-defined data (non-owning).

std::optional<std::filesystem::path> file_path

Path for saving state/data.

Friends

inline friend std::ostream &operator<<(std::ostream &os, const Options &opts)

Stream insertion operator for Options.

Prints the set options in a readable format.

Parameters:
  • os – The output stream.

  • opts – The Options object to print.

Returns:

The output stream.

struct keys
#include <options.h>

Provides keyword objects for setting options.

This struct contains static OptionKey members for each option field, allowing for syntax like keys::neval = 1000.

Usage example: integrator.integrate(func, Options::keys::neval = 1000);

Public Static Attributes

static constexpr OptionKey<&Options::neval> neval = {}

Key for neval option.

static constexpr OptionKey<&Options::niter> niter = {}

Key for niter option.

static constexpr OptionKey<&Options::adapt> adapt = {}

Key for adapt option.

static constexpr OptionKey<&Options::frozen> frozen = {}

Key for frozen option.

static constexpr OptionKey<&Options::seed> seed = {}

Key for seed option.

static constexpr OptionKey<&Options::rel_tol> rel_tol = {}

Key for rel_tol option.

static constexpr OptionKey<&Options::abs_tol> abs_tol = {}

Key for abs_tol option.

static constexpr OptionKey<&Options::verbosity> verbosity = {}

Key for verbosity option.

static constexpr OptionKey<&Options::user_data> user_data = {}

Key for user_data option.

static constexpr OptionKey<&Options::file_path> file_path = {}

Key for file_path option.

template<auto MemberPtr>
struct OptionKey
#include <options.h>

Helper for keyword-argument-like option setting.

This struct facilitates a fluent interface for setting individual options using a syntax similar to keyword arguments in other languages.

Template Parameters:

MemberPtr – A pointer to a member of the Options struct.

template<typename V>
struct Setter
#include <options.h>
template<typename NT = util::num_traits_t<>, typename RNG = typename IntegratorDefaults<NT>::rng_type, typename DIST = typename IntegratorDefaults<NT>::dist_type>
class Plain : public kakuhen::integrator::IntegratorBase<Plain<util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>, util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>
#include <plain.h>

A naive Monte Carlo integrator.

This class implements a simple (naive) Monte Carlo integration algorithm. It samples points uniformly within the unit hypercube and accumulates the function values. This integrator is straightforward but less efficient than adaptive methods for many integrands, as it does not attempt to concentrate samples in important regions. It does not support any special features like adaptation or state serialization.

Template Parameters:
  • NT – The numeric traits for the integrator.

  • RNG – The random number generator to use.

  • DIST – The random number distribution to use.

Integration Implementation

template<typename I>
inline int_acc_type integrate_impl(I &&integrand, count_type neval)

Implementation of the integration loop for a single iteration.

Template Parameters:

I – The type of the integrand function.

Parameters:
  • integrand – The function to integrate.

  • neval – The number of evaluations to perform.

Returns:

An int_acc_type containing the accumulated results for this iteration.

Public Functions

inline explicit Plain(size_type ndim)

Construct a new Plain object.

Parameters:

ndim – The number of dimensions of the integration.

Public Members

size_type ndim_

The number of dimensions for the integration.

options_type opts_

The persistent options for the integrator.

template<typename NT = kakuhen::util::num_traits_t<>>
struct Point
#include <point.h>

Represents a sample point in the integration space.

This struct encapsulates all the necessary information for a single sample point during a Monte Carlo integration. It is passed to the integrand function/functor.

It owns the memory for the coordinates (x) using a std::vector.

Template Parameters:

NT – The numeric traits for the integrator, defining value_type, size_type, and count_type.

Public Functions

inline explicit Point(size_type dimensions, void *user_data = nullptr)

Constructs a Point with a specified dimensionality.

Parameters:
  • dimensions – The number of dimensions for the point.

  • user_data – Optional pointer to user-defined data.

Public Members

std::vector<value_type> x

The coordinates of the point in the integration space.

value_type weight

The weight associated with this point (e.g. importance sampling).

size_type ndim

The dimensionality of the integration space (matches x.size()).

count_type sample_index

The index of the current sample in the sequence.

void *user_data

Pointer to user-defined data passed to the integrand.

template<typename T, typename U>
class Result
#include <result.h>

Stores and processes results from multiple integral accumulations.

This class is designed to accumulate and analyze results from multiple independent integral calculations. It can compute the weighted mean, variance, error, chi-squared, and degrees of freedom from a collection of IntegralAccumulator objects.

Template Parameters:
  • T – The value type for the integral results (e.g., double).

  • U – The count type for the number of evaluations (e.g., uint64_t).

Queries

inline U size() const noexcept

Get the number of individual integral results accumulated.

Returns:

The number of accumulated IntegralAccumulator objects.

inline U count() const noexcept

Get the total number of function evaluations across all accumulated results.

Returns:

The sum of count() from all IntegralAccumulator objects.

inline T value() const

Computes the weighted mean of the accumulated integral results.

The weighting is done by the inverse variance of each individual result.

Throws:

std::runtime_error – if no results have been accumulated.

Returns:

The weighted mean value of the integral.

inline T variance() const

Computes the variance of the weighted mean.

Throws:

std::runtime_error – if no results have been accumulated.

Returns:

The variance of the weighted mean.

inline T error() const

Computes the error (standard deviation) of the weighted mean.

This is the square root of the variance.

Returns:

The error of the weighted mean.

inline T chi2() const

Computes the chi-squared value of the accumulated results.

This measures the consistency of the individual results with their weighted mean.

Returns:

The chi-squared value. Returns 0 if there are less than 2 results.

inline U dof() const

Get the degrees of freedom for the chi-squared calculation.

Returns:

The number of results minus one, or zero if there’s one or fewer results.

inline T chi2dof() const

Computes the chi-squared per degree of freedom (chi2/dof).

This is a common metric for assessing the goodness-of-fit or consistency.

Returns:

The chi-squared per degree of freedom. Returns 0 if there are less than 2 results.

Serialization

inline void serialize(std::ostream &out, bool with_type = false) const noexcept

Serializes the result object to an output stream.

Parameters:
  • out – The output stream.

  • with_type – Whether to include type information.

inline void deserialize(std::istream &in, bool with_type = false)

Deserializes the result object from an input stream.

Parameters:
  • in – The input stream.

  • with_type – Whether to verify type information.

Public Functions

inline void accumulate(const int_acc_type &acc)

Accumulate a single integral result.

Adds an IntegralAccumulator object to the collection of results.

Parameters:

acc – The IntegralAccumulator object to add.

inline void accumulate(const Result<T, U> &res)

Accumulate results from another Result object.

Appends all IntegralAccumulator objects from another Result instance to this collection.

Parameters:

res – The Result object whose contents will be accumulated.

inline void reset()

Clears all accumulated results.

template<typename NT = util::num_traits_t<>, typename RNG = typename IntegratorDefaults<NT>::rng_type, typename DIST = typename IntegratorDefaults<NT>::dist_type>
class Vegas : public kakuhen::integrator::IntegratorBase<Vegas<util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>, util::num_traits_t<>, typename IntegratorDefaults<util::num_traits_t<>>::rng_type, typename IntegratorDefaults<util::num_traits_t<>>::dist_type>
#include <vegas.h>

The VEGAS Monte Carlo integrator.

This class implements the VEGAS algorithm, a classic method for multi-dimensional Monte Carlo integration based on adaptive importance sampling. It divides the integration space into a grid and adapts the grid over several iterations to concentrate sampling in regions where the integrand is the largest. This leads to a more efficient convergence compared to naive Monte Carlo sampling.

The state of the grid can be saved and loaded to resume an integration.

Template Parameters:
  • NT – The numeric traits for the integrator.

  • RNG – The random number generator to use.

  • DIST – The random number distribution to use.

Integration Implementation

template<typename I>
inline int_acc_type integrate_impl(I &&integrand, U neval)

Implementation of the integration loop for a single iteration.

Template Parameters:

I – The type of the integrand function.

Parameters:
  • integrand – The function to integrate.

  • neval – The number of evaluations to perform.

Returns:

An int_acc_type containing the accumulated results for this iteration.

inline void reset()

Reset the grid to a uniform state.

This method resets the grid to a uniform state, where each dimension is divided into ndiv equal-sized intervals. It also clears the accumulator and the result.

inline void adapt()

Adapt the grid based on the accumulated data.

This method adapts the grid based on the data that has been accumulated during the integration. It uses the accumulated function values to refine the grid, so that more points are sampled in the regions where the integrand is large.

inline void clear_data()

Clears accumulated integration data.

inline void print_grid() const

Prints the current grid structure to standard output.

Public Functions

inline explicit Vegas(S ndim, S ndiv = 128)

Construct a new Vegas object.

Parameters:
  • ndim – The number of dimensions of the integration.

  • ndiv – The number of divisions of the grid along each dimension.

inline explicit Vegas(const std::filesystem::path &filepath)

Construct a new Vegas object by loading state from a file.

Parameters:

filepath – The path to the file containing the integrator state.

inline S ndiv() const noexcept

Get the number of grid divisions.

Returns:

The value of the number of grid divisions.

inline void set_alpha(const T &alpha) noexcept

Set the alpha parameter for grid adaptation.

The alpha parameter controls the damping of the grid adaptation. A value of 0 means no damping, while a value greater than 0 will dampen the adaptation. The default value is 0.75.

Parameters:

alpha – The new value for the alpha parameter.

inline T alpha() const noexcept

Get the alpha parameter for grid adaptation.

Returns:

The current value of the alpha parameter.

inline kakuhen::util::Hash hash() const

Computes a hash of the current grid state.

Returns:

A kakuhen::util::Hash object representing the state of the grid.

inline std::string prefix(bool with_hash = false) const noexcept

Generates a prefix string for filenames.

Parameters:

with_hash – If true, the hash of the grid is included in the prefix.

Returns:

A prefix string for filenames.

Public Members

size_type ndim_

The number of dimensions for the integration.

options_type opts_

The persistent options for the integrator.

namespace detail

Traits Deduction

template<typename F>
using num_traits_arg_t = kakuhen::util::num_traits_t<std::remove_cvref_t<typename function_traits<decltype(&F::operator())>::argument_type>>

Helper alias to deduce NumericTraits from a functor’s argument type.

This alias inspects the operator() of the given functor type F, extracts its argument type, removes const/volatile/reference qualifiers, and then uses num_traits_t to determine the corresponding NumericTraits.

This is used to automatically deduce numeric traits from the integrand function passed to the integrator.

Template Parameters:

F – The functor type (e.g., lambda or struct with operator()).

Enums

enum class FileType : uint8_t

Values:

enumerator STATE
enumerator DATA

Variables

constexpr std::string_view file_signature = "KAKUHEN\0"
constexpr std::size_t file_signature_size = file_signature.size()
constexpr std::string_view suffix_state = ".khs"
constexpr std::string_view suffix_data = ".khd"
template<typename T>
struct function_traits

Helper struct to extract argument and return types from function objects.

This primary template is undefined and will cause a compile-time error if instantiated with a type that is not a pointer to member function.

Template Parameters:

T – The type to inspect.

template<typename C, typename R, typename Arg>
struct function_traits<R (C::*)(Arg) const>
#include <detail.h>

Specialization for const-qualified member functions (e.g., lambdas).

Template Parameters:
  • C – The class type.

  • R – The return type.

  • Arg – The argument type.

template<typename C, typename R, typename Arg>
struct function_traits<R (C::*)(Arg)>
#include <detail.h>

Specialization for non-const member functions.

Template Parameters:
  • C – The class type.

  • R – The return type.

  • Arg – The argument type.