MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_BlockedGaussSeidelSmoother_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 #ifndef MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_DEF_HPP_
48 #define MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_DEF_HPP_
49 
50 #include "Teuchos_ArrayViewDecl.hpp"
51 #include "Teuchos_ScalarTraits.hpp"
52 
53 #include "MueLu_ConfigDefs.hpp"
54 
56 #include <Xpetra_Matrix.hpp>
60 #include <Xpetra_MultiVectorFactory.hpp>
61 
63 #include "MueLu_Level.hpp"
64 #include "MueLu_Monitor.hpp"
65 #include "MueLu_HierarchyUtils.hpp"
66 #include "MueLu_SmootherBase.hpp"
67 
68 namespace MueLu {
69 
70 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
72  : type_("blocked GaussSeidel")
73  , A_(Teuchos::null) {
74  FactManager_.reserve(10); // TODO fix me!
75 }
76 
77 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
79 
80 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
82  RCP<ParameterList> validParamList = rcp(new ParameterList());
83 
84  validParamList->set<RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A");
85  validParamList->set<Scalar>("Damping factor", 1.0, "Damping/Scaling factor in BGS");
86  validParamList->set<LocalOrdinal>("Sweeps", 1, "Number of BGS sweeps (default = 1)");
87 
88  return validParamList;
89 }
90 
91 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
93  TEUCHOS_TEST_FOR_EXCEPTION(pos < 0, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::AddFactoryManager: parameter \'pos\' must not be negative! error.");
94 
95  size_t myPos = Teuchos::as<size_t>(pos);
96 
97  if (myPos < FactManager_.size()) {
98  // replace existing entries in FactManager_ vector
99  FactManager_.at(myPos) = FactManager;
100  } else if (myPos == FactManager_.size()) {
101  // append new Factory manager at the end of the vector
102  FactManager_.push_back(FactManager);
103  } else { // if(myPos > FactManager_.size())
104  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
105  *out << "Warning: cannot add new FactoryManager at proper position " << pos << ". The FactoryManager is just appended to the end. Check this!" << std::endl;
106 
107  // add new Factory manager in the end of the vector
108  FactManager_.push_back(FactManager);
109  }
110 }
111 
112 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
114  // this->Input(currentLevel, "A");
115  // TODO: check me: why is this->Input not freeing properly A in release mode?
116  currentLevel.DeclareInput("A", this->GetFactory("A").get());
117 
118  // loop over all factory managers for the subblocks of blocked operator A
119  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
120  for (it = FactManager_.begin(); it != FactManager_.end(); ++it) {
121  SetFactoryManager currentSFM(rcpFromRef(currentLevel), *it);
122 
123  // request "Smoother" for current subblock row.
124  currentLevel.DeclareInput("PreSmoother", (*it)->GetFactory("Smoother").get());
125 
126  // request "A" for current subblock row (only needed for Thyra mode)
127  currentLevel.DeclareInput("A", (*it)->GetFactory("A").get());
128  }
129 }
130 
131 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
133  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
134 
135  FactoryMonitor m(*this, "Setup blocked Gauss-Seidel Smoother", currentLevel);
136  if (SmootherPrototype::IsSetup() == true) this->GetOStream(Warnings0) << "MueLu::BlockedGaussSeidelSmoother::Setup(): Setup() has already been called";
137 
138  // extract blocked operator A from current level
139  A_ = Factory::Get<RCP<Matrix> >(currentLevel, "A"); // A needed for extracting map extractors
140  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
141  TEUCHOS_TEST_FOR_EXCEPTION(bA == Teuchos::null, Exceptions::BadCast, "MueLu::BlockedPFactory::Build: input matrix A is not of type BlockedCrsMatrix! error.");
142 
143  // plausibility check
144  TEUCHOS_TEST_FOR_EXCEPTION(bA->Rows() != FactManager_.size(), Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Setup: number of block rows of A is " << bA->Rows() << " and does not match number of SubFactoryManagers " << FactManager_.size() << ". error.");
145  TEUCHOS_TEST_FOR_EXCEPTION(bA->Cols() != FactManager_.size(), Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Setup: number of block cols of A is " << bA->Cols() << " and does not match number of SubFactoryManagers " << FactManager_.size() << ". error.");
146 
147  // store map extractors
148  rangeMapExtractor_ = bA->getRangeMapExtractor();
149  domainMapExtractor_ = bA->getDomainMapExtractor();
150 
151  // loop over all factory managers for the subblocks of blocked operator A
152  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
153  for (it = FactManager_.begin(); it != FactManager_.end(); ++it) {
154  SetFactoryManager currentSFM(rcpFromRef(currentLevel), *it);
155 
156  // extract Smoother for current block row (BGS ordering)
157  RCP<const SmootherBase> Smoo = currentLevel.Get<RCP<SmootherBase> >("PreSmoother", (*it)->GetFactory("Smoother").get());
158  Inverse_.push_back(Smoo);
159 
160  // store whether subblock matrix is blocked or not!
161  RCP<Matrix> Aii = currentLevel.Get<RCP<Matrix> >("A", (*it)->GetFactory("A").get());
162  bIsBlockedOperator_.push_back(Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(Aii) != Teuchos::null);
163  }
164 
166 }
167 
168 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
169 void BlockedGaussSeidelSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero) const {
170  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): Setup() has not been called");
171 
172 #if 0 // def HAVE_MUELU_DEBUG
173  // TODO simplify this debug check
174  RCP<MultiVector> rcpDebugX = Teuchos::rcpFromRef(X);
175  RCP<const MultiVector> rcpDebugB = Teuchos::rcpFromRef(B);
176  RCP<BlockedMultiVector> rcpBDebugX = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(rcpDebugX);
177  RCP<const BlockedMultiVector> rcpBDebugB = Teuchos::rcp_dynamic_cast<const BlockedMultiVector>(rcpDebugB);
178  //RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
179  if(rcpBDebugB.is_null() == false) {
180  //this->GetOStream(Runtime1) << "BlockedGaussSeidel: B is a BlockedMultiVector of size " << B.getMap()->getGlobalNumElements() << " with " << rcpBDebugB->getBlockedMap()->getNumMaps() << " blocks." << std::endl;
181  //TEUCHOS_TEST_FOR_EXCEPTION(A_->getRangeMap()->isSameAs(*(B.getMap())) == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): The map of RHS vector B is not the same as range map of the blocked operator A. Please check the map of B and A.");
182  } else {
183  //this->GetOStream(Runtime1) << "BlockedGaussSeidel: B is a MultiVector of size " << B.getMap()->getGlobalNumElements() << std::endl;
184  //TEUCHOS_TEST_FOR_EXCEPTION(bA->getFullRangeMap()->isSameAs(*(B.getMap())) == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): The map of RHS vector B is not the same as range map of the blocked operator A. Please check the map of B and A.");
185  }
186  if(rcpBDebugX.is_null() == false) {
187  //this->GetOStream(Runtime1) << "BlockedGaussSeidel: X is a BlockedMultiVector of size " << X.getMap()->getGlobalNumElements() << " with " << rcpBDebugX->getBlockedMap()->getNumMaps() << " blocks." << std::endl;
188  //TEUCHOS_TEST_FOR_EXCEPTION(A_->getDomainMap()->isSameAs(*(X.getMap())) == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): The map of the solution vector X is not the same as domain map of the blocked operator A. Please check the map of X and A.");
189  } else {
190  //this->GetOStream(Runtime1) << "BlockedGaussSeidel: X is a MultiVector of size " << X.getMap()->getGlobalNumElements() << std::endl;
191  //TEUCHOS_TEST_FOR_EXCEPTION(bA->getFullDomainMap()->isSameAs(*(X.getMap())) == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): The map of the solution vector X is not the same as domain map of the blocked operator A. Please check the map of X and A.");
192  }
193 #endif
195 
196  // Input variables used for the rest of the algorithm
197  RCP<MultiVector> rcpX = Teuchos::rcpFromRef(X);
198  RCP<const MultiVector> rcpB = Teuchos::rcpFromRef(B);
199 
200  // make sure that both rcpX and rcpB are BlockedMultiVector objects
201  bool bCopyResultX = false;
202  bool bReorderX = false;
203  bool bReorderB = false;
204  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
205  MUELU_TEST_FOR_EXCEPTION(bA.is_null() == true, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): A_ must be a BlockedCrsMatrix");
206  RCP<BlockedMultiVector> bX = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(rcpX);
207  RCP<const BlockedMultiVector> bB = Teuchos::rcp_dynamic_cast<const BlockedMultiVector>(rcpB);
208 
209  // check the type of operator
212 
213  if (rbA.is_null() == false) {
214  // A is a ReorderedBlockedCrsMatrix and thus uses nested maps, retrieve BlockedCrsMatrix and use plain blocked
215  // map for the construction of the blocked multivectors
216 
217  // check type of X vector
218  if (bX.is_null() == true) {
219  RCP<MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(rbA->getBlockedCrsMatrix()->getBlockedDomainMap(), rcpX));
220  rcpX.swap(vectorWithBlockedMap);
221  bCopyResultX = true;
222  bReorderX = true;
223  }
224 
225  // check type of B vector
226  if (bB.is_null() == true) {
227  RCP<const MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(rbA->getBlockedCrsMatrix()->getBlockedRangeMap(), rcpB));
228  rcpB.swap(vectorWithBlockedMap);
229  bReorderB = true;
230  }
231  } else {
232  // A is a BlockedCrsMatrix and uses a plain blocked map
233  if (bX.is_null() == true) {
234  RCP<MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(bA->getBlockedDomainMap(), rcpX));
235  rcpX.swap(vectorWithBlockedMap);
236  bCopyResultX = true;
237  }
238 
239  if (bB.is_null() == true) {
240  RCP<const MultiVector> vectorWithBlockedMap = Teuchos::rcp(new BlockedMultiVector(bA->getBlockedRangeMap(), rcpB));
241  rcpB.swap(vectorWithBlockedMap);
242  }
243  }
244 
245  // we now can guarantee that X and B are blocked multi vectors
246  bX = Teuchos::rcp_dynamic_cast<BlockedMultiVector>(rcpX);
247  bB = Teuchos::rcp_dynamic_cast<const BlockedMultiVector>(rcpB);
248 
249  // Finally we can do a reordering of the blocked multivectors if A is a ReorderedBlockedCrsMatrix
250  if (rbA.is_null() == false) {
251  Teuchos::RCP<const Xpetra::BlockReorderManager> brm = rbA->getBlockReorderManager();
252 
253  // check type of X vector
254  if (bX->getBlockedMap()->getNumMaps() != bA->getDomainMapExtractor()->NumMaps() || bReorderX) {
255  // X is a blocked multi vector but incompatible to the reordered blocked operator A
256  Teuchos::RCP<MultiVector> reorderedBlockedVector = buildReorderedBlockedMultiVector(brm, bX);
257  rcpX.swap(reorderedBlockedVector);
258  }
259 
260  if (bB->getBlockedMap()->getNumMaps() != bA->getRangeMapExtractor()->NumMaps() || bReorderB) {
261  // B is a blocked multi vector but incompatible to the reordered blocked operator A
262  Teuchos::RCP<const MultiVector> reorderedBlockedVector = buildReorderedBlockedMultiVector(brm, bB);
263  rcpB.swap(reorderedBlockedVector);
264  }
265  }
266 
267  // Throughout the rest of the algorithm rcpX and rcpB are used for solution vector and RHS
268 
269  RCP<MultiVector> residual = MultiVectorFactory::Build(rcpB->getMap(), rcpB->getNumVectors());
270  RCP<MultiVector> tempres = MultiVectorFactory::Build(rcpB->getMap(), rcpB->getNumVectors());
271 
272  // extract parameters from internal parameter list
274  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
275  Scalar omega = pL.get<Scalar>("Damping factor");
276 
277  // Clear solution from previos V cycles in case it is still stored
278  if (InitialGuessIsZero == true)
279  rcpX->putScalar(Teuchos::ScalarTraits<Scalar>::zero());
280 
281  // outer Richardson loop
282  for (LocalOrdinal run = 0; run < nSweeps; ++run) {
283  // one BGS sweep
284  // loop over all block rows
285  for (size_t i = 0; i < Inverse_.size(); i++) {
286  // calculate block residual r = B-A*X
287  // note: A_ is the full blocked operator
288  residual->update(1.0, *rcpB, 0.0); // r = B
289  if (InitialGuessIsZero == false || i > 0 || run > 0)
290  bA->bgs_apply(*rcpX, *residual, i, Teuchos::NO_TRANS, -1.0, 1.0);
291 
292  // extract corresponding subvectors from X and residual
293  bool bRangeThyraMode = rangeMapExtractor_->getThyraMode();
294  bool bDomainThyraMode = domainMapExtractor_->getThyraMode();
295  Teuchos::RCP<MultiVector> Xi = domainMapExtractor_->ExtractVector(rcpX, i, bDomainThyraMode);
296  Teuchos::RCP<MultiVector> ri = rangeMapExtractor_->ExtractVector(residual, i, bRangeThyraMode);
297  Teuchos::RCP<MultiVector> tXi = domainMapExtractor_->getVector(i, X.getNumVectors(), bDomainThyraMode);
298 
299  // apply solver/smoother
300  Inverse_.at(i)->Apply(*tXi, *ri, false);
301 
302  // update vector
303  Xi->update(omega, *tXi, 1.0); // X_{i+1} = X_i + omega \Delta X_i
304  }
305  }
306 
307  if (bCopyResultX == true) {
308  RCP<MultiVector> Xmerged = bX->Merge();
309  X.update(one, *Xmerged, zero);
310  }
311 }
312 
313 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
315  return rcp(new BlockedGaussSeidelSmoother(*this));
316 }
317 
318 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
320  std::ostringstream out;
322  out << "{type = " << type_ << "}";
323  return out.str();
324 }
325 
326 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
329 
330  // extract parameters from internal parameter list
332  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
333  Scalar omega = pL.get<Scalar>("Damping factor");
334 
335  if (verbLevel & Parameters0) {
336  out0 << "Prec. type: " << type_ << " Sweeps: " << nSweeps << " damping: " << omega << std::endl;
337  }
338 
339  if (verbLevel & Debug) {
340  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl;
341  }
342 }
343 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
345  // FIXME: This is a placeholder
347 }
348 
349 } // namespace MueLu
350 
351 #endif /* MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_DEF_HPP_ */
Important warning messages (one line)
virtual const Teuchos::ParameterList & GetParameterList() const
Exception indicating invalid cast attempted.
MueLu::DefaultLocalOrdinal LocalOrdinal
T & get(const std::string &name, T def_value)
size_t getNodeSmootherComplexity() const
Get a rough estimate of cost per iteration.
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)
block Gauss-Seidel method for blocked matrices
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 verbLevel to an FancyOStream object out.
std::string description() const
Return a simple one-line description of this object.
void DeclareInput(Level &currentLevel) const
Input.
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
void Setup(Level &currentLevel)
Setup routine In the Setup method the Inverse_ vector is filled with the corresponding SmootherBase o...
bool IsSetup() const
Get the state of a smoother prototype.
std::vector< Teuchos::RCP< const FactoryManagerBase > > FactManager_
vector of factory managers
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
RCP< const ParameterList > GetValidParameterList() const
Input.
Print class parameters.
Scalar SC
void Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero=false) const
Apply the direct solver. Solves the linear system AX=B using the constructed solver.
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 AddFactoryManager(RCP< const FactoryManagerBase > FactManager, int pos)
Add a factory manager.
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