Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
LeastSquareConjugateGradient.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2015 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_LEAST_SQUARE_CONJUGATE_GRADIENT_H
12#define EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
26template <typename RealScalar>
27RealScalar least_square_power_of_two_at_most(const RealScalar& v) {
28 // 2^-2^k for k < 32, which covers the exponents up to 2^32 - 1. For a scalar with a wider range the result is the
29 // power of two 2^-2^32 if that is above v: still an exact scale of b, but it raises b by less than s <= v < 2 s does.
30 RealScalar factors[32];
31 int count = 0;
32 for (RealScalar f = RealScalar(0.5); count < 32 && f > v; f = RealScalar(f * f)) factors[count++] = f;
33 RealScalar s(1); // 2^-e with s > v
34 for (int k = count - 1; k >= 0; --k) {
35 const RealScalar t = RealScalar(s * factors[k]);
36 if (t > v) s = t;
37 }
38 return RealScalar(s * RealScalar(0.5));
39}
40
43template <typename RealScalar, typename MatrixType>
44auto least_square_dot_length(const MatrixType& mat, int) -> decltype(RealScalar(mat.nonZeros())) {
45 return numext::maxi(RealScalar(1),
46 RealScalar(RealScalar(mat.nonZeros()) / RealScalar(numext::maxi(mat.cols(), Index(1)))));
47}
48template <typename RealScalar, typename MatrixType>
49RealScalar least_square_dot_length(const MatrixType& mat, long) {
50 return RealScalar(mat.rows());
51}
52
65template <typename MatrixType, typename Rhs, typename Dest, typename Preconditioner>
66EIGEN_DONT_INLINE bool least_square_conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x,
67 const Preconditioner& precond, Index& iters,
68 typename Dest::RealScalar& tol_error) {
69 using RealScalar = typename Dest::RealScalar;
70 using Scalar = typename Dest::Scalar;
71 using VectorType = Matrix<Scalar, Dynamic, 1>;
72
73 RealScalar tol = tol_error;
74 Index maxIters = iters;
75
76 Index m = mat.rows(), n = mat.cols();
77
78 VectorType residual = rhs - mat * x;
79 VectorType normal_residual = mat.adjoint() * residual;
80 VectorType normal_rhs = mat.adjoint() * rhs;
81
82 RealScalar rhsNorm = normal_rhs.stableNorm();
83 // A'b below the smallest normal number has lost its precision or underflowed to 0, and x = 0 would be returned with
84 // Success. When |b| < 1, solve for b / s and x / s instead, with s the power of two at most |b| so that the scaling
85 // is exact: that only raises A'b, unlike a division by a |b| above 1. The guess is left alone if x / s overflows.
86 RealScalar rhsScale(1);
87 if (rhsNorm < (std::numeric_limits<RealScalar>::min)()) {
88 const RealScalar bNorm = rhs.stableNorm();
89 if (bNorm > RealScalar(0) && bNorm < RealScalar(1)) {
90 const RealScalar scale = least_square_power_of_two_at_most(bNorm);
91 const VectorType scaledGuess = x / scale;
92 if (scaledGuess.allFinite()) {
93 rhsScale = scale;
94 x = scaledGuess;
95 residual = rhs / rhsScale - mat * x;
96 normal_residual = mat.adjoint() * residual;
97 normal_rhs = mat.adjoint() * (rhs / rhsScale);
98 rhsNorm = normal_rhs.stableNorm();
99 }
100 }
101 }
102 const auto restoreScale = [&]() {
103 if (rhsScale != RealScalar(1)) x *= rhsScale;
104 };
105 if (rhsNorm == 0) {
106 x.setZero();
107 iters = 0;
108 tol_error = 0;
109 return true;
110 }
111 RealScalar threshold = tol * rhsNorm;
112 RealScalar residualNorm = normal_residual.stableNorm();
113 if (residualNorm == 0 || residualNorm < threshold) {
114 restoreScale();
115 iters = 0;
116 tol_error = residualNorm / rhsNorm;
117 return true;
118 }
119
120 // Keep the quadratic recurrence terms representable for very small or large residuals.
121 const RealScalar residualScale = internal::iterative_solver_scaling_factor(residualNorm);
122 normal_residual /= residualScale;
123 residualNorm /= residualScale;
124 // The threshold and the floor are in units of the scaled residual; the floor makes tol_error = 0 stop where the
125 // squares of the residual would underflow.
126 threshold = internal::iterative_solver_threshold(tol, RealScalar(rhsNorm / residualScale),
127 internal::iterative_solver_residual_floor<RealScalar>());
128
129 VectorType p(n);
130 p = precond.solve(normal_residual); // initial search direction
131
132 VectorType z(n), tmp(m);
133 RealScalar absNew = numext::real(normal_residual.dot(p)); // the square of the absolute value of r scaled by invM
134 Index i = 0;
135 // The gradient A' r cannot be resolved below about sqrt(L) eps |A| |r|, the rounding error of its dot products of L
136 // terms, the nonzeros of a column of A (Higham and Mary, SIAM J. Sci. Comput. 41(5), 2019), and CG iterates on that
137 // noise past it and can diverge (Hestenes and Stiefel 1952; Bjorck, Numerical Methods for Least Squares Problems,
138 // SIAM 1996). |A| is bounded below by |A p| / |p|. The floor is in units of the scaled normal residual. The squares
139 // of p and r / scale cost one pass each, and are not used if they overflow.
140 const RealScalar eps = NumTraits<RealScalar>::epsilon();
141 const RealScalar sqrtLength = numext::sqrt(internal::least_square_dot_length<RealScalar>(mat, 0));
142 RealScalar normA(0);
143 const auto gradientFloor = [&](RealScalar apNorm) {
144 const RealScalar pNorm2 = p.squaredNorm();
145 if (pNorm2 > RealScalar(0) && (numext::isfinite)(pNorm2))
146 normA = numext::maxi(normA, RealScalar(apNorm / numext::sqrt(pNorm2)));
147 const RealScalar rNorm2 = (residual / residualScale).squaredNorm();
148 const RealScalar floor = RealScalar(sqrtLength * eps * normA * numext::sqrt(rNorm2));
149 return (numext::isfinite)(floor) ? floor : RealScalar(0);
150 };
151 bool atFloor = false;
152 while (i < maxIters) {
153 tmp.noalias() = mat * p;
154
155 // The step along p, in units of the unscaled residual: residualScale |g|^2 / |A p|^2.
156 const RealScalar tmpNorm2 = tmp.squaredNorm();
157 RealScalar apNorm = numext::sqrt(tmpNorm2);
158 RealScalar step = RealScalar(residualScale * (absNew / tmpNorm2));
159 if (!(tmpNorm2 >= (std::numeric_limits<RealScalar>::min)() && (numext::isfinite)(tmpNorm2)) ||
160 !(numext::isfinite)(step)) {
161 // |A p|^2 or the step over- or underflows: use the scaled norm, as the product (|g|^2 / |A p|) (scale / |A p|)
162 // whose factors are applied one after the other.
163 apNorm = tmp.stableNorm();
164 step = RealScalar(absNew / apNorm);
165 const RealScalar tail = RealScalar(residualScale / apNorm);
166 if (!(numext::isfinite)(step) || !(numext::isfinite)(tail) || !(numext::isfinite)(apNorm)) {
167 // A p vanishes or is not finite, so the step is not defined: p is numerically in the null space of A. Only a
168 // gradient below its finite floor counts as converged.
169 atFloor = residualNorm <= gradientFloor(apNorm);
170 break;
171 }
172 x += step * (tail * p); // update solution
173 residual -= step * (tail * tmp); // update residual
174 } else {
175 x += step * p; // update solution
176 residual -= step * tmp; // update residual
177 }
178 normal_residual.noalias() = mat.adjoint() * residual; // update residual of the normal equation
179 normal_residual /= residualScale;
180
181 residualNorm = normal_residual.stableNorm();
182 if (residualNorm < threshold) break;
183
184 // Past the floor the gradient is noise: stop with the current iterate, which is as good as any later one.
185 if (residualNorm <= gradientFloor(apNorm)) {
186 atFloor = true;
187 break;
188 }
189
190 z = precond.solve(normal_residual); // approximately solve for "A'A z = normal_residual"
191
192 RealScalar absOld = absNew;
193 absNew = numext::real(normal_residual.dot(z)); // update the absolute value of r
194 RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
195 p = z + beta * p; // update search direction
196 i++;
197 }
198 restoreScale();
199 tol_error = residualNorm / (rhsNorm / residualScale);
200 iters = i;
201 return tol_error <= tol || atFloor;
202}
203
204} // namespace internal
205
206template <typename MatrixType_,
209
210namespace internal {
211
212template <typename MatrixType_, typename Preconditioner_>
213struct traits<LeastSquaresConjugateGradient<MatrixType_, Preconditioner_> > {
214 using MatrixType = MatrixType_;
215 using Preconditioner = Preconditioner_;
216};
217
218} // namespace internal
219
264template <typename MatrixType_, typename Preconditioner_>
266 : public IterativeSolverBase<LeastSquaresConjugateGradient<MatrixType_, Preconditioner_> > {
267 protected:
269 using Base::m_error;
270 using Base::m_info;
271 using Base::m_isInitialized;
272 using Base::m_iterations;
273 using Base::matrix;
274
275 public:
276 using MatrixType = MatrixType_;
277 using Scalar = typename MatrixType::Scalar;
278 using RealScalar = typename MatrixType::RealScalar;
279 using Preconditioner = Preconditioner_;
280
281 public:
284
295 template <typename MatrixDerived>
296 explicit LeastSquaresConjugateGradient(const EigenBase<MatrixDerived>& A) : Base(A.derived()) {}
297
299 template <typename Rhs, typename Dest>
300 void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const {
301 m_iterations = Base::maxIterations();
302 m_error = Base::m_tolerance;
303
304 const bool converged =
305 internal::least_square_conjugate_gradient(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error);
306 m_info = converged ? Success : NoConvergence;
307 }
308};
309
310} // end namespace Eigen
311
312#endif // EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H
Index maxIterations() const
Definition IterativeSolverBase.h:307
Jacobi preconditioner for LeastSquaresConjugateGradient.
Definition BasicPreconditioners.h:122
A conjugate gradient solver for sparse (or dense) least-square problems.
Definition LeastSquareConjugateGradient.h:266
LeastSquaresConjugateGradient()
Definition LeastSquareConjugateGradient.h:283
LeastSquaresConjugateGradient(const EigenBase< MatrixDerived > &A)
Definition LeastSquareConjugateGradient.h:296
@ Success
Definition Constants.h:457
@ NoConvergence
Definition Constants.h:461
Definition EigenBase.h:34