Belos Version of the Day
Loading...
Searching...
No Matches
BelosPseudoBlockCGSolMgr.hpp
Go to the documentation of this file.
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_PSEUDO_BLOCK_CG_SOLMGR_HPP
11#define BELOS_PSEUDO_BLOCK_CG_SOLMGR_HPP
12
16
17#include "BelosCGIteration.hpp"
18#include "BelosConfigDefs.hpp"
19#include "BelosTypes.hpp"
20
23
25#include "BelosCGIter.hpp"
31#include "Teuchos_LAPACK.hpp"
32#ifdef BELOS_TEUCHOS_TIME_MONITOR
33#include "Teuchos_TimeMonitor.hpp"
34#endif
35
45
54
55namespace Belos {
56
58
59
67 PseudoBlockCGSolMgrLinearProblemFailure(const std::string& what_arg) : BelosError(what_arg)
68 {}};
69
70
71 // Partial specialization for unsupported ScalarType types.
72 // This contains a stub implementation.
73 template<class ScalarType, class MV, class OP, class DM = DefaultDenseMatrix<int,ScalarType>,
74 const bool supportsScalarType =
75 Details::LapackSupportsScalar<ScalarType>::value>
77 public Details::SolverManagerRequiresLapack<ScalarType, MV, OP, DM,
78 Details::LapackSupportsScalar<ScalarType>::value>
79 {
80 static const bool scalarTypeIsSupported =
83
84 public:
86 base_type ()
87 {}
89 const Teuchos::RCP<Teuchos::ParameterList> &pl) :
90 base_type ()
91 {}
92 virtual ~PseudoBlockCGSolMgr () = default;
93
94 Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP,DM> >
95 getResidualStatusTest() const { return Teuchos::null; }
96 };
97
98
99 template<class ScalarType, class MV, class OP, class DM>
100 class PseudoBlockCGSolMgr<ScalarType, MV, OP, DM, true> :
101 public Details::SolverManagerRequiresLapack<ScalarType, MV, OP, DM, true>
102 {
103 private:
106 using SCT = Teuchos::ScalarTraits<ScalarType>;
107 using MagnitudeType = typename Teuchos::ScalarTraits<ScalarType>::magnitudeType;
108 using MT = Teuchos::ScalarTraits<MagnitudeType>;
109
110 public:
111
113
114
121
137 PseudoBlockCGSolMgr( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP,DM> > &problem,
138 const Teuchos::RCP<Teuchos::ParameterList> &pl );
139
141 virtual ~PseudoBlockCGSolMgr() = default;
142
144 Teuchos::RCP<SolverManager<ScalarType, MV, OP, DM> > clone () const override {
145 return Teuchos::rcp(new PseudoBlockCGSolMgr<ScalarType,MV,OP,DM>);
146 }
147
148
150
151
153 return *problem_;
154 }
155
158 Teuchos::RCP<const Teuchos::ParameterList> getValidParameters() const override;
159
162 Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters() const override { return params_; }
163
169 Teuchos::Array<Teuchos::RCP<Teuchos::Time> > getTimers() const {
170 return Teuchos::tuple(timerSolve_);
171 }
172
173
184 MagnitudeType achievedTol() const override {
185 return achievedTol_;
186 }
187
189 int getNumIters() const override {
190 return numIters_;
191 }
192
196 bool isLOADetected() const override { return false; }
197
201 ScalarType getConditionEstimate() const {return condEstimate_;}
202 Teuchos::ArrayRCP<MagnitudeType> getEigenEstimates() const {return eigenEstimates_;}
203
205 Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP,DM> >
206 getResidualStatusTest() const { return convTest_; }
207
209
211
212
214 void setProblem( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP,DM> > &problem ) override { problem_ = problem; }
215
217 void setParameters( const Teuchos::RCP<Teuchos::ParameterList> &params ) override;
218
220 void setDebugStatusTest( const Teuchos::RCP<StatusTest<ScalarType,MV,OP,DM> > &debugStatusTest ) override {
221 debugStatusTest_ = debugStatusTest;
222 // Force the cached status-test tree (and its output wrapper) to be rebuilt
223 // on the next solve so the debug test is wired into sTest_. This manager
224 // caches sTest_/outputTest_ behind null checks, so clear them and re-run
225 // setParameters.
226 sTest_ = Teuchos::null;
227 outputTest_ = Teuchos::null;
228 isSet_ = false;
229 }
230
232
234
235
239 void reset( const ResetType type ) override { if ((type & Belos::Problem) && !Teuchos::is_null(problem_)) problem_->setProblem(); }
241
243
244
262 ReturnType solve() override;
263
265
268
270 std::string description() const override;
271
273 private:
274 // Compute the condition number estimate
275 void compute_condnum_tridiag_sym(Teuchos::ArrayView<MagnitudeType> diag,
276 Teuchos::ArrayView<MagnitudeType> offdiag,
277 Teuchos::ArrayRCP<MagnitudeType>& lambdas,
278 ScalarType & lambda_min,
279 ScalarType & lambda_max,
280 ScalarType & ConditionNumber );
281
282 // Linear problem.
283 Teuchos::RCP<LinearProblem<ScalarType,MV,OP,DM> > problem_;
284
285 // Output manager.
286 Teuchos::RCP<OutputManager<ScalarType> > printer_;
287 Teuchos::RCP<std::ostream> outputStream_;
288
289 // Status test.
290 Teuchos::RCP<StatusTest<ScalarType,MV,OP,DM> > sTest_;
291 Teuchos::RCP<StatusTestMaxIters<ScalarType,MV,OP,DM> > maxIterTest_;
292 Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP,DM> > convTest_;
293 Teuchos::RCP<StatusTestOutput<ScalarType,MV,OP,DM> > outputTest_;
294 Teuchos::RCP<StatusTest<ScalarType,MV,OP,DM> > debugStatusTest_;
295
296 // Current parameter list.
297 Teuchos::RCP<Teuchos::ParameterList> params_;
298
304 mutable Teuchos::RCP<const Teuchos::ParameterList> validParams_;
305
306 // Default solver values.
307 static constexpr int maxIters_default_ = 1000;
308 static constexpr bool assertPositiveDefiniteness_default_ = true;
309 static constexpr bool showMaxResNormOnly_default_ = false;
310 static constexpr int verbosity_default_ = Belos::Errors;
311 static constexpr int outputStyle_default_ = Belos::General;
312 static constexpr int outputFreq_default_ = -1;
313 static constexpr int defQuorum_default_ = 1;
314 static constexpr bool foldConvergenceDetectionIntoAllreduce_default_ = false;
315 static constexpr const char * resScale_default_ = "Norm of Initial Residual";
316 static constexpr const char * label_default_ = "Belos";
317 static constexpr bool genCondEst_default_ = false;
318
319 // Current solver values.
320 MagnitudeType convtol_,achievedTol_;
321 int maxIters_, numIters_;
322 int verbosity_, outputStyle_, outputFreq_, defQuorum_;
323 bool assertPositiveDefiniteness_, showMaxResNormOnly_;
324 bool foldConvergenceDetectionIntoAllreduce_;
325 std::string resScale_;
326 bool genCondEst_;
327 ScalarType condEstimate_;
328 Teuchos::ArrayRCP<MagnitudeType> eigenEstimates_;
329
330 Teuchos::RCP<CGIterationStateBase<ScalarType, MV, DM> > state_;
331
332 // Timers.
333 std::string label_;
334 Teuchos::RCP<Teuchos::Time> timerSolve_;
335
336 // Internal state variables.
337 bool isSet_;
338 };
339
340
341// Empty Constructor
342template<class ScalarType, class MV, class OP, class DM>
344 outputStream_(Teuchos::rcpFromRef(std::cout)),
345 convtol_(DefaultSolverParameters::convTol),
346 maxIters_(maxIters_default_),
347 numIters_(0),
348 verbosity_(verbosity_default_),
349 outputStyle_(outputStyle_default_),
350 outputFreq_(outputFreq_default_),
351 defQuorum_(defQuorum_default_),
352 assertPositiveDefiniteness_(assertPositiveDefiniteness_default_),
353 showMaxResNormOnly_(showMaxResNormOnly_default_),
354 foldConvergenceDetectionIntoAllreduce_(foldConvergenceDetectionIntoAllreduce_default_),
355 resScale_(resScale_default_),
356 genCondEst_(genCondEst_default_),
357 condEstimate_(-Teuchos::ScalarTraits<ScalarType>::one()),
358 label_(label_default_),
359 isSet_(false)
360{}
361
362// Basic Constructor
363template<class ScalarType, class MV, class OP, class DM>
365PseudoBlockCGSolMgr (const Teuchos::RCP<LinearProblem<ScalarType,MV,OP,DM> > &problem,
366 const Teuchos::RCP<Teuchos::ParameterList> &pl ) :
367 problem_(problem),
368 outputStream_(Teuchos::rcpFromRef(std::cout)),
369 convtol_(DefaultSolverParameters::convTol),
370 maxIters_(maxIters_default_),
371 numIters_(0),
372 verbosity_(verbosity_default_),
373 outputStyle_(outputStyle_default_),
374 outputFreq_(outputFreq_default_),
375 defQuorum_(defQuorum_default_),
376 assertPositiveDefiniteness_(assertPositiveDefiniteness_default_),
377 showMaxResNormOnly_(showMaxResNormOnly_default_),
378 foldConvergenceDetectionIntoAllreduce_(foldConvergenceDetectionIntoAllreduce_default_),
379 resScale_(resScale_default_),
380 genCondEst_(genCondEst_default_),
381 condEstimate_(-Teuchos::ScalarTraits<ScalarType>::one()),
382 label_(label_default_),
383 isSet_(false)
384{
385 TEUCHOS_TEST_FOR_EXCEPTION(
386 problem_.is_null (), std::invalid_argument,
387 "Belos::PseudoBlockCGSolMgr two-argument constructor: "
388 "'problem' is null. You must supply a non-null Belos::LinearProblem "
389 "instance when calling this constructor.");
390
391 if (! pl.is_null ()) {
392 // Set the parameters using the list that was passed in.
393 setParameters (pl);
394 }
395}
396
397template<class ScalarType, class MV, class OP, class DM>
399setParameters (const Teuchos::RCP<Teuchos::ParameterList>& params)
400{
401 using Teuchos::ParameterList;
402 using Teuchos::parameterList;
403 using Teuchos::RCP;
404 using Teuchos::rcp;
405
406 RCP<const ParameterList> defaultParams = this->getValidParameters ();
407
408 // Create the internal parameter list if one doesn't already exist.
409 // Belos' solvers treat the input ParameterList to setParameters as
410 // a "delta" -- that is, a change from the current state -- so the
411 // default parameter list (if the input is null) should be empty.
412 // This explains also why Belos' solvers copy parameters one by one
413 // from the input list to the current list.
414 //
415 // Belos obfuscates the latter, because it takes the input parameter
416 // list by RCP, rather than by (nonconst) reference. The latter
417 // would make more sense, given that it doesn't actually keep the
418 // input parameter list.
419 //
420 // Note, however, that Belos still correctly triggers the "used"
421 // field of each parameter in the input list. While isParameter()
422 // doesn't (apparently) trigger the "used" flag, get() certainly
423 // does.
424
425 if (params_.is_null ()) {
426 // Create an empty list with the same name as the default list.
427 params_ = parameterList (defaultParams->name ());
428 } else {
429 params->validateParameters (*defaultParams);
430 }
431
432 // Check for maximum number of iterations
433 if (params->isParameter ("Maximum Iterations")) {
434 maxIters_ = params->get ("Maximum Iterations", maxIters_default_);
435
436 // Update parameter in our list and in status test.
437 params_->set ("Maximum Iterations", maxIters_);
438 if (! maxIterTest_.is_null ()) {
439 maxIterTest_->setMaxIters (maxIters_);
440 }
441 }
442
443 // Check if positive definiteness assertions are to be performed
444 if (params->isParameter ("Assert Positive Definiteness")) {
445 assertPositiveDefiniteness_ =
446 params->get ("Assert Positive Definiteness",
447 assertPositiveDefiniteness_default_);
448
449 // Update parameter in our list.
450 params_->set ("Assert Positive Definiteness", assertPositiveDefiniteness_);
451 }
452
453 if (params->isParameter("Fold Convergence Detection Into Allreduce")) {
454 foldConvergenceDetectionIntoAllreduce_ = params->get("Fold Convergence Detection Into Allreduce",
455 foldConvergenceDetectionIntoAllreduce_default_);
456 }
457
458 // Check to see if the timer label changed.
459 if (params->isParameter ("Timer Label")) {
460 const std::string tempLabel = params->get ("Timer Label", label_default_);
461
462 // Update parameter in our list and solver timer
463 if (tempLabel != label_) {
464 label_ = tempLabel;
465 params_->set ("Timer Label", label_);
466 const std::string solveLabel =
467 label_ + ": PseudoBlockCGSolMgr total solve time";
468#ifdef BELOS_TEUCHOS_TIME_MONITOR
469 timerSolve_ = Teuchos::TimeMonitor::getNewCounter (solveLabel);
470#endif
471 }
472 }
473
474 // Check for a change in verbosity level
475 if (params->isParameter ("Verbosity")) {
476 if (Teuchos::isParameterType<int> (*params, "Verbosity")) {
477 verbosity_ = params->get ("Verbosity", verbosity_default_);
478 } else {
479 verbosity_ = (int) Teuchos::getParameter<Belos::MsgType> (*params, "Verbosity");
480 }
481
482 // Update parameter in our list.
483 params_->set ("Verbosity", verbosity_);
484 if (! printer_.is_null ()) {
485 printer_->setVerbosity (verbosity_);
486 }
487 }
488
489 // Check for a change in output style
490 if (params->isParameter ("Output Style")) {
491 if (Teuchos::isParameterType<int> (*params, "Output Style")) {
492 outputStyle_ = params->get ("Output Style", outputStyle_default_);
493 } else {
494 // FIXME (mfh 29 Jul 2015) What if the type is wrong?
495 outputStyle_ = (int) Teuchos::getParameter<Belos::OutputType> (*params, "Output Style");
496 }
497
498 // Reconstruct the convergence test if the explicit residual test
499 // is not being used.
500 params_->set ("Output Style", outputStyle_);
501 outputTest_ = Teuchos::null;
502 }
503
504 // output stream
505 if (params->isParameter ("Output Stream")) {
506 outputStream_ = params->get<RCP<std::ostream> > ("Output Stream");
507
508 // Update parameter in our list.
509 params_->set ("Output Stream", outputStream_);
510 if (! printer_.is_null ()) {
511 printer_->setOStream (outputStream_);
512 }
513 }
514
515 // frequency level
516 if (verbosity_ & Belos::StatusTestDetails) {
517 if (params->isParameter ("Output Frequency")) {
518 outputFreq_ = params->get ("Output Frequency", outputFreq_default_);
519 }
520
521 // Update parameter in out list and output status test.
522 params_->set ("Output Frequency", outputFreq_);
523 if (! outputTest_.is_null ()) {
524 outputTest_->setOutputFrequency (outputFreq_);
525 }
526 }
527
528 // Condition estimate
529 if (params->isParameter ("Estimate Condition Number")) {
530 genCondEst_ = params->get ("Estimate Condition Number", genCondEst_default_);
531
532 // Update parameter in our list.
533 params_->set("Estimate Condition Number", genCondEst_);
534 }
535
536 // Create output manager if we need to.
537 if (printer_.is_null ()) {
538 printer_ = rcp (new OutputManager<ScalarType> (verbosity_, outputStream_));
539 }
540
541 // Convergence
542 using StatusTestCombo_t = Belos::StatusTestCombo<ScalarType, MV, OP, DM>;
543 using StatusTestResNorm_t = Belos::StatusTestGenResNorm<ScalarType, MV, OP, DM>;
544
545 // Check for convergence tolerance
546 if (params->isParameter ("Convergence Tolerance")) {
547 if (params->isType<MagnitudeType> ("Convergence Tolerance")) {
548 convtol_ = params->get ("Convergence Tolerance",
549 static_cast<MagnitudeType> (DefaultSolverParameters::convTol));
550 }
551 else {
552 convtol_ = params->get ("Convergence Tolerance", DefaultSolverParameters::convTol);
553 }
554
555 // Update parameter in our list and residual tests.
556 params_->set ("Convergence Tolerance", convtol_);
557 if (! convTest_.is_null ()) {
558 convTest_->setTolerance (convtol_);
559 }
560 }
561
562 if (params->isParameter ("Show Maximum Residual Norm Only")) {
563 showMaxResNormOnly_ = params->get<bool> ("Show Maximum Residual Norm Only");
564
565 // Update parameter in our list and residual tests
566 params_->set ("Show Maximum Residual Norm Only", showMaxResNormOnly_);
567 if (! convTest_.is_null ()) {
568 convTest_->setShowMaxResNormOnly (showMaxResNormOnly_);
569 }
570 }
571
572 // Check for a change in scaling, if so we need to build new residual tests.
573 bool newResTest = false;
574 {
575 // "Residual Scaling" is the old parameter name; "Implicit
576 // Residual Scaling" is the new name. We support both options for
577 // backwards compatibility.
578 std::string tempResScale = resScale_;
579 bool implicitResidualScalingName = false;
580 if (params->isParameter ("Residual Scaling")) {
581 tempResScale = params->get<std::string> ("Residual Scaling");
582 }
583 else if (params->isParameter ("Implicit Residual Scaling")) {
584 tempResScale = params->get<std::string> ("Implicit Residual Scaling");
585 implicitResidualScalingName = true;
586 }
587
588 // Only update the scaling if it's different.
589 if (resScale_ != tempResScale) {
590 const Belos::ScaleType resScaleType =
591 convertStringToScaleType (tempResScale);
592 resScale_ = tempResScale;
593
594 // Update parameter in our list and residual tests, using the
595 // given parameter name.
596 if (implicitResidualScalingName) {
597 params_->set ("Implicit Residual Scaling", resScale_);
598 }
599 else {
600 params_->set ("Residual Scaling", resScale_);
601 }
602
603 if (! convTest_.is_null ()) {
604 try {
605 convTest_->defineScaleForm (resScaleType, Belos::TwoNorm);
606 }
607 catch (std::exception& e) {
608 // Make sure the convergence test gets constructed again.
609 newResTest = true;
610 }
611 }
612 }
613 }
614
615 // Get the deflation quorum, or number of converged systems before deflation is allowed
616 if (params->isParameter ("Deflation Quorum")) {
617 defQuorum_ = params->get ("Deflation Quorum", defQuorum_);
618 params_->set ("Deflation Quorum", defQuorum_);
619 if (! convTest_.is_null ()) {
620 convTest_->setQuorum( defQuorum_ );
621 }
622 }
623
624 // Create status tests if we need to.
625
626 // Basic test checks maximum iterations and native residual.
627 if (maxIterTest_.is_null ()) {
628 maxIterTest_ = rcp (new StatusTestMaxIters<ScalarType,MV,OP,DM> (maxIters_));
629 }
630
631 // Implicit residual test, using the native residual to determine if convergence was achieved.
632 if (convTest_.is_null () || newResTest) {
633 convTest_ = rcp (new StatusTestResNorm_t (convtol_, defQuorum_, showMaxResNormOnly_));
634 convTest_->defineScaleForm (convertStringToScaleType (resScale_), Belos::TwoNorm);
635 }
636
637 if (sTest_.is_null () || newResTest) {
638 sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR, maxIterTest_, convTest_));
639 if (Teuchos::nonnull(debugStatusTest_)) {
640 // Add the debug convergence test, if it exists.
641 sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR, sTest_, debugStatusTest_));
642 }
643 }
644
645 if (outputTest_.is_null () || newResTest) {
646 // Create the status test output class.
647 // This class manages and formats the output from the status test.
648 StatusTestOutputFactory<ScalarType,MV,OP,DM> stoFactory (outputStyle_);
649 outputTest_ = stoFactory.create (printer_, sTest_, outputFreq_,
651
652 // Set the solver string for the output test
653 const std::string solverDesc = " Pseudo Block CG ";
654 outputTest_->setSolverDesc (solverDesc);
655 }
656
657 // Create the timer if we need to.
658 if (timerSolve_.is_null ()) {
659 const std::string solveLabel =
660 label_ + ": PseudoBlockCGSolMgr total solve time";
661#ifdef BELOS_TEUCHOS_TIME_MONITOR
662 timerSolve_ = Teuchos::TimeMonitor::getNewCounter (solveLabel);
663#endif
664 }
665
666 // Inform the solver manager that the current parameters were set.
667 isSet_ = true;
668}
669
670
671template<class ScalarType, class MV, class OP, class DM>
672Teuchos::RCP<const Teuchos::ParameterList>
674{
675 using Teuchos::ParameterList;
676 using Teuchos::parameterList;
677 using Teuchos::RCP;
678
679 if (validParams_.is_null()) {
680 // Set all the valid parameters and their default values.
681 RCP<ParameterList> pl = parameterList ();
682 pl->set("Convergence Tolerance", static_cast<MagnitudeType>(DefaultSolverParameters::convTol),
683 "The relative residual tolerance that needs to be achieved by the\n"
684 "iterative solver in order for the linear system to be declared converged.");
685 pl->set("Maximum Iterations", static_cast<int>(maxIters_default_),
686 "The maximum number of block iterations allowed for each\n"
687 "set of RHS solved.");
688 pl->set("Assert Positive Definiteness", static_cast<bool>(assertPositiveDefiniteness_default_),
689 "Whether or not to assert that the linear operator\n"
690 "and the preconditioner are indeed positive definite.");
691 pl->set("Verbosity", static_cast<int>(verbosity_default_),
692 "What type(s) of solver information should be outputted\n"
693 "to the output stream.");
694 pl->set("Output Style", static_cast<int>(outputStyle_default_),
695 "What style is used for the solver information outputted\n"
696 "to the output stream.");
697 pl->set("Output Frequency", static_cast<int>(outputFreq_default_),
698 "How often convergence information should be outputted\n"
699 "to the output stream.");
700 pl->set("Deflation Quorum", static_cast<int>(defQuorum_default_),
701 "The number of linear systems that need to converge before\n"
702 "they are deflated. This number should be <= block size.");
703 pl->set("Output Stream", Teuchos::rcpFromRef(std::cout),
704 "A reference-counted pointer to the output stream where all\n"
705 "solver output is sent.");
706 pl->set("Show Maximum Residual Norm Only", static_cast<bool>(showMaxResNormOnly_default_),
707 "When convergence information is printed, only show the maximum\n"
708 "relative residual norm when the block size is greater than one.");
709 pl->set("Implicit Residual Scaling", resScale_default_,
710 "The type of scaling used in the residual convergence test.");
711 pl->set("Estimate Condition Number", static_cast<bool>(genCondEst_default_),
712 "Whether or not to estimate the condition number of the preconditioned system.");
713 // We leave the old name as a valid parameter for backwards
714 // compatibility (so that validateParametersAndSetDefaults()
715 // doesn't raise an exception if it encounters "Residual
716 // Scaling"). The new name was added for compatibility with other
717 // solvers, none of which use "Residual Scaling".
718 pl->set("Residual Scaling", resScale_default_,
719 "The type of scaling used in the residual convergence test. This "
720 "name is deprecated; the new name is \"Implicit Residual Scaling\".");
721 pl->set("Timer Label", static_cast<const char *>(label_default_),
722 "The string to use as a prefix for the timer labels.");
723 pl->set("Fold Convergence Detection Into Allreduce",static_cast<bool>(foldConvergenceDetectionIntoAllreduce_default_),
724 "Merge the allreduce for convergence detection with the one for CG.\n"
725 "This saves one all-reduce, but incurs more computation.");
726 validParams_ = pl;
727 }
728 return validParams_;
729}
730
731
732// solve()
733template<class ScalarType, class MV, class OP, class DM>
735{
736 // Re-initialize the condition number estimate in case of consecutive runs.
737 condEstimate_ = -Teuchos::ScalarTraits<ScalarType>::one();
738
739 const char prefix[] = "Belos::PseudoBlockCGSolMgr::solve: ";
740
741 ReturnType retType = Undetermined;
742
743 // Set the current parameters if they were not set before.
744 // NOTE: This may occur if the user generated the solver manager with the default constructor and
745 // then didn't set any parameters using setParameters().
746 if (!isSet_) { setParameters( params_ ); }
747
748 TEUCHOS_TEST_FOR_EXCEPTION
749 (! problem_->isProblemSet (), PseudoBlockCGSolMgrLinearProblemFailure,
750 prefix << "The linear problem to solve is not ready. You must call "
751 "setProblem() on the Belos::LinearProblem instance before telling the "
752 "Belos solver to solve it.");
753
754 // Create indices for the linear systems to be solved.
755 int startPtr = 0;
756 int numRHS2Solve = MVT::GetNumberVecs( *(problem_->getRHS()) );
757 int numCurrRHS = numRHS2Solve;
758
759 std::vector<int> currIdx( numRHS2Solve ), currIdx2( numRHS2Solve );
760 for (int i=0; i<numRHS2Solve; ++i) {
761 currIdx[i] = startPtr+i;
762 currIdx2[i]=i;
763 }
764
765 // Inform the linear problem of the current linear system to solve.
766 problem_->setLSIndex( currIdx );
767
769 // Parameter list (iteration)
770 Teuchos::ParameterList plist;
771
772 plist.set("Assert Positive Definiteness",assertPositiveDefiniteness_);
773 if(genCondEst_) plist.set("Max Size For Condest",maxIters_);
774
775 // Reset the status test.
776 outputTest_->reset();
777
778 // Assume convergence is achieved, then let any failed convergence set this to false.
779 bool isConverged = true;
780
782 // Pseudo-Block CG solver
783 Teuchos::RCP<CGIteration<ScalarType,MV,OP,DM> > block_cg_iter;
784 if (numRHS2Solve == 1) {
785 plist.set("Fold Convergence Detection Into Allreduce",
786 foldConvergenceDetectionIntoAllreduce_);
787 block_cg_iter =
788 Teuchos::rcp (new CGIter<ScalarType,MV,OP,DM> (problem_, printer_, outputTest_, convTest_, plist));
789 if (state_.is_null() || Teuchos::rcp_dynamic_cast<CGIterationState<ScalarType, MV, DM> >(state_).is_null())
790 state_ = Teuchos::rcp(new CGIterationState<ScalarType, MV, DM>());
791 } else {
792 block_cg_iter =
793 Teuchos::rcp (new PseudoBlockCGIter<ScalarType,MV,OP,DM> (problem_, printer_, outputTest_, plist));
794 if (state_.is_null() || Teuchos::rcp_dynamic_cast<PseudoBlockCGIterationState<ScalarType, MV, DM> >(state_).is_null())
795 state_ = Teuchos::rcp(new PseudoBlockCGIterationState<ScalarType, MV, DM>());
796 }
797
798 // Setup condition estimate
799 block_cg_iter->setDoCondEst(genCondEst_);
800 bool condEstPerf = false;
801
802 // Enter solve() iterations
803 {
804#ifdef BELOS_TEUCHOS_TIME_MONITOR
805 Teuchos::TimeMonitor slvtimer(*timerSolve_);
806#endif
807
808 while ( numRHS2Solve > 0 ) {
809
810 // Reset the active / converged vectors from this block
811 std::vector<int> convRHSIdx;
812 std::vector<int> currRHSIdx( currIdx );
813 currRHSIdx.resize(numCurrRHS);
814
815 // Reset the number of iterations.
816 block_cg_iter->resetNumIters();
817
818 // Reset the number of calls that the status test output knows about.
819 outputTest_->resetNumCalls();
820
821 // Get the current residual for this block of linear systems.
822 Teuchos::RCP<MV> R_0 = MVT::CloneViewNonConst( *(Teuchos::rcp_const_cast<MV>(problem_->getInitResVec())), currIdx );
823
824 // Get a new state struct and initialize the solver.
825 block_cg_iter->initializeCG(state_, R_0);
826
827 while(true) {
828
829 // tell block_gmres_iter to iterate
830 try {
831
832 block_cg_iter->iterate();
833
835 //
836 // check convergence first
837 //
839 if ( convTest_->getStatus() == Passed ) {
840
841 // Figure out which linear systems converged.
842 std::vector<int> convIdx = Teuchos::rcp_dynamic_cast<StatusTestGenResNorm<ScalarType,MV,OP,DM> >(convTest_)->convIndices();
843
844 // If the number of converged linear systems is equal to the
845 // number of current linear systems, then we are done with this block.
846 if (convIdx.size() == currRHSIdx.size())
847 break; // break from while(1){block_cg_iter->iterate()}
848
849 // Inform the linear problem that we are finished with this current linear system.
850 problem_->setCurrLS();
851
852 // Reset currRHSIdx to have the right-hand sides that are left to converge for this block.
853 int have = 0;
854 for (unsigned int i=0; i<currRHSIdx.size(); ++i) {
855 bool found = false;
856 for (unsigned int j=0; j<convIdx.size(); ++j) {
857 if (currRHSIdx[i] == convIdx[j]) {
858 found = true;
859 break;
860 }
861 }
862 if (!found) {
863 currIdx2[have] = currIdx2[i];
864 currRHSIdx[have++] = currRHSIdx[i];
865 }
866 }
867 currRHSIdx.resize(have);
868 currIdx2.resize(have);
869
870 // Compute condition estimate if the very first linear system in the block has converged.
871 if (currRHSIdx[0] != 0 && genCondEst_ && !condEstPerf)
872 {
873 // Compute the estimate.
874 ScalarType l_min, l_max;
875 Teuchos::ArrayView<MagnitudeType> diag = block_cg_iter->getDiag();
876 Teuchos::ArrayView<MagnitudeType> offdiag = block_cg_iter->getOffDiag();
877 compute_condnum_tridiag_sym(diag,offdiag,eigenEstimates_,l_min,l_max,condEstimate_);
878
879 // Make sure not to do more condition estimate computations for this solve.
880 block_cg_iter->setDoCondEst(false);
881 condEstPerf = true;
882 }
883
884 // Set the remaining indices after deflation.
885 problem_->setLSIndex( currRHSIdx );
886
887 // Get the current residual vector.
888 std::vector<MagnitudeType> norms;
889 R_0 = MVT::CloneCopy( *(block_cg_iter->getNativeResiduals(&norms)),currIdx2 );
890 for (int i=0; i<have; ++i) { currIdx2[i] = i; }
891
892 // Set the new state and initialize the solver.
893 block_cg_iter->initializeCG(state_, R_0);
894 }
895
897 //
898 // check for maximum iterations
899 //
901 else if ( maxIterTest_->getStatus() == Passed ) {
902 // we don't have convergence
903 retType = MaxItersReached;
904 isConverged = false;
905 break; // break from while(1){block_cg_iter->iterate()}
906 }
907
909 //
910 // a debug status test (if any) stopped the iteration
911 //
913 else if (Teuchos::nonnull(debugStatusTest_) &&
914 debugStatusTest_->getStatus() == Passed) {
915 // we don't have convergence, but a debug test asked us to stop
916 retType = Unconverged;
917 isConverged = false;
918 break; // break from while(1){block_cg_iter->iterate()}
919 }
920
922 //
923 // we returned from iterate(), but none of our status tests Passed.
924 // something is wrong, and it is probably our fault.
925 //
927
928 else {
929 retType = InconsistentState;
930 TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,
931 "Belos::PseudoBlockCGSolMgr::solve(): Invalid return from PseudoBlockCGIter::iterate().");
932 }
933 }
934 catch (const StatusTestNaNError& e) {
935 // A NaN was detected in the solver. Set the solution to zero and return unconverged.
936 retType = NaNDetected;
937 achievedTol_ = MT::one();
938 Teuchos::RCP<MV> X = problem_->getLHS();
939 MVT::MvInit( *X, SCT::zero() );
940 printer_->stream(Warnings) << "Belos::PseudoBlockCGSolMgr::solve(): Warning! NaN has been detected!"
941 << std::endl;
942 return retType;
943 }
944 catch (const std::exception &e) {
945 retType = NonspecificException;
946 printer_->stream(Errors) << "Error! Caught std::exception in PseudoBlockCGIter::iterate() at iteration "
947 << block_cg_iter->getNumIters() << std::endl
948 << e.what() << std::endl;
949 throw;
950 }
951 }
952
953 // Inform the linear problem that we are finished with this block linear system.
954 problem_->setCurrLS();
955
956 // Update indices for the linear systems to be solved.
957 startPtr += numCurrRHS;
958 numRHS2Solve -= numCurrRHS;
959
960 if ( numRHS2Solve > 0 ) {
961
962 numCurrRHS = numRHS2Solve;
963 currIdx.resize( numCurrRHS );
964 currIdx2.resize( numCurrRHS );
965 for (int i=0; i<numCurrRHS; ++i)
966 { currIdx[i] = startPtr+i; currIdx2[i] = i; }
967
968 // Set the next indices.
969 problem_->setLSIndex( currIdx );
970 }
971 else {
972 currIdx.resize( numRHS2Solve );
973 }
974
975 }// while ( numRHS2Solve > 0 )
976
977 }
978
979 // print final summary
980 sTest_->print( printer_->stream(FinalSummary) );
981
982 // print timing information
983#ifdef BELOS_TEUCHOS_TIME_MONITOR
984 // Calling summarize() can be expensive, so don't call unless the
985 // user wants to print out timing details. summarize() will do all
986 // the work even if it's passed a "black hole" output stream.
987 if (verbosity_ & TimingDetails)
988 Teuchos::TimeMonitor::summarize( printer_->stream(TimingDetails) );
989#endif
990
991 // get iteration information for this solve
992 numIters_ = maxIterTest_->getNumIters();
993
994 // Save the convergence test value ("achieved tolerance") for this
995 // solve.
996 const std::vector<MagnitudeType>* pTestValues = convTest_->getTestValue();
997 if (pTestValues != NULL && pTestValues->size () > 0) {
998 achievedTol_ = *std::max_element (pTestValues->begin(), pTestValues->end());
999 }
1000
1001 // Do condition estimate, if needed
1002 if (genCondEst_ && !condEstPerf) {
1003 ScalarType l_min, l_max;
1004 Teuchos::ArrayView<MagnitudeType> diag = block_cg_iter->getDiag();
1005 Teuchos::ArrayView<MagnitudeType> offdiag = block_cg_iter->getOffDiag();
1006 compute_condnum_tridiag_sym(diag,offdiag,eigenEstimates_,l_min,l_max,condEstimate_);
1007 condEstPerf = true;
1008 }
1009
1010 if (!isConverged) {
1011 return retType; // return from PseudoBlockCGSolMgr::solve()
1012 }
1013 return Converged; // return from PseudoBlockCGSolMgr::solve()
1014}
1015
1016// This method requires the solver manager to return a std::string that describes itself.
1017template<class ScalarType, class MV, class OP, class DM>
1019{
1020 std::ostringstream oss;
1021 oss << "Belos::PseudoBlockCGSolMgr<...,"<<Teuchos::ScalarTraits<ScalarType>::name()<<">";
1022 oss << "{";
1023 oss << "}";
1024 return oss.str();
1025}
1026
1027
1028template<class ScalarType, class MV, class OP, class DM>
1030compute_condnum_tridiag_sym (Teuchos::ArrayView<MagnitudeType> diag,
1031 Teuchos::ArrayView<MagnitudeType> offdiag,
1032 Teuchos::ArrayRCP<MagnitudeType>& lambdas,
1033 ScalarType & lambda_min,
1034 ScalarType & lambda_max,
1035 ScalarType & ConditionNumber )
1036{
1037 using STS = Teuchos::ScalarTraits<ScalarType>;
1038
1039 /* Copied from az_cg.c: compute_condnum_tridiag_sym */
1040 /* diag == ScalarType vector of size N, containing the diagonal
1041 elements of A
1042 offdiag == ScalarType vector of size N-1, containing the offdiagonal
1043 elements of A. Note that A is supposed to be symmatric
1044 */
1045 int info = 0;
1046 const int N = diag.size ();
1047 ScalarType scalar_dummy;
1048 std::vector<MagnitudeType> mag_dummy(4*N);
1049 char char_N = 'N';
1050 Teuchos::LAPACK<int,ScalarType> lapack;
1051
1052 lambdas.resize(N, 0.0);
1053 lambda_min = STS::one ();
1054 lambda_max = STS::one ();
1055 if( N > 2 ) {
1056 lapack.PTEQR (char_N, N, diag.getRawPtr (), offdiag.getRawPtr (),
1057 &scalar_dummy, 1, &mag_dummy[0], &info);
1058 TEUCHOS_TEST_FOR_EXCEPTION
1059 (info < 0, std::logic_error, "Belos::PseudoBlockCGSolMgr::"
1060 "compute_condnum_tridiag_sym: LAPACK's _PTEQR failed with info = "
1061 << info << " < 0. This suggests there might be a bug in the way Belos "
1062 "is calling LAPACK. Please report this to the Belos developers.");
1063 for (int k = 0; k < N; k++) {
1064 lambdas[k] = diag[N - 1 - k];
1065 }
1066 lambda_min = Teuchos::as<ScalarType> (diag[N-1]);
1067 lambda_max = Teuchos::as<ScalarType> (diag[0]);
1068 }
1069
1070 // info > 0 means that LAPACK's eigensolver didn't converge. This
1071 // is unlikely but may be possible. In that case, the best we can
1072 // do is use the eigenvalues that it computes, as long as lambda_max
1073 // >= lambda_min.
1074 if (STS::real (lambda_max) < STS::real (lambda_min)) {
1075 ConditionNumber = STS::one ();
1076 }
1077 else {
1078 // It's OK for the condition number to be Inf.
1079 ConditionNumber = lambda_max / lambda_min;
1080 }
1081
1082} /* compute_condnum_tridiag_sym */
1083
1084
1085
1086
1087
1088} // end Belos namespace
1089
1090#ifdef HAVE_BELOS_TPETRA
1092
1093#define BELOS_TPETRA_PSEUDOBLOCKCGSOLMGR_NOEXTERN_CALL(SC, LO, GO, NT) \
1094 BELOS_TPETRA_CALL(Belos::PseudoBlockCGSolMgr, SC, LO, GO, NT)
1095
1096#define BELOS_TPETRA_PSEUDOBLOCKCGSOLMGR_EXTERN_CALL(SC, LO, GO, NT) \
1097 BELOS_TPETRA_EXTERN_CALL(Belos::PseudoBlockCGSolMgr, SC, LO, GO, NT)
1098
1099TPETRA_INSTANTIATE_SLGN_NO_ORDINAL_SCALAR(BELOS_TPETRA_PSEUDOBLOCKCGSOLMGR_EXTERN_CALL)
1100#endif
1101
1102#endif /* BELOS_PSEUDO_BLOCK_CG_SOLMGR_HPP */
Belos concrete class for performing the conjugate-gradient (CG) iteration.
Pure virtual base class which augments the basic interface for a conjugate gradient linear solver ite...
Belos header file which uses auto-configuration information to include necessary C++ headers.
Class which describes the linear problem to be solved by the iterative solver.
Class which manages the output and verbosity of the Belos solvers.
Belos concrete class for performing the pseudo-block CG iteration.
Pure virtual base class which describes the basic interface for a solver manager.
Belos::StatusTest for logically combining several status tests.
Belos::StatusTestResNorm for specifying general residual norm stopping criteria.
Belos::StatusTest class for specifying a maximum number of iterations.
A factory class for generating StatusTestOutput objects.
Collection of types and exceptions used within the Belos solvers.
BelosError(const std::string &what_arg)
This class implements the preconditioned Conjugate Gradient (CG) iteration.
Structure to contain pointers to CGIteration state variables.
Base class for Belos::SolverManager subclasses which normally can only compile with ScalarType types ...
Traits class which defines basic operations on multivectors.
static void MvInit(MV &mv, const ScalarType alpha=Teuchos::ScalarTraits< ScalarType >::zero())
static Teuchos::RCP< MV > CloneCopy(const MV &mv)
static Teuchos::RCP< MV > CloneViewNonConst(MV &mv, const std::vector< int > &index)
Class which defines basic traits for the operator type.
Belos's basic output manager for sending information of select verbosity levels to the appropriate ou...
This class implements the pseudo-block CG iteration, where the basic CG algorithm is performed on all...
Structure to contain pointers to PseudoBlockCGIteration state variables.
MagnitudeType achievedTol() const override
Tolerance achieved by the last solve() invocation.
int getNumIters() const override
Get the iteration count for the most recent call to solve().
const LinearProblem< ScalarType, MV, OP, DM > & getProblem() const override
Return a reference to the linear problem being solved by this solver manager.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const override
Get a parameter list containing the valid parameters for this object.
void reset(const ResetType type) override
Performs a reset of the solver manager specified by the ResetType. This informs the solver manager th...
void setDebugStatusTest(const Teuchos::RCP< StatusTest< ScalarType, MV, OP, DM > > &debugStatusTest) override
Set a debug status test, OR-combined into the top-level status test.
Teuchos::RCP< StatusTestGenResNorm< ScalarType, MV, OP, DM > > getResidualStatusTest() const
Return the residual status test.
PseudoBlockCGSolMgr()
Empty constructor for BlockCGSolMgr. This constructor takes no arguments and sets the default values ...
void setParameters(const Teuchos::RCP< Teuchos::ParameterList > &params) override
Set the parameters the solver manager should use to solve the linear problem.
void setProblem(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP, DM > > &problem) override
Set the linear problem that needs to be solved.
bool isLOADetected() const override
Return whether a loss of accuracy was detected by this solver during the most current solve.
Teuchos::RCP< SolverManager< ScalarType, MV, OP, DM > > clone() const override
clone for Inverted Injection (DII)
Teuchos::RCP< const Teuchos::ParameterList > getCurrentParameters() const override
Get a parameter list containing the current parameters for this object.
ScalarType getConditionEstimate() const
Gets the estimated condition number.
Teuchos::Array< Teuchos::RCP< Teuchos::Time > > getTimers() const
Return the timers for this object.
The Belos::PseudoBlockCGSolMgr provides a powerful and fully-featured solver manager over the pseudo-...
virtual ~PseudoBlockCGSolMgr()=default
PseudoBlockCGSolMgr(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP, DM > > &problem, const Teuchos::RCP< Teuchos::ParameterList > &pl)
Teuchos::RCP< StatusTestGenResNorm< ScalarType, MV, OP, DM > > getResidualStatusTest() const
PseudoBlockCGSolMgrLinearProblemFailure is thrown when the linear problem is not setup (i....
PseudoBlockCGSolMgrLinearProblemFailure(const std::string &what_arg)
A class for extending the status testing capabilities of Belos via logical combinations.
An implementation of StatusTestResNorm using a family of residual norms.
A pure virtual class for defining the status tests for the Belos iterative solvers.
A Belos::StatusTest class for specifying a maximum number of iterations.
A factory class for generating StatusTestOutput objects.
Teuchos::RCP< StatusTestOutput< ScalarType, MV, OP, DM > > create(const Teuchos::RCP< OutputManager< ScalarType > > &printer, Teuchos::RCP< StatusTest< ScalarType, MV, OP, DM > > test, int mod, int printStates)
Create the StatusTestOutput object specified by the outputStyle.
ScaleType convertStringToScaleType(const std::string &scaleType)
Convert the given string to its ScaleType enum value.
@ StatusTestDetails
@ FinalSummary
@ TimingDetails
ReturnType
Whether the Belos solve converged for all linear systems.
@ NaNDetected
@ Unconverged
@ MaxItersReached
@ NonspecificException
@ InconsistentState
@ Undetermined
ScaleType
The type of scaling to use on the residual norm value.
ResetType
How to reset the solver.
Default parameters common to most Belos solvers.
static const double convTol
Default convergence tolerance.

Generated for Belos by doxygen 1.15.0