MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
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 #include "MueLu_Aggregates.hpp"
59 
60 namespace MueLu {
61 
62 template <class Node>
63 IfpackSmoother<Node>::IfpackSmoother(std::string const& type, Teuchos::ParameterList const& paramList, LO const& overlap)
64  : type_(type)
65  , overlap_(overlap) {
66  this->declareConstructionOutcome(false, "");
67  SetParameterList(paramList);
68 }
69 
70 template <class Node>
72  Factory::SetParameterList(paramList);
73 
75  // It might be invalid to change parameters after the setup, but it depends entirely on Ifpack implementation.
76  // TODO: I don't know if Ifpack returns an error code or exception or ignore parameters modification in this case...
77  prec_->SetParameters(const_cast<ParameterList&>(this->GetParameterList()));
78  }
79 }
80 
81 template <class Node>
83  ParameterList& paramList = const_cast<ParameterList&>(this->GetParameterList());
84  paramList.setParameters(list);
85 
86  RCP<ParameterList> precList = this->RemoveFactoriesFromList(this->GetParameterList());
87 
88  prec_->SetParameters(*precList);
89 
90  // We would like to have the following line here:
91  // paramList.setParameters(*precList);
92  // For instance, if Ifpack sets somem parameters internally, we would like to have
93  // them listed when we call this->GetParameterList()
94  // But because of the way Ifpack handles the list, we cannot do that.
95  // The bad scenario goes like this:
96  // * SmootherFactory calls Setup
97  // * Setup calls SetPrecParameters
98  // * We call prec_->SetParameters(*precList)
99  // This actually updates the internal parameter list with default prec_ parameters
100  // This means that we get a parameter ("chebyshev: max eigenvalue", -1) in the list
101  // * Setup calls prec_->Compute()
102  // Here we may compute the max eigenvalue, but we get no indication of this. If we
103  // do compute it, our parameter list becomes outdated
104  // * SmootherFactory calls Apply
105  // * Apply constructs a list with a list with an entry "chebyshev: zero starting solution"
106  // * We call prec_->SetParameters(*precList)
107  // The last call is the problem. At this point, we have a list with an outdated entry
108  // "chebyshev: max eigenvalue", but prec_ uses this entry and replaces the computed max
109  // eigenvalue with the one from the list, resulting in -1.0 eigenvalue.
110  //
111  // Ifpack2 does not have this problem, as it does not populate the list with new entries
112 }
113 
114 template <class Node>
115 void IfpackSmoother<Node>::DeclareInput(Level& currentLevel) const {
116  this->Input(currentLevel, "A");
117 
118  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
119  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
120  type_ == "LINESMOOTHING_BANDEDRELAXATION" ||
121  type_ == "LINESMOOTHING_BLOCK_RELAXATION" ||
122  type_ == "LINESMOOTHING_BLOCK RELAXATION" ||
123  type_ == "LINESMOOTHING_BLOCKRELAXATION") {
124  this->Input(currentLevel, "CoarseNumZLayers"); // necessary for fallback criterion
125  this->Input(currentLevel, "LineDetection_VertLineIds"); // necessary to feed block smoother
126  } // if (type_ == "LINESMOOTHING_BANDEDRELAXATION")
127  else if (type_ == "AGGREGATE") {
128  // Aggregate smoothing needs aggregates
129  this->Input(currentLevel, "Aggregates");
130  }
131 }
132 
133 template <class Node>
134 void IfpackSmoother<Node>::Setup(Level& currentLevel) {
135  FactoryMonitor m(*this, "Setup Smoother", currentLevel);
136  if (SmootherPrototype::IsSetup() == true)
137  this->GetOStream(Warnings0) << "MueLu::IfpackSmoother::Setup(): Setup() has already been called" << std::endl;
138 
139  A_ = Factory::Get<RCP<Matrix> >(currentLevel, "A");
140 
141  double lambdaMax = -1.0;
142  if (type_ == "Chebyshev") {
143  std::string maxEigString = "chebyshev: max eigenvalue";
144  std::string eigRatioString = "chebyshev: ratio eigenvalue";
145 
146  try {
147  lambdaMax = Teuchos::getValue<Scalar>(this->GetParameter(maxEigString));
148  this->GetOStream(Statistics1) << maxEigString << " (cached with smoother parameter list) = " << lambdaMax << std::endl;
149 
151  lambdaMax = A_->GetMaxEigenvalueEstimate();
152 
153  if (lambdaMax != -1.0) {
154  this->GetOStream(Statistics1) << maxEigString << " (cached with matrix) = " << lambdaMax << std::endl;
155  this->SetParameter(maxEigString, ParameterEntry(lambdaMax));
156  }
157  }
158 
159  // Calculate the eigenvalue ratio
160  const Scalar defaultEigRatio = 20;
161 
162  Scalar ratio = defaultEigRatio;
163  try {
164  ratio = Teuchos::getValue<Scalar>(this->GetParameter(eigRatioString));
165 
167  this->SetParameter(eigRatioString, ParameterEntry(ratio));
168  }
169 
170  if (currentLevel.GetLevelID()) {
171  // Update ratio to be
172  // ratio = max(number of fine DOFs / number of coarse DOFs, defaultValue)
173  //
174  // NOTE: We don't need to request previous level matrix as we know for sure it was constructed
175  RCP<const Matrix> fineA = currentLevel.GetPreviousLevel()->Get<RCP<Matrix> >("A");
176  size_t nRowsFine = fineA->getGlobalNumRows();
177  size_t nRowsCoarse = A_->getGlobalNumRows();
178 
179  ratio = std::max(ratio, as<Scalar>(nRowsFine) / nRowsCoarse);
180 
181  this->GetOStream(Statistics1) << eigRatioString << " (computed) = " << ratio << std::endl;
182  this->SetParameter(eigRatioString, ParameterEntry(ratio));
183  }
184  } // if (type_ == "Chebyshev")
185 
186  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
187  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
188  type_ == "LINESMOOTHING_BANDEDRELAXATION" ||
189  type_ == "LINESMOOTHING_BLOCK_RELAXATION" ||
190  type_ == "LINESMOOTHING_BLOCK RELAXATION" ||
191  type_ == "LINESMOOTHING_BLOCKRELAXATION") {
192  ParameterList& myparamList = const_cast<ParameterList&>(this->GetParameterList());
193 
194  LO CoarseNumZLayers = currentLevel.Get<LO>("CoarseNumZLayers", Factory::GetFactory("CoarseNumZLayers").get());
195  if (CoarseNumZLayers > 0) {
196  Teuchos::ArrayRCP<LO> TVertLineIdSmoo = currentLevel.Get<Teuchos::ArrayRCP<LO> >("LineDetection_VertLineIds", Factory::GetFactory("LineDetection_VertLineIds").get());
197 
198  // determine number of local parts
199  LO maxPart = 0;
200  for (size_t k = 0; k < Teuchos::as<size_t>(TVertLineIdSmoo.size()); k++) {
201  if (maxPart < TVertLineIdSmoo[k]) maxPart = TVertLineIdSmoo[k];
202  }
203 
204  size_t numLocalRows = A_->getLocalNumRows();
205  TEUCHOS_TEST_FOR_EXCEPTION(numLocalRows % TVertLineIdSmoo.size() != 0, Exceptions::RuntimeError, "MueLu::Ifpack2Smoother::Setup(): the number of local nodes is incompatible with the TVertLineIdsSmoo.");
206 
207  if (numLocalRows == Teuchos::as<size_t>(TVertLineIdSmoo.size())) {
208  myparamList.set("partitioner: type", "user");
209  myparamList.set("partitioner: map", &(TVertLineIdSmoo[0]));
210  myparamList.set("partitioner: local parts", maxPart + 1);
211  } else {
212  // we assume a constant number of DOFs per node
213  size_t numDofsPerNode = numLocalRows / TVertLineIdSmoo.size();
214 
215  // Create a new Teuchos::ArrayRCP<LO> of size numLocalRows and fill it with the corresponding information
217  for (size_t blockRow = 0; blockRow < Teuchos::as<size_t>(TVertLineIdSmoo.size()); ++blockRow)
218  for (size_t dof = 0; dof < numDofsPerNode; dof++)
219  partitionerMap[blockRow * numDofsPerNode + dof] = TVertLineIdSmoo[blockRow];
220  myparamList.set("partitioner: type", "user");
221  myparamList.set("partitioner: map", &(partitionerMap[0]));
222  myparamList.set("partitioner: local parts", maxPart + 1);
223  }
224 
225  if (type_ == "LINESMOOTHING_BANDED_RELAXATION" ||
226  type_ == "LINESMOOTHING_BANDED RELAXATION" ||
227  type_ == "LINESMOOTHING_BANDEDRELAXATION")
228  type_ = "block relaxation";
229  else
230  type_ = "block relaxation";
231  } else {
232  // line detection failed -> fallback to point-wise relaxation
233  this->GetOStream(Runtime0) << "Line detection failed: fall back to point-wise relaxation" << std::endl;
234  myparamList.remove("partitioner: type", false);
235  myparamList.remove("partitioner: map", false);
236  myparamList.remove("partitioner: local parts", false);
237  type_ = "point relaxation stand-alone";
238  }
239 
240  } // if (type_ == "LINESMOOTHING_BANDEDRELAXATION")
241 
242  if (type_ == "AGGREGATE") {
243  SetupAggregate(currentLevel);
244  }
245 
246  else {
247  // If we're using a linear partitioner and haven't set the # local parts, set it to match the operator's block size
248  ParameterList precList = this->GetParameterList();
249  if (precList.isParameter("partitioner: type") && precList.get<std::string>("partitioner: type") == "linear" &&
250  !precList.isParameter("partitioner: local parts")) {
251  precList.set("partitioner: local parts", (int)A_->getLocalNumRows() / A_->GetFixedBlockSize());
252  }
253 
255 
256  Ifpack factory;
257  prec_ = rcp(factory.Create(type_, &(*epA), overlap_));
258  TEUCHOS_TEST_FOR_EXCEPTION(prec_.is_null(), Exceptions::RuntimeError, "Could not create an Ifpack preconditioner with type = \"" << type_ << "\"");
259  SetPrecParameters();
260  prec_->Compute();
261  }
262 
264 
265  if (type_ == "Chebyshev" && lambdaMax == -1.0) {
266  Teuchos::RCP<Ifpack_Chebyshev> chebyPrec = rcp_dynamic_cast<Ifpack_Chebyshev>(prec_);
267  if (chebyPrec != Teuchos::null) {
268  lambdaMax = chebyPrec->GetLambdaMax();
269  A_->SetMaxEigenvalueEstimate(lambdaMax);
270  this->GetOStream(Statistics1) << "chebyshev: max eigenvalue (calculated by Ifpack)"
271  << " = " << lambdaMax << std::endl;
272  }
273  TEUCHOS_TEST_FOR_EXCEPTION(lambdaMax == -1.0, Exceptions::RuntimeError, "MueLu::IfpackSmoother::Setup(): no maximum eigenvalue estimate");
274  }
275 
276  this->GetOStream(Statistics1) << description() << std::endl;
277 }
278 
279 template <class Node>
281  ParameterList& paramList = const_cast<ParameterList&>(this->GetParameterList());
282 
283  if (this->IsSetup() == true) {
284  this->GetOStream(Warnings0) << "MueLu::Ifpack2moother::SetupAggregate(): Setup() has already been called" << std::endl;
285  this->GetOStream(Warnings0) << "MueLu::IfpackSmoother::SetupAggregate(): reuse of this type is not available, reverting to full construction" << std::endl;
286  }
287 
288  this->GetOStream(Statistics0) << "IfpackSmoother: Using Aggregate Smoothing" << std::endl;
289 
290  RCP<Aggregates> aggregates = Factory::Get<RCP<Aggregates> >(currentLevel, "Aggregates");
291  RCP<const LOMultiVector> vertex2AggId = aggregates->GetVertex2AggId();
292  ArrayRCP<LO> aggregate_ids = rcp_const_cast<LOMultiVector>(vertex2AggId)->getDataNonConst(0);
293  ArrayRCP<LO> dof_ids;
294 
295  // We need to unamalgamate, if the FixedBlockSize > 1
296  if (A_->GetFixedBlockSize() > 1) {
297  // NOTE: We're basically going to have to leave a deallocated pointer hanging out
298  // in the paramList object (and inside the partitioner). This never gets
299  // use again after Compute() gets called, so this is OK, but I'm still leaving
300  // this note here in case it bites us again later.
301  LO blocksize = (LO)A_->GetFixedBlockSize();
302  dof_ids.resize(aggregate_ids.size() * blocksize);
303  for (LO i = 0; i < (LO)aggregate_ids.size(); i++) {
304  for (LO j = 0; j < (LO)blocksize; j++)
305  dof_ids[i * blocksize + j] = aggregate_ids[i];
306  }
307  } else {
308  dof_ids = aggregate_ids;
309  }
310 
311  paramList.set("partitioner: map", dof_ids.getRawPtr());
312  paramList.set("partitioner: type", "user");
313  paramList.set("partitioner: overlap", 0);
314  paramList.set("partitioner: local parts", (int)aggregates->GetNumAggregates());
315  // In case of Dirichlet nodes
316  paramList.set("partitioner: keep singletons", true);
317 
319  type_ = "block relaxation stand-alone";
320 
321  Ifpack factory;
322  prec_ = rcp(factory.Create(type_, &(*A), overlap_));
323  TEUCHOS_TEST_FOR_EXCEPTION(prec_.is_null(), Exceptions::RuntimeError, "Could not create an Ifpack preconditioner with type = \"" << type_ << "\"");
324  SetPrecParameters();
325 
326  int rv = prec_->Compute();
327  TEUCHOS_TEST_FOR_EXCEPTION(rv, Exceptions::RuntimeError, "Ifpack preconditioner with type = \"" << type_ << "\" Compute() call failed.");
328 }
329 
330 template <class Node>
331 void IfpackSmoother<Node>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
332  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IfpackSmoother::Apply(): Setup() has not been called");
333 
334  // Forward the InitialGuessIsZero option to Ifpack
335  Teuchos::ParameterList paramList;
336  bool supportInitialGuess = false;
337  if (type_ == "Chebyshev") {
338  paramList.set("chebyshev: zero starting solution", InitialGuessIsZero);
339  supportInitialGuess = true;
340 
341  } else if (type_ == "point relaxation stand-alone") {
342  paramList.set("relaxation: zero starting solution", InitialGuessIsZero);
343  supportInitialGuess = true;
344  }
345 
346  SetPrecParameters(paramList);
347 
348  // Apply
349  if (InitialGuessIsZero || supportInitialGuess) {
352 
353  prec_->ApplyInverse(epB, epX);
354 
355  } else {
356  RCP<MultiVector> Residual = Utilities::Residual(*A_, X, B);
357  RCP<MultiVector> Correction = MultiVectorFactory::Build(A_->getDomainMap(), X.getNumVectors());
358 
360  const Epetra_MultiVector& epB = Utilities::MV2EpetraMV(*Residual);
361 
362  prec_->ApplyInverse(epB, epX);
363 
364  X.update(1.0, *Correction, 1.0);
365  }
366 }
367 
368 template <class Node>
370  RCP<IfpackSmoother<Node> > smoother = rcp(new IfpackSmoother<Node>(*this));
371  smoother->SetParameterList(this->GetParameterList());
372  return Teuchos::rcp_dynamic_cast<MueLu::SmootherPrototype<double, int, int, Node> >(smoother);
373 }
374 
375 template <class Node>
377  std::ostringstream out;
378  // The check "GetVerbLevel() == Test" is to avoid
379  // failures in the EasyInterface test.
380  if (prec_ == Teuchos::null || this->GetVerbLevel() == InterfaceTest) {
382  out << "{type = " << type_ << "}";
383  } else {
384  out << prec_->Label();
385  }
386  return out.str();
387 }
388 
389 template <class Node>
392 
393  if (verbLevel & Parameters0)
394  out0 << "Prec. type: " << type_ << std::endl;
395 
396  if (verbLevel & Parameters1) {
397  out0 << "Parameter list: " << std::endl;
398  Teuchos::OSTab tab2(out);
399  out << this->GetParameterList();
400  out0 << "Overlap: " << overlap_ << std::endl;
401  }
402 
403  if (verbLevel & External)
404  if (prec_ != Teuchos::null) {
405  Teuchos::OSTab tab2(out);
406  out << *prec_ << std::endl;
407  }
408 
409  if (verbLevel & Debug) {
410  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl
411  << "-" << std::endl
412  << "RCP<A_>: " << A_ << std::endl
413  << "RCP<prec_>: " << prec_ << std::endl;
414  }
415 }
416 
417 template <class Node>
419  // FIXME: This is a placeholder
421 }
422 
423 } // namespace MueLu
424 
425 // The IfpackSmoother is only templated on the Node, since it is an Epetra only object
426 // Therefore we do not need the full ETI instantiations as we do for the other MueLu
427 // objects which are instantiated on all template parameters.
428 #if defined(HAVE_MUELU_EPETRA)
430 #endif
431 
432 #endif
void Setup(Level &currentLevel)
Set up the smoother.
Important warning messages (one line)
RCP< SmootherPrototype > Copy() const
void SetPrecParameters(const Teuchos::ParameterList &list=Teuchos::ParameterList()) const
KOKKOS_INLINE_FUNCTION LO GetNumAggregates() const
Print external lib objects.
T & get(const std::string &name, T def_value)
ParameterList & set(std::string const &name, T const &value, std::string const &docString="", RCP< const ParameterEntryValidator > const &validator=null)
static RCP< Epetra_CrsMatrix > Op2NonConstEpetraCrs(RCP< Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node >> Op)
Timer to be used in factories. Similar to Monitor but with additional timers.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Print more statistics.
T * getRawPtr() const
Print additional debugging information.
LocalOrdinal LO
One-liner description of what is happening.
size_type size() const
Ifpack_Preconditioner * Create(const std::string PrecType, Epetra_RowMatrix *Matrix, const int overlap=0, bool overrideSerialDefault=false)
IfpackSmoother(std::string const &type, Teuchos::ParameterList const &paramList=Teuchos::ParameterList(), LO const &overlap=0)
Constructor.
void print(Teuchos::FancyOStream &out, const VerbLevel verbLevel=Default) const
Print the object with some verbosity level to an FancyOStream object.
void resize(const size_type n, const T &val=T())
bool isParameter(const std::string &name) const
Print statistics that do not involve significant additional computation.
bool remove(std::string const &name, bool throwIfNotExists=true)
static RCP< MultiVector > Residual(const Xpetra::Operator< Scalar, LocalOrdinal, GlobalOrdinal, Node > &Op, const MultiVector &X, const MultiVector &RHS)
virtual void SetParameterList(const Teuchos::ParameterList &paramList)
Set parameters from a parameter list and return with default values.
void DeclareInput(Level &currentLevel) const
Input.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
static RCP< Epetra_MultiVector > MV2NonConstEpetraMV(RCP< Xpetra::MultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node >> vec)
void declareConstructionOutcome(bool fail, std::string msg)
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
bool IsSetup() const
Get the state of a smoother prototype.
size_t getNodeSmootherComplexity() const
Get a rough estimate of cost per iteration.
const RCP< LOMultiVector > & GetVertex2AggId() const
Returns constant vector that maps local node IDs to local aggregates IDs.
virtual double GetLambdaMax()
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
ParameterList & setParameters(const ParameterList &source)
void SetParameterList(const Teuchos::ParameterList &paramList)
Set parameters from a parameter list and return with default values.
Print class parameters.
std::string description() const
Return a simple one-line description of this object.
void SetupAggregate(Level &currentLevel)
static RCP< const Epetra_MultiVector > MV2EpetraMV(RCP< Xpetra::MultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node >> const vec)
Helper utility to pull out the underlying Epetra objects from an Xpetra object.
virtual const RCP< const FactoryBase > GetFactory(const std::string &varName) const =0
Print class parameters (more parameters, more verbose)
Exception throws to report errors in the internal logical of the program.
void Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero=false) const
Apply the preconditioner.
virtual std::string description() const
Return a simple one-line description of this object.
Class that encapsulates Ifpack smoothers.
std::string toString(const T &t)