Actual source code: mpiaij.c

petsc-master 2014-10-18
Report Typos and Errors
  2: #include <../src/mat/impls/aij/mpi/mpiaij.h>   /*I "petscmat.h" I*/
  3: #include <petsc-private/vecimpl.h>
  4: #include <petscblaslapack.h>
  5: #include <petscsf.h>

  7: /*MC
  8:    MATAIJ - MATAIJ = "aij" - A matrix type to be used for sparse matrices.

 10:    This matrix type is identical to MATSEQAIJ when constructed with a single process communicator,
 11:    and MATMPIAIJ otherwise.  As a result, for single process communicators,
 12:   MatSeqAIJSetPreallocation is supported, and similarly MatMPIAIJSetPreallocation is supported
 13:   for communicators controlling multiple processes.  It is recommended that you call both of
 14:   the above preallocation routines for simplicity.

 16:    Options Database Keys:
 17: . -mat_type aij - sets the matrix type to "aij" during a call to MatSetFromOptions()

 19:   Developer Notes: Subclasses include MATAIJCUSP, MATAIJCUSPARSE, MATAIJPERM, MATAIJCRL, and also automatically switches over to use inodes when
 20:    enough exist.

 22:   Level: beginner

 24: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ,MATMPIAIJ
 25: M*/

 27: /*MC
 28:    MATAIJCRL - MATAIJCRL = "aijcrl" - A matrix type to be used for sparse matrices.

 30:    This matrix type is identical to MATSEQAIJCRL when constructed with a single process communicator,
 31:    and MATMPIAIJCRL otherwise.  As a result, for single process communicators,
 32:    MatSeqAIJSetPreallocation() is supported, and similarly MatMPIAIJSetPreallocation() is supported
 33:   for communicators controlling multiple processes.  It is recommended that you call both of
 34:   the above preallocation routines for simplicity.

 36:    Options Database Keys:
 37: . -mat_type aijcrl - sets the matrix type to "aijcrl" during a call to MatSetFromOptions()

 39:   Level: beginner

 41: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
 42: M*/

 46: PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M,IS *keptrows)
 47: {
 48:   PetscErrorCode  ierr;
 49:   Mat_MPIAIJ      *mat = (Mat_MPIAIJ*)M->data;
 50:   Mat_SeqAIJ      *a   = (Mat_SeqAIJ*)mat->A->data;
 51:   Mat_SeqAIJ      *b   = (Mat_SeqAIJ*)mat->B->data;
 52:   const PetscInt  *ia,*ib;
 53:   const MatScalar *aa,*bb;
 54:   PetscInt        na,nb,i,j,*rows,cnt=0,n0rows;
 55:   PetscInt        m = M->rmap->n,rstart = M->rmap->rstart;

 58:   *keptrows = 0;
 59:   ia        = a->i;
 60:   ib        = b->i;
 61:   for (i=0; i<m; i++) {
 62:     na = ia[i+1] - ia[i];
 63:     nb = ib[i+1] - ib[i];
 64:     if (!na && !nb) {
 65:       cnt++;
 66:       goto ok1;
 67:     }
 68:     aa = a->a + ia[i];
 69:     for (j=0; j<na; j++) {
 70:       if (aa[j] != 0.0) goto ok1;
 71:     }
 72:     bb = b->a + ib[i];
 73:     for (j=0; j <nb; j++) {
 74:       if (bb[j] != 0.0) goto ok1;
 75:     }
 76:     cnt++;
 77: ok1:;
 78:   }
 79:   MPI_Allreduce(&cnt,&n0rows,1,MPIU_INT,MPIU_SUM,PetscObjectComm((PetscObject)M));
 80:   if (!n0rows) return(0);
 81:   PetscMalloc1((M->rmap->n-cnt),&rows);
 82:   cnt  = 0;
 83:   for (i=0; i<m; i++) {
 84:     na = ia[i+1] - ia[i];
 85:     nb = ib[i+1] - ib[i];
 86:     if (!na && !nb) continue;
 87:     aa = a->a + ia[i];
 88:     for (j=0; j<na;j++) {
 89:       if (aa[j] != 0.0) {
 90:         rows[cnt++] = rstart + i;
 91:         goto ok2;
 92:       }
 93:     }
 94:     bb = b->a + ib[i];
 95:     for (j=0; j<nb; j++) {
 96:       if (bb[j] != 0.0) {
 97:         rows[cnt++] = rstart + i;
 98:         goto ok2;
 99:       }
100:     }
101: ok2:;
102:   }
103:   ISCreateGeneral(PetscObjectComm((PetscObject)M),cnt,rows,PETSC_OWN_POINTER,keptrows);
104:   return(0);
105: }

109: PetscErrorCode  MatDiagonalSet_MPIAIJ(Mat Y,Vec D,InsertMode is)
110: {
111:   PetscErrorCode    ierr;
112:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*) Y->data;

115:   if (Y->assembled && Y->rmap->rstart == Y->cmap->rstart && Y->rmap->rend == Y->cmap->rend) {
116:     MatDiagonalSet(aij->A,D,is);
117:   } else {
118:     MatDiagonalSet_Default(Y,D,is);
119:   }
120:   return(0);
121: }


126: PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M,IS *zrows)
127: {
128:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)M->data;
130:   PetscInt       i,rstart,nrows,*rows;

133:   *zrows = NULL;
134:   MatFindZeroDiagonals_SeqAIJ_Private(aij->A,&nrows,&rows);
135:   MatGetOwnershipRange(M,&rstart,NULL);
136:   for (i=0; i<nrows; i++) rows[i] += rstart;
137:   ISCreateGeneral(PetscObjectComm((PetscObject)M),nrows,rows,PETSC_OWN_POINTER,zrows);
138:   return(0);
139: }

143: PetscErrorCode MatGetColumnNorms_MPIAIJ(Mat A,NormType type,PetscReal *norms)
144: {
146:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)A->data;
147:   PetscInt       i,n,*garray = aij->garray;
148:   Mat_SeqAIJ     *a_aij = (Mat_SeqAIJ*) aij->A->data;
149:   Mat_SeqAIJ     *b_aij = (Mat_SeqAIJ*) aij->B->data;
150:   PetscReal      *work;

153:   MatGetSize(A,NULL,&n);
154:   PetscCalloc1(n,&work);
155:   if (type == NORM_2) {
156:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
157:       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]*a_aij->a[i]);
158:     }
159:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
160:       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]*b_aij->a[i]);
161:     }
162:   } else if (type == NORM_1) {
163:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
164:       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
165:     }
166:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
167:       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
168:     }
169:   } else if (type == NORM_INFINITY) {
170:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
171:       work[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), work[A->cmap->rstart + a_aij->j[i]]);
172:     }
173:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
174:       work[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]),work[garray[b_aij->j[i]]]);
175:     }

177:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Unknown NormType");
178:   if (type == NORM_INFINITY) {
179:     MPI_Allreduce(work,norms,n,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)A));
180:   } else {
181:     MPI_Allreduce(work,norms,n,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)A));
182:   }
183:   PetscFree(work);
184:   if (type == NORM_2) {
185:     for (i=0; i<n; i++) norms[i] = PetscSqrtReal(norms[i]);
186:   }
187:   return(0);
188: }

192: /*
193:     Distributes a SeqAIJ matrix across a set of processes. Code stolen from
194:     MatLoad_MPIAIJ(). Horrible lack of reuse. Should be a routine for each matrix type.

196:     Only for square matrices

198:     Used by a preconditioner, hence PETSC_EXTERN
199: */
200: PETSC_EXTERN PetscErrorCode MatDistribute_MPIAIJ(MPI_Comm comm,Mat gmat,PetscInt m,MatReuse reuse,Mat *inmat)
201: {
202:   PetscMPIInt    rank,size;
203:   PetscInt       *rowners,*dlens,*olens,i,rstart,rend,j,jj,nz = 0,*gmataj,cnt,row,*ld,bses[2];
205:   Mat            mat;
206:   Mat_SeqAIJ     *gmata;
207:   PetscMPIInt    tag;
208:   MPI_Status     status;
209:   PetscBool      aij;
210:   MatScalar      *gmataa,*ao,*ad,*gmataarestore=0;

213:   MPI_Comm_rank(comm,&rank);
214:   MPI_Comm_size(comm,&size);
215:   if (!rank) {
216:     PetscObjectTypeCompare((PetscObject)gmat,MATSEQAIJ,&aij);
217:     if (!aij) SETERRQ1(PetscObjectComm((PetscObject)gmat),PETSC_ERR_SUP,"Currently no support for input matrix of type %s\n",((PetscObject)gmat)->type_name);
218:   }
219:   if (reuse == MAT_INITIAL_MATRIX) {
220:     MatCreate(comm,&mat);
221:     MatSetSizes(mat,m,m,PETSC_DETERMINE,PETSC_DETERMINE);
222:     MatGetBlockSizes(gmat,&bses[0],&bses[1]);
223:     MPI_Bcast(bses,2,MPIU_INT,0,comm);
224:     MatSetBlockSizes(mat,bses[0],bses[1]);
225:     MatSetType(mat,MATAIJ);
226:     PetscMalloc1((size+1),&rowners);
227:     PetscMalloc2(m,&dlens,m,&olens);
228:     MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

230:     rowners[0] = 0;
231:     for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
232:     rstart = rowners[rank];
233:     rend   = rowners[rank+1];
234:     PetscObjectGetNewTag((PetscObject)mat,&tag);
235:     if (!rank) {
236:       gmata = (Mat_SeqAIJ*) gmat->data;
237:       /* send row lengths to all processors */
238:       for (i=0; i<m; i++) dlens[i] = gmata->ilen[i];
239:       for (i=1; i<size; i++) {
240:         MPI_Send(gmata->ilen + rowners[i],rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
241:       }
242:       /* determine number diagonal and off-diagonal counts */
243:       PetscMemzero(olens,m*sizeof(PetscInt));
244:       PetscCalloc1(m,&ld);
245:       jj   = 0;
246:       for (i=0; i<m; i++) {
247:         for (j=0; j<dlens[i]; j++) {
248:           if (gmata->j[jj] < rstart) ld[i]++;
249:           if (gmata->j[jj] < rstart || gmata->j[jj] >= rend) olens[i]++;
250:           jj++;
251:         }
252:       }
253:       /* send column indices to other processes */
254:       for (i=1; i<size; i++) {
255:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
256:         MPI_Send(&nz,1,MPIU_INT,i,tag,comm);
257:         MPI_Send(gmata->j + gmata->i[rowners[i]],nz,MPIU_INT,i,tag,comm);
258:       }

260:       /* send numerical values to other processes */
261:       for (i=1; i<size; i++) {
262:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
263:         MPI_Send(gmata->a + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
264:       }
265:       gmataa = gmata->a;
266:       gmataj = gmata->j;

268:     } else {
269:       /* receive row lengths */
270:       MPI_Recv(dlens,m,MPIU_INT,0,tag,comm,&status);
271:       /* receive column indices */
272:       MPI_Recv(&nz,1,MPIU_INT,0,tag,comm,&status);
273:       PetscMalloc2(nz,&gmataa,nz,&gmataj);
274:       MPI_Recv(gmataj,nz,MPIU_INT,0,tag,comm,&status);
275:       /* determine number diagonal and off-diagonal counts */
276:       PetscMemzero(olens,m*sizeof(PetscInt));
277:       PetscCalloc1(m,&ld);
278:       jj   = 0;
279:       for (i=0; i<m; i++) {
280:         for (j=0; j<dlens[i]; j++) {
281:           if (gmataj[jj] < rstart) ld[i]++;
282:           if (gmataj[jj] < rstart || gmataj[jj] >= rend) olens[i]++;
283:           jj++;
284:         }
285:       }
286:       /* receive numerical values */
287:       PetscMemzero(gmataa,nz*sizeof(PetscScalar));
288:       MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
289:     }
290:     /* set preallocation */
291:     for (i=0; i<m; i++) {
292:       dlens[i] -= olens[i];
293:     }
294:     MatSeqAIJSetPreallocation(mat,0,dlens);
295:     MatMPIAIJSetPreallocation(mat,0,dlens,0,olens);

297:     for (i=0; i<m; i++) {
298:       dlens[i] += olens[i];
299:     }
300:     cnt = 0;
301:     for (i=0; i<m; i++) {
302:       row  = rstart + i;
303:       MatSetValues(mat,1,&row,dlens[i],gmataj+cnt,gmataa+cnt,INSERT_VALUES);
304:       cnt += dlens[i];
305:     }
306:     if (rank) {
307:       PetscFree2(gmataa,gmataj);
308:     }
309:     PetscFree2(dlens,olens);
310:     PetscFree(rowners);

312:     ((Mat_MPIAIJ*)(mat->data))->ld = ld;

314:     *inmat = mat;
315:   } else {   /* column indices are already set; only need to move over numerical values from process 0 */
316:     Mat_SeqAIJ *Ad = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->A->data;
317:     Mat_SeqAIJ *Ao = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->B->data;
318:     mat  = *inmat;
319:     PetscObjectGetNewTag((PetscObject)mat,&tag);
320:     if (!rank) {
321:       /* send numerical values to other processes */
322:       gmata  = (Mat_SeqAIJ*) gmat->data;
323:       MatGetOwnershipRanges(mat,(const PetscInt**)&rowners);
324:       gmataa = gmata->a;
325:       for (i=1; i<size; i++) {
326:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
327:         MPI_Send(gmataa + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
328:       }
329:       nz = gmata->i[rowners[1]]-gmata->i[rowners[0]];
330:     } else {
331:       /* receive numerical values from process 0*/
332:       nz   = Ad->nz + Ao->nz;
333:       PetscMalloc1(nz,&gmataa); gmataarestore = gmataa;
334:       MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
335:     }
336:     /* transfer numerical values into the diagonal A and off diagonal B parts of mat */
337:     ld = ((Mat_MPIAIJ*)(mat->data))->ld;
338:     ad = Ad->a;
339:     ao = Ao->a;
340:     if (mat->rmap->n) {
341:       i  = 0;
342:       nz = ld[i];                                   PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
343:       nz = Ad->i[i+1] - Ad->i[i];                   PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
344:     }
345:     for (i=1; i<mat->rmap->n; i++) {
346:       nz = Ao->i[i] - Ao->i[i-1] - ld[i-1] + ld[i]; PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
347:       nz = Ad->i[i+1] - Ad->i[i];                   PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
348:     }
349:     i--;
350:     if (mat->rmap->n) {
351:       nz = Ao->i[i+1] - Ao->i[i] - ld[i];           PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar));
352:     }
353:     if (rank) {
354:       PetscFree(gmataarestore);
355:     }
356:   }
357:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
358:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
359:   return(0);
360: }

362: /*
363:   Local utility routine that creates a mapping from the global column
364: number to the local number in the off-diagonal part of the local
365: storage of the matrix.  When PETSC_USE_CTABLE is used this is scalable at
366: a slightly higher hash table cost; without it it is not scalable (each processor
367: has an order N integer array but is fast to acess.
368: */
371: PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
372: {
373:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
375:   PetscInt       n = aij->B->cmap->n,i;

378:   if (!aij->garray) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MPIAIJ Matrix was assembled but is missing garray");
379: #if defined(PETSC_USE_CTABLE)
380:   PetscTableCreate(n,mat->cmap->N+1,&aij->colmap);
381:   for (i=0; i<n; i++) {
382:     PetscTableAdd(aij->colmap,aij->garray[i]+1,i+1,INSERT_VALUES);
383:   }
384: #else
385:   PetscCalloc1((mat->cmap->N+1),&aij->colmap);
386:   PetscLogObjectMemory((PetscObject)mat,(mat->cmap->N+1)*sizeof(PetscInt));
387:   for (i=0; i<n; i++) aij->colmap[aij->garray[i]] = i+1;
388: #endif
389:   return(0);
390: }

392: #define MatSetValues_SeqAIJ_A_Private(row,col,value,addv) \
393: { \
394:     if (col <= lastcol1)  low1 = 0;     \
395:     else                 high1 = nrow1; \
396:     lastcol1 = col;\
397:     while (high1-low1 > 5) { \
398:       t = (low1+high1)/2; \
399:       if (rp1[t] > col) high1 = t; \
400:       else              low1  = t; \
401:     } \
402:       for (_i=low1; _i<high1; _i++) { \
403:         if (rp1[_i] > col) break; \
404:         if (rp1[_i] == col) { \
405:           if (addv == ADD_VALUES) ap1[_i] += value;   \
406:           else                    ap1[_i] = value; \
407:           goto a_noinsert; \
408:         } \
409:       }  \
410:       if (value == 0.0 && ignorezeroentries) {low1 = 0; high1 = nrow1;goto a_noinsert;} \
411:       if (nonew == 1) {low1 = 0; high1 = nrow1; goto a_noinsert;}                \
412:       if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
413:       MatSeqXAIJReallocateAIJ(A,am,1,nrow1,row,col,rmax1,aa,ai,aj,rp1,ap1,aimax,nonew,MatScalar); \
414:       N = nrow1++ - 1; a->nz++; high1++; \
415:       /* shift up all the later entries in this row */ \
416:       for (ii=N; ii>=_i; ii--) { \
417:         rp1[ii+1] = rp1[ii]; \
418:         ap1[ii+1] = ap1[ii]; \
419:       } \
420:       rp1[_i] = col;  \
421:       ap1[_i] = value;  \
422:       A->nonzerostate++;\
423:       a_noinsert: ; \
424:       ailen[row] = nrow1; \
425: }


428: #define MatSetValues_SeqAIJ_B_Private(row,col,value,addv) \
429:   { \
430:     if (col <= lastcol2) low2 = 0;                        \
431:     else high2 = nrow2;                                   \
432:     lastcol2 = col;                                       \
433:     while (high2-low2 > 5) {                              \
434:       t = (low2+high2)/2;                                 \
435:       if (rp2[t] > col) high2 = t;                        \
436:       else             low2  = t;                         \
437:     }                                                     \
438:     for (_i=low2; _i<high2; _i++) {                       \
439:       if (rp2[_i] > col) break;                           \
440:       if (rp2[_i] == col) {                               \
441:         if (addv == ADD_VALUES) ap2[_i] += value;         \
442:         else                    ap2[_i] = value;          \
443:         goto b_noinsert;                                  \
444:       }                                                   \
445:     }                                                     \
446:     if (value == 0.0 && ignorezeroentries) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
447:     if (nonew == 1) {low2 = 0; high2 = nrow2; goto b_noinsert;}                        \
448:     if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
449:     MatSeqXAIJReallocateAIJ(B,bm,1,nrow2,row,col,rmax2,ba,bi,bj,rp2,ap2,bimax,nonew,MatScalar); \
450:     N = nrow2++ - 1; b->nz++; high2++;                    \
451:     /* shift up all the later entries in this row */      \
452:     for (ii=N; ii>=_i; ii--) {                            \
453:       rp2[ii+1] = rp2[ii];                                \
454:       ap2[ii+1] = ap2[ii];                                \
455:     }                                                     \
456:     rp2[_i] = col;                                        \
457:     ap2[_i] = value;                                      \
458:     B->nonzerostate++;                                    \
459:     b_noinsert: ;                                         \
460:     bilen[row] = nrow2;                                   \
461:   }

465: PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A,PetscInt row,const PetscScalar v[])
466: {
467:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)A->data;
468:   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)mat->A->data,*b = (Mat_SeqAIJ*)mat->B->data;
470:   PetscInt       l,*garray = mat->garray,diag;

473:   /* code only works for square matrices A */

475:   /* find size of row to the left of the diagonal part */
476:   MatGetOwnershipRange(A,&diag,0);
477:   row  = row - diag;
478:   for (l=0; l<b->i[row+1]-b->i[row]; l++) {
479:     if (garray[b->j[b->i[row]+l]] > diag) break;
480:   }
481:   PetscMemcpy(b->a+b->i[row],v,l*sizeof(PetscScalar));

483:   /* diagonal part */
484:   PetscMemcpy(a->a+a->i[row],v+l,(a->i[row+1]-a->i[row])*sizeof(PetscScalar));

486:   /* right of diagonal part */
487:   PetscMemcpy(b->a+b->i[row]+l,v+l+a->i[row+1]-a->i[row],(b->i[row+1]-b->i[row]-l)*sizeof(PetscScalar));
488:   return(0);
489: }

493: PetscErrorCode MatSetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
494: {
495:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
496:   PetscScalar    value;
498:   PetscInt       i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
499:   PetscInt       cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
500:   PetscBool      roworiented = aij->roworiented;

502:   /* Some Variables required in the macro */
503:   Mat        A                 = aij->A;
504:   Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
505:   PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
506:   MatScalar  *aa               = a->a;
507:   PetscBool  ignorezeroentries = a->ignorezeroentries;
508:   Mat        B                 = aij->B;
509:   Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
510:   PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
511:   MatScalar  *ba               = b->a;

513:   PetscInt  *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
514:   PetscInt  nonew;
515:   MatScalar *ap1,*ap2;

518:   for (i=0; i<m; i++) {
519:     if (im[i] < 0) continue;
520: #if defined(PETSC_USE_DEBUG)
521:     if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
522: #endif
523:     if (im[i] >= rstart && im[i] < rend) {
524:       row      = im[i] - rstart;
525:       lastcol1 = -1;
526:       rp1      = aj + ai[row];
527:       ap1      = aa + ai[row];
528:       rmax1    = aimax[row];
529:       nrow1    = ailen[row];
530:       low1     = 0;
531:       high1    = nrow1;
532:       lastcol2 = -1;
533:       rp2      = bj + bi[row];
534:       ap2      = ba + bi[row];
535:       rmax2    = bimax[row];
536:       nrow2    = bilen[row];
537:       low2     = 0;
538:       high2    = nrow2;

540:       for (j=0; j<n; j++) {
541:         if (roworiented) value = v[i*n+j];
542:         else             value = v[i+j*m];
543:         if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
544:         if (in[j] >= cstart && in[j] < cend) {
545:           col   = in[j] - cstart;
546:           nonew = a->nonew;
547:           MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
548:         } else if (in[j] < 0) continue;
549: #if defined(PETSC_USE_DEBUG)
550:         else if (in[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);
551: #endif
552:         else {
553:           if (mat->was_assembled) {
554:             if (!aij->colmap) {
555:               MatCreateColmap_MPIAIJ_Private(mat);
556:             }
557: #if defined(PETSC_USE_CTABLE)
558:             PetscTableFind(aij->colmap,in[j]+1,&col);
559:             col--;
560: #else
561:             col = aij->colmap[in[j]] - 1;
562: #endif
563:             if (col < 0 && !((Mat_SeqAIJ*)(aij->B->data))->nonew) {
564:               MatDisAssemble_MPIAIJ(mat);
565:               col  =  in[j];
566:               /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
567:               B     = aij->B;
568:               b     = (Mat_SeqAIJ*)B->data;
569:               bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j; ba = b->a;
570:               rp2   = bj + bi[row];
571:               ap2   = ba + bi[row];
572:               rmax2 = bimax[row];
573:               nrow2 = bilen[row];
574:               low2  = 0;
575:               high2 = nrow2;
576:               bm    = aij->B->rmap->n;
577:               ba    = b->a;
578:             } else if (col < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", im[i], in[j]);
579:           } else col = in[j];
580:           nonew = b->nonew;
581:           MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
582:         }
583:       }
584:     } else {
585:       if (mat->nooffprocentries) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Setting off process row %D even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set",im[i]);
586:       if (!aij->donotstash) {
587:         mat->assembled = PETSC_FALSE;
588:         if (roworiented) {
589:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
590:         } else {
591:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
592:         }
593:       }
594:     }
595:   }
596:   return(0);
597: }

601: PetscErrorCode MatGetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
602: {
603:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
605:   PetscInt       i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
606:   PetscInt       cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;

609:   for (i=0; i<m; i++) {
610:     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
611:     if (idxm[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",idxm[i],mat->rmap->N-1);
612:     if (idxm[i] >= rstart && idxm[i] < rend) {
613:       row = idxm[i] - rstart;
614:       for (j=0; j<n; j++) {
615:         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
616:         if (idxn[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",idxn[j],mat->cmap->N-1);
617:         if (idxn[j] >= cstart && idxn[j] < cend) {
618:           col  = idxn[j] - cstart;
619:           MatGetValues(aij->A,1,&row,1,&col,v+i*n+j);
620:         } else {
621:           if (!aij->colmap) {
622:             MatCreateColmap_MPIAIJ_Private(mat);
623:           }
624: #if defined(PETSC_USE_CTABLE)
625:           PetscTableFind(aij->colmap,idxn[j]+1,&col);
626:           col--;
627: #else
628:           col = aij->colmap[idxn[j]] - 1;
629: #endif
630:           if ((col < 0) || (aij->garray[col] != idxn[j])) *(v+i*n+j) = 0.0;
631:           else {
632:             MatGetValues(aij->B,1,&row,1,&col,v+i*n+j);
633:           }
634:         }
635:       }
636:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
637:   }
638:   return(0);
639: }

641: extern PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat,Vec,Vec);

645: PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
646: {
647:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
649:   PetscInt       nstash,reallocs;
650:   InsertMode     addv;

653:   if (aij->donotstash || mat->nooffprocentries) return(0);

655:   /* make sure all processors are either in INSERTMODE or ADDMODE */
656:   MPI_Allreduce((PetscEnum*)&mat->insertmode,(PetscEnum*)&addv,1,MPIU_ENUM,MPI_BOR,PetscObjectComm((PetscObject)mat));
657:   if (addv == (ADD_VALUES|INSERT_VALUES)) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"Some processors inserted others added");
658:   mat->insertmode = addv; /* in case this processor had no cache */

660:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
661:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
662:   PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
663:   return(0);
664: }

668: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat,MatAssemblyType mode)
669: {
670:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
671:   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)aij->A->data;
673:   PetscMPIInt    n;
674:   PetscInt       i,j,rstart,ncols,flg;
675:   PetscInt       *row,*col;
676:   PetscBool      other_disassembled;
677:   PetscScalar    *val;
678:   InsertMode     addv = mat->insertmode;

680:   /* do not use 'b = (Mat_SeqAIJ*)aij->B->data' as B can be reset in disassembly */

683:   if (!aij->donotstash && !mat->nooffprocentries) {
684:     while (1) {
685:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
686:       if (!flg) break;

688:       for (i=0; i<n; ) {
689:         /* Now identify the consecutive vals belonging to the same row */
690:         for (j=i,rstart=row[j]; j<n; j++) {
691:           if (row[j] != rstart) break;
692:         }
693:         if (j < n) ncols = j-i;
694:         else       ncols = n-i;
695:         /* Now assemble all these values with a single function call */
696:         MatSetValues_MPIAIJ(mat,1,row+i,ncols,col+i,val+i,addv);

698:         i = j;
699:       }
700:     }
701:     MatStashScatterEnd_Private(&mat->stash);
702:   }
703:   MatAssemblyBegin(aij->A,mode);
704:   MatAssemblyEnd(aij->A,mode);

706:   /* determine if any processor has disassembled, if so we must
707:      also disassemble ourselfs, in order that we may reassemble. */
708:   /*
709:      if nonzero structure of submatrix B cannot change then we know that
710:      no processor disassembled thus we can skip this stuff
711:   */
712:   if (!((Mat_SeqAIJ*)aij->B->data)->nonew) {
713:     MPI_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));
714:     if (mat->was_assembled && !other_disassembled) {
715:       MatDisAssemble_MPIAIJ(mat);
716:     }
717:   }
718:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
719:     MatSetUpMultiply_MPIAIJ(mat);
720:   }
721:   MatSetOption(aij->B,MAT_USE_INODES,PETSC_FALSE);
722:   MatAssemblyBegin(aij->B,mode);
723:   MatAssemblyEnd(aij->B,mode);

725:   PetscFree2(aij->rowvalues,aij->rowindices);

727:   aij->rowvalues = 0;

729:   /* used by MatAXPY() */
730:   a->xtoy = 0; ((Mat_SeqAIJ*)aij->B->data)->xtoy = 0;   /* b->xtoy = 0 */
731:   a->XtoY = 0; ((Mat_SeqAIJ*)aij->B->data)->XtoY = 0;   /* b->XtoY = 0 */

733:   VecDestroy(&aij->diag);
734:   if (a->inode.size) mat->ops->multdiagonalblock = MatMultDiagonalBlock_MPIAIJ;

736:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
737:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
738:     PetscObjectState state = aij->A->nonzerostate + aij->B->nonzerostate;
739:     MPI_Allreduce(&state,&mat->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)mat));
740:   }
741:   return(0);
742: }

