From 3390f50dcf1834674a9c0c8ec9851027026bb6d8 Mon Sep 17 00:00:00 2001 From: "Alexander J. Pfleger" <70842573+AJPfleger@users.noreply.github.com> Date: Thu, 5 Dec 2024 16:02:19 +0100 Subject: [PATCH] feat: safe inverse for dynamic matrices (#3945) ## Summary by CodeRabbit - **New Features** - Enhanced the `safeInverse` function to support dynamic matrices in addition to fixed-size matrices. - **Tests** - Added a new test case for the `safeInverse` function to validate its behavior with dynamically sized identity matrices. --- Core/include/Acts/Utilities/AlgebraHelpers.hpp | 5 ++--- .../Core/Utilities/AlgebraHelpersTests.cpp | 16 +++++++++------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Core/include/Acts/Utilities/AlgebraHelpers.hpp b/Core/include/Acts/Utilities/AlgebraHelpers.hpp index 06379ec3559..aa522a7dbc2 100644 --- a/Core/include/Acts/Utilities/AlgebraHelpers.hpp +++ b/Core/include/Acts/Utilities/AlgebraHelpers.hpp @@ -178,7 +178,7 @@ inline ActsMatrix blockedMult( /// Calculate the inverse of an Eigen matrix after checking if it can be /// numerically inverted. This allows to catch potential FPEs before they occur. /// For matrices up to 4x4, the inverse is computed directly. For larger -/// matrices, the FullPivLU is used. +/// matrices, and dynamic matrices the FullPivLU is used. /// /// @tparam Derived Eigen derived concrete type /// @tparam Result Eigen result type defaulted to input type @@ -192,12 +192,11 @@ std::optional safeInverse(const MatrixType& m) noexcept { constexpr int cols = MatrixType::ColsAtCompileTime; static_assert(rows == cols); - static_assert(rows != -1); ResultType result; bool invertible = false; - if constexpr (rows > 4) { + if constexpr (rows > 4 || rows == -1) { Eigen::FullPivLU mFullPivLU(m); if (mFullPivLU.isInvertible()) { invertible = true; diff --git a/Tests/UnitTests/Core/Utilities/AlgebraHelpersTests.cpp b/Tests/UnitTests/Core/Utilities/AlgebraHelpersTests.cpp index 86165ddb2ba..87e47d3e3a9 100644 --- a/Tests/UnitTests/Core/Utilities/AlgebraHelpersTests.cpp +++ b/Tests/UnitTests/Core/Utilities/AlgebraHelpersTests.cpp @@ -51,6 +51,15 @@ BOOST_AUTO_TEST_CASE(safeInverseLargeMatrix) { BOOST_CHECK_EQUAL(*identityInv, identity); } +BOOST_AUTO_TEST_CASE(safeInverseDynamicMatrix) { + Eigen::MatrixXd identity{Eigen::MatrixXd::Identity(2, 2)}; + + auto identityInv = Acts::safeInverse(identity); + + BOOST_CHECK(identityInv); + BOOST_CHECK_EQUAL(*identityInv, identity); +} + BOOST_AUTO_TEST_CASE(SafeInverseBadSmallMatrix) { Eigen::Matrix m; m << 1, 1, 2, 2; @@ -111,13 +120,6 @@ BOOST_AUTO_TEST_CASE(SafeInverseFPELargeMatrix) { // auto mInv = Acts::safeInverse(m); // } -/// This test should not compile -// BOOST_AUTO_TEST_CASE(SafeInverseDynamicMatrix) { -// Eigen::MatrixXd m{Eigen::MatrixXd::Identity(2, 2)}; -// -// auto mInv = Acts::safeInverse(m); -// } - BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(SafeExp)