11 #ifndef EIGEN_SPARSE_QR_H 12 #define EIGEN_SPARSE_QR_H 16 template<
typename MatrixType,
typename OrderingType>
class SparseQR;
23 typedef typename SparseQRType::MatrixType ReturnType;
24 typedef typename ReturnType::Index Index;
25 typedef typename ReturnType::StorageKind StorageKind;
29 typedef typename SparseQRType::MatrixType ReturnType;
33 typedef typename Derived::PlainObject ReturnType;
64 template<
typename _MatrixType,
typename _OrderingType>
69 typedef _OrderingType OrderingType;
71 typedef typename MatrixType::RealScalar RealScalar;
72 typedef typename MatrixType::Index Index;
78 SparseQR () : m_isInitialized(
false), m_analysisIsok(
false), m_lastError(
""), m_useDefaultThreshold(
true),m_isQSorted(
false),m_isEtreeOk(
false)
87 SparseQR(
const MatrixType& mat) : m_isInitialized(false), m_analysisIsok(false), m_lastError(
""), m_useDefaultThreshold(true),m_isQSorted(false),m_isEtreeOk(false)
103 void analyzePattern(
const MatrixType& mat);
104 void factorize(
const MatrixType& mat);
108 inline Index
rows()
const {
return m_pmat.rows(); }
112 inline Index
cols()
const {
return m_pmat.cols();}
116 const QRMatrixType&
matrixR()
const {
return m_R; }
124 eigen_assert(m_isInitialized &&
"The factorization should be called first, use compute()");
125 return m_nonzeropivots;
154 eigen_assert(m_isInitialized &&
"Decomposition is not initialized.");
155 return m_outputPerm_c;
164 template<
typename Rhs,
typename Dest>
167 eigen_assert(m_isInitialized &&
"The factorization should be called first, use compute()");
168 eigen_assert(this->rows() == B.rows() &&
"SparseQR::solve() : invalid number of rows in the right hand side matrix");
170 Index rank = this->rank();
173 typename Dest::PlainObject y, b;
174 y = this->matrixQ().transpose() * B;
178 y.
resize((std::max)(cols(),Index(y.rows())),y.cols());
179 y.topRows(rank) = this->matrixR().topLeftCorner(rank, rank).template triangularView<Upper>().solve(b.topRows(rank));
180 y.bottomRows(y.rows()-rank).setZero();
183 if (m_perm_c.size()) dest = colsPermutation() * y.
topRows(cols());
198 m_useDefaultThreshold =
false;
199 m_threshold = threshold;
206 template<
typename Rhs>
209 eigen_assert(m_isInitialized &&
"The factorization should be called first, use compute()");
210 eigen_assert(this->rows() == B.rows() &&
"SparseQR::solve() : invalid number of rows in the right hand side matrix");
213 template<
typename Rhs>
216 eigen_assert(m_isInitialized &&
"The factorization should be called first, use compute()");
217 eigen_assert(this->rows() == B.
rows() &&
"SparseQR::solve() : invalid number of rows in the right hand side matrix");
231 eigen_assert(m_isInitialized &&
"Decomposition is not initialized.");
236 inline void sort_matrix_Q()
238 if(this->m_isQSorted)
return;
242 this->m_isQSorted =
true;
247 bool m_isInitialized;
249 bool m_factorizationIsok;
251 std::string m_lastError;
255 ScalarVector m_hcoeffs;
256 PermutationType m_perm_c;
257 PermutationType m_pivotperm;
258 PermutationType m_outputPerm_c;
259 RealScalar m_threshold;
260 bool m_useDefaultThreshold;
261 Index m_nonzeropivots;
263 IndexVector m_firstRowElt;
281 template <
typename MatrixType,
typename OrderingType>
284 eigen_assert(mat.isCompressed() &&
"SparseQR requires a sparse matrix in compressed mode. Call .makeCompressed() before passing it to SparseQR");
289 ord(matCpy, m_perm_c);
290 Index n = mat.cols();
291 Index m = mat.rows();
292 Index diagSize = (std::min)(m,n);
294 if (!m_perm_c.size())
297 m_perm_c.indices().setLinSpaced(n, 0,n-1);
301 m_outputPerm_c = m_perm_c.inverse();
306 m_Q.resize(m, diagSize);
309 m_R.reserve(2*mat.nonZeros());
310 m_Q.reserve(2*mat.nonZeros());
311 m_hcoeffs.resize(diagSize);
312 m_analysisIsok =
true;
322 template <
typename MatrixType,
typename OrderingType>
328 eigen_assert(m_analysisIsok &&
"analyzePattern() should be called before this step");
329 Index m = mat.rows();
330 Index n = mat.cols();
331 Index diagSize = (std::min)(m,n);
334 Index nzcolR, nzcolQ;
336 RealScalar pivotThreshold = m_threshold;
343 m_outputPerm_c = m_perm_c.inverse();
356 const Index *originalOuterIndices = mat.outerIndexPtr();
357 if(MatrixType::IsRowMajor)
359 originalOuterIndicesCpy = IndexVector::Map(m_pmat.outerIndexPtr(),n+1);
360 originalOuterIndices = originalOuterIndicesCpy.
data();
363 for (
int i = 0; i < n; i++)
365 Index p = m_perm_c.size() ? m_perm_c.indices()(i) : i;
366 m_pmat.outerIndexPtr()[p] = originalOuterIndices[i];
367 m_pmat.innerNonZeroPtr()[p] = originalOuterIndices[i+1] - originalOuterIndices[i];
375 if(m_useDefaultThreshold)
377 RealScalar max2Norm = 0.0;
378 for (
int j = 0; j < n; j++) max2Norm = (max)(max2Norm, m_pmat.col(j).norm());
379 if(max2Norm==RealScalar(0))
380 max2Norm = RealScalar(1);
385 m_pivotperm.setIdentity(n);
387 Index nonzeroCol = 0;
391 for (Index col = 0; col < n; ++col)
395 mark(nonzeroCol) = col;
396 Qidx(0) = nonzeroCol;
397 nzcolR = 0; nzcolQ = 1;
398 bool found_diag = nonzeroCol>=m;
405 for (
typename QRMatrixType::InnerIterator itp(m_pmat, col); itp || !found_diag; ++itp)
407 Index curIdx = nonzeroCol;
408 if(itp) curIdx = itp.row();
409 if(curIdx == nonzeroCol) found_diag =
true;
412 Index st = m_firstRowElt(curIdx);
415 m_lastError =
"Empty row found during numerical factorization";
422 for (; mark(st) != col; st = m_etree(st))
430 Index nt = nzcolR-bi;
431 for(Index i = 0; i < nt/2; i++) std::swap(Ridx(bi+i), Ridx(nzcolR-i-1));
434 if(itp) tval(curIdx) = itp.value();
435 else tval(curIdx) =
Scalar(0);
438 if(curIdx > nonzeroCol && mark(curIdx) != col )
440 Qidx(nzcolQ) = curIdx;
447 for (Index i = nzcolR-1; i >= 0; i--)
449 Index curIdx = Ridx(i);
455 tdot = m_Q.col(curIdx).dot(tval);
457 tdot *= m_hcoeffs(curIdx);
461 for (
typename QRMatrixType::InnerIterator itq(m_Q, curIdx); itq; ++itq)
462 tval(itq.row()) -= itq.value() * tdot;
465 if(m_etree(Ridx(i)) == nonzeroCol)
467 for (
typename QRMatrixType::InnerIterator itq(m_Q, curIdx); itq; ++itq)
469 Index iQ = itq.row();
482 if(nonzeroCol < diagSize)
486 Scalar c0 = nzcolQ ? tval(Qidx(0)) :
Scalar(0);
489 RealScalar sqrNorm = 0.;
490 for (Index itq = 1; itq < nzcolQ; ++itq) sqrNorm += numext::abs2(tval(Qidx(itq)));
491 if(sqrNorm == RealScalar(0) && numext::imag(c0) == RealScalar(0))
493 beta = numext::real(c0);
499 beta = sqrt(numext::abs2(c0) + sqrNorm);
500 if(numext::real(c0) >= RealScalar(0))
503 for (Index itq = 1; itq < nzcolQ; ++itq)
504 tval(Qidx(itq)) /= (c0 - beta);
505 tau = numext::conj((beta-c0) / beta);
511 for (Index i = nzcolR-1; i >= 0; i--)
513 Index curIdx = Ridx(i);
514 if(curIdx < nonzeroCol)
516 m_R.insertBackByOuterInnerUnordered(col, curIdx) = tval(curIdx);
517 tval(curIdx) =
Scalar(0.);
521 if(nonzeroCol < diagSize && abs(beta) >= pivotThreshold)
523 m_R.insertBackByOuterInner(col, nonzeroCol) = beta;
525 m_hcoeffs(nonzeroCol) = tau;
527 for (Index itq = 0; itq < nzcolQ; ++itq)
529 Index iQ = Qidx(itq);
530 m_Q.insertBackByOuterInnerUnordered(nonzeroCol,iQ) = tval(iQ);
534 if(nonzeroCol<diagSize)
535 m_Q.startVec(nonzeroCol);
540 for (Index j = nonzeroCol; j < n-1; j++)
541 std::swap(m_pivotperm.indices()(j), m_pivotperm.indices()[j+1]);
549 m_hcoeffs.tail(diagSize-nonzeroCol).setZero();
553 m_Q.makeCompressed();
555 m_R.makeCompressed();
558 m_nonzeropivots = nonzeroCol;
564 m_R = tempR * m_pivotperm;
567 m_outputPerm_c = m_outputPerm_c * m_pivotperm;
570 m_isInitialized =
true;
571 m_factorizationIsok =
true;
577 template<
typename _MatrixType,
typename OrderingType,
typename Rhs>
582 EIGEN_MAKE_SOLVE_HELPERS(Dec,Rhs)
584 template<
typename Dest>
void evalTo(Dest& dst)
const 586 dec()._solve(rhs(),dst);
589 template<
typename _MatrixType,
typename OrderingType,
typename Rhs>
594 EIGEN_MAKE_SPARSE_SOLVE_HELPERS(Dec, Rhs)
596 template<
typename Dest>
void evalTo(Dest& dst)
const 598 this->defaultEvalTo(dst);
603 template <
typename SparseQRType,
typename Derived>
606 typedef typename SparseQRType::QRMatrixType
MatrixType;
608 typedef typename SparseQRType::Index Index;
610 SparseQR_QProduct(
const SparseQRType& qr,
const Derived& other,
bool transpose) :
611 m_qr(qr),m_other(other),m_transpose(transpose) {}
612 inline Index rows()
const {
return m_transpose ? m_qr.rows() : m_qr.cols(); }
613 inline Index cols()
const {
return m_other.cols(); }
616 template<
typename DesType>
617 void evalTo(DesType& res)
const 619 Index m = m_qr.rows();
620 Index n = m_qr.cols();
621 Index diagSize = (std::min)(m,n);
625 eigen_assert(m_qr.m_Q.rows() == m_other.rows() &&
"Non conforming object sizes");
627 for(Index j = 0; j < res.cols(); j++){
628 for (Index k = 0; k < diagSize; k++)
631 tau = m_qr.m_Q.col(k).dot(res.col(j));
632 if(tau==
Scalar(0))
continue;
633 tau = tau * m_qr.m_hcoeffs(k);
634 res.col(j) -= tau * m_qr.m_Q.col(k);
640 eigen_assert(m_qr.m_Q.rows() == m_other.rows() &&
"Non conforming object sizes");
642 for(Index j = 0; j < res.cols(); j++)
644 for (Index k = diagSize-1; k >=0; k--)
647 tau = m_qr.m_Q.col(k).dot(res.col(j));
648 if(tau==
Scalar(0))
continue;
649 tau = tau * m_qr.m_hcoeffs(k);
650 res.col(j) -= tau * m_qr.m_Q.col(k);
656 const SparseQRType& m_qr;
657 const Derived& m_other;
661 template<
typename SparseQRType>
664 typedef typename SparseQRType::Index Index;
668 template<
typename Derived>
677 inline Index rows()
const {
return m_qr.rows(); }
678 inline Index cols()
const {
return (std::min)(m_qr.rows(),m_qr.cols()); }
686 dest.derived() = m_qr.matrixQ() * Dest::Identity(m_qr.rows(), m_qr.rows());
690 Dest idMat(m_qr.rows(), m_qr.rows());
693 const_cast<SparseQRType *
>(&m_qr)->sort_matrix_Q();
697 const SparseQRType& m_qr;
700 template<
typename SparseQRType>
704 template<
typename Derived>
709 const SparseQRType& m_qr;
Definition: ForwardDeclarations.h:124
Index cols() const
Definition: SparseQR.h:112
SparseQRMatrixQReturnType< SparseQR > matrixQ() const
Definition: SparseQR.h:146
RowsBlockXpr topRows(Index n)
Definition: DenseBase.h:381
Derived & setIdentity()
Writes the identity expression (not necessarily square) into *this.
Definition: CwiseNullaryOp.h:772
EIGEN_STRONG_INLINE const Scalar * data() const
Definition: PlainObjectBase.h:212
ComputationInfo info() const
Reports whether previous computation was successful.
Definition: SparseQR.h:229
iterative scaling algorithm to equilibrate rows and column norms in matrices
Definition: TestIMU_Common.h:87
Definition: SparseSolve.h:18
Holds information about the various numeric (i.e.
Definition: NumTraits.h:88
const internal::permut_matrix_product_retval< PermutationDerived, Derived, OnTheRight > operator*(const MatrixBase< Derived > &matrix, const PermutationBase< PermutationDerived > &permutation)
Definition: PermutationMatrix.h:539
Index rows() const
Definition: SparseQR.h:108
void resize(Index newSize)
Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods...
Definition: DenseBase.h:213
const QRMatrixType & matrixR() const
Definition: SparseQR.h:116
void factorize(const MatrixType &mat)
Performs the numerical QR factorization of the input matrix.
Definition: SparseQR.h:323
Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor Matrix...
Definition: EigenBase.h:26
Definition: SparseQR.h:19
Definition: ReturnByValue.h:50
int coletree(const MatrixType &mat, IndexVector &parent, IndexVector &firstRowElt, typename MatrixType::Index *perm=0)
Compute the column elimination tree of a sparse matrix.
Definition: SparseColEtree.h:61
Sparse left-looking rank-revealing QR factorization.
Definition: SparseQR.h:16
Index rows() const
Definition: SparseMatrixBase.h:159
Base class of any sparse matrices or sparse expressions.
Definition: ForwardDeclarations.h:239
Definition: SparseQR.h:17
Definition: SparseQR.h:18
Derived & setZero(Index size)
Resizes to the given size, and sets all coefficients in this expression to zero.
Definition: CwiseNullaryOp.h:515
The inputs are invalid, or the algorithm has been improperly called.
Definition: Constants.h:383
Derived & setConstant(Index size, const Scalar &value)
Resizes to the given size, and sets all coefficients in this expression to the given value...
Definition: CwiseNullaryOp.h:348
Computation was successful.
Definition: Constants.h:376
void analyzePattern(const MatrixType &mat)
Preprocessing step of a QR factorization.
Definition: SparseQR.h:282
Definition: BandTriangularSolver.h:13
Definition: SparseSolve.h:17
Index rank() const
Definition: SparseQR.h:122
const internal::solve_retval< SparseQR, Rhs > solve(const MatrixBase< Rhs > &B) const
Definition: SparseQR.h:207
Definition: ForwardDeclarations.h:125
const PermutationType & colsPermutation() const
Definition: SparseQR.h:152
std::string lastErrorMessage() const
Definition: SparseQR.h:161
ComputationInfo
Enum for reporting the status of a computation.
Definition: Constants.h:374
SparseQR(const MatrixType &mat)
Construct a QR factorization of the matrix mat.
Definition: SparseQR.h:87
Base class for all dense matrices, vectors, and expressions.
Definition: MatrixBase.h:48
Definition: ForwardDeclarations.h:17
void setPivotThreshold(const RealScalar &threshold)
Sets the threshold that is used to determine linearly dependent columns during the factorization...
Definition: SparseQR.h:196
double Scalar
Common scalar type.
Definition: FlexibleKalmanBase.h:48
void compute(const MatrixType &mat)
Computes the QR factorization of the sparse matrix mat.
Definition: SparseQR.h:98