Stratimikos Version of the Day
Loading...
Searching...
No Matches
Thyra_BelosLinearOpWithSolve_def.hpp
1// @HEADER
2// *****************************************************************************
3// Stratimikos: Thyra-based strategies for linear solvers
4//
5// Copyright 2006 NTESS and the Stratimikos contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
10#ifndef THYRA_BELOS_LINEAR_OP_WITH_SOLVE_HPP
11#define THYRA_BELOS_LINEAR_OP_WITH_SOLVE_HPP
12
14#include "Thyra_BelosLinearOpWithSolve_decl.hpp"
15#include "Thyra_GeneralSolveCriteriaBelosStatusTest.hpp"
16#include "Thyra_LinearOpWithSolveHelpers.hpp"
17#include "Teuchos_DebugDefaultAsserts.hpp"
18#include "Teuchos_Assert.hpp"
19#include "Teuchos_TimeMonitor.hpp"
20#include "Stratimikos_Config.h"
21#ifdef HAVE_STRATIMIKOS_THYRATPETRAADAPTERS
22# include "Thyra_TpetraThyraWrappers.hpp"
23# include <MatrixMarket_Tpetra.hpp>
24# include <TpetraExt_MatrixMatrix.hpp>
25#endif
26
27namespace {
28 // Set the Belos solver's parameter list to scale its residual norms
29 // in the specified way.
30 //
31 // We break this out in a separate function because the parameters
32 // to set depend on which parameters the Belos solver supports. Not
33 // all Belos solvers support both the "Implicit Residual Scaling"
34 // and "Explicit Residual Scaling" parameters, so we have to check
35 // the solver's list of valid parameters for the existence of these.
36 //
37 // Scaling options: Belos lets you decide whether the solver will
38 // scale residual norms by the (left-)preconditioned initial
39 // residual norms (residualScalingType = "Norm of Initial
40 // Residual"), or by the unpreconditioned initial residual norms
41 // (residualScalingType = "Norm of RHS"). Usually you want to scale
42 // by the unpreconditioned initial residual norms. This is because
43 // preconditioning is just an optimization, and you really want to
44 // make ||B - AX|| small, rather than ||M B - M (A X)||. If you're
45 // measuring ||B - AX|| and scaling by the initial residual, you
46 // should use the unpreconditioned initial residual to match it.
47 //
48 // Note, however, that the implicit residual test computes
49 // left-preconditioned residuals, if a left preconditioner was
50 // provided. That's OK because when Belos solvers (at least the
51 // GMRES variants) are given a left preconditioner, they first check
52 // the implicit residuals. If those converge, they then check the
53 // explicit residuals. The explicit residual test does _not_ apply
54 // the left preconditioner when computing the residual. The
55 // implicit residual test is just an optimization so that Belos
56 // doesn't have to compute explicit residuals B - A*X at every
57 // iteration. This is why we use the same scaling factor for both
58 // the implicit and explicit residuals.
59 //
60 // Arguments:
61 //
62 // solverParams [in/out] Parameters for the current solve.
63 //
64 // solverValidParams [in] Valid parameter list for the Belos solver.
65 // Result of calling the solver's getValidParameters() method.
66 //
67 // residualScalingType [in] String describing how the solver should
68 // scale residuals. Valid values include "Norm of RHS" and "Norm
69 // of Initial Residual" (these are the only two options this file
70 // currently uses, though Belos offers other options).
71 void
72 setResidualScalingType (const Teuchos::RCP<Teuchos::ParameterList>& solverParams,
73 const Teuchos::RCP<const Teuchos::ParameterList>& solverValidParams,
74 const std::string& residualScalingType)
75 {
76 // Many Belos solvers (especially the GMRES variants) define both
77 // "Implicit Residual Scaling" and "Explicit Residual Scaling"
78 // options.
79 //
80 // "Implicit" means "the left-preconditioned approximate
81 // a.k.a. 'recursive' residual as computed by the Krylov method."
82 //
83 // "Explicit" means ||B - A*X||, the unpreconditioned, "exact"
84 // residual.
85 //
86 // Belos' GMRES implementations chain these two tests in sequence.
87 // Implicit comes first, and explicit is not evaluated unless
88 // implicit passes. In some cases (e.g., no left preconditioner),
89 // GMRES _only_ uses the implicit tests. This means that only
90 // setting "Explicit Residual Scaling" won't change the solver's
91 // behavior. Stratimikos tends to prefer using a right
92 // preconditioner, in which case setting only the "Explicit
93 // Residual Scaling" argument has no effect. Furthermore, if
94 // "Explicit Residual Scaling" is set to something other than the
95 // default (initial residual norm), without "Implicit Residual
96 // Scaling" getting the same setting, then the implicit residual
97 // test will be using a radically different scaling factor than
98 // the user wanted.
99 //
100 // Not all Belos solvers support both options. We check the
101 // solver's valid parameter list first before attempting to set
102 // the option.
103 if (solverValidParams->isParameter ("Implicit Residual Scaling")) {
104 solverParams->set ("Implicit Residual Scaling", residualScalingType);
105 }
106 if (solverValidParams->isParameter ("Explicit Residual Scaling")) {
107 solverParams->set ("Explicit Residual Scaling", residualScalingType);
108 }
109 }
110
111} // namespace (anonymous)
112
113
114namespace Thyra {
115
116
117// Constructors/initializers/accessors
118
119
120template<class Scalar>
122 :convergenceTestFrequency_(-1),
123 isExternalPrec_(false),
124 supportSolveUse_(SUPPORT_SOLVE_UNSPECIFIED),
125 defaultTol_ (-1.0),
126 label_(""),
127 filenameLHS_(""),
128 filenameRHS_(""),
129 init_(false),
130 counter_(0)
131{}
132
133
134template<class Scalar>
137 const RCP<Teuchos::ParameterList> &solverPL,
138 const RCP<Belos::SolverManager<Scalar,MV_t,LO_t> > &iterativeSolver,
139 const RCP<const LinearOpSourceBase<Scalar> > &fwdOpSrc,
140 const RCP<const PreconditionerBase<Scalar> > &prec,
141 const bool isExternalPrec_in,
142 const RCP<const LinearOpSourceBase<Scalar> > &approxFwdOpSrc,
143 const ESupportSolveUse &supportSolveUse_in,
144 const int convergenceTestFrequency
145 )
146{
147 using Teuchos::as;
148 using Teuchos::TypeNameTraits;
149 using Teuchos::Exceptions::InvalidParameterType;
150 typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitude_type;
151
152 this->setLinePrefix("BELOS/T");
153 // ToDo: Validate input
154 lp_ = lp;
155 solverPL_ = solverPL;
156 iterativeSolver_ = iterativeSolver;
157 fwdOpSrc_ = fwdOpSrc;
158 prec_ = prec;
159 isExternalPrec_ = isExternalPrec_in;
160 approxFwdOpSrc_ = approxFwdOpSrc;
161 supportSolveUse_ = supportSolveUse_in;
162 convergenceTestFrequency_ = convergenceTestFrequency;
163 init_ = false;
164 // Check if "Convergence Tolerance" is in the solver parameter list. If
165 // not, use the default from the solver.
166 if ( !is_null(solverPL_) ) {
167 if (solverPL_->isParameter("Convergence Tolerance")) {
168
169 // Stratimikos prefers tolerances as double, no matter the
170 // Scalar type. However, we also want it to accept the
171 // tolerance as magnitude_type, for example float if the Scalar
172 // type is float or std::complex<float>.
173 if (solverPL_->isType<double> ("Convergence Tolerance")) {
174 defaultTol_ =
175 as<magnitude_type> (solverPL_->get<double> ("Convergence Tolerance"));
176 }
177 else if (std::is_same_v<double, magnitude_type>) {
178 // magnitude_type == double in this case, and we've already
179 // checked double above.
180 TEUCHOS_TEST_FOR_EXCEPTION(
181 true, std::invalid_argument, "BelosLinearOpWithSolve::initialize: "
182 "The \"Convergence Tolerance\" parameter, which you provided, must "
183 "have type double (the type of the magnitude of Scalar = double).");
184 }
185 else if (solverPL_->isType<magnitude_type> ("Convergence Tolerance")) {
186 defaultTol_ = solverPL_->get<magnitude_type> ("Convergence Tolerance");
187 }
188 else {
189 // Throwing InvalidParameterType ensures that the exception's
190 // type is consistent both with what this method would have
191 // thrown before for an unrecognized type, and with what the
192 // user expects in general when the parameter doesn't have the
193 // right type.
194 TEUCHOS_TEST_FOR_EXCEPTION(
195 true, InvalidParameterType, "BelosLinearOpWithSolve::initialize: "
196 "The \"Convergence Tolerance\" parameter, which you provided, must "
197 "have type double (preferred) or the type of the magnitude of Scalar "
198 "= " << TypeNameTraits<Scalar>::name () << ", which is " <<
199 TypeNameTraits<magnitude_type>::name () << " in this case. You can "
200 "find that type using Teuchos::ScalarTraits<Scalar>::magnitudeType.");
201 }
202 }
203
204 if (solverPL_->isParameter("Timer Label") && solverPL_->isType<std::string>("Timer Label")) {
205 label_ = solverPL_->get<std::string>("Timer Label");
206 lp_->setLabel(label_);
207 }
208 if (solverPL_->isParameter("Filename LHS") && solverPL_->isType<std::string>("Filename LHS")) {
209 filenameLHS_ = solverPL_->get<std::string>("Filename LHS");
210 }
211 if (solverPL_->isParameter("Filename RHS") && solverPL_->isType<std::string>("Filename RHS")) {
212 filenameRHS_ = solverPL_->get<std::string>("Filename RHS");
213 }
214 }
215 else {
216 RCP<const Teuchos::ParameterList> defaultPL =
217 iterativeSolver->getValidParameters();
218
219 // Stratimikos prefers tolerances as double, no matter the
220 // Scalar type. However, we also want it to accept the
221 // tolerance as magnitude_type, for example float if the Scalar
222 // type is float or std::complex<float>.
223 if (defaultPL->isType<double> ("Convergence Tolerance")) {
224 defaultTol_ =
225 as<magnitude_type> (defaultPL->get<double> ("Convergence Tolerance"));
226 }
227 else if (std::is_same_v<double, magnitude_type>) {
228 // magnitude_type == double in this case, and we've already
229 // checked double above.
230 TEUCHOS_TEST_FOR_EXCEPTION(
231 true, std::invalid_argument, "BelosLinearOpWithSolve::initialize: "
232 "The \"Convergence Tolerance\" parameter, which you provided, must "
233 "have type double (the type of the magnitude of Scalar = double).");
234 }
235 else if (defaultPL->isType<magnitude_type> ("Convergence Tolerance")) {
236 defaultTol_ = defaultPL->get<magnitude_type> ("Convergence Tolerance");
237 }
238 else {
239 // Throwing InvalidParameterType ensures that the exception's
240 // type is consistent both with what this method would have
241 // thrown before for an unrecognized type, and with what the
242 // user expects in general when the parameter doesn't have the
243 // right type.
244 TEUCHOS_TEST_FOR_EXCEPTION(
245 true, InvalidParameterType, "BelosLinearOpWithSolve::initialize: "
246 "The \"Convergence Tolerance\" parameter, which you provided, must "
247 "have type double (preferred) or the type of the magnitude of Scalar "
248 "= " << TypeNameTraits<Scalar>::name () << ", which is " <<
249 TypeNameTraits<magnitude_type>::name () << " in this case. You can "
250 "find that type using Teuchos::ScalarTraits<Scalar>::magnitudeType.");
251 }
252 }
253}
254
255
256template<class Scalar>
257RCP<const LinearOpSourceBase<Scalar> >
259{
260 RCP<const LinearOpSourceBase<Scalar> >
261 _fwdOpSrc = fwdOpSrc_;
262 fwdOpSrc_ = Teuchos::null;
263 return _fwdOpSrc;
264}
265
266
267template<class Scalar>
268RCP<const PreconditionerBase<Scalar> >
270{
271 RCP<const PreconditionerBase<Scalar> >
272 _prec = prec_;
273 prec_ = Teuchos::null;
274 return _prec;
275}
276
277
278template<class Scalar>
280{
281 return isExternalPrec_;
282}
283
284
285template<class Scalar>
286RCP<const LinearOpSourceBase<Scalar> >
288{
289 RCP<const LinearOpSourceBase<Scalar> >
290 _approxFwdOpSrc = approxFwdOpSrc_;
291 approxFwdOpSrc_ = Teuchos::null;
292 return _approxFwdOpSrc;
293}
294
295
296template<class Scalar>
298{
299 return supportSolveUse_;
300}
301
302
303template<class Scalar>
306 RCP<Teuchos::ParameterList> *solverPL,
307 RCP<Belos::SolverManager<Scalar,MV_t,LO_t> > *iterativeSolver,
308 RCP<const LinearOpSourceBase<Scalar> > *fwdOpSrc,
309 RCP<const PreconditionerBase<Scalar> > *prec,
310 bool *isExternalPrec_in,
311 RCP<const LinearOpSourceBase<Scalar> > *approxFwdOpSrc,
312 ESupportSolveUse *supportSolveUse_in
313 )
314{
315 if (lp) *lp = lp_;
316 if (solverPL) *solverPL = solverPL_;
317 if (iterativeSolver) *iterativeSolver = iterativeSolver_;
318 if (fwdOpSrc) *fwdOpSrc = fwdOpSrc_;
319 if (prec) *prec = prec_;
320 if (isExternalPrec_in) *isExternalPrec_in = isExternalPrec_;
321 if (approxFwdOpSrc) *approxFwdOpSrc = approxFwdOpSrc_;
322 if (supportSolveUse_in) *supportSolveUse_in = supportSolveUse_;
323
324 lp_ = Teuchos::null;
325 solverPL_ = Teuchos::null;
326 iterativeSolver_ = Teuchos::null;
327 fwdOpSrc_ = Teuchos::null;
328 prec_ = Teuchos::null;
329 isExternalPrec_ = false;
330 approxFwdOpSrc_ = Teuchos::null;
331 supportSolveUse_ = SUPPORT_SOLVE_UNSPECIFIED;
332 init_ = false;
333}
334
335
336// Overridden from LinearOpBase
337
338
339template<class Scalar>
340RCP< const VectorSpaceBase<Scalar> >
342{
343 if (!is_null(lp_))
344 return lp_->getOperator()->range();
345 return Teuchos::null;
346}
347
348
349template<class Scalar>
350RCP< const VectorSpaceBase<Scalar> >
352{
353 if (!is_null(lp_))
354 return lp_->getOperator()->domain();
355 return Teuchos::null;
356}
357
358
359template<class Scalar>
360RCP<const LinearOpBase<Scalar> >
362{
363 return Teuchos::null; // Not supported yet but could be
364}
365
366
367// Overridden from Teuchos::Describable
368
369
370template<class Scalar>
372{
373 std::ostringstream oss;
374 oss << Teuchos::Describable::description();
375 if ( !is_null(lp_) && !is_null(lp_->getOperator()) ) {
376 oss << "{";
377 oss << "iterativeSolver=\'"<<iterativeSolver_->description()<<"\'";
378 oss << ",fwdOp=\'"<<lp_->getOperator()->description()<<"\'";
379 if (lp_->getLeftPrec().get())
380 oss << ",leftPrecOp=\'"<<lp_->getLeftPrec()->description()<<"\'";
381 if (lp_->getRightPrec().get())
382 oss << ",rightPrecOp=\'"<<lp_->getRightPrec()->description()<<"\'";
383 oss << "}";
384 }
385 // ToDo: Make Belos::SolverManager derive from Teuchos::Describable so
386 // that we can get better information.
387 return oss.str();
388}
389
390
391template<class Scalar>
393 Teuchos::FancyOStream &out_arg,
394 const Teuchos::EVerbosityLevel verbLevel
395 ) const
396{
397 using Teuchos::FancyOStream;
398 using Teuchos::OSTab;
399 using Teuchos::describe;
400 RCP<FancyOStream> out = rcp(&out_arg,false);
401 OSTab tab(out);
402 switch (verbLevel) {
403 case Teuchos::VERB_DEFAULT: // fall-through
404 case Teuchos::VERB_LOW:
405 case Teuchos::VERB_MEDIUM: // fall-through
406 *out << this->description() << std::endl;
407 break;
408 case Teuchos::VERB_HIGH: // fall-through
409 case Teuchos::VERB_EXTREME:
410 {
411 *out
412 << Teuchos::Describable::description()<< "{"
413 << "rangeDim=" << this->range()->dim()
414 << ",domainDim=" << this->domain()->dim() << "}\n";
415 if (lp_->getOperator().get()) {
416 OSTab tab1(out);
417 *out
418 << "iterativeSolver = "<<describe(*iterativeSolver_,verbLevel)
419 << "fwdOp = " << describe(*lp_->getOperator(),verbLevel);
420 if (lp_->getLeftPrec().get())
421 *out << "leftPrecOp = "<<describe(*lp_->getLeftPrec(),verbLevel);
422 if (lp_->getRightPrec().get())
423 *out << "rightPrecOp = "<<describe(*lp_->getRightPrec(),verbLevel);
424 }
425 break;
426 }
427 default:
428 TEUCHOS_TEST_FOR_EXCEPT(true); // Should never get here!
429 }
430}
431
432
433// protected
434
435
436// Overridden from LinearOpBase
437
438
439template<class Scalar>
441{
442 return ::Thyra::opSupported(*lp_->getOperator(),M_trans);
443}
444
445
446template<class Scalar>
448 const EOpTransp M_trans,
449 const MultiVectorBase<Scalar> &X,
450 const Ptr<MultiVectorBase<Scalar> > &Y,
451 const Scalar alpha,
452 const Scalar beta
453 ) const
454{
455 ::Thyra::apply<Scalar>(*lp_->getOperator(), M_trans, X, Y, alpha, beta);
456}
457
458
459// Overridden from LinearOpWithSolveBase
460
461
462template<class Scalar>
463bool
465{
466 return solveSupportsNewImpl(M_trans, Teuchos::null);
467}
468
469
470template<class Scalar>
471bool
473 const Ptr<const SolveCriteria<Scalar> > /* solveCriteria */) const
474{
475 // Only support forward solve right now!
476 if (real_trans(transp)==NOTRANS) return true;
477 return false; // ToDo: Support adjoint solves!
478 // Otherwise, Thyra/Belos now supports every solve criteria type that exists
479 // because of the class Thyra::GeneralSolveCriteriaBelosStatusTest!
480/*
481 if (real_trans(M_trans)==NOTRANS) {
482 return (
483 solveMeasureType.useDefault()
484 ||
485 solveMeasureType(SOLVE_MEASURE_NORM_RESIDUAL,SOLVE_MEASURE_NORM_RHS)
486 ||
487 solveMeasureType(SOLVE_MEASURE_NORM_RESIDUAL,SOLVE_MEASURE_NORM_INIT_RESIDUAL)
488 );
489 }
490*/
491}
492
493
494template<class Scalar>
495bool
497 EOpTransp M_trans, const SolveMeasureType& solveMeasureType) const
498{
499 SolveCriteria<Scalar> solveCriteria(solveMeasureType, SolveCriteria<Scalar>::unspecifiedTolerance());
500 return solveSupportsNewImpl(M_trans, Teuchos::constOptInArg(solveCriteria));
501}
502
503
504template<class Scalar>
505SolveStatus<Scalar>
507 const EOpTransp M_trans,
508 const MultiVectorBase<Scalar> &B,
509 const Ptr<MultiVectorBase<Scalar> > &X,
510 const Ptr<const SolveCriteria<Scalar> > solveCriteria
511 ) const
512{
513
514 THYRA_FUNC_TIME_MONITOR("Stratimikos: BelosLOWS");
515
516 using Teuchos::rcp;
517 using Teuchos::rcpFromRef;
518 using Teuchos::rcpFromPtr;
519 using Teuchos::FancyOStream;
520 using Teuchos::OSTab;
521 using Teuchos::ParameterList;
522 using Teuchos::parameterList;
523 using Teuchos::describe;
524 typedef Teuchos::ScalarTraits<Scalar> ST;
525 typedef typename ST::magnitudeType ScalarMag;
526 Teuchos::Time totalTimer("Stratimikos::BelosLinearOpWithSolve::totalTime");
527 totalTimer.start(true);
528
529 assertSolveSupports(*this, M_trans, solveCriteria);
530 // 2010/08/22: rabartl: Bug 4915 ToDo: Move the above into the NIV function
531 // solve(...).
532
533 const RCP<FancyOStream> out = this->getOStream();
534 const Teuchos::EVerbosityLevel verbLevel = this->getVerbLevel();
535 OSTab tab = this->getOSTab();
536 if (out.get() && static_cast<int>(verbLevel) > static_cast<int>(Teuchos::VERB_LOW)) {
537 *out << "\nStarting iterations with Belos:\n";
538 OSTab tab2(out);
539 *out << "Using forward operator = " << describe(*fwdOpSrc_->getOp(),verbLevel);
540 *out << "Using iterative solver = " << describe(*iterativeSolver_,verbLevel);
541 *out << "With #Eqns="<<B.range()->dim()<<", #RHSs="<<B.domain()->dim()<<" ...\n";
542 }
543
544#ifdef HAVE_STRATIMIKOS_THYRATPETRAADAPTERS
545 //
546 // Write RHS and LHS to file if desired
547 //
548 if (filenameLHS_ != "") {
549 try {
550 auto tmv = Thyra::TpetraOperatorVectorExtraction<Scalar>::getTpetraMultiVector(Teuchos::rcpFromPtr(X));
551 Tpetra::MatrixMarket::Writer<::Tpetra::CrsMatrix<Scalar> >::writeDenseFile(filenameLHS_+ "." + label_ + "." + std::to_string(counter_), *tmv, "", "");
552 } catch (const std::logic_error&) {
553 *out << "Warning: Cannot write LHS multivector to file.\n";
554 }
555 }
556 if (filenameRHS_ != "") {
557 try {
558 auto tmv = Thyra::TpetraOperatorVectorExtraction<Scalar>::getConstTpetraMultiVector(Teuchos::rcpFromRef(B));
559 Tpetra::MatrixMarket::Writer<::Tpetra::CrsMatrix<Scalar> >::writeDenseFile(filenameRHS_+ "." + label_ + "." + std::to_string(counter_), *tmv, "", "");
560 } catch (const std::logic_error&) {
561 *out << "Warning: Cannot write RHS multivector to file.\n";
562 }
563 }
564 ++counter_;
565#endif
566
567 //
568 // Set RHS and LHS
569 //
570
571 bool ret = lp_->setProblem( rcpFromPtr(X), rcpFromRef(B) );
572 TEUCHOS_TEST_FOR_EXCEPTION(
573 ret == false, CatastrophicSolveFailure
574 ,"Error, the Belos::LinearProblem could not be set for the current solve!"
575 );
576
577 //
578 // Set the solution criteria
579 //
580
581 // Parameter list for the current solve.
582 const RCP<ParameterList> tmpPL = Teuchos::parameterList();
583
584 // The solver's valid parameter list.
585 RCP<const ParameterList> validPL = iterativeSolver_->getValidParameters();
586
587 SolveMeasureType solveMeasureType;
588 RCP<GeneralSolveCriteriaBelosStatusTest<Scalar> > generalSolveCriteriaBelosStatusTest;
589 if (nonnull(solveCriteria)) {
590 solveMeasureType = solveCriteria->solveMeasureType;
591 const ScalarMag requestedTol = solveCriteria->requestedTol;
592 if (solveMeasureType.useDefault()) {
593 tmpPL->set("Convergence Tolerance", defaultTol_);
594 }
595 else if (solveMeasureType(SOLVE_MEASURE_NORM_RESIDUAL, SOLVE_MEASURE_NORM_RHS)) {
596 if (requestedTol != SolveCriteria<Scalar>::unspecifiedTolerance()) {
597 tmpPL->set("Convergence Tolerance", requestedTol);
598 }
599 else {
600 tmpPL->set("Convergence Tolerance", defaultTol_);
601 }
602 setResidualScalingType (tmpPL, validPL, "Norm of RHS");
603 }
604 else if (solveMeasureType(SOLVE_MEASURE_NORM_RESIDUAL, SOLVE_MEASURE_NORM_INIT_RESIDUAL)) {
605 if (requestedTol != SolveCriteria<Scalar>::unspecifiedTolerance()) {
606 tmpPL->set("Convergence Tolerance", requestedTol);
607 }
608 else {
609 tmpPL->set("Convergence Tolerance", defaultTol_);
610 }
611 setResidualScalingType (tmpPL, validPL, "Norm of Initial Residual");
612 }
613 else {
614 // Set the most generic (and inefficient) solve criteria
615 generalSolveCriteriaBelosStatusTest = createGeneralSolveCriteriaBelosStatusTest(
616 *solveCriteria, convergenceTestFrequency_);
617 // Set the verbosity level (one level down)
618 generalSolveCriteriaBelosStatusTest->setOStream(out);
619 generalSolveCriteriaBelosStatusTest->setVerbLevel(incrVerbLevel(verbLevel, -1));
620 // Set the default convergence tolerance to always converged to allow
621 // the above status test to control things.
622 tmpPL->set("Convergence Tolerance", 1.0);
623 }
624 // maximum iterations
625 if (nonnull(solveCriteria->extraParameters)) {
626 if (Teuchos::isParameterType<int>(*solveCriteria->extraParameters,"Maximum Iterations")) {
627 tmpPL->set("Maximum Iterations", Teuchos::get<int>(*solveCriteria->extraParameters,"Maximum Iterations"));
628 }
629 }
630 // If a preconditioner is on the left, then the implicit residual test
631 // scaling should be the preconditioned initial residual.
632 if (Teuchos::nonnull(lp_->getLeftPrec()) &&
633 validPL->isParameter ("Implicit Residual Scaling"))
634 tmpPL->set("Implicit Residual Scaling",
635 "Norm of Preconditioned Initial Residual");
636 }
637 else {
638 // No solveCriteria was even passed in!
639 tmpPL->set("Convergence Tolerance", defaultTol_);
640 }
641
642 //
643 // Solve the linear system
644 //
645
646 Belos::ReturnType belosSolveStatus;
647 {
648 // Write detailed convergence information if requested for levels >= VERB_LOW
649 RCP<std::ostream>
650 outUsed =
651 ( static_cast<int>(verbLevel) >= static_cast<int>(Teuchos::VERB_LOW)
652 ? out
653 : rcp(new FancyOStream(rcp(new Teuchos::oblackholestream())))
654 );
655 Teuchos::OSTab tab1(outUsed,1,"BELOS");
656 tmpPL->set("Output Stream", outUsed);
657 if (!init_) {
658 iterativeSolver_->setParameters(tmpPL);
659 init_ = !nonnull(solveCriteria);
660 }
661 if (nonnull(generalSolveCriteriaBelosStatusTest)) {
662 iterativeSolver_->setUserConvStatusTest(generalSolveCriteriaBelosStatusTest);
663 }
664 try {
665 belosSolveStatus = iterativeSolver_->solve();
666 }
667 catch (Belos::BelosError& ex) {
668 TEUCHOS_TEST_FOR_EXCEPTION( true,
669 CatastrophicSolveFailure,
670 ex.what() );
671 }
672 }
673
674 //
675 // Report the solve status
676 //
677
678 totalTimer.stop();
679
680 SolveStatus<Scalar> solveStatus;
681 if (belosSolveStatus == Belos::Converged) {
682 solveStatus.solveStatus = SOLVE_STATUS_CONVERGED;
683 if (nonnull(generalSolveCriteriaBelosStatusTest)) {
684 // The user set a custom status test. This means that we
685 // should ask the custom status test itself, rather than the
686 // Belos solver, what the final achieved convergence tolerance
687 // was.
688 const ArrayView<const ScalarMag> achievedTol =
689 generalSolveCriteriaBelosStatusTest->achievedTol();
690 solveStatus.achievedTol = Teuchos::ScalarTraits<ScalarMag>::zero();
691 for (Ordinal i = 0; i < achievedTol.size(); ++i) {
692 solveStatus.achievedTol = std::max(solveStatus.achievedTol, achievedTol[i]);
693 }
694 }
695 else {
696 try {
697 // Some solvers might not have implemented achievedTol().
698 // The default implementation throws std::runtime_error.
699 solveStatus.achievedTol = iterativeSolver_->achievedTol();
700 } catch (std::runtime_error&) {
701 // Use the default convergence tolerance. This is a correct
702 // upper bound, since we did actually converge.
703 solveStatus.achievedTol = tmpPL->get("Convergence Tolerance", defaultTol_);
704 }
705 }
706 }
707 else {
708 solveStatus.solveStatus = SOLVE_STATUS_UNCONVERGED;
709 // Set achievedTol even if the solver did not converge. This is
710 // helpful for things like nonlinear solvers, which might be
711 // able to use a partially converged result, and which would
712 // like to know the achieved convergence tolerance for use in
713 // computing bounds. It's also helpful for estimating whether a
714 // small increase in the maximum iteration count might be
715 // helpful next time.
716 try {
717 // Some solvers might not have implemented achievedTol().
718 // The default implementation throws std::runtime_error.
719 solveStatus.achievedTol = iterativeSolver_->achievedTol();
720 } catch (std::runtime_error&) {
721 // Do nothing; use the default value of achievedTol.
722 }
723 }
724
725 std::ostringstream ossmessage;
726 ossmessage
727 << "The Belos solver " << (label_ != "" ? ("\"" + label_ + "\" ") : "")
728 << "of type \""<<iterativeSolver_->description()
729 <<"\" returned a solve status of \""<< toString(solveStatus.solveStatus) << "\""
730 << " in " << iterativeSolver_->getNumIters() << " iterations"
731 << " with total CPU time of " << totalTimer.totalElapsedTime() << " sec" ;
732 if (out.get() && static_cast<int>(verbLevel) > static_cast<int>(Teuchos::VERB_LOW))
733 *out << "\n" << ossmessage.str() << "\n";
734
735 solveStatus.message = ossmessage.str();
736
737 // Dump the getNumIters() and the achieved convergence tolerance
738 // into solveStatus.extraParameters, as the "Belos/Iteration Count"
739 // resp. "Belos/Achieved Tolerance" parameters.
740 if (solveStatus.extraParameters.is_null()) {
741 solveStatus.extraParameters = parameterList ();
742 }
743 solveStatus.extraParameters->set ("Belos/Iteration Count",
744 iterativeSolver_->getNumIters());\
745 // package independent version of the same
746 solveStatus.extraParameters->set ("Iteration Count",
747 iterativeSolver_->getNumIters());\
748 // NOTE (mfh 13 Dec 2011) Though the most commonly used Belos
749 // solvers do implement achievedTol(), some Belos solvers currently
750 // do not. In the latter case, if the solver did not converge, the
751 // reported achievedTol() value may just be the default "invalid"
752 // value -1, and if the solver did converge, the reported value will
753 // just be the convergence tolerance (a correct upper bound).
754 solveStatus.extraParameters->set ("Belos/Achieved Tolerance",
755 solveStatus.achievedTol);
756
757 solveStatus.extraParameters->template set<Belos::ReturnType> ("Belos/ReturnType",
758 belosSolveStatus);
759
760// This information is in the previous line, which is printed anytime the verbosity
761// is not set to Teuchos::VERB_NONE, so I'm commenting this out for now.
762// if (out.get() && static_cast<int>(verbLevel) > static_cast<int>(Teuchos::VERB_NONE))
763// *out << "\nTotal solve time in Belos = "<<totalTimer.totalElapsedTime()<<" sec\n";
764
765 //
766 // PseudoBlockCG
767 // The following gives access to the condition number estimate if the request was given to Belos' PseudoBlockCG.
768 //
769
771 // If a scalar type is not supported, the CG solver will not contain the function getConditionEstimate(),
772 // so we do a compile-time check for its existence.
773 if constexpr ( requires(const CGSolver& solver) {solver.getConditionEstimate();} ) {
774 auto cgSolver = Teuchos::rcp_dynamic_cast<CGSolver>(iterativeSolver_, false);
775 // Check if the solver is a pseudo block CG solver.
776 if (Teuchos::nonnull(cgSolver)) {
777 // Check if the user requested the condition number estimate.
778 const Teuchos::RCP<const Teuchos::ParameterList>& params = cgSolver->getCurrentParameters();
779 const bool estimateRequested = Teuchos::nonnull(params) &&
780 params->isParameter("Estimate Condition Number") &&
781 params->get<bool>("Estimate Condition Number");
782
783 if (estimateRequested) {
784 const Scalar condEstimate = cgSolver->getConditionEstimate();
785
786 // Normally, if the condition number was requested, it should be >= 1.
787 // If something goes wrong, it is initialized to -1, so we make this additional check.
788 if (condEstimate == -Teuchos::ScalarTraits<Scalar>::one()) {
789 if (out.get() && verbLevel != Teuchos::VERB_NONE) {
790 *out << "Warning: Belos PseudoBlockCG condition number estimation "
791 "was requested, but no estimate is available.\n";
792 }
793 } else {
794 // Return the condition number estimate as a solver status.
795 if (solveStatus.extraParameters.is_null()) {
796 solveStatus.extraParameters = parameterList();
797 }
798 solveStatus.extraParameters->set(
799 "Belos/Condition Number Estimate",
800 condEstimate);
801 solveStatus.extraParameters->set(
802 "Condition Number Estimate",
803 condEstimate);
804 }
805 }
806 }
807 }
808
809 return solveStatus;
810
811}
812
813
814} // end namespace Thyra
815
816
817#endif // THYRA_BELOS_LINEAR_OP_WITH_SOLVE_HPP
void uninitialize(RCP< Belos::LinearProblem< Scalar, MV_t, LO_t > > *lp=NULL, RCP< Teuchos::ParameterList > *solverPL=NULL, RCP< Belos::SolverManager< Scalar, MV_t, LO_t > > *iterativeSolver=NULL, RCP< const LinearOpSourceBase< Scalar > > *fwdOpSrc=NULL, RCP< const PreconditionerBase< Scalar > > *prec=NULL, bool *isExternalPrec=NULL, RCP< const LinearOpSourceBase< Scalar > > *approxFwdOpSrc=NULL, ESupportSolveUse *supportSolveUse=NULL)
Uninitializes and returns stored quantities.
RCP< const LinearOpBase< Scalar > > clone() const
virtual bool opSupportedImpl(EOpTransp M_trans) const
RCP< const VectorSpaceBase< Scalar > > domain() const
virtual bool solveSupportsNewImpl(EOpTransp transp, const Ptr< const SolveCriteria< Scalar > > solveCriteria) const
RCP< const VectorSpaceBase< Scalar > > range() const
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel) const
virtual SolveStatus< Scalar > solveImpl(const EOpTransp transp, const MultiVectorBase< Scalar > &B, const Ptr< MultiVectorBase< Scalar > > &X, const Ptr< const SolveCriteria< Scalar > > solveCriteria) const
virtual bool solveSupportsSolveMeasureTypeImpl(EOpTransp M_trans, const SolveMeasureType &solveMeasureType) const
RCP< const LinearOpSourceBase< Scalar > > extract_approxFwdOpSrc()
RCP< const PreconditionerBase< Scalar > > extract_prec()
virtual bool solveSupportsImpl(EOpTransp M_trans) const
RCP< const LinearOpSourceBase< Scalar > > extract_fwdOpSrc()
virtual void applyImpl(const EOpTransp M_trans, const MultiVectorBase< Scalar > &X, const Ptr< MultiVectorBase< Scalar > > &Y, const Scalar alpha, const Scalar beta) const
void initialize(const RCP< Belos::LinearProblem< Scalar, MV_t, LO_t > > &lp, const RCP< Teuchos::ParameterList > &solverPL, const RCP< Belos::SolverManager< Scalar, MV_t, LO_t > > &iterativeSolver, const RCP< const LinearOpSourceBase< Scalar > > &fwdOpSrc, const RCP< const PreconditionerBase< Scalar > > &prec, const bool isExternalPrec, const RCP< const LinearOpSourceBase< Scalar > > &approxFwdOpSrc, const ESupportSolveUse &supportSolveUse, const int convergenceTestFrequency)
Initializes given precreated solver objects.
RCP< GeneralSolveCriteriaBelosStatusTest< Scalar > > createGeneralSolveCriteriaBelosStatusTest(const SolveCriteria< Scalar > &solveCriteria, const int convergenceTestFrequency)
Nonmember constructor.
NOTRANS

Generated for Stratimikos by doxygen 1.15.0