MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_IndefBlockedDiagonalSmoother_def.hpp
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 /*
47  * MueLu_IndefBlockedDiagonalSmoother_def.hpp
48  *
49  * Created on: 13 May 2014
50  * Author: wiesner
51  */
52 
53 #ifndef MUELU_INDEFBLOCKEDDIAGONALSMOOTHER_DEF_HPP_
54 #define MUELU_INDEFBLOCKEDDIAGONALSMOOTHER_DEF_HPP_
55 
56 #include "Teuchos_ArrayViewDecl.hpp"
57 #include "Teuchos_ScalarTraits.hpp"
58 
59 #include "MueLu_ConfigDefs.hpp"
60 
61 #include <Xpetra_Matrix.hpp>
62 #include <Xpetra_CrsMatrixWrap.hpp>
64 #include <Xpetra_MultiVectorFactory.hpp>
65 #include <Xpetra_VectorFactory.hpp>
67 
69 #include "MueLu_Level.hpp"
70 #include "MueLu_Monitor.hpp"
71 #include "MueLu_HierarchyUtils.hpp"
72 #include "MueLu_SmootherBase.hpp"
73 
74 // include files for default FactoryManager
75 #include "MueLu_SchurComplementFactory.hpp"
76 #include "MueLu_FactoryManager.hpp"
77 
78 namespace MueLu {
79 
80 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
82  : type_("IndefiniteBlockDiagonalSmoother")
83  , A_(Teuchos::null) {
84 }
85 
86 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
88 
89 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
91  RCP<ParameterList> validParamList = rcp(new ParameterList());
92 
93  validParamList->set<RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A (must be a 2x2 block matrix)");
94  validParamList->set<Scalar>("Damping factor", 1.0, "Damping/Scaling factor");
95  validParamList->set<LocalOrdinal>("Sweeps", 1, "Number of SIMPLE sweeps (default = 1)");
96  // validParamList->set< bool > ("UseSIMPLEC", false, "Use SIMPLEC instead of SIMPLE (default = false)");
97 
98  return validParamList;
99 }
100 
102 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
104  TEUCHOS_TEST_FOR_EXCEPTION(pos < 0, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::AddFactoryManager: parameter \'pos\' must not be negative! error.");
105 
106  size_t myPos = Teuchos::as<size_t>(pos);
107 
108  if (myPos < FactManager_.size()) {
109  // replace existing entris in FactManager_ vector
110  FactManager_.at(myPos) = FactManager;
111  } else if (myPos == FactManager_.size()) {
112  // add new Factory manager in the end of the vector
113  FactManager_.push_back(FactManager);
114  } else { // if(myPos > FactManager_.size())
115  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
116  *out << "Warning: cannot add new FactoryManager at proper position " << pos << ". The FactoryManager is just appended to the end. Check this!" << std::endl;
117 
118  // add new Factory manager in the end of the vector
119  FactManager_.push_back(FactManager);
120  }
121 }
122 
123 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
125  currentLevel.DeclareInput("A", this->GetFactory("A").get());
126 
127  TEUCHOS_TEST_FOR_EXCEPTION(FactManager_.size() != 2, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::DeclareInput: You have to declare two FactoryManagers with a \"Smoother\" object: One for predicting the primary variable and one for the SchurComplement system. The smoother for the SchurComplement system needs a SchurComplementFactory as input for variable \"A\"!");
128 
129  // loop over all factory managers for the subblocks of blocked operator A
130  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
131  for (it = FactManager_.begin(); it != FactManager_.end(); ++it) {
132  SetFactoryManager currentSFM(rcpFromRef(currentLevel), *it);
133 
134  // request "Smoother" for current subblock row.
135  currentLevel.DeclareInput("PreSmoother", (*it)->GetFactory("Smoother").get());
136  }
137 }
138 
139 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
141  FactoryMonitor m(*this, "Setup for indefinite blocked diagonal smoother", currentLevel);
142 
143  if (SmootherPrototype::IsSetup() == true)
144  this->GetOStream(Warnings0) << "MueLu::IndefBlockedDiagonalSmoother::Setup(): Setup() has already been called";
145 
146  // extract blocked operator A from current level
147  A_ = Factory::Get<RCP<Matrix> >(currentLevel, "A");
148 
149  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
150  TEUCHOS_TEST_FOR_EXCEPTION(bA == Teuchos::null, Exceptions::BadCast, "MueLu::IndefBlockedDiagonalSmoother::Setup: input matrix A is not of type BlockedCrsMatrix! error.");
151 
152  // store map extractors
153  rangeMapExtractor_ = bA->getRangeMapExtractor();
154  domainMapExtractor_ = bA->getDomainMapExtractor();
155 
156  // Store the blocks in local member variables
157  Teuchos::RCP<Matrix> A00 = bA->getMatrix(0, 0);
158  Teuchos::RCP<Matrix> A01 = bA->getMatrix(0, 1);
159  Teuchos::RCP<Matrix> A10 = bA->getMatrix(1, 0);
160  Teuchos::RCP<Matrix> A11 = bA->getMatrix(1, 1);
161 
162  F_ = A00;
163  Z_ = A11;
164 
165  /*const ParameterList & pL = Factory::GetParameterList();
166  bool bSIMPLEC = pL.get<bool>("UseSIMPLEC");
167 
168  // Create the inverse of the diagonal of F
169  RCP<Vector> diagFVector = VectorFactory::Build(F_->getRowMap());
170  if(!bSIMPLEC) {
171  F_->getLocalDiagCopy(*diagFVector); // extract diagonal of F
172  diagFVector->reciprocal(*diagFVector); // build reciprocal
173  } else {
174  const RCP<const Map> rowmap = F_->getRowMap();
175  size_t locSize = rowmap->getLocalNumElements();
176  Teuchos::ArrayRCP<SC> diag = diagFVector->getDataNonConst(0);
177  Teuchos::ArrayView<const LO> cols;
178  Teuchos::ArrayView<const SC> vals;
179  for (size_t i=0; i<locSize; ++i) { // loop over rows
180  F_->getLocalRowView(i,cols,vals);
181  Scalar absRowSum = Teuchos::ScalarTraits<Scalar>::zero();
182  for (LO j=0; j<cols.size(); ++j) { // loop over cols
183  absRowSum += Teuchos::ScalarTraits<Scalar>::magnitude(vals[j]);
184  }
185  diag[i] = absRowSum;
186  }
187  diagFVector->reciprocal(*diagFVector); // build reciprocal
188  }
189  diagFinv_ = diagFVector;*/
190 
191  // Set the Smoother
192  // carefully switch to the SubFactoryManagers (defined by the users)
193  {
194  RCP<const FactoryManagerBase> velpredictFactManager = FactManager_.at(0);
195  SetFactoryManager currentSFM(rcpFromRef(currentLevel), velpredictFactManager);
196  velPredictSmoo_ = currentLevel.Get<RCP<SmootherBase> >("PreSmoother", velpredictFactManager->GetFactory("Smoother").get());
197  }
198  {
199  RCP<const FactoryManagerBase> schurFactManager = FactManager_.at(1);
200  SetFactoryManager currentSFM(rcpFromRef(currentLevel), schurFactManager);
201  schurCompSmoo_ = currentLevel.Get<RCP<SmootherBase> >("PreSmoother", schurFactManager->GetFactory("Smoother").get());
202  }
204 }
205 
206 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
207 void IndefBlockedDiagonalSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector &X, const MultiVector &B, bool /* InitialGuessIsZero */) const {
208  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::Apply(): Setup() has not been called");
209 
210  Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::getFancyOStream(Teuchos::rcpFromRef(std::cout));
211 
213 
214  // extract parameters from internal parameter list
216  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
217  Scalar omega = pL.get<Scalar>("Damping factor");
218 
219  bool bRangeThyraMode = rangeMapExtractor_->getThyraMode();
220  bool bDomainThyraMode = domainMapExtractor_->getThyraMode();
221 
222  // wrap current solution vector in RCP
223  RCP<MultiVector> rcpX = Teuchos::rcpFromRef(X);
224  RCP<const MultiVector> rcpB = Teuchos::rcpFromRef(B);
225 
226  // make sure that both rcpX and rcpB are BlockedMultiVector objects
227  bool bCopyResultX = false;
228  bool bReorderX = false;
229  bool bReorderB = false;
230  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
231  MUELU_TEST_FOR_EXCEPTION(bA.is_null() == true, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): A_ must be a BlockedCrsMatrix");
232  RCP<BlockedMultiVector> bX = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(rcpX);
233  RCP<const BlockedMultiVector> bB = Teuchos::rcp_dynamic_cast<const BlockedMultiVector>(rcpB);
234 
235  // check the type of operator
238 
239  if (rbA.is_null() == false) {
240  // A is a ReorderedBlockedCrsMatrix and thus uses nested maps, retrieve BlockedCrsMatrix and use plain blocked
241  // map for the construction of the blocked multivectors
242 
243  // check type of X vector
244  if (bX.is_null() == true) {
245  RCP<MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(rbA->getBlockedCrsMatrix()->getBlockedDomainMap(), rcpX));
246  rcpX.swap(vectorWithBlockedMap);
247  bCopyResultX = true;
248  bReorderX = true;
249  }
250 
251  // check type of B vector
252  if (bB.is_null() == true) {
253  RCP<const MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(rbA->getBlockedCrsMatrix()->getBlockedRangeMap(), rcpB));
254  rcpB.swap(vectorWithBlockedMap);
255  bReorderB = true;
256  }
257  } else {
258  // A is a BlockedCrsMatrix and uses a plain blocked map
259  if (bX.is_null() == true) {
260  RCP<MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(bA->getBlockedDomainMap(), rcpX));
261  rcpX.swap(vectorWithBlockedMap);
262  bCopyResultX = true;
263  }
264 
265  if (bB.is_null() == true) {
266  RCP<const MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(bA->getBlockedRangeMap(), rcpB));
267  rcpB.swap(vectorWithBlockedMap);
268  }
269  }
270 
271  // we now can guarantee that X and B are blocked multi vectors
272  bX = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(rcpX);
273  bB = Teuchos::rcp_dynamic_cast<const BlockedMultiVector>(rcpB);
274 
275  // Finally we can do a reordering of the blocked multivectors if A is a ReorderedBlockedCrsMatrix
276  if (rbA.is_null() == false) {
277  Teuchos::RCP<const Xpetra::BlockReorderManager> brm = rbA->getBlockReorderManager();
278 
279  // check type of X vector
280  if (bX->getBlockedMap()->getNumMaps() != bA->getDomainMapExtractor()->NumMaps() || bReorderX) {
281  // X is a blocked multi vector but incompatible to the reordered blocked operator A
282  Teuchos::RCP<MultiVector> reorderedBlockedVector = buildReorderedBlockedMultiVector(brm, bX);
283  rcpX.swap(reorderedBlockedVector);
284  }
285 
286  if (bB->getBlockedMap()->getNumMaps() != bA->getRangeMapExtractor()->NumMaps() || bReorderB) {
287  // B is a blocked multi vector but incompatible to the reordered blocked operator A
288  Teuchos::RCP<const MultiVector> reorderedBlockedVector = buildReorderedBlockedMultiVector(brm, bB);
289  rcpB.swap(reorderedBlockedVector);
290  }
291  }
292 
293  // Throughout the rest of the algorithm rcpX and rcpB are used for solution vector and RHS
294 
295  // create residual vector
296  // contains current residual of current solution X with rhs B
297  RCP<MultiVector> residual = MultiVectorFactory::Build(rcpB->getMap(), rcpB->getNumVectors());
298  RCP<BlockedMultiVector> bresidual = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(residual);
299  Teuchos::RCP<MultiVector> r1 = bresidual->getMultiVector(0, bRangeThyraMode);
300  Teuchos::RCP<MultiVector> r2 = bresidual->getMultiVector(1, bRangeThyraMode);
301 
302  // helper vector 1
303  RCP<MultiVector> xtilde = MultiVectorFactory::Build(rcpX->getMap(), rcpX->getNumVectors());
304  RCP<BlockedMultiVector> bxtilde = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(xtilde);
305  RCP<MultiVector> xtilde1 = bxtilde->getMultiVector(0, bDomainThyraMode);
306  RCP<MultiVector> xtilde2 = bxtilde->getMultiVector(1, bDomainThyraMode);
307 
308  // incrementally improve solution vector X
309  for (LocalOrdinal run = 0; run < nSweeps; ++run) {
310  // 1) calculate current residual
311  residual->update(one, *rcpB, zero); // residual = B
312  A_->apply(*rcpX, *residual, Teuchos::NO_TRANS, -one, one);
313 
314  // split residual vector
315  // Teuchos::RCP<MultiVector> r1 = rangeMapExtractor_->ExtractVector(residual, 0, bRangeThyraMode);
316  // Teuchos::RCP<MultiVector> r2 = rangeMapExtractor_->ExtractVector(residual, 1, bRangeThyraMode);
317 
318  // 2) solve F * \Delta \tilde{x}_1 = r_1
319  // start with zero guess \Delta \tilde{x}_1
320  // RCP<MultiVector> xtilde1 = MultiVectorFactory::Build(r1->getMap(),rcpX->getNumVectors(),true);
321  // RCP<MultiVector> xtilde2 = MultiVectorFactory::Build(r2->getMap(),rcpX->getNumVectors(),true);
322  bxtilde->putScalar(zero);
323  velPredictSmoo_->Apply(*xtilde1, *r1);
324 
325  // 3) solve SchurComp equation
326  // start with zero guess \Delta \tilde{x}_2
327  schurCompSmoo_->Apply(*xtilde2, *r2);
328 #if 1
329  // 4) update solution vector
330  rcpX->update(omega, *bxtilde, one);
331 #else
332  Teuchos::RCP<MultiVector> x1 = domainMapExtractor_->ExtractVector(rcpX, 0, bDomainThyraMode);
333  Teuchos::RCP<MultiVector> x2 = domainMapExtractor_->ExtractVector(rcpX, 1, bDomainThyraMode);
334 
335  // 5) update solution vector with increments xhat1 and xhat2
336  // rescale increment for x2 with omega_
337  x1->update(omega, *xtilde1, one); // x1 = x1_old + omega xtilde1
338  x2->update(omega, *xtilde2, one); // x2 = x2_old + omega xtilde2
339 
340  // write back solution in global vector X
341  domainMapExtractor_->InsertVector(x1, 0, rcpX, bDomainThyraMode);
342  domainMapExtractor_->InsertVector(x2, 1, rcpX, bDomainThyraMode);
343 #endif
344  }
345 
346  if (bCopyResultX == true) {
347  RCP<MultiVector> Xmerged = bX->Merge();
348  X.update(one, *Xmerged, zero);
349  }
350 }
351 
352 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
355  return rcp(new IndefBlockedDiagonalSmoother(*this));
356 }
357 
358 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
360  std::ostringstream out;
362  out << "{type = " << type_ << "}";
363  return out.str();
364 }
365 
366 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
369 
370  if (verbLevel & Parameters0) {
371  out0 << "Prec. type: " << type_ << /*" Sweeps: " << nSweeps_ << " damping: " << omega_ <<*/ std::endl;
372  }
373 
374  if (verbLevel & Debug) {
375  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl;
376  }
377 }
378 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
380  // FIXME: This is a placeholder
382 }
383 
384 } // namespace MueLu
385 
386 #endif /* MUELU_INDEFBLOCKEDDIAGONALSMOOTHER_DEF_HPP_ */
Important warning messages (one line)
virtual const Teuchos::ParameterList & GetParameterList() const
Exception indicating invalid cast attempted.
std::string description() const
Return a simple one-line description of this object.
MueLu::DefaultLocalOrdinal LocalOrdinal
void Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero=false) const
Apply the Braess Sarazin smoother.
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)
Timer to be used in factories. Similar to Monitor but with additional timers.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
void swap(RCP< T > &r_ptr)
Print additional debugging information.
void print(Teuchos::FancyOStream &out, const VerbLevel verbLevel=Default) const
Print the object with some verbosity level to an FancyOStream object.
void DeclareInput(Level &currentLevel) const
Input.
virtual const RCP< const FactoryBase > GetFactory(const std::string &varName) const =0
Get.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
MueLu::DefaultScalar Scalar
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Cheap Blocked diagonal smoother for indefinite 2x2 block matrices.
RCP< const ParameterList > GetValidParameterList() const
Input.
bool IsSetup() const
Get the state of a smoother prototype.
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
Print class parameters.
size_t getNodeSmootherComplexity() const
Get a rough estimate of cost per iteration.
Scalar SC
void AddFactoryManager(RCP< const FactoryManagerBase > FactManager, int pos=0)
Add a factory manager for BraessSarazin internal SchurComplement handling.
void residual(const Operator< SC, LO, GO, NO > &Aop, const MultiVector< SC, LO, GO, NO > &X_in, const MultiVector< SC, LO, GO, NO > &B_in, MultiVector< SC, LO, GO, NO > &R_in)
Exception throws to report errors in the internal logical of the program.
#define MUELU_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
An exception safe way to call the method &#39;Level::SetFactoryManager()&#39;.
Teuchos::RCP< const Xpetra::MultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node > > buildReorderedBlockedMultiVector(Teuchos::RCP< const Xpetra::BlockReorderManager > brm, Teuchos::RCP< const Xpetra::BlockedMultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node > > bvec)
void DeclareInput(const std::string &ename, const FactoryBase *factory, const FactoryBase *requestedBy=NoFactory::get())
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput()
virtual std::string description() const
Return a simple one-line description of this object.
std::string toString(const T &t)
bool is_null() const