MueLu  Version of the Day
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>
63 #include <Xpetra_BlockedCrsMatrix.hpp>
64 #include <Xpetra_MultiVectorFactory.hpp>
65 #include <Xpetra_VectorFactory.hpp>
66 
68 #include "MueLu_Level.hpp"
69 #include "MueLu_Utilities.hpp"
70 #include "MueLu_Monitor.hpp"
71 #include "MueLu_HierarchyUtils.hpp"
72 #include "MueLu_SmootherBase.hpp"
73 #include "MueLu_SubBlockAFactory.hpp"
74 
75 // include files for default FactoryManager
76 #include "MueLu_SchurComplementFactory.hpp"
77 #include "MueLu_DirectSolver.hpp"
78 #include "MueLu_SmootherFactory.hpp"
79 #include "MueLu_FactoryManager.hpp"
80 
81 namespace MueLu {
82 
83  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
85  : type_("IndefiniteBlockDiagonalSmoother"), A_(Teuchos::null)
86  {
87  }
88 
89  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
91 
92  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
94  RCP<ParameterList> validParamList = rcp(new ParameterList());
95 
96  validParamList->set< RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A (must be a 2x2 block matrix)");
97  validParamList->set< Scalar > ("Damping factor", 1.0, "Damping/Scaling factor");
98  validParamList->set< LocalOrdinal > ("Sweeps", 1, "Number of SIMPLE sweeps (default = 1)");
99  //validParamList->set< bool > ("UseSIMPLEC", false, "Use SIMPLEC instead of SIMPLE (default = false)");
100 
101  return validParamList;
102  }
103 
105  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
107  TEUCHOS_TEST_FOR_EXCEPTION(pos < 0, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::AddFactoryManager: parameter \'pos\' must not be negative! error.");
108 
109  size_t myPos = Teuchos::as<size_t>(pos);
110 
111  if (myPos < FactManager_.size()) {
112  // replace existing entris in FactManager_ vector
113  FactManager_.at(myPos) = FactManager;
114  } else if( myPos == FactManager_.size()) {
115  // add new Factory manager in the end of the vector
116  FactManager_.push_back(FactManager);
117  } else { // if(myPos > FactManager_.size())
118  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
119  *out << "Warning: cannot add new FactoryManager at proper position " << pos << ". The FactoryManager is just appended to the end. Check this!" << std::endl;
120 
121  // add new Factory manager in the end of the vector
122  FactManager_.push_back(FactManager);
123  }
124  }
125 
126  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
128  currentLevel.DeclareInput("A",this->GetFactory("A").get());
129 
130  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\"!");
131 
132  // loop over all factory managers for the subblocks of blocked operator A
133  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
134  for(it = FactManager_.begin(); it!=FactManager_.end(); ++it) {
135  SetFactoryManager currentSFM (rcpFromRef(currentLevel), *it);
136 
137  // request "Smoother" for current subblock row.
138  currentLevel.DeclareInput("PreSmoother",(*it)->GetFactory("Smoother").get());
139  }
140 
141  }
142 
143  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
145  FactoryMonitor m(*this, "Setup for indefinite blocked diagonal smoother", currentLevel);
146 
147  if (SmootherPrototype::IsSetup() == true)
148  this->GetOStream(Warnings0) << "MueLu::IndefBlockedDiagonalSmoother::Setup(): Setup() has already been called";
149 
150  // extract blocked operator A from current level
151  A_ = Factory::Get<RCP<Matrix> > (currentLevel, "A");
152 
153  RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A_);
154  TEUCHOS_TEST_FOR_EXCEPTION(bA == Teuchos::null, Exceptions::BadCast, "MueLu::IndefBlockedDiagonalSmoother::Setup: input matrix A is not of type BlockedCrsMatrix! error.");
155 
156  // store map extractors
157  rangeMapExtractor_ = bA->getRangeMapExtractor();
158  domainMapExtractor_ = bA->getDomainMapExtractor();
159 
160  // Store the blocks in local member variables
161  Teuchos::RCP<Matrix> A00 = bA->getMatrix(0, 0);
162  Teuchos::RCP<Matrix> A01 = bA->getMatrix(0, 1);
163  Teuchos::RCP<Matrix> A10 = bA->getMatrix(1, 0);
164  Teuchos::RCP<Matrix> A11 = bA->getMatrix(1, 1);
165 
166  F_ = A00;
167  Z_ = A11;
168 
169  /*const ParameterList & pL = Factory::GetParameterList();
170  bool bSIMPLEC = pL.get<bool>("UseSIMPLEC");
171 
172  // Create the inverse of the diagonal of F
173  RCP<Vector> diagFVector = VectorFactory::Build(F_->getRowMap());
174  if(!bSIMPLEC) {
175  F_->getLocalDiagCopy(*diagFVector); // extract diagonal of F
176  diagFVector->reciprocal(*diagFVector); // build reciprocal
177  } else {
178  const RCP<const Map> rowmap = F_->getRowMap();
179  size_t locSize = rowmap->getNodeNumElements();
180  Teuchos::ArrayRCP<SC> diag = diagFVector->getDataNonConst(0);
181  Teuchos::ArrayView<const LO> cols;
182  Teuchos::ArrayView<const SC> vals;
183  for (size_t i=0; i<locSize; ++i) { // loop over rows
184  F_->getLocalRowView(i,cols,vals);
185  Scalar absRowSum = Teuchos::ScalarTraits<Scalar>::zero();
186  for (LO j=0; j<cols.size(); ++j) { // loop over cols
187  absRowSum += Teuchos::ScalarTraits<Scalar>::magnitude(vals[j]);
188  }
189  diag[i] = absRowSum;
190  }
191  diagFVector->reciprocal(*diagFVector); // build reciprocal
192  }
193  diagFinv_ = diagFVector;*/
194 
195  // Set the Smoother
196  // carefully switch to the SubFactoryManagers (defined by the users)
197  {
198  RCP<const FactoryManagerBase> velpredictFactManager = FactManager_.at(0);
199  SetFactoryManager currentSFM (rcpFromRef(currentLevel), velpredictFactManager);
200  velPredictSmoo_ = currentLevel.Get< RCP<SmootherBase> >("PreSmoother",velpredictFactManager->GetFactory("Smoother").get());
201  }
202  {
203  RCP<const FactoryManagerBase> schurFactManager = FactManager_.at(1);
204  SetFactoryManager currentSFM (rcpFromRef(currentLevel), schurFactManager);
205  schurCompSmoo_ = currentLevel.Get< RCP<SmootherBase> >("PreSmoother", schurFactManager->GetFactory("Smoother").get());
206  }
208  }
209 
210  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
211  void IndefBlockedDiagonalSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const
212  {
213  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::IndefBlockedDiagonalSmoother::Apply(): Setup() has not been called");
214 
215  Teuchos::RCP<Teuchos::FancyOStream> fos = Teuchos::getFancyOStream(Teuchos::rcpFromRef(std::cout));
216 
217  SC zero = Teuchos::ScalarTraits<SC>::zero(), one = Teuchos::ScalarTraits<SC>::one();
218 
219  // The following boolean flags catch the case where we need special transformation
220  // for the GIDs when calling the subsmoothers.
221  RCP<BlockedCrsMatrix> bA00 = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(F_);
222  RCP<BlockedCrsMatrix> bA11 = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(Z_);
223  bool bA00ThyraSpecialTreatment = false;
224  bool bA11ThyraSpecialTreatment = false;
225  if (bA00 != Teuchos::null) {
226  if(bA00->Rows() == 1 && bA00->Cols() == 1 && rangeMapExtractor_->getThyraMode() == true) bA00ThyraSpecialTreatment = true;
227  }
228  if (bA11 != Teuchos::null) {
229  if(bA11->Rows() == 1 && bA11->Cols() == 1 && rangeMapExtractor_->getThyraMode() == true) bA11ThyraSpecialTreatment = true;
230  }
231 
232  // extract parameters from internal parameter list
233  const ParameterList & pL = Factory::GetParameterList();
234  LocalOrdinal nSweeps = pL.get<LocalOrdinal>("Sweeps");
235  Scalar omega = pL.get<Scalar>("Damping factor");
236 
237  // wrap current solution vector in RCP
238  RCP<MultiVector> rcpX = Teuchos::rcpFromRef(X);
239 
240  // create residual vector
241  // contains current residual of current solution X with rhs B
242  RCP<MultiVector> residual = MultiVectorFactory::Build(B.getMap(), B.getNumVectors());
243 
244  // incrementally improve solution vector X
245  for (LocalOrdinal run = 0; run < nSweeps; ++run) {
246  // 1) calculate current residual
247  residual->update(one,B,zero); // residual = B
248  A_->apply(*rcpX, *residual, Teuchos::NO_TRANS, -one, one);
249 
250  // split residual vector
251  Teuchos::RCP<MultiVector> r1 = rangeMapExtractor_->ExtractVector(residual, 0);
252  Teuchos::RCP<MultiVector> r2 = rangeMapExtractor_->ExtractVector(residual, 1);
253 
254  // 2) solve F * \Delta \tilde{x}_1 = r_1
255  // start with zero guess \Delta \tilde{x}_1
256  RCP<MultiVector> xtilde1 = MultiVectorFactory::Build(F_->getRowMap(),X.getNumVectors(),true);
257 
258  // Special handling if SchurComplement operator was a 1x1 blocked operator in Thyra mode
259  // Then, we have to translate the Xpetra offset GIDs to plain Thyra GIDs and vice versa
260  if(bA00ThyraSpecialTreatment == true) {
261  RCP<MultiVector> xtilde1_thyra = domainMapExtractor_->getVector(0, X.getNumVectors(), true);
262  RCP<MultiVector> r1_thyra = rangeMapExtractor_->getVector(0, B.getNumVectors(), true);
263  // transform vector
264  for(size_t k=0; k < r1->getNumVectors(); k++) {
265  Teuchos::ArrayRCP<const Scalar> xpetraVecData = r1->getData(k);
266  Teuchos::ArrayRCP<Scalar> thyraVecData = r1_thyra->getDataNonConst(k);
267  for(size_t i=0; i < r1->getLocalLength(); i++) {
268  thyraVecData[i] = xpetraVecData[i];
269  }
270  }
271 
272  velPredictSmoo_->Apply(*xtilde1_thyra,*r1_thyra);
273 
274  for(size_t k=0; k < xtilde1_thyra->getNumVectors(); k++) {
275  Teuchos::ArrayRCP<Scalar> xpetraVecData = xtilde1->getDataNonConst(k);
276  Teuchos::ArrayRCP<const Scalar> thyraVecData = xtilde1_thyra->getData(k);
277  for(size_t i=0; i < xtilde1_thyra->getLocalLength(); i++) {
278  xpetraVecData[i] = thyraVecData[i];
279  }
280  }
281  } else {
282  velPredictSmoo_->Apply(*xtilde1,*r1);
283  }
284 
285  // 3) solve SchurComp equation
286  // start with zero guess \Delta \tilde{x}_2
287  RCP<MultiVector> xtilde2 = MultiVectorFactory::Build(Z_->getRowMap(),X.getNumVectors(),true);
288 
289  // Special handling if SchurComplement operator was a 1x1 blocked operator in Thyra mode
290  // Then, we have to translate the Xpetra offset GIDs to plain Thyra GIDs and vice versa
291  if(bA11ThyraSpecialTreatment == true) {
292  RCP<MultiVector> xtilde2_thyra = domainMapExtractor_->getVector(1, X.getNumVectors(), true);
293  RCP<MultiVector> r2_thyra = rangeMapExtractor_->getVector(1, B.getNumVectors(), true);
294  // transform vector
295  for(size_t k=0; k < r2->getNumVectors(); k++) {
296  Teuchos::ArrayRCP<const Scalar> xpetraVecData = r2->getData(k);
297  Teuchos::ArrayRCP<Scalar> thyraVecData = r2_thyra->getDataNonConst(k);
298  for(size_t i=0; i < r2->getLocalLength(); i++) {
299  thyraVecData[i] = xpetraVecData[i];
300  }
301  }
302 
303  schurCompSmoo_->Apply(*xtilde2_thyra,*r2_thyra);
304 
305  for(size_t k=0; k < xtilde2_thyra->getNumVectors(); k++) {
306  Teuchos::ArrayRCP<Scalar> xpetraVecData = xtilde2->getDataNonConst(k);
307  Teuchos::ArrayRCP<const Scalar> thyraVecData = xtilde2_thyra->getData(k);
308  for(size_t i=0; i < xtilde2_thyra->getLocalLength(); i++) {
309  xpetraVecData[i] = thyraVecData[i];
310  }
311  }
312  } else {
313  schurCompSmoo_->Apply(*xtilde2,*r2);
314  }
315 
316  // 4) extract parts of solution vector X
317  Teuchos::RCP<MultiVector> x1 = domainMapExtractor_->ExtractVector(rcpX, 0);
318  Teuchos::RCP<MultiVector> x2 = domainMapExtractor_->ExtractVector(rcpX, 1);
319 
320  // 5) update solution vector with increments xhat1 and xhat2
321  // rescale increment for x2 with omega_
322  x1->update(omega,*xtilde1,one); // x1 = x1_old + omega xtilde1
323  x2->update(omega,*xtilde2,one); // x2 = x2_old + omega xtilde2
324 
325  // write back solution in global vector X
326  domainMapExtractor_->InsertVector(x1, 0, rcpX);
327  domainMapExtractor_->InsertVector(x2, 1, rcpX);
328  }
329  }
330 
331  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
332  RCP<MueLu::SmootherPrototype<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
334  return rcp( new IndefBlockedDiagonalSmoother(*this) );
335  }
336 
337  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
339  std::ostringstream out;
341  out << "{type = " << type_ << "}";
342  return out.str();
343  }
344 
345  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
346  void IndefBlockedDiagonalSmoother<Scalar, LocalOrdinal, GlobalOrdinal, Node>::print(Teuchos::FancyOStream &out, const VerbLevel verbLevel) const {
348 
349  if (verbLevel & Parameters0) {
350  out0 << "Prec. type: " << type_ << /*" Sweeps: " << nSweeps_ << " damping: " << omega_ <<*/ std::endl;
351  }
352 
353  if (verbLevel & Debug) {
354  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl;
355  }
356  }
357 
358 } // namespace MueLu
359 
360 #endif /* MUELU_INDEFBLOCKEDDIAGONALSMOOTHER_DEF_HPP_ */
Important warning messages (one line)
Exception indicating invalid cast attempted.
std::string toString(const T &what)
Little helper function to convert non-string types to strings.
bool IsSetup() const
Get the state of a smoother prototype.
Timer to be used in factories. Similar to Monitor but with additional timers.
RCP< const ParameterList > GetValidParameterList() const
Input.
Print additional debugging information.
Namespace for MueLu classes and methods.
void Apply(MultiVector &X, const MultiVector &B, bool InitialGuessIsZero=false) const
Apply the Braess Sarazin smoother.
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Cheap Blocked diagonal smoother for indefinite 2x2 block matrices.
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
virtual const Teuchos::ParameterList & GetParameterList() const
Print class parameters.
void print(Teuchos::FancyOStream &out, const VerbLevel verbLevel=Default) const
Print the object with some verbosity level to an FancyOStream object.
void AddFactoryManager(RCP< const FactoryManagerBase > FactManager, int pos=0)
Add a factory manager for BraessSarazin internal SchurComplement handling.
Exception throws to report errors in the internal logical of the program.
An exception safe way to call the method &#39;Level::SetFactoryManager()&#39;.
std::string description() const
Return a simple one-line description of this object.
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.