Belos  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BelosLSQRSolMgr.hpp
Go to the documentation of this file.
1 //@HEADER
2 // ************************************************************************
3 //
4 // Belos: Block Linear Solvers Package
5 // Copyright 2004 Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ************************************************************************
40 //@HEADER
41 
42 #ifndef BELOS_LSQR_SOLMGR_HPP
43 #define BELOS_LSQR_SOLMGR_HPP
44 
47 
48 #include "BelosConfigDefs.hpp"
49 #include "BelosTypes.hpp"
50 
51 #include "BelosLinearProblem.hpp"
52 #include "BelosSolverManager.hpp"
53 
54 #include "BelosLSQRIteration.hpp"
55 #include "BelosLSQRIter.hpp"
58 #include "BelosLSQRStatusTest.hpp"
59 #include "BelosStatusTestCombo.hpp"
61 #include "BelosOutputManager.hpp"
62 #include "Teuchos_as.hpp"
63 #include "Teuchos_BLAS.hpp"
64 #include "Teuchos_LAPACK.hpp"
65 
66 #ifdef BELOS_TEUCHOS_TIME_MONITOR
67 #include "Teuchos_TimeMonitor.hpp"
68 #endif
69 
70 namespace Belos {
71 
72 
74 
75 
83 public:
84  LSQRSolMgrLinearProblemFailure(const std::string& what_arg)
85  : BelosError(what_arg)
86  {}
87 };
88 
96 public:
97  LSQRSolMgrOrthoFailure(const std::string& what_arg)
98  : BelosError(what_arg)
99  {}
100 };
101 
109 public:
110  LSQRSolMgrBlockSizeFailure(const std::string& what_arg)
111  : BelosError(what_arg)
112  {}
113 };
114 
217 template<class ScalarType, class MV, class OP>
218 class LSQRSolMgr : public SolverManager<ScalarType,MV,OP> {
219 
220 private:
224  typedef typename Teuchos::ScalarTraits<ScalarType>::magnitudeType MagnitudeType;
226 
227 public:
228 
230 
231 
238  LSQRSolMgr();
239 
262  // This LSQR implementation only supports block size 1. Like CG, LSQR is a short
263  // recurrence method that, in finite precision arithmetic and without reorthogonalization,
264  // does not have the "n" step convergence property. Without either blocks or
265  // reorthogonalization, there is nothing to "Orthogonalize."
266 
269 
271  virtual ~LSQRSolMgr() {};
273 
275 
276 
280  return *problem_;
281  }
282 
286 
290 
297  return Teuchos::tuple(timerSolve_);
298  }
299 
301  int getNumIters() const {
302  return numIters_;
303  }
304 
309  MagnitudeType getMatCondNum () const {
310  return matCondNum_;
311  }
312 
317  MagnitudeType getMatNorm () const {
318  return matNorm_;
319  }
320 
329  MagnitudeType getResNorm () const {
330  return resNorm_;
331  }
332 
334  MagnitudeType getMatResNorm () const {
335  return matResNorm_;
336  }
337 
346  bool isLOADetected() const { return false; }
347 
349 
351 
352 
354  void setProblem( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem ) { problem_ = problem; }
355 
358 
360 
362 
363 
367  void reset( const ResetType type ) { if ((type & Belos::Problem) && !Teuchos::is_null(problem_)) problem_->setProblem(); }
369 
371 
372 
391  ReturnType solve();
392 
394 
397 
399  std::string description() const;
400 
402 
403 private:
404 
405  // Linear problem.
407 
408  // Output manager.
410  Teuchos::RCP<std::ostream> outputStream_;
411 
412  // Status test.
417 
418  // Orthogonalization manager.
420 
421  // Current parameter list.
428  mutable Teuchos::RCP<const Teuchos::ParameterList> validParams_;
429 
430  // Current solver input parameters
431  MagnitudeType lambda_;
432  MagnitudeType relRhsErr_;
433  MagnitudeType relMatErr_;
434  MagnitudeType condMax_;
435  int maxIters_, termIterMax_;
436  std::string orthoType_;
437  MagnitudeType orthoKappa_;
438  int verbosity_, outputStyle_, outputFreq_;
439 
440  // Terminal solver state values
441  int numIters_;
442  MagnitudeType matCondNum_;
443  MagnitudeType matNorm_;
444  MagnitudeType resNorm_;
445  MagnitudeType matResNorm_;
446 
447  // Timers.
448  std::string label_;
449  Teuchos::RCP<Teuchos::Time> timerSolve_;
450 
451  // Internal state variables.
452  bool isSet_;
453  bool loaDetected_;
454 };
455 
456 // Empty Constructor
457 template<class ScalarType, class MV, class OP>
459  isSet_(false),
460  loaDetected_(false)
461 {}
462 
463 
464 // Basic Constructor
465 template<class ScalarType, class MV, class OP>
469  problem_(problem),
470  isSet_(false),
471  loaDetected_(false)
472 {
473  // The linear problem to solve is allowed to be null here. The user
474  // must then set a nonnull linear problem (by calling setProblem())
475  // before calling solve().
476  //
477  // Similarly, users are allowed to set a null parameter list here,
478  // but they must first set a nonnull parameter list (by calling
479  // setParameters()) before calling solve().
480  if (! is_null (pl)) {
481  setParameters (pl);
482  }
483 }
484 
485 
486 template<class ScalarType, class MV, class OP>
489 {
491  using Teuchos::parameterList;
492  using Teuchos::RCP;
493  using Teuchos::rcp;
494  using Teuchos::rcpFromRef;
496 
497  // Set all the valid parameters and their default values.
498  if (is_null (validParams_)) {
499  // We use Teuchos::as just in case MagnitudeType doesn't have a
500  // constructor that takes an int. Otherwise, we could just write
501  // "MagnitudeType(10)".
502  const MagnitudeType ten = Teuchos::as<MagnitudeType> (10);
503  const MagnitudeType sqrtEps = STM::squareroot (STM::eps());
504 
505  const MagnitudeType lambda = STM::zero();
506  RCP<std::ostream> outputStream = rcpFromRef (std::cout);
507  const MagnitudeType relRhsErr = ten * sqrtEps;
508  const MagnitudeType relMatErr = ten * sqrtEps;
509  const MagnitudeType condMax = STM::one() / STM::eps();
510  const int maxIters = 1000;
511  const int termIterMax = 1;
512  const std::string orthoType ("DGKS");
513  const MagnitudeType orthoKappa = Teuchos::as<MagnitudeType> (-1.0);
514  const int verbosity = Belos::Errors;
515  const int outputStyle = Belos::General;
516  const int outputFreq = -1;
517  const std::string label ("Belos");
518 
519  RCP<Teuchos::ParameterList> pl = Teuchos::parameterList();
520  pl->set("Output Stream", outputStream,
521  "is a reference-counted pointer to the output stream receiving\n"
522  "all solver output.");
523  pl->set("Lambda", lambda, "is the damping parameter.");
524  pl->set("Rel RHS Err", relRhsErr,
525  "estimates the error in the data defining the right-\n"
526  "hand side.");
527  pl->set("Rel Mat Err", relMatErr,
528  "estimates the error in the data defining the matrix.");
529  pl->set("Condition Limit", condMax,
530  "bounds the estimated condition number of Abar.");
531  pl->set("Maximum Iterations", maxIters,
532  "allows at most the maximum number of iterations.");
533  pl->set("Term Iter Max", termIterMax,
534  "consecutive iterations meeting thresholds are necessary for\n"
535  "for convergence.");
536  pl->set("Orthogonalization", orthoType,
537  "uses orthogonalization of either DGKS, ICGS, IMGS, or TSQR.");
538  {
540  pl->set("Orthogonalization", orthoType,
541  "refers to the orthogonalization method to use. Valid "
542  "options: " + factory.validNamesString());
543  RCP<const ParameterList> orthoParams =
544  factory.getDefaultParameters (orthoType);
545  pl->set ("Orthogonalization Parameters", *orthoParams,
546  "Parameters specific to the type of orthogonalization used.");
547  }
548  pl->set("Orthogonalization Constant", orthoKappa,
549  "is the threshold used by DGKS orthogonalization to determine\n"
550  "whether or not to repeat classical Gram-Schmidt. This parameter\n"
551  "is ignored if \"Orthogonalization\" is not \"DGKS\".");
552  pl->set("Verbosity", verbosity,
553  "type(s) of solver information are outputted to the output\n"
554  "stream.");
555  pl->set("Output Style", outputStyle,
556  "the style used for the solver information outputted to the\n"
557  "output stream.");
558  pl->set("Output Frequency", outputFreq,
559  "is the frequency at which information is written to the\n"
560  "output stream.");
561  pl->set("Timer Label", label,
562  "is the string to use as a prefix for the timer labels.");
563  // pl->set("Restart Timers", restartTimers_);
564  pl->set("Block Size", 1, "Block size parameter (currently, this must always be 1).");
565 
566  validParams_ = pl;
567  }
568  return validParams_;
569 }
570 
571 
572 template<class ScalarType, class MV, class OP>
573 void
576 {
577  using Teuchos::isParameterType;
578  using Teuchos::getParameter;
579  using Teuchos::null;
581  using Teuchos::parameterList;
582  using Teuchos::RCP;
583  using Teuchos::rcp;
584  using Teuchos::rcp_dynamic_cast;
585  using Teuchos::rcpFromRef;
586  using Teuchos::Time;
587  using Teuchos::TimeMonitor;
591 
592  TEUCHOS_TEST_FOR_EXCEPTION(params.is_null(), std::invalid_argument,
593  "Belos::LSQRSolMgr::setParameters: "
594  "the input ParameterList is null.");
595  RCP<const ParameterList> defaultParams = getValidParameters ();
596  params->validateParametersAndSetDefaults (*defaultParams);
597 
598  // At this point, params is a valid parameter list with defaults
599  // filled in. Now we can "commit" it to our instance's parameter
600  // list.
601  params_ = params;
602 
603  // Get the damping (a.k.a. regularization) parameter lambda.
604  lambda_ = params->get<MagnitudeType> ("Lambda");
605 
606  // Get the maximum number of iterations.
607  maxIters_ = params->get<int>("Maximum Iterations");
608 
609  // (Re)set the timer label.
610  {
611  const std::string newLabel = params->get<std::string>("Timer Label");
612 
613  // Update parameter in our list and solver timer
614  if (newLabel != label_) {
615  label_ = newLabel;
616  }
617 
618 #ifdef BELOS_TEUCHOS_TIME_MONITOR
619  std::string newSolveLabel = label_ + ": LSQRSolMgr total solve time";
620  if (timerSolve_.is_null()) {
621  // Ask TimeMonitor for a new timer.
622  timerSolve_ = TimeMonitor::getNewCounter (newSolveLabel);
623  } else {
624  // We've already created a timer, but we may have changed its
625  // label. If we did change its name, then we have to forget
626  // about the old timer and create a new one with a different
627  // name. This is because Teuchos::Time doesn't give you a way
628  // to change a timer's name, once you've created it. We assume
629  // that if the user changed the timer's label, then the user
630  // wants to reset the timer's results.
631  const std::string oldSolveLabel = timerSolve_->name ();
632 
633  if (oldSolveLabel != newSolveLabel) {
634  // Tell TimeMonitor to forget about the old timer.
635  // TimeMonitor lets you clear timers by name.
636  TimeMonitor::clearCounter (oldSolveLabel);
637  timerSolve_ = TimeMonitor::getNewCounter (newSolveLabel);
638  }
639  }
640 #endif // BELOS_TEUCHOS_TIME_MONITOR
641  }
642 
643  // Check for a change in verbosity level
644  {
645  int newVerbosity = 0;
646  // ParameterList gets confused sometimes about enums. This
647  // ensures that no matter how "Verbosity" was stored -- either an
648  // an int, or as a Belos::MsgType enum, we will be able to extract
649  // it. If it was stored as some other type, we let the exception
650  // through.
651  try {
652  newVerbosity = params->get<Belos::MsgType> ("Verbosity");
654  newVerbosity = params->get<int> ("Verbosity");
655  }
656  if (newVerbosity != verbosity_) {
657  verbosity_ = newVerbosity;
658  }
659  }
660 
661  // (Re)set the output style.
662  outputStyle_ = params->get<int> ("Output Style");
663 
664  // Get the output stream for the output manager.
665  //
666  // In case the output stream can't be read back in, we default to
667  // stdout (std::cout), just to ensure reasonable behavior.
668  {
669  outputStream_ = params->get<RCP<std::ostream> > ("Output Stream");
670 
671  // We assume that a null output stream indicates that the user
672  // doesn't want to print anything, so we replace it with a "black
673  // hole" stream that prints nothing sent to it. (We can't use a
674  // null output stream, since the output manager always sends
675  // things it wants to print to the output stream.)
676  if (outputStream_.is_null())
677  outputStream_ = rcp (new Teuchos::oblackholestream);
678  }
679 
680  // Get the frequency of solver output. (For example, -1 means
681  // "never," 1 means "every iteration.")
682  outputFreq_ = params->get<int> ("Output Frequency");
683 
684  // Create output manager if we need to, using the verbosity level
685  // and output stream that we fetched above. We do this here because
686  // instantiating an OrthoManager using OrthoManagerFactory requires
687  // a valid OutputManager.
688  if (printer_.is_null()) {
689  printer_ = rcp (new OutputManager<ScalarType> (verbosity_, outputStream_));
690  } else {
691  printer_->setVerbosity (verbosity_);
692  printer_->setOStream (outputStream_);
693  }
694 
695  // Check if the orthogonalization changed, or if we need to
696  // initialize it.
697  typedef OrthoManagerFactory<ScalarType, MV, OP> factory_type;
698  factory_type factory;
699  bool mustMakeOrtho = false;
700  {
701  std::string tempOrthoType;
702  try {
703  tempOrthoType = params_->get<std::string> ("Orthogonalization");
704  } catch (InvalidParameterName&) {
705  tempOrthoType = orthoType_;
706  }
707  if (ortho_.is_null() || tempOrthoType != orthoType_) {
708  mustMakeOrtho = true;
709 
710  // Ensure that the specified orthogonalization type is valid.
711  if (! factory.isValidName (tempOrthoType)) {
712  std::ostringstream os;
713  os << "Belos::LSQRSolMgr: Invalid orthogonalization name \""
714  << tempOrthoType << "\". The following are valid options "
715  << "for the \"Orthogonalization\" name parameter: ";
716  factory.printValidNames (os);
717  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, os.str());
718  }
719  orthoType_ = tempOrthoType; // The name is valid, so accept it.
720  params_->set ("Orthogonalization", orthoType_);
721  }
722  }
723 
724  // Get any parameters for the orthogonalization ("Orthogonalization
725  // Parameters"). If not supplied, the orthogonalization manager
726  // factory will supply default values.
727  //
728  // NOTE (mfh 21 Oct 2011) For the sake of backwards compatibility,
729  // if params has an "Orthogonalization Constant" parameter and the
730  // DGKS orthogonalization manager is to be used, the value of this
731  // parameter will override DGKS's "depTol" parameter.
732  //
733  // Users must supply the orthogonalization manager parameters as a
734  // sublist (supplying it as an RCP<ParameterList> would make the
735  // resulting parameter list not serializable).
736  RCP<ParameterList> orthoParams;
737  { // The nonmember function returns an RCP<ParameterList>,
738  // which is what we want here.
739  using Teuchos::sublist;
740  // Abbreviation to avoid typos.
741  const std::string paramName ("Orthogonalization Parameters");
742 
743  try {
744  orthoParams = sublist (params_, paramName, true);
745  } catch (InvalidParameter&) {
746  // We didn't get the parameter list from params, so get a
747  // default parameter list from the OrthoManagerFactory.
748  // Modify params_ so that it has the default parameter list,
749  // and set orthoParams to ensure it's a sublist of params_
750  // (and not just a copy of one).
751  params_->set (paramName, factory.getDefaultParameters (orthoType_));
752  orthoParams = sublist (params_, paramName, true);
753  }
754  }
755  TEUCHOS_TEST_FOR_EXCEPTION(orthoParams.is_null(), std::logic_error,
756  "Failed to get orthogonalization parameters. "
757  "Please report this bug to the Belos developers.");
758 
759  // If we need to, instantiate a new MatOrthoManager subclass
760  // instance corresponding to the desired orthogonalization method.
761  // We've already fetched the orthogonalization method name
762  // (orthoType_) and its parameters (orthoParams) above.
763  //
764  // NOTE (mfh 21 Oct 2011) We only instantiate a new MatOrthoManager
765  // subclass if the orthogonalization method name is different than
766  // before. Thus, for some orthogonalization managers, changes to
767  // their parameters may not get propagated, if the manager type
768  // itself didn't change. The one exception is the "depTol"
769  // (a.k.a. orthoKappa or "Orthogonalization Constant") parameter of
770  // DGKS; changes to that _do_ get propagated down to the DGKS
771  // instance.
772  //
773  // The most general way to fix this issue would be to supply each
774  // orthogonalization manager class with a setParameterList() method
775  // that takes a parameter list input, and changes the parameters as
776  // appropriate. A less efficient but correct way would be simply to
777  // reinstantiate the OrthoManager every time, whether or not the
778  // orthogonalization method name or parameters have changed.
779  if (mustMakeOrtho) {
780  // Create orthogonalization manager. This requires that the
781  // OutputManager (printer_) already be initialized. LSQR
782  // currently only orthogonalizes with respect to the Euclidean
783  // inner product, so we set the inner product matrix M to null.
784  RCP<const OP> M = null;
785  ortho_ = factory.makeMatOrthoManager (orthoType_, M, printer_,
786  label_, orthoParams);
787  }
788  TEUCHOS_TEST_FOR_EXCEPTION(ortho_.is_null(), std::logic_error,
789  "The MatOrthoManager is not yet initialized, but "
790  "should be by this point. "
791  "Please report this bug to the Belos developers.");
792 
793  // Check which orthogonalization constant to use. We only need this
794  // if orthoType_ == "DGKS" (and we already fetched the orthoType_
795  // parameter above).
796  if (orthoType_ == "DGKS") {
797  if (params->isParameter ("Orthogonalization Constant")) {
798  orthoKappa_ = params_->get<MagnitudeType> ("Orthogonalization Constant");
799 
800  if (orthoKappa_ > 0 && ! ortho_.is_null()) {
801  typedef DGKSOrthoManager<ScalarType,MV,OP> ortho_impl_type;
802  rcp_dynamic_cast<ortho_impl_type> (ortho_)->setDepTol (orthoKappa_);
803  }
804  }
805  }
806 
807  // Check for condition number limit, number of consecutive passed
808  // iterations, relative RHS error, and relative matrix error.
809  // Create the LSQR convergence test if necessary.
810  {
811  condMax_ = params->get<MagnitudeType> ("Condition Limit");
812  termIterMax_ = params->get<int>("Term Iter Max");
813  relRhsErr_ = params->get<MagnitudeType> ("Rel RHS Err");
814  relMatErr_ = params->get<MagnitudeType> ("Rel Mat Err");
815 
816  // Create the LSQR convergence test if it doesn't exist yet.
817  // Otherwise, update its parameters.
818  if (convTest_.is_null()) {
819  convTest_ =
820  rcp (new LSQRStatusTest<ScalarType,MV,OP> (condMax_, termIterMax_,
821  relRhsErr_, relMatErr_));
822  } else {
823  convTest_->setCondLim (condMax_);
824  convTest_->setTermIterMax (termIterMax_);
825  convTest_->setRelRhsErr (relRhsErr_);
826  convTest_->setRelMatErr (relMatErr_);
827  }
828  }
829 
830  // Create the status test for maximum number of iterations if
831  // necessary. Otherwise, update it with the new maximum iteration
832  // count.
833  if (maxIterTest_.is_null()) {
834  maxIterTest_ = rcp (new StatusTestMaxIters<ScalarType,MV,OP> (maxIters_));
835  } else {
836  maxIterTest_->setMaxIters (maxIters_);
837  }
838 
839  // The stopping criterion is an OR combination of the test for
840  // maximum number of iterations, and the LSQR convergence test.
841  // ("OR combination" means that both tests will always be evaluated,
842  // as opposed to a SEQ combination.)
843  typedef StatusTestCombo<ScalarType,MV,OP> StatusTestCombo_t;
844  // If sTest_ is not null, then maxIterTest_ and convTest_ were
845  // already constructed on entry to this routine, and sTest_ has
846  // their pointers. Thus, maxIterTest_ and convTest_ have gotten any
847  // parameter changes, so we don't need to do anything to sTest_.
848  if (sTest_.is_null()) {
849  sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR,
850  maxIterTest_,
851  convTest_));
852  }
853 
854  if (outputTest_.is_null()) {
855  // Create the status test output class.
856  // This class manages and formats the output from the status test.
857  StatusTestOutputFactory<ScalarType,MV,OP> stoFactory (outputStyle_);
858  outputTest_ = stoFactory.create (printer_, sTest_, outputFreq_,
859  Passed + Failed + Undefined);
860  // Set the solver string for the output test.
861  const std::string solverDesc = " LSQR ";
862  outputTest_->setSolverDesc (solverDesc);
863  } else {
864  // FIXME (mfh 18 Sep 2011) How do we change the output style of
865  // outputTest_, without destroying and recreating it?
866  outputTest_->setOutputManager (printer_);
867  outputTest_->setChild (sTest_);
868  outputTest_->setOutputFrequency (outputFreq_);
869  // Since outputTest_ can only be created here, I'm assuming that
870  // the fourth constructor argument ("printStates") was set
871  // correctly on constrution; I don't need to reset it (and I can't
872  // set it anyway, given StatusTestOutput's interface).
873  }
874 
875  // Inform the solver manager that the current parameters were set.
876  isSet_ = true;
877 }
878 
879 
880 template<class ScalarType, class MV, class OP>
882  using Teuchos::RCP;
883  using Teuchos::rcp;
884 
885  // Set the current parameters if they were not set before. NOTE:
886  // This may occur if the user generated the solver manager with the
887  // default constructor, but did not set any parameters using
888  // setParameters().
889  if (!isSet_) {
890  setParameters (Teuchos::parameterList (*getValidParameters()));
891  }
892 
894  "The linear problem to solve is null.");
896  "LSQRSolMgr::solve(): The linear problem is not ready, "
897  "as its setProblem() method has not been called.");
898  TEUCHOS_TEST_FOR_EXCEPTION(MVT::GetNumberVecs (*(problem_->getRHS ())) != 1,
900  "LSQRSolMgr::solve(): The current implementation of LSQR "
901  "only knows how to solve problems with one right-hand "
902  "side, but the linear problem to solve has "
903  << MVT::GetNumberVecs (*(problem_->getRHS ()))
904  << " right-hand sides.");
905 
906  // We've validated the LinearProblem instance above. If any of the
907  // StatusTests needed to be initialized using information from the
908  // LinearProblem, now would be the time to do so. (This is true of
909  // GMRES, where the residual convergence test(s) to instantiate
910  // depend on knowing whether there is a left preconditioner. This
911  // is why GMRES has an "isSTSet_" Boolean member datum, which tells
912  // you whether the status tests have been instantiated and are ready
913  // for use.
914 
915  // test isFlexible might go here.
916 
917  // Next the right-hand sides to solve are identified. Among other things,
918  // this enables getCurrLHSVec() to get the current initial guess vector,
919  // and getCurrRHSVec() to get the current right-hand side (in Iter).
920  std::vector<int> currRHSIdx(1, 0);
921  problem_->setLSIndex(currRHSIdx);
922 
923  // Reset the status test.
924  outputTest_->reset();
925 
926  // Don't assume convergence unless we've verified that the
927  // convergence test passed.
928  bool isConverged = false;
929 
930  // FIXME: Currently we are setting the initial guess to zero, since
931  // the solver doesn't yet know how to handle a nonzero initial
932  // guess. This could be fixed by rewriting the solver to work with
933  // the residual and a delta.
934  //
935  // In a least squares problem with a nonzero initial guess, the
936  // minimzation problem involves the distance (in a norm depending on
937  // the preconditioner) between the solution and the the initial
938  // guess.
939 
941  // Solve the linear problem using LSQR
943 
944  // Parameter list for the LSQR iteration.
946 
947  // Use the solver manager's "Lambda" parameter to set the
948  // iteration's "Lambda" parameter. We know that the solver
949  // manager's parameter list (params_) does indeed contain the
950  // "Lambda" parameter, because solve() always ensures that
951  // setParameters() has been called.
952  plist.set ("Lambda", lambda_);
953 
954  typedef LSQRIter<ScalarType,MV,OP> iter_type;
955  RCP<iter_type> lsqr_iter =
956  rcp (new iter_type (problem_, printer_, outputTest_, plist));
957 #ifdef BELOS_TEUCHOS_TIME_MONITOR
958  Teuchos::TimeMonitor slvtimer(*timerSolve_);
959 #endif
960 
961  // Reset the number of iterations.
962  lsqr_iter->resetNumIters();
963  // Reset the number of calls that the status test output knows about.
964  outputTest_->resetNumCalls();
965  // Set the new state and initialize the solver.
967  lsqr_iter->initializeLSQR(newstate);
968  // tell lsqr_iter to iterate
969  try {
970  lsqr_iter->iterate();
971 
972  // First check for convergence. If we didn't converge, then check
973  // whether we reached the maximum number of iterations. If
974  // neither of those happened, there must have been a bug.
975  if (convTest_->getStatus() == Belos::Passed) {
976  isConverged = true;
977  } else if (maxIterTest_->getStatus() == Belos::Passed) {
978  isConverged = false;
979  } else {
980  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
981  "LSQRSolMgr::solve(): LSQRIteration::iterate() "
982  "returned without either the convergence test or "
983  "the maximum iteration count test passing."
984  "Please report this bug to the Belos developers.");
985  }
986  } catch (const std::exception &e) {
987  printer_->stream(Belos::Errors) << "Error! Caught std::exception in LSQRIter::iterate() at iteration "
988  << lsqr_iter->getNumIters() << std::endl
989  << e.what() << std::endl;
990  throw;
991  }
992 
993  // identify current linear system as solved LinearProblem
994  problem_->setCurrLS();
995  // print final summary
996  sTest_->print (printer_->stream (Belos::FinalSummary));
997 
998  // Print timing information, if the corresponding compile-time and
999  // run-time options are enabled.
1000 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1001  // Calling summarize() can be expensive, so don't call unless the
1002  // user wants to print out timing details. summarize() will do all
1003  // the work even if it's passed a "black hole" output stream.
1004  if (verbosity_ & TimingDetails)
1006 #endif // BELOS_TEUCHOS_TIME_MONITOR
1007 
1008  // A posteriori solve information
1009  numIters_ = maxIterTest_->getNumIters();
1010  matCondNum_ = convTest_->getMatCondNum();
1011  matNorm_ = convTest_->getMatNorm();
1012  resNorm_ = convTest_->getResidNorm();
1013  matResNorm_ = convTest_->getLSResidNorm();
1014 
1015  if (! isConverged) {
1016  return Belos::Unconverged;
1017  } else {
1018  return Belos::Converged;
1019  }
1020 }
1021 
1022 // LSQRSolMgr requires the solver manager to return an eponymous std::string.
1023 template<class ScalarType, class MV, class OP>
1025 {
1026  std::ostringstream oss;
1027  oss << "LSQRSolMgr<...,"<<Teuchos::ScalarTraits<ScalarType>::name()<<">";
1028  oss << "{";
1029  oss << "Ortho Type='"<<orthoType_<<"'";
1030  oss << ", Lambda="<< lambda_;
1031  oss << ", condition number limit="<< condMax_;
1032  oss << ", relative RHS Error="<< relRhsErr_;
1033  oss << ", relative Matrix Error="<< relMatErr_;
1034  oss << ", maximum number of iterations="<< maxIters_;
1035  oss << ", termIterMax="<<termIterMax_;
1036  oss << "}";
1037  return oss.str();
1038 }
1039 
1040 } // end Belos namespace
1041 
1042 #endif /* BELOS_LSQR_SOLMGR_HPP */
Collection of types and exceptions used within the Belos solvers.
IterationState contains the data that defines the state of the LSQR solver at any given time...
Belos concrete class that iterates LSQR.
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
Class which manages the output and verbosity of the Belos solvers.
bool is_null(const boost::shared_ptr< T > &p)
LSQRSolMgrBlockSizeFailure(const std::string &what_arg)
Teuchos::Array< Teuchos::RCP< Teuchos::Time > > getTimers() const
Return the timers for this object.
MagnitudeType getMatResNorm() const
Estimate of (residual vector ) from the last solve.
LSQRSolMgrBlockSizeFailure is thrown when the linear problem has more than one RHS.
T & get(const std::string &name, T def_value)
MsgType
Available message types recognized by the linear solvers.
Definition: BelosTypes.hpp:252
ParameterList & set(std::string const &name, T const &value, std::string const &docString="", RCP< const ParameterEntryValidator > const &validator=null)
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
A factory class for generating StatusTestOutput objects.
Teuchos::RCP< const Teuchos::ParameterList > getDefaultParameters(const std::string &name) const
Default parameters for the given MatOrthoManager subclass.
Belos::StatusTest class for specifying a maximum number of iterations.
Belos::StatusTest class defining LSQR convergence.
static std::string name()
std::string description() const
Method to return description of the LSQR solver manager.
A factory class for generating StatusTestOutput objects.
std::string validNamesString() const
List (as a string) of recognized MatOrthoManager names.
static void summarize(Ptr< const Comm< int > > comm, std::ostream &out=std::cout, const bool alwaysWriteLocal=false, const bool writeGlobalStats=true, const bool writeZeroTimers=true, const ECounterSetOp setOp=Intersection, const std::string &filter="")
void reset(const ResetType type)
reset the solver manager as specified by the ResetType, informs the solver manager that the solver sh...
Traits class which defines basic operations on multivectors.
Belos::StatusTest for logically combining several status tests.
Belos::LSQRSolMgrLinearProblemFailure is thrown when the linear problem is not setup (i...
bool isParameter(const std::string &name) const
A Belos::StatusTest class for specifying a maximum number of iterations.
ResetType
How to reset the solver.
Definition: BelosTypes.hpp:200
LSQRSolMgrOrthoFailure(const std::string &what_arg)
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
LSQRSolMgr()
Empty constructor for LSQRSolMgr. This constructor takes no arguments and sets the default values for...
Pure virtual base class which describes the basic interface for a solver manager. ...
std::ostream & printValidNames(std::ostream &out) const
Print all recognized MatOrthoManager names to the given ostream.
int getNumIters() const
Iteration count from the last solve.
A linear system to solve, and its associated information.
Class which describes the linear problem to be solved by the iterative solver.
void validateParametersAndSetDefaults(ParameterList const &validParamList, int const depth=1000)
ReturnType
Whether the Belos solve converged for all linear systems.
Definition: BelosTypes.hpp:149
virtual ~LSQRSolMgr()
Destructor.
The Belos::SolverManager is a templated virtual base class that defines the basic interface that any ...
Teuchos::RCP< const Teuchos::ParameterList > getCurrentParameters() const
Get a parameter list containing the current parameters for this object.
ReturnType solve()
method that performs possibly repeated calls to the underlying linear solver&#39;s iterate() routine unti...
MagnitudeType getResNorm() const
Estimated residual norm from the last solve.
Teuchos::RCP< StatusTestOutput< ScalarType, MV, OP > > create(const Teuchos::RCP< OutputManager< ScalarType > > &printer, Teuchos::RCP< StatusTest< ScalarType, MV, OP > > test, int mod, int printStates)
Create the StatusTestOutput object specified by the outputStyle.
LSQRSolMgrOrthoFailure is thrown when the orthogonalization manager is unable to generate orthonormal...
bool isLOADetected() const
Whether a loss of accuracy was detected during the last solve.
An implementation of the Belos::MatOrthoManager that performs orthogonalization using (potentially) m...
A class for extending the status testing capabilities of Belos via logical combinations.
MagnitudeType getMatCondNum() const
Estimated matrix condition number from the last solve.
LSQR method (for linear systems and linear least-squares problems).
Class which defines basic traits for the operator type.
Implementation of the LSQR iteration.
Parent class to all Belos exceptions.
Definition: BelosTypes.hpp:60
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Get a parameter list containing the valid parameters for this object.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get current linear problem being solved for in this object.
Structure to contain pointers to LSQRIteration state variables, ...
Belos header file which uses auto-configuration information to include necessary C++ headers...
MagnitudeType getMatNorm() const
Estimated matrix Frobenius norm from the last solve.
void setProblem(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem)
Set the linear problem that needs to be solved.
LSQRSolMgrLinearProblemFailure(const std::string &what_arg)
void setParameters(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set the parameters the solver manager should use to solve the linear problem.
bool is_null() const