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

LDLT.h

00001 // This file is part of Eigen, a lightweight C++ template library
00002 // for linear algebra.
00003 //
00004 // Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr>
00005 // Copyright (C) 2009 Keir Mierle <mierle@gmail.com>
00006 // Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
00007 // Copyright (C) 2011 Timothy E. Holy <tim.holy@gmail.com >
00008 //
00009 // This Source Code Form is subject to the terms of the Mozilla
00010 // Public License v. 2.0. If a copy of the MPL was not distributed
00011 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
00012 
00013 #ifndef EIGEN_LDLT_H
00014 #define EIGEN_LDLT_H
00015 
00016 namespace Eigen { 
00017 
00018 namespace internal {
00019   template<typename MatrixType, int UpLo> struct LDLT_Traits;
00020 
00021   // PositiveSemiDef means positive semi-definite and non-zero; same for NegativeSemiDef
00022   enum SignMatrix { PositiveSemiDef, NegativeSemiDef, ZeroSign, Indefinite };
00023 }
00024 
00048 template<typename _MatrixType, int _UpLo> class LDLT
00049 {
00050   public:
00051     typedef _MatrixType MatrixType;
00052     enum {
00053       RowsAtCompileTime = MatrixType::RowsAtCompileTime,
00054       ColsAtCompileTime = MatrixType::ColsAtCompileTime,
00055       Options = MatrixType::Options & ~RowMajorBit, // these are the options for the TmpMatrixType, we need a ColMajor matrix here!
00056       MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
00057       MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
00058       UpLo = _UpLo
00059     };
00060     typedef typename MatrixType::Scalar Scalar;
00061     typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
00062     typedef typename MatrixType::Index Index;
00063     typedef Matrix<Scalar, RowsAtCompileTime, 1, Options, MaxRowsAtCompileTime, 1> TmpMatrixType;
00064 
00065     typedef Transpositions<RowsAtCompileTime, MaxRowsAtCompileTime> TranspositionType;
00066     typedef PermutationMatrix<RowsAtCompileTime, MaxRowsAtCompileTime> PermutationType;
00067 
00068     typedef internal::LDLT_Traits<MatrixType,UpLo> Traits;
00069 
00075     LDLT() 
00076       : m_matrix(), 
00077         m_transpositions(), 
00078         m_sign(internal::ZeroSign),
00079         m_isInitialized(false) 
00080     {}
00081 
00088     LDLT(Index size)
00089       : m_matrix(size, size),
00090         m_transpositions(size),
00091         m_temporary(size),
00092         m_sign(internal::ZeroSign),
00093         m_isInitialized(false)
00094     {}
00095 
00101     LDLT(const MatrixType& matrix)
00102       : m_matrix(matrix.rows(), matrix.cols()),
00103         m_transpositions(matrix.rows()),
00104         m_temporary(matrix.rows()),
00105         m_sign(internal::ZeroSign),
00106         m_isInitialized(false)
00107     {
00108       compute(matrix);
00109     }
00110 
00114     void setZero()
00115     {
00116       m_isInitialized = false;
00117     }
00118 
00120     inline typename Traits::MatrixU matrixU() const
00121     {
00122       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00123       return Traits::getU(m_matrix);
00124     }
00125 
00127     inline typename Traits::MatrixL matrixL() const
00128     {
00129       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00130       return Traits::getL(m_matrix);
00131     }
00132 
00135     inline const TranspositionType& transpositionsP() const
00136     {
00137       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00138       return m_transpositions;
00139     }
00140 
00142     inline Diagonal<const MatrixType> vectorD() const
00143     {
00144       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00145       return m_matrix.diagonal();
00146     }
00147 
00149     inline bool isPositive() const
00150     {
00151       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00152       return m_sign == internal::PositiveSemiDef || m_sign == internal::ZeroSign;
00153     }
00154     
00155     #ifdef EIGEN2_SUPPORT
00156     inline bool isPositiveDefinite() const
00157     {
00158       return isPositive();
00159     }
00160     #endif
00161 
00163     inline bool isNegative(void) const
00164     {
00165       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00166       return m_sign == internal::NegativeSemiDef || m_sign == internal::ZeroSign;
00167     }
00168 
00184     template<typename Rhs>
00185     inline const internal::solve_retval<LDLT, Rhs>
00186     solve(const MatrixBase<Rhs>& b) const
00187     {
00188       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00189       eigen_assert(m_matrix.rows()==b.rows()
00190                 && "LDLT::solve(): invalid number of rows of the right hand side matrix b");
00191       return internal::solve_retval<LDLT, Rhs>(*this, b.derived());
00192     }
00193 
00194     #ifdef EIGEN2_SUPPORT
00195     template<typename OtherDerived, typename ResultType>
00196     bool solve(const MatrixBase<OtherDerived>& b, ResultType *result) const
00197     {
00198       *result = this->solve(b);
00199       return true;
00200     }
00201     #endif
00202 
00203     template<typename Derived>
00204     bool solveInPlace(MatrixBase<Derived> &bAndX) const;
00205 
00206     LDLT& compute(const MatrixType& matrix);
00207 
00208     template <typename Derived>
00209     LDLT& rankUpdate(const MatrixBase<Derived>& w, const RealScalar& alpha=1);
00210 
00215     inline const MatrixType& matrixLDLT() const
00216     {
00217       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00218       return m_matrix;
00219     }
00220 
00221     MatrixType reconstructedMatrix() const;
00222 
00223     inline Index rows() const { return m_matrix.rows(); }
00224     inline Index cols() const { return m_matrix.cols(); }
00225 
00231     ComputationInfo info() const
00232     {
00233       eigen_assert(m_isInitialized && "LDLT is not initialized.");
00234       return Success;
00235     }
00236 
00237   protected:
00238 
00245     MatrixType m_matrix;
00246     TranspositionType m_transpositions;
00247     TmpMatrixType m_temporary;
00248     internal::SignMatrix m_sign;
00249     bool m_isInitialized;
00250 };
00251 
00252 namespace internal {
00253 
00254 template<int UpLo> struct ldlt_inplace;
00255 
00256 template<> struct ldlt_inplace<Lower>
00257 {
00258   template<typename MatrixType, typename TranspositionType, typename Workspace>
00259   static bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign)
00260   {
00261     using std::abs;
00262     typedef typename MatrixType::Scalar Scalar;
00263     typedef typename MatrixType::RealScalar RealScalar;
00264     typedef typename MatrixType::Index Index;
00265     eigen_assert(mat.rows()==mat.cols());
00266     const Index size = mat.rows();
00267 
00268     if (size <= 1)
00269     {
00270       transpositions.setIdentity();
00271       if (numext::real(mat.coeff(0,0)) > 0) sign = PositiveSemiDef;
00272       else if (numext::real(mat.coeff(0,0)) < 0) sign = NegativeSemiDef;
00273       else sign = ZeroSign;
00274       return true;
00275     }
00276 
00277     for (Index k = 0; k < size; ++k)
00278     {
00279       // Find largest diagonal element
00280       Index index_of_biggest_in_corner;
00281       mat.diagonal().tail(size-k).cwiseAbs().maxCoeff(&index_of_biggest_in_corner);
00282       index_of_biggest_in_corner += k;
00283 
00284       transpositions.coeffRef(k) = index_of_biggest_in_corner;
00285       if(k != index_of_biggest_in_corner)
00286       {
00287         // apply the transposition while taking care to consider only
00288         // the lower triangular part
00289         Index s = size-index_of_biggest_in_corner-1; // trailing size after the biggest element
00290         mat.row(k).head(k).swap(mat.row(index_of_biggest_in_corner).head(k));
00291         mat.col(k).tail(s).swap(mat.col(index_of_biggest_in_corner).tail(s));
00292         std::swap(mat.coeffRef(k,k),mat.coeffRef(index_of_biggest_in_corner,index_of_biggest_in_corner));
00293         for(int i=k+1;i<index_of_biggest_in_corner;++i)
00294         {
00295           Scalar tmp = mat.coeffRef(i,k);
00296           mat.coeffRef(i,k) = numext::conj(mat.coeffRef(index_of_biggest_in_corner,i));
00297           mat.coeffRef(index_of_biggest_in_corner,i) = numext::conj(tmp);
00298         }
00299         if(NumTraits<Scalar>::IsComplex)
00300           mat.coeffRef(index_of_biggest_in_corner,k) = numext::conj(mat.coeff(index_of_biggest_in_corner,k));
00301       }
00302 
00303       // partition the matrix:
00304       //       A00 |  -  |  -
00305       // lu  = A10 | A11 |  -
00306       //       A20 | A21 | A22
00307       Index rs = size - k - 1;
00308       Block<MatrixType,Dynamic,1> A21(mat,k+1,k,rs,1);
00309       Block<MatrixType,1,Dynamic> A10(mat,k,0,1,k);
00310       Block<MatrixType,Dynamic,Dynamic> A20(mat,k+1,0,rs,k);
00311 
00312       if(k>0)
00313       {
00314         temp.head(k) = mat.diagonal().real().head(k).asDiagonal() * A10.adjoint();
00315         mat.coeffRef(k,k) -= (A10 * temp.head(k)).value();
00316         if(rs>0)
00317           A21.noalias() -= A20 * temp.head(k);
00318       }
00319       
00320       // In some previous versions of Eigen (e.g., 3.2.1), the scaling was omitted if the pivot
00321       // was smaller than the cutoff value. However, soince LDLT is not rank-revealing
00322       // we should only make sure we do not introduce INF or NaN values.
00323       // LAPACK also uses 0 as the cutoff value.
00324       RealScalar realAkk = numext::real(mat.coeffRef(k,k));
00325       if((rs>0) && (abs(realAkk) > RealScalar(0)))
00326         A21 /= realAkk;
00327 
00328       if (sign == PositiveSemiDef) {
00329         if (realAkk < 0) sign = Indefinite;
00330       } else if (sign == NegativeSemiDef) {
00331         if (realAkk > 0) sign = Indefinite;
00332       } else if (sign == ZeroSign) {
00333         if (realAkk > 0) sign = PositiveSemiDef;
00334         else if (realAkk < 0) sign = NegativeSemiDef;
00335       }
00336     }
00337 
00338     return true;
00339   }
00340 
00341   // Reference for the algorithm: Davis and Hager, "Multiple Rank
00342   // Modifications of a Sparse Cholesky Factorization" (Algorithm 1)
00343   // Trivial rearrangements of their computations (Timothy E. Holy)
00344   // allow their algorithm to work for rank-1 updates even if the
00345   // original matrix is not of full rank.
00346   // Here only rank-1 updates are implemented, to reduce the
00347   // requirement for intermediate storage and improve accuracy
00348   template<typename MatrixType, typename WDerived>
00349   static bool updateInPlace(MatrixType& mat, MatrixBase<WDerived>& w, const typename MatrixType::RealScalar& sigma=1)
00350   {
00351     using numext::isfinite;
00352     typedef typename MatrixType::Scalar Scalar;
00353     typedef typename MatrixType::RealScalar RealScalar;
00354     typedef typename MatrixType::Index Index;
00355 
00356     const Index size = mat.rows();
00357     eigen_assert(mat.cols() == size && w.size()==size);
00358 
00359     RealScalar alpha = 1;
00360 
00361     // Apply the update
00362     for (Index j = 0; j < size; j++)
00363     {
00364       // Check for termination due to an original decomposition of low-rank
00365       if (!(isfinite)(alpha))
00366         break;
00367 
00368       // Update the diagonal terms
00369       RealScalar dj = numext::real(mat.coeff(j,j));
00370       Scalar wj = w.coeff(j);
00371       RealScalar swj2 = sigma*numext::abs2(wj);
00372       RealScalar gamma = dj*alpha + swj2;
00373 
00374       mat.coeffRef(j,j) += swj2/alpha;
00375       alpha += swj2/dj;
00376 
00377 
00378       // Update the terms of L
00379       Index rs = size-j-1;
00380       w.tail(rs) -= wj * mat.col(j).tail(rs);
00381       if(gamma != 0)
00382         mat.col(j).tail(rs) += (sigma*numext::conj(wj)/gamma)*w.tail(rs);
00383     }
00384     return true;
00385   }
00386 
00387   template<typename MatrixType, typename TranspositionType, typename Workspace, typename WType>
00388   static bool update(MatrixType& mat, const TranspositionType& transpositions, Workspace& tmp, const WType& w, const typename MatrixType::RealScalar& sigma=1)
00389   {
00390     // Apply the permutation to the input w
00391     tmp = transpositions * w;
00392 
00393     return ldlt_inplace<Lower>::updateInPlace(mat,tmp,sigma);
00394   }
00395 };
00396 
00397 template<> struct ldlt_inplace<Upper>
00398 {
00399   template<typename MatrixType, typename TranspositionType, typename Workspace>
00400   static EIGEN_STRONG_INLINE bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign)
00401   {
00402     Transpose<MatrixType> matt(mat);
00403     return ldlt_inplace<Lower>::unblocked(matt, transpositions, temp, sign);
00404   }
00405 
00406   template<typename MatrixType, typename TranspositionType, typename Workspace, typename WType>
00407   static EIGEN_STRONG_INLINE bool update(MatrixType& mat, TranspositionType& transpositions, Workspace& tmp, WType& w, const typename MatrixType::RealScalar& sigma=1)
00408   {
00409     Transpose<MatrixType> matt(mat);
00410     return ldlt_inplace<Lower>::update(matt, transpositions, tmp, w.conjugate(), sigma);
00411   }
00412 };
00413 
00414 template<typename MatrixType> struct LDLT_Traits<MatrixType,Lower>
00415 {
00416   typedef const TriangularView<const MatrixType, UnitLower> MatrixL;
00417   typedef const TriangularView<const typename MatrixType::AdjointReturnType, UnitUpper> MatrixU;
00418   static inline MatrixL getL(const MatrixType& m) { return m; }
00419   static inline MatrixU getU(const MatrixType& m) { return m.adjoint(); }
00420 };
00421 
00422 template<typename MatrixType> struct LDLT_Traits<MatrixType,Upper>
00423 {
00424   typedef const TriangularView<const typename MatrixType::AdjointReturnType, UnitLower> MatrixL;
00425   typedef const TriangularView<const MatrixType, UnitUpper> MatrixU;
00426   static inline MatrixL getL(const MatrixType& m) { return m.adjoint(); }
00427   static inline MatrixU getU(const MatrixType& m) { return m; }
00428 };
00429 
00430 } // end namespace internal
00431 
00434 template<typename MatrixType, int _UpLo>
00435 LDLT<MatrixType,_UpLo>& LDLT<MatrixType,_UpLo>::compute(const MatrixType& a)
00436 {
00437   eigen_assert(a.rows()==a.cols());
00438   const Index size = a.rows();
00439 
00440   m_matrix = a;
00441 
00442   m_transpositions.resize(size);
00443   m_isInitialized = false;
00444   m_temporary.resize(size);
00445   m_sign = internal::ZeroSign;
00446 
00447   internal::ldlt_inplace<UpLo>::unblocked(m_matrix, m_transpositions, m_temporary, m_sign);
00448 
00449   m_isInitialized = true;
00450   return *this;
00451 }
00452 
00458 template<typename MatrixType, int _UpLo>
00459 template<typename Derived>
00460 LDLT<MatrixType,_UpLo>& LDLT<MatrixType,_UpLo>::rankUpdate(const MatrixBase<Derived>& w, const typename NumTraits<typename MatrixType::Scalar>::Real& sigma)
00461 {
00462   const Index size = w.rows();
00463   if (m_isInitialized)
00464   {
00465     eigen_assert(m_matrix.rows()==size);
00466   }
00467   else
00468   {    
00469     m_matrix.resize(size,size);
00470     m_matrix.setZero();
00471     m_transpositions.resize(size);
00472     for (Index i = 0; i < size; i++)
00473       m_transpositions.coeffRef(i) = i;
00474     m_temporary.resize(size);
00475     m_sign = sigma>=0 ? internal::PositiveSemiDef : internal::NegativeSemiDef;
00476     m_isInitialized = true;
00477   }
00478 
00479   internal::ldlt_inplace<UpLo>::update(m_matrix, m_transpositions, m_temporary, w, sigma);
00480 
00481   return *this;
00482 }
00483 
00484 namespace internal {
00485 template<typename _MatrixType, int _UpLo, typename Rhs>
00486 struct solve_retval<LDLT<_MatrixType,_UpLo>, Rhs>
00487   : solve_retval_base<LDLT<_MatrixType,_UpLo>, Rhs>
00488 {
00489   typedef LDLT<_MatrixType,_UpLo> LDLTType;
00490   EIGEN_MAKE_SOLVE_HELPERS(LDLTType,Rhs)
00491 
00492   template<typename Dest> void evalTo(Dest& dst) const
00493   {
00494     eigen_assert(rhs().rows() == dec().matrixLDLT().rows());
00495     // dst = P b
00496     dst = dec().transpositionsP() * rhs();
00497 
00498     // dst = L^-1 (P b)
00499     dec().matrixL().solveInPlace(dst);
00500 
00501     // dst = D^-1 (L^-1 P b)
00502     // more precisely, use pseudo-inverse of D (see bug 241)
00503     using std::abs;
00504     using std::max;
00505     typedef typename LDLTType::MatrixType MatrixType;
00506     typedef typename LDLTType::RealScalar RealScalar;
00507     const typename Diagonal<const MatrixType>::RealReturnType vectorD(dec().vectorD());
00508     // In some previous versions, tolerance was set to the max of 1/highest and the maximal diagonal entry * epsilon
00509     // as motivated by LAPACK's xGELSS:
00510     // RealScalar tolerance = (max)(vectorD.array().abs().maxCoeff() *NumTraits<RealScalar>::epsilon(),RealScalar(1) / NumTraits<RealScalar>::highest());
00511     // However, LDLT is not rank revealing, and so adjusting the tolerance wrt to the highest
00512     // diagonal element is not well justified and to numerical issues in some cases.
00513     // Moreover, Lapack's xSYTRS routines use 0 for the tolerance.
00514     RealScalar tolerance = RealScalar(1) / NumTraits<RealScalar>::highest();
00515     
00516     for (Index i = 0; i < vectorD.size(); ++i) {
00517       if(abs(vectorD(i)) > tolerance)
00518         dst.row(i) /= vectorD(i);
00519       else
00520         dst.row(i).setZero();
00521     }
00522 
00523     // dst = L^-T (D^-1 L^-1 P b)
00524     dec().matrixU().solveInPlace(dst);
00525 
00526     // dst = P^-1 (L^-T D^-1 L^-1 P b) = A^-1 b
00527     dst = dec().transpositionsP().transpose() * dst;
00528   }
00529 };
00530 }
00531 
00545 template<typename MatrixType,int _UpLo>
00546 template<typename Derived>
00547 bool LDLT<MatrixType,_UpLo>::solveInPlace(MatrixBase<Derived> &bAndX) const
00548 {
00549   eigen_assert(m_isInitialized && "LDLT is not initialized.");
00550   eigen_assert(m_matrix.rows() == bAndX.rows());
00551 
00552   bAndX = this->solve(bAndX);
00553 
00554   return true;
00555 }
00556 
00560 template<typename MatrixType, int _UpLo>
00561 MatrixType LDLT<MatrixType,_UpLo>::reconstructedMatrix() const
00562 {
00563   eigen_assert(m_isInitialized && "LDLT is not initialized.");
00564   const Index size = m_matrix.rows();
00565   MatrixType res(size,size);
00566 
00567   // P
00568   res.setIdentity();
00569   res = transpositionsP() * res;
00570   // L^* P
00571   res = matrixU() * res;
00572   // D(L^*P)
00573   res = vectorD().real().asDiagonal() * res;
00574   // L(DL^*P)
00575   res = matrixL() * res;
00576   // P^T (LDL^*P)
00577   res = transpositionsP().transpose() * res;
00578 
00579   return res;
00580 }
00581 
00585 template<typename MatrixType, unsigned int UpLo>
00586 inline const LDLT<typename SelfAdjointView<MatrixType, UpLo>::PlainObject, UpLo>
00587 SelfAdjointView<MatrixType, UpLo>::ldlt() const
00588 {
00589   return LDLT<PlainObject,UpLo>(m_matrix);
00590 }
00591 
00595 template<typename Derived>
00596 inline const LDLT<typename MatrixBase<Derived>::PlainObject>
00597 MatrixBase<Derived>::ldlt() const
00598 {
00599   return LDLT<PlainObject>(derived());
00600 }
00601 
00602 } // end namespace Eigen
00603 
00604 #endif // EIGEN_LDLT_H