Debian Codegraph @

packages/trilinoscouplings/examples/scaling/TrilinosCouplings_TpetraIntrepidStructuredPoissonExample.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_TpetraIntrepidStructuredPoissonExample.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<MT> >& 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<MT> >& 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<MT> nodeCoord (numNodes, dim);
340 MT * nodeCoordx = new MT [numNodes];
341 MT * nodeCoordy = new MT [numNodes];
342 MT * nodeCoordz = new MT [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 int numFieldsG = hexHGradBasis.getCardinality ();
518 FieldContainer<ST> HGBValues (numFieldsG, numCubPoints);
519 FieldContainer<ST> HGBGrads (numFieldsG, numCubPoints, spaceDim);
520
521 // Evaluate basis values and gradients at cubature points
522 hexHGradBasis.getValues (HGBValues, cubPoints, OPERATOR_VALUE);
523 hexHGradBasis.getValues (HGBGrads, cubPoints, OPERATOR_GRAD);
524
525 /**********************************************************************************/
526 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
527 /**********************************************************************************/
528
529 *out << "Building Maps" << endl;
530
531 Array<GO> ownedGIDs;
532 RCP<const map_type> globalMapG;
533 {
534 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Build global maps", build_maps);
535
536 // Count owned nodes
537 int ownedNodes = 0;
538 for (int i = 0; i < numNodes; ++i) {
539 if (nodeIsOwned[i]) {
540 ++ownedNodes;
541 }
542 }
543
544 // Build a list of the OWNED global ids...
545 // NTS: will need to switch back to long long
546 // Get owned coordinates
547 ownedGIDs.resize(ownedNodes);
548 coordArray[0].resize(ownedNodes);
549 coordArray[1].resize(ownedNodes);
550 coordArray[2].resize(ownedNodes);
551
552 // It is expected that some nodes are duplicated locally
553 // so the values extracted with lNodePerDim are possibly
554 // wrong... Check that node i=0 and node i=nx are owned.
555 Teuchos::Array<LO> lNodesPerDimOld(3);
556 for(int k = 0; k < 3; ++k) {lNodesPerDimOld[k] = lNodesPerDim[k];}
557 if(lNodesPerDimOld[0] > 2 && lNodesPerDimOld[1] > 2 && lNodesPerDimOld[2] > 2) {
558 LO idx = 0;
559 Teuchos::Array<LO> factors(3);
560 for(int k = 0; k < 3; ++k) {factors[k] = lNodesPerDimOld[k] / 2;}
561
562 // check ilo face
563 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
564 + factors[1]*lNodesPerDimOld[0];
565 if(!nodeIsOwned[idx]) {--lNodesPerDim[0];}
566
567 // check ihi face
568 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
569 + factors[1]*lNodesPerDimOld[0] + lNodesPerDimOld[0] - 1;
570 if(!nodeIsOwned[idx]) {--lNodesPerDim[0];}
571
572 // check jlo face
573 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
574 + 0*lNodesPerDimOld[0] + factors[0];
575 if(!nodeIsOwned[idx]) {--lNodesPerDim[1];}
576
577 // check jhi face
578 idx = factors[2]*lNodesPerDimOld[1]*lNodesPerDimOld[0]
579 + (lNodesPerDimOld[1] - 1)*lNodesPerDimOld[0] + factors[0];
580 if(!nodeIsOwned[idx]) {--lNodesPerDim[1];}
581
582 // check klo face
583 idx = 0*lNodesPerDimOld[1]*lNodesPerDimOld[0]
584 + factors[1]*lNodesPerDimOld[0] + factors[0];
585 if(!nodeIsOwned[idx]) {--lNodesPerDim[2];}
586
587 // check khi face
588 idx = (lNodesPerDimOld[2] - 1)*lNodesPerDimOld[1]*lNodesPerDimOld[0]
589 + factors[1]*lNodesPerDimOld[0] + factors[0];
590 if(!nodeIsOwned[idx]) {--lNodesPerDim[2];}
591 }
592
593 int oidx = 0;
594 for (int i = 0; i < numNodes; ++i) {
595 if (nodeIsOwned[i]) {
596 ownedGIDs[oidx] = as<int> (globalNodeIds[i]);
597
598 coordArray[0][oidx] = nodeCoord(i,0);
599 coordArray[1][oidx] = nodeCoord(i,1);
600 coordArray[2][oidx] = nodeCoord(i,2);
601
602 ++oidx;
603 }
604 }
605 globalMapG = rcp (new map_type (INVALID_GO, ownedGIDs (), 0, comm));
606 }
607
608 /**********************************************************************************/
609 /********************* BUILD MAPS FOR OVERLAPPED SOLUTION *************************/
610 /**********************************************************************************/
611
612 Array<GO> overlappedGIDs;
613 RCP<const map_type> overlappedMapG;
614 RCP<const export_type> exporter;
615 {
616 // Count owned nodes
617 int overlappedNodes = numNodes;
618
619 // Build a list of the OVERLAPPED global ids...
620 overlappedGIDs.resize (overlappedNodes);
621 for (int i = 0; i < numNodes; ++i) {
622 overlappedGIDs[i] = as<int> (globalNodeIds[i]);
623 }
624
625 //Generate overlapped Map for nodes.
626 overlappedMapG = rcp (new map_type (INVALID_GO, overlappedGIDs (), 0, comm));
627
628 // Build Tpetra Export from overlapped to owned Map.
629 exporter = rcp (new export_type (overlappedMapG, globalMapG));
630 }
631
632 /**********************************************************************************/
633 /********************* BUILD GRAPH FOR OVERLAPPED SOLUTION ************************/
634 /**********************************************************************************/
635
636 *out << "Building Graph" << endl;
637
638 RCP<sparse_graph_type> overlappedGraph;
639 RCP<sparse_graph_type> ownedGraph;
640 {
641 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Build matrix graph: 0-Total", graph_total);
642
643 // Construct Tpetra::CrsGraph objects.
644 overlappedGraph = rcp (new sparse_graph_type (overlappedMapG, 27));
645 ownedGraph = rcp (new sparse_graph_type (globalMapG, 0));
646
647 // Define desired workset size and count how many worksets
648 // there are on this process's mesh block.
649 //int desiredWorksetSize = numElems; // change to desired workset size!
650 int desiredWorksetSize = 100; // change to desired workset size!
651 int numWorksets = (numElems+desiredWorksetSize-1)/desiredWorksetSize;
652
653 for (int workset = 0; workset < numWorksets; ++workset) {
654 // Compute cell numbers where the workset starts and ends
655 int worksetBegin = (workset + 0)*desiredWorksetSize;
656 int worksetEnd = (workset + 1)*desiredWorksetSize;
657
658 // When numElems is not divisible by desiredWorksetSize, the
659 // last workset ends at numElems.
660 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
661
662 // Now we know the actual workset size and can allocate the
663 // array for the cell nodes.
664 //int worksetSize = worksetEnd - worksetBegin;
665
666 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
667 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
668 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
669 "Build matrix graph: 1-Insert global indices", graph_insert);
670
671 // Compute cell ordinal relative to the current workset
672 //int worksetCellOrdinal = cell - worksetBegin;
673
674 // "CELL EQUATION" loop for the workset cell: cellRow is
675 // relative to the cell DoF numbering
676 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
677
678 int localRow = elemToNode(cell, cellRow);
679 //globalRow for Tpetra Graph
680 global_size_t globalRowT = as<global_size_t> (globalNodeIds[localRow]);
681
682 // "CELL VARIABLE" loop for the workset cell: cellCol is
683 // relative to the cell DoF numbering
684 for (int cellCol = 0; cellCol < numFieldsG; ++cellCol) {
685 int localCol = elemToNode (cell, cellCol);
686 GO globalCol = as<GO> (globalNodeIds[localCol]);
687 //create ArrayView globalCol object for Tpetra
688 ArrayView<GO> globalColAV = arrayView (&globalCol, 1);
689
690 //Update Tpetra overlap Graph
691 overlappedGraph->insertGlobalIndices (globalRowT, globalColAV);
692 }// *** cell col loop ***
693 }// *** cell row loop ***
694 }// *** workset cell loop **
695 }// *** workset loop ***
696
697 // Fill-complete overlapping distribution Graph.
698 {
699 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
700 "Build matrix graph: 2-Overlapped fill complete",
701 overlapped_fill_complete);
702 overlappedGraph->fillComplete ();
703 }
704
705 // Export to owned distribution Graph, and fill-complete the latter.
706 {
707 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
708 "Build matrix graph: 3-Owned graph export", graph_export);
709 ownedGraph->doExport (*overlappedGraph, *exporter, Tpetra::INSERT);
710 }
711 {
712 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
713 "Build matrix graph: 4-Owned fill complete", owned_fill_complete);
714 ownedGraph->fillComplete ();
715 }
716 }
717
718 *out << "Constructing stiffness matrix and vectors" << endl;
719
720 //
721 // Construct stiffness matrix, right-hand side vector, and exact
722 // solution vector. The linear algebra objects starting with gl_
723 // are for the nonoverlapped ("owned") distribution; the ones not
724 // starting with gl_ are for the overlapped distribution. Once
725 // we've constructed the overlapped distribution objects, we'll
726 // Export to the owned distribution objects.
727 //
728 // Owned distribution objects: their names start with gl_.
729 //
730 RCP<sparse_matrix_type> gl_StiffMatrix =
731 rcp (new sparse_matrix_type (ownedGraph.getConst ()));
732 RCP<vector_type> gl_rhsVector = rcp (new vector_type (globalMapG));
733 // We compute the exact solution vector when we make v, and v has
734 // the owned distribution, so we only need an owned distribution
735 // version of the exact solution vector.
736 RCP<vector_type> gl_exactSolVector = rcp (new vector_type (globalMapG));
737
738 //
739 // Overlapped distribution objects: their names don't start with gl_.
740 //
741 RCP<sparse_matrix_type> StiffMatrix =
742 rcp (new sparse_matrix_type (overlappedGraph.getConst ()));
743 StiffMatrix->setAllToScalar (STS::zero ());
744 RCP<vector_type> rhsVector = rcp (new vector_type (overlappedMapG));
745 rhsVector->putScalar (STS::zero ());
746
747 /**********************************************************************************/
748 /************************** DIRICHLET BC SETUP ************************************/
749 /**********************************************************************************/
750
751 *out << "Setting up Dirichlet boundary conditions" << endl;
752
753 int numBCNodes = 0;
754 RCP<vector_type> v;
755 Array<int> BCNodes;
756 {
757 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Dirichlet BC setup", bc_setup);
758 for (int inode = 0; inode < numNodes; ++inode) {
759 if (nodeOnBoundary(inode) && nodeIsOwned[inode]) {
760 ++numBCNodes;
761 }
762 }
763 // v: Vector for use in applying Dirichlet BCs.
764 // v uses the owned (nonoverlapped) distribution.
765 v = rcp (new vector_type (globalMapG, true));
766 v->putScalar (STS::zero ());
767
768 // Set v to boundary values on Dirichlet nodes. While we're
769 // iterating through all the nodes that this process can see
770 // (which includes the nodes which my process owns, as well as
771 // nodes on the interface between my process and another process),
772 // also set the exact solution values.
773 BCNodes.resize (numBCNodes);
774 int indbc = 0;
775 int iOwned = 0;
776 for (int inode = 0; inode < numNodes; ++inode) {
777 if (nodeIsOwned[inode]) {
778 const ST x = nodeCoord(inode, 0);
779 const ST y = nodeCoord(inode, 1);
780 const ST z = nodeCoord(inode, 2);
781
782 if (nodeOnBoundary (inode)) {
783 BCNodes[indbc]=iOwned;
784 ++indbc;
785 // We assume that the exact solution is defined on the
786 // boundary, and evaluate the exact solution function to get
787 // boundary values.
788 v->replaceLocalValue (iOwned, exactSolution (x,y,z));
789 } // if node inode is on the boundary
790
791 gl_exactSolVector->replaceLocalValue (iOwned, exactSolution (x,y,z));
792 ++iOwned;
793 } // if node inode is owned by my process
794 } // for each node inode that my process can see
795 } // Done setting up v (for Dirichlet BCs) and gl_exactSolVector
796
797 /**********************************************************************************/
798 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
799 /**********************************************************************************/
800
801 *out << "Building discretization matrix and right hand side" << endl;
802
803 {
804 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
805 "Matrix/RHS fill: 0-Total", fill_total);
806
807 // Define desired workset size and count how many worksets there are
808 // on this processor's mesh block
809 //int desiredWorksetSize = numElems; // change to desired workset size!
810 int desiredWorksetSize = 100; // change to desired workset size!
811 int numWorksets = (numElems+desiredWorksetSize-1)/desiredWorksetSize;
812
813 {
814 Teuchos::OSTab tab2 (out);
815 *out << "Desired workset size: " << desiredWorksetSize << endl
816 << "Number of worksets (per process): " << numWorksets << endl;
817 }
818
819 for (int workset = 0; workset < numWorksets; ++workset) {
820
821 // Compute cell numbers where the workset starts and ends
822 int worksetBegin = (workset + 0)*desiredWorksetSize;
823 int worksetEnd = (workset + 1)*desiredWorksetSize;
824
825 // When numElems is not divisible by desiredWorksetSize, the last
826 // workset ends at numElems.
827 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
828
829 // Now we know the actual workset size and can allocate the array
830 // for the cell nodes.
831 int worksetSize = worksetEnd - worksetBegin;
832 FieldContainer<ST> cellWorkset (worksetSize, numNodesPerElem, spaceDim);
833
834 // Copy coordinates into cell workset
835 int cellCounter = 0;
836 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
837 for (int node = 0; node < numNodesPerElem; ++node) {
838 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
839 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
840 cellWorkset(cellCounter, node, 2) = nodeCoord( elemToNode(cell, node), 2);
841 }
842 ++cellCounter;
843 }
844
845 /**********************************************************************************/
846 /* Allocate arrays */
847 /**********************************************************************************/
848
849 // Containers for Jacobians, integration measure & cubature points in workset cells
850 FieldContainer<ST> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
851 FieldContainer<ST> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
852 FieldContainer<ST> worksetJacobDet (worksetSize, numCubPoints);
853 FieldContainer<ST> worksetCubWeights(worksetSize, numCubPoints);
854 FieldContainer<ST> worksetCubPoints (worksetSize, numCubPoints, cubDim);
855
856 // Containers for basis values transformed to workset cells and
857 // them multiplied by cubature weights
858 FieldContainer<ST> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
859 FieldContainer<ST> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
860 FieldContainer<ST> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
861 FieldContainer<ST> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
862
863 // Containers for diffusive & advective fluxes & non-conservative
864 // adv. term and reactive terms
865 FieldContainer<ST> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
866
867 // Containers for material values and source term. Require
868 // user-defined functions
869 FieldContainer<ST> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
870 FieldContainer<ST> worksetSourceTerm (worksetSize, numCubPoints);
871
872 // Containers for workset contributions to the discretization
873 // matrix and the right hand side
874 FieldContainer<ST> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
875 FieldContainer<ST> worksetRHS (worksetSize, numFieldsG);
876
877 {
878 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
879 "Matrix/RHS fill: 1-Element discretization", elem_discretization);
880
881 /**********************************************************************************/
882 /* Calculate Jacobians */
883 /**********************************************************************************/
884
885 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
886 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
887 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
888
889 /**********************************************************************************/
890 /* Cubature Points to Physical Frame and Compute Data */
891 /**********************************************************************************/
892
893 // Map cubature points to physical frame.
894 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, cellType);
895
896 // Evaluate the material tensor A at cubature points.
897 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
898
899 // Evaluate the source term at cubature points.
900 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
901
902 /**********************************************************************************/
903 /* Compute Stiffness Matrix */
904 /**********************************************************************************/
905
906 // Transform basis gradients to physical frame:
907 IntrepidFSTools::HGRADtransformGRAD<ST> (worksetHGBGrads, // DF^{-T}(grad u)
908 worksetJacobInv,
909 HGBGrads);
910 // Compute integration measure for workset cells:
911 IntrepidFSTools::computeCellMeasure<ST> (worksetCubWeights, // Det(DF)*w = J*w
912 worksetJacobDet,
913 cubWeights);
914 // Multiply transformed (workset) gradients with weighted measure
915 IntrepidFSTools::multiplyMeasure<ST> (worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
916 worksetCubWeights,
917 worksetHGBGrads);
918 // Compute the diffusive flux:
919 IntrepidFSTools::tensorMultiplyDataField<ST> (worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
920 worksetMaterialVals,
921 worksetHGBGrads);
922 // Integrate to compute workset diffusion contribution to global matrix:
923 IntrepidFSTools::integrate<ST> (worksetStiffMatrix, // (DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
924 worksetHGBGradsWeighted,
925 worksetDiffusiveFlux,
926 COMP_BLAS);
927
928 /**********************************************************************************/
929 /* Compute RHS */
930 /**********************************************************************************/
931
932 // Transform basis values to physical frame:
933 IntrepidFSTools::HGRADtransformVALUE<ST> (worksetHGBValues, // clones basis values (u)
934 HGBValues);
935 // Multiply transformed (workset) values with weighted measure
936 IntrepidFSTools::multiplyMeasure<ST> (worksetHGBValuesWeighted, // (u)*J*w
937 worksetCubWeights,
938 worksetHGBValues);
939 // Integrate worksetSourceTerm against weighted basis function set
940 IntrepidFSTools::integrate<ST> (worksetRHS, // f.(u)*J*w
941 worksetSourceTerm,
942 worksetHGBValuesWeighted,
943 COMP_BLAS);
944
945 } // Element discretization timer
946
947 /**********************************************************************************/
948 /* Assemble into Global Matrix */
949 /**********************************************************************************/
950
951 {
952 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
953 "Matrix/RHS fill: 2-Element assembly", elem_assembly_total);
954
955 // "WORKSET CELL" loop: local cell ordinal is relative to numElems
956 for (int cell = worksetBegin; cell < worksetEnd; ++cell) {
957
958 // Compute cell ordinal relative to the current workset
959 const int worksetCellOrdinal = cell - worksetBegin;
960
961 // "CELL EQUATION" loop for the workset cell: cellRow is
962 // relative to the cell DoF numbering.
963 for (int cellRow = 0; cellRow < numFieldsG; ++cellRow) {
964 int localRow = elemToNode (cell, cellRow);
965 ST sourceTermContribution = worksetRHS (worksetCellOrdinal, cellRow);
966
967 {
968 // TEUCHOS_FUNC_TIME_MONITOR_DIFF(
969 // "Matrix/RHS fill: 2a-RHS sum into local values",
970 // elem_rhs);
971 rhsVector->sumIntoLocalValue (localRow, sourceTermContribution);
972 }
973
974 // "CELL VARIABLE" loop for the workset cell: sum entire element
975 // stiff matrix contribution in one function call
976 ArrayView<int> localColAV =
977 arrayView<int> (&elemToNode(cell,0), numFieldsG);
978 ArrayView<ST> operatorMatrixContributionAV =
979 arrayView<ST> (&worksetStiffMatrix(worksetCellOrdinal,cellRow,0),
980 numFieldsG);
981 {
982 // TEUCHOS_FUNC_TIME_MONITOR_DIFF(
983 // "Matrix/RHS fill: 2b-Matrix sum into local values",
984 // elem_matrix);
985 StiffMatrix->sumIntoLocalValues (localRow, localColAV,
986 operatorMatrixContributionAV);
987 }
988 }// *** cell row loop ***
989 }// *** workset cell loop **
990 } // *** stop timer ***
991 }// *** workset loop ***
992
993 //////////////////////////////////////////////////////////////////////////////
994 // Export sparse matrix and right-hand side from overlapping row Map
995 // to owned (nonoverlapping) row Map.
996 //////////////////////////////////////////////////////////////////////////////
997
998 *out << "Exporting matrix and right-hand side from overlapped to owned Map" << endl;
999
1000 gl_StiffMatrix->setAllToScalar (STS::zero ());
1001 {
1002 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1003 "Matrix/RHS fill: 3-Matrix export", matrix_export);
1004 gl_StiffMatrix->doExport (*StiffMatrix, *exporter, Tpetra::ADD);
1005 }
1006 // If target of export has static graph, no need to do
1007 // setAllToScalar(0.0); export will clobber values.
1008 {
1009 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1010 "Matrix/RHS fill: 4-Matrix fill complete", matrix_fill_complete);
1011 gl_StiffMatrix->fillComplete ();
1012 }
1013
1014 gl_rhsVector->putScalar (STS::zero ());
1015 {
1016 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1017 "Matrix/RHS fill: 5-RHS export", rhs_export);
1018 gl_rhsVector->doExport (*rhsVector, *exporter, Tpetra::ADD);
1019 }
1020
1021 //////////////////////////////////////////////////////////////////////////////
1022 // Adjust matrix for boundary conditions
1023 //////////////////////////////////////////////////////////////////////////////
1024
1025 *out << "Adjusting matrix and right-hand side for BCs" << endl;
1026
1027 {
1028 TEUCHOS_FUNC_TIME_MONITOR_DIFF(
1029 "Matrix/RHS fill: 6-Dirichlet BC assembly", bc_assembly);
1030
1031 // Apply owned stiffness matrix to v: rhs := A*v
1032 RCP<multivector_type> rhsDir =
1033 rcp (new multivector_type (globalMapG, true));
1034 gl_StiffMatrix->apply (*v.getConst (), *rhsDir);
1035 // Update right-hand side
1036 gl_rhsVector->update (as<ST> (-STS::one ()), *rhsDir, STS::one ());
1037
1038 // Get a const view of the vector's local data.
1039 ArrayRCP<const ST> vArrayRCP = v->getData (0);
1040
1041 // Adjust rhs due to Dirichlet boundary conditions.
1042 for (int inode = 0; inode < numNodes; ++inode) {
1043 if (nodeIsOwned[inode]) {
1044 if (nodeOnBoundary (inode)) {
1045 // Get global node ID
1046 const GO gni = as<GO> (globalNodeIds[inode]);
1047 const LO lidT = globalMapG->getLocalElement (gni);
1048 ST v_valT = vArrayRCP[lidT];
1049 gl_rhsVector->replaceGlobalValue (gni, v_valT);
1050 }
1051 }
1052 }
1053
1054 // Zero out rows and columns of stiffness matrix corresponding to
1055 // Dirichlet edges and add one to diagonal. The following is the
1056 // Tpetra analog of Apply_OAZToMatrix().
1057 //
1058 // Reenable changes to the values and structure of the global
1059 // stiffness matrix.
1060 gl_StiffMatrix->resumeFill ();
1061
1062 // Find the local column numbers to nuke
1063 RCP<const map_type> ColMap = gl_StiffMatrix->getColMap ();
1064 RCP<const map_type> globalMap =
1065 rcp (new map_type (gl_StiffMatrix->getGlobalNumCols (), 0, comm,
1066 Tpetra::GloballyDistributed));
1067
1068 // Create the exporter from this process' column Map to the global
1069 // 1-1 column map. (???)
1070 RCP<const export_type> bdyExporter =
1071 rcp (new export_type (ColMap, globalMap));
1072 // Create a vector of global column indices to which we will export
1073 RCP<Tpetra::Vector<int, LO, GO, Node> > globColsToZeroT =
1074 rcp (new Tpetra::Vector<int, LO, GO, Node> (globalMap));
1075 // Create a vector of local column indices from which we will export
1076 RCP<Tpetra::Vector<int, LO, GO, Node> > myColsToZeroT =
1077 rcp (new Tpetra::Vector<int, LO, GO, Node> (ColMap));
1078 myColsToZeroT->putScalar (0);
1079
1080 // Flag (set to 1) all local columns corresponding to the local
1081 // rows specified.
1082 for (int i = 0; i < numBCNodes; ++i) {
1083 const GO globalRow = gl_StiffMatrix->getRowMap ()->getGlobalElement (BCNodes[i]);
1084 const LO localCol = gl_StiffMatrix->getColMap ()->getLocalElement (globalRow);
1085 // Tpetra::Vector<int, ...> works just like
1086 // Tpetra::Vector<double, ...>. Epetra has a separate
1087 // Epetra_IntVector class for ints.
1088 myColsToZeroT->replaceLocalValue (localCol, 1);
1089 }
1090
1091 // Export to the global column map.
1092 globColsToZeroT->doExport (*myColsToZeroT, *bdyExporter, Tpetra::ADD);
1093 // Import from the global column map to the local column map.
1094 myColsToZeroT->doImport (*globColsToZeroT, *bdyExporter, Tpetra::INSERT);
1095
1096 ArrayRCP<const int> myColsToZeroArrayRCP = myColsToZeroT->getData(0);
1097 size_t NumEntries = 0;
1098
1099 // Zero the columns corresponding to Dirichlet BCs.
1100 typename sparse_matrix_type::nonconst_local_inds_host_view_type indices("indices", 1);
1101 typename sparse_matrix_type::nonconst_values_host_view_type values("values", 1);
1102 for (LO i = 0; i < as<int> (gl_StiffMatrix->getLocalNumRows ()); ++i) {
1103 NumEntries = gl_StiffMatrix->getNumEntriesInLocalRow (i);
1104 Kokkos::resize(indices, NumEntries);
1105 Kokkos::resize(values, NumEntries);
1106 gl_StiffMatrix->getLocalRowCopy (i, indices, values, NumEntries);
1107 for (int j = 0; j < as<int> (NumEntries); ++j) {
1108 if (myColsToZeroArrayRCP[indices(j)] == 1)
1109 values(j) = STS::zero ();
1110 }
1111 gl_StiffMatrix->replaceLocalValues (i, indices, values);
1112 } // for each (local) row of the global stiffness matrix
1113
1114 // Zero the rows and add ones to diagonal.
1115 for (int i = 0; i < numBCNodes; ++i) {
1116 NumEntries = gl_StiffMatrix->getNumEntriesInLocalRow (BCNodes[i]);
1117 Kokkos::resize(indices, NumEntries);
1118 Kokkos::resize(values, NumEntries);
1119 gl_StiffMatrix->getLocalRowCopy (BCNodes[i], indices, values, NumEntries);
1120 const GO globalRow = gl_StiffMatrix->getRowMap ()->getGlobalElement (BCNodes[i]);
1121 const LO localCol = gl_StiffMatrix->getColMap ()->getLocalElement (globalRow);
1122 for (int j = 0; j < as<int> (NumEntries); ++j) {
1123 values(j) = STS::zero ();
1124 if (indices(j) == localCol) {
1125 values(j) = STS::one ();
1126 }
1127 } // for each entry in the current row
1128 gl_StiffMatrix->replaceLocalValues (BCNodes[i], indices, values);
1129 } // for each BC node
1130 }
1131
1132 *out << "Calling fillComplete() on owned-Map stiffness matrix" << endl;
1133
1134 // We're done modifying the owned stiffness matrix.
1135 gl_StiffMatrix->fillComplete ();
1136
1137 } // Matrix/RHS fill timing
1138
1139 //
1140 // We're done with assembly, so we can delete the mesh.
1141 //
1142 delete [] nodeIsOwned;
1143 nodeIsOwned = NULL;
1144 Delete_Pamgen_Mesh ();
1145
1146 // Create vector to store approximate solution, and set initial guess.
1147 RCP<vector_type> gl_approxSolVector = rcp (new vector_type (globalMapG));
1148 gl_approxSolVector->putScalar (STS::zero ());
1149
1150 // Store the output pointers.
1151 A = gl_StiffMatrix;
1152 B = gl_rhsVector;
1153 X_exact = gl_exactSolVector;
1154 X = gl_approxSolVector;
1155 }
1156
1157 std::vector<Teuchos::ScalarTraits<ST>::magnitudeType>
1158 exactResidualNorm (const Teuchos::RCP<const sparse_matrix_type>& A,
1159 const Teuchos::RCP<const vector_type>& B,
1160 const Teuchos::RCP<const vector_type>& X_exact)
1161 {
1162 using Teuchos::RCP;
1163 using Teuchos::rcp;
1164 typedef Teuchos::ScalarTraits<ST> STS;
1165 typedef STS::magnitudeType MT;
1166
1167 RCP<vector_type> R = rcp (new vector_type (*B)); // R := B
1168 // R := 1.0*R - 1.0*A*X_exact.
1169 A->apply (*X_exact, *R, Teuchos::NO_TRANS, -STS::one(), STS::one());
1170
1171 std::vector<MT> results (3);
1172 results[0] = R->norm2 ();
1173 results[1] = B->norm2 ();
1174 results[2] = A->getFrobeniusNorm ();
1175 return results;
1176 }
1177
1178 /**********************************************************************************/
1179 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1180 /**********************************************************************************/
1181
1182 template<typename Scalar>
1183 const Scalar
1184 exactSolution (const Scalar& x, const Scalar& y, const Scalar& z)
1185 {
1186 // Patch test: tri-linear function is in the FE space and should be recovered
1187 return 1. + x + y + z + x*y + x*z + y*z + x*y*z;
1188
1189 // Analytic solution with homogeneous Dirichlet boundary data
1190 // return sin(M_PI*x)*sin(M_PI*y)*sin(M_PI*z)*exp(x+y+z);
1191
1192 // Analytic solution with inhomogeneous Dirichlet boundary data
1193 // return exp(x + y + z)/(1. + x*y + y*z + x*y*z);
1194 }
1195
1196
1197 using ::TrilinosCouplings::IntrepidPoissonExample::getMaterialTensorOffDiagonalValue;
1198
1199 /** \brief User-defined material tensor.
1200
1201 Evaluate the tensor using operator(). Its arguments are:
1202
1203 \param material [out] 3 x 3 material tensor evaluated at (x,y,z)
1204 \param x [in] x-coordinate of the evaluation point
1205 \param y [in] y-coordinate of the evaluation point
1206 \param z [in] z-coordinate of the evaluation point
1207
1208 \warning Symmetric and positive definite tensor is required for every (x,y,z).
1209 */
1210 template<typename Scalar>
1211 class MaterialTensor {
1212 public:
1213 MaterialTensor (const double offDiagVal) :
1214 offDiagVal_ (Scalar (offDiagVal))
1215 {}
1216
1217 void
1218 operator () (Scalar material[][3],
1219 const Scalar& x,
1220 const Scalar& y,
1221 const Scalar& z) const
1222 {
1223 typedef Teuchos::ScalarTraits<Scalar> STS;
1224
1225 // We go through this trouble to make numbers, because Scalar
1226 // isn't necessarily double. It could be some automatic
1227 // differentiation type.
1228 const Scalar zero = STS::zero ();
1229 const Scalar one = STS::one ();
1230
1231 // You can use the value of offDiagVal_ to control the iteration
1232 // count. The iteration counts below are for Belos' GMRES with no
1233 // preconditioning, using the default problem size.
1234 // setMaterialTensorOffDiagonalValue() sets the value of this
1235 // parameter.
1236 //
1237 // Classical elasticity assumes a symmetric material tensor. I
1238 // suppose one could solve Poisson's equation with an unsymmetric
1239 // material tensor, but I'm not sure what that would mean.
1240
1241 // offDiagVal_ = -5/4: 209 iterations (CG breaks!)
1242 // offDiagVal_ = -1/2: 47 iterations
1243 // offDiagVal_ = 0: 40 iterations (CG works)
1244 // offDiagVal_ = 1/2: 46 iterations
1245 // offDiagVal_ = 3/4: 47 iterations
1246 // offDiagVal_ = 1: 59 iterations
1247 // offDiagVal_ = 5/4: 183 iterations
1248 // offDiagVal_ = 3/2: 491 iterations
1249 // offDiagVal_ = 2: 939 iterations (CG breaks!)
1250 material[0][0] = one;
1251 material[0][1] = zero;
1252 material[0][2] = offDiagVal_;
1253
1254 material[1][0] = zero;
1255 material[1][1] = one;
1256 material[1][2] = zero;
1257
1258 material[2][0] = offDiagVal_;
1259 material[2][1] = zero;
1260 material[2][2] = one;
1261 }
1262
1263 private:
1264 const Scalar offDiagVal_;
1265 };
1266
1267 /**********************************************************************************/
1268 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1269 /**********************************************************************************/
1270
1271 /// \brief Compute gradient of exact solution at (x,y,z).
1272 ///
1273 /// \param gradExact [out] The gradient at (x,y,z).
1274 /// \param x [in]
1275 /// \param y [in]
1276 /// \param z [in]
1277 template<typename Scalar>
1278 void
1279 exactSolutionGrad (Scalar gradExact[3],
1280 const Scalar& x,
1281 const Scalar& y,
1282 const Scalar& z)
1283 {
1284 // To enable taking derivatives of the gradient (that is, second
1285 // derivatives of the exact solution), we need 2 levels of fad
1286 // types.
1287 Sacado::Fad::SFad<Scalar,3> fad_x = x;
1288 Sacado::Fad::SFad<Scalar,3> fad_y = y;
1289 Sacado::Fad::SFad<Scalar,3> fad_z = z;
1290 Sacado::Fad::SFad<Scalar,3> u;
1291
1292 // Indicate the independent variables
1293 fad_x.diff(0,3);
1294 fad_y.diff(1,3);
1295 fad_z.diff(2,3);
1296
1297 u = exactSolution(fad_x, fad_y, fad_z);
1298
1299 gradExact[0] = u.dx(0);
1300 gradExact[1] = u.dx(1);
1301 gradExact[2] = u.dx(2);
1302 }
1303
1304 /// \brief Compute the source term (right-hand side) at (x,y,z).
1305 ///
1306 /// We compute the source term from the exact solution, its gradient,
1307 /// and the material tensor at (x,y,z).
1308 template<typename Scalar>
1309 const Scalar
1310 sourceTerm (Scalar& x, Scalar& y, Scalar& z)
1311 {
1312 Scalar u;
1313 Scalar grad_u[3];
1314 Scalar flux[3] = {0.0, 0.0, 0.0};
1315 Scalar material[3][3];
1316 Scalar f = 0.;
1317
1318 // Indicate the independent variables
1319 x.diff(0,3);
1320 y.diff(1,3);
1321 z.diff(2,3);
1322
1323 // Get exact solution and its gradient
1324 u = exactSolution (x, y, z);
1325 exactSolutionGrad (grad_u, x, y, z);
1326
1327 // Get material tensor
1328 MaterialTensor<Scalar> matTens (getMaterialTensorOffDiagonalValue ());
1329 matTens (material, x, y, z);
1330
1331 // Compute total flux = (A.grad u)
1332 for (int i = 0; i < 3; ++i) {
1333 // Add diffusive flux
1334 for (int j = 0; j < 3; ++j) {
1335 flux[i] += material[i][j]*grad_u[j];
1336 }
1337 }
1338
1339 // Compute source term (right hand side): f = -div(A.grad u)
1340 f = -(flux[0].dx(0) + flux[1].dx(1) + flux[2].dx(2));
1341
1342 return f;
1343 }
1344
1345 /**********************************************************************************/
1346 /*************************** EVALUATION METHODS ***********************************/
1347 /**********************************************************************************/
1348
1349 //! Compute the material tensor over a workset.
1350 template<class ArrayOut, class ArrayIn>
1351 void
1352 evaluateMaterialTensor (ArrayOut& matTensorValues,
1353 const ArrayIn& evaluationPoints)
1354 {
1355 typedef typename ArrayOut::scalar_type scalar_type;
1356
1357 const int numWorksetCells = evaluationPoints.dimension(0);
1358 const int numPoints = evaluationPoints.dimension(1);
1359 const int spaceDim = evaluationPoints.dimension(2);
1360
1361 scalar_type material[3][3];
1362
1363 MaterialTensor<scalar_type> matTens (getMaterialTensorOffDiagonalValue ());
1364 for (int cell = 0; cell < numWorksetCells; ++cell) {
1365 for (int pt = 0; pt < numPoints; ++pt) {
1366 scalar_type x = evaluationPoints(cell, pt, 0);
1367 scalar_type y = evaluationPoints(cell, pt, 1);
1368 scalar_type z = evaluationPoints(cell, pt, 2);
1369
1370 matTens (material, x, y, z);
1371
1372 for (int row = 0; row < spaceDim; ++row) {
1373 for(int col = 0; col < spaceDim; ++col) {
1374 matTensorValues(cell, pt, row, col) = material[row][col];
1375 }
1376 }
1377 }
1378 }
1379 }
1380
1381 /************ Source Term (RHS) ****************/
1382 template<class ArrayOut, class ArrayIn>
1383 void
1384 evaluateSourceTerm (ArrayOut& sourceTermValues,
1385 const ArrayIn& evaluationPoints)
1386 {
1387 typedef typename ArrayOut::scalar_type scalar_type;
1388
1389 const int numWorksetCells = evaluationPoints.dimension(0);
1390 const int numPoints = evaluationPoints.dimension(1);
1391
1392 for (int cell = 0; cell < numWorksetCells; ++cell) {
1393 for (int pt = 0; pt < numPoints; ++pt) {
1394 Sacado::Fad::SFad<scalar_type,3> x = evaluationPoints(cell, pt, 0);
1395 Sacado::Fad::SFad<scalar_type,3> y = evaluationPoints(cell, pt, 1);
1396 Sacado::Fad::SFad<scalar_type,3> z = evaluationPoints(cell, pt, 2);
1397
1398 sourceTermValues(cell, pt) =
1399 sourceTerm<Sacado::Fad::SFad<scalar_type,3> > (x, y, z).val ();
1400 }
1401 }
1402 }
1403
1404 /************ Exact Solution ****************/
1405 template<class ArrayOut, class ArrayIn>
1406 void
1407 evaluateExactSolution (ArrayOut& exactSolutionValues,
1408 const ArrayIn& evaluationPoints)
1409 {
1410 typedef typename ArrayOut::scalar_type scalar_type;
1411
1412 const int numWorksetCells = evaluationPoints.dimension(0);
1413 const int numPoints = evaluationPoints.dimension(1);
1414
1415 for (int cell = 0; cell < numWorksetCells; ++cell) {
1416 for (int pt = 0; pt < numPoints; ++pt) {
1417 const scalar_type x = evaluationPoints(cell, pt, 0);
1418 const scalar_type y = evaluationPoints(cell, pt, 1);
1419 const scalar_type z = evaluationPoints(cell, pt, 2);
1420 exactSolutionValues(cell, pt) = exactSolution<scalar_type> (x, y, z);
1421 }
1422 }
1423 }
1424
1425 /************ Grad of Exact Solution ****************/
1426 template<class ArrayOut, class ArrayIn>
1427 void
1428 evaluateExactSolutionGrad (ArrayOut& exactSolutionGradValues,
1429 const ArrayIn& evaluationPoints)
1430 {
1431 typedef typename ArrayOut::scalar_type scalar_type;
1432
1433 const int numWorksetCells = evaluationPoints.dimension(0);
1434 const int numPoints = evaluationPoints.dimension(1);
1435 const int spaceDim = evaluationPoints.dimension(2);
1436
1437 scalar_type gradient[3];
1438
1439 for (int cell = 0; cell < numWorksetCells; ++cell) {
1440 for (int pt = 0; pt < numPoints; ++pt) {
1441 const scalar_type x = evaluationPoints(cell, pt, 0);
1442 const scalar_type y = evaluationPoints(cell, pt, 1);
1443 const scalar_type z = evaluationPoints(cell, pt, 2);
1444
1445 exactSolutionGrad<scalar_type> (gradient, x, y, z);
1446
1447 for (int row = 0; row < spaceDim; ++row) {
1448 exactSolutionGradValues(cell, pt, row) = gradient[row];
1449 }
1450 }
1451 }
1452 }
1453
1454 } // namespace TpetraIntrepidPoissonExample
1455 } // namespace TrilinosCouplings