746: PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
747: {
748:   Mat_MPIAIJ     *l = (Mat_MPIAIJ*)A->data;

752:   MatZeroEntries(l->A);
753:   MatZeroEntries(l->B);
754:   return(0);
755: }

759: PetscErrorCode MatZeroRows_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
760: {
761:   Mat_MPIAIJ    *mat    = (Mat_MPIAIJ *) A->data;
762:   PetscInt      *owners = A->rmap->range;
763:   PetscInt       n      = A->rmap->n;
764:   PetscSF        sf;
765:   PetscInt      *lrows;
766:   PetscSFNode   *rrows;
767:   PetscInt       r, p = 0, len = 0;

771:   /* Create SF where leaves are input rows and roots are owned rows */
772:   PetscMalloc1(n, &lrows);
773:   for (r = 0; r < n; ++r) lrows[r] = -1;
774:   if (!A->nooffproczerorows) {PetscMalloc1(N, &rrows);}
775:   for (r = 0; r < N; ++r) {
776:     const PetscInt idx   = rows[r];
777:     if (idx < 0 || A->rmap->N <= idx) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row %D out of range [0,%D)",idx,A->rmap->N);
778:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
779:       PetscLayoutFindOwner(A->rmap,idx,&p);
780:     }
781:     if (A->nooffproczerorows) {
782:       if (p != mat->rank) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"MAT_NO_OFF_PROC_ZERO_ROWS set, but row %D is not owned by rank %d",idx,mat->rank);
783:       lrows[len++] = idx - owners[p];
784:     } else {
785:       rrows[r].rank = p;
786:       rrows[r].index = rows[r] - owners[p];
787:     }
788:   }
789:   if (!A->nooffproczerorows) {
790:     PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
791:     PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
792:     /* Collect flags for rows to be zeroed */
793:     PetscSFReduceBegin(sf, MPIU_INT, (PetscInt*)rows, lrows, MPI_LOR);
794:     PetscSFReduceEnd(sf, MPIU_INT, (PetscInt*)rows, lrows, MPI_LOR);
795:     PetscSFDestroy(&sf);
796:     /* Compress and put in row numbers */
797:     for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
798:   }
799:   /* fix right hand side if needed */
800:   if (x && b) {
801:     const PetscScalar *xx;
802:     PetscScalar       *bb;

804:     VecGetArrayRead(x, &xx);
805:     VecGetArray(b, &bb);
806:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag*xx[lrows[r]];
807:     VecRestoreArrayRead(x, &xx);
808:     VecRestoreArray(b, &bb);
809:   }
810:   /* Must zero l->B before l->A because the (diag) case below may put values into l->B*/
811:   MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL);
812:   if ((diag != 0.0) && (mat->A->rmap->N == mat->A->cmap->N)) {
813:     MatZeroRows(mat->A, len, lrows, diag, NULL, NULL);
814:   } else if (diag != 0.0) {
815:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
816:     if (((Mat_SeqAIJ *) mat->A->data)->nonew) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MatZeroRows() on rectangular matrices cannot be used with the Mat options\nMAT_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
817:     for (r = 0; r < len; ++r) {
818:       const PetscInt row = lrows[r] + A->rmap->rstart;
819:       MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES);
820:     }
821:     MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
822:     MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
823:   } else {
824:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
825:   }
826:   PetscFree(lrows);

828:   /* only change matrix nonzero state if pattern was allowed to be changed */
829:   if (!((Mat_SeqAIJ*)(mat->A->data))->keepnonzeropattern) {
830:     PetscObjectState state = mat->A->nonzerostate + mat->B->nonzerostate;
831:     MPI_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
832:   }
833:   return(0);
834: }

838: PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
839: {
840:   Mat_MPIAIJ        *l = (Mat_MPIAIJ*)A->data;
841:   PetscErrorCode    ierr;
842:   PetscMPIInt       n = A->rmap->n;
843:   PetscInt          i,j,r,m,p = 0,len = 0;
844:   PetscInt          *lrows,*owners = A->rmap->range;
845:   PetscSFNode       *rrows;
846:   PetscSF           sf;
847:   const PetscScalar *xx;
848:   PetscScalar       *bb,*mask;
849:   Vec               xmask,lmask;
850:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ*)l->B->data;
851:   const PetscInt    *aj, *ii,*ridx;
852:   PetscScalar       *aa;

855:   /* Create SF where leaves are input rows and roots are owned rows */
856:   PetscMalloc1(n, &lrows);
857:   for (r = 0; r < n; ++r) lrows[r] = -1;
858:   PetscMalloc1(N, &rrows);
859:   for (r = 0; r < N; ++r) {
860:     const PetscInt idx   = rows[r];
861:     if (idx < 0 || A->rmap->N <= idx) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row %D out of range [0,%D)",idx,A->rmap->N);
862:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
863:       PetscLayoutFindOwner(A->rmap,idx,&p);
864:     }
865:     rrows[r].rank  = p;
866:     rrows[r].index = rows[r] - owners[p];
867:   }
868:   PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
869:   PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
870:   /* Collect flags for rows to be zeroed */
871:   PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
872:   PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
873:   PetscSFDestroy(&sf);
874:   /* Compress and put in row numbers */
875:   for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
876:   /* zero diagonal part of matrix */
877:   MatZeroRowsColumns(l->A,len,lrows,diag,x,b);
878:   /* handle off diagonal part of matrix */
879:   MatCreateVecs(A,&xmask,NULL);
880:   VecDuplicate(l->lvec,&lmask);
881:   VecGetArray(xmask,&bb);
882:   for (i=0; i<len; i++) bb[lrows[i]] = 1;
883:   VecRestoreArray(xmask,&bb);
884:   VecScatterBegin(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
885:   VecScatterEnd(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
886:   VecDestroy(&xmask);
887:   if (x) {
888:     VecScatterBegin(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
889:     VecScatterEnd(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
890:     VecGetArrayRead(l->lvec,&xx);
891:     VecGetArray(b,&bb);
892:   }
893:   VecGetArray(lmask,&mask);
894:   /* remove zeroed rows of off diagonal matrix */
895:   ii = aij->i;
896:   for (i=0; i<len; i++) {
897:     PetscMemzero(aij->a + ii[lrows[i]],(ii[lrows[i]+1] - ii[lrows[i]])*sizeof(PetscScalar));
898:   }
899:   /* loop over all elements of off process part of matrix zeroing removed columns*/
900:   if (aij->compressedrow.use) {
901:     m    = aij->compressedrow.nrows;
902:     ii   = aij->compressedrow.i;
903:     ridx = aij->compressedrow.rindex;
904:     for (i=0; i<m; i++) {
905:       n  = ii[i+1] - ii[i];
906:       aj = aij->j + ii[i];
907:       aa = aij->a + ii[i];

909:       for (j=0; j<n; j++) {
910:         if (PetscAbsScalar(mask[*aj])) {
911:           if (b) bb[*ridx] -= *aa*xx[*aj];
912:           *aa = 0.0;
913:         }
914:         aa++;
915:         aj++;
916:       }
917:       ridx++;
918:     }
919:   } else { /* do not use compressed row format */
920:     m = l->B->rmap->n;
921:     for (i=0; i<m; i++) {
922:       n  = ii[i+1] - ii[i];
923:       aj = aij->j + ii[i];
924:       aa = aij->a + ii[i];
925:       for (j=0; j<n; j++) {
926:         if (PetscAbsScalar(mask[*aj])) {
927:           if (b) bb[i] -= *aa*xx[*aj];
928:           *aa = 0.0;
929:         }
930:         aa++;
931:         aj++;
932:       }
933:     }
934:   }
935:   if (x) {
936:     VecRestoreArray(b,&bb);
937:     VecRestoreArrayRead(l->lvec,&xx);
938:   }
939:   VecRestoreArray(lmask,&mask);
940:   VecDestroy(&lmask);
941:   PetscFree(lrows);

943:   /* only change matrix nonzero state if pattern was allowed to be changed */
944:   if (!((Mat_SeqAIJ*)(l->A->data))->keepnonzeropattern) {
945:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
946:     MPI_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
947:   }
948:   return(0);
949: }

953: PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
954: {
955:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
957:   PetscInt       nt;

960:   VecGetLocalSize(xx,&nt);
961:   if (nt != A->cmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A (%D) and xx (%D)",A->cmap->n,nt);
962:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
963:   (*a->A->ops->mult)(a->A,xx,yy);
964:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
965:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
966:   return(0);
967: }

971: PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A,Vec bb,Vec xx)
972: {
973:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

977:   MatMultDiagonalBlock(a->A,bb,xx);
978:   return(0);
979: }

983: PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
984: {
985:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

989:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
990:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
991:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
992:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
993:   return(0);
994: }

998: PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
999: {
1000:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1002:   PetscBool      merged;

1005:   VecScatterGetMerged(a->Mvctx,&merged);
1006:   /* do nondiagonal part */
1007:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1008:   if (!merged) {
1009:     /* send it on its way */
1010:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1011:     /* do local part */
1012:     (*a->A->ops->multtranspose)(a->A,xx,yy);
1013:     /* receive remote parts: note this assumes the values are not actually */
1014:     /* added in yy until the next line, */
1015:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1016:   } else {
1017:     /* do local part */
1018:     (*a->A->ops->multtranspose)(a->A,xx,yy);
1019:     /* send it on its way */
1020:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1021:     /* values actually were received in the Begin() but we need to call this nop */
1022:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1023:   }
1024:   return(0);
1025: }

1029: PetscErrorCode  MatIsTranspose_MPIAIJ(Mat Amat,Mat Bmat,PetscReal tol,PetscBool  *f)
1030: {
1031:   MPI_Comm       comm;
1032:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ*) Amat->data, *Bij;
1033:   Mat            Adia = Aij->A, Bdia, Aoff,Boff,*Aoffs,*Boffs;
1034:   IS             Me,Notme;
1036:   PetscInt       M,N,first,last,*notme,i;
1037:   PetscMPIInt    size;

1040:   /* Easy test: symmetric diagonal block */
1041:   Bij  = (Mat_MPIAIJ*) Bmat->data; Bdia = Bij->A;
1042:   MatIsTranspose(Adia,Bdia,tol,f);
1043:   if (!*f) return(0);
1044:   PetscObjectGetComm((PetscObject)Amat,&comm);
1045:   MPI_Comm_size(comm,&size);
1046:   if (size == 1) return(0);

1048:   /* Hard test: off-diagonal block. This takes a MatGetSubMatrix. */
1049:   MatGetSize(Amat,&M,&N);
1050:   MatGetOwnershipRange(Amat,&first,&last);
1051:   PetscMalloc1((N-last+first),&notme);
1052:   for (i=0; i<first; i++) notme[i] = i;
1053:   for (i=last; i<M; i++) notme[i-last+first] = i;
1054:   ISCreateGeneral(MPI_COMM_SELF,N-last+first,notme,PETSC_COPY_VALUES,&Notme);
1055:   ISCreateStride(MPI_COMM_SELF,last-first,first,1,&Me);
1056:   MatGetSubMatrices(Amat,1,&Me,&Notme,MAT_INITIAL_MATRIX,&Aoffs);
1057:   Aoff = Aoffs[0];
1058:   MatGetSubMatrices(Bmat,1,&Notme,&Me,MAT_INITIAL_MATRIX,&Boffs);
1059:   Boff = Boffs[0];
1060:   MatIsTranspose(Aoff,Boff,tol,f);
1061:   MatDestroyMatrices(1,&Aoffs);
1062:   MatDestroyMatrices(1,&Boffs);
1063:   ISDestroy(&Me);
1064:   ISDestroy(&Notme);
1065:   PetscFree(notme);
1066:   return(0);
1067: }

1071: PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1072: {
1073:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1077:   /* do nondiagonal part */
1078:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1079:   /* send it on its way */
1080:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1081:   /* do local part */
1082:   (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
1083:   /* receive remote parts */
1084:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1085:   return(0);
1086: }

1088: /*
1089:   This only works correctly for square matrices where the subblock A->A is the
1090:    diagonal block
1091: */
1094: PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
1095: {
1097:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1100:   if (A->rmap->N != A->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1101:   if (A->rmap->rstart != A->cmap->rstart || A->rmap->rend != A->cmap->rend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"row partition must equal col partition");
1102:   MatGetDiagonal(a->A,v);
1103:   return(0);
1104: }

1108: PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
1109: {
1110:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1114:   MatScale(a->A,aa);
1115:   MatScale(a->B,aa);
1116:   return(0);
1117: }

1121: PetscErrorCode MatDestroy_Redundant(Mat_Redundant **redundant)
1122: {
1124:   Mat_Redundant  *redund = *redundant;
1125:   PetscInt       i;

1128:   *redundant = NULL;
1129:   if (redund){
1130:     if (redund->matseq) { /* via MatGetSubMatrices()  */
1131:       ISDestroy(&redund->isrow);
1132:       ISDestroy(&redund->iscol);
1133:       MatDestroy(&redund->matseq[0]);
1134:       PetscFree(redund->matseq);
1135:     } else {
1136:       PetscFree2(redund->send_rank,redund->recv_rank);
1137:       PetscFree(redund->sbuf_j);
1138:       PetscFree(redund->sbuf_a);
1139:       for (i=0; i<redund->nrecvs; i++) {
1140:         PetscFree(redund->rbuf_j[i]);
1141:         PetscFree(redund->rbuf_a[i]);
1142:       }
1143:       PetscFree4(redund->sbuf_nz,redund->rbuf_nz,redund->rbuf_j,redund->rbuf_a);
1144:     }

1146:     if (redund->psubcomm) {
1147:       PetscSubcommDestroy(&redund->psubcomm);
1148:     }
1149:     PetscFree(redund);
1150:   }
1151:   return(0);
1152: }

1156: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
1157: {
1158:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

1162: #if defined(PETSC_USE_LOG)
1163:   PetscLogObjectState((PetscObject)mat,"Rows=%D, Cols=%D",mat->rmap->N,mat->cmap->N);
1164: #endif
1165:   MatDestroy_Redundant(&aij->redundant);
1166:   MatStashDestroy_Private(&mat->stash);
1167:   VecDestroy(&aij->diag);
1168:   MatDestroy(&aij->A);
1169:   MatDestroy(&aij->B);
1170: #if defined(PETSC_USE_CTABLE)
1171:   PetscTableDestroy(&aij->colmap);
1172: #else
1173:   PetscFree(aij->colmap);
1174: #endif
1175:   PetscFree(aij->garray);
1176:   VecDestroy(&aij->lvec);
1177:   VecScatterDestroy(&aij->Mvctx);
1178:   PetscFree2(aij->rowvalues,aij->rowindices);
1179:   PetscFree(aij->ld);
1180:   PetscFree(mat->data);

1182:   PetscObjectChangeTypeName((PetscObject)mat,0);
1183:   PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);
1184:   PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);
1185:   PetscObjectComposeFunction((PetscObject)mat,"MatGetDiagonalBlock_C",NULL);
1186:   PetscObjectComposeFunction((PetscObject)mat,"MatIsTranspose_C",NULL);
1187:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocation_C",NULL);
1188:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocationCSR_C",NULL);
1189:   PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",NULL);
1190:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_mpisbaij_C",NULL);
1191: #if defined(PETSC_HAVE_ELEMENTAL)
1192:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_elemental_C",NULL);
1193: #endif
1194:   return(0);
1195: }

1199: PetscErrorCode MatView_MPIAIJ_Binary(Mat mat,PetscViewer viewer)
1200: {
1201:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
1202:   Mat_SeqAIJ     *A   = (Mat_SeqAIJ*)aij->A->data;
1203:   Mat_SeqAIJ     *B   = (Mat_SeqAIJ*)aij->B->data;
1205:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
1206:   int            fd;
1207:   PetscInt       nz,header[4],*row_lengths,*range=0,rlen,i;
1208:   PetscInt       nzmax,*column_indices,j,k,col,*garray = aij->garray,cnt,cstart = mat->cmap->rstart,rnz = 0;
1209:   PetscScalar    *column_values;
1210:   PetscInt       message_count,flowcontrolcount;
1211:   FILE           *file;

1214:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1215:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1216:   nz   = A->nz + B->nz;
1217:   if (!rank) {
1218:     header[0] = MAT_FILE_CLASSID;
1219:     header[1] = mat->rmap->N;
1220:     header[2] = mat->cmap->N;

1222:     MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1223:     PetscViewerBinaryGetDescriptor(viewer,&fd);
1224:     PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);
1225:     /* get largest number of rows any processor has */
1226:     rlen  = mat->rmap->n;
1227:     range = mat->rmap->range;
1228:     for (i=1; i<size; i++) rlen = PetscMax(rlen,range[i+1] - range[i]);
1229:   } else {
1230:     MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1231:     rlen = mat->rmap->n;
1232:   }

1234:   /* load up the local row counts */
1235:   PetscMalloc1((rlen+1),&row_lengths);
1236:   for (i=0; i<mat->rmap->n; i++) row_lengths[i] = A->i[i+1] - A->i[i] + B->i[i+1] - B->i[i];

1238:   /* store the row lengths to the file */
1239:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1240:   if (!rank) {
1241:     PetscBinaryWrite(fd,row_lengths,mat->rmap->n,PETSC_INT,PETSC_TRUE);
1242:     for (i=1; i<size; i++) {
1243:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1244:       rlen = range[i+1] - range[i];
1245:       MPIULong_Recv(row_lengths,rlen,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1246:       PetscBinaryWrite(fd,row_lengths,rlen,PETSC_INT,PETSC_TRUE);
1247:     }
1248:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1249:   } else {
1250:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1251:     MPIULong_Send(row_lengths,mat->rmap->n,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1252:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1253:   }
1254:   PetscFree(row_lengths);

1256:   /* load up the local column indices */
1257:   nzmax = nz; /* th processor needs space a largest processor needs */
1258:   MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,PetscObjectComm((PetscObject)mat));
1259:   PetscMalloc1((nzmax+1),&column_indices);
1260:   cnt   = 0;
1261:   for (i=0; i<mat->rmap->n; i++) {
1262:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1263:       if ((col = garray[B->j[j]]) > cstart) break;
1264:       column_indices[cnt++] = col;
1265:     }
1266:     for (k=A->i[i]; k<A->i[i+1]; k++) column_indices[cnt++] = A->j[k] + cstart;
1267:     for (; j<B->i[i+1]; j++) column_indices[cnt++] = garray[B->j[j]];
1268:   }
1269:   if (cnt != A->nz + B->nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);

1271:   /* store the column indices to the file */
1272:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1273:   if (!rank) {
1274:     MPI_Status status;
1275:     PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);
1276:     for (i=1; i<size; i++) {
1277:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1278:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1279:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1280:       MPIULong_Recv(column_indices,rnz,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1281:       PetscBinaryWrite(fd,column_indices,rnz,PETSC_INT,PETSC_TRUE);
1282:     }
1283:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1284:   } else {
1285:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1286:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1287:     MPIULong_Send(column_indices,nz,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1288:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1289:   }
1290:   PetscFree(column_indices);

1292:   /* load up the local column values */
1293:   PetscMalloc1((nzmax+1),&column_values);
1294:   cnt  = 0;
1295:   for (i=0; i<mat->rmap->n; i++) {
1296:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1297:       if (garray[B->j[j]] > cstart) break;
1298:       column_values[cnt++] = B->a[j];
1299:     }
1300:     for (k=A->i[i]; k<A->i[i+1]; k++) column_values[cnt++] = A->a[k];
1301:     for (; j<B->i[i+1]; j++) column_values[cnt++] = B->a[j];
1302:   }
1303:   if (cnt != A->nz + B->nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal PETSc error: cnt = %D nz = %D",cnt,A->nz+B->nz);

1305:   /* store the column values to the file */
1306:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1307:   if (!rank) {
1308:     MPI_Status status;
1309:     PetscBinaryWrite(fd,column_values,nz,PETSC_SCALAR,PETSC_TRUE);
1310:     for (i=1; i<size; i++) {
1311:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1312:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1313:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1314:       MPIULong_Recv(column_values,rnz,MPIU_SCALAR,i,tag,PetscObjectComm((PetscObject)mat));
1315:       PetscBinaryWrite(fd,column_values,rnz,PETSC_SCALAR,PETSC_TRUE);
1316:     }
1317:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1318:   } else {
1319:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1320:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1321:     MPIULong_Send(column_values,nz,MPIU_SCALAR,0,tag,PetscObjectComm((PetscObject)mat));
1322:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1323:   }
1324:   PetscFree(column_values);

1326:   PetscViewerBinaryGetInfoPointer(viewer,&file);
1327:   if (file) fprintf(file,"-matload_block_size %d\n",(int)PetscAbs(mat->rmap->bs));
1328:   return(0);
1329: }

1331: #include <petscdraw.h>
1334: PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1335: {
1336:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*)mat->data;
1337:   PetscErrorCode    ierr;
1338:   PetscMPIInt       rank = aij->rank,size = aij->size;
1339:   PetscBool         isdraw,iascii,isbinary;
1340:   PetscViewer       sviewer;
1341:   PetscViewerFormat format;

1344:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1345:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1346:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1347:   if (iascii) {
1348:     PetscViewerGetFormat(viewer,&format);
1349:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1350:       MatInfo   info;
1351:       PetscBool inodes;

1353:       MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1354:       MatGetInfo(mat,MAT_LOCAL,&info);
1355:       MatInodeGetInodeSizes(aij->A,NULL,(PetscInt**)&inodes,NULL);
1356:       PetscViewerASCIISynchronizedAllow(viewer,PETSC_TRUE);
1357:       if (!inodes) {
1358:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, not using I-node routines\n",
1359:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1360:       } else {
1361:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, using I-node routines\n",
1362:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1363:       }
1364:       MatGetInfo(aij->A,MAT_LOCAL,&info);
1365:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1366:       MatGetInfo(aij->B,MAT_LOCAL,&info);
1367:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1368:       PetscViewerFlush(viewer);
1369:       PetscViewerASCIISynchronizedAllow(viewer,PETSC_FALSE);
1370:       PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
1371:       VecScatterView(aij->Mvctx,viewer);
1372:       return(0);
1373:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1374:       PetscInt inodecount,inodelimit,*inodes;
1375:       MatInodeGetInodeSizes(aij->A,&inodecount,&inodes,&inodelimit);
1376:       if (inodes) {
1377:         PetscViewerASCIIPrintf(viewer,"using I-node (on process 0) routines: found %D nodes, limit used is %D\n",inodecount,inodelimit);
1378:       } else {
1379:         PetscViewerASCIIPrintf(viewer,"not using I-node (on process 0) routines\n");
1380:       }
1381:       return(0);
1382:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1383:       return(0);
1384:     }
1385:   } else if (isbinary) {
1386:     if (size == 1) {
1387:       PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1388:       MatView(aij->A,viewer);
1389:     } else {
1390:       MatView_MPIAIJ_Binary(mat,viewer);
1391:     }
1392:     return(0);
1393:   } else if (isdraw) {
1394:     PetscDraw draw;
1395:     PetscBool isnull;
1396:     PetscViewerDrawGetDraw(viewer,0,&draw);
1397:     PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
1398:   }

1400:   {
1401:     /* assemble the entire matrix onto first processor. */
1402:     Mat        A;
1403:     Mat_SeqAIJ *Aloc;
1404:     PetscInt   M = mat->rmap->N,N = mat->cmap->N,m,*ai,*aj,row,*cols,i,*ct;
1405:     MatScalar  *a;

1407:     MatCreate(PetscObjectComm((PetscObject)mat),&A);
1408:     if (!rank) {
1409:       MatSetSizes(A,M,N,M,N);
1410:     } else {
1411:       MatSetSizes(A,0,0,M,N);
1412:     }
1413:     /* This is just a temporary matrix, so explicitly using MATMPIAIJ is probably best */
1414:     MatSetType(A,MATMPIAIJ);
1415:     MatMPIAIJSetPreallocation(A,0,NULL,0,NULL);
1416:     MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
1417:     PetscLogObjectParent((PetscObject)mat,(PetscObject)A);

1419:     /* copy over the A part */
1420:     Aloc = (Mat_SeqAIJ*)aij->A->data;
1421:     m    = aij->A->rmap->n; ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1422:     row  = mat->rmap->rstart;
1423:     for (i=0; i<ai[m]; i++) aj[i] += mat->cmap->rstart;
1424:     for (i=0; i<m; i++) {
1425:       MatSetValues(A,1,&row,ai[i+1]-ai[i],aj,a,INSERT_VALUES);
1426:       row++;
1427:       a += ai[i+1]-ai[i]; aj += ai[i+1]-ai[i];
1428:     }
1429:     aj = Aloc->j;
1430:     for (i=0; i<ai[m]; i++) aj[i] -= mat->cmap->rstart;

1432:     /* copy over the B part */
1433:     Aloc = (Mat_SeqAIJ*)aij->B->data;
1434:     m    = aij->B->rmap->n;  ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1435:     row  = mat->rmap->rstart;
1436:     PetscMalloc1((ai[m]+1),&cols);
1437:     ct   = cols;
1438:     for (i=0; i<ai[m]; i++) cols[i] = aij->garray[aj[i]];
1439:     for (i=0; i<m; i++) {
1440:       MatSetValues(A,1,&row,ai[i+1]-ai[i],cols,a,INSERT_VALUES);
1441:       row++;
1442:       a += ai[i+1]-ai[i]; cols += ai[i+1]-ai[i];
1443:     }
1444:     PetscFree(ct);
1445:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1446:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1447:     /*
1448:        Everyone has to call to draw the matrix since the graphics waits are
1449:        synchronized across all processors that share the PetscDraw object
1450:     */
1451:     PetscViewerGetSingleton(viewer,&sviewer);
1452:     if (!rank) {
1453:       MatView_SeqAIJ(((Mat_MPIAIJ*)(A->data))->A,sviewer);
1454:     }
1455:     PetscViewerRestoreSingleton(viewer,&sviewer);
1456:     MatDestroy(&A);
1457:   }
1458:   return(0);
1459: }

1463: PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1464: {
1466:   PetscBool      iascii,isdraw,issocket,isbinary;

1469:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1470:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1471:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1472:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
1473:   if (iascii || isdraw || isbinary || issocket) {
1474:     MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);
1475:   }
1476:   return(0);
1477: }

1481: PetscErrorCode MatSOR_MPIAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1482: {
1483:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1485:   Vec            bb1 = 0;
1486:   PetscBool      hasop;

1489:   if (flag == SOR_APPLY_UPPER) {
1490:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1491:     return(0);
1492:   }

1494:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) {
1495:     VecDuplicate(bb,&bb1);
1496:   }

1498:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1499:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1500:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1501:       its--;
1502:     }

