Spectra  1.0.1
Header-only C++ Library for Large Scale Eigenvalue Problems
SparseCholesky.h
1 // Copyright (C) 2016-2022 Yixuan Qiu <yixuan.qiu@cos.name>
2 //
3 // This Source Code Form is subject to the terms of the Mozilla
4 // Public License v. 2.0. If a copy of the MPL was not distributed
5 // with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 
7 #ifndef SPECTRA_SPARSE_CHOLESKY_H
8 #define SPECTRA_SPARSE_CHOLESKY_H
9 
10 #include <Eigen/Core>
11 #include <Eigen/SparseCore>
12 #include <Eigen/SparseCholesky>
13 #include <stdexcept>
14 
15 #include "../Util/CompInfo.h"
16 
17 namespace Spectra {
18 
35 template <typename Scalar_, int Uplo = Eigen::Lower, int Flags = Eigen::ColMajor, typename StorageIndex = int>
37 {
38 public:
42  using Scalar = Scalar_;
43 
44 private:
45  using Index = Eigen::Index;
46  using Vector = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
47  using MapConstVec = Eigen::Map<const Vector>;
48  using MapVec = Eigen::Map<Vector>;
49  using SparseMatrix = Eigen::SparseMatrix<Scalar, Flags, StorageIndex>;
50 
51  const Index m_n;
52  Eigen::SimplicialLLT<SparseMatrix, Uplo> m_decomp;
53  CompInfo m_info; // status of the decomposition
54 
55 public:
63  template <typename Derived>
64  SparseCholesky(const Eigen::SparseMatrixBase<Derived>& mat) :
65  m_n(mat.rows())
66  {
67  static_assert(
68  static_cast<int>(Derived::PlainObject::IsRowMajor) == static_cast<int>(SparseMatrix::IsRowMajor),
69  "SparseCholesky: the \"Flags\" template parameter does not match the input matrix (Eigen::ColMajor/Eigen::RowMajor)");
70 
71  if (mat.rows() != mat.cols())
72  throw std::invalid_argument("SparseCholesky: matrix must be square");
73 
74  m_decomp.compute(mat);
75  m_info = (m_decomp.info() == Eigen::Success) ?
78  }
79 
83  Index rows() const { return m_n; }
87  Index cols() const { return m_n; }
88 
93  CompInfo info() const { return m_info; }
94 
101  // y_out = inv(L) * x_in
102  void lower_triangular_solve(const Scalar* x_in, Scalar* y_out) const
103  {
104  MapConstVec x(x_in, m_n);
105  MapVec y(y_out, m_n);
106  y.noalias() = m_decomp.permutationP() * x;
107  m_decomp.matrixL().solveInPlace(y);
108  }
109 
116  // y_out = inv(L') * x_in
117  void upper_triangular_solve(const Scalar* x_in, Scalar* y_out) const
118  {
119  MapConstVec x(x_in, m_n);
120  MapVec y(y_out, m_n);
121  y.noalias() = m_decomp.matrixU().solve(x);
122  y = m_decomp.permutationPinv() * y;
123  }
124 };
125 
126 } // namespace Spectra
127 
128 #endif // SPECTRA_SPARSE_CHOLESKY_H
SparseCholesky(const Eigen::SparseMatrixBase< Derived > &mat)
CompInfo info() const
void upper_triangular_solve(const Scalar *x_in, Scalar *y_out) const
void lower_triangular_solve(const Scalar *x_in, Scalar *y_out) const
CompInfo
Definition: CompInfo.h:18
@ Successful
Computation was successful.