Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_Poisson2D_pn_tpetra.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Trilinos: An Object-Oriented Solver Framework
4 //
5 // Copyright 2001-2024 NTESS and the Trilinos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /** \file example_Poisson.cpp
11 \brief Example solution of a Poisson equation on a quad mesh using
12 nodal (Hgrad) elements.
13
14 This example uses the following Trilinos packages:
15 \li Pamgen to generate a Quad mesh.
16 \li Sacado to form the source term from user-specified manufactured solution.
17 \li Intrepid to build the discretization matrix and right-hand side.
18 \li Tpetra to handle the global matrix and vector.
19 \li Isorropia to partition the matrix. (Optional)
20 \li ML to solve the linear system.
21
22
23 \verbatim
24
25 Poisson system:
26
27 div A grad u = f in Omega
28 u = g on Gamma
29
30 where
31 A is a symmetric, positive definite material tensor
32 f is a given source term
33
34 Corresponding discrete linear system for nodal coefficients(x):
35
36 Kx = b
37
38 K - HGrad stiffness matrix
39 b - right hand side vector
40
41 \endverbatim
42
43 \author Created by P. Bochev, D. Ridzal, K. Peterson, D. Hensinger, C. Siefert.
44
45 \remark Usage:
46 \code ./TrilinosCouplings_examples_scaling_example_Poisson.exe \endcode
47
48 \remark Example driver requires input file named Poisson2D.xml with Pamgen
49 formatted mesh description and settings for Isorropia (a version
50 is included in the Trilinos repository with this driver).
51
52 \remark The exact solution (u) and material tensor (A) are set in the
53 functions "exactSolution" and "materialTensor" and may be
54 modified by the user.
55
56 */
57
58 /*** Uncomment if you would like output data for plotting ***/
59 //#define DUMP_DATA
60
61 /**************************************************************/
62 /* Includes */
63 /**************************************************************/
64 #include <stdlib.h>
65
66 // TrilinosCouplings includes
67 #include "TrilinosCouplings_config.h"
68 #include "TrilinosCouplings_Pamgen_Utils.hpp"
69 #include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
70
71
72 // Intrepid includes
73 #include "Intrepid_FunctionSpaceTools.hpp"
74 #include "Intrepid_CellTools.hpp"
75 #include "Intrepid_ArrayTools.hpp"
76 #include "Intrepid_HGRAD_QUAD_Cn_FEM.hpp"
77 #include "Intrepid_HGRAD_QUAD_C2_FEM.hpp"
78 #include "Intrepid_HGRAD_QUAD_C1_FEM.hpp"
79 #include "Intrepid_RealSpaceTools.hpp"
80 #include "Intrepid_DefaultCubatureFactory.hpp"
81 #include "Intrepid_Utils.hpp"
82
83 // Intrepid2 Includes
84 #include "Kokkos_DynRankView.hpp"
85
86 // Tpetra includes
87 #include <Tpetra_CrsMatrix.hpp>
88 #include <Tpetra_Vector.hpp>
89 #include <MatrixMarket_Tpetra.hpp>
90
91 // Teuchos includes
92 #include "Teuchos_oblackholestream.hpp"
93 #include "Teuchos_RCP.hpp"
94 #include "Teuchos_BLAS.hpp"
95 #include "Teuchos_GlobalMPISession.hpp"
96 #include "Teuchos_XMLParameterListHelpers.hpp"
97
98 // Shards includes
99 #include "Shards_CellTopology.hpp"
100
101 // Pamgen includes
102 #include "create_inline_mesh.h"
103 #include "pamgen_im_exodusII_l.h"
104 #include "pamgen_im_ne_nemesisI_l.h"
105 #include "pamgen_extras.h"
106
107 // MueLu Includes
108 # include "MueLu.hpp"
109 # include "MueLu_ParameterListInterpreter.hpp"
110 # include "MueLu_TpetraOperator.hpp"
111 # include "MueLu_Utilities.hpp"
112 # include "MueLu_HierarchyManager.hpp"
113 # include "MueLu_FactoryManagerBase.hpp"
114 # include "MueLu_CreateTpetraPreconditioner.hpp"
115 // MueLu/Avatar Includes
116 #ifdef HAVE_TRILINOSCOUPLINGS_AVATAR
117 # include "MueLu_AvatarInterface.hpp"
118 #endif
119
120 #ifdef HAVE_INTREPID_KOKKOS
121 #include "Sacado.hpp"
122 #else
123 // Sacado includes
124 #include "Sacado_No_Kokkos.hpp"
125 #endif
126
127 #include <BelosConfigDefs.hpp>
128 #include <BelosLinearProblem.hpp>
129 #include <BelosPseudoBlockCGSolMgr.hpp>
130 #include <BelosPseudoBlockGmresSolMgr.hpp>
131 #include <BelosFixedPointSolMgr.hpp>
132 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
133 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
134
135 using namespace std;
136 using namespace Intrepid;
137 using Teuchos::RCP;
138 using Teuchos::ArrayRCP;
139 using Teuchos::Array;
140 using Teuchos::ArrayView;
141 using Teuchos::rcp;
142 using Teuchos::rcpFromRef;
143 using Teuchos::TimeMonitor;
144 using Teuchos::ParameterList;
145
146 // for debugging
147 #define zwrap(x) (std::abs(x)<1e-10 ? 0.0 : x)
148
149 // Statistics for machine learning
150 const int NUM_STATISTICS = 8;
151 std::vector<double> local_stat_max(NUM_STATISTICS);
152 std::vector<double> local_stat_min(NUM_STATISTICS);
153 std::vector<double> local_stat_sum(NUM_STATISTICS);
154
155
156 // Disable the full set of problem statistics
157 const bool use_new_problem_stats = true;
158
159 struct fecomp{
160 bool operator () ( topo_entity* x, topo_entity* y )const
161 {
162 if(x->sorted_local_node_ids < y->sorted_local_node_ids)return true;
163 return false;
164 }
165 };
166
167 template<class FC>
168 double distance2(const FC & coord, int n1, int n2) {
169 double dist = 0.0;
170 for(int i=0; i<coord.dimension(1); i++)
171 dist += (coord(n2,i) -coord(n1,i)) * (coord(n2,i) -coord(n1,i));
172 return sqrt(dist);
173 }
174
175
176 /*********************************************************/
177 /* Typedefs */
178 /*********************************************************/
179 typedef double scalar_type;
180 typedef Teuchos::ScalarTraits<scalar_type> ScalarTraits;
181 using local_ordinal_type = Tpetra::Map<>::local_ordinal_type;
182 using global_ordinal_type = Tpetra::Map<>::global_ordinal_type;
183 typedef Tpetra::KokkosClassic::DefaultNode::DefaultNodeType NO;
184 typedef Sacado::Fad::SFad<double,2> Fad2; //# ind. vars fixed at 2
185 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
186 typedef Intrepid::RealSpaceTools<double> IntrepidRSTools;
187 typedef Intrepid::CellTools<double> IntrepidCTools;
188
189 typedef Tpetra::Operator<scalar_type,local_ordinal_type,global_ordinal_type,NO> operator_type;
190 typedef Tpetra::CrsGraph<local_ordinal_type,global_ordinal_type,NO> crs_graph_type;
191 typedef Tpetra::CrsMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO> crs_matrix_type;
192 typedef Tpetra::Vector<scalar_type,local_ordinal_type,global_ordinal_type,NO> vector_type;
193 typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO> multivector_type;
194 typedef Tpetra::Map<local_ordinal_type,global_ordinal_type,NO> driver_map_type;
195 Tpetra::global_size_t INVALID_GO = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid();
196 Tpetra::global_size_t INVALID_LO = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid();
197
198
199 typedef Xpetra::Matrix<scalar_type,local_ordinal_type,global_ordinal_type,NO> xpetra_crs_matrix_type;
200 typedef Xpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO> xpetra_multivector_type;
201
202 typedef Belos::LinearProblem<scalar_type, multivector_type, operator_type> linear_problem_type;
203
204 typedef MueLu::TpetraOperator<scalar_type,local_ordinal_type,global_ordinal_type,NO> muelu_tpetra_operator;
205
206 //typedef Tpetra::MatrixMarket::Writer<crs_matrix_type> writer_type;
207
208 #define TC_sumAll(rcpComm, in, out) \
209 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_SUM, in, Teuchos::outArg(out))
210 #define TC_minAll(rcpComm, in, out) \
211 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MIN, in, Teuchos::outArg(out))
212 #define TC_maxAll(rcpComm, in, out) \
213 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MAX, in, Teuchos::outArg(out))
214
215
216 double myDistance2(const multivector_type &v, int i0, int i1) {
217 const size_t numVectors = v.getNumVectors();
218 double distance = 0.0;
219 for (size_t j=0; j<numVectors; j++) {
220 distance += (v.getData(j)[i0]-v.getData(j)[i1])*(v.getData(j)[i0]-v.getData(j)[i1]);
221 }
222 return distance;
223 }
224
225 // forward declarations
226 void PromoteMesh_Pn_Kirby(const int degree, const EPointType & pointType, const FieldContainer<int> & P1_elemToNode, const FieldContainer<double> & P1_nodeCoord, const FieldContainer<double> & P1_edgeCoord, const FieldContainer<int> & P1_elemToEdge, const FieldContainer<int> & P1_elemToEdgeOrient, const FieldContainer<int> & P1_nodeOnBoundary,
227 FieldContainer<int> & Pn_elemToNode, FieldContainer<double> & Pn_nodeCoord,FieldContainer<int> & Pn_nodeOnBoundary, std::vector<int> &Pn_edgeNodes, std::vector<int> &Pn_cellNodes);
228
229 void GenerateEdgeEnumeration(const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, FieldContainer<int> & elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<int> & edgeToNode, FieldContainer<double> & edgeCoord);
230
231 void CreateP1MeshFromPnMesh(const int degree, const FieldContainer<int> & P2_elemToNode, FieldContainer<int> &aux_P1_elemToNode);
232
233 void CreateLinearSystem(int numWorkSets,
234 int desiredWorksetSize,
235 FieldContainer<int> const &elemToNode,
236 FieldContainer<double> const &nodeCoord,
237 FieldContainer<double> const &cubPoints,
238 FieldContainer<double> const &cubWeights,
239 RCP<Basis<double,FieldContainer<double> > > &myBasis_rcp,
240 FieldContainer<double> const &HGBGrads,
241 FieldContainer<double> const &HGBValues,
242 std::vector<global_ordinal_type> const &globalNodeIds,
243 crs_matrix_type &StiffMatrix,
244 RCP<multivector_type> &rhsVector,
245 std::string &msg
246 );
247
248
249 void GenerateIdentityCoarsening_pn_to_p1(const FieldContainer<int> & P2_elemToNode,
250 //const FieldContainer<int> & P1_elemToNode,
251 RCP<const driver_map_type> const & P1_map_aux, RCP<const driver_map_type> const &P2_map,
252 RCP<crs_matrix_type> & Interpolation,
253 RCP<crs_matrix_type> & Restriction);
254
255 //GenerateIdentityCoarsening_pn_to_p1(elemToNode, StiffMatrix_aux.getDomainMap(), StiffMatrix.getRangeMap(), P_identity, R_identity);
256
257 void Apply_Dirichlet_BCs(std::vector<int> &BCNodes, crs_matrix_type & A, multivector_type & x, multivector_type & b,
258 const multivector_type & soln);
259
260 /**********************************************************************************/
261 /***************** FUNCTION DECLARATION FOR ML PRECONDITIONER *********************/
262 /**********************************************************************************/
263
264 /** \brief ML Preconditioner
265
266 \param ProblemType [in] problem type
267 \param MLList [in] ML parameter list
268 \param A [in] discrete operator matrix
269 \param nCoord [in] Nodal Coordinates
270 \param xexact [in] exact solution
271 \param b [in] right-hand-side vector
272 \param maxits [in] max iterations
273 \param tol [in] solver tolerance
274 \param uh [in/out] solution vector
275 \param TotalErrorResidual [out] error residual
276 \param TotalErrorExactSol [out] error in uh
277
278 */
279 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
280 ParameterList & AMGList,
281 RCP<crs_matrix_type> const & A,
282 RCP<multivector_type> & nCoord,
283 RCP<multivector_type> const & xexact,
284 RCP<multivector_type> & b,
285 int maxits,
286 double tol,
287 RCP<multivector_type> & uh,
288 double & TotalErrorResidual,
289 double & TotalErrorExactSol,
290 std::string &amgType,
291 std::string &solveType);
292
293
294
295 /**********************************************************************************/
296 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
297 /**********************************************************************************/
298
299 /** \brief User-defined exact solution.
300
301 \param x [in] x-coordinate of the evaluation point
302 \param y [in] y-coordinate of the evaluation point
303
304 \return Value of the exact solution at (x,y)
305 */
306 template<typename Scalar>
307 const Scalar exactSolution(const Scalar& x, const Scalar& y);
308
309 /** \brief User-defined material tensor.
310
311 \param material [out] 3 x 3 material tensor evaluated at (x,y)
312 \param x [in] x-coordinate of the evaluation point
313 \param y [in] y-coordinate of the evaluation point
314
315 \warning Symmetric and positive definite tensor is required for every (x,y).
316 */
317 template<typename Scalar>
318 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y);
319
320 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
321
322 \param gradExact [out] gradient of the exact solution evaluated at (x,y)
323 \param x [in] x-coordinate of the evaluation point
324 \param y [in] y-coordinate of the evaluation point
325 */
326 template<typename Scalar>
327 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y);
328
329
330 /** \brief Computes source term: f = -div(A.grad u). Requires user-defined exact solution
331 and material tensor.
332
333 \param x [in] x-coordinate of the evaluation point
334 \param y [in] y-coordinate of the evaluation point
335
336 \return Source term corresponding to the user-defined exact solution evaluated at (x,y)
337 */
338 template<typename Scalar>
339 const Scalar sourceTerm(Scalar& x, Scalar& y);
340
341
342 /** \brief Computation of the material tensor at array of points in physical space.
343
344 \param worksetMaterialValues [out] Rank-2, 3 or 4 array with dimensions (C,P), (C,P,D) or (C,P,D,D)
345 with the values of the material tensor
346 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
347 */
348 template<class ArrayOut, class ArrayIn>
349 void evaluateMaterialTensor(ArrayOut & worksetMaterialValues,
350 const ArrayIn & evaluationPoints);
351
352
353 /** \brief Computation of the source term at array of points in physical space.
354
355 \param sourceTermValues [out] Rank-2 (C,P) array with the values of the source term
356 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
357 */
358 template<class ArrayOut, class ArrayIn>
359 void evaluateSourceTerm(ArrayOut & sourceTermValues,
360 const ArrayIn & evaluationPoints);
361
362 /** \brief Computation of the exact solution at array of points in physical space.
363
364 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
365 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
366 */
367 template<class ArrayOut, class ArrayIn>
368 void evaluateExactSolution(ArrayOut & exactSolutionValues,
369 const ArrayIn & evaluationPoints);
370
371
372 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
373
374 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
375 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
376 */
377 template<class ArrayOut, class ArrayIn>
378 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
379 const ArrayIn & evaluationPoints);
380
381
382
383 // Copy field containers
384 template<class FC1, class FC2>
385 void CopyFieldContainer2D(const FC1 & c1, FC2 & c2) {
386 Kokkos::resize(c2,c1.dimension(0),c1.dimension(1));
387 auto c2_h = Kokkos::create_mirror_view(c2);
388 for(size_t i=0; i<(size_t)c1.dimension(0); i++)
389 for(size_t j=0; j<(size_t)c1.dimension(1); j++)
390 c2_h(i,j) = c1(i,j);
391 Kokkos::deep_copy(c2, c2_h);
392 }
393
394
395
396 /**********************************************************************************/
397 /******************************** MAIN ********************************************/
398 /**********************************************************************************/
399
400 int main(int argc, char *argv[]) {
401
402 int error = 0;
403 int numProcs=1;
404 int rank=0;
405
406 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
407 RCP<const Teuchos::Comm<int> > Comm = Teuchos::DefaultComm<int>::getComm();
408 int MyPID = Comm->getRank();
409
410 Teuchos::CommandLineProcessor clp(false);
411 Teuchos::ParameterList problemStatistics;
412
413 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Pamgen Setup")));
414
415 std::string optMeshFile = "Poisson2D.xml";
416 clp.setOption("mesh", &optMeshFile, "xml file with description of Pamgen mesh");
417 std::string optSolverFile = "";
418 clp.setOption("solver", &optSolverFile, "xml file containing linear solver options");
419 bool optPrintTimings = false;
420 clp.setOption("timings", "notimings", &optPrintTimings, "print timer summary");
421
422 // If matrixFilename is nonempty, dump the matrix to that file
423 // in MatrixMarket format.
424 std::string matrixFilename;
425 clp.setOption ("matrixFilename", &matrixFilename, "If nonempty, dump the "
426 "generated matrix to that file in MatrixMarket format.");
427
428 // If coordsFilename is nonempty, dump the rhs to that file
429 // in MatrixMarket format.
430 std::string rhsFilename;
431 clp.setOption ("rhsFilename", &rhsFilename, "If nonempty, dump the "
432 "generated rhs to that file in MatrixMarket format.");
433
434 // If coordsFilename is nonempty, dump the coords to that file
435 // in MatrixMarket format.
436 std::string coordsFilename;
437 clp.setOption ("coordsFilename", &coordsFilename, "If nonempty, dump the "
438 "generated coordinates to that file in MatrixMarket format.");
439
440 // Random number seed
441 int randomSeed=24601;
442 clp.setOption ("seed", &randomSeed, "Random Seed.");
443
444
445 // Material diffusion strength and rotation (in 3D)
446 // We'll get the 2D version of this later
447 std::vector<double> diff_rotation_angle {0.0, 0.0, 0.0};
448 std::vector<double> diff_strength {1.0, 1.0, 1.0};
449 for(int i=0; i<3; i++) {
450 char letter[4] = "xyz";
451 char str1[80], str2[80];
452 // Rotation
453 sprintf(str1,"rot_%c_angle",letter[i]);
454 sprintf(str2,"Rotation around %c axis, in degrees",letter[i]);
455 clp.setOption(str1,&diff_rotation_angle[i],str2);
456
457 // Strength
458 sprintf(str1,"strength_%c",letter[i]);
459 sprintf(str2,"Strength of pre-rotation %c-diffusion",letter[i]);
460 clp.setOption(str1,&diff_strength[i],str2);
461 }
462
463
464 switch (clp.parse(argc, argv)) {
465 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
466 case Teuchos::CommandLineProcessor::PARSE_ERROR:
467 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
468 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
469 }
470
471 // Initialize RNG
472 srand(randomSeed);
473
474 if (MyPID == 0){
475 std::cout \
476 << "===============================================================================\n" \
477 << "| |\n" \
478 << "| Example: Solve Poisson Equation on Hexahedral Mesh |\n" \
479 << "| |\n" \
480 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
481 << "| Denis Ridzal ([email protected]), |\n" \
482 << "| Kara Peterson ([email protected]). |\n" \
483 << "| |\n" \
484 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
485 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
486 << "| ML's website: http://trilinos.sandia.gov/packages/ml |\n" \
487 << "| Isorropia's website: http://trilinos.sandia.gov/packages/isorropia |\n" \
488 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
489 << "| |\n" \
490 << "===============================================================================\n";
491 }
492
493
494 // Diffusion Tensor
495 ::TrilinosCouplings::IntrepidPoissonExample::setDiffusionRotationAndStrength(diff_rotation_angle, diff_strength);
496 if(MyPID == 0) {
497 const std::vector<double> & A = ::TrilinosCouplings::IntrepidPoissonExample::getDiffusionMatrix2D();
498 std::cout<<"[ "<<A[0]<<" "<<A[1]<<" ]\n"
499 <<"[ "<<A[2]<<" "<<A[3]<<" ]"<<std::endl;
500 }
501
502
503 #ifdef HAVE_MPI
504 if (MyPID == 0) {
505 std::cout << "PARALLEL executable \n";
506 }
507 #else
508 if (MyPID == 0) {
509 std::cout << "SERIAL executable \n";
510 }
511 #endif
512
513 /**********************************************************************************/
514 /********************************** GET XML INPUTS ********************************/
515 /**********************************************************************************/
516
517 // Command line for xml file, otherwise use default
518 std::string xmlMeshInFileName(optMeshFile), xmlSolverInFileName(optSolverFile);
519
520 // Read xml file into parameter list
521 ParameterList inputMeshList;
522 ParameterList inputSolverList;
523
524 if(xmlMeshInFileName.length()) {
525 if (MyPID == 0) {
526 std::cout << "\nReading parameter list from the XML file \""<<xmlMeshInFileName<<"\" ...\n\n";
527 }
528 Teuchos::updateParametersFromXmlFile (xmlMeshInFileName, Teuchos::ptr (&inputMeshList));
529 if (MyPID == 0) {
530 inputMeshList.print(std::cout,2,true,true);
531 std::cout << "\n";
532 }
533 }
534 else
535 {
536 std::cout << "Cannot read input file: " << xmlMeshInFileName << "\n";
537 return 0;
538 }
539
540 if(xmlSolverInFileName.length()) {
541 if (MyPID == 0)
542 std::cout << "\nReading parameter list from the XML file \""<<xmlSolverInFileName<<"\" ...\n\n";
543 Teuchos::updateParametersFromXmlFile(xmlSolverInFileName, Teuchos::inoutArg(inputSolverList));
544 } else if (MyPID == 0) std::cout << "Using default solver values ..." << std::endl;
545
546 // Get pamgen mesh definition
547 std::string meshInput = Teuchos::getParameter<std::string>(inputMeshList,"meshInput");
548 int degree = inputMeshList.get("degree",2);
549
550 // Get Isorropia and Zoltan parameters.
551 ParameterList iso_paramlist = inputMeshList.sublist
552 ("Isorropia Input") ;
553 if (MyPID == 0) {
554 std::cout << "Isorropia/Zoltan parameters" << std::endl;
555 iso_paramlist.print(std::cout,2,true,true);
556 }
557
558
559 /**********************************************************************************/
560 /***************************** GET CELL TOPOLOGY **********************************/
561 /**********************************************************************************/
562
563 // Get cell topology for base hexahedron
564 shards::CellTopology P1_cellType(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
565 shards::CellTopology Pn_cellType(shards::getCellTopologyData<shards::Quadrilateral<> >() );
566 assert(P1_cellType.getDimension() == Pn_cellType.getDimension());
567
568 // Get dimensions
569 int P1_numNodesPerElem = P1_cellType.getNodeCount();
570 int P1_numEdgesPerElem = P1_cellType.getEdgeCount();
571 int P1_numNodesPerEdge = 2; // for any rational universe
572 int spaceDim = P1_cellType.getDimension();
573 int dim = 2;
574
575
576 // Build reference element edge to node map
577 FieldContainer<int> refEdgeToNode(P1_numEdgesPerElem, P1_numNodesPerEdge);
578 for (int i=0; i<P1_numEdgesPerElem; i++){
579 refEdgeToNode(i,0)=P1_cellType.getNodeMap(1, i, 0);
580 refEdgeToNode(i,1)=P1_cellType.getNodeMap(1, i, 1);
581 }
582
583 /**********************************************************************************/
584 /******************************* GENERATE MESH ************************************/
585 /**********************************************************************************/
586
587 if (MyPID == 0) {
588 std::cout << "Generating mesh ... \n\n";
589 }
590
591 long long * node_comm_proc_ids = NULL;
592 long long * node_cmap_node_cnts = NULL;
593 long long * node_cmap_ids = NULL;
594 long long ** comm_node_ids = NULL;
595 long long ** comm_node_proc_ids = NULL;
596
597 // Generate mesh with Pamgen
598 long long maxInt = 9223372036854775807LL;
599 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
600 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
601
602 string msg("Poisson: ");
603 tm.reset();
604 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Mesh queries")));
605
606 // Get mesh size info
607 char title[100];
608 long long numDim;
609 long long numNodes;
610 long long numElems;
611 long long numElemBlk;
612 long long numNodeSets;
613 long long numSideSets;
614 int id = 0;
615
616 im_ex_get_init_l(id, title, &numDim, &numNodes,
617 &numElems, &numElemBlk, &numNodeSets,
618 &numSideSets);
619
620 long long numNodesGlobal;
621 long long numElemsGlobal;
622 long long numElemBlkGlobal;
623 long long numNodeSetsGlobal;
624 long long numSideSetsGlobal;
625
626 im_ne_get_init_global_l(id, &numNodesGlobal, &numElemsGlobal,
627 &numElemBlkGlobal, &numNodeSetsGlobal,
628 &numSideSetsGlobal);
629
630 // Print mesh information
631 if (MyPID == 0){
632 std::cout << " Number of Global Elements: " << numElemsGlobal << " \n";
633 std::cout << " Number of Global Nodes: " << numNodesGlobal << " \n\n";
634 }
635
636 long long * block_ids = new long long [numElemBlk];
637 error += im_ex_get_elem_blk_ids_l(id, block_ids);
638
639
640 long long *nodes_per_element = new long long [numElemBlk];
641 long long *element_attributes = new long long [numElemBlk];
642 long long *elements = new long long [numElemBlk];
643 char **element_types = new char * [numElemBlk];
644 long long **elmt_node_linkage = new long long * [numElemBlk];
645
646
647 for(long long i = 0; i < numElemBlk; i ++){
648 element_types[i] = new char [MAX_STR_LENGTH + 1];
649 error += im_ex_get_elem_block_l(id,
650 block_ids[i],
651 element_types[i],
652 (long long*)&(elements[i]),
653 (long long*)&(nodes_per_element[i]),
654 (long long*)&(element_attributes[i]));
655 }
656
657 /*connectivity*/
658 for(long long b = 0; b < numElemBlk; b++){
659 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
660 error += im_ex_get_elem_conn_l(id,block_ids[b],elmt_node_linkage[b]);
661 }
662
663 // Get node-element connectivity
664 int telct = 0;
665 FieldContainer<int> P1_elemToNode(numElems,P1_numNodesPerElem);
666 for(long long b = 0; b < numElemBlk; b++){
667 for(long long el = 0; el < elements[b]; el++){
668 for (int j=0; j<P1_numNodesPerElem; j++) {
669 P1_elemToNode(telct,j) = elmt_node_linkage[b][el*P1_numNodesPerElem + j]-1;
670 }
671 telct ++;
672 }
673 }
674
675 // Read node coordinates and place in field container
676 FieldContainer<double> P1_nodeCoord(numNodes,dim);
677 double * nodeCoordx = new double [numNodes];
678 double * nodeCoordy = new double [numNodes];
679 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,0);
680 for (int i=0; i<numNodes; i++) {
681 P1_nodeCoord(i,0)=nodeCoordx[i];
682 P1_nodeCoord(i,1)=nodeCoordy[i];
683 }
684 /*parallel info*/
685 long long num_internal_nodes;
686 long long num_border_nodes;
687 long long num_external_nodes;
688 long long num_internal_elems;
689 long long num_border_elems;
690 long long num_node_comm_maps;
691 long long num_elem_comm_maps;
692 im_ne_get_loadbal_param_l( id,
693 &num_internal_nodes,
694 &num_border_nodes,
695 &num_external_nodes,
696 &num_internal_elems,
697 &num_border_elems,
698 &num_node_comm_maps,
699 &num_elem_comm_maps,
700 0/*unused*/ );
701
702 if(num_node_comm_maps > 0){
703 node_comm_proc_ids = new long long [num_node_comm_maps];
704 node_cmap_node_cnts = new long long [num_node_comm_maps];
705 node_cmap_ids = new long long [num_node_comm_maps];
706 comm_node_ids = new long long* [num_node_comm_maps];
707 comm_node_proc_ids = new long long* [num_node_comm_maps];
708
709 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
710 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
711
712
713 if ( im_ne_get_cmap_params_l( id,
714 node_cmap_ids,
715 (long long*)node_cmap_node_cnts,
716 elem_cmap_ids,
717 (long long*)elem_cmap_elem_cnts,
718 0/*not used proc_id*/ ) < 0 )++error;
719
720 for(long long j = 0; j < num_node_comm_maps; j++) {
721 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
722 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
723 if ( im_ne_get_node_cmap_l( id,
724 node_cmap_ids[j],
725 comm_node_ids[j],
726 comm_node_proc_ids[j],
727 0/*not used proc_id*/ ) < 0 )++error;
728 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
729 }
730
731 delete [] elem_cmap_ids;
732 delete [] elem_cmap_elem_cnts;
733 }
734
735 tm.reset();
736 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global Node Nums")));
737
738 //Calculate global node ids
739 long long * P1_globalNodeIds = new long long[numNodes];
740 bool * P1_nodeIsOwned = new bool[numNodes];
741
742 calc_global_node_ids(P1_globalNodeIds,
743 P1_nodeIsOwned,
744 numNodes,
745 num_node_comm_maps,
746 node_cmap_node_cnts,
747 node_comm_proc_ids,
748 comm_node_ids,
749 rank);
750
751 tm.reset();
752 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Boundary Conds")));
753
754 // Container indicating whether a node is on the boundary (1-yes 0-no)
755 FieldContainer<int> P1_nodeOnBoundary(numNodes);
756
757 // Get boundary (side set) information
758 long long * sideSetIds = new long long [numSideSets];
759 long long numSidesInSet;
760 long long numDFinSet;
761 im_ex_get_side_set_ids_l(id,sideSetIds);
762 for (int i=0; i<numSideSets; i++) {
763 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
764 if (numSidesInSet > 0){
765 long long * sideSetElemList = new long long [numSidesInSet];
766 long long * sideSetSideList = new long long [numSidesInSet];
767 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
768 for (int j=0; j<numSidesInSet; j++) {
769
770 int sideNode0 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,0);
771 int sideNode1 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,1);
772
773 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode0))=1;
774 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode1))=1;
775 }
776 delete [] sideSetElemList;
777 delete [] sideSetSideList;
778 }
779 }
780 delete [] sideSetIds;
781
782
783 // Enumerate edges
784 // NOTE: Only correct in serial
785 FieldContainer<int> P1_elemToEdge(numElems,4);// Because quads
786 FieldContainer<int> P1_elemToEdgeOrient(numElems,4);
787 FieldContainer<double> P1_edgeCoord(1,dim);//will be resized
788 FieldContainer<int> P1_edgeToNode(1,2);//will be resized
789 GenerateEdgeEnumeration(P1_elemToNode, P1_nodeCoord, P1_elemToEdge,P1_elemToEdgeOrient,P1_edgeToNode,P1_edgeCoord);
790
791
792 tm.reset();
793 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Mesh Statistics")));
794
795 /**********************************************************************************/
796 /****************************** STATISTICS (Part I) *******************************/
797 /**********************************************************************************/
798 // Statistics: Compute max / min of sigma parameter, mesh information
799 // Put the current statistics into their own functions so this looks less awful
800 double edge_length_max = 0;
801 double edge_length_min = 0;
802 double diag_length_max = 0;
803 double diag_length_min = 0;
804 double maxmin_ratio = 0;
805 double diag_ratio = 0;
806 double stretch = 0;
807 double taper = 0;
808 double skew = 0;
809
810 double dist1 = 0.0;
811 double dist2 = 0.0;
812 double dist3 = 0.0;
813 double dist4 = 0.0;
814
815 int edge = P1_elemToEdge(0, 0);
816 int node1 = P1_edgeToNode(edge, 0);
817 int node2 = P1_edgeToNode(edge, 1);
818 double dist = 0;
819 static const int NUM_NODE_PAIRS = 2;
820 int diag_nodes1[] = {0, 1};
821 int diag_nodes2[] = {2, 3};
822
823 double x0 = 0.0;
824 double x1 = 0.0;
825 double x2 = 0.0;
826 double x3 = 0.0;
827 double y0 = 0.0;
828 double y1 = 0.0;
829 double y2 = 0.0;
830 double y3 = 0.0;
831 double e3 = 0.0;
832 double f3 = 0.0;
833
834 // Intialize
835 for(int i=0; i<NUM_STATISTICS; i++) {
836 local_stat_max[i] = 0.0;
837 local_stat_min[i] = std::numeric_limits<double>::max();
838 local_stat_sum[i] = 0.0;
839 }
840
841 for(int i=0; i<numElems; i++) {
842 // 0 - Material property
843 local_stat_max[0] = 1.0;
844 local_stat_min[0] = 1.0;
845 local_stat_sum[0] += 1.0;
846
847 edge = P1_elemToEdge(i, 0);
848 node1 = P1_edgeToNode(edge, 0);
849 node2 = P1_edgeToNode(edge, 1);
850
851 // 1 - Max/min edge - ratio of max to min edge length
852 edge_length_max = distance2(P1_nodeCoord, node1, node2);
853 edge_length_min = edge_length_max;
854 for (int j=0; j<P1_numEdgesPerElem; j++) {
855 edge = P1_elemToEdge(i,j);
856 node1 = P1_edgeToNode(edge,0);
857 node2 = P1_edgeToNode(edge,1);
858 dist = distance2(P1_nodeCoord,node1,node2);
859 edge_length_max = std::max(edge_length_max,dist);
860 edge_length_min = std::min(edge_length_min,dist);
861 }
862 maxmin_ratio = edge_length_max / edge_length_min;
863 local_stat_max[1] = std::max(local_stat_max[1],maxmin_ratio);
864 local_stat_min[1] = std::min(local_stat_min[1],maxmin_ratio);
865 local_stat_sum[1] += maxmin_ratio;
866
867 // 2 - det of cell Jacobian (later)
868
869 // 3 - Stretch
870 diag_length_max = distance2(P1_nodeCoord, P1_elemToNode(i, diag_nodes1[0]),
871 P1_elemToNode(i, diag_nodes2[0]));
872 diag_length_min = distance2(P1_nodeCoord, P1_elemToNode(i, diag_nodes1[0]),
873 P1_elemToNode(i, diag_nodes2[0]));
874 for (int j=0; j<NUM_NODE_PAIRS; j++) {
875 node1 = P1_elemToNode(i, diag_nodes1[j]);
876 node2 = P1_elemToNode(i, diag_nodes2[j]);
877 dist = distance2(P1_nodeCoord, node1, node2);
878 diag_length_max = std::max(diag_length_max, dist);
879 diag_length_min = std::min(diag_length_min, dist);
880 }
881 stretch = sqrt(3) * edge_length_min / diag_length_max;
882 diag_ratio = diag_length_min / diag_length_max;
883 local_stat_max[3] = std::max(local_stat_max[3], stretch);
884 local_stat_min[3] = std::min(local_stat_min[3], stretch);
885 local_stat_sum[3] += stretch;
886
887 // 4 - Diagonal Ratio
888 local_stat_max[4] = std::max(local_stat_max[4], diag_ratio);
889 local_stat_min[4] = std::min(local_stat_min[4], diag_ratio);
890 local_stat_sum[4] += diag_ratio;
891
892 // 5 - Inverse Taper
893 int opposite_edges1[2][2] = {{0, 1}, {0, 3}};
894 int opposite_edges2[2][2] = {{2, 3}, {1, 2}};
895 dist1 = distance2(P1_nodeCoord, P1_elemToNode(i, opposite_edges1[0][0]), P1_elemToNode(i, opposite_edges1[0][1]));
896 dist2 = distance2(P1_nodeCoord, P1_elemToNode(i, opposite_edges2[0][0]), P1_elemToNode(i, opposite_edges2[0][1]));
897 dist3 = distance2(P1_nodeCoord, P1_elemToNode(i, opposite_edges1[1][0]), P1_elemToNode(i, opposite_edges1[1][1]));
898 dist4 = distance2(P1_nodeCoord, P1_elemToNode(i, opposite_edges2[1][0]), P1_elemToNode(i, opposite_edges2[1][1]));
899 taper = std::max(dist1/dist2, dist2/dist1);
900 taper = std::max(taper, dist3/dist4);
901 taper = std::max(taper, dist4/dist3);
902 local_stat_max[5] = std::max(local_stat_max[5], taper);
903 local_stat_min[5] = std::min(local_stat_min[5], taper);
904 local_stat_sum[5] += taper;
905
906
907 // 6 - Skew
908 // See "Quadrilateral and hexagonal shape parameters" - Robinson, J. 1994
909 x0 = P1_nodeCoord(P1_elemToNode(i, 0), 0);
910 x1 = P1_nodeCoord(P1_elemToNode(i, 1), 0);
911 x2 = P1_nodeCoord(P1_elemToNode(i, 2), 0);
912 x3 = P1_nodeCoord(P1_elemToNode(i, 3), 0);
913
914 y0 = P1_nodeCoord(P1_elemToNode(i, 0), 1);
915 y1 = P1_nodeCoord(P1_elemToNode(i, 1), 1);
916 y2 = P1_nodeCoord(P1_elemToNode(i, 2), 1);
917 y3 = P1_nodeCoord(P1_elemToNode(i, 3), 1);
918
919 e3 = 0.25 * (x0-x1+x2-x3);
920 f3 = 0.25 * (-y0-y1+y2+y3);
921 skew = e3 / f3;
922 local_stat_max[6] = std::max(local_stat_max[4], skew);
923 local_stat_min[6] = std::min(local_stat_max[4], skew);
924 local_stat_sum[6] += skew;
925
926
927 }
928
929
930 /**********************************************************************************/
931 tm.reset();
932 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting cubature")));
933
934
935
936
937 // Generate higher order mesh
938 // NOTE: Only correct in serial
939 int Pn_numNodes = numNodes + (degree-1)*P1_edgeCoord.dimension(0) + (degree-1)*(degree-1)*numElems;
940 int Pn_numNodesperElem = (degree+1)*(degree+1); // Quads
941 FieldContainer<int> elemToNode(numElems,Pn_numNodesperElem);
942 FieldContainer<double> nodeCoord(Pn_numNodes,dim);
943 FieldContainer<int> nodeOnBoundary(Pn_numNodes);
944 std::vector<int> Pn_edgeNodes;
945 std::vector<int> Pn_cellNodes;
946
947
948 PromoteMesh_Pn_Kirby(degree,POINTTYPE_EQUISPACED,P1_elemToNode,P1_nodeCoord,P1_edgeCoord,P1_elemToEdge,P1_elemToEdgeOrient,
949 P1_nodeOnBoundary, elemToNode, nodeCoord, nodeOnBoundary, Pn_edgeNodes, Pn_cellNodes);
950
951
952 long long numElems_aux = numElems*degree*degree; //degree^2 P1 elements per Pn element in auxiliary mesh
953 FieldContainer<int> aux_P1_elemToNode(numElems_aux,P1_numNodesPerElem); //4 P1 elements per Pn element
954 CreateP1MeshFromPnMesh(degree, elemToNode, aux_P1_elemToNode);
955
956 // Only works in serial
957 std::vector<bool>Pn_nodeIsOwned(Pn_numNodes,true);
958 std::vector<global_ordinal_type>Pn_globalNodeIds(Pn_numNodes);
959 for(int i=0; i<Pn_numNodes; i++)
960 Pn_globalNodeIds[i]=static_cast<global_ordinal_type>(i);
961
962 std::vector<double> Pn_nodeCoordx(Pn_numNodes);
963 std::vector<double> Pn_nodeCoordy(Pn_numNodes);
964 for (int i=0; i<Pn_numNodes; i++) {
965 Pn_nodeCoordx[i] = nodeCoord(i,0);
966 Pn_nodeCoordy[i] = nodeCoord(i,1);
967 }
968
969 // Reset constants
970 int P1_numNodes =numNodes;
971 numNodes = Pn_numNodes;
972 numNodesGlobal = numNodes;
973
974 // Print mesh information
975 if (MyPID == 0){
976 std::cout << " Number of Pn Global Elements: " << numElemsGlobal << " \n";
977 std::cout << " Number of Pn Global Nodes: " << numNodesGlobal << " \n";
978 std::cout << " Number of faux P1 Global Elements: " << aux_P1_elemToNode.dimension(0) << " \n\n";
979 }
980
981
982 /**********************************************************************************/
983 /********************************* GET CUBATURE ***********************************/
984 /**********************************************************************************/
985
986 // Get numerical integration points and weights
987 DefaultCubatureFactory<double> cubFactory;
988 int cubDegree = 2*degree;
989 RCP<Cubature<double> > myCub = cubFactory.create(Pn_cellType, cubDegree);
990
991 int cubDim = myCub->getDimension();
992 int numCubPoints = myCub->getNumPoints();
993
994 FieldContainer<double> cubPoints(numCubPoints, cubDim);
995 FieldContainer<double> cubWeights(numCubPoints);
996
997 myCub->getCubature(cubPoints, cubWeights);
998
999 tm.reset();
1000 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting cubature")));
1001
1002 /**********************************************************************************/
1003 /*********************************** GET BASIS ************************************/
1004 /**********************************************************************************/
1005
1006 // Define basis
1007 Basis_HGRAD_QUAD_Cn_FEM<double, FieldContainer<double> > myHGradBasis(degree,POINTTYPE_EQUISPACED);
1008 RCP<Basis<double,FieldContainer<double> > > myHGradBasis_rcp(&myHGradBasis, false);
1009 RCP<Basis_HGRAD_QUAD_Cn_FEM<double,FieldContainer<double> > > myHGradBasisWithDofCoords_rcp(&myHGradBasis, false);
1010
1011 // Auxillary p=1 basis
1012 Basis_HGRAD_QUAD_C1_FEM<double, FieldContainer<double> > myHGradBasis_aux;
1013 RCP<Basis<double,FieldContainer<double> > > myHGradBasis_aux_rcp(&myHGradBasis_aux, false);
1014
1015
1016 int numFieldsG = myHGradBasis.getCardinality();
1017
1018 FieldContainer<double> HGBValues(numFieldsG, numCubPoints);
1019 FieldContainer<double> HGBGrads(numFieldsG, numCubPoints, spaceDim);
1020
1021 // Evaluate basis values and gradients at cubature points
1022 myHGradBasis.getValues(HGBValues, cubPoints, OPERATOR_VALUE);
1023 myHGradBasis.getValues(HGBGrads, cubPoints, OPERATOR_GRAD);
1024
1025
1026 //#define OUTPUT_REFERENCE_FUNCTIONS
1027 #ifdef OUTPUT_REFERENCE_FUNCTIONS
1028 // Evaluate basis values and gradients at DOF points
1029 FieldContainer<double> DofCoords(numFieldsG,spaceDim);
1030 myHGradBasis.getDofCoords(DofCoords);
1031 FieldContainer<double> HGBValues_at_Dofs(numFieldsG,numFieldsG);
1032 myHGradBasis.getValues(HGBValues_at_Dofs, DofCoords, OPERATOR_VALUE);
1033
1034
1035 printf("*** Dof Coords ***\n");
1036 for(int j=0; j<numFieldsG; j++)
1037 printf("[%d] %10.2e %10.2e\n",j,DofCoords(j,0),DofCoords(j,1));
1038
1039 printf("*** CubPoints & Weights ***\n");
1040 for(int j=0; j<numCubPoints; j++)
1041 printf("[%d] %10.2e %10.2e (%10.2e)\n",j,cubPoints(j,0),cubPoints(j,1),cubWeights(j));
1042
1043 printf("*** HGBValues @ Dofs ***\n");
1044 for(int i=0; i<numFieldsG; i++) {
1045 printf("[%d] ",i);
1046 for(int j=0; j<numFieldsG; j++) {
1047 printf("%10.2e ",zwrap(HGBValues_at_Dofs(i,j)));
1048 }
1049 printf("\n");
1050 }
1051
1052 printf("*** HGBValues ***\n");
1053 for(int i=0; i<numFieldsG; i++) {
1054 printf("[%d] ",i);
1055 for(int j=0; j<numCubPoints; j++) {
1056 printf("%10.2e ",zwrap(HGBValues(i,j)));
1057
1058 }
1059 printf("\n");
1060 }
1061
1062 printf("*** HGBGrad ***\n");
1063 for(int i=0; i<numFieldsG; i++) {
1064 printf("[%d] ",i);
1065 for(int j=0; j<numCubPoints; j++) {
1066 printf("(%10.2e %10.2e)",zwrap(HGBGrads(i,j,0)),zwrap(HGBGrads(i,j,1)));
1067 printf("\n");
1068 }
1069 }
1070
1071 printf("*** Pn_nodeIsOwned ***\n");
1072 for(int i=0; i<Pn_numNodes; i++)
1073 printf("%d ",(int)Pn_nodeIsOwned[i]);
1074 printf("\n");
1075
1076 printf("*** Pn_nodeOnBoundary ***\n");
1077 for(int i=0; i<Pn_numNodes; i++)
1078 printf("%d ",(int)nodeOnBoundary[i]);
1079 printf("\n");
1080
1081 #endif
1082
1083 tm.reset();
1084 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Build global maps")));
1085
1086 /**********************************************************************************/
1087 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
1088 /**********************************************************************************/
1089 // Count owned nodes (Pn)
1090 int Pn_ownedNodes=0;
1091 for(int i=0;i<numNodes;i++)
1092 if(Pn_nodeIsOwned[i]) Pn_ownedNodes++;
1093
1094 // Build a list of the OWNED global ids...
1095 // NTS: will need to switch back to long long
1096 std::vector<global_ordinal_type> Pn_ownedGIDs(Pn_ownedNodes);
1097 int oidx=0;
1098 for(int i=0;i<numNodes;i++)
1099 if(Pn_nodeIsOwned[i]){
1100 Pn_ownedGIDs[oidx]=(global_ordinal_type)Pn_globalNodeIds[i];
1101 oidx++;
1102 }
1103
1104 // Count owned nodes (P1)
1105 int P1_ownedNodes=0;
1106 for(int i=0;i<P1_numNodes;i++)
1107 if(P1_nodeIsOwned[i]) P1_ownedNodes++;
1108 std::vector<global_ordinal_type> P1_ownedGIDs(P1_ownedNodes);
1109 oidx=0;
1110 for(int i=0;i<P1_numNodes;i++)
1111 if(P1_nodeIsOwned[i]){
1112 P1_ownedGIDs[oidx]=(global_ordinal_type)P1_globalNodeIds[i];
1113 oidx++;
1114 }
1115 //TODO JJH 8-June-2016 need to populate edge and elem seed nodes
1116
1117 //seed points for block relaxation
1118 ArrayRCP<int> nodeSeeds(Pn_numNodes,INVALID_LO);
1119 //unknowns at mesh nodes
1120 oidx=0;
1121 for(int i=0;i<P1_numNodes;i++) {
1122 if(P1_nodeIsOwned[i]){
1123 nodeSeeds[(int)P1_globalNodeIds[i]] = oidx;
1124 oidx++;
1125 }
1126 }
1127 int numNodeSeeds = oidx;
1128
1129 //unknowns on edges
1130 ArrayRCP<int> edgeSeeds(Pn_numNodes,INVALID_LO);
1131 for (size_t i=0; i<Pn_edgeNodes.size(); ++i)
1132 edgeSeeds[Pn_edgeNodes[i]] = i;
1133 int numEdgeSeeds = Pn_edgeNodes.size();
1134
1135 //unknowns in cell interiors
1136 ArrayRCP<int> cellSeeds(Pn_numNodes,INVALID_LO);
1137 for (size_t i=0; i<Pn_cellNodes.size(); ++i)
1138 cellSeeds[Pn_cellNodes[i]] = i;
1139 int numCellSeeds = Pn_cellNodes.size();
1140
1141 // Generate map for nodes
1142 RCP<driver_map_type> globalMapG = rcp(new driver_map_type(INVALID_GO,&Pn_ownedGIDs[0],Pn_ownedNodes,0,Comm));
1143
1144 // Generate p1 map
1145 RCP<driver_map_type> P1_globalMap = rcp(new driver_map_type(INVALID_GO,&P1_ownedGIDs[0],P1_ownedNodes,0,Comm));
1146
1147 // Genetrate Pn-to-P1 coarsening.
1148 Kokkos::DynRankView<local_ordinal_type,typename NO::device_type> elemToNodeI2;
1149
1150 CopyFieldContainer2D(elemToNode,elemToNodeI2);
1151
1152 if (inputSolverList.isParameter("aux P1") && inputSolverList.isParameter("linear P1"))
1153 throw std::runtime_error("Can only specify \"aux P1\" or \"linear P1\", not both.");
1154 if (inputSolverList.isParameter("linear P1")) {
1155 printf("Activating Linear scheduled p-coarsening...\n");
1156 Teuchos::ParameterList & mymuelu = inputSolverList.sublist("MueLu");
1157 Teuchos::ParameterList & level0 = mymuelu.sublist("level 0");
1158 level0.set("pcoarsen: element to node map",rcp(&elemToNodeI2,false));
1159 inputSolverList.remove("linear P1"); //even though LevelWrap happily accepts this parameter
1160 }
1161
1162
1163
1164 // Global arrays in Tpetra format
1165 crs_matrix_type StiffMatrix(globalMapG, 20*numFieldsG);
1166 RCP<multivector_type> rhsVector = rcp(new multivector_type(globalMapG,1));
1167 RCP<multivector_type> femCoefficients = rcp(new multivector_type(globalMapG,1));
1168
1169 tm = Teuchos::null;
1170
1171 /**********************************************************************************/
1172 /**** COOORDINATES FOR DISTANCE LAPLACIAN ***/
1173 /**********************************************************************************/
1174
1175 // Put coordinates in multivector for output
1176 RCP<multivector_type> nCoord = rcp(new multivector_type(globalMapG,dim));
1177
1178 int indOwned = 0;
1179 for (int inode=0; inode<Pn_numNodes; inode++) {
1180 if (Pn_nodeIsOwned[inode]) {
1181 nCoord->getDataNonConst(0)[indOwned]=nodeCoord(inode,0);
1182 nCoord->getDataNonConst(1)[indOwned]=nodeCoord(inode,1);
1183 indOwned++;
1184 }
1185 }
1186
1187 /**********************************************************************************/
1188 /************************** DIRICHLET BC SETUP ************************************/
1189 /**********************************************************************************/
1190 tm.reset();
1191 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Get Dirichlet boundary values")));
1192
1193 int numBCNodes = 0;
1194 for (int inode = 0; inode < numNodes; inode++){
1195 if (nodeOnBoundary(inode) && Pn_nodeIsOwned[inode]){
1196 numBCNodes++;
1197 }
1198 }
1199
1200 // Vector for use in applying BCs
1201 multivector_type v(globalMapG,true);
1202 ArrayRCP<scalar_type> vdata = v.getDataNonConst(0);
1203
1204 // Set v to boundary values on Dirichlet nodes
1205 std::vector<int> BCNodes(numBCNodes);
1206 int indbc=0;
1207 int iOwned=0;
1208 for (int inode=0; inode<numNodes; inode++){
1209 if (Pn_nodeIsOwned[inode]){
1210 if (nodeOnBoundary(inode)){
1211 BCNodes[indbc]=iOwned;
1212 indbc++;
1213 double x = nodeCoord(inode, 0);
1214 double y = nodeCoord(inode, 1);
1215 vdata[iOwned]=exactSolution(x, y);
1216 }
1217 iOwned++;
1218 }
1219 }
1220
1221 tm.reset();
1222 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global assembly")));
1223
1224 /**********************************************************************************/
1225 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
1226 /**********************************************************************************/
1227
1228 // Define desired workset size and count how many worksets there are on this processor's mesh block
1229 int desiredWorksetSize = numElems; // change to desired workset size!
1230 int numWorksets = numElems/desiredWorksetSize;
1231
1232 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1233 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
1234
1235 if (MyPID == 0) {
1236 std::cout << "Building discretization matrix and right hand side... \n\n";
1237 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
1238 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
1239 }
1240
1241 // Create Pn matrix and RHS
1242 CreateLinearSystem(numWorksets,
1243 desiredWorksetSize,
1244 elemToNode,
1245 nodeCoord,
1246 cubPoints,
1247 cubWeights,
1248 myHGradBasis_rcp,
1249 HGBGrads,
1250 HGBValues,
1251 Pn_globalNodeIds,
1252 StiffMatrix,
1253 rhsVector,
1254 msg
1255 );
1256
1257 /**********************************************************************************/
1258 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
1259 /**********************************************************************************/
1260
1261 printf("Example: StiffMatrix (ra,ro,co,do) = (%d,%d,%d,%d)\n",
1262 (int)StiffMatrix.getRangeMap()->getGlobalNumElements(),
1263 (int)StiffMatrix.getRowMap()->getGlobalNumElements(),
1264 (int)StiffMatrix.getColMap()->getGlobalNumElements(),
1265 (int)StiffMatrix.getRangeMap()->getGlobalNumElements());
1266
1267 tm.reset();
1268 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting cubature for auxiliary P1 mesh")));
1269
1270 /////////////////////////////////////////////////////////////////////
1271 // Create P1 matrix and RHS to be used in preconditioner
1272 /////////////////////////////////////////////////////////////////////
1273
1274 //Cubature
1275
1276 // Get numerical integration points and weights
1277 int cubDegree_aux = 2; //TODO This was 3 for P=2. I think this should be 2 now .... Ask Chris.
1278 RCP<Cubature<double> > myCub_aux = cubFactory.create(P1_cellType, cubDegree_aux);
1279
1280 int cubDim_aux = myCub_aux->getDimension();
1281 int numCubPoints_aux = myCub_aux->getNumPoints();
1282
1283 FieldContainer<double> cubPoints_aux(numCubPoints_aux, cubDim_aux);
1284 FieldContainer<double> cubWeights_aux(numCubPoints_aux);
1285 myCub_aux->getCubature(cubPoints_aux, cubWeights_aux);
1286
1287 tm.reset();
1288 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting basis for auxiliary P1 mesh")));
1289
1290 //Basis
1291
1292 // Define basis
1293 int numFieldsG_aux = myHGradBasis_aux.getCardinality();
1294 FieldContainer<double> HGBValues_aux(numFieldsG_aux, numCubPoints_aux);
1295 FieldContainer<double> HGBGrads_aux(numFieldsG_aux, numCubPoints_aux, spaceDim);
1296
1297 // Evaluate basis values and gradients at cubature points
1298 myHGradBasis_aux.getValues(HGBValues_aux, cubPoints_aux, OPERATOR_VALUE);
1299 myHGradBasis_aux.getValues(HGBGrads_aux, cubPoints_aux, OPERATOR_GRAD);
1300
1301 tm.reset();
1302 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global assembly (auxiliary system)")));
1303
1304 crs_matrix_type StiffMatrix_aux(globalMapG, 20*numFieldsG_aux);
1305 RCP<multivector_type> rhsVector_aux = rcp(new multivector_type(globalMapG,1));
1306
1307 desiredWorksetSize = numElems_aux;
1308 numWorksets = numElems_aux/desiredWorksetSize;
1309 if(numWorksets*desiredWorksetSize < numElems_aux) numWorksets += 1;
1310 CreateLinearSystem(numWorksets,
1311 desiredWorksetSize,
1312 aux_P1_elemToNode,
1313 nodeCoord,
1314 cubPoints_aux,
1315 cubWeights_aux,
1316 myHGradBasis_aux_rcp,
1317 HGBGrads_aux,
1318 HGBValues_aux,
1319 Pn_globalNodeIds,
1320 StiffMatrix_aux,
1321 rhsVector_aux,
1322 msg
1323 );
1324
1325
1326 /**********************************************************************************/
1327 /***************************** STATISTICS (Part III) ******************************/
1328 /**********************************************************************************/
1329 std::vector<double> global_stat_max(NUM_STATISTICS),global_stat_min(NUM_STATISTICS), global_stat_sum(NUM_STATISTICS);
1330 Teuchos::reduceAll(*Comm,Teuchos::REDUCE_MIN,NUM_STATISTICS,local_stat_min.data(),global_stat_min.data());
1331 Teuchos::reduceAll(*Comm,Teuchos::REDUCE_MAX,NUM_STATISTICS,local_stat_max.data(),global_stat_max.data());
1332 Teuchos::reduceAll(*Comm,Teuchos::REDUCE_SUM,NUM_STATISTICS,local_stat_sum.data(),global_stat_sum.data());
1333 // NOTE: All output properties should be unitless if we want to compare across problems.
1334 // NOTE: Should the mean be weighted by cell volume? That is not currently done.
1335
1336 // 0 - Material property
1337 problemStatistics.set("sigma: min/mean",global_stat_min[0]/global_stat_sum[0]*numElemsGlobal);
1338 problemStatistics.set("sigma: max/mean",global_stat_max[0]/global_stat_sum[0]*numElemsGlobal);
1339
1340 // 1 - Max/min edge ratio
1341 problemStatistics.set("element edge ratio: min",global_stat_min[1]);
1342 problemStatistics.set("element edge ratio: max",global_stat_max[1]);
1343 problemStatistics.set("element edge ratio: mean",global_stat_sum[1] / numElemsGlobal);
1344
1345 // 2 - det of cell Jacobian (later)
1346 problemStatistics.set("element det jacobian: min/mean",global_stat_min[2]/global_stat_sum[2]*numElemsGlobal);
1347 problemStatistics.set("element det jacobian: max/mean",global_stat_max[2]/global_stat_sum[2]*numElemsGlobal);
1348
1349 if(use_new_problem_stats) {
1350 // 3 - Stretch
1351 problemStatistics.set("Stretch max", global_stat_max[3]);
1352 problemStatistics.set("Stretch min", global_stat_min[3]);
1353 problemStatistics.set("Stretch mean", global_stat_sum[3] / numElemsGlobal);
1354
1355 // 4 - Diagonal Ratio
1356 problemStatistics.set("Diagonal Ratio max", global_stat_max[4]);
1357 problemStatistics.set("Diagonal Ratio min", global_stat_min[4]);
1358 problemStatistics.set("Diagonal Ratio mean", global_stat_sum[4]/numElemsGlobal);
1359
1360 // 5 - Inverse Taper
1361 problemStatistics.set("Inverse Taper max", global_stat_max[5]);
1362 problemStatistics.set("Inverse Taper min", global_stat_min[5]);
1363 problemStatistics.set("Inverse Taper mean", global_stat_sum[5] / numElemsGlobal);
1364
1365 // 6 - Skew
1366 problemStatistics.set("Skew max", global_stat_max[6]);
1367 problemStatistics.set("Skew min", global_stat_min[6]);
1368 problemStatistics.set("Skew mean", global_stat_sum[6] / numElemsGlobal);
1369
1370 // 7 - Lapl Diag
1371 problemStatistics.set("Lapl Diag max", global_stat_max[7]);
1372 problemStatistics.set("Lapl Diag min", global_stat_min[7]);
1373 problemStatistics.set("Lapl Diag mean", global_stat_sum[7] / StiffMatrix.getGlobalNumEntries());
1374 }
1375
1376 // Print Problem Statistics
1377 std::cout<<"*** Problem Statistics ***\n"<<problemStatistics<<std::endl;
1378
1379
1380 /**********************************************************************************/
1381 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
1382 /**********************************************************************************/
1383 tm.reset();
1384 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Adjust global matrix and rhs due to BCs")));
1385
1386 // Generate Pn-to-P1 identity coarsening (base mesh to auxiliary mesh).
1387 RCP<crs_matrix_type> P_identity, R_identity;
1388
1389 if (inputSolverList.isParameter("aux P1")) {
1390 printf("Generating Identity Pn-to-P1 coarsening...\n");
1391 GenerateIdentityCoarsening_pn_to_p1(elemToNode, StiffMatrix_aux.getDomainMap(), StiffMatrix.getRangeMap(), P_identity, R_identity);
1392 inputSolverList.remove("aux P1"); //even though LevelWrap happily accepts this parameter
1393 }
1394
1395 /**********************************************************************************/
1396 /******************************* ADJUST MATRIX DUE TO BC **************************/
1397 /**********************************************************************************/
1398
1399 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1400 // and add one to diagonal.
1401 Apply_Dirichlet_BCs(BCNodes,StiffMatrix,*femCoefficients,*rhsVector,v);
1402
1403 ///////////////////////////////////////////
1404 // Apply BCs to auxiliary P1 matrix
1405 ///////////////////////////////////////////
1406 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1407 // and add one to diagonal.
1408 std::cout << "numBCNodes = " << numBCNodes << std::endl;
1409 std::cout << "globalMapG #elts = " << globalMapG->getLocalNumElements() << std::endl;
1410 Apply_Dirichlet_BCs(BCNodes,StiffMatrix_aux,*rhsVector_aux,*rhsVector_aux,v);
1411
1412 tm = Teuchos::null;
1413
1414 // Optionally dump the matrix and/or its coords to files.
1415 {
1416 typedef Tpetra::MatrixMarket::Writer<crs_matrix_type> writer_type;
1417 if (matrixFilename != "") {
1418 writer_type::writeSparseFile (matrixFilename, StiffMatrix);
1419 }
1420 if (rhsFilename != "") {
1421 writer_type::writeDenseFile (rhsFilename, rhsVector);
1422 }
1423 if (coordsFilename != "") {
1424 writer_type::writeDenseFile (coordsFilename, nCoord);
1425 }
1426 }
1427
1428
1429 /**********************************************************************************/
1430 /*********************************** SOLVE ****************************************/
1431 /**********************************************************************************/
1432 // Which Solver?
1433 std::string solveType("cg");
1434 if(inputSolverList.isParameter("solver")) {
1435 solveType = inputSolverList.get<std::string>("solver");
1436 }
1437
1438
1439 // Run the solver
1440 std::string amgType("MueLu");
1441
1442 ParameterList amgList;
1443 std::string seedType = inputSolverList.get("seed type","node");
1444 inputSolverList.remove("seed type");
1445 if (inputSolverList.isSublist("MueLu"))
1446 amgList = inputSolverList.sublist("MueLu");
1447 else
1448 amgList = inputSolverList;
1449
1450
1451 #ifdef HAVE_TRILINOSCOUPLINGS_AVATAR
1452 // If we have Avatar, then let's use it
1453 if (inputSolverList.isSublist("Avatar-MueLu")) {
1454 // NOTE: User will need to make sure these are named consistently with the tree files specified
1455 ParameterList problemFeatures = problemStatistics;
1456 ParameterList avatarParams = inputSolverList.sublist("Avatar-MueLu");
1457 std::cout<<"*** Avatar Parameters ***\n"<<avatarParams<<std::endl;
1458 Teuchos::RCP<const Teuchos::Comm<int> > mycomm = StiffMatrix.getRowMap()->getComm();
1459
1460 MueLu::AvatarInterface avatar(mycomm,avatarParams);
1461 std::cout<<"*** Avatar Setup ***"<<std::endl;
1462 avatar.Setup();
1463 avatar.SetMueLuParameters(problemFeatures,amgList, true);
1464 std::cout<<"*** Updated MueLu Parameters ***\n"<<amgList<<std::endl;
1465 avatar.Cleanup();
1466 }
1467 #endif
1468
1469 std::string lev0List = "level 0";
1470 if (amgList.isSublist(lev0List)) {
1471 std::cout << "found \"" << lev0List << "\" sublist" << std::endl;
1472 ParameterList &sl = amgList.sublist(lev0List);
1473 std::string smooType = sl.get<std::string>("smoother: type");
1474 if ( (smooType == "SPARSE BLOCK RELAXATION" || smooType == "BLOCK RELAXATION") && sl.isParameter("smoother: params")) {
1475 ParameterList &ssl = sl.sublist("smoother: params");
1476 std::cout << "found \"smoother: params\" for block relaxation" << std::endl;
1477 int numLocalParts = -1;
1478 std::cout << "setting \"partitioner: map\"" << std::endl;
1479 if (seedType == "node") {
1480 ssl.set("partitioner: map", nodeSeeds);
1481 numLocalParts = numNodeSeeds;
1482 } else if (seedType == "edge") {
1483 ssl.set("partitioner: map", edgeSeeds);
1484 numLocalParts = numEdgeSeeds;
1485 } else if (seedType == "cell") {
1486 ssl.set("partitioner: map", cellSeeds);
1487 numLocalParts = numCellSeeds;
1488 }
1489 if(numLocalParts!=-1){
1490 std::cout << "setting \"partitioner: local parts\" = " << numLocalParts << std::endl;
1491 ssl.set("partitioner: local parts", numLocalParts);
1492 }
1493 }
1494 if(sl.isParameter("coarse: type")) {
1495 std::string coarseType = sl.get<std::string>("coarse: type");
1496 if ((coarseType == "SPARSE BLOCK RELAXATION"|| coarseType == "BLOCK RELAXATION") && sl.isParameter("coarse: params")) {
1497 ParameterList &ssl = sl.sublist("coarse: params");
1498 std::cout << "found \"smoother: params\" for block relaxation" << std::endl;
1499 int numLocalParts=-1;
1500 std::cout << "setting \"partitioner: map\"" << std::endl;
1501 if (seedType == "node") {
1502 ssl.set("partitioner: map", nodeSeeds);
1503 numLocalParts = numNodeSeeds;
1504 } else if (seedType == "edge") {
1505 ssl.set("partitioner: map", edgeSeeds);
1506 numLocalParts = numEdgeSeeds;
1507 } else if (seedType == "cell") {
1508 ssl.set("partitioner: map", cellSeeds);
1509 numLocalParts = numCellSeeds;
1510 }
1511 if(numLocalParts!=-1){
1512 std::cout << "setting \"partitioner: local parts\" = " << numLocalParts << std::endl;
1513 ssl.set("partitioner: local parts", numLocalParts);
1514 }
1515 }
1516 }
1517
1518 }
1519
1520 // /////////////////////////////////////////////////////////////////////// //
1521
1522 // Shove coordinates in multivector for saving to file.
1523 multivector_type coordinates(StiffMatrix.getRowMap(),2);
1524 ArrayRCP<scalar_type> xdat = coordinates.getDataNonConst(0);
1525 ArrayRCP<scalar_type> ydat = coordinates.getDataNonConst(1);
1526 for (size_t i=0; i<Pn_nodeCoordx.size(); ++i) {
1527 xdat[i] = Pn_nodeCoordx[i];
1528 ydat[i] = Pn_nodeCoordy[i];
1529 }
1530 xdat = Teuchos::null; ydat = Teuchos::null;
1531 //writer_type::writeDenseFile("coords.m", coordinates);
1532
1533 multivector_type P1coordinates(P1_globalMap,2);
1534 xdat = P1coordinates.getDataNonConst(0);
1535 ydat = P1coordinates.getDataNonConst(1);
1536 for (size_t i=0; i<P1coordinates.getLocalLength(); i++) {
1537 xdat[i] = nodeCoordx[i];
1538 ydat[i] = nodeCoordy[i];
1539 }
1540 xdat = Teuchos::null; ydat = Teuchos::null;
1541 //writer_type::writeDenseFile("P1coords.m", P1coordinates);
1542
1543 multivector_type nBound(globalMapG,true);
1544
1545 RCP<multivector_type> exactNodalVals = rcp(new multivector_type(globalMapG,1));
1546 double TotalErrorResidual = 0.0;
1547 double TotalErrorExactSol = 0.0;
1548
1549 // Get exact solution at nodes
1550 for (int i = 0; i<numNodes; i++) {
1551 if (Pn_nodeIsOwned[i]){
1552 double x = nodeCoord(i,0);
1553 double y = nodeCoord(i,1);
1554 double exactu = exactSolution(x, y);
1555
1556 int rowindex=Pn_globalNodeIds[i];
1557 exactNodalVals->sumIntoGlobalValue(rowindex, 0, exactu);
1558 }
1559 }
1560
1561 char probType[10] = "laplace";
1562
1563 RCP<crs_matrix_type> interpolationMatrix, restrictionMatrix;
1564 if (P_identity != Teuchos::null) {
1565 Teuchos::ParameterList & level1 = amgList.sublist("level 1");
1566 RCP<xpetra_crs_matrix_type> xA1 = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(rcpFromRef(StiffMatrix_aux));
1567 RCP<xpetra_crs_matrix_type> xP = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(P_identity);
1568 level1.set("A",xA1);
1569 level1.set("P",xP);
1570 amgList.set("transpose: use implicit",true);
1571 // create nullspace for Level 1 (first coarse AMG level)
1572 RCP<multivector_type> nullspace = rcp(new multivector_type(exactNodalVals->getMap(),1));
1573 ArrayRCP<scalar_type> data = nullspace->getDataNonConst(0);
1574 for (int i=0; i<data.size(); ++i)
1575 data[i] = 1.0;
1576 RCP<xpetra_multivector_type> xnullspace = MueLu::TpetraMultiVector_To_XpetraMultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO>(nullspace);
1577 level1.set("Nullspace",xnullspace);
1578 }
1579
1580 int maxits = inputSolverList.get("Maximum Iterations",(int)100);
1581 double tol = inputSolverList.get("Convergence Tolerance",(double)1e-10);
1582
1583 if (amgList.isParameter("solve Ae=0")) {
1584 rhsVector->scale(0.0);
1585 femCoefficients->randomize();
1586 }
1587
1588
1589 TestMultiLevelPreconditionerLaplace(probType, amgList,
1590 rcpFromRef(StiffMatrix),
1591 nCoord,
1592 exactNodalVals,
1593 rhsVector,
1594 maxits,
1595 tol,
1596 femCoefficients,
1597 TotalErrorResidual, TotalErrorExactSol,
1598 amgType,
1599 solveType);
1600
1601 /**********************************************************************************/
1602 /**************************** CALCULATE ERROR *************************************/
1603 /**********************************************************************************/
1604
1605 tm.reset();
1606 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Calculate error")));
1607
1608 double L2err = 0.0;
1609 double L2errTot = 0.0;
1610 double H1err = 0.0;
1611 double H1errTot = 0.0;
1612 double Linferr = 0.0;
1613 double LinferrTot = 0.0;
1614
1615 // Import solution onto current processor
1616 //int numNodesGlobal = globalMapG.NumGlobalElements();
1617 RCP<driver_map_type> solnMap = rcp(new driver_map_type(static_cast<Tpetra::global_size_t>(numNodesGlobal), static_cast<size_t>(numNodesGlobal), 0, Comm));
1618 Tpetra::Import<local_ordinal_type, global_ordinal_type, NO> solnImporter(globalMapG,solnMap);
1619 multivector_type uCoeff(solnMap,1);
1620 uCoeff.doImport(*femCoefficients, solnImporter, Tpetra::INSERT);
1621
1622 // Define desired workset size
1623 desiredWorksetSize = numElems;
1624 int numWorksetsErr = numElems/desiredWorksetSize;
1625
1626 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1627 if(numWorksetsErr*desiredWorksetSize < numElems) numWorksetsErr += 1;
1628
1629 // Get cubature points and weights for error calc (may be different from previous)
1630 Intrepid::DefaultCubatureFactory<double> cubFactoryErr;
1631 int cubDegErr = 3*degree;
1632 RCP<Intrepid::Cubature<double> > cellCubatureErr = cubFactoryErr.create(Pn_cellType, cubDegErr);
1633 int cubDimErr = cellCubatureErr->getDimension();
1634 int numCubPointsErr = cellCubatureErr->getNumPoints();
1635 Intrepid::FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
1636 Intrepid::FieldContainer<double> cubWeightsErr(numCubPointsErr);
1637 cellCubatureErr->getCubature(cubPointsErr, cubWeightsErr);
1638
1639 // Evaluate basis values and gradients at cubature points
1640 Intrepid::FieldContainer<double> uhGVals(numFieldsG, numCubPointsErr);
1641 Intrepid::FieldContainer<double> uhGrads(numFieldsG, numCubPointsErr, spaceDim);
1642 myHGradBasis.getValues(uhGVals, cubPointsErr, Intrepid::OPERATOR_VALUE);
1643 myHGradBasis.getValues(uhGrads, cubPointsErr, Intrepid::OPERATOR_GRAD);
1644
1645 // Loop over worksets
1646 for(int workset = 0; workset < numWorksetsErr; workset++){
1647
1648 // compute cell numbers where the workset starts and ends
1649 int worksetSize = 0;
1650 int worksetBegin = (workset + 0)*desiredWorksetSize;
1651 int worksetEnd = (workset + 1)*desiredWorksetSize;
1652
1653 // when numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1654 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1655
1656 // now we know the actual workset size and can allocate the array for the cell nodes
1657 worksetSize = worksetEnd - worksetBegin;
1658 Intrepid::FieldContainer<double> cellWorksetEr(worksetSize, numFieldsG, spaceDim);
1659 Intrepid::FieldContainer<double> worksetApproxSolnCoef(worksetSize, numFieldsG);
1660
1661 // loop over cells to fill arrays with coordinates and discrete solution coefficient
1662 int cellCounter = 0;
1663 ArrayRCP<const scalar_type> uCoeffData = uCoeff.getData(0);
1664 ArrayRCP<const scalar_type> femCoeffData = femCoefficients->getData(0);
1665 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1666
1667 for (int node = 0; node < numFieldsG; node++) {
1668 cellWorksetEr(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
1669 cellWorksetEr(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
1670
1671 int rowIndex = Pn_globalNodeIds[elemToNode(cell, node)];
1672 #ifdef HAVE_MPI
1673 worksetApproxSolnCoef(cellCounter, node) = uCoeffData[rowIndex];
1674 #else
1675 worksetApproxSolnCoef(cellCounter, node) = femCoeffData[rowIndex];
1676 #endif
1677 }
1678
1679 cellCounter++;
1680
1681 } // end cell loop
1682
1683 // Containers for Jacobian
1684 Intrepid::FieldContainer<double> worksetJacobianE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1685 Intrepid::FieldContainer<double> worksetJacobInvE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1686 Intrepid::FieldContainer<double> worksetJacobDetE(worksetSize, numCubPointsErr);
1687 Intrepid::FieldContainer<double> worksetCubWeightsE(worksetSize, numCubPointsErr);
1688
1689 // Containers for basis values and gradients in physical space
1690 Intrepid::FieldContainer<double> uhGValsTrans(worksetSize,numFieldsG, numCubPointsErr);
1691 Intrepid::FieldContainer<double> uhGradsTrans(worksetSize, numFieldsG, numCubPointsErr, spaceDim);
1692
1693 // compute cell Jacobians, their inverses and their determinants
1694 IntrepidCTools::setJacobian(worksetJacobianE, cubPointsErr, cellWorksetEr, myHGradBasis_rcp);
1695 IntrepidCTools::setJacobianInv(worksetJacobInvE, worksetJacobianE );
1696 IntrepidCTools::setJacobianDet(worksetJacobDetE, worksetJacobianE );
1697
1698 // map cubature points to physical frame
1699 Intrepid::FieldContainer<double> worksetCubPoints(worksetSize, numCubPointsErr, cubDimErr);
1700 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPointsErr, cellWorksetEr, myHGradBasis_rcp);
1701
1702 // evaluate exact solution and gradient at cubature points
1703 Intrepid::FieldContainer<double> worksetExactSoln(worksetSize, numCubPointsErr);
1704 Intrepid::FieldContainer<double> worksetExactSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1705 evaluateExactSolution(worksetExactSoln, worksetCubPoints);
1706 evaluateExactSolutionGrad(worksetExactSolnGrad, worksetCubPoints);
1707
1708 // transform basis values to physical coordinates
1709 IntrepidFSTools::HGRADtransformVALUE<double>(uhGValsTrans, uhGVals);
1710 IntrepidFSTools::HGRADtransformGRAD<double>(uhGradsTrans, worksetJacobInvE, uhGrads);
1711
1712 // compute weighted measure
1713 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeightsE, worksetJacobDetE, cubWeightsErr);
1714
1715 // evaluate the approximate solution and gradient at cubature points
1716 Intrepid::FieldContainer<double> worksetApproxSoln(worksetSize, numCubPointsErr);
1717 Intrepid::FieldContainer<double> worksetApproxSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1718 IntrepidFSTools::evaluate<double>(worksetApproxSoln, worksetApproxSolnCoef, uhGValsTrans);
1719 IntrepidFSTools::evaluate<double>(worksetApproxSolnGrad, worksetApproxSolnCoef, uhGradsTrans);
1720
1721 // get difference between approximate and exact solutions
1722 Intrepid::FieldContainer<double> worksetDeltaSoln(worksetSize, numCubPointsErr);
1723 Intrepid::FieldContainer<double> worksetDeltaSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1724 IntrepidRSTools::subtract(worksetDeltaSoln, worksetApproxSoln, worksetExactSoln);
1725 IntrepidRSTools::subtract(worksetDeltaSolnGrad, worksetApproxSolnGrad, worksetExactSolnGrad);
1726
1727 // take absolute values
1728 IntrepidRSTools::absval(worksetDeltaSoln);
1729 IntrepidRSTools::absval(worksetDeltaSolnGrad);
1730 // apply cubature weights to differences in values and grads for use in integration
1731 Intrepid::FieldContainer<double> worksetDeltaSolnWeighted(worksetSize, numCubPointsErr);
1732 Intrepid::FieldContainer<double> worksetDeltaSolnGradWeighted(worksetSize, numCubPointsErr, spaceDim);
1733 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnWeighted,
1734 worksetCubWeightsE, worksetDeltaSoln);
1735 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnGradWeighted,
1736 worksetCubWeightsE, worksetDeltaSolnGrad);
1737
1738 // integrate to get errors on each element
1739 Intrepid::FieldContainer<double> worksetL2err(worksetSize);
1740 Intrepid::FieldContainer<double> worksetH1err(worksetSize);
1741 IntrepidFSTools::integrate<double>(worksetL2err, worksetDeltaSoln,
1742 worksetDeltaSolnWeighted, Intrepid::COMP_BLAS);
1743 IntrepidFSTools::integrate<double>(worksetH1err, worksetDeltaSolnGrad,
1744 worksetDeltaSolnGradWeighted, Intrepid::COMP_BLAS);
1745
1746 // loop over cells to get errors for total workset
1747 cellCounter = 0;
1748 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1749
1750 // loop over cubature points
1751 for(int nPt = 0; nPt < numCubPointsErr; nPt++){
1752
1753 Linferr = std::max(Linferr, worksetDeltaSoln(cellCounter,nPt));
1754
1755 }
1756
1757 L2err += worksetL2err(cellCounter);
1758 H1err += worksetH1err(cellCounter);
1759
1760 cellCounter++;
1761
1762 } // end cell loop
1763
1764 } // end loop over worksets
1765
1766 #ifdef HAVE_MPI
1767 // sum over all processors
1768 TC_sumAll(Comm,L2err,L2errTot);
1769 TC_sumAll(Comm,H1err,H1errTot);
1770 TC_maxAll(Comm,Linferr,LinferrTot);
1771 #else
1772 L2errTot = L2err;
1773 H1errTot = H1err;
1774 LinferrTot = Linferr;
1775 #endif
1776
1777
1778 if (MyPID == 0) {
1779 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
1780 std::cout << "H1 Error: " << sqrt(H1errTot) <<"\n";
1781 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
1782 }
1783
1784 const bool alwaysWriteLocal = false;
1785 const bool writeGlobalStats = true;
1786 const bool writeZeroTimers = false;
1787 const bool ignoreZeroTimers = true;
1788 const std::string filter = "";
1789 if (optPrintTimings) {
1790 tm.reset();
1791 TimeMonitor::summarize(Comm.ptr(), std::cout, alwaysWriteLocal, writeGlobalStats,
1792 writeZeroTimers, Teuchos::Union, filter, ignoreZeroTimers);
1793 }
1794
1795 // Cleanup
1796 for(long long b = 0; b < numElemBlk; b++){
1797 delete [] elmt_node_linkage[b];
1798 delete [] element_types[b];
1799 }
1800 delete [] block_ids;
1801 delete [] nodes_per_element;
1802 delete [] element_attributes;
1803 delete [] element_types;
1804 delete [] elmt_node_linkage;
1805 delete [] elements;
1806 delete [] P1_globalNodeIds;
1807 delete [] P1_nodeIsOwned;
1808 if(num_node_comm_maps > 0){
1809 delete [] node_comm_proc_ids;
1810 delete [] node_cmap_node_cnts;
1811 delete [] node_cmap_ids;
1812 for(long long i=0;i<num_node_comm_maps;i++){
1813 delete [] comm_node_ids[i];
1814 delete [] comm_node_proc_ids[i];
1815 }
1816
1817 delete [] comm_node_ids;
1818 delete [] comm_node_proc_ids;
1819 }
1820
1821 delete [] nodeCoordx;
1822 delete [] nodeCoordy;
1823
1824 // delete mesh
1825 Delete_Pamgen_Mesh();
1826
1827 return 0;
1828
1829 }
1830 /**********************************************************************************/
1831 /********************************* END MAIN ***************************************/
1832 /**********************************************************************************/
1833
1834 /**********************************************************************************/
1835 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1836 /**********************************************************************************/
1837
1838 template<typename Scalar>
1839 const Scalar exactSolution(const Scalar& x, const Scalar& y) {
1840
1841 // Patch test: bi-linear function is in the FE space and should be recovered
1842 return 1. + x + y + x*y;
1843
1844 // Analytic solution with homogeneous Dirichlet boundary data
1845 // return sin(M_PI*x)*sin(M_PI*y)**exp(x+y);
1846
1847 // Analytic solution with inhomogeneous Dirichlet boundary data
1848 // return exp(x + y )/(1. + x*y);
1849 }
1850
1851
1852 // Stored diffusion tensor
1853 std::vector<double> diffusion_tensor;
1854
1855 template<typename Scalar>
1856 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y) {
1857 if(diffusion_tensor.size() == 0)
1858 diffusion_tensor = ::TrilinosCouplings::IntrepidPoissonExample::getDiffusionMatrix2D();
1859 material[0][0] = (Scalar)diffusion_tensor[0];
1860 material[0][1] = (Scalar)diffusion_tensor[1];
1861 //
1862 material[1][0] = (Scalar)diffusion_tensor[2];
1863 material[1][1] = (Scalar)diffusion_tensor[3];
1864 }
1865
1866 /**********************************************************************************/
1867 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1868 /**********************************************************************************/
1869
1870 /************ Grad of Exact Solution ****************/
1871 template<typename Scalar>
1872 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y) {
1873
1874 // To enable derivatives of the gradient (i.e., 2nd derivatives of the exact solution) need 2 levels of fad types
1875 Sacado::Fad::SFad<Scalar,2> fad_x = x;
1876 Sacado::Fad::SFad<Scalar,2> fad_y = y;
1877 Sacado::Fad::SFad<Scalar,2> u;
1878
1879 // Indicate the independent variables
1880 fad_x.diff(0,2);
1881 fad_y.diff(1,2);
1882
1883 u = exactSolution(fad_x, fad_y);
1884
1885 gradExact[0] = u.dx(0);
1886 gradExact[1] = u.dx(1);
1887 }
1888
1889 /************ Source Term (RHS) ****************/
1890 template<typename Scalar>
1891 const Scalar sourceTerm(Scalar& x, Scalar& y){
1892
1893 Scalar u;
1894 Scalar grad_u[2];
1895 Scalar flux[2] = {0.0, 0.0};
1896 Scalar material[2][2];
1897 Scalar f = 0.;
1898
1899 // Indicate the independent variables
1900 x.diff(0,2);
1901 y.diff(1,2);
1902
1903 // Get exact solution and its gradient
1904 u = exactSolution(x, y);
1905 exactSolutionGrad(grad_u, x, y);
1906
1907 // Get material tensor
1908 materialTensor<Scalar>(material, x, y);
1909
1910 // Compute total flux = (A.grad u)
1911 for(int i = 0; i < 2; i++){
1912
1913 // Add diffusive flux
1914 for(int j = 0; j < 2; j++){
1915 flux[i] += material[i][j]*grad_u[j];
1916 }
1917 }
1918
1919 // Compute source term (right hand side): f = -div(A.grad u)
1920 f = -(flux[0].dx(0) + flux[1].dx(1));
1921
1922 return f;
1923 }
1924
1925 /**********************************************************************************/
1926 /*************************** EVALUATION METHODS ***********************************/
1927 /**********************************************************************************/
1928
1929 /************ Material Tensor ****************/
1930 template<class ArrayOut, class ArrayIn>
1931 void evaluateMaterialTensor(ArrayOut & matTensorValues,
1932 const ArrayIn & evaluationPoints){
1933
1934 int numWorksetCells = evaluationPoints.dimension(0);
1935 int numPoints = evaluationPoints.dimension(1);
1936 int spaceDim = evaluationPoints.dimension(2);
1937
1938 double material[2][2];
1939
1940 for(int cell = 0; cell < numWorksetCells; cell++){
1941 for(int pt = 0; pt < numPoints; pt++){
1942
1943 double x = evaluationPoints(cell, pt, 0);
1944 double y = evaluationPoints(cell, pt, 1);
1945
1946 materialTensor<double>(material, x, y);
1947
1948 for(int row = 0; row < spaceDim; row++){
1949 for(int col = 0; col < spaceDim; col++){
1950 matTensorValues(cell, pt, row, col) = material[row][col];
1951 }
1952 }
1953 }
1954 }
1955 }
1956 /************ Source Term (RHS) ****************/
1957 template<class ArrayOut, class ArrayIn>
1958 void evaluateSourceTerm(ArrayOut & sourceTermValues,
1959 const ArrayIn & evaluationPoints){
1960
1961 int numWorksetCells = evaluationPoints.dimension(0);
1962 int numPoints = evaluationPoints.dimension(1);
1963
1964 for(int cell = 0; cell < numWorksetCells; cell++){
1965 for(int pt = 0; pt < numPoints; pt++){
1966
1967 Sacado::Fad::SFad<double,2> x = evaluationPoints(cell, pt, 0);
1968 Sacado::Fad::SFad<double,2> y = evaluationPoints(cell, pt, 1);
1969
1970 sourceTermValues(cell, pt) = sourceTerm<Sacado::Fad::SFad<double,2> >(x, y).val();
1971 }
1972 }
1973 }
1974
1975 /************ Exact Solution ****************/
1976 template<class ArrayOut, class ArrayIn>
1977 void evaluateExactSolution(ArrayOut & exactSolutionValues,
1978 const ArrayIn & evaluationPoints){
1979
1980 int numWorksetCells = evaluationPoints.dimension(0);
1981 int numPoints = evaluationPoints.dimension(1);
1982
1983 for(int cell = 0; cell < numWorksetCells; cell++){
1984 for(int pt = 0; pt < numPoints; pt++){
1985
1986 double x = evaluationPoints(cell, pt, 0);
1987 double y = evaluationPoints(cell, pt, 1);
1988
1989 exactSolutionValues(cell, pt) = exactSolution<double>(x, y);
1990 }
1991 }
1992 }
1993 /************ Grad of Exact Solution ****************/
1994 template<class ArrayOut, class ArrayIn>
1995 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
1996 const ArrayIn & evaluationPoints){
1997
1998 int numWorksetCells = evaluationPoints.dimension(0);
1999 int numPoints = evaluationPoints.dimension(1);
2000 int spaceDim = evaluationPoints.dimension(2);
2001
2002 double gradient[2];
2003
2004 for(int cell = 0; cell < numWorksetCells; cell++){
2005 for(int pt = 0; pt < numPoints; pt++){
2006
2007 double x = evaluationPoints(cell, pt, 0);
2008 double y = evaluationPoints(cell, pt, 1);
2009
2010 exactSolutionGrad<double>(gradient, x, y);
2011
2012 for(int row = 0; row < spaceDim; row++){
2013 exactSolutionGradValues(cell, pt, row) = gradient[row];
2014 }
2015 }
2016 }
2017 }
2018
2019 /**********************************************************************************/
2020 /******************************* TEST ML ******************************************/
2021 /**********************************************************************************/
2022
2023 // Test ML
2024 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
2025 ParameterList & amgList,
2026 RCP<crs_matrix_type> const &A0,
2027 RCP<multivector_type> & nCoord,
2028 RCP<multivector_type> const & xexact,
2029 RCP<multivector_type> & b,
2030 int maxIts,
2031 double tol,
2032 RCP<multivector_type> & uh,
2033 double & TotalErrorResidual,
2034 double & TotalErrorExactSol,
2035 std::string &amgType,
2036 std::string &solveType)
2037 {
2038
2039 // int mypid = A0->getComm()->getRank();
2040 RCP<multivector_type>x = uh;
2041
2042 linear_problem_type Problem(linear_problem_type(A0, x, b));
2043 RCP<multivector_type> lhs = Problem.getLHS();
2044 RCP<const multivector_type> rhs = Problem.getRHS();
2045
2046 RCP<TimeMonitor>
2047 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Total solve time")));
2048
2049 // =================== //
2050 // call ML and Belos //
2051 // =================== //
2052
2053 if (amgType != "ML" && amgType != "MueLu") {
2054 std::ostringstream errStr;
2055 errStr << "Error: \"amgType\" has value \"" << amgType << "\". Valid values are \"ML\" or \"MueLu\".";
2056 throw std::runtime_error(errStr.str());
2057 }
2058
2059 int numIterations=0;
2060 if (amgType == "ML") {
2061 throw std::runtime_error("Error: ML does not support Tpetra objects");
2062 } else if (amgType == "MueLu") {
2063
2064 // Multigrid Hierarchy, the easy way
2065 RCP<operator_type> A0op = A0;
2066 amgList.sublist("user data").set("Coordinates",nCoord);
2067 Teuchos::RCP<muelu_tpetra_operator> M = MueLu::CreateTpetraPreconditioner<scalar_type,local_ordinal_type,global_ordinal_type,NO>(A0op, amgList);
2068 Problem.setRightPrec(M);
2069
2070 bool set = Problem.setProblem();
2071 if (set == false) {
2072 std::cout << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
2073 return EXIT_FAILURE;
2074 }
2075
2076 // Belos parameter list
2077 ParameterList belosList;
2078 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
2079 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
2080 // belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
2081 belosList.set("Output Frequency", 1);
2082 belosList.set("Output Style", 1);
2083 belosList.set ("Verbosity", 33);
2084 bool scaleResidualHist = true;
2085 if (!scaleResidualHist)
2086 belosList.set("Implicit Residual Scaling", "None");
2087
2088 // Create an iterative solver manager
2089 RCP< Belos::SolverManager<scalar_type, multivector_type, operator_type> > solver;
2090 if(solveType == "cg")
2091 solver = rcp(new Belos::PseudoBlockCGSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
2092 else if (solveType == "gmres") {
2093 solver = rcp(new Belos::PseudoBlockGmresSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
2094 }
2095 else if (solveType == "fixed point" || solveType == "fixed-point") {
2096 solver = rcp(new Belos::FixedPointSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
2097 }
2098 else {
2099 std::cout << "\nERROR: Invalid solver '"<<solveType<<"'" << std::endl;
2100 return EXIT_FAILURE;
2101 }
2102
2103
2104 // Perform solve
2105 solver->solve();
2106 //writer_type::writeDenseFile("sol.m", x);
2107 numIterations = solver->getNumIters();
2108 }
2109
2110 ArrayRCP<const scalar_type> lhsdata = lhs->getData(0);
2111 ArrayRCP<const scalar_type> xexactdata = xexact->getData(0);
2112
2113 // ==================================================== //
2114 // compute difference between exact solution and ML one //
2115 // ==================================================== //
2116 double d = 0.0, d_tot = 0.0 , s =0.0, s_tot=0.0;
2117 for( size_t i=0 ; i<lhs->getMap()->getLocalNumElements() ; ++i ) {
2118 d += (lhsdata[i] - xexactdata[i]) * (lhsdata[i] - xexactdata[i]);
2119 s += xexactdata[i]* xexactdata[i];
2120 }
2121 lhsdata = Teuchos::null;
2122 xexactdata = Teuchos::null;
2123
2124 TC_sumAll(A0->getComm(),d,d_tot);
2125 TC_sumAll(A0->getComm(),s,s_tot);
2126
2127 // ================== //
2128 // compute ||Ax - b|| //
2129 // ================== //
2130 Array<typename ScalarTraits::magnitudeType> Norm(1);
2131 vector_type Ax(rhs->getMap());
2132 A0->apply(*lhs, Ax);
2133 Ax.update(1.0, *rhs, -1.0);
2134 Ax.norm2(Norm);
2135
2136 string msg = ProblemType;
2137
2138 int numProc = A0->getComm()->getSize();
2139 if (A0->getComm()->getRank() == 0) {
2140 cout << msg << endl << "......Using " << numProc << " processes" << endl;
2141 cout << msg << "......||A x - b||_2 = " << Norm[0] << endl;
2142 cout << msg << "......||x_exact - x||_2/||x_exact||_2 = " << sqrt(d_tot/s_tot) << endl;
2143 }
2144
2145 TotalErrorExactSol += sqrt(d_tot);
2146 TotalErrorResidual += Norm[0];
2147
2148 return(numIterations);
2149
2150 }
2151
2152 /*********************************************************************************************************/
2153 /*********************************************************************************************************/
2154 /*********************************************************************************************************/
2155
2156
2157 void GenerateEdgeEnumeration(const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, FieldContainer<int> & elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<int> & edgeToNode, FieldContainer<double> & edgeCoord) {
2158 // Not especially efficient, but effective... at least in serial!
2159
2160 int numElems = elemToNode.dimension(0);
2161 int numNodesperElem = elemToNode.dimension(1);
2162 int dim = nodeCoord.dimension(1);
2163
2164 // Sanity checks
2165 if(numNodesperElem !=4) throw std::runtime_error("Error: GenerateEdgeEnumeration only works on Quads!");
2166 if(elemToEdge.dimension(0)!=numElems || elemToEdge.dimension(1)!=4 || elemToEdge.dimension(0)!=elemToEdgeOrient.dimension(0) || elemToEdge.dimension(1)!=elemToEdgeOrient.dimension(1))
2167 throw std::runtime_error("Error: GenerateEdgeEnumeration array size mismatch");
2168
2169 int edge_node0_id[4]={0,1,2,3};
2170 int edge_node1_id[4]={1,2,3,0};
2171
2172 // Run over all the elements and start enumerating edges
2173 typedef std::map<std::pair<int,int>,int> en_map_type;
2174 en_map_type e2n;
2175
2176 int num_edges=0;
2177 en_map_type edge_map;
2178 for(int i=0; i<numElems; i++) {
2179
2180 // Generate edge pairs, based on the global orientation of "edges go from low ID to high ID"
2181 for(int j=0; j<4; j++) {
2182 int lo = std::min(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
2183 int hi = std::max(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
2184
2185 std::pair<int,int> ep(lo,hi);
2186
2187 int edge_id;
2188 en_map_type::iterator iter = edge_map.find(ep);
2189 if(iter==edge_map.end()) {
2190 edge_map[ep] = num_edges;
2191 edge_id = num_edges;
2192 num_edges++;
2193 }
2194 else
2195 edge_id = (*iter).second;
2196
2197 elemToEdge(i,j) = edge_id;
2198 elemToEdgeOrient(i,j) = (lo==elemToNode(i,edge_node0_id[j]))?1:-1;
2199 }
2200 }
2201
2202 // Fill out the edge centers (clobbering data if needed)
2203 edgeCoord.resize(num_edges,dim);
2204 for(int i=0; i<numElems; i++) {
2205 for(int j=0; j<4; j++) {
2206 int n0 = elemToNode(i,edge_node0_id[j]);
2207 int n1 = elemToNode(i,edge_node1_id[j]);
2208 for(int k=0; k<dim; k++)
2209 edgeCoord(elemToEdge(i,j),k) = (nodeCoord(n0,k)+nodeCoord(n1,k))/2.0;
2210 }
2211 }
2212
2213 // Edge to Node connectivity
2214 edgeToNode.resize(num_edges,2);
2215 for(int i=0; i<numElems; i++) {
2216 for(int j=0; j<4; j++) {
2217 int lo = std::min(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
2218 int hi = std::max(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
2219 edgeToNode(elemToEdge(i,j),0) = lo;
2220 edgeToNode(elemToEdge(i,j),1) = hi;
2221 }
2222 }
2223
2224
2225 //#define DEBUG_EDGE_ENUMERATION
2226 #ifdef DEBUG_EDGE_ENUMERATION
2227 printf("**** Edge coordinates ***\n");
2228 for(int i=0; i<num_edges; i++)
2229 printf("[%2d] %10.2f %10.2f\n",i,edgeCoord(i,0),edgeCoord(i,1));
2230 #endif
2231
2232 }
2233
2234
2235
2236 /*********************************************************************************************************/
2237 void PromoteMesh_Pn_Kirby(const int degree, const EPointType & pointType,
2238 const FieldContainer<int> & P1_elemToNode,
2239 const FieldContainer<double> & P1_nodeCoord,
2240 const FieldContainer<double> & P1_edgeCoord,
2241 const FieldContainer<int> & P1_elemToEdge,
2242 const FieldContainer<int> & P1_elemToEdgeOrient,
2243 const FieldContainer<int> & P1_nodeOnBoundary,
2244 FieldContainer<int> & Pn_elemToNode,
2245 FieldContainer<double> & Pn_nodeCoord,
2246 FieldContainer<int> & Pn_nodeOnBoundary,
2247 std::vector<int> & Pn_edgeNodes,
2248 std::vector<int> & Pn_cellNodes) {
2249 //#define DEBUG_PROMOTE_MESH
2250 int numElems = P1_elemToNode.dimension(0);
2251 int P1_numNodesperElem = P1_elemToNode.dimension(1);
2252 int P1_numEdgesperElem = P1_elemToEdge.dimension(1);
2253 int Pn_numNodesperElem = Pn_elemToNode.dimension(1);
2254 int P1_numNodes = P1_nodeCoord.dimension(0);
2255 int P1_numEdges = P1_edgeCoord.dimension(0);
2256 int dim = P1_nodeCoord.dimension(1);
2257
2258
2259 #ifdef DEBUG_PROMOTE_MESH
2260 int Pn_numNodes = Pn_nodeCoord.dimension(0);
2261 #endif
2262
2263 int Pn_ExpectedNodesperElem = P1_numNodesperElem + (degree-1)*P1_numEdgesperElem + (degree-1)*(degree-1);
2264 int Pn_ExpectedNumNodes = P1_numNodes + (degree-1)*P1_numEdges + (degree-1)*(degree-1)*numElems;
2265
2266 // Sanity checks
2267 if(P1_numNodesperElem !=4 || Pn_numNodesperElem !=Pn_ExpectedNodesperElem ) throw std::runtime_error("Error: PromoteMesh_Pn_Kirby only works on Quads!");
2268 if(P1_elemToEdge.dimension(0)!=numElems || P1_elemToEdge.dimension(1)!=4 || P1_elemToEdge.dimension(0)!=P1_elemToEdgeOrient.dimension(0) || P1_elemToEdge.dimension(1)!=P1_elemToEdgeOrient.dimension(1) ||
2269 Pn_elemToNode.dimension(0)!=numElems || Pn_nodeCoord.dimension(0) != Pn_ExpectedNumNodes)
2270 throw std::runtime_error("Error: PromoteMesh_Pn_Kirby array size mismatch");
2271
2272 const CellTopologyData &cellTopoData = *shards::getCellTopologyData<shards::Quadrilateral<4> >();
2273 shards::CellTopology cellTopo(&cellTopoData);
2274
2275 // Kirby elements are ordered strictly in lex ordering from the bottom left to the top right
2276 /*
2277 Kirby Quad-9 Layout (p=2)
2278 inode6 -- inode7 -- inode8
2279 | |
2280 inode3 inode4 inode5
2281 | |
2282 inode0 -- inode1 -- inode2
2283
2284
2285 Kirby Quad-16 Layout (p=3)
2286 inode12-- inode13-- inode14-- inode15
2287 | |
2288 inode8 inode9 inode10 inode11
2289 | |
2290 inode4 inode5 inode6 inode7
2291 | |
2292 inode0 -- inode1 -- inode2 -- inode3
2293 */
2294
2295 // We still number the global nodes in the exodus-style (node,edge,face) ordering, *by global orientation* but
2296 // the elem2node map has to account for Kirby-style elements
2297 int p1_node_in_pn[4] = {0,degree, (degree+1)*(degree+1)-1, degree*(degree+1)};
2298 int edge_node0_id[4]={0,1,2,3};
2299 int edge_node1_id[4]={1,2,3,0};
2300
2301 // As you advance along each edge, we'll skip by the following amount to get to the next Kirby dof
2302 // edge_skip is in *local* orientation, so we'll multiply it by the elemToEdgeOrient value
2303 int edge_skip[4] = {1,degree+1,-1,-(degree+1)};
2304 int center_root = degree+2;
2305
2306 // Make the new el2node array
2307 for(int i=0; i<numElems; i++) {
2308 // P1 nodes
2309 for(int j=0; j<P1_numNodesperElem; j++)
2310 Pn_elemToNode(i,p1_node_in_pn[j]) = P1_elemToNode(i,j);
2311
2312 // P1 edges
2313 for(int j=0; j<P1_numEdgesperElem; j++){
2314 int orient = P1_elemToEdgeOrient(i,j);
2315 int base_id = (orient==1) ? p1_node_in_pn[edge_node0_id[j]] : p1_node_in_pn[edge_node1_id[j]];
2316 int skip = orient*edge_skip[j];
2317 for(int k=0; k<degree-1; k++) {
2318 int node = P1_numNodes+P1_elemToEdge(i,j)*(degree-1)+k;
2319 Pn_elemToNode(i,base_id+(k+1)*skip) = node;
2320 Pn_edgeNodes.push_back(node);
2321 }
2322 }
2323
2324 // P1 cells
2325 for(int j=0; j<degree-1; j++)
2326 for(int k=0; k<degree-1; k++) {
2327 int node = P1_numNodes+P1_numEdges*(degree-1)+i*(degree-1)*(degree-1) + j*(degree-1)+k;
2328 Pn_elemToNode(i,center_root+j*(degree+1)+k) = node;
2329 Pn_cellNodes.push_back(node);
2330 }
2331
2332 }
2333
2334 // Get the p=n node locations
2335 FieldContainer<double> RefNodeCoords(Pn_numNodesperElem,dim);
2336 FieldContainer<double> RefNodeCoords2(1,Pn_numNodesperElem,dim);
2337 FieldContainer<double> PhysNodeCoords(1,Pn_numNodesperElem,dim);
2338 Basis_HGRAD_QUAD_Cn_FEM<double, FieldContainer<double> > BasisPn(degree,pointType);
2339 BasisPn.getDofCoords(RefNodeCoords);
2340
2341 #ifdef DEBUG_PROMOTE_MESH
2342 printf("**** P=%d reference nodal coordinates ***\n",degree);
2343 for(int i=0; i<Pn_numNodesperElem; i++)
2344 printf("[%2d] %10.2f %10.2f\n",i,RefNodeCoords(i,0),RefNodeCoords(i,1));
2345 #endif
2346
2347 for(int i=0; i<Pn_numNodesperElem; i++)
2348 for(int k=0; k<dim; k++)
2349 RefNodeCoords2(0,i,k) = RefNodeCoords(i,k);
2350
2351 // Make the new coordinates (inefficient, but correct)
2352 for(int i=0; i<numElems; i++) {
2353 // Get Element coords
2354 FieldContainer<double> my_p1_nodes(1,P1_numNodesperElem,dim);
2355 for(int j=0; j<P1_numNodesperElem; j++) {
2356 int jj = P1_elemToNode(i,j);
2357 for(int k=0; k<dim; k++)
2358 my_p1_nodes(0,j,k) = P1_nodeCoord(jj,k);
2359 }
2360
2361 // Map the reference node location to physical
2362 Intrepid::CellTools<double>::mapToPhysicalFrame(PhysNodeCoords,RefNodeCoords2,my_p1_nodes,cellTopo);
2363
2364
2365 #ifdef DEBUG_PROMOTE_MESH
2366 printf("[%2d] PhysNodes : ",i);
2367 for(int j=0; j<Pn_numNodesperElem; j++)
2368 printf("(%10.2f %10.2f) ",PhysNodeCoords(0,j,0),PhysNodeCoords(0,j,1));
2369 printf("\n");
2370 #endif
2371
2372
2373 // Copy the physical node locations to the Pn_nodeCoord array
2374 for(int j=0; j<Pn_numNodesperElem; j++) {
2375 int jj = Pn_elemToNode(i,j);
2376 for(int k=0; k<dim; k++)
2377 Pn_nodeCoord(jj,k) = PhysNodeCoords(0,j,k);
2378 }
2379
2380 }
2381
2382 #ifdef DEBUG_PROMOTE_MESH
2383 for(int i=0; i<numElems; i++) {
2384 printf("[%2d] Effective : ",i);
2385 for(int j=0; j<Pn_numNodesperElem; j++)
2386 printf("(%10.2f %10.2f) ",Pn_nodeCoord(Pn_elemToNode(i,j),0),Pn_nodeCoord(Pn_elemToNode(i,j),1));
2387 printf("\n");
2388 }
2389 #endif
2390
2391 // Update the boundary conditions
2392
2393 // P1 nodes
2394 for(int i=0; i<P1_numNodes; i++)
2395 Pn_nodeOnBoundary(i) = P1_nodeOnBoundary(i);
2396
2397 // P1 edges
2398 // Not all that efficient
2399 for(int i=0; i<numElems; i++) {
2400 for(int j=0; j<P1_numEdgesperElem; j++) {
2401 int n0 = P1_elemToNode(i,edge_node0_id[j]);
2402 int n1 = P1_elemToNode(i,edge_node1_id[j]);
2403 if(P1_nodeOnBoundary(n0) && P1_nodeOnBoundary(n1)) {
2404 for(int k=0; k<degree-1; k++)
2405 Pn_nodeOnBoundary(P1_numNodes+P1_elemToEdge(i,j)*(degree-1)+k) =1;
2406 }
2407 }
2408 }
2409
2410 #ifdef DEBUG_PROMOTE_MESH
2411 // debug
2412 printf("**** P=%d elem2node ***\n",degree);
2413 for(int i=0; i<numElems; i++) {
2414 printf("[%2d] ",i);
2415 for(int j=0; j<Pn_numNodesperElem; j++)
2416 printf("%2d ",Pn_elemToNode(i,j));
2417 printf("\n");
2418 }
2419
2420
2421 printf("**** P=%d nodes ***\n",degree);
2422 for(int i=0; i<Pn_numNodes; i++) {
2423 printf("[%2d] %10.2e %10.2e (%d)\n",i,Pn_nodeCoord(i,0),Pn_nodeCoord(i,1),(int)Pn_nodeOnBoundary(i));
2424 }
2425
2426 printf("**** P=1 nodes ***\n");
2427 for(int i=0; i<P1_numNodes; i++) {
2428 printf("[%2d] %10.2e %10.2e (%d)\n",i,P1_nodeCoord(i,0),P1_nodeCoord(i,1),(int)P1_nodeOnBoundary(i));
2429 }
2430 #endif
2431
2432
2433 }
2434
2435
2436 /*********************************************************************************************************/
2437
2438 void CreateP1MeshFromPnMesh(int degree,
2439 FieldContainer<int> const & Pn_elemToNode,
2440 FieldContainer<int> & P1_elemToNode)
2441 {
2442
2443 /*
2444 Main idea:
2445 For each P=n element
2446 Create n^2 P1 elements
2447 For each of those P1 elements
2448 Create element to node map
2449 */
2450
2451 int Pn_numElems = Pn_elemToNode.dimension(0);
2452
2453 int p1ElemCtr=0;
2454 for (int i=0; i<Pn_numElems; ++i) {
2455
2456 // Kirby elements are ordered strictly in lex ordering from the bottom left to the top right
2457 /*
2458 Kirby Quad-9 Layout (p=2)
2459 inode6 -- inode7 -- inode8
2460 | |
2461 inode3 inode4 inode5
2462 | |
2463 inode0 -- inode1 -- inode2
2464
2465
2466 Kirby Quad-16 Layout (p=3)
2467 inode12-- inode13-- inode14-- inode15
2468 | |
2469 inode8 inode9 inode10 inode11
2470 | |
2471 inode4 inode5 inode6 inode7
2472 | |
2473 inode0 -- inode1 -- inode2 -- inode3
2474 */
2475
2476 /*
2477 How "P1" elements are traversed in a Kirby P2 element
2478
2479 inode6 -- inode7 -- inode8
2480
2481 | 2 | 3 |
2482
2483 inode3 -- inode4 -- inode5
2484
2485 | 0 | 1 |
2486
2487 inode0 -- inode1 -- inode2
2488 */
2489
2490 int dp1 = degree+1;
2491 for (int j=0; j<degree; ++j) { //"y" direction
2492 for (int k=0; k<degree; ++k) { //"x" direction
2493
2494 int lowerLeftNode = dp1*j + k;
2495 //Exodus ordering (counter-clockwise)
2496 P1_elemToNode(p1ElemCtr,0) = Pn_elemToNode(i,lowerLeftNode);
2497 P1_elemToNode(p1ElemCtr,1) = Pn_elemToNode(i,lowerLeftNode+1);
2498 P1_elemToNode(p1ElemCtr,2) = Pn_elemToNode(i,lowerLeftNode+dp1+1);
2499 P1_elemToNode(p1ElemCtr,3) = Pn_elemToNode(i,lowerLeftNode+dp1);
2500 p1ElemCtr++;
2501
2502 }
2503 }
2504
2505 }
2506 } //CreateP1MeshFromPnMesh
2507
2508 /*********************************************************************************************************/
2509
2510 void CreateLinearSystem(int numWorksets,
2511 int desiredWorksetSize,
2512 FieldContainer<int> const &elemToNode,
2513 FieldContainer<double> const &nodeCoord,
2514 FieldContainer<double> const &cubPoints,
2515 FieldContainer<double> const &cubWeights,
2516 RCP<Basis<double,FieldContainer<double> > >&myBasis_rcp,
2517 FieldContainer<double> const &HGBGrads,
2518 FieldContainer<double> const &HGBValues,
2519 std::vector<global_ordinal_type> const &globalNodeIds,
2520 crs_matrix_type &StiffMatrix,
2521 RCP<multivector_type> &rhsVector,
2522 std::string &msg
2523 )
2524 {
2525 int numCubPoints = cubPoints.dimension(0);
2526 int cubDim = cubPoints.dimension(1);
2527 int spaceDim = nodeCoord.dimension(1);
2528 int numFieldsG = HGBGrads.dimension(0);
2529 long long numElems = elemToNode.dimension(0);
2530 int numNodesPerElem = elemToNode.dimension(1);
2531
2532
2533 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Allocate arrays")));
2534
2535 std::cout << "CreateLinearSystem:" << std::endl;
2536 std::cout << " numCubPoints = " << numCubPoints << std::endl;
2537 std::cout << " cubDim = " << cubDim << std::endl;
2538 std::cout << " spaceDim = " << spaceDim << std::endl;
2539 std::cout << " numFieldsG = " << numFieldsG << std::endl;
2540 std::cout << " numElems = " << numElems << std::endl;
2541 std::cout << " numNodesPerElem = " << numNodesPerElem << std::endl;
2542 std::cout << " length(globalNodeIds) = " << globalNodeIds.size() << std::endl;
2543 std::cout << " length(nodeCoord) = " << nodeCoord.dimension(0) << std::endl;
2544
2545 if(nodeCoord.dimension(0) != Teuchos::as<int>(globalNodeIds.size())) {
2546 std::ostringstream errStr;
2547 errStr << "Error: CreateLinearSystem: length of coordinates != #nodes ("
2548 << nodeCoord.dimension(0) << "!=" << globalNodeIds.size() << ")";
2549 throw std::runtime_error(errStr.str());
2550 }
2551
2552 for(int workset = 0; workset < numWorksets; workset++){
2553
2554 // Compute cell numbers where the workset starts and ends
2555 int worksetSize = 0;
2556 int worksetBegin = (workset + 0)*desiredWorksetSize;
2557 int worksetEnd = (workset + 1)*desiredWorksetSize;
2558
2559 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
2560 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
2561
2562 // Now we know the actual workset size and can allocate the array for the cell nodes
2563 worksetSize = worksetEnd - worksetBegin;
2564 //std::cout << " cellWorkset: begin=" << worksetBegin << ", end=" << worksetEnd
2565 // << ", size=" << worksetSize << std::endl;
2566 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
2567
2568 // Copy coordinates into cell workset
2569 int cellCounter = 0;
2570 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2571 for (int node = 0; node < numNodesPerElem; node++) {
2572 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
2573 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
2574 }
2575 cellCounter++;
2576 }
2577
2578 /**********************************************************************************/
2579 /* Allocate arrays */
2580 /**********************************************************************************/
2581
2582 // Containers for Jacobians, integration measure & cubature points in workset cells
2583 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
2584 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
2585 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
2586 FieldContainer<double> worksetCubWeights(worksetSize, numCubPoints);
2587 FieldContainer<double> worksetCubPoints (worksetSize, numCubPoints, cubDim);
2588
2589 // Containers for basis values transformed to workset cells and them multiplied by cubature weights
2590 FieldContainer<double> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
2591 FieldContainer<double> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
2592 FieldContainer<double> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
2593 FieldContainer<double> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
2594
2595 // Containers for diffusive & advective fluxes & non-conservative adv. term and reactive terms
2596 FieldContainer<double> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
2597
2598 // Containers for material values and source term. Require user-defined functions
2599 FieldContainer<double> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
2600 FieldContainer<double> worksetSourceTerm (worksetSize, numCubPoints);
2601
2602 // Containers for workset contributions to the discretization matrix and the right hand side
2603 FieldContainer<double> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
2604 FieldContainer<double> worksetRHS (worksetSize, numFieldsG);
2605
2606 tm.reset();
2607 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Calculate Jacobians")));
2608
2609 /**********************************************************************************/
2610 /* Calculate Jacobians */
2611 /**********************************************************************************/
2612 // Due to the way setJacobian works, we need to use the basis form here
2613 // IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
2614 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, myBasis_rcp);
2615 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
2616 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
2617
2618 //#define DEBUG_OUTPUT
2619 #ifdef DEBUG_OUTPUT
2620 printf("*** cubPoints ***\n");
2621 for(int j=0; j<numCubPoints; j++)
2622 printf("(%d) [%10.2e %10.2e]\n",j,cubPoints(j,0),cubPoints(j,1));
2623
2624 printf("*** cellWorkset ***\n");
2625 for(int i=0; i<worksetSize; i++)
2626 for(int j=0; j<numNodesPerElem; j++)
2627 printf("(%d,%d) [%10.2e %10.2e]\n",i,j,cellWorkset(i,j,0),cellWorkset(i,j,1));
2628
2629 printf("*** Jacobian ***\n");
2630 for(int i=0; i<worksetSize; i++)
2631 for(int j=0; j<numCubPoints; j++)
2632 printf("(%d,%d) [%10.2e %10.2e; %10.2e %10.2e]\n",i,j,zwrap(worksetJacobian(i,j,0,0)),zwrap(worksetJacobian(i,j,0,1)),zwrap(worksetJacobian(i,j,1,0)),zwrap(worksetJacobian(i,j,1,1)));
2633
2634 printf("*** det J ***\n");
2635 for(int i=0; i<worksetSize; i++)
2636 for(int j=0; j<numCubPoints; j++)
2637 printf("(%d,%d) %10.2e\n",i,j,zwrap(worksetJacobDet(i,j)));
2638
2639 #endif
2640
2641
2642 /**********************************************************************************/
2643 /* Cubature Points to Physical Frame and Compute Data */
2644 /**********************************************************************************/
2645
2646 tm.reset();
2647 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Map to physical frame and get source term")));
2648
2649 // map cubature points to physical frame
2650 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, myBasis_rcp);
2651
2652 // get A at cubature points
2653 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
2654
2655 // get source term at cubature points
2656 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
2657
2658 /**********************************************************************************/
2659 /* Compute Stiffness Matrix */
2660 /**********************************************************************************/
2661
2662 tm.reset();
2663 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Compute stiffness matrix")));
2664
2665 // Transform basis gradients to physical frame:
2666 IntrepidFSTools::HGRADtransformGRAD<double>(worksetHGBGrads, // DF^{-T}(grad u)
2667 worksetJacobInv, HGBGrads);
2668
2669 // Compute integration measure for workset cells:
2670 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeights, // Det(DF)*w = J*w
2671 worksetJacobDet, cubWeights);
2672
2673
2674 // Multiply transformed (workset) gradients with weighted measure
2675 IntrepidFSTools::multiplyMeasure<double>(worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
2676 worksetCubWeights, worksetHGBGrads);
2677
2678
2679 // Compute the diffusive flux:
2680 IntrepidFSTools::tensorMultiplyDataField<double>(worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
2681 worksetMaterialVals,
2682 worksetHGBGrads);
2683
2684 // Integrate to compute workset diffusion contribution to global matrix:
2685 IntrepidFSTools::integrate<double>(worksetStiffMatrix, //(DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
2686 worksetHGBGradsWeighted,
2687 worksetDiffusiveFlux, COMP_BLAS);
2688
2689 /**********************************************************************************/
2690 /* Compute RHS */
2691 /**********************************************************************************/
2692
2693 tm.reset();
2694 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Compute right-hand side")));
2695
2696 // Transform basis values to physical frame:
2697 IntrepidFSTools::HGRADtransformVALUE<double>(worksetHGBValues, // clones basis values (u)
2698 HGBValues);
2699
2700 // Multiply transformed (workset) values with weighted measure
2701 IntrepidFSTools::multiplyMeasure<double>(worksetHGBValuesWeighted, // (u)*J*w
2702 worksetCubWeights, worksetHGBValues);
2703
2704 // Integrate worksetSourceTerm against weighted basis function set
2705 IntrepidFSTools::integrate<double>(worksetRHS, // f.(u)*J*w
2706 worksetSourceTerm,
2707 worksetHGBValuesWeighted, COMP_BLAS);
2708
2709 /**********************************************************************************/
2710 /***************************** STATISTICS (Part II) ******************************/
2711 /**********************************************************************************/
2712 for(int i=0; i<worksetSize; i++) {
2713 // 0 - Material property
2714 // 1 - Max/min edge - ratio of max to min edge length
2715 // 2 - det of cell Jacobian (later)
2716 double elementdetJ = 0.0, elementWeight=0.0;
2717 for(int j=0; j<numCubPoints; j++) {
2718 elementdetJ += worksetJacobDet(i,j) * worksetCubWeights(i,j);
2719 elementWeight += worksetCubWeights(i,j);
2720 }
2721 double detJ = elementdetJ / elementWeight;
2722 local_stat_max[2] = std::max(local_stat_max[2],detJ);
2723 local_stat_min[2] = std::min(local_stat_min[2],detJ);
2724 local_stat_sum[2] += detJ;
2725 }
2726
2727
2728 #ifdef DEBUG_OUTPUT
2729 printf("*** worksetSourceTerm ***\n");
2730 for(int i=0; i<worksetSize; i++)
2731 for(int j=0; j<numCubPoints; j++)
2732 printf("(%d,%d) %10.2e\n",i,j,worksetSourceTerm(i,j));
2733
2734
2735 printf("*** worksetCubWeights ***\n");
2736 for(int i=0; i<worksetSize; i++)
2737 for(int j=0; j<numCubPoints; j++)
2738 printf("(%d,%d) %10.2e\n",i,j,worksetCubWeights(i,j));
2739
2740
2741 printf("*** worksetHGBValues ***\n");
2742 for(int i=0; i<worksetSize; i++)
2743 for(int j=0; j<numFieldsG; j++) {
2744 printf("(%d,%d) ",i,j);
2745 for(int k=0; k<numCubPoints; k++) {
2746 printf("%10.2e ",zwrap(worksetHGBValues(i,j,k)));
2747 }
2748 printf("\n");
2749 }
2750
2751 printf("*** worksetHGBValuesWeighted ***\n");
2752 for(int i=0; i<worksetSize; i++)
2753 for(int j=0; j<numFieldsG; j++) {
2754 printf("(%d,%d) ",i,j);
2755 for(int k=0; k<numCubPoints; k++) {
2756 printf("%10.2e ",zwrap(worksetHGBValues(i,j,k)));
2757 }
2758 printf("\n");
2759 }
2760
2761 printf("*** worksetRHS ***\n");
2762 for(int i=0; i<worksetSize; i++)
2763 for(int j=0; j<numFieldsG; j++)
2764 printf("(%d,%d) %10.2e\n",i,j,worksetRHS(i,j));
2765
2766 printf("*** worksetStiffMatrix ***\n");
2767 for(int i=0; i<worksetSize; i++) {
2768 printf("(%d) [ ",i);
2769 for(int j=0; j<numFieldsG; j++) {
2770 for(int k=0; k<numFieldsG; k++) {
2771 printf("%10.2e ",zwrap(worksetStiffMatrix(i,j,k)));
2772 }
2773 if(j!=numFieldsG-1) printf(";");
2774 }
2775 printf("]\n");
2776 }
2777
2778
2779
2780 #endif
2781
2782 /**********************************************************************************/
2783 /* Assemble into Global Matrix and RHS */
2784 /**********************************************************************************/
2785
2786 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
2787
2788 Array<scalar_type> vals1(1);
2789 Array<global_ordinal_type> cols1(1);
2790 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2791
2792 // Compute cell ordinal relative to the current workset
2793 int worksetCellOrdinal = cell - worksetBegin;
2794
2795 // "CELL EQUATION" loop for the workset cell: cellRow is relative to the cell DoF numbering
2796 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
2797
2798 int localRow = elemToNode(cell, cellRow);
2799 int globalRow = globalNodeIds[localRow];
2800 double sourceTermContribution = worksetRHS(worksetCellOrdinal, cellRow);
2801
2802
2803 rhsVector->sumIntoGlobalValue(globalRow, 0, sourceTermContribution);
2804
2805 // "CELL VARIABLE" loop for the workset cell: cellCol is relative to the cell DoF numbering
2806 for (int cellCol = 0; cellCol < numFieldsG; cellCol++){
2807
2808 int localCol = elemToNode(cell, cellCol);
2809 int globalCol = globalNodeIds[localCol];
2810 double operatorMatrixContribution = worksetStiffMatrix(worksetCellOrdinal, cellRow, cellCol);
2811 cols1[0] = globalCol;
2812 vals1[0] = operatorMatrixContribution;
2813 StiffMatrix.insertGlobalValues(globalRow, cols1(), vals1());
2814 // printf("Inserting A(%d,%d) = %6.4e\n",(int)globalCol,(int)cols1[0],vals1[0]);
2815 }// *** cell col loop ***
2816 }// *** cell row loop ***
2817 }// *** workset cell loop **
2818
2819 }// *** workset loop ***
2820
2821 StiffMatrix.fillComplete();
2822
2823 /**********************************************************************************/
2824 /***************************** STATISTICS (Part IIb) ******************************/
2825 /**********************************************************************************/
2826 Teuchos::RCP<const crs_graph_type> gl_StiffGraph = StiffMatrix.getCrsGraph();
2827 Teuchos::RCP<const driver_map_type> rowMap = gl_StiffGraph->getRowMap();
2828 Teuchos::RCP<multivector_type> coordsOwnedPlusShared;
2829
2830 RCP<multivector_type> nCoord= rcp(new multivector_type(rowMap,2));
2831 {
2832 auto nCoordD = nCoord->get2dViewNonConst();
2833 for (int inode=0; inode<nodeCoord.dimension(0); inode++) {
2834 nCoordD[0][inode]=nodeCoord(inode,0);
2835 nCoordD[1][inode]=nodeCoord(inode,1);
2836 }
2837 }
2838
2839 if (!(gl_StiffGraph->getImporter().is_null())) {
2840 coordsOwnedPlusShared = rcp(new multivector_type(gl_StiffGraph->getColMap(), 3, true));
2841 coordsOwnedPlusShared->doImport(*nCoord, *gl_StiffGraph->getImporter(), Tpetra::CombineMode::ADD, false);
2842 }
2843 else {
2844 coordsOwnedPlusShared = nCoord;
2845 }
2846
2847 vector_type laplDiagOwned(rowMap, true);
2848 typename crs_matrix_type::local_inds_host_view_type indices;
2849 typename crs_matrix_type::values_host_view_type values;
2850 size_t numOwnedRows = rowMap->getLocalNumElements();
2851 for (size_t row=0; row<numOwnedRows; row++) {
2852 StiffMatrix.getLocalRowView(row, indices, values);
2853 size_t numIndices = indices.size();
2854 for (size_t j=0; j<numIndices; j++) {
2855 size_t col = indices(j);
2856 if (row == col) continue;
2857 laplDiagOwned.sumIntoLocalValue(row, 1/myDistance2(*coordsOwnedPlusShared, row, col));
2858 }
2859 }
2860 Teuchos::RCP<vector_type> laplDiagOwnedPlusShared;
2861 if (!gl_StiffGraph->getImporter().is_null()) {
2862 laplDiagOwnedPlusShared = rcp(new vector_type(gl_StiffGraph->getColMap(), true));
2863 laplDiagOwnedPlusShared->doImport(laplDiagOwned, *gl_StiffGraph->getImporter(), Tpetra::CombineMode::ADD, false);
2864 }
2865 else {
2866 laplDiagOwnedPlusShared = rcp(&laplDiagOwned, false);
2867 }
2868 for (size_t row=0; row<numOwnedRows; row++) {
2869 StiffMatrix.getLocalRowView(row, indices, values);
2870 size_t numIndices = indices.size();
2871 for(size_t j=0; j<numIndices; j++) {
2872 size_t col = indices[j];
2873 if (row==col) continue;
2874 double laplVal = 1.0 / myDistance2(*coordsOwnedPlusShared, row, col);
2875 double aiiajj = std::abs(laplDiagOwnedPlusShared->getData()[row]*laplDiagOwnedPlusShared->getData()[col]);
2876 double aij = laplVal * laplVal;
2877 double ratio = sqrt(aij / aiiajj);
2878 local_stat_max[7] = std::max(local_stat_max[7], ratio);
2879 local_stat_min[7] = std::min(local_stat_min[7], ratio);
2880 local_stat_sum[7] += ratio;
2881 }
2882 }
2883
2884 } //CreateLinearSystem
2885
2886 /*********************************************************************************************************/
2887 void GenerateIdentityCoarsening_pn_to_p1(const FieldContainer<int> & Pn_elemToNode,
2888 RCP<const driver_map_type> const & P1_map_aux, RCP<const driver_map_type> const &Pn_map,
2889 RCP<crs_matrix_type> & P,
2890 RCP<crs_matrix_type> & R) {
2891
2892 // Generate prolongator matrix that will be used to transfer from P1 on auxiliary mesh to Pn on base mesh.
2893 // It's just the identity matrix.
2894 // By construction, the node numbering on the P1 auxiliary mesh is the same as on the Pn base mesh
2895 // (see CreateP1MeshFromPnMesh). The P2 map is the range map, the P1 auxiliary map is the domain map.
2896
2897 double one = 1.0;
2898 P = rcp(new crs_matrix_type(Pn_map,1));
2899
2900 //We must keep track of the nodes already encountered. Inserting more than once will cause
2901 //the values to be summed. Using a hashtable would work -- we abuse std::map for this purpose.
2902 std::map<int,int> hashTable;
2903 int Nelem=Pn_elemToNode.dimension(0);
2904 Array<scalar_type> vals1(1);
2905 vals1[0] = one;
2906 Array<global_ordinal_type> cols1(1);
2907 for(int i=0; i<Nelem; i++) {
2908 for(int j=0; j<Pn_elemToNode.dimension(1); j++) {
2909 int row = Pn_elemToNode(i,j);
2910 if (hashTable.find(row) == hashTable.end()) {
2911 //not found
2912 cols1[0] = row;
2913 P->insertGlobalValues(row,cols1(),vals1());
2914 hashTable[row] = 1;
2915 }
2916 }
2917 }
2918 P->fillComplete(P1_map_aux,Pn_map);
2919
2920 /*
2921 //JJH FIXME no need to generate R ... it's the identity, stupid
2922 hashTable.clear();
2923 R = rcp(new crs_matrix_type(P1_map_aux,1));
2924 Nelem = P1_elemToNode.dimension(0);
2925 int nodesPerElem = P1_elemToNode.dimension(1);
2926 for(int i=0; i<Nelem; ++i) {
2927 for(int j=0; j<nodesPerElem; ++j) {
2928 int row = P1_elemToNode(i,j);
2929 if (hashTable.find(row) == hashTable.end()) {
2930 //not found
2931 cols1[0] = row;
2932 R->insertGlobalValues(row,cols1(),vals1());
2933 hashTable[row] = 1;
2934 }
2935 }
2936 }
2937 R->fillComplete(Pn_map,P1_map_aux);
2938 */
2939
2940 }
2941
2942
2943 /*********************************************************************************************************/
2944 void Apply_Dirichlet_BCs(std::vector<int> &BCNodes, crs_matrix_type & A, multivector_type & x, multivector_type & b,
2945 const multivector_type & soln) {
2946 int N=(int)BCNodes.size();
2947 ArrayRCP<scalar_type> xdata = x.getDataNonConst(0);
2948 ArrayRCP<scalar_type> bdata = b.getDataNonConst(0);
2949 ArrayRCP<const scalar_type> solndata = soln.getData(0);
2950
2951 A.resumeFill();
2952
2953 for(int i=0; i<N; i++) {
2954 local_ordinal_type lrid = BCNodes[i];
2955
2956 xdata[lrid]=bdata[lrid] = solndata[lrid];
2957
2958 size_t numEntriesInRow = A.getNumEntriesInLocalRow(lrid);
2959 typename crs_matrix_type::nonconst_local_inds_host_view_type cols("cols", numEntriesInRow);
2960 typename crs_matrix_type::nonconst_values_host_view_type vals("vals", numEntriesInRow);
2961 A.getLocalRowCopy(lrid, cols, vals, numEntriesInRow);
2962
2963 for(size_t j=0; j<vals.extent(0); j++)
2964 vals(j) = (cols(j) == lrid) ? 1.0 : 0.0;
2965
2966 A.replaceLocalValues(lrid, cols, vals);
2967 }
2968
2969 A.fillComplete();
2970
2971 }