Debian Codegraph @

packages/belos/tpetra/src/solvers/Belos_Tpetra_Krylov.hpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Belos: Block Linear Solvers Package
4 //
5 // Copyright 2004-2016 NTESS and the Belos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #ifndef BELOS_TPETRA_KRYLOV_HPP
11 #define BELOS_TPETRA_KRYLOV_HPP
12
13 #include "Belos_Tpetra_Krylov_parameters.hpp"
14 #include "Tpetra_Core.hpp"
15 #include "Tpetra_Map.hpp"
16 #include "Tpetra_MultiVector.hpp"
17 #include "Tpetra_Operator.hpp"
18 #include "Tpetra_Vector.hpp"
19 #include "Teuchos_FancyOStream.hpp"
20 #include "Teuchos_oblackholestream.hpp"
21 #include "Teuchos_ParameterList.hpp"
22
23 namespace BelosTpetra {
24 namespace Impl {
25
26 /// \brief Base class for iterative solvers that only work with Tpetra
27 /// objects, and that only solve for one right-hand-side vector at a
28 /// time.
29 ///
30 /// \warning This is an implementation detail of Belos.
31 ///
32 /// \tparam SC The type of of a dot product result.
33 /// \tparam MV Tpetra::MultiVector specialization.
34 /// \tparam OP Tpetra::MultiVector specialization.
35 ///
36 /// This is a base class for Tpetra-based "non-block" solvers. Here,
37 /// "block" means that the solver can solve for multiple right-hand
38 /// sides at a time. Subclasses need only implement \c solveOneVec.
39 ///
40 /// Users do not interact directly with this class. Instead, when
41 /// users select the appropriate solver type, they get a
42 /// BelosTpetra::Impl::SolverManager instance from
43 /// Belos::SolverFactory. The BelosTpetra::Impl::SolverManager
44 /// instance wraps an instance of a subclass of Krylov.
45 template<class SC = Tpetra::MultiVector<>::scalar_type,
46 class MV = Tpetra::MultiVector<SC>,
47 class OP = Tpetra::Operator<SC>>
48 class Krylov {
49 private:
50 static_assert (std::is_same<MV, Tpetra::MultiVector<typename MV::scalar_type,
51 typename MV::local_ordinal_type,
52 typename MV::global_ordinal_type,
53 typename MV::node_type>>::value,
54 "MV must be a Tpetra::MultiVector specialization.");
55 static_assert (std::is_same<OP, Tpetra::Operator<typename OP::scalar_type,
56 typename OP::local_ordinal_type,
57 typename OP::global_ordinal_type,
58 typename OP::node_type>>::value,
59 "OP must be a Tpetra::Operator specialization.");
60 public:
61 using vec_type = Tpetra::Vector<typename MV::scalar_type,
62 typename MV::local_ordinal_type,
63 typename MV::global_ordinal_type,
64 typename MV::node_type>;
65
66 private:
67 using STS = Teuchos::ScalarTraits<SC>;
68 using mag_type = typename STS::magnitudeType;
69 using STM = Teuchos::ScalarTraits<mag_type>;
70 using device_type = typename MV::device_type;
71
72 public:
73 Krylov () = default;
74
75 Krylov (const Teuchos::RCP<const OP>& A) :
76 Krylov ()
77 {
78 A_ = A;
79 }
80
81 virtual ~Krylov () = default;
82
83 //! Set the matrix A in the linear system to solve.
84 void setMatrix (const Teuchos::RCP<const OP>& A) {
85 if (A_.get () != A.get ()) {
86 A_ = A;
87 }
88 }
89
90 void setLeftPrec (Teuchos::RCP<const OP> M) {
91 input_.precoSide = "left";
92 M_ = M;
93 }
94
95 void setRightPrec (Teuchos::RCP<const OP> M) {
96 input_.precoSide = "right";
97 M_ = M;
98 }
99
100 Teuchos::RCP<const OP>
101 getMatrix () const {
102 return A_;
103 }
104
105 Teuchos::RCP<const OP>
106 getPreconditioner () const {
107 return M_;
108 }
109
110 /// \brief Fill \c params with all parameters this solver
111 /// understands, and either their current values, or their default
112 /// values.
113 ///
114 /// \param params [out] To be filled with this solver's parameters.
115 /// \param defaultValues [in] Whether to use default values (true)
116 /// or current values (false).
117 virtual void
118 getParameters (Teuchos::ParameterList& params,
119 const bool defaultValues) const
120 {
121 if (defaultValues) {
122 getDefaultParameters (params);
123 }
124 else {
125 const std::string implResScal = input_.needToScale ?
126 "Norm of Preconditioned Initial Residual" : "None"; // ???
127
128 params.set ("Convergence Tolerance", input_.tol);
129 params.set ("Implicit Residual Scaling", implResScal);
130 params.set ("Maximum Iterations", input_.maxNumIters);
131 params.set ("Verbosity", verbosity_);
132 }
133 }
134
135 virtual void
136 getDefaultParameters (Teuchos::ParameterList& params) const
137 {
138 const SolverInput<SC> input;
139 const int verbosity = 0;
140 const std::string implResScal = input.needToScale ?
141 "Norm of Preconditioned Initial Residual" : "None"; // ???
142
143 params.set ("Convergence Tolerance", input.tol);
144 params.set ("Implicit Residual Scaling", implResScal);
145 params.set ("Maximum Iterations", input.maxNumIters);
146 params.set ("Verbosity", verbosity);
147 }
148
149 /// \brief Set the solver's parameters.
150 ///
151 /// This solver takes a subset of the parameters that
152 /// Belos::PseudoBlockCGSolMgr (Belos' CG implementation) takes, and
153 /// ignores the rest. The point is minimal sufficient compatibility
154 /// with Belos' "generic" solvers.
155 virtual void
156 setParameters (Teuchos::ParameterList& params)
157 {
158 const mag_type tol = params.get<mag_type> ("Convergence Tolerance", input_.tol);
159 TEUCHOS_TEST_FOR_EXCEPTION
160 (tol < STM::zero (), std::invalid_argument,
161 "\"Convergence tolerance\" = " << tol << " < 0.");
162 input_.tol = tol;
163
164 if (params.isParameter ("Implicit Residual Scaling")) {
165 const std::string implScal =
166 params.get<std::string> ("Implicit Residual Scaling");
167 if (implScal == "Norm of Initial Residual") {
168 // FIXME (mfh 26 Oct 2016) Once we implement left
169 // preconditioning, we'll have to keep separate preconditioned
170 // and unpreconditioned absolute residuals.
171 input_.needToScale = true;
172 }
173 else if (implScal == "Norm of Preconditioned Initial Residual") {
174 input_.needToScale = true;
175 }
176 else if (implScal == "Norm of RHS") {
177 // FIXME (mfh 26 Oct 2016) If we want to implement this, it
178 // would make sense to combine that all-reduce with the
179 // all-reduce for computing the initial residual norms. We
180 // could modify computeResidualVectorsAndNorms to have an
181 // option to do this.
182 TEUCHOS_TEST_FOR_EXCEPTION
183 (true, std::logic_error,
184 "\"Norm of RHS\" scaling option not implemented");
185 }
186 else if (implScal == "None") {
187 input_.needToScale = false;
188 }
189 else {
190 TEUCHOS_TEST_FOR_EXCEPTION
191 (true, std::invalid_argument, "\"Implicit Residual Scaling\""
192 " has an invalid value \"" << implScal << "\".");
193 }
194 }
195
196 if (params.isParameter ("Maximum Iterations")) {
197 const int maxNumIters = params.get<int> ("Maximum Iterations");
198 TEUCHOS_TEST_FOR_EXCEPTION
199 (maxNumIters < 0, std::invalid_argument,
200 "\"Maximum Iterations\" = " << maxNumIters << " < 0.");
201 input_.maxNumIters = maxNumIters;
202 }
203
204 int verbosity = verbosity_;
205 if (params.isType<int> ("Verbosity")) {
206 verbosity = params.get<int> ("Verbosity");
207 }
208 else if (params.isType<bool> ("Verbosity")) {
209 const bool verbBool = params.get<bool> ("Verbosity");
210 verbosity = verbBool ? 1 : 0;
211 }
212 verbosity_ = verbosity;
213 }
214
215 private:
216 static MV
217 computeResidualVectorsAndNorms (const Teuchos::ArrayView<mag_type>& norms,
218 const OP& A,
219 const MV& X,
220 const MV& B)
221 {
222 const SC ONE = STS::one ();
223 MV R (B, Teuchos::Copy);
224 A.apply (X, R, Teuchos::NO_TRANS, -ONE, ONE); // R := -1*(A*X) + 1*B
225 R.norm2 (norms);
226 return R; // shallow copy
227 }
228
229 static mag_type
230 computeResidual (vec_type& R,
231 const OP& A,
232 const vec_type& X,
233 const vec_type& B)
234 {
235 const SC ONE = STS::one ();
236 A.apply (X, R);
237 R.update (ONE, B, -ONE); // R := B - A*X
238 const mag_type r_norm = R.norm2 ();
239 return r_norm;
240 }
241
242 public:
243 //! Solve the linear system(s) AX=B.
244 SolverOutput<SC>
245 solve (MV& X, const MV& B)
246 {
247 using Teuchos::FancyOStream;
248 using Teuchos::getFancyOStream;
249 using Teuchos::oblackholestream;
250 using Teuchos::RCP;
251 using Teuchos::rcp;
252 using Teuchos::rcpFromRef;
253 using std::endl;
254
255 TEUCHOS_TEST_FOR_EXCEPTION
256 (A_.is_null (), std::runtime_error, "Matrix A is null. Please call "
257 "setMatrix() with a nonnull argument before calling solve().");
258 TEUCHOS_TEST_FOR_EXCEPTION
259 (X.getNumVectors () != B.getNumVectors (), std::runtime_error,
260 "X.getNumVectors() = " << X.getNumVectors () <<
261 " != B.getNumVectors() = " << B.getNumVectors () << ".");
262
263 RCP<FancyOStream> outPtr;
264 if (verbosity_) {
265 const int myRank = A_->getDomainMap ()->getComm ()->getRank ();
266 if (myRank == 0) {
267 outPtr = getFancyOStream (rcpFromRef (std::cout));
268 }
269 else {
270 outPtr = getFancyOStream (rcp (new oblackholestream ()));
271 }
272 }
273 return solveImpl (outPtr.get (), X, B);
274 }
275
276 //! Return solver inputs
277 SolverInput<SC> getSolverInput() {
278 return input_;
279 }
280
281 //! Return achieved residual
282 typename Teuchos::ScalarTraits<SC>::magnitudeType achievedTol() const {
283 return output_.absResid;
284 }
285
286 protected:
287 static mag_type
288 getConvergenceMetric (const mag_type r_norm_new,
289 const SolverInput<SC>& input)
290 {
291 if (input.needToScale) {
292 return input.r_norm_orig == STM::zero () ?
293 r_norm_new :
294 (r_norm_new / input.r_norm_orig);
295 }
296 else {
297 return r_norm_new;
298 }
299 }
300
301 static mag_type
302 getConvergenceMetric (const mag_type r_norm_new,
303 const mag_type r_norm_orig,
304 const SolverInput<SC>& input)
305 {
306 if (input.needToScale) {
307 return r_norm_orig == STM::zero () ?
308 r_norm_new :
309 (r_norm_new / r_norm_orig);
310 }
311 else {
312 return r_norm_new;
313 }
314 }
315
316 private:
317 //! Solve the linear system(s) AX=B.
318 SolverOutput<SC>
319 solveImpl (Teuchos::FancyOStream* outPtr, MV& X, const MV& B)
320 {
321 using Teuchos::RCP;
322 using std::endl;
323 const char prefix[] = "BelosTpetra::Impl::Krylov::solveImpl: ";
324 TEUCHOS_TEST_FOR_EXCEPTION
325 (M_.get () == nullptr && input_.precoSide != "none",
326 std::logic_error, prefix << "The preconditioner M_ is null, but "
327 "input_.precoSide=\"" << input_.precoSide << "\" != \"none\". "
328 "Please report this bug to the Belos developers.");
329
330 const size_t numVecs = B.getNumVectors ();
331 TEUCHOS_TEST_FOR_EXCEPTION
332 (X.getNumVectors () != numVecs, std::runtime_error, prefix
333 << "X.getNumVectors() = " << X.getNumVectors ()
334 << " != B.getNumVectors() = " << numVecs << ".");
335
336 Teuchos::Array<mag_type> norms (numVecs);
337 MV R = computeResidualVectorsAndNorms (norms (), *A_, X, B);
338
339 // Solving $A X = B$ with a nonzero initial guess $X_0$ is
340 // equivalent to solving $A*\Delta = R (= B - A*X_0)$ with a zero
341 // initial guess, then computing $X = X_0 + \Delta$. This
342 // approach will avoid the extra overhead of each solver
343 // recomputing the residual vector.
344 //
345 // TODO (mfh 19 Sep 2018) It would make sense to optimize for the
346 // case where users know their initial guess is zero, by skipping
347 // the extra copy here and the extra update at the end.
348 MV Delta (X.getMap (), numVecs);
349
350 SolverOutput<SC> allOutput {};
351 for (size_t j = 0; j < numVecs; ++j) {
352 if (outPtr != nullptr) {
353 *outPtr << "Solve for column " << (j+1) << " of " << numVecs << ":"
354 << endl;
355 }
356 Indent indentInner (outPtr);
357 RCP<vec_type> R_j = R.getVectorNonConst (j);
358 RCP<vec_type> Delta_j = Delta.getVectorNonConst (j);
359 input_.r_norm_orig = norms[j];
360 const SolverOutput<SC> curOutput =
361 solveOneVec (outPtr, *Delta_j, *R_j, *A_,
362 (input_.precoSide == "none" ? *A_ : *M_), input_);
363 combineSolverOutput (allOutput, curOutput);
364 }
365 // See note above about a potential optimization.
366 X.update (STS::one (), Delta, STS::one ()); // $X := X_0 + \Delta$
367 output_ = allOutput;
368
369 return allOutput;
370 }
371
372 protected:
373 /// \brief Implementation of solving the linear system.
374 ///
375 /// This is the method that subclasses must override.
376 ///
377 /// \param outPtr [out] If nonnull, print verbose output to this.
378 ///
379 /// \param X [in/out] On input: initial guess vector; on output:
380 /// computed solution vector.
381 ///
382 /// \param R [in/out] On input: initial residual vector (R = B -
383 /// A*X); on output: final residual vector (again, R = B - A*X).
384 virtual SolverOutput<SC>
385 solveOneVec (Teuchos::FancyOStream* outPtr,
386 vec_type& X, // in X/out X
387 vec_type& R, // in B/out R
388 const OP& A,
389 const OP& M,
390 const SolverInput<SC>& input) = 0;
391
392 protected:
393 SolverInput<SC> input_;
394 SolverOutput<SC> output_;
395
396 private:
397 Teuchos::RCP<const OP> A_;
398 std::string precoType_;
399 Teuchos::RCP<const OP> M_;
400 int verbosity_ = 0;
401 };
402
403 } // namespace Impl
404 } // namespace BelosTpetra
405
406 #endif // BELOS_TPETRA_KRYLOV_HPP