Eigen-Contrib  5.0.1-dev+master
 
Loading...
Searching...
No Matches
SparseInverse.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2022 Julian Kent <jkflying@gmail.com>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_SPARSEINVERSE_H
12#define EIGEN_SPARSEINVERSE_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17#include "../../../../Eigen/Sparse"
18#include "../../../../Eigen/SparseLU"
19
20namespace Eigen {
21
35template <typename Scalar>
36class KahanSum {
37 // Straightforward Kahan summation for accurate accumulation of a sum of numbers
38 Scalar _sum{};
39 Scalar _correction{};
40
41 public:
42 Scalar value() const { return _sum; }
43
44 void operator+=(Scalar increment) {
45 const Scalar correctedIncrement = increment + _correction;
46 const Scalar previousSum = _sum;
47 _sum += correctedIncrement;
48 _correction = correctedIncrement - (_sum - previousSum);
49 }
50};
51template <typename Scalar, Index Width = 16>
52class FABSum {
53 // https://epubs.siam.org/doi/pdf/10.1137/19M1257780
54 // Fast and Accurate Blocked Summation
55 // Uses naive summation for the fast sum, and Kahan summation for the accurate sum
56 // Theoretically SIMD sum could be changed to a tree sum which would improve accuracy
57 // over naive summation
58 KahanSum<Scalar> _totalSum;
60 Index _blockUsed{};
61
62 public:
63 Scalar value() const { return _block.topRows(_blockUsed).sum() + _totalSum.value(); }
64
65 void operator+=(Scalar increment) {
66 _block(_blockUsed++, 0) = increment;
67 if (_blockUsed == Width) {
68 _totalSum += _block.sum();
69 _blockUsed = 0;
70 }
71 }
72};
73
74namespace internal {
75// Accurate sum of A_k * B_k over the shared indices, with A_k conjugated when Conjugate is true.
76template <bool Conjugate, typename Derived, typename OtherDerived>
77typename Derived::Scalar accurate_sparse_dot(const SparseMatrixBase<Derived>& A,
78 const SparseMatrixBase<OtherDerived>& other) {
79 using Scalar = typename Derived::Scalar;
80 EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
81 EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
82 EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived, OtherDerived)
83 static_assert(std::is_same<Scalar, typename OtherDerived::Scalar>::value, "mismatched types");
84
85 internal::evaluator<Derived> thisEval(A.derived());
86 typename Derived::ReverseInnerIterator i(thisEval, 0);
87
88 internal::evaluator<OtherDerived> otherEval(other.derived());
89 typename OtherDerived::ReverseInnerIterator j(otherEval, 0);
90
91 FABSum<Scalar> res;
92 while (i && j) {
93 if (i.index() == j.index()) {
94 res += (Conjugate ? numext::conj(i.value()) : i.value()) * j.value();
95 --i;
96 --j;
97 } else if (i.index() > j.index())
98 --i;
99 else
100 --j;
101 }
102 return res.value();
103}
104} // namespace internal
105
114template <typename Derived, typename OtherDerived>
115typename Derived::Scalar accurateDot(const SparseMatrixBase<Derived>& A, const SparseMatrixBase<OtherDerived>& other) {
116 return internal::accurate_sparse_dot<true>(A, other);
117}
118
138template <typename Scalar>
139class SparseInverse {
140 public:
141 using MatrixType = SparseMatrix<Scalar, ColMajor>;
142 using RowMatrixType = SparseMatrix<Scalar, RowMajor>;
143
144 SparseInverse() {}
145
153 SparseInverse(const SparseLU<MatrixType>& slu) { _result = computeInverse(slu); }
154
158 SparseInverse& compute(const SparseMatrix<Scalar>& A) {
160 slu.compute(A);
161 _result = computeInverse(slu);
162 return *this;
163 }
164
168 const MatrixType& inverse() const { return _result; }
169
174 static MatrixType computeInverse(const SparseLU<MatrixType>& slu) {
175 if (slu.info() != Success) {
176 return MatrixType(0, 0);
177 }
178
179 // Extract from SparseLU and decompose into L, inverse D and U terms
181 RowMatrixType Upper;
182 {
183 RowMatrixType DU = slu.matrixU().toSparse();
184 invD = DU.diagonal().cwiseInverse();
185 Upper = invD.asDiagonal() * DU.template triangularView<StrictlyUpper>();
186 }
187 MatrixType Lower = slu.matrixL().toSparse().template triangularView<StrictlyLower>();
188
189 // Compute the inverse and reapply the permutation matrix from the LU decomposition
190 return slu.colsPermutation().transpose() * computeInverse(Upper, invD, Lower) * slu.rowsPermutation();
191 }
192
196 static MatrixType computeInverse(const RowMatrixType& Upper, const Matrix<Scalar, Dynamic, 1>& inverseDiagonal,
197 const MatrixType& Lower) {
198 // Calculate the 'minimal set', which is the nonzeros of (L+U).transpose()
199 // It could be zeroed, but we will overwrite all non-zeros anyways.
200 MatrixType colInv = Lower.transpose().template triangularView<UnitUpper>();
201 colInv += Upper.transpose();
202
203 // We also need rowmajor representation in order to do efficient row-wise dot products
204 RowMatrixType rowInv = Upper.transpose().template triangularView<UnitLower>();
205 rowInv += Lower.transpose();
206
207 // Use the Takahashi algorithm to build the supporting elements of the inverse
208 // upwards and to the left, from the bottom right element, 1 col/row at a time
209 for (Index recurseLevel = Upper.cols() - 1; recurseLevel >= 0; recurseLevel--) {
210 const auto& col = Lower.col(recurseLevel);
211 const auto& row = Upper.row(recurseLevel);
212
213 // Calculate the inverse values for the nonzeros in this column
214 typename MatrixType::ReverseInnerIterator colIter(colInv, recurseLevel);
215 for (; recurseLevel < colIter.index(); --colIter) {
216 const Scalar element = -internal::accurate_sparse_dot<false>(col, rowInv.row(colIter.index()));
217 colIter.valueRef() = element;
218 rowInv.coeffRef(colIter.index(), recurseLevel) = element;
219 }
220
221 // Calculate the inverse values for the nonzeros in this row
222 typename RowMatrixType::ReverseInnerIterator rowIter(rowInv, recurseLevel);
223 for (; recurseLevel < rowIter.index(); --rowIter) {
224 const Scalar element = -internal::accurate_sparse_dot<false>(row, colInv.col(rowIter.index()));
225 rowIter.valueRef() = element;
226 colInv.coeffRef(recurseLevel, rowIter.index()) = element;
227 }
228
229 // And finally the diagonal, which corresponds to both row and col iterator now
230 const Scalar diag =
231 inverseDiagonal(recurseLevel) - internal::accurate_sparse_dot<false>(row, colInv.col(recurseLevel));
232 rowIter.valueRef() = diag;
233 colIter.valueRef() = diag;
234 }
235
236 return colInv;
237 }
238
239 private:
240 MatrixType _result;
241};
242
243} // namespace Eigen
244#endif
Kahan algorithm based accumulator.
Definition SparseInverse.h:36
static MatrixType computeInverse(const RowMatrixType &Upper, const Matrix< Scalar, Dynamic, 1 > &inverseDiagonal, const MatrixType &Lower)
Internal function to calculate the inverse from strictly upper, diagonal and strictly lower component...
Definition SparseInverse.h:196
SparseInverse(const SparseLU< MatrixType > &slu)
This Constructor is for if you already have a factored SparseLU and would like to use it to calculate...
Definition SparseInverse.h:153
static MatrixType computeInverse(const SparseLU< MatrixType > &slu)
Internal function to calculate the sparse inverse in a functional way.
Definition SparseInverse.h:174
const MatrixType & inverse() const
return the already-calculated sparse inverse, or a 0x0 matrix if it could not be computed
Definition SparseInverse.h:168
SparseInverse & compute(const SparseMatrix< Scalar > &A)
Calculate the sparse inverse from a given sparse input.
Definition SparseInverse.h:158
SparseLUMatrixUReturnType< SCMatrix, Map< SparseMatrix< Scalar, ColMajor, StorageIndex > > > matrixU() const
SparseLUMatrixLReturnType< SCMatrix > matrixL() const
void compute(const MatrixType &matrix)
ComputationInfo info() const
const PermutationType & colsPermutation() const
const PermutationType & rowsPermutation() const
constexpr RowXpr row(Index i)
constexpr ColXpr col(Index i)
Scalar & coeffRef(Index row, Index col)
DiagonalReturnType diagonal()
Namespace containing all symbols from the Eigen library.
Derived::Scalar accurateDot(const SparseMatrixBase< Derived > &A, const SparseMatrixBase< OtherDerived > &other)
computes an accurate dot product on two sparse vectors
Definition SparseInverse.h:115