Debian Codegraph @

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