EpetraExt  Development
EpetraExt_MatrixMatrix_mult_A_B.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_MatrixMatrix.h>
44 
45 #include <EpetraExt_MMHelpers.h>
46 
48 
49 #include <Epetra_Export.h>
50 #include <Epetra_Import.h>
51 #include <Epetra_Util.h>
52 #include <Epetra_Map.h>
53 #include <Epetra_Comm.h>
54 #include <Epetra_CrsMatrix.h>
55 #include <Epetra_Directory.h>
56 #include <Epetra_HashTable.h>
57 #include <Epetra_Distributor.h>
58 #include <Epetra_IntSerialDenseVector.h>
59 
60 #ifdef HAVE_VECTOR
61 #include <vector>
62 #endif
63 
64 #ifdef HAVE_MPI
65 #include <Epetra_MpiDistributor.h>
66 #endif
67 
68 
69 #include <Teuchos_TimeMonitor.hpp>
70 
71 namespace EpetraExt {
72 
73 /*****************************************************************************/
74 /*****************************************************************************/
75 /*****************************************************************************/
76 static inline int C_estimate_nnz(const Epetra_CrsMatrix & A, const Epetra_CrsMatrix &B){
77  // Follows the NZ estimate in ML's ml_matmatmult.c
78  int Aest=(A.NumMyRows()>0)? A.NumMyNonzeros()/A.NumMyRows():100;
79  int Best=(B.NumMyRows()>0)? B.NumMyNonzeros()/B.NumMyRows():100;
80 
81  int nnzperrow=(int)(sqrt((double)Aest) + sqrt((double)Best) - 1);
82  nnzperrow*=nnzperrow;
83 
84  return (int)(A.NumMyRows()*nnzperrow*0.75 + 100);
85 }
86 
87 /*****************************************************************************/
88 /*****************************************************************************/
89 /*****************************************************************************/
90 static inline int auto_resize(std::vector<int> &x,int num_new){
91  int newsize=x.size() + EPETRA_MAX((int)x.size(),num_new);
92  x.resize(newsize);
93  return newsize;
94 }
95 
96 
97 /*****************************************************************************/
98 /*****************************************************************************/
99 /*****************************************************************************/
100 int aztecoo_and_ml_compatible_map_union(const Epetra_CrsMatrix &B, const LightweightCrsMatrix &Bimport, Epetra_Map*& unionmap, std::vector<int>& Cremotepids,
101  std::vector<int> &Bcols2Ccols, std::vector<int> &Icols2Ccols)
102 {
103 #ifdef HAVE_MPI
104 
105 #ifdef ENABLE_MMM_TIMINGS
106  Teuchos::Time myTime("global");
107  Teuchos::TimeMonitor M(myTime);
108  Teuchos::RCP<Teuchos::Time> mtime;
109  mtime=M.getNewTimer("M5 CMap 1");
110  mtime->start();
111 #endif
112 
113  // So we need to merge the ColMap of B and the TargetMap of Bimport in an AztecOO/Ifpack/ML compliant order.
114  Epetra_Util util;
115  int i,j,MyPID = B.Comm().MyPID(), NumProc = B.Comm().NumProc();
116  int Bstart=0, Istart=0, Cstart=0,Pstart=0;
117 
118  const Epetra_Map & BColMap = B.ColMap();
119  const Epetra_Map & DomainMap = B.DomainMap();
120  const LightweightMap & IColMap = Bimport.ColMap_;
121 
122  int Nb = BColMap.NumMyElements();
123  int * Bgids = BColMap.MyGlobalElements();
124  int Ni = IColMap.NumMyElements();
125  int * Igids = (Ni>0)?(IColMap.MyGlobalElements()):0;
126 
127  if((int)Bcols2Ccols.size() != Nb) Bcols2Ccols.resize(Nb);
128  if((int)Icols2Ccols.size() != Ni) Icols2Ccols.resize(Ni);
129 
130  // Since we're getting called, we know we have to be using an MPI implementation of Epetra.
131  // Which means we should have an MpiDistributor for both B and Bimport.
132  // Unless all of B's columns are owned by the calling proc (e.g. MueLu for A*Ptent w/ uncoupled aggregation)
133  Epetra_MpiDistributor *Distor=0;
134  if(B.Importer()) {
135  Distor=dynamic_cast<Epetra_MpiDistributor*>(&B.Importer()->Distributor());
136  if(!Distor) EPETRA_CHK_ERR(-2);
137  }
138 
139  // **********************
140  // Stage 1: Get the owning PIDs
141  // **********************
142  // Note: if B doesn't have an importer, the calling proc owns all its colids...
143  std::vector<int> Bpids(Nb), Ipids(Ni);
144  if(B.Importer()) {EPETRA_CHK_ERR(util.GetPids(*B.Importer(),Bpids,true));}
145  else Bpids.assign(Nb,-1);
146 
147  if(Ni != (int) Bimport.ColMapOwningPIDs_.size()) {
148  EPETRA_CHK_ERR(-21);
149  }
150  for(i=0;i<Ni;i++){
151  Ipids[i] = (Bimport.ColMapOwningPIDs_[i]==MyPID)?(-1):(Bimport.ColMapOwningPIDs_[i]);
152  }
153 
154  // **********************
155  // Stage 2: Allocate memory (make things too big)
156  // **********************
157  int Csize=Nb+Ni;
158  int Psize=Nb+Ni;
159  std::vector<int> Cgids(Csize);
160  Cremotepids.resize(Psize);
161 
162 #ifdef ENABLE_MMM_TIMINGS
163  mtime->stop();
164  mtime=M.getNewTimer("M5 CMap 2");
165  mtime->start();
166 #endif
167 
168  // **********************
169  // Stage 3: Local Unknowns
170  // **********************
171  if(!B.Importer() || (B.Importer()->NumSameIDs() == DomainMap.NumMyElements())) {
172  // B's colmap has all of the domain elements. We can just copy those into the start of the array.
173  DomainMap.MyGlobalElements(&Cgids[0]);
174  Cstart=DomainMap.NumMyElements();
175  Bstart=DomainMap.NumMyElements();
176 
177  for(i=0; i<DomainMap.NumMyElements(); i++) Bcols2Ccols[i] = i;
178  }
179  else {
180  // There are more entries in the DomainMap than B's ColMap. So we stream through both B and Bimport for the copy.
181  int NumDomainElements = DomainMap.NumMyElements();
182  for(i = 0; i < NumDomainElements; i++) {
183  int GID = DomainMap.GID(i);
184  int LID = BColMap.LID(GID);
185  // B has this guy
186  if(LID!=-1) {
187  Bcols2Ccols[LID]=Cstart;
188  Cgids[Cstart] = GID;
189  Cstart++;
190  Bstart++;
191  }
192  else {
193  // B import has this guy
194  LID = IColMap.LID(GID);
195  if(LID!=-1) {
196  Icols2Ccols[LID]=Cstart;
197  Cgids[Cstart] = GID;
198  Cstart++;
199  }
200  }
201  }
202  }
203 
204  // Now advance Ilast to the last owned unknown in Bimport
205  for(i=0,j=0; i<Ni && Ipids[i]==-1; i++) {
206  while(Cgids[j]!=Igids[i]) j++;
207  Icols2Ccols[i]=j;
208  }
209  Istart=i;
210 
211 
212 #ifdef ENABLE_MMM_TIMINGS
213  mtime->stop();
214  mtime=M.getNewTimer("M5 CMap 3");
215  mtime->start();
216 #endif
217 
218 
219  // **********************
220  // Stage 4: Processor-by-processor set_union
221  // **********************
222  // NOTE: Intial sizes for Btemp/Itemp from B's distributor. This should be exact for Btemp and a decent guess for Itemp
223  int initial_temp_length = 0;
224  const int * lengths_from=0;
225  if(Distor) {
226  lengths_from= Distor->LengthsFrom();
227  for(i=0; i < Distor->NumReceives(); i++) initial_temp_length += lengths_from[i];
228  }
229  else initial_temp_length=100;
230 
231  std::vector<int> Btemp(initial_temp_length), Itemp(initial_temp_length);
232  std::vector<int> Btemp2(initial_temp_length), Itemp2(initial_temp_length);
233 
234 
235  while (Bstart < Nb || Istart < Ni) {
236  int Bproc=NumProc+1, Iproc=NumProc+1, Cproc;
237 
238  // Find the next active processor ID
239  if(Bstart < Nb) Bproc=Bpids[Bstart];
240  if(Istart < Ni) Iproc=Ipids[Istart];
241 
242  Cproc = (Bproc < Iproc)?Bproc:Iproc;
243 
244  if(Bproc == Cproc && Iproc != Cproc) {
245  // Only B has this processor. Copy the data.
246  // B: Find the beginning of the next processor
247  for(i=Bstart; i<Nb && Bpids[i]==Bproc; i++) {}
248  int Bnext=i;
249 
250  // Copy data to C
251  int tCsize = Bnext-Bstart;
252  if(Btemp.size() < (size_t)tCsize) {Btemp2.resize(tCsize);}
253 
254  for(i=Bstart; i<Bnext; i++) {
255  Cremotepids[i-Bstart+Pstart] = Cproc;
256  Cgids[i-Bstart+Cstart] = Bgids[i];
257  Btemp2[i-Bstart] = i;
258  }
259 
260  // Sort & record reindexing
261  int *Bptr2 = &Btemp2[0];
262  util.Sort(true, tCsize, &Cgids[Cstart], 0, 0, 1, &Bptr2);
263 
264  for(i=0, j=Cstart; i<tCsize; i++){
265  while(Cgids[j] != Bgids[Btemp2[i]]) j++;
266  Bcols2Ccols[Btemp2[i]] = j;
267  }
268  Cstart+=tCsize;
269  Pstart+=tCsize;
270  Bstart=Bnext;
271  }
272  else if(Bproc != Cproc && Iproc == Cproc) {
273  // Only I has this processor. Copy the data.
274  // I: Find the beginning of the next processor
275  for(i=Istart; i<Ni && Ipids[i]==Iproc; i++) {}
276  int Inext=i;
277 
278  // Copy data to C
279  int tCsize = Inext-Istart;
280  if(Itemp.size() < (size_t)tCsize) {Itemp2.resize(tCsize);}
281 
282  for(i=Istart; i<Inext; i++) {
283  Cremotepids[i-Istart+Pstart] = Cproc;
284  Cgids[i-Istart+Cstart] = Igids[i];
285  Itemp2[i-Istart] = i;
286  }
287 
288  // Sort & record reindexing
289  int *Iptr2 = &Itemp2[0];
290  util.Sort(true, tCsize, &Cgids[Cstart], 0, 0, 1, &Iptr2);
291 
292  for(i=0, j=Cstart; i<tCsize; i++){
293  while(Cgids[j] != Igids[Itemp2[i]]) j++;
294  Icols2Ccols[Itemp2[i]] = j;
295  }
296  Cstart+=tCsize;
297  Pstart+=tCsize;
298  Istart=Inext;
299  }
300  else {
301  // Both B and I have this processor, so we need to do a set_union. So we need to sort.
302  int Bnext, Inext;
303  // B: Find the beginning of the next processor
304  for(i=Bstart; i<Nb && Bpids[i]==Bproc; i++) {}
305  Bnext=i;
306 
307  // I: Find the beginning of the next processor
308  for(i=Istart; i<Ni && Ipids[i]==Iproc; i++) {}
309  Inext=i;
310 
311  // Copy data to temp
312  int tBsize = Bnext-Bstart;
313  int tIsize = Inext-Istart;
314  // int tCsize = tBsize+tIsize;
315  if(Btemp.size() < (size_t)tBsize) {Btemp.resize(tBsize); Btemp2.resize(tBsize);}
316  if(Itemp.size() < (size_t)tIsize) {Itemp.resize(tIsize); Itemp2.resize(tIsize);}
317 
318  for(i=Bstart; i<Bnext; i++) {Btemp[i-Bstart]=Bgids[i]; Btemp2[i-Bstart]=i;}
319  for(i=Istart; i<Inext; i++) {Itemp[i-Istart]=Igids[i]; Itemp2[i-Istart]=i;}
320 
321  // Sort & set_union
322  int *Bptr2 = &Btemp2[0]; int *Iptr2 = &Itemp2[0];
323  util.Sort(true, tBsize, &Btemp[0], 0, 0, 1, &Bptr2);
324  util.Sort(true, tIsize, &Itemp[0], 0, 0, 1, &Iptr2);
325  std::vector<int>::iterator mycstart = Cgids.begin()+Cstart;
326  std::vector<int>::iterator last_el=std::set_union(Btemp.begin(),Btemp.begin()+tBsize,Itemp.begin(),Itemp.begin()+tIsize,mycstart);
327 
328  for(i=0, j=Cstart; i<tBsize; i++){
329  while(Cgids[j] != Bgids[Btemp2[i]]) j++;
330  Bcols2Ccols[Btemp2[i]] = j;
331  }
332 
333  for(i=0, j=Cstart; i<tIsize; i++){
334  while(Cgids[j] != Igids[Itemp2[i]]) j++;
335  Icols2Ccols[Itemp2[i]] = j;
336  }
337 
338  for(i=Pstart; i<(last_el - mycstart) + Pstart; i++) Cremotepids[i]=Cproc;
339  Cstart = (last_el - mycstart) + Cstart;
340  Pstart = (last_el - mycstart) + Pstart;
341  Bstart=Bnext;
342  Istart=Inext;
343  }
344  } // end while
345 
346 
347 
348 #ifdef ENABLE_MMM_TIMINGS
349  mtime->stop();
350  mtime=M.getNewTimer("M5 CMap 4");
351  mtime->start();
352 #endif
353 
354  // Resize the RemotePIDs down
355  Cremotepids.resize(Pstart);
356 
357  // **********************
358  // Stage 5: Call constructor
359  // **********************
360  // Make the map
361  unionmap=new Epetra_Map(-1,Cstart,&Cgids[0],B.ColMap().IndexBase(),B.Comm(),B.ColMap().DistributedGlobal(),B.ColMap().MinAllGID(),B.ColMap().MaxAllGID());
362 #ifdef ENABLE_MMM_TIMINGS
363  mtime->stop();
364 #endif
365  return 0;
366 #else
367  return -1;
368 #endif
369  }
370 
371 /*****************************************************************************/
372 /*****************************************************************************/
373 /*****************************************************************************/
374 // Provide a "resize" operation for double*'s.
375 inline void resize_doubles(int nold,int nnew,double*& d){
376  if(nnew > nold){
377  double *tmp = new double[nnew];
378  for(int i=0; i<nold; i++)
379  tmp[i]=d[i];
380  delete [] d;
381  d=tmp;
382  }
383 }
384 
385 
386 /*****************************************************************************/
387 /*****************************************************************************/
388 /*****************************************************************************/
389 int mult_A_B_newmatrix(const Epetra_CrsMatrix & A,
390  const Epetra_CrsMatrix & B,
391  CrsMatrixStruct& Bview,
392  std::vector<int> & Bcol2Ccol,
393  std::vector<int> & Bimportcol2Ccol,
394  std::vector<int>& Cremotepids,
395  Epetra_CrsMatrix& C
396 ){
397 #ifdef ENABLE_MMM_TIMINGS
398  Teuchos::Time myTime("global");
399  Teuchos::TimeMonitor M(myTime);
400  Teuchos::RCP<Teuchos::Time> mtime;
401  mtime=M.getNewTimer("M5 SerialCore");
402  mtime->start();
403 #endif
404 
405  // *****************************
406  // Improved Parallel Gustavson in Local IDs
407  // *****************************
408  const Epetra_Map * colmap_C = &(C.ColMap());
409 
410 
411  int NumMyDiagonals=0; // Counter to speed up ESFC
412 
413  int m=A.NumMyRows();
414  int n=colmap_C->NumMyElements();
415  int i,j,k;
416 
417  // DataPointers for A
418  int *Arowptr, *Acolind;
419  double *Avals;
420  EPETRA_CHK_ERR(A.ExtractCrsDataPointers(Arowptr,Acolind,Avals));
421 
422  // DataPointers for B, Bimport
423  int *Browptr, *Bcolind;
424  double *Bvals;
425  EPETRA_CHK_ERR(B.ExtractCrsDataPointers(Browptr,Bcolind,Bvals));
426 
427  int *Irowptr=0, *Icolind=0;
428  double *Ivals=0;
429  if(Bview.importMatrix){
430  Irowptr = &Bview.importMatrix->rowptr_[0];
431  Icolind = (Bview.importMatrix->colind_.size()>0)?(&Bview.importMatrix->colind_[0]):0;
432  Ivals = (Bview.importMatrix->vals_.size()>0)?(&Bview.importMatrix->vals_[0]):0;
433  }
434 
435  // MemorySetup: If somebody else is sharing this C's graphdata, make a new one.
436  // This is needed because I'm about to walk all over the CrsGrapData...
437  C.ExpertMakeUniqueCrsGraphData();
438 
439  // The status array will contain the index into colind where this entry was last deposited.
440  // c_status[i] < CSR_ip - not in the row yet.
441  // c_status[i] >= CSR_ip, this is the entry where you can find the data
442  // We start with this filled with -1's indicating that there are no entries yet.
443  std::vector<int> c_status(n, -1);
444 
445  // Classic csr assembly (low memory edition)
446  int CSR_alloc=C_estimate_nnz(A,B);
447  int CSR_ip=0,OLD_ip=0;
448  Epetra_IntSerialDenseVector & CSR_rowptr = C.ExpertExtractIndexOffset();
449  Epetra_IntSerialDenseVector & CSR_colind = C.ExpertExtractIndices();
450  double *& CSR_vals = C.ExpertExtractValues();
451 
452  CSR_rowptr.Resize(m+1);
453  CSR_colind.Resize(CSR_alloc);
454  resize_doubles(0,CSR_alloc,CSR_vals);
455 
456  // Static Profile stuff
457  std::vector<int> NumEntriesPerRow(m);
458 
459  // For each row of A/C
460  for(i=0; i<m; i++){
461  bool found_diagonal=false;
462  CSR_rowptr[i]=CSR_ip;
463 
464  for(k=Arowptr[i]; k<Arowptr[i+1]; k++){
465  int Ak = Acolind[k];
466  double Aval = Avals[k];
467  if(Aval==0) continue;
468 
469  if(Bview.targetMapToOrigRow[Ak] != -1){
470  // Local matrix
471  int Bk = Bview.targetMapToOrigRow[Ak];
472  for(j=Browptr[Bk]; j<Browptr[Bk+1]; ++j) {
473  int Cj=Bcol2Ccol[Bcolind[j]];
474 
475  if(Cj==i && !found_diagonal) {found_diagonal=true; NumMyDiagonals++;}
476 
477  if(c_status[Cj]<OLD_ip){
478  // New entry
479  c_status[Cj]=CSR_ip;
480  CSR_colind[CSR_ip]=Cj;
481  CSR_vals[CSR_ip]=Aval*Bvals[j];
482  CSR_ip++;
483  }
484  else
485  CSR_vals[c_status[Cj]]+=Aval*Bvals[j];
486  }
487  }
488  else{
489  // Remote matrix
490  int Ik = Bview.targetMapToImportRow[Ak];
491  for(j=Irowptr[Ik]; j<Irowptr[Ik+1]; ++j) {
492  int Cj=Bimportcol2Ccol[Icolind[j]];
493 
494  if(Cj==i && !found_diagonal) {found_diagonal=true; NumMyDiagonals++;}
495 
496  if(c_status[Cj]<OLD_ip){
497  // New entry
498  c_status[Cj]=CSR_ip;
499  CSR_colind[CSR_ip]=Cj;
500  CSR_vals[CSR_ip]=Aval*Ivals[j];
501  CSR_ip++;
502  }
503  else
504  CSR_vals[c_status[Cj]]+=Aval*Ivals[j];
505  }
506  }
507  }
508  NumEntriesPerRow[i]=CSR_ip-CSR_rowptr[i];
509 
510  // Resize for next pass if needed
511  if(CSR_ip + n > CSR_alloc){
512  resize_doubles(CSR_alloc,2*CSR_alloc,CSR_vals);
513  CSR_alloc*=2;
514  CSR_colind.Resize(CSR_alloc);
515  }
516  OLD_ip=CSR_ip;
517  }
518 
519  CSR_rowptr[m]=CSR_ip;
520 
521 #ifdef ENABLE_MMM_TIMINGS
522  mtime->stop();
523  mtime=M.getNewTimer("Final Sort");
524  mtime->start();
525 #endif
526 
527  // Sort the entries
528  Epetra_Util::SortCrsEntries(m, &CSR_rowptr[0], &CSR_colind[0], &CSR_vals[0]);
529 
530 #ifdef ENABLE_MMM_TIMINGS
531  mtime->stop();
532  mtime=M.getNewTimer("Fast IE");
533  mtime->start();
534 #endif
535 
536  // Do a fast build of C's importer
537  Epetra_Import * Cimport=0;
538  int *RemotePIDs = Cremotepids.size()?&Cremotepids[0]:0;
539  int NumExports=0;
540  int *ExportLIDs=0, *ExportPIDs=0;
541  if(Bview.importMatrix) {
542  NumExports=Bview.importMatrix->ExportLIDs_.size();
543  ExportLIDs = Bview.importMatrix->ExportLIDs_.size()?&Bview.importMatrix->ExportLIDs_[0]:0;
544  ExportPIDs = Bview.importMatrix->ExportPIDs_.size()?&Bview.importMatrix->ExportPIDs_[0]:0;
545  }
546 
547  if(!C.ColMap().SameAs(B.DomainMap()))
548  Cimport = new Epetra_Import(C.ColMap(),B.DomainMap(),Cremotepids.size(),RemotePIDs,NumExports,ExportLIDs,ExportPIDs);
549 
550 
551 #ifdef ENABLE_MMM_TIMINGS
552  mtime->stop();
553  mtime=M.getNewTimer("ESFC");
554  mtime->start();
555 #endif
556 
557  // Update the CrsGraphData
558  C.ExpertStaticFillComplete(B.DomainMap(),A.RangeMap(),Cimport,0,NumMyDiagonals);
559 
560 
561 #ifdef ENABLE_MMM_TIMINGS
562  mtime->stop();
563 #endif
564 
565  return 0;
566 }
567 
568 
569 
570 
571 /*****************************************************************************/
572 /*****************************************************************************/
573 /*****************************************************************************/
574 int mult_A_B_reuse(const Epetra_CrsMatrix & A,
575  const Epetra_CrsMatrix & B,
576  CrsMatrixStruct& Bview,
577  std::vector<int> & Bcol2Ccol,
578  std::vector<int> & Bimportcol2Ccol,
579  Epetra_CrsMatrix& C){
580 
581  // *****************************
582  // Improved Parallel Gustavson in Local IDs
583  // *****************************
584  const Epetra_Map * colmap_C = &(C.ColMap());
585 
586  int m=A.NumMyRows();
587  int n=colmap_C->NumMyElements();
588  int i,j,k;
589 
590  // DataPointers for A
591  int *Arowptr, *Acolind;
592  double *Avals;
593  EPETRA_CHK_ERR(A.ExtractCrsDataPointers(Arowptr,Acolind,Avals));
594 
595  // DataPointers for B, Bimport
596  int *Browptr, *Bcolind;
597  double *Bvals;
598  EPETRA_CHK_ERR(B.ExtractCrsDataPointers(Browptr,Bcolind,Bvals));
599 
600  int *Irowptr=0, *Icolind=0;
601  double *Ivals=0;
602  if(Bview.importMatrix){
603  Irowptr = &Bview.importMatrix->rowptr_[0];
604  Icolind = &Bview.importMatrix->colind_[0];
605  Ivals = &Bview.importMatrix->vals_[0];
606  }
607 
608  // DataPointers for C
609  int *CSR_rowptr, *CSR_colind;
610  double *CSR_vals;
611  EPETRA_CHK_ERR(C.ExtractCrsDataPointers(CSR_rowptr,CSR_colind,CSR_vals));
612 
613 
614  // The status array will contain the index into colind where this dude was last deposited.
615  // c_status[i] < CSR_ip - not in the row yet.
616  // c_status[i] >= CSR_ip, this is the entry where you can find the data
617  // We start with this filled with -1's indicating that there are no entries yet.
618  std::vector<int> c_status(n, -1);
619 
620  // Classic csr assembly
621  int CSR_alloc=CSR_rowptr[m] - CSR_rowptr[0];
622  int CSR_ip=0,OLD_ip=0;
623 
624  // For each row of A/C
625  for(i=0; i<m; i++){
626  for(k=Arowptr[i]; k<Arowptr[i+1]; k++){
627  int Ak=Acolind[k];
628  double Aval = Avals[k];
629  if(Aval==0) continue;
630 
631  if(Bview.targetMapToOrigRow[Ak] != -1){
632  // Local matrix
633  int Bk = Bview.targetMapToOrigRow[Ak];
634  for(j=Browptr[Bk]; j<Browptr[Bk+1]; ++j) {
635  int Cj=Bcol2Ccol[Bcolind[j]];
636 
637  if(c_status[Cj]<OLD_ip){
638  // New entry
639  if(CSR_ip >= CSR_alloc) EPETRA_CHK_ERR(-13);
640  c_status[Cj]=CSR_ip;
641  CSR_colind[CSR_ip]=Cj;
642  CSR_vals[CSR_ip]=Aval*Bvals[j];
643  CSR_ip++;
644  }
645  else
646  CSR_vals[c_status[Cj]]+=Aval*Bvals[j];
647  }
648  }
649  else{
650  // Remote matrix
651  int Ik = Bview.targetMapToImportRow[Ak];
652  for(j=Irowptr[Ik]; j<Irowptr[Ik+1]; ++j) {
653  int Cj=Bimportcol2Ccol[Icolind[j]];
654 
655  if(c_status[Cj]<OLD_ip){
656  // New entry
657  if(CSR_ip >= CSR_alloc) EPETRA_CHK_ERR(-14);
658  c_status[Cj]=CSR_ip;
659  CSR_colind[CSR_ip]=Cj;
660  CSR_vals[CSR_ip]=Aval*Ivals[j];
661  CSR_ip++;
662  }
663  else
664  CSR_vals[c_status[Cj]]+=Aval*Ivals[j];
665  }
666  }
667  }
668  OLD_ip=CSR_ip;
669  }
670 
671  // Sort the entries
672  Epetra_Util::SortCrsEntries(m, &CSR_rowptr[0], &CSR_colind[0], &CSR_vals[0]);
673 
674  return 0;
675 }
676 
677 
678 
679 /*****************************************************************************/
680 /*****************************************************************************/
681 /*****************************************************************************/
682 //kernel method for computing the local portion of C = A*B
683  int mult_A_B_general(const Epetra_CrsMatrix & A,
684  CrsMatrixStruct & Aview,
685  const Epetra_CrsMatrix & B,
686  CrsMatrixStruct& Bview,
687  Epetra_CrsMatrix& C,
688  bool call_FillComplete_on_result)
689 {
690  int C_firstCol = Bview.colMap->MinLID();
691  int C_lastCol = Bview.colMap->MaxLID();
692 
693  int C_firstCol_import = 0;
694  int C_lastCol_import = -1;
695 
696  int* bcols = Bview.colMap->MyGlobalElements();
697  int* bcols_import = NULL;
698  if (Bview.importMatrix != NULL) {
699  C_firstCol_import = Bview.importMatrix->ColMap_.MinLID();
700  C_lastCol_import = Bview.importMatrix->ColMap_.MaxLID();
701  bcols_import = Bview.importMatrix->ColMap_.MyGlobalElements();
702  }
703 
704  int C_numCols = C_lastCol - C_firstCol + 1;
705  int C_numCols_import = C_lastCol_import - C_firstCol_import + 1;
706 
707  if (C_numCols_import > C_numCols) C_numCols = C_numCols_import;
708 
709  // Allocate workspace memory
710  double* dwork = new double[C_numCols];
711  int* iwork = new int[C_numCols];
712  int *c_cols=iwork;
713  double *c_vals=dwork;
714  int *c_index=new int[C_numCols];
715 
716  int i, j, k;
717  bool C_filled=C.Filled();
718 
719  // DataPointers for A
720  int *Arowptr, *Acolind;
721  double *Avals;
722  EPETRA_CHK_ERR(A.ExtractCrsDataPointers(Arowptr,Acolind,Avals));
723 
724  //To form C = A*B we're going to execute this expression:
725  //
726  // C(i,j) = sum_k( A(i,k)*B(k,j) )
727  //
728  //Our goal, of course, is to navigate the data in A and B once, without
729  //performing searches for column-indices, etc.
730 
731  // Mark indices as empty w/ -1
732  for(k=0;k<C_numCols;k++) c_index[k]=-1;
733 
734  //loop over the rows of A.
735  for(i=0; i<A.NumMyRows(); ++i) {
736 
737  int global_row = Aview.rowMap->GID(i);
738 
739  //loop across the i-th row of A and for each corresponding row
740  //in B, loop across colums and accumulate product
741  //A(i,k)*B(k,j) into our partial sum quantities C_row_i. In other words,
742  //as we stride across B(k,:) we're calculating updates for row i of the
743  //result matrix C.
744 
745  /* Outline of the revised, ML-inspired algorithm
746 
747  C_{i,j} = \sum_k A_{i,k} B_{k,j}
748 
749  This algorithm uses a "middle product" formulation, with the loop ordering of
750  i, k, j. This means we compute a row of C at a time, but compute partial sums of
751  each entry in row i until we finish the k loop.
752 
753  This algorithm also has a few twists worth documenting.
754 
755  1) The first major twist involves the c_index, c_cols and c_vals arrays. The arrays c_cols
756  and c_vals store the *local* column index and values accumulator respectively. These
757  arrays are allocated to a size equal to the max number of local columns in C, namely C_numcols.
758  The value c_current tells us how many non-zeros we currently have in this row.
759 
760  So how do we take a LCID and find the right accumulator? This is where the c_index array
761  comes in. At the start (and stop) and the i loop, c_index is filled with -1's. Now
762  whenever we find a LCID in the k loop, we first loop at c_index[lcid]. If this value is
763  -1 we haven't seen this entry yet. In which case we add the appropriate stuff to c_cols
764  and c_vals and then set c_index[lcid] to the location of the accumulator (c_current before
765  we increment it). If the value is NOT -1, this tells us the location in the c_vals/c_cols
766  arrays (namely c_index[lcid]) where our accumulator lives.
767 
768  This trick works because we're working with local ids. We can then loop from 0 to c_current
769  and reset c_index to -1's when we're done, only touching the arrays that have changed.
770  While we're at it, we can switch to the global ids so we can call [Insert|SumInto]GlobalValues.
771  Thus, the effect of this trick is to avoid passes over the index array.
772 
773  2) The second major twist involves handling the remote and local components of B separately.
774  (ML doesn't need to do this, because its local ordering scheme is consistent between the local
775  and imported components of B.) Since they have different column maps, they have inconsistent
776  local column ids. This means the "second twist" won't work as stated on both matrices at the
777  same time. While this could be handled any number of ways, I have chosen to do the two parts
778  of B separately to make the code easier to read (and reduce the memory footprint of the MMM).
779  */
780 
781  // Local matrix: Zero Current counts for matrix
782  int c_current=0;
783 
784  // Local matrix: Do the "middle product"
785  for(k=Arowptr[i]; k<Arowptr[i+1]; ++k) {
786  int Ak = Acolind[k];
787  double Aval = Avals[k];
788  // We're skipping remote entries on this pass.
789  if(Bview.remote[Ak] || Aval==0) continue;
790 
791  int* Bcol_inds = Bview.indices[Ak];
792  double* Bvals_k = Bview.values[Ak];
793 
794  for(j=0; j<Bview.numEntriesPerRow[Ak]; ++j) {
795  int col=Bcol_inds[j];
796  if(c_index[col]<0){
797  // We haven't seen this entry before; add it. (In ML, on
798  // the first pass, you haven't seen any of the entries
799  // before, so they are added without the check. Not sure
800  // how much more efficient that would be; depends on branch
801  // prediction. We've favored code readability here.)
802  c_cols[c_current]=col;
803  c_vals[c_current]=Aval*Bvals_k[j];
804  c_index[col]=c_current;
805  c_current++;
806  }
807  else{
808  // We've already seen this entry; accumulate it.
809  c_vals[c_index[col]]+=Aval*Bvals_k[j];
810  }
811  }
812  }
813  // Local matrix: Reset c_index and switch c_cols to GIDs
814  for(k=0; k<c_current; k++){
815  c_index[c_cols[k]]=-1;
816  c_cols[k]=bcols[c_cols[k]]; // Switch from local to global IDs.
817  }
818  // Local matrix: Insert.
819  //
820  // We should check global error results after the algorithm is
821  // through. It's probably safer just to let the algorithm run all
822  // the way through before doing this, since otherwise we have to
823  // remember to free all allocations carefully.
824  int err = C_filled ?
825  C.SumIntoGlobalValues(global_row,c_current,c_vals,c_cols)
826  :
827  C.InsertGlobalValues(global_row,c_current,c_vals,c_cols);
828 
829  // Remote matrix: Zero current counts again for matrix
830  c_current=0;
831 
832  // Remote matrix: Do the "middle product"
833  for(k=Arowptr[i]; k<Arowptr[i+1]; ++k) {
834  int Ak = Acolind[k];
835  double Aval = Avals[k];
836  // We're skipping local entries on this pass.
837  if(!Bview.remote[Ak] || Aval==0) continue;
838 
839  int* Bcol_inds = Bview.indices[Ak];
840  double* Bvals_k = Bview.values[Ak];
841 
842  for(j=0; j<Bview.numEntriesPerRow[Ak]; ++j) {
843  int col=Bcol_inds[j];
844  if(c_index[col]<0){
845  c_cols[c_current]=col;
846  c_vals[c_current]=Aval*Bvals_k[j];
847  c_index[col]=c_current;
848  c_current++;
849  }
850  else{
851  c_vals[c_index[col]]+=Aval*Bvals_k[j];
852  }
853  }
854  }
855  // Remote matrix: Reset c_index and switch c_cols to GIDs
856  for(k=0; k<c_current; k++){
857  c_index[c_cols[k]]=-1;
858  c_cols[k]=bcols_import[c_cols[k]];
859  }
860  // Remove matrix: Insert
861  //
862  // See above (on error handling).
863  err = C_filled ?
864  C.SumIntoGlobalValues(global_row,c_current,c_vals,c_cols)
865  :
866  C.InsertGlobalValues(global_row,c_current,c_vals,c_cols);
867  }
868 
869  // Since Multiply won't do this
870  if(call_FillComplete_on_result)
871  C.FillComplete(B.DomainMap(),A.RangeMap());
872 
873  delete [] dwork;
874  delete [] iwork;
875  delete [] c_index;
876  return(0);
877 }
878 
879 
880 
881 
882 
883 /*****************************************************************************/
884 /*****************************************************************************/
885 /*****************************************************************************/
886 int MatrixMatrix::mult_A_B(const Epetra_CrsMatrix & A,
887  CrsMatrixStruct & Aview,
888  const Epetra_CrsMatrix & B,
889  CrsMatrixStruct& Bview,
890  Epetra_CrsMatrix& C,
891  bool call_FillComplete_on_result){
892 
893  int i,rv;
894  Epetra_Map* mapunion = 0;
895  const Epetra_Map * colmap_B = &(B.ColMap());
896  const Epetra_Map * colmap_C = &(C.ColMap());
897 
898  std::vector<int> Cremotepids;
899  std::vector<int> Bcol2Ccol(B.ColMap().NumMyElements());
900  std::vector<int> Bimportcol2Ccol;
901  if(Bview.importMatrix) Bimportcol2Ccol.resize(Bview.importMatrix->ColMap_.NumMyElements());
902 
903 #ifdef ENABLE_MMM_TIMINGS
904  Teuchos::Time myTime("global");
905  Teuchos::TimeMonitor M(myTime);
906  Teuchos::RCP<Teuchos::Time> mtime;
907 #endif
908 
909  // If the user doesn't want us to call FillComplete, use the general routine
910  if(!call_FillComplete_on_result) {
911 #ifdef ENABLE_MMM_TIMINGS
912  mtime=M.getNewTimer("M4 Multiply");
913  mtime->start();
914 #endif
915  rv=mult_A_B_general(A,Aview,B,Bview,C,false);
916 #ifdef ENABLE_MMM_TIMINGS
917  mtime->stop();
918 #endif
919  return rv;
920  }
921 
922  // Is this a "clean" matrix
923  bool NewFlag=!C.IndicesAreLocal() && !C.IndicesAreGlobal();
924 
925  // Does ExtractCrsDataPointers work?
926  int *C_rowptr, *C_colind;
927  double * C_vals;
928  C.ExtractCrsDataPointers(C_rowptr,C_colind,C_vals);
929  bool ExtractFailFlag=!C_rowptr || !C_colind || !C_vals;
930 
931  // It's a new matrix that hasn't been fill-completed, use the general routine
932  if(!NewFlag && ExtractFailFlag){
933 #ifdef ENABLE_MMM_TIMINGS
934  mtime=M.getNewTimer("M4 Multiply");
935  mtime->start();
936 #endif
937  rv=mult_A_B_general(A,Aview,B,Bview,C,call_FillComplete_on_result);
938 #ifdef ENABLE_MMM_TIMINGS
939  mtime->stop();
940 #endif
941  return rv;
942  }
943 
944 #ifdef ENABLE_MMM_TIMINGS
945  if(NewFlag) mtime=M.getNewTimer("M5 CMap");
946  else mtime=M.getNewTimer("M5r CMap");
947  mtime->start();
948 #endif
949 
950  // If new, build & clobber a colmap for C
951  if(NewFlag){
952  if(Bview.importMatrix) {
953  EPETRA_CHK_ERR( aztecoo_and_ml_compatible_map_union(B,*Bview.importMatrix,mapunion,Cremotepids,Bcol2Ccol,Bimportcol2Ccol) );
954  EPETRA_CHK_ERR( C.ReplaceColMap(*mapunion) );
955  }
956  else {
957  EPETRA_CHK_ERR( C.ReplaceColMap(B.ColMap()) );
958  for(i=0;i<colmap_B->NumMyElements();i++) Bcol2Ccol[i]=i;
959  }
960  }
961 
962 #ifdef ENABLE_MMM_TIMINGS
963  mtime->stop();
964  if(NewFlag) mtime=M.getNewTimer("M5 Lookups");
965  else mtime=M.getNewTimer("M5r Lookups");
966  mtime->start();
967 #endif
968 
969  // ********************************************
970  // Setup Bcol2Ccol / Bimportcol2Ccol lookups
971  // ********************************************
972  // Note: If we ran the map_union, we have this information already
973 
974  if(!NewFlag) {
975  if(colmap_B->SameAs(*colmap_C)){
976  // Maps are the same: Use local IDs as the hash
977  for(i=0;i<colmap_B->NumMyElements();i++)
978  Bcol2Ccol[i]=i;
979  }
980  else {
981  // Maps are not the same: Use the map's hash
982  for(i=0;i<colmap_B->NumMyElements();i++){
983  Bcol2Ccol[i]=colmap_C->LID(colmap_B->GID(i));
984  if(Bcol2Ccol[i]==-1) EPETRA_CHK_ERR(-11);
985  }
986  }
987 
988  if(Bview.importMatrix){
989  Bimportcol2Ccol.resize(Bview.importMatrix->ColMap_.NumMyElements());
990  for(i=0;i<Bview.importMatrix->ColMap_.NumMyElements();i++){
991  Bimportcol2Ccol[i]=colmap_C->LID(Bview.importMatrix->ColMap_.GID(i));
992  if(Bimportcol2Ccol[i]==-1) EPETRA_CHK_ERR(-12);
993  }
994 
995  }
996  }
997 
998 
999 #ifdef ENABLE_MMM_TIMINGS
1000  mtime->stop();
1001 #endif
1002 
1003  // Call the appropriate core routine
1004  if(NewFlag) {
1005  EPETRA_CHK_ERR(mult_A_B_newmatrix(A,B,Bview,Bcol2Ccol,Bimportcol2Ccol,Cremotepids,C));
1006  }
1007  else {
1008  // This always has a real map
1009  EPETRA_CHK_ERR(mult_A_B_reuse(A,B,Bview,Bcol2Ccol,Bimportcol2Ccol,C));
1010  }
1011 
1012  // Cleanup
1013  delete mapunion;
1014  return 0;
1015 }
1016 
1017 
1018 
1019 
1020 }//namespace EpetraExt
int mult_A_B_general(const Epetra_CrsMatrix &A, CrsMatrixStruct &Aview, const Epetra_CrsMatrix &B, CrsMatrixStruct &Bview, Epetra_CrsMatrix &C, bool call_FillComplete_on_result)
LightweightCrsMatrix * importMatrix
std::vector< int > targetMapToOrigRow
int mult_A_B_reuse(const Epetra_CrsMatrix &A, const Epetra_CrsMatrix &B, CrsMatrixStruct &Bview, std::vector< int > &Bcol2Ccol, std::vector< int > &Bimportcol2Ccol, Epetra_CrsMatrix &C)
EpetraExt::BlockCrsMatrix: A class for constructing a distributed block matrix.
void resize_doubles(int nold, int nnew, double *&d)
std::vector< int > targetMapToImportRow
static int C_estimate_nnz(const Epetra_CrsMatrix &A, const Epetra_CrsMatrix &B)
int aztecoo_and_ml_compatible_map_union(const Epetra_CrsMatrix &B, const LightweightCrsMatrix &Bimport, Epetra_Map *&unionmap, std::vector< int > &Cremotepids, std::vector< int > &Bcols2Ccols, std::vector< int > &Icols2Ccols)
static int auto_resize(std::vector< int > &x, int num_new)
int mult_A_B_newmatrix(const Epetra_CrsMatrix &A, const Epetra_CrsMatrix &B, CrsMatrixStruct &Bview, std::vector< int > &Bcol2Ccol, std::vector< int > &Bimportcol2Ccol, std::vector< int > &Cremotepids, Epetra_CrsMatrix &C)