Debian Codegraph @

packages/muelu/research/max/AdditiveMG/SmoothedAdditiveStride.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 // To compile and run this example, Trilinos must be configured with
12 // Tpetra, Amesos2, MueLu, Ifpack2, and Belos.
13 //
14 // This example will only work with Tpetra, not Epetra.
15 //
16 // Commonly used options are
17 // --matrixType
18 // --nx
19 // --ny
20 // --xmlFile
21 //
22 // "./MueLu_Repartition_ADR.exe --help" shows all supported command line options.
23 //
24
25 #include <iostream>
26 #include <cmath>
27
28 // Belos provides Krylov solvers
29 #include <BelosConfigDefs.hpp>
30 #include <BelosLinearProblem.hpp>
31 #include <BelosBlockCGSolMgr.hpp>
32 #include <BelosPseudoBlockCGSolMgr.hpp>
33 #include <BelosBlockGmresSolMgr.hpp>
34 #include <BelosBiCGStabSolMgr.hpp>
35 #include <BelosTpetraAdapter.hpp>
36
37 // Galeri
38 #include <Galeri_XpetraParameters.hpp>
39 #include <Galeri_XpetraProblemFactory.hpp>
40 #include <Galeri_XpetraUtils.hpp>
41 #include <Galeri_XpetraMaps.hpp>
42
43 // ADR subdirectory
44 #include "CreateADRMatrix.hpp"
45 #include <CreateADRMatrix.hpp>
46 #include <ADRProblemFactory.hpp>
47 #include <ADR_XpetraParameters.hpp>
48
49 #include "Smooth_Prolongation.cpp"
50 //#include "coloring.hpp"
51 #include "BAP.hpp"
52
53 int main(int argc, char* argv[]) {
54 // Define default types
55 typedef double scalar_type;
56 typedef int local_ordinal_type;
57 typedef int global_ordinal_type;
58 typedef Tpetra::KokkosClassic::DefaultNode::DefaultNodeType node_type;
59
60 // Convenient typedef's
61 typedef Tpetra::Operator<scalar_type, local_ordinal_type, global_ordinal_type, node_type> operator_type;
62 typedef Tpetra::CrsMatrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type> crs_matrix_type;
63 typedef Tpetra::RowMatrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type> row_matrix_type;
64 typedef Tpetra::Vector<scalar_type, local_ordinal_type, global_ordinal_type, node_type> vector_type;
65 typedef Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type> multivector_type;
66 typedef Tpetra::Map<local_ordinal_type, global_ordinal_type, node_type> driver_map_type;
67
68 typedef MueLu::TpetraOperator<scalar_type, local_ordinal_type, global_ordinal_type, node_type> muelu_tpetra_operator_type;
69 typedef MueLu::Utilities<scalar_type, local_ordinal_type, global_ordinal_type, node_type> MueLuUtilities;
70
71 typedef Belos::LinearProblem<scalar_type, multivector_type, operator_type> linear_problem_type;
72 typedef Belos::SolverManager<scalar_type, multivector_type, operator_type> belos_solver_manager_type;
73 typedef Belos::PseudoBlockCGSolMgr<scalar_type, multivector_type, operator_type> belos_pseudocg_manager_type;
74 typedef Belos::BlockGmresSolMgr<scalar_type, multivector_type, operator_type> belos_gmres_manager_type;
75 typedef Belos::BiCGStabSolMgr<scalar_type, multivector_type, operator_type> belos_bicgstab_manager_type;
76
77 typedef Ifpack2::Preconditioner<scalar_type, local_ordinal_type, global_ordinal_type, node_type> precond_type;
78
79 // MueLu_UseShortNames.hpp wants these typedefs.
80 typedef scalar_type Scalar;
81 typedef local_ordinal_type LocalOrdinal;
82 typedef global_ordinal_type GlobalOrdinal;
83 typedef node_type Node;
84 #include <MueLu_UseShortNames.hpp>
85
86 typedef Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> GaleriXpetraProblem;
87 typedef ADR::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> ADRXpetraProblem;
88
89 using Teuchos::RCP; // reference count pointers
90 using Teuchos::rcp; // reference count pointers
91
92 //
93 // MPI initialization using Teuchos
94 //
95
96 Teuchos::GlobalMPISession mpiSession(&argc, &argv, NULL);
97 RCP<const Teuchos::Comm<int>> comm = Teuchos::DefaultComm<int>::getComm();
98 int mypid = comm->getRank();
99 /*
100 int subCommRank[3]={0,1,2};
101 Teuchos::ArrayView<int> arraySubCommRank(subCommRank, 3);
102 auto subComm = comm->createSubcommunicator(arraySubCommRank);
103 */
104 Teuchos::CommandLineProcessor clp(false);
105
106 global_ordinal_type maxIts = 10000;
107 scalar_type tol = 1e-10;
108 std::string solverOptionsFile = "final_parser.xml";
109 std::string krylovSolverType = "bicgstab";
110
111 clp.setOption("xmlFile", &solverOptionsFile, "XML file containing MueLu solver parameters");
112 clp.setOption("maxits", &maxIts, "maximum number of Krylov iterations");
113 clp.setOption("tol", &tol, "tolerance for Krylov solver");
114 clp.setOption("krylovType", &krylovSolverType, "cg or gmres solver");
115
116 switch (clp.parse(argc, argv)) {
117 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
118 case Teuchos::CommandLineProcessor::PARSE_ERROR:
119 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
120 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
121 }
122
123 Teuchos::ParameterList xmlParams;
124 Teuchos::ParameterList mueluParams;
125 Teuchos::ParameterList problemParams;
126 Teuchos::updateParametersFromXmlFile(solverOptionsFile, Teuchos::inoutArg(xmlParams));
127 mueluParams = xmlParams.sublist(static_cast<const std::string>("MueLu"));
128 problemParams = xmlParams.sublist(static_cast<const std::string>("Problem"));
129
130 // Problem definition
131 std::string problem_type = problemParams.get<std::string>(static_cast<const std::string>("problem type"));
132
133 // Parameters
134
135 Scalar Lx = problemParams.get<scalar_type>(static_cast<const std::string>("domain size in x-direction"));
136 Scalar Ly = problemParams.get<scalar_type>(static_cast<const std::string>("domain size in y-direction"));
137 Scalar Lz = problemParams.get<scalar_type>(static_cast<const std::string>("domain size in z-direction"));
138
139 global_ordinal_type nx = problemParams.get<int>(static_cast<const std::string>("nodes in x-direction"));
140 global_ordinal_type ny = problemParams.get<int>(static_cast<const std::string>("nodes in y-direction"));
141 global_ordinal_type nz = problemParams.get<int>(static_cast<const std::string>("nodes in z-direction"));
142
143 global_ordinal_type number_runs = problemParams.get<int>(static_cast<const std::string>("number of runs"));
144
145 MueLu::DomainPartitioning domain;
146
147 int keep_boundary = 0;
148 Scalar stretchx = (Scalar)Lx / nx;
149 Scalar stretchy = (Scalar)Ly / ny;
150 Scalar stretchz = (Scalar)Lz / nz;
151
152 ADR::Xpetra::Parameters<GO> matrixParameters(clp, nx, ny, nz, problem_type, keep_boundary, stretchx, stretchy, stretchz); // manage parameters of the test case
153 Xpetra::Parameters xpetraParameters(clp); // manage parameters of xpetra
154
155 //
156 // Construct the problem
157 //
158
159 global_ordinal_type indexBase = 0;
160 RCP<const Map> xpetraMap;
161 std::vector<global_ordinal_type> ind;
162
163 // Creation of the map where processor 0 gets nothing at the fine level
164 if (comm->getSize() > 1) {
165 ind.reserve(static_cast<int>(matrixParameters.GetNumGlobalElements() / (comm->getSize() - 1) + 1));
166 if (mypid != 0 && mypid != comm->getSize() - 1)
167 for (int i = 0; i <= (static_cast<int>(matrixParameters.GetNumGlobalElements() / (comm->getSize() - 1))) - 1; ++i)
168 ind.emplace_back((mypid - 1) * static_cast<int>(matrixParameters.GetNumGlobalElements() / (comm->getSize() - 1)) + i);
169
170 if (mypid == comm->getSize() - 1)
171 for (int i = (mypid - 1) * static_cast<int>(matrixParameters.GetNumGlobalElements() / (comm->getSize() - 1)); i != matrixParameters.GetNumGlobalElements(); ++i)
172 ind.emplace_back(i);
173
174 ind.shrink_to_fit();
175
176 Teuchos::ArrayView<const global_ordinal_type> elementList(ind);
177 xpetraMap = MapFactory::Build(Xpetra::UseTpetra, matrixParameters.GetNumGlobalElements(), elementList, indexBase, comm);
178 } else if (comm->getSize() == 1)
179 xpetraMap = MapFactory::Build(Xpetra::UseTpetra, matrixParameters.GetNumGlobalElements(), indexBase, comm);
180
181 RCP<MultiVector> coordinates;
182
183 if (problem_type == "ADR1D")
184 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<scalar_type, local_ordinal_type, global_ordinal_type, Map, MultiVector>("1D", xpetraMap, matrixParameters.GetParameterList());
185 else if (problem_type == "ADR2D")
186 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<scalar_type, local_ordinal_type, global_ordinal_type, Map, MultiVector>("2D", xpetraMap, matrixParameters.GetParameterList());
187 else if (problem_type == "ADR3D")
188 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<scalar_type, local_ordinal_type, global_ordinal_type, Map, MultiVector>("3D", xpetraMap, matrixParameters.GetParameterList());
189
190 RCP<ADRXpetraProblem> Pr = ADR::Xpetra::BuildProblem<scalar_type, local_ordinal_type, global_ordinal_type, Map, CrsMatrixWrap, MultiVector>(matrixParameters.GetMatrixType(), xpetraMap, matrixParameters.GetParameterList());
191 RCP<Matrix> xpetraA = Pr->BuildMatrix();
192
193 RCP<crs_matrix_type> A = toTpetra(xpetraA);
194 RCP<const driver_map_type> map = toTpetra(xpetraMap);
195
196 // ===================================================
197 // Domain Decomposition Preconditioner
198 // ===================================
199
200 // Creation of the MueLu list for the DD preconditioner
201 RCP<Teuchos::ParameterList> dd_list = rcp(new Teuchos::ParameterList());
202 dd_list->setName("MueLu");
203 dd_list->set("verbosity", "low");
204 dd_list->set("number of equations", 1);
205 dd_list->set("max levels", 1);
206 dd_list->set("coarse: type", "SCHWARZ"); // FOR A ONE LEVEL PRECONDITIONER THE COARSE LEVEL IS INTERPRETED AS SMOOTHING LEVEL
207
208 Teuchos::ParameterList& dd_smooth_sublist = dd_list->sublist("coarse: params");
209 dd_smooth_sublist.set("schwarz: overlap level", 0);
210 dd_smooth_sublist.set("schwarz: combine mode", "Zero");
211 dd_smooth_sublist.set("subdomain solver name", "RILUK");
212
213 Teuchos::ParameterList& coarse_subdomain_solver = dd_smooth_sublist.sublist("subdomain solver parameters");
214 coarse_subdomain_solver.set("fact: iluk level-of-fill", 3);
215 coarse_subdomain_solver.set("fact: absolute threshold", 0.);
216 coarse_subdomain_solver.set("fact: relative threshold", 1.);
217 coarse_subdomain_solver.set("fact: relax value", 0.);
218
219 RCP<muelu_tpetra_operator_type> B_DD = MueLu::CreateTpetraPreconditioner((RCP<operator_type>)A, *dd_list);
220
221 // ===================================================
222 // Multi Grid Preconditioner
223 // ===================================
224 RCP<muelu_tpetra_operator_type> M;
225
226 // Manual set up of the prolongation and restriction
227 MueLu::ParameterListInterpreter<scalar_type> mueLuFactory(mueluParams);
228 RCP<MueLu::Hierarchy<scalar_type>> H = mueLuFactory.CreateHierarchy();
229 H->setVerbLevel(Teuchos::VERB_HIGH);
230
231 H->GetLevel(0)->Set("A", xpetraA);
232 H->GetLevel(0)->Set("Coordinates", coordinates);
233
234 // Multigrid setup phase
235 mueLuFactory.SetupHierarchy(*H);
236
237 RCP<Level> L = H->GetLevel(1);
238
239 RCP<Xpetra::Matrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type>> prolong, restr;
240
241 if (L->IsAvailable("P"))
242 prolong = L->template Get<RCP<Xpetra::Matrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type>>>("P");
243
244 if (L->IsAvailable("R"))
245 restr = L->template Get<RCP<Xpetra::Matrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type>>>("R");
246
247 RCP<crs_matrix_type> tpetra_prolong = toTpetra(prolong);
248 RCP<crs_matrix_type> tpetra_restr = toTpetra(restr);
249
250 Tpetra::MatrixMarket::Writer<crs_matrix_type>::writeSparseFile("P.mtx", tpetra_prolong); // Auxiliary prints introduced to generate pictures
251
252 RCP<Matrix> mueluPbar;
253
254 // We have to transform P into a condensed multivector
255 RCP<multivector_type> identity_shrunk = rcp(new multivector_type(tpetra_prolong->getDomainMap(), 3));
256 Teuchos::ArrayView<const global_ordinal_type> myIdentityGlobalElements = tpetra_prolong->getDomainMap()->getLocalElementList();
257 typedef typename Teuchos::ArrayView<const global_ordinal_type>::const_iterator iter_type;
258
259 for (int trial = 1; trial <= number_runs; ++trial) {
260 for (int j = 0; j < tpetra_prolong->getGlobalNumCols(); ++j) {
261 int color = j % 3;
262
263 Teuchos::ArrayRCP<scalar_type> localMV = identity_shrunk->getDataNonConst(color);
264
265 for (iter_type it = myIdentityGlobalElements.begin(); it != myIdentityGlobalElements.end(); ++it) {
266 const local_ordinal_type i_local = *it;
267 const local_ordinal_type aux = identity_shrunk->getMap()->getLocalElement(i_local);
268
269 if (i_local % 3 == color)
270 localMV[aux] = 1.0;
271 }
272 }
273
274 RCP<multivector_type> P_shrunk = rcp(new multivector_type(tpetra_prolong->getRangeMap(), 3));
275 tpetra_prolong->apply(*identity_shrunk, *P_shrunk);
276 RCP<multivector_type> AP_shrunk = rcp(new multivector_type(A->getRangeMap(), 3));
277 A->apply(*P_shrunk, *AP_shrunk);
278
279 //========================================================================================================
280
281 // CREATION OF BAP
282
283 RCP<multivector_type> BAP_multivector = rcp(new multivector_type(B_DD->getRangeMap(), AP_shrunk->getNumVectors()));
284 RCP<multivector_type> BAP_shrunk = rcp(new multivector_type(B_DD->getRangeMap(), AP_shrunk->getNumVectors()));
285 B_DD->apply(*AP_shrunk, *BAP_shrunk, Teuchos::NO_TRANS, Teuchos::ScalarTraits<scalar_type>::one(), Teuchos::ScalarTraits<scalar_type>::zero());
286
287 // I just need this to generate the right colMap to populate BAP
288 RCP<crs_matrix_type> AP = rcp(new crs_matrix_type(tpetra_prolong->getRowMap(), tpetra_prolong->getColMap(), tpetra_prolong->getGlobalNumRows()));
289 Tpetra::MatrixMatrix::Multiply(*A, false, *tpetra_prolong, false, *AP, true);
290
291 // Columns Map for BAP
292 std::vector<int> indBAPcolMap;
293 for (int i = 0; i < static_cast<size_t>(tpetra_prolong->getGlobalNumCols()); ++i)
294 indBAPcolMap.emplace_back(i);
295
296 Teuchos::ArrayView<const global_ordinal_type> elementListBAP(indBAPcolMap);
297 Teuchos::RCP<Tpetra::Map<local_ordinal_type, global_ordinal_type, node_type>> BAPcolMap = rcp(new Tpetra::Map<local_ordinal_type, global_ordinal_type, node_type>(static_cast<size_t>(tpetra_prolong->getGlobalNumCols()), elementListBAP, indexBase, comm));
298
299 RCP<crs_matrix_type> BAP = rcp(new crs_matrix_type(tpetra_prolong->getRowMap(), BAPcolMap, tpetra_prolong->getGlobalNumCols()));
300 Teuchos::ArrayView<const global_ordinal_type> myLocalElements = BAP->getRowMap()->getLocalElementList();
301
302 for (int color = 0; color < 3; ++color) {
303 Teuchos::ArrayRCP<const scalar_type> localBAP = BAP_shrunk->getData(color);
304
305 for (iter_type it = myLocalElements.begin(); it != myLocalElements.end(); ++it) {
306 const local_ordinal_type i_local = *it;
307 const local_ordinal_type aux = BAP->getRowMap()->getLocalElement(i_local);
308
309 std::vector<global_ordinal_type> BAP_inds;
310 std::vector<scalar_type> BAP_vals;
311
312 local_ordinal_type aux2;
313
314 if ((mypid - 1) % 3 == color && (mypid - 1) >= 0 && (mypid - 1) < tpetra_prolong->getGlobalNumCols())
315 aux2 = BAP->getColMap()->getLocalElement(mypid - 1);
316 else if ((mypid - 2) % 3 == color && (mypid - 2) >= 0 && (mypid - 2) < tpetra_prolong->getGlobalNumCols())
317 aux2 = BAP->getColMap()->getLocalElement(mypid - 2);
318 else if ((mypid) % 3 == color && (mypid) >= 0 && (mypid) < tpetra_prolong->getGlobalNumCols())
319 aux2 = BAP->getColMap()->getLocalElement(mypid);
320
321 if (aux2 >= 0) {
322 BAP_inds.emplace_back(aux2);
323 BAP_vals.emplace_back(localBAP[aux]);
324 BAP->insertLocalValues(aux, BAP_inds, BAP_vals);
325 }
326 }
327 }
328 BAP->fillComplete(tpetra_prolong->getDomainMap(), tpetra_prolong->getRangeMap());
329
330 //=============================================================================================================
331 RCP<crs_matrix_type> Pbar = Tpetra::MatrixMatrix::add(1.0, false, *tpetra_prolong, -1.0, false, *BAP);
332 mueluPbar = MueLu::TpetraCrs_To_XpetraMatrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type>(Pbar);
333 Tpetra::MatrixMarket::Writer<crs_matrix_type>::writeSparseFile("Pbar.mtx", Pbar); // Auxiliary prints introduced to generate pictures
334 }
335 H->GetLevel(1)->Set("Pbar", mueluPbar);
336
337 H->IsPreconditioner(true);
338
339 M = rcp(new muelu_tpetra_operator_type(H));
340
341 // Intermediate print before zeroing out the global timers (needed to split set up timing and solve timing)
342 Teuchos::TimeMonitor::summarize();
343 Teuchos::TimeMonitor::zeroOutTimers();
344 //======================================================================================================================
345
346 // Linear Solver
347
348 RCP<multivector_type> X_muelu = rcp(new multivector_type(map, 1));
349 RCP<multivector_type> B = rcp(new multivector_type(map, 1));
350 RCP<linear_problem_type> Problem_muelu;
351 X_muelu->putScalar((scalar_type)0.0);
352 B->randomize();
353
354 Problem_muelu = rcp(new linear_problem_type(A, X_muelu, B));
355
356 RCP<Teuchos::ParameterList> belosList = rcp(new Teuchos::ParameterList());
357 belosList->set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
358 belosList->set("Convergence Tolerance", tol); // Relative convergence tolerance requested
359 // belosList->set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
360 belosList->set("Verbosity", Belos::Errors);
361 belosList->set("Output Frequency", 1);
362 belosList->set("Output Style", Belos::Brief);
363 belosList->set("Implicit Residual Scaling", "None");
364 RCP<belos_solver_manager_type> solver;
365 if (krylovSolverType == "cg")
366 solver = rcp(new belos_pseudocg_manager_type(Problem_muelu, belosList));
367 else if (krylovSolverType == "gmres")
368 solver = rcp(new belos_gmres_manager_type(Problem_muelu, belosList));
369 else if (krylovSolverType == "bicgstab")
370 solver = rcp(new belos_bicgstab_manager_type(Problem_muelu, belosList));
371 else
372 throw std::invalid_argument("bad Krylov solver type");
373
374 for (int trial = 1; trial <= number_runs; ++trial) {
375 X_muelu->putScalar((scalar_type)0.0);
376 B->randomize();
377
378 //
379 // Set up Krylov solver and iterate.
380 //
381
382 Problem_muelu = rcp(new linear_problem_type(A, X_muelu, B));
383 Problem_muelu->setRightPrec(M);
384 Problem_muelu->setProblem();
385
386 solver->setProblem(Problem_muelu);
387 solver->solve();
388 int numIterations_muelu = solver->getNumIters();
389
390 Teuchos::Array<typename Teuchos::ScalarTraits<scalar_type>::magnitudeType> normVec_muelu(1);
391 multivector_type residual_muelu(B->getMap(), 1);
392 A->apply(*X_muelu, residual_muelu);
393 residual_muelu.update(1.0, *B, -1.0);
394 residual_muelu.norm2(normVec_muelu);
395 if (mypid == 0) {
396 std::cout << "number of iterations with MueLu preconditioner= " << numIterations_muelu << std::endl;
397 std::cout << "||Residual|| = " << normVec_muelu[0] << std::endl;
398 }
399 }
400
401 Teuchos::TimeMonitor::summarize();
402
403 return EXIT_SUCCESS;
404 }