Debian Codegraph @

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