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
172  << " on level " << toString(GetLevelID()) << ", as it has not been requested and no keep flags were set for it" << std::endl;
173  }
174  } // Set
175 
177 
180 
182 
190  template <class T>
191  T& Get(const std::string& ename, const FactoryBase* factory = NoFactory::get()) {
192  const FactoryBase* fac = GetFactory(ename, factory);
193  // printf("(l=%d) getting \"%20s\" generated by %10p [actually, generated by %p (%43s)]\n",
194  // levelID_, ename.c_str(), factory, fac, fac->description().c_str());
195 
196  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(fac, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found");
197 
198  if (!IsAvailable(ename, fac)) {
199  TEUCHOS_TEST_FOR_EXCEPTION(NumRequests(fac, ename) < 1 && GetKeepFlag(ename, fac) == 0, Exceptions::RuntimeError,
200  "\"" << ename << "\" has not been requested (counter = " << NumRequests(fac, ename) << ", "
201  "KeepFlag = " << GetKeepFlag(ename, fac) << "). " << std::endl <<
202  "Generating factory:" << *fac << " NoFactory = " << NoFactory::get());
203  fac->CallBuild(*this);
204  Release(*fac);
205  }
206 
207  TEUCHOS_TEST_FOR_EXCEPTION(!IsAvailable(ename, fac), Exceptions::RuntimeError, "MueLu::Level::Get(): factory did not produce expected output. "
208  "\"" << ename << "\" has not been generated by " << *fac);
209 
210  return map_[fac][ename]->template GetData<T>();
211  }
212 
214  template <class T>
215  void Get(const std::string& ename, T& rValue, const FactoryBase* factory = NoFactory::get()) {
216  rValue = Get<T>(ename, factory);
217  }
218 
219 
226  std::string GetTypeName(const std::string& ename, const FactoryBase* factory = NoFactory::get()) {
227  const FactoryBase* fac = GetFactory(ename, factory);
228  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(fac, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found");
229 
230  TEUCHOS_TEST_FOR_EXCEPTION(!IsAvailable(ename, fac), Exceptions::RuntimeError, "MueLu::Level::GetTypeString(): Data "
231  "\"" << ename << "\" generated by " << *fac << " is not available.");
232 
233  return map_[fac][ename]->GetTypeName();
234  }
235 
237 
239 
240 
242  // 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.
243  //
244  // This method is an alias for: AddKeepFlag(ename, factory, MueLu::Keep)
245  // See also the description of KeepEnum for more information.
246  //
247  // To undo a keep request, one can use:
248  // - Delete(ename, factory) to delete the data and remove the "Keep" flag
249  // - or RemoveKeepFlag(ename, factory, MueLu::Keep) to go back to previous condition (data are kept only if internal MueLu logic need so).
250  //
251  // Note: Level variables tagged using this methods are also keep on the levels built using this.Build().
252  // 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.
253  void Keep(const std::string & ename, const FactoryBase* factory) { AddKeepFlag(ename, factory, MueLu::Keep); } // Note: do not add default value for input parameter 'factory'
254 
256  // Special cases:
257  // - If entry (ename, factory) does not exist, nothing is done.
258  // - If entry exists but counter !=, entry cannot be desallocated before counter set to 0 (using Release()) so an exeption is thrown.
259  void Delete(const std::string& ename, const FactoryBase* factory) { // Note: do not add default value for input parameter 'factory'
260  if (!IsKey(factory, ename))
261  return;
262 
263  // Precondition:
264  // Delete() should only be called if counter == 0
265  // 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
266  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.");
267  // If counter == 0 and entry exists, this means that a keep flag is set. Or there is an internal logic problem.
268  TEUCHOS_TEST_FOR_EXCEPTION(GetKeepFlag(ename, factory) == 0, Exceptions::RuntimeError, "MueLu::Level::Delete(), Keep flag == 0?");
269 
270  RemoveKeepFlag(ename, factory, MueLu::All); // will delete the data if counter == 0
271 
272  // Post condition: data must have been deleted
273  TEUCHOS_TEST_FOR_EXCEPTION(IsAvailable(ename, factory) == true, Exceptions::RuntimeError, "MueLu::Level::Delete(): Internal error (Post condition). Data have not been deleted.");
274  }
275 
277  void Clear();
278 
281  void ExpertClear();
282 
286  bool IsKept(const std::string& ename, const FactoryBase* factory, KeepType keep) const { return GetKeepFlag(ename, factory) & keep; }
287 
292  void AddKeepFlag(const std::string & ename, const FactoryBase* factory = NoFactory::get(), KeepType keep = MueLu::Keep); // TODO: remove default value for input parameter 'factory'?
293 
297  void RemoveKeepFlag(const std::string & ename, const FactoryBase* factory, KeepType keep = MueLu::All);
298 
300  KeepType GetKeepFlag(const std::string& ename, const FactoryBase* factory) const;
301 
303 
306 
307 
309  void Request(const FactoryBase& factory);
310 
312  void Release(const FactoryBase& factory);
313 
315  void DeclareInput(const std::string& ename, const FactoryBase* factory, const FactoryBase* requestedBy = NoFactory::get() );
316 
318  void DeclareDependencies(const FactoryBase* factory, bool bRequestOnly = false, bool bReleaseOnly = false);
319 
321  void Request(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
322 
324  void Release(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
325 
327 
329 
330 
332  bool IsAvailable(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
333  if (!IsKey(factory, ename))
334  return false;
335  try {
336  return Get(factory, ename)->IsAvailable();
337  } catch (...) {
338  return false;
339  }
340  }
341 
343  bool IsRequested(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
344  if (!IsKey(factory, ename))
345  return false;
346  try {
347  return IsRequested(Get(factory, ename));
348  } catch (...) {
349  return false;
350  }
351  }
352 
353 
355 
357 
359  std::string description() const;
360 
362  // TODO: print only shows requested variables. check if we also list kept factories with ref counter=0?
363  void print(std::ostream& out, const VerbLevel verbLevel = Default) const;
364 
365 #if defined(HAVE_MUELU_BOOST) && defined(HAVE_MUELU_BOOST_FOR_REAL) && defined(BOOST_VERSION) && (BOOST_VERSION >= 104400)
366  void UpdateGraph(std::map<const FactoryBase*, BoostVertex>& vindices,
367  std::map<std::pair<BoostVertex, BoostVertex>, std::string>& edges,
368  BoostProperties& dp,
369  BoostGraph& graph) const;
370 #endif
371 
373 
376 
377  void setlib(Xpetra::UnderlyingLib lib2) { lib_ = lib2; }
379 
380  void SetComm(RCP<const Teuchos::Comm<int> > const &comm) { comm_ = comm; }
382 
383  private:
384 
386  Level(const Level& source);
387 
389  //
390  // If factory == NULL, the default factory is defined as follow:
391  // - If user data is available, it is considered as the default and the factory manager is ignored.
392  // => The default factory is then NoFactory.
393  // - Else, the factory manager is used to get the default factory.
394  //
395  // This strategy allows to use the same factory manager on the fine and coarse level without any trouble.
396  // Example :
397  //
398  // FineLevel:
399  // ----------
400  // A -> User provided
401  // Nullspace -> User provided
402  //
403  // CoarseLevel:
404  // ------------
405  // A -> RAPFactory
406  // NullSpace -> NullspaceFactory
407  //
408  const FactoryBase* GetFactory(const std::string& varname, const FactoryBase* factory) const;
409 
413 
414  typedef const FactoryBase* Key1;
415  typedef const std::string Key2;
419 
420  int levelID_; // id number associated with level
422  RCP<Level> previousLevel_; // linked list of Level
424 
426 
427 
429  bool IsKey(const FactoryBase* factory, const std::string& ename) const {
430  TwoKeyMap::const_iterator it = map_.find(factory);
431  return (it != map_.end()) ? (it->second).count(ename) : false;
432  }
433 
434  bool IsAvailableFactory(const FactoryBase* factory) const {
435  TwoKeyMap::const_iterator it = map_.find(factory);
436  if (it == map_.end())
437  return false;
438  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++) {
439  if (sit->second->IsAvailable())
440  return true;
441  }
442  return false;
443  }
444 
445  bool IsRequested(const Value& v) const {
446  TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
447  "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
448  return v->IsRequested();
449  }
450 
451  bool IsRequestedBy(const FactoryBase* factory, const std::string& ename, const FactoryBase* requestedBy) const {
452  if (!IsKey(factory, ename))
453  return false;
454 
455  return IsRequestedBy(Get(factory, ename), requestedBy);
456  }
457 
458  bool IsRequestedBy(const Value& v, const FactoryBase* requestedBy) const {
459  TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
460  "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
461  return v->IsRequested(requestedBy);
462  }
463 
464  bool IsRequestedFactory(const FactoryBase* factory) const {
465  TwoKeyMap::const_iterator it = map_.find(factory);
466  if (it == map_.end())
467  return false;
468  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
469  if (IsRequested(sit->second))
470  return true;
471  return false;
472  }
473 
474  const Value& Get(const FactoryBase* factory, const std::string& ename) const {
475  TwoKeyMap::const_iterator it = map_.find(factory);
476  TEUCHOS_TEST_FOR_EXCEPTION(it == map_.end(), Exceptions::RuntimeError, "Key (" << factory << ", *) does not exist.");
477 
478  SubMap::const_iterator sit = it->second.find(ename);
479  TEUCHOS_TEST_FOR_EXCEPTION(sit == it->second.end(), Exceptions::RuntimeError, "Key (" << factory << ", " << ename << ") does not exist.");
480 
481  return sit->second;
482  }
483 
484  int NumRequests(const FactoryBase* factory, const std::string & ename) const {
485  TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(factory, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found. Do a request first.");
486  const Teuchos::RCP<MueLu::VariableContainer>& v = Get(factory, ename);
488  "NumRequests(): Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
489  return v->NumAllRequests();
490  }
491 
492  int CountRequestedFactory(const FactoryBase* factory) const {
493  TwoKeyMap::const_iterator it = map_.find(factory);
494  if (it == map_.end())
495  return 0;
496 
497  int cnt = 0;
498  for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
499  cnt += sit->second->NumAllRequests();
500 
501  return cnt;
502  }
503 
505 
506  }; //class Level
507 
508 } //namespace MueLu
509 
510 //TODO: Caps should not matter
511 
512 #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;.
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
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
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