Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_Maxwell_Tpetra.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_Maxwell_Tpetra.cpp
11 \brief Example solution of the eddy current Maxwell's equations using
12 curl-conforming (edge) elements.
13
14
15 This example uses the following Trilinos packages:
16 \li Pamgen to generate a Hexahedral mesh.
17 \li Intrepid to build the discretization matrices and right-hand side.
18 \li Epetra to handle the global matrix and vector.
19 \li ML to solve the linear system.
20
21
22
23 \verbatim
24
25 Maxwell System:
26
27 curl x mu^{-1} curl E + sigma E = f
28
29 Corresponding discrete linear system for edge element coeficients (x):
30
31 (Kc + Mc)x = b
32
33 Kc - Hcurl stiffness matrix
34 Mc - Hcurl mass matrix
35 b - right hand side vector
36
37 \endverbatim
38
39 \author Created by P. Bochev, D. Ridzal, K. Peterson, D. Hensinger, C. Siefert.
40
41 \remark Usage
42 \verbatim
43
44 ./TrilinosCouplings_examples_scaling_Example_Maxwell.exe inputfile.xml
45
46
47 inputfile.xml (optional) - xml input file containing Pamgen mesh description
48 and material parameters for each Pamgen block,
49 if not present code attempts to read Maxwell.xml.
50
51 \endverbatim
52
53 Input files available in Trilinos for use with the Maxwell driver:
54
55 \li Maxwell.xml - basic input file with box mesh and one mesh block
56 \li Ninja.xml - input file with distorted mesh (shaped like Ninja star) and one mesh block
57 \li Maxwell_in_block.xml - input file with box mesh with a center block with different material values.
58
59 **/
60
61 /**************************************************************/
62 /* Includes */
63 /**************************************************************/
64 // TrilinosCouplings includes
65 #include "TrilinosCouplings_config.h"
66 #include "TrilinosCouplings_Pamgen_Utils.hpp"
67 #include "TrilinosCouplings_Statistics.hpp"
68 #include "TrilinosCouplings_IntrepidPoissonExample_SolveWithBelos.hpp"
69
70 // Intrepid includes
71 #include "Intrepid_FunctionSpaceTools.hpp"
72 #include "Intrepid_FieldContainer.hpp"
73 #include "Intrepid_CellTools.hpp"
74 #include "Intrepid_ArrayTools.hpp"
75 #include "Intrepid_HCURL_HEX_I1_FEM.hpp"
76 #include "Intrepid_HGRAD_HEX_C1_FEM.hpp"
77 #include "Intrepid_RealSpaceTools.hpp"
78 #include "Intrepid_DefaultCubatureFactory.hpp"
79 #include "Intrepid_Utils.hpp"
80
81 // Kokkos includes
82 #include "Kokkos_Core.hpp"
83
84 // Tpetra includes
85 #include "Tpetra_Map.hpp"
86 #include "Tpetra_Import.hpp"
87 #include "Tpetra_Export.hpp"
88 #include "Tpetra_CrsMatrix.hpp"
89 #include "Tpetra_FECrsMatrix.hpp"
90 #include "Tpetra_FECrsGraph.hpp"
91 #include "Tpetra_FEMultiVector.hpp"
92 #include "Tpetra_Assembly_Helpers.hpp"
93 #include "TpetraExt_MatrixMatrix.hpp"
94 #include "MatrixMarket_Tpetra.hpp"
95 #include "Tpetra_applyDirichletBoundaryCondition.hpp"
96
97
98
99 // Teuchos includes
100 #include "Teuchos_oblackholestream.hpp"
101 #include "Teuchos_RCP.hpp"
102 #include "Teuchos_BLAS.hpp"
103 #include "Teuchos_GlobalMPISession.hpp"
104 #include "Teuchos_ParameterList.hpp"
105 #include "Teuchos_XMLParameterListHelpers.hpp"
106 #include "Teuchos_Comm.hpp"
107 #include "Teuchos_OrdinalTraits.hpp"
108 #include "Teuchos_StackedTimer.hpp"
109
110 // Shards includes
111 #include "Shards_CellTopology.hpp"
112
113
114 // Xpetra
115 #include <Xpetra_MultiVector.hpp>
116 #include <Xpetra_MultiVectorFactory.hpp>
117 #include <Xpetra_CrsMatrix.hpp>
118 #include <Xpetra_CrsMatrixWrap.hpp>
119 #include <Xpetra_Matrix.hpp>
120
121 // Belos includes
122 #include <BelosConfigDefs.hpp>
123 #include <BelosLinearProblem.hpp>
124 #include <BelosSolverFactory.hpp>
125 #include <BelosXpetraAdapter.hpp>
126 #include <BelosMueLuAdapter.hpp>
127
128 // MueLu
129 #include <MueLu_RefMaxwell.hpp>
130 #include <MueLu_Exceptions.hpp>
131
132
133 // Pamgen includes
134 #include "create_inline_mesh.h"
135 #include "pamgen_im_exodusII_l.h"
136 #include "pamgen_im_ne_nemesisI_l.h"
137 #include "pamgen_extras.h"
138
139
140 #ifdef HAVE_TRILINOSCOUPLINGS_STRATIMIKOS
141 #include "Stratimikos_DefaultLinearSolverBuilder.hpp"
142 #include <Stratimikos_MueLuHelpers.hpp>
143 #ifdef HAVE_TRILINOSCOUPLINGS_IFPACK2
144 #include <Thyra_Ifpack2PreconditionerFactory.hpp>
145 #endif
146 #endif
147
148 //#include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
149
150
151 #define ABS(x) ((x)>0?(x):-(x))
152 #define SQR(x) ((x)*(x))
153
154
155 #define TC_sumAll(rcpComm, in, out) \
156 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_SUM, in, Teuchos::outArg(out))
157 #define TC_minAll(rcpComm, in, out) \
158 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MIN, in, Teuchos::outArg(out))
159 #define TC_maxAll(rcpComm, in, out) \
160 Teuchos::reduceAll(*rcpComm, Teuchos::REDUCE_MAX, in, Teuchos::outArg(out))
161
162
163
164 using namespace std;
165 using namespace Intrepid;
166 using Teuchos::RCP;
167 using Teuchos::rcp;
168 using Teuchos::rcp_dynamic_cast;
169
170 // Typedefs for Tpetra
171 typedef double SC;
172 typedef int LO;
173 typedef Tpetra::Map<>::global_ordinal_type GO;
174 typedef Tpetra::Map<>::node_type Node;
175 typedef Node NO;
176
177 typedef Tpetra::CrsMatrix<SC, LO, GO, Node> Tpetra_CrsMatrix;
178 typedef Tpetra::FECrsMatrix<SC, LO, GO, Node> Tpetra_FECrsMatrix;
179 typedef Tpetra::FECrsGraph<LO, GO, Node> Tpetra_FECrsGraph;
180 typedef Tpetra::MultiVector<SC, LO, GO, Node> Tpetra_MultiVector;
181 typedef Tpetra::FEMultiVector<SC, LO, GO, Node> Tpetra_FEMultiVector;
182 typedef Tpetra::Vector<SC, LO, GO, Node> Tpetra_Vector;
183 typedef Tpetra::Map<LO, GO, Node> Tpetra_Map;
184 typedef Tpetra::Import<LO, GO, Node> Tpetra_Import;
185 typedef Tpetra::Export<LO, GO, Node> Tpetra_Export;
186 typedef Tpetra::Operator<SC, LO, GO, Node> Tpetra_Operator;
187
188 typedef Xpetra::Operator<SC, LO, GO, Node> Xpetra_Operator;
189 typedef Xpetra::Matrix<SC,LO,GO,NO> Matrix;
190 typedef Xpetra::MultiVector<SC,LO,GO,NO> Xpetra_MultiVector;
191 // typedef Xpetra::CrsMatrix<SC,LO,GO,NO> CrsMatrix;
192 // typedef Xpetra::TpetraCrsMatrix<SC,LO,GO,NO> TpetraCrsMatrix;
193
194
195
196
197
198
199
200 /*********************************************************/
201 /* Typedefs */
202 /*********************************************************/
203 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
204 typedef Intrepid::RealSpaceTools<double> IntrepidRSTools;
205 typedef Intrepid::CellTools<double> IntrepidCTools;
206
207
208 struct fecomp{
209 bool operator () ( topo_entity* x, topo_entity* y )const
210 {
211 if(x->sorted_local_node_ids < y->sorted_local_node_ids)return true;
212 return false;
213 }
214 };
215
216 template<class Container>
217 double distance(Container &nodeCoord, int i1, int i2) {
218 double dist = 0.0;
219 for(int j=0; j<3; j++)
220 dist+= SQR( nodeCoord(i1,j) - nodeCoord(i2,j) );
221 return sqrt(dist);
222 }
223
224
225 RCP<Matrix> toXpetra(RCP<Tpetra_CrsMatrix> & mat) {
226 typedef Xpetra::CrsMatrix<SC,LO,GO,NO> CrsMatrix;
227 typedef Xpetra::TpetraCrsMatrix<SC,LO,GO,NO> TpetraCrsMatrix;
228 typedef Xpetra::CrsMatrixWrap<SC,LO,GO,NO> CrsMatrixWrap;
229 RCP<CrsMatrix> ccMat = rcp(new TpetraCrsMatrix(mat));
230 RCP<CrsMatrixWrap> ccOp = rcp(new CrsMatrixWrap(ccMat));
231 return rcp_dynamic_cast<Matrix>(ccOp);
232 }
233
234 RCP<Xpetra_MultiVector> toXpetra(RCP<Tpetra_MultiVector> & vec) {
235 typedef Xpetra::TpetraMultiVector<SC,LO,GO,NO> TpetraMultiVector;
236 return rcp(new TpetraMultiVector(vec));
237 }
238
239 /**********************************************************************************/
240 /***************** FUNCTION DECLARATION FOR ML PRECONDITIONER *********************/
241 /**********************************************************************************/
242
243
244 /** \brief MueLu Preconditioner
245 \param ProblemType [in] problem type
246 \param MLList [in] Parameter list
247 \param CurlCurl [in] H(curl) stiffness matrix
248 \param D0clean [in] Edge to node stiffness matrix
249 \param M0inv [in] H(grad) mass matrix inverse
250 \param Ms [in] H(curl) mass matrix w/ sigma
251 \param M1 [in] H(curl) mass matrix w/o sigm
252 */
253 RCP<Xpetra_Operator> BuildPreconditioner_MueLu(char ProblemType[],
254 Teuchos::ParameterList & MLList,
255 RCP<Tpetra_CrsMatrix> & CurlCurl,
256 RCP<Tpetra_CrsMatrix> & D0clean,
257 RCP<Tpetra_CrsMatrix> & M0inv,
258 RCP<Tpetra_CrsMatrix> & Ms,
259 RCP<Tpetra_CrsMatrix> & M1,
260 RCP<Tpetra_MultiVector> & coords);
261
262 #ifdef HAVE_TRILINOSCOUPLINGS_STRATIMIKOS
263
264 /** \brief Stratimikos Preconditioner
265 \param ProblemType [in] problem type
266 \param MLList [in] Parameter list
267 \param CurlCurl [in] H(curl) stiffness matrix
268 \param D0clean [in] Edge to node stiffness matrix
269 \param M0inv [in] H(grad) mass matrix inverse
270 \param Ms [in] H(curl) mass matrix w/ sigma
271 \param M1 [in] H(curl) mass matrix w/o sigma
272 */
273
274 void TestPreconditioner_Stratimikos(char ProblemType[],
275 Teuchos::ParameterList & SList,
276 RCP<Tpetra_CrsMatrix> & CurlCurl,
277 RCP<Tpetra_CrsMatrix> & D0clean,
278 RCP<Tpetra_CrsMatrix> & M0inv,
279 RCP<Tpetra_CrsMatrix> & Ms,
280 RCP<Tpetra_CrsMatrix> & M1,
281 RCP<Tpetra_MultiVector> & coords,
282 RCP<Tpetra_MultiVector> & x,
283 RCP<Tpetra_MultiVector> & b);
284
285 #endif
286
287 /**********************************************************************************/
288 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
289 /**********************************************************************************/
290
291 /** \brief Exact solution evaluation.
292
293 \param uExact0 [out] first component of exact solution at (x,y,z)
294 \param uExact1 [out] second component of exact solution at (x,y,z)
295 \param uExact2 [out] third component of exact solution at (x,y,z)
296 \param x [in] x coordinate
297 \param y [in] y coordinate
298 \param z [in] z coordinate
299 */
300 int evalu(double & uExact0,
301 double & uExact1,
302 double & uExact2,
303 double & x,
304 double & y,
305 double & z);
306
307 /** \brief Curl of exact solution.
308
309 \param curlu0 [out] first component of curl of exact solution
310 \param curlu1 [out] second component of curl of exact solution
311 \param curlu2 [out] third component of curl of exact solution
312 \param x [in] x coordinate
313 \param y [in] y coordinate
314 \param z [in] z coordinate
315 \param mu [in] material parameter
316 */
317 int evalCurlu(double & curlu0,
318 double & curlu1,
319 double & curlu2,
320 double & x,
321 double & y,
322 double & z,
323 double & mu);
324
325 /** \brief CurlCurl of exact solution.
326
327 \param curlcurlu0 [out] first component of curl-curl of exact solution
328 \param curlcurlu1 [out] second component of curl-curl of exact solution
329 \param curlcurlu2 [out] third component of curl-curl of exact solution
330 \param x [in] x coordinate
331 \param y [in] y coordinate
332 \param z [in] z coordinate
333 \param mu [in] material parameter
334 */
335 int evalCurlCurlu(double & curlcurlu0,
336 double & curlcurlu1,
337 double & curlcurlu2,
338 double & x,
339 double & y,
340 double & z,
341 double & mu);
342
343 /**********************************************************************************/
344 /**********************************************************************************/
345 /**********************************************************************************/
346
347
348
349 /**********************************************************************************/
350 /******************************** MAIN ********************************************/
351 /**********************************************************************************/
352 #ifndef HAVE_MPI
353 int main(int argc, char *argv[]) {
354 return 0;
355 }
356 #else
357 int body(int argc, char *argv[]);
358
359 int main(int argc, char *argv[]) {
360 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
361 Kokkos::initialize(argc,argv);
362 body(argc,argv);
363 if (!Kokkos::is_finalized())
364 Kokkos::finalize();
365 }
366
367
368 int body(int argc, char *argv[]) {
369 // using namespace TrilinosCouplings;
370 // using IntrepidPoissonExample::parseCommandLineArguments;
371 // using IntrepidPoissonExample::setCommandLineArgumentDefaults;
372 // using IntrepidPoissonExample::setMaterialTensorOffDiagonalValue;
373 // using IntrepidPoissonExample::setUpCommandLineArguments;
374 using Teuchos::CommandLineProcessor;
375
376 int error = 0;
377 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
378 int rank=comm->getRank();
379 int numProcs=comm->getSize();
380 int MyPID=rank;
381
382 // Did the user specify --help at the command line to print help
383 // with command-line arguments?
384 bool printedHelp = false;
385 // Values of command-line arguments.
386 int nx, ny, nz;
387 std::string xmlInFileName, xmlStratimikos;
388 bool verbose, debug, jiggle, dump;
389 std::string solverName;
390 double scaling = 1.0;
391 bool use_stacked_timer;
392
393 // Set default values of command-line arguments.
394 nx = 10;
395 ny = 10;
396 nz = 10;
397 xmlInFileName = "Maxwell.xml";
398 xmlStratimikos = "stratimikos.xml";
399 solverName = "default";
400 verbose = false;
401 debug = false;
402 jiggle = false;
403 dump = false;
404 use_stacked_timer = false;
405 // Parse and validate command-line arguments.
406 Teuchos::CommandLineProcessor cmdp (false, true);
407 cmdp.setOption ("nx", &nx, "Number of cells along the x dimension");
408 cmdp.setOption ("ny", &ny, "Number of cells along the y dimension");
409 cmdp.setOption ("nz", &nz, "Number of cells along the z dimension");
410 cmdp.setOption ("inputParams", &xmlInFileName, "XML file of input "
411 "parameters, which we read if specified and not \"\". "
412 "If it has a \"meshInput\" parameter, we use its "
413 "std::string value as the Pamgen mesh specification. "
414 "Otherwise, we tell Pamgen to make a cube, using "
415 "nx, ny, and nz.");
416 cmdp.setOption ("stratimikosParams", &xmlStratimikos, "XML file with Stratimikos inputs");
417 cmdp.setOption ("solverName", &solverName, "Name of iterative linear solver "
418 "to use for solving the linear system. Examples include "
419 "\"MueLu\", and \"Stratimikos\".");
420 cmdp.setOption ("verbose", "quiet", &verbose,
421 "Whether to print verbose status output.");
422 cmdp.setOption ("debug", "release", &debug,
423 "Whether to print copious debugging output to stderr.");
424 cmdp.setOption ("scaling", &scaling, "scale mass matrix");
425 cmdp.setOption ("jiggle", "nojiggle", &jiggle,
426 "Whether to randomly perturb the mesh.");
427 cmdp.setOption ("dump", "nodump", &dump,
428 "Whether to dump data.");
429 cmdp.setOption ("stacked-timer", "no-stacked-timer", &use_stacked_timer,
430 "Run with or without stacked timer output");
431
432 if (MyPID == 0) {
433 std::cout \
434 << "===============================================================================\n" \
435 << "| |\n" \
436 << "| Example: Solve Div-Curl System on Hexahedral Mesh |\n" \
437 << "| with Curl-conforming Elements |\n" \
438 << "| |\n" \
439 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
440 << "| Denis Ridzal ([email protected]), |\n" \
441 << "| Kara Peterson ([email protected]). |\n" \
442 << "| |\n" \
443 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
444 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
445 << "| MueLu's website: http://trilinos.sandia.gov/packages/muelu |\n" \
446 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
447 << "| |\n" \
448 << "===============================================================================\n";
449 }
450
451 const CommandLineProcessor::EParseCommandLineReturn parseResult =
452 cmdp.parse (argc, argv);
453 if (parseResult == CommandLineProcessor::PARSE_HELP_PRINTED) {
454 printedHelp = true;
455 }
456 else {
457 printedHelp = false;
458 TEUCHOS_TEST_FOR_EXCEPTION(
459 parseResult != CommandLineProcessor::PARSE_SUCCESSFUL,
460 std::invalid_argument, "Failed to parse command-line arguments.");
461 TEUCHOS_TEST_FOR_EXCEPTION(
462 xmlInFileName == "" && (nx <= 0 || ny <= 0 || nz <= 0),
463 std::invalid_argument, "If no XML parameters filename is specified (via "
464 "--inputParams), then the number of cells along each dimension of the "
465 "mesh (--nx, --ny, and --nz) must be positive.");
466 }
467
468 if (printedHelp) {
469 // The user specified --help at the command line to print help
470 // with command-line arguments. We printed help already, so quit
471 // with a happy return code.
472 return EXIT_SUCCESS;
473 }
474
475 Teuchos::RCP<Teuchos::StackedTimer> stacked_timer;
476 if (use_stacked_timer) {
477 stacked_timer = rcp(new Teuchos::StackedTimer("TC Maxwell Tpetra"));
478 Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::rcp(new Teuchos::FancyOStream(Teuchos::rcpFromRef(std::cout)));
479 stacked_timer->setVerboseOstream(out);
480 Teuchos::TimeMonitor::setStackedTimer(stacked_timer);
481 }
482
483 long long * node_comm_proc_ids = NULL;
484 long long * node_cmap_node_cnts = NULL;
485 long long * node_cmap_ids = NULL;
486 long long ** comm_node_ids = NULL;
487 long long ** comm_node_proc_ids = NULL;
488
489 std::set < topo_entity * , fecomp > edge_set;
490 std::set < topo_entity * , fecomp > face_set;
491
492 std::vector < topo_entity * > edge_vector;
493 std::vector < topo_entity * > face_vector;
494
495 std::vector < int > edge_comm_procs;
496
497
498 /**********************************************************************************/
499 /********************************** GET XML INPUTS ********************************/
500 /**********************************************************************************/
501
502 // Read xml file into parameter list
503 Teuchos::ParameterList inputList;
504
505 if(xmlInFileName.length()) {
506 if (MyPID == 0) {
507 std::cout << "\nReading parameter list from the XML file \""<<xmlInFileName<<"\" ...\n\n";
508 }
509 Teuchos::updateParametersFromXmlFile(xmlInFileName,Teuchos::ptr (&inputList));
510 if (MyPID == 0) {
511 inputList.print(std::cout,2,true,true);
512 std::cout << "\n";
513 }
514 }
515 // Get pamgen mesh definition
516 std::string meshInput = \
517 "mesh \n"
518 " brick \n"
519 " zmin = 0.0 \n"
520 " xmin = 0.0 \n"
521 " ymin = 0.0 \n"
522 " numz 1 \n"
523 " zblock 1 1.0 interval " + std::to_string(nz) + "\n" +
524 " numx 1 \n"
525 " xblock 1 1.0 interval " + std::to_string(nx) + "\n" +
526 " numy 1 \n"
527 " yblock 1 1.0 interval " + std::to_string(ny) + "\n" +
528 " end \n"
529 " set assign \n"
530 " sideset, ilo, 1 \n"
531 " sideset, jlo, 2 \n"
532 " sideset, klo, 3 \n"
533 " sideset, ihi, 4 \n"
534 " sideset, jhi, 5 \n"
535 " sideset, khi, 6 \n"
536 " end \n"
537 "end \n";
538 meshInput = inputList.get("meshInput", meshInput);
539
540 // Get the solver name from input deck or command line
541 if(solverName == "default") {
542 if(inputList.isParameter("Preconditioner"))
543 solverName=inputList.get("Preconditioner","MueLu");
544 else
545 solverName="MueLu";
546 }
547
548
549
550
551
552 /**********************************************************************************/
553 /***************************** GET CELL TOPOLOGY **********************************/
554 /**********************************************************************************/
555
556 // Get cell topology for base hexahedron
557 shards::CellTopology cellType(shards::getCellTopologyData<shards::Hexahedron<8> >() );
558
559 // Get dimensions
560 int numNodesPerElem = cellType.getNodeCount();
561 int numEdgesPerElem = cellType.getEdgeCount();
562 int numFacesPerElem = cellType.getSideCount();
563 int numNodesPerEdge = 2;
564 int numNodesPerFace = 4;
565 int numEdgesPerFace = 4;
566 int spaceDim = cellType.getDimension();
567
568 // Build reference element edge to node map
569 FieldContainer<int> refEdgeToNode(numEdgesPerElem,numNodesPerEdge);
570 for (int i=0; i<numEdgesPerElem; i++){
571 refEdgeToNode(i,0)=cellType.getNodeMap(1, i, 0);
572 refEdgeToNode(i,1)=cellType.getNodeMap(1, i, 1);
573 }
574
575 // Build reference element face to node map
576 FieldContainer<int> refFaceToNode(numFacesPerElem,numNodesPerFace);
577 for (int i=0; i<numFacesPerElem; i++){
578 refFaceToNode(i,0)=cellType.getNodeMap(2, i, 0);
579 refFaceToNode(i,1)=cellType.getNodeMap(2, i, 1);
580 refFaceToNode(i,2)=cellType.getNodeMap(2, i, 2);
581 refFaceToNode(i,3)=cellType.getNodeMap(2, i, 3);
582 }
583
584 // Build reference element face to edge map (Hardcoded for now)
585 FieldContainer<int> refFaceToEdge(numFacesPerElem,numEdgesPerFace);
586 refFaceToEdge(0,0)=0; refFaceToEdge(0,1)=9;
587 refFaceToEdge(0,2)=4; refFaceToEdge(0,3)=8;
588 refFaceToEdge(1,0)=1; refFaceToEdge(1,1)=10;
589 refFaceToEdge(1,2)=5; refFaceToEdge(1,3)=9;
590 refFaceToEdge(2,0)=2; refFaceToEdge(2,1)=11;
591 refFaceToEdge(2,2)=6; refFaceToEdge(2,3)=10;
592 refFaceToEdge(3,0)=3; refFaceToEdge(3,1)=8;
593 refFaceToEdge(3,2)=7; refFaceToEdge(3,3)=11;
594 refFaceToEdge(4,0)=0; refFaceToEdge(4,1)=1;
595 refFaceToEdge(4,2)=2; refFaceToEdge(4,3)=3;
596 refFaceToEdge(5,0)=4; refFaceToEdge(5,1)=5;
597 refFaceToEdge(5,2)=6; refFaceToEdge(5,3)=7;
598
599
600 /**********************************************************************************/
601 /******************************* GENERATE MESH ************************************/
602 /**********************************************************************************/
603
604
605 if (MyPID == 0) {
606 std::cout << "Generating mesh ... \n\n";
607 }
608
609 // Generate mesh with Pamgen
610 int dim=3;
611 long long maxInt = 9223372036854775807LL;
612 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
613 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
614
615 // Get local mesh size info
616 char title[100];
617 long long numDim;
618 long long numNodes;
619 long long numElems;
620 long long numElemBlk;
621 long long numNodeSets;
622 long long numSideSets;
623 int id = 0;
624
625 im_ex_get_init_l(id, title, &numDim, &numNodes,
626 &numElems, &numElemBlk, &numNodeSets,
627 &numSideSets);
628
629 // Get global mesh size info
630 long long numNodesGlobal;
631 long long numElemsGlobal;
632 long long numElemBlkGlobal;
633 long long numNodeSetsGlobal;
634 long long numSideSetsGlobal;
635
636 im_ne_get_init_global_l(id, &numNodesGlobal, &numElemsGlobal,
637 &numElemBlkGlobal, &numNodeSetsGlobal,
638 &numSideSetsGlobal);
639
640 MachineLearningStatistics_Hex3D<SC,LO,GO,Node> MLStatistics(numElemsGlobal);
641
642
643 long long * block_ids = new long long [numElemBlk];
644 error += im_ex_get_elem_blk_ids_l(id, block_ids);
645
646
647 long long *nodes_per_element = new long long [numElemBlk];
648 long long *element_attributes = new long long [numElemBlk];
649 long long *elements = new long long [numElemBlk];
650 char **element_types = new char * [numElemBlk];
651 long long **elmt_node_linkage = new long long * [numElemBlk];
652
653
654 for(long long i = 0; i < numElemBlk; i ++){
655 element_types[i] = new char [MAX_STR_LENGTH + 1];
656 error += im_ex_get_elem_block_l(id,
657 block_ids[i],
658 element_types[i],
659 (long long*)&(elements[i]),
660 (long long*)&(nodes_per_element[i]),
661 (long long*)&(element_attributes[i]));
662 }
663
664 /*connectivity*/
665 for(long long b = 0; b < numElemBlk; b++){
666 elmt_node_linkage[b] = new long long [nodes_per_element[b]*elements[b]];
667 error += im_ex_get_elem_conn_l(id,block_ids[b],elmt_node_linkage[b]);
668 }
669
670 // Get mu value for each block of elements from parameter list
671 double *mu = new double [numElemBlk];
672 for(int b = 0; b < numElemBlk; b++){
673 stringstream muBlock;
674 muBlock.clear();
675 muBlock << "mu" << b;
676 mu[b] = inputList.get(muBlock.str(),1.0);
677 }
678
679 // Get mu value for each block of elements from parameter list
680 double *sigma = new double [numElemBlk];
681 for(int b = 0; b < numElemBlk; b++){
682 stringstream sigmaBlock;
683 sigmaBlock.clear();
684 sigmaBlock << "sigma" << b;
685 sigma[b] = inputList.get(sigmaBlock.str(),1.0);
686 }
687
688 // Get node-element connectivity and set element mu/sigma value
689 int telct = 0;
690 FieldContainer<int> elemToNode(numElems,numNodesPerElem);
691 FieldContainer<double> muVal(numElems);
692 FieldContainer<double> sigmaVal(numElems);
693
694 for(long long b = 0; b < numElemBlk; b++){
695 for(long long el = 0; el < elements[b]; el++){
696 for (int j=0; j<numNodesPerElem; j++) {
697 elemToNode(telct,j) = elmt_node_linkage[b][el*numNodesPerElem + j]-1;
698 }
699 muVal(telct) = mu[b];
700 sigmaVal(telct) = sigma[b];
701
702 telct ++;
703 }
704 }
705
706 // Read node coordinates and place in field container
707 FieldContainer<double> nodeCoord(numNodes,dim);
708 double * nodeCoordx = new double [numNodes];
709 double * nodeCoordy = new double [numNodes];
710 double * nodeCoordz = new double [numNodes];
711 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,nodeCoordz);
712 for (int i=0; i<numNodes; i++) {
713 nodeCoord(i,0)=nodeCoordx[i];
714 nodeCoord(i,1)=nodeCoordy[i];
715 nodeCoord(i,2)=nodeCoordz[i];
716 }
717
718 /*parallel info*/
719 long long num_internal_nodes;
720 long long num_border_nodes;
721 long long num_external_nodes;
722 long long num_internal_elems;
723 long long num_border_elems;
724 long long num_node_comm_maps;
725 long long num_elem_comm_maps;
726 im_ne_get_loadbal_param_l( id,
727 &num_internal_nodes,
728 &num_border_nodes,
729 &num_external_nodes,
730 &num_internal_elems,
731 &num_border_elems,
732 &num_node_comm_maps,
733 &num_elem_comm_maps,
734 0/*unused*/ );
735
736 if(num_node_comm_maps > 0){
737 node_comm_proc_ids = new long long [num_node_comm_maps];
738 node_cmap_node_cnts = new long long [num_node_comm_maps];
739 node_cmap_ids = new long long [num_node_comm_maps];
740 comm_node_ids = new long long* [num_node_comm_maps];
741 comm_node_proc_ids = new long long* [num_node_comm_maps];
742
743 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
744 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
745 if ( im_ne_get_cmap_params_l( id,
746 node_cmap_ids,
747 (long long*)node_cmap_node_cnts,
748 elem_cmap_ids,
749 (long long*)elem_cmap_elem_cnts,
750 0/*not used proc_id*/ ) < 0 )++error;
751
752 for(long long j = 0; j < num_node_comm_maps; j++) {
753 comm_node_ids[j] = new long long [node_cmap_node_cnts[j]];
754 comm_node_proc_ids[j] = new long long [node_cmap_node_cnts[j]];
755 if ( im_ne_get_node_cmap_l( id,
756 node_cmap_ids[j],
757 comm_node_ids[j],
758 comm_node_proc_ids[j],
759 0/*not used proc_id*/ ) < 0 )++error;
760 node_comm_proc_ids[j] = comm_node_proc_ids[j][0];
761 }
762 }
763
764
765
766 //Calculate global node ids
767 long long * globalNodeIds = new long long[numNodes];
768 bool * nodeIsOwned = new bool[numNodes];
769
770 calc_global_node_ids(globalNodeIds,
771 nodeIsOwned,
772 numNodes,
773 num_node_comm_maps,
774 node_cmap_node_cnts,
775 node_comm_proc_ids,
776 comm_node_ids,
777 rank);
778
779 // Count owned nodes
780 LO ownedNodes=0;
781 for(int i=0;i<numNodes;i++)
782 if(nodeIsOwned[i]) ownedNodes++;
783
784 // Build a list of the OWNED global ids...
785 Teuchos::Array<GO> ownedGIDs(ownedNodes);
786 int oidx=0;
787 for(int i=0;i<numNodes;i++)
788 if(nodeIsOwned[i]){
789 ownedGIDs[oidx]=(GO)globalNodeIds[i];
790 oidx++;
791 }
792
793 FieldContainer<int> elemToEdge(numElems,numEdgesPerElem);
794 FieldContainer<int> elemToFace(numElems,numFacesPerElem);
795
796 // Calculate edge and face ids
797 int elct = 0;
798 for(long long b = 0; b < numElemBlk; b++){
799 if(nodes_per_element[b] == 4){
800 }
801 else if (nodes_per_element[b] == 8){
802 //loop over all elements and push their edges onto a set if they are not there already
803 for(long long el = 0; el < elements[b]; el++){
804 std::set< topo_entity *, fecomp > ::iterator fit;
805 for (int i=0; i < numEdgesPerElem; i++){
806 topo_entity * teof = new topo_entity;
807 for(int j = 0; j < numNodesPerEdge;j++){
808 teof->add_node(elmt_node_linkage[b][el*numNodesPerElem + refEdgeToNode(i,j)],globalNodeIds);
809 }
810 teof->sort();
811 fit = edge_set.find(teof);
812 if(fit == edge_set.end()){
813 teof->local_id = edge_vector.size();
814 edge_set.insert(teof);
815 elemToEdge(elct,i)= edge_vector.size();
816 edge_vector.push_back(teof);
817 }
818 else{
819 elemToEdge(elct,i) = (*fit)->local_id;
820 delete teof;
821 }
822 }
823 for (int i=0; i < numFacesPerElem; i++){
824 topo_entity * teof = new topo_entity;
825 for(int j = 0; j < numNodesPerFace;j++){
826 teof->add_node(elmt_node_linkage[b][el*numNodesPerElem + refFaceToNode(i,j)],globalNodeIds);
827 }
828 teof->sort();
829 fit = face_set.find(teof);
830 if(fit == face_set.end()){
831 teof->local_id = face_vector.size();
832 face_set.insert(teof);
833 elemToFace(elct,i)= face_vector.size();
834 face_vector.push_back(teof);
835 }
836 else{
837 elemToFace(elct,i) = (*fit)->local_id;
838 delete teof;
839 }
840 }
841 elct ++;
842 }
843 }
844 }
845
846 // Edge to Node connectivity
847 FieldContainer<int> edgeToNode(edge_vector.size(), numNodesPerEdge);
848 for(unsigned ect = 0; ect != edge_vector.size(); ect++){
849 std::list<long long>::iterator elit;
850 int nct = 0;
851 for(elit = edge_vector[ect]->local_node_ids.begin();
852 elit != edge_vector[ect]->local_node_ids.end();
853 elit ++){
854 edgeToNode(ect,nct) = *elit-1;
855 nct++;
856 }
857 }
858
859 // Face to Node connectivity
860 FieldContainer<int> faceToNode(face_vector.size(), numNodesPerFace);
861 for(unsigned fct = 0; fct != face_vector.size(); fct++){
862 std::list<long long>::iterator flit;
863 int nct = 0;
864 for(flit = face_vector[fct]->local_node_ids.begin();
865 flit != face_vector[fct]->local_node_ids.end();
866 flit ++){
867 faceToNode(fct,nct) = *flit-1;
868 nct++;
869 }
870 }
871
872 // Face to Edge connectivity
873 FieldContainer<int> faceToEdge(face_vector.size(), numEdgesPerFace);
874 FieldContainer<bool> faceDone(face_vector.size());
875 for (int ielem = 0; ielem < numElems; ielem++){
876 for (int iface = 0; iface < numFacesPerElem; iface++){
877 if (!faceDone(elemToFace(ielem,iface))){
878 for (int iedge = 0; iedge < numEdgesPerFace; iedge++){
879 faceToEdge(elemToFace(ielem,iface),iedge) =
880 elemToEdge(ielem,refFaceToEdge(iface,iedge));
881 faceDone(elemToFace(ielem,iface))=1;
882 }
883 }
884 }
885 }
886
887 int numEdges = edge_vector.size();
888 int numFaces = face_vector.size();
889
890 // Calculate global edge and face numbering
891 std::string doing_type;
892 doing_type = "EDGES";
893 calc_global_ids(edge_vector,
894 comm_node_ids,
895 node_comm_proc_ids,
896 node_cmap_node_cnts,
897 num_node_comm_maps,
898 rank,
899 doing_type);
900
901
902 doing_type = "FACES";
903 calc_global_ids(face_vector,
904 comm_node_ids,
905 node_comm_proc_ids,
906 node_cmap_node_cnts,
907 num_node_comm_maps,
908 rank,
909 doing_type);
910
911 // Build list of owned global edge ids
912 long long * globalEdgeIds = new long long[numEdges];
913 bool * edgeIsOwned = new bool[numEdges];
914 int numOwnedEdges=0;
915 for (int i=0; i<numEdges; i++) {
916 edgeIsOwned[i] = edge_vector[i]->owned;
917 globalEdgeIds[i] = edge_vector[i]->global_id;
918 if (edgeIsOwned[i]){
919 numOwnedEdges++;
920 }
921 }
922 Teuchos::Array<GO> ownedEdgeIds(numOwnedEdges);
923 int nedge=0;
924 for (int i=0; i<numEdges; i++) {
925 if (edgeIsOwned[i]){
926 ownedEdgeIds[nedge]=(GO)globalEdgeIds[i];
927 nedge++;
928 }
929 }
930
931 // Build list of owned global face ids
932 long long * globalFaceIds = new long long[numFaces];
933 bool * faceIsOwned = new bool[numFaces];
934 int numOwnedFaces=0;
935 for (int i=0; i<numFaces; i++) {
936 faceIsOwned[i] = face_vector[i]->owned;
937 globalFaceIds[i] = face_vector[i]->global_id;
938 if (faceIsOwned[i]){
939 numOwnedFaces++;
940 }
941 }
942 int * ownedFaceIds = new int[numOwnedFaces];
943 int nface=0;
944 for (int i=0; i<numFaces; i++) {
945 if (faceIsOwned[i]){
946 ownedFaceIds[nface]=(int)globalFaceIds[i];
947 nface++;
948 }
949 }
950
951 // Calculate number of global edges and faces
952 int numEdgesGlobal;
953 int numFacesGlobal;
954 TC_sumAll(comm,numOwnedEdges,numEdgesGlobal);
955 TC_sumAll(comm,numOwnedFaces,numFacesGlobal);
956
957
958 // Print mesh size information
959 if (MyPID == 0) {
960 std::cout << " Number of Elements: " << numElemsGlobal << " \n";
961 std::cout << " Number of Nodes: " << numNodesGlobal << " \n";
962 std::cout << " Number of Edges: " << numEdgesGlobal << " \n";
963 std::cout << " Number of Faces: " << numFacesGlobal << " \n\n";
964 }
965
966
967
968 // Container indicating whether a face is on the boundary (1-yes 0-no)
969 FieldContainer<int> edgeOnBoundary(numEdges);
970 FieldContainer<int> faceOnBoundary(numFaces);
971
972 // Get boundary (side set) information
973 long long * sideSetIds = new long long [numSideSets];
974 long long numSidesInSet;
975 long long numDFinSet;
976 im_ex_get_side_set_ids_l(id,sideSetIds);
977 for (int i=0; i<numSideSets; i++) {
978 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
979 if (numSidesInSet > 0){
980 long long * sideSetElemList = new long long [numSidesInSet];
981 long long * sideSetSideList = new long long [numSidesInSet];
982 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
983 for (int j=0; j<numSidesInSet; j++) {
984 int iface = sideSetSideList[j]-1;
985 faceOnBoundary(elemToFace(sideSetElemList[j]-1,iface))=1;
986 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),0))=1;
987 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),1))=1;
988 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),2))=1;
989 edgeOnBoundary(faceToEdge(elemToFace(sideSetElemList[j]-1,iface),3))=1;
990 }
991 delete [] sideSetElemList;
992 delete [] sideSetSideList;
993 }
994 }
995
996 delete [] sideSetIds;
997
998
999 // Container indicating whether a node is on the boundary (1-yes 0-no)
1000 FieldContainer<int> nodeOnBoundary(numNodes);
1001 int numEdgeOnBndy=0;
1002 for (int i=0; i<numEdges; i++) {
1003 if (edgeOnBoundary(i)){
1004 nodeOnBoundary(edgeToNode(i,0))=1;
1005 nodeOnBoundary(edgeToNode(i,1))=1;
1006 numEdgeOnBndy++;
1007 }
1008 }
1009
1010 // Define global owned maps
1011 Tpetra::global_size_t GST_INVALID=Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid();
1012 RCP<const Tpetra_Map> globalMapG = rcp(new Tpetra_Map(GST_INVALID,ownedGIDs,0,comm));
1013 RCP<const Tpetra_Map> globalMapC = rcp(new Tpetra_Map(GST_INVALID,ownedEdgeIds,0,comm));
1014
1015
1016 // Define overlapping maps
1017 Teuchos::Array<GO> overlappedNodes(numNodes);
1018 {
1019 int inode = 0;
1020 for (int i=0; i<numNodes; i++) {
1021 if(nodeIsOwned[i]) {
1022 overlappedNodes[inode]=(GO)globalNodeIds[i];
1023 inode++;
1024 }
1025 }
1026 for (int i=0; i<numNodes; i++) {
1027 if(!nodeIsOwned[i]) {
1028 overlappedNodes[inode]=(GO)globalNodeIds[i];
1029 inode++;
1030 }
1031 }
1032 }
1033 RCP<const Tpetra_Map> overlapMapG = rcp(new Tpetra_Map(GST_INVALID,overlappedNodes,0,comm));
1034 Teuchos::Array<GO> overlappedEdges(numEdges);
1035 {
1036 int iedge = 0;
1037 for (int i=0; i<numEdges; i++) {
1038 if(edgeIsOwned[i]) {
1039 overlappedEdges[iedge]=(GO)globalEdgeIds[i];
1040 iedge++;
1041 }
1042 }
1043 for (int i=0; i<numEdges; i++) {
1044 if(!edgeIsOwned[i]) {
1045 overlappedEdges[iedge]=(GO)globalEdgeIds[i];
1046 iedge++;
1047 }
1048 }
1049 }
1050 RCP<const Tpetra_Map> overlapMapC = rcp(new Tpetra_Map(GST_INVALID,overlappedEdges,0,comm));
1051
1052
1053 if (jiggle) {
1054 /***********************************************************************************/
1055 /* This block of code will create a randomly perturbed mesh by jiggling the node */
1056 /* coordinates away from their initial location. */
1057 /***********************************************************************************/
1058
1059 if(MyPID==0) {std::cout << "Jiggling the mesh" << std::endl << std::endl;}
1060
1061
1062 // get random numbers between -1.0 and 1.0 wrt to 1-to-1 map
1063 Tpetra_MultiVector displacementTemp(globalMapG,3);
1064 displacementTemp.randomize();
1065
1066 // import that to overlapping map
1067 Tpetra_MultiVector displacement(overlapMapG,3);
1068 Tpetra_Export MyImporter(overlapMapG,globalMapG);
1069 displacement.doImport(displacementTemp,MyImporter,Tpetra::INSERT);
1070
1071 // Side length assuming an initially regular grid
1072 double hx = nodeCoord(elemToNode(0,1),0)-nodeCoord(elemToNode(0,0),0);
1073 double hy = nodeCoord(elemToNode(0,3),1)-nodeCoord(elemToNode(0,0),1);
1074 double hz = nodeCoord(elemToNode(0,4),2)-nodeCoord(elemToNode(0,0),2);
1075
1076 const double fac = 0.05;
1077
1078 // Loop over nodes
1079 for (int inode = 0; inode < numNodes; inode++){
1080 if (!nodeOnBoundary(inode)) {
1081 double rx = displacement.getData(0)[inode];
1082 double ry = displacement.getData(1)[inode];
1083 double rz = displacement.getData(2)[inode];
1084
1085 nodeCoord(inode,0) = nodeCoord(inode,0) + fac * hx * rx;
1086 nodeCoord(inode,1) = nodeCoord(inode,1) + fac * hy * ry;
1087 nodeCoord(inode,2) = nodeCoord(inode,2) + fac * hz * rz;
1088 nodeCoordx[inode] = nodeCoord(inode,0);
1089 nodeCoordy[inode] = nodeCoord(inode,1);
1090 nodeCoordz[inode] = nodeCoord(inode,2);
1091 }
1092 }
1093 }
1094
1095 // Statistics: Phase 1
1096 MLStatistics.Phase1(elemToNode,elemToEdge,edgeToNode,nodeCoord,sigmaVal);
1097
1098
1099 /**********************************************************************************/
1100 /********************************* GET CUBATURE ***********************************/
1101 /**********************************************************************************/
1102
1103 // Get numerical integration points and weights for cell
1104 DefaultCubatureFactory<double> cubFactory;
1105 int cubDegree = 2;
1106 RCP<Cubature<double> > hexCub = cubFactory.create(cellType, cubDegree);
1107
1108 int cubDim = hexCub->getDimension();
1109 int numCubPoints = hexCub->getNumPoints();
1110
1111 FieldContainer<double> cubPoints(numCubPoints, cubDim);
1112 FieldContainer<double> cubWeights(numCubPoints);
1113
1114 hexCub->getCubature(cubPoints, cubWeights);
1115
1116 /**********************************************************************************/
1117 /* Get numerical integration points and weights for hexahedron face */
1118 /* (needed for rhs boundary term) */
1119 /**********************************************************************************/
1120
1121 // Define topology of the face parametrization domain as [-1,1]x[-1,1]
1122 shards::CellTopology paramQuadFace(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
1123
1124 // Define cubature
1125 DefaultCubatureFactory<double> cubFactoryFace;
1126 RCP<Cubature<double> > hexFaceCubature = cubFactoryFace.create(paramQuadFace, 3);
1127 int cubFaceDim = hexFaceCubature -> getDimension();
1128 int numFacePoints = hexFaceCubature -> getNumPoints();
1129
1130 // Define storage for cubature points and weights on [-1,1]x[-1,1]
1131 FieldContainer<double> paramFaceWeights(numFacePoints);
1132 FieldContainer<double> paramFacePoints(numFacePoints,cubFaceDim);
1133
1134 // Define storage for cubature points on workset faces
1135 hexFaceCubature -> getCubature(paramFacePoints, paramFaceWeights);
1136
1137 /**********************************************************************************/
1138 /* Get numerical integration points and weights for hexahedron edge */
1139 /* (needed for inhomogeneous boundary terms) */
1140 /**********************************************************************************/
1141
1142 // Define topology of the edge parametrization domain as [-1,1]
1143 shards::CellTopology paramEdge(shards::getCellTopologyData<shards::Line<2> >() );
1144
1145 // Define cubature
1146 DefaultCubatureFactory<double> cubFactoryEdge;
1147 RCP<Cubature<double> > hexEdgeCubature = cubFactoryEdge.create(paramEdge, 3);
1148 int cubEdgeDim = hexEdgeCubature -> getDimension();
1149 int numEdgePoints = hexEdgeCubature -> getNumPoints();
1150
1151 // Define storage for cubature points and weights on [-1,1]
1152 FieldContainer<double> paramEdgeWeights(numEdgePoints);
1153 FieldContainer<double> paramEdgePoints(numEdgePoints,cubEdgeDim);
1154
1155 // Define storage for cubature points on workset faces
1156 hexEdgeCubature -> getCubature(paramEdgePoints, paramEdgeWeights);
1157
1158 if(MyPID==0) {std::cout << "Getting cubature \n";}
1159
1160
1161
1162 /**********************************************************************************/
1163 /*********************************** GET BASIS ************************************/
1164 /**********************************************************************************/
1165
1166 // Define basis
1167 Basis_HCURL_HEX_I1_FEM<double, FieldContainer<double> > hexHCurlBasis;
1168 Basis_HGRAD_HEX_C1_FEM<double, FieldContainer<double> > hexHGradBasis;
1169
1170 int numFieldsC = hexHCurlBasis.getCardinality();
1171 int numFieldsG = hexHGradBasis.getCardinality();
1172
1173 // Evaluate basis at cubature points
1174 FieldContainer<double> HGVals(numFieldsG, numCubPoints);
1175 FieldContainer<double> HCVals(numFieldsC, numCubPoints, spaceDim);
1176 FieldContainer<double> HCurls(numFieldsC, numCubPoints, spaceDim);
1177 FieldContainer<double> worksetCVals(numFieldsC, numFacePoints, spaceDim);
1178
1179 hexHCurlBasis.getValues(HCVals, cubPoints, OPERATOR_VALUE);
1180 hexHCurlBasis.getValues(HCurls, cubPoints, OPERATOR_CURL);
1181 hexHGradBasis.getValues(HGVals, cubPoints, OPERATOR_VALUE);
1182
1183 if(MyPID==0) {std::cout << "Getting basis \n";}
1184
1185
1186
1187 /**********************************************************************************/
1188 /********************* BUILD Graphs FOR GLOBAL SOLUTION ***************************/
1189 /**********************************************************************************/
1190 // Define desired workset size and count how many worksets there are on this processor's mesh block
1191 int desiredWorksetSize = numElems; // change to desired workset size!
1192 //int desiredWorksetSize = 100; // change to desired workset size!
1193 int numWorksets = numElems/desiredWorksetSize;
1194
1195 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1196 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
1197
1198 RCP<Tpetra_FECrsGraph> EdgeGraph = rcp(new Tpetra_FECrsGraph(globalMapC,overlapMapC,27*numFieldsC));
1199 RCP<Tpetra_FECrsGraph> NodeGraph = rcp(new Tpetra_FECrsGraph(globalMapG,overlapMapG,9*numFieldsG));
1200
1201 Tpetra::beginAssembly(*EdgeGraph,*NodeGraph);
1202 for(int workset = 0; workset < numWorksets; workset++){
1203 // Compute cell numbers where the workset starts and ends
1204 // int worksetSize = 0;
1205 int worksetBegin = (workset + 0)*desiredWorksetSize;
1206 int worksetEnd = (workset + 1)*desiredWorksetSize;
1207
1208 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1209 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1210
1211 // Now we know the actual workset size and can allocate the array for the cell nodes
1212 // worksetSize = worksetEnd - worksetBegin;
1213
1214 // Loop over workset cells
1215 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1216
1217 /*** Assemble H(grad) mass matrix ***/
1218 // loop over nodes for matrix row
1219 for (int cellNodeRow = 0; cellNodeRow < numFieldsG; cellNodeRow++){
1220 int localNodeRow = elemToNode(cell, cellNodeRow);
1221 GO globalNodeRow = (GO) globalNodeIds[localNodeRow];
1222
1223 // loop over nodes for matrix column
1224 for (int cellNodeCol = 0; cellNodeCol < numFieldsG; cellNodeCol++){
1225 int localNodeCol = elemToNode(cell, cellNodeCol);
1226 GO globalNodeCol = (GO) globalNodeIds[localNodeCol];
1227 NodeGraph->insertGlobalIndices(globalNodeRow,1,&globalNodeCol);
1228
1229 }// *** cell node col loop ***
1230 }// *** cell node row loop ***
1231
1232
1233 /*** Assemble H(curl) mass matrix, stiffness matrix and right-hand side ***/
1234
1235 // loop over edges for matrix row
1236 for (int cellEdgeRow = 0; cellEdgeRow < numFieldsC; cellEdgeRow++){
1237 int localEdgeRow = elemToEdge(cell, cellEdgeRow);
1238 GO globalEdgeRow = (GO) globalEdgeIds[localEdgeRow];
1239
1240 // loop over edges for matrix column
1241 for (int cellEdgeCol = 0; cellEdgeCol < numFieldsC; cellEdgeCol++){
1242 int localEdgeCol = elemToEdge(cell, cellEdgeCol);
1243 GO globalEdgeCol = globalEdgeIds[localEdgeCol];
1244 EdgeGraph->insertGlobalIndices(globalEdgeRow,1,&globalEdgeCol);
1245 }// *** cell edge col loop ***
1246 }// *** cell edge row loop ***
1247
1248 }// *** workset cell loop **
1249 }// *** workset loop ***
1250 Tpetra::endAssembly(*EdgeGraph,*NodeGraph);
1251
1252 /**********************************************************************************/
1253 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
1254 /**********************************************************************************/
1255 Tpetra_FECrsMatrix SystemMatrix(EdgeGraph);
1256 Tpetra_FECrsMatrix StiffMatrixC(EdgeGraph);
1257 Tpetra_FECrsMatrix MassMatrixC (EdgeGraph);
1258 Tpetra_FECrsMatrix MassMatrixC1(EdgeGraph);// No sigma
1259 Tpetra_FECrsMatrix MassMatrixG (NodeGraph);
1260 Tpetra_FEMultiVector rhsVector (EdgeGraph->getRowMap(),EdgeGraph->getImporter(),1);
1261
1262 if(MyPID==0) {std::cout << "Build global maps \n";}
1263
1264
1265 /**********************************************************************************/
1266 /************************** OUTPUT CONNECTIVITY (FOR PLOTTING) ********************/
1267 /**********************************************************************************/
1268
1269
1270 // Build the coordinate vectors for ML solver (including owned nodes only)
1271 Tpetra_Vector Nx(globalMapG), Ny(globalMapG),Nz(globalMapG);
1272 {
1273 auto Nx_data=Nx.getDataNonConst(0);
1274 auto Ny_data=Ny.getDataNonConst(0);
1275 auto Nz_data=Nz.getDataNonConst(0);
1276 for(int i=0,nlid=0;i<numNodes;i++)
1277 if(nodeIsOwned[i]) {
1278 Nx_data[nlid]=nodeCoordx[i];
1279 Ny_data[nlid]=nodeCoordy[i];
1280 Nz_data[nlid]=nodeCoordz[i];
1281 nlid++;
1282 }
1283 }
1284
1285 RCP<const Tpetra_Map> globalMapElem = rcp(new Tpetra_Map(numElemsGlobal, numElems, 0, comm));
1286
1287 // Put coordinates in multivector for output
1288 Tpetra_MultiVector nCoord(globalMapG,3);
1289 {
1290 auto Nx_data=nCoord.getDataNonConst(0);
1291 auto Ny_data=nCoord.getDataNonConst(1);
1292 auto Nz_data=nCoord.getDataNonConst(2);
1293 int ownedNode = 0;
1294 for (int inode=0; inode<numNodes; inode++) {
1295 if (nodeIsOwned[inode]) {
1296 Nx_data[ownedNode]=nodeCoord(inode,0);
1297 Ny_data[ownedNode]=nodeCoord(inode,1);
1298 Nz_data[ownedNode]=nodeCoord(inode,2);
1299 ownedNode++;
1300 }
1301 }
1302 }
1303
1304
1305
1306 if (dump){
1307 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("coords.dat",nCoord);
1308
1309 // Put element to node mapping in multivector for output
1310 Tpetra_MultiVector elem2node(globalMapElem, numNodesPerElem);
1311 for (int inode=0; inode<numNodesPerElem; inode++) {
1312 auto data = elem2node.getDataNonConst(inode);
1313 for (int ielem=0; ielem<numElems; ielem++) {
1314 data[ielem]=globalNodeIds[elemToNode(ielem,inode)];
1315 }
1316 }
1317 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("elem2node.dat",elem2node);
1318
1319 // Put element to edge mapping in multivector for output
1320 Tpetra_MultiVector elem2edge(globalMapElem, numEdgesPerElem);
1321 for (int iedge=0; iedge<numEdgesPerElem; iedge++) {
1322 auto data = elem2edge.getDataNonConst(iedge);
1323 for (int ielem=0; ielem<numElems; ielem++) {
1324 data[ielem]=globalEdgeIds[elemToEdge(ielem,iedge)];
1325 }
1326 }
1327 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("elem2edge.dat",elem2edge);
1328
1329 // Put edge to node mapping in multivector for output
1330 Tpetra_MultiVector edge2node(globalMapC, numNodesPerEdge);
1331 for (int inode=0; inode<numNodesPerEdge; inode++) {
1332 int ownedEdge = 0;
1333 auto data = edge2node.getDataNonConst(inode);
1334 for (int iedge=0; iedge<numEdges; iedge++) {
1335 if (edgeIsOwned[iedge]) {
1336 data[ownedEdge]=globalNodeIds[edgeToNode(iedge,inode)];
1337 ownedEdge++;
1338 }
1339 }
1340 }
1341 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("edge2node.dat",edge2node);
1342 }
1343
1344 // Define multi-vector for cell edge sign (fill during cell loop)
1345 Tpetra_MultiVector edgeSign(globalMapElem, numEdgesPerElem);
1346
1347
1348 /**********************************************************************************/
1349 /*************************BUILD INCIDENCE MATRIX***********************************/
1350 /**********************************************************************************/
1351
1352 // Edge to node incidence matrix
1353 Tpetra_CrsMatrix DGrad(globalMapC, overlapMapG, 2);
1354
1355 // Estimate the global CFL based on minimum edge length and assumed dt=1"
1356
1357 // Grab edge coordinates (for dumping to disk)
1358 Tpetra_Vector EDGE_X(globalMapC);
1359 Tpetra_Vector EDGE_Y(globalMapC);
1360 Tpetra_Vector EDGE_Z(globalMapC);
1361 {
1362 auto ex_data = EDGE_X.getDataNonConst(0);
1363 auto ey_data = EDGE_Y.getDataNonConst(0);
1364 auto ez_data = EDGE_Z.getDataNonConst(0);
1365 double vals[2];
1366 vals[0]=-1.0; vals[1]=1.0;
1367 for (int j=0, elid=0; j<numEdges; j++){
1368 if (edgeIsOwned[j]){
1369 GO rowNum = (GO) globalEdgeIds[j];
1370 GO colNum[2];
1371 colNum[0] = (GO) globalNodeIds[edgeToNode(j,0)];
1372 colNum[1] = (GO) globalNodeIds[edgeToNode(j,1)];
1373 DGrad.insertGlobalValues(rowNum, 2, vals, colNum);
1374 ex_data[elid] = (nodeCoordx[edgeToNode(j,0)] + nodeCoordx[edgeToNode(j,1)])/2.0;
1375 ey_data[elid] = (nodeCoordy[edgeToNode(j,0)] + nodeCoordy[edgeToNode(j,1)])/2.0;
1376 ez_data[elid] = (nodeCoordz[edgeToNode(j,0)] + nodeCoordz[edgeToNode(j,1)])/2.0;
1377 elid++;
1378 }
1379 }
1380 }
1381
1382 DGrad.fillComplete(globalMapG, globalMapC);
1383
1384 if(MyPID==0) {std::cout << "Building incidence matrix \n";}
1385
1386
1387 // Local CFL Calculations
1388 double DOUBLE_MAX = std::numeric_limits<double>::max();
1389 double l_max_sigma=0.0, l_max_mu = 0.0, l_max_cfl = 0.0, l_max_dx = 0.0, l_max_osm=0.0;
1390 double l_min_sigma=DOUBLE_MAX, l_min_mu= DOUBLE_MAX, l_min_cfl = DOUBLE_MAX, l_min_dx = DOUBLE_MAX, l_min_osm=DOUBLE_MAX;
1391
1392 for(long long b = 0, idx=0; b < numElemBlk; b++){
1393 for(long long el = 0; el < elements[b]; el++){
1394 l_max_sigma = std::max(l_max_sigma,sigmaVal(idx));
1395 l_min_sigma = std::min(l_min_sigma,sigmaVal(idx));
1396 l_max_mu = std::max(l_max_mu,muVal(idx));
1397 l_min_mu = std::min(l_min_mu,muVal(idx));
1398 l_max_osm = std::max(l_max_osm,1/(sigmaVal(idx)*muVal(idx)));
1399 l_min_osm = std::min(l_min_osm,1/(sigmaVal(idx)*muVal(idx)));
1400
1401 // We'll chose "dx" as the max/min edge length over the cell
1402 double my_edge_min = DOUBLE_MAX, my_edge_max=0.0;
1403 for(int j=0; j<numEdgesPerElem; j++) {
1404 int edge = elemToEdge(idx,j);
1405 double my_dx = distance(nodeCoord,edgeToNode(edge,0),edgeToNode(edge,1));
1406 my_edge_max = std::max(my_edge_max,my_dx);
1407 my_edge_min = std::min(my_edge_min,my_dx);
1408 }
1409
1410 l_max_dx = std::max(l_max_dx,my_edge_max);
1411 l_min_dx = std::min(l_min_dx,my_edge_min);
1412
1413 // Note: The max/min's switch here because they're in the denominator
1414 double my_max_cfl = 1.0 / (sigmaVal(idx) * muVal(idx) * l_min_dx * l_min_dx);
1415 double my_min_cfl = 1.0 / (sigmaVal(idx) * muVal(idx) * l_max_dx * l_max_dx);
1416 l_max_cfl = std::max(l_max_cfl,my_max_cfl);
1417 l_min_cfl = std::min(l_min_cfl,my_min_cfl);
1418
1419 idx++;
1420 }
1421 }
1422
1423 // CFL Range Calculations (assuming a timestep dt=1)
1424 double g_max_dx, g_min_dx, g_max_mu, g_min_mu, g_max_sigma, g_min_sigma, g_max_cfl, g_min_cfl, g_max_osm, g_min_osm;
1425 TC_maxAll(comm,l_max_dx,g_max_dx); TC_minAll(comm,l_min_dx,g_min_dx);
1426 TC_maxAll(comm,l_max_sigma,g_max_sigma); TC_minAll(comm,l_min_sigma,g_min_sigma);
1427 TC_maxAll(comm,l_max_mu,g_max_mu); TC_minAll(comm,l_min_mu,g_min_mu);
1428 TC_maxAll(comm,l_max_cfl,g_max_cfl); TC_minAll(comm,l_min_cfl,g_min_cfl);
1429 TC_maxAll(comm,l_max_osm,g_max_osm); TC_minAll(comm,l_min_osm,g_min_osm);
1430
1431 if(MyPID==0) {
1432 std::cout<<"*** Parameter Ranges ***"<<std::endl;
1433 std::cout<<"Edge dx Range : "<<g_min_dx << " to "<<g_max_dx<<std::endl;
1434 std::cout<<"Sigma Range : "<<g_min_sigma << " to "<<g_max_sigma<<std::endl;
1435 std::cout<<"Mu Range : "<<g_min_mu << " to "<<g_max_mu<<std::endl;
1436 std::cout<<"1/(Sigma Mu) Range : "<<g_min_osm << " to "<<g_max_osm<<std::endl;
1437 std::cout<<"Diffusive CFL Range: "<<g_min_cfl<< " to "<<g_max_cfl<<std::endl;
1438
1439 }
1440
1441
1442 /**********************************************************************************/
1443 /******************** INHOMOGENEOUS BOUNDARY CONDITIONS ***************************/
1444 /**********************************************************************************/
1445
1446 FieldContainer<double> bndyEdgeVal(numEdgeOnBndy);
1447 FieldContainer<int> bndyEdgeToEdge(numEdges);
1448 FieldContainer<bool> bndyEdgeDone(numEdges);
1449 FieldContainer<double> refEdgePoints(numEdgePoints,spaceDim);
1450 FieldContainer<double> bndyEdgePoints(1,numEdgePoints,spaceDim);
1451 FieldContainer<double> bndyEdgeJacobians(1,numEdgePoints,spaceDim,spaceDim);
1452 FieldContainer<double> edgeTan(1,numEdgePoints,spaceDim);
1453 FieldContainer<double> uDotTangent(numEdgePoints);
1454 FieldContainer<double> uEdge(numEdgePoints,spaceDim);
1455 FieldContainer<double> nodes(1, numNodesPerElem, spaceDim);
1456
1457 int ibedge=0;
1458 // Evaluate tangent at edge quadrature points
1459 for (int ielem=0; ielem<numElems; ielem++) {
1460 for (int inode=0; inode<numNodesPerElem; inode++) {
1461 nodes(0,inode,0) = nodeCoord(elemToNode(ielem,inode),0);
1462 nodes(0,inode,1) = nodeCoord(elemToNode(ielem,inode),1);
1463 nodes(0,inode,2) = nodeCoord(elemToNode(ielem,inode),2);
1464 }
1465 for (int iedge=0; iedge<numEdgesPerElem; iedge++){
1466 if(edgeOnBoundary(elemToEdge(ielem,iedge)) && !bndyEdgeDone(elemToEdge(ielem,iedge))){
1467
1468 // map evaluation points from reference edge to reference cell
1469 IntrepidCTools::mapToReferenceSubcell(refEdgePoints,
1470 paramEdgePoints,
1471 1, iedge, cellType);
1472
1473 // calculate Jacobian
1474 IntrepidCTools::setJacobian(bndyEdgeJacobians, refEdgePoints,
1475 nodes, cellType);
1476
1477 // map evaluation points from reference cell to physical cell
1478 IntrepidCTools::mapToPhysicalFrame(bndyEdgePoints,
1479 refEdgePoints,
1480 nodes, cellType);
1481
1482 // Compute edge tangents
1483 IntrepidCTools::getPhysicalEdgeTangents(edgeTan,
1484 bndyEdgeJacobians,
1485 iedge, cellType);
1486
1487 // evaluate exact solution at edge center and dot with normal
1488 for(int nPt = 0; nPt < numEdgePoints; nPt++){
1489
1490 double x = bndyEdgePoints(0, nPt, 0);
1491 double y = bndyEdgePoints(0, nPt, 1);
1492 double z = bndyEdgePoints(0, nPt, 2);
1493
1494 evalu(uEdge(nPt,0), uEdge(nPt,1), uEdge(nPt,2), x, y, z);
1495 uDotTangent(nPt)=(uEdge(nPt,0)*edgeTan(0,nPt,0)+uEdge(nPt,1)*edgeTan(0,nPt,1)+uEdge(nPt,2)*edgeTan(0,nPt,2));
1496 }
1497
1498 // integrate
1499 for(int nPt = 0; nPt < numEdgePoints; nPt++){
1500 bndyEdgeVal(ibedge)=bndyEdgeVal(ibedge)+uDotTangent(nPt)*paramEdgeWeights(nPt);
1501 }
1502
1503 bndyEdgeToEdge(elemToEdge(ielem,iedge))=ibedge;
1504 ibedge++;
1505 bndyEdgeDone(elemToEdge(ielem,iedge))=1;
1506 }
1507 }
1508 }
1509
1510 // Count of boundary edges
1511 int numBCEdges=0;
1512 for (int i=0; i<numEdges; i++){
1513 if (edgeOnBoundary(i) && edgeIsOwned[i]){
1514 numBCEdges++;
1515 }
1516 }
1517
1518 // Vector for use in applying BCs
1519 Tpetra_Vector v(globalMapC);
1520 v.putScalar(0.0);
1521
1522 // Set v to boundary values on Dirichlet edges
1523 Teuchos::Array<LO> BCEdges(numBCEdges);
1524 {
1525 auto v_data = v.getDataNonConst(0);
1526 int indbc=0;
1527 int iOwned=0;
1528 for (int i=0; i<numEdges; i++){
1529 if (edgeIsOwned[i]){
1530 if (edgeOnBoundary(i)){
1531 BCEdges[indbc]=iOwned;
1532 indbc++;
1533 v_data[iOwned]=bndyEdgeVal(bndyEdgeToEdge(i));
1534 }
1535 iOwned++;
1536 }
1537 }
1538 }
1539
1540 if(numProcs==1 && dump) {
1541 FILE * f=fopen("boundary_edge_list.dat","w");
1542 for(LO i=0; i<(LO)BCEdges.size(); i++)
1543 fprintf(f,"%d ",BCEdges[i]);
1544 fclose(f);
1545 }
1546
1547
1548
1549 if(MyPID==0) {std::cout << "Boundary Condition Setup \n";}
1550
1551
1552 /**********************************************************************************/
1553 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
1554 /**********************************************************************************/
1555
1556 if (MyPID == 0) {
1557 std::cout << "Building discretization matrix and right hand side... \n\n";
1558 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
1559 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
1560 }
1561
1562 for(int workset = 0; workset < numWorksets; workset++){
1563
1564 // Compute cell numbers where the workset starts and ends
1565 int worksetSize = 0;
1566 int worksetBegin = (workset + 0)*desiredWorksetSize;
1567 int worksetEnd = (workset + 1)*desiredWorksetSize;
1568
1569 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1570 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1571
1572 // Now we know the actual workset size and can allocate the array for the cell nodes
1573 worksetSize = worksetEnd - worksetBegin;
1574 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
1575 FieldContainer<double> worksetEdgeSigns(worksetSize, numEdgesPerElem);
1576
1577 // Copy coordinates into cell workset
1578 int cellCounter = 0;
1579 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1580
1581 // Physical cell coordinates
1582 for (int inode=0; inode<numNodesPerElem; inode++) {
1583 cellWorkset(cellCounter,inode,0) = nodeCoord(elemToNode(cell,inode),0);
1584 cellWorkset(cellCounter,inode,1) = nodeCoord(elemToNode(cell,inode),1);
1585 cellWorkset(cellCounter,inode,2) = nodeCoord(elemToNode(cell,inode),2);
1586 }
1587
1588 // Edge signs
1589 for (int iedge=0; iedge<numEdgesPerElem; iedge++) {
1590 if (elemToNode(cell,refEdgeToNode(iedge,0))==edgeToNode(elemToEdge(cell,iedge),0) &&
1591 elemToNode(cell,refEdgeToNode(iedge,1))==edgeToNode(elemToEdge(cell,iedge),1))
1592 worksetEdgeSigns(cellCounter,iedge) = 1.0;
1593 else
1594 worksetEdgeSigns(cellCounter,iedge) = -1.0;
1595 }
1596
1597 // modify signs for edges that are owned by another processor
1598 // (Note: this is particular to the numbering of edges used in Pamgen!!)
1599 if (!faceIsOwned[elemToFace(cell,0)]) {
1600 worksetEdgeSigns(cellCounter,0)=-1.0*worksetEdgeSigns(cellCounter,0);
1601 worksetEdgeSigns(cellCounter,4)=-1.0*worksetEdgeSigns(cellCounter,4);
1602 }
1603 if (!faceIsOwned[elemToFace(cell,1)]) {
1604 worksetEdgeSigns(cellCounter,1)=-1.0*worksetEdgeSigns(cellCounter,1);
1605 worksetEdgeSigns(cellCounter,5)=-1.0*worksetEdgeSigns(cellCounter,5);
1606 }
1607 if (!faceIsOwned[elemToFace(cell,2)]) {
1608 worksetEdgeSigns(cellCounter,2)=-1.0*worksetEdgeSigns(cellCounter,2);
1609 worksetEdgeSigns(cellCounter,6)=-1.0*worksetEdgeSigns(cellCounter,6);
1610 }
1611 if (!faceIsOwned[elemToFace(cell,3)]) {
1612 worksetEdgeSigns(cellCounter,3)=-1.0*worksetEdgeSigns(cellCounter,3);
1613 worksetEdgeSigns(cellCounter,7)=-1.0*worksetEdgeSigns(cellCounter,7);
1614 }
1615
1616 if (dump){
1617 for (int iedge=0; iedge<numEdgesPerElem; iedge++) {
1618 edgeSign.getDataNonConst(iedge)[cell] = worksetEdgeSigns(cellCounter,iedge);
1619 }
1620 }
1621
1622 cellCounter++;
1623
1624 } // end loop over workset cells
1625
1626 /**********************************************************************************/
1627 /* Allocate arrays */
1628 /**********************************************************************************/
1629
1630 // Containers for Jacobian
1631 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
1632 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
1633 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
1634
1635 // Container for cubature points in physical space
1636 FieldContainer<double> worksetCubPoints (worksetSize,numCubPoints, cubDim);
1637
1638 // Containers for element HGRAD mass matrix
1639 FieldContainer<double> massMatrixHGrad (worksetSize, numFieldsG, numFieldsG);
1640 FieldContainer<double> weightedMeasure (worksetSize, numCubPoints);
1641 FieldContainer<double> weightedMeasureMuInv (worksetSize, numCubPoints);
1642 FieldContainer<double> HGValsTransformed (worksetSize, numFieldsG, numCubPoints);
1643 FieldContainer<double> HGValsTransformedWeighted (worksetSize, numFieldsG, numCubPoints);
1644
1645 // Containers for element HCURL mass matrix
1646 FieldContainer<double> massMatrixHCurl (worksetSize, numFieldsC, numFieldsC);
1647 FieldContainer<double> massMatrixHCurlNoSigma (worksetSize, numFieldsC, numFieldsC);
1648 FieldContainer<double> weightedMeasureSigma (worksetSize, numCubPoints);
1649 FieldContainer<double> HCValsTransformed (worksetSize, numFieldsC, numCubPoints, spaceDim);
1650 FieldContainer<double> HCValsTransformedWeighted (worksetSize, numFieldsC, numCubPoints, spaceDim);
1651 FieldContainer<double> HCValsTransformedWeightedNoSigma (worksetSize, numFieldsC, numCubPoints, spaceDim);
1652
1653 // Containers for element HCURL stiffness matrix
1654 FieldContainer<double> stiffMatrixHCurl (worksetSize, numFieldsC, numFieldsC);
1655 FieldContainer<double> weightedMeasureMu (worksetSize, numCubPoints);
1656 FieldContainer<double> HCurlsTransformed (worksetSize, numFieldsC, numCubPoints, spaceDim);
1657 FieldContainer<double> HCurlsTransformedWeighted (worksetSize, numFieldsC, numCubPoints, spaceDim);
1658
1659 // Containers for right hand side vectors
1660 FieldContainer<double> rhsDatag (worksetSize, numCubPoints, cubDim);
1661 FieldContainer<double> rhsDatah (worksetSize, numCubPoints, cubDim);
1662 FieldContainer<double> gC (worksetSize, numFieldsC);
1663 FieldContainer<double> hC (worksetSize, numFieldsC);
1664
1665 // Containers for right hand side boundary term
1666 FieldContainer<double> hCBoundary (1, numFieldsC);
1667 FieldContainer<double> refFacePoints (numFacePoints,spaceDim);
1668 FieldContainer<double> cellNodes (1, numNodesPerElem, spaceDim);
1669 FieldContainer<double> worksetFacePoints (1, numFacePoints, spaceDim);
1670 FieldContainer<double> faceJacobians (1, numFacePoints, spaceDim, spaceDim);
1671 FieldContainer<double> faceJacobInv (1, numFacePoints, spaceDim, spaceDim);
1672 FieldContainer<double> faceNormal (1, numFacePoints, spaceDim);
1673 FieldContainer<double> bcFaceCVals (numFieldsC, numFacePoints, spaceDim);
1674 FieldContainer<double> faceVFieldVals (1, numFacePoints, spaceDim);
1675 FieldContainer<double> bcCValsTransformed (1, numFieldsC, numFacePoints, spaceDim);
1676 FieldContainer<double> bcFieldDotNormal (1, numFieldsC, numFacePoints);
1677 FieldContainer<double> bcEdgeSigns (1, numFieldsC);
1678
1679
1680 /**********************************************************************************/
1681 /* Calculate Jacobians */
1682 /**********************************************************************************/
1683
1684 IntrepidCTools::setJacobian (worksetJacobian, cubPoints, cellWorkset, cellType);
1685 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
1686 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
1687
1688 if(MyPID==0) {std::cout << "Calculate Jacobians \n";}
1689
1690
1691
1692 /**********************************************************************************/
1693 /* Compute HGRAD Mass Matrix */
1694 /**********************************************************************************/
1695
1696 // transform to physical coordinates
1697 IntrepidFSTools::HGRADtransformVALUE<double>(HGValsTransformed, HGVals);
1698
1699 // compute weighted measure
1700 IntrepidFSTools::computeCellMeasure<double>(weightedMeasure, worksetJacobDet, cubWeights);
1701
1702 // combine mu value with weighted measure
1703 cellCounter = 0;
1704 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1705 for (int nPt = 0; nPt < numCubPoints; nPt++){
1706 weightedMeasureMuInv(cellCounter,nPt) = weightedMeasure(cellCounter,nPt) / muVal(cell);
1707 }
1708 cellCounter++;
1709 }
1710
1711 // multiply values with weighted measure
1712 IntrepidFSTools::multiplyMeasure<double>(HGValsTransformedWeighted,
1713 weightedMeasureMuInv, HGValsTransformed);
1714
1715 // integrate to compute element mass matrix
1716 IntrepidFSTools::integrate<double>(massMatrixHGrad,
1717 HGValsTransformed, HGValsTransformedWeighted, COMP_BLAS);
1718
1719 if(MyPID==0) {std::cout << "Compute HGRAD Mass Matrix \n";}
1720
1721
1722 // Statistics: Phase 2a
1723 MLStatistics.Phase2a(worksetJacobDet,cubWeights);
1724
1725 /**********************************************************************************/
1726 /* Compute HCURL Mass Matrix */
1727 /**********************************************************************************/
1728
1729 // transform to physical coordinates
1730 IntrepidFSTools::HCURLtransformVALUE<double>(HCValsTransformed, worksetJacobInv,
1731 HCVals);
1732
1733 // combine sigma value with weighted measure
1734 cellCounter = 0;
1735 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1736 for (int nPt = 0; nPt < numCubPoints; nPt++){
1737 weightedMeasureSigma(cellCounter,nPt) = weightedMeasure(cellCounter,nPt) * sigmaVal(cell);
1738 }
1739 cellCounter++;
1740 }
1741
1742 // multiply by weighted measure
1743 IntrepidFSTools::multiplyMeasure<double>(HCValsTransformedWeighted,
1744 weightedMeasureSigma, HCValsTransformed);
1745
1746 // integrate to compute element mass matrix
1747 IntrepidFSTools::integrate<double>(massMatrixHCurl,
1748 HCValsTransformed, HCValsTransformedWeighted,
1749 COMP_BLAS);
1750
1751 // apply edge signs
1752 IntrepidFSTools::applyLeftFieldSigns<double> (massMatrixHCurl, worksetEdgeSigns);
1753 IntrepidFSTools::applyRightFieldSigns<double>(massMatrixHCurl, worksetEdgeSigns);
1754
1755
1756 // Now for the no-sigma version
1757 IntrepidFSTools::multiplyMeasure<double>(HCValsTransformedWeightedNoSigma,
1758 weightedMeasure, HCValsTransformed);
1759
1760 // integrate to compute element mass matrix
1761 IntrepidFSTools::integrate<double>(massMatrixHCurlNoSigma,
1762 HCValsTransformed, HCValsTransformedWeightedNoSigma,
1763 COMP_BLAS);
1764
1765 if(MyPID==0) {std::cout << "Compute HCURL Mass Matrix \n";}
1766
1767
1768
1769 /**********************************************************************************/
1770 /* Compute HCURL Stiffness Matrix */
1771 /**********************************************************************************/
1772
1773 // transform to physical coordinates
1774 IntrepidFSTools::HCURLtransformCURL<double>(HCurlsTransformed, worksetJacobian, worksetJacobDet,
1775 HCurls);
1776
1777 // combine mu value with weighted measure
1778 cellCounter = 0;
1779 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1780 for (int nPt = 0; nPt < numCubPoints; nPt++){
1781 weightedMeasureMu(cellCounter,nPt) = weightedMeasure(cellCounter,nPt) * muVal(cell);
1782 }
1783 cellCounter++;
1784 }
1785
1786 // multiply by weighted measure
1787 IntrepidFSTools::multiplyMeasure<double>(HCurlsTransformedWeighted,
1788 weightedMeasureMuInv, HCurlsTransformed);
1789
1790 // integrate to compute element stiffness matrix
1791 IntrepidFSTools::integrate<double>(stiffMatrixHCurl,
1792 HCurlsTransformed, HCurlsTransformedWeighted,
1793 COMP_BLAS);
1794
1795 // apply edge signs
1796 IntrepidFSTools::applyLeftFieldSigns<double> (stiffMatrixHCurl, worksetEdgeSigns);
1797 IntrepidFSTools::applyRightFieldSigns<double>(stiffMatrixHCurl, worksetEdgeSigns);
1798
1799 if(MyPID==0) {std::cout << "Compute HCURL Stiffness Matrix \n";}
1800
1801
1802
1803 /**********************************************************************************/
1804 /* Build Right Hand Side */
1805 /**********************************************************************************/
1806
1807 // transform integration points to physical points
1808 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPoints, cellWorkset, cellType);
1809
1810 // evaluate right hand side functions at physical points
1811 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1812
1813 // Compute cell ordinal relative to the current workset
1814 int worksetCellOrdinal = cell - worksetBegin;
1815
1816 for (int nPt = 0; nPt < numCubPoints; nPt++){
1817 double x = worksetCubPoints(worksetCellOrdinal,nPt,0);
1818 double y = worksetCubPoints(worksetCellOrdinal,nPt,1);
1819 double z = worksetCubPoints(worksetCellOrdinal,nPt,2);
1820 double du1, du2, du3;
1821
1822 evalCurlCurlu(du1, du2, du3, x, y, z, muVal(cell));
1823 rhsDatag(worksetCellOrdinal,nPt,0) = du1;
1824 rhsDatag(worksetCellOrdinal,nPt,1) = du2;
1825 rhsDatag(worksetCellOrdinal,nPt,2) = du3;
1826
1827
1828 double u1, u2, u3;
1829 evalu(u1, u2, u3, x, y, z);
1830 rhsDatah(worksetCellOrdinal,nPt,0) = u1;
1831 rhsDatah(worksetCellOrdinal,nPt,1) = u2;
1832 rhsDatah(worksetCellOrdinal,nPt,2) = u3;
1833
1834 }
1835 }
1836
1837 // integrate (g,curl w) term
1838 // IntrepidFSTools::integrate<double>(gC, rhsDatag, HCurlsTransformedWeighted,
1839 // COMP_BLAS);
1840
1841 // integrate (h,w) term
1842 IntrepidFSTools::integrate<double>(gC, rhsDatag, HCValsTransformedWeighted, COMP_BLAS);
1843
1844 IntrepidFSTools::integrate<double>(hC, rhsDatah, HCValsTransformedWeighted, COMP_BLAS);
1845
1846
1847 // apply signs
1848 IntrepidFSTools::applyFieldSigns<double>(gC, worksetEdgeSigns);
1849 IntrepidFSTools::applyFieldSigns<double>(hC, worksetEdgeSigns);
1850
1851
1852 // evaluate RHS boundary term
1853 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1854
1855 // Compute cell ordinal relative to the current workset
1856 int worksetCellOrdinal = cell - worksetBegin;
1857
1858 // evaluate boundary term
1859 for (int iface = 0; iface < numFacesPerElem; iface++){
1860 if (faceOnBoundary(elemToFace(cell,iface))){
1861
1862 // cell nodal coordinates
1863 for (int inode =0; inode < numNodesPerElem; inode++){
1864 cellNodes(0,inode,0) = cellWorkset(worksetCellOrdinal,inode,0);
1865 cellNodes(0,inode,1) = cellWorkset(worksetCellOrdinal,inode,1);
1866 cellNodes(0,inode,2) = cellWorkset(worksetCellOrdinal,inode,2);
1867 }
1868
1869 // cell edge signs
1870 for (int iedge =0; iedge < numEdgesPerElem; iedge++){
1871 bcEdgeSigns(0,iedge) = worksetEdgeSigns(worksetCellOrdinal,iedge);
1872 }
1873
1874 // map Gauss points on quad to reference face: paramFacePoints -> refFacePoints
1875 IntrepidCTools::mapToReferenceSubcell(refFacePoints,
1876 paramFacePoints,
1877 2, iface, cellType);
1878
1879 // get basis values at points on reference cell
1880 hexHCurlBasis.getValues(bcFaceCVals, refFacePoints, OPERATOR_VALUE);
1881
1882 // compute Jacobians at Gauss pts. on reference face for all parent cells
1883 IntrepidCTools::setJacobian(faceJacobians,
1884 refFacePoints,
1885 cellNodes, cellType);
1886 IntrepidCTools::setJacobianInv(faceJacobInv, faceJacobians );
1887
1888 // transform to physical coordinates
1889 IntrepidFSTools::HCURLtransformVALUE<double>(bcCValsTransformed, faceJacobInv,
1890 bcFaceCVals);
1891
1892 // map Gauss points on quad from ref. face to face workset: refFacePoints -> worksetFacePoints
1893 IntrepidCTools::mapToPhysicalFrame(worksetFacePoints,
1894 refFacePoints,
1895 cellNodes, cellType);
1896
1897 // Compute face normals
1898 IntrepidCTools::getPhysicalFaceNormals(faceNormal,
1899 faceJacobians,
1900 iface, cellType);
1901
1902 // compute the dot product and multiply by Gauss weights
1903 for (int nF = 0; nF < numFieldsC; nF++){
1904 for(int nPt = 0; nPt < numFacePoints; nPt++){
1905 bcFieldDotNormal(0,nF,nPt)=0.0;
1906 for (int dim = 0; dim < spaceDim; dim++){
1907 bcFieldDotNormal(0,nF,nPt) += bcCValsTransformed(0,nF,nPt,dim)
1908 * faceNormal(0,nPt,dim) * paramFaceWeights(nPt);
1909 } //dim
1910 } //nPt
1911 } //nF
1912
1913 // integrate
1914 // IntrepidFSTools::integrate<double>(hCBoundary, divuFace, bcFieldDotNormal,
1915 // COMP_CPP);
1916
1917 // apply signs
1918 // IntrepidFSTools::applyFieldSigns<double>(hCBoundary, bcEdgeSigns);
1919
1920 // add into hC term
1921 // for (int nF = 0; nF < numFieldsC; nF++){
1922 // hC(worksetCellOrdinal,nF) = hC(worksetCellOrdinal,nF) - hCBoundary(0,nF);
1923 // }
1924
1925 } // if faceOnBoundary
1926
1927 } // numFaces
1928
1929 }// *** workset cell loop **
1930
1931
1932 if(MyPID==0) {std::cout << "Compute right-hand side \n";}
1933
1934
1935
1936 /**********************************************************************************/
1937 /* Assemble into Global Matrix */
1938 /**********************************************************************************/
1939 Tpetra::beginAssembly(MassMatrixG,MassMatrixC,MassMatrixC1,StiffMatrixC,SystemMatrix,rhsVector);
1940
1941 // Loop over workset cells
1942 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1943
1944 // Compute cell ordinal relative to the current workset
1945 int worksetCellOrdinal = cell - worksetBegin;
1946
1947
1948 /*** Assemble H(grad) mass matrix ***/
1949
1950 // loop over nodes for matrix row
1951 for (int cellNodeRow = 0; cellNodeRow < numFieldsG; cellNodeRow++){
1952
1953 int localNodeRow = elemToNode(cell, cellNodeRow);
1954 GO globalNodeRow = (GO) globalNodeIds[localNodeRow];
1955
1956 // loop over nodes for matrix column
1957 for (int cellNodeCol = 0; cellNodeCol < numFieldsG; cellNodeCol++){
1958
1959 int localNodeCol = elemToNode(cell, cellNodeCol);
1960 GO globalNodeCol = (GO) globalNodeIds[localNodeCol];
1961 double massGContribution = massMatrixHGrad(worksetCellOrdinal, cellNodeRow, cellNodeCol);
1962
1963 MassMatrixG.sumIntoGlobalValues(globalNodeRow, 1, &massGContribution, &globalNodeCol);
1964
1965 }// *** cell node col loop ***
1966 }// *** cell node row loop ***
1967
1968
1969 /*** Assemble H(curl) mass matrix, stiffness matrix and right-hand side ***/
1970
1971 // loop over edges for matrix row
1972 for (int cellEdgeRow = 0; cellEdgeRow < numFieldsC; cellEdgeRow++){
1973
1974 int localEdgeRow = elemToEdge(cell, cellEdgeRow);
1975 GO globalEdgeRow = (GO) globalEdgeIds[localEdgeRow];
1976 double rhsContribution = gC(worksetCellOrdinal, cellEdgeRow) + hC(worksetCellOrdinal, cellEdgeRow);
1977
1978 rhsVector.sumIntoGlobalValue(globalEdgeRow, 0, rhsContribution);
1979
1980 // loop over edges for matrix column
1981 for (int cellEdgeCol = 0; cellEdgeCol < numFieldsC; cellEdgeCol++){
1982
1983 int localEdgeCol = elemToEdge(cell, cellEdgeCol);
1984 GO globalEdgeCol = (GO) globalEdgeIds[localEdgeCol];
1985
1986 double massCContribution = massMatrixHCurl (worksetCellOrdinal, cellEdgeRow, cellEdgeCol);
1987 double stiffCContribution = stiffMatrixHCurl(worksetCellOrdinal, cellEdgeRow, cellEdgeCol);
1988
1989 double massCContribution1 = massMatrixHCurlNoSigma (worksetCellOrdinal, cellEdgeRow, cellEdgeCol);
1990
1991 double systemContribution = massCContribution*scaling + stiffCContribution;
1992
1993 MassMatrixC.sumIntoGlobalValues (globalEdgeRow, 1, &massCContribution, &globalEdgeCol);
1994 MassMatrixC1.sumIntoGlobalValues(globalEdgeRow, 1, &massCContribution1, &globalEdgeCol);
1995 StiffMatrixC.sumIntoGlobalValues(globalEdgeRow, 1, &stiffCContribution, &globalEdgeCol);
1996 SystemMatrix.sumIntoGlobalValues(globalEdgeRow, 1, &systemContribution, &globalEdgeCol);
1997
1998
1999 }// *** cell edge col loop ***
2000 }// *** cell edge row loop ***
2001
2002 }// *** workset cell loop **
2003 }// *** workset loop ***
2004
2005 if(MyPID==0) {std::cout << "Assemble Matrices \n";}
2006
2007
2008
2009 /**********************************************************************************/
2010 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
2011 /**********************************************************************************/
2012
2013 // Assemble over multiple processors, if necessary
2014 Tpetra::endAssembly(MassMatrixG,MassMatrixC,MassMatrixC1,StiffMatrixC,SystemMatrix,rhsVector);
2015
2016 MLStatistics.Phase2b(MassMatrixG.getCrsGraph(),rcp(&nCoord,false));
2017
2018 if(MyPID==0) {std::cout << "Global assembly \n";}
2019
2020 if (dump) {
2021 // Node Coordinates
2022 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("coordx.dat",Nx);
2023 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("coordy.dat",Ny);
2024 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("coordz.dat",Nz);
2025
2026 // Edge Coordinates
2027 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("ecoordx.dat",EDGE_X);
2028 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("ecoordy.dat",EDGE_Y);
2029 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("ecoordz.dat",EDGE_Z);
2030
2031 // Boundary Application
2032 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("boundary_v.dat",v);
2033
2034 // Edge signs
2035 Tpetra::MatrixMarket::Writer<Tpetra_MultiVector>::writeDenseFile("edge_signs.dat",edgeSign);
2036
2037 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("mag_k1_matrix.dat",StiffMatrixC);
2038 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("mag_ms_matrix.dat",MassMatrixC);
2039 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("mag_m1_matrix.dat",MassMatrixC1);
2040 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("mag_t_matrix.dat",DGrad);
2041 }
2042
2043
2044
2045 /**********************************************************************************/
2046 /*********************** ADJUST MATRICES AND RHS FOR BCs **************************/
2047 /**********************************************************************************/
2048
2049 // Build the inverse diagonal for MassMatrixG
2050 Tpetra_Vector DiagG(MassMatrixG.getRowMap());
2051 {
2052 DiagG.putScalar(1.0);
2053 MassMatrixG.apply(DiagG,DiagG);
2054 auto d_data = DiagG.getDataNonConst(0);
2055 for(int i=0;i<(int)d_data.size();i++) {
2056 d_data[i]=1.0/d_data[i];
2057 }
2058 }
2059
2060 Tpetra_CrsMatrix MassMatrixGinv(MassMatrixG.getRowMap(),MassMatrixG.getRowMap(),1);
2061 {
2062 auto d_data = DiagG.getData(0);
2063 for(int i=0;i<(int)MassMatrixGinv.getRowMap()->getLocalNumElements();i++) {
2064 GO GCID=MassMatrixG.getColMap()->getGlobalElement(i);
2065 GO GRID=MassMatrixG.getRowMap()->getGlobalElement(i);
2066 MassMatrixGinv.insertGlobalValues(GRID,1,&(d_data[i]),&GCID);
2067 }
2068 }
2069 MassMatrixGinv.fillComplete();
2070
2071 // Zero out entries that correspond to boundary nodes
2072 for(int i=0;i<numNodes;i++) {
2073 if (nodeOnBoundary(i)){
2074 double val=0.0;
2075 GO index = (GO) globalNodeIds[i];
2076 MassMatrixGinv.replaceGlobalValues(index,1,&val,&index);
2077 }
2078 }
2079
2080 // Apply it to v
2081 Tpetra_MultiVector rhsDir(globalMapC,1);
2082 SystemMatrix.apply(v,rhsDir);
2083
2084 // Update right-hand side
2085 rhsVector.update(-1.0,rhsDir,1.0);
2086
2087 // Adjust rhs due to Dirichlet boundary conditions
2088 {
2089 auto rhsV_data = rhsVector.getDataNonConst(0);
2090 auto rhsD_data = rhsDir.getDataNonConst(0);
2091 int indbc=0;
2092 int indOwned=0;
2093 for (int i=0; i<numEdges; i++){
2094 if (edgeIsOwned[i]){
2095 if (edgeOnBoundary(i)){
2096 indbc++;
2097 rhsV_data[indOwned]=bndyEdgeVal(bndyEdgeToEdge(i));
2098 rhsD_data[indOwned]=0.0;
2099 }
2100 indOwned++;
2101 }
2102 }
2103 }
2104
2105 if (dump) {
2106 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("edge_matrix_nobcs.mat",SystemMatrix);
2107 }
2108
2109 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
2110 // and add one to diagonal.
2111 {
2112
2113 Kokkos::View<LO*, Kokkos::HostSpace> bce(BCEdges.data(),numBCEdges);
2114 Tpetra::applyDirichletBoundaryConditionToLocalMatrixRowsAndColumns(SystemMatrix,bce);
2115 }
2116
2117 if(MyPID==0) {std::cout << "Adjust global matrix and rhs due to BCs \n";}
2118
2119
2120 if (dump) {
2121 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("mag_m0_matrix.mat",MassMatrixG);
2122 Tpetra::MatrixMarket::Writer<Tpetra_CrsMatrix>::writeSparseFile("edge_matrix.mat",SystemMatrix);
2123 }
2124
2125 /**********************************************************************************/
2126 /*********************************** SOLVE ****************************************/
2127 /**********************************************************************************/
2128
2129
2130 MLStatistics.Phase3();
2131 Teuchos::ParameterList problemStatistics = MLStatistics.GetStatistics();
2132 if(MyPID==0) {
2133 std::cout<<"*** Problem Statistics ***"<<std::endl;
2134 std::cout<<problemStatistics<<std::endl;
2135 }
2136
2137
2138 // double TotalErrorResidual=0, TotalErrorExactSol=0;
2139
2140
2141 // Parameter list for MueLu
2142 Teuchos::ParameterList MueLuList;
2143 if(inputList.isSublist("MueLu")) {
2144 MueLuList = inputList.sublist("MueLu");
2145 } else {
2146 Teuchos::ParameterList &MueList11=MueLuList.sublist("refmaxwell: 11list");
2147 Teuchos::ParameterList &MueList22=MueLuList.sublist("refmaxwell: 22list");
2148 MueLuList.set("aggregation: type","Uncoupled");
2149 // MueLuList.set("refmaxwell: mode","none");
2150 MueLuList.set("refmaxwell: mode","additive");
2151 MueLuList.set("refmaxwell: disable addon",false);;
2152 MueLuList.set("smoother: type","CHEBYSHEV");
2153
2154 Teuchos::ParameterList &MueLuSmootherList=MueLuList.sublist("smoother: params");
2155 MueLuSmootherList.set("chebyshev: degree",2);
2156 MueLuSmootherList.set("chebyshev: ratio eigenvalue",30.0);
2157
2158 MueList11.set("coarse: max size", 128);
2159 MueList11.set("smoother: type", "CHEBYSHEV");
2160 //MueList11.sublist("smoother: params").set("chebyshev: max eigenvalue",1.85123);
2161 MueList11.sublist("smoother: params").set("chebyshev: ratio eigenvalue",30.0);
2162 MueList11.sublist("smoother: params").set("chebyshev: degree",2);
2163 //MueList11.set("coarse: type","Amesos-KLU");
2164 MueList11.set("number of equations",3);
2165
2166 MueList22.set("coarse: max size", 128);
2167 MueList22.set("smoother: type", "CHEBYSHEV");
2168 //MueList22.sublist("smoother: params").set("chebyshev: max eigenvalue",1.431);
2169 MueList22.sublist("smoother: params").set("chebyshev: ratio eigenvalue",30.0);
2170 MueList22.sublist("smoother: params").set("chebyshev: degree",2);
2171 //MueList22.set("coarse: type","Amesos-KLU");
2172 }
2173
2174
2175 #if defined(HAVE_TRILINOSCOUPLINGS_AVATAR)
2176 Teuchos::ParameterList &MueList11=MueLuList.sublist("refmaxwell: 11list");
2177 Teuchos::ParameterList &MueList22=MueLuList.sublist("refmaxwell: 22list");
2178
2179 std::vector<std::string> AvatarSublists{"Avatar-MueLu-Fine","Avatar-MueLu-11","Avatar-MueLu-22"};
2180 std::vector<Teuchos::ParameterList *> MueLuSublists{&MueLuList,&MueList11,&MueList22};
2181 for (int i=0; i<(int)AvatarSublists.size(); i++) {
2182 if (inputList.isSublist(AvatarSublists[i])) {
2183 Teuchos::ParameterList problemFeatures = problemStatistics;
2184 Teuchos::ParameterList avatarParams = inputList.sublist(AvatarSublists[i]);
2185 std::cout<<"*** Avatar["<<AvatarSublists[i]<<"] Parameters ***\n"<<avatarParams<<std::endl;
2186
2187 MueLu::AvatarInterface avatar(comm,avatarParams);
2188 std::cout<<"*** Avatar Setup ***"<<std::endl;
2189 avatar.Setup();
2190 avatar.SetMueLuParameters(problemFeatures,*MueLuSublists[i], true);
2191 }
2192 }
2193 #endif
2194
2195 Tpetra_MultiVector xh(EdgeGraph->getRowMap(),1);
2196
2197 char probType[12] = "maxwell";
2198 bool converged;
2199 int numItersPerformed;
2200 int maxNumIters = 200;
2201 int num_steps = 1;
2202 double tol = 1e-10;
2203
2204 RCP<Tpetra_CrsMatrix> SystemMatrix_r = rcp(&SystemMatrix,false);
2205 RCP<Tpetra_CrsMatrix> DGrad_r = rcp(&DGrad,false);
2206 RCP<Tpetra_CrsMatrix> MassMatrixGinv_r = rcp(&MassMatrixGinv,false);
2207 RCP<Tpetra_CrsMatrix> MassMatrixC_r = rcp(&MassMatrixC,false);
2208 RCP<Tpetra_CrsMatrix> MassMatrixC1_r = rcp(&MassMatrixC1,false);
2209 RCP<Tpetra_MultiVector> nCoord_r = rcp(&nCoord,false);
2210 RCP<Tpetra_MultiVector> xh_r = rcp(&xh,false);
2211 RCP<Tpetra_MultiVector> rhsVector_r = rcp(&rhsVector,false);
2212
2213 if (solverName == "MueLu") {
2214 // MueLu RefMaxwell
2215 if(MyPID==0) {std::cout << "\n\nMueLu solve \n";}
2216 RCP<Xpetra_Operator> preconditioner =
2217 BuildPreconditioner_MueLu(probType,MueLuList,SystemMatrix_r,DGrad_r,MassMatrixGinv_r,MassMatrixC_r,MassMatrixC1_r,nCoord_r);
2218
2219 RCP<Xpetra_Operator> A_x = toXpetra(SystemMatrix_r);
2220 RCP<Xpetra_MultiVector> xh_x = toXpetra(xh_r);
2221 RCP<Xpetra_MultiVector> rhsVector_x = toXpetra(rhsVector_r);
2222
2223 using BMV = Xpetra_MultiVector;
2224 using BOP = typename Belos::OperatorT<BMV>;
2225 RCP<BOP> belosOp = rcp(new Belos::XpetraOp<SC,LO,GO,NO>(A_x));
2226 RCP<BOP> precOp = rcp(new Belos::XpetraOp<SC,LO,GO,NO>(preconditioner));
2227 RCP<BOP> dummy;
2228
2229 solverName="CG";
2230 TrilinosCouplings::IntrepidPoissonExample::
2231 solveWithBelos<SC,BMV,BOP>(converged,numItersPerformed,solverName,tol,maxNumIters,num_steps,
2232 xh_x,belosOp,rhsVector_x,dummy,precOp);
2233
2234 }
2235
2236 #ifdef HAVE_TRILINOSCOUPLINGS_STRATIMIKOS
2237 if (solverName == "Stratimikos") {
2238 if(MyPID==0) {std::cout << "\n\nStratimikos solve \n" << xmlStratimikos << std::endl;}
2239 Teuchos::ParameterList SList;
2240 Teuchos::updateParametersFromXmlFile(xmlStratimikos,Teuchos::ptr (&SList));
2241 TestPreconditioner_Stratimikos(probType,SList,SystemMatrix_r,
2242 DGrad_r,MassMatrixGinv_r,MassMatrixC_r,MassMatrixC1_r,
2243 nCoord_r,
2244 xh_r, rhsVector_r);
2245 }
2246 #endif
2247
2248
2249
2250 /**********************************************************************************/
2251 /**************************** CALCULATE ERROR *************************************/
2252 /**********************************************************************************/
2253
2254
2255
2256 double L2err = 0.0;
2257 double HCurlerr = 0.0;
2258 double Linferr = 0.0;
2259 double L2errTot = 0.0;
2260 double HCurlerrTot = 0.0;
2261 double LinferrTot = 0.0;
2262
2263 // Import solution onto current processor
2264 RCP<const Tpetra_Map> solnMap = rcp(new Tpetra_Map(numEdgesGlobal, numEdgesGlobal, 0, comm));
2265 Tpetra_Import solnImporter(solnMap, globalMapC);
2266 Tpetra_Vector uCoeff(solnMap);
2267 uCoeff.doImport(xh, solnImporter, Tpetra::INSERT);
2268
2269 int numCells = 1;
2270 FieldContainer<double> hexEdgeSigns(numCells, numFieldsC);
2271 FieldContainer<double> hexNodes(numCells, numFieldsG, spaceDim);
2272
2273 // Get cubature points and weights for error calc (may be different from previous)
2274 DefaultCubatureFactory<double> cubFactoryErr;
2275 int cubDegErr = 3;
2276 RCP<Cubature<double> > hexCubErr = cubFactoryErr.create(cellType, cubDegErr);
2277 int cubDimErr = hexCubErr->getDimension();
2278 int numCubPointsErr = hexCubErr->getNumPoints();
2279 FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
2280 FieldContainer<double> cubWeightsErr(numCubPointsErr);
2281 hexCubErr->getCubature(cubPointsErr, cubWeightsErr);
2282 FieldContainer<double> physCubPointsE(numCells,numCubPointsErr, cubDimErr);
2283
2284 // Containers for Jacobian
2285 FieldContainer<double> hexJacobianE(numCells, numCubPointsErr, spaceDim, spaceDim);
2286 FieldContainer<double> hexJacobInvE(numCells, numCubPointsErr, spaceDim, spaceDim);
2287 FieldContainer<double> hexJacobDetE(numCells, numCubPointsErr);
2288 FieldContainer<double> weightedMeasureE(numCells, numCubPointsErr);
2289
2290 // Evaluate basis values and curls at cubature points
2291 FieldContainer<double> uhCVals(numFieldsC, numCubPointsErr, spaceDim);
2292 FieldContainer<double> uhCValsTrans(numCells,numFieldsC, numCubPointsErr, spaceDim);
2293 FieldContainer<double> uhCurls(numFieldsC, numCubPointsErr, spaceDim);
2294 FieldContainer<double> uhCurlsTrans(numCells, numFieldsC, numCubPointsErr, spaceDim);
2295 hexHCurlBasis.getValues(uhCVals, cubPointsErr, OPERATOR_VALUE);
2296 hexHCurlBasis.getValues(uhCurls, cubPointsErr, OPERATOR_CURL);
2297
2298 // Loop over elements
2299 for (int k=0; k<numElems; k++){
2300
2301 double L2errElem = 0.0;
2302 double HCurlerrElem = 0.0;
2303 double uExact1, uExact2, uExact3;
2304 double curluExact1, curluExact2, curluExact3;
2305
2306 // physical cell coordinates
2307 for (int i=0; i<numNodesPerElem; i++) {
2308 hexNodes(0,i,0) = nodeCoord(elemToNode(k,i),0);
2309 hexNodes(0,i,1) = nodeCoord(elemToNode(k,i),1);
2310 hexNodes(0,i,2) = nodeCoord(elemToNode(k,i),2);
2311 }
2312 // Edge signs
2313 for (int j=0; j<numEdgesPerElem; j++) {
2314 if (elemToNode(k,refEdgeToNode(j,0))==edgeToNode(elemToEdge(k,j),0) &&
2315 elemToNode(k,refEdgeToNode(j,1))==edgeToNode(elemToEdge(k,j),1))
2316 hexEdgeSigns(0,j) = 1.0;
2317 else
2318 hexEdgeSigns(0,j) = -1.0;
2319 }
2320
2321 // modify signs for edges whose signs were defined on another processor
2322 if (!faceIsOwned[elemToFace(k,0)]) {
2323 hexEdgeSigns(0,0)=-1.0*hexEdgeSigns(0,0);
2324 hexEdgeSigns(0,4)=-1.0*hexEdgeSigns(0,4);
2325 }
2326 if (!faceIsOwned[elemToFace(k,1)]) {
2327 hexEdgeSigns(0,1)=-1.0*hexEdgeSigns(0,1);
2328 hexEdgeSigns(0,5)=-1.0*hexEdgeSigns(0,5);
2329 }
2330 if (!faceIsOwned[elemToFace(k,2)]) {
2331 hexEdgeSigns(0,2)=-1.0*hexEdgeSigns(0,2);
2332 hexEdgeSigns(0,6)=-1.0*hexEdgeSigns(0,6);
2333 }
2334 if (!faceIsOwned[elemToFace(k,3)]) {
2335 hexEdgeSigns(0,3)=-1.0*hexEdgeSigns(0,3);
2336 hexEdgeSigns(0,7)=-1.0*hexEdgeSigns(0,7);
2337 }
2338
2339 // compute cell Jacobians, their inverses and their determinants
2340 IntrepidCTools::setJacobian(hexJacobianE, cubPointsErr, hexNodes, cellType);
2341 IntrepidCTools::setJacobianInv(hexJacobInvE, hexJacobianE );
2342 IntrepidCTools::setJacobianDet(hexJacobDetE, hexJacobianE );
2343
2344 // transform integration points to physical points
2345 IntrepidCTools::mapToPhysicalFrame(physCubPointsE, cubPointsErr, hexNodes, cellType);
2346
2347 // transform basis values to physical coordinates
2348 IntrepidFSTools::HCURLtransformVALUE<double>(uhCValsTrans, hexJacobInvE, uhCVals);
2349 IntrepidFSTools::HCURLtransformCURL<double>(uhCurlsTrans, hexJacobianE, hexJacobDetE, uhCurls);
2350
2351 // compute weighted measure
2352 IntrepidFSTools::computeCellMeasure<double>(weightedMeasureE, hexJacobDetE, cubWeightsErr);
2353
2354 // loop over cubature points
2355 for (int nPt = 0; nPt < numCubPointsErr; nPt++){
2356
2357 // get exact solution and curls
2358 double x = physCubPointsE(0,nPt,0);
2359 double y = physCubPointsE(0,nPt,1);
2360 double z = physCubPointsE(0,nPt,2);
2361 evalu(uExact1, uExact2, uExact3, x, y, z);
2362 double mu = 1.0; // use mu=1 to get the curl without material parameter
2363 evalCurlu(curluExact1, curluExact2, curluExact3, x, y, z, mu);
2364
2365 // calculate approximate solution and curls
2366 double uApprox1 = 0.0;
2367 double uApprox2 = 0.0;
2368 double uApprox3 = 0.0;
2369 double curluApprox1 = 0.0;
2370 double curluApprox2= 0.0;
2371 double curluApprox3 = 0.0;
2372 auto ucoeff_data = uCoeff.getData(0);
2373 for (int i = 0; i < numFieldsC; i++){
2374 int rowIndex = globalEdgeIds[elemToEdge(k,i)];
2375 double uh1 = ucoeff_data[rowIndex];
2376
2377 uApprox1 += uh1*uhCValsTrans(0,i,nPt,0)*hexEdgeSigns(0,i);
2378 uApprox2 += uh1*uhCValsTrans(0,i,nPt,1)*hexEdgeSigns(0,i);
2379 uApprox3 += uh1*uhCValsTrans(0,i,nPt,2)*hexEdgeSigns(0,i);
2380 curluApprox1 += uh1*uhCurlsTrans(0,i,nPt,0)*hexEdgeSigns(0,i);
2381 curluApprox2 += uh1*uhCurlsTrans(0,i,nPt,1)*hexEdgeSigns(0,i);
2382 curluApprox3 += uh1*uhCurlsTrans(0,i,nPt,2)*hexEdgeSigns(0,i);
2383 }
2384
2385 // evaluate the error at cubature points
2386 Linferr = max(Linferr, abs(uExact1 - uApprox1));
2387 Linferr = max(Linferr, abs(uExact2 - uApprox2));
2388 Linferr = max(Linferr, abs(uExact3 - uApprox3));
2389 L2errElem+=(uExact1 - uApprox1)*(uExact1 - uApprox1)*weightedMeasureE(0,nPt);
2390 L2errElem+=(uExact2 - uApprox2)*(uExact2 - uApprox2)*weightedMeasureE(0,nPt);
2391 L2errElem+=(uExact3 - uApprox3)*(uExact3 - uApprox3)*weightedMeasureE(0,nPt);
2392 HCurlerrElem+=((curluExact1 - curluApprox1)*(curluExact1 - curluApprox1))
2393 *weightedMeasureE(0,nPt);
2394 HCurlerrElem+=((curluExact2 - curluApprox2)*(curluExact2 - curluApprox2))
2395 *weightedMeasureE(0,nPt);
2396 HCurlerrElem+=((curluExact3 - curluApprox3)*(curluExact3 - curluApprox3))
2397 *weightedMeasureE(0,nPt);
2398 }
2399
2400 L2err+=L2errElem;
2401 HCurlerr+=HCurlerrElem;
2402 }
2403
2404 // sum over all processors
2405 TC_sumAll(comm,L2err,L2errTot);
2406 TC_sumAll(comm,HCurlerr,HCurlerrTot);
2407 TC_maxAll(comm,Linferr,LinferrTot);
2408
2409 if (MyPID == 0) {
2410 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
2411 std::cout << "HCurl Error: " << sqrt(HCurlerrTot) <<"\n";
2412 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
2413 }
2414
2415
2416 // delete mesh
2417 Delete_Pamgen_Mesh();
2418
2419 //clean up
2420 for(long long b = 0; b < numElemBlk; b++){
2421 delete [] elmt_node_linkage[b];
2422 delete [] element_types[b];
2423 }
2424 delete [] block_ids;
2425 delete [] nodes_per_element;
2426 delete [] element_attributes;
2427 delete [] element_types;
2428 delete [] elmt_node_linkage;
2429 delete [] elements;
2430 delete [] nodeCoordx;
2431 delete [] nodeCoordy;
2432 delete [] nodeCoordz;
2433
2434 delete [] globalNodeIds;
2435 delete [] nodeIsOwned;
2436 delete [] globalEdgeIds;
2437 delete [] edgeIsOwned;
2438 delete [] globalFaceIds;
2439 delete [] faceIsOwned;
2440 if(num_node_comm_maps > 0){
2441 delete [] node_comm_proc_ids;
2442 delete [] node_cmap_node_cnts;
2443 delete [] node_cmap_ids;
2444 for(long long i=0;i<num_node_comm_maps;i++){
2445 delete [] comm_node_ids[i];
2446 delete [] comm_node_proc_ids[i];
2447 }
2448
2449 delete [] comm_node_ids;
2450 delete [] comm_node_proc_ids;
2451 }
2452
2453 // Summarize timings
2454 if (use_stacked_timer) {
2455 Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::rcp(new Teuchos::FancyOStream(Teuchos::rcpFromRef(std::cout)));
2456 stacked_timer->stop("TC Maxwell Tpetra");
2457 Teuchos::StackedTimer::OutputOptions options;
2458 options.output_fraction = options.output_histogram = options.output_minmax = true;
2459 stacked_timer->report(*out, comm, options);
2460 } else
2461 Teuchos::TimeMonitor::report (comm.ptr(), std::cout);
2462
2463 return 0;
2464 }
2465 #endif
2466 /**********************************************************************************/
2467 /********************************* END MAIN ***************************************/
2468 /**********************************************************************************/
2469
2470
2471
2472
2473 /*************************************************************************************/
2474 /**************************** GET ML RESIDUAL ****************************************/
2475 /*************************************************************************************/
2476 /** \brief Compute ML solution residual
2477
2478 \param A [in] discrete operator
2479 \param lhs [in] solution vector
2480 \param rhs [in] right hand side vector
2481 \param Time [in] elapsed time for output
2482 \param TotalErrorResidual [out] error residual
2483 \param TotalErrorExactSol [out] error in xh (not an appropriate measure
2484 for H(curl) basis functions)
2485 */
2486 void solution_test(string msg, const Tpetra_Operator &A,const Tpetra_MultiVector &lhs,const Tpetra_MultiVector &rhs,const Tpetra_MultiVector &xexact, double & TotalErrorExactSol, double& TotalErrorResidual){
2487 // ==================================================== //
2488 // compute difference between exact solution and ML one //
2489 // ==================================================== //
2490 auto comm = A.getDomainMap()->getComm();
2491 double d = 0.0, d_tot = 0.0;
2492 auto lhs_data = lhs.getData(0);
2493 auto xexact_data = xexact.getData(0);
2494 for(LO i=0 ; i<(LO)lhs.getMap()->getLocalNumElements() ; ++i )
2495 d += (lhs_data[i] - xexact_data[i]) * (lhs_data[i] - xexact_data[i]);
2496
2497 TC_sumAll(comm,d,d_tot);
2498
2499 // ================== //
2500 // compute ||Ax - b|| //
2501 // ================== //
2502 Teuchos::Array<double> Norm(1);
2503 Tpetra_Vector Ax(rhs.getMap());
2504 A.apply(lhs, Ax);
2505 Ax.update(1.0, rhs, -1.0);
2506 Ax.norm2(Norm);
2507
2508 // NOTE: (x_exact - x) does not make sense for H(curl) or H(grad) basis functions
2509 if (comm->getRank() == 0) {
2510 cout << msg << "......Using " << comm->getSize() << " processes" << endl;
2511 cout << msg << "......||A x - b||_2 = " << Norm << endl;
2512 // cout << msg << "......||x_exact - x||_2 = " << sqrt(d_tot) << endl;
2513 }
2514
2515 TotalErrorExactSol += sqrt(d_tot);
2516 TotalErrorResidual += Norm[0];
2517 }
2518
2519 /*************************************************************************************/
2520 /*************************** MueLu PRECONDITIONER ************************************/
2521 /*************************************************************************************/
2522 RCP<Xpetra_Operator> BuildPreconditioner_MueLu(char ProblemType[],
2523 Teuchos::ParameterList & MLList,
2524 RCP<Tpetra_CrsMatrix> & CurlCurl,
2525 RCP<Tpetra_CrsMatrix> & D0clean,
2526 RCP<Tpetra_CrsMatrix> & M0inv,
2527 RCP<Tpetra_CrsMatrix> & Ms,
2528 RCP<Tpetra_CrsMatrix> & M1,
2529 RCP<Tpetra_MultiVector> & coords){
2530 MLList.set("parameterlist: syntax","muelu");
2531
2532 RCP<Matrix> curlcurlOp = toXpetra(CurlCurl);
2533 RCP<Matrix> D0cleanOp = toXpetra(D0clean);
2534 RCP<Matrix> M0invOp = toXpetra(M0inv);
2535 RCP<Matrix> M1Op = toXpetra(M1);
2536 RCP<Matrix> MsOp = toXpetra(Ms);
2537
2538 RCP<Xpetra_MultiVector> xcoords = toXpetra(coords);
2539
2540
2541 // construct preconditioner
2542 RCP<MueLu::RefMaxwell<SC,LO,GO,NO> > preconditioner
2543 = rcp( new MueLu::RefMaxwell<SC,LO,GO,NO>(curlcurlOp,D0cleanOp,MsOp,M0invOp,
2544 M1Op,Teuchos::null,xcoords,MLList) );
2545 return preconditioner;
2546 }
2547
2548
2549
2550 #ifdef HAVE_TRILINOSCOUPLINGS_STRATIMIKOS
2551 /*************************************************************************************/
2552 /********************* Straitmikos PRECONDITIONER*************************************/
2553 /*************************************************************************************/
2554 void TestPreconditioner_Stratimikos(char ProblemType[],
2555 Teuchos::ParameterList & SList,
2556 RCP<Tpetra_CrsMatrix> & CurlCurl,
2557 RCP<Tpetra_CrsMatrix> & D0clean,
2558 RCP<Tpetra_CrsMatrix> & M0inv,
2559 RCP<Tpetra_CrsMatrix> & Ms,
2560 RCP<Tpetra_CrsMatrix> & M1,
2561 RCP<Tpetra_MultiVector> & coords,
2562 RCP<Tpetra_MultiVector> & x,
2563 RCP<Tpetra_MultiVector> & b) {
2564
2565 /* Build the rest of the Stratimikos list */
2566 SList.sublist("Preconditioner Types").sublist("ML").set("Base Method Defaults","refmaxwell");
2567
2568 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").set("D0","substitute const D0");
2569 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").set("M0inv","substitute const M0inv");
2570 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").set("M1","substitute const M1");
2571 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").set("Ms","substitute const Ms");
2572 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 11list").set("x-coordinates","substitute x-coordinates");
2573 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 11list").set("y-coordinates","substitute y-coordinates");
2574 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 11list").set("z-coordinates","substitute z-coordinates");
2575 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 22list").set("x-coordinates","substitute x-coordinates");
2576 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 22list").set("y-coordinates","substitute y-coordinates");
2577 SList.sublist("Preconditioner Types").sublist("ML").sublist("ML Settings").sublist("refmaxwell: 22list").set("z-coordinates","substitute z-coordinates");
2578
2579 SList.sublist("Preconditioner Types").sublist("MueLuRefMaxwell").set("D0","substitute D0");
2580 SList.sublist("Preconditioner Types").sublist("MueLuRefMaxwell").set("M0inv","substitute M0inv");
2581 SList.sublist("Preconditioner Types").sublist("MueLuRefMaxwell").set("M1","substitute M1");
2582 SList.sublist("Preconditioner Types").sublist("MueLuRefMaxwell").set("Ms","substitute Ms");
2583 SList.sublist("Preconditioner Types").sublist("MueLuRefMaxwell").set("Coordinates","substitute Coordinates");
2584
2585 /* Add matrices to parameterlist */
2586 Teuchos::ParameterList& precTypesPL = SList.sublist("Preconditioner Types");
2587 std::list<Teuchos::ParameterList*> sublists;
2588 sublists.push_back(&precTypesPL);
2589 while (sublists.size() > 0) {
2590 Teuchos::ParameterList* sublist = sublists.front();
2591 sublists.pop_front();
2592 std::list<std::string> keys;
2593 for (Teuchos::ParameterList::ConstIterator it = sublist->begin(); it != sublist->end(); ++it) {
2594 const std::string &entryName = sublist->name(it);
2595 const Teuchos::ParameterEntry &theEntry = sublist->entry(it);
2596 if (theEntry.isList()) {
2597 Teuchos::ParameterList& sl = sublist->sublist(entryName);
2598 sublists.push_back(&sl);
2599 } else if (theEntry.isType<std::string>() && Teuchos::getValue<std::string>(theEntry).find("substitute ") != std::string::npos) {
2600 keys.push_back(entryName);
2601 }
2602 }
2603 for (auto key_it = keys.begin(); key_it != keys.end(); ++key_it) {
2604 std::string value = sublist->get<std::string>(*key_it).substr(11, std::string::npos);
2605 if (value == "D0")
2606 sublist->set(*key_it, rcp((Tpetra_CrsMatrix*) &*D0clean,false));
2607 else if (value == "M0inv")
2608 sublist->set(*key_it, rcp((Tpetra_CrsMatrix*) &*M0inv,false));
2609 else if (value == "M1")
2610 sublist->set(*key_it, rcp((Tpetra_CrsMatrix*) &*M1,false));
2611 else if (value == "Ms")
2612 sublist->set(*key_it, rcp((Tpetra_CrsMatrix*) &*Ms,false));
2613 else if (value == "Coordinates")
2614 sublist->set(*key_it, rcp((Tpetra_MultiVector*) &*coords,false));
2615 else if (value == "const D0")
2616 sublist->set(*key_it, rcp((const Tpetra_CrsMatrix*) &*D0clean,false));
2617 else if (value == "const M0inv")
2618 sublist->set(*key_it, rcp((const Tpetra_CrsMatrix*) &*M0inv,false));
2619 else if (value == "const M1")
2620 sublist->set(*key_it, rcp((const Tpetra_CrsMatrix*) &*M1,false));
2621 else if (value == "const Ms")
2622 sublist->set(*key_it, rcp((const Tpetra_CrsMatrix*) &*Ms,false));
2623 else if (value == "const Coordinates")
2624 sublist->set(*key_it, rcp((const Tpetra_MultiVector*) &*coords,false));
2625 // else if (value == "x-coordinates")
2626 // sublist->set(*key_it, &Nx[0]);
2627 // else if (value == "y-coordinates")
2628 // sublist->set(*key_it, &Ny[0]);
2629 // else if (value == "z-coordinates")
2630 // sublist->set(*key_it, &Nz[0]);
2631 }
2632 }
2633
2634 // Tpetra_Time Time(CurlCurl.Comm());
2635
2636 /* Thyra Wrappers */
2637 // Tpetra_MultiVector x(xh);
2638 x->putScalar(0.0);
2639
2640 Teuchos::RCP<const Tpetra::RowMatrix<SC,LO,GO,NO> > tpRowMat = Teuchos::rcp_dynamic_cast<const Tpetra::RowMatrix<SC,LO,GO,NO> >(CurlCurl);
2641 TEUCHOS_TEST_FOR_EXCEPT(Teuchos::is_null(tpRowMat));
2642 Teuchos::RCP<const Tpetra::Operator <SC,LO,GO,NO> > tpOperator = Teuchos::rcp_dynamic_cast<const Tpetra::Operator<SC,LO,GO,NO> >(tpRowMat);
2643 TEUCHOS_TEST_FOR_EXCEPT(Teuchos::is_null(tpOperator));
2644
2645 RCP<const Thyra::LinearOpBase<SC> > At = Thyra::createConstLinearOp(tpOperator);
2646
2647 auto thyTpMap = Thyra::tpetraVectorSpace<SC,LO,GO,NO>(x->getMap());
2648 auto thyDomMap = Thyra::tpetraVectorSpace<SC,LO,GO,NO>(Tpetra::createLocalMapWithNode<LO,GO,NO>(x->getNumVectors(), x->getMap()->getComm()));
2649 auto xt = rcp(new Thyra::TpetraMultiVector<SC,LO,GO,NO>());
2650 xt->initialize(thyTpMap, thyDomMap, x);
2651 auto bt = rcp(new Thyra::TpetraMultiVector<SC,LO,GO,NO>());
2652 bt->initialize(thyTpMap, thyDomMap, b);
2653
2654 /* Stratimikos setup */
2655 Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder;
2656 Stratimikos::enableMueLuRefMaxwell<SC,LO,GO,Node>(linearSolverBuilder); // Register MueLu as a Stratimikos preconditioner strategy.
2657
2658 linearSolverBuilder.setParameterList(rcp(&SList,false));
2659 RCP<Thyra::LinearOpWithSolveFactoryBase<SC> > lowsFactory = createLinearSolveStrategy(linearSolverBuilder);
2660 RCP<Thyra::LinearOpWithSolveBase<SC> > lows = Thyra::linearOpWithSolve<SC>(*lowsFactory,At);
2661
2662 /* Solve */
2663 Thyra::SolveStatus<SC> status = Thyra::solve<SC>(*lows, Thyra::NOTRANS, *bt, xt.ptr());
2664
2665 }
2666
2667 #endif // HAVE_TRILINOSCOUPLINGS_STRATIMIKOS
2668
2669 /**********************************************************************************/
2670 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
2671 /**********************************************************************************/
2672
2673 // Calculates value of exact solution u
2674 int evalu(double & uExact0, double & uExact1, double & uExact2, double & x, double & y, double & z)
2675 {
2676
2677 // Exact solution 1 - homogeneous boundary conditions
2678 uExact0 = sin(M_PI*x)*sin(M_PI*y);
2679 uExact1 = y;
2680 uExact2 = z;
2681
2682 return 0;
2683 }
2684
2685 // Calculates curl of exact solution u
2686 int evalCurlu(double & curlu0, double & curlu1, double & curlu2, double & x, double & y, double & z, double &mu)
2687 {
2688 // Exact solution 1 - homogeneous boundary conditions
2689 curlu0 = 0;
2690 curlu1 = 0;
2691 curlu2 = -mu*M_PI*(sin(M_PI*x)*cos(M_PI*y));
2692
2693 return 0;
2694 }
2695
2696
2697
2698 // Calculates curl of exact solution u
2699 int evalCurlCurlu(double & curlcurlu0, double & curlcurlu1, double & curlcurlu2, double & x, double & y, double & z, double &mu)
2700 {
2701 // Exact solution 1 - homogeneous boundary conditions
2702 curlcurlu0 = mu*M_PI*M_PI*(sin(M_PI*x)*sin(M_PI*y));
2703 curlcurlu1 = mu*M_PI*M_PI*(cos(M_PI*x)*cos(M_PI*y));
2704 curlcurlu2 = 0;
2705
2706 return 0;
2707 }