Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
EigenSolver.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
5// Copyright (C) 2010,2012 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_EIGENSOLVER_H
13#define EIGEN_EIGENSOLVER_H
14
15#include "./RealSchur.h"
16
17// IWYU pragma: private
18#include "./InternalHeaderCheck.h"
19
20namespace Eigen {
21
68template <typename MatrixType_>
70 public:
72 using MatrixType = MatrixType_;
73
74 enum {
75 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
76 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
77 Options = internal::plain_object_options<MatrixType>::value,
78 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
79 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
80 };
81
83 using Scalar = typename MatrixType::Scalar;
84 using RealScalar = typename NumTraits<Scalar>::Real;
85 using Index = Eigen::Index;
86
91
98 using ComplexScalar = internal::make_complex_t<Scalar>;
99
106
114
122 EigenSolver() : m_eivalues(), m_isInitialized(false), m_eigenvectorsOk(false), m_realSchur(), m_tmp() {}
123
130 explicit EigenSolver(Index size)
131 : m_eivalues(size), m_isInitialized(false), m_eigenvectorsOk(false), m_realSchur(size), m_tmp(size) {}
132
148 template <typename InputType>
149 explicit EigenSolver(const EigenBase<InputType>& matrix, bool computeEigenvectors = true)
150 : m_eivalues(matrix.cols()),
151 m_isInitialized(false),
152 m_eigenvectorsOk(false),
153 m_realSchur(matrix.derived(), computeEigenvectors),
154 m_tmp(matrix.cols()) {
155 check_template_parameters();
156 computeFromSchur(computeEigenvectors);
157 }
158
170 template <typename InputType>
171 explicit EigenSolver(EigenBase<InputType>& matrix, bool computeEigenvectors = true)
172 : m_eivalues(matrix.cols()),
173 m_isInitialized(false),
174 m_eigenvectorsOk(false),
175 m_realSchur(matrix.derived(), computeEigenvectors),
176 m_tmp(matrix.cols()) {
177 check_template_parameters();
178 computeFromSchur(computeEigenvectors);
179 }
180
202
222 eigen_assert(m_isInitialized && "EigenSolver is not initialized.");
223 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
224 return m_realSchur.m_matU;
225 }
226
246
266 eigen_assert(m_isInitialized && "EigenSolver is not initialized.");
267 return m_eivalues;
268 }
269
297 template <typename InputType>
298 EigenSolver& compute(const EigenBase<InputType>& matrix, bool computeEigenvectors = true);
299
304 eigen_assert(m_isInitialized && "EigenSolver is not initialized.");
305 return m_info;
306 }
307
310 m_realSchur.setMaxIterations(maxIters);
311 return *this;
312 }
313
315 Index getMaxIterations() const { return m_realSchur.getMaxIterations(); }
316
317 private:
318 EigenSolver& computeFromSchur(bool computeEigenvectors);
319 void doComputeEigenvectors();
320
321 protected:
322 static void check_template_parameters() {
323 EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar);
324 EIGEN_STATIC_ASSERT(!NumTraits<Scalar>::IsComplex, NUMERIC_TYPE_MUST_BE_REAL);
325 }
326
327 EigenvalueType m_eivalues;
328 bool m_isInitialized;
329 bool m_eigenvectorsOk;
330 ComputationInfo m_info;
331 // Holds the Schur form T and U of the last matrix; computing the eigenvectors overwrites T with the eigenvectors
332 // of T and U with the pseudo-eigenvectors.
333 RealSchur<MatrixType> m_realSchur;
334
335 using ColumnVectorType = Matrix<Scalar, ColsAtCompileTime, 1, Options & ~RowMajor, MaxColsAtCompileTime, 1>;
336 ColumnVectorType m_tmp;
337};
338
339template <typename MatrixType>
341 eigen_assert(m_isInitialized && "EigenSolver is not initialized.");
342 const Index n = m_eivalues.rows();
343 PlainMatrixType matD = PlainMatrixType::Zero(n, n);
344 Index i = 0;
345 for (; i < n - 1; ++i) {
346 RealScalar real = numext::real(m_eivalues.coeff(i));
347 RealScalar imag = numext::imag(m_eivalues.coeff(i));
348 matD.coeffRef(i, i) = real;
349 // The eigenvalue of a real scalar block has an exactly zero imaginary part, whatever the size of the real part.
350 if (!numext::is_exactly_zero(imag)) {
351 matD.coeffRef(i, i + 1) = imag;
352 matD.coeffRef(i + 1, i) = -imag;
353 matD.coeffRef(i + 1, i + 1) = real;
354 ++i;
355 }
356 }
357 if (i == n - 1) {
358 matD.coeffRef(i, i) = numext::real(m_eivalues.coeff(i));
359 }
360
361 return matD;
362}
363
364template <typename MatrixType>
366 eigen_assert(m_isInitialized && "EigenSolver is not initialized.");
367 eigen_assert(m_eigenvectorsOk && "The eigenvectors have not been computed together with the eigenvalues.");
368 const PlainMatrixType& eivec = m_realSchur.m_matU;
369 Index n = eivec.cols();
370 EigenvectorsType matV(n, n);
371 for (Index j = 0; j < n; ++j) {
372 if (numext::is_exactly_zero(numext::imag(m_eivalues.coeff(j))) || j + 1 == n) {
373 // we have a real eigen value
374 matV.col(j) = eivec.col(j).template cast<ComplexScalar>();
375 matV.col(j).normalize();
376 } else {
377 // we have a pair of complex eigen values
378 for (Index i = 0; i < n; ++i) {
379 matV.coeffRef(i, j) = ComplexScalar(eivec.coeff(i, j), eivec.coeff(i, j + 1));
380 matV.coeffRef(i, j + 1) = ComplexScalar(eivec.coeff(i, j), -eivec.coeff(i, j + 1));
381 }
382 matV.col(j).normalize();
383 matV.col(j + 1).normalize();
384 ++j;
385 }
386 }
387 return matV;
388}
389
390template <typename MatrixType>
391template <typename InputType>
393 bool computeEigenvectors) {
394 check_template_parameters();
395 EIGEN_INTERNAL_ASSERT_SQUARE(matrix);
396
397 // Reduce to real Schur form.
398 m_realSchur.compute(matrix.derived(), computeEigenvectors);
399 return computeFromSchur(computeEigenvectors);
400}
401
404template <typename MatrixType>
405EigenSolver<MatrixType>& EigenSolver<MatrixType>::computeFromSchur(bool computeEigenvectors) {
406 m_info = m_realSchur.info();
407
408 if (m_info == Success) {
409 const MatrixType& matT = m_realSchur.m_matT;
410 const Index n = matT.cols();
411
412 // Compute eigenvalues from matT
413 m_eivalues.resize(n);
414 Index i = 0;
415 while (i < n) {
416 if (i == n - 1 || matT.coeff(i + 1, i) == Scalar(0)) {
417 m_eivalues.coeffRef(i) = matT.coeff(i, i);
418 if (!(numext::isfinite)(m_eivalues.coeffRef(i))) {
419 m_isInitialized = true;
420 m_eigenvectorsOk = false;
421 m_info = NumericalIssue;
422 return *this;
423 }
424 ++i;
425 } else {
426 Scalar p = Scalar(0.5) * (matT.coeff(i, i) - matT.coeff(i + 1, i + 1));
427 Scalar z;
428 // Compute z = sqrt(abs(p * p + matT.coeff(i+1, i) * matT.coeff(i, i+1)));
429 // without overflow
430 {
431 Scalar t0 = matT.coeff(i + 1, i);
432 Scalar t1 = matT.coeff(i, i + 1);
433 Scalar maxval = numext::maxi<Scalar>(numext::abs(p), numext::maxi<Scalar>(numext::abs(t0), numext::abs(t1)));
434 t0 /= maxval;
435 t1 /= maxval;
436 Scalar p0 = p / maxval;
437 z = maxval * numext::sqrt(numext::abs(p0 * p0 + t0 * t1));
438 }
439
440 m_eivalues.coeffRef(i) = ComplexScalar(matT.coeff(i + 1, i + 1) + p, z);
441 m_eivalues.coeffRef(i + 1) = ComplexScalar(matT.coeff(i + 1, i + 1) + p, -z);
442 if (!((numext::isfinite)(m_eivalues.coeffRef(i)) && (numext::isfinite)(m_eivalues.coeffRef(i + 1)))) {
443 m_isInitialized = true;
444 m_eigenvectorsOk = false;
445 m_info = NumericalIssue;
446 return *this;
447 }
448 i += 2;
449 }
450 }
451
452 // Compute eigenvectors.
453 if (computeEigenvectors) doComputeEigenvectors();
454 } else if (!m_realSchur.m_matT.allFinite()) {
455 // RealSchur reports both nonfinite input and iteration exhaustion as NoConvergence.
456 m_info = NumericalIssue;
457 }
458
459 m_isInitialized = true;
460 m_eigenvectorsOk = computeEigenvectors;
461
462 return *this;
463}
464
465template <typename MatrixType>
466void EigenSolver<MatrixType>::doComputeEigenvectors() {
467 // Back-substitution stores the eigenvectors of T over T itself; the back-transformation then turns U into the
468 // pseudo-eigenvectors in place, column by column from the last one.
469 MatrixType& matT = m_realSchur.m_matT;
470 PlainMatrixType& eivec = m_realSchur.m_matU;
471 const Index size = eivec.cols();
472 const Scalar eps = NumTraits<Scalar>::epsilon();
473
474 Scalar norm = internal::hessenberg_abs_sum<Upper>(matT);
475
476 // Backsubstitute to find vectors of upper triangular form
477 if (norm == Scalar(0)) {
478 return;
479 }
480
481 // The back-substitution squares and multiplies entries of T, which overflows or underflows once the entries are
482 // outside about [sqrt(min/eps), sqrt(max/(8n))]. The eigenvectors of T are those of T/s for a power of two s, so
483 // scale T and the eigenvalues together. Since max|t_ij| <= norm <= n^2 max|t_ij|, the test below is a cheap
484 // sufficient condition and the ordinary case does no further work.
485 const Scalar safeMin = numext::sqrt((std::numeric_limits<Scalar>::min)() / eps);
486 const Scalar safeMax = numext::sqrt(NumTraits<Scalar>::highest() / Scalar(8 * size));
487 EigenvalueType scaledEivalues;
488 bool scaled = false;
489 if (!(norm <= safeMax && norm >= Scalar(size) * Scalar(size) * safeMin)) {
490 Scalar maxCoeff(0);
491 for (Index j = 0; j < size; ++j)
492 maxCoeff = numext::maxi(maxCoeff, matT.col(j).head(numext::mini(j + 2, size)).cwiseAbs().maxCoeff());
493 const auto factors = internal::safe_scaling<Scalar>::scale_in_place(matT, maxCoeff);
494 scaledEivalues = m_eivalues;
495 internal::safe_scaling<Scalar>::scale_in_place(scaledEivalues, maxCoeff, factors);
496 norm = internal::hessenberg_abs_sum<Upper>(matT);
497 scaled = true;
498 }
499 const EigenvalueType& eivalues = scaled ? scaledEivalues : m_eivalues;
500
501 for (Index n = size - 1; n >= 0; n--) {
502 Scalar p = eivalues.coeff(n).real();
503 Scalar q = eivalues.coeff(n).imag();
504
505 // Scalar vector
506 if (q == Scalar(0)) {
507 Scalar lastr(0), lastw(0);
508 Index l = n;
509
510 matT.coeffRef(n, n) = Scalar(1);
511 for (Index i = n - 1; i >= 0; i--) {
512 Scalar w = matT.coeff(i, i) - p;
513 Scalar r = matT.row(i).segment(l, n - l + 1).dot(matT.col(n).segment(l, n - l + 1));
514
515 if (eivalues.coeff(i).imag() < Scalar(0)) {
516 lastw = w;
517 lastr = r;
518 } else {
519 l = i;
520 if (eivalues.coeff(i).imag() == Scalar(0)) {
521 const Scalar divisor = w != Scalar(0) ? w : eps * norm;
522 // |r / divisor| > max would overflow the component. The column is determined up to a factor, so scale
523 // the components computed so far, and r with them, by f = |divisor| / |r| to make |x_i| = 1. The scaled
524 // r is sign(r) |divisor| by construction; assign it, since r *= f gives 0 when f underflows (a subnormal
525 // divisor) and the column would be zeroed.
526 if (numext::abs(r) > numext::abs(divisor) * NumTraits<Scalar>::highest() && (numext::isfinite)(r)) {
527 const Scalar f = numext::abs(divisor) / numext::abs(r);
528 matT.col(n).tail(size - i - 1) *= f;
529 r = r < Scalar(0) ? -numext::abs(divisor) : numext::abs(divisor);
530 }
531 matT.coeffRef(i, n) = -r / divisor;
532 } else // Solve real equations
533 {
534 Scalar x = matT.coeff(i, i + 1);
535 Scalar y = matT.coeff(i + 1, i);
536 Scalar denom = (eivalues.coeff(i).real() - p) * (eivalues.coeff(i).real() - p) +
537 eivalues.coeff(i).imag() * eivalues.coeff(i).imag();
538 Scalar t = (x * lastr - lastw * r) / denom;
539 matT.coeffRef(i, n) = t;
540 if (numext::abs(x) > numext::abs(lastw))
541 matT.coeffRef(i + 1, n) = (-r - w * t) / x;
542 else
543 matT.coeffRef(i + 1, n) = (-lastr - y * t) / lastw;
544 }
545
546 // Overflow control
547 Scalar t = numext::abs(matT.coeff(i, n));
548 if ((eps * t) * t > Scalar(1)) matT.col(n).tail(size - i) /= t;
549 }
550 }
551 } else if (q < Scalar(0) && n > 0) // Complex vector
552 {
553 Scalar lastra(0), lastsa(0), lastw(0);
554 Index l = n - 1;
555
556 // Last vector component imaginary so matrix is triangular
557 if (numext::abs(matT.coeff(n, n - 1)) > numext::abs(matT.coeff(n - 1, n))) {
558 matT.coeffRef(n - 1, n - 1) = q / matT.coeff(n, n - 1);
559 matT.coeffRef(n - 1, n) = -(matT.coeff(n, n) - p) / matT.coeff(n, n - 1);
560 } else {
561 ComplexScalar cc =
562 ComplexScalar(Scalar(0), -matT.coeff(n - 1, n)) / ComplexScalar(matT.coeff(n - 1, n - 1) - p, q);
563 matT.coeffRef(n - 1, n - 1) = numext::real(cc);
564 matT.coeffRef(n - 1, n) = numext::imag(cc);
565 }
566 matT.coeffRef(n, n - 1) = Scalar(0);
567 matT.coeffRef(n, n) = Scalar(1);
568 for (Index i = n - 2; i >= 0; i--) {
569 Scalar ra = matT.row(i).segment(l, n - l + 1).dot(matT.col(n - 1).segment(l, n - l + 1));
570 Scalar sa = matT.row(i).segment(l, n - l + 1).dot(matT.col(n).segment(l, n - l + 1));
571 Scalar w = matT.coeff(i, i) - p;
572
573 if (eivalues.coeff(i).imag() < Scalar(0)) {
574 lastw = w;
575 lastra = ra;
576 lastsa = sa;
577 } else {
578 l = i;
579 if (eivalues.coeff(i).imag() == RealScalar(0)) {
580 ComplexScalar cc = ComplexScalar(-ra, -sa) / ComplexScalar(w, q);
581 matT.coeffRef(i, n - 1) = numext::real(cc);
582 matT.coeffRef(i, n) = numext::imag(cc);
583 } else {
584 // Solve complex equations
585 Scalar x = matT.coeff(i, i + 1);
586 Scalar y = matT.coeff(i + 1, i);
587 Scalar vr = (eivalues.coeff(i).real() - p) * (eivalues.coeff(i).real() - p) +
588 eivalues.coeff(i).imag() * eivalues.coeff(i).imag() - q * q;
589 Scalar vi = (eivalues.coeff(i).real() - p) * Scalar(2) * q;
590 if ((vr == Scalar(0)) && (vi == Scalar(0)))
591 vr =
592 eps * norm * (numext::abs(w) + numext::abs(q) + numext::abs(x) + numext::abs(y) + numext::abs(lastw));
593
594 ComplexScalar cc = ComplexScalar(x * lastra - lastw * ra + q * sa, x * lastsa - lastw * sa - q * ra) /
595 ComplexScalar(vr, vi);
596 matT.coeffRef(i, n - 1) = numext::real(cc);
597 matT.coeffRef(i, n) = numext::imag(cc);
598 if (numext::abs(x) > (numext::abs(lastw) + numext::abs(q))) {
599 matT.coeffRef(i + 1, n - 1) = (-ra - w * matT.coeff(i, n - 1) + q * matT.coeff(i, n)) / x;
600 matT.coeffRef(i + 1, n) = (-sa - w * matT.coeff(i, n) - q * matT.coeff(i, n - 1)) / x;
601 } else {
602 cc = ComplexScalar(-lastra - y * matT.coeff(i, n - 1), -lastsa - y * matT.coeff(i, n)) /
603 ComplexScalar(lastw, q);
604 matT.coeffRef(i + 1, n - 1) = numext::real(cc);
605 matT.coeffRef(i + 1, n) = numext::imag(cc);
606 }
607 }
608
609 // Overflow control
610 Scalar t = numext::maxi<Scalar>(numext::abs(matT.coeff(i, n - 1)), numext::abs(matT.coeff(i, n)));
611 if ((eps * t) * t > Scalar(1)) matT.block(i, n - 1, size - i, 2) /= t;
612 }
613 }
614
615 // We handled a pair of complex conjugate eigenvalues, so need to skip them both
616 n--;
617 } else {
618 eigen_assert(0 && "Internal bug in EigenSolver (INF or NaN has not been detected)"); // this should not happen
619 }
620 }
621
622 // Back transformation to get eigenvectors of original matrix
623 for (Index j = size - 1; j >= 0; j--) {
624 m_tmp.noalias() = eivec.leftCols(j + 1) * matT.col(j).segment(0, j + 1);
625 eivec.col(j) = m_tmp;
626 }
627}
628
629} // end namespace Eigen
630
631#endif // EIGEN_EIGENSOLVER_H
Computes eigenvalues and eigenvectors of general matrices.
Definition EigenSolver.h:69
EigenSolver(const EigenBase< InputType > &matrix, bool computeEigenvectors=true)
Constructor; computes eigendecomposition of given matrix.
Definition EigenSolver.h:149
PlainMatrixType pseudoEigenvalueMatrix() const
Returns the block-diagonal matrix in the pseudo-eigendecomposition.
Definition EigenSolver.h:340
EigenSolver(EigenBase< InputType > &matrix, bool computeEigenvectors=true)
Constructor for inplace decomposition .
Definition EigenSolver.h:171
typename MatrixType::Scalar Scalar
Scalar type for matrices of type MatrixType.
Definition EigenSolver.h:83
EigenSolver(Index size)
Default constructor with memory preallocation.
Definition EigenSolver.h:130
Matrix< ComplexScalar, ColsAtCompileTime, 1, Options &~RowMajor, MaxColsAtCompileTime, 1 > EigenvalueType
Type for vector of eigenvalues as returned by eigenvalues().
Definition EigenSolver.h:105
ComputationInfo info() const
Definition EigenSolver.h:303
EigenvectorsType eigenvectors() const
Returns the eigenvectors of given matrix.
Definition EigenSolver.h:365
EigenSolver()
Default constructor.
Definition EigenSolver.h:122
EigenSolver & setMaxIterations(Index maxIters)
Sets the maximum number of iterations allowed.
Definition EigenSolver.h:309
const PlainMatrixType & pseudoEigenvectors() const
Returns the pseudo-eigenvectors of given matrix.
Definition EigenSolver.h:221
Index getMaxIterations() const
Returns the maximum number of iterations.
Definition EigenSolver.h:315
Matrix< ComplexScalar, RowsAtCompileTime, ColsAtCompileTime, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime > EigenvectorsType
Type for matrix of eigenvectors as returned by eigenvectors().
Definition EigenSolver.h:112
EigenSolver & compute(const EigenBase< InputType > &matrix, bool computeEigenvectors=true)
Computes eigendecomposition of given matrix.
MatrixType_ MatrixType
Synonym for the template parameter MatrixType_.
Definition EigenSolver.h:72
internal::make_complex_t< Scalar > ComplexScalar
Complex scalar type for MatrixType.
Definition EigenSolver.h:98
const EigenvalueType & eigenvalues() const
Returns the eigenvalues of given matrix.
Definition EigenSolver.h:265
Eigen::Index Index
Definition EigenSolver.h:85
Matrix< Scalar, RowsAtCompileTime, ColsAtCompileTime, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime > PlainMatrixType
Plain matrix type with the shape and storage options of MatrixType; MatrixType itself unless that is ...
Definition EigenSolver.h:89
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
constexpr Scalar & coeffRef(Index rowId, Index colId)
Definition PlainObjectBase.h:218
constexpr const Scalar & coeff(Index rowId, Index colId) const
Definition PlainObjectBase.h:200
ComputationInfo
Definition Constants.h:455
@ NumericalIssue
Definition Constants.h:459
@ Success
Definition Constants.h:457
Definition EigenBase.h:34
constexpr Derived & derived()
Definition EigenBase.h:50