Debian Codegraph @

packages/muelu/test/navierstokes/Navier2D_Epetra.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // MueLu: A package for multigrid based preconditioning
4 //
5 // Copyright 2012 NTESS and the MueLu contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /*
11 * Navier2D_epetra.cpp
12 *
13 * Created on: Mar 26, 2011
14 * Author: wiesner
15 */
16
17 #include <unistd.h>
18 #include <iostream>
19 #include <fstream>
20
21 // Teuchos
22 #include <Teuchos_RCP.hpp>
23 #include <Teuchos_ParameterList.hpp>
24 #include <Teuchos_CommandLineProcessor.hpp>
25 #include <Teuchos_GlobalMPISession.hpp>
26 #include <Teuchos_DefaultComm.hpp>
27 #include <Teuchos_StandardCatchMacros.hpp>
28
29 // Epetra
30 #include <EpetraExt_CrsMatrixIn.h>
31 #include <EpetraExt_VectorIn.h>
32 #include <EpetraExt_MultiVectorIn.h>
33
34 // Xpetra
35 #include <Xpetra_Map.hpp>
36 #include <Xpetra_MapFactory.hpp>
37 #include <Xpetra_CrsMatrixWrap.hpp>
38 #include <Xpetra_MultiVectorFactory.hpp>
39 #include <Xpetra_VectorFactory.hpp>
40 #include <Xpetra_Parameters.hpp>
41
42 // MueLu
43 #include "MueLu_ConfigDefs.hpp"
44 #include "MueLu_Memory.hpp"
45 #include "MueLu_Hierarchy.hpp"
46 #include "MueLu_AmalgamationFactory.hpp"
47 #include "MueLu_UncoupledAggregationFactory.hpp"
48 #include "MueLu_PgPFactory.hpp"
49 #include "MueLu_GenericRFactory.hpp"
50 #include "MueLu_SaPFactory.hpp"
51 #include "MueLu_TransPFactory.hpp"
52 #include "MueLu_RAPFactory.hpp"
53 #include "MueLu_TrilinosSmoother.hpp"
54 #include "MueLu_Utilities.hpp"
55 #include "MueLu_Exceptions.hpp"
56 #include "MueLu_Aggregates.hpp"
57 #include "MueLu_CoalesceDropFactory.hpp"
58 #include "MueLu_PreDropFunctionConstVal.hpp"
59 #include "MueLu_NullspaceFactory.hpp"
60 #include "MueLu_TentativePFactory.hpp"
61 #include "MueLu_SmootherFactory.hpp"
62 #include "MueLu_DirectSolver.hpp"
63 #include "MueLu_EpetraOperator.hpp"
64 #if defined(HAVE_MPI) && defined(HAVE_MUELU_ZOLTAN) && defined(HAVE_MUELU_ISORROPIA)
65 #include "MueLu_IsorropiaInterface.hpp"
66 #include "MueLu_RepartitionInterface.hpp"
67 #include "MueLu_RepartitionHeuristicFactory.hpp"
68 #include "MueLu_RepartitionFactory.hpp"
69 #include "MueLu_RebalanceTransferFactory.hpp"
70 #include "MueLu_RebalanceAcFactory.hpp"
71 #endif
72
73 #include <Epetra_LinearProblem.h>
74 #include <AztecOO.h>
75
76 /*!
77 * 2d Navier Stokes example (for Epetra)
78 *
79 */
80
81 int main(int argc, char* argv[]) {
82 #if defined(HAVE_MUELU_EPETRA) && defined(HAVE_MUELU_EPETRAEXT)
83 typedef double Scalar;
84 typedef int LocalOrdinal;
85 typedef int GlobalOrdinal;
86 typedef LocalOrdinal LO;
87 typedef GlobalOrdinal GO;
88 typedef Xpetra::EpetraNode Node;
89 #include "MueLu_UseShortNames.hpp"
90
91 using Teuchos::RCP;
92 using Teuchos::rcp;
93
94 Teuchos::oblackholestream blackhole;
95 Teuchos::GlobalMPISession mpiSession(&argc, &argv, &blackhole);
96
97 bool success = false;
98 try {
99 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
100 RCP<Teuchos::FancyOStream> out = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
101 out->setOutputToRootOnly(0);
102 *out << MueLu::MemUtils::PrintMemoryUsage() << std::endl;
103
104 // Timing
105 Teuchos::Time myTime("global");
106 Teuchos::TimeMonitor m(myTime);
107
108 //
109 // SET TEST PARAMETERS
110 //
111 // Note: use --help to list available options.
112 Teuchos::CommandLineProcessor clp(false);
113
114 // - Levels
115 LO optMaxLevels = 4;
116 clp.setOption("maxLevels", &optMaxLevels, "maximum number of levels allowed");
117 int optMaxCoarseSize = 1;
118 clp.setOption("maxCoarseSize", &optMaxCoarseSize, "maximum #dofs in coarse operator"); // FIXME clp doesn't like long long int
119
120 // - Repartitioning
121 #if defined(HAVE_MPI) && defined(HAVE_MUELU_ZOLTAN) && defined(HAVE_MUELU_ISORROPIA)
122 int optRepartition = 1;
123 clp.setOption("repartition", &optRepartition, "enable repartitioning");
124 LO optMinRowsPerProc = 50;
125 clp.setOption("minRowsPerProc", &optMinRowsPerProc, "min #rows allowable per proc before repartitioning occurs");
126 double optNnzImbalance = 1.2;
127 clp.setOption("nnzImbalance", &optNnzImbalance, "max allowable nonzero imbalance before repartitioning occurs");
128 #else
129 int optRepartition = 0;
130 #endif
131
132 switch (clp.parse(argc, argv)) {
133 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
134 case Teuchos::CommandLineProcessor::PARSE_ERROR:
135 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
136 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
137 }
138
139 /////////////////////////////////////////////
140 // custom parameters
141 LO maxLevels = optMaxLevels;
142
143 GO maxCoarseSize = optMaxCoarseSize;
144 std::string aggOrdering = "natural";
145 int minPerAgg = 3;
146 int maxNbrAlreadySelected = 0;
147
148 int globalNumDofs = 1500;
149 int nProcs = comm->getSize();
150 int nDofsPerNode = 3;
151
152 int nLocalDofs = (int)globalNumDofs / nProcs;
153 nLocalDofs = nLocalDofs - (nLocalDofs % nDofsPerNode);
154 int nCumulatedDofs = 0;
155 MueLu_sumAll(comm, nLocalDofs, nCumulatedDofs);
156 // Teuchos::reduceAll<int,int>(*comm,Teuchos::REDUCE_SUM, 1, nLocalDofs, &nCumulatedDofs );
157
158 if (comm->getRank() == nProcs - 1) {
159 nLocalDofs += globalNumDofs - nCumulatedDofs;
160 }
161
162 std::cout << "PROC: " << comm->getRank() << " numLocalDofs=" << nLocalDofs << std::endl;
163
164 // read in problem
165 Epetra_Map emap(globalNumDofs, nLocalDofs, 0, *Xpetra::toEpetra(comm));
166 Epetra_CrsMatrix* ptrA = 0;
167 Epetra_Vector* ptrf = 0;
168 Epetra_MultiVector* ptrNS = 0;
169
170 std::cout << "Reading matrix market file" << std::endl;
171 EpetraExt::MatrixMarketFileToCrsMatrix("A_re1000_5932.txt", emap, emap, emap, ptrA);
172 EpetraExt::MatrixMarketFileToVector("b_re1000_5932.txt", emap, ptrf);
173 RCP<Epetra_CrsMatrix> epA = Teuchos::rcp(ptrA);
174 RCP<Epetra_Vector> epv = Teuchos::rcp(ptrf);
175 RCP<Epetra_MultiVector> epNS = Teuchos::rcp(ptrNS);
176
177 // Epetra_CrsMatrix -> Xpetra::Matrix
178 RCP<CrsMatrix> exA = Teuchos::rcp(new Xpetra::EpetraCrsMatrixT<GO, NO>(epA));
179 RCP<CrsMatrixWrap> crsOp = Teuchos::rcp(new CrsMatrixWrap(exA));
180 RCP<Matrix> Op = Teuchos::rcp_dynamic_cast<Matrix>(crsOp);
181
182 Op->SetFixedBlockSize(nDofsPerNode); // 2 velocity dofs and 1 pressure dof per node.
183
184 // Epetra_Vector -> Xpetra::Vector
185 RCP<Vector> xRhs = Teuchos::rcp(new Xpetra::EpetraVectorT<int, Node>(epv));
186
187 RCP<MultiVector> xNS = Teuchos::rcp(new Xpetra::EpetraMultiVectorT<int, Node>(epNS));
188
189 // Epetra_Map -> Xpetra::Map
190 const RCP<const Map> map = Xpetra::toXpetra<int, Node>(emap);
191
192 RCP<Hierarchy> H = rcp(new Hierarchy());
193 H->setDefaultVerbLevel(Teuchos::VERB_HIGH);
194 H->SetMaxCoarseSize(maxCoarseSize);
195
196 // build finest Level
197 RCP<MueLu::Level> Finest = H->GetLevel();
198 Finest->setDefaultVerbLevel(Teuchos::VERB_HIGH);
199 Finest->Set("A", Op);
200 // Finest->Set("Nullspace",xNS);
201
202 if (optRepartition == 1) {
203 // create null space
204
205 RCP<MultiVector> nullspace;
206 // determine numPDEs
207 LocalOrdinal numPDEs = 1;
208 if (Op->IsView("stridedMaps") == true) {
209 Xpetra::viewLabel_t oldView = Op->SwitchToView("stridedMaps"); // note: "stridedMaps are always non-overlapping (correspond to range and domain maps!)
210 // TEUCHOS_TEST_FOR_EXCEPTION(Teuchos::rcp_dynamic_cast<const StridedMap>(Op->getRowMap()) == Teuchos::null, Exceptions::BadCast, "cast to strided row map failed.");
211 numPDEs = Teuchos::rcp_dynamic_cast<const StridedMap>(Op->getRowMap())->getFixedBlockSize();
212 oldView = Op->SwitchToView(oldView);
213 }
214
215 // GetOStream(Runtime1, 0) << "Generating canonical nullspace: dimension = " << numPDEs << std::endl;
216 nullspace = MultiVectorFactory::Build(Op->getDomainMap(), numPDEs);
217
218 for (int i = 0; i < numPDEs; ++i) {
219 Teuchos::ArrayRCP<Scalar> nsValues = nullspace->getDataNonConst(i);
220 int numBlocks = nsValues.size() / numPDEs;
221 for (int j = 0; j < numBlocks; ++j) {
222 nsValues[j * numPDEs + i] = 1.0;
223 }
224 }
225 Finest->Set("Nullspace", nullspace);
226 }
227
228 RCP<CoalesceDropFactory> dropFact = rcp(new CoalesceDropFactory());
229 dropFact->SetParameter("lightweight wrap", Teuchos::ParameterEntry(false));
230 dropFact->SetVerbLevel(MueLu::Extreme);
231
232 // RCP<PreDropFunctionConstVal> predrop = rcp(new PreDropFunctionConstVal(0.00001));
233 // dropFact->SetPreDropFunction(predrop);
234 RCP<UncoupledAggregationFactory> UncoupledAggFact = rcp(new UncoupledAggregationFactory());
235 UncoupledAggFact->SetFactory("Graph", dropFact);
236 *out << "========================= Aggregate option summary =========================" << std::endl;
237 *out << "min DOFs per aggregate : " << minPerAgg << std::endl;
238 *out << "min # of root nbrs already aggregated : " << maxNbrAlreadySelected << std::endl;
239 UncoupledAggFact->SetMinNodesPerAggregate(minPerAgg); // TODO should increase if run anything other than 1D
240 UncoupledAggFact->SetMaxNeighAlreadySelected(maxNbrAlreadySelected);
241 std::transform(aggOrdering.begin(), aggOrdering.end(), aggOrdering.begin(), ::tolower);
242 if (aggOrdering == "natural" || aggOrdering == "random" || aggOrdering == "graph") {
243 *out << "aggregate ordering : " << aggOrdering << std::endl;
244 UncoupledAggFact->SetOrdering(aggOrdering);
245 } else {
246 std::string msg =
247 "main: bad aggregation option "
248 "" +
249 aggOrdering +
250 ""
251 ".";
252 throw(MueLu::Exceptions::RuntimeError(msg));
253 }
254 *out << "=============================================================================" << std::endl;
255
256 // build non-rebalanced transfer operators
257 RCP<PgPFactory> Pfact = rcp(new PgPFactory());
258 RCP<Factory> Rfact = rcp(new GenericRFactory());
259 // RCP<SaPFactory> Pfact = rcp( new SaPFactory() );
260 // RCP<Factory> Rfact = rcp( new TransPFactory() );
261 RCP<RAPFactory> Acfact = rcp(new RAPFactory());
262 Acfact->setVerbLevel(Teuchos::VERB_HIGH);
263
264 // build level smoothers
265 RCP<SmootherPrototype> smooProto;
266 std::string ifpackType;
267 Teuchos::ParameterList ifpackList;
268 ifpackList.set("relaxation: sweeps", (LO)3);
269 ifpackList.set("relaxation: damping factor", (SC)0.6); // 0.7
270 ifpackType = "RELAXATION";
271 ifpackList.set("relaxation: type", "Gauss-Seidel");
272
273 smooProto = Teuchos::rcp(new TrilinosSmoother(ifpackType, ifpackList));
274 RCP<SmootherFactory> SmooFact;
275 if (maxLevels > 1)
276 SmooFact = rcp(new SmootherFactory(smooProto));
277
278 // create coarsest smoother
279 RCP<SmootherPrototype> coarsestSmooProto;
280 std::string type = "";
281 Teuchos::ParameterList coarsestSmooList;
282 #if defined(HAVE_AMESOS_SUPERLU)
283 coarsestSmooProto = Teuchos::rcp(new DirectSolver("Superlu", coarsestSmooList));
284 #else
285 coarsestSmooProto = Teuchos::rcp(new DirectSolver("Klu", coarsestSmooList));
286 #endif
287 RCP<SmootherFactory> coarsestSmooFact = rcp(new SmootherFactory(coarsestSmooProto, Teuchos::null));
288
289 FactoryManager M;
290 M.SetKokkosRefactor(false);
291 M.SetFactory("Graph", dropFact);
292 // M.SetFactory("UnAmalgamationInfo", amalgFact);
293 M.SetFactory("Aggregates", UncoupledAggFact);
294 M.SetFactory("Smoother", SmooFact);
295 M.SetFactory("CoarseSolver", coarsestSmooFact);
296
297 if (optRepartition == 0) {
298 // no rebalancing
299 M.SetFactory("P", Pfact);
300 M.SetFactory("R", Rfact);
301 M.SetFactory("A", Acfact);
302 } else {
303 #if defined(HAVE_MPI) && defined(HAVE_MUELU_ZOLTAN) && defined(HAVE_MUELU_ISORROPIA)
304 // The Factory Manager will be configured to return the rebalanced versions of P, R, A by default.
305 // Everytime we want to use the non-rebalanced versions, we need to explicitly define the generating factory.
306 Rfact->SetFactory("P", Pfact);
307 //
308 Acfact->SetFactory("P", Pfact);
309 Acfact->SetFactory("R", Rfact);
310
311 // define rebalancing factory for coarse block matrix A(1,1)
312 RCP<AmalgamationFactory> rebAmalgFact = rcp(new AmalgamationFactory());
313 rebAmalgFact->SetFactory("A", Acfact);
314
315 // Repartitioning (decides how many partitions are built)
316 RCP<Factory> RepartitionHeuristicFact = rcp(new RepartitionHeuristicFactory());
317 {
318 Teuchos::ParameterList paramList;
319 paramList.set("repartition: min rows per proc", optMinRowsPerProc);
320 paramList.set("repartition: max imbalance", optNnzImbalance);
321 RepartitionHeuristicFact->SetParameterList(paramList);
322 }
323 RepartitionHeuristicFact->SetFactory("A", Acfact);
324
325 // create amalgamated "Partition"
326 RCP<MueLu::IsorropiaInterface<LO, GO, NO> > isoInterface = rcp(new MueLu::IsorropiaInterface<LO, GO, NO>());
327 isoInterface->SetFactory("A", Acfact);
328 isoInterface->SetFactory("number of partitions", RepartitionHeuristicFact);
329 isoInterface->SetFactory("UnAmalgamationInfo", rebAmalgFact);
330
331 // create "Partition" by unamalgamtion
332 RCP<MueLu::RepartitionInterface<LO, GO, NO> > repInterface = rcp(new MueLu::RepartitionInterface<LO, GO, NO>());
333 repInterface->SetFactory("A", Acfact);
334 repInterface->SetFactory("number of partitions", RepartitionHeuristicFact);
335 repInterface->SetFactory("AmalgamatedPartition", isoInterface);
336
337 // Repartitioning (creates "Importer" from "Partition")
338 RCP<Factory> RepartitionFact = rcp(new RepartitionFactory());
339 RepartitionFact->SetFactory("A", Acfact);
340 RepartitionFact->SetFactory("number of partitions", RepartitionHeuristicFact);
341 RepartitionFact->SetFactory("Partition", repInterface);
342
343 // Reordering of the transfer operators
344 RCP<Factory> RebalancedPFact = rcp(new RebalanceTransferFactory());
345 RebalancedPFact->SetParameter("type", Teuchos::ParameterEntry(std::string("Interpolation")));
346 RebalancedPFact->SetFactory("P", Pfact);
347 RebalancedPFact->SetFactory("Nullspace", M.GetFactory("Ptent"));
348
349 RCP<Factory> RebalancedRFact = rcp(new RebalanceTransferFactory());
350 RebalancedRFact->SetParameter("type", Teuchos::ParameterEntry(std::string("Restriction")));
351 RebalancedRFact->SetFactory("R", Rfact);
352 // RebalancedRFact->SetFactory("Coordinates", TransferCoordinatesFact);
353
354 // Compute Ac from rebalanced P and R
355 RCP<Factory> RebalancedAFact = rcp(new RebalanceAcFactory());
356 RebalancedAFact->SetFactory("A", Acfact);
357
358 // Configure FactoryManager
359 M.SetFactory("A", RebalancedAFact);
360 M.SetFactory("P", RebalancedPFact);
361 M.SetFactory("R", RebalancedRFact);
362 M.SetFactory("Nullspace", RebalancedPFact);
363 M.SetFactory("Importer", RepartitionFact);
364 #else
365 // no re-balancing available
366 M.SetFactory("P", Pfact);
367 M.SetFactory("R", Rfact);
368 M.SetFactory("A", Acfact);
369 #endif
370 }
371
372 H->Setup(M, 0, maxLevels);
373
374 { // some debug output
375 // print out content of levels
376 std::cout << "FINAL CONTENT of multigrid levels" << std::endl;
377 for (LO l = 0; l < H->GetNumLevels(); l++) {
378 RCP<Level> coarseLevel = H->GetLevel(l);
379 coarseLevel->print(*out);
380 }
381 std::cout << "END FINAL CONTENT of multigrid levels" << std::endl;
382 } // end debug output
383
384 RCP<MultiVector> xLsg = MultiVectorFactory::Build(map, 1);
385
386 // Use AMG directly as an iterative method
387 {
388 xLsg->putScalar((SC)0.0);
389
390 // calculate initial (absolute) residual
391 Teuchos::Array<Teuchos::ScalarTraits<SC>::magnitudeType> norms(1);
392 xRhs->norm2(norms);
393 *out << "||x_0|| = " << norms[0] << std::endl;
394
395 // apply ten multigrid iterations
396 H->Iterate(*xRhs, *xLsg, 10);
397
398 // calculate and print residual
399 RCP<MultiVector> xTmp = MultiVectorFactory::Build(map, 1);
400 Op->apply(*xLsg, *xTmp, Teuchos::NO_TRANS, (SC)1.0, (SC)0.0);
401 xRhs->update((SC)-1.0, *xTmp, (SC)1.0);
402 xRhs->norm2(norms);
403 *out << "||x|| = " << norms[0] << std::endl;
404 }
405
406 //
407 // Solve Ax = b using AMG as a preconditioner in AztecOO
408 //
409 {
410 RCP<Epetra_Vector> X = rcp(new Epetra_Vector(epv->Map()));
411 X->PutScalar(0.0);
412 Epetra_LinearProblem epetraProblem(epA.get(), X.get(), epv.get());
413
414 AztecOO aztecSolver(epetraProblem);
415 aztecSolver.SetAztecOption(AZ_solver, AZ_gmres);
416
417 #if 0
418 // TODO TAW: 4/8/2016
419 // temporarely deactivate this due to runtime error on perseus:
420 // Cast from Xpetra::CrsMatrix to Xpetra::EpetraCrsMatrix failed
421 // if SERIAL=OFF, OPENMP=OFF, PTHREAD=ON, CUDA=OFF
422 // probably a fix necessary in EpetraOperator (which only supports
423 // SERIAL or OPENMP, but not PTHREAD of course).
424 MueLu::EpetraOperator aztecPrec(H);
425 aztecSolver.SetPrecOperator(&aztecPrec);
426
427 int maxIts = 50;
428 double tol = 1e-8;
429
430 aztecSolver.Iterate(maxIts, tol);
431 #endif
432 }
433
434 success = true;
435 }
436 TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);
437
438 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
439 #else
440 std::cout << "Epetra (and/or EpetraExt) are not available. Skip test." << std::endl;
441 return EXIT_SUCCESS;
442 #endif
443 }