Stratimikos Package Browser (Single Doxygen Collection)  Version of the Day
Thyra_MLPreconditionerFactory.cpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Stratimikos: Thyra-based strategies for linear solvers
5 // Copyright (2006) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
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 Roscoe A. Bartlett (rabartl@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
43 
44 #include "Thyra_EpetraOperatorViewExtractorStd.hpp"
45 #include "Thyra_EpetraLinearOp.hpp"
46 #include "Thyra_DefaultPreconditioner.hpp"
47 #include "ml_MultiLevelPreconditioner.h"
48 #include "ml_MultiLevelOperator.h"
49 #include "ml_ValidateParameters.h"
50 #include "Epetra_RowMatrix.h"
52 #include "Teuchos_dyn_cast.hpp"
53 #include "Teuchos_TimeMonitor.hpp"
58 
59 
60 namespace {
61 
62 
64  ML_PROBTYPE_NONE,
65  ML_PROBTYPE_SMOOTHED_AGGREGATION,
66  ML_PROBTYPE_DOMAIN_DECOMPOSITION,
67  ML_PROBTYPE_DOMAIN_DECOMPOSITION_ML,
68  ML_PROBTYPE_MAXWELL
69 };
70 const std::string BaseMethodDefaults_valueNames_none = "none";
71 const Teuchos::Array<std::string> BaseMethodDefaults_valueNames
72 = Teuchos::tuple<std::string>(
73  BaseMethodDefaults_valueNames_none,
74  "SA",
75  "DD",
76  "DD-ML",
77  "maxwell"
78  );
79 
80 
82 
83 
85 {
87 }
88 
89 const std::string BaseMethodDefaults_name = "Base Method Defaults";
90 const std::string BaseMethodDefaults_default = "SA";
93  >
94 BaseMethodDefaults_validator;
95 
96 const std::string ReuseFineLevelSmoother_name = "Reuse Fine Level Smoother";
97 const bool ReuseFineLevelSmoother_default = false;
98 
99 const std::string MLSettings_name = "ML Settings";
100 
101 
102 } // namespace
103 
104 
105 namespace Thyra {
106 
107 
108 using Teuchos::RCP;
110 
111 
112 // Constructors/initializers/accessors
113 
114 
116  :epetraFwdOpViewExtractor_(Teuchos::rcp(new EpetraOperatorViewExtractorStd()))
117 {}
118 
119 
120 // Overridden from PreconditionerFactoryBase
121 
122 
124  const LinearOpSourceBase<double> &fwdOpSrc
125  ) const
126 {
127  using Teuchos::outArg;
129  EOpTransp epetraFwdOpTransp;
130  EApplyEpetraOpAs epetraFwdOpApplyAs;
131  EAdjointEpetraOp epetraFwdOpAdjointSupport;
132  double epetraFwdOpScalar;
134  fwdOp = fwdOpSrc.getOp();
135  epetraFwdOpViewExtractor_->getEpetraOpView(
136  fwdOp,
137  outArg(epetraFwdOp),outArg(epetraFwdOpTransp),
138  outArg(epetraFwdOpApplyAs),
139  outArg(epetraFwdOpAdjointSupport),
140  outArg(epetraFwdOpScalar)
141  );
142  if( !dynamic_cast<const Epetra_RowMatrix*>(&*epetraFwdOp) )
143  return false;
144  return true;
145 }
146 
147 
149 {
150  return true;
151 }
152 
153 
155 {
156  return false; // See comment below
157 }
158 
159 
162 {
163  return Teuchos::rcp(new DefaultPreconditioner<double>());
164 }
165 
166 
168  const Teuchos::RCP<const LinearOpSourceBase<double> > &fwdOpSrc,
169  PreconditionerBase<double> *prec,
170  const ESupportSolveUse supportSolveUse
171  ) const
172 {
173  using Teuchos::outArg;
174  using Teuchos::OSTab;
175  using Teuchos::dyn_cast;
176  using Teuchos::RCP;
177  using Teuchos::null;
178  using Teuchos::rcp;
179  using Teuchos::rcp_dynamic_cast;
180  using Teuchos::rcp_const_cast;
181  using Teuchos::set_extra_data;
182  using Teuchos::get_optional_extra_data;
184  Teuchos::Time totalTimer(""), timer("");
185  totalTimer.start(true);
186  const RCP<Teuchos::FancyOStream> out = this->getOStream();
187  const Teuchos::EVerbosityLevel verbLevel = this->getVerbLevel();
188  Teuchos::OSTab tab(out);
189  if(out.get() && implicit_cast<int>(verbLevel) > implicit_cast<int>(Teuchos::VERB_LOW))
190  *out << "\nEntering Thyra::MLPreconditionerFactory::initializePrec(...) ...\n";
191 
192  Teuchos::RCP<const LinearOpBase<double> > fwdOp = fwdOpSrc->getOp();
193 #ifdef _DEBUG
194  TEUCHOS_TEST_FOR_EXCEPT(fwdOp.get()==NULL);
195  TEUCHOS_TEST_FOR_EXCEPT(prec==NULL);
196 #endif
197  //
198  // Unwrap and get the forward Epetra_Operator object
199  //
201  EOpTransp epetraFwdOpTransp;
202  EApplyEpetraOpAs epetraFwdOpApplyAs;
203  EAdjointEpetraOp epetraFwdOpAdjointSupport;
204  double epetraFwdOpScalar;
205  epetraFwdOpViewExtractor_->getEpetraOpView(
206  fwdOp,outArg(epetraFwdOp),outArg(epetraFwdOpTransp),outArg(epetraFwdOpApplyAs),
207  outArg(epetraFwdOpAdjointSupport),outArg(epetraFwdOpScalar)
208  );
209  // Validate what we get is what we need
211  epetraFwdRowMat = rcp_dynamic_cast<const Epetra_RowMatrix>(epetraFwdOp,true);
213  epetraFwdOpApplyAs != EPETRA_OP_APPLY_APPLY, std::logic_error
214  ,"Error, incorrect apply mode for an Epetra_RowMatrix"
215  );
216 
217  //
218  // Get the concrete preconditioner object
219  //
220  DefaultPreconditioner<double>
221  *defaultPrec = &Teuchos::dyn_cast<DefaultPreconditioner<double> >(*prec);
222  //
223  // Get the EpetraLinearOp object that is used to implement the preconditoner linear op
224  //
226  epetra_precOp = rcp_dynamic_cast<EpetraLinearOp>(defaultPrec->getNonconstUnspecifiedPrecOp(),true);
227  //
228  // Get the embedded ML_Epetra::MultiLevelPreconditioner object if it exists
229  //
231  if(epetra_precOp.get())
232  ml_precOp = rcp_dynamic_cast<ML_Epetra::MultiLevelPreconditioner>(epetra_precOp->epetra_op(),true);
233  //
234  // Get the attached forward operator if it exists and make sure that it matches
235  //
236  if(ml_precOp!=Teuchos::null) {
237  // Get the forward operator and make sure that it matches what is
238  // already being used!
239  const Epetra_RowMatrix & rm = ml_precOp->RowMatrix();
240 
241  TEUCHOS_TEST_FOR_EXCEPTION(
242  &rm!=&*epetraFwdRowMat, std::logic_error
243  ,"ML requires Epetra_RowMatrix to be the same for each initialization of the preconditioner"
244  );
245  }
246  //
247  // Perform initialization if needed
248  //
249  const bool startingOver = (ml_precOp.get() == NULL);
250  if(startingOver)
251  {
252  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
253  *out << "\nCreating the initial ML_Epetra::MultiLevelPreconditioner object...\n";
254  timer.start(true);
255  // Create the initial preconditioner: DO NOT compute it yet
256  ml_precOp = rcp(
257  new ML_Epetra::MultiLevelPreconditioner(
258  *epetraFwdRowMat, paramList_->sublist(MLSettings_name),false
259  )
260  );
261 
262  timer.stop();
263  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
264  OSTab(out).o() <<"> Creation time = "<<timer.totalElapsedTime()<<" sec\n";
265  // RAB: Above, I am just passing a string to ML::Create(...) in order
266  // get this code written. However, in the future, it would be good to
267  // copy the contents of what is in ML::Create(...) into a local
268  // function and then use switch(...) to create the initial
269  // ML_Epetra::MultiLevelPreconditioner object. This would result in better validation
270  // and faster code.
271  // Set parameters if the list exists
272  if(paramList_.get())
273  TEUCHOS_TEST_FOR_EXCEPT(
274  0!=ml_precOp->SetParameterList(paramList_->sublist(MLSettings_name))
275  );
276  // Initialize the structure for the preconditioner
277  // TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->Initialize());
278  }
279  //
280  // Attach the epetraFwdOp to the ml_precOp to guarantee that it will not go away
281  //
282  set_extra_data(epetraFwdOp, "IFPF::epetraFwdOp", Teuchos::inOutArg(ml_precOp),
283  Teuchos::POST_DESTROY, false);
284  //
285  // Update the factorization
286  //
287  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
288  *out << "\nComputing the preconditioner ...\n";
289  timer.start(true);
290  if (startingOver) {
291  TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->ComputePreconditioner());
292  }
293  else {
294  TEUCHOS_TEST_FOR_EXCEPT(0!=ml_precOp->ReComputePreconditioner(paramList_->get<bool>(ReuseFineLevelSmoother_name)));
295  }
296  timer.stop();
297  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
298  OSTab(out).o() <<"=> Setup time = "<<timer.totalElapsedTime()<<" sec\n";
299  //
300  // Compute the conditioner number estimate if asked
301  //
302 
303  // ToDo: Implement
304 
305  //
306  // Attach fwdOp to the ml_precOp
307  //
308  set_extra_data(fwdOp, "IFPF::fwdOp", Teuchos::inOutArg(ml_precOp),
309  Teuchos::POST_DESTROY, false);
310  //
311  // Initialize the output EpetraLinearOp
312  //
313  if(startingOver) {
314  epetra_precOp = rcp(new EpetraLinearOp);
315  }
316  epetra_precOp->initialize(
317  ml_precOp
318  ,epetraFwdOpTransp
319  ,EPETRA_OP_APPLY_APPLY_INVERSE
320  ,EPETRA_OP_ADJOINT_UNSUPPORTED // ToDo: Look into adjoints again.
321  );
322  //
323  // Initialize the preconditioner
324  //
325  defaultPrec->initializeUnspecified(
326  Teuchos::rcp_implicit_cast<LinearOpBase<double> >(epetra_precOp)
327  );
328  totalTimer.stop();
329  if(out.get() && implicit_cast<int>(verbLevel) >= implicit_cast<int>(Teuchos::VERB_LOW))
330  *out << "\nTotal time in MLPreconditionerFactory = "<<totalTimer.totalElapsedTime()<<" sec\n";
331  if(out.get() && implicit_cast<int>(verbLevel) > implicit_cast<int>(Teuchos::VERB_LOW))
332  *out << "\nLeaving Thyra::MLPreconditionerFactory::initializePrec(...) ...\n";
333 }
334 
335 
337  PreconditionerBase<double> *prec,
338  Teuchos::RCP<const LinearOpSourceBase<double> > *fwdOp,
339  ESupportSolveUse *supportSolveUse
340  ) const
341 {
343 }
344 
345 
346 // Overridden from ParameterListAcceptor
347 
348 
350  Teuchos::RCP<ParameterList> const& paramList
351  )
352 {
353  TEUCHOS_TEST_FOR_EXCEPT(paramList.get()==NULL);
354  paramList->validateParameters(*this->getValidParameters(),0);
355  paramList_ = paramList;
356 
357  // set default for reuse of fine level smoother
358  if(!paramList_->isType<bool>(ReuseFineLevelSmoother_name))
359  paramList_->set<bool>(ReuseFineLevelSmoother_name,ReuseFineLevelSmoother_default);
360 
361  const EMLProblemType
362  defaultType = BaseMethodDefaults_validator->getIntegralValue(
363  *paramList_,BaseMethodDefaults_name,BaseMethodDefaults_default
364  );
365  if( ML_PROBTYPE_NONE != defaultType ) {
366  const std::string
367  defaultTypeStr = BaseMethodDefaults_valueNames[defaultType];
368  Teuchos::ParameterList defaultParams;
370  0!=ML_Epetra::SetDefaults(defaultTypeStr,defaultParams)
372  ,"Error, the ML problem type \"" << defaultTypeStr << "\' is not recognized by ML!"
373  );
374  // Note, the only way the above exception message could be generated is if
375  // a default problem type was removed from ML_Epetra::SetDefaults(...).
376  // When a new problem type is added to this function, it must be added to
377  // our enum EMLProblemType along with associated objects ... In other
378  // words, this adapter must be maintained as ML is maintained. An
379  // alternative design would be to just pass in whatever string to this
380  // function. This would improve maintainability but it would not generate
381  // very good error messages when a bad string was passed in. Currently,
382  // the error message attached to the exception will contain the list of
383  // valid problem types.
384  paramList_->sublist(MLSettings_name).setParametersNotAlreadySet(
385  defaultParams);
386  }
387 #ifdef TEUCHOS_DEBUG
388  paramList->validateParameters(*this->getValidParameters(),0);
389 #endif
390 }
391 
392 
395 {
396  return paramList_;
397 }
398 
399 
402 {
404  paramList_ = Teuchos::null;
405  return _paramList;
406 }
407 
408 
411 {
412  return paramList_;
413 }
414 
415 
418 {
419 
420  using Teuchos::rcp;
421  using Teuchos::tuple;
423  using Teuchos::rcp_implicit_cast;
425 
426  static RCP<const ParameterList> validPL;
427 
428  if(is_null(validPL)) {
429 
431  pl = rcp(new ParameterList());
432 
433  BaseMethodDefaults_validator = rcp(
435  BaseMethodDefaults_valueNames,
436  tuple<std::string>(
437  "Do not set any default parameters",
438  "Set default parameters for a smoothed aggregation method",
439  "Set default parameters for a domain decomposition method",
440  "Set default parameters for a domain decomposition method special to ML",
441  "Set default parameters for a Maxwell-type of linear operator"
442  ),
443  tuple<EMLProblemType>(
444  ML_PROBTYPE_NONE,
445  ML_PROBTYPE_SMOOTHED_AGGREGATION,
446  ML_PROBTYPE_DOMAIN_DECOMPOSITION,
447  ML_PROBTYPE_DOMAIN_DECOMPOSITION_ML,
448  ML_PROBTYPE_MAXWELL
449  ),
450  BaseMethodDefaults_name
451  )
452  );
453 
454  pl->set(BaseMethodDefaults_name,BaseMethodDefaults_default,
455  "Select the default method type which also sets parameter defaults\n"
456  "in the sublist \"" + MLSettings_name + "\"!",
457  rcp_implicit_cast<const PEV>(BaseMethodDefaults_validator)
458  );
459 
460  pl->set(ReuseFineLevelSmoother_name,ReuseFineLevelSmoother_default,
461  "Enables/disables the reuse of the fine level smoother.");
462 
463 /* 2007/07/02: rabartl: The statement below should be the correct way to
464  * get the list of valid parameters but it seems to be causing problems so
465  * I am commenting it out for now.
466  */
467 /*
468  pl->sublist(
469  MLSettings_name, false,
470  "Parameters directly accepted by ML_Epetra interface."
471  ).setParameters(*rcp(ML_Epetra::GetValidMLPParameters()));
472 */
473 
474  {
475  ParameterList &mlSettingsPL = pl->sublist(
476  MLSettings_name, false,
477  "Sampling of the parameters directly accepted by ML\n"
478  "This list of parameters is generated by combining all of\n"
479  "the parameters set for all of the default problem types supported\n"
480  "by ML. Therefore, do not assume these parameters are at values that\n"
481  "are reasonable to ML. This list is just to give a sense of some of\n"
482  "the parameters that ML accepts. Consult ML documentation on how to\n"
483  "set these parameters. Also, you can print the parameter list after\n"
484  "it is used and see what defaults where set for each default problem\n"
485  "type. Warning! the parameters in this sublist are currently *not*\n"
486  "being validated by ML!"
487  );
488  //std::cout << "\nMLSettings doc before = " << pl->getEntryPtr(MLSettings_name)->docString() << "\n";
489  { // Set of valid parameters (but perhaps not acceptable values)
490  for (
491  int i = 0;
492  i < implicit_cast<int>(BaseMethodDefaults_valueNames.size());
493  ++i
494  )
495  {
496  ParameterList defaultParams;
497  const std::string defaultTypeStr = BaseMethodDefaults_valueNames[i];
498  if (defaultTypeStr != BaseMethodDefaults_valueNames_none) {
500  0!=ML_Epetra::SetDefaults(defaultTypeStr,defaultParams)
502  ,"Error, the ML problem type \"" << defaultTypeStr
503  << "\' is not recognized by ML!"
504  );
505  mlSettingsPL.setParameters(defaultParams);
506  }
507  }
508  }
509  }
510 
511  validPL = pl;
512 
513  }
514 
515  return validPL;
516 
517 }
518 
519 
520 // Public functions overridden from Teuchos::Describable
521 
522 
524 {
525  std::ostringstream oss;
526  oss << "Thyra::MLPreconditionerFactory";
527  return oss.str();
528 }
529 
530 
531 } // namespace Thyra
bool is_null(const boost::shared_ptr< T > &p)
Teuchos::RCP< Teuchos::ParameterList > paramList_
T & get(ParameterList &l, const std::string &name)
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)
Teuchos::RCP< const Teuchos::ParameterList > getParameterList() const
RCP< ParameterList > sublist(const RCP< ParameterList > &paramList, const std::string &name, bool mustAlreadyExist=false, const std::string &docString="")
T * get() const
#define TEUCHOS_ENUM_INPUT_STREAM_OPERATOR(ENUMTYPE)
basic_OSTab< char > OSTab
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Teuchos::RCP< Teuchos::ParameterList > unsetParameterList()
IntegralType getIntegralValue(ParameterList const &paramList, std::string const &paramName)
void setParameterList(Teuchos::RCP< Teuchos::ParameterList > const &paramList)
void start(bool reset=false)
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
double stop()
T_To & dyn_cast(T_From &from)
void initializePrec(const Teuchos::RCP< const LinearOpSourceBase< double > > &fwdOp, PreconditionerBase< double > *prec, const ESupportSolveUse supportSolveUse) const
TypeTo implicit_cast(const TypeFrom &t)
ParameterList & setParameters(const ParameterList &source)
#define TEUCHOS_ADD_STRINGTOINTEGRALVALIDATOR_CONVERTER(INTEGRALTYPE)
void uninitializePrec(PreconditionerBase< double > *prec, Teuchos::RCP< const LinearOpSourceBase< double > > *fwdOp, ESupportSolveUse *supportSolveUse) const
Teuchos::RCP< PreconditionerBase< double > > createPrec() const
bool isType(const std::string &name) const
double totalElapsedTime(bool readCurrentTime=false) const
Teuchos::RCP< Teuchos::ParameterList > getNonconstParameterList()
#define TEUCHOS_TEST_FOR_EXCEPT(throw_exception_test)
bool isCompatible(const LinearOpSourceBase< double > &fwdOp) const
TEUCHOS_STATIC_SETUP()