EpetraExt  Development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
EpetraExt_MatrixMatrix.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 
59 
60 #include <Teuchos_TimeMonitor.hpp>
61 
62 #ifdef HAVE_VECTOR
63 #include <vector>
64 #endif
65 
66 
67 
68 namespace EpetraExt {
69 //=========================================================================
70 //
71 //Method for internal use... sparsedot forms a dot-product between two
72 //sparsely-populated 'vectors'.
73 //Important assumption: assumes the indices in u_ind and v_ind are sorted.
74 //
75 double sparsedot(double* u, int* u_ind, int u_len,
76  double* v, int* v_ind, int v_len)
77 {
78  double result = 0.0;
79 
80  int v_idx = 0;
81  int u_idx = 0;
82 
83  while(v_idx < v_len && u_idx < u_len) {
84  int ui = u_ind[u_idx];
85  int vi = v_ind[v_idx];
86 
87  if (ui < vi) {
88  ++u_idx;
89  }
90  else if (ui > vi) {
91  ++v_idx;
92  }
93  else {
94  result += u[u_idx++]*v[v_idx++];
95  }
96  }
97 
98  return(result);
99 }
100 
101 //=========================================================================
102 //kernel method for computing the local portion of C = A*B^T
104  CrsMatrixStruct& Bview,
105  CrsWrapper& C)
106 {
107  int i, j, k;
108  int returnValue = 0;
109 
110  int maxlen = 0;
111  for(i=0; i<Aview.numRows; ++i) {
112  if (Aview.numEntriesPerRow[i] > maxlen) maxlen = Aview.numEntriesPerRow[i];
113  }
114  for(i=0; i<Bview.numRows; ++i) {
115  if (Bview.numEntriesPerRow[i] > maxlen) maxlen = Bview.numEntriesPerRow[i];
116  }
117 
118  //cout << "Aview: " << endl;
119  //dumpCrsMatrixStruct(Aview);
120 
121  //cout << "Bview: " << endl;
122  //dumpCrsMatrixStruct(Bview);
123 
124  int numBcols = Bview.colMap->NumMyElements();
125  int numBrows = Bview.numRows;
126 
127  int iworklen = maxlen*2 + numBcols;
128  int* iwork = new int[iworklen];
129 
130  int* bcols = iwork+maxlen*2;
131  int* bgids = Bview.colMap->MyGlobalElements();
132  double* bvals = new double[maxlen*2];
133  double* avals = bvals+maxlen;
134 
135  int max_all_b = Bview.colMap->MaxAllGID();
136  int min_all_b = Bview.colMap->MinAllGID();
137 
138  //bcols will hold the GIDs from B's column-map for fast access
139  //during the computations below
140  for(i=0; i<numBcols; ++i) {
141  int blid = Bview.colMap->LID(bgids[i]);
142  bcols[blid] = bgids[i];
143  }
144 
145  //next create arrays indicating the first and last column-index in
146  //each row of B, so that we can know when to skip certain rows below.
147  //This will provide a large performance gain for banded matrices, and
148  //a somewhat smaller gain for *most* other matrices.
149  int* b_firstcol = new int[2*numBrows];
150  int* b_lastcol = b_firstcol+numBrows;
151  int temp;
152  for(i=0; i<numBrows; ++i) {
153  b_firstcol[i] = max_all_b;
154  b_lastcol[i] = min_all_b;
155 
156  int Blen_i = Bview.numEntriesPerRow[i];
157  if (Blen_i < 1) continue;
158  int* Bindices_i = Bview.indices[i];
159 
160  if (Bview.remote[i]) {
161  for(k=0; k<Blen_i; ++k) {
162  temp = Bview.importColMap->GID(Bindices_i[k]);
163  if (temp < b_firstcol[i]) b_firstcol[i] = temp;
164  if (temp > b_lastcol[i]) b_lastcol[i] = temp;
165  }
166  }
167  else {
168  for(k=0; k<Blen_i; ++k) {
169  temp = bcols[Bindices_i[k]];
170  if (temp < b_firstcol[i]) b_firstcol[i] = temp;
171  if (temp > b_lastcol[i]) b_lastcol[i] = temp;
172  }
173  }
174  }
175 
176  Epetra_Util util;
177 
178  int* Aind = iwork;
179  int* Bind = iwork+maxlen;
180 
181  bool C_filled = C.Filled();
182 
183  //To form C = A*B^T, we're going to execute this expression:
184  //
185  // C(i,j) = sum_k( A(i,k)*B(j,k) )
186  //
187  //This is the easiest case of all to code (easier than A*B, A^T*B, A^T*B^T).
188  //But it requires the use of a 'sparsedot' function (we're simply forming
189  //dot-products with row A_i and row B_j for all i and j).
190 
191  //loop over the rows of A.
192  for(i=0; i<Aview.numRows; ++i) {
193  if (Aview.remote[i]) {
194  continue;
195  }
196 
197  int* Aindices_i = Aview.indices[i];
198  double* Aval_i = Aview.values[i];
199  int A_len_i = Aview.numEntriesPerRow[i];
200  if (A_len_i < 1) {
201  continue;
202  }
203 
204  for(k=0; k<A_len_i; ++k) {
205  Aind[k] = Aview.colMap->GID(Aindices_i[k]);
206  avals[k] = Aval_i[k];
207  }
208 
209  util.Sort(true, A_len_i, Aind, 1, &avals, 0, NULL);
210 
211  int mina = Aind[0];
212  int maxa = Aind[A_len_i-1];
213 
214  if (mina > max_all_b || maxa < min_all_b) {
215  continue;
216  }
217 
218  int global_row = Aview.rowMap->GID(i);
219 
220  //loop over the rows of B and form results C_ij = dot(A(i,:),B(j,:))
221  for(j=0; j<Bview.numRows; ++j) {
222  if (b_firstcol[j] > maxa || b_lastcol[j] < mina) {
223  continue;
224  }
225 
226  int* Bindices_j = Bview.indices[j];
227  int B_len_j = Bview.numEntriesPerRow[j];
228  if (B_len_j < 1) {
229  continue;
230  }
231 
232  int tmp, Blen = 0;
233 
234  if (Bview.remote[j]) {
235  for(k=0; k<B_len_j; ++k) {
236  tmp = Bview.importColMap->GID(Bindices_j[k]);
237  if (tmp < mina || tmp > maxa) {
238  continue;
239  }
240 
241  bvals[Blen] = Bview.values[j][k];
242  Bind[Blen++] = tmp;
243  }
244  }
245  else {
246  for(k=0; k<B_len_j; ++k) {
247  tmp = bcols[Bindices_j[k]];
248  if (tmp < mina || tmp > maxa) {
249  continue;
250  }
251 
252  bvals[Blen] = Bview.values[j][k];
253  Bind[Blen++] = tmp;
254  }
255  }
256 
257  if (Blen < 1) {
258  continue;
259  }
260 
261  util.Sort(true, Blen, Bind, 1, &bvals, 0, NULL);
262 
263  double C_ij = sparsedot(avals, Aind, A_len_i,
264  bvals, Bind, Blen);
265 
266  if (C_ij == 0.0) {
267  continue;
268  }
269  int global_col = Bview.rowMap->GID(j);
270 
271  int err = C_filled ?
272  C.SumIntoGlobalValues(global_row, 1, &C_ij, &global_col)
273  :
274  C.InsertGlobalValues(global_row, 1, &C_ij, &global_col);
275 
276  if (err < 0) {
277  return(err);
278  }
279  if (err > 0) {
280  if (C_filled) {
281  //C.Filled()==true, and C doesn't have all the necessary nonzero
282  //locations, or global_row or global_col is out of range (less
283  //than 0 or non local).
284  std::cerr << "EpetraExt::MatrixMatrix::Multiply Warning: failed "
285  << "to insert value in result matrix at position "<<global_row
286  <<"," <<global_col<<", possibly because result matrix has a "
287  << "column-map that doesn't include column "<<global_col
288  <<" on this proc." <<std::endl;
289  return(err);
290  }
291  }
292  }
293  }
294 
295  delete [] iwork;
296  delete [] bvals;
297  delete [] b_firstcol;
298 
299  return(returnValue);
300 }
301 
302 //=========================================================================
303 //kernel method for computing the local portion of C = A^T*B
305  CrsMatrixStruct& Bview,
306  CrsWrapper& C)
307 {
308  int C_firstCol = Bview.colMap->MinLID();
309  int C_lastCol = Bview.colMap->MaxLID();
310 
311  int C_firstCol_import = 0;
312  int C_lastCol_import = -1;
313 
314  if (Bview.importColMap != NULL) {
315  C_firstCol_import = Bview.importColMap->MinLID();
316  C_lastCol_import = Bview.importColMap->MaxLID();
317  }
318 
319  int C_numCols = C_lastCol - C_firstCol + 1;
320  int C_numCols_import = C_lastCol_import - C_firstCol_import + 1;
321 
322  if (C_numCols_import > C_numCols) C_numCols = C_numCols_import;
323 
324  double* C_row_i = new double[C_numCols];
325  int* C_colInds = new int[C_numCols];
326 
327  int i, j, k;
328 
329  for(j=0; j<C_numCols; ++j) {
330  C_row_i[j] = 0.0;
331  C_colInds[j] = 0;
332  }
333 
334  //To form C = A^T*B, compute a series of outer-product updates.
335  //
336  // for (ith column of A^T) {
337  // C_i = outer product of A^T(:,i) and B(i,:)
338  // Where C_i is the ith matrix update,
339  // A^T(:,i) is the ith column of A^T, and
340  // B(i,:) is the ith row of B.
341  //
342 
343  //dumpCrsMatrixStruct(Aview);
344  //dumpCrsMatrixStruct(Bview);
345  int localProc = Bview.colMap->Comm().MyPID();
346 
347  int* Arows = Aview.rowMap->MyGlobalElements();
348 
349  bool C_filled = C.Filled();
350 
351  //loop over the rows of A (which are the columns of A^T).
352  for(i=0; i<Aview.numRows; ++i) {
353 
354  int* Aindices_i = Aview.indices[i];
355  double* Aval_i = Aview.values[i];
356 
357  //we'll need to get the row of B corresponding to Arows[i],
358  //where Arows[i] is the GID of A's ith row.
359  int Bi = Bview.rowMap->LID(Arows[i]);
360  if (Bi<0) {
361  cout << "mult_Atrans_B ERROR, proc "<<localProc<<" needs row "
362  <<Arows[i]<<" of matrix B, but doesn't have it."<<endl;
363  return(-1);
364  }
365 
366  int* Bcol_inds = Bview.indices[Bi];
367  double* Bvals_i = Bview.values[Bi];
368 
369  //for each column-index Aj in the i-th row of A, we'll update
370  //global-row GID(Aj) of the result matrix C. In that row of C,
371  //we'll update column-indices given by the column-indices in the
372  //ith row of B that we're now holding (Bcol_inds).
373 
374  //First create a list of GIDs for the column-indices
375  //that we'll be updating.
376 
377  int Blen = Bview.numEntriesPerRow[Bi];
378  if (Bview.remote[Bi]) {
379  for(j=0; j<Blen; ++j) {
380  C_colInds[j] = Bview.importColMap->GID(Bcol_inds[j]);
381  }
382  }
383  else {
384  for(j=0; j<Blen; ++j) {
385  C_colInds[j] = Bview.colMap->GID(Bcol_inds[j]);
386  }
387  }
388 
389  //loop across the i-th row of A (column of A^T)
390  for(j=0; j<Aview.numEntriesPerRow[i]; ++j) {
391 
392  int Aj = Aindices_i[j];
393  double Aval = Aval_i[j];
394 
395  int global_row;
396  if (Aview.remote[i]) {
397  global_row = Aview.importColMap->GID(Aj);
398  }
399  else {
400  global_row = Aview.colMap->GID(Aj);
401  }
402 
403  if (!C.RowMap().MyGID(global_row)) {
404  continue;
405  }
406 
407  for(k=0; k<Blen; ++k) {
408  C_row_i[k] = Aval*Bvals_i[k];
409  }
410 
411  //
412  //Now add this row-update to C.
413  //
414 
415  int err = C_filled ?
416  C.SumIntoGlobalValues(global_row, Blen, C_row_i, C_colInds)
417  :
418  C.InsertGlobalValues(global_row, Blen, C_row_i, C_colInds);
419 
420  if (err < 0) {
421  return(err);
422  }
423  if (err > 0) {
424  if (C_filled) {
425  //C is Filled, and doesn't have all the necessary nonzero locations.
426  return(err);
427  }
428  }
429  }
430  }
431 
432  delete [] C_row_i;
433  delete [] C_colInds;
434 
435  return(0);
436 }
437 
438 //kernel method for computing the local portion of C = A^T*B^T
440  CrsMatrixStruct& Bview,
441  CrsWrapper& C)
442 {
443  int C_firstCol = Aview.rowMap->MinLID();
444  int C_lastCol = Aview.rowMap->MaxLID();
445 
446  int C_firstCol_import = 0;
447  int C_lastCol_import = -1;
448 
449  if (Aview.importColMap != NULL) {
450  C_firstCol_import = Aview.importColMap->MinLID();
451  C_lastCol_import = Aview.importColMap->MaxLID();
452  }
453 
454  int C_numCols = C_lastCol - C_firstCol + 1;
455  int C_numCols_import = C_lastCol_import - C_firstCol_import + 1;
456 
457  if (C_numCols_import > C_numCols) C_numCols = C_numCols_import;
458 
459  double* dwork = new double[C_numCols];
460  int* iwork = new int[C_numCols];
461 
462  double* C_col_j = dwork;
463  int* C_inds = iwork;
464 
465  //cout << "Aview: " << endl;
466  //dumpCrsMatrixStruct(Aview);
467 
468  //cout << "Bview: " << endl;
469  //dumpCrsMatrixStruct(Bview);
470 
471 
472  int i, j, k;
473 
474  for(j=0; j<C_numCols; ++j) {
475  C_col_j[j] = 0.0;
476  C_inds[j] = -1;
477  }
478 
479  int* A_col_inds = Aview.colMap->MyGlobalElements();
480  int* A_col_inds_import = Aview.importColMap ?
481  Aview.importColMap->MyGlobalElements() : 0;
482 
483  const Epetra_Map* Crowmap = &(C.RowMap());
484 
485  //To form C = A^T*B^T, we're going to execute this expression:
486  //
487  // C(i,j) = sum_k( A(k,i)*B(j,k) )
488  //
489  //Our goal, of course, is to navigate the data in A and B once, without
490  //performing searches for column-indices, etc. In other words, we avoid
491  //column-wise operations like the plague...
492 
493  int* Brows = Bview.rowMap->MyGlobalElements();
494 
495  //loop over the rows of B
496  for(j=0; j<Bview.numRows; ++j) {
497  int* Bindices_j = Bview.indices[j];
498  double* Bvals_j = Bview.values[j];
499 
500  int global_col = Brows[j];
501 
502  //loop across columns in the j-th row of B and for each corresponding
503  //row in A, loop across columns and accumulate product
504  //A(k,i)*B(j,k) into our partial sum quantities in C_col_j. In other
505  //words, as we stride across B(j,:), we use selected rows in A to
506  //calculate updates for column j of the result matrix C.
507 
508  for(k=0; k<Bview.numEntriesPerRow[j]; ++k) {
509 
510  int bk = Bindices_j[k];
511  double Bval = Bvals_j[k];
512 
513  int global_k;
514  if (Bview.remote[j]) {
515  global_k = Bview.importColMap->GID(bk);
516  }
517  else {
518  global_k = Bview.colMap->GID(bk);
519  }
520 
521  //get the corresponding row in A
522  int ak = Aview.rowMap->LID(global_k);
523  if (ak<0) {
524  continue;
525  }
526 
527  int* Aindices_k = Aview.indices[ak];
528  double* Avals_k = Aview.values[ak];
529 
530  int C_len = 0;
531 
532  if (Aview.remote[ak]) {
533  for(i=0; i<Aview.numEntriesPerRow[ak]; ++i) {
534  C_col_j[C_len] = Avals_k[i]*Bval;
535  C_inds[C_len++] = A_col_inds_import[Aindices_k[i]];
536  }
537  }
538  else {
539  for(i=0; i<Aview.numEntriesPerRow[ak]; ++i) {
540  C_col_j[C_len] = Avals_k[i]*Bval;
541  C_inds[C_len++] = A_col_inds[Aindices_k[i]];
542  }
543  }
544 
545  //Now loop across the C_col_j values and put non-zeros into C.
546 
547  for(i=0; i < C_len ; ++i) {
548  if (C_col_j[i] == 0.0) continue;
549 
550  int global_row = C_inds[i];
551  if (!Crowmap->MyGID(global_row)) {
552  continue;
553  }
554 
555  int err = C.SumIntoGlobalValues(global_row, 1, &(C_col_j[i]), &global_col);
556 
557  if (err < 0) {
558  return(err);
559  }
560  else {
561  if (err > 0) {
562  err = C.InsertGlobalValues(global_row, 1, &(C_col_j[i]), &global_col);
563  if (err < 0) {
564  return(err);
565  }
566  }
567  }
568  }
569 
570  }
571  }
572 
573  delete [] dwork;
574  delete [] iwork;
575 
576  return(0);
577 }
578 
579 // ==============================================================
580 int import_and_extract_views(const Epetra_CrsMatrix& M,
581  const Epetra_Map& targetMap,
582  CrsMatrixStruct& Mview,
583  const Epetra_Import * prototypeImporter=0)
584 {
585  //The goal of this method is to populate the 'Mview' struct with views of the
586  //rows of M, including all rows that correspond to elements in 'targetMap'.
587  //
588  //If targetMap includes local elements that correspond to remotely-owned rows
589  //of M, then those remotely-owned rows will be imported into
590  //'Mview.importMatrix', and views of them will be included in 'Mview'.
591 
592  // The prototype importer, if used, has to know who owns all of the PIDs in M's rowmap.
593  // The typical use of this is to provide A's column map when I&XV is called for B, for
594  // a C = A * B multiply.
595 
596 #ifdef ENABLE_MMM_TIMINGS
597  Teuchos::Time myTime("global");
598  Teuchos::TimeMonitor MM(myTime);
599  Teuchos::RCP<Teuchos::Time> mtime;
600  mtime=MM.getNewTimer("All I&X Alloc");
601  mtime->start();
602 #endif
603  Mview.deleteContents();
604 
605  Mview.origMatrix = &M;
606  const Epetra_Map& Mrowmap = M.RowMap();
607  int numProcs = Mrowmap.Comm().NumProc();
608  Mview.numRows = targetMap.NumMyElements();
609  int* Mrows = targetMap.MyGlobalElements();
610 
611  if (Mview.numRows > 0) {
612  Mview.numEntriesPerRow = new int[Mview.numRows];
613  Mview.indices = new int*[Mview.numRows];
614  Mview.values = new double*[Mview.numRows];
615  Mview.remote = new bool[Mview.numRows];
616  }
617 
618  Mview.origRowMap = &(M.RowMap());
619  Mview.rowMap = &targetMap;
620  Mview.colMap = &(M.ColMap());
621  Mview.domainMap = &(M.DomainMap());
622  Mview.importColMap = NULL;
623  Mview.numRemote = 0;
624 
625 
626 #ifdef ENABLE_MMM_TIMINGS
627  mtime->stop();
628  mtime=MM.getNewTimer("All I&X Extract");
629  mtime->start();
630 #endif
631 
632  int i;
633  int *rowptr=0, *colind=0;
634  double *vals=0;
635 
636  EPETRA_CHK_ERR( M.ExtractCrsDataPointers(rowptr,colind,vals) );
637 
638  if(Mrowmap.SameAs(targetMap)) {
639  // Short Circuit: The Row and Target Maps are the Same
640  for(i=0; i<Mview.numRows; ++i) {
641  Mview.numEntriesPerRow[i] = rowptr[i+1]-rowptr[i];
642  Mview.indices[i] = colind + rowptr[i];
643  Mview.values[i] = vals + rowptr[i];
644  Mview.remote[i] = false;
645  }
646 #ifdef ENABLE_MMM_TIMINGS
647  mtime->stop();
648 #endif
649  return 0;
650  }
651  else if(prototypeImporter && prototypeImporter->SourceMap().SameAs(M.RowMap()) && prototypeImporter->TargetMap().SameAs(targetMap)){
652  // The prototypeImporter can tell me what is local and what is remote
653  int * PermuteToLIDs = prototypeImporter->PermuteToLIDs();
654  int * PermuteFromLIDs = prototypeImporter->PermuteFromLIDs();
655  int * RemoteLIDs = prototypeImporter->RemoteLIDs();
656  for(int i=0; i<prototypeImporter->NumSameIDs();i++){
657  Mview.numEntriesPerRow[i] = rowptr[i+1]-rowptr[i];
658  Mview.indices[i] = colind + rowptr[i];
659  Mview.values[i] = vals + rowptr[i];
660  Mview.remote[i] = false;
661  }
662  for(int i=0; i<prototypeImporter->NumPermuteIDs();i++){
663  int to = PermuteToLIDs[i];
664  int from = PermuteFromLIDs[i];
665  Mview.numEntriesPerRow[to] = rowptr[from+1]-rowptr[from];
666  Mview.indices[to] = colind + rowptr[from];
667  Mview.values[to] = vals + rowptr[from];
668  Mview.remote[to] = false;
669  }
670  for(int i=0; i<prototypeImporter->NumRemoteIDs();i++){
671  Mview.remote[RemoteLIDs[i]] = true;
672  ++Mview.numRemote;
673  }
674  }
675  else {
676  // Only LID can tell me who is local and who is remote
677  for(i=0; i<Mview.numRows; ++i) {
678  int mlid = Mrowmap.LID(Mrows[i]);
679  if (mlid < 0) {
680  Mview.remote[i] = true;
681  ++Mview.numRemote;
682  }
683  else {
684  Mview.numEntriesPerRow[i] = rowptr[mlid+1]-rowptr[mlid];
685  Mview.indices[i] = colind + rowptr[mlid];
686  Mview.values[i] = vals + rowptr[mlid];
687  Mview.remote[i] = false;
688  }
689  }
690  }
691 
692 #ifdef ENABLE_MMM_TIMINGS
693  mtime->stop();
694  mtime=MM.getNewTimer("All I&X Collective-0");
695  mtime->start();
696 #endif
697 
698 
699  if (numProcs < 2) {
700  if (Mview.numRemote > 0) {
701  cerr << "EpetraExt::MatrixMatrix::Multiply ERROR, numProcs < 2 but "
702  << "attempting to import remote matrix rows."<<endl;
703  return(-1);
704  }
705 
706  //If only one processor we don't need to import any remote rows, so return.
707  return(0);
708  }
709 
710  //
711  //Now we will import the needed remote rows of M, if the global maximum
712  //value of numRemote is greater than 0.
713  //
714 
715  int globalMaxNumRemote = 0;
716  Mrowmap.Comm().MaxAll(&Mview.numRemote, &globalMaxNumRemote, 1);
717 
718 #ifdef ENABLE_MMM_TIMINGS
719  mtime->stop();
720 #endif
721 
722  if (globalMaxNumRemote > 0) {
723 #ifdef ENABLE_MMM_TIMINGS
724  mtime=MM.getNewTimer("All I&X Import-1");
725  mtime->start();
726 #endif
727  //Create a map that describes the remote rows of M that we need.
728 
729  int* MremoteRows = Mview.numRemote>0 ? new int[Mview.numRemote] : NULL;
730  int offset = 0;
731  for(i=0; i<Mview.numRows; ++i) {
732  if (Mview.remote[i]) {
733  MremoteRows[offset++] = Mrows[i];
734  }
735  }
736 
737  LightweightMap MremoteRowMap(-1, Mview.numRemote, MremoteRows,Mrowmap.IndexBase());
738 
739 #ifdef ENABLE_MMM_TIMINGS
740  mtime->stop();
741  mtime=MM.getNewTimer("All I&X Import-2");
742  mtime->start();
743 #endif
744  //Create an importer with target-map MremoteRowMap and
745  //source-map Mrowmap.
746  Epetra_Import * importer=0;
747  RemoteOnlyImport * Rimporter=0;
748  if(prototypeImporter && prototypeImporter->SourceMap().SameAs(M.RowMap()) && prototypeImporter->TargetMap().SameAs(targetMap)) {
749  Rimporter = new RemoteOnlyImport(*prototypeImporter,MremoteRowMap);
750  }
751  else if(!prototypeImporter) {
752  Epetra_Map MremoteRowMap2(-1, Mview.numRemote, MremoteRows,Mrowmap.IndexBase(), Mrowmap.Comm());
753  importer=new Epetra_Import(MremoteRowMap2, Mrowmap);
754  }
755  else
756  throw std::runtime_error("prototypeImporter->SourceMap() does not match M.RowMap()!");
757 
758 
759 #ifdef ENABLE_MMM_TIMINGS
760  mtime->stop();
761  mtime=MM.getNewTimer("All I&X Import-3");
762  mtime->start();
763 #endif
764 
765  if(Mview.importMatrix) delete Mview.importMatrix;
766  if(Rimporter) Mview.importMatrix = new LightweightCrsMatrix(M,*Rimporter);
767  else Mview.importMatrix = new LightweightCrsMatrix(M,*importer);
768 
769 #ifdef ENABLE_MMM_TIMINGS
770  mtime->stop();
771  mtime=MM.getNewTimer("All I&X Import-4");
772  mtime->start();
773 #endif
774 
775  //Finally, use the freshly imported data to fill in the gaps in our views
776  int N;
777  if(Mview.importMatrix->use_lw) N = Mview.importMatrix->RowMapLW_->NumMyElements();
778  else N = Mview.importMatrix->RowMapEP_->NumMyElements();
779 
780  if(N > 0) {
781  rowptr = &Mview.importMatrix->rowptr_[0];
782  colind = &Mview.importMatrix->colind_[0];
783  vals = &Mview.importMatrix->vals_[0];
784  }
785 
786 
787  for(i=0; i<Mview.numRows; ++i) {
788  if (Mview.remote[i]) {
789  int importLID = MremoteRowMap.LID(Mrows[i]);
790  Mview.numEntriesPerRow[i] = rowptr[importLID+1]-rowptr[importLID];
791  Mview.indices[i] = colind + rowptr[importLID];
792  Mview.values[i] = vals + rowptr[importLID];
793  }
794  }
795 
796 
797  int * MyColGIDs = (Mview.importMatrix->ColMap_.NumMyElements()>0)?Mview.importMatrix->ColMap_.MyGlobalElements():0;
798  Mview.importColMap = new Epetra_Map(-1,Mview.importMatrix->ColMap_.NumMyElements(),MyColGIDs,Mview.importMatrix->ColMap_.IndexBase(),M.Comm());
799  delete [] MremoteRows;
800 #ifdef ENABLE_MMM_TIMINGS
801  mtime->stop();
802 #endif
803 
804  // Cleanup
805  delete Rimporter;
806  delete importer;
807 
808  }
809  return(0);
810 }
811 
812 
813 
814 
815 // ==============================================================
816 int import_only(const Epetra_CrsMatrix& M,
817  const Epetra_Map& targetMap,
818  CrsMatrixStruct& Mview,
819  const Epetra_Import * prototypeImporter=0)
820 {
821  // The goal of this method to populare the Mview object with ONLY the rows of M
822  // that correspond to elements in 'targetMap.' There will be no population of the
823  // numEntriesPerRow, indices, values, remote or numRemote arrays.
824 
825 
826  // The prototype importer, if used, has to know who owns all of the PIDs in M's rowmap.
827  // The typical use of this is to provide A's column map when I&XV is called for B, for
828  // a C = A * B multiply.
829 
830 #ifdef ENABLE_MMM_TIMINGS
831  Teuchos::Time myTime("global");
832  Teuchos::TimeMonitor MM(myTime);
833  Teuchos::RCP<Teuchos::Time> mtime;
834  mtime=MM.getNewTimer("Ionly Setup");
835  mtime->start();
836 #endif
837 
838  Mview.deleteContents();
839 
840  Mview.origMatrix = &M;
841  const Epetra_Map& Mrowmap = M.RowMap();
842  int numProcs = Mrowmap.Comm().NumProc();
843  Mview.numRows = targetMap.NumMyElements();
844 
845  Mview.origRowMap = &(M.RowMap());
846  Mview.rowMap = &targetMap;
847  Mview.colMap = &(M.ColMap());
848  Mview.domainMap = &(M.DomainMap());
849  Mview.importColMap = NULL;
850 
851  int i;
852  int numRemote =0;
853  int N = Mview.rowMap->NumMyElements();
854 
855  if(Mrowmap.SameAs(targetMap)) {
856  numRemote = 0;
857  Mview.targetMapToOrigRow.resize(N);
858  for(i=0;i<N; i++) Mview.targetMapToOrigRow[i]=i;
859 
860 #ifdef ENABLE_MMM_TIMINGS
861  mtime->stop();
862 #endif
863  return 0;
864  }
865  else if(prototypeImporter && prototypeImporter->SourceMap().SameAs(M.RowMap()) && prototypeImporter->TargetMap().SameAs(targetMap)){
866  numRemote = prototypeImporter->NumRemoteIDs();
867 
868  Mview.targetMapToOrigRow.resize(N); Mview.targetMapToOrigRow.assign(N,-1);
869  Mview.targetMapToImportRow.resize(N); Mview.targetMapToImportRow.assign(N,-1);
870 
871  const int * PermuteToLIDs = prototypeImporter->PermuteToLIDs();
872  const int * PermuteFromLIDs = prototypeImporter->PermuteFromLIDs();
873  const int * RemoteLIDs = prototypeImporter->RemoteLIDs();
874 
875  for(i=0; i<prototypeImporter->NumSameIDs();i++)
876  Mview.targetMapToOrigRow[i] = i;
877 
878  // NOTE: These are reversed on purpose since we're doing a revere map.
879  for(i=0; i<prototypeImporter->NumPermuteIDs();i++)
880  Mview.targetMapToOrigRow[PermuteToLIDs[i]] = PermuteFromLIDs[i];
881 
882  for(i=0; i<prototypeImporter->NumRemoteIDs();i++)
883  Mview.targetMapToImportRow[RemoteLIDs[i]] = i;
884 
885  }
886  else
887  throw "import_only: This routine only works if you either have the right map or no prototypeImporter";
888 
889  if (numProcs < 2) {
890  if (Mview.numRemote > 0) {
891  cerr << "EpetraExt::MatrixMatrix::Multiply ERROR, numProcs < 2 but "
892  << "attempting to import remote matrix rows."<<endl;
893  return(-1);
894  }
895 #ifdef ENABLE_MMM_TIMINGS
896  mtime->stop();
897 #endif
898 
899  //If only one processor we don't need to import any remote rows, so return.
900  return(0);
901  }
902 
903 #ifdef ENABLE_MMM_TIMINGS
904  mtime->stop();
905  mtime=MM.getNewTimer("Ionly Import-1");
906  mtime->start();
907 #endif
908  const int * RemoteLIDs = prototypeImporter->RemoteLIDs();
909 
910  //Create a map that describes the remote rows of M that we need.
911  int* MremoteRows = numRemote>0 ? new int[prototypeImporter->NumRemoteIDs()] : 0;
912  for(i=0; i<prototypeImporter->NumRemoteIDs(); i++)
913  MremoteRows[i] = targetMap.GID(RemoteLIDs[i]);
914 
915  LightweightMap MremoteRowMap(-1, numRemote, MremoteRows,Mrowmap.IndexBase());
916 
917 #ifdef ENABLE_MMM_TIMINGS
918  mtime->stop();
919  mtime=MM.getNewTimer("Ionly Import-2");
920  mtime->start();
921 #endif
922  //Create an importer with target-map MremoteRowMap and
923  //source-map Mrowmap.
924  RemoteOnlyImport * Rimporter=0;
925  Rimporter = new RemoteOnlyImport(*prototypeImporter,MremoteRowMap);
926 
927 #ifdef ENABLE_MMM_TIMINGS
928  mtime->stop();
929  mtime=MM.getNewTimer("Ionly Import-3");
930  mtime->start();
931 #endif
932 
933  Mview.importMatrix = new LightweightCrsMatrix(M,*Rimporter);
934 
935 #ifdef ENABLE_MMM_TIMINGS
936  mtime->stop();
937  mtime=MM.getNewTimer("Ionly Import-4");
938  mtime->start();
939 #endif
940 
941  // Cleanup
942  delete Rimporter;
943  delete [] MremoteRows;
944 #ifdef ENABLE_MMM_TIMINGS
945  mtime->stop();
946 #endif
947 
948 
949  return(0);
950 }
951 
952 
953 
954 
955 //=========================================================================
956 int form_map_union(const Epetra_Map* map1,
957  const Epetra_Map* map2,
958  const Epetra_Map*& mapunion)
959 {
960  //form the union of two maps
961 
962  if (map1 == NULL) {
963  mapunion = new Epetra_Map(*map2);
964  return(0);
965  }
966 
967  if (map2 == NULL) {
968  mapunion = new Epetra_Map(*map1);
969  return(0);
970  }
971 
972  int map1_len = map1->NumMyElements();
973  int* map1_elements = map1->MyGlobalElements();
974  int map2_len = map2->NumMyElements();
975  int* map2_elements = map2->MyGlobalElements();
976 
977  int* union_elements = new int[map1_len+map2_len];
978 
979  int map1_offset = 0, map2_offset = 0, union_offset = 0;
980 
981  while(map1_offset < map1_len && map2_offset < map2_len) {
982  int map1_elem = map1_elements[map1_offset];
983  int map2_elem = map2_elements[map2_offset];
984 
985  if (map1_elem < map2_elem) {
986  union_elements[union_offset++] = map1_elem;
987  ++map1_offset;
988  }
989  else if (map1_elem > map2_elem) {
990  union_elements[union_offset++] = map2_elem;
991  ++map2_offset;
992  }
993  else {
994  union_elements[union_offset++] = map1_elem;
995  ++map1_offset;
996  ++map2_offset;
997  }
998  }
999 
1000  int i;
1001  for(i=map1_offset; i<map1_len; ++i) {
1002  union_elements[union_offset++] = map1_elements[i];
1003  }
1004 
1005  for(i=map2_offset; i<map2_len; ++i) {
1006  union_elements[union_offset++] = map2_elements[i];
1007  }
1008 
1009  mapunion = new Epetra_Map(-1, union_offset, union_elements,
1010  map1->IndexBase(), map1->Comm());
1011 
1012  delete [] union_elements;
1013 
1014  return(0);
1015 }
1016 
1017 //=========================================================================
1018 Epetra_Map* find_rows_containing_cols(const Epetra_CrsMatrix& M,
1019  const Epetra_Map& column_map)
1020 {
1021  //The goal of this function is to find all rows in the matrix M that contain
1022  //column-indices which are in 'column_map'. A map containing those rows is
1023  //returned. (The returned map will then be used as the source row-map for
1024  //importing those rows into an overlapping distribution.)
1025 
1026  std::pair<int,int> my_col_range = get_col_range(column_map);
1027 
1028  const Epetra_Comm& Comm = M.RowMap().Comm();
1029  int num_procs = Comm.NumProc();
1030  int my_proc = Comm.MyPID();
1031  std::vector<int> send_procs;
1032  send_procs.reserve(num_procs-1);
1033  std::vector<int> col_ranges;
1034  col_ranges.reserve(2*(num_procs-1));
1035  for(int p=0; p<num_procs; ++p) {
1036  if (p == my_proc) continue;
1037  send_procs.push_back(p);
1038  col_ranges.push_back(my_col_range.first);
1039  col_ranges.push_back(my_col_range.second);
1040  }
1041 
1042  Epetra_Distributor* distor = Comm.CreateDistributor();
1043 
1044  int num_recv_procs = 0;
1045  int num_send_procs = send_procs.size();
1046  bool deterministic = true;
1047  int* send_procs_ptr = send_procs.size()>0 ? &send_procs[0] : NULL;
1048  distor->CreateFromSends(num_send_procs, send_procs_ptr, deterministic, num_recv_procs);
1049 
1050  int len_import_chars = 0;
1051  char* import_chars = NULL;
1052 
1053  char* export_chars = col_ranges.size()>0 ? reinterpret_cast<char*>(&col_ranges[0]) : NULL;
1054  int err = distor->Do(export_chars, 2*sizeof(int), len_import_chars, import_chars);
1055  if (err != 0) {
1056  std::cout << "ERROR returned from Distributor::Do."<<std::endl;
1057  }
1058 
1059  int* IntImports = reinterpret_cast<int*>(import_chars);
1060  int num_import_pairs = len_import_chars/(2*sizeof(int));
1061  int offset = 0;
1062  std::vector<int> send_procs2;
1063  send_procs2.reserve(num_procs);
1064  std::vector<int> proc_col_ranges;
1065  std::pair<int,int> M_col_range = get_col_range(M);
1066  for(int i=0; i<num_import_pairs; ++i) {
1067  int first_col = IntImports[offset++];
1068  int last_col = IntImports[offset++];
1069  if (first_col <= M_col_range.second && last_col >= M_col_range.first) {
1070  send_procs2.push_back(send_procs[i]);
1071  proc_col_ranges.push_back(first_col);
1072  proc_col_ranges.push_back(last_col);
1073  }
1074  }
1075 
1076  std::vector<int> send_rows;
1077  std::vector<int> rows_per_send_proc;
1078  pack_outgoing_rows(M, proc_col_ranges, send_rows, rows_per_send_proc);
1079 
1080  Epetra_Distributor* distor2 = Comm.CreateDistributor();
1081 
1082  int* send_procs2_ptr = send_procs2.size()>0 ? &send_procs2[0] : NULL;
1083  num_recv_procs = 0;
1084  err = distor2->CreateFromSends(send_procs2.size(), send_procs2_ptr, deterministic, num_recv_procs);
1085 
1086  export_chars = send_rows.size()>0 ? reinterpret_cast<char*>(&send_rows[0]) : NULL;
1087  int* rows_per_send_proc_ptr = rows_per_send_proc.size()>0 ? &rows_per_send_proc[0] : NULL;
1088  len_import_chars = 0;
1089  err = distor2->Do(export_chars, (int)sizeof(int), rows_per_send_proc_ptr, len_import_chars, import_chars);
1090 
1091  int* recvd_row_ints = reinterpret_cast<int*>(import_chars);
1092  int num_recvd_rows = len_import_chars/sizeof(int);
1093 
1094  Epetra_Map recvd_rows(-1, num_recvd_rows, recvd_row_ints, column_map.IndexBase(), Comm);
1095 
1096  delete distor;
1097  delete distor2;
1098  delete [] import_chars;
1099 
1100  Epetra_Map* result_map = NULL;
1101 
1102  err = form_map_union(&(M.RowMap()), &recvd_rows, (const Epetra_Map*&)result_map);
1103  if (err != 0) {
1104  return(NULL);
1105  }
1106 
1107  return(result_map);
1108 }
1109 
1110 //=========================================================================
1111 int MatrixMatrix::Multiply(const Epetra_CrsMatrix& A,
1112  bool transposeA,
1113  const Epetra_CrsMatrix& B,
1114  bool transposeB,
1115  Epetra_CrsMatrix& C,
1116  bool call_FillComplete_on_result)
1117 {
1118 
1119  // DEBUG
1120  // bool NewFlag=!C.IndicesAreLocal() && !C.IndicesAreGlobal();
1121 #ifdef ENABLE_MMM_TIMINGS
1122  Teuchos::Time myTime("global");
1123  Teuchos::TimeMonitor M(myTime);
1124  Teuchos::RCP<Teuchos::Time> mtime;
1125  mtime=M.getNewTimer("All Setup");
1126  mtime->start();
1127 #endif
1128  // end DEBUG
1129 
1130  //
1131  //This method forms the matrix-matrix product C = op(A) * op(B), where
1132  //op(A) == A if transposeA is false,
1133  //op(A) == A^T if transposeA is true,
1134  //and similarly for op(B).
1135  //
1136 
1137  //A and B should already be Filled.
1138  //(Should we go ahead and call FillComplete() on them if necessary?
1139  // or error out? For now, we choose to error out.)
1140  if (!A.Filled() || !B.Filled()) {
1141  EPETRA_CHK_ERR(-1);
1142  }
1143 
1144  //We're going to refer to the different combinations of op(A) and op(B)
1145  //as scenario 1 through 4.
1146 
1147  int scenario = 1;//A*B
1148  if (transposeB && !transposeA) scenario = 2;//A*B^T
1149  if (transposeA && !transposeB) scenario = 3;//A^T*B
1150  if (transposeA && transposeB) scenario = 4;//A^T*B^T
1151 
1152  //now check size compatibility
1153  int Aouter = transposeA ? A.NumGlobalCols() : A.NumGlobalRows();
1154  int Bouter = transposeB ? B.NumGlobalRows() : B.NumGlobalCols();
1155  int Ainner = transposeA ? A.NumGlobalRows() : A.NumGlobalCols();
1156  int Binner = transposeB ? B.NumGlobalCols() : B.NumGlobalRows();
1157  if (Ainner != Binner) {
1158  cerr << "MatrixMatrix::Multiply: ERROR, inner dimensions of op(A) and op(B) "
1159  << "must match for matrix-matrix product. op(A) is "
1160  <<Aouter<<"x"<<Ainner << ", op(B) is "<<Binner<<"x"<<Bouter<<endl;
1161  return(-1);
1162  }
1163 
1164  //The result matrix C must at least have a row-map that reflects the
1165  //correct row-size. Don't check the number of columns because rectangular
1166  //matrices which were constructed with only one map can still end up
1167  //having the correct capacity and dimensions when filled.
1168  if (Aouter > C.NumGlobalRows()) {
1169  cerr << "MatrixMatrix::Multiply: ERROR, dimensions of result C must "
1170  << "match dimensions of op(A) * op(B). C has "<<C.NumGlobalRows()
1171  << " rows, should have at least "<<Aouter << endl;
1172  return(-1);
1173  }
1174 
1175  //It doesn't matter whether C is already Filled or not. If it is already
1176  //Filled, it must have space allocated for the positions that will be
1177  //referenced in forming C = op(A)*op(B). If it doesn't have enough space,
1178  //we'll error out later when trying to store result values.
1179 
1180  //We're going to need to import remotely-owned sections of A and/or B
1181  //if more than 1 processor is performing this run, depending on the scenario.
1182  int numProcs = A.Comm().NumProc();
1183 
1184  //If we are to use the transpose of A and/or B, we'll need to be able to
1185  //access, on the local processor, all rows that contain column-indices in
1186  //the domain-map.
1187  const Epetra_Map* domainMap_A = &(A.DomainMap());
1188  const Epetra_Map* domainMap_B = &(B.DomainMap());
1189 
1190  const Epetra_Map* rowmap_A = &(A.RowMap());
1191  const Epetra_Map* rowmap_B = &(B.RowMap());
1192 
1193  //Declare some 'work-space' maps which may be created depending on
1194  //the scenario, and which will be deleted before exiting this function.
1195  const Epetra_Map* workmap1 = NULL;
1196  const Epetra_Map* workmap2 = NULL;
1197  const Epetra_Map* mapunion1 = NULL;
1198 
1199  //Declare a couple of structs that will be used to hold views of the data
1200  //of A and B, to be used for fast access during the matrix-multiplication.
1201  CrsMatrixStruct Aview;
1202  CrsMatrixStruct Bview;
1203 
1204  const Epetra_Map* targetMap_A = rowmap_A;
1205  const Epetra_Map* targetMap_B = rowmap_B;
1206 
1207 #ifdef ENABLE_MMM_TIMINGS
1208  mtime->stop();
1209  mtime=M.getNewTimer("All I&X");
1210  mtime->start();
1211 #endif
1212  if (numProcs > 1) {
1213  //If op(A) = A^T, find all rows of A that contain column-indices in the
1214  //local portion of the domain-map. (We'll import any remote rows
1215  //that fit this criteria onto the local processor.)
1216  if (transposeA) {
1217  workmap1 = find_rows_containing_cols(A, *domainMap_A);
1218  targetMap_A = workmap1;
1219  }
1220  }
1221 
1222  //Now import any needed remote rows and populate the Aview struct.
1223  if(scenario==1 && call_FillComplete_on_result) {
1224  EPETRA_CHK_ERR(import_only(A,*targetMap_A,Aview));
1225  }
1226  else {
1227  EPETRA_CHK_ERR( import_and_extract_views(A, *targetMap_A, Aview));
1228  }
1229 
1230 
1231  // NOTE: Next up is to switch to import_only for B as well, and then modify the THREE SerialCores
1232  // to add a Acol2Brow and Acol2Bimportrow array for in-algorithm lookups.
1233 
1234 
1235  // Make sure B's views are consistent with A even in serial.
1236  const Epetra_Map* colmap_op_A = NULL;
1237  if(scenario==1 || numProcs > 1){
1238  if (transposeA) {
1239  colmap_op_A = targetMap_A;
1240  }
1241  else {
1242  colmap_op_A = &(A.ColMap());
1243  }
1244  targetMap_B = colmap_op_A;
1245  }
1246 
1247  if (numProcs > 1) {
1248  //If op(B) = B^T, find all rows of B that contain column-indices in the
1249  //local-portion of the domain-map, or in the column-map of op(A).
1250  //We'll import any remote rows that fit this criteria onto the
1251  //local processor.
1252  if (transposeB) {
1253  EPETRA_CHK_ERR( form_map_union(colmap_op_A, domainMap_B, mapunion1) );
1254  workmap2 = find_rows_containing_cols(B, *mapunion1);
1255  targetMap_B = workmap2;
1256  }
1257  }
1258 
1259  //Now import any needed remote rows and populate the Bview struct.
1260  if(scenario==1 && call_FillComplete_on_result) {
1261  EPETRA_CHK_ERR(import_only(B,*targetMap_B,Bview,A.Importer()));
1262  }
1263  else {
1264  EPETRA_CHK_ERR( import_and_extract_views(B, *targetMap_B, Bview) );
1265  }
1266 
1267 #ifdef ENABLE_MMM_TIMINGS
1268  mtime->stop();
1269  mtime=M.getNewTimer("All Multiply");
1270  mtime->start();
1271 #endif
1272 
1273  // Zero if filled
1274  if(C.Filled()) C.PutScalar(0.0);
1275 
1276  //Now call the appropriate method to perform the actual multiplication.
1277  CrsWrapper_Epetra_CrsMatrix ecrsmat(C);
1278 
1279  switch(scenario) {
1280  case 1: EPETRA_CHK_ERR( mult_A_B(A,Aview,B,Bview,C,call_FillComplete_on_result) );
1281  break;
1282  case 2: EPETRA_CHK_ERR( mult_A_Btrans(Aview, Bview, ecrsmat) );
1283  break;
1284  case 3: EPETRA_CHK_ERR( mult_Atrans_B(Aview, Bview, ecrsmat) );
1285  break;
1286  case 4: EPETRA_CHK_ERR( mult_Atrans_Btrans(Aview, Bview, ecrsmat) );
1287  break;
1288  }
1289 
1290 
1291  if (scenario != 1 && call_FillComplete_on_result) {
1292  //We'll call FillComplete on the C matrix before we exit, and give
1293  //it a domain-map and a range-map.
1294  //The domain-map will be the domain-map of B, unless
1295  //op(B)==transpose(B), in which case the range-map of B will be used.
1296  //The range-map will be the range-map of A, unless
1297  //op(A)==transpose(A), in which case the domain-map of A will be used.
1298 
1299  const Epetra_Map* domainmap =
1300  transposeB ? &(B.RangeMap()) : &(B.DomainMap());
1301 
1302  const Epetra_Map* rangemap =
1303  transposeA ? &(A.DomainMap()) : &(A.RangeMap());
1304 
1305  if (!C.Filled()) {
1306  EPETRA_CHK_ERR( C.FillComplete(*domainmap, *rangemap) );
1307  }
1308  }
1309 
1310  //Finally, delete the objects that were potentially created
1311  //during the course of importing remote sections of A and B.
1312 
1313  delete mapunion1; mapunion1 = NULL;
1314  delete workmap1; workmap1 = NULL;
1315  delete workmap2; workmap2 = NULL;
1316 
1317 #ifdef ENABLE_MMM_TIMINGS
1318  mtime->stop();
1319 #endif
1320 
1321 
1322  return(0);
1323 }
1324 
1325 //=========================================================================
1326 int MatrixMatrix::Add(const Epetra_CrsMatrix& A,
1327  bool transposeA,
1328  double scalarA,
1329  Epetra_CrsMatrix& B,
1330  double scalarB )
1331 {
1332  //
1333  //This method forms the matrix-matrix sum B = scalarA * op(A) + scalarB * B, where
1334 
1335  //A should already be Filled. It doesn't matter whether B is
1336  //already Filled, but if it is, then its graph must already contain
1337  //all nonzero locations that will be referenced in forming the
1338  //sum.
1339 
1340  if (!A.Filled() ) {
1341  std::cerr << "EpetraExt::MatrixMatrix::Add ERROR, input matrix A.Filled() is false, it is required to be true. (Result matrix B is not required to be Filled())."<<std::endl;
1342  EPETRA_CHK_ERR(-1);
1343  }
1344 
1345  //explicit tranpose A formed as necessary
1346  Epetra_CrsMatrix * Aprime = 0;
1347  EpetraExt::RowMatrix_Transpose * Atrans = 0;
1348  if( transposeA )
1349  {
1350  Atrans = new EpetraExt::RowMatrix_Transpose();
1351  Aprime = &(dynamic_cast<Epetra_CrsMatrix&>(((*Atrans)(const_cast<Epetra_CrsMatrix&>(A)))));
1352  }
1353  else
1354  Aprime = const_cast<Epetra_CrsMatrix*>(&A);
1355 
1356  int MaxNumEntries = EPETRA_MAX( A.MaxNumEntries(), B.MaxNumEntries() );
1357  int A_NumEntries, B_NumEntries;
1358  int * A_Indices = new int[MaxNumEntries];
1359  double * A_Values = new double[MaxNumEntries];
1360  int* B_Indices;
1361  double* B_Values;
1362 
1363  int NumMyRows = B.NumMyRows();
1364  int Row, err;
1365  int ierr = 0;
1366 
1367  if( scalarA )
1368  {
1369  //Loop over B's rows and sum into
1370  for( int i = 0; i < NumMyRows; ++i )
1371  {
1372  Row = B.GRID(i);
1373  EPETRA_CHK_ERR( Aprime->ExtractGlobalRowCopy( Row, MaxNumEntries, A_NumEntries, A_Values, A_Indices ) );
1374 
1375  if (scalarB != 1.0) {
1376  if (!B.Filled()) {
1377  EPETRA_CHK_ERR( B.ExtractGlobalRowView( Row, B_NumEntries,
1378  B_Values, B_Indices));
1379  }
1380  else {
1381  EPETRA_CHK_ERR( B.ExtractMyRowView( i, B_NumEntries,
1382  B_Values, B_Indices));
1383  }
1384 
1385  for(int jj=0; jj<B_NumEntries; ++jj) {
1386  B_Values[jj] = scalarB*B_Values[jj];
1387  }
1388  }
1389 
1390  if( scalarA != 1.0 ) {
1391  for( int j = 0; j < A_NumEntries; ++j ) A_Values[j] *= scalarA;
1392  }
1393 
1394  if( B.Filled() ) {//Sum In Values
1395  err = B.SumIntoGlobalValues( Row, A_NumEntries, A_Values, A_Indices );
1396  assert( err >= 0 );
1397  if (err < 0) ierr = err;
1398  }
1399  else {
1400  err = B.InsertGlobalValues( Row, A_NumEntries, A_Values, A_Indices );
1401  assert( err == 0 || err == 1 || err == 3 );
1402  if (err < 0) ierr = err;
1403  }
1404  }
1405  }
1406  else {
1407  EPETRA_CHK_ERR( B.Scale(scalarB) );
1408  }
1409 
1410  delete [] A_Indices;
1411  delete [] A_Values;
1412 
1413  if( Atrans ) delete Atrans;
1414 
1415  return(ierr);
1416 }
1417 
1418 int MatrixMatrix::Add(const Epetra_CrsMatrix& A,
1419  bool transposeA,
1420  double scalarA,
1421  const Epetra_CrsMatrix & B,
1422  bool transposeB,
1423  double scalarB,
1424  Epetra_CrsMatrix * & C)
1425 {
1426  //
1427  //This method forms the matrix-matrix sum C = scalarA * op(A) + scalarB * op(B), where
1428 
1429  //A and B should already be Filled. C should be an empty pointer.
1430 
1431  if (!A.Filled() || !B.Filled() ) {
1432  std::cerr << "EpetraExt::MatrixMatrix::Add ERROR, input matrix A.Filled() or B.Filled() is false,"
1433  << "they are required to be true. (Result matrix C should be an empty pointer)" << std::endl;
1434  EPETRA_CHK_ERR(-1);
1435  }
1436 
1437  Epetra_CrsMatrix * Aprime = 0, * Bprime=0;
1438  EpetraExt::RowMatrix_Transpose * Atrans = 0,* Btrans = 0;
1439 
1440  //explicit tranpose A formed as necessary
1441  if( transposeA ) {
1442  Atrans = new EpetraExt::RowMatrix_Transpose();
1443  Aprime = &(dynamic_cast<Epetra_CrsMatrix&>(((*Atrans)(const_cast<Epetra_CrsMatrix&>(A)))));
1444  }
1445  else
1446  Aprime = const_cast<Epetra_CrsMatrix*>(&A);
1447 
1448  //explicit tranpose B formed as necessary
1449  if( transposeB ) {
1450  Btrans = new EpetraExt::RowMatrix_Transpose();
1451  Bprime = &(dynamic_cast<Epetra_CrsMatrix&>(((*Btrans)(const_cast<Epetra_CrsMatrix&>(B)))));
1452  }
1453  else
1454  Bprime = const_cast<Epetra_CrsMatrix*>(&B);
1455 
1456  // allocate or zero the new matrix
1457  if(C!=0)
1458  C->PutScalar(0.0);
1459  else
1460  C = new Epetra_CrsMatrix(Copy,Aprime->RowMap(),0);
1461 
1462  // build arrays for easy resuse
1463  int ierr = 0;
1464  Epetra_CrsMatrix * Mat[] = { Aprime,Bprime};
1465  double scalar[] = { scalarA, scalarB};
1466 
1467  // do a loop over each matrix to add: A reordering might be more efficient
1468  for(int k=0;k<2;k++) {
1469  int MaxNumEntries = Mat[k]->MaxNumEntries();
1470  int NumEntries;
1471  int * Indices = new int[MaxNumEntries];
1472  double * Values = new double[MaxNumEntries];
1473 
1474  int NumMyRows = Mat[k]->NumMyRows();
1475  int Row, err;
1476  int ierr = 0;
1477 
1478  //Loop over rows and sum into C
1479  for( int i = 0; i < NumMyRows; ++i ) {
1480  Row = Mat[k]->GRID(i);
1481  EPETRA_CHK_ERR( Mat[k]->ExtractGlobalRowCopy( Row, MaxNumEntries, NumEntries, Values, Indices));
1482 
1483  if( scalar[k] != 1.0 )
1484  for( int j = 0; j < NumEntries; ++j ) Values[j] *= scalar[k];
1485 
1486  if(C->Filled()) { // Sum in values
1487  err = C->SumIntoGlobalValues( Row, NumEntries, Values, Indices );
1488  if (err < 0) ierr = err;
1489  } else { // just add it to the unfilled CRS Matrix
1490  err = C->InsertGlobalValues( Row, NumEntries, Values, Indices );
1491  if (err < 0) ierr = err;
1492  }
1493  }
1494 
1495  delete [] Indices;
1496  delete [] Values;
1497  }
1498 
1499  if( Atrans ) delete Atrans;
1500  if( Btrans ) delete Btrans;
1501 
1502  return(ierr);
1503 }
1504 
1505 
1506 } // namespace EpetraExt
1507 
LightweightCrsMatrix * importMatrix
std::vector< int > targetMapToOrigRow
int form_map_union(const Epetra_Map *map1, const Epetra_Map *map2, const Epetra_Map *&mapunion)
virtual int SumIntoGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)=0
int import_only(const Epetra_CrsMatrix &M, const Epetra_Map &targetMap, CrsMatrixStruct &Mview, const Epetra_Import *prototypeImporter=0)
static int Multiply(const Epetra_CrsMatrix &A, bool transposeA, const Epetra_CrsMatrix &B, bool transposeB, Epetra_CrsMatrix &C, bool call_FillComplete_on_result=true)
Given Epetra_CrsMatrix objects A, B and C, form the product C = A*B.
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)
double sparsedot(double *u, int *u_ind, int u_len, double *v, int *v_ind, int v_len)
Method for internal use...
virtual bool Filled()=0
int mult_Atrans_Btrans(CrsMatrixStruct &Aview, CrsMatrixStruct &Bview, CrsWrapper &C)
virtual int InsertGlobalValues(int GlobalRow, int NumEntries, double *Values, int *Indices)=0
int mult_Atrans_B(CrsMatrixStruct &Aview, CrsMatrixStruct &Bview, CrsWrapper &C)
const Epetra_CrsMatrix * origMatrix
Transform to form the explicit transpose of a Epetra_RowMatrix.
Epetra_Map * find_rows_containing_cols(const Epetra_CrsMatrix &M, const Epetra_Map &column_map)
std::vector< int > targetMapToImportRow
virtual const Epetra_Map & RowMap() const =0
std::pair< int, int > get_col_range(const Epetra_Map &emap)
static int Add(const Epetra_CrsMatrix &A, bool transposeA, double scalarA, Epetra_CrsMatrix &B, double scalarB)
Given Epetra_CrsMatrix objects A and B, form the sum B = a*A + b*B.
const Epetra_BlockMap * importColMap
int import_and_extract_views(const Epetra_CrsMatrix &M, const Epetra_Map &targetMap, CrsMatrixStruct &Mview, const Epetra_Import *prototypeImporter=0)
int mult_A_Btrans(CrsMatrixStruct &Aview, CrsMatrixStruct &Bview, CrsWrapper &C)