Debian Codegraph @

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