1504:     while (its--) {
1505:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1506:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1508:       /* update rhs: bb1 = bb - B*x */
1509:       VecScale(mat->lvec,-1.0);
1510:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1512:       /* local sweep */
1513:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,1,xx);
1514:     }
1515:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1516:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1517:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1518:       its--;
1519:     }
1520:     while (its--) {
1521:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1522:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1524:       /* update rhs: bb1 = bb - B*x */
1525:       VecScale(mat->lvec,-1.0);
1526:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1528:       /* local sweep */
1529:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,1,xx);
1530:     }
1531:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1532:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1533:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1534:       its--;
1535:     }
1536:     while (its--) {
1537:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1538:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1540:       /* update rhs: bb1 = bb - B*x */
1541:       VecScale(mat->lvec,-1.0);
1542:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1544:       /* local sweep */
1545:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);
1546:     }
1547:   } else if (flag & SOR_EISENSTAT) {
1548:     Vec xx1;

1550:     VecDuplicate(bb,&xx1);
1551:     (*mat->A->ops->sor)(mat->A,bb,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP),fshift,lits,1,xx);

1553:     VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1554:     VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1555:     if (!mat->diag) {
1556:       MatCreateVecs(matin,&mat->diag,NULL);
1557:       MatGetDiagonal(matin,mat->diag);
1558:     }
1559:     MatHasOperation(matin,MATOP_MULT_DIAGONAL_BLOCK,&hasop);
1560:     if (hasop) {
1561:       MatMultDiagonalBlock(matin,xx,bb1);
1562:     } else {
1563:       VecPointwiseMult(bb1,mat->diag,xx);
1564:     }
1565:     VecAYPX(bb1,(omega-2.0)/omega,bb);

1567:     MatMultAdd(mat->B,mat->lvec,bb1,bb1);

1569:     /* local sweep */
1570:     (*mat->A->ops->sor)(mat->A,bb1,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP),fshift,lits,1,xx1);
1571:     VecAXPY(xx,1.0,xx1);
1572:     VecDestroy(&xx1);
1573:   } else SETERRQ(PetscObjectComm((PetscObject)matin),PETSC_ERR_SUP,"Parallel SOR not supported");

1575:   VecDestroy(&bb1);
1576:   return(0);
1577: }

1581: PetscErrorCode MatPermute_MPIAIJ(Mat A,IS rowp,IS colp,Mat *B)
1582: {
1583:   Mat            aA,aB,Aperm;
1584:   const PetscInt *rwant,*cwant,*gcols,*ai,*bi,*aj,*bj;
1585:   PetscScalar    *aa,*ba;
1586:   PetscInt       i,j,m,n,ng,anz,bnz,*dnnz,*onnz,*tdnnz,*tonnz,*rdest,*cdest,*work,*gcdest;
1587:   PetscSF        rowsf,sf;
1588:   IS             parcolp = NULL;
1589:   PetscBool      done;

1593:   MatGetLocalSize(A,&m,&n);
1594:   ISGetIndices(rowp,&rwant);
1595:   ISGetIndices(colp,&cwant);
1596:   PetscMalloc3(PetscMax(m,n),&work,m,&rdest,n,&cdest);

1598:   /* Invert row permutation to find out where my rows should go */
1599:   PetscSFCreate(PetscObjectComm((PetscObject)A),&rowsf);
1600:   PetscSFSetGraphLayout(rowsf,A->rmap,A->rmap->n,NULL,PETSC_OWN_POINTER,rwant);
1601:   PetscSFSetFromOptions(rowsf);
1602:   for (i=0; i<m; i++) work[i] = A->rmap->rstart + i;
1603:   PetscSFReduceBegin(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);
1604:   PetscSFReduceEnd(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);

1606:   /* Invert column permutation to find out where my columns should go */
1607:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1608:   PetscSFSetGraphLayout(sf,A->cmap,A->cmap->n,NULL,PETSC_OWN_POINTER,cwant);
1609:   PetscSFSetFromOptions(sf);
1610:   for (i=0; i<n; i++) work[i] = A->cmap->rstart + i;
1611:   PetscSFReduceBegin(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1612:   PetscSFReduceEnd(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1613:   PetscSFDestroy(&sf);

1615:   ISRestoreIndices(rowp,&rwant);
1616:   ISRestoreIndices(colp,&cwant);
1617:   MatMPIAIJGetSeqAIJ(A,&aA,&aB,&gcols);

1619:   /* Find out where my gcols should go */
1620:   MatGetSize(aB,NULL,&ng);
1621:   PetscMalloc1(ng,&gcdest);
1622:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1623:   PetscSFSetGraphLayout(sf,A->cmap,ng,NULL,PETSC_OWN_POINTER,gcols);
1624:   PetscSFSetFromOptions(sf);
1625:   PetscSFBcastBegin(sf,MPIU_INT,cdest,gcdest);
1626:   PetscSFBcastEnd(sf,MPIU_INT,cdest,gcdest);
1627:   PetscSFDestroy(&sf);

1629:   PetscCalloc4(m,&dnnz,m,&onnz,m,&tdnnz,m,&tonnz);
1630:   MatGetRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1631:   MatGetRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1632:   for (i=0; i<m; i++) {
1633:     PetscInt row = rdest[i],rowner;
1634:     PetscLayoutFindOwner(A->rmap,row,&rowner);
1635:     for (j=ai[i]; j<ai[i+1]; j++) {
1636:       PetscInt cowner,col = cdest[aj[j]];
1637:       PetscLayoutFindOwner(A->cmap,col,&cowner); /* Could build an index for the columns to eliminate this search */
1638:       if (rowner == cowner) dnnz[i]++;
1639:       else onnz[i]++;
1640:     }
1641:     for (j=bi[i]; j<bi[i+1]; j++) {
1642:       PetscInt cowner,col = gcdest[bj[j]];
1643:       PetscLayoutFindOwner(A->cmap,col,&cowner);
1644:       if (rowner == cowner) dnnz[i]++;
1645:       else onnz[i]++;
1646:     }
1647:   }
1648:   PetscSFBcastBegin(rowsf,MPIU_INT,dnnz,tdnnz);
1649:   PetscSFBcastEnd(rowsf,MPIU_INT,dnnz,tdnnz);
1650:   PetscSFBcastBegin(rowsf,MPIU_INT,onnz,tonnz);
1651:   PetscSFBcastEnd(rowsf,MPIU_INT,onnz,tonnz);
1652:   PetscSFDestroy(&rowsf);

1654:   MatCreateAIJ(PetscObjectComm((PetscObject)A),A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N,0,tdnnz,0,tonnz,&Aperm);
1655:   MatSeqAIJGetArray(aA,&aa);
1656:   MatSeqAIJGetArray(aB,&ba);
1657:   for (i=0; i<m; i++) {
1658:     PetscInt *acols = dnnz,*bcols = onnz; /* Repurpose now-unneeded arrays */
1659:     PetscInt j0,rowlen;
1660:     rowlen = ai[i+1] - ai[i];
1661:     for (j0=j=0; j<rowlen; j0=j) { /* rowlen could be larger than number of rows m, so sum in batches */
1662:       for ( ; j<PetscMin(rowlen,j0+m); j++) acols[j-j0] = cdest[aj[ai[i]+j]];
1663:       MatSetValues(Aperm,1,&rdest[i],j-j0,acols,aa+ai[i]+j0,INSERT_VALUES);
1664:     }
1665:     rowlen = bi[i+1] - bi[i];
1666:     for (j0=j=0; j<rowlen; j0=j) {
1667:       for ( ; j<PetscMin(rowlen,j0+m); j++) bcols[j-j0] = gcdest[bj[bi[i]+j]];
1668:       MatSetValues(Aperm,1,&rdest[i],j-j0,bcols,ba+bi[i]+j0,INSERT_VALUES);
1669:     }
1670:   }
1671:   MatAssemblyBegin(Aperm,MAT_FINAL_ASSEMBLY);
1672:   MatAssemblyEnd(Aperm,MAT_FINAL_ASSEMBLY);
1673:   MatRestoreRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1674:   MatRestoreRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1675:   MatSeqAIJRestoreArray(aA,&aa);
1676:   MatSeqAIJRestoreArray(aB,&ba);
1677:   PetscFree4(dnnz,onnz,tdnnz,tonnz);
1678:   PetscFree3(work,rdest,cdest);
1679:   PetscFree(gcdest);
1680:   if (parcolp) {ISDestroy(&colp);}
1681:   *B = Aperm;
1682:   return(0);
1683: }

1687: PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1688: {
1689:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1690:   Mat            A    = mat->A,B = mat->B;
1692:   PetscReal      isend[5],irecv[5];

1695:   info->block_size = 1.0;
1696:   MatGetInfo(A,MAT_LOCAL,info);

1698:   isend[0] = info->nz_used; isend[1] = info->nz_allocated; isend[2] = info->nz_unneeded;
1699:   isend[3] = info->memory;  isend[4] = info->mallocs;

1701:   MatGetInfo(B,MAT_LOCAL,info);

1703:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1704:   isend[3] += info->memory;  isend[4] += info->mallocs;
1705:   if (flag == MAT_LOCAL) {
1706:     info->nz_used      = isend[0];
1707:     info->nz_allocated = isend[1];
1708:     info->nz_unneeded  = isend[2];
1709:     info->memory       = isend[3];
1710:     info->mallocs      = isend[4];
1711:   } else if (flag == MAT_GLOBAL_MAX) {
1712:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

1714:     info->nz_used      = irecv[0];
1715:     info->nz_allocated = irecv[1];
1716:     info->nz_unneeded  = irecv[2];
1717:     info->memory       = irecv[3];
1718:     info->mallocs      = irecv[4];
1719:   } else if (flag == MAT_GLOBAL_SUM) {
1720:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));

1722:     info->nz_used      = irecv[0];
1723:     info->nz_allocated = irecv[1];
1724:     info->nz_unneeded  = irecv[2];
1725:     info->memory       = irecv[3];
1726:     info->mallocs      = irecv[4];
1727:   }
1728:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1729:   info->fill_ratio_needed = 0;
1730:   info->factor_mallocs    = 0;
1731:   return(0);
1732: }

1736: PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscBool flg)
1737: {
1738:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1742:   switch (op) {
1743:   case MAT_NEW_NONZERO_LOCATIONS:
1744:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1745:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1746:   case MAT_KEEP_NONZERO_PATTERN:
1747:   case MAT_NEW_NONZERO_LOCATION_ERR:
1748:   case MAT_USE_INODES:
1749:   case MAT_IGNORE_ZERO_ENTRIES:
1750:     MatCheckPreallocated(A,1);
1751:     MatSetOption(a->A,op,flg);
1752:     MatSetOption(a->B,op,flg);
1753:     break;
1754:   case MAT_ROW_ORIENTED:
1755:     a->roworiented = flg;

1757:     MatSetOption(a->A,op,flg);
1758:     MatSetOption(a->B,op,flg);
1759:     break;
1760:   case MAT_NEW_DIAGONALS:
1761:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1762:     break;
1763:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1764:     a->donotstash = flg;
1765:     break;
1766:   case MAT_SPD:
1767:     A->spd_set = PETSC_TRUE;
1768:     A->spd     = flg;
1769:     if (flg) {
1770:       A->symmetric                  = PETSC_TRUE;
1771:       A->structurally_symmetric     = PETSC_TRUE;
1772:       A->symmetric_set              = PETSC_TRUE;
1773:       A->structurally_symmetric_set = PETSC_TRUE;
1774:     }
1775:     break;
1776:   case MAT_SYMMETRIC:
1777:     MatSetOption(a->A,op,flg);
1778:     break;
1779:   case MAT_STRUCTURALLY_SYMMETRIC:
1780:     MatSetOption(a->A,op,flg);
1781:     break;
1782:   case MAT_HERMITIAN:
1783:     MatSetOption(a->A,op,flg);
1784:     break;
1785:   case MAT_SYMMETRY_ETERNAL:
1786:     MatSetOption(a->A,op,flg);
1787:     break;
1788:   default:
1789:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1790:   }
1791:   return(0);
1792: }

1796: PetscErrorCode MatGetRow_MPIAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1797: {
1798:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1799:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
1801:   PetscInt       i,*cworkA,*cworkB,**pcA,**pcB,cstart = matin->cmap->rstart;
1802:   PetscInt       nztot,nzA,nzB,lrow,rstart = matin->rmap->rstart,rend = matin->rmap->rend;
1803:   PetscInt       *cmap,*idx_p;

1806:   if (mat->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Already active");
1807:   mat->getrowactive = PETSC_TRUE;

1809:   if (!mat->rowvalues && (idx || v)) {
1810:     /*
1811:         allocate enough space to hold information from the longest row.
1812:     */
1813:     Mat_SeqAIJ *Aa = (Mat_SeqAIJ*)mat->A->data,*Ba = (Mat_SeqAIJ*)mat->B->data;
1814:     PetscInt   max = 1,tmp;
1815:     for (i=0; i<matin->rmap->n; i++) {
1816:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
1817:       if (max < tmp) max = tmp;
1818:     }
1819:     PetscMalloc2(max,&mat->rowvalues,max,&mat->rowindices);
1820:   }

1822:   if (row < rstart || row >= rend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only local rows");
1823:   lrow = row - rstart;

1825:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1826:   if (!v)   {pvA = 0; pvB = 0;}
1827:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1828:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1829:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1830:   nztot = nzA + nzB;

1832:   cmap = mat->garray;
1833:   if (v  || idx) {
1834:     if (nztot) {
1835:       /* Sort by increasing column numbers, assuming A and B already sorted */
1836:       PetscInt imark = -1;
1837:       if (v) {
1838:         *v = v_p = mat->rowvalues;
1839:         for (i=0; i<nzB; i++) {
1840:           if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1841:           else break;
1842:         }
1843:         imark = i;
1844:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1845:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1846:       }
1847:       if (idx) {
1848:         *idx = idx_p = mat->rowindices;
1849:         if (imark > -1) {
1850:           for (i=0; i<imark; i++) {
1851:             idx_p[i] = cmap[cworkB[i]];
1852:           }
1853:         } else {
1854:           for (i=0; i<nzB; i++) {
1855:             if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1856:             else break;
1857:           }
1858:           imark = i;
1859:         }
1860:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart + cworkA[i];
1861:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]];
1862:       }
1863:     } else {
1864:       if (idx) *idx = 0;
1865:       if (v)   *v   = 0;
1866:     }
1867:   }
1868:   *nz  = nztot;
1869:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1870:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1871:   return(0);
1872: }

1876: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1877: {
1878:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1881:   if (!aij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1882:   aij->getrowactive = PETSC_FALSE;
1883:   return(0);
1884: }

1888: PetscErrorCode MatNorm_MPIAIJ(Mat mat,NormType type,PetscReal *norm)
1889: {
1890:   Mat_MPIAIJ     *aij  = (Mat_MPIAIJ*)mat->data;
1891:   Mat_SeqAIJ     *amat = (Mat_SeqAIJ*)aij->A->data,*bmat = (Mat_SeqAIJ*)aij->B->data;
1893:   PetscInt       i,j,cstart = mat->cmap->rstart;
1894:   PetscReal      sum = 0.0;
1895:   MatScalar      *v;

1898:   if (aij->size == 1) {
1899:      MatNorm(aij->A,type,norm);
1900:   } else {
1901:     if (type == NORM_FROBENIUS) {
1902:       v = amat->a;
1903:       for (i=0; i<amat->nz; i++) {
1904:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1905:       }
1906:       v = bmat->a;
1907:       for (i=0; i<bmat->nz; i++) {
1908:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1909:       }
1910:       MPI_Allreduce(&sum,norm,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1911:       *norm = PetscSqrtReal(*norm);
1912:     } else if (type == NORM_1) { /* max column norm */
1913:       PetscReal *tmp,*tmp2;
1914:       PetscInt  *jj,*garray = aij->garray;
1915:       PetscCalloc1((mat->cmap->N+1),&tmp);
1916:       PetscMalloc1((mat->cmap->N+1),&tmp2);
1917:       *norm = 0.0;
1918:       v     = amat->a; jj = amat->j;
1919:       for (j=0; j<amat->nz; j++) {
1920:         tmp[cstart + *jj++] += PetscAbsScalar(*v);  v++;
1921:       }
1922:       v = bmat->a; jj = bmat->j;
1923:       for (j=0; j<bmat->nz; j++) {
1924:         tmp[garray[*jj++]] += PetscAbsScalar(*v); v++;
1925:       }
1926:       MPI_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1927:       for (j=0; j<mat->cmap->N; j++) {
1928:         if (tmp2[j] > *norm) *norm = tmp2[j];
1929:       }
1930:       PetscFree(tmp);
1931:       PetscFree(tmp2);
1932:     } else if (type == NORM_INFINITY) { /* max row norm */
1933:       PetscReal ntemp = 0.0;
1934:       for (j=0; j<aij->A->rmap->n; j++) {
1935:         v   = amat->a + amat->i[j];
1936:         sum = 0.0;
1937:         for (i=0; i<amat->i[j+1]-amat->i[j]; i++) {
1938:           sum += PetscAbsScalar(*v); v++;
1939:         }
1940:         v = bmat->a + bmat->i[j];
1941:         for (i=0; i<bmat->i[j+1]-bmat->i[j]; i++) {
1942:           sum += PetscAbsScalar(*v); v++;
1943:         }
1944:         if (sum > ntemp) ntemp = sum;
1945:       }
1946:       MPI_Allreduce(&ntemp,norm,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)mat));
1947:     } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No support for two norm");
1948:   }
1949:   return(0);
1950: }

