Debian Codegraph @

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