Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_CVFEM.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 /********************************************************************************/
11 /****************** Solution of Advection Diffusion Equation ********************/
12 /********************** Using CVFEM with Multi-dimensional **********************/
13 /************************ Scharfetter-Gummel Updwinding *************************/
14 /********************************************************************************/
15
16 /** \file example_CVFEM.cpp
17 \brief Example solution of an Advection Diffusion equation on a quadrilateral
18 or triangular mesh using the CVFEM.
19
20 \verbatim
21
22 Advection diffusion system:
23
24 - div (epsilon grad phi - u phi) = f in Omega
25 phi = g on Gamma
26
27 where
28 u is the advection velocity
29 epsilon is the diffusion coefficient
30 f is a given source term
31
32
33 Corresponding discrete linear system for nodal coefficients(x):
34
35 Kx = b
36
37 K - HGrad stiffness matrix
38 b - right hand side vector
39
40 \endverbatim
41
42 \author K. Peterson
43
44 \remark Usage:
45 \code ./TrilinosCouplings_Example_CVFEM.exe <input.xml> \endcode
46
47 \remark Example requires an xml input file with mesh and solver settings.
48
49
50 NOTE: This problem does not currently work on more than one core ([email protected] 3/17/16)
51 */
52
53 /********************************************************************************/
54 /********************************************************************************/
55 /********************************************************************************/
56
57 /**************************************************************/
58 /* Includes */
59 /**************************************************************/
60
61 // Intrepid includes
62 #include "Intrepid_FunctionSpaceTools.hpp"
63 #include "Intrepid_CellTools.hpp"
64 #include "Intrepid_ArrayTools.hpp"
65 #include "Intrepid_Basis.hpp"
66 #include "Intrepid_HGRAD_QUAD_C1_FEM.hpp"
67 #include "Intrepid_HCURL_QUAD_I1_FEM.hpp"
68 #include "Intrepid_HGRAD_TRI_C1_FEM.hpp"
69 #include "Intrepid_HCURL_TRI_I1_FEM.hpp"
70 #include "Intrepid_RealSpaceTools.hpp"
71 #include "Intrepid_DefaultCubatureFactory.hpp"
72 #include "Intrepid_Cubature.hpp"
73 #include "Intrepid_CubatureControlVolume.hpp"
74 #include "Intrepid_CubatureControlVolumeSide.hpp"
75 #include "Intrepid_Utils.hpp"
76
77 // Epetra includes
78 #include "Epetra_Time.h"
79 #include "Epetra_Map.h"
80 #ifdef HAVE_MPI
81 #include "Epetra_MpiComm.h"
82 #else
83 #include "Epetra_SerialComm.h"
84 #endif
85 #include "Epetra_FECrsMatrix.h"
86 #include "Epetra_FEVector.h"
87 #include "Epetra_Import.h"
88
89 // Teuchos includes
90 #include "Teuchos_oblackholestream.hpp"
91 #include "Teuchos_RCP.hpp"
92 #include "Teuchos_BLAS.hpp"
93 #include "Teuchos_GlobalMPISession.hpp"
94 #include "Teuchos_XMLParameterListHelpers.hpp"
95
96 // Shards includes
97 #include "Shards_CellTopology.hpp"
98
99 // EpetraExt includes
100 #include "EpetraExt_RowMatrixOut.h"
101 #include "EpetraExt_MultiVectorOut.h"
102
103 // AztecOO includes
104 #include "AztecOO.h"
105
106 // ML includes
107 #include "ml_MultiLevelPreconditioner.h"
108 #include "ml_epetra_utils.h"
109
110 // Sacado includes
111 #include "Sacado.hpp"
112
113 /*** Uncomment if you would like output data for plotting ***/
114 //#define DUMP_DATA
115
116 /**********************************************************************************/
117 /**************************** FUNCTION DECLARATIONS *******************************/
118 /**********************************************************************************/
119
120 /** \brief User-defined exact solution.
121
122 \param x [in] x-coordinate of the evaluation point
123 \param y [in] y-coordinate of the evaluation point
124
125 \return Value of the exact solution at (x,y)
126 */
127 template<typename Scalar>
128 const Scalar exactSolution(const Scalar& x, const Scalar& y);
129
130 /** \brief User-defined advection velocity.
131
132 \param advVel [out] advection velocity evaluated at (x,y)
133 \param x [in] x-coordinate of the evaluation point
134 \param y [in] y-coordinate of the evaluation point
135 */
136 template<typename Scalar>
137 void advectionVelocity(Scalar advVel[2], const Scalar& x, const Scalar& y, const std::string problem);
138
139 /** \brief User-defined diffusivity
140
141 \param x [in] x-coordinate of the evaluation point
142 \param y [in] y-coordinate of the evaluation point
143 \param epsilon [in] diffusion coefficient from xml imput file
144
145 \return Value of the diffusivity at (x,y)
146 */
147 template<typename Scalar1, typename Scalar2>
148 const Scalar1 diffusivity(const Scalar1& x, const Scalar1& y, const Scalar2& epsilon, const bool variableEpsilon);
149
150 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
151
152 \param gradExact [out] gradient of the exact solution evaluated at (x,y)
153 \param x [in] x-coordinate of the evaluation point
154 \param y [in] y-coordinate of the evaluation point
155 */
156 template<typename Scalar>
157 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y);
158
159 /** \brief Computes source term: f = -div(J_n). Requires user-defined exact solution
160 and material parameters.
161
162 \param x [in] x-coordinate of the evaluation point
163 \param y [in] y-coordinate of the evaluation point
164 \param epsilon [in] diffusion coefficient
165
166 \return Source term corresponding to the user-defined exact solution evaluated at (x,y)
167 */
168 template<typename Scalar1, typename Scalar2>
169 const Scalar1 sourceTerm(Scalar1& x, Scalar1& y, Scalar2& epsilon,
170 const bool variableEpsilon, const std::string problem);
171
172
173 /** \brief Computation of the exact solution at array of points in physical space.
174
175 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
176 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
177 */
178 template<class ArrayOut, class ArrayIn>
179 void evaluateExactSolution(ArrayOut & exactSolutionValues,
180 const ArrayIn & evaluationPoints);
181
182 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
183
184 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
185 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
186 */
187 template<class ArrayOut, class ArrayIn>
188 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
189 const ArrayIn & evaluationPoints);
190
191 /** \brief Create quadrilateral or triangle mesh on the domain [0,1]x[0,1]
192
193 \param elemToNode [out] Array with element to node mapping
194 \param nodeCoords [out] Array with nodal coordinates
195 \param bcLeftId [out] Array with ids of left boundary nodes,
196 \param bcRightId [out] Array with ids of right boundary nodes
197 \param bcTopId [out] Array with ids of top boundary nodes
198 \param bcBotId [out] Array with ids of bottom boundary nodes
199 \param meshType [in] Mesh type (quad or tri)
200 \param meshSize [in] Number of elements in each direction
201 */
202 template<class ArrayOut1, class ArrayOut2, class Scalar>
203 void createMesh(ArrayOut1 & elemToNode, ArrayOut2 & nodeCoords,
204 ArrayOut1 & bcLeftId, ArrayOut1 & bcRightId,
205 ArrayOut1 & bcTopId, ArrayOut1 & bcBotId,
206 const std::string & meshType, const Scalar & meshSize);
207
208 /**********************************************************************************/
209 /******************************** MAIN ********************************************/
210 /**********************************************************************************/
211
212 int main(int argc, char *argv[]) {
213
214 #ifdef HAVE_MPI
215 int numProcs=1;
216 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
217 numProcs=mpiSession.getNProc();
218 Epetra_MpiComm Comm(MPI_COMM_WORLD);
219 #else
220 Epetra_SerialComm Comm;
221 #endif
222
223 int MyPID = Comm.MyPID();
224 Epetra_Time Time(Comm);
225
226 bool showTiming = 0;
227
228 #ifdef HAVE_MPI
229 if (numProcs > 1) {
230 if (MyPID == 0) {
231 std::cout <<"\n>>> ERROR: Example will only run on a single processor for now. \n\n";
232 }
233 exit(1);
234 }
235 #endif
236
237 /**********************************************************************************/
238 /*********************************** XML INPUT ************************************/
239 /**********************************************************************************/
240
241 // get xml file from command line if provided, otherwise use default
242 std::string xmlInFileName;
243 if(argc>=2) xmlInFileName=std::string(argv[1]);
244 else xmlInFileName="CVFEM.xml";
245
246 // default values
247 std::string meshType = "quad";
248 std::string meshMotion = "none";
249 int meshSize = 10;
250 std::string problem = "manufacturedSoln";
251 std::string stabilization = "type1";
252 double epsilon = 0.001;
253 bool variableEpsilon = 0;
254
255 // read xml file into parameter list
256 Teuchos::ParameterList inputList;
257
258 if(xmlInFileName.length()) {
259
260 if (MyPID == 0)
261 std::cout << "\nReading parameter list from \""<<xmlInFileName<<"\" \n\n";
262
263 Teuchos::updateParametersFromXmlFile(xmlInFileName, Teuchos::ptr (&inputList));
264
265 // get mesh input
266 Teuchos::ParameterList & meshList=inputList.sublist("Mesh Input");
267 meshType = Teuchos::getParameter<std::string>(meshList,"meshType");
268 meshMotion = Teuchos::getParameter<std::string>(meshList,"meshMotion");
269 meshSize = Teuchos::getParameter<int>(meshList,"meshSize");
270 meshMotion = Teuchos::getParameter<std::string>(meshList,"meshMotion");
271
272 // get problem definition
273 problem = Teuchos::getParameter<std::string>(inputList,"problem");
274
275 // get stabilization type
276 stabilization = Teuchos::getParameter<std::string>(inputList,"stabilization");
277
278 // get solver inputs
279 Teuchos::ParameterList inputSolverList = inputList.sublist("ML Input") ;
280
281 // get physical parameter values
282 Teuchos::ParameterList & physicsList=inputList.sublist("Physics Input");
283 epsilon = physicsList.get("epsilon",0.001);
284 variableEpsilon = Teuchos::getParameter<bool>(physicsList,"variableEpsilon");
285
286 std::cout <<" meshType = " << meshType << " \n";
287 std::cout <<" meshSize = " << meshSize << " \n";
288 std::cout <<" meshMotion = " << meshMotion << " \n";
289 std::cout <<" problem = " << problem << " \n";
290 std::cout <<" stabilization = " << stabilization<< " \n";
291 std::cout <<" epsilon = " << epsilon << " \n";
292 std::cout <<" variableEpsilon = " << variableEpsilon << " \n\n";
293
294 }
295 else {
296
297 if (MyPID == 0){
298 std::cout << "\nSetting default parameters: \n";
299 std::cout <<" meshType = " << meshType << " \n";
300 std::cout <<" meshSize = " << meshSize << " \n";
301 std::cout <<" meshMotion = " << meshMotion << " \n";
302 std::cout <<" problem = " << problem << " \n";
303 std::cout <<" stabilization = " << stabilization<< " \n";
304 std::cout <<" epsilon = " << epsilon << " \n";
305 std::cout <<" variableEpsilon = " << variableEpsilon << " \n\n";
306 }
307
308 }
309
310 TEUCHOS_TEST_FOR_EXCEPTION( ( (stabilization != "type1") &&
311 (stabilization != "type2") && (stabilization != "type3")),
312 std::invalid_argument,
313 "Unknown stabilization type./n/n");
314
315 TEUCHOS_TEST_FOR_EXCEPTION( ( (problem != "manufacturedSoln") && (problem != "skewAdvection") &&
316 (problem != "horizAdvection") && (problem != "doubleGlazing")),
317 std::invalid_argument,
318 "Unknown problem type./n/n");
319
320 /**********************************************************************************/
321 /*********************************** BUILD MESH ***********************************/
322 /**********************************************************************************/
323
324 // 2-D meshes only for now
325 int spaceDim = 2;
326
327 // For selected mesh type define element to node mapping and element node coordinates
328 Intrepid::FieldContainer<int> elemToNode;
329 Intrepid::FieldContainer<double> nodeCoords;
330
331 // Also define arrays for use in defining boundary conditions
332 Intrepid::FieldContainer<int> bcLeftId;
333 Intrepid::FieldContainer<int> bcRightId;
334 Intrepid::FieldContainer<int> bcTopId;
335 Intrepid::FieldContainer<int> bcBotId;
336
337 // Create mesh on square domain [0,1]x[0,1]
338 createMesh(elemToNode, nodeCoords, bcLeftId,
339 bcRightId, bcTopId, bcBotId,
340 meshType, meshSize);
341
342 int numNodes = nodeCoords.dimension(0);
343 int numElems = elemToNode.dimension(0);
344
345 Intrepid::FieldContainer<int> nodeOnBoundary(numNodes);
346 for (int i = 0; i<bcLeftId.dimension(0); i++){
347 nodeOnBoundary(bcLeftId(i)) = 1;
348 }
349 for (int i = 0; i<bcRightId.dimension(0); i++){
350 nodeOnBoundary(bcRightId(i)) = 1;
351 }
352 for (int i = 0; i<bcTopId.dimension(0); i++){
353 nodeOnBoundary(bcTopId(i)) = 1;
354 }
355 for (int i = 0; i<bcBotId.dimension(0); i++){
356 nodeOnBoundary(bcBotId(i)) = 1;
357 }
358
359 // For now assume regular mesh
360 double hx = nodeCoords(elemToNode(0,1),0) - nodeCoords(elemToNode(0,0),0);
361 double hy = nodeCoords(elemToNode(0,2),1) - nodeCoords(elemToNode(0,1),1);
362
363 // Modify nodal coordinates, if necessary
364 for (int inode = 0; inode < numNodes; inode++) {
365
366 double x = nodeCoords(inode,0);
367 double y = nodeCoords(inode,1);
368
369 // randomly perturbed mesh
370 if (meshMotion == "random"){
371 if (!nodeOnBoundary(inode)) {
372 double rx = 2.0 * (double)rand()/RAND_MAX - 1.0;
373 double ry = 2.0 * (double)rand()/RAND_MAX - 1.0;
374 nodeCoords(inode,0) = x + 0.25 * hx * rx;
375 nodeCoords(inode,1) = y + 0.25 * hy * ry;
376 } // end if !node on boundary
377 }
378
379 // Wavy grid motion 1
380 else if (meshMotion == "wave"){
381 double alpha = 0.5/5.0;
382 nodeCoords(inode,0) = x + alpha*sin(2.0*M_PI*x)*sin(2.0*M_PI*y);
383 nodeCoords(inode,1) = y + alpha*sin(2.0*M_PI*x)*sin(2.0*M_PI*y);
384 }
385
386 // Tensor product grid
387 else if (meshMotion == "tensor"){
388 double gamma = 0.1;
389 double alpha = sin(4.0*M_PI*gamma)/2.0;
390 nodeCoords(inode,0) = (1.0-alpha)*x + alpha*x*x*x;
391 nodeCoords(inode,1) = (1.0-alpha)*y + alpha*y*y*y;
392 }
393
394 } // end node loop
395
396
397 if(showTiming) {std::cout << "Read/Create mesh "
398 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
399
400 /**********************************************************************************/
401 /********************************SET CELL TOPOLOGY ********************************/
402 /**********************************************************************************/
403
404 // For now set cell topology based on number of nodes per element.
405 // WARNING: only works for 2-D 1st degree elements.
406
407 Teuchos::RCP<shards::CellTopology> cellType;
408
409 int numNodesPerElem = elemToNode.dimension(1);
410
411 TEUCHOS_TEST_FOR_EXCEPTION( ( (numNodesPerElem != 4) && (numNodesPerElem != 3) ),
412 std::invalid_argument,
413 "Unknown number of nodes per element for cell topology selection. Please use 3 for Triangle or 4 for Quadrilateral.");
414
415 const CellTopologyData &myCellData =
416 (numNodesPerElem == 4) ? *shards::getCellTopologyData<shards::Quadrilateral<4> >() : *shards::getCellTopologyData<shards::Triangle<3> >();
417
418 // shards::CellTopology cellType(&myCellData);
419
420 cellType = Teuchos::rcp(new shards::CellTopology(&myCellData));
421
422 int numEdgesPerElem = cellType->getEdgeCount();
423
424 if(showTiming) {std::cout << "Get cell topology "
425 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
426
427 /**********************************************************************************/
428 /******************* GET CONTROL VOLUME INTEGRATION POINTS ************************/
429 /**********************************************************************************/
430
431 // Loop over cells to fill cell coordinate array
432 Intrepid::FieldContainer<double> cellCoords(numElems, numNodesPerElem, spaceDim);
433
434 // loop over elements
435 for (int ielem = 0; ielem < numElems; ielem++) {
436
437 // loop over nodes and fill cell coordinates array
438 for (int inode = 0; inode < numNodesPerElem; inode++) {
439
440 cellCoords(ielem, inode, 0) = nodeCoords(elemToNode(ielem,inode),0);
441 cellCoords(ielem, inode, 1) = nodeCoords(elemToNode(ielem,inode),1);
442
443 } // end node loop
444
445 } // end cell loop
446
447 Teuchos::RCP<Intrepid::Cubature<double,Intrepid::FieldContainer<double> > > controlVolCub;
448 Teuchos::RCP<Intrepid::Cubature<double,Intrepid::FieldContainer<double> > > controlVolSideCub;
449
450 // cubature rule for subcontrol volume points
451 controlVolCub = Teuchos::rcp(new Intrepid::CubatureControlVolume<double,Intrepid::FieldContainer<double>,Intrepid::FieldContainer<double> >(cellType));
452 int numVolPoints = controlVolCub->getNumPoints();
453
454 // cubature rule for points along control volume edges
455 controlVolSideCub = Teuchos::rcp(new Intrepid::CubatureControlVolumeSide<double,Intrepid::FieldContainer<double>,Intrepid::FieldContainer<double> >(cellType));
456 int numSidePoints = controlVolSideCub->getNumPoints();
457
458 // get volume cubature points and weights - points are in physical coordinates!
459 Intrepid::FieldContainer<double> volCubPoints(numElems,numVolPoints,spaceDim);
460 Intrepid::FieldContainer<double> volCubWeights(numElems,numVolPoints);
461 controlVolCub->getCubature(volCubPoints,volCubWeights,cellCoords);
462
463 // get side cubature points and weights - points are in physical coordinates!
464 // also note that the weights are vectors, it is the side normal weighted by the side length!
465 Intrepid::FieldContainer<double> sideCubPoints(numElems,numSidePoints,spaceDim);
466 Intrepid::FieldContainer<double> sideCubWeights(numElems,numSidePoints,spaceDim);
467 controlVolSideCub->getCubature(sideCubPoints,sideCubWeights,cellCoords);
468
469 if(showTiming) {std::cout << "Get control volume cubature "
470 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
471
472 /**********************************************************************************/
473 /************************ GET JACOBIANS AT CUBATURE POINTS ************************/
474 /**********************************************************************************/
475
476 // get cubature points in reference space
477 Intrepid::FieldContainer<double> refVolPoints(numElems,numVolPoints,spaceDim);
478 Intrepid::FieldContainer<double> refSidePoints(numElems,numSidePoints,spaceDim);
479 Intrepid::CellTools<double>::mapToReferenceFrame(refVolPoints, volCubPoints, cellCoords,*cellType);
480 Intrepid::CellTools<double>::mapToReferenceFrame(refSidePoints, sideCubPoints, cellCoords,*cellType);
481
482 // get Jacobian
483 Intrepid::FieldContainer<double> cellJacobianVol(numElems,numVolPoints,spaceDim,spaceDim);
484 Intrepid::FieldContainer<double> cellJacobianSide(numElems,numSidePoints,spaceDim,spaceDim);
485 Intrepid::FieldContainer<double> cellJacobInvVol(numElems,numVolPoints,spaceDim,spaceDim);
486 Intrepid::FieldContainer<double> cellJacobInvSide(numElems,numSidePoints,spaceDim,spaceDim);
487 Intrepid::CellTools<double>::setJacobian(cellJacobianVol, refVolPoints, cellCoords,*cellType,-1);
488 Intrepid::CellTools<double>::setJacobianInv(cellJacobInvVol, cellJacobianVol );
489 Intrepid::CellTools<double>::setJacobian(cellJacobianSide, refSidePoints, cellCoords,*cellType,-1);
490 Intrepid::CellTools<double>::setJacobianInv(cellJacobInvSide, cellJacobianSide );
491
492
493 if(showTiming) {std::cout << "Get cell jacobians "
494 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
495
496 /**********************************************************************************/
497 /*********************************** GET BASIS ************************************/
498 /**********************************************************************************/
499
500 // Choose appropriate HGRAD and HCURL bases based on cell topology
501 // Evaluate basis at cubature points in cell loop because points are in physical space
502 Teuchos::RCP<Intrepid::Basis<double, Intrepid::FieldContainer<double> > > HGradBasis;
503 Teuchos::RCP<Intrepid::Basis<double, Intrepid::FieldContainer<double> > > HCurlBasis;
504
505 switch (cellType->getKey()) {
506
507 case shards::Triangle<3>::key:
508 HGradBasis = Teuchos::rcp(new Intrepid::Basis_HGRAD_TRI_C1_FEM<double, Intrepid::FieldContainer<double> > );
509 HCurlBasis = Teuchos::rcp(new Intrepid::Basis_HCURL_TRI_I1_FEM<double, Intrepid::FieldContainer<double> > );
510 break;
511
512 case shards::Quadrilateral<4>::key:
513 HGradBasis = Teuchos::rcp(new Intrepid::Basis_HGRAD_QUAD_C1_FEM<double, Intrepid::FieldContainer<double> > );
514 HCurlBasis = Teuchos::rcp(new Intrepid::Basis_HCURL_QUAD_I1_FEM<double, Intrepid::FieldContainer<double> > );
515 break;
516
517 default:
518 TEUCHOS_TEST_FOR_EXCEPTION( ( (cellType->getKey() != shards::Quadrilateral<4>::key) &&
519 (cellType->getKey() != shards::Triangle<3>::key) ),
520 std::invalid_argument,
521 "Unknown cell topology for basis selection. Please use Triangle_3 or Quadrilateral_4.");
522 }
523
524 int numFields = HGradBasis->getCardinality();
525 int numFieldsEdge = HCurlBasis->getCardinality();
526
527
528 if(showTiming) {std::cout << "Getting basis "
529 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
530
531
532 /**********************************************************************************/
533 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
534 /**********************************************************************************/
535
536 // For now assume local nodes = global nodes (and assume DOFs = nodes)
537
538 Epetra_Map globalMapNodes(numNodes, 0, Comm);
539 Epetra_FECrsMatrix OpMatrix(Copy, globalMapNodes, numFields);
540 Epetra_FEVector rhsVector(globalMapNodes);
541
542 if(showTiming) {std::cout << "Build global maps "
543 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
544
545
546 /**********************************************************************************/
547 /**** PUT COORDINATES AND NODAL VALUES IN ARRAYS FOR OUTPUT (FOR PLOTTING ONLY) ***/
548 /**********************************************************************************/
549
550 // Put coordinates in multivector for output
551 Epetra_MultiVector nCoord(globalMapNodes,2);
552
553 // Put element to node mapping in multivector for output
554 Epetra_Map globalMapElem(numElems, 0, Comm);
555 Epetra_MultiVector elem2node(globalMapElem,numNodesPerElem);
556
557 // Loop over elements
558 for (int j = 0; j < numElems; j++) {
559
560 for (int i = 0; i < numNodesPerElem; i++) {
561 int inode = elemToNode(j,i);
562 elem2node[i][j] = inode;
563 nCoord[0][inode] = nodeCoords(inode,0);
564 nCoord[1][inode] = nodeCoords(inode,1);
565 }
566
567 } // end loop over elements
568
569 // output multivectors
570 #ifdef DUMP_DATA
571 EpetraExt::MultiVectorToMatrixMarketFile("elem2node.dat",elem2node,0,0,false);
572 EpetraExt::MultiVectorToMatrixMarketFile("coords.dat",nCoord,0,0,false);
573 #endif
574
575 if(showTiming) {Time.ResetStartTime();}
576
577 /**********************************************************************************/
578 /************************** DIRICHLET BC SETUP ************************************/
579 /**********************************************************************************/
580
581 // Vector for use in applying BCs
582 Epetra_MultiVector v(globalMapNodes,true);
583 v.PutScalar(0.0);
584
585 int numBCNodes = bcLeftId.dimension(0) + bcTopId.dimension(0)
586 + bcRightId.dimension(0) + bcBotId.dimension(0);
587
588 int * bcNodeVec = new int [numBCNodes];
589
590 int bcNodeCount = 0;
591
592 // Loop over right boundary
593 for (int i = 0; i < bcRightId.dimension(0); i++) {
594
595 int bcNodeId = bcRightId(i);
596 bcNodeVec[bcNodeCount] = bcNodeId;
597
598 // get value of exact solution on boundary
599 double x = nodeCoords(bcNodeId,0);
600 double y = nodeCoords(bcNodeId,1);
601
602 v[0][bcRightId(i)]=1.0;
603
604 if (problem == "manufacturedSoln")
605 v[0][bcNodeId]=exactSolution(x,y);
606 if (problem == "horizAdvection")
607 v[0][bcNodeId]=0.0;
608
609 bcNodeCount ++;
610
611 } // end loop over right boundary nodes
612
613 // Loop over left boundary
614 for (int i = 0; i < bcLeftId.dimension(0); i++) {
615
616 int bcNodeId = bcLeftId(i);
617
618 bcNodeVec[bcNodeCount] = bcNodeId;
619
620 // get value of exact solution on boundary
621 double x = nodeCoords(bcNodeId,0);
622 double y = nodeCoords(bcNodeId,1);
623
624 v[0][bcNodeId]=0.0;
625
626 if (problem == "manufacturedSoln")
627 v[0][bcNodeId]=exactSolution(x,y);
628 if (problem == "horizAdvection")
629 v[0][bcNodeId]=1.0;
630
631 bcNodeCount ++;
632
633 } // end loop over left boundary nodes
634
635 // Loop over top boundary
636 for (int i = 0; i < bcTopId.dimension(0); i++) {
637
638 int bcNodeId = bcTopId(i);
639 bcNodeVec[bcNodeCount] = bcNodeId;
640
641 // get value of exact solution on boundary
642 double x = nodeCoords(bcNodeId,0);
643 double y = nodeCoords(bcNodeId,1);
644
645 v[0][bcNodeId]=0.0;
646
647 if (problem == "manufacturedSoln")
648 v[0][bcNodeId]=exactSolution(x,y);
649 if (problem == "horizAdvection")
650 v[0][bcNodeId]=1.0;
651
652 bcNodeCount ++;
653
654 } // end loop over top boundary nodes
655
656 // Loop over bottom boundary
657 for (int i = 0; i < bcBotId.dimension(0); i++) {
658
659 int bcNodeId = bcBotId(i);
660 bcNodeVec[bcNodeCount] = bcNodeId;
661
662 // get value of exact solution on boundary
663 double x = nodeCoords(bcNodeId,0);
664 double y = nodeCoords(bcNodeId,1);
665
666 v[0][bcNodeId]=0.0;
667
668 if (problem == "manufacturedSoln")
669 v[0][bcNodeId]=exactSolution(x,y);
670 if (problem == "horizAdvection")
671 v[0][bcNodeId]=1.0;
672 if (problem == "skewAdvection" && x > 0.5)
673 v[0][bcNodeId]=1.0;
674
675 bcNodeCount ++;
676
677 } // end loop over bottom boundary nodes
678
679 if(showTiming) {std::cout << "Get Dirichlet boundary values "
680 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
681
682
683 /**********************************************************************************/
684 /*********************** ASSEMBLE MATRIX AND VECTOR *******************************/
685 /**********************************************************************************/
686
687 // Define desired workset size
688 int desiredWorksetSize = 50;
689 int numWorksets = numElems/desiredWorksetSize;
690
691 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
692 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
693
694 // Loop over worksets
695 for(int workset = 0; workset < numWorksets; workset++){
696
697 // Compute cell numbers where the workset starts and ends
698 int worksetSize = 0;
699 int worksetBegin = (workset + 0)*desiredWorksetSize;
700 int worksetEnd = (workset + 1)*desiredWorksetSize;
701
702 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
703 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
704 worksetSize = worksetEnd - worksetBegin;
705
706
707 /**********************************************************************************/
708 /* Compute RHS */
709 /**********************************************************************************/
710
711 Intrepid::FieldContainer<double> worksetRHS (worksetSize, numNodesPerElem);
712
713 int cellCounter = 0;
714 for(int icell = worksetBegin; icell < worksetEnd; icell++){
715
716 // loop over nodes to compute contribution from subcontrol volumes
717 // (one subcontrol volume associated with each primary cell node)
718 for (int inode = 0; inode < numNodesPerElem; inode++) {
719 double x = volCubPoints(icell,inode,0);
720 double y = volCubPoints(icell,inode,1);
721 double source = 0;
722 if (problem == "manufacturedSoln")
723 {
724 Sacado::Fad::SFad<double,2> xfad = x;
725 Sacado::Fad::SFad<double,2> yfad = y;
726 source = sourceTerm<Sacado::Fad::SFad<double,2> >(xfad, yfad, epsilon, variableEpsilon, problem).val();
727 }
728 worksetRHS(cellCounter,inode) = source * volCubWeights(icell,inode);
729 }
730 cellCounter++;
731
732 } // end cell workset loop
733
734 // if(showTiming) {std::cout << "Compute right-hand side "
735 // << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
736
737
738 /**********************************************************************************/
739 /* Compute Diffusion, Advection, Stabilization */
740 /**********************************************************************************/
741
742 // Loop over cells to assemble diffusion, advection, and stabilization terms
743 Intrepid::FieldContainer<double> worksetDiffOp(worksetSize, numFields, numFields);
744 Intrepid::FieldContainer<double> worksetAdvOp(worksetSize, numFields, numFields);
745 Intrepid::FieldContainer<double> worksetStabOp(worksetSize, numFields, numFields);
746
747 cellCounter = 0;
748 for(int icell = worksetBegin; icell < worksetEnd; icell++){
749
750 // get subcontrol volume edge midpoints in reference frame
751 // needed for evaluation of basis function
752 Intrepid::FieldContainer<double> thisCellCoords(1,numNodesPerElem, spaceDim);
753 Intrepid::FieldContainer<double> thisRefSidePoint(numSidePoints, spaceDim);
754 Intrepid::FieldContainer<double> thiscellJacobInv(1, numSidePoints, spaceDim, spaceDim);
755 for (int idim = 0; idim < spaceDim; idim++){
756 for (int inode = 0; inode < numNodesPerElem; inode++){
757 thisCellCoords(0,inode,idim) = cellCoords(icell,inode,idim);
758 }
759 for (int ipt = 0; ipt < numSidePoints; ipt++){
760 thisRefSidePoint(ipt,idim) = refSidePoints(icell,ipt,idim);
761 for (int jdim = 0; jdim < spaceDim; jdim++){
762 thiscellJacobInv(0,ipt,idim,jdim) = cellJacobInvSide(icell,ipt,idim,jdim);
763 }
764 }
765 }
766
767 // evaluate nodal basis function gradients at subcontrol volume side midpoints
768 Intrepid::FieldContainer<double> nodeBasisGrads(numFields, numSidePoints, spaceDim);
769 HGradBasis->getValues(nodeBasisGrads, thisRefSidePoint, Intrepid::OPERATOR_GRAD);
770
771 // evaluate nodal basis function values at subcontrol volume side midpoints
772 Intrepid::FieldContainer<double> nodeBasisVals(numFields, numSidePoints);
773 HGradBasis->getValues(nodeBasisVals, thisRefSidePoint, Intrepid::OPERATOR_VALUE);
774
775 // evaluate edge basis functions at subcontrol volume side midpoints
776 Intrepid::FieldContainer<double> edgeBasisVals(numFieldsEdge, numSidePoints, spaceDim);
777 HCurlBasis->getValues(edgeBasisVals, thisRefSidePoint, Intrepid::OPERATOR_VALUE);
778
779 // transform node basis function values to physical coordinates
780 Intrepid::FieldContainer<double> nodeBasisValsTrans(1, numFields, numSidePoints);
781 Intrepid::FunctionSpaceTools::HGRADtransformVALUE<double>(nodeBasisValsTrans, nodeBasisVals);
782
783 // transform node basis function gradients to physical coordinates
784 Intrepid::FieldContainer<double> nodeBasisGradsTrans(1, numFields, numSidePoints, spaceDim);
785 Intrepid::FunctionSpaceTools::HGRADtransformGRAD<double>(nodeBasisGradsTrans, thiscellJacobInv, nodeBasisGrads);
786
787 // transform edge basis functions to physical coordinates
788 Intrepid::FieldContainer<double> edgeBasisValsTrans(1, numFieldsEdge, numSidePoints, spaceDim);
789 Intrepid::FunctionSpaceTools::HCURLtransformVALUE<double>(edgeBasisValsTrans, thiscellJacobInv,
790 edgeBasisVals);
791
792 // Get velocity and diffusivity at subcontrol volume side midpoints
793 Intrepid::FieldContainer<double> sideAdvVel(numEdgesPerElem,spaceDim);
794 Intrepid::FieldContainer<double> sideDiffusivity(numEdgesPerElem);
795 for (int iedge = 0; iedge < numEdgesPerElem; iedge++) {
796
797 double x = sideCubPoints(icell,iedge,0);
798 double y = sideCubPoints(icell,iedge,1);
799 double advVel[2];
800 advectionVelocity(advVel,x,y,problem);
801 sideAdvVel(iedge,0) = advVel[0];
802 sideAdvVel(iedge,1) = advVel[1];
803 sideDiffusivity(iedge) = diffusivity(x,y,epsilon,variableEpsilon);
804
805 }
806
807 // Assemble cell diffusion operator
808 // Number of side cubature points is equal to number of primary cell edges
809 for (int iedge = 0; iedge < numSidePoints; iedge++) {
810
811 // get local node Ids for primary cell edge
812 int rowNodeId0 = cellType->getNodeMap(1,iedge,0);
813 int rowNodeId1 = cellType->getNodeMap(1,iedge,1);
814
815 for (int inode = 0; inode < numFields; inode++){
816
817 int colNodeId = inode;
818
819 double operatorContrib0 = 0.0;
820 for (int idim = 0; idim < spaceDim; idim++){
821 operatorContrib0 += nodeBasisGradsTrans(0,inode,iedge,idim) * sideCubWeights(icell,iedge,idim);
822 }
823
824 operatorContrib0 *= sideDiffusivity(iedge);
825 double operatorContrib1 = -operatorContrib0;
826
827 worksetDiffOp(cellCounter,colNodeId,rowNodeId0) += operatorContrib1;
828 worksetDiffOp(cellCounter,colNodeId,rowNodeId1) += operatorContrib0;
829
830 }
831 }
832
833 // Assemble cell advection operator
834 for (int iedge = 0; iedge < numFieldsEdge; iedge++) {
835
836 // get local element node Ids
837 int rowNodeId0 = cellType->getNodeMap(1,iedge,0);
838 int rowNodeId1 = cellType->getNodeMap(1,iedge,1);
839
840 for (int inode = 0; inode < numFields; inode++){
841
842 int colNodeId = inode;
843
844 double operatorContrib0 = 0.0;
845 for (int idim = 0; idim < spaceDim; idim++){
846 operatorContrib0 += nodeBasisValsTrans(0,inode,iedge) * sideAdvVel(iedge,idim)
847 * sideCubWeights(icell,iedge,idim);
848 }
849
850 double operatorContrib1 = -operatorContrib0;
851
852 worksetAdvOp(cellCounter,colNodeId,rowNodeId0) += operatorContrib0;
853 worksetAdvOp(cellCounter,colNodeId,rowNodeId1) += operatorContrib1;
854
855 }
856 }
857
858 // Get edge coefficients
859 Intrepid::FieldContainer<double> edgeCoef(numFieldsEdge);
860 Intrepid::FieldContainer<double> edgeCoefOther(numFieldsEdge);
861 for (int iedge = 0; iedge < numFieldsEdge; iedge++) {
862
863 // get local element node Ids
864 int rowNodeId0 = cellType->getNodeMap(1,iedge,0);
865 int rowNodeId1 = cellType->getNodeMap(1,iedge,1);
866
867 // get coords of nodes
868 double x0 = cellCoords(icell,rowNodeId0,0); double y0 = cellCoords(icell,rowNodeId0,1);
869 double x1 = cellCoords(icell,rowNodeId1,0); double y1 = cellCoords(icell,rowNodeId1,1);
870
871 // get diffusion coefficient at nodes and average
872 double D0 = diffusivity(x0,y0,epsilon,variableEpsilon);
873 double D1 = diffusivity(x1,y1,epsilon,variableEpsilon);
874 double edgeDiffCoef = (D0 + D1)/2.0;
875
876 // get edge length and tangent
877 Intrepid::FieldContainer<double> edgeTan(spaceDim);
878 double xlen = x1-x0;
879 double ylen = y1-y0;
880 double edgeLen = sqrt(xlen*xlen + ylen*ylen);
881 edgeTan(0) = xlen/edgeLen;
882 edgeTan(1) = ylen/edgeLen;
883
884 // get average velocity and dot with tangent
885 Intrepid::FieldContainer<double> edgeVel(spaceDim);
886 double advVel0[2]; double advVel1[2];
887 advectionVelocity(advVel0,x0,y0,problem);
888 advectionVelocity(advVel1,x1,y1,problem);
889 edgeVel(0) = (advVel0[0] + advVel1[0])/2.0;
890 edgeVel(1) = (advVel0[1] + advVel1[1])/2.0;
891 double barEdgeVel = edgeVel(0)*edgeTan(0) + edgeVel(1)*edgeTan(1);
892
893 // compute edge Peclet number
894 //double edgeAlpha = barEdgeVel * edgeLen / (2.0*edgeDiffCoef);
895 double edgeAlpha = barEdgeVel * edgeLen / (edgeDiffCoef);
896
897 // compute nodal coefficients for this edge
898 double edgeCoef0 = 0.0;
899 double edgeCoef1 = edgeDiffCoef;
900 double edgeCoef2 = edgeDiffCoef;
901 double edgeCoef3 = edgeDiffCoef;
902
903
904 if (abs(edgeAlpha) > 1.0e-10) {
905 double coth = 1.0/tanh(edgeAlpha/2.0);
906 edgeCoef0 = barEdgeVel*edgeLen/2.0 * coth - edgeDiffCoef;
907 edgeCoef1 = barEdgeVel*edgeLen/2.0 * (coth);
908 edgeCoef2 = barEdgeVel*edgeLen/2.0 * (coth + 1.0);
909 edgeCoef3 = barEdgeVel*edgeLen/2.0 * (coth - 1.0);
910 }
911
912
913 if (stabilization == "type1")
914 edgeCoef(iedge) = edgeCoef0;
915 if (stabilization == "type2")
916 edgeCoef(iedge) = edgeCoef1;
917 if (stabilization == "type3")
918 {
919 edgeCoef(iedge) = edgeCoef2;
920 edgeCoefOther(iedge) = -edgeCoef3;
921 }
922
923 } // end edge loop
924
925 // TESTING THIS MAY NOT WORK
926
927 // loop over primary cell edges
928 for (int iedge = 0; iedge < numEdgesPerElem; iedge++) {
929
930 // get node Ids - these are local element node ids
931 int rowNodeId0 = cellType->getNodeMap(1,iedge,0);
932 int rowNodeId1 = cellType->getNodeMap(1,iedge,1);
933
934 // loop over subcontrol volume sides
935 for (int jedge = 0; jedge < numEdgesPerElem; jedge++) {
936
937 int colNodeId0 = cellType->getNodeMap(1,jedge,0);
938 int colNodeId1 = cellType->getNodeMap(1,jedge,1);
939
940 // get operator contributions
941 double Wdotn = 0.0;
942 for (int idim = 0; idim < spaceDim; idim++) {
943 Wdotn += edgeBasisValsTrans(0,iedge,jedge,idim)*sideCubWeights(icell,jedge,idim);
944 }
945 double operatorContrib = edgeCoef(iedge)*Wdotn;
946 double operatorContrib2 = edgeCoefOther(iedge)*Wdotn;
947
948 // sum into operator matrix
949 if (stabilization == "type1" || stabilization == "type2"){
950
951 worksetStabOp(cellCounter,colNodeId0,rowNodeId0) += operatorContrib;
952 worksetStabOp(cellCounter,colNodeId0,rowNodeId1) += -operatorContrib;
953 worksetStabOp(cellCounter,colNodeId1,rowNodeId0) += -operatorContrib;
954 worksetStabOp(cellCounter,colNodeId1,rowNodeId1) += operatorContrib;
955 }
956 if (stabilization == "type3"){
957
958 worksetStabOp(cellCounter,colNodeId0,rowNodeId0) += operatorContrib;
959 worksetStabOp(cellCounter,colNodeId0,rowNodeId1) += operatorContrib2;
960 worksetStabOp(cellCounter,colNodeId1,rowNodeId0) += -operatorContrib;
961 worksetStabOp(cellCounter,colNodeId1,rowNodeId1) += -operatorContrib2;
962 }
963
964 } // end loop over edges
965
966 } // end loop over edges
967
968 cellCounter++;
969
970 } // end workset cell loop
971
972 /**********************************************************************************/
973 /* Assemble into Global Matrix */
974 /**********************************************************************************/
975 cellCounter = 0;
976 for(int icell = worksetBegin; icell < worksetEnd; icell++){
977
978 //std::cout << "cellCounter = " << cellCounter <<", icell = " << icell <<"\n";
979 // Loop over matrix row
980 for (int cellRow = 0; cellRow < numFields; cellRow++){
981
982 int globalRow = elemToNode(icell,cellRow);
983 double sourceTermContribution = worksetRHS(cellCounter, cellRow);
984 rhsVector.SumIntoGlobalValues(1, &globalRow, &sourceTermContribution);
985
986 // Loop over matrix column
987 for (int cellCol = 0; cellCol < numFields; cellCol++){
988
989 int globalCol = elemToNode(icell,cellCol);
990
991 // TEMP - no stab.
992 // double operatorMatrixContribution = worksetDiffOp(cellCounter, cellRow, cellCol)
993 // - worksetAdvOp(cellCounter, cellRow, cellCol);
994
995
996
997 double operatorMatrixContribution = worksetStabOp(cellCounter, cellRow, cellCol);
998
999 if (stabilization == "type2" || stabilization == "type1" ){
1000 operatorMatrixContribution += -worksetAdvOp(cellCounter, cellRow, cellCol);
1001 }
1002
1003 if (stabilization == "type1" ){
1004 operatorMatrixContribution += worksetDiffOp(cellCounter, cellRow, cellCol);
1005 }
1006
1007
1008
1009 OpMatrix.InsertGlobalValues(1, &globalRow, 1, &globalCol, &operatorMatrixContribution);
1010
1011 }// end cell col loop
1012
1013 }// end cell row loop
1014
1015 cellCounter++;
1016
1017 } // end workset cell loop
1018
1019 } // end loop over worksets
1020
1021
1022 /**********************************************************************************/
1023 /* Assemble Global Matrix */
1024 /**********************************************************************************/
1025
1026 OpMatrix.GlobalAssemble();
1027 OpMatrix.FillComplete();
1028 rhsVector.GlobalAssemble();
1029
1030 if(showTiming) {std::cout << "Global assembly "
1031 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1032
1033
1034 /**********************************************************************************/
1035 /************************ ADJUST MATRIX AND RHS FOR BCs ***************************/
1036 /**********************************************************************************/
1037
1038 // Apply stiffness matrix to v
1039 Epetra_MultiVector rhsDir(globalMapNodes,true);
1040 OpMatrix.Apply(v,rhsDir);
1041
1042 // Update right-hand side
1043 rhsVector.Update(-1.0,rhsDir,1.0);
1044
1045 // Loop over boundary nodes and replace rhs values with boundary values
1046 for (int i = 0; i < numBCNodes; i++) {
1047
1048 int bcNodeId = bcNodeVec[i];
1049
1050 rhsVector[0][bcNodeId]=v[0][bcNodeId];
1051
1052 } // end loop over boundary nodes
1053
1054 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1055 // and add one to diagonal.
1056 ML_Epetra::Apply_OAZToMatrix(bcNodeVec, numBCNodes, OpMatrix);
1057
1058 //delete [] bcNodeVec;
1059
1060 if(showTiming) {std::cout << "Adjust global matrix and rhs due to BCs " << Time.ElapsedTime()
1061 << " sec \n"; Time.ResetStartTime();}
1062
1063
1064 #ifdef DUMP_DATA
1065 // Dump matrices to disk
1066 EpetraExt::RowMatrixToMatlabFile("op_matrix_cvfem.dat",OpMatrix);
1067 EpetraExt::MultiVectorToMatrixMarketFile("rhs_vector_cvfem.dat",rhsVector,0,0,false);
1068 #endif
1069
1070 /**********************************************************************************/
1071 /*********************************** SOLVE ****************************************/
1072 /**********************************************************************************/
1073
1074 // Build ML preconditioner
1075 Teuchos::ParameterList MLList;
1076 ML_Epetra::SetDefaults("SA",MLList);
1077 MLList.set("ML output",1);
1078 //MLList.set("max levels",10);
1079 MLList.set("max levels",1);
1080 MLList.set("coarse: type","Amesos-KLU");
1081 MLList.set("smoother: type","ILU");
1082 MLList.set("smoother: sweeps",2);
1083 MLList.set("coarse: max size",1000);
1084 ML_Epetra::MultiLevelPreconditioner *MLPrec = new ML_Epetra::MultiLevelPreconditioner(OpMatrix, MLList, true);
1085
1086 // Solve
1087 Epetra_MultiVector x(rhsVector);
1088 x.PutScalar(0.0);
1089
1090 Epetra_LinearProblem Problem(&OpMatrix,&x,&rhsVector);
1091 Epetra_MultiVector* lhs = Problem.GetLHS();
1092
1093 AztecOO solver(Problem);
1094 solver.SetPrecOperator(MLPrec);
1095 solver.SetAztecOption(AZ_solver, AZ_gmres);
1096 solver.SetAztecOption(AZ_output, 1);
1097 solver.Iterate(100, 1e-10);
1098
1099 #ifdef DUMP_DATA
1100 EpetraExt::MultiVectorToMatrixMarketFile("soln_vector_cvfem.dat",*lhs,0,0,false);
1101 #endif
1102
1103 delete MLPrec;
1104
1105 if(showTiming) {std::cout << "Solve linear system " << Time.ElapsedTime()
1106 << " sec \n"; Time.ResetStartTime();}
1107
1108
1109 /**********************************************************************************/
1110 /**************************** CALCULATE ERROR *************************************/
1111 /**********************************************************************************/
1112
1113 if (problem == "manufacturedSoln") // perform error calculation
1114 {
1115
1116 if (showTiming) {Time.ResetStartTime();}
1117
1118 double L2err = 0.0;
1119 double L2errTot = 0.0;
1120 double H1err = 0.0;
1121 double H1errTot = 0.0;
1122 double Linferr = 0.0;
1123 double LinferrTot = 0.0;
1124
1125 /*
1126 // NOTE: If using multiple processors need to import solution for error calculation !!
1127 // Import solution onto current processor
1128 // FIXME - not efficient
1129 int numNodesGlobal = globalMapNodes.NumGlobalElements();
1130 Epetra_Map solnMap(numNodesGlobal, numNodesGlobal, 0, Comm);
1131 Epetra_Import solnImporter(solnMap, globalMapNodes);
1132 Epetra_Vector uCoeff(solnMap);
1133 uCoeff.Import(*lhs, solnImporter, Insert);
1134 */
1135 // Get cubature points and weights for error calc (may be different from previous)
1136 Intrepid::DefaultCubatureFactory<double> cubFactoryErr;
1137 int cubDegErr = 3;
1138 Teuchos::RCP<Intrepid::Cubature<double> > cellCubatureErr = cubFactoryErr.create(*cellType, cubDegErr);
1139 int cubDimErr = cellCubatureErr->getDimension();
1140 int numCubPointsErr = cellCubatureErr->getNumPoints();
1141 Intrepid::FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
1142 Intrepid::FieldContainer<double> cubWeightsErr(numCubPointsErr);
1143 cellCubatureErr->getCubature(cubPointsErr, cubWeightsErr);
1144
1145 // Evaluate basis values and gradients at cubature points
1146 Intrepid::FieldContainer<double> basisValsErr(numFields, numCubPointsErr);
1147 Intrepid::FieldContainer<double> basisGradsErr(numFields, numCubPointsErr, spaceDim);
1148 HGradBasis->getValues(basisValsErr, cubPointsErr, Intrepid::OPERATOR_VALUE);
1149 HGradBasis->getValues(basisGradsErr, cubPointsErr, Intrepid::OPERATOR_GRAD);
1150
1151 // Loop over worksets
1152 for (int workset = 0; workset < numWorksets; workset++){
1153
1154 // compute cell numbers where the workset starts and ends
1155 int worksetSize = 0;
1156 int worksetBegin = (workset + 0)*desiredWorksetSize;
1157 int worksetEnd = (workset + 1)*desiredWorksetSize;
1158
1159 // when numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1160 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1161 worksetSize = worksetEnd - worksetBegin;
1162
1163 // loop over cells to fill arrays with coordinates and discrete solution coefficient
1164 Intrepid::FieldContainer<double> approxSolnCoef(worksetSize, numNodesPerElem);
1165 Intrepid::FieldContainer<double> cellWorksetErr(worksetSize, numNodesPerElem, spaceDim);
1166
1167 int cellCounter = 0;
1168 // loop over workset cells and fill arrays with approximate solution
1169 for(int icell = worksetBegin; icell < worksetEnd; icell++){
1170
1171 for (int inode = 0; inode < numNodesPerElem; inode++) {
1172
1173 int rowIndex = elemToNode(icell,inode);
1174 approxSolnCoef(cellCounter, inode) = (*lhs).Values()[rowIndex];
1175 cellWorksetErr(cellCounter, inode, 0) = nodeCoords(elemToNode(icell,inode),0);
1176 cellWorksetErr(cellCounter, inode, 1) = nodeCoords(elemToNode(icell,inode),1);
1177 }
1178 cellCounter++;
1179 }
1180
1181 // Containers for Jacobian
1182 Intrepid::FieldContainer<double> worksetJacobianE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1183 Intrepid::FieldContainer<double> worksetJacobInvE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
1184 Intrepid::FieldContainer<double> worksetJacobDetE(worksetSize, numCubPointsErr);
1185 Intrepid::FieldContainer<double> worksetCubWeightsE(worksetSize, numCubPointsErr);
1186
1187 // Containers for basis values and gradients in physical space
1188 Intrepid::FieldContainer<double> basisValsErrTrans(worksetSize, numFields, numCubPointsErr);
1189 Intrepid::FieldContainer<double> basisGradsErrTrans(worksetSize, numFields, numCubPointsErr, spaceDim);
1190
1191 // compute cell Jacobians, their inverses and their determinants
1192 Intrepid::CellTools<double>::setJacobian(worksetJacobianE, cubPointsErr, cellWorksetErr, *cellType);
1193 Intrepid::CellTools<double>::setJacobianInv(worksetJacobInvE, worksetJacobianE );
1194 Intrepid::CellTools<double>::setJacobianDet(worksetJacobDetE, worksetJacobianE );
1195
1196 // map cubature points to physical frame
1197 Intrepid::FieldContainer<double> worksetCubPointsErr(worksetSize, numCubPointsErr, cubDimErr);
1198 Intrepid::CellTools<double>::mapToPhysicalFrame(worksetCubPointsErr, cubPointsErr, cellWorksetErr, *cellType);
1199
1200 // evaluate exact solution and gradient at cubature points
1201 Intrepid::FieldContainer<double> worksetExactSoln(worksetSize, numCubPointsErr);
1202 Intrepid::FieldContainer<double> worksetExactSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1203 evaluateExactSolution(worksetExactSoln, worksetCubPointsErr);
1204 evaluateExactSolutionGrad(worksetExactSolnGrad, worksetCubPointsErr);
1205
1206 // transform basis values to physical coordinates
1207 Intrepid::FunctionSpaceTools::HGRADtransformVALUE<double>(basisValsErrTrans, basisValsErr);
1208 Intrepid::FunctionSpaceTools::HGRADtransformGRAD<double>(basisGradsErrTrans, worksetJacobInvE, basisGradsErr);
1209
1210 // compute weighted measure
1211 Intrepid::FunctionSpaceTools::computeCellMeasure<double>(worksetCubWeightsE, worksetJacobDetE, cubWeightsErr);
1212
1213 // evaluate the approximate solution and gradient at cubature points
1214 Intrepid::FieldContainer<double> worksetApproxSoln(worksetSize, numCubPointsErr);
1215 Intrepid::FieldContainer<double> worksetApproxSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1216 Intrepid::FunctionSpaceTools::evaluate<double>(worksetApproxSoln, approxSolnCoef, basisValsErrTrans);
1217 Intrepid::FunctionSpaceTools::evaluate<double>(worksetApproxSolnGrad, approxSolnCoef, basisGradsErrTrans);
1218
1219 // get difference between approximate and exact solutions
1220 Intrepid::FieldContainer<double> worksetDeltaSoln(worksetSize, numCubPointsErr);
1221 Intrepid::FieldContainer<double> worksetDeltaSolnGrad(worksetSize, numCubPointsErr, spaceDim);
1222 Intrepid::RealSpaceTools<double>::subtract(worksetDeltaSoln, worksetApproxSoln, worksetExactSoln);
1223 Intrepid::RealSpaceTools<double>::subtract(worksetDeltaSolnGrad, worksetApproxSolnGrad, worksetExactSolnGrad);
1224
1225 // take absolute values
1226 Intrepid::RealSpaceTools<double>::absval(worksetDeltaSoln);
1227 Intrepid::RealSpaceTools<double>::absval(worksetDeltaSolnGrad);
1228
1229 // apply cubature weights to differences in values and grads for use in integration
1230 Intrepid::FieldContainer<double> worksetDeltaSolnWeighted(worksetSize, numCubPointsErr);
1231 Intrepid::FieldContainer<double> worksetDeltaSolnGradWeighted(worksetSize, numCubPointsErr, spaceDim);
1232 Intrepid::FunctionSpaceTools::scalarMultiplyDataData<double>(worksetDeltaSolnWeighted,
1233 worksetCubWeightsE, worksetDeltaSoln);
1234 Intrepid::FunctionSpaceTools::scalarMultiplyDataData<double>(worksetDeltaSolnGradWeighted,
1235 worksetCubWeightsE, worksetDeltaSolnGrad);
1236
1237 // integrate to get errors on each element
1238 Intrepid::FieldContainer<double> worksetL2err(worksetSize);
1239 Intrepid::FieldContainer<double> worksetH1err(worksetSize);
1240 Intrepid::FunctionSpaceTools::integrate<double>(worksetL2err, worksetDeltaSoln,
1241 worksetDeltaSolnWeighted, Intrepid::COMP_BLAS);
1242 Intrepid::FunctionSpaceTools::integrate<double>(worksetH1err, worksetDeltaSolnGrad,
1243 worksetDeltaSolnGradWeighted, Intrepid::COMP_BLAS);
1244
1245 // loop over cells to get errors for total workset
1246 cellCounter = 0;
1247 for(int icell = worksetBegin; icell < worksetEnd; icell++){
1248
1249 // loop over cubature points
1250 for(int nPt = 0; nPt < numCubPointsErr; nPt++){
1251 Linferr = std::max(Linferr, worksetDeltaSoln(cellCounter,nPt));
1252 }
1253
1254 L2err += worksetL2err(cellCounter);
1255 H1err += worksetH1err(cellCounter);
1256
1257 cellCounter++;
1258
1259 } // end workset cell loop
1260
1261 } // end loop over worksets
1262
1263
1264
1265 #ifdef HAVE_MPI
1266 // sum over all processors
1267 Comm.SumAll(&L2err,&L2errTot,1);
1268 Comm.SumAll(&H1err,&H1errTot,1);
1269 Comm.MaxAll(&Linferr,&LinferrTot,1);
1270 #else
1271 L2errTot = L2err;
1272 H1errTot = H1err;
1273 LinferrTot = Linferr;
1274 #endif
1275
1276 if (MyPID == 0) {
1277 std::cout << "\n";
1278 std::cout << " L2 Error: " << sqrt(L2errTot) <<"\n";
1279 std::cout << " H1 Error: " << sqrt(H1errTot) <<"\n";
1280 std::cout << " LInf Error: " << LinferrTot <<"\n\n";
1281 }
1282
1283
1284 if(showTiming) {std::cout << "Calculate error "
1285 << Time.ElapsedTime() << " s \n"; Time.ResetStartTime();}
1286
1287 } // end if problem == manufacturedSoln
1288
1289
1290 return 0;
1291
1292 }
1293 /**********************************************************************************/
1294 /********************************* END MAIN ***************************************/
1295 /**********************************************************************************/
1296
1297
1298 /**********************************************************************************/
1299 /********************** USER DEFINED FUNCTIONS FOR TEST ***************************/
1300 /**********************************************************************************/
1301
1302 template<typename Scalar>
1303 const Scalar exactSolution(const Scalar& x, const Scalar& y) {
1304
1305 //return x + y;
1306 return x*x*x - y*y;
1307
1308 }
1309
1310 template<typename Scalar>
1311 void advectionVelocity(Scalar advVel[2], const Scalar& x, const Scalar& y, const std::string problem) {
1312
1313 advVel[0] = 0;
1314 advVel[1] = 0;
1315
1316 if (problem == "horizAdvection"){
1317 advVel[0] = 1.0;
1318 advVel[1] = 0.0;
1319 }
1320
1321 if (problem == "skewAdvection" || problem == "manufacturedSoln"){
1322 advVel[0] = -sin(M_PI/6);
1323 advVel[1] = cos(M_PI/6);
1324 }
1325
1326 if (problem == "doubleGlazing"){
1327 advVel[0] = 2.0*(2.0*y-1.0)*(1.0-(2.0*x - 1.0)*(2.0*x - 1.0));
1328 advVel[1] = -2.0*(2.0*x-1.0)*(1.0-(2.0*y - 1.0)*(2.0*y - 1.0));
1329 }
1330
1331 }
1332
1333 template<typename Scalar1, typename Scalar2>
1334 const Scalar1 diffusivity(const Scalar1& x, const Scalar1& y, const Scalar2& epsilon, const bool variableEpsilon) {
1335
1336 Scalar1 D = epsilon;
1337 if (variableEpsilon) {
1338
1339 // Variable diffusion coefficient
1340 D = 0.5*epsilon*sin(M_PI*x)*cos(M_PI*y) + epsilon;
1341
1342 }
1343
1344 return D;
1345
1346 }
1347
1348
1349 /**********************************************************************************/
1350 /***************** AUXILIARY FUNCTIONS FROM USER DEFINED **************************/
1351 /**********************************************************************************/
1352
1353 /************ Grad of Exact Solution ****************/
1354 template<typename Scalar>
1355 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y) {
1356
1357 // To enable derivatives of the gradient (i.e., 2nd derivatives of the exact solution) need 2 levels of fad types
1358 Sacado::Fad::SFad<Scalar,2> fad_x = x;
1359 Sacado::Fad::SFad<Scalar,2> fad_y = y;
1360 Sacado::Fad::SFad<Scalar,2> u;
1361
1362 // Indicate the independent variables
1363 fad_x.diff(0,2);
1364 fad_y.diff(1,2);
1365
1366 u = exactSolution(fad_x, fad_y);
1367
1368 gradExact[0] = u.dx(0);
1369 gradExact[1] = u.dx(1);
1370 }
1371
1372 /************ Source Term (RHS) ****************/
1373 template<typename Scalar1, typename Scalar2>
1374 const Scalar1 sourceTerm(Scalar1& x, Scalar1& y, Scalar2& epsilon,
1375 bool variableEpsilon, std::string problem) {
1376
1377 Scalar1 phi;
1378 Scalar1 D;
1379 Scalar1 u[2];
1380 Scalar1 grad_phi[2];
1381 Scalar1 flux[2];
1382 Scalar1 f = 0.;
1383
1384 // Indicate the independent variables
1385 x.diff(0,2);
1386 y.diff(1,2);
1387
1388 // Get exact solution and its gradient
1389 phi = exactSolution(x, y);
1390 exactSolutionGrad(grad_phi, x, y);
1391
1392 // Get diffusivity
1393 D = diffusivity(x,y,epsilon,variableEpsilon);
1394
1395 // Get advection velocity
1396 advectionVelocity(u, x, y, problem);
1397
1398 // Compute total flux = J_n = epsilon grad phi - u phi
1399 for(int i = 0; i < 2; i++){
1400 flux[i] = D * grad_phi[i] - phi * u[i];
1401 }
1402
1403 // Compute source term (right hand side): f = -div J_n
1404 f = -(flux[0].dx(0) + flux[1].dx(1));
1405
1406 return f;
1407 }
1408
1409 /**********************************************************************************/
1410 /*************************** EVALUATION METHODS ***********************************/
1411 /**********************************************************************************/
1412
1413 /************ Exact Solution ****************/
1414 template<class ArrayOut, class ArrayIn>
1415 void evaluateExactSolution(ArrayOut & exactSolutionValues,
1416 const ArrayIn & evaluationPoints){
1417
1418 int numWorksetCells = evaluationPoints.dimension(0);
1419 int numPoints = evaluationPoints.dimension(1);
1420
1421 for(int cell = 0; cell < numWorksetCells; cell++){
1422 for(int pt = 0; pt < numPoints; pt++){
1423
1424 double x = evaluationPoints(cell, pt, 0);
1425 double y = evaluationPoints(cell, pt, 1);
1426
1427 exactSolutionValues(cell, pt) = exactSolution<double>(x, y);
1428 }
1429 }
1430 }
1431
1432
1433 /************ Grad of Exact Solution ****************/
1434 template<class ArrayOut, class ArrayIn>
1435 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
1436 const ArrayIn & evaluationPoints){
1437
1438 int numWorksetCells = evaluationPoints.dimension(0);
1439 int numPoints = evaluationPoints.dimension(1);
1440 int spaceDim = evaluationPoints.dimension(2);
1441
1442 double gradient[2];
1443
1444 for(int cell = 0; cell < numWorksetCells; cell++){
1445 for(int pt = 0; pt < numPoints; pt++){
1446
1447 double x = evaluationPoints(cell, pt, 0);
1448 double y = evaluationPoints(cell, pt, 1);
1449
1450 exactSolutionGrad<double>(gradient, x, y);
1451
1452 for(int row = 0; row < spaceDim; row++){
1453 exactSolutionGradValues(cell, pt, row) = gradient[row];
1454 }
1455 }
1456 }
1457 }
1458
1459 /**********************************************************************************/
1460 /****************************** CREATE MESH ***************************************/
1461 /**********************************************************************************/
1462
1463 template<class ArrayOut1, class ArrayOut2, class Scalar>
1464 void createMesh(ArrayOut1 & elemToNode, ArrayOut2 & nodeCoords,
1465 ArrayOut1 & bcLeftId, ArrayOut1 & bcRightId,
1466 ArrayOut1 & bcTopId, ArrayOut1 & bcBotId,
1467 const std::string & meshType, const Scalar & meshSize){
1468
1469 int spaceDim = 2;
1470
1471 // Create regular quadrilateral mesh on square domain [0,1]x[0,1]
1472 if (meshType == "quad")
1473 {
1474 int numElems = meshSize*meshSize;
1475 int numNodes = (meshSize+1)*(meshSize+1);
1476 int numNodesPerElem = 4;
1477
1478 nodeCoords.resize(numNodes,spaceDim);
1479 elemToNode.resize(numElems,numNodesPerElem);
1480
1481 double hx = 1.0/((double)meshSize);
1482 int nx = meshSize;
1483
1484 int ielem = 0;
1485 for (int j=0; j<nx; j++){
1486 for (int i=0; i<nx; i++){
1487
1488 int inode0 = (nx+1)*(j) + i;
1489 int inode1 = (nx+1)*(j) + i+1;
1490 int inode2 = (nx+1)*(j+1) + i+1;
1491 int inode3 = (nx+1)*(j+1) + i;
1492
1493 nodeCoords(inode0,0) = (double)i*hx;
1494 nodeCoords(inode0,1) = (double)j*hx;
1495 nodeCoords(inode1,0) = (double)(i+1)*hx;
1496 nodeCoords(inode1,1) = (double)j*hx;
1497 nodeCoords(inode2,0) = (double)(i+1)*hx;
1498 nodeCoords(inode2,1) = (double)(j+1)*hx;
1499 nodeCoords(inode3,0) = (double)i*hx;
1500 nodeCoords(inode3,1) = (double)(j+1)*hx;
1501
1502 elemToNode(ielem,0) = inode0;
1503 elemToNode(ielem,1) = inode1;
1504 elemToNode(ielem,2) = inode2;
1505 elemToNode(ielem,3) = inode3;
1506
1507 ielem++;
1508 }
1509 }
1510
1511 }
1512 // Create regular triangular mesh on square domain [0,1]x[0,1]
1513 else if (meshType == "tri")
1514 {
1515 int numElems = 2*meshSize*meshSize;
1516 int numNodes = (meshSize+1)*(meshSize+1);
1517 int numNodesPerElem = 3;
1518
1519 nodeCoords.resize(numNodes,spaceDim);
1520 elemToNode.resize(numElems,numNodesPerElem);
1521
1522 double hx = 1.0/((double)meshSize);
1523 int nx = meshSize;
1524
1525 // loop over quads and create two triangles for each quad
1526 // _________
1527 // | /|
1528 // | / |
1529 // | / |
1530 // | / |
1531 // |/________|
1532 //
1533 int ielem = 0;
1534 for (int j=0; j<nx; j++){
1535 for (int i=0; i<nx; i++){
1536
1537 int inode0 = (nx+1)*(j) + i;
1538 int inode1 = (nx+1)*(j) + i+1;
1539 int inode2 = (nx+1)*(j+1) + i;
1540
1541 int inode3 = (nx+1)*(j+1) + i;
1542 int inode4 = (nx+1)*(j) + i+1;
1543 int inode5 = (nx+1)*(j+1) + i+1;
1544
1545 nodeCoords(inode0,0) = (double)i*hx;
1546 nodeCoords(inode0,1) = (double)j*hx;
1547 nodeCoords(inode1,0) = (double)(i+1)*hx;
1548 nodeCoords(inode1,1) = (double)j*hx;
1549 nodeCoords(inode2,0) = (double)i*hx;
1550 nodeCoords(inode2,1) = (double)(j+1)*hx;
1551
1552 nodeCoords(inode3,0) = (double)i*hx;
1553 nodeCoords(inode3,1) = (double)(j+1)*hx;
1554 nodeCoords(inode4,0) = (double)(i+1)*hx;
1555 nodeCoords(inode4,1) = (double)j*hx;
1556 nodeCoords(inode5,0) = (double)(i+1)*hx;
1557 nodeCoords(inode5,1) = (double)(j+1)*hx;
1558
1559 elemToNode(ielem,0) = (nx+1)*j + i;
1560 elemToNode(ielem,1) = (nx+1)*j + i+1;
1561 elemToNode(ielem,2) = (nx+1)*(j+1) + i;
1562
1563 elemToNode(ielem+1,0) = (nx+1)*(j+1) + i;
1564 elemToNode(ielem+1,1) = (nx+1)*j + i+1;
1565 elemToNode(ielem+1,2) = (nx+1)*(j+1) + i+1;
1566
1567 ielem+=2;
1568 }
1569 }
1570
1571 }
1572
1573
1574 // Fill boundary arrays
1575 bcLeftId.resize(meshSize);
1576 bcRightId.resize(meshSize);
1577 bcTopId.resize(meshSize);
1578 bcBotId.resize(meshSize);
1579
1580 // For this square grid each boundary has meshSize nodes
1581 // (the left corner of each boundary belongs to that boundary)
1582 int nx = meshSize;
1583 for (int ibcnode = 0; ibcnode < nx; ibcnode++){
1584
1585 bcBotId(ibcnode) = ibcnode;
1586 bcTopId(ibcnode) = (nx+1)*nx + ibcnode + 1;
1587 bcLeftId(ibcnode) = (nx+1)*(ibcnode+1);
1588 bcRightId(ibcnode) = (nx+1)*(ibcnode) + nx;
1589
1590 }
1591
1592 }
1593
1594 /**********************************************************************************/
1595 /************************************** END ***************************************/
1596 /**********************************************************************************/