Debian Codegraph @

packages/panzer/adapters-stk/test/projection/projection.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Panzer: A partial differential equation assembly
4 // engine for strongly coupled complex multiphysics systems
5 //
6 // Copyright 2011 NTESS and the Panzer contributors.
7 // SPDX-License-Identifier: BSD-3-Clause
8 // *****************************************************************************
9 // @HEADER
10
11 // Panzer STK
12 #include "PanzerAdaptersSTK_config.hpp"
13 #include "Panzer_STK_Interface.hpp"
14 #include "Panzer_STK_CubeHexMeshFactory.hpp"
15 #include "Panzer_STK_SquareQuadMeshFactory.hpp"
16 #include "Panzer_STK_SquareTriMeshFactory.hpp"
17 #include "Panzer_STK_WorksetFactory.hpp"
18 #include "Panzer_STKConnManager.hpp"
19
20 // Panzer
21 #include "Panzer_Workset.hpp"
22 #include "Panzer_WorksetDescriptor.hpp"
23 #include "Panzer_WorksetNeeds.hpp"
24 #include "Panzer_WorksetContainer.hpp"
25 #include "Panzer_IntegrationDescriptor.hpp"
26 #include "Panzer_OrientationsInterface.hpp"
27 #include "Panzer_BasisDescriptor.hpp"
28 #include "Panzer_Evaluator_DomainInterface.hpp"
29 #include "Panzer_Traits.hpp"
30 #include "Panzer_Evaluator_WithBaseImpl.hpp"
31 #include "Panzer_IntrepidBasisFactory.hpp"
32 #include "Panzer_IntrepidOrientation.hpp"
33 #include "Panzer_L2Projection.hpp"
34 #include "Panzer_DOFManager.hpp"
35 #include "Panzer_BlockedDOFManager.hpp"
36 #include "Panzer_BlockedTpetraLinearObjFactory.hpp"
37
38 //Intrepid2
39 #include "Intrepid2_Orientation.hpp"
40 #include "Intrepid2_LagrangianInterpolation.hpp"
41
42 #include "Tpetra_Vector.hpp"
43 #include "Tpetra_CrsMatrix.hpp"
44 #include "TpetraExt_MatrixMatrix.hpp"
45
46 // Teuchos
47 #include "Teuchos_DefaultMpiComm.hpp"
48 #include "Teuchos_RCP.hpp"
49 #include "Teuchos_TimeMonitor.hpp"
50 #include "Teuchos_UnitTestHarness.hpp"
51 #include "Teuchos_TimeMonitor.hpp"
52 #include "Teuchos_StackedTimer.hpp"
53
54 // Solver
55 #include "BelosSolverFactory.hpp"
56 #include "BelosMultiVecTraits_Tpetra.hpp"
57 #include "BelosOperatorTraits_Tpetra.hpp"
58 #include "BelosTpetraAdapter.hpp"
59 #include "BelosLinearProblem.hpp"
60
61 #include <memory>
62 #include <vector>
63 #include <string>
64 #include <cmath>
65
66 TEUCHOS_UNIT_TEST(L2Projection, ToNodal)
67 {
68 using namespace Teuchos;
69 using namespace panzer;
70 using namespace panzer_stk;
71
72 RCP<MpiComm<int>> comm = rcp(new MpiComm<int>(MPI_COMM_WORLD));
73
74 auto timer = Teuchos::TimeMonitor::getStackedTimer();
75 timer->start("Total Time");
76
77 const int myRank = comm->getRank();
78 const int numProcs = comm->getSize();
79 const int numXElements = 3;
80 const int numYElements = numXElements;
81 const int numZElements = numXElements;
82 const double boxLength = 1.0;
83 TEUCHOS_ASSERT(numXElements >= numProcs);
84
85 RCP<panzer_stk::STK_Interface> mesh;
86 {
87 PANZER_FUNC_TIME_MONITOR("L2Projection: mesh construction");
88 Teuchos::RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
89 pl->set("X Blocks",1);
90 pl->set("Y Blocks",1);
91 pl->set("Z Blocks",1);
92 pl->set("X Elements",numXElements);
93 pl->set("Y Elements",numYElements);
94 pl->set("Z Elements",numZElements);
95 pl->set("X Procs",numProcs);
96 pl->set("Y Procs",1);
97 pl->set("Z Procs",1);
98 pl->set("X0",0.0);
99 pl->set("Y0",0.0);
100 pl->set("Z0",0.0);
101 pl->set("Xf",boxLength);
102 pl->set("Yf",boxLength);
103 pl->set("Zf",boxLength);
104 panzer_stk::CubeHexMeshFactory factory;
105 factory.setParameterList(pl);
106 mesh = factory.buildUncommitedMesh(MPI_COMM_WORLD);
107 factory.completeMeshConstruction(*mesh,MPI_COMM_WORLD);
108 }
109
110 // Build Worksets
111
112 const int basisOrder = 1;
113 BasisDescriptor hgradBD(basisOrder,"HGrad");
114 BasisDescriptor hcurlBD(basisOrder,"HCurl");
115 BasisDescriptor hdivBD(basisOrder,"HDiv");
116
117 const int intOrder = 2;
118 IntegrationDescriptor integrationDescriptor(intOrder,IntegrationDescriptor::VOLUME);
119
120 // Build Connection Manager
121 using LO = int;
122 using GO = panzer::GlobalOrdinal;
123 timer->start("ConnManager ctor");
124 const RCP<panzer_stk::STKConnManager> connManager = rcp(new panzer_stk::STKConnManager(mesh));
125 timer->stop("ConnManager ctor");
126
127 // Set up bases for projections
128 std::vector<std::string> eBlockNames;
129 mesh->getElementBlockNames(eBlockNames);
130 auto cellTopology = mesh->getCellTopology(eBlockNames[0]);
131 auto dim = cellTopology->getDimension();
132
133 auto hgradBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hgradBD.getType(),hgradBD.getOrder(),*cellTopology);
134 RCP<const panzer::FieldPattern> hgradFP(new panzer::Intrepid2FieldPattern(hgradBasis));
135
136 auto curlBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hcurlBD.getType(),hcurlBD.getOrder(),*cellTopology);
137 RCP<const panzer::FieldPattern> hcurlFP(new panzer::Intrepid2FieldPattern(curlBasis));
138
139 auto divBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hdivBD.getType(),hdivBD.getOrder(),*cellTopology);
140 RCP<const panzer::FieldPattern> hdivFP(new panzer::Intrepid2FieldPattern(divBasis));
141
142 // ****************
143 // Testing ghosting
144 // ****************
145 // This shows that the new workset construction path does not
146 // provide a full one-ring but only supplies ghosted elements on
147 // faces of owned elements.
148 const bool printGhostingInfo = true;
149 if (printGhostingInfo) {
150 PANZER_FUNC_TIME_MONITOR("L2Projection: test ghosting (build connectivity)");
151 out.setShowProcRank(true);
152 out.setOutputToRootOnly(myRank);
153 connManager->buildConnectivity(*hgradFP);
154 for (const auto& block : eBlockNames) {
155 const auto& localElements = connManager->getElementBlock(block);
156 const auto& ghostElements = connManager->getNeighborElementBlock(block);
157 out << "block=" << block << ", numOwnedElements = " << localElements.size()
158 << ", numGhostedElements = " << ghostElements.size() << std::endl;
159 for (const auto& e : localElements) {
160 auto cellSize = connManager->getConnectivitySize(e);
161 auto conn = connManager->getConnectivity(e);
162 std::stringstream os;
163 os << "owned lid=" << e << ", cellSize=" << cellSize << ", conn=";
164 for (int i=0; i < cellSize; ++i)
165 os << conn[i] << ",";
166 out << os.str() << std::endl;
167 }
168 for (const auto& e : ghostElements) {
169 auto cellSize = connManager->getConnectivitySize(e);
170 auto conn = connManager->getConnectivity(e);
171 std::stringstream os;
172 os << "ghosted lid=" << e << ", cellSize=" << cellSize << ", conn=";
173 for (int i=0; i < cellSize; ++i)
174 os << conn[i] << ",";
175 out << os.str() << std::endl;
176 }
177 }
178 out.setOutputToRootOnly(0);
179 }
180 // ****************
181 // ****************
182
183 // Build source DOF Manager that mimics multi-fluid plasma dof manager
184 timer->start("Build sourceGlobalIndexer");
185 RCP<panzer::DOFManager> sourceGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
186 sourceGlobalIndexer->addField("PHI",hgradFP); // Electric Potential for ES
187 sourceGlobalIndexer->addField("Chaff0",hgradFP); // Dummy
188 sourceGlobalIndexer->addField("Chaff1",hgradFP); // Dummy
189 sourceGlobalIndexer->addField("Chaff2",hgradFP); // Dummy
190 sourceGlobalIndexer->addField("E_Field",hcurlFP); // Electric Field for EM
191 sourceGlobalIndexer->addField("B_Field",hdivFP); // Magnetic Field for EM
192 sourceGlobalIndexer->buildGlobalUnknowns();
193 timer->stop("Build sourceGlobalIndexer");
194
195 // Build Target DOF Manager (Separate scalar fields on hgrad)
196 timer->start("Build targetGlobalIndexer");
197 RCP<panzer::DOFManager> targetGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
198 targetGlobalIndexer->addField("Projection to Mesh Vertices",hgradFP);
199 targetGlobalIndexer->buildGlobalUnknowns();
200 timer->stop("Build targetGlobalIndexer");
201
202 // Create worksets
203 RCP<WorksetContainer> worksetContainer;
204 {
205 RCP<WorksetFactory> worksetFactory(new WorksetFactory(mesh));
206 worksetFactory->setOrientationsInterface(rcp(new OrientationsInterface(sourceGlobalIndexer)));
207 worksetContainer = rcp(new WorksetContainer(worksetFactory));
208 }
209
210 // Build projection factory
211 timer->start("projectionFactory.setup()");
212 panzer::L2Projection projectionFactory;
213 projectionFactory.setup(hgradBD,integrationDescriptor,comm,connManager,eBlockNames,worksetContainer);
214 timer->stop("projectionFactory.setup()");
215
216
217
218
219
220 // Ignore the workset factory and set the basis directly
221 bool ignoreWorksetFactory = true;
222 std::map<std::string,Teuchos::RCP<panzer::BasisValues2<double>>> map_basis_values;
223 if (ignoreWorksetFactory) {
224
225 // Get the orientations for all element blocks
226 std::map<std::string,std::vector<Intrepid2::Orientation>> orientations;
227 panzer::buildIntrepidOrientations(eBlockNames,*connManager,orientations);
228
229 std::vector<shards::CellTopology> topologies;
230 connManager->getElementBlockTopologies(topologies);
231
232 for (size_t i=0; i < eBlockNames.size(); ++i) {
233
234 const auto& eblock = eBlockNames[i];
235 const auto& topo = topologies[i];
236
237 // Get nodal coordinates for integration rules
238 std::vector<std::size_t> lids;
239 panzer::Intrepid2FieldPattern coord_fp(hgradBasis);
240 Kokkos::DynRankView<double,PHX::Device> nodal_coords_kokkos;
241 connManager->getDofCoords(eblock,coord_fp,lids,nodal_coords_kokkos);
242
243 // This is ugly. Need to fix connManager interface for layouts (fad vs non-fad).
244 PHX::MDField<double,panzer::Cell,panzer::BASIS,panzer::Dim> nodal_coords("nodal_coords","<Cell,BASIS,Dim>",
245 nodal_coords_kokkos.extent(0),
246 nodal_coords_kokkos.extent(1),
247 nodal_coords_kokkos.extent(2));
248 Kokkos::deep_copy(nodal_coords.get_view(),nodal_coords_kokkos);
249
250 // Build IV
251 Teuchos::RCP<shards::CellTopology> rcp_topo = Teuchos::rcp(new shards::CellTopology(topo.getCellTopologyData()));
252 Teuchos::RCP<panzer::IntegrationRule> ir = Teuchos::rcp(new panzer::IntegrationRule(integrationDescriptor,rcp_topo,static_cast<int>(nodal_coords_kokkos.extent(0))));
253 Teuchos::RCP<panzer::IntegrationValues2<double>> iv = Teuchos::rcp(new panzer::IntegrationValues2<double>);
254 iv->setup(ir,nodal_coords);
255
256 // Build BV
257 Teuchos::RCP<panzer::BasisValues2<double>> bv = Teuchos::rcp(new panzer::BasisValues2<double>);
258 Teuchos::RCP<panzer::BasisIRLayout> birl = Teuchos::rcp(new panzer::BasisIRLayout(hgradBD.getType(),hgradBD.getOrder(),*ir));
259 bv->setupUniform(birl,
260 iv->getUniformCubaturePointsRef(true),
261 iv->getJacobian(true),
262 iv->getJacobianDeterminant(true),
263 iv->getJacobianInverse(true));
264 bv->setOrientations(orientations[eblock]);
265 bv->setWeightedMeasure(iv->getWeightedMeasure(true));
266 bv->setCellNodeCoordinates(nodal_coords);
267 map_basis_values[eblock] = bv;
268 }
269 projectionFactory.useBasisValues(map_basis_values);
270 }
271
272
273
274
275
276 TEST_ASSERT(nonnull(projectionFactory.getTargetGlobalIndexer()));
277
278 // Build mass matrix
279 timer->start("projectionFactory.buildMassMatrix()");
280 auto massMatrix = projectionFactory.buildMassMatrix();
281 timer->stop("projectionFactory.buildMassMatrix()");
282 massMatrix->print(out);
283 massMatrix->getRowMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
284 massMatrix->getColMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
285
286 // Build rhs matrix
287 timer->start("projectionFactory.buildRHSMatrix()");
288 const int xDir = 0;
289 const int yDir = 1;
290 const int zDir = 2;
291 using NodeType = Tpetra::KokkosCompat::KokkosDeviceWrapperNode<PHX::Device>;
292 auto rhsMatrix_PHI = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD); // Project value from scalar basis
293 auto rhsMatrix_DPHI_DX = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD,xDir); // Project gradient from scalar basis
294 auto rhsMatrix_DPHI_DY = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD,yDir); // Project gradient from scalar basis
295 auto rhsMatrix_DPHI_DZ = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD,zDir); // Project gradient from scalar basis
296 auto rhsMatrix_E0 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"E_Field",hcurlBD,xDir); // Project value from vector basis
297 auto rhsMatrix_E1 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"E_Field",hcurlBD,yDir); // Project value from vector basis
298 auto rhsMatrix_E2 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"E_Field",hcurlBD,zDir); // Project value from vector basis
299 auto rhsMatrix_B0 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"B_Field",hdivBD,xDir); // Project value from vector basis
300 auto rhsMatrix_B1 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"B_Field",hdivBD,yDir); // Project value from vector basis
301 auto rhsMatrix_B2 = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"B_Field",hdivBD,zDir); // Project value from vector basis
302 timer->stop("projectionFactory.buildRHSMatrix()");
303
304 // Store in vector for convenience
305 std::vector<RCP<Tpetra::CrsMatrix<double,LO,GO,NodeType>>> rhsMatrices;
306 rhsMatrices.push_back(rhsMatrix_PHI);
307 rhsMatrices.push_back(rhsMatrix_DPHI_DX);
308 rhsMatrices.push_back(rhsMatrix_DPHI_DY);
309 rhsMatrices.push_back(rhsMatrix_DPHI_DZ);
310 rhsMatrices.push_back(rhsMatrix_E0);
311 rhsMatrices.push_back(rhsMatrix_E1);
312 rhsMatrices.push_back(rhsMatrix_E2);
313 rhsMatrices.push_back(rhsMatrix_B0);
314 rhsMatrices.push_back(rhsMatrix_B1);
315 rhsMatrices.push_back(rhsMatrix_B2);
316
317 // Create a Names vector for output
318 std::vector<std::string> names;
319 names.push_back("PHI");
320 names.push_back("DPHI_DX");
321 names.push_back("DPHI_DY");
322 names.push_back("DPHI_DZ");
323 names.push_back("E0");
324 names.push_back("E1");
325 names.push_back("E2");
326 names.push_back("B0");
327 names.push_back("B1");
328 names.push_back("B2");
329
330 // Allocate the source vector
331 timer->start("Allocate Source Vector");
332 using VectorType = Tpetra::Vector<double,LO,GO,NodeType>;
333 auto sourceValues = rcp(new VectorType(rhsMatrix_PHI->getDomainMap(),true));
334 timer->stop("Allocate Source Vector");
335
336 // Fill the source vector.
337 timer->start("Fill Source Vector");
338
339 using DynRankView = Kokkos::DynRankView<double,PHX::Device>;
340 using DynRankViewIntHost = Kokkos::DynRankView<int,Kokkos::HostSpace>;
341 {
342 const int PHI_Index = sourceGlobalIndexer->getFieldNum("PHI");
343 const int E_Index = sourceGlobalIndexer->getFieldNum("E_Field");
344 const int B_Index = sourceGlobalIndexer->getFieldNum("B_Field");
345
346 std::vector<std::string> elementBlockNames;
347 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
348 for (const auto& block : elementBlockNames) {
349
350 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
351 const auto worksets = worksetContainer->getWorksets(wd);
352 for (const auto& workset : *worksets) {
353
354
355 //Initialize orientation tools
356 DynRankViewIntHost ownedNodesGID("ownedNodesGID", workset.numOwnedCells(), cellTopology->getNodeCount());
357 for (int e = 0; e < (int)workset.numOwnedCells(); ++e) {
358 auto conn = connManager->getConnectivity(e);
359 for(int j=0; j< (int)cellTopology->getNodeCount(); ++j)
360 ownedNodesGID(e,j) = conn[j];
361 }
362 Kokkos::DynRankView<Intrepid2::Orientation,PHX::Device> elemOrts("elemOrts", workset.numOwnedCells());
363 Intrepid2::OrientationTools<PHX::Device>::getOrientation(elemOrts, ownedNodesGID, *cellTopology);
364
365 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
366 sourceGlobalIndexer->getElementBlockGIDCount(block));
367 // Remove the ghosted cell ids or the call to getElementLocalIds will spill array bounds
368 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
369 sourceGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
370
371 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
372 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
373
374 // Create vector to store if LID is owned
375 timer->start("Create isOwned view");
376 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
377 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
378 {
379 std::vector<GO> cellGIDs(localIds.extent(1));
380 std::vector<bool> cellOwnedIds(localIds.extent(1));
381 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
382 sourceGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
383 sourceGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
384 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
385 isOwned_h(cell,i) = cellOwnedIds[i];
386 }
387 }
388 timer->stop("Create isOwned view");
389
390 Kokkos::deep_copy(isOwned, isOwned_h);
391
392 const auto offsetsPHI = sourceGlobalIndexer->getGIDFieldOffsetsKokkos(block,PHI_Index);
393 const auto offsetsE = sourceGlobalIndexer->getGIDFieldOffsetsKokkos(block,E_Index);
394 const auto offsetsB = sourceGlobalIndexer->getGIDFieldOffsetsKokkos(block,B_Index);
395 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
396 const auto& coords = basisValues.getBasisCoordinates();
397 const auto& x = sourceValues->getLocalViewDevice(Tpetra::Access::ReadWrite);
398 const int numBasisPHI = static_cast<int>(offsetsPHI.extent(0));
399 const int numBasisE = static_cast<int>(offsetsE.extent(0));
400 const int numBasisB = static_cast<int>(offsetsB.extent(0));
401 using li = Intrepid2::LagrangianInterpolation<PHX::Device>;
402
403 //Computing HGRAD coefficients for PHI to interpolate function f(x,y,z) = 1+x+2y+3z
404 DynRankView basisCoeffsPHI("basisCoeffsPHI", workset.numOwnedCells(), numBasisPHI);
405 {
406 DynRankView dofCoordsPHI("dofCoordsPHI", numBasisPHI, dim);
407 hgradBasis->getDofCoords(dofCoordsPHI);
408
409 //map the reference Dof coordinates into physical frame
410 DynRankView physCoordsPHI("physCoordsPHI", workset.numOwnedCells(), numBasisPHI, dim);
411 auto wsCoords = Kokkos::subview(coords.get_view(), std::pair<int,int>(0, workset.numOwnedCells()), Kokkos::ALL(), Kokkos::ALL());
412 Intrepid2::CellTools<PHX::Device>::mapToPhysicalFrame(physCoordsPHI,dofCoordsPHI,wsCoords,*cellTopology);
413
414 //evaluate the function f at the coordinates physCoordsPHI
415 DynRankView functValuesAtDofCoordsPHI("funPHI", workset.numOwnedCells(), numBasisPHI);
416 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
417 for (int basis=0; basis < numBasisPHI; ++basis)
418 functValuesAtDofCoordsPHI(cell, basis) = 1.0 + physCoordsPHI(cell,basis,0) + 2.0 * physCoordsPHI(cell,basis,1)
419 + 3.0 * physCoordsPHI(cell,basis,2);
420 });
421
422 //compute basis coefficients
423 li::getBasisCoeffs(basisCoeffsPHI, functValuesAtDofCoordsPHI, hgradBasis.getRawPtr(), elemOrts);
424 }
425
426
427 //Computing HCURL coefficients for E to interpolate the constant vector [1,1,1]
428 DynRankView basisCoeffsE("basisCoeffsE", workset.numOwnedCells(), numBasisE);
429 {
430 //Because the function is constant, we do not need the DoF coordinates.
431 //DynRankView dofCoordsE("dofCoordsE", numBasisE, dim);
432 //curlBasis->getDofCoords(dofCoordsE);
433
434
435
436 // Evaluate the function (in the physical frame) and map it back to the reference frame
437 // In order to map an HCurl function back to the reference frame we need to multiply it
438 // by J^T (J being the Jacobian of the map from reference to physical frame)
439 // In our case J is diagonal with entries equal to boxLength/2.0/numXElements,
440 // where 2 is the length of the reference cell edge.
441 DynRankView functValuesAtDofCoordsE("funE", workset.numOwnedCells(), numBasisE,dim);
442 double curlScaling = boxLength/2.0/numXElements;
443 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
444 for (int basis=0; basis < numBasisE; ++basis)
445 for (int d = 0; d < (int)dim; d++)
446 functValuesAtDofCoordsE(cell,basis,d) = curlScaling*1.0;
447 });
448
449 //compute basis coefficients
450 li::getBasisCoeffs(basisCoeffsE, functValuesAtDofCoordsE, curlBasis.getRawPtr(), elemOrts);
451 }
452
453 /*
454 // Alternative way of computing HCurl coefficients with L2 projection
455 #include "Intrepid2_ProjectionTools.hpp"
456 using pts = Intrepid2::ProjectionTools<PHX::Device>;
457 DynRankView basisCoeffsE("basisCoeffsE", workset.numOwnedCells(), numBasisE);
458 {
459 int targetCubDegree(0);
460 Intrepid2::ProjectionStruct<PHX::Device,double> projStruct;
461 projStruct.createL2DGProjectionStruct(curlBasis, targetCubDegree);
462 int numPoints = projStruct.getNumTargetEvalPoints();
463 //DynRankView evalPoints("evalPoints", elemOrts, workset.numOwnedCells(), numPoints, dim);
464 //auto evalPoints = projStruct->getAllEvalPoints();
465
466 DynRankView functValuesAtEvalPoints("funE", workset.numOwnedCells(), numPoints ,dim);
467 double curlScaling = boxLength/2.0/numXElements;
468 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
469 for (int pt=0; pt < numPoints; ++pt)
470 for (int d = 0; d < (int)dim; d++)
471 functValuesAtEvalPoints(cell,pt,d) = curlScaling*1.0;
472 });
473 pts::getL2DGBasisCoeffs(basisCoeffsE,
474 functValuesAtEvalPoints,
475 elemOrts,
476 curlBasis.getRawPtr(),
477 &projStruct);
478 }
479 */
480
481
482 //Computing HDIV coefficients for B to interpolate the constant vector [1,1,1]
483 DynRankView basisCoeffsB("basisCoeffsB", workset.numOwnedCells(), numBasisB);
484 {
485 // Evaluate the function (in the physical frame) and map it back to the reference frame
486 // In order to map an HDiv function back to the reference frame we need to multiply it
487 // by det(J) J^(-1) (J being the Jacobian of the map from reference to physical frame)
488 // In our case J is diagonal with entries equal to boxLength/2.0/numXElements,
489 // where 2 is the length of the reference cell edge, so
490 // det(J) J^(-1) = (boxLength/2.0/numXElements)^2 I
491 DynRankView functValuesAtDofCoordsB("funB", workset.numOwnedCells(), numBasisB, dim);
492 double divScaling = std::pow(boxLength/2.0/numXElements,2);
493 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
494 for (int basis=0; basis < numBasisB; ++basis)
495 for (int d = 0; d < (int)dim; ++d)
496 functValuesAtDofCoordsB(cell, basis,d) = divScaling * 1.0;
497 });
498
499 //compute basis coefficients
500 li::getBasisCoeffs(basisCoeffsB, functValuesAtDofCoordsB, divBasis.getRawPtr(), elemOrts);
501 }
502
503
504
505 // fill the vector of basis coefficients x
506 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
507 for (int basis=0; basis < numBasisPHI; ++basis) {
508 const int lid = localIds(cell,offsetsPHI(basis));
509 if (isOwned(cell,offsetsPHI(basis))) {
510 x(lid,0) = basisCoeffsPHI(cell,basis);
511 }
512 }
513 for (int basis=0; basis < numBasisE; ++basis) {
514 const int lid = localIds(cell,offsetsE(basis));
515 if (isOwned(cell,offsetsE(basis)))
516 x(lid,0) = basisCoeffsE(cell,basis);;
517 }
518 for (int basis=0; basis < numBasisB; ++basis) {
519 const int lid = localIds(cell,offsetsB(basis));
520 if (isOwned(cell,offsetsB(basis)))
521 x(lid,0) = basisCoeffsB(cell,basis);
522 }
523 });
524 }
525 }
526 }
527
528 timer->stop("Fill Source Vector");
529
530 // Assemble RHS vectors using matvec
531 timer->start("Allocate RHS Vectors");
532 auto rhs_PHI = rcp(new VectorType(massMatrix->getDomainMap(),true));
533 auto rhs_DPHI_DX = rcp(new VectorType(massMatrix->getDomainMap(),true));
534 auto rhs_DPHI_DY = rcp(new VectorType(massMatrix->getDomainMap(),true));
535 auto rhs_DPHI_DZ = rcp(new VectorType(massMatrix->getDomainMap(),true));
536 auto rhs_E0 = rcp(new VectorType(massMatrix->getDomainMap(),true));
537 auto rhs_E1 = rcp(new VectorType(massMatrix->getDomainMap(),true));
538 auto rhs_E2 = rcp(new VectorType(massMatrix->getDomainMap(),true));
539 auto rhs_B0 = rcp(new VectorType(massMatrix->getDomainMap(),true));
540 auto rhs_B1 = rcp(new VectorType(massMatrix->getDomainMap(),true));
541 auto rhs_B2 = rcp(new VectorType(massMatrix->getDomainMap(),true));
542 timer->stop("Allocate RHS Vectors");
543
544 // Store in vector for convenience
545 std::vector<RCP<VectorType>> rhs;
546 rhs.push_back(rhs_PHI);
547 rhs.push_back(rhs_DPHI_DX);
548 rhs.push_back(rhs_DPHI_DY);
549 rhs.push_back(rhs_DPHI_DZ);
550 rhs.push_back(rhs_E0);
551 rhs.push_back(rhs_E1);
552 rhs.push_back(rhs_E2);
553 rhs.push_back(rhs_B0);
554 rhs.push_back(rhs_B1);
555 rhs.push_back(rhs_B2);
556
557 timer->start("Assemble RHS Vectors");
558 for (size_t i=0; i < rhs.size(); ++i)
559 rhsMatrices[i]->apply(*sourceValues,*rhs[i]);
560 timer->stop("Assemble RHS Vectors");
561
562 // Build RHS Multivector target for efficient consistent matrix solve
563 timer->start("Copy RHS Values into MV");
564 const auto targetRangeMap = massMatrix->getRangeMap();
565 const int numVectors = 10; // PHI, DPHI_DX, DPHI_XY, DPHI_DZ, E, B
566 const auto rhsMV = rcp(new Tpetra::MultiVector<double,LO,GO,NodeType>(targetRangeMap,numVectors,false));
567 const auto mvView = rhsMV->getLocalViewDevice(Tpetra::Access::OverwriteAll);
568 TEST_EQUALITY(mvView.extent(1),static_cast<size_t>(numVectors));
569 for (int col=0; col < numVectors; ++col) {
570 const auto source = rhs[col]->getLocalViewDevice(Tpetra::Access::ReadOnly);
571 const int numEntries = source.extent(0);
572 Kokkos::parallel_for(numEntries, KOKKOS_LAMBDA (const int& i) { mvView(i,col) = source(i,0); });
573 typename PHX::Device().fence();
574 }
575 timer->stop("Copy RHS Values into MV");
576
577 // Solve the multiple matrices
578 using MV = Tpetra::MultiVector<double,LO,GO,NodeType>;
579 using OP = Tpetra::Operator<double,LO,GO,NodeType>;
580 const auto solutionMV = rcp(new Tpetra::MultiVector<double,LO,GO,NodeType>(targetRangeMap,numVectors,true));
581 const auto problem = rcp(new Belos::LinearProblem<double,MV,OP>(massMatrix, solutionMV, rhsMV));
582 problem->setProblem();
583
584 TEST_ASSERT(nonnull(massMatrix));
585 TEST_ASSERT(nonnull(solutionMV));
586 TEST_ASSERT(nonnull(rhsMV));
587 TEST_ASSERT(nonnull(problem));
588
589 timer->start("Create Belos Solver");
590 RCP<ParameterList> pl = parameterList("L2 Consistent Projection Linear Solver");
591 pl->set("Num Blocks", 100); // Max Krylov vectors to store
592 pl->set("Maximum Iterations", 100);
593 pl->set("Convergence Tolerance", 1e-8);
594 pl->set("output Frequency",1); // all iterations
595 pl->set("Verbosity", Belos::Errors | Belos::Warnings | Belos::IterationDetails| Belos::FinalSummary);
596 Belos::SolverFactory<double,MV,OP> belosFactory;
597 const auto solver = belosFactory.create("GMRES",pl);
598 solver->setProblem(problem);
599 timer->stop("Create Belos Solver");
600
601 timer->start("Belos Solve");
602 const auto result = solver->solve();
603 timer->stop("Belos Solve");
604
605 TEST_EQUALITY(result,Belos::Converged);
606
607 // Check the final values on host
608 timer->start("Check CONSISTENT Projected Values on Host");
609 {
610 const auto hostValues = solutionMV->getLocalViewHost(Tpetra::Access::ReadOnly);
611 typename PHX::Device().fence();
612
613 const int phiIndex = 0;
614 const int dphiDxIndex = 1;
615 const int dphiDyIndex = 2;
616 const int dphiDzIndex = 3;
617 const int exIndex = 4;
618 const int eyIndex = 5;
619 const int ezIndex = 6;
620 const int bxIndex = 7;
621 const int byIndex = 8;
622 const int bzIndex = 9;
623 double tol = 1.0e-4;
624
625 std::vector<std::string> elementBlockNames;
626 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
627 for (const auto& block : elementBlockNames) {
628
629 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
630 const auto worksets = worksetContainer->getWorksets(wd);
631 for (const auto& workset : *worksets) {
632 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
633 targetGlobalIndexer->getElementBlockGIDCount(block));
634 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
635 targetGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
636
637 auto localIds_h = Kokkos::create_mirror_view(localIds);
638 Kokkos::deep_copy(localIds_h, localIds);
639
640 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
641 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
642
643 // Create vector to store if LID is owned
644 timer->start("Create isOwned view");
645 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
646 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
647 {
648 std::vector<GO> cellGIDs(localIds.extent(1));
649 std::vector<bool> cellOwnedIds(localIds.extent(1));
650 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
651 targetGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
652 targetGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
653 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
654 isOwned_h(cell,i) = cellOwnedIds[i];
655 }
656 }
657 timer->stop("Create isOwned view");
658
659 const auto offsets = targetGlobalIndexer->getGIDFieldOffsets(block,0);
660 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
661 const auto& coords = basisValues.getBasisCoordinates();
662 auto coords_h = Kokkos::create_mirror_view(PHX::as_view(coords));
663 Kokkos::deep_copy(coords_h, PHX::as_view(coords));
664 const int numBasis = static_cast<int>(offsets.size());
665
666 for (int cell=0; cell < workset.numOwnedCells(); ++cell) {
667 for (int basis=0; basis < numBasis; ++basis) {
668 if (isOwned_h(cell,offsets[basis])) {
669 const int lid = localIds_h(cell,offsets[basis]);
670 const double phiGold = 1.0 + coords_h(cell,basis,0) + 2.0 * coords_h(cell,basis,1)
671 + 3.0 * coords_h(cell,basis,2);
672
673 //Note: here we are relying on the fact that, for low order HGRAD basis,
674 //the basis coefficients are the values of the function at the nodes
675 TEST_FLOATING_EQUALITY(hostValues(lid,phiIndex), phiGold, tol);
676 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDxIndex), 1.0, tol);
677 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDyIndex), 2.0, tol);
678 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDzIndex), 3.0, tol);
679 TEST_FLOATING_EQUALITY(hostValues(lid,exIndex), 1.0, tol);
680 TEST_FLOATING_EQUALITY(hostValues(lid,eyIndex), 1.0, tol);
681 TEST_FLOATING_EQUALITY(hostValues(lid,ezIndex), 1.0, tol);
682 TEST_FLOATING_EQUALITY(hostValues(lid,bxIndex), 1.0, tol);
683 TEST_FLOATING_EQUALITY(hostValues(lid,byIndex), 1.0, tol);
684 TEST_FLOATING_EQUALITY(hostValues(lid,bzIndex), 1.0, tol);
685 }
686 }
687 }
688 }
689 }
690 }
691 timer->stop("Check CONSISTENT Projected Values on Host");
692
693 // ***************************
694 // Now test lumped mass matrix
695 // ***************************
696 timer->start("projectionFactory.buildInverseLumpedMassMatrix()");
697 auto invLumpedMassMatrix = projectionFactory.buildInverseLumpedMassMatrix();
698 timer->stop("projectionFactory.buildInverseLumpedMassMatrix()");
699
700 timer->start("apply lumped mass matrix");
701 {
702 auto x = solutionMV->getLocalViewDevice(Tpetra::Access::OverwriteAll);
703 auto rhsMV_k = rhsMV->getLocalViewDevice(Tpetra::Access::ReadOnly);
704 const auto ilmm = invLumpedMassMatrix->getLocalViewDevice(Tpetra::Access::ReadOnly);
705 const int numEntries = static_cast<int>(x.extent(0));
706 Kokkos::parallel_for(numEntries,KOKKOS_LAMBDA (const int i)
707 {
708 for (int field=0; field < numVectors; ++field)
709 x(i,field) = ilmm(i,0) * rhsMV_k(i,field);
710 });
711 typename PHX::Device().fence();
712 }
713 timer->stop("apply lumped mass matrix");
714
715 // Check the final values on host
716 timer->start("Check LUMPED Projected Values on Host");
717 {
718 const auto hostValues = solutionMV->getLocalViewHost(Tpetra::Access::ReadOnly);
719 typename PHX::Device().fence();
720
721 const int phiIndex = 0;
722 const int dphiDxIndex = 1;
723 const int dphiDyIndex = 2;
724 const int dphiDzIndex = 3;
725 const int exIndex = 4;
726 const int eyIndex = 5;
727 const int ezIndex = 6;
728 const int bxIndex = 7;
729 const int byIndex = 8;
730 const int bzIndex = 9;
731 // NOTE: Lumping generates significant errors when the meshes are
732 // very coarse (such as in this unit test). We see
733 // superconvergence on the interior points of this axis aligned
734 // mesh and for the constant fields, thus can can tighten the
735 // tolerances for some fields. Refining the mesh results in more
736 // accurate projected values.
737 double looseTol = 0.5;
738 double superconvergedTol = 1.0e-4;
739
740 std::vector<std::string> elementBlockNames;
741 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
742 for (const auto& block : elementBlockNames) {
743
744 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
745 const auto worksets = worksetContainer->getWorksets(wd);
746 for (const auto& workset : *worksets) {
747 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
748 targetGlobalIndexer->getElementBlockGIDCount(block));
749 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
750 targetGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
751
752 auto localIds_h = Kokkos::create_mirror_view(localIds);
753 Kokkos::deep_copy(localIds_h, localIds);
754
755 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
756 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
757
758 // Create vector to store if LID is owned
759 timer->start("Create isOwned view");
760 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
761 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
762 {
763 std::vector<GO> cellGIDs(localIds.extent(1));
764 std::vector<bool> cellOwnedIds(localIds.extent(1));
765 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
766 targetGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
767 targetGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
768 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
769 isOwned_h(cell,i) = cellOwnedIds[i];
770 }
771 }
772 timer->stop("Create isOwned view");
773
774 const auto offsets = targetGlobalIndexer->getGIDFieldOffsets(block,0);
775 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
776 const auto& coords = basisValues.getBasisCoordinates();
777 auto coords_h = Kokkos::create_mirror_view(PHX::as_view(coords));
778 Kokkos::deep_copy(coords_h, PHX::as_view(coords));
779 const int numBasis = static_cast<int>(offsets.size());
780
781 for (int cell=0; cell < workset.numOwnedCells(); ++cell) {
782 for (int basis=0; basis < numBasis; ++basis) {
783 if (isOwned_h(cell,offsets[basis])) {
784 const int lid = localIds_h(cell,offsets[basis]);
785 const double phiGold = 1.0 + coords_h(cell,basis,0) + 2.0 * coords_h(cell,basis,1)
786 + 3.0 * coords_h(cell,basis,2);
787
788 //Note: here we are relying on the fact that, for low order HGRAD basis,
789 //the basis coefficients are the values of the function at the nodes
790 TEST_FLOATING_EQUALITY(hostValues(lid,phiIndex), phiGold, looseTol);
791 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDxIndex), 1.0, superconvergedTol);
792 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDyIndex), 2.0, superconvergedTol);
793 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDzIndex), 3.0, superconvergedTol);
794 TEST_FLOATING_EQUALITY(hostValues(lid,exIndex), 1.0, superconvergedTol);
795 TEST_FLOATING_EQUALITY(hostValues(lid,eyIndex), 1.0, superconvergedTol);
796 TEST_FLOATING_EQUALITY(hostValues(lid,ezIndex), 1.0, superconvergedTol);
797 TEST_FLOATING_EQUALITY(hostValues(lid,bxIndex), 1.0, superconvergedTol);
798 TEST_FLOATING_EQUALITY(hostValues(lid,byIndex), 1.0, superconvergedTol);
799 TEST_FLOATING_EQUALITY(hostValues(lid,bzIndex), 1.0, superconvergedTol);
800 }
801 }
802 }
803 }
804 }
805 }
806 timer->stop("Check LUMPED Projected Values on Host");
807
808 timer->stop("Total Time");
809
810 Teuchos::StackedTimer::OutputOptions options;
811 options.output_fraction = true;
812 options.output_minmax = true;
813 options.output_histogram = false;
814 options.num_histogram = 5;
815 timer->report(out,comm,options);
816 }
817
818 TEUCHOS_UNIT_TEST(L2Projection, CurlMassMatrix)
819 {
820 using namespace Teuchos;
821 using namespace panzer;
822 using namespace panzer_stk;
823
824 RCP<MpiComm<int>> comm = rcp(new MpiComm<int>(MPI_COMM_WORLD));
825
826 auto timer = Teuchos::TimeMonitor::getStackedTimer();
827 timer->start("Total Time");
828
829 const int numProcs = comm->getSize();
830 const int numXElements = 4;
831 const int numYElements = 2;
832 const double boxLength = 1.0;
833 const double boxHeight = 0.5;
834 TEUCHOS_ASSERT(numXElements >= numProcs);
835
836 RCP<panzer_stk::STK_Interface> mesh;
837 {
838 PANZER_FUNC_TIME_MONITOR("L2Projection: mesh construction");
839 Teuchos::RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
840 pl->set("X Blocks",1);
841 pl->set("Y Blocks",1);
842 pl->set("X Elements",numXElements);
843 pl->set("Y Elements",numYElements);
844 pl->set("X Procs",numProcs);
845 pl->set("Y Procs",1);
846 pl->set("X0",0.0);
847 pl->set("Y0",0.0);
848 pl->set("Xf",boxLength);
849 pl->set("Yf",boxHeight);
850 panzer_stk::SquareQuadMeshFactory factory;
851 factory.setParameterList(pl);
852 mesh = factory.buildUncommitedMesh(MPI_COMM_WORLD);
853 factory.completeMeshConstruction(*mesh,MPI_COMM_WORLD);
854 }
855
856 // Build Worksets
857
858 const int basisOrder = 1;
859 BasisDescriptor hcurlBD(basisOrder,"HCurl");
860 BasisDescriptor hdivBD(basisOrder,"HDiv");
861
862 const int intOrder = 2;
863 IntegrationDescriptor integrationDescriptor(intOrder,IntegrationDescriptor::VOLUME);
864
865 // Build Connection Manager
866 using LO = int;
867 using GO = panzer::GlobalOrdinal;
868 timer->start("ConnManager ctor");
869 const RCP<panzer::ConnManager> connManager = rcp(new panzer_stk::STKConnManager(mesh));
870 timer->stop("ConnManager ctor");
871
872 // Set up bases for projections
873 std::vector<std::string> eBlockNames;
874 mesh->getElementBlockNames(eBlockNames);
875 auto cellTopology = mesh->getCellTopology(eBlockNames[0]);
876
877 auto curlBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hcurlBD.getType(),hcurlBD.getOrder(),*cellTopology);
878 RCP<const panzer::FieldPattern> hcurlFP(new panzer::Intrepid2FieldPattern(curlBasis));
879
880 auto divBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hdivBD.getType(),hdivBD.getOrder(),*cellTopology);
881 RCP<const panzer::FieldPattern> hdivFP(new panzer::Intrepid2FieldPattern(divBasis));
882
883 // Build source DOF Manager for edge and face DOFs
884 timer->start("Build sourceGlobalIndexer");
885 RCP<panzer::BlockedDOFManager> sourceGlobalIndexer = rcp(new panzer::BlockedDOFManager(connManager,*comm->getRawMpiComm()));
886 sourceGlobalIndexer->addField("E_Field",hcurlFP); // Electric Field for EM
887 sourceGlobalIndexer->addField("B_Field",hdivFP); // Magnetic Field for EM
888 sourceGlobalIndexer->buildGlobalUnknowns();
889 timer->stop("Build sourceGlobalIndexer");
890
891 // Create worksets
892 RCP<WorksetContainer> worksetContainer;
893 {
894 RCP<WorksetFactory> worksetFactory(new WorksetFactory(mesh));
895 worksetFactory->setOrientationsInterface(rcp(new OrientationsInterface(sourceGlobalIndexer)));
896 worksetContainer = rcp(new WorksetContainer(worksetFactory));
897 }
898
899 // Build projection factory
900 timer->start("projectionFactory.setup()");
901 panzer::L2Projection projectionFactory;
902 projectionFactory.setup(hcurlBD,integrationDescriptor,comm,connManager,eBlockNames,worksetContainer);
903 timer->stop("projectionFactory.setup()");
904
905 TEST_ASSERT(nonnull(projectionFactory.getTargetGlobalIndexer()));
906
907 // Build mass matrix
908 timer->start("projectionFactory.buildMassMatrix()");
909 auto curlMassMatrix = projectionFactory.buildMassMatrix();
910 timer->stop("projectionFactory.buildMassMatrix()");
911 curlMassMatrix->print(out);
912 curlMassMatrix->getRowMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
913 curlMassMatrix->getColMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
914
915 // Build the mass matrix from connectivity knowing that this is a regular quad mesh
916 timer->start("build mass matrix from connectivity");
917
918 // get local ids
919 auto e_ugi = sourceGlobalIndexer->getFieldDOFManagers()[sourceGlobalIndexer->getFieldBlock(sourceGlobalIndexer->getFieldNum("E_Field"))];
920 auto lids = e_ugi->getLIDs();
921
922 // set up a global and ghosted mass matrix
923 std::vector<Teuchos::RCP<const panzer::GlobalIndexer>> indexers;
924 indexers.push_back(e_ugi);
925 panzer::BlockedTpetraLinearObjFactory<panzer::Traits,double,LO,GO,panzer::TpetraNodeType> factory(comm,indexers);
926 auto connMassMatrix = factory.getTpetraMatrix(0,0);
927 auto ghostedMatrix = factory.getGhostedTpetraMatrix(0,0);
928 connMassMatrix->resumeFill();
929 connMassMatrix->setAllToScalar(0.0);
930 ghostedMatrix->resumeFill();
931 ghostedMatrix->setAllToScalar(0.0);
932 typename PHX::Device().fence();
933
934 // fill in the mass matrix
935 // the integral of the edge basis squared over one cell is 4/3
936 // the integral of the edge basis times the basis function across from it in the element is 2/3
937 {
938 const auto localMass = ghostedMatrix->getLocalMatrixDevice();
939 const int numElems = lids.extent(0);
940 Kokkos::parallel_for(numElems, KOKKOS_LAMBDA (const int& i) {
941 double row_values[2]={4.0/3.0,2.0/3.0};
942 LO cols[2];
943 for(int r = 0; r < 4; r++){
944 cols[0] = lids(i,r);
945 cols[1] = lids(i,(r+2)%4);
946 localMass.sumIntoValues(lids(i,r),cols,2,row_values,false,true);
947 }
948 });
949 typename PHX::Device().fence();
950 }
951
952 ghostedMatrix->fillComplete();
953 const auto exporter = factory.getGhostedExport(0);
954 connMassMatrix->doExport(*ghostedMatrix, *exporter, Tpetra::ADD);
955 connMassMatrix->fillComplete();
956 timer->stop("build mass matrix from connectivity");
957
958 connMassMatrix->print(out);
959 connMassMatrix->getRowMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
960 connMassMatrix->getColMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
961
962 // compute difference between the two versions of the mass matrix
963 using NodeType = Tpetra::KokkosCompat::KokkosDeviceWrapperNode<PHX::Device>;
964 auto difference = Tpetra::MatrixMatrix::add<double,LO,GO,NodeType>(1.0,false,*curlMassMatrix,-1.0,false,*connMassMatrix);
965 double error = difference->getFrobeniusNorm();
966 double norm = connMassMatrix->getFrobeniusNorm();
967 double tol = 1.0e-14;
968 TEST_COMPARE(error,<,tol*norm);
969 }
970
971 // This is to demonstrate the issue with row sum lumping as opposed to
972 // proportional lumping.
973 TEUCHOS_UNIT_TEST(L2Projection, HighOrderTri)
974 {
975 using namespace Teuchos;
976 using namespace panzer;
977 using namespace panzer_stk;
978
979 RCP<MpiComm<int>> comm = rcp(new MpiComm<int>(MPI_COMM_WORLD));
980
981 auto timer = Teuchos::TimeMonitor::getStackedTimer();
982 timer->start("Total Time");
983
984 const int numProcs = comm->getSize();
985 const int numXElements = 3;
986 const int numYElements = numXElements;
987 const double boxLength = 1.0;
988 TEUCHOS_ASSERT(numXElements >= numProcs);
989
990 RCP<panzer_stk::STK_Interface> mesh;
991 {
992 PANZER_FUNC_TIME_MONITOR("L2Projection: mesh construction");
993 Teuchos::RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
994 pl->set("X Blocks",1);
995 pl->set("Y Blocks",1);
996 pl->set("X Elements",numXElements);
997 pl->set("Y Elements",numYElements);
998 pl->set("X Procs",numProcs);
999 pl->set("Y Procs",1);
1000 pl->set("X0",0.0);
1001 pl->set("Y0",0.0);
1002 pl->set("Xf",boxLength);
1003 pl->set("Yf",boxLength);
1004 panzer_stk::SquareTriMeshFactory factory;
1005 factory.setParameterList(pl);
1006 mesh = factory.buildUncommitedMesh(MPI_COMM_WORLD);
1007 factory.completeMeshConstruction(*mesh,MPI_COMM_WORLD);
1008 }
1009
1010 // Build Worksets
1011
1012 const int basisOrder = 1;
1013 BasisDescriptor hgradBD(basisOrder,"HGrad");
1014
1015 const int intOrder = 2;
1016 IntegrationDescriptor integrationDescriptor(intOrder,IntegrationDescriptor::VOLUME);
1017
1018 // Build Connection Manager
1019 using LO = int;
1020 using GO = panzer::GlobalOrdinal;
1021 timer->start("ConnManager ctor");
1022 const RCP<panzer::ConnManager> connManager = rcp(new panzer_stk::STKConnManager(mesh));
1023 timer->stop("ConnManager ctor");
1024
1025 // Set up bases for projections
1026 std::vector<std::string> eBlockNames;
1027 mesh->getElementBlockNames(eBlockNames);
1028 auto cellTopology = mesh->getCellTopology(eBlockNames[0]);
1029
1030 auto hgradBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hgradBD.getType(),hgradBD.getOrder(),*cellTopology);
1031 RCP<const panzer::FieldPattern> hgradFP(new panzer::Intrepid2FieldPattern(hgradBasis));
1032
1033 // Build source DOF Manager that mimics multi-fluid plasma dof manager
1034 timer->start("Build sourceGlobalIndexer");
1035 RCP<panzer::DOFManager> sourceGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
1036 sourceGlobalIndexer->addField("PHI",hgradFP); // Electric Potential for ES
1037 sourceGlobalIndexer->addField("Chaff0",hgradFP); // Dummy
1038 sourceGlobalIndexer->addField("Chaff1",hgradFP); // Dummy
1039 sourceGlobalIndexer->addField("Chaff2",hgradFP); // Dummy
1040 sourceGlobalIndexer->buildGlobalUnknowns();
1041 timer->stop("Build sourceGlobalIndexer");
1042
1043 // Build Target DOF Manager (Separate scalar fields on hgrad)
1044 timer->start("Build targetGlobalIndexer");
1045 RCP<panzer::DOFManager> targetGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
1046 targetGlobalIndexer->addField("Projection to Mesh Vertices",hgradFP);
1047 targetGlobalIndexer->buildGlobalUnknowns();
1048 timer->stop("Build targetGlobalIndexer");
1049
1050 // Create worksets
1051 RCP<WorksetContainer> worksetContainer;
1052 {
1053 RCP<WorksetFactory> worksetFactory(new WorksetFactory(mesh));
1054 worksetFactory->setOrientationsInterface(rcp(new OrientationsInterface(sourceGlobalIndexer)));
1055 worksetContainer = rcp(new WorksetContainer(worksetFactory));
1056 }
1057
1058 // Build projection factory
1059 timer->start("projectionFactory.setup()");
1060 panzer::L2Projection projectionFactory;
1061 projectionFactory.setup(hgradBD,integrationDescriptor,comm,connManager,eBlockNames,worksetContainer);
1062 timer->stop("projectionFactory.setup()");
1063
1064 TEST_ASSERT(nonnull(projectionFactory.getTargetGlobalIndexer()));
1065
1066 // Build mass matrix
1067 timer->start("projectionFactory.buildMassMatrix()");
1068 auto massMatrix = projectionFactory.buildMassMatrix();
1069 timer->stop("projectionFactory.buildMassMatrix()");
1070 massMatrix->print(out);
1071 massMatrix->getRowMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
1072 massMatrix->getColMap()->describe(out,Teuchos::EVerbosityLevel::VERB_EXTREME);
1073
1074 // Build rhs matrix
1075 timer->start("projectionFactory.buildRHSMatrix()");
1076 const int xDir = 0;
1077 const int yDir = 1;
1078 using NodeType = Tpetra::KokkosCompat::KokkosDeviceWrapperNode<PHX::Device>;
1079 auto rhsMatrix_PHI = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD); // Project value from scalar basis
1080 auto rhsMatrix_DPHI_DX = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD,xDir); // Project gradient from scalar basis
1081 auto rhsMatrix_DPHI_DY = projectionFactory.buildRHSMatrix(*sourceGlobalIndexer,Teuchos::null,"PHI",hgradBD,yDir); // Project gradient from scalar basis
1082 timer->stop("projectionFactory.buildRHSMatrix()");
1083
1084 // Store in vector for convenience
1085 std::vector<RCP<Tpetra::CrsMatrix<double,LO,GO,NodeType>>> rhsMatrices;
1086 rhsMatrices.push_back(rhsMatrix_PHI);
1087 rhsMatrices.push_back(rhsMatrix_DPHI_DX);
1088 rhsMatrices.push_back(rhsMatrix_DPHI_DY);
1089
1090 // Create a Names vector for output
1091 std::vector<std::string> names;
1092 names.push_back("PHI");
1093 names.push_back("DPHI_DX");
1094 names.push_back("DPHI_DY");
1095
1096 // Allocate the source vector
1097 timer->start("Allocate Source Vector");
1098 using VectorType = Tpetra::Vector<double,LO,GO,NodeType>;
1099 auto sourceValues = rcp(new VectorType(rhsMatrix_PHI->getDomainMap(),true));
1100 timer->stop("Allocate Source Vector");
1101
1102 // Fill the source vector.
1103 timer->start("Fill Source Vector");
1104 {
1105 const int PHI_Index = sourceGlobalIndexer->getFieldNum("PHI");
1106
1107 std::vector<std::string> elementBlockNames;
1108 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
1109 for (const auto& block : elementBlockNames) {
1110
1111 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
1112 const auto worksets = worksetContainer->getWorksets(wd);
1113 for (const auto& workset : *worksets) {
1114
1115 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
1116 sourceGlobalIndexer->getElementBlockGIDCount(block));
1117 // Remove the ghosted cell ids or the call to getElementLocalIds will spill array bounds
1118 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
1119 sourceGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
1120
1121 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
1122 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
1123
1124 // Create vector to store if LID is owned
1125 timer->start("Create isOwned view");
1126 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
1127 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
1128 {
1129 std::vector<GO> cellGIDs(localIds.extent(1));
1130 std::vector<bool> cellOwnedIds(localIds.extent(1));
1131 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
1132 sourceGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
1133 sourceGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
1134 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
1135 isOwned_h(cell,i) = cellOwnedIds[i];
1136 }
1137 }
1138 timer->stop("Create isOwned view");
1139
1140 Kokkos::deep_copy(isOwned, isOwned_h);
1141
1142 const auto offsetsPHI = sourceGlobalIndexer->getGIDFieldOffsetsKokkos(block,PHI_Index);
1143 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
1144 const auto& coords = basisValues.getBasisCoordinates().get_view();
1145 const auto& x = sourceValues->getLocalViewDevice(Tpetra::Access::OverwriteAll);
1146 const int numBasisPHI = static_cast<int>(offsetsPHI.extent(0));
1147
1148 Kokkos::parallel_for(workset.numOwnedCells(),KOKKOS_LAMBDA (const int& cell) {
1149 for (int basis=0; basis < numBasisPHI; ++basis) {
1150 const int lid = localIds(cell,offsetsPHI(basis));
1151 if (isOwned(cell,offsetsPHI(basis)))
1152 x(lid,0) = 1.0 + coords(cell,basis,0) + 2.0 * coords(cell,basis,1);
1153 }
1154 });
1155 }
1156 }
1157 }
1158
1159 timer->stop("Fill Source Vector");
1160
1161 // Assemble RHS vectors using matvec
1162 timer->start("Allocate RHS Vectors");
1163 auto rhs_PHI = rcp(new VectorType(massMatrix->getDomainMap(),true));
1164 auto rhs_DPHI_DX = rcp(new VectorType(massMatrix->getDomainMap(),true));
1165 auto rhs_DPHI_DY = rcp(new VectorType(massMatrix->getDomainMap(),true));
1166 timer->stop("Allocate RHS Vectors");
1167
1168 // Store in vector for convenience
1169 std::vector<RCP<VectorType>> rhs;
1170 rhs.push_back(rhs_PHI);
1171 rhs.push_back(rhs_DPHI_DX);
1172 rhs.push_back(rhs_DPHI_DY);
1173
1174 timer->start("Assemble RHS Vectors");
1175 for (size_t i=0; i < rhs.size(); ++i)
1176 rhsMatrices[i]->apply(*sourceValues,*rhs[i]);
1177 timer->stop("Assemble RHS Vectors");
1178
1179 // Build RHS Multivector target for efficient consistent matrix solve
1180 timer->start("Copy RHS Values into MV");
1181 const auto targetRangeMap = massMatrix->getRangeMap();
1182 const int numVectors = 3; // PHI, DPHI_DX, DPHI_XY
1183 const auto rhsMV = rcp(new Tpetra::MultiVector<double,LO,GO,NodeType>(targetRangeMap,numVectors,false));
1184 const auto mvView = rhsMV->getLocalViewDevice(Tpetra::Access::OverwriteAll);
1185 TEST_EQUALITY(mvView.extent(1),static_cast<size_t>(numVectors));
1186 for (int col=0; col < numVectors; ++col) {
1187 const auto source = rhs[col]->getLocalViewDevice(Tpetra::Access::ReadOnly);
1188 const int numEntries = source.extent(0);
1189 Kokkos::parallel_for(numEntries, KOKKOS_LAMBDA (const int& i) { mvView(i,col) = source(i,0); });
1190 typename PHX::Device().fence();
1191 }
1192 timer->stop("Copy RHS Values into MV");
1193
1194 // Solve the multiple matrices
1195 using MV = Tpetra::MultiVector<double,LO,GO,NodeType>;
1196 using OP = Tpetra::Operator<double,LO,GO,NodeType>;
1197 const auto solutionMV = rcp(new Tpetra::MultiVector<double,LO,GO,NodeType>(targetRangeMap,numVectors,true));
1198 const auto problem = rcp(new Belos::LinearProblem<double,MV,OP>(massMatrix, solutionMV, rhsMV));
1199 problem->setProblem();
1200
1201 TEST_ASSERT(nonnull(massMatrix));
1202 TEST_ASSERT(nonnull(solutionMV));
1203 TEST_ASSERT(nonnull(rhsMV));
1204 TEST_ASSERT(nonnull(problem));
1205
1206 timer->start("Create Belos Solver");
1207 RCP<ParameterList> pl = parameterList("L2 Consistent Projection Linear Solver");
1208 pl->set("Num Blocks", 100); // Max Krylov vectors to store
1209 pl->set("Maximum Iterations", 100);
1210 pl->set("Convergence Tolerance", 1e-8);
1211 pl->set("output Frequency",1); // all iterations
1212 pl->set("Verbosity", Belos::Errors | Belos::Warnings | Belos::IterationDetails| Belos::FinalSummary);
1213 Belos::SolverFactory<double,MV,OP> belosFactory;
1214 const auto solver = belosFactory.create("GMRES",pl);
1215 solver->setProblem(problem);
1216 timer->stop("Create Belos Solver");
1217
1218 timer->start("Belos Solve");
1219 const auto result = solver->solve();
1220 timer->stop("Belos Solve");
1221
1222 TEST_EQUALITY(result,Belos::Converged);
1223
1224 // Check the final values on host
1225 out << "Checking CONSISTENT values!" << std::endl;
1226 timer->start("Check CONSISTENT Projected Values on Host");
1227 {
1228 const auto hostValues = solutionMV->getLocalViewHost(Tpetra::Access::ReadOnly);
1229 typename PHX::Device().fence();
1230
1231 const int phiIndex = 0;
1232 const int dphiDxIndex = 1;
1233 const int dphiDyIndex = 2;
1234 double tol = 1.0e-4;
1235
1236 std::vector<std::string> elementBlockNames;
1237 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
1238 for (const auto& block : elementBlockNames) {
1239
1240 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
1241 const auto worksets = worksetContainer->getWorksets(wd);
1242 for (const auto& workset : *worksets) {
1243 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
1244 targetGlobalIndexer->getElementBlockGIDCount(block));
1245 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
1246 targetGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
1247
1248 auto localIds_h = Kokkos::create_mirror_view(localIds);
1249 Kokkos::deep_copy(localIds_h, localIds);
1250
1251 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
1252 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
1253
1254 // Create vector to store if LID is owned
1255 timer->start("Create isOwned view");
1256 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
1257 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
1258 {
1259 std::vector<GO> cellGIDs(localIds.extent(1));
1260 std::vector<bool> cellOwnedIds(localIds.extent(1));
1261 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
1262 targetGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
1263 targetGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
1264 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
1265 isOwned_h(cell,i) = cellOwnedIds[i];
1266 }
1267 }
1268 timer->stop("Create isOwned view");
1269
1270 const auto offsets = targetGlobalIndexer->getGIDFieldOffsets(block,0);
1271 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
1272 const auto& coords = basisValues.getBasisCoordinates();
1273 auto coords_h = Kokkos::create_mirror_view(PHX::as_view(coords));
1274 Kokkos::deep_copy(coords_h, PHX::as_view(coords));
1275 const int numBasis = static_cast<int>(offsets.size());
1276
1277 for (int cell=0; cell < workset.numOwnedCells(); ++cell) {
1278 for (int basis=0; basis < numBasis; ++basis) {
1279 if (isOwned_h(cell,offsets[basis])) {
1280 const int lid = localIds_h(cell,offsets[basis]);
1281 const double phiGold = 1.0 + coords_h(cell,basis,0) + 2.0 * coords_h(cell,basis,1);
1282 TEST_FLOATING_EQUALITY(hostValues(lid,phiIndex), phiGold, tol);
1283 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDxIndex), 1.0, tol);
1284 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDyIndex), 2.0, tol);
1285 }
1286 }
1287 }
1288 }
1289 }
1290 }
1291 timer->stop("Check CONSISTENT Projected Values on Host");
1292
1293 // ***************************
1294 // Now test lumped mass matrix
1295 // ***************************
1296 timer->start("projectionFactory.buildInverseLumpedMassMatrix()");
1297 auto invLumpedMassMatrix = projectionFactory.buildInverseLumpedMassMatrix();
1298 timer->stop("projectionFactory.buildInverseLumpedMassMatrix()");
1299
1300 timer->start("apply lumped mass matrix");
1301 {
1302 auto x = solutionMV->getLocalViewDevice(Tpetra::Access::OverwriteAll);
1303 auto rhsMV_k = rhsMV->getLocalViewDevice(Tpetra::Access::ReadOnly);
1304 const auto ilmm = invLumpedMassMatrix->getLocalViewDevice(Tpetra::Access::ReadOnly);
1305 const int numEntries = static_cast<int>(x.extent(0));
1306 Kokkos::parallel_for(numEntries,KOKKOS_LAMBDA (const int i)
1307 {
1308 for (int field=0; field < numVectors; ++field)
1309 x(i,field) = ilmm(i,0) * rhsMV_k(i,field);
1310 });
1311 typename PHX::Device().fence();
1312 }
1313 timer->stop("apply lumped mass matrix");
1314
1315 // Check the final values on host
1316 out << "Checking LUMPED values!" << std::endl;
1317 timer->start("Check LUMPED Projected Values on Host");
1318 {
1319 const auto hostValues = solutionMV->getLocalViewHost(Tpetra::Access::ReadOnly);
1320 typename PHX::Device().fence();
1321
1322 const int phiIndex = 0;
1323 const int dphiDxIndex = 1;
1324 const int dphiDyIndex = 2;
1325 // NOTE: Lumping generates significant errors when the meshes are
1326 // very coarse (such as in this unit test). We see
1327 // superconvergence on the interior points of this axis aligned
1328 // mesh and for the constant fields, thus can can tighten the
1329 // tolerances for some fields. Refining the mesh results in more
1330 // accurate projected values.
1331 double looseTol = 0.5;
1332 double superconvergedTol = 1.0e-4;
1333
1334 std::vector<std::string> elementBlockNames;
1335 sourceGlobalIndexer->getElementBlockIds(elementBlockNames);
1336 for (const auto& block : elementBlockNames) {
1337
1338 panzer::WorksetDescriptor wd(block,panzer::WorksetSizeType::ALL_ELEMENTS,true,true);
1339 const auto worksets = worksetContainer->getWorksets(wd);
1340 for (const auto& workset : *worksets) {
1341 PHX::View<LO**> localIds("projection unit test: LocalIds", workset.numOwnedCells()+workset.numGhostCells()+workset.numVirtualCells(),
1342 targetGlobalIndexer->getElementBlockGIDCount(block));
1343 const auto cellLocalIdsNoGhost = Kokkos::subview(workset.cell_local_ids_k,std::make_pair(0,workset.numOwnedCells()));
1344 targetGlobalIndexer->getElementLIDs(cellLocalIdsNoGhost,localIds);
1345
1346 auto localIds_h = Kokkos::create_mirror_view(localIds);
1347 Kokkos::deep_copy(localIds_h, localIds);
1348
1349 auto cellLocalIdsNoGhost_h = Kokkos::create_mirror_view(cellLocalIdsNoGhost);
1350 Kokkos::deep_copy(cellLocalIdsNoGhost_h, cellLocalIdsNoGhost);
1351
1352 // Create vector to store if LID is owned
1353 timer->start("Create isOwned view");
1354 PHX::View<bool**> isOwned("projection unit test: isOwned", workset.numOwnedCells(),localIds.extent(1));
1355 auto isOwned_h = Kokkos::create_mirror_view(isOwned);
1356 {
1357 std::vector<GO> cellGIDs(localIds.extent(1));
1358 std::vector<bool> cellOwnedIds(localIds.extent(1));
1359 for (std::size_t cell=0; cell < cellLocalIdsNoGhost.extent(0); ++cell) {
1360 targetGlobalIndexer->getElementGIDs(cellLocalIdsNoGhost_h(cell),cellGIDs);
1361 targetGlobalIndexer->ownedIndices(cellGIDs,cellOwnedIds);
1362 for (std::size_t i=0; i < cellOwnedIds.size(); ++i)
1363 isOwned_h(cell,i) = cellOwnedIds[i];
1364 }
1365 }
1366 timer->stop("Create isOwned view");
1367
1368 const auto offsets = targetGlobalIndexer->getGIDFieldOffsets(block,0);
1369 const auto& basisValues = workset.getBasisValues(hgradBD,integrationDescriptor);
1370 const auto& coords = basisValues.getBasisCoordinates();
1371 auto coords_h = Kokkos::create_mirror_view(PHX::as_view(coords));
1372 Kokkos::deep_copy(coords_h, PHX::as_view(coords));
1373 const int numBasis = static_cast<int>(offsets.size());
1374
1375 for (int cell=0; cell < workset.numOwnedCells(); ++cell) {
1376 for (int basis=0; basis < numBasis; ++basis) {
1377 if (isOwned_h(cell,offsets[basis])) {
1378 const int lid = localIds_h(cell,offsets[basis]);
1379 const double phiGold = 1.0 + coords_h(cell,basis,0) + 2.0 * coords_h(cell,basis,1);
1380 TEST_FLOATING_EQUALITY(hostValues(lid,phiIndex), phiGold, looseTol);
1381 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDxIndex), 1.0, superconvergedTol);
1382 TEST_FLOATING_EQUALITY(hostValues(lid,dphiDyIndex), 2.0, superconvergedTol);
1383 }
1384 }
1385 }
1386 }
1387 }
1388 }
1389 timer->stop("Check LUMPED Projected Values on Host");
1390
1391 timer->stop("Total Time");
1392
1393 Teuchos::StackedTimer::OutputOptions options;
1394 options.output_fraction = true;
1395 options.output_minmax = true;
1396 options.output_histogram = false;
1397 options.num_histogram = 5;
1398 timer->report(out,comm,options);
1399 }
1400
1401
1402 // Tests the element block multiplier
1403 TEUCHOS_UNIT_TEST(L2Projection, ElementBlockMultiplier)
1404 {
1405 using namespace Teuchos;
1406 using namespace panzer;
1407 using namespace panzer_stk;
1408
1409 RCP<MpiComm<int>> comm = rcp(new MpiComm<int>(MPI_COMM_WORLD));
1410
1411 auto timer = Teuchos::TimeMonitor::getStackedTimer();
1412 timer->start("Total Time");
1413
1414 const int numProcs = comm->getSize();
1415 const int numXElements = 3;
1416 const int numYElements = numXElements;
1417 const double boxLength = 1.0;
1418 TEUCHOS_ASSERT(numXElements >= numProcs);
1419
1420 RCP<panzer_stk::STK_Interface> mesh;
1421 {
1422 PANZER_FUNC_TIME_MONITOR("L2Projection: mesh construction");
1423 Teuchos::RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
1424 pl->set("X Blocks",2);
1425 pl->set("Y Blocks",1);
1426 pl->set("X Elements",numXElements);
1427 pl->set("Y Elements",numYElements);
1428 pl->set("X Procs",numProcs);
1429 pl->set("Y Procs",1);
1430 pl->set("X0",0.0);
1431 pl->set("Y0",0.0);
1432 pl->set("Xf",boxLength);
1433 pl->set("Yf",boxLength);
1434 panzer_stk::SquareTriMeshFactory factory;
1435 factory.setParameterList(pl);
1436 mesh = factory.buildUncommitedMesh(MPI_COMM_WORLD);
1437 factory.completeMeshConstruction(*mesh,MPI_COMM_WORLD);
1438 }
1439
1440 // Build Worksets
1441
1442 const int basisOrder = 1;
1443 BasisDescriptor hgradBD(basisOrder,"HGrad");
1444
1445 const int intOrder = 2;
1446 IntegrationDescriptor integrationDescriptor(intOrder,IntegrationDescriptor::VOLUME);
1447
1448 // Build Connection Manager
1449 timer->start("ConnManager ctor");
1450 const RCP<panzer::ConnManager> connManager = rcp(new panzer_stk::STKConnManager(mesh));
1451 timer->stop("ConnManager ctor");
1452
1453 // Set up bases for projections
1454 std::vector<std::string> eBlockNames;
1455 mesh->getElementBlockNames(eBlockNames);
1456 auto cellTopology = mesh->getCellTopology(eBlockNames[0]);
1457
1458 auto hgradBasis = panzer::createIntrepid2Basis<PHX::Device,double,double>(hgradBD.getType(),hgradBD.getOrder(),*cellTopology);
1459 RCP<const panzer::FieldPattern> hgradFP(new panzer::Intrepid2FieldPattern(hgradBasis));
1460
1461 // Build source DOF Manager that mimics multi-fluid plasma dof manager
1462 timer->start("Build sourceGlobalIndexer");
1463 RCP<panzer::DOFManager> sourceGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
1464 sourceGlobalIndexer->addField("PHI",hgradFP); // Electric Potential for ES
1465 sourceGlobalIndexer->addField("Chaff0",hgradFP); // Dummy
1466 sourceGlobalIndexer->addField("Chaff1",hgradFP); // Dummy
1467 sourceGlobalIndexer->addField("Chaff2",hgradFP); // Dummy
1468 sourceGlobalIndexer->buildGlobalUnknowns();
1469 timer->stop("Build sourceGlobalIndexer");
1470
1471 // Build Target DOF Manager (Separate scalar fields on hgrad)
1472 timer->start("Build targetGlobalIndexer");
1473 RCP<panzer::DOFManager> targetGlobalIndexer = rcp(new panzer::DOFManager(connManager,*comm->getRawMpiComm()));
1474 targetGlobalIndexer->addField("Projection to Mesh Vertices",hgradFP);
1475 targetGlobalIndexer->buildGlobalUnknowns();
1476 timer->stop("Build targetGlobalIndexer");
1477
1478 // Create worksets
1479 RCP<WorksetContainer> worksetContainer;
1480 {
1481 RCP<WorksetFactory> worksetFactory(new WorksetFactory(mesh));
1482 worksetFactory->setOrientationsInterface(rcp(new OrientationsInterface(sourceGlobalIndexer)));
1483 worksetContainer = rcp(new WorksetContainer(worksetFactory));
1484 }
1485
1486 // Build projection factory
1487 timer->start("projectionFactory.setup()");
1488 panzer::L2Projection projectionFactory;
1489 projectionFactory.setup(hgradBD,integrationDescriptor,comm,connManager,eBlockNames,worksetContainer);
1490 timer->stop("projectionFactory.setup()");
1491
1492 TEST_ASSERT(nonnull(projectionFactory.getTargetGlobalIndexer()));
1493
1494 // Build mass matrix
1495 std::unordered_map<std::string,double> ebMultipliers = {{"eblock-0_0",1.0},{"eblock-1_0",1.0}};
1496
1497 timer->start("projectionFactory.buildMassMatrix() 1.0");
1498 auto massMatrix_1 = projectionFactory.buildMassMatrix(false,&ebMultipliers);
1499 timer->stop("projectionFactory.buildMassMatrix() 1.0");
1500
1501 const double multiplier = 4.0;
1502 ebMultipliers["eblock-0_0"] = multiplier;
1503 ebMultipliers["eblock-1_0"] = multiplier;
1504
1505 timer->start("projectionFactory.buildMassMatrix() 4.0");
1506 auto massMatrix_4 = projectionFactory.buildMassMatrix(false,&ebMultipliers);
1507 timer->stop("projectionFactory.buildMassMatrix() 4.0");
1508
1509 const auto view_1 = massMatrix_1->getLocalValuesDevice(Tpetra::Access::ReadOnly);
1510 const auto view_4 = massMatrix_4->getLocalValuesDevice(Tpetra::Access::ReadOnly);
1511
1512 const double tol = 100.0 * std::numeric_limits<double>::epsilon();
1513 int valuesCheck = 0; // if check > 0 then multipliers broke
1514
1515 Kokkos::parallel_reduce(view_1.size(),KOKKOS_LAMBDA (const int i, int& update) {
1516 if (std::fabs(multiplier * view_1(i) - view_4(i)) > tol)
1517 update += 1;
1518 }, valuesCheck);
1519 Kokkos::fence();
1520
1521 TEST_EQUALITY(valuesCheck, 0);
1522 }