diff --git a/Sofa/Component/LinearSolver/Direct/tests/CMakeLists.txt b/Sofa/Component/LinearSolver/Direct/tests/CMakeLists.txt
index 2e2a3dd76bd..ab00724d66d 100644
--- a/Sofa/Component/LinearSolver/Direct/tests/CMakeLists.txt
+++ b/Sofa/Component/LinearSolver/Direct/tests/CMakeLists.txt
@@ -3,6 +3,7 @@ cmake_minimum_required(VERSION 3.22)
project(Sofa.Component.LinearSolver.Direct_test)
set(SOURCE_FILES
+ ComplianceMatrix_test.cpp
EigenDirectSparseSolver_test.cpp
SparseLDLSolver_test.cpp
)
@@ -11,4 +12,5 @@ add_executable(${PROJECT_NAME} ${SOURCE_FILES})
# dependencies are managed directly in the target_link_libraries pass
target_link_libraries(${PROJECT_NAME} Sofa.Testing
Sofa.Component.LinearSolver.Direct
+ Sofa.Component.StateContainer
)
diff --git a/Sofa/Component/LinearSolver/Direct/tests/ComplianceMatrix_test.cpp b/Sofa/Component/LinearSolver/Direct/tests/ComplianceMatrix_test.cpp
new file mode 100644
index 00000000000..66695646df0
--- /dev/null
+++ b/Sofa/Component/LinearSolver/Direct/tests/ComplianceMatrix_test.cpp
@@ -0,0 +1,494 @@
+/******************************************************************************
+* SOFA, Simulation Open-Framework Architecture *
+* (c) 2006 INRIA, USTL, UJF, CNRS, MGH *
+* *
+* This program is free software; you can redistribute it and/or modify it *
+* under the terms of the GNU Lesser General Public License as published by *
+* the Free Software Foundation; either version 2.1 of the License, or (at *
+* your option) any later version. *
+* *
+* This program is distributed in the hope that it will be useful, but WITHOUT *
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
+* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
+* for more details. *
+* *
+* You should have received a copy of the GNU Lesser General Public License *
+* along with this program. If not, see . *
+*******************************************************************************
+* Authors: The SOFA Team and external contributors (see Authors.txt) *
+* *
+* Contact information: contact@sofa-framework.org *
+******************************************************************************/
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+/**
+ * Checks the product J * A^{-1} * J^T (buildComplianceMatrix, addJMInvJt) computed
+ * by the direct linear solvers, against a dense reference.
+ *
+ * The test problem is shared by all the solvers:
+ * - A is a 9x9 SPD matrix. Its 9 DOFs are split over two MechanicalObject ranges:
+ * a Vec3 object with 2 nodes (columns 0-5), and a Vec1 object with 3 nodes
+ * (columns 6-8). A couples the two ranges.
+ * - J has 5 rows. Some rows touch a single object, others both. Row 2 is empty:
+ * it must remain empty in the result, and must not be regularized.
+ *
+ * J is always written through the BaseMatrix interface, so that the tests do not
+ * depend on the concrete type of the constraint matrix used by the solvers.
+ */
+namespace
+{
+
+using namespace sofa;
+
+using MatrixType = linearalgebra::CompressedRowSparseMatrix;
+using VectorType = linearalgebra::FullVector;
+using LinearSystem = component::linearsystem::MatrixLinearSystem;
+using NaturalOrdering = component::linearsolver::ordering::NaturalOrderingMethod;
+using MechanicalObject3 = component::statecontainer::MechanicalObject;
+using MechanicalObject1 = component::statecontainer::MechanicalObject;
+using DenseMatrix = Eigen::Matrix;
+
+/// Description of the problem shared by all the tests
+struct Problem
+{
+ static constexpr sofa::Size nbNodes3 = 2; ///< number of nodes in the Vec3 object
+ static constexpr sofa::Size nbNodes1 = 3; ///< number of nodes in the Vec1 object
+ static constexpr sofa::Size offset1 = 3 * nbNodes3; ///< first column of the Vec1 object
+ static constexpr sofa::Size n = offset1 + nbNodes1;
+ static constexpr sofa::Size m = 5;
+ static constexpr sofa::Index emptyRow = 2;
+
+ struct Entry3 { sofa::Index row; sofa::Index node; type::Vec3 value; };
+ struct Entry1 { sofa::Index row; sofa::Index node; SReal value; };
+
+ /// Constraint entries on the Vec3 object. Only non-zero components are
+ /// meaningful, but MechanicalObject writes the full Deriv.
+ static inline const std::vector entries3 {
+ {0, 0, {1.0, 0.5, 0.0}},
+ {3, 1, {0.0, -1.0, 0.25}},
+ {4, 0, {0.0, 0.0, 1.0}},
+ };
+
+ /// Constraint entries on the Vec1 object
+ static inline const std::vector entries1 {
+ {1, 2, 2.0},
+ {3, 0, 1.5},
+ {4, 1, -0.5},
+ };
+
+ static DenseMatrix denseA()
+ {
+ DenseMatrix A = DenseMatrix::Zero(n, n);
+ for (sofa::Index i = 0; i < n; ++i)
+ {
+ A(i, i) = 4.0 + 0.1 * i;
+ if (i > 0)
+ {
+ A(i, i - 1) = A(i - 1, i) = -1.0;
+ }
+ }
+ // coupling between the two object ranges
+ A(1, 7) = A(7, 1) = 0.3;
+ A(4, 8) = A(8, 4) = -0.2;
+ return A;
+ }
+
+ static DenseMatrix denseJ()
+ {
+ DenseMatrix J = DenseMatrix::Zero(m, n);
+ for (const auto& [row, node, value] : entries3)
+ {
+ for (sofa::Index k = 0; k < 3; ++k)
+ {
+ J(row, 3 * node + k) += value[k];
+ }
+ }
+ for (const auto& [row, node, value] : entries1)
+ {
+ J(row, offset1 + node) += value;
+ }
+ return J;
+ }
+
+ /// Write the non-zero values of the dense J into any matrix, through the
+ /// BaseMatrix interface only
+ static void writeJ(linearalgebra::BaseMatrix& J)
+ {
+ const DenseMatrix Jd = denseJ();
+ J.resize(m, n);
+ for (sofa::Index i = 0; i < m; ++i)
+ {
+ for (sofa::Index j = 0; j < n; ++j)
+ {
+ if (Jd(i, j) != 0)
+ {
+ J.add(i, j, Jd(i, j));
+ }
+ }
+ }
+ J.compress();
+ }
+};
+
+constexpr SReal fact = 0.75;
+constexpr SReal tolerance = 1e-10;
+
+void initTaskScheduler()
+{
+ auto* taskScheduler = simulation::MainTaskSchedulerFactory::createInRegistry();
+ ASSERT_NE(taskScheduler, nullptr);
+ if (taskScheduler->getThreadCount() < 1)
+ {
+ taskScheduler->init(std::max(2u, simulation::TaskScheduler::GetHardwareThreadsCount()));
+ }
+}
+
+/// Solver traits ////////////////////////////////////////////////////////////
+
+template
+struct SolverTraits
+{
+ using Solver = TSolver;
+ static constexpr bool parallel = TParallel;
+ static void registerFactories() {}
+};
+
+using SparseLDL = component::linearsolver::direct::SparseLDLSolver;
+using AsyncSparseLDL = component::linearsolver::direct::AsyncSparseLDLSolver;
+/// A CRS-based direct solver which does not override addJMInvJtLocal: it uses
+/// the generic implementation of MatrixLinearSolver
+using EigenLDLT = component::linearsolver::direct::EigenSimplicialLDLT;
+
+template
+struct EigenLDLTTraits : SolverTraits
+{
+ static void registerFactories()
+ {
+ // the factories are populated when the module is initialized, which does not
+ // happen here since the test links the library directly
+ component::linearsolver::direct::MainSimplicialLDLTFactory::registerSolver<
+ Eigen::NaturalOrdering, SReal>("Natural");
+ }
+};
+
+struct SparseLDLSequentialTraits : SolverTraits {};
+struct SparseLDLParallelTraits : SolverTraits {};
+struct AsyncSparseLDLTraits : SolverTraits {};
+struct EigenLDLTSequentialTraits : EigenLDLTTraits {};
+struct EigenLDLTParallelTraits : EigenLDLTTraits {};
+
+/// Fixture //////////////////////////////////////////////////////////////////
+
+template
+class ComplianceMatrix_test : public sofa::testing::BaseTest
+{
+public:
+ using Solver = typename Traits::Solver;
+
+ simulation::Node::SPtr root;
+ typename LinearSystem::SPtr linearSystem;
+ typename Solver::SPtr solver;
+ MechanicalObject3::SPtr mstate3;
+ MechanicalObject1::SPtr mstate1;
+
+ DenseMatrix Adense;
+ DenseMatrix Jdense;
+
+ void doSetUp() override
+ {
+ Traits::registerFactories();
+ if constexpr (Traits::parallel)
+ {
+ initTaskScheduler();
+ }
+
+ Adense = Problem::denseA();
+ Jdense = Problem::denseJ();
+
+ root = simulation::MainSimulation::getSimulation()->createNewGraph("root");
+ root->addObject(core::objectmodel::New());
+
+ const auto ordering = core::objectmodel::New();
+ root->addObject(ordering);
+
+ linearSystem = core::objectmodel::New();
+ root->addObject(linearSystem);
+
+ solver = core::objectmodel::New();
+ solver->l_orderingMethod.set(ordering.get());
+ solver->l_linearSystem.set(linearSystem.get());
+ solver->d_parallelInverseProduct.setValue(Traits::parallel);
+ root->addObject(solver);
+
+ // Two mechanical states, in two child nodes (one state per node). The
+ // constraint Jacobian visitor visits them in this order, so the Vec3
+ // object owns the columns [0, 6) and the Vec1 object the columns [6, 9).
+ const auto node3 = root->createChild("vec3");
+ mstate3 = core::objectmodel::New();
+ node3->addObject(mstate3);
+
+ const auto node1 = root->createChild("vec1");
+ mstate1 = core::objectmodel::New();
+ node1->addObject(mstate1);
+
+ simulation::node::initRoot(root.get());
+ ASSERT_TRUE(solver->isComponentStateValid());
+
+ mstate3->resize(Problem::nbNodes3);
+ mstate1->resize(Problem::nbNodes1);
+
+ writeConstraintJacobian();
+ assembleAndFactorize();
+ }
+
+ void doTearDown() override
+ {
+ if (root)
+ {
+ simulation::node::unload(root);
+ }
+ }
+
+ /// Fill the constraint Jacobians of both mechanical states
+ void writeConstraintJacobian()
+ {
+ {
+ auto c = helper::getWriteOnlyAccessor(*mstate3->write(core::vec_id::write_access::constraintJacobian));
+ c->clear();
+ for (const auto& [row, node, value] : Problem::entries3)
+ {
+ c->writeLine(row).addCol(node, value);
+ }
+ }
+ {
+ auto c = helper::getWriteOnlyAccessor(*mstate1->write(core::vec_id::write_access::constraintJacobian));
+ c->clear();
+ for (const auto& [row, node, value] : Problem::entries1)
+ {
+ c->writeLine(row).addCol(node, defaulttype::Vec1Types::Deriv(value));
+ }
+ }
+ }
+
+ /// Write A into the linear system, and factorize it
+ void assembleAndFactorize()
+ {
+ linearSystem->resizeSystem(Problem::n); // also invalidates the factorization
+ MatrixType* A = linearSystem->getSystemMatrix();
+ ASSERT_NE(A, nullptr);
+ for (sofa::Index i = 0; i < Problem::n; ++i)
+ {
+ for (sofa::Index j = 0; j < Problem::n; ++j)
+ {
+ if (Adense(i, j) != 0)
+ {
+ A->add(i, j, Adense(i, j));
+ }
+ }
+ }
+ A->compress();
+
+ // solveSystem goes through the factorization in all the solvers, including
+ // the asynchronous one (for which invertSystem would not make the
+ // factorization available to the main thread)
+ linearSystem->getRHSVector()->clear();
+ solver->solveSystem();
+ }
+
+ /// W = fact * J * A^{-1} * J^T
+ DenseMatrix expectedCompliance() const
+ {
+ return fact * Jdense * Adense.inverse() * Jdense.transpose();
+ }
+
+ static void expectNear(const linearalgebra::BaseMatrix& actual, const DenseMatrix& expected, const std::string& what)
+ {
+ ASSERT_EQ(actual.rowSize(), static_cast(expected.rows()));
+ ASSERT_EQ(actual.colSize(), static_cast(expected.cols()));
+ for (Eigen::Index i = 0; i < expected.rows(); ++i)
+ {
+ for (Eigen::Index j = 0; j < expected.cols(); ++j)
+ {
+ EXPECT_NEAR(actual.element(i, j), expected(i, j), tolerance)
+ << what << " mismatch at (" << i << "," << j << ")";
+ }
+ }
+ }
+};
+
+using SolverTypes = ::testing::Types<
+ SparseLDLSequentialTraits,
+ SparseLDLParallelTraits,
+ AsyncSparseLDLTraits,
+ EigenLDLTSequentialTraits,
+ EigenLDLTParallelTraits
+>;
+
+class SolverTypeNames
+{
+public:
+ template
+ static std::string GetName(int)
+ {
+ if constexpr (std::is_same_v) return "SparseLDL";
+ if constexpr (std::is_same_v) return "SparseLDLParallel";
+ if constexpr (std::is_same_v) return "AsyncSparseLDL";
+ if constexpr (std::is_same_v) return "GenericEigenLDLT";
+ if constexpr (std::is_same_v) return "GenericEigenLDLTParallel";
+ return "Unknown";
+ }
+};
+
+TYPED_TEST_SUITE(ComplianceMatrix_test, SolverTypes, SolverTypeNames);
+
+/// The reference itself: row 2 of J is empty
+TYPED_TEST(ComplianceMatrix_test, problemHasAnEmptyRow)
+{
+ EXPECT_EQ(this->Jdense.row(Problem::emptyRow).norm(), 0);
+ for (sofa::Index i = 0; i < Problem::m; ++i)
+ {
+ if (i != Problem::emptyRow)
+ {
+ EXPECT_GT(this->Jdense.row(i).norm(), 0) << "row " << i;
+ }
+ }
+}
+
+/// addJMInvJt with a J provided by the caller
+TYPED_TEST(ComplianceMatrix_test, addJMInvJt)
+{
+ typename TestFixture::Solver::JMatrixType J;
+ Problem::writeJ(J);
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(this->solver->addJMInvJt(&W, &J, fact));
+
+ this->expectNear(W, this->expectedCompliance(), "J*A^-1*J^T");
+}
+
+/// addJMInvJt adds to the result: it does not overwrite it
+TYPED_TEST(ComplianceMatrix_test, addJMInvJtAccumulates)
+{
+ typename TestFixture::Solver::JMatrixType J;
+ Problem::writeJ(J);
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+ DenseMatrix initial = DenseMatrix::Zero(Problem::m, Problem::m);
+ for (sofa::Index i = 0; i < Problem::m; ++i)
+ {
+ for (sofa::Index j = 0; j < Problem::m; ++j)
+ {
+ initial(i, j) = 0.01 * (1 + i + 2 * j);
+ W.set(i, j, initial(i, j));
+ }
+ }
+
+ ASSERT_TRUE(this->solver->addJMInvJt(&W, &J, fact));
+
+ this->expectNear(W, initial + this->expectedCompliance(), "W0 + J*A^-1*J^T");
+}
+
+/// J of another type than the solver's: the solver must convert it
+TYPED_TEST(ComplianceMatrix_test, addJMInvJtFromFullMatrix)
+{
+ linearalgebra::FullMatrix J;
+ Problem::writeJ(J);
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(this->solver->addJMInvJt(&W, &J, fact));
+
+ this->expectNear(W, this->expectedCompliance(), "J*A^-1*J^T");
+}
+
+/// J is built from the constraint Jacobians stored in the mechanical states
+TYPED_TEST(ComplianceMatrix_test, buildComplianceMatrix)
+{
+ const core::ConstraintParams cparams;
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(this->solver->buildComplianceMatrix(&cparams, &W, fact, 0));
+
+ this->expectNear(W, this->expectedCompliance(), "J*A^-1*J^T");
+}
+
+/// The regularization term is added on the diagonal of the non-empty rows only
+TYPED_TEST(ComplianceMatrix_test, buildComplianceMatrixRegularization)
+{
+ const core::ConstraintParams cparams;
+ constexpr SReal regularization = 0.125;
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(this->solver->buildComplianceMatrix(&cparams, &W, fact, regularization));
+
+ DenseMatrix expected = this->expectedCompliance();
+ for (sofa::Index i = 0; i < Problem::m; ++i)
+ {
+ if (i != Problem::emptyRow)
+ {
+ expected(i, i) += regularization;
+ }
+ }
+ this->expectNear(W, expected, "J*A^-1*J^T + reg*I");
+
+ EXPECT_EQ(W.element(Problem::emptyRow, Problem::emptyRow), 0)
+ << "the empty constraint row must not be regularized";
+}
+
+/// buildComplianceMatrix after the constraint Jacobian changed: the solver must
+/// not reuse the previous J
+TYPED_TEST(ComplianceMatrix_test, buildComplianceMatrixTwice)
+{
+ const core::ConstraintParams cparams;
+
+ {
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+ ASSERT_TRUE(this->solver->buildComplianceMatrix(&cparams, &W, fact, 0));
+ }
+
+ // keep only the constraints on the Vec1 object
+ {
+ auto c = helper::getWriteOnlyAccessor(*this->mstate3->write(core::vec_id::write_access::constraintJacobian));
+ c->clear();
+ }
+ this->Jdense.leftCols(Problem::offset1).setZero();
+
+ linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+ ASSERT_TRUE(this->solver->buildComplianceMatrix(&cparams, &W, fact, 0));
+
+ this->expectNear(W, this->expectedCompliance(), "J*A^-1*J^T");
+}
+
+} // namespace
diff --git a/applications/plugins/SofaCHOLMOD/tests/CMakeLists.txt b/applications/plugins/SofaCHOLMOD/tests/CMakeLists.txt
index e25025a8d8e..b021d5a445e 100644
--- a/applications/plugins/SofaCHOLMOD/tests/CMakeLists.txt
+++ b/applications/plugins/SofaCHOLMOD/tests/CMakeLists.txt
@@ -11,5 +11,6 @@ target_link_libraries(${PROJECT_NAME}
Sofa.Testing
SofaCHOLMOD
Sofa.Component.LinearSolver.Ordering
+ Sofa.Component.StateContainer
Eigen3::Eigen
)
diff --git a/applications/plugins/SofaCHOLMOD/tests/EigenCholmodSupernodalLLT_test.cpp b/applications/plugins/SofaCHOLMOD/tests/EigenCholmodSupernodalLLT_test.cpp
index 4fc1fd710c2..52ab3cbcc62 100644
--- a/applications/plugins/SofaCHOLMOD/tests/EigenCholmodSupernodalLLT_test.cpp
+++ b/applications/plugins/SofaCHOLMOD/tests/EigenCholmodSupernodalLLT_test.cpp
@@ -25,6 +25,14 @@
#include
#include
#include
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
#include
#include
@@ -180,15 +188,18 @@ TEST(EigenCholmodSupernodalLLT, AddJMInvJtMatchesDenseReference)
// by init(); addJMInvJtLocal early-returns unless the component is valid.
solver->d_componentState.setValue(sofa::core::objectmodel::ComponentState::Valid);
- // Constraint Jacobian J (m x n), sparse.
+ // Constraint Jacobian J (m x n), sparse. It is written through the BaseMatrix
+ // interface only, so that the test does not depend on the concrete JMatrixType.
constexpr int m = 3;
Solver::JMatrixType J;
- J.resize(m, n);
+ sofa::linearalgebra::BaseMatrix& Jbase = J;
+ Jbase.resize(m, n);
Eigen::MatrixXd Jdense = Eigen::MatrixXd::Zero(m, n);
- const auto setJ = [&](int i, int j, double v) { J.set(i, j, v); Jdense(i, j) = v; };
+ const auto setJ = [&](int i, int j, double v) { Jbase.add(i, j, v); Jdense(i, j) += v; };
setJ(0, 0, 1.0); setJ(0, 2, -0.5);
setJ(1, 1, 2.0); setJ(1, 4, 1.0);
setJ(2, 3, 1.0); setJ(2, 5, -1.0);
+ Jbase.compress();
const SReal fact = 0.75;
@@ -210,4 +221,302 @@ TEST(EigenCholmodSupernodalLLT, AddJMInvJtMatchesDenseReference)
}
}
+namespace
+{
+using DenseMatrix = Eigen::MatrixXd;
+using MatrixType = sofa::linearalgebra::CompressedRowSparseMatrix;
+using VectorType = sofa::linearalgebra::FullVector;
+using LinearSystem = sofa::component::linearsystem::MatrixLinearSystem;
+using MechanicalObject3 = sofa::component::statecontainer::MechanicalObject;
+using MechanicalObject1 = sofa::component::statecontainer::MechanicalObject;
+
+/**
+ * A 9x9 SPD system whose DOFs are split over two MechanicalObject ranges: a Vec3
+ * object with 2 nodes (columns 0-5) and a Vec1 object with 3 nodes (columns 6-8).
+ * J has 5 rows, some on one object, some on both. Row 2 is empty.
+ */
+struct Problem
+{
+ static constexpr sofa::Size nbNodes3 = 2;
+ static constexpr sofa::Size nbNodes1 = 3;
+ static constexpr sofa::Size offset1 = 3 * nbNodes3;
+ static constexpr sofa::Size n = offset1 + nbNodes1;
+ static constexpr sofa::Size m = 5;
+ static constexpr sofa::Index emptyRow = 2;
+
+ struct Entry3 { sofa::Index row; sofa::Index node; sofa::type::Vec3 value; };
+ struct Entry1 { sofa::Index row; sofa::Index node; SReal value; };
+
+ static inline const std::vector entries3 {
+ {0, 0, {1.0, 0.5, 0.0}},
+ {3, 1, {0.0, -1.0, 0.25}},
+ {4, 0, {0.0, 0.0, 1.0}},
+ };
+ static inline const std::vector entries1 {
+ {1, 2, 2.0},
+ {3, 0, 1.5},
+ {4, 1, -0.5},
+ };
+
+ static DenseMatrix denseA()
+ {
+ DenseMatrix A = DenseMatrix::Zero(n, n);
+ for (sofa::Index i = 0; i < n; ++i)
+ {
+ A(i, i) = 4.0 + 0.1 * i;
+ if (i > 0)
+ {
+ A(i, i - 1) = A(i - 1, i) = -1.0;
+ }
+ }
+ A(1, 7) = A(7, 1) = 0.3;
+ A(4, 8) = A(8, 4) = -0.2;
+ return A;
+ }
+
+ static DenseMatrix denseJ()
+ {
+ DenseMatrix J = DenseMatrix::Zero(m, n);
+ for (const auto& [row, node, value] : entries3)
+ {
+ for (sofa::Index k = 0; k < 3; ++k)
+ {
+ J(row, 3 * node + k) += value[k];
+ }
+ }
+ for (const auto& [row, node, value] : entries1)
+ {
+ J(row, offset1 + node) += value;
+ }
+ return J;
+ }
+
+ /// Write the non-zero values of J through the BaseMatrix interface only
+ static void writeJ(sofa::linearalgebra::BaseMatrix& J)
+ {
+ const DenseMatrix Jd = denseJ();
+ J.resize(m, n);
+ for (sofa::Index i = 0; i < m; ++i)
+ {
+ for (sofa::Index j = 0; j < n; ++j)
+ {
+ if (Jd(i, j) != 0)
+ {
+ J.add(i, j, Jd(i, j));
+ }
+ }
+ }
+ J.compress();
+ }
+};
+
+constexpr SReal fact = 0.75;
+constexpr SReal tolerance = 1e-10;
+
+void expectNear(const sofa::linearalgebra::BaseMatrix& actual, const DenseMatrix& expected, const std::string& what)
+{
+ ASSERT_EQ(actual.rowSize(), static_cast(expected.rows()));
+ ASSERT_EQ(actual.colSize(), static_cast(expected.cols()));
+ for (Eigen::Index i = 0; i < expected.rows(); ++i)
+ {
+ for (Eigen::Index j = 0; j < expected.cols(); ++j)
+ {
+ EXPECT_NEAR(actual.element(i, j), expected(i, j), tolerance)
+ << what << " mismatch at (" << i << "," << j << ")";
+ }
+ }
+}
+}
+
+/// Same checks as in the tests of the direct solvers (Sofa.Component.LinearSolver.Direct):
+/// the solver is placed in a scene with its linear system and two mechanical states,
+/// so that the public API (addJMInvJt, buildComplianceMatrix) is tested.
+class EigenCholmodSupernodalLLTScene : public sofa::testing::BaseTest
+{
+public:
+ using Solver = EigenCholmodSupernodalLLT;
+
+ sofa::simulation::Node::SPtr root;
+ LinearSystem::SPtr linearSystem;
+ Solver::SPtr solver;
+ MechanicalObject3::SPtr mstate3;
+ MechanicalObject1::SPtr mstate1;
+
+ DenseMatrix Adense;
+ DenseMatrix Jdense;
+
+ void doSetUp() override
+ {
+ sofacholmod::init();
+
+ Adense = Problem::denseA();
+ Jdense = Problem::denseJ();
+
+ root = sofa::simulation::MainSimulation::getSimulation()->createNewGraph("root");
+ root->addObject(New());
+
+ const auto ordering = New();
+ root->addObject(ordering);
+
+ linearSystem = New();
+ root->addObject(linearSystem);
+
+ solver = New();
+ solver->l_orderingMethod.set(ordering.get());
+ solver->l_linearSystem.set(linearSystem.get());
+ root->addObject(solver);
+
+ // the constraint Jacobian visitor visits the states in this order: the Vec3
+ // object owns the columns [0, 6), the Vec1 object the columns [6, 9)
+ const auto node3 = root->createChild("vec3");
+ mstate3 = New();
+ node3->addObject(mstate3);
+
+ const auto node1 = root->createChild("vec1");
+ mstate1 = New();
+ node1->addObject(mstate1);
+
+ sofa::simulation::node::initRoot(root.get());
+ ASSERT_TRUE(solver->isComponentStateValid());
+
+ mstate3->resize(Problem::nbNodes3);
+ mstate1->resize(Problem::nbNodes1);
+
+ {
+ auto c = sofa::helper::getWriteOnlyAccessor(*mstate3->write(sofa::core::vec_id::write_access::constraintJacobian));
+ c->clear();
+ for (const auto& [row, node, value] : Problem::entries3)
+ {
+ c->writeLine(row).addCol(node, value);
+ }
+ }
+ {
+ auto c = sofa::helper::getWriteOnlyAccessor(*mstate1->write(sofa::core::vec_id::write_access::constraintJacobian));
+ c->clear();
+ for (const auto& [row, node, value] : Problem::entries1)
+ {
+ c->writeLine(row).addCol(node, sofa::defaulttype::Vec1Types::Deriv(value));
+ }
+ }
+
+ linearSystem->resizeSystem(Problem::n); // also invalidates the factorization
+ MatrixType* A = linearSystem->getSystemMatrix();
+ ASSERT_NE(A, nullptr);
+ for (sofa::Index i = 0; i < Problem::n; ++i)
+ {
+ for (sofa::Index j = 0; j < Problem::n; ++j)
+ {
+ if (Adense(i, j) != 0)
+ {
+ A->add(i, j, Adense(i, j));
+ }
+ }
+ }
+ A->compress();
+
+ linearSystem->getRHSVector()->clear();
+ solver->solveSystem(); // factorization
+ }
+
+ void doTearDown() override
+ {
+ if (root)
+ {
+ sofa::simulation::node::unload(root);
+ }
+ }
+
+ DenseMatrix expectedCompliance() const
+ {
+ return fact * Jdense * Adense.inverse() * Jdense.transpose();
+ }
+};
+
+TEST_F(EigenCholmodSupernodalLLTScene, addJMInvJt)
+{
+ Solver::JMatrixType J;
+ Problem::writeJ(J);
+
+ sofa::linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(solver->addJMInvJt(&W, &J, fact));
+
+ expectNear(W, expectedCompliance(), "J*A^-1*J^T");
+}
+
+/// addJMInvJt adds to the result: the row and column of the empty constraint row
+/// keep their initial values
+TEST_F(EigenCholmodSupernodalLLTScene, addJMInvJtAccumulates)
+{
+ Solver::JMatrixType J;
+ Problem::writeJ(J);
+
+ sofa::linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ DenseMatrix initial(Problem::m, Problem::m);
+ for (sofa::Index i = 0; i < Problem::m; ++i)
+ {
+ for (sofa::Index j = 0; j < Problem::m; ++j)
+ {
+ initial(i, j) = 0.01 * (1 + i + 2 * j);
+ W.set(i, j, initial(i, j));
+ }
+ }
+
+ ASSERT_TRUE(solver->addJMInvJt(&W, &J, fact));
+
+ expectNear(W, initial + expectedCompliance(), "W0 + J*A^-1*J^T");
+}
+
+/// J of another type than the solver's: the solver must convert it
+TEST_F(EigenCholmodSupernodalLLTScene, addJMInvJtFromFullMatrix)
+{
+ sofa::linearalgebra::FullMatrix J;
+ Problem::writeJ(J);
+
+ sofa::linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(solver->addJMInvJt(&W, &J, fact));
+
+ expectNear(W, expectedCompliance(), "J*A^-1*J^T");
+}
+
+TEST_F(EigenCholmodSupernodalLLTScene, buildComplianceMatrix)
+{
+ const sofa::core::ConstraintParams cparams;
+
+ sofa::linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(solver->buildComplianceMatrix(&cparams, &W, fact, 0));
+
+ expectNear(W, expectedCompliance(), "J*A^-1*J^T");
+}
+
+/// The regularization term is added on the diagonal of the non-empty rows only
+TEST_F(EigenCholmodSupernodalLLTScene, buildComplianceMatrixRegularization)
+{
+ const sofa::core::ConstraintParams cparams;
+ constexpr SReal regularization = 0.125;
+
+ sofa::linearalgebra::FullMatrix W(Problem::m, Problem::m);
+ W.clear();
+
+ ASSERT_TRUE(solver->buildComplianceMatrix(&cparams, &W, fact, regularization));
+
+ DenseMatrix expected = expectedCompliance();
+ for (sofa::Index i = 0; i < Problem::m; ++i)
+ {
+ if (i != Problem::emptyRow)
+ {
+ expected(i, i) += regularization;
+ }
+ }
+ expectNear(W, expected, "J*A^-1*J^T + reg*I");
+
+ EXPECT_EQ(W.element(Problem::emptyRow, Problem::emptyRow), 0)
+ << "the empty constraint row must not be regularized";
+}
+
} // namespace sofacholmod