Tpetra Matrix/Vector Services  Version of the Day
Tpetra_CrsGraph_def.hpp
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Tpetra: Templated Linear Algebra Services Package
5 // Copyright (2008) Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
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 // FINISH: can't use rowPtrs_ without checking that it exists
43 // FINISH: add code to fillComplete() and CrsMatrix::fillComplete() to delete the Tpetra data
44 
45 #ifndef TPETRA_CRSGRAPH_DEF_HPP
46 #define TPETRA_CRSGRAPH_DEF_HPP
47 
48 #include <Kokkos_NodeTrace.hpp>
49 #include "Tpetra_Distributor.hpp"
50 #include <Teuchos_Assert.hpp>
51 #include <Teuchos_NullIteratorTraits.hpp>
52 #include <Teuchos_as.hpp>
53 #include <algorithm>
54 #include <string>
55 #include <utility>
57 
58 #ifdef DOXYGEN_USE_ONLY
59  #include "Tpetra_CrsGraph_decl.hpp"
60 #endif
61 
62 namespace Tpetra {
63 
66  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
67  CrsGraph<LocalOrdinal,GlobalOrdinal,Node,LocalMatOps>::
68  CrsGraph (const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > &rowMap,
69  size_t maxNumEntriesPerRow,
70  ProfileType pftype,
71  const RCP<ParameterList>& params)
72  : DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>(rowMap)
73  , rowMap_(rowMap)
74  , nodeNumEntries_(0)
75  , nodeNumAllocated_(OrdinalTraits<size_t>::invalid())
76  , pftype_(pftype)
77  , numAllocForAllRows_(maxNumEntriesPerRow)
78  , indicesAreAllocated_(false)
79  , indicesAreLocal_(false)
80  , indicesAreGlobal_(false)
81  , fillComplete_(false)
82  , indicesAreSorted_ (true)
83  , noRedundancies_ (true)
84  , haveLocalConstants_ (false)
85  , haveGlobalConstants_ (false)
86  , haveRowInfo_(true)
87  {
88  typedef Teuchos::OrdinalTraits<size_t> OTST;
89  staticAssertions();
90  TEUCHOS_TEST_FOR_EXCEPTION(maxNumEntriesPerRow == OTST::invalid(),
91  std::invalid_argument, "The allocation hint must be a valid size_t value, "
92  "which in this case means it must not be Teuchos::OrdinalTraits<size_t>::"
93  "invalid().");
94  resumeFill(params);
95  checkInternalState();
96  }
97 
100  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
103  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > &colMap,
104  size_t maxNumEntriesPerRow,
105  ProfileType pftype,
106  const RCP<ParameterList>& params)
107  : DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>(rowMap)
108  , rowMap_(rowMap)
109  , colMap_(colMap)
110  , nodeNumEntries_(0)
111  , nodeNumAllocated_(OrdinalTraits<size_t>::invalid())
112  , pftype_(pftype)
113  , numAllocForAllRows_(maxNumEntriesPerRow)
114  , indicesAreAllocated_(false)
115  , indicesAreLocal_(false)
116  , indicesAreGlobal_(false)
117  , fillComplete_(false)
118  , indicesAreSorted_(true)
119  , noRedundancies_(true)
120  , haveLocalConstants_ (false)
121  , haveGlobalConstants_ (false)
122  , haveRowInfo_(true)
123  {
124  typedef Teuchos::OrdinalTraits<size_t> OTST;
125  staticAssertions();
126  TEUCHOS_TEST_FOR_EXCEPTION(maxNumEntriesPerRow == OTST::invalid(),
127  std::invalid_argument, "The allocation hint must be a valid size_t value, "
128  "which in this case means it must not be Teuchos::OrdinalTraits<size_t>::"
129  "invalid().");
130  resumeFill(params);
131  checkInternalState();
132  }
133 
136  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
139  const ArrayRCP<const size_t> &NumEntriesPerRowToAlloc,
140  ProfileType pftype,
141  const RCP<ParameterList>& params)
142  : DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>(rowMap)
143  , rowMap_(rowMap)
144  , nodeNumEntries_(0)
145  , nodeNumAllocated_(OrdinalTraits<size_t>::invalid())
146  , pftype_(pftype)
147  , numAllocPerRow_(NumEntriesPerRowToAlloc)
149  , indicesAreAllocated_(false)
150  , indicesAreLocal_(false)
151  , indicesAreGlobal_(false)
152  , fillComplete_(false)
153  , indicesAreSorted_(true)
154  , noRedundancies_(true)
155  , haveLocalConstants_ (false)
156  , haveGlobalConstants_ (false)
157  , haveRowInfo_(true)
158  {
159  typedef Teuchos::OrdinalTraits<size_t> OTST;
160  const char tfecfFuncName[] = "CrsGraph(rowMap,NumEntriesPerRowToAlloc)";
161  staticAssertions();
162  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC((size_t)NumEntriesPerRowToAlloc.size() != getNodeNumRows(), std::invalid_argument,
163  ": NumEntriesPerRowToAlloc must have as many entries as specified by rowMap for this node.");
164  for (size_t r=0; r < getNodeNumRows(); ++r) {
165  const size_t curRowCount = NumEntriesPerRowToAlloc[r];
166  TEUCHOS_TEST_FOR_EXCEPTION(curRowCount == OTST::invalid(),
167  std::invalid_argument, "NumEntriesPerRowToAlloc[" << r << "] specifies "
168  "an invalid number of entries (Teuchos::OrdinalTraits<size_t>::"
169  "invalid()).");
170  }
171  resumeFill(params);
172  checkInternalState();
173  }
174 
175 
178  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
181  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > &colMap,
182  const ArrayRCP<const size_t> &NumEntriesPerRowToAlloc,
183  ProfileType pftype,
184  const RCP<ParameterList>& params)
185  : DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>(rowMap)
186  , rowMap_(rowMap)
187  , colMap_(colMap)
188  , nodeNumEntries_(0)
189  , nodeNumAllocated_(OrdinalTraits<size_t>::invalid())
190  , pftype_(pftype)
191  , numAllocPerRow_(NumEntriesPerRowToAlloc)
193  , indicesAreAllocated_(false)
194  , indicesAreLocal_(false)
195  , indicesAreGlobal_(false)
196  , fillComplete_(false)
197  , indicesAreSorted_(true)
198  , noRedundancies_(true)
199  , haveLocalConstants_ (false)
200  , haveGlobalConstants_ (false)
201  , haveRowInfo_(true)
202  {
203  typedef Teuchos::OrdinalTraits<size_t> OTST;
204  const char tfecfFuncName[] = "CrsGraph(rowMap,colMap,NumEntriesPerRowToAlloc)";
205  staticAssertions();
206  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC((size_t)NumEntriesPerRowToAlloc.size() != getNodeNumRows(), std::invalid_argument,
207  ": NumEntriesPerRowToAlloc must have as many entries as specified by rowMap for this node.");
208  for (size_t r=0; r < getNodeNumRows(); ++r) {
209  const size_t curRowCount = NumEntriesPerRowToAlloc[r];
210  TEUCHOS_TEST_FOR_EXCEPTION(curRowCount == OTST::invalid(),
211  std::invalid_argument, "NumEntriesPerRowToAlloc[" << r << "] specifies "
212  "an invalid number of entries (Teuchos::OrdinalTraits<size_t>::"
213  "invalid()).");
214  }
215  resumeFill(params);
216  checkInternalState();
217  }
218 
219 
222  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
225  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > &colMap,
226  const ArrayRCP<size_t> & rowPointers,
227  const ArrayRCP<LocalOrdinal> & columnIndices,
228  const RCP<ParameterList>& params)
229  : DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>(rowMap)
230  , rowMap_(rowMap)
231  , colMap_(colMap)
232  , nodeNumEntries_(0)
233  , nodeNumAllocated_(OrdinalTraits<size_t>::invalid())
236  , indicesAreAllocated_(true)
237  , indicesAreLocal_(true)
238  , indicesAreGlobal_(false)
239  , fillComplete_(false)
240  , indicesAreSorted_(true)
241  , noRedundancies_(true)
242  , haveLocalConstants_ (false)
243  , haveGlobalConstants_ (false)
244  , haveRowInfo_(true)
245  {
246  staticAssertions();
247  globalNumEntries_ = globalNumDiags_ = globalMaxNumRowEntries_ = OrdinalTraits<global_size_t>::invalid();
248  setAllIndices(rowPointers,columnIndices);
249  checkInternalState();
250  }
251 
254  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
256  {}
257 
258  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
262  {
263  RCP<ParameterList> params = parameterList ("Tpetra::CrsGraph");
264 
265  // Make a sublist for the Import.
266  RCP<ParameterList> importSublist = parameterList ("Import");
267 
268  // FIXME (mfh 02 Apr 2012) We should really have the Import and
269  // Export objects fill in these lists. However, we don't want to
270  // create an Import or Export unless we need them. For now, we
271  // know that the Import and Export just pass the list directly to
272  // their Distributor, so we can create a Distributor here
273  // (Distributor's constructor is a lightweight operation) and have
274  // it fill in the list.
275 
276  // Fill in Distributor default parameters by creating a
277  // Distributor and asking it to do the work.
278  Distributor distributor (rowMap_->getComm(), importSublist);
279  params->set ("Import", *importSublist, "How the Import performs communication.");
280 
281  // Make a sublist for the Export. For now, it's a clone of the
282  // Import sublist. It's not a shallow copy, though, since we
283  // might like the Import to do communication differently than the
284  // Export.
285  params->set ("Export", *importSublist, "How the Export performs communication.");
286 
287  return params;
288  }
289 
290  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
291  void
294  {
296  params->validateParametersAndSetDefaults (*validParams);
297  this->setMyParamList (params);
298  }
299 
300  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
302  {
303  return rowMap_->getGlobalNumElements();
304  }
305 
306  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
308  {
309  const char tfecfFuncName[] = "getGlobalNumCols()";
311  isFillComplete() == false, std::runtime_error,
312  ": requires domain map, which requires that fillComplete() has been "
313  "called.");
314  return getDomainMap()->getGlobalNumElements();
315  }
316 
317  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
319  {
320  return rowMap_->getNodeNumElements();
321  }
322 
323  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
325  {
326  const char tfecfFuncName[] = "getNodeNumCols()";
328  hasColMap() == false, std::runtime_error,
329  ": requires column map. This requires either that a custom column Map "
330  "was given to the constructor, or that fillComplete() has been called.");
331  return colMap_->getNodeNumElements();
332  }
333 
334  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
336  {
337  return nodeNumDiags_;
338  }
339 
340  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
342  {
343  return globalNumDiags_;
344  }
345 
346  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
347  RCP<Node>
349  {
350  return rowMap_->getNode();
351  }
352 
353  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
356  {
357  return rowMap_;
358  }
359 
360  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
363  {
364  return colMap_;
365  }
366 
367  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
370  {
371  return domainMap_;
372  }
373 
374  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
377  {
378  return rangeMap_;
379  }
380 
381  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
384  {
385  return importer_;
386  }
387 
388  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
391  {
392  return exporter_;
393  }
394 
395  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
397  {
398  return (colMap_ != null);
399  }
400 
401  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
403  {
404  bool isOpt = indicesAreAllocated_ && (numRowEntries_ == null) && (getNodeNumRows() > 0);
405 #ifdef HAVE_TPETRA_DEBUG
406  const char tfecfFuncName[] = "isStorageOptimized()";
407  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( (isOpt == true) && (getProfileType() == DynamicProfile), std::logic_error,
408  ": Violated stated post-conditions. Please contact Tpetra team.");
409 #endif
410  return isOpt;
411  }
412 
413  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
415  {
416  return pftype_;
417  }
418 
419  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
421  {
422  return globalNumEntries_;
423  }
424 
425  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
427  {
428  return nodeNumEntries_;
429  }
430 
431  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
433  {
434  return globalMaxNumRowEntries_;
435  }
436 
437  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
439  {
440  return nodeMaxNumRowEntries_;
441  }
442 
443  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
445  {
446  return fillComplete_;
447  }
448 
449  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
451  {
452  return !fillComplete_;
453  }
454 
455  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
457  {
458  return upperTriangular_;
459  }
460 
461  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
463  {
464  return lowerTriangular_;
465  }
466 
467  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
469  {
470  return indicesAreLocal_;
471  }
472 
473  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
475  {
476  return indicesAreGlobal_;
477  }
478 
479  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
481  {
482  return nodeNumAllocated_;
483  }
484 
485  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
486  const RCP<const Comm<int> > &
488  {
489  return rowMap_->getComm();
490  }
491 
492  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
494  {
495  return rowMap_->getIndexBase();
496  }
497 
498  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
500  {
501  return indicesAreAllocated_;
502  }
503 
504 
507  // //
508  // Internal utility methods //
509  // //
512 
513 
516  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
518  {
519  return indicesAreSorted_;
520  }
521 
522 
525  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
527  {
528  return noRedundancies_;
529  }
530 
533  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
535  {
536  // FIXME (mfh 07 May 2013) How do we know that the change
537  // introduced a redundancy, or even that it invalidated the sorted
538  // order of indices? CrsGraph has always made this conservative
539  // guess. It could be a bit costly to check at insertion time,
540  // though.
541  indicesAreSorted_ = false;
542  noRedundancies_ = false;
543 
544  // We've modified the graph, so we'll have to recompute local
545  // constants like the number of diagonal entries on this process.
546  haveLocalConstants_ = false;
547  }
548 
551  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
552  void
554  allocateIndices (ELocalGlobal lg)
555  {
556  // This is a protected function, only callable by us. If it was
557  // called incorrectly, it is our fault. That's why the tests
558  // below throw std::logic_error instead of std::invalid_argument.
559  const char tfecfFuncName[] = "allocateIndices()";
561  isLocallyIndexed() && lg==GlobalIndices, std::logic_error,
562  ": The graph is locally indexed, but Tpetra code is calling this method "
563  "with lg=GlobalIndices. Please report this bug to the Tpetra developers.");
565  isGloballyIndexed() && lg==LocalIndices, std::logic_error,
566  ": The graph is globally indexed, but Tpetra code is calling this method "
567  "with lg=LocalIndices. Please report this bug to the Tpetra developers.");
569  indicesAreAllocated(), std::logic_error, ": The graph's indices are "
570  "already allocated, but Tpetra code is calling allocateIndices() again. "
571  "Please report this bug to the Tpetra developers.");
572 
573  const size_t numRows = getNodeNumRows();
574  indicesAreLocal_ = (lg == LocalIndices);
575  indicesAreGlobal_ = (lg == GlobalIndices);
576  nodeNumAllocated_ = 0;
577  if (numAllocPerRow_ == null && getNodeNumRows() > 0) {
578  // this wastes memory, temporarily, but it simplifies the code
579  // and interfaces to follow
580  ArrayRCP<size_t> tmpnumallocperrow = arcp<size_t>(numRows);
581  std::fill(tmpnumallocperrow.begin(), tmpnumallocperrow.end(), numAllocForAllRows_);
582  numAllocPerRow_ = tmpnumallocperrow;
583  }
584  //
585  if (getProfileType() == StaticProfile) {
586  //
587  // STATIC ALLOCATION PROFILE
588  //
589  // Have the local sparse kernels object allocate row offsets for
590  // us, with first-touch allocation if applicable. This is not
591  // as important for global indices, because we never use global
592  // indices in sparse kernels, but we might as well use the code
593  // that we have for both the local and global indices cases.
594  // Furthermore, first-touch allocation ensures that we don't
595  // take up too much memory in any one NUMA affinity region.
596  rowPtrs_ = LocalMatOps::allocRowPtrs( getRowMap()->getNode(), numAllocPerRow_() );
597  if (lg == LocalIndices) {
598  lclInds1D_ = LocalMatOps::template allocStorage<LocalOrdinal>( getRowMap()->getNode(), rowPtrs_() );
599  }
600  else {
601  gblInds1D_ = LocalMatOps::template allocStorage<GlobalOrdinal>( getRowMap()->getNode(), rowPtrs_() );
602  }
603  nodeNumAllocated_ = rowPtrs_[numRows];
604  }
605  else {
606  //
607  // DYNAMIC ALLOCATION PROFILE
608  //
610  size_t howmany = numAllocForAllRows_;
611  if (lg == LocalIndices) {
612  lclInds2D_ = arcp< Array<LocalOrdinal> >(numRows);
613  nodeNumAllocated_ = 0;
614  for (size_t i=0; i < numRows; ++i) {
615  if (numAllocPerRow_ != null) howmany = *numalloc++;
616  nodeNumAllocated_ += howmany;
617  if (howmany > 0) lclInds2D_[i].resize(howmany);
618  }
619  }
620  else { // allocate global indices
621  gblInds2D_ = arcp< Array<GlobalOrdinal> >(numRows);
622  nodeNumAllocated_ = 0;
623  for (size_t i=0; i < numRows; ++i) {
624  if (numAllocPerRow_ != null) howmany = *numalloc++;
625  nodeNumAllocated_ += howmany;
626  if (howmany > 0) gblInds2D_[i].resize(howmany);
627  }
628  }
629  }
630  if (numRows > 0) {
631  numRowEntries_ = arcp<size_t>(numRows);
632  std::fill( numRowEntries_.begin(), numRowEntries_.end(), 0 );
633  }
634  // done with these
636  numAllocPerRow_ = null;
637  indicesAreAllocated_ = true;
638  checkInternalState();
639  }
640 
641 
644  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
645  template <class T>
647  {
648  const char tfecfFuncName[] = "allocateValues()";
650  indicesAreAllocated() == false,
651  std::runtime_error, ": graph indices must be allocated before values."
652  );
655  std::runtime_error, ": graph indices must be allocated in a static profile."
656  );
657  ArrayRCP<T> values1D;
658  values1D = LocalMatOps::template allocStorage<T>( getRowMap()->getNode(), rowPtrs_() );
659  return values1D;
660  }
661 
662 
665  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
666  template <class T>
669  {
670  const char tfecfFuncName[] = "allocateValues2D()";
672  indicesAreAllocated() == false,
673  std::runtime_error, ": graph indices must be allocated before values."
674  );
677  std::runtime_error, ": graph indices must be allocated in a dynamic profile."
678  );
679  ArrayRCP<Array<T> > values2D;
680  values2D = arcp<Array<T> > (getNodeNumRows ());
681  if (lclInds2D_ != null) {
682  const size_t numRows = lclInds2D_.size ();
683  for (size_t r = 0; r < numRows; ++r) {
684  values2D[r].resize (lclInds2D_[r].size ());
685  }
686  }
687  else if (gblInds2D_ != null) {
688  const size_t numRows = gblInds2D_.size ();
689  for (size_t r = 0; r < numRows; ++r) {
690  values2D[r].resize (gblInds2D_[r].size ());
691  }
692  }
693  return values2D;
694  }
695 
696 
699  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
700  template <ELocalGlobal lg, class T>
701  RowInfo
704  size_t newAllocSize,
705  Array<T>& rowVals)
706  {
707 #ifdef HAVE_TPETRA_DEBUG
708  TEUCHOS_TEST_FOR_EXCEPT( ! rowMap_->isNodeLocalElement(rowinfo.localRow) );
709  TEUCHOS_TEST_FOR_EXCEPT( newAllocSize < rowinfo.allocSize );
710  TEUCHOS_TEST_FOR_EXCEPT( (lg == LocalIndices && ! isLocallyIndexed()) ||
711  (lg == GlobalIndices && ! isGloballyIndexed()) );
712  TEUCHOS_TEST_FOR_EXCEPT( newAllocSize == 0 );
713  TEUCHOS_TEST_FOR_EXCEPT( ! indicesAreAllocated() );
714 #endif
715  // ArrayRCP::resize automatically copies over values on reallocation.
716  if (lg == LocalIndices) {
717  lclInds2D_[rowinfo.localRow].resize (newAllocSize);
718  }
719  else { // lg == GlobalIndices
720  gblInds2D_[rowinfo.localRow].resize (newAllocSize);
721  }
722  rowVals.resize (newAllocSize);
723  nodeNumAllocated_ += (newAllocSize - rowinfo.allocSize);
724  rowinfo.allocSize = newAllocSize;
725  return rowinfo;
726  }
727 
728 
731  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
734  getLocalView (RowInfo rowinfo) const
735  {
737  if (rowinfo.allocSize > 0) {
738  if (lclInds1D_ != null) {
739  view = lclInds1D_ (rowinfo.offset1D, rowinfo.allocSize);
740  }
741  else if (!lclInds2D_[rowinfo.localRow].empty()) {
742  view = lclInds2D_[rowinfo.localRow] ();
743  }
744  }
745  return view;
746  }
747 
748 
751  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
755  {
757  if (rowinfo.allocSize > 0) {
758  if (lclInds1D_ != null) {
759  view = lclInds1D_ (rowinfo.offset1D, rowinfo.allocSize);
760  }
761  else if (! lclInds2D_[rowinfo.localRow].empty()) {
762  view = lclInds2D_[rowinfo.localRow] ();
763  }
764  }
765  return view;
766  }
767 
768 
771  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
774  getGlobalView (RowInfo rowinfo) const
775  {
777  if (rowinfo.allocSize > 0) {
778  if (gblInds1D_ != null) {
779  view = gblInds1D_ (rowinfo.offset1D, rowinfo.allocSize);
780  }
781  else if (! gblInds2D_[rowinfo.localRow].empty()) {
782  view = gblInds2D_[rowinfo.localRow] ();
783  }
784  }
785  return view;
786  }
787 
788 
791  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
795  {
797  if (rowinfo.allocSize > 0) {
798  if (gblInds1D_ != null) {
799  view = gblInds1D_ (rowinfo.offset1D, rowinfo.allocSize);
800  }
801  else if (!gblInds2D_[rowinfo.localRow].empty()) {
802  view = gblInds2D_[rowinfo.localRow] ();
803  }
804  }
805  return view;
806  }
807 
808 
811  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
813  {
814 #ifdef HAVE_TPETRA_DEBUG
815  const char tfecfFuncName[] = "getRowInfo()";
817  rowMap_->isNodeLocalElement (myRow) == false,
818  std::logic_error,
819  ": The given (local) row index myRow = " << myRow
820  << " does not belong to the graph's row Map. "
821  "This probably indicates a bug in Tpetra::CrsGraph or Tpetra::CrsMatrix. "
822  "Please report this to the Tpetra developers.");
824  hasRowInfo() == false, std::logic_error,
825  ": Late catch! Graph does not have row info anymore. "
826  "Error should have been caught earlier. Please contact Tpetra team.");
827 #endif // HAVE_TPETRA_DEBUG
828  const size_t STINV = Teuchos::OrdinalTraits<size_t>::invalid ();
829  RowInfo ret;
830  ret.localRow = myRow;
831  if (nodeNumAllocated_ != 0 && nodeNumAllocated_ != STINV) {
832  // graph data structures have the info that we need
833  //
834  // if static graph, offsets tell us the allocation size
835  if (getProfileType() == StaticProfile) {
836  ret.offset1D = rowPtrs_[myRow];
837  ret.allocSize = rowPtrs_[myRow+1] - rowPtrs_[myRow];
838  if (numRowEntries_ == null) {
839  ret.numEntries = ret.allocSize;
840  }
841  else {
842  ret.numEntries = numRowEntries_[myRow];
843  }
844  }
845  else {
846  ret.offset1D = STINV;
847  if (isLocallyIndexed ()) {
848  ret.allocSize = lclInds2D_[myRow].size();
849  }
850  else {
851  ret.allocSize = gblInds2D_[myRow].size();
852  }
853  ret.numEntries = numRowEntries_[myRow];
854  }
855  }
856  else if (nodeNumAllocated_ == 0) {
857  // have performed allocation, but the graph has no allocation or entries
858  ret.allocSize = 0;
859  ret.numEntries = 0;
860  ret.offset1D = STINV;
861  }
862  else if (indicesAreAllocated () == false) {
863  // haven't performed allocation yet; probably won't hit this code
864  if (numAllocPerRow_ == null) {
865  ret.allocSize = numAllocForAllRows_;
866  }
867  else {
868  ret.allocSize = numAllocPerRow_[myRow];
869  }
870  ret.numEntries = 0;
871  ret.offset1D = STINV;
872  }
873  else {
874  // don't know how we ended up here...
876  }
877  return ret;
878  }
879 
880 
883  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
885  {
886  // Assumption: sizeof(GlobalOrdinal) >= sizeof(LocalOrdinal):
887  // This is so that we can store local indices in the memory
888  // formerly occupied by global indices.
889  //
890  // Assumption: max(GlobalOrdinal) >= max(LocalOrdinal) and
891  // max(size_t) >= max(LocalOrdinal)
892  // This is so that we can represent any LocalOrdinal as a
893  // size_t, and any LocalOrdinal as a GlobalOrdinal
896  // can't call max() with CompileTimeAssert, because it isn't a constant expression; will need to make this a runtime check
897  std::string msg = typeName(*this) + ": Object cannot be allocated with stated template arguments: size assumptions are not valid.";
902  }
903 
904 
907  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
908  template <ELocalGlobal lg>
909  size_t CrsGraph<LocalOrdinal,GlobalOrdinal,Node,LocalMatOps>::filterIndices(const SLocalGlobalNCViews &inds) const
910  {
913  (void)cta_lg;
914  size_t numFiltered = 0;
915 #ifdef HAVE_TPETRA_DEBUG
916  size_t numFiltered_debug = 0;
917 #endif
918  if (lg == GlobalIndices) {
919  ArrayView<GlobalOrdinal> ginds = inds.ginds;
920  typename ArrayView<GlobalOrdinal>::iterator fend = ginds.begin(),
921  cptr = ginds.begin();
922  while (cptr != ginds.end()) {
923  if (cmap.isNodeGlobalElement(*cptr)) {
924  *fend++ = *cptr;
925 #ifdef HAVE_TPETRA_DEBUG
926  ++numFiltered_debug;
927 #endif
928  }
929  ++cptr;
930  }
931  numFiltered = fend - ginds.begin();
932  }
933  else if (lg == LocalIndices) {
934  ArrayView<LocalOrdinal> linds = inds.linds;
935  typename ArrayView<LocalOrdinal>::iterator fend = linds.begin(),
936  cptr = linds.begin();
937  while (cptr != linds.end()) {
938  if (cmap.isNodeLocalElement(*cptr)) {
939  *fend++ = *cptr;
940 #ifdef HAVE_TPETRA_DEBUG
941  ++numFiltered_debug;
942 #endif
943  }
944  ++cptr;
945  }
946  numFiltered = fend - linds.begin();
947  }
948 #ifdef HAVE_TPETRA_DEBUG
949  TEUCHOS_TEST_FOR_EXCEPT( numFiltered != numFiltered_debug );
950 #endif
951  return numFiltered;
952  }
953 
954 
957  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
958  template <class T>
961  const ArrayView<T>& vals) const
962  {
964  size_t numFiltered = 0;
965  typename ArrayView<T>::iterator fvalsend = vals.begin();
966  typename ArrayView<T>::iterator valscptr = vals.begin();
967 #ifdef HAVE_TPETRA_DEBUG
968  size_t numFiltered_debug = 0;
969 #endif
970  typename ArrayView<GlobalOrdinal>::iterator fend = ginds.begin();
971  typename ArrayView<GlobalOrdinal>::iterator cptr = ginds.begin();
972  while (cptr != ginds.end()) {
973  if (cmap.isNodeGlobalElement (*cptr)) {
974  *fend++ = *cptr;
975  *fvalsend++ = *valscptr;
976 #ifdef HAVE_TPETRA_DEBUG
977  ++numFiltered_debug;
978 #endif
979  }
980  ++cptr;
981  ++valscptr;
982  }
983  numFiltered = fend - ginds.begin();
984 #ifdef HAVE_TPETRA_DEBUG
985  TEUCHOS_TEST_FOR_EXCEPT( numFiltered != numFiltered_debug );
986  TEUCHOS_TEST_FOR_EXCEPT( valscptr != vals.end() );
987  const size_t numFilteredActual =
988  Teuchos::as<size_t> (fvalsend - vals.begin ());
989  TEUCHOS_TEST_FOR_EXCEPT( numFiltered != numFilteredActual );
990 #endif
991  return numFiltered;
992  }
993 
994 
997  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
998  template <class T>
999  size_t
1002  const ArrayView<T>& vals) const
1003  {
1005  size_t numFiltered = 0;
1006  typename ArrayView<T>::iterator fvalsend = vals.begin();
1007  typename ArrayView<T>::iterator valscptr = vals.begin();
1008 #ifdef HAVE_TPETRA_DEBUG
1009  size_t numFiltered_debug = 0;
1010 #endif
1011  typename ArrayView<LocalOrdinal>::iterator fend = linds.begin();
1012  typename ArrayView<LocalOrdinal>::iterator cptr = linds.begin();
1013  while (cptr != linds.end()) {
1014  if (cmap.isNodeLocalElement (*cptr)) {
1015  *fend++ = *cptr;
1016  *fvalsend++ = *valscptr;
1017 #ifdef HAVE_TPETRA_DEBUG
1018  ++numFiltered_debug;
1019 #endif
1020  }
1021  ++cptr;
1022  ++valscptr;
1023  }
1024  numFiltered = fend - linds.begin();
1025 #ifdef HAVE_TPETRA_DEBUG
1026  TEUCHOS_TEST_FOR_EXCEPT( numFiltered != numFiltered_debug );
1027  TEUCHOS_TEST_FOR_EXCEPT( valscptr != vals.end() );
1028  const size_t numFilteredActual =
1029  Teuchos::as<size_t> (fvalsend - vals.begin ());
1030  TEUCHOS_TEST_FOR_EXCEPT( numFiltered != numFilteredActual );
1031 #endif
1032  return numFiltered;
1033  }
1034 
1035 
1038  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1039  size_t
1041  insertIndices (const RowInfo& rowinfo,
1042  const SLocalGlobalViews &newInds,
1043  const ELocalGlobal lg,
1044  const ELocalGlobal I)
1045  {
1046 #ifdef HAVE_TPETRA_DEBUG
1048  lg != GlobalIndices && lg != LocalIndices, std::invalid_argument,
1049  "Tpetra::CrsGraph::insertIndices: lg must be either GlobalIndices or "
1050  "LocalIndices.");
1051 #endif // HAVE_TPETRA_DEBUG
1052  size_t numNewInds = 0;
1053  if (lg == GlobalIndices) { // input indices are global
1054  ArrayView<const GlobalOrdinal> new_ginds = newInds.ginds;
1055  numNewInds = new_ginds.size();
1056  if (I == GlobalIndices) { // store global indices
1057  ArrayView<GlobalOrdinal> gind_view = getGlobalViewNonConst(rowinfo);
1058  std::copy(new_ginds.begin(), new_ginds.end(), gind_view.begin()+rowinfo.numEntries);
1059  }
1060  else if (I == LocalIndices) { // store local indices
1061  ArrayView<LocalOrdinal> lind_view = getLocalViewNonConst(rowinfo);
1062  typename ArrayView<const GlobalOrdinal>::iterator in = new_ginds.begin();
1063  const typename ArrayView<const GlobalOrdinal>::iterator stop = new_ginds.end();
1064  typename ArrayView<LocalOrdinal>::iterator out = lind_view.begin()+rowinfo.numEntries;
1065  while (in != stop) {
1066  *out++ = colMap_->getLocalElement (*in++);
1067  }
1068  }
1069  }
1070  else if (lg == LocalIndices) { // input indices are local
1071  ArrayView<const LocalOrdinal> new_linds = newInds.linds;
1072  numNewInds = new_linds.size();
1073  if (I == LocalIndices) { // store local indices
1074  ArrayView<LocalOrdinal> lind_view = getLocalViewNonConst(rowinfo);
1075  std::copy(new_linds.begin(), new_linds.end(), lind_view.begin()+rowinfo.numEntries);
1076  }
1077  else if (I == GlobalIndices) {
1078  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Tpetra::CrsGraph::"
1079  "insertIndices: the case where the input indices are local and the "
1080  "indices to write are global (lg=LocalIndices, I=GlobalIndices) is "
1081  "not implemented, because it does not make sense." << std::endl <<
1082  "If you have correct local column indices, that means the graph has "
1083  "a column Map. In that case, you should be storing local indices.");
1084  }
1085  }
1086  numRowEntries_[rowinfo.localRow] += numNewInds;
1087  nodeNumEntries_ += numNewInds;
1088  setLocallyModified ();
1089  return numNewInds;
1090  }
1091 
1094  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1096  insertGlobalIndicesImpl (const LocalOrdinal myRow,
1097  const ArrayView<const GlobalOrdinal> &indices)
1098  {
1099  const char* tfecfFuncName ("insertGlobalIndicesImpl");
1100 
1101  RowInfo rowInfo = getRowInfo(myRow);
1102  const size_t numNewInds = indices.size();
1103  const size_t newNumEntries = rowInfo.numEntries + numNewInds;
1104  if (newNumEntries > rowInfo.allocSize) {
1106  getProfileType() == StaticProfile, std::runtime_error,
1107  ": new indices exceed statically allocated graph structure.");
1108 
1109  // update allocation, doubling size to reduce number of reallocations
1110  size_t newAllocSize = 2*rowInfo.allocSize;
1111  if (newAllocSize < newNumEntries)
1112  newAllocSize = newNumEntries;
1113  gblInds2D_[myRow].resize(newAllocSize);
1114  nodeNumAllocated_ += (newAllocSize - rowInfo.allocSize);
1115  }
1116 
1117  // Copy new indices at end of global index array
1118  if (gblInds1D_ != null)
1119  std::copy(indices.begin(), indices.end(),
1120  gblInds1D_.begin()+rowInfo.offset1D+rowInfo.numEntries);
1121  else
1122  std::copy(indices.begin(), indices.end(),
1123  gblInds2D_[myRow].begin()+rowInfo.numEntries);
1124  numRowEntries_[myRow] += numNewInds;
1125  nodeNumEntries_ += numNewInds;
1126  setLocallyModified ();
1127 
1128 #ifdef HAVE_TPETRA_DEBUG
1129  {
1130  const size_t chkNewNumEntries = getNumEntriesInLocalRow (myRow);
1132  chkNewNumEntries != newNumEntries, std::logic_error,
1133  ": Internal logic error. Please contact Tpetra team.");
1134  }
1135 #endif
1136  }
1137 
1140  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1142  insertLocalIndicesImpl (const LocalOrdinal myRow,
1143  const ArrayView<const LocalOrdinal> &indices)
1144  {
1145  const char* tfecfFuncName ("insertLocallIndicesImpl");
1146 
1147  RowInfo rowInfo = getRowInfo(myRow);
1148  const size_t numNewInds = indices.size();
1149  const size_t newNumEntries = rowInfo.numEntries + numNewInds;
1150  if (newNumEntries > rowInfo.allocSize) {
1152  getProfileType() == StaticProfile, std::runtime_error,
1153  ": new indices exceed statically allocated graph structure.");
1154 
1155  // update allocation, doubling size to reduce number of reallocations
1156  size_t newAllocSize = 2*rowInfo.allocSize;
1157  if (newAllocSize < newNumEntries)
1158  newAllocSize = newNumEntries;
1159  lclInds2D_[myRow].resize(newAllocSize);
1160  nodeNumAllocated_ += (newAllocSize - rowInfo.allocSize);
1161  }
1162 
1163  // Insert new indices at end of lclInds array
1164  if (lclInds1D_ != null)
1165  std::copy(indices.begin(), indices.end(),
1166  lclInds1D_.begin()+rowInfo.offset1D+rowInfo.numEntries);
1167  else
1168  std::copy(indices.begin(), indices.end(),
1169  lclInds2D_[myRow].begin()+rowInfo.numEntries);
1170  numRowEntries_[myRow] += numNewInds;
1171  nodeNumEntries_ += numNewInds;
1172  setLocallyModified ();
1173 #ifdef HAVE_TPETRA_DEBUG
1174  {
1175  const size_t chkNewNumEntries = getNumEntriesInLocalRow (myRow);
1177  chkNewNumEntries != newNumEntries, std::logic_error,
1178  ": Internal logic error. Please contact Tpetra team.");
1179  }
1180 #endif
1181  }
1182 
1185  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1186  template <class Scalar>
1189  const SLocalGlobalViews& newInds,
1190  const ArrayView<Scalar>& oldRowVals,
1191  const ArrayView<const Scalar>& newRowVals,
1192  const ELocalGlobal lg,
1193  const ELocalGlobal I)
1194  {
1195  const size_t numNewInds = insertIndices (rowInfo, newInds, lg, I);
1196  typename ArrayView<const Scalar>::const_iterator newRowValsBegin =
1197  newRowVals.begin ();
1198  std::copy (newRowValsBegin, newRowValsBegin + numNewInds,
1199  oldRowVals.begin () + rowInfo.numEntries);
1200  }
1201 
1204  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1205  template <class Scalar, class BinaryFunction>
1206  void
1209  const Teuchos::ArrayView<Scalar>& rowVals,
1211  const Teuchos::ArrayView<const Scalar>& newVals,
1212  BinaryFunction f) const
1213  {
1214  const size_t STINV = Teuchos::OrdinalTraits<size_t>::invalid();
1215  const size_t numElts = Teuchos::as<size_t> (inds.size ());
1216  size_t hint = 0; // Guess for the current index k into rowVals
1217 
1218  // Get a view of the column indices in the row. This amortizes
1219  // the cost of getting the view over all the entries of inds.
1220  ArrayView<const LocalOrdinal> colInds = getLocalView (rowInfo);
1221 
1222  for (size_t j = 0; j < numElts; ++j) {
1223  const size_t k = findLocalIndex (rowInfo, inds[j], colInds, hint);
1224  if (k != STINV) {
1225  rowVals[k] = f( rowVals[k], newVals[j] );
1226  hint = k+1;
1227  }
1228  }
1229  }
1230 
1231 
1234  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1235  template <class Scalar, class BinaryFunction>
1236  void
1239  const Teuchos::ArrayView<Scalar>& rowVals,
1241  const Teuchos::ArrayView<const Scalar>& newVals,
1242  BinaryFunction f) const
1243  {
1244  const size_t STINV = Teuchos::OrdinalTraits<size_t>::invalid();
1245  const size_t numElts = Teuchos::as<size_t> (inds.size ());
1246  size_t hint = 0; // hint is a guess as to wheter the index is
1247 
1248  for (size_t j = 0; j < numElts; ++j) {
1249  const size_t k = findGlobalIndex (rowInfo, inds[j], hint);
1250  if (k != STINV) {
1251  rowVals[k] = f( rowVals[k], newVals[j] );
1252  hint = k+1;
1253  }
1254  }
1255  }
1256 
1257 
1258 
1261  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1263  {
1264  if (rowinfo.numEntries > 0) {
1265  ArrayView<LocalOrdinal> inds_view = getLocalViewNonConst(rowinfo);
1266  std::sort(inds_view.begin(), inds_view.begin() + rowinfo.numEntries);
1267  }
1268  }
1269 
1270 
1273  // in the future, perhaps this could use std::sort with a boost::zip_iterator
1274  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1275  template <class Scalar>
1277  {
1278  if (rowinfo.numEntries > 0) {
1279  ArrayView<LocalOrdinal> inds_view = getLocalViewNonConst(rowinfo);
1280  sort2(inds_view.begin(), inds_view.begin()+rowinfo.numEntries, values.begin());
1281  }
1282  }
1283 
1284 
1287  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1289  {
1290  const char tfecfFuncName[] = "mergRowIndices()";
1292  isStorageOptimized() == true, std::logic_error,
1293  ": The graph is already storage optimized, so we shouldn't be merging any indices."
1294  " Please report this bug to the Tpetra developers.");
1295  ArrayView<LocalOrdinal> inds_view = getLocalViewNonConst(rowinfo);
1296  typename ArrayView<LocalOrdinal>::iterator beg, end, newend;
1297  beg = inds_view.begin();
1298  end = inds_view.begin() + rowinfo.numEntries;
1299  newend = std::unique(beg,end);
1300  const size_t mergedEntries = newend - beg;
1301 #ifdef HAVE_TPETRA_DEBUG
1302  // merge should not have eliminated any entries; if so, the assignment below will destory the packed structure
1303  TEUCHOS_TEST_FOR_EXCEPT( isStorageOptimized() && mergedEntries != rowinfo.numEntries );
1304 #endif
1305  numRowEntries_[rowinfo.localRow] = mergedEntries;
1306  nodeNumEntries_ -= (rowinfo.numEntries - mergedEntries);
1307  }
1308 
1309 
1312  // in the future, this could use std::unique with a boost::zip_iterator
1313  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1314  template<class Scalar>
1317  {
1318  const char tfecfFuncName[] = "mergeRowIndicesAndValues";
1320  isStorageOptimized(), std::logic_error, ": It is invalid to call this "
1321  "method if the graph's storage has already been optimized." << std::endl
1322  << "Please report this bug to the Tpetra developers.");
1323 
1324  typedef typename ArrayView<Scalar>::iterator Iter;
1325  Iter rowValueIter = rowValues.begin ();
1326  ArrayView<LocalOrdinal> inds_view = getLocalViewNonConst (rowinfo);
1327  typename ArrayView<LocalOrdinal>::iterator beg, end, newend;
1328 
1329  // beg,end define a half-exclusive interval over which to iterate.
1330  beg = inds_view.begin();
1331  end = inds_view.begin() + rowinfo.numEntries;
1332  newend = beg;
1333  if (beg != end) {
1334  typename ArrayView<LocalOrdinal>::iterator cur = beg + 1;
1335  Iter vcur = rowValueIter + 1;
1336  Iter vend = rowValueIter;
1337  cur = beg+1;
1338  while (cur != end) {
1339  if (*cur != *newend) {
1340  // new entry; save it
1341  ++newend;
1342  ++vend;
1343  (*newend) = (*cur);
1344  (*vend) = (*vcur);
1345  }
1346  else {
1347  // old entry; merge it
1348  //(*vend) = f (*vend, *vcur);
1349  (*vend) += *vcur;
1350  }
1351  ++cur;
1352  ++vcur;
1353  }
1354  ++newend; // one past the last entry, per typical [beg,end) semantics
1355  }
1356  const size_t mergedEntries = newend - beg;
1357 #ifdef HAVE_TPETRA_DEBUG
1358  // merge should not have eliminated any entries; if so, the
1359  // assignment below will destroy the packed structure
1361  isStorageOptimized() && mergedEntries != rowinfo.numEntries,
1362  std::logic_error,
1363  ": Merge was incorrect; it eliminated entries from the graph. "
1364  << std::endl << "Please report this bug to the Tpetra developers.");
1365 #endif // HAVE_TPETRA_DEBUG
1366  numRowEntries_[rowinfo.localRow] = mergedEntries;
1367  nodeNumEntries_ -= (rowinfo.numEntries - mergedEntries);
1368  }
1369 
1370 
1373  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1376  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> >& rangeMap)
1377  {
1378  // simple pointer comparison for equality
1379  if (domainMap_ != domainMap) {
1380  domainMap_ = domainMap;
1381  importer_ = null;
1382  }
1383  if (rangeMap_ != rangeMap) {
1384  rangeMap_ = rangeMap;
1385  exporter_ = null;
1386  }
1387  }
1388 
1389 
1392  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1393  size_t
1395  findLocalIndex (RowInfo rowinfo, LocalOrdinal ind, size_t hint) const
1396  {
1397  ArrayView<const LocalOrdinal> colInds = getLocalView (rowinfo);
1398  return this->findLocalIndex (rowinfo, ind, colInds, hint);
1399  }
1400 
1401 
1404  template <class LocalOrdinal,
1405  class GlobalOrdinal,
1406  class Node,
1407  class LocalMatOps>
1408  size_t
1411  LocalOrdinal ind,
1413  size_t hint) const
1414  {
1415  typedef typename ArrayView<const LocalOrdinal>::iterator IT;
1416 
1417  // If the hint was correct, then the hint is the offset to return.
1418  if (hint < rowinfo.numEntries && colInds[hint] == ind) {
1419  return hint;
1420  }
1421 
1422  // The hint was wrong, so we must search for the given column
1423  // index in the column indices for the given row. How we do the
1424  // search depends on whether the graph's column indices are
1425  // sorted.
1426  IT beg = colInds.begin ();
1427  IT end = beg + rowinfo.numEntries;
1428  IT ptr = beg + rowinfo.numEntries; // "null"
1429  bool found = true;
1430 
1431  if (isSorted ()) {
1432  // binary search
1433  std::pair<IT,IT> p = std::equal_range (beg, end, ind);
1434  if (p.first == p.second) {
1435  found = false;
1436  }
1437  else {
1438  ptr = p.first;
1439  }
1440  }
1441  else {
1442  // direct search
1443  ptr = std::find (beg, end, ind);
1444  if (ptr == end) {
1445  found = false;
1446  }
1447  }
1448 
1449  if (found) {
1450  return Teuchos::as<size_t> (ptr - beg);
1451  }
1452  else {
1454  }
1455  }
1456 
1457 
1460  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1461  size_t
1463  findGlobalIndex (RowInfo rowinfo, GlobalOrdinal ind, size_t hint) const
1464  {
1465  typedef typename ArrayView<const GlobalOrdinal>::iterator IT;
1466  ArrayView<const GlobalOrdinal> indices = getGlobalView (rowinfo);
1467 
1468  // We don't actually require that the hint be a valid index.
1469  // If it is not in range, we just ignore it.
1470  if (hint < rowinfo.numEntries && indices[hint] == ind) {
1471  return hint;
1472  }
1473 
1474  IT beg = indices.begin ();
1475  IT end = indices.begin () + rowinfo.numEntries; // not indices.end()
1476  if (isSorted ()) { // use binary search
1477  const std::pair<IT,IT> p = std::equal_range (beg, end, ind);
1478  if (p.first == p.second) { // range of matching entries is empty
1480  } else {
1481  return p.first - beg;
1482  }
1483  }
1484  else { // not sorted; must use linear search
1485  const IT loc = std::find (beg, end, ind);
1486  if (loc == end) {
1488  } else {
1489  return loc - beg;
1490  }
1491  }
1492  }
1493 
1494 
1497  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1499  {
1500  globalNumEntries_ = OrdinalTraits<global_size_t>::invalid();
1501  globalNumDiags_ = OrdinalTraits<global_size_t>::invalid();
1502  globalMaxNumRowEntries_ = OrdinalTraits<global_size_t>::invalid();
1503  haveGlobalConstants_ = false;
1504  }
1505 
1506 
1509  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1511  {
1512 #ifdef HAVE_TPETRA_DEBUG
1514  const size_t STI = OrdinalTraits<size_t>::invalid();
1515  std::string err = typeName(*this) + "::checkInternalState(): Likely internal logic error. Please contact Tpetra team.";
1516  // check the internal state of this data structure
1517  // this is called by numerous state-changing methods, in a debug build, to ensure that the object
1518  // always remains in a valid state
1519  // the graph should have been allocated with a row map
1520  TEUCHOS_TEST_FOR_EXCEPTION( rowMap_ == null, std::logic_error, err );
1521  // am either complete or active
1522  TEUCHOS_TEST_FOR_EXCEPTION( isFillActive() == isFillComplete(), std::logic_error, err );
1523  // if active, i have no local graph
1524  TEUCHOS_TEST_FOR_EXCEPTION( isFillActive() && lclGraph_ != null, std::logic_error, err );
1525  // if the graph has been fill completed, then all maps should be present
1526  TEUCHOS_TEST_FOR_EXCEPTION( isFillComplete() == true && (colMap_ == null || rangeMap_ == null || domainMap_ == null), std::logic_error, err );
1527  // if storage has been optimized, then indices should have been allocated (even if trivially so)
1528  TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() == true && indicesAreAllocated() == false, std::logic_error, err );
1529  // if storage has been optimized, then number of allocated is now the number of entries
1530  TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() == true && getNodeAllocationSize() != getNodeNumEntries(), std::logic_error, err );
1531  // if graph doesn't have the global constants, then they should all be marked as invalid
1532  TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == false && ( globalNumEntries_ != GSTI || globalNumDiags_ != GSTI || globalMaxNumRowEntries_ != GSTI ), std::logic_error, err );
1533  // if the graph has global cosntants, then they should be valid.
1534  TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == true && ( globalNumEntries_ == GSTI || globalNumDiags_ == GSTI || globalMaxNumRowEntries_ == GSTI ), std::logic_error, err );
1535  TEUCHOS_TEST_FOR_EXCEPTION( haveGlobalConstants_ == true && ( globalNumEntries_ < nodeNumEntries_ || globalNumDiags_ < nodeNumDiags_ || globalMaxNumRowEntries_ < nodeMaxNumRowEntries_ ),
1536  std::logic_error, err );
1537  // if indices are allocated, then the allocation specifications should have been released
1538  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == true && (numAllocForAllRows_ != 0 || numAllocPerRow_ != null), std::logic_error, err );
1539  // if indices are not allocated, then information dictating allocation quantities should be present
1540  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == false && (nodeNumAllocated_ != STI || nodeNumEntries_ != 0), std::logic_error, err );
1541  // if storage is optimized, then profile should be static
1542  TEUCHOS_TEST_FOR_EXCEPTION( isStorageOptimized() && pftype_ != StaticProfile, std::logic_error, err );
1543  // if rowPtrs_ exists, it is required to have N+1 rows, and rowPtrs_[N] == gblInds1D_.size()/lclInds1D_.size()
1544  TEUCHOS_TEST_FOR_EXCEPTION( isGloballyIndexed() && rowPtrs_ != null && ((size_t)rowPtrs_.size() != getNodeNumRows()+1 || rowPtrs_[getNodeNumRows()] != (size_t)gblInds1D_.size()), std::logic_error, err );
1545  TEUCHOS_TEST_FOR_EXCEPTION( isLocallyIndexed() && rowPtrs_ != null && ((size_t)rowPtrs_.size() != getNodeNumRows()+1 || rowPtrs_[getNodeNumRows()] != (size_t)lclInds1D_.size()), std::logic_error, err );
1546  // if profile is dynamic and we have allocated, then 2D allocations should be present
1547  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == DynamicProfile && indicesAreAllocated() && getNodeNumRows() > 0 && lclInds2D_ == null && gblInds2D_ == null,
1548  std::logic_error, err );
1549  // if profile is dynamic, then numentries and 2D indices are needed and should be present
1550  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == DynamicProfile && indicesAreAllocated() && getNodeNumRows() > 0 && (numRowEntries_ == null || (lclInds2D_ == null && gblInds2D_ == null)),
1551  std::logic_error, err );
1552  // if profile is dynamic, then 1D allocations should not be present
1553  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == DynamicProfile && (lclInds1D_ != null || gblInds1D_ != null), std::logic_error, err );
1554  // if profile is dynamic, then row offsets should not be present
1555  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == DynamicProfile && rowPtrs_ != null, std::logic_error, err );
1556  // if profile is static and we have allocated non-trivially, then 1D allocations should be present
1557  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == StaticProfile && indicesAreAllocated() && getNodeAllocationSize() > 0 && lclInds1D_ == null && gblInds1D_ == null,
1558  std::logic_error, err );
1559  // if profile is static, then 2D allocations should not be present
1560  TEUCHOS_TEST_FOR_EXCEPTION( pftype_ == StaticProfile && (lclInds2D_ != null || gblInds2D_ != null), std::logic_error, err );
1561  // if indices are not allocated, then none of the buffers should be.
1562  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == false && (rowPtrs_ != null || numRowEntries_ != null ||
1563  lclInds1D_ != null || lclInds2D_ != null ||
1564  gblInds1D_ != null || gblInds2D_ != null), std::logic_error, err );
1565  // indices may be local or global only if they are allocated (numAllocated is redundant; could simply be indicesAreLocal_ || indicesAreGlobal_)
1566  TEUCHOS_TEST_FOR_EXCEPTION( (indicesAreLocal_ == true || indicesAreGlobal_ == true) && indicesAreAllocated_ == false, std::logic_error, err );
1567  // indices may be local or global, but not both
1568  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreLocal_ == true && indicesAreGlobal_ == true, std::logic_error, err );
1569  // if indices are local, then global allocations should not be present
1570  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreLocal_ == true && (gblInds1D_ != null || gblInds2D_ != null), std::logic_error, err );
1571  // if indices are global, then local allocations should not be present
1572  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreGlobal_ == true && (lclInds1D_ != null || lclInds2D_ != null), std::logic_error, err );
1573  // if indices are local, then local allocations should be present
1574  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreLocal_ == true && getNodeAllocationSize() > 0 && lclInds1D_ == null && getNodeNumRows() > 0 && lclInds2D_ == null,
1575  std::logic_error, err );
1576  // if indices are global, then global allocations should be present
1577  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreGlobal_ == true && getNodeAllocationSize() > 0 && gblInds1D_ == null && getNodeNumRows() > 0 && gblInds2D_ == null,
1578  std::logic_error, err );
1579  // if indices are allocated, then we should have recorded how many were allocated
1580  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == true && nodeNumAllocated_ == STI, std::logic_error, err );
1581  // if indices are not allocated, then the allocation size should be marked invalid
1582  TEUCHOS_TEST_FOR_EXCEPTION( indicesAreAllocated() == false && nodeNumAllocated_ != STI, std::logic_error, err );
1583  // check the actual allocations
1584  if (indicesAreAllocated()) {
1585  size_t actualNumAllocated = 0;
1586  if (pftype_ == DynamicProfile) {
1587  if (isGloballyIndexed() && gblInds2D_ != null) {
1588  for (size_t r = 0; r < getNodeNumRows(); ++r) {
1589  actualNumAllocated += gblInds2D_[r].size();
1590  }
1591  }
1592  else if (isLocallyIndexed() && lclInds2D_ != null) {
1593  for (size_t r = 0; r < getNodeNumRows(); ++r) {
1594  actualNumAllocated += lclInds2D_[r].size();
1595  }
1596  }
1597  TEUCHOS_TEST_FOR_EXCEPTION(actualNumAllocated != nodeNumAllocated_, std::logic_error, err );
1598  }
1599  else if (rowPtrs_ != null) { // pftype_ == StaticProfile
1600  actualNumAllocated = rowPtrs_[getNodeNumRows()];
1601  TEUCHOS_TEST_FOR_EXCEPTION( isLocallyIndexed() == true && (size_t)lclInds1D_.size() != actualNumAllocated, std::logic_error, err );
1602  TEUCHOS_TEST_FOR_EXCEPTION( isGloballyIndexed() == true && (size_t)gblInds1D_.size() != actualNumAllocated, std::logic_error, err );
1603  TEUCHOS_TEST_FOR_EXCEPTION(actualNumAllocated != nodeNumAllocated_, std::logic_error, err );
1604  }
1605  }
1606 #endif
1607  }
1608 
1609 
1612  // //
1613  // User-visible class methods //
1614  // //
1617 
1618 
1621  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1623  {
1624  const LocalOrdinal lrow = rowMap_->getLocalElement(globalRow);
1625  size_t ret = OrdinalTraits<size_t>::invalid();
1626  if (hasRowInfo() && lrow != OrdinalTraits<LocalOrdinal>::invalid())
1627  {
1628  RowInfo rowinfo = getRowInfo(lrow);
1629  ret = rowinfo.numEntries;
1630  }
1631  return ret;
1632  }
1633 
1634 
1637  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1639  {
1640  size_t ret = OrdinalTraits<size_t>::invalid();
1641  if (hasRowInfo() && rowMap_->isNodeLocalElement(localRow)) {
1642  RowInfo rowinfo = getRowInfo(localRow);
1643  ret = rowinfo.numEntries;
1644  }
1645  return ret;
1646  }
1647 
1648 
1651  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1653  {
1654  const LocalOrdinal lrow = rowMap_->getLocalElement(globalRow);
1655  size_t ret = OrdinalTraits<size_t>::invalid();
1656  if (hasRowInfo() && lrow != OrdinalTraits<LocalOrdinal>::invalid())
1657  {
1658  RowInfo rowinfo = getRowInfo(lrow);
1659  ret = rowinfo.allocSize;
1660  }
1661  return ret;
1662  }
1663 
1664 
1667  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1669  {
1670  size_t ret = OrdinalTraits<size_t>::invalid();
1671  if (hasRowInfo() && rowMap_->isNodeLocalElement(localRow)) {
1672  RowInfo rowinfo = getRowInfo(localRow);
1673  ret = rowinfo.allocSize;
1674  }
1675  return ret;
1676  }
1677 
1678 
1681  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1683  {
1684  return rowPtrs_;
1685  }
1686 
1687 
1690  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1692  {
1693  return lclInds1D_;
1694  }
1695 
1696 
1699  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1700  void CrsGraph<LocalOrdinal,GlobalOrdinal,Node,LocalMatOps>::getLocalRowCopy(LocalOrdinal localRow, const ArrayView<LocalOrdinal> &indices, size_t &NumIndices) const
1701  {
1702  // can only do this if
1703  // * we have local indices: isLocallyIndexed()
1704  // or
1705  // * we are capable of producing them: isGloballyIndexed() && hasColMap()
1706  // short circuit if we aren't allocated
1707  const char tfecfFuncName[] = "getLocalRowCopy(localRow,...)";
1708  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isGloballyIndexed() == true && hasColMap() == false, std::runtime_error, ": local indices cannot be produced.");
1709  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(rowMap_->isNodeLocalElement(localRow) == false, std::runtime_error,
1710  ": localRow (== " << localRow << ") is not valid on this node.");
1711  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(hasRowInfo() == false, std::runtime_error, ": graph row information was deleted at fillComplete().");
1712  const RowInfo rowinfo = getRowInfo(localRow);
1713  NumIndices = rowinfo.numEntries;
1714  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC((size_t)indices.size() < NumIndices, std::runtime_error,
1715  ": specified storage (size==" << indices.size()
1716  << ") is not large enough to hold all entries for this row (NumIndices == " << NumIndices << ").");
1717  if (isLocallyIndexed()) {
1718  ArrayView<const LocalOrdinal> lview = getLocalView(rowinfo);
1719  std::copy( lview.begin(), lview.begin() + NumIndices, indices.begin());
1720  }
1721  else if (isGloballyIndexed()) {
1722  ArrayView<const GlobalOrdinal> gview = getGlobalView(rowinfo);
1723  for (size_t j=0; j < NumIndices; ++j) {
1724  indices[j] = colMap_->getLocalElement(gview[j]);
1725  }
1726  }
1727  else {
1728 #ifdef HAVE_TPETRA_DEBUG
1729  // should have fallen in one of the above
1730  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( indicesAreAllocated() == true, std::logic_error, ": Internal logic error. Please contact Tpetra team.");
1731 #endif
1732  NumIndices = 0;
1733  }
1734  return;
1735  }
1736 
1737 
1740  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1741  void CrsGraph<LocalOrdinal,GlobalOrdinal,Node,LocalMatOps>::getGlobalRowCopy(GlobalOrdinal globalRow, const ArrayView<GlobalOrdinal> &indices, size_t &NumIndices) const
1742  {
1743  // we either currently store global indices, or we have a column map with which to transcribe our local indices for the user
1744  const LocalOrdinal lrow = rowMap_->getLocalElement(globalRow);
1745  const char tfecfFuncName[] = "getGlobalRowCopy(globalRow,...)";
1747  ": globalRow (== " << globalRow << ") does not belong to this node.");
1748  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(hasRowInfo() == false, std::runtime_error, ": graph row information was deleted at fillComplete().");
1749  const RowInfo rowinfo = getRowInfo((size_t)lrow);
1750  NumIndices = rowinfo.numEntries;
1751  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC((size_t)indices.size() < NumIndices, std::runtime_error,
1752  ": specified storage (size==" << indices.size()
1753  << ") is not large enough to hold all entries for this row (NumIndices == " << NumIndices << ").");
1754  if (isLocallyIndexed()) {
1755  ArrayView<const LocalOrdinal> lview = getLocalView(rowinfo);
1756  for (size_t j=0; j < NumIndices; ++j) {
1757  indices[j] = colMap_->getGlobalElement(lview[j]);
1758  }
1759  }
1760  else if (isGloballyIndexed()) {
1761  ArrayView<const GlobalOrdinal> gview = getGlobalView(rowinfo);
1762  std::copy(gview.begin(), gview.begin() + NumIndices, indices.begin());
1763  }
1764  return;
1765  }
1766 
1767 
1770  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1772  {
1773  const char tfecfFuncName[] = "getLocalRowView()";
1774  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(isGloballyIndexed() == true, std::runtime_error, ": local indices cannot be provided.");
1775  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(hasRowInfo() == false, std::runtime_error, ": graph row information was deleted at fillComplete().");
1776  indices = null;
1777  if (rowMap_->isNodeLocalElement(localRow) == true) {
1778  const RowInfo rowinfo = getRowInfo(localRow);
1779  if (rowinfo.numEntries > 0) {
1780  indices = getLocalView(rowinfo);
1781  indices = indices(0,rowinfo.numEntries);
1782  }
1783  }
1784 #ifdef HAVE_TPETRA_DEBUG
1785  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( (size_t)indices.size() != getNumEntriesInLocalRow(localRow), std::logic_error, ": Violated stated post-conditions. Please contact Tpetra team.");
1786 #endif
1787  return;
1788  }
1789 
1790 
1793  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1795  {
1796  using Teuchos::as;
1797  const char tfecfFuncName[] = "getGlobalRowView()";
1799  isLocallyIndexed() == true, std::runtime_error,
1800  ": The graph is locally indexed, so we cannot return a view with global "
1801  "column indices. Use getGlobalRowCopy() instead.");
1802 
1804  hasRowInfo() == false, std::runtime_error,
1805  ": graph row information was deleted at fillComplete().");
1806 
1807  // isNodeGlobalElement() requires a global to local lookup anyway,
1808  // and getLocalElement() returns invalid() if the element wasn't found.
1809  const LocalOrdinal localRow = rowMap_->getLocalElement (globalRow);
1810  indices = null;
1811  if (localRow != Teuchos::OrdinalTraits<LocalOrdinal>::invalid ()) {
1812  const RowInfo rowInfo = getRowInfo (as<size_t> (localRow));
1813  if (rowInfo.numEntries > 0) {
1814  indices = (getGlobalView (rowInfo)) (0, rowInfo.numEntries);
1815  }
1816  }
1817 #ifdef HAVE_TPETRA_DEBUG
1818  using std::endl;
1820  as<size_t> (indices.size ()) != getNumEntriesInGlobalRow (globalRow),
1821  std::logic_error,
1822  ": Violated stated post-conditions:"
1823  << " indices.size () = " << indices.size () << endl
1824  << " as<size_t> (indices.size ()) = " << as<size_t> (indices.size ())
1825  << endl << " getNumEntriesInGlobalRow (globalRow = " << globalRow
1826  << ") = " << getNumEntriesInGlobalRow (globalRow) << endl
1827  << "Please report this bug to the Tpetra developers.");
1828 #endif // HAVE_TPETRA_DEBUG
1829  }
1830 
1831 
1834  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1835  void
1837  insertLocalIndices (const LocalOrdinal localRow,
1838  const ArrayView<const LocalOrdinal> &indices)
1839  {
1840  using Teuchos::ArrayView;
1841  typedef LocalOrdinal LO;
1842  const char tfecfFuncName[] = "insertLocalIndices";
1843 
1845  isFillActive() == false, std::runtime_error,
1846  ": requires that fill is active.");
1848  isGloballyIndexed() == true, std::runtime_error,
1849  ": graph indices are global; use insertGlobalIndices().");
1851  hasColMap() == false, std::runtime_error,
1852  ": cannot insert local indices without a column map.");
1854  rowMap_->isNodeLocalElement(localRow) == false, std::runtime_error,
1855  ": row does not belong to this node.");
1857  hasRowInfo() == false, std::runtime_error,
1858  ": graph row information was deleted at fillComplete().");
1859  if (! indicesAreAllocated ()) {
1860  allocateIndices (LocalIndices);
1861  }
1862 
1863 #ifdef HAVE_TPETRA_DEBUG
1864  // In a debug build, if the graph has a column Map, test whether
1865  // any of the given column indices are not in the column Map.
1866  // Keep track of the invalid column indices so we can tell the
1867  // user about them.
1868  if (hasColMap ()) {
1869  using Teuchos::Array;
1870  using Teuchos::toString;
1871  using std::endl;
1872  typedef typename ArrayView<const LO>::size_type size_type;
1873 
1874  const map_type& colMap = * (getColMap ());
1875  Array<LO> badColInds;
1876  bool allInColMap = true;
1877  for (size_type k = 0; k < indices.size (); ++k) {
1878  if (! colMap.isNodeLocalElement (indices[k])) {
1879  allInColMap = false;
1880  badColInds.push_back (indices[k]);
1881  }
1882  }
1883  if (! allInColMap) {
1884  std::ostringstream os;
1885  os << "Tpetra::CrsMatrix::insertLocalIndices: You attempted to insert "
1886  "entries in owned row " << localRow << ", at the following column "
1887  "indices: " << toString (indices) << "." << endl;
1888  os << "Of those, the following indices are not in the column Map on "
1889  "this process: " << toString (badColInds) << "." << endl << "Since "
1890  "the graph has a column Map already, it is invalid to insert entries "
1891  "at those locations.";
1892  TEUCHOS_TEST_FOR_EXCEPTION(! allInColMap, std::invalid_argument, os.str ());
1893  }
1894  }
1895 #endif // HAVE_TPETRA_DEBUG
1896 
1897  insertLocalIndicesImpl (localRow, indices);
1898 
1899 #ifdef HAVE_TPETRA_DEBUG
1900  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
1901  indicesAreAllocated() == false || isLocallyIndexed() == false,
1902  std::logic_error,
1903  ": Violated stated post-conditions. Please contact Tpetra team.");
1904 #endif
1905  }
1906 
1907 
1910  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1911  void
1913  insertLocalIndicesFiltered (const LocalOrdinal localRow,
1914  const ArrayView<const LocalOrdinal> &indices)
1915  {
1916  typedef LocalOrdinal LO;
1917  const char tfecfFuncName[] = "insertLocalIndicesFiltered";
1918 
1920  isFillActive() == false, std::runtime_error,
1921  ": requires that fill is active.");
1923  isGloballyIndexed() == true, std::runtime_error,
1924  ": graph indices are global; use insertGlobalIndices().");
1926  hasColMap() == false, std::runtime_error,
1927  ": cannot insert local indices without a column map.");
1929  rowMap_->isNodeLocalElement(localRow) == false, std::runtime_error,
1930  ": row does not belong to this node.");
1932  hasRowInfo() == false, std::runtime_error,
1933  ": graph row information was deleted at fillComplete().");
1934  if (indicesAreAllocated() == false) {
1935  allocateIndices(LocalIndices);
1936  }
1937 
1938  // If we have a column map, use it to filter the entries.
1939  if (hasColMap ()) {
1940  Array<LO> filtered_indices(indices);
1941  SLocalGlobalViews inds_view;
1942  SLocalGlobalNCViews inds_ncview;
1943  inds_ncview.linds = filtered_indices();
1944  const size_t numFilteredEntries =
1945  filterIndices<LocalIndices>(inds_ncview);
1946  inds_view.linds = filtered_indices (0, numFilteredEntries);
1947  insertLocalIndicesImpl(localRow, inds_view.linds);
1948  }
1949  else {
1950  insertLocalIndicesImpl(localRow, indices);
1951  }
1952 #ifdef HAVE_TPETRA_DEBUG
1953  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(
1954  indicesAreAllocated() == false || isLocallyIndexed() == false,
1955  std::logic_error,
1956  ": Violated stated post-conditions. Please contact Tpetra team.");
1957 #endif
1958  }
1959 
1960 
1963  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
1964  void
1966  insertGlobalIndices (const GlobalOrdinal grow,
1967  const ArrayView<const GlobalOrdinal> &indices)
1968  {
1969  typedef LocalOrdinal LO;
1970  typedef GlobalOrdinal GO;
1971  typedef typename ArrayView<const GO>::size_type size_type;
1972  const char tfecfFuncName[] = "insertGlobalIndices";
1973 
1975  isLocallyIndexed() == true, std::runtime_error,
1976  ": graph indices are local; use insertLocalIndices().");
1978  hasRowInfo() == false, std::runtime_error,
1979  ": graph row information was deleted at fillComplete().");
1980  // This can't really be satisfied for now, because if we are
1981  // fillComplete(), then we are local. In the future, this may
1982  // change. However, the rule that modification require active
1983  // fill will not change.
1985  isFillActive() == false, std::runtime_error,
1986  ": You are not allowed to call this method if fill is not active. "
1987  "If fillComplete has been called, you must first call resumeFill "
1988  "before you may insert indices.");
1989  if (! indicesAreAllocated ()) {
1990  allocateIndices (GlobalIndices);
1991  }
1992  const LO myRow = rowMap_->getLocalElement (grow);
1993  if (myRow != Teuchos::OrdinalTraits<LO>::invalid ()) {
1994 #ifdef HAVE_TPETRA_DEBUG
1995  if (hasColMap ()) {
1996  using std::endl;
1997  const map_type& colMap = * (getColMap ());
1998  // In a debug build, keep track of the nonowned ("bad") column
1999  // indices, so that we can display them in the exception
2000  // message. In a release build, just ditch the loop early if
2001  // we encounter a nonowned column index.
2002  Array<GO> badColInds;
2003  bool allInColMap = true;
2004  for (size_type k = 0; k < indices.size (); ++k) {
2005  if (! colMap.isNodeGlobalElement (indices[k])) {
2006  allInColMap = false;
2007  badColInds.push_back (indices[k]);
2008  }
2009  }
2010  if (! allInColMap) {
2011  std::ostringstream os;
2012  os << "Tpetra::CrsGraph::insertGlobalIndices: You attempted to insert "
2013  "entries in owned row " << grow << ", at the following column "
2014  "indices: " << toString (indices) << "." << endl;
2015  os << "Of those, the following indices are not in the column Map on "
2016  "this process: " << toString (badColInds) << "." << endl << "Since "
2017  "the matrix has a column Map already, it is invalid to insert "
2018  "entries at those locations.";
2019  TEUCHOS_TEST_FOR_EXCEPTION(! allInColMap, std::invalid_argument, os.str ());
2020  }
2021  }
2022 #endif // HAVE_TPETRA_DEBUG
2023  insertGlobalIndicesImpl (myRow, indices);
2024  }
2025  else { // a nonlocal row
2026  const size_type numIndices = indices.size ();
2027  // This creates the Array if it doesn't exist yet. std::map's
2028  // operator[] does a lookup each time, so it's better to pull
2029  // nonlocals_[grow] out of the loop.
2030  std::deque<GO>& nonlocalRow = nonlocals_[grow];
2031  for (size_type k = 0; k < numIndices; ++k) {
2032  nonlocalRow.push_back (indices[k]);
2033  }
2034  }
2035 #ifdef HAVE_TPETRA_DEBUG
2037  indicesAreAllocated() == false || isGloballyIndexed() == false,
2038  std::logic_error,
2039  ": Violated stated post-conditions. Please contact Tpetra team.");
2040 #endif
2041  }
2042 
2043 
2046  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2047  void
2049  insertGlobalIndicesFiltered (const GlobalOrdinal grow,
2050  const ArrayView<const GlobalOrdinal> &indices)
2051  {
2052  typedef LocalOrdinal LO;
2053  typedef GlobalOrdinal GO;
2054  const char tfecfFuncName[] = "insertGlobalIndicesFiltered";
2055 
2057  isLocallyIndexed() == true, std::runtime_error,
2058  ": graph indices are local; use insertLocalIndices().");
2060  hasRowInfo() == false, std::runtime_error,
2061  ": graph row information was deleted at fillComplete().");
2062  // This can't really be satisfied for now, because if we are
2063  // fillComplete(), then we are local. In the future, this may
2064  // change. However, the rule that modification require active
2065  // fill will not change.
2067  isFillActive() == false, std::runtime_error,
2068  ": You are not allowed to call this method if fill is not active. "
2069  "If fillComplete has been called, you must first call resumeFill "
2070  "before you may insert indices.");
2071  if (indicesAreAllocated() == false) {
2072  allocateIndices (GlobalIndices);
2073  }
2074  const LO myRow = rowMap_->getLocalElement (grow);
2075  if (myRow != Teuchos::OrdinalTraits<LO>::invalid ()) {
2076  // If we have a column map, use it to filter the entries.
2077  if (hasColMap ()) {
2078  Array<GO> filtered_indices(indices);
2079  SLocalGlobalViews inds_view;
2080  SLocalGlobalNCViews inds_ncview;
2081  inds_ncview.ginds = filtered_indices();
2082  const size_t numFilteredEntries =
2083  filterIndices<GlobalIndices> (inds_ncview);
2084  inds_view.ginds = filtered_indices (0, numFilteredEntries);
2085  insertGlobalIndicesImpl(myRow, inds_view.ginds);
2086  }
2087  else {
2088  insertGlobalIndicesImpl(myRow, indices);
2089  }
2090  }
2091  else { // a nonlocal row
2092  typedef typename ArrayView<const GO>::size_type size_type;
2093  const size_type numIndices = indices.size ();
2094  for (size_type k = 0; k < numIndices; ++k) {
2095  nonlocals_[grow].push_back (indices[k]);
2096  }
2097  }
2098 #ifdef HAVE_TPETRA_DEBUG
2100  indicesAreAllocated() == false || isGloballyIndexed() == false,
2101  std::logic_error,
2102  ": Violated stated post-conditions. Please contact Tpetra team.");
2103 #endif
2104  }
2105 
2108  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2110  {
2111  const char tfecfFuncName[] = "removeLocalIndices()";
2112  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( isFillActive() == false, std::runtime_error, ": requires that fill is active.");
2113  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( isStorageOptimized() == true, std::runtime_error, ": cannot remove indices after optimizeStorage() has been called.");
2114  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( isGloballyIndexed() == true, std::runtime_error, ": graph indices are global.");
2115  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( rowMap_->isNodeLocalElement(lrow) == false, std::runtime_error, ": row does not belong to this node.");
2116  if (indicesAreAllocated() == false) {
2117  allocateIndices(LocalIndices);
2118  }
2119  //
2120  clearGlobalConstants();
2121  //
2122  if (numRowEntries_ != null) {
2123  nodeNumEntries_ -= numRowEntries_[lrow];
2124  numRowEntries_[lrow] = 0;
2125  }
2126 #ifdef HAVE_TPETRA_DEBUG
2127  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(getNumEntriesInLocalRow(lrow) != 0 || indicesAreAllocated() == false || isLocallyIndexed() == false, std::logic_error,
2128  ": Violated stated post-conditions. Please contact Tpetra team.");
2129 #endif
2130  }
2131 
2134  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2136  {
2137  const char tfecfFuncName[] = "setAllIndices()";
2138  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( hasColMap() == false, std::runtime_error, ": requires a ColMap.");
2139  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( (size_t)rowPointers.size() != getNodeNumRows()+1, std::runtime_error, ": requires rowPointers.size() == getNodeNumRows()+1");
2140  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( lclInds1D_ != Teuchos::null || gblInds1D_ != Teuchos::null, std::runtime_error, ": cannot have 1D data structures allocated.");
2141  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( lclInds2D_ != Teuchos::null || gblInds2D_ != Teuchos::null, std::runtime_error, ": cannot have 2D data structures allocated.");
2142 
2143  indicesAreAllocated_ = true;
2144  indicesAreLocal_ = true;
2145  pftype_ = StaticProfile; // if the profile wasn't static before, it sure is now.
2146  lclInds1D_ = columnIndices;
2147  rowPtrs_ = rowPointers;
2148  nodeNumEntries_ = nodeNumAllocated_ = rowPtrs_[getNodeNumRows()];
2149  checkInternalState();
2150  }
2151 
2152  // TODO: in the future, globalAssemble() should use import/export functionality
2155  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2157  {
2158  using Teuchos::Array;
2159  using Teuchos::as;
2160  using Teuchos::Comm;
2161  using Teuchos::gatherAll;
2162  using Teuchos::ireceive;
2163  using Teuchos::isend;
2164  using Teuchos::outArg;
2165  using Teuchos::REDUCE_MAX;
2166  using Teuchos::reduceAll;
2167  using Teuchos::toString;
2168  using Teuchos::waitAll;
2169  using std::deque;
2170  using std::endl;
2171  using std::make_pair;
2172  using std::pair;
2173  typedef GlobalOrdinal GO;
2174  typedef typename std::map<GO, std::deque<GO> >::const_iterator NLITER;
2175  typedef typename Array<GO>::size_type size_type;
2176 
2177  const char tfecfFuncName[] = "globalAssemble"; // for exception macro
2178  RCP<const Comm<int> > comm = getComm();
2179 
2180  const int numImages = comm->getSize();
2181  const int myImageID = comm->getRank();
2182 #ifdef HAVE_TPETRA_DEBUG
2183  Teuchos::barrier (*comm);
2184 #endif // HAVE_TPETRA_DEBUG
2185 
2186  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( ! isFillActive(), std::runtime_error,
2187  ": requires that fill is active.");
2188  // Determine if any nodes have global entries to share
2189  {
2190  size_t MyNonlocals = nonlocals_.size(), MaxGlobalNonlocals;
2191  reduceAll (*comm, REDUCE_MAX, MyNonlocals, outArg (MaxGlobalNonlocals));
2192  if (MaxGlobalNonlocals == 0) {
2193  return; // no entries to share
2194  }
2195  }
2196 
2197  // compute a list of NLRs from nonlocals_ and use it to compute:
2198  // IdsAndRows: a vector of (id,row) pairs
2199  // NLR2Id: a map from NLR to the Id that owns it
2200  // globalNeighbors: a global graph of connectivity between images: globalNeighbors(i,j) indicates that j sends to i
2201  // sendIDs: a list of all images I send to
2202  // recvIDs: a list of all images I receive from (constructed later)
2203  Array<pair<int, GO> > IdsAndRows;
2204  std::map<GO, int> NLR2Id;
2205  Teuchos::SerialDenseMatrix<int, char> globalNeighbors;
2206  Array<int> sendIDs, recvIDs;
2207  {
2208  // nonlocals_ contains the entries we are holding for all non-local rows
2209  // we want a list of the rows for which we have data
2210  Array<GO> NLRs;
2211  std::set<GO> setOfRows;
2212  for (NLITER iter = nonlocals_.begin(); iter != nonlocals_.end(); ++iter) {
2213  setOfRows.insert(iter->first);
2214  }
2215  // copy the elements in the set into an Array
2216  NLRs.resize(setOfRows.size());
2217  std::copy(setOfRows.begin(), setOfRows.end(), NLRs.begin());
2218 
2219  // get a list of ImageIDs for the non-local rows (NLRs)
2220  Array<int> NLRIds(NLRs.size());
2221  {
2222  LookupStatus stat = rowMap_->getRemoteIndexList(NLRs(),NLRIds());
2223  int lclerror = ( stat == IDNotPresent ? 1 : 0 );
2224  int gblerror;
2225  reduceAll<int, int> (*comm, REDUCE_MAX, lclerror, outArg (gblerror));
2226  if (gblerror != 0) {
2227  const int myRank = comm->getRank ();
2228  std::ostringstream os;
2229  os << "On one or more processes in the communicator, "
2230  << "there were insertions into rows of the graph that do not "
2231  << "exist in the row Map on any process in the communicator."
2232  << endl << "This process " << myRank << " is "
2233  << (lclerror == 0 ? "not " : "") << "one of those offending "
2234  << "processes." << endl;
2235  if (lclerror != 0) {
2236  // If NLRIds[k] is -1, then NLRs[k] is a row index not in
2237  // the row Map. Collect this list of invalid row indices
2238  // for display in the exception message.
2239  Array<GO> invalidNonlocalRows;
2240  for (size_type k = 0; k < NLRs.size (); ++k) {
2241  if (NLRIds[k] == -1) {
2242  invalidNonlocalRows.push_back (NLRs[k]);
2243  }
2244  }
2245  const size_type numInvalid = invalidNonlocalRows.size ();
2246  os << "On this process, " << numInvalid << " nonlocal row"
2247  << (numInvalid != 1 ? "s " : " ") << " were inserted that are "
2248  << "not in the row Map on any process." << endl;
2249  // Don't print _too_ many nonlocal rows.
2250  if (numInvalid <= 100) {
2251  os << "Offending row indices: "
2252  << toString (invalidNonlocalRows ()) << endl;
2253  }
2254  }
2256  gblerror != 0, std::runtime_error,
2257  ": nonlocal entries correspond to invalid rows."
2258  << endl << os.str ());
2259  }
2260  }
2261 
2262  // build up a list of neighbors, as well as a map between NLRs and Ids
2263  // localNeighbors[i] != 0 iff I have data to send to image i
2264  // put NLRs,Ids into an array of pairs
2265  IdsAndRows.reserve(NLRs.size());
2266  Array<char> localNeighbors(numImages, 0);
2267  typename Array<GO>::const_iterator nlr;
2268  typename Array<int>::const_iterator id;
2269  for (nlr = NLRs.begin(), id = NLRIds.begin();
2270  nlr != NLRs.end(); ++nlr, ++id) {
2271  NLR2Id[*nlr] = *id;
2272  localNeighbors[*id] = 1;
2273  // IdsAndRows.push_back(make_pair<int,GlobalOrdinal>(*id,*nlr));
2274  IdsAndRows.push_back(make_pair(*id,*nlr));
2275  }
2276  for (int j=0; j<numImages; ++j) {
2277  if (localNeighbors[j]) {
2278  sendIDs.push_back(j);
2279  }
2280  }
2281  // sort IdsAndRows, by Ids first, then rows
2282  std::sort(IdsAndRows.begin(),IdsAndRows.end());
2283  // gather from other nodes to form the full graph
2284  globalNeighbors.shapeUninitialized(numImages,numImages);
2285  gatherAll (*getComm(), numImages, localNeighbors.getRawPtr(),
2286  numImages * numImages, globalNeighbors.values());
2287  // globalNeighbors at this point contains (on all images) the
2288  // connectivity between the images.
2289  // globalNeighbors(i,j) != 0 means that j sends to i/that i receives from j
2290  }
2291 
2293  // FIGURE OUT WHO IS SENDING TO WHOM AND HOW MUCH
2294  // DO THIS IN THE PROCESS OF PACKING ALL OUTGOING DATA ACCORDING TO DESTINATION ID
2296 
2297  // loop over all columns to know from which images I can expect to receive something
2298  for (int j=0; j<numImages; ++j) {
2299  if (globalNeighbors(myImageID,j)) {
2300  recvIDs.push_back(j);
2301  }
2302  }
2303  const size_t numRecvs = recvIDs.size();
2304 
2305  // we know how many we're sending to already
2306  // form a contiguous list of all data to be sent
2307  // track the number of entries for each ID
2308  Array<pair<GO, GO> > IJSendBuffer;
2309  Array<size_t> sendSizes(sendIDs.size(), 0);
2310  size_t numSends = 0;
2311  for (typename Array<pair<int, GO> >::const_iterator IdAndRow = IdsAndRows.begin();
2312  IdAndRow != IdsAndRows.end(); ++IdAndRow) {
2313  int id = IdAndRow->first;
2314  GO row = IdAndRow->second;
2315  // have we advanced to a new send?
2316  if (sendIDs[numSends] != id) {
2317  numSends++;
2318  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(sendIDs[numSends] != id,
2319  std::logic_error, ": internal logic error. Contact Tpetra team.");
2320  }
2321  // copy data for row into contiguous storage
2322  for (typename deque<GO>::const_iterator j = nonlocals_[row].begin(); j != nonlocals_[row].end(); ++j)
2323  {
2324  IJSendBuffer.push_back( pair<GlobalOrdinal,GlobalOrdinal>(row,*j) );
2325  sendSizes[numSends]++;
2326  }
2327  }
2328  if (IdsAndRows.size() > 0) {
2329  numSends++; // one last increment, to make it a count instead of an index
2330  }
2331  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(as<typename Array<int>::size_type>(numSends) != sendIDs.size(), std::logic_error, ": internal logic error. Contact Tpetra team.");
2332 
2333  // don't need this data anymore
2334  nonlocals_.clear();
2335 
2337  // TRANSMIT SIZE INFO BETWEEN SENDERS AND RECEIVERS
2339 
2340  // Array of pending nonblocking communication requests. It's OK
2341  // to mix nonblocking send and receive requests in the same
2342  // waitAll() call.
2344 
2345  // perform non-blocking sends: send sizes to our recipients
2346  for (size_t s = 0; s < numSends ; ++s) {
2347  // We're using a nonowning RCP because all communication
2348  // will be local to this method and the scope of our data
2349  requests.push_back (isend<int, size_t> (*comm,
2350  rcp (&sendSizes[s], false),
2351  sendIDs[s]));
2352  }
2353  // perform non-blocking receives: receive sizes from our senders
2354  Array<size_t> recvSizes (numRecvs);
2355  for (size_t r = 0; r < numRecvs; ++r) {
2356  // We're using a nonowning RCP because all communication
2357  // will be local to this method and the scope of our data
2358  requests.push_back (ireceive (*comm, rcp (&recvSizes[r], false), recvIDs[r]));
2359  }
2360  // Wait on all the nonblocking sends and receives.
2361  if (! requests.empty()) {
2362  waitAll (*comm, requests());
2363  }
2364 #ifdef HAVE_TPETRA_DEBUG
2365  Teuchos::barrier (*comm);
2366 #endif // HAVE_TPETRA_DEBUG
2367 
2368  // This doesn't necessarily deallocate the array.
2369  requests.resize (0);
2370 
2372  // NOW SEND/RECEIVE ALL ROW DATA
2374  // from the size info, build the ArrayViews into IJSendBuffer
2375  Array<ArrayView<pair<GO,GO> > > sendBuffers(numSends,null);
2376  {
2377  size_t cur = 0;
2378  for (size_t s=0; s<numSends; ++s) {
2379  sendBuffers[s] = IJSendBuffer(cur,sendSizes[s]);
2380  cur += sendSizes[s];
2381  }
2382  }
2383  // perform non-blocking sends
2384  for (size_t s=0; s < numSends ; ++s)
2385  {
2386  // We're using a nonowning RCP because all communication
2387  // will be local to this method and the scope of our data
2388  ArrayRCP<pair<GO,GO> > tmpSendBuf =
2389  arcp (sendBuffers[s].getRawPtr(), 0, sendBuffers[s].size(), false);
2390  requests.push_back (isend<int, pair<GO,GO> > (*comm, tmpSendBuf, sendIDs[s]));
2391  }
2392  // calculate amount of storage needed for receives
2393  // setup pointers for the receives as well
2394  size_t totalRecvSize = std::accumulate (recvSizes.begin(), recvSizes.end(), 0);
2395  Array<pair<GO,GO> > IJRecvBuffer (totalRecvSize);
2396  // from the size info, build the ArrayViews into IJRecvBuffer
2397  Array<ArrayView<pair<GO,GO> > > recvBuffers (numRecvs, null);
2398  {
2399  size_t cur = 0;
2400  for (size_t r=0; r<numRecvs; ++r) {
2401  recvBuffers[r] = IJRecvBuffer(cur,recvSizes[r]);
2402  cur += recvSizes[r];
2403  }
2404  }
2405  // perform non-blocking recvs
2406  for (size_t r = 0; r < numRecvs; ++r) {
2407  // We're using a nonowning RCP because all communication
2408  // will be local to this method and the scope of our data
2409  ArrayRCP<pair<GO,GO> > tmpRecvBuf =
2410  arcp (recvBuffers[r].getRawPtr(), 0, recvBuffers[r].size(), false);
2411  requests.push_back (ireceive (*comm, tmpRecvBuf, recvIDs[r]));
2412  }
2413  // perform waits
2414  if (! requests.empty()) {
2415  waitAll (*comm, requests());
2416  }
2417 #ifdef HAVE_TPETRA_DEBUG
2418  Teuchos::barrier (*comm);
2419 #endif // HAVE_TPETRA_DEBUG
2420 
2422  // NOW PROCESS THE RECEIVED ROW DATA
2424  // TODO: instead of adding one entry at a time, add one row at a time.
2425  // this requires resorting; they arrived sorted by sending node,
2426  // so that entries could be non-contiguous if we received
2427  // multiple entries for a particular row from different processors.
2428  // it also requires restoring the data, which may make it not worth the trouble.
2429  for (typename Array<pair<GO,GO> >::const_iterator ij = IJRecvBuffer.begin();
2430  ij != IJRecvBuffer.end(); ++ij)
2431  {
2432  insertGlobalIndicesFiltered (ij->first, tuple<GO> (ij->second));
2433  }
2434  checkInternalState();
2435  }
2436 
2437 
2440  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2441  void
2444  {
2445  const char tfecfFuncName[] = "resumeFill";
2446  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(! hasRowInfo(), std::runtime_error,
2447  ": Sorry, you cannot resume fill of the CrsGraph, since the graph's row "
2448  "information was deleted in fillComplete().");
2449 
2450 #ifdef HAVE_TPETRA_DEBUG
2451  Teuchos::barrier( *rowMap_->getComm() );
2452 #endif // HAVE_TPETRA_DEBUG
2453  clearGlobalConstants();
2454  lclGraph_ = null;
2455  if (params != null) this->setParameterList (params);
2456  lowerTriangular_ = false;
2457  upperTriangular_ = false;
2458  // either still sorted/merged or initially sorted/merged
2459  indicesAreSorted_ = true;
2460  noRedundancies_ = true;
2461  fillComplete_ = false;
2462 #ifdef HAVE_TPETRA_DEBUG
2464  ! isFillActive() || isFillComplete(), std::logic_error,
2465  "::resumeFill(): At end of method, either fill is not active or fill is "
2466  "complete. This violates stated post-conditions. Please report this bug "
2467  "to the Tpetra developers.");
2468 #endif // HAVE_TPETRA_DEBUG
2469  }
2470 
2471 
2474  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2476  {
2477  fillComplete(rowMap_,rowMap_,params);
2478  }
2479 
2480 
2483  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2484  void
2487  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > &rangeMap,
2488  const RCP<ParameterList> &params)
2489  {
2490 #ifdef HAVE_TPETRA_DEBUG
2491  rowMap_->getComm ()->barrier ();
2492 #endif // HAVE_TPETRA_DEBUG
2493  const char tfecfFuncName[] = "fillComplete()";
2495  std::runtime_error, ": Graph fill state must be active (isFillActive() "
2496  "must be true) before calling fillComplete().");
2497 
2498  const int numProcs = getComm ()->getSize ();
2499 
2500  // allocate if unallocated
2501  if (! indicesAreAllocated()) {
2502  // allocate global, in case we do not have a column map
2503  allocateIndices( GlobalIndices );
2504  }
2505 
2506  // If true, the caller promises that no process did nonlocal
2507  // changes since the last call to fillComplete.
2508  bool assertNoNonlocalInserts = false;
2509  if (! params.is_null ()) {
2510  assertNoNonlocalInserts =
2511  params->get<bool> ("No Nonlocal Changes", assertNoNonlocalInserts);
2512  }
2513  // We also don't need to do global assembly if there is only one
2514  // process in the communicator.
2515  const bool mayNeedGlobalAssemble = ! assertNoNonlocalInserts && numProcs > 1;
2516  if (mayNeedGlobalAssemble) {
2517  // This first checks if we need to do global assembly.
2518  // The check costs a single all-reduce.
2519  globalAssemble();
2520  }
2521  else {
2523  numProcs > 1 && nonlocals_.size() > 0, std::runtime_error,
2524  ":" << std::endl << "The graph's communicator contains only one "
2525  "process, but there are nonlocal entries. " << std::endl <<
2526  "This probably means that invalid entries were added to the graph.");
2527  }
2528  // set domain/range map: may clear the import/export objects
2529  setDomainRangeMaps(domainMap,rangeMap);
2530  // make column map
2531  if (! hasColMap()) {
2532  makeColMap();
2533  }
2534  if (isGloballyIndexed()) {
2535  makeIndicesLocal();
2536  }
2537  if (! isSorted()) {
2538  sortAllIndices();
2539  }
2540  if (! isMerged()) {
2541  mergeAllIndices();
2542  }
2543  makeImportExport(); // Make Import and Export objects
2544  computeGlobalConstants();
2545  // fill local objects
2546  fillLocalGraph(params);
2547  //
2548  fillComplete_ = true;
2549 #ifdef HAVE_TPETRA_DEBUG
2550  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( isFillActive() == true || isFillComplete() == false, std::logic_error, ": Violated stated post-conditions. Please contact Tpetra team.");
2551 #endif
2552  //
2553  checkInternalState();
2554  }
2555 
2556 
2559  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2561  const RCP<const Map<LocalOrdinal,GlobalOrdinal,Node> > & rangeMap,
2562  const RCP<const Import<LocalOrdinal,GlobalOrdinal,Node> > &importer,
2563  const RCP<const Export<LocalOrdinal,GlobalOrdinal,Node> > &exporter,
2564  const RCP<ParameterList> &params)
2565  {
2566 #ifdef HAVE_TPETRA_DEBUG
2567  rowMap_->getComm ()->barrier ();
2568 #endif // HAVE_TPETRA_DEBUG
2569  const char tfecfFuncName[] = "expertStaticFillComplete()";
2571  std::runtime_error, ": fillComplete cannot have already been called and a ColMap is required.");
2572 
2573  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( getNodeNumRows() > 0 && rowPtrs_==Teuchos::null,
2574  std::runtime_error, ": a matrix will getNodeNumRows()>0 requires rowptr to be set.");
2575 
2576  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( domainMap == Teuchos::null || rangeMap == Teuchos::null,
2577  std::runtime_error, ": requires a non-null domainMap & rangeMap.");
2578 
2580  std::runtime_error, ": requires StaticProfile.");
2581 
2582  // Note: We don't need to do the following things which are normally done in fillComplete:
2583  // allocateIndices, globalAssemble, makeColMap, makeIndicesLocal, sortAllIndices, mergeAllIndices
2584 
2585  // Note: Need to do this so computeGlobalConstants & fillLocalGraph work
2586  nodeNumEntries_ = nodeNumAllocated_ = rowPtrs_[getNodeNumRows()];
2587 
2588  // Constants from allocateIndices
2589  numAllocForAllRows_ = 0;
2590  numAllocPerRow_ = null;
2591  indicesAreAllocated_ = true;
2592 
2593  // Constants from makeIndicesLocal
2594  indicesAreLocal_ = true;
2595  indicesAreGlobal_ = false;
2596 
2597  // set domain/range map: may clear the import/export objects
2598  setDomainRangeMaps(domainMap,rangeMap);
2599 
2600  // Presume the user sorted and merged the arrays first
2601  indicesAreSorted_ = true;
2602  noRedundancies_ = true;
2603 
2604  // makeImportExport won't create a new importer/exporter if I set one here first.
2605  importer_=Teuchos::null;
2606  exporter_=Teuchos::null;
2607  if(importer != Teuchos::null) {
2608  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(!importer->getSourceMap()->isSameAs(*getDomainMap()) || !importer->getTargetMap()->isSameAs(*getColMap()),
2609  std::invalid_argument,": importer does not match matrix maps.");
2610  importer_ = importer;
2611 
2612  }
2613  if(exporter != Teuchos::null) {
2614  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(!exporter->getSourceMap()->isSameAs(*getRowMap()) || !exporter->getTargetMap()->isSameAs(*getRangeMap()),
2615  std::invalid_argument,": exporter does not match matrix maps.");
2616  exporter_ = exporter;
2617  }
2618  makeImportExport();
2619 
2620  // Compute the constants
2621  computeGlobalConstants();
2622 
2623  // Since we have a StaticProfile, fillLocalGraph will do the right thing...
2624  fillLocalGraph(params);
2625  fillComplete_ = true;
2626 
2627 #ifdef HAVE_TPETRA_DEBUG
2628  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( isFillActive() == true || isFillComplete() == false, std::logic_error, ": Violated stated post-conditions. Please contact Tpetra team.");
2629 #endif
2630  checkInternalState();
2631  }
2632 
2633 
2634 
2637  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2639  {
2640  const size_t numRows = getNodeNumRows();
2641  ArrayRCP<size_t> ptrs;
2643  bool requestOptimizedStorage = true;
2644  if (params != null && params->get("Optimize Storage",true) == false) requestOptimizedStorage = false;
2645  if (getProfileType() == DynamicProfile) {
2646  // 2d -> 1d packed
2647  ptrs = LocalMatOps::allocRowPtrs( getRowMap()->getNode(), numRowEntries_() );
2648  inds = LocalMatOps::template allocStorage<LocalOrdinal>( getRowMap()->getNode(), ptrs() );
2649  for (size_t row=0; row < numRows; ++row) {
2650  const size_t numentrs = numRowEntries_[row];
2651  std::copy( lclInds2D_[row].begin(), lclInds2D_[row].begin()+numentrs, inds+ptrs[row] );
2652  }
2653  }
2654  else if (getProfileType() == StaticProfile) {
2655  // 1d non-packed -> 1d packed
2656  if (nodeNumEntries_ != nodeNumAllocated_) {
2657  ptrs = LocalMatOps::allocRowPtrs( getRowMap()->getNode(), numRowEntries_() );
2658  inds = LocalMatOps::template allocStorage<LocalOrdinal>( getRowMap()->getNode(), ptrs() );
2659  for (size_t row=0; row < numRows; ++row) {
2660  const size_t numentrs = numRowEntries_[row];
2661  std::copy( lclInds1D_+rowPtrs_[row], lclInds1D_+rowPtrs_[row]+numentrs, inds+ptrs[row] );
2662  }
2663  }
2664  else {
2665  inds = lclInds1D_;
2666  ptrs = rowPtrs_;
2667  }
2668  }
2669  // can we ditch the old allocations for the packed one?
2670  if ( requestOptimizedStorage ) {
2671  lclInds2D_ = null;
2672  numRowEntries_ = null;
2673  // keep the new stuff
2674  lclInds1D_ = inds;
2675  rowPtrs_ = ptrs;
2676  nodeNumAllocated_ = nodeNumEntries_;
2678  }
2679  // build the local graph, hand over the indices
2680  RCP<ParameterList> lclparams;
2681  if (params == null) lclparams = parameterList();
2682  else lclparams = sublist(params,"Local Graph");
2683  lclGraph_ = rcp( new local_graph_type( getRowMap()->getNodeNumElements(), getColMap()->getNodeNumElements(), getRowMap()->getNode(), lclparams ) );
2684  lclGraph_->setStructure(ptrs,inds);
2685  ptrs = null;
2686  inds = null;
2687  // finalize local graph
2690  if (isUpperTriangular()) uplo = Teuchos::UPPER_TRI;
2691  else if (isLowerTriangular()) uplo = Teuchos::LOWER_TRI;
2692  LocalMatOps::finalizeGraph(uplo,diag,*lclGraph_,params);
2693  }
2694 
2695 
2698  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2700  {
2701  const char tfecfFuncName[] = "replaceDomainMapAndImporter()";
2702 
2703  if( (newImporter==Teuchos::null && colMap_!=Teuchos::null && colMap_->isSameAs(*newDomainMap)) ||
2704  (newImporter!=Teuchos::null && colMap_!=Teuchos::null && colMap_->isSameAs(*newImporter->getTargetMap()) && newDomainMap->isSameAs(*newImporter->getSourceMap()))) {
2705  domainMap_ = newDomainMap;
2706  importer_ = rcp_const_cast<Tpetra::Import<LocalOrdinal,GlobalOrdinal,Node> >(newImporter);
2707 
2708  }
2709  else {
2710  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC( false, std::runtime_error, " requires matching maps and non-static graph.");
2711  }
2712  }
2713 
2714 
2717  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2720  {
2721  return lclGraph_;
2722  }
2723 
2724 
2727  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2730  {
2731  return lclGraph_;
2732  }
2733 
2734 
2737  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2739  {
2740  using Teuchos::as;
2741  using Teuchos::outArg;
2742  using Teuchos::reduceAll;
2743  typedef LocalOrdinal LO;
2744  typedef GlobalOrdinal GO;
2745  typedef global_size_t GST;
2746 
2747 #ifdef HAVE_TPETRA_DEBUG
2748  TEUCHOS_TEST_FOR_EXCEPTION(! hasColMap(), std::logic_error, "Tpetra::"
2749  "CrsGraph::computeGlobalConstants: At this point, the graph should have "
2750  "a column Map, but it does not. Please report this bug to the Tpetra "
2751  "developers.");
2752 #endif // HAVE_TPETRA_DEBUG
2753 
2754  // If necessary, (re)compute the local constants: nodeNumDiags_,
2755  // lowerTriangular_, upperTriangular_, and nodeMaxNumRowEntries_.
2756  if (! haveLocalConstants_) {
2757  // We have actually already computed nodeNumEntries_.
2758  // nodeNumEntries_ gets updated by methods that insert or remove
2759  // indices (including setAllIndices and
2760  // expertStaticFillComplete). Before fillComplete, its count
2761  // may include duplicate column indices in the same row.
2762  // However, mergeRowIndices and mergeRowIndicesAndValues both
2763  // subtract off merged indices in each row from the total count.
2764  // Thus, nodeNumEntries_ _should_ be accurate at this point,
2765  // meaning that we don't have to re-count it here.
2766 
2767  // Reset local properties
2768  upperTriangular_ = true;
2769  lowerTriangular_ = true;
2770  nodeMaxNumRowEntries_ = 0;
2771  nodeNumDiags_ = 0;
2772 
2773  // At this point, we know that we have both a row Map and a column Map.
2774  const Map<LO,GO,Node>& rowMap = *rowMap_;
2775  const Map<LO,GO,Node>& colMap = *colMap_;
2776 
2777  // Go through all the entries of the graph. Count the number of
2778  // diagonal elements we encounter, and figure out whether the
2779  // graph is lower or upper triangular. Diagonal elements are
2780  // determined using global indices, with respect to the whole
2781  // graph. However, lower or upper triangularity is a local
2782  // property, and is determined using local indices.
2783  //
2784  // At this point, indices have already been sorted in each row.
2785  // That makes finding out whether the graph is lower / upper
2786  // triangular easier.
2787  if (indicesAreAllocated () && nodeNumAllocated_ > 0) {
2788  const size_t numLocalRows = getNodeNumRows ();
2789  for (size_t localRow = 0; localRow < numLocalRows; ++localRow) {
2790  const GO globalRow = rowMap.getGlobalElement (localRow);
2791  // Find the local (column) index for the diagonal element.
2792  const LO rlcid = colMap.getLocalElement (globalRow);
2793  RowInfo rowInfo = getRowInfo (localRow);
2794  ArrayView<const LO> rview = getLocalView (rowInfo);
2795  typename ArrayView<const LO>::iterator beg, end, cur;
2796  beg = rview.begin();
2797  end = beg + rowInfo.numEntries;
2798  if (beg != end) {
2799  for (cur = beg; cur != end; ++cur) {
2800  // is this the diagonal?
2801  if (rlcid == *cur) ++nodeNumDiags_;
2802  }
2803  // Local column indices are sorted in each row. That means
2804  // the smallest column index in this row (on this process)
2805  // is *beg, and the largest column index in this row (on
2806  // this process) is *(end - 1). We know that end - 1 is
2807  // valid because beg != end.
2808  const size_t smallestCol = as<size_t> (*beg);
2809  const size_t largestCol = as<size_t> (*(end - 1));
2810 
2811  if (smallestCol < localRow) {
2812  upperTriangular_ = false;
2813  }
2814  if (localRow < largestCol) {
2815  lowerTriangular_ = false;
2816  }
2817  }
2818  // Update the max number of entries over all rows.
2819  nodeMaxNumRowEntries_ = std::max (nodeMaxNumRowEntries_, rowInfo.numEntries);
2820  }
2821  }
2822  haveLocalConstants_ = true;
2823  } // if my process doesn't have local constants
2824 
2825  // Compute global constants from local constants. Processes that
2826  // already have local constants still participate in the
2827  // all-reduces, using their previously computed values.
2828  if (haveGlobalConstants_ == false) {
2829  // Promote all the nodeNum* and nodeMaxNum* quantities from
2830  // size_t to global_size_t, when doing the all-reduces for
2831  // globalNum* / globalMaxNum* results.
2832  //
2833  // FIXME (mfh 07 May 2013) Unfortunately, we either have to do
2834  // this in two all-reduces (one for the sum and the other for
2835  // the max), or use a custom MPI_Op that combines the sum and
2836  // the max. The latter might even be slower than two
2837  // all-reduces on modern network hardware. It would also be a
2838  // good idea to use nonblocking all-reduces (MPI 3), so that we
2839  // don't have to wait around for the first one to finish before
2840  // starting the second one.
2841  GST lcl[2], gbl[2];
2842  lcl[0] = as<GST> (nodeNumEntries_);
2843  lcl[1] = as<GST> (nodeNumDiags_);
2844  reduceAll<int,GST> (*getComm (), Teuchos::REDUCE_SUM,
2845  2, lcl, gbl);
2846  globalNumEntries_ = gbl[0];
2847  globalNumDiags_ = gbl[1];
2848  reduceAll<int,GST> (*getComm (), Teuchos::REDUCE_MAX,
2849  as<GST> (nodeMaxNumRowEntries_),
2850  outArg (globalMaxNumRowEntries_));
2851  haveGlobalConstants_ = true;
2852  }
2853  }
2854 
2855 
2858  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2860  {
2861  typedef LocalOrdinal LO;
2862  typedef GlobalOrdinal GO;
2863 
2864  // All nodes must be in the same index state.
2865  // Update index state by checking isLocallyIndexed/Global on all nodes
2867  const char tfecfFuncName[] = "makeIndicesLocal()";
2869  isLocallyIndexed() && isGloballyIndexed(), std::logic_error,
2870  ": inconsistent index state. Indices must be either local on all "
2871  "processes, or global on all processes.");
2872  // If user has not prescribed a column Map, create one from indices.
2873  // If we already have a column Map, this call won't do anything.
2874  makeColMap ();
2875  // Transform indices to local index space
2876  const size_t nlrs = getNodeNumRows();
2877  if (isGloballyIndexed() && nlrs > 0) {
2878  // allocate data for local indices
2879  if (getProfileType() == StaticProfile) {
2880  // If GO and LO are the same size, we can reuse the existing
2881  // array of 1-D index storage to convert column indices from
2882  // GO to LO. Otherwise, we'll just allocate a new buffer.
2883  if (nodeNumAllocated_ && sizeof (LO) == sizeof (GO)) {
2884  lclInds1D_ = arcp_reinterpret_cast<LO> (gblInds1D_).persistingView (0, nodeNumAllocated_);
2885  }
2886  else {
2887  lclInds1D_ = LocalMatOps::template allocStorage<LO> (getRowMap ()->getNode (), rowPtrs_ ());
2888  }
2889  for (size_t r = 0; r < getNodeNumRows (); ++r) {
2890  const size_t offset = rowPtrs_[r];
2891  const size_t numentry = numRowEntries_[r];
2892  for (size_t j = 0; j < numentry; ++j) {
2893  const GO gid = gblInds1D_[offset + j];
2894  const LO lid = colMap_->getLocalElement (gid);
2895  lclInds1D_[offset + j] = lid;
2896 #ifdef HAVE_TPETRA_DEBUG
2899  std::logic_error,
2900  ": In local row r=" << r << ", global column " << gid << " is "
2901  "not in the column Map. This should never happen. Please "
2902  "report this bug to the Tpetra developers.");
2903 #endif // HAVE_TPETRA_DEBUG
2904  }
2905  }
2906  // We've converted column indices from global to local, so we
2907  // can deallocate the global column indices (which we know are
2908  // in 1-D storage, because the graph has static profile).
2909  gblInds1D_ = null;
2910  }
2911  else { // the graph has dynamic profile (2-D index storage)
2912  lclInds2D_ = arcp<Array<LO> > (nlrs);
2913  for (size_t r = 0; r < getNodeNumRows (); ++r) {
2914  if (! gblInds2D_[r].empty ()) {
2915  const GO* const ginds = gblInds2D_[r].getRawPtr ();
2916  const size_t rna = gblInds2D_[r].size ();
2917  const size_t numentry = numRowEntries_[r];
2918  lclInds2D_[r].resize (rna);
2919  LO* const linds = lclInds2D_[r].getRawPtr ();
2920  for (size_t j = 0; j < numentry; ++j) {
2921  GO gid = ginds[j];
2922  LO lid = colMap_->getLocalElement (gid);
2923  linds[j] = lid;
2924 #ifdef HAVE_TPETRA_DEBUG
2927  std::logic_error,
2928  ": Global column ginds[j=" << j << "]=" << ginds[j]
2929  << " of local row r=" << r << " is not in the column Map. "
2930  "This should never happen. Please report this bug to the "
2931  "Tpetra developers.");
2932 #endif // HAVE_TPETRA_DEBUG
2933  }
2934  }
2935  }
2936  gblInds2D_ = null;
2937  }
2938  }
2939  indicesAreLocal_ = true;
2940  indicesAreGlobal_ = false;
2941  checkInternalState();
2942  }
2943 
2944 
2947  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
2949  {
2950  // FIXME (mfh 03 Mar 2013) It's not clear to me that we need to do
2951  // an all-reduce.
2952  //
2953  // This method is _only_ called in makeIndicesLocal() and
2954  // makeColMap(). makeIndicesLocal() calls makeColMap(), which is
2955  // collective, so both methods must be called collectively.
2956  //
2957  // There are only two methods that modify indicesAreLocal_:
2958  // allocateIndices(), and makeIndicesLocal(). makeIndicesLocal()
2959  // always has the eponymous effect. It must be called
2960  // collectively, since it calls makeColMap(), which must be called
2961  // collectively.
2962  //
2963  // allocateIndices(), on the other hand, could perhaps be called
2964  // with lg=LocalIndices on one process, but with lg=GlobalIndices
2965  // on another. However, I will argue that CrsGraph cannot reach
2966  // this state if used correctly.
2967  //
2968  // allocateIndices() specifically forbids an lg argument which
2969  // does not correspond to the state of the graph. The graph
2970  // starts out locally indexed if its constructor was given a
2971  // column Map; otherwise, it starts out neither locally nor
2972  // globally indexed, and only gains one of these identities on the
2973  // calling process ("locally") once the user inserts an entry.
2974  // (This is the classic Epetra way to tell if a graph is empty.)
2975  // It is an error to call different constructors for the same
2976  // CrsGraph instance on different processes. Thus, the initial
2977  // local-or-global state before any insertions on any processes
2978  // must be the same.
2979  //
2980  // Before inserting any entries, indicesAreLocal_ and
2981  // indicesAreGlobal_ are both locally false. They may be modified
2982  // locally by calls to insertGlobalIndices() or
2983  // insertLocalIndices(). These two methods only call
2984  // allocateIndices() if no insertion method has yet been called on
2985  // the graph. Furthermore, these methods only allow indices to
2986  // have the state matching their name. insertLocalIndices()
2987  // explicitly requires that the graph has a column Map.
2988  // insertGlobalIndices() requires that the graph not be locally
2989  // indexed, which currently means that the graph was not
2990  // constructed with a column Map and that fillComplete() (which is
2991  // collective) has not yet been called.
2992  //
2993  // Thus, before calling fillComplete() for the first time, it is
2994  // possible that on some (but not necessarily all) processes,
2995  // indicesAreLocal_ == false && indicesAreGlobal_ == false.
2996  // However, on all processes p on which any one of these Booleans
2997  // are true, the two Booleans must have the same values, for the
2998  // reasons discussed in the previous paragraph.
2999  //
3000  // fillComplete() makes the column Map first (if it doesn't
3001  // already exist) before making indices local, so there is a point
3002  // in fillComplete() at which the graph has a column Map and is
3003  // globally indexed. However, makeIndicesLocal() fixes this state
3004  // right away. This intermediate state would never be exposed to
3005  // users. fillComplete() must be called collectively.
3006  //
3007  // resumeFill() does _not_ currently change the global vs. local
3008  // indices state of the graph. If we were to give users the
3009  // option to do this in the future (e.g., they want to insert
3010  // column indices not in the column Map, so that we would have to
3011  // convert all the column indices back to global first and get rid
3012  // of the existing column Map), then that would be a collective
3013  // decision in any case.
3014  //
3015  // The only part of makeIndicesLocal() that is not a local
3016  // operation is the call to makeColMap(). Everything else is
3017  // local. Thus, it suffices in that method to check the local
3018  // state. Furthermore, makeIndicesLocal() always makes indices
3019  // local, so there is no need to check at the end of the method.
3020  // One would only call makeColMap() if the graph does not have a
3021  // column Map. In that case, the graph must be globally indexed
3022  // anyway.
3023  int myIndices[2] = {0,0};
3024  if (indicesAreLocal_) myIndices[0] = 1;
3025  if (indicesAreGlobal_) myIndices[1] = 1;
3026  int allIndices[2];
3027  Teuchos::reduceAll<int, int> (* (getComm()), Teuchos::REDUCE_MAX,
3028  2, myIndices, allIndices);
3029  // If indices are (local, global) on one process, they should be
3030  // (local, global) on all processes.
3031  indicesAreLocal_ = (allIndices[0]==1);
3032  indicesAreGlobal_ = (allIndices[1]==1);
3033  }
3034 
3035 
3038  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3040  {
3041  TEUCHOS_TEST_FOR_EXCEPT(isGloballyIndexed()==true); // this should be called only after makeIndicesLocal()
3042  if (isSorted() == false) {
3043  for (size_t row=0; row < getNodeNumRows(); ++row) {
3044  RowInfo rowInfo = getRowInfo(row);
3045  sortRowIndices(rowInfo);
3046  }
3047  }
3048  // we just sorted every row
3049  indicesAreSorted_ = true;
3050  }
3051 
3052 
3055  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3057  {
3058  using std::endl;
3059  using Teuchos::REDUCE_MAX;
3060  using Teuchos::reduceAll;
3061  typedef LocalOrdinal LO;
3062  typedef GlobalOrdinal GO;
3063  const char tfecfFuncName[] = "makeColMap";
3064 
3065  if (hasColMap ()) { // The graph already has a column Map.
3066  // FIXME (mfh 26 Feb 2013): This currently prevents structure
3067  // changes that affect the column Map.
3068  return;
3069  }
3070 
3071  computeIndexState ();
3073  isLocallyIndexed (), std::runtime_error,
3074  ": The graph is locally indexed. Calling makeColMap() to make the "
3075  "column Map requires that the graph be globally indexed.");
3076 
3077  // After the calling process is done going through all of the rows
3078  // it owns, myColumns will contain the list of indices owned by
3079  // this process in the column Map.
3080  Array<GO> myColumns;
3081 
3082  // If we reach this point, we don't have a column Map yet, so the
3083  // graph can't be locally indexed. Thus, isGloballyIndexed() ==
3084  // false means that the graph is empty on this process, so
3085  // myColumns will be left empty.
3086  if (isGloballyIndexed ()) {
3087  // Go through all the rows, finding the populated column indices.
3088  //
3089  // Our final list of indices for the column Map constructor will
3090  // have the following properties (all of which are with respect
3091  // to the calling process):
3092  //
3093  // 1. Indices in the domain Map go first.
3094  // 2. Indices not in the domain Map follow, ordered first
3095  // contiguously by their owning process rank (in the domain
3096  // Map), then in increasing order within that.
3097  // 3. No duplicate indices.
3098  //
3099  // This imitates the ordering used by Aztec(OO) and Epetra.
3100  // Storing indices owned by the same process (in the domain Map)
3101  // contiguously permits the use of contiguous send and receive
3102  // buffers.
3103  //
3104  // We begin by partitioning the column indices into "local" GIDs
3105  // (owned by the domain Map) and "remote" GIDs (not owned by the
3106  // domain Map). We use the same order for local GIDs as the
3107  // domain Map, so we track them in place in their array. We use
3108  // an std::set (RemoteGIDSet) to keep track of remote GIDs, so
3109  // that we don't have to merge duplicates later.
3110  const LO LINV = Teuchos::OrdinalTraits<LO>::invalid ();
3111  size_t numLocalColGIDs = 0, numRemoteColGIDs = 0;
3112 
3113  // GIDisLocal[lid] == 0 if and only if local index lid in the
3114  // domain Map is remote (not local).
3115  Array<char> GIDisLocal (domainMap_->getNodeNumElements (), 0);
3116  std::set<GO> RemoteGIDSet;
3117  const size_t myNumRows = getNodeNumRows ();
3118  for (size_t r = 0; r < myNumRows; ++r) {
3119  RowInfo rowinfo = getRowInfo (r);
3120  if (rowinfo.numEntries > 0) {
3121  // FIXME (mfh 03 Mar 2013) It's a bit puzzling to me why the
3122  // ArrayView that getGlobalView() returns doesn't return
3123  // rowinfo.numEntries entries.
3124  ArrayView<const GO> rowGids = getGlobalView (rowinfo);
3125  rowGids = rowGids (0, rowinfo.numEntries);
3126 
3127  for (size_t k = 0; k < rowinfo.numEntries; ++k) {
3128  const GO gid = rowGids[k];
3129  const LO lid = domainMap_->getLocalElement (gid);
3130  if (lid != LINV) {
3131  const char alreadyFound = GIDisLocal[lid];
3132  if (alreadyFound == 0) {
3133  GIDisLocal[lid] = 1;
3134  ++numLocalColGIDs;
3135  }
3136  }
3137  else {
3138  const bool notAlreadyFound = RemoteGIDSet.insert (gid).second;
3139  if (notAlreadyFound) { // gid did not exist in the set before
3140  ++numRemoteColGIDs;
3141  }
3142  }
3143  } // for each entry k in row r
3144  } // if row r contains > 0 entries
3145  } // for each locally owned row r
3146 
3147  // Possible short-circuit for serial scenario:
3148  //
3149  // If all domain GIDs are present as column indices, then set
3150  // ColMap=DomainMap. By construction, LocalGIDs is a subset of
3151  // DomainGIDs.
3152  //
3153  // If we have
3154  // * Number of remote GIDs is 0, so that ColGIDs == LocalGIDs,
3155  // and
3156  // * Number of local GIDs is number of domain GIDs
3157  // then
3158  // * LocalGIDs \subset DomainGIDs && size(LocalGIDs) ==
3159  // size(DomainGIDs) => DomainGIDs == LocalGIDs == ColGIDs
3160  // on the calling process.
3161  //
3162  // We will concern ourselves only with the special case of a
3163  // serial DomainMap, obviating the need for communication.
3164  //
3165  // If
3166  // * DomainMap has a serial communicator
3167  // then we can set the column Map as the domain Map
3168  // return. Benefit: this graph won't need an Import object
3169  // later.
3170  //
3171  // Note, for a serial domain map, there can be no RemoteGIDs,
3172  // because there are no remote processes. Likely explanations
3173  // for this are:
3174  // * user submitted erroneous column indices
3175  // * user submitted erroneous domain Map
3176  if (domainMap_->getComm ()->getSize () == 1) {
3178  numRemoteColGIDs != 0, std::runtime_error,
3179  ": " << numRemoteColGIDs << " column "
3180  << (numRemoteColGIDs != 1 ? "indices are" : "index is")
3181  << " not in the domain Map." << endl
3182  << "Either these indices are invalid or the domain Map is invalid."
3183  << endl << "Remember that nonsquare matrices, or matrices where the "
3184  "row and range Maps are different, require calling the version of "
3185  "fillComplete that takes the domain and range Maps as input.");
3186  if (numLocalColGIDs == domainMap_->getNodeNumElements()) {
3187  colMap_ = domainMap_;
3188  checkInternalState ();
3189  return;
3190  }
3191  }
3192 
3193  // Populate myColumns with a list of all column GIDs. Put
3194  // locally owned (in the domain Map) GIDs at the front: they
3195  // correspond to "same" and "permuted" entries between the
3196  // column Map and the domain Map. Put remote GIDs at the back.
3197  myColumns.resize (numLocalColGIDs + numRemoteColGIDs);
3198  // get pointers into myColumns for each part
3199  ArrayView<GO> LocalColGIDs = myColumns (0, numLocalColGIDs);
3200  ArrayView<GO> RemoteColGIDs = myColumns (numLocalColGIDs, numRemoteColGIDs);
3201 
3202  // Copy the remote GIDs into myColumns
3203  std::copy (RemoteGIDSet.begin(), RemoteGIDSet.end(), RemoteColGIDs.begin());
3204 
3205  // Make a list of process ranks corresponding to the remote GIDs.
3206  Array<int> RemoteImageIDs (numRemoteColGIDs);
3207  // Look up the remote process' ranks in the domain Map.
3208  {
3209  const LookupStatus stat =
3210  domainMap_->getRemoteIndexList (RemoteColGIDs, RemoteImageIDs ());
3211 #ifdef HAVE_TPETRA_DEBUG
3212  // If any process returns IDNotPresent, then at least one of
3213  // the remote indices was not present in the domain Map. This
3214  // means that the Import object cannot be constructed, because
3215  // of incongruity between the column Map and domain Map.
3216  // This has two likely causes:
3217  // - The user has made a mistake in the column indices
3218  // - The user has made a mistake with respect to the domain Map
3219  const int missingID_lcl = (stat == IDNotPresent ? 1 : 0);
3220  int missingID_gbl = 0;
3221  reduceAll<int, int> (*getComm (), REDUCE_MAX, missingID_lcl,
3222  outArg (missingID_gbl));
3224  missingID_gbl == 1, std::runtime_error,
3225  ": Some column indices are not in the domain Map." << endl
3226  << "Either these column indices are invalid or the domain Map is "
3227  "invalid." << endl << "Likely cause: For a nonsquare matrix, you "
3228  "must give the domain and range Maps as input to fillComplete.");
3229 #else
3230  (void) stat; // forestall compiler warning for unused variable
3231 #endif // HAVE_TPETRA_DEBUG
3232  }
3233  // Sort incoming remote column indices so that all columns
3234  // coming from a given remote process are contiguous. This
3235  // means the Import's Distributor doesn't need to reorder data.
3236  sort2 (RemoteImageIDs.begin(), RemoteImageIDs.end(), RemoteColGIDs.begin());
3237 
3238  // Copy the local GIDs into myColumns. Two cases:
3239  // 1. If the number of Local column GIDs is the same as the
3240  // number of Local domain GIDs, we can simply read the domain
3241  // GIDs into the front part of ColIndices (see logic above
3242  // from the serial short circuit case)
3243  // 2. We step through the GIDs of the DomainMap, checking to see
3244  // if each domain GID is a column GID. We want to do this to
3245  // maintain a consistent ordering of GIDs between the columns
3246  // and the domain.
3247 
3248  // FIXME (mfh 03 Mar 2013) It's common that the domain Map is
3249  // contiguous. It would be more efficient in that case to avoid
3250  // calling getNodeElementList(), since that permanently
3251  // constructs and caches the GID list in the contiguous Map.
3252  ArrayView<const GO> domainElts = domainMap_->getNodeElementList ();
3253  const size_t numDomainElts = domainMap_->getNodeNumElements ();
3254  if (numLocalColGIDs == numDomainElts) {
3255  // If the number of locally owned GIDs are the same as the
3256  // number of local domain Map elements, then the local domain
3257  // Map elements are the same as the locally owned GIDs.
3258  std::copy (domainElts.begin(), domainElts.end(), LocalColGIDs.begin());
3259  }
3260  else {
3261  // Count the number of locally owned GIDs, both to keep track
3262  // of the current array index, and as a sanity check.
3263  size_t numLocalCount = 0;
3264  for (size_t i = 0; i < numDomainElts; ++i) {
3265  if (GIDisLocal[i]) {
3266  LocalColGIDs[numLocalCount++] = domainElts[i];
3267  }
3268  }
3270  numLocalCount != numLocalColGIDs, std::logic_error,
3271  ": numLocalCount = " << numLocalCount << " != numLocalColGIDs = "
3272  << numLocalColGIDs << ". This should never happen. Please report "
3273  "this bug to the Tpetra developers.");
3274  }
3275 
3276  // FIXME (mfh 03 Apr 2013) Now would be a good time to use the
3277  // information we collected above to construct the Import. In
3278  // particular, building an Import requires:
3279  //
3280  // 1. numSameIDs (length of initial contiguous sequence of GIDs
3281  // on this process that are the same in both Maps; this
3282  // equals the number of domain Map elements on this process)
3283  //
3284  // 2. permuteToLIDs and permuteFromLIDs (both empty in this
3285  // case, since there's no permutation going on; the column
3286  // Map starts with the domain Map's GIDs, and immediately
3287  // after them come the remote GIDs)
3288  //
3289  // 3. remoteGIDs (exactly those GIDs that we found out above
3290  // were not in the domain Map) and remoteLIDs (which we could
3291  // have gotten above by using the three-argument version of
3292  // getRemoteIndexList() that computes local indices as well
3293  // as process ranks, instead of the two-argument version that
3294  // was used above)
3295  //
3296  // 4. remotePIDs (which we have from the getRemoteIndexList()
3297  // call above)
3298  //
3299  // 5. Sorting remotePIDs, and applying that permutation to
3300  // remoteGIDs and remoteLIDs (by calling sort3 above instead
3301  // of sort2)
3302  //
3303  // 6. Everything after the sort3 call in Import::setupExport():
3304  // a. Create the Distributor via createFromRecvs(), which
3305  // computes exportGIDs and exportPIDs
3306  // b. Compute exportLIDs from exportGIDs (by asking the
3307  // source Map, in this case the domain Map, to convert
3308  // global to local)
3309  //
3310  // Steps 1-5 come for free, since we must do that work anyway in
3311  // order to compute the column Map. In particular, Step 3 is
3312  // even more expensive than Step 6a, since it involves both
3313  // creating and using a new Distributor object.
3314 
3315  } // if the graph is globally indexed
3316 
3317  const global_size_t gstInv =
3319  const GO indexBase = domainMap_->getIndexBase ();
3320  colMap_ = rcp (new map_type (gstInv, myColumns, indexBase,
3321  domainMap_->getComm (),
3322  domainMap_->getNode ()));
3323  checkInternalState ();
3324  return;
3325  }
3326 
3327 
3328  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3330  {
3331  TEUCHOS_TEST_FOR_EXCEPT( isGloballyIndexed() ); // call only after makeIndicesLocal()
3332  TEUCHOS_TEST_FOR_EXCEPT( ! isSorted() ); // call only after sortIndices()
3333  if (! isMerged ()) {
3334  for (size_t row=0; row < getNodeNumRows(); ++row) {
3335  RowInfo rowInfo = getRowInfo(row);
3336  mergeRowIndices(rowInfo);
3337  }
3338  // we just merged every row
3339  noRedundancies_ = true;
3340  }
3341  }
3342 
3343 
3344  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3345  void
3347  {
3348  typedef Import<LocalOrdinal,GlobalOrdinal,Node> import_type;
3349  typedef Export<LocalOrdinal,GlobalOrdinal,Node> export_type;
3350 
3351  TEUCHOS_TEST_FOR_EXCEPTION(! hasColMap (), std::logic_error, "Tpetra::"
3352  "CrsGraph: It's not allowed to call makeImportExport() unless the graph "
3353  "has a column Map.");
3354  RCP<ParameterList> params = this->getNonconstParameterList (); // could be null
3355 
3356  // Don't do any checks to see if we need to create the Import, if
3357  // it exists already.
3358  //
3359  // FIXME (mfh 25 Mar 2013) This will become incorrect if we
3360  // change CrsGraph in the future to allow changing the column
3361  // Map after fillComplete. For now, the column Map is fixed
3362  // after the first fillComplete call.
3363  if (importer_.is_null ()) {
3364  // Create the Import instance if necessary.
3365  if (domainMap_ != colMap_ && (! domainMap_->isSameAs (*colMap_))) {
3366  if (params.is_null () || ! params->isSublist ("Import")) {
3367  importer_ = rcp (new import_type (domainMap_, colMap_));
3368  } else {
3369  RCP<ParameterList> importSublist = sublist (params, "Import", true);
3370  importer_ = rcp (new import_type (domainMap_, colMap_, importSublist));
3371  }
3372  }
3373  }
3374 
3375  // Don't do any checks to see if we need to create the Export, if
3376  // it exists already.
3377  if (exporter_.is_null ()) {
3378  // Create the Export instance if necessary.
3379  if (rangeMap_ != rowMap_ && ! rangeMap_->isSameAs (*rowMap_)) {
3380  if (params.is_null () || ! params->isSublist ("Export")) {
3381  exporter_ = rcp (new export_type (rowMap_, rangeMap_));
3382  }
3383  else {
3384  RCP<ParameterList> exportSublist = sublist (params, "Export", true);
3385  exporter_ = rcp (new export_type (rowMap_, rangeMap_, exportSublist));
3386  }
3387  }
3388  }
3389  }
3390 
3391 
3392  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3393  std::string
3395  {
3396  std::ostringstream oss;
3397  oss << DistObject<GlobalOrdinal,LocalOrdinal,GlobalOrdinal,Node>::description();
3398  if (isFillComplete()) {
3399  oss << "{status = fill complete"
3400  << ", global rows = " << getGlobalNumRows()
3401  << ", global cols = " << getGlobalNumCols()
3402  << ", global num entries = " << getGlobalNumEntries()
3403  << "}";
3404  }
3405  else {
3406  oss << "{status = fill not complete"
3407  << ", global rows = " << getGlobalNumRows()
3408  << "}";
3409  }
3410  return oss.str();
3411  }
3412 
3413 
3414  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3415  void
3418  const Teuchos::EVerbosityLevel verbLevel) const
3419  {
3420  const char tfecfFuncName[] = "describe()";
3421  using std::endl;
3422  using std::setw;
3423  using Teuchos::VERB_DEFAULT;
3424  using Teuchos::VERB_NONE;
3425  using Teuchos::VERB_LOW;
3426  using Teuchos::VERB_MEDIUM;
3427  using Teuchos::VERB_HIGH;
3428  using Teuchos::VERB_EXTREME;
3429  Teuchos::EVerbosityLevel vl = verbLevel;
3430  if (vl == VERB_DEFAULT) vl = VERB_LOW;
3431  RCP<const Comm<int> > comm = this->getComm();
3432  const int myImageID = comm->getRank(),
3433  numImages = comm->getSize();
3434  size_t width = 1;
3435  for (size_t dec=10; dec<getGlobalNumRows(); dec *= 10) {
3436  ++width;
3437  }
3438  width = std::max<size_t>(width,Teuchos::as<size_t>(11)) + 2;
3439  Teuchos::OSTab tab(out);
3440  // none: print nothing
3441  // low: print O(1) info from node 0
3442  // medium: print O(P) info, num entries per node
3443  // high: print O(N) info, num entries per row
3444  // extreme: print O(NNZ) info: print graph indices
3445  //
3446  // for medium and higher, print constituent objects at specified verbLevel
3447  if (vl != VERB_NONE) {
3448  if (myImageID == 0) out << this->description() << std::endl;
3449  // O(1) globals, minus what was already printed by description()
3450  if (isFillComplete() && myImageID == 0) {
3451  out << "Global number of diagonals = " << globalNumDiags_ << std::endl;
3452  out << "Global max number of row entries = " << globalMaxNumRowEntries_ << std::endl;
3453  }
3454  // constituent objects
3455  if (vl == VERB_MEDIUM || vl == VERB_HIGH || vl == VERB_EXTREME) {
3456  if (myImageID == 0) out << "\nRow map: " << std::endl;
3457  rowMap_->describe(out,vl);
3458  if (colMap_ != null) {
3459  if (myImageID == 0) out << "\nColumn map: " << std::endl;
3460  colMap_->describe(out,vl);
3461  }
3462  if (domainMap_ != null) {
3463  if (myImageID == 0) out << "\nDomain map: " << std::endl;
3464  domainMap_->describe(out,vl);
3465  }
3466  if (rangeMap_ != null) {
3467  if (myImageID == 0) out << "\nRange map: " << std::endl;
3468  rangeMap_->describe(out,vl);
3469  }
3470  }
3471  // O(P) data
3472  if (vl == VERB_MEDIUM || vl == VERB_HIGH || vl == VERB_EXTREME) {
3473  for (int imageCtr = 0; imageCtr < numImages; ++imageCtr) {
3474  if (myImageID == imageCtr) {
3475  out << "Node ID = " << imageCtr << std::endl
3476  << "Node number of entries = " << nodeNumEntries_ << std::endl
3477  << "Node number of diagonals = " << nodeNumDiags_ << std::endl
3478  << "Node max number of entries = " << nodeMaxNumRowEntries_ << std::endl;
3479  if (indicesAreAllocated()) {
3480  out << "Node number of allocated entries = " << nodeNumAllocated_ << std::endl;
3481  }
3482  else {
3483  out << "Indices are not allocated." << std::endl;
3484  }
3485  }
3486  comm->barrier();
3487  comm->barrier();
3488  comm->barrier();
3489  }
3490  }
3491  // O(N) and O(NNZ) data
3492  if (vl == VERB_HIGH || vl == VERB_EXTREME) {
3493  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(hasRowInfo() == false, std::runtime_error, ": reduce verbosity level; graph row information was deleted at fillComplete().");
3494  for (int imageCtr = 0; imageCtr < numImages; ++imageCtr) {
3495  if (myImageID == imageCtr) {
3496  out << std::setw(width) << "Node ID"
3497  << std::setw(width) << "Global Row"
3498  << std::setw(width) << "Num Entries";
3499  if (vl == VERB_EXTREME) {
3500  out << "Entries";
3501  }
3502  out << std::endl;
3503  for (size_t r=0; r < getNodeNumRows(); ++r) {
3504  RowInfo rowinfo = getRowInfo(r);
3505  GlobalOrdinal gid = rowMap_->getGlobalElement(r);
3506  out << std::setw(width) << myImageID
3507  << std::setw(width) << gid
3508  << std::setw(width) << rowinfo.numEntries;
3509  if (vl == VERB_EXTREME) {
3510  if (isGloballyIndexed()) {
3511  ArrayView<const GlobalOrdinal> rowview = getGlobalView(rowinfo);
3512  for (size_t j=0; j < rowinfo.numEntries; ++j) out << rowview[j] << " ";
3513  }
3514  else if (isLocallyIndexed()) {
3515  ArrayView<const LocalOrdinal> rowview = getLocalView(rowinfo);
3516  for (size_t j=0; j < rowinfo.numEntries; ++j) out << colMap_->getGlobalElement(rowview[j]) << " ";
3517  }
3518  }
3519  out << std::endl;
3520  }
3521  }
3522  comm->barrier();
3523  comm->barrier();
3524  comm->barrier();
3525  }
3526  }
3527  }
3528  }
3529 
3530 
3531  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3532  bool
3535  {
3536  (void) source; // forestall "unused variable" compiler warnings
3537 
3538  // It's not clear what kind of compatibility checks on sizes can
3539  // be performed here. Epetra_CrsGraph doesn't check any sizes for
3540  // compatibility.
3541  return true;
3542  }
3543 
3544 
3545  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3546  void
3549  size_t numSameIDs,
3550  const Teuchos::ArrayView<const LocalOrdinal> &permuteToLIDs,
3551  const Teuchos::ArrayView<const LocalOrdinal> &permuteFromLIDs)
3552  {
3553  using Teuchos::Array;
3554  using Teuchos::ArrayView;
3555  const char tfecfFuncName[] = "copyAndPermute";
3557  const this_type& src_graph = dynamic_cast<const this_type&> (source);
3558 
3560  permuteToLIDs.size() != permuteFromLIDs.size(), std::runtime_error,
3561  ": permuteToLIDs and permuteFromLIDs must have the same size.");
3562  const bool src_filled = src_graph.isFillComplete ();
3563 
3564  const map_type& srcRowMap = * (src_graph.getRowMap ());
3565  const map_type& tgtRowMap = * (this->getRowMap ());
3566 
3567  Array<GlobalOrdinal> row_copy;
3568  LocalOrdinal myid = 0;
3569  for (size_t i = 0; i < numSameIDs; ++i, ++myid) {
3570  GlobalOrdinal gid = srcRowMap.getGlobalElement (myid);
3571  if (src_filled) {
3572  size_t row_length = src_graph.getNumEntriesInGlobalRow (gid);
3573  row_copy.resize (row_length);
3574  size_t check_row_length = 0;
3575  src_graph.getGlobalRowCopy (gid, row_copy (), check_row_length);
3576  this->insertGlobalIndices (gid, row_copy ());
3577  }
3578  else {
3580  src_graph.getGlobalRowView (gid,row);
3581  insertGlobalIndices (gid, row);
3582  }
3583  }
3584 
3585  for (LocalOrdinal i=0; i<permuteToLIDs.size(); ++i) {
3586  GlobalOrdinal mygid = tgtRowMap.getGlobalElement (permuteToLIDs[i]);
3587  GlobalOrdinal srcgid = srcRowMap.getGlobalElement (permuteFromLIDs[i]);
3588  if (src_filled) {
3589  size_t row_length = src_graph.getNumEntriesInGlobalRow (srcgid);
3590  row_copy.resize (row_length);
3591  size_t check_row_length = 0;
3592  src_graph.getGlobalRowCopy (srcgid, row_copy (), check_row_length);
3593  this->insertGlobalIndices (mygid, row_copy ());
3594  }
3595  else {
3597  src_graph.getGlobalRowView (srcgid, row);
3598  this->insertGlobalIndices (mygid, row);
3599  }
3600  }
3601  }
3602 
3603 
3604  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3605  void
3608  const Teuchos::ArrayView<const LocalOrdinal> &exportLIDs,
3610  const Teuchos::ArrayView<size_t> & numPacketsPerLID,
3611  size_t& constantNumPackets,
3612  Distributor &distor)
3613  {
3614  using Teuchos::Array;
3615  const char tfecfFuncName[] = "packAndPrepare";
3617  exportLIDs.size() != numPacketsPerLID.size(), std::runtime_error,
3618  ": exportLIDs and numPacketsPerLID must have the same size.");
3620  const this_type& src_graph = dynamic_cast<const this_type&> (source);
3621 
3622  // We don't check whether src_graph has had fillComplete called,
3623  // because it doesn't matter whether the *source* graph has been
3624  // fillComplete'd. The target graph can not be fillComplete'd yet.
3626  this->isFillComplete (), std::runtime_error,
3627  ": The target CrsGraph of an Import or Export must not be fillComplete.");
3628 
3629  constantNumPackets = 0;
3630  // first set the contents of numPacketsPerLID, and accumulate a total-num-packets:
3631  size_t totalNumPackets = 0;
3633  for (LocalOrdinal i=0; i<exportLIDs.size(); ++i) {
3634  GlobalOrdinal GID = src_graph.getMap()->getGlobalElement(exportLIDs[i]);
3635  size_t row_length = src_graph.getNumEntriesInGlobalRow(GID);
3636  numPacketsPerLID[i] = row_length;
3637  totalNumPackets += row_length;
3638  }
3639 
3640  exports.resize(totalNumPackets);
3641 
3642  // now loop again and pack rows of indices into exports:
3643  size_t exportsOffset = 0;
3644  for (LocalOrdinal i=0; i<exportLIDs.size(); ++i) {
3645  GlobalOrdinal GID = src_graph.getMap()->getGlobalElement(exportLIDs[i]);
3646  size_t row_length = src_graph.getNumEntriesInGlobalRow(GID);
3647  row.resize(row_length);
3648  size_t check_row_length = 0;
3649  src_graph.getGlobalRowCopy(GID, row(), check_row_length);
3651  row_iter = row.begin(), row_end = row.end();
3652  size_t j = 0;
3653  for (; row_iter != row_end; ++row_iter, ++j) {
3654  exports[exportsOffset+j] = *row_iter;
3655  }
3656  exportsOffset += row.size();
3657  }
3658  }
3659 
3660 
3661  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3662  void
3666  const Teuchos::ArrayView<size_t> &numPacketsPerLID,
3667  size_t constantNumPackets,
3668  Distributor& /* distor */,
3669  CombineMode /* CM */)
3670  {
3671  // FIXME (mfh 02 Apr 2012) REPLACE combine mode has a perfectly
3672  // reasonable meaning, whether or not the matrix is fill complete.
3673  // It's just more work to implement.
3674 
3675  // We are not checking the value of the CombineMode input
3676  // argument. For CrsGraph, we only support import/export
3677  // operations if fillComplete has not yet been called. Any
3678  // incoming column-indices are inserted into the target graph. In
3679  // this context, CombineMode values of ADD vs INSERT are
3680  // equivalent. What is the meaning of REPLACE for CrsGraph? If a
3681  // duplicate column-index is inserted, it will be compressed out
3682  // when fillComplete is called.
3683  //
3684  // Note: I think REPLACE means that an existing row is replaced by
3685  // the imported row, i.e., the existing indices are cleared. CGB,
3686  // 6/17/2010
3687 
3688  const char tfecfFuncName[] = "unpackAndCombine";
3690  importLIDs.size() != numPacketsPerLID.size(), std::runtime_error,
3691  ": importLIDs and numPacketsPerLID must have the same size.");
3693  isFillComplete (), std::runtime_error,
3694  ": Import or Export operations are not allowed on the destination "
3695  "CrsGraph if it is fill complete.");
3696  size_t importsOffset = 0;
3697 
3698  typedef typename ArrayView<const LocalOrdinal>::const_iterator iter_type;
3699  iter_type impLIDiter = importLIDs.begin();
3700  iter_type impLIDend = importLIDs.end();
3701 
3702  for (size_t i = 0; impLIDiter != impLIDend; ++impLIDiter, ++i) {
3703  LocalOrdinal row_length = numPacketsPerLID[i];
3704  ArrayView<const GlobalOrdinal> row (&imports[importsOffset], row_length);
3705  insertGlobalIndicesFiltered (this->getMap ()->getGlobalElement (*impLIDiter), row);
3706  importsOffset += row_length;
3707  }
3708  }
3709 
3710 
3711  template <class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
3712  void
3715  {
3716  using Teuchos::Comm;
3717  using Teuchos::null;
3718  using Teuchos::ParameterList;
3719  using Teuchos::RCP;
3720  typedef Import<LocalOrdinal,GlobalOrdinal,Node> import_type;
3721  typedef Export<LocalOrdinal,GlobalOrdinal,Node> export_type;
3722 
3723  // We'll set all the state "transactionally," so that this method
3724  // satisfies the strong exception guarantee. This object's state
3725  // won't be modified until the end of this method.
3726  RCP<const map_type> rowMap, domainMap, rangeMap, colMap;
3727  RCP<import_type> importer;
3728  RCP<export_type> exporter;
3729 
3730  rowMap = newMap;
3731  RCP<const Comm<int> > newComm =
3732  (newMap.is_null ()) ? null : newMap->getComm ();
3733 
3734  if (! domainMap_.is_null ()) {
3735  if (domainMap_.getRawPtr () == rowMap_.getRawPtr ()) {
3736  // Common case: original domain and row Maps are identical.
3737  // In that case, we need only replace the original domain Map
3738  // with the new Map. This ensures that the new domain and row
3739  // Maps _stay_ identical.
3740  domainMap = newMap;
3741  } else {
3742  domainMap = domainMap_->replaceCommWithSubset (newComm);
3743  }
3744  }
3745  if (! rangeMap_.is_null ()) {
3746  if (rangeMap_.getRawPtr () == rowMap_.getRawPtr ()) {
3747  // Common case: original range and row Maps are identical. In
3748  // that case, we need only replace the original range Map with
3749  // the new Map. This ensures that the new range and row Maps
3750  // _stay_ identical.
3751  rangeMap = newMap;
3752  } else {
3753  rangeMap = rangeMap_->replaceCommWithSubset (newComm);
3754  }
3755  }
3756  if (! colMap.is_null ()) {
3757  colMap = colMap_->replaceCommWithSubset (newComm);
3758  }
3759 
3760  // (Re)create the Export and / or Import if necessary.
3761  if (! newComm.is_null ()) {
3762  RCP<ParameterList> params = this->getNonconstParameterList (); // could be null
3763  //
3764  // The operations below are collective on the new communicator.
3765  //
3766  // (Re)create the Export object if necessary. If I haven't
3767  // called fillComplete yet, I don't have a rangeMap, so I must
3768  // first check if the _original_ rangeMap is not null. Ditto
3769  // for the Import object and the domain Map.
3770  if (! rangeMap_.is_null () &&
3771  rangeMap != rowMap &&
3772  ! rangeMap->isSameAs (*rowMap)) {
3773  if (params.is_null () || ! params->isSublist ("Export")) {
3774  exporter = rcp (new export_type (rowMap, rangeMap));
3775  }
3776  else {
3777  RCP<ParameterList> exportSublist = sublist (params, "Export", true);
3778  exporter = rcp (new export_type (rowMap, rangeMap, exportSublist));
3779  }
3780  }
3781  // (Re)create the Import object if necessary.
3782  if (! domainMap_.is_null () &&
3783  domainMap != colMap &&
3784  ! domainMap->isSameAs (*colMap)) {
3785  if (params.is_null () || ! params->isSublist ("Import")) {
3786  importer = rcp (new import_type (domainMap, colMap));
3787  } else {
3788  RCP<ParameterList> importSublist = sublist (params, "Import", true);
3789  importer = rcp (new import_type (domainMap, colMap, importSublist));
3790  }
3791  }
3792  } // if newComm is not null
3793 
3794  // Defer side effects until the end. If no destructors throw
3795  // exceptions (they shouldn't anyway), then this method satisfies
3796  // the strong exception guarantee.
3797  exporter_ = exporter;
3798  importer_ = importer;
3799  rowMap_ = rowMap;
3800  // mfh 31 Mar 2013: DistObject's map_ is the row Map of a CrsGraph
3801  // or CrsMatrix. CrsGraph keeps a redundant pointer (rowMap_) to
3802  // the same object. We might want to get rid of this redundant
3803  // pointer sometime, but for now, we'll leave it alone and just
3804  // set map_ to the same object.
3805  this->map_ = rowMap;
3806  domainMap_ = domainMap;
3807  rangeMap_ = rangeMap;
3808  colMap_ = colMap;
3809  }
3810 
3811 } // namespace Tpetra
3812 
3813 
3814 //
3815 // Explicit instantiation macro
3816 //
3817 // Must be expanded from within the Tpetra namespace!
3818 //
3819 
3820 #define TPETRA_CRSGRAPH_INSTANT(LO,GO,NODE) \
3821  \
3822  template class CrsGraph< LO , GO , NODE >; \
3823 
3824 
3825 #endif // TPETRA_CRSGRAPH_DEF_HPP
ScalarType * values() const
size_t getNodeNumCols() const
Returns the number of columns connected to the locally owned rows of this graph.
Communication plan for data redistribution from a uniquely-owned to a (possibly) multiply-owned distr...
RCP< const ParameterList > getValidParameters() const
Default parameter list suitable for validation.
Namespace Tpetra contains the class and methods constituting the Tpetra library.
void reserve(size_type n)
size_t findLocalIndex(RowInfo rowinfo, LocalOrdinal ind, size_t hint=0) const
Find the column offset corresponding to the given (local) column index.
void getGlobalRowView(GlobalOrdinal GlobalRow, ArrayView< const GlobalOrdinal > &Indices) const
Extract a const, non-persisting view of global indices in a specified row of the graph.
bool isLowerTriangular() const
Whether the graph is locally lower triangular.
RCP< const Export< LocalOrdinal, GlobalOrdinal, Node > > getExporter() const
Returns the exporter associated with this graph.
ProfileType getProfileType() const
Returns true if the graph was allocated with static data structures.
size_t getNodeNumRows() const
Returns the number of graph rows owned on the calling node.
int shapeUninitialized(OrdinalType numRows, OrdinalType numCols)
bool isNodeGlobalElement(GlobalOrdinal globalIndex) const
Whether the given global index is valid for this Map on this process.
RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > rangeMap_
The Map describing the range of the (matrix corresponding to the) graph.
bool haveGlobalConstants_
Whether all processes have computed global constants.
bool hasColMap() const
Whether the graph has a column Map.
ArrayRCP< const size_t > numAllocPerRow_
The maximum number of entries to allow in each locally owned row, per row.
bool isUpperTriangular() const
Whether the graph is locally upper triangular.
virtual bool checkSizes(const SrcDistObject &source)
Compare the source and target (this) objects for compatibility.
void getLocalRowCopy(LocalOrdinal LocalRow, const ArrayView< LocalOrdinal > &indices, size_t &NumIndices) const
Extract a list of elements in a specified local row of the graph. Put into storage allocated by calli...
void insertGlobalIndicesFiltered(const GlobalOrdinal localRow, const ArrayView< const GlobalOrdinal > &indices)
Like insertGlobalIndices(), but with column Map filtering.
void transformLocalValues(RowInfo rowInfo, const Teuchos::ArrayView< Scalar > &rowVals, const Teuchos::ArrayView< const LocalOrdinal > &inds, const Teuchos::ArrayView< const Scalar > &newVals, BinaryFunction f) const
Transform the given values using local indices.
iterator begin() const
void sortRowIndices(RowInfo rowinfo)
Sort the column indices in the given row.
void setParameterList(const RCP< ParameterList > &params)
Set the given list of parameters (must be nonnull).
ArrayRCP< LocalOrdinal > lclInds1D_
lclInds1D_ are the indices for all rows
bool empty() const
RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > domainMap_
The Map describing the domain of the (matrix corresponding to the) graph.
#define TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(throw_exception_test, Exception, msg)
void replaceDomainMapAndImporter(const Teuchos::RCP< const map_type > &newDomainMap, Teuchos::RCP< const Tpetra::Import< LocalOrdinal, GlobalOrdinal, Node > > &newImporter)
Replace the current domain Map and Import with the given parameters.
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel=Teuchos::Describable::verbLevel_default) const
Print the object with some verbosity level to an FancyOStream object.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
std::map< GlobalOrdinal, std::deque< GlobalOrdinal > > nonlocals_
Nonlocal data given to insertGlobalValues or sumIntoGlobalValues.
const_pointer const_iterator
GlobalOrdinal getIndexBase() const
Returns the index base for global indices for this graph.
size_t getNodeNumEntries() const
Returns the local number of entries in the graph.
void getLocalRowView(LocalOrdinal LocalRow, ArrayView< const LocalOrdinal > &indices) const
Extract a const, non-persisting view of local indices in a specified row of the graph.
ArrayRCP< size_t > numRowEntries_
The number of local entries in each locally owned row.
size_type size() const
void insertGlobalIndices(GlobalOrdinal globalRow, const ArrayView< const GlobalOrdinal > &indices)
Insert global indices into the graph.
RCP< const Export< LocalOrdinal, GlobalOrdinal, Node > > exporter_
The Export from the row Map to the range Map.
bool isSorted() const
Indicates whether the graph indices in all rows are known to be sorted.
bool isStorageOptimized() const
Returns true if storage has been optimized.
global_size_t getGlobalNumRows() const
Returns the number of global rows in the graph.
T * get() const
const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getRowMap() const
Returns the Map that describes the row distribution in this graph.
char * getRawPtr()
size_type size() const
Allocation information for a locally owned row in a CrsGraph or CrsMatrix.
ArrayRCP< const LocalOrdinal > getNodePackedIndices() const
Get an ArrayRCP of the packed column-indices.
size_t getGlobalMaxNumRowEntries() const
Maximum number of entries in all rows over all processes.
bool isNodeLocalElement(LocalOrdinal localIndex) const
Whether the given local index is valid for this Map on this process.
virtual void removeEmptyProcessesInPlace(const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &newMap)
Remove processes owning zero rows from the Maps and their communicator.
void makeColMap()
Make the column Map.
void setDomainRangeMaps(const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &domainMap, const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &rangeMap)
RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > colMap_
The Map describing the distribution of columns of the graph.
size_t getNodeAllocationSize() const
Returns the total number of indices allocated for the graph, across all rows on this node...
ArrayRCP< GlobalOrdinal > gblInds1D_
gblInds1D_ are the indices for all rows
global_size_t getGlobalNumCols() const
Returns the number of global columns in the graph.
void mergeRowIndicesAndValues(RowInfo rowinfo, const Teuchos::ArrayView< Scalar > &rowValues)
Merge duplicate row indices in the given row, along with their corresponding values.
virtual void packAndPrepare(const SrcDistObject &source, const Teuchos::ArrayView< const LocalOrdinal > &exportLIDs, Teuchos::Array< GlobalOrdinal > &exports, const Teuchos::ArrayView< size_t > &numPacketsPerLID, size_t &constantNumPackets, Distributor &distor)
Perform any packing or preparation required for communication.
const RCP< const Comm< int > > & getComm() const
Returns the communicator.
void resize(const size_type n, const T &val=T())
size_t global_size_t
Global size_t object.
void fillComplete(const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &domainMap, const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &rangeMap, const RCP< ParameterList > &params=null)
Signal that data entry is complete, specifying domain and range maps.
RCP< const Import< LocalOrdinal, GlobalOrdinal, Node > > getImporter() const
Returns the importer associated with this graph.
Ordinal size_type
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
ProfileType pftype_
Whether the graph was allocated with static or dynamic profile.
bool noRedundancies_
Whether the graph&#39;s indices are non-redundant (merged) in each row, on this process.
virtual void unpackAndCombine(const Teuchos::ArrayView< const LocalOrdinal > &importLIDs, const Teuchos::ArrayView< const GlobalOrdinal > &imports, const Teuchos::ArrayView< size_t > &numPacketsPerLID, size_t constantNumPackets, Distributor &distor, CombineMode CM)
Perform any unpacking and combining after communication.
size_t getNumAllocatedEntriesInGlobalRow(GlobalOrdinal globalRow) const
Returns the current number of allocated entries for this node in the specified global row ...
void mergeAllIndices()
Merge duplicate row indices in all of the rows.
size_t findGlobalIndex(RowInfo rowinfo, GlobalOrdinal ind, size_t hint=0) const
Find the column offset corresponding to the given (global) column index.
Communication plan for data redistribution from a (possibly) multiply-owned to a uniquely-owned distr...
size_t getNumEntriesInGlobalRow(GlobalOrdinal globalRow) const
Returns the current number of entries on this node in the specified global row.
void getGlobalRowCopy(GlobalOrdinal GlobalRow, const ArrayView< GlobalOrdinal > &Indices, size_t &NumIndices) const
Extract a list of elements in a specified global row of the graph. Put into pre-allocated storage...
Sets up and executes a communication plan for a Tpetra DistObject.
GlobalOrdinal getGlobalElement(LocalOrdinal localIndex) const
The global index corresponding to the given local index.
CombineMode
Tpetra::Combine Mode enumerable type.
size_t getNodeMaxNumRowEntries() const
Maximum number of entries in all rows owned by the calling process.
size_t getNumAllocatedEntriesInLocalRow(LocalOrdinal localRow) const
Returns the current number of allocated entries on this node in the specified local row...
void setLocallyModified()
Report that we made a local modification to its structure.
const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getMap() const
The Map describing the parallel distribution of this object.
TEUCHOSCORE_LIB_DLL_EXPORT std::string toString(const EVerbosityLevel verbLevel)
void setMyParamList(const RCP< ParameterList > &paramList)
bool isMerged() const
Whether duplicate column indices in each row have been merged.
virtual void copyAndPermute(const SrcDistObject &source, size_t numSameIDs, const Teuchos::ArrayView< const LocalOrdinal > &permuteToLIDs, const Teuchos::ArrayView< const LocalOrdinal > &permuteFromLIDs)
Perform copies and permutations that are local to this process.
TEUCHOS_DEPRECATED void reduceAll(const Comm< Ordinal > &comm, const EReductionType reductType, const Packet &send, Packet *globalReduct)
RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > rowMap_
The Map describing the distribution of rows of the graph.
Abstract base class for objects that can be the source of an Import or Export operation.
bool lowerTriangular_
Whether the graph is locally lower triangular.
void resize(size_type new_size, const value_type &x=value_type())
ArrayRCP< Array< LocalOrdinal > > lclInds2D_
lclInds2D_[r] are the indices for row r.
RCP< ParameterList > getNonconstParameterList()
size_t numAllocForAllRows_
The maximum number of entries to allow in each locally owned row.
const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getDomainMap() const
Returns the Map associated with the domain of this graph.
iterator end()
std::vector< T >::const_iterator const_iterator
RCP< const Import< LocalOrdinal, GlobalOrdinal, Node > > importer_
The Import from the domain Map to the column Map.
const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getColMap() const
Returns the Map that describes the column distribution in this graph.
void insertLocalIndices(const LocalOrdinal localRow, const ArrayView< const LocalOrdinal > &indices)
Insert local indices into the graph.
void transformGlobalValues(RowInfo rowInfo, const Teuchos::ArrayView< Scalar > &rowVals, const Teuchos::ArrayView< const GlobalOrdinal > &inds, const Teuchos::ArrayView< const Scalar > &newVals, BinaryFunction f) const
Transform the given values using global indices.
RCP< CommRequest< Ordinal > > ireceive(const ArrayRCP< Packet > &recvBuffer, const int sourceRank, const int tag, const Comm< Ordinal > &comm)
std::string description() const
Return a simple one-line description of this object.
LocalOrdinal getLocalElement(GlobalOrdinal globalIndex) const
The local index corresponding to the given global index.
void push_back(const value_type &x)
void sort2(const IT1 &first1, const IT1 &last1, const IT2 &first2)
Sort the first array, and apply the resulting permutation to the second array.
A distributed graph accessed by rows (adjacency lists) and stored sparsely.
size_t getNodeNumDiags() const
Returns the number of local diagonal entries, based on global row/column index comparisons.
void computeIndexState()
Set collectively whether the graph uses global or local indices.
Describes a parallel distribution of objects over processes.
void resumeFill(const RCP< ParameterList > &params=null)
bool isSameAs(const Map< LocalOrdinal, GlobalOrdinal, Node > &map) const
True if and only if map is identical to this Map.
bool upperTriangular_
Whether the graph is locally upper triangular.
iterator end() const
size_type size() const
TypeTo as(const TypeFrom &t)
bool isGloballyIndexed() const
If graph indices are in the global range, this function returns true. Otherwise, this function return...
ArrayRCP< const size_t > getNodeRowPtrs() const
Get an ArrayRCP of the row-offsets.
void mergeRowIndices(RowInfo rowinfo)
Merge duplicate row indices in the given row.
void expertStaticFillComplete(const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &domainMap, const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &rangeMap, const RCP< const Import< LocalOrdinal, GlobalOrdinal, Node > > &importer=Teuchos::null, const RCP< const Export< LocalOrdinal, GlobalOrdinal, Node > > &exporter=Teuchos::null, const RCP< ParameterList > &params=Teuchos::null)
Perform a fillComplete on a graph that already has data, via setAllIndices().
void insertLocalIndicesFiltered(const LocalOrdinal localRow, const ArrayView< const LocalOrdinal > &indices)
Like insertLocalIndices(), but with column Map filtering.
size_t insertIndices(const RowInfo &rowInfo, const SLocalGlobalViews &newInds, const ELocalGlobal lg, const ELocalGlobal I)
Insert indices into the given row.
bool isFillComplete() const
Returns true if fillComplete() has been called and the graph is in compute mode.
void sortRowIndicesAndValues(RowInfo rowinfo, ArrayView< Scalar > values)
Sort the column indices and their values in the given row.
RCP< Node > getNode() const
Returns the underlying node.
void sortAllIndices()
Sort the column indices in all the rows.
bool indicesAreSorted_
Whether the graph&#39;s indices are sorted in each row, on this process.
RCP< CommRequest< Ordinal > > isend(const ArrayRCP< const Packet > &sendBuffer, const int destRank, const int tag, const Comm< Ordinal > &comm)
bool isLocallyIndexed() const
If graph indices are in the local range, this function returns true. Otherwise, this function returns...
size_t getNumEntriesInLocalRow(LocalOrdinal localRow) const
Returns the current number of entries on this node in the specified local row.
void globalAssemble()
Communicate non-local contributions to other processes.
global_size_t getGlobalNumEntries() const
Returns the global number of entries in the graph.
const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getRangeMap() const
Returns the Map associated with the domain of this graph.
bool haveLocalConstants_
Whether this process has computed local constants.
iterator end() const
virtual ~CrsGraph()
Destructor.
Base class for distributed Tpetra objects that support data redistribution.
iterator insert(iterator position, const value_type &x)
iterator begin()
void removeLocalIndices(LocalOrdinal localRow)
Remove all graph indices from the specified local row.
bool isFillActive() const
Returns true if resumeFill() has been called and the graph is in edit mode.
ArrayRCP< Array< GlobalOrdinal > > gblInds2D_
gblInds2D_[r] are the indices for row r.
void insertIndicesAndValues(const RowInfo &rowInfo, const SLocalGlobalViews &newInds, const ArrayView< Scalar > &oldRowVals, const ArrayView< const Scalar > &newRowVals, const ELocalGlobal lg, const ELocalGlobal I)
Insert indices and their values into the given row.
#define TEUCHOS_TEST_FOR_EXCEPT(throw_exception_test)
iterator begin() const
global_size_t getGlobalNumDiags() const
Returns the number of global diagonal entries, based on global row/column index comparisons.
std::string toString(const T &t)
std::string typeName(const T &t)
Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > map_
The Map over which this object is distributed.
bool is_null() const
void setAllIndices(const ArrayRCP< size_t > &rowPointers, const ArrayRCP< LocalOrdinal > &columnIndices)
Set the graph&#39;s data directly, using 1-D storage.