MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_GeometricInterpolationPFactory_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_GEOMETRICINTERPOLATIONPFACTORY_DEF_HPP
47 #define MUELU_GEOMETRICINTERPOLATIONPFACTORY_DEF_HPP
48 
49 #include "Xpetra_CrsGraph.hpp"
50 #include "Xpetra_CrsMatrixUtils.hpp"
51 
52 #include "MueLu_MasterList.hpp"
53 #include "MueLu_Monitor.hpp"
54 #include "MueLu_Aggregates.hpp"
55 
56 // Including this one last ensure that the short names of the above headers are defined properly
58 
59 namespace MueLu {
60 
61  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
63  RCP<ParameterList> validParamList = rcp(new ParameterList());
64 
65 #define SET_VALID_ENTRY(name) validParamList->setEntry(name, MasterList::getEntry(name))
66  SET_VALID_ENTRY("interp: interpolation order");
67  SET_VALID_ENTRY("interp: build coarse coordinates");
68 #undef SET_VALID_ENTRY
69 
70  // general variables needed in GeometricInterpolationPFactory
71  validParamList->set<RCP<const FactoryBase> >("A", Teuchos::null,
72  "Generating factory of the matrix A");
73  validParamList->set<RCP<const FactoryBase> >("Aggregates", Teuchos::null,
74  "Aggregates generated by StructuredAggregationFactory used to construct a piece-constant prolongator.");
75  validParamList->set<RCP<const FactoryBase> >("prolongatorGraph", Teuchos::null,
76  "Graph generated by StructuredAggregationFactory used to construct a piece-linear prolongator.");
77  validParamList->set<RCP<const FactoryBase> >("Coordinates", Teuchos::null,
78  "Fine level coordinates used to construct piece-wise linear prolongator and coarse level coordinates.");
79  validParamList->set<RCP<const FactoryBase> >("coarseCoordinatesFineMap", Teuchos::null,
80  "map of the coarse coordinates' GIDs as indexed on the fine mesh.");
81  validParamList->set<RCP<const FactoryBase> >("coarseCoordinatesMap", Teuchos::null,
82  "map of the coarse coordinates' GIDs as indexed on the coarse mesh.");
83  validParamList->set<RCP<const FactoryBase> >("Nullspace", Teuchos::null,
84  "Fine level nullspace used to construct the coarse level nullspace.");
85  validParamList->set<RCP<const FactoryBase> >("numDimensions", Teuchos::null,
86  "Number of spacial dimensions in the problem.");
87  validParamList->set<RCP<const FactoryBase> >("lCoarseNodesPerDim", Teuchos::null,
88  "Number of nodes per spatial dimension on the coarse grid.");
89  validParamList->set<bool> ("keep coarse coords", false, "Flag to keep coordinates for special coarse grid solve");
90  validParamList->set<bool> ("interp: remove small entries", true, "Remove small interpolation coeficient from prolongator to reduce fill-in on coarse level");
91 
92  return validParamList;
93  }
94 
95  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
97  DeclareInput(Level& fineLevel, Level& /* coarseLevel */) const {
98  const ParameterList& pL = GetParameterList();
99 
100  Input(fineLevel, "A");
101  Input(fineLevel, "Nullspace");
102  Input(fineLevel, "numDimensions");
103  Input(fineLevel, "prolongatorGraph");
104  Input(fineLevel, "lCoarseNodesPerDim");
105 
106  if( pL.get<bool>("interp: build coarse coordinates") ||
107  (pL.get<int>("interp: interpolation order") == 1) ) {
108  Input(fineLevel, "Coordinates");
109  Input(fineLevel, "coarseCoordinatesFineMap");
110  Input(fineLevel, "coarseCoordinatesMap");
111  }
112 
113  }
114 
115  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
117  Build(Level& fineLevel, Level &coarseLevel) const {
118  return BuildP(fineLevel, coarseLevel);
119  }
120 
121  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
123  BuildP(Level &fineLevel, Level &coarseLevel) const {
124  FactoryMonitor m(*this, "BuildP", coarseLevel);
125 
126  // Set debug outputs based on environment variable
128  if(const char* dbg = std::getenv("MUELU_GEOMETRICINTERPOLATIONPFACTORY_DEBUG")) {
129  out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
130  out->setShowAllFrontMatter(false).setShowProcRank(true);
131  } else {
132  out = Teuchos::getFancyOStream(rcp(new Teuchos::oblackholestream()));
133  }
134 
135  *out << "Starting GeometricInterpolationPFactory::BuildP." << std::endl;
136 
137  // Get inputs from the parameter list
138  const ParameterList& pL = GetParameterList();
139  const bool removeSmallEntries = pL.get<bool>("interp: remove small entries");
140  const bool buildCoarseCoordinates = pL.get<bool>("interp: build coarse coordinates");
141  const int interpolationOrder = pL.get<int> ("interp: interpolation order");
142  const int numDimensions = Get<int>(fineLevel, "numDimensions");
143 
144  // Declared main input/outputs to be retrieved and placed on the fine resp. coarse level
145  RCP<Matrix> A = Get<RCP<Matrix> >(fineLevel, "A");
146  RCP<const CrsGraph> prolongatorGraph = Get<RCP<CrsGraph> >(fineLevel, "prolongatorGraph");
147  RCP<realvaluedmultivector_type> fineCoordinates, coarseCoordinates;
148  RCP<Matrix> P;
149 
150  // Check if we need to build coarse coordinates as they are used if we construct
151  // a linear interpolation prolongator
152  if(buildCoarseCoordinates || (interpolationOrder == 1)) {
153  SubFactoryMonitor sfm(*this, "BuildCoordinates", coarseLevel);
154  RCP<const Map> coarseCoordsFineMap = Get< RCP<const Map> >(fineLevel, "coarseCoordinatesFineMap");
155  RCP<const Map> coarseCoordsMap = Get< RCP<const Map> >(fineLevel, "coarseCoordinatesMap");
156  fineCoordinates = Get< RCP<realvaluedmultivector_type> >(fineLevel, "Coordinates");
157  coarseCoordinates = Xpetra::MultiVectorFactory<real_type,LO,GO,Node>::Build(coarseCoordsFineMap,
158  fineCoordinates->getNumVectors());
159  RCP<const Import> coordsImporter = ImportFactory::Build(fineCoordinates->getMap(),
160  coarseCoordsFineMap);
161  coarseCoordinates->doImport(*fineCoordinates, *coordsImporter, Xpetra::INSERT);
162  coarseCoordinates->replaceMap(coarseCoordsMap);
163 
164  Set(coarseLevel, "Coordinates", coarseCoordinates);
165 
166  if(pL.get<bool>("keep coarse coords")) {
167  coarseLevel.Set<RCP<realvaluedmultivector_type> >("Coordinates2", coarseCoordinates, NoFactory::get());
168  }
169  }
170 
171  *out << "Fine and coarse coordinates have been loaded from the fine level and set on the coarse level." << std::endl;
172 
173  if(interpolationOrder == 0) {
174  SubFactoryMonitor sfm(*this, "BuildConstantP", coarseLevel);
175  // Compute the prolongator using piece-wise constant interpolation
176  BuildConstantP(P, prolongatorGraph, A);
177  } else if(interpolationOrder == 1) {
178  // Compute the prolongator using piece-wise linear interpolation
179  // First get all the required coordinates to compute the local part of P
180  RCP<const Map> prolongatorColMap = prolongatorGraph->getColMap();
181 
182  const size_t dofsPerNode = static_cast<size_t>(A->GetFixedBlockSize());
183  const size_t numColIndices = prolongatorColMap->getNodeNumElements();
184  TEUCHOS_TEST_FOR_EXCEPTION((numColIndices % dofsPerNode) != 0,
186  "Something went wrong, the number of columns in the prolongator is not a multiple of dofsPerNode!");
187  const size_t numGhostCoords = numColIndices / dofsPerNode;
188  const GO indexBase = prolongatorColMap->getIndexBase();
189  const GO coordIndexBase = fineCoordinates->getMap()->getIndexBase();
190 
191  ArrayView<const GO> prolongatorColIndices = prolongatorColMap->getNodeElementList();
192  Array<GO> ghostCoordIndices(numGhostCoords);
193  for(size_t ghostCoordIdx = 0; ghostCoordIdx < numGhostCoords; ++ghostCoordIdx) {
194  ghostCoordIndices[ghostCoordIdx]
195  = (prolongatorColIndices[ghostCoordIdx*dofsPerNode] - indexBase) / dofsPerNode
196  + coordIndexBase;
197  }
198  RCP<Map> ghostCoordMap = MapFactory::Build(fineCoordinates->getMap()->lib(),
199  prolongatorColMap->getGlobalNumElements() / dofsPerNode,
200  ghostCoordIndices(),
201  coordIndexBase,
202  fineCoordinates->getMap()->getComm());
203 
204  RCP<realvaluedmultivector_type> ghostCoordinates
205  = Xpetra::MultiVectorFactory<real_type,LO,GO,NO>::Build(ghostCoordMap,
206  fineCoordinates->getNumVectors());
207  RCP<const Import> ghostImporter = ImportFactory::Build(coarseCoordinates->getMap(),
208  ghostCoordMap);
209  ghostCoordinates->doImport(*coarseCoordinates, *ghostImporter, Xpetra::INSERT);
210 
211  BuildLinearP(coarseLevel, A, prolongatorGraph, fineCoordinates,
212  ghostCoordinates, numDimensions, removeSmallEntries, P);
213  }
214 
215  *out << "The prolongator matrix has been built." << std::endl;
216 
217  {
218  SubFactoryMonitor sfm(*this, "BuildNullspace", coarseLevel);
219  // Build the coarse nullspace
220  RCP<MultiVector> fineNullspace = Get< RCP<MultiVector> > (fineLevel, "Nullspace");
221  RCP<MultiVector> coarseNullspace = MultiVectorFactory::Build(P->getDomainMap(),
222  fineNullspace->getNumVectors());
223  P->apply(*fineNullspace, *coarseNullspace, Teuchos::TRANS, Teuchos::ScalarTraits<SC>::one(),
225  Set(coarseLevel, "Nullspace", coarseNullspace);
226  }
227 
228  *out << "The coarse nullspace is constructed and set on the coarse level." << std::endl;
229 
230  Set(coarseLevel, "P", P);
231 
232  *out << "GeometricInterpolationPFactory::BuildP has completed." << std::endl;
233 
234  } // BuildP
235 
236  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
238  BuildConstantP(RCP<Matrix>& P, RCP<const CrsGraph>& prolongatorGraph, RCP<Matrix>& A) const {
239 
240  // Set debug outputs based on environment variable
242  if(const char* dbg = std::getenv("MUELU_GEOMETRICINTERPOLATIONPFACTORY_DEBUG")) {
243  out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
244  out->setShowAllFrontMatter(false).setShowProcRank(true);
245  } else {
246  out = Teuchos::getFancyOStream(rcp(new Teuchos::oblackholestream()));
247  }
248 
249  *out << "BuildConstantP" << std::endl;
250 
251  std::vector<size_t> strideInfo(1);
252  strideInfo[0] = A->GetFixedBlockSize();
253  RCP<const StridedMap> stridedDomainMap =
254  StridedMapFactory::Build(prolongatorGraph->getDomainMap(), strideInfo);
255 
256  *out << "Call prolongator constructor" << std::endl;
257 
258  // Create the prolongator matrix and its associated objects
259  RCP<ParameterList> dummyList = rcp(new ParameterList());
260  P = rcp(new CrsMatrixWrap(prolongatorGraph, dummyList));
261  RCP<CrsMatrix> PCrs = rcp_dynamic_cast<CrsMatrixWrap>(P)->getCrsMatrix();
262  PCrs->setAllToScalar(1.0);
263  PCrs->fillComplete();
264 
265  // set StridingInformation of P
266  if (A->IsView("stridedMaps") == true) {
267  P->CreateView("stridedMaps", A->getRowMap("stridedMaps"), stridedDomainMap);
268  } else {
269  P->CreateView("stridedMaps", P->getRangeMap(), stridedDomainMap);
270  }
271 
272  } // BuildConstantP
273 
274  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
276  BuildLinearP(Level& coarseLevel,
277  RCP<Matrix>& A, RCP<const CrsGraph>& prolongatorGraph,
278  RCP<realvaluedmultivector_type>& fineCoordinates,
279  RCP<realvaluedmultivector_type>& ghostCoordinates,
280  const int numDimensions, const bool removeSmallEntries,
281  RCP<Matrix>& P) const {
282 
283  // Set debug outputs based on environment variable
285  if(const char* dbg = std::getenv("MUELU_GEOMETRICINTERPOLATIONPFACTORY_DEBUG")) {
286  out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
287  out->setShowAllFrontMatter(false).setShowProcRank(true);
288  } else {
289  out = Teuchos::getFancyOStream(rcp(new Teuchos::oblackholestream()));
290  }
291 
292  // Compute 2^numDimensions using bit logic to avoid round-off errors
293  const int numInterpolationPoints = 1 << numDimensions;
294  const int dofsPerNode = A->GetFixedBlockSize();
295 
296  RCP<ParameterList> dummyList = rcp(new ParameterList());
297  P = rcp(new CrsMatrixWrap(prolongatorGraph, dummyList));
298  RCP<CrsMatrix> PCrs = rcp_dynamic_cast<CrsMatrixWrap>(P)->getCrsMatrix();
299  PCrs->resumeFill(); // The Epetra matrix is considered filled at this point.
300 
301  {
302  *out << "Entering BuildLinearP" << std::endl;
303  SubFactoryMonitor sfm(*this, "BuildLinearP", coarseLevel);
304 
305  // Extract coordinates for interpolation stencil calculations
306  const LO numFineNodes = fineCoordinates->getLocalLength();
307  const LO numGhostNodes = ghostCoordinates->getLocalLength();
308  Array<ArrayRCP<const real_type> > fineCoords(3);
309  Array<ArrayRCP<const real_type> > ghostCoords(3);
310  const real_type realZero = Teuchos::as<real_type>(0.0);
311  ArrayRCP<real_type> fineZero(numFineNodes, realZero);
312  ArrayRCP<real_type> ghostZero(numGhostNodes, realZero);
313  for(int dim = 0; dim < 3; ++dim) {
314  if(dim < numDimensions) {
315  fineCoords[dim] = fineCoordinates->getData(dim);
316  ghostCoords[dim] = ghostCoordinates->getData(dim);
317  } else {
318  fineCoords[dim] = fineZero;
319  ghostCoords[dim] = ghostZero;
320  }
321  }
322 
323  *out << "Coordinates extracted from the multivectors!" << std::endl;
324 
325  { // Construct the linear interpolation prolongator
326  LO interpolationNodeIdx = 0, rowIdx = 0;
327  ArrayView<const LO> colIndices;
328  Array<SC> values;
329  Array<Array<real_type> > coords(numInterpolationPoints + 1);
330  Array<real_type> stencil(numInterpolationPoints);
331  for(LO nodeIdx = 0; nodeIdx < numFineNodes; ++nodeIdx) {
332  if(PCrs->getNumEntriesInLocalRow(nodeIdx*dofsPerNode) == 1) {
333  values.resize(1);
334  values[0] = 1.0;
335  for(LO dof = 0; dof < dofsPerNode; ++dof) {
336  rowIdx = nodeIdx*dofsPerNode + dof;
337  prolongatorGraph->getLocalRowView(rowIdx, colIndices);
338  PCrs->replaceLocalValues(rowIdx, colIndices, values());
339  }
340  } else {
341  // Extract the coordinates associated with the current node
342  // and the neighboring coarse nodes
343  coords[0].resize(3);
344  for(int dim = 0; dim < 3; ++dim) {
345  coords[0][dim] = fineCoords[dim][nodeIdx];
346  }
347  prolongatorGraph->getLocalRowView(nodeIdx*dofsPerNode, colIndices);
348  for(int interpolationIdx=0; interpolationIdx < numInterpolationPoints; ++interpolationIdx) {
349  coords[interpolationIdx + 1].resize(3);
350  interpolationNodeIdx = colIndices[interpolationIdx] / dofsPerNode;
351  for(int dim = 0; dim < 3; ++dim) {
352  coords[interpolationIdx + 1][dim] = ghostCoords[dim][interpolationNodeIdx];
353  }
354  }
355  RCP<Teuchos::TimeMonitor> tm = rcp(new Teuchos::TimeMonitor(*Teuchos::TimeMonitor::getNewTimer("Compute Linear Interpolation")));
356  ComputeLinearInterpolationStencil(numDimensions, numInterpolationPoints, coords, stencil);
357  tm = Teuchos::null;
358  values.resize(numInterpolationPoints);
359  for(LO valueIdx = 0; valueIdx < numInterpolationPoints; ++valueIdx) {
360  values[valueIdx] = Teuchos::as<SC>(stencil[valueIdx]);
361  }
362 
363  // Set values in all the rows corresponding to nodeIdx
364  for(LO dof = 0; dof < dofsPerNode; ++dof) {
365  rowIdx = nodeIdx*dofsPerNode + dof;
366  prolongatorGraph->getLocalRowView(rowIdx, colIndices);
367  PCrs->replaceLocalValues(rowIdx, colIndices, values());
368  }
369  } // Check for Coarse vs. Fine point
370  } // Loop over fine nodes
371  } // Construct the linear interpolation prolongator
372 
373  *out << "The calculation of the interpolation stencils has completed." << std::endl;
374 
375  PCrs->fillComplete();
376  }
377 
378  *out << "All values in P have been set and fillComplete has been performed." << std::endl;
379 
380  // Note lbv Jan 29 2019: this should be handle at aggregation level
381  // if the user really does not want potential d2 neighbors on coarse grid
382  // that way we would avoid a new graph construction...
383 
384  // Check if we want to remove small entries from P
385  // to reduce stencil growth on next level.
386  if(removeSmallEntries) {
387  *out << "Entering remove small entries" << std::endl;
388  SubFactoryMonitor sfm(*this, "remove small entries", coarseLevel);
389 
390  ArrayRCP<const size_t> rowptrOrig;
391  ArrayRCP<const LO> colindOrig;
392  ArrayRCP<const Scalar> valuesOrig;
393  PCrs->getAllValues(rowptrOrig, colindOrig, valuesOrig);
394 
395  const size_t numRows = static_cast<size_t>(rowptrOrig.size() - 1);
396  ArrayRCP<size_t> rowPtr(numRows + 1);
397  ArrayRCP<size_t> nnzOnRows(numRows);
398  rowPtr[0] = 0;
399  size_t countRemovedEntries = 0;
400  for(size_t rowIdx = 0; rowIdx < numRows; ++rowIdx) {
401  for(size_t entryIdx = rowptrOrig[rowIdx]; entryIdx < rowptrOrig[rowIdx + 1]; ++entryIdx) {
402  if(Teuchos::ScalarTraits<Scalar>::magnitude(valuesOrig[entryIdx]) < 1e-6) {++countRemovedEntries;}
403  }
404  rowPtr[rowIdx + 1] = rowptrOrig[rowIdx + 1] - countRemovedEntries;
405  nnzOnRows[rowIdx] = rowPtr[rowIdx + 1] - rowPtr[rowIdx];
406  }
407  GetOStream(Statistics1) << "interp: number of small entries removed= " << countRemovedEntries << " / " << rowptrOrig[numRows] << std::endl;
408 
409  size_t countKeptEntries = 0;
410  ArrayRCP<LO> colInd(rowPtr[numRows]);
411  ArrayRCP<SC> values(rowPtr[numRows]);
412  for(size_t entryIdx = 0; entryIdx < rowptrOrig[numRows]; ++entryIdx) {
413  if(Teuchos::ScalarTraits<Scalar>::magnitude(valuesOrig[entryIdx]) > 1e-6) {
414  colInd[countKeptEntries] = colindOrig[entryIdx];
415  values[countKeptEntries] = valuesOrig[entryIdx];
416  ++countKeptEntries;
417  }
418  }
419 
420  P = rcp(new CrsMatrixWrap(prolongatorGraph->getRowMap(),
421  prolongatorGraph->getColMap(),
422  nnzOnRows));
423  RCP<CrsMatrix> PCrsSqueezed = rcp_dynamic_cast<CrsMatrixWrap>(P)->getCrsMatrix();
424  PCrsSqueezed->resumeFill(); // The Epetra matrix is considered filled at this point.
425  PCrsSqueezed->setAllValues(rowPtr, colInd, values);
426  PCrsSqueezed->expertStaticFillComplete(prolongatorGraph->getDomainMap(),
427  prolongatorGraph->getRangeMap());
428  }
429 
430  std::vector<size_t> strideInfo(1);
431  strideInfo[0] = dofsPerNode;
432  RCP<const StridedMap> stridedDomainMap =
433  StridedMapFactory::Build(prolongatorGraph->getDomainMap(), strideInfo);
434 
435  *out << "The strided maps of P have been computed" << std::endl;
436 
437  // set StridingInformation of P
438  if (A->IsView("stridedMaps") == true) {
439  P->CreateView("stridedMaps", A->getRowMap("stridedMaps"), stridedDomainMap);
440  } else {
441  P->CreateView("stridedMaps", P->getRangeMap(), stridedDomainMap);
442  }
443 
444  } // BuildLinearP
445 
446 
447  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
449  ComputeLinearInterpolationStencil(const int numDimensions, const int numInterpolationPoints,
450  const Array<Array<real_type> > coord,
451  Array<real_type>& stencil) const {
452 
453  // 7 8 Find xi, eta and zeta such that
454  // x---------x
455  // /| /| Rx = x_p - sum N_i(xi,eta,zeta)x_i = 0
456  // 5/ | 6/ | Ry = y_p - sum N_i(xi,eta,zeta)y_i = 0
457  // x---------x | Rz = z_p - sum N_i(xi,eta,zeta)z_i = 0
458  // | | *P | |
459  // | x------|--x We can do this with a Newton solver:
460  // | /3 | /4 We will start with initial guess (xi,eta,zeta) = (0,0,0)
461  // |/ |/ We compute the Jacobian and iterate until convergence...
462  // z y x---------x
463  // | / 1 2 Once we have (xi,eta,zeta), we can evaluate all N_i which
464  // |/ give us the weights for the interpolation stencil!
465  // o---x
466  //
467 
468  Teuchos::SerialDenseMatrix<LO,real_type> Jacobian(numDimensions, numDimensions);
469  Teuchos::SerialDenseVector<LO,real_type> residual(numDimensions);
470  Teuchos::SerialDenseVector<LO,real_type> solutionDirection(numDimensions);
471  Teuchos::SerialDenseVector<LO,real_type> paramCoords(numDimensions);
473  int iter = 0, max_iter = 5;
474  real_type functions[4][8], norm_ref = 1.0, norm2 = 1.0, tol = 1.0e-5;
475  paramCoords.size(numDimensions);
476 
477  while( (iter < max_iter) && (norm2 > tol*norm_ref) ) {
478  ++iter;
479  norm2 = 0.0;
480  solutionDirection.size(numDimensions);
481  residual.size(numDimensions);
482  Jacobian = 0.0;
483 
484  // Compute Jacobian and Residual
485  GetInterpolationFunctions(numDimensions, paramCoords, functions);
486  for(LO i = 0; i < numDimensions; ++i) {
487  residual(i) = coord[0][i]; // Add coordinates from point of interest
488  for(LO k = 0; k < numInterpolationPoints; ++k) {
489  residual(i) -= functions[0][k]*coord[k+1][i]; //Remove contribution from all coarse points
490  }
491  if(iter == 1) {
492  norm_ref += residual(i)*residual(i);
493  if(i == numDimensions - 1) {
494  norm_ref = std::sqrt(norm_ref);
495  }
496  }
497 
498  for(LO j = 0; j < numDimensions; ++j) {
499  for(LO k = 0; k < numInterpolationPoints; ++k) {
500  Jacobian(i,j) += functions[j+1][k]*coord[k+1][i];
501  }
502  }
503  }
504 
505  // Set Jacobian, Vectors and solve problem
506  problem.setMatrix(Teuchos::rcp(&Jacobian, false));
507  problem.setVectors(Teuchos::rcp(&solutionDirection, false), Teuchos::rcp(&residual, false));
508  if(problem.shouldEquilibrate()) {problem.factorWithEquilibration(true);}
509  problem.solve();
510 
511  for(LO i = 0; i < numDimensions; ++i) {
512  paramCoords(i) = paramCoords(i) + solutionDirection(i);
513  }
514 
515  // Recompute Residual norm
516  GetInterpolationFunctions(numDimensions, paramCoords, functions);
517  for(LO i = 0; i < numDimensions; ++i) {
518  real_type tmp = coord[0][i];
519  for(LO k = 0; k < numInterpolationPoints; ++k) {
520  tmp -= functions[0][k]*coord[k+1][i];
521  }
522  norm2 += tmp*tmp;
523  tmp = 0.0;
524  }
525  norm2 = std::sqrt(norm2);
526  }
527 
528  // Load the interpolation values onto the stencil.
529  for(LO i = 0; i < numInterpolationPoints; ++i) {
530  stencil[i] = functions[0][i];
531  }
532 
533  } // End ComputeLinearInterpolationStencil
534 
535  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
537  GetInterpolationFunctions(const LO numDimensions,
538  const Teuchos::SerialDenseVector<LO, real_type> parametricCoordinates,
539  real_type functions[4][8]) const {
540  real_type xi = 0.0, eta = 0.0, zeta = 0.0, denominator = 0.0;
541  if(numDimensions == 1) {
542  xi = parametricCoordinates[0];
543  denominator = 2.0;
544  } else if(numDimensions == 2) {
545  xi = parametricCoordinates[0];
546  eta = parametricCoordinates[1];
547  denominator = 4.0;
548  } else if(numDimensions == 3) {
549  xi = parametricCoordinates[0];
550  eta = parametricCoordinates[1];
551  zeta = parametricCoordinates[2];
552  denominator = 8.0;
553  }
554 
555  functions[0][0] = (1.0 - xi)*(1.0 - eta)*(1.0 - zeta) / denominator;
556  functions[0][1] = (1.0 + xi)*(1.0 - eta)*(1.0 - zeta) / denominator;
557  functions[0][2] = (1.0 - xi)*(1.0 + eta)*(1.0 - zeta) / denominator;
558  functions[0][3] = (1.0 + xi)*(1.0 + eta)*(1.0 - zeta) / denominator;
559  functions[0][4] = (1.0 - xi)*(1.0 - eta)*(1.0 + zeta) / denominator;
560  functions[0][5] = (1.0 + xi)*(1.0 - eta)*(1.0 + zeta) / denominator;
561  functions[0][6] = (1.0 - xi)*(1.0 + eta)*(1.0 + zeta) / denominator;
562  functions[0][7] = (1.0 + xi)*(1.0 + eta)*(1.0 + zeta) / denominator;
563 
564  functions[1][0] = -(1.0 - eta)*(1.0 - zeta) / denominator;
565  functions[1][1] = (1.0 - eta)*(1.0 - zeta) / denominator;
566  functions[1][2] = -(1.0 + eta)*(1.0 - zeta) / denominator;
567  functions[1][3] = (1.0 + eta)*(1.0 - zeta) / denominator;
568  functions[1][4] = -(1.0 - eta)*(1.0 + zeta) / denominator;
569  functions[1][5] = (1.0 - eta)*(1.0 + zeta) / denominator;
570  functions[1][6] = -(1.0 + eta)*(1.0 + zeta) / denominator;
571  functions[1][7] = (1.0 + eta)*(1.0 + zeta) / denominator;
572 
573  functions[2][0] = -(1.0 - xi)*(1.0 - zeta) / denominator;
574  functions[2][1] = -(1.0 + xi)*(1.0 - zeta) / denominator;
575  functions[2][2] = (1.0 - xi)*(1.0 - zeta) / denominator;
576  functions[2][3] = (1.0 + xi)*(1.0 - zeta) / denominator;
577  functions[2][4] = -(1.0 - xi)*(1.0 + zeta) / denominator;
578  functions[2][5] = -(1.0 + xi)*(1.0 + zeta) / denominator;
579  functions[2][6] = (1.0 - xi)*(1.0 + zeta) / denominator;
580  functions[2][7] = (1.0 + xi)*(1.0 + zeta) / denominator;
581 
582  functions[3][0] = -(1.0 - xi)*(1.0 - eta) / denominator;
583  functions[3][1] = -(1.0 + xi)*(1.0 - eta) / denominator;
584  functions[3][2] = -(1.0 - xi)*(1.0 + eta) / denominator;
585  functions[3][3] = -(1.0 + xi)*(1.0 + eta) / denominator;
586  functions[3][4] = (1.0 - xi)*(1.0 - eta) / denominator;
587  functions[3][5] = (1.0 + xi)*(1.0 - eta) / denominator;
588  functions[3][6] = (1.0 - xi)*(1.0 + eta) / denominator;
589  functions[3][7] = (1.0 + xi)*(1.0 + eta) / denominator;
590 
591  } // End GetInterpolationFunctions
592 
593 } // namespace MueLu
594 
595 #endif // MUELU_GEOMETRICINTERPOLATIONPFACTORY_DEF_HPP
basic_FancyOStream & setShowProcRank(const bool showProcRank)
T & get(const std::string &name, T def_value)
ParameterList & set(std::string const &name, T const &value, std::string const &docString="", RCP< const ParameterEntryValidator > const &validator=null)
Timer to be used in factories. Similar to Monitor but with additional timers.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Print more statistics.
void BuildLinearP(Level &coarseLevel, RCP< Matrix > &A, RCP< const CrsGraph > &prolongatorGraph, RCP< realvaluedmultivector_type > &fineCoordinates, RCP< realvaluedmultivector_type > &ghostCoordinates, const int numDimensions, const bool keepD2, RCP< Matrix > &P) const
size_type size() const
static const NoFactory * get()
void GetInterpolationFunctions(const LO numDimensions, const Teuchos::SerialDenseVector< LO, real_type > parametricCoordinates, real_type functions[4][8]) const
static RCP< Time > getNewTimer(const std::string &name)
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
void Build(Level &fineLevel, Level &coarseLevel) const
Build an object with this factory.
Class that holds all level-specific information.
Definition: MueLu_Level.hpp:99
void ComputeLinearInterpolationStencil(const int numDimensions, const int numInterpolationPoints, const Array< Array< real_type > > coord, Array< real_type > &stencil) const
Timer to be used in factories. Similar to SubMonitor but adds a timer level by level.
void factorWithEquilibration(bool flag)
#define SET_VALID_ENTRY(name)
basic_FancyOStream & setShowAllFrontMatter(const bool showAllFrontMatter)
void resize(size_type new_size, const value_type &x=value_type())
void Set(const std::string &ename, const T &entry, const FactoryBase *factory=NoFactory::get())
void DeclareInput(Level &fineLevel, Level &coarseLevel) const
Input.
TransListIter iter
int size(OrdinalType length_in)
int setVectors(const RCP< SerialDenseMatrix< OrdinalType, ScalarType > > &X, const RCP< SerialDenseMatrix< OrdinalType, ScalarType > > &B)
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 BuildConstantP(RCP< Matrix > &P, RCP< const CrsGraph > &prolongatorGraph, RCP< Matrix > &A) const
typename Teuchos::ScalarTraits< SC >::coordinateType real_type
void BuildP(Level &fineLevel, Level &coarseLevel) const
Abstract Build method.
int setMatrix(const RCP< SerialDenseMatrix< OrdinalType, ScalarType > > &A)