//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Device/Data/ArrayUtil.cpp
//! @brief     Implements internal functions
//!
//! @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 "Device/Data/ArrayUtil.h"
#include "Base/Axis/MakeScale.h"
#include "Base/Axis/Scale.h"
#include "Base/Util/Assert.h"
#include "Device/Data/Datafield.h"
#include <stdexcept>

std::pair<size_t, size_t> DataUtil::Array::getShape(const std::vector<std::vector<double>>& data)
{
    size_t nrows = data.size();
    size_t ncols(0);
    if (nrows)
        ncols = data[0].size();
    for (size_t row = 0; row < nrows; row++)
        ASSERT(data[row].size() == ncols);
    return std::make_pair(nrows, ncols);
}

std::unique_ptr<Datafield> DataUtil::Array::createPField1D(const std::vector<double>& vec)
{
    const size_t N = vec.size();
    std::vector<const Scale*> axes{newEquiDivision("axis0", N, 0.0, (double)N)};
    return std::make_unique<Datafield>(std::move(axes), vec);
}

std::unique_ptr<Datafield>
DataUtil::Array::createPField2D(const std::vector<std::vector<double>>& vec)
{
    auto shape = DataUtil::Array::getShape(vec);
    const size_t nrows = shape.first;
    const size_t ncols = shape.second;

    ASSERT(nrows > 0);
    ASSERT(ncols > 0);

    std::vector<const Scale*> axes{newEquiDivision("axis0", ncols, 0.0, (double)ncols),
                                   newEquiDivision("axis1", nrows, 0.0, (double)nrows)};

    std::vector<double> out(nrows * ncols);
    for (size_t row = 0; row < nrows; ++row) {
        for (size_t col = 0; col < ncols; ++col) {
            size_t iout = nrows - row - 1 + col * nrows;
            out[iout] = vec[row][col];
        }
    }

    return std::make_unique<Datafield>(std::move(axes), out);
}

std::vector<double> DataUtil::Array::createVector1D(const Datafield& data)
{
    ASSERT(data.rank() == 1);
    std::vector<double> result = data.flatVector();
    return result;
}

std::vector<std::vector<double>> DataUtil::Array::createVector2D(const Datafield& data)
{
    std::vector<std::vector<double>> result;

    const size_t nrows = data.axis(1).size();
    const size_t ncols = data.axis(0).size();

    result.resize(nrows);

    for (size_t row = 0; row < nrows; ++row) {
        result[row].resize(ncols, 0.0);
        for (size_t col = 0; col < ncols; ++col) {
            size_t globalbin = nrows - row - 1 + col * nrows;
            result[row][col] = data[globalbin];
        }
    }

    return result;
}
