Debian Codegraph @

packages/muelu/test/scaling/Reuse.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_DefaultPlatform.hpp>
14 #include <Xpetra_IO.hpp>
15
16 #include <Teuchos_Time.hpp>
17 #include <Teuchos_StandardCatchMacros.hpp>
18
19 // Galeri
20 #include <Galeri_XpetraParameters.hpp>
21 #include <Galeri_XpetraProblemFactory.hpp>
22 #include <Galeri_XpetraUtils.hpp>
23 #include <Galeri_XpetraMaps.hpp>
24 //
25
26 #include <MueLu.hpp>
27 #include <MueLu_Level.hpp>
28 #include <MueLu_BaseClass.hpp>
29 #include <MueLu_Exceptions.hpp>
30 #include <MueLu_ParameterListInterpreter.hpp> // TODO: move into MueLu.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 <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
39 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
40 #endif
41 //- -- --------------------------------------------------------
42 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
43 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib &lib, int argc, char *argv[]) {
44 #include <MueLu_UseShortNames.hpp>
45
46 using Teuchos::Array;
47 using Teuchos::ArrayRCP;
48 using Teuchos::RCP; // reference count pointers
49 using Teuchos::rcp;
50 using Teuchos::Time;
51 using Teuchos::TimeMonitor;
52
53 typedef Teuchos::ScalarTraits<SC> STS;
54
55 bool success = false;
56 bool verbose = true;
57 try {
58 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
59 int mypid = comm->getRank();
60
61 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(cout));
62 Teuchos::FancyOStream &out = *fancy;
63 out.setOutputToRootOnly(0);
64
65 SC zero = STS::zero(), one = STS::one();
66
67 //
68 // Parameters
69 //
70
71 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
72
73 std::string xmlFileName = "reuse.xml";
74 clp.setOption("xml", &xmlFileName, "read parameters from a file. Otherwise, this example uses by default 'reuse.xml'");
75 std::string matrixPrefix = "jac";
76 clp.setOption("matrix", &matrixPrefix, "prefix for matrix file names. Default = 'jac'");
77 bool binary = false;
78 clp.setOption("binary", "nobinary", &binary, "matrix files are binary. Default = false");
79 std::string rhsPrefix = "rhs";
80 clp.setOption("rhs", &rhsPrefix, "prefix for rhs file names. Default = 'rhs'");
81 bool printTimings = true;
82 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
83 int first_matrix = 0;
84 clp.setOption("firstMatrix", &first_matrix, "first matrix in the sequence to use");
85 int last_matrix = 1;
86 clp.setOption("lastMatrix", &last_matrix, "last matrix in the sequence to use");
87 bool inMemory = false;
88 clp.setOption("inmemory", "noinmemory", &inMemory, "load all matrices in memory");
89 bool doReuse = true;
90 clp.setOption("reuse", "noreuse", &doReuse, "if you want to try reuse");
91 const int numPDEs = 2;
92
93 switch (clp.parse(argc, argv)) {
94 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
95 case Teuchos::CommandLineProcessor::PARSE_ERROR:
96 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
97 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
98 }
99
100 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Global Time"))), tm;
101 RCP<Time> timer;
102
103 // Operator and Multivector type that will be used with Belos
104 typedef MultiVector MV;
105 typedef Belos::OperatorT<MV> OP;
106
107 // Stats tracking
108 int numSteps = last_matrix - first_matrix + 1;
109 Array<Array<int> > iteration_counts(numSteps);
110 Array<Array<double> > iteration_times(numSteps);
111 Array<Array<double> > setup_times(numSteps);
112 Array<RCP<Matrix> > matrices(numSteps);
113 Array<RCP<MultiVector> > rhss(numSteps);
114
115 for (int i = 0; i < numSteps; i++) {
116 iteration_counts[i].resize(numSteps);
117 iteration_times[i].resize(numSteps);
118 setup_times[i].resize(numSteps);
119 }
120
121 ParameterListInterpreter mueLuFactory(xmlFileName, *comm);
122
123 for (int i = first_matrix; i <= last_matrix; i++) {
124 out << "==================================================================" << std::endl;
125
126 char matrixFileName[80];
127 char rhsFileName[80];
128 char timerName[80];
129
130 sprintf(matrixFileName, "%s%d.mm", matrixPrefix.c_str(), i);
131
132 // Load the matrix
133 RCP<Matrix> Aprecond = matrices[i];
134 if (Aprecond.is_null()) {
135 out << "[" << i << "] Loading matrix \"" << matrixFileName << "\"... ";
136 Aprecond = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileName), xpetraParameters.GetLib(), comm, binary);
137 out << "done" << std::endl;
138
139 Aprecond->SetFixedBlockSize(numPDEs);
140
141 if (inMemory)
142 matrices[i] = Aprecond;
143
144 } else {
145 // Reset estimate
146 Aprecond->SetMaxEigenvalueEstimate(-one);
147 }
148
149 // Build the nullspace
150 RCP<MultiVector> nullspace = MultiVectorFactory::Build(Aprecond->getRowMap(), numPDEs);
151 nullspace->putScalar(zero);
152
153 Teuchos::ArrayRCP<SC> data0, data1;
154 data0 = nullspace->getDataNonConst(0);
155 data1 = nullspace->getDataNonConst(1);
156 for (size_t k = 0; k < Aprecond->getRowMap()->getLocalNumElements(); k += 2)
157 data0[k + 0] = data1[k + 1] = one;
158
159 // Build the preconditioner
160 out << "[" << i << "] Building preconditioner \"" << matrixFileName << "\" ..." << std::endl;
161 sprintf(timerName, "Reuse: Preconditioner Setup i=%d", i);
162 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer(timerName)));
163
164 RCP<Hierarchy> H = mueLuFactory.CreateHierarchy();
165 H->SetDefaultVerbLevel(MueLu::Extreme);
166 H->GetLevel(0)->Set("A", Aprecond);
167 H->GetLevel(0)->Set("Nullspace", nullspace);
168 H->IsPreconditioner(true);
169
170 sprintf(timerName, "Reuse: Setup i=%d j=%d", i, i);
171 timer = TimeMonitor::getNewTimer(timerName);
172 timer->start();
173 mueLuFactory.SetupHierarchy(*H);
174 setup_times[i - first_matrix][i - first_matrix] = timer->stop();
175 timer = Teuchos::null;
176
177 Teuchos::RCP<OP> belosPrec = Teuchos::rcp(new Belos::MueLuOp<SC, LO, GO, NO>(H)); // Turns a MueLu::Hierarchy object into a Belos operator
178 tm = Teuchos::null;
179
180 // Loop over all future matrices
181 int j = i;
182 for (; j <= last_matrix; j++) {
183 out << "------------------------------------------------------------------" << std::endl;
184
185 sprintf(matrixFileName, "%s%d.mm", matrixPrefix.c_str(), j);
186 sprintf(rhsFileName, "%s%d.mm", rhsPrefix.c_str(), j);
187
188 RCP<Matrix> Amatvec = matrices[j];
189 if (j != i) {
190 if (Amatvec.is_null()) {
191 // Load the matrix
192 out << "[" << j << "]<-[" << i << "] Loading matrix \"" << matrixFileName << "\"... ";
193 Amatvec = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileName), xpetraParameters.GetLib(), comm, binary);
194 out << "done" << std::endl;
195
196 Amatvec->SetFixedBlockSize(numPDEs);
197
198 if (inMemory)
199 matrices[j] = Amatvec;
200
201 } else {
202 // Reset estimate
203 Amatvec->SetMaxEigenvalueEstimate(-one);
204 }
205
206 // Preconditioner update
207 sprintf(timerName, "Reuse: Preconditioner Update i=%d", i);
208 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer(timerName)));
209 // No-op at present
210
211 sprintf(timerName, "Reuse: Setup i=%d j=%d", i, j);
212 timer = TimeMonitor::getNewTimer(timerName);
213 timer->start();
214 out << "[" << j << "]<-[" << i << "] Updating preconditioner \"" << matrixFileName << "\" ..." << std::endl;
215
216 H->GetLevel(0)->Set("A", Amatvec);
217 mueLuFactory.SetupHierarchy(*H);
218
219 setup_times[i - first_matrix][j - first_matrix] = timer->stop();
220 timer = Teuchos::null;
221
222 tm = Teuchos::null;
223
224 } else {
225 Amatvec = Aprecond;
226 }
227
228 // Load the RHS
229 RCP<MultiVector> rhs = rhss[j];
230 if (rhs.is_null()) {
231 out << "[" << j << "] Loading rhs " << rhsFileName << "\"... ";
232 rhs = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(std::string(rhsFileName), Amatvec->getRowMap());
233 out << "done" << std::endl;
234
235 if (inMemory)
236 rhss[j] = rhs;
237 }
238
239 // Create an LHS
240 RCP<Vector> X = VectorFactory::Build(Amatvec->getRowMap());
241 X->putScalar(0.0);
242
243 // Define Operator and Preconditioner
244 Teuchos::RCP<OP> belosOp = Teuchos::rcp(new Belos::XpetraOp<SC, LO, GO, NO>(Amatvec)); // Turns a Xpetra::Matrix object into a Belos operator
245
246 // Construct a Belos LinearProblem object
247 RCP<Belos::LinearProblem<SC, MV, OP> > belosProblem = rcp(new Belos::LinearProblem<SC, MV, OP>(belosOp, X, rhs));
248 belosProblem->setLeftPrec(belosPrec);
249 belosProblem->setProblem();
250
251 // Belos parameter list
252 int maxIts = 100;
253 double tol = 1e-4;
254 Teuchos::ParameterList belosList;
255 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
256 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
257 // belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::TimingDetails + Belos::StatusTestDetails);
258 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
259 belosList.set("Output Frequency", 1);
260 belosList.set("Output Style", Belos::Brief);
261
262 // Create an iterative solver manager
263 RCP<Belos::SolverManager<SC, MV, OP> > solver = rcp(new Belos::BlockCGSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
264
265 // Perform solve
266 sprintf(timerName, "Reuse: Solve i=%d j=%d", i, j);
267 timer = TimeMonitor::getNewTimer(timerName);
268 timer->start();
269 Belos::ReturnType ret = Belos::Unconverged;
270 ret = solver->solve();
271
272 double my_time = timer->stop();
273 timer = Teuchos::null;
274
275 // Get the number of iterations for this solve.
276
277 // Check convergence
278 if (ret != Belos::Converged) {
279 out << "ERROR : Belos did not converge! " << std::endl;
280 break;
281 } else {
282 out << "SUCCESS: Belos converged!" << std::endl;
283 out << "Number of iterations performed for this solve: " << solver->getNumIters() << std::endl;
284 iteration_counts[i - first_matrix][j - first_matrix] = solver->getNumIters();
285 iteration_times[i - first_matrix][j - first_matrix] = my_time;
286 }
287
288 if (doReuse == 0) {
289 j++;
290 break;
291 }
292 } // end j
293 for (; j <= last_matrix; j++)
294 setup_times[i - first_matrix][j - first_matrix] = Teuchos::ScalarTraits<double>::nan();
295 } // end i
296
297 globalTimeMonitor = Teuchos::null;
298
299 if (printTimings)
300 // TimeMonitor::summarize(comm.ptr(), out, false, true, false, Teuchos::Union);
301 TimeMonitor::summarize(comm.ptr(), out);
302
303 if (!mypid) {
304 printf("************************* Iteration Counts ***********************\n");
305 for (int i = 0; i < numSteps; i++) {
306 for (int j = 0; j < i; j++) printf(" ");
307 for (int j = i; j < numSteps; j++) {
308 if (STS::isnaninf(setup_times[i][j])) {
309 if (i == j)
310 printf(" -");
311 break;
312 }
313 printf(" %7d", iteration_counts[i][j]);
314 }
315 printf("\n");
316 }
317 // For convenince, print data without reuse in a single line
318 for (int i = 0; i < numSteps; i++)
319 printf(" %7d", iteration_counts[i][i]);
320 printf("\n");
321
322 printf("************************* Iteration Times ***********************\n");
323 for (int i = 0; i < numSteps; i++) {
324 for (int j = 0; j < i; j++) printf(" ");
325 for (int j = i; j < numSteps; j++) {
326 if (STS::isnaninf(setup_times[i][j]))
327 break;
328 printf(" %7.2f", iteration_times[i][j]);
329 }
330 printf("\n");
331 }
332 // For convenince, print data without reuse in a single line
333 for (int i = 0; i < numSteps; i++)
334 printf(" %7.2f", iteration_times[i][i]);
335 printf("\n");
336
337 printf("************************* Setup Times ***********************\n");
338 for (int i = 0; i < numSteps; i++) {
339 for (int j = 0; j < i; j++) printf(" ");
340 for (int j = i; j < numSteps; j++) {
341 if (STS::isnaninf(setup_times[i][j]))
342 break;
343 printf(" %7.2f", setup_times[i][j]);
344 }
345 printf("\n");
346 }
347 // For convenince, print data without reuse in a single line
348 for (int i = 0; i < numSteps; i++)
349 printf(" %7.2f", setup_times[i][i]);
350 printf("\n");
351
352 printf("************************* Total Times ***********************\n");
353 for (int i = 0; i < numSteps; i++) {
354 for (int j = 0; j < i; j++) printf(" ");
355 for (int j = i; j < numSteps; j++) {
356 if (STS::isnaninf(setup_times[i][j]))
357 break;
358 printf(" %7.2f", setup_times[i][j] + iteration_times[i][j]);
359 }
360 printf("\n");
361 }
362 // For convenince, print data without reuse in a single line
363 for (int i = 0; i < numSteps; i++)
364 printf(" %7.2f", setup_times[i][i] + iteration_times[i][i]);
365 printf("\n");
366 }
367
368 success = true;
369 }
370 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
371
372 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
373 }
374
375 //- -- --------------------------------------------------------
376 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
377 #include "MueLu_Test_ETI.hpp"
378
379 int main(int argc, char *argv[]) {
380 return Automatic_Test_ETI(argc, argv);
381 }