Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_Poisson2D.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
138 /**********************************************************************************/
139 /***************** FUNCTION DECLARATION FOR ML PRECONDITIONER *********************/
140 /**********************************************************************************/
141
142 /** \brief ML Preconditioner
143
144 \param ProblemType [in] problem type
145 \param MLList [in] ML parameter list
146 \param A [in] discrete operator matrix
147 \param xexact [in] exact solution
148 \param b [in] right-hand-side vector
149 \param uh [out] solution vector
150 \param TotalErrorResidual [out] error residual
151 \param TotalErrorExactSol [out] error in uh
152
153 */
154 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
155 Teuchos::ParameterList & MLList,
156 Epetra_CrsMatrix & A,
157 const Epetra_MultiVector & xexact,
158 Epetra_MultiVector & b,
159 Epetra_MultiVector & uh,
160 double & TotalErrorResidual,
161 double & TotalErrorExactSol);
162
163
164
165 /**********************************************************************************/
166 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
167 /**********************************************************************************/
168
169 /** \brief User-defined exact solution.
170
171 \param x [in] x-coordinate of the evaluation point
172 \param y [in] y-coordinate of the evaluation point
173
174 \return Value of the exact solution at (x,y)
175 */
176 template<typename Scalar>
177 const Scalar exactSolution(const Scalar& x, const Scalar& y);
178
179 /** \brief User-defined material tensor.
180
181 \param material [out] 3 x 3 material tensor evaluated at (x,y)
182 \param x [in] x-coordinate of the evaluation point
183 \param y [in] y-coordinate of the evaluation point
184
185 \warning Symmetric and positive definite tensor is required for every (x,y).
186 */
187 template<typename Scalar>
188 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y);
189
190 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
191
192 \param gradExact [out] gradient of the exact solution evaluated at (x,y)
193 \param x [in] x-coordinate of the evaluation point
194 \param y [in] y-coordinate of the evaluation point
195 */
196 template<typename Scalar>
197 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y);
198
199
200 /** \brief Computes source term: f = -div(A.grad u). Requires user-defined exact solution
201 and material tensor.
202
203 \param x [in] x-coordinate of the evaluation point
204 \param y [in] y-coordinate of the evaluation point
205
206 \return Source term corresponding to the user-defined exact solution evaluated at (x,y)
207 */
208 template<typename Scalar>
209 const Scalar sourceTerm(Scalar& x, Scalar& y);
210
211
212 /** \brief Computation of the material tensor at array of points in physical space.
213
214 \param worksetMaterialValues [out] Rank-2, 3 or 4 array with dimensions (C,P), (C,P,D) or (C,P,D,D)
215 with the values of the material tensor
216 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
217 */
218 template<class ArrayOut, class ArrayIn>
219 void evaluateMaterialTensor(ArrayOut & worksetMaterialValues,
220 const ArrayIn & evaluationPoints);
221
222
223 /** \brief Computation of the source term at array of points in physical space.
224
225 \param sourceTermValues [out] Rank-2 (C,P) array with the values of the source term
226 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
227 */
228 template<class ArrayOut, class ArrayIn>
229 void evaluateSourceTerm(ArrayOut & sourceTermValues,
230 const ArrayIn & evaluationPoints);
231
232 /** \brief Computation of the exact solution at array of points in physical space.
233
234 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
235 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
236 */
237 template<class ArrayOut, class ArrayIn>
238 void evaluateExactSolution(ArrayOut & exactSolutionValues,
239 const ArrayIn & evaluationPoints);
240
241
242 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
243
244 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
245 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
246 */
247 template<class ArrayOut, class ArrayIn>
248 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
249 const ArrayIn & evaluationPoints);
250
251
252 /**********************************************************************************/
253 /******************************** MAIN ********************************************/
254 /**********************************************************************************/
255
256 int main(int argc, char *argv[]) {
257
258 int error = 0;
259 int numProcs=1;
260 int rank=0;
261
262 #ifdef HAVE_MPI
263 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
264 rank=mpiSession.getRank();
265 numProcs=mpiSession.getNProc();
266 Epetra_MpiComm Comm(MPI_COMM_WORLD);
267 #else
268 Epetra_SerialComm Comm;
269 #endif
270
271 int MyPID = Comm.MyPID();
272 Epetra_Time Time(Comm);
273
274 //Check number of arguments
275 if (argc > 3) {
276 std::cout <<"\n>>> ERROR: Invalid number of arguments.\n\n";
277 std::cout <<"Usage:\n\n";
278 std::cout <<" ./TrilinosCouplings_examples_scaling_Example_Poisson.exe [meshfile.xml] [solver.xml]\n\n";
279 std::cout <<" meshfile.xml(optional) - xml file with description of Pamgen mesh\n\n";
280 std::cout <<" solver.xml(optional) - xml file with ML solver options\n\n";
281 exit(1);
282 }
283
284 if (MyPID == 0){
285 std::cout \
286 << "===============================================================================\n" \
287 << "| |\n" \
288 << "| Example: Solve Poisson Equation on Hexahedral Mesh |\n" \
289 << "| |\n" \
290 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
291 << "| Denis Ridzal ([email protected]), |\n" \
292 << "| Kara Peterson ([email protected]). |\n" \
293 << "| |\n" \
294 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
295 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
296 << "| ML's website: http://trilinos.sandia.gov/packages/ml |\n" \
297 << "| Isorropia's website: http://trilinos.sandia.gov/packages/isorropia |\n" \
298 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
299 << "| |\n" \
300 << "===============================================================================\n";
301 }
302
303
304 #ifdef HAVE_MPI
305 if (MyPID == 0) {
306 std::cout << "PARALLEL executable \n";
307 }
308 #else
309 if (MyPID == 0) {
310 std::cout << "SERIAL executable \n";
311 }
312 #endif
313
314 /**********************************************************************************/
315 /********************************** GET XML INPUTS ********************************/
316 /**********************************************************************************/
317
318 // Command line for xml file, otherwise use default
319 std::string xmlMeshInFileName, xmlSolverInFileName;
320 if(argc>=2) xmlMeshInFileName=string(argv[1]);
321 else xmlMeshInFileName="Poisson2D.xml";
322 if(argc>=3) xmlSolverInFileName=string(argv[2]);
323
324 // Read xml file into parameter list
325 Teuchos::ParameterList inputMeshList;
326 Teuchos::ParameterList inputSolverList;
327
328 if(xmlMeshInFileName.length()) {
329 if (MyPID == 0) {
330 std::cout << "\nReading parameter list from the XML file \""<<xmlMeshInFileName<<"\" ...\n\n";
331 }
332 Teuchos::updateParametersFromXmlFile (xmlMeshInFileName, Teuchos::ptr (&inputMeshList));
333 if (MyPID == 0) {
334 inputMeshList.print(std::cout,2,true,true);
335 std::cout << "\n";
336 }
337 }
338 else
339 {
340 std::cout << "Cannot read input file: " << xmlMeshInFileName << "\n";
341 return 0;
342 }
343
344 if(xmlSolverInFileName.length()) {
345 if (MyPID == 0)
346 std::cout << "\nReading parameter list from the XML file \""<<xmlSolverInFileName<<"\" ...\n\n";
347 Teuchos::updateParametersFromXmlFile(xmlSolverInFileName, Teuchos::inoutArg(inputSolverList));
348 } else if (MyPID == 0) std::cout << "Using default solver values ..." << std::endl;
349
350 // Get pamgen mesh definition
351 std::string meshInput = Teuchos::getParameter<std::string>(inputMeshList,"meshInput");
352
353 // Get Isorropia and Zoltan parameters.
354 Teuchos::ParameterList iso_paramlist = inputMeshList.sublist
355 ("Isorropia Input") ;
356 if (MyPID == 0) {
357 std::cout << "Isorropia/Zoltan parameters" << std::endl;
358 iso_paramlist.print(std::cout,2,true,true);
359 }
360
361
362 /**********************************************************************************/
363 /***************************** GET CELL TOPOLOGY **********************************/
364 /**********************************************************************************/
365
366 // Get cell topology for base hexahedron
367 shards::CellTopology cellType(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
368
369 // Get dimensions
370 int numNodesPerElem = cellType.getNodeCount();
371 int spaceDim = cellType.getDimension();
372 int dim = 2;
373
374 /**********************************************************************************/
375 /******************************* GENERATE MESH ************************************/
376 /**********************************************************************************/
377
378 if (MyPID == 0) {
379 std::cout << "Generating mesh ... \n\n";
380 }
381
382 long long * node_comm_proc_ids = NULL;
383 long long * node_cmap_node_cnts = NULL;
384 long long * node_cmap_ids = NULL;
385 long long ** comm_node_ids = NULL;
386 long long ** comm_node_proc_ids = NULL;
387
388 // Generate mesh with Pamgen
389 long long maxInt = 9223372036854775807LL;
390 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
391 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
392
393 string msg("Poisson: ");
394 if(MyPID == 0) {cout << msg << "Pamgen Setup = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
395
396 // Get mesh size info
397 char title[100];
398 long long numDim;
399 long long numNodes;
400 long long numElems;
401 long long numElemBlk;
402 long long numNodeSets;
403 long long numSideSets;
404 int id = 0;
405
406 im_ex_get_init_l(id, title, &numDim, &numNodes,
407 &numElems, &numElemBlk, &numNodeSets,
408 &numSideSets);
409
410 long long numNodesGlobal;
411 long long numElemsGlobal;
412 long long numElemBlkGlobal;
413 long long numNodeSetsGlobal;
414 long long numSideSetsGlobal;
415
416 im_ne_get_init_global_l(id, &numNodesGlobal, &numElemsGlobal,
417 &numElemBlkGlobal, &numNodeSetsGlobal,
418 &numSideSetsGlobal);
419
420 // Print mesh information
421 if (MyPID == 0){
422 std::cout << " Number of Global Elements: " << numElemsGlobal << " \n";
423 std::cout << " Number of Global Nodes: " << numNodesGlobal << " \n\n";
424 }
425
426 long long * block_ids = new long long [numElemBlk];
427 error += im_ex_get_elem_blk_ids_l(id, block_ids);
428
429
430 long long *nodes_per_element = new long long [numElemBlk];
431 long long *element_attributes = new long long [numElemBlk];
432 long long *elements = new long long [numElemBlk];
433 char **element_types = new char * [numElemBlk];
434 long long **elmt_node_linkage = new long long * [numElemBlk];
435
436
437 for(long long i = 0; i < numElemBlk; i ++){
438 element_types[i] = new char [MAX_STR_LENGTH + 1];
439 error += im_ex_get_elem_block_l(id,
440 block_ids[i],
441 element_types[i],
442 (long long*)&(elements[i]),
443 (long long*)&(nodes_per_element[i]),
444 (long long*)&(element_attributes[i]));
445 }
446
447 /*connectivity*/
448 for(long long b = 0; b < numElemBlk; b++){
449 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
450 error += im_ex_get_elem_conn_l(id,block_ids[b],elmt_node_linkage[b]);
451 }
452
453 // Get node-element connectivity
454 int telct = 0;
455 FieldContainer<int> elemToNode(numElems,numNodesPerElem);
456 for(long long b = 0; b < numElemBlk; b++){
457 for(long long el = 0; el < elements[b]; el++){
458 for (int j=0; j<numNodesPerElem; j++) {
459 elemToNode(telct,j) = elmt_node_linkage[b][el*numNodesPerElem + j]-1;
460 }
461 telct ++;
462 }
463 }
464
465 // Read node coordinates and place in field container
466 FieldContainer<double> nodeCoord(numNodes,dim);
467 double * nodeCoordx = new double [numNodes];
468 double * nodeCoordy = new double [numNodes];
469 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,0);
470 for (int i=0; i<numNodes; i++) {
471 nodeCoord(i,0)=nodeCoordx[i];
472 nodeCoord(i,1)=nodeCoordy[i];
473 }
474 /*parallel info*/
475 long long num_internal_nodes;
476 long long num_border_nodes;
477 long long num_external_nodes;
478 long long num_internal_elems;
479 long long num_border_elems;
480 long long num_node_comm_maps;
481 long long num_elem_comm_maps;
482 im_ne_get_loadbal_param_l( id,
483 &num_internal_nodes,
484 &num_border_nodes,
485 &num_external_nodes,
486 &num_internal_elems,
487 &num_border_elems,
488 &num_node_comm_maps,
489 &num_elem_comm_maps,
490 0/*unused*/ );
491
492 if(num_node_comm_maps > 0){
493 node_comm_proc_ids = new long long [num_node_comm_maps];
494 node_cmap_node_cnts = new long long [num_node_comm_maps];
495 node_cmap_ids = new long long [num_node_comm_maps];
496 comm_node_ids = new long long* [num_node_comm_maps];
497 comm_node_proc_ids = new long long* [num_node_comm_maps];
498
499 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
500 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
501
502
503 if ( im_ne_get_cmap_params_l( id,
504 node_cmap_ids,
505 (long long*)node_cmap_node_cnts,
506 elem_cmap_ids,
507 (long long*)elem_cmap_elem_cnts,
508 0/*not used proc_id*/ ) < 0 )++error;
509
510 for(long long j = 0; j < num_node_comm_maps; j++) {
511 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
512 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
513 if ( im_ne_get_node_cmap_l( id,
514 node_cmap_ids[j],
515 comm_node_ids[j],
516 comm_node_proc_ids[j],
517 0/*not used proc_id*/ ) < 0 )++error;
518 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
519 }
520
521 delete [] elem_cmap_ids;
522 delete [] elem_cmap_elem_cnts;
523 }
524
525 if(!Comm.MyPID()) {cout << msg << "Mesh Queries = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
526
527 //Calculate global node ids
528 long long * globalNodeIds = new long long[numNodes];
529 bool * nodeIsOwned = new bool[numNodes];
530
531 calc_global_node_ids(globalNodeIds,
532 nodeIsOwned,
533 numNodes,
534 num_node_comm_maps,
535 node_cmap_node_cnts,
536 node_comm_proc_ids,
537 comm_node_ids,
538 rank);
539
540
541 if(MyPID==0) {cout << msg << "Global Node Nums = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
542
543
544 // Container indicating whether a node is on the boundary (1-yes 0-no)
545 FieldContainer<int> nodeOnBoundary(numNodes);
546
547 // Get boundary (side set) information
548 long long * sideSetIds = new long long [numSideSets];
549 long long numSidesInSet;
550 long long numDFinSet;
551 im_ex_get_side_set_ids_l(id,sideSetIds);
552 for (int i=0; i<numSideSets; i++) {
553 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
554 if (numSidesInSet > 0){
555 long long * sideSetElemList = new long long [numSidesInSet];
556 long long * sideSetSideList = new long long [numSidesInSet];
557 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
558 for (int j=0; j<numSidesInSet; j++) {
559
560 int sideNode0 = cellType.getNodeMap(1,sideSetSideList[j]-1,0);
561 int sideNode1 = cellType.getNodeMap(1,sideSetSideList[j]-1,1);
562
563 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode0))=1;
564 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode1))=1;
565 }
566 delete [] sideSetElemList;
567 delete [] sideSetSideList;
568 }
569 }
570 delete [] sideSetIds;
571
572 if(MyPID ==0) {cout << msg << "Boundary Conds = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
573
574
575
576 /**********************************************************************************/
577 /********************************* GET CUBATURE ***********************************/
578 /**********************************************************************************/
579
580 // Get numerical integration points and weights
581 DefaultCubatureFactory<double> cubFactory;
582 int cubDegree = 2;
583 Teuchos::RCP<Cubature<double> > myCub = cubFactory.create(cellType, cubDegree);
584
585 int cubDim = myCub->getDimension();
586 int numCubPoints = myCub->getNumPoints();
587
588 FieldContainer<double> cubPoints(numCubPoints, cubDim);
589 FieldContainer<double> cubWeights(numCubPoints);
590
591 myCub->getCubature(cubPoints, cubWeights);
592
593 if(MyPID==0) {std::cout << "Getting cubature "
594 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
595
596
597
598 /**********************************************************************************/
599 /*********************************** GET BASIS ************************************/
600 /**********************************************************************************/
601
602 // Define basis
603 Basis_HGRAD_QUAD_C1_FEM<double, FieldContainer<double> > myHGradBasis;
604 int numFieldsG = myHGradBasis.getCardinality();
605 FieldContainer<double> HGBValues(numFieldsG, numCubPoints);
606 FieldContainer<double> HGBGrads(numFieldsG, numCubPoints, spaceDim);
607
608 // Evaluate basis values and gradients at cubature points
609 myHGradBasis.getValues(HGBValues, cubPoints, OPERATOR_VALUE);
610 myHGradBasis.getValues(HGBGrads, cubPoints, OPERATOR_GRAD);
611
612 if(MyPID==0) {std::cout << "Getting basis "
613 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
614
615
616 /**********************************************************************************/
617 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
618 /**********************************************************************************/
619
620 // Count owned nodes
621 int ownedNodes=0;
622 for(int i=0;i<numNodes;i++)
623 if(nodeIsOwned[i]) ownedNodes++;
624
625 // Build a list of the OWNED global ids...
626 // NTS: will need to switch back to long long
627 int *ownedGIDs=new int[ownedNodes];
628 int oidx=0;
629 for(int i=0;i<numNodes;i++)
630 if(nodeIsOwned[i]){
631 ownedGIDs[oidx]=(int)globalNodeIds[i];
632 oidx++;
633 }
634 // Generate epetra map for nodes
635 Epetra_Map globalMapG(-1,ownedNodes,ownedGIDs,0,Comm);
636
637
638 // Global arrays in Epetra format
639 Epetra_FECrsMatrix StiffMatrix(Copy, globalMapG, 20*numFieldsG);
640 Epetra_FEVector rhsVector(globalMapG);
641
642 if(MyPID==0) {std::cout << msg << "Build global maps "
643 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
644
645
646 #ifdef DUMP_DATA
647 /**********************************************************************************/
648 /**** PUT COORDINATES AND NODAL VALUES IN ARRAYS FOR OUTPUT (FOR PLOTTING ONLY) ***/
649 /**********************************************************************************/
650
651 // Put coordinates in multivector for output
652 Epetra_MultiVector nCoord(globalMapG,dim);
653 Epetra_MultiVector nBound(globalMapG,1);
654
655 int indOwned = 0;
656 for (int inode=0; inode<numNodes; inode++) {
657 if (nodeIsOwned[inode]) {
658 nCoord[0][indOwned]=nodeCoord(inode,0);
659 nCoord[1][indOwned]=nodeCoord(inode,1);
660 nBound[0][indOwned]=nodeOnBoundary(inode);
661 indOwned++;
662 }
663 }
664 EpetraExt::MultiVectorToMatrixMarketFile("coords.dat",nCoord,0,0,false);
665 EpetraExt::MultiVectorToMatrixMarketFile("nodeOnBound.dat",nBound,0,0,false);
666
667 // Put element to node mapping in multivector for output
668 Epetra_Map globalMapElem(numElemsGlobal, numElems, 0, Comm);
669 Epetra_MultiVector elem2node(globalMapElem, numNodesPerElem);
670 for (int ielem=0; ielem<numElems; ielem++) {
671 for (int inode=0; inode<numNodesPerElem; inode++) {
672 elem2node[inode][ielem]=globalNodeIds[elemToNode(ielem,inode)];
673 }
674 }
675 EpetraExt::MultiVectorToMatrixMarketFile("elem2node.dat",elem2node,0,0,false);
676
677 if(MyPID==0) {Time.ResetStartTime();}
678
679 #endif
680
681 /**********************************************************************************/
682 /************************** DIRICHLET BC SETUP ************************************/
683 /**********************************************************************************/
684
685 int numBCNodes = 0;
686 for (int inode = 0; inode < numNodes; inode++){
687 if (nodeOnBoundary(inode) && nodeIsOwned[inode]){
688 numBCNodes++;
689 }
690 }
691
692 // Vector for use in applying BCs
693 Epetra_MultiVector v(globalMapG,true);
694 v.PutScalar(0.0);
695
696 // Set v to boundary values on Dirichlet nodes
697 int * BCNodes = new int [numBCNodes];
698 int indbc=0;
699 int iOwned=0;
700 for (int inode=0; inode<numNodes; inode++){
701 if (nodeIsOwned[inode]){
702 if (nodeOnBoundary(inode)){
703 BCNodes[indbc]=iOwned;
704 indbc++;
705 double x = nodeCoord(inode, 0);
706 double y = nodeCoord(inode, 1);
707 v[0][iOwned]=exactSolution(x, y);
708 }
709 iOwned++;
710 }
711 }
712
713 if(MyPID==0) {std::cout << msg << "Get Dirichlet boundary values "
714 << Time.ElapsedTime() << " sec \n\n"; Time.ResetStartTime();}
715
716
717 /**********************************************************************************/
718 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
719 /**********************************************************************************/
720
721
722 // Define desired workset size and count how many worksets there are on this processor's mesh block
723 int desiredWorksetSize = numElems; // change to desired workset size!
724 //int desiredWorksetSize = 100; // change to desired workset size!
725 int numWorksets = numElems/desiredWorksetSize;
726
727 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
728 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
729
730 if (MyPID == 0) {
731 std::cout << "Building discretization matrix and right hand side... \n\n";
732 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
733 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
734 Time.ResetStartTime();
735 }
736
737 for(int workset = 0; workset < numWorksets; workset++){
738
739 // Compute cell numbers where the workset starts and ends
740 int worksetSize = 0;
741 int worksetBegin = (workset + 0)*desiredWorksetSize;
742 int worksetEnd = (workset + 1)*desiredWorksetSize;
743
744 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
745 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
746
747 // Now we know the actual workset size and can allocate the array for the cell nodes
748 worksetSize = worksetEnd - worksetBegin;
749 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
750
751 // Copy coordinates into cell workset
752 int cellCounter = 0;
753 for(int cell = worksetBegin; cell < worksetEnd; cell++){
754 for (int node = 0; node < numNodesPerElem; node++) {
755 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
756 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
757 }
758 cellCounter++;
759 }
760
761 /**********************************************************************************/
762 /* Allocate arrays */
763 /**********************************************************************************/
764
765 // Containers for Jacobians, integration measure & cubature points in workset cells
766 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
767 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
768 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
769 FieldContainer<double> worksetCubWeights(worksetSize, numCubPoints);
770 FieldContainer<double> worksetCubPoints (worksetSize, numCubPoints, cubDim);
771
772 // Containers for basis values transformed to workset cells and them multiplied by cubature weights
773 FieldContainer<double> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
774 FieldContainer<double> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
775 FieldContainer<double> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
776 FieldContainer<double> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
777
778 // Containers for diffusive & advective fluxes & non-conservative adv. term and reactive terms
779 FieldContainer<double> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
780
781 // Containers for material values and source term. Require user-defined functions
782 FieldContainer<double> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
783 FieldContainer<double> worksetSourceTerm (worksetSize, numCubPoints);
784
785 // Containers for workset contributions to the discretization matrix and the right hand side
786 FieldContainer<double> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
787 FieldContainer<double> worksetRHS (worksetSize, numFieldsG);
788
789 if(MyPID==0) {std::cout << msg << "Allocate arrays "
790 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
791
792
793 /**********************************************************************************/
794 /* Calculate Jacobians */
795 /**********************************************************************************/
796
797 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
798 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
799 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
800
801 if(MyPID==0) {std::cout << msg << "Calculate Jacobians "
802 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
803
804 /**********************************************************************************/
805 /* Cubature Points to Physical Frame and Compute Data */
806 /**********************************************************************************/
807
808 // map cubature points to physical frame
809 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, cellType);
810
811 // get A at cubature points
812 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
813
814 // get source term at cubature points
815 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
816
817 if(MyPID==0) {std::cout << msg << "Map to physical frame and get source term "
818 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
819
820
821 /**********************************************************************************/
822 /* Compute Stiffness Matrix */
823 /**********************************************************************************/
824
825 // Transform basis gradients to physical frame:
826 IntrepidFSTools::HGRADtransformGRAD<double>(worksetHGBGrads, // DF^{-T}(grad u)
827 worksetJacobInv, HGBGrads);
828
829 // Compute integration measure for workset cells:
830 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeights, // Det(DF)*w = J*w
831 worksetJacobDet, cubWeights);
832
833
834 // Multiply transformed (workset) gradients with weighted measure
835 IntrepidFSTools::multiplyMeasure<double>(worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
836 worksetCubWeights, worksetHGBGrads);
837
838
839 // Compute the diffusive flux:
840 IntrepidFSTools::tensorMultiplyDataField<double>(worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
841 worksetMaterialVals,
842 worksetHGBGrads);
843
844 // Integrate to compute workset diffusion contribution to global matrix:
845 IntrepidFSTools::integrate<double>(worksetStiffMatrix, // (DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
846 worksetHGBGradsWeighted,
847 worksetDiffusiveFlux, COMP_BLAS);
848
849 if(MyPID==0) {std::cout << msg << "Compute stiffness matrix "
850 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
851
852
853 /**********************************************************************************/
854 /* Compute RHS */
855 /**********************************************************************************/
856
857 // Transform basis values to physical frame:
858 IntrepidFSTools::HGRADtransformVALUE<double>(worksetHGBValues, // clones basis values (u)
859 HGBValues);
860
861 // Multiply transformed (workset) values with weighted measure
862 IntrepidFSTools::multiplyMeasure<double>(worksetHGBValuesWeighted, // (u)*J*w
863 worksetCubWeights, worksetHGBValues);
864
865 // Integrate worksetSourceTerm against weighted basis function set
866 IntrepidFSTools::integrate<double>(worksetRHS, // f.(u)*J*w
867 worksetSourceTerm,
868 worksetHGBValuesWeighted, COMP_BLAS);
869
870
871 if(MyPID==0) {std::cout << msg << "Compute right-hand side "
872 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
873
874 /**********************************************************************************/
875 /* Assemble into Global Matrix */
876 /**********************************************************************************/
877
878 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
879 for(int cell = worksetBegin; cell < worksetEnd; cell++){
880
881 // Compute cell ordinal relative to the current workset
882 int worksetCellOrdinal = cell - worksetBegin;
883
884 // "CELL EQUATION" loop for the workset cell: cellRow is relative to the cell DoF numbering
885 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
886
887 int localRow = elemToNode(cell, cellRow);
888 int globalRow = globalNodeIds[localRow];
889 double sourceTermContribution = worksetRHS(worksetCellOrdinal, cellRow);
890
891 rhsVector.SumIntoGlobalValues(1, &globalRow, &sourceTermContribution);
892
893 // "CELL VARIABLE" loop for the workset cell: cellCol is relative to the cell DoF numbering
894 for (int cellCol = 0; cellCol < numFieldsG; cellCol++){
895
896 int localCol = elemToNode(cell, cellCol);
897 int globalCol = globalNodeIds[localCol];
898 double operatorMatrixContribution = worksetStiffMatrix(worksetCellOrdinal, cellRow, cellCol);
899
900 StiffMatrix.InsertGlobalValues(1, &globalRow, 1, &globalCol, &operatorMatrixContribution);
901
902 }// *** cell col loop ***
903 }// *** cell row loop ***
904 }// *** workset cell loop **
905 }// *** workset loop ***
906
907 /**********************************************************************************/
908 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
909 /**********************************************************************************/
910
911 StiffMatrix.GlobalAssemble();
912 StiffMatrix.FillComplete();
913 rhsVector.GlobalAssemble();
914
915 if(MyPID==0) {std::cout << msg << "Global assembly "
916 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
917
918 /**********************************************************************************/
919 /******************************* ADJUST MATRIX DUE TO BC **************************/
920 /**********************************************************************************/
921
922 // Apply stiffness matrix to v
923 Epetra_MultiVector rhsDir(globalMapG,true);
924 StiffMatrix.Apply(v,rhsDir);
925
926 // Update right-hand side
927 rhsVector.Update(-1.0,rhsDir,1.0);
928
929 // Adjust rhs due to Dirichlet boundary conditions
930 iOwned=0;
931 for (int inode=0; inode<numNodes; inode++){
932 if (nodeIsOwned[inode]){
933 if (nodeOnBoundary(inode)){
934 rhsVector[0][iOwned]=v[0][iOwned];
935 }
936 iOwned++;
937 }
938 }
939
940 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
941 // and add one to diagonal.
942 ML_Epetra::Apply_OAZToMatrix(BCNodes, numBCNodes, StiffMatrix);
943
944
945 delete [] BCNodes;
946
947 if(MyPID==0) {std::cout << msg << "Adjust global matrix and rhs due to BCs " << Time.ElapsedTime()
948 << " sec \n"; Time.ResetStartTime();}
949
950
951 #ifdef DUMP_DATA
952 // Dump matrices to disk
953 EpetraExt::RowMatrixToMatlabFile("stiff_matrix.dat",StiffMatrix);
954 EpetraExt::MultiVectorToMatrixMarketFile("rhs_vector.dat",rhsVector,0,0,false);
955 #endif
956
957 /**********************************************************************************/
958 /*********************************** SOLVE ****************************************/
959 /**********************************************************************************/
960
961 // Run the solver
962 Teuchos::ParameterList MLList = inputSolverList;
963 ML_Epetra::SetDefaults("SA", MLList, 0, 0, false);
964 MLList.set("repartition: Zoltan dimensions",2);
965 MLList.set("x-coordinates",nodeCoordx);
966 MLList.set("y-coordinates",nodeCoordy);
967
968
969 Epetra_FEVector exactNodalVals(globalMapG);
970 Epetra_FEVector femCoefficients(globalMapG);
971 double TotalErrorResidual = 0.0;
972 double TotalErrorExactSol = 0.0;
973
974 // Get exact solution at nodes
975 for (int i = 0; i<numNodes; i++) {
976 if (nodeIsOwned[i]){
977 double x = nodeCoord(i,0);
978 double y = nodeCoord(i,1);
979 double exactu = exactSolution(x, y);
980
981 int rowindex=globalNodeIds[i];
982 exactNodalVals.SumIntoGlobalValues(1, &rowindex, &exactu);
983 }
984 }
985 exactNodalVals.GlobalAssemble();
986
987 char probType[10] = "laplace";
988
989
990 TestMultiLevelPreconditionerLaplace(probType, MLList,
991 StiffMatrix, exactNodalVals,
992 rhsVector, femCoefficients,
993 TotalErrorResidual, TotalErrorExactSol);
994
995 /**********************************************************************************/
996 /**************************** CALCULATE ERROR *************************************/
997 /**********************************************************************************/
998
999 if (MyPID == 0) {Time.ResetStartTime();}
1000
1001 double L2err = 0.0;
1002 double L2errTot = 0.0;
1003 double H1err = 0.0;
1004 double H1errTot = 0.0;
1005 double Linferr = 0.0;
1006 double LinferrTot = 0.0;
1007
1008 #ifdef HAVE_MPI
1009 // Import solution onto current processor
1010 //int numNodesGlobal = globalMapG.NumGlobalElements();
1011 Epetra_Map solnMap(static_cast<int>(numNodesGlobal), static_cast<int>(numNodesGlobal), 0, Comm);
1012 Epetra_Import solnImporter(solnMap, globalMapG);
1013 Epetra_Vector uCoeff(solnMap);
1014 uCoeff.Import(femCoefficients, solnImporter, Insert);
1015 #endif
1016
1017 // Define desired workset size
1018 desiredWorksetSize = numElems;
1019 int numWorksetsErr = numElems/desiredWorksetSize;
1020
1021 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1022 if(numWorksetsErr*desiredWorksetSize < numElems) numWorksetsErr += 1;
1023
1024 // Get cubature points and weights for error calc (may be different from previous)
1025 Intrepid::DefaultCubatureFactory<double> cubFactoryErr;
1026 int cubDegErr = 3;
1027 Teuchos::RCP<Intrepid::Cubature<double> > cellCubatureErr = cubFactoryErr.create(cellType, cubDegErr);
1028 int cubDimErr = cellCubatureErr->getDimension();
1029 int numCubPointsErr = cellCubatureErr->getNumPoints();
1030 Intrepid::FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
1031 Intrepid::FieldContainer<double> cubWeightsErr(numCubPointsErr);
1032 cellCubatureErr->getCubature(cubPointsErr, cubWeightsErr);
1033
1034 // Evaluate basis values and gradients at cubature points
1035 Intrepid::FieldContainer<double> uhGVals(numFieldsG, numCubPointsErr);
1036 Intrepid::FieldContainer<double> uhGrads(numFieldsG, numCubPointsErr, spaceDim);
1037 myHGradBasis.getValues(uhGVals, cubPointsErr, Intrepid::OPERATOR_VALUE);
1038 myHGradBasis.getValues(uhGrads, cubPointsErr, Intrepid::OPERATOR_GRAD);
1039
1040 // Loop over worksets
1041 for(int workset = 0; workset < numWorksetsErr; workset++){
1042
1043 // compute cell numbers where the workset starts and ends
1044 int worksetSize = 0;
1045 int worksetBegin = (workset + 0)*desiredWorksetSize;
1046 int worksetEnd = (workset + 1)*desiredWorksetSize;
1047
1048 // when numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1049 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1050
1051 // now we know the actual workset size and can allocate the array for the cell nodes
1052 worksetSize = worksetEnd - worksetBegin;
1053 Intrepid::FieldContainer<double> cellWorksetEr(worksetSize, numNodesPerElem, spaceDim);
1054 Intrepid::FieldContainer<double> worksetApproxSolnCoef(worksetSize, numNodesPerElem);
1055
1056 // loop over cells to fill arrays with coordinates and discrete solution coefficient
1057 int cellCounter = 0;
1058 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1059
1060 for (int node = 0; node < numNodesPerElem; node++) {
1061 cellWorksetEr(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
1062 cellWorksetEr(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
1063
1064 int rowIndex = globalNodeIds[elemToNode(cell, node)];
1065 #ifdef HAVE_MPI
1066 worksetApproxSolnCoef(cellCounter, node) = uCoeff.Values()[rowIndex];
1067 #else
1068 worksetApproxSolnCoef(cellCounter, node) = femCoefficients.Values()[rowIndex];
1069 #endif
1070 }
1071
1072 cellCounter++;
1073
1074 } // end cell loop
1075
1076 // Containers for Jacobian
1077 Intrepid::FieldContainer<double> worksetJacobianE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1078 Intrepid::FieldContainer<double> worksetJacobInvE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1079 Intrepid::FieldContainer<double> worksetJacobDetE(worksetSize, numCubPointsErr);
1080 Intrepid::FieldContainer<double> worksetCubWeightsE(worksetSize, numCubPointsErr);
1081
1082 // Containers for basis values and gradients in physical space
1083 Intrepid::FieldContainer<double> uhGValsTrans(worksetSize,numFieldsG, numCubPointsErr);
1084 Intrepid::FieldContainer<double> uhGradsTrans(worksetSize, numFieldsG, numCubPointsErr, spaceDim);
1085
1086 // compute cell Jacobians, their inverses and their determinants
1087 IntrepidCTools::setJacobian(worksetJacobianE, cubPointsErr, cellWorksetEr, cellType);
1088 IntrepidCTools::setJacobianInv(worksetJacobInvE, worksetJacobianE );
1089 IntrepidCTools::setJacobianDet(worksetJacobDetE, worksetJacobianE );
1090
1091 // map cubature points to physical frame
1092 Intrepid::FieldContainer<double> worksetCubPoints(worksetSize, numCubPointsErr, cubDimErr);
1093 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPointsErr, cellWorksetEr, cellType);
1094
1095 // evaluate exact solution and gradient at cubature points
1096 Intrepid::FieldContainer<double> worksetExactSoln(worksetSize, numCubPointsErr);
1097 Intrepid::FieldContainer<double> worksetExactSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1098 evaluateExactSolution(worksetExactSoln, worksetCubPoints);
1099 evaluateExactSolutionGrad(worksetExactSolnGrad, worksetCubPoints);
1100
1101 // transform basis values to physical coordinates
1102 IntrepidFSTools::HGRADtransformVALUE<double>(uhGValsTrans, uhGVals);
1103 IntrepidFSTools::HGRADtransformGRAD<double>(uhGradsTrans, worksetJacobInvE, uhGrads);
1104
1105 // compute weighted measure
1106 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeightsE, worksetJacobDetE, cubWeightsErr);
1107
1108 // evaluate the approximate solution and gradient at cubature points
1109 Intrepid::FieldContainer<double> worksetApproxSoln(worksetSize, numCubPointsErr);
1110 Intrepid::FieldContainer<double> worksetApproxSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1111 IntrepidFSTools::evaluate<double>(worksetApproxSoln, worksetApproxSolnCoef, uhGValsTrans);
1112 IntrepidFSTools::evaluate<double>(worksetApproxSolnGrad, worksetApproxSolnCoef, uhGradsTrans);
1113
1114 // get difference between approximate and exact solutions
1115 Intrepid::FieldContainer<double> worksetDeltaSoln(worksetSize, numCubPointsErr);
1116 Intrepid::FieldContainer<double> worksetDeltaSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1117 IntrepidRSTools::subtract(worksetDeltaSoln, worksetApproxSoln, worksetExactSoln);
1118 IntrepidRSTools::subtract(worksetDeltaSolnGrad, worksetApproxSolnGrad, worksetExactSolnGrad);
1119
1120 // take absolute values
1121 IntrepidRSTools::absval(worksetDeltaSoln);
1122 IntrepidRSTools::absval(worksetDeltaSolnGrad);
1123 // apply cubature weights to differences in values and grads for use in integration
1124 Intrepid::FieldContainer<double> worksetDeltaSolnWeighted(worksetSize, numCubPointsErr);
1125 Intrepid::FieldContainer<double> worksetDeltaSolnGradWeighted(worksetSize, numCubPointsErr, spaceDim);
1126 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnWeighted,
1127 worksetCubWeightsE, worksetDeltaSoln);
1128 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnGradWeighted,
1129 worksetCubWeightsE, worksetDeltaSolnGrad);
1130
1131 // integrate to get errors on each element
1132 Intrepid::FieldContainer<double> worksetL2err(worksetSize);
1133 Intrepid::FieldContainer<double> worksetH1err(worksetSize);
1134 IntrepidFSTools::integrate<double>(worksetL2err, worksetDeltaSoln,
1135 worksetDeltaSolnWeighted, Intrepid::COMP_BLAS);
1136 IntrepidFSTools::integrate<double>(worksetH1err, worksetDeltaSolnGrad,
1137 worksetDeltaSolnGradWeighted, Intrepid::COMP_BLAS);
1138
1139 // loop over cells to get errors for total workset
1140 cellCounter = 0;
1141 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1142
1143 // loop over cubature points
1144 for(int nPt = 0; nPt < numCubPointsErr; nPt++){
1145
1146 Linferr = std::max(Linferr, worksetDeltaSoln(cellCounter,nPt));
1147
1148 }
1149
1150 L2err += worksetL2err(cellCounter);
1151 H1err += worksetH1err(cellCounter);
1152
1153 cellCounter++;
1154
1155 } // end cell loop
1156
1157 } // end loop over worksets
1158
1159 #ifdef HAVE_MPI
1160 // sum over all processors
1161 Comm.SumAll(&L2err,&L2errTot,1);
1162 Comm.SumAll(&H1err,&H1errTot,1);
1163 Comm.MaxAll(&Linferr,&LinferrTot,1);
1164 #else
1165 L2errTot = L2err;
1166 H1errTot = H1err;
1167 LinferrTot = Linferr;
1168 #endif
1169
1170
1171 if (MyPID == 0) {
1172 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
1173 std::cout << "H1 Error: " << sqrt(H1errTot) <<"\n";
1174 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
1175 }
1176
1177 if(MyPID==0) {std::cout << msg << "Calculate error "
1178 << Time.ElapsedTime() << " s \n"; Time.ResetStartTime();}
1179
1180
1181 // Cleanup
1182 for(long long b = 0; b < numElemBlk; b++){
1183 delete [] elmt_node_linkage[b];
1184 delete [] element_types[b];
1185 }
1186 delete [] block_ids;
1187 delete [] nodes_per_element;
1188 delete [] element_attributes;
1189 delete [] element_types;
1190 delete [] elmt_node_linkage;
1191 delete [] ownedGIDs;
1192 delete [] elements;
1193 delete [] globalNodeIds;
1194 delete [] nodeIsOwned;
1195 if(num_node_comm_maps > 0){
1196 delete [] node_comm_proc_ids;
1197 delete [] node_cmap_node_cnts;
1198 delete [] node_cmap_ids;
1199 for(long long i=0;i<num_node_comm_maps;i++){
1200 delete [] comm_node_ids[i];
1201 delete [] comm_node_proc_ids[i];
1202 }
1203
1204 delete [] comm_node_ids;
1205 delete [] comm_node_proc_ids;
1206 }
1207
1208 delete [] nodeCoordx;
1209 delete [] nodeCoordy;
1210
1211 // delete mesh
1212 Delete_Pamgen_Mesh();
1213
1214 return 0;
1215
1216 }
1217 /**********************************************************************************/
1218 /********************************* END MAIN ***************************************/
1219 /**********************************************************************************/
1220
1221 /**********************************************************************************/
1222 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1223 /**********************************************************************************/
1224
1225 template<typename Scalar>
1226 const Scalar exactSolution(const Scalar& x, const Scalar& y) {
1227
1228 // Patch test: bi-linear function is in the FE space and should be recovered
1229 return 1. + x + y + x*y;
1230
1231 // Analytic solution with homogeneous Dirichlet boundary data
1232 // return sin(M_PI*x)*sin(M_PI*y)**exp(x+y);
1233
1234 // Analytic solution with inhomogeneous Dirichlet boundary data
1235 // return exp(x + y )/(1. + x*y);
1236 }
1237
1238
1239 template<typename Scalar>
1240 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y) {
1241
1242 material[0][0] = 1.;
1243 material[0][1] = 0.;
1244 //
1245 material[1][0] = 0.;
1246 material[1][1] = 1.;
1247 }
1248
1249 /**********************************************************************************/
1250 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1251 /**********************************************************************************/
1252
1253 /************ Grad of Exact Solution ****************/
1254 template<typename Scalar>
1255 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y) {
1256
1257 // To enable derivatives of the gradient (i.e., 2nd derivatives of the exact solution) need 2 levels of fad types
1258 Sacado::Fad::SFad<Scalar,2> fad_x = x;
1259 Sacado::Fad::SFad<Scalar,2> fad_y = y;
1260 Sacado::Fad::SFad<Scalar,2> u;
1261
1262 // Indicate the independent variables
1263 fad_x.diff(0,2);
1264 fad_y.diff(1,2);
1265
1266 u = exactSolution(fad_x, fad_y);
1267
1268 gradExact[0] = u.dx(0);
1269 gradExact[1] = u.dx(1);
1270 }
1271
1272 /************ Source Term (RHS) ****************/
1273 template<typename Scalar>
1274 const Scalar sourceTerm(Scalar& x, Scalar& y){
1275
1276 Scalar u;
1277 Scalar grad_u[2];
1278 Scalar flux[2] = {0.0, 0.0};
1279 Scalar material[2][2];
1280 Scalar f = 0.;
1281
1282 // Indicate the independent variables
1283 x.diff(0,2);
1284 y.diff(1,2);
1285
1286 // Get exact solution and its gradient
1287 u = exactSolution(x, y);
1288 exactSolutionGrad(grad_u, x, y);
1289
1290 // Get material tensor
1291 materialTensor<Scalar>(material, x, y);
1292
1293 // Compute total flux = (A.grad u)
1294 for(int i = 0; i < 2; i++){
1295
1296 // Add diffusive flux
1297 for(int j = 0; j < 2; j++){
1298 flux[i] += material[i][j]*grad_u[j];
1299 }
1300 }
1301
1302 // Compute source term (right hand side): f = -div(A.grad u)
1303 f = -(flux[0].dx(0) + flux[1].dx(1));
1304
1305 return f;
1306 }
1307
1308 /**********************************************************************************/
1309 /*************************** EVALUATION METHODS ***********************************/
1310 /**********************************************************************************/
1311
1312 /************ Material Tensor ****************/
1313 template<class ArrayOut, class ArrayIn>
1314 void evaluateMaterialTensor(ArrayOut & matTensorValues,
1315 const ArrayIn & evaluationPoints){
1316
1317 int numWorksetCells = evaluationPoints.dimension(0);
1318 int numPoints = evaluationPoints.dimension(1);
1319 int spaceDim = evaluationPoints.dimension(2);
1320
1321 double material[2][2];
1322
1323 for(int cell = 0; cell < numWorksetCells; cell++){
1324 for(int pt = 0; pt < numPoints; pt++){
1325
1326 double x = evaluationPoints(cell, pt, 0);
1327 double y = evaluationPoints(cell, pt, 1);
1328
1329 materialTensor<double>(material, x, y);
1330
1331 for(int row = 0; row < spaceDim; row++){
1332 for(int col = 0; col < spaceDim; col++){
1333 matTensorValues(cell, pt, row, col) = material[row][col];
1334 }
1335 }
1336 }
1337 }
1338 }
1339 /************ Source Term (RHS) ****************/
1340 template<class ArrayOut, class ArrayIn>
1341 void evaluateSourceTerm(ArrayOut & sourceTermValues,
1342 const ArrayIn & evaluationPoints){
1343
1344 int numWorksetCells = evaluationPoints.dimension(0);
1345 int numPoints = evaluationPoints.dimension(1);
1346
1347 for(int cell = 0; cell < numWorksetCells; cell++){
1348 for(int pt = 0; pt < numPoints; pt++){
1349
1350 Sacado::Fad::SFad<double,2> x = evaluationPoints(cell, pt, 0);
1351 Sacado::Fad::SFad<double,2> y = evaluationPoints(cell, pt, 1);
1352
1353 sourceTermValues(cell, pt) = sourceTerm<Sacado::Fad::SFad<double,2> >(x, y).val();
1354 }
1355 }
1356 }
1357
1358 /************ Exact Solution ****************/
1359 template<class ArrayOut, class ArrayIn>
1360 void evaluateExactSolution(ArrayOut & exactSolutionValues,
1361 const ArrayIn & evaluationPoints){
1362
1363 int numWorksetCells = evaluationPoints.dimension(0);
1364 int numPoints = evaluationPoints.dimension(1);
1365
1366 for(int cell = 0; cell < numWorksetCells; cell++){
1367 for(int pt = 0; pt < numPoints; pt++){
1368
1369 double x = evaluationPoints(cell, pt, 0);
1370 double y = evaluationPoints(cell, pt, 1);
1371
1372 exactSolutionValues(cell, pt) = exactSolution<double>(x, y);
1373 }
1374 }
1375 }
1376 /************ Grad of Exact Solution ****************/
1377 template<class ArrayOut, class ArrayIn>
1378 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
1379 const ArrayIn & evaluationPoints){
1380
1381 int numWorksetCells = evaluationPoints.dimension(0);
1382 int numPoints = evaluationPoints.dimension(1);
1383 int spaceDim = evaluationPoints.dimension(2);
1384
1385 double gradient[2];
1386
1387 for(int cell = 0; cell < numWorksetCells; cell++){
1388 for(int pt = 0; pt < numPoints; pt++){
1389
1390 double x = evaluationPoints(cell, pt, 0);
1391 double y = evaluationPoints(cell, pt, 1);
1392
1393 exactSolutionGrad<double>(gradient, x, y);
1394
1395 for(int row = 0; row < spaceDim; row++){
1396 exactSolutionGradValues(cell, pt, row) = gradient[row];
1397 }
1398 }
1399 }
1400 }
1401
1402 /**********************************************************************************/
1403 /******************************* TEST ML ******************************************/
1404 /**********************************************************************************/
1405
1406 // Test ML
1407 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
1408 Teuchos::ParameterList & MLList,
1409 Epetra_CrsMatrix & A,
1410 const Epetra_MultiVector & xexact,
1411 Epetra_MultiVector & b,
1412 Epetra_MultiVector & uh,
1413 double & TotalErrorResidual,
1414 double & TotalErrorExactSol)
1415 {
1416 Epetra_MultiVector x(xexact);
1417 x.PutScalar(0.0);
1418
1419 Epetra_LinearProblem Problem(&A,&x,&b);
1420 Epetra_MultiVector* lhs = Problem.GetLHS();
1421 Epetra_MultiVector* rhs = Problem.GetRHS();
1422
1423 Epetra_Time Time(A.Comm());
1424
1425 // =================== //
1426 // call ML and AztecOO //
1427 // =================== //
1428
1429 AztecOO solver(Problem);
1430 ML_Epetra::MultiLevelPreconditioner *MLPrec = new ML_Epetra::MultiLevelPreconditioner(A, MLList, true);
1431
1432 // tell AztecOO to use this preconditioner, then solve
1433 solver.SetPrecOperator(MLPrec);
1434 solver.SetAztecOption(AZ_solver, AZ_cg);
1435 solver.SetAztecOption(AZ_output, 1);
1436
1437 solver.Iterate(200, 1e-10);
1438
1439 delete MLPrec;
1440
1441 uh = *lhs;
1442
1443 // ==================================================== //
1444 // compute difference between exact solution and ML one //
1445 // ==================================================== //
1446 double d = 0.0, d_tot = 0.0;
1447 for( int i=0 ; i<lhs->Map().NumMyElements() ; ++i )
1448 d += ((*lhs)[0][i] - xexact[0][i]) * ((*lhs)[0][i] - xexact[0][i]);
1449
1450 A.Comm().SumAll(&d,&d_tot,1);
1451
1452 // ================== //
1453 // compute ||Ax - b|| //
1454 // ================== //
1455 double Norm;
1456 Epetra_Vector Ax(rhs->Map());
1457 A.Multiply(false, *lhs, Ax);
1458 Ax.Update(1.0, *rhs, -1.0);
1459 Ax.Norm2(&Norm);
1460
1461 string msg = ProblemType;
1462
1463 if (A.Comm().MyPID() == 0) {
1464 cout << msg << endl << "......Using " << A.Comm().NumProc() << " processes" << endl;
1465 cout << msg << "......||A x - b||_2 = " << Norm << endl;
1466 cout << msg << "......||x_exact - x||_2 = " << sqrt(d_tot) << endl;
1467 cout << msg << "......Total Time = " << Time.ElapsedTime() << endl;
1468 }
1469
1470 TotalErrorExactSol += sqrt(d_tot);
1471 TotalErrorResidual += Norm;
1472
1473 return( solver.NumIters() );
1474
1475 }
1476
1477