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 = double, class LocalOrdinal = int, class GlobalOrdinal = LocalOrdinal, class Node = KokkosClassic::DefaultNode::DefaultNodeType>
78  class HierarchyManager : public HierarchyFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node> {
79 #undef MUELU_HIERARCHYMANAGER_SHORT
80 #include "MueLu_UseShortNames.hpp"
81  typedef std::pair<std::string, const FactoryBase*> keep_pair;
82 
83  public:
84 
86  HierarchyManager(int numDesiredLevel = MasterList::getDefault<int>("max levels")) :
87  numDesiredLevel_ (numDesiredLevel),
88  maxCoarseSize_ (MasterList::getDefault<int>("coarse: max size")),
90  doPRrebalance_ (MasterList::getDefault<bool>("repartition: rebalance P and R")),
91  implicitTranspose_ (MasterList::getDefault<bool>("transpose: use implicit")),
92  graphOutputLevel_(-1) { }
93 
95  virtual ~HierarchyManager() { }
96 
98  void AddFactoryManager(int startLevel, int numDesiredLevel, RCP<FactoryManagerBase> manager) {
99  const int lastLevel = startLevel + numDesiredLevel - 1;
100  if (levelManagers_.size() < lastLevel + 1)
101  levelManagers_.resize(lastLevel + 1);
102 
103  for (int iLevel = startLevel; iLevel <= lastLevel; iLevel++)
104  levelManagers_[iLevel] = manager;
105  }
106 
109  // NOTE: last levelManager is used for all the remaining levels
110  return (levelID >= levelManagers_.size() ? levelManagers_[levelManagers_.size()-1] : levelManagers_[levelID]);
111  }
112 
114  size_t getNumFactoryManagers() const {
115  return levelManagers_.size();
116  }
117 
119  void CheckConfig() {
120  for (int i = 0; i < levelManagers_.size(); i++)
121  TEUCHOS_TEST_FOR_EXCEPTION(levelManagers_[i] == Teuchos::null, Exceptions::RuntimeError, "MueLu:HierarchyConfig::CheckConfig(): Undefined configuration for level:");
122  }
123 
125 
126  virtual RCP<Hierarchy> CreateHierarchy() const {
127  return rcp(new Hierarchy());
128  }
129 
130  virtual RCP<Hierarchy> CreateHierarchy(const std::string& label) const {
131  return rcp(new Hierarchy(label));
132  }
133 
135  virtual void SetupHierarchy(Hierarchy& H) const {
136  TEUCHOS_TEST_FOR_EXCEPTION(!H.GetLevel(0)->IsAvailable("A"), Exceptions::RuntimeError, "No fine level operator");
137 
138  RCP<Level> l0 = H.GetLevel(0);
139  RCP<Operator> Op = l0->Get<RCP<Operator> >("A");
140  // Check that user-supplied nullspace dimension is at least as large as NumPDEs
141  if (l0->IsAvailable("Nullspace")) {
142  RCP<Matrix> A = Teuchos::rcp_dynamic_cast<Matrix>(Op);
143  if (A != Teuchos::null) {
144  Teuchos::RCP<MultiVector> nullspace = l0->Get<RCP<MultiVector> >("Nullspace");
145  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() << ")");
146  } else {
147  this->GetOStream(Warnings0) << "Skipping dimension check of user-supplied nullspace because user-supplied operator is not a matrix" << std::endl;
148  }
149  }
150 
151 #ifdef HAVE_MUELU_DEBUG
152  // Reset factories' data used for debugging
153  for (int i = 0; i < levelManagers_.size(); i++)
154  levelManagers_[i]->ResetDebugData();
155 
156 #endif
157 
158  // Setup Matrix
159  // TODO: I should certainly undo this somewhere...
160 
161  Xpetra::UnderlyingLib lib = Op->getDomainMap()->lib();
162  H.setlib(lib);
163 
164  SetupOperator(*Op);
165  SetupExtra(H);
166 
167  // Setup Hierarchy
170  if (graphOutputLevel_ >= 0)
171  H.EnableGraphDumping("dep_graph.dot", graphOutputLevel_);
172 
174  RCP<Matrix> Amat = rcp_dynamic_cast<Matrix>(Op);
175 
176  if (!Amat.is_null()) {
177  RCP<ParameterList> params = rcp(new ParameterList());
178  params->set("printLoadBalancingInfo", true);
179  params->set("printCommInfo", true);
180 
182  } else {
183  VerboseObject::GetOStream(Warnings1) << "Fine level operator is not a matrix, statistics are not available" << std::endl;
184  }
185  }
186 
189 
190  H.Clear();
191 
192  // There are few issues with using Keep in the interpreter:
193  // 1. Hierarchy::Keep interface takes a name and a factory. If
194  // factories are different on different levels, the AddNewLevel() call
195  // in Hierarchy does not work properly, as it assume that factories are
196  // the same.
197  // 2. FactoryManager does not have a Keep option, only Hierarchy and
198  // Level have it
199  // 3. Interpreter constructs factory managers, but not levels. So we
200  // cannot set up Keep flags there.
201  //
202  // The solution implemented here does the following:
203  // 1. Construct hierarchy with dummy levels. This avoids
204  // Hierarchy::AddNewLevel() calls which will propagate wrong
205  // inheritance.
206  // 2. Interpreter constructs keep_ array with names and factories for
207  // that level
208  // 3. For each level, we call Keep(name, factory) for each keep_
209  for (int i = 0; i < numDesiredLevel_; i++) {
210  std::map<int, std::vector<keep_pair> >::const_iterator it = keep_.find(i);
211  if (it != keep_.end()) {
212  RCP<Level> l = H.GetLevel(i);
213  const std::vector<keep_pair>& keeps = it->second;
214  for (size_t j = 0; j < keeps.size(); j++)
215  l->Keep(keeps[j].first, keeps[j].second);
216  }
217  if (i < numDesiredLevel_-1) {
218  RCP<Level> newLevel = rcp(new Level());
219  H.AddLevel(newLevel);
220  }
221  }
225  ExportDataSetKeepFlags(H, nullspaceToPrint_, "Nullspace");
226  ExportDataSetKeepFlags(H, coordinatesToPrint_, "Coordinates");
227 #ifdef HAVE_MUELU_INTREPID2
228  ExportDataSetKeepFlags(H,elementToNodeMapsToPrint_, "pcoarsen: element to node map");
229 #endif
230 
231  int levelID = 0;
232  int lastLevelID = numDesiredLevel_ - 1;
233  bool isLastLevel = false;
234 
235  while (!isLastLevel) {
236  bool r = H.Setup(levelID,
237  LvlMngr(levelID-1, lastLevelID),
238  LvlMngr(levelID, lastLevelID),
239  LvlMngr(levelID+1, lastLevelID));
240 
241  isLastLevel = r || (levelID == lastLevelID);
242  levelID++;
243  }
244  // FIXME: Should allow specification of NumVectors on parameterlist
247 
248  // When we reuse hierarchy, it is necessary that we don't
249  // change the number of levels. We also cannot make requests
250  // for coarser levels, because we don't construct all the
251  // data on previous levels. For instance, let's say our first
252  // run constructed three levels. If we try to do requests during
253  // next setup for the fourth level, it would need Aggregates
254  // which we didn't construct for level 3 because we reused P.
255  // To fix this situation, we change the number of desired levels
256  // here.
257  numDesiredLevel_ = levelID;
258 
259  WriteData<Matrix>(H, matricesToPrint_, "A");
260  WriteData<Matrix>(H, prolongatorsToPrint_, "P");
261  WriteData<Matrix>(H, restrictorsToPrint_, "R");
262  WriteData<MultiVector>(H, nullspaceToPrint_, "Nullspace");
263  WriteData<MultiVector>(H, coordinatesToPrint_, "Coordinates");
264 #ifdef HAVE_MUELU_INTREPID2
265  typedef Kokkos::DynRankView<LocalOrdinal,typename Node::device_type> FCi;
266  WriteDataFC<FCi>(H,elementToNodeMapsToPrint_, "pcoarsen: element to node map","el2node");
267 #endif
268 
269 
270  } //SetupHierarchy
271 
273 
274  typedef std::map<std::string, RCP<const FactoryBase> > FactoryMap;
275 
276  protected: //TODO: access function
277 
279  virtual void SetupOperator(Operator& /* Op */) const { }
280 
282  // TODO: merge with SetupMatrix ?
283  virtual void SetupExtra(Hierarchy& /* H */) const { }
284 
285  // TODO this was private
286  // Used in SetupHierarchy() to access levelManagers_
287  // Inputs i=-1 and i=size() are allowed to simplify calls to hierarchy->Setup()
288  Teuchos::RCP<FactoryManagerBase> LvlMngr(int levelID, int lastLevelID) const {
289  // NOTE: the order of 'if' statements is important
290  if (levelID == -1) // levelID = -1 corresponds to the finest level
291  return Teuchos::null;
292 
293  if (levelID == lastLevelID+1) // levelID = 'lastLevelID+1' corresponds to the last level (i.e., no nextLevel)
294  return Teuchos::null;
295 
296  if (levelManagers_.size() == 0) { // default factory manager.
297  // The default manager is shared across levels, initialized only if needed and deleted with the HierarchyManager
298  static RCP<FactoryManagerBase> defaultMngr = rcp(new FactoryManager());
299  return defaultMngr;
300  }
301 
302  return GetFactoryManager(levelID);
303  }
304 
305  // Hierarchy parameters
306  mutable int numDesiredLevel_;
318 
319  std::map<int, std::vector<keep_pair> > keep_;
320 
321  private:
322  // Set the keep flags for Export Data
323  void ExportDataSetKeepFlags(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name) const {
324  for (int i = 0; i < data.size(); ++i) {
325  if (data[i] < H.GetNumLevels()) {
326  RCP<Level> L = H.GetLevel(data[i]);
327  if(!L.is_null() && data[i] < levelManagers_.size())
328  L->AddKeepFlag(name, &*levelManagers_[data[i]]->GetFactory(name));
329  }
330  }
331  }
332 
333 
334  template<class T>
335  void WriteData(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name) const {
336  for (int i = 0; i < data.size(); ++i) {
337  std::string fileName = name + "_" + Teuchos::toString(data[i]) + ".m";
338 
339  if (data[i] < H.GetNumLevels()) {
340  RCP<Level> L = H.GetLevel(data[i]);
341  if (data[i] < levelManagers_.size() && L->IsAvailable(name,&*levelManagers_[data[i]]->GetFactory(name))) {
342  // Try generating factory
343  RCP<T> M = L->template Get< RCP<T> >(name,&*levelManagers_[data[i]]->GetFactory(name));
344  if (!M.is_null()) {
346  }
347  }
348  else if (L->IsAvailable(name)) {
349  // Try nofactory
350  RCP<T> M = L->template Get< RCP<T> >(name);
351  if (!M.is_null()) {
353  }
354  }
355 
356  }
357  }
358  }
359 
360 
361  template<class T>
362  void WriteDataFC(Hierarchy& H, const Teuchos::Array<int>& data, const std::string& name, const std::string & ofname) const {
363  for (int i = 0; i < data.size(); ++i) {
364  const std::string fileName = ofname + "_" + Teuchos::toString(data[i]) + ".m";
365 
366  if (data[i] < H.GetNumLevels()) {
367  RCP<Level> L = H.GetLevel(data[i]);
368 
369  if (L->IsAvailable(name)) {
370  RCP<T> M = L->template Get< RCP<T> >(name);
371  if (!M.is_null()) {
372  RCP<Matrix> A = L->template Get<RCP<Matrix> >("A");
373  RCP<const CrsGraph> AG = A->getCrsGraph();
374  WriteFieldContainer<T>(fileName,*M,*AG->getColMap());
375  }
376  }
377  }
378  }
379  }
380 
381  // For dumping an IntrepidPCoarsening element-to-node map to disk
382  template<class T>
383  void WriteFieldContainer(const std::string& fileName, T & fcont,const Map &colMap) const {
384  typedef LocalOrdinal LO;
385  typedef GlobalOrdinal GO;
386  typedef Node NO;
387  typedef Xpetra::MultiVector<GO,LO,GO,NO> GOMultiVector;
388 
389  size_t num_els = (size_t) fcont.extent(0);
390  size_t num_vecs =(size_t) fcont.extent(1);
391 
392  // Generate rowMap
393  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());
394 
395  // Fill multivector to use *petra dump routines
397 
398  for(size_t j=0; j<num_vecs; j++) {
399  Teuchos::ArrayRCP<GO> v = vec->getDataNonConst(j);
400  for(size_t i=0; i<num_els; i++)
401  v[i] = colMap.getGlobalElement(fcont(i,j));
402  }
403 
404  Xpetra::IO<GO,LO,GO,NO>::Write(fileName,*vec);
405  }
406 
407 
408 
409  // Levels
410  Array<RCP<FactoryManagerBase> > levelManagers_; // one FactoryManager per level (the last levelManager is used for all the remaining levels)
411 
412  }; // class HierarchyManager
413 
414 } // namespace MueLu
415 
416 #define MUELU_HIERARCHYMANAGER_SHORT
417 #endif // MUELU_HIERARCHYMANAGER_HPP
418 
419 //TODO: split into _decl/_def
420 // 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_
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
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
GlobalOrdinal GO
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_
static void Write(const std::string &fileName, const Xpetra::Map< LocalOrdinal, GlobalOrdinal, Node > &M)
void SetMaxCoarseSize(Xpetra::global_size_t maxCoarseSize)
void AddFactoryManager(int startLevel, int numDesiredLevel, RCP< FactoryManagerBase > manager)
LocalOrdinal LO
One-liner description of what is happening.
void Clear(int startLevel=0)
Clear impermanent data from previous setup.
std::map< std::string, RCP< const FactoryBase > > FactoryMap
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.
void WriteData(Hierarchy &H, const Teuchos::Array< int > &data, const std::string &name) const
static void SetDefaultVerbLevel(const VerbLevel defaultVerbLevel)
Set the default (global) verbosity level.
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)
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Teuchos::Array< int > nullspaceToPrint_
bool IsPrint(MsgType type, int thisProcRankOnly=-1) const
Find out whether we need to print out information for a specific message type.
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)
size_t global_size_t
virtual void SetupOperator(Operator &) const
Setup Matrix object.
void SetImplicitTranspose(const bool &implicit)
Teuchos::Array< int > prolongatorsToPrint_
size_type size() const
static Teuchos::RCP< MultiVector< Scalar, LocalOrdinal, GlobalOrdinal, Node > > Build(const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &map, size_t NumVectors, bool zeroOut=true)
Teuchos::Array< int > coordinatesToPrint_
Node NO
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.
static Teuchos::RCP< Map< LocalOrdinal, GlobalOrdinal, Node > > Build(UnderlyingLib lib, global_size_t numGlobalElements, GlobalOrdinal indexBase, const Teuchos::RCP< const Teuchos::Comm< int > > &comm, LocalGlobal lg=Xpetra::GloballyDistributed)
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