Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
SelfAdjointEigenSolver.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) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
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// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_SELFADJOINTEIGENSOLVER_H
13#define EIGEN_SELFADJOINTEIGENSOLVER_H
14
15#include "./Tridiagonalization.h"
16
17// IWYU pragma: private
18#include "./InternalHeaderCheck.h"
19
20namespace Eigen {
21
22template <typename MatrixType_>
24
25namespace internal {
26template <typename SolverType, int Size, bool IsComplex, bool IsDirect = !IsComplex && (Size == 2 || Size == 3)>
27struct direct_selfadjoint_eigenvalues;
28
29template <bool PerBlockScaling, typename MatrixType, typename DiagType, typename SubDiagType>
30EIGEN_DEVICE_FUNC ComputationInfo computeFromTridiagonal_impl(DiagType& diag, SubDiagType& subdiag,
31 const Index maxIterations, bool computeEigenvectors,
32 MatrixType& eivec);
33} // namespace internal
34
83template <typename MatrixType_>
85 public:
86 using MatrixType = MatrixType_;
87 enum {
88 Size = MatrixType::RowsAtCompileTime,
89 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
90 Options = internal::plain_object_options<MatrixType>::value,
91 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
92 };
93
95 using Scalar = typename MatrixType::Scalar;
96 using Index = Eigen::Index;
97
102
108 std::conditional_t<internal::is_ref<MatrixType>::value, MatrixType,
110
117 using RealScalar = typename NumTraits<Scalar>::Real;
118
119 friend struct internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver, Size, NumTraits<Scalar>::IsComplex>;
120
126 using VectorType = typename internal::plain_col_type<MatrixType, Scalar>::type;
127 using RealVectorType = typename internal::plain_col_type<MatrixType, RealScalar>::type;
128 using TridiagonalizationType = Tridiagonalization<MatrixType>;
129 using SubDiagonalType = typename TridiagonalizationType::SubDiagonalType;
130
141 EIGEN_DEVICE_FUNC SelfAdjointEigenSolver()
142 : m_eivec(),
143 m_workspace(),
144 m_eivalues(),
145 m_subdiag(),
146 m_hcoeffs(),
147 m_info(InvalidInput),
148 m_isInitialized(false),
149 m_eigenvectorsOk(false) {}
150
163 EIGEN_DEVICE_FUNC explicit SelfAdjointEigenSolver(Index size)
164 : m_eivec(size, size),
165 m_workspace(size),
166 m_eivalues(size),
167 m_subdiag(size > 1 ? size - 1 : 1),
168 m_hcoeffs(size > 1 ? size - 1 : 1),
169 m_isInitialized(false),
170 m_eigenvectorsOk(false) {}
171
188 template <typename InputType>
189 EIGEN_DEVICE_FUNC explicit SelfAdjointEigenSolver(const EigenBase<InputType>& matrix,
190 int options = ComputeEigenvectors)
191 : m_eivec(matrix.rows(), matrix.cols()),
192 m_workspace(matrix.cols()),
193 m_eivalues(matrix.cols()),
194 m_subdiag(matrix.rows() > 1 ? matrix.rows() - 1 : 1),
195 m_hcoeffs(matrix.cols() > 1 ? matrix.cols() - 1 : 1),
196 m_isInitialized(false),
197 m_eigenvectorsOk(false) {
198 compute(matrix.derived(), options);
199 }
200
213 template <typename InputType, bool IsRef = internal::is_ref<MatrixType>::value, std::enable_if_t<IsRef, int> = 0>
214 EIGEN_DEVICE_FUNC explicit SelfAdjointEigenSolver(EigenBase<InputType>& matrix, int options = ComputeEigenvectors)
215 : SelfAdjointEigenSolver(matrix, BindStorageTag()) {
216 m_eivec.template triangularView<StrictlyUpper>().setZero();
217 computeInPlace(options);
218 }
219
251 template <typename InputType>
252 EIGEN_DEVICE_FUNC SelfAdjointEigenSolver& compute(const EigenBase<InputType>& matrix,
253 int options = ComputeEigenvectors);
254
281 EIGEN_DEVICE_FUNC SelfAdjointEigenSolver& computeDirect(const MatrixType& matrix, int options = ComputeEigenvectors);
282
295 SelfAdjointEigenSolver& computeFromTridiagonal(const RealVectorType& diag, const SubDiagonalType& subdiag,
296 int options = ComputeEigenvectors);
297
321 EIGEN_DEVICE_FUNC const EigenvectorsType& eigenvectors() const {
322 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
323 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
324 return m_eivec;
325 }
326
342 EIGEN_DEVICE_FUNC const RealVectorType& eigenvalues() const {
343 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
344 return m_eivalues;
345 }
346
364 EIGEN_DEVICE_FUNC PlainMatrixType operatorSqrt() const {
365 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
366 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
367 return m_eivec * m_eivalues.cwiseSqrt().asDiagonal() * m_eivec.adjoint();
368 }
369
380 EIGEN_DEVICE_FUNC PlainMatrixType operatorExp() const {
381 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
382 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
383 return m_eivec * m_eivalues.array().exp().matrix().asDiagonal() * m_eivec.adjoint();
384 }
385
404 EIGEN_DEVICE_FUNC PlainMatrixType operatorInverseSqrt() const {
405 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
406 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
407 return m_eivec * m_eivalues.cwiseInverse().cwiseSqrt().asDiagonal() * m_eivec.adjoint();
408 }
409
414 EIGEN_DEVICE_FUNC ComputationInfo info() const {
415 eigen_assert(m_isInitialized && "SelfAdjointEigenSolver is not initialized.");
416 return m_info;
417 }
418
424 static const int m_maxIterations = 30;
425
426 protected:
427 EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar)
428
429
430 struct BindStorageTag {};
431
434 template <typename InputType>
435 EIGEN_DEVICE_FUNC SelfAdjointEigenSolver(EigenBase<InputType>& matrix, BindStorageTag)
436 : m_eivec(matrix.derived()),
437 m_workspace(matrix.cols()),
438 m_eivalues(matrix.cols()),
439 m_subdiag(matrix.rows() > 1 ? matrix.rows() - 1 : 1),
440 m_hcoeffs(matrix.cols() > 1 ? matrix.cols() - 1 : 1),
441 m_isInitialized(false),
442 m_eigenvectorsOk(false) {}
443
446 EIGEN_DEVICE_FUNC SelfAdjointEigenSolver& computeInPlace(int options);
447
448 EigenvectorsType m_eivec;
449 VectorType m_workspace;
450 RealVectorType m_eivalues;
451 typename TridiagonalizationType::SubDiagonalType m_subdiag;
452 typename TridiagonalizationType::CoeffVectorType m_hcoeffs;
453 ComputationInfo m_info;
454 bool m_isInitialized;
455 bool m_eigenvectorsOk;
456};
457
458namespace internal {
477template <typename RealScalar, typename Index, typename MatrixQType>
478EIGEN_DEVICE_FUNC static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index start, Index end,
479 MatrixQType* matrixQ);
480} // namespace internal
481
482template <typename MatrixType>
483template <typename InputType>
485 const EigenBase<InputType>& a_matrix, int options) {
486 const InputType& matrix(a_matrix.derived());
487 EIGEN_INTERNAL_ASSERT_SQUARE(matrix);
488 m_eivec = matrix.template triangularView<Lower>();
489 return computeInPlace(options);
490}
491
492template <typename MatrixType>
493EIGEN_DEVICE_FUNC SelfAdjointEigenSolver<MatrixType>& SelfAdjointEigenSolver<MatrixType>::computeInPlace(int options) {
494 EIGEN_INTERNAL_ASSERT_SQUARE(m_eivec);
495 eigen_assert((options & ~(EigVecMask | GenEigMask)) == 0 && (options & EigVecMask) != EigVecMask &&
496 "invalid option parameter");
497 bool computeEigenvectors = (options & ComputeEigenvectors) == ComputeEigenvectors;
498 Index n = m_eivec.cols();
499 m_eivalues.resize(n, 1);
500
501 if (n <= 1) {
502 if (n == 1) m_eivalues.coeffRef(0, 0) = numext::real(m_eivec.coeff(0, 0));
503 if (computeEigenvectors) m_eivec.setOnes();
504 m_info = m_eivalues.allFinite() ? Success : NoConvergence;
505 m_isInitialized = true;
506 m_eigenvectorsOk = computeEigenvectors;
507 return *this;
508 }
509
510 // declare some aliases
511 RealVectorType& diag = m_eivalues;
512 EigenvectorsType& mat = m_eivec;
513
514 // A selfadjoint matrix has a real diagonal: ignore the imaginary part, as LAPACK's xLANHE and xHETRD do, so that
515 // it neither sets the scale below nor injects a NaN or Inf.
516 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
517 mat.diagonal() = mat.diagonal().real();
518 }
519
520 // Scale the matrix to O(1) to avoid overflow/underflow during tridiagonalization. Power-of-two factors avoid
521 // rounding representable scaled coefficients. The QR iteration then scales each unreduced block again by its own
522 // maximum. Note: for block-diagonal matrices with widely separated scales, the global scaling can underflow
523 // small blocks before the tridiagonalization. Users with such matrices should tridiagonalize separately
524 // and call computeFromTridiagonal().
525 const RealScalar maxCoeff = internal::safe_scaling<RealScalar>::max_abs_component(mat);
526 if (!(numext::isfinite)(maxCoeff)) {
527 // Input contains Inf or NaN.
528 m_info = NoConvergence;
529 m_isInitialized = true;
530 m_eigenvectorsOk = false;
531 return *this;
532 }
533 const auto factors = internal::safe_scaling<RealScalar>::with_scaled(mat, maxCoeff, [&](const auto& scaled) {
534 mat.template triangularView<Lower>() = scaled.template triangularView<Lower>();
535 });
536 m_subdiag.resize(n - 1);
537 m_hcoeffs.resize(n - 1);
538 internal::tridiagonalization_inplace(mat, diag, m_subdiag, m_hcoeffs, m_workspace, computeEigenvectors);
539
540 // Iterate on each unreduced block scaled to its own maximum, as xSTEQR does (Anderson et al., LAPACK Users' Guide):
541 // the deflation floor sqrt(min) is then relative to the block, and an isolated block of tiny entries keeps its
542 // accuracy.
543 m_info = internal::computeFromTridiagonal_impl<true>(diag, m_subdiag, m_maxIterations, computeEigenvectors, m_eivec);
544
545 // Scale back the eigenvalues.
546 internal::safe_scaling<RealScalar>::unscale_in_place(m_eivalues, maxCoeff, factors);
547
548 m_isInitialized = true;
549 m_eigenvectorsOk = computeEigenvectors;
550 return *this;
551}
552
553template <typename MatrixType>
555 const RealVectorType& diag, const SubDiagonalType& subdiag, int options) {
556 bool computeEigenvectors = (options & ComputeEigenvectors) == ComputeEigenvectors;
557
558 m_eivalues = diag;
559 m_subdiag = subdiag;
560
561 // Check for Inf/NaN in the input.
562 {
563 RealScalar scale = RealScalar(0);
564 if (m_eivalues.size() > 0) scale = m_eivalues.cwiseAbs().maxCoeff();
565 if (m_subdiag.size() > 0) scale = numext::maxi(scale, m_subdiag.cwiseAbs().maxCoeff());
566 if (!(numext::isfinite)(scale)) {
567 m_info = NoConvergence;
568 m_isInitialized = true;
569 m_eigenvectorsOk = false;
570 return *this;
571 }
572 }
573
574 if (computeEigenvectors) {
575 m_eivec.setIdentity(diag.size(), diag.size());
576 }
577 // Use per-deflation-block scaling (the scaling, not the deflation test, of LAPACK's DSTERF) to avoid losing
578 // precision when the tridiagonal entries span a wide range of magnitudes.
579 m_info =
580 internal::computeFromTridiagonal_impl<true>(m_eivalues, m_subdiag, m_maxIterations, computeEigenvectors, m_eivec);
581
582 m_isInitialized = true;
583 m_eigenvectorsOk = computeEigenvectors;
584 return *this;
585}
586
587namespace internal {
604template <bool PerBlockScaling, typename MatrixType, typename DiagType, typename SubDiagType>
605EIGEN_DEVICE_FUNC ComputationInfo computeFromTridiagonal_impl(DiagType& diag, SubDiagType& subdiag,
606 const Index maxIterations, bool computeEigenvectors,
607 MatrixType& eivec) {
608 ComputationInfo info;
609
610 Index n = diag.size();
611 Index end = n - 1;
612 Index start = 0;
613 Index iter = 0; // total number of iterations
614
615 using RealScalar = typename DiagType::RealScalar;
616 // Absolute floor of the deflation test, used in coordinates scaled to max in [1, 2) of the unreduced block being
617 // iterated: from the second call of the test on, because the first one precedes the scaling of any block (a
618 // coupling below the floor can be significant for T = s T0 with s near min()). A dropped coupling is at most
619 // sqrt(min) times the norm of its block (1.5e-154 in double, 1.1e-19 in float), far below eps times it. It is the
620 // effective floor of the xSTEQR criterion e_i^2 <= eps^2 |d_i| |d_{i+1}| + safmin (Anderson et al., LAPACK Users'
621 // Guide). A floor of min() lets a block that is graded over more than ~1/sqrt(min) make one rotation per
622 // iteration, as the underflowing bulge entries never deflate: NoConvergence. The limit, as in LAPACK: eigenvalues
623 // below about sqrt(min) |block| inside a coupled graded chain are not accurate relative to themselves.
624 // The floor is capped at eps^2, and at min() from below: in Eigen::half sqrt(min) = 8 eps would deflate a coupling of
625 // a few eps, while eps^2 < min() leaves min(). The other types keep sqrt(min).
626 const RealScalar safmin = (std::numeric_limits<RealScalar>::min)();
627 const RealScalar precision = NumTraits<RealScalar>::epsilon();
628 const RealScalar considerAsZero =
629 numext::maxi<RealScalar>(safmin, numext::mini<RealScalar>(numext::sqrt(safmin), precision * precision));
630
631 // Helper lambda for the deflation test.
632 auto deflate = [&](Index lo, Index hi) {
633 for (Index i = lo; i < hi; ++i) {
634 const RealScalar absSubdiag = numext::abs(subdiag[i]);
635 // |e_i| <= eps * max(|d_i|, |d_{i+1}|) is homogeneous of degree one in the entries, so the decision is unchanged
636 // by any scaling of the block; it perturbs T by at most eps * ||T||. The absolute floor applies only in scaled
637 // coordinates; see considerAsZero.
638 const bool belowMin = (!PerBlockScaling || iter != 0) && absSubdiag < considerAsZero;
639 if (belowMin || absSubdiag <= precision * numext::maxi(numext::abs(diag[i]), numext::abs(diag[i + 1]))) {
640 subdiag[i] = RealScalar(0);
641 }
642 }
643 };
644
645 // For per-block scaling, track the currently scaled block and its scale factor.
646 // When the outer loop identifies a block outside the scaled region, unscale the old
647 // block and scale the new one. This keeps the same outer loop structure (one QR step
648 // per iteration) while ensuring each block is processed in scaled coordinates.
649 Index scaled_start = -1, scaled_end = -1;
650 RealScalar block_norm = RealScalar(0);
651 safe_scaling_factors<RealScalar> blockFactors;
652 const auto restore_block = [&]() {
653 if (scaled_start < 0) return;
654 auto diagonal = diag.segment(scaled_start, scaled_end - scaled_start + 1);
655 auto offDiagonal = subdiag.segment(scaled_start, scaled_end - scaled_start);
656 safe_scaling<RealScalar>::unscale_in_place(diagonal, block_norm, blockFactors);
657 safe_scaling<RealScalar>::unscale_in_place(offDiagonal, block_norm, blockFactors);
658 };
659
660 while (end > 0) {
661 deflate(start, end);
662
663 // Find the largest unreduced block at the end of the matrix.
664 while (end > 0 && numext::is_exactly_zero(subdiag[end - 1])) {
665 end--;
666 }
667 if (end <= 0) break;
668
669 // if we spent too many iterations, we give up
670 iter++;
671 if (iter > maxIterations * n) break;
672
673 start = end - 1;
674 while (start > 0 && !numext::is_exactly_zero(subdiag[start - 1])) start--;
675
676 if (PerBlockScaling) {
677 // Check if we've moved to a different block than the one currently scaled.
678 if (start != scaled_start || end != scaled_end) {
679 restore_block();
680 // Compute the norm and scale the new block to O(1).
681 block_norm = RealScalar(0);
682 for (Index i = start; i <= end; ++i) block_norm = numext::maxi(block_norm, numext::abs(diag[i]));
683 for (Index i = start; i < end; ++i) block_norm = numext::maxi(block_norm, numext::abs(subdiag[i]));
684 auto diagonal = diag.segment(start, end - start + 1);
685 auto offDiagonal = subdiag.segment(start, end - start);
686 blockFactors = safe_scaling<RealScalar>::scale_to(diagonal, diagonal, block_norm);
687 safe_scaling<RealScalar>::scale_to(offDiagonal, offDiagonal, block_norm, blockFactors);
688 scaled_start = start;
689 scaled_end = end;
690 }
691 }
692
693 internal::tridiagonal_qr_step(diag.data(), subdiag.data(), start, end,
694 computeEigenvectors ? &eivec : static_cast<MatrixType*>(nullptr));
695 }
696
697 // Unscale any remaining scaled block.
698 if (PerBlockScaling) restore_block();
699 if (iter <= maxIterations * n)
700 info = Success;
701 else
702 info = NoConvergence;
703
704 // Sort eigenvalues and corresponding vectors.
705 // TODO: make the sort optional and use a more efficient sorting algorithm.
706 if (info == Success) {
707 for (Index i = 0; i < n - 1; ++i) {
708 // Scalar argmin: the vectorized minCoeff path can return the wrong
709 // index on targets whose SIMD reduction flushes subnormals (32-bit ARM
710 // NEON always treats subnormal inputs to vminq_f32 as zero), which
711 // corrupts ordering when eigenvalues span the subnormal range.
712 Index k = i;
713 RealScalar min_val = diag[i];
714 for (Index j = i + 1; j < n; ++j) {
715 if (diag[j] < min_val) {
716 min_val = diag[j];
717 k = j;
718 }
719 }
720 if (k != i) {
721 numext::swap(diag[i], diag[k]);
722 if (computeEigenvectors) eivec.col(i).swap(eivec.col(k));
723 }
724 }
725 }
726 return info;
727}
728
729template <typename SolverType, int Size, bool IsComplex, bool IsDirect>
730struct direct_selfadjoint_eigenvalues {
731 EIGEN_DEVICE_FUNC static inline void run(SolverType& eig, const typename SolverType::MatrixType& A, int options) {
732 eig.compute(A, options);
733 }
734};
735
736template <typename SolverType, int Size>
737struct direct_selfadjoint_eigensolver_kernel;
738
739template <typename SolverType>
740struct direct_selfadjoint_eigensolver_kernel<SolverType, 3> {
741 using MatrixType = typename SolverType::MatrixType;
742 using VectorType = typename SolverType::RealVectorType;
743 using Scalar = typename SolverType::Scalar;
744 using EigenvectorsType = typename SolverType::EigenvectorsType;
745 using PlainMatrixType = typename SolverType::PlainMatrixType;
746
751 EIGEN_DEVICE_FUNC static inline void computeRoots(const MatrixType& m, VectorType& roots) {
752 const Scalar s_inv3 = Scalar(1) / Scalar(3);
753 const Scalar s_sqrt3 = numext::sqrt(Scalar(3));
754
755 // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The
756 // eigenvalues are the roots to this equation, all guaranteed to be
757 // real-valued, because the matrix is symmetric.
758 Scalar c0 = m(0, 0) * m(1, 1) * m(2, 2) + Scalar(2) * m(1, 0) * m(2, 0) * m(2, 1) - m(0, 0) * m(2, 1) * m(2, 1) -
759 m(1, 1) * m(2, 0) * m(2, 0) - m(2, 2) * m(1, 0) * m(1, 0);
760 Scalar c1 = m(0, 0) * m(1, 1) - m(1, 0) * m(1, 0) + m(0, 0) * m(2, 2) - m(2, 0) * m(2, 0) + m(1, 1) * m(2, 2) -
761 m(2, 1) * m(2, 1);
762 Scalar c2 = m(0, 0) + m(1, 1) + m(2, 2);
763
764 // Construct the parameters used in classifying the roots of the equation
765 // and in solving the equation for the roots in closed form.
766 Scalar c2_over_3 = c2 * s_inv3;
767 Scalar a_over_3 = (c2 * c2_over_3 - c1) * s_inv3;
768 a_over_3 = numext::maxi(a_over_3, Scalar(0));
769
770 Scalar half_b = Scalar(0.5) * (c0 + c2_over_3 * (Scalar(2) * c2_over_3 * c2_over_3 - c1));
771
772 Scalar q = a_over_3 * a_over_3 * a_over_3 - half_b * half_b;
773 q = numext::maxi(q, Scalar(0));
774
775 // Compute the eigenvalues by solving for the roots of the polynomial.
776 Scalar rho = numext::sqrt(a_over_3);
777 Scalar theta = numext::atan2(numext::sqrt(q), half_b) *
778 s_inv3; // since sqrt(q) > 0, atan2 is in [0, pi] and theta is in [0, pi/3]
779 Scalar cos_theta = numext::cos(theta);
780 Scalar sin_theta = numext::sin(theta);
781 // roots are already sorted, since cos is monotonically decreasing on [0, pi]
782 roots(0) = c2_over_3 - rho * (cos_theta + s_sqrt3 * sin_theta); // == 2*rho*cos(theta+2pi/3)
783 roots(1) = c2_over_3 - rho * (cos_theta - s_sqrt3 * sin_theta); // == 2*rho*cos(theta+ pi/3)
784 roots(2) = c2_over_3 + Scalar(2) * rho * cos_theta;
785 }
786
787 EIGEN_DEVICE_FUNC static inline bool extract_kernel(PlainMatrixType& mat, Ref<VectorType> res,
788 Ref<VectorType> representative) {
789 Index i0;
790 // Find non-zero column i0 (by construction, there must exist a non zero coefficient on the diagonal):
791 mat.diagonal().cwiseAbs().maxCoeff(&i0);
792 // mat.col(i0) is a good candidate for an orthogonal vector to the current eigenvector,
793 // so let's save it:
794 representative = mat.col(i0);
795 Scalar n0, n1;
796 VectorType c0, c1;
797 n0 = (c0 = representative.cross(mat.col((i0 + 1) % 3))).squaredNorm();
798 n1 = (c1 = representative.cross(mat.col((i0 + 2) % 3))).squaredNorm();
799 if (n0 > n1)
800 res = c0 / numext::sqrt(n0);
801 else
802 res = c1 / numext::sqrt(n1);
803
804 return true;
805 }
806
807 EIGEN_DEVICE_FUNC static void run(PlainMatrixType& scaledMat, VectorType& eivals, EigenvectorsType& eivecs,
808 bool computeEigenvectors, const Scalar& maxCoeff) {
809 // compute the eigenvalues
810 computeRoots(scaledMat, eivals);
811
812 // computeRoots produces theoretically sorted roots, but floating-point
813 // rounding in the trigonometric formulas can break the ordering.
814 // Enforce sorting with a fixed 3-element compare-swap network.
815 if (eivals(0) > eivals(1)) numext::swap(eivals(0), eivals(1));
816 if (eivals(1) > eivals(2)) numext::swap(eivals(1), eivals(2));
817 if (eivals(0) > eivals(1)) numext::swap(eivals(0), eivals(1));
818
819 // compute the eigenvectors
820 if (computeEigenvectors) {
821 if ((eivals(2) - eivals(0)) <= Eigen::NumTraits<Scalar>::epsilon() * maxCoeff) {
822 // All three eigenvalues are numerically the same
823 eivecs.setIdentity();
824 } else {
825 PlainMatrixType tmp;
826 tmp = scaledMat;
827
828 // Compute the eigenvector of the most distinct eigenvalue
829 Scalar d0 = eivals(2) - eivals(1);
830 Scalar d1 = eivals(1) - eivals(0);
831 Index k(0), l(2);
832 if (d0 > d1) {
833 numext::swap(k, l);
834 d0 = d1;
835 }
836
837 // Compute the eigenvector of index k
838 {
839 tmp.diagonal().array() -= eivals(k);
840 // By construction, 'tmp' is of rank 2, and its kernel corresponds to the respective eigenvector.
841 extract_kernel(tmp, eivecs.col(k), eivecs.col(l));
842 }
843
844 // Compute eigenvector of index l
845 if (d0 <= 2 * Eigen::NumTraits<Scalar>::epsilon() * d1) {
846 // If d0 is too small, then the two other eigenvalues are numerically the same,
847 // and thus we only have to ortho-normalize the near orthogonal vector we saved above.
848 eivecs.col(l) -= eivecs.col(k).dot(eivecs.col(l)) * eivecs.col(k);
849 eivecs.col(l).normalize();
850 } else {
851 tmp = scaledMat;
852 tmp.diagonal().array() -= eivals(l);
853
854 VectorType dummy;
855 extract_kernel(tmp, eivecs.col(l), dummy);
856 }
857
858 // Compute last eigenvector from the other two
859 eivecs.col(1) = eivecs.col(2).cross(eivecs.col(0)).normalized();
860 }
861 }
862 }
863};
864
865// 2x2 direct eigenvalues decomposition, code from Hauke Heibel
866template <typename SolverType>
867struct direct_selfadjoint_eigensolver_kernel<SolverType, 2> {
868 using MatrixType = typename SolverType::MatrixType;
869 using VectorType = typename SolverType::RealVectorType;
870 using Scalar = typename SolverType::Scalar;
871 using EigenvectorsType = typename SolverType::EigenvectorsType;
872 using PlainMatrixType = typename SolverType::PlainMatrixType;
873
874 EIGEN_DEVICE_FUNC static inline void computeRoots(const MatrixType& m, VectorType& roots) {
875 const Scalar t0 =
876 Scalar(0.5) * numext::sqrt<Scalar>(numext::abs2(m(0, 0) - m(1, 1)) + Scalar(4) * numext::abs2(m(1, 0)));
877 const Scalar t1 = Scalar(0.5) * (m(0, 0) + m(1, 1));
878 roots(0) = t1 - t0;
879 roots(1) = t1 + t0;
880 }
881
882 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static void run(PlainMatrixType& scaledMat, VectorType& eivals,
883 EigenvectorsType& eivecs, bool computeEigenvectors,
884 const Scalar&) {
885 // Compute the eigenvalues
886 computeRoots(scaledMat, eivals);
887
888 // compute the eigen vectors
889 if (computeEigenvectors) {
890 if ((eivals(1) - eivals(0)) <= numext::abs(eivals(1)) * Eigen::NumTraits<Scalar>::epsilon()) {
891 eivecs.setIdentity();
892 } else {
893 scaledMat.diagonal().array() -= eivals(1);
894 Scalar a2 = numext::abs2(scaledMat(0, 0));
895 Scalar c2 = numext::abs2(scaledMat(1, 1));
896 Scalar b2 = numext::abs2(scaledMat(1, 0));
897 if (a2 > c2) {
898 eivecs.col(1) << -scaledMat(1, 0), scaledMat(0, 0);
899 eivecs.col(1) /= numext::sqrt<Scalar>(a2 + b2);
900 } else {
901 eivecs.col(1) << -scaledMat(1, 1), scaledMat(1, 0);
902 eivecs.col(1) /= numext::sqrt<Scalar>(c2 + b2);
903 }
904
905 // The partner is already normalized; this rotation preserves its norm.
906 eivecs.col(0) << -eivecs(1, 1), eivecs(0, 1);
907 }
908 }
909 }
910};
911
912template <typename SolverType, int Size>
913struct direct_selfadjoint_eigenvalues<SolverType, Size, false, true> {
914 using MatrixType = typename SolverType::MatrixType;
915 using PlainMatrixType = typename SolverType::PlainMatrixType;
916 using Scalar = typename SolverType::Scalar;
917
918 // Only host-side long double limits need more range than double.
919 using Limit = std::conditional_t<std::is_same<Scalar, long double>::value, long double, double>;
920
921 EIGEN_DEVICE_FUNC static constexpr Limit power_of_two(int exponent) {
922 Limit result = 1;
923 for (; exponent > 0; --exponent) result *= 2;
924 for (; exponent < 0; ++exponent) result /= 2;
925 return result;
926 }
927
928 EIGEN_DEVICE_FUNC static bool safe_without_scaling(const Scalar& magnitude, true_type) {
929 // The quadratic/cubic kernels have degree 2/6. Reserve 12 exponent bits
930 // for intermediate growth and keep flushed terms below epsilon*mu^degree.
931 constexpr int degree = Size == 3 ? 6 : 2;
932 constexpr int lower = std::numeric_limits<Scalar>::min_exponent - 1 + std::numeric_limits<Scalar>::digits - 1 + 12;
933 constexpr int upper = std::numeric_limits<Scalar>::max_exponent - 1 - 12;
934 constexpr int minExponent = lower >= 0 ? (lower + degree - 1) / degree : lower / degree;
935 constexpr int maxExponent = upper >= 0 ? upper / degree : (upper - degree + 1) / degree;
936 constexpr Limit minimum = power_of_two(minExponent);
937 constexpr Limit maximum = power_of_two(maxExponent);
938 return magnitude >= Scalar(minimum) && magnitude <= Scalar(maximum);
939 }
940
941 EIGEN_DEVICE_FUNC static bool safe_without_scaling(const Scalar& magnitude, false_type) {
942 return magnitude >= Scalar(0.25) && magnitude <= Scalar(2) &&
943 NumTraits<Scalar>::epsilon() / Scalar(4096) >= (std::numeric_limits<Scalar>::min)();
944 }
945
946 EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE static void run_scaled(SolverType& solver, const MatrixType& mat,
947 const Scalar& shift, Scalar centeredMax, int options) {
948 PlainMatrixType scaledMat = mat.template selfadjointView<Lower>();
949 scaledMat.diagonal().array() -= shift;
950 centeredMax = safe_scaling<Scalar>::recover_flushed_max_coeff(scaledMat, centeredMax);
951 const auto factors = safe_scaling<Scalar>::scale_to(scaledMat, scaledMat, centeredMax);
952 direct_selfadjoint_eigensolver_kernel<SolverType, Size>::run(scaledMat, solver.m_eivalues, solver.m_eivec,
954 scaledMat.cwiseAbs().maxCoeff());
955 safe_scaling<Scalar>::unscale_in_place(solver.m_eivalues, centeredMax, factors);
956 }
957
958 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static void run_centered(SolverType& solver, const MatrixType& mat,
959 int options) {
960 const bool computeEigenvectors = (options & ComputeEigenvectors) == ComputeEigenvectors;
961 PlainMatrixType scaledMat = mat.template selfadjointView<Lower>();
962 const Scalar first = scaledMat(0, 0);
963 Scalar shift = first;
964 for (Index i = 1; i < Size; ++i) shift += (scaledMat(i, i) - first) / Scalar(Size);
965 scaledMat.diagonal().array() -= shift;
966 // Centering can leave a much smaller matrix; normalize again for the cubic and cross-product formulas.
967 const Scalar centeredMax = scaledMat.cwiseAbs().maxCoeff();
968 if (safe_without_scaling(centeredMax, supports_power_of_two_scaling<Scalar>())) {
969 direct_selfadjoint_eigensolver_kernel<SolverType, Size>::run(scaledMat, solver.m_eivalues, solver.m_eivec,
970 computeEigenvectors, centeredMax);
971 } else {
972 run_scaled(solver, mat, shift, centeredMax, options);
973 }
974 solver.m_eivalues.array() += shift;
975 solver.m_info = Success;
976 solver.m_isInitialized = true;
977 solver.m_eigenvectorsOk = computeEigenvectors;
978 }
979
980 EIGEN_DEVICE_FUNC static void run_large(SolverType& solver, PlainMatrixType& scaledMat, int options, false_type) {
981 run_centered(solver, scaledMat, options);
982 }
983
984 EIGEN_DEVICE_FUNC static void run_large(SolverType& solver, PlainMatrixType& scaledMat, int options, true_type) {
985 // The cubic loses accuracy near repeated roots; at the exponent limit that error can overflow a finite result.
986 solver.compute(scaledMat, options);
987 }
988
989 EIGEN_DEVICE_FUNC EIGEN_DONT_INLINE static void run_prescaled(SolverType& solver, const MatrixType& mat,
990 const Scalar& maxCoeff, int options) {
991 PlainMatrixType scaledMat = mat.template selfadjointView<Lower>();
992 const Scalar recoveredMax = safe_scaling<Scalar>::recover_flushed_max_coeff(scaledMat, maxCoeff);
993 const auto inputFactors = safe_scaling<Scalar>::scale_to(scaledMat, scaledMat, recoveredMax);
994 if (maxCoeff > (NumTraits<Scalar>::highest() * Scalar(0.5)) / Scalar(Size)) {
995 run_large(solver, scaledMat, options,
996 bool_constant<(Size == 3 && supports_power_of_two_scaling<Scalar>::value)>());
997 } else {
998 run_centered(solver, scaledMat, options);
999 }
1000 safe_scaling<Scalar>::unscale_in_place(solver.m_eivalues, recoveredMax, inputFactors);
1001 }
1002
1003 EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE static void run(SolverType& solver, const MatrixType& mat, int options) {
1004 EIGEN_INTERNAL_CHECK_SHAPE(mat.rows() == Size && mat.cols() == Size, YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES,
1005 internal::fixed_dimensions<MatrixType, Size, Size>);
1006 eigen_assert((options & ~(EigVecMask | GenEigMask)) == 0 && (options & EigVecMask) != EigVecMask &&
1007 "invalid option parameter");
1008 PlainMatrixType scaledMat = mat.template selfadjointView<Lower>();
1009 const Scalar maxCoeff = scaledMat.cwiseAbs().maxCoeff();
1010 // Bound centered coefficients by 2*M and eigenvalues by Size*M. Prescale tiny inputs before any FTZ-sensitive
1011 // subtraction, and large inputs before centering or restoring the centered eigenvalues could overflow.
1012 // Halve highest() first: IBM double-double division can overflow internally at the maximum value.
1013 if (EIGEN_PREDICT_FALSE(maxCoeff < (std::numeric_limits<Scalar>::min)() / NumTraits<Scalar>::epsilon() ||
1014 maxCoeff > (NumTraits<Scalar>::highest() * Scalar(0.5)) / Scalar(Size))) {
1015 run_prescaled(solver, mat, maxCoeff, options);
1016 } else {
1017 run_centered(solver, mat, options);
1018 }
1019 }
1020};
1021
1022} // namespace internal
1023
1024template <typename MatrixType>
1026 const MatrixType& matrix, int options) {
1027 internal::direct_selfadjoint_eigenvalues<SelfAdjointEigenSolver, Size, NumTraits<Scalar>::IsComplex>::run(
1028 *this, matrix, options);
1029 return *this;
1030}
1031
1032namespace internal {
1033
1034// Francis implicit QR step; the rotations accumulate into *matrixQ when it is non-null.
1035template <typename RealScalar, typename Index, typename MatrixQType>
1036EIGEN_DEVICE_FUNC static void tridiagonal_qr_step(RealScalar* diag, RealScalar* subdiag, Index start, Index end,
1037 MatrixQType* matrixQ) {
1038 // Wilkinson Shift.
1039 RealScalar td = (diag[end - 1] - diag[end]) * RealScalar(0.5);
1040 RealScalar e = subdiag[end - 1];
1041 RealScalar mu = diag[end];
1042 if (numext::is_exactly_zero(td)) {
1043 mu -= numext::abs(e);
1044 } else if (!numext::is_exactly_zero(e)) {
1045 const RealScalar e2 = numext::abs2(e);
1046 if (numext::is_exactly_zero(e2)) {
1047 // Scaling prevents e^2 and td^2 from overflowing, but e^2 can still underflow. A subdiagonal that survives
1048 // deflation satisfies (e/epsilon)^2 > 2*abs(td), so td/e remains bounded in this branch. LAPACK's xSTEQR uses
1049 // this dimensionless form; keeping td/e inside hypot prevents fast-math from reassociating the correction into
1050 // an underflowing e^2 expression.
1051 const RealScalar ratio = td / e;
1052 const RealScalar h = numext::hypot(ratio, RealScalar(1));
1053 mu -= e / (ratio + (ratio > RealScalar(0) ? h : -h));
1054 } else {
1055 const RealScalar h = numext::hypot(td, e);
1056 mu -= e2 / (td + (td > RealScalar(0) ? h : -h));
1057 }
1058 }
1059
1060 RealScalar x = diag[start] - mu;
1061 RealScalar z = subdiag[start];
1062 // If z ever becomes zero, the Givens rotation will be the identity and
1063 // z will stay zero for all future iterations.
1064 for (Index k = start; k < end && !numext::is_exactly_zero(z); ++k) {
1065 JacobiRotation<RealScalar> rot;
1066 rot.makeGivens(x, z);
1067
1068 // do T = G' T G. The two new diagonal entries and the new off-diagonal are all expressed below
1069 // as functions of the original difference diff = diag[k] - diag[k+1] and the original subdiag[k],
1070 // so capture diff and compute delta/subdiag[k] before overwriting the diagonal.
1071 const RealScalar diff = diag[k] - diag[k + 1];
1072
1073 // Update the 2x2 diagonal block by the symmetric change delta, applied with opposite signs to
1074 // diag[k] and diag[k+1]. A similarity leaves the trace invariant, so this preserves diag[k] +
1075 // diag[k+1] exactly. Forming the two new diagonal entries from independent explicit formulas
1076 // (diag[k] = c^2 d_k - 2 c s e_k + s^2 d_{k+1}, diag[k+1] = s^2 d_k + 2 c s e_k + c^2 d_{k+1})
1077 // instead lets the two roundings drift the trace a little on every rotation, an error that
1078 // accumulates over the O(n^2) rotations of a full solve and measurably degrades the eigenvalues.
1079 // Algebraically delta = s^2 (d_k - d_{k+1}) + 2 c s e_k, which is exactly d_k minus the formula above.
1080 const RealScalar delta = rot.s() * (rot.s() * diff + RealScalar(2) * rot.c() * subdiag[k]);
1081 // The exact (G' T G) off-diagonal, c*s*(d_k - d_{k+1}) + (c^2 - s^2)*e_k, written in the same diff
1082 // form rather than via the c*sdk - s*dkp1 temporaries.
1083 subdiag[k] = rot.c() * rot.s() * diff + (rot.c() * rot.c() - rot.s() * rot.s()) * subdiag[k];
1084 diag[k] -= delta;
1085 diag[k + 1] += delta;
1086
1087 if (k > start) subdiag[k - 1] = rot.c() * subdiag[k - 1] - rot.s() * z;
1088
1089 // "Chasing the bulge" to return to triangular form.
1090 x = subdiag[k];
1091 if (k < end - 1) {
1092 z = -rot.s() * subdiag[k + 1];
1093 subdiag[k + 1] = rot.c() * subdiag[k + 1];
1094 }
1095
1096 // apply the givens rotation to the unit matrix Q = Q * G
1097 if (matrixQ) {
1098 // Contiguous column-major storage is rotated through a dynamic-size map: the rotation kernel then dispatches
1099 // on the runtime alignment for fixed-size matrices too, and rounds as it always did. Other storage (a
1100 // row-major Ref<>) is rotated through the matrix type itself.
1101 EIGEN_IF_CONSTEXPR (!MatrixQType::IsRowMajor && int(MatrixQType::InnerStrideAtCompileTime) == 1) {
1102 using Scalar = typename MatrixQType::Scalar;
1103 Map<Matrix<Scalar, Dynamic, Dynamic, ColMajor>, Unaligned, OuterStride<>> q(
1104 matrixQ->data(), matrixQ->rows(), matrixQ->cols(), OuterStride<>(matrixQ->outerStride()));
1105 q.applyOnTheRight(k, k + 1, rot);
1106 } else {
1107 matrixQ->applyOnTheRight(k, k + 1, rot);
1108 }
1109 }
1110 }
1111}
1112
1113} // end namespace internal
1114
1115} // end namespace Eigen
1116
1117#endif // EIGEN_SELFADJOINTEIGENSOLVER_H
Computes eigenvalues and eigenvectors of the generalized selfadjoint eigen problem.
Definition GeneralizedSelfAdjointEigenSolver.h:53
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
Computes eigenvalues and eigenvectors of selfadjoint matrices.
Definition SelfAdjointEigenSolver.h:84
PlainMatrixType operatorExp() const
Computes the matrix exponential of the matrix.
Definition SelfAdjointEigenSolver.h:380
SelfAdjointEigenSolver & compute(const EigenBase< InputType > &matrix, int options=ComputeEigenvectors)
Computes eigendecomposition of given matrix.
SelfAdjointEigenSolver & computeFromTridiagonal(const RealVectorType &diag, const SubDiagonalType &subdiag, int options=ComputeEigenvectors)
Computes the eigen decomposition from a tridiagonal symmetric matrix.
Definition SelfAdjointEigenSolver.h:554
SelfAdjointEigenSolver(EigenBase< InputType > &matrix, int options=ComputeEigenvectors)
Constructor for inplace decomposition .
Definition SelfAdjointEigenSolver.h:214
typename MatrixType::Scalar Scalar
Scalar type for matrices of type MatrixType_.
Definition SelfAdjointEigenSolver.h:95
typename internal::plain_col_type< MatrixType, Scalar >::type VectorType
Type for vector of eigenvalues as returned by eigenvalues().
Definition SelfAdjointEigenSolver.h:126
SelfAdjointEigenSolver()
Default constructor for fixed-size matrices.
Definition SelfAdjointEigenSolver.h:141
ComputationInfo info() const
Reports whether previous computation was successful.
Definition SelfAdjointEigenSolver.h:414
Matrix< Scalar, Size, ColsAtCompileTime, Options, MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime > PlainMatrixType
Plain matrix type with the shape and storage options of MatrixType_; MatrixType_ itself unless that i...
Definition SelfAdjointEigenSolver.h:100
PlainMatrixType operatorInverseSqrt() const
Computes the inverse square root of the matrix.
Definition SelfAdjointEigenSolver.h:404
std::conditional_t< internal::is_ref< MatrixType >::value, MatrixType, Matrix< Scalar, Size, Size, ColMajor, MaxColsAtCompileTime, MaxColsAtCompileTime > > EigenvectorsType
Type of the matrix returned by eigenvectors().
Definition SelfAdjointEigenSolver.h:107
typename NumTraits< Scalar >::Real RealScalar
Real scalar type for MatrixType_.
Definition SelfAdjointEigenSolver.h:117
PlainMatrixType operatorSqrt() const
Computes the positive-definite square root of the matrix.
Definition SelfAdjointEigenSolver.h:364
Eigen::Index Index
Definition SelfAdjointEigenSolver.h:96
SelfAdjointEigenSolver(Index size)
Constructor, pre-allocates memory for dynamic-size matrices.
Definition SelfAdjointEigenSolver.h:163
const RealVectorType & eigenvalues() const
Returns the eigenvalues of given matrix.
Definition SelfAdjointEigenSolver.h:342
static const int m_maxIterations
Maximum number of iterations.
Definition SelfAdjointEigenSolver.h:424
const EigenvectorsType & eigenvectors() const
Returns the eigenvectors of given matrix.
Definition SelfAdjointEigenSolver.h:321
SelfAdjointEigenSolver(const EigenBase< InputType > &matrix, int options=ComputeEigenvectors)
Constructor; computes eigendecomposition of given matrix.
Definition SelfAdjointEigenSolver.h:189
SelfAdjointEigenSolver & computeDirect(const MatrixType &matrix, int options=ComputeEigenvectors)
Computes eigendecomposition of given matrix primarily using a closed-form algorithm.
Definition SelfAdjointEigenSolver.h:1025
Tridiagonal decomposition of a selfadjoint matrix.
Definition Tridiagonalization.h:71
ComputationInfo
Definition Constants.h:455
@ Unaligned
Definition Constants.h:236
@ Success
Definition Constants.h:457
@ NoConvergence
Definition Constants.h:461
@ ComputeEigenvectors
Definition Constants.h:406
Definition EigenBase.h:34
constexpr Derived & derived()
Definition EigenBase.h:50
Holds information about the various numeric (i.e. scalar) types allowed by Eigen.
Definition NumTraits.h:267