//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Tests/Functional/Mumufit/ResidualTestPlan.cpp
//! @brief     Implements class ResidualTestPlan.
//!
//! @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 "Tests/Functional/Mumufit/ResidualTestPlan.h"
#include "Fit/Kernel/Minimizer.h"
#include <cassert>
#include <iostream>
#include <utility>

using namespace mumufit;

ResidualTestPlan::ResidualTestPlan(const std::string&, test_funct_t func)
    : m_test_func(std::move(func))
{
    m_xvalues.resize(101);
    for (int i = 0; i <= 100; ++i)
        m_xvalues[i] = i * 0.1;
}

fcn_residual_t ResidualTestPlan::residualFunction() const
{
    return [&](mumufit::Parameters pars) -> std::vector<double> { return evaluate(pars.values()); };
}

bool ResidualTestPlan::checkMinimizer(Minimizer& minimizer) const
{
    auto result = minimizer.minimize(residualFunction(), parameters());
    std::cout << result.toString() << std::endl;
    return valuesAsExpected(result.parameters().values());
}

void ResidualTestPlan::finalizeParameters()
{
    std::vector<double> pars;
    pars.reserve(m_parameter_references.size());
    for (const auto& plan : m_parameter_references)
        pars.push_back(plan.expected_value);

    for (auto x : m_xvalues)
        m_data_values.push_back(m_test_func(x, pars));
}

std::vector<double> ResidualTestPlan::evaluate(const std::vector<double>& pars) const
{
    assert(!m_data_values.empty());

    std::vector<double> result;
    for (size_t i = 0; i < m_xvalues.size(); ++i)
        result.push_back(m_test_func(m_xvalues[i], pars) - m_data_values[i]);
    return result;
}
