Debian Codegraph @

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