11 #ifndef EIGEN_SPARSE_QR_H
12 #define EIGEN_SPARSE_QR_H
16 template<
typename MatrixType,
typename OrderingType>
class SparseQR;
17 template<
typename SparseQRType>
struct SparseQRMatrixQReturnType;
18 template<
typename SparseQRType>
struct SparseQRMatrixQTransposeReturnType;
19 template<
typename SparseQRType,
typename Derived>
struct SparseQR_QProduct;
21 template <
typename SparseQRType>
struct traits<SparseQRMatrixQReturnType<SparseQRType> >
23 typedef typename SparseQRType::MatrixType ReturnType;
24 typedef typename ReturnType::Index Index;
25 typedef typename ReturnType::StorageKind StorageKind;
27 template <
typename SparseQRType>
struct traits<SparseQRMatrixQTransposeReturnType<SparseQRType> >
29 typedef typename SparseQRType::MatrixType ReturnType;
31 template <
typename SparseQRType,
typename Derived>
struct traits<SparseQR_QProduct<SparseQRType, Derived> >
33 typedef typename Derived::PlainObject ReturnType;
64 template<
typename _MatrixType,
typename _OrderingType>
68 typedef _MatrixType MatrixType;
69 typedef _OrderingType OrderingType;
70 typedef typename MatrixType::Scalar Scalar;
71 typedef typename MatrixType::RealScalar RealScalar;
72 typedef typename MatrixType::Index Index;
73 typedef SparseMatrix<Scalar,ColMajor,Index> QRMatrixType;
74 typedef Matrix<Index, Dynamic, 1> IndexVector;
75 typedef Matrix<Scalar, Dynamic, 1> ScalarVector;
76 typedef PermutationMatrix<Dynamic, Dynamic, Index> PermutationType;
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)
108 inline Index
rows()
const {
return m_pmat.
rows(); }
124 eigen_assert(m_isInitialized &&
"The factorization should be called first, use compute()");
125 return m_nonzeropivots;
146 SparseQRMatrixQReturnType<SparseQR>
matrixQ()
const
147 {
return SparseQRMatrixQReturnType<SparseQR>(*this); }
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");
173 typename Dest::PlainObject y, b;
174 y = this->
matrixQ().transpose() * B;
178 y.
resize((std::max)(
cols(),Index(y.rows())),y.cols());
180 y.bottomRows(y.rows()-
rank).setZero();
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");
211 return internal::solve_retval<SparseQR, Rhs>(*
this, B.derived());
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");
218 return internal::sparse_solve_retval<SparseQR, Rhs>(*
this, B.
derived());
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;
267 template <
typename,
typename >
friend struct SparseQR_QProduct;
268 template <
typename >
friend struct SparseQRMatrixQReturnType;
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");
286 typename internal::conditional<MatrixType::IsRowMajor,QRMatrixType,const MatrixType&>::type matCpy(mat);
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);
531 tval(iQ) = Scalar(0.);
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>
578 struct solve_retval<
SparseQR<_MatrixType,OrderingType>, Rhs>
579 : solve_retval_base<SparseQR<_MatrixType,OrderingType>, 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>
590 struct sparse_solve_retval<SparseQR<_MatrixType, OrderingType>, Rhs>
591 : sparse_solve_retval_base<SparseQR<_MatrixType, OrderingType>, Rhs>
593 typedef SparseQR<_MatrixType, OrderingType> Dec;
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>
604 struct SparseQR_QProduct : ReturnByValue<SparseQR_QProduct<SparseQRType, Derived> >
606 typedef typename SparseQRType::QRMatrixType MatrixType;
607 typedef typename SparseQRType::Scalar Scalar;
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++)
630 Scalar tau = Scalar(0);
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--)
646 Scalar tau = Scalar(0);
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>
662 struct SparseQRMatrixQReturnType :
public EigenBase<SparseQRMatrixQReturnType<SparseQRType> >
664 typedef typename SparseQRType::Index Index;
665 typedef typename SparseQRType::Scalar Scalar;
666 typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
667 SparseQRMatrixQReturnType(
const SparseQRType& qr) : m_qr(qr) {}
668 template<
typename Derived>
669 SparseQR_QProduct<SparseQRType, Derived>
operator*(
const MatrixBase<Derived>& other)
671 return SparseQR_QProduct<SparseQRType,Derived>(m_qr,other.derived(),
false);
673 SparseQRMatrixQTransposeReturnType<SparseQRType> adjoint()
const
675 return SparseQRMatrixQTransposeReturnType<SparseQRType>(m_qr);
677 inline Index rows()
const {
return m_qr.rows(); }
678 inline Index cols()
const {
return (std::min)(m_qr.rows(),m_qr.cols()); }
680 SparseQRMatrixQTransposeReturnType<SparseQRType> transpose()
const
682 return SparseQRMatrixQTransposeReturnType<SparseQRType>(m_qr);
684 template<
typename Dest>
void evalTo(MatrixBase<Dest>& dest)
const
686 dest.derived() = m_qr.matrixQ() * Dest::Identity(m_qr.rows(), m_qr.rows());
688 template<
typename Dest>
void evalTo(SparseMatrixBase<Dest>& dest)
const
690 Dest idMat(m_qr.rows(), m_qr.rows());
693 const_cast<SparseQRType *
>(&m_qr)->sort_matrix_Q();
694 dest.derived() = SparseQR_QProduct<SparseQRType, Dest>(m_qr, idMat,
false);
697 const SparseQRType& m_qr;
700 template<
typename SparseQRType>
701 struct SparseQRMatrixQTransposeReturnType
703 SparseQRMatrixQTransposeReturnType(
const SparseQRType& qr) : m_qr(qr) {}
704 template<
typename Derived>
705 SparseQR_QProduct<SparseQRType,Derived>
operator*(
const MatrixBase<Derived>& other)
707 return SparseQR_QProduct<SparseQRType,Derived>(m_qr,other.derived(),
true);
709 const SparseQRType& m_qr;
Index rows() const
Definition: SparseMatrix.h:119
void resize(Index newSize)
Definition: DenseBase.h:213
const Scalar * data() const
Definition: PlainObjectBase.h:212
std::string lastErrorMessage() const
Definition: SparseQR.h:161
Index cols() const
Definition: SparseMatrix.h:121
Index rank() const
Definition: SparseQR.h:122
void compute(const MatrixType &mat)
Definition: SparseQR.h:98
Holds information about the various numeric (i.e. scalar) types allowed by Eigen. ...
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
void factorize(const MatrixType &mat)
Performs the numerical QR factorization of the input matrix.
Definition: SparseQR.h:323
SparseQRMatrixQReturnType< SparseQR > matrixQ() const
Definition: SparseQR.h:146
int coletree(const MatrixType &mat, IndexVector &parent, IndexVector &firstRowElt, typename MatrixType::Index *perm=0)
Definition: SparseColEtree.h:61
Sparse left-looking rank-revealing QR factorization.
Definition: SparseQR.h:16
Index size() const
Definition: PermutationMatrix.h:114
Base class of any sparse matrices or sparse expressions.
Definition: ForwardDeclarations.h:239
Index rows() const
Definition: SparseQR.h:108
Derived & derived()
Definition: EigenBase.h:34
SparseQR(const MatrixType &mat)
Definition: SparseQR.h:87
ComputationInfo info() const
Reports whether previous computation was successful.
Definition: SparseQR.h:229
Index cols() const
Definition: SparseQR.h:112
Derived & setConstant(Index size, const Scalar &value)
Definition: CwiseNullaryOp.h:348
RowsBlockXpr topRows(Index n)
Definition: DenseBase.h:381
Definition: Constants.h:383
void setPivotThreshold(const RealScalar &threshold)
Definition: SparseQR.h:196
const PermutationType & colsPermutation() const
Definition: SparseQR.h:152
const internal::solve_retval< SparseQR, Rhs > solve(const MatrixBase< Rhs > &B) const
Definition: SparseQR.h:207
const QRMatrixType & matrixR() const
Definition: SparseQR.h:116
void analyzePattern(const MatrixType &mat)
Preprocessing step of a QR factorization.
Definition: SparseQR.h:282
Definition: Constants.h:376
Block< Derived > topLeftCorner(Index cRows, Index cCols)
Definition: SparseMatrixBase.h:157
Index rows() const
Definition: SparseMatrixBase.h:159
ComputationInfo
Definition: Constants.h:374
Base class for all dense matrices, vectors, and expressions.
Definition: MatrixBase.h:48
Derived & setZero(Index size)
Definition: CwiseNullaryOp.h:515