1954: PetscErrorCode MatTranspose_MPIAIJ(Mat A,MatReuse reuse,Mat *matout)
1955: {
1956:   Mat_MPIAIJ     *a   = (Mat_MPIAIJ*)A->data;
1957:   Mat_SeqAIJ     *Aloc=(Mat_SeqAIJ*)a->A->data,*Bloc=(Mat_SeqAIJ*)a->B->data;
1959:   PetscInt       M      = A->rmap->N,N = A->cmap->N,ma,na,mb,nb,*ai,*aj,*bi,*bj,row,*cols,*cols_tmp,i;
1960:   PetscInt       cstart = A->cmap->rstart,ncol;
1961:   Mat            B;
1962:   MatScalar      *array;

1965:   if (reuse == MAT_REUSE_MATRIX && A == *matout && M != N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Square matrix only for in-place");

1967:   ma = A->rmap->n; na = A->cmap->n; mb = a->B->rmap->n; nb = a->B->cmap->n;
1968:   ai = Aloc->i; aj = Aloc->j;
1969:   bi = Bloc->i; bj = Bloc->j;
1970:   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1971:     PetscInt             *d_nnz,*g_nnz,*o_nnz;
1972:     PetscSFNode          *oloc;
1973:     PETSC_UNUSED PetscSF sf;

1975:     PetscMalloc4(na,&d_nnz,na,&o_nnz,nb,&g_nnz,nb,&oloc);
1976:     /* compute d_nnz for preallocation */
1977:     PetscMemzero(d_nnz,na*sizeof(PetscInt));
1978:     for (i=0; i<ai[ma]; i++) {
1979:       d_nnz[aj[i]]++;
1980:       aj[i] += cstart; /* global col index to be used by MatSetValues() */
1981:     }
1982:     /* compute local off-diagonal contributions */
1983:     PetscMemzero(g_nnz,nb*sizeof(PetscInt));
1984:     for (i=0; i<bi[ma]; i++) g_nnz[bj[i]]++;
1985:     /* map those to global */
1986:     PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1987:     PetscSFSetGraphLayout(sf,A->cmap,nb,NULL,PETSC_USE_POINTER,a->garray);
1988:     PetscSFSetFromOptions(sf);
1989:     PetscMemzero(o_nnz,na*sizeof(PetscInt));
1990:     PetscSFReduceBegin(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
1991:     PetscSFReduceEnd(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
1992:     PetscSFDestroy(&sf);

1994:     MatCreate(PetscObjectComm((PetscObject)A),&B);
1995:     MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);
1996:     MatSetBlockSizes(B,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
1997:     MatSetType(B,((PetscObject)A)->type_name);
1998:     MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
1999:     PetscFree4(d_nnz,o_nnz,g_nnz,oloc);
2000:   } else {
2001:     B    = *matout;
2002:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
2003:     for (i=0; i<ai[ma]; i++) aj[i] += cstart; /* global col index to be used by MatSetValues() */
2004:   }

2006:   /* copy over the A part */
2007:   array = Aloc->a;
2008:   row   = A->rmap->rstart;
2009:   for (i=0; i<ma; i++) {
2010:     ncol = ai[i+1]-ai[i];
2011:     MatSetValues(B,ncol,aj,1,&row,array,INSERT_VALUES);
2012:     row++;
2013:     array += ncol; aj += ncol;
2014:   }
2015:   aj = Aloc->j;
2016:   for (i=0; i<ai[ma]; i++) aj[i] -= cstart; /* resume local col index */

2018:   /* copy over the B part */
2019:   PetscCalloc1(bi[mb],&cols);
2020:   array = Bloc->a;
2021:   row   = A->rmap->rstart;
2022:   for (i=0; i<bi[mb]; i++) cols[i] = a->garray[bj[i]];
2023:   cols_tmp = cols;
2024:   for (i=0; i<mb; i++) {
2025:     ncol = bi[i+1]-bi[i];
2026:     MatSetValues(B,ncol,cols_tmp,1,&row,array,INSERT_VALUES);
2027:     row++;
2028:     array += ncol; cols_tmp += ncol;
2029:   }
2030:   PetscFree(cols);

2032:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2033:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2034:   if (reuse == MAT_INITIAL_MATRIX || *matout != A) {
2035:     *matout = B;
2036:   } else {
2037:     MatHeaderMerge(A,B);
2038:   }
2039:   return(0);
2040: }

2044: PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat,Vec ll,Vec rr)
2045: {
2046:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
2047:   Mat            a    = aij->A,b = aij->B;
2049:   PetscInt       s1,s2,s3;

2052:   MatGetLocalSize(mat,&s2,&s3);
2053:   if (rr) {
2054:     VecGetLocalSize(rr,&s1);
2055:     if (s1!=s3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
2056:     /* Overlap communication with computation. */
2057:     VecScatterBegin(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
2058:   }
2059:   if (ll) {
2060:     VecGetLocalSize(ll,&s1);
2061:     if (s1!=s2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
2062:     (*b->ops->diagonalscale)(b,ll,0);
2063:   }
2064:   /* scale  the diagonal block */
2065:   (*a->ops->diagonalscale)(a,ll,rr);

2067:   if (rr) {
2068:     /* Do a scatter end and then right scale the off-diagonal block */
2069:     VecScatterEnd(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
2070:     (*b->ops->diagonalscale)(b,0,aij->lvec);
2071:   }
2072:   return(0);
2073: }

2077: PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2078: {
2079:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2083:   MatSetUnfactored(a->A);
2084:   return(0);
2085: }

2089: PetscErrorCode MatEqual_MPIAIJ(Mat A,Mat B,PetscBool  *flag)
2090: {
2091:   Mat_MPIAIJ     *matB = (Mat_MPIAIJ*)B->data,*matA = (Mat_MPIAIJ*)A->data;
2092:   Mat            a,b,c,d;
2093:   PetscBool      flg;

2097:   a = matA->A; b = matA->B;
2098:   c = matB->A; d = matB->B;

2100:   MatEqual(a,c,&flg);
2101:   if (flg) {
2102:     MatEqual(b,d,&flg);
2103:   }
2104:   MPI_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2105:   return(0);
2106: }

2110: PetscErrorCode MatCopy_MPIAIJ(Mat A,Mat B,MatStructure str)
2111: {
2113:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2114:   Mat_MPIAIJ     *b = (Mat_MPIAIJ*)B->data;

2117:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2118:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2119:     /* because of the column compression in the off-processor part of the matrix a->B,
2120:        the number of columns in a->B and b->B may be different, hence we cannot call
2121:        the MatCopy() directly on the two parts. If need be, we can provide a more
2122:        efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2123:        then copying the submatrices */
2124:     MatCopy_Basic(A,B,str);
2125:   } else {
2126:     MatCopy(a->A,b->A,str);
2127:     MatCopy(a->B,b->B,str);
2128:   }
2129:   return(0);
2130: }

2134: PetscErrorCode MatSetUp_MPIAIJ(Mat A)
2135: {

2139:    MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
2140:   return(0);
2141: }

2143: /*
2144:    Computes the number of nonzeros per row needed for preallocation when X and Y
2145:    have different nonzero structure.
2146: */
2149: PetscErrorCode MatAXPYGetPreallocation_MPIX_private(PetscInt m,const PetscInt *xi,const PetscInt *xj,const PetscInt *xltog,const PetscInt *yi,const PetscInt *yj,const PetscInt *yltog,PetscInt *nnz)
2150: {
2151:   PetscInt       i,j,k,nzx,nzy;

2154:   /* Set the number of nonzeros in the new matrix */
2155:   for (i=0; i<m; i++) {
2156:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
2157:     nzx = xi[i+1] - xi[i];
2158:     nzy = yi[i+1] - yi[i];
2159:     nnz[i] = 0;
2160:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
2161:       for (; k<nzy && yltog[yjj[k]]<xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2162:       if (k<nzy && yltog[yjj[k]]==xltog[xjj[j]]) k++;             /* Skip duplicate */
2163:       nnz[i]++;
2164:     }
2165:     for (; k<nzy; k++) nnz[i]++;
2166:   }
2167:   return(0);
2168: }

2170: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2173: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y,const PetscInt *yltog,Mat X,const PetscInt *xltog,PetscInt *nnz)
2174: {
2176:   PetscInt       m = Y->rmap->N;
2177:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
2178:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

2181:   MatAXPYGetPreallocation_MPIX_private(m,x->i,x->j,xltog,y->i,y->j,yltog,nnz);
2182:   return(0);
2183: }

2187: PetscErrorCode MatAXPY_MPIAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2188: {
2190:   PetscInt       i;
2191:   Mat_MPIAIJ     *xx = (Mat_MPIAIJ*)X->data,*yy = (Mat_MPIAIJ*)Y->data;
2192:   PetscBLASInt   bnz,one=1;
2193:   Mat_SeqAIJ     *x,*y;

2196:   if (str == SAME_NONZERO_PATTERN) {
2197:     PetscScalar alpha = a;
2198:     x    = (Mat_SeqAIJ*)xx->A->data;
2199:     PetscBLASIntCast(x->nz,&bnz);
2200:     y    = (Mat_SeqAIJ*)yy->A->data;
2201:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2202:     x    = (Mat_SeqAIJ*)xx->B->data;
2203:     y    = (Mat_SeqAIJ*)yy->B->data;
2204:     PetscBLASIntCast(x->nz,&bnz);
2205:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2206:     PetscObjectStateIncrease((PetscObject)Y);
2207:   } else if (str == SUBSET_NONZERO_PATTERN) {
2208:     MatAXPY_SeqAIJ(yy->A,a,xx->A,str);

2210:     x = (Mat_SeqAIJ*)xx->B->data;
2211:     y = (Mat_SeqAIJ*)yy->B->data;
2212:     if (y->xtoy && y->XtoY != xx->B) {
2213:       PetscFree(y->xtoy);
2214:       MatDestroy(&y->XtoY);
2215:     }
2216:     if (!y->xtoy) { /* get xtoy */
2217:       MatAXPYGetxtoy_Private(xx->B->rmap->n,x->i,x->j,xx->garray,y->i,y->j,yy->garray,&y->xtoy);
2218:       y->XtoY = xx->B;
2219:       PetscObjectReference((PetscObject)xx->B);
2220:     }
2221:     for (i=0; i<x->nz; i++) y->a[y->xtoy[i]] += a*(x->a[i]);
2222:     PetscObjectStateIncrease((PetscObject)Y);
2223:   } else {
2224:     Mat      B;
2225:     PetscInt *nnz_d,*nnz_o;
2226:     PetscMalloc1(yy->A->rmap->N,&nnz_d);
2227:     PetscMalloc1(yy->B->rmap->N,&nnz_o);
2228:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2229:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2230:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2231:     MatSetBlockSizesFromMats(B,Y,Y);
2232:     MatSetType(B,MATMPIAIJ);
2233:     MatAXPYGetPreallocation_SeqAIJ(yy->A,xx->A,nnz_d);
2234:     MatAXPYGetPreallocation_MPIAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);
2235:     MatMPIAIJSetPreallocation(B,0,nnz_d,0,nnz_o);
2236:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2237:     MatHeaderReplace(Y,B);
2238:     PetscFree(nnz_d);
2239:     PetscFree(nnz_o);
2240:   }
2241:   return(0);
2242: }

2244: extern PetscErrorCode  MatConjugate_SeqAIJ(Mat);

2248: PetscErrorCode  MatConjugate_MPIAIJ(Mat mat)
2249: {
2250: #if defined(PETSC_USE_COMPLEX)
2252:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2255:   MatConjugate_SeqAIJ(aij->A);
2256:   MatConjugate_SeqAIJ(aij->B);
2257: #else
2259: #endif
2260:   return(0);
2261: }

2265: PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2266: {
2267:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2271:   MatRealPart(a->A);
2272:   MatRealPart(a->B);
2273:   return(0);
2274: }

2278: PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2279: {
2280:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2284:   MatImaginaryPart(a->A);
2285:   MatImaginaryPart(a->B);
2286:   return(0);
2287: }

2289: #if defined(PETSC_HAVE_PBGL)

2291: #include <boost/parallel/mpi/bsp_process_group.hpp>
2292: #include <boost/graph/distributed/ilu_default_graph.hpp>
2293: #include <boost/graph/distributed/ilu_0_block.hpp>
2294: #include <boost/graph/distributed/ilu_preconditioner.hpp>
2295: #include <boost/graph/distributed/petsc/interface.hpp>
2296: #include <boost/multi_array.hpp>
2297: #include <boost/parallel/distributed_property_map->hpp>

2301: /*
2302:   This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
2303: */
2304: PetscErrorCode MatILUFactorSymbolic_MPIAIJ(Mat fact,Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2305: {
2306:   namespace petsc = boost::distributed::petsc;

2308:   namespace graph_dist = boost::graph::distributed;
2309:   using boost::graph::distributed::ilu_default::process_group_type;
2310:   using boost::graph::ilu_permuted;

2312:   PetscBool      row_identity, col_identity;
2313:   PetscContainer c;
2314:   PetscInt       m, n, M, N;

2318:   if (info->levels != 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only levels = 0 supported for parallel ilu");
2319:   ISIdentity(isrow, &row_identity);
2320:   ISIdentity(iscol, &col_identity);
2321:   if (!row_identity || !col_identity) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Row and column permutations must be identity for parallel ILU");

2323:   process_group_type pg;
2324:   typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
2325:   lgraph_type  *lgraph_p   = new lgraph_type(petsc::num_global_vertices(A), pg, petsc::matrix_distribution(A, pg));
2326:   lgraph_type& level_graph = *lgraph_p;
2327:   graph_dist::ilu_default::graph_type&            graph(level_graph.graph);

2329:   petsc::read_matrix(A, graph, get(boost::edge_weight, graph));
2330:   ilu_permuted(level_graph);

2332:   /* put together the new matrix */
2333:   MatCreate(PetscObjectComm((PetscObject)A), fact);
2334:   MatGetLocalSize(A, &m, &n);
2335:   MatGetSize(A, &M, &N);
2336:   MatSetSizes(fact, m, n, M, N);
2337:   MatSetBlockSizesFromMats(fact,A,A);
2338:   MatSetType(fact, ((PetscObject)A)->type_name);
2339:   MatAssemblyBegin(fact, MAT_FINAL_ASSEMBLY);
2340:   MatAssemblyEnd(fact, MAT_FINAL_ASSEMBLY);

2342:   PetscContainerCreate(PetscObjectComm((PetscObject)A), &c);
2343:   PetscContainerSetPointer(c, lgraph_p);
2344:   PetscObjectCompose((PetscObject) (fact), "graph", (PetscObject) c);
2345:   PetscContainerDestroy(&c);
2346:   return(0);
2347: }

2351: PetscErrorCode MatLUFactorNumeric_MPIAIJ(Mat B,Mat A, const MatFactorInfo *info)
2352: {
2354:   return(0);
2355: }

2359: /*
2360:   This uses the parallel ILU factorization of Peter Gottschling <pgottsch@osl.iu.edu>
2361: */
2362: PetscErrorCode MatSolve_MPIAIJ(Mat A, Vec b, Vec x)
2363: {
2364:   namespace graph_dist = boost::graph::distributed;

2366:   typedef graph_dist::ilu_default::ilu_level_graph_type lgraph_type;
2367:   lgraph_type    *lgraph_p;
2368:   PetscContainer c;

2372:   PetscObjectQuery((PetscObject) A, "graph", (PetscObject*) &c);
2373:   PetscContainerGetPointer(c, (void**) &lgraph_p);
2374:   VecCopy(b, x);

2376:   PetscScalar *array_x;
2377:   VecGetArray(x, &array_x);
2378:   PetscInt sx;
2379:   VecGetSize(x, &sx);

2381:   PetscScalar *array_b;
2382:   VecGetArray(b, &array_b);
2383:   PetscInt sb;
2384:   VecGetSize(b, &sb);

2386:   lgraph_type& level_graph = *lgraph_p;
2387:   graph_dist::ilu_default::graph_type&            graph(level_graph.graph);

2389:   typedef boost::multi_array_ref<PetscScalar, 1> array_ref_type;
2390:   array_ref_type                                 ref_b(array_b, boost::extents[num_vertices(graph)]);
2391:   array_ref_type                                 ref_x(array_x, boost::extents[num_vertices(graph)]);

2393:   typedef boost::iterator_property_map<array_ref_type::iterator,
2394:                                        boost::property_map<graph_dist::ilu_default::graph_type, boost::vertex_index_t>::type>  gvector_type;
2395:   gvector_type                                   vector_b(ref_b.begin(), get(boost::vertex_index, graph));
2396:   gvector_type                                   vector_x(ref_x.begin(), get(boost::vertex_index, graph));

2398:   ilu_set_solve(*lgraph_p, vector_b, vector_x);
2399:   return(0);
2400: }
2401: #endif


2406: PetscErrorCode MatGetRedundantMatrix_MPIAIJ_interlaced(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
2407: {
2408:   PetscMPIInt    rank,size;
2409:   MPI_Comm       comm;
2411:   PetscInt       nsends=0,nrecvs=0,i,rownz_max=0,M=mat->rmap->N,N=mat->cmap->N;
2412:   PetscMPIInt    *send_rank= NULL,*recv_rank=NULL,subrank,subsize;
2413:   PetscInt       *rowrange = mat->rmap->range;
2414:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
2415:   Mat            A = aij->A,B=aij->B,C=*matredundant;
2416:   Mat_SeqAIJ     *a = (Mat_SeqAIJ*)A->data,*b=(Mat_SeqAIJ*)B->data;
2417:   PetscScalar    *sbuf_a;
2418:   PetscInt       nzlocal=a->nz+b->nz;
2419:   PetscInt       j,cstart=mat->cmap->rstart,cend=mat->cmap->rend,row,nzA,nzB,ncols,*cworkA,*cworkB;
2420:   PetscInt       rstart=mat->rmap->rstart,rend=mat->rmap->rend,*bmap=aij->garray;
2421:   PetscInt       *cols,ctmp,lwrite,*rptr,l,*sbuf_j;
2422:   MatScalar      *aworkA,*aworkB;
2423:   PetscScalar    *vals;
2424:   PetscMPIInt    tag1,tag2,tag3,imdex;
2425:   MPI_Request    *s_waits1=NULL,*s_waits2=NULL,*s_waits3=NULL;
2426:   MPI_Request    *r_waits1=NULL,*r_waits2=NULL,*r_waits3=NULL;
2427:   MPI_Status     recv_status,*send_status;
2428:   PetscInt       *sbuf_nz=NULL,*rbuf_nz=NULL,count;
2429:   PetscInt       **rbuf_j=NULL;
2430:   PetscScalar    **rbuf_a=NULL;
2431:   Mat_Redundant  *redund =NULL;
2432: 
2434:   PetscObjectGetComm((PetscObject)mat,&comm);
2435:   MPI_Comm_rank(comm,&rank);
2436:   MPI_Comm_size(comm,&size);
2437:   MPI_Comm_rank(subcomm,&subrank);
2438:   MPI_Comm_size(subcomm,&subsize);

2440:   if (reuse == MAT_REUSE_MATRIX) {
2441:     if (M != mat->rmap->N || N != mat->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong global size");
2442:     if (subsize == 1) {
2443:       Mat_SeqAIJ *c = (Mat_SeqAIJ*)C->data;
2444:       redund = c->redundant;
2445:     } else {
2446:       Mat_MPIAIJ *c = (Mat_MPIAIJ*)C->data;
2447:       redund = c->redundant;
2448:     }
2449:     if (nzlocal != redund->nzlocal) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Cannot reuse matrix. Wrong nzlocal");

2451:     nsends    = redund->nsends;
2452:     nrecvs    = redund->nrecvs;
2453:     send_rank = redund->send_rank;
2454:     recv_rank = redund->recv_rank;
2455:     sbuf_nz   = redund->sbuf_nz;
2456:     rbuf_nz   = redund->rbuf_nz;
2457:     sbuf_j    = redund->sbuf_j;
2458:     sbuf_a    = redund->sbuf_a;
2459:     rbuf_j    = redund->rbuf_j;
2460:     rbuf_a    = redund->rbuf_a;
2461:   }

2463:   if (reuse == MAT_INITIAL_MATRIX) {
2464:     PetscInt    nleftover,np_subcomm;

2466:     /* get the destination processors' id send_rank, nsends and nrecvs */
2467:     PetscMalloc2(size,&send_rank,size,&recv_rank);

2469:     np_subcomm = size/nsubcomm;
2470:     nleftover  = size - nsubcomm*np_subcomm;

2472:     /* block of codes below is specific for INTERLACED */
2473:     /* ------------------------------------------------*/
2474:     nsends = 0; nrecvs = 0;
2475:     for (i=0; i<size; i++) {
2476:       if (subrank == i/nsubcomm && i != rank) { /* my_subrank == other's subrank */
2477:         send_rank[nsends++] = i;
2478:         recv_rank[nrecvs++] = i;
2479:       }
2480:     }
2481:     if (rank >= size - nleftover) { /* this proc is a leftover processor */
2482:       i = size-nleftover-1;
2483:       j = 0;
2484:       while (j < nsubcomm - nleftover) {
2485:         send_rank[nsends++] = i;
2486:         i--; j++;
2487:       }
2488:     }

2490:     if (nleftover && subsize == size/nsubcomm && subrank==subsize-1) { /* this proc recvs from leftover processors */
2491:       for (i=0; i<nleftover; i++) {
2492:         recv_rank[nrecvs++] = size-nleftover+i;
2493:       }
2494:     }
2495:     /*----------------------------------------------*/

2497:     /* allocate sbuf_j, sbuf_a */
2498:     i    = nzlocal + rowrange[rank+1] - rowrange[rank] + 2;
2499:     PetscMalloc1(i,&sbuf_j);
2500:     PetscMalloc1((nzlocal+1),&sbuf_a);
2501:     /*
2502:     PetscSynchronizedPrintf(comm,"[%d] nsends %d, nrecvs %d\n",rank,nsends,nrecvs);
2503:     PetscSynchronizedFlush(comm,PETSC_STDOUT);
2504:      */
2505:   } /* endof if (reuse == MAT_INITIAL_MATRIX) */

2507:   /* copy mat's local entries into the buffers */
2508:   if (reuse == MAT_INITIAL_MATRIX) {
2509:     rownz_max = 0;
2510:     rptr      = sbuf_j;
2511:     cols      = sbuf_j + rend-rstart + 1;
2512:     vals      = sbuf_a;
2513:     rptr[0]   = 0;
2514:     for (i=0; i<rend-rstart; i++) {
2515:       row    = i + rstart;
2516:       nzA    = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2517:       ncols  = nzA + nzB;
2518:       cworkA = a->j + a->i[i]; cworkB = b->j + b->i[i];
2519:       aworkA = a->a + a->i[i]; aworkB = b->a + b->i[i];
2520:       /* load the column indices for this row into cols */
2521:       lwrite = 0;
2522:       for (l=0; l<nzB; l++) {
2523:         if ((ctmp = bmap[cworkB[l]]) < cstart) {
2524:           vals[lwrite]   = aworkB[l];
2525:           cols[lwrite++] = ctmp;
2526:         }
2527:       }
2528:       for (l=0; l<nzA; l++) {
2529:         vals[lwrite]   = aworkA[l];
2530:         cols[lwrite++] = cstart + cworkA[l];
2531:       }
2532:       for (l=0; l<nzB; l++) {
2533:         if ((ctmp = bmap[cworkB[l]]) >= cend) {
2534:           vals[lwrite]   = aworkB[l];
2535:           cols[lwrite++] = ctmp;
2536:         }
2537:       }
2538:       vals     += ncols;
2539:       cols     += ncols;
2540:       rptr[i+1] = rptr[i] + ncols;
2541:       if (rownz_max < ncols) rownz_max = ncols;
2542:     }
2543:     if (rptr[rend-rstart] != a->nz + b->nz) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_PLIB, "rptr[%d] %d != %d + %d",rend-rstart,rptr[rend-rstart+1],a->nz,b->nz);
2544:   } else { /* only copy matrix values into sbuf_a */
2545:     rptr    = sbuf_j;
2546:     vals    = sbuf_a;
2547:     rptr[0] = 0;
2548:     for (i=0; i<rend-rstart; i++) {
2549:       row    = i + rstart;
2550:       nzA    = a->i[i+1] - a->i[i]; nzB = b->i[i+1] - b->i[i];
2551:       ncols  = nzA + nzB;
2552:       cworkB = b->j + b->i[i];
2553:       aworkA = a->a + a->i[i];
2554:       aworkB = b->a + b->i[i];
2555:       lwrite = 0;
2556:       for (l=0; l<nzB; l++) {
2557:         if ((ctmp = bmap[cworkB[l]]) < cstart) vals[lwrite++] = aworkB[l];
2558:       }
2559:       for (l=0; l<nzA; l++) vals[lwrite++] = aworkA[l];
2560:       for (l=0; l<nzB; l++) {
2561:         if ((ctmp = bmap[cworkB[l]]) >= cend) vals[lwrite++] = aworkB[l];
2562:       }
2563:       vals     += ncols;
2564:       rptr[i+1] = rptr[i] + ncols;
2565:     }
2566:   } /* endof if (reuse == MAT_INITIAL_MATRIX) */

2568:   /* send nzlocal to others, and recv other's nzlocal */
2569:   /*--------------------------------------------------*/
2570:   if (reuse == MAT_INITIAL_MATRIX) {
2571:     PetscMalloc2(3*(nsends + nrecvs)+1,&s_waits3,nsends+1,&send_status);

2573:     s_waits2 = s_waits3 + nsends;
2574:     s_waits1 = s_waits2 + nsends;
2575:     r_waits1 = s_waits1 + nsends;
2576:     r_waits2 = r_waits1 + nrecvs;
2577:     r_waits3 = r_waits2 + nrecvs;
2578:   } else {
2579:     PetscMalloc2(nsends + nrecvs +1,&s_waits3,nsends+1,&send_status);

2581:     r_waits3 = s_waits3 + nsends;
2582:   }

2584:   PetscObjectGetNewTag((PetscObject)mat,&tag3);
2585:   if (reuse == MAT_INITIAL_MATRIX) {
2586:     /* get new tags to keep the communication clean */
2587:     PetscObjectGetNewTag((PetscObject)mat,&tag1);
2588:     PetscObjectGetNewTag((PetscObject)mat,&tag2);
2589:     PetscMalloc4(nsends,&sbuf_nz,nrecvs,&rbuf_nz,nrecvs,&rbuf_j,nrecvs,&rbuf_a);

2591:     /* post receives of other's nzlocal */
2592:     for (i=0; i<nrecvs; i++) {
2593:       MPI_Irecv(rbuf_nz+i,1,MPIU_INT,MPI_ANY_SOURCE,tag1,comm,r_waits1+i);
2594:     }
2595:     /* send nzlocal to others */
2596:     for (i=0; i<nsends; i++) {
2597:       sbuf_nz[i] = nzlocal;
2598:       MPI_Isend(sbuf_nz+i,1,MPIU_INT,send_rank[i],tag1,comm,s_waits1+i);
2599:     }
2600:     /* wait on receives of nzlocal; allocate space for rbuf_j, rbuf_a */
2601:     count = nrecvs;
2602:     while (count) {
2603:       MPI_Waitany(nrecvs,r_waits1,&imdex,&recv_status);

2605:       recv_rank[imdex] = recv_status.MPI_SOURCE;
2606:       /* allocate rbuf_a and rbuf_j; then post receives of rbuf_j */
2607:       PetscMalloc1((rbuf_nz[imdex]+1),&rbuf_a[imdex]);

2609:       i = rowrange[recv_status.MPI_SOURCE+1] - rowrange[recv_status.MPI_SOURCE]; /* number of expected mat->i */

2611:       rbuf_nz[imdex] += i + 2;

2613:       PetscMalloc1(rbuf_nz[imdex],&rbuf_j[imdex]);
2614:       MPI_Irecv(rbuf_j[imdex],rbuf_nz[imdex],MPIU_INT,recv_status.MPI_SOURCE,tag2,comm,r_waits2+imdex);
2615:       count--;
2616:     }
2617:     /* wait on sends of nzlocal */
2618:     if (nsends) {MPI_Waitall(nsends,s_waits1,send_status);}
2619:     /* send mat->i,j to others, and recv from other's */
2620:     /*------------------------------------------------*/
2621:     for (i=0; i<nsends; i++) {
2622:       j    = nzlocal + rowrange[rank+1] - rowrange[rank] + 1;
2623:       MPI_Isend(sbuf_j,j,MPIU_INT,send_rank[i],tag2,comm,s_waits2+i);
2624:     }
2625:     /* wait on receives of mat->i,j */
2626:     /*------------------------------*/
2627:     count = nrecvs;
2628:     while (count) {
2629:       MPI_Waitany(nrecvs,r_waits2,&imdex,&recv_status);
2630:       if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(PETSC_COMM_SELF,1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2631:       count--;
2632:     }
2633:     /* wait on sends of mat->i,j */
2634:     /*---------------------------*/
2635:     if (nsends) {
2636:       MPI_Waitall(nsends,s_waits2,send_status);
2637:     }
2638:   } /* endof if (reuse == MAT_INITIAL_MATRIX) */

2640:   /* post receives, send and receive mat->a */
2641:   /*----------------------------------------*/
2642:   for (imdex=0; imdex<nrecvs; imdex++) {
2643:     MPI_Irecv(rbuf_a[imdex],rbuf_nz[imdex],MPIU_SCALAR,recv_rank[imdex],tag3,comm,r_waits3+imdex);
2644:   }
2645:   for (i=0; i<nsends; i++) {
2646:     MPI_Isend(sbuf_a,nzlocal,MPIU_SCALAR,send_rank[i],tag3,comm,s_waits3+i);
2647:   }
2648:   count = nrecvs;
2649:   while (count) {
2650:     MPI_Waitany(nrecvs,r_waits3,&imdex,&recv_status);
2651:     if (recv_rank[imdex] != recv_status.MPI_SOURCE) SETERRQ2(PETSC_COMM_SELF,1, "recv_rank %d != MPI_SOURCE %d",recv_rank[imdex],recv_status.MPI_SOURCE);
2652:     count--;
2653:   }
2654:   if (nsends) {
2655:     MPI_Waitall(nsends,s_waits3,send_status);
2656:   }

2658:   PetscFree2(s_waits3,send_status);

2660:   /* create redundant matrix */
2661:   /*-------------------------*/
2662:   if (reuse == MAT_INITIAL_MATRIX) {
2663:     const PetscInt *range;
2664:     PetscInt       rstart_sub,rend_sub,mloc_sub;

2666:     /* compute rownz_max for preallocation */
2667:     for (imdex=0; imdex<nrecvs; imdex++) {
2668:       j    = rowrange[recv_rank[imdex]+1] - rowrange[recv_rank[imdex]];
2669:       rptr = rbuf_j[imdex];
2670:       for (i=0; i<j; i++) {
2671:         ncols = rptr[i+1] - rptr[i];
2672:         if (rownz_max < ncols) rownz_max = ncols;
2673:       }
2674:     }

2676:     MatCreate(subcomm,&C);

2678:     /* get local size of redundant matrix
2679:        - mloc_sub is chosen for PETSC_SUBCOMM_INTERLACED, works for other types, but may not efficient! */
2680:     MatGetOwnershipRanges(mat,&range);
2681:     rstart_sub = range[nsubcomm*subrank];
2682:     if (subrank+1 < subsize) { /* not the last proc in subcomm */
2683:       rend_sub = range[nsubcomm*(subrank+1)];
2684:     } else {
2685:       rend_sub = mat->rmap->N;
2686:     }
2687:     mloc_sub = rend_sub - rstart_sub;

2689:     if (M == N) {
2690:       MatSetSizes(C,mloc_sub,mloc_sub,PETSC_DECIDE,PETSC_DECIDE);
2691:     } else { /* non-square matrix */
2692:       MatSetSizes(C,mloc_sub,PETSC_DECIDE,PETSC_DECIDE,mat->cmap->N);
2693:     }
2694:     MatSetBlockSizesFromMats(C,mat,mat);
2695:     MatSetFromOptions(C);
2696:     MatSeqAIJSetPreallocation(C,rownz_max,NULL);
2697:     MatMPIAIJSetPreallocation(C,rownz_max,NULL,rownz_max,NULL);
2698:   } else {
2699:     C = *matredundant;
2700:   }

2702:   /* insert local matrix entries */
2703:   rptr = sbuf_j;
2704:   cols = sbuf_j + rend-rstart + 1;
2705:   vals = sbuf_a;
2706:   for (i=0; i<rend-rstart; i++) {
2707:     row   = i + rstart;
2708:     ncols = rptr[i+1] - rptr[i];
2709:     MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);
2710:     vals += ncols;
2711:     cols += ncols;
2712:   }
2713:   /* insert received matrix entries */
2714:   for (imdex=0; imdex<nrecvs; imdex++) {
2715:     rstart = rowrange[recv_rank[imdex]];
2716:     rend   = rowrange[recv_rank[imdex]+1];
2717:     /* printf("[%d] insert rows %d - %d\n",rank,rstart,rend-1); */
2718:     rptr   = rbuf_j[imdex];
2719:     cols   = rbuf_j[imdex] + rend-rstart + 1;
2720:     vals   = rbuf_a[imdex];
2721:     for (i=0; i<rend-rstart; i++) {
2722:       row   = i + rstart;
2723:       ncols = rptr[i+1] - rptr[i];
2724:       MatSetValues(C,1,&row,ncols,cols,vals,INSERT_VALUES);
2725:       vals += ncols;
2726:       cols += ncols;
2727:     }
2728:   }
2729:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2730:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2732:   if (reuse == MAT_INITIAL_MATRIX) {
2733:     *matredundant = C;

2735:     /* create a supporting struct and attach it to C for reuse */
2736:     PetscNewLog(C,&redund);
2737:     if (subsize == 1) {
2738:       Mat_SeqAIJ *c = (Mat_SeqAIJ*)C->data;
2739:       c->redundant = redund;
2740:     } else {
2741:       Mat_MPIAIJ *c = (Mat_MPIAIJ*)C->data;
2742:       c->redundant = redund;
2743:     }

2745:     redund->nzlocal   = nzlocal;
2746:     redund->nsends    = nsends;
2747:     redund->nrecvs    = nrecvs;
2748:     redund->send_rank = send_rank;
2749:     redund->recv_rank = recv_rank;
2750:     redund->sbuf_nz   = sbuf_nz;
2751:     redund->rbuf_nz   = rbuf_nz;
2752:     redund->sbuf_j    = sbuf_j;
2753:     redund->sbuf_a    = sbuf_a;
2754:     redund->rbuf_j    = rbuf_j;
2755:     redund->rbuf_a    = rbuf_a;
2756:     redund->psubcomm  = NULL;
2757:   }
2758:   return(0);
2759: }

2763: PetscErrorCode MatGetRedundantMatrix_MPIAIJ(Mat mat,PetscInt nsubcomm,MPI_Comm subcomm,MatReuse reuse,Mat *matredundant)
2764: {
2766:   MPI_Comm       comm;
2767:   PetscMPIInt    size,subsize;
2768:   PetscInt       mloc_sub,rstart,rend,M=mat->rmap->N,N=mat->cmap->N;
2769:   Mat_Redundant  *redund=NULL;
2770:   PetscSubcomm   psubcomm=NULL;
2771:   MPI_Comm       subcomm_in=subcomm;
2772:   Mat            *matseq;
2773:   IS             isrow,iscol;

2776:   if (subcomm_in == MPI_COMM_NULL) { /* user does not provide subcomm */
2777:     if (reuse ==  MAT_INITIAL_MATRIX) {
2778:       /* create psubcomm, then get subcomm */
2779:       PetscObjectGetComm((PetscObject)mat,&comm);
2780:       MPI_Comm_size(comm,&size);
2781:       if (nsubcomm < 1 || nsubcomm > size) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"nsubcomm must between 1 and %D",size);

2783:       PetscSubcommCreate(comm,&psubcomm);
2784:       PetscSubcommSetNumber(psubcomm,nsubcomm);
2785:       PetscSubcommSetType(psubcomm,PETSC_SUBCOMM_CONTIGUOUS);
2786:       PetscSubcommSetFromOptions(psubcomm);
2787:       subcomm = psubcomm->comm;
2788:     } else { /* retrieve psubcomm and subcomm */
2789:       PetscObjectGetComm((PetscObject)(*matredundant),&subcomm);
2790:       MPI_Comm_size(subcomm,&subsize);
2791:       if (subsize == 1) {
2792:         Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
2793:         redund = c->redundant;
2794:       } else {
2795:         Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
2796:         redund = c->redundant;
2797:       }
2798:       psubcomm = redund->psubcomm;
2799:     }
2800:     if (psubcomm->type == PETSC_SUBCOMM_INTERLACED) {
2801:       MatGetRedundantMatrix_MPIAIJ_interlaced(mat,nsubcomm,subcomm,reuse,matredundant);
2802:       if (reuse ==  MAT_INITIAL_MATRIX) { /* psubcomm is created in this routine, free it in MatDestroy_Redundant() */
2803:         MPI_Comm_size(psubcomm->comm,&subsize);
2804:         if (subsize == 1) {
2805:           Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
2806:           c->redundant->psubcomm = psubcomm;
2807:         } else {
2808:           Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
2809:           c->redundant->psubcomm = psubcomm ;
2810:         }
2811:       }
2812:       return(0);
2813:     }
2814:   }

2816:   /* use MPI subcomm via MatGetSubMatrices(); use subcomm_in or psubcomm->comm (psubcomm->type != INTERLACED) */
2817:   MPI_Comm_size(subcomm,&subsize);
2818:   if (reuse == MAT_INITIAL_MATRIX) {
2819:     /* create a local sequential matrix matseq[0] */
2820:     mloc_sub = PETSC_DECIDE;
2821:     PetscSplitOwnership(subcomm,&mloc_sub,&M);
2822:     MPI_Scan(&mloc_sub,&rend,1,MPIU_INT,MPI_SUM,subcomm);
2823:     rstart = rend - mloc_sub;
2824:     ISCreateStride(PETSC_COMM_SELF,mloc_sub,rstart,1,&isrow);
2825:     ISCreateStride(PETSC_COMM_SELF,N,0,1,&iscol);
2826:   } else { /* reuse == MAT_REUSE_MATRIX */
2827:     if (subsize == 1) {
2828:       Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
2829:       redund = c->redundant;
2830:     } else {
2831:       Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
2832:       redund = c->redundant;
2833:     }

2835:     isrow  = redund->isrow;
2836:     iscol  = redund->iscol;
2837:     matseq = redund->matseq;
2838:   }
2839:   MatGetSubMatrices(mat,1,&isrow,&iscol,reuse,&matseq);
2840:   MatCreateMPIAIJConcatenateSeqAIJ(subcomm,matseq[0],PETSC_DECIDE,reuse,matredundant);

2842:   if (reuse == MAT_INITIAL_MATRIX) {
2843:     /* create a supporting struct and attach it to C for reuse */
2844:     PetscNewLog(*matredundant,&redund);
2845:     if (subsize == 1) {
2846:       Mat_SeqAIJ *c = (Mat_SeqAIJ*)(*matredundant)->data;
2847:       c->redundant = redund;
2848:     } else {
2849:       Mat_MPIAIJ *c = (Mat_MPIAIJ*)(*matredundant)->data;
2850:       c->redundant = redund;
2851:     }
2852:     redund->isrow    = isrow;
2853:     redund->iscol    = iscol;
2854:     redund->matseq   = matseq;
2855:     redund->psubcomm = psubcomm;
2856:   }
2857:   return(0);
2858: }

2862: PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2863: {
2864:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2866:   PetscInt       i,*idxb = 0;
2867:   PetscScalar    *va,*vb;
2868:   Vec            vtmp;

2871:   MatGetRowMaxAbs(a->A,v,idx);
2872:   VecGetArray(v,&va);
2873:   if (idx) {
2874:     for (i=0; i<A->rmap->n; i++) {
2875:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2876:     }
2877:   }

2879:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2880:   if (idx) {
2881:     PetscMalloc1(A->rmap->n,&idxb);
2882:   }
2883:   MatGetRowMaxAbs(a->B,vtmp,idxb);
2884:   VecGetArray(vtmp,&vb);

2886:   for (i=0; i<A->rmap->n; i++) {
2887:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2888:       va[i] = vb[i];
2889:       if (idx) idx[i] = a->garray[idxb[i]];
2890:     }
2891:   }

2893:   VecRestoreArray(v,&va);
2894:   VecRestoreArray(vtmp,&vb);
2895:   PetscFree(idxb);
2896:   VecDestroy(&vtmp);
2897:   return(0);
2898: }

2902: PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2903: {
2904:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2906:   PetscInt       i,*idxb = 0;
2907:   PetscScalar    *va,*vb;
2908:   Vec            vtmp;

2911:   MatGetRowMinAbs(a->A,v,idx);
2912:   VecGetArray(v,&va);
2913:   if (idx) {
2914:     for (i=0; i<A->cmap->n; i++) {
2915:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2916:     }
2917:   }

2919:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2920:   if (idx) {
2921:     PetscMalloc1(A->rmap->n,&idxb);
2922:   }
2923:   MatGetRowMinAbs(a->B,vtmp,idxb);
2924:   VecGetArray(vtmp,&vb);

2926:   for (i=0; i<A->rmap->n; i++) {
2927:     if (PetscAbsScalar(va[i]) > PetscAbsScalar(vb[i])) {
2928:       va[i] = vb[i];
2929:       if (idx) idx[i] = a->garray[idxb[i]];
2930:     }
2931:   }

2933:   VecRestoreArray(v,&va);
2934:   VecRestoreArray(vtmp,&vb);
2935:   PetscFree(idxb);
2936:   VecDestroy(&vtmp);
2937:   return(0);
2938: }

2942: PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2943: {
2944:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2945:   PetscInt       n      = A->rmap->n;
2946:   PetscInt       cstart = A->cmap->rstart;
2947:   PetscInt       *cmap  = mat->garray;
2948:   PetscInt       *diagIdx, *offdiagIdx;
2949:   Vec            diagV, offdiagV;
2950:   PetscScalar    *a, *diagA, *offdiagA;
2951:   PetscInt       r;

2955:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2956:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &diagV);
2957:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &offdiagV);
2958:   MatGetRowMin(mat->A, diagV,    diagIdx);
2959:   MatGetRowMin(mat->B, offdiagV, offdiagIdx);
2960:   VecGetArray(v,        &a);
2961:   VecGetArray(diagV,    &diagA);
2962:   VecGetArray(offdiagV, &offdiagA);
2963:   for (r = 0; r < n; ++r) {
2964:     if (PetscAbsScalar(diagA[r]) <= PetscAbsScalar(offdiagA[r])) {
2965:       a[r]   = diagA[r];
2966:       idx[r] = cstart + diagIdx[r];
2967:     } else {
2968:       a[r]   = offdiagA[r];
2969:       idx[r] = cmap[offdiagIdx[r]];
2970:     }
2971:   }
2972:   VecRestoreArray(v,        &a);
2973:   VecRestoreArray(diagV,    &diagA);
2974:   VecRestoreArray(offdiagV, &offdiagA);
2975:   VecDestroy(&diagV);
2976:   VecDestroy(&offdiagV);
2977:   PetscFree2(diagIdx, offdiagIdx);
2978:   return(0);
2979: }

2983: PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2984: {
2985:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2986:   PetscInt       n      = A->rmap->n;
2987:   PetscInt       cstart = A->cmap->rstart;
2988:   PetscInt       *cmap  = mat->garray;
2989:   PetscInt       *diagIdx, *offdiagIdx;
2990:   Vec            diagV, offdiagV;
2991:   PetscScalar    *a, *diagA, *offdiagA;
2992:   PetscInt       r;

2996:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2997:   VecCreateSeq(PETSC_COMM_SELF, n, &diagV);
2998:   VecCreateSeq(PETSC_COMM_SELF, n, &offdiagV);
2999:   MatGetRowMax(mat->A, diagV,    diagIdx);
3000:   MatGetRowMax(mat->B, offdiagV, offdiagIdx);
3001:   VecGetArray(v,        &a);
3002:   VecGetArray(diagV,    &diagA);
3003:   VecGetArray(offdiagV, &offdiagA);
3004:   for (r = 0; r < n; ++r) {
3005:     if (PetscAbsScalar(diagA[r]) >= PetscAbsScalar(offdiagA[r])) {
3006:       a[r]   = diagA[r];
3007:       idx[r] = cstart + diagIdx[r];
3008:     } else {
3009:       a[r]   = offdiagA[r];
3010:       idx[r] = cmap[offdiagIdx[r]];
3011:     }
3012:   }
3013:   VecRestoreArray(v,        &a);
3014:   VecRestoreArray(diagV,    &diagA);
3015:   VecRestoreArray(offdiagV, &offdiagA);
3016:   VecDestroy(&diagV);
3017:   VecDestroy(&offdiagV);
3018:   PetscFree2(diagIdx, offdiagIdx);
3019:   return(0);
3020: }

3024: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat,Mat *newmat)
3025: {
3027:   Mat            *dummy;

3030:   MatGetSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,&dummy);
3031:   *newmat = *dummy;
3032:   PetscFree(dummy);
3033:   return(0);
3034: }

