Tpetra Matrix/Vector Services  Version of the Day
Tpetra_DirectoryImpl_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 #ifndef __Tpetra_DirectoryImpl_def_hpp
43 #define __Tpetra_DirectoryImpl_def_hpp
44 
45 #ifdef DOXYGEN_USE_ONLY
46 # include <Tpetra_DirectoryImpl_decl.hpp>
47 #endif
48 #include <Tpetra_Distributor.hpp>
49 #include <Tpetra_Map.hpp>
50 
51 #ifdef HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
52 # include <Tpetra_Details_FixedHashTable.hpp>
53 #endif // HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
54 
55 
56 // FIXME (mfh 16 Apr 2013) GIANT HACK BELOW
57 #ifdef HAVE_MPI
58 # include "mpi.h"
59 #endif // HAVE_MPI
60 // FIXME (mfh 16 Apr 2013) GIANT HACK ABOVE
61 
62 
63 namespace Tpetra {
64  namespace Details {
65  template<class LO, class GO, class NT>
67  Directory (const Teuchos::RCP<const typename Directory<LO, GO, NT>::map_type>& map) :
68  map_ (map)
69  {}
70 
71  template<class LO, class GO, class NT>
75  const Teuchos::ArrayView<int> &nodeIDs,
76  const Teuchos::ArrayView<LO> &localIDs,
77  const bool computeLIDs) const
78  {
79  // Ensure that globalIDs, nodeIDs, and localIDs (if applicable)
80  // all have the same size, before modifying any output arguments.
81  TEUCHOS_TEST_FOR_EXCEPTION(nodeIDs.size() != globalIDs.size(),
82  std::invalid_argument, Teuchos::typeName(*this) << "::getEntries(): "
83  "Output arrays do not have the right sizes. nodeIDs.size() = "
84  << nodeIDs.size() << " != globalIDs.size() = " << globalIDs.size()
85  << ".");
87  computeLIDs && localIDs.size() != globalIDs.size(),
88  std::invalid_argument, Teuchos::typeName(*this) << "::getEntries(): "
89  "Output array do not have the right sizes. localIDs.size() = "
90  << localIDs.size() << " != globalIDs.size() = " << globalIDs.size()
91  << ".");
92 
93  // Initially, fill nodeIDs and localIDs (if applicable) with
94  // invalid values. The "invalid" process ID is -1 (this means
95  // the same thing as MPI_ANY_SOURCE to Teuchos, so it's an
96  // "invalid" process ID); the invalid local ID comes from
97  // OrdinalTraits.
98  std::fill (nodeIDs.begin(), nodeIDs.end(), -1);
99  if (computeLIDs) {
100  std::fill (localIDs.begin(), localIDs.end(),
102  }
103  // Actually do the work.
104  return this->getEntriesImpl (globalIDs, nodeIDs, localIDs, computeLIDs);
105  }
106 
107  template<class LO, class GO, class NT>
110  Directory<LO, GO, NT> (map)
111  {}
112 
113  template<class LO, class GO, class NT>
114  std::string
116  {
117  std::ostringstream os;
118  os << "ReplicatedDirectory"
121  << ", " << Teuchos::TypeNameTraits<NT>::name () << ">";
122  return os.str ();
123  }
124 
125 
126  template<class LO, class GO, class NT>
130  {
131  TEUCHOS_TEST_FOR_EXCEPTION(! map->isContiguous (), std::invalid_argument,
132  Teuchos::typeName (*this) << " constructor: Map is not contiguous.");
133  TEUCHOS_TEST_FOR_EXCEPTION(! map->isUniform (), std::invalid_argument,
134  Teuchos::typeName (*this) << " constructor: Map is not uniform.");
135  }
136 
137 
138  template<class LO, class GO, class NT>
139  std::string
141  {
142  std::ostringstream os;
143  os << "ContiguousUniformDirectory"
146  << ", " << Teuchos::TypeNameTraits<NT>::name () << ">";
147  return os.str ();
148  }
149 
150 
151  template<class LO, class GO, class NT>
155  const Teuchos::ArrayView<int> &nodeIDs,
156  const Teuchos::ArrayView<LO> &localIDs,
157  const bool computeLIDs) const
158  {
159  using Teuchos::as;
160  using Teuchos::Comm;
161  using Teuchos::RCP;
162  typedef typename Teuchos::ArrayView<const GO>::size_type size_type;
163  const LO invalidLid = Teuchos::OrdinalTraits<LO>::invalid ();
165 
166  RCP<const map_type> map = this->getMap ();
167  RCP<const Comm<int> > comm = map->getComm ();
168  const GO g_min = map->getMinAllGlobalIndex ();
169 
170  // Let N_G be the global number of elements in the Map,
171  // and P be the number of processes in its communicator.
172  // Then, N_G = P * N_L + R = R*(N_L + 1) + (P - R)*N_L.
173  //
174  // The first R processes own N_L+1 elements.
175  // The remaining P-R processes own N_L elements.
176  //
177  // Let g be the current GID, g_min be the global minimum GID,
178  // and g_0 = g - g_min. If g is a valid GID in this Map, then
179  // g_0 is in [0, N_G - 1].
180  //
181  // If g is a valid GID in this Map and g_0 < R*(N_L + 1), then
182  // the rank of the process that owns g is floor(g_0 / (N_L +
183  // 1)), and its corresponding local index on that process is g_0
184  // mod (N_L + 1).
185  //
186  // Let g_R = g_0 - R*(N_L + 1). If g is a valid GID in this Map
187  // and g_0 >= R*(N_L + 1), then the rank of the process that
188  // owns g is then R + floor(g_R / N_L), and its corresponding
189  // local index on that process is g_R mod N_L.
190 
191  const size_type N_G = as<size_type> (map->getGlobalNumElements ());
192  const size_type P = as<size_type> (comm->getSize ());
193  const size_type N_L = N_G / P;
194  const size_type R = N_G - N_L * P; // N_G mod P
195  const size_type N_R = R * (N_L + 1);
196 
197 #ifdef HAVE_TPETRA_DEBUG
199  N_G != P*N_L + R, std::logic_error,
200  "Tpetra::ContiguousUniformDirectory::getEntriesImpl: "
201  "N_G = " << N_G << " != P*N_L + R = " << P << "*" << N_L << " + " << R
202  << " = " << P*N_L + R << ". "
203  "Please report this bug to the Tpetra developers.");
204 #endif // HAVE_TPETRA_DEBUG
205 
206  const size_type numGids = globalIDs.size (); // for const loop bound
207  if (computeLIDs) {
208  for (size_type k = 0; k < numGids; ++k) {
209  const GO g_0 = globalIDs[k] - g_min;
210  // The first test is a little strange just in case GO is
211  // unsigned. Compilers raise a warning on tests like "x <
212  // 0" if x is unsigned, but don't usually raise a warning if
213  // the expression is a bit more complicated than that.
214  if (g_0 + 1 < 1 || g_0 >= N_G) {
215  nodeIDs[k] = -1;
216  localIDs[k] = invalidLid;
217  res = IDNotPresent;
218  }
219  else if (g_0 < as<GO> (N_R)) {
220  // The GID comes from the initial sequence of R processes.
221  nodeIDs[k] = as<int> (g_0 / (N_L + 1));
222  localIDs[k] = g_0 % (N_L + 1);
223  }
224  else if (g_0 >= as<GO> (N_R)) {
225  // The GID comes from the remaining P-R processes.
226  const GO g_R = g_0 - N_R;
227  nodeIDs[k] = as<int> (R + g_R / N_L);
228  localIDs[k] = as<int> (g_R % N_L);
229  }
230 #ifdef HAVE_TPETRA_DEBUG
231  else {
232  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
233  "Tpetra::ContiguousUniformDirectory::getEntriesImpl: "
234  "should never get here. "
235  "Please report this bug to the Tpetra developers.");
236  }
237 #endif // HAVE_TPETRA_DEBUG
238  }
239  }
240  else { // don't compute local indices
241  for (size_type k = 0; k < numGids; ++k) {
242  const GO g_0 = globalIDs[k] - g_min;
243  // The first test is a little strange just in case GO is
244  // unsigned. Compilers raise a warning on tests like "x <
245  // 0" if x is unsigned, but don't usually raise a warning if
246  // the expression is a bit more complicated than that.
247  if (g_0 + 1 < 1 || g_0 >= N_G) {
248  nodeIDs[k] = -1;
249  res = IDNotPresent;
250  }
251  else if (g_0 < as<GO> (N_R)) {
252  // The GID comes from the initial sequence of R processes.
253  nodeIDs[k] = as<int> (g_0 / (N_L + 1));
254  }
255  else if (g_0 >= as<GO> (N_R)) {
256  // The GID comes from the remaining P-R processes.
257  const GO g_R = g_0 - N_R;
258  nodeIDs[k] = as<int> (R + g_R / N_L);
259  }
260 #ifdef HAVE_TPETRA_DEBUG
261  else {
262  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
263  "Tpetra::ContiguousUniformDirectory::getEntriesImpl: "
264  "should never get here. "
265  "Please report this bug to the Tpetra developers.");
266  }
267 #endif // HAVE_TPETRA_DEBUG
268  }
269  }
270  return res;
271  }
272 
273 
274  template<class LO, class GO, class NT>
278  {
279  using Teuchos::gatherAll;
280  using Teuchos::RCP;
281 
282  RCP<const Teuchos::Comm<int> > comm = map->getComm ();
283 
284  TEUCHOS_TEST_FOR_EXCEPTION(! map->isDistributed (), std::invalid_argument,
285  Teuchos::typeName (*this) << " constructor: Map is not distributed.");
286  TEUCHOS_TEST_FOR_EXCEPTION(! map->isContiguous (), std::invalid_argument,
287  Teuchos::typeName (*this) << " constructor: Map is not contiguous.");
288 
289  const int numProcs = comm->getSize ();
290 
291  // Make room for the min global ID on each process, plus one
292  // entry at the end for the "max cap."
293  allMinGIDs_ = arcp<GO> (numProcs + 1);
294  // Get my process' min global ID.
295  GO minMyGID = map->getMinGlobalIndex ();
296  // Gather all of the min global IDs into the first numProcs
297  // entries of allMinGIDs_.
298 
299  // FIXME (mfh 16 Apr 2013) GIANT HACK BELOW
300  //
301  // The purpose of this giant hack is that gatherAll appears to
302  // interpret the "receive count" argument differently than
303  // MPI_Allgather does. Matt Bettencourt reports Valgrind issues
304  // (memcpy with overlapping data) with MpiComm<int>::gatherAll,
305  // which could relate either to this, or to OpenMPI.
306 #ifdef HAVE_MPI
307  MPI_Datatype rawMpiType = MPI_INT;
308  bool useRawMpi = true;
309  if (typeid (GO) == typeid (int)) {
310  rawMpiType = MPI_INT;
311  } else if (typeid (GO) == typeid (long)) {
312  rawMpiType = MPI_LONG;
313  } else {
314  useRawMpi = false;
315  }
316  if (useRawMpi) {
317  using Teuchos::rcp_dynamic_cast;
318  using Teuchos::MpiComm;
319  RCP<const MpiComm<int> > mpiComm =
320  rcp_dynamic_cast<const MpiComm<int> > (comm);
321  // It could be a SerialComm instead, even in an MPI build, so
322  // be sure to check.
323  if (! comm.is_null ()) {
324  MPI_Comm rawMpiComm = * (mpiComm->getRawMpiComm ());
325  const int err =
326  MPI_Allgather (&minMyGID, 1, rawMpiType,
327  allMinGIDs_.getRawPtr (), 1, rawMpiType,
328  rawMpiComm);
329  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
330  "Tpetra::DistributedContiguousDirectory: MPI_Allgather failed");
331  } else {
332  gatherAll<int, GO> (*comm, 1, &minMyGID, numProcs, allMinGIDs_.getRawPtr ());
333  }
334  } else {
335  gatherAll<int, GO> (*comm, 1, &minMyGID, numProcs, allMinGIDs_.getRawPtr ());
336  }
337 #else // NOT HAVE_MPI
338  gatherAll<int, GO> (*comm, 1, &minMyGID, numProcs, allMinGIDs_.getRawPtr ());
339 #endif // HAVE_MPI
340  // FIXME (mfh 16 Apr 2013) GIANT HACK ABOVE
341 
342  //gatherAll<int, GO> (*comm, 1, &minMyGID, numProcs, allMinGIDs_.getRawPtr ());
343 
344  // Put the max cap at the end. Adding one lets us write loops
345  // over the global IDs with the usual strict less-than bound.
346  allMinGIDs_[numProcs] = map->getMaxAllGlobalIndex ()
348  }
349 
350  template<class LO, class GO, class NT>
351  std::string
353  {
354  std::ostringstream os;
355  os << "DistributedContiguousDirectory"
358  << ", " << Teuchos::TypeNameTraits<NT>::name () << ">";
359  return os.str ();
360  }
361 
362  template<class LO, class GO, class NT>
366  const Teuchos::ArrayView<int> &nodeIDs,
367  const Teuchos::ArrayView<LO> &localIDs,
368  const bool computeLIDs) const
369  {
370  using Teuchos::Array;
371  using Teuchos::ArrayRCP;
372  using Teuchos::ArrayView;
373  using Teuchos::as;
374  using Teuchos::Comm;
375  using Teuchos::RCP;
376 
378  RCP<const map_type> map = this->getMap ();
379  RCP<const Teuchos::Comm<int> > comm = map->getComm ();
380  const int myRank = comm->getRank ();
381 
382  // Map is on one process or is locally replicated.
383  typename ArrayView<int>::iterator procIter = nodeIDs.begin();
384  typename ArrayView<LO>::iterator lidIter = localIDs.begin();
385  typename ArrayView<const GO>::iterator gidIter;
386  for (gidIter = globalIDs.begin(); gidIter != globalIDs.end(); ++gidIter) {
387  if (map->isNodeGlobalElement (*gidIter)) {
388  *procIter++ = myRank;
389  if (computeLIDs) {
390  *lidIter++ = map->getLocalElement (*gidIter);
391  }
392  }
393  else {
394  // Advance the pointers, leaving these values set to invalid
395  procIter++;
396  if (computeLIDs) {
397  lidIter++;
398  }
399  res = IDNotPresent;
400  }
401  }
402  return res;
403  }
404 
405  template<class LO, class GO, class NT>
409  const Teuchos::ArrayView<int> &nodeIDs,
410  const Teuchos::ArrayView<LO> &localIDs,
411  const bool computeLIDs) const
412  {
413  using Teuchos::Array;
414  using Teuchos::ArrayRCP;
415  using Teuchos::ArrayView;
416  using Teuchos::as;
417  using Teuchos::Comm;
418  using Teuchos::RCP;
419 
420  const LO LINVALID = Teuchos::OrdinalTraits<LO>::invalid();
422 
423  RCP<const map_type> map = this->getMap ();
424  RCP<const Teuchos::Comm<int> > comm = map->getComm ();
425  const int numProcs = comm->getSize ();
426  const global_size_t nOverP = map->getGlobalNumElements () / numProcs;
427 
428  // Map is distributed but contiguous.
429  typename ArrayView<int>::iterator procIter = nodeIDs.begin();
430  typename ArrayView<LO>::iterator lidIter = localIDs.begin();
431  typename ArrayView<const GO>::iterator gidIter;
432  for (gidIter = globalIDs.begin(); gidIter != globalIDs.end(); ++gidIter) {
433  LO LID = LINVALID; // Assume not found until proven otherwise
434  int image = -1;
435  GO GID = *gidIter;
436  // Guess uniform distribution and start a little above it
437  // TODO: replace by a binary search
438  int curRank;
439  { // We go through all this trouble to avoid overflow and
440  // signed / unsigned casting mistakes (that were made in
441  // previous versions of this code).
442  const GO one = as<GO> (1);
443  const GO two = as<GO> (2);
444  const GO nOverP_GID = as<GO> (nOverP);
445  const GO lowerBound = GID / std::max(nOverP_GID, one) + two;
446  curRank = as<int>(std::min(lowerBound, as<GO>(numProcs - 1)));
447  }
448  bool found = false;
449  while (curRank >= 0 && curRank < numProcs) {
450  if (allMinGIDs_[curRank] <= GID) {
451  if (GID < allMinGIDs_[curRank + 1]) {
452  found = true;
453  break;
454  }
455  else {
456  curRank++;
457  }
458  }
459  else {
460  curRank--;
461  }
462  }
463  if (found) {
464  image = curRank;
465  LID = as<LO> (GID - allMinGIDs_[image]);
466  }
467  else {
468  res = IDNotPresent;
469  }
470  *procIter++ = image;
471  if (computeLIDs) {
472  *lidIter++ = LID;
473  }
474  }
475  return res;
476  }
477 
478  template<class LO, class GO, class NT>
481  Directory<LO, GO, NT> (map),
482  useHashTables_ (false) // to be revised below
483  {
484  using Teuchos::Array;
485  using Teuchos::ArrayView;
486  using Teuchos::as;
487  using Teuchos::RCP;
488  using Teuchos::rcp;
489  using Teuchos::typeName;
491 
492  // This class' implementation of getEntriesImpl() currently
493  // encodes the following assumptions:
494  //
495  // 1. global_size_t >= GO
496  // 2. global_size_t >= int
497  // 3. global_size_t >= LO
498  //
499  // We check these assumptions here.
500  TEUCHOS_TEST_FOR_EXCEPTION(sizeof(global_size_t) < sizeof(GO),
501  std::logic_error, typeName (*this) << ": sizeof(Tpetra::"
502  "global_size_t) = " << sizeof(global_size_t) << " < sizeof(Global"
503  "Ordinal = " << TypeNameTraits<LO>::name () << ") = " << sizeof(GO)
504  << ".");
505  TEUCHOS_TEST_FOR_EXCEPTION(sizeof(global_size_t) < sizeof(int),
506  std::logic_error, typeName (*this) << ": sizeof(Tpetra::"
507  "global_size_t) = " << sizeof(global_size_t) << " < sizeof(int) = "
508  << sizeof(int) << ".");
509  TEUCHOS_TEST_FOR_EXCEPTION(sizeof(global_size_t) < sizeof(LO),
510  std::logic_error, typeName (*this) << ": sizeof(Tpetra::"
511  "global_size_t) = " << sizeof(global_size_t) << " < sizeof(Local"
512  "Ordinal = " << TypeNameTraits<LO>::name () << ") = " << sizeof(LO)
513  << ".");
514 
515  RCP<const Teuchos::Comm<int> > comm = map->getComm ();
516  const LO LINVALID = Teuchos::OrdinalTraits<LO>::invalid ();
517  const GO minAllGID = map->getMinAllGlobalIndex ();
518  const GO maxAllGID = map->getMaxAllGlobalIndex ();
519 
520  // The "Directory Map" (see below) will have a range of elements
521  // from the minimum to the maximum GID of the user Map, and a
522  // minimum GID of minAllGID from the user Map. It doesn't
523  // actually have to store all those entries, though do beware of
524  // calling getNodeElementList on it (see Bug 5822).
525  const global_size_t numGlobalEntries = maxAllGID - minAllGID + 1;
526 
527  // We can't afford to replicate the whole directory on each
528  // process, so create the "Directory Map", a uniform contiguous
529  // Map that describes how we will distribute the directory over
530  // processes.
531  //
532  // FIXME (mfh 08 May 2012) Here we're setting minAllGID to be
533  // the index base. The index base should be separate from the
534  // minimum GID.
535  directoryMap_ = rcp (new map_type (numGlobalEntries, minAllGID, comm,
536  GloballyDistributed, map->getNode ()));
537  // The number of Directory elements that my process owns.
538  const size_t dir_numMyEntries = directoryMap_->getNodeNumElements ();
539 
540  // Fix for Bug 5822: If the input Map is "sparse," that is if
541  // the difference between the global min and global max GID is
542  // much larger than the global number of elements in the input
543  // Map, then it's possible that the Directory Map might have
544  // many more entries than the input Map on this process. This
545  // can cause memory scalability issues. In that case, we switch
546  // from the array-based implementation of Directory storage to
547  // the hash table - based implementation. We don't use hash
548  // tables all the time, because they are slower in the common
549  // case of a nonsparse Map.
550  //
551  // NOTE: This is a per-process decision. Some processes may use
552  // array-based storage, whereas others may use hash table -
553  // based storage.
554 #ifdef HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
555  // A hash table takes a constant factor more space, more or
556  // less, than an array. Thus, it's not worthwhile, even in
557  // terms of memory usage, always to use a hash table.
558  // Furthermore, array lookups are faster than hash table
559  // lookups, so it may be worthwhile to use an array even if it
560  // takes more space. The "sparsity threshold" governs when to
561  // switch to a hash table - based implementation.
562  const size_t inverseSparsityThreshold = 10;
563  useHashTables_ =
564  dir_numMyEntries >= inverseSparsityThreshold * map->getNodeNumElements ();
565 #endif // HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
566 
567  // Get list of process IDs that own the directory entries for the
568  // Map GIDs. These will be the targets of the sends that the
569  // Distributor will do.
570  const int myRank = comm->getRank ();
571  const size_t numMyEntries = map->getNodeNumElements ();
572  Array<int> sendImageIDs (numMyEntries);
573  ArrayView<const GO> myGlobalEntries = map->getNodeElementList ();
574  // An ID not present in this lookup indicates that it lies outside
575  // of the range [minAllGID,maxAllGID] (from map_). this means
576  // something is wrong with map_, our fault.
578  directoryMap_->getRemoteIndexList (myGlobalEntries, sendImageIDs) == IDNotPresent,
579  std::logic_error, Teuchos::typeName(*this) << " constructor: the "
580  "Directory Map could not find out where one or more of my Map's "
581  "elements should go. This probably means there is a bug in Map or "
582  "Directory. Please report this bug to the Tpetra developers.");
583 
584  // Initialize the distributor using the list of process IDs to
585  // which to send. We'll use the distributor to send out triples
586  // of (GID, process ID, LID). We're sending the entries to the
587  // processes that the Directory Map says should own them, which is
588  // why we called directoryMap_->getRemoteIndexList() above.
589  Distributor distor (comm);
590  const size_t numReceives = distor.createFromSends (sendImageIDs);
591 
592  // NOTE (mfh 21 Mar 2012) The following code assumes that
593  // sizeof(GO) >= sizeof(int) and sizeof(GO) >= sizeof(LO).
594  //
595  // Create and fill buffer of (GID, process ID, LID) triples to
596  // send out. We pack the (GID, process ID, LID) triples into a
597  // single Array of GO, casting the process ID from int to GO and
598  // the LID from LO to GO as we do so.
599  const int packetSize = 3; // We're sending triples, so packet size is 3.
600  Array<GO> exportEntries (packetSize * numMyEntries); // data to send out
601  {
602  typename Array<GO>::iterator iter = exportEntries.begin();
603  for (size_t i=0; i < numMyEntries; ++i) {
604  *iter++ = myGlobalEntries[i];
605  *iter++ = as<GO> (myRank);
606  *iter++ = as<GO> (i);
607  }
608  }
609  // Buffer of data to receive. The Distributor figured out for
610  // us how many packets we're receiving, when we called its
611  // createFromSends() method to set up the distribution plan.
612  Array<GO> importElements (packetSize * distor.getTotalReceiveLength ());
613 
614  // Distribute the triples of (GID, process ID, LID).
615  distor.doPostsAndWaits (exportEntries ().getConst (), packetSize, importElements ());
616 
617 #ifdef HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
618  // Unpack the redistributed data. Both implementations of
619  // Directory storage map from an LID in the Directory Map (which
620  // is the LID of the GID to store) to either a PID or an LID in
621  // the input Map. Each "packet" (contiguous chunk of
622  // importElements) contains a triple: (GID, PID, LID).
623  if (useHashTables_) {
624  // Create the hash tables. We know exactly how many elements
625  // to expect in each hash table. FixedHashTable's constructor
626  // currently requires all the keys and values at once, so we
627  // have to extract them in temporary arrays. It may be
628  // possible to rewrite FixedHashTable to use a "start fill" /
629  // "end fill" approach that avoids the temporary arrays, but
630  // we won't try that for now.
631 
632  // The constructors of Array and ArrayRCP that take a number
633  // of elements all initialize the arrays. Instead, allocate
634  // raw arrays, then hand them off to ArrayRCP, to avoid the
635  // initial unnecessary initialization without losing the
636  // benefit of exception safety (and bounds checking, in a
637  // debug build).
638  LO* tableKeysRaw = NULL;
639  LO* tableLidsRaw = NULL;
640  int* tablePidsRaw = NULL;
641  try {
642  tableKeysRaw = new LO [numReceives];
643  tableLidsRaw = new LO [numReceives];
644  tablePidsRaw = new int [numReceives];
645  } catch (...) {
646  if (tableKeysRaw != NULL) {
647  delete [] tableKeysRaw;
648  }
649  if (tableLidsRaw != NULL) {
650  delete [] tableLidsRaw;
651  }
652  if (tablePidsRaw != NULL) {
653  delete [] tablePidsRaw;
654  }
655  throw;
656  }
657  ArrayRCP<LO> tableKeys (tableKeysRaw, 0, numReceives, true);
658  ArrayRCP<LO> tableLids (tableLidsRaw, 0, numReceives, true);
659  ArrayRCP<int> tablePids (tablePidsRaw, 0, numReceives, true);
660 
661  // Fill the temporary arrays of keys and values.
662  typename Array<GO>::const_iterator iter = importElements.begin ();
663  for (size_t i = 0; i < numReceives; ++i) {
664  const GO curGID = *iter++;
665  const LO curLID = directoryMap_->getLocalElement (curGID);
666  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
667  Teuchos::typeName(*this) << " constructor: Incoming global index "
668  << curGID << " does not have a corresponding local index in the "
669  "Directory Map. Please report this bug to the Tpetra developers.");
670  tableKeys[i] = curLID;
671  tablePids[i] = *iter++;
672  tableLids[i] = *iter++;
673  }
674  // Set up the hash tables.
675  lidToPidTable_ =
676  rcp (new Details::FixedHashTable<LO, int> (tableKeys (),
677  tablePids ()));
678  lidToLidTable_ =
679  rcp (new Details::FixedHashTable<LO, LO> (tableKeys (),
680  tableLids ()));
681  }
682  else { // use array-based implementation of Directory storage
683  // Allocate arrays implementing Directory storage. Fill them
684  // with invalid values, in case the input Map's GID list is
685  // sparse (i.e., does not populate all GIDs from minAllGID to
686  // maxAllGID).
687  PIDs_ = arcp<int> (dir_numMyEntries);
688  std::fill (PIDs_.begin (), PIDs_.end (), -1);
689  LIDs_ = arcp<LO> (dir_numMyEntries);
690  std::fill (LIDs_.begin (), LIDs_.end (), LINVALID);
691  // Fill in the arrays with PIDs resp. LIDs.
692  typename Array<GO>::const_iterator iter = importElements.begin ();
693  for (size_t i = 0; i < numReceives; ++i) {
694  const GO curGID = *iter++;
695  const LO curLID = directoryMap_->getLocalElement (curGID);
696  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
697  Teuchos::typeName(*this) << " constructor: Incoming global index "
698  << curGID << " does not have a corresponding local index in the "
699  "Directory Map. Please report this bug to the Tpetra developers.");
700  PIDs_[curLID] = *iter++;
701  LIDs_[curLID] = *iter++;
702  }
703  }
704 #else // NOT HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
705  if (! useHashTables_) {
706  // Allocate arrays implementing Directory storage. Fill them
707  // with invalid values, in case the input Map's GID list is
708  // sparse (i.e., does not populate all GIDs from minAllGID to
709  // maxAllGID).
710  PIDs_ = arcp<int> (dir_numMyEntries);
711  std::fill (PIDs_.begin (), PIDs_.end (), -1);
712  LIDs_ = arcp<LO> (dir_numMyEntries);
713  std::fill (LIDs_.begin (), LIDs_.end (), LINVALID);
714  // Fill in the arrays with PIDs resp. LIDs.
715  typename Array<GO>::iterator iter = importElements.begin();
716  for (size_t i = 0; i < numReceives; ++i) {
717  const GO curGID = *iter++;
718  const LO curLID = directoryMap_->getLocalElement (curGID);
719  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
720  Teuchos::typeName(*this) << " constructor: Incoming global index "
721  << curGID << " does not have a corresponding local index in the "
722  "Directory Map. Please report this bug to the Tpetra developers.");
723  PIDs_[curLID] = *iter++;
724  LIDs_[curLID] = *iter++;
725  }
726  } else {
727  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Should never get here!");
728  }
729 #endif // HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
730  }
731 
732  template<class LO, class GO, class NT>
733  std::string
735  {
736  std::ostringstream os;
737  os << "DistributedNoncontiguousDirectory"
740  << ", " << Teuchos::TypeNameTraits<NT>::name () << ">";
741  return os.str ();
742  }
743 
744  template<class LO, class GO, class NT>
748  const Teuchos::ArrayView<int> &nodeIDs,
749  const Teuchos::ArrayView<LO> &localIDs,
750  const bool computeLIDs) const
751  {
752  using Teuchos::Array;
753  using Teuchos::ArrayRCP;
754  using Teuchos::ArrayView;
755  using Teuchos::as;
756  using Teuchos::RCP;
757 
758  const LO LINVALID = Teuchos::OrdinalTraits<LO>::invalid();
760 
761  RCP<const map_type> map = this->getMap ();
762  RCP<const Teuchos::Comm<int> > comm = map->getComm ();
763  const size_t numEntries = globalIDs.size ();
764 
765  //
766  // Set up directory structure.
767  //
768 
769  // If we're computing LIDs, we also have to include them in each
770  // packet, along with the GID and process ID.
771  const int packetSize = computeLIDs ? 3 : 2;
772 
773  // For data distribution, we use: Surprise! A Distributor!
774  Distributor distor (comm);
775 
776  // Get directory locations for the requested list of entries.
777  Array<int> dirImages (numEntries);
778  res = directoryMap_->getRemoteIndexList (globalIDs, dirImages ());
779  // Check for unfound globalIDs and set corresponding nodeIDs to -1
780  size_t numMissing = 0;
781  if (res == IDNotPresent) {
782  for (size_t i=0; i < numEntries; ++i) {
783  if (dirImages[i] == -1) {
784  nodeIDs[i] = -1;
785  if (computeLIDs) {
786  localIDs[i] = LINVALID;
787  }
788  numMissing++;
789  }
790  }
791  }
792 
793  Array<GO> sendGIDs;
794  Array<int> sendImages;
795  distor.createFromRecvs (globalIDs, dirImages (), sendGIDs, sendImages);
796  const size_t numSends = sendGIDs.size ();
797 
798  //
799  // mfh 13 Nov 2012:
800  //
801  // The code below temporarily stores LO, GO, and int values in
802  // an array of global_size_t. If one of the signed types (LO
803  // and GO should both be signed) happened to be -1 (or some
804  // negative number, but -1 is the one that came up today), then
805  // conversion to global_size_t will result in a huge
806  // global_size_t value, and thus conversion back may overflow.
807  // (Teuchos::as doesn't know that we meant it to be an LO or GO
808  // all along.)
809  //
810  // The overflow normally would not be a problem, since it would
811  // just go back to -1 again. However, Teuchos::as does range
812  // checking on conversions in a debug build, so it throws an
813  // exception (std::range_error) in this case. Range checking is
814  // generally useful in debug mode, so we don't want to disable
815  // this behavior globally.
816  //
817  // We solve this problem by forgoing use of Teuchos::as for the
818  // conversions below from LO, GO, or int to global_size_t, and
819  // the later conversions back from global_size_t to LO, GO, or
820  // int.
821  //
822  // I've recorded this discussion as Bug 5760.
823  //
824 
825  // global_size_t >= GO
826  // global_size_t >= size_t >= int
827  // global_size_t >= size_t >= LO
828  // Therefore, we can safely store all of these in a global_size_t
829  Array<global_size_t> exports (packetSize * numSends);
830  {
831  // Packet format:
832  // - If computing LIDs: (GID, PID, LID)
833  // - Otherwise: (GID, PID)
834  //
835  // "PID" means "process ID" (a.k.a. "node ID," a.k.a. "rank").
836  typename Array<global_size_t>::iterator exportsIter = exports.begin();
837  typename Array<GO>::const_iterator gidIter = sendGIDs.begin();
838 
839 #ifdef HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
840  if (useHashTables_) {
841  for ( ; gidIter != sendGIDs.end(); ++gidIter) {
842  const GO curGID = *gidIter;
843  // Don't use as() here (see above note).
844  *exportsIter++ = static_cast<global_size_t> (curGID);
845  const LO curLID = directoryMap_->getLocalElement (curGID);
846  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
847  Teuchos::typeName (*this) << "::getEntriesImpl(): The Directory "
848  "Map's global index " << curGID << " does not have a corresponding "
849  "local index. Please report this bug to the Tpetra developers.");
850  // Don't use as() here (see above note).
851  *exportsIter++ = static_cast<global_size_t> (lidToPidTable_->get (curLID));
852  if (computeLIDs) {
853  // Don't use as() here (see above note).
854  *exportsIter++ = static_cast<global_size_t> (lidToLidTable_->get (curLID));
855  }
856  }
857  } else {
858  for ( ; gidIter != sendGIDs.end(); ++gidIter) {
859  const GO curGID = *gidIter;
860  // Don't use as() here (see above note).
861  *exportsIter++ = static_cast<global_size_t> (curGID);
862  const LO curLID = directoryMap_->getLocalElement (curGID);
863  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
864  Teuchos::typeName (*this) << "::getEntriesImpl(): The Directory "
865  "Map's global index " << curGID << " does not have a corresponding "
866  "local index. Please report this bug to the Tpetra developers.");
867  // Don't use as() here (see above note).
868  *exportsIter++ = static_cast<global_size_t> (PIDs_[curLID]);
869  if (computeLIDs) {
870  // Don't use as() here (see above note).
871  *exportsIter++ = static_cast<global_size_t> (LIDs_[curLID]);
872  }
873  }
874  }
875 #else // NOT HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
876  for ( ; gidIter != sendGIDs.end (); ++gidIter) {
877  const GO curGID = *gidIter;
878  // Don't use as() here (see above note).
879  *exportsIter++ = static_cast<global_size_t> (curGID);
880  const LO curLID = directoryMap_->getLocalElement (curGID);
881  TEUCHOS_TEST_FOR_EXCEPTION(curLID == LINVALID, std::logic_error,
882  Teuchos::typeName (*this) << "::getEntriesImpl(): The Directory "
883  "Map's global index " << curGID << " does not have a corresponding "
884  "local index. Please report this bug to the Tpetra developers.");
885  // Don't use as() here (see above note).
886  *exportsIter++ = static_cast<global_size_t> (PIDs_[curLID]);
887  if (computeLIDs) {
888  // Don't use as() here (see above note).
889  *exportsIter++ = static_cast<global_size_t> (LIDs_[curLID]);
890  }
891  }
892 #endif // HAVE_TPETRA_DIRECTORY_SPARSE_MAP_FIX
893  }
894 
895  Array<global_size_t> imports (packetSize * distor.getTotalReceiveLength ());
896  distor.doPostsAndWaits (exports ().getConst (), packetSize, imports ());
897 
898  //
899  // mfh 13 Nov 2012: See note above on conversions between
900  // global_size_t and LO, GO, or int.
901  //
902  typename Array<global_size_t>::iterator ptr = imports.begin();
903  const size_t numRecv = numEntries - numMissing;
904 
905  Array<GO> sortedIDs (globalIDs);
906  ArrayRCP<GO> offset = arcp<GO> (numEntries);
907  GO ii=0;
908  for (typename ArrayRCP<GO>::iterator oo = offset.begin();
909  oo != offset.end(); ++oo, ++ii) {
910  *oo = ii;
911  }
912  sort2 (sortedIDs.begin(), sortedIDs.begin() + numEntries, offset.begin());
913 
914  typedef typename Array<GO>::iterator IT;
915  // we know these conversions are in range, because we loaded this data
916  for (size_t i = 0; i < numRecv; ++i) {
917  // Don't use as() here (see above note).
918  const GO curGID = static_cast<GO> (*ptr++);
919  std::pair<IT, IT> p1 = std::equal_range (sortedIDs.begin(), sortedIDs.end(), curGID);
920  if (p1.first != p1.second) {
921  const size_t j = p1.first - sortedIDs.begin();
922  // Don't use as() here (see above note).
923  nodeIDs[offset[j]] = static_cast<int> (*ptr++);
924  if (computeLIDs) {
925  // Don't use as() here (see above note).
926  localIDs[offset[j]] = static_cast<LO> (*ptr++);
927  }
928  if (nodeIDs[offset[j]] == -1) {
929  res = IDNotPresent;
930  }
931  }
932  }
933  return res;
934  }
935  } // namespace Details
936 } // namespace Tpetra
937 
938 //
939 // Explicit instantiation macro
940 //
941 // Must be expanded from within the Tpetra::Details namespace!
942 //
943 #define TPETRA_DIRECTORY_IMPL_INSTANT(LO,GO,NODE) \
944  template class Directory< LO , GO , NODE >; \
945  template class ReplicatedDirectory< LO , GO , NODE >; \
946  template class DistributedContiguousDirectory< LO , GO , NODE >; \
947  template class DistributedNoncontiguousDirectory< LO , GO , NODE >; \
948 
949 
950 #endif // __Tpetra_DirectoryImpl_def_hpp
Namespace Tpetra contains the class and methods constituting the Tpetra library.
LookupStatus getEntries(const Teuchos::ArrayView< const GlobalOrdinal > &globalIDs, const Teuchos::ArrayView< int > &nodeIDs, const Teuchos::ArrayView< LocalOrdinal > &localIDs, const bool computeLIDs) const
std::string description() const
A one-line human-readable description of this object.
bool isNodeGlobalElement(GlobalOrdinal globalIndex) const
Whether the given global index is valid for this Map on this process.
const Teuchos::RCP< const Teuchos::Comm< int > > & getComm() const
Accessors for the Teuchos::Comm and Kokkos Node objects.
iterator begin() const
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
size_type size() const
Implementation of Directory for a distributed noncontiguous Map.
Implementation of Directory for a distributed contiguous Map.
GlobalOrdinal getMinAllGlobalIndex() const
The minimum global index over all processes in the communicator.
LookupStatus getEntriesImpl(const Teuchos::ArrayView< const GlobalOrdinal > &globalIDs, const Teuchos::ArrayView< int > &nodeIDs, const Teuchos::ArrayView< LocalOrdinal > &localIDs, const bool computeLIDs) const
Find process IDs and (optionally) local IDs for the given global IDs.
Implementation details of Tpetra.
size_t global_size_t
Global size_t object.
T * getRawPtr() const
void doPostsAndWaits(const ArrayView< const Packet > &exports, size_t numPackets, const ArrayView< Packet > &imports)
Execute the (forward) communication plan.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
LookupStatus getEntriesImpl(const Teuchos::ArrayView< const GlobalOrdinal > &globalIDs, const Teuchos::ArrayView< int > &nodeIDs, const Teuchos::ArrayView< LocalOrdinal > &localIDs, const bool computeLIDs) const
Find process IDs and (optionally) local IDs for the given global IDs.
Sets up and executes a communication plan for a Tpetra DistObject.
size_t getTotalReceiveLength() const
Total number of values this process will receive from other processes.
Directory()
Empty constructor for post-constructor initialization.
LookupStatus getEntriesImpl(const Teuchos::ArrayView< const GlobalOrdinal > &globalIDs, const Teuchos::ArrayView< int > &nodeIDs, const Teuchos::ArrayView< LocalOrdinal > &localIDs, const bool computeLIDs) const
Find process IDs and (optionally) local IDs for the given global IDs.
LookupStatus getEntriesImpl(const Teuchos::ArrayView< const GlobalOrdinal > &globalIDs, const Teuchos::ArrayView< int > &nodeIDs, const Teuchos::ArrayView< LocalOrdinal > &localIDs, const bool computeLIDs) const
Find process IDs and (optionally) local IDs for the given global IDs.
iterator end()
std::vector< T >::const_iterator const_iterator
std::string description() const
A one-line human-readable description of this object.
std::string description() const
A one-line human-readable description of this object.
LocalOrdinal getLocalElement(GlobalOrdinal globalIndex) const
The local index corresponding to the given global index.
void sort2(const IT1 &first1, const IT1 &last1, const IT2 &first2)
Sort the first array, and apply the resulting permutation to the second array.
Describes a parallel distribution of objects over processes.
Computes the local ID and process ID corresponding to given global IDs.
std::string description() const
A one-line human-readable description of this object.
iterator end() const
size_type size() const
TypeTo as(const TypeFrom &t)
iterator end() const
Teuchos::RCP< const map_type > getMap() const
Get the Map with which this object was created.
const T & getConst(T &t)
Implementation of Directory for a contiguous, uniformly distributed Map.
std::vector< T >::iterator iterator
iterator begin()
void createFromRecvs(const ArrayView< const Ordinal > &remoteIDs, const ArrayView< const int > &remoteNodeIDs, Array< Ordinal > &exportIDs, Array< int > &exportNodeIDs)
Set up Distributor using list of process ranks from which to receive.
iterator begin() const
global_size_t getGlobalNumElements() const
The number of elements in this Map.
static std::string name()
std::string typeName(const T &t)
ReplicatedDirectory(const Teuchos::RCP< const map_type > &map)
Constructor.
bool is_null() const