Debian Codegraph @

packages/belos/tpetra/src/solvers/Belos_Tpetra_Gmres.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_GMRES_HPP
11 #define BELOS_TPETRA_GMRES_HPP
12
13 #include "BelosMultiVecTraits_Tpetra.hpp"
14 #include "BelosOrthoManagerFactory.hpp"
15 #include "Belos_Tpetra_Krylov.hpp"
16 #include "Teuchos_BLAS.hpp"
17 #include "Teuchos_LAPACK.hpp"
18 #include "Teuchos_SerialDenseMatrix.hpp"
19 #include "Teuchos_SerialDenseVector.hpp"
20
21 namespace BelosTpetra {
22 namespace Impl {
23
24 namespace { // (anonymous)
25
26 // LAPACK's _GSEQR routine returns eigenvalues as (array of real
27 // parts, array of imaginary parts) for real Scalar types, but returns
28 // eigenvalues as (array of pairs (real, imag)) for complex Scalar
29 // types. computeRitzValues() provides a single interface for both
30 // cases.
31 template<class LO, class SC, bool isComplex = Teuchos::ScalarTraits<SC>::isComplex>
32 struct ComputeRitzValues {
33 using STS = Teuchos::ScalarTraits<SC>;
34 using real_type = typename STS::magnitudeType;
35 using complex_type = std::complex<real_type>;
36
37 static void
38 run (const int iter,
39 Teuchos::SerialDenseMatrix<LO, SC>& G,
40 std::vector<complex_type>& ritzValues);
41 };
42
43 // Real Scalar (SC) case.
44 template<class LO, class SC>
45 struct ComputeRitzValues<LO, SC, false> {
46 using STS = Teuchos::ScalarTraits<SC>;
47 using real_type = typename STS::magnitudeType;
48 using complex_type = std::complex<real_type>;
49
50 static void
51 run (const int iter,
52 Teuchos::SerialDenseMatrix<LO, SC>& G,
53 std::vector<complex_type>& ritzValues)
54 {
55 if (ritzValues.size () < std::size_t (iter)) {
56 ritzValues.resize (iter);
57 }
58
59 std::vector<real_type> WR (iter);
60 std::vector<real_type> WI (iter);
61 Teuchos::LAPACK<LO, SC> lapack;
62 SC TEMP = STS::zero ();
63 LO info = 0;
64 LO lwork = -1;
65 lapack.HSEQR ('E', 'N', iter, 1, iter, G.values (), G.stride (),
66 WR.data (), WI.data (), nullptr, 1, &TEMP, lwork, &info);
67 TEUCHOS_TEST_FOR_EXCEPTION
68 (info != 0, std::runtime_error, "LAPACK {D,S}SEQR LWORK query failed "
69 "with INFO = " << info << " != 0.");
70 lwork = static_cast<LO> (TEMP);
71 TEUCHOS_TEST_FOR_EXCEPTION
72 (lwork < LO {0}, std::runtime_error, "LAPACK {C,Z}SEQR LWORK query "
73 "returned LWORK = " << lwork << " < 0.");
74
75 std::vector<SC> WORK (lwork);
76 lapack.HSEQR ('E', 'N', iter, 1, iter, G.values (), G.stride (),
77 WR.data (), WI.data (), nullptr, 1, WORK.data (),
78 lwork, &info);
79 TEUCHOS_TEST_FOR_EXCEPTION
80 (info != 0, std::runtime_error, "LAPACK {D,S}SEQR failed "
81 "with INFO = " << info << " != 0.");
82 for (int i = 0; i < iter; ++i) {
83 ritzValues[i] = complex_type { WR[i], WI[i] };
84 }
85 }
86 };
87
88 // Complex Scalar (SC) case.
89 template<class LO, class SC>
90 struct ComputeRitzValues<LO, SC, true> {
91 using STS = Teuchos::ScalarTraits<SC>;
92 using real_type = typename STS::magnitudeType;
93 using complex_type = std::complex<real_type>;
94
95 static void
96 run (const int iter,
97 Teuchos::SerialDenseMatrix<LO, SC>& G,
98 std::vector<complex_type>& ritzValues)
99 {
100 if (ritzValues.size () < std::size_t (iter)) {
101 ritzValues.resize (iter);
102 }
103
104 Teuchos::LAPACK<LO, SC> lapack;
105 SC TEMP = STS::zero ();
106 LO lwork = -1;
107 LO info = 0;
108 lapack.HSEQR ('E', 'N', iter, 1, iter, G.values (), G.stride (),
109 ritzValues.data (), nullptr, 1, &TEMP, lwork, &info);
110 TEUCHOS_TEST_FOR_EXCEPTION
111 (info != 0, std::runtime_error, "LAPACK {C,Z}SEQR LWORK query failed "
112 "with INFO = " << info << " != 0.");
113 lwork = static_cast<LO> (STS::real (TEMP));
114 TEUCHOS_TEST_FOR_EXCEPTION
115 (lwork < LO {0}, std::runtime_error, "LAPACK {C,Z}SEQR LWORK query "
116 "returned LWORK = " << lwork << " < 0.");
117
118 std::vector<SC> WORK (lwork);
119 lapack.HSEQR ('E', 'N', iter, 1, iter, G.values (), G.stride (),
120 ritzValues.data (), nullptr, 1, WORK.data (), lwork, &info);
121 TEUCHOS_TEST_FOR_EXCEPTION
122 (info != 0, std::runtime_error, "LAPACK {C,Z}SEQR failed "
123 "with INFO = " << info << " != 0.");
124 }
125 };
126
127 /// \brief Compute eigenvalues of the upper Hessenberg matrix from GMRES.
128 ///
129 /// \param iter [in] The current GMRES iteration number
130 /// \param G [in] Upper Hessenberg matrix from GMRES.
131 /// \param ritzValues [out] The eigenvalues of G.
132 template<class LO, class SC>
133 void
134 computeRitzValues (const int iter,
135 Teuchos::SerialDenseMatrix<LO, SC>& G,
136 std::vector<std::complex<typename Teuchos::ScalarTraits<SC>::magnitudeType>>& ritzValues)
137 {
138 ComputeRitzValues<LO, SC>::run (iter, G, ritzValues);
139 }
140
141 /// \brief Sort Ritz values computed by computeRitzValues, using the
142 /// Leja ordering.
143 template<class LO, class SC>
144 void
145 sortRitzValues (const LO m,
146 std::vector<std::complex<typename Teuchos::ScalarTraits<SC>::magnitudeType>>& RR)
147 {
148 using STS = Teuchos::ScalarTraits<SC>;
149 using real_type = typename STS::magnitudeType;
150 using complex_type = std::complex<real_type>;
151 std::vector<complex_type> ritzValues (m);
152
153 // the first Ritz is the largest
154 LO i = 0;
155 LO next_index = 0;
156 real_type next_value = std::abs (RR[0]);
157 for (i = 1; i < m; ++i) {
158 if (next_value < std::abs (RR[i])) {
159 next_index = i;
160 next_value = std::abs (RR[i]);
161 }
162 }
163 ritzValues[0] = RR[next_index];
164 RR[next_index] = RR[0];
165
166 i = 0;
167 if (! STS::isComplex) {
168 if (RR[i].imag() != 0.0) {
169
170 if (next_index == 0) {
171 ritzValues[1] = ritzValues[0];
172 RR[next_index+1] = RR[1];
173 } else if (next_index == m-1) {
174 ritzValues[1] = ritzValues[0];
175 RR[next_index-1] = RR[1];
176 } else {
177 real_type val1 = std::abs(std::conj(RR[next_index-1]) - RR[next_index]);
178 real_type val2 = std::abs(std::conj(RR[next_index+1]) - RR[next_index]);
179 if (val1 < val2) {
180 ritzValues[1] = ritzValues[0];
181 RR[next_index-1] = RR[1];
182 } else {
183 ritzValues[1] = ritzValues[0];
184 RR[next_index+1] = RR[1];
185 }
186 }
187
188 ritzValues[0].imag( 0.0 );
189 i++;
190 }
191 }
192 i++;
193
194 // sort the rest of Ritz values
195 for (; i < m; i++) {
196 next_index = i;
197 next_value = std::abs( RR[i] - ritzValues[0] );
198 for (int j = 1; j < i; j++ ) {
199 next_value *= std::abs( RR[i] - ritzValues[j] );
200 }
201
202 for (int k = i+1; k < m; k++ ) {
203 real_type value = std::abs( RR[k] - ritzValues[0] );
204 for (int j = 1; j < i; j++ ) {
205 value *= std::abs( RR[k] - ritzValues[j] );
206 }
207 if (next_value < value) {
208 next_value = value;
209 next_index = k;
210 }
211 }
212 ritzValues[i] = RR[next_index];
213 RR[next_index] = RR[i];
214
215 if (! STS::isComplex) {
216 if (RR[i].imag() != 0.0) {
217 if (next_index == 0) {
218 ritzValues[i+1] = ritzValues[i];
219 RR[next_index+1] = RR[i+1];
220 } else if (next_index == m-1) {
221 if (i + 1 < m) {
222 ritzValues[i+1] = ritzValues[i];
223 RR[next_index-1] = RR[i+1];
224 }
225 } else {
226 real_type val1 = std::abs(std::conj(RR[next_index-1]) - ritzValues[i]);
227 real_type val2 = std::abs(std::conj(RR[next_index+1]) - ritzValues[i]);
228 if (val1 < val2) {
229 ritzValues[i+1] = ritzValues[i];
230 RR[next_index-1] = RR[i+1];
231 } else {
232 ritzValues[i+1] = ritzValues[i];
233 RR[next_index+1] = RR[i+1];
234 }
235 }
236 ritzValues[i].imag( 0.0 );
237 i++;
238 }
239 }
240 }
241
242 // copy back in the Leja order
243 for (i = 0; i < m; i++) {
244 RR[i] = ritzValues[i];
245 }
246 }
247
248 } // namespace (anonymous)
249
250 template<class SC = Tpetra::Operator<>::scalar_type,
251 class MV = Tpetra::MultiVector<SC>,
252 class OP = Tpetra::Operator<SC>>
253 class Gmres : public Krylov<SC, MV, OP> {
254 public:
255 using base_type = Krylov<SC, MV, OP>;
256
257 protected:
258 using vec_type = typename base_type::vec_type;
259
260 private:
261 using MVT = Belos::MultiVecTraits<SC, MV>;
262 using LO = typename MV::local_ordinal_type;
263 using STS = Teuchos::ScalarTraits<SC>;
264 using real_type = typename STS::magnitudeType;
265 using STM = Teuchos::ScalarTraits<real_type>;
266 using device_type = typename MV::device_type;
267
268 using ortho_type = Belos::OrthoManager<SC, MV>;
269 using dense_matrix_type = Teuchos::SerialDenseMatrix<LO, SC>;
270 using dense_vector_type = Teuchos::SerialDenseVector<LO, SC>;
271 using real_vector_type = Teuchos::SerialDenseVector<LO, real_type>;
272
273 public:
274 Gmres () = default;
275
276 Gmres (const Teuchos::RCP<const OP>& A) :
277 Krylov<SC, MV, OP>::Krylov (A)
278 {}
279
280 virtual ~Gmres () = default;
281
282 virtual void
283 getParameters (Teuchos::ParameterList& params,
284 const bool defaultValues) const override
285 {
286 Krylov<SC, MV, OP>::getParameters (params, defaultValues);
287
288 const int resCycle = defaultValues ? 30 : this->input_.resCycle;
289 params.set ("Num Blocks", resCycle);
290 // FIXME (mfh 16 Sep 2018) This isn't quite right -- "Maximum
291 // Restarts" in Belos refers to the number of restart cycles.
292 // These Krylov solvers appear to use maxNumIters as the maximum
293 // total number of iterations over all restart cycles.
294 params.set ("Maximum Restarts", this->input_.maxNumIters);
295 }
296
297 virtual void
298 setParameters (Teuchos::ParameterList& params) override
299 {
300 Krylov<SC, MV, OP>::setParameters (params);
301
302 bool computeRitzValues
303 = params.get<bool> ("Compute Ritz Values", this->input_.computeRitzValues);
304
305 bool needToReortho
306 = params.get<bool> ("Reorthogonalize Blocks", this->input_.needToReortho);
307
308 int resCycle = params.get<int> ("Num Blocks", this->input_.resCycle);
309 TEUCHOS_TEST_FOR_EXCEPTION
310 (resCycle < 0, std::invalid_argument,
311 "\"Num Blocks\" (restart length) = " << resCycle << " < 0.");
312
313 std::string orthoType
314 = params.get<std::string> ("Orthogonalization", this->input_.orthoType);
315
316 int maxOrthoSteps
317 = params.get<int> ("Max Orthogonalization Passes", this->input_.maxOrthoSteps);
318
319 this->input_.computeRitzValues = computeRitzValues;
320 this->input_.needToReortho = needToReortho;
321 this->input_.resCycle = resCycle;
322 this->input_.orthoType = orthoType;
323 this->input_.maxOrthoSteps = maxOrthoSteps;
324 }
325
326 protected:
327 //! Create Belos::OrthoManager instance.
328 void
329 setOrthogonalizer (const std::string& ortho)
330 {
331 if (ortho_.get () == nullptr || this->input_.orthoType != ortho) {
332 TEUCHOS_TEST_FOR_EXCEPTION
333 (this->input_.orthoType == "", std::runtime_error,
334 "Gmres: Failed to specify \"Orthogonalization\" parameter.");
335 // Since setOrthogonalizer only gets called on demand, we know
336 // the preconditioner (if any) at this point. Thus, we can use
337 // Belos::OrthoManagerFactory here.
338 Belos::OrthoManagerFactory<SC, MV, OP> factory;
339 Teuchos::RCP<Belos::OutputManager<SC>> outMan; // can be null
340 Teuchos::RCP<Teuchos::ParameterList> params; // can be null
341 if (this->input_.maxOrthoSteps > 0) {
342 params = Teuchos::rcp (new Teuchos::ParameterList());
343 params->set ("maxNumOrthogPasses", this->input_.maxOrthoSteps);
344 }
345 ortho_ = factory.makeMatOrthoManager (ortho, Teuchos::null, outMan, "Belos", params);
346 TEUCHOS_TEST_FOR_EXCEPTION
347 (ortho_.get () == nullptr, std::runtime_error, "Gmres: Failed to "
348 "create (Mat)OrthoManager of type \"" << ortho << "\".");
349 this->input_.orthoType = ortho;
350 }
351 }
352
353 private:
354 int
355 projectAndNormalize (const int n,
356 const SolverInput<SC>& input,
357 MV& Q,
358 dense_matrix_type& H,
359 dense_matrix_type& /* WORK */)
360 {
361 return this->projectAndNormalizeBelosOrthoManager (n, Q, H, input);
362 }
363
364 // ! Apply the orthogonalization using Belos' OrthoManager
365 int
366 projectAndNormalizeBelosOrthoManager (int n, MV &Q, dense_matrix_type &H,
367 const SolverInput<SC>& input)
368 {
369 using Teuchos::RCP;
370 using Teuchos::rcp;
371
372 // vector to be orthogonalized
373 vec_type AP = * (Q.getVectorNonConst (n+1));
374 // vectors to be orthogonalized against
375 Teuchos::Range1D index_prev(0, n);
376 RCP<const MV> Q_prev = MVT::CloneView (Q, index_prev);
377 Teuchos::Array<RCP<const MV>> Q_array( 1, Q_prev );
378
379 // orthogonalize scalars
380 auto h_new = rcp (new dense_matrix_type (Teuchos::View, H, n+1, 1, 0, n));
381 Teuchos::Array<RCP<dense_matrix_type>> h_array (1, h_new);
382 auto r_new = rcp (new dense_matrix_type (Teuchos::View, H, 1, 1, n+1, n));
383
384 if (ortho_.get () == nullptr) {
385 setOrthogonalizer (input.orthoType);
386 }
387 TEUCHOS_TEST_FOR_EXCEPTION
388 (ortho_.get () == nullptr, std::logic_error, "Gmres: Failed to create "
389 "(Mat)OrthoManager. This should never happen. Please report this bug "
390 "to the Belos developers.");
391 // FIXME (mfh 14 Aug 2018) For left preconditioning, we may need
392 // to use the MatOrthoManager interface.
393 return ortho_->projectAndNormalize (AP, h_array, r_new, Q_array);
394 }
395
396 protected:
397 //! Apply the orthogonalization using Belos' OrthoManager
398 void
399 projectBelosOrthoManager (const int n,
400 const int s,
401 MV& Q,
402 dense_matrix_type& R)
403 {
404 using Teuchos::RCP;
405 using Teuchos::rcp;
406
407 if (n > 0) {
408 // vector to be orthogonalized
409 Teuchos::Range1D index(n, n+s);
410 RCP<MV> Qnew = Q.subViewNonConst (index);
411
412 // vectors to be orthogonalized against
413 Teuchos::Range1D index_prev (0, n-1);
414 RCP<const MV> Q_prev = MVT::CloneView (Q, index_prev);
415 Teuchos::Array<RCP<const MV> > Qprev (1, Q_prev);
416
417 // orthogonalize scalars
418 RCP<dense_matrix_type> r_new =
419 rcp (new dense_matrix_type (Teuchos::View, R, n, s+1, 0, 0));
420 Teuchos::Array<RCP<dense_matrix_type>> r_array (1, r_new);
421
422 if (this->ortho_ == Teuchos::null) {
423 this->setOrthogonalizer (this->input_.orthoType);
424 }
425 this->ortho_->project (*Qnew, r_array, Qprev);
426 }
427 }
428
429 int
430 normalizeBelosOrthoManager (MV& Q, dense_matrix_type& R)
431 {
432 if (ortho_.get () == nullptr) {
433 setOrthogonalizer (this->input_.orthoType);
434 }
435 Teuchos::RCP<dense_matrix_type> R_ptr = Teuchos::rcpFromRef (R);
436 return ortho_->normalize (Q, R_ptr);
437 }
438
439 //! Reduce a column of Henssenburg matrix to triangular form
440 void
441 reduceHessenburgToTriangular(const int j,
442 dense_matrix_type& H,
443 std::vector<real_type>& cs,
444 std::vector<SC>& sn,
445 SC y[]) const
446 {
447 Teuchos::BLAS<LO, SC> blas;
448 // Apply previous Givens rotations to new column of H
449 for (int i = 0; i < j; ++i) {
450 blas.ROT (1, &H(i, j), 1, &H(i+1, j), 1, &cs[i], &sn[i]);
451 }
452 // Calculate new Givens rotation
453 blas.ROTG (&H(j, j), &H(j+1, j), &cs[j], &sn[j]);
454 H(j+1, j) = STS::zero ();
455 // Update RHS w/ new transformation
456 blas.ROT (1, &y[j], 1, &y[j+1], 1, &cs[j], &sn[j]);
457 }
458
459 void
460 reduceHessenburgToTriangular(const int j,
461 dense_matrix_type& H,
462 std::vector<real_type>& cs,
463 std::vector<SC>& sn,
464 dense_vector_type& y) const
465 {
466 this->reduceHessenburgToTriangular (j, H, cs, sn, y.values ());
467 }
468
469 SolverOutput<SC>
470 solveOneVec (Teuchos::FancyOStream* outPtr,
471 vec_type& X, // in X/out X
472 vec_type& B, // in B/out R (not left-preconditioned)
473 const OP& A,
474 const OP& M,
475 const SolverInput<SC>& input) override
476 {
477 using std::endl;
478 int restart = input.resCycle;
479 const SC zero = STS::zero ();
480 const SC one = STS::one ();
481
482 // timers
483 Teuchos::RCP< Teuchos::Time > spmvTimer = Teuchos::TimeMonitor::getNewCounter ("Gmres::matrix-apply ");
484 Teuchos::RCP< Teuchos::Time > precTimer = Teuchos::TimeMonitor::getNewCounter ("Gmres::precondition ");
485 Teuchos::RCP< Teuchos::Time > orthTimer = Teuchos::TimeMonitor::getNewCounter ("Gmres::orthogonalize");
486
487 Teuchos::RCP< Teuchos::Time > totalTimer = Teuchos::TimeMonitor::getNewCounter ("Gmres::total ");
488 Teuchos::TimeMonitor GmresTimer (*totalTimer);
489
490 // initialize output parameters
491 SolverOutput<SC> output {};
492 output.converged = false;
493 output.numRests = 0;
494 output.numIters = 0;
495
496
497 if (outPtr != nullptr) {
498 *outPtr << "Gmres" << endl;
499 }
500 Indent indent1 (outPtr);
501 if (outPtr != nullptr) {
502 *outPtr << "Solver input:" << endl;
503 Indent indentInner (outPtr);
504 *outPtr << input;
505 }
506
507 real_type b_norm; // initial residual norm
508 real_type b0_norm; // initial residual norm, not left preconditioned
509 real_type r_norm;
510 real_type r_norm_imp;
511
512 bool zeroOut = false; // Kokkos::View:init can take a long time on GPU?
513 vec_type R (B.getMap (), zeroOut);
514 vec_type Y (B.getMap (), zeroOut);
515 vec_type MP (B.getMap (), zeroOut);
516 MV Q (B.getMap (), restart+1, zeroOut);
517 vec_type P0 = * (Q.getVectorNonConst (0));
518
519 // initial residual (making sure R = B - Ax)
520 {
521 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
522 A.apply (X, R);
523 }
524 R.update (one, B, -one);
525 b0_norm = R.norm2 (); // residual norm, not-preconditioned
526 if (input.precoSide == "left") {
527 {
528 Teuchos::TimeMonitor LocalTimer (*precTimer);
529 M.apply (R, P0);
530 }
531 b_norm = P0.norm2 (); // residual norm, left-preconditioned
532 }
533 else {
534 Tpetra::deep_copy (P0, R);
535 b_norm = b0_norm;
536 }
537 real_type metric = this->getConvergenceMetric (b0_norm, b0_norm, input);
538
539 if (metric <= input.tol) {
540 if (outPtr != nullptr) {
541 *outPtr << "Initial guess' residual norm " << b_norm
542 << " meets tolerance " << input.tol << endl;
543 }
544 output.absResid = b_norm;
545 output.relResid = STM::one ();
546 output.numIters = 0;
547 output.converged = true;
548 // return residual norm as B
549 Tpetra::deep_copy (B, P0);
550 return output;
551 } else if (outPtr != NULL) {
552 *outPtr << "Initial guess' residual norm " << b0_norm << endl;
553 }
554
555 Teuchos::BLAS<LO ,SC> blas;
556 Teuchos::LAPACK<LO ,SC> lapack;
557 dense_matrix_type H (restart+1, restart, true);
558 dense_matrix_type G (restart+1, restart, true); // only for Ritz values
559 dense_vector_type y (restart+1, true);
560 dense_matrix_type h (restart+1, 1, true); // for reorthogonalization
561 std::vector<real_type> cs (restart);
562 std::vector<SC> sn (restart);
563
564 //#define HAVE_TPETRA_DEBUG
565 #ifdef HAVE_TPETRA_DEBUG
566 dense_matrix_type H2 (restart+1, restart, true);
567 dense_matrix_type H3 (restart+1, restart, true);
568 #endif
569
570 // initialize starting vector
571 P0.scale (one / b_norm);
572 y[0] = SC {b_norm};
573
574 // main loop
575 int iter = 0;
576 while (output.numIters < input.maxNumIters && ! output.converged) {
577 if (outPtr != nullptr) {
578 *outPtr << "Restart cycle " << output.numRests << ":" << endl;
579 Indent indent2 (outPtr);
580 *outPtr << output;
581 }
582
583 if (input.maxNumIters < output.numIters+restart) {
584 restart = input.maxNumIters-output.numIters;
585 }
586
587 // restart cycle
588 for (; iter < restart && metric > input.tol; ++iter) {
589 if (outPtr != nullptr) {
590 *outPtr << "Current iteration: iter=" << iter
591 << ", restart=" << restart
592 << ", metric=" << metric << endl;
593 Indent indent3 (outPtr);
594 }
595
596 // AP = A*P
597 vec_type P = * (Q.getVectorNonConst (iter));
598 vec_type AP = * (Q.getVectorNonConst (iter+1));
599 if (input.precoSide == "none") {
600 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
601 A.apply (P, AP);
602 }
603 else if (input.precoSide == "right") {
604 {
605 Teuchos::TimeMonitor LocalTimer (*precTimer);
606 M.apply (P, MP);
607 }
608 {
609 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
610 A.apply (MP, AP);
611 }
612 }
613 else { // left
614 {
615 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
616 A.apply (P, MP);
617 }
618 {
619 Teuchos::TimeMonitor LocalTimer (*precTimer);
620 M.apply (MP, AP);
621 }
622 }
623 output.numIters++;
624
625 int rank = 0;
626 {
627 Teuchos::TimeMonitor LocalTimer (*orthTimer);
628 rank = this->projectAndNormalize (iter, input, Q, H, h);
629 }
630 // Save H if Ritz values are requested
631 if (input.computeRitzValues && output.numRests == 0) {
632 blas.COPY (iter+2, &H(0, iter), 1, &G(0, iter), 1);
633 }
634 // Check for negative norm
635 TEUCHOS_TEST_FOR_EXCEPTION
636 (STS::real (H(iter+1, iter)) < STM::zero (), std::runtime_error,
637 "At iteration " << iter << ", H(" << iter+1 << ", " << iter << ") = "
638 << H(iter+1, iter) << " < 0.");
639
640 #ifdef HAVE_TPETRA_DEBUG
641 // Numeric check
642 this->checkNumerics (outPtr, iter, iter, A, M, Q, X, B, y,
643 H, H2, H3, cs, sn, input);
644 #endif
645
646 // Convergence check
647 if (rank == 1 && H(iter+1, iter) != zero) {
648 // Apply Givens rotations to new column of H and y
649 this->reduceHessenburgToTriangular(iter, H, cs, sn, y);
650 metric = this->getConvergenceMetric (STS::magnitude (y(iter+1)), b_norm, input);
651 }
652 else {
653 metric = STM::zero ();
654 }
655 } // end of restart cycle
656
657 if (iter < restart) {
658 // save the old solution, just in case explicit residual norm failed the convergence test
659 Tpetra::deep_copy (Y, X);
660 blas.COPY (1+iter, y.values(), 1, h.values(), 1);
661 }
662 r_norm_imp = STS::magnitude (y (iter)); // save implicit residual norm
663 if (iter > 0) {
664 // Compute Ritz values, if requested
665 if (input.computeRitzValues && output.numRests == 0) {
666 computeRitzValues (iter, G, output.ritzValues);
667 sortRitzValues <LO, SC> (iter, output.ritzValues);
668 }
669 // Update solution
670 blas.TRSM (Teuchos::LEFT_SIDE, Teuchos::UPPER_TRI,
671 Teuchos::NO_TRANS, Teuchos::NON_UNIT_DIAG,
672 iter, 1, one,
673 H.values(), H.stride(), y.values(), y.stride());
674 Teuchos::Range1D cols(0, iter-1);
675 Teuchos::RCP<const MV> Qj = Q.subView(cols);
676 dense_vector_type y_iter (Teuchos::View, y.values (), iter);
677 if (input.precoSide == "right") {
678 //MVT::MvTimesMatAddMv (one, *Qj, y, zero, R);
679 MVT::MvTimesMatAddMv (one, *Qj, y_iter, zero, R);
680 {
681 Teuchos::TimeMonitor LocalTimer (*precTimer);
682 M.apply (R, MP);
683 }
684 X.update (one, MP, one);
685 }
686 else {
687 //MVT::MvTimesMatAddMv (one, *Qj, y, one, X);
688 MVT::MvTimesMatAddMv (one, *Qj, y_iter, one, X);
689 }
690 //y.resize (restart+1);
691 }
692 // Compute explicit unpreconditioned residual
693 {
694 Teuchos::TimeMonitor LocalTimer (*spmvTimer);
695 A.apply (X, R);
696 }
697 R.update (one, B, -one);
698 r_norm = R.norm2 (); // residual norm
699 output.absResid = r_norm;
700 output.relResid = r_norm / b0_norm;
701 if (outPtr != nullptr) {
702 *outPtr << "Implicit and explicit residual norms at restart: " << r_norm_imp << ", " << r_norm << endl;
703 }
704
705 metric = this->getConvergenceMetric (r_norm, b0_norm, input);
706 if (metric <= input.tol) {
707 output.converged = true;
708 }
709 else if (output.numIters < input.maxNumIters) {
710 // Restart, only if max inner-iteration was reached.
711 // Otherwise continue the inner-iteration.
712 if (iter >= restart) {
713 // Restart: Initialize starting vector for restart
714 iter = 0;
715 P0 = * (Q.getVectorNonConst (0));
716 if (input.precoSide == "left") {
717 {
718 Teuchos::TimeMonitor LocalTimer (*precTimer);
719 M.apply (R, P0);
720 }
721 r_norm = P0.norm2 (); // norm
722 }
723 else {
724 // set the starting vector
725 Tpetra::deep_copy (P0, R);
726 }
727 P0.scale (one / r_norm);
728 y[0] = SC {r_norm};
729 for (int i=1; i < restart+1; i++) {
730 y[i] = STS::zero ();
731 }
732 output.numRests++;
733 }
734 else {
735 // reset to the old solution
736 Tpetra::deep_copy (X, Y);
737 blas.COPY (1+iter, h.values(), 1, y.values(), 1);
738 }
739 }
740 }
741
742 // return residual norm as B
743 Tpetra::deep_copy (B, R);
744
745 if (outPtr != nullptr) {
746 *outPtr << "At end of solve:" << endl;
747 Indent indentInner (outPtr);
748 *outPtr << output;
749 }
750 return output;
751 }
752
753 // ! compute matrix norm
754 real_type
755 computeNorm(dense_matrix_type &T)
756 {
757 const LO ione = 1;
758
759 LO m = T.numRows ();
760 LO n = T.numCols ();
761 LO minmn = (m < n ? m : n);
762
763 LO INFO, LWORK;
764 SC U, VT, TEMP;
765 real_type RWORK;
766 real_vector_type S (minmn, true);
767 LWORK = -1;
768 Teuchos::LAPACK<LO ,SC> lapack;
769 lapack.GESVD('N', 'N', m, n, T.values (), T.stride (),
770 S.values (), &U, ione, &VT, ione,
771 &TEMP, LWORK, &RWORK, &INFO);
772 LWORK = Teuchos::as<LO> (STS::real (TEMP));
773 dense_vector_type WORK (LWORK, true);
774 lapack.GESVD('N', 'N', m, n, T.values (), T.stride (),
775 S.values (), &U, ione, &VT, ione,
776 WORK.values (), LWORK, &RWORK, &INFO);
777
778 return S(0);
779 }
780
781 // ! Check numerics
782 void
783 checkNumerics (Teuchos::FancyOStream* outPtr,
784 const int iter,
785 const int check,
786 const OP& A,
787 const OP& M,
788 const MV& Q,
789 const vec_type& X,
790 const vec_type& B,
791 const dense_vector_type& y,
792 const dense_matrix_type& H,
793 dense_matrix_type& H2,
794 dense_matrix_type& H3,
795 std::vector<real_type>& cs,
796 std::vector<SC>& sn,
797 const SolverInput<SC>& input)
798 {
799 Teuchos::BLAS<LO ,SC> blas;
800 const SC zero = STS::zero ();
801 const SC one = STS::one ();
802
803 // quick return
804 if (outPtr == nullptr) {
805 return;
806 }
807
808 // save H (before convert it to triangular form)
809 for (int i = 0; i <= check+1; i++) {
810 H2 (i, check) = H (i, check);
811 H3 (i, check) = H (i, check);
812 }
813 // reduce H3 to triangular
814 dense_vector_type y2 (check+2, true); // to save y
815 blas.COPY (check+1, y.values(), 1, y2.values(), 1);
816 this->reduceHessenburgToTriangular (check, H3, cs, sn, y2.values ());
817
818 #if 0
819 printf( " > checkNumeric(iter = %d, check = %d)\n",iter,check );
820 /*auto Q_lcl = Q.getLocalViewHost();
821 printf( " Q = [\n" );
822 for (int i = 0; i < (int)Q_lcl.extent(0); i++) {
823 for (int j = 0; j <= check+1; j++) printf( "%.16e ",Q_lcl(i,j) );
824 printf("\n" );
825 }
826 printf("];\n" );*/
827
828 printf( " H2 = [\n" );
829 for (int i = 0; i <= check+1; i++) {
830 for (int j = 0; j <= check; j++) {
831 printf( "%.16e ", H2 (i, j) );
832 }
833 printf( "\n" );
834 }
835 printf( "];\n" );
836 /*printf( " H3 = [\n" );
837 for (int i = 0; i <= check+1; i++) {
838 for (int j = 0; j <= check; j++) {
839 printf( "%e ", H3 (i, j) );
840 }
841 printf( "\n" );
842 }
843 printf( "];\n" );*/
844 //for (int i = 0; i <= check+1; i++) printf( "%d %e -> %e\n",i,y(i),y2(i) );
845 fflush(stdout);
846 #endif
847
848 // save X
849 vec_type X2 (X.getMap (), false); // to save X
850 Tpetra::deep_copy (X2, X);
851
852 // implicit residual norm
853 real_type r_norm_imp = STS::magnitude (y2 (check+1));
854 y2.resize (check+1);
855
856 // --------------------------------------
857 // compute explicit residual norm
858 // > Update solution, X += Q*y
859 vec_type R (X.getMap (), false); // to save X
860 vec_type MP (X.getMap (), false); // to save X
861 blas.TRSM (Teuchos::LEFT_SIDE, Teuchos::UPPER_TRI, Teuchos::NO_TRANS,
862 Teuchos::NON_UNIT_DIAG, check+1, 1, one,
863 H3.values(), H3.stride(), y2.values (), y2.stride ());
864 Teuchos::Range1D cols(0, check);
865 Teuchos::RCP<const MV> Qj = Q.subView(cols);
866 if (input.precoSide == "right") {
867 MVT::MvTimesMatAddMv (one, *Qj, y2, zero, R);
868 M.apply (R, MP);
869 X2.update (one, MP, one);
870 }
871 else {
872 MVT::MvTimesMatAddMv (one, *Qj, y2, one, X2);
873 }
874 // > Compute explicit residual vector
875 A.apply (X2, R);
876 R.update (one, B, -one);
877 real_type r_norm = R.norm2 (); // residual norm
878 real_type b_norm = B.norm2 (); // originial noorm
879
880 // --------------------------------------
881 // compute orthogonality error, norm (Q'*Q-I)
882 real_type ortho_error (0.0);
883 {
884 Teuchos::Range1D index_prev(0, check+1);
885 Teuchos::RCP<const MV> Q_prev = MVT::CloneView (Q, index_prev);
886 dense_matrix_type T (check+2, check+2, true);
887 MVT::MvTransMv(one, *Q_prev, *Q_prev, T);
888 for (int i = 0; i < check+2; i++) {
889 T (i, i) -= one;
890 }
891 /*printf("Y=[\n");
892 for (int i = 0; i < check+2; i++) {
893 for (int j = 0; j < check+2; j++) {
894 printf("%e ",T (i, j));
895 }
896 printf("\n");
897 }
898 printf("];\n");*/
899 ortho_error = computeNorm(T);
900 }
901
902 // --------------------------------------
903 // compute Arnoldi representation error
904 real_type repre_error (0.0);
905 real_type proje_error (0.0);
906 {
907 // > compute AQ=A*Q
908 MV AQ (Q.getMap (), check+1);
909 {
910 Teuchos::Range1D index_prev(0, check);
911 Teuchos::RCP<const MV> Q_prev = MVT::CloneView (Q, index_prev);
912 if (input.precoSide == "left") {
913 MV AM (Q.getMap (), check+1);
914 A.apply (*Q_prev, AM);
915 M.apply (AM, AQ);
916 } else if (input.precoSide == "right") {
917 MV AM (Q.getMap (), check+1);
918 M.apply (*Q_prev, AM);
919 A.apply (AM, AQ);
920 } else {
921 A.apply (*Q_prev, AQ);
922 }
923 }
924
925 // > compute HH = H - Q'*A*Q and AQ = Q*H - AQ
926 dense_matrix_type HH(check+2, check+1, true);
927 {
928 Teuchos::Range1D index_prev(0, check+1);
929 Teuchos::RCP<const MV> Q_prev = MVT::CloneView (Q, index_prev);
930 auto H_new = rcp (new dense_matrix_type (Teuchos::View, H2, check+2, check+1, 0, 0));
931
932 // > compute H - Q'*A*Q
933 MVT::MvTransMv(one, *Q_prev, AQ, HH);
934 for (int j = 0; j < check+1; j++) {
935 blas.AXPY (check+2, -one, &(H2(0, j)), 1, &(HH(0, j)), 1);
936 }
937
938 // > compute AQ = Q*H - AQ
939 MVT::MvTimesMatAddMv (one, *Q_prev, *H_new, -one, AQ);
940 }
941
942 // > compute norm, norm(HH) and sqrt(norm(AQ'*AQ))
943 {
944 proje_error = computeNorm(HH);
945
946 dense_matrix_type T (check+1, check+1, true);
947 MVT::MvTransMv(one, AQ, AQ, T);
948 repre_error = STM::squareroot (computeNorm(T));
949 }
950 }
951
952 *outPtr << " > iter = " << iter
953 << ", check = " << check
954 << ", Right-hand side norm: "
955 << b_norm
956 << ", Implicit and explicit residual norms: "
957 << r_norm_imp << ", " << r_norm
958 << " -> "
959 << r_norm_imp/b_norm << ", " << r_norm/b_norm
960 << ", Ortho error: "
961 << ortho_error
962 << ", Arnoldi representation error: "
963 << repre_error
964 << ", Projection error: "
965 << proje_error
966 << std::endl;
967 }
968
969 private:
970 Teuchos::RCP<ortho_type> ortho_;
971 };
972
973 template<class SC, class MV, class OP,
974 template<class, class, class> class KrylovSubclassType>
975 class SolverManager;
976
977 // This is the Belos::SolverManager subclass that gets registered with
978 // Belos::SolverFactory.
979 template<class SC, class MV, class OP>
980 using GmresSolverManager = SolverManager<SC, MV, OP, Gmres>;
981
982 /// \brief Register GmresSolverManager for all enabled Tpetra
983 /// template parameter combinations.
984 void register_Gmres (const bool verbose);
985
986 } // namespace Impl
987 } // namespace BelosTpetra
988
989 #endif // BELOS_TPETRA_GMRES_HPP