Debian Codegraph @

packages/muelu/test/scaling/ReadMatrix.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 #include <iostream>
11
12 #include <Xpetra_MultiVectorFactory.hpp>
13 #include <Xpetra_IO.hpp>
14
15 // Teuchos
16 #include <Teuchos_StandardCatchMacros.hpp>
17
18 // Galeri
19 #include <Galeri_XpetraParameters.hpp>
20 #include <Galeri_XpetraProblemFactory.hpp>
21 #include <Galeri_XpetraUtils.hpp>
22 #include <Galeri_XpetraMaps.hpp>
23 //
24
25 #include <MueLu.hpp>
26 #include <MueLu_Level.hpp>
27 #include <MueLu_BaseClass.hpp>
28 #include <MueLu_ParameterListInterpreter.hpp> // TODO: move into MueLu.hpp
29
30 #include <MueLu_Utilities.hpp>
31
32 #include <MueLu_MutuallyExclusiveTime.hpp>
33
34 #ifdef HAVE_MUELU_BELOS
35 #include <BelosConfigDefs.hpp>
36 #include <BelosLinearProblem.hpp>
37 #include <BelosBlockCGSolMgr.hpp>
38 #include <BelosBlockGmresSolMgr.hpp>
39 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
40 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
41 #endif
42
43 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
44 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib &lib, int argc, char *argv[]) {
45 #include <MueLu_UseShortNames.hpp>
46
47 using Teuchos::RCP; // reference count pointers
48 using Teuchos::rcp;
49 using Teuchos::TimeMonitor;
50
51 bool success = false;
52 bool verbose = true;
53 try {
54 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
55
56 // =========================================================================
57 // Convenient definitions
58 // =========================================================================
59 SC zero = Teuchos::ScalarTraits<SC>::zero(), one = Teuchos::ScalarTraits<SC>::one();
60
61 // Instead of checking each time for rank, create a rank 0 stream
62 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
63 Teuchos::FancyOStream &fancyout = *fancy;
64 fancyout.setOutputToRootOnly(0);
65
66 // =========================================================================
67 // Parameters initialization
68 // =========================================================================
69 GO nx = 100, ny = 100, nz = 100;
70 Galeri::Xpetra::Parameters<GO> matrixParameters(clp, nx, ny, nz, "Laplace2D"); // manage parameters of the test case
71 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
72
73 std::string xmlFileName = "scalingTest.xml";
74 clp.setOption("xml", &xmlFileName, "read parameters from a file. Otherwise, this example uses by default 'scalingTest.xml'");
75 int amgAsPrecond = 1;
76 clp.setOption("precond", &amgAsPrecond, "apply multigrid as preconditioner");
77 int amgAsSolver = 0;
78 clp.setOption("fixPoint", &amgAsSolver, "apply multigrid as solver");
79 bool printTimings = true;
80 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
81 int writeMatricesOPT = -2;
82 clp.setOption("write", &writeMatricesOPT, "write matrices to file (-1 means all; i>=0 means level i)");
83 double tol = 1e-12;
84 clp.setOption("tol", &tol, "solver convergence tolerance");
85 std::string krylovMethod = "cg";
86 clp.setOption("krylov", &krylovMethod, "outer Krylov method");
87 int maxIts = 100;
88 clp.setOption("maxits", &maxIts, "maximum number of Krylov iterations");
89 int output = 1;
90 clp.setOption("output", &output, "how often to print Krylov residual history");
91 std::string matrixFileName = "A.mm";
92 clp.setOption("matrixfile", &matrixFileName, "matrix market file containing matrix");
93 std::string rhsFileName = "";
94 clp.setOption("rhsfile", &rhsFileName, "matrix market file containing right-hand side");
95 int nPDE = 1;
96 clp.setOption("numpdes", &nPDE, "number of PDE equations");
97 std::string convType = "r0";
98 clp.setOption("convtype", &convType, "convergence type (r0 or none)");
99
100 switch (clp.parse(argc, argv)) {
101 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
102 case Teuchos::CommandLineProcessor::PARSE_ERROR:
103 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
104 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
105 }
106
107 fancyout << "========================================================\n"
108 << xpetraParameters << matrixParameters;
109
110 // =========================================================================
111 // Problem construction
112 // =========================================================================
113 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MatrixRead: S - Global Time"))), tm;
114
115 comm->barrier();
116 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 1 - Matrix Build")));
117
118 RCP<Matrix> A = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileName), lib, comm);
119 RCP<const Map> map = A->getRowMap();
120 RCP<MultiVector> nullspace = MultiVectorFactory::Build(A->getDomainMap(), nPDE);
121 // RCP<MultiVector> fakeCoordinates = MultiVectorFactory::Build(A->getDomainMap(),1);
122 A->SetFixedBlockSize(nPDE);
123 std::cout << "#pdes = " << A->GetFixedBlockSize() << std::endl;
124 if (nPDE == 1)
125 nullspace->putScalar(Teuchos::ScalarTraits<SC>::one());
126 else {
127 for (int i = 0; i < nPDE; ++i) {
128 Teuchos::ArrayRCP<SC> nsData = nullspace->getDataNonConst(i);
129 for (int j = 0; j < nsData.size(); ++j) {
130 GO gel = A->getDomainMap()->getGlobalElement(j) - A->getDomainMap()->getIndexBase();
131 if ((gel - i) % nPDE == 0)
132 nsData[j] = Teuchos::ScalarTraits<SC>::one();
133 }
134 }
135 }
136
137 comm->barrier();
138 tm = Teuchos::null;
139
140 fancyout << "Galeri complete.\n========================================================" << std::endl;
141
142 // =========================================================================
143 // Preconditioner construction
144 // =========================================================================
145 comm->barrier();
146 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 1.5 - MueLu read XML")));
147 ParameterListInterpreter mueLuFactory(xmlFileName, *comm);
148
149 comm->barrier();
150 tm.reset();
151 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 2 - MueLu Setup")));
152
153 RCP<Hierarchy> H = mueLuFactory.CreateHierarchy();
154
155 // By default, we use Extreme. However, typically the xml file contains verbosity parameter
156 // which is used instead
157 H->SetDefaultVerbLevel(MueLu::Extreme);
158
159 H->GetLevel(0)->Set("A", A);
160 H->GetLevel(0)->Set("Nullspace", nullspace);
161 // H->GetLevel(0)->Set("Coordinates", fakeCoordinates);
162
163 mueLuFactory.SetupHierarchy(*H);
164
165 comm->barrier();
166 tm = Teuchos::null;
167
168 // Print out the hierarchy stats. We should not need this line, but for some reason the
169 // print out in the hierarchy construction does not work.
170 H->print(fancyout);
171
172 // =========================================================================
173 // System solution (Ax = b)
174 // =========================================================================
175 comm->barrier();
176 tm.reset();
177 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 3 - LHS and RHS initialization")));
178
179 RCP<Vector> X = VectorFactory::Build(map, 1);
180 RCP<MultiVector> B = VectorFactory::Build(map, 1);
181
182 if (rhsFileName != "")
183 B = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(std::string(rhsFileName), A->getRowMap());
184 else {
185 // we set seed for reproducibility
186 X->setSeed(846930886);
187 bool useSameRandomGen = false;
188 X->randomize(useSameRandomGen);
189 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
190
191 Teuchos::Array<typename Teuchos::ScalarTraits<Scalar>::magnitudeType> norms(1);
192 B->norm2(norms);
193 // B->scale(1.0/norms[0]);
194 }
195 X->putScalar(zero);
196 tm = Teuchos::null;
197
198 if (writeMatricesOPT > -2)
199 H->Write(writeMatricesOPT, writeMatricesOPT);
200
201 comm->barrier();
202 if (amgAsSolver) {
203 tm.reset();
204 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 4 - Fixed Point Solve")));
205
206 H->IsPreconditioner(false);
207 Teuchos::Array<typename Teuchos::ScalarTraits<Scalar>::magnitudeType> norms(1);
208 norms = Utilities::ResidualNorm(*A, *X, *B);
209 std::cout << " iter: 0 residual = " << norms[0] << std::endl;
210 for (int i = 0; i < maxIts; ++i) {
211 H->Iterate(*B, *X);
212 norms = Utilities::ResidualNorm(*A, *X, *B);
213 std::cout << " iter: " << i + 1 << " residual = " << norms[0] << std::endl;
214 }
215
216 } else if (amgAsPrecond) {
217 #ifdef HAVE_MUELU_BELOS
218 tm.reset();
219 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 5 - Belos Solve")));
220 // Operator and Multivector type that will be used with Belos
221 typedef MultiVector MV;
222 typedef Belos::OperatorT<MV> OP;
223 H->IsPreconditioner(true);
224
225 // Define Operator and Preconditioner
226 Teuchos::RCP<OP> belosOp = Teuchos::rcp(new Belos::XpetraOp<SC, LO, GO, NO>(A)); // Turns a Xpetra::Matrix object into a Belos operator
227 Teuchos::RCP<OP> belosPrec = Teuchos::rcp(new Belos::MueLuOp<SC, LO, GO, NO>(H)); // Turns a MueLu::Hierarchy object into a Belos operator
228
229 // Construct a Belos LinearProblem object
230 RCP<Belos::LinearProblem<SC, MV, OP> > belosProblem = rcp(new Belos::LinearProblem<SC, MV, OP>(belosOp, X, B));
231 belosProblem->setRightPrec(belosPrec);
232
233 bool set = belosProblem->setProblem();
234 if (set == false) {
235 fancyout << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
236 return EXIT_FAILURE;
237 }
238
239 // Belos parameter list
240 Teuchos::ParameterList belosList;
241 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
242 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
243 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
244 belosList.set("Output Frequency", output);
245 belosList.set("Output Style", Belos::Brief);
246 // belosList.set("Orthogonalization", "ICGS");
247 if (convType == "none") {
248 belosList.set("Explicit Residual Scaling", "None");
249 belosList.set("Implicit Residual Scaling", "None");
250 }
251
252 // Create an iterative solver manager
253 RCP<Belos::SolverManager<SC, MV, OP> > solver;
254 if (krylovMethod == "cg") {
255 solver = rcp(new Belos::BlockCGSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
256 } else if (krylovMethod == "gmres") {
257 solver = rcp(new Belos::BlockGmresSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
258 } else {
259 TEUCHOS_TEST_FOR_EXCEPTION(true, MueLu::Exceptions::RuntimeError, "Invalid Krylov method. Options are \"cg\" or \" gmres\".");
260 }
261
262 // Perform solve
263 Belos::ReturnType ret = Belos::Unconverged;
264 try {
265 ret = solver->solve();
266
267 // Get the number of iterations for this solve.
268 fancyout << "Number of iterations performed for this solve: " << solver->getNumIters() << std::endl;
269
270 } catch (...) {
271 fancyout << std::endl
272 << "ERROR: Belos threw an error! " << std::endl;
273 }
274
275 // Check convergence
276 if (ret != Belos::Converged)
277 fancyout << std::endl
278 << "ERROR: Belos did not converge! " << std::endl;
279 else
280 fancyout << std::endl
281 << "SUCCESS: Belos converged!" << std::endl;
282 #endif // ifdef HAVE_MUELU_BELOS
283 }
284 comm->barrier();
285 tm = Teuchos::null;
286 globalTimeMonitor = Teuchos::null;
287
288 if (printTimings) {
289 TimeMonitor::summarize(A->getRowMap()->getComm().ptr(), std::cout, false, true, false, Teuchos::Union, "", true);
290 MueLu::MutuallyExclusiveTime<MueLu::BaseClass>::PrintParentChildPairs();
291 }
292
293 success = true;
294 }
295 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
296
297 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
298 } // main
299
300 //- -- --------------------------------------------------------
301 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
302 #include "MueLu_Test_ETI.hpp"
303
304 int main(int argc, char *argv[]) {
305 return Automatic_Test_ETI(argc, argv);
306 }