Debian Codegraph @

packages/trilinoscouplings/examples/scaling/example_Poisson2D_pn.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_Poisson.cpp
11 \brief Example solution of a Poisson equation on a quad mesh using
12 nodal (Hgrad) elements.
13
14 This example uses the following Trilinos packages:
15 \li Pamgen to generate a Quad mesh.
16 \li Sacado to form the source term from user-specified manufactured solution.
17 \li Intrepid to build the discretization matrix and right-hand side.
18 \li Epetra to handle the global matrix and vector.
19 \li Isorropia to partition the matrix. (Optional)
20 \li ML to solve the linear system.
21
22
23 \verbatim
24
25 Poisson system:
26
27 div A grad u = f in Omega
28 u = g on Gamma
29
30 where
31 A is a symmetric, positive definite material tensor
32 f is a given source term
33
34 Corresponding discrete linear system for nodal coefficients(x):
35
36 Kx = b
37
38 K - HGrad stiffness matrix
39 b - right hand side vector
40
41 \endverbatim
42
43 \author Created by P. Bochev, D. Ridzal, K. Peterson, D. Hensinger, C. Siefert.
44
45 \remark Usage:
46 \code ./TrilinosCouplings_examples_scaling_example_Poisson.exe \endcode
47
48 \remark Example driver requires input file named Poisson2D.xml with Pamgen
49 formatted mesh description and settings for Isorropia (a version
50 is included in the Trilinos repository with this driver).
51
52 \remark The exact solution (u) and material tensor (A) are set in the
53 functions "exactSolution" and "materialTensor" and may be
54 modified by the user.
55
56 */
57
58 /*** Uncomment if you would like output data for plotting ***/
59 //#define DUMP_DATA
60 //#define DUMP_DATA_COORD
61 /**************************************************************/
62 /* Includes */
63 /**************************************************************/
64
65 // TrilinosCouplings includes
66 #include "TrilinosCouplings_config.h"
67 #include "TrilinosCouplings_Pamgen_Utils.hpp"
68
69 // Intrepid includes
70 #include "Intrepid_FunctionSpaceTools.hpp"
71 #include "Intrepid_CellTools.hpp"
72 #include "Intrepid_ArrayTools.hpp"
73 #include "Intrepid_HGRAD_QUAD_Cn_FEM.hpp"
74 #include "Intrepid_HGRAD_QUAD_C2_FEM.hpp"
75 #include "Intrepid_HGRAD_QUAD_C1_FEM.hpp"
76 #include "Intrepid_RealSpaceTools.hpp"
77 #include "Intrepid_DefaultCubatureFactory.hpp"
78 #include "Intrepid_Utils.hpp"
79
80 // Epetra includes
81 #include "Epetra_Time.h"
82 #include "Epetra_Map.h"
83 #ifdef HAVE_MPI
84 #include "Epetra_MpiComm.h"
85 #else
86 #include "Epetra_SerialComm.h"
87 #endif
88 #include "Epetra_FECrsMatrix.h"
89 #include "Epetra_FEVector.h"
90 #include "Epetra_Import.h"
91
92 // Teuchos includes
93 #include "Teuchos_oblackholestream.hpp"
94 #include "Teuchos_RCP.hpp"
95 #include "Teuchos_BLAS.hpp"
96 #include "Teuchos_GlobalMPISession.hpp"
97 #include "Teuchos_XMLParameterListHelpers.hpp"
98
99 // Shards includes
100 #include "Shards_CellTopology.hpp"
101
102 // EpetraExt includes
103 #include "EpetraExt_RowMatrixOut.h"
104 #include "EpetraExt_MultiVectorOut.h"
105
106 // Pamgen includes
107 #include "create_inline_mesh.h"
108 #include "pamgen_im_exodusII_l.h"
109 #include "pamgen_im_ne_nemesisI_l.h"
110 #include "pamgen_extras.h"
111
112 // AztecOO includes
113 #include "AztecOO.h"
114
115 // ML Includes
116 #include "ml_MultiLevelPreconditioner.h"
117
118 #ifdef HAVE_INTREPID_KOKKOS
119 #include "Sacado.hpp"
120 #else
121 // Sacado includes
122 #include "Sacado_No_Kokkos.hpp"
123 #endif
124
125 #include <sstream>
126
127
128 #if defined(HAVE_TRILINOSCOUPLINGS_MUELU)
129 #include "MueLu_IntrepidPCoarsenFactory.hpp"
130 #endif
131
132 using namespace std;
133 using namespace Intrepid;
134
135
136 // for debugging
137 #define zwrap(x) (std::abs(x)<1e-10 ? 0.0 : x)
138
139 /*********************************************************/
140 /* Typedefs */
141 /*********************************************************/
142 typedef Sacado::Fad::SFad<double,2> Fad2; //# ind. vars fixed at 2
143 typedef Intrepid::FunctionSpaceTools IntrepidFSTools;
144 typedef Intrepid::RealSpaceTools<double> IntrepidRSTools;
145 typedef Intrepid::CellTools<double> IntrepidCTools;
146
147
148 struct fecomp{
149 bool operator () ( topo_entity* x, topo_entity* y )const
150 {
151 if(x->sorted_local_node_ids < y->sorted_local_node_ids)return true;
152 return false;
153 }
154 };
155
156
157 int global_MyPID;//DEBUG
158
159 #if 0
160 long long *nodes_per_element = new long long [numElemBlk];
161 long long *element_attributes = new long long [numElemBlk];
162 long long *elements = new long long [numElemBlk];
163 char **element_types = new char * [numElemBlk];
164 long long **elmt_node_linkage = new long long * [numElemBlk];
165 #endif
166
167
168 //elements,nodes_per_element,elmt_node_linkage,numElemBlk,
169 struct PamgenMesh{
170 int dim;
171
172 /* Mesh connectivity info */
173 long long numElemBlk;
174 std::vector<long long> nodes_per_element;
175 std::vector<long long> element_attributes;
176 std::vector<long long> elements;
177 std::vector<std::vector<char> > element_types;
178 std::vector<std::vector<long long> >elmt_node_linkage;
179
180 /* Communicator info */
181 std::vector<long long> node_comm_proc_ids;
182 std::vector<long long> node_cmap_node_cnts;
183 std::vector<long long> node_cmap_ids;
184 std::vector<long long*> comm_node_ids;
185 std::vector<std::vector<long long> > comm_node_proc_ids;
186 long long num_node_comm_maps;
187
188 PamgenMesh(int mydim):dim(mydim){}
189 ~PamgenMesh() {
190 for(int i=0;i<(int)comm_node_ids.size(); i++)
191 delete [] comm_node_ids[i];
192 }
193
194
195 void allocateConnectivity(long long my_numElemBlk) {
196 numElemBlk = my_numElemBlk;
197 nodes_per_element.resize(numElemBlk);
198 element_attributes.resize(numElemBlk);
199 elements.resize(numElemBlk);
200 element_types.resize(numElemBlk);
201 elmt_node_linkage.resize(numElemBlk);
202 }
203
204
205
206 };
207
208
209
210 // forward declarations
211 void PromoteMesh_Pn_Kirby(const int degree, const EPointType & pointType,long long P1_globalNumNodes,long long P1_globalNumEdges,long long P1_globalNumElem,
212 const FieldContainer<int> & P1_elemToNode,
213 const FieldContainer<double> & P1_nodeCoord,
214 const FieldContainer<double> & P1_edgeCoord,
215 const FieldContainer<int> & P1_elemToEdge,
216 const FieldContainer<int> & P1_elemToEdgeOrient,
217 const FieldContainer<int> & P1_nodeOnBoundary,
218 const bool* P1_nodeIsOwned,
219 const std::vector<bool> & P1_edgeIsOwned,
220 const std::vector<long long> & P1_globalNodeIds,
221 const std::vector<long long> & P1_globalEdgeIds,
222 const std::vector<long long> & P1_globalElementIds,
223 long long & Pn_globalNumNodes,
224 FieldContainer<int> & Pn_elemToNode,
225 FieldContainer<double> & Pn_nodeCoord,
226 FieldContainer<int> & Pn_nodeOnBoundary,
227 std::vector<bool> & Pn_nodeIsOwned,
228 std::vector<long long> & Pn_globalNodeIds);
229
230
231 void PamgenEnumerateEdges(int numNodesPerElem, int numEdgesPerElem, int numNodesPerEdge,
232 FieldContainer<int> refEdgeToNode,const FieldContainer<double> & nodeCoord,
233 std::vector<long long> globalNodeIds,
234 PamgenMesh & mesh,
235 Epetra_Comm & Comm,
236 /*Output args */
237 std::vector<long long> & globalEdgeIds,
238 std::vector<bool> & edgeIsOwned,
239 std::vector<int> & ownedEdgeIds,
240 FieldContainer<int> &elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<int> &edgeToNode,FieldContainer<double> & edgeCoord,
241 long long & numEdgesGlobal);
242
243 void EnumerateElements(Epetra_Comm & Comm, int numMyElements, std::vector<long long> & globalElementIds);
244
245 void CreateP1MeshFromP2Mesh(const FieldContainer<int> & P2_elemToNode, FieldContainer<int> &aux_P1_elemToNode);
246
247 void CreateLinearSystem(int numWorkSets,
248 int desiredWorksetSize,
249 FieldContainer<int> const &elemToNode,
250 FieldContainer<double> const &nodeCoord,
251 FieldContainer<double> const &cubPoints,
252 FieldContainer<double> const &cubWeights,
253 Teuchos::RCP<Basis<double,FieldContainer<double> > > &myBasis_rcp,
254 FieldContainer<double> const &HGBGrads,
255 FieldContainer<double> const &HGBValues,
256 std::vector<long long> const &globalNodeIds,
257 Epetra_FECrsMatrix &StiffMatrix,
258 Epetra_FEVector &rhsVector,
259 std::string &msg,
260 Epetra_Time &Time
261 );
262
263
264 void GenerateLinearCoarsening_pn_kirby_to_p1(const int degree,const FieldContainer<int> & Pn_elemToNode, const std::vector<bool> & Pn_nodeIsOwned, Teuchos::RCP<Basis_HGRAD_QUAD_Cn_FEM<double,FieldContainer<double> > > &PnBasis_rcp,Teuchos::RCP<Basis<double,FieldContainer<double> > > &P1Basis_rcp,Epetra_Map & P1_map, Epetra_Map & Pn_map,Teuchos::RCP<Epetra_CrsMatrix>& P);
265
266 void GenerateIdentityCoarsening_pn_to_p1(const FieldContainer<int> & Pn_elemToNode,
267 Epetra_Map const & P1_map_aux, Epetra_Map const &Pn_map,
268 Teuchos::RCP<Epetra_CrsMatrix> & I);
269
270 void Apply_Dirichlet_BCs(std::vector<int> BCNodes, Epetra_FECrsMatrix & A, Epetra_MultiVector & x, Epetra_MultiVector & b, const Epetra_MultiVector & soln);
271
272 /**********************************************************************************/
273 /***************** FUNCTION DECLARATION FOR ML PRECONDITIONER *********************/
274 /**********************************************************************************/
275
276 /** \brief ML Preconditioner
277
278 \param ProblemType [in] problem type
279 \param MLList [in] ML parameter list
280 \param A [in] discrete operator matrix
281 \param xexact [in] exact solution
282 \param b [in] right-hand-side vector
283 \param uh [out] solution vector
284 \param TotalErrorResidual [out] error residual
285 \param TotalErrorExactSol [out] error in uh
286
287 */
288 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
289 Teuchos::ParameterList & MLList,
290 Teuchos::RCP<Epetra_CrsMatrix> const & A,
291 Teuchos::RCP<Epetra_CrsMatrix> const & P,
292 const Epetra_MultiVector & xexact,
293 Epetra_MultiVector & b,
294 Epetra_MultiVector & uh,
295 double & TotalErrorResidual,
296 double & TotalErrorExactSol);
297
298 void CalculateError(const Epetra_FEVector & femCoefficients, const Epetra_Map &overlapMap,Epetra_Time & Time, shards::CellTopology &Pn_cellType, Teuchos::RCP<Basis<double,FieldContainer<double> > > myHGradBasis_rcp, const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, int degree);
299
300 /**********************************************************************************/
301 /******** FUNCTION DECLARATIONS FOR EXACT SOLUTION AND SOURCE TERMS ***************/
302 /**********************************************************************************/
303
304 /** \brief User-defined exact solution.
305
306 \param x [in] x-coordinate of the evaluation point
307 \param y [in] y-coordinate of the evaluation point
308
309 \return Value of the exact solution at (x,y)
310 */
311 template<typename Scalar>
312 const Scalar exactSolution(const Scalar& x, const Scalar& y);
313
314 /** \brief User-defined material tensor.
315
316 \param material [out] 3 x 3 material tensor evaluated at (x,y)
317 \param x [in] x-coordinate of the evaluation point
318 \param y [in] y-coordinate of the evaluation point
319
320 \warning Symmetric and positive definite tensor is required for every (x,y).
321 */
322 template<typename Scalar>
323 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y);
324
325 /** \brief Computes gradient of the exact solution. Requires user-defined exact solution.
326
327 \param gradExact [out] gradient of the exact solution evaluated at (x,y)
328 \param x [in] x-coordinate of the evaluation point
329 \param y [in] y-coordinate of the evaluation point
330 */
331 template<typename Scalar>
332 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y);
333
334
335 /** \brief Computes source term: f = -div(A.grad u). Requires user-defined exact solution
336 and material tensor.
337
338 \param x [in] x-coordinate of the evaluation point
339 \param y [in] y-coordinate of the evaluation point
340
341 \return Source term corresponding to the user-defined exact solution evaluated at (x,y)
342 */
343 template<typename Scalar>
344 const Scalar sourceTerm(Scalar& x, Scalar& y);
345
346
347 /** \brief Computation of the material tensor at array of points in physical space.
348
349 \param worksetMaterialValues [out] Rank-2, 3 or 4 array with dimensions (C,P), (C,P,D) or (C,P,D,D)
350 with the values of the material tensor
351 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
352 */
353 template<class ArrayOut, class ArrayIn>
354 void evaluateMaterialTensor(ArrayOut & worksetMaterialValues,
355 const ArrayIn & evaluationPoints);
356
357
358 /** \brief Computation of the source term at array of points in physical space.
359
360 \param sourceTermValues [out] Rank-2 (C,P) array with the values of the source term
361 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
362 */
363 template<class ArrayOut, class ArrayIn>
364 void evaluateSourceTerm(ArrayOut & sourceTermValues,
365 const ArrayIn & evaluationPoints);
366
367 /** \brief Computation of the exact solution at array of points in physical space.
368
369 \param exactSolutionValues [out] Rank-2 (C,P) array with the values of the exact solution
370 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
371 */
372 template<class ArrayOut, class ArrayIn>
373 void evaluateExactSolution(ArrayOut & exactSolutionValues,
374 const ArrayIn & evaluationPoints);
375
376
377 /** \brief Computation of the gradient of the exact solution at array of points in physical space.
378
379 \param exactSolutionGradValues [out] Rank-3 (C,P,D) array with the values of the gradient of the exact solution
380 \param evaluationPoints [in] Rank-3 (C,P,D) array with the evaluation points in physical frame
381 */
382 template<class ArrayOut, class ArrayIn>
383 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
384 const ArrayIn & evaluationPoints);
385
386
387
388 /**********************************************************************************/
389 /******************************** MAIN ********************************************/
390 /**********************************************************************************/
391
392 int main(int argc, char *argv[]) {
393
394 int error = 0;
395 int numProcs=1;
396 int rank=0;
397
398 #ifdef HAVE_MPI
399 Teuchos::GlobalMPISession mpiSession(&argc, &argv,0);
400 rank=mpiSession.getRank();
401 numProcs=mpiSession.getNProc();
402 Epetra_MpiComm Comm(MPI_COMM_WORLD);
403
404 // if(numProcs!=1) {printf("Error: This test only currently works in serial\n");return 1;}
405 #else
406 Epetra_SerialComm Comm;
407 #endif
408
409 int MyPID = Comm.MyPID();
410 global_MyPID = MyPID;//DEBUG
411 Epetra_Time Time(Comm);
412
413 //Check number of arguments
414 if (argc > 3) {
415 std::cout <<"\n>>> ERROR: Invalid number of arguments.\n\n";
416 std::cout <<"Usage:\n\n";
417 std::cout <<" ./TrilinosCouplings_examples_scaling_Example_Poisson.exe [meshfile.xml] [solver.xml]\n\n";
418 std::cout <<" meshfile.xml(optional) - xml file with description of Pamgen mesh\n\n";
419 std::cout <<" solver.xml(optional) - xml file with ML solver options\n\n";
420 exit(1);
421 }
422
423 if (MyPID == 0){
424 std::cout \
425 << "===============================================================================\n" \
426 << "| |\n" \
427 << "| Example: Solve Poisson Equation on Hexahedral Mesh |\n" \
428 << "| |\n" \
429 << "| Questions? Contact Pavel Bochev ([email protected]), |\n" \
430 << "| Denis Ridzal ([email protected]), |\n" \
431 << "| Kara Peterson ([email protected]). |\n" \
432 << "| |\n" \
433 << "| Intrepid's website: http://trilinos.sandia.gov/packages/intrepid |\n" \
434 << "| Pamgen's website: http://trilinos.sandia.gov/packages/pamgen |\n" \
435 << "| ML's website: http://trilinos.sandia.gov/packages/ml |\n" \
436 << "| Isorropia's website: http://trilinos.sandia.gov/packages/isorropia |\n" \
437 << "| Trilinos website: http://trilinos.sandia.gov |\n" \
438 << "| |\n" \
439 << "===============================================================================\n";
440 }
441
442
443 #ifdef HAVE_MPI
444 if (MyPID == 0) {
445 std::cout << "PARALLEL executable \n";
446 }
447 #else
448 if (MyPID == 0) {
449 std::cout << "SERIAL executable \n";
450 }
451 #endif
452
453 /**********************************************************************************/
454 /********************************** GET XML INPUTS ********************************/
455 /**********************************************************************************/
456
457 // Command line for xml file, otherwise use default
458 std::string xmlMeshInFileName, xmlSolverInFileName;
459 if(argc>=2) xmlMeshInFileName=string(argv[1]);
460 else xmlMeshInFileName="Poisson2D.xml";
461 if(argc>=3) xmlSolverInFileName=string(argv[2]);
462
463 // Read xml file into parameter list
464 Teuchos::ParameterList inputMeshList;
465 Teuchos::ParameterList inputSolverList;
466
467 if(xmlMeshInFileName.length()) {
468 if (MyPID == 0) {
469 std::cout << "\nReading parameter list from the XML file \""<<xmlMeshInFileName<<"\" ...\n\n";
470 }
471 Teuchos::updateParametersFromXmlFile (xmlMeshInFileName, Teuchos::ptr (&inputMeshList));
472 if (MyPID == 0) {
473 inputMeshList.print(std::cout,2,true,true);
474 std::cout << "\n";
475 }
476 }
477 else
478 {
479 std::cout << "Cannot read input file: " << xmlMeshInFileName << "\n";
480 return 0;
481 }
482 std::cout<<std::endl;
483
484 if(xmlSolverInFileName.length()) {
485 if (MyPID == 0)
486 std::cout << "\nReading parameter list from the XML file \""<<xmlSolverInFileName<<"\" ...\n\n";
487 Teuchos::updateParametersFromXmlFile(xmlSolverInFileName, Teuchos::inoutArg(inputSolverList));
488 } else if (MyPID == 0) std::cout << "Using default solver values ..." << std::endl;
489
490 // Get pamgen mesh definition
491 std::string meshInput = Teuchos::getParameter<std::string>(inputMeshList,"meshInput");
492 int degree = inputMeshList.get("degree",2);
493
494 // Get Isorropia and Zoltan parameters.
495 Teuchos::ParameterList iso_paramlist = inputMeshList.sublist
496 ("Isorropia Input") ;
497 if (MyPID == 0) {
498 std::cout << "Isorropia/Zoltan parameters" << std::endl;
499 iso_paramlist.print(std::cout,2,true,true);
500 }
501
502
503 /**********************************************************************************/
504 /***************************** GET CELL TOPOLOGY **********************************/
505 /**********************************************************************************/
506
507 // Get cell topology for base quad
508 shards::CellTopology P1_cellType(shards::getCellTopologyData<shards::Quadrilateral<4> >() );
509 shards::CellTopology Pn_cellType(shards::getCellTopologyData<shards::Quadrilateral<> >() );
510 assert(P1_cellType.getDimension() == Pn_cellType.getDimension());
511
512 // Get dimensions
513 int P1_numNodesPerElem = P1_cellType.getNodeCount();
514 int P1_numEdgesPerElem = P1_cellType.getEdgeCount();
515 int spaceDim = P1_cellType.getDimension();
516 int dim = 2;
517 int P1_numNodesPerEdge=2;
518
519 // Build reference element edge to node map
520 FieldContainer<int> P1_refEdgeToNode(P1_numEdgesPerElem,P1_numNodesPerEdge);
521 for (int i=0; i<P1_numEdgesPerElem; i++){
522 P1_refEdgeToNode(i,0)=P1_cellType.getNodeMap(1, i, 0);
523 P1_refEdgeToNode(i,1)=P1_cellType.getNodeMap(1, i, 1);
524 }
525
526 /**********************************************************************************/
527 /******************************* GENERATE MESH ************************************/
528 /**********************************************************************************/
529
530 if (MyPID == 0) {
531 std::cout << "Generating mesh ... \n\n";
532 }
533
534 // Generate mesh with Pamgen
535 long long maxInt = 9223372036854775807LL;
536 long long cr_result = Create_Pamgen_Mesh(meshInput.c_str(), dim, rank, numProcs, maxInt);
537 TrilinosCouplings::pamgen_error_check(std::cout,cr_result);
538 PamgenMesh P1_mesh(dim);
539
540
541 string msg("Poisson: ");
542 if(MyPID == 0) {cout << msg << "Pamgen Setup = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
543
544 // Get mesh size info
545 char title[100];
546 long long numDim;
547 long long numNodes;
548 long long numElems;
549 long long numNodeSets;
550 long long numSideSets;
551 int id = 0;
552 long long my_numElemBlk;
553
554 im_ex_get_init_l(id, title, &numDim, &numNodes,
555 &numElems, &my_numElemBlk, &numNodeSets,
556 &numSideSets);
557 P1_mesh.allocateConnectivity(my_numElemBlk);
558
559
560 long long P1_globalNumNodes;
561 long long P1_globalNumElems;
562 long long numElemBlkGlobal;
563 long long numNodeSetsGlobal;
564 long long numSideSetsGlobal;
565
566 im_ne_get_init_global_l(id, &P1_globalNumNodes, &P1_globalNumElems,
567 &numElemBlkGlobal, &numNodeSetsGlobal,
568 &numSideSetsGlobal);
569
570 // Print mesh information
571 if (MyPID == 0){
572 std::cout << " Number of Global Elements: " << P1_globalNumElems << " \n";
573 std::cout << " Number of Global Nodes: " << P1_globalNumNodes << " \n\n";
574 }
575
576 long long * block_ids = new long long [P1_mesh.numElemBlk];
577 error += im_ex_get_elem_blk_ids_l(id, block_ids);
578
579
580
581 for(long long i = 0; i < P1_mesh.numElemBlk; i ++){
582 P1_mesh.element_types[i].resize(MAX_STR_LENGTH + 1);
583 error += im_ex_get_elem_block_l(id,
584 block_ids[i],
585 P1_mesh.element_types[i].data(),
586 &(P1_mesh.elements[i]),
587 &(P1_mesh.nodes_per_element[i]),
588 &(P1_mesh.element_attributes[i]));
589 }
590
591 /*connectivity*/
592 for(long long b = 0; b < P1_mesh.numElemBlk; b++){
593 P1_mesh.elmt_node_linkage[b].resize(P1_mesh.nodes_per_element[b]* P1_mesh.elements[b]);
594 error += im_ex_get_elem_conn_l(id,block_ids[b],P1_mesh.elmt_node_linkage[b].data());
595 }
596
597 // Get node-element connectivity
598 int telct = 0;
599 FieldContainer<int> P1_elemToNode(numElems,P1_numNodesPerElem);
600 for(long long b = 0; b <P1_mesh.numElemBlk; b++){
601 for(long long el = 0; el < P1_mesh.elements[b]; el++){
602 for (int j=0; j<P1_numNodesPerElem; j++) {
603 P1_elemToNode(telct,j) = P1_mesh.elmt_node_linkage[b][el*P1_numNodesPerElem + j]-1;
604 }
605 telct ++;
606 }
607 }
608
609 // Read node coordinates and place in field container
610 FieldContainer<double> P1_nodeCoord(numNodes,dim);
611 double * nodeCoordx = new double [numNodes];
612 double * nodeCoordy = new double [numNodes];
613 im_ex_get_coord_l(id,nodeCoordx,nodeCoordy,0);
614 for (int i=0; i<numNodes; i++) {
615 P1_nodeCoord(i,0)=nodeCoordx[i];
616 P1_nodeCoord(i,1)=nodeCoordy[i];
617 }
618 /*parallel info*/
619 long long num_internal_nodes;
620 long long num_border_nodes;
621 long long num_external_nodes;
622 long long num_internal_elems;
623 long long num_border_elems;
624 long long num_elem_comm_maps;
625 im_ne_get_loadbal_param_l( id,
626 &num_internal_nodes,
627 &num_border_nodes,
628 &num_external_nodes,
629 &num_internal_elems,
630 &num_border_elems,
631 &P1_mesh.num_node_comm_maps,
632 &num_elem_comm_maps,
633 0/*unused*/ );
634
635 if(P1_mesh.num_node_comm_maps > 0){
636 P1_mesh.node_comm_proc_ids.resize(P1_mesh.num_node_comm_maps);
637 P1_mesh.node_cmap_node_cnts.resize(P1_mesh.num_node_comm_maps);
638 P1_mesh.node_cmap_ids.resize(P1_mesh.num_node_comm_maps);
639 P1_mesh.comm_node_ids.resize(P1_mesh.num_node_comm_maps);
640 P1_mesh.comm_node_proc_ids.resize(P1_mesh.num_node_comm_maps);
641
642 long long * elem_cmap_ids = new long long [num_elem_comm_maps];
643 long long * elem_cmap_elem_cnts = new long long [num_elem_comm_maps];
644
645
646 if ( im_ne_get_cmap_params_l( id,
647 P1_mesh.node_cmap_ids.data(),
648 (long long*)P1_mesh.node_cmap_node_cnts.data(),
649 elem_cmap_ids,
650 (long long*)elem_cmap_elem_cnts,
651 0/*not used proc_id*/ ) < 0 )++error;
652
653 for(long long j = 0; j < P1_mesh.num_node_comm_maps; j++) {
654 P1_mesh.comm_node_ids[j] = new long long [P1_mesh.node_cmap_node_cnts[j]];
655 P1_mesh.comm_node_proc_ids[j].resize(P1_mesh.node_cmap_node_cnts[j]);
656 if ( im_ne_get_node_cmap_l( id,
657 P1_mesh.node_cmap_ids[j],
658 P1_mesh.comm_node_ids[j],
659 P1_mesh.comm_node_proc_ids[j].data(),
660 0/*not used proc_id*/ ) < 0 )++error;
661 P1_mesh.node_comm_proc_ids[j] = P1_mesh.comm_node_proc_ids[j][0];
662 }
663
664 delete [] elem_cmap_ids;
665 delete [] elem_cmap_elem_cnts;
666 }
667
668 if(!Comm.MyPID()) {cout << msg << "Mesh Queries = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
669
670 //Calculate global node ids
671 std::vector<long long> P1_globalNodeIds(numNodes);
672 bool* P1_nodeIsOwned = new bool[numNodes];
673
674 calc_global_node_ids(P1_globalNodeIds.data(),
675 P1_nodeIsOwned,
676 numNodes,
677 P1_mesh.num_node_comm_maps,
678 P1_mesh.node_cmap_node_cnts.data(),
679 P1_mesh.node_comm_proc_ids.data(),
680 P1_mesh.comm_node_ids.data(),
681 rank);
682
683
684 if(MyPID==0) {cout << msg << "Global Node Nums = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
685
686 // Container indicating whether a node is on the boundary (1-yes 0-no)
687 FieldContainer<int> P1_nodeOnBoundary(numNodes);
688
689 // Get boundary (side set) information
690 long long * sideSetIds = new long long [numSideSets];
691 long long numSidesInSet;
692 long long numDFinSet;
693 im_ex_get_side_set_ids_l(id,sideSetIds);
694 for (int i=0; i<numSideSets; i++) {
695 im_ex_get_side_set_param_l(id,sideSetIds[i],&numSidesInSet,&numDFinSet);
696 if (numSidesInSet > 0){
697 long long * sideSetElemList = new long long [numSidesInSet];
698 long long * sideSetSideList = new long long [numSidesInSet];
699 im_ex_get_side_set_l(id,sideSetIds[i],sideSetElemList,sideSetSideList);
700 for (int j=0; j<numSidesInSet; j++) {
701
702 int sideNode0 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,0);
703 int sideNode1 = P1_cellType.getNodeMap(1,sideSetSideList[j]-1,1);
704
705 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode0))=1;
706 P1_nodeOnBoundary(P1_elemToNode(sideSetElemList[j]-1,sideNode1))=1;
707 }
708 delete [] sideSetElemList;
709 delete [] sideSetSideList;
710 }
711 }
712 delete [] sideSetIds;
713
714 if(MyPID ==0) {cout << msg << "Boundary Conds = " << Time.ElapsedTime() << endl; Time.ResetStartTime();}
715
716
717 /******************************************/
718 // Enumerate Edges
719 if(MyPID==0) printf("Using new edge enumeration\n");
720 std::vector<long long> P1_globalEdgeIds;
721 std::vector<bool> P1_edgeIsOwned;
722 std::vector<int> P1_ownedEdgeIds;
723 FieldContainer<int> P1_elemToEdge(numElems,P1_numEdgesPerElem);
724 FieldContainer<int> P1_elemToEdgeOrient(numElems,P1_numEdgesPerElem);
725 FieldContainer<int> P1_edgeToNode;
726 FieldContainer<double> P1_edgeCoord;
727 long long P1_globalNumEdges;
728
729 PamgenEnumerateEdges(P1_numNodesPerElem,P1_numEdgesPerElem,P1_numNodesPerEdge,P1_refEdgeToNode,P1_nodeCoord,
730 P1_globalNodeIds,P1_mesh,
731 Comm, P1_globalEdgeIds,P1_edgeIsOwned,P1_ownedEdgeIds,P1_elemToEdge,P1_elemToEdgeOrient,P1_edgeToNode,P1_edgeCoord,P1_globalNumEdges);
732
733 #if 0
734 {
735 ostringstream ss;
736 ss<<"***** Edge Enumeration ["<<Comm.MyPID()<<"] *****"<<endl;
737 for (int i=0;i<numElems; i++) {
738 for (int j=0; j<P1_numEdgesPerElem; j++)
739 ss<<P1_elemToEdge(i,j)<<"("<<PG_globalEdgeIds[P1_elemToEdge(i,j)]<<")["<<P1_elemToEdgeOrient(i,j)<<"] ";
740 ss<<endl;
741 }
742 ss<<"***** Edge2Node ["<<Comm.MyPID()<<"] *****"<<endl;
743 for (int i=0; i<PG_edgeToNode.dimension(0); i++) {
744 for (int j=0; j<PG_edgeToNode.dimension(1); j++)
745 ss<<PG_edgeToNode(i,j)<<" ";
746 ss<<endl;
747 }
748 printf("%s",ss.str().c_str());
749 fflush(stdout);
750 }
751 #endif
752
753 /******************************************/
754 // Enumerate Elements
755 std::vector<long long> P1_globalElementIds;
756 EnumerateElements(Comm,numElems,P1_globalElementIds);
757
758
759 /******************************************/
760 // Generate higher order mesh
761 // The number of *my* Pn nodes will be related to the number of *my* nodes, edges (owned and ghosted) and elements (owned)
762 int Pn_numNodes = numNodes + (degree-1)*P1_edgeCoord.dimension(0) + (degree-1)*(degree-1)*numElems; // local
763 int Pn_numNodesperElem = (degree+1)*(degree+1); // Quads
764 FieldContainer<int> elemToNode(numElems,Pn_numNodesperElem);
765 FieldContainer<double> nodeCoord(Pn_numNodes,dim);
766 FieldContainer<int> nodeOnBoundary(Pn_numNodes);
767
768 // printf("[%d] P1_numNodes = %d Pn_numNodes = %d Pn_numNodesperElem = %d degree = %d\n",Comm.MyPID(),(int)numNodes,Pn_numNodes,Pn_numNodesperElem,degree);
769
770 std::vector<bool>Pn_nodeIsOwned(Pn_numNodes,false);
771 std::vector<long long>Pn_globalNodeIds(Pn_numNodes);
772 long long Pn_globalNumNodes=0;
773 long long Pn_globalNumElems=P1_globalNumElems;
774
775 PromoteMesh_Pn_Kirby(degree,POINTTYPE_EQUISPACED,P1_globalNumNodes,P1_globalNumEdges,P1_globalNumElems,
776 P1_elemToNode,P1_nodeCoord,P1_edgeCoord,P1_elemToEdge,P1_elemToEdgeOrient,P1_nodeOnBoundary,P1_nodeIsOwned,P1_edgeIsOwned,P1_globalNodeIds,P1_globalEdgeIds,P1_globalElementIds,
777 Pn_globalNumNodes,elemToNode, nodeCoord, nodeOnBoundary,Pn_nodeIsOwned,Pn_globalNodeIds);
778
779
780 if(!MyPID) printf("P1 global (nodes,edges) = (%lld,%lld) Pn global nodes = %lld\n",P1_globalNumNodes,P1_globalNumEdges,Pn_globalNumNodes);
781
782 #if 0
783 {
784 ostringstream ss;
785 ss<<"***** Node ids & ownership ["<<Comm.MyPID()<<"] *****"<<endl;
786 for (int i=0; i<Pn_numNodes; i++)
787 ss<<i<<"["<<Pn_globalNodeIds[i]<<","<<Pn_nodeIsOwned[i]<<"] ";
788 ss<<endl;
789
790 printf("%s",ss.str().c_str());
791 fflush(stdout);
792 }
793 #endif
794
795
796 /******************************************/
797 // Generate Auxillary Mesh
798 int numElems_aux = numElems*4; //4 P1 elements per Pn element in auxiliary mesh
799 long long globalNumElems_aux = P1_globalNumElems*4;
800 FieldContainer<int> aux_P1_elemToNode(numElems_aux,P1_numNodesPerElem); //4 P1 elements per Pn element
801 CreateP1MeshFromP2Mesh(elemToNode, aux_P1_elemToNode);
802
803 // Print mesh information
804 if (MyPID == 0){
805 std::cout << " Number of Pn Global Elements: " << Pn_globalNumElems << " \n";
806 std::cout << " Number of Pn Global Nodes: " << Pn_globalNumNodes << " \n";
807 std::cout << " Number of faux P1 Global Elements: " << globalNumElems_aux << " \n\n";
808 }
809
810 // Coordinates in single vector form
811 std::vector<double> Pn_nodeCoordx(Pn_numNodes);
812 std::vector<double> Pn_nodeCoordy(Pn_numNodes);
813 for (int i=0; i<Pn_numNodes; i++) {
814 Pn_nodeCoordx[i] = nodeCoord(i,0);
815 Pn_nodeCoordy[i] = nodeCoord(i,1);
816 }
817
818 // Reset constants
819 int P1_numNodes =numNodes;
820 numNodes = Pn_numNodes;
821
822 /**********************************************************************************/
823 /********************************* GET CUBATURE ***********************************/
824 /**********************************************************************************/
825
826 // Get numerical integration points and weights
827 DefaultCubatureFactory<double> cubFactory;
828 int cubDegree = 2*degree;
829 Teuchos::RCP<Cubature<double> > myCub = cubFactory.create(Pn_cellType, cubDegree);
830
831 int cubDim = myCub->getDimension();
832 int numCubPoints = myCub->getNumPoints();
833
834 FieldContainer<double> cubPoints(numCubPoints, cubDim);
835 FieldContainer<double> cubWeights(numCubPoints);
836
837 myCub->getCubature(cubPoints, cubWeights);
838
839 if(MyPID==0) {std::cout << "Getting cubature "
840 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
841
842 /**********************************************************************************/
843 /*********************************** GET BASIS ************************************/
844 /**********************************************************************************/
845
846 // Define basis
847 Basis_HGRAD_QUAD_Cn_FEM<double, FieldContainer<double> > myHGradBasis(degree,POINTTYPE_EQUISPACED);
848 Teuchos::RCP<Basis<double,FieldContainer<double> > > myHGradBasis_rcp(&myHGradBasis, false);
849 Teuchos::RCP<Basis_HGRAD_QUAD_Cn_FEM<double,FieldContainer<double> > > myHGradBasisWithDofCoords_rcp(&myHGradBasis, false);
850
851 // Auxillary p=1 basis
852 Basis_HGRAD_QUAD_C1_FEM<double, FieldContainer<double> > myHGradBasis_aux;
853 Teuchos::RCP<Basis<double,FieldContainer<double> > > myHGradBasis_aux_rcp(&myHGradBasis_aux, false);
854
855 int numFieldsG = myHGradBasis.getCardinality();
856
857 FieldContainer<double> HGBValues(numFieldsG, numCubPoints);
858 FieldContainer<double> HGBGrads(numFieldsG, numCubPoints, spaceDim);
859
860 // Evaluate basis values and gradients at cubature points
861 myHGradBasis.getValues(HGBValues, cubPoints, OPERATOR_VALUE);
862 myHGradBasis.getValues(HGBGrads, cubPoints, OPERATOR_GRAD);
863
864
865 //#define OUTPUT_REFERENCE_FUNCTIONS
866 #ifdef OUTPUT_REFERENCE_FUNCTIONS
867 // Evaluate basis values and gradients at DOF points
868 FieldContainer<double> DofCoords(numFieldsG,spaceDim);
869 myHGradBasis.getDofCoords(DofCoords);
870 FieldContainer<double> HGBValues_at_Dofs(numFieldsG,numFieldsG);
871 myHGradBasis.getValues(HGBValues_at_Dofs, DofCoords, OPERATOR_VALUE);
872
873
874 printf("*** Dof Coords ***\n");
875 for(int j=0; j<numFieldsG; j++)
876 printf("[%d] %10.2e %10.2e\n",j,DofCoords(j,0),DofCoords(j,1));
877
878 printf("*** CubPoints & Weights ***\n");
879 for(int j=0; j<numCubPoints; j++)
880 printf("[%d] %10.2e %10.2e (%10.2e)\n",j,cubPoints(j,0),cubPoints(j,1),cubWeights(j));
881
882 printf("*** HGBValues @ Dofs ***\n");
883 for(int i=0; i<numFieldsG; i++) {
884 printf("[%d] ",i);
885 for(int j=0; j<numFieldsG; j++) {
886 printf("%10.2e ",zwrap(HGBValues_at_Dofs(i,j)));
887 }
888 printf("\n");
889 }
890
891 printf("*** HGBValues ***\n");
892 for(int i=0; i<numFieldsG; i++) {
893 printf("[%d] ",i);
894 for(int j=0; j<numCubPoints; j++) {
895 printf("%10.2e ",zwrap(HGBValues(i,j)));
896
897 }
898 printf("\n");
899 }
900
901 printf("*** HGBGrad ***\n");
902 for(int i=0; i<numFieldsG; i++) {
903 printf("[%d] ",i);
904 for(int j=0; j<numCubPoints; j++) {
905 printf("(%10.2e %10.2e)",zwrap(HGBGrads(i,j,0)),zwrap(HGBGrads(i,j,1)));
906 printf("\n");
907 }
908 }
909
910 printf("*** Pn_nodeIsOwned ***\n");
911 for(int i=0; i<Pn_numNodes; i++)
912 printf("%d ",(int)Pn_nodeIsOwned[i]);
913 printf("\n");
914
915 printf("*** Pn_nodeOnBoundary ***\n");
916 for(int i=0; i<Pn_numNodes; i++)
917 printf("%d ",(int)nodeOnBoundary[i]);
918 printf("\n");
919
920 #endif
921
922
923 if(MyPID==0) {std::cout << "Getting basis "
924 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
925
926 /**********************************************************************************/
927 /********************* BUILD MAPS FOR GLOBAL SOLUTION *****************************/
928 /**********************************************************************************/
929 // Count owned nodes (Pn)
930 int Pn_ownedNodes=0;
931 for(int i=0;i<numNodes;i++)
932 if(Pn_nodeIsOwned[i]) Pn_ownedNodes++;
933
934 // Build a list of the OWNED global ids...
935 // NOTE: We cast all of this down to ints for ease of use w/ epetra
936 std::vector<int> Pn_ownedGIDs(Pn_ownedNodes);
937 int oidx=0;
938 for(int i=0;i<numNodes;i++)
939 if(Pn_nodeIsOwned[i]){
940 Pn_ownedGIDs[oidx]=(int)Pn_globalNodeIds[i];
941 oidx++;
942 }
943
944 // Count owned nodes (P1)
945 int P1_ownedNodes=0;
946 for(int i=0;i<P1_numNodes;i++)
947 if(P1_nodeIsOwned[i]) P1_ownedNodes++;
948 std::vector<int> P1_ownedGIDs(P1_ownedNodes);
949 oidx=0;
950 for(int i=0;i<P1_numNodes;i++)
951 if(P1_nodeIsOwned[i]){
952 P1_ownedGIDs[oidx]=(int)P1_globalNodeIds[i];
953 oidx++;
954 }
955
956 // Generate epetra map for nodes
957 Epetra_Map globalMapG(-1,Pn_ownedNodes,&Pn_ownedGIDs[0],0,Comm);
958
959 // Generate p1 map
960 Epetra_Map P1_globalMap(-1,P1_ownedNodes,&P1_ownedGIDs[0],0,Comm);
961
962 // Genetrate Pn-to-P1 coarsening.
963 if (inputSolverList.isParameter("aux P1") && inputSolverList.isParameter("linear P1"))
964 throw std::runtime_error("Can only specify \"aux P1\" or \"linear P1\", not both.");
965 Teuchos::RCP<Epetra_CrsMatrix> P_linear;
966 if (inputSolverList.isParameter("linear P1")) {
967 printf("Generating Linear Pn-to-P1 coarsening...\n");
968 GenerateLinearCoarsening_pn_kirby_to_p1(degree,elemToNode,Pn_nodeIsOwned,myHGradBasisWithDofCoords_rcp, myHGradBasis_aux_rcp,P1_globalMap,globalMapG,P_linear);
969 inputSolverList.remove("linear P1"); //even though LevelWrap happily accepts this parameter
970 }
971
972 // Global arrays in Epetra format
973 Epetra_FECrsMatrix StiffMatrix(Copy, globalMapG, 20*numFieldsG);
974 Epetra_FEVector rhsVector(globalMapG);
975 Epetra_FEVector femCoefficients(globalMapG);
976
977
978 if(MyPID==0) {std::cout << msg << "Build global maps "
979 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
980
981
982
983 #ifdef DUMP_DATA_COORD
984 /**********************************************************************************/
985 /**** PUT COORDINATES AND NODAL VALUES IN ARRAYS FOR OUTPUT (FOR PLOTTING ONLY) ***/
986 /**********************************************************************************/
987
988 // Put coordinates in multivector for output
989 Epetra_MultiVector nCoord(globalMapG,dim);
990 Epetra_MultiVector nBound(globalMapG,1);
991
992 int indOwned = 0;
993 for (int inode=0; inode<numNodes; inode++) {
994 if (Pn_nodeIsOwned[inode]) {
995 nCoord[0][indOwned]=nodeCoord(inode,0);
996 nCoord[1][indOwned]=nodeCoord(inode,1);
997 indOwned++;
998 }
999 }
1000 EpetraExt::MultiVectorToMatrixMarketFile("coords.dat",nCoord,0,0,false);
1001
1002 if(MyPID==0) {Time.ResetStartTime();}
1003
1004 #endif
1005
1006 /**********************************************************************************/
1007 /************************** DIRICHLET BC SETUP ************************************/
1008 /**********************************************************************************/
1009
1010 int numBCNodes = 0;
1011 for (int inode = 0; inode < numNodes; inode++){
1012 if (nodeOnBoundary(inode) && Pn_nodeIsOwned[inode]){
1013 numBCNodes++;
1014 }
1015 }
1016
1017 // Vector for use in applying BCs
1018 Epetra_MultiVector v(globalMapG,true);
1019 v.PutScalar(0.0);
1020
1021 // Set v to boundary values on Dirichlet nodes
1022 std::vector<int> BCNodes(numBCNodes);
1023 int indbc=0;
1024 int iOwned=0;
1025 for (int inode=0; inode<numNodes; inode++){
1026 if (Pn_nodeIsOwned[inode]){
1027 if (nodeOnBoundary(inode)){
1028 BCNodes[indbc]=iOwned;
1029 indbc++;
1030 double x = nodeCoord(inode, 0);
1031 double y = nodeCoord(inode, 1);
1032 v[0][iOwned]=exactSolution(x, y);
1033 }
1034 iOwned++;
1035 }
1036 }
1037
1038 if(MyPID==0) {std::cout << msg << "Get Dirichlet boundary values "
1039 << Time.ElapsedTime() << " sec \n\n"; Time.ResetStartTime();}
1040
1041 /**********************************************************************************/
1042 /******************** DEFINE WORKSETS AND LOOP OVER THEM **************************/
1043 /**********************************************************************************/
1044
1045 // Define desired workset size and count how many worksets there are on this processor's mesh block
1046 int desiredWorksetSize = numElems; // change to desired workset size!
1047 //int desiredWorksetSize = 100; // change to desired workset size!
1048 int numWorksets = numElems/desiredWorksetSize;
1049
1050 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
1051 if(numWorksets*desiredWorksetSize < numElems) numWorksets += 1;
1052
1053 if (MyPID == 0) {
1054 std::cout << "Building discretization matrix and right hand side... \n\n";
1055 std::cout << "\tDesired workset size: " << desiredWorksetSize <<"\n";
1056 std::cout << "\tNumber of worksets (per processor): " << numWorksets <<"\n\n";
1057 Time.ResetStartTime();
1058 }
1059
1060 // Create Pn matrix and RHS
1061 CreateLinearSystem(numWorksets,
1062 desiredWorksetSize,
1063 elemToNode,
1064 nodeCoord,
1065 cubPoints,
1066 cubWeights,
1067 myHGradBasis_rcp,
1068 HGBGrads,
1069 HGBValues,
1070 Pn_globalNodeIds,
1071 StiffMatrix,
1072 rhsVector,
1073 msg,
1074 Time
1075 );
1076
1077 /**********************************************************************************/
1078 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
1079 /**********************************************************************************/
1080
1081 StiffMatrix.GlobalAssemble();
1082 StiffMatrix.FillComplete();
1083 rhsVector.GlobalAssemble();
1084
1085 if(MyPID==0) {std::cout << msg << "Global assembly "
1086 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1087
1088 /////////////////////////////////////////////////////////////////////
1089 // Create P1 matrix and RHS to be used in preconditioner
1090 /////////////////////////////////////////////////////////////////////
1091 //Cubature
1092 // Get numerical integration points and weights
1093 int cubDegree_aux = 2; //TODO This was 3 for P=2. I think this should be 2 now .... Ask Chris.
1094 Teuchos::RCP<Cubature<double> > myCub_aux = cubFactory.create(P1_cellType, cubDegree_aux);
1095
1096 int cubDim_aux = myCub_aux->getDimension();
1097 int numCubPoints_aux = myCub_aux->getNumPoints();
1098
1099 FieldContainer<double> cubPoints_aux(numCubPoints_aux, cubDim_aux);
1100 FieldContainer<double> cubWeights_aux(numCubPoints_aux);
1101 myCub_aux->getCubature(cubPoints_aux, cubWeights_aux);
1102
1103 if(MyPID==0) {std::cout << "Getting cubature for auxiliary P1 mesh "
1104 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
1105
1106 //Basis
1107 // Define basis
1108 int numFieldsG_aux = myHGradBasis_aux.getCardinality();
1109 FieldContainer<double> HGBValues_aux(numFieldsG_aux, numCubPoints_aux);
1110 FieldContainer<double> HGBGrads_aux(numFieldsG_aux, numCubPoints_aux, spaceDim);
1111
1112 // Evaluate basis values and gradients at cubature points
1113 myHGradBasis_aux.getValues(HGBValues_aux, cubPoints_aux, OPERATOR_VALUE);
1114 myHGradBasis_aux.getValues(HGBGrads_aux, cubPoints_aux, OPERATOR_GRAD);
1115
1116 if(MyPID==0) {std::cout << "Getting basis for auxiliary P1 mesh "
1117 << Time.ElapsedTime() << " sec \n" ; Time.ResetStartTime();}
1118
1119 Epetra_FECrsMatrix StiffMatrix_aux(Copy, globalMapG, 20*numFieldsG_aux);
1120 Epetra_FEVector rhsVector_aux(globalMapG);
1121
1122 desiredWorksetSize = numElems_aux;
1123 numWorksets = numElems_aux/desiredWorksetSize;
1124 if(numWorksets*desiredWorksetSize < numElems_aux) numWorksets += 1;
1125 CreateLinearSystem(numWorksets,
1126 desiredWorksetSize,
1127 aux_P1_elemToNode,
1128 nodeCoord,
1129 cubPoints_aux,
1130 cubWeights_aux,
1131 myHGradBasis_aux_rcp,
1132 HGBGrads_aux,
1133 HGBValues_aux,
1134 Pn_globalNodeIds,
1135 StiffMatrix_aux,
1136 rhsVector_aux,
1137 msg,
1138 Time
1139 );
1140 /**********************************************************************************/
1141 /********************* ASSEMBLE OVER MULTIPLE PROCESSORS **************************/
1142 /**********************************************************************************/
1143
1144 StiffMatrix_aux.GlobalAssemble();
1145 StiffMatrix_aux.FillComplete();
1146 rhsVector_aux.GlobalAssemble();
1147
1148 if(MyPID==0) {std::cout << msg << "Global assembly (auxiliary system) "
1149 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1150
1151
1152
1153 // Generate Pn-to-P1 identity coarsening (base mesh to auxiliary mesh).
1154 Teuchos::RCP<Epetra_CrsMatrix> P_identity;
1155 if (inputSolverList.isParameter("aux P1")) {
1156 printf("Generating Identity Pn-to-P1 coarsening...\n");
1157 GenerateIdentityCoarsening_pn_to_p1(elemToNode, StiffMatrix_aux.DomainMap(), StiffMatrix.RangeMap(), P_identity);
1158 inputSolverList.remove("aux P1"); //even though LevelWrap happily accepts this parameter
1159 }
1160
1161
1162 /**********************************************************************************/
1163 /******************************* ADJUST MATRIX DUE TO BC **************************/
1164 /**********************************************************************************/
1165
1166 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1167 // and add one to diagonal.
1168 Apply_Dirichlet_BCs(BCNodes,StiffMatrix,femCoefficients,rhsVector,v);
1169
1170 ///////////////////////////////////////////
1171 // Apply BCs to auxiliary P1 matrix
1172 ///////////////////////////////////////////
1173 // Zero out rows and columns of stiffness matrix corresponding to Dirichlet edges
1174 // and add one to diagonal.
1175 Apply_Dirichlet_BCs(BCNodes,StiffMatrix_aux,rhsVector_aux,rhsVector_aux,v);
1176
1177 if(MyPID==0) {std::cout << msg << "Adjust global matrix and rhs due to BCs " << Time.ElapsedTime()
1178 << " sec \n"; Time.ResetStartTime();}
1179
1180
1181 #ifdef DUMP_DATA
1182 // Dump matrices to disk
1183 EpetraExt::RowMatrixToMatlabFile("stiff_matrix.dat",StiffMatrix);
1184 EpetraExt::MultiVectorToMatrixMarketFile("rhs_vector.dat",rhsVector,0,0,false);
1185 EpetraExt::RowMatrixToMatlabFile("stiff_matrix_aux.dat",StiffMatrix_aux);
1186 EpetraExt::MultiVectorToMatrixMarketFile("rhs_vector_aux.dat",rhsVector_aux,0,0,false);
1187 //#undef DUMP_DATA
1188 #endif
1189
1190 /**********************************************************************************/
1191 /*********************************** SOLVE ****************************************/
1192 /**********************************************************************************/
1193 // Run the solver
1194 Teuchos::ParameterList MLList = inputSolverList;
1195 ML_Epetra::SetDefaults("SA", MLList, 0, 0, false);
1196 MLList.set("repartition: Zoltan dimensions",2);
1197 MLList.set("x-coordinates",Pn_nodeCoordx.data());
1198 MLList.set("y-coordinates",Pn_nodeCoordy.data());
1199
1200 Epetra_FEVector exactNodalVals(globalMapG);
1201 double TotalErrorResidual = 0.0;
1202 double TotalErrorExactSol = 0.0;
1203
1204 // Get exact solution at nodes
1205 for (int i = 0; i<numNodes; i++) {
1206 if (Pn_nodeIsOwned[i]){
1207 double x = nodeCoord(i,0);
1208 double y = nodeCoord(i,1);
1209 double exactu = exactSolution(x, y);
1210
1211 int rowindex=Pn_globalNodeIds[i];
1212 exactNodalVals.SumIntoGlobalValues(1, &rowindex, &exactu);
1213 }
1214 }
1215 exactNodalVals.GlobalAssemble();
1216
1217 char probType[10] = "laplace";
1218
1219 Teuchos::RCP<Epetra_CrsMatrix> interpolationMatrix;
1220 if (P_identity != Teuchos::null) {
1221 MLList.set("user coarse matrix",(Epetra_CrsMatrix*)&StiffMatrix_aux);
1222 interpolationMatrix = P_identity;
1223 }
1224 if (P_linear != Teuchos::null) {
1225 interpolationMatrix = P_linear;
1226 }
1227
1228 TestMultiLevelPreconditionerLaplace(probType, MLList,
1229 Teuchos::rcpFromRef(StiffMatrix), interpolationMatrix, exactNodalVals,
1230 rhsVector, femCoefficients,
1231 TotalErrorResidual, TotalErrorExactSol);
1232
1233
1234 #ifdef DUMP_DATA
1235 // Dump matrices to disk
1236 EpetraExt::MultiVectorToMatrixMarketFile("lhs_vector.dat",femCoefficients,0,0,false);
1237 EpetraExt::MultiVectorToMatrixMarketFile("lhs_vector_exact.dat",exactNodalVals,0,0,false);
1238 #endif
1239
1240 // Build an overlap map for error calculation. This is kind of like StiffMatrix's ColMap, but in a different order
1241 std::vector<int>Pn_globalNodeIds_int(Pn_numNodes);
1242 for(int i=0;i<Pn_numNodes; i++)
1243 Pn_globalNodeIds_int[i] = (int)Pn_globalNodeIds[i];
1244 Epetra_Map OverlapMap(-1,Pn_numNodes,Pn_globalNodeIds_int.data(),0,Comm);
1245
1246 // Calculate Error
1247 CalculateError(femCoefficients,OverlapMap,Time,Pn_cellType,myHGradBasis_rcp,elemToNode,nodeCoord,degree);
1248
1249 // Cleanup
1250 delete [] block_ids;
1251
1252 delete [] nodeCoordx;
1253 delete [] nodeCoordy;
1254 delete [] P1_nodeIsOwned;
1255
1256 // delete mesh
1257 Delete_Pamgen_Mesh();
1258
1259 return 0;
1260
1261 }
1262 /**********************************************************************************/
1263 /********************************* END MAIN ***************************************/
1264 /**********************************************************************************/
1265
1266 /**********************************************************************************/
1267 /************ USER DEFINED FUNCTIONS FOR EXACT SOLUTION ***************************/
1268 /**********************************************************************************/
1269
1270 template<typename Scalar>
1271 const Scalar exactSolution(const Scalar& x, const Scalar& y) {
1272
1273 // Patch test: bi-linear function is in the FE space and should be recovered
1274 // return 1. + x + y + x*y;
1275
1276 // Analytic solution with homogeneous Dirichlet boundary data
1277 //return sin(M_PI*x)*sin(M_PI*y)**exp(x+y);
1278
1279 // Analytic solution with inhomogeneous Dirichlet boundary data
1280 return exp(x + y )/(1. + x*y);
1281 }
1282
1283
1284 template<typename Scalar>
1285 void materialTensor(Scalar material[][2], const Scalar& x, const Scalar& y) {
1286
1287 material[0][0] = 1.;
1288 material[0][1] = 0.;
1289 //
1290 material[1][0] = 0.;
1291 material[1][1] = 1.;
1292 }
1293
1294 /**********************************************************************************/
1295 /************** AUXILIARY FUNCTIONS FROM EXACT SOLUTION ***************************/
1296 /**********************************************************************************/
1297
1298 /************ Grad of Exact Solution ****************/
1299 template<typename Scalar>
1300 void exactSolutionGrad(Scalar gradExact[2], const Scalar& x, const Scalar& y) {
1301
1302 // To enable derivatives of the gradient (i.e., 2nd derivatives of the exact solution) need 2 levels of fad types
1303 Sacado::Fad::SFad<Scalar,2> fad_x = x;
1304 Sacado::Fad::SFad<Scalar,2> fad_y = y;
1305 Sacado::Fad::SFad<Scalar,2> u;
1306
1307 // Indicate the independent variables
1308 fad_x.diff(0,2);
1309 fad_y.diff(1,2);
1310
1311 u = exactSolution(fad_x, fad_y);
1312
1313 gradExact[0] = u.dx(0);
1314 gradExact[1] = u.dx(1);
1315 }
1316
1317 /************ Source Term (RHS) ****************/
1318 template<typename Scalar>
1319 const Scalar sourceTerm(Scalar& x, Scalar& y){
1320
1321 Scalar u;
1322 Scalar grad_u[2];
1323 Scalar flux[2] = {0.0, 0.0};
1324 Scalar material[2][2];
1325 Scalar f = 0.;
1326
1327 // Indicate the independent variables
1328 x.diff(0,2);
1329 y.diff(1,2);
1330
1331 // Get exact solution and its gradient
1332 u = exactSolution(x, y);
1333 exactSolutionGrad(grad_u, x, y);
1334
1335 // Get material tensor
1336 materialTensor<Scalar>(material, x, y);
1337
1338 // Compute total flux = (A.grad u)
1339 for(int i = 0; i < 2; i++){
1340
1341 // Add diffusive flux
1342 for(int j = 0; j < 2; j++){
1343 flux[i] += material[i][j]*grad_u[j];
1344 }
1345 }
1346
1347 // Compute source term (right hand side): f = -div(A.grad u)
1348 f = -(flux[0].dx(0) + flux[1].dx(1));
1349
1350 return f;
1351 }
1352
1353 /**********************************************************************************/
1354 /*************************** EVALUATION METHODS ***********************************/
1355 /**********************************************************************************/
1356
1357 /************ Material Tensor ****************/
1358 template<class ArrayOut, class ArrayIn>
1359 void evaluateMaterialTensor(ArrayOut & matTensorValues,
1360 const ArrayIn & evaluationPoints){
1361
1362 int numWorksetCells = evaluationPoints.dimension(0);
1363 int numPoints = evaluationPoints.dimension(1);
1364 int spaceDim = evaluationPoints.dimension(2);
1365
1366 double material[2][2];
1367
1368 for(int cell = 0; cell < numWorksetCells; cell++){
1369 for(int pt = 0; pt < numPoints; pt++){
1370
1371 double x = evaluationPoints(cell, pt, 0);
1372 double y = evaluationPoints(cell, pt, 1);
1373
1374 materialTensor<double>(material, x, y);
1375
1376 for(int row = 0; row < spaceDim; row++){
1377 for(int col = 0; col < spaceDim; col++){
1378 matTensorValues(cell, pt, row, col) = material[row][col];
1379 }
1380 }
1381 }
1382 }
1383 }
1384 /************ Source Term (RHS) ****************/
1385 template<class ArrayOut, class ArrayIn>
1386 void evaluateSourceTerm(ArrayOut & sourceTermValues,
1387 const ArrayIn & evaluationPoints){
1388
1389 int numWorksetCells = evaluationPoints.dimension(0);
1390 int numPoints = evaluationPoints.dimension(1);
1391
1392 for(int cell = 0; cell < numWorksetCells; cell++){
1393 for(int pt = 0; pt < numPoints; pt++){
1394
1395 Sacado::Fad::SFad<double,2> x = evaluationPoints(cell, pt, 0);
1396 Sacado::Fad::SFad<double,2> y = evaluationPoints(cell, pt, 1);
1397
1398 sourceTermValues(cell, pt) = sourceTerm<Sacado::Fad::SFad<double,2> >(x, y).val();
1399 }
1400 }
1401 }
1402
1403 /************ Exact Solution ****************/
1404 template<class ArrayOut, class ArrayIn>
1405 void evaluateExactSolution(ArrayOut & exactSolutionValues,
1406 const ArrayIn & evaluationPoints){
1407
1408 int numWorksetCells = evaluationPoints.dimension(0);
1409 int numPoints = evaluationPoints.dimension(1);
1410
1411 for(int cell = 0; cell < numWorksetCells; cell++){
1412 for(int pt = 0; pt < numPoints; pt++){
1413
1414 double x = evaluationPoints(cell, pt, 0);
1415 double y = evaluationPoints(cell, pt, 1);
1416
1417 exactSolutionValues(cell, pt) = exactSolution<double>(x, y);
1418 }
1419 }
1420 }
1421 /************ Grad of Exact Solution ****************/
1422 template<class ArrayOut, class ArrayIn>
1423 void evaluateExactSolutionGrad(ArrayOut & exactSolutionGradValues,
1424 const ArrayIn & evaluationPoints){
1425
1426 int numWorksetCells = evaluationPoints.dimension(0);
1427 int numPoints = evaluationPoints.dimension(1);
1428 int spaceDim = evaluationPoints.dimension(2);
1429
1430 double gradient[2];
1431
1432 for(int cell = 0; cell < numWorksetCells; cell++){
1433 for(int pt = 0; pt < numPoints; pt++){
1434
1435 double x = evaluationPoints(cell, pt, 0);
1436 double y = evaluationPoints(cell, pt, 1);
1437
1438 exactSolutionGrad<double>(gradient, x, y);
1439
1440 for(int row = 0; row < spaceDim; row++){
1441 exactSolutionGradValues(cell, pt, row) = gradient[row];
1442 }
1443 }
1444 }
1445 }
1446
1447 /**********************************************************************************/
1448 /******************************* TEST ML ******************************************/
1449 /**********************************************************************************/
1450
1451 #include "ml_LevelWrap.h"
1452
1453 // Test ML
1454 int TestMultiLevelPreconditionerLaplace(char ProblemType[],
1455 Teuchos::ParameterList & MLList,
1456 Teuchos::RCP<Epetra_CrsMatrix> const &A0,
1457 Teuchos::RCP<Epetra_CrsMatrix> const &P0,
1458 const Epetra_MultiVector & xexact,
1459 Epetra_MultiVector & b,
1460 Epetra_MultiVector & uh,
1461 double & TotalErrorResidual,
1462 double & TotalErrorExactSol)
1463 {
1464 Epetra_MultiVector x(xexact);
1465 x = uh;
1466
1467 Epetra_LinearProblem Problem(&*A0,&x,&b);
1468 Epetra_MultiVector* lhs = Problem.GetLHS();
1469 Epetra_MultiVector* rhs = Problem.GetRHS();
1470
1471 Epetra_Time Time(A0->Comm());
1472
1473 // =================== //
1474 // call ML and AztecOO //
1475 // =================== //
1476
1477 AztecOO solver(Problem);
1478 Epetra_Operator *MLPrec;
1479 if (P0 == Teuchos::null)
1480 MLPrec = new ML_Epetra::MultiLevelPreconditioner(*A0, MLList, true);
1481 else
1482 MLPrec = new ML_Epetra::LevelWrap(A0, P0, MLList, true);
1483
1484 // tell AztecOO to use this preconditioner, then solve
1485 solver.SetPrecOperator(MLPrec);
1486 solver.SetAztecOption(AZ_solver, AZ_cg);
1487 solver.SetAztecOption(AZ_output, 1);
1488
1489 solver.Iterate(200, 1e-12);
1490
1491 delete MLPrec;
1492
1493 uh = *lhs;
1494
1495
1496 #ifdef DUMP_DATA
1497 EpetraExt::MultiVectorToMatrixMarketFile("lhs_vector.dat",*lhs,0,0,false);
1498 #undef DUMP_DATA
1499 #endif
1500
1501 // ==================================================== //
1502 // compute difference between exact solution and ML one //
1503 // ==================================================== //
1504 double d = 0.0, d_tot = 0.0 , s =0.0, s_tot=0.0;
1505 for( int i=0 ; i<lhs->Map().NumMyElements() ; ++i ) {
1506 d += ((*lhs)[0][i] - xexact[0][i]) * ((*lhs)[0][i] - xexact[0][i]);
1507 s += xexact[0][i]* xexact[0][i];
1508 }
1509
1510 A0->Comm().SumAll(&d,&d_tot,1);
1511 A0->Comm().SumAll(&s,&s_tot,1);
1512
1513 // ================== //
1514 // compute ||Ax - b|| //
1515 // ================== //
1516 double Norm;
1517 Epetra_Vector Ax(rhs->Map());
1518 A0->Multiply(false, *lhs, Ax);
1519 Ax.Update(1.0, *rhs, -1.0);
1520 Ax.Norm2(&Norm);
1521
1522 string msg = ProblemType;
1523
1524 if (A0->Comm().MyPID() == 0) {
1525 cout << msg << "......Using " << A0->Comm().NumProc() << " processes" << endl;
1526 cout << msg << "......||A x - b||_2 = " << Norm << endl;
1527 cout << msg << "......||x_exact - x||_2/||x_exact||_2 = " << sqrt(d_tot/s_tot) << endl;
1528 cout << msg << "......Total Time = " << Time.ElapsedTime() << endl;
1529 }
1530
1531 TotalErrorExactSol += sqrt(d_tot);
1532 TotalErrorResidual += Norm;
1533
1534 return( solver.NumIters() );
1535
1536 }
1537
1538 /*********************************************************************************************************/
1539 /*********************************************************************************************************/
1540
1541
1542 /*********************************************************************************************************/
1543 void PromoteMesh_Pn_Kirby(const int degree, const EPointType & pointType,long long P1_globalNumNodes, long long P1_globalNumEdges,long long P1_globalNumElem,
1544 const FieldContainer<int> & P1_elemToNode,
1545 const FieldContainer<double> & P1_nodeCoord,
1546 const FieldContainer<double> & P1_edgeCoord,
1547 const FieldContainer<int> & P1_elemToEdge,
1548 const FieldContainer<int> & P1_elemToEdgeOrient,
1549 const FieldContainer<int> & P1_nodeOnBoundary,
1550 const bool * P1_nodeIsOwned,
1551 const std::vector<bool> & P1_edgeIsOwned,
1552 const std::vector<long long> & P1_globalNodeIds,
1553 const std::vector<long long> & P1_globalEdgeIds,
1554 const std::vector<long long> & P1_globalElementIds,
1555 long long & Pn_globalNumNodes,
1556 FieldContainer<int> & Pn_elemToNode,
1557 FieldContainer<double> & Pn_nodeCoord,
1558 FieldContainer<int> & Pn_nodeOnBoundary,
1559 std::vector<bool> & Pn_nodeIsOwned,
1560 std::vector<long long> & Pn_globalNodeIds
1561 ) {
1562 //#define DEBUG_PROMOTE_MESH
1563 int numElems = P1_elemToNode.dimension(0);
1564 int P1_numNodesperElem = P1_elemToNode.dimension(1);
1565 int P1_numEdgesperElem = P1_elemToEdge.dimension(1);
1566 int Pn_numNodesperElem = Pn_elemToNode.dimension(1);
1567 int P1_numNodes = P1_nodeCoord.dimension(0);
1568 int P1_numEdges = P1_edgeCoord.dimension(0);
1569 int dim = P1_nodeCoord.dimension(1);
1570
1571
1572 #ifdef DEBUG_PROMOTE_MESH
1573 int Pn_numNodes = Pn_nodeCoord.dimension(0);
1574 #endif
1575
1576 int Pn_ExpectedNodesperElem = P1_numNodesperElem + (degree-1)*P1_numEdgesperElem + (degree-1)*(degree-1);
1577 int Pn_ExpectedNumNodes = P1_numNodes + (degree-1)*P1_numEdges + (degree-1)*(degree-1)*numElems;
1578
1579 // Sanity checks
1580 if(P1_numNodesperElem !=4 || Pn_numNodesperElem !=Pn_ExpectedNodesperElem ) throw std::runtime_error("Error: PromoteMesh_Pn_Kirby only works on Quads!");
1581 if(P1_elemToEdge.dimension(0)!=numElems || P1_elemToEdge.dimension(1)!=4 || P1_elemToEdge.dimension(0)!=P1_elemToEdgeOrient.dimension(0) || P1_elemToEdge.dimension(1)!=P1_elemToEdgeOrient.dimension(1) ||
1582 Pn_elemToNode.dimension(0)!=numElems || Pn_nodeCoord.dimension(0) != Pn_ExpectedNumNodes)
1583 throw std::runtime_error("Error: PromoteMesh_Pn_Kirby array size mismatch");
1584
1585 const CellTopologyData &cellTopoData = *shards::getCellTopologyData<shards::Quadrilateral<4> >();
1586 shards::CellTopology cellTopo(&cellTopoData);
1587
1588 // Kirby elements are ordered strictly in lex ordering from the bottom left to the top right
1589 /*
1590 Kirby Quad-9 Layout (p=2)
1591 inode6 -- inode7 -- inode8
1592 | |
1593 inode3 inode4 inode5
1594 | |
1595 inode0 -- inode1 -- inode2
1596
1597
1598 Kirby Quad-16 Layout (p=3)
1599 inode12-- inode13-- inode14-- inode15
1600 | |
1601 inode8 inode9 inode10 inode11
1602 | |
1603 inode4 inode5 inode6 inode7
1604 | |
1605 inode0 -- inode1 -- inode2 -- inode3
1606 */
1607
1608 // We still number the global nodes in the exodus-style (node,edge,face) ordering, *by global orientation* but
1609 // the elem2node map has to account for Kirby-style elements
1610 int p1_node_in_pn[4] = {0,degree, (degree+1)*(degree+1)-1, degree*(degree+1)};
1611 int edge_node0_id[4]={0,1,2,3};
1612 int edge_node1_id[4]={1,2,3,0};
1613
1614 // As you advance along each edge, we'll skip by the following amount to get to the next Kirby dof
1615 // edge_skip is in *local* orientation, so we'll multiply it by the elemToEdgeOrient value
1616 int edge_skip[4] = {1,degree+1,-1,-(degree+1)};
1617 int center_root = degree+2;
1618
1619 // printf("[%d] Global Edge Offset = %d Global Element Offset = %d\n",global_MyPID, P1_globalNumNodes, P1_globalNumNodes+P1_globalNumEdges*(degree-1));
1620
1621 // Make the new el2node array
1622 for(int i=0; i<numElems; i++) {
1623 // P1 nodes
1624 for(int j=0; j<P1_numNodesperElem; j++) {
1625 int lid = P1_elemToNode(i,j);
1626 Pn_elemToNode(i,p1_node_in_pn[j]) = lid;
1627 Pn_nodeIsOwned[lid] = P1_nodeIsOwned[lid];
1628 Pn_globalNodeIds[lid] = P1_globalNodeIds[lid];
1629 }
1630
1631 // P1 edges
1632 for(int j=0; j<P1_numEdgesperElem; j++){
1633 int orient = P1_elemToEdgeOrient(i,j);
1634 int base_id = (orient==1) ? p1_node_in_pn[edge_node0_id[j]] : p1_node_in_pn[edge_node1_id[j]];
1635 int skip = orient*edge_skip[j];
1636 bool is_owned= P1_edgeIsOwned[P1_elemToEdge(i,j)];// new node is owned if the edge was
1637 for(int k=0; k<degree-1; k++) {
1638 int lid = P1_numNodes+P1_elemToEdge(i,j)*(degree-1)+k;
1639 long long gid = P1_globalNumNodes + P1_globalEdgeIds[P1_elemToEdge(i,j)]*(degree-1)+k;
1640 Pn_elemToNode(i,base_id+(k+1)*skip) = lid;
1641 Pn_nodeIsOwned[lid] = is_owned;
1642 Pn_globalNodeIds[lid] = gid;
1643 }
1644 }
1645
1646 // printf("GID Base = %d degree = %d\n", P1_globalNumNodes+P1_globalNumEdges*(degree-1) + P1_globalElementIds[i]*(degree-1)*(degree-1),degree);
1647 // P1 cells
1648 for(int j=0; j<degree-1; j++)
1649 for(int k=0; k<degree-1; k++) {
1650 int offset = j*(degree-1)+k;
1651 int lid = P1_numNodes+P1_numEdges*(degree-1)+i*(degree-1)*(degree-1)+offset;
1652 long long gid = P1_globalNumNodes+P1_globalNumEdges*(degree-1) + P1_globalElementIds[i]*(degree-1)*(degree-1) + offset;
1653 // printf("offset = %d lid = %d gid = %d P1_globalElementIds = %d\n",offset,lid,gid, P1_globalElementIds[i]);
1654 Pn_elemToNode(i,center_root+j*(degree+1)+k) = lid;
1655 Pn_nodeIsOwned[lid] = true; //elements are always owned
1656 Pn_globalNodeIds[lid] = gid;
1657 }
1658
1659 }
1660
1661 Pn_globalNumNodes = P1_globalNumNodes+P1_globalNumEdges*(degree-1) + P1_globalNumElem*(degree-1)*(degree-1);
1662
1663 // Get the p=n node locations
1664 FieldContainer<double> RefNodeCoords(Pn_numNodesperElem,dim);
1665 FieldContainer<double> RefNodeCoords2(1,Pn_numNodesperElem,dim);
1666 FieldContainer<double> PhysNodeCoords(1,Pn_numNodesperElem,dim);
1667 Basis_HGRAD_QUAD_Cn_FEM<double, FieldContainer<double> > BasisPn(degree,pointType);
1668 BasisPn.getDofCoords(RefNodeCoords);
1669
1670 #ifdef DEBUG_PROMOTE_MESH
1671 printf("**** P=%d reference nodal coordinates ***\n",degree);
1672 for(int i=0; i<Pn_numNodesperElem; i++)
1673 printf("[%2d] %10.2f %10.2f\n",i,RefNodeCoords(i,0),RefNodeCoords(i,1));
1674 #endif
1675
1676 for(int i=0; i<Pn_numNodesperElem; i++)
1677 for(int k=0; k<dim; k++)
1678 RefNodeCoords2(0,i,k) = RefNodeCoords(i,k);
1679
1680 // Make the new coordinates (inefficient, but correct)
1681 for(int i=0; i<numElems; i++) {
1682 // Get Element coords
1683 FieldContainer<double> my_p1_nodes(1,P1_numNodesperElem,dim);
1684 for(int j=0; j<P1_numNodesperElem; j++) {
1685 int jj = P1_elemToNode(i,j);
1686 for(int k=0; k<dim; k++)
1687 my_p1_nodes(0,j,k) = P1_nodeCoord(jj,k);
1688 }
1689
1690 // Map the reference node location to physical
1691 Intrepid::CellTools<double>::mapToPhysicalFrame(PhysNodeCoords,RefNodeCoords2,my_p1_nodes,cellTopo);
1692
1693 #ifdef DEBUG_PROMOTE_MESH
1694 printf("[%2d] PhysNodes : ",i);
1695 for(int j=0; j<Pn_numNodesperElem; j++)
1696 printf("(%10.2f %10.2f) ",PhysNodeCoords(0,j,0),PhysNodeCoords(0,j,1));
1697 printf("\n");
1698 #endif
1699
1700 // Copy the physical node locations to the Pn_nodeCoord array
1701 for(int j=0; j<Pn_numNodesperElem; j++) {
1702 int jj = Pn_elemToNode(i,j);
1703 for(int k=0; k<dim; k++)
1704 Pn_nodeCoord(jj,k) = PhysNodeCoords(0,j,k);
1705 }
1706
1707 }
1708
1709 #ifdef DEBUG_PROMOTE_MESH
1710 for(int i=0; i<numElems; i++) {
1711 printf("[%2d] Effective : ",i);
1712 for(int j=0; j<Pn_numNodesperElem; j++)
1713 printf("(%10.2f %10.2f) ",Pn_nodeCoord(Pn_elemToNode(i,j),0),Pn_nodeCoord(Pn_elemToNode(i,j),1));
1714 printf("\n");
1715 }
1716 #endif
1717
1718 // Update the boundary conditions
1719
1720 // P1 nodes
1721 for(int i=0; i<P1_numNodes; i++)
1722 Pn_nodeOnBoundary(i) = P1_nodeOnBoundary(i);
1723
1724 // P1 edges
1725 // Not all that efficient
1726 for(int i=0; i<numElems; i++) {
1727 for(int j=0; j<P1_numEdgesperElem; j++) {
1728 int n0 = P1_elemToNode(i,edge_node0_id[j]);
1729 int n1 = P1_elemToNode(i,edge_node1_id[j]);
1730 if(P1_nodeOnBoundary(n0) && P1_nodeOnBoundary(n1)) {
1731 for(int k=0; k<degree-1; k++)
1732 Pn_nodeOnBoundary(P1_numNodes+P1_elemToEdge(i,j)*(degree-1)+k) =1;
1733 }
1734 }
1735 }
1736
1737 #ifdef DEBUG_PROMOTE_MESH
1738 // debug
1739 printf("**** P=%d elem2node ***\n",degree);
1740 for(int i=0; i<numElems; i++) {
1741 printf("[%2d] ",i);
1742 for(int j=0; j<Pn_numNodesperElem; j++)
1743 printf("%2d ",Pn_elemToNode(i,j));
1744 printf("\n");
1745 }
1746
1747
1748 printf("**** P=%d nodes ***\n",degree);
1749 for(int i=0; i<Pn_numNodes; i++) {
1750 printf("[%2d] %10.2e %10.2e (%d)\n",i,Pn_nodeCoord(i,0),Pn_nodeCoord(i,1),(int)Pn_nodeOnBoundary(i));
1751 }
1752
1753 printf("**** P=1 nodes ***\n");
1754 for(int i=0; i<P1_numNodes; i++) {
1755 printf("[%2d] %10.2e %10.2e (%d)\n",i,P1_nodeCoord(i,0),P1_nodeCoord(i,1),(int)P1_nodeOnBoundary(i));
1756 }
1757 #endif
1758
1759 }
1760
1761
1762 /*********************************************************************************************************/
1763
1764 void CreateP1MeshFromP2Mesh(FieldContainer<int> const & P2_elemToNode,
1765 FieldContainer<int> & P1_elemToNode)
1766 {
1767
1768 /*
1769 Main idea:
1770 For each P2 element
1771 Create four P1 elements
1772 For each of those P1 elements
1773 Create element to node map
1774 */
1775
1776 int P2_numElems = P2_elemToNode.dimension(0);
1777
1778 int p1ElemCtr=0;
1779 for (int i=0; i<P2_numElems; ++i) {
1780
1781 /*
1782 How "P1" elements are traversed in a P2 element
1783
1784 inode3 -- inode6 -- inode2
1785
1786 | 3 | 2 |
1787
1788 inode7 -- inode8 -- inode5
1789
1790 | 0 | 1 |
1791
1792 inode0 -- inode4 -- inode1
1793 */
1794
1795 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,0);
1796 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,4);
1797 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,8);
1798 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,7);
1799
1800 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,4);
1801 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,1);
1802 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,5);
1803 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,8);
1804
1805 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,8);
1806 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,5);
1807 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,2);
1808 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,6);
1809
1810 P1_elemToNode(p1ElemCtr,0) = P2_elemToNode(i,7);
1811 P1_elemToNode(p1ElemCtr,1) = P2_elemToNode(i,8);
1812 P1_elemToNode(p1ElemCtr,2) = P2_elemToNode(i,6);
1813 P1_elemToNode(p1ElemCtr++,3) = P2_elemToNode(i,3);
1814
1815 }
1816 } //CreateP1MeshFromP2Mesh
1817
1818 /*********************************************************************************************************/
1819
1820 void CreateLinearSystem(int numWorksets,
1821 int desiredWorksetSize,
1822 FieldContainer<int> const &elemToNode,
1823 FieldContainer<double> const &nodeCoord,
1824 FieldContainer<double> const &cubPoints,
1825 FieldContainer<double> const &cubWeights,
1826 Teuchos::RCP<Basis<double,FieldContainer<double> > >&myBasis_rcp,
1827 FieldContainer<double> const &HGBGrads,
1828 FieldContainer<double> const &HGBValues,
1829 std::vector<long long> const &globalNodeIds,
1830 Epetra_FECrsMatrix &StiffMatrix,
1831 Epetra_FEVector &rhsVector,
1832 std::string &msg0,
1833 Epetra_Time &Time
1834 )
1835 {
1836 int MyPID = StiffMatrix.Comm().MyPID();
1837 int numCubPoints = cubPoints.dimension(0);
1838 int cubDim = cubPoints.dimension(1);
1839 int spaceDim = nodeCoord.dimension(1);
1840 int numFieldsG = HGBGrads.dimension(0);
1841 long long numElems = elemToNode.dimension(0);
1842 int numNodesPerElem = elemToNode.dimension(1);
1843
1844
1845
1846 if(!global_MyPID) {
1847 std::cout << "CreateLinearSystem:" << std::endl;
1848 std::cout << " numCubPoints = " << numCubPoints << std::endl;
1849 std::cout << " cubDim = " << cubDim << std::endl;
1850 std::cout << " spaceDim = " << spaceDim << std::endl;
1851 std::cout << " numFieldsG = " << numFieldsG << std::endl;
1852 // std::cout << " numElems = " << numElems << std::endl;
1853 std::cout << " numNodesPerElem = " << numNodesPerElem << std::endl;
1854 // std::cout << " length(globalNodeIds) = " << globalNodeIds.size() << std::endl;
1855 // std::cout << " length(nodeCoord) = " << nodeCoord.dimension(0) << std::endl;
1856 }
1857 std::string msg = " " + msg0;
1858
1859 if(nodeCoord.dimension(0) != Teuchos::as<int>(globalNodeIds.size())) {
1860 std::ostringstream errStr;
1861 errStr << "Error: CreateLinearSystem: length of coordinates != #nodes ("
1862 << nodeCoord.dimension(0) << "!=" << globalNodeIds.size() << ")";
1863 throw std::runtime_error(errStr.str());
1864 }
1865
1866 for(int workset = 0; workset < numWorksets; workset++){
1867
1868 // Compute cell numbers where the workset starts and ends
1869 int worksetSize = 0;
1870 int worksetBegin = (workset + 0)*desiredWorksetSize;
1871 int worksetEnd = (workset + 1)*desiredWorksetSize;
1872
1873 // When numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
1874 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
1875
1876 // Now we know the actual workset size and can allocate the array for the cell nodes
1877 worksetSize = worksetEnd - worksetBegin;
1878 //std::cout << " cellWorkset: begin=" << worksetBegin << ", end=" << worksetEnd
1879 // << ", size=" << worksetSize << std::endl;
1880 FieldContainer<double> cellWorkset(worksetSize, numNodesPerElem, spaceDim);
1881
1882 // Copy coordinates into cell workset
1883 int cellCounter = 0;
1884 for(int cell = worksetBegin; cell < worksetEnd; cell++){
1885 for (int node = 0; node < numNodesPerElem; node++) {
1886 cellWorkset(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
1887 cellWorkset(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
1888 }
1889 cellCounter++;
1890 }
1891
1892 /**********************************************************************************/
1893 /* Allocate arrays */
1894 /**********************************************************************************/
1895
1896 // Containers for Jacobians, integration measure & cubature points in workset cells
1897 FieldContainer<double> worksetJacobian (worksetSize, numCubPoints, spaceDim, spaceDim);
1898 FieldContainer<double> worksetJacobInv (worksetSize, numCubPoints, spaceDim, spaceDim);
1899 FieldContainer<double> worksetJacobDet (worksetSize, numCubPoints);
1900 FieldContainer<double> worksetCubWeights(worksetSize, numCubPoints);
1901 FieldContainer<double> worksetCubPoints (worksetSize, numCubPoints, cubDim);
1902
1903 // Containers for basis values transformed to workset cells and them multiplied by cubature weights
1904 FieldContainer<double> worksetHGBValues (worksetSize, numFieldsG, numCubPoints);
1905 FieldContainer<double> worksetHGBValuesWeighted(worksetSize, numFieldsG, numCubPoints);
1906 FieldContainer<double> worksetHGBGrads (worksetSize, numFieldsG, numCubPoints, spaceDim);
1907 FieldContainer<double> worksetHGBGradsWeighted (worksetSize, numFieldsG, numCubPoints, spaceDim);
1908
1909 // Containers for diffusive & advective fluxes & non-conservative adv. term and reactive terms
1910 FieldContainer<double> worksetDiffusiveFlux(worksetSize, numFieldsG, numCubPoints, spaceDim);
1911
1912 // Containers for material values and source term. Require user-defined functions
1913 FieldContainer<double> worksetMaterialVals (worksetSize, numCubPoints, spaceDim, spaceDim);
1914 FieldContainer<double> worksetSourceTerm (worksetSize, numCubPoints);
1915
1916 // Containers for workset contributions to the discretization matrix and the right hand side
1917 FieldContainer<double> worksetStiffMatrix (worksetSize, numFieldsG, numFieldsG);
1918 FieldContainer<double> worksetRHS (worksetSize, numFieldsG);
1919
1920 if(MyPID==0) {std::cout << msg << "Allocate arrays "
1921 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1922
1923
1924 /**********************************************************************************/
1925 /* Calculate Jacobians */
1926 /**********************************************************************************/
1927 // Due to the way setJacobian works, we need to use the basis form here
1928 // IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, cellType);
1929 IntrepidCTools::setJacobian(worksetJacobian, cubPoints, cellWorkset, myBasis_rcp);
1930 IntrepidCTools::setJacobianInv(worksetJacobInv, worksetJacobian );
1931 IntrepidCTools::setJacobianDet(worksetJacobDet, worksetJacobian );
1932
1933 //#define DEBUG_OUTPUT
1934 #ifdef DEBUG_OUTPUT
1935 printf("*** cubPoints ***\n");
1936 for(int j=0; j<numCubPoints; j++)
1937 printf("(%d) [%10.2e %10.2e]\n",j,cubPoints(j,0),cubPoints(j,1));
1938
1939 printf("*** cellWorkset ***\n");
1940 for(int i=0; i<worksetSize; i++)
1941 for(int j=0; j<numNodesPerElem; j++)
1942 printf("(%d,%d) [%10.2e %10.2e]\n",i,j,cellWorkset(i,j,0),cellWorkset(i,j,1));
1943
1944 printf("*** Jacobian ***\n");
1945 for(int i=0; i<worksetSize; i++)
1946 for(int j=0; j<numCubPoints; j++)
1947 printf("(%d,%d) [%10.2e %10.2e; %10.2e %10.2e]\n",i,j,zwrap(worksetJacobian(i,j,0,0)),zwrap(worksetJacobian(i,j,0,1)),zwrap(worksetJacobian(i,j,1,0)),zwrap(worksetJacobian(i,j,1,1)));
1948
1949 printf("*** det J ***\n");
1950 for(int i=0; i<worksetSize; i++)
1951 for(int j=0; j<numCubPoints; j++)
1952 printf("(%d,%d) %10.2e\n",i,j,zwrap(worksetJacobDet(i,j)));
1953
1954 #endif
1955
1956
1957 if(MyPID==0) {std::cout << msg << "Calculate Jacobians "
1958 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1959
1960 /**********************************************************************************/
1961 /* Cubature Points to Physical Frame and Compute Data */
1962 /**********************************************************************************/
1963
1964 // map cubature points to physical frame
1965 IntrepidCTools::mapToPhysicalFrame (worksetCubPoints, cubPoints, cellWorkset, myBasis_rcp);
1966
1967 // get A at cubature points
1968 evaluateMaterialTensor (worksetMaterialVals, worksetCubPoints);
1969
1970 // get source term at cubature points
1971 evaluateSourceTerm (worksetSourceTerm, worksetCubPoints);
1972
1973 if(MyPID==0) {std::cout << msg << "Map to physical frame and get source term "
1974 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
1975
1976
1977 /**********************************************************************************/
1978 /* Compute Stiffness Matrix */
1979 /**********************************************************************************/
1980
1981 // Transform basis gradients to physical frame:
1982 IntrepidFSTools::HGRADtransformGRAD<double>(worksetHGBGrads, // DF^{-T}(grad u)
1983 worksetJacobInv, HGBGrads);
1984
1985 // Compute integration measure for workset cells:
1986 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeights, // Det(DF)*w = J*w
1987 worksetJacobDet, cubWeights);
1988
1989
1990 // Multiply transformed (workset) gradients with weighted measure
1991 IntrepidFSTools::multiplyMeasure<double>(worksetHGBGradsWeighted, // DF^{-T}(grad u)*J*w
1992 worksetCubWeights, worksetHGBGrads);
1993
1994
1995 // Compute the diffusive flux:
1996 IntrepidFSTools::tensorMultiplyDataField<double>(worksetDiffusiveFlux, // A*(DF^{-T}(grad u)
1997 worksetMaterialVals,
1998 worksetHGBGrads);
1999
2000 // Integrate to compute workset diffusion contribution to global matrix:
2001 IntrepidFSTools::integrate<double>(worksetStiffMatrix, //(DF^{-T}(grad u)*J*w)*(A*DF^{-T}(grad u))
2002 worksetHGBGradsWeighted,
2003 worksetDiffusiveFlux, COMP_BLAS);
2004
2005 if(MyPID==0) {std::cout << msg << "Compute stiffness matrix "
2006 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
2007
2008
2009 /**********************************************************************************/
2010 /* Compute RHS */
2011 /**********************************************************************************/
2012
2013 // Transform basis values to physical frame:
2014 IntrepidFSTools::HGRADtransformVALUE<double>(worksetHGBValues, // clones basis values (u)
2015 HGBValues);
2016
2017 // Multiply transformed (workset) values with weighted measure
2018 IntrepidFSTools::multiplyMeasure<double>(worksetHGBValuesWeighted, // (u)*J*w
2019 worksetCubWeights, worksetHGBValues);
2020
2021 // Integrate worksetSourceTerm against weighted basis function set
2022 IntrepidFSTools::integrate<double>(worksetRHS, // f.(u)*J*w
2023 worksetSourceTerm,
2024 worksetHGBValuesWeighted, COMP_BLAS);
2025 #ifdef DEBUG_OUTPUT
2026 printf("*** worksetSourceTerm ***\n");
2027 for(int i=0; i<worksetSize; i++)
2028 for(int j=0; j<numCubPoints; j++)
2029 printf("(%d,%d) %10.2e\n",i,j,worksetSourceTerm(i,j));
2030
2031
2032 printf("*** worksetCubWeights ***\n");
2033 for(int i=0; i<worksetSize; i++)
2034 for(int j=0; j<numCubPoints; j++)
2035 printf("(%d,%d) %10.2e\n",i,j,worksetCubWeights(i,j));
2036
2037
2038 printf("*** worksetHGBValues ***\n");
2039 for(int i=0; i<worksetSize; i++)
2040 for(int j=0; j<numFieldsG; j++) {
2041 printf("(%d,%d) ",i,j);
2042 for(int k=0; k<numCubPoints; k++) {
2043 printf("%10.2e ",zwrap(worksetHGBValues(i,j,k)));
2044 }
2045 printf("\n");
2046 }
2047
2048 printf("*** worksetHGBValuesWeighted ***\n");
2049 for(int i=0; i<worksetSize; i++)
2050 for(int j=0; j<numFieldsG; j++) {
2051 printf("(%d,%d) ",i,j);
2052 for(int k=0; k<numCubPoints; k++) {
2053 printf("%10.2e ",zwrap(worksetHGBValues(i,j,k)));
2054 }
2055 printf("\n");
2056 }
2057
2058 printf("*** worksetRHS ***\n");
2059 for(int i=0; i<worksetSize; i++)
2060 for(int j=0; j<numFieldsG; j++)
2061 printf("(%d,%d) %10.2e\n",i,j,worksetRHS(i,j));
2062
2063 printf("*** worksetStiffMatrix ***\n");
2064 for(int i=0; i<worksetSize; i++) {
2065 printf("(%d) [ ",i);
2066 for(int j=0; j<numFieldsG; j++) {
2067 for(int k=0; k<numFieldsG; k++) {
2068 printf("%10.2e ",zwrap(worksetStiffMatrix(i,j,k)));
2069 }
2070 if(j!=numFieldsG-1) printf(";");
2071 }
2072 printf("]\n");
2073 }
2074
2075
2076
2077 #endif
2078
2079 if(MyPID==0) {std::cout << msg << "Compute right-hand side "
2080 << Time.ElapsedTime() << " sec \n"; Time.ResetStartTime();}
2081
2082 /**********************************************************************************/
2083 /* Assemble into Global Matrix and RHS */
2084 /**********************************************************************************/
2085
2086 //"WORKSET CELL" loop: local cell ordinal is relative to numElems
2087 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2088
2089 // Compute cell ordinal relative to the current workset
2090 int worksetCellOrdinal = cell - worksetBegin;
2091
2092 // "CELL EQUATION" loop for the workset cell: cellRow is relative to the cell DoF numbering
2093 for (int cellRow = 0; cellRow < numFieldsG; cellRow++){
2094
2095 int localRow = elemToNode(cell, cellRow);
2096 int globalRow = (int) globalNodeIds[localRow];
2097 double sourceTermContribution = worksetRHS(worksetCellOrdinal, cellRow);
2098
2099 rhsVector.SumIntoGlobalValues(1,&globalRow,&sourceTermContribution);
2100
2101 // "CELL VARIABLE" loop for the workset cell: cellCol is relative to the cell DoF numbering
2102 for (int cellCol = 0; cellCol < numFieldsG; cellCol++){
2103
2104 int localCol = elemToNode(cell, cellCol);
2105 int globalCol = (int) globalNodeIds[localCol];
2106 double operatorMatrixContribution = worksetStiffMatrix(worksetCellOrdinal, cellRow, cellCol);
2107 StiffMatrix.InsertGlobalValues(1, &globalRow, 1, &globalCol, &operatorMatrixContribution);
2108
2109 }// *** cell col loop ***
2110 }// *** cell row loop ***
2111 }// *** workset cell loop **
2112
2113 }// *** workset loop ***
2114
2115 } //CreateLinearSystem
2116
2117 /*********************************************************************************************************/
2118 void GenerateLinearCoarsening_pn_kirby_to_p1(const int degree,const FieldContainer<int> & Pn_elemToNode, const std::vector<bool> & Pn_nodeIsOwned,Teuchos::RCP<Basis_HGRAD_QUAD_Cn_FEM<double,FieldContainer<double> > > &PnBasis_rcp,Teuchos::RCP<Basis<double,FieldContainer<double> > > &P1Basis_rcp, Epetra_Map & P1_map, Epetra_Map & Pn_map,Teuchos::RCP<Epetra_CrsMatrix>& P) {
2119
2120 // Sanity checks
2121 assert(Pn_elemToNode.dimension(1) == PnBasis_rcp->getCardinality());
2122 assert(P1Basis_rcp->getCardinality() == 4);
2123
2124 // Generate a P matrix that uses the linear coarsening from pn to p1 on the base mesh.
2125 // This presumes that the Pn element is number according to the Kirby convention (aka straight across, bottom to top)
2126 // Resulting matrix is #Pnnodes x #P1nodes
2127 int p1_node_in_pn[4] = {0,degree, (degree+1)*(degree+1)-1, degree*(degree+1)};
2128
2129 // Get the reference coordinates for the Pn element
2130 int numFieldsPn = PnBasis_rcp->getCardinality();
2131 int spaceDim = PnBasis_rcp->getBaseCellTopology().getDimension();
2132 FieldContainer<double> PnDofCoords(numFieldsPn,spaceDim);
2133 PnBasis_rcp->getDofCoords(PnDofCoords);
2134
2135 // Evaluate the linear basis functions at the Pn nodes
2136 int numFieldsP1 = P1Basis_rcp->getCardinality();
2137 FieldContainer<double> P1Values_at_PnDofs(numFieldsP1,numFieldsPn);
2138 P1Basis_rcp->getValues(P1Values_at_PnDofs, PnDofCoords, OPERATOR_VALUE);
2139
2140 // Generate P
2141 int Nelem=Pn_elemToNode.dimension(0);
2142 P = Teuchos::rcp(new Epetra_CrsMatrix(Copy,Pn_map,0));
2143
2144 // Assemble
2145 std::vector<int> touched(P1_map.NumMyElements(),0);
2146
2147 for(int i=0; i<Nelem; i++) {
2148 for(int j=0; j<numFieldsPn; j++) {
2149 int row_lid = Pn_elemToNode(i,j);
2150 int row_gid = Pn_map.GID(row_lid);
2151 for(int k=0; k<numFieldsP1; k++) {
2152 int col_lid = Pn_elemToNode(i,p1_node_in_pn[k]);
2153 int col_gid = P1_map.GID(col_lid);
2154 double val = P1Values_at_PnDofs(k,j);
2155 if(Pn_nodeIsOwned[row_lid] && !touched[row_lid]) {
2156 P->InsertGlobalValues(row_gid,1,&val,&col_gid);
2157 touched[row_lid]=1;
2158 }
2159 }
2160 }
2161 }
2162 P->FillComplete(P1_map,Pn_map);
2163 }
2164
2165 /*********************************************************************************************************/
2166 void GenerateIdentityCoarsening_pn_to_p1(const FieldContainer<int> & Pn_elemToNode,
2167 Epetra_Map const & P1_map_aux, Epetra_Map const &Pn_map,
2168 Teuchos::RCP<Epetra_CrsMatrix> & P) {
2169
2170 // Generate prolongator matrix that will be used to transfer from P1 on auxiliary mesh to Pn on base mesh.
2171 // It's just the identity matrix.
2172 // By construction, the node numbering on the P1 auxiliary mesh is the same as on the Pn base mesh
2173 // (see CreateP1MeshFromPnMesh). The P2 map is the range map, the P1 auxiliary map is the domain map.
2174
2175 double one = 1.0;
2176 P = Teuchos::rcp(new Epetra_CrsMatrix(Copy,Pn_map,0));
2177
2178 // Identity matrices are easy - exploit the fact that the maps are identical
2179 for(int i=0; i<Pn_map.NumMyElements(); i++) {
2180 int row_gid = Pn_map.GID(i);
2181 P->InsertGlobalValues(row_gid,1,&one,&row_gid);
2182 }
2183 P->FillComplete(P1_map_aux,Pn_map);
2184 }
2185
2186
2187
2188
2189
2190 /*********************************************************************************************************/
2191 void Apply_Dirichlet_BCs(std::vector<int> BCNodes, Epetra_FECrsMatrix & A, Epetra_MultiVector & x, Epetra_MultiVector & b, const Epetra_MultiVector & soln) {
2192 int N=(int)BCNodes.size();
2193 for(int i=0; i<N; i++) {
2194 int lrid = BCNodes[i];
2195
2196 int NumEntries, *Indices;
2197 double *Values;
2198
2199 x[0][lrid]=b[0][lrid] = soln[0][lrid];
2200
2201 A.ExtractMyRowView(lrid,NumEntries,Values,Indices);
2202
2203 for(int j=0; j<NumEntries; j++)
2204 Values[j] = (Indices[j] == lrid) ? 1.0 : 0.0;
2205 }
2206 }
2207
2208
2209 /*********************************************************************************************************/
2210 void PamgenEnumerateEdges(int numNodesPerElem, int numEdgesPerElem, int numNodesPerEdge,
2211 FieldContainer<int> refEdgeToNode,const FieldContainer<double> & nodeCoord,
2212 std::vector<long long> globalNodeIds,
2213 PamgenMesh & mesh,
2214 Epetra_Comm & Comm,
2215 /*Output args */
2216 std::vector<long long> & globalEdgeIds,
2217 std::vector<bool> & edgeIsOwned,
2218 std::vector<int> & ownedEdgeIds,
2219 FieldContainer<int> &elemToEdge, FieldContainer<int> & elemToEdgeOrient, FieldContainer<int> &edgeToNode,FieldContainer<double> & edgeCoord,
2220 long long & numEdgesGlobal) {
2221 std::vector < topo_entity * > edge_vector;
2222 std::set < topo_entity * , fecomp > edge_set;
2223 std::vector < int > edge_comm_procs;
2224 int rank = Comm.MyPID();
2225
2226 /***** Hensinger Stuff *****/
2227 // Calculate edge and ids
2228 int elct = 0;
2229 for(long long b = 0; b < mesh.numElemBlk; b++){
2230 //loop over all elements and push their edges onto a set if they are not there already
2231 for(long long el = 0; el < mesh.elements[b]; el++){
2232 std::set< topo_entity *, fecomp > ::iterator fit;
2233 for (int i=0; i < numEdgesPerElem; i++){
2234 topo_entity * teof = new topo_entity;
2235 for(int j = 0; j < numNodesPerEdge;j++)
2236 teof->add_node(mesh.elmt_node_linkage[b][el*numNodesPerElem + refEdgeToNode(i,j)],globalNodeIds.data());
2237 teof->sort();
2238 fit = edge_set.find(teof);
2239 if(fit == edge_set.end()){
2240 teof->local_id = edge_vector.size();
2241 edge_set.insert(teof);
2242 // printf("[%d] Adding edge %d to element %d/%d\n",Comm.MyPID(),edge_vector.size(),elct,elemToEdge.dimension(0));fflush(stdout);
2243 elemToEdge(elct,i)= edge_vector.size();
2244 edge_vector.push_back(teof);
2245 }
2246 else{
2247 elemToEdge(elct,i) = (*fit)->local_id;
2248 delete teof;
2249 }
2250 }
2251 elct ++;
2252 }
2253 }
2254
2255 // Edge to Node connectivity
2256 assert(numNodesPerEdge==2);
2257 edgeToNode.resize(edge_vector.size(), numNodesPerEdge);
2258 for(unsigned ect = 0; ect != edge_vector.size(); ect++){
2259 int n[2];
2260 std::list<long long>::iterator elit=edge_vector[ect]->local_node_ids.begin();
2261 n[0] = *elit-1;
2262 elit++;
2263 n[1] = *elit-1;
2264 long long nid0 = globalNodeIds[n[0]];
2265 long long nid1 = globalNodeIds[n[1]];
2266 long long lo = std::min(nid0,nid1);
2267 edgeToNode(ect,0)= (lo==nid0)? n[0] : n[1];
2268 edgeToNode(ect,1)= (lo==nid0)? n[1] : n[0];
2269 }
2270
2271
2272 int numEdges = edge_vector.size();
2273
2274 // Calculate global edge and face numbering
2275 std::string doing_type;
2276 doing_type = "EDGES";
2277 calc_global_ids(edge_vector,
2278 mesh.comm_node_ids.data(),
2279 mesh.node_comm_proc_ids.data(),
2280 mesh.node_cmap_node_cnts.data(),
2281 mesh.num_node_comm_maps,
2282 rank,
2283 doing_type);
2284
2285 // Build list of owned global edge ids
2286 globalEdgeIds.resize(numEdges);
2287 edgeIsOwned.resize(numEdges);
2288 int numOwnedEdges=0;
2289 for (int i=0; i<numEdges; i++) {
2290 edgeIsOwned[i] = edge_vector[i]->owned;
2291 globalEdgeIds[i] = edge_vector[i]->global_id;
2292 if (edgeIsOwned[i]){
2293 numOwnedEdges++;
2294 }
2295 }
2296 ownedEdgeIds.resize(numOwnedEdges);
2297 int nedge=0;
2298 for (int i=0; i<numEdges; i++) {
2299 if (edgeIsOwned[i]){
2300 ownedEdgeIds[nedge]=(int)globalEdgeIds[i];
2301 nedge++;
2302 }
2303 }
2304
2305 // Calculate number of global edges
2306 #ifdef HAVE_MPI
2307 long long numOwnedEdges_ll = numOwnedEdges;
2308 Comm.SumAll(&numOwnedEdges_ll,&numEdgesGlobal,1);
2309 #else
2310 numEdgesGlobal = numEdges;
2311 #endif
2312
2313 assert(numNodesPerEdge==2);
2314
2315 /***** Non-Hensinger Stuff ****/
2316 // Fill out the edge centers (clobbering data if needed)
2317 edgeCoord.resize(numEdges,mesh.dim);
2318 for (int i=0; i<numEdges; i++) {
2319 for(int j=0; j<mesh.dim; j++) {
2320 edgeCoord(i,j)=0;
2321 for(int k=0; k<numNodesPerEdge; k++)
2322 edgeCoord(i,j)+=nodeCoord(edgeToNode(i,k),j)/numNodesPerEdge;
2323 }
2324 }
2325
2326 //#define DEBUG_EDGE_ENUMERATION
2327 #ifdef DEBUG_EDGE_ENUMERATION
2328 printf("**** New Edge coordinates ***\n");
2329 for(int i=0; i<edgeCoord.dimension(0); i++)
2330 printf("[%2d] %10.2f %10.2f\n",i,edgeCoord(i,0),edgeCoord(i,1));
2331 #endif
2332
2333 // Build the element edge orientation list
2334 int elid=0;
2335 for(long long b = 0; b < mesh.numElemBlk; b++){
2336 for(long long el = 0; el < mesh.elements[b]; el++){
2337 for (int i=0; i < numEdgesPerElem; i++){
2338 int edge = elemToEdge(elid,i);
2339 int n0 = mesh.elmt_node_linkage[b][el*numNodesPerElem + refEdgeToNode(i,0)]-1;
2340 elemToEdgeOrient(elid,i) = (n0==edgeToNode(edge,0))? 1 : -1;
2341 }
2342 elid++;
2343 }
2344 }
2345
2346 }
2347
2348
2349
2350 /*********************************************************************************************************/
2351 void EnumerateElements(Epetra_Comm & Comm, int numMyElements, std::vector<long long> & globalElementIds) {
2352 long long numMyElements_ll = numMyElements;
2353 long long myGlobalElementBase = 0;
2354
2355 Comm.ScanSum(&numMyElements_ll,&myGlobalElementBase,1);
2356 myGlobalElementBase -=numMyElements;
2357 // printf("[%d] MyGlobalElementBase = %lld\n",Comm.MyPID(),myGlobalElementBase);
2358
2359 globalElementIds.resize(numMyElements);
2360 for(int i=0; i<numMyElements; i++)
2361 globalElementIds[i] = myGlobalElementBase + i;
2362 }
2363
2364
2365
2366
2367 /**********************************************************************************/
2368 /**************************** CALCULATE ERROR *************************************/
2369 /**********************************************************************************/
2370 void CalculateError(const Epetra_FEVector & femCoefficients, const Epetra_Map &overlapMap,Epetra_Time & Time, shards::CellTopology &Pn_cellType, Teuchos::RCP<Basis<double,FieldContainer<double> > > myHGradBasis_rcp, const FieldContainer<int> & elemToNode, const FieldContainer<double> & nodeCoord, int degree) {
2371
2372 const Epetra_BlockMap & globalMapG = femCoefficients.Map();
2373 const Epetra_Comm & Comm = globalMapG.Comm();
2374 int MyPID = Comm.MyPID();
2375 int numFieldsG = myHGradBasis_rcp->getCardinality();
2376 int spaceDim = Pn_cellType.getDimension();
2377 int numElems = elemToNode.dimension(0);
2378 string msg("Poisson: ");
2379
2380 if (MyPID == 0) {Time.ResetStartTime();}
2381
2382 double L2err = 0.0;
2383 double L2errTot = 0.0;
2384 double H1err = 0.0;
2385 double H1errTot = 0.0;
2386 double Linferr = 0.0;
2387 double LinferrTot = 0.0;
2388
2389 #ifdef HAVE_MPI
2390 // Get ghost information from solution to compute error
2391 Epetra_Import solnImporter(overlapMap, globalMapG);
2392 Epetra_Vector uCoeff(overlapMap);
2393 uCoeff.Import(femCoefficients, solnImporter, Insert);
2394 #endif
2395
2396 // Define desired workset size
2397 int desiredWorksetSize = numElems;
2398 int numWorksetsErr = numElems/desiredWorksetSize;
2399
2400 // When numElems is not divisible by desiredWorksetSize, increase workset count by 1
2401 if(numWorksetsErr*desiredWorksetSize < numElems) numWorksetsErr += 1;
2402
2403 // Get cubature points and weights for error calc (may be different from previous)
2404 Intrepid::DefaultCubatureFactory<double> cubFactoryErr;
2405 int cubDegErr = 3*degree;
2406 Teuchos::RCP<Intrepid::Cubature<double> > cellCubatureErr = cubFactoryErr.create(Pn_cellType, cubDegErr);
2407 int cubDimErr = cellCubatureErr->getDimension();
2408 int numCubPointsErr = cellCubatureErr->getNumPoints();
2409 Intrepid::FieldContainer<double> cubPointsErr(numCubPointsErr, cubDimErr);
2410 Intrepid::FieldContainer<double> cubWeightsErr(numCubPointsErr);
2411 cellCubatureErr->getCubature(cubPointsErr, cubWeightsErr);
2412
2413 // Evaluate basis values and gradients at cubature points
2414 Intrepid::FieldContainer<double> uhGVals(numFieldsG, numCubPointsErr);
2415 Intrepid::FieldContainer<double> uhGrads(numFieldsG, numCubPointsErr, spaceDim);
2416 myHGradBasis_rcp->getValues(uhGVals, cubPointsErr, Intrepid::OPERATOR_VALUE);
2417 myHGradBasis_rcp->getValues(uhGrads, cubPointsErr, Intrepid::OPERATOR_GRAD);
2418
2419 // Loop over worksets
2420 for(int workset = 0; workset < numWorksetsErr; workset++){
2421
2422 // compute cell numbers where the workset starts and ends
2423 int worksetSize = 0;
2424 int worksetBegin = (workset + 0)*desiredWorksetSize;
2425 int worksetEnd = (workset + 1)*desiredWorksetSize;
2426
2427 // when numElems is not divisible by desiredWorksetSize, the last workset ends at numElems
2428 worksetEnd = (worksetEnd <= numElems) ? worksetEnd : numElems;
2429
2430 // now we know the actual workset size and can allocate the array for the cell nodes
2431 worksetSize = worksetEnd - worksetBegin;
2432 Intrepid::FieldContainer<double> cellWorksetEr(worksetSize, numFieldsG, spaceDim);
2433 Intrepid::FieldContainer<double> worksetApproxSolnCoef(worksetSize, numFieldsG);
2434
2435 // loop over cells to fill arrays with coordinates and discrete solution coefficient
2436 int cellCounter = 0;
2437 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2438
2439 for (int node = 0; node < numFieldsG; node++) {
2440 cellWorksetEr(cellCounter, node, 0) = nodeCoord( elemToNode(cell, node), 0);
2441 cellWorksetEr(cellCounter, node, 1) = nodeCoord( elemToNode(cell, node), 1);
2442
2443 int rowIndex = elemToNode(cell, node);
2444 #ifdef HAVE_MPI
2445 worksetApproxSolnCoef(cellCounter, node) = uCoeff.Values()[rowIndex];
2446 #else
2447 worksetApproxSolnCoef(cellCounter, node) = femCoefficients.Values()[rowIndex];
2448 #endif
2449 }
2450
2451 cellCounter++;
2452
2453 } // end cell loop
2454
2455 // Containers for Jacobian
2456 Intrepid::FieldContainer<double> worksetJacobianE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
2457 Intrepid::FieldContainer<double> worksetJacobInvE(worksetSize, numCubPointsErr, spaceDim, spaceDim);
2458 Intrepid::FieldContainer<double> worksetJacobDetE(worksetSize, numCubPointsErr);
2459 Intrepid::FieldContainer<double> worksetCubWeightsE(worksetSize, numCubPointsErr);
2460
2461 // Containers for basis values and gradients in physical space
2462 Intrepid::FieldContainer<double> uhGValsTrans(worksetSize,numFieldsG, numCubPointsErr);
2463 Intrepid::FieldContainer<double> uhGradsTrans(worksetSize, numFieldsG, numCubPointsErr, spaceDim);
2464
2465 // compute cell Jacobians, their inverses and their determinants
2466 IntrepidCTools::setJacobian(worksetJacobianE, cubPointsErr, cellWorksetEr, myHGradBasis_rcp);
2467 IntrepidCTools::setJacobianInv(worksetJacobInvE, worksetJacobianE );
2468 IntrepidCTools::setJacobianDet(worksetJacobDetE, worksetJacobianE );
2469
2470 // map cubature points to physical frame
2471 Intrepid::FieldContainer<double> worksetCubPoints(worksetSize, numCubPointsErr, cubDimErr);
2472 IntrepidCTools::mapToPhysicalFrame(worksetCubPoints, cubPointsErr, cellWorksetEr, myHGradBasis_rcp);
2473
2474 // evaluate exact solution and gradient at cubature points
2475 Intrepid::FieldContainer<double> worksetExactSoln(worksetSize, numCubPointsErr);
2476 Intrepid::FieldContainer<double> worksetExactSolnGrad(worksetSize, numCubPointsErr, spaceDim);
2477 evaluateExactSolution(worksetExactSoln, worksetCubPoints);
2478 evaluateExactSolutionGrad(worksetExactSolnGrad, worksetCubPoints);
2479
2480 // transform basis values to physical coordinates
2481 IntrepidFSTools::HGRADtransformVALUE<double>(uhGValsTrans, uhGVals);
2482 IntrepidFSTools::HGRADtransformGRAD<double>(uhGradsTrans, worksetJacobInvE, uhGrads);
2483
2484 // compute weighted measure
2485 IntrepidFSTools::computeCellMeasure<double>(worksetCubWeightsE, worksetJacobDetE, cubWeightsErr);
2486
2487 // evaluate the approximate solution and gradient at cubature points
2488 Intrepid::FieldContainer<double> worksetApproxSoln(worksetSize, numCubPointsErr);
2489 Intrepid::FieldContainer<double> worksetApproxSolnGrad(worksetSize, numCubPointsErr, spaceDim);
2490 IntrepidFSTools::evaluate<double>(worksetApproxSoln, worksetApproxSolnCoef, uhGValsTrans);
2491 IntrepidFSTools::evaluate<double>(worksetApproxSolnGrad, worksetApproxSolnCoef, uhGradsTrans);
2492
2493 // get difference between approximate and exact solutions
2494 Intrepid::FieldContainer<double> worksetDeltaSoln(worksetSize, numCubPointsErr);
2495 Intrepid::FieldContainer<double> worksetDeltaSolnGrad(worksetSize, numCubPointsErr, spaceDim);
2496 IntrepidRSTools::subtract(worksetDeltaSoln, worksetApproxSoln, worksetExactSoln);
2497 IntrepidRSTools::subtract(worksetDeltaSolnGrad, worksetApproxSolnGrad, worksetExactSolnGrad);
2498
2499 // take absolute values
2500 IntrepidRSTools::absval(worksetDeltaSoln);
2501 IntrepidRSTools::absval(worksetDeltaSolnGrad);
2502 // apply cubature weights to differences in values and grads for use in integration
2503 Intrepid::FieldContainer<double> worksetDeltaSolnWeighted(worksetSize, numCubPointsErr);
2504 Intrepid::FieldContainer<double> worksetDeltaSolnGradWeighted(worksetSize, numCubPointsErr, spaceDim);
2505 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnWeighted,
2506 worksetCubWeightsE, worksetDeltaSoln);
2507 IntrepidFSTools::scalarMultiplyDataData<double>(worksetDeltaSolnGradWeighted,
2508 worksetCubWeightsE, worksetDeltaSolnGrad);
2509
2510 // integrate to get errors on each element
2511 Intrepid::FieldContainer<double> worksetL2err(worksetSize);
2512 Intrepid::FieldContainer<double> worksetH1err(worksetSize);
2513 IntrepidFSTools::integrate<double>(worksetL2err, worksetDeltaSoln,
2514 worksetDeltaSolnWeighted, Intrepid::COMP_BLAS);
2515 IntrepidFSTools::integrate<double>(worksetH1err, worksetDeltaSolnGrad,
2516 worksetDeltaSolnGradWeighted, Intrepid::COMP_BLAS);
2517
2518 // loop over cells to get errors for total workset
2519 cellCounter = 0;
2520 for(int cell = worksetBegin; cell < worksetEnd; cell++){
2521
2522 // loop over cubature points
2523 for(int nPt = 0; nPt < numCubPointsErr; nPt++){
2524
2525 Linferr = std::max(Linferr, worksetDeltaSoln(cellCounter,nPt));
2526
2527 }
2528
2529 L2err += worksetL2err(cellCounter);
2530 H1err += worksetH1err(cellCounter);
2531
2532 cellCounter++;
2533
2534 } // end cell loop
2535
2536 } // end loop over worksets
2537
2538 #ifdef HAVE_MPI
2539 // sum over all processors
2540 Comm.SumAll(&L2err,&L2errTot,1);
2541 Comm.SumAll(&H1err,&H1errTot,1);
2542 Comm.MaxAll(&Linferr,&LinferrTot,1);
2543 #else
2544 L2errTot = L2err;
2545 H1errTot = H1err;
2546 LinferrTot = Linferr;
2547 #endif
2548
2549
2550 if (MyPID == 0) {
2551 std::cout << "\n" << "L2 Error: " << sqrt(L2errTot) <<"\n";
2552 std::cout << "H1 Error: " << sqrt(H1errTot) <<"\n";
2553 std::cout << "LInf Error: " << LinferrTot <<"\n\n";
2554 }
2555
2556 if(MyPID==0) {std::cout << msg << "Calculate error "
2557 << Time.ElapsedTime() << " s \n"; Time.ResetStartTime();}
2558
2559
2560 }