Debian Codegraph @

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