Tpetra Matrix/Vector Services  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
Tpetra_Distributor.cpp
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 #include "Tpetra_Distributor.hpp"
43 #include "Teuchos_StandardParameterEntryValidators.hpp"
44 #include "Teuchos_VerboseObjectParameterListHelpers.hpp"
45 
46 
47 namespace Tpetra {
48  namespace Details {
49  std::string
50  DistributorSendTypeEnumToString (EDistributorSendType sendType)
51  {
52  if (sendType == DISTRIBUTOR_ISEND) {
53  return "Isend";
54  }
55  else if (sendType == DISTRIBUTOR_RSEND) {
56  return "Rsend";
57  }
58  else if (sendType == DISTRIBUTOR_SEND) {
59  return "Send";
60  }
61  else if (sendType == DISTRIBUTOR_SSEND) {
62  return "Ssend";
63  }
64  else {
65  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, "Invalid "
66  "EDistributorSendType enum value " << sendType << ".");
67  }
68  }
69  } // namespace Details
70 
71  Array<std::string>
73  {
74  Array<std::string> sendTypes;
75  sendTypes.push_back ("Isend");
76  sendTypes.push_back ("Rsend");
77  sendTypes.push_back ("Send");
78  sendTypes.push_back ("Ssend");
79  return sendTypes;
80  }
81 
82  // We set default values of Distributor's Boolean parameters here,
83  // in this one place. That way, if we want to change the default
84  // value of a parameter, we don't have to search the whole file to
85  // ensure a consistent setting.
86  namespace {
87  // Default value of the "Debug" parameter.
88  const bool tpetraDistributorDebugDefault = false;
89  // Default value of the "Barrier between receives and sends" parameter.
90  const bool barrierBetween_default = false;
91  // Default value of the "Use distinct tags" parameter.
92  const bool useDistinctTags_default = true;
93  } // namespace (anonymous)
94 
95  int Distributor::getTag (const int pathTag) const {
96  return useDistinctTags_ ? pathTag : comm_->getTag ();
97  }
98 
99 
100 #ifdef TPETRA_DISTRIBUTOR_TIMERS
101  void Distributor::makeTimers () {
102  const std::string name_doPosts3 = "Tpetra::Distributor: doPosts(3)";
103  const std::string name_doPosts4 = "Tpetra::Distributor: doPosts(4)";
104  const std::string name_doWaits = "Tpetra::Distributor: doWaits";
105  const std::string name_doPosts3_recvs = "Tpetra::Distributor: doPosts(3): recvs";
106  const std::string name_doPosts4_recvs = "Tpetra::Distributor: doPosts(4): recvs";
107  const std::string name_doPosts3_barrier = "Tpetra::Distributor: doPosts(3): barrier";
108  const std::string name_doPosts4_barrier = "Tpetra::Distributor: doPosts(4): barrier";
109  const std::string name_doPosts3_sends = "Tpetra::Distributor: doPosts(3): sends";
110  const std::string name_doPosts4_sends = "Tpetra::Distributor: doPosts(4): sends";
111 
112  timer_doPosts3_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts3);
113  timer_doPosts4_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts4);
114  timer_doWaits_ = Teuchos::TimeMonitor::getNewTimer (name_doWaits);
115  timer_doPosts3_recvs_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts3_recvs);
116  timer_doPosts4_recvs_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts4_recvs);
117  timer_doPosts3_barrier_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts3_barrier);
118  timer_doPosts4_barrier_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts4_barrier);
119  timer_doPosts3_sends_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts3_sends);
120  timer_doPosts4_sends_ = Teuchos::TimeMonitor::getNewTimer (name_doPosts4_sends);
121  }
122 #endif // TPETRA_DISTRIBUTOR_TIMERS
123 
124  void
125  Distributor::init (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
126  const Teuchos::RCP<Teuchos::ParameterList>& plist)
127  {
128  this->setVerbLevel (debug_ ? Teuchos::VERB_EXTREME : Teuchos::VERB_NONE);
129  this->setOStream (out_);
130  if (! plist.is_null ()) {
131  // The input parameters may override the above verbosity level
132  // setting, if there is a "VerboseObject" sublist.
133  this->setParameterList (plist);
134  }
135 
136 #ifdef TPETRA_DISTRIBUTOR_TIMERS
137  makeTimers ();
138 #endif // TPETRA_DISTRIBUTOR_TIMERS
139 
140  if (debug_) {
141  Teuchos::OSTab tab (out_);
142  std::ostringstream os;
143  os << comm_->getRank ()
144  << ": Distributor ctor done" << std::endl;
145  *out_ << os.str ();
146  }
147  }
148 
149  Distributor::Distributor (const Teuchos::RCP<const Teuchos::Comm<int> >& comm)
150  : comm_ (comm)
151  , out_ (Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr)))
152  , sendType_ (Details::DISTRIBUTOR_SEND)
153  , barrierBetween_ (barrierBetween_default)
154  , debug_ (tpetraDistributorDebugDefault)
155  , numExports_ (0)
156  , selfMessage_ (false)
157  , numSends_ (0)
158  , maxSendLength_ (0)
159  , numReceives_ (0)
160  , totalReceiveLength_ (0)
161  , useDistinctTags_ (useDistinctTags_default)
162  {
163  init (comm, Teuchos::null);
164  }
165 
166  Distributor::Distributor (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
167  const Teuchos::RCP<Teuchos::FancyOStream>& out)
168  : comm_ (comm)
169  , out_ (out.is_null () ? Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr)) : out)
170  , sendType_ (Details::DISTRIBUTOR_SEND)
171  , barrierBetween_ (barrierBetween_default)
172  , debug_ (tpetraDistributorDebugDefault)
173  , numExports_ (0)
174  , selfMessage_ (false)
175  , numSends_ (0)
176  , maxSendLength_ (0)
177  , numReceives_ (0)
178  , totalReceiveLength_ (0)
179  , useDistinctTags_ (useDistinctTags_default)
180  {
181  init (comm, Teuchos::null);
182  }
183 
184  Distributor::Distributor (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
185  const Teuchos::RCP<Teuchos::ParameterList>& plist)
186  : comm_ (comm)
187  , out_ (Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr)))
188  , sendType_ (Details::DISTRIBUTOR_SEND)
189  , barrierBetween_ (barrierBetween_default)
190  , debug_ (tpetraDistributorDebugDefault)
191  , numExports_ (0)
192  , selfMessage_ (false)
193  , numSends_ (0)
194  , maxSendLength_ (0)
195  , numReceives_ (0)
196  , totalReceiveLength_ (0)
197  , useDistinctTags_ (useDistinctTags_default)
198  {
199  init (comm, plist);
200  }
201 
202  Distributor::Distributor (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
203  const Teuchos::RCP<Teuchos::FancyOStream>& out,
204  const Teuchos::RCP<Teuchos::ParameterList>& plist)
205  : comm_ (comm)
206  , out_ (out.is_null () ? Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr)) : out)
207  , sendType_ (Details::DISTRIBUTOR_SEND)
208  , barrierBetween_ (barrierBetween_default)
209  , debug_ (tpetraDistributorDebugDefault)
210  , numExports_ (0)
211  , selfMessage_ (false)
212  , numSends_ (0)
213  , maxSendLength_ (0)
214  , numReceives_ (0)
215  , totalReceiveLength_ (0)
216  , useDistinctTags_ (useDistinctTags_default)
217  {
218  init (comm, plist);
219  }
220 
221  Distributor::Distributor (const Distributor & distributor)
222  : comm_ (distributor.comm_)
223  , out_ (distributor.out_)
224  , sendType_ (distributor.sendType_)
225  , barrierBetween_ (distributor.barrierBetween_)
226  , debug_ (distributor.debug_)
227  , numExports_ (distributor.numExports_)
228  , selfMessage_ (distributor.selfMessage_)
229  , numSends_ (distributor.numSends_)
230  , imagesTo_ (distributor.imagesTo_)
231  , startsTo_ (distributor.startsTo_)
232  , lengthsTo_ (distributor.lengthsTo_)
233  , maxSendLength_ (distributor.maxSendLength_)
234  , indicesTo_ (distributor.indicesTo_)
235  , numReceives_ (distributor.numReceives_)
236  , totalReceiveLength_ (distributor.totalReceiveLength_)
237  , lengthsFrom_ (distributor.lengthsFrom_)
238  , imagesFrom_ (distributor.imagesFrom_)
239  , startsFrom_ (distributor.startsFrom_)
240  , indicesFrom_ (distributor.indicesFrom_)
241  , reverseDistributor_ (distributor.reverseDistributor_)
242  , useDistinctTags_ (distributor.useDistinctTags_)
243  {
244  using Teuchos::ParameterList;
245  using Teuchos::parameterList;
246  using Teuchos::RCP;
247  using Teuchos::rcp;
248 
249  this->setVerbLevel (distributor.getVerbLevel ());
250  this->setOStream (out_);
251  // The input parameters may override the above verbosity level
252  // setting, if there is a "VerboseObject" sublist.
253  //
254  // Clone the right-hand side's ParameterList, so that this' list
255  // is decoupled from the right-hand side's list. We don't need to
256  // do validation, since the right-hand side already has validated
257  // its parameters, so just call setMyParamList(). Note that this
258  // won't work if the right-hand side doesn't have a list set yet,
259  // so we first check for null.
260  RCP<const ParameterList> rhsList = distributor.getParameterList ();
261  if (! rhsList.is_null ()) {
262  this->setMyParamList (parameterList (* rhsList));
263  }
264 
265 #ifdef TPETRA_DISTRIBUTOR_TIMERS
266  makeTimers ();
267 #endif // TPETRA_DISTRIBUTOR_TIMERS
268 
269  if (debug_) {
270  Teuchos::OSTab tab (out_);
271  std::ostringstream os;
272  os << comm_->getRank ()
273  << ": Distributor copy ctor done" << std::endl;
274  *out_ << os.str ();
275  }
276  }
277 
279  using Teuchos::ParameterList;
280  using Teuchos::parameterList;
281  using Teuchos::RCP;
282 
283  std::swap (comm_, rhs.comm_);
284  std::swap (out_, rhs.out_);
285  std::swap (sendType_, rhs.sendType_);
286  std::swap (barrierBetween_, rhs.barrierBetween_);
287  std::swap (debug_, rhs.debug_);
288  std::swap (numExports_, rhs.numExports_);
289  std::swap (selfMessage_, rhs.selfMessage_);
290  std::swap (numSends_, rhs.numSends_);
291  std::swap (imagesTo_, rhs.imagesTo_);
292  std::swap (startsTo_, rhs.startsTo_);
293  std::swap (lengthsTo_, rhs.lengthsTo_);
294  std::swap (maxSendLength_, rhs.maxSendLength_);
295  std::swap (indicesTo_, rhs.indicesTo_);
296  std::swap (numReceives_, rhs.numReceives_);
297  std::swap (totalReceiveLength_, rhs.totalReceiveLength_);
298  std::swap (lengthsFrom_, rhs.lengthsFrom_);
299  std::swap (imagesFrom_, rhs.imagesFrom_);
300  std::swap (startsFrom_, rhs.startsFrom_);
301  std::swap (indicesFrom_, rhs.indicesFrom_);
302  std::swap (reverseDistributor_, rhs.reverseDistributor_);
303  std::swap (useDistinctTags_, rhs.useDistinctTags_);
304 
305  // Swap verbosity levels.
306  const Teuchos::EVerbosityLevel lhsVerb = this->getVerbLevel ();
307  const Teuchos::EVerbosityLevel rhsVerb = rhs.getVerbLevel ();
308  this->setVerbLevel (rhsVerb);
309  rhs.setVerbLevel (lhsVerb);
310 
311  // Swap output streams. We've swapped out_ above, but we have to
312  // tell the parent class VerboseObject about the swap.
313  this->setOStream (out_);
314  rhs.setOStream (rhs.out_);
315 
316  // Swap parameter lists. If they are the same object, make a deep
317  // copy first, so that modifying one won't modify the other one.
318  RCP<ParameterList> lhsList = this->getNonconstParameterList ();
319  RCP<ParameterList> rhsList = rhs.getNonconstParameterList ();
320  if (lhsList.getRawPtr () == rhsList.getRawPtr () && ! rhsList.is_null ()) {
321  rhsList = parameterList (*rhsList);
322  }
323  if (! rhsList.is_null ()) {
324  this->setMyParamList (rhsList);
325  }
326  if (! lhsList.is_null ()) {
327  rhs.setMyParamList (lhsList);
328  }
329 
330  // We don't need to swap timers, because all instances of
331  // Distributor use the same timers.
332  }
333 
335  {
336  // We shouldn't have any outstanding communication requests at
337  // this point.
338  TEUCHOS_TEST_FOR_EXCEPTION(requests_.size() != 0, std::runtime_error,
339  "Tpetra::Distributor: Destructor called with " << requests_.size()
340  << " outstanding posts (unfulfilled communication requests). There "
341  "should be none at this point. Please report this bug to the Tpetra "
342  "developers.");
343  }
344 
345  void
346  Distributor::setParameterList (const Teuchos::RCP<Teuchos::ParameterList>& plist)
347  {
348  using Teuchos::FancyOStream;
349  using Teuchos::getIntegralValue;
350  using Teuchos::includesVerbLevel;
351  using Teuchos::OSTab;
352  using Teuchos::ParameterList;
353  using Teuchos::parameterList;
354  using Teuchos::RCP;
355  using std::endl;
356 
357  RCP<const ParameterList> validParams = getValidParameters ();
358  plist->validateParametersAndSetDefaults (*validParams);
359 
360  const bool barrierBetween =
361  plist->get<bool> ("Barrier between receives and sends");
362  const Details::EDistributorSendType sendType =
363  getIntegralValue<Details::EDistributorSendType> (*plist, "Send type");
364  const bool useDistinctTags = plist->get<bool> ("Use distinct tags");
365  const bool debug = plist->get<bool> ("Debug");
366 
367  // We check this property explicitly, since we haven't yet learned
368  // how to make a validator that can cross-check properties.
369  // Later, turn this into a validator so that it can be embedded in
370  // the valid ParameterList and used in Optika.
371  TEUCHOS_TEST_FOR_EXCEPTION(
372  ! barrierBetween && sendType == Details::DISTRIBUTOR_RSEND,
373  std::invalid_argument, "Tpetra::Distributor::setParameterList: " << endl
374  << "You specified \"Send type\"=\"Rsend\", but turned off the barrier "
375  "between receives and sends." << endl << "This is invalid; you must "
376  "include the barrier if you use ready sends." << endl << "Ready sends "
377  "require that their corresponding receives have already been posted, "
378  "and the only way to guarantee that in general is with a barrier.");
379 
380  if (plist->isSublist ("VerboseObject")) {
381  // Read the "VerboseObject" sublist for (optional) verbosity
382  // settings. We've set defaults already in Distributor's
383  // constructor, so we don't need this sublist to exist.
384  Teuchos::readVerboseObjectSublist (&*plist, this);
385  }
386 
387  // Now that we've validated the input list, save the results.
388  sendType_ = sendType;
389  barrierBetween_ = barrierBetween;
390  useDistinctTags_ = useDistinctTags;
391  debug_ = debug;
392 
393  // ParameterListAcceptor semantics require pointer identity of the
394  // sublist passed to setParameterList(), so we save the pointer.
395  this->setMyParamList (plist);
396  }
397 
398  Teuchos::RCP<const Teuchos::ParameterList>
400  {
401  using Teuchos::Array;
402  using Teuchos::ParameterList;
403  using Teuchos::parameterList;
404  using Teuchos::RCP;
405  using Teuchos::setStringToIntegralParameter;
406 
407  const bool barrierBetween = barrierBetween_default;
408  const bool useDistinctTags = useDistinctTags_default;
409  const bool debug = tpetraDistributorDebugDefault;
410 
411  Array<std::string> sendTypes = distributorSendTypes ();
412  const std::string defaultSendType ("Send");
413  Array<Details::EDistributorSendType> sendTypeEnums;
414  sendTypeEnums.push_back (Details::DISTRIBUTOR_ISEND);
415  sendTypeEnums.push_back (Details::DISTRIBUTOR_RSEND);
416  sendTypeEnums.push_back (Details::DISTRIBUTOR_SEND);
417  sendTypeEnums.push_back (Details::DISTRIBUTOR_SSEND);
418 
419  RCP<ParameterList> plist = parameterList ("Tpetra::Distributor");
420  plist->set ("Barrier between receives and sends", barrierBetween,
421  "Whether to execute a barrier between receives and sends in do"
422  "[Reverse]Posts(). Required for correctness when \"Send type\""
423  "=\"Rsend\", otherwise correct but not recommended.");
424  setStringToIntegralParameter<Details::EDistributorSendType> ("Send type",
425  defaultSendType, "When using MPI, the variant of send to use in "
426  "do[Reverse]Posts()", sendTypes(), sendTypeEnums(), plist.getRawPtr());
427  plist->set ("Use distinct tags", useDistinctTags, "Whether to use distinct "
428  "MPI message tags for different code paths.");
429  plist->set ("Debug", debug, "Whether to print copious debugging output on "
430  "all processes.");
431 
432  Teuchos::setupVerboseObjectSublist (&*plist);
433  return Teuchos::rcp_const_cast<const ParameterList> (plist);
434  }
435 
436 
438  { return totalReceiveLength_; }
439 
441  { return numReceives_; }
442 
444  { return selfMessage_; }
445 
447  { return numSends_; }
448 
450  { return maxSendLength_; }
451 
452  Teuchos::ArrayView<const int> Distributor::getImagesFrom() const
453  { return imagesFrom_; }
454 
455  Teuchos::ArrayView<const size_t> Distributor::getLengthsFrom() const
456  { return lengthsFrom_; }
457 
458  Teuchos::ArrayView<const int> Distributor::getImagesTo() const
459  { return imagesTo_; }
460 
461  Teuchos::ArrayView<const size_t> Distributor::getLengthsTo() const
462  { return lengthsTo_; }
463 
464  const Teuchos::RCP<Distributor> &
466  if (reverseDistributor_ == Teuchos::null) {
467  // need to create reverse distributor
468  createReverseDistributor();
469  }
470  return reverseDistributor_;
471  }
472 
473 
474  void
475  Distributor::createReverseDistributor() const
476  {
477  reverseDistributor_ = Teuchos::rcp (new Distributor (comm_));
478 
479  // The total length of all the sends of this Distributor. We
480  // calculate it because it's the total length of all the receives
481  // of the reverse Distributor.
482  size_t totalSendLength =
483  std::accumulate (lengthsTo_.begin(), lengthsTo_.end(), 0);
484 
485  // The maximum length of any of the receives of this Distributor.
486  // We calculate it because it's the maximum length of any of the
487  // sends of the reverse Distributor.
488  size_t maxReceiveLength = 0;
489  const int myImageID = comm_->getRank();
490  for (size_t i=0; i < numReceives_; ++i) {
491  if (imagesFrom_[i] != myImageID) {
492  // Don't count receives for messages sent by myself to myself.
493  if (lengthsFrom_[i] > maxReceiveLength) {
494  maxReceiveLength = lengthsFrom_[i];
495  }
496  }
497  }
498 
499  // Initialize all of reverseDistributor's data members. This
500  // mainly just involves flipping "send" and "receive," or the
501  // equivalent "to" and "from."
502  reverseDistributor_->lengthsTo_ = lengthsFrom_;
503  reverseDistributor_->imagesTo_ = imagesFrom_;
504  reverseDistributor_->indicesTo_ = indicesFrom_;
505  reverseDistributor_->startsTo_ = startsFrom_;
506  reverseDistributor_->lengthsFrom_ = lengthsTo_;
507  reverseDistributor_->imagesFrom_ = imagesTo_;
508  reverseDistributor_->indicesFrom_ = indicesTo_;
509  reverseDistributor_->startsFrom_ = startsTo_;
510  reverseDistributor_->numSends_ = numReceives_;
511  reverseDistributor_->numReceives_ = numSends_;
512  reverseDistributor_->selfMessage_ = selfMessage_;
513  reverseDistributor_->maxSendLength_ = maxReceiveLength;
514  reverseDistributor_->totalReceiveLength_ = totalSendLength;
515  // Note: technically, I am my reverse distributor's reverse distributor, but
516  // we will not set this up, as it gives us an opportunity to test
517  // that reverseDistributor is an inverse operation w.r.t. value semantics of distributors
518  // Note: numExports_ was not copied
519  }
520 
521 
523  using Teuchos::Array;
524  using Teuchos::CommRequest;
525  using Teuchos::FancyOStream;
526  using Teuchos::includesVerbLevel;
527  using Teuchos::is_null;
528  using Teuchos::OSTab;
529  using Teuchos::RCP;
530  using Teuchos::waitAll;
531  using std::endl;
532 
533  Teuchos::OSTab tab (out_);
534 
535 #ifdef TPETRA_DISTRIBUTOR_TIMERS
536  Teuchos::TimeMonitor timeMon (*timer_doWaits_);
537 #endif // TPETRA_DISTRIBUTOR_TIMERS
538 
539  const int myRank = comm_->getRank ();
540 
541  if (debug_) {
542  std::ostringstream os;
543  os << myRank << ": doWaits: # reqs = "
544  << requests_.size () << endl;
545  *out_ << os.str ();
546  }
547 
548  if (requests_.size() > 0) {
549  waitAll (*comm_, requests_());
550 
551 #ifdef HAVE_TEUCHOS_DEBUG
552  // Make sure that waitAll() nulled out all the requests.
553  for (Array<RCP<CommRequest<int> > >::const_iterator it = requests_.begin();
554  it != requests_.end(); ++it)
555  {
556  TEUCHOS_TEST_FOR_EXCEPTION( ! is_null (*it), std::runtime_error,
557  Teuchos::typeName(*this) << "::doWaits(): Communication requests "
558  "should all be null aftr calling Teuchos::waitAll() on them, but "
559  "at least one request is not null.");
560  }
561 #endif // HAVE_TEUCHOS_DEBUG
562  // Restore the invariant that requests_.size() is the number of
563  // outstanding nonblocking communication requests.
564  requests_.resize (0);
565  }
566 
567 #ifdef HAVE_TEUCHOS_DEBUG
568  {
569  const int localSizeNonzero = (requests_.size () != 0) ? 1 : 0;
570  int globalSizeNonzero = 0;
571  Teuchos::reduceAll<int, int> (*comm_, Teuchos::REDUCE_MAX,
572  localSizeNonzero,
573  Teuchos::outArg (globalSizeNonzero));
574  TEUCHOS_TEST_FOR_EXCEPTION(
575  globalSizeNonzero != 0, std::runtime_error,
576  "Tpetra::Distributor::doWaits: After waitAll, at least one process has "
577  "a nonzero number of outstanding posts. There should be none at this "
578  "point. Please report this bug to the Tpetra developers.");
579  }
580 #endif // HAVE_TEUCHOS_DEBUG
581 
582  if (debug_) {
583  std::ostringstream os;
584  os << myRank << ": doWaits done" << endl;
585  *out_ << os.str ();
586  }
587  }
588 
590  // call doWaits() on the reverse Distributor, if it exists
591  if (! reverseDistributor_.is_null()) {
592  reverseDistributor_->doWaits();
593  }
594  }
595 
596  std::string Distributor::description() const {
597  std::ostringstream oss;
598  oss << Teuchos::Describable::description();
599  return oss.str();
600  }
601 
602  void
603  Distributor::describe (Teuchos::FancyOStream &out,
604  const Teuchos::EVerbosityLevel verbLevel) const
605  {
606  using std::endl;
607  using std::setw;
608  using Teuchos::VERB_DEFAULT;
609  using Teuchos::VERB_NONE;
610  using Teuchos::VERB_LOW;
611  using Teuchos::VERB_MEDIUM;
612  using Teuchos::VERB_HIGH;
613  using Teuchos::VERB_EXTREME;
614  Teuchos::EVerbosityLevel vl = verbLevel;
615  if (vl == VERB_DEFAULT) vl = VERB_LOW;
616  const int myImageID = comm_->getRank();
617  const int numImages = comm_->getSize();
618  Teuchos::OSTab tab (out);
619 
620  if (vl == VERB_NONE) {
621  return;
622  } else {
623  if (myImageID == 0) {
624  // VERB_LOW and higher prints description() (on Proc 0 only).
625  // We quote the class name because it contains colons:
626  // quoting makes the output valid YAML.
627  out << "\"Tpetra::Distributor\":" << endl;
628  Teuchos::OSTab tab2 (out);
629  const std::string label = this->getObjectLabel ();
630  if (label != "") {
631  out << "Label: " << label << endl;
632  }
633  out << "Parameters: " << endl;
634  {
635  Teuchos::OSTab tab3 (out);
636  out << "\"Send type\": "
637  << DistributorSendTypeEnumToString (sendType_) << endl
638  << "\"Barrier between receives and sends\": "
639  << (barrierBetween_ ? "true" : "false") << endl;
640  out << "\"Use distinct tags\": "
641  << (useDistinctTags_ ? "true" : "false") << endl;
642  out << "\"Debug\": " << (debug_ ? "true" : "false") << endl;
643  }
644  }
645  if (vl == VERB_LOW) {
646  return;
647  } else {
648  Teuchos::OSTab tab2 (out);
649  // vl > VERB_LOW lets each image print its data. We assume
650  // that all images can print to the given output stream, and
651  // execute barriers to make it more likely that the output
652  // will be in the right order.
653  for (int imageCtr = 0; imageCtr < numImages; ++imageCtr) {
654  if (myImageID == imageCtr) {
655  if (myImageID == 0) {
656  out << "Number of processes: " << numImages << endl;
657  }
658  out << "Process: " << myImageID << endl;
659  Teuchos::OSTab tab3 (out);
660  out << "selfMessage: " << hasSelfMessage () << endl;
661  out << "numSends: " << getNumSends () << endl;
662  if (vl == VERB_HIGH || vl == VERB_EXTREME) {
663  out << "imagesTo: " << toString (imagesTo_) << endl;
664  out << "lengthsTo: " << toString (lengthsTo_) << endl;
665  out << "maxSendLength: " << getMaxSendLength () << endl;
666  }
667  if (vl == VERB_EXTREME) {
668  out << "startsTo: " << toString (startsTo_) << endl;
669  out << "indicesTo: " << toString (indicesTo_) << endl;
670  }
671  if (vl == VERB_HIGH || vl == VERB_EXTREME) {
672  out << "numReceives: " << getNumReceives () << endl;
673  out << "totalReceiveLength: " << getTotalReceiveLength () << endl;
674  out << "lengthsFrom: " << toString (lengthsFrom_) << endl;
675  out << "startsFrom: " << toString (startsFrom_) << endl;
676  out << "imagesFrom: " << toString (imagesFrom_) << endl;
677  }
678  // Last output is a flush; it leaves a space and also
679  // helps synchronize output.
680  out << std::flush;
681  } // if it's my image's turn to print
682  // Execute barriers to give output time to synchronize.
683  // One barrier generally isn't enough.
684  comm_->barrier();
685  comm_->barrier();
686  comm_->barrier();
687  } // for each image
688  }
689  }
690  }
691 
692  void
693  Distributor::computeReceives ()
694  {
695  using Teuchos::Array;
696  using Teuchos::as;
697  using Teuchos::CommStatus;
698  using Teuchos::CommRequest;
699  using Teuchos::ireceive;
700  using Teuchos::RCP;
701  using Teuchos::rcp;
702  using Teuchos::REDUCE_SUM;
703  using Teuchos::receive;
704  using Teuchos::reduceAllAndScatter;
705  using Teuchos::send;
706  using Teuchos::waitAll;
707  using std::endl;
708 
709  Teuchos::OSTab tab (out_);
710  const int myRank = comm_->getRank();
711  const int numProcs = comm_->getSize();
712 
713  // MPI tag for nonblocking receives and blocking sends in this method.
714  const int pathTag = 2;
715  const int tag = this->getTag (pathTag);
716 
717  if (debug_) {
718  std::ostringstream os;
719  os << myRank << ": computeReceives: "
720  "{selfMessage_: " << (selfMessage_ ? "true" : "false")
721  << ", tag: " << tag << "}" << endl;
722  *out_ << os.str ();
723  }
724 
725  // toNodesFromMe[i] == the number of messages sent by this process
726  // to process i. The data in numSends_, imagesTo_, and lengthsTo_
727  // concern the contiguous sends. Therefore, each process will be
728  // listed in imagesTo_ at most once, and so toNodesFromMe[i] will
729  // either be 0 or 1.
730  {
731  Array<int> toNodesFromMe (numProcs, 0);
732 #ifdef HAVE_TEUCHOS_DEBUG
733  bool counting_error = false;
734 #endif // HAVE_TEUCHOS_DEBUG
735  for (size_t i = 0; i < (numSends_ + (selfMessage_ ? 1 : 0)); ++i) {
736 #ifdef HAVE_TEUCHOS_DEBUG
737  if (toNodesFromMe[imagesTo_[i]] != 0) {
738  counting_error = true;
739  }
740 #endif // HAVE_TEUCHOS_DEBUG
741  toNodesFromMe[imagesTo_[i]] = 1;
742  }
743 #ifdef HAVE_TEUCHOS_DEBUG
744  SHARED_TEST_FOR_EXCEPTION(counting_error, std::logic_error,
745  "Tpetra::Distributor::computeReceives: There was an error on at least "
746  "one process in counting the number of messages send by that process to "
747  "the other processs. Please report this bug to the Tpetra developers.",
748  *comm_);
749 #endif // HAVE_TEUCHOS_DEBUG
750 
751  if (debug_) {
752  std::ostringstream os;
753  os << myRank << ": computeReceives: "
754  "Calling reduceAllAndScatter" << endl;
755  *out_ << os.str ();
756  }
757 
758  // Compute the number of receives that this process needs to
759  // post. The number of receives includes any self sends (i.e.,
760  // messages sent by this process to itself).
761  //
762  // (We will use numReceives_ this below to post exactly that
763  // number of receives, with MPI_ANY_SOURCE as the sending rank.
764  // This will tell us from which processes this process expects
765  // to receive, and how many packets of data we expect to receive
766  // from each process.)
767  //
768  // toNodesFromMe[i] is the number of messages sent by this
769  // process to process i. Compute the sum (elementwise) of all
770  // the toNodesFromMe arrays on all processes in the
771  // communicator. If the array x is that sum, then if this
772  // process has rank j, x[j] is the number of messages sent
773  // to process j, that is, the number of receives on process j
774  // (including any messages sent by process j to itself).
775  //
776  // Yes, this requires storing and operating on an array of
777  // length P, where P is the number of processes in the
778  // communicator. Epetra does this too. Avoiding this O(P)
779  // memory bottleneck would require some research.
780  //
781  // In the (wrapped) MPI_Reduce_scatter call below, since the
782  // counts array contains only ones, there is only one output on
783  // each process, namely numReceives_ (which is x[j], in the
784  // above notation).
785  //
786  // mfh 09 Jan 2012: The reduceAllAndScatter really isn't
787  // necessary here. Since counts is just all ones, we could
788  // replace this with an all-reduce on toNodesFromMe, and let my
789  // process (with rank myRank) get numReceives_ from
790  // toNodesFromMe[myRank]. The HPCCG miniapp uses the all-reduce
791  // method. It could be possible that reduceAllAndScatter is
792  // faster, but it also makes the code more complicated, and it
793  // can't be _asymptotically_ faster (MPI_Allreduce has twice the
794  // critical path length of MPI_Reduce, so reduceAllAndScatter
795  // can't be more than twice as fast as the all-reduce, even if
796  // the scatter is free).
797  //
798  // mfh 12 Apr 2013: See discussion in createFromSends() about
799  // how we could use this communication to propagate an error
800  // flag for "free" in a release build.
801  Array<int> counts (numProcs, 1);
802  int numReceivesAsInt = 0; // output
803  reduceAllAndScatter<int, int> (*comm_, REDUCE_SUM, numProcs,
804  toNodesFromMe.getRawPtr (),
805  counts.getRawPtr (),
806  &numReceivesAsInt);
807  numReceives_ = Teuchos::as<size_t> (numReceivesAsInt);
808  }
809 
810  // Now we know numReceives_, which is this process' number of
811  // receives. Allocate the lengthsFrom_ and imagesFrom_ arrays
812  // with this number of entries.
813  lengthsFrom_.assign (numReceives_, 0);
814  imagesFrom_.assign (numReceives_, 0);
815 
816  //
817  // Ask (via nonblocking receive) each process from which we are
818  // receiving how many packets we should expect from it in the
819  // communication pattern.
820  //
821 
822  // At this point, numReceives_ includes any self message that
823  // there may be. At the end of this routine, we'll subtract off
824  // the self message (if there is one) from numReceives_. In this
825  // routine, we don't need to receive a message from ourselves in
826  // order to figure out our lengthsFrom_ and source process ID; we
827  // can just ask ourselves directly. Thus, the actual number of
828  // nonblocking receives we post here does not include the self
829  // message.
830  const size_t actualNumReceives = numReceives_ - (selfMessage_ ? 1 : 0);
831 
832  // Teuchos' wrapper for nonblocking receives requires receive
833  // buffers that it knows won't go away. This is why we use RCPs,
834  // one RCP per nonblocking receive request. They get allocated in
835  // the loop below.
836  Array<RCP<CommRequest<int> > > requests (actualNumReceives);
837  Array<ArrayRCP<size_t> > lengthsFromBuffers (actualNumReceives);
838  Array<RCP<CommStatus<int> > > statuses (actualNumReceives);
839 
840  // Teuchos::Comm treats a negative process ID as MPI_ANY_SOURCE
841  // (receive data from any process).
842  const int anySourceProc = -1;
843 
844  if (debug_) {
845  std::ostringstream os;
846  os << myRank << ": computeReceives: Posting "
847  << actualNumReceives << " irecvs" << endl;
848  *out_ << os.str ();
849  }
850 
851  // Post the (nonblocking) receives.
852  for (size_t i = 0; i < actualNumReceives; ++i) {
853  // Once the receive completes, we can ask the corresponding
854  // CommStatus object (output by wait()) for the sending process'
855  // ID (which we'll assign to imagesFrom_[i] -- don't forget to
856  // do that!).
857  lengthsFromBuffers[i].resize (1);
858  lengthsFromBuffers[i][0] = as<size_t> (0);
859  requests[i] = ireceive<int, size_t> (lengthsFromBuffers[i], anySourceProc, tag, *comm_);
860  if (debug_) {
861  std::ostringstream os;
862  os << myRank << ": computeReceives: "
863  "Posted any-proc irecv w/ specified tag " << tag << endl;
864  *out_ << os.str ();
865  }
866  }
867 
868  if (debug_) {
869  std::ostringstream os;
870  os << myRank << ": computeReceives: "
871  "posting " << numSends_ << " sends" << endl;
872  *out_ << os.str ();
873  }
874  // Post the sends: Tell each process to which we are sending how
875  // many packets it should expect from us in the communication
876  // pattern. We could use nonblocking sends here, as long as we do
877  // a waitAll() on all the sends and receives at once.
878  //
879  // We assume that numSends_ and selfMessage_ have already been
880  // set. The value of numSends_ (my process' number of sends) does
881  // not include any message that it might send to itself.
882  for (size_t i = 0; i < numSends_ + (selfMessage_ ? 1 : 0); ++i) {
883  if (imagesTo_[i] != myRank) {
884  // Send a message to imagesTo_[i], telling that process that
885  // this communication pattern will send that process
886  // lengthsTo_[i] blocks of packets.
887  const size_t* const lengthsTo_i = &lengthsTo_[i];
888  send<int, size_t> (lengthsTo_i, 1, as<int> (imagesTo_[i]), tag, *comm_);
889  if (debug_) {
890  std::ostringstream os;
891  os << myRank << ": computeReceives: "
892  "Posted send to Proc " << imagesTo_[i] << " w/ specified tag "
893  << tag << endl;
894  *out_ << os.str ();
895  }
896  }
897  else {
898  // We don't need a send in the self-message case. If this
899  // process will send a message to itself in the communication
900  // pattern, then the last element of lengthsFrom_ and
901  // imagesFrom_ corresponds to the self-message. Of course
902  // this process knows how long the message is, and the process
903  // ID is its own process ID.
904  lengthsFrom_[numReceives_-1] = lengthsTo_[i];
905  imagesFrom_[numReceives_-1] = myRank;
906  }
907  }
908 
909  if (debug_) {
910  std::ostringstream os;
911  os << myRank << ": computeReceives: waitAll on "
912  << requests.size () << " requests" << endl;
913  *out_ << os.str ();
914  }
915  //
916  // Wait on all the receives. When they arrive, check the status
917  // output of wait() for the receiving process ID, unpack the
918  // request buffers into lengthsFrom_, and set imagesFrom_ from the
919  // status.
920  //
921  waitAll (*comm_, requests (), statuses ());
922  for (size_t i = 0; i < actualNumReceives; ++i) {
923  lengthsFrom_[i] = *lengthsFromBuffers[i];
924  imagesFrom_[i] = statuses[i]->getSourceRank ();
925  }
926 
927  // Sort the imagesFrom_ array, and apply the same permutation to
928  // lengthsFrom_. This ensures that imagesFrom_[i] and
929  // lengthsFrom_[i] refers to the same thing.
930  sort2 (imagesFrom_.begin(), imagesFrom_.end(), lengthsFrom_.begin());
931 
932  // Compute indicesFrom_
933  totalReceiveLength_ = std::accumulate (lengthsFrom_.begin(), lengthsFrom_.end(), 0);
934  indicesFrom_.clear ();
935  indicesFrom_.reserve (totalReceiveLength_);
936  for (size_t i = 0; i < totalReceiveLength_; ++i) {
937  indicesFrom_.push_back(i);
938  }
939 
940  startsFrom_.clear ();
941  startsFrom_.reserve (numReceives_);
942  for (size_t i = 0, j = 0; i < numReceives_; ++i) {
943  startsFrom_.push_back(j);
944  j += lengthsFrom_[i];
945  }
946 
947  if (selfMessage_) {
948  --numReceives_;
949  }
950 
951  if (debug_) {
952  std::ostringstream os;
953  os << myRank << ": computeReceives: done" << endl;
954  *out_ << os.str ();
955  }
956  }
957 
958  size_t
959  Distributor::createFromSends (const Teuchos::ArrayView<const int> &exportNodeIDs)
960  {
961  using Teuchos::outArg;
962  using Teuchos::REDUCE_MAX;
963  using Teuchos::reduceAll;
964  using std::endl;
965 
966  Teuchos::OSTab tab (out_);
967 
968  numExports_ = exportNodeIDs.size();
969 
970  const int myImageID = comm_->getRank();
971  const int numImages = comm_->getSize();
972  if (debug_) {
973  std::ostringstream os;
974  os << myImageID << ": createFromSends" << endl;
975  *out_ << os.str ();
976  }
977 
978  // exportNodeIDs tells us the communication pattern for this
979  // distributor. It dictates the way that the export data will be
980  // interpreted in doPosts(). We want to perform at most one
981  // send per process in doPosts; this is for two reasons:
982  // * minimize latency / overhead in the comm routines (nice)
983  // * match the number of receives and sends between processes
984  // (necessary)
985  //
986  // Teuchos::Comm requires that the data for a send are contiguous
987  // in a send buffer. Therefore, if the data in the send buffer
988  // for doPosts() are not contiguous, they will need to be copied
989  // into a contiguous buffer. The user has specified this
990  // noncontiguous pattern and we can't do anything about it.
991  // However, if they do not provide an efficient pattern, we will
992  // warn them if one of the following compile-time options has been
993  // set:
994  // * HAVE_TPETRA_THROW_EFFICIENCY_WARNINGS
995  // * HAVE_TPETRA_PRINT_EFFICIENCY_WARNINGS
996  //
997  // If the data are contiguous, then we can post the sends in situ
998  // (i.e., without needing to copy them into a send buffer).
999  //
1000  // Determine contiguity. There are a number of ways to do this:
1001  // * If the export IDs are sorted, then all exports to a
1002  // particular node must be contiguous. This is what Epetra does.
1003  // * If the export ID of the current export already has been
1004  // listed, then the previous listing should correspond to the
1005  // same export. This tests contiguity, but not sortedness.
1006  //
1007  // Both of these tests require O(n), where n is the number of
1008  // exports. However, the latter will positively identify a greater
1009  // portion of contiguous patterns. We use the latter method.
1010  //
1011  // Check to see if values are grouped by images without gaps
1012  // If so, indices_to -> 0.
1013 
1014  // Set up data structures for quick traversal of arrays.
1015  // This contains the number of sends for each process ID.
1016  Teuchos::Array<size_t> starts (numImages + 1, 0);
1017 
1018  // numActive is the number of sends that are not Null
1019  size_t numActive = 0;
1020  int needSendBuff = 0; // Boolean
1021 
1022  int badID = -1;
1023  for (size_t i = 0; i < numExports_; ++i) {
1024  int exportID = exportNodeIDs[i];
1025  if (exportID >= numImages) {
1026  badID = myImageID;
1027  break;
1028  }
1029  else if (exportID >= 0) {
1030  // exportID is a valid process ID. Increment the number of
1031  // messages this process will send to that process.
1032  ++starts[exportID];
1033 
1034  // If we're sending more than one message to process exportID,
1035  // then it is possible that the data are not contiguous.
1036  // Check by seeing if the previous process ID in the list
1037  // (exportNodeIDs[i-1]) is the same. It's safe to use i-1,
1038  // because if starts[exportID] > 1, then i must be > 1 (since
1039  // the starts array was filled with zeros initially).
1040 
1041  // null entries break continuity.
1042  // e.g., [ 0, 0, 0, 1, -99, 1, 2, 2, 2] is not contiguous
1043  if (needSendBuff==0 && starts[exportID] > 1 && exportID != exportNodeIDs[i-1]) {
1044  needSendBuff = 1;
1045  }
1046  ++numActive;
1047  }
1048  }
1049 
1050 #ifdef HAVE_TPETRA_DEBUG
1051  // Test whether any process in the communicator got an invalid
1052  // process ID. If badID != -1 on this process, then it equals
1053  // this process' rank. The max of all badID over all processes is
1054  // the max rank which has an invalid process ID.
1055  {
1056  int gbl_badID;
1057  reduceAll<int, int> (*comm_, REDUCE_MAX, badID, outArg (gbl_badID));
1058  TEUCHOS_TEST_FOR_EXCEPTION(gbl_badID >= 0, std::runtime_error,
1059  Teuchos::typeName(*this) << "::createFromSends(): Process " << gbl_badID
1060  << ", perhaps among other processes, got a bad send process ID.");
1061  }
1062 #else
1063  // FIXME (mfh 12 Apr 2013) Rather than simply ignoring this
1064  // information, we should think about how to pass it along so that
1065  // all the processes find out about it. In a release build with
1066  // efficiency warnings turned off, the next communication happens
1067  // in computeReceives(), in the reduceAllAndScatter
1068  // (MPI_Reduce_scatter). We could figure out how to encode the
1069  // error flag in that operation, for example by replacing it with
1070  // a reduceAll (MPI_Allreduce) as described there, and adding an
1071  // extra element to the array that encodes the error condition
1072  // (zero on all processes if no error, else 1 on any process with
1073  // the error, so that the sum will produce a nonzero value if any
1074  // process had an error). I'll defer this change for now and
1075  // recommend instead that people with troubles try a debug build.
1076 
1077  (void) badID; // forestall "unused variable" compile warning
1078 #endif // HAVE_TPETRA_DEBUG
1079 
1080 #if defined(HAVE_TPETRA_THROW_EFFICIENCY_WARNINGS) || defined(HAVE_TPETRA_PRINT_EFFICIENCY_WARNINGS)
1081  {
1082  int global_needSendBuff;
1083  reduceAll<int, int> (*comm_, REDUCE_MAX, needSendBuff,
1084  outArg (global_needSendBuff));
1086  global_needSendBuff != 0, std::runtime_error,
1087  "::createFromSends: Grouping export IDs together by process rank often "
1088  "improves performance.");
1089  }
1090 #endif
1091 
1092  // Determine from the caller's data whether or not the current
1093  // process should send (a) message(s) to itself.
1094  if (starts[myImageID] != 0) {
1095  selfMessage_ = true;
1096  }
1097  else {
1098  selfMessage_ = false;
1099  }
1100 
1101 #ifdef HAVE_TEUCHOS_DEBUG
1102  bool index_neq_numActive = false;
1103  bool send_neq_numSends = false;
1104 #endif
1105  if (! needSendBuff) {
1106  // grouped by image, no send buffer or indicesTo_ needed
1107  numSends_ = 0;
1108  // Count total number of sends, i.e., total number of images to
1109  // which we are sending. This includes myself, if applicable.
1110  for (int i = 0; i < numImages; ++i) {
1111  if (starts[i]) {
1112  ++numSends_;
1113  }
1114  }
1115 
1116  // Not only do we not need these, but we must clear them, as
1117  // empty status of indicesTo is a flag used later.
1118  indicesTo_.resize(0);
1119  // Size these to numSends_; note, at the moment, numSends_
1120  // includes self sends. Set their values to zeros.
1121  imagesTo_.assign(numSends_,0);
1122  startsTo_.assign(numSends_,0);
1123  lengthsTo_.assign(numSends_,0);
1124 
1125  // set startsTo to the offset for each send (i.e., each image ID)
1126  // set imagesTo to the image ID for each send
1127  // in interpreting this code, remember that we are assuming contiguity
1128  // that is why index skips through the ranks
1129  {
1130  size_t index = 0, nodeIndex = 0;
1131  for (size_t i = 0; i < numSends_; ++i) {
1132  while (exportNodeIDs[nodeIndex] < 0) {
1133  ++nodeIndex; // skip all negative node IDs
1134  }
1135  startsTo_[i] = nodeIndex;
1136  int imageID = exportNodeIDs[nodeIndex];
1137  imagesTo_[i] = imageID;
1138  index += starts[imageID];
1139  nodeIndex += starts[imageID];
1140  }
1141 #ifdef HAVE_TEUCHOS_DEBUG
1142  if (index != numActive) {
1143  index_neq_numActive = true;
1144  }
1145 #endif
1146  }
1147  // sort the startsTo and image IDs together, in ascending order, according
1148  // to image IDs
1149  if (numSends_ > 0) {
1150  sort2(imagesTo_.begin(), imagesTo_.end(), startsTo_.begin());
1151  }
1152  // compute the maximum send length
1153  maxSendLength_ = 0;
1154  for (size_t i = 0; i < numSends_; ++i) {
1155  int imageID = imagesTo_[i];
1156  lengthsTo_[i] = starts[imageID];
1157  if ((imageID != myImageID) && (lengthsTo_[i] > maxSendLength_)) {
1158  maxSendLength_ = lengthsTo_[i];
1159  }
1160  }
1161  }
1162  else {
1163  // not grouped by image, need send buffer and indicesTo_
1164 
1165  // starts[i] is the number of sends to node i
1166  // numActive equals number of sends total, \sum_i starts[i]
1167 
1168  // this loop starts at starts[1], so explicitly check starts[0]
1169  if (starts[0] == 0 ) {
1170  numSends_ = 0;
1171  }
1172  else {
1173  numSends_ = 1;
1174  }
1175  for (Teuchos::Array<size_t>::iterator i=starts.begin()+1,
1176  im1=starts.begin();
1177  i != starts.end(); ++i)
1178  {
1179  if (*i != 0) ++numSends_;
1180  *i += *im1;
1181  im1 = i;
1182  }
1183  // starts[i] now contains the number of exports to nodes 0 through i
1184 
1185  for (Teuchos::Array<size_t>::reverse_iterator ip1=starts.rbegin(),
1186  i=starts.rbegin()+1;
1187  i != starts.rend(); ++i)
1188  {
1189  *ip1 = *i;
1190  ip1 = i;
1191  }
1192  starts[0] = 0;
1193  // starts[i] now contains the number of exports to nodes 0 through
1194  // i-1, i.e., all nodes before node i
1195 
1196  indicesTo_.resize(numActive);
1197 
1198  for (size_t i = 0; i < numExports_; ++i) {
1199  if (exportNodeIDs[i] >= 0) {
1200  // record the offset to the sendBuffer for this export
1201  indicesTo_[starts[exportNodeIDs[i]]] = i;
1202  // now increment the offset for this node
1203  ++starts[exportNodeIDs[i]];
1204  }
1205  }
1206  // our send buffer will contain the export data for each of the nodes
1207  // we communicate with, in order by node id
1208  // sendBuffer = {node_0_data, node_1_data, ..., node_np-1_data}
1209  // indicesTo now maps each export to the location in our send buffer
1210  // associated with the export
1211  // data for export i located at sendBuffer[indicesTo[i]]
1212  //
1213  // starts[i] once again contains the number of exports to
1214  // nodes 0 through i
1215  for (int node = numImages-1; node != 0; --node) {
1216  starts[node] = starts[node-1];
1217  }
1218  starts.front() = 0;
1219  starts[numImages] = numActive;
1220  //
1221  // starts[node] once again contains the number of exports to
1222  // nodes 0 through node-1
1223  // i.e., the start of my data in the sendBuffer
1224 
1225  // this contains invalid data at nodes we don't care about, that is okay
1226  imagesTo_.resize(numSends_);
1227  startsTo_.resize(numSends_);
1228  lengthsTo_.resize(numSends_);
1229 
1230  // for each group of sends/exports, record the destination node,
1231  // the length, and the offset for this send into the
1232  // send buffer (startsTo_)
1233  maxSendLength_ = 0;
1234  size_t snd = 0;
1235  for (int node = 0; node < numImages; ++node ) {
1236  if (starts[node+1] != starts[node]) {
1237  lengthsTo_[snd] = starts[node+1] - starts[node];
1238  startsTo_[snd] = starts[node];
1239  // record max length for all off-node sends
1240  if ((node != myImageID) && (lengthsTo_[snd] > maxSendLength_)) {
1241  maxSendLength_ = lengthsTo_[snd];
1242  }
1243  imagesTo_[snd] = node;
1244  ++snd;
1245  }
1246  }
1247 #ifdef HAVE_TEUCHOS_DEBUG
1248  if (snd != numSends_) {
1249  send_neq_numSends = true;
1250  }
1251 #endif
1252  }
1253 #ifdef HAVE_TEUCHOS_DEBUG
1254  SHARED_TEST_FOR_EXCEPTION(index_neq_numActive, std::logic_error,
1255  "Tpetra::Distributor::createFromSends: logic error. Please notify the Tpetra team.",*comm_);
1256  SHARED_TEST_FOR_EXCEPTION(send_neq_numSends, std::logic_error,
1257  "Tpetra::Distributor::createFromSends: logic error. Please notify the Tpetra team.",*comm_);
1258 #endif
1259 
1260  if (selfMessage_) --numSends_;
1261 
1262  // Invert map to see what msgs are received and what length
1263  computeReceives();
1264 
1265  if (debug_) {
1266  std::ostringstream os;
1267  os << myImageID << ": createFromSends: done" << endl;
1268  *out_ << os.str ();
1269  }
1270  return totalReceiveLength_;
1271  }
1272 
1273 } // namespace Tpetra
size_t getNumReceives() const
The number of processes from which we will receive data.
std::string description() const
A simple one-line description of this object.
ArrayView< const int > getImagesTo() const
Ranks of the processes to which this process will send values.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
List of valid Distributor parameters.
void swap(Distributor &rhs)
Swap the contents of rhs with those of *this.
ArrayView< const size_t > getLengthsFrom() const
Number of values this process will receive from each process.
bool hasSelfMessage() const
Whether the calling process will send or receive messages to itself.
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.
void setParameterList(const Teuchos::RCP< Teuchos::ParameterList > &plist)
Set Distributor parameters.
size_t createFromSends(const ArrayView< const int > &exportNodeIDs)
Set up Distributor using list of process ranks to which this process will send.
#define TPETRA_EFFICIENCY_WARNING(throw_exception_test, Exception, msg)
Print or throw an efficency warning.
ArrayView< const size_t > getLengthsTo() const
Number of values this process will send to each process.
virtual ~Distributor()
Destructor (virtual for memory safety).
void sort2(const IT1 &first1, const IT1 &last1, const IT2 &first2)
Sort the first array, and apply the resulting permutation to the second array.
ArrayView< const int > getImagesFrom() const
Ranks of the processes sending values to this process.
size_t getNumSends() const
The number of processes to which we will send data.
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel=Teuchos::Describable::verbLevel_default) const
Print the object with some verbosity level to an FancyOStream.
size_t getMaxSendLength() const
Maximum number of values this process will send to another single process.
#define SHARED_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg, comm)
Test for exception, with reduction over the given communicator.
Array< std::string > distributorSendTypes()
Valid values for Distributor&#39;s &quot;Send type&quot; parameter.
const RCP< Distributor > & getReverse() const
A reverse communication plan Distributor.
Distributor(const Teuchos::RCP< const Teuchos::Comm< int > > &comm)
Construct using the specified communicator and default parameters.