//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Base/Math/IntegratorMCMiser.cpp
//! @brief     Implements class IntegratorMCMiser.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Base/Math/IntegratorMCMiser.h"

namespace {

//! Wraps external function pointer and external parameter pointer.
struct param_t {
    const IntegratorMCMiser::integrand_t* f;
    void* params;
};

//! Wraps external lambda function in a stateless C function that can be passed to GSL.
static double trampoline(double* x, size_t /*dim*/, void* P)
{
    const auto* p = static_cast<const param_t*>(P);
    return (*p->f)(x, p->params);
}

} // namespace


IntegratorMCMiser::IntegratorMCMiser(size_t dim)
    : m_dim(dim)
    , m_gsl_workspace{nullptr}
{
    m_gsl_workspace = gsl_monte_miser_alloc(m_dim);

    const gsl_rng_type* random_type;
    gsl_rng_env_setup();
    random_type = gsl_rng_default;
    m_random_gen = gsl_rng_alloc(random_type);
}

IntegratorMCMiser::~IntegratorMCMiser()
{
    gsl_monte_miser_free(m_gsl_workspace);
    gsl_rng_free(m_random_gen);
}

double IntegratorMCMiser::integrate(double* min_array, double* max_array, const integrand_t& f,
                                    void* params, size_t n_points) const
{
    param_t P{&f, params};

    gsl_monte_function F = {trampoline, m_dim, &P};

    double result, error;
    gsl_monte_miser_integrate(&F, min_array, max_array, m_dim, n_points, m_random_gen,
                              m_gsl_workspace, &result, &error);
    return result;
}
