Debian Codegraph @

packages/muelu/research/tawiesn/crada/Driver.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 #include <sstream>
12 #include <string>
13 #include <fstream>
14
15 #include <Xpetra_MapExtractorFactory.hpp>
16 #include <Xpetra_MultiVectorFactory.hpp>
17 #include <Xpetra_StridedMapFactory.hpp>
18 #include <Xpetra_IO.hpp>
19 #include <Xpetra_MatrixUtils.hpp>
20
21 // Teuchos
22 #include <Teuchos_StandardCatchMacros.hpp>
23 #include <Teuchos_XMLParameterListHelpers.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
32 #include <MueLu.hpp>
33 #include <MueLu_Exceptions.hpp>
34 #include <MueLu_Level.hpp>
35 #include <MueLu_BaseClass.hpp>
36 #include <MueLu_ParameterListInterpreter.hpp> // TODO: move into MueLu.hpp
37 #include <MueLu_VisualizationHelpers.hpp>
38
39 #include <MueLu_Utilities.hpp>
40
41 #include <MueLu_MutuallyExclusiveTime.hpp>
42
43 #ifdef HAVE_MUELU_BELOS
44 #include <BelosConfigDefs.hpp>
45 #include <BelosLinearProblem.hpp>
46 #include <BelosBlockCGSolMgr.hpp>
47 #include <BelosPseudoBlockGmresSolMgr.hpp>
48 #include <BelosXpetraStatusTestGenResSubNorm.hpp>
49 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
50 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
51 #endif
52
53 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
54 class ExportVTK : public MueLu::VisualizationHelpers<Scalar, LocalOrdinal, GlobalOrdinal, Node> {
55 public:
56 using real_type = typename Teuchos::ScalarTraits<Scalar>::coordinateType;
57 using RealValuedMultiVector = typename Xpetra::MultiVector<real_type, LocalOrdinal, GlobalOrdinal, Node>;
58
59 ExportVTK(){};
60
61 public:
62 void writeFile(std::ofstream& fout, Teuchos::RCP<RealValuedMultiVector>& coordinates, Teuchos::RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node> >& sol) {
63 using namespace std;
64 typedef MueLu::VisualizationHelpers<Scalar, LocalOrdinal, GlobalOrdinal, Node> VH;
65 Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > nodeMap = coordinates->getMap();
66 std::vector<LocalOrdinal> vertices;
67 std::vector<LocalOrdinal> geomSize;
68 LocalOrdinal numFineNodes = Teuchos::as<LocalOrdinal>(coordinates->getLocalLength());
69
70 vertices.reserve(numFineNodes);
71 geomSize.reserve(numFineNodes);
72 for (LocalOrdinal i = 0; i < numFineNodes; i++) {
73 vertices.push_back(i);
74 geomSize.push_back(1);
75 }
76
77 Teuchos::ArrayRCP<const real_type> xCoords = Teuchos::arcp_reinterpret_cast<const real_type>(coordinates->getData(0));
78 Teuchos::ArrayRCP<const real_type> yCoords = Teuchos::arcp_reinterpret_cast<const real_type>(coordinates->getData(1));
79 Teuchos::ArrayRCP<const real_type> zCoords = Teuchos::null;
80 if (coordinates->getNumVectors() == 3) {
81 zCoords = Teuchos::arcp_reinterpret_cast<const real_type>(coordinates->getData(2));
82 }
83 Teuchos::ArrayRCP<const Scalar> solData = Teuchos::arcp_reinterpret_cast<const Scalar>(sol->getData(0));
84
85 std::vector<int> uniqueFine = this->makeUnique(vertices);
86 this->writeFileVTKOpening(fout, uniqueFine, geomSize);
87 this->writeFileVTKNodes(fout, uniqueFine, nodeMap);
88
89 std::string indent = " ";
90 fout << " <DataArray type=\"Int32\" Name=\"Processor\" format=\"ascii\">" << std::endl;
91 fout << indent;
92 int myRank = coordinates->getMap()->getComm()->getRank();
93 for (int i = 0; i < int(uniqueFine.size()); i++) {
94 fout << myRank << " ";
95 if (i % 20 == 19)
96 fout << std::endl
97 << indent;
98 }
99 fout << std::endl;
100 fout << " </DataArray>" << std::endl;
101 // solution vector
102 fout << " <DataArray type=\"Float64\" Name=\"Solution\" NumberOfComponents=\"3\" format=\"ascii\">" << std::endl;
103 fout << indent;
104 for (int i = 0; i < int(uniqueFine.size()); i++) {
105 size_t numVec = coordinates->getNumVectors();
106 for (int d = 0; d < (int)numVec; d++)
107 fout << solData[i * numVec + d] << " ";
108 if (i % 3 == 0)
109 fout << std::endl
110 << indent;
111 }
112 fout << std::endl;
113 fout << " </DataArray>" << std::endl;
114 fout << " </PointData>" << std::endl; // that is annoying
115
116 this->writeFileVTKCoordinates(fout, uniqueFine, xCoords, yCoords, zCoords, coordinates->getNumVectors());
117 this->writeFileVTKCells(fout, uniqueFine, vertices, geomSize);
118 this->writeFileVTKClosing(fout);
119 fout.close();
120 };
121 };
122
123 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
124 int main_(Teuchos::CommandLineProcessor& clp, Xpetra::UnderlyingLib lib, int argc, char* argv[]) {
125 #include <MueLu_UseShortNames.hpp>
126
127 using Teuchos::RCP; // reference count pointers
128 using Teuchos::rcp;
129 using Teuchos::TimeMonitor;
130 using TST = Teuchos::ScalarTraits<SC>;
131 using MT = typename Teuchos::ScalarTraits<SC>::magnitudeType;
132 using real_type = typename Teuchos::ScalarTraits<SC>::coordinateType;
133 using RealValuedMultiVector = Xpetra::MultiVector<real_type, LO, GO, NO>;
134 // =========================================================================
135 // MPI initialization using Teuchos
136 // =========================================================================
137
138 bool success = false;
139 bool verbose = true;
140 try {
141 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
142
143 // =========================================================================
144 // Convenient definitions
145 // =========================================================================
146 SC zero = TST::zero(), one = TST::one();
147
148 // Instead of checking each time for rank, create a rank 0 stream
149 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
150 Teuchos::FancyOStream& fancyout = *fancy;
151 fancyout.setOutputToRootOnly(0);
152
153 // =========================================================================
154 // Parameters initialization
155 // =========================================================================
156
157 // GO nx = 100, ny = 100, nz = 100;
158 // Galeri::Xpetra::Parameters<GO> matrixParameters(clp, nx, ny, nz, "Laplace2D"); // manage parameters of the test case
159 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
160
161 std::string xmlFileName = "driver.xml";
162 clp.setOption("xml", &xmlFileName, "read parameters from a file. Otherwise, this example uses by default 'scalingTest.xml'");
163 std::string belosFileName = "";
164 clp.setOption("belosXml", &belosFileName, "read parameters for Belos from a file.");
165 int amgAsPrecond = 1;
166 clp.setOption("precond", &amgAsPrecond, "apply multigrid as preconditioner");
167 int amgAsSolver = 0;
168 clp.setOption("fixPoint", &amgAsSolver, "apply multigrid as solver");
169 bool printTimings = true;
170 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
171 int blockedSystem = 1;
172 clp.setOption("split", &blockedSystem, "split system matrix into 2x2 system (default=0)");
173 int useThyraGIDs = 0;
174 clp.setOption("thyra", &useThyraGIDs, "use Thyra style numbering of GIDs.");
175 int writeMatricesOPT = -2;
176 clp.setOption("write", &writeMatricesOPT, "write matrices to file (-1 means all; i>=0 means level i)");
177 double tol = 1e-6;
178 clp.setOption("tol", &tol, "solver convergence tolerance");
179 std::string krylovMethod = "gmres";
180 clp.setOption("krylov", &krylovMethod, "outer Krylov method");
181 int maxIts = 100;
182 clp.setOption("maxits", &maxIts, "maximum number of Krylov iterations");
183 int output = 1;
184 clp.setOption("output", &output, "how often to print Krylov residual history");
185 std::string matrixFileName = "crada1/crada_A.mm";
186 clp.setOption("matrixfile", &matrixFileName, "matrix market file containing matrix");
187 std::string rhsFileName = "crada1/crada_b.mm";
188 clp.setOption("rhsfile", &rhsFileName, "matrix market file containing right-hand side");
189 std::string nspFileName = "crada1/crada_ns.mm";
190 clp.setOption("nspfile", &nspFileName, "matrix market file containing fine level null space");
191 std::string cooFileName = "crada1/crada_coordinates.mm";
192 clp.setOption("coordinatesfile", &cooFileName, "matrix market file containing fine level coordinates");
193 std::string spcFileName = "crada1/crada_special.mm";
194 clp.setOption("specialfile", &spcFileName, "matrix market file containing fine level special dofs");
195 int nPDE = 3;
196 clp.setOption("numpdes", &nPDE, "number of PDE equations");
197 int nNspVectors = 6;
198 clp.setOption("numnsp", &nNspVectors, "number of nullspace vectors. Only used if null space is read from file. Must be smaller or equal than the number of null space vectors read in from file.");
199 std::string convType = "r0";
200 clp.setOption("convtype", &convType, "convergence type (r0 or none)");
201 std::string strOutputFilename = "";
202 clp.setOption("output", &strOutputFilename, "filename prefix for output file name. If empty, no output is written.");
203
204 switch (clp.parse(argc, argv)) {
205 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS; break;
206 case Teuchos::CommandLineProcessor::PARSE_ERROR:
207 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE; break;
208 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
209 }
210
211 // =========================================================================
212 // Problem construction
213 // =========================================================================
214 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MatrixRead: S - Global Time"))), tm;
215
216 comm->barrier();
217 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1 - Matrix Build")));
218
219 RCP<Matrix> A = Teuchos::null;
220 if (matrixFileName != "") {
221 fancyout << "Read matrix from file " << matrixFileName << std::endl;
222 RCP<Matrix> Atest = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileName), xpetraParameters.GetLib(), comm);
223 RCP<const Map> maptest = Atest->getRowMap();
224
225 // re-read matrix and make sure it is properly distributed over all processors
226 // make sure that all DOF rows per node are located on same processor.
227 GO numGlobalNodes = maptest->getGlobalNumElements() / nPDE;
228 GO numMyNodes = numGlobalNodes / comm->getSize();
229 if (comm->getRank() == comm->getSize() - 1)
230 numMyNodes = numGlobalNodes - (comm->getSize() - 1) * numMyNodes;
231 LO numMyDofs = Teuchos::as<LocalOrdinal>(numMyNodes) * nPDE;
232
233 // construct new row map for equally distributing the matrix rows without
234 // splitting dofs that belong to the same node
235 Teuchos::Array<GO> myDofGIDs(numMyDofs);
236 for (LO i = 0; i < numMyDofs; i++) {
237 if (comm->getRank() == comm->getSize() - 1)
238 myDofGIDs[i] = Teuchos::as<GO>(maptest->getGlobalNumElements()) - Teuchos::as<GO>(numMyDofs - i);
239 else
240 myDofGIDs[i] = Teuchos::as<GO>(comm->getRank() * numMyDofs) + Teuchos::as<GO>(i);
241 }
242 RCP<const Map> Arowmap = MapFactory::Build(xpetraParameters.GetLib(), Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(), myDofGIDs(), 0, comm);
243
244 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFileName, Arowmap);
245 A->SetFixedBlockSize(Teuchos::as<LocalOrdinal>(nPDE));
246 }
247 RCP<const Map> map = A->getRowMap();
248 RCP<MultiVector> nullspace = MultiVectorFactory::Build(A->getDomainMap(), nPDE);
249 A->SetFixedBlockSize(nPDE);
250 fancyout << "#pdes = " << A->GetFixedBlockSize() << std::endl;
251
252 if (nspFileName != "") {
253 fancyout << "Read null space from file " << nspFileName << std::endl;
254
255 nullspace = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(std::string(nspFileName), A->getRowMap());
256 // nullspace = MultiVectorFactory::Build(A->getRowMap(),6);//haq
257 fancyout << "Found " << nullspace->getNumVectors() << " null space vectors" << std::endl;
258 if (nNspVectors > Teuchos::as<int>(nullspace->getNumVectors())) {
259 fancyout << "Set number of null space vectors from " << nNspVectors << " to " << nullspace->getNumVectors() << " as only " << nullspace->getNumVectors() << " are provided by " << nspFileName << std::endl;
260 nNspVectors = nullspace->getNumVectors();
261 }
262 if (nNspVectors < 1) {
263 fancyout << "Set number of null space vectors from " << nNspVectors << " to " << nullspace->getNumVectors() << ". Note: we need at least one null space vector!!!" << std::endl;
264 nNspVectors = nullspace->getNumVectors();
265 }
266 if (nNspVectors < Teuchos::as<int>(nullspace->getNumVectors())) {
267 RCP<MultiVector> temp = MultiVectorFactory::Build(A->getDomainMap(), nNspVectors);
268 for (int j = 0; j < nNspVectors; j++) {
269 Teuchos::ArrayRCP<SC> tempData = temp->getDataNonConst(j);
270 Teuchos::ArrayRCP<const SC> nsData = nullspace->getData(j);
271 for (int i = 0; i < nsData.size(); ++i) {
272 tempData[i] = nsData[i];
273 }
274 }
275 nullspace = Teuchos::null;
276 nullspace = temp;
277 }
278 } else {
279 if (nPDE == 1)
280 nullspace->putScalar(Teuchos::ScalarTraits<SC>::one());
281 else {
282 for (int i = 0; i < nPDE; ++i) {
283 Teuchos::ArrayRCP<SC> nsData = nullspace->getDataNonConst(i);
284 for (int j = 0; j < nsData.size(); ++j) {
285 GO gel = A->getDomainMap()->getGlobalElement(j) - A->getDomainMap()->getIndexBase();
286 if ((gel - i) % nPDE == 0)
287 nsData[j] = Teuchos::ScalarTraits<SC>::one();
288 }
289 }
290 }
291 }
292
293 RCP<RealValuedMultiVector> coordinates = Teuchos::null; // MultiVectorFactory::Build(A->getDomainMap(),1);
294 if (cooFileName != "") {
295 TEUCHOS_TEST_FOR_EXCEPTION(map->getLocalNumElements() % A->GetFixedBlockSize() != 0, MueLu::Exceptions::RuntimeError, "Driver: Number of DOFs on proc " << comm->getRank() << " is " << map->getLocalNumElements() << " and not divisible by 3.");
296
297 Teuchos::ArrayView<const GO> dofGidList = map->getLocalElementList();
298 GlobalOrdinal indexBase = map->getIndexBase();
299 LocalOrdinal blkSize = A->GetFixedBlockSize();
300 TEUCHOS_TEST_FOR_EXCEPTION(Teuchos::as<size_t>(dofGidList.size()) != Teuchos::as<size_t>(map->getLocalNumElements()), MueLu::Exceptions::RuntimeError, "Driver: Number of local DOFs inconsistent.");
301
302 size_t numNodes = dofGidList.size() / blkSize;
303 Teuchos::Array<GO> nodeList(numNodes);
304
305 // Amalgamate the map
306 for (LO i = 0; i < Teuchos::as<LO>(numNodes); i++)
307 nodeList[i] = (dofGidList[i * blkSize] - indexBase) / blkSize + indexBase;
308
309 TEUCHOS_TEST_FOR_EXCEPTION(dofGidList.size() / blkSize != nodeList.size(), MueLu::Exceptions::RuntimeError, "Driver: Number of local DOFs and local Nodes inconsistent.");
310
311 GO gCntGIDs = 0;
312 GO glCntGIDs = Teuchos::as<GlobalOrdinal>(nodeList.size());
313 MueLu_sumAll(comm, glCntGIDs, gCntGIDs);
314
315 // Teuchos::Array<GlobalOrdinal> eltList(myGIDs);
316 RCP<const Map> myCoordMap = MapFactory::Build(xpetraParameters.GetLib(), gCntGIDs, nodeList(), indexBase, comm);
317
318 fancyout << "Read fine level coordinates from file " << cooFileName << std::endl;
319 coordinates = Xpetra::IO<real_type, LO, GO, Node>::ReadMultiVector(std::string(cooFileName), myCoordMap);
320 fancyout << "Found " << coordinates->getNumVectors() << " coordinate vectors of length " << myCoordMap->getGlobalNumElements() << std::endl;
321 /*TEUCHOS_TEST_FOR_EXCEPTION(myCoordMap->getMinGlobalIndex() != map->getMinGlobalIndex() / blkSize, MueLu::Exceptions::RuntimeError,
322 "Driver: Inconsistent minGlobalIndex on proc " << comm->getRank());
323 TEUCHOS_TEST_FOR_EXCEPTION(myCoordMap->getMaxGlobalIndex() != map->getMaxGlobalIndex() / blkSize, MueLu::Exceptions::RuntimeError,
324 "Driver: Inconsistent maxGlobalIndex on proc " << comm->getRank());*/
325 }
326
327 // shouldn't these be const?
328 RCP<Map> mySpecialMap = Teuchos::null;
329 if (spcFileName != "") {
330 // read file on each processor and pick out the special dof numbers which belong to the current proc
331 std::ifstream infile(spcFileName);
332 std::string line;
333 Teuchos::Array<GlobalOrdinal> mySpecialGids;
334 Teuchos::Array<GlobalOrdinal> nonSpecialGids;
335 GlobalOrdinal cnt = 0; // count overall number of gids
336 // GlobalOrdinal mycnt = 0; // count only local gids
337 while (std::getline(infile, line)) {
338 if (0 == line.find("%")) continue;
339 if (0 == line.find(" ")) {
340 cnt++;
341 GlobalOrdinal gid;
342 std::istringstream iss(line);
343 iss >> gid;
344 gid--; // note, that the matlab vector starts counting at 1 and not 0!
345 if (map->isNodeGlobalElement(gid)) {
346 mySpecialGids.push_back(gid);
347 // mycnt++;
348 }
349 }
350 }
351
352 std::vector<GlobalOrdinal> mySpecialNodeGids;
353 for (size_t k = 0; k < Teuchos::as<size_t>(mySpecialGids.size()); k++) {
354 mySpecialNodeGids.push_back(mySpecialGids[k] / 3);
355 }
356
357 std::sort(mySpecialNodeGids.begin(), mySpecialNodeGids.end());
358 mySpecialNodeGids.erase(std::unique(mySpecialNodeGids.begin(), mySpecialNodeGids.end()), mySpecialNodeGids.end());
359
360 cnt = 0;
361 Teuchos::Array<GlobalOrdinal> myFinalSpecialGids;
362 for (size_t k = 0; k < mySpecialNodeGids.size(); k++) {
363 myFinalSpecialGids.push_back(mySpecialNodeGids[k] * 3);
364 myFinalSpecialGids.push_back(mySpecialNodeGids[k] * 3 + 1);
365 myFinalSpecialGids.push_back(mySpecialNodeGids[k] * 3 + 2);
366 cnt += 3;
367 }
368
369 std::cout << "Number of special gids read: " << mySpecialGids.size() << " Final number of special gids: " << myFinalSpecialGids.size() << std::endl;
370
371 // Teuchos::Array<GlobalOrdinal> eltList(mySpecialGids);
372 mySpecialMap = MapFactory::Build(xpetraParameters.GetLib(), cnt, myFinalSpecialGids(), 0, comm);
373
374 // empty processors
375 std::vector<size_t> lelePerProc(comm->getSize(), 0);
376 std::vector<size_t> gelePerProc(comm->getSize(), 0);
377 lelePerProc[comm->getRank()] = mySpecialMap->getLocalNumElements();
378 Teuchos::reduceAll(*comm, Teuchos::REDUCE_MAX, comm->getSize(), &lelePerProc[0], &gelePerProc[0]);
379 if (comm->getRank() == 0) {
380 fancyout << "Distribution of " << cnt << " special dofs over processors:" << std::endl;
381 fancyout << "Proc #DOFs" << std::endl;
382 for (int i = 0; i < comm->getSize(); i++) {
383 fancyout << i << " " << gelePerProc[i] << std::endl;
384 }
385 }
386 }
387
388 comm->barrier();
389 tm = Teuchos::null;
390
391 comm->barrier();
392 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1.2 - LHS and RHS initialization")));
393
394 RCP<Vector> X = VectorFactory::Build(map, 1);
395 RCP<MultiVector> B = VectorFactory::Build(map, 1);
396
397 if (rhsFileName != "")
398 B = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(std::string(rhsFileName), A->getRowMap());
399 else {
400 // we set seed for reproducibility
401 X->setSeed(846930886);
402 bool useSameRandomGen = false;
403 X->randomize(useSameRandomGen);
404 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
405
406 Teuchos::Array<MT> norms(1);
407 B->norm2(norms);
408 // B->scale(1.0/norms[0]);
409 }
410
411 X->putScalar(zero);
412
413 comm->barrier();
414 tm = Teuchos::null;
415
416 // =========================================================================
417 // Preconditioner construction
418 // =========================================================================
419 comm->barrier();
420 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1.5 - MueLu read XML and feed MueLu")));
421 ParameterListInterpreter mueLuFactory(xmlFileName, *comm);
422
423 RCP<Hierarchy> H = mueLuFactory.CreateHierarchy();
424
425 // By default, we use Extreme. However, typically the xml file contains verbosity parameter
426 // which is used instead
427 H->SetDefaultVerbLevel(MueLu::Extreme);
428
429 // =========================================================================
430 // Prepare linear system
431 // =========================================================================
432 // We have the following different formulations:
433 // - split the linear system in a 2x2 multiphysics problem using Xpetra style gids
434 // - split the linear system in a 2x2 multiphysics problem using Thyra style gids
435 // - solve the problem as a monolithic linear system
436 if (blockedSystem == 1) {
437 // split matrix and vectors
438
439 // create map extractor
440 Teuchos::Array<GlobalOrdinal> nonSpecialGids;
441 Teuchos::Array<GlobalOrdinal> specialGids;
442 for (size_t i = 0; i < map->getLocalNumElements(); i++) {
443 GlobalOrdinal gid = map->getGlobalElement(i);
444 if (mySpecialMap->isNodeGlobalElement(gid) == false) {
445 nonSpecialGids.push_back(gid);
446 } else {
447 specialGids.push_back(gid);
448 }
449 }
450
451 std::cout << "non special gids: " << nonSpecialGids.size() << std::endl;
452
453 // MapFactory::Build (xpetraParameters.GetLib(),Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(),nonSpecialGids(),0,comm);
454 std::vector<size_t> strInfo(1, nPDE);
455 RCP<const Map> myStridedNonSpecialMap = StridedMapFactory::Build(xpetraParameters.GetLib(), Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(), nonSpecialGids(), 0, strInfo, comm);
456 RCP<const Map> myStridedSpecialMap = StridedMapFactory::Build(xpetraParameters.GetLib(), Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(), specialGids(), 0, strInfo, comm);
457 // RCP<const Map> myStridedSpecialMap = StridedMapFactory::Build(mySpecialMap, strInfo);
458
459 // std::cout << "map " << map->getMaxAllGlobalIndex() << " nonspecial " << myStridedNonSpecialMap->getMinAllGlobalIndex() << " " << myStridedNonSpecialMap->getMaxAllGlobalIndex() << " (" << myStridedNonSpecialMap->getGlobalNumElements() << ") special " << mySpecialMap->getMinAllGlobalIndex() << " " << mySpecialMap->getMaxAllGlobalIndex() << "(" << myStridedSpecialMap->getGlobalNumElements() << ")" << std::endl;
460 // std::cout << Teuchos::rcp_dynamic_cast<const Xpetra::EpetraMapT<int, Node> >(myNonSpecialMap)->getEpetra_Map() << std::endl;
461 // std::cout << Teuchos::rcp_dynamic_cast<const Xpetra::EpetraMapT<int, Node> >(myStridedSpecialMap)->getEpetra_Map() << std::endl;
462
463 // We always build an Xpetra style map extractor with unique global ids
464 TEUCHOS_TEST_FOR_EXCEPTION(map->getLocalNumElements() != myStridedNonSpecialMap->getLocalNumElements() + myStridedSpecialMap->getLocalNumElements(), MueLu::Exceptions::RuntimeError, "Driver: Number of DOFs on proc " << comm->getRank() << " is " << map->getLocalNumElements() << " and does not match the sum of the partial maps of size " << myStridedNonSpecialMap->getLocalNumElements() << " and " << myStridedSpecialMap->getLocalNumElements());
465
466 std::vector<Teuchos::RCP<const Map> > xmaps;
467 xmaps.push_back(myStridedNonSpecialMap);
468 xmaps.push_back(myStridedSpecialMap);
469
470 // Xpetra mode
471 Teuchos::RCP<const Xpetra::MapExtractor<Scalar, LocalOrdinal, GlobalOrdinal, Node> > map_extractor = Xpetra::MapExtractorFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(map, xmaps);
472
473 // split null space vectors
474 RCP<MultiVector> nullspace1 = map_extractor->ExtractVector(nullspace, 0);
475 RCP<MultiVector> nullspace2 = map_extractor->ExtractVector(nullspace, 1);
476
477 bool bThyraMode = (useThyraGIDs == 1) ? true : false;
478 Teuchos::RCP<Xpetra::BlockedCrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > bOp =
479 Xpetra::MatrixUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::SplitMatrix(*A, map_extractor, map_extractor, Teuchos::null, bThyraMode);
480
481 // TODO plausibility checks
482 // TODO set number of dofs per node
483
484 // use bOp as A
485 A = bOp;
486
487 // split coordinate vector
488 RCP<RealValuedMultiVector> coordinates1 = Teuchos::null;
489 RCP<RealValuedMultiVector> coordinates2 = Teuchos::null;
490 if (coordinates != Teuchos::null) {
491 TEUCHOS_TEST_FOR_EXCEPTION(myStridedNonSpecialMap->getLocalNumElements() % 3 != 0, MueLu::Exceptions::RuntimeError, "Driver: Number of DOFs of non-special map on proc " << comm->getRank() << " is " << myStridedNonSpecialMap->getLocalNumElements() << " and cannot divided by 3");
492 TEUCHOS_TEST_FOR_EXCEPTION(myStridedSpecialMap->getLocalNumElements() % 3 != 0, MueLu::Exceptions::RuntimeError, "Driver: Number of DOFs of special map on proc " << comm->getRank() << " is " << myStridedSpecialMap->getLocalNumElements() << " and cannot divided by 3");
493
494 Teuchos::Array<GlobalOrdinal> nonSpecialCoordGids;
495 Teuchos::Array<GlobalOrdinal> SpecialCoordGids;
496 for (size_t i = 0; i < coordinates->getMap()->getLocalNumElements(); i++) {
497 GlobalOrdinal gid = coordinates->getMap()->getGlobalElement(i);
498
499 for (size_t j = 0; j < Teuchos::as<size_t>(3); j++) {
500 GlobalOrdinal dofgid = gid * 3 + j;
501 if (myStridedSpecialMap->isNodeGlobalElement(dofgid)) {
502 SpecialCoordGids.append(gid);
503 break;
504 } else if (myStridedNonSpecialMap->isNodeGlobalElement(dofgid)) {
505 nonSpecialCoordGids.append(gid);
506 break;
507 } else
508 TEUCHOS_TEST_FOR_EXCEPTION(true, MueLu::Exceptions::RuntimeError, "Driver: DofGid " << dofgid << " is neither contained in special nor in non-special map.");
509 }
510 }
511
512 RCP<const Map> myNonSpecialCoordsMap = MapFactory::Build(xpetraParameters.GetLib(), Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(), nonSpecialCoordGids(), 0, comm);
513 TEUCHOS_TEST_FOR_EXCEPTION(myStridedNonSpecialMap->getLocalNumElements() / 3 != myNonSpecialCoordsMap->getLocalNumElements(), MueLu::Exceptions::RuntimeError, "Driver: Number of entries in non-special node map is inconsistent");
514
515 RCP<const Map> mySpecialCoordsMap = MapFactory::Build(xpetraParameters.GetLib(), Teuchos::OrdinalTraits<GlobalOrdinal>::invalid(), SpecialCoordGids(), 0, comm);
516 TEUCHOS_TEST_FOR_EXCEPTION(myStridedSpecialMap->getLocalNumElements() / 3 != mySpecialCoordsMap->getLocalNumElements(), MueLu::Exceptions::RuntimeError, "Driver: Number of entries in non-special node map is inconsistent");
517
518 std::vector<Teuchos::RCP<const Map> > nodexmaps;
519 nodexmaps.push_back(myNonSpecialCoordsMap);
520 nodexmaps.push_back(mySpecialCoordsMap);
521
522 Teuchos::RCP<const Xpetra::MapExtractor<real_type, LO, GO, NO> > nodemap_extractor = Xpetra::MapExtractorFactory<real_type, LO, GO, NO>::Build(coordinates->getMap(), nodexmaps);
523
524 // split coordinate vectors
525 coordinates1 = nodemap_extractor->ExtractVector(coordinates, 0);
526 coordinates2 = nodemap_extractor->ExtractVector(coordinates, 1);
527 // std::cout << Teuchos::rcp_dynamic_cast<const Xpetra::EpetraMapT<int, Node> >(myNonSpecialCoordsMap)->getEpetra_Map() << std::endl;
528 // std::cout << Teuchos::rcp_dynamic_cast<const Xpetra::EpetraMapT<int, Node> >(mySpecialCoordsMap)->getEpetra_Map() << std::endl;
529 }
530
531 if (bThyraMode == false) {
532 // use Xpetra style GIDs
533 H->GetLevel(0)->Set("A", Teuchos::rcp_dynamic_cast<Matrix>(bOp));
534 H->GetLevel(0)->Set("Nullspace1", nullspace1);
535 H->GetLevel(0)->Set("Nullspace2", nullspace2);
536 H->GetLevel(0)->Set("Coordinates", coordinates); // TODO split coordinates for rebalancing! (or provide the full vector in the right map and split it in the factories!)
537 H->GetLevel(0)->Set("Coordinates1", coordinates1);
538 H->GetLevel(0)->Set("Coordinates2", coordinates2);
539 if (mySpecialMap != Teuchos::null) H->GetLevel(0)->Set("map SpecialMap", mySpecialMap);
540 } else {
541 // use Thyra style GIDs
542 RCP<MultiVector> nsp1shrinked = Xpetra::MatrixUtils<SC, LO, GO, NO>::xpetraGidNumbering2ThyraGidNumbering(*nullspace1);
543 RCP<MultiVector> nsp2shrinked = Xpetra::MatrixUtils<SC, LO, GO, NO>::xpetraGidNumbering2ThyraGidNumbering(*nullspace2);
544 RCP<RealValuedMultiVector> coordsshrinked = Xpetra::MatrixUtils<real_type, LO, GO, NO>::xpetraGidNumbering2ThyraGidNumbering(*coordinates);
545 H->GetLevel(0)->Set("A", Teuchos::rcp_dynamic_cast<Matrix>(bOp));
546 H->GetLevel(0)->Set("Nullspace1", nsp1shrinked);
547 H->GetLevel(0)->Set("Nullspace2", nsp2shrinked);
548 H->GetLevel(0)->Set("Coordinates", coordsshrinked); // TODO split coordinates for rebalancing! (or provide the full vector in the right map and split it in the factories!)
549 if (mySpecialMap != Teuchos::null) {
550 RCP<const Map> specialmapshrinked = Xpetra::MapUtils<LocalOrdinal, GlobalOrdinal, Node>::shrinkMapGIDs(*mySpecialMap, *mySpecialMap);
551 H->GetLevel(0)->Set("map SpecialMap", Teuchos::rcp_const_cast<Map>(specialmapshrinked));
552 }
553
554 // rearrange contents of rhs vector B
555 RCP<const MapExtractor> thy_map_extractor = bOp->getRangeMapExtractor();
556 RCP<MultiVector> Bshrinked = Xpetra::MultiVectorFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Build(thy_map_extractor->getFullMap(), B->getNumVectors(), true);
557
558 size_t numMaps = map_extractor->NumMaps();
559 for (size_t k = 0; k < numMaps; k++) {
560 RCP<MultiVector> partVec = map_extractor->ExtractVector(B, k);
561 RCP<MultiVector> newPartVec = thy_map_extractor->getVector(k, B->getNumVectors(), false); // we need real GIDs (not zero based Thyra GIDs)
562 // copy data
563 for (size_t c = 0; c < partVec->getNumVectors(); c++) {
564 Teuchos::ArrayRCP<const Scalar> data = partVec->getData(c);
565 for (size_t r = 0; r < partVec->getLocalLength(); r++) {
566 newPartVec->replaceLocalValue(Teuchos::as<LocalOrdinal>(r), c, data[r]);
567 }
568 }
569 thy_map_extractor->InsertVector(*newPartVec, k, *Bshrinked, false);
570 }
571
572 B = Bshrinked;
573 X = VectorFactory::Build(thy_map_extractor->getFullMap(), 1);
574 X->putScalar(zero);
575
576 // TODO the ordering of the solution vector X is different!
577 }
578 } else {
579 // standard (non-blocked) case
580 H->GetLevel(0)->Set("A", A);
581 H->GetLevel(0)->Set("Nullspace", nullspace);
582 H->GetLevel(0)->Set("Coordinates", coordinates);
583 if (mySpecialMap != Teuchos::null) H->GetLevel(0)->Set("map SpecialMap", mySpecialMap);
584 }
585
586 comm->barrier();
587 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 2 - MueLu Setup")));
588
589 mueLuFactory.SetupHierarchy(*H);
590
591 comm->barrier();
592 tm = Teuchos::null;
593
594 // Print out the hierarchy stats. We should not need this line, but for some reason the
595 // print out in the hierarchy construction does not work.
596 H->print(fancyout);
597
598 // =========================================================================
599 // System solution (Ax = b)
600 // =========================================================================
601
602 tm = Teuchos::null;
603
604 if (writeMatricesOPT > -2)
605 H->Write(writeMatricesOPT, writeMatricesOPT);
606
607 comm->barrier();
608 if (amgAsSolver) {
609 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3 - Fixed Point Solve")));
610
611 H->IsPreconditioner(false);
612 Teuchos::Array<MT> norms(1);
613 norms = Utilities::ResidualNorm(*A, *X, *B);
614 std::cout << " iter: 0 residual = " << norms[0] << std::endl;
615 for (int i = 0; i < maxIts; ++i) {
616 H->Iterate(*B, *X);
617 norms = Utilities::ResidualNorm(*A, *X, *B);
618 std::cout << " iter: " << i + 1 << " residual = " << norms[0] << std::endl;
619 }
620
621 } else if (amgAsPrecond) {
622 #ifdef HAVE_MUELU_BELOS
623 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 4 - Belos Solve")));
624 // Operator and Multivector type that will be used with Belos
625 typedef MultiVector MV;
626 typedef Belos::OperatorT<MV> OP;
627 H->IsPreconditioner(true);
628
629 // Define Operator and Preconditioner
630 Teuchos::RCP<OP> belosOp = Teuchos::rcp(new Belos::XpetraOp<SC, LO, GO, NO>(A)); // Turns a Xpetra::Matrix object into a Belos operator
631 Teuchos::RCP<OP> belosPrec = Teuchos::rcp(new Belos::MueLuOp<SC, LO, GO, NO>(H)); // Turns a MueLu::Hierarchy object into a Belos operator
632 // Construct a Belos LinearProblem object
633 RCP<Belos::LinearProblem<SC, MV, OP> > belosProblem = rcp(new Belos::LinearProblem<SC, MV, OP>(belosOp, X, B));
634 belosProblem->setRightPrec(belosPrec);
635 bool set = belosProblem->setProblem();
636 if (set == false) {
637 fancyout << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
638 return EXIT_FAILURE;
639 }
640
641 // Belos parameter list
642 Teuchos::ParameterList belosList;
643 if (belosFileName == "") {
644 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
645 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
646 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
647 belosList.set("Output Frequency", output);
648 belosList.set("Output Style", Belos::Brief);
649 if (convType == "none") {
650 belosList.set("Explicit Residual Scaling", "None");
651 belosList.set("Implicit Residual Scaling", "None");
652 }
653 } else {
654 Teuchos::updateParametersFromXmlFileAndBroadcast(belosFileName, Teuchos::Ptr<Teuchos::ParameterList>(&belosList), *comm);
655
656 /*belosList.set("Output Style", Belos::User);
657 belosList.set("User Status Tests Combo Type", "OR");
658 Teuchos::ParameterList& userList = belosList.sublist("User Status Tests");
659 userList.set("Test Type","Combo");
660 userList.set("Combo Type","AND");
661 userList.set("Number of Tests",3);
662 Teuchos::ParameterList& userList1 = userList.sublist("Test 0");
663 userList1.set("Tag","1 FULL");
664 userList1.set("Test Type","ResidualNorm");
665 userList1.set("Convergence Tolerance",tol);
666 userList1.set("Scaling Type","None");
667 userList1.set("Residual Norm","OneNorm");
668 userList1.set("Scaling Norm","OneNorm");
669 Teuchos::ParameterList& userList2 = userList.sublist("Test 1");
670 userList2.set("Tag","2 PRIM");
671 userList2.set("Test Type","PartialResidualNorm");
672 userList2.set("Block index",0);
673 userList2.set("Convergence Tolerance",tol);
674 userList2.set("Scaling Type","None");
675 userList2.set("Residual Norm","OneNorm");
676 userList2.set("Scaling Norm","OneNorm");
677 Teuchos::ParameterList& userList3 = userList.sublist("Test 2");
678 userList3.set("Tag","3 SECOND");
679 userList3.set("Test Type","PartialResidualNorm");
680 userList3.set("Block index",1);
681 userList3.set("Convergence Tolerance",tol);
682 userList3.set("Scaling Type","None");
683 userList3.set("Residual Norm","OneNorm");
684 userList3.set("Scaling Norm","OneNorm");*/
685 }
686
687 // Create an iterative solver manager
688 RCP<Belos::SolverManager<SC, MV, OP> > solver;
689 if (krylovMethod == "cg") {
690 solver = rcp(new Belos::BlockCGSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
691 } else if (krylovMethod == "gmres") {
692 solver = rcp(new Belos::PseudoBlockGmresSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
693 } else {
694 TEUCHOS_TEST_FOR_EXCEPTION(true, MueLu::Exceptions::RuntimeError, "Invalid Krylov method. Options are \"cg\" or \" gmres\".");
695 }
696
697 // Perform solve
698 Belos::ReturnType ret = Belos::Unconverged;
699 try {
700 ret = solver->solve();
701
702 // Get the number of iterations for this solve.
703 fancyout << "Number of iterations performed for this solve: " << solver->getNumIters() << std::endl;
704
705 } catch (...) {
706 fancyout << std::endl
707 << "ERROR: Belos threw an error! " << std::endl;
708 }
709 // Check convergence
710 if (ret != Belos::Converged)
711 fancyout << std::endl
712 << "ERROR: Belos did not converge! " << std::endl;
713 else
714 fancyout << std::endl
715 << "SUCCESS: Belos converged!" << std::endl;
716 #endif // ifdef HAVE_MUELU_BELOS
717 }
718 comm->barrier();
719 tm = Teuchos::null;
720
721 if (strOutputFilename.empty() == false) {
722 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 5 - Export solution in VTK")));
723 if (comm->getSize() > 1) {
724 std::stringstream ss;
725 ss << "-proc" << comm->getRank();
726 strOutputFilename.append(ss.str());
727 }
728 strOutputFilename.append(".vtu");
729
730 std::ofstream fout(strOutputFilename);
731 ExportVTK<Scalar, LocalOrdinal, GlobalOrdinal, Node> expVTK;
732 expVTK.writeFile(fout, coordinates, X);
733 fout.close();
734
735 size_t start_pos = strOutputFilename.find(".vtu");
736 strOutputFilename.replace(start_pos, 4, ".m");
737 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write(strOutputFilename, *X);
738 }
739
740 // print timings
741
742 comm->barrier();
743 tm = Teuchos::null;
744 globalTimeMonitor = Teuchos::null;
745
746 if (printTimings) {
747 TimeMonitor::summarize(A->getRowMap()->getComm().ptr(), std::cout, false, true, false, Teuchos::Union, "", true);
748 MueLu::MutuallyExclusiveTime<MueLu::BaseClass>::PrintParentChildPairs();
749 }
750
751 success = true;
752 }
753 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
754
755 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
756 } // main
757
758 //- -- --------------------------------------------------------
759 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
760 #include "MueLu_Test_ETI.hpp"
761
762 int main(int argc, char* argv[]) {
763 return Automatic_Test_ETI(argc, argv);
764 }