MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_StratimikosSmoother_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 #ifndef MUELU_STRATIMIKOSSMOOTHER_DEF_HPP
47 #define MUELU_STRATIMIKOSSMOOTHER_DEF_HPP
48 
49 #include "MueLu_ConfigDefs.hpp"
50 
51 #if defined(HAVE_MUELU_STRATIMIKOS) && defined(HAVE_MUELU_THYRA)
52 
54 
55 #include <Xpetra_CrsMatrix.hpp>
56 #include <Xpetra_CrsMatrixWrap.hpp>
57 #include <Xpetra_Matrix.hpp>
58 
60 #include "MueLu_Level.hpp"
61 #include "MueLu_Utilities.hpp"
62 #include "MueLu_Monitor.hpp"
63 #ifdef MUELU_RECURMG
65 #endif
66 
67 #include <Stratimikos_DefaultLinearSolverBuilder.hpp>
68 #include "Teuchos_AbstractFactoryStd.hpp"
70 #include <unordered_map>
71 
72 namespace MueLu {
73 
74 template <class LocalOrdinal, class GlobalOrdinal, class Node>
75 StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::StratimikosSmoother(const std::string type, const Teuchos::ParameterList& paramList)
76  : type_(type) {
77  std::transform(type_.begin(), type_.end(), type_.begin(), ::toupper);
78  ParameterList& pList = const_cast<ParameterList&>(paramList);
79 
80  if (pList.isParameter("smoother: recurMgOnFilteredA")) {
81  recurMgOnFilteredA_ = true;
82  pList.remove("smoother: recurMgOnFilteredA");
83  }
84  bool isSupported = type_ == "STRATIMIKOS";
85  this->declareConstructionOutcome(!isSupported, "Stratimikos does not provide the smoother '" + type_ + "'.");
86  if (isSupported)
87  SetParameterList(paramList);
88 }
89 
90 template <class LocalOrdinal, class GlobalOrdinal, class Node>
91 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::SetParameterList(const Teuchos::ParameterList& paramList) {
92  Factory::SetParameterList(paramList);
93 }
94 
95 template <class LocalOrdinal, class GlobalOrdinal, class Node>
96 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::DeclareInput(Level& currentLevel) const {
97  this->Input(currentLevel, "A");
98 }
99 
100 template <class LocalOrdinal, class GlobalOrdinal, class Node>
101 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::Setup(Level& currentLevel) {
102  FactoryMonitor m(*this, "Setup Smoother", currentLevel);
103 
104  A_ = Factory::Get<RCP<Matrix> >(currentLevel, "A");
105  SetupStratimikos(currentLevel);
106  SmootherPrototype::IsSetup(true);
107  this->GetOStream(Statistics1) << description() << std::endl;
108 }
109 
110 template <class LocalOrdinal, class GlobalOrdinal, class Node>
111 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::SetupStratimikos(Level& currentLevel) {
112  RCP<const Thyra::LinearOpBase<Scalar> > thyraA;
113  if (recurMgOnFilteredA_) {
114  RCP<Matrix> filteredA;
115  ExperimentalDropVertConnections(filteredA, currentLevel);
116  thyraA = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyra(Teuchos::rcp_dynamic_cast<CrsMatrixWrap>(filteredA)->getCrsMatrix());
117  } else
118  thyraA = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyra(Teuchos::rcp_dynamic_cast<CrsMatrixWrap>(A_)->getCrsMatrix());
119 
120  // Build Stratimikos solver
121  Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder;
122  if (recurMgOnFilteredA_) {
123 #ifdef MUELU_RECURMG
124  Stratimikos::enableMueLu<LocalOrdinal, GlobalOrdinal, Node>(linearSolverBuilder);
125 #else
126  TEUCHOS_TEST_FOR_EXCEPTION(true, Exceptions::RuntimeError, "MueLu::StratimikosSmoother:: must compile with MUELU_RECURMG defined. Unfortunately, cmake does not always produce a proper link.txt file (which sometimes requires libmuelu.a before and after libmuelu-interface.a). After configuring, run script muelu/utils/misc/patchLinkForRecurMG to change link.txt files manually. If you want to create test example, add -DMUELU_RECURMG=ON to cmake arguments.");
127 #endif
128  }
129 
130  linearSolverBuilder.setParameterList(rcpFromRef(const_cast<ParameterList&>(this->GetParameterList())));
131 
132  // Build a new "solver factory" according to the previously specified parameter list.
133  RCP<Thyra::LinearOpWithSolveFactoryBase<Scalar> > solverFactory = Thyra::createLinearSolveStrategy(linearSolverBuilder);
134  solver_ = Thyra::linearOpWithSolve(*solverFactory, thyraA);
135 #ifdef dumpOutRecurMGDebug
136  char mystring[120];
137  sprintf(mystring, "for i in A_[0123456789].m P_[0123456789].m; do T=Xecho $i | sed Xs/.m$/%d.m/XX; mv $i $T; done", (int)currentLevel.GetLevelID());
138  fflush(stdout);
139  mystring[50] = '`';
140  mystring[65] = '"';
141  mystring[76] = '"';
142  mystring[77] = '`';
143  system(mystring);
144 #endif
145 }
146 
147 template <class LocalOrdinal, class GlobalOrdinal, class Node>
148 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::ExperimentalDropVertConnections(RCP<Matrix>& filteredA, Level& currentLevel) {
149  // strip out the veritcal connections.
150  //
151  // There is some code, which is currently turned off (via sumDropped). That
152  // makes things more complicated. I want to keep it for now, and so it is
153  // explained here. The basic idea is to try and maintain the character
154  // of the horizontal stencil by summing dropped entries appropriately.
155  // However, this does not correspond to plane relexation, and so I am
156  // not sure it is really justified. Anyway, the picture below
157  // gives a situation with a 15-pt stencil
158  //
159  // a
160  // /
161  // /
162  // b ----c----- d
163  // /
164  // /
165  // e
166  // f dropped a & l summed into f
167  // / dropped b & m summed into g
168  // / dropped c & n summed into i
169  // g ----i----- j dropped d & o summed into j
170  // / dropped e & p summed into k
171  // /
172  // k
173  // l
174  // /
175  // /
176  // m ----n----- o
177  // /
178  // /
179  // p
180  // To do this, we use umap to record locations within the middle layer associated
181  // with each line ID (e.g. g corresponds to the 13th line). Then, when dropping (in a 2nd pass) we
182  // use lineId and umap to find where dropped entries should be summed (e.g., b corresponds to the
183  // 13th line and umap[13] points at location for g).
184  // using TST = typename Teuchos::ScalarTraits<SC>;
185 
186  bool sumDropped = false;
187 
188  LO dofsPerNode = A_->GetFixedBlockSize();
189 
190  RCP<ParameterList> fillCompleteParams(new ParameterList); // This code taken from Build method
191  fillCompleteParams->set("No Nonlocal Changes", true); // within MueLu_FilteredAFactory_def
192  filteredA = MatrixFactory::Build(A_->getCrsGraph());
193  filteredA->resumeFill();
194 
195  ArrayView<const LocalOrdinal> inds;
196  ArrayView<const Scalar> valsA;
197  ArrayView<Scalar> vals;
198  Teuchos::ArrayRCP<LocalOrdinal> TVertLineId = Factory::Get<Teuchos::ArrayRCP<LocalOrdinal> >(currentLevel, "LineDetection_VertLineIds");
199  Teuchos::ArrayRCP<LocalOrdinal> TLayerId = Factory::Get<Teuchos::ArrayRCP<LocalOrdinal> >(currentLevel, "LineDetection_Layers");
200  LocalOrdinal* VertLineId = TVertLineId.getRawPtr();
201  LocalOrdinal* LayerId = TLayerId.getRawPtr();
202  TEUCHOS_TEST_FOR_EXCEPTION((LayerId == NULL) || (VertLineId == NULL), Exceptions::RuntimeError, "MueLu::StratimikosSmoother:: no line information found on this level. Cannot use recurMgOnFilteredA on this level.");
203 
205  for (size_t i = 0; i < A_->getRowMap()->getLocalNumElements(); i++) {
206  A_->getLocalRowView(i, inds, valsA);
207  size_t nnz = inds.size();
208  ArrayView<const Scalar> vals1;
209  filteredA->getLocalRowView(i, inds, vals1);
210  vals = ArrayView<Scalar>(const_cast<Scalar*>(vals1.getRawPtr()), nnz);
211  memcpy(vals.getRawPtr(), valsA.getRawPtr(), nnz * sizeof(Scalar));
212  size_t inode, jdof, jnode, jdof_offset;
213  inode = i / dofsPerNode;
214 
215  std::unordered_map<LocalOrdinal, LocalOrdinal> umap; // umap[k] indicates where the dropped entry
216  // corresponding to kth line should be added
217  // within the row. See comments above.
218  if (sumDropped) {
219  for (size_t j = 0; j < nnz; j++) {
220  jdof = inds[j];
221  jnode = jdof / dofsPerNode;
222  jdof_offset = jdof - jnode * dofsPerNode;
223  if (LayerId[jnode] == LayerId[inode]) umap[dofsPerNode * VertLineId[jnode] + jdof_offset] = j;
224  }
225  }
226 
227  // drop non-middle layer entries. When sumDropped=true, sum dropped entries to corresponding mid-layer entry
228  for (size_t j = 0; j < nnz; j++) {
229  jdof = inds[j];
230  jnode = jdof / dofsPerNode;
231  jdof_offset = jdof - jnode * dofsPerNode;
232  if (LayerId[jnode] != LayerId[inode]) {
233  if (sumDropped) {
234  if (umap.find(dofsPerNode * VertLineId[jnode + jdof_offset]) != umap.end())
235  vals[umap[dofsPerNode * VertLineId[jnode + jdof_offset]]] += vals[j];
236  }
237  vals[j] = ZERO;
238  }
239  }
240  }
241  filteredA->fillComplete(fillCompleteParams);
242 }
243 
244 template <class LocalOrdinal, class GlobalOrdinal, class Node>
245 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::Apply(MultiVector& X, const MultiVector& B, bool InitialGuessIsZero) const {
246  TEUCHOS_TEST_FOR_EXCEPTION(SmootherPrototype::IsSetup() == false, Exceptions::RuntimeError, "MueLu::StratimikosSmoother::Apply(): Setup() has not been called");
247 
248  // Apply
249  if (InitialGuessIsZero) {
250  X.putScalar(0.0);
251  RCP<Thyra::MultiVectorBase<Scalar> > thyraX = Teuchos::rcp_const_cast<Thyra::MultiVectorBase<Scalar> >(Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyraMultiVector(rcpFromRef(X)));
252  RCP<const Thyra::MultiVectorBase<Scalar> > thyraB = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyraMultiVector(rcpFromRef(B));
253  Thyra::SolveStatus<Scalar> status = Thyra::solve<Scalar>(*solver_, Thyra::NOTRANS, *thyraB, thyraX.ptr());
254  RCP<MultiVector> thyXpX = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toXpetra(thyraX, X.getMap()->getComm());
255  X = *thyXpX;
256 
257  } else {
258  typedef Teuchos::ScalarTraits<Scalar> TST;
259  RCP<MultiVector> Residual = Utilities::Residual(*A_, X, B);
260 
261  RCP<MultiVector> Cor = Xpetra::MultiVectorFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(X.getMap(), X.getNumVectors(), true);
262  RCP<Thyra::MultiVectorBase<Scalar> > thyraCor = Teuchos::rcp_const_cast<Thyra::MultiVectorBase<Scalar> >(Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyraMultiVector(Cor));
263  RCP<const Thyra::MultiVectorBase<Scalar> > thyraRes = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toThyraMultiVector(Residual);
264  Thyra::SolveStatus<Scalar> status = Thyra::solve<Scalar>(*solver_, Thyra::NOTRANS, *thyraRes, thyraCor.ptr());
265  RCP<MultiVector> thyXpCor = Xpetra::ThyraUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::toXpetra(thyraCor, X.getMap()->getComm());
266  X.update(TST::one(), *thyXpCor, TST::one());
267  }
268 }
269 
270 template <class LocalOrdinal, class GlobalOrdinal, class Node>
271 RCP<MueLu::SmootherPrototype<double, LocalOrdinal, GlobalOrdinal, Node> > StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::Copy() const {
272  RCP<StratimikosSmoother> smoother = rcp(new StratimikosSmoother(*this));
273  smoother->SetParameterList(this->GetParameterList());
274  return smoother;
275 }
276 
277 template <class LocalOrdinal, class GlobalOrdinal, class Node>
278 std::string StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::description() const {
279  std::ostringstream out;
280  if (SmootherPrototype::IsSetup()) {
281  out << solver_->description();
282  } else {
283  out << "STRATIMIKOS {type = " << type_ << "}";
284  }
285  return out.str();
286 }
287 
288 template <class LocalOrdinal, class GlobalOrdinal, class Node>
289 void StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::print(Teuchos::FancyOStream& out, const VerbLevel verbLevel) const {
291 
292  if (verbLevel & Parameters1) {
293  out0 << "Parameter list: " << std::endl;
294  Teuchos::OSTab tab2(out);
295  out << this->GetParameterList();
296  }
297 
298  if (verbLevel & External)
299  if (solver_ != Teuchos::null) {
300  Teuchos::OSTab tab2(out);
301  out << *solver_ << std::endl;
302  }
303 
304  if (verbLevel & Debug) {
305  out0 << "IsSetup: " << Teuchos::toString(SmootherPrototype::IsSetup()) << std::endl
306  << "-" << std::endl
307  << "RCP<solver_>: " << solver_ << std::endl;
308  }
309 }
310 
311 template <class LocalOrdinal, class GlobalOrdinal, class Node>
312 size_t StratimikosSmoother<double, LocalOrdinal, GlobalOrdinal, Node>::getNodeSmootherComplexity() const {
314 }
315 
316 } // namespace MueLu
317 
318 #endif // HAVE_MUELU_STRATIMIKOS
319 #endif // MUELU_STRATIMIKOSSMOOTHER_DEF_HPP
MueLu::DefaultLocalOrdinal LocalOrdinal
static Teuchos::RCP< MultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node > > Build(const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node >> &map, size_t NumVectors, bool zeroOut=true)
Print external lib objects.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Print more statistics.
T * getRawPtr() const
Print additional debugging information.
LocalOrdinal LO
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
MueLu::DefaultScalar Scalar
#define MUELU_DESCRIBE
Helper macro for implementing Describable::describe() for BaseClass objects.
Print class parameters (more parameters, more verbose)
std::string toString(const T &t)