MueLu  Version of the Day
MueLu_RebalanceBlockRestrictionFactory_def.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_REBALANCEBLOCKRESTRICTIONFACTORY_DEF_HPP_
47 #define MUELU_REBALANCEBLOCKRESTRICTIONFACTORY_DEF_HPP_
48 
49 #ifdef HAVE_MUELU_EXPERIMENTAL
50 
51 #include <Teuchos_Tuple.hpp>
52 
53 #include "Xpetra_Vector.hpp"
54 #include "Xpetra_VectorFactory.hpp"
55 #include "Xpetra_MultiVector.hpp"
56 #include "Xpetra_MultiVectorFactory.hpp"
57 #include <Xpetra_Matrix.hpp>
58 #include <Xpetra_BlockedCrsMatrix.hpp>
59 #include <Xpetra_MapFactory.hpp>
60 #include <Xpetra_MapExtractor.hpp>
61 #include <Xpetra_MapExtractorFactory.hpp>
62 #include <Xpetra_MatrixFactory.hpp>
63 #include <Xpetra_Import.hpp>
64 #include <Xpetra_ImportFactory.hpp>
65 
67 
68 #include "MueLu_HierarchyHelpers.hpp"
70 #include "MueLu_Level.hpp"
71 #include "MueLu_Monitor.hpp"
72 #include "MueLu_PerfUtils.hpp"
73 
74 namespace MueLu {
75 
76 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
78  RCP<ParameterList> validParamList = rcp(new ParameterList());
79 
80  validParamList->set< RCP<const FactoryBase> >("R", Teuchos::null, "Factory of the restriction operator that need to be rebalanced (only used if type=Restriction)");
81 
82  return validParamList;
83 }
84 
85 template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class Node>
87  FactManager_.push_back(FactManager);
88 }
89 
90 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
92  Input(coarseLevel, "R");
93 
94  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
95  for(it = FactManager_.begin(); it!=FactManager_.end(); ++it) {
96  SetFactoryManager fineSFM (rcpFromRef(fineLevel), *it);
97  SetFactoryManager coarseSFM(rcpFromRef(coarseLevel), *it);
98 
99  coarseLevel.DeclareInput("Importer",(*it)->GetFactory("Importer").get(), this);
100  coarseLevel.DeclareInput("Nullspace",(*it)->GetFactory("Nullspace").get(), this);
101  }
102 }
103 
104 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
106  FactoryMonitor m(*this, "Build", coarseLevel);
107  //const Teuchos::ParameterList & pL = GetParameterList();
108 
109  RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
110 
111  Teuchos::RCP<Matrix> originalTransferOp = Teuchos::null;
112  originalTransferOp = Get< RCP<Matrix> >(coarseLevel, "R");
113 
114  RCP<Xpetra::BlockedCrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > bOriginalTransferOp =
115  Teuchos::rcp_dynamic_cast<Xpetra::BlockedCrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >(originalTransferOp);
116  TEUCHOS_TEST_FOR_EXCEPTION(bOriginalTransferOp==Teuchos::null, Exceptions::BadCast, "MueLu::RebalanceBlockTransferFactory::Build: input matrix P or R is not of type BlockedCrsMatrix! error.");
117 
118  // plausibility check
119  TEUCHOS_TEST_FOR_EXCEPTION(bOriginalTransferOp->Rows() != 2,Exceptions::RuntimeError, "MueLu::RebalanceBlockTransferFactory::Build: number of block rows of transfer operator is not equal 2. error.");
120  TEUCHOS_TEST_FOR_EXCEPTION(bOriginalTransferOp->Cols() != 2,Exceptions::RuntimeError, "MueLu::RebalanceBlockTransferFactory::Build: number of block columns of transfer operator is not equal 2. error.");
121 
122  // rebuild rebalanced blocked P operator
123  std::vector<GO> fullRangeMapVector;
124  std::vector<GO> fullDomainMapVector;
125  std::vector<RCP<const Map> > subBlockRRangeMaps;
126  std::vector<RCP<const Map> > subBlockRDomainMaps;
127  subBlockRRangeMaps.reserve(bOriginalTransferOp->Rows()); // reserve size for block P operators
128  subBlockRDomainMaps.reserve(bOriginalTransferOp->Cols()); // reserve size for block P operators
129 
130  std::vector<Teuchos::RCP<Matrix> > subBlockRebR;
131  subBlockRebR.reserve(bOriginalTransferOp->Cols());
132 
133  int curBlockId = 0;
134  Teuchos::RCP<const Import> rebalanceImporter = Teuchos::null;
135  std::vector<Teuchos::RCP<const FactoryManagerBase> >::const_iterator it;
136  for (it = FactManager_.begin(); it != FactManager_.end(); ++it) {
137  // begin SubFactoryManager environment
138  SetFactoryManager fineSFM (rcpFromRef(fineLevel), *it);
139  SetFactoryManager coarseSFM(rcpFromRef(coarseLevel), *it);
140 
141  rebalanceImporter = coarseLevel.Get<Teuchos::RCP<const Import> >("Importer", (*it)->GetFactory("Importer").get());
142 
143  // extract matrix block
144  Teuchos::RCP<CrsMatrix> Rmii = bOriginalTransferOp->getMatrix(curBlockId, curBlockId);
145  Teuchos::RCP<CrsMatrixWrap> Rwii = Teuchos::rcp(new CrsMatrixWrap(Rmii));
146  Teuchos::RCP<Matrix> Rii = Teuchos::rcp_dynamic_cast<Matrix>(Rwii);
147 
148  Teuchos::RCP<Matrix> rebRii;
149  if(rebalanceImporter != Teuchos::null) {
150  std::stringstream ss; ss << "Rebalancing restriction block R(" << curBlockId << "," << curBlockId << ")";
151  SubFactoryMonitor m1(*this, ss.str(), coarseLevel);
152  {
153  SubFactoryMonitor subM(*this, "Rebalancing restriction -- fusedImport", coarseLevel);
154  // Note: The 3rd argument says to use originalR's domain map.
155 
156  RCP<Map> dummy;
157  rebRii = MatrixFactory::Build(Rii,*rebalanceImporter,dummy,rebalanceImporter->getTargetMap());
158  }
159 
160  RCP<ParameterList> params = rcp(new ParameterList());
161  params->set("printLoadBalancingInfo", true);
162  std::stringstream ss2; ss2 << "R(" << curBlockId << "," << curBlockId << ") rebalanced:";
163  GetOStream(Statistics0) << PerfUtils::PrintMatrixInfo(*rebRii, ss2.str(), params);
164  } else {
165  rebRii = Rii;
166  RCP<ParameterList> params = rcp(new ParameterList());
167  params->set("printLoadBalancingInfo", true);
168  std::stringstream ss2; ss2 << "R(" << curBlockId << "," << curBlockId << ") not rebalanced:";
169  GetOStream(Statistics0) << PerfUtils::PrintMatrixInfo(*rebRii, ss2.str(), params);
170  }
171 
172  // fix striding information for rebalanced diagonal block rebRii
173  RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > rgRMapExtractor = bOriginalTransferOp->getRangeMapExtractor(); // original map extractor
174  Teuchos::RCP<const StridedMap> orig_stridedRgMap = Teuchos::rcp_dynamic_cast<const StridedMap>(rgRMapExtractor->getMap(Teuchos::as<size_t>(curBlockId)));
175  Teuchos::RCP<const Map> stridedRgMap = Teuchos::null;
176  if(orig_stridedRgMap != Teuchos::null) {
177  std::vector<size_t> stridingData = orig_stridedRgMap->getStridingData();
178  Teuchos::ArrayView< const GlobalOrdinal > nodeRangeMapii = rebRii->getRangeMap()->getNodeElementList();
179  stridedRgMap = StridedMapFactory::Build(
180  originalTransferOp->getRangeMap()->lib(),
181  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
182  nodeRangeMapii,
183  rebRii->getRangeMap()->getIndexBase(),
184  stridingData,
185  originalTransferOp->getRangeMap()->getComm(),
186  orig_stridedRgMap->getStridedBlockId(),
187  orig_stridedRgMap->getOffset());
188  }
189  RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > doRMapExtractor = bOriginalTransferOp->getDomainMapExtractor(); // original map extractor
190  Teuchos::RCP<const StridedMap> orig_stridedDoMap = Teuchos::rcp_dynamic_cast<const StridedMap>(doRMapExtractor->getMap(Teuchos::as<size_t>(curBlockId)));
191  Teuchos::RCP<const Map> stridedDoMap = Teuchos::null;
192  if(orig_stridedDoMap != Teuchos::null) {
193  std::vector<size_t> stridingData = orig_stridedDoMap->getStridingData();
194  Teuchos::ArrayView< const GlobalOrdinal > nodeDomainMapii = rebRii->getDomainMap()->getNodeElementList();
195  stridedDoMap = StridedMapFactory::Build(
196  originalTransferOp->getDomainMap()->lib(),
197  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
198  nodeDomainMapii,
199  rebRii->getDomainMap()->getIndexBase(),
200  stridingData,
201  originalTransferOp->getDomainMap()->getComm(),
202  orig_stridedDoMap->getStridedBlockId(),
203  orig_stridedDoMap->getOffset());
204  }
205 
206  TEUCHOS_TEST_FOR_EXCEPTION(stridedRgMap == Teuchos::null,Exceptions::RuntimeError, "MueLu::RebalanceBlockRestrictionFactory::Build: failed to generate striding information. error.");
207  TEUCHOS_TEST_FOR_EXCEPTION(stridedDoMap == Teuchos::null,Exceptions::RuntimeError, "MueLu::RebalanceBlockRestrictionFactory::Build: failed to generate striding information. error.");
208 
209  // replace stridedMaps view in diagonal sub block
210  if(rebRii->IsView("stridedMaps")) rebRii->RemoveView("stridedMaps");
211  rebRii->CreateView("stridedMaps", stridedRgMap, stridedDoMap);
212 
213  // store rebalanced subblock
214  subBlockRebR.push_back(rebRii);
215 
216  // append strided row map (= range map) to list of range maps.
217  Teuchos::RCP<const Map> rangeMapii = rebRii->getRowMap("stridedMaps"); //rebRii->getRangeMap();
218  subBlockRRangeMaps.push_back(rangeMapii);
219  Teuchos::ArrayView< const GlobalOrdinal > nodeRangeMapii = rebRii->getRangeMap()->getNodeElementList();
220  fullRangeMapVector.insert(fullRangeMapVector.end(), nodeRangeMapii.begin(), nodeRangeMapii.end());
221  sort(fullRangeMapVector.begin(), fullRangeMapVector.end());
222 
223  // append strided col map (= domain map) to list of range maps.
224  Teuchos::RCP<const Map> domainMapii = rebRii->getColMap("stridedMaps"); //rebRii->getDomainMap();
225  subBlockRDomainMaps.push_back(domainMapii);
226  Teuchos::ArrayView< const GlobalOrdinal > nodeDomainMapii = rebRii->getDomainMap()->getNodeElementList();
227  fullDomainMapVector.insert(fullDomainMapVector.end(), nodeDomainMapii.begin(), nodeDomainMapii.end());
228  sort(fullDomainMapVector.begin(), fullDomainMapVector.end());
229 
231 
232  // rebalance null space
233  if(rebalanceImporter != Teuchos::null)
234  { // rebalance null space
235  std::stringstream ss2; ss2 << "Rebalancing nullspace block(" << curBlockId << "," << curBlockId << ")";
236  SubFactoryMonitor subM(*this, ss2.str(), coarseLevel);
237 
238  RCP<MultiVector> nullspace = coarseLevel.Get<RCP<MultiVector> >("Nullspace", (*it)->GetFactory("Nullspace").get());
239  RCP<MultiVector> permutedNullspace = MultiVectorFactory::Build(rebalanceImporter->getTargetMap(), nullspace->getNumVectors());
240  permutedNullspace->doImport(*nullspace, *rebalanceImporter, Xpetra::INSERT);
241 
242  // TODO think about this
243  //if (pL.get<bool>("repartition: use subcommunicators") == true) // TODO either useSubcomm is enabled everywhere or nowhere
244  //permutedNullspace->replaceMap(permutedNullspace->getMap()->removeEmptyProcesses());
245 
246  coarseLevel.Set<RCP<MultiVector> >("Nullspace", permutedNullspace, (*it)->GetFactory("Nullspace").get());
247 
248  } // end rebalance null space
249  else { // do nothing
250  RCP<MultiVector> nullspace = coarseLevel.Get<RCP<MultiVector> >("Nullspace", (*it)->GetFactory("Nullspace").get());
251  coarseLevel.Set<RCP<MultiVector> >("Nullspace", nullspace, (*it)->GetFactory("Nullspace").get());
252  }
253 
255 
256  curBlockId++;
257  } // end for loop
258 
259  // extract map index base from maps of blocked P
260  GO rangeIndexBase = originalTransferOp->getRangeMap()->getIndexBase();
261  GO domainIndexBase= originalTransferOp->getDomainMap()->getIndexBase();
262 
263  // check this
264  RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > rangeRMapExtractor = bOriginalTransferOp->getRangeMapExtractor(); // original map extractor
265  Teuchos::ArrayView<GO> fullRangeMapGIDs(fullRangeMapVector.size() ? &fullRangeMapVector[0] : 0,fullRangeMapVector.size());
266  Teuchos::RCP<const StridedMap> stridedRgFullMap = Teuchos::rcp_dynamic_cast<const StridedMap>(rangeRMapExtractor->getFullMap());
267  Teuchos::RCP<const Map > fullRangeMap = Teuchos::null;
268  if(stridedRgFullMap != Teuchos::null) {
269  std::vector<size_t> stridedData = stridedRgFullMap->getStridingData();
270  fullRangeMap =
271  StridedMapFactory::Build(
272  originalTransferOp->getRangeMap()->lib(),
273  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
274  fullRangeMapGIDs,
275  rangeIndexBase,
276  stridedData,
277  originalTransferOp->getRangeMap()->getComm(),
278  stridedRgFullMap->getStridedBlockId(),
279  stridedRgFullMap->getOffset());
280  } else {
281  fullRangeMap =
282  MapFactory::Build(
283  originalTransferOp->getRangeMap()->lib(),
284  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
285  fullRangeMapGIDs,
286  rangeIndexBase,
287  originalTransferOp->getRangeMap()->getComm());
288  }
289 
290  RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > domainAMapExtractor = bOriginalTransferOp->getDomainMapExtractor();
291  Teuchos::ArrayView<GO> fullDomainMapGIDs(fullDomainMapVector.size() ? &fullDomainMapVector[0] : 0,fullDomainMapVector.size());
292  Teuchos::RCP<const StridedMap> stridedDoFullMap = Teuchos::rcp_dynamic_cast<const StridedMap>(domainAMapExtractor->getFullMap());
293  Teuchos::RCP<const Map > fullDomainMap = Teuchos::null;
294  if(stridedDoFullMap != Teuchos::null) {
295  TEUCHOS_TEST_FOR_EXCEPTION(stridedDoFullMap==Teuchos::null, Exceptions::BadCast, "MueLu::BlockedPFactory::Build: full map in domain map extractor has no striding information! error.");
296  std::vector<size_t> stridedData2 = stridedDoFullMap->getStridingData();
297  fullDomainMap =
298  StridedMapFactory::Build(
299  originalTransferOp->getDomainMap()->lib(),
300  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
301  fullDomainMapGIDs,
302  domainIndexBase,
303  stridedData2,
304  originalTransferOp->getDomainMap()->getComm(),
305  stridedDoFullMap->getStridedBlockId(),
306  stridedDoFullMap->getOffset());
307  } else {
308 
309  fullDomainMap =
310  MapFactory::Build(
311  originalTransferOp->getDomainMap()->lib(),
312  Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
313  fullDomainMapGIDs,
314  domainIndexBase,
315  originalTransferOp->getDomainMap()->getComm());
316  }
317 
318  // build map extractors
319  Teuchos::RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > rangeMapExtractor =
320  Xpetra::MapExtractorFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(fullRangeMap, subBlockRRangeMaps);
321  Teuchos::RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > domainMapExtractor =
322  Xpetra::MapExtractorFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(fullDomainMap, subBlockRDomainMaps);
323 
324  Teuchos::RCP<BlockedCrsMatrix> bRebR = Teuchos::rcp(new BlockedCrsMatrix(rangeMapExtractor,domainMapExtractor,10));
325  for(size_t i = 0; i<subBlockRRangeMaps.size(); i++) {
326  Teuchos::RCP<const CrsMatrixWrap> crsOpii = Teuchos::rcp_dynamic_cast<const CrsMatrixWrap>(subBlockRebR[i]);
327  Teuchos::RCP<CrsMatrix> crsMatii = crsOpii->getCrsMatrix();
328  bRebR->setMatrix(i,i,crsMatii);
329  }
330 
331  bRebR->fillComplete();
332 
333  Set(coarseLevel, "R", Teuchos::rcp_dynamic_cast<Matrix>(bRebR)); // do nothing // TODO remove this!
334 
335 } // Build
336 
337 } // namespace MueLu
338 
339 #endif /* HAVE_MUELU_EXPERIMENTAL */
340 #endif /* MUELU_REBALANCEBLOCKRESTRICTIONFACTORY_DEF_HPP_ */
void DeclareInput(Level &fineLevel, Level &coarseLevel) const
Specifies the data that this class needs, and the factories that generate that data.
Exception indicating invalid cast attempted.
Timer to be used in factories. Similar to Monitor but with additional timers.
Namespace for MueLu classes and methods.
Print statistics that do not involve significant additional computation.
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
Timer to be used in factories. Similar to SubMonitor but adds a timer level by level.
static std::string PrintMatrixInfo(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
RCP< const ParameterList > GetValidParameterList() const
Return a const parameter list of valid parameters that setParameterList() will accept.
Exception throws to report errors in the internal logical of the program.
void Build(Level &fineLevel, Level &coarseLevel) const
Build an object with this factory.
An exception safe way to call the method &#39;Level::SetFactoryManager()&#39;.
void AddFactoryManager(RCP< const FactoryManagerBase > FactManager)
Add a factory manager.
void DeclareInput(const std::string &ename, const FactoryBase *factory, const FactoryBase *requestedBy=NoFactory::get())
Callback from FactoryBase::CallDeclareInput() and FactoryBase::DeclareInput()