//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Base/Util/VectorUtil.cpp
//! @brief     Implements namespace VectorUtil.
//!
//! @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 "Base/Util/VectorUtil.h"
#include <cmath>
#include <stdexcept>

bool VectorUtil::is_equidistant(const std::vector<double>& vec, double tol)
{
    double span = vec.back() - vec.front();
    if (span == 0.) {
        for (std::size_t i = 1; i < vec.size() - 1; ++i)
            if (vec[i] != vec.front())
                return false;
        return true;
    }

    double step = span / vec.size();
    for (std::size_t i = 1; i < vec.size() - 1; ++i)
        if (fabs(vec[i]) - (vec.front() + i * step) > tol * step)
            return false;
    return true;
}

std::vector<double> VectorUtil::make_grid(std::size_t n, double first, double last)
{
    std::vector<double> result;
    result.reserve(n);

    if (n == 1) {
        if (first != last)
            throw std::runtime_error("Cannot make grid of size 1 unless first == last");
        result.push_back(first);
        return result;
    }

    for (std::size_t i = 0; i < n; ++i)
        result.push_back(first + i * (last - first) / (n - 1));
    return result;
}

std::vector<double> VectorUtil::real(const std::vector<complex_t>& v)
{
    std::vector<double> result(v.size());
    for (size_t i = 0; i < v.size(); i++)
        result[i] = real(v[i]);
    return result;
}
