Debian Codegraph @

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