Eigen  5.0.1
 
Loading...
Searching...
No Matches
DGMRES.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
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_DGMRES_H
12#define EIGEN_DGMRES_H
13
14#include "../../Eigenvalues"
15
16// IWYU pragma: private
17#include "./InternalHeaderCheck.h"
18
19namespace Eigen {
20
21template <typename MatrixType_, typename Preconditioner_ = DiagonalPreconditioner<typename MatrixType_::Scalar> >
22class DGMRES;
23
24namespace internal {
25
26template <typename MatrixType_, typename Preconditioner_>
27struct traits<DGMRES<MatrixType_, Preconditioner_> > {
28 using MatrixType = MatrixType_;
29 using Preconditioner = Preconditioner_;
30};
31
40template <typename VectorType, typename IndexType>
41void sortWithPermutation(VectorType& vec, IndexType& perm, typename IndexType::Scalar& ncut) {
42 eigen_assert(vec.size() == perm.size());
43 for (Index k = 0; k < ncut; k++) {
44 bool flag = false;
45 for (Index j = 0; j < vec.size() - 1; j++) {
46 if (vec(perm(j)) < vec(perm(j + 1))) {
47 std::swap(perm(j), perm(j + 1));
48 flag = true;
49 }
50 if (!flag) break; // The vector is in sorted order
51 }
52 }
53}
54
55} // namespace internal
97template <typename MatrixType_, typename Preconditioner_>
98class DGMRES : public IterativeSolverBase<DGMRES<MatrixType_, Preconditioner_> > {
99 protected:
100 using Base = IterativeSolverBase<DGMRES>;
101 using Base::m_error;
102 using Base::m_info;
103 using Base::m_isInitialized;
104 using Base::m_iterations;
105 using Base::m_tolerance;
106 using Base::matrix;
107
108 public:
109 using Base::_solve_impl;
110 using Base::_solve_with_guess_impl;
111 using MatrixType = MatrixType_;
112 using Scalar = typename MatrixType::Scalar;
113 using StorageIndex = typename MatrixType::StorageIndex;
114 using RealScalar = typename MatrixType::RealScalar;
115 using ComplexScalar = internal::make_complex_t<Scalar>;
116 using Preconditioner = Preconditioner_;
117 using DenseMatrix = Matrix<Scalar, Dynamic, Dynamic>;
118 using DenseRealMatrix = Matrix<RealScalar, Dynamic, Dynamic>;
119 using DenseVector = Matrix<Scalar, Dynamic, 1>;
120 using DenseRealVector = Matrix<RealScalar, Dynamic, 1>;
121 using ComplexVector = Matrix<ComplexScalar, Dynamic, 1>;
122
125 : Base(), m_restart(30), m_neig(0), m_r(0), m_maxNeig(5), m_isDeflAllocated(false), m_isDeflInitialized(false) {}
126
137 template <typename MatrixDerived>
139 : Base(A.derived()),
140 m_restart(30),
141 m_neig(0),
142 m_r(0),
143 m_maxNeig(5),
144 m_isDeflAllocated(false),
145 m_isDeflInitialized(false) {}
146
148 template <typename Rhs, typename Dest>
149 void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const {
150 EIGEN_STATIC_ASSERT(Rhs::ColsAtCompileTime == 1 || Dest::ColsAtCompileTime == 1,
151 YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX);
152
153 m_iterations = Base::maxIterations();
154 m_error = Base::m_tolerance;
155
156 dgmres(matrix(), b, x, Base::m_preconditioner);
157 }
158
162 Index restart() const { return m_restart; }
163
167 void set_restart(const Index restart) { m_restart = restart; }
168
172 void setEigenv(const Index neig) {
173 m_neig = neig;
174 if (neig + 1 > m_maxNeig) m_maxNeig = neig + 1; // To allow for complex conjugates
175 }
176
180 Index deflSize() const { return m_r; }
181
185 void setMaxEigenv(const Index maxNeig) { m_maxNeig = maxNeig; }
186
187 protected:
188 // DGMRES algorithm
189 template <typename Rhs, typename Dest>
190 void dgmres(const MatrixType& mat, const Rhs& rhs, Dest& x, const Preconditioner& precond) const;
191 // Perform one cycle of GMRES
192 template <typename Dest>
193 Index dgmresCycle(const MatrixType& mat, const Preconditioner& precond, Dest& x, DenseVector& r0, RealScalar& beta,
194 const RealScalar& normRhs, Index& nbIts) const;
195 // Compute data to use for deflation
196 Index dgmresComputeDeflationData(const MatrixType& mat, const Preconditioner& precond, const Index& it,
197 StorageIndex& neig) const;
198 // Apply deflation to a vector
199 template <typename RhsType, typename DestType>
200 Index dgmresApplyDeflation(const RhsType& In, DestType& Out) const;
201 ComplexVector schurValues(const ComplexSchur<DenseMatrix>& schurofH) const;
202 ComplexVector schurValues(const RealSchur<DenseMatrix>& schurofH) const;
203 // Init data for deflation
204 void dgmresInitDeflation(Index& rows) const;
205 mutable DenseMatrix m_V; // Krylov basis vectors
206 mutable DenseMatrix m_H; // Hessenberg matrix
207 mutable DenseMatrix m_Hes; // Initial hessenberg matrix without Givens rotations applied
208 mutable Index m_restart; // Maximum size of the Krylov subspace
209 mutable DenseMatrix m_U; // Vectors that form the basis of the invariant subspace
210 mutable DenseMatrix m_MU; // matrix operator applied to m_U (for next cycles)
211 mutable DenseMatrix m_T; /* T=U^T*M^{-1}*A*U */
212 mutable PartialPivLU<DenseMatrix> m_luT; // LU factorization of m_T
213 mutable StorageIndex m_neig; // Number of eigenvalues to extract at each restart
214 mutable Index m_r; // Current number of deflated eigenvalues, size of m_U
215 mutable Index m_maxNeig; // Maximum number of eigenvalues to deflate
216 mutable RealScalar m_lambdaN; // Modulus of the largest eigenvalue of A
217 mutable bool m_isDeflAllocated;
218 mutable bool m_isDeflInitialized;
219
220 // Adaptive strategy
221 mutable RealScalar m_smv; // Smaller multiple of the remaining number of steps allowed
222 mutable bool m_force; // Force the use of deflation at each restart
223};
224
230template <typename MatrixType_, typename Preconditioner_>
231template <typename Rhs, typename Dest>
232void DGMRES<MatrixType_, Preconditioner_>::dgmres(const MatrixType& mat, const Rhs& rhs, Dest& x,
233 const Preconditioner& precond) const {
234 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
235
236 RealScalar normRhs = rhs.norm();
237 if (normRhs <= considerAsZero) {
238 x.setZero();
239 m_error = 0;
240 m_iterations = 0;
241 return;
242 }
243
244 // Initialization
245 m_isDeflInitialized = false;
246 Index n = mat.rows();
247 DenseVector r0(n);
248 Index nbIts = 0;
249 m_H.resize(m_restart + 1, m_restart);
250 m_Hes.resize(m_restart, m_restart);
251 m_V.resize(n, m_restart + 1);
252 // Initial residual vector and initial norm
253 if (x.squaredNorm() == 0) x = precond.solve(rhs);
254 r0.noalias() = rhs - mat * x;
255 RealScalar beta = r0.norm();
256
257 m_error = beta / normRhs;
258 if (m_error < m_tolerance)
259 m_info = Success;
260 else
261 m_info = NoConvergence;
262
263 // Iterative process
264 while (nbIts < m_iterations && m_info == NoConvergence) {
265 dgmresCycle(mat, precond, x, r0, beta, normRhs, nbIts);
266
267 // Compute the new residual vector for the restart
268 if (nbIts < m_iterations && m_info == NoConvergence) {
269 r0.noalias() = rhs - mat * x;
270 beta = r0.norm();
271 }
272 }
273 // m_iterations carried the iteration cap for the loops above; report the number actually performed.
274 m_iterations = nbIts;
275}
276
287template <typename MatrixType_, typename Preconditioner_>
288template <typename Dest>
289Index DGMRES<MatrixType_, Preconditioner_>::dgmresCycle(const MatrixType& mat, const Preconditioner& precond, Dest& x,
290 DenseVector& r0, RealScalar& beta, const RealScalar& normRhs,
291 Index& nbIts) const {
292 // Initialization
293 DenseVector g(m_restart + 1); // Right hand side of the least square problem
294 g.setZero();
295 g(0) = Scalar(beta);
296 m_V.col(0) = r0 / beta;
297 m_info = NoConvergence;
298 std::vector<JacobiRotation<Scalar> > gr(m_restart); // Givens rotations
299 Index it = 0; // Number of inner iterations
300 Index n = mat.rows();
301 DenseVector tv1(n), tv2(n); // Temporary vectors
302 while (m_info == NoConvergence && it < m_restart && nbIts < m_iterations) {
303 // Apply preconditioner(s) at right
304 if (m_isDeflInitialized) {
305 dgmresApplyDeflation(m_V.col(it), tv1); // Deflation
306 tv2 = precond.solve(tv1);
307 } else {
308 tv2 = precond.solve(m_V.col(it)); // User's selected preconditioner
309 }
310 tv1.noalias() = mat * tv2;
311
312 // Orthogonalize it with the previous basis in the basis using modified Gram-Schmidt
313 Scalar coef;
314 for (Index i = 0; i <= it; ++i) {
315 coef = tv1.dot(m_V.col(i));
316 tv1 = tv1 - coef * m_V.col(i);
317 m_H(i, it) = coef;
318 m_Hes(i, it) = coef;
319 }
320 // Normalize the vector. coef == 0 is an Arnoldi happy breakdown: the new
321 // direction lies in span(V[0..it]), so skip the division (which would
322 // poison m_V.col(it+1) with NaN) and fall through to the termination
323 // check below.
324 coef = tv1.norm();
325 const bool happy_breakdown = numext::is_exactly_zero(coef);
326 if (!happy_breakdown) {
327 m_V.col(it + 1) = tv1 / coef;
328 }
329 m_H(it + 1, it) = coef;
330
331 // Update Hessenberg matrix with Givens rotations
332 for (Index i = 1; i <= it; ++i) {
333 m_H.col(it).applyOnTheLeft(i - 1, i, gr[i - 1].adjoint());
334 }
335
336 // If the rotated diagonal is also zero, the reduced triangular system
337 // becomes singular and the back-substitution below would produce Inf/NaN.
338 // Stop with NumericalIssue instead of polluting x.
339 if (happy_breakdown && numext::is_exactly_zero(m_H(it, it))) {
340 m_info = NumericalIssue;
341 break;
342 }
343
344 // Compute the new plane rotation
345 gr[it].makeGivens(m_H(it, it), m_H(it + 1, it));
346 // Apply the new rotation
347 m_H.col(it).applyOnTheLeft(it, it + 1, gr[it].adjoint());
348 g.applyOnTheLeft(it, it + 1, gr[it].adjoint());
349
350 beta = numext::abs(g(it + 1));
351 m_error = beta / normRhs;
352 it++;
353 nbIts++;
354
355 if (m_error < m_tolerance || happy_breakdown) {
356 // Happy breakdown: residual on the current subspace is exactly zero, so
357 // the it-dim triangular system yields the exact solution.
358 m_info = Success;
359 break;
360 }
361 }
362
363 // Compute the new coefficients by solving the least square problem.
364 DenseVector nrs = m_H.topLeftCorner(it, it).template triangularView<Upper>().solve(g.head(it));
365
366 // Form the new solution
367 if (m_isDeflInitialized) {
368 tv1.noalias() = m_V.leftCols(it) * nrs;
369 dgmresApplyDeflation(tv1, tv2);
370 x = x + precond.solve(tv2);
371 } else
372 x = x + precond.solve(m_V.leftCols(it) * nrs);
373
374 // Go for a new cycle and compute data for deflation
375 if (nbIts < m_iterations && m_info == NoConvergence && m_neig > 0 && (m_r + m_neig) < m_maxNeig)
376 dgmresComputeDeflationData(mat, precond, it, m_neig);
377 return 0;
378}
379
380template <typename MatrixType_, typename Preconditioner_>
381void DGMRES<MatrixType_, Preconditioner_>::dgmresInitDeflation(Index& rows) const {
382 m_U.resize(rows, m_maxNeig);
383 m_MU.resize(rows, m_maxNeig);
384 m_T.resize(m_maxNeig, m_maxNeig);
385 m_lambdaN = 0.0;
386 m_isDeflAllocated = true;
387}
388
389template <typename MatrixType_, typename Preconditioner_>
390inline typename DGMRES<MatrixType_, Preconditioner_>::ComplexVector DGMRES<MatrixType_, Preconditioner_>::schurValues(
391 const ComplexSchur<DenseMatrix>& schurofH) const {
392 return schurofH.matrixT().diagonal();
393}
394
395template <typename MatrixType_, typename Preconditioner_>
396inline typename DGMRES<MatrixType_, Preconditioner_>::ComplexVector DGMRES<MatrixType_, Preconditioner_>::schurValues(
397 const RealSchur<DenseMatrix>& schurofH) const {
398 const DenseMatrix& T = schurofH.matrixT();
399 Index it = T.rows();
400 ComplexVector eig(it);
401 Index j = 0;
402 while (j < it - 1) {
403 if (T(j + 1, j) == Scalar(0)) {
404 eig(j) = ComplexScalar(T(j, j), RealScalar(0));
405 j++;
406 } else {
407 eig(j) = ComplexScalar(T(j, j), T(j + 1, j));
408 eig(j + 1) = ComplexScalar(T(j, j + 1), T(j + 1, j + 1));
409 j++;
410 }
411 }
412 if (j < it - 1) eig(j) = ComplexScalar(T(j, j), RealScalar(0));
413 return eig;
414}
415
416template <typename MatrixType_, typename Preconditioner_>
417Index DGMRES<MatrixType_, Preconditioner_>::dgmresComputeDeflationData(const MatrixType& mat,
418 const Preconditioner& precond, const Index& it,
419 StorageIndex& neig) const {
420 // First, find the Schur form of the Hessenberg matrix H
421 std::conditional_t<NumTraits<Scalar>::IsComplex, ComplexSchur<DenseMatrix>, RealSchur<DenseMatrix> > schurofH;
422 bool computeU = true;
423 DenseMatrix matrixQ(it, it);
424 matrixQ.setIdentity();
425 schurofH.computeFromHessenberg(m_Hes.topLeftCorner(it, it), matrixQ, computeU);
426
427 ComplexVector eig = this->schurValues(schurofH);
429
430 // Reorder the absolute values of Schur values
431 DenseRealVector modulEig(it);
432 for (Index j = 0; j < it; ++j) modulEig(j) = numext::abs(eig(j));
433 perm.setLinSpaced(it, 0, internal::convert_index<StorageIndex>(it - 1));
434 internal::sortWithPermutation(modulEig, perm, neig);
435
436 if (!m_lambdaN) {
437 m_lambdaN = (std::max)(modulEig.maxCoeff(), m_lambdaN);
438 }
439 // Count the real number of extracted eigenvalues (with complex conjugates)
440 Index nbrEig = 0;
441 while (nbrEig < neig) {
442 if (eig(perm(it - nbrEig - 1)).imag() == RealScalar(0))
443 nbrEig++;
444 else
445 nbrEig += 2;
446 }
447 // Extract the Schur vectors corresponding to the smallest Ritz values
448 DenseMatrix Sr(it, nbrEig);
449 Sr.setZero();
450 for (Index j = 0; j < nbrEig; j++) {
451 Sr.col(j) = schurofH.matrixU().col(perm(it - j - 1));
452 }
453
454 // Form the Schur vectors of the initial matrix using the Krylov basis
455 DenseMatrix X = m_V.leftCols(it) * Sr;
456 if (m_r) {
457 // Orthogonalize X against m_U using modified Gram-Schmidt
458 for (Index j = 0; j < nbrEig; j++)
459 for (Index k = 0; k < m_r; k++) X.col(j) = X.col(j) - (m_U.col(k).dot(X.col(j))) * m_U.col(k);
460 }
461
462 // Compute MX = M^-1 * A * X
463 Index m = m_V.rows();
464 if (!m_isDeflAllocated) dgmresInitDeflation(m);
465 DenseMatrix MX(m, nbrEig);
466 DenseVector tv1(m);
467 for (Index j = 0; j < nbrEig; j++) {
468 tv1.noalias() = mat * X.col(j);
469 MX.col(j) = precond.solve(tv1);
470 }
471
472 // Update m_T = [U'MU U'MX; X'MU X'MX]
473 m_T.block(m_r, m_r, nbrEig, nbrEig).noalias() = X.transpose() * MX;
474 if (m_r) {
475 m_T.block(0, m_r, m_r, nbrEig).noalias() = m_U.leftCols(m_r).transpose() * MX;
476 m_T.block(m_r, 0, nbrEig, m_r).noalias() = X.transpose() * m_MU.leftCols(m_r);
477 }
478
479 // Save X into m_U and m_MX in m_MU
480 for (Index j = 0; j < nbrEig; j++) m_U.col(m_r + j) = X.col(j);
481 for (Index j = 0; j < nbrEig; j++) m_MU.col(m_r + j) = MX.col(j);
482 // Increase the size of the invariant subspace
483 m_r += nbrEig;
484
485 // Factorize m_T into m_luT
486 m_luT.compute(m_T.topLeftCorner(m_r, m_r));
487
488 // FIXME: Check if the factorization was correctly done (nonsingular matrix).
489 m_isDeflInitialized = true;
490 return 0;
491}
492template <typename MatrixType_, typename Preconditioner_>
493template <typename RhsType, typename DestType>
494Index DGMRES<MatrixType_, Preconditioner_>::dgmresApplyDeflation(const RhsType& x, DestType& y) const {
495 DenseVector x1 = m_U.leftCols(m_r).transpose() * x;
496 y = x + m_U.leftCols(m_r) * (m_lambdaN * m_luT.solve(x1) - x1);
497 return 0;
498}
499
500} // end namespace Eigen
501#endif
Performs a complex Schur decomposition of a real or complex square matrix.
Definition ComplexSchur.h:60
A Restarted GMRES with deflation. This class implements a modification of the GMRES solver for sparse...
Definition DGMRES.h:98
Index dgmresCycle(const MatrixType &mat, const Preconditioner &precond, Dest &x, DenseVector &r0, RealScalar &beta, const RealScalar &normRhs, Index &nbIts) const
Perform one restart cycle of DGMRES.
Definition DGMRES.h:289
DGMRES(const EigenBase< MatrixDerived > &A)
Definition DGMRES.h:138
void setMaxEigenv(const Index maxNeig)
Definition DGMRES.h:185
DGMRES()
Definition DGMRES.h:124
Index restart() const
Definition DGMRES.h:162
void dgmres(const MatrixType &mat, const Rhs &rhs, Dest &x, const Preconditioner &precond) const
Perform several cycles of restarted GMRES with modified Gram Schmidt,.
Definition DGMRES.h:232
void set_restart(const Index restart)
Definition DGMRES.h:167
void setEigenv(const Index neig)
Definition DGMRES.h:172
Index deflSize() const
Definition DGMRES.h:180
Index maxIterations() const
Definition IterativeSolverBase.h:245
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
LU decomposition of a matrix with partial pivoting, and related features.
Definition PartialPivLU.h:67
Derived & setZero(Index size)
Definition CwiseNullaryOp.h:536
Performs a real Schur decomposition of a square matrix.
Definition RealSchur.h:62
@ NumericalIssue
Definition Constants.h:459
@ Success
Definition Constants.h:457
@ NoConvergence
Definition Constants.h:461
Definition EigenBase.h:34