Eigen  3.2.93
ColPivHouseholderQR.h
1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
5 // Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
6 //
7 // This Source Code Form is subject to the terms of the Mozilla
8 // Public License v. 2.0. If a copy of the MPL was not distributed
9 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 
11 #ifndef EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
12 #define EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
13 
14 namespace Eigen {
15 
16 namespace internal {
17 template<typename _MatrixType> struct traits<ColPivHouseholderQR<_MatrixType> >
18  : traits<_MatrixType>
19 {
20  enum { Flags = 0 };
21 };
22 
23 } // end namespace internal
24 
48 template<typename _MatrixType> class ColPivHouseholderQR
49 {
50  public:
51 
52  typedef _MatrixType MatrixType;
53  enum {
54  RowsAtCompileTime = MatrixType::RowsAtCompileTime,
55  ColsAtCompileTime = MatrixType::ColsAtCompileTime,
56  MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
57  MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
58  };
59  typedef typename MatrixType::Scalar Scalar;
60  typedef typename MatrixType::RealScalar RealScalar;
61  // FIXME should be int
62  typedef typename MatrixType::StorageIndex StorageIndex;
63  typedef typename internal::plain_diag_type<MatrixType>::type HCoeffsType;
64  typedef PermutationMatrix<ColsAtCompileTime, MaxColsAtCompileTime> PermutationType;
65  typedef typename internal::plain_row_type<MatrixType, Index>::type IntRowVectorType;
66  typedef typename internal::plain_row_type<MatrixType>::type RowVectorType;
67  typedef typename internal::plain_row_type<MatrixType, RealScalar>::type RealRowVectorType;
68  typedef HouseholderSequence<MatrixType,typename internal::remove_all<typename HCoeffsType::ConjugateReturnType>::type> HouseholderSequenceType;
69  typedef typename MatrixType::PlainObject PlainObject;
70 
71  private:
72 
73  typedef typename PermutationType::StorageIndex PermIndexType;
74 
75  public:
76 
84  : m_qr(),
85  m_hCoeffs(),
86  m_colsPermutation(),
87  m_colsTranspositions(),
88  m_temp(),
89  m_colNormsUpdated(),
90  m_colNormsDirect(),
91  m_isInitialized(false),
92  m_usePrescribedThreshold(false) {}
93 
101  : m_qr(rows, cols),
102  m_hCoeffs((std::min)(rows,cols)),
103  m_colsPermutation(PermIndexType(cols)),
104  m_colsTranspositions(cols),
105  m_temp(cols),
106  m_colNormsUpdated(cols),
107  m_colNormsDirect(cols),
108  m_isInitialized(false),
109  m_usePrescribedThreshold(false) {}
110 
123  template<typename InputType>
125  : m_qr(matrix.rows(), matrix.cols()),
126  m_hCoeffs((std::min)(matrix.rows(),matrix.cols())),
127  m_colsPermutation(PermIndexType(matrix.cols())),
128  m_colsTranspositions(matrix.cols()),
129  m_temp(matrix.cols()),
130  m_colNormsUpdated(matrix.cols()),
131  m_colNormsDirect(matrix.cols()),
132  m_isInitialized(false),
133  m_usePrescribedThreshold(false)
134  {
135  compute(matrix.derived());
136  }
137 
144  template<typename InputType>
146  : m_qr(matrix.derived()),
147  m_hCoeffs((std::min)(matrix.rows(),matrix.cols())),
148  m_colsPermutation(PermIndexType(matrix.cols())),
149  m_colsTranspositions(matrix.cols()),
150  m_temp(matrix.cols()),
151  m_colNormsUpdated(matrix.cols()),
152  m_colNormsDirect(matrix.cols()),
153  m_isInitialized(false),
154  m_usePrescribedThreshold(false)
155  {
156  computeInPlace();
157  }
158 
176  template<typename Rhs>
178  solve(const MatrixBase<Rhs>& b) const
179  {
180  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
181  return Solve<ColPivHouseholderQR, Rhs>(*this, b.derived());
182  }
183 
184  HouseholderSequenceType householderQ() const;
185  HouseholderSequenceType matrixQ() const
186  {
187  return householderQ();
188  }
189 
192  const MatrixType& matrixQR() const
193  {
194  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
195  return m_qr;
196  }
197 
207  const MatrixType& matrixR() const
208  {
209  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
210  return m_qr;
211  }
212 
213  template<typename InputType>
214  ColPivHouseholderQR& compute(const EigenBase<InputType>& matrix);
215 
217  const PermutationType& colsPermutation() const
218  {
219  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
220  return m_colsPermutation;
221  }
222 
236  typename MatrixType::RealScalar absDeterminant() const;
237 
250  typename MatrixType::RealScalar logAbsDeterminant() const;
251 
258  inline Index rank() const
259  {
260  using std::abs;
261  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
262  RealScalar premultiplied_threshold = abs(m_maxpivot) * threshold();
263  Index result = 0;
264  for(Index i = 0; i < m_nonzero_pivots; ++i)
265  result += (abs(m_qr.coeff(i,i)) > premultiplied_threshold);
266  return result;
267  }
268 
275  inline Index dimensionOfKernel() const
276  {
277  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
278  return cols() - rank();
279  }
280 
288  inline bool isInjective() const
289  {
290  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
291  return rank() == cols();
292  }
293 
301  inline bool isSurjective() const
302  {
303  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
304  return rank() == rows();
305  }
306 
313  inline bool isInvertible() const
314  {
315  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
316  return isInjective() && isSurjective();
317  }
318 
325  {
326  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
327  return Inverse<ColPivHouseholderQR>(*this);
328  }
329 
330  inline Index rows() const { return m_qr.rows(); }
331  inline Index cols() const { return m_qr.cols(); }
332 
337  const HCoeffsType& hCoeffs() const { return m_hCoeffs; }
338 
356  ColPivHouseholderQR& setThreshold(const RealScalar& threshold)
357  {
358  m_usePrescribedThreshold = true;
359  m_prescribedThreshold = threshold;
360  return *this;
361  }
362 
372  {
373  m_usePrescribedThreshold = false;
374  return *this;
375  }
376 
381  RealScalar threshold() const
382  {
383  eigen_assert(m_isInitialized || m_usePrescribedThreshold);
384  return m_usePrescribedThreshold ? m_prescribedThreshold
385  // this formula comes from experimenting (see "LU precision tuning" thread on the list)
386  // and turns out to be identical to Higham's formula used already in LDLt.
387  : NumTraits<Scalar>::epsilon() * RealScalar(m_qr.diagonalSize());
388  }
389 
397  inline Index nonzeroPivots() const
398  {
399  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
400  return m_nonzero_pivots;
401  }
402 
406  RealScalar maxPivot() const { return m_maxpivot; }
407 
415  {
416  eigen_assert(m_isInitialized && "Decomposition is not initialized.");
417  return Success;
418  }
419 
420  #ifndef EIGEN_PARSED_BY_DOXYGEN
421  template<typename RhsType, typename DstType>
422  EIGEN_DEVICE_FUNC
423  void _solve_impl(const RhsType &rhs, DstType &dst) const;
424  #endif
425 
426  protected:
427 
428  friend class CompleteOrthogonalDecomposition<MatrixType>;
429 
430  static void check_template_parameters()
431  {
432  EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar);
433  }
434 
435  void computeInPlace();
436 
437  MatrixType m_qr;
438  HCoeffsType m_hCoeffs;
439  PermutationType m_colsPermutation;
440  IntRowVectorType m_colsTranspositions;
441  RowVectorType m_temp;
442  RealRowVectorType m_colNormsUpdated;
443  RealRowVectorType m_colNormsDirect;
444  bool m_isInitialized, m_usePrescribedThreshold;
445  RealScalar m_prescribedThreshold, m_maxpivot;
446  Index m_nonzero_pivots;
447  Index m_det_pq;
448 };
449 
450 template<typename MatrixType>
451 typename MatrixType::RealScalar ColPivHouseholderQR<MatrixType>::absDeterminant() const
452 {
453  using std::abs;
454  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
455  eigen_assert(m_qr.rows() == m_qr.cols() && "You can't take the determinant of a non-square matrix!");
456  return abs(m_qr.diagonal().prod());
457 }
458 
459 template<typename MatrixType>
460 typename MatrixType::RealScalar ColPivHouseholderQR<MatrixType>::logAbsDeterminant() const
461 {
462  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
463  eigen_assert(m_qr.rows() == m_qr.cols() && "You can't take the determinant of a non-square matrix!");
464  return m_qr.diagonal().cwiseAbs().array().log().sum();
465 }
466 
473 template<typename MatrixType>
474 template<typename InputType>
476 {
477  m_qr = matrix.derived();
478  computeInPlace();
479  return *this;
480 }
481 
482 template<typename MatrixType>
484 {
485  check_template_parameters();
486 
487  // the column permutation is stored as int indices, so just to be sure:
488  eigen_assert(m_qr.cols()<=NumTraits<int>::highest());
489 
490  using std::abs;
491 
492  Index rows = m_qr.rows();
493  Index cols = m_qr.cols();
494  Index size = m_qr.diagonalSize();
495 
496  m_hCoeffs.resize(size);
497 
498  m_temp.resize(cols);
499 
500  m_colsTranspositions.resize(m_qr.cols());
501  Index number_of_transpositions = 0;
502 
503  m_colNormsUpdated.resize(cols);
504  m_colNormsDirect.resize(cols);
505  for (Index k = 0; k < cols; ++k) {
506  // colNormsDirect(k) caches the most recent directly computed norm of
507  // column k.
508  m_colNormsDirect.coeffRef(k) = m_qr.col(k).norm();
509  m_colNormsUpdated.coeffRef(k) = m_colNormsDirect.coeffRef(k);
510  }
511 
512  RealScalar threshold_helper = numext::abs2(m_colNormsUpdated.maxCoeff() * NumTraits<Scalar>::epsilon()) / RealScalar(rows);
513  RealScalar norm_downdate_threshold = numext::sqrt(NumTraits<Scalar>::epsilon());
514 
515  m_nonzero_pivots = size; // the generic case is that in which all pivots are nonzero (invertible case)
516  m_maxpivot = RealScalar(0);
517 
518  for(Index k = 0; k < size; ++k)
519  {
520  // first, we look up in our table m_colNormsUpdated which column has the biggest norm
521  Index biggest_col_index;
522  RealScalar biggest_col_sq_norm = numext::abs2(m_colNormsUpdated.tail(cols-k).maxCoeff(&biggest_col_index));
523  biggest_col_index += k;
524 
525  // Track the number of meaningful pivots but do not stop the decomposition to make
526  // sure that the initial matrix is properly reproduced. See bug 941.
527  if(m_nonzero_pivots==size && biggest_col_sq_norm < threshold_helper * RealScalar(rows-k))
528  m_nonzero_pivots = k;
529 
530  // apply the transposition to the columns
531  m_colsTranspositions.coeffRef(k) = biggest_col_index;
532  if(k != biggest_col_index) {
533  m_qr.col(k).swap(m_qr.col(biggest_col_index));
534  std::swap(m_colNormsUpdated.coeffRef(k), m_colNormsUpdated.coeffRef(biggest_col_index));
535  std::swap(m_colNormsDirect.coeffRef(k), m_colNormsDirect.coeffRef(biggest_col_index));
536  ++number_of_transpositions;
537  }
538 
539  // generate the householder vector, store it below the diagonal
540  RealScalar beta;
541  m_qr.col(k).tail(rows-k).makeHouseholderInPlace(m_hCoeffs.coeffRef(k), beta);
542 
543  // apply the householder transformation to the diagonal coefficient
544  m_qr.coeffRef(k,k) = beta;
545 
546  // remember the maximum absolute value of diagonal coefficients
547  if(abs(beta) > m_maxpivot) m_maxpivot = abs(beta);
548 
549  // apply the householder transformation
550  m_qr.bottomRightCorner(rows-k, cols-k-1)
551  .applyHouseholderOnTheLeft(m_qr.col(k).tail(rows-k-1), m_hCoeffs.coeffRef(k), &m_temp.coeffRef(k+1));
552 
553  // update our table of norms of the columns
554  for (Index j = k + 1; j < cols; ++j) {
555  // The following implements the stable norm downgrade step discussed in
556  // http://www.netlib.org/lapack/lawnspdf/lawn176.pdf
557  // and used in LAPACK routines xGEQPF and xGEQP3.
558  // See lines 278-297 in http://www.netlib.org/lapack/explore-html/dc/df4/sgeqpf_8f_source.html
559  if (m_colNormsUpdated.coeffRef(j) != 0) {
560  RealScalar temp = abs(m_qr.coeffRef(k, j)) / m_colNormsUpdated.coeffRef(j);
561  temp = (RealScalar(1) + temp) * (RealScalar(1) - temp);
562  temp = temp < 0 ? 0 : temp;
563  RealScalar temp2 = temp * numext::abs2(m_colNormsUpdated.coeffRef(j) /
564  m_colNormsDirect.coeffRef(j));
565  if (temp2 <= norm_downdate_threshold) {
566  // The updated norm has become too inaccurate so re-compute the column
567  // norm directly.
568  m_colNormsDirect.coeffRef(j) = m_qr.col(j).tail(rows - k - 1).norm();
569  m_colNormsUpdated.coeffRef(j) = m_colNormsDirect.coeffRef(j);
570  } else {
571  m_colNormsUpdated.coeffRef(j) *= numext::sqrt(temp);
572  }
573  }
574  }
575  }
576 
577  m_colsPermutation.setIdentity(PermIndexType(cols));
578  for(PermIndexType k = 0; k < size/*m_nonzero_pivots*/; ++k)
579  m_colsPermutation.applyTranspositionOnTheRight(k, PermIndexType(m_colsTranspositions.coeff(k)));
580 
581  m_det_pq = (number_of_transpositions%2) ? -1 : 1;
582  m_isInitialized = true;
583 }
584 
585 #ifndef EIGEN_PARSED_BY_DOXYGEN
586 template<typename _MatrixType>
587 template<typename RhsType, typename DstType>
588 void ColPivHouseholderQR<_MatrixType>::_solve_impl(const RhsType &rhs, DstType &dst) const
589 {
590  eigen_assert(rhs.rows() == rows());
591 
592  const Index nonzero_pivots = nonzeroPivots();
593 
594  if(nonzero_pivots == 0)
595  {
596  dst.setZero();
597  return;
598  }
599 
600  typename RhsType::PlainObject c(rhs);
601 
602  // Note that the matrix Q = H_0^* H_1^*... so its inverse is Q^* = (H_0 H_1 ...)^T
603  c.applyOnTheLeft(householderSequence(m_qr, m_hCoeffs)
604  .setLength(nonzero_pivots)
605  .transpose()
606  );
607 
608  m_qr.topLeftCorner(nonzero_pivots, nonzero_pivots)
609  .template triangularView<Upper>()
610  .solveInPlace(c.topRows(nonzero_pivots));
611 
612  for(Index i = 0; i < nonzero_pivots; ++i) dst.row(m_colsPermutation.indices().coeff(i)) = c.row(i);
613  for(Index i = nonzero_pivots; i < cols(); ++i) dst.row(m_colsPermutation.indices().coeff(i)).setZero();
614 }
615 #endif
616 
617 namespace internal {
618 
619 template<typename DstXprType, typename MatrixType, typename Scalar>
620 struct Assignment<DstXprType, Inverse<ColPivHouseholderQR<MatrixType> >, internal::assign_op<Scalar,Scalar>, Dense2Dense>
621 {
622  typedef ColPivHouseholderQR<MatrixType> QrType;
623  typedef Inverse<QrType> SrcXprType;
624  static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op<Scalar,Scalar> &)
625  {
626  dst = src.nestedExpression().solve(MatrixType::Identity(src.rows(), src.cols()));
627  }
628 };
629 
630 } // end namespace internal
631 
635 template<typename MatrixType>
638 {
639  eigen_assert(m_isInitialized && "ColPivHouseholderQR is not initialized.");
640  return HouseholderSequenceType(m_qr, m_hCoeffs.conjugate());
641 }
642 
643 #ifndef __CUDACC__
644 
648 template<typename Derived>
651 {
652  return ColPivHouseholderQR<PlainObject>(eval());
653 }
654 #endif // __CUDACC__
655 
656 } // end namespace Eigen
657 
658 #endif // EIGEN_COLPIVOTINGHOUSEHOLDERQR_H
const PermutationType & colsPermutation() const
Definition: ColPivHouseholderQR.h:217
ColPivHouseholderQR(EigenBase< InputType > &matrix)
Constructs a QR factorization from a given matrix.
Definition: ColPivHouseholderQR.h:145
Index nonzeroPivots() const
Definition: ColPivHouseholderQR.h:397
const Inverse< ColPivHouseholderQR > inverse() const
Definition: ColPivHouseholderQR.h:324
bool isInjective() const
Definition: ColPivHouseholderQR.h:288
ColPivHouseholderQR()
Default Constructor.
Definition: ColPivHouseholderQR.h:83
ColPivHouseholderQR(Index rows, Index cols)
Default Constructor with memory preallocation.
Definition: ColPivHouseholderQR.h:100
const Solve< ColPivHouseholderQR, Rhs > solve(const MatrixBase< Rhs > &b) const
Definition: ColPivHouseholderQR.h:178
MatrixType::RealScalar logAbsDeterminant() const
Definition: ColPivHouseholderQR.h:460
Index rank() const
Definition: ColPivHouseholderQR.h:258
bool isInvertible() const
Definition: ColPivHouseholderQR.h:313
Namespace containing all symbols from the Eigen library.
Definition: Core:271
Definition: Half.h:502
Holds information about the various numeric (i.e. scalar) types allowed by Eigen. ...
Definition: NumTraits.h:167
Derived & derived()
Definition: EigenBase.h:44
Complete orthogonal decomposition (COD) of a matrix.
Definition: ForwardDeclarations.h:257
HouseholderSequence< VectorsType, CoeffsType > householderSequence(const VectorsType &v, const CoeffsType &h)
Convenience function for constructing a Householder sequence.
Definition: HouseholderSequence.h:451
ComputationInfo info() const
Reports whether the QR factorization was succesful.
Definition: ColPivHouseholderQR.h:414
Definition: EigenBase.h:28
Sequence of Householder reflections acting on subspaces with decreasing size.
Definition: ForwardDeclarations.h:262
ColPivHouseholderQR(const EigenBase< InputType > &matrix)
Constructs a QR factorization from a given matrix.
Definition: ColPivHouseholderQR.h:124
Expression of the inverse of another expression.
Definition: Inverse.h:43
ColPivHouseholderQR & setThreshold(Default_t)
Definition: ColPivHouseholderQR.h:371
RealScalar threshold() const
Definition: ColPivHouseholderQR.h:381
const MatrixType & matrixR() const
Definition: ColPivHouseholderQR.h:207
Householder rank-revealing QR decomposition of a matrix with column-pivoting.
Definition: ForwardDeclarations.h:255
const MatrixType & matrixQR() const
Definition: ColPivHouseholderQR.h:192
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: XprHelper.h:35
HouseholderSequenceType householderQ() const
Definition: ColPivHouseholderQR.h:637
const HCoeffsType & hCoeffs() const
Definition: ColPivHouseholderQR.h:337
const ColPivHouseholderQR< PlainObject > colPivHouseholderQr() const
Definition: ColPivHouseholderQR.h:650
Definition: Constants.h:432
ColPivHouseholderQR & setThreshold(const RealScalar &threshold)
Definition: ColPivHouseholderQR.h:356
RealScalar maxPivot() const
Definition: ColPivHouseholderQR.h:406
const Eigen::CwiseUnaryOp< Eigen::internal::scalar_abs_op< typename Derived::Scalar >, const Derived > abs(const Eigen::ArrayBase< Derived > &x)
Definition: Eigen_Colamd.h:50
MatrixType::RealScalar absDeterminant() const
Definition: ColPivHouseholderQR.h:451
bool isSurjective() const
Definition: ColPivHouseholderQR.h:301
Pseudo expression representing a solving operation.
Definition: Solve.h:62
ComputationInfo
Definition: Constants.h:430
Base class for all dense matrices, vectors, and expressions.
Definition: MatrixBase.h:48
Index dimensionOfKernel() const
Definition: ColPivHouseholderQR.h:275