Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
ConjugateGradient.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2011-2014 Gael Guennebaud <gael.guennebaud@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_CONJUGATE_GRADIENT_H
12#define EIGEN_CONJUGATE_GRADIENT_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
30template <typename MatrixType, typename Rhs, typename Dest, typename Preconditioner>
31EIGEN_DONT_INLINE void conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x, const Preconditioner& precond,
32 Index& iters, typename Dest::RealScalar& tol_error) {
33 using RealScalar = typename Dest::RealScalar;
34 using Scalar = typename Dest::Scalar;
35 // Use Dest's plain (owning) type as VectorType. For CPU Matrix/Map this
36 // resolves to Matrix<Scalar,Dynamic,1>. For GPU DeviceMatrix, PlainObject
37 // is DeviceMatrix itself (already owning).
38 using VectorType = typename Dest::PlainObject;
39
40 RealScalar tol = tol_error;
41 Index maxIters = iters;
42
43 Index n = mat.cols();
44
45 VectorType residual = rhs - mat * x; // initial residual
46
47 RealScalar rhsNorm = rhs.stableNorm();
48 if (rhsNorm == 0) {
49 x.setZero();
50 iters = 0;
51 tol_error = 0;
52 return;
53 }
54 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
55 RealScalar threshold = numext::maxi(RealScalar(tol * rhsNorm), considerAsZero);
56 RealScalar residualNorm = residual.stableNorm();
57 if (residualNorm < threshold) {
58 iters = 0;
59 tol_error = residualNorm / rhsNorm;
60 return;
61 }
62
63 // Keep the quadratic recurrence terms representable for very small or large residuals.
64 const RealScalar residualScale = internal::iterative_solver_scaling_factor(residualNorm);
65 residual /= residualScale;
66 // The threshold and the floor are in units of the scaled residual; the floor makes tol_error = 0 stop where the
67 // squares of the residual would underflow.
68 threshold = internal::iterative_solver_threshold(tol, RealScalar(rhsNorm / residualScale),
69 internal::iterative_solver_residual_floor<RealScalar>());
70
71 VectorType p(n);
72 p = precond.solve(residual); // initial search direction
73
74 VectorType z(n), tmp(n);
75 RealScalar absNew = numext::real(residual.dot(p)); // the square of the absolute value of r scaled by invM
76 Index i = 0;
77 while (i < maxIters) {
78 tmp.noalias() = mat * p; // the bottleneck of the algorithm
79
80 Scalar alpha = absNew / p.dot(tmp); // the amount we travel on dir
81 x += (residualScale * alpha) * p; // update solution
82 residual -= alpha * tmp; // update residual
83
84 residualNorm = residual.stableNorm();
85 if (residualNorm < threshold) break;
86
87 z = precond.solve(residual); // approximately solve for "A z = residual"
88
89 RealScalar absOld = absNew;
90 absNew = numext::real(residual.dot(z)); // update the absolute value of r
91 RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
92 p = z + beta * p; // update search direction
93 i++;
94 }
95 tol_error = residualNorm / (rhsNorm / residualScale);
96 iters = i;
97}
98
99} // namespace internal
100
101template <typename MatrixType_, int UpLo_ = Lower,
104
105namespace internal {
106
107template <typename MatrixType_, int UpLo_, typename Preconditioner_>
108struct traits<ConjugateGradient<MatrixType_, UpLo_, Preconditioner_> > {
109 using MatrixType = MatrixType_;
110 using Preconditioner = Preconditioner_;
111};
112
113} // namespace internal
114
163template <typename MatrixType_, int UpLo_, typename Preconditioner_>
164class ConjugateGradient : public IterativeSolverBase<ConjugateGradient<MatrixType_, UpLo_, Preconditioner_> > {
165 protected:
167 using Base::m_error;
168 using Base::m_info;
169 using Base::m_isInitialized;
170 using Base::m_iterations;
171 using Base::matrix;
172
173 public:
174 using MatrixType = MatrixType_;
175 using Scalar = typename MatrixType::Scalar;
176 using RealScalar = typename MatrixType::RealScalar;
177 using Preconditioner = Preconditioner_;
178
179 enum { UpLo = UpLo_ };
180
181 public:
183 ConjugateGradient() : Base() {}
184
195 template <typename MatrixDerived>
196 explicit ConjugateGradient(const EigenBase<MatrixDerived>& A) : Base(A.derived()) {}
197
199 template <typename Rhs, typename Dest>
200 void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const {
201 using MatrixWrapper = typename Base::MatrixWrapper;
202 using ActualMatrixType = typename Base::ActualMatrixType;
203 enum {
204 TransposeInput = (!MatrixWrapper::MatrixFree) && (UpLo == (Lower | Upper)) && (!MatrixType::IsRowMajor) &&
205 (!NumTraits<Scalar>::IsComplex)
206 };
207 using RowMajorWrapper =
208 std::conditional_t<TransposeInput, Transpose<const ActualMatrixType>, ActualMatrixType const&>;
209 EIGEN_STATIC_ASSERT(internal::check_implication(MatrixWrapper::MatrixFree, UpLo == (Lower | Upper)),
210 MATRIX_FREE_CONJUGATE_GRADIENT_IS_COMPATIBLE_WITH_UPPER_UNION_LOWER_MODE_ONLY);
211 using SelfAdjointWrapper =
212 std::conditional_t<UpLo == (Lower | Upper), RowMajorWrapper,
213 typename MatrixWrapper::template ConstSelfAdjointViewReturnType<UpLo>::Type>;
214
215 m_iterations = Base::maxIterations();
216 m_error = Base::m_tolerance;
217
218 RowMajorWrapper row_mat(matrix());
219 internal::conjugate_gradient(SelfAdjointWrapper(row_mat), b, x, Base::m_preconditioner, m_iterations, m_error);
220 m_info = m_error <= Base::m_tolerance ? Success : NoConvergence;
221 }
222};
223
224} // end namespace Eigen
225
226#endif // EIGEN_CONJUGATE_GRADIENT_H
A conjugate gradient solver for sparse (or dense) self-adjoint problems.
Definition ConjugateGradient.h:164
ConjugateGradient(const EigenBase< MatrixDerived > &A)
Definition ConjugateGradient.h:196
ConjugateGradient()
Definition ConjugateGradient.h:183
A preconditioner based on the diagonal entries.
Definition BasicPreconditioners.h:40
Index maxIterations() const
Definition IterativeSolverBase.h:307
Expression of an array as a mathematical vector or matrix.
Definition ArrayWrapper.h:120
@ Lower
Definition Constants.h:212
@ Upper
Definition Constants.h:214
@ Success
Definition Constants.h:457
@ NoConvergence
Definition Constants.h:461
Definition EigenBase.h:34