Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
HouseholderQR.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2008-2010 Gael Guennebaud <gael.guennebaud@inria.fr>
5// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
6// Copyright (C) 2010 Vincent Lejeune
7//
8// This Source Code Form is subject to the terms of the Mozilla
9// Public License v. 2.0. If a copy of the MPL was not distributed
10// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
11// SPDX-License-Identifier: MPL-2.0
12
13#ifndef EIGEN_QR_H
14#define EIGEN_QR_H
15
16// IWYU pragma: private
17#include "./InternalHeaderCheck.h"
18
19namespace Eigen {
20
21namespace internal {
22template <typename MatrixType_>
23struct traits<HouseholderQR<MatrixType_>> : traits<MatrixType_> {
24 using XprKind = MatrixXpr;
25 using StorageKind = SolverStorage;
26 using StorageIndex = int;
27 enum { Flags = 0 };
28};
29
30} // end namespace internal
31
76template <typename MatrixType_>
77class HouseholderQR : public SolverBase<HouseholderQR<MatrixType_>> {
78 public:
79 using MatrixType = MatrixType_;
80 using Base = SolverBase<HouseholderQR>;
81 friend class SolverBase<HouseholderQR>;
82
83 EIGEN_GENERIC_PUBLIC_INTERFACE(HouseholderQR)
84 enum {
85 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
86 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
87 };
88 using MatrixQType =
89 Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime, (MatrixType::Flags & RowMajorBit) ? RowMajor : ColMajor,
90 MaxRowsAtCompileTime, MaxRowsAtCompileTime>;
91 using HCoeffsType = typename internal::plain_diag_type<MatrixType>::type;
92 using RowVectorType = typename internal::plain_row_type<MatrixType>::type;
93 using HouseholderSequenceType =
95
103 eigen_assert(m_isInitialized && "HouseHolderQR is not initialized.");
104 return Success;
105 }
106
113 HouseholderQR() : m_qr(), m_hCoeffs(), m_temp(), m_isInitialized(false) {}
114
122 : m_qr(rows, cols), m_hCoeffs((std::min)(rows, cols)), m_temp(cols), m_isInitialized(false) {}
123
136 template <typename InputType>
137 explicit HouseholderQR(const EigenBase<InputType>& matrix)
138 : m_qr(matrix.rows(), matrix.cols()),
139 m_hCoeffs((std::min)(matrix.rows(), matrix.cols())),
140 m_temp(matrix.cols()),
141 m_isInitialized(false) {
142 compute(matrix.derived());
143 }
144
152 template <typename InputType>
154 : m_qr(matrix.derived()),
155 m_hCoeffs((std::min)(matrix.rows(), matrix.cols())),
156 m_temp(matrix.cols()),
157 m_isInitialized(false) {
159 }
160
161#ifdef EIGEN_PARSED_BY_DOXYGEN
176 template <typename Rhs>
178#endif
179
189 HouseholderSequenceType householderQ() const {
190 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
191 return HouseholderSequenceType(m_qr, m_hCoeffs.conjugate());
192 }
193
197 const MatrixType& matrixQR() const {
198 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
199 return m_qr;
200 }
201
202 template <typename InputType>
203 HouseholderQR& compute(const EigenBase<InputType>& matrix) {
204 m_qr.resize(matrix.rows(), matrix.cols());
205 m_qr = matrix.derived();
207 return *this;
208 }
209
225 typename MatrixType::Scalar determinant() const;
226
242 typename MatrixType::RealScalar absDeterminant() const;
243
259 typename MatrixType::RealScalar logAbsDeterminant() const;
260
276 typename MatrixType::Scalar signDeterminant() const;
277
278 inline Index rows() const { return m_qr.rows(); }
279 inline Index cols() const { return m_qr.cols(); }
280
285 const HCoeffsType& hCoeffs() const { return m_hCoeffs; }
286
287#ifndef EIGEN_PARSED_BY_DOXYGEN
288 template <typename RhsType, typename DstType>
289 void _solve_impl(const RhsType& rhs, DstType& dst) const;
290
291 template <bool Conjugate, typename RhsType, typename DstType>
292 void _solve_impl_transposed(const RhsType& rhs, DstType& dst) const;
293#endif
294
295 protected:
296 EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar)
297
299
300 MatrixType m_qr;
301 HCoeffsType m_hCoeffs;
302 RowVectorType m_temp;
303 bool m_isInitialized;
304};
305
306namespace internal {
307
309template <typename HCoeffs, typename Scalar, bool IsComplex>
310struct householder_determinant {
311 static void run(const HCoeffs& hCoeffs, Scalar& out_det) {
312 out_det = Scalar(1);
313 Index size = hCoeffs.rows();
314 for (Index i = 0; i < size; i++) {
315 // For each valid reflection Q_n,
316 // det(Q_n) = - conj(h_n) / h_n
317 // where h_n is the Householder coefficient.
318 if (hCoeffs(i) != Scalar(0)) out_det *= -numext::conj(hCoeffs(i)) / hCoeffs(i);
319 }
320 }
321};
322
324template <typename HCoeffs, typename Scalar>
325struct householder_determinant<HCoeffs, Scalar, false> {
326 static void run(const HCoeffs& hCoeffs, Scalar& out_det) {
327 bool negated = false;
328 Index size = hCoeffs.rows();
329 for (Index i = 0; i < size; i++) {
330 // Each valid reflection negates the determinant.
331 if (hCoeffs(i) != Scalar(0)) negated ^= true;
332 }
333 out_det = negated ? Scalar(-1) : Scalar(1);
334 }
335};
336
337} // end namespace internal
338
339template <typename MatrixType>
340typename MatrixType::Scalar HouseholderQR<MatrixType>::determinant() const {
341 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
342 EIGEN_INTERNAL_ASSERT_SQUARE_MSG(m_qr, "You can't take the determinant of a non-square matrix!");
343 Scalar detQ;
344 internal::householder_determinant<HCoeffsType, Scalar, NumTraits<Scalar>::IsComplex>::run(m_hCoeffs, detQ);
345 internal::scaled_product<Scalar> det = internal::scaled_prod(m_qr.diagonal());
346 det.multiply(detQ);
347 return det.value();
348}
349
350template <typename MatrixType>
351typename MatrixType::RealScalar HouseholderQR<MatrixType>::absDeterminant() const {
352 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
353 EIGEN_INTERNAL_ASSERT_SQUARE_MSG(m_qr, "You can't take the determinant of a non-square matrix!");
354 return internal::scaled_prod(m_qr.diagonal()).abs();
355}
356
357template <typename MatrixType>
358typename MatrixType::RealScalar HouseholderQR<MatrixType>::logAbsDeterminant() const {
359 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
360 EIGEN_INTERNAL_ASSERT_SQUARE_MSG(m_qr, "You can't take the determinant of a non-square matrix!");
361 return internal::log_abs_prod(m_qr.diagonal());
362}
363
364template <typename MatrixType>
365typename MatrixType::Scalar HouseholderQR<MatrixType>::signDeterminant() const {
366 eigen_assert(m_isInitialized && "HouseholderQR is not initialized.");
367 EIGEN_INTERNAL_ASSERT_SQUARE_MSG(m_qr, "You can't take the determinant of a non-square matrix!");
368 Scalar detQ;
369 internal::householder_determinant<HCoeffsType, Scalar, NumTraits<Scalar>::IsComplex>::run(m_hCoeffs, detQ);
370 return detQ * m_qr.diagonal().array().sign().prod();
371}
373namespace internal {
374
376template <typename MatrixQR, typename HCoeffs>
377void householder_qr_inplace_unblocked(MatrixQR& mat, HCoeffs& hCoeffs, typename MatrixQR::Scalar* tempData = 0) {
378 using Scalar = typename MatrixQR::Scalar;
379 using RealScalar = typename MatrixQR::RealScalar;
380 Index rows = mat.rows();
381 Index cols = mat.cols();
382 Index size = (std::min)(rows, cols);
383
384 eigen_assert(hCoeffs.size() == size);
385
387 TempType tempVector;
388 if (tempData == 0) {
389 tempVector.resize(cols);
390 tempData = tempVector.data();
391 }
392
393 for (Index k = 0; k < size; ++k) {
394 Index remainingRows = rows - k;
395 Index remainingCols = cols - k - 1;
396
397 RealScalar beta;
398 mat.col(k).tail(remainingRows).makeHouseholderInPlace(hCoeffs.coeffRef(k), beta);
399 mat.coeffRef(k, k) = beta;
400
401 // apply H to remaining part of mat from the left
402 mat.bottomRightCorner(remainingRows, remainingCols)
403 .applyHouseholderOnTheLeft(mat.col(k).tail(remainingRows - 1), hCoeffs.coeffRef(k), tempData + k + 1);
404 }
405}
406
420template <typename MatrixQR, typename HCoeffs, typename VectorQR>
421void householder_qr_inplace_update(MatrixQR& mat, HCoeffs& hCoeffs, const VectorQR& newColumn,
422 typename MatrixQR::Index k, typename MatrixQR::Scalar* tempData) {
423 using Index = typename MatrixQR::Index;
424 using RealScalar = typename MatrixQR::RealScalar;
425 Index rows = mat.rows();
426
427 eigen_assert(k < mat.cols());
428 eigen_assert(k < rows);
429 EIGEN_INTERNAL_ASSERT_SIZE_MATCHES_COLS(hCoeffs, mat);
430 EIGEN_INTERNAL_ASSERT_SIZE_MATCHES_ROWS(newColumn, mat);
431 eigen_assert(tempData);
432
433 // Store new column in mat at column k
434 mat.col(k) = newColumn;
435 // Apply H = H_1...H_{k-1} on newColumn (skip if k=0)
436 for (Index i = 0; i < k; ++i) {
437 Index remainingRows = rows - i;
438 mat.col(k)
439 .tail(remainingRows)
440 .applyHouseholderOnTheLeft(mat.col(i).tail(remainingRows - 1), hCoeffs.coeffRef(i), tempData + i + 1);
441 }
442 // Construct Householder projector in-place in column k
443 RealScalar beta;
444 mat.col(k).tail(rows - k).makeHouseholderInPlace(hCoeffs.coeffRef(k), beta);
445 mat.coeffRef(k, k) = beta;
446}
447
449template <typename MatrixQR, typename HCoeffs, typename MatrixQRScalar = typename MatrixQR::Scalar,
450 bool InnerStrideIsOne = (MatrixQR::InnerStrideAtCompileTime == 1 && HCoeffs::InnerStrideAtCompileTime == 1)>
451struct householder_qr_inplace_blocked {
452 // This is specialized for LAPACK-supported Scalar types in HouseholderQR_LAPACKE.h
453 static void run(MatrixQR& mat, HCoeffs& hCoeffs, Index maxBlockSize = 32, typename MatrixQR::Scalar* tempData = 0) {
454 using Scalar = typename MatrixQR::Scalar;
455 using BlockType = Block<MatrixQR, Dynamic, Dynamic>;
456
457 Index rows = mat.rows();
458 Index cols = mat.cols();
459 Index size = (std::min)(rows, cols);
460
462 TempType tempVector;
463 if (tempData == 0) {
464 tempVector.resize(cols);
465 tempData = tempVector.data();
466 }
467
468 Index blockSize = (std::min)(maxBlockSize, size);
469
470 Index k = 0;
471 for (k = 0; k < size; k += blockSize) {
472 Index bs = (std::min)(size - k, blockSize); // actual size of the block
473 Index tcols = cols - k - bs; // trailing columns
474 Index brows = rows - k; // rows of the block
475
476 // partition the matrix:
477 // A00 | A01 | A02
478 // mat = A10 | A11 | A12
479 // A20 | A21 | A22
480 // and performs the qr dec of [A11^T A12^T]^T
481 // and update [A21^T A22^T]^T using level 3 operations.
482 // Finally, the algorithm continues on A22
483
484 BlockType A11_21 = mat.block(k, k, brows, bs);
485 Block<HCoeffs, Dynamic, 1> hCoeffsSegment = hCoeffs.segment(k, bs);
486
487 householder_qr_inplace_unblocked(A11_21, hCoeffsSegment, tempData);
488
489 if (tcols) {
490 BlockType A21_22 = mat.block(k, k + bs, brows, tcols);
491 apply_block_householder_on_the_left(A21_22, A11_21, hCoeffsSegment, false); // false == backward
492 }
493 }
494 }
495};
496
509template <typename Scalar>
510Index householder_qr_panel_width(Index rows, Index cols) {
511 const Index size = numext::mini(rows, cols);
512 const double m = double(rows), n = double(cols), s = double(size);
513 if (m * n * s <= 64.0 * 64.0 * 64.0) return size;
514 const double P = m * s - s * s / 2;
515 const double Q = m * n * s - (m + n) * s * s / 2 + s * s * s / 3;
516 const double target = numext::sqrt(3 * Q / P);
517 constexpr Index kPacketSize = packet_traits<Scalar>::size;
518 const Index kWidths[] = {8, 16, 24, 32, 48};
519 Index width = kPacketSize;
520 double distance = NumTraits<double>::highest();
521 for (Index w : kWidths) {
522 const double d = numext::maxi(double(w) / target, target / double(w));
523 if (w % kPacketSize == 0 && d < distance) {
524 width = w;
525 distance = d;
526 }
527 }
528 return width;
529}
530
531} // end namespace internal
532
533#ifndef EIGEN_PARSED_BY_DOXYGEN
534template <typename MatrixType_>
535template <typename RhsType, typename DstType>
536void HouseholderQR<MatrixType_>::_solve_impl(const RhsType& rhs, DstType& dst) const {
537 const Index rank = (std::min)(rows(), cols());
538
539 typename RhsType::PlainObject c(rhs);
540
541 c.applyOnTheLeft(householderQ().setLength(rank).adjoint());
542
543 m_qr.topLeftCorner(rank, rank).template triangularView<Upper>().solveInPlace(c.topRows(rank));
544
545 dst.topRows(rank) = c.topRows(rank);
546 dst.bottomRows(cols() - rank).setZero();
547}
548
549template <typename MatrixType_>
550template <bool Conjugate, typename RhsType, typename DstType>
551void HouseholderQR<MatrixType_>::_solve_impl_transposed(const RhsType& rhs, DstType& dst) const {
552 const Index rank = (std::min)(rows(), cols());
553
554 typename RhsType::PlainObject c(rhs);
555
556 m_qr.topLeftCorner(rank, rank)
557 .template triangularView<Upper>()
558 .transpose()
559 .template conjugateIf<Conjugate>()
560 .solveInPlace(c.topRows(rank));
561
562 dst.topRows(rank) = c.topRows(rank);
563 dst.bottomRows(rows() - rank).setZero();
564
565 dst.applyOnTheLeft(householderQ().setLength(rank).template conjugateIf<!Conjugate>());
566}
567#endif
568
575template <typename MatrixType>
577 Index rows = m_qr.rows();
578 Index cols = m_qr.cols();
579 Index size = (std::min)(rows, cols);
580
581 m_hCoeffs.resize(size);
582
583 m_temp.resize(cols);
584
585 const Index maxBlockSize = internal::householder_qr_panel_width<Scalar>(rows, cols);
586 internal::householder_qr_inplace_blocked<MatrixType, HCoeffsType>::run(m_qr, m_hCoeffs, maxBlockSize, m_temp.data());
587
588 m_isInitialized = true;
589}
590
595template <typename Derived>
599
600} // end namespace Eigen
601
602#endif // EIGEN_QR_H
Expression of a fixed-size or dynamic-size block.
Definition Block.h:111
EvalReturnType eval() const
Definition DenseBase.h:389
typename internal::traits< Derived >::Scalar Scalar
Definition DenseBase.h:63
Householder QR decomposition of a matrix.
Definition HouseholderQR.h:77
MatrixType::Scalar signDeterminant() const
Definition HouseholderQR.h:365
HouseholderQR(Index rows, Index cols)
Default Constructor with memory preallocation.
Definition HouseholderQR.h:121
HouseholderQR(EigenBase< InputType > &matrix)
Constructs a QR factorization from a given matrix.
Definition HouseholderQR.h:153
const HCoeffsType & hCoeffs() const
Definition HouseholderQR.h:285
void computeInPlace()
Definition HouseholderQR.h:576
HouseholderQR(const EigenBase< InputType > &matrix)
Constructs a QR factorization from a given matrix.
Definition HouseholderQR.h:137
Solve< HouseholderQR, Rhs > solve(const MatrixBase< Rhs > &b) const
ComputationInfo info() const
Reports whether the QR factorization was successful.
Definition HouseholderQR.h:102
MatrixType::Scalar determinant() const
Definition HouseholderQR.h:340
HouseholderSequenceType householderQ() const
Definition HouseholderQR.h:189
const MatrixType & matrixQR() const
Definition HouseholderQR.h:197
HouseholderQR()
Default Constructor.
Definition HouseholderQR.h:113
MatrixType::RealScalar absDeterminant() const
Definition HouseholderQR.h:351
MatrixType::RealScalar logAbsDeterminant() const
Definition HouseholderQR.h:358
Sequence of Householder reflections acting on subspaces with decreasing size.
Definition HouseholderSequence.h:155
Base class for all dense matrices, vectors, and expressions.
Definition MatrixBase.h:53
HouseholderQR< PlainObject > householderQr() const
Definition HouseholderQR.h:596
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
Pseudo expression representing a solving operation.
Definition Solve.h:63
constexpr Derived & derived()
Definition EigenBase.h:50
const AdjointReturnType adjoint() const
Definition SolverBase.h:143
ComputationInfo
Definition Constants.h:455
@ Success
Definition Constants.h:457
@ ColMajor
Definition Constants.h:319
@ RowMajor
Definition Constants.h:321
constexpr unsigned int RowMajorBit
Definition Constants.h:71
Definition EigenBase.h:34
constexpr Index cols() const noexcept
Definition EigenBase.h:62
constexpr Derived & derived()
Definition EigenBase.h:50
constexpr Index rows() const noexcept
Definition EigenBase.h:60
constexpr Index size() const noexcept
Definition EigenBase.h:65
Eigen::Index Index
The interface type of indices.
Definition EigenBase.h:44