//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Interface/CrosscorrelationModels.cpp
//! @brief     Implement CrossCorrModel classes.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2024
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Sample/Interface/CrosscorrelationModels.h"
#include "Base/Util/Assert.h"
#include <cmath>
#include <numbers>

using std::numbers::pi;

SpatialFrequencyCrosscorrelation::SpatialFrequencyCrosscorrelation(double base_crosscorr_depth,
                                                                   double base_frequency,
                                                                   double power)
    : m_base_crosscorr_depth(base_crosscorr_depth)
    , m_base_spatial_frequency(base_frequency)
    , m_power(power)
{
    SpatialFrequencyCrosscorrelation::validate();
}

double SpatialFrequencyCrosscorrelation::crosscorrSpectrum(double spectrum_up, double spectrum_low,
                                                           double thickness, double spatial_f) const
{
    ASSERT(thickness >= 0);

    if (m_base_crosscorr_depth == 0 || spectrum_up == 0 || spectrum_low == 0)
        return 0;

    const double frequency_factor = std::pow(spatial_f / m_base_spatial_frequency, m_power);
    const double base_cross_spectrum = std::sqrt(spectrum_up * spectrum_low);
    return base_cross_spectrum * std::exp(-thickness / m_base_crosscorr_depth * frequency_factor);
}

SpatialFrequencyCrosscorrelation* SpatialFrequencyCrosscorrelation::clone() const
{
    return new SpatialFrequencyCrosscorrelation(m_base_crosscorr_depth, m_base_spatial_frequency,
                                                m_power);
}

void SpatialFrequencyCrosscorrelation::validate() const
{
    if (m_base_crosscorr_depth < 0)
        throw std::runtime_error("base_crosscorr_depth < 0");
    if (m_base_spatial_frequency < 0)
        throw std::runtime_error("base_spatial_frequency < 0");
    if (m_power < 0)
        throw std::runtime_error("power < 0");

    m_validated = true;
}

//-------------------------------------------------------------------------------------------------

CommonDepthCrosscorrelation::CommonDepthCrosscorrelation(double cross_corr_depth)
    : SpatialFrequencyCrosscorrelation(cross_corr_depth, 1, 0)
{
}

CommonDepthCrosscorrelation* CommonDepthCrosscorrelation::clone() const
{
    return new CommonDepthCrosscorrelation(m_base_crosscorr_depth);
}
