$treeview $search $mathjax
|
Eigen
3.2.3
$projectbrief
|
$projectbrief
|
$searchbox |
00001 // This file is part of Eigen, a lightweight C++ template library 00002 // for linear algebra. 00003 // 00004 // Copyright (C) 2006-2009 Benoit Jacob <jacob.benoit.1@gmail.com> 00005 // 00006 // This Source Code Form is subject to the terms of the Mozilla 00007 // Public License v. 2.0. If a copy of the MPL was not distributed 00008 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 00009 00010 #ifndef EIGEN_LU_H 00011 #define EIGEN_LU_H 00012 00013 namespace Eigen { 00014 00046 template<typename _MatrixType> class FullPivLU 00047 { 00048 public: 00049 typedef _MatrixType MatrixType; 00050 enum { 00051 RowsAtCompileTime = MatrixType::RowsAtCompileTime, 00052 ColsAtCompileTime = MatrixType::ColsAtCompileTime, 00053 Options = MatrixType::Options, 00054 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, 00055 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime 00056 }; 00057 typedef typename MatrixType::Scalar Scalar; 00058 typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; 00059 typedef typename internal::traits<MatrixType>::StorageKind StorageKind; 00060 typedef typename MatrixType::Index Index; 00061 typedef typename internal::plain_row_type<MatrixType, Index>::type IntRowVectorType; 00062 typedef typename internal::plain_col_type<MatrixType, Index>::type IntColVectorType; 00063 typedef PermutationMatrix<ColsAtCompileTime, MaxColsAtCompileTime> PermutationQType; 00064 typedef PermutationMatrix<RowsAtCompileTime, MaxRowsAtCompileTime> PermutationPType; 00065 00072 FullPivLU(); 00073 00080 FullPivLU(Index rows, Index cols); 00081 00087 FullPivLU(const MatrixType& matrix); 00088 00096 FullPivLU& compute(const MatrixType& matrix); 00097 00104 inline const MatrixType& matrixLU() const 00105 { 00106 eigen_assert(m_isInitialized && "LU is not initialized."); 00107 return m_lu; 00108 } 00109 00117 inline Index nonzeroPivots() const 00118 { 00119 eigen_assert(m_isInitialized && "LU is not initialized."); 00120 return m_nonzero_pivots; 00121 } 00122 00126 RealScalar maxPivot() const { return m_maxpivot; } 00127 00132 inline const PermutationPType& permutationP() const 00133 { 00134 eigen_assert(m_isInitialized && "LU is not initialized."); 00135 return m_p; 00136 } 00137 00142 inline const PermutationQType& permutationQ() const 00143 { 00144 eigen_assert(m_isInitialized && "LU is not initialized."); 00145 return m_q; 00146 } 00147 00162 inline const internal::kernel_retval<FullPivLU> kernel() const 00163 { 00164 eigen_assert(m_isInitialized && "LU is not initialized."); 00165 return internal::kernel_retval<FullPivLU>(*this); 00166 } 00167 00187 inline const internal::image_retval<FullPivLU> 00188 image(const MatrixType& originalMatrix) const 00189 { 00190 eigen_assert(m_isInitialized && "LU is not initialized."); 00191 return internal::image_retval<FullPivLU>(*this, originalMatrix); 00192 } 00193 00213 template<typename Rhs> 00214 inline const internal::solve_retval<FullPivLU, Rhs> 00215 solve(const MatrixBase<Rhs>& b) const 00216 { 00217 eigen_assert(m_isInitialized && "LU is not initialized."); 00218 return internal::solve_retval<FullPivLU, Rhs>(*this, b.derived()); 00219 } 00220 00236 typename internal::traits<MatrixType>::Scalar determinant() const; 00237 00255 FullPivLU& setThreshold(const RealScalar& threshold) 00256 { 00257 m_usePrescribedThreshold = true; 00258 m_prescribedThreshold = threshold; 00259 return *this; 00260 } 00261 00270 FullPivLU& setThreshold(Default_t) 00271 { 00272 m_usePrescribedThreshold = false; 00273 return *this; 00274 } 00275 00280 RealScalar threshold() const 00281 { 00282 eigen_assert(m_isInitialized || m_usePrescribedThreshold); 00283 return m_usePrescribedThreshold ? m_prescribedThreshold 00284 // this formula comes from experimenting (see "LU precision tuning" thread on the list) 00285 // and turns out to be identical to Higham's formula used already in LDLt. 00286 : NumTraits<Scalar>::epsilon() * m_lu.diagonalSize(); 00287 } 00288 00295 inline Index rank() const 00296 { 00297 using std::abs; 00298 eigen_assert(m_isInitialized && "LU is not initialized."); 00299 RealScalar premultiplied_threshold = abs(m_maxpivot) * threshold(); 00300 Index result = 0; 00301 for(Index i = 0; i < m_nonzero_pivots; ++i) 00302 result += (abs(m_lu.coeff(i,i)) > premultiplied_threshold); 00303 return result; 00304 } 00305 00312 inline Index dimensionOfKernel() const 00313 { 00314 eigen_assert(m_isInitialized && "LU is not initialized."); 00315 return cols() - rank(); 00316 } 00317 00325 inline bool isInjective() const 00326 { 00327 eigen_assert(m_isInitialized && "LU is not initialized."); 00328 return rank() == cols(); 00329 } 00330 00338 inline bool isSurjective() const 00339 { 00340 eigen_assert(m_isInitialized && "LU is not initialized."); 00341 return rank() == rows(); 00342 } 00343 00350 inline bool isInvertible() const 00351 { 00352 eigen_assert(m_isInitialized && "LU is not initialized."); 00353 return isInjective() && (m_lu.rows() == m_lu.cols()); 00354 } 00355 00363 inline const internal::solve_retval<FullPivLU,typename MatrixType::IdentityReturnType> inverse() const 00364 { 00365 eigen_assert(m_isInitialized && "LU is not initialized."); 00366 eigen_assert(m_lu.rows() == m_lu.cols() && "You can't take the inverse of a non-square matrix!"); 00367 return internal::solve_retval<FullPivLU,typename MatrixType::IdentityReturnType> 00368 (*this, MatrixType::Identity(m_lu.rows(), m_lu.cols())); 00369 } 00370 00371 MatrixType reconstructedMatrix() const; 00372 00373 inline Index rows() const { return m_lu.rows(); } 00374 inline Index cols() const { return m_lu.cols(); } 00375 00376 protected: 00377 MatrixType m_lu; 00378 PermutationPType m_p; 00379 PermutationQType m_q; 00380 IntColVectorType m_rowsTranspositions; 00381 IntRowVectorType m_colsTranspositions; 00382 Index m_det_pq, m_nonzero_pivots; 00383 RealScalar m_maxpivot, m_prescribedThreshold; 00384 bool m_isInitialized, m_usePrescribedThreshold; 00385 }; 00386 00387 template<typename MatrixType> 00388 FullPivLU<MatrixType>::FullPivLU() 00389 : m_isInitialized(false), m_usePrescribedThreshold(false) 00390 { 00391 } 00392 00393 template<typename MatrixType> 00394 FullPivLU<MatrixType>::FullPivLU(Index rows, Index cols) 00395 : m_lu(rows, cols), 00396 m_p(rows), 00397 m_q(cols), 00398 m_rowsTranspositions(rows), 00399 m_colsTranspositions(cols), 00400 m_isInitialized(false), 00401 m_usePrescribedThreshold(false) 00402 { 00403 } 00404 00405 template<typename MatrixType> 00406 FullPivLU<MatrixType>::FullPivLU(const MatrixType& matrix) 00407 : m_lu(matrix.rows(), matrix.cols()), 00408 m_p(matrix.rows()), 00409 m_q(matrix.cols()), 00410 m_rowsTranspositions(matrix.rows()), 00411 m_colsTranspositions(matrix.cols()), 00412 m_isInitialized(false), 00413 m_usePrescribedThreshold(false) 00414 { 00415 compute(matrix); 00416 } 00417 00418 template<typename MatrixType> 00419 FullPivLU<MatrixType>& FullPivLU<MatrixType>::compute(const MatrixType& matrix) 00420 { 00421 // the permutations are stored as int indices, so just to be sure: 00422 eigen_assert(matrix.rows()<=NumTraits<int>::highest() && matrix.cols()<=NumTraits<int>::highest()); 00423 00424 m_isInitialized = true; 00425 m_lu = matrix; 00426 00427 const Index size = matrix.diagonalSize(); 00428 const Index rows = matrix.rows(); 00429 const Index cols = matrix.cols(); 00430 00431 // will store the transpositions, before we accumulate them at the end. 00432 // can't accumulate on-the-fly because that will be done in reverse order for the rows. 00433 m_rowsTranspositions.resize(matrix.rows()); 00434 m_colsTranspositions.resize(matrix.cols()); 00435 Index number_of_transpositions = 0; // number of NONTRIVIAL transpositions, i.e. m_rowsTranspositions[i]!=i 00436 00437 m_nonzero_pivots = size; // the generic case is that in which all pivots are nonzero (invertible case) 00438 m_maxpivot = RealScalar(0); 00439 00440 for(Index k = 0; k < size; ++k) 00441 { 00442 // First, we need to find the pivot. 00443 00444 // biggest coefficient in the remaining bottom-right corner (starting at row k, col k) 00445 Index row_of_biggest_in_corner, col_of_biggest_in_corner; 00446 RealScalar biggest_in_corner; 00447 biggest_in_corner = m_lu.bottomRightCorner(rows-k, cols-k) 00448 .cwiseAbs() 00449 .maxCoeff(&row_of_biggest_in_corner, &col_of_biggest_in_corner); 00450 row_of_biggest_in_corner += k; // correct the values! since they were computed in the corner, 00451 col_of_biggest_in_corner += k; // need to add k to them. 00452 00453 if(biggest_in_corner==RealScalar(0)) 00454 { 00455 // before exiting, make sure to initialize the still uninitialized transpositions 00456 // in a sane state without destroying what we already have. 00457 m_nonzero_pivots = k; 00458 for(Index i = k; i < size; ++i) 00459 { 00460 m_rowsTranspositions.coeffRef(i) = i; 00461 m_colsTranspositions.coeffRef(i) = i; 00462 } 00463 break; 00464 } 00465 00466 if(biggest_in_corner > m_maxpivot) m_maxpivot = biggest_in_corner; 00467 00468 // Now that we've found the pivot, we need to apply the row/col swaps to 00469 // bring it to the location (k,k). 00470 00471 m_rowsTranspositions.coeffRef(k) = row_of_biggest_in_corner; 00472 m_colsTranspositions.coeffRef(k) = col_of_biggest_in_corner; 00473 if(k != row_of_biggest_in_corner) { 00474 m_lu.row(k).swap(m_lu.row(row_of_biggest_in_corner)); 00475 ++number_of_transpositions; 00476 } 00477 if(k != col_of_biggest_in_corner) { 00478 m_lu.col(k).swap(m_lu.col(col_of_biggest_in_corner)); 00479 ++number_of_transpositions; 00480 } 00481 00482 // Now that the pivot is at the right location, we update the remaining 00483 // bottom-right corner by Gaussian elimination. 00484 00485 if(k<rows-1) 00486 m_lu.col(k).tail(rows-k-1) /= m_lu.coeff(k,k); 00487 if(k<size-1) 00488 m_lu.block(k+1,k+1,rows-k-1,cols-k-1).noalias() -= m_lu.col(k).tail(rows-k-1) * m_lu.row(k).tail(cols-k-1); 00489 } 00490 00491 // the main loop is over, we still have to accumulate the transpositions to find the 00492 // permutations P and Q 00493 00494 m_p.setIdentity(rows); 00495 for(Index k = size-1; k >= 0; --k) 00496 m_p.applyTranspositionOnTheRight(k, m_rowsTranspositions.coeff(k)); 00497 00498 m_q.setIdentity(cols); 00499 for(Index k = 0; k < size; ++k) 00500 m_q.applyTranspositionOnTheRight(k, m_colsTranspositions.coeff(k)); 00501 00502 m_det_pq = (number_of_transpositions%2) ? -1 : 1; 00503 return *this; 00504 } 00505 00506 template<typename MatrixType> 00507 typename internal::traits<MatrixType>::Scalar FullPivLU<MatrixType>::determinant() const 00508 { 00509 eigen_assert(m_isInitialized && "LU is not initialized."); 00510 eigen_assert(m_lu.rows() == m_lu.cols() && "You can't take the determinant of a non-square matrix!"); 00511 return Scalar(m_det_pq) * Scalar(m_lu.diagonal().prod()); 00512 } 00513 00517 template<typename MatrixType> 00518 MatrixType FullPivLU<MatrixType>::reconstructedMatrix() const 00519 { 00520 eigen_assert(m_isInitialized && "LU is not initialized."); 00521 const Index smalldim = (std::min)(m_lu.rows(), m_lu.cols()); 00522 // LU 00523 MatrixType res(m_lu.rows(),m_lu.cols()); 00524 // FIXME the .toDenseMatrix() should not be needed... 00525 res = m_lu.leftCols(smalldim) 00526 .template triangularView<UnitLower>().toDenseMatrix() 00527 * m_lu.topRows(smalldim) 00528 .template triangularView<Upper>().toDenseMatrix(); 00529 00530 // P^{-1}(LU) 00531 res = m_p.inverse() * res; 00532 00533 // (P^{-1}LU)Q^{-1} 00534 res = res * m_q.inverse(); 00535 00536 return res; 00537 } 00538 00539 /********* Implementation of kernel() **************************************************/ 00540 00541 namespace internal { 00542 template<typename _MatrixType> 00543 struct kernel_retval<FullPivLU<_MatrixType> > 00544 : kernel_retval_base<FullPivLU<_MatrixType> > 00545 { 00546 EIGEN_MAKE_KERNEL_HELPERS(FullPivLU<_MatrixType>) 00547 00548 enum { MaxSmallDimAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED( 00549 MatrixType::MaxColsAtCompileTime, 00550 MatrixType::MaxRowsAtCompileTime) 00551 }; 00552 00553 template<typename Dest> void evalTo(Dest& dst) const 00554 { 00555 using std::abs; 00556 const Index cols = dec().matrixLU().cols(), dimker = cols - rank(); 00557 if(dimker == 0) 00558 { 00559 // The Kernel is just {0}, so it doesn't have a basis properly speaking, but let's 00560 // avoid crashing/asserting as that depends on floating point calculations. Let's 00561 // just return a single column vector filled with zeros. 00562 dst.setZero(); 00563 return; 00564 } 00565 00566 /* Let us use the following lemma: 00567 * 00568 * Lemma: If the matrix A has the LU decomposition PAQ = LU, 00569 * then Ker A = Q(Ker U). 00570 * 00571 * Proof: trivial: just keep in mind that P, Q, L are invertible. 00572 */ 00573 00574 /* Thus, all we need to do is to compute Ker U, and then apply Q. 00575 * 00576 * U is upper triangular, with eigenvalues sorted so that any zeros appear at the end. 00577 * Thus, the diagonal of U ends with exactly 00578 * dimKer zero's. Let us use that to construct dimKer linearly 00579 * independent vectors in Ker U. 00580 */ 00581 00582 Matrix<Index, Dynamic, 1, 0, MaxSmallDimAtCompileTime, 1> pivots(rank()); 00583 RealScalar premultiplied_threshold = dec().maxPivot() * dec().threshold(); 00584 Index p = 0; 00585 for(Index i = 0; i < dec().nonzeroPivots(); ++i) 00586 if(abs(dec().matrixLU().coeff(i,i)) > premultiplied_threshold) 00587 pivots.coeffRef(p++) = i; 00588 eigen_internal_assert(p == rank()); 00589 00590 // we construct a temporaty trapezoid matrix m, by taking the U matrix and 00591 // permuting the rows and cols to bring the nonnegligible pivots to the top of 00592 // the main diagonal. We need that to be able to apply our triangular solvers. 00593 // FIXME when we get triangularView-for-rectangular-matrices, this can be simplified 00594 Matrix<typename MatrixType::Scalar, Dynamic, Dynamic, MatrixType::Options, 00595 MaxSmallDimAtCompileTime, MatrixType::MaxColsAtCompileTime> 00596 m(dec().matrixLU().block(0, 0, rank(), cols)); 00597 for(Index i = 0; i < rank(); ++i) 00598 { 00599 if(i) m.row(i).head(i).setZero(); 00600 m.row(i).tail(cols-i) = dec().matrixLU().row(pivots.coeff(i)).tail(cols-i); 00601 } 00602 m.block(0, 0, rank(), rank()); 00603 m.block(0, 0, rank(), rank()).template triangularView<StrictlyLower>().setZero(); 00604 for(Index i = 0; i < rank(); ++i) 00605 m.col(i).swap(m.col(pivots.coeff(i))); 00606 00607 // ok, we have our trapezoid matrix, we can apply the triangular solver. 00608 // notice that the math behind this suggests that we should apply this to the 00609 // negative of the RHS, but for performance we just put the negative sign elsewhere, see below. 00610 m.topLeftCorner(rank(), rank()) 00611 .template triangularView<Upper>().solveInPlace( 00612 m.topRightCorner(rank(), dimker) 00613 ); 00614 00615 // now we must undo the column permutation that we had applied! 00616 for(Index i = rank()-1; i >= 0; --i) 00617 m.col(i).swap(m.col(pivots.coeff(i))); 00618 00619 // see the negative sign in the next line, that's what we were talking about above. 00620 for(Index i = 0; i < rank(); ++i) dst.row(dec().permutationQ().indices().coeff(i)) = -m.row(i).tail(dimker); 00621 for(Index i = rank(); i < cols; ++i) dst.row(dec().permutationQ().indices().coeff(i)).setZero(); 00622 for(Index k = 0; k < dimker; ++k) dst.coeffRef(dec().permutationQ().indices().coeff(rank()+k), k) = Scalar(1); 00623 } 00624 }; 00625 00626 /***** Implementation of image() *****************************************************/ 00627 00628 template<typename _MatrixType> 00629 struct image_retval<FullPivLU<_MatrixType> > 00630 : image_retval_base<FullPivLU<_MatrixType> > 00631 { 00632 EIGEN_MAKE_IMAGE_HELPERS(FullPivLU<_MatrixType>) 00633 00634 enum { MaxSmallDimAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED( 00635 MatrixType::MaxColsAtCompileTime, 00636 MatrixType::MaxRowsAtCompileTime) 00637 }; 00638 00639 template<typename Dest> void evalTo(Dest& dst) const 00640 { 00641 using std::abs; 00642 if(rank() == 0) 00643 { 00644 // The Image is just {0}, so it doesn't have a basis properly speaking, but let's 00645 // avoid crashing/asserting as that depends on floating point calculations. Let's 00646 // just return a single column vector filled with zeros. 00647 dst.setZero(); 00648 return; 00649 } 00650 00651 Matrix<Index, Dynamic, 1, 0, MaxSmallDimAtCompileTime, 1> pivots(rank()); 00652 RealScalar premultiplied_threshold = dec().maxPivot() * dec().threshold(); 00653 Index p = 0; 00654 for(Index i = 0; i < dec().nonzeroPivots(); ++i) 00655 if(abs(dec().matrixLU().coeff(i,i)) > premultiplied_threshold) 00656 pivots.coeffRef(p++) = i; 00657 eigen_internal_assert(p == rank()); 00658 00659 for(Index i = 0; i < rank(); ++i) 00660 dst.col(i) = originalMatrix().col(dec().permutationQ().indices().coeff(pivots.coeff(i))); 00661 } 00662 }; 00663 00664 /***** Implementation of solve() *****************************************************/ 00665 00666 template<typename _MatrixType, typename Rhs> 00667 struct solve_retval<FullPivLU<_MatrixType>, Rhs> 00668 : solve_retval_base<FullPivLU<_MatrixType>, Rhs> 00669 { 00670 EIGEN_MAKE_SOLVE_HELPERS(FullPivLU<_MatrixType>,Rhs) 00671 00672 template<typename Dest> void evalTo(Dest& dst) const 00673 { 00674 /* The decomposition PAQ = LU can be rewritten as A = P^{-1} L U Q^{-1}. 00675 * So we proceed as follows: 00676 * Step 1: compute c = P * rhs. 00677 * Step 2: replace c by the solution x to Lx = c. Exists because L is invertible. 00678 * Step 3: replace c by the solution x to Ux = c. May or may not exist. 00679 * Step 4: result = Q * c; 00680 */ 00681 00682 const Index rows = dec().rows(), cols = dec().cols(), 00683 nonzero_pivots = dec().nonzeroPivots(); 00684 eigen_assert(rhs().rows() == rows); 00685 const Index smalldim = (std::min)(rows, cols); 00686 00687 if(nonzero_pivots == 0) 00688 { 00689 dst.setZero(); 00690 return; 00691 } 00692 00693 typename Rhs::PlainObject c(rhs().rows(), rhs().cols()); 00694 00695 // Step 1 00696 c = dec().permutationP() * rhs(); 00697 00698 // Step 2 00699 dec().matrixLU() 00700 .topLeftCorner(smalldim,smalldim) 00701 .template triangularView<UnitLower>() 00702 .solveInPlace(c.topRows(smalldim)); 00703 if(rows>cols) 00704 { 00705 c.bottomRows(rows-cols) 00706 -= dec().matrixLU().bottomRows(rows-cols) 00707 * c.topRows(cols); 00708 } 00709 00710 // Step 3 00711 dec().matrixLU() 00712 .topLeftCorner(nonzero_pivots, nonzero_pivots) 00713 .template triangularView<Upper>() 00714 .solveInPlace(c.topRows(nonzero_pivots)); 00715 00716 // Step 4 00717 for(Index i = 0; i < nonzero_pivots; ++i) 00718 dst.row(dec().permutationQ().indices().coeff(i)) = c.row(i); 00719 for(Index i = nonzero_pivots; i < dec().matrixLU().cols(); ++i) 00720 dst.row(dec().permutationQ().indices().coeff(i)).setZero(); 00721 } 00722 }; 00723 00724 } // end namespace internal 00725 00726 /******* MatrixBase methods *****************************************************************/ 00727 00734 template<typename Derived> 00735 inline const FullPivLU<typename MatrixBase<Derived>::PlainObject> 00736 MatrixBase<Derived>::fullPivLu() const 00737 { 00738 return FullPivLU<PlainObject>(eval()); 00739 } 00740 00741 } // end namespace Eigen 00742 00743 #endif // EIGEN_LU_H
1.6.1