Debian Codegraph @

packages/muelu/test/scaling/MatrixLoad.hpp

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 #ifndef MATRIXLOAD_HPP
11 #include <cstdio>
12 #include <iomanip>
13 #include <iostream>
14 #include <unistd.h>
15
16 #include <Teuchos_XMLParameterListHelpers.hpp>
17 #include <Teuchos_StandardCatchMacros.hpp>
18
19 // Xpetra
20 #include <Xpetra_MultiVectorFactory.hpp>
21 #include <Xpetra_ImportFactory.hpp>
22 #include <Xpetra_Operator.hpp>
23 #include <Xpetra_IO.hpp>
24
25 // Galeri
26 #include <Galeri_XpetraParameters.hpp>
27 #include <Galeri_XpetraProblemFactory.hpp>
28 #include <Galeri_XpetraUtils.hpp>
29 #include <Galeri_XpetraMaps.hpp>
30
31 #include <MueLu.hpp>
32
33 // This is a standard Galeri-or-MatrixFile loading routine designed to be shared between the various scaling tests
34
35 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
36 void MatrixLoad(Teuchos::RCP<const Teuchos::Comm<int> >& comm, Xpetra::UnderlyingLib& lib,
37 bool binaryFormat, const std::string& matrixFile, const std::string& rhsFile,
38 const std::string& rowMapFile,
39 const std::string& colMapFile,
40 const std::string& domainMapFile,
41 const std::string& rangeMapFile,
42 const std::string& coordFile,
43 const std::string& coordMapFile, const std::string& nullFile, const std::string& materialFile,
44 Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> >& map,
45 Teuchos::RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& A,
46 Teuchos::RCP<Xpetra::MultiVector<typename Teuchos::ScalarTraits<Scalar>::magnitudeType, LocalOrdinal, GlobalOrdinal, Node> >& coordinates,
47 Teuchos::RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& nullspace,
48 Teuchos::RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& material,
49 Teuchos::RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& X,
50 Teuchos::RCP<Xpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& B,
51 const int numVectors,
52 Galeri::Xpetra::Parameters<GlobalOrdinal>& galeriParameters, Xpetra::Parameters& xpetraParameters,
53 std::ostringstream& galeriStream) {
54 #include <MueLu_UseShortNames.hpp>
55 using Teuchos::RCP;
56 using Teuchos::rcp;
57 using Teuchos::TimeMonitor;
58 typedef Teuchos::ScalarTraits<SC> STS;
59 SC zero = STS::zero(), one = STS::one();
60 typedef typename STS::magnitudeType real_type;
61 typedef Xpetra::MultiVector<real_type, LO, GO, NO> RealValuedMultiVector;
62
63 Teuchos::ParameterList galeriList = galeriParameters.GetParameterList();
64 galeriStream << "========================================================\n"
65 << xpetraParameters;
66 if (matrixFile.empty()) {
67 galeriStream << galeriParameters;
68
69 // Galeri will attempt to create a square-as-possible distribution of subdomains di, e.g.,
70 // d1 d2 d3
71 // d4 d5 d6
72 // d7 d8 d9
73 // d10 d11 d12
74 // A perfect distribution is only possible when the #processors is a perfect square.
75 // This *will* result in "strip" distribution if the #processors is a prime number or if the factors are very different in
76 // size. For example, np=14 will give a 7-by-2 distribution.
77 // If you don't want Galeri to do this, specify mx or my on the galeriList.
78 std::string matrixType = galeriParameters.GetMatrixType();
79
80 // Create map and coordinates
81 // In the future, we hope to be able to first create a Galeri problem, and then request map and coordinates from it
82 // At the moment, however, things are fragile as we hope that the Problem uses same map and coordinates inside
83 if (matrixType == "Laplace1D" || matrixType == "Identity") {
84 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
85 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<real_type, LO, GO, Map, RealValuedMultiVector>("1D", map, galeriList);
86
87 } else if (matrixType == "Laplace2D" || matrixType == "Star2D" ||
88 matrixType == "BigStar2D" || matrixType == "AnisotropicDiffusion" || matrixType == "Elasticity2D") {
89 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
90 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<real_type, LO, GO, Map, RealValuedMultiVector>("2D", map, galeriList);
91
92 } else if (matrixType == "Laplace3D" || matrixType == "Brick3D" || matrixType == "Elasticity3D") {
93 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
94 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<real_type, LO, GO, Map, RealValuedMultiVector>("3D", map, galeriList);
95 }
96
97 // Expand map to do multiple DOF per node for block problems
98 if (matrixType == "Elasticity2D")
99 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 2);
100 if (matrixType == "Elasticity3D")
101 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 3);
102
103 galeriStream << "Processor subdomains in x direction: " << galeriList.get<GO>("mx") << std::endl
104 << "Processor subdomains in y direction: " << galeriList.get<GO>("my") << std::endl
105 << "Processor subdomains in z direction: " << galeriList.get<GO>("mz") << std::endl
106 << "========================================================" << std::endl;
107
108 if (matrixType == "Elasticity2D" || matrixType == "Elasticity3D") {
109 // Our default test case for elasticity: all boundaries of a square/cube have Neumann b.c. except left which has Dirichlet
110 galeriList.set("right boundary", "Neumann");
111 galeriList.set("bottom boundary", "Neumann");
112 galeriList.set("top boundary", "Neumann");
113 galeriList.set("front boundary", "Neumann");
114 galeriList.set("back boundary", "Neumann");
115 }
116
117 RCP<Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> > Pr =
118 Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(galeriParameters.GetMatrixType(), map, galeriList);
119 A = Pr->BuildMatrix();
120 nullspace = Pr->BuildNullspace();
121 // The coordinates used by Galeri here might not match the coordinates that come into this function.
122 // In particular, they might correspond to different stretch factors. To fix this, we overwrite the
123 // coordinate array with those that Galeri now provides.
124
125 if (!coordinates.is_null() && (matrixType == "Elasticity2D" || matrixType == "Elasticity3D")) {
126 Teuchos::RCP<Xpetra::MultiVector<real_type, LocalOrdinal, GlobalOrdinal, Node> > newcoordinates;
127 newcoordinates = Pr->BuildCoords();
128
129 // Galeri makes multiple copies of coordinates to deal with
130 // some issues when Ndofs != Nmeshnodes
131
132 for (size_t kkk = 0; kkk < coordinates->getNumVectors(); kkk++) {
133 Teuchos::ArrayRCP<real_type> old = coordinates->getDataNonConst(kkk);
134 Teuchos::ArrayRCP<real_type> newvals = newcoordinates->getDataNonConst(kkk);
135 int numCopies = newvals.size() / old.size();
136 for (int jj = 0; jj < old.size(); jj++) old[jj] = newvals[numCopies * jj];
137 }
138 }
139
140 if (matrixType == "Elasticity2D" ||
141 matrixType == "Elasticity3D") {
142 A->SetFixedBlockSize((galeriParameters.GetMatrixType() == "Elasticity2D") ? 2 : 3);
143 }
144
145 } else {
146 if (!rowMapFile.empty())
147 map = Xpetra::IO<SC, LO, GO, Node>::ReadMap(rowMapFile, lib, comm);
148 comm->barrier();
149
150 {
151 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1a - Matrix read")));
152 if (!binaryFormat && !map.is_null()) {
153 RCP<const Map> colMap = (!colMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(colMapFile, lib, comm) : Teuchos::null);
154 RCP<const Map> domainMap = (!domainMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(domainMapFile, lib, comm) : Teuchos::null);
155 RCP<const Map> rangeMap = (!rangeMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(rangeMapFile, lib, comm) : Teuchos::null);
156 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFile, map, colMap, domainMap, rangeMap);
157
158 } else {
159 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFile, lib, comm, binaryFormat);
160 }
161 comm->barrier();
162 } // timer scope
163
164 // If no rowmap file has been provided and the driver is being run in parallel,
165 // create a uniformly distributed map and use it as A's row map.
166 if (map.is_null() && comm->getSize() > 1) {
167 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1b - Matrix redistribute")));
168 if (comm->getRank() == 0)
169 std::cout << "No rowmap file specified, redistributing matrix using a uniformly distributed rowmap." << std::endl;
170 map = Xpetra::MapFactory<LO, GO, Node>::Build(lib, A->getRowMap()->getGlobalNumElements(), (int)0, comm);
171
172 RCP<Matrix> newMatrix = MatrixFactory::Build(map, 1);
173 RCP<Import> importer = ImportFactory::Build(A->getRowMap(), map);
174 newMatrix->doImport(*A, *importer, Xpetra::INSERT);
175 newMatrix->fillComplete();
176
177 A.swap(newMatrix);
178 } else {
179 map = A->getRowMap();
180 }
181
182 comm->barrier();
183 }
184
185 if (!coordFile.empty()) {
186 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1c - Read coordinates")));
187 RCP<const Map> coordMap;
188 if (!coordMapFile.empty())
189 coordMap = Xpetra::IO<SC, LO, GO, Node>::ReadMap(coordMapFile, lib, comm);
190 else
191 coordMap = map;
192 coordinates = Xpetra::IO<real_type, LO, GO, Node>::ReadMultiVector(coordFile, coordMap);
193 comm->barrier();
194 }
195
196 if (!nullFile.empty()) {
197 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1d - Read nullspace")));
198 nullspace = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(nullFile, map);
199 comm->barrier();
200 }
201
202 if (!materialFile.empty()) {
203 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1e - Read material")));
204 material = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(materialFile, map);
205 comm->barrier();
206 }
207
208 X = MultiVectorFactory::Build(map, numVectors);
209 B = MultiVectorFactory::Build(map, numVectors);
210
211 if (rhsFile.empty()) {
212 // we set seed for reproducibility
213 Utilities::SetRandomSeed(*comm);
214 X->randomize();
215 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
216
217 Teuchos::Array<real_type> norms(numVectors);
218 B->norm2(norms);
219 B->scale(one / norms[0]);
220
221 } else {
222 // read in B
223 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1d - Read RHS")));
224 B = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(rhsFile, map);
225 comm->barrier();
226 }
227 galeriStream << "Galeri complete.\n========================================================" << std::endl;
228 }
229
230 // Read in block information when doing user based blocks smoothing via "partitioner: global ID parts"
231 // Block information is read from file userBlkFileName. This file is assumed to be 'MatrixMarket
232 // matrix coordinate real general' where each row corresponds defines one
233 // block. Specifically, each point dof j residing in the ith block is
234 // indicated by having a nonzero (i,j) in userBlkFileName. The file reader
235 // makes the following additional assumptions
236 // 1) The first line in the file is a comment
237 // 2) all file entries defining blk k occur before
238 // file entries defining blk k+1.
239 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
240 void readUserBlks(const std::string& userBlkFileName, const std::string& smootherOrCoarse, Teuchos::ParameterList& mueluList,
241 const Teuchos::RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& A) {
242 // userBlkFileName MatrixMarket file defining blocks
243 // smootherOrCoarse Whether blocks are associated with "smoother: params" or "coarse: params"
244 // mueluList Parameter list that is modified to reflect block informaiton found in file
245 // A Matrix that block smoother will be applied to
246 using Teuchos::ArrayRCP;
247 using Teuchos::ParameterList;
248 using Teuchos::RCP;
249 using Teuchos::rcp;
250 using Teuchos::TimeMonitor;
251
252 RCP<const Teuchos::Comm<int> > comm = A->getRowMap()->getComm();
253
254 TEUCHOS_TEST_FOR_EXCEPTION((smootherOrCoarse != "smoother") && (smootherOrCoarse != "coarse"),
255 std::runtime_error, "2nd argument to readUserBlks must be either \"smoother\" or \"coarse\" and not \"" + smootherOrCoarse + "\"");
256 if ((!userBlkFileName.empty()) && (mueluList.isSublist(smootherOrCoarse + ": params"))) {
257 bool hasSubdomSolver = mueluList.sublist(smootherOrCoarse + ": params").isSublist("subdomain solver parameters");
258 if (hasSubdomSolver) {
259 if (mueluList.sublist(smootherOrCoarse + ": params").sublist("subdomain solver parameters").isParameter("partitioner: type")) {
260 if (mueluList.sublist(smootherOrCoarse + ": params").sublist("subdomain solver parameters").get<std::string>("partitioner: type") == "user") {
261 FILE* fp;
262 int retVal;
263 int nBlks, nRows, nnzs, row, col;
264 int procId = comm->getRank();
265 double val;
266
267 /* read block information from file only to count the # of rows */
268 /* we own within each block. We'll reopen the file later to fill*/
269 /* the Teuchos::Array for "partitioner: global ID parts" */
270
271 fp = fopen(&userBlkFileName[0], "r");
272 TEUCHOS_TEST_FOR_EXCEPTION(fp == NULL, std::runtime_error, userBlkFileName + " file not found");
273
274 while ((getc(fp) != '\n'))
275 ; // read first line
276
277 retVal = fscanf(fp, "%d %d %d\n", &nBlks, &nRows, &nnzs);
278 TEUCHOS_TEST_FOR_EXCEPTION(retVal != 3,
279 std::runtime_error, "unable to parse nBlks, nRows, nnzs in user file " + userBlkFileName);
280
281 TEUCHOS_TEST_FOR_EXCEPTION(nRows != (int)A->getRowMap()->getGlobalNumElements(),
282 std::runtime_error, "number of global rows in " + userBlkFileName + " does not match those in A");
283
284 Teuchos::ArrayRCP<int> myOwnedRowsPerBlock(nBlks, 0);
285
286 for (int i = 0; i < nnzs; i++) {
287 retVal = fscanf(fp, "%d %d %lf", &row, &col, &val);
288 row--;
289 col--;
290 if (A->getRowMap()->getLocalElement((GlobalOrdinal)col) != Teuchos::OrdinalTraits<LocalOrdinal>::invalid()) (myOwnedRowsPerBlock[row])++;
291 }
292 fclose(fp);
293
294 // Assign ownership of each block to one mpirank corresponding
295 // to which mpirank owns the most rows within a block. When
296 // ties occur, highest procId wins.
297
298 // first, set to procId+1 if we own the largest # of rows
299 // in block. Otherwise, set to 0.
300
301 Teuchos::ArrayRCP<int> maxOwnedRowsPerBlock(nBlks, 0);
302 Teuchos::reduceAll(*comm, Teuchos::REDUCE_MAX, (LocalOrdinal)nBlks, myOwnedRowsPerBlock.getRawPtr(), maxOwnedRowsPerBlock.getRawPtr());
303
304 Teuchos::ArrayRCP<int> haveMaxOwned(nBlks, 0);
305 for (int i = 0; i < nBlks; i++) {
306 haveMaxOwned[i] = 0;
307 if ((myOwnedRowsPerBlock[i] == maxOwnedRowsPerBlock[i]) && (myOwnedRowsPerBlock[i] > 0)) haveMaxOwned[i] = procId + 1;
308 }
309 Teuchos::ArrayRCP<int> maxProcIdPlusOne(nBlks, 0);
310 Teuchos::reduceAll(*comm, Teuchos::REDUCE_MAX, (LocalOrdinal)nBlks, haveMaxOwned.getRawPtr(), maxProcIdPlusOne.getRawPtr());
311
312 Teuchos::ArrayRCP<bool> ownBlk(nBlks, false);
313 int nOwned = 0;
314 int maxDofsInAnyBlock = 0;
315 for (int i = 0; i < nBlks; i++) {
316 TEUCHOS_TEST_FOR_EXCEPTION(maxProcIdPlusOne[i] == 0, std::runtime_error,
317 "some blocks are not owned by any processor?");
318 if (maxProcIdPlusOne[i] == procId + 1) {
319 ownBlk[i] = true;
320 nOwned++;
321 maxDofsInAnyBlock += myOwnedRowsPerBlock[i];
322 }
323 }
324 maxDofsInAnyBlock *= 2; // We only have an estimate as to the largest number of dofs in any block (as some dofs
325 maxDofsInAnyBlock++; // might reside on other processors. So we multiple our estimate by 2 hoping to be large
326 // enough. Later, we check to see if things are not large enough and re-allocate space
327 // in this case.
328
329 Teuchos::Array<Teuchos::ArrayRCP<GlobalOrdinal> > blockLists(nOwned, Teuchos::null);
330
331 Teuchos::Array<int> buffer(maxDofsInAnyBlock, 0);
332
333 int curRow, currentOwnedRow = 0;
334
335 // reopen userBlkFilename and record block information in blockLists
336
337 fp = fopen(&userBlkFileName[0], "r");
338 TEUCHOS_TEST_FOR_EXCEPTION(fp == NULL, std::runtime_error, userBlkFileName + " file not found");
339
340 while ((getc(fp) != '\n'))
341 ;
342
343 retVal = fscanf(fp, "%d %d %d\n", &nBlks, &nRows, &nnzs);
344 TEUCHOS_TEST_FOR_EXCEPTION(retVal != 3,
345 std::runtime_error, "unable to parse nBlks, nRows, nnzs in user file " + userBlkFileName);
346
347 retVal = fscanf(fp, "%d %d %lf", &row, &col, &val);
348 row = row - 1;
349 col = col - 1;
350
351 int jj = 1;
352 while (jj <= nnzs) {
353 if (ownBlk[row] == true) {
354 int i = 0;
355 curRow = row;
356 while ((row == curRow) && (jj <= nnzs)) {
357 if (i == maxDofsInAnyBlock) {
358 maxDofsInAnyBlock *= 2;
359 buffer.resize(maxDofsInAnyBlock);
360 }
361 buffer[i] = col;
362 i++;
363 retVal = fscanf(fp, "%d %d %lf", &row, &col, &val);
364 jj++;
365 row = row - 1;
366 col = col - 1;
367 }
368 blockLists[currentOwnedRow] = Teuchos::arcp<GlobalOrdinal>(i);
369 for (int k = 0; k < i; k++) {
370 blockLists[currentOwnedRow][k] = (GlobalOrdinal)buffer[k];
371 }
372 currentOwnedRow++;
373 } else {
374 retVal = fscanf(fp, "%d %d %lf", &row, &col, &val);
375 jj++;
376 row = row - 1;
377 col = col - 1;
378 }
379 }
380 fclose(fp);
381 mueluList.sublist(smootherOrCoarse + ": params").sublist("subdomain solver parameters").set<Teuchos::Array<Teuchos::ArrayRCP<GlobalOrdinal> > >("partitioner: global ID parts", blockLists);
382 }
383 }
384 }
385 }
386 }
387
388 #endif