$treeview $search $mathjax
Eigen  3.2.3
$projectbrief
$projectbrief
$searchbox

FullPivHouseholderQR.h

00001 // This file is part of Eigen, a lightweight C++ template library
00002 // for linear algebra.
00003 //
00004 // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
00005 // Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
00006 //
00007 // This Source Code Form is subject to the terms of the Mozilla
00008 // Public License v. 2.0. If a copy of the MPL was not distributed
00009 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
00010 
00011 #ifndef EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H
00012 #define EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H
00013 
00014 namespace Eigen { 
00015 
00016 namespace internal {
00017 
00018 template<typename MatrixType> struct FullPivHouseholderQRMatrixQReturnType;
00019 
00020 template<typename MatrixType>
00021 struct traits<FullPivHouseholderQRMatrixQReturnType<MatrixType> >
00022 {
00023   typedef typename MatrixType::PlainObject ReturnType;
00024 };
00025 
00026 }
00027 
00049 template<typename _MatrixType> class FullPivHouseholderQR
00050 {
00051   public:
00052 
00053     typedef _MatrixType MatrixType;
00054     enum {
00055       RowsAtCompileTime = MatrixType::RowsAtCompileTime,
00056       ColsAtCompileTime = MatrixType::ColsAtCompileTime,
00057       Options = MatrixType::Options,
00058       MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
00059       MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
00060     };
00061     typedef typename MatrixType::Scalar Scalar;
00062     typedef typename MatrixType::RealScalar RealScalar;
00063     typedef typename MatrixType::Index Index;
00064     typedef internal::FullPivHouseholderQRMatrixQReturnType<MatrixType> MatrixQReturnType;
00065     typedef typename internal::plain_diag_type<MatrixType>::type HCoeffsType;
00066     typedef Matrix<Index, 1,
00067                    EIGEN_SIZE_MIN_PREFER_DYNAMIC(ColsAtCompileTime,RowsAtCompileTime), RowMajor, 1,
00068                    EIGEN_SIZE_MIN_PREFER_FIXED(MaxColsAtCompileTime,MaxRowsAtCompileTime)> IntDiagSizeVectorType;
00069     typedef PermutationMatrix<ColsAtCompileTime, MaxColsAtCompileTime> PermutationType;
00070     typedef typename internal::plain_row_type<MatrixType>::type RowVectorType;
00071     typedef typename internal::plain_col_type<MatrixType>::type ColVectorType;
00072 
00078     FullPivHouseholderQR()
00079       : m_qr(),
00080         m_hCoeffs(),
00081         m_rows_transpositions(),
00082         m_cols_transpositions(),
00083         m_cols_permutation(),
00084         m_temp(),
00085         m_isInitialized(false),
00086         m_usePrescribedThreshold(false) {}
00087 
00094     FullPivHouseholderQR(Index rows, Index cols)
00095       : m_qr(rows, cols),
00096         m_hCoeffs((std::min)(rows,cols)),
00097         m_rows_transpositions((std::min)(rows,cols)),
00098         m_cols_transpositions((std::min)(rows,cols)),
00099         m_cols_permutation(cols),
00100         m_temp(cols),
00101         m_isInitialized(false),
00102         m_usePrescribedThreshold(false) {}
00103 
00116     FullPivHouseholderQR(const MatrixType& matrix)
00117       : m_qr(matrix.rows(), matrix.cols()),
00118         m_hCoeffs((std::min)(matrix.rows(), matrix.cols())),
00119         m_rows_transpositions((std::min)(matrix.rows(), matrix.cols())),
00120         m_cols_transpositions((std::min)(matrix.rows(), matrix.cols())),
00121         m_cols_permutation(matrix.cols()),
00122         m_temp(matrix.cols()),
00123         m_isInitialized(false),
00124         m_usePrescribedThreshold(false)
00125     {
00126       compute(matrix);
00127     }
00128 
00147     template<typename Rhs>
00148     inline const internal::solve_retval<FullPivHouseholderQR, Rhs>
00149     solve(const MatrixBase<Rhs>& b) const
00150     {
00151       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00152       return internal::solve_retval<FullPivHouseholderQR, Rhs>(*this, b.derived());
00153     }
00154 
00157     MatrixQReturnType matrixQ(void) const;
00158 
00161     const MatrixType& matrixQR() const
00162     {
00163       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00164       return m_qr;
00165     }
00166 
00167     FullPivHouseholderQR& compute(const MatrixType& matrix);
00168 
00170     const PermutationType& colsPermutation() const
00171     {
00172       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00173       return m_cols_permutation;
00174     }
00175 
00177     const IntDiagSizeVectorType& rowsTranspositions() const
00178     {
00179       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00180       return m_rows_transpositions;
00181     }
00182 
00196     typename MatrixType::RealScalar absDeterminant() const;
00197 
00210     typename MatrixType::RealScalar logAbsDeterminant() const;
00211 
00218     inline Index rank() const
00219     {
00220       using std::abs;
00221       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00222       RealScalar premultiplied_threshold = abs(m_maxpivot) * threshold();
00223       Index result = 0;
00224       for(Index i = 0; i < m_nonzero_pivots; ++i)
00225         result += (abs(m_qr.coeff(i,i)) > premultiplied_threshold);
00226       return result;
00227     }
00228 
00235     inline Index dimensionOfKernel() const
00236     {
00237       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00238       return cols() - rank();
00239     }
00240 
00248     inline bool isInjective() const
00249     {
00250       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00251       return rank() == cols();
00252     }
00253 
00261     inline bool isSurjective() const
00262     {
00263       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00264       return rank() == rows();
00265     }
00266 
00273     inline bool isInvertible() const
00274     {
00275       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00276       return isInjective() && isSurjective();
00277     }
00278     inline const
00284     internal::solve_retval<FullPivHouseholderQR, typename MatrixType::IdentityReturnType>
00285     inverse() const
00286     {
00287       eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00288       return internal::solve_retval<FullPivHouseholderQR,typename MatrixType::IdentityReturnType>
00289                (*this, MatrixType::Identity(m_qr.rows(), m_qr.cols()));
00290     }
00291 
00292     inline Index rows() const { return m_qr.rows(); }
00293     inline Index cols() const { return m_qr.cols(); }
00294     
00299     const HCoeffsType& hCoeffs() const { return m_hCoeffs; }
00300 
00318     FullPivHouseholderQR& setThreshold(const RealScalar& threshold)
00319     {
00320       m_usePrescribedThreshold = true;
00321       m_prescribedThreshold = threshold;
00322       return *this;
00323     }
00324 
00333     FullPivHouseholderQR& setThreshold(Default_t)
00334     {
00335       m_usePrescribedThreshold = false;
00336       return *this;
00337     }
00338 
00343     RealScalar threshold() const
00344     {
00345       eigen_assert(m_isInitialized || m_usePrescribedThreshold);
00346       return m_usePrescribedThreshold ? m_prescribedThreshold
00347       // this formula comes from experimenting (see "LU precision tuning" thread on the list)
00348       // and turns out to be identical to Higham's formula used already in LDLt.
00349                                       : NumTraits<Scalar>::epsilon() * RealScalar(m_qr.diagonalSize());
00350     }
00351 
00359     inline Index nonzeroPivots() const
00360     {
00361       eigen_assert(m_isInitialized && "LU is not initialized.");
00362       return m_nonzero_pivots;
00363     }
00364 
00368     RealScalar maxPivot() const { return m_maxpivot; }
00369 
00370   protected:
00371     MatrixType m_qr;
00372     HCoeffsType m_hCoeffs;
00373     IntDiagSizeVectorType m_rows_transpositions;
00374     IntDiagSizeVectorType m_cols_transpositions;
00375     PermutationType m_cols_permutation;
00376     RowVectorType m_temp;
00377     bool m_isInitialized, m_usePrescribedThreshold;
00378     RealScalar m_prescribedThreshold, m_maxpivot;
00379     Index m_nonzero_pivots;
00380     RealScalar m_precision;
00381     Index m_det_pq;
00382 };
00383 
00384 template<typename MatrixType>
00385 typename MatrixType::RealScalar FullPivHouseholderQR<MatrixType>::absDeterminant() const
00386 {
00387   using std::abs;
00388   eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00389   eigen_assert(m_qr.rows() == m_qr.cols() && "You can't take the determinant of a non-square matrix!");
00390   return abs(m_qr.diagonal().prod());
00391 }
00392 
00393 template<typename MatrixType>
00394 typename MatrixType::RealScalar FullPivHouseholderQR<MatrixType>::logAbsDeterminant() const
00395 {
00396   eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00397   eigen_assert(m_qr.rows() == m_qr.cols() && "You can't take the determinant of a non-square matrix!");
00398   return m_qr.diagonal().cwiseAbs().array().log().sum();
00399 }
00400 
00407 template<typename MatrixType>
00408 FullPivHouseholderQR<MatrixType>& FullPivHouseholderQR<MatrixType>::compute(const MatrixType& matrix)
00409 {
00410   using std::abs;
00411   Index rows = matrix.rows();
00412   Index cols = matrix.cols();
00413   Index size = (std::min)(rows,cols);
00414 
00415   m_qr = matrix;
00416   m_hCoeffs.resize(size);
00417 
00418   m_temp.resize(cols);
00419 
00420   m_precision = NumTraits<Scalar>::epsilon() * RealScalar(size);
00421 
00422   m_rows_transpositions.resize(size);
00423   m_cols_transpositions.resize(size);
00424   Index number_of_transpositions = 0;
00425 
00426   RealScalar biggest(0);
00427 
00428   m_nonzero_pivots = size; // the generic case is that in which all pivots are nonzero (invertible case)
00429   m_maxpivot = RealScalar(0);
00430 
00431   for (Index k = 0; k < size; ++k)
00432   {
00433     Index row_of_biggest_in_corner, col_of_biggest_in_corner;
00434     RealScalar biggest_in_corner;
00435 
00436     biggest_in_corner = m_qr.bottomRightCorner(rows-k, cols-k)
00437                             .cwiseAbs()
00438                             .maxCoeff(&row_of_biggest_in_corner, &col_of_biggest_in_corner);
00439     row_of_biggest_in_corner += k;
00440     col_of_biggest_in_corner += k;
00441     if(k==0) biggest = biggest_in_corner;
00442 
00443     // if the corner is negligible, then we have less than full rank, and we can finish early
00444     if(internal::isMuchSmallerThan(biggest_in_corner, biggest, m_precision))
00445     {
00446       m_nonzero_pivots = k;
00447       for(Index i = k; i < size; i++)
00448       {
00449         m_rows_transpositions.coeffRef(i) = i;
00450         m_cols_transpositions.coeffRef(i) = i;
00451         m_hCoeffs.coeffRef(i) = Scalar(0);
00452       }
00453       break;
00454     }
00455 
00456     m_rows_transpositions.coeffRef(k) = row_of_biggest_in_corner;
00457     m_cols_transpositions.coeffRef(k) = col_of_biggest_in_corner;
00458     if(k != row_of_biggest_in_corner) {
00459       m_qr.row(k).tail(cols-k).swap(m_qr.row(row_of_biggest_in_corner).tail(cols-k));
00460       ++number_of_transpositions;
00461     }
00462     if(k != col_of_biggest_in_corner) {
00463       m_qr.col(k).swap(m_qr.col(col_of_biggest_in_corner));
00464       ++number_of_transpositions;
00465     }
00466 
00467     RealScalar beta;
00468     m_qr.col(k).tail(rows-k).makeHouseholderInPlace(m_hCoeffs.coeffRef(k), beta);
00469     m_qr.coeffRef(k,k) = beta;
00470 
00471     // remember the maximum absolute value of diagonal coefficients
00472     if(abs(beta) > m_maxpivot) m_maxpivot = abs(beta);
00473 
00474     m_qr.bottomRightCorner(rows-k, cols-k-1)
00475         .applyHouseholderOnTheLeft(m_qr.col(k).tail(rows-k-1), m_hCoeffs.coeffRef(k), &m_temp.coeffRef(k+1));
00476   }
00477 
00478   m_cols_permutation.setIdentity(cols);
00479   for(Index k = 0; k < size; ++k)
00480     m_cols_permutation.applyTranspositionOnTheRight(k, m_cols_transpositions.coeff(k));
00481 
00482   m_det_pq = (number_of_transpositions%2) ? -1 : 1;
00483   m_isInitialized = true;
00484 
00485   return *this;
00486 }
00487 
00488 namespace internal {
00489 
00490 template<typename _MatrixType, typename Rhs>
00491 struct solve_retval<FullPivHouseholderQR<_MatrixType>, Rhs>
00492   : solve_retval_base<FullPivHouseholderQR<_MatrixType>, Rhs>
00493 {
00494   EIGEN_MAKE_SOLVE_HELPERS(FullPivHouseholderQR<_MatrixType>,Rhs)
00495 
00496   template<typename Dest> void evalTo(Dest& dst) const
00497   {
00498     const Index rows = dec().rows(), cols = dec().cols();
00499     eigen_assert(rhs().rows() == rows);
00500 
00501     // FIXME introduce nonzeroPivots() and use it here. and more generally,
00502     // make the same improvements in this dec as in FullPivLU.
00503     if(dec().rank()==0)
00504     {
00505       dst.setZero();
00506       return;
00507     }
00508 
00509     typename Rhs::PlainObject c(rhs());
00510 
00511     Matrix<Scalar,1,Rhs::ColsAtCompileTime> temp(rhs().cols());
00512     for (Index k = 0; k < dec().rank(); ++k)
00513     {
00514       Index remainingSize = rows-k;
00515       c.row(k).swap(c.row(dec().rowsTranspositions().coeff(k)));
00516       c.bottomRightCorner(remainingSize, rhs().cols())
00517        .applyHouseholderOnTheLeft(dec().matrixQR().col(k).tail(remainingSize-1),
00518                                   dec().hCoeffs().coeff(k), &temp.coeffRef(0));
00519     }
00520 
00521     dec().matrixQR()
00522        .topLeftCorner(dec().rank(), dec().rank())
00523        .template triangularView<Upper>()
00524        .solveInPlace(c.topRows(dec().rank()));
00525 
00526     for(Index i = 0; i < dec().rank(); ++i) dst.row(dec().colsPermutation().indices().coeff(i)) = c.row(i);
00527     for(Index i = dec().rank(); i < cols; ++i) dst.row(dec().colsPermutation().indices().coeff(i)).setZero();
00528   }
00529 };
00530 
00537 template<typename MatrixType> struct FullPivHouseholderQRMatrixQReturnType
00538   : public ReturnByValue<FullPivHouseholderQRMatrixQReturnType<MatrixType> >
00539 {
00540 public:
00541   typedef typename MatrixType::Index Index;
00542   typedef typename FullPivHouseholderQR<MatrixType>::IntDiagSizeVectorType IntDiagSizeVectorType;
00543   typedef typename internal::plain_diag_type<MatrixType>::type HCoeffsType;
00544   typedef Matrix<typename MatrixType::Scalar, 1, MatrixType::RowsAtCompileTime, RowMajor, 1,
00545                  MatrixType::MaxRowsAtCompileTime> WorkVectorType;
00546 
00547   FullPivHouseholderQRMatrixQReturnType(const MatrixType&       qr,
00548                                         const HCoeffsType&      hCoeffs,
00549                                         const IntDiagSizeVectorType& rowsTranspositions)
00550     : m_qr(qr),
00551       m_hCoeffs(hCoeffs),
00552       m_rowsTranspositions(rowsTranspositions)
00553       {}
00554 
00555   template <typename ResultType>
00556   void evalTo(ResultType& result) const
00557   {
00558     const Index rows = m_qr.rows();
00559     WorkVectorType workspace(rows);
00560     evalTo(result, workspace);
00561   }
00562 
00563   template <typename ResultType>
00564   void evalTo(ResultType& result, WorkVectorType& workspace) const
00565   {
00566     using numext::conj;
00567     // compute the product H'_0 H'_1 ... H'_n-1,
00568     // where H_k is the k-th Householder transformation I - h_k v_k v_k'
00569     // and v_k is the k-th Householder vector [1,m_qr(k+1,k), m_qr(k+2,k), ...]
00570     const Index rows = m_qr.rows();
00571     const Index cols = m_qr.cols();
00572     const Index size = (std::min)(rows, cols);
00573     workspace.resize(rows);
00574     result.setIdentity(rows, rows);
00575     for (Index k = size-1; k >= 0; k--)
00576     {
00577       result.block(k, k, rows-k, rows-k)
00578             .applyHouseholderOnTheLeft(m_qr.col(k).tail(rows-k-1), conj(m_hCoeffs.coeff(k)), &workspace.coeffRef(k));
00579       result.row(k).swap(result.row(m_rowsTranspositions.coeff(k)));
00580     }
00581   }
00582 
00583     Index rows() const { return m_qr.rows(); }
00584     Index cols() const { return m_qr.rows(); }
00585 
00586 protected:
00587   typename MatrixType::Nested m_qr;
00588   typename HCoeffsType::Nested m_hCoeffs;
00589   typename IntDiagSizeVectorType::Nested m_rowsTranspositions;
00590 };
00591 
00592 } // end namespace internal
00593 
00594 template<typename MatrixType>
00595 inline typename FullPivHouseholderQR<MatrixType>::MatrixQReturnType FullPivHouseholderQR<MatrixType>::matrixQ() const
00596 {
00597   eigen_assert(m_isInitialized && "FullPivHouseholderQR is not initialized.");
00598   return MatrixQReturnType(m_qr, m_hCoeffs, m_rows_transpositions);
00599 }
00600 
00605 template<typename Derived>
00606 const FullPivHouseholderQR<typename MatrixBase<Derived>::PlainObject>
00607 MatrixBase<Derived>::fullPivHouseholderQr() const
00608 {
00609   return FullPivHouseholderQR<PlainObject>(eval());
00610 }
00611 
00612 } // end namespace Eigen
00613 
00614 #endif // EIGEN_FULLPIVOTINGHOUSEHOLDERQR_H