Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
IterativeSolverBase.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_ITERATIVE_SOLVER_BASE_H
12#define EIGEN_ITERATIVE_SOLVER_BASE_H
13
14// IWYU pragma: private
15#include "./InternalHeaderCheck.h"
16
17namespace Eigen {
18
19namespace internal {
20
21template <typename T>
22auto is_ref_compatible_test(T& matrix) -> decltype(Ref<const T>(matrix), std::true_type());
23std::false_type is_ref_compatible_test(...);
24
25template <typename MatrixType>
26using is_ref_compatible = decltype(is_ref_compatible_test(std::declval<remove_all_t<MatrixType>&>()));
27
28// Returns a \a rows x \a cols matrix whose columns are an orthonormal basis of a random subspace,
29// obtained by QR-orthonormalizing a random matrix. The IDR(s)-type solvers use this to build the
30// shadow space; the basis only has to be (almost surely) non-degenerate, so any random seed is fine.
31template <typename MatrixType>
32MatrixType random_orthonormal_basis(Index rows, Index cols) {
33 HouseholderQR<MatrixType> qr(MatrixType::Random(rows, cols));
34 return qr.householderQ() * MatrixType::Identity(rows, cols);
35}
36
37// The more severe of two solver statuses: NumericalIssue, then NoConvergence, then Success. The enumerators are not
38// ordered by severity.
39inline ComputationInfo most_severe_info(ComputationInfo a, ComputationInfo b) {
40 if (a == NumericalIssue || b == NumericalIssue) return NumericalIssue;
41 if (a == NoConvergence || b == NoConvergence) return NoConvergence;
42 return a == Success ? b : a;
43}
44
45template <typename RealScalar>
46EIGEN_DEVICE_FUNC RealScalar iterative_solver_scaling_factor(RealScalar norm) {
47 // Scale only when forming a quadratic recurrence term from norm, or from the eps norm that a solver can reduce it
48 // to, may underflow or overflow. A square below the smallest normal number is subnormal, which loses precision, and
49 // is flushed to 0 where subnormals are not supported (float NEON on ARMv7).
50 const RealScalar sqrtMin = numext::sqrt((std::numeric_limits<RealScalar>::min)());
51 const RealScalar sqrtMax = numext::sqrt((std::numeric_limits<RealScalar>::max)());
52 return norm < sqrtMin / NumTraits<RealScalar>::epsilon() || norm > sqrtMax ? norm : RealScalar(1);
53}
54
61template <typename Rhs, typename Dest, typename Solve>
62auto iterative_solver_on_scaled_problem(const Rhs& b, Dest& x, Solve solve) -> decltype(solve(b, x)) {
63 using RealScalar = typename Dest::RealScalar;
64 using VectorType = Matrix<typename Dest::Scalar, Dynamic, 1>;
65 const RealScalar normb = b.stableNorm();
66 if (normb > RealScalar(0) && (numext::isfinite)(normb)) {
67 const RealScalar scale = iterative_solver_scaling_factor(normb);
68 if (scale != RealScalar(1)) {
69 VectorType scaledGuess = x / scale;
70 if (scaledGuess.allFinite()) {
71 const VectorType scaledRhs = b / scale;
72 const auto ret = solve(scaledRhs, scaledGuess);
73 x = scaledGuess * scale;
74 return ret;
75 }
76 }
77 }
78 return solve(b, x);
79}
80
81// The least residual norm that a stopping rule can ask for. Recurrences that form squares of residual norms underflow
82// below it, so a tolerance of 0 ("iterate until the residual vanishes") must stop here, not at the first denormal.
83template <typename RealScalar>
84EIGEN_DEVICE_FUNC RealScalar iterative_solver_residual_floor() {
85 return numext::sqrt((std::numeric_limits<RealScalar>::min)());
86}
87
88// The stopping threshold tol |b| for the residual, raised to min(floor, eps |b|). The raise exists only so that a
89// tolerance of 0, or below what the recurrences can resolve, stops where the residual underflows instead of dividing by
90// zero. It never exceeds eps |b|, which a solver cannot reach anyway, so it leaves every tolerance tol >= eps unchanged
91// whatever the size of b, where an absolute floor would exceed tol |b| for small |b| (|b| < 1e-12 in float at the
92// default tolerance).
93template <typename RealScalar>
94EIGEN_DEVICE_FUNC RealScalar iterative_solver_threshold(RealScalar tol, RealScalar norm, RealScalar floor) {
95 return numext::maxi(RealScalar(tol * norm), numext::mini(floor, RealScalar(NumTraits<RealScalar>::epsilon() * norm)));
96}
97
98template <typename MatrixType, bool MatrixFree = !internal::is_ref_compatible<MatrixType>::value>
99class generic_matrix_wrapper;
100
101// We have an explicit matrix at hand, compatible with Ref<>
102template <typename MatrixType>
103class generic_matrix_wrapper<MatrixType, false> {
104 public:
105 using ActualMatrixType = Ref<const MatrixType>;
106 template <int UpLo>
107 struct ConstSelfAdjointViewReturnType {
108 using Type = typename ActualMatrixType::template ConstSelfAdjointViewReturnType<UpLo>::Type;
109 };
110
111 enum { MatrixFree = false };
112
113 // Default-construct: passing (0,0) trips the size assertion for fixed-size MatrixType (#1704).
114 generic_matrix_wrapper() : m_dummy(), m_matrix(m_dummy) {}
115
116 template <typename InputType>
117 generic_matrix_wrapper(const InputType& mat) : m_matrix(mat) {}
118
119 const ActualMatrixType& matrix() const { return m_matrix; }
120
121 bool hasMatrix() const { return true; }
122
123 template <typename MatrixDerived>
124 void grab(const EigenBase<MatrixDerived>& mat) {
125 internal::destroy_at(&m_matrix);
126 internal::construct_at(&m_matrix, mat.derived());
127 }
128
129 void grab(const Ref<const MatrixType>& mat) {
130 if (&(mat.derived()) != &m_matrix) {
131 internal::destroy_at(&m_matrix);
132 internal::construct_at(&m_matrix, mat);
133 }
134 }
135
136 protected:
137 MatrixType m_dummy; // used to default initialize the Ref<> object
138 ActualMatrixType m_matrix;
139};
140
141// MatrixType is not compatible with Ref<> -> matrix-free wrapper
142template <typename MatrixType>
143class generic_matrix_wrapper<MatrixType, true> {
144 public:
145 using ActualMatrixType = MatrixType;
146 template <int UpLo>
147 struct ConstSelfAdjointViewReturnType {
148 using Type = ActualMatrixType;
149 };
150
151 enum { MatrixFree = true };
152
153 generic_matrix_wrapper() = default;
154
155 generic_matrix_wrapper(const MatrixType& mat) : mp_matrix(&mat) {}
156
157 const ActualMatrixType& matrix() const { return *mp_matrix; }
158
159 // False until compute(): a matrix-free operator has nothing to dereference before it is attached.
160 bool hasMatrix() const { return mp_matrix != nullptr; }
161
162 void grab(const MatrixType& mat) { mp_matrix = &mat; }
163
164 protected:
165 const ActualMatrixType* mp_matrix = nullptr;
166};
167
168} // namespace internal
169
175template <typename Derived>
176class IterativeSolverBase : public SparseSolverBase<Derived> {
177 protected:
178 using Base = SparseSolverBase<Derived>;
179 using Base::m_isInitialized;
180
181 public:
182 using MatrixType = typename internal::traits<Derived>::MatrixType;
183 using Preconditioner = typename internal::traits<Derived>::Preconditioner;
184 using Scalar = typename MatrixType::Scalar;
185 using StorageIndex = typename MatrixType::StorageIndex;
186 using RealScalar = typename MatrixType::RealScalar;
187
188 enum { ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime };
189
190 public:
191 using Base::derived;
192
195
206 template <typename MatrixDerived>
207 explicit IterativeSolverBase(const EigenBase<MatrixDerived>& A) : m_matrixWrapper(A.derived()) {
208 init();
209 compute(matrix());
210 }
211
213
219 template <typename MatrixDerived>
221 grab(A.derived());
222 m_preconditioner.analyzePattern(matrix());
223 m_isInitialized = true;
224 m_analysisIsOk = true;
225 m_info = m_preconditioner.info();
226 return derived();
227 }
228
239 template <typename MatrixDerived>
241 eigen_assert(m_analysisIsOk && "You must first call analyzePattern()");
242 grab(A.derived());
243 m_preconditioner.factorize(matrix());
244 m_factorizationIsOk = true;
245 m_info = m_preconditioner.info();
246 return derived();
247 }
248
259 template <typename MatrixDerived>
261 grab(A.derived());
262 m_preconditioner.compute(matrix());
263 m_isInitialized = true;
264 m_analysisIsOk = true;
265 m_factorizationIsOk = true;
266 m_info = m_preconditioner.info();
267 return derived();
268 }
269
271 constexpr Index rows() const noexcept { return matrix().rows(); }
272
274 constexpr Index cols() const noexcept { return matrix().cols(); }
275
279 RealScalar tolerance() const { return m_tolerance; }
280
292 Derived& setTolerance(const RealScalar& tolerance) {
293 m_tolerance = tolerance;
294 return derived();
295 }
296
298 Preconditioner& preconditioner() { return m_preconditioner; }
299
301 const Preconditioner& preconditioner() const { return m_preconditioner; }
302
307 Index maxIterations() const { return (m_maxIterations < 0) ? 2 * attachedCols() : m_maxIterations; }
308
312 Derived& setMaxIterations(Index maxIters) {
313 m_maxIterations = maxIters;
314 return derived();
315 }
316
318 Index iterations() const {
319 eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
320 return m_iterations;
321 }
322
328 RealScalar error() const {
329 eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
330 return m_error;
331 }
332
338 template <typename Rhs, typename Guess>
339 inline const SolveWithGuess<Derived, Rhs, Guess> solveWithGuess(const MatrixBase<Rhs>& b, const Guess& x0) const {
340 eigen_assert(m_isInitialized && "Solver is not initialized.");
341 EIGEN_INTERNAL_ASSERT_SOLVER_RHS_MSG(derived(), b, false,
342 "solve(): invalid number of rows of the right hand side matrix b");
343 return SolveWithGuess<Derived, Rhs, Guess>(derived(), b.derived(), x0);
344 }
345
356 template <typename Rhs, typename Dest>
357 void solveWithGuessInPlace(const Rhs& b, Dest& x) const {
358 eigen_assert(m_isInitialized && "Solver is not initialized.");
359 EIGEN_INTERNAL_ASSERT_SOLVER_RHS_MSG(derived(), b, false,
360 "solveWithGuessInPlace(): invalid number of rows of the right hand side b");
361 derived()._solve_vector_with_guess_impl(b, x);
362 }
363
369 eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
370 return m_info;
371 }
372
374 template <typename Rhs, typename DestDerived>
375 void _solve_with_guess_impl(const Rhs& b, SparseMatrixBase<DestDerived>& aDest) const {
376 EIGEN_INTERNAL_ASSERT_SOLVER_RHS(derived(), b, false);
377
378 Index rhsCols = b.cols();
379 Index size = b.rows();
380 DestDerived& dest(aDest.derived());
381 using DestScalar = typename DestDerived::Scalar;
384 // We do not directly fill dest because sparse expressions have to be free of aliasing issue.
385 // For non square least-square problems, b and dest might not have the same size whereas they might alias
386 // each-other.
387 typename DestDerived::PlainObject tmp(cols(), rhsCols);
388 ComputationInfo global_info = Success;
389 for (Index k = 0; k < rhsCols; ++k) {
390 tb = b.col(k);
391 tx = dest.col(k);
392 derived()._solve_vector_with_guess_impl(tb, tx);
393 tmp.col(k) = tx.sparseView(0);
394
395 // The call to _solve_vector_with_guess_impl updates m_info, so keep the most severe status over the columns.
396 global_info = internal::most_severe_info(global_info, m_info);
397 }
398 m_info = global_info;
399 dest.swap(tmp);
400 }
401
402 template <typename Rhs, typename DestDerived>
403 std::enable_if_t<Rhs::ColsAtCompileTime != 1 && DestDerived::ColsAtCompileTime != 1> _solve_with_guess_impl(
404 const Rhs& b, MatrixBase<DestDerived>& aDest) const {
405 EIGEN_INTERNAL_ASSERT_SOLVER_RHS(derived(), b, false);
406
407 Index rhsCols = b.cols();
408 DestDerived& dest(aDest.derived());
409 ComputationInfo global_info = Success;
410 for (Index k = 0; k < rhsCols; ++k) {
411 typename DestDerived::ColXpr xk(dest, k);
412 typename Rhs::ConstColXpr bk(b, k);
413 derived()._solve_vector_with_guess_impl(bk, xk);
414
415 // The call to _solve_vector_with_guess_impl updates m_info, so keep the most severe status over the columns.
416 global_info = internal::most_severe_info(global_info, m_info);
417 }
418 m_info = global_info;
419 }
420
421 template <typename Rhs, typename DestDerived>
422 std::enable_if_t<Rhs::ColsAtCompileTime == 1 || DestDerived::ColsAtCompileTime == 1> _solve_with_guess_impl(
423 const Rhs& b, MatrixBase<DestDerived>& dest) const {
424 derived()._solve_vector_with_guess_impl(b, dest.derived());
425 }
426
428 template <typename Rhs, typename Dest>
429 void _solve_impl(const Rhs& b, Dest& x) const {
430 x.setZero();
431 derived()._solve_with_guess_impl(b, x);
432 }
433
434 protected:
435 void init() {
436 m_isInitialized = false;
437 m_analysisIsOk = false;
438 m_factorizationIsOk = false;
439 m_maxIterations = -1;
440 m_tolerance = NumTraits<Scalar>::epsilon();
441 }
442
443 using MatrixWrapper = internal::generic_matrix_wrapper<MatrixType>;
444 using ActualMatrixType = typename MatrixWrapper::ActualMatrixType;
445
446 const ActualMatrixType& matrix() const { return m_matrixWrapper.matrix(); }
447
449 Index attachedCols() const { return m_matrixWrapper.hasMatrix() ? matrix().cols() : Index(0); }
450
453 RealScalar sizeScaledTolerance() const {
454 return RealScalar(8) * numext::sqrt(RealScalar(numext::maxi(attachedCols(), Index(1)))) *
455 NumTraits<RealScalar>::epsilon();
456 }
457
460 RealScalar toleranceOrEps() const {
461 return m_tolerance >= RealScalar(0) ? m_tolerance : NumTraits<RealScalar>::epsilon();
462 }
463
468 ComputationInfo infoAtDefaultOrSetTolerance(RealScalar error, RealScalar tol) const {
469 const bool confirmed = error <= tol || (m_tolerance < RealScalar(0) && error <= sizeScaledTolerance());
470 return confirmed ? Success : NoConvergence;
471 }
472
473 template <typename InputType>
474 void grab(const InputType& A) {
475 m_matrixWrapper.grab(A);
476 }
477
478 MatrixWrapper m_matrixWrapper;
479 Preconditioner m_preconditioner;
480
481 Index m_maxIterations;
482 RealScalar m_tolerance;
483
484 mutable RealScalar m_error;
485 mutable Index m_iterations;
486 mutable ComputationInfo m_info;
487 mutable bool m_analysisIsOk, m_factorizationIsOk;
488};
489
490} // end namespace Eigen
491
492#endif // EIGEN_ITERATIVE_SOLVER_BASE_H
Base class for linear iterative solvers.
Definition IterativeSolverBase.h:176
IterativeSolverBase()
Definition IterativeSolverBase.h:194
ComputationInfo info() const
Definition IterativeSolverBase.h:368
RealScalar error() const
Definition IterativeSolverBase.h:328
Index maxIterations() const
Definition IterativeSolverBase.h:307
Derived & setMaxIterations(Index maxIters)
Definition IterativeSolverBase.h:312
Derived & compute(const EigenBase< MatrixDerived > &A)
Definition IterativeSolverBase.h:260
IterativeSolverBase(const EigenBase< MatrixDerived > &A)
Definition IterativeSolverBase.h:207
void solveWithGuessInPlace(const Rhs &b, Dest &x) const
Definition IterativeSolverBase.h:357
const Preconditioner & preconditioner() const
Definition IterativeSolverBase.h:301
Derived & analyzePattern(const EigenBase< MatrixDerived > &A)
Definition IterativeSolverBase.h:220
Derived & factorize(const EigenBase< MatrixDerived > &A)
Definition IterativeSolverBase.h:240
Preconditioner & preconditioner()
Definition IterativeSolverBase.h:298
Derived & setTolerance(const RealScalar &tolerance)
Definition IterativeSolverBase.h:292
RealScalar tolerance() const
Definition IterativeSolverBase.h:279
const SolveWithGuess< Derived, Rhs, Guess > solveWithGuess(const MatrixBase< Rhs > &b, const Guess &x0) const
Definition IterativeSolverBase.h:339
Index iterations() const
Definition IterativeSolverBase.h:318
Base class for all dense matrices, vectors, and expressions.
Definition MatrixBase.h:53
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
Pseudo expression representing a solving operation.
Definition SolveWithGuess.h:44
Base class of any sparse matrices or sparse expressions.
Definition SparseMatrixBase.h:31
ComputationInfo
Definition Constants.h:455
@ NumericalIssue
Definition Constants.h:459
@ Success
Definition Constants.h:457
@ NoConvergence
Definition Constants.h:461
Definition EigenBase.h:34
constexpr Derived & derived()
Definition EigenBase.h:50