3038: PetscErrorCode  MatInvertBlockDiagonal_MPIAIJ(Mat A,const PetscScalar **values)
3039: {
3040:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*) A->data;

3044:   MatInvertBlockDiagonal(a->A,values);
3045:   return(0);
3046: }

3050: static PetscErrorCode  MatSetRandom_MPIAIJ(Mat x,PetscRandom rctx)
3051: {
3053:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)x->data;

3056:   MatSetRandom(aij->A,rctx);
3057:   MatSetRandom(aij->B,rctx);
3058:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
3059:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
3060:   return(0);
3061: }

3063: /* -------------------------------------------------------------------*/
3064: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
3065:                                        MatGetRow_MPIAIJ,
3066:                                        MatRestoreRow_MPIAIJ,
3067:                                        MatMult_MPIAIJ,
3068:                                 /* 4*/ MatMultAdd_MPIAIJ,
3069:                                        MatMultTranspose_MPIAIJ,
3070:                                        MatMultTransposeAdd_MPIAIJ,
3071: #if defined(PETSC_HAVE_PBGL)
3072:                                        MatSolve_MPIAIJ,
3073: #else
3074:                                        0,
3075: #endif
3076:                                        0,
3077:                                        0,
3078:                                 /*10*/ 0,
3079:                                        0,
3080:                                        0,
3081:                                        MatSOR_MPIAIJ,
3082:                                        MatTranspose_MPIAIJ,
3083:                                 /*15*/ MatGetInfo_MPIAIJ,
3084:                                        MatEqual_MPIAIJ,
3085:                                        MatGetDiagonal_MPIAIJ,
3086:                                        MatDiagonalScale_MPIAIJ,
3087:                                        MatNorm_MPIAIJ,
3088:                                 /*20*/ MatAssemblyBegin_MPIAIJ,
3089:                                        MatAssemblyEnd_MPIAIJ,
3090:                                        MatSetOption_MPIAIJ,
3091:                                        MatZeroEntries_MPIAIJ,
3092:                                 /*24*/ MatZeroRows_MPIAIJ,
3093:                                        0,
3094: #if defined(PETSC_HAVE_PBGL)
3095:                                        0,
3096: #else
3097:                                        0,
3098: #endif
3099:                                        0,
3100:                                        0,
3101:                                 /*29*/ MatSetUp_MPIAIJ,
3102: #if defined(PETSC_HAVE_PBGL)
3103:                                        0,
3104: #else
3105:                                        0,
3106: #endif
3107:                                        0,
3108:                                        0,
3109:                                        0,
3110:                                 /*34*/ MatDuplicate_MPIAIJ,
3111:                                        0,
3112:                                        0,
3113:                                        0,
3114:                                        0,
3115:                                 /*39*/ MatAXPY_MPIAIJ,
3116:                                        MatGetSubMatrices_MPIAIJ,
3117:                                        MatIncreaseOverlap_MPIAIJ,
3118:                                        MatGetValues_MPIAIJ,
3119:                                        MatCopy_MPIAIJ,
3120:                                 /*44*/ MatGetRowMax_MPIAIJ,
3121:                                        MatScale_MPIAIJ,
3122:                                        0,
3123:                                        MatDiagonalSet_MPIAIJ,
3124:                                        MatZeroRowsColumns_MPIAIJ,
3125:                                 /*49*/ MatSetRandom_MPIAIJ,
3126:                                        0,
3127:                                        0,
3128:                                        0,
3129:                                        0,
3130:                                 /*54*/ MatFDColoringCreate_MPIXAIJ,
3131:                                        0,
3132:                                        MatSetUnfactored_MPIAIJ,
3133:                                        MatPermute_MPIAIJ,
3134:                                        0,
3135:                                 /*59*/ MatGetSubMatrix_MPIAIJ,
3136:                                        MatDestroy_MPIAIJ,
3137:                                        MatView_MPIAIJ,
3138:                                        0,
3139:                                        MatMatMatMult_MPIAIJ_MPIAIJ_MPIAIJ,
3140:                                 /*64*/ MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ,
3141:                                        MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
3142:                                        0,
3143:                                        0,
3144:                                        0,
3145:                                 /*69*/ MatGetRowMaxAbs_MPIAIJ,
3146:                                        MatGetRowMinAbs_MPIAIJ,
3147:                                        0,
3148:                                        MatSetColoring_MPIAIJ,
3149:                                        0,
3150:                                        MatSetValuesAdifor_MPIAIJ,
3151:                                 /*75*/ MatFDColoringApply_AIJ,
3152:                                        0,
3153:                                        0,
3154:                                        0,
3155:                                        MatFindZeroDiagonals_MPIAIJ,
3156:                                 /*80*/ 0,
3157:                                        0,
3158:                                        0,
3159:                                 /*83*/ MatLoad_MPIAIJ,
3160:                                        0,
3161:                                        0,
3162:                                        0,
3163:                                        0,
3164:                                        0,
3165:                                 /*89*/ MatMatMult_MPIAIJ_MPIAIJ,
3166:                                        MatMatMultSymbolic_MPIAIJ_MPIAIJ,
3167:                                        MatMatMultNumeric_MPIAIJ_MPIAIJ,
3168:                                        MatPtAP_MPIAIJ_MPIAIJ,
3169:                                        MatPtAPSymbolic_MPIAIJ_MPIAIJ,
3170:                                 /*94*/ MatPtAPNumeric_MPIAIJ_MPIAIJ,
3171:                                        0,
3172:                                        0,
3173:                                        0,
3174:                                        0,
3175:                                 /*99*/ 0,
3176:                                        0,
3177:                                        0,
3178:                                        MatConjugate_MPIAIJ,
3179:                                        0,
3180:                                 /*104*/MatSetValuesRow_MPIAIJ,
3181:                                        MatRealPart_MPIAIJ,
3182:                                        MatImaginaryPart_MPIAIJ,
3183:                                        0,
3184:                                        0,
3185:                                 /*109*/0,
3186:                                        MatGetRedundantMatrix_MPIAIJ,
3187:                                        MatGetRowMin_MPIAIJ,
3188:                                        0,
3189:                                        0,
3190:                                 /*114*/MatGetSeqNonzeroStructure_MPIAIJ,
3191:                                        0,
3192:                                        0,
3193:                                        0,
3194:                                        0,
3195:                                 /*119*/0,
3196:                                        0,
3197:                                        0,
3198:                                        0,
3199:                                        MatGetMultiProcBlock_MPIAIJ,
3200:                                 /*124*/MatFindNonzeroRows_MPIAIJ,
3201:                                        MatGetColumnNorms_MPIAIJ,
3202:                                        MatInvertBlockDiagonal_MPIAIJ,
3203:                                        0,
3204:                                        MatGetSubMatricesParallel_MPIAIJ,
3205:                                 /*129*/0,
3206:                                        MatTransposeMatMult_MPIAIJ_MPIAIJ,
3207:                                        MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ,
3208:                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
3209:                                        0,
3210:                                 /*134*/0,
3211:                                        0,
3212:                                        0,
3213:                                        0,
3214:                                        0,
3215:                                 /*139*/0,
3216:                                        0,
3217:                                        0,
3218:                                        MatFDColoringSetUp_MPIXAIJ
3219: };

3221: /* ----------------------------------------------------------------------------------------*/

3225: PetscErrorCode  MatStoreValues_MPIAIJ(Mat mat)
3226: {
3227:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

3231:   MatStoreValues(aij->A);
3232:   MatStoreValues(aij->B);
3233:   return(0);
3234: }

3238: PetscErrorCode  MatRetrieveValues_MPIAIJ(Mat mat)
3239: {
3240:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

3244:   MatRetrieveValues(aij->A);
3245:   MatRetrieveValues(aij->B);
3246:   return(0);
3247: }

3251: PetscErrorCode  MatMPIAIJSetPreallocation_MPIAIJ(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3252: {
3253:   Mat_MPIAIJ     *b;

3257:   PetscLayoutSetUp(B->rmap);
3258:   PetscLayoutSetUp(B->cmap);
3259:   b = (Mat_MPIAIJ*)B->data;

3261:   if (!B->preallocated) {
3262:     /* Explicitly create 2 MATSEQAIJ matrices. */
3263:     MatCreate(PETSC_COMM_SELF,&b->A);
3264:     MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
3265:     MatSetBlockSizesFromMats(b->A,B,B);
3266:     MatSetType(b->A,MATSEQAIJ);
3267:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->A);
3268:     MatCreate(PETSC_COMM_SELF,&b->B);
3269:     MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);
3270:     MatSetBlockSizesFromMats(b->B,B,B);
3271:     MatSetType(b->B,MATSEQAIJ);
3272:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->B);
3273:   }

3275:   MatSeqAIJSetPreallocation(b->A,d_nz,d_nnz);
3276:   MatSeqAIJSetPreallocation(b->B,o_nz,o_nnz);
3277:   B->preallocated = PETSC_TRUE;
3278:   return(0);
3279: }

3283: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
3284: {
3285:   Mat            mat;
3286:   Mat_MPIAIJ     *a,*oldmat = (Mat_MPIAIJ*)matin->data;

3290:   *newmat = 0;
3291:   MatCreate(PetscObjectComm((PetscObject)matin),&mat);
3292:   MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
3293:   MatSetBlockSizesFromMats(mat,matin,matin);
3294:   MatSetType(mat,((PetscObject)matin)->type_name);
3295:   PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));
3296:   a       = (Mat_MPIAIJ*)mat->data;

3298:   mat->factortype   = matin->factortype;
3299:   mat->assembled    = PETSC_TRUE;
3300:   mat->insertmode   = NOT_SET_VALUES;
3301:   mat->preallocated = PETSC_TRUE;

3303:   a->size         = oldmat->size;
3304:   a->rank         = oldmat->rank;
3305:   a->donotstash   = oldmat->donotstash;
3306:   a->roworiented  = oldmat->roworiented;
3307:   a->rowindices   = 0;
3308:   a->rowvalues    = 0;
3309:   a->getrowactive = PETSC_FALSE;

3311:   PetscLayoutReference(matin->rmap,&mat->rmap);
3312:   PetscLayoutReference(matin->cmap,&mat->cmap);

3314:   if (oldmat->colmap) {
3315: #if defined(PETSC_USE_CTABLE)
3316:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
3317: #else
3318:     PetscMalloc1((mat->cmap->N),&a->colmap);
3319:     PetscLogObjectMemory((PetscObject)mat,(mat->cmap->N)*sizeof(PetscInt));
3320:     PetscMemcpy(a->colmap,oldmat->colmap,(mat->cmap->N)*sizeof(PetscInt));
3321: #endif
3322:   } else a->colmap = 0;
3323:   if (oldmat->garray) {
3324:     PetscInt len;
3325:     len  = oldmat->B->cmap->n;
3326:     PetscMalloc1((len+1),&a->garray);
3327:     PetscLogObjectMemory((PetscObject)mat,len*sizeof(PetscInt));
3328:     if (len) { PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt)); }
3329:   } else a->garray = 0;

3331:   VecDuplicate(oldmat->lvec,&a->lvec);
3332:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
3333:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
3334:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);
3335:   MatDuplicate(oldmat->A,cpvalues,&a->A);
3336:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->A);
3337:   MatDuplicate(oldmat->B,cpvalues,&a->B);
3338:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->B);
3339:   PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
3340:   *newmat = mat;
3341:   return(0);
3342: }



3348: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
3349: {
3350:   PetscScalar    *vals,*svals;
3351:   MPI_Comm       comm;
3353:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
3354:   PetscInt       i,nz,j,rstart,rend,mmax,maxnz = 0,grows,gcols;
3355:   PetscInt       header[4],*rowlengths = 0,M,N,m,*cols;
3356:   PetscInt       *ourlens = NULL,*procsnz = NULL,*offlens = NULL,jj,*mycols,*smycols;
3357:   PetscInt       cend,cstart,n,*rowners,sizesset=1;
3358:   int            fd;
3359:   PetscInt       bs = 1;

3362:   PetscObjectGetComm((PetscObject)viewer,&comm);
3363:   MPI_Comm_size(comm,&size);
3364:   MPI_Comm_rank(comm,&rank);
3365:   if (!rank) {
3366:     PetscViewerBinaryGetDescriptor(viewer,&fd);
3367:     PetscBinaryRead(fd,(char*)header,4,PETSC_INT);
3368:     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
3369:   }

3371:   PetscOptionsBegin(comm,NULL,"Options for loading SEQAIJ matrix","Mat");
3372:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
3373:   PetscOptionsEnd();

3375:   if (newMat->rmap->n < 0 && newMat->rmap->N < 0 && newMat->cmap->n < 0 && newMat->cmap->N < 0) sizesset = 0;

3377:   MPI_Bcast(header+1,3,MPIU_INT,0,comm);
3378:   M    = header[1]; N = header[2];
3379:   /* If global rows/cols are set to PETSC_DECIDE, set it to the sizes given in the file */
3380:   if (sizesset && newMat->rmap->N < 0) newMat->rmap->N = M;
3381:   if (sizesset && newMat->cmap->N < 0) newMat->cmap->N = N;

3383:   /* If global sizes are set, check if they are consistent with that given in the file */
3384:   if (sizesset) {
3385:     MatGetSize(newMat,&grows,&gcols);
3386:   }
3387:   if (sizesset && newMat->rmap->N != grows) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of rows:Matrix in file has (%d) and input matrix has (%d)",M,grows);
3388:   if (sizesset && newMat->cmap->N != gcols) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of cols:Matrix in file has (%d) and input matrix has (%d)",N,gcols);

3390:   /* determine ownership of all (block) rows */
3391:   if (M%bs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of rows (%d) and block size (%d)",M,bs);
3392:   if (newMat->rmap->n < 0) m = bs*((M/bs)/size + (((M/bs) % size) > rank));    /* PETSC_DECIDE */
3393:   else m = newMat->rmap->n; /* Set by user */

3395:   PetscMalloc1((size+1),&rowners);
3396:   MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

3398:   /* First process needs enough room for process with most rows */
3399:   if (!rank) {
3400:     mmax = rowners[1];
3401:     for (i=2; i<=size; i++) {
3402:       mmax = PetscMax(mmax, rowners[i]);
3403:     }
3404:   } else mmax = -1;             /* unused, but compilers complain */

3406:   rowners[0] = 0;
3407:   for (i=2; i<=size; i++) {
3408:     rowners[i] += rowners[i-1];
3409:   }
3410:   rstart = rowners[rank];
3411:   rend   = rowners[rank+1];

3413:   /* distribute row lengths to all processors */
3414:   PetscMalloc2(m,&ourlens,m,&offlens);
3415:   if (!rank) {
3416:     PetscBinaryRead(fd,ourlens,m,PETSC_INT);
3417:     PetscMalloc1(mmax,&rowlengths);
3418:     PetscCalloc1(size,&procsnz);
3419:     for (j=0; j<m; j++) {
3420:       procsnz[0] += ourlens[j];
3421:     }
3422:     for (i=1; i<size; i++) {
3423:       PetscBinaryRead(fd,rowlengths,rowners[i+1]-rowners[i],PETSC_INT);
3424:       /* calculate the number of nonzeros on each processor */
3425:       for (j=0; j<rowners[i+1]-rowners[i]; j++) {
3426:         procsnz[i] += rowlengths[j];
3427:       }
3428:       MPIULong_Send(rowlengths,rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
3429:     }
3430:     PetscFree(rowlengths);
3431:   } else {
3432:     MPIULong_Recv(ourlens,m,MPIU_INT,0,tag,comm);
3433:   }

3435:   if (!rank) {
3436:     /* determine max buffer needed and allocate it */
3437:     maxnz = 0;
3438:     for (i=0; i<size; i++) {
3439:       maxnz = PetscMax(maxnz,procsnz[i]);
3440:     }
3441:     PetscMalloc1(maxnz,&cols);

3443:     /* read in my part of the matrix column indices  */
3444:     nz   = procsnz[0];
3445:     PetscMalloc1(nz,&mycols);
3446:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);

3448:     /* read in every one elses and ship off */
3449:     for (i=1; i<size; i++) {
3450:       nz   = procsnz[i];
3451:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
3452:       MPIULong_Send(cols,nz,MPIU_INT,i,tag,comm);
3453:     }
3454:     PetscFree(cols);
3455:   } else {
3456:     /* determine buffer space needed for message */
3457:     nz = 0;
3458:     for (i=0; i<m; i++) {
3459:       nz += ourlens[i];
3460:     }
3461:     PetscMalloc1(nz,&mycols);

3463:     /* receive message of column indices*/
3464:     MPIULong_Recv(mycols,nz,MPIU_INT,0,tag,comm);
3465:   }

3467:   /* determine column ownership if matrix is not square */
3468:   if (N != M) {
3469:     if (newMat->cmap->n < 0) n = N/size + ((N % size) > rank);
3470:     else n = newMat->cmap->n;
3471:     MPI_Scan(&n,&cend,1,MPIU_INT,MPI_SUM,comm);
3472:     cstart = cend - n;
3473:   } else {
3474:     cstart = rstart;
3475:     cend   = rend;
3476:     n      = cend - cstart;
3477:   }

3479:   /* loop over local rows, determining number of off diagonal entries */
3480:   PetscMemzero(offlens,m*sizeof(PetscInt));
3481:   jj   = 0;
3482:   for (i=0; i<m; i++) {
3483:     for (j=0; j<ourlens[i]; j++) {
3484:       if (mycols[jj] < cstart || mycols[jj] >= cend) offlens[i]++;
3485:       jj++;
3486:     }
3487:   }

3489:   for (i=0; i<m; i++) {
3490:     ourlens[i] -= offlens[i];
3491:   }
3492:   if (!sizesset) {
3493:     MatSetSizes(newMat,m,n,M,N);
3494:   }

3496:   if (bs > 1) {MatSetBlockSize(newMat,bs);}

3498:   MatMPIAIJSetPreallocation(newMat,0,ourlens,0,offlens);

3500:   for (i=0; i<m; i++) {
3501:     ourlens[i] += offlens[i];
3502:   }

3504:   if (!rank) {
3505:     PetscMalloc1((maxnz+1),&vals);

3507:     /* read in my part of the matrix numerical values  */
3508:     nz   = procsnz[0];
3509:     PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);

3511:     /* insert into matrix */
3512:     jj      = rstart;
3513:     smycols = mycols;
3514:     svals   = vals;
3515:     for (i=0; i<m; i++) {
3516:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
3517:       smycols += ourlens[i];
3518:       svals   += ourlens[i];
3519:       jj++;
3520:     }

3522:     /* read in other processors and ship out */
3523:     for (i=1; i<size; i++) {
3524:       nz   = procsnz[i];
3525:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
3526:       MPIULong_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newMat)->tag,comm);
3527:     }
3528:     PetscFree(procsnz);
3529:   } else {
3530:     /* receive numeric values */
3531:     PetscMalloc1((nz+1),&vals);

3533:     /* receive message of values*/
3534:     MPIULong_Recv(vals,nz,MPIU_SCALAR,0,((PetscObject)newMat)->tag,comm);

3536:     /* insert into matrix */
3537:     jj      = rstart;
3538:     smycols = mycols;
3539:     svals   = vals;
3540:     for (i=0; i<m; i++) {
3541:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
3542:       smycols += ourlens[i];
3543:       svals   += ourlens[i];
3544:       jj++;
3545:     }
3546:   }
3547:   PetscFree2(ourlens,offlens);
3548:   PetscFree(vals);
3549:   PetscFree(mycols);
3550:   PetscFree(rowners);
3551:   MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);
3552:   MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);
3553:   return(0);
3554: }

3558: PetscErrorCode MatGetSubMatrix_MPIAIJ(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *newmat)
3559: {
3561:   IS             iscol_local;
3562:   PetscInt       csize;

3565:   ISGetLocalSize(iscol,&csize);
3566:   if (call == MAT_REUSE_MATRIX) {
3567:     PetscObjectQuery((PetscObject)*newmat,"ISAllGather",(PetscObject*)&iscol_local);
3568:     if (!iscol_local) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3569:   } else {
3570:     PetscInt cbs;
3571:     ISGetBlockSize(iscol,&cbs);
3572:     ISAllGather(iscol,&iscol_local);
3573:     ISSetBlockSize(iscol_local,cbs);
3574:   }
3575:   MatGetSubMatrix_MPIAIJ_Private(mat,isrow,iscol_local,csize,call,newmat);
3576:   if (call == MAT_INITIAL_MATRIX) {
3577:     PetscObjectCompose((PetscObject)*newmat,"ISAllGather",(PetscObject)iscol_local);
3578:     ISDestroy(&iscol_local);
3579:   }
3580:   return(0);
3581: }

