Debian Codegraph @

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