//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Sample/Interface/RoughnessMap.h
//! @brief     Define RoughnessMap class.
//!
//! @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)
//
//  ************************************************************************************************

#ifndef BORNAGAIN_SAMPLE_MULTILAYER_ROUGHNESSMAP_H
#define BORNAGAIN_SAMPLE_MULTILAYER_ROUGHNESSMAP_H

#include "Base/Math/FourierTransform.h"
#include "Sample/Multilayer/Sample.h"
#include <random>

#ifdef BORNAGAIN_PYTHON
#include "Base/Py/ArrayWrapper.h" // Arrayf64Wrapper
#endif                            // BORNAGAIN_PYTHON

//! Generation of random rough surface with given both spectrum and height statistics.
//!
//! Algorithm by Pérez-Ràfols & Almqvist, Tribology International 131, 591-604 (2019)
//! https://doi.org/10.1016/j.triboint.2018.11.020

class RoughnessMap {
public:
    RoughnessMap(size_t x_points, size_t y_points, double Lx, double Ly, const Sample& sample,
                 int i_layer, int seed = -1);
    RoughnessMap() = delete;

    double2d_t generateMap();

#ifdef BORNAGAIN_PYTHON
    //! Returns data to construct a Python Numpy array.
    Arrayf64Wrapper generate();
#endif // BORNAGAIN_PYTHON

private:
    // create random uncorrelated map with given height statistics
    double2d_t mapFromHeights() const;

    // create random map with gives autocorrelation spectrum
    double2d_t mapFromSpectrum() const;

    double2d_t applySpectrumToHeights(const double2d_t& h_map, const double2d_t& s_map) const;
    double2d_t applyHeightsToSpectrum(const double2d_t& h_map, const double2d_t& s_map) const;

    // create random map with both spectrum and height distribution
    void createMap();

    int m_x_points = 0;
    int m_y_points = 0;
    double m_lx; //!< sample x size in nm
    double m_ly; //!< sample y size in nm

    const Sample& m_sample;

    int m_i_layer;
    double2d_t m_rough_map;

    mutable FourierTransform m_ft;
    std::random_device m_rd;
    mutable std::mt19937 m_gen;
};

#endif // BORNAGAIN_SAMPLE_MULTILAYER_ROUGHNESSMAP_H
