MueLu  Version of the Day
MueLu_IfpackSmoother.cpp
Go to the documentation of this file.
1 // @HEADER
2 //
3 // ***********************************************************************
4 //
5 // MueLu: A package for multigrid based preconditioning
6 // Copyright 2012 Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact
39 // Jonathan Hu (jhu@sandia.gov)
40 // Andrey Prokopenko (aprokop@sandia.gov)
41 // Ray Tuminaro (rstumin@sandia.gov)
42 //
43 // ***********************************************************************
44 //
45 // @HEADER
46 #include "MueLu_ConfigDefs.hpp"
47 
48 #if defined(HAVE_MUELU_EPETRA) && defined(HAVE_MUELU_IFPACK)
49 #include <Ifpack.h>
50 #include <Ifpack_Chebyshev.h>
51 #include "Xpetra_MultiVectorFactory.hpp"
52 
53 #include "MueLu_IfpackSmoother.hpp"
54 
55 #include "MueLu_Level.hpp"
56 #include "MueLu_Utilities.hpp"
57 #include "MueLu_Monitor.hpp"
58 
59 namespace MueLu {
60 
61  IfpackSmoother::IfpackSmoother(std::string const & type, Teuchos::ParameterList const & paramList, LO const &overlap)
62  : type_(type), overlap_(overlap)
63  {
64  SetParameterList(paramList);
65  }
66 
67  void IfpackSmoother::SetParameterList(const Teuchos::ParameterList& paramList) {
68  Factory::SetParameterList(paramList);
69 
71  // It might be invalid to change parameters after the setup, but it depends entirely on Ifpack implementation.
72  // TODO: I don't know if Ifpack returns an error code or exception or ignore parameters modification in this case...
73  prec_->SetParameters(const_cast<ParameterList&>(this->GetParameterList()));
74  }
75  }
76 
77  void IfpackSmoother::SetPrecParameters(const Teuchos::ParameterList& list) const {
78  ParameterList& paramList = const_cast<ParameterList&>(this->GetParameterList());
79  paramList.setParameters(list);
80 
81  RCP<ParameterList> precList = this->RemoveFactoriesFromList(this->GetParameterList());
82 
83  prec_->SetParameters(*precList);
84 
85  // We would like to have the following line here:
86  // paramList.setParameters(*precList);
87  // For instance, if Ifpack sets somem parameters internally, we would like to have
88  // them listed when we call this->GetParameterList()
89  // But because of the way Ifpack handles the list, we cannot do that.
90  // The bad scenario goes like this:
91  // * SmootherFactory calls Setup
92  // * Setup calls SetPrecParameters
93  // * We call prec_->SetParameters(*precList)
94  // This actually updates the internal parameter list with default prec_ parameters
95  // This means that we get a parameter ("chebyshev: max eigenvalue", -1) in the list
96  // * Setup calls prec_->Compute()
97  // Here we may compute the max eigenvalue, but we get no indication of this. If we
98  // do compute it, our parameter list becomes outdated
99  // * SmootherFactory calls Apply
100  // * Apply constructs a list with a list with an entry "chebyshev: zero starting solution"
101  // * We call prec_->SetParameters(*precList)
102  // The last call is the problem. At this point, we have a list with an outdated entry
103  // "chebyshev: max eigenvalue", but prec_ uses this entry and replaces the computed max
104  // eigenvalue with the one from the list, resulting in -1.0 eigenvalue.
105  //
106  // Ifpack2 does not have this problem, as it does not populate the list with new entries
107  }
108 
109  void IfpackSmoother::DeclareInput(Level &currentLevel) const {
110  this->Input(currentLevel, "A");
111 
112  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
113  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
114  type_ == "LINESMOOTHING_BANDEDRELAXATION" ||
115  type_ == "LINESMOOTHING_BLOCK_RELAXATION" ||
116  type_ == "LINESMOOTHING_BLOCK RELAXATION" ||
117  type_ == "LINESMOOTHING_BLOCKRELAXATION") {
118  this->Input(currentLevel, "CoarseNumZLayers"); // necessary for fallback criterion
119  this->Input(currentLevel, "LineDetection_VertLineIds"); // necessary to feed block smoother
120  } // if (type_ == "LINESMOOTHING_BANDEDRELAXATION")
121  }
122 
123  void IfpackSmoother::Setup(Level &currentLevel) {
124  FactoryMonitor m(*this, "Setup Smoother", currentLevel);
125  if (SmootherPrototype::IsSetup() == true)
126  GetOStream(Warnings0) << "MueLu::IfpackSmoother::Setup(): Setup() has already been called";
127 
128  A_ = Factory::Get< RCP<Matrix> >(currentLevel, "A");
129 
130  double lambdaMax = -1.0;
131  if (type_ == "Chebyshev") {
132  std::string maxEigString = "chebyshev: max eigenvalue";
133  std::string eigRatioString = "chebyshev: ratio eigenvalue";
134 
135  try {
136  lambdaMax = Teuchos::getValue<Scalar>(this->GetParameter(maxEigString));
137  this->GetOStream(Statistics1) << maxEigString << " (cached with smoother parameter list) = " << lambdaMax << std::endl;
138 
139  } catch (Teuchos::Exceptions::InvalidParameterName) {
140  lambdaMax = A_->GetMaxEigenvalueEstimate();
141 
142  if (lambdaMax != -1.0) {
143  this->GetOStream(Statistics1) << maxEigString << " (cached with matrix) = " << lambdaMax << std::endl;
144  this->SetParameter(maxEigString, ParameterEntry(lambdaMax));
145  }
146  }
147 
148  // Calculate the eigenvalue ratio
149  const Scalar defaultEigRatio = 20;
150 
151  Scalar ratio = defaultEigRatio;
152  try {
153  ratio = Teuchos::getValue<Scalar>(this->GetParameter(eigRatioString));
154 
155  } catch (Teuchos::Exceptions::InvalidParameterName) {
156  this->SetParameter(eigRatioString, ParameterEntry(ratio));
157  }
158 
159  if (currentLevel.GetLevelID()) {
160  // Update ratio to be
161  // ratio = max(number of fine DOFs / number of coarse DOFs, defaultValue)
162  //
163  // NOTE: We don't need to request previous level matrix as we know for sure it was constructed
164  RCP<const Matrix> fineA = currentLevel.GetPreviousLevel()->Get<RCP<Matrix> >("A");
165  size_t nRowsFine = fineA->getGlobalNumRows();
166  size_t nRowsCoarse = A_->getGlobalNumRows();
167 
168  ratio = std::max(ratio, as<Scalar>(nRowsFine)/nRowsCoarse);
169 
170  this->GetOStream(Statistics1) << eigRatioString << " (computed) = " << ratio << std::endl;
171  this->SetParameter(eigRatioString, ParameterEntry(ratio));
172  }
173  } // if (type_ == "Chebyshev")
174 
175  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
176  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
177  type_ == "LINESMOOTHING_BANDEDRELAXATION" ||
178  type_ == "LINESMOOTHING_BLOCK_RELAXATION" ||
179  type_ == "LINESMOOTHING_BLOCK RELAXATION" ||
180  type_ == "LINESMOOTHING_BLOCKRELAXATION" ) {
181  ParameterList& myparamList = const_cast<ParameterList&>(this->GetParameterList());
182 
183  LO CoarseNumZLayers = Factory::Get<LO>(currentLevel,"CoarseNumZLayers");
184  if (CoarseNumZLayers > 0) {
185  Teuchos::ArrayRCP<LO> TVertLineIdSmoo = Factory::Get< Teuchos::ArrayRCP<LO> >(currentLevel, "LineDetection_VertLineIds");
186 
187  // determine number of local parts
188  LO maxPart = 0;
189  for(size_t k = 0; k < Teuchos::as<size_t>(TVertLineIdSmoo.size()); k++) {
190  if(maxPart < TVertLineIdSmoo[k]) maxPart = TVertLineIdSmoo[k];
191  }
192 
193  size_t numLocalRows = A_->getNodeNumRows();
194  TEUCHOS_TEST_FOR_EXCEPTION(numLocalRows % TVertLineIdSmoo.size() != 0, Exceptions::RuntimeError, "MueLu::Ifpack2Smoother::Setup(): the number of local nodes is incompatible with the TVertLineIdsSmoo.");
195 
196  if (numLocalRows == Teuchos::as<size_t>(TVertLineIdSmoo.size())) {
197  myparamList.set("partitioner: type","user");
198  myparamList.set("partitioner: map",&(TVertLineIdSmoo[0]));
199  myparamList.set("partitioner: local parts",maxPart+1);
200  } else {
201  // we assume a constant number of DOFs per node
202  size_t numDofsPerNode = numLocalRows / TVertLineIdSmoo.size();
203 
204  // Create a new Teuchos::ArrayRCP<LO> of size numLocalRows and fill it with the corresponding information
205  Teuchos::ArrayRCP<LO> partitionerMap(numLocalRows, Teuchos::OrdinalTraits<LocalOrdinal>::invalid());
206  for (size_t blockRow = 0; blockRow < Teuchos::as<size_t>(TVertLineIdSmoo.size()); ++blockRow)
207  for (size_t dof = 0; dof < numDofsPerNode; dof++)
208  partitionerMap[blockRow * numDofsPerNode + dof] = TVertLineIdSmoo[blockRow];
209  myparamList.set("partitioner: type","user");
210  myparamList.set("partitioner: map",&(partitionerMap[0]));
211  myparamList.set("partitioner: local parts",maxPart + 1);
212  }
213 
214  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
215  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
216  type_ == "LINESMOOTHING_BANDEDRELAXATION")
217  type_ = "block relaxation";
218  else
219  type_ = "block relaxation";
220  } else {
221  // line detection failed -> fallback to point-wise relaxation
222  this->GetOStream(Runtime0) << "Line detection failed: fall back to point-wise relaxation" << std::endl;
223  myparamList.remove("partitioner: type",false);
224  myparamList.remove("partitioner: map", false);
225  myparamList.remove("partitioner: local parts",false);
226  type_ = "point relaxation stand-alone";
227  }
228 
229  } // if (type_ == "LINESMOOTHING_BANDEDRELAXATION")
230 
231  RCP<Epetra_CrsMatrix> epA = Utils::Op2NonConstEpetraCrs(A_);
232 
233  Ifpack factory;
234  prec_ = rcp(factory.Create(type_, &(*epA), overlap_));
235  TEUCHOS_TEST_FOR_EXCEPTION(prec_.is_null(), Exceptions::RuntimeError, "Could not create an Ifpack preconditioner with type = \"" << type_ << "\"");
237  prec_->Compute();
238 
240 
241  if (type_ == "Chebyshev" && lambdaMax == -1.0) {
242  Teuchos::RCP<Ifpack_Chebyshev> chebyPrec = rcp_dynamic_cast<Ifpack_Chebyshev>(prec_);
243  if (chebyPrec != Teuchos::null) {
244  lambdaMax = chebyPrec->GetLambdaMax();
245  A_->SetMaxEigenvalueEstimate(lambdaMax);
246  this->GetOStream(Statistics1) << "chebyshev: max eigenvalue (calculated by Ifpack)" << " = " << lambdaMax << std::endl;
247  }
248  TEUCHOS_TEST_FOR_EXCEPTION(lambdaMax == -1.0, Exceptions::RuntimeError, "MueLu::IfpackSmoother::Setup(): no maximum eigenvalue estimate");
249  }
250 
251  this->GetOStream(Statistics0) << description() << std::endl;
252  }
253 
254  void IfpackSmoother::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
255  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IfpackSmoother::Apply(): Setup() has not been called");
256 
257  // Forward the InitialGuessIsZero option to Ifpack
258  Teuchos::ParameterList paramList;
259  bool supportInitialGuess = false;
260  if (type_ == "Chebyshev") {
261  paramList.set("chebyshev: zero starting solution", InitialGuessIsZero);
262  supportInitialGuess = true;
263 
264  } else if (type_ == "point relaxation stand-alone") {
265  paramList.set("relaxation: zero starting solution", InitialGuessIsZero);
266  supportInitialGuess = true;
267  }
268 
269  SetPrecParameters(paramList);
270 
271  // Apply
272  if (InitialGuessIsZero || supportInitialGuess) {
273  Epetra_MultiVector& epX = Utils::MV2NonConstEpetraMV(X);
274  const Epetra_MultiVector& epB = Utils::MV2EpetraMV(B);
275 
276  prec_->ApplyInverse(epB, epX);
277 
278  } else {
279  RCP<MultiVector> Residual = Utils::Residual(*A_, X, B);
280  RCP<MultiVector> Correction = MultiVectorFactory::Build(A_->getDomainMap(), X.getNumVectors());
281 
282  Epetra_MultiVector& epX = Utils::MV2NonConstEpetraMV(*Correction);
283  const Epetra_MultiVector& epB = Utils::MV2EpetraMV(*Residual);
284 
285  prec_->ApplyInverse(epB, epX);
286 
287  X.update(1.0, *Correction, 1.0);
288  }
289  }
290 
291  RCP<MueLu::SmootherPrototype<double, int, int> > IfpackSmoother::Copy() const {
292  RCP<IfpackSmoother> smoother = rcp(new IfpackSmoother(*this) );
293  smoother->SetParameterList(this->GetParameterList());
294  return smoother;
295  }
296 
297  std::string IfpackSmoother::description() const {
298  std::ostringstream out;
299  // The check "GetVerbLevel() == Test" is to avoid
300  // failures in the EasyInterface test.
301  if (prec_ == Teuchos::null || GetVerbLevel() == Test) {
303  out << "{type = " << type_ << "}";
304  } else {
305  out << prec_->Label();
306  }
307  return out.str();
308  }
309 
310  void IfpackSmoother::print(Teuchos::FancyOStream &out, const VerbLevel verbLevel) const {
312 
313  if (verbLevel & Parameters0)
314  out0 << "Prec. type: " << type_ << std::endl;
315 
316  if (verbLevel & Parameters1) {
317  out0 << "Parameter list: " << std::endl;
318  Teuchos::OSTab tab2(out);
319  out << this->GetParameterList();
320  out0 << "Overlap: " << overlap_ << std::endl;
321  }
322 
323  if (verbLevel & External)
324  if (prec_ != Teuchos::null) {
325  Teuchos::OSTab tab2(out);
326  out << *prec_ << std::endl;
327  }
328 
329  if (verbLevel & Debug) {
330  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl
331  << "-" << std::endl
332  << "RCP<A_>: " << A_ << std::endl
333  << "RCP<prec_>: " << prec_ << std::endl;
334  }
335  }
336 
337 } // namespace MueLu
338 
339 #endif
Important warning messages (one line)
void SetParameterList(const Teuchos::ParameterList &paramList)
std::string description() const
Return a simple one-line description of this object.
static RCP< Epetra_MultiVector > MV2NonConstEpetraMV(RCP< MultiVector > Vec)
std::string toString(const T &what)
Little helper function to convert non-string types to strings.
RCP< SmootherPrototype > Copy() const
RCP< Matrix > A_
Matrix. Not used directly, but held inside of prec_. So we have to keep an RCP pointer to it! ...
Print external lib objects.
LO overlap_
overlap when using the smoother in additive Schwarz mode
void SetPrecParameters(const Teuchos::ParameterList &list=Teuchos::ParameterList()) const
Timer to be used in factories. Similar to Monitor but with additional timers.
Print more statistics.
Print additional debugging information.
One-liner description of what is happening.
Namespace for MueLu classes and methods.
virtual const Teuchos::ParameterList & GetParameterList() const
Ifpack_Preconditioner * Create(const std::string PrecType, Epetra_RowMatrix *Matrix, const int overlap=0, bool overrideSerialDefault=false)
Print skeleton for the run, i.e. factory calls and used parameters.
static RCP< const Epetra_MultiVector > MV2EpetraMV(RCP< MultiVector > const Vec)
Helper utility to pull out the underlying Epetra objects from an Xpetra object.
RCP< Ifpack_Preconditioner > prec_
pointer to Ifpack solver object
VerbLevel GetVerbLevel() const
Get the verbosity level.
Print statistics that do not involve significant additional computation.
RCP< ParameterList > RemoveFactoriesFromList(const ParameterList &list) const
virtual void SetParameterList(const ParameterList &paramList)
Set parameters from a parameter list and return with default values.
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
void print(Teuchos::FancyOStream &out, const VerbLevel verbLevel=Default) const
Print the object with some verbosity level to an FancyOStream object.
IfpackSmoother(std::string const &type, Teuchos::ParameterList const &paramList=Teuchos::ParameterList(), LO const &overlap=0)
Constructor.
bool IsSetup() const
Get the state of a smoother prototype.
void Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero=false) const
Apply the preconditioner.
virtual double GetLambdaMax()
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
void SetParameter(const std::string &name, const ParameterEntry &entry)
Set a parameter directly as a ParameterEntry.
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
Print class parameters.
void Setup(Level &currentLevel)
Set up the smoother.
std::string type_
ifpack-specific key phrase that denote smoother type
Print class parameters (more parameters, more verbose)
Exception throws to report errors in the internal logical of the program.
static RCP< Epetra_CrsMatrix > Op2NonConstEpetraCrs(RCP< Matrix > Op)
const ParameterEntry & GetParameter(const std::string &name) const
Retrieves a const entry with the name name.
void Input(Level &level, const std::string &varName) const
virtual std::string description() const
Return a simple one-line description of this object.
static RCP< MultiVector > Residual(const Operator &Op, const MultiVector &X, const MultiVector &RHS)
void DeclareInput(Level &currentLevel) const
Input.