MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_HierarchyManager.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_HIERARCHYMANAGER_DECL_HPP
47 #define MUELU_HIERARCHYMANAGER_DECL_HPP
48 
49 #include <string>
50 #include <map>
51 
52 #include <Teuchos_Array.hpp>
53 
54 #include <Xpetra_Operator.hpp>
55 #include <Xpetra_IO.hpp>
56 
57 #include "MueLu_ConfigDefs.hpp"
58 
59 #include "MueLu_Exceptions.hpp"
60 #include "MueLu_Hierarchy.hpp"
62 #include "MueLu_Level.hpp"
63 #include "MueLu_MasterList.hpp"
64 #include "MueLu_PerfUtils.hpp"
65 
66 #ifdef HAVE_MUELU_INTREPID2
67 #include "Kokkos_DynRankView.hpp"
68 #endif
69 
70 namespace MueLu {
71 
72  // This class stores the configuration of a Hierarchy.
73  // The class also provides an algorithm to build a Hierarchy from the configuration.
74  //
75  // See also: FactoryManager
76  //
77  template <class Scalar = DefaultScalar,
80  class Node = DefaultNode>
81  class HierarchyManager : public HierarchyFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node> {
82 #undef MUELU_HIERARCHYMANAGER_SHORT
83 #include "MueLu_UseShortNames.hpp"
84  typedef std::pair<std::string, const FactoryBase*> keep_pair;
85 
86  public:
87 
89  HierarchyManager(int numDesiredLevel = MasterList::getDefault<int>("max levels")) :
90  numDesiredLevel_ (numDesiredLevel),
91  maxCoarseSize_ (MasterList::getDefault<int>("coarse: max size")),
93  doPRrebalance_ (MasterList::getDefault<bool>("repartition: rebalance P and R")),
94  implicitTranspose_ (MasterList::getDefault<bool>("transpose: use implicit")),
95  fuseProlongationAndUpdate_ (MasterList::getDefault<bool>("fuse prolongation and update")),
96  sizeOfMultiVectors_ (MasterList::getDefault<int>("number of vectors")),
97  graphOutputLevel_(-1) { }
98 
100  virtual ~HierarchyManager() { }
101 
103  void AddFactoryManager(int startLevel, int numDesiredLevel, RCP<FactoryManagerBase> manager) {
104  const int lastLevel = startLevel + numDesiredLevel - 1;
105  if (levelManagers_.size() < lastLevel + 1)
106  levelManagers_.resize(lastLevel + 1);
107 
108  for (int iLevel = startLevel; iLevel <= lastLevel; iLevel++)
109  levelManagers_[iLevel] = manager;
110  }
111 
114  // NOTE: last levelManager is used for all the remaining levels
115  return (levelID >= levelManagers_.size() ? levelManagers_[levelManagers_.size()-1] : levelManagers_[levelID]);
116  }
117 
119  size_t getNumFactoryManagers() const {
120  return levelManagers_.size();
121  }
122 
124  void CheckConfig() {
125  for (int i = 0; i < levelManagers_.size(); i++)
126  TEUCHOS_TEST_FOR_EXCEPTION(levelManagers_[i] == Teuchos::null, Exceptions::RuntimeError, "MueLu:HierarchyConfig::CheckConfig(): Undefined configuration for level:");
127  }
128 
130 
131  virtual RCP<Hierarchy> CreateHierarchy() const {
132  return rcp(new Hierarchy());
133  }
134 
135  virtual RCP<Hierarchy> CreateHierarchy(const std::string& label) const {
136  return rcp(new Hierarchy(label));
137  }
138 
140  virtual void SetupHierarchy(Hierarchy& H) const {
141  TEUCHOS_TEST_FOR_EXCEPTION(!H.GetLevel(0)->IsAvailable("A"), Exceptions::RuntimeError, "No fine level operator");
142 
143  RCP<Level> l0 = H.GetLevel(0);
144  RCP<Operator> Op = l0->Get<RCP<Operator> >("A");
145  // Check that user-supplied nullspace dimension is at least as large as NumPDEs
146  if (l0->IsAvailable("Nullspace")) {
147  RCP<Matrix> A = Teuchos::rcp_dynamic_cast<Matrix>(Op);
148  if (A != Teuchos::null) {
149  Teuchos::RCP<MultiVector> nullspace = l0->Get<RCP<MultiVector> >("Nullspace");
150  TEUCHOS_TEST_FOR_EXCEPTION(static_cast<size_t>(A->GetFixedBlockSize()) > nullspace->getNumVectors(), Exceptions::RuntimeError, "user-provided nullspace has fewer vectors (" << nullspace->getNumVectors() << ") than number of PDE equations (" << A->GetFixedBlockSize() << ")");
151  } else {
152  this->GetOStream(Warnings0) << "Skipping dimension check of user-supplied nullspace because user-supplied operator is not a matrix" << std::endl;
153  }
154  }
155 
156 #ifdef HAVE_MUELU_DEBUG
157  // Reset factories' data used for debugging
158  for (int i = 0; i < levelManagers_.size(); i++)
159  levelManagers_[i]->ResetDebugData();
160 
161 #endif
162 
163  // Setup Matrix
164  // TODO: I should certainly undo this somewhere...
165 
166  Xpetra::UnderlyingLib lib = Op->getDomainMap()->lib();
167  H.setlib(lib);
168 
169  SetupOperator(*Op);
170  SetupExtra(H);
171 
172  // Setup Hierarchy
175  if (graphOutputLevel_ >= 0)
176  H.EnableGraphDumping("dep_graph.dot", graphOutputLevel_);
177 
179  RCP<Matrix> Amat = rcp_dynamic_cast<Matrix>(Op);
180 
181  if (!Amat.is_null()) {
182  RCP<ParameterList> params = rcp(new ParameterList());
183  params->set("printLoadBalancingInfo", true);
184  params->set("printCommInfo", true);
185 
187  } else {
188  VerboseObject::GetOStream(Warnings1) << "Fine level operator is not a matrix, statistics are not available" << std::endl;
189  }
190  }
191 
195 
196  H.Clear();
197 
198  // There are few issues with using Keep in the interpreter:
199  // 1. Hierarchy::Keep interface takes a name and a factory. If
200  // factories are different on different levels, the AddNewLevel() call
201  // in Hierarchy does not work properly, as it assume that factories are
202  // the same.
203  // 2. FactoryManager does not have a Keep option, only Hierarchy and
204  // Level have it
205  // 3. Interpreter constructs factory managers, but not levels. So we
206  // cannot set up Keep flags there.
207  //
208  // The solution implemented here does the following:
209  // 1. Construct hierarchy with dummy levels. This avoids
210  // Hierarchy::AddNewLevel() calls which will propagate wrong
211  // inheritance.
212  // 2. Interpreter constructs keep_ array with names and factories for
213  // that level
214  // 3. For each level, we call Keep(name, factory) for each keep_
215  for (int i = 0; i < numDesiredLevel_; i++) {
216  std::map<int, std::vector<keep_pair> >::const_iterator it = keep_.find(i);
217  if (it != keep_.end()) {
218  RCP<Level> l = H.GetLevel(i);
219  const std::vector<keep_pair>& keeps = it->second;
220  for (size_t j = 0; j < keeps.size(); j++)
221  l->Keep(keeps[j].first, keeps[j].second);
222  }
223  if (i < numDesiredLevel_-1) {
224  RCP<Level> newLevel = rcp(new Level());
225  H.AddLevel(newLevel);
226  }
227  }
231  ExportDataSetKeepFlags(H, nullspaceToPrint_, "Nullspace");
232  ExportDataSetKeepFlags(H, coordinatesToPrint_, "Coordinates");
233 #ifdef HAVE_MUELU_INTREPID2
234  ExportDataSetKeepFlags(H,elementToNodeMapsToPrint_, "pcoarsen: element to node map");
235 #endif
236 
237  int levelID = 0;
238  int lastLevelID = numDesiredLevel_ - 1;
239  bool isLastLevel = false;
240 
241  while (!isLastLevel) {
242  bool r = H.Setup(levelID,
243  LvlMngr(levelID-1, lastLevelID),
244  LvlMngr(levelID, lastLevelID),
245  LvlMngr(levelID+1, lastLevelID));
246 
247  isLastLevel = r || (levelID == lastLevelID);
248  levelID++;
249  }
250  if (!matvecParams_.is_null())
254 
255  // When we reuse hierarchy, it is necessary that we don't
256  // change the number of levels. We also cannot make requests
257  // for coarser levels, because we don't construct all the
258  // data on previous levels. For instance, let's say our first
259  // run constructed three levels. If we try to do requests during
260  // next setup for the fourth level, it would need Aggregates
261  // which we didn't construct for level 3 because we reused P.
262  // To fix this situation, we change the number of desired levels
263  // here.
264  numDesiredLevel_ = levelID;
265 
266  WriteData<Matrix>(H, matricesToPrint_, "A");
267  WriteData<Matrix>(H, prolongatorsToPrint_, "P");
268  WriteData<Matrix>(H, restrictorsToPrint_, "R");
269  WriteData<MultiVector>(H, nullspaceToPrint_, "Nullspace");
270  WriteData<MultiVector>(H, coordinatesToPrint_, "Coordinates");
271 #ifdef HAVE_MUELU_INTREPID2
272  typedef Kokkos::DynRankView<LocalOrdinal,typename Node::device_type> FCi;
273  WriteDataFC<FCi>(H,elementToNodeMapsToPrint_, "pcoarsen: element to node map","el2node");
274 #endif
275 
276 
277  } //SetupHierarchy
278 
280 
281  typedef std::map<std::string, RCP<const FactoryBase> > FactoryMap;
282 
283  protected: //TODO: access function
284 
286  virtual void SetupOperator(Operator& /* Op */) const { }
287 
289  // TODO: merge with SetupMatrix ?
290  virtual void SetupExtra(Hierarchy& /* H */) const { }
291 
292  // TODO this was private
293  // Used in SetupHierarchy() to access levelManagers_
294  // Inputs i=-1 and i=size() are allowed to simplify calls to hierarchy->Setup()
295  Teuchos::RCP<FactoryManagerBase> LvlMngr(int levelID, int lastLevelID) const {
296  // NOTE: the order of 'if' statements is important
297  if (levelID == -1) // levelID = -1 corresponds to the finest level
298  return Teuchos::null;
299 
300  if (levelID == lastLevelID+1) // levelID = 'lastLevelID+1' corresponds to the last level (i.e., no nextLevel)
301  return Teuchos::null;
302 
303  if (levelManagers_.size() == 0) { // default factory manager.
304  // The default manager is shared across levels, initialized only if needed and deleted with the HierarchyManager
305  static RCP<FactoryManagerBase> defaultMngr = rcp(new FactoryManager());
306  return defaultMngr;
307  }
308 
309  return GetFactoryManager(levelID);
310  }
311 
312  // Hierarchy parameters
313  mutable int numDesiredLevel_;
314  Xpetra::global_size_t maxCoarseSize_;
328 
329  std::map<int, std::vector<keep_pair> > keep_;
330 
331  private:
332  // Set the keep flags for Export Data
333  void ExportDataSetKeepFlags(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name) const {
334  for (int i = 0; i < data.size(); ++i) {
335  if (data[i] < H.GetNumLevels()) {
336  RCP<Level> L = H.GetLevel(data[i]);
337  if(!L.is_null() && data[i] < levelManagers_.size())
338  L->AddKeepFlag(name, &*levelManagers_[data[i]]->GetFactory(name));
339  }
340  }
341  }
342 
343 
344  template<class T>
345  void WriteData(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name) const {
346  for (int i = 0; i < data.size(); ++i) {
347  std::string fileName;
348  if (H.getObjectLabel() != "")
349  fileName = H.getObjectLabel() + "_" + name + "_" + Teuchos::toString(data[i]) + ".m";
350  else
351  fileName = name + "_" + Teuchos::toString(data[i]) + ".m";
352 
353  if (data[i] < H.GetNumLevels()) {
354  RCP<Level> L = H.GetLevel(data[i]);
355  if (data[i] < levelManagers_.size() && L->IsAvailable(name,&*levelManagers_[data[i]]->GetFactory(name))) {
356  // Try generating factory
357  RCP<T> M = L->template Get< RCP<T> >(name,&*levelManagers_[data[i]]->GetFactory(name));
358  if (!M.is_null()) {
359  Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write(fileName,* M);
360  }
361  }
362  else if (L->IsAvailable(name)) {
363  // Try nofactory
364  RCP<T> M = L->template Get< RCP<T> >(name);
365  if (!M.is_null()) {
366  Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write(fileName,* M);
367  }
368  }
369 
370  }
371  }
372  }
373 
374 
375  template<class T>
376  void WriteDataFC(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name, const std::string & ofname) const {
377  for (int i = 0; i < data.size(); ++i) {
378  const std::string fileName = ofname + "_" + Teuchos::toString(data[i]) + ".m";
379 
380  if (data[i] < H.GetNumLevels()) {
381  RCP<Level> L = H.GetLevel(data[i]);
382 
383  if (L->IsAvailable(name)) {
384  RCP<T> M = L->template Get< RCP<T> >(name);
385  if (!M.is_null()) {
386  RCP<Matrix> A = L->template Get<RCP<Matrix> >("A");
387  RCP<const CrsGraph> AG = A->getCrsGraph();
388  WriteFieldContainer<T>(fileName,*M,*AG->getColMap());
389  }
390  }
391  }
392  }
393  }
394 
395  // For dumping an IntrepidPCoarsening element-to-node map to disk
396  template<class T>
397  void WriteFieldContainer(const std::string& fileName, T & fcont,const Map &colMap) const {
398 
399  size_t num_els = (size_t) fcont.extent(0);
400  size_t num_vecs =(size_t) fcont.extent(1);
401 
402  // Generate rowMap
403  Teuchos::RCP<const Map> rowMap = Xpetra::MapFactory<LO,GO,NO>::Build(colMap.lib(),Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),fcont.extent(0),colMap.getIndexBase(),colMap.getComm());
404 
405  // Fill multivector to use *petra dump routines
406  RCP<GOMultiVector> vec = Xpetra::MultiVectorFactory<GO, LO, GO, NO>::Build(rowMap,num_vecs);
407 
408  for(size_t j=0; j<num_vecs; j++) {
409  Teuchos::ArrayRCP<GO> v = vec->getDataNonConst(j);
410  for(size_t i=0; i<num_els; i++)
411  v[i] = colMap.getGlobalElement(fcont(i,j));
412  }
413 
414  Xpetra::IO<GO,LO,GO,NO>::Write(fileName,*vec);
415  }
416 
417 
418 
419  // Levels
420  Array<RCP<FactoryManagerBase> > levelManagers_; // one FactoryManager per level (the last levelManager is used for all the remaining levels)
421 
422  }; // class HierarchyManager
423 
424 } // namespace MueLu
425 
426 #define MUELU_HIERARCHYMANAGER_SHORT
427 #endif // MUELU_HIERARCHYMANAGER_HPP
428 
429 //TODO: split into _decl/_def
430 // TODO: default value for first param (FactoryManager()) should not be duplicated (code maintainability)
virtual void SetupExtra(Hierarchy &) const
Setup extra data.
Important warning messages (one line)
This class specifies the default factory that should generate some data on a Level if the data does n...
Teuchos::Array< int > matricesToPrint_
MueLu::DefaultLocalOrdinal LocalOrdinal
virtual std::string getObjectLabel() const
KokkosClassic::DefaultNode::DefaultNodeType DefaultNode
RCP< Level > & GetLevel(const int levelID=0)
Retrieve a certain level from hierarchy.
void ExportDataSetKeepFlags(Hierarchy &H, const Teuchos::Array< int > &data, const std::string &name) const
static void SetDefaultVerbLevel(const VerbLevel defaultVerbLevel)
Set the default (global) verbosity level.
virtual RCP< Hierarchy > CreateHierarchy(const std::string &label) const
Create a labeled empty Hierarchy object.
void AddLevel(const RCP< Level > &level)
Add a level at the end of the hierarchy.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Teuchos::Array< int > elementToNodeMapsToPrint_
void SetMaxCoarseSize(Xpetra::global_size_t maxCoarseSize)
void AddFactoryManager(int startLevel, int numDesiredLevel, RCP< FactoryManagerBase > manager)
One-liner description of what is happening.
void Clear(int startLevel=0)
Clear impermanent data from previous setup.
void SetFuseProlongationAndUpdate(const bool &fuse)
std::map< std::string, RCP< const FactoryBase > > FactoryMap
MueLu::DefaultNode Node
Static class that holds the complete list of valid MueLu parameters.
void AllocateLevelMultiVectors(int numvecs)
Teuchos::RCP< FactoryManagerBase > LvlMngr(int levelID, int lastLevelID) const
Print even more statistics.
Additional warnings.
Teuchos::RCP< Teuchos::ParameterList > matvecParams_
void WriteData(Hierarchy &H, const Teuchos::Array< int > &data, const std::string &name) const
size_t getNumFactoryManagers() const
returns number of factory managers stored in levelManagers_ vector.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
MueLu::DefaultScalar Scalar
MueLu::DefaultGlobalOrdinal GlobalOrdinal
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Teuchos::Array< int > nullspaceToPrint_
Array< RCP< FactoryManagerBase > > levelManagers_
RCP< FactoryManagerBase > GetFactoryManager(int levelID) const
static std::string PrintMatrixInfo(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
void SetPRrebalance(bool doPRrebalance)
void SetMatvecParams(RCP< ParameterList > matvecParams)
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
bool IsPrint(MsgType type, int thisProcRankOnly=-1) const
Find out whether we need to print out information for a specific message type.
virtual void SetupOperator(Operator &) const
Setup Matrix object.
void SetImplicitTranspose(const bool &implicit)
Teuchos::Array< int > prolongatorsToPrint_
size_type size() const
Teuchos::Array< int > coordinatesToPrint_
std::map< int, std::vector< keep_pair > > keep_
HierarchyManager(int numDesiredLevel=MasterList::getDefault< int >("max levels"))
Exception throws to report errors in the internal logical of the program.
std::pair< std::string, const FactoryBase * > keep_pair
void describe(Teuchos::FancyOStream &out, const VerbLevel verbLevel=Default) const
Print the Hierarchy with some verbosity level to a FancyOStream object.
void WriteDataFC(Hierarchy &H, const Teuchos::Array< int > &data, const std::string &name, const std::string &ofname) const
void setlib(Xpetra::UnderlyingLib inlib)
Xpetra::global_size_t maxCoarseSize_
virtual RCP< Hierarchy > CreateHierarchy() const
Create an empty Hierarchy object.
bool Setup(int coarseLevelID, const RCP< const FactoryManagerBase > fineLevelManager, const RCP< const FactoryManagerBase > coarseLevelManager, const RCP< const FactoryManagerBase > nextLevelManager=Teuchos::null)
Multi-level setup phase: build a new level of the hierarchy.
void WriteFieldContainer(const std::string &fileName, T &fcont, const Map &colMap) const
Teuchos::Array< int > restrictorsToPrint_
void EnableGraphDumping(const std::string &filename, int levelID=1)
Provides methods to build a multigrid hierarchy and apply multigrid cycles.
std::string toString(const T &t)
virtual void SetupHierarchy(Hierarchy &H) const
Setup Hierarchy object.
bool is_null() const