MueLu  Version of the Day
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  * MueLu_BlockedGaussSeidelSmoother_def.hpp
48  *
49  * Created on: 30.01.2012
50  * Author: tobias
51  */
52 
53 #ifndef MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_DEF_HPP_
54 #define MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_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_BlockedCrsMatrix.hpp>
63 #include <Xpetra_MultiVectorFactory.hpp>
64 
66 #include "MueLu_Level.hpp"
67 #include "MueLu_Utilities.hpp"
68 #include "MueLu_Monitor.hpp"
69 #include "MueLu_HierarchyHelpers.hpp"
70 #include "MueLu_SmootherBase.hpp"
71 
72 namespace MueLu {
73 
74  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
76  : type_("blocked GaussSeidel"), A_(Teuchos::null)
77  {
78  FactManager_.reserve(10);
79  }
80 
81  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
83 
84  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
86  RCP<ParameterList> validParamList = rcp(new ParameterList());
87 
88  validParamList->set< RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A");
89  validParamList->set< Scalar > ("Damping factor", 1.0, "Damping/Scaling factor in BGS");
90  validParamList->set< LocalOrdinal > ("Sweeps", 1, "Number of BGS sweeps (default = 1)");
91 
92  return validParamList;
93  }
94 
95  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
96  void BlockedGaussSeidelSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::AddFactoryManager(RCP<const FactoryManagerBase> FactManager, int pos) {
97  TEUCHOS_TEST_FOR_EXCEPTION(pos < 0, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::AddFactoryManager: parameter \'pos\' must not be negative! error.");
98 
99  size_t myPos = Teuchos::as<size_t>(pos);
100 
101  if (myPos < FactManager_.size()) {
102  // replace existing entris in FactManager_ vector
103  FactManager_.at(myPos) = FactManager;
104  } else if( myPos == FactManager_.size()) {
105  // add new Factory manager in the end of the vector
106  FactManager_.push_back(FactManager);
107  } else { // if(myPos > FactManager_.size())
108  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
109  *out << "Warning: cannot add new FactoryManager at proper position " << pos << ". The FactoryManager is just appended to the end. Check this!" << std::endl;
110 
111  // add new Factory manager in the end of the vector
112  FactManager_.push_back(FactManager);
113  }
114  }
115 
116  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
118  //this->Input(currentLevel, "A");
119  // TODO: check me: why is this->Input not freeing properly A in release mode?
120  currentLevel.DeclareInput("A",this->GetFactory("A").get());
121 
122  // loop over all factory managers for the subblocks of blocked operator A
123  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
124  for(it = FactManager_.begin(); it!=FactManager_.end(); ++it) {
125  SetFactoryManager currentSFM (rcpFromRef(currentLevel), *it);
126 
127  // request "Smoother" for current subblock row.
128  currentLevel.DeclareInput("PreSmoother",(*it)->GetFactory("Smoother").get());
129  }
130 
131  //RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
132  }
133 
134  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
136  //typedef Xpetra::BlockedCrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> BlockedCrsOMatrix;
137 
138  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
139 
140  FactoryMonitor m(*this, "Setup blocked Gauss-Seidel Smoother", currentLevel);
141  if (SmootherPrototype::IsSetup() == true) this->GetOStream(Warnings0) << "MueLu::BlockedGaussSeidelSmoother::Setup(): Setup() has already been called";
142 
143  // extract blocked operator A from current level
144  A_ = Factory::Get< RCP<Matrix> >(currentLevel, "A"); // A needed for extracting map extractors
145  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
146  TEUCHOS_TEST_FOR_EXCEPTION(bA==Teuchos::null, Exceptions::BadCast, "MueLu::BlockedPFactory::Build: input matrix A is not of type BlockedCrsMatrix! error.");
147 
148  // plausibility check
149  TEUCHOS_TEST_FOR_EXCEPTION(bA->Rows() != FactManager_.size(), Exceptions::RuntimeError, "MueLu::BlockedPFactory::Build: number of block rows of A does not match number of SubFactoryManagers. error.");
150  TEUCHOS_TEST_FOR_EXCEPTION(bA->Cols() != FactManager_.size(), Exceptions::RuntimeError, "MueLu::BlockedPFactory::Build: number of block cols of A does not match number of SubFactoryManagers. error.");
151 
152  // store map extractors
153  rangeMapExtractor_ = bA->getRangeMapExtractor();
154  domainMapExtractor_ = bA->getDomainMapExtractor();
155 
156  Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::getFancyOStream(Teuchos::rcpFromRef(std::cout));
157 
158  // loop over all factory managers for the subblocks of blocked operator A
159  size_t bgsOrderingIndex = 0;
160  //std::map<size_t,size_t> bgsOrderingIndex2blockRowIndex;
161  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
162  for(it = FactManager_.begin(); it!=FactManager_.end(); ++it) {
163  SetFactoryManager currentSFM (rcpFromRef(currentLevel), *it);
164 
165  // extract Smoother for current block row (BGS ordering)
166  RCP<const SmootherBase> Smoo = currentLevel.Get< RCP<SmootherBase> >("PreSmoother",(*it)->GetFactory("Smoother").get());
167  Inverse_.push_back(Smoo);
168 
169  // extract i-th diagonal block Aii -> determine block
170  /*currentLevel.print(*out, Teuchos::VERB_EXTREME);
171  std::cout << "BGS: need A from factory " << (*it)->GetFactory("A").get() << std::endl;
172  RCP<Matrix> Aii = currentLevel.Get< RCP<Matrix> >("A",(*it)->GetFactory("A").get());
173  currentLevel.print(*out, Teuchos::VERB_EXTREME);
174  for(size_t i = 0; i<rangeMapExtractor_->NumMaps(); i++) {
175  if(rangeMapExtractor_->getMap(i)->isSameAs(*(Aii->getRangeMap()))) {
176  // map found: i is the true block row index
177  // fill std::map with information bgsOrderingIndex -> i
178  bgsOrderingIndex2blockRowIndex_[bgsOrderingIndex] = i;
179  break;
180  }
181  }*/
182  bgsOrderingIndex2blockRowIndex_[bgsOrderingIndex] = bgsOrderingIndex; // TODO fix me
183 
184  bgsOrderingIndex++;
185  }
186 
188  }
189 
190  // This function is equivalent to the std::map 'at' method introduced in C++11.
191  // TODO: move to Utils
192  template <class StdMapType>
193  const typename StdMapType::mapped_type & at(const StdMapType& map, const typename StdMapType::key_type& x) {
194  typename StdMapType::const_iterator it = map.find(x);
195  TEUCHOS_TEST_FOR_EXCEPTION(it == map.end(), std::out_of_range, "MueLu::at(): element does not exist in the map");
196  return it->second;
197  }
198 
199  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
200  void BlockedGaussSeidelSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector &X, const MultiVector& B, bool InitialGuessIsZero) const
201  {
202  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::BlockedGaussSeidelSmoother::Apply(): Setup() has not been called");
203 
204  RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> > residual = MultiVectorFactory::Build(B.getMap(), B.getNumVectors());
205  RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> > tempres = MultiVectorFactory::Build(B.getMap(), B.getNumVectors());
206  RCP<MultiVector> rcpX = Teuchos::rcpFromRef(X);
207 
208 
209  //Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::getFancyOStream(Teuchos::rcpFromRef(std::cout));
210 
211  // extract parameters from internal parameter list
212  const ParameterList & pL = Factory::GetParameterList();
213  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
214  Scalar omega = pL.get<Scalar>("Damping factor");
215 
216  // outer Richardson loop
217  for (LocalOrdinal run = 0; run < nSweeps; ++run) {
218  // one BGS sweep
219  // loop over all block rows
220  for(size_t i = 0; i<Inverse_.size(); i++) {
221 
222  // calculate block residual r = B-A*X
223  // note: A_ is the full blocked operator
224  residual->update(1.0,B,0.0); // r = B
225  A_->apply(X, *residual, Teuchos::NO_TRANS, -1.0, 1.0);
226 
227  // extract corresponding subvectors from X and residual
228  size_t blockRowIndex = at(bgsOrderingIndex2blockRowIndex_, i); // == bgsOrderingIndex2blockRowIndex_.at(i) (only available since C++11)
229  Teuchos::RCP<MultiVector> Xi = domainMapExtractor_->ExtractVector(rcpX, blockRowIndex);
230  Teuchos::RCP<MultiVector> ri = rangeMapExtractor_->ExtractVector(residual, blockRowIndex);
231 
232  Teuchos::RCP<MultiVector> tXi = domainMapExtractor_->getVector(blockRowIndex, X.getNumVectors());
233 
234  // apply solver/smoother
235  Inverse_.at(i)->Apply(*tXi, *ri, false);
236 
237  // update vector
238  Xi->update(omega,*tXi,1.0); // X_{i+1} = X_i + omega \Delta X_i
239 
240  // update corresponding part of rhs and lhs
241  domainMapExtractor_->InsertVector(Xi, blockRowIndex, rcpX); // TODO wrong! fix me
242  }
243  }
244 
245  }
246 
247  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
248  RCP<MueLu::SmootherPrototype<Scalar, LocalOrdinal, GlobalOrdinal, Node> > BlockedGaussSeidelSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Copy() const {
249  return rcp( new BlockedGaussSeidelSmoother(*this) );
250  }
251 
252  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
254  std::ostringstream out;
256  out << "{type = " << type_ << "}";
257  return out.str();
258  }
259 
260  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
261  void BlockedGaussSeidelSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::print(Teuchos::FancyOStream &out, const VerbLevel verbLevel) const {
263 
264  // extract parameters from internal parameter list
265  const ParameterList & pL = Factory::GetParameterList();
266  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
267  Scalar omega = pL.get<Scalar>("Damping factor");
268 
269  if (verbLevel & Parameters0) {
270  out0 << "Prec. type: " << type_ << " Sweeps: " << nSweeps << " damping: " << omega << std::endl;
271  }
272 
273  if (verbLevel & Debug) {
274  std::map<size_t,size_t>::const_iterator itOrdering;
275  for(itOrdering = bgsOrderingIndex2blockRowIndex_.begin(); itOrdering!=bgsOrderingIndex2blockRowIndex_.end(); itOrdering++) {
276  std::cout << "block GaussSeidel ordering index: " << (*itOrdering).first << " -> block row in blocked A: " << (*itOrdering).second << std::endl;
277  }
278  }
279 
280  if (verbLevel & Debug) {
281  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl;
282  }
283  }
284 
285 } // namespace MueLu
286 
287 
288 
289 #endif /* MUELU_BLOCKEDGAUSSSEIDELSMOOTHER_DEF_HPP_ */
Important warning messages (one line)
Exception indicating invalid cast attempted.
RCP< const MapExtractorClass > domainMapExtractor_
domain map extractor (from A_ generated by AFact)
std::string toString(const T &what)
Little helper function to convert non-string types to strings.
Timer to be used in factories. Similar to Monitor but with additional timers.
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.
Namespace for MueLu classes and methods.
virtual const Teuchos::ParameterList & GetParameterList() const
std::vector< Teuchos::RCP< const SmootherBase > > Inverse_
vector of smoother/solver factories
std::string description() const
Return a simple one-line description of this object.
void DeclareInput(Level &currentLevel) const
Input.
RCP< const MapExtractorClass > rangeMapExtractor_
range map extractor (from A_ generated by AFact)
const StdMapType::mapped_type & at(const StdMapType &map, const typename StdMapType::key_type &x)
std::map< size_t, size_t > bgsOrderingIndex2blockRowIndex_
map: block GaussSeidel ordering to block row ordering
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.
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
Print class parameters.
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.
Exception throws to report errors in the internal logical of the program.
An exception safe way to call the method &#39;Level::SetFactoryManager()&#39;.
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.
const RCP< const FactoryBase > GetFactory(const std::string &varName) const
Default implementation of FactoryAcceptor::GetFactory()