rotgen/test/unit/free_functions/norms.cpp
2025-07-20 20:23:51 +02:00

60 lines
No EOL
2.4 KiB
C++

//==================================================================================================
/*
ROTGEN - Runtime Overlay for Eigen
Copyright : CODE RECKONS
SPDX-License-Identifier: BSL-1.0
*/
//==================================================================================================
#include "unit/tests.hpp"
#include <rotgen/rotgen.hpp>
#include <Eigen/Dense>
template <typename MatrixType>
struct MatrixDescriptor
{
std::size_t rows, cols;
std::function<void(MatrixType &, std::size_t, std::size_t)> init_fn;
};
template <typename MatrixType>
void test_matrix_norms(std::size_t rows, std::size_t cols,
const std::function<void(MatrixType &, std::size_t, std::size_t)> &init_fn)
{
MatrixType matrix(rows, cols);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> ref(rows, cols);
for (std::size_t r = 0; r < rows; ++r)
for (std::size_t c = 0; c < cols; ++c)
{
init_fn(matrix, r, c);
ref(r, c) = matrix(r, c);
}
constexpr double epsilon = 1e-10;
TTS_RELATIVE_EQUAL(rotgen::norm(matrix), ref.norm(), epsilon);
TTS_RELATIVE_EQUAL(rotgen::squaredNorm(matrix), ref.squaredNorm(), epsilon);
TTS_RELATIVE_EQUAL(rotgen::lpNorm<1>(matrix), ref.lpNorm<1>(), epsilon);
TTS_RELATIVE_EQUAL(rotgen::lpNorm<2>(matrix), ref.lpNorm<2>(), epsilon);
TTS_RELATIVE_EQUAL(rotgen::lpNorm<-1>(matrix), ref.lpNorm<Eigen::Infinity>(), epsilon);
}
TTS_CASE("Matrix norm-related operations")
{
std::vector<MatrixDescriptor<rotgen::matrix<double>>> test_matrices = {
{3, 3, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = r + c; }},
{2, 3, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = 0.0; }},
{2, 7, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = -r*r*r - c*c - 1.23; }},
{17, 3, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = r*c + 0.98; }},
{1, 1, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = 42.0; }},
{10, 11, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = std::tan(r + c); }},
{1, 5, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = -1.5*r + 2.56*c + 3.33; }},
{7, 1, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = (r == c ? 1.0 : 0.0); }},
{0, 0, [](auto& m, std::size_t r, std::size_t c) { m(r, c) = (r == c ? 1.0 : 0.0); }},
};
for (const auto& [rows, cols, init_fn] : test_matrices)
test_matrix_norms<rotgen::matrix<double>>(rows, cols, init_fn);
};