//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Tests/Functional/Fitting/SimfitTestPlan.cpp
//! @brief     Defines class SimfitTestPlan.
//!
//! @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/Fitting/SimfitTestPlan.h"
#include "Device/Data/Datafield.h"
#include "Fit/Kernel/Minimizer.h"
#include "Sample/Multilayer/Sample.h"
#include "Sim/Fitting/FitObjective.h"
#include "Sim/Fitting/SimDataPair.h"
#include "Sim/Simulation/ISimulation.h"
#include <utility>

SimfitTestPlan::SimfitTestPlan(const simulation_builder_t& sim_builder, bool residual_based,
                               const std::vector<ParameterReference>& parameter_references)
    : MinimizerTestPlan(parameter_references)
    , m_sim_builder(sim_builder)
    , m_residual_based(residual_based)
{
}

SimfitTestPlan::~SimfitTestPlan() = default;

bool SimfitTestPlan::checkMinimizer(mumufit::Minimizer& minimizer) const
{
    std::unique_ptr<FitObjective> fit_objective = createFitObjective();
    mumufit::MinimizerResult result;
    if (m_residual_based)
        result = minimizer.minimize(
            [&](const mumufit::Parameters& params) {
                return fit_objective->evaluate_residuals(params);
            },
            parameters());
    else
        result = minimizer.minimize(
            [&](const mumufit::Parameters& params) { return fit_objective->evaluate(params); },
            parameters());
    fit_objective->finalize(result);

    return valuesAsExpected(result.parameters().values());
}

std::unique_ptr<FitObjective> SimfitTestPlan::createFitObjective() const
{
    std::unique_ptr<FitObjective> result(new FitObjective);

    result->addFitPair(m_sim_builder, *fakeData(), 1.0);
    result->initPrint(1);

    return result;
}

//! Creates "experimental" data for fitting.

std::unique_ptr<Datafield> SimfitTestPlan::fakeData() const
{
    // use expected values of fit parameters to construct simulation
    auto params = parameters();
    params.setValues(expectedValues());
    auto simulation = m_sim_builder(params);
    auto result = simulation->simulate();
    return std::make_unique<Datafield>(result);
}
