MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_PerfUtils_def.hpp
Go to the documentation of this file.
1 // @HEADER
2 //
3 // ***********************************************************************
4 //
5 // MueLu: A package for multigrid based preconditioning
6 // Copyright 2012 Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NodeT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DIScalarLAIMED. IN Node EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NodeT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GlobalOrdinalODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact
39 // Jonathan Hu (jhu@sandia.gov)
40 // Andrey Prokopenko (aprokop@sandia.gov)
41 // Ray Tuminaro (rstumin@sandia.gov)
42 //
43 // ***********************************************************************
44 //
45 // @HEADER
46 #ifndef MUELU_PERFUTILS_DEF_HPP
47 #define MUELU_PERFUTILS_DEF_HPP
48 
49 #include <algorithm>
50 #include <string>
51 
52 #ifdef HAVE_MPI
53 #include <Teuchos_CommHelpers.hpp>
54 #endif
55 
56 #include <Xpetra_Export.hpp>
57 #include <Xpetra_Import.hpp>
58 #include <Xpetra_Matrix.hpp>
59 #include <Xpetra_CrsMatrixWrap.hpp>
60 
61 #include "MueLu_PerfUtils_decl.hpp"
62 
63 //#include "MueLu_Utilities.hpp"
64 
65 namespace MueLu {
66 
67 template <class Type>
68 void calculateStats(Type& minVal, Type& maxVal, double& avgVal, double& devVal, int& minProc, int& maxProc, const RCP<const Teuchos::Comm<int> >& comm, int numActiveProcs, const Type& v) {
69  Type sumVal, sum2Val, v2 = v * v;
72 
73  MueLu_sumAll(comm, v, sumVal);
74  MueLu_sumAll(comm, v2, sum2Val);
75  MueLu_minAll(comm, v, minVal);
76  MueLu_maxAll(comm, v, maxVal);
77 
78  int w;
79  w = (minVal == v) ? comm->getRank() : -1;
80  MueLu_maxAll(comm, w, maxProc);
81  w = (maxVal == v) ? comm->getRank() : -1;
82  MueLu_maxAll(comm, w, minProc);
83 
84  avgVal = (numActiveProcs > 0 ? (as<double>(Teuchos::ScalarTraits<Type>::real(sumVal)) / numActiveProcs) : zero);
85  MT avgVal_MT = Teuchos::as<MT>(avgVal);
86  devVal = (numActiveProcs > 1 ? sqrt((as<double>(Teuchos::ScalarTraits<Type>::real(sum2Val - sumVal * avgVal_MT))) / (numActiveProcs - 1)) : zero);
87 }
88 
89 template <class Type>
90 std::string stringStats(const RCP<const Teuchos::Comm<int> >& comm, int numActiveProcs, const Type& v, RCP<ParameterList> paramList = Teuchos::null) {
91  Type minVal, maxVal;
92  double avgVal, devVal;
93  int minProc, maxProc;
94  calculateStats<Type>(minVal, maxVal, avgVal, devVal, minProc, maxProc, comm, numActiveProcs, v);
95 
96  const double zero = Teuchos::ScalarTraits<double>::zero();
97  const double one = Teuchos::ScalarTraits<double>::one();
98  std::ostringstream buf;
99  buf << std::fixed;
100  if ((avgVal != zero) && (paramList.is_null() || !paramList->isParameter("print abs") || paramList->get<bool>("print abs") == false)) {
101  double relDev = (devVal / avgVal) * 100;
102  double relMin = (as<double>(Teuchos::ScalarTraits<Type>::real(minVal)) / avgVal - one) * 100;
103  double relMax = (as<double>(Teuchos::ScalarTraits<Type>::real(maxVal)) / avgVal - one) * 100;
104  buf << "avg = " << std::scientific << std::setw(10) << std::setprecision(2) << avgVal << ", "
105  << "dev = " << std::fixed << std::setw(6) << std::setprecision(1) << relDev << "%, "
106  << "min = " << std::fixed << std::setw(7) << std::setprecision(1) << std::setw(7) << relMin << "%"
107  << " (" << std::scientific << std::setw(10) << std::setprecision(2) << minVal << " on " << std::fixed << std::setw(4) << minProc << "), "
108  << "max = " << std::fixed << std::setw(7) << std::setprecision(1) << relMax << "%"
109  << " (" << std::scientific << std::setw(10) << std::setprecision(2) << maxVal << " on " << std::fixed << std::setw(4) << maxProc << ")";
110  } else {
111  double relDev = (avgVal != zero ? (devVal / avgVal) * 100 : zero);
112  buf << "avg = " << std::scientific << std::setw(10) << std::setprecision(2) << avgVal << ", "
113  << "dev = " << std::fixed << std::setw(6) << std::setprecision(1) << relDev << "%, "
114  << "min = " << std::scientific << std::setw(10) << std::setprecision(2) << minVal
115  << " (on " << std::fixed << std::setw(4) << minProc << "), "
116  << "max = " << std::scientific << std::setw(10) << std::setprecision(2) << maxVal
117  << " (on " << std::fixed << std::setw(4) << maxProc << ")";
118  }
119  return buf.str();
120 }
121 
122 template <class Map>
123 bool cmp_less(typename Map::value_type& v1, typename Map::value_type& v2) {
124  return v1.second < v2.second;
125 }
126 
127 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
128 std::string PerfUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::PrintMatrixInfo(const Matrix& A, const std::string& msgTag, RCP<const ParameterList> params) {
129  if (!CheckMatrix(A))
130  return "";
131 
133 
134  std::ostringstream ss;
135 
136  ss << msgTag << " size = " << A.getGlobalNumRows() << " x " << A.getGlobalNumCols();
137  if (A.haveGlobalConstants())
138  ss << ", nnz = " << A.getGlobalNumEntries();
139  ss << std::endl;
140 
141  if (params.is_null())
142  return ss.str();
143 
144  bool printLoadBalanceInfo = false, printCommInfo = false, printEntryStats = false;
145  if (params->isParameter("printLoadBalancingInfo") && params->get<bool>("printLoadBalancingInfo"))
146  printLoadBalanceInfo = true;
147  if (params->isParameter("printCommInfo") && params->get<bool>("printCommInfo"))
148  printCommInfo = true;
149  if (params->isParameter("printEntryStats") && params->get<bool>("printEntryStats"))
150  printEntryStats = true;
151 
152  if (!printLoadBalanceInfo && !printCommInfo && !printEntryStats)
153  return ss.str();
154 
155  RCP<const Import> importer = A.getCrsGraph()->getImporter();
156  RCP<const Export> exporter = A.getCrsGraph()->getExporter();
157 
158  size_t numMyNnz = A.getLocalNumEntries(), numMyRows = A.getLocalNumRows();
159 
160  // Create communicator only for active processes
161  RCP<const Teuchos::Comm<int> > origComm = A.getRowMap()->getComm();
162  bool activeProc = true;
163  int numProc = origComm->getSize();
164  int numActiveProcs = 0;
165 #ifdef HAVE_MPI
166  RCP<const Teuchos::MpiComm<int> > mpiComm = rcp_dynamic_cast<const Teuchos::MpiComm<int> >(origComm);
167  MPI_Comm rawComm = (*mpiComm->getRawMpiComm())();
168 
169  std::vector<size_t> numRowsPerProc(numProc);
170  Teuchos::gatherAll(*origComm, 1, &numMyRows, numProc, &numRowsPerProc[0]);
171 
172  int root = 0;
173  bool rootFlag = true;
174  for (int i = 0; i < numProc; i++) {
175  if (numRowsPerProc[i]) {
176  ++numActiveProcs;
177  if (rootFlag) {
178  root = i;
179  rootFlag = false;
180  }
181  }
182  }
183 
184  if (numMyRows == 0) {
185  activeProc = false;
186  numMyNnz = 0;
187  } // Reset numMyNnz to avoid adding it up in reduceAll
188 #else
189  if (numMyRows == 0) {
190  // FIXME JJH 10-May-2017 Is there any case in serial where numMyRows would be zero?
191  // Reset numMyNnz to avoid adding it up in reduceAll
192  numActiveProcs = 0;
193  activeProc = false;
194  numMyNnz = 0;
195  } else {
196  numActiveProcs = 1;
197  }
198 #endif
199 
200  std::string outstr;
201  ParameterList absList;
202  absList.set("print abs", true);
203 
204  RCP<const Matrix> rcpA = rcpFromRef(A);
207  if (!crsWrapA.is_null())
208  crsA = crsWrapA->getCrsMatrix();
209  if (printEntryStats && !crsA.is_null()) {
210  typedef Teuchos::ScalarTraits<Scalar> STS;
211  typedef typename STS::magnitudeType magnitudeType;
213  ArrayRCP<const size_t> rowptr_RCP;
214  ArrayRCP<const LocalOrdinal> colind_RCP;
215  ArrayRCP<const Scalar> vals_RCP;
216  ArrayRCP<size_t> offsets_RCP;
219  ArrayView<size_t> offsets;
220 
221  crsA->getAllValues(rowptr_RCP, colind_RCP, vals_RCP);
222  crsA->getLocalDiagOffsets(offsets_RCP);
223  rowptr = rowptr_RCP();
224  vals = vals_RCP();
225  offsets = offsets_RCP();
226 
227  Scalar val, minVal, maxVal;
228  magnitudeType absVal, minAbsVal, maxAbsVal;
229  {
230  minVal = STS::rmax();
231  maxVal = STS::rmin();
232  minAbsVal = MTS::rmax();
233  maxAbsVal = MTS::zero();
234 
235  for (int i = 0; i < offsets.size(); i++) {
236  val = vals[rowptr[i] + offsets[i]];
237  if (STS::real(val) < STS::real(minVal))
238  minVal = val;
239  if (STS::real(val) > STS::real(maxVal))
240  maxVal = val;
241  absVal = STS::magnitude(val);
242  minAbsVal = std::min(minAbsVal, absVal);
243  maxAbsVal = std::max(maxAbsVal, absVal);
244  }
245 
246  ss << msgTag << " diag min : " << stringStats<Scalar>(origComm, numActiveProcs, minVal) << std::endl;
247  ss << msgTag << " diag max : " << stringStats<Scalar>(origComm, numActiveProcs, maxVal) << std::endl;
248  ss << msgTag << " abs(diag) min : " << stringStats<Scalar>(origComm, numActiveProcs, minAbsVal) << std::endl;
249  ss << msgTag << " abs(diag) max : " << stringStats<Scalar>(origComm, numActiveProcs, maxAbsVal) << std::endl;
250  }
251 
252  {
253  minVal = STS::rmax();
254  maxVal = STS::rmin();
255  minAbsVal = MTS::rmax();
256  maxAbsVal = MTS::zero();
257 
258  for (int i = 0; i < vals.size(); i++) {
259  val = vals[i];
260  if (STS::real(val) < STS::real(minVal))
261  minVal = val;
262  if (STS::real(val) > STS::real(maxVal))
263  maxVal = val;
264  absVal = STS::magnitude(val);
265  minAbsVal = std::min(minAbsVal, absVal);
266  maxAbsVal = std::max(maxAbsVal, absVal);
267  }
268 
269  ss << msgTag << " entry min : " << stringStats<Scalar>(origComm, numActiveProcs, minVal) << std::endl;
270  ss << msgTag << " entry max : " << stringStats<Scalar>(origComm, numActiveProcs, maxVal) << std::endl;
271  ss << msgTag << " abs(entry) min : " << stringStats<Scalar>(origComm, numActiveProcs, minAbsVal) << std::endl;
272  ss << msgTag << " abs(entry) max : " << stringStats<Scalar>(origComm, numActiveProcs, maxAbsVal) << std::endl;
273  }
274  }
275 
276  if (printLoadBalanceInfo) {
277  ss << msgTag << " Load balancing info" << std::endl;
278  ss << msgTag << " # active processes: " << numActiveProcs << "/" << numProc << std::endl;
279  ss << msgTag << " # rows per proc : " << stringStats<global_size_t>(origComm, numActiveProcs, numMyRows) << std::endl;
280  ss << msgTag << " # nnz per proc : " << stringStats<global_size_t>(origComm, numActiveProcs, numMyNnz) << std::endl;
281  }
282 
283  if (printCommInfo && numActiveProcs != 1) {
284  typedef std::map<int, size_t> map_type;
285  map_type neighMap;
286  if (!importer.is_null()) {
287  ArrayView<const int> exportPIDs = importer->getExportPIDs();
288  if (exportPIDs.size())
289  for (int i = 0; i < exportPIDs.size(); i++)
290  neighMap[exportPIDs[i]]++;
291  }
292 
293  // Communication volume
294  size_t numExportSend = 0;
295  size_t numImportSend = 0;
296  size_t numMsgs = 0;
297  size_t minMsg = 0;
298  size_t maxMsg = 0;
299 
300  if (activeProc) {
301  numExportSend = (!exporter.is_null() ? exporter->getNumExportIDs() : 0);
302  numImportSend = (!importer.is_null() ? importer->getNumExportIDs() : 0);
303  numMsgs = neighMap.size();
304  map_type::const_iterator it = std::min_element(neighMap.begin(), neighMap.end(), cmp_less<map_type>);
305  minMsg = (it != neighMap.end() ? it->second : 0);
306  it = std::max_element(neighMap.begin(), neighMap.end(), cmp_less<map_type>);
307  maxMsg = (it != neighMap.end() ? it->second : 0);
308  }
309 
310  ss << msgTag << " Communication info" << std::endl;
311  ss << msgTag << " # num export send : " << stringStats<global_size_t>(origComm, numActiveProcs, numExportSend) << std::endl;
312  ss << msgTag << " # num import send : " << stringStats<global_size_t>(origComm, numActiveProcs, numImportSend) << std::endl;
313  ss << msgTag << " # num msgs : " << stringStats<global_size_t>(origComm, numActiveProcs, numMsgs, rcpFromRef(absList)) << std::endl;
314  ss << msgTag << " # min msg size : " << stringStats<global_size_t>(origComm, numActiveProcs, minMsg) << std::endl;
315  ss << msgTag << " # max msg size : " << stringStats<global_size_t>(origComm, numActiveProcs, maxMsg) << std::endl;
316  }
317 
318  outstr = ss.str();
319 
320 #ifdef HAVE_MPI
321  int strLength = outstr.size();
322  MPI_Bcast(&strLength, 1, MPI_INT, root, rawComm);
323  if (origComm->getRank() != root)
324  outstr.resize(strLength);
325  MPI_Bcast(&outstr[0], strLength, MPI_CHAR, root, rawComm);
326 #endif
327 
328  return outstr;
329 }
330 
331 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
334 
335  std::ostringstream ss;
336 
337  // Create communicator only for active processes
338  RCP<const Teuchos::Comm<int> > origComm = importer->getSourceMap()->getComm();
339  bool activeProc = true;
340  int numActiveProcs = origComm->getSize();
341 #ifdef HAVE_MPI
342  RCP<const Teuchos::MpiComm<int> > mpiComm = rcp_dynamic_cast<const Teuchos::MpiComm<int> >(origComm);
343  MPI_Comm rawComm = (*mpiComm->getRawMpiComm())();
344  int root = 0;
345 #endif
346 
347  std::string outstr;
348  ParameterList absList;
349  absList.set("print abs", true);
350 
351  typedef std::map<int, size_t> map_type;
352  map_type neighMap;
353  ArrayView<const int> exportPIDs = importer->getExportPIDs();
354  if (exportPIDs.size())
355  for (int i = 0; i < exportPIDs.size(); i++)
356  neighMap[exportPIDs[i]]++;
357 
358  // Communication volume
359  size_t numImportSend = 0;
360  size_t numMsgs = 0;
361  size_t minMsg = 0;
362  size_t maxMsg = 0;
363 
364  if (activeProc) {
365  numImportSend = importer->getNumExportIDs();
366  numMsgs = neighMap.size();
367  map_type::const_iterator it = std::min_element(neighMap.begin(), neighMap.end(), cmp_less<map_type>);
368  minMsg = (it != neighMap.end() ? it->second : 0);
369  it = std::max_element(neighMap.begin(), neighMap.end(), cmp_less<map_type>);
370  maxMsg = (it != neighMap.end() ? it->second : 0);
371  }
372 
373  ss << msgTag << " Communication info" << std::endl;
374  ss << msgTag << " # num import send : " << stringStats<global_size_t>(origComm, numActiveProcs, numImportSend) << std::endl;
375  ss << msgTag << " # num msgs : " << stringStats<global_size_t>(origComm, numActiveProcs, numMsgs, rcpFromRef(absList)) << std::endl;
376  ss << msgTag << " # min msg size : " << stringStats<global_size_t>(origComm, numActiveProcs, minMsg) << std::endl;
377  ss << msgTag << " # max msg size : " << stringStats<global_size_t>(origComm, numActiveProcs, maxMsg) << std::endl;
378 
379  outstr = ss.str();
380 
381 #ifdef HAVE_MPI
382  int strLength = outstr.size();
383  MPI_Bcast(&strLength, 1, MPI_INT, root, rawComm);
384  if (origComm->getRank() != root)
385  outstr.resize(strLength);
386  MPI_Bcast(&outstr[0], strLength, MPI_CHAR, root, rawComm);
387 #endif
388 
389  return outstr;
390 }
391 
392 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
393 std::string PerfUtils<Scalar, LocalOrdinal, GlobalOrdinal, Node>::CommPattern(const Matrix& A, const std::string& msgTag, RCP<const ParameterList> /* params */) {
394  if (!CheckMatrix(A))
395  return "";
396 
397  std::ostringstream out;
398 
399  RCP<const Teuchos::Comm<int> > comm = A.getRowMap()->getComm();
400  int myRank = comm->getRank();
401 
402  out << msgTag << " " << myRank << ":";
403 
404  RCP<const Import> importer = (A.getCrsGraph() != Teuchos::null ? A.getCrsGraph()->getImporter() : Teuchos::null);
405  if (importer.is_null()) {
406  out << std::endl;
407  return out.str();
408  }
409 
410  ArrayView<const int> exportPIDs = importer->getExportPIDs();
411 
412  if (exportPIDs.size()) {
413  // NodeTE: exportPIDs is sorted but not unique ( 1 1 1 2 2 3 4 4 4 )
414  int neigh = exportPIDs[0];
415  GO weight = 1;
416  for (int i = 1; i < exportPIDs.size(); i++) {
417  if (exportPIDs[i] != exportPIDs[i - 1]) {
418  out << " " << neigh << "(" << weight << ")";
419 
420  neigh = exportPIDs[i];
421  weight = 1;
422 
423  } else {
424  weight += 1;
425  }
426  }
427  out << " " << neigh << "(" << weight << ")" << std::endl;
428  }
429 
430  return out.str();
431 }
432 
433 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
435  // We can only print statistics for matrices that have a crs graph. A
436  // potential issue is regarding Xpetra::TpetraBlockCrsMatrix which has no
437  // CrsGraph. It is held as a private data member by Xpetra::CrsMatrix,
438  // which itself is an Xpetra::Matrix. So we check directly whether the
439  // request for the graph throws.
440  bool hasCrsGraph = true;
441  try {
442  A.getCrsGraph();
443 
444  } catch (...) {
445  hasCrsGraph = false;
446  }
447 
448  return hasCrsGraph;
449 }
450 
451 } // namespace MueLu
452 
453 #endif // MUELU_PERFUTILS_DEF_HPP
static bool CheckMatrix(const Matrix &A)
std::string stringStats(const RCP< const Teuchos::Comm< int > > &comm, int numActiveProcs, const Type &v, RCP< ParameterList > paramList=Teuchos::null)
#define MueLu_sumAll(rcpComm, in, out)
#define MueLu_maxAll(rcpComm, in, out)
GlobalOrdinal GO
T & get(const std::string &name, T def_value)
ParameterList & set(std::string const &name, T const &value, std::string const &docString="", RCP< const ParameterEntryValidator > const &validator=null)
static magnitudeType real(T a)
size_type size() const
#define MueLu_minAll(rcpComm, in, out)
static std::string CommPattern(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
static std::string PrintImporterInfo(RCP< const Import > importer, const std::string &msgTag)
bool isParameter(const std::string &name) const
MueLu::DefaultScalar Scalar
static std::string PrintMatrixInfo(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
void calculateStats(Type &minVal, Type &maxVal, double &avgVal, double &devVal, int &minProc, int &maxProc, const RCP< const Teuchos::Comm< int > > &comm, int numActiveProcs, const Type &v)
size_t global_size_t
bool cmp_less(typename Map::value_type &v1, typename Map::value_type &v2)
bool is_null() const