Debian Codegraph @

packages/belos/tpetra/example/PCPG/PCPGTpetraExFile.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Belos: Block Linear Solvers Package
4 //
5 // Copyright 2004-2016 NTESS and the Belos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 // Purpose
11 // The example tests the successive right-hand sides capabilities of ML
12 // and Belos on a heat flow u_t = u_xx problem.
13 //
14 // A sequence of linear systems with the same coefficient matrix and
15 // different right-hand sides is solved. A seed space is generated dynamically,
16 // and a deflated linear system is solved. After each solves, the first
17 // few Krylov vectors are saved, and used to reduce the number of iterations
18 // for later solves.
19 // The optimal numbers of vectors to deflate and save are not known.
20 // Presently, the maximum number of vectors to deflate (seed space dimension)
21 // and to save are user paraemters.
22 // The seed space dimension is less than or equal to total number of vectors
23 // saved. The difference between the seed space dimension and the total number
24 // of vectors, is the number of vectors used to update the seed space after each
25 // solve. I guess that a seed space whose dimension is a small fraction of the
26 // total space will be best.
27 //
28 // maxSave=1 and maxDeflate=0 uses no recycling (not tested ).
29 //
30 // TODO: Instrument with timers, so that we can tell what is going on besides
31 // by counting the numbers of iterations.
32 //
33 //
34 // Adapted from PCPGEpetraExFile.cpp by David M. Day (with original comments)
35
36 // All preconditioning has been commented out
37
38 // Tpetra
39 #include <TpetraExt_MatrixMatrix.hpp>
40 #include <Tpetra_Core.hpp>
41 #include <Tpetra_CrsMatrix_fwd.hpp>
42 #include <Tpetra_Map_fwd.hpp>
43 #include <Tpetra_Vector_fwd.hpp>
44
45 // MueLu
46 // #include <MueLu_TpetraOperator.hpp>
47 // #include <MueLu_CreateTpetraPreconditioner.hpp>
48
49 // Teuchos
50 #include <Teuchos_Comm.hpp>
51 #include <Teuchos_CommHelpers.hpp>
52 #include <Teuchos_CommandLineProcessor.hpp>
53 #include <Teuchos_DefaultComm.hpp>
54 #include <Teuchos_FancyOStream.hpp>
55 #include <Teuchos_ParameterList.hpp>
56 #include <Teuchos_RCP.hpp>
57 #include <Teuchos_StandardCatchMacros.hpp>
58 #include <Teuchos_Tuple.hpp>
59 #include <Teuchos_VerboseObject.hpp>
60
61 // Belos
62 #include "BelosLinearProblem.hpp"
63 #include "BelosPCPGSolMgr.hpp"
64 #include "BelosTpetraAdapter.hpp"
65
66 template <typename ScalarType>
67 int run(int argc, char *argv[]) {
68 //
69 // Laplace's equation, homogeneous Dirichlet boundary conditions, [0,1]^2
70 // regular mesh, Q1 finite elements
71 //
72
73 using Teuchos::ParameterList;
74 using Teuchos::RCP;
75 using Teuchos::rcp;
76 using Teuchos::tuple;
77
78 using ST = typename Tpetra::MultiVector<ScalarType>::scalar_type;
79 using LO = typename Tpetra::Vector<>::local_ordinal_type;
80 using GO = typename Tpetra::Vector<>::global_ordinal_type;
81 using NT = typename Tpetra::Vector<>::node_type;
82
83 using V = typename Tpetra::Vector<ST, LO, GO, NT>;
84 using MV = typename Tpetra::MultiVector<ST, LO, GO, NT>;
85 using OP = typename Tpetra::Operator<ST, LO, GO, NT>;
86 using MVT = typename Belos::MultiVecTraits<ST, MV>;
87 using OPT = typename Belos::OperatorTraits<ST, MV, OP>;
88 using MAP = typename Tpetra::Map<LO, GO, NT>;
89 using MAT = typename Tpetra::CrsMatrix<ST, LO, GO, NT>;
90 using SCT = typename Teuchos::ScalarTraits<ST>;
91 using MT = typename SCT::magnitudeType;
92
93 using LinearProblem = typename Belos::LinearProblem<ST, MV, OP>;
94 using PCPGSolMgr = ::Belos::PCPGSolMgr<ST, MV, OP>;
95
96 Teuchos::GlobalMPISession session(&argc, &argv, NULL);
97 RCP<const Teuchos::Comm<int>> comm = Tpetra::getDefaultComm();
98
99 bool verbose = false;
100 bool success = true;
101
102 try {
103 bool procVerbose = false;
104 int frequency = -1; // frequency of status test output.
105 int blocksize = 1; // blocksize, PCPGIter
106 int numRhs = 1; // number of right-hand sides to solve for
107 int maxIters = 30; // maximum number of iterations allowed per linear system
108
109 int maxDeflate = 4; // maximum number of vectors deflated from the linear system;
110 // There is no overhead cost assoc with changing maxDeflate between solves
111 int maxSave = 8; // maximum number of vectors saved from current and previous .");
112 // If maxSave changes between solves, then re-initialize (setSize).
113
114 // Hypothesis: seed vectors are conjugate.
115 // Initial versions allowed users to supply a seed space et cetera, but no
116 // longer.
117
118 // The documentation it suitable for certain tasks, like defining a modules
119 // grammar,
120 std::string ortho("ICGS"); // The Belos documentation obscures the fact that
121 // IMGS is Iterated Modified Gram Schmidt,
122 // ICGS is Iterated Classical Gram Schmidt, and
123 // DKGS is another Iterated Classical Gram Schmidt.
124 // Mathematical issues, such as the difference between ICGS and DKGS, are
125 // not documented at all. UH tells me that Anasazi::SVQBOrthoManager is
126 // available; I need it for Belos
127 MT tol = sqrt(std::numeric_limits<ST>::epsilon()); // relative residual tolerance
128
129 // How do command line parsers work?
130 Teuchos::CommandLineProcessor cmdp(false, true);
131 cmdp.setOption("verbose", "quiet", &verbose, "Print messages and results");
132 cmdp.setOption("frequency", &frequency, "Solvers frequency for printing residuals (#iters)");
133 cmdp.setOption("tol", &tol, "Relative residual tolerance used by PCPG solver");
134 cmdp.setOption("num-rhs", &numRhs, "Number of right-hand sides to be solved for");
135 cmdp.setOption("max-iters", &maxIters,
136 "Maximum number of iterations per linear system (-1 = "
137 "adapted to problem/block size)");
138 cmdp.setOption("num-deflate", &maxDeflate, "Number of vectors deflated from the linear system");
139 cmdp.setOption("num-save", &maxSave, "Number of vectors saved from old Krylov subspaces");
140 cmdp.setOption("ortho-type", &ortho, "Orthogonalization type, either DGKS, ICGS or IMGS");
141 if (cmdp.parse(argc, argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
142 return -1;
143 }
144 if (!verbose)
145 frequency = -1; // reset frequency if test is not verbose
146
147 //
148 // *************Form the problem****************
149 //
150 int numTimeStep = 4;
151 GO numElePerDirection = 14 * comm->getSize(); // 5 -> 20
152 size_t numNodes = (numElePerDirection - 1) * (numElePerDirection - 1);
153
154 // By the way, either matrix has (3*numElePerDirection - 2)^2 nonzeros.
155 RCP<MAP> map = rcp(new MAP(numNodes, 0, comm));
156 RCP<MAT> stiff = rcp(new MAT(map, numNodes));
157 RCP<MAT> mass = rcp(new MAT(map, numNodes));
158 RCP<V> vecLHS = rcp(new V(map));
159 RCP<V> vecRHS = rcp(new V(map));
160 RCP<MV> LHS, RHS;
161
162 ST ko = 8.0 / 3.0, k1 = -1.0 / 3.0;
163
164 ST h = 1.0 / static_cast<ST>(numElePerDirection); // x=(iX,iY)h
165 ST mo = h * h * 4.0 / 9.0, m1 = h * h / 9.0, m2 = h * h / 36.0;
166
167 ST pi = 4.0 * atan(1.0), valueLHS;
168 GO node, iX, iY;
169
170 for (LO lid = map->getMinLocalIndex(); lid <= map->getMaxLocalIndex(); lid++) {
171 node = map->getGlobalElement(lid);
172 iX = node % (numElePerDirection - 1);
173 iY = (node - iX) / (numElePerDirection - 1);
174 GO pos = node;
175 stiff->insertGlobalValues(node, tuple(pos), tuple(ko));
176 mass->insertGlobalValues(node, tuple(pos),
177 tuple(mo)); // init guess violates hom Dir bc
178 valueLHS = sin(pi * h * ((ST)iX + 1)) * cos(2.0 * pi * h * ((ST)iY + 1));
179 vecLHS->replaceGlobalValue(1, valueLHS);
180
181 if (iY > 0) {
182 pos = iX + (iY - 1) * (numElePerDirection - 1);
183 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // North
184 mass->insertGlobalValues(node, tuple(pos), tuple(m1));
185 }
186 if (iY < numElePerDirection - 2) {
187 pos = iX + (iY + 1) * (numElePerDirection - 1);
188 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // South
189 mass->insertGlobalValues(node, tuple(pos), tuple(m1));
190 }
191
192 if (iX > 0) {
193 pos = iX - 1 + iY * (numElePerDirection - 1);
194 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // West
195 mass->insertGlobalValues(node, tuple(pos), tuple(m1));
196 if (iY > 0) {
197 pos = iX - 1 + (iY - 1) * (numElePerDirection - 1);
198 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // North West
199 mass->insertGlobalValues(node, tuple(pos), tuple(m2));
200 }
201 if (iY < numElePerDirection - 2) {
202 pos = iX - 1 + (iY + 1) * (numElePerDirection - 1);
203 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // South West
204 mass->insertGlobalValues(node, tuple(pos), tuple(m2));
205 }
206 }
207
208 if (iX < numElePerDirection - 2) {
209 pos = iX + 1 + iY * (numElePerDirection - 1);
210 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // East
211 mass->insertGlobalValues(node, tuple(pos), tuple(m1));
212 if (iY > 0) {
213 pos = iX + 1 + (iY - 1) * (numElePerDirection - 1);
214 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // North East
215 mass->insertGlobalValues(node, tuple(pos), tuple(m2));
216 }
217 if (iY < numElePerDirection - 2) {
218 pos = iX + 1 + (iY + 1) * (numElePerDirection - 1);
219 stiff->insertGlobalValues(node, tuple(pos), tuple(k1)); // South East
220 mass->insertGlobalValues(node, tuple(pos), tuple(m2));
221 }
222 }
223 }
224
225 stiff->fillComplete();
226 mass->fillComplete();
227
228 const ST one = SCT::one();
229 ST hdt = .00005; // half time step
230
231 // A = Mass+Stiff*dt/2
232 RCP<MAT> A = Tpetra::MatrixMatrix::add(one, false, *mass, hdt, false, *stiff);
233
234 // B = Mass-Stiff*dt/2
235 hdt = -hdt;
236 RCP<MAT> B = Tpetra::MatrixMatrix::add(one, false, *mass, hdt, false, *stiff);
237
238 B->apply(*vecLHS, *vecRHS);
239
240 procVerbose = verbose && (comm->getRank() == 0); // Only print on the zero processor
241
242 LHS = Teuchos::rcp_implicit_cast<MV>(vecLHS);
243 RHS = Teuchos::rcp_implicit_cast<MV>(vecRHS);
244
245 //
246 // **********Construct preconditioner***********
247 //
248
249 // Teuchos::ParameterList MLList; // Set MLList for Smoothed Aggregation
250 // ML_Tpetra::SetDefaults("SA",MLList); // reset parameters ML User's Guide
251 // MLList.set("smoother: type","CHEBYSHEV"); // Chebyshev smoother ... aztec??
252 // MLList.set("smoother: sweeps",3);
253 // MLList.set("smoother: pre or post", "both"); // both pre- and post-smoothing
254
255 // #ifdef HAVE_MUELU_AMESOS2
256 // MueLuList.set("coarse: type", "KLU2"); // solve with serial direct
257 // solver KLU
258 // #else
259 // MLList.set("coarse: type", "Jacobi"); // not recommended
260 // puts("Warning: Iterative coarse grid solve");
261 // #endif
262
263 //
264 // RCP<OP> prec = MueLu::CreateTpetraPreconditioner(A, MLList );
265 // assert(prec != Teuchos::null);
266
267 // Create the Belos preconditioned operator from the preconditioner.
268 // NOTE: This is necessary because Belos expects an operator to apply the
269 // preconditioner with Apply() NOT ApplyInverse().
270 // RCP<Belos::EpetraPrecOp> belosPrec = rcp( new Belos::EpetraPrecOp( Prec )
271 // );
272
273 // Create parameter list for the PCPG solver manager
274 const int numGlobalElements = RHS->getGlobalLength();
275 if (maxIters == -1)
276 maxIters = numGlobalElements / blocksize - 1; // maximum number of iterations to run
277
278 RCP<ParameterList> belosList = rcp(new ParameterList());
279 belosList->set("Block Size",
280 blocksize); // Blocksize to be used by iterative solver
281 belosList->set("Maximum Iterations",
282 maxIters); // Maximum number of iterations allowed
283 belosList->set("Convergence Tolerance",
284 tol); // Relative convergence tolerance requested
285 belosList->set("Num Deflated Blocks",
286 maxDeflate); // Number of vectors in seed space
287 belosList->set("Num Saved Blocks",
288 maxSave); // Number of vectors saved from old spaces
289 belosList->set("Orthogonalization", ortho); // Orthogonalization type
290
291 if (numRhs > 1) {
292 belosList->set("Show Maximum Residual Norm Only",
293 true); // although numRhs = 1.
294 }
295 if (verbose) {
296 belosList->set("Verbosity", Belos::Errors + Belos::Warnings + Belos::TimingDetails +
297 Belos::FinalSummary + Belos::StatusTestDetails);
298 if (frequency > 0)
299 belosList->set("Output Frequency", frequency);
300 } else
301 belosList->set("Verbosity", Belos::Errors + Belos::Warnings + Belos::FinalSummary);
302
303 // Construct a preconditioned linear problem
304 RCP<LinearProblem> problem = rcp(new LinearProblem(A, LHS, RHS));
305
306 // problem->setLeftPrec( prec );
307
308 bool set = problem->setProblem();
309 if (set == false) {
310 if (procVerbose)
311 std::cout << std::endl
312 << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
313 return -1;
314 }
315
316 // Create an iterative solver manager.
317 RCP<PCPGSolMgr> solver = rcp(new PCPGSolMgr(problem, belosList));
318
319 //
320 // *******************************************************************
321 // ************************* Iterate PCPG ****************************
322 // *******************************************************************
323 //
324 if (procVerbose) {
325 std::cout << std::endl << std::endl;
326 std::cout << "Dimension of matrix: " << numGlobalElements << std::endl;
327 std::cout << "Number of right-hand sides: " << numRhs << std::endl;
328 std::cout << "Block size used by solver: " << blocksize << std::endl;
329 std::cout << "Maximum number of iterations allowed: " << maxIters << std::endl;
330 std::cout << "Relative residual tolerance: " << tol << std::endl;
331 std::cout << std::endl;
332 }
333 bool badRes;
334 for (int timeStep = 0; timeStep < numTimeStep; timeStep++) {
335 if (timeStep) {
336 // old epetra B->multiply(false, *vecLHS, *vecRHS); // rhs_new :=
337 // B*lhs_old,
338 B->apply(*LHS, *RHS); // rhs_new := B*lhs_old,
339 set = problem->setProblem(LHS, RHS);
340 if (set == false) {
341 if (procVerbose)
342 std::cout << std::endl
343 << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
344 return -1;
345 }
346 } // if timeStep
347 std::vector<ST> rhs_norm(numRhs);
348 MVT::MvNorm(*RHS, rhs_norm);
349 std::cout << " RHS norm is ... " << rhs_norm[0] << std::endl;
350
351 // Perform solve
352 Belos::ReturnType ret = solver->solve();
353
354 // Compute actual residuals.
355 badRes = false;
356 std::vector<ST> actual_resids(numRhs);
357 MV resid(map, numRhs);
358 OPT::Apply(*A, *LHS, resid);
359 MVT::MvAddMv(-1.0, resid, 1.0, *RHS, resid);
360 MVT::MvNorm(resid, actual_resids);
361 MVT::MvNorm(*RHS, rhs_norm);
362 std::cout << " RHS norm is ... " << rhs_norm[0] << std::endl;
363
364 if (procVerbose) {
365 std::cout << "---------- Actual Residuals (normalized) ----------" << std::endl
366 << std::endl;
367 for (int i = 0; i < numRhs; i++) {
368 double actRes = actual_resids[i] / rhs_norm[i];
369 std::cout << "Problem " << i << " : \t" << actRes << std::endl;
370 if (actRes > tol)
371 badRes = true;
372 }
373 }
374 if (ret != Belos::Converged || badRes) {
375 success = false;
376 break;
377 }
378 } // for timeStep
379
380 if (procVerbose) {
381 if (success)
382 std::cout << std::endl << "SUCCESS: Belos converged!" << std::endl;
383 else
384 std::cout << std::endl << "ERROR: Belos did not converge!" << std::endl;
385 }
386 } // end try
387 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
388
389 return success ? EXIT_SUCCESS : EXIT_FAILURE;
390 }
391
392 int main(int argc, char *argv[]) {
393 return run<double>(argc, argv);
394 // return run<float>(argc, argv); }
395 }
396
397 // end PCPGTpetraExFile.cpp