MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_RAPShiftFactory_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_RAPSHIFTFACTORY_DEF_HPP
47 #define MUELU_RAPSHIFTFACTORY_DEF_HPP
48 
49 #include <sstream>
50 
51 #include <Xpetra_Matrix.hpp>
52 #include <Xpetra_MatrixMatrix.hpp>
53 #include <Xpetra_MatrixUtils.hpp>
54 #include <Xpetra_Vector.hpp>
55 #include <Xpetra_VectorFactory.hpp>
56 
58 #include "MueLu_MasterList.hpp"
59 #include "MueLu_Monitor.hpp"
60 #include "MueLu_PerfUtils.hpp"
61 
62 namespace MueLu {
63 
64 /*********************************************************************************************************/
65 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
67  : implicitTranspose_(false) {}
68 
69 /*********************************************************************************************************/
70 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
72  RCP<ParameterList> validParamList = rcp(new ParameterList());
73 
74 #define SET_VALID_ENTRY(name) validParamList->setEntry(name, MasterList::getEntry(name))
75  SET_VALID_ENTRY("transpose: use implicit");
76  SET_VALID_ENTRY("rap: fix zero diagonals");
77  SET_VALID_ENTRY("rap: shift");
78  SET_VALID_ENTRY("rap: shift array");
79  SET_VALID_ENTRY("rap: cfl array");
80  SET_VALID_ENTRY("rap: shift diagonal M");
81  SET_VALID_ENTRY("rap: shift low storage");
82  SET_VALID_ENTRY("rap: relative diagonal floor");
83 #undef SET_VALID_ENTRY
84 
85  validParamList->set<RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A used during the prolongator smoothing process");
86  validParamList->set<RCP<const FactoryBase> >("M", Teuchos::null, "Generating factory of the matrix M used during the non-Galerkin RAP");
87  validParamList->set<RCP<const FactoryBase> >("Mdiag", Teuchos::null, "Generating factory of the matrix Mdiag used during the non-Galerkin RAP");
88  validParamList->set<RCP<const FactoryBase> >("K", Teuchos::null, "Generating factory of the matrix K used during the non-Galerkin RAP");
89  validParamList->set<RCP<const FactoryBase> >("P", Teuchos::null, "Prolongator factory");
90  validParamList->set<RCP<const FactoryBase> >("R", Teuchos::null, "Restrictor factory");
91 
92  validParamList->set<bool>("CheckMainDiagonal", false, "Check main diagonal for zeros");
93  validParamList->set<bool>("RepairMainDiagonal", false, "Repair zeros on main diagonal");
94 
95  validParamList->set<RCP<const FactoryBase> >("deltaT", Teuchos::null, "user deltaT");
96  validParamList->set<RCP<const FactoryBase> >("cfl", Teuchos::null, "user cfl");
97  validParamList->set<RCP<const FactoryBase> >("cfl-based shift array", Teuchos::null, "MueLu-generated shift array for CFL-based shifting");
98 
99  // Make sure we don't recursively validate options for the matrixmatrix kernels
100  ParameterList norecurse;
101  norecurse.disableRecursiveValidation();
102  validParamList->set<ParameterList>("matrixmatrix: kernel params", norecurse, "MatrixMatrix kernel parameters");
103 
104  return validParamList;
105 }
106 
107 /*********************************************************************************************************/
108 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
110  const Teuchos::ParameterList &pL = GetParameterList();
111 
112  bool use_mdiag = false;
113  if (pL.isParameter("rap: shift diagonal M"))
114  use_mdiag = pL.get<bool>("rap: shift diagonal M");
115 
116  // The low storage version requires mdiag
117  bool use_low_storage = false;
118  if (pL.isParameter("rap: shift low storage")) {
119  use_low_storage = pL.get<bool>("rap: shift low storage");
120  use_mdiag = use_low_storage ? true : use_mdiag;
121  }
122 
123  if (implicitTranspose_ == false) {
124  Input(coarseLevel, "R");
125  }
126 
127  if (!use_low_storage)
128  Input(fineLevel, "K");
129  else
130  Input(fineLevel, "A");
131  Input(coarseLevel, "P");
132 
133  if (!use_mdiag)
134  Input(fineLevel, "M");
135  else
136  Input(fineLevel, "Mdiag");
137 
138  // CFL array stuff
139  if (pL.isParameter("rap: cfl array") && pL.get<Teuchos::Array<double> >("rap: cfl array").size() > 0) {
140  if (fineLevel.GetLevelID() == 0) {
141  if (fineLevel.IsAvailable("deltaT", NoFactory::get())) {
142  fineLevel.DeclareInput("deltaT", NoFactory::get(), this);
143  } else {
144  TEUCHOS_TEST_FOR_EXCEPTION(fineLevel.IsAvailable("fine deltaT", NoFactory::get()),
146  "deltaT was not provided by the user on level0!");
147  }
148 
149  if (fineLevel.IsAvailable("cfl", NoFactory::get())) {
150  fineLevel.DeclareInput("cfl", NoFactory::get(), this);
151  } else {
152  TEUCHOS_TEST_FOR_EXCEPTION(fineLevel.IsAvailable("fine cfl", NoFactory::get()),
154  "cfl was not provided by the user on level0!");
155  }
156  } else {
157  Input(fineLevel, "cfl-based shift array");
158  }
159  }
160 
161  // call DeclareInput of all user-given transfer factories
162  for (std::vector<RCP<const FactoryBase> >::const_iterator it = transferFacts_.begin(); it != transferFacts_.end(); ++it) {
163  (*it)->CallDeclareInput(coarseLevel);
164  }
165 }
166 
167 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
168 void RAPShiftFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(Level &fineLevel, Level &coarseLevel) const { // FIXME make fineLevel const
169  {
170  FactoryMonitor m(*this, "Computing Ac", coarseLevel);
171  const Teuchos::ParameterList &pL = GetParameterList();
172 
173  bool M_is_diagonal = false;
174  if (pL.isParameter("rap: shift diagonal M"))
175  M_is_diagonal = pL.get<bool>("rap: shift diagonal M");
176 
177  // The low storage version requires mdiag
178  bool use_low_storage = false;
179  if (pL.isParameter("rap: shift low storage")) {
180  use_low_storage = pL.get<bool>("rap: shift low storage");
181  M_is_diagonal = use_low_storage ? true : M_is_diagonal;
182  }
183 
185  Teuchos::ArrayRCP<double> myshifts;
186  if (pL.isParameter("rap: shift array") && pL.get<Teuchos::Array<double> >("rap: shift array").size() > 0) {
187  // Do we have an array of shifts? If so, we set doubleShifts_
188  doubleShifts = pL.get<Teuchos::Array<double> >("rap: shift array")();
189  }
190  if (pL.isParameter("rap: cfl array") && pL.get<Teuchos::Array<double> >("rap: cfl array").size() > 0) {
191  // Do we have an array of CFLs? If so, we calculated the shifts from them.
192  Teuchos::ArrayView<const double> CFLs = pL.get<Teuchos::Array<double> >("rap: cfl array")();
193  if (fineLevel.GetLevelID() == 0) {
194  double dt = Get<double>(fineLevel, "deltaT");
195  double cfl = Get<double>(fineLevel, "cfl");
196  double ts_at_cfl1 = dt / cfl;
197  myshifts.resize(CFLs.size());
198  Teuchos::Array<double> myCFLs(CFLs.size());
199  myCFLs[0] = cfl;
200 
201  // Never make the CFL bigger
202  for (int i = 1; i < (int)CFLs.size(); i++)
203  myCFLs[i] = (CFLs[i] > cfl) ? cfl : CFLs[i];
204 
205  {
206  std::ostringstream ofs;
207  ofs << "RAPShiftFactory: CFL schedule = ";
208  for (int i = 0; i < (int)CFLs.size(); i++)
209  ofs << " " << myCFLs[i];
210  GetOStream(Statistics0) << ofs.str() << std::endl;
211  }
212  GetOStream(Statistics0) << "RAPShiftFactory: Timestep at CFL=1 is " << ts_at_cfl1 << " " << std::endl;
213 
214  // The shift array needs to be 1/dt
215  for (int i = 0; i < (int)myshifts.size(); i++)
216  myshifts[i] = 1.0 / (ts_at_cfl1 * myCFLs[i]);
217  doubleShifts = myshifts();
218 
219  {
220  std::ostringstream ofs;
221  ofs << "RAPShiftFactory: shift schedule = ";
222  for (int i = 0; i < (int)doubleShifts.size(); i++)
223  ofs << " " << doubleShifts[i];
224  GetOStream(Statistics0) << ofs.str() << std::endl;
225  }
226  Set(coarseLevel, "cfl-based shift array", myshifts);
227  } else {
228  myshifts = Get<Teuchos::ArrayRCP<double> >(fineLevel, "cfl-based shift array");
229  doubleShifts = myshifts();
230  Set(coarseLevel, "cfl-based shift array", myshifts);
231  // NOTE: If we're not on level zero, then we should have a shift array
232  }
233  }
234 
235  // Inputs: K, M, P
236  // Note: In the low-storage case we do not keep a separate "K", we just use A
237  RCP<Matrix> K;
238  RCP<Matrix> M;
239  RCP<Vector> Mdiag;
240 
241  if (use_low_storage)
242  K = Get<RCP<Matrix> >(fineLevel, "A");
243  else
244  K = Get<RCP<Matrix> >(fineLevel, "K");
245  if (!M_is_diagonal)
246  M = Get<RCP<Matrix> >(fineLevel, "M");
247  else
248  Mdiag = Get<RCP<Vector> >(fineLevel, "Mdiag");
249 
250  RCP<Matrix> P = Get<RCP<Matrix> >(coarseLevel, "P");
251 
252  // Build Kc = RKP, Mc = RMP
253  RCP<Matrix> KP, MP;
254 
255  // Reuse pattern if available (multiple solve)
256  // FIXME: Old style reuse doesn't work any more
257  // if (IsAvailable(coarseLevel, "AP Pattern")) {
258  // KP = Get< RCP<Matrix> >(coarseLevel, "AP Pattern");
259  // MP = Get< RCP<Matrix> >(coarseLevel, "AP Pattern");
260  // }
261 
262  {
263  SubFactoryMonitor subM(*this, "MxM: K x P", coarseLevel);
265  if (!M_is_diagonal) {
267  } else {
269  MP->leftScale(*Mdiag);
270  }
271 
272  Set(coarseLevel, "AP Pattern", KP);
273  }
274 
275  bool doOptimizedStorage = true;
276 
277  RCP<Matrix> Ac, Kc, Mc;
278 
279  // Reuse pattern if available (multiple solve)
280  // if (IsAvailable(coarseLevel, "RAP Pattern"))
281  // Ac = Get< RCP<Matrix> >(coarseLevel, "RAP Pattern");
282 
283  bool doFillComplete = true;
284  if (implicitTranspose_) {
285  SubFactoryMonitor m2(*this, "MxM: P' x (KP) (implicit)", coarseLevel);
286  Kc = Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(*P, true, *KP, false, Kc, GetOStream(Statistics2), doFillComplete, doOptimizedStorage);
287  Mc = Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(*P, true, *MP, false, Mc, GetOStream(Statistics2), doFillComplete, doOptimizedStorage);
288  } else {
289  RCP<Matrix> R = Get<RCP<Matrix> >(coarseLevel, "R");
290  SubFactoryMonitor m2(*this, "MxM: R x (KP) (explicit)", coarseLevel);
291  Kc = Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(*R, false, *KP, false, Kc, GetOStream(Statistics2), doFillComplete, doOptimizedStorage);
292  Mc = Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(*R, false, *MP, false, Mc, GetOStream(Statistics2), doFillComplete, doOptimizedStorage);
293  }
294 
295  // Get the shift
296  // FIXME - We should really get rid of the shifts array and drive this the same way everything else works
297  // If we're using the recursive "low storage" version, we need to shift by ( \prod_{i=1}^k shift[i] - \prod_{i=1}^{k-1} shift[i]) to
298  // get the recursive relationships correct
299  int level = coarseLevel.GetLevelID();
301  if (!use_low_storage) {
302  // High Storage version
303  if (level < (int)shifts_.size())
304  shift = shifts_[level];
305  else
306  shift = Teuchos::as<Scalar>(pL.get<double>("rap: shift"));
307  } else {
308  // Low Storage Version
309  if (level < (int)shifts_.size()) {
310  if (level == 1)
311  shift = shifts_[level];
312  else {
314  for (int i = 1; i < level - 1; i++) {
315  prod1 *= shifts_[i];
316  }
317  shift = (prod1 * shifts_[level] - prod1);
318  }
319  } else if (doubleShifts.size() != 0) {
320  double d_shift = 0.0;
321  if (level < doubleShifts.size())
322  d_shift = doubleShifts[level] - doubleShifts[level - 1];
323 
324  if (d_shift < 0.0)
325  GetOStream(Warnings1) << "WARNING: RAPShiftFactory has detected a negative shift... This implies a less stable coarse grid." << std::endl;
326  shift = Teuchos::as<Scalar>(d_shift);
327  } else {
328  double base_shift = pL.get<double>("rap: shift");
329  if (level == 1)
330  shift = Teuchos::as<Scalar>(base_shift);
331  else
332  shift = Teuchos::as<Scalar>(pow(base_shift, level) - pow(base_shift, level - 1));
333  }
334  }
335  GetOStream(Runtime0) << "RAPShiftFactory: Using shift " << shift << std::endl;
336 
337  // recombine to get K+shift*M
338  {
339  SubFactoryMonitor m2(*this, "Add: RKP + s*RMP", coarseLevel);
341  Ac->fillComplete();
342  }
343 
344  Teuchos::ArrayView<const double> relativeFloor = pL.get<Teuchos::Array<double> >("rap: relative diagonal floor")();
345  if (relativeFloor.size() > 0)
347 
348  bool repairZeroDiagonals = pL.get<bool>("RepairMainDiagonal") || pL.get<bool>("rap: fix zero diagonals");
349  bool checkAc = pL.get<bool>("CheckMainDiagonal") || pL.get<bool>("rap: fix zero diagonals");
350  ;
351  if (checkAc || repairZeroDiagonals)
352  Xpetra::MatrixUtils<SC, LO, GO, NO>::CheckRepairMainDiagonal(Ac, repairZeroDiagonals, GetOStream(Warnings1));
353 
354  RCP<ParameterList> params = rcp(new ParameterList());
355  ;
356  params->set("printLoadBalancingInfo", true);
357  GetOStream(Statistics0) << PerfUtils::PrintMatrixInfo(*Ac, "Ac", params);
358 
359  Set(coarseLevel, "A", Ac);
360  // We only need K in the 'high storage' mode
361  if (!use_low_storage)
362  Set(coarseLevel, "K", Kc);
363 
364  if (!M_is_diagonal) {
365  Set(coarseLevel, "M", Mc);
366  } else {
367  // If M is diagonal, then we only pass that part down the hierarchy
368  // NOTE: Should we be doing some kind of rowsum instead?
370  Mc->getLocalDiagCopy(*Mcv);
371  Set(coarseLevel, "Mdiag", Mcv);
372  }
373 
374  // Set(coarseLevel, "RAP Pattern", Ac);
375  }
376 
377  if (transferFacts_.begin() != transferFacts_.end()) {
378  SubFactoryMonitor m(*this, "Projections", coarseLevel);
379 
380  // call Build of all user-given transfer factories
381  for (std::vector<RCP<const FactoryBase> >::const_iterator it = transferFacts_.begin(); it != transferFacts_.end(); ++it) {
382  RCP<const FactoryBase> fac = *it;
383  GetOStream(Runtime0) << "RAPShiftFactory: call transfer factory: " << fac->description() << std::endl;
384  fac->CallBuild(coarseLevel);
385  // AP (11/11/13): I am not sure exactly why we need to call Release, but we do need it to get rid
386  // of dangling data for CoordinatesTransferFactory
387  coarseLevel.Release(*fac);
388  }
389  }
390 }
391 
392 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
394  // check if it's a TwoLevelFactoryBase based transfer factory
395  TEUCHOS_TEST_FOR_EXCEPTION(Teuchos::rcp_dynamic_cast<const TwoLevelFactoryBase>(factory) == Teuchos::null, Exceptions::BadCast, "MueLu::RAPShiftFactory::AddTransferFactory: Transfer factory is not derived from TwoLevelFactoryBase. This is very strange. (Note: you can remove this exception if there's a good reason for)");
396  transferFacts_.push_back(factory);
397 }
398 
399 } // namespace MueLu
400 
401 #define MUELU_RAPSHIFTFACTORY_SHORT
402 #endif // MUELU_RAPSHIFTFACTORY_DEF_HPP
Exception indicating invalid cast attempted.
void Build(Level &fineLevel, Level &coarseLevel) const
Build an object with this factory.
virtual void CallBuild(Level &requestedLevel) const =0
void Release(const FactoryBase &factory)
Decrement the storage counter for all the inputs of a factory.
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)
size_type size() const
One-liner description of what is happening.
RCP< const ParameterList > GetValidParameterList() const
Return a const parameter list of valid parameters that setParameterList() will accept.
size_type size() const
static void CheckRepairMainDiagonal(RCP< Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node >> &Ac, bool const &repairZeroDiagonals, Teuchos::FancyOStream &fos, const typename Teuchos::ScalarTraits< Scalar >::magnitudeType threshold=Teuchos::ScalarTraits< typename Teuchos::ScalarTraits< Scalar >::magnitudeType >::zero())
static const NoFactory * get()
Print even more statistics.
Additional warnings.
void resize(const size_type n, const T &val=T())
bool isParameter(const std::string &name) const
void DeclareInput(Level &fineLevel, Level &coarseLevel) const
Input.
Print statistics that do not involve significant additional computation.
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
Timer to be used in factories. Similar to SubMonitor but adds a timer level by level.
static RCP< Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > > BuildCopy(const RCP< const Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > > A)
static std::string PrintMatrixInfo(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
static RCP< Vector > Build(const Teuchos::RCP< const Map > &map, bool zeroOut=true)
static void TwoMatrixAdd(const Matrix &A, bool transposeA, SC alpha, Matrix &B, SC beta)
void AddTransferFactory(const RCP< const FactoryBase > &factory)
Add transfer factory in the end of list of transfer factories in RepartitionAcFactory.
static void Multiply(const Matrix &A, bool transposeA, const Matrix &B, bool transposeB, Matrix &C, bool call_FillComplete_on_result=true, bool doOptimizeStorage=true, const std::string &label=std::string(), const RCP< ParameterList > &params=null)
int GetLevelID() const
Return level number.
Definition: MueLu_Level.cpp:76
Exception throws to report errors in the internal logical of the program.
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.
bool IsAvailable(const std::string &ename, const FactoryBase *factory=NoFactory::get()) const
Test whether a need&#39;s value has been saved.
#define SET_VALID_ENTRY(name)