3583: extern PetscErrorCode MatGetSubMatrices_MPIAIJ_Local(Mat,PetscInt,const IS[],const IS[],MatReuse,PetscBool*,Mat*);
3586: /*
3587:     Not great since it makes two copies of the submatrix, first an SeqAIJ
3588:   in local and then by concatenating the local matrices the end result.
3589:   Writing it directly would be much like MatGetSubMatrices_MPIAIJ()

3591:   Note: This requires a sequential iscol with all indices.
3592: */
3593: PetscErrorCode MatGetSubMatrix_MPIAIJ_Private(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
3594: {
3596:   PetscMPIInt    rank,size;
3597:   PetscInt       i,m,n,rstart,row,rend,nz,*cwork,j,bs,cbs;
3598:   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal,ncol;
3599:   PetscBool      allcolumns, colflag;
3600:   Mat            M,Mreuse;
3601:   MatScalar      *vwork,*aa;
3602:   MPI_Comm       comm;
3603:   Mat_SeqAIJ     *aij;

3606:   PetscObjectGetComm((PetscObject)mat,&comm);
3607:   MPI_Comm_rank(comm,&rank);
3608:   MPI_Comm_size(comm,&size);

3610:   ISIdentity(iscol,&colflag);
3611:   ISGetLocalSize(iscol,&ncol);
3612:   if (colflag && ncol == mat->cmap->N) {
3613:     allcolumns = PETSC_TRUE;
3614:   } else {
3615:     allcolumns = PETSC_FALSE;
3616:   }
3617:   if (call ==  MAT_REUSE_MATRIX) {
3618:     PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Mreuse);
3619:     if (!Mreuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3620:     MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&allcolumns,&Mreuse);
3621:   } else {
3622:     MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&allcolumns,&Mreuse);
3623:   }

3625:   /*
3626:       m - number of local rows
3627:       n - number of columns (same on all processors)
3628:       rstart - first row in new global matrix generated
3629:   */
3630:   MatGetSize(Mreuse,&m,&n);
3631:   MatGetBlockSizes(Mreuse,&bs,&cbs);
3632:   if (call == MAT_INITIAL_MATRIX) {
3633:     aij = (Mat_SeqAIJ*)(Mreuse)->data;
3634:     ii  = aij->i;
3635:     jj  = aij->j;

3637:     /*
3638:         Determine the number of non-zeros in the diagonal and off-diagonal
3639:         portions of the matrix in order to do correct preallocation
3640:     */

3642:     /* first get start and end of "diagonal" columns */
3643:     if (csize == PETSC_DECIDE) {
3644:       ISGetSize(isrow,&mglobal);
3645:       if (mglobal == n) { /* square matrix */
3646:         nlocal = m;
3647:       } else {
3648:         nlocal = n/size + ((n % size) > rank);
3649:       }
3650:     } else {
3651:       nlocal = csize;
3652:     }
3653:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3654:     rstart = rend - nlocal;
3655:     if (rank == size - 1 && rend != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Local column sizes %D do not add up to total number of columns %D",rend,n);

3657:     /* next, compute all the lengths */
3658:     PetscMalloc1((2*m+1),&dlens);
3659:     olens = dlens + m;
3660:     for (i=0; i<m; i++) {
3661:       jend = ii[i+1] - ii[i];
3662:       olen = 0;
3663:       dlen = 0;
3664:       for (j=0; j<jend; j++) {
3665:         if (*jj < rstart || *jj >= rend) olen++;
3666:         else dlen++;
3667:         jj++;
3668:       }
3669:       olens[i] = olen;
3670:       dlens[i] = dlen;
3671:     }
3672:     MatCreate(comm,&M);
3673:     MatSetSizes(M,m,nlocal,PETSC_DECIDE,n);
3674:     MatSetBlockSizes(M,bs,cbs);
3675:     MatSetType(M,((PetscObject)mat)->type_name);
3676:     MatMPIAIJSetPreallocation(M,0,dlens,0,olens);
3677:     PetscFree(dlens);
3678:   } else {
3679:     PetscInt ml,nl;

3681:     M    = *newmat;
3682:     MatGetLocalSize(M,&ml,&nl);
3683:     if (ml != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3684:     MatZeroEntries(M);
3685:     /*
3686:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3687:        rather than the slower MatSetValues().
3688:     */
3689:     M->was_assembled = PETSC_TRUE;
3690:     M->assembled     = PETSC_FALSE;
3691:   }
3692:   MatGetOwnershipRange(M,&rstart,&rend);
3693:   aij  = (Mat_SeqAIJ*)(Mreuse)->data;
3694:   ii   = aij->i;
3695:   jj   = aij->j;
3696:   aa   = aij->a;
3697:   for (i=0; i<m; i++) {
3698:     row   = rstart + i;
3699:     nz    = ii[i+1] - ii[i];
3700:     cwork = jj;     jj += nz;
3701:     vwork = aa;     aa += nz;
3702:     MatSetValues_MPIAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);
3703:   }

3705:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3706:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
3707:   *newmat = M;

3709:   /* save submatrix used in processor for next request */
3710:   if (call ==  MAT_INITIAL_MATRIX) {
3711:     PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);
3712:     MatDestroy(&Mreuse);
3713:   }
3714:   return(0);
3715: }

3719: PetscErrorCode  MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3720: {
3721:   PetscInt       m,cstart, cend,j,nnz,i,d;
3722:   PetscInt       *d_nnz,*o_nnz,nnz_max = 0,rstart,ii;
3723:   const PetscInt *JJ;
3724:   PetscScalar    *values;

3728:   if (Ii[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Ii[0] must be 0 it is %D",Ii[0]);

3730:   PetscLayoutSetUp(B->rmap);
3731:   PetscLayoutSetUp(B->cmap);
3732:   m      = B->rmap->n;
3733:   cstart = B->cmap->rstart;
3734:   cend   = B->cmap->rend;
3735:   rstart = B->rmap->rstart;

3737:   PetscMalloc2(m,&d_nnz,m,&o_nnz);

3739: #if defined(PETSC_USE_DEBUGGING)
3740:   for (i=0; i<m; i++) {
3741:     nnz = Ii[i+1]- Ii[i];
3742:     JJ  = J + Ii[i];
3743:     if (nnz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
3744:     if (nnz && (JJ[0] < 0)) SETERRRQ1(PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,j);
3745:     if (nnz && (JJ[nnz-1] >= B->cmap->N) SETERRRQ3(PETSC_ERR_ARG_WRONGSTATE,"Row %D ends with too large a column index %D (max allowed %D)",i,JJ[nnz-1],B->cmap->N);
3746:   }
3747: #endif

3749:   for (i=0; i<m; i++) {
3750:     nnz     = Ii[i+1]- Ii[i];
3751:     JJ      = J + Ii[i];
3752:     nnz_max = PetscMax(nnz_max,nnz);
3753:     d       = 0;
3754:     for (j=0; j<nnz; j++) {
3755:       if (cstart <= JJ[j] && JJ[j] < cend) d++;
3756:     }
3757:     d_nnz[i] = d;
3758:     o_nnz[i] = nnz - d;
3759:   }
3760:   MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
3761:   PetscFree2(d_nnz,o_nnz);

3763:   if (v) values = (PetscScalar*)v;
3764:   else {
3765:     PetscCalloc1((nnz_max+1),&values);
3766:   }

3768:   for (i=0; i<m; i++) {
3769:     ii   = i + rstart;
3770:     nnz  = Ii[i+1]- Ii[i];
3771:     MatSetValues_MPIAIJ(B,1,&ii,nnz,J+Ii[i],values+(v ? Ii[i] : 0),INSERT_VALUES);
3772:   }
3773:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3774:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

3776:   if (!v) {
3777:     PetscFree(values);
3778:   }
3779:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3780:   return(0);
3781: }

3785: /*@
3786:    MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
3787:    (the default parallel PETSc format).

3789:    Collective on MPI_Comm

3791:    Input Parameters:
3792: +  B - the matrix
3793: .  i - the indices into j for the start of each local row (starts with zero)
3794: .  j - the column indices for each local row (starts with zero)
3795: -  v - optional values in the matrix

3797:    Level: developer

3799:    Notes:
3800:        The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
3801:      thus you CANNOT change the matrix entries by changing the values of a[] after you have
3802:      called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.

3804:        The i and j indices are 0 based, and i indices are indices corresponding to the local j array.

3806:        The format which is used for the sparse matrix input, is equivalent to a
3807:     row-major ordering.. i.e for the following matrix, the input data expected is
3808:     as shown:

3810:         1 0 0
3811:         2 0 3     P0
3812:        -------
3813:         4 5 6     P1

3815:      Process0 [P0]: rows_owned=[0,1]
3816:         i =  {0,1,3}  [size = nrow+1  = 2+1]
3817:         j =  {0,0,2}  [size = nz = 6]
3818:         v =  {1,2,3}  [size = nz = 6]

3820:      Process1 [P1]: rows_owned=[2]
3821:         i =  {0,3}    [size = nrow+1  = 1+1]
3822:         j =  {0,1,2}  [size = nz = 6]
3823:         v =  {4,5,6}  [size = nz = 6]

3825: .keywords: matrix, aij, compressed row, sparse, parallel

3827: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateAIJ(), MPIAIJ,
3828:           MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
3829: @*/
3830: PetscErrorCode  MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
3831: {

3835:   PetscTryMethod(B,"MatMPIAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
3836:   return(0);
3837: }

3841: /*@C
3842:    MatMPIAIJSetPreallocation - Preallocates memory for a sparse parallel matrix in AIJ format
3843:    (the default parallel PETSc format).  For good matrix assembly performance
3844:    the user should preallocate the matrix storage by setting the parameters
3845:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
3846:    performance can be increased by more than a factor of 50.

3848:    Collective on MPI_Comm

3850:    Input Parameters:
3851: +  B - the matrix
3852: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
3853:            (same value is used for all local rows)
3854: .  d_nnz - array containing the number of nonzeros in the various rows of the
3855:            DIAGONAL portion of the local submatrix (possibly different for each row)
3856:            or NULL, if d_nz is used to specify the nonzero structure.
3857:            The size of this array is equal to the number of local rows, i.e 'm'.
3858:            For matrices that will be factored, you must leave room for (and set)
3859:            the diagonal entry even if it is zero.
3860: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
3861:            submatrix (same value is used for all local rows).
3862: -  o_nnz - array containing the number of nonzeros in the various rows of the
3863:            OFF-DIAGONAL portion of the local submatrix (possibly different for
3864:            each row) or NULL, if o_nz is used to specify the nonzero
3865:            structure. The size of this array is equal to the number
3866:            of local rows, i.e 'm'.

3868:    If the *_nnz parameter is given then the *_nz parameter is ignored

3870:    The AIJ format (also called the Yale sparse matrix format or
3871:    compressed row storage (CSR)), is fully compatible with standard Fortran 77
3872:    storage.  The stored row and column indices begin with zero.
3873:    See Users-Manual: ch_mat for details.

3875:    The parallel matrix is partitioned such that the first m0 rows belong to
3876:    process 0, the next m1 rows belong to process 1, the next m2 rows belong
3877:    to process 2 etc.. where m0,m1,m2... are the input parameter 'm'.

3879:    The DIAGONAL portion of the local submatrix of a processor can be defined
3880:    as the submatrix which is obtained by extraction the part corresponding to
3881:    the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
3882:    first row that belongs to the processor, r2 is the last row belonging to
3883:    the this processor, and c1-c2 is range of indices of the local part of a
3884:    vector suitable for applying the matrix to.  This is an mxn matrix.  In the
3885:    common case of a square matrix, the row and column ranges are the same and
3886:    the DIAGONAL part is also square. The remaining portion of the local
3887:    submatrix (mxN) constitute the OFF-DIAGONAL portion.

3889:    If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.

3891:    You can call MatGetInfo() to get information on how effective the preallocation was;
3892:    for example the fields mallocs,nz_allocated,nz_used,nz_unneeded;
3893:    You can also run with the option -info and look for messages with the string
3894:    malloc in them to see if additional memory allocation was needed.

3896:    Example usage:

3898:    Consider the following 8x8 matrix with 34 non-zero values, that is
3899:    assembled across 3 processors. Lets assume that proc0 owns 3 rows,
3900:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
3901:    as follows:

3903: .vb
3904:             1  2  0  |  0  3  0  |  0  4
3905:     Proc0   0  5  6  |  7  0  0  |  8  0
3906:             9  0 10  | 11  0  0  | 12  0
3907:     -------------------------------------
3908:            13  0 14  | 15 16 17  |  0  0
3909:     Proc1   0 18  0  | 19 20 21  |  0  0
3910:             0  0  0  | 22 23  0  | 24  0
3911:     -------------------------------------
3912:     Proc2  25 26 27  |  0  0 28  | 29  0
3913:            30  0  0  | 31 32 33  |  0 34
3914: .ve

3916:    This can be represented as a collection of submatrices as:

3918: .vb
3919:       A B C
3920:       D E F
3921:       G H I
3922: .ve

3924:    Where the submatrices A,B,C are owned by proc0, D,E,F are
3925:    owned by proc1, G,H,I are owned by proc2.

3927:    The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3928:    The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
3929:    The 'M','N' parameters are 8,8, and have the same values on all procs.

3931:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
3932:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
3933:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
3934:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
3935:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
3936:    matrix, ans [DF] as another SeqAIJ matrix.

3938:    When d_nz, o_nz parameters are specified, d_nz storage elements are
3939:    allocated for every row of the local diagonal submatrix, and o_nz
3940:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
3941:    One way to choose d_nz and o_nz is to use the max nonzerors per local
3942:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
3943:    In this case, the values of d_nz,o_nz are:
3944: .vb
3945:      proc0 : dnz = 2, o_nz = 2
3946:      proc1 : dnz = 3, o_nz = 2
3947:      proc2 : dnz = 1, o_nz = 4
3948: .ve
3949:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
3950:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
3951:    for proc3. i.e we are using 12+15+10=37 storage locations to store
3952:    34 values.

3954:    When d_nnz, o_nnz parameters are specified, the storage is specified
3955:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
3956:    In the above case the values for d_nnz,o_nnz are:
3957: .vb
3958:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
3959:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
3960:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
3961: .ve
3962:    Here the space allocated is sum of all the above values i.e 34, and
3963:    hence pre-allocation is perfect.

3965:    Level: intermediate

3967: .keywords: matrix, aij, compressed row, sparse, parallel

3969: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateAIJ(), MatMPIAIJSetPreallocationCSR(),
3970:           MPIAIJ, MatGetInfo(), PetscSplitOwnership()
3971: @*/
3972: PetscErrorCode  MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3973: {

3979:   PetscTryMethod(B,"MatMPIAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
3980:   return(0);
3981: }

3985: /*@
3986:      MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
3987:          CSR format the local rows.

3989:    Collective on MPI_Comm

3991:    Input Parameters:
3992: +  comm - MPI communicator
3993: .  m - number of local rows (Cannot be PETSC_DECIDE)
3994: .  n - This value should be the same as the local size used in creating the
3995:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
3996:        calculated if N is given) For square matrices n is almost always m.
3997: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3998: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3999: .   i - row indices
4000: .   j - column indices
4001: -   a - matrix values

4003:    Output Parameter:
4004: .   mat - the matrix

4006:    Level: intermediate

4008:    Notes:
4009:        The i, j, and a arrays ARE copied by this routine into the internal format used by PETSc;
4010:      thus you CANNOT change the matrix entries by changing the values of a[] after you have
4011:      called this routine. Use MatCreateMPIAIJWithSplitArrays() to avoid needing to copy the arrays.

4013:        The i and j indices are 0 based, and i indices are indices corresponding to the local j array.

4015:        The format which is used for the sparse matrix input, is equivalent to a
4016:     row-major ordering.. i.e for the following matrix, the input data expected is
4017:     as shown:

4019:         1 0 0
4020:         2 0 3     P0
4021:        -------
4022:         4 5 6     P1

4024:      Process0 [P0]: rows_owned=[0,1]
4025:         i =  {0,1,3}  [size = nrow+1  = 2+1]
4026:         j =  {0,0,2}  [size = nz = 6]
4027:         v =  {1,2,3}  [size = nz = 6]

4029:      Process1 [P1]: rows_owned=[2]
4030:         i =  {0,3}    [size = nrow+1  = 1+1]
4031:         j =  {0,1,2}  [size = nz = 6]
4032:         v =  {4,5,6}  [size = nz = 6]

4034: .keywords: matrix, aij, compressed row, sparse, parallel

4036: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4037:           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
4038: @*/
4039: PetscErrorCode  MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
4040: {

4044:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4045:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4046:   MatCreate(comm,mat);
4047:   MatSetSizes(*mat,m,n,M,N);
4048:   /* MatSetBlockSizes(M,bs,cbs); */
4049:   MatSetType(*mat,MATMPIAIJ);
4050:   MatMPIAIJSetPreallocationCSR(*mat,i,j,a);
4051:   return(0);
4052: }

4056: /*@C
4057:    MatCreateAIJ - Creates a sparse parallel matrix in AIJ format
4058:    (the default parallel PETSc format).  For good matrix assembly performance
4059:    the user should preallocate the matrix storage by setting the parameters
4060:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
4061:    performance can be increased by more than a factor of 50.

4063:    Collective on MPI_Comm

4065:    Input Parameters:
4066: +  comm - MPI communicator
4067: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
4068:            This value should be the same as the local size used in creating the
4069:            y vector for the matrix-vector product y = Ax.
4070: .  n - This value should be the same as the local size used in creating the
4071:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4072:        calculated if N is given) For square matrices n is almost always m.
4073: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4074: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4075: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4076:            (same value is used for all local rows)
4077: .  d_nnz - array containing the number of nonzeros in the various rows of the
4078:            DIAGONAL portion of the local submatrix (possibly different for each row)
4079:            or NULL, if d_nz is used to specify the nonzero structure.
4080:            The size of this array is equal to the number of local rows, i.e 'm'.
4081: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4082:            submatrix (same value is used for all local rows).
4083: -  o_nnz - array containing the number of nonzeros in the various rows of the
4084:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4085:            each row) or NULL, if o_nz is used to specify the nonzero
4086:            structure. The size of this array is equal to the number
4087:            of local rows, i.e 'm'.

4089:    Output Parameter:
4090: .  A - the matrix

4092:    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
4093:    MatXXXXSetPreallocation() paradgm instead of this routine directly.
4094:    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]

4096:    Notes:
4097:    If the *_nnz parameter is given then the *_nz parameter is ignored

4099:    m,n,M,N parameters specify the size of the matrix, and its partitioning across
4100:    processors, while d_nz,d_nnz,o_nz,o_nnz parameters specify the approximate
4101:    storage requirements for this matrix.

4103:    If PETSC_DECIDE or  PETSC_DETERMINE is used for a particular argument on one
4104:    processor than it must be used on all processors that share the object for
4105:    that argument.

4107:    The user MUST specify either the local or global matrix dimensions
4108:    (possibly both).

4110:    The parallel matrix is partitioned across processors such that the
4111:    first m0 rows belong to process 0, the next m1 rows belong to
4112:    process 1, the next m2 rows belong to process 2 etc.. where
4113:    m0,m1,m2,.. are the input parameter 'm'. i.e each processor stores
4114:    values corresponding to [m x N] submatrix.

4116:    The columns are logically partitioned with the n0 columns belonging
4117:    to 0th partition, the next n1 columns belonging to the next
4118:    partition etc.. where n0,n1,n2... are the input parameter 'n'.

4120:    The DIAGONAL portion of the local submatrix on any given processor
4121:    is the submatrix corresponding to the rows and columns m,n
4122:    corresponding to the given processor. i.e diagonal matrix on
4123:    process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4124:    etc. The remaining portion of the local submatrix [m x (N-n)]
4125:    constitute the OFF-DIAGONAL portion. The example below better
4126:    illustrates this concept.

4128:    For a square global matrix we define each processor's diagonal portion
4129:    to be its local rows and the corresponding columns (a square submatrix);
4130:    each processor's off-diagonal portion encompasses the remainder of the
4131:    local matrix (a rectangular submatrix).

4133:    If o_nnz, d_nnz are specified, then o_nz, and d_nz are ignored.

4135:    When calling this routine with a single process communicator, a matrix of
4136:    type SEQAIJ is returned.  If a matrix of type MPIAIJ is desired for this
4137:    type of communicator, use the construction mechanism:
4138:      MatCreate(...,&A); MatSetType(A,MATMPIAIJ); MatSetSizes(A, m,n,M,N); MatMPIAIJSetPreallocation(A,...);

4140:    By default, this format uses inodes (identical nodes) when possible.
4141:    We search for consecutive rows with the same nonzero structure, thereby
4142:    reusing matrix information to achieve increased efficiency.

4144:    Options Database Keys:
4145: +  -mat_no_inode  - Do not use inodes
4146: .  -mat_inode_limit <limit> - Sets inode limit (max limit=5)
4147: -  -mat_aij_oneindex - Internally use indexing starting at 1
4148:         rather than 0.  Note that when calling MatSetValues(),
4149:         the user still MUST index entries starting at 0!


4152:    Example usage:

4154:    Consider the following 8x8 matrix with 34 non-zero values, that is
4155:    assembled across 3 processors. Lets assume that proc0 owns 3 rows,
4156:    proc1 owns 3 rows, proc2 owns 2 rows. This division can be shown
4157:    as follows:

4159: .vb
4160:             1  2  0  |  0  3  0  |  0  4
4161:     Proc0   0  5  6  |  7  0  0  |  8  0
4162:             9  0 10  | 11  0  0  | 12  0
4163:     -------------------------------------
4164:            13  0 14  | 15 16 17  |  0  0
4165:     Proc1   0 18  0  | 19 20 21  |  0  0
4166:             0  0  0  | 22 23  0  | 24  0
4167:     -------------------------------------
4168:     Proc2  25 26 27  |  0  0 28  | 29  0
4169:            30  0  0  | 31 32 33  |  0 34
4170: .ve

4172:    This can be represented as a collection of submatrices as:

4174: .vb
4175:       A B C
4176:       D E F
4177:       G H I
4178: .ve

4180:    Where the submatrices A,B,C are owned by proc0, D,E,F are
4181:    owned by proc1, G,H,I are owned by proc2.

4183:    The 'm' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4184:    The 'n' parameters for proc0,proc1,proc2 are 3,3,2 respectively.
4185:    The 'M','N' parameters are 8,8, and have the same values on all procs.

4187:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4188:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4189:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4190:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4191:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4192:    matrix, ans [DF] as another SeqAIJ matrix.

4194:    When d_nz, o_nz parameters are specified, d_nz storage elements are
4195:    allocated for every row of the local diagonal submatrix, and o_nz
4196:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4197:    One way to choose d_nz and o_nz is to use the max nonzerors per local
4198:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4199:    In this case, the values of d_nz,o_nz are:
4200: .vb
4201:      proc0 : dnz = 2, o_nz = 2
4202:      proc1 : dnz = 3, o_nz = 2
4203:      proc2 : dnz = 1, o_nz = 4
4204: .ve
4205:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4206:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4207:    for proc3. i.e we are using 12+15+10=37 storage locations to store
4208:    34 values.

4210:    When d_nnz, o_nnz parameters are specified, the storage is specified
4211:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4212:    In the above case the values for d_nnz,o_nnz are:
4213: .vb
4214:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4215:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4216:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4217: .ve
4218:    Here the space allocated is sum of all the above values i.e 34, and
4219:    hence pre-allocation is perfect.

4221:    Level: intermediate

4223: .keywords: matrix, aij, compressed row, sparse, parallel

4225: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4226:           MPIAIJ, MatCreateMPIAIJWithArrays()
4227: @*/
4228: PetscErrorCode  MatCreateAIJ(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[],Mat *A)
4229: {
4231:   PetscMPIInt    size;

4234:   MatCreate(comm,A);
4235:   MatSetSizes(*A,m,n,M,N);
4236:   MPI_Comm_size(comm,&size);
4237:   if (size > 1) {
4238:     MatSetType(*A,MATMPIAIJ);
4239:     MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);
4240:   } else {
4241:     MatSetType(*A,MATSEQAIJ);
4242:     MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);
4243:   }
4244:   return(0);
4245: }

4249: PetscErrorCode  MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
4250: {
4251:   Mat_MPIAIJ *a = (Mat_MPIAIJ*)A->data;

4254:   if (Ad)     *Ad     = a->A;
4255:   if (Ao)     *Ao     = a->B;
4256:   if (colmap) *colmap = a->garray;
4257:   return(0);
4258: }

4262: PetscErrorCode MatSetColoring_MPIAIJ(Mat A,ISColoring coloring)
4263: {
4265:   PetscInt       i;
4266:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

4269:   if (coloring->ctype == IS_COLORING_GLOBAL) {
4270:     ISColoringValue *allcolors,*colors;
4271:     ISColoring      ocoloring;

4273:     /* set coloring for diagonal portion */
4274:     MatSetColoring_SeqAIJ(a->A,coloring);

4276:     /* set coloring for off-diagonal portion */
4277:     ISAllGatherColors(PetscObjectComm((PetscObject)A),coloring->n,coloring->colors,NULL,&allcolors);
4278:     PetscMalloc1((a->B->cmap->n+1),&colors);
4279:     for (i=0; i<a->B->cmap->n; i++) {
4280:       colors[i] = allcolors[a->garray[i]];
4281:     }
4282:     PetscFree(allcolors);
4283:     ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);
4284:     MatSetColoring_SeqAIJ(a->B,ocoloring);
4285:     ISColoringDestroy(&ocoloring);
4286:   } else if (coloring->ctype == IS_COLORING_GHOSTED) {
4287:     ISColoringValue *colors;
4288:     PetscInt        *larray;
4289:     ISColoring      ocoloring;

4291:     /* set coloring for diagonal portion */
4292:     PetscMalloc1((a->A->cmap->n+1),&larray);
4293:     for (i=0; i<a->A->cmap->n; i++) {
4294:       larray[i] = i + A->cmap->rstart;
4295:     }
4296:     ISGlobalToLocalMappingApply(A->cmap->mapping,IS_GTOLM_MASK,a->A->cmap->n,larray,NULL,larray);
4297:     PetscMalloc1((a->A->cmap->n+1),&colors);
4298:     for (i=0; i<a->A->cmap->n; i++) {
4299:       colors[i] = coloring->colors[larray[i]];
4300:     }
4301:     PetscFree(larray);
4302:     ISColoringCreate(PETSC_COMM_SELF,coloring->n,a->A->cmap->n,colors,&ocoloring);
4303:     MatSetColoring_SeqAIJ(a->A,ocoloring);
4304:     ISColoringDestroy(&ocoloring);

4306:     /* set coloring for off-diagonal portion */
4307:     PetscMalloc1((a->B->cmap->n+1),&larray);
4308:     ISGlobalToLocalMappingApply(A->cmap->mapping,IS_GTOLM_MASK,a->B->cmap->n,a->garray,NULL,larray);
4309:     PetscMalloc1((a->B->cmap->n+1),&colors);
4310:     for (i=0; i<a->B->cmap->n; i++) {
4311:       colors[i] = coloring->colors[larray[i]];
4312:     }
4313:     PetscFree(larray);
4314:     ISColoringCreate(MPI_COMM_SELF,coloring->n,a->B->cmap->n,colors,&ocoloring);
4315:     MatSetColoring_SeqAIJ(a->B,ocoloring);
4316:     ISColoringDestroy(&ocoloring);
4317:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support ISColoringType %d",(int)coloring->ctype);
4318:   return(0);
4319: }

4323: PetscErrorCode MatSetValuesAdifor_MPIAIJ(Mat A,PetscInt nl,void *advalues)
4324: {
4325:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

4329:   MatSetValuesAdifor_SeqAIJ(a->A,nl,advalues);
4330:   MatSetValuesAdifor_SeqAIJ(a->B,nl,advalues);
4331:   return(0);
4332: }

4336: PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJSymbolic(MPI_Comm comm,Mat inmat,PetscInt n,Mat *outmat)
4337: {
4339:   PetscInt       m,N,i,rstart,nnz,*dnz,*onz,sum,bs,cbs;
4340:   PetscInt       *indx;

4343:   /* This routine will ONLY return MPIAIJ type matrix */
4344:   MatGetSize(inmat,&m,&N);
4345:   MatGetBlockSizes(inmat,&bs,&cbs);
4346:   if (n == PETSC_DECIDE) {
4347:     PetscSplitOwnership(comm,&n,&N);
4348:   }
4349:   /* Check sum(n) = N */
4350:   MPI_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);
4351:   if (sum != N) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns != global columns %d",N);

4353:   MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);
4354:   rstart -= m;

4356:   MatPreallocateInitialize(comm,m,n,dnz,onz);
4357:   for (i=0; i<m; i++) {
4358:     MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4359:     MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);
4360:     MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4361:   }

4363:   MatCreate(comm,outmat);
4364:   MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4365:   MatSetBlockSizes(*outmat,bs,cbs);
4366:   MatSetType(*outmat,MATMPIAIJ);
4367:   MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);
4368:   MatPreallocateFinalize(dnz,onz);
4369:   return(0);
4370: }

