Debian Codegraph @

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