Eigen  5.0.1
 
Loading...
Searching...
No Matches
SparseLU.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
5// Copyright (C) 2012-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_SPARSE_LU_H
13#define EIGEN_SPARSE_LU_H
14
15// IWYU pragma: private
16#include "./InternalHeaderCheck.h"
17
18namespace Eigen {
19
20template <typename MatrixType_, typename OrderingType_ = COLAMDOrdering<typename MatrixType_::StorageIndex>>
21class SparseLU;
22template <typename MappedSparseMatrixType>
23struct SparseLUMatrixLReturnType;
24template <typename MatrixLType, typename MatrixUType>
25struct SparseLUMatrixUReturnType;
26
27template <bool Conjugate, class SparseLUType>
28class SparseLUTransposeView : public SparseSolverBase<SparseLUTransposeView<Conjugate, SparseLUType>> {
29 protected:
31 using APIBase::m_isInitialized;
32
33 public:
34 using Scalar = typename SparseLUType::Scalar;
35 using StorageIndex = typename SparseLUType::StorageIndex;
36 using MatrixType = typename SparseLUType::MatrixType;
37 using OrderingType = typename SparseLUType::OrderingType;
38
39 enum { ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime };
40
41 SparseLUTransposeView() = default;
42 SparseLUTransposeView(const SparseLUTransposeView& view) : APIBase() {
43 this->m_sparseLU = view.m_sparseLU;
44 this->m_isInitialized = view.m_isInitialized;
45 }
46 void setIsInitialized(const bool isInitialized) { this->m_isInitialized = isInitialized; }
47 void setSparseLU(SparseLUType* sparseLU) { m_sparseLU = sparseLU; }
48 using APIBase::_solve_impl;
49 template <typename Rhs, typename Dest>
50 bool _solve_impl(const MatrixBase<Rhs>& B, MatrixBase<Dest>& X_base) const {
51 Dest& X(X_base.derived());
52 eigen_assert(m_sparseLU->info() == Success && "The matrix should be factorized first");
53 EIGEN_STATIC_ASSERT((Dest::Flags & RowMajorBit) == 0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
54
55 // const_cast_derived() is needed to enable aliasing detection when applying the permutations.
56 for (Index j = 0; j < B.cols(); ++j) {
57 X.col(j) = m_sparseLU->colsPermutation() * B.const_cast_derived().col(j);
58 }
59 // Forward substitution with transposed or adjoint of U
60 m_sparseLU->matrixU().template solveTransposedInPlace<Conjugate>(X);
61
62 // Backward substitution with transposed or adjoint of L
63 m_sparseLU->matrixL().template solveTransposedInPlace<Conjugate>(X);
64
65 // Permute back the solution
66 for (Index j = 0; j < B.cols(); ++j) X.col(j) = m_sparseLU->rowsPermutation().transpose() * X.col(j);
67 return true;
68 }
69 inline Index rows() const { return m_sparseLU->rows(); }
70 inline Index cols() const { return m_sparseLU->cols(); }
71
72 private:
73 SparseLUType* m_sparseLU = nullptr;
74 SparseLUTransposeView& operator=(const SparseLUTransposeView&) = delete;
75};
76
150template <typename MatrixType_, typename OrderingType_>
151class SparseLU : public SparseSolverBase<SparseLU<MatrixType_, OrderingType_>>,
152 public internal::SparseLUImpl<typename MatrixType_::Scalar, typename MatrixType_::StorageIndex> {
153 protected:
155 using APIBase::m_isInitialized;
156
157 public:
158 using APIBase::_solve_impl;
159
160 using MatrixType = MatrixType_;
161 using OrderingType = OrderingType_;
162 using Scalar = typename MatrixType::Scalar;
163 using RealScalar = typename MatrixType::RealScalar;
164 using StorageIndex = typename MatrixType::StorageIndex;
167 using ScalarVector = Matrix<Scalar, Dynamic, 1>;
168 using IndexVector = Matrix<StorageIndex, Dynamic, 1>;
171
172 enum { ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime };
173
174 public:
180 : m_lastError(""), m_Ustore(0, 0, 0, 0, 0, 0), m_symmetricmode(false), m_diagpivotthresh(1.0), m_detPermR(1) {
181 initperfvalues();
182 }
183
187 explicit SparseLU(const MatrixType& matrix)
188 : m_lastError(""), m_Ustore(0, 0, 0, 0, 0, 0), m_symmetricmode(false), m_diagpivotthresh(1.0), m_detPermR(1) {
189 initperfvalues();
190 compute(matrix);
191 }
192
193 ~SparseLU() {
194 // Free all explicit dynamic pointers
195 }
196
197 void analyzePattern(const MatrixType& matrix);
198 void factorize(const MatrixType& matrix);
199 void simplicialfactorize(const MatrixType& matrix);
200
211 void compute(const MatrixType& matrix) {
212 // Analyze
213 analyzePattern(matrix);
214 // Factorize
215 factorize(matrix);
216 }
217
230 const SparseLUTransposeView<false, SparseLU<MatrixType_, OrderingType_>> transpose() {
231 SparseLUTransposeView<false, SparseLU<MatrixType_, OrderingType_>> transposeView;
232 transposeView.setSparseLU(this);
233 transposeView.setIsInitialized(this->m_isInitialized);
234 return transposeView;
235 }
236
251 const SparseLUTransposeView<true, SparseLU<MatrixType_, OrderingType_>> adjoint() {
252 SparseLUTransposeView<true, SparseLU<MatrixType_, OrderingType_>> adjointView;
253 adjointView.setSparseLU(this);
254 adjointView.setIsInitialized(this->m_isInitialized);
255 return adjointView;
256 }
257
260 inline Index rows() const { return m_mat.rows(); }
263 inline Index cols() const { return m_mat.cols(); }
266 void isSymmetric(bool sym) { m_symmetricmode = sym; }
267
276 SparseLUMatrixLReturnType<SCMatrix> matrixL() const { return SparseLUMatrixLReturnType<SCMatrix>(m_Lstore); }
285 SparseLUMatrixUReturnType<SCMatrix, Map<SparseMatrix<Scalar, ColMajor, StorageIndex>>> matrixU() const {
286 return SparseLUMatrixUReturnType<SCMatrix, Map<SparseMatrix<Scalar, ColMajor, StorageIndex>>>(m_Lstore, m_Ustore);
287 }
288
294 inline const PermutationType& rowsPermutation() const { return m_perm_r; }
300 inline const PermutationType& colsPermutation() const { return m_perm_c; }
302 void setPivotThreshold(const RealScalar& thresh) { m_diagpivotthresh = thresh; }
303
304#ifdef EIGEN_PARSED_BY_DOXYGEN
313 template <typename Rhs>
315#endif // EIGEN_PARSED_BY_DOXYGEN
316
328 eigen_assert(m_isInitialized && "Decomposition is not initialized.");
329 return m_info;
330 }
331
336 std::string lastErrorMessage() const { return m_lastError; }
337
338 template <typename Rhs, typename Dest>
339 bool _solve_impl(const MatrixBase<Rhs>& B, MatrixBase<Dest>& X_base) const {
340 Dest& X(X_base.derived());
341 eigen_assert(m_factorizationIsOk && "The matrix should be factorized first");
342 EIGEN_STATIC_ASSERT((Dest::Flags & RowMajorBit) == 0, THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES);
343
344 // Permute the right hand side to form X = Pr*B
345 // on return, X is overwritten by the computed solution
346 X.resize(B.rows(), B.cols());
347
348 // const_cast_derived() is needed to enable aliasing detection when applying the permutations.
349 for (Index j = 0; j < B.cols(); ++j) X.col(j) = rowsPermutation() * B.const_cast_derived().col(j);
350
351 // Forward substitution with L
352 this->matrixL().solveInPlace(X);
353 this->matrixU().solveInPlace(X);
354
355 // Permute back the solution
356 for (Index j = 0; j < B.cols(); ++j) X.col(j) = colsPermutation().inverse() * X.col(j);
357
358 return true;
359 }
360
372 Scalar absDeterminant() const {
373 using std::abs;
374 eigen_assert(m_factorizationIsOk && "The matrix should be factorized first.");
375 // Initialize with the determinant of the row matrix
376 Scalar det = Scalar(1.);
377 // Note that the diagonal blocks of U are stored in supernodes,
378 // which are available in the L part :)
379 for (Index j = 0; j < this->cols(); ++j) {
380 for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) {
381 if (it.index() == j) {
382 det *= abs(it.value());
383 break;
384 }
385 }
386 }
387 return det;
388 }
389
400 Scalar logAbsDeterminant() const {
401 using std::abs;
402 using std::log;
403
404 eigen_assert(m_factorizationIsOk && "The matrix should be factorized first.");
405 Scalar det = Scalar(0.);
406 for (Index j = 0; j < this->cols(); ++j) {
407 for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) {
408 if (it.row() < j) continue;
409 if (it.row() == j) {
410 det += log(abs(it.value()));
411 break;
412 }
413 }
414 }
415 return det;
416 }
417
424 Scalar signDeterminant() const {
425 eigen_assert(m_factorizationIsOk && "The matrix should be factorized first.");
426 // Initialize with the determinant of the row matrix
427 Index det = 1;
428 // Note that the diagonal blocks of U are stored in supernodes,
429 // which are available in the L part :)
430 for (Index j = 0; j < this->cols(); ++j) {
431 for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) {
432 if (it.index() == j) {
433 if (it.value() < 0)
434 det = -det;
435 else if (it.value() == 0)
436 return 0;
437 break;
438 }
439 }
440 }
441 return det * m_detPermR * m_detPermC;
442 }
443
450 Scalar determinant() const {
451 eigen_assert(m_factorizationIsOk && "The matrix should be factorized first.");
452 // Initialize with the determinant of the row matrix
453 Scalar det = Scalar(1.);
454 // Note that the diagonal blocks of U are stored in supernodes,
455 // which are available in the L part :)
456 for (Index j = 0; j < this->cols(); ++j) {
457 for (typename SCMatrix::InnerIterator it(m_Lstore, j); it; ++it) {
458 if (it.index() == j) {
459 det *= it.value();
460 break;
461 }
462 }
463 }
464 return (m_detPermR * m_detPermC) > 0 ? det : -det;
465 }
466
469 Index nnzL() const { return m_nnzL; }
472 Index nnzU() const { return m_nnzU; }
473
474 protected:
475 // Functions
476 void initperfvalues() {
477 m_perfv.panel_size = 16;
478 m_perfv.relax = 1;
479 m_perfv.maxsuper = 128;
480 m_perfv.rowblk = 16;
481 m_perfv.colblk = 8;
482 m_perfv.fillfactor = 20;
483 }
484
485 // Variables
486 mutable ComputationInfo m_info;
487 bool m_factorizationIsOk;
488 bool m_analysisIsOk;
489 std::string m_lastError;
490 NCMatrix m_mat; // The input (permuted ) matrix
491 SCMatrix m_Lstore; // The lower triangular matrix (supernodal)
492 Map<SparseMatrix<Scalar, ColMajor, StorageIndex>> m_Ustore; // The upper triangular matrix
493 PermutationType m_perm_c; // Column permutation
494 PermutationType m_perm_r; // Row permutation
495 IndexVector m_etree; // Column elimination tree
496
497 typename Base::GlobalLU_t m_glu;
498
499 // SparseLU options
500 bool m_symmetricmode;
501 // values for performance
502 internal::perfvalues m_perfv;
503 RealScalar m_diagpivotthresh; // Specifies the threshold used for a diagonal entry to be an acceptable pivot
504 Index m_nnzL, m_nnzU; // Nonzeros in L and U factors
505 Index m_detPermR, m_detPermC; // Determinants of the permutation matrices
506 private:
507 SparseLU(const SparseLU&) = delete;
508}; // End class SparseLU
509
510// Functions needed by the analysis phase
527template <typename MatrixType, typename OrderingType>
529 // TODO It is possible as in SuperLU to compute row and column scaling vectors to equilibrate the matrix mat.
530
531 // Firstly, copy the whole input matrix.
532 m_mat = mat;
533
534 // Compute fill-in ordering
535 OrderingType ord;
536 ord(m_mat, m_perm_c);
537
538 // Apply the permutation to the column of the input matrix
539 if (m_perm_c.size()) {
540 // Switch to uncompressed mode so innerNonZeroPtr() exists and can be
541 // permuted consistently with outerIndexPtr().
542 // Downstream sparse traversals may also rely on these per-column counts
543 // while m_mat remains uncompressed.
544 m_mat.uncompress();
545 // A compressed column-major input already exposes valid column pointers.
546 // Otherwise snapshot the internal column-major structure before permuting in place.
547 const bool useInputOuterIndex = !MatrixType::IsRowMajor && mat.isCompressed();
548 ei_declare_aligned_stack_constructed_variable(
549 StorageIndex, outerIndexPtr, m_mat.cols() + 1,
550 useInputOuterIndex ? const_cast<StorageIndex*>(mat.outerIndexPtr()) : 0);
551 if (!useInputOuterIndex)
552 IndexVector::Map(outerIndexPtr, m_mat.cols() + 1) = IndexVector::Map(m_mat.outerIndexPtr(), m_mat.cols() + 1);
553
554 // Apply the permutation and compute the nnz per column.
555 for (Index i = 0; i < mat.cols(); i++) {
556 m_mat.outerIndexPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i];
557 m_mat.innerNonZeroPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i + 1] - outerIndexPtr[i];
558 }
559 }
560
561 // Compute the column elimination tree of the permuted matrix
562 IndexVector firstRowElt;
563 internal::coletree(m_mat, m_etree, firstRowElt);
564
565 // In symmetric mode, do not do postorder here
566 if (!m_symmetricmode) {
567 IndexVector post, iwork;
568 // Post order etree
569 internal::treePostorder(StorageIndex(m_mat.cols()), m_etree, post);
570
571 // Renumber etree in postorder
572 Index m = m_mat.cols();
573 iwork.resize(m + 1);
574 for (Index i = 0; i < m; ++i) iwork(post(i)) = post(m_etree(i));
575 m_etree = iwork;
576
577 // Postmultiply A*Pc by post, i.e reorder the matrix according to the postorder of the etree
578 PermutationType post_perm(m);
579 for (Index i = 0; i < m; i++) post_perm.indices()(i) = post(i);
580
581 // Combine the two permutations : postorder the permutation for future use
582 if (m_perm_c.size()) {
583 m_perm_c = post_perm * m_perm_c;
584 }
585
586 } // end postordering
587
588 m_analysisIsOk = true;
589}
590
591// Functions needed by the numerical factorization phase
592
612template <typename MatrixType, typename OrderingType>
613void SparseLU<MatrixType, OrderingType>::factorize(const MatrixType& matrix) {
614 using internal::emptyIdxLU;
615 eigen_assert(m_analysisIsOk && "analyzePattern() should be called first");
616 eigen_assert((matrix.rows() == matrix.cols()) && "Only for squared matrices");
617
618 m_isInitialized = true;
619
620 // Reset state from any prior factorize() so info() and lastErrorMessage()
621 // describe this call's outcome, not the previous matrix's.
622 m_info = Success;
623 m_lastError.clear();
624
625 // Apply the column permutation computed in analyzepattern()
626 m_mat = matrix;
627 if (m_perm_c.size()) {
628 // Switch to uncompressed mode so innerNonZeroPtr() exists and can be
629 // permuted consistently with outerIndexPtr().
630 m_mat.uncompress();
631 const bool useInputOuterIndex = !MatrixType::IsRowMajor && matrix.isCompressed();
632 ei_declare_aligned_stack_constructed_variable(
633 StorageIndex, outerIndexPtr, m_mat.cols() + 1,
634 useInputOuterIndex ? const_cast<StorageIndex*>(matrix.outerIndexPtr()) : 0);
635 if (!useInputOuterIndex)
636 IndexVector::Map(outerIndexPtr, m_mat.cols() + 1) = IndexVector::Map(m_mat.outerIndexPtr(), m_mat.cols() + 1);
637 for (Index i = 0; i < matrix.cols(); i++) {
638 m_mat.outerIndexPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i];
639 m_mat.innerNonZeroPtr()[m_perm_c.indices()(i)] = outerIndexPtr[i + 1] - outerIndexPtr[i];
640 }
641 } else { // FIXME This should not be needed if the empty permutation is handled transparently
642 m_perm_c.resize(matrix.cols());
643 for (StorageIndex i = 0; i < matrix.cols(); ++i) m_perm_c.indices()(i) = i;
644 }
645
646 Index m = m_mat.rows();
647 Index n = m_mat.cols();
648 Index nnz = m_mat.nonZeros();
649 Index maxpanel = m_perfv.panel_size * m;
650 // Allocate working storage common to the factor routines
651 Index lwork = 0;
652 // Return the size of actually allocated memory when allocation failed,
653 // and 0 on success.
654 Index info = Base::memInit(m, n, nnz, lwork, m_perfv.fillfactor, m_perfv.panel_size, m_glu);
655 if (info) {
656 m_lastError = "UNABLE TO ALLOCATE WORKING MEMORY\n\n";
657 m_factorizationIsOk = false;
658 return;
659 }
660
661 // Set up pointers for integer working arrays
662 IndexVector segrep(m);
663 segrep.setZero();
664 IndexVector parent(m);
665 parent.setZero();
666 IndexVector xplore(m);
667 xplore.setZero();
668 IndexVector repfnz(maxpanel);
669 IndexVector panel_lsub(maxpanel);
670 IndexVector xprune(n);
671 xprune.setZero();
672 IndexVector marker(m * internal::LUNoMarker);
673 marker.setZero();
674
675 repfnz.setConstant(-1);
676 panel_lsub.setConstant(-1);
677
678 // Set up pointers for scalar working arrays
679 ScalarVector dense;
680 dense.setZero(maxpanel);
681 ScalarVector tempv;
682 tempv.setZero(internal::LUnumTempV(m, m_perfv.panel_size, m_perfv.maxsuper, /*m_perfv.rowblk*/ m));
683
684 // Compute the inverse of perm_c
685 PermutationType iperm_c(m_perm_c.inverse());
686
687 // Identify initial relaxed snodes
688 IndexVector relax_end(n);
689 if (m_symmetricmode == true)
690 Base::heap_relax_snode(n, m_etree, m_perfv.relax, marker, relax_end);
691 else
692 Base::relax_snode(n, m_etree, m_perfv.relax, marker, relax_end);
693
694 m_perm_r.resize(m);
695 m_perm_r.indices().setConstant(-1);
696 marker.setConstant(-1);
697 m_detPermR = 1; // Record the determinant of the row permutation
698
699 m_glu.supno(0) = emptyIdxLU;
700 m_glu.xsup.setConstant(0);
701 m_glu.xsup(0) = m_glu.xlsub(0) = m_glu.xusub(0) = m_glu.xlusup(0) = Index(0);
702
703 // Work on one 'panel' at a time. A panel is one of the following :
704 // (a) a relaxed supernode at the bottom of the etree, or
705 // (b) panel_size contiguous columns, <panel_size> defined by the user
706 Index jcol;
707 Index pivrow; // Pivotal row number in the original row matrix
708 Index nseg1; // Number of segments in U-column above panel row jcol
709 Index nseg; // Number of segments in each U-column
710 Index irep;
711 Index i, k, jj;
712 for (jcol = 0; jcol < n;) {
713 // Adjust panel size so that a panel won't overlap with the next relaxed snode.
714 Index panel_size = m_perfv.panel_size; // upper bound on panel width
715 for (k = jcol + 1; k < (std::min)(jcol + panel_size, n); k++) {
716 if (relax_end(k) != emptyIdxLU) {
717 panel_size = k - jcol;
718 break;
719 }
720 }
721 if (k == n) panel_size = n - jcol;
722
723 // Symbolic outer factorization on a panel of columns
724 Base::panel_dfs(m, panel_size, jcol, m_mat, m_perm_r.indices(), nseg1, dense, panel_lsub, segrep, repfnz, xprune,
725 marker, parent, xplore, m_glu);
726
727 // Numeric sup-panel updates in topological order
728 Base::panel_bmod(m, panel_size, jcol, nseg1, dense, tempv, segrep, repfnz, m_glu);
729
730 // Sparse LU within the panel, and below the panel diagonal
731 for (jj = jcol; jj < jcol + panel_size; jj++) {
732 k = (jj - jcol) * m; // Column index for w-wide arrays
733
734 nseg = nseg1; // begin after all the panel segments
735 // Depth-first-search for the current column
736 VectorBlock<IndexVector> panel_lsubk(panel_lsub, k, m);
737 VectorBlock<IndexVector> repfnz_k(repfnz, k, m);
738 // Return 0 on success and > 0 number of bytes allocated when run out of space.
739 info = Base::column_dfs(m, jj, m_perm_r.indices(), m_perfv.maxsuper, nseg, panel_lsubk, segrep, repfnz_k, xprune,
740 marker, parent, xplore, m_glu);
741 if (info) {
742 m_lastError = "UNABLE TO EXPAND MEMORY IN COLUMN_DFS() ";
743 m_info = NumericalIssue;
744 m_factorizationIsOk = false;
745 return;
746 }
747 // Numeric updates to this column
748 VectorBlock<ScalarVector> dense_k(dense, k, m);
749 VectorBlock<IndexVector> segrep_k(segrep, nseg1, m - nseg1);
750 // Return 0 on success and > 0 number of bytes allocated when run out of space.
751 info = Base::column_bmod(jj, (nseg - nseg1), dense_k, tempv, segrep_k, repfnz_k, jcol, m_glu);
752 if (info) {
753 m_lastError = "UNABLE TO EXPAND MEMORY IN COLUMN_BMOD() ";
754 m_info = NumericalIssue;
755 m_factorizationIsOk = false;
756 return;
757 }
758
759 // Copy the U-segments to ucol(*)
760 // Return 0 on success and > 0 number of bytes allocated when run out of space.
761 info = Base::copy_to_ucol(jj, nseg, segrep, repfnz_k, m_perm_r.indices(), dense_k, m_glu);
762 if (info) {
763 m_lastError = "UNABLE TO EXPAND MEMORY IN COPY_TO_UCOL() ";
764 m_info = NumericalIssue;
765 m_factorizationIsOk = false;
766 return;
767 }
768
769 // Form the L-segment
770 // Return 0 if success, i > 0 if U(i, i) is exactly zero.
771 info = Base::pivotL(jj, m_diagpivotthresh, m_perm_r.indices(), iperm_c.indices(), pivrow, m_glu);
772 if (info) {
773 m_lastError = "THE MATRIX IS STRUCTURALLY SINGULAR";
774#ifndef EIGEN_NO_IO
775 std::ostringstream returnInfo;
776 returnInfo << " ... ZERO COLUMN AT ";
777 returnInfo << info;
778 m_lastError += returnInfo.str();
779#endif
780 m_info = NumericalIssue;
781 m_factorizationIsOk = false;
782 return;
783 }
784
785 // Prune columns (0:jj-1) using column jj
786 Base::pruneL(jj, m_perm_r.indices(), pivrow, nseg, segrep, repfnz_k, xprune, m_glu);
787
788 // Reset repfnz for this column
789 for (i = 0; i < nseg; i++) {
790 irep = segrep(i);
791 repfnz_k(irep) = emptyIdxLU;
792 }
793 } // end SparseLU within the panel
794 jcol += panel_size; // Move to the next panel
795 } // end for -- end elimination
796
797 m_detPermR = m_perm_r.determinant();
798 m_detPermC = m_perm_c.determinant();
799
800 // Count the number of nonzeros in factors
801 Base::countnz(n, m_nnzL, m_nnzU, m_glu);
802 // Apply permutation to the L subscripts
803 Base::fixupL(n, m_perm_r.indices(), m_glu);
804
805 // Create supernode matrix L
806 m_Lstore.setInfos(m, n, m_glu.lusup, m_glu.xlusup, m_glu.lsub, m_glu.xlsub, m_glu.supno, m_glu.xsup);
807 // Create the column major upper sparse matrix U;
808 new (&m_Ustore) Map<SparseMatrix<Scalar, ColMajor, StorageIndex>>(m, n, m_nnzU, m_glu.xusub.data(), m_glu.usub.data(),
809 m_glu.ucol.data());
810
811 m_info = Success;
812 m_factorizationIsOk = true;
813}
814
815template <typename MappedSupernodalType>
816struct SparseLUMatrixLReturnType : internal::no_assignment_operator {
817 using Scalar = typename MappedSupernodalType::Scalar;
818 explicit SparseLUMatrixLReturnType(const MappedSupernodalType& mapL) : m_mapL(mapL) {}
819 Index rows() const { return m_mapL.rows(); }
820 Index cols() const { return m_mapL.cols(); }
821 template <typename Dest>
822 void solveInPlace(MatrixBase<Dest>& X) const {
823 m_mapL.solveInPlace(X);
824 }
825 template <bool Conjugate, typename Dest>
826 void solveTransposedInPlace(MatrixBase<Dest>& X) const {
827 m_mapL.template solveTransposedInPlace<Conjugate>(X);
828 }
829
830 SparseMatrix<Scalar, ColMajor, Index> toSparse() const {
831 ArrayXi colCount = ArrayXi::Ones(cols());
832 for (Index i = 0; i < cols(); i++) {
833 typename MappedSupernodalType::InnerIterator iter(m_mapL, i);
834 for (; iter; ++iter) {
835 if (iter.row() > iter.col()) {
836 colCount(iter.col())++;
837 }
838 }
839 }
840 SparseMatrix<Scalar, ColMajor, Index> sL(rows(), cols());
841 sL.reserve(colCount);
842 for (Index i = 0; i < cols(); i++) {
843 sL.insert(i, i) = 1.0;
844 typename MappedSupernodalType::InnerIterator iter(m_mapL, i);
845 for (; iter; ++iter) {
846 if (iter.row() > iter.col()) {
847 sL.insert(iter.row(), iter.col()) = iter.value();
848 }
849 }
850 }
851 sL.makeCompressed();
852 return sL;
853 }
854
855 const MappedSupernodalType& m_mapL;
856};
857
858template <typename MatrixLType, typename MatrixUType>
859struct SparseLUMatrixUReturnType : internal::no_assignment_operator {
860 using Scalar = typename MatrixLType::Scalar;
861 SparseLUMatrixUReturnType(const MatrixLType& mapL, const MatrixUType& mapU) : m_mapL(mapL), m_mapU(mapU) {}
862 Index rows() const { return m_mapL.rows(); }
863 Index cols() const { return m_mapL.cols(); }
864
865 template <typename Dest>
866 void solveInPlace(MatrixBase<Dest>& X) const {
867 Index nrhs = X.cols();
868 // Backward solve with U
869 for (Index k = m_mapL.nsuper(); k >= 0; k--) {
870 Index fsupc = m_mapL.supToCol()[k];
871 Index lda = m_mapL.colIndexPtr()[fsupc + 1] - m_mapL.colIndexPtr()[fsupc]; // leading dimension
872 Index nsupc = m_mapL.supToCol()[k + 1] - fsupc;
873 Index luptr = m_mapL.colIndexPtr()[fsupc];
874
875 if (nsupc == 1) {
876 for (Index j = 0; j < nrhs; j++) {
877 X(fsupc, j) /= m_mapL.valuePtr()[luptr];
878 }
879 } else {
880 // FIXME: the following lines should use Block expressions and not Map!
881 Map<const Matrix<Scalar, Dynamic, Dynamic, ColMajor>, 0, OuterStride<>> A(&(m_mapL.valuePtr()[luptr]), nsupc,
882 nsupc, OuterStride<>(lda));
883 typename Dest::RowsBlockXpr U = X.derived().middleRows(fsupc, nsupc);
884 U = A.template triangularView<Upper>().solve(U);
885 }
886
887 for (Index j = 0; j < nrhs; ++j) {
888 for (Index jcol = fsupc; jcol < fsupc + nsupc; jcol++) {
889 typename MatrixUType::InnerIterator it(m_mapU, jcol);
890 for (; it; ++it) {
891 Index irow = it.index();
892 X(irow, j) -= X(jcol, j) * it.value();
893 }
894 }
895 }
896 } // End For U-solve
897 }
898
899 template <bool Conjugate, typename Dest>
900 void solveTransposedInPlace(MatrixBase<Dest>& X) const {
901 using numext::conj;
902 Index nrhs = X.cols();
903 // Forward solve with U
904 for (Index k = 0; k <= m_mapL.nsuper(); k++) {
905 Index fsupc = m_mapL.supToCol()[k];
906 Index lda = m_mapL.colIndexPtr()[fsupc + 1] - m_mapL.colIndexPtr()[fsupc]; // leading dimension
907 Index nsupc = m_mapL.supToCol()[k + 1] - fsupc;
908 Index luptr = m_mapL.colIndexPtr()[fsupc];
909
910 for (Index j = 0; j < nrhs; ++j) {
911 for (Index jcol = fsupc; jcol < fsupc + nsupc; jcol++) {
912 typename MatrixUType::InnerIterator it(m_mapU, jcol);
913 for (; it; ++it) {
914 Index irow = it.index();
915 X(jcol, j) -= X(irow, j) * (Conjugate ? conj(it.value()) : it.value());
916 }
917 }
918 }
919 if (nsupc == 1) {
920 for (Index j = 0; j < nrhs; j++) {
921 X(fsupc, j) /= (Conjugate ? conj(m_mapL.valuePtr()[luptr]) : m_mapL.valuePtr()[luptr]);
922 }
923 } else {
924 Map<const Matrix<Scalar, Dynamic, Dynamic, ColMajor>, 0, OuterStride<>> A(&(m_mapL.valuePtr()[luptr]), nsupc,
925 nsupc, OuterStride<>(lda));
926 typename Dest::RowsBlockXpr U = X.derived().middleRows(fsupc, nsupc);
927 EIGEN_IF_CONSTEXPR (Conjugate)
928 U = A.adjoint().template triangularView<Lower>().solve(U);
929 else
930 U = A.transpose().template triangularView<Lower>().solve(U);
931 }
932 } // End For U-solve
933 }
934
935 SparseMatrix<Scalar, RowMajor, Index> toSparse() {
936 ArrayXi rowCount = ArrayXi::Zero(rows());
937 for (Index i = 0; i < cols(); i++) {
938 typename MatrixLType::InnerIterator iter(m_mapL, i);
939 for (; iter; ++iter) {
940 if (iter.row() <= iter.col()) {
941 rowCount(iter.row())++;
942 }
943 }
944 }
945
946 SparseMatrix<Scalar, RowMajor, Index> sU(rows(), cols());
947 sU.reserve(rowCount);
948 for (Index i = 0; i < cols(); i++) {
949 typename MatrixLType::InnerIterator iter(m_mapL, i);
950 for (; iter; ++iter) {
951 if (iter.row() <= iter.col()) {
952 sU.insert(iter.row(), iter.col()) = iter.value();
953 }
954 }
955 }
956 sU.makeCompressed();
957 const SparseMatrix<Scalar, RowMajor, Index> u = m_mapU; // convert to RowMajor
958 sU += u;
959 return sU;
960 }
961
962 const MatrixLType& m_mapL;
963 const MatrixUType& m_mapU;
964};
965
966} // End namespace Eigen
967
968#endif
constexpr ColXpr col(Index i)
Definition DenseBase.h:1081
A matrix or vector expression mapping an existing array of data.
Definition Map.h:97
Base class for all dense matrices, vectors, and expressions.
Definition MatrixBase.h:53
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
InverseReturnType inverse() const
Definition PermutationMatrix.h:229
Permutation matrix.
Definition PermutationMatrix.h:346
constexpr const IndicesType & indices() const
Definition PermutationMatrix.h:400
Derived & setConstant(Index size, const Scalar &val)
Definition CwiseNullaryOp.h:349
Derived & setZero(Index size)
Definition CwiseNullaryOp.h:536
constexpr void resize(Index rows, Index cols)
Definition PlainObjectBase.h:282
Pseudo expression representing a solving operation.
Definition Solve.h:63
Sparse supernodal LU factorization for general matrices.
Definition SparseLU.h:152
SparseLUMatrixUReturnType< SCMatrix, Map< SparseMatrix< Scalar, ColMajor, StorageIndex > > > matrixU() const
Give the MatrixU.
Definition SparseLU.h:285
void setPivotThreshold(const RealScalar &thresh)
Definition SparseLU.h:302
Index cols() const
Give the number of columns.
Definition SparseLU.h:263
Scalar logAbsDeterminant() const
Give the natural log of the absolute determinant.
Definition SparseLU.h:400
Index rows() const
Give the number of rows.
Definition SparseLU.h:260
Index nnzU() const
Give the number of non zero in matrix U.
Definition SparseLU.h:472
const SparseLUTransposeView< true, SparseLU< MatrixType_, OrderingType_ > > adjoint()
Return a solver for the adjointed matrix.
Definition SparseLU.h:251
Solve< SparseLU, Rhs > solve(const MatrixBase< Rhs > &B) const
Solve a system .
void factorize(const MatrixType &matrix)
Factorize the matrix to get the solver ready.
Definition SparseLU.h:613
Scalar determinant() const
Give the determinant.
Definition SparseLU.h:450
Scalar signDeterminant() const
Give the sign of the determinant.
Definition SparseLU.h:424
std::string lastErrorMessage() const
Give a human readable error.
Definition SparseLU.h:336
SparseLUMatrixLReturnType< SCMatrix > matrixL() const
Give the matrixL.
Definition SparseLU.h:276
void compute(const MatrixType &matrix)
Analyze and factorize the matrix so the solver is ready to solve.
Definition SparseLU.h:211
ComputationInfo info() const
Reports whether previous computation was successful.
Definition SparseLU.h:327
const PermutationType & colsPermutation() const
Give the column matrix permutation.
Definition SparseLU.h:300
SparseLU()
Basic constructor of the solver.
Definition SparseLU.h:179
void analyzePattern(const MatrixType &matrix)
Compute the column permutation.
Definition SparseLU.h:528
Index nnzL() const
Give the number of non zero in matrix L.
Definition SparseLU.h:469
const PermutationType & rowsPermutation() const
Give the row matrix permutation.
Definition SparseLU.h:294
void isSymmetric(bool sym)
Let you set that the pattern of the input matrix is symmetric.
Definition SparseLU.h:266
Scalar absDeterminant() const
Give the absolute value of the determinant.
Definition SparseLU.h:372
SparseLU(const MatrixType &matrix)
Constructor of the solver already based on a specific matrix.
Definition SparseLU.h:187
const SparseLUTransposeView< false, SparseLU< MatrixType_, OrderingType_ > > transpose()
Return a solver for the transposed matrix.
Definition SparseLU.h:230
A versatile sparse matrix representation.
Definition SparseMatrix.h:122
A base class for sparse solvers.
Definition SparseSolverBase.h:68
Expression of a fixed-size or dynamic-size sub-vector.
Definition VectorBlock.h:59
a class to manipulate the L supernodal factor from the SparseLU factorization
Definition SparseLU_SupernodalMatrix.h:33
Definition SparseLUImpl.h:24
void relax_snode(const Index n, IndexVector &et, const Index relax_columns, IndexVector &descendants, IndexVector &relax_end)
Identify the initial relaxed supernodes.
Definition SparseLU_relax_snode.h:51
Index column_dfs(const Index m, const Index jcol, IndexVector &perm_r, Index maxsuper, Index &nseg, BlockIndexVector lsub_col, IndexVector &segrep, BlockIndexVector repfnz, IndexVector &xprune, IndexVector &marker, IndexVector &parent, IndexVector &xplore, GlobalLU_t &glu)
Performs a symbolic factorization on column jcol and decide the supernode boundary.
Definition SparseLU_column_dfs.h:91
void fixupL(const Index n, const IndexVector &perm_r, GlobalLU_t &glu)
Fix up the data storage lsub for L-subscripts.
Definition SparseLU_Utils.h:52
Index copy_to_ucol(const Index jcol, const Index nseg, IndexVector &segrep, BlockIndexVector repfnz, IndexVector &perm_r, BlockScalarVector dense, GlobalLU_t &glu)
Performs numeric block updates (sup-col) in topological order.
Definition SparseLU_copy_to_ucol.h:54
void heap_relax_snode(const Index n, IndexVector &et, const Index relax_columns, IndexVector &descendants, IndexVector &relax_end)
Identify the initial relaxed supernodes.
Definition SparseLU_heap_relax_snode.h:50
void panel_dfs(const Index m, const Index w, const Index jcol, MatrixType &A, IndexVector &perm_r, Index &nseg, ScalarVector &dense, IndexVector &panel_lsub, IndexVector &segrep, IndexVector &repfnz, IndexVector &xprune, IndexVector &marker, IndexVector &parent, IndexVector &xplore, GlobalLU_t &glu)
Performs a symbolic factorization on a panel of columns [jcol, jcol+w)
Definition SparseLU_panel_dfs.h:195
void countnz(const Index n, Index &nnzL, Index &nnzU, GlobalLU_t &glu)
Count Nonzero elements in the factors.
Definition SparseLU_Utils.h:24
Index column_bmod(const Index jcol, const Index nseg, BlockScalarVector dense, ScalarVector &tempv, BlockIndexVector segrep, BlockIndexVector repfnz, Index fpanelc, GlobalLU_t &glu)
Performs numeric block updates (sup-col) in topological order.
Definition SparseLU_column_bmod.h:57
Index pivotL(const Index jcol, const RealScalar &diagpivotthresh, IndexVector &perm_r, IndexVector &iperm_c, Index &pivrow, GlobalLU_t &glu)
Performs the numerical pivoting on the current column of L, and the CDIV operation.
Definition SparseLU_pivotL.h:64
Index memInit(Index m, Index n, Index annz, Index lwork, Index fillratio, Index panel_size, GlobalLU_t &glu)
Allocate various working space for the numerical factorization phase.
Definition SparseLU_Memory.h:135
void pruneL(const Index jcol, const IndexVector &perm_r, const Index pivrow, const Index nseg, const IndexVector &segrep, BlockIndexVector repfnz, IndexVector &xprune, GlobalLU_t &glu)
Prunes the L-structure.
Definition SparseLU_pruneL.h:57
void panel_bmod(const Index m, const Index w, const Index jcol, const Index nseg, ScalarVector &dense, ScalarVector &tempv, IndexVector &segrep, IndexVector &repfnz, GlobalLU_t &glu)
Performs numeric block updates (sup-panel) in topological order.
Definition SparseLU_panel_bmod.h:60
ComputationInfo
Definition Constants.h:455
@ NumericalIssue
Definition Constants.h:459
@ Success
Definition Constants.h:457
constexpr unsigned int RowMajorBit
Definition Constants.h:71