MueLu Version of the Day
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
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
72namespace 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
118 RCP<Level> Build();
119
121
123
124
126 int GetLevelID() const;
127
129 void SetLevelID(int levelID);
130
132 RCP<Level>& GetPreviousLevel() { return previousLevel_; }
133
136 void SetPreviousLevel(const RCP<Level>& previousLevel);
138
140
141
142 // Users should not use this method.
143 void SetFactoryManager(const RCP<const FactoryManagerBase>& factoryManager);
144
146 // Users should not use this method
147 const RCP<const FactoryManagerBase> GetFactoryManager();
149
151
152
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 on level " + toString(GetLevelID()) + ".");
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,
209 "MueLu::Level::Get(): factory did not produce expected output on level " << GetLevelID()
210 << ". The data \"" << ename << "\" has not been generated by " << *fac);
211
212 return map_[fac][ename]->template GetData<T>();
213 }
214
216 template <class T>
217 void Get(const std::string& ename, T& rValue, const FactoryBase* factory = NoFactory::get()) {
218 rValue = Get<T>(ename, factory);
219 }
220
221
228 std::string GetTypeName(const std::string& ename, const FactoryBase* factory = NoFactory::get()) {
229 const FactoryBase* fac = GetFactory(ename, factory);
230 TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(fac, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found");
231
232 TEUCHOS_TEST_FOR_EXCEPTION(!IsAvailable(ename, fac), Exceptions::RuntimeError, "MueLu::Level::GetTypeString(): Data "
233 "\"" << ename << "\" generated by " << *fac << " is not available.");
234
235 return map_[fac][ename]->GetTypeName();
236 }
237
239
241
242
244 // 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.
245 //
246 // This method is an alias for: AddKeepFlag(ename, factory, MueLu::Keep)
247 // See also the description of KeepEnum for more information.
248 //
249 // To undo a keep request, one can use:
250 // - Delete(ename, factory) to delete the data and remove the "Keep" flag
251 // - or RemoveKeepFlag(ename, factory, MueLu::Keep) to go back to previous condition (data are kept only if internal MueLu logic need so).
252 //
253 // Note: Level variables tagged using this methods are also keep on the levels built using this.Build().
254 // 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.
255 void Keep(const std::string & ename, const FactoryBase* factory) { AddKeepFlag(ename, factory, MueLu::Keep); } // Note: do not add default value for input parameter 'factory'
256
258 // Special cases:
259 // - If entry (ename, factory) does not exist, nothing is done.
260 // - If entry exists but counter !=, entry cannot be desallocated before counter set to 0 (using Release()) so an exeption is thrown.
261 void Delete(const std::string& ename, const FactoryBase* factory) { // Note: do not add default value for input parameter 'factory'
262 if (!IsKey(factory, ename))
263 return;
264
265 // Precondition:
266 // Delete() should only be called if counter == 0
267 // 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
268 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.");
269 // If counter == 0 and entry exists, this means that a keep flag is set. Or there is an internal logic problem.
270 TEUCHOS_TEST_FOR_EXCEPTION(GetKeepFlag(ename, factory) == 0, Exceptions::RuntimeError, "MueLu::Level::Delete(), Keep flag == 0?");
271
272 RemoveKeepFlag(ename, factory, MueLu::All); // will delete the data if counter == 0
273
274 // Post condition: data must have been deleted
275 TEUCHOS_TEST_FOR_EXCEPTION(IsAvailable(ename, factory) == true, Exceptions::RuntimeError, "MueLu::Level::Delete(): Internal error (Post condition). Data have not been deleted.");
276 }
277
279 void Clear();
280
283 void ExpertClear();
284
288 bool IsKept(const std::string& ename, const FactoryBase* factory, KeepType keep) const { return GetKeepFlag(ename, factory) & keep; }
289
294 void AddKeepFlag(const std::string & ename, const FactoryBase* factory = NoFactory::get(), KeepType keep = MueLu::Keep); // TODO: remove default value for input parameter 'factory'?
295
299 void RemoveKeepFlag(const std::string & ename, const FactoryBase* factory, KeepType keep = MueLu::All);
300
302 KeepType GetKeepFlag(const std::string& ename, const FactoryBase* factory) const;
303
305
308
309
311 void Request(const FactoryBase& factory);
312
314 void Release(const FactoryBase& factory);
315
317 void DeclareInput(const std::string& ename, const FactoryBase* factory, const FactoryBase* requestedBy = NoFactory::get() );
318
320 void DeclareDependencies(const FactoryBase* factory, bool bRequestOnly = false, bool bReleaseOnly = false);
321
323 void Request(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
324
326 void Release(const std::string& ename, const FactoryBase* factory = NoFactory::get(), const FactoryBase* requestedBy = NoFactory::get());
327
329
331
332
334 bool IsAvailable(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
335 if (!IsKey(factory, ename))
336 return false;
337 try {
338 return Get(factory, ename)->IsAvailable();
339 } catch (...) {
340 return false;
341 }
342 }
343
345 bool IsRequested(const std::string& ename, const FactoryBase* factory = NoFactory::get()) const {
346 if (!IsKey(factory, ename))
347 return false;
348 try {
349 return IsRequested(Get(factory, ename));
350 } catch (...) {
351 return false;
352 }
353 }
354
355
357
359
361 std::string description() const;
362
364 // TODO: print only shows requested variables. check if we also list kept factories with ref counter=0?
365 void print(std::ostream& out, const VerbLevel verbLevel = Default) const;
366
367#if defined(HAVE_MUELU_BOOST) && defined(HAVE_MUELU_BOOST_FOR_REAL) && defined(BOOST_VERSION) && (BOOST_VERSION >= 104400)
368 void UpdateGraph(std::map<const FactoryBase*, BoostVertex>& vindices,
369 std::map<std::pair<BoostVertex, BoostVertex>, std::string>& edges,
370 BoostProperties& dp,
371 BoostGraph& graph) const;
372#endif
373
375
378
379 void setlib(Xpetra::UnderlyingLib lib2) { lib_ = lib2; }
380 Xpetra::UnderlyingLib lib() { return lib_; }
381
382 void SetComm(RCP<const Teuchos::Comm<int> > const &comm) { comm_ = comm; }
383 RCP<const Teuchos::Comm<int> > GetComm() const { return comm_; }
384
385 private:
386
388 Level(const Level& source);
389
391 //
392 // If factory == NULL, the default factory is defined as follow:
393 // - If user data is available, it is considered as the default and the factory manager is ignored.
394 // => The default factory is then NoFactory.
395 // - Else, the factory manager is used to get the default factory.
396 //
397 // This strategy allows to use the same factory manager on the fine and coarse level without any trouble.
398 // Example :
399 //
400 // FineLevel:
401 // ----------
402 // A -> User provided
403 // Nullspace -> User provided
404 //
405 // CoarseLevel:
406 // ------------
407 // A -> RAPFactory
408 // NullSpace -> NullspaceFactory
409 //
410 const FactoryBase* GetFactory(const std::string& varname, const FactoryBase* factory) const;
411
413 Xpetra::UnderlyingLib lib_;
414 RCP<const Teuchos::Comm<int> > comm_;
415
416 typedef const FactoryBase* Key1;
417 typedef const std::string Key2;
418 typedef RCP<VariableContainer> Value;
419 typedef Teuchos::map<Key2, Value> SubMap;
420 typedef Teuchos::map<Key1, SubMap> TwoKeyMap;
421
422 int levelID_; // id number associated with level
423 RCP<const FactoryManagerBase> factoryManager_;
424 RCP<Level> previousLevel_; // linked list of Level
426
428
429
431 bool IsKey(const FactoryBase* factory, const std::string& ename) const {
432 TwoKeyMap::const_iterator it = map_.find(factory);
433 return (it != map_.end()) ? (it->second).count(ename) : false;
434 }
435
436 bool IsAvailableFactory(const FactoryBase* factory) const {
437 TwoKeyMap::const_iterator it = map_.find(factory);
438 if (it == map_.end())
439 return false;
440 for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++) {
441 if (sit->second->IsAvailable())
442 return true;
443 }
444 return false;
445 }
446
447 bool IsRequested(const Value& v) const {
448 TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
449 "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
450 return v->IsRequested();
451 }
452
453 bool IsRequestedBy(const FactoryBase* factory, const std::string& ename, const FactoryBase* requestedBy) const {
454 if (!IsKey(factory, ename))
455 return false;
456
457 return IsRequestedBy(Get(factory, ename), requestedBy);
458 }
459
460 bool IsRequestedBy(const Value& v, const FactoryBase* requestedBy) const {
461 TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
462 "Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
463 return v->IsRequested(requestedBy);
464 }
465
466 bool IsRequestedFactory(const FactoryBase* factory) const {
467 TwoKeyMap::const_iterator it = map_.find(factory);
468 if (it == map_.end())
469 return false;
470 for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
471 if (IsRequested(sit->second))
472 return true;
473 return false;
474 }
475
476 const Value& Get(const FactoryBase* factory, const std::string& ename) const {
477 TwoKeyMap::const_iterator it = map_.find(factory);
478 TEUCHOS_TEST_FOR_EXCEPTION(it == map_.end(), Exceptions::RuntimeError, "Key (" << factory << ", *) does not exist.");
479
480 SubMap::const_iterator sit = it->second.find(ename);
481 TEUCHOS_TEST_FOR_EXCEPTION(sit == it->second.end(), Exceptions::RuntimeError, "Key (" << factory << ", " << ename << ") does not exist.");
482
483 return sit->second;
484 }
485
486 int NumRequests(const FactoryBase* factory, const std::string & ename) const {
487 TEUCHOS_TEST_FOR_EXCEPTION(!IsKey(factory, ename), Exceptions::RuntimeError, "\"" + ename + "\" not found. Do a request first.");
488 const Teuchos::RCP<MueLu::VariableContainer>& v = Get(factory, ename);
489 TEUCHOS_TEST_FOR_EXCEPTION(v->NumAllRequests() == 0 && v->GetKeepFlag() == 0, Exceptions::RuntimeError,
490 "NumRequests(): Internal logic error: if counter == 0, the entry in countTable_ should have been deleted");
491 return v->NumAllRequests();
492 }
493
494 int CountRequestedFactory(const FactoryBase* factory) const {
495 TwoKeyMap::const_iterator it = map_.find(factory);
496 if (it == map_.end())
497 return 0;
498
499 int cnt = 0;
500 for (SubMap::const_iterator sit = it->second.begin(); sit != it->second.end(); sit++)
501 cnt += sit->second->NumAllRequests();
502
503 return cnt;
504 }
505
507
508 }; //class Level
509
510} //namespace MueLu
511
512//TODO: Caps should not matter
513
514#endif // MUELU_LEVEL_HPP
Base class for MueLu classes.
Exception throws to report errors in the internal logical of the program.
Base class for factories (e.g., R, P, and A_coarse).
virtual void CallBuild(Level &requestedLevel) const =0
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
bool IsAvailable(const std::string &ename, const FactoryBase *factory=NoFactory::get()) const
Test whether a need's value has been saved.
const FactoryBase * GetFactory(const std::string &varname, const FactoryBase *factory) const
If input factory == NULL, returns the default factory. Else, return input factory.
void SetComm(RCP< const Teuchos::Comm< int > > const &comm)
Teuchos::map< Key2, Value > SubMap
void DeclareInput(const std::string &ename, const FactoryBase *factory, const FactoryBase *requestedBy=NoFactory::get())
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput()
RCP< Level > Build()
Definition: MueLu_Level.cpp:54
std::string description() const
Return a simple one-line description of this object.
Xpetra::UnderlyingLib lib_
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).
Level(const Level &source)
Copy constructor.
void setlib(Xpetra::UnderlyingLib lib2)
bool IsRequestedBy(const Value &v, const FactoryBase *requestedBy) const
RCP< Level > & GetPreviousLevel()
Previous level.
static RequestMode requestMode_
const Value & Get(const FactoryBase *factory, const std::string &ename) const
void Release(const FactoryBase &factory)
Decrement the storage counter for all the inputs of a factory.
int CountRequestedFactory(const FactoryBase *factory) const
const std::string Key2
RCP< const Teuchos::Comm< int > > GetComm() const
const RCP< const FactoryManagerBase > GetFactoryManager()
returns the current factory manager
Definition: MueLu_Level.cpp:96
void SetLevelID(int levelID)
Set level number.
Definition: MueLu_Level.cpp:78
bool IsRequested(const Value &v) const
void print(std::ostream &out, const VerbLevel verbLevel=Default) const
Printing method.
virtual ~Level()
Destructor.
Teuchos::map< Key1, SubMap > TwoKeyMap
Sub-map container (Key2 -> Value)
RCP< VariableContainer > Value
const FactoryBase * Key1
RCP< Level > previousLevel_
void RemoveKeepFlag(const std::string &ename, const FactoryBase *factory, KeepType keep=MueLu::All)
int GetLevelID() const
Return level number.
Definition: MueLu_Level.cpp:76
std::string GetTypeName(const std::string &ename, const FactoryBase *factory=NoFactory::get())
GetTypeName returns type string of variable stored using ename and factory.
void Clear()
Delete all data that have been retained after the setup phase using Final flag.
void AddKeepFlag(const std::string &ename, const FactoryBase *factory=NoFactory::get(), KeepType keep=MueLu::Keep)
T & Get(const std::string &ename, const FactoryBase *factory=NoFactory::get())
Get data without decrementing associated storage counter (i.e., read-only access)....
void ExpertClear()
void DeclareDependencies(const FactoryBase *factory, bool bRequestOnly=false, bool bReleaseOnly=false)
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput() to declare factory depe...
bool IsRequestedFactory(const FactoryBase *factory) const
RequestMode GetRequestMode() const
RCP< const Teuchos::Comm< int > > comm_
KeepType GetKeepFlag(const std::string &ename, const FactoryBase *factory) const
Get the flag combination set for variable 'ename' generated by 'factory'.
void Set(const std::string &ename, const T &entry, const FactoryBase *factory=NoFactory::get())
RCP< const FactoryManagerBase > factoryManager_
bool IsKept(const std::string &ename, const FactoryBase *factory, KeepType keep) const
bool IsAvailableFactory(const FactoryBase *factory) const
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's value exist...
int NumRequests(const FactoryBase *factory, const std::string &ename) const
void Request(const FactoryBase &factory)
Increment the storage counter for all the inputs of a factory.
bool IsRequestedBy(const FactoryBase *factory, const std::string &ename, const FactoryBase *requestedBy) const
void SetPreviousLevel(const RCP< Level > &previousLevel)
Definition: MueLu_Level.cpp:85
Xpetra::UnderlyingLib lib()
void SetFactoryManager(const RCP< const FactoryManagerBase > &factoryManager)
Set default factories (used internally by Hierarchy::SetLevel()).
Definition: MueLu_Level.cpp:92
int levelID_
Map of a map (Key1 -> SubMap)
TwoKeyMap map_
Level(RCP< FactoryManagerBase > &factoryManager)
bool IsKey(const FactoryBase *factory, const std::string &ename) const
Test whether some information about (ename, factory) are stored.
void Keep(const std::string &ename, const FactoryBase *factory)
Request to keep variable 'ename' generated by 'factory' after the setup phase.
void Delete(const std::string &ename, const FactoryBase *factory)
Delete data that have been retained after the setup phase (using Keep(), AddKeepFlag(),...
static const NoFactory * get()
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
Namespace for MueLu classes and methods.
@ Keep
Always keep data, even accross run. This flag is set by Level::Keep(). This flag is propagated to coa...
@ UserData
User data are always kept. This flag is set automatically when Level::Set("data", data) is used....
@ Warnings1
Additional warnings.
short KeepType
std::string toString(const T &what)
Little helper function to convert non-string types to strings.