4374: PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJNumeric(MPI_Comm comm,Mat inmat,PetscInt n,Mat outmat)
4375: {
4377:   PetscInt       m,N,i,rstart,nnz,Ii;
4378:   PetscInt       *indx;
4379:   PetscScalar    *values;

4382:   MatGetSize(inmat,&m,&N);
4383:   MatGetOwnershipRange(outmat,&rstart,NULL);
4384:   for (i=0; i<m; i++) {
4385:     MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4386:     Ii   = i + rstart;
4387:     MatSetValues(outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
4388:     MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4389:   }
4390:   MatAssemblyBegin(outmat,MAT_FINAL_ASSEMBLY);
4391:   MatAssemblyEnd(outmat,MAT_FINAL_ASSEMBLY);
4392:   return(0);
4393: }

4397: /*@
4398:       MatCreateMPIAIJConcatenateSeqAIJ - Creates a single large PETSc matrix by concatenating sequential
4399:                  matrices from each processor

4401:     Collective on MPI_Comm

4403:    Input Parameters:
4404: +    comm - the communicators the parallel matrix will live on
4405: .    inmat - the input sequential matrices
4406: .    n - number of local columns (or PETSC_DECIDE)
4407: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4409:    Output Parameter:
4410: .    outmat - the parallel matrix generated

4412:     Level: advanced

4414:    Notes: The number of columns of the matrix in EACH processor MUST be the same.

4416: @*/
4417: PetscErrorCode  MatCreateMPIAIJConcatenateSeqAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4418: {
4420:   PetscMPIInt    size;

4423:   MPI_Comm_size(comm,&size);
4424:   PetscLogEventBegin(MAT_Merge,inmat,0,0,0);
4425:   if (size == 1) {
4426:     if (scall == MAT_INITIAL_MATRIX) {
4427:       MatDuplicate(inmat,MAT_COPY_VALUES,outmat);
4428:     } else {
4429:       MatCopy(inmat,*outmat,SAME_NONZERO_PATTERN);
4430:     }
4431:   } else {
4432:     if (scall == MAT_INITIAL_MATRIX) {
4433:       MatCreateMPIAIJConcatenateSeqAIJSymbolic(comm,inmat,n,outmat);
4434:     }
4435:     MatCreateMPIAIJConcatenateSeqAIJNumeric(comm,inmat,n,*outmat);
4436:   }
4437:   PetscLogEventEnd(MAT_Merge,inmat,0,0,0);
4438:   return(0);
4439: }

4443: PetscErrorCode MatFileSplit(Mat A,char *outfile)
4444: {
4445:   PetscErrorCode    ierr;
4446:   PetscMPIInt       rank;
4447:   PetscInt          m,N,i,rstart,nnz;
4448:   size_t            len;
4449:   const PetscInt    *indx;
4450:   PetscViewer       out;
4451:   char              *name;
4452:   Mat               B;
4453:   const PetscScalar *values;

4456:   MatGetLocalSize(A,&m,0);
4457:   MatGetSize(A,0,&N);
4458:   /* Should this be the type of the diagonal block of A? */
4459:   MatCreate(PETSC_COMM_SELF,&B);
4460:   MatSetSizes(B,m,N,m,N);
4461:   MatSetBlockSizesFromMats(B,A,A);
4462:   MatSetType(B,MATSEQAIJ);
4463:   MatSeqAIJSetPreallocation(B,0,NULL);
4464:   MatGetOwnershipRange(A,&rstart,0);
4465:   for (i=0; i<m; i++) {
4466:     MatGetRow(A,i+rstart,&nnz,&indx,&values);
4467:     MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);
4468:     MatRestoreRow(A,i+rstart,&nnz,&indx,&values);
4469:   }
4470:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4471:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

4473:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);
4474:   PetscStrlen(outfile,&len);
4475:   PetscMalloc1((len+5),&name);
4476:   sprintf(name,"%s.%d",outfile,rank);
4477:   PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);
4478:   PetscFree(name);
4479:   MatView(B,out);
4480:   PetscViewerDestroy(&out);
4481:   MatDestroy(&B);
4482:   return(0);
4483: }

4485: extern PetscErrorCode MatDestroy_MPIAIJ(Mat);
4488: PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
4489: {
4490:   PetscErrorCode      ierr;
4491:   Mat_Merge_SeqsToMPI *merge;
4492:   PetscContainer      container;

4495:   PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject*)&container);
4496:   if (container) {
4497:     PetscContainerGetPointer(container,(void**)&merge);
4498:     PetscFree(merge->id_r);
4499:     PetscFree(merge->len_s);
4500:     PetscFree(merge->len_r);
4501:     PetscFree(merge->bi);
4502:     PetscFree(merge->bj);
4503:     PetscFree(merge->buf_ri[0]);
4504:     PetscFree(merge->buf_ri);
4505:     PetscFree(merge->buf_rj[0]);
4506:     PetscFree(merge->buf_rj);
4507:     PetscFree(merge->coi);
4508:     PetscFree(merge->coj);
4509:     PetscFree(merge->owners_co);
4510:     PetscLayoutDestroy(&merge->rowmap);
4511:     PetscFree(merge);
4512:     PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);
4513:   }
4514:   MatDestroy_MPIAIJ(A);
4515:   return(0);
4516: }

4518: #include <../src/mat/utils/freespace.h>
4519: #include <petscbt.h>

4523: PetscErrorCode  MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat,Mat mpimat)
4524: {
4525:   PetscErrorCode      ierr;
4526:   MPI_Comm            comm;
4527:   Mat_SeqAIJ          *a  =(Mat_SeqAIJ*)seqmat->data;
4528:   PetscMPIInt         size,rank,taga,*len_s;
4529:   PetscInt            N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj;
4530:   PetscInt            proc,m;
4531:   PetscInt            **buf_ri,**buf_rj;
4532:   PetscInt            k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
4533:   PetscInt            nrows,**buf_ri_k,**nextrow,**nextai;
4534:   MPI_Request         *s_waits,*r_waits;
4535:   MPI_Status          *status;
4536:   MatScalar           *aa=a->a;
4537:   MatScalar           **abuf_r,*ba_i;
4538:   Mat_Merge_SeqsToMPI *merge;
4539:   PetscContainer      container;

4542:   PetscObjectGetComm((PetscObject)mpimat,&comm);
4543:   PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);

4545:   MPI_Comm_size(comm,&size);
4546:   MPI_Comm_rank(comm,&rank);

4548:   PetscObjectQuery((PetscObject)mpimat,"MatMergeSeqsToMPI",(PetscObject*)&container);
4549:   PetscContainerGetPointer(container,(void**)&merge);

4551:   bi     = merge->bi;
4552:   bj     = merge->bj;
4553:   buf_ri = merge->buf_ri;
4554:   buf_rj = merge->buf_rj;

4556:   PetscMalloc1(size,&status);
4557:   owners = merge->rowmap->range;
4558:   len_s  = merge->len_s;

4560:   /* send and recv matrix values */
4561:   /*-----------------------------*/
4562:   PetscObjectGetNewTag((PetscObject)mpimat,&taga);
4563:   PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);

4565:   PetscMalloc1((merge->nsend+1),&s_waits);
4566:   for (proc=0,k=0; proc<size; proc++) {
4567:     if (!len_s[proc]) continue;
4568:     i    = owners[proc];
4569:     MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
4570:     k++;
4571:   }

4573:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
4574:   if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}
4575:   PetscFree(status);

4577:   PetscFree(s_waits);
4578:   PetscFree(r_waits);

4580:   /* insert mat values of mpimat */
4581:   /*----------------------------*/
4582:   PetscMalloc1(N,&ba_i);
4583:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextai);

4585:   for (k=0; k<merge->nrecv; k++) {
4586:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4587:     nrows       = *(buf_ri_k[k]);
4588:     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
4589:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4590:   }

4592:   /* set values of ba */
4593:   m = merge->rowmap->n;
4594:   for (i=0; i<m; i++) {
4595:     arow = owners[rank] + i;
4596:     bj_i = bj+bi[i];  /* col indices of the i-th row of mpimat */
4597:     bnzi = bi[i+1] - bi[i];
4598:     PetscMemzero(ba_i,bnzi*sizeof(PetscScalar));

4600:     /* add local non-zero vals of this proc's seqmat into ba */
4601:     anzi   = ai[arow+1] - ai[arow];
4602:     aj     = a->j + ai[arow];
4603:     aa     = a->a + ai[arow];
4604:     nextaj = 0;
4605:     for (j=0; nextaj<anzi; j++) {
4606:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4607:         ba_i[j] += aa[nextaj++];
4608:       }
4609:     }

4611:     /* add received vals into ba */
4612:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4613:       /* i-th row */
4614:       if (i == *nextrow[k]) {
4615:         anzi   = *(nextai[k]+1) - *nextai[k];
4616:         aj     = buf_rj[k] + *(nextai[k]);
4617:         aa     = abuf_r[k] + *(nextai[k]);
4618:         nextaj = 0;
4619:         for (j=0; nextaj<anzi; j++) {
4620:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4621:             ba_i[j] += aa[nextaj++];
4622:           }
4623:         }
4624:         nextrow[k]++; nextai[k]++;
4625:       }
4626:     }
4627:     MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);
4628:   }
4629:   MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);
4630:   MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);

4632:   PetscFree(abuf_r[0]);
4633:   PetscFree(abuf_r);
4634:   PetscFree(ba_i);
4635:   PetscFree3(buf_ri_k,nextrow,nextai);
4636:   PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);
4637:   return(0);
4638: }

4640: extern PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat);

4644: PetscErrorCode  MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
4645: {
4646:   PetscErrorCode      ierr;
4647:   Mat                 B_mpi;
4648:   Mat_SeqAIJ          *a=(Mat_SeqAIJ*)seqmat->data;
4649:   PetscMPIInt         size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
4650:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
4651:   PetscInt            M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
4652:   PetscInt            len,proc,*dnz,*onz,bs,cbs;
4653:   PetscInt            k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
4654:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
4655:   MPI_Request         *si_waits,*sj_waits,*ri_waits,*rj_waits;
4656:   MPI_Status          *status;
4657:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
4658:   PetscBT             lnkbt;
4659:   Mat_Merge_SeqsToMPI *merge;
4660:   PetscContainer      container;

4663:   PetscLogEventBegin(MAT_Seqstompisym,seqmat,0,0,0);

4665:   /* make sure it is a PETSc comm */
4666:   PetscCommDuplicate(comm,&comm,NULL);
4667:   MPI_Comm_size(comm,&size);
4668:   MPI_Comm_rank(comm,&rank);

4670:   PetscNew(&merge);
4671:   PetscMalloc1(size,&status);

4673:   /* determine row ownership */
4674:   /*---------------------------------------------------------*/
4675:   PetscLayoutCreate(comm,&merge->rowmap);
4676:   PetscLayoutSetLocalSize(merge->rowmap,m);
4677:   PetscLayoutSetSize(merge->rowmap,M);
4678:   PetscLayoutSetBlockSize(merge->rowmap,1);
4679:   PetscLayoutSetUp(merge->rowmap);
4680:   PetscMalloc1(size,&len_si);
4681:   PetscMalloc1(size,&merge->len_s);

4683:   m      = merge->rowmap->n;
4684:   owners = merge->rowmap->range;

4686:   /* determine the number of messages to send, their lengths */
4687:   /*---------------------------------------------------------*/
4688:   len_s = merge->len_s;

4690:   len          = 0; /* length of buf_si[] */
4691:   merge->nsend = 0;
4692:   for (proc=0; proc<size; proc++) {
4693:     len_si[proc] = 0;
4694:     if (proc == rank) {
4695:       len_s[proc] = 0;
4696:     } else {
4697:       len_si[proc] = owners[proc+1] - owners[proc] + 1;
4698:       len_s[proc]  = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
4699:     }
4700:     if (len_s[proc]) {
4701:       merge->nsend++;
4702:       nrows = 0;
4703:       for (i=owners[proc]; i<owners[proc+1]; i++) {
4704:         if (ai[i+1] > ai[i]) nrows++;
4705:       }
4706:       len_si[proc] = 2*(nrows+1);
4707:       len         += len_si[proc];
4708:     }
4709:   }

4711:   /* determine the number and length of messages to receive for ij-structure */
4712:   /*-------------------------------------------------------------------------*/
4713:   PetscGatherNumberOfMessages(comm,NULL,len_s,&merge->nrecv);
4714:   PetscGatherMessageLengths2(comm,merge->nsend,merge->nrecv,len_s,len_si,&merge->id_r,&merge->len_r,&len_ri);

4716:   /* post the Irecv of j-structure */
4717:   /*-------------------------------*/
4718:   PetscCommGetNewTag(comm,&tagj);
4719:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);

4721:   /* post the Isend of j-structure */
4722:   /*--------------------------------*/
4723:   PetscMalloc2(merge->nsend,&si_waits,merge->nsend,&sj_waits);

4725:   for (proc=0, k=0; proc<size; proc++) {
4726:     if (!len_s[proc]) continue;
4727:     i    = owners[proc];
4728:     MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);
4729:     k++;
4730:   }

4732:   /* receives and sends of j-structure are complete */
4733:   /*------------------------------------------------*/
4734:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,rj_waits,status);}
4735:   if (merge->nsend) {MPI_Waitall(merge->nsend,sj_waits,status);}

4737:   /* send and recv i-structure */
4738:   /*---------------------------*/
4739:   PetscCommGetNewTag(comm,&tagi);
4740:   PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);

4742:   PetscMalloc1((len+1),&buf_s);
4743:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
4744:   for (proc=0,k=0; proc<size; proc++) {
4745:     if (!len_s[proc]) continue;
4746:     /* form outgoing message for i-structure:
4747:          buf_si[0]:                 nrows to be sent
4748:                [1:nrows]:           row index (global)
4749:                [nrows+1:2*nrows+1]: i-structure index
4750:     */
4751:     /*-------------------------------------------*/
4752:     nrows       = len_si[proc]/2 - 1;
4753:     buf_si_i    = buf_si + nrows+1;
4754:     buf_si[0]   = nrows;
4755:     buf_si_i[0] = 0;
4756:     nrows       = 0;
4757:     for (i=owners[proc]; i<owners[proc+1]; i++) {
4758:       anzi = ai[i+1] - ai[i];
4759:       if (anzi) {
4760:         buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
4761:         buf_si[nrows+1]   = i-owners[proc]; /* local row index */
4762:         nrows++;
4763:       }
4764:     }
4765:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);
4766:     k++;
4767:     buf_si += len_si[proc];
4768:   }

4770:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,ri_waits,status);}
4771:   if (merge->nsend) {MPI_Waitall(merge->nsend,si_waits,status);}

4773:   PetscInfo2(seqmat,"nsend: %D, nrecv: %D\n",merge->nsend,merge->nrecv);
4774:   for (i=0; i<merge->nrecv; i++) {
4775:     PetscInfo3(seqmat,"recv len_ri=%D, len_rj=%D from [%D]\n",len_ri[i],merge->len_r[i],merge->id_r[i]);
4776:   }

4778:   PetscFree(len_si);
4779:   PetscFree(len_ri);
4780:   PetscFree(rj_waits);
4781:   PetscFree2(si_waits,sj_waits);
4782:   PetscFree(ri_waits);
4783:   PetscFree(buf_s);
4784:   PetscFree(status);

4786:   /* compute a local seq matrix in each processor */
4787:   /*----------------------------------------------*/
4788:   /* allocate bi array and free space for accumulating nonzero column info */
4789:   PetscMalloc1((m+1),&bi);
4790:   bi[0] = 0;

4792:   /* create and initialize a linked list */
4793:   nlnk = N+1;
4794:   PetscLLCreate(N,N,nlnk,lnk,lnkbt);

4796:   /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4797:   len  = ai[owners[rank+1]] - ai[owners[rank]];
4798:   PetscFreeSpaceGet((PetscInt)(2*len+1),&free_space);

4800:   current_space = free_space;

4802:   /* determine symbolic info for each local row */
4803:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextai);

4805:   for (k=0; k<merge->nrecv; k++) {
4806:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4807:     nrows       = *buf_ri_k[k];
4808:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
4809:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4810:   }

4812:   MatPreallocateInitialize(comm,m,n,dnz,onz);
4813:   len  = 0;
4814:   for (i=0; i<m; i++) {
4815:     bnzi = 0;
4816:     /* add local non-zero cols of this proc's seqmat into lnk */
4817:     arow  = owners[rank] + i;
4818:     anzi  = ai[arow+1] - ai[arow];
4819:     aj    = a->j + ai[arow];
4820:     PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4821:     bnzi += nlnk;
4822:     /* add received col data into lnk */
4823:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4824:       if (i == *nextrow[k]) { /* i-th row */
4825:         anzi  = *(nextai[k]+1) - *nextai[k];
4826:         aj    = buf_rj[k] + *nextai[k];
4827:         PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4828:         bnzi += nlnk;
4829:         nextrow[k]++; nextai[k]++;
4830:       }
4831:     }
4832:     if (len < bnzi) len = bnzi;  /* =max(bnzi) */

4834:     /* if free space is not available, make more free space */
4835:     if (current_space->local_remaining<bnzi) {
4836:       PetscFreeSpaceGet(bnzi+current_space->total_array_size,&current_space);
4837:       nspacedouble++;
4838:     }
4839:     /* copy data into free space, then initialize lnk */
4840:     PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);
4841:     MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);

4843:     current_space->array           += bnzi;
4844:     current_space->local_used      += bnzi;
4845:     current_space->local_remaining -= bnzi;

4847:     bi[i+1] = bi[i] + bnzi;
4848:   }

4850:   PetscFree3(buf_ri_k,nextrow,nextai);

4852:   PetscMalloc1((bi[m]+1),&bj);
4853:   PetscFreeSpaceContiguous(&free_space,bj);
4854:   PetscLLDestroy(lnk,lnkbt);

4856:   /* create symbolic parallel matrix B_mpi */
4857:   /*---------------------------------------*/
4858:   MatGetBlockSizes(seqmat,&bs,&cbs);
4859:   MatCreate(comm,&B_mpi);
4860:   if (n==PETSC_DECIDE) {
4861:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);
4862:   } else {
4863:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4864:   }
4865:   MatSetBlockSizes(B_mpi,bs,cbs);
4866:   MatSetType(B_mpi,MATMPIAIJ);
4867:   MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);
4868:   MatPreallocateFinalize(dnz,onz);
4869:   MatSetOption(B_mpi,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

4871:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
4872:   B_mpi->assembled    = PETSC_FALSE;
4873:   B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
4874:   merge->bi           = bi;
4875:   merge->bj           = bj;
4876:   merge->buf_ri       = buf_ri;
4877:   merge->buf_rj       = buf_rj;
4878:   merge->coi          = NULL;
4879:   merge->coj          = NULL;
4880:   merge->owners_co    = NULL;

4882:   PetscCommDestroy(&comm);

4884:   /* attach the supporting struct to B_mpi for reuse */
4885:   PetscContainerCreate(PETSC_COMM_SELF,&container);
4886:   PetscContainerSetPointer(container,merge);
4887:   PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);
4888:   PetscContainerDestroy(&container);
4889:   *mpimat = B_mpi;

4891:   PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);
4892:   return(0);
4893: }

4897: /*@C
4898:       MatCreateMPIAIJSumSeqAIJ - Creates a MPIAIJ matrix by adding sequential
4899:                  matrices from each processor

4901:     Collective on MPI_Comm

4903:    Input Parameters:
4904: +    comm - the communicators the parallel matrix will live on
4905: .    seqmat - the input sequential matrices
4906: .    m - number of local rows (or PETSC_DECIDE)
4907: .    n - number of local columns (or PETSC_DECIDE)
4908: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4910:    Output Parameter:
4911: .    mpimat - the parallel matrix generated

4913:     Level: advanced

4915:    Notes:
4916:      The dimensions of the sequential matrix in each processor MUST be the same.
4917:      The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
4918:      destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
4919: @*/
4920: PetscErrorCode  MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
4921: {
4923:   PetscMPIInt    size;

4926:   MPI_Comm_size(comm,&size);
4927:   if (size == 1) {
4928:     PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4929:     if (scall == MAT_INITIAL_MATRIX) {
4930:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
4931:     } else {
4932:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
4933:     }
4934:     PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4935:     return(0);
4936:   }
4937:   PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4938:   if (scall == MAT_INITIAL_MATRIX) {
4939:     MatCreateMPIAIJSumSeqAIJSymbolic(comm,seqmat,m,n,mpimat);
4940:   }
4941:   MatCreateMPIAIJSumSeqAIJNumeric(seqmat,*mpimat);
4942:   PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4943:   return(0);
4944: }

4948: /*@
4949:      MatMPIAIJGetLocalMat - Creates a SeqAIJ from a MPIAIJ matrix by taking all its local rows and putting them into a sequential vector with
4950:           mlocal rows and n columns. Where mlocal is the row count obtained with MatGetLocalSize() and n is the global column count obtained
4951:           with MatGetSize()

4953:     Not Collective

4955:    Input Parameters:
4956: +    A - the matrix
4957: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4959:    Output Parameter:
4960: .    A_loc - the local sequential matrix generated

4962:     Level: developer

4964: .seealso: MatGetOwnerShipRange(), MatMPIAIJGetLocalMatCondensed()

4966: @*/
4967: PetscErrorCode  MatMPIAIJGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
4968: {
4970:   Mat_MPIAIJ     *mpimat=(Mat_MPIAIJ*)A->data;
4971:   Mat_SeqAIJ     *mat,*a,*b;
4972:   PetscInt       *ai,*aj,*bi,*bj,*cmap=mpimat->garray;
4973:   MatScalar      *aa,*ba,*cam;
4974:   PetscScalar    *ca;
4975:   PetscInt       am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
4976:   PetscInt       *ci,*cj,col,ncols_d,ncols_o,jo;
4977:   PetscBool      match;
4978:   MPI_Comm       comm;
4979:   PetscMPIInt    size;

4982:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
4983:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MPIAIJ matrix as input");
4984:   PetscObjectGetComm((PetscObject)A,&comm);
4985:   MPI_Comm_size(comm,&size);
4986:   if (size == 1 && scall == MAT_REUSE_MATRIX) return(0);
4987: 
4988:   PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);
4989:   a = (Mat_SeqAIJ*)(mpimat->A)->data;
4990:   b = (Mat_SeqAIJ*)(mpimat->B)->data;
4991:   ai = a->i; aj = a->j; bi = b->i; bj = b->j;
4992:   aa = a->a; ba = b->a;
4993:   if (scall == MAT_INITIAL_MATRIX) {
4994:     if (size == 1) {
4995:       MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ai,aj,aa,A_loc);
4996:       return(0);
4997:     }

4999:     PetscMalloc1((1+am),&ci);
5000:     ci[0] = 0;
5001:     for (i=0; i<am; i++) {
5002:       ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
5003:     }
5004:     PetscMalloc1((1+ci[am]),&cj);
5005:     PetscMalloc1((1+ci[am]),&ca);
5006:     k    = 0;
5007:     for (i=0; i<am; i++) {
5008:       ncols_o = bi[i+1] - bi[i];
5009:       ncols_d = ai[i+1] - ai[i];
5010:       /* off-diagonal portion of A */
5011:       for (jo=0; jo<ncols_o; jo++) {
5012:         col = cmap[*bj];
5013:         if (col >= cstart) break;
5014:         cj[k]   = col; bj++;
5015:         ca[k++] = *ba++;
5016:       }
5017:       /* diagonal portion of A */
5018:       for (j=0; j<ncols_d; j++) {
5019:         cj[k]   = cstart + *aj++;
5020:         ca[k++] = *aa++;
5021:       }
5022:       /* off-diagonal portion of A */
5023:       for (j=jo; j<ncols_o; j++) {
5024:         cj[k]   = cmap[*bj++];
5025:         ca[k++] = *ba++;
5026:       }
5027:     }
5028:     /* put together the new matrix */
5029:     MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);
5030:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5031:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5032:     mat          = (Mat_SeqAIJ*)(*A_loc)->data;
5033:     mat->free_a  = PETSC_TRUE;
5034:     mat->free_ij = PETSC_TRUE;
5035:     mat->nonew   = 0;
5036:   } else if (scall == MAT_REUSE_MATRIX) {
5037:     mat=(Mat_SeqAIJ*)(*A_loc)->data;
5038:     ci = mat->i; cj = mat->j; cam = mat->a;
5039:     for (i=0; i<am; i++) {
5040:       /* off-diagonal portion of A */
5041:       ncols_o = bi[i+1] - bi[i];
5042:       for (jo=0; jo<ncols_o; jo++) {
5043:         col = cmap[*bj];
5044:         if (col >= cstart) break;
5045:         *cam++ = *ba++; bj++;
5046:       }
5047:       /* diagonal portion of A */
5048:       ncols_d = ai[i+1] - ai[i];
5049:       for (j=0; j<ncols_d; j++) *cam++ = *aa++;
5050:       /* off-diagonal portion of A */
5051:       for (j=jo; j<ncols_o; j++) {
5052:         *cam++ = *ba++; bj++;
5053:       }
5054:     }
5055:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
5056:   PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);
5057:   return(0);
5058: }

5062: /*@C
5063:      MatMPIAIJGetLocalMatCondensed - Creates a SeqAIJ matrix from an MPIAIJ matrix by taking all its local rows and NON-ZERO columns

5065:     Not Collective

5067:    Input Parameters:
5068: +    A - the matrix
5069: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5070: -    row, col - index sets of rows and columns to extract (or NULL)

5072:    Output Parameter:
5073: .    A_loc - the local sequential matrix generated

5075:     Level: developer

5077: .seealso: MatGetOwnershipRange(), MatMPIAIJGetLocalMat()

5079: @*/
5080: PetscErrorCode  MatMPIAIJGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
5081: {
5082:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5084:   PetscInt       i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
5085:   IS             isrowa,iscola;
5086:   Mat            *aloc;
5087:   PetscBool      match;

5090:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
5091:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MPIAIJ matrix as input");
5092:   PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);
5093:   if (!row) {
5094:     start = A->rmap->rstart; end = A->rmap->rend;
5095:     ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);
5096:   } else {
5097:     isrowa = *row;
5098:   }
5099:   if (!col) {
5100:     start = A->cmap->rstart;
5101:     cmap  = a->garray;
5102:     nzA   = a->A->cmap->n;
5103:     nzB   = a->B->cmap->n;
5104:     PetscMalloc1((nzA+nzB), &idx);
5105:     ncols = 0;
5106:     for (i=0; i<nzB; i++) {
5107:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5108:       else break;
5109:     }
5110:     imark = i;
5111:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;
5112:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
5113:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&iscola);
5114:   } else {
5115:     iscola = *col;
5116:   }
5117:   if (scall != MAT_INITIAL_MATRIX) {
5118:     PetscMalloc(sizeof(Mat),&aloc);
5119:     aloc[0] = *A_loc;
5120:   }
5121:   MatGetSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);
5122:   *A_loc = aloc[0];
5123:   PetscFree(aloc);
5124:   if (!row) {
5125:     ISDestroy(&isrowa);
5126:   }
5127:   if (!col) {
5128:     ISDestroy(&iscola);
5129:   }
5130:   PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);
5131:   return(0);
5132: }

5136: /*@C
5137:     MatGetBrowsOfAcols - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns of local A

5139:     Collective on Mat

5141:    Input Parameters:
5142: +    A,B - the matrices in mpiaij format
5143: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5144: -    rowb, colb - index sets of rows and columns of B to extract (or NULL)

5146:    Output Parameter:
5147: +    rowb, colb - index sets of rows and columns of B to extract
5148: -    B_seq - the sequential matrix generated

5150:     Level: developer

5152: @*/
5153: PetscErrorCode  MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,Mat *B_seq)
5154: {
5155:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5157:   PetscInt       *idx,i,start,ncols,nzA,nzB,*cmap,imark;
5158:   IS             isrowb,iscolb;
5159:   Mat            *bseq=NULL;

5162:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5163:     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%D, %D) != (%D,%D)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);
5164:   }
5165:   PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);

5167:   if (scall == MAT_INITIAL_MATRIX) {
5168:     start = A->cmap->rstart;
5169:     cmap  = a->garray;
5170:     nzA   = a->A->cmap->n;
5171:     nzB   = a->B->cmap->n;
5172:     PetscMalloc1((nzA+nzB), &idx);
5173:     ncols = 0;
5174:     for (i=0; i<nzB; i++) {  /* row < local row index */
5175:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5176:       else break;
5177:     }
5178:     imark = i;
5179:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;  /* local rows */
5180:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5181:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&isrowb);
5182:     ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);
5183:   } else {
5184:     if (!rowb || !colb) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5185:     isrowb  = *rowb; iscolb = *colb;
5186:     PetscMalloc(sizeof(Mat),&bseq);
5187:     bseq[0] = *B_seq;
5188:   }
5189:   MatGetSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);
5190:   *B_seq = bseq[0];
5191:   PetscFree(bseq);
5192:   if (!rowb) {
5193:     ISDestroy(&isrowb);
5194:   } else {
5195:     *rowb = isrowb;
5196:   }
5197:   if (!colb) {
5198:     ISDestroy(&iscolb);
5199:   } else {
5200:     *colb = iscolb;
5201:   }
5202:   PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);
5203:   return(0);
5204: }

5208: /*
5209:     MatGetBrowsOfAoCols_MPIAIJ - Creates a SeqAIJ matrix by taking rows of B that equal to nonzero columns
5210:     of the OFF-DIAGONAL portion of local A

5212:     Collective on Mat

5214:    Input Parameters:
5215: +    A,B - the matrices in mpiaij format
5216: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5218:    Output Parameter:
5219: +    startsj_s - starting point in B's sending j-arrays, saved for MAT_REUSE (or NULL)
5220: .    startsj_r - starting point in B's receiving j-arrays, saved for MAT_REUSE (or NULL)
5221: .    bufa_ptr - array for sending matrix values, saved for MAT_REUSE (or NULL)
5222: -    B_oth - the sequential matrix generated with size aBn=a->B->cmap->n by B->cmap->N

5224:     Level: developer

5226: */
5227: PetscErrorCode  MatGetBrowsOfAoCols_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscInt **startsj_s,PetscInt **startsj_r,MatScalar **bufa_ptr,Mat *B_oth)
5228: {
5229:   VecScatter_MPI_General *gen_to,*gen_from;
5230:   PetscErrorCode         ierr;
5231:   Mat_MPIAIJ             *a=(Mat_MPIAIJ*)A->data;
5232:   Mat_SeqAIJ             *b_oth;
5233:   VecScatter             ctx =a->Mvctx;
5234:   MPI_Comm               comm;
5235:   PetscMPIInt            *rprocs,*sprocs,tag=((PetscObject)ctx)->tag,rank;
5236:   PetscInt               *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj;
5237:   PetscScalar            *rvalues,*svalues;
5238:   MatScalar              *b_otha,*bufa,*bufA;
5239:   PetscInt               i,j,k,l,ll,nrecvs,nsends,nrows,*srow,*rstarts,*rstartsj = 0,*sstarts,*sstartsj,len;
5240:   MPI_Request            *rwaits = NULL,*swaits = NULL;
5241:   MPI_Status             *sstatus,rstatus;
5242:   PetscMPIInt            jj,size;
5243:   PetscInt               *cols,sbs,rbs;
5244:   PetscScalar            *vals;

5247:   PetscObjectGetComm((PetscObject)A,&comm);
5248:   MPI_Comm_size(comm,&size);
5249:   if (size == 1) return(0);

5251:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5252:     SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrix local dimensions are incompatible, (%d, %d) != (%d,%d)",A->cmap->rstart,A->cmap->rend,B->rmap->rstart,B->rmap->rend);
5253:   }
5254:   PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);
5255:   MPI_Comm_rank(comm,&rank);

5257:   gen_to   = (VecScatter_MPI_General*)ctx->todata;
5258:   gen_from = (VecScatter_MPI_General*)ctx->fromdata;
5259:   rvalues  = gen_from->values; /* holds the length of receiving row */
5260:   svalues  = gen_to->values;   /* holds the length of sending row */
5261:   nrecvs   = gen_from->n;
5262:   nsends   = gen_to->n;

5264:   PetscMalloc2(nrecvs,&rwaits,nsends,&swaits);
5265:   srow    = gen_to->indices;    /* local row index to be sent */
5266:   sstarts = gen_to->starts;
5267:   sprocs  = gen_to->procs;
5268:   sstatus = gen_to->sstatus;
5269:   sbs     = gen_to->bs;
5270:   rstarts = gen_from->starts;
5271:   rprocs  = gen_from->procs;
5272:   rbs     = gen_from->bs;

5274:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5275:   if (scall == MAT_INITIAL_MATRIX) {
5276:     /* i-array */
5277:     /*---------*/
5278:     /*  post receives */
5279:     for (i=0; i<nrecvs; i++) {
5280:       rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
5281:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
5282:       MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5283:     }

5285:     /* pack the outgoing message */
5286:     PetscMalloc2(nsends+1,&sstartsj,nrecvs+1,&rstartsj);

5288:     sstartsj[0] = 0;
5289:     rstartsj[0] = 0;
5290:     len         = 0; /* total length of j or a array to be sent */
5291:     k           = 0;
5292:     for (i=0; i<nsends; i++) {
5293:       rowlen = (PetscInt*)svalues + sstarts[i]*sbs;
5294:       nrows  = sstarts[i+1]-sstarts[i]; /* num of block rows */
5295:       for (j=0; j<nrows; j++) {
5296:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5297:         for (l=0; l<sbs; l++) {
5298:           MatGetRow_MPIAIJ(B,row+l,&ncols,NULL,NULL); /* rowlength */

5300:           rowlen[j*sbs+l] = ncols;

5302:           len += ncols;
5303:           MatRestoreRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);
5304:         }
5305:         k++;
5306:       }
5307:       MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);

5309:       sstartsj[i+1] = len;  /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5310:     }
5311:     /* recvs and sends of i-array are completed */
5312:     i = nrecvs;
5313:     while (i--) {
5314:       MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
5315:     }
5316:     if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}

5318:     /* allocate buffers for sending j and a arrays */
5319:     PetscMalloc1((len+1),&bufj);
5320:     PetscMalloc1((len+1),&bufa);

5322:     /* create i-array of B_oth */
5323:     PetscMalloc1((aBn+2),&b_othi);

5325:     b_othi[0] = 0;
5326:     len       = 0; /* total length of j or a array to be received */
5327:     k         = 0;
5328:     for (i=0; i<nrecvs; i++) {
5329:       rowlen = (PetscInt*)rvalues + rstarts[i]*rbs;
5330:       nrows  = rbs*(rstarts[i+1]-rstarts[i]); /* num of rows to be recieved */
5331:       for (j=0; j<nrows; j++) {
5332:         b_othi[k+1] = b_othi[k] + rowlen[j];
5333:         len        += rowlen[j]; k++;
5334:       }
5335:       rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5336:     }

5338:     /* allocate space for j and a arrrays of B_oth */
5339:     PetscMalloc1((b_othi[aBn]+1),&b_othj);
5340:     PetscMalloc1((b_othi[aBn]+1),&b_otha);

5342:     /* j-array */
5343:     /*---------*/
5344:     /*  post receives of j-array */
5345:     for (i=0; i<nrecvs; i++) {
5346:       nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5347:       MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5348:     }

5350:     /* pack the outgoing message j-array */
5351:     k = 0;
5352:     for (i=0; i<nsends; i++) {
5353:       nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5354:       bufJ  = bufj+sstartsj[i];
5355:       for (j=0; j<nrows; j++) {
5356:         row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5357:         for (ll=0; ll<sbs; ll++) {
5358:           MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5359:           for (l=0; l<ncols; l++) {
5360:             *bufJ++ = cols[l];
5361:           }
5362:           MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5363:         }
5364:       }
5365:       MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);
5366:     }

5368:     /* recvs and sends of j-array are completed */
5369:     i = nrecvs;
5370:     while (i--) {
5371:       MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
5372:     }
5373:     if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
5374:   } else if (scall == MAT_REUSE_MATRIX) {
5375:     sstartsj = *startsj_s;
5376:     rstartsj = *startsj_r;
5377:     bufa     = *bufa_ptr;
5378:     b_oth    = (Mat_SeqAIJ*)(*B_oth)->data;
5379:     b_otha   = b_oth->a;
5380:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");

5382:   /* a-array */
5383:   /*---------*/
5384:   /*  post receives of a-array */
5385:   for (i=0; i<nrecvs; i++) {
5386:     nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5387:     MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
5388:   }

5390:   /* pack the outgoing message a-array */
5391:   k = 0;
5392:   for (i=0; i<nsends; i++) {
5393:     nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5394:     bufA  = bufa+sstartsj[i];
5395:     for (j=0; j<nrows; j++) {
5396:       row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5397:       for (ll=0; ll<sbs; ll++) {
5398:         MatGetRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5399:         for (l=0; l<ncols; l++) {
5400:           *bufA++ = vals[l];
5401:         }
5402:         MatRestoreRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5403:       }
5404:     }
5405:     MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
5406:   }
5407:   /* recvs and sends of a-array are completed */
5408:   i = nrecvs;
5409:   while (i--) {
5410:     MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
5411:   }
5412:   if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
5413:   PetscFree2(rwaits,swaits);

5415:   if (scall == MAT_INITIAL_MATRIX) {
5416:     /* put together the new matrix */
5417:     MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,aBn,B->cmap->N,b_othi,b_othj,b_otha,B_oth);

5419:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5420:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5421:     b_oth          = (Mat_SeqAIJ*)(*B_oth)->data;
5422:     b_oth->free_a  = PETSC_TRUE;
5423:     b_oth->free_ij = PETSC_TRUE;
5424:     b_oth->nonew   = 0;

5426:     PetscFree(bufj);
5427:     if (!startsj_s || !bufa_ptr) {
5428:       PetscFree2(sstartsj,rstartsj);
5429:       PetscFree(bufa_ptr);
5430:     } else {
5431:       *startsj_s = sstartsj;
5432:       *startsj_r = rstartsj;
5433:       *bufa_ptr  = bufa;
5434:     }
5435:   }
5436:   PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);
5437:   return(0);
5438: }

5442: /*@C
5443:   MatGetCommunicationStructs - Provides access to the communication structures used in matrix-vector multiplication.

5445:   Not Collective

5447:   Input Parameters:
5448: . A - The matrix in mpiaij format

5450:   Output Parameter:
5451: + lvec - The local vector holding off-process values from the argument to a matrix-vector product
5452: . colmap - A map from global column index to local index into lvec
5453: - multScatter - A scatter from the argument of a matrix-vector product to lvec

5455:   Level: developer

5457: @*/
5458: #if defined(PETSC_USE_CTABLE)
5459: PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
5460: #else
5461: PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
5462: #endif
5463: {
5464:   Mat_MPIAIJ *a;

5471:   a = (Mat_MPIAIJ*) A->data;
5472:   if (lvec) *lvec = a->lvec;
5473:   if (colmap) *colmap = a->colmap;
5474:   if (multScatter) *multScatter = a->Mvctx;
5475:   return(0);
5476: }

5478: PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat,MatType,MatReuse,Mat*);
5479: PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat,MatType,MatReuse,Mat*);
5480: PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat,MatType,MatReuse,Mat*);
5481: #if defined(PETSC_HAVE_ELEMENTAL)
5482: PETSC_EXTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
5483: #endif

5487: /*
5488:     Computes (B'*A')' since computing B*A directly is untenable

5490:                n                       p                          p
5491:         (              )       (              )         (                  )
5492:       m (      A       )  *  n (       B      )   =   m (         C        )
5493:         (              )       (              )         (                  )

5495: */
5496: PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
5497: {
5499:   Mat            At,Bt,Ct;

5502:   MatTranspose(A,MAT_INITIAL_MATRIX,&At);
5503:   MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);
5504:   MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);
5505:   MatDestroy(&At);
5506:   MatDestroy(&Bt);
5507:   MatTranspose(Ct,MAT_REUSE_MATRIX,&C);
5508:   MatDestroy(&Ct);
5509:   return(0);
5510: }

5514: PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
5515: {
5517:   PetscInt       m=A->rmap->n,n=B->cmap->n;
5518:   Mat            Cmat;

5521:   if (A->cmap->n != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"A->cmap->n %d != B->rmap->n %d\n",A->cmap->n,B->rmap->n);
5522:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
5523:   MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
5524:   MatSetBlockSizesFromMats(Cmat,A,B);
5525:   MatSetType(Cmat,MATMPIDENSE);
5526:   MatMPIDenseSetPreallocation(Cmat,NULL);
5527:   MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);
5528:   MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);

5530:   Cmat->ops->matmultnumeric = MatMatMultNumeric_MPIDense_MPIAIJ;

5532:   *C = Cmat;
5533:   return(0);
5534: }

5536: /* ----------------------------------------------------------------*/
5539: PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
5540: {

5544:   if (scall == MAT_INITIAL_MATRIX) {
5545:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
5546:     MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);
5547:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
5548:   }
5549:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
5550:   MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);
5551:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
5552:   return(0);
5553: }

5555: #if defined(PETSC_HAVE_MUMPS)
5556: PETSC_EXTERN PetscErrorCode MatGetFactor_aij_mumps(Mat,MatFactorType,Mat*);
5557: #endif
5558: #if defined(PETSC_HAVE_PASTIX)
5559: PETSC_EXTERN PetscErrorCode MatGetFactor_mpiaij_pastix(Mat,MatFactorType,Mat*);
5560: #endif
5561: #if defined(PETSC_HAVE_SUPERLU_DIST)
5562: PETSC_EXTERN PetscErrorCode MatGetFactor_mpiaij_superlu_dist(Mat,MatFactorType,Mat*);
5563: #endif
5564: #if defined(PETSC_HAVE_CLIQUE)
5565: PETSC_EXTERN PetscErrorCode MatGetFactor_aij_clique(Mat,MatFactorType,Mat*);
5566: #endif

5568: /*MC
5569:    MATMPIAIJ - MATMPIAIJ = "mpiaij" - A matrix type to be used for parallel sparse matrices.

5571:    Options Database Keys:
5572: . -mat_type mpiaij - sets the matrix type to "mpiaij" during a call to MatSetFromOptions()

5574:   Level: beginner

5576: .seealso: MatCreateAIJ()
5577: M*/

5581: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
5582: {
5583:   Mat_MPIAIJ     *b;
5585:   PetscMPIInt    size;

5588:   MPI_Comm_size(PetscObjectComm((PetscObject)B),&size);

5590:   PetscNewLog(B,&b);
5591:   B->data       = (void*)b;
5592:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
5593:   B->assembled  = PETSC_FALSE;
5594:   B->insertmode = NOT_SET_VALUES;
5595:   b->size       = size;

5597:   MPI_Comm_rank(PetscObjectComm((PetscObject)B),&b->rank);

5599:   /* build cache for off array entries formed */
5600:   MatStashCreate_Private(PetscObjectComm((PetscObject)B),1,&B->stash);

5602:   b->donotstash  = PETSC_FALSE;
5603:   b->colmap      = 0;
5604:   b->garray      = 0;
5605:   b->roworiented = PETSC_TRUE;

5607:   /* stuff used for matrix vector multiply */
5608:   b->lvec  = NULL;
5609:   b->Mvctx = NULL;

5611:   /* stuff for MatGetRow() */
5612:   b->rowindices   = 0;
5613:   b->rowvalues    = 0;
5614:   b->getrowactive = PETSC_FALSE;

5616:   /* flexible pointer used in CUSP/CUSPARSE classes */
5617:   b->spptr = NULL;

5619: #if defined(PETSC_HAVE_MUMPS)
5620:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_mumps_C",MatGetFactor_aij_mumps);
5621: #endif
5622: #if defined(PETSC_HAVE_PASTIX)
5623:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_pastix_C",MatGetFactor_mpiaij_pastix);
5624: #endif
5625: #if defined(PETSC_HAVE_SUPERLU_DIST)
5626:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_superlu_dist_C",MatGetFactor_mpiaij_superlu_dist);
5627: #endif
5628: #if defined(PETSC_HAVE_CLIQUE)
5629:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_clique_C",MatGetFactor_aij_clique);
5630: #endif
5631:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIAIJ);
5632:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIAIJ);
5633:   PetscObjectComposeFunction((PetscObject)B,"MatGetDiagonalBlock_C",MatGetDiagonalBlock_MPIAIJ);
5634:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_MPIAIJ);
5635:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",MatMPIAIJSetPreallocation_MPIAIJ);
5636:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",MatMPIAIJSetPreallocationCSR_MPIAIJ);
5637:   PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIAIJ);
5638:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijperm_C",MatConvert_MPIAIJ_MPIAIJPERM);
5639:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijcrl_C",MatConvert_MPIAIJ_MPIAIJCRL);
5640:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisbaij_C",MatConvert_MPIAIJ_MPISBAIJ);
5641: #if defined(PETSC_HAVE_ELEMENTAL)
5642:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_elemental_C",MatConvert_MPIAIJ_Elemental);
5643: #endif
5644:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",MatMatMult_MPIDense_MPIAIJ);
5645:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",MatMatMultSymbolic_MPIDense_MPIAIJ);
5646:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",MatMatMultNumeric_MPIDense_MPIAIJ);
5647:   PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);
5648:   return(0);
5649: }

5653: /*@
5654:      MatCreateMPIAIJWithSplitArrays - creates a MPI AIJ matrix using arrays that contain the "diagonal"
5655:          and "off-diagonal" part of the matrix in CSR format.

5657:    Collective on MPI_Comm

5659:    Input Parameters:
5660: +  comm - MPI communicator
5661: .  m - number of local rows (Cannot be PETSC_DECIDE)
5662: .  n - This value should be the same as the local size used in creating the
5663:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
5664:        calculated if N is given) For square matrices n is almost always m.
5665: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
5666: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
5667: .   i - row indices for "diagonal" portion of matrix
5668: .   j - column indices
5669: .   a - matrix values
5670: .   oi - row indices for "off-diagonal" portion of matrix
5671: .   oj - column indices
5672: -   oa - matrix values

5674:    Output Parameter:
5675: .   mat - the matrix

5677:    Level: advanced

5679:    Notes:
5680:        The i, j, and a arrays ARE NOT copied by this routine into the internal format used by PETSc. The user
5681:        must free the arrays once the matrix has been destroyed and not before.

5683:        The i and j indices are 0 based

5685:        See MatCreateAIJ() for the definition of "diagonal" and "off-diagonal" portion of the matrix

5687:        This sets local rows and cannot be used to set off-processor values.

5689:        Use of this routine is discouraged because it is inflexible and cumbersome to use. It is extremely rare that a
5690:        legacy application natively assembles into exactly this split format. The code to do so is nontrivial and does
5691:        not easily support in-place reassembly. It is recommended to use MatSetValues() (or a variant thereof) because
5692:        the resulting assembly is easier to implement, will work with any matrix format, and the user does not have to
5693:        keep track of the underlying array. Use MatSetOption(A,MAT_IGNORE_OFF_PROC_ENTRIES,PETSC_TRUE) to disable all
5694:        communication if it is known that only local entries will be set.

5696: .keywords: matrix, aij, compressed row, sparse, parallel

5698: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
5699:           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithArrays()
5700: @*/
5701: PetscErrorCode  MatCreateMPIAIJWithSplitArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt i[],PetscInt j[],PetscScalar a[],PetscInt oi[], PetscInt oj[],PetscScalar oa[],Mat *mat)
5702: {
5704:   Mat_MPIAIJ     *maij;

5707:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
5708:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
5709:   if (oi[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
5710:   MatCreate(comm,mat);
5711:   MatSetSizes(*mat,m,n,M,N);
5712:   MatSetType(*mat,MATMPIAIJ);
5713:   maij = (Mat_MPIAIJ*) (*mat)->data;

5715:   (*mat)->preallocated = PETSC_TRUE;

5717:   PetscLayoutSetUp((*mat)->rmap);
5718:   PetscLayoutSetUp((*mat)->cmap);

5720:   MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,n,i,j,a,&maij->A);
5721:   MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,(*mat)->cmap->N,oi,oj,oa,&maij->B);

5723:   MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);
5724:   MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);
5725:   MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);
5726:   MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);

5728:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
5729:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
5730:   MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
5731:   return(0);
5732: }

5734: /*
5735:     Special version for direct calls from Fortran
5736: */
5737: #include <petsc-private/fortranimpl.h>

5739: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5740: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
5741: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5742: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
5743: #endif

5745: /* Change these macros so can be used in void function */
5746: #undef CHKERRQ
5747: #define CHKERRQ(ierr) CHKERRABORT(PETSC_COMM_WORLD,ierr)
5748: #undef SETERRQ2
5749: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
5750: #undef SETERRQ3
5751: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)
5752: #undef SETERRQ
5753: #define SETERRQ(c,ierr,b) CHKERRABORT(c,ierr)

5757: PETSC_EXTERN void PETSC_STDCALL matsetvaluesmpiaij_(Mat *mmat,PetscInt *mm,const PetscInt im[],PetscInt *mn,const PetscInt in[],const PetscScalar v[],InsertMode *maddv,PetscErrorCode *_ierr)
5758: {
5759:   Mat            mat  = *mmat;
5760:   PetscInt       m    = *mm, n = *mn;
5761:   InsertMode     addv = *maddv;
5762:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
5763:   PetscScalar    value;

5766:   MatCheckPreallocated(mat,1);
5767:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;

5769: #if defined(PETSC_USE_DEBUG)
5770:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
5771: #endif
5772:   {
5773:     PetscInt  i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
5774:     PetscInt  cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
5775:     PetscBool roworiented = aij->roworiented;

5777:     /* Some Variables required in the macro */
5778:     Mat        A                 = aij->A;
5779:     Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
5780:     PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
5781:     MatScalar  *aa               = a->a;
5782:     PetscBool  ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
5783:     Mat        B                 = aij->B;
5784:     Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
5785:     PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
5786:     MatScalar  *ba               = b->a;

5788:     PetscInt  *rp1,*rp2,ii,nrow1,nrow2,_i,rmax1,rmax2,N,low1,high1,low2,high2,t,lastcol1,lastcol2;
5789:     PetscInt  nonew = a->nonew;
5790:     MatScalar *ap1,*ap2;

5793:     for (i=0; i<m; i++) {
5794:       if (im[i] < 0) continue;
5795: #if defined(PETSC_USE_DEBUG)
5796:       if (im[i] >= mat->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],mat->rmap->N-1);
5797: #endif
5798:       if (im[i] >= rstart && im[i] < rend) {
5799:         row      = im[i] - rstart;
5800:         lastcol1 = -1;
5801:         rp1      = aj + ai[row];
5802:         ap1      = aa + ai[row];
5803:         rmax1    = aimax[row];
5804:         nrow1    = ailen[row];
5805:         low1     = 0;
5806:         high1    = nrow1;
5807:         lastcol2 = -1;
5808:         rp2      = bj + bi[row];
5809:         ap2      = ba + bi[row];
5810:         rmax2    = bimax[row];
5811:         nrow2    = bilen[row];
5812:         low2     = 0;
5813:         high2    = nrow2;

5815:         for (j=0; j<n; j++) {
5816:           if (roworiented) value = v[i*n+j];
5817:           else value = v[i+j*m];
5818:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
5819:           if (in[j] >= cstart && in[j] < cend) {
5820:             col = in[j] - cstart;
5821:             MatSetValues_SeqAIJ_A_Private(row,col,value,addv);
5822:           } else if (in[j] < 0) continue;
5823: #if defined(PETSC_USE_DEBUG)
5824:           else if (in[j] >= mat->cmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large: col %D max %D",in[j],mat->cmap->N-1);
5825: #endif
5826:           else {
5827:             if (mat->was_assembled) {
5828:               if (!aij->colmap) {
5829:                 MatCreateColmap_MPIAIJ_Private(mat);
5830:               }
5831: #if defined(PETSC_USE_CTABLE)
5832:               PetscTableFind(aij->colmap,in[j]+1,&col);
5833:               col--;
5834: #else
5835:               col = aij->colmap[in[j]] - 1;
5836: #endif
5837:               if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
5838:                 MatDisAssemble_MPIAIJ(mat);
5839:                 col  =  in[j];
5840:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
5841:                 B     = aij->B;
5842:                 b     = (Mat_SeqAIJ*)B->data;
5843:                 bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
5844:                 rp2   = bj + bi[row];
5845:                 ap2   = ba + bi[row];
5846:                 rmax2 = bimax[row];
5847:                 nrow2 = bilen[row];
5848:                 low2  = 0;
5849:                 high2 = nrow2;
5850:                 bm    = aij->B->rmap->n;
5851:                 ba    = b->a;
5852:               }
5853:             } else col = in[j];
5854:             MatSetValues_SeqAIJ_B_Private(row,col,value,addv);
5855:           }
5856:         }
5857:       } else if (!aij->donotstash) {
5858:         if (roworiented) {
5859:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5860:         } else {
5861:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5862:         }
5863:       }
5864:     }
5865:   }
5866:   PetscFunctionReturnVoid();
5867: }