Stratimikos Package Browser (Single Doxygen Collection)  Version of the Day
galeri_driver.cpp
Go to the documentation of this file.
1 /*@HEADER
2 // ***********************************************************************
3 //
4 // Ifpack2: Templated Object-Oriented Algebraic Preconditioner Package
5 // Copyright (2009) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 //@HEADER
41 */
42 #include <iostream>
43 
44 /*
45  Call Ifpack2 via the Stratimikos interface.
46 
47 Usage:
48 ./Ifpack2_Stratimikos.exe : use xml configuration file stratimikos_ParameterList.xml
49 
50 Note:
51 The source code is not MueLu specific and can be used with any Stratimikos strategy.
52 */
53 
54 // Teuchos includes
55 #include <Teuchos_ConfigDefs.hpp>
56 #include <Teuchos_GlobalMPISession.hpp>
57 #include <Teuchos_StackedTimer.hpp>
58 #include <Teuchos_RCP.hpp>
59 #include <Teuchos_XMLParameterListHelpers.hpp>
60 #include <Teuchos_YamlParameterListHelpers.hpp>
61 #include <Teuchos_StandardCatchMacros.hpp>
62 #include "Teuchos_AbstractFactoryStd.hpp"
63 
64 // Thyra includes
65 #include <Thyra_LinearOpWithSolveBase.hpp>
66 #include <Thyra_VectorBase.hpp>
67 #include <Thyra_SolveSupportTypes.hpp>
68 
69 // Stratimikos includes
71 
72 // Xpetra include
73 #include <Xpetra_Parameters.hpp>
74 #include <Xpetra_ThyraUtils.hpp>
75 
76 // Galeri includes
77 #include <Galeri_XpetraParameters.hpp>
78 #include <Galeri_XpetraProblemFactory.hpp>
79 #include <Galeri_XpetraUtils.hpp>
80 #include <Galeri_XpetraMaps.hpp>
81 
82 
83 // Ifpack2 includes
84 #include <Thyra_Ifpack2PreconditionerFactory.hpp>
85 
86 
87 int
88 main(int argc, char *argv[]) {
89  typedef double Scalar;
90  typedef Teuchos::ScalarTraits<Scalar> STS;
91  typedef Tpetra::Map<> map_type;
92  typedef map_type::local_ordinal_type LocalOrdinal;
93  typedef map_type::global_ordinal_type GlobalOrdinal;
94  typedef map_type::node_type Node;
95  using Teuchos::RCP;
96  using Teuchos::rcp;
97  using Teuchos::ParameterList;
98  using Teuchos::TimeMonitor;
99  #include <Xpetra_UseShortNames.hpp>
100 
101  bool success = false;
102  bool verbose = true;
103  try {
104 
105  //
106  // MPI initialization
107  //
108  Teuchos::GlobalMPISession session (&argc, &argv, NULL);
109  Teuchos::CommandLineProcessor clp(false);
110  const auto comm = Teuchos::DefaultComm<int>::getComm ();
111 
112  //
113  // Parameters
114  //
115  // manage parameters of the test case
116  Galeri::Xpetra::Parameters<GlobalOrdinal> galeriParameters(clp, 100, 100, 100, "Laplace2D");
117  // manage parameters of Xpetra
118  Xpetra::Parameters xpetraParameters(clp);
119 
120  // command line parameters
121  std::string xmlFileName = "stratimikos_ParameterList.xml"; clp.setOption("xml", &xmlFileName, "read parameters from an xml file");
122  std::string yamlFileName = ""; clp.setOption("yaml", &yamlFileName, "read parameters from a yaml file");
123  bool printTimings = false; clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
124  bool use_stacked_timer = false; clp.setOption("stacked-timer", "no-stacked-timer", &use_stacked_timer, "Run with or without stacked timer output");
125  std::string timingsFormat = "table-fixed"; clp.setOption("time-format", &timingsFormat, "timings format (table-fixed | table-scientific | yaml)");
126  int numVectors = 1; clp.setOption("multivector", &numVectors, "number of rhs to solve simultaneously");
127  int numSolves = 1; clp.setOption("numSolves", &numSolves, "number of times the system should be solved");
128 
129  switch (clp.parse(argc,argv)) {
130  case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
131  case Teuchos::CommandLineProcessor::PARSE_ERROR:
132  case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
133  case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
134  }
135 
136  RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
137  Teuchos::FancyOStream& out = *fancy;
138  out.setOutputToRootOnly(0);
139 
140  // Set up timers
141  Teuchos::RCP<Teuchos::StackedTimer> stacked_timer;
142  if (use_stacked_timer)
143  stacked_timer = rcp(new Teuchos::StackedTimer("Main"));
144  TimeMonitor::setStackedTimer(stacked_timer);
145 
146  // Read in parameter list
147  TEUCHOS_TEST_FOR_EXCEPTION(xmlFileName == "" && yamlFileName == "", std::runtime_error,
148  "Need to provide xml or yaml input file");
149  RCP<ParameterList> paramList = rcp(new ParameterList("params"));
150  if (yamlFileName != "")
151  Teuchos::updateParametersFromYamlFileAndBroadcast(yamlFileName, paramList.ptr(), *comm);
152  else
153  Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFileName, paramList.ptr(), *comm);
154 
155  //
156  // Construct the problem
157  //
158 
159  RCP<Matrix> A;
160  RCP<const Map> map;
161  RCP<MultiVector> X, B;
162 
163  std::ostringstream galeriStream;
164  Teuchos::ParameterList galeriList = galeriParameters.GetParameterList();
165  galeriStream << "========================================================\n" << xpetraParameters;
166  galeriStream << galeriParameters;
167 
168  // Galeri will attempt to create a square-as-possible distribution of subdomains di, e.g.,
169  // d1 d2 d3
170  // d4 d5 d6
171  // d7 d8 d9
172  // d10 d11 d12
173  // A perfect distribution is only possible when the #processors is a perfect square.
174  // This *will* result in "strip" distribution if the #processors is a prime number or if the factors are very different in
175  // size. For example, np=14 will give a 7-by-2 distribution.
176  // If you don't want Galeri to do this, specify mx or my on the galeriList.
177  std::string matrixType = galeriParameters.GetMatrixType();
178 
179  // Create map
180  if (matrixType == "Laplace1D") {
181  map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
182 
183  } else if (matrixType == "Laplace2D" || matrixType == "Star2D" ||
184  matrixType == "BigStar2D" || matrixType == "AnisotropicDiffusion" || matrixType == "Elasticity2D") {
185  map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
186 
187  } else if (matrixType == "Laplace3D" || matrixType == "Brick3D" || matrixType == "Elasticity3D") {
188  map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
189  }
190 
191  // Expand map to do multiple DOF per node for block problems
192  if (matrixType == "Elasticity2D")
193  map = Xpetra::MapFactory<LO,GO,Node>::Build(map, 2);
194  if (matrixType == "Elasticity3D")
195  map = Xpetra::MapFactory<LO,GO,Node>::Build(map, 3);
196 
197  galeriStream << "Processor subdomains in x direction: " << galeriList.get<GO>("mx") << std::endl
198  << "Processor subdomains in y direction: " << galeriList.get<GO>("my") << std::endl
199  << "Processor subdomains in z direction: " << galeriList.get<GO>("mz") << std::endl
200  << "========================================================" << std::endl;
201 
202  if (matrixType == "Elasticity2D" || matrixType == "Elasticity3D") {
203  // Our default test case for elasticity: all boundaries of a square/cube have Neumann b.c. except left which has Dirichlet
204  galeriList.set("right boundary" , "Neumann");
205  galeriList.set("bottom boundary", "Neumann");
206  galeriList.set("top boundary" , "Neumann");
207  galeriList.set("front boundary" , "Neumann");
208  galeriList.set("back boundary" , "Neumann");
209  }
210 
211  RCP<Galeri::Xpetra::Problem<Map,CrsMatrixWrap,MultiVector> > Pr =
212  Galeri::Xpetra::BuildProblem<SC,LO,GO,Map,CrsMatrixWrap,MultiVector>(galeriParameters.GetMatrixType(), map, galeriList);
213  A = Pr->BuildMatrix();
214 
215  if (matrixType == "Elasticity2D" ||
216  matrixType == "Elasticity3D") {
217  A->SetFixedBlockSize((galeriParameters.GetMatrixType() == "Elasticity2D") ? 2 : 3);
218  }
219 
220  out << galeriStream.str();
221  X = MultiVectorFactory::Build(map, numVectors);
222  B = MultiVectorFactory::Build(map, numVectors);
223  B->putScalar(1);
224  X->putScalar(0);
225 
226  //
227  // Build Thyra linear algebra objects
228  //
229 
230  RCP<const Xpetra::CrsMatrixWrap<Scalar,LocalOrdinal,GlobalOrdinal,Node> > xpCrsA = Teuchos::rcp_dynamic_cast<const Xpetra::CrsMatrixWrap<Scalar,LocalOrdinal,GlobalOrdinal,Node> >(A);
231 
232  RCP<const Thyra::LinearOpBase<Scalar> > thyraA = Xpetra::ThyraUtils<Scalar,LocalOrdinal,GlobalOrdinal,Node>::toThyra(xpCrsA->getCrsMatrix());
233  RCP< Thyra::MultiVectorBase<Scalar> > thyraX = Teuchos::rcp_const_cast<Thyra::MultiVectorBase<Scalar> >(Xpetra::ThyraUtils<Scalar,LocalOrdinal,GlobalOrdinal,Node>::toThyraMultiVector(X));
234  RCP<const Thyra::MultiVectorBase<Scalar> > thyraB = Xpetra::ThyraUtils<Scalar,LocalOrdinal,GlobalOrdinal,Node>::toThyraMultiVector(B);
235 
236  //
237  // Build Stratimikos solver
238  //
239 
240  // This is the Stratimikos main class (= factory of solver factory).
241  Stratimikos::DefaultLinearSolverBuilder linearSolverBuilder;
242  // Register Ifpack2 as a Stratimikos preconditioner strategy.
243  typedef Thyra::PreconditionerFactoryBase<Scalar> Base;
244  typedef Thyra::Ifpack2PreconditionerFactory<Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node> > Impl;
245  linearSolverBuilder.setPreconditioningStrategyFactory(Teuchos::abstractFactoryStd<Base, Impl>(), "Ifpack2");
246 
247  // Setup solver parameters using a Stratimikos parameter list.
248  linearSolverBuilder.setParameterList(paramList);
249 
250  // Build a new "solver factory" according to the previously specified parameter list.
251  RCP<Thyra::LinearOpWithSolveFactoryBase<Scalar> > solverFactory = Thyra::createLinearSolveStrategy(linearSolverBuilder);
252  auto precFactory = solverFactory->getPreconditionerFactory();
253  RCP<Thyra::PreconditionerBase<Scalar> > prec;
254  Teuchos::RCP<Thyra::LinearOpWithSolveBase<Scalar> > thyraInverseA;
255  if (!precFactory.is_null()) {
256  prec = precFactory->createPrec();
257 
258  // Build a Thyra operator corresponding to A^{-1} computed using the Stratimikos solver.
259  Thyra::initializePrec<double>(*precFactory, thyraA, prec.ptr());
260  thyraInverseA = solverFactory->createOp();
261  Thyra::initializePreconditionedOp<double>(*solverFactory, thyraA, prec, thyraInverseA.ptr());
262  } else {
263  thyraInverseA = Thyra::linearOpWithSolve(*solverFactory, thyraA);
264  }
265 
266  // Solve Ax = b.
267  Thyra::SolveStatus<Scalar> status = Thyra::solve<Scalar>(*thyraInverseA, Thyra::NOTRANS, *thyraB, thyraX.ptr());
268 
269  success = (status.solveStatus == Thyra::SOLVE_STATUS_CONVERGED);
270 
271  for (int solveno = 1; solveno < numSolves; solveno++) {
272  if (!precFactory.is_null())
273  Thyra::initializePrec<double>(*precFactory, thyraA, prec.ptr());
274  thyraX->assign(0.);
275 
276  status = Thyra::solve<Scalar>(*thyraInverseA, Thyra::NOTRANS, *thyraB, thyraX.ptr());
277 
278  success = success && (status.solveStatus == Thyra::SOLVE_STATUS_CONVERGED);
279  }
280 
281  // print timings
282  if (printTimings) {
283  if (use_stacked_timer) {
284  stacked_timer->stop("Main");
285  Teuchos::StackedTimer::OutputOptions options;
286  options.output_fraction = options.output_histogram = options.output_minmax = true;
287  stacked_timer->report(out, comm, options);
288  } else {
289  RCP<ParameterList> reportParams = rcp(new ParameterList);
290  if (timingsFormat == "yaml") {
291  reportParams->set("Report format", "YAML"); // "Table" or "YAML"
292  reportParams->set("YAML style", "compact"); // "spacious" or "compact"
293  }
294  reportParams->set("How to merge timer sets", "Union");
295  reportParams->set("alwaysWriteLocal", false);
296  reportParams->set("writeGlobalStats", true);
297  reportParams->set("writeZeroTimers", false);
298 
299  const std::string filter = "";
300 
301  std::ios_base::fmtflags ff(out.flags());
302  if (timingsFormat == "table-fixed") out << std::fixed;
303  else out << std::scientific;
304  TimeMonitor::report(comm.ptr(), out, filter, reportParams);
305  out << std::setiosflags(ff);
306  }
307  }
308 
309  TimeMonitor::clearCounters();
310  out << std::endl;
311 
312  }
313  TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
314 
315  return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
316 }
317 
318 
void setPreconditioningStrategyFactory(const RCP< const AbstractFactory< Thyra::PreconditionerFactoryBase< double > > > &precStrategyFactory, const std::string &precStrategyName, const bool makeDefault=false)
Set a new preconditioner strategy factory object.
Tpetra::Map< int, int > map_type
int main(int argc, char *argv[])
void setParameterList(RCP< ParameterList > const &paramList)
Concrete subclass of Thyra::LinearSolverBuilderBase for creating LinearOpWithSolveFactoryBase objects...
map_type::global_ordinal_type GO