//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Tests/Suite/Persist/Check.cpp
//! @brief     Implements function checkSimulation for core standard test.
//!
//! @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 "BABuild.h"
#include "BATesting.h"
#include "Base/Util/Assert.h"
#include "Base/Util/PathUtil.h"
#include "Device/Data/Datafield.h"
#include "Device/IO/DiffUtil.h"
#include "Device/IO/IOFactory.h"
#include "Sim/Simulation/ISimulation.h"
#include <iostream>

//! Run simulation directly (in C++ core), and compare result with reference data.

bool checkSimulation(const std::string& name, ISimulation& direct_simulation, double precision,
                     double snr, int allowed_outliers)
{
    // Run simulation directly.
    const Datafield result_data = direct_simulation.simulate();

    ASSERT(!name.empty());
    try {
        const std::string refPath =
            Base::Path::jointPath(BATesting::ReferenceDir_Suite, name + ".int");
        std::cout << "- reference: " << refPath << "\n";
        Datafield reference = IO::readData2D(refPath, IO::Filetype2D::bornagain2D);
        std::cout << "- check diff" << std::endl;
        if (DiffUtil::checkConsistence(result_data, reference, precision, snr, allowed_outliers))
            return true; // regular exit
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << std::endl;
    }

    // Save simulation, as it differs from reference.
    Base::Path::createDirectories(BATesting::TestOutDir_Suite);
    std::string out_fname = Base::Path::jointPath(BATesting::TestOutDir_Suite, name + ".int");
    IO::writeDatafield(result_data, out_fname);
    std::cout << "Notes:\n- to visualize an intensity map, use " << BABuild::srcDir()
              << "/devtools/view/plot-int.py\n"
              << "- to plot a difference image, use " << BABuild::srcDir()
              << "/devtools/view/plot-diff.py\n"
              << "- if the new simulation result is correct, then\n"
              << "  cp -f  " << out_fname << " " << BATesting::ReferenceDir_Suite << "/\n\n";

    return false;
}
