Debian Codegraph @

packages/trilinoscouplings/examples/scaling/TrilinosCouplings_TpetraIntrepidHybridPoisson3DExample.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 // TrilinosCouplings includes
11 #include <TrilinosCouplings_config.h>
12
13 // Intrepid includes
14 #include <Intrepid_FunctionSpaceTools.hpp>
15 #include <Intrepid_CellTools.hpp>
16 #include <Intrepid_ArrayTools.hpp>
17 #include <Intrepid_HGRAD_HEX_C1_FEM.hpp>
18 #include <Intrepid_RealSpaceTools.hpp>
19 #include <Intrepid_DefaultCubatureFactory.hpp>
20 #include <Intrepid_Utils.hpp>
21
22 // Teuchos includes
23 //#include <Teuchos_TimeMonitor.hpp>
24
25 // Shards includes
26 #include <Shards_CellTopology.hpp>
27
28 // Pamgen includes
29 #include <create_inline_mesh.h>
30 #include <pamgen_im_exodusII_l.h>
31 #include <pamgen_im_ne_nemesisI_l.h>
32 #include <pamgen_extras.h>
33
34 #ifdef HAVE_INTREPID_KOKKOS
35 #include "Sacado.hpp"
36 #else
37 // Sacado includes
38 #include <Sacado_No_Kokkos.hpp>
39 #endif
40
41 // My includes
42 #include "TrilinosCouplings_TpetraIntrepidHybridPoisson3DExample.hpp"
43 #include "TrilinosCouplings_Pamgen_Utils.hpp"
44 #include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
45
46 namespace TrilinosCouplings {
47 namespace TpetraIntrepidPoissonExample {
48
49 /**********************************************************************************/
50 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
51 /**********************************************************************************/
52
53 /** \brief User-defined exact solution.
54
55 \param x [in] x-coordinate of the evaluation point
56 \param y [in] y-coordinate of the evaluation point
57 \param z [in] z-coordinate of the evaluation point
58
59 \return Value of the exact solution at (x,y,z)
60 */
61 template<typename Scalar>
62 const Scalar
63 exactSolution (const Scalar& x, const Scalar& y, const Scalar& z);
64
65 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
66
67 \param gradExact [out] gradient of the exact solution evaluated at (x,y,z)
68 \param x [in] x-coordinate of the evaluation point
69 \param y [in] y-coordinate of the evaluation point
70 \param z [in] z-coordinate of the evaluation point
71 */
72 template<typename Scalar>
73 void
74 exactSolutionGrad (Scalar gradExact[3],
75 const Scalar& x,
76 const Scalar& y,
77 const Scalar& z);
78
79 /** \brief Computes source term: f = -div(A.grad u). Requires user-defined exact solution
80 and material tensor.
81
82 \param x [in] x-coordinate of the evaluation point
83 \param y [in] y-coordinate of the evaluation point
84 \param z [in] z-coordinate of the evaluation point
85
86 \return Source term corresponding to the user-defined exact solution evaluated at (x,y,z)
87 */
88 template<typename Scalar>
89 const Scalar
90 sourceTerm (Scalar& x, Scalar& y, Scalar& z);
91
92 /** \brief Compute the material tensor at array of points in physical space.
93
94 \param worksetMaterialValues [out] Rank-2, 3 or 4 array with dimensions (C,P), (C,P,D) or (C,P,D,D)
95 with the values of the material tensor
96 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
97 */
98 template<class ArrayOut, class ArrayIn>
99 void
100 evaluateMaterialTensor (ArrayOut& worksetMaterialValues,
101 const ArrayIn& evaluationPoints);
102
103 /** \brief Compute the source term at array of points in physical space.
104
105 \param sourceTermValues [out] Rank-2 (C,P) array with the values of the source term
106 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
107 */
108 template<class ArrayOut, class ArrayIn>
109 void
110 evaluateSourceTerm (ArrayOut& sourceTermValues,
111 const ArrayIn& evaluationPoints);
112
113 /** \brief Compute the exact solution at array of points in physical space.
114
115 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
116 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
117 */
118 template<class ArrayOut, class ArrayIn>
119 void
120 evaluateExactSolution (ArrayOut& exactSolutionValues,
121 const ArrayIn& evaluationPoints);
122
123 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
124
125 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
126 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
127 */
128 template<class ArrayOut, class ArrayIn>
129 void
130 evaluateExactSolutionGrad (ArrayOut& exactSolutionGradValues,
131 const ArrayIn& evaluationPoints);
132
133 void
134 makeMatrixAndRightHandSide (Teuchos::RCP<sparse_matrix_type>& A,
135 Teuchos::RCP<multivector_type>& B,
136 Teuchos::RCP<multivector_type>& X_exact,
137 Teuchos::RCP<multivector_type>& X,
138 Teuchos::Array<Teuchos::Array<ST> >& coordArray,
139 Teuchos::Array<LO>& lNodesPerDim,
140 const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
141 const std::string& meshInput,
142 const Teuchos::RCP<Teuchos::FancyOStream>& out,
143 const Teuchos::RCP<Teuchos::FancyOStream>& err,
144 const bool verbose,
145 const bool debug)
146 {
147 using Teuchos::RCP;
148 using Teuchos::rcp_implicit_cast;
149
150 RCP<vector_type> b, x_exact, x;
151 makeMatrixAndRightHandSide (A, b, x_exact, x, coordArray, lNodesPerDim, comm,
152 meshInput, out, err, verbose, debug);
153
154 B = rcp_implicit_cast<multivector_type> (b);
155 X_exact = rcp_implicit_cast<multivector_type> (x_exact);
156 X = rcp_implicit_cast<multivector_type> (x);
157 }
158
159 void
160 makeMatrixAndRightHandSide (Teuchos::RCP<sparse_matrix_type>& A,
161 Teuchos::RCP<vector_type>& B,
162 Teuchos::RCP<vector_type>& X_exact,
163 Teuchos::RCP<vector_type>& X,
164 Teuchos::Array<Teuchos::Array<ST> >& coordArray,
165 Teuchos::Array<LO>& lNodesPerDim,
166 const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
167 const std::string& meshInput,
168 const Teuchos::RCP<Teuchos::FancyOStream>& out,
169 const Teuchos::RCP<Teuchos::FancyOStream>& err,
170 const bool verbose,
171 const bool debug)
172 {
173 using namespace Intrepid;
174 using Tpetra::global_size_t;
175 using Teuchos::Array;
176 using Teuchos::ArrayRCP;
177 using Teuchos::ArrayView;
178 using Teuchos::arrayView;
179 using Teuchos::as;
180 using Teuchos::outArg;
181 using Teuchos::ParameterList;
182 using Teuchos::RCP;
183 using Teuchos::rcp;
184 using Teuchos::TimeMonitor;
185 using std::endl;
186 //typedef Teuchos::ArrayView<LO>::size_type size_type; // unused
187 typedef Teuchos::ScalarTraits<ST> STS;
188
189 (void) verbose;
190 (void) debug;
191
192 Tpetra::global_size_t INVALID_GO = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid();
193
194 //
195 // mfh 19 Apr 2012: If you want to change the template parameters of
196 // these typedefs, modify the typedefs (ST, LO, GO, Node) near the
197 // top of this file.
198 //
199 typedef Tpetra::Map<LO, GO, Node> map_type;
200 typedef Tpetra::Export<LO, GO, Node> export_type;
201 //typedef Tpetra::Import<LO, GO, Node> import_type; // unused
202 typedef Tpetra::CrsGraph<LO, GO, Node> sparse_graph_type;
203
204 // Number of independent variables fixed at 3
205 //typedef Sacado::Fad::SFad<ST, 3> Fad3; // unused
206 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
207 //typedef Intrepid::RealSpaceTools<ST> IntrepidRSTools; // unused
208 typedef Intrepid::CellTools<ST> IntrepidCTools;
209
210 const int numProcs = comm->getSize ();
211 const int myRank = comm->getRank ();
212
213 *out << "makeMatrixAndRightHandSide:" << endl;
214 Teuchos::OSTab tab (out);
215
216 /**********************************************************************************/
217 /***************************** GET CELL TOPOLOGY **********************************/
218 /**********************************************************************************/
219
220 *out << "Getting cell topology" << endl;
221
222 // Get cell topology for base hexahedron
223 shards::CellTopology cellType (shards::getCellTopologyData<shards::Hexahedron<8> > ());
224
225 // Get dimensions
226 int numNodesPerElem = cellType.getNodeCount();
227 int spaceDim = cellType.getDimension();
228 int dim = 3;
229
230 /**********************************************************************************/
231 /******************************* GENERATE MESH ************************************/
232 /**********************************************************************************/
233
234 *out << "Generating mesh (tpetra)" << endl;
235
236 int error = 0; // Number of errors in generating the mesh
237
238 long long * node_comm_proc_ids = NULL;
239 long long * node_cmap_node_cnts = NULL;
240 long long * node_cmap_ids = NULL;
241 long long ** comm_node_ids = NULL;
242 long long ** comm_node_proc_ids = NULL;
243
244 // Generate mesh with Pamgen
245 long long maxInt = 9223372036854775807LL;
246 long long cr_result = Create_Pamgen_Mesh (meshInput.c_str (), dim, myRank, numProcs, maxInt);
247 TrilinosCouplings::pamgen_error_check(*out,cr_result);
248
249 std::string msg ("Poisson: ");
250
251 // Get mesh size info
252 char title[100];
253 long long numDim;
254 long long numNodes;
255 long long numElems;
256 long long numElemBlk;
257 long long numNodeSets;
258 long long numSideSets;
259 int id = 0;
260
261 im_ex_get_init_l (id, title, &numDim, &numNodes, &numElems, &numElemBlk,
262 &numNodeSets, &numSideSets);
263
264 TEUCHOS_TEST_FOR_EXCEPTION(numElems == 0, std::runtime_error,
265 "The number of elements in the mesh is zero.");
266
267 long long numNodesGlobal;
268 long long numElemsGlobal;
269 long long numElemBlkGlobal;
270 long long numNodeSetsGlobal;
271 long long numSideSetsGlobal;
272
273 im_ne_get_init_global_l (id, &numNodesGlobal, &numElemsGlobal,
274 &numElemBlkGlobal, &numNodeSetsGlobal,
275 &numSideSetsGlobal);
276
277 long long local_num_ijk[3];
278 im_ne_get_local_num_ijk_l (id, local_num_ijk);
279 for(int dim = 0; dim < 3; ++dim) {
280 lNodesPerDim[dim] = local_num_ijk[dim];
281 }
282
283 Teuchos::Array<LO> nodesPerDim(3);
284 long long num_ijk[3];
285 im_ne_get_num_ijk_l (id, num_ijk);
286 for(int dim = 0; dim < 3; ++dim) {
287 nodesPerDim[dim] = num_ijk[dim];
288 }
289
290 // Print mesh information
291 {
292 Teuchos::OSTab tab2 (out);
293 *out << "Global number of elements: "
294 << numElemsGlobal << endl
295 << "Global number of nodes (incl. boundary nodes): "
296 << numNodesGlobal << endl
297 << "lNodesPerDim: " << lNodesPerDim << endl
298 << "nodesPerDim: " << nodesPerDim << endl;
299 }
300
301 long long * block_ids = new long long [numElemBlk];
302 error += im_ex_get_elem_blk_ids_l(id, block_ids);
303
304 long long *nodes_per_element = new long long [numElemBlk];
305 long long *element_attributes = new long long [numElemBlk];
306 long long *elements = new long long [numElemBlk];
307 char **element_types = new char * [numElemBlk];
308 long long **elmt_node_linkage = new long long * [numElemBlk];
309
310 for (long long i = 0; i < numElemBlk; ++i) {
311 element_types[i] = new char [MAX_STR_LENGTH + 1];
312 error += im_ex_get_elem_block_l (id,
313 block_ids[i],
314 element_types[i],
315 (long long*)&(elements[i]),
316 (long long*)&(nodes_per_element[i]),
317 (long long*)&(element_attributes[i]));
318 }
319
320 // connectivity
321 for (long long b = 0; b < numElemBlk; ++b) {
322 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
323 error += im_ex_get_elem_conn_l (id,block_ids[b], elmt_node_linkage[b]);
324 }
325
326 // Get node-element connectivity
327 int telct = 0;
328 FieldContainer<int> elemToNode(numElems,numNodesPerElem);
329 for (long long b = 0; b < numElemBlk; b++) {
330 for (long long el = 0; el < elements[b]; el++) {
331 for (int j = 0; j < numNodesPerElem; ++j) {
332 elemToNode(telct,j) = elmt_node_linkage[b][el*numNodesPerElem + j]-1;
333 }
334 ++telct;
335 }
336 }
337
338 // Read node coordinates and place in field container
339 FieldContainer<ST> nodeCoord (numNodes, dim);
340 ST * nodeCoordx = new ST [numNodes];
341 ST * nodeCoordy = new ST [numNodes];
342 ST * nodeCoordz = new ST [numNodes];
343 im_ex_get_coord_l (id, nodeCoordx, nodeCoordy, nodeCoordz);
344 for (int i=0; i<numNodes; i++) {
345 nodeCoord(i,0)=nodeCoordx[i];
346 nodeCoord(i,1)=nodeCoordy[i];
347 nodeCoord(i,2)=nodeCoordz[i];
348 }
349 delete [] nodeCoordx;
350 delete [] nodeCoordy;
351 delete [] nodeCoordz;
352
353 // parallel info
354 long long num_internal_nodes;
355 long long num_border_nodes;
356 long long num_external_nodes;
357 long long num_internal_elems;
358 long long num_border_elems;
359 long long num_node_comm_maps;
360 long long num_elem_comm_maps;
361 im_ne_get_loadbal_param_l( id,
362 &num_internal_nodes,
363 &num_border_nodes,
364 &num_external_nodes,
365 &num_internal_elems,
366 &num_border_elems,
367 &num_node_comm_maps,
368 &num_elem_comm_maps,
369 0/*unused*/ );
370
371 if (num_node_comm_maps > 0) {
372 node_comm_proc_ids = new long long [num_node_comm_maps];
373 node_cmap_node_cnts = new long long [num_node_comm_maps];
374 node_cmap_ids = new long long [num_node_comm_maps];
375 comm_node_ids = new long long* [num_node_comm_maps];
376 comm_node_proc_ids = new long long* [num_node_comm_maps];
377
378 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
379 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
380
381 if (im_ne_get_cmap_params_l (id,
382 node_cmap_ids,
383 (long long*)node_cmap_node_cnts,
384 elem_cmap_ids,
385 (long long*)elem_cmap_elem_cnts,
386 0/*not used proc_id*/ ) < 0) {
387 ++error;
388 }
389
390 for (long long j = 0; j < num_node_comm_maps; ++j) {
391 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
392 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
393 if (im_ne_get_node_cmap_l (id,
394 node_cmap_ids[j],
395 comm_node_ids[j],
396 comm_node_proc_ids[j],
397 0/*not used proc_id*/ ) < 0) {
398 ++error;
399 }
400 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
401 }
402
403 delete [] elem_cmap_ids;
404 delete [] elem_cmap_elem_cnts;
405 }
406
407 //
408 // Calculate global node ids
409 //
410 Array<long long> globalNodeIds (numNodes);
411 // nodeIsOwned must be a raw array, because std::vector<T> (and
412 // therefore Teuchos::Array<T>) has a specialization for T = bool
413 // that messes up the pointer type.
414 bool* nodeIsOwned = new bool [numNodes];
415 calc_global_node_ids (globalNodeIds.getRawPtr (),
416 nodeIsOwned,
417 numNodes,
418 num_node_comm_maps,
419 node_cmap_node_cnts,
420 node_comm_proc_ids,
421 comm_node_ids,
422 myRank);
423 //
424 // Mesh cleanup
425 //
426 delete [] block_ids;
427 block_ids = NULL;
428 delete [] nodes_per_element;
429 nodes_per_element = NULL;
430 delete [] element_attributes;
431 element_attributes = NULL;
432 for (long long b = 0; b < numElemBlk; ++b) {
433 delete [] elmt_node_linkage[b];
434 delete [] element_types[b];
435 }
436 delete [] element_types;
437 element_types = NULL;
438 delete [] elmt_node_linkage;
439 elmt_node_linkage = NULL;
440 if (num_node_comm_maps > 0) {
441 delete [] node_comm_proc_ids;
442 node_comm_proc_ids = NULL;
443 delete [] node_cmap_node_cnts;
444 node_cmap_node_cnts = NULL;
445 delete [] node_cmap_ids;
446 node_cmap_ids = NULL;
447 for (long long i = 0; i < num_node_comm_maps; ++i) {
448 delete [] comm_node_ids[i];
449 delete [] comm_node_proc_ids[i];
450 }
451 delete [] comm_node_ids;
452 comm_node_ids = NULL;
453 delete [] comm_node_proc_ids;
454 comm_node_proc_ids = NULL;
455 }
456 delete [] elements;
457 elements = NULL;
458
459 // Container indicating whether a node is on the boundary (1-yes 0-no)
460 FieldContainer<int> nodeOnBoundary (numNodes);
461
462 // Get boundary (side set) information
463 long long * sideSetIds = new long long [numSideSets];
464 long long numSidesInSet;
465 long long numDFinSet;
466 im_ex_get_side_set_ids_l(id,sideSetIds);
467 for (int i=0; i < numSideSets; ++i) {
468 im_ex_get_side_set_param_l (id,sideSetIds[i], &numSidesInSet, &numDFinSet);
469 if (numSidesInSet > 0){
470 long long * sideSetElemList = new long long [numSidesInSet];
471 long long * sideSetSideList = new long long [numSidesInSet];
472 im_ex_get_side_set_l (id, sideSetIds[i], sideSetElemList, sideSetSideList);
473 for (int j = 0; j < numSidesInSet; ++j) {
474 int sideNode0 = cellType.getNodeMap(2,sideSetSideList[j]-1,0);
475 int sideNode1 = cellType.getNodeMap(2,sideSetSideList[j]-1,1);
476 int sideNode2 = cellType.getNodeMap(2,sideSetSideList[j]-1,2);
477 int sideNode3 = cellType.getNodeMap(2,sideSetSideList[j]-1,3);
478
479 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode0))=1;
480 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode1))=1;
481 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode2))=1;
482 nodeOnBoundary(elemToNode(sideSetElemList[j]-1,sideNode3))=1;
483 }
484 delete [] sideSetElemList;
485 delete [] sideSetSideList;
486 }
487 }
488 delete [] sideSetIds;
489
490 /**********************************************************************************/
491 /********************************* GET CUBATURE ***********************************/
492 /**********************************************************************************/
493
494 *out << "Getting cubature" << endl;
495
496 // Get numerical integration points and weights
497 DefaultCubatureFactory<ST> cubFactory;
498 int cubDegree = 2;
499 RCP<Cubature<ST> > hexCub = cubFactory.create (cellType, cubDegree);
500
501 int cubDim = hexCub->getDimension ();
502 int numCubPoints = hexCub->getNumPoints ();
503
504 FieldContainer<ST> cubPoints (numCubPoints, cubDim);
505 FieldContainer<ST> cubWeights (numCubPoints);
506
507 hexCub->getCubature (cubPoints, cubWeights);
508
509 /**********************************************************************************/
510 /*********************************** GET BASIS ************************************/
511 /**********************************************************************************/
512
513 *out << "Getting basis" << endl;
514
515 // Define basis
516 Basis_HGRAD_HEX_C1_FEM<ST, FieldContainer<ST> > hexHGradBasis;
517
518 int numFieldsG = hexHGradBasis.getCardinality ();
519 FieldContainer<ST> HGBValues (numFieldsG, numCubPoints);
520 FieldContainer<ST> HGBGrads (numFieldsG, numCubPoints, spaceDim);
521
522 // Evaluate basis values and gradients at cubature points
523 hexHGradBasis.getValues (HGBValues, cubPoints, OPERATOR_VALUE);
524 hexHGradBasis.getValues (HGBGrads, cubPoints, OPERATOR_GRAD);
525
526 /**********************************************************************************/
527 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
528 /**********************************************************************************/
529
530 *out << "Building Maps" << endl;
531
532 Array<GO> ownedGIDs;
533 RCP<const map_type> globalMapG;
534 Teuchos::Array<ST> coordXArray;
535 Teuchos::Array<ST> coordYArray;
536 Teuchos::Array<ST> coordZArray;
537 {
538 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Build global maps", build_maps);
539
540 // Count owned nodes
541 int ownedNodes = 0;
542 for (int i = 0; i < numNodes; ++i) {
543 if (nodeIsOwned[i]) {
544 ++ownedNodes;
545 }
546 }
547
548 // Build a list of the OWNED global ids...
549 // NTS: will need to switch back to long long
550 // Get owned coordinates
551 ownedGIDs.resize(ownedNodes);
552 coordXArray.resize(ownedNodes);
553 coordYArray.resize(ownedNodes);
554 coordZArray.resize(ownedNodes);
555
556 // It is expected that some nodes are duplicated locally
557 // so the values extracted with lNodePerDim are possibly
558 // wrong... Check that node i=0 and node i=nx are owned.
559 Teuchos::Array<LO> lNodesPerDimOld(3);
560 for(int k = 0; k < 3; ++k) {lNodesPerDimOld[k] = lNodesPerDim[k];}
561 // if(lNodesPerDimOld[0] > 2 && lNodesPerDimOld[1] > 2 && lNodesPerDimOld[2] > 2) {
562 // if(lNodesPerDimOld[0] >= 2 && lNodesPerDimOld[1] >= 2 && lNodesPerDimOld[2] >= 2) {
563 LO idx = 0;
564 Teuchos::Array<LO> factors(3);
565 for(int k = 0; k < 3; ++k) {factors[k] = lNodesPerDimOld[k] / 2;}
566
567 // check ilo face
568 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
569 + factors[1]*lNodesPerDimOld[0];
570 if(!nodeIsOwned[idx]) {--lNodesPerDim[0];}
571
572 // check ihi face
573 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
574 + factors[1]*lNodesPerDimOld[0] + lNodesPerDimOld[0] - 1;
575 if(!nodeIsOwned[idx]) {--lNodesPerDim[0];}
576
577 // check jlo face
578 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
579 + 0*lNodesPerDimOld[0] + factors[0];
580 if(!nodeIsOwned[idx]) {--lNodesPerDim[1];}
581
582 // check jhi face
583 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
584 + (lNodesPerDimOld[1] - 1)*lNodesPerDimOld[0] + factors[0];
585 if(!nodeIsOwned[idx]) {--lNodesPerDim[1];}
586
587 // check klo face
588 idx = 0*lNodesPerDimOld[1]*lNodesPerDimOld[0]
589 + factors[1]*lNodesPerDimOld[0] + factors[0];
590 if(!nodeIsOwned[idx]) {--lNodesPerDim[2];}
591
592 // check khi face
593 idx = (lNodesPerDimOld[2] - 1)*lNodesPerDimOld[1]*lNodesPerDimOld[0]
594 + factors[1]*lNodesPerDimOld[0] + factors[0];
595 if(!nodeIsOwned[idx]) {--lNodesPerDim[2];}
596 // }
597
598 int oidx = 0;
599 for (int i = 0; i < numNodes; ++i) {
600 if (nodeIsOwned[i]) {
601 ownedGIDs[oidx] = as<GO> (globalNodeIds[i]);
602
603 coordXArray[oidx] = nodeCoord(i,0);
604 coordYArray[oidx] = nodeCoord(i,1);
605 coordZArray[oidx] = nodeCoord(i,2);
606
607 ++oidx;
608 }
609 }
610 coordArray[0] = coordXArray;
611 coordArray[1] = coordYArray;
612 coordArray[2] = coordZArray;
613 globalMapG = rcp (new map_type (INVALID_GO, ownedGIDs (), 0, comm));
614 }
615
616 /**********************************************************************************/
617 /********************* BUILD MAPS FOR OVERLAPPED SOLUTION *************************/
618 /**********************************************************************************/
619
620 Array<GO> overlappedGIDs;
621 RCP<const map_type> overlappedMapG;
622 RCP<const export_type> exporter;
623 {
624 // Count owned nodes
625 int overlappedNodes = numNodes;
626
627 // Build a list of the OVERLAPPED global ids...
628 overlappedGIDs.resize (overlappedNodes);
629 for (int i = 0; i < numNodes; ++i) {
630 overlappedGIDs[i] = as<int> (globalNodeIds[i]);
631 }
632
633 //Generate overlapped Map for nodes.
634 overlappedMapG = rcp (new map_type (INVALID_GO, overlappedGIDs (), 0, comm));
635
636 // Build Tpetra Export from overlapped to owned Map.
637 exporter = rcp (new export_type (overlappedMapG, globalMapG));
638 }
639
640 /**********************************************************************************/
641 /********************* BUILD GRAPH FOR OVERLAPPED SOLUTION ************************/
642 /**********************************************************************************/
643
644 *out << "Building Graph" << endl;
645
646 RCP<sparse_graph_type> overlappedGraph;
647 RCP<sparse_graph_type> ownedGraph;
648 {
649 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Build matrix graph: 0-Total", graph_total);
650
651 // Construct Tpetra::CrsGraph objects.
652 overlappedGraph = rcp (new sparse_graph_type (overlappedMapG, 0));
653 ownedGraph = rcp (new sparse_graph_type (globalMapG, 0));
654
655 // Define desired workset size and count how many worksets
656 // there are on this process's mesh block.
657 //int desiredWorksetSize = numElems; // change to desired workset size!
658 int desiredWorksetSize = 100; // change to desired workset size!
659 int numWorksets = (numElems+desiredWorksetSize-1)/desiredWorksetSize;
660
661 for (int workset = 0; workset < numWorksets; ++workset) {
662 // Compute cell numbers where the workset starts and ends
663 int worksetBegin = (workset + 0)*desiredWorksetSize;
664 int worksetEnd = (workset + 1)*desiredWorksetSize;
665
666 // When numElems is not divisible by desiredWorksetSize, the
667 // last workset ends at numElems.
668 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
669
670 // Now we know the actual workset size and can allocate the
671 // array for the cell nodes.
672 //int worksetSize = worksetEnd - worksetBegin;
673
674 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
675 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
676 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
677 "Build matrix graph: 1-Insert global indices", graph_insert);
678
679 // Compute cell ordinal relative to the current workset
680 //int worksetCellOrdinal = cell - worksetBegin;
681
682 // "CELL EQUATION" loop for the workset cell: cellRow is
683 // relative to the cell DoF numbering
684 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
685
686 int localRow = elemToNode(cell, cellRow);
687 //globalRow for Tpetra Graph
688 global_size_t globalRowT = as<global_size_t> (globalNodeIds[localRow]);
689
690 // "CELL VARIABLE" loop for the workset cell: cellCol is
691 // relative to the cell DoF numbering
692 for (int cellCol = 0; cellCol < numFieldsG; ++cellCol) {
693 int localCol = elemToNode (cell, cellCol);
694 GO globalCol = as<GO> (globalNodeIds[localCol]);
695 //create ArrayView globalCol object for Tpetra
696 ArrayView<GO> globalColAV = arrayView (&globalCol, 1);
697
698 //Update Tpetra overlap Graph
699 overlappedGraph->insertGlobalIndices (globalRowT, globalColAV);
700 }// *** cell col loop ***
701 }// *** cell row loop ***
702 }// *** workset cell loop **
703 }// *** workset loop ***
704
705 // Fill-complete overlapping distribution Graph.
706 {
707 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
708 "Build matrix graph: 2-Overlapped fill complete",
709 overlapped_fill_complete);
710 overlappedGraph->fillComplete ();
711 }
712
713 // Export to owned distribution Graph, and fill-complete the latter.
714 {
715 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
716 "Build matrix graph: 3-Owned graph export", graph_export);
717 ownedGraph->doExport (*overlappedGraph, *exporter, Tpetra::INSERT);
718 }
719 {
720 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
721 "Build matrix graph: 4-Owned fill complete", owned_fill_complete);
722 ownedGraph->fillComplete ();
723 }
724 }
725
726 *out << "Constructing stiffness matrix and vectors" << endl;
727
728 //
729 // Construct stiffness matrix, right-hand side vector, and exact
730 // solution vector. The linear algebra objects starting with gl_
731 // are for the nonoverlapped ("owned") distribution; the ones not
732 // starting with gl_ are for the overlapped distribution. Once
733 // we've constructed the overlapped distribution objects, we'll
734 // Export to the owned distribution objects.
735 //
736 // Owned distribution objects: their names start with gl_.
737 //
738 RCP<sparse_matrix_type> gl_StiffMatrix =
739 rcp (new sparse_matrix_type (ownedGraph.getConst ()));
740 RCP<vector_type> gl_rhsVector = rcp (new vector_type (globalMapG));
741 // We compute the exact solution vector when we make v, and v has
742 // the owned distribution, so we only need an owned distribution
743 // version of the exact solution vector.
744 RCP<vector_type> gl_exactSolVector = rcp (new vector_type (globalMapG));
745
746 //
747 // Overlapped distribution objects: their names don't start with gl_.
748 //
749 RCP<sparse_matrix_type> StiffMatrix =
750 rcp (new sparse_matrix_type (overlappedGraph.getConst ()));
751 StiffMatrix->setAllToScalar (STS::zero ());
752 RCP<vector_type> rhsVector = rcp (new vector_type (overlappedMapG));
753 rhsVector->putScalar (STS::zero ());
754
755 /**********************************************************************************/
756 /************************** DIRICHLET BC SETUP ************************************/
757 /**********************************************************************************/
758
759 *out << "Setting up Dirichlet boundary conditions" << endl;
760
761 int numBCNodes = 0;
762 RCP<vector_type> v;
763 Array<int> BCNodes;
764 {
765 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Dirichlet BC setup", bc_setup);
766 for (int inode = 0; inode < numNodes; ++inode) {
767 if (nodeOnBoundary(inode) && nodeIsOwned[inode]) {
768 ++numBCNodes;
769 }
770 }
771 // v: Vector for use in applying Dirichlet BCs.
772 // v uses the owned (nonoverlapped) distribution.
773 v = rcp (new vector_type (globalMapG, true));
774 v->putScalar (STS::zero ());
775
776 // Set v to boundary values on Dirichlet nodes. While we're
777 // iterating through all the nodes that this process can see
778 // (which includes the nodes which my process owns, as well as
779 // nodes on the interface between my process and another process),
780 // also set the exact solution values.
781 BCNodes.resize (numBCNodes);
782 int indbc = 0;
783 int iOwned = 0;
784 for (int inode = 0; inode < numNodes; ++inode) {
785 if (nodeIsOwned[inode]) {
786 const ST x = nodeCoord(inode, 0);
787 const ST y = nodeCoord(inode, 1);
788 const ST z = nodeCoord(inode, 2);
789
790 if (nodeOnBoundary (inode)) {
791 BCNodes[indbc]=iOwned;
792 ++indbc;
793 // We assume that the exact solution is defined on the
794 // boundary, and evaluate the exact solution function to get
795 // boundary values.
796 v->replaceLocalValue (iOwned, exactSolution (x,y,z));
797 } // if node inode is on the boundary
798
799 gl_exactSolVector->replaceLocalValue (iOwned, exactSolution (x,y,z));
800 ++iOwned;
801 } // if node inode is owned by my process
802 } // for each node inode that my process can see
803 } // Done setting up v (for Dirichlet BCs) and gl_exactSolVector
804
805 /**********************************************************************************/
806 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
807 /**********************************************************************************/
808
809 *out << "Building discretization matrix and right hand side" << endl;
810
811 {
812 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
813 "Matrix/RHS fill: 0-Total", fill_total);
814
815 // Define desired workset size and count how many worksets there are
816 // on this processor's mesh block
817 //int desiredWorksetSize = numElems; // change to desired workset size!
818 int desiredWorksetSize = 100; // change to desired workset size!
819 int numWorksets = (numElems+desiredWorksetSize-1)/desiredWorksetSize;
820
821 {
822 Teuchos::OSTab tab2 (out);
823 *out << "Desired workset size: " << desiredWorksetSize << endl
824 << "Number of worksets (per process): " << numWorksets << endl;
825 }
826
827 for (int workset = 0; workset < numWorksets; ++workset) {
828
829 // Compute cell numbers where the workset starts and ends
830 int worksetBegin = (workset + 0)*desiredWorksetSize;
831 int worksetEnd = (workset + 1)*desiredWorksetSize;
832
833 // When numElems is not divisible by desiredWorksetSize, the last
834 // workset ends at numElems.
835 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
836
837 // Now we know the actual workset size and can allocate the array
838 // for the cell nodes.
839 int worksetSize = worksetEnd - worksetBegin;
840 FieldContainer<ST> cellWorkset (worksetSize, numNodesPerElem, spaceDim);
841
842 // Copy coordinates into cell workset
843 int cellCounter = 0;
844 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
845 for (int node = 0; node < numNodesPerElem; ++node) {
846 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
847 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
848 cellWorkset(cellCounter, node, 2) = nodeCoord( elemToNode(cell, node), 2);
849 }
850 ++cellCounter;
851 }
852
853 /**********************************************************************************/
854 /* Allocate arrays */
855 /**********************************************************************************/
856
857 // Containers for Jacobians, integration measure & cubature points in workset cells
858 FieldContainer<ST> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
859 FieldContainer<ST> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
860 FieldContainer<ST> worksetJacobDet (worksetSize, numCubPoints);
861 FieldContainer<ST> worksetCubWeights(worksetSize, numCubPoints);
862 FieldContainer<ST> worksetCubPoints (worksetSize, numCubPoints, cubDim);
863
864 // Containers for basis values transformed to workset cells and
865 // them multiplied by cubature weights
866 FieldContainer<ST> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
867 FieldContainer<ST> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
868 FieldContainer<ST> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
869 FieldContainer<ST> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
870
871 // Containers for diffusive & advective fluxes & non-conservative
872 // adv. term and reactive terms
873 FieldContainer<ST> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
874
875 // Containers for material values and source term. Require
876 // user-defined functions
877 FieldContainer<ST> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
878 FieldContainer<ST> worksetSourceTerm (worksetSize, numCubPoints);
879
880 // Containers for workset contributions to the discretization
881 // matrix and the right hand side
882 FieldContainer<ST> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
883 FieldContainer<ST> worksetRHS (worksetSize, numFieldsG);
884
885 {
886 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
887 "Matrix/RHS fill: 1-Element discretization", elem_discretization);
888
889 /**********************************************************************************/
890 /* Calculate Jacobians */
891 /**********************************************************************************/
892
893 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
894 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
895 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
896
897 /**********************************************************************************/
898 /* Cubature Points to Physical Frame and Compute Data */
899 /**********************************************************************************/
900
901 // Map cubature points to physical frame.
902 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, cellType);
903
904 // Evaluate the material tensor A at cubature points.
905 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
906
907 // Evaluate the source term at cubature points.
908 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
909
910 /**********************************************************************************/
911 /* Compute Stiffness Matrix */
912 /**********************************************************************************/
913
914 // Transform basis gradients to physical frame:
915 IntrepidFSTools::HGRADtransformGRAD<ST> (worksetHGBGrads, // DF^{-T}(grad u)
916 worksetJacobInv,
917 HGBGrads);
918 // Compute integration measure for workset cells:
919 IntrepidFSTools::computeCellMeasure<ST> (worksetCubWeights, // Det(DF)*w = J*w
920 worksetJacobDet,
921 cubWeights);
922 // Multiply transformed (workset) gradients with weighted measure
923 IntrepidFSTools::multiplyMeasure<ST> (worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
924 worksetCubWeights,
925 worksetHGBGrads);
926 // Compute the diffusive flux:
927 IntrepidFSTools::tensorMultiplyDataField<ST> (worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
928 worksetMaterialVals,
929 worksetHGBGrads);
930 // Integrate to compute workset diffusion contribution to global matrix:
931 IntrepidFSTools::integrate<ST> (worksetStiffMatrix, // (DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
932 worksetHGBGradsWeighted,
933 worksetDiffusiveFlux,
934 COMP_BLAS);
935
936 /**********************************************************************************/
937 /* Compute RHS */
938 /**********************************************************************************/
939
940 // Transform basis values to physical frame:
941 IntrepidFSTools::HGRADtransformVALUE<ST> (worksetHGBValues, // clones basis values (u)
942 HGBValues);
943 // Multiply transformed (workset) values with weighted measure
944 IntrepidFSTools::multiplyMeasure<ST> (worksetHGBValuesWeighted, // (u)*J*w
945 worksetCubWeights,
946 worksetHGBValues);
947 // Integrate worksetSourceTerm against weighted basis function set
948 IntrepidFSTools::integrate<ST> (worksetRHS, // f.(u)*J*w
949 worksetSourceTerm,
950 worksetHGBValuesWeighted,
951 COMP_BLAS);
952
953 } // Element discretization timer
954
955 /**********************************************************************************/
956 /* Assemble into Global Matrix */
957 /**********************************************************************************/
958
959 {
960 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
961 "Matrix/RHS fill: 2-Element assembly", elem_assembly_total);
962
963 // "WORKSET CELL" loop: local cell ordinal is relative to numElems
964 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
965
966 // Compute cell ordinal relative to the current workset
967 const int worksetCellOrdinal = cell - worksetBegin;
968
969 // "CELL EQUATION" loop for the workset cell: cellRow is
970 // relative to the cell DoF numbering.
971 for (int cellRow = 0; cellRow < numFieldsG; ++cellRow) {
972 int localRow = elemToNode (cell, cellRow);
973 ST sourceTermContribution = worksetRHS (worksetCellOrdinal, cellRow);
974
975 {
976 // TEUCHOS_FUNC_TIME_MONITOR_DIFF(
977 // "Matrix/RHS fill: 2a-RHS sum into local values",
978 // elem_rhs);
979 rhsVector->sumIntoLocalValue (localRow, sourceTermContribution);
980 }
981
982 // "CELL VARIABLE" loop for the workset cell: sum entire element
983 // stiff matrix contribution in one function call
984 ArrayView<int> localColAV =
985 arrayView<int> (&elemToNode(cell,0), numFieldsG);
986 ArrayView<ST> operatorMatrixContributionAV =
987 arrayView<ST> (&worksetStiffMatrix(worksetCellOrdinal,cellRow,0),
988 numFieldsG);
989 {
990 // TEUCHOS_FUNC_TIME_MONITOR_DIFF(
991 // "Matrix/RHS fill: 2b-Matrix sum into local values",
992 // elem_matrix);
993 StiffMatrix->sumIntoLocalValues (localRow, localColAV,
994 operatorMatrixContributionAV);
995 }
996 }// *** cell row loop ***
997 }// *** workset cell loop **
998 } // *** stop timer ***
999 }// *** workset loop ***
1000
1001 //////////////////////////////////////////////////////////////////////////////
1002 // Export sparse matrix and right-hand side from overlapping row Map
1003 // to owned (nonoverlapping) row Map.
1004 //////////////////////////////////////////////////////////////////////////////
1005
1006 *out << "Exporting matrix and right-hand side from overlapped to owned Map" << endl;
1007
1008 gl_StiffMatrix->setAllToScalar (STS::zero ());
1009 {
1010 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1011 "Matrix/RHS fill: 3-Matrix export", matrix_export);
1012 gl_StiffMatrix->doExport (*StiffMatrix, *exporter, Tpetra::ADD);
1013 }
1014 // If target of export has static graph, no need to do
1015 // setAllToScalar(0.0); export will clobber values.
1016 {
1017 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1018 "Matrix/RHS fill: 4-Matrix fill complete", matrix_fill_complete);
1019 gl_StiffMatrix->fillComplete ();
1020 }
1021
1022 gl_rhsVector->putScalar (STS::zero ());
1023 {
1024 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1025 "Matrix/RHS fill: 5-RHS export", rhs_export);
1026 gl_rhsVector->doExport (*rhsVector, *exporter, Tpetra::ADD);
1027 }
1028
1029 //////////////////////////////////////////////////////////////////////////////
1030 // Adjust matrix for boundary conditions
1031 //////////////////////////////////////////////////////////////////////////////
1032
1033 *out << "Adjusting matrix and right-hand side for BCs" << endl;
1034
1035 {
1036 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1037 "Matrix/RHS fill: 6-Dirichlet BC assembly", bc_assembly);
1038
1039 // Apply owned stiffness matrix to v: rhs := A*v
1040 RCP<multivector_type> rhsDir =
1041 rcp (new multivector_type (globalMapG, true));
1042 gl_StiffMatrix->apply (*v.getConst (), *rhsDir);
1043 // Update right-hand side
1044 gl_rhsVector->update (as<ST> (-STS::one ()), *rhsDir, STS::one ());
1045
1046 // Get a const view of the vector's local data.
1047 ArrayRCP<const ST> vArrayRCP = v->getData (0);
1048
1049 // Adjust rhs due to Dirichlet boundary conditions.
1050 for (int inode = 0; inode < numNodes; ++inode) {
1051 if (nodeIsOwned[inode]) {
1052 if (nodeOnBoundary (inode)) {
1053 // Get global node ID
1054 const GO gni = as<GO> (globalNodeIds[inode]);
1055 const LO lidT = globalMapG->getLocalElement (gni);
1056 ST v_valT = vArrayRCP[lidT];
1057 gl_rhsVector->replaceGlobalValue (gni, v_valT);
1058 }
1059 }
1060 }
1061
1062 // Zero out rows and columns of stiffness matrix corresponding to
1063 // Dirichlet edges and add one to diagonal. The following is the
1064 // Tpetra analog of Apply_OAZToMatrix().
1065 //
1066 // Reenable changes to the values and structure of the global
1067 // stiffness matrix.
1068 gl_StiffMatrix->resumeFill ();
1069
1070 // Find the local column numbers to nuke
1071 RCP<const map_type> ColMap = gl_StiffMatrix->getColMap ();
1072 RCP<const map_type> globalMap =
1073 rcp (new map_type (gl_StiffMatrix->getGlobalNumCols (), 0, comm,
1074 Tpetra::GloballyDistributed));
1075
1076 // Create the exporter from this process' column Map to the global
1077 // 1-1 column map. (???)
1078 RCP<const export_type> bdyExporter =
1079 rcp (new export_type (ColMap, globalMap));
1080 // Create a vector of global column indices to which we will export
1081 RCP<Tpetra::Vector<int, LO, GO, Node> > globColsToZeroT =
1082 rcp (new Tpetra::Vector<int, LO, GO, Node> (globalMap));
1083 // Create a vector of local column indices from which we will export
1084 RCP<Tpetra::Vector<int, LO, GO, Node> > myColsToZeroT =
1085 rcp (new Tpetra::Vector<int, LO, GO, Node> (ColMap));
1086 myColsToZeroT->putScalar (0);
1087
1088 // Flag (set to 1) all local columns corresponding to the local
1089 // rows specified.
1090 for (int i = 0; i < numBCNodes; ++i) {
1091 const GO globalRow = gl_StiffMatrix->getRowMap ()->getGlobalElement (BCNodes[i]);
1092 const LO localCol = gl_StiffMatrix->getColMap ()->getLocalElement (globalRow);
1093 // Tpetra::Vector<int, ...> works just like
1094 // Tpetra::Vector<double, ...>. Epetra has a separate
1095 // Epetra_IntVector class for ints.
1096 myColsToZeroT->replaceLocalValue (localCol, 1);
1097 }
1098
1099 // Export to the global column map.
1100 globColsToZeroT->doExport (*myColsToZeroT, *bdyExporter, Tpetra::ADD);
1101 // Import from the global column map to the local column map.
1102 myColsToZeroT->doImport (*globColsToZeroT, *bdyExporter, Tpetra::INSERT);
1103
1104 ArrayRCP<const int> myColsToZeroArrayRCP = myColsToZeroT->getData(0);
1105 size_t NumEntries = 0;
1106
1107 // Zero the columns corresponding to Dirichlet BCs.
1108 typename sparse_matrix_type::nonconst_local_inds_host_view_type indices("indices", 1);
1109 typename sparse_matrix_type::nonconst_values_host_view_type values("values", 1);
1110 for (LO i = 0; i < as<int> (gl_StiffMatrix->getLocalNumRows ()); ++i) {
1111 NumEntries = gl_StiffMatrix->getNumEntriesInLocalRow (i);
1112 Kokkos::resize(indices, NumEntries);
1113 Kokkos::resize(values, NumEntries);
1114 gl_StiffMatrix->getLocalRowCopy (i, indices, values, NumEntries);
1115 for (int j = 0; j < as<int> (NumEntries); ++j) {
1116 if (myColsToZeroArrayRCP[indices(j)] == 1)
1117 values(j) = STS::zero ();
1118 }
1119 gl_StiffMatrix->replaceLocalValues (i, indices, values);
1120 } // for each (local) row of the global stiffness matrix
1121
1122 // Zero the rows and add ones to diagonal.
1123 for (int i = 0; i < numBCNodes; ++i) {
1124 NumEntries = gl_StiffMatrix->getNumEntriesInLocalRow (BCNodes[i]);
1125 Kokkos::resize(indices, NumEntries);
1126 Kokkos::resize(values, NumEntries);
1127 gl_StiffMatrix->getLocalRowCopy (BCNodes[i], indices, values, NumEntries);
1128 const GO globalRow = gl_StiffMatrix->getRowMap ()->getGlobalElement (BCNodes[i]);
1129 const LO localCol = gl_StiffMatrix->getColMap ()->getLocalElement (globalRow);
1130 for (int j = 0; j < as<int> (NumEntries); ++j) {
1131 values(j) = STS::zero ();
1132 if (indices(j) == localCol) {
1133 values(j) = STS::one ();
1134 }
1135 } // for each entry in the current row
1136 gl_StiffMatrix->replaceLocalValues (BCNodes[i], indices, values);
1137 } // for each BC node
1138 }
1139
1140 *out << "Calling fillComplete() on owned-Map stiffness matrix" << endl;
1141
1142 // We're done modifying the owned stiffness matrix.
1143 gl_StiffMatrix->fillComplete ();
1144
1145 } // Matrix/RHS fill timing
1146
1147 //
1148 // We're done with assembly, so we can delete the mesh.
1149 //
1150 delete [] nodeIsOwned;
1151 nodeIsOwned = NULL;
1152 Delete_Pamgen_Mesh ();
1153
1154 // Create vector to store approximate solution, and set initial guess.
1155 RCP<vector_type> gl_approxSolVector = rcp (new vector_type (globalMapG));
1156 gl_approxSolVector->putScalar (STS::zero ());
1157
1158 // Store the output pointers.
1159 A = gl_StiffMatrix;
1160 B = gl_rhsVector;
1161 X_exact = gl_exactSolVector;
1162 X = gl_approxSolVector;
1163 }
1164
1165 std::vector<Teuchos::ScalarTraits<ST>::magnitudeType>
1166 exactResidualNorm (const Teuchos::RCP<const sparse_matrix_type>& A,
1167 const Teuchos::RCP<const vector_type>& B,
1168 const Teuchos::RCP<const vector_type>& X_exact)
1169 {
1170 using Teuchos::RCP;
1171 using Teuchos::rcp;
1172 typedef Teuchos::ScalarTraits<ST> STS;
1173 typedef STS::magnitudeType MT;
1174
1175 RCP<vector_type> R = rcp (new vector_type (*B)); // R := B
1176 // R := 1.0*R - 1.0*A*X_exact.
1177 A->apply (*X_exact, *R, Teuchos::NO_TRANS, -STS::one(), STS::one());
1178
1179 std::vector<MT> results (3);
1180 results[0] = R->norm2 ();
1181 results[1] = B->norm2 ();
1182 results[2] = A->getFrobeniusNorm ();
1183 return results;
1184 }
1185
1186 /**********************************************************************************/
1187 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1188 /**********************************************************************************/
1189
1190 template<typename Scalar>
1191 const Scalar
1192 exactSolution (const Scalar& x, const Scalar& y, const Scalar& z)
1193 {
1194 // Patch test: tri-linear function is in the FE space and should be recovered
1195 return 1. + x + y + z + x*y + x*z + y*z + x*y*z;
1196
1197 // Analytic solution with homogeneous Dirichlet boundary data
1198 // return sin(M_PI*x)*sin(M_PI*y)*sin(M_PI*z)*exp(x+y+z);
1199
1200 // Analytic solution with inhomogeneous Dirichlet boundary data
1201 // return exp(x + y + z)/(1. + x*y + y*z + x*y*z);
1202 }
1203
1204
1205 using ::TrilinosCouplings::IntrepidPoissonExample::getMaterialTensorOffDiagonalValue;
1206
1207 /** \brief User-defined material tensor.
1208
1209 Evaluate the tensor using operator(). Its arguments are:
1210
1211 \param material [out] 3 x 3 material tensor evaluated at (x,y,z)
1212 \param x [in] x-coordinate of the evaluation point
1213 \param y [in] y-coordinate of the evaluation point
1214 \param z [in] z-coordinate of the evaluation point
1215
1216 \warning Symmetric and positive definite tensor is required for every (x,y,z).
1217 */
1218 template<typename Scalar>
1219 class MaterialTensor {
1220 public:
1221 MaterialTensor (const double offDiagVal) :
1222 offDiagVal_ (Scalar (offDiagVal))
1223 {}
1224
1225 void
1226 operator () (Scalar material[][3],
1227 const Scalar& x,
1228 const Scalar& y,
1229 const Scalar& z) const
1230 {
1231 typedef Teuchos::ScalarTraits<Scalar> STS;
1232
1233 // We go through this trouble to make numbers, because Scalar
1234 // isn't necessarily double. It could be some automatic
1235 // differentiation type.
1236 const Scalar zero = STS::zero ();
1237 const Scalar one = STS::one ();
1238
1239 // You can use the value of offDiagVal_ to control the iteration
1240 // count. The iteration counts below are for Belos' GMRES with no
1241 // preconditioning, using the default problem size.
1242 // setMaterialTensorOffDiagonalValue() sets the value of this
1243 // parameter.
1244 //
1245 // Classical elasticity assumes a symmetric material tensor. I
1246 // suppose one could solve Poisson's equation with an unsymmetric
1247 // material tensor, but I'm not sure what that would mean.
1248
1249 // offDiagVal_ = -5/4: 209 iterations (CG breaks!)
1250 // offDiagVal_ = -1/2: 47 iterations
1251 // offDiagVal_ = 0: 40 iterations (CG works)
1252 // offDiagVal_ = 1/2: 46 iterations
1253 // offDiagVal_ = 3/4: 47 iterations
1254 // offDiagVal_ = 1: 59 iterations
1255 // offDiagVal_ = 5/4: 183 iterations
1256 // offDiagVal_ = 3/2: 491 iterations
1257 // offDiagVal_ = 2: 939 iterations (CG breaks!)
1258 material[0][0] = one;
1259 material[0][1] = zero;
1260 material[0][2] = offDiagVal_;
1261
1262 material[1][0] = zero;
1263 material[1][1] = one;
1264 material[1][2] = zero;
1265
1266 material[2][0] = offDiagVal_;
1267 material[2][1] = zero;
1268 material[2][2] = one;
1269 }
1270
1271 private:
1272 const Scalar offDiagVal_;
1273 };
1274
1275 /**********************************************************************************/
1276 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1277 /**********************************************************************************/
1278
1279 /// \brief Compute gradient of exact solution at (x,y,z).
1280 ///
1281 /// \param gradExact [out] The gradient at (x,y,z).
1282 /// \param x [in]
1283 /// \param y [in]
1284 /// \param z [in]
1285 template<typename Scalar>
1286 void
1287 exactSolutionGrad (Scalar gradExact[3],
1288 const Scalar& x,
1289 const Scalar& y,
1290 const Scalar& z)
1291 {
1292 // To enable taking derivatives of the gradient (that is, second
1293 // derivatives of the exact solution), we need 2 levels of fad
1294 // types.
1295 Sacado::Fad::SFad<Scalar,3> fad_x = x;
1296 Sacado::Fad::SFad<Scalar,3> fad_y = y;
1297 Sacado::Fad::SFad<Scalar,3> fad_z = z;
1298 Sacado::Fad::SFad<Scalar,3> u;
1299
1300 // Indicate the independent variables
1301 fad_x.diff(0,3);
1302 fad_y.diff(1,3);
1303 fad_z.diff(2,3);
1304
1305 u = exactSolution(fad_x, fad_y, fad_z);
1306
1307 gradExact[0] = u.dx(0);
1308 gradExact[1] = u.dx(1);
1309 gradExact[2] = u.dx(2);
1310 }
1311
1312 /// \brief Compute the source term (right-hand side) at (x,y,z).
1313 ///
1314 /// We compute the source term from the exact solution, its gradient,
1315 /// and the material tensor at (x,y,z).
1316 template<typename Scalar>
1317 const Scalar
1318 sourceTerm (Scalar& x, Scalar& y, Scalar& z)
1319 {
1320 Scalar u;
1321 Scalar grad_u[3];
1322 Scalar flux[3] = {0.0, 0.0, 0.0};
1323 Scalar material[3][3];
1324 Scalar f = 0.;
1325
1326 // Indicate the independent variables
1327 x.diff(0,3);
1328 y.diff(1,3);
1329 z.diff(2,3);
1330
1331 // Get exact solution and its gradient
1332 u = exactSolution (x, y, z);
1333 exactSolutionGrad (grad_u, x, y, z);
1334
1335 // Get material tensor
1336 MaterialTensor<Scalar> matTens (getMaterialTensorOffDiagonalValue ());
1337 matTens (material, x, y, z);
1338
1339 // Compute total flux = (A.grad u)
1340 for (int i = 0; i < 3; ++i) {
1341 // Add diffusive flux
1342 for (int j = 0; j < 3; ++j) {
1343 flux[i] += material[i][j]*grad_u[j];
1344 }
1345 }
1346
1347 // Compute source term (right hand side): f = -div(A.grad u)
1348 f = -(flux[0].dx(0) + flux[1].dx(1) + flux[2].dx(2));
1349
1350 return f;
1351 }
1352
1353 /**********************************************************************************/
1354 /*************************** EVALUATION METHODS ***********************************/
1355 /**********************************************************************************/
1356
1357 //! Compute the material tensor over a workset.
1358 template<class ArrayOut, class ArrayIn>
1359 void
1360 evaluateMaterialTensor (ArrayOut& matTensorValues,
1361 const ArrayIn& evaluationPoints)
1362 {
1363 typedef typename ArrayOut::scalar_type scalar_type;
1364
1365 const int numWorksetCells = evaluationPoints.dimension(0);
1366 const int numPoints = evaluationPoints.dimension(1);
1367 const int spaceDim = evaluationPoints.dimension(2);
1368
1369 scalar_type material[3][3];
1370
1371 MaterialTensor<scalar_type> matTens (getMaterialTensorOffDiagonalValue ());
1372 for (int cell = 0; cell < numWorksetCells; ++cell) {
1373 for (int pt = 0; pt < numPoints; ++pt) {
1374 scalar_type x = evaluationPoints(cell, pt, 0);
1375 scalar_type y = evaluationPoints(cell, pt, 1);
1376 scalar_type z = evaluationPoints(cell, pt, 2);
1377
1378 matTens (material, x, y, z);
1379
1380 for (int row = 0; row < spaceDim; ++row) {
1381 for(int col = 0; col < spaceDim; ++col) {
1382 matTensorValues(cell, pt, row, col) = material[row][col];
1383 }
1384 }
1385 }
1386 }
1387 }
1388
1389 /************ Source Term (RHS) ****************/
1390 template<class ArrayOut, class ArrayIn>
1391 void
1392 evaluateSourceTerm (ArrayOut& sourceTermValues,
1393 const ArrayIn& evaluationPoints)
1394 {
1395 typedef typename ArrayOut::scalar_type scalar_type;
1396
1397 const int numWorksetCells = evaluationPoints.dimension(0);
1398 const int numPoints = evaluationPoints.dimension(1);
1399
1400 for (int cell = 0; cell < numWorksetCells; ++cell) {
1401 for (int pt = 0; pt < numPoints; ++pt) {
1402 Sacado::Fad::SFad<scalar_type,3> x = evaluationPoints(cell, pt, 0);
1403 Sacado::Fad::SFad<scalar_type,3> y = evaluationPoints(cell, pt, 1);
1404 Sacado::Fad::SFad<scalar_type,3> z = evaluationPoints(cell, pt, 2);
1405
1406 sourceTermValues(cell, pt) =
1407 sourceTerm<Sacado::Fad::SFad<scalar_type,3> > (x, y, z).val ();
1408 }
1409 }
1410 }
1411
1412 /************ Exact Solution ****************/
1413 template<class ArrayOut, class ArrayIn>
1414 void
1415 evaluateExactSolution (ArrayOut& exactSolutionValues,
1416 const ArrayIn& evaluationPoints)
1417 {
1418 typedef typename ArrayOut::scalar_type scalar_type;
1419
1420 const int numWorksetCells = evaluationPoints.dimension(0);
1421 const int numPoints = evaluationPoints.dimension(1);
1422
1423 for (int cell = 0; cell < numWorksetCells; ++cell) {
1424 for (int pt = 0; pt < numPoints; ++pt) {
1425 const scalar_type x = evaluationPoints(cell, pt, 0);
1426 const scalar_type y = evaluationPoints(cell, pt, 1);
1427 const scalar_type z = evaluationPoints(cell, pt, 2);
1428 exactSolutionValues(cell, pt) = exactSolution<scalar_type> (x, y, z);
1429 }
1430 }
1431 }
1432
1433 /************ Grad of Exact Solution ****************/
1434 template<class ArrayOut, class ArrayIn>
1435 void
1436 evaluateExactSolutionGrad (ArrayOut& exactSolutionGradValues,
1437 const ArrayIn& evaluationPoints)
1438 {
1439 typedef typename ArrayOut::scalar_type scalar_type;
1440
1441 const int numWorksetCells = evaluationPoints.dimension(0);
1442 const int numPoints = evaluationPoints.dimension(1);
1443 const int spaceDim = evaluationPoints.dimension(2);
1444
1445 scalar_type gradient[3];
1446
1447 for (int cell = 0; cell < numWorksetCells; ++cell) {
1448 for (int pt = 0; pt < numPoints; ++pt) {
1449 const scalar_type x = evaluationPoints(cell, pt, 0);
1450 const scalar_type y = evaluationPoints(cell, pt, 1);
1451 const scalar_type z = evaluationPoints(cell, pt, 2);
1452
1453 exactSolutionGrad<scalar_type> (gradient, x, y, z);
1454
1455 for (int row = 0; row < spaceDim; ++row) {
1456 exactSolutionGradValues(cell, pt, row) = gradient[row];
1457 }
1458 }
1459 }
1460 }
1461
1462 } // namespace TpetraIntrepidPoissonExample
1463 } // namespace TrilinosCouplings