EpetraExt  Development
EpetraExt_MMHelpers.cpp
Go to the documentation of this file.
1 //@HEADER
2 // ***********************************************************************
3 //
4 // EpetraExt: Epetra Extended - Linear Algebra Services Package
5 // Copyright (2011) 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 <EpetraExt_ConfigDefs.h>
43 #include <EpetraExt_MMHelpers.h>
44 #include <Epetra_Comm.h>
45 #include <Epetra_CrsMatrix.h>
46 #include <Epetra_Import.h>
47 #include <Epetra_Distributor.h>
48 #include <Epetra_HashTable.h>
49 #include <Epetra_Util.h>
50 #include <Epetra_Import_Util.h>
51 
52 #include <Teuchos_TimeMonitor.hpp>
53 
54 #ifdef HAVE_MPI
55 #include "Epetra_MpiComm.h"
56 #include "Epetra_MpiDistributor.h"
57 #endif
58 #define MIN(x,y) ((x)<(y)?(x):(y))
59 #define MIN3(x,y,z) ((x)<(y)?(MIN(x,z)):(MIN(y,z)))
60 
61 namespace EpetraExt {
62 
64  : numRows(0), numEntriesPerRow(NULL), indices(NULL), values(NULL),
65  remote(NULL), numRemote(0), importColMap(NULL), rowMap(NULL), colMap(NULL),
66  domainMap(NULL), importMatrix(NULL), origMatrix(NULL)
67 {
68 }
69 
71 {
73 }
74 
76 {
77  numRows = 0;
78  delete [] numEntriesPerRow; numEntriesPerRow = NULL;
79  delete [] indices; indices = NULL;
80  delete [] values; values = NULL;
81  delete [] remote; remote = NULL;
82  numRemote = 0;
83  delete importMatrix; importMatrix=0;
84  // origMatrix is not owned by me, so don't delete
85  origMatrix=0;
86  targetMapToOrigRow.resize(0);
87  targetMapToImportRow.resize(0);
88 }
89 
91 {
92  cout << "proc " << M.rowMap->Comm().MyPID()<<endl;
93  cout << "numRows: " << M.numRows<<endl;
94  for(int i=0; i<M.numRows; ++i) {
95  for(int j=0; j<M.numEntriesPerRow[i]; ++j) {
96  if (M.remote[i]) {
97  cout << " *"<<M.rowMap->GID(i)<<" "
98  <<M.importColMap->GID(M.indices[i][j])<<" "<<M.values[i][j]<<endl;
99  }
100  else {
101  cout << " "<<M.rowMap->GID(i)<<" "
102  <<M.colMap->GID(M.indices[i][j])<<" "<<M.values[i][j]<<endl;
103  }
104  }
105  }
106  return(0);
107 }
108 
110  : ecrsmat_(epetracrsmatrix)
111 {
112 }
113 
115 {
116 }
117 
118 const Epetra_Map&
120 {
121  return ecrsmat_.RowMap();
122 }
123 
125 {
126  return ecrsmat_.Filled();
127 }
128 
129 int
130 CrsWrapper_Epetra_CrsMatrix::InsertGlobalValues(int GlobalRow, int NumEntries, double* Values, int* Indices)
131 {
132  return ecrsmat_.InsertGlobalValues(GlobalRow, NumEntries, Values, Indices);
133 }
134 
135 int
136 CrsWrapper_Epetra_CrsMatrix::SumIntoGlobalValues(int GlobalRow, int NumEntries, double* Values, int* Indices)
137 {
138  return ecrsmat_.SumIntoGlobalValues(GlobalRow, NumEntries, Values, Indices);
139 }
140 
141 
142 //------------------------------------
143 
145  : graph_(),
146  rowmap_(emap),
147  max_row_length_(0)
148 {
149  int num_rows = emap.NumMyElements();
150  int* rows = emap.MyGlobalElements();
151 
152  for(int i=0; i<num_rows; ++i) {
153  graph_[rows[i]] = new std::set<int>;
154  }
155 }
156 
158 {
159  std::map<int,std::set<int>*>::iterator
160  iter = graph_.begin(), iter_end = graph_.end();
161  for(; iter!=iter_end; ++iter) {
162  delete iter->second;
163  }
164 
165  graph_.clear();
166 }
167 
169 {
170  return false;
171 }
172 
173 int
174 CrsWrapper_GraphBuilder::InsertGlobalValues(int GlobalRow, int NumEntries, double* Values, int* Indices)
175 {
176  std::map<int,std::set<int>*>::iterator
177  iter = graph_.find(GlobalRow);
178 
179  if (iter == graph_.end()) return(-1);
180 
181  std::set<int>& cols = *(iter->second);
182 
183  for(int i=0; i<NumEntries; ++i) {
184  cols.insert(Indices[i]);
185  }
186 
187  int row_length = cols.size();
188  if (row_length > max_row_length_) max_row_length_ = row_length;
189 
190  return(0);
191 }
192 
193 int
194 CrsWrapper_GraphBuilder::SumIntoGlobalValues(int GlobalRow, int NumEntries, double* Values, int* Indices)
195 {
196  return InsertGlobalValues(GlobalRow, NumEntries, Values, Indices);
197 }
198 
199 std::map<int,std::set<int>*>&
201 {
202  return graph_;
203 }
204 
206  Epetra_CrsMatrix& C)
207 {
208  int max_row_length = graphbuilder.get_max_row_length();
209  if (max_row_length < 1) return;
210 
211  std::vector<int> indices(max_row_length);
212  int* indices_ptr = &indices[0];
213  std::vector<double> zeros(max_row_length, 0.0);
214  double* zeros_ptr = &zeros[0];
215 
216  std::map<int,std::set<int>*>& graph = graphbuilder.get_graph();
217 
218  std::map<int,std::set<int>*>::iterator
219  iter = graph.begin(), iter_end = graph.end();
220 
221  for(; iter!=iter_end; ++iter) {
222  int row = iter->first;
223  std::set<int>& cols = *(iter->second);
224  int num_entries = cols.size();
225 
226  std::set<int>::iterator
227  col_iter = cols.begin(), col_end = cols.end();
228  for(int j=0; col_iter!=col_end; ++col_iter, ++j) {
229  indices_ptr[j] = *col_iter;
230  }
231 
232  C.InsertGlobalValues(row, num_entries, zeros_ptr, indices_ptr);
233  }
234 }
235 
236 void pack_outgoing_rows(const Epetra_CrsMatrix& mtx,
237  const std::vector<int>& proc_col_ranges,
238  std::vector<int>& send_rows,
239  std::vector<int>& rows_per_send_proc)
240 {
241  const Epetra_Map& rowmap = mtx.RowMap();
242  int numrows = mtx.NumMyRows();
243  const Epetra_CrsGraph& graph = mtx.Graph();
244  int rowlen = 0;
245  int* col_indices = NULL;
246  int num_col_ranges = proc_col_ranges.size()/2;
247  rows_per_send_proc.resize(num_col_ranges);
248  send_rows.clear();
249  for(int nc=0; nc<num_col_ranges; ++nc) {
250  int first_col = proc_col_ranges[nc*2];
251  int last_col = proc_col_ranges[nc*2+1];
252  int num_send_rows = 0;
253  for(int i=0; i<numrows; ++i) {
254  int grow = rowmap.GID(i);
255  if (mtx.Filled()) {
256  const Epetra_Map& colmap = mtx.ColMap();
257  graph.ExtractMyRowView(i, rowlen, col_indices);
258  for(int j=0; j<rowlen; ++j) {
259  int col = colmap.GID(col_indices[j]);
260  if (first_col <= col && last_col >= col) {
261  ++num_send_rows;
262  send_rows.push_back(grow);
263  break;
264  }
265  }
266  }
267  else {
268  graph.ExtractGlobalRowView(grow, rowlen, col_indices);
269  for(int j=0; j<rowlen; ++j) {
270  if (first_col <= col_indices[j] && last_col >= col_indices[j]) {
271  ++num_send_rows;
272  send_rows.push_back(grow);
273  break;
274  }
275  }
276  }
277  }
278  rows_per_send_proc[nc] = num_send_rows;
279  }
280 }
281 
282 std::pair<int,int> get_col_range(const Epetra_Map& emap)
283 {
284  return std::make_pair(emap.MinMyGID(),emap.MaxMyGID());
285 }
286 
287 
288 std::pair<int,int> get_col_range(const Epetra_CrsMatrix& mtx)
289 {
290  std::pair<int,int> col_range;
291  if (mtx.Filled()) {
292  col_range = get_col_range(mtx.ColMap());
293  }
294  else {
295  const Epetra_Map& row_map = mtx.RowMap();
296  col_range.first = row_map.MaxMyGID();
297  col_range.second = row_map.MinMyGID();
298  int rowlen = 0;
299  int* col_indices = NULL;
300  const Epetra_CrsGraph& graph = mtx.Graph();
301  for(int i=0; i<row_map.NumMyElements(); ++i) {
302  graph.ExtractGlobalRowView(row_map.GID(i), rowlen, col_indices);
303  for(int j=0; j<rowlen; ++j) {
304  if (col_indices[j] < col_range.first) col_range.first = col_indices[j];
305  if (col_indices[j] > col_range.second) col_range.second = col_indices[j];
306  }
307  }
308  }
309 
310  return col_range;
311 }
312 
313 /**********************************************************************************************/
314 /**********************************************************************************************/
315 /**********************************************************************************************/
316 #ifdef HAVE_MPI
317 template <typename MyType>
318 void boundary_exchange(const Epetra_MpiComm Comm, MPI_Datatype DataType,
319  int NumSends, const int * SendProcs, const int * SendSizes, MyType* SendBuffer,
320  int NumRecvs, const int * RecvProcs, const int * RecvSizes, MyType* RecvBuffer,int SizeOfPacket,int msg_tag)
321 {
322 
323  MPI_Comm comm = Comm.Comm();
324  std::vector<MPI_Request> requests(NumRecvs);
325  std::vector<MPI_Status> status(NumRecvs);
326 
327  int i,num_waits=0,MyPID=Comm.MyPID();
328  int start, self_recv_len=-1,self_recv_start=-1, self_send_start=-1;
329 
330  // Default send/recv size if the Sizes arrays are NULL.
331  int mysendsize=1, myrecvsize=1;
332 
333  // Post Recvs
334  start=0;
335  for(i=0; i<NumRecvs; i++){
336  if(RecvSizes) myrecvsize=RecvSizes[i]*SizeOfPacket;
337  if(RecvProcs[i] != MyPID) {
338  MPI_Irecv(RecvBuffer + start, myrecvsize, DataType, RecvProcs[i], msg_tag, comm, &requests[num_waits]);
339  num_waits++;
340  }
341  else {
342  self_recv_len = myrecvsize;
343  self_recv_start=start;
344  }
345  start+=myrecvsize;
346  }
347 
348  // Do sends
349  start=0;
350  for(i=0; i<NumSends; i++){
351  if(SendSizes) mysendsize=SendSizes[i]*SizeOfPacket;
352  if(SendProcs[i] != MyPID)
353  MPI_Send(SendBuffer + start, mysendsize,DataType,SendProcs[i],msg_tag,comm);
354  else
355  self_send_start=start;
356  start+=mysendsize;
357  }
358 
359  // Self-copy (if needed)
360  if(self_recv_len != -1)
361  memcpy(RecvBuffer+self_recv_start,SendBuffer+self_send_start,self_recv_len*sizeof(MyType)*SizeOfPacket);
362 
363  // Wait
364  if(NumRecvs > 0)
365  MPI_Waitall(num_waits, &requests[0],&status[0]);
366 }
367 #endif
368 
369 
370 #ifdef HAVE_MPI
371 template <typename MyType>
372 void boundary_exchange_varsize(const Epetra_MpiComm Comm, MPI_Datatype DataType,
373  int NumSends, const int * SendProcs, const int * SendSizes, MyType* SendBuffer,
374  int NumRecvs, const int * RecvProcs, int * RecvSizes, MyType*& RecvBuffer,int SizeOfPacket,int msg_tag)
375 {
376 
377  int i,rbuffersize=0;
378 
379  // Do a first round of boundary exchange with the the SendBuffer sizes
380  boundary_exchange<int>(Comm,MPI_INT,NumSends,SendProcs,(int*)0,const_cast<int*>(SendSizes),NumRecvs,RecvProcs,(int*)0,RecvSizes,1,msg_tag);
381 
382  // Allocate the RecvBuffer
383  for(i=0; i<NumRecvs; i++) rbuffersize+=RecvSizes[i]*SizeOfPacket;
384  RecvBuffer = new MyType[rbuffersize];
385 
386  // Do a second round of boundary exchange to trade the actual values
387  boundary_exchange<MyType>(Comm,DataType,NumSends,SendProcs,SendSizes,SendBuffer,NumRecvs,RecvProcs,RecvSizes,RecvBuffer,SizeOfPacket,msg_tag+100);
388 }
389 #endif
390 
391 
392 //=========================================================================
393 //=========================================================================
394 //=========================================================================
396  Epetra_Data(),
397  IndexBase_(0),
398  LIDHash_(0),
399  CopyMap_(0)
400 {
401 }
402 //=========================================================================
404  delete LIDHash_;
405  delete CopyMap_;
406 }
407 
408 //=========================================================================
410 
411 //=========================================================================
412 LightweightMap::LightweightMap(int NumGlobalElements,int NumMyElements, const int * MyGlobalElements, int IndexBase, bool GenerateHash)
413 {
414  Data_=new LightweightMapData();
415  Data_->MyGlobalElements_.resize(NumMyElements);
416 
417  // Build the hash table
418  if(GenerateHash) Data_->LIDHash_ = new Epetra_HashTable<int>(NumMyElements + 1 );
419  for(int i=0; i < NumMyElements; ++i ) {
420  Data_->MyGlobalElements_[i]=MyGlobalElements[i];
421  if(GenerateHash) Data_->LIDHash_->Add(MyGlobalElements[i], i);
422  }
423 }
424 
425 //=========================================================================
426 LightweightMap::LightweightMap(const Epetra_Map & Map)
427 {
428  Data_=new LightweightMapData();
429  Data_->CopyMap_=new Epetra_Map(Map);
430 }
431 
432 //=========================================================================
434  : Data_(map.Data_)
435 {
436  Data_->IncrementReferenceCount();
437 }
438 
439 //=========================================================================
441  CleanupData();
442 }
443 
444 //=========================================================================
446 {
447  if((this != &map) && (Data_ != map.Data_)) {
448  CleanupData();
449  Data_ = map.Data_;
450  Data_->IncrementReferenceCount();
451  }
452  return(*this);
453 }
454 
455 //=========================================================================
456 void LightweightMap::CleanupData(){
457  if(Data_){
458  Data_->DecrementReferenceCount();
459  if(Data_->ReferenceCount() == 0) {
460  delete Data_;
461  }
462  }
463 }
464 
465 //=========================================================================
467  if(Data_->CopyMap_) return Data_->CopyMap_->NumMyElements();
468  return Data_->MyGlobalElements_.size();
469 }
470 
471 //=========================================================================
472 int LightweightMap::LID(int GID) const {
473  if(Data_->CopyMap_) return Data_->CopyMap_->LID(GID);
474  return Data_->LIDHash_->Get(GID);
475 }
476 
477 //=========================================================================
478 int LightweightMap::GID(int LID) const {
479  if(Data_->CopyMap_) return Data_->CopyMap_->GID(LID);
480  if(LID < 0 || LID > (int)Data_->MyGlobalElements_.size()) return -1;
481  return Data_->MyGlobalElements_[LID];
482 }
483 
484 //=========================================================================
486  if(Data_->CopyMap_) return Data_->CopyMap_->MyGlobalElements();
487  else if(Data_->MyGlobalElements_.size()>0) return const_cast<int*>(&Data_->MyGlobalElements_[0]);
488  else return 0;
489 }
490 
491 //=========================================================================
493  if(Data_->CopyMap_) return Data_->CopyMap_->MinLID();
494  else return 0;
495 }
496 
497 //=========================================================================
499  if(Data_->CopyMap_) return Data_->CopyMap_->MaxLID();
500  else return (int)(Data_->MyGlobalElements_.size()-1);
501 }
502 
503 
504 //=========================================================================
505 //=========================================================================
506 //=========================================================================
507 RemoteOnlyImport::RemoteOnlyImport(const Epetra_Import & Importer, LightweightMap & RemoteOnlyTargetMap)
508 {
509  int i;
510 
511  // Build an "Importer" that only takes the remote parts of the Importer.
512  SourceMap_=&Importer.SourceMap();
513  TargetMap_=&RemoteOnlyTargetMap;
514 
515  // Pull data from the Importer
516  NumSend_ = Importer.NumSend();
517  NumRemoteIDs_ = Importer.NumRemoteIDs();
518  NumExportIDs_ = Importer.NumExportIDs();
519  Distor_ = &Importer.Distributor();
520  int * OldRemoteLIDs = Importer.RemoteLIDs();
521  int * OldExportLIDs = Importer.ExportLIDs();
522  int * OldExportPIDs = Importer.ExportPIDs();
523 
524  // Sanity Check
525  if(NumRemoteIDs_ != RemoteOnlyTargetMap.NumMyElements())
526  throw std::runtime_error("RemoteOnlyImport: Importer doesn't match RemoteOnlyTargetMap for number of remotes.");
527 
528  // Copy the ExportIDs_, since they don't change
529  ExportLIDs_ = new int[NumExportIDs_];
530  ExportPIDs_ = new int[NumExportIDs_];
531  for(i=0; i<NumExportIDs_; i++) {
532  ExportLIDs_[i] = OldExportLIDs[i];
533  ExportPIDs_[i] = OldExportPIDs[i];
534  }
535 
536  // The RemoteIDs, on the other hand, do change. So let's do this right.
537  // Note: We might be able to bypass the LID call by just indexing off the Same and Permute GIDs, but at the moment this
538  // is fast enough not to worry about it.
539  RemoteLIDs_ = new int[NumRemoteIDs_];
540  for(i=0; i<NumRemoteIDs_; i++)
541  RemoteLIDs_[i] = TargetMap_->LID(Importer.TargetMap().GID(OldRemoteLIDs[i]));
542 
543  // Nowe we make sure these guys are in sorted order. AztecOO, ML and all that jazz.
544  for(i=0; i<NumRemoteIDs_-1; i++)
545  if(RemoteLIDs_[i] > RemoteLIDs_[i+1])
546  throw std::runtime_error("RemoteOnlyImport: Importer and RemoteOnlyTargetMap order don't match.");
547 }
548 
549 //=========================================================================
551 {
552  delete [] ExportLIDs_;
553  delete [] ExportPIDs_;
554  delete [] RemoteLIDs_;
555  // Don't delete the Distributor, SourceMap_ or TargetMap_ - those were shallow copies
556 }
557 
558 //=========================================================================
559 //=========================================================================
560 //=========================================================================
561 template <class GO>
562 int LightweightCrsMatrix::MakeColMapAndReindex(std::vector<int> owningPIDs, std::vector<GO> Gcolind)
563 {
564  int i,j;
565 
566 #ifdef ENABLE_MMM_TIMINGS
567  Teuchos::Time myTime("global");
568  Teuchos::TimeMonitor MM(myTime);
569  Teuchos::RCP<Teuchos::Time> mtime;
570  mtime=MM.getNewTimer("LWCRS C-3.1");
571  mtime->start();
572 #endif
573 
574  // Scan all column indices and sort into two groups:
575  // Local: those whose GID matches a GID of the domain map on this processor and
576  // Remote: All others.
577  int numDomainElements = DomainMap_.NumMyElements();
578  std::vector<bool> LocalGIDs(numDomainElements,false);
579 
580  bool DoSizes = !DomainMap_.ConstantElementSize(); // If not constant element size, then error
581  if(DoSizes) EPETRA_CHK_ERR(-1);
582 
583  // In principle it is good to have RemoteGIDs and RemoteGIDList be as long as the number of remote GIDs
584  // on this processor, but this would require two passes through the column IDs, so we make it the max of 100
585  // and the number of block rows.
586  int numMyBlockRows;
587  if(use_lw) numMyBlockRows = RowMapLW_->NumMyElements();
588  else numMyBlockRows = RowMapEP_->NumMyElements();
589 
590  int hashsize = numMyBlockRows; if (hashsize < 100) hashsize = 100;
591  Epetra_HashTable<GO> RemoteGIDs(hashsize);
592  std::vector<GO> RemoteGIDList; RemoteGIDList.reserve(hashsize);
593  std::vector<int> RemoteOwningPIDs; RemoteOwningPIDs.reserve(hashsize);
594 
595  // In order to do the map reindexing inexpensively, we clobber the GIDs during this pass. For *local* GID's we clobber them
596  // with their LID in the domainMap. For *remote* GIDs, we clobber them with (numDomainElements+NumRemoteColGIDs) before the increment of
597  // the remote count. These numberings will be separate because no local LID is greater than numDomainElements.
598  int NumLocalColGIDs = 0;
599  int NumRemoteColGIDs = 0;
600  for(i = 0; i < numMyBlockRows; i++) {
601  for(j = rowptr_[i]; j < rowptr_[i+1]; j++) {
602  GO GID = Gcolind[j];
603  // Check if GID matches a row GID
604  int LID = DomainMap_.LID(GID);
605  if(LID != -1) {
606  bool alreadyFound = LocalGIDs[LID];
607  if (!alreadyFound) {
608  LocalGIDs[LID] = true; // There is a column in the graph associated with this domain map GID
609  NumLocalColGIDs++;
610  }
611  colind_[j] = LID;
612  }
613  else {
614  int hash_value=RemoteGIDs.Get(GID);
615  if(hash_value == -1) { // This means its a new remote GID
616  int PID = owningPIDs[j];
617  if(PID==-1) printf("[%d] ERROR: Remote PID should not be -1\n",DomainMap_.Comm().MyPID());
618  colind_[j] = numDomainElements + NumRemoteColGIDs;
619  RemoteGIDs.Add(GID, NumRemoteColGIDs);
620  RemoteGIDList.push_back(GID);
621  RemoteOwningPIDs.push_back(PID);
622  NumRemoteColGIDs++;
623  }
624  else
625  colind_[j] = numDomainElements + hash_value;
626  }
627  }
628  }
629 
630  // Possible short-circuit: If all domain map GIDs are present as column indices, then set ColMap=domainMap and quit
631  if (DomainMap_.Comm().NumProc()==1) {
632  if (NumRemoteColGIDs!=0) {
633  throw "Some column IDs are not in domainMap. If matrix is rectangular, you must pass in domainMap to FillComplete";
634  // Sanity test: When one processor,there can be no remoteGIDs
635  }
636  if (NumLocalColGIDs==numDomainElements) {
637  ColMap_ = DomainMap_;
638 
639  // In this case, we just use the domainMap's indices, which is, not coincidently, what we clobbered colind_ with up above anyway.
640  // No further reindexing is needed.
641  return(0);
642  }
643  }
644 
645  // Now build integer array containing column GIDs
646  // Build back end, containing remote GIDs, first
647  int numMyBlockCols = NumLocalColGIDs + NumRemoteColGIDs;
648  Epetra_IntSerialDenseVector Colindices;
649  if(numMyBlockCols > 0)
650  Colindices.Size(numMyBlockCols);
651  int* RemoteColindices = Colindices.Values() + NumLocalColGIDs; // Points to back end of Colindices
652 
653  for(i = 0; i < NumRemoteColGIDs; i++)
654  RemoteColindices[i] = RemoteGIDList[i];
655 
656  int NLists = 2;
657 
658  // Build permute array for *remote* reindexing.
659  std::vector<int> RemotePermuteIDs(NumRemoteColGIDs);
660  for(i=0; i<NumRemoteColGIDs; i++) RemotePermuteIDs[i]=i;
661 
662  // Sort External column indices so that all columns coming from a given remote processor are contiguous
663  int* SortLists[3]; // this array is allocated on the stack, and so we won't need to delete it.
664  if(NumRemoteColGIDs > 0) {
665  SortLists[0] = RemoteColindices;
666  SortLists[1] = &RemotePermuteIDs[0];
667  Epetra_Util::Sort(true, NumRemoteColGIDs, &RemoteOwningPIDs[0], 0, 0, NLists, SortLists);
668  }
669 
670 
671  bool SortGhostsAssociatedWithEachProcessor_ = false;
672  if (SortGhostsAssociatedWithEachProcessor_) {
673  // Sort external column indices so that columns from a given remote processor are not only contiguous
674  // but also in ascending order. NOTE: I don't know if the number of externals associated
675  // with a given remote processor is known at this point ... so I count them here.
676 
677  NLists=1;
678  int StartCurrent, StartNext;
679  StartCurrent = 0; StartNext = 1;
680  while ( StartNext < NumRemoteColGIDs ) {
681  if (RemoteOwningPIDs[StartNext]==RemoteOwningPIDs[StartNext-1]) StartNext++;
682  else {
683  SortLists[0] = &RemotePermuteIDs[StartCurrent];
684  Epetra_Util::Sort(true,StartNext-StartCurrent, &(RemoteColindices[StartCurrent]),0,0,NLists,SortLists);
685  StartCurrent = StartNext; StartNext++;
686  }
687  }
688  SortLists[0] = &RemotePermuteIDs[StartCurrent];
689  Epetra_Util::Sort(true, StartNext-StartCurrent, &(RemoteColindices[StartCurrent]), 0, 0, NLists, SortLists);
690  }
691 
692  // Reverse the permutation to get the information we actually care about
693  std::vector<int> ReverseRemotePermuteIDs(NumRemoteColGIDs);
694  for(i=0; i<NumRemoteColGIDs; i++) ReverseRemotePermuteIDs[RemotePermuteIDs[i]]=i;
695 
696  // Build permute array for *local* reindexing.
697  bool use_local_permute=false;
698  std::vector<int> LocalPermuteIDs(numDomainElements);
699 
700  // Now fill front end. Two cases:
701  // (1) If the number of Local column GIDs is the same as the number of Local domain GIDs, we
702  // can simply read the domain GIDs into the front part of Colindices, otherwise
703  // (2) We step through the GIDs of the domainMap, checking to see if each domain GID is a column GID.
704  // we want to do this to maintain a consistent ordering of GIDs between the columns and the domain.
705 
706  if(NumLocalColGIDs == DomainMap_.NumMyElements()) {
707  DomainMap_.MyGlobalElements(Colindices.Values()); // Load Global Indices into first numMyBlockCols elements column GID list
708  }
709  else {
710  int* MyGlobalElements = DomainMap_.MyGlobalElements();
711  int NumLocalAgain = 0;
712  use_local_permute = true;
713  for(i = 0; i < numDomainElements; i++) {
714  if(LocalGIDs[i]) {
715  LocalPermuteIDs[i] = NumLocalAgain;
716  Colindices[NumLocalAgain++] = MyGlobalElements[i];
717  }
718  }
719  assert(NumLocalAgain==NumLocalColGIDs); // Sanity test
720  }
721 
722 
723  // Copy the remote PID list correctly
724  ColMapOwningPIDs_.resize(numMyBlockCols);
725  ColMapOwningPIDs_.assign(numMyBlockCols,DomainMap_.Comm().MyPID());
726  for(int i=0;i<NumRemoteColGIDs;i++)
727  ColMapOwningPIDs_[NumLocalColGIDs+i] = RemoteOwningPIDs[i];
728 
729 #ifdef ENABLE_MMM_TIMINGS
730  mtime->stop();
731  mtime=MM.getNewTimer("LWCRS C-3.2");
732  mtime->start();
733 #endif
734 
735  // Make Column map with same element sizes as Domain map
736  LightweightMap temp(-1, numMyBlockCols, Colindices.Values(), DomainMap_.IndexBase());
737  ColMap_ = temp;
738 
739 
740 #ifdef ENABLE_MMM_TIMINGS
741  mtime->stop();
742  mtime=MM.getNewTimer("LWCRS C-3.3");
743  mtime->start();
744 #endif
745 
746  // Low-cost reindex of the matrix
747  for(i=0; i<numMyBlockRows; i++){
748  for(j=rowptr_[i]; j<rowptr_[i+1]; j++){
749  int ID=colind_[j];
750  if(ID < numDomainElements){
751  if(use_local_permute) colind_[j] = LocalPermuteIDs[colind_[j]];
752  // In the case where use_local_permute==false, we just copy the DomainMap's ordering, which it so happens
753  // is what we put in colind_ to begin with.
754  }
755  else
756  colind_[j] = NumLocalColGIDs + ReverseRemotePermuteIDs[colind_[j]-numDomainElements];
757  }
758  }
759 
760  assert((size_t)ColMap_.NumMyElements() == ColMapOwningPIDs_.size());
761 
762 #ifdef ENABLE_MMM_TIMINGS
763  mtime->stop();
764 #endif
765 
766  return(0);
767 }
768 
769 
770 //=========================================================================
771 // Template params are <PID,GID>
772 static inline bool lessthan12(std::pair<int,int> i, std::pair<int,int> j){
773  return ((i.first<j.first) || (i.first==j.first && i.second <j.second));
774 }
775 
776 
777 template<typename ImportType>
778 int LightweightCrsMatrix::PackAndPrepareReverseComm(const Epetra_CrsMatrix & SourceMatrix, ImportType & RowImporter,
779  std::vector<int> &ReverseSendSizes, std::vector<int> &ReverseSendBuffer) {
780 #ifdef HAVE_MPI
781  // Buffer pairs are in (PID,GID) order
782  int i,j,k;
783  const Epetra_Import *MyImporter= SourceMatrix.Importer();
784  if(MyImporter == 0) return -1;
785  const Epetra_MpiComm * MpiComm = dynamic_cast<const Epetra_MpiComm*>(&SourceMatrix.Comm());
786  int MyPID = MpiComm->MyPID();
787 
788  // Things related to messages I and sending in forward mode (RowImporter)
789  int NumExportIDs = RowImporter.NumExportIDs();
790  int* ExportLIDs = RowImporter.ExportLIDs();
791  int* ExportPIDs = RowImporter.ExportPIDs();
792 
793  // Things related to messages I am sending in reverse mode (MyImporter)
794  Epetra_Distributor& Distor = MyImporter->Distributor();
795  const Epetra_MpiDistributor * MDistor = dynamic_cast<Epetra_MpiDistributor*>(&Distor);
796  int NumRecvs = MDistor->NumReceives();
797  int* RemoteLIDs = MyImporter->RemoteLIDs();
798  const int * ProcsFrom = MDistor->ProcsFrom();
799  const int * LengthsFrom = MDistor->LengthsFrom();
800 
801 
802  // Get the owning pids in a special way, s.t. ProcsFrom[RemotePIDs[i]] is the guy who owns
803  // RemoteLIDs[j]....
804  std::vector<int> RemotePIDOrder(SourceMatrix.NumMyCols(),-1);
805 
806  // Now, for each remote ID, record which processor (in ProcsFrom ordering) owns it.
807  for(i=0,j=0;i<NumRecvs;i++){
808  for(k=0;k<LengthsFrom[i];k++){
809  int pid=ProcsFrom[i];
810  if(pid!=MyPID) RemotePIDOrder[RemoteLIDs[j]]=i;
811  j++;
812  }
813  }
814 
815  // Step One: Start tacking the (GID,PID) pairs on the std sets
816  std::vector<std::set<std::pair<int,int> > > ReversePGIDs(NumRecvs);
817  int *rowptr, *colind;
818  double *vals;
819  EPETRA_CHK_ERR(SourceMatrix.ExtractCrsDataPointers(rowptr,colind,vals));
820 
821 
822  // Loop over each exported row and add to the temp list
823  for(i=0; i < NumExportIDs; i++) {
824  int lid = ExportLIDs[i];
825  int exp_pid = ExportPIDs[i];
826  for(j=rowptr[lid]; j<rowptr[lid+1]; j++){
827  int pid_order = RemotePIDOrder[colind[j]];
828  if(pid_order!=-1) {
829  int gid = SourceMatrix.GCID(colind[j]);
830  // This GID is getting shipped off somewhere
831  ReversePGIDs[pid_order].insert(std::pair<int,int>(exp_pid,gid));
832  }
833  }
834  }
835 
836  // Step 2: Count sizes (one too large to avoid std::vector errors)
837  ReverseSendSizes.resize(NumRecvs+1);
838  int totalsize=0;
839  for(i=0; i<NumRecvs; i++) {
840  ReverseSendSizes[i] = 2*ReversePGIDs[i].size();
841  totalsize += ReverseSendSizes[i];
842  }
843 
844  // Step 3: Alloc and fill the send buffer (one too large to avoid std::vector errors)
845  ReverseSendBuffer.resize(totalsize+1);
846  for(i=0, j=0; i<NumRecvs; i++) {
847  for(std::set<std::pair<int,int> >::iterator it=ReversePGIDs[i].begin(); it!=ReversePGIDs[i].end(); it++) {
848  ReverseSendBuffer[j] = it->first;
849  ReverseSendBuffer[j+1] = it->second;
850  j+=2;
851  }
852  }
853 #endif
854 
855  return 0;
856 }
857 
858 //=========================================================================
859 int build_type3_exports(int MyPID,int Nrecv, Epetra_BlockMap &DomainMap, std::vector<int> &ReverseRecvSizes, const int *ReverseRecvBuffer, std::vector<int> &ExportLID3, std::vector<int> &ExportPID3){
860  int i,j;
861 
862  // Estimate total length of procs_to for Type 3
863  int total_length3=0;
864  for(i=0; i<Nrecv; i++)
865  total_length3+=ReverseRecvSizes[i]/2;
866  if(total_length3==0) return 0;
867 
868  std::vector<int> ExportGID3(total_length3);
869  ExportLID3.resize(total_length3);
870  ExportPID3.resize(total_length3);
871 
872  // Build a sorted colmap-style list for Type3 (removing any self-sends)
873  for(i=0,j=0; i<2*total_length3; i+=2) {
874  if(ReverseRecvBuffer[i] != MyPID){
875  ExportPID3[j]=ReverseRecvBuffer[i];
876  ExportGID3[j]=ReverseRecvBuffer[i+1];
877  j++;
878  }
879  }
880  total_length3=j;
881 
882  if(total_length3==0) return 0;
883 
884  // Sort (ala Epetra_CrsGraph)
885  int * companion = &ExportGID3[0];
886  Epetra_Util::Sort(true,total_length3,&ExportPID3[0],0,0,1,&companion,0,0);
887  int StartCurrent, StartNext;
888  StartCurrent = 0; StartNext = 1;
889  while ( StartNext < total_length3 ) {
890  if(ExportPID3[StartNext] == ExportPID3[StartNext-1]) StartNext++;
891  else {
892  Epetra_Util::Sort(true,StartNext-StartCurrent, &(ExportGID3[StartCurrent]),0,0,0,0, 0, 0);
893  StartCurrent = StartNext; StartNext++;
894  }
895  }
896  Epetra_Util::Sort(true,StartNext-StartCurrent, &(ExportGID3[StartCurrent]),0,0,0,0, 0, 0);
897 
898 
899  /* printf("[%d] Type 3 Sorted= ",MyComm.MyPID());
900  for(i=0; i<total_length3; i++)
901  printf("(--,%2d,%2d) ",ExportGID3[i],ExportPID3[i]);
902  printf("\n");
903  fflush(stdout);*/
904 
905 
906  // Uniq & resize
907  for(i=1,j=1; i<total_length3; i++){
908  if(ExportPID3[i]!=ExportPID3[i-1] || ExportGID3[i]!=ExportGID3[i-1]){
909  ExportPID3[j] = ExportPID3[i];
910  ExportGID3[j] = ExportGID3[i];
911  j++;
912  }
913  }
914  ExportPID3.resize(j);
915  ExportLID3.resize(j);
916  total_length3=j;
917 
918  /* printf("[%d] Type 3 UNIQ = ",MyComm.MyPID());
919  for(i=0; i<total_length3; i++)
920  printf("(--,%2d,%2d) ",ExportGID3[i],ExportPID3[i]);
921  printf("\n");
922  fflush(stdout);*/
923 
924 
925 
926  // Now index down to LIDs
927  for(i=0; i<total_length3; i++) {
928  ExportLID3[i]=DomainMap.LID(ExportGID3[i]);
929  if(ExportLID3[i] < 0) throw std::runtime_error("LightweightCrsMatrix:MakeExportLists invalid LID");
930  }
931 
932  /* printf("[%d] Type 3 FINAL = ",MyComm.MyPID());
933  for(i=0; i<total_length3; i++)
934  printf("(%2d,%2d,%2d) ",ExportLID3[i],ExportGID3[i],ExportPID3[i]);
935  printf("\n");
936  fflush(stdout);*/
937 
938  return total_length3;
939 }
940 
941 //=========================================================================
942 template<typename ImportType>
943 int build_type2_exports(const Epetra_CrsMatrix & SourceMatrix, ImportType & MyImporter, std::vector<int> &ExportLID2, std::vector<int> &ExportPID2){
944  int total_length2=0;
945 #ifdef HAVE_MPI
946  int i,j;
947  const Epetra_Import *SourceImporter= SourceMatrix.Importer();
948 
949  int *rowptr, *colind;
950  double *vals;
951  EPETRA_CHK_ERR(SourceMatrix.ExtractCrsDataPointers(rowptr,colind,vals));
952 
953  // Things related to messages I am sending in forward mode (MyImporter)
954  int NumExportIDs = MyImporter.NumExportIDs();
955  const int* ExportLIDs = MyImporter.ExportLIDs();
956  const int* ExportPIDs = MyImporter.ExportPIDs();
957  if(NumExportIDs==0) return 0;
958 
959  Epetra_Distributor& Distor = MyImporter.Distributor();
960  const Epetra_MpiDistributor * MDistor = dynamic_cast<Epetra_MpiDistributor*>(&Distor);
961 
962  // Assume I own all the cols, then flag any cols I don't own
963  // This allows us to avoid LID calls later...
964  std::vector<bool> IsOwned(SourceMatrix.NumMyCols(),true);
965  if(SourceImporter) {
966  const int * RemoteLIDs = SourceImporter->RemoteLIDs();
967  // Now flag the cols I don't own
968  for(i=0; i<SourceImporter->NumRemoteIDs(); i++)
969  IsOwned[RemoteLIDs[i]]=false;
970  }
971 
972  // Status vector
973  std::vector<int> SentTo(SourceMatrix.NumMyCols(),-1);
974 
975  // Initial allocation: NumUnknowsSent * Max row size (guaranteed to be too large)
976  for(i=0,total_length2=0; i<MDistor->NumSends(); i++) total_length2+= MDistor->LengthsTo()[i] * SourceMatrix.MaxNumEntries();
977  std::vector<int> ExportGID2(total_length2);
978 
979  ExportLID2.resize(total_length2);
980  ExportPID2.resize(total_length2);
981 
982  int current=0, last_start=0, last_pid=ExportPIDs[0];
983  for(i=0; i<NumExportIDs; i++){
984  // For each row I have to send via MyImporter...
985  int row=ExportLIDs[i];
986  int pid=ExportPIDs[i];
987 
988  if(i!=0 && pid>last_pid) {
989  // We have a new PID, so lets finish up the current one
990  if(current!=last_start){
991  int *lids = &ExportLID2[last_start];
992  Epetra_Util::Sort(true,current-last_start,&ExportGID2[last_start],0,0,1,&lids,0,0);
993  // Note: we don't need to sort the ExportPIDs since they're the same since last_start
994  }
995  // Reset the list
996  last_pid=pid;
997  last_start=current;
998  }
999  else if(pid < last_pid) {
1000  throw std::runtime_error("build_type2_exports: ExportPIDs are not sorted!");
1001  }
1002 
1003  for(j=rowptr[row]; j<rowptr[row+1]; j++) {
1004  // For each column in that row...
1005  int col=colind[j];
1006  if(IsOwned[col] && SentTo[col]!=pid){
1007  // We haven't added this guy to the list yet.
1008  if(current>= total_length2) throw std::runtime_error("build_type2_exports: More export ids than I thought!");
1009  SentTo[col] = pid;
1010  ExportGID2[current] = SourceMatrix.GCID(col);
1011  ExportLID2[current] = SourceMatrix.DomainMap().LID(ExportGID2[current]);
1012  ExportPID2[current] = pid;
1013  current++;
1014  }
1015  }
1016  }//end main loop
1017 
1018  // Final Sort
1019  int *lids = &ExportLID2[last_start];
1020  Epetra_Util::Sort(true,current-last_start,&ExportGID2[last_start],0,0,1,&lids,0,0);
1021  // Note: we don't need to sort the ExportPIDs since they're the same since last_start
1022 
1023  total_length2=current;
1024  ExportLID2.resize(total_length2);
1025  ExportPID2.resize(total_length2);
1026 #endif
1027  return total_length2;
1028 }
1029 
1030 //=========================================================================
1031 int build_type1_exports(const Epetra_Import * Importer1, std::vector<int> &ExportLID1, std::vector<int> &ExportPID1){
1032  int i, total_length1=0;
1033  if(!Importer1) return 0;
1034  total_length1 = Importer1->NumSend();
1035  if(total_length1==0) return 0;
1036 
1037  std::vector<int> ExportGID1(total_length1);
1038  ExportLID1.resize(total_length1);
1039  ExportPID1.resize(total_length1);
1040  const int * ExportLID1Base = Importer1->ExportLIDs();
1041  const int * ExportPID1Base = Importer1->ExportPIDs();
1042 
1043  for(i=0; i<total_length1; i++){
1044  ExportLID1[i] = ExportLID1Base[i];
1045  ExportPID1[i] = ExportPID1Base[i];
1046  ExportGID1[i] = Importer1->SourceMap().GID(ExportLID1Base[i]);
1047  }
1048 
1049  // Sort (ala Epetra_CrsGraph)
1050  int * companion[2] = {&ExportLID1[0],&ExportGID1[0]};
1051  Epetra_Util::Sort(true,total_length1,&ExportPID1[0],0,0,2,&companion[0],0,0);
1052 
1053  int StartCurrent, StartNext;
1054  StartCurrent = 0; StartNext = 1;
1055  while ( StartNext < total_length1 ) {
1056  if(ExportPID1[StartNext] == ExportPID1[StartNext-1]) StartNext++;
1057  else {
1058  int *new_companion = {&ExportLID1[StartCurrent]};
1059  Epetra_Util::Sort(true,StartNext-StartCurrent, &(ExportGID1[StartCurrent]),0,0,1,&new_companion, 0, 0);
1060  StartCurrent = StartNext; StartNext++;
1061  }
1062  }
1063  int *new_companion = {&ExportLID1[StartCurrent]};
1064  Epetra_Util::Sort(true,StartNext-StartCurrent, &(ExportGID1[StartCurrent]),0,0,1,&new_companion, 0, 0);
1065  return total_length1;
1066 }
1067 
1068 //=========================================================================
1069 template<typename ImportType>
1070 int LightweightCrsMatrix::MakeExportLists(const Epetra_CrsMatrix & SourceMatrix, ImportType & Importer2,
1071  std::vector<int> &ReverseRecvSizes, const int *ReverseRecvBuffer,
1072  std::vector<int> & ExportPIDs, std::vector<int> & ExportLIDs) {
1073 #ifdef HAVE_MPI
1074  int MyPID = SourceMatrix.Comm().MyPID();
1075 
1076  // This could (legitimately) be zero, in which case we don't have any ReverseRecvs either.
1077  const Epetra_Import *Importer1= SourceMatrix.Importer();
1078 
1079  // So for each entry in the DomainMap, I have to answer the question: Do I need to send this to anybody? And if so, to whom?
1080  //
1081  // This information comes from three sources:
1082  // 1) IDs in my DomainMap that are in someone else's ColMap (e.g. SourceMatrix.Importer()).
1083  // 2) IDs that I own that I sent to another proc in the Forward communication round (e.g. RowImporter).
1084  // 3) IDs that someone else sent on during the Forward round (and they told me about duing the reverse round).
1085  //
1086  // Any of these could legitimately be null.
1087  Epetra_MpiDistributor * Distor1 = (Importer1)?(dynamic_cast<Epetra_MpiDistributor*>(&Importer1->Distributor())):0;
1088 
1089  int Nsend1 = (Distor1)?(Distor1->NumSends()):0; // Also the number of messages we'll need to parse through in build_type3_exports
1090 
1091  std::vector<int> ExportPID3;
1092  std::vector<int> ExportLID3;
1093 
1094  std::vector<int> ExportPID2;
1095  std::vector<int> ExportLID2;
1096 
1097  std::vector<int> ExportPID1;
1098  std::vector<int> ExportLID1;
1099 
1100  // Build (sorted) ExportLID / ExportGID list for Type
1101  int Len1=build_type1_exports(Importer1, ExportLID1, ExportPID1);
1102  int Len2=build_type2_exports<ImportType>(SourceMatrix, Importer2, ExportLID2, ExportPID2);
1103  int Len3=build_type3_exports(MyPID,Nsend1,DomainMap_,ReverseRecvSizes, ReverseRecvBuffer, ExportLID3, ExportPID3);
1104 
1105  // Since everything should now be sorted correctly, we can do a streaming merge of the three Export lists...
1106 #ifdef HAVE_EPETRAEXT_DEBUG
1107  {
1108  int i;
1109  // Now we sanity check the 1 & 2 lists
1110  bool test_passed=true;
1111  for(i=1; i<Len1; i++) {
1112  if(ExportPID1[i] < ExportPID1[i-1] || (ExportPID1[i] == ExportPID1[i-1] && DomainMap_.GID(ExportLID1[i]) < DomainMap_.GID(ExportLID1[i-1])))
1113  test_passed=false;
1114  }
1115  SourceMatrix.Comm().Barrier();
1116  if(!test_passed) {
1117  printf("[%d] Type1 ERRORS = ",SourceMatrix.Comm().MyPID());
1118  for(int i=0; i<Len1; i++)
1119  printf("(%2d,%2d,%2d) ",ExportLID1[i],DomainMap_.GID(ExportLID1[i]),ExportPID1[i]);
1120  printf("\n");
1121  fflush(stdout);
1122  throw std::runtime_error("Importer1 fails the sanity test");
1123  }
1124 
1125  for(i=1; i<Len2; i++) {
1126  if(ExportPID2[i] < ExportPID2[i-1] || (ExportPID2[i] == ExportPID2[i-1] && DomainMap_.GID(ExportLID2[i]) < DomainMap_.GID(ExportLID2[i-1])))
1127  test_passed=false;
1128  }
1129 
1130  SourceMatrix.Comm().Barrier();
1131  if(!test_passed) {
1132  printf("[%d] Type2 ERRORS = ",SourceMatrix.Comm().MyPID());
1133  for(int i=0; i<Len2; i++)
1134  printf("(%2d,%2d,%2d) ",ExportLID2[i],DomainMap_.GID(ExportLID2[i]),ExportPID2[i]);
1135  printf("\n");
1136  fflush(stdout);
1137  throw std::runtime_error("Importer2 fails the sanity test");
1138  }
1139 
1140  for(i=1; i<Len3; i++) {
1141  if(ExportPID3[i] < ExportPID3[i-1] || (ExportPID3[i] == ExportPID3[i-1] && DomainMap_.GID(ExportLID3[i]) < DomainMap_.GID(ExportLID3[i-1])))
1142  test_passed=false;
1143  }
1144 
1145  SourceMatrix.Comm().Barrier();
1146  if(!test_passed) {
1147  printf("[%d] Type3 ERRORS = ",SourceMatrix.Comm().MyPID());
1148  for(int i=0; i<Len3; i++)
1149  printf("(%2d,%2d,%2d) ",ExportLID3[i],DomainMap_.GID(ExportLID3[i]),ExportPID3[i]);
1150  printf("\n");
1151  fflush(stdout);
1152  throw std::runtime_error("Importer3 fails the sanity test");
1153  }
1154 
1155 
1156  }
1157 #endif
1158 
1159  if(Importer1 && !Importer1->SourceMap().SameAs(DomainMap_))
1160  throw std::runtime_error("ERROR: Map Mismatch Importer1");
1161 
1162  if(!Importer2.SourceMap().SameAs(SourceMatrix.RowMap()))
1163  throw std::runtime_error("ERROR: Map Mismatch Importer2");
1164 
1165  int InfGID = INT_MAX;
1166  int InfPID = INT_MAX;
1167 
1168  int i1=0, i2=0, i3=0, current=0;
1169 
1170  int MyLen=Len1+Len2+Len3;
1171  ExportLIDs.resize(MyLen);
1172  ExportPIDs.resize(MyLen);
1173 
1174  while(i1 < Len1 || i2 < Len2 || i3 < Len3){
1175  int PID1 = (i1<Len1)?(ExportPID1[i1]):InfPID;
1176  int PID2 = (i2<Len2)?(ExportPID2[i2]):InfPID;
1177  int PID3 = (i3<Len3)?(ExportPID3[i3]):InfPID;
1178 
1179  int GID1 = (i1<Len1)?(DomainMap_.GID(ExportLID1[i1])):InfGID;
1180  int GID2 = (i2<Len2)?(DomainMap_.GID(ExportLID2[i2])):InfGID;
1181  int GID3 = (i3<Len3)?(DomainMap_.GID(ExportLID3[i3])):InfGID;
1182 
1183  int MIN_PID = MIN3(PID1,PID2,PID3);
1184  int MIN_GID = MIN3( ((PID1==MIN_PID)?GID1:InfGID), ((PID2==MIN_PID)?GID2:InfGID), ((PID3==MIN_PID)?GID3:InfGID));
1185  bool added_entry=false;
1186 
1187  // Case 1: Add off list 1
1188  if(PID1 == MIN_PID && GID1 == MIN_GID){
1189  ExportLIDs[current] = ExportLID1[i1];
1190  ExportPIDs[current] = ExportPID1[i1];
1191  current++;
1192  i1++;
1193  added_entry=true;
1194  }
1195 
1196  // Case 2: Add off list 2
1197  if(PID2 == MIN_PID && GID2 == MIN_GID){
1198  if(!added_entry) {
1199  ExportLIDs[current] = ExportLID2[i2];
1200  ExportPIDs[current] = ExportPID2[i2];
1201  current++;
1202  added_entry=true;
1203  }
1204  i2++;
1205  }
1206 
1207  // Case 3: Add off list 3
1208  if(PID3 == MIN_PID && GID3 == MIN_GID){
1209  if(!added_entry) {
1210  ExportLIDs[current] = ExportLID3[i3];
1211  ExportPIDs[current] = ExportPID3[i3];
1212  current++;
1213  }
1214  i3++;
1215  }
1216  }// end while
1217  if(current!=MyLen) {
1218  ExportLIDs.resize(current);
1219  ExportPIDs.resize(current);
1220  }
1221 #endif
1222  return 0;
1223 }
1224 
1225 //=========================================================================
1226 template<typename ImportType>
1227 void LightweightCrsMatrix::Construct(const Epetra_CrsMatrix & SourceMatrix, ImportType & RowImporter)
1228 {
1229  // Do we need to use long long for GCIDs?
1230  bool UseLL=false;
1231  int SizeofIntType=-1;
1232 
1233  // Get the size of int typpe
1234  if(SourceMatrix.Map().GlobalIndicesInt()) {
1235  SizeofIntType = (int)sizeof(int);
1236  UseLL=false;
1237  }
1238  else if(SourceMatrix.Map().GlobalIndicesLongLong()) {
1239  SizeofIntType = (int)sizeof(long long);
1240  UseLL=true;
1241  }
1242  else
1243  throw std::runtime_error("EpetraExt::LightweightCrsMatrix::Construct: Unable to determine source global index type");
1244 
1245 #ifdef ENABLE_MMM_TIMINGS
1246  Teuchos::Time myTime("global");
1247  Teuchos::TimeMonitor MM(myTime);
1248  Teuchos::RCP<Teuchos::Time> mtime;
1249  mtime=MM.getNewTimer("LWCRS C-1");
1250  mtime->start();
1251 #endif
1252 
1253  // Fused constructor, import & FillComplete
1254  int i,rv=0;
1255  int N;
1256  if(use_lw) N = RowMapLW_->NumMyElements();
1257  else N = RowMapEP_->NumMyElements();
1258 
1259  // int MyPID = SourceMatrix.Comm().MyPID();
1260 
1261 #ifdef HAVE_MPI
1262  std::vector<int> ReverseSendSizes, ReverseSendBuffer;
1263  std::vector<int> ReverseRecvSizes;
1264  int * ReverseRecvBuffer=0;
1265 #endif
1266 
1267  bool communication_needed = RowImporter.SourceMap().DistributedGlobal();
1268 
1269  // The basic algorithm here is:
1270  // 1) Call Distor.Do to handle the import.
1271  // 2) Copy all the Imported and Copy/Permuted data into the raw Epetra_CrsMatrix / Epetra_CrsGraphData pointers, still using GIDs.
1272  // 3) Call an optimized version of MakeColMap that avoids the Directory lookups (since the importer knows who owns all the gids) AND
1273  // reindexes to LIDs.
1274 
1275  // Sanity Check
1276  if (!SourceMatrix.RowMap().SameAs(RowImporter.SourceMap()))
1277  throw "LightweightCrsMatrix: Fused copy constructor requires Importer.SourceMap() to match SourceMatrix.RowMap()";
1278 
1279  // Get information from the Importer
1280  int NumSameIDs = RowImporter.NumSameIDs();
1281  int NumPermuteIDs = RowImporter.NumPermuteIDs();
1282  int NumRemoteIDs = RowImporter.NumRemoteIDs();
1283  int NumExportIDs = RowImporter.NumExportIDs();
1284  int* ExportLIDs = RowImporter.ExportLIDs();
1285  int* RemoteLIDs = RowImporter.RemoteLIDs();
1286  int* PermuteToLIDs = RowImporter.PermuteToLIDs();
1287  int* PermuteFromLIDs = RowImporter.PermuteFromLIDs();
1288  Epetra_Distributor& Distor = RowImporter.Distributor();
1289 
1290 #ifdef HAVE_MPI
1291  const Epetra_MpiComm * MpiComm = dynamic_cast<const Epetra_MpiComm*>(&SourceMatrix.Comm());
1292  const Epetra_MpiDistributor * MDistor = dynamic_cast<Epetra_MpiDistributor*>(&Distor);
1293 #endif
1294 
1295  // Allocate memory
1296  rowptr_.resize(N+1);
1297 
1298 
1299  // Owning PIDs
1300  std::vector<int> SourcePids;
1301  std::vector<int> TargetPids;
1302 
1303 
1304  /***************************************************/
1305  /***** 1) From Epetra_DistObject::DoTransfer() *****/
1306  /***************************************************/
1307  // rv=SourceMatrix.CheckSizes(SourceMatrix);
1308 
1309  // NTS: Add CheckSizes stuff here.
1310  if(rv) throw "LightweightCrsMatrix: Fused copy constructor failed in CheckSizes()";
1311 
1312  // Buffers & Other Relevant Info
1313  char* Exports_ = 0;
1314  char* Imports_ = 0;
1315  int LenImports_ =0;
1316  int LenExports_ = 0;
1317  int *Sizes_ = 0;
1318 
1319  int SizeOfPacket;
1320  bool VarSizes = false;
1321  if( NumExportIDs > 0) {
1322  Sizes_ = new int[NumExportIDs];
1323  }
1324 
1325 
1326  // Get the owning PIDs
1327  const Epetra_Import *MyImporter= SourceMatrix.Importer();
1328  if(MyImporter) Epetra_Util::GetPids(*MyImporter,SourcePids,false);
1329  else {
1330  SourcePids.resize(SourceMatrix.ColMap().NumMyElements());
1331  SourcePids.assign(SourceMatrix.ColMap().NumMyElements(),SourceMatrix.Comm().MyPID());
1332  }
1333 
1334  // Pack & Prepare w/ owning PIDs
1335  rv=Epetra_Import_Util::PackAndPrepareWithOwningPIDs(SourceMatrix,
1336  NumExportIDs,ExportLIDs,
1337  LenExports_,Exports_,SizeOfPacket,
1338  Sizes_,VarSizes,SourcePids);
1339  if(rv) throw "LightweightCrsMatrix: Fused copy constructor failed in PackAndPrepare()";
1340 
1341  if (communication_needed) {
1342 #ifdef HAVE_MPI
1343  // Do the exchange of remote data
1344  int curr_pid;
1345  const int * ExportPIDs = RowImporter.ExportPIDs();
1346 
1347  // Use the fact that the export procs are sorted to avoid building a hash table.
1348  // NOTE: The +1's on the message size lists are to avoid std::vector problems if a proc has no sends or recvs.
1349  std::vector<int> SendSizes(MDistor->NumSends()+1,0);
1350  for(i=0, curr_pid=0; i<NumExportIDs; i++) {
1351  if(i>0 && ExportPIDs[i] > ExportPIDs[i-1]) curr_pid++;
1352  SendSizes[curr_pid] +=Sizes_[i];
1353 
1354  // sanity check
1355  if(i>0 && ExportPIDs[i] < ExportPIDs[i-1]) throw "ExportPIDs not sorted";
1356  }
1357 
1358  std::vector<int> RecvSizes(MDistor->NumReceives()+1);
1359  int msg_tag=MpiComm->GetMpiTag();
1360  boundary_exchange_varsize<char>(*MpiComm,MPI_CHAR,MDistor->NumSends(),MDistor->ProcsTo(),&SendSizes[0],Exports_,
1361  MDistor->NumReceives(),MDistor->ProcsFrom(),&RecvSizes[0],Imports_,SizeOfPacket,msg_tag);
1362 
1363  // If the source matrix doesn't have an importer, then nobody sent data belonging to me in the forward round.
1364  if(SourceMatrix.Importer()) {
1365  Epetra_Import* SourceImporter=const_cast<Epetra_Import*>(SourceMatrix.Importer());
1366  const Epetra_MpiDistributor * MyDistor = dynamic_cast<Epetra_MpiDistributor*>(&SourceImporter->Distributor());
1367 
1368  // Setup the reverse communication
1369  // Note: Buffer pairs are in (PID,GID) order
1370  PackAndPrepareReverseComm<ImportType>(SourceMatrix,RowImporter,ReverseSendSizes,ReverseSendBuffer);
1371 
1372  // Do the reverse communication
1373  // NOTE: Make the vector one too large to avoid std::vector errors
1374  ReverseRecvSizes.resize(MyDistor->NumSends()+1);
1375  int msg_tag=MpiComm->GetMpiTag();
1376  boundary_exchange_varsize<int>(*MpiComm,MPI_INT,MyDistor->NumReceives(),MyDistor->ProcsFrom(),&ReverseSendSizes[0],&ReverseSendBuffer[0],
1377  MyDistor->NumSends(),MyDistor->ProcsTo(),&ReverseRecvSizes[0],ReverseRecvBuffer,1,msg_tag);
1378  }
1379 #endif
1380  }
1381 
1382  if(rv) throw "LightweightCrsMatrix: Fused copy constructor failed in Distor.Do";
1383 
1384  /*********************************************************************/
1385  /**** 2) Copy all of the Same/Permute/Remote data into CSR_arrays ****/
1386  /*********************************************************************/
1387 #ifdef ENABLE_MMM_TIMINGS
1388  mtime->stop();
1389  mtime=MM.getNewTimer("LWCRS C-2");
1390  mtime->start();
1391 #endif
1392 
1393  // Count nnz
1394  int mynnz = Epetra_Import_Util::UnpackWithOwningPIDsCount(SourceMatrix,NumSameIDs,NumRemoteIDs,RemoteLIDs,NumPermuteIDs,PermuteToLIDs,PermuteFromLIDs,LenImports_,Imports_);
1395  // Presume the rowptr_ is the right size
1396  // Allocate colind_ & vals_ arrays
1397  colind_.resize(mynnz);
1398  vals_.resize(mynnz);
1399 
1400  // Reset the Source PIDs (now with -1 rule)
1401  if(MyImporter) Epetra_Util::GetPids(*MyImporter,SourcePids,true);
1402  else {
1403  SourcePids.assign(SourceMatrix.ColMap().NumMyElements(),-1);
1404  }
1405 
1406  // Unpack into arrays
1407  int * myrowptr = rowptr_.size() ? & rowptr_[0] : 0;
1408  int * mycolind = colind_.size() ? & colind_[0] : 0;
1409  double * myvals = vals_.size() ? & vals_[0] : 0;
1410  Epetra_Import_Util::UnpackAndCombineIntoCrsArrays(SourceMatrix,NumSameIDs,NumRemoteIDs,RemoteLIDs,NumPermuteIDs,PermuteToLIDs,PermuteFromLIDs,LenImports_,Imports_,N,mynnz,myrowptr,mycolind,myvals,SourcePids,TargetPids);
1411 
1412  /**************************************************************/
1413  /**** 3) Call Optimized MakeColMap w/ no Directory Lookups ****/
1414  /**************************************************************/
1415 #ifdef ENABLE_MMM_TIMINGS
1416  mtime->stop();
1417  mtime=MM.getNewTimer("LWCRS C-3");
1418  mtime->start();
1419 #endif
1420 
1421  //Call an optimized version of MakeColMap that avoids the Directory lookups (since the importer knows who owns all the gids).
1422  if(UseLL) MakeColMapAndReindex<long long>(TargetPids,colind_LL_);
1423  else MakeColMapAndReindex<int>(TargetPids,colind_);
1424 
1425  /********************************************/
1426  /**** 4) Make Export Lists for Import ****/
1427  /********************************************/
1428 #ifdef HAVE_MPI
1429  MakeExportLists<ImportType>(SourceMatrix,RowImporter,ReverseRecvSizes,ReverseRecvBuffer,ExportPIDs_,ExportLIDs_);
1430 #endif
1431 
1432  /********************************************/
1433  /**** 5) Call sort the entries ****/
1434  /********************************************/
1435  // NOTE: If we have no entries the &blah[0] will cause the STL to die in debug mode
1436 #ifdef ENABLE_MMM_TIMINGS
1437  mtime->stop();
1438  mtime=MM.getNewTimer("LWCRS C-4");
1439  mtime->start();
1440 #endif
1441  if(N>0) Epetra_Util::SortCrsEntries(N, &rowptr_[0], &colind_[0], &vals_[0]);
1442 
1443  /********************************************/
1444  /**** 6) Cleanup ****/
1445  /********************************************/
1446 #ifdef ENABLE_MMM_TIMINGS
1447  mtime->stop();
1448  mtime=MM.getNewTimer("LWCRS C-5");
1449  mtime->start();
1450 #endif
1451 
1452 #ifdef HAVE_MPI
1453  delete [] ReverseRecvBuffer;
1454 #endif
1455 
1456  delete [] Exports_;
1457  delete [] Imports_;
1458  delete [] Sizes_;
1459 
1460 #ifdef ENABLE_MMM_TIMINGS
1461  mtime->stop();
1462 #endif
1463  }// end fused copy constructor
1464 
1465 
1466 
1467 
1468 //=========================================================================
1469 LightweightCrsMatrix::LightweightCrsMatrix(const Epetra_CrsMatrix & SourceMatrix, RemoteOnlyImport & RowImporter):
1470  use_lw(true),
1471  RowMapLW_(0),
1472  RowMapEP_(0),
1473  DomainMap_(SourceMatrix.DomainMap())
1474 {
1475 #ifdef ENABLE_MMM_TIMINGS
1476  Teuchos::Time myTime("global");
1477  Teuchos::TimeMonitor MM(myTime);
1478  Teuchos::RCP<Teuchos::Time> mtime;
1479  mtime=MM.getNewTimer("LWCRS Total");
1480  mtime->start();
1481 #endif
1482  RowMapLW_= new LightweightMap(RowImporter.TargetMap());
1483 
1484  Construct<RemoteOnlyImport>(SourceMatrix,RowImporter);
1485 #ifdef ENABLE_MMM_TIMINGS
1486  mtime->stop();
1487 #endif
1488 
1489 }
1490 
1491 
1492 //=========================================================================
1493 LightweightCrsMatrix::LightweightCrsMatrix(const Epetra_CrsMatrix & SourceMatrix, Epetra_Import & RowImporter):
1494  use_lw(false),
1495  RowMapLW_(0),
1496  RowMapEP_(0),
1497  DomainMap_(SourceMatrix.DomainMap())
1498 {
1499  RowMapEP_= new Epetra_BlockMap(RowImporter.TargetMap());
1500  Construct<Epetra_Import>(SourceMatrix,RowImporter);
1501 }
1502 
1503 
1505  delete RowMapLW_;
1506  delete RowMapEP_;
1507 }
1508 
1509 
1510 }//namespace EpetraExt
1511 
int build_type3_exports(int MyPID, int Nrecv, Epetra_BlockMap &DomainMap, std::vector< int > &ReverseRecvSizes, const int *ReverseRecvBuffer, std::vector< int > &ExportLID3, std::vector< int > &ExportPID3)
LightweightCrsMatrix * importMatrix
RemoteOnlyImport(const Epetra_Import &Importer, LightweightMap &RemoteOnlyTargetMap)
std::vector< int > targetMapToOrigRow
int SumIntoGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)
void pack_outgoing_rows(const Epetra_CrsMatrix &mtx, const std::vector< int > &proc_col_ranges, std::vector< int > &send_rows, std::vector< int > &rows_per_send_proc)
int InsertGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)
const Epetra_CrsMatrix * origMatrix
EpetraExt::BlockCrsMatrix: A class for constructing a distributed block matrix.
static bool lessthan12(std::pair< int, int > i, std::pair< int, int > j)
int InsertGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)
std::vector< int > targetMapToImportRow
LightweightMap & operator=(const LightweightMap &map)
std::pair< int, int > get_col_range(const Epetra_Map &emap)
int SumIntoGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)
#define MIN3(x, y, z)
LightweightCrsMatrix(const Epetra_CrsMatrix &A, RemoteOnlyImport &RowImporter)
CrsWrapper_Epetra_CrsMatrix(Epetra_CrsMatrix &epetracrsmatrix)
Epetra_HashTable< int > * LIDHash_
const LightweightMap & TargetMap() const
int build_type1_exports(const Epetra_Import *Importer1, std::vector< int > &ExportLID1, std::vector< int > &ExportPID1)
std::map< int, std::set< int > * > & get_graph()
int build_type2_exports(const Epetra_CrsMatrix &SourceMatrix, ImportType &MyImporter, std::vector< int > &ExportLID2, std::vector< int > &ExportPID2)
const Epetra_BlockMap * importColMap
int dumpCrsMatrixStruct(const CrsMatrixStruct &M)
void insert_matrix_locations(CrsWrapper_GraphBuilder &graphbuilder, Epetra_CrsMatrix &C)
CrsWrapper_GraphBuilder(const Epetra_Map &emap)