MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_Level.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_LEVEL_HPP
47 #define MUELU_LEVEL_HPP
48 
49 #include <algorithm> // for swap
50 #include <map> // for _Rb_tree_const_iterator, etc
51 #include <ostream> // for basic_ostream, etc
52 #include <string> // for char_traits, string, etc
53 #include <utility> // for pair
54 
55 #include <Teuchos_Describable.hpp> // for operator<<
56 #include <Teuchos_FancyOStream.hpp> // for FancyOStream
57 #include <Teuchos_RCPDecl.hpp> // for RCP
58 #include <Teuchos_RCP.hpp> // for RCP::operator->, etc
59 #include <Teuchos_TestForException.hpp> // for TEUCHOS_TEST_FOR_EXCEPTION
60 
61 #include <Xpetra_Map.hpp> // for UnderlyingLib definition
62 
63 #include "MueLu_BoostGraphviz.hpp"
64 #include "MueLu_Exceptions.hpp" // for RuntimeError
66 #include "MueLu_KeepType.hpp"
67 #include "MueLu_NoFactory.hpp"
68 #include "MueLu_Utilities.hpp"
70 #include "MueLu_VerbosityLevel.hpp" // for MsgType::Default, VerbLevel
71 
72 namespace MueLu {
73 
99  class Level : public BaseClass {
100 
101  public:
103 
105 
106  Level() : lib_(Xpetra::NotSpecified), levelID_(-1) { }
107 
108  Level(RCP<FactoryManagerBase>& factoryManager) : lib_(Xpetra::UseTpetra), levelID_(-1), factoryManager_(factoryManager) { }
109 
111  virtual ~Level() { }
112 
114 
116  RCP<Level> Build();
119 
121 
123 
126  int GetLevelID() const;
127 
129  void SetLevelID(int levelID);
130 
133 
136  void SetPreviousLevel(const RCP<Level>& previousLevel);
138 
140 
141  // Users should not use this method.
143  void SetFactoryManager(const RCP<const FactoryManagerBase>& factoryManager);
144 
146  // Users should not use this method
149 
151 
156  template <class T>
157  void Set(const std::string& ename, const T& entry, const FactoryBase* factory = NoFactory::get()) {
158  const FactoryBase* fac = GetFactory(ename, factory);
159 
160  if (fac == NoFactory::get()) {
161  // Any data set with a NoFactory gets UserData keep flag by default
163  }
164 
165  // Store entry only if data have been requested (or any keep flag)
166  if (IsRequested(ename, factory) || GetKeepFlag(ename, factory) != 0) {
167  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(factory, ename), Exceptions::RuntimeError, "" + ename + " not found in");
168  map_[factory][ename]->SetData(entry);
169 
170  } else {
171  GetOStream(Warnings1) << "Level::Set: unable to store \"" << ename << "\" generated by factory " << factory->ShortClassName() << "["<<factory->GetID()<<"]"
172  << "(" << factory << ")"
173  << " on level " << toString(GetLevelID()) << ", as it has not been requested and no keep flags were set for it" << std::endl;
174  }
175  } // Set
176 
178 
181 
183 
191  template <class T>
192  T& Get(const std::string& ename, const FactoryBase* factory = NoFactory::get()) {
193  const FactoryBase* fac = GetFactory(ename, factory);
194  // printf("(l=%d) getting \"%20s\" generated by %10p [actually, generated by %p (%43s)]\n",
195  // levelID_, ename.c_str(), factory, fac, fac->description().c_str());
196 
197  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(fac, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found");
198 
199  if (!IsAvailable(ename, fac)) {
200  TEUCHOS_TEST_FOR_EXCEPTION(NumRequests(fac, ename) < 1 && GetKeepFlag(ename, fac) == 0, Exceptions::RuntimeError,
201  "\"" << ename << "\" has not been requested (counter = " << NumRequests(fac, ename) << ", "
202  "KeepFlag = " << GetKeepFlag(ename, fac) << "). " << std::endl <<
203  "Generating factory:" << *fac << " NoFactory = " << NoFactory::get());
204  fac->CallBuild(*this);
205  Release(*fac);
206  }
207 
208  TEUCHOS_TEST_FOR_EXCEPTION(!IsAvailable(ename, fac), Exceptions::RuntimeError, "MueLu::Level::Get(): factory did not produce expected output. "
209  "\"" << ename << "\" has not been generated by " << *fac);
210 
211  return map_[fac][ename]->template GetData<T>();
212  }
213 
215  template <class T>
216  void Get(const std::string& ename, T& rValue, const FactoryBase* factory = NoFactory::get()) {
217  rValue = Get<T>(ename, factory);
218  }
219 
220 
227  std::string GetTypeName(const std::string& ename, const FactoryBase* factory = NoFactory::get()) {
228  const FactoryBase* fac = GetFactory(ename, factory);
229  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(fac, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found");
230 
231  TEUCHOS_TEST_FOR_EXCEPTION(!IsAvailable(ename, fac), Exceptions::RuntimeError, "MueLu::Level::GetTypeString(): Data "
232  "\"" << ename << "\" generated by " << *fac << " is not available.");
233 
234  return map_[fac][ename]->GetTypeName();
235  }
236 
238 
240 
241 
243  // This method is intented to be used by user drivers for printing, debugging or to keep some computed data for a next run of the setup phase.
244  //
245  // This method is an alias for: AddKeepFlag(ename, factory, MueLu::Keep)
246  // See also the description of KeepEnum for more information.
247  //
248  // To undo a keep request, one can use:
249  // - Delete(ename, factory) to delete the data and remove the "Keep" flag
250  // - or RemoveKeepFlag(ename, factory, MueLu::Keep) to go back to previous condition (data are kept only if internal MueLu logic need so).
251  //
252  // Note: Level variables tagged using this methods are also keep on the levels built using this.Build().
253  // This means that is you request to keep a specific variable on a fine level, all the coarser level that are created automatically during the setup phase will also retain the same variable.
254  void Keep(const std::string & ename, const FactoryBase* factory) { AddKeepFlag(ename, factory, MueLu::Keep); } // Note: do not add default value for input parameter 'factory'
255 
257  // Special cases:
258  // - If entry (ename, factory) does not exist, nothing is done.
259  // - If entry exists but counter !=, entry cannot be desallocated before counter set to 0 (using Release()) so an exeption is thrown.
260  void Delete(const std::string& ename, const FactoryBase* factory) { // Note: do not add default value for input parameter 'factory'
261  if (!IsKey(factory, ename))
262  return;
263 
264  // Precondition:
265  // Delete() should only be called if counter == 0
266  // Note: It better to throw an exception rather than deleting the data if counter != 0 because users are not supposed to manipulate data with counter != 0
267  TEUCHOS_TEST_FOR_EXCEPTION(IsRequested(ename, factory) == true, Exceptions::RuntimeError, "MueLu::Level::Delete(): IsRequested() == true. Ref counter != 0. You are not allowed to delete data that are still in use.");
268  // If counter == 0 and entry exists, this means that a keep flag is set. Or there is an internal logic problem.
269  TEUCHOS_TEST_FOR_EXCEPTION(GetKeepFlag(ename, factory) == 0, Exceptions::RuntimeError, "MueLu::Level::Delete(), Keep flag == 0?");
270 
271  RemoveKeepFlag(ename, factory, MueLu::All); // will delete the data if counter == 0
272 
273  // Post condition: data must have been deleted
274  TEUCHOS_TEST_FOR_EXCEPTION(IsAvailable(ename, factory) == true, Exceptions::RuntimeError, "MueLu::Level::Delete(): Internal error (Post condition). Data have not been deleted.");
275  }
276 
278  void Clear();
279 
282  void ExpertClear();
283 
287  bool IsKept(const std::string& ename, const FactoryBase* factory, KeepType keep) const { return GetKeepFlag(ename, factory) & keep; }
288 
293  void AddKeepFlag(const std::string & ename, const FactoryBase* factory = NoFactory::get(), KeepType keep = MueLu::Keep); // TODO: remove default value for input parameter 'factory'?
294 
298  void RemoveKeepFlag(const std::string & ename, const FactoryBase* factory, KeepType keep = MueLu::All);
299 
301  KeepType GetKeepFlag(const std::string& ename, const FactoryBase* factory) const;
302 
304 
307 
308 
310  void Request(const FactoryBase& factory);
311 
313  void Release(const FactoryBase& factory);
314 
316  void DeclareInput(const std::string& ename, const FactoryBase* factory, const FactoryBase* requestedBy = NoFactory::get() );
317 
319  void DeclareDependencies(const FactoryBase* factory, bool bRequestOnly = false, bool bReleaseOnly = false);
320 
322  void Request(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
323 
325  void Release(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
326 
328 
330 
331 
333  bool IsAvailable(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
334  if (!IsKey(factory, ename))
335  return false;
336  try {
337  return Get(factory, ename)->IsAvailable();
338  } catch (...) {
339  return false;
340  }
341  }
342 
344  bool IsRequested(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
345  if (!IsKey(factory, ename))
346  return false;
347  try {
348  return IsRequested(Get(factory, ename));
349  } catch (...) {
350  return false;
351  }
352  }
353 
354 
356 
358 
360  std::string description() const;
361 
363  // TODO: print only shows requested variables. check if we also list kept factories with ref counter=0?
364  void print(std::ostream& out, const VerbLevel verbLevel = Default) const;
365 
366 #if defined(HAVE_MUELU_BOOST) && defined(HAVE_MUELU_BOOST_FOR_REAL) && defined(BOOST_VERSION) && (BOOST_VERSION >= 104400)
367  void UpdateGraph(std::map<const FactoryBase*, BoostVertex>& vindices,
368  std::map<std::pair<BoostVertex, BoostVertex>, std::string>& edges,
369  BoostProperties& dp,
370  BoostGraph& graph) const;
371 #endif
372 
374 
377 
378  void setlib(Xpetra::UnderlyingLib lib2) { lib_ = lib2; }
379  Xpetra::UnderlyingLib lib() { return lib_; }
380 
381  void SetComm(RCP<const Teuchos::Comm<int> > const &comm) { comm_ = comm; }
383 
384  private:
385 
387  Level(const Level& source);
388 
390  //
391  // If factory == NULL, the default factory is defined as follow:
392  // - If user data is available, it is considered as the default and the factory manager is ignored.
393  // => The default factory is then NoFactory.
394  // - Else, the factory manager is used to get the default factory.
395  //
396  // This strategy allows to use the same factory manager on the fine and coarse level without any trouble.
397  // Example :
398  //
399  // FineLevel:
400  // ----------
401  // A -> User provided
402  // Nullspace -> User provided
403  //
404  // CoarseLevel:
405  // ------------
406  // A -> RAPFactory
407  // NullSpace -> NullspaceFactory
408  //
409  const FactoryBase* GetFactory(const std::string& varname, const FactoryBase* factory) const;
410 
412  Xpetra::UnderlyingLib lib_;
414 
415  typedef const FactoryBase* Key1;
416  typedef const std::string Key2;
420 
421  int levelID_; // id number associated with level
423  RCP<Level> previousLevel_; // linked list of Level
425 
427 
428 
430  bool IsKey(const FactoryBase* factory, const std::string& ename) const {
431  TwoKeyMap::const_iterator it = map_.find(factory);
432  return (it != map_.end()) ? (it->second).count(ename) : false;
433  }
434 
435  bool IsAvailableFactory(const FactoryBase* factory) const {
436  TwoKeyMap::const_iterator it = map_.find(factory);
437  if (it == map_.end())
438  return false;
439  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++) {
440  if (sit->second->IsAvailable())
441  return true;
442  }
443  return false;
444  }
445 
446  bool IsRequested(const Value& v) const {
447  TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
448  "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
449  return v->IsRequested();
450  }
451 
452  bool IsRequestedBy(const FactoryBase* factory, const std::string& ename, const FactoryBase* requestedBy) const {
453  if (!IsKey(factory, ename))
454  return false;
455 
456  return IsRequestedBy(Get(factory, ename), requestedBy);
457  }
458 
459  bool IsRequestedBy(const Value& v, const FactoryBase* requestedBy) const {
460  TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
461  "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
462  return v->IsRequested(requestedBy);
463  }
464 
465  bool IsRequestedFactory(const FactoryBase* factory) const {
466  TwoKeyMap::const_iterator it = map_.find(factory);
467  if (it == map_.end())
468  return false;
469  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
470  if (IsRequested(sit->second))
471  return true;
472  return false;
473  }
474 
475  const Value& Get(const FactoryBase* factory, const std::string& ename) const {
476  TwoKeyMap::const_iterator it = map_.find(factory);
477  TEUCHOS_TEST_FOR_EXCEPTION(it == map_.end(), Exceptions::RuntimeError, "Key (" << factory << ", *) does not exist.");
478 
479  SubMap::const_iterator sit = it->second.find(ename);
480  TEUCHOS_TEST_FOR_EXCEPTION(sit == it->second.end(), Exceptions::RuntimeError, "Key (" << factory << ", " << ename << ") does not exist.");
481 
482  return sit->second;
483  }
484 
485  int NumRequests(const FactoryBase* factory, const std::string & ename) const {
486  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(factory, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found. Do a request first.");
487  const Teuchos::RCP<MueLu::VariableContainer>& v = Get(factory, ename);
489  "NumRequests(): Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
490  return v->NumAllRequests();
491  }
492 
493  int CountRequestedFactory(const FactoryBase* factory) const {
494  TwoKeyMap::const_iterator it = map_.find(factory);
495  if (it == map_.end())
496  return 0;
497 
498  int cnt = 0;
499  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
500  cnt += sit->second->NumAllRequests();
501 
502  return cnt;
503  }
504 
506 
507  }; //class Level
508 
509 } //namespace MueLu
510 
511 //TODO: Caps should not matter
512 
513 #endif // MUELU_LEVEL_HPP
void Keep(const std::string &ename, const FactoryBase *factory)
Request to keep variable &#39;ename&#39; generated by &#39;factory&#39; after the setup phase.
RCP< Level > & GetPreviousLevel()
Previous level.
RCP< const Teuchos::Comm< int > > comm_
KeepType GetKeepFlag(const std::string &ename, const FactoryBase *factory) const
Get the flag combination set for variable &#39;ename&#39; generated by &#39;factory&#39;.
T & Get(const std::string &ename, const FactoryBase *factory=NoFactory::get())
Get data without decrementing associated storage counter (i.e., read-only access). Usage: Level-&gt;Get&lt; RCP&lt;Matrix&gt; &gt;(&quot;A&quot;, factory) if factory == NULL =&gt; use default factory.
virtual void CallBuild(Level &requestedLevel) const =0
std::string toString(const T &what)
Little helper function to convert non-string types to strings.
bool IsKept(const std::string &ename, const FactoryBase *factory, KeepType keep) const
void DeclareDependencies(const FactoryBase *factory, bool bRequestOnly=false, bool bReleaseOnly=false)
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput() to declare factory depe...
bool IsRequested(const Value &v) const
void Release(const FactoryBase &factory)
Decrement the storage counter for all the inputs of a factory.
const std::string Key2
Xpetra::UnderlyingLib lib_
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
short KeepType
KeepType GetKeepFlag() const
Returns the keep flag combination.
TwoKeyMap map_
RCP< Level > previousLevel_
User data are always kept. This flag is set automatically when Level::Set(&quot;data&quot;, data) is used...
void SetPreviousLevel(const RCP< Level > &previousLevel)
Definition: MueLu_Level.cpp:85
void SetFactoryManager(const RCP< const FactoryManagerBase > &factoryManager)
Set default factories (used internally by Hierarchy::SetLevel()).
Definition: MueLu_Level.cpp:92
int CountRequestedFactory(const FactoryBase *factory) const
static const NoFactory * get()
void setlib(Xpetra::UnderlyingLib lib2)
RequestMode GetRequestMode() const
Additional warnings.
const Value & Get(const FactoryBase *factory, const std::string &ename) const
Base class for factories (e.g., R, P, and A_coarse).
void Clear()
Delete all data that have been retained after the setup phase using Final flag.
bool IsRequestedBy(const FactoryBase *factory, const std::string &ename, const FactoryBase *requestedBy) const
const FactoryBase * GetFactory(const std::string &varname, const FactoryBase *factory) const
If input factory == NULL, returns the default factory. Else, return input factory.
void ExpertClear()
const FactoryBase * Key1
bool IsRequestedBy(const Value &v, const FactoryBase *requestedBy) const
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Level(RCP< FactoryManagerBase > &factoryManager)
static RequestMode requestMode_
void Delete(const std::string &ename, const FactoryBase *factory)
Delete data that have been retained after the setup phase (using Keep(), AddKeepFlag(), or internal MueLu logic).
int levelID_
Map of a map (Key1 -&gt; SubMap)
std::string GetTypeName(const std::string &ename, const FactoryBase *factory=NoFactory::get())
GetTypeName returns type string of variable stored using ename and factory.
void RemoveKeepFlag(const std::string &ename, const FactoryBase *factory, KeepType keep=MueLu::All)
std::string description() const
Return a simple one-line description of this object.
Xpetra::UnderlyingLib lib()
Always keep data, even accross run. This flag is set by Level::Keep(). This flag is propagated to coa...
virtual ~Level()
Destructor.
int NumRequests(const FactoryBase *factory, const std::string &ename) const
void AddKeepFlag(const std::string &ename, const FactoryBase *factory=NoFactory::get(), KeepType keep=MueLu::Keep)
void Set(const std::string &ename, const T &entry, const FactoryBase *factory=NoFactory::get())
bool IsAvailableFactory(const FactoryBase *factory) const
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
Base class for MueLu classes.
RCP< Level > Build()
Definition: MueLu_Level.cpp:54
void print(std::ostream &out, const VerbLevel verbLevel=Default) const
Printing method.
Teuchos::map< Key1, SubMap > TwoKeyMap
Sub-map container (Key2 -&gt; Value)
void SetLevelID(int levelID)
Set level number.
Definition: MueLu_Level.cpp:78
RCP< const FactoryManagerBase > factoryManager_
bool IsRequestedFactory(const FactoryBase *factory) const
Teuchos::map< Key2, Value > SubMap
const RCP< const FactoryManagerBase > GetFactoryManager()
returns the current factory manager
Definition: MueLu_Level.cpp:96
int GetLevelID() const
Return level number.
Definition: MueLu_Level.cpp:76
Exception throws to report errors in the internal logical of the program.
void SetComm(RCP< const Teuchos::Comm< int > > const &comm)
bool IsRequested(const std::string &ename, const FactoryBase *factory=NoFactory::get()) const
Test whether a need has been requested. Note: this tells nothing about whether the need&#39;s value exist...
bool IsKey(const FactoryBase *factory, const std::string &ename) const
Test whether some information about (ename, factory) are stored.
int NumAllRequests() const
Returns the number of times the data has been requested.
void DeclareInput(const std::string &ename, const FactoryBase *factory, const FactoryBase *requestedBy=NoFactory::get())
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput()
RCP< const Teuchos::Comm< int > > GetComm() const
void Get(const std::string &ename, T &rValue, const FactoryBase *factory=NoFactory::get())
Get data without decrementing associated storage counter (i.e., read-only access).
bool IsAvailable(const std::string &ename, const FactoryBase *factory=NoFactory::get()) const
Test whether a need&#39;s value has been saved.
void Request(const FactoryBase &factory)
Increment the storage counter for all the inputs of a factory.
RCP< VariableContainer > Value