Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_Poisson2D_p2_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 MueLu 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
65 // TrilinosCouplings includes
66 #include "TrilinosCouplings_config.h"
67 #include "TrilinosCouplings_Pamgen_Utils.hpp"
68
69 // Intrepid includes
70 #include "Intrepid_FunctionSpaceTools.hpp"
71 #include "Intrepid_CellTools.hpp"
72 #include "Intrepid_ArrayTools.hpp"
73 #include "Intrepid_HGRAD_HEX_C1_FEM.hpp"
74 #include "Intrepid_RealSpaceTools.hpp"
75 #include "Intrepid_DefaultCubatureFactory.hpp"
76 #include "Intrepid_Utils.hpp"
77
78 #include <Tpetra_CrsMatrix.hpp>
79 #include <Tpetra_Vector.hpp>
80 #include <MatrixMarket_Tpetra.hpp>
81
82 // Teuchos includes
83 #include "Teuchos_oblackholestream.hpp"
84 #include "Teuchos_RCP.hpp"
85 #include "Teuchos_BLAS.hpp"
86 #include "Teuchos_GlobalMPISession.hpp"
87 #include "Teuchos_XMLParameterListHelpers.hpp"
88
89 // Shards includes
90 #include "Shards_CellTopology.hpp"
91
92 // Pamgen includes
93 #include "create_inline_mesh.h"
94 #include "pamgen_im_exodusII_l.h"
95 #include "pamgen_im_ne_nemesisI_l.h"
96 #include "pamgen_extras.h"
97
98 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
99 # include "MueLu.hpp"
100 # include "MueLu_ParameterListInterpreter.hpp"
101 # include "MueLu_TpetraOperator.hpp"
102 # include "MueLu_Utilities.hpp"
103 # include "MueLu_HierarchyManager.hpp"
104 # include "MueLu_FactoryManagerBase.hpp"
105 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
106
107 #ifdef HAVE_INTREPID_KOKKOS
108 #include "Sacado.hpp"
109 #else
110 // Sacado includes
111 #include "Sacado_No_Kokkos.hpp"
112 #endif
113
114 #include <BelosConfigDefs.hpp>
115 #include <BelosLinearProblem.hpp>
116 #include <BelosPseudoBlockCGSolMgr.hpp>
117 #include <BelosPseudoBlockGmresSolMgr.hpp>
118 #include <BelosFixedPointSolMgr.hpp>
119
120 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
121 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
122
123 using namespace std;
124 using namespace Intrepid;
125 using Teuchos::RCP;
126 using Teuchos::ArrayRCP;
127 using Teuchos::Array;
128 using Teuchos::rcp;
129 using Teuchos::rcpFromRef;
130 using Teuchos::TimeMonitor;
131 using Teuchos::ParameterList;
132
133
134
135 /*********************************************************/
136 /* Typedefs */
137 /*********************************************************/
138 typedef double scalar_type;
139 typedef Teuchos::ScalarTraits<scalar_type> ScalarTraits;
140 using local_ordinal_type = Tpetra::Map<>::local_ordinal_type;
141 using global_ordinal_type = Tpetra::Map<>::global_ordinal_type;
142 typedef Tpetra::KokkosClassic::DefaultNode::DefaultNodeType NO;
143 typedef Sacado::Fad::SFad<double,2> Fad2; //# ind. vars fixed at 2
144 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
145 typedef Intrepid::RealSpaceTools<double> IntrepidRSTools;
146 typedef Intrepid::CellTools<double> IntrepidCTools;
147
148 typedef Tpetra::Operator<scalar_type,local_ordinal_type,global_ordinal_type,NO> operator_type;
149 typedef Tpetra::CrsMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO> crs_matrix_type;
150 typedef Tpetra::Vector<scalar_type,local_ordinal_type,global_ordinal_type,NO> vector_type;
151 typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO> multivector_type;
152 typedef Tpetra::Map<local_ordinal_type,global_ordinal_type,NO> driver_map_type;
153 Tpetra::global_size_t INVALID_GO = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid();
154
155 typedef Belos::LinearProblem<scalar_type, multivector_type, operator_type> linear_problem_type;
156
157 typedef MueLu::TpetraOperator<scalar_type,local_ordinal_type,global_ordinal_type,NO> muelu_tpetra_operator;
158
159 //typedef Tpetra::MatrixMarket::Writer<crs_matrix_type> writer_type;
160
161 #define TC_sumAll(rcpComm, in, out) \
162 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_SUM, in, Teuchos::outArg(out))
163 #define TC_minAll(rcpComm, in, out) \
164 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MIN, in, Teuchos::outArg(out))
165 #define TC_maxAll(rcpComm, in, out) \
166 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MAX, in, Teuchos::outArg(out))
167
168
169 // forward declarations
170
171 void PromoteMesh(const int degree, 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,
172 FieldContainer<int> & P2_elemToNode, FieldContainer<double> & P2_nodeCoord,FieldContainer<int> & P2_nodeOnBoundary, std::vector<int> & P2_edgeNodes, std::vector<int> & P2_cellNodes);
173
174 void GenerateEdgeEnumeration(const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, FieldContainer<int> & elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<double> & edgeCoord);
175
176 void CreateP1MeshFromP2Mesh(const FieldContainer<int> & P2_elemToNode, FieldContainer<int> &aux_P1_elemToNode);
177
178 void CreateLinearSystem(int numWorkSets,
179 int desiredWorksetSize,
180 FieldContainer<int> const &elemToNode,
181 FieldContainer<double> const &nodeCoord,
182 FieldContainer<double> const &cubPoints,
183 FieldContainer<double> const &cubWeights,
184 FieldContainer<double> const &HGBGrads,
185 FieldContainer<double> const &HGBValues,
186 std::vector<global_ordinal_type> const &globalNodeIds,
187 shards::CellTopology const &cellType,
188 crs_matrix_type &StiffMatrix,
189 RCP<multivector_type> &rhsVector,
190 std::string &msg
191 );
192
193 void GenerateLinearCoarsening_p2_to_p1(const FieldContainer<int> & P2_elemToNode, RCP<driver_map_type> &P1_map, RCP<driver_map_type> & P2_map,RCP<crs_matrix_type> & P);
194
195 void GenerateIdentityCoarsening_p2_to_p1(const FieldContainer<int> & P2_elemToNode,
196 const FieldContainer<int> & P1_elemToNode,
197 RCP<const driver_map_type> const & P1_map_aux, RCP<const driver_map_type> const &P2_map,
198 RCP<crs_matrix_type> & Interpolation,
199 RCP<crs_matrix_type> & Restriction);
200
201 void Apply_Dirichlet_BCs(std::vector<int> &BCNodes, crs_matrix_type & A, multivector_type & x, multivector_type & b, const multivector_type & soln);
202
203 /**********************************************************************************/
204 /***************** FUNCTION DECLARATION FOR MUELU PRECONDITIONER *********************/
205 /**********************************************************************************/
206
207 /** \brief MueLu Preconditioner
208
209 \param ProblemType [in] problem type
210 \param amgList [in] MueLu parameter list
211 \param A [in] discrete operator matrix
212 \param xexact [in] exact solution
213 \param b [in] right-hand-side vector
214 \param uh [out] solution vector
215 \param TotalErrorResidual [out] error residual
216 \param TotalErrorExactSol [out] error in uh
217
218 */
219 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
220 ParameterList & amgList,
221 RCP<crs_matrix_type> const & A,
222 RCP<crs_matrix_type> const & P,
223 RCP<crs_matrix_type> const & R,
224 RCP<multivector_type> const & xexact,
225 RCP<multivector_type> & b,
226 RCP<multivector_type> & uh,
227 double & TotalErrorResidual,
228 double & TotalErrorExactSol,
229 std::string &amgType,
230 std::string &solveType);
231
232
233
234 /**********************************************************************************/
235 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
236 /**********************************************************************************/
237
238 /** \brief User-defined exact solution.
239
240 \param x [in] x-coordinate of the evaluation point
241 \param y [in] y-coordinate of the evaluation point
242
243 \return Value of the exact solution at (x,y)
244 */
245 template<typename Scalar>
246 const Scalar exactSolution(const Scalar& x, const Scalar& y);
247
248 /** \brief User-defined material tensor.
249
250 \param material [out] 3 x 3 material tensor evaluated at (x,y)
251 \param x [in] x-coordinate of the evaluation point
252 \param y [in] y-coordinate of the evaluation point
253
254 \warning Symmetric and positive definite tensor is required for every (x,y).
255 */
256 template<typename Scalar>
257 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y);
258
259 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
260
261 \param gradExact [out] gradient of the exact solution evaluated at (x,y)
262 \param x [in] x-coordinate of the evaluation point
263 \param y [in] y-coordinate of the evaluation point
264 */
265 template<typename Scalar>
266 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y);
267
268
269 /** \brief Computes source term: f = -div(A.grad u). Requires user-defined exact solution
270 and material tensor.
271
272 \param x [in] x-coordinate of the evaluation point
273 \param y [in] y-coordinate of the evaluation point
274
275 \return Source term corresponding to the user-defined exact solution evaluated at (x,y)
276 */
277 template<typename Scalar>
278 const Scalar sourceTerm(Scalar& x, Scalar& y);
279
280
281 /** \brief Computation of the material tensor at array of points in physical space.
282
283 \param worksetMaterialValues [out] Rank-2, 3 or 4 array with dimensions (C,P), (C,P,D) or (C,P,D,D)
284 with the values of the material tensor
285 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
286 */
287 template<class ArrayOut, class ArrayIn>
288 void evaluateMaterialTensor(ArrayOut & worksetMaterialValues,
289 const ArrayIn & evaluationPoints);
290
291
292 /** \brief Computation of the source term at array of points in physical space.
293
294 \param sourceTermValues [out] Rank-2 (C,P) array with the values of the source term
295 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
296 */
297 template<class ArrayOut, class ArrayIn>
298 void evaluateSourceTerm(ArrayOut & sourceTermValues,
299 const ArrayIn & evaluationPoints);
300
301 /** \brief Computation of the exact solution at array of points in physical space.
302
303 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
304 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
305 */
306 template<class ArrayOut, class ArrayIn>
307 void evaluateExactSolution(ArrayOut & exactSolutionValues,
308 const ArrayIn & evaluationPoints);
309
310
311 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
312
313 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
314 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
315 */
316 template<class ArrayOut, class ArrayIn>
317 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
318 const ArrayIn & evaluationPoints);
319
320
321 /**********************************************************************************/
322 /******************************** MAIN ********************************************/
323 /**********************************************************************************/
324
325 int main(int argc, char *argv[]) {
326
327 int error = 0;
328 int numProcs=1;
329 int rank=0;
330
331 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
332 RCP<const Teuchos::Comm<int> > Comm = Teuchos::DefaultComm<int>::getComm();
333 int MyPID = Comm->getRank();
334
335 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Pamgen Setup")));
336
337 //Check number of arguments
338 if (argc > 3) {
339 std::cout <<"\n>>> ERROR: Invalid number of arguments.\n\n";
340 std::cout <<"Usage:\n\n";
341 std::cout <<" ./TrilinosCouplings_examples_scaling_Example_Poisson.exe [meshfile.xml] [solver.xml]\n\n";
342 std::cout <<" meshfile.xml(optional) - xml file with description of Pamgen mesh\n\n";
343 std::cout <<" solver.xml(optional) - xml file with MueLu solver options\n\n";
344 exit(1);
345 }
346
347 if (MyPID == 0){
348 std::cout \
349 << "===============================================================================\n" \
350 << "| |\n" \
351 << "| Example: Solve Poisson Equation on Hexahedral Mesh |\n" \
352 << "| |\n" \
353 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
354 << "| Denis Ridzal ([email protected]), |\n" \
355 << "| Kara Peterson ([email protected]). |\n" \
356 << "| |\n" \
357 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
358 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
359 << "| ML's website: http://trilinos.sandia.gov/packages/ml |\n" \
360 << "| Isorropia's website: http://trilinos.sandia.gov/packages/isorropia |\n" \
361 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
362 << "| |\n" \
363 << "===============================================================================\n";
364 }
365
366
367 #ifdef HAVE_MPI
368 if (MyPID == 0) {
369 std::cout << "PARALLEL executable \n";
370 }
371 #else
372 if (MyPID == 0) {
373 std::cout << "SERIAL executable \n";
374 }
375 #endif
376
377 /**********************************************************************************/
378 /********************************** GET XML INPUTS ********************************/
379 /**********************************************************************************/
380
381 // Command line for xml file, otherwise use default
382 std::string xmlMeshInFileName, xmlSolverInFileName;
383 if(argc>=2) xmlMeshInFileName=string(argv[1]);
384 else xmlMeshInFileName="Poisson2D.xml";
385 if(argc>=3) xmlSolverInFileName=string(argv[2]);
386
387 // Read xml file into parameter list
388 ParameterList inputMeshList;
389 ParameterList inputSolverList;
390
391 if(xmlMeshInFileName.length()) {
392 if (MyPID == 0) {
393 std::cout << "\nReading parameter list from the XML file \""<<xmlMeshInFileName<<"\" ...\n\n";
394 }
395 Teuchos::updateParametersFromXmlFile (xmlMeshInFileName, Teuchos::ptr (&inputMeshList));
396 if (MyPID == 0) {
397 inputMeshList.print(std::cout,2,true,true);
398 std::cout << "\n";
399 }
400 }
401 else
402 {
403 std::cout << "Cannot read input file: " << xmlMeshInFileName << "\n";
404 return 0;
405 }
406
407 if(xmlSolverInFileName.length()) {
408 if (MyPID == 0)
409 std::cout << "\nReading parameter list from the XML file \""<<xmlSolverInFileName<<"\" ...\n\n";
410 Teuchos::updateParametersFromXmlFile(xmlSolverInFileName, Teuchos::inoutArg(inputSolverList));
411 } else if (MyPID == 0) std::cout << "Using default solver values ..." << std::endl;
412
413 // Get pamgen mesh definition
414 std::string meshInput = Teuchos::getParameter<std::string>(inputMeshList,"meshInput");
415
416 // Get Isorropia and Zoltan parameters.
417 ParameterList iso_paramlist = inputMeshList.sublist
418 ("Isorropia Input") ;
419 if (MyPID == 0) {
420 std::cout << "Isorropia/Zoltan parameters" << std::endl;
421 iso_paramlist.print(std::cout,2,true,true);
422 }
423
424
425 /**********************************************************************************/
426 /***************************** GET CELL TOPOLOGY **********************************/
427 /**********************************************************************************/
428
429 // Get cell topology for base hexahedron
430 shards::CellTopology P1_cellType(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
431 shards::CellTopology P2_cellType(shards::getCellTopologyData<shards::Quadrilateral<9> >() );
432 assert(P1_cellType.getDimension() == P2_cellType.getDimension());
433
434 // Get dimensions
435 int P1_numNodesPerElem = P1_cellType.getNodeCount();
436 int P2_numNodesPerElem = P2_cellType.getNodeCount();
437 int spaceDim = P1_cellType.getDimension();
438 int dim = 2;
439
440 /**********************************************************************************/
441 /******************************* GENERATE MESH ************************************/
442 /**********************************************************************************/
443
444 if (MyPID == 0) {
445 std::cout << "Generating mesh ... \n\n";
446 }
447
448 long long * node_comm_proc_ids = NULL;
449 long long * node_cmap_node_cnts = NULL;
450 long long * node_cmap_ids = NULL;
451 long long ** comm_node_ids = NULL;
452 long long ** comm_node_proc_ids = NULL;
453
454 // Generate mesh with Pamgen
455 long long maxInt = 9223372036854775807LL;
456 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
457 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
458
459 string msg("Poisson: ");
460 tm.reset();
461 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Mesh queries")));
462
463 // Get mesh size info
464 char title[100];
465 long long numDim;
466 long long numNodes;
467 long long numElems;
468 long long numElemBlk;
469 long long numNodeSets;
470 long long numSideSets;
471 int id = 0;
472
473 im_ex_get_init_l(id, title, &numDim, &numNodes,
474 &numElems, &numElemBlk, &numNodeSets,
475 &numSideSets);
476
477 long long numNodesGlobal;
478 long long numElemsGlobal;
479 long long numElemBlkGlobal;
480 long long numNodeSetsGlobal;
481 long long numSideSetsGlobal;
482
483 im_ne_get_init_global_l(id, &numNodesGlobal, &numElemsGlobal,
484 &numElemBlkGlobal, &numNodeSetsGlobal,
485 &numSideSetsGlobal);
486
487 // Print mesh information
488 if (MyPID == 0){
489 std::cout << " Number of Global Elements: " << numElemsGlobal << " \n";
490 std::cout << " Number of Global Nodes: " << numNodesGlobal << " \n\n";
491 }
492
493 long long * block_ids = new long long [numElemBlk];
494 error += im_ex_get_elem_blk_ids_l(id, block_ids);
495
496
497 long long *nodes_per_element = new long long [numElemBlk];
498 long long *element_attributes = new long long [numElemBlk];
499 long long *elements = new long long [numElemBlk];
500 char **element_types = new char * [numElemBlk];
501 long long **elmt_node_linkage = new long long * [numElemBlk];
502
503
504 for(long long i = 0; i < numElemBlk; i ++){
505 element_types[i] = new char [MAX_STR_LENGTH + 1];
506 error += im_ex_get_elem_block_l(id,
507 block_ids[i],
508 element_types[i],
509 (long long*)&(elements[i]),
510 (long long*)&(nodes_per_element[i]),
511 (long long*)&(element_attributes[i]));
512 }
513
514 /*connectivity*/
515 for(long long b = 0; b < numElemBlk; b++){
516 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
517 error += im_ex_get_elem_conn_l(id,block_ids[b],elmt_node_linkage[b]);
518 }
519
520 // Get node-element connectivity
521 int telct = 0;
522 FieldContainer<int> P1_elemToNode(numElems,P1_numNodesPerElem);
523 for(long long b = 0; b < numElemBlk; b++){
524 for(long long el = 0; el < elements[b]; el++){
525 for (int j=0; j<P1_numNodesPerElem; j++) {
526 P1_elemToNode(telct,j) = elmt_node_linkage[b][el*P1_numNodesPerElem + j]-1;
527 }
528 telct ++;
529 }
530 }
531
532 // Read node coordinates and place in field container
533 FieldContainer<double> P1_nodeCoord(numNodes,dim);
534 double * nodeCoordx = new double [numNodes];
535 double * nodeCoordy = new double [numNodes];
536 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,0);
537 for (int i=0; i<numNodes; i++) {
538 P1_nodeCoord(i,0)=nodeCoordx[i];
539 P1_nodeCoord(i,1)=nodeCoordy[i];
540 }
541
542 /*parallel info*/
543 long long num_internal_nodes;
544 long long num_border_nodes;
545 long long num_external_nodes;
546 long long num_internal_elems;
547 long long num_border_elems;
548 long long num_node_comm_maps;
549 long long num_elem_comm_maps;
550 im_ne_get_loadbal_param_l( id,
551 &num_internal_nodes,
552 &num_border_nodes,
553 &num_external_nodes,
554 &num_internal_elems,
555 &num_border_elems,
556 &num_node_comm_maps,
557 &num_elem_comm_maps,
558 0/*unused*/ );
559
560 if(num_node_comm_maps > 0){
561 node_comm_proc_ids = new long long [num_node_comm_maps];
562 node_cmap_node_cnts = new long long [num_node_comm_maps];
563 node_cmap_ids = new long long [num_node_comm_maps];
564 comm_node_ids = new long long* [num_node_comm_maps];
565 comm_node_proc_ids = new long long* [num_node_comm_maps];
566
567 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
568 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
569
570
571 if ( im_ne_get_cmap_params_l( id,
572 node_cmap_ids,
573 (long long*)node_cmap_node_cnts,
574 elem_cmap_ids,
575 (long long*)elem_cmap_elem_cnts,
576 0/*not used proc_id*/ ) < 0 )++error;
577
578 for(long long j = 0; j < num_node_comm_maps; j++) {
579 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
580 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
581 if ( im_ne_get_node_cmap_l( id,
582 node_cmap_ids[j],
583 comm_node_ids[j],
584 comm_node_proc_ids[j],
585 0/*not used proc_id*/ ) < 0 )++error;
586 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
587 }
588
589 delete [] elem_cmap_ids;
590 delete [] elem_cmap_elem_cnts;
591 }
592
593 tm.reset();
594 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global Node Nums")));
595
596
597 //Calculate global node ids
598 long long * P1_globalNodeIds = new long long[numNodes];
599 bool * P1_nodeIsOwned = new bool[numNodes];
600
601 calc_global_node_ids(P1_globalNodeIds,
602 P1_nodeIsOwned,
603 numNodes,
604 num_node_comm_maps,
605 node_cmap_node_cnts,
606 node_comm_proc_ids,
607 comm_node_ids,
608 rank);
609
610
611 tm.reset();
612 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Boundary Conds")));
613
614 // Container indicating whether a node is on the boundary (1-yes 0-no)
615 FieldContainer<int> P1_nodeOnBoundary(numNodes);
616
617 // Get boundary (side set) information
618 long long * sideSetIds = new long long [numSideSets];
619 long long numSidesInSet;
620 long long numDFinSet;
621 im_ex_get_side_set_ids_l(id,sideSetIds);
622 for (int i=0; i<numSideSets; i++) {
623 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
624 if (numSidesInSet > 0){
625 long long * sideSetElemList = new long long [numSidesInSet];
626 long long * sideSetSideList = new long long [numSidesInSet];
627 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
628 for (int j=0; j<numSidesInSet; j++) {
629
630 int sideNode0 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,0);
631 int sideNode1 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,1);
632
633 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode0))=1;
634 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode1))=1;
635 }
636 delete [] sideSetElemList;
637 delete [] sideSetSideList;
638 }
639 }
640 delete [] sideSetIds;
641
642 tm.reset();
643 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting cubature")));
644
645
646
647 // Enumerate edges
648 // NOTE: Only correct in serial
649 FieldContainer<int> P1_elemToEdge(numElems,4);// Because quads
650 FieldContainer<int> P1_elemToEdgeOrient(numElems,4);
651 FieldContainer<double> P1_edgeCoord(1,dim);//will be resized
652 GenerateEdgeEnumeration(P1_elemToNode, P1_nodeCoord, P1_elemToEdge,P1_elemToEdgeOrient,P1_edgeCoord);
653
654
655 // Generate higher order mesh
656 // NOTE: Only correct in serial
657 int P2_numNodes = numNodes + P1_edgeCoord.dimension(0) + numElems;
658 FieldContainer<int> elemToNode(numElems,9); //because quads
659 FieldContainer<double> nodeCoord(P2_numNodes,dim);
660 FieldContainer<int> nodeOnBoundary(P2_numNodes);
661 std::vector<int> P2_edgeNodes;
662 std::vector<int> P2_cellNodes;
663 PromoteMesh(2,P1_elemToNode,P1_nodeCoord,P1_edgeCoord,P1_elemToEdge,P1_elemToEdgeOrient,P1_nodeOnBoundary,
664 elemToNode, nodeCoord, nodeOnBoundary, P2_edgeNodes, P2_cellNodes);
665
666 long long numElems_aux = numElems*4; //4 P1 elements per P2 element in auxiliary mesh
667 FieldContainer<int> aux_P1_elemToNode(numElems_aux,P1_numNodesPerElem); //4 P1 elements per P2 element
668 CreateP1MeshFromP2Mesh(elemToNode, aux_P1_elemToNode);
669
670 // Only works in serial
671 std::vector<bool>P2_nodeIsOwned(P2_numNodes,true);
672 std::vector<global_ordinal_type>P2_globalNodeIds(P2_numNodes);
673 for(int i=0; i<P2_numNodes; i++)
674 P2_globalNodeIds[i]=i;
675
676 std::vector<double> P2_nodeCoordx(P2_numNodes);
677 std::vector<double> P2_nodeCoordy(P2_numNodes);
678 for (int i=0; i<P2_numNodes; i++) {
679 P2_nodeCoordx[i] = nodeCoord(i,0);
680 P2_nodeCoordy[i] = nodeCoord(i,1);
681 }
682
683 // Reset constants
684 int P1_numNodes =numNodes;
685 numNodes = P2_numNodes;
686 numNodesGlobal = numNodes;
687
688 // Print mesh information
689 if (MyPID == 0){
690 std::cout << " Number of P2 Global Elements: " << numElemsGlobal << " \n";
691 std::cout << " Number of P2 Global Nodes: " << numNodesGlobal << " \n";
692 std::cout << " Number of faux P1 Global Elements: " << aux_P1_elemToNode.dimension(0) << " \n\n";
693 }
694
695
696 /**********************************************************************************/
697 /********************************* GET CUBATURE ***********************************/
698 /**********************************************************************************/
699
700 // Get numerical integration points and weights
701 DefaultCubatureFactory<double> cubFactory;
702 int cubDegree = 4;
703 RCP<Cubature<double> > myCub = cubFactory.create(P2_cellType, cubDegree);
704
705 int cubDim = myCub->getDimension();
706 int numCubPoints = myCub->getNumPoints();
707
708 FieldContainer<double> cubPoints(numCubPoints, cubDim);
709 FieldContainer<double> cubWeights(numCubPoints);
710
711 myCub->getCubature(cubPoints, cubWeights);
712
713 tm.reset();
714 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting basis")));
715
716
717
718 /**********************************************************************************/
719 /*********************************** GET BASIS ************************************/
720 /**********************************************************************************/
721
722 // Define basis
723 Basis_HGRAD_QUAD_C2_FEM<double, FieldContainer<double> > myHGradBasis;
724 int numFieldsG = myHGradBasis.getCardinality();
725 FieldContainer<double> HGBValues(numFieldsG, numCubPoints);
726 FieldContainer<double> HGBGrads(numFieldsG, numCubPoints, spaceDim);
727
728 // Evaluate basis values and gradients at cubature points
729 myHGradBasis.getValues(HGBValues, cubPoints, OPERATOR_VALUE);
730 myHGradBasis.getValues(HGBGrads, cubPoints, OPERATOR_GRAD);
731
732 tm.reset();
733 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Build global maps")));
734
735
736 /**********************************************************************************/
737 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
738 /**********************************************************************************/
739 // Count owned nodes (P2)
740 int P2_ownedNodes=0;
741 for(int i=0;i<numNodes;i++)
742 if(P2_nodeIsOwned[i]) P2_ownedNodes++;
743
744 // Build a list of the OWNED global ids...
745 // NTS: will need to switch back to long long
746 std::vector<global_ordinal_type> P2_ownedGIDs(P2_ownedNodes);
747 int oidx=0;
748 for(int i=0;i<numNodes;i++)
749 if(P2_nodeIsOwned[i]){
750 P2_ownedGIDs[oidx]=(global_ordinal_type)P2_globalNodeIds[i];
751 oidx++;
752 }
753
754 // Count owned nodes (P1)
755 int P1_ownedNodes=0;
756 for(int i=0;i<P1_numNodes;i++)
757 if(P1_nodeIsOwned[i]) P1_ownedNodes++;
758 std::vector<global_ordinal_type> P1_ownedGIDs(P1_ownedNodes);
759 oidx=0;
760 for(int i=0;i<P1_numNodes;i++)
761 if(P1_nodeIsOwned[i]){
762 P1_ownedGIDs[oidx]=(global_ordinal_type)P1_globalNodeIds[i];
763 //nodeSeeds[oidx] = (int)P1_globalNodeIds[i];
764 oidx++;
765 }
766
767 //seed points for block relaxation
768 // numNodes is the number of nodes in the P2 mesh
769 ArrayRCP<global_ordinal_type> nodeSeeds(numNodes,Teuchos::OrdinalTraits<local_ordinal_type>::invalid());
770 //P1 nodes
771 oidx=0;
772 for(int i=0;i<P1_numNodes;i++) {
773 if(P1_nodeIsOwned[i]){
774 nodeSeeds[(int)P1_globalNodeIds[i]] = oidx;
775 oidx++;
776 }
777 }
778 int numNodeSeeds = oidx;
779
780 //edge nodes only
781 ArrayRCP<global_ordinal_type> edgeSeeds(numNodes,Teuchos::OrdinalTraits<local_ordinal_type>::invalid());
782 for(size_t i=0;i<P2_edgeNodes.size();i++) {
783 edgeSeeds[P2_edgeNodes[i]] = i;
784 }
785 int numEdgeSeeds = P2_edgeNodes.size();
786
787 //cell nodes only
788 ArrayRCP<global_ordinal_type> cellSeeds(numNodes,Teuchos::OrdinalTraits<local_ordinal_type>::invalid());
789 for(size_t i=0;i<P2_cellNodes.size();i++) {
790 cellSeeds[P2_cellNodes[i]] = i;
791 }
792 int numCellSeeds = P2_cellNodes.size();
793
794
795 // Generate map for nodes
796 RCP<driver_map_type> globalMapG = rcp(new driver_map_type(INVALID_GO,&P2_ownedGIDs[0],P2_ownedNodes,0,Comm));
797
798 // Generate p1 map
799 RCP<driver_map_type> P1_globalMap = rcp(new driver_map_type(INVALID_GO,&P1_ownedGIDs[0],P1_ownedNodes,0,Comm));
800
801 // Genetrate P2-to-P1 coarsening.
802 if (inputSolverList.isParameter("aux P1") && inputSolverList.isParameter("linear P1"))
803 throw std::runtime_error("Can only specify \"aux P1\" or \"linear P1\", not both.");
804 RCP<crs_matrix_type> P_linear;
805 if (inputSolverList.isParameter("linear P1")) {
806 GenerateLinearCoarsening_p2_to_p1(elemToNode,P1_globalMap,globalMapG,P_linear);
807 inputSolverList.remove("linear P1"); //even though LevelWrap happily accepts this parameter
808 }
809
810 crs_matrix_type StiffMatrix(globalMapG, 20*numFieldsG);
811 RCP<multivector_type> rhsVector = rcp(new multivector_type(globalMapG,1));
812 RCP<multivector_type> femCoefficients = rcp(new multivector_type(globalMapG,1));
813
814 tm = Teuchos::null;
815
816
817 #ifdef DUMP_DATA_OLD
818 /**********************************************************************************/
819 /**** PUT COORDINATES AND NODAL VALUES IN ARRAYS FOR OUTPUT (FOR PLOTTING ONLY) ***/
820 /**********************************************************************************/
821
822 // Put coordinates in multivector for output
823 multivector_type nCoord(*globalMapG,dim);
824 multivector_type nBound(*globalMapG,1);
825
826 int indOwned = 0;
827 for (int inode=0; inode<numNodes; inode++) {
828 if (nodeIsOwned[inode]) {
829 nCoord[0][indOwned]=nodeCoord(inode,0);
830 nCoord[1][indOwned]=nodeCoord(inode,1);
831 nBound[0][indOwned]=nodeOnBoundary(inode);
832 indOwned++;
833 }
834 }
835 EpetraExt::MultiVectorToMatrixMarketFile("coords.dat",nCoord,0,0,false);
836 EpetraExt::MultiVectorToMatrixMarketFile("nodeOnBound.dat",nBound,0,0,false);
837
838 // Put element to node mapping in multivector for output
839 //driver_map_type globalMapElem(numElemsGlobal, numElems, 0, Comm);
840 driver_map_type globalMapElem(numElemsGlobal, numElems, 0, Comm, NO);
841 multivector_type elem2nodeMV(globalMapElem, numNodesPerElem);
842 for (int ielem=0; ielem<numElems; ielem++) {
843 for (int inode=0; inode<numNodesPerElem; inode++) {
844 elem2nodeMV[inode][ielem]=globalNodeIds[elemToNode(ielem,inode)];
845 }
846 }
847 EpetraExt::MultiVectorToMatrixMarketFile("elem2node.dat",elem2nodeMV,0,0,false);
848
849 if(MyPID==0) {Time.ResetStartTime();}
850
851 #endif
852
853 /**********************************************************************************/
854 /************************** DIRICHLET BC SETUP ************************************/
855 /**********************************************************************************/
856 tm.reset();
857 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Get Dirichlet boundary values")));
858
859 int numBCNodes = 0;
860 for (int inode = 0; inode < numNodes; inode++){
861 if (nodeOnBoundary(inode) && P2_nodeIsOwned[inode]){
862 numBCNodes++;
863 }
864 }
865
866
867 // Vector for use in applying BCs
868 multivector_type v(globalMapG,true);
869 ArrayRCP<scalar_type> vdata = v.getDataNonConst(0);
870
871 // Set v to boundary values on Dirichlet nodes
872 //int * BCNodes = new int [numBCNodes];
873 std::vector<int> BCNodes(numBCNodes);
874 int indbc=0;
875 int iOwned=0;
876 for (int inode=0; inode<numNodes; inode++){
877 if (P2_nodeIsOwned[inode]){
878 if (nodeOnBoundary(inode)){
879 BCNodes[indbc]=iOwned;
880 indbc++;
881 double x = nodeCoord(inode, 0);
882 double y = nodeCoord(inode, 1);
883 vdata[iOwned]=exactSolution(x, y);
884 }
885 iOwned++;
886 }
887 }
888
889
890 tm.reset();
891 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global assembly")));
892
893 /**********************************************************************************/
894 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
895 /**********************************************************************************/
896
897 // Define desired workset size and count how many worksets there are on this processor's mesh block
898 int desiredWorksetSize = numElems; // change to desired workset size!
899 int numWorksets = numElems/desiredWorksetSize;
900
901 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
902 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
903
904 if (MyPID == 0) {
905 std::cout << "Building discretization matrix and right hand side... \n\n";
906 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
907 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
908 }
909
910 // Create P2 matrix and RHS
911 CreateLinearSystem(numWorksets,
912 desiredWorksetSize,
913 elemToNode,
914 nodeCoord,
915 cubPoints,
916 cubWeights,
917 HGBGrads,
918 HGBValues,
919 P2_globalNodeIds,
920 P2_cellType,
921 StiffMatrix,
922 rhsVector,
923 msg
924 );
925
926 /**********************************************************************************/
927 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
928 /**********************************************************************************/
929
930 StiffMatrix.fillComplete();
931 //writer_type::writeSparseFile("A0_p2_tpetra.m", rcpFromRef(StiffMatrix));
932 //writer_type::writeDenseFile("rhs_tpetra.m", rhsVector);
933
934 tm.reset();
935 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting cubature for auxiliary P1 mesh")));
936
937 /////////////////////////////////////////////////////////////////////
938 // Create P1 matrix and RHS to be used in preconditioner
939 /////////////////////////////////////////////////////////////////////
940
941 //Cubature
942
943 // Get numerical integration points and weights
944 int cubDegree_aux = 2; //TODO This was 3 for P=2. I think this should be 2 now .... Ask Chris.
945 RCP<Cubature<double> > myCub_aux = cubFactory.create(P1_cellType, cubDegree_aux);
946
947 int cubDim_aux = myCub_aux->getDimension();
948 int numCubPoints_aux = myCub_aux->getNumPoints();
949
950 FieldContainer<double> cubPoints_aux(numCubPoints_aux, cubDim_aux);
951 FieldContainer<double> cubWeights_aux(numCubPoints_aux);
952 myCub_aux->getCubature(cubPoints_aux, cubWeights_aux);
953
954 tm.reset();
955 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Getting basis for auxiliary P1 mesh")));
956
957 //Basis
958
959 // Define basis
960 Basis_HGRAD_QUAD_C1_FEM<double, FieldContainer<double> > myHGradBasis_aux;
961 int numFieldsG_aux = myHGradBasis_aux.getCardinality();
962 FieldContainer<double> HGBValues_aux(numFieldsG_aux, numCubPoints_aux);
963 FieldContainer<double> HGBGrads_aux(numFieldsG_aux, numCubPoints_aux, spaceDim);
964
965 // Evaluate basis values and gradients at cubature points
966 myHGradBasis_aux.getValues(HGBValues_aux, cubPoints_aux, OPERATOR_VALUE);
967 myHGradBasis_aux.getValues(HGBGrads_aux, cubPoints_aux, OPERATOR_GRAD);
968
969 tm.reset();
970 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global assembly (auxiliary system)")));
971
972 crs_matrix_type StiffMatrix_aux(globalMapG, 20*numFieldsG_aux);
973 RCP<multivector_type> rhsVector_aux = rcp(new multivector_type(globalMapG,1));
974
975 desiredWorksetSize = numElems_aux;
976 numWorksets = numElems_aux/desiredWorksetSize;
977 if(numWorksets*desiredWorksetSize < numElems_aux) numWorksets += 1;
978 CreateLinearSystem(numWorksets,
979 desiredWorksetSize,
980 aux_P1_elemToNode,
981 nodeCoord,
982 cubPoints_aux,
983 cubWeights_aux,
984 HGBGrads_aux,
985 HGBValues_aux,
986 P2_globalNodeIds,
987 P1_cellType,
988 StiffMatrix_aux,
989 rhsVector_aux,
990 msg
991 );
992
993 /**********************************************************************************/
994 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
995 /**********************************************************************************/
996
997 StiffMatrix_aux.fillComplete();
998 //writer_type::writeSparseFile("A1_p1_aux_tpetra.m", rcpFromRef(StiffMatrix_aux));
999
1000 tm.reset();
1001 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Adjust global matrix and rhs due to BCs")));
1002
1003 // Generate P2-to-P1 identity coarsening (base mesh to auxiliary mesh).
1004 RCP<crs_matrix_type> P_identity, R_identity;
1005 if (inputSolverList.isParameter("aux P1")) {
1006 GenerateIdentityCoarsening_p2_to_p1(elemToNode, aux_P1_elemToNode, StiffMatrix_aux.getDomainMap(), StiffMatrix.getRangeMap(), P_identity, R_identity);
1007 //writer_type::writeSparseFile("IdentityP_tpetra.m", P_identity);
1008 //writer_type::writeSparseFile("IdentityR_tpetra.m", R_identity);
1009 inputSolverList.remove("aux P1"); //even though LevelWrap happily accepts this parameter
1010 }
1011
1012 /**********************************************************************************/
1013 /******************************* ADJUST MATRIX DUE TO BC **************************/
1014 /**********************************************************************************/
1015
1016 //writer_type::writeDenseFile("rhs_tpetra_bcs.m", rhsVector);
1017
1018 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1019 // and add one to diagonal.
1020 Apply_Dirichlet_BCs(BCNodes,StiffMatrix,*femCoefficients,*rhsVector,v);
1021
1022 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1023 // and add one to diagonal.
1024 Apply_Dirichlet_BCs(BCNodes,StiffMatrix_aux,*rhsVector_aux,*rhsVector_aux,v);
1025
1026 tm = Teuchos::null;
1027
1028 //writer_type::writeSparseFile("A1_p1_aux_bcs_tpetra.m", rcpFromRef(StiffMatrix_aux));
1029
1030 /**********************************************************************************/
1031 /*********************************** SOLVE ****************************************/
1032 /**********************************************************************************/
1033
1034 // Which Solver?
1035 std::string solveType("cg");
1036 if(inputSolverList.isParameter("solver")) {
1037 solveType = inputSolverList.get<std::string>("solver");
1038 }
1039
1040 // Run the solver
1041 std::string amgType("MueLu");
1042
1043 ParameterList amgList;
1044 std::string seedType = inputSolverList.get("seed type","node");
1045 inputSolverList.remove("seed type");
1046 if (inputSolverList.isSublist("MueLu"))
1047 amgList = inputSolverList.sublist("MueLu");
1048 else
1049 amgList = inputSolverList;
1050
1051 std::string lev0List = "level 0";
1052 if (amgList.isSublist(lev0List)) {
1053 std::cout << "found \"" << lev0List << "\" sublist" << std::endl;
1054 ParameterList &sl = amgList.sublist(lev0List);
1055 std::string smooType = sl.get<std::string>("smoother: type");
1056 if (smooType == "BLOCK RELAXATION" && sl.isParameter("smoother: params")) {
1057 ParameterList &ssl = sl.sublist("smoother: params");
1058 std::cout << "found \"smoother: params\" for block relaxation" << std::endl;
1059 int numLocalParts;
1060 std::cout << "setting \"partitioner: map\"" << std::endl;
1061 if (seedType == "node") {
1062 ssl.set("partitioner: map", nodeSeeds);
1063 numLocalParts = numNodeSeeds;
1064 } else if (seedType == "edge") {
1065 ssl.set("partitioner: map", edgeSeeds);
1066 numLocalParts = numEdgeSeeds;
1067 } else if (seedType == "cell") {
1068 ssl.set("partitioner: map", cellSeeds);
1069 numLocalParts = numCellSeeds;
1070 }
1071 std::cout << "setting \"partitioner: local parts\" = " << numLocalParts << std::endl;
1072 ssl.set("partitioner: local parts", numLocalParts);
1073 }
1074 }
1075
1076 // /////////////////////////////////////////////////////////////////////// //
1077
1078 // Shove coordinates in multivector for saving to file.
1079 multivector_type coordinates(StiffMatrix.getRowMap(),2);
1080 ArrayRCP<scalar_type> xdat = coordinates.getDataNonConst(0);
1081 ArrayRCP<scalar_type> ydat = coordinates.getDataNonConst(1);
1082 for (size_t i=0; i<P2_nodeCoordx.size(); ++i) {
1083 xdat[i] = P2_nodeCoordx[i];
1084 ydat[i] = P2_nodeCoordy[i];
1085 }
1086 xdat = Teuchos::null; ydat = Teuchos::null;
1087 //writer_type::writeDenseFile("coords.m", coordinates);
1088
1089 multivector_type P1coordinates(P1_globalMap,2);
1090 xdat = P1coordinates.getDataNonConst(0);
1091 ydat = P1coordinates.getDataNonConst(1);
1092 for (size_t i=0; i<P1coordinates.getLocalLength(); i++) {
1093 xdat[i] = nodeCoordx[i];
1094 ydat[i] = nodeCoordy[i];
1095 }
1096 xdat = Teuchos::null; ydat = Teuchos::null;
1097 //writer_type::writeDenseFile("P1coords.m", P1coordinates);
1098
1099 multivector_type nBound(globalMapG,true);
1100
1101 RCP<multivector_type> exactNodalVals = rcp(new multivector_type(globalMapG,1));
1102 double TotalErrorResidual = 0.0;
1103 double TotalErrorExactSol = 0.0;
1104
1105 // Get exact solution at nodes
1106 for (int i = 0; i<numNodes; i++) {
1107 if (P2_nodeIsOwned[i]){
1108 double x = nodeCoord(i,0);
1109 double y = nodeCoord(i,1);
1110 double exactu = exactSolution(x, y);
1111
1112 int rowindex=P2_globalNodeIds[i];
1113 exactNodalVals->sumIntoGlobalValue(rowindex, 0, exactu);
1114 }
1115 }
1116
1117 char probType[10] = "laplace";
1118
1119 RCP<crs_matrix_type> interpolationMatrix, restrictionMatrix;
1120 if (P_identity != Teuchos::null) {
1121 amgList.set("user coarse matrix",(crs_matrix_type*)&StiffMatrix_aux);
1122 interpolationMatrix = P_identity;
1123 restrictionMatrix = R_identity;
1124 }
1125 if (P_linear != Teuchos::null) {
1126 interpolationMatrix = P_linear;
1127 }
1128
1129 TestMultiLevelPreconditionerLaplace(probType, amgList,
1130 rcpFromRef(StiffMatrix),
1131 interpolationMatrix, restrictionMatrix, exactNodalVals,
1132 rhsVector, femCoefficients,
1133 TotalErrorResidual, TotalErrorExactSol,
1134 amgType,
1135 solveType);
1136
1137 /**********************************************************************************/
1138 /**************************** CALCULATE ERROR *************************************/
1139 /**********************************************************************************/
1140
1141 tm.reset();
1142 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Calculate error")));
1143
1144 double L2err = 0.0;
1145 double L2errTot = 0.0;
1146 double H1err = 0.0;
1147 double H1errTot = 0.0;
1148 double Linferr = 0.0;
1149 double LinferrTot = 0.0;
1150
1151 #ifdef HAVE_MPI
1152 // Import solution onto current processor
1153 RCP<driver_map_type> solnMap = rcp(new driver_map_type(static_cast<int>(numNodesGlobal), static_cast<int>(numNodesGlobal), 0, Comm));
1154 Tpetra::Import<local_ordinal_type, global_ordinal_type, NO> solnImporter(globalMapG,solnMap);
1155 multivector_type uCoeff(solnMap,1);
1156 uCoeff.doImport(*femCoefficients, solnImporter, Tpetra::INSERT);
1157 #endif
1158
1159 // Define desired workset size
1160 desiredWorksetSize = numElems;
1161 int numWorksetsErr = numElems/desiredWorksetSize;
1162
1163 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1164 if(numWorksetsErr*desiredWorksetSize < numElems) numWorksetsErr += 1;
1165
1166 // Get cubature points and weights for error calc (may be different from previous)
1167 Intrepid::DefaultCubatureFactory<double> cubFactoryErr;
1168 int cubDegErr = 6;
1169 RCP<Intrepid::Cubature<double> > cellCubatureErr = cubFactoryErr.create(P2_cellType, cubDegErr);
1170 int cubDimErr = cellCubatureErr->getDimension();
1171 int numCubPointsErr = cellCubatureErr->getNumPoints();
1172 Intrepid::FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
1173 Intrepid::FieldContainer<double> cubWeightsErr(numCubPointsErr);
1174 cellCubatureErr->getCubature(cubPointsErr, cubWeightsErr);
1175
1176 // Evaluate basis values and gradients at cubature points
1177 Intrepid::FieldContainer<double> uhGVals(numFieldsG, numCubPointsErr);
1178 Intrepid::FieldContainer<double> uhGrads(numFieldsG, numCubPointsErr, spaceDim);
1179 myHGradBasis.getValues(uhGVals, cubPointsErr, Intrepid::OPERATOR_VALUE);
1180 myHGradBasis.getValues(uhGrads, cubPointsErr, Intrepid::OPERATOR_GRAD);
1181
1182 // Loop over worksets
1183 for(int workset = 0; workset < numWorksetsErr; workset++){
1184
1185 // compute cell numbers where the workset starts and ends
1186 int worksetSize = 0;
1187 int worksetBegin = (workset + 0)*desiredWorksetSize;
1188 int worksetEnd = (workset + 1)*desiredWorksetSize;
1189
1190 // when numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1191 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1192
1193 // now we know the actual workset size and can allocate the array for the cell nodes
1194 worksetSize = worksetEnd - worksetBegin;
1195 Intrepid::FieldContainer<double> cellWorksetEr(worksetSize, P2_numNodesPerElem, spaceDim);
1196 Intrepid::FieldContainer<double> worksetApproxSolnCoef(worksetSize, P2_numNodesPerElem);
1197
1198 // loop over cells to fill arrays with coordinates and discrete solution coefficient
1199 int cellCounter = 0;
1200 ArrayRCP<const scalar_type> uCoeffData = uCoeff.getData(0);
1201 ArrayRCP<const scalar_type> femCoeffData = femCoefficients->getData(0);
1202 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1203
1204 for (int node = 0; node < P2_numNodesPerElem; node++) {
1205 cellWorksetEr(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
1206 cellWorksetEr(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
1207
1208 int rowIndex = P2_globalNodeIds[elemToNode(cell, node)];
1209 #ifdef HAVE_MPI
1210 worksetApproxSolnCoef(cellCounter, node) = uCoeffData[rowIndex];
1211 #else
1212 worksetApproxSolnCoef(cellCounter, node) = femCoeffData[rowIndex];
1213 #endif
1214 }
1215
1216 cellCounter++;
1217
1218 } // end cell loop
1219
1220 // Containers for Jacobian
1221 Intrepid::FieldContainer<double> worksetJacobianE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1222 Intrepid::FieldContainer<double> worksetJacobInvE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1223 Intrepid::FieldContainer<double> worksetJacobDetE(worksetSize, numCubPointsErr);
1224 Intrepid::FieldContainer<double> worksetCubWeightsE(worksetSize, numCubPointsErr);
1225
1226 // Containers for basis values and gradients in physical space
1227 Intrepid::FieldContainer<double> uhGValsTrans(worksetSize,numFieldsG, numCubPointsErr);
1228 Intrepid::FieldContainer<double> uhGradsTrans(worksetSize, numFieldsG, numCubPointsErr, spaceDim);
1229
1230 // compute cell Jacobians, their inverses and their determinants
1231 IntrepidCTools::setJacobian(worksetJacobianE, cubPointsErr, cellWorksetEr, P2_cellType);
1232 IntrepidCTools::setJacobianInv(worksetJacobInvE, worksetJacobianE );
1233 IntrepidCTools::setJacobianDet(worksetJacobDetE, worksetJacobianE );
1234
1235 // map cubature points to physical frame
1236 Intrepid::FieldContainer<double> worksetCubPoints(worksetSize, numCubPointsErr, cubDimErr);
1237 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPointsErr, cellWorksetEr, P2_cellType);
1238
1239 // evaluate exact solution and gradient at cubature points
1240 Intrepid::FieldContainer<double> worksetExactSoln(worksetSize, numCubPointsErr);
1241 Intrepid::FieldContainer<double> worksetExactSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1242 evaluateExactSolution(worksetExactSoln, worksetCubPoints);
1243 evaluateExactSolutionGrad(worksetExactSolnGrad, worksetCubPoints);
1244
1245 // transform basis values to physical coordinates
1246 IntrepidFSTools::HGRADtransformVALUE<double>(uhGValsTrans, uhGVals);
1247 IntrepidFSTools::HGRADtransformGRAD<double>(uhGradsTrans, worksetJacobInvE, uhGrads);
1248
1249 // compute weighted measure
1250 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeightsE, worksetJacobDetE, cubWeightsErr);
1251
1252 // evaluate the approximate solution and gradient at cubature points
1253 Intrepid::FieldContainer<double> worksetApproxSoln(worksetSize, numCubPointsErr);
1254 Intrepid::FieldContainer<double> worksetApproxSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1255 IntrepidFSTools::evaluate<double>(worksetApproxSoln, worksetApproxSolnCoef, uhGValsTrans);
1256 IntrepidFSTools::evaluate<double>(worksetApproxSolnGrad, worksetApproxSolnCoef, uhGradsTrans);
1257
1258 // get difference between approximate and exact solutions
1259 Intrepid::FieldContainer<double> worksetDeltaSoln(worksetSize, numCubPointsErr);
1260 Intrepid::FieldContainer<double> worksetDeltaSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1261 IntrepidRSTools::subtract(worksetDeltaSoln, worksetApproxSoln, worksetExactSoln);
1262 IntrepidRSTools::subtract(worksetDeltaSolnGrad, worksetApproxSolnGrad, worksetExactSolnGrad);
1263
1264 // take absolute values
1265 IntrepidRSTools::absval(worksetDeltaSoln);
1266 IntrepidRSTools::absval(worksetDeltaSolnGrad);
1267 // apply cubature weights to differences in values and grads for use in integration
1268 Intrepid::FieldContainer<double> worksetDeltaSolnWeighted(worksetSize, numCubPointsErr);
1269 Intrepid::FieldContainer<double> worksetDeltaSolnGradWeighted(worksetSize, numCubPointsErr, spaceDim);
1270 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnWeighted,
1271 worksetCubWeightsE, worksetDeltaSoln);
1272 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnGradWeighted,
1273 worksetCubWeightsE, worksetDeltaSolnGrad);
1274
1275 // integrate to get errors on each element
1276 Intrepid::FieldContainer<double> worksetL2err(worksetSize);
1277 Intrepid::FieldContainer<double> worksetH1err(worksetSize);
1278 IntrepidFSTools::integrate<double>(worksetL2err, worksetDeltaSoln,
1279 worksetDeltaSolnWeighted, Intrepid::COMP_BLAS);
1280 IntrepidFSTools::integrate<double>(worksetH1err, worksetDeltaSolnGrad,
1281 worksetDeltaSolnGradWeighted, Intrepid::COMP_BLAS);
1282
1283 // loop over cells to get errors for total workset
1284 cellCounter = 0;
1285 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1286
1287 // loop over cubature points
1288 for(int nPt = 0; nPt < numCubPointsErr; nPt++){
1289
1290 Linferr = std::max(Linferr, worksetDeltaSoln(cellCounter,nPt));
1291
1292 }
1293
1294 L2err += worksetL2err(cellCounter);
1295 H1err += worksetH1err(cellCounter);
1296
1297 cellCounter++;
1298
1299 } // end cell loop
1300
1301 } // end loop over worksets
1302
1303 #ifdef HAVE_MPI
1304 // sum over all processors
1305 TC_sumAll(Comm,L2err,L2errTot);
1306 TC_sumAll(Comm,H1err,H1errTot);
1307 TC_maxAll(Comm,Linferr,LinferrTot);
1308 #else
1309 L2errTot = L2err;
1310 H1errTot = H1err;
1311 LinferrTot = Linferr;
1312 #endif
1313
1314
1315 if (MyPID == 0) {
1316 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
1317 std::cout << "H1 Error: " << sqrt(H1errTot) <<"\n";
1318 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
1319 }
1320
1321 const bool alwaysWriteLocal = false;
1322 const bool writeGlobalStats = true;
1323 const bool writeZeroTimers = false;
1324 const bool ignoreZeroTimers = true;
1325 const std::string filter = "";
1326 TimeMonitor::summarize(Comm.ptr(), std::cout, alwaysWriteLocal, writeGlobalStats,
1327 writeZeroTimers, Teuchos::Union, filter, ignoreZeroTimers);
1328
1329
1330 // Cleanup
1331 for(long long b = 0; b < numElemBlk; b++){
1332 delete [] elmt_node_linkage[b];
1333 delete [] element_types[b];
1334 }
1335 delete [] block_ids;
1336 delete [] nodes_per_element;
1337 delete [] element_attributes;
1338 delete [] element_types;
1339 delete [] elmt_node_linkage;
1340 delete [] elements;
1341 delete [] P1_globalNodeIds;
1342 delete [] P1_nodeIsOwned;
1343 if(num_node_comm_maps > 0){
1344 delete [] node_comm_proc_ids;
1345 delete [] node_cmap_node_cnts;
1346 delete [] node_cmap_ids;
1347 for(long long i=0;i<num_node_comm_maps;i++){
1348 delete [] comm_node_ids[i];
1349 delete [] comm_node_proc_ids[i];
1350 }
1351
1352 delete [] comm_node_ids;
1353 delete [] comm_node_proc_ids;
1354 }
1355
1356 delete [] nodeCoordx;
1357 delete [] nodeCoordy;
1358
1359 // delete mesh
1360 Delete_Pamgen_Mesh();
1361
1362 return 0;
1363
1364 }
1365 /**********************************************************************************/
1366 /********************************* END MAIN ***************************************/
1367 /**********************************************************************************/
1368
1369 /**********************************************************************************/
1370 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1371 /**********************************************************************************/
1372
1373 template<typename Scalar>
1374 const Scalar exactSolution(const Scalar& x, const Scalar& y) {
1375
1376 // Patch test: bi-linear function is in the FE space and should be recovered
1377 // return 1. + x + y + x*y;
1378
1379 // Analytic solution with homogeneous Dirichlet boundary data
1380 //return sin(M_PI*x)*sin(M_PI*y)**exp(x+y);
1381
1382 // Analytic solution with inhomogeneous Dirichlet boundary data
1383 return exp(x + y )/(1. + x*y);
1384 }
1385
1386
1387 template<typename Scalar>
1388 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y) {
1389
1390 material[0][0] = 1.;
1391 material[0][1] = 0.;
1392 //
1393 material[1][0] = 0.;
1394 material[1][1] = 1.;
1395 }
1396
1397 /**********************************************************************************/
1398 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1399 /**********************************************************************************/
1400
1401 /************ Grad of Exact Solution ****************/
1402 template<typename Scalar>
1403 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y) {
1404
1405 // To enable derivatives of the gradient (i.e., 2nd derivatives of the exact solution) need 2 levels of fad types
1406 Sacado::Fad::SFad<Scalar,2> fad_x = x;
1407 Sacado::Fad::SFad<Scalar,2> fad_y = y;
1408 Sacado::Fad::SFad<Scalar,2> u;
1409
1410 // Indicate the independent variables
1411 fad_x.diff(0,2);
1412 fad_y.diff(1,2);
1413
1414 u = exactSolution(fad_x, fad_y);
1415
1416 gradExact[0] = u.dx(0);
1417 gradExact[1] = u.dx(1);
1418 }
1419
1420 /************ Source Term (RHS) ****************/
1421 template<typename Scalar>
1422 const Scalar sourceTerm(Scalar& x, Scalar& y){
1423
1424 Scalar u;
1425 Scalar grad_u[2];
1426 Scalar flux[2] = {0.0, 0.0};
1427 Scalar material[2][2];
1428 Scalar f = 0.;
1429
1430 // Indicate the independent variables
1431 x.diff(0,2);
1432 y.diff(1,2);
1433
1434 // Get exact solution and its gradient
1435 u = exactSolution(x, y);
1436 exactSolutionGrad(grad_u, x, y);
1437
1438 // Get material tensor
1439 materialTensor<Scalar>(material, x, y);
1440
1441 // Compute total flux = (A.grad u)
1442 for(int i = 0; i < 2; i++){
1443
1444 // Add diffusive flux
1445 for(int j = 0; j < 2; j++){
1446 flux[i] += material[i][j]*grad_u[j];
1447 }
1448 }
1449
1450 // Compute source term (right hand side): f = -div(A.grad u)
1451 f = -(flux[0].dx(0) + flux[1].dx(1));
1452
1453 return f;
1454 }
1455
1456 /**********************************************************************************/
1457 /*************************** EVALUATION METHODS ***********************************/
1458 /**********************************************************************************/
1459
1460 /************ Material Tensor ****************/
1461 template<class ArrayOut, class ArrayIn>
1462 void evaluateMaterialTensor(ArrayOut & matTensorValues,
1463 const ArrayIn & evaluationPoints){
1464
1465 int numWorksetCells = evaluationPoints.dimension(0);
1466 int numPoints = evaluationPoints.dimension(1);
1467 int spaceDim = evaluationPoints.dimension(2);
1468
1469 double material[2][2];
1470
1471 for(int cell = 0; cell < numWorksetCells; cell++){
1472 for(int pt = 0; pt < numPoints; pt++){
1473
1474 double x = evaluationPoints(cell, pt, 0);
1475 double y = evaluationPoints(cell, pt, 1);
1476
1477 materialTensor<double>(material, x, y);
1478
1479 for(int row = 0; row < spaceDim; row++){
1480 for(int col = 0; col < spaceDim; col++){
1481 matTensorValues(cell, pt, row, col) = material[row][col];
1482 }
1483 }
1484 }
1485 }
1486 }
1487 /************ Source Term (RHS) ****************/
1488 template<class ArrayOut, class ArrayIn>
1489 void evaluateSourceTerm(ArrayOut & sourceTermValues,
1490 const ArrayIn & evaluationPoints){
1491
1492 int numWorksetCells = evaluationPoints.dimension(0);
1493 int numPoints = evaluationPoints.dimension(1);
1494
1495 for(int cell = 0; cell < numWorksetCells; cell++){
1496 for(int pt = 0; pt < numPoints; pt++){
1497
1498 Sacado::Fad::SFad<double,2> x = evaluationPoints(cell, pt, 0);
1499 Sacado::Fad::SFad<double,2> y = evaluationPoints(cell, pt, 1);
1500
1501 sourceTermValues(cell, pt) = sourceTerm<Sacado::Fad::SFad<double,2> >(x, y).val();
1502 }
1503 }
1504 }
1505
1506 /************ Exact Solution ****************/
1507 template<class ArrayOut, class ArrayIn>
1508 void evaluateExactSolution(ArrayOut & exactSolutionValues,
1509 const ArrayIn & evaluationPoints){
1510
1511 int numWorksetCells = evaluationPoints.dimension(0);
1512 int numPoints = evaluationPoints.dimension(1);
1513
1514 for(int cell = 0; cell < numWorksetCells; cell++){
1515 for(int pt = 0; pt < numPoints; pt++){
1516
1517 double x = evaluationPoints(cell, pt, 0);
1518 double y = evaluationPoints(cell, pt, 1);
1519
1520 exactSolutionValues(cell, pt) = exactSolution<double>(x, y);
1521 }
1522 }
1523 }
1524 /************ Grad of Exact Solution ****************/
1525 template<class ArrayOut, class ArrayIn>
1526 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
1527 const ArrayIn & evaluationPoints){
1528
1529 int numWorksetCells = evaluationPoints.dimension(0);
1530 int numPoints = evaluationPoints.dimension(1);
1531 int spaceDim = evaluationPoints.dimension(2);
1532
1533 double gradient[2];
1534
1535 for(int cell = 0; cell < numWorksetCells; cell++){
1536 for(int pt = 0; pt < numPoints; pt++){
1537
1538 double x = evaluationPoints(cell, pt, 0);
1539 double y = evaluationPoints(cell, pt, 1);
1540
1541 exactSolutionGrad<double>(gradient, x, y);
1542
1543 for(int row = 0; row < spaceDim; row++){
1544 exactSolutionGradValues(cell, pt, row) = gradient[row];
1545 }
1546 }
1547 }
1548 }
1549
1550 /**********************************************************************************/
1551 /******************************* TEST MueLu ***************************************/
1552 /**********************************************************************************/
1553
1554 // Test MueLu
1555 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
1556 ParameterList & amgList,
1557 RCP<crs_matrix_type> const &A0,
1558 RCP<crs_matrix_type> const &P0,
1559 RCP<crs_matrix_type> const &R0,
1560 RCP<multivector_type> const & xexact,
1561 RCP<multivector_type> & b,
1562 RCP<multivector_type> & uh,
1563 double & TotalErrorResidual,
1564 double & TotalErrorExactSol,
1565 std::string &amgType,
1566 std::string &solveType)
1567 {
1568 int mypid = A0->getComm()->getRank();
1569 int maxIts = 100;
1570 double tol =1e-10;
1571 RCP<multivector_type> x = rcp(new multivector_type(xexact->getMap(),1));
1572 if (amgList.isParameter("solve Ae=0")) {
1573 b->scale(0.0);
1574 x->randomize();
1575 }
1576
1577 linear_problem_type Problem(linear_problem_type(A0, x, b));
1578 RCP<multivector_type> lhs = Problem.getLHS();
1579 RCP<const multivector_type> rhs = Problem.getRHS();
1580
1581 RCP<TimeMonitor>
1582 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Total solve time")));
1583
1584 // ==================== //
1585 // call MueLu and Belos //
1586 // ==================== //
1587
1588 if (amgType != "ML" && amgType != "MueLu") {
1589 std::ostringstream errStr;
1590 errStr << "Error: \"amgType\" has value \"" << amgType << "\". Valid values are \"ML\" or \"MueLu\".";
1591 throw std::runtime_error(errStr.str());
1592 }
1593
1594 int numIterations=0;
1595 if (amgType == "ML") {
1596 throw std::runtime_error("Error: ML does not support Tpetra objects");
1597 } else if (amgType == "MueLu") {
1598 // Turns a Tpetra::CrsMatrix into a MueLu::Matrix
1599 RCP<Xpetra::Matrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>> mueluA = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(A0);
1600 // Multigrid Hierarchy
1601 crs_matrix_type * A1;
1602 RCP<Xpetra::Matrix <scalar_type, local_ordinal_type, global_ordinal_type> > xA1;
1603 bool userCoarseA = false;
1604 if (amgList.isParameter("user coarse matrix")) {
1605 A1=amgList.get<crs_matrix_type*>("user coarse matrix");
1606 xA1 = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(rcpFromRef(*A1));
1607 amgList.remove("user coarse matrix");
1608 userCoarseA = true;
1609 }
1610 MueLu::ParameterListInterpreter<scalar_type,local_ordinal_type,global_ordinal_type> mueLuFactory(amgList);
1611 RCP<MueLu::Hierarchy<scalar_type,local_ordinal_type,global_ordinal_type> > H = mueLuFactory.CreateHierarchy();
1612 H->setVerbLevel(Teuchos::VERB_HIGH);
1613 H->GetLevel(0)->Set("A", mueluA);
1614 MueLu::FactoryManager<scalar_type,local_ordinal_type,global_ordinal_type,NO> M1, M2;
1615 if (P0 != Teuchos::null) {
1616 H->AddNewLevel();
1617 RCP<Xpetra::Matrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>> xP0 = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(P0);
1618 H->GetLevel(1)->AddKeepFlag("P",MueLu::NoFactory::get(),MueLu::UserData);
1619 H->GetLevel(1)->Set("P", xP0);
1620 RCP<Xpetra::Matrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>> xR0 = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type,local_ordinal_type,global_ordinal_type,NO>(R0);
1621 H->GetLevel(1)->AddKeepFlag("R",MueLu::NoFactory::get(),MueLu::UserData);
1622 H->GetLevel(1)->Set("R", xR0);
1623 if (mypid==0) std::cout << ">>>>>>>>>>>>>>>>>>>>> "
1624 << "adding P0 to AMG hierarchy" << std::endl;
1625 }
1626 RCP<multivector_type> nullspace;
1627 if (userCoarseA) {
1628 H->GetLevel(1)->AddKeepFlag("A",MueLu::NoFactory::get(),MueLu::UserData);
1629 H->GetLevel(1)->AddKeepFlag("Nullspace",MueLu::NoFactory::get(),MueLu::UserData);
1630 H->GetLevel(1)->Set("A", xA1);
1631 if (mypid==0) std::cout << ">>>>>>>>>>>>>>>>>>>>> "
1632 << "adding coarse auxiliary matrix to AMG hierarchy" << std::endl;
1633 // create nullspace for Level 1 (first coarse AMG level)
1634 nullspace = rcp(new multivector_type(xexact->getMap(),1));
1635 ArrayRCP<scalar_type> data = nullspace->getDataNonConst(0);
1636 for (int i=0; i<data.size(); ++i)
1637 data[i] = 1.0;
1638 data = Teuchos::null;
1639 RCP<Xpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO>> xnullspace = MueLu::TpetraMultiVector_To_XpetraMultiVector<scalar_type,local_ordinal_type,global_ordinal_type,NO>(nullspace);
1640 H->GetLevel(1)->Set("Nullspace", xnullspace);
1641 }
1642 // Multigrid setup phase
1643 mueLuFactory.SetupHierarchy(*H);
1644 //copied directly from MueLu's blockReader.cpp
1645
1646 H->IsPreconditioner(true);
1647 RCP<muelu_tpetra_operator> M = rcp(new muelu_tpetra_operator(H));
1648
1649 Problem.setRightPrec(M);
1650
1651 bool set = Problem.setProblem();
1652 if (set == false) {
1653 std::cout << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
1654 return EXIT_FAILURE;
1655 }
1656
1657 // Belos parameter list
1658 ParameterList belosList;
1659 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
1660 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
1661 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
1662 belosList.set("Output Frequency", 1);
1663 belosList.set("Output Style", Belos::Brief);
1664 //if (!scaleResidualHist)
1665 belosList.set("Implicit Residual Scaling", "None");
1666
1667 // Create an iterative solver manager
1668 RCP< Belos::SolverManager<scalar_type, multivector_type, operator_type> > solver;
1669 if(solveType == "cg")
1670 solver = rcp(new Belos::PseudoBlockCGSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
1671 else if (solveType == "gmres") {
1672 solver = rcp(new Belos::PseudoBlockGmresSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
1673 }
1674 else if (solveType == "fixed point" || solveType == "fixed-point") {
1675 solver = rcp(new Belos::FixedPointSolMgr<scalar_type, multivector_type, operator_type>(rcpFromRef(Problem), rcp(&belosList, false)));
1676 }
1677 else {
1678 std::cout << "\nERROR: Invalid solver '"<<solveType<<"'" << std::endl;
1679 return EXIT_FAILURE;
1680 }
1681
1682 // Perform solve
1683 solver->solve();
1684 //writer_type::writeDenseFile("sol.m", x);
1685 numIterations = solver->getNumIters();
1686 }
1687
1688 uh = lhs;
1689
1690 ArrayRCP<const scalar_type> lhsdata = lhs->getData(0);
1691 ArrayRCP<const scalar_type> xexactdata = xexact->getData(0);
1692 // ======================================================= //
1693 // compute difference between exact solution and MueLu one //
1694 // ======================================================= //
1695 double d = 0.0, d_tot = 0.0 , s =0.0, s_tot=0.0;
1696 //for( int i=0 ; i<lhs->Map().NumMyElements() ; ++i ) {
1697 for( size_t i=0 ; i<lhs->getMap()->getLocalNumElements() ; ++i ) {
1698 d += (lhsdata[i] - xexactdata[i]) * (lhsdata[i] - xexactdata[i]);
1699 s += xexactdata[i]* xexactdata[i];
1700 }
1701 lhsdata = Teuchos::null;
1702 xexactdata = Teuchos::null;
1703
1704 TC_sumAll(A0->getComm(),d,d_tot);
1705 TC_sumAll(A0->getComm(),s,s_tot);
1706
1707 // ================== //
1708 // compute ||Ax - b|| //
1709 // ================== //
1710 Array<typename ScalarTraits::magnitudeType> Norm(1);
1711 vector_type Ax(rhs->getMap());
1712 A0->apply(*lhs, Ax);
1713 Ax.update(1.0, *rhs, -1.0);
1714 Ax.norm2(Norm);
1715
1716 string msg = ProblemType;
1717
1718 int numProc = A0->getComm()->getSize();
1719 if (A0->getComm()->getRank() == 0) {
1720 cout << msg << endl << "......Using " << numProc << " processes" << endl;
1721 cout << msg << "......||A x - b||_2 = " << Norm[0] << endl;
1722 cout << msg << "......||x_exact - x||_2/||x_exact||_2 = " << sqrt(d_tot/s_tot) << endl;
1723 }
1724
1725 TotalErrorExactSol += sqrt(d_tot);
1726 TotalErrorResidual += Norm[0];
1727
1728 return(numIterations);
1729
1730 }
1731
1732 /*********************************************************************************************************/
1733 /*********************************************************************************************************/
1734 /*********************************************************************************************************/
1735
1736
1737 void GenerateEdgeEnumeration(const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, FieldContainer<int> & elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<double> & edgeCoord) {
1738 // Not especially efficient, but effective... at least in serial!
1739
1740 int numElems = elemToNode.dimension(0);
1741 int numNodesperElem = elemToNode.dimension(1);
1742 int dim = nodeCoord.dimension(1);
1743
1744 // Sanity checks
1745 if(numNodesperElem !=4) throw std::runtime_error("Error: GenerateEdgeEnumeration only works on Quads!");
1746 if(elemToEdge.dimension(0)!=numElems || elemToEdge.dimension(1)!=4 || elemToEdge.dimension(0)!=elemToEdgeOrient.dimension(0) || elemToEdge.dimension(1)!=elemToEdgeOrient.dimension(1))
1747 throw std::runtime_error("Error: GenerateEdgeEnumeration array size mismatch");
1748
1749 int edge_node0_id[4]={0,1,2,3};
1750 int edge_node1_id[4]={1,2,3,0};
1751
1752 // Run over all the elements and start enumerating edges
1753 typedef std::map<std::pair<int,int>,int> en_map_type;
1754 en_map_type e2n;
1755
1756 int num_edges=0;
1757 en_map_type edge_map;
1758 for(int i=0; i<numElems; i++) {
1759
1760 // Generate edge pairs, based on the global orientation of "edges go from low ID to high ID"
1761 for(int j=0; j<4; j++) {
1762 int lo = std::min(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
1763 int hi = std::max(elemToNode(i,edge_node0_id[j]),elemToNode(i,edge_node1_id[j]));
1764
1765 std::pair<int,int> ep(lo,hi);
1766
1767 int edge_id;
1768 en_map_type::iterator iter = edge_map.find(ep);
1769 if(iter==edge_map.end()) {
1770 edge_map[ep] = num_edges;
1771 edge_id = num_edges;
1772 num_edges++;
1773 }
1774 else
1775 edge_id = (*iter).second;
1776
1777 elemToEdge(i,j) = edge_id;
1778 elemToEdgeOrient(i,j) = (lo==elemToNode(i,edge_node0_id[j]))?1:-1;
1779 }
1780 }
1781
1782 // Fill out the edge centers (clobbering data if needed)
1783 edgeCoord.resize(num_edges,dim);
1784 for(int i=0; i<numElems; i++) {
1785 for(int j=0; j<4; j++) {
1786 int n0 = elemToNode(i,edge_node0_id[j]);
1787 int n1 = elemToNode(i,edge_node1_id[j]);
1788 for(int k=0; k<dim; k++)
1789 edgeCoord(elemToEdge(i,j),k) = (nodeCoord(n0,k)+nodeCoord(n1,k))/2.0;
1790 }
1791 }
1792
1793 }
1794
1795 /*********************************************************************************************************/
1796
1797 void PromoteMesh(const int degree,
1798 const FieldContainer<int> & P1_elemToNode,
1799 const FieldContainer<double> & P1_nodeCoord,
1800 const FieldContainer<double> & P1_edgeCoord,
1801 const FieldContainer<int> & P1_elemToEdge,
1802 const FieldContainer<int> & P1_elemToEdgeOrient,
1803 const FieldContainer<int> & P1_nodeOnBoundary,
1804 FieldContainer<int> & P2_elemToNode,
1805 FieldContainer<double> & P2_nodeCoord,
1806 FieldContainer<int> & P2_nodeOnBoundary,
1807 std::vector<int> & P2_edgeNodes,
1808 std::vector<int> & P2_cellNodes) {
1809
1810 int numElems = P1_elemToNode.dimension(0);
1811 int P1_numNodesperElem = P1_elemToNode.dimension(1);
1812 int P1_numEdgesperElem = P1_elemToEdge.dimension(1);
1813 int P2_numNodesperElem = P2_elemToNode.dimension(1);
1814 int P1_numNodes = P1_nodeCoord.dimension(0);
1815 int P1_numEdges = P1_edgeCoord.dimension(0);
1816 int dim = P1_nodeCoord.dimension(1);
1817
1818
1819 // Sanity checks
1820 if(P1_numNodesperElem !=4 || P2_numNodesperElem !=9 ) throw std::runtime_error("Error: GenerateEdgeEnumeration only works on Quads!");
1821 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) ||
1822 P2_elemToNode.dimension(0)!=numElems || P2_nodeCoord.dimension(0) != P1_numNodes+P1_numEdges+numElems)
1823 throw std::runtime_error("Error: GenerateEdgeEnumeration array size mismatch");
1824
1825 /*Quad-9 Layout:
1826 inode3 -- inode6 -- inode2
1827 | |
1828 inode7 inode8 inode5
1829 | |
1830 inode0 -- inode4 -- inode1
1831 */
1832 // Make the new el2node array
1833 for(int i=0; i<numElems; i++) {
1834 // P1 nodes
1835 for(int j=0; j<P1_numNodesperElem; j++)
1836 P2_elemToNode(i,j) = P1_elemToNode(i,j);
1837
1838 // P1 edges
1839 for(int j=0; j<P1_numEdgesperElem; j++) {
1840 P2_elemToNode(i,P1_numNodesperElem+j) = P1_numNodes+P1_elemToEdge(i,j);
1841 P2_edgeNodes.push_back(P1_numNodes+P1_elemToEdge(i,j));
1842 }
1843
1844 // P1 cells
1845 P2_elemToNode(i,P1_numNodesperElem+P1_numEdgesperElem) = P1_numNodes+P1_numEdges+i;
1846 P2_cellNodes.push_back(P1_numNodes+P1_numEdges+i);
1847
1848 }
1849
1850 // Make the new coordinates
1851 // P1 nodes
1852 for(int i=0; i<P1_numNodes; i++)
1853 for(int j=0; j<dim; j++)
1854 P2_nodeCoord(i,j) = P1_nodeCoord(i,j);
1855
1856 // P1 edges
1857 for(int i=0; i<P1_numEdges; i++)
1858 for(int j=0; j<dim; j++)
1859 P2_nodeCoord(P1_numNodes+i,j) = P1_edgeCoord(i,j);
1860
1861 // P1 cells
1862 for(int i=0; i<numElems; i++)
1863 for(int j=0; j<dim; j++) {
1864 P2_nodeCoord(P1_numNodes+P1_numEdges+i,j) =0;
1865 for(int k=0; k<P1_numNodesperElem; k++)
1866 P2_nodeCoord(P1_numNodes+P1_numEdges+i,j) += P1_nodeCoord(P1_elemToNode(i,k),j) / P1_numNodesperElem;
1867 }
1868
1869
1870
1871 // Update the boundary conditions
1872 int edge_node0_id[4]={0,1,2,3};
1873 int edge_node1_id[4]={1,2,3,0};
1874
1875 // P1 nodes
1876 for(int i=0; i<P1_numNodes; i++)
1877 P2_nodeOnBoundary(i) = P1_nodeOnBoundary(i);
1878
1879
1880 // P1 edges
1881 // Not all that efficient
1882 for(int i=0; i<numElems; i++) {
1883 for(int j=0; j<P1_numEdgesperElem; j++) {
1884 int P1_edge = P1_elemToEdge(i,j);
1885 int n0 = P1_elemToNode(i,edge_node0_id[j]);
1886 int n1 = P1_elemToNode(i,edge_node1_id[j]);
1887
1888 if(P1_nodeOnBoundary(n0) && P2_nodeOnBoundary(n1))
1889 P2_nodeOnBoundary(P1_numNodes+P1_edge) = 1;
1890 }
1891 }
1892 }
1893
1894 /*********************************************************************************************************/
1895
1896 void CreateP1MeshFromP2Mesh(
1897 FieldContainer<int> const & P2_elemToNode,
1898 FieldContainer<int> & P1_elemToNode)
1899 {
1900
1901 /*
1902 Main idea:
1903 For each P2 element
1904 Create four P1 elements
1905 For each of those P1 elements
1906 Create element to node map
1907 */
1908
1909 int P2_numElems = P2_elemToNode.dimension(0);
1910
1911 int p1ElemCtr=0;
1912 for (int i=0; i<P2_numElems; ++i) {
1913
1914 /*
1915 How "P1" elements are traversed in a P2 element
1916
1917 inode3 -- inode6 -- inode2
1918
1919 | 3 | 2 |
1920
1921 inode7 -- inode8 -- inode5
1922
1923 | 0 | 1 |
1924
1925 inode0 -- inode4 -- inode1
1926 */
1927
1928 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,0);
1929 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,4);
1930 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,8);
1931 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,7);
1932
1933 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,4);
1934 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,1);
1935 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,5);
1936 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,8);
1937
1938 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,8);
1939 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,5);
1940 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,2);
1941 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,6);
1942
1943 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,7);
1944 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,8);
1945 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,6);
1946 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,3);
1947
1948 }
1949 } //CreateP1MeshFromP2Mesh
1950
1951 /*********************************************************************************************************/
1952
1953 void CreateLinearSystem(int numWorksets,
1954 int desiredWorksetSize,
1955 FieldContainer<int> const &elemToNode,
1956 FieldContainer<double> const &nodeCoord,
1957 FieldContainer<double> const &cubPoints,
1958 FieldContainer<double> const &cubWeights,
1959 FieldContainer<double> const &HGBGrads,
1960 FieldContainer<double> const &HGBValues,
1961 std::vector<global_ordinal_type> const &globalNodeIds,
1962 shards::CellTopology const &cellType,
1963 crs_matrix_type &StiffMatrix,
1964 RCP<multivector_type> &rhsVector,
1965 std::string &msg
1966 )
1967 {
1968 int numCubPoints = cubPoints.dimension(0);
1969 int cubDim = cubPoints.dimension(1);
1970 int spaceDim = cellType.getDimension();
1971 int numFieldsG = HGBGrads.dimension(0);
1972 long long numElems = elemToNode.dimension(0);
1973 int numNodesPerElem = cellType.getNodeCount();
1974
1975
1976 std::cout << "CreateLinearSystem:" << std::endl;
1977 std::cout << " numCubPoints = " << numCubPoints << std::endl;
1978 std::cout << " cubDim = " << cubDim << std::endl;
1979 std::cout << " spaceDim = " << spaceDim << std::endl;
1980 std::cout << " numFieldsG = " << numFieldsG << std::endl;
1981 std::cout << " numElems = " << numElems << std::endl;
1982 std::cout << " numNodesPerElem = " << numNodesPerElem << std::endl;
1983 std::cout << " length(globalNodeIds) = " << globalNodeIds.size() << std::endl;
1984 std::cout << " length(nodeCoord) = " << nodeCoord.dimension(0) << std::endl;
1985
1986
1987 if(nodeCoord.dimension(0) != Teuchos::as<int>(globalNodeIds.size())) {
1988 std::ostringstream errStr;
1989 errStr << "Error: CreateLinearSystem: length of coordinates != #nodes ("
1990 << nodeCoord.dimension(0) << "!=" << globalNodeIds.size() << ")";
1991 throw std::runtime_error(errStr.str());
1992 }
1993
1994 for(int workset = 0; workset < numWorksets; workset++){
1995
1996 // Compute cell numbers where the workset starts and ends
1997 int worksetSize = 0;
1998 int worksetBegin = (workset + 0)*desiredWorksetSize;
1999 int worksetEnd = (workset + 1)*desiredWorksetSize;
2000
2001 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
2002 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
2003
2004 // Now we know the actual workset size and can allocate the array for the cell nodes
2005 worksetSize = worksetEnd - worksetBegin;
2006 //std::cout << " cellWorkset: begin=" << worksetBegin << ", end=" << worksetEnd
2007 // << ", size=" << worksetSize << std::endl;
2008 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
2009
2010 // Copy coordinates into cell workset
2011 int cellCounter = 0;
2012 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2013 for (int node = 0; node < numNodesPerElem; node++) {
2014 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
2015 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
2016 }
2017 cellCounter++;
2018 }
2019
2020 /**********************************************************************************/
2021 /* Allocate arrays */
2022 /**********************************************************************************/
2023
2024 // Containers for Jacobians, integration measure & cubature points in workset cells
2025 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
2026 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
2027 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
2028 FieldContainer<double> worksetCubWeights(worksetSize, numCubPoints);
2029 FieldContainer<double> worksetCubPoints (worksetSize, numCubPoints, cubDim);
2030
2031 // Containers for basis values transformed to workset cells and them multiplied by cubature weights
2032 FieldContainer<double> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
2033 FieldContainer<double> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
2034 FieldContainer<double> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
2035 FieldContainer<double> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
2036
2037 // Containers for diffusive & advective fluxes & non-conservative adv. term and reactive terms
2038 FieldContainer<double> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
2039
2040 // Containers for material values and source term. Require user-defined functions
2041 FieldContainer<double> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
2042 FieldContainer<double> worksetSourceTerm (worksetSize, numCubPoints);
2043
2044 // Containers for workset contributions to the discretization matrix and the right hand side
2045 FieldContainer<double> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
2046 FieldContainer<double> worksetRHS (worksetSize, numFieldsG);
2047
2048
2049 /**********************************************************************************/
2050 /* Calculate Jacobians */
2051 /**********************************************************************************/
2052
2053 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
2054 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
2055 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
2056
2057 /**********************************************************************************/
2058 /* Cubature Points to Physical Frame and Compute Data */
2059 /**********************************************************************************/
2060
2061 // map cubature points to physical frame
2062 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, cellType);
2063
2064 // get A at cubature points
2065 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
2066
2067 // get source term at cubature points
2068 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
2069
2070
2071 /**********************************************************************************/
2072 /* Compute Stiffness Matrix */
2073 /**********************************************************************************/
2074
2075 // Transform basis gradients to physical frame:
2076 IntrepidFSTools::HGRADtransformGRAD<double>(worksetHGBGrads, // DF^{-T}(grad u)
2077 worksetJacobInv, HGBGrads);
2078
2079 // Compute integration measure for workset cells:
2080 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeights, // Det(DF)*w = J*w
2081 worksetJacobDet, cubWeights);
2082
2083
2084 // Multiply transformed (workset) gradients with weighted measure
2085 IntrepidFSTools::multiplyMeasure<double>(worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
2086 worksetCubWeights, worksetHGBGrads);
2087
2088
2089 // Compute the diffusive flux:
2090 IntrepidFSTools::tensorMultiplyDataField<double>(worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
2091 worksetMaterialVals,
2092 worksetHGBGrads);
2093
2094 // Integrate to compute workset diffusion contribution to global matrix:
2095 IntrepidFSTools::integrate<double>(worksetStiffMatrix, //(DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
2096 worksetHGBGradsWeighted,
2097 worksetDiffusiveFlux, COMP_BLAS);
2098
2099 /**********************************************************************************/
2100 /* Compute RHS */
2101 /**********************************************************************************/
2102
2103 // Transform basis values to physical frame:
2104 IntrepidFSTools::HGRADtransformVALUE<double>(worksetHGBValues, // clones basis values (u)
2105 HGBValues);
2106
2107 // Multiply transformed (workset) values with weighted measure
2108 IntrepidFSTools::multiplyMeasure<double>(worksetHGBValuesWeighted, // (u)*J*w
2109 worksetCubWeights, worksetHGBValues);
2110
2111 // Integrate worksetSourceTerm against weighted basis function set
2112 IntrepidFSTools::integrate<double>(worksetRHS, // f.(u)*J*w
2113 worksetSourceTerm,
2114 worksetHGBValuesWeighted, COMP_BLAS);
2115
2116 /**********************************************************************************/
2117 /* Assemble into Global Matrix and RHS */
2118 /**********************************************************************************/
2119
2120 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
2121
2122 Array<scalar_type> vals1(1);
2123 Array<global_ordinal_type> cols1(1);
2124 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2125
2126 // Compute cell ordinal relative to the current workset
2127 int worksetCellOrdinal = cell - worksetBegin;
2128
2129 // "CELL EQUATION" loop for the workset cell: cellRow is relative to the cell DoF numbering
2130 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
2131
2132 int localRow = elemToNode(cell, cellRow);
2133 int globalRow = globalNodeIds[localRow];
2134 double sourceTermContribution = worksetRHS(worksetCellOrdinal, cellRow);
2135
2136 //rhsVector.sumIntoGlobalValue(globalRow, 0, sourceTermContribution);
2137 rhsVector->sumIntoGlobalValue(globalRow, 0, sourceTermContribution);
2138
2139 // "CELL VARIABLE" loop for the workset cell: cellCol is relative to the cell DoF numbering
2140 for (int cellCol = 0; cellCol < numFieldsG; cellCol++){
2141
2142 int localCol = elemToNode(cell, cellCol);
2143 int globalCol = globalNodeIds[localCol];
2144 double operatorMatrixContribution = worksetStiffMatrix(worksetCellOrdinal, cellRow, cellCol);
2145 cols1[0] = globalCol;
2146 vals1[0] = operatorMatrixContribution;
2147 StiffMatrix.insertGlobalValues(globalRow, cols1(), vals1());
2148
2149 }// *** cell col loop ***
2150 }// *** cell row loop ***
2151 }// *** workset cell loop **
2152
2153 }// *** workset loop ***
2154
2155 } //CreateLinearSystem
2156
2157 /*********************************************************************************************************/
2158 void GenerateLinearCoarsening_p2_to_p1(const FieldContainer<int> & P2_elemToNode, RCP<driver_map_type> &P1_map, RCP<driver_map_type> & P2_map,RCP<crs_matrix_type>& P) {
2159
2160 // Generate a P matrix that uses the linear coarsening from p2 to p1 on the base mesh.
2161 // This presumes that the P2 element has all of the P1 nodes numbered first
2162 // Resulting matrix is #P2nodes x #P1nodes
2163 double one = 1.0;
2164 double half = 0.5;
2165 double quarter = 0.25;
2166 int edge_node0_id[4]={0,1,2,3};
2167 int edge_node1_id[4]={1,2,3,0};
2168
2169 int Nelem=P2_elemToNode.dimension(0);
2170 if(P2_elemToNode.dimension(1) != 9) throw std::runtime_error("Unidentified element type");
2171
2172 P = rcp(new crs_matrix_type(P2_map,0));
2173
2174 Array<scalar_type> vals1(1);
2175 Array<global_ordinal_type> cols1(1);
2176 Array<scalar_type> vals2(2);
2177 Array<global_ordinal_type> cols2(2);
2178 Array<scalar_type> vals4(4);
2179 Array<global_ordinal_type> cols4(4);
2180
2181 for(int i=0; i<Nelem; i++)
2182 for(int j=0; j<P2_elemToNode.dimension(1); j++) {
2183 int row = P2_elemToNode(i,j);
2184
2185 if(j<4) {
2186 vals1[0] = one; cols1[0] = row;
2187 P->insertGlobalValues(row,cols1(),vals1());
2188 }
2189 else if (j>=4 && j<8){
2190 int col0 = P2_elemToNode(i,edge_node0_id[j-4]);
2191 int col1 = P2_elemToNode(i,edge_node1_id[j-4]);
2192 vals2[0] = half; vals2[1] = half;
2193 cols2[0] = col0; cols2[1] = col1;
2194 P->insertGlobalValues(row,cols2(),vals2());
2195 }
2196 else {
2197 cols4[0] = P2_elemToNode(i,0); cols4[1] = P2_elemToNode(i,1);
2198 cols4[2] = P2_elemToNode(i,2); cols4[3] = P2_elemToNode(i,3);
2199 vals4[0] = quarter; vals4[1] = quarter;
2200 vals4[2] = quarter; vals4[3] = quarter;
2201 P->insertGlobalValues(row,cols4(),vals4());
2202 }
2203 }
2204 P->fillComplete(P1_map,P2_map);
2205 }
2206
2207 /*********************************************************************************************************/
2208 void GenerateIdentityCoarsening_p2_to_p1(const FieldContainer<int> & P2_elemToNode,
2209 const FieldContainer<int> & P1_elemToNode,
2210 RCP<const driver_map_type> const & P1_map_aux, RCP<const driver_map_type> const &P2_map,
2211 RCP<crs_matrix_type> & P,
2212 RCP<crs_matrix_type> & R) {
2213
2214 // Generate prolongator matrix that will be used to transfer from P1 on auxiliary mesh to P2 on base mesh.
2215 // It's just the identity matrix.
2216 // By construction, the node numbering on the P1 auxiliary mesh is the same as on the P2 base mesh
2217 // (see CreateP1MeshFromP2Mesh). The P2 map is the range map, the P1 auxiliary map is the domain map.
2218
2219 double one = 1.0;
2220 P = rcp(new crs_matrix_type(P2_map,1));
2221
2222 //We must keep track of the nodes already encountered. Inserting more than once will cause
2223 //the values to be summed. Using a hashtable would work -- we abuse std::map for this purpose.
2224 std::map<int,int> hashTable;
2225 int Nelem=P2_elemToNode.dimension(0);
2226 Array<scalar_type> vals1(1);
2227 vals1[0] = one;
2228 Array<global_ordinal_type> cols1(1);
2229 for(int i=0; i<Nelem; i++) {
2230 for(int j=0; j<P2_elemToNode.dimension(1); j++) {
2231 int row = P2_elemToNode(i,j);
2232 if (hashTable.find(row) == hashTable.end()) {
2233 //not found
2234 cols1[0] = row;
2235 P->insertGlobalValues(row,cols1(),vals1());
2236 hashTable[row] = 1;
2237 }
2238 }
2239 }
2240 P->fillComplete(P1_map_aux,P2_map);
2241
2242 hashTable.clear();
2243 R = rcp(new crs_matrix_type(P1_map_aux,1));
2244 Nelem = P1_elemToNode.dimension(0);
2245 int nodesPerElem = P1_elemToNode.dimension(1);
2246 for(int i=0; i<Nelem; ++i) {
2247 for(int j=0; j<nodesPerElem; ++j) {
2248 int row = P1_elemToNode(i,j);
2249 if (hashTable.find(row) == hashTable.end()) {
2250 //not found
2251 cols1[0] = row;
2252 R->insertGlobalValues(row,cols1(),vals1());
2253 hashTable[row] = 1;
2254 }
2255 }
2256 }
2257 R->fillComplete(P2_map,P1_map_aux);
2258 }
2259
2260 /*********************************************************************************************************/
2261 void Apply_Dirichlet_BCs(std::vector<int> &BCNodes, crs_matrix_type & A, multivector_type & x, multivector_type & b,
2262 const multivector_type & soln) {
2263 int N=(int)BCNodes.size();
2264 ArrayRCP<scalar_type> xdata = x.getDataNonConst(0);
2265 ArrayRCP<scalar_type> bdata = b.getDataNonConst(0);
2266 ArrayRCP<const scalar_type> solndata = soln.getData(0);
2267
2268 A.resumeFill();
2269
2270 for(int i=0; i<N; i++) {
2271 local_ordinal_type lrid = BCNodes[i];
2272
2273 xdata[lrid]=bdata[lrid] = solndata[lrid];
2274
2275 size_t numEntriesInRow = A.getNumEntriesInLocalRow(lrid); typename crs_matrix_type::nonconst_local_inds_host_view_type cols("cols", numEntriesInRow);
2276 typename crs_matrix_type::nonconst_values_host_view_type vals("vals", numEntriesInRow);
2277 A.getLocalRowCopy(lrid, cols, vals, numEntriesInRow);
2278
2279 for(size_t j=0; j<vals.extent(0); j++)
2280 vals(j) = (cols(j) == lrid) ? 1.0 : 0.0;
2281
2282 A.replaceLocalValues(lrid, cols, vals);
2283 }
2284
2285 A.fillComplete();
2286
2287 }