Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
MatrixPower.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2012, 2013 Chen-Pang He <jdh8@ms63.hinet.net>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_MATRIX_POWER
12#define EIGEN_MATRIX_POWER
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19template <typename MatrixType>
20class MatrixPower;
21
35/* TODO: This class is only used by MatrixPower, so it should be nested
36 * into MatrixPower, like MatrixPower::ReturnValue. However, my
37 * compiler complained about unused template parameter in the
38 * following declaration in namespace internal.
39 *
40 * template<typename MatrixType>
41 * struct traits<MatrixPower<MatrixType>::ReturnValue>;
42 */
43template <typename MatrixType>
44class MatrixPowerParenthesesReturnValue : public ReturnByValue<MatrixPowerParenthesesReturnValue<MatrixType> > {
45 public:
46 typedef typename MatrixType::RealScalar RealScalar;
47
54 MatrixPowerParenthesesReturnValue(MatrixPower<MatrixType>& pow, RealScalar p) : m_pow(pow), m_p(p) {}
55
61 template <typename ResultType>
62 inline void evalTo(ResultType& result) const {
63 m_pow.compute(result, m_p);
64 }
65
66 Index rows() const { return m_pow.rows(); }
67 Index cols() const { return m_pow.cols(); }
68
69 private:
70 MatrixPower<MatrixType>& m_pow;
71 const RealScalar m_p;
72};
73
89template <typename MatrixType>
90class MatrixPowerAtomic {
91 private:
92 enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime };
93 typedef typename MatrixType::Scalar Scalar;
94 typedef typename MatrixType::RealScalar RealScalar;
95 typedef internal::make_complex_t<Scalar> ComplexScalar;
96 typedef Block<MatrixType, Dynamic, Dynamic> ResultType;
97
98 const MatrixType& m_A;
99 RealScalar m_p;
100
101 void computePade(int degree, const MatrixType& IminusT, ResultType& res) const;
102 void compute2x2(ResultType& res, RealScalar p) const;
103 void computeBig(ResultType& res) const;
104 static int getPadeDegree(float normIminusT);
105 static int getPadeDegree(double normIminusT);
106 static int getPadeDegree(long double normIminusT);
107 static ComplexScalar computeSuperDiag(const ComplexScalar&, const ComplexScalar&, RealScalar p);
108 static RealScalar computeSuperDiag(RealScalar, RealScalar, RealScalar p);
109
110 public:
111 MatrixPowerAtomic(const MatrixPowerAtomic&) = delete;
112 MatrixPowerAtomic& operator=(const MatrixPowerAtomic&) = delete;
113
125 MatrixPowerAtomic(const MatrixType& T, RealScalar p);
126
133 void compute(ResultType& res) const;
134};
135
136template <typename MatrixType>
137MatrixPowerAtomic<MatrixType>::MatrixPowerAtomic(const MatrixType& T, RealScalar p) : m_A(T), m_p(p) {
138 eigen_assert(T.rows() == T.cols());
139 eigen_assert(p > -1 && p < 1);
140}
141
142template <typename MatrixType>
143void MatrixPowerAtomic<MatrixType>::compute(ResultType& res) const {
144 using std::pow;
145 switch (m_A.rows()) {
146 case 0:
147 break;
148 case 1:
149 res(0, 0) = pow(m_A(0, 0), m_p);
150 break;
151 case 2:
152 compute2x2(res, m_p);
153 break;
154 default:
155 computeBig(res);
156 }
157}
158
159template <typename MatrixType>
160void MatrixPowerAtomic<MatrixType>::computePade(int degree, const MatrixType& IminusT, ResultType& res) const {
161 int i = 2 * degree;
162 res = (m_p - RealScalar(degree)) / RealScalar(2 * i - 2) * IminusT;
163
164 for (--i; i; --i) {
165 res = (MatrixType::Identity(IminusT.rows(), IminusT.cols()) + res)
166 .template triangularView<Upper>()
167 .solve((i == 1 ? -m_p
168 : i & 1 ? (-m_p - RealScalar(i / 2)) / RealScalar(2 * i)
169 : (m_p - RealScalar(i / 2)) / RealScalar(2 * i - 2)) *
170 IminusT)
171 .eval();
172 }
173 res += MatrixType::Identity(IminusT.rows(), IminusT.cols());
174}
175
176// This function assumes that res has the correct size (see bug 614)
177template <typename MatrixType>
178void MatrixPowerAtomic<MatrixType>::compute2x2(ResultType& res, RealScalar p) const {
179 using std::abs;
180 using std::pow;
181 res.coeffRef(0, 0) = pow(m_A.coeff(0, 0), p);
182
183 for (Index i = 1; i < m_A.cols(); ++i) {
184 res.coeffRef(i, i) = pow(m_A.coeff(i, i), p);
185 Scalar a = m_A.coeff(i - 1, i - 1);
186 Scalar b = m_A.coeff(i, i);
187 Scalar diff = b - a;
188 // Use the derivative formula when eigenvalues are nearly equal to avoid
189 // catastrophic cancellation in the difference quotient.
190 if (abs(diff) <= RealScalar(2) * (std::numeric_limits<RealScalar>::epsilon)() * (std::max)(abs(a), abs(b)))
191 res.coeffRef(i - 1, i) = p * pow(b, p - 1);
192 else if (2 * abs(a) < abs(b) || 2 * abs(b) < abs(a))
193 res.coeffRef(i - 1, i) = (res.coeff(i, i) - res.coeff(i - 1, i - 1)) / diff;
194 else
195 res.coeffRef(i - 1, i) = computeSuperDiag(b, a, p);
196 res.coeffRef(i - 1, i) *= m_A.coeff(i - 1, i);
197 }
198}
199
200template <typename MatrixType>
201void MatrixPowerAtomic<MatrixType>::computeBig(ResultType& res) const {
202 using std::ldexp;
203 const int digits = std::numeric_limits<RealScalar>::digits;
204 const RealScalar maxNormForPade =
205 RealScalar(digits <= 24 ? 4.3386528e-1L // single precision
206 : digits <= 53 ? 2.789358995219730e-1L // double precision
207 : digits <= 64 ? 2.4471944416607995472e-1L // extended precision
208 : digits <= 106 ? 1.1016843812851143391275867258512e-1L // double-double
209 : 9.134603732914548552537150753385375e-2L); // quadruple precision
210 MatrixType IminusT, sqrtT, T = m_A.template triangularView<Upper>();
211 RealScalar normIminusT;
212 int degree, degree2, numberOfSquareRoots = 0;
213 bool hasExtraSquareRoot = false;
214
215 for (Index i = 0; i < m_A.cols(); ++i) eigen_assert(m_A(i, i) != RealScalar(0));
216
217 while (true) {
218 IminusT = MatrixType::Identity(m_A.rows(), m_A.cols()) - T;
219 normIminusT = IminusT.cwiseAbs().colwise().sum().maxCoeff();
220 if (normIminusT < maxNormForPade) {
221 degree = getPadeDegree(normIminusT);
222 degree2 = getPadeDegree(normIminusT / 2);
223 if (degree - degree2 <= 1 || hasExtraSquareRoot) break;
224 hasExtraSquareRoot = true;
225 }
226 matrix_sqrt_triangular(T, sqrtT);
227 T = sqrtT.template triangularView<Upper>();
228 ++numberOfSquareRoots;
229 }
230 computePade(degree, IminusT, res);
231
232 for (; numberOfSquareRoots; --numberOfSquareRoots) {
233 compute2x2(res, ldexp(m_p, -numberOfSquareRoots));
234 res = res.template triangularView<Upper>() * res;
235 }
236 compute2x2(res, m_p);
237}
238
239template <typename MatrixType>
240inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(float normIminusT) {
241 const float maxNormForPade[] = {2.8064004e-1f /* degree = 3 */, 4.3386528e-1f};
242 int degree = 3;
243 for (; degree <= 4; ++degree)
244 if (normIminusT <= maxNormForPade[degree - 3]) break;
245 return degree;
246}
247
248template <typename MatrixType>
249inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(double normIminusT) {
250 const double maxNormForPade[] = {1.884160592658218e-2 /* degree = 3 */, 6.038881904059573e-2, 1.239917516308172e-1,
251 1.999045567181744e-1, 2.789358995219730e-1};
252 int degree = 3;
253 for (; degree <= 7; ++degree)
254 if (normIminusT <= maxNormForPade[degree - 3]) break;
255 return degree;
256}
257
258template <typename MatrixType>
259inline int MatrixPowerAtomic<MatrixType>::getPadeDegree(long double normIminusT) {
260#if LDBL_MANT_DIG == 53
261 const int maxPadeDegree = 7;
262 const double maxNormForPade[] = {1.884160592658218e-2L /* degree = 3 */, 6.038881904059573e-2L, 1.239917516308172e-1L,
263 1.999045567181744e-1L, 2.789358995219730e-1L};
264#elif LDBL_MANT_DIG <= 64
265 const int maxPadeDegree = 8;
266 const long double maxNormForPade[] = {6.3854693117491799460e-3L /* degree = 3 */,
267 2.6394893435456973676e-2L,
268 6.4216043030404063729e-2L,
269 1.1701165502926694307e-1L,
270 1.7904284231268670284e-1L,
271 2.4471944416607995472e-1L};
272#elif LDBL_MANT_DIG <= 106
273 const int maxPadeDegree = 10;
274 const double maxNormForPade[] = {1.0007161601787493236741409687186e-4L /* degree = 3 */,
275 1.0007161601787493236741409687186e-3L,
276 4.7069769360887572939882574746264e-3L,
277 1.3220386624169159689406653101695e-2L,
278 2.8063482381631737920612944054906e-2L,
279 4.9625993951953473052385361085058e-2L,
280 7.7367040706027886224557538328171e-2L,
281 1.1016843812851143391275867258512e-1L};
282#else
283 const int maxPadeDegree = 10;
284 const double maxNormForPade[] = {5.524506147036624377378713555116378e-5L /* degree = 3 */,
285 6.640600568157479679823602193345995e-4L,
286 3.227716520106894279249709728084626e-3L,
287 9.619593944683432960546978734646284e-3L,
288 2.134595382433742403911124458161147e-2L,
289 3.908166513900489428442993794761185e-2L,
290 6.266780814639442865832535460550138e-2L,
291 9.134603732914548552537150753385375e-2L};
292#endif
293 int degree = 3;
294 for (; degree <= maxPadeDegree; ++degree)
295 if (normIminusT <= static_cast<long double>(maxNormForPade[degree - 3])) break;
296 return degree;
297}
298
299template <typename MatrixType>
300inline typename MatrixPowerAtomic<MatrixType>::ComplexScalar MatrixPowerAtomic<MatrixType>::computeSuperDiag(
301 const ComplexScalar& curr, const ComplexScalar& prev, RealScalar p) {
302 using std::ceil;
303 using std::exp;
304 using std::log;
305 using std::sinh;
306
307 ComplexScalar logCurr = log(curr);
308 ComplexScalar logPrev = log(prev);
309 RealScalar unwindingNumber =
310 ceil((numext::imag(logCurr - logPrev) - RealScalar(EIGEN_PI)) / RealScalar(2 * EIGEN_PI));
311 ComplexScalar w =
312 numext::log1p((curr - prev) / prev) / RealScalar(2) + ComplexScalar(0, RealScalar(EIGEN_PI) * unwindingNumber);
313 return RealScalar(2) * exp(RealScalar(0.5) * p * (logCurr + logPrev)) * sinh(p * w) / (curr - prev);
314}
315
316template <typename MatrixType>
317inline typename MatrixPowerAtomic<MatrixType>::RealScalar MatrixPowerAtomic<MatrixType>::computeSuperDiag(
318 RealScalar curr, RealScalar prev, RealScalar p) {
319 using std::exp;
320 using std::log;
321 using std::sinh;
322
323 RealScalar w = numext::log1p((curr - prev) / prev) / RealScalar(2);
324 return 2 * exp(p * (log(curr) + log(prev)) / 2) * sinh(p * w) / (curr - prev);
325}
326
346template <typename MatrixType>
347class MatrixPower {
348 private:
349 typedef typename MatrixType::Scalar Scalar;
350 typedef typename MatrixType::RealScalar RealScalar;
351
352 public:
353 MatrixPower(const MatrixPower&) = delete;
354 MatrixPower& operator=(const MatrixPower&) = delete;
355
364 explicit MatrixPower(const MatrixType& A) : m_A(A), m_conditionNumber(0), m_rank(A.cols()), m_nulls(0) {
365 eigen_assert(A.rows() == A.cols());
366 }
367
378
386 template <typename ResultType>
387 void compute(ResultType& res, RealScalar p);
388
389 Index rows() const { return m_A.rows(); }
390 Index cols() const { return m_A.cols(); }
391
392 private:
393 typedef internal::make_complex_t<Scalar> ComplexScalar;
394 typedef Matrix<ComplexScalar, Dynamic, Dynamic, 0, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime>
395 ComplexMatrix;
396
398 typename MatrixType::Nested m_A;
399
401 MatrixType m_tmp;
402
404 ComplexMatrix m_T, m_U;
405
407 ComplexMatrix m_fT;
408
415 RealScalar m_conditionNumber;
416
418 Index m_rank;
419
421 Index m_nulls;
422
432 void split(RealScalar& p, RealScalar& intpart);
433
435 void initialize();
436
437 template <typename ResultType>
438 void computeIntPower(ResultType& res, RealScalar p);
439
440 template <typename ResultType>
441 void computeFracPower(ResultType& res, RealScalar p);
442
443 template <int Rows, int Cols, int Options, int MaxRows, int MaxCols>
444 static void revertSchur(Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T,
445 const ComplexMatrix& U);
446
447 template <int Rows, int Cols, int Options, int MaxRows, int MaxCols>
448 static void revertSchur(Matrix<RealScalar, Rows, Cols, Options, MaxRows, MaxCols>& res, const ComplexMatrix& T,
449 const ComplexMatrix& U);
450};
451
452template <typename MatrixType>
453template <typename ResultType>
454void MatrixPower<MatrixType>::compute(ResultType& res, RealScalar p) {
455 using std::pow;
456 switch (cols()) {
457 case 0:
458 break;
459 case 1:
460 res(0, 0) = pow(m_A.coeff(0, 0), p);
461 break;
462 default:
463 RealScalar intpart;
464 split(p, intpart);
465
466 res = MatrixType::Identity(rows(), cols());
467 computeIntPower(res, intpart);
468 if (p) computeFracPower(res, p);
469 }
470}
471
472template <typename MatrixType>
473void MatrixPower<MatrixType>::split(RealScalar& p, RealScalar& intpart) {
474 using std::floor;
475 using std::pow;
476
477 intpart = floor(p);
478 p -= intpart;
479
480 // Perform Schur decomposition if it is not yet performed and the power is
481 // not an integer.
482 if (!m_conditionNumber && p) initialize();
483
484 // Choose the more stable of intpart = floor(p) and intpart = ceil(p).
485 if (p > RealScalar(0.5) && p > (1 - p) * pow(m_conditionNumber, p)) {
486 --p;
487 ++intpart;
488 }
489}
490
491template <typename MatrixType>
492void MatrixPower<MatrixType>::initialize() {
493 const ComplexSchur<MatrixType> schurOfA(m_A);
495 ComplexScalar eigenvalue;
496
497 m_fT.resizeLike(m_A);
498 m_T = schurOfA.matrixT();
499 m_U = schurOfA.matrixU();
500 m_conditionNumber = m_T.diagonal().array().abs().maxCoeff() / m_T.diagonal().array().abs().minCoeff();
501
502 // Move zero eigenvalues to the bottom right corner.
503 for (Index i = cols() - 1; i >= 0; --i) {
504 if (m_rank <= 2) return;
505 if (m_T.coeff(i, i) == RealScalar(0)) {
506 for (Index j = i + 1; j < m_rank; ++j) {
507 eigenvalue = m_T.coeff(j, j);
508 rot.makeGivens(m_T.coeff(j - 1, j), eigenvalue);
509 m_T.applyOnTheRight(j - 1, j, rot);
510 m_T.applyOnTheLeft(j - 1, j, rot.adjoint());
511 m_T.coeffRef(j - 1, j - 1) = eigenvalue;
512 m_T.coeffRef(j, j) = RealScalar(0);
513 m_U.applyOnTheRight(j - 1, j, rot);
514 }
515 --m_rank;
516 }
517 }
518
519 m_nulls = rows() - m_rank;
520 if (m_nulls) {
521 eigen_assert(m_T.bottomRightCorner(m_nulls, m_nulls).isZero() &&
522 "Base of matrix power should be invertible or with a semisimple zero eigenvalue.");
523 m_fT.bottomRows(m_nulls).fill(RealScalar(0));
524 }
525}
526
527template <typename MatrixType>
528template <typename ResultType>
529void MatrixPower<MatrixType>::computeIntPower(ResultType& res, RealScalar p) {
530 using std::abs;
531 using std::fmod;
532 RealScalar pp = abs(p);
533
534 if (p < 0)
535 m_tmp = m_A.inverse();
536 else
537 m_tmp = m_A;
538
539 while (true) {
540 if (fmod(pp, 2) >= 1) res = m_tmp * res;
541 pp /= 2;
542 if (pp < 1) break;
543 m_tmp *= m_tmp;
544 }
545}
546
547template <typename MatrixType>
548template <typename ResultType>
549void MatrixPower<MatrixType>::computeFracPower(ResultType& res, RealScalar p) {
550 Block<ComplexMatrix, Dynamic, Dynamic> blockTp(m_fT, 0, 0, m_rank, m_rank);
551 eigen_assert(m_conditionNumber);
552 eigen_assert(m_rank + m_nulls == rows());
553
554 MatrixPowerAtomic<ComplexMatrix>(m_T.topLeftCorner(m_rank, m_rank), p).compute(blockTp);
555 if (m_nulls) {
556 m_fT.topRightCorner(m_rank, m_nulls) = m_T.topLeftCorner(m_rank, m_rank)
557 .template triangularView<Upper>()
558 .solve(blockTp * m_T.topRightCorner(m_rank, m_nulls));
559 }
560 revertSchur(m_tmp, m_fT, m_U);
561 res = m_tmp * res;
562}
563
564template <typename MatrixType>
565template <int Rows, int Cols, int Options, int MaxRows, int MaxCols>
566inline void MatrixPower<MatrixType>::revertSchur(Matrix<ComplexScalar, Rows, Cols, Options, MaxRows, MaxCols>& res,
567 const ComplexMatrix& T, const ComplexMatrix& U) {
568 res.noalias() = U * (T.template triangularView<Upper>() * U.adjoint());
569}
570
571template <typename MatrixType>
572template <int Rows, int Cols, int Options, int MaxRows, int MaxCols>
573inline void MatrixPower<MatrixType>::revertSchur(Matrix<RealScalar, Rows, Cols, Options, MaxRows, MaxCols>& res,
574 const ComplexMatrix& T, const ComplexMatrix& U) {
575 res.noalias() = (U * (T.template triangularView<Upper>() * U.adjoint())).real();
576}
577
591template <typename Derived>
592class MatrixPowerReturnValue : public ReturnByValue<MatrixPowerReturnValue<Derived> > {
593 public:
594 typedef typename Derived::PlainObject PlainObject;
595 typedef typename Derived::RealScalar RealScalar;
596
603 MatrixPowerReturnValue(const Derived& A, RealScalar p) : m_A(A), m_p(p) {}
604
611 template <typename ResultType>
612 inline void evalTo(ResultType& result) const {
613 MatrixPower<PlainObject>(m_A.eval()).compute(result, m_p);
614 }
615
616 Index rows() const { return m_A.rows(); }
617 Index cols() const { return m_A.cols(); }
618
619 private:
620 const Derived& m_A;
621 const RealScalar m_p;
622};
623
637template <typename Derived>
638class MatrixComplexPowerReturnValue : public ReturnByValue<MatrixComplexPowerReturnValue<Derived> > {
639 public:
640 typedef typename Derived::PlainObject PlainObject;
641 typedef internal::make_complex_t<typename Derived::Scalar> ComplexScalar;
642
649 MatrixComplexPowerReturnValue(const Derived& A, const ComplexScalar& p) : m_A(A), m_p(p) {}
650
660 template <typename ResultType>
661 inline void evalTo(ResultType& result) const {
662 result = (m_p * m_A.log()).exp();
663 }
664
665 Index rows() const { return m_A.rows(); }
666 Index cols() const { return m_A.cols(); }
667
668 private:
669 const Derived& m_A;
670 const ComplexScalar m_p;
671};
672
673namespace internal {
674
675template <typename MatrixPowerType>
676struct traits<MatrixPowerParenthesesReturnValue<MatrixPowerType> > {
677 typedef typename MatrixPowerType::PlainObject ReturnType;
678};
679
680template <typename Derived>
681struct traits<MatrixPowerReturnValue<Derived> > {
682 typedef typename Derived::PlainObject ReturnType;
683};
684
685template <typename Derived>
686struct traits<MatrixComplexPowerReturnValue<Derived> > {
687 typedef typename Derived::PlainObject ReturnType;
688};
689
690} // namespace internal
691
692template <typename Derived>
693const MatrixPowerReturnValue<Derived> MatrixBase<Derived>::pow(const RealScalar& p) const {
694 return MatrixPowerReturnValue<Derived>(derived(), p);
695}
696
697template <typename Derived>
698const MatrixComplexPowerReturnValue<Derived> MatrixBase<Derived>::pow(const internal::make_complex_t<Scalar>& p) const {
699 return MatrixComplexPowerReturnValue<Derived>(derived(), p);
700}
701
702} // namespace Eigen
703
704#endif // EIGEN_MATRIX_POWER
const MatrixComplexPowerReturnValue< Derived > pow(const internal::make_complex_t< Scalar > &p) const
Definition MatrixPower.h:698
Proxy for the matrix power of some matrix (expression).
Definition MatrixPower.h:638
MatrixComplexPowerReturnValue(const Derived &A, const ComplexScalar &p)
Constructor.
Definition MatrixPower.h:649
void evalTo(ResultType &result) const
Compute the matrix power.
Definition MatrixPower.h:661
Class for computing matrix powers.
Definition MatrixPower.h:90
void compute(ResultType &res) const
Compute the matrix power.
Definition MatrixPower.h:143
Proxy for the matrix power of some matrix.
Definition MatrixPower.h:44
MatrixPowerParenthesesReturnValue(MatrixPower< MatrixType > &pow, RealScalar p)
Constructor.
Definition MatrixPower.h:54
void evalTo(ResultType &result) const
Compute the matrix power.
Definition MatrixPower.h:62
Proxy for the matrix power of some matrix (expression).
Definition MatrixPower.h:592
MatrixPowerReturnValue(const Derived &A, RealScalar p)
Constructor.
Definition MatrixPower.h:603
void evalTo(ResultType &result) const
Compute the matrix power.
Definition MatrixPower.h:612
Class for computing matrix powers.
Definition MatrixPower.h:347
MatrixPower(const MatrixType &A)
Constructor.
Definition MatrixPower.h:364
const MatrixPowerParenthesesReturnValue< MatrixType > operator()(RealScalar p)
Returns the matrix power.
Definition MatrixPower.h:375
void compute(ResultType &res, RealScalar p)
Compute the matrix power.
Definition MatrixPower.h:454
void matrix_sqrt_triangular(const MatrixType &arg, ResultType &result)
Compute matrix square root of triangular matrix.
Definition MatrixSquareRoot.h:194
Namespace containing all symbols from the Eigen library.