Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_GradDiv.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Trilinos: An Object-Oriented Solver Framework
4 //
5 // Copyright 2001-2024 NTESS and the Trilinos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /** \file example_GradDiv.cpp
11 \brief Example solution grad-div diffusion system with
12 div-conforming (face) elements.
13
14 This example uses the following Trilinos packages:
15 \li Pamgen to generate a Hexahedral mesh.
16 \li Intrepid to build the discretization matrices and right-hand side.
17 \li Epetra to handle the global matrix and vector.
18 \li ML to solve the linear system.
19
20
21 For more details on the formulation see
22
23 \li P. Bochev, K. Peterson, C. Siefert, "Analysis and Computation
24 of Compatible Least-Squares Methods for Div-Curl Equations",
25 SIAM J. Numerical Analysis, vol 49, pp 159-191, 2011.
26
27 \verbatim
28
29 Grad-Div System:
30
31 grad kappa div F + mu F = g in Omega
32
33 Corresponding discrete linear system for edge element coeficients (x):
34 (Kc + Mc)x = b
35
36 Kd - Hdiv stiffness matrix
37 Md - Hcdiv mass matrix
38 b - right hand side vector
39
40 \endverbatim
41
42 \author Created by P. Bochev, D. Ridzal, K. Peterson, D. Hensinger, C. Siefert.
43
44 \remark Usage
45 \verbatim
46
47 ./TrilinosCouplings_examples_scaling_Example_GradDiv.exe inputfile.xml
48
49 inputfile.xml (optional) - xml input file containing Pamgen mesh description
50 and material parameters for each Pamgen block,
51 if not present code attempts to read DivLSFEMin.xml.
52
53
54 \endverbatim
55 **/
56 // TrilinosCouplings includes
57 #include "TrilinosCouplings_config.h"
58 #include "TrilinosCouplings_Pamgen_Utils.hpp"
59
60 // Intrepid includes
61 #include "Intrepid_FunctionSpaceTools.hpp"
62 #include "Intrepid_FieldContainer.hpp"
63 #include "Intrepid_CellTools.hpp"
64 #include "Intrepid_ArrayTools.hpp"
65 #include "Intrepid_HCURL_HEX_I1_FEM.hpp"
66 #include "Intrepid_HGRAD_HEX_C1_FEM.hpp"
67 #include "Intrepid_HDIV_HEX_I1_FEM.hpp"
68 #include "Intrepid_RealSpaceTools.hpp"
69 #include "Intrepid_DefaultCubatureFactory.hpp"
70 #include "Intrepid_Utils.hpp"
71
72 // Epetra includes
73 #include "Epetra_Time.h"
74 #include "Epetra_Map.h"
75 #ifdef HAVE_MPI
76 #include "Epetra_MpiComm.h"
77 #else
78 #include "Epetra_SerialComm.h"
79 #endif
80 #include "Epetra_FECrsMatrix.h"
81 #include "Epetra_FEVector.h"
82 #include "Epetra_Vector.h"
83 #include "Epetra_LinearProblem.h"
84 #include "Epetra_Import.h"
85 #include "Epetra_Export.h"
86
87 // Teuchos includes
88 #include "Teuchos_oblackholestream.hpp"
89 #include "Teuchos_RCP.hpp"
90 #include "Teuchos_BLAS.hpp"
91 #include "Teuchos_GlobalMPISession.hpp"
92 #include "Teuchos_ParameterList.hpp"
93 #include "Teuchos_XMLParameterListHelpers.hpp"
94
95 // Shards includes
96 #include "Shards_CellTopology.hpp"
97
98 // EpetraExt includes
99 #include "EpetraExt_RowMatrixOut.h"
100 #include "EpetraExt_MultiVectorOut.h"
101 #include "EpetraExt_VectorOut.h"
102 #include "EpetraExt_MatrixMatrix.h"
103
104 // Pamgen includes
105 #include "create_inline_mesh.h"
106 #include "pamgen_im_exodusII_l.h"
107 #include "pamgen_im_ne_nemesisI_l.h"
108 #include "pamgen_extras.h"
109
110 // AztecOO includes
111 #include "AztecOO.h"
112
113 // ML Includes
114 #include "ml_epetra_utils.h"
115 #include "ml_GradDiv.h"
116
117 #define ABS(x) ((x)>0?(x):-(x))
118
119 /*** Uncomment if you would like output data for plotting ***/
120 //#define DUMP_DATA
121
122 using namespace std;
123 using namespace Intrepid;
124 using namespace Teuchos;
125
126 /*********************************************************/
127 /* Typedefs */
128 /*********************************************************/
129 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
130 typedef Intrepid::RealSpaceTools<double> IntrepidRSTools;
131 typedef Intrepid::CellTools<double> IntrepidCTools;
132
133
134 struct fecomp{
135 bool operator () ( topo_entity* x, topo_entity* y )const
136 {
137 if(x->sorted_local_node_ids < y->sorted_local_node_ids)return true;
138 return false;
139 }
140 };
141
142 /**********************************************************************************/
143 /***************** FUNCTION DECLARATIONS FOR ML PRECONDITIONER ********************/
144 /**********************************************************************************/
145
146 /** \brief Multiplies abs(A)x = y, where all non-zero entries of A are replaced with their absolute values value
147
148 \param A [in] matrix
149 \param x [in] vector
150 \param y [out] vector
151 */
152 int Multiply_Abs(const Epetra_CrsMatrix &A,const Epetra_Vector &x,Epetra_Vector &y);
153
154
155 /** \brief ML Preconditioner
156
157 \param ProblemType [in] problem type
158 \param MLList [in] ML parameter list
159 \param GradDiv [in] H(curl) stiffness matrix
160 \param D0clean [in] Edge to node incidence matrix
161 \param D1clean [in] Face to edge incidence matrix
162 \param FaceNode [in] Face to node incidence matrix
163 \param M1inv [in] H(curl) mass matrix inverse
164 \param M2 [in] H(div) mass matrix
165 \param xh [out] solution vector
166 \param b [in] right-hand-side vector
167 \param TotalErrorResidual [out] error residual
168 \param TotalErrorExactSol [out] error in xh
169
170 */
171 void TestMultiLevelPreconditioner_GradDiv(char ProblemType[],
172 Teuchos::ParameterList & MLList,
173 Epetra_CrsMatrix & GradDiv,
174 Epetra_CrsMatrix & D0clean,
175 Epetra_CrsMatrix & D1clean,
176 Epetra_CrsMatrix & FaceNode,
177 Epetra_CrsMatrix & M1,
178 Epetra_CrsMatrix & M1inv,
179 Epetra_CrsMatrix & M2,
180 Epetra_MultiVector & xh,
181 Epetra_MultiVector & b,
182 double & TotalErrorResidual,
183 double & TotalErrorExactSol);
184
185 /**********************************************************************************/
186 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
187 /**********************************************************************************/
188
189 /** \brief Exact solution evaluation.
190
191 \param uExact0 [out] first component of exact solution at (x,y,z)
192 \param uExact1 [out] second component of exact solution at (x,y,z)
193 \param uExact2 [out] third component of exact solution at (x,y,z)
194 \param x [in] x coordinate
195 \param y [in] y coordinate
196 \param z [in] z coordinate
197 */
198 int evalu(double & uExact0,
199 double & uExact1,
200 double & uExact2,
201 double & x,
202 double & y,
203 double & z);
204
205 /** \brief Divergence of exact solution.
206
207 \param x [in] x coordinate
208 \param y [in] y coordinate
209 \param z [in] z coordinate
210
211 \return Value of the divergence of exact solution at (x,y,z)
212 */
213 double evalDivu(double & x,
214 double & y,
215 double & z);
216
217 /** \brief Grad of Div of exact solution.
218
219 \param gradDivu0 [out] first component of grad div of exact solution
220 \param gradDivu1 [out] second component of grad div of exact solution
221 \param gradDivu2 [out] third component of grad div of exact solution
222 \param x [in] x coordinate
223 \param y [in] y coordinate
224 \param z [in] z coordinate
225 \param mu [in] material parameter
226 */
227 int evalGradDivu(double & gradDivu0,
228 double & gradDivu1,
229 double & gradDivu2,
230 double & x,
231 double & y,
232 double & z,
233 double & kappa);
234
235
236 /**********************************************************************************/
237 /**********************************************************************************/
238 /**********************************************************************************/
239
240
241
242 /**********************************************************************************/
243 /******************************** MAIN ********************************************/
244 /**********************************************************************************/
245 int main(int argc, char *argv[]) {
246
247 int error = 0;
248 #ifdef HAVE_MPI
249 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
250 int rank=mpiSession.getRank();
251 int numProcs=mpiSession.getNProc();
252 Epetra_MpiComm Comm(MPI_COMM_WORLD);
253 int MyPID = Comm.MyPID();
254 #else
255 int rank=0;
256 int numProcs=1;
257 int MyPID = 0;
258 Epetra_SerialComm Comm;
259 #endif
260 Epetra_Time Time(Comm);
261
262 //Check number of arguments
263 if (argc > 2) {
264 std::cout <<"\n>>> ERROR: Invalid number of arguments.\n\n";
265 std::cout <<"Usage:\n\n";
266 std::cout <<" ./TrilinosCouplings_examples_scaling_Example_GradDiv.exe [inputfile.xml] \n\n";
267 std::cout <<" inputfile.xml(optional) - xml file with description of Pamgen mesh \n";
268 std::cout <<" and material parameters for each block \nn";
269 exit(1);
270 }
271
272 if (MyPID == 0) {
273 std::cout \
274 << "===============================================================================\n" \
275 << "| |\n" \
276 << "| Example: Div-Curl System on Hexahedral Mesh |\n" \
277 << "| |\n" \
278 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
279 << "| Denis Ridzal ([email protected]), |\n" \
280 << "| Kara Peterson ([email protected]). |\n" \
281 << "| |\n" \
282 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
283 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
284 << "| ML's website: http://trilinos.sandia.gov/packages/ml |\n" \
285 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
286 << "| |\n" \
287 << "===============================================================================\n";
288 }
289
290 long long * node_comm_proc_ids = NULL;
291 long long * node_cmap_node_cnts = NULL;
292 long long * node_cmap_ids = NULL;
293 long long ** comm_node_ids = NULL;
294 long long ** comm_node_proc_ids = NULL;
295
296 std::set < topo_entity * , fecomp > edge_set;
297 std::set < topo_entity * , fecomp > face_set;
298
299 std::vector < topo_entity * > edge_vector;
300 std::vector < topo_entity * > face_vector;
301
302 std::vector < int > edge_comm_procs;
303
304 int dim = 3;
305
306 /**********************************************************************************/
307 /********************************** GET XML INPUTS ********************************/
308 /**********************************************************************************/
309
310 // Command line for xml file, otherwise use default
311 std::string xmlInFileName;
312 if(argc>=2) xmlInFileName=string(argv[1]);
313 else xmlInFileName="GradDiv.xml";
314
315 // Read xml file into parameter list
316 Teuchos::ParameterList inputList;
317
318 if(xmlInFileName.length()) {
319 if (MyPID == 0) {
320 std::cout << "\nReading parameter list from the XML file \""<<xmlInFileName<<"\" ...\n\n";
321 }
322 Teuchos::updateParametersFromXmlFile(xmlInFileName, Teuchos::ptr (&inputList));
323 if (MyPID == 0) {
324 inputList.print(std::cout,2,true,true);
325 std::cout << "\n";
326 }
327 }
328 else
329 {
330 std::cout << "Cannot read input file: " << xmlInFileName << "\n";
331 return 0;
332 }
333
334 // Get pamgen mesh definition
335 std::string meshInput = Teuchos::getParameter<std::string>(inputList,"meshInput");
336
337
338 /**********************************************************************************/
339 /***************************** GET CELL TOPOLOGY **********************************/
340 /**********************************************************************************/
341
342 // Get cell topology for base hexahedron
343 typedef shards::CellTopology CellTopology;
344 CellTopology cellType(shards::getCellTopologyData<shards::Hexahedron<8> >() );
345
346 // Get dimensions
347 int numNodesPerElem = cellType.getNodeCount();
348 int numEdgesPerElem = cellType.getEdgeCount();
349 int numFacesPerElem = cellType.getSideCount();
350 int numNodesPerEdge = 2;
351 int numNodesPerFace = 4;
352 int numEdgesPerFace = 4;
353 int spaceDim = cellType.getDimension();
354
355 // Build reference element edge to node map
356 FieldContainer<int> refEdgeToNode(numEdgesPerElem,numNodesPerEdge);
357 for (int i=0; i<numEdgesPerElem; i++){
358 refEdgeToNode(i,0)=cellType.getNodeMap(1, i, 0);
359 refEdgeToNode(i,1)=cellType.getNodeMap(1, i, 1);
360 }
361
362 // Build reference element face to node map
363 FieldContainer<int> refFaceToNode(numFacesPerElem,numNodesPerFace);
364 for (int i=0; i<numFacesPerElem; i++){
365 refFaceToNode(i,0)=cellType.getNodeMap(2, i, 0);
366 refFaceToNode(i,1)=cellType.getNodeMap(2, i, 1);
367 refFaceToNode(i,2)=cellType.getNodeMap(2, i, 2);
368 refFaceToNode(i,3)=cellType.getNodeMap(2, i, 3);
369 }
370
371 // Build reference element face to edge map (Hardcoded for now)
372 FieldContainer<int> refFaceToEdge(numFacesPerElem,numEdgesPerFace);
373 refFaceToEdge(0,0)=0; refFaceToEdge(0,1)=9;
374 refFaceToEdge(0,2)=4; refFaceToEdge(0,3)=8;
375 refFaceToEdge(1,0)=1; refFaceToEdge(1,1)=10;
376 refFaceToEdge(1,2)=5; refFaceToEdge(1,3)=9;
377 refFaceToEdge(2,0)=2; refFaceToEdge(2,1)=11;
378 refFaceToEdge(2,2)=6; refFaceToEdge(2,3)=10;
379 refFaceToEdge(3,0)=8; refFaceToEdge(3,1)=7;
380 refFaceToEdge(3,2)=11; refFaceToEdge(3,3)=3;
381 refFaceToEdge(4,0)=3; refFaceToEdge(4,1)=2;
382 refFaceToEdge(4,2)=1; refFaceToEdge(4,3)=0;
383 refFaceToEdge(5,0)=4; refFaceToEdge(5,1)=5;
384 refFaceToEdge(5,2)=6; refFaceToEdge(5,3)=7;
385
386 /**********************************************************************************/
387 /******************************* GENERATE MESH ************************************/
388 /**********************************************************************************/
389
390 // Generate mesh with Pamgen
391 long long maxInt = 9223372036854775807LL;
392 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
393 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
394
395 // Get local mesh size info
396 char title[100];
397 long long numDim;
398 long long numNodes;
399 long long numElems;
400 long long numElemBlk;
401 long long numNodeSets;
402 long long numSideSets;
403 int id = 0;
404
405 im_ex_get_init_l(id, title, &numDim, &numNodes,
406 &numElems, &numElemBlk, &numNodeSets,
407 &numSideSets);
408 // Get global mesh size info
409 long long numNodesGlobal;
410 long long numElemsGlobal;
411 long long numElemBlkGlobal;
412 long long numNodeSetsGlobal;
413 long long numSideSetsGlobal;
414
415 im_ne_get_init_global_l(id, &numNodesGlobal, &numElemsGlobal,
416 &numElemBlkGlobal, &numNodeSetsGlobal,
417 &numSideSetsGlobal);
418
419
420 long long * block_ids = new long long [numElemBlk];
421 error += im_ex_get_elem_blk_ids_l(id, block_ids);
422
423
424 long long *nodes_per_element = new long long [numElemBlk];
425 long long *element_attributes = new long long [numElemBlk];
426 long long *elements = new long long [numElemBlk];
427 char **element_types = new char * [numElemBlk];
428 long long **elmt_node_linkage = new long long * [numElemBlk];
429
430
431 for(long long i = 0; i < numElemBlk; i ++){
432 element_types[i] = new char [MAX_STR_LENGTH + 1];
433 error += im_ex_get_elem_block_l(id,
434 block_ids[i],
435 element_types[i],
436 (long long*)&(elements[i]),
437 (long long*)&(nodes_per_element[i]),
438 (long long*)&(element_attributes[i]));
439 }
440
441 /*connectivity*/
442 for(long long b = 0; b < numElemBlk; b++){
443 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
444 error += im_ex_get_elem_conn_l(id,block_ids[b],elmt_node_linkage[b]);
445 }
446
447 // Get mu value for each block of elements from parameter list
448 double *mu = new double [numElemBlk];
449 for(int b = 0; b < numElemBlk; b++){
450 stringstream muBlock;
451 muBlock.clear();
452 muBlock << "mu" << b;
453 mu[b] = inputList.get(muBlock.str(),1.0);
454 }
455
456 // Get kapopa value for each block of elements from parameter list
457 double *kappa = new double [numElemBlk];
458 for(int b = 0; b < numElemBlk; b++){
459 stringstream kappaBlock;
460 kappaBlock.clear();
461 kappaBlock << "kappa" << b;
462 kappa[b] = inputList.get(kappaBlock.str(),1.0);
463 }
464
465
466 // Get node-element connectivity and set element mu value
467 int telct = 0;
468 FieldContainer<int> elemToNode(numElems,numNodesPerElem);
469 FieldContainer<double> muVal(numElems);
470 FieldContainer<double> kappaVal(numElems);
471 for(long long b = 0; b < numElemBlk; b++){
472 for(long long el = 0; el < elements[b]; el++){
473 for (int j=0; j<numNodesPerElem; j++) {
474 elemToNode(telct,j) = elmt_node_linkage[b][el*numNodesPerElem + j]-1;
475 }
476 muVal(telct) = mu[b];
477 kappaVal(telct) = kappa[b];
478 telct ++;
479 }
480 }
481
482 // Read node coordinates and place in field container
483 FieldContainer<double> nodeCoord(numNodes,dim);
484 double * nodeCoordx = new double [numNodes];
485 double * nodeCoordy = new double [numNodes];
486 double * nodeCoordz = new double [numNodes];
487 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,nodeCoordz);
488 for (int i=0; i<numNodes; i++) {
489 nodeCoord(i,0)=nodeCoordx[i];
490 nodeCoord(i,1)=nodeCoordy[i];
491 nodeCoord(i,2)=nodeCoordz[i];
492 }
493
494 /*parallel info*/
495 long long num_internal_nodes;
496 long long num_border_nodes;
497 long long num_external_nodes;
498 long long num_internal_elems;
499 long long num_border_elems;
500 long long num_node_comm_maps;
501 long long num_elem_comm_maps;
502 im_ne_get_loadbal_param_l( id,
503 &num_internal_nodes,
504 &num_border_nodes,
505 &num_external_nodes,
506 &num_internal_elems,
507 &num_border_elems,
508 &num_node_comm_maps,
509 &num_elem_comm_maps,
510 0/*unused*/ );
511
512 if(num_node_comm_maps > 0){
513 node_comm_proc_ids = new long long [num_node_comm_maps];
514 node_cmap_node_cnts = new long long [num_node_comm_maps];
515 node_cmap_ids = new long long [num_node_comm_maps];
516 comm_node_ids = new long long* [num_node_comm_maps];
517 comm_node_proc_ids = new long long* [num_node_comm_maps];
518
519 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
520 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
521
522
523 if ( im_ne_get_cmap_params_l( id,
524 node_cmap_ids,
525 (long long*)node_cmap_node_cnts,
526 elem_cmap_ids,
527 (long long*)elem_cmap_elem_cnts,
528 0/*not used proc_id*/ ) < 0 )++error;
529
530 for(long long j = 0; j < num_node_comm_maps; j++) {
531 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
532 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
533 if ( im_ne_get_node_cmap_l( id,
534 node_cmap_ids[j],
535 comm_node_ids[j],
536 comm_node_proc_ids[j],
537 0/*not used proc_id*/ ) < 0 )++error;
538 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
539 }
540 }
541
542
543 //Calculate global node ids
544 long long * globalNodeIds = new long long[numNodes];
545 bool * nodeIsOwned = new bool[numNodes];
546
547 calc_global_node_ids(globalNodeIds,
548 nodeIsOwned,
549 numNodes,
550 num_node_comm_maps,
551 node_cmap_node_cnts,
552 node_comm_proc_ids,
553 comm_node_ids,
554 rank);
555 // Count owned nodes
556 int ownedNodes=0;
557 for(int i=0;i<numNodes;i++)
558 if(nodeIsOwned[i]) ownedNodes++;
559
560 // Build a list of the OWNED global ids...
561 int *ownedGIDs=new int [ownedNodes];
562 int oidx=0;
563 for(int i=0;i<numNodes;i++)
564 if(nodeIsOwned[i]){
565 ownedGIDs[oidx]=(int)globalNodeIds[i];
566 oidx++;
567 }
568
569
570 FieldContainer<int> elemToEdge(numElems,numEdgesPerElem);
571 FieldContainer<int> elemToFace(numElems,numFacesPerElem);
572
573 // calculate edge and face ids
574 int elct = 0;
575 for(long long b = 0; b < numElemBlk; b++){
576 if(nodes_per_element[b] == 4){
577 }
578 else if (nodes_per_element[b] == 8){
579 //loop over all elements and push their edges onto a set if they are not there already
580 for(long long el = 0; el < elements[b]; el++){
581 std::set< topo_entity *, fecomp > ::iterator fit;
582 for (int i=0; i < numEdgesPerElem; i++){
583 topo_entity * teof = new topo_entity;
584 for(int j = 0; j < numNodesPerEdge;j++){
585 teof->add_node(elmt_node_linkage[b][el*numNodesPerElem + refEdgeToNode(i,j)],globalNodeIds);
586 }
587 teof->sort();
588 fit = edge_set.find(teof);
589 if(fit == edge_set.end()){
590 teof->local_id = edge_vector.size();
591 edge_set.insert(teof);
592 elemToEdge(elct,i)= edge_vector.size();
593 edge_vector.push_back(teof);
594 }
595 else{
596 elemToEdge(elct,i) = (*fit)->local_id;
597 delete teof;
598 }
599 }
600 for (int i=0; i < numFacesPerElem; i++){
601 topo_entity * teof = new topo_entity;
602 for(int j = 0; j < numNodesPerFace;j++){
603 teof->add_node(elmt_node_linkage[b][el*numNodesPerElem + refFaceToNode(i,j)],globalNodeIds);
604 }
605 teof->sort();
606 fit = face_set.find(teof);
607 if(fit == face_set.end()){
608 teof->local_id = face_vector.size();
609 face_set.insert(teof);
610 elemToFace(elct,i)= face_vector.size();
611 face_vector.push_back(teof);
612 }
613 else{
614 elemToFace(elct,i) = (*fit)->local_id;
615 delete teof;
616 }
617 }
618 elct ++;
619 }
620 }
621 }
622
623 // Edge to Node connectivity
624 FieldContainer<int> edgeToNode(edge_vector.size(), numNodesPerEdge);
625 for(unsigned ect = 0; ect != edge_vector.size(); ect++){
626 std::list<long long>::iterator elit;
627 int nct = 0;
628 for(elit = edge_vector[ect]->local_node_ids.begin();
629 elit != edge_vector[ect]->local_node_ids.end();
630 elit ++){
631 edgeToNode(ect,nct) = *elit-1;
632 nct++;
633 }
634 }
635
636 // Face to Node connectivity
637 FieldContainer<int> faceToNode(face_vector.size(), numNodesPerFace);
638 for(unsigned fct = 0; fct != face_vector.size(); fct++){
639 std::list<long long>::iterator flit;
640 int nct = 0;
641 for(flit = face_vector[fct]->local_node_ids.begin();
642 flit != face_vector[fct]->local_node_ids.end();
643 flit ++){
644 faceToNode(fct,nct) = *flit-1;
645 nct++;
646 }
647 }
648
649
650 // Face to Edge connectivity
651 FieldContainer<int> faceToEdge(face_vector.size(), numEdgesPerFace);
652 FieldContainer<bool> faceDone(face_vector.size());
653 for (int ielem = 0; ielem < numElems; ielem++){
654 for (int iface = 0; iface < numFacesPerElem; iface++){
655 if (!faceDone(elemToFace(ielem,iface))){
656 for (int iedge = 0; iedge < numEdgesPerFace; iedge++){
657 faceToEdge(elemToFace(ielem,iface),iedge) =
658 elemToEdge(ielem,refFaceToEdge(iface,iedge));
659 faceDone(elemToFace(ielem,iface))=1;
660 }
661 }
662 }
663 }
664
665 int numEdges = edge_vector.size();
666 int numFaces = face_vector.size();
667
668 // Calculate global edge and face numbering
669 std::string doing_type;
670 doing_type = "EDGES";
671 calc_global_ids(edge_vector,
672 comm_node_ids,
673 node_comm_proc_ids,
674 node_cmap_node_cnts,
675 num_node_comm_maps,
676 rank,
677 doing_type);
678
679
680 doing_type = "FACES";
681 calc_global_ids(face_vector,
682 comm_node_ids,
683 node_comm_proc_ids,
684 node_cmap_node_cnts,
685 num_node_comm_maps,
686 rank,
687 doing_type);
688
689 // Build list of owned global edge ids
690 long long * globalEdgeIds = new long long[numEdges];
691 bool * edgeIsOwned = new bool[numEdges];
692 int numOwnedEdges=0;
693 for (int i=0; i<numEdges; i++) {
694 edgeIsOwned[i] = edge_vector[i]->owned;
695 globalEdgeIds[i] = edge_vector[i]->global_id;
696 if (edgeIsOwned[i]){
697 numOwnedEdges++;
698 }
699 }
700 int * ownedEdgeIds = new int[numOwnedEdges];
701 int nedge=0;
702 for (int i=0; i<numEdges; i++) {
703 if (edgeIsOwned[i]){
704 ownedEdgeIds[nedge]=(int)globalEdgeIds[i];
705 nedge++;
706 }
707 }
708
709 // Build list of owned global face ids
710 long long * globalFaceIds = new long long[numFaces];
711 bool * faceIsOwned = new bool[numFaces];
712 int numOwnedFaces=0;
713 for (int i=0; i<numFaces; i++) {
714 faceIsOwned[i] = face_vector[i]->owned;
715 globalFaceIds[i] = face_vector[i]->global_id;
716 if (faceIsOwned[i]){
717 numOwnedFaces++;
718 }
719 }
720 int * ownedFaceIds = new int[numOwnedFaces];
721 int nface=0;
722 for (int i=0; i<numFaces; i++) {
723 if (faceIsOwned[i]){
724 ownedFaceIds[nface]=(int)globalFaceIds[i];
725 nface++;
726 }
727 }
728
729 // Calculate number of global edges and faces
730 int numEdgesGlobal;
731 int numFacesGlobal;
732 #ifdef HAVE_MPI
733 Comm.SumAll(&numOwnedEdges,&numEdgesGlobal,1);
734 Comm.SumAll(&numOwnedFaces,&numFacesGlobal,1);
735 #else
736 numEdgesGlobal = numEdges;
737 numFacesGlobal = numFaces;
738 #endif
739
740 // Print mesh size information
741 if (MyPID == 0) {
742 std::cout << " Number of Elements: " << numElemsGlobal << " \n";
743 std::cout << " Number of Nodes: " << numNodesGlobal << " \n";
744 std::cout << " Number of Edges: " << numEdgesGlobal << " \n";
745 std::cout << " Number of Faces: " << numFacesGlobal << " \n\n";
746 }
747
748 // Container indicating whether a face is on the boundary (1-yes 0-no)
749 FieldContainer<int> edgeOnBoundary(numEdges);
750 FieldContainer<int> faceOnBoundary(numFaces);
751
752 // Get boundary (side set) information
753 long long * sideSetIds = new long long [numSideSets];
754 long long numSidesInSet;
755 long long numDFinSet;
756 int numBndyFaces=0;
757 im_ex_get_side_set_ids_l(id,sideSetIds);
758 for (int i=0; i<numSideSets; i++) {
759 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
760 if (numSidesInSet > 0){
761 long long * sideSetElemList = new long long [numSidesInSet];
762 long long * sideSetSideList = new long long [numSidesInSet];
763 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
764 for (int j=0; j<numSidesInSet; j++) {
765 int iface = sideSetSideList[j]-1;
766 faceOnBoundary(elemToFace(sideSetElemList[j]-1,iface))=1;
767 numBndyFaces++;
768 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),0))=1;
769 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),1))=1;
770 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),2))=1;
771 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),3))=1;
772 }
773 delete [] sideSetElemList;
774 delete [] sideSetSideList;
775 }
776 }
777
778 delete [] sideSetIds;
779
780 #ifdef RANDOM_GRID
781 /***********************************************************************************/
782 /* This block of code will create a randomly perturbed mesh by jiggling the node
783 coordinates up to 1/4 of an edge length away from their initial location.
784 !!!NOTE: THIS WILL ONLY WORK CORRECTLY ON A SINGLE PROCESSOR!!! */
785 /***********************************************************************************/
786
787 // Container indicating whether a node is on the boundary (1-yes 0-no)
788 FieldContainer<int> nodeOnBoundary(numNodes);
789 for (int i=0; i<numEdges; i++) {
790 if (edgeOnBoundary(i)){
791 nodeOnBoundary(edgeToNode(i,0))=1;
792 nodeOnBoundary(edgeToNode(i,1))=1;
793 }
794 }
795
796 // Side length assuming an initially regular grid
797 double hx = nodeCoord(elemToNode(0,1),0)-nodeCoord(elemToNode(0,0),0);
798 double hy = nodeCoord(elemToNode(0,3),1)-nodeCoord(elemToNode(0,0),1);
799 double hz = nodeCoord(elemToNode(0,4),2)-nodeCoord(elemToNode(0,0),2);
800
801 // Loop over nodes
802 for (int inode = 0; inode < numNodes; inode++){
803 if (!nodeOnBoundary(inode) & nodeIsOwned[inode]) {
804 // random numbers between -1.0 and 1.0
805 double rx = 2.0 * (double)rand()/RAND_MAX - 1.0;
806 double ry = 2.0 * (double)rand()/RAND_MAX - 1.0;
807 double rz = 2.0 * (double)rand()/RAND_MAX - 1.0;
808 // limit variation to 1/4 edge length
809 nodeCoord(inode,0) = nodeCoord(inode,0) + 0.125 * hx * rx;
810 nodeCoord(inode,1) = nodeCoord(inode,1) + 0.125 * hy * ry;
811 nodeCoord(inode,2) = nodeCoord(inode,2) + 0.125 * hz * rz;
812 nodeCoordx[inode] = nodeCoord(inode,0);
813 nodeCoordy[inode] = nodeCoord(inode,1);
814 nodeCoordz[inode] = nodeCoord(inode,2);
815 }
816 }
817 #endif
818
819 /**********************************************************************************/
820 /********************************* GET CUBATURE ***********************************/
821 /**********************************************************************************/
822
823 // Get numerical integration points and weights
824 DefaultCubatureFactory<double> cubFactory;
825 int cubDegree = 2;
826 Teuchos::RCP<Cubature<double> > hexCub = cubFactory.create(cellType, cubDegree);
827
828 int cubDim = hexCub->getDimension();
829 int numCubPoints = hexCub->getNumPoints();
830
831 FieldContainer<double> cubPoints(numCubPoints, cubDim);
832 FieldContainer<double> cubWeights(numCubPoints);
833
834 hexCub->getCubature(cubPoints, cubWeights);
835
836 /**********************************************************************************/
837 /* Get numerical integration points and weights for hexahedron face */
838 /* (needed for rhs boundary term) */
839 /**********************************************************************************/
840
841 // Define topology of the face parametrization domain as [-1,1]x[-1,1]
842 CellTopology paramQuadFace(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
843
844 // Define cubature
845 DefaultCubatureFactory<double> cubFactoryFace;
846 Teuchos::RCP<Cubature<double> > hexFaceCubature = cubFactoryFace.create(paramQuadFace, 3);
847 int cubFaceDim = hexFaceCubature -> getDimension();
848 int numFacePoints = hexFaceCubature -> getNumPoints();
849
850 // Define storage for cubature points and weights on [-1,1]x[-1,1]
851 FieldContainer<double> paramFaceWeights(numFacePoints);
852 FieldContainer<double> paramFacePoints(numFacePoints,cubFaceDim);
853
854 // Define storage for cubature points on workset faces
855 hexFaceCubature -> getCubature(paramFacePoints, paramFaceWeights);
856
857 if(MyPID==0) {std::cout << "Getting cubature "
858 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
859
860
861 /**********************************************************************************/
862 /*********************************** GET BASIS ************************************/
863 /**********************************************************************************/
864
865 // Define basis
866 Basis_HCURL_HEX_I1_FEM<double, FieldContainer<double> > hexHCurlBasis;
867 Basis_HDIV_HEX_I1_FEM<double, FieldContainer<double> > hexHDivBasis;
868 Basis_HGRAD_HEX_C1_FEM<double, FieldContainer<double> > hexHGradBasis;
869
870 int numFieldsC = hexHCurlBasis.getCardinality();
871 int numFieldsD = hexHDivBasis.getCardinality();
872 int numFieldsG = hexHGradBasis.getCardinality();
873
874 // Evaluate basis at cubature points
875 FieldContainer<double> HCVals(numFieldsC, numCubPoints, spaceDim);
876 FieldContainer<double> HDVals(numFieldsD, numCubPoints, spaceDim);
877 FieldContainer<double> HDivs(numFieldsD, numCubPoints);
878 FieldContainer<double> HGVals(numFieldsG, numCubPoints);
879
880 hexHCurlBasis.getValues(HCVals, cubPoints, OPERATOR_VALUE);
881 hexHDivBasis.getValues(HDVals, cubPoints, OPERATOR_VALUE);
882 hexHDivBasis.getValues(HDivs, cubPoints, OPERATOR_DIV);
883 hexHGradBasis.getValues(HGVals, cubPoints, OPERATOR_VALUE);
884
885 /**********************************************************************************/
886 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
887 /**********************************************************************************/
888
889 // Define global epetra maps
890 Epetra_Map globalMapG(-1,ownedNodes,ownedGIDs,0,Comm);
891 Epetra_Map globalMapC(-1,numOwnedEdges,ownedEdgeIds,0,Comm);
892 Epetra_Map globalMapD(-1,numOwnedFaces,ownedFaceIds,0,Comm);
893
894 // Global arrays in Epetra format
895 Epetra_FECrsMatrix MassMatrixC(Copy, globalMapC, numFieldsC);
896 Epetra_FECrsMatrix MassMatrixD(Copy, globalMapD, numFieldsD);
897 Epetra_FECrsMatrix MassMatrixG(Copy, globalMapG, numFieldsG);
898 Epetra_FECrsMatrix StiffMatrixD(Copy, globalMapD, numFieldsD);
899 Epetra_FEVector rhsVector(globalMapD);
900
901 if(MyPID==0) {std::cout << "Build global maps "
902 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
903
904
905 /**********************************************************************************/
906 /************************** OUTPUT CONNECTIVITY (FOR PLOTTING) ********************/
907 /**********************************************************************************/
908
909 // Build the coordinate vectors for ML solver (including owned nodes only)
910 Epetra_Vector Nx(globalMapG), Ny(globalMapG),Nz(globalMapG);
911 for(int i=0,nlid=0;i<numNodes;i++)
912 if(nodeIsOwned[i]) {
913 Nx[nlid]=nodeCoordx[i];
914 Ny[nlid]=nodeCoordy[i];
915 Nz[nlid]=nodeCoordz[i];
916 nlid++;
917 }
918
919 #ifdef DUMP_DATA
920 // Put element to node mapping in multivector for output
921 Epetra_Map globalMapElem(numElemsGlobal, numElems, 0, Comm);
922 Epetra_MultiVector elem2node(globalMapElem, numNodesPerElem);
923 for (int ielem=0; ielem<numElems; ielem++) {
924 for (int inode=0; inode<numNodesPerElem; inode++) {
925 elem2node[inode][ielem]=globalNodeIds[elemToNode(ielem,inode)];
926 }
927 }
928 EpetraExt::MultiVectorToMatrixMarketFile("elem2node.dat",elem2node,0,0,false);
929
930 // Put element to face mapping in multivector for output
931 Epetra_MultiVector elem2face(globalMapElem, numFacesPerElem);
932 for (int ielem=0; ielem<numElems; ielem++) {
933 for (int iface=0; iface<numFacesPerElem; iface++) {
934 elem2face[iface][ielem]=globalFaceIds[elemToFace(ielem,iface)];
935 }
936 }
937 EpetraExt::MultiVectorToMatrixMarketFile("elem2face.dat",elem2face,0,0,false);
938
939 // Put face to edge mapping in multivector for output
940 Epetra_MultiVector face2edge(globalMapD, numEdgesPerFace);
941 int ownedFace = 0;
942 for (int iface=0; iface<numFaces; iface++) {
943 if (faceIsOwned[iface]) {
944 for (int iedge=0; iedge<numEdgesPerFace; iedge++) {
945 face2edge[iedge][ownedFace]=globalEdgeIds[faceToEdge(iface,iedge)];
946 }
947 ownedFace++;
948 }
949 }
950 EpetraExt::MultiVectorToMatrixMarketFile("face2edge.dat",face2edge,0,0,false);
951
952 // Put face to node mapping in multivector for output
953 Epetra_MultiVector face2node(globalMapD, numNodesPerFace);
954 int iFace = 0;
955 for (int iface=0; iface<numFaces; iface++) {
956 if (faceIsOwned[iface]) {
957 for (int inode=0; inode<numNodesPerFace; inode++) {
958 face2node[inode][iFace]=globalNodeIds[faceToNode(iface,inode)];
959 }
960 iFace++;
961 }
962 }
963 EpetraExt::MultiVectorToMatrixMarketFile("face2node.dat",face2node,0,0,false);
964
965 // Define multi-vector for cell face and edge signs (fill during cell loop)
966 Epetra_MultiVector faceSign(globalMapElem, numFacesPerElem);
967 Epetra_MultiVector edgeSign(globalMapElem, numEdgesPerElem);
968
969 if(MyPID==0) {Time.ResetStartTime();}
970 #endif
971
972 /**********************************************************************************/
973 /*************************BUILD INCIDENCE MATRIX***********************************/
974 /**********************************************************************************/
975
976 // Edge to node (DGrad) and face to edge (DCurl) incidence matrices
977 Epetra_FECrsMatrix DCurl(Copy, globalMapD, 4);
978 Epetra_FECrsMatrix DGrad(Copy, globalMapC, 2);
979
980 // Edge to node incidence matrix
981 double edgevals[2];
982 edgevals[0]=-1.0; edgevals[1]=1.0;
983 for (int j=0; j<numEdges; j++){
984 if (edgeIsOwned[j]){
985 int rowNum = globalEdgeIds[j];
986 int colNum[2];
987 colNum[0] = globalNodeIds[edgeToNode(j,0)];
988 colNum[1] = globalNodeIds[edgeToNode(j,1)];
989 DGrad.InsertGlobalValues(1, &rowNum, 2, colNum, edgevals);
990 }
991 }
992
993 // Edge to face incidence matrix
994 FieldContainer<bool> faceDone2(numFaces);
995 for (int i=0; i<numElems; i++){
996 for (int k=0; k<numFacesPerElem; k++){
997 int iface=elemToFace(i,k);
998 if (faceIsOwned[iface] && !faceDone2(iface)){
999 double vals[4];
1000 int rowNum = globalFaceIds[iface];
1001 int colNum[4];
1002
1003 for (int m=0; m<numEdgesPerFace; m++){
1004 colNum[m] = globalEdgeIds[faceToEdge(iface,m)];
1005 int indm = m+1;
1006 if (indm >= numEdgesPerFace) indm=0;
1007 if (edgeToNode(faceToEdge(iface,m),1) == edgeToNode(faceToEdge(iface,indm),0) ||
1008 edgeToNode(faceToEdge(iface,m),1) == edgeToNode(faceToEdge(iface,indm),1)){
1009 vals[m]=1.0;}
1010 else vals[m]=-1.0;
1011
1012 // This is a convoluted way to account for edge orientations that
1013 // may be incorrect on the local processor because the edge is
1014 // not owned by the local processor.
1015 int edgeIndex = -1;
1016 if (!edgeIsOwned[faceToEdge(iface,m)]){
1017 for (int l=0; l<numEdgesPerElem; l++){
1018 if (faceToEdge(iface,m)==elemToEdge(i,l))
1019 edgeIndex=l;
1020 }
1021 }
1022 if (edgeIndex != -1 && edgeIndex < 8){
1023 if (edgeIndex < 4 && faceIsOwned[elemToFace(i,4)]){
1024 vals[m]=-1.0*vals[m];
1025 }
1026 else if (edgeIndex > 3 && faceIsOwned[elemToFace(i,5)]){
1027 vals[m]=-1.0*vals[m];
1028 }
1029 }
1030 } // end loop over face edges
1031
1032 DCurl.InsertGlobalValues(1, &rowNum, 4, colNum, vals);
1033 faceDone2(iface)=1;
1034
1035 } // end if face is owned and face not done
1036 } // end loop over element faces
1037 } // end loop over elements
1038
1039
1040 DGrad.GlobalAssemble(globalMapG,globalMapC);
1041 DGrad.FillComplete(MassMatrixG.RowMap(),MassMatrixC.RowMap());
1042
1043 DCurl.GlobalAssemble(globalMapC,globalMapD);
1044 DCurl.FillComplete(MassMatrixC.RowMap(),MassMatrixD.RowMap());
1045
1046 if(MyPID==0) {std::cout << "Building incidence matrices "
1047 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
1048
1049
1050 /**********************************************************************************/
1051 /******************** INHOMOGENEOUS BOUNDARY CONDITIONS ***************************/
1052 /**********************************************************************************/
1053
1054
1055 FieldContainer<double> bndyFaceVal(numBndyFaces);
1056 FieldContainer<int> bndyFaceToFace(numFaces);
1057 FieldContainer<double> refFacePoints(numFacePoints,spaceDim);
1058 FieldContainer<double> bndyFacePoints(1,numFacePoints,spaceDim);
1059 FieldContainer<double> bndyFaceJacobians(1,numFacePoints,spaceDim,spaceDim);
1060 FieldContainer<double> faceNorm(1,numFacePoints,spaceDim);
1061 FieldContainer<double> uDotNormal(1,numFacePoints);
1062 FieldContainer<double> uFace(numFacePoints,spaceDim);
1063 FieldContainer<double> nodes(1, numNodesPerElem, spaceDim);
1064
1065 int ibface=0;
1066 // Evaluate normal at face quadrature points
1067 for (int ielem=0; ielem<numElems; ielem++) {
1068 for (int inode=0; inode<numNodesPerElem; inode++) {
1069 nodes(0,inode,0) = nodeCoord(elemToNode(ielem,inode),0);
1070 nodes(0,inode,1) = nodeCoord(elemToNode(ielem,inode),1);
1071 nodes(0,inode,2) = nodeCoord(elemToNode(ielem,inode),2);
1072 }
1073 for (int iface=0; iface<numFacesPerElem; iface++){
1074 if(faceOnBoundary(elemToFace(ielem,iface))){
1075
1076 // map evaluation points from reference face to reference cell
1077 IntrepidCTools::mapToReferenceSubcell(refFacePoints,
1078 paramFacePoints,
1079 2, iface, cellType);
1080
1081 // calculate Jacobian
1082 IntrepidCTools::setJacobian(bndyFaceJacobians, refFacePoints,
1083 nodes, cellType);
1084
1085 // map evaluation points from reference cell to physical cell
1086 IntrepidCTools::mapToPhysicalFrame(bndyFacePoints,
1087 refFacePoints,
1088 nodes, cellType);
1089
1090 // Compute face normals
1091 IntrepidCTools::getPhysicalFaceNormals(faceNorm,
1092 bndyFaceJacobians,
1093 iface, cellType);
1094
1095 // evaluate exact solution and dot with normal
1096 for(int nPt = 0; nPt < numFacePoints; nPt++){
1097
1098 double x = bndyFacePoints(0, nPt, 0);
1099 double y = bndyFacePoints(0, nPt, 1);
1100 double z = bndyFacePoints(0, nPt, 2);
1101
1102 evalu(uFace(nPt,0), uFace(nPt,1), uFace(nPt,2), x, y, z);
1103 uDotNormal(0,nPt)=(uFace(nPt,0)*faceNorm(0,nPt,0)+uFace(nPt,1)*faceNorm(0,nPt,1)+uFace(nPt,2)*faceNorm(0,nPt,2));
1104 }
1105
1106 // integrate
1107 for(int nPt = 0; nPt < numFacePoints; nPt++){
1108 bndyFaceVal(ibface)=bndyFaceVal(ibface)+uDotNormal(0,nPt)*paramFaceWeights(nPt);
1109 }
1110 bndyFaceToFace(elemToFace(ielem,iface))=ibface;
1111 ibface++;
1112 } // end if face on boundary
1113
1114 } // end loop over element faces
1115
1116 } // end loop over elements
1117
1118
1119 // Count boundary faces
1120 int numBCFaces=0;
1121 for (int i=0; i<numFaces; i++){
1122 if (faceOnBoundary(i) && faceIsOwned[i]){
1123 numBCFaces++;
1124 }
1125 }
1126
1127 // Vector for use in applying BCs
1128 Epetra_MultiVector v(globalMapD,true);
1129 v.PutScalar(0.0);
1130
1131 // Set v to boundary values on Dirichlet faces
1132 int * BCFaces = new int [numBCFaces];
1133 int indbc=0;
1134 int indOwned=0;
1135 for (int i=0; i<numFaces; i++){
1136 if (faceIsOwned[i]){
1137 if (faceOnBoundary(i)){
1138 BCFaces[indbc]=indOwned;
1139 indbc++;
1140 v[0][indOwned]=bndyFaceVal(bndyFaceToFace(i));
1141 }
1142 indOwned++;
1143 }
1144 }
1145
1146 if(MyPID==0) {std::cout << "Boundary Condition Setup "
1147 << Time.ElapsedTime() << " sec \n\n"; Time.ResetStartTime();}
1148
1149 /**********************************************************************************/
1150 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
1151 /**********************************************************************************/
1152
1153 // Define desired workset size and count how many worksets there are on this processor's mesh block
1154 int desiredWorksetSize = numElems; // change to desired workset size!
1155 //int desiredWorksetSize = 100; // change to desired workset size!
1156 int numWorksets = numElems/desiredWorksetSize;
1157
1158 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1159 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
1160
1161 if (MyPID == 0) {
1162 std::cout << "Building discretization matrix and right hand side... \n\n";
1163 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
1164 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
1165 Time.ResetStartTime();
1166 }
1167
1168 for(int workset = 0; workset < numWorksets; workset++){
1169
1170 // Compute cell numbers where the workset starts and ends
1171 int worksetSize = 0;
1172 int worksetBegin = (workset + 0)*desiredWorksetSize;
1173 int worksetEnd = (workset + 1)*desiredWorksetSize;
1174
1175 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1176 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1177
1178 // Now we know the actual workset size and can allocate the array for the cell nodes
1179 worksetSize = worksetEnd - worksetBegin;
1180 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
1181 FieldContainer<double> worksetEdgeSigns(worksetSize, numEdgesPerElem);
1182 FieldContainer<double> worksetFaceSigns(worksetSize, numFacesPerElem);
1183
1184 // Copy coordinates into cell workset
1185 int cellCounter = 0;
1186 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1187
1188 // Physical cell coordinates
1189 for (int inode=0; inode<numNodesPerElem; inode++) {
1190 cellWorkset(cellCounter,inode,0) = nodeCoord(elemToNode(cell,inode),0);
1191 cellWorkset(cellCounter,inode,1) = nodeCoord(elemToNode(cell,inode),1);
1192 cellWorkset(cellCounter,inode,2) = nodeCoord(elemToNode(cell,inode),2);
1193 }
1194
1195 // Face signs
1196 for (int iface=0; iface<numFacesPerElem; iface++) {
1197 worksetFaceSigns(cellCounter,iface) = -1.0;
1198 for (int i=0; i<numNodesPerFace; i++) {
1199 int indf=i+1;
1200 if (indf >= numNodesPerFace) indf=0;
1201 if (elemToNode(cell,refFaceToNode(iface,0))==faceToNode(elemToFace(cell,iface),i) &&
1202 elemToNode(cell,refFaceToNode(iface,1))==faceToNode(elemToFace(cell,iface),indf))
1203 worksetFaceSigns(cellCounter,iface) = 1.0;
1204 }
1205 if (!faceIsOwned[elemToFace(cell,iface)]){
1206 worksetFaceSigns(cellCounter,iface)=-1.0*worksetFaceSigns(cellCounter,iface);
1207 }
1208 }
1209
1210 #ifdef DUMP_DATA
1211 for (int iface=0; iface<numFacesPerElem; iface++) {
1212 faceSign[iface][cell] = worksetFaceSigns(cellCounter,iface);
1213 }
1214 #endif
1215
1216 // Edge signs
1217 for (int iedge=0; iedge<numEdgesPerElem; iedge++) {
1218 if (elemToNode(cell,refEdgeToNode(iedge,0))==edgeToNode(elemToEdge(cell,iedge),0) &&
1219 elemToNode(cell,refEdgeToNode(iedge,1))==edgeToNode(elemToEdge(cell,iedge),1))
1220 worksetEdgeSigns(cellCounter,iedge) = 1.0;
1221 else
1222 worksetEdgeSigns(cellCounter,iedge) = -1.0;
1223 }
1224
1225 // modify signs for edges that are owned by another processor
1226 // (Note: this is particular to the numbering of edges used in Pamgen!!)
1227 if (!faceIsOwned[elemToFace(cell,0)]) {
1228 worksetEdgeSigns(cellCounter,0)=-1.0*worksetEdgeSigns(cellCounter,0);
1229 worksetEdgeSigns(cellCounter,4)=-1.0*worksetEdgeSigns(cellCounter,4);
1230 }
1231 if (!faceIsOwned[elemToFace(cell,1)]) {
1232 worksetEdgeSigns(cellCounter,1)=-1.0*worksetEdgeSigns(cellCounter,1);
1233 worksetEdgeSigns(cellCounter,5)=-1.0*worksetEdgeSigns(cellCounter,5);
1234 }
1235 if (!faceIsOwned[elemToFace(cell,2)]) {
1236 worksetEdgeSigns(cellCounter,2)=-1.0*worksetEdgeSigns(cellCounter,2);
1237 worksetEdgeSigns(cellCounter,6)=-1.0*worksetEdgeSigns(cellCounter,6);
1238 }
1239 if (!faceIsOwned[elemToFace(cell,3)]) {
1240 worksetEdgeSigns(cellCounter,3)=-1.0*worksetEdgeSigns(cellCounter,3);
1241 worksetEdgeSigns(cellCounter,7)=-1.0*worksetEdgeSigns(cellCounter,7);
1242 }
1243
1244 #ifdef DUMP_DATA
1245 for (int iedge=0; iedge<numEdgesPerElem; iedge++) {
1246 edgeSign[iedge][cell] = worksetEdgeSigns(cellCounter,iedge);
1247 }
1248 #endif
1249 cellCounter++;
1250
1251 } // end loop over workset cells
1252
1253 /**********************************************************************************/
1254 /* Allocate arrays */
1255 /**********************************************************************************/
1256
1257 // Containers for Jacobian
1258 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
1259 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
1260 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
1261
1262 // Container for cubature points in physical space
1263 FieldContainer<double> worksetCubPoints (worksetSize,numCubPoints, cubDim);
1264
1265 // Containers for element HCURL mass matrix
1266 FieldContainer<double> massMatrixHCurl (worksetSize, numFieldsC, numFieldsC);
1267 FieldContainer<double> weightedMeasure (worksetSize, numCubPoints);
1268 FieldContainer<double> HCValsTransformed (worksetSize, numFieldsC, numCubPoints, spaceDim);
1269 FieldContainer<double> HCValsTransformedWeighted (worksetSize, numFieldsC, numCubPoints, spaceDim);
1270
1271 // Containers for element HDIV mass matrix
1272 FieldContainer<double> massMatrixHDiv (worksetSize, numFieldsD, numFieldsD);
1273 FieldContainer<double> HDValsTransformed (worksetSize, numFieldsD, numCubPoints, spaceDim);
1274 FieldContainer<double> HDValsTransformedWeighted (worksetSize, numFieldsD, numCubPoints, spaceDim);
1275 FieldContainer<double> weightedMeasureMu (worksetSize, numCubPoints);
1276
1277 // Containers for element HDIV stiffness matrix
1278 FieldContainer<double> stiffMatrixHDiv (worksetSize, numFieldsD, numFieldsD);
1279 FieldContainer<double> HDivsTransformed (worksetSize, numFieldsD, numCubPoints);
1280 FieldContainer<double> HDivsTransformedWeighted (worksetSize, numFieldsD, numCubPoints);
1281 FieldContainer<double> weightedMeasureKappa (worksetSize, numCubPoints);
1282
1283 // Containers for element HGRAD mass matrix
1284 FieldContainer<double> massMatrixHGrad (worksetSize, numFieldsG, numFieldsG);
1285 FieldContainer<double> HGValsTransformed (worksetSize, numFieldsG, numCubPoints);
1286 FieldContainer<double> HGValsTransformedWeighted (worksetSize, numFieldsG, numCubPoints);
1287
1288 // Containers for right hand side vectors
1289 FieldContainer<double> rhsDatag (worksetSize, numCubPoints, cubDim);
1290 FieldContainer<double> rhsDatah (worksetSize, numCubPoints);
1291 FieldContainer<double> gD (worksetSize, numFieldsD);
1292 FieldContainer<double> hD (worksetSize, numFieldsD);
1293
1294 // Containers for right hand side boundary term
1295 FieldContainer<double> gDBoundary (1, numFieldsD);
1296 FieldContainer<double> refFacePoints (numFacePoints,spaceDim);
1297 FieldContainer<double> cellNodes (1, numNodesPerElem, spaceDim);
1298 FieldContainer<double> worksetFacePoints (1, numFacePoints, spaceDim);
1299 FieldContainer<double> faceJacobians (1, numFacePoints, spaceDim, spaceDim);
1300 FieldContainer<double> faceJacobInv (1, numFacePoints, spaceDim, spaceDim);
1301 FieldContainer<double> faceJacobDet (1, numFacePoints);
1302 FieldContainer<double> faceNormal (1, numFacePoints, spaceDim);
1303 FieldContainer<double> bcFaceDVals (numFieldsD, numFacePoints, spaceDim);
1304 FieldContainer<double> bcDValsTransformed (1, numFieldsD, numFacePoints, spaceDim);
1305 FieldContainer<double> bcDataCrossField (1, numFieldsD, numFacePoints, spaceDim);
1306 FieldContainer<double> bcFaceSigns (1, numFieldsD);
1307
1308
1309 /**********************************************************************************/
1310 /* Calculate Jacobians */
1311 /**********************************************************************************/
1312
1313 IntrepidCTools::setJacobian (worksetJacobian, cubPoints, cellWorkset, cellType);
1314 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
1315 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
1316
1317 if(MyPID==0) {std::cout << "Calculate Jacobians "
1318 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1319
1320
1321 /**********************************************************************************/
1322 /* Compute HCURL Mass Matrix */
1323 /**********************************************************************************/
1324
1325 // transform to physical coordinates
1326 IntrepidFSTools::HCURLtransformVALUE<double>(HCValsTransformed, worksetJacobInv,
1327 HCVals);
1328
1329 // compute weighted measure
1330 IntrepidFSTools::computeCellMeasure<double>(weightedMeasure, worksetJacobDet, cubWeights);
1331
1332
1333 // multiply by weighted measure
1334 IntrepidFSTools::multiplyMeasure<double>(HCValsTransformedWeighted,
1335 weightedMeasure, HCValsTransformed);
1336
1337 // integrate to compute element mass matrix
1338 IntrepidFSTools::integrate<double>(massMatrixHCurl,
1339 HCValsTransformed, HCValsTransformedWeighted,
1340 COMP_BLAS);
1341
1342 // apply edge signs
1343 IntrepidFSTools::applyLeftFieldSigns<double>(massMatrixHCurl, worksetEdgeSigns);
1344 IntrepidFSTools::applyRightFieldSigns<double>(massMatrixHCurl, worksetEdgeSigns);
1345
1346 if(MyPID==0) {std::cout << "Compute HCURL Mass Matrix "
1347 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1348
1349 /**********************************************************************************/
1350 /* Compute HDiv Mass Matrix */
1351 /**********************************************************************************/
1352
1353 // transform to physical coordinates
1354 IntrepidFSTools::HDIVtransformVALUE<double>(HDValsTransformed, worksetJacobian,
1355 worksetJacobDet, HDVals);
1356
1357 // combine mu value with weighted measure
1358 cellCounter = 0;
1359 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1360 for (int nPt = 0; nPt < numCubPoints; nPt++){
1361 weightedMeasureMu(cellCounter,nPt) = weightedMeasure(cellCounter,nPt) * muVal(cell);
1362 }
1363 cellCounter++;
1364 }
1365
1366 // multiply by weighted measure
1367 IntrepidFSTools::multiplyMeasure<double>(HDValsTransformedWeighted,
1368 weightedMeasureMu, HDValsTransformed);
1369
1370 // integrate to compute element mass matrix
1371 IntrepidFSTools::integrate<double>(massMatrixHDiv,
1372 HDValsTransformed, HDValsTransformedWeighted,
1373 COMP_BLAS);
1374
1375 // apply face signs
1376 IntrepidFSTools::applyLeftFieldSigns<double>(massMatrixHDiv, worksetFaceSigns);
1377 IntrepidFSTools::applyRightFieldSigns<double>(massMatrixHDiv, worksetFaceSigns);
1378
1379
1380 if(MyPID==0) {std::cout << "Compute HDIV Mass Matrix "
1381 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1382
1383 /**********************************************************************************/
1384 /* Compute HDiv Stiffness Matrix */
1385 /**********************************************************************************/
1386
1387 // transform to physical coordinates
1388 IntrepidFSTools::HDIVtransformDIV<double>(HDivsTransformed, worksetJacobDet,
1389 HDivs);
1390
1391 // combine kappa value with weighted measure
1392 cellCounter = 0;
1393 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1394 for (int nPt = 0; nPt < numCubPoints; nPt++){
1395 weightedMeasureKappa(cellCounter,nPt) = weightedMeasure(cellCounter,nPt) * kappaVal(cell);
1396 }
1397 cellCounter++;
1398 }
1399
1400 // multiply by weighted measure
1401 IntrepidFSTools::multiplyMeasure<double>(HCValsTransformedWeighted,
1402 weightedMeasureKappa, HCValsTransformed);
1403
1404
1405
1406
1407
1408 // multiply by weighted measure
1409 IntrepidFSTools::multiplyMeasure<double>(HDivsTransformedWeighted,
1410 weightedMeasure, HDivsTransformed);
1411
1412 // integrate to compute element stiffness matrix
1413 IntrepidFSTools::integrate<double>(stiffMatrixHDiv,
1414 HDivsTransformed, HDivsTransformedWeighted,
1415 COMP_BLAS);
1416
1417 // apply face signs
1418 IntrepidFSTools::applyLeftFieldSigns<double>(stiffMatrixHDiv, worksetFaceSigns);
1419 IntrepidFSTools::applyRightFieldSigns<double>(stiffMatrixHDiv, worksetFaceSigns);
1420
1421 if(MyPID==0) {std::cout << "Compute HDiv Stiffness Matrix "
1422 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1423
1424 /**********************************************************************************/
1425 /* Compute HGrad Mass Matrix */
1426 /**********************************************************************************/
1427
1428 // transform to physical coordinates
1429 IntrepidFSTools::HGRADtransformVALUE<double>(HGValsTransformed, HGVals);
1430
1431 // multiply values with weighted measure
1432 IntrepidFSTools::multiplyMeasure<double>(HGValsTransformedWeighted,
1433 weightedMeasure, HGValsTransformed);
1434
1435 // integrate to compute element mass matrix
1436 IntrepidFSTools::integrate<double>(massMatrixHGrad,
1437 HGValsTransformed, HGValsTransformedWeighted,
1438 COMP_BLAS);
1439
1440 if(MyPID==0) {std::cout << "Compute HGRAD Mass Matrix "
1441 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1442
1443 /**********************************************************************************/
1444 /* Build Right Hand Side */
1445 /**********************************************************************************/
1446
1447 // transform integration points to physical points
1448 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPoints, cellWorkset, cellType);
1449
1450 // evaluate right hand side functions at physical points
1451 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1452
1453 // Compute cell ordinal relative to the current workset
1454 int worksetCellOrdinal = cell - worksetBegin;
1455
1456 for (int nPt = 0; nPt < numCubPoints; nPt++){
1457
1458 double x = worksetCubPoints(worksetCellOrdinal,nPt,0);
1459 double y = worksetCubPoints(worksetCellOrdinal,nPt,1);
1460 double z = worksetCubPoints(worksetCellOrdinal,nPt,2);
1461 double du1, du2, du3;
1462
1463 evalGradDivu(du1, du2, du3, x, y, z, kappaVal(cell));
1464 rhsDatag(worksetCellOrdinal,nPt,0) = du1;
1465 rhsDatag(worksetCellOrdinal,nPt,1) = du2;
1466 rhsDatag(worksetCellOrdinal,nPt,2) = du3;
1467
1468 rhsDatah(worksetCellOrdinal,nPt) = evalDivu(x, y, z);
1469 }
1470
1471 } // end workset cell loop
1472
1473 // integrate (g,curl w) term
1474 IntrepidFSTools::integrate<double>(gD, rhsDatag, HDValsTransformedWeighted,
1475 COMP_BLAS);
1476
1477 // integrate (h,div w) term
1478 IntrepidFSTools::integrate<double>(hD, rhsDatah, HDivsTransformedWeighted,
1479 COMP_BLAS);
1480
1481 // apply signs
1482 IntrepidFSTools::applyFieldSigns<double>(gD, worksetFaceSigns);
1483 IntrepidFSTools::applyFieldSigns<double>(hD, worksetFaceSigns);
1484
1485
1486 // calculate RHS boundary term
1487 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1488
1489 // Compute cell ordinal relative to the current workset
1490 int worksetCellOrdinal = cell - worksetBegin;
1491
1492 // evaluate boundary term
1493 for (int iface = 0; iface < numFacesPerElem; iface++){
1494 if (faceOnBoundary(elemToFace(cell,iface))){
1495
1496 // cell nodal coordinates
1497 for (int inode =0; inode < numNodesPerElem; inode++){
1498 cellNodes(0,inode,0) = cellWorkset(worksetCellOrdinal,inode,0);
1499 cellNodes(0,inode,1) = cellWorkset(worksetCellOrdinal,inode,1);
1500 cellNodes(0,inode,2) = cellWorkset(worksetCellOrdinal,inode,2);
1501 }
1502
1503 // cell face signs
1504 for (int jface =0; jface < numFacesPerElem; jface++){
1505 bcFaceSigns(0,jface) = worksetFaceSigns(worksetCellOrdinal,jface);
1506 }
1507
1508 // map Gauss points on quad to reference face: paramFacePoints -> refFacePoints
1509 IntrepidCTools::mapToReferenceSubcell(refFacePoints,
1510 paramFacePoints,
1511 2, iface, cellType);
1512
1513 // get basis values at points on reference cell
1514 hexHDivBasis.getValues(bcFaceDVals, refFacePoints, OPERATOR_VALUE);
1515
1516 // compute Jacobians at Gauss pts. on reference face for all parent cells
1517 IntrepidCTools::setJacobian(faceJacobians, refFacePoints,
1518 cellNodes, cellType);
1519 IntrepidCTools::setJacobianDet(faceJacobDet, faceJacobians);
1520
1521 // transform to physical coordinates
1522 IntrepidFSTools::HDIVtransformVALUE<double>(bcDValsTransformed, faceJacobians,
1523 faceJacobDet, bcFaceDVals);
1524
1525 // map Gauss points on quad from ref. face to face workset: refFacePoints -> worksetFacePoints
1526 IntrepidCTools::mapToPhysicalFrame(worksetFacePoints,
1527 refFacePoints,
1528 cellNodes, cellType);
1529
1530 // Compute face normals
1531 IntrepidCTools::getPhysicalFaceNormals(faceNormal,
1532 faceJacobians,
1533 iface, cellType);
1534
1535 #if 0
1536 // evaluate curl u at face points
1537 for(int nPt = 0; nPt < numFacePoints; nPt++){
1538
1539 double x = worksetFacePoints(0, nPt, 0);
1540 double y = worksetFacePoints(0, nPt, 1);
1541 double z = worksetFacePoints(0, nPt, 2);
1542
1543 evalCurlu(curluFace(0,nPt,0), curluFace(0,nPt,1),
1544 curluFace(0,nPt,2), x, y, z, muVal(cell));
1545 }
1546 // compute the cross product of curluFace with basis and multiply by weights
1547 for (int nF = 0; nF < numFieldsD; nF++){
1548 for(int nPt = 0; nPt < numFacePoints; nPt++){
1549 bcDataCrossField(0,nF,nPt,0) = (curluFace(0,nPt,1)*bcDValsTransformed(0,nF,nPt,2)
1550 - curluFace(0,nPt,2)*bcDValsTransformed(0,nF,nPt,1))
1551 * paramFaceWeights(nPt);
1552 bcDataCrossField(0,nF,nPt,1) = (curluFace(0,nPt,2)*bcDValsTransformed(0,nF,nPt,0)
1553 - curluFace(0,nPt,0)*bcDValsTransformed(0,nF,nPt,2))
1554 * paramFaceWeights(nPt);
1555 bcDataCrossField(0,nF,nPt,2) = (curluFace(0,nPt,0)*bcDValsTransformed(0,nF,nPt,1)
1556 - curluFace(0,nPt,1)*bcDValsTransformed(0,nF,nPt,0))
1557 *paramFaceWeights(nPt);
1558 } //nPt
1559 } //nF
1560
1561 // integrate
1562 IntrepidFSTools::integrate<double>(gDBoundary, faceNormal, bcDataCrossField,
1563 COMP_CPP);
1564 // apply signs
1565 IntrepidFSTools::applyFieldSigns<double>(gDBoundary, bcFaceSigns);
1566
1567 // add into gD term
1568 for (int nF = 0; nF < numFieldsD; nF++){
1569 gD(worksetCellOrdinal,nF) = gD(worksetCellOrdinal,nF) - gDBoundary(0,nF);
1570 }
1571 #endif
1572
1573 } // if faceOnBoundary
1574
1575 } // numFaces
1576
1577 }// *** workset cell loop **
1578
1579
1580
1581 if(MyPID==0) {std::cout << "Compute right-hand side "
1582 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1583
1584 /**********************************************************************************/
1585 /* Assemble into Global Matrix */
1586 /**********************************************************************************/
1587
1588 // Loop over workset cells
1589 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1590
1591 // Compute cell ordinal relative to the current workset
1592 int worksetCellOrdinal = cell - worksetBegin;
1593
1594
1595 /*** Assemble H(grad) mass matrix ***/
1596
1597 // loop over nodes for matrix row
1598 for (int cellNodeRow = 0; cellNodeRow < numFieldsG; cellNodeRow++){
1599
1600 int localNodeRow = elemToNode(cell, cellNodeRow);
1601 int globalNodeRow = globalNodeIds[localNodeRow];
1602
1603 // loop over nodes for matrix column
1604 for (int cellNodeCol = 0; cellNodeCol < numFieldsG; cellNodeCol++){
1605
1606 int localNodeCol = elemToNode(cell, cellNodeCol);
1607 int globalNodeCol = globalNodeIds[localNodeCol];
1608 double massGContribution = massMatrixHGrad(worksetCellOrdinal, cellNodeRow, cellNodeCol);
1609
1610 MassMatrixG.InsertGlobalValues(1, &globalNodeRow, 1, &globalNodeCol, &massGContribution);
1611
1612 }// *** cell node col loop ***
1613 }// *** cell node row loop ***
1614
1615
1616 /*** Assemble H(curl) mass matrix ***/
1617
1618 // loop over edges for matrix row
1619 for (int cellEdgeRow = 0; cellEdgeRow < numFieldsC; cellEdgeRow++){
1620
1621 int localEdgeRow = elemToEdge(cell, cellEdgeRow);
1622 int globalEdgeRow = globalEdgeIds[localEdgeRow];
1623
1624 // loop over edges for matrix column
1625 for (int cellEdgeCol = 0; cellEdgeCol < numFieldsC; cellEdgeCol++){
1626
1627 int localEdgeCol = elemToEdge(cell, cellEdgeCol);
1628 int globalEdgeCol = globalEdgeIds[localEdgeCol];
1629
1630 double massCContribution = massMatrixHCurl (worksetCellOrdinal, cellEdgeRow, cellEdgeCol);
1631
1632 MassMatrixC.InsertGlobalValues (1, &globalEdgeRow, 1, &globalEdgeCol, &massCContribution);
1633
1634 }// *** cell edge col loop ***
1635 }// *** cell edge row loop ***
1636
1637
1638 /*** Assemble H(div) mass matrix, stiffness matrix and right-hand side ***/
1639
1640 // loop over faces for matrix row
1641 for (int cellFaceRow = 0; cellFaceRow < numFieldsD; cellFaceRow++){
1642
1643 int localFaceRow = elemToFace(cell, cellFaceRow);
1644 int globalFaceRow = globalFaceIds[localFaceRow];
1645 double rhsContribution = gD(worksetCellOrdinal, cellFaceRow) + hD(worksetCellOrdinal, cellFaceRow);
1646
1647 rhsVector.SumIntoGlobalValues(1, &globalFaceRow, &rhsContribution);
1648
1649 // loop over faces for matrix column
1650 for (int cellFaceCol = 0; cellFaceCol < numFieldsD; cellFaceCol++){
1651
1652 int localFaceCol = elemToFace(cell, cellFaceCol);
1653 int globalFaceCol = globalFaceIds[localFaceCol];
1654
1655 double massDContribution = massMatrixHDiv (worksetCellOrdinal, cellFaceRow, cellFaceCol);
1656 double stiffDContribution = stiffMatrixHDiv(worksetCellOrdinal, cellFaceRow, cellFaceCol);
1657
1658 MassMatrixD.InsertGlobalValues (1, &globalFaceRow, 1, &globalFaceCol, &massDContribution);
1659 StiffMatrixD.InsertGlobalValues(1, &globalFaceRow, 1, &globalFaceCol, &stiffDContribution);
1660
1661
1662 }// *** cell face col loop ***
1663 }// *** cell face row loop ***
1664
1665 }// *** workset cell loop **
1666 }// *** workset loop ***
1667
1668 if(MyPID==0) {std::cout << "Assemble Matrices "
1669 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1670
1671
1672 /**********************************************************************************/
1673 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
1674 /**********************************************************************************/
1675
1676 // Assemble over multiple processors, if necessary
1677 MassMatrixG.GlobalAssemble(); MassMatrixG.FillComplete();
1678 MassMatrixC.GlobalAssemble(); MassMatrixC.FillComplete();
1679 MassMatrixD.GlobalAssemble(); MassMatrixD.FillComplete();
1680 StiffMatrixD.GlobalAssemble(); StiffMatrixD.FillComplete();
1681 rhsVector.GlobalAssemble();
1682
1683
1684 if(MyPID==0) {std::cout << "Global assembly "
1685 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1686
1687
1688 #ifdef DUMP_DATA
1689 // Node Coordinates
1690 EpetraExt::VectorToMatrixMarketFile("coordx.dat",Nx,0,0,false);
1691 EpetraExt::VectorToMatrixMarketFile("coordy.dat",Ny,0,0,false);
1692 EpetraExt::VectorToMatrixMarketFile("coordz.dat",Nz,0,0,false);
1693
1694 // Edge signs
1695 EpetraExt::MultiVectorToMatrixMarketFile("edge_signs.dat",edgeSign,0,0,false);
1696
1697 // Face signs
1698 EpetraExt::MultiVectorToMatrixMarketFile("face_signs.dat",faceSign,0,0,false);
1699 #endif
1700
1701 /**********************************************************************************/
1702 /*********************** ADJUST MATRICES AND RHS FOR BCs **************************/
1703 /**********************************************************************************/
1704
1705 // Build the inverse diagonal for MassMatrixC
1706 // We do this by computing the absolute rowsum and inverting that.
1707 Epetra_CrsMatrix MassMatrixCinv(Copy,MassMatrixC.RowMap(),MassMatrixC.RowMap(),1);
1708 Epetra_Vector DiagC(MassMatrixC.RowMap());
1709 Epetra_Vector temp(MassMatrixC.RowMap());
1710 temp.PutScalar(1.0);
1711 Multiply_Abs(MassMatrixC,temp,DiagC);
1712
1713 for(int i=0; i<DiagC.MyLength(); i++) {
1714 DiagC[i]=1.0/DiagC[i];
1715 }
1716 for(int i=0; i<DiagC.MyLength(); i++) {
1717 int CID=MassMatrixC.GCID(i);
1718 MassMatrixCinv.InsertGlobalValues(MassMatrixC.GRID(i),1,&(DiagC[i]),&CID);
1719 }
1720 MassMatrixCinv.FillComplete();
1721
1722 // Set value to zero on diagonal that corresponds to boundary edge
1723 for(int i=0;i<numEdges;i++) {
1724 if (edgeOnBoundary(i)){
1725 double val=0.0;
1726 int index = globalEdgeIds[i];
1727 MassMatrixCinv.ReplaceGlobalValues(index,1,&val,&index);
1728 }
1729 }
1730
1731 #ifdef DUMP_DATA
1732 EpetraExt::RowMatrixToMatlabFile("mag_k2_matrix.dat",StiffMatrixD);
1733 #endif
1734
1735 // Get the full matrix operator Kd += Md
1736 int rv=EpetraExt::MatrixMatrix::Add(MassMatrixD,false,1.0,StiffMatrixD,1.0);
1737 if(rv!=0) {printf("EpetraExt::MatrixMatrix:Add FAILED\n"); exit(1);}
1738
1739 // Apply it to v
1740 Epetra_MultiVector rhsDir(globalMapD,true);
1741 StiffMatrixD.Apply(v,rhsDir);
1742
1743 // Update right-hand side
1744 rhsVector.Update(-1.0,rhsDir,1.0);
1745
1746 // Update rhs values on Dirichlet edges
1747 indbc=0;
1748 int iOwned=0;
1749 for (int i=0; i<numFaces; i++){
1750 if (faceIsOwned[i]){
1751 if (faceOnBoundary(i)){
1752 indbc++;
1753 rhsVector[0][iOwned]=bndyFaceVal(bndyFaceToFace(i));
1754 }
1755 iOwned++;
1756 }
1757 }
1758
1759 // Zero out rows and columns of stiffness and mass matrix corresponding to Dirichlet faces
1760 // and add one to diagonal.
1761 ML_Epetra::Apply_OAZToMatrix(BCFaces, numBCFaces, StiffMatrixD);
1762 ML_Epetra::Apply_OAZToMatrix(BCFaces, numBCFaces, MassMatrixD);
1763
1764 delete [] BCFaces;
1765
1766 // Build Face-Node Incidence Matrix
1767 Epetra_CrsMatrix DGrad1(DGrad);
1768 Epetra_CrsMatrix DCurl1(DCurl);
1769 Epetra_CrsMatrix FaceNode(Copy,globalMapD,0);
1770 DGrad1.PutScalar(1.0);
1771 DCurl1.PutScalar(1.0);
1772 EpetraExt::MatrixMatrix::Multiply(DCurl1,false,DGrad1,false,FaceNode);
1773 FaceNode.PutScalar(1.0);
1774
1775 if(MyPID==0) {std::cout << "Adjust global matrix and rhs due to BCs " << Time.ElapsedTime()
1776 << " sec \n"; Time.ResetStartTime();}
1777
1778 #ifdef DUMP_DATA
1779 // Dump matrices to disk
1780 EpetraExt::RowMatrixToMatlabFile("mag_m0_matrix.dat",MassMatrixG);
1781 EpetraExt::RowMatrixToMatlabFile("mag_m1_matrix.dat",MassMatrixC);
1782 EpetraExt::RowMatrixToMatlabFile("mag_m1inv_matrix.dat",MassMatrixCinv);
1783 EpetraExt::RowMatrixToMatlabFile("mag_m2_matrix.dat",MassMatrixD);
1784 EpetraExt::RowMatrixToMatlabFile("mag_m2k2_matrix.dat",StiffMatrixD);
1785 EpetraExt::RowMatrixToMatlabFile("mag_t0_matrix.dat",DGrad);
1786 EpetraExt::RowMatrixToMatlabFile("mag_t1_matrix.dat",DCurl);
1787 EpetraExt::RowMatrixToMatlabFile("mag_fn_matrix.dat",FaceNode);
1788 EpetraExt::MultiVectorToMatrixMarketFile("mag_rhs2.dat",rhsVector,0,0,false);
1789 EpetraExt::VectorToMatrixMarketFile("diagc.dat",DiagC,0,0,false);
1790 #endif
1791
1792
1793 /**********************************************************************************/
1794 /*********************************** SOLVE ****************************************/
1795 /**********************************************************************************/
1796
1797 // Parameter list for ML
1798 Teuchos::ParameterList MLList,dummy,dummy2;
1799 double TotalErrorResidual=0, TotalErrorExactSol=0;
1800 ML_Epetra::SetDefaultsGradDiv(MLList);
1801 MLList.set("aggregation: threshold",0.0);
1802 MLList.set("ML output",10);
1803 Teuchos::ParameterList &MLList1=MLList.sublist("graddiv: 11list");
1804 MLList1.set("aggregation: threshold",0.0);
1805 MLList1.set("max levels",1);
1806 MLList1.set("x-coordinates",&Nx[0]);
1807 MLList1.set("y-coordinates",&Ny[0]);
1808 MLList1.set("z-coordinates",&Nz[0]);
1809 MLList1.set("ML output",10);
1810 Teuchos::ParameterList & MLList1f=MLList1.sublist("face matrix free: coarse");
1811 MLList1f.set("x-coordinates",&Nx[0]);
1812 MLList1f.set("y-coordinates",&Ny[0]);
1813 MLList1f.set("z-coordinates",&Nz[0]);
1814 MLList1f.set("ML output",10);
1815
1816 Teuchos::ParameterList &MLList2=MLList.sublist("graddiv: 22list");
1817 MLList2.set("x-coordinates",&Nx[0]);
1818 MLList2.set("y-coordinates",&Ny[0]);
1819 MLList2.set("z-coordinates",&Nz[0]);
1820 MLList2.set("ML output",10);
1821 Teuchos::ParameterList & MLList2e=MLList2.sublist("edge matrix free: coarse");
1822 MLList2e.set("x-coordinates",&Nx[0]);
1823 MLList2e.set("y-coordinates",&Ny[0]);
1824 MLList2e.set("z-coordinates",&Nz[0]);
1825 MLList2e.set("ML output",10);
1826
1827
1828 Epetra_FEVector xh(rhsVector);
1829 MassMatrixG.SetLabel("M0");
1830 MassMatrixC.SetLabel("M1");
1831 MassMatrixD.SetLabel("M2");
1832 StiffMatrixD.SetLabel("D2");
1833 DGrad.SetLabel("D0");
1834 DCurl.SetLabel("D1");
1835 MassMatrixCinv.SetLabel("M1^{-1}");
1836
1837 char probType[9] = "grad_div";
1838
1839 TestMultiLevelPreconditioner_GradDiv(probType, MLList, StiffMatrixD,
1840 DGrad, DCurl, FaceNode,
1841 MassMatrixC, MassMatrixCinv,
1842 MassMatrixD, xh, rhsVector,
1843 TotalErrorResidual, TotalErrorExactSol);
1844
1845 /**********************************************************************************/
1846 /**************************** CALCULATE ERROR *************************************/
1847 /**********************************************************************************/
1848
1849 if (MyPID == 0) {Time.ResetStartTime();}
1850
1851 double L2err = 0.0;
1852 double HDiverr = 0.0;
1853 double Linferr = 0.0;
1854 double L2errTot = 0.0;
1855 double HDiverrTot = 0.0;
1856 double LinferrTot = 0.0;
1857
1858 #ifdef HAVE_MPI
1859 // Import solution onto current processor
1860 Epetra_Map solnMap(numFacesGlobal, numFacesGlobal, 0, Comm);
1861 Epetra_Import solnImporter(solnMap, globalMapD);
1862 Epetra_FEVector uCoeff(solnMap);
1863 uCoeff.Import(xh, solnImporter, Insert);
1864 #endif
1865
1866 int numCells = 1;
1867 FieldContainer<double> hexFaceSigns(numCells, numFieldsD);
1868 FieldContainer<double> hexNodes(numCells, numFieldsG, spaceDim);
1869
1870 // Get cubature points and weights for error calc (may be different from previous)
1871 DefaultCubatureFactory<double> cubFactoryErr;
1872 int cubDegErr = 3;
1873 Teuchos::RCP<Cubature<double> > hexCubErr = cubFactoryErr.create(cellType, cubDegErr);
1874 int cubDimErr = hexCubErr->getDimension();
1875 int numCubPointsErr = hexCubErr->getNumPoints();
1876 FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
1877 FieldContainer<double> cubWeightsErr(numCubPointsErr);
1878 hexCubErr->getCubature(cubPointsErr, cubWeightsErr);
1879 FieldContainer<double> physCubPointsE(numCells,numCubPointsErr, cubDimErr);
1880
1881 // Containers for Jacobian
1882 FieldContainer<double> hexJacobianE(numCells, numCubPointsErr, spaceDim, spaceDim);
1883 FieldContainer<double> hexJacobInvE(numCells, numCubPointsErr, spaceDim, spaceDim);
1884 FieldContainer<double> hexJacobDetE(numCells, numCubPointsErr);
1885 FieldContainer<double> weightedMeasureE(numCells, numCubPointsErr);
1886
1887 // Evaluate basis values and curls at cubature points
1888 FieldContainer<double> uhDVals(numFieldsD, numCubPointsErr, spaceDim);
1889 FieldContainer<double> uhDValsTrans(numCells,numFieldsD, numCubPointsErr, spaceDim);
1890 FieldContainer<double> uhDivs(numFieldsD, numCubPointsErr);
1891 FieldContainer<double> uhDivsTrans(numCells, numFieldsD, numCubPointsErr);
1892 hexHDivBasis.getValues(uhDVals, cubPointsErr, OPERATOR_VALUE);
1893 hexHDivBasis.getValues(uhDivs, cubPointsErr, OPERATOR_DIV);
1894
1895
1896 // Loop over elements
1897 for (int k=0; k<numElems; k++){
1898
1899 double L2errElem = 0.0;
1900 double HDiverrElem = 0.0;
1901 double uExact1, uExact2, uExact3;
1902 double divuExact;
1903
1904 // physical cell coordinates
1905 for (int i=0; i<numNodesPerElem; i++) {
1906 hexNodes(0,i,0) = nodeCoord(elemToNode(k,i),0);
1907 hexNodes(0,i,1) = nodeCoord(elemToNode(k,i),1);
1908 hexNodes(0,i,2) = nodeCoord(elemToNode(k,i),2);
1909 }
1910 // Face signs
1911 for (int j=0; j<numFacesPerElem; j++) {
1912 hexFaceSigns(0,j) = -1.0;
1913 for (int i=0; i<numNodesPerFace; i++) {
1914 int indf=i+1;
1915 if (indf > numNodesPerFace) indf=0;
1916 if (elemToNode(k,refFaceToNode(j,0))==faceToNode(elemToFace(k,j),i) &&
1917 elemToNode(k,refFaceToNode(j,1))==faceToNode(elemToFace(k,j),indf))
1918 hexFaceSigns(0,j) = 1.0;
1919 }
1920 if (!faceIsOwned[elemToFace(k,j)]){
1921 hexFaceSigns(0,j)=-1.0*hexFaceSigns(0,j);
1922 }
1923 }
1924
1925 // compute cell Jacobians, their inverses and their determinants
1926 IntrepidCTools::setJacobian(hexJacobianE, cubPointsErr, hexNodes, cellType);
1927 IntrepidCTools::setJacobianInv(hexJacobInvE, hexJacobianE );
1928 IntrepidCTools::setJacobianDet(hexJacobDetE, hexJacobianE );
1929
1930 // transform integration points to physical points
1931 IntrepidCTools::mapToPhysicalFrame(physCubPointsE, cubPointsErr, hexNodes, cellType);
1932
1933 // transform basis values to physical coordinates
1934 IntrepidFSTools::HDIVtransformVALUE<double>(uhDValsTrans, hexJacobianE, hexJacobDetE, uhDVals);
1935 IntrepidFSTools::HDIVtransformDIV<double>(uhDivsTrans, hexJacobDetE, uhDivs);
1936
1937 // compute weighted measure
1938 IntrepidFSTools::computeCellMeasure<double>(weightedMeasureE, hexJacobDetE, cubWeightsErr);
1939
1940 // loop over cubature points
1941 for (int nPt = 0; nPt < numCubPointsErr; nPt++){
1942
1943 // get exact solution and divs
1944 double x = physCubPointsE(0,nPt,0);
1945 double y = physCubPointsE(0,nPt,1);
1946 double z = physCubPointsE(0,nPt,2);
1947 evalu(uExact1, uExact2, uExact3, x, y, z);
1948 divuExact = evalDivu(x, y, z);
1949
1950 // calculate approximate solution and divs
1951 double uApprox1 = 0.0;
1952 double uApprox2 = 0.0;
1953 double uApprox3 = 0.0;
1954 double divuApprox = 0.0;
1955 for (int i = 0; i < numFieldsD; i++){
1956 int rowIndex = globalFaceIds[elemToFace(k,i)];
1957 #ifdef HAVE_MPI
1958 double uh1 = uCoeff.Values()[rowIndex];
1959 #else
1960 double uh1 = xh.Values()[rowIndex];
1961 #endif
1962 uApprox1 += uh1*uhDValsTrans(0,i,nPt,0)*hexFaceSigns(0,i);
1963 uApprox2 += uh1*uhDValsTrans(0,i,nPt,1)*hexFaceSigns(0,i);
1964 uApprox3 += uh1*uhDValsTrans(0,i,nPt,2)*hexFaceSigns(0,i);
1965 divuApprox += uh1*uhDivsTrans(0,i,nPt)*hexFaceSigns(0,i);
1966 }
1967
1968 // evaluate the error at cubature points
1969 Linferr = max(Linferr, abs(uExact1 - uApprox1));
1970 Linferr = max(Linferr, abs(uExact2 - uApprox2));
1971 Linferr = max(Linferr, abs(uExact3 - uApprox3));
1972 L2errElem+=(uExact1 - uApprox1)*(uExact1 - uApprox1)*weightedMeasureE(0,nPt);
1973 L2errElem+=(uExact2 - uApprox2)*(uExact2 - uApprox2)*weightedMeasureE(0,nPt);
1974 L2errElem+=(uExact3 - uApprox3)*(uExact3 - uApprox3)*weightedMeasureE(0,nPt);
1975 HDiverrElem+=((divuExact - divuApprox)*(divuExact - divuApprox))
1976 *weightedMeasureE(0,nPt);
1977 }
1978
1979 L2err+=L2errElem;
1980 HDiverr+=HDiverrElem;
1981 }
1982
1983 #ifdef HAVE_MPI
1984 // sum over all processors
1985 Comm.SumAll(&L2err,&L2errTot,1);
1986 Comm.SumAll(&HDiverr,&HDiverrTot,1);
1987 Comm.MaxAll(&Linferr,&LinferrTot,1);
1988
1989 #else
1990 L2errTot = L2err;
1991 HDiverrTot = HDiverr;
1992 LinferrTot = Linferr;
1993 #endif
1994
1995
1996 if (MyPID == 0) {
1997 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
1998 std::cout << "HDiv Error: " << sqrt(HDiverrTot) <<"\n";
1999 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
2000 }
2001
2002
2003 // delete mesh
2004 Delete_Pamgen_Mesh();
2005
2006 //clean up
2007 for(long long b = 0; b < numElemBlk; b++){
2008 delete [] elmt_node_linkage[b];
2009 delete [] element_types[b];
2010 }
2011 delete [] block_ids;
2012 delete [] nodes_per_element;
2013 delete [] element_attributes;
2014 delete [] element_types;
2015 delete [] elmt_node_linkage;
2016 delete [] elements;
2017 delete [] nodeCoordx;
2018 delete [] nodeCoordy;
2019 delete [] nodeCoordz;
2020
2021 delete [] globalNodeIds;
2022 delete [] nodeIsOwned;
2023 delete [] globalEdgeIds;
2024 delete [] edgeIsOwned;
2025 delete [] globalFaceIds;
2026 delete [] faceIsOwned;
2027 if(num_node_comm_maps > 0){
2028 delete [] node_comm_proc_ids;
2029 delete [] node_cmap_node_cnts;
2030 delete [] node_cmap_ids;
2031 for(long long i=0;i<num_node_comm_maps;i++){
2032 delete [] comm_node_ids[i];
2033 delete [] comm_node_proc_ids[i];
2034 }
2035
2036 delete [] comm_node_ids;
2037 delete [] comm_node_proc_ids;
2038 }
2039
2040
2041 return 0;
2042 }
2043 /**********************************************************************************/
2044 /********************************* END MAIN ***************************************/
2045 /**********************************************************************************/
2046
2047
2048 /*************************************************************************************/
2049 /****************************** Multiply Ones ****************************************/
2050 /*************************************************************************************/
2051 /** \brief Multiplies Ax = y, where all non-zero entries of A are replaced with the value 1.0
2052
2053 \param A [in] matrix
2054 \param x [in] vector
2055 \param y [in] vector
2056 */
2057 int Multiply_Ones(const Epetra_CrsMatrix &A,const Epetra_Vector &x,Epetra_Vector &y){
2058 if(!A.Filled())
2059 EPETRA_CHK_ERR(-1); // Matrix must be filled.
2060
2061 double* xp = (double*) x.Values();
2062 double* yp = (double*) y.Values();
2063 const Epetra_Import* Importer_=A.Importer();
2064 const Epetra_Export* Exporter_=A.Exporter();
2065 Epetra_Vector *xcopy=0, *ImportVector_=0, *ExportVector_=0;
2066
2067 if (&x==&y && Importer_==0 && Exporter_==0) {
2068 xcopy = new Epetra_Vector(x);
2069 xp = (double *) xcopy->Values();
2070 }
2071 else if (Importer_)
2072 ImportVector_ = new Epetra_Vector(Importer_->TargetMap());
2073 else if (Exporter_)
2074 ExportVector_ = new Epetra_Vector(Exporter_->SourceMap());
2075
2076
2077 // If we have a non-trivial importer, we must import elements that are permuted or are on other processors
2078 if(Importer_ != 0) {
2079 EPETRA_CHK_ERR(ImportVector_->Import(x, *Importer_, Insert));
2080 xp = (double*) ImportVector_->Values();
2081 }
2082
2083 // If we have a non-trivial exporter, we must export elements that are permuted or belong to other processors
2084 if(Exporter_ != 0) yp = (double*) ExportVector_->Values();
2085
2086 // Do actual computation
2087 for(int i = 0; i < A.NumMyRows(); i++) {
2088 int NumEntries,*RowIndices;
2089 A.Graph().ExtractMyRowView(i,NumEntries,RowIndices);
2090 double sum = 0.0;
2091 for(int j = 0; j < NumEntries; j++)
2092 sum += xp[*RowIndices++];
2093 yp[i] = sum;
2094 }
2095
2096 if(Exporter_ != 0) {
2097 y.PutScalar(0.0); // Make sure target is zero
2098 EPETRA_CHK_ERR(y.Export(*ExportVector_, *Exporter_, Add)); // Fill y with Values from export vector
2099 }
2100 // Handle case of rangemap being a local replicated map
2101 if (!A.Graph().RangeMap().DistributedGlobal() && A.Comm().NumProc()>1) EPETRA_CHK_ERR(y.Reduce());
2102
2103 delete xcopy;
2104 delete ImportVector_;
2105 delete ExportVector_;
2106
2107
2108 return(0);
2109 }
2110
2111 /*************************************************************************************/
2112 /****************************** Multiply Abs *****************************************/
2113 /*************************************************************************************/
2114 // Multiplies abs(A)x = y, where all non-zero entries of A are replaced with their absolute values value
2115 int Multiply_Abs(const Epetra_CrsMatrix &A,const Epetra_Vector &x,Epetra_Vector &y){
2116 if(!A.Filled())
2117 EPETRA_CHK_ERR(-1); // Matrix must be filled.
2118
2119 double* xp = (double*) x.Values();
2120 double* yp = (double*) y.Values();
2121 const Epetra_Import* Importer_=A.Importer();
2122 const Epetra_Export* Exporter_=A.Exporter();
2123 Epetra_Vector *xcopy=0, *ImportVector_=0, *ExportVector_=0;
2124
2125 if (&x==&y && Importer_==0 && Exporter_==0) {
2126 xcopy = new Epetra_Vector(x);
2127 xp = (double *) xcopy->Values();
2128 }
2129 else if (Importer_)
2130 ImportVector_ = new Epetra_Vector(Importer_->TargetMap());
2131 else if (Exporter_)
2132 ExportVector_ = new Epetra_Vector(Exporter_->SourceMap());
2133
2134
2135 // If we have a non-trivial importer, we must import elements that are permuted or are on other processors
2136 if(Importer_ != 0) {
2137 EPETRA_CHK_ERR(ImportVector_->Import(x, *Importer_, Insert));
2138 xp = (double*) ImportVector_->Values();
2139 }
2140
2141 // If we have a non-trivial exporter, we must export elements that are permuted or belong to other processors
2142 if(Exporter_ != 0) yp = (double*) ExportVector_->Values();
2143
2144 // Do actual computation
2145 for(int i = 0; i < A.NumMyRows(); i++) {
2146 int NumEntries,*RowIndices;
2147 double *RowValues;
2148 A.ExtractMyRowView(i,NumEntries,RowValues,RowIndices);
2149 double sum = 0.0;
2150 for(int j = 0; j < NumEntries; j++){
2151 double v=*RowValues++;
2152 sum += ABS(v) * xp[*RowIndices++];
2153 }
2154 yp[i] = sum;
2155 }
2156
2157 if(Exporter_ != 0) {
2158 y.PutScalar(0.0); // Make sure target is zero
2159 EPETRA_CHK_ERR(y.Export(*ExportVector_, *Exporter_, Add)); // Fill y with Values from export vector
2160 }
2161 // Handle case of rangemap being a local replicated map
2162 if (!A.Graph().RangeMap().DistributedGlobal() && A.Comm().NumProc()>1) EPETRA_CHK_ERR(y.Reduce());
2163
2164 delete xcopy;
2165 delete ImportVector_;
2166 delete ExportVector_;
2167
2168
2169 return(0);
2170 }
2171
2172 /*************************************************************************************/
2173 /**************************** GET ML RESIDUAL ****************************************/
2174 /*************************************************************************************/
2175 /** \brief Compute ML solution residual
2176
2177 \param A [in] discrete operator
2178 \param lhs [in] solution vector
2179 \param rhs [in] right hand side vector
2180 \param Time [in] elapsed time for output
2181 \param TotalErrorResidual [out] error residual
2182 \param TotalErrorExactSol [out] error in xh (not an appropriate measure
2183 for H(div) basis functions)
2184 */
2185 void solution_test(string msg, const Epetra_Operator &A,const Epetra_MultiVector &lhs,const Epetra_MultiVector &rhs,const Epetra_MultiVector &xexact,Epetra_Time & Time, double & TotalErrorExactSol, double& TotalErrorResidual){
2186 // ==================================================== //
2187 // compute difference between exact solution and ML one //
2188 // ==================================================== //
2189 double d = 0.0, d_tot = 0.0;
2190 for( int i=0 ; i<lhs.Map().NumMyElements() ; ++i )
2191 d += (lhs[0][i] - xexact[0][i]) * (lhs[0][i] - xexact[0][i]);
2192
2193 A.Comm().SumAll(&d,&d_tot,1);
2194
2195 // ================== //
2196 // compute ||Ax - b|| //
2197 // ================== //
2198 double Norm;
2199 Epetra_Vector Ax(rhs.Map());
2200 A.Apply(lhs, Ax);
2201 Ax.Update(1.0, rhs, -1.0);
2202 Ax.Norm2(&Norm);
2203
2204 if (A.Comm().MyPID() == 0) {
2205 cout << msg << "......Using " << A.Comm().NumProc() << " processes" << endl;
2206 cout << msg << "......||A x - b||_2 = " << Norm << endl;
2207 // cout << msg << "......||x_exact - x||_2 = " << sqrt(d_tot) << endl;
2208 cout << msg << "......Total Time = " << Time.ElapsedTime() << endl;
2209 }
2210
2211 TotalErrorExactSol += sqrt(d_tot);
2212 TotalErrorResidual += Norm;
2213 }
2214
2215
2216 /*************************************************************************************/
2217 /*************************** ML PRECONDITIONER****************************************/
2218 /*************************************************************************************/
2219 void TestMultiLevelPreconditioner_GradDiv(char ProblemType[],
2220 Teuchos::ParameterList & MLList,
2221 Epetra_CrsMatrix & GradDiv,
2222 Epetra_CrsMatrix & D0clean,
2223 Epetra_CrsMatrix & D1clean,
2224 Epetra_CrsMatrix & FaceNode,
2225 Epetra_CrsMatrix & M1,
2226 Epetra_CrsMatrix & M1inv,
2227 Epetra_CrsMatrix & M2,
2228 Epetra_MultiVector & xh,
2229 Epetra_MultiVector & b,
2230 double & TotalErrorResidual,
2231 double & TotalErrorExactSol){
2232
2233 /* Nuke M1 for D0, OAZ*/
2234 Epetra_CrsMatrix D1(D1clean);
2235 ML_Epetra::Apply_BCsToGradient(GradDiv,D1);
2236
2237 /* Get the BC faces*/
2238 int numBCfaces;
2239 int* BCfaces=ML_Epetra::FindLocalDiricheltRowsFromOnesAndZeros(GradDiv,numBCfaces);
2240 ML_Epetra::Apply_OAZToMatrix(BCfaces,numBCfaces,M2);
2241 ArrayRCP<int> BCfaces_arcp(BCfaces,0,numBCfaces,false);
2242
2243 if(!GradDiv.Comm().MyPID())
2244 cout<<"Total number of rows = "<<GradDiv.NumGlobalRows()<<endl;
2245
2246 /* Build the AztecOO stuff */
2247 Epetra_MultiVector x(xh);
2248 x.PutScalar(0.0);
2249
2250 Epetra_LinearProblem Problem(&GradDiv,&x,&b);
2251 Epetra_MultiVector* lhs = Problem.GetLHS();
2252 Epetra_MultiVector* rhs = Problem.GetRHS();
2253
2254 Epetra_Time Time(GradDiv.Comm());
2255
2256 /* Build the aggregation guide matrix */
2257 Epetra_CrsMatrix *TMT_Agg_Matrix;
2258 ML_Epetra::ML_Epetra_PtAP(M1,D0clean,TMT_Agg_Matrix,false);
2259
2260 #ifdef DUMP_DATA
2261 // Dump matrices to disk
2262 EpetraExt::RowMatrixToMatlabFile("mag_tmt_matrix.dat",*TMT_Agg_Matrix);
2263 #endif
2264
2265 /* Build the EMFP Preconditioner */
2266 ML_Epetra::GradDivPreconditioner FMFP(GradDiv, FaceNode,D1clean,D0clean,*TMT_Agg_Matrix,MLList);
2267 // ML_Epetra::FaceMatrixFreePreconditioner FMFP(rcp(&Operator11,false),rcp(&Diagonal,false),rcp(&FaceNode,false),rcp(TMT_Agg_Matrix,false),BCfaces_arcp,MLList);
2268
2269 /* Solve! */
2270 AztecOO solver(Problem);
2271 solver.SetPrecOperator(&FMFP);
2272 solver.SetAztecOption(AZ_solver, AZ_cg);
2273 solver.SetAztecOption(AZ_output, 32);
2274 solver.Iterate(500, 1e-10);
2275 // solver.Iterate(1, 1e-10);
2276
2277 Epetra_MultiVector xexact(xh);
2278 xexact.PutScalar(0.0);
2279
2280 // accuracy check
2281 string msg = ProblemType;
2282 solution_test(msg,GradDiv,*lhs,*rhs,xexact,Time,TotalErrorExactSol,TotalErrorResidual);
2283
2284 #ifdef DUMP_DATA
2285 EpetraExt::MultiVectorToMatrixMarketFile("mag_lhs2.dat",*lhs,0,0,false);
2286 #endif
2287
2288
2289 xh = *lhs;
2290
2291 // Cleanup
2292 delete TMT_Agg_Matrix;
2293 delete [] BCfaces;
2294 }
2295
2296 /**********************************************************************************/
2297 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
2298 /**********************************************************************************/
2299
2300 // Calculates value of exact solution u
2301 int evalu(double & uExact0, double & uExact1, double & uExact2, double & x, double & y, double & z)
2302 {
2303
2304 /*
2305 // Exact Solution 1 - homogeneous boundary conditions, nonzero curl
2306 uExact0 = exp(y+z)*(x+1.0)*(x-1.0);
2307 uExact1 = exp(x+z)*(y+1.0)*(y-1.0);
2308 uExact2 = exp(x+y)*(z+1.0)*(z-1.0);
2309 */
2310
2311 /*
2312 // Exact Solution 2 - homogeneous boundary conditions, nonzero curl
2313 uExact0 = cos(M_PI*y)*cos(M_PI*z)*(x+1.0)*(x-1.0);
2314 uExact1 = cos(M_PI*x)*cos(M_PI*z)*(y+1.0)*(y-1.0);
2315 uExact2 = cos(M_PI*x)*cos(M_PI*y)*(z+1.0)*(z-1.0);
2316 */
2317
2318 /*
2319 // Exact Solution 3 - homogeneous boundary conditions, zero curl
2320 uExact0 = x*x-1.0;
2321 uExact1 = y*y-1.0;
2322 uExact2 = z*z-1.0;
2323 */
2324
2325 // Exact solution 4 - patch test with inhomogeneous boundary conditions,
2326 // zero curl, linear field should be recovered
2327 uExact0 = 1.0 + 2.0*x;
2328 uExact1 = 3.0 + 4.0*y;
2329 uExact2 = 5.0 + 6.0*z;
2330
2331 return 0;
2332 }
2333
2334 // Calculates divergence of exact solution u
2335 double evalDivu(double & x, double & y, double & z)
2336 {
2337
2338 // Exact Solution 1 - homogeneous boundary conditions, nonzero curl
2339 // double divu = 2.0*x*exp(y+z)+2.0*y*exp(x+z)+2.0*z*exp(x+y);
2340
2341 // Exact Solution 2 - homogeneous boundary conditions, nonzero curl
2342 //double divu = 2.0*x*cos(M_PI*y)*cos(M_PI*z) + 2.0*y*cos(M_PI*x)*cos(M_PI*z)
2343 // + 2.0*z*cos(M_PI*x)*cos(M_PI*y);
2344
2345 // Exact Solution 3 - homogeneous boundary conditions, zero curl
2346 // double divu = 2.0*(x + y + z);
2347
2348 // Exact solution 4 - patch test with inhomogeneous boundary conditions,
2349 // zero curl, linear field should be recovered
2350 double divu = 12.0;
2351
2352 return divu;
2353 }
2354
2355
2356 // Calculates curl of exact solution u
2357 int evalCurlu(double & curlu0, double & curlu1, double & curlu2,
2358 double & x, double & y, double & z, double & mu)
2359 {
2360
2361 /*
2362 // Exact Solution 1 - homogeneous boundary conditions, nonzero curl
2363 double duxdy = exp(y+z)*(x+1.0)*(x-1.0);
2364 double duxdz = exp(y+z)*(x+1.0)*(x-1.0);
2365 double duydx = exp(x+z)*(y+1.0)*(y-1.0);
2366 double duydz = exp(x+z)*(y+1.0)*(y-1.0);
2367 double duzdx = exp(x+y)*(z+1.0)*(z-1.0);
2368 double duzdy = exp(x+y)*(z+1.0)*(z-1.0);
2369 */
2370
2371
2372 /*
2373 // Exact Solution 2 - homogeneous boundary conditions, nonzero curl
2374 double duxdy = -M_PI*sin(M_PI*y)*cos(M_PI*z)*(x+1.0)*(x-1.0);
2375 double duxdz = -M_PI*sin(M_PI*z)*cos(M_PI*y)*(x+1.0)*(x-1.0);
2376 double duydx = -M_PI*sin(M_PI*x)*cos(M_PI*z)*(y+1.0)*(y-1.0);
2377 double duydz = -M_PI*sin(M_PI*z)*cos(M_PI*x)*(y+1.0)*(y-1.0);
2378 double duzdx = -M_PI*sin(M_PI*x)*cos(M_PI*y)*(z+1.0)*(z-1.0);
2379 double duzdy = -M_PI*sin(M_PI*y)*cos(M_PI*x)*(z+1.0)*(z-1.0);
2380 */
2381
2382 /*
2383 curlu0 = (duzdy - duydz)/mu;
2384 curlu1 = (duxdz - duzdx)/mu;
2385 curlu2 = (duydx - duxdy)/mu;
2386 */
2387
2388 /*
2389 // Exact Solution 3 - homogeneous boundary conditions, zero curl
2390 curlu0 = 0;
2391 curlu1 = 0;
2392 curlu2 = 0;
2393 */
2394
2395 // Exact solution 4 - patch test with inhomogeneous boundary conditions,
2396 // zero curl, linear field should be recovered
2397 curlu0 = 0;
2398 curlu1 = 0;
2399 curlu2 = 0;
2400
2401 return 0;
2402 }
2403
2404 // Calculates curl of the curl of exact solution u
2405 int evalGradDivu(double & gradDivu0, double & gradDivu1, double & gradDivu2,
2406 double & x, double & y, double & z, double & kappa)
2407 {
2408
2409 /*
2410 // Exact Solution 1 - homogeneous boundary conditions, nonzero curl
2411 double dcurlu0dy = exp(x+y)*(z+1.0)*(z-1.0) - 2.0*y*exp(x+z);
2412 double dcurlu0dz = 2.0*z*exp(x+y) - exp(x+z)*(y+1.0)*(y-1.0);
2413 double dcurlu1dx = 2.0*x*exp(y+z) - exp(x+y)*(z+1.0)*(z-1.0);
2414 double dcurlu1dz = exp(y+z)*(x+1.0)*(x-1.0) - 2.0*z*exp(x+y);
2415 double dcurlu2dx = exp(x+z)*(y+1.0)*(y-1.0) - 2.0*x*exp(y+z);
2416 double dcurlu2dy = 2.0*y*exp(x+z) - exp(y+z)*(x+1.0)*(x-1.0);
2417 */
2418
2419
2420 /*
2421 // Exact Solution 2 - homogeneous boundary conditions, nonzero curl
2422 double dcurlu0dy = -M_PI*M_PI*cos(M_PI*y)*cos(M_PI*x)*(z+1.0)*(z-1.0)
2423 + 2.0*y*M_PI*sin(M_PI*z)*cos(M_PI*x);
2424 double dcurlu0dz = -2.0*z*M_PI*sin(M_PI*y)*cos(M_PI*x)
2425 + M_PI*M_PI*cos(M_PI*z)*cos(M_PI*x)*(y+1.0)*(y-1.0);
2426 double dcurlu1dx = -2.0*x*M_PI*sin(M_PI*z)*cos(M_PI*y)
2427 + M_PI*M_PI*cos(M_PI*x)*cos(M_PI*y)*(z+1.0)*(z-1.0);
2428 double dcurlu1dz = -M_PI*M_PI*cos(M_PI*z)*cos(M_PI*y)*(x+1.0)*(x-1.0)
2429 + 2.0*z*M_PI*sin(M_PI*x)*cos(M_PI*y);
2430 double dcurlu2dx = -M_PI*M_PI*cos(M_PI*x)*cos(M_PI*z)*(y+1.0)*(y-1.0)
2431 + 2.0*x*M_PI*sin(M_PI*y)*cos(M_PI*z);
2432 double dcurlu2dy = -2.0*y*M_PI*sin(M_PI*x)*cos(M_PI*z)
2433 + M_PI*M_PI*cos(M_PI*y)*cos(M_PI*z)*(x+1.0)*(x-1.0);
2434 */
2435
2436 /*
2437 curlCurlu0 = (dcurlu2dy - dcurlu1dz)/mu;
2438 curlCurlu1 = (dcurlu0dz - dcurlu2dx)/mu;
2439 curlCurlu2 = (dcurlu1dx - dcurlu0dy)/mu;
2440 */
2441
2442 /*
2443 // Exact Solution 3 - homogeneous boundary conditions, zero curl
2444 curlCurlu0 = 0.0;
2445 curlCurlu1 = 0.0;
2446 curlCurlu2 = 0.0;
2447 */
2448
2449 // Exact solution 4 - patch test with inhomogeneous boundary conditions,
2450 // zero curl, linear field should be recovered
2451 gradDivu0 = 0.0;
2452 gradDivu1 = 0.0;
2453 gradDivu2 = 0.0;
2454
2455 return 0;
2456 }
2457