//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Fit/Kernel/Kernel.cpp
//! @brief     Implements class Kernel.
//!
//! @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 "Fit/Kernel/Kernel.h"
#include "Fit/Kernel/MinimizerFactory.h"
#include "Fit/Minimizer/IMinimizer.h"
#include "Fit/Tool/WallclockTimer.h"

using namespace mumufit;

namespace {

const std::string default_minimizer = "Minuit2";
const std::string default_algorithm = "Migrad";

} // namespace

Kernel::Kernel()
{
    setMinimizer(default_minimizer, default_algorithm);
}

Kernel::~Kernel() = default;

void Kernel::setMinimizer(const std::string& minimizerName, const std::string& algorithmName,
                          const std::string& options)
{
    m_minimizer.reset(MinimizerFactory::createMinimizer(minimizerName, algorithmName, options));
}

void Kernel::setMinimizer(IMinimizer* minimizer)
{
    m_minimizer.reset(minimizer);
}

MinimizerResult Kernel::minimize(const fcn_scalar_t fcn, const Parameters& parameters) const
{
    WallclockTimer timer;
    timer.start();
    if (m_minimizer->requiresResiduals())
        throw std::runtime_error(
            "Error in Kernel::minimize: the chosen minimizer requires residuals computation. "
            "Please use FitObjective::evaluate_residuals with this minimizer.");
    auto result = m_minimizer->minimize_scalar(fcn, parameters);
    timer.stop();

    result.setDuration(timer.runTime());
    return result;
}

MinimizerResult Kernel::minimize(const fcn_residual_t fcn, const Parameters& parameters) const
{
    WallclockTimer timer;
    timer.start();
    auto result = m_minimizer->minimize_residual(fcn, parameters);
    timer.stop();

    result.setDuration(timer.runTime());
    return result;
}
