Actual source code: mpiaij.c

petsc-master 2019-05-24
Report Typos and Errors


  3:  #include <../src/mat/impls/aij/mpi/mpiaij.h>
  4:  #include <petsc/private/vecimpl.h>
  5:  #include <petsc/private/vecscatterimpl.h>
  6:  #include <petsc/private/isimpl.h>
  7:  #include <petscblaslapack.h>
  8:  #include <petscsf.h>

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

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

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

 22:   Developer Notes:
 23:     Subclasses include MATAIJCUSP, MATAIJCUSPARSE, MATAIJPERM, MATAIJSELL, MATAIJMKL, MATAIJCRL, and also automatically switches over to use inodes when
 24:    enough exist.

 26:   Level: beginner

 28: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ, MATMPIAIJ
 29: M*/

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

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

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

 43:   Level: beginner

 45: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
 46: M*/

 48: PetscErrorCode MatSetBlockSizes_MPIAIJ(Mat M, PetscInt rbs, PetscInt cbs)
 49: {
 51:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)M->data;

 54:   if (mat->A) {
 55:     MatSetBlockSizes(mat->A,rbs,cbs);
 56:     MatSetBlockSizes(mat->B,rbs,1);
 57:   }
 58:   return(0);
 59: }

 61: PetscErrorCode MatFindNonzeroRows_MPIAIJ(Mat M,IS *keptrows)
 62: {
 63:   PetscErrorCode  ierr;
 64:   Mat_MPIAIJ      *mat = (Mat_MPIAIJ*)M->data;
 65:   Mat_SeqAIJ      *a   = (Mat_SeqAIJ*)mat->A->data;
 66:   Mat_SeqAIJ      *b   = (Mat_SeqAIJ*)mat->B->data;
 67:   const PetscInt  *ia,*ib;
 68:   const MatScalar *aa,*bb;
 69:   PetscInt        na,nb,i,j,*rows,cnt=0,n0rows;
 70:   PetscInt        m = M->rmap->n,rstart = M->rmap->rstart;

 73:   *keptrows = 0;
 74:   ia        = a->i;
 75:   ib        = b->i;
 76:   for (i=0; i<m; i++) {
 77:     na = ia[i+1] - ia[i];
 78:     nb = ib[i+1] - ib[i];
 79:     if (!na && !nb) {
 80:       cnt++;
 81:       goto ok1;
 82:     }
 83:     aa = a->a + ia[i];
 84:     for (j=0; j<na; j++) {
 85:       if (aa[j] != 0.0) goto ok1;
 86:     }
 87:     bb = b->a + ib[i];
 88:     for (j=0; j <nb; j++) {
 89:       if (bb[j] != 0.0) goto ok1;
 90:     }
 91:     cnt++;
 92: ok1:;
 93:   }
 94:   MPIU_Allreduce(&cnt,&n0rows,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)M));
 95:   if (!n0rows) return(0);
 96:   PetscMalloc1(M->rmap->n-cnt,&rows);
 97:   cnt  = 0;
 98:   for (i=0; i<m; i++) {
 99:     na = ia[i+1] - ia[i];
100:     nb = ib[i+1] - ib[i];
101:     if (!na && !nb) continue;
102:     aa = a->a + ia[i];
103:     for (j=0; j<na;j++) {
104:       if (aa[j] != 0.0) {
105:         rows[cnt++] = rstart + i;
106:         goto ok2;
107:       }
108:     }
109:     bb = b->a + ib[i];
110:     for (j=0; j<nb; j++) {
111:       if (bb[j] != 0.0) {
112:         rows[cnt++] = rstart + i;
113:         goto ok2;
114:       }
115:     }
116: ok2:;
117:   }
118:   ISCreateGeneral(PetscObjectComm((PetscObject)M),cnt,rows,PETSC_OWN_POINTER,keptrows);
119:   return(0);
120: }

122: PetscErrorCode  MatDiagonalSet_MPIAIJ(Mat Y,Vec D,InsertMode is)
123: {
124:   PetscErrorCode    ierr;
125:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*) Y->data;
126:   PetscBool         cong;

129:   MatHasCongruentLayouts(Y,&cong);
130:   if (Y->assembled && cong) {
131:     MatDiagonalSet(aij->A,D,is);
132:   } else {
133:     MatDiagonalSet_Default(Y,D,is);
134:   }
135:   return(0);
136: }

138: PetscErrorCode MatFindZeroDiagonals_MPIAIJ(Mat M,IS *zrows)
139: {
140:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)M->data;
142:   PetscInt       i,rstart,nrows,*rows;

145:   *zrows = NULL;
146:   MatFindZeroDiagonals_SeqAIJ_Private(aij->A,&nrows,&rows);
147:   MatGetOwnershipRange(M,&rstart,NULL);
148:   for (i=0; i<nrows; i++) rows[i] += rstart;
149:   ISCreateGeneral(PetscObjectComm((PetscObject)M),nrows,rows,PETSC_OWN_POINTER,zrows);
150:   return(0);
151: }

153: PetscErrorCode MatGetColumnNorms_MPIAIJ(Mat A,NormType type,PetscReal *norms)
154: {
156:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)A->data;
157:   PetscInt       i,n,*garray = aij->garray;
158:   Mat_SeqAIJ     *a_aij = (Mat_SeqAIJ*) aij->A->data;
159:   Mat_SeqAIJ     *b_aij = (Mat_SeqAIJ*) aij->B->data;
160:   PetscReal      *work;

163:   MatGetSize(A,NULL,&n);
164:   PetscCalloc1(n,&work);
165:   if (type == NORM_2) {
166:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
167:       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]*a_aij->a[i]);
168:     }
169:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
170:       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]*b_aij->a[i]);
171:     }
172:   } else if (type == NORM_1) {
173:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
174:       work[A->cmap->rstart + a_aij->j[i]] += PetscAbsScalar(a_aij->a[i]);
175:     }
176:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
177:       work[garray[b_aij->j[i]]] += PetscAbsScalar(b_aij->a[i]);
178:     }
179:   } else if (type == NORM_INFINITY) {
180:     for (i=0; i<a_aij->i[aij->A->rmap->n]; i++) {
181:       work[A->cmap->rstart + a_aij->j[i]] = PetscMax(PetscAbsScalar(a_aij->a[i]), work[A->cmap->rstart + a_aij->j[i]]);
182:     }
183:     for (i=0; i<b_aij->i[aij->B->rmap->n]; i++) {
184:       work[garray[b_aij->j[i]]] = PetscMax(PetscAbsScalar(b_aij->a[i]),work[garray[b_aij->j[i]]]);
185:     }

187:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Unknown NormType");
188:   if (type == NORM_INFINITY) {
189:     MPIU_Allreduce(work,norms,n,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)A));
190:   } else {
191:     MPIU_Allreduce(work,norms,n,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)A));
192:   }
193:   PetscFree(work);
194:   if (type == NORM_2) {
195:     for (i=0; i<n; i++) norms[i] = PetscSqrtReal(norms[i]);
196:   }
197:   return(0);
198: }

200: PetscErrorCode MatFindOffBlockDiagonalEntries_MPIAIJ(Mat A,IS *is)
201: {
202:   Mat_MPIAIJ      *a  = (Mat_MPIAIJ*)A->data;
203:   IS              sis,gis;
204:   PetscErrorCode  ierr;
205:   const PetscInt  *isis,*igis;
206:   PetscInt        n,*iis,nsis,ngis,rstart,i;

209:   MatFindOffBlockDiagonalEntries(a->A,&sis);
210:   MatFindNonzeroRows(a->B,&gis);
211:   ISGetSize(gis,&ngis);
212:   ISGetSize(sis,&nsis);
213:   ISGetIndices(sis,&isis);
214:   ISGetIndices(gis,&igis);

216:   PetscMalloc1(ngis+nsis,&iis);
217:   PetscMemcpy(iis,igis,ngis*sizeof(PetscInt));
218:   PetscMemcpy(iis+ngis,isis,nsis*sizeof(PetscInt));
219:   n    = ngis + nsis;
220:   PetscSortRemoveDupsInt(&n,iis);
221:   MatGetOwnershipRange(A,&rstart,NULL);
222:   for (i=0; i<n; i++) iis[i] += rstart;
223:   ISCreateGeneral(PetscObjectComm((PetscObject)A),n,iis,PETSC_OWN_POINTER,is);

225:   ISRestoreIndices(sis,&isis);
226:   ISRestoreIndices(gis,&igis);
227:   ISDestroy(&sis);
228:   ISDestroy(&gis);
229:   return(0);
230: }

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

236:     Only for square matrices

238:     Used by a preconditioner, hence PETSC_EXTERN
239: */
240: PETSC_EXTERN PetscErrorCode MatDistribute_MPIAIJ(MPI_Comm comm,Mat gmat,PetscInt m,MatReuse reuse,Mat *inmat)
241: {
242:   PetscMPIInt    rank,size;
243:   PetscInt       *rowners,*dlens,*olens,i,rstart,rend,j,jj,nz = 0,*gmataj,cnt,row,*ld,bses[2];
245:   Mat            mat;
246:   Mat_SeqAIJ     *gmata;
247:   PetscMPIInt    tag;
248:   MPI_Status     status;
249:   PetscBool      aij;
250:   MatScalar      *gmataa,*ao,*ad,*gmataarestore=0;

253:   MPI_Comm_rank(comm,&rank);
254:   MPI_Comm_size(comm,&size);
255:   if (!rank) {
256:     PetscObjectTypeCompare((PetscObject)gmat,MATSEQAIJ,&aij);
257:     if (!aij) SETERRQ1(PetscObjectComm((PetscObject)gmat),PETSC_ERR_SUP,"Currently no support for input matrix of type %s\n",((PetscObject)gmat)->type_name);
258:   }
259:   if (reuse == MAT_INITIAL_MATRIX) {
260:     MatCreate(comm,&mat);
261:     MatSetSizes(mat,m,m,PETSC_DETERMINE,PETSC_DETERMINE);
262:     MatGetBlockSizes(gmat,&bses[0],&bses[1]);
263:     MPI_Bcast(bses,2,MPIU_INT,0,comm);
264:     MatSetBlockSizes(mat,bses[0],bses[1]);
265:     MatSetType(mat,MATAIJ);
266:     PetscMalloc1(size+1,&rowners);
267:     PetscMalloc2(m,&dlens,m,&olens);
268:     MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

270:     rowners[0] = 0;
271:     for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
272:     rstart = rowners[rank];
273:     rend   = rowners[rank+1];
274:     PetscObjectGetNewTag((PetscObject)mat,&tag);
275:     if (!rank) {
276:       gmata = (Mat_SeqAIJ*) gmat->data;
277:       /* send row lengths to all processors */
278:       for (i=0; i<m; i++) dlens[i] = gmata->ilen[i];
279:       for (i=1; i<size; i++) {
280:         MPI_Send(gmata->ilen + rowners[i],rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
281:       }
282:       /* determine number diagonal and off-diagonal counts */
283:       PetscMemzero(olens,m*sizeof(PetscInt));
284:       PetscCalloc1(m,&ld);
285:       jj   = 0;
286:       for (i=0; i<m; i++) {
287:         for (j=0; j<dlens[i]; j++) {
288:           if (gmata->j[jj] < rstart) ld[i]++;
289:           if (gmata->j[jj] < rstart || gmata->j[jj] >= rend) olens[i]++;
290:           jj++;
291:         }
292:       }
293:       /* send column indices to other processes */
294:       for (i=1; i<size; i++) {
295:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
296:         MPI_Send(&nz,1,MPIU_INT,i,tag,comm);
297:         MPI_Send(gmata->j + gmata->i[rowners[i]],nz,MPIU_INT,i,tag,comm);
298:       }

300:       /* send numerical values to other processes */
301:       for (i=1; i<size; i++) {
302:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
303:         MPI_Send(gmata->a + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
304:       }
305:       gmataa = gmata->a;
306:       gmataj = gmata->j;

308:     } else {
309:       /* receive row lengths */
310:       MPI_Recv(dlens,m,MPIU_INT,0,tag,comm,&status);
311:       /* receive column indices */
312:       MPI_Recv(&nz,1,MPIU_INT,0,tag,comm,&status);
313:       PetscMalloc2(nz,&gmataa,nz,&gmataj);
314:       MPI_Recv(gmataj,nz,MPIU_INT,0,tag,comm,&status);
315:       /* determine number diagonal and off-diagonal counts */
316:       PetscMemzero(olens,m*sizeof(PetscInt));
317:       PetscCalloc1(m,&ld);
318:       jj   = 0;
319:       for (i=0; i<m; i++) {
320:         for (j=0; j<dlens[i]; j++) {
321:           if (gmataj[jj] < rstart) ld[i]++;
322:           if (gmataj[jj] < rstart || gmataj[jj] >= rend) olens[i]++;
323:           jj++;
324:         }
325:       }
326:       /* receive numerical values */
327:       PetscMemzero(gmataa,nz*sizeof(PetscScalar));
328:       MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
329:     }
330:     /* set preallocation */
331:     for (i=0; i<m; i++) {
332:       dlens[i] -= olens[i];
333:     }
334:     MatSeqAIJSetPreallocation(mat,0,dlens);
335:     MatMPIAIJSetPreallocation(mat,0,dlens,0,olens);

337:     for (i=0; i<m; i++) {
338:       dlens[i] += olens[i];
339:     }
340:     cnt = 0;
341:     for (i=0; i<m; i++) {
342:       row  = rstart + i;
343:       MatSetValues(mat,1,&row,dlens[i],gmataj+cnt,gmataa+cnt,INSERT_VALUES);
344:       cnt += dlens[i];
345:     }
346:     if (rank) {
347:       PetscFree2(gmataa,gmataj);
348:     }
349:     PetscFree2(dlens,olens);
350:     PetscFree(rowners);

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

354:     *inmat = mat;
355:   } else {   /* column indices are already set; only need to move over numerical values from process 0 */
356:     Mat_SeqAIJ *Ad = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->A->data;
357:     Mat_SeqAIJ *Ao = (Mat_SeqAIJ*)((Mat_MPIAIJ*)((*inmat)->data))->B->data;
358:     mat  = *inmat;
359:     PetscObjectGetNewTag((PetscObject)mat,&tag);
360:     if (!rank) {
361:       /* send numerical values to other processes */
362:       gmata  = (Mat_SeqAIJ*) gmat->data;
363:       MatGetOwnershipRanges(mat,(const PetscInt**)&rowners);
364:       gmataa = gmata->a;
365:       for (i=1; i<size; i++) {
366:         nz   = gmata->i[rowners[i+1]]-gmata->i[rowners[i]];
367:         MPI_Send(gmataa + gmata->i[rowners[i]],nz,MPIU_SCALAR,i,tag,comm);
368:       }
369:       nz = gmata->i[rowners[1]]-gmata->i[rowners[0]];
370:     } else {
371:       /* receive numerical values from process 0*/
372:       nz   = Ad->nz + Ao->nz;
373:       PetscMalloc1(nz,&gmataa); gmataarestore = gmataa;
374:       MPI_Recv(gmataa,nz,MPIU_SCALAR,0,tag,comm,&status);
375:     }
376:     /* transfer numerical values into the diagonal A and off diagonal B parts of mat */
377:     ld = ((Mat_MPIAIJ*)(mat->data))->ld;
378:     ad = Ad->a;
379:     ao = Ao->a;
380:     if (mat->rmap->n) {
381:       i  = 0;
382:       nz = ld[i];                                   PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
383:       nz = Ad->i[i+1] - Ad->i[i];                   PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
384:     }
385:     for (i=1; i<mat->rmap->n; i++) {
386:       nz = Ao->i[i] - Ao->i[i-1] - ld[i-1] + ld[i]; PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar)); ao += nz; gmataa += nz;
387:       nz = Ad->i[i+1] - Ad->i[i];                   PetscMemcpy(ad,gmataa,nz*sizeof(PetscScalar)); ad += nz; gmataa += nz;
388:     }
389:     i--;
390:     if (mat->rmap->n) {
391:       nz = Ao->i[i+1] - Ao->i[i] - ld[i];           PetscMemcpy(ao,gmataa,nz*sizeof(PetscScalar));
392:     }
393:     if (rank) {
394:       PetscFree(gmataarestore);
395:     }
396:   }
397:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
398:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
399:   return(0);
400: }

402: /*
403:   Local utility routine that creates a mapping from the global column
404: number to the local number in the off-diagonal part of the local
405: storage of the matrix.  When PETSC_USE_CTABLE is used this is scalable at
406: a slightly higher hash table cost; without it it is not scalable (each processor
407: has an order N integer array but is fast to acess.
408: */
409: PetscErrorCode MatCreateColmap_MPIAIJ_Private(Mat mat)
410: {
411:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
413:   PetscInt       n = aij->B->cmap->n,i;

416:   if (!aij->garray) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"MPIAIJ Matrix was assembled but is missing garray");
417: #if defined(PETSC_USE_CTABLE)
418:   PetscTableCreate(n,mat->cmap->N+1,&aij->colmap);
419:   for (i=0; i<n; i++) {
420:     PetscTableAdd(aij->colmap,aij->garray[i]+1,i+1,INSERT_VALUES);
421:   }
422: #else
423:   PetscCalloc1(mat->cmap->N+1,&aij->colmap);
424:   PetscLogObjectMemory((PetscObject)mat,(mat->cmap->N+1)*sizeof(PetscInt));
425:   for (i=0; i<n; i++) aij->colmap[aij->garray[i]] = i+1;
426: #endif
427:   return(0);
428: }

430: #define MatSetValues_SeqAIJ_A_Private(row,col,value,addv,orow,ocol)     \
431: { \
432:     if (col <= lastcol1)  low1 = 0;     \
433:     else                 high1 = nrow1; \
434:     lastcol1 = col;\
435:     while (high1-low1 > 5) { \
436:       t = (low1+high1)/2; \
437:       if (rp1[t] > col) high1 = t; \
438:       else              low1  = t; \
439:     } \
440:       for (_i=low1; _i<high1; _i++) { \
441:         if (rp1[_i] > col) break; \
442:         if (rp1[_i] == col) { \
443:           if (addv == ADD_VALUES) { \
444:             ap1[_i] += value;   \
445:             /* Not sure LogFlops will slow dow the code or not */ \
446:             (void)PetscLogFlops(1.0);   \
447:            } \
448:           else                    ap1[_i] = value; \
449:           goto a_noinsert; \
450:         } \
451:       }  \
452:       if (value == 0.0 && ignorezeroentries && row != col) {low1 = 0; high1 = nrow1;goto a_noinsert;} \
453:       if (nonew == 1) {low1 = 0; high1 = nrow1; goto a_noinsert;}                \
454:       if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at global row/column (%D, %D) into matrix", orow, ocol); \
455:       MatSeqXAIJReallocateAIJ(A,am,1,nrow1,row,col,rmax1,aa,ai,aj,rp1,ap1,aimax,nonew,MatScalar); \
456:       N = nrow1++ - 1; a->nz++; high1++; \
457:       /* shift up all the later entries in this row */ \
458:       for (ii=N; ii>=_i; ii--) { \
459:         rp1[ii+1] = rp1[ii]; \
460:         ap1[ii+1] = ap1[ii]; \
461:       } \
462:       rp1[_i] = col;  \
463:       ap1[_i] = value;  \
464:       A->nonzerostate++;\
465:       a_noinsert: ; \
466:       ailen[row] = nrow1; \
467: }

469: #define MatSetValues_SeqAIJ_B_Private(row,col,value,addv,orow,ocol) \
470:   { \
471:     if (col <= lastcol2) low2 = 0;                        \
472:     else high2 = nrow2;                                   \
473:     lastcol2 = col;                                       \
474:     while (high2-low2 > 5) {                              \
475:       t = (low2+high2)/2;                                 \
476:       if (rp2[t] > col) high2 = t;                        \
477:       else             low2  = t;                         \
478:     }                                                     \
479:     for (_i=low2; _i<high2; _i++) {                       \
480:       if (rp2[_i] > col) break;                           \
481:       if (rp2[_i] == col) {                               \
482:         if (addv == ADD_VALUES) {                         \
483:           ap2[_i] += value;                               \
484:           (void)PetscLogFlops(1.0);                       \
485:         }                                                 \
486:         else                    ap2[_i] = value;          \
487:         goto b_noinsert;                                  \
488:       }                                                   \
489:     }                                                     \
490:     if (value == 0.0 && ignorezeroentries) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
491:     if (nonew == 1) {low2 = 0; high2 = nrow2; goto b_noinsert;}                        \
492:     if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at global row/column (%D, %D) into matrix", orow, ocol); \
493:     MatSeqXAIJReallocateAIJ(B,bm,1,nrow2,row,col,rmax2,ba,bi,bj,rp2,ap2,bimax,nonew,MatScalar); \
494:     N = nrow2++ - 1; b->nz++; high2++;                    \
495:     /* shift up all the later entries in this row */      \
496:     for (ii=N; ii>=_i; ii--) {                            \
497:       rp2[ii+1] = rp2[ii];                                \
498:       ap2[ii+1] = ap2[ii];                                \
499:     }                                                     \
500:     rp2[_i] = col;                                        \
501:     ap2[_i] = value;                                      \
502:     B->nonzerostate++;                                    \
503:     b_noinsert: ;                                         \
504:     bilen[row] = nrow2;                                   \
505:   }

507: PetscErrorCode MatSetValuesRow_MPIAIJ(Mat A,PetscInt row,const PetscScalar v[])
508: {
509:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)A->data;
510:   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)mat->A->data,*b = (Mat_SeqAIJ*)mat->B->data;
512:   PetscInt       l,*garray = mat->garray,diag;

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

517:   /* find size of row to the left of the diagonal part */
518:   MatGetOwnershipRange(A,&diag,0);
519:   row  = row - diag;
520:   for (l=0; l<b->i[row+1]-b->i[row]; l++) {
521:     if (garray[b->j[b->i[row]+l]] > diag) break;
522:   }
523:   PetscMemcpy(b->a+b->i[row],v,l*sizeof(PetscScalar));

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

528:   /* right of diagonal part */
529:   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));
530:   return(0);
531: }

533: PetscErrorCode MatSetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
534: {
535:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
536:   PetscScalar    value;
538:   PetscInt       i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
539:   PetscInt       cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
540:   PetscBool      roworiented = aij->roworiented;

542:   /* Some Variables required in the macro */
543:   Mat        A                 = aij->A;
544:   Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
545:   PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
546:   MatScalar  *aa               = a->a;
547:   PetscBool  ignorezeroentries = a->ignorezeroentries;
548:   Mat        B                 = aij->B;
549:   Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
550:   PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
551:   MatScalar  *ba               = b->a;

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

558:   for (i=0; i<m; i++) {
559:     if (im[i] < 0) continue;
560: #if defined(PETSC_USE_DEBUG)
561:     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);
562: #endif
563:     if (im[i] >= rstart && im[i] < rend) {
564:       row      = im[i] - rstart;
565:       lastcol1 = -1;
566:       rp1      = aj + ai[row];
567:       ap1      = aa + ai[row];
568:       rmax1    = aimax[row];
569:       nrow1    = ailen[row];
570:       low1     = 0;
571:       high1    = nrow1;
572:       lastcol2 = -1;
573:       rp2      = bj + bi[row];
574:       ap2      = ba + bi[row];
575:       rmax2    = bimax[row];
576:       nrow2    = bilen[row];
577:       low2     = 0;
578:       high2    = nrow2;

580:       for (j=0; j<n; j++) {
581:         if (roworiented) value = v[i*n+j];
582:         else             value = v[i+j*m];
583:         if (in[j] >= cstart && in[j] < cend) {
584:           col   = in[j] - cstart;
585:           nonew = a->nonew;
586:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && row != col) continue;
587:           MatSetValues_SeqAIJ_A_Private(row,col,value,addv,im[i],in[j]);
588:         } else if (in[j] < 0) continue;
589: #if defined(PETSC_USE_DEBUG)
590:         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);
591: #endif
592:         else {
593:           if (mat->was_assembled) {
594:             if (!aij->colmap) {
595:               MatCreateColmap_MPIAIJ_Private(mat);
596:             }
597: #if defined(PETSC_USE_CTABLE)
598:             PetscTableFind(aij->colmap,in[j]+1,&col);
599:             col--;
600: #else
601:             col = aij->colmap[in[j]] - 1;
602: #endif
603:             if (col < 0 && !((Mat_SeqAIJ*)(aij->B->data))->nonew) {
604:               MatDisAssemble_MPIAIJ(mat);
605:               col  =  in[j];
606:               /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
607:               B     = aij->B;
608:               b     = (Mat_SeqAIJ*)B->data;
609:               bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j; ba = b->a;
610:               rp2   = bj + bi[row];
611:               ap2   = ba + bi[row];
612:               rmax2 = bimax[row];
613:               nrow2 = bilen[row];
614:               low2  = 0;
615:               high2 = nrow2;
616:               bm    = aij->B->rmap->n;
617:               ba    = b->a;
618:             } else if (col < 0) {
619:               if (1 == ((Mat_SeqAIJ*)(aij->B->data))->nonew) {
620:                 PetscInfo3(mat,"Skipping of insertion of new nonzero location in off-diagonal portion of matrix %g(%D,%D)\n",(double)PetscRealPart(value),im[i],in[j]);
621:               } else SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at global row/column (%D, %D) into matrix", im[i], in[j]);
622:             }
623:           } else col = in[j];
624:           nonew = b->nonew;
625:           MatSetValues_SeqAIJ_B_Private(row,col,value,addv,im[i],in[j]);
626:         }
627:       }
628:     } else {
629:       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]);
630:       if (!aij->donotstash) {
631:         mat->assembled = PETSC_FALSE;
632:         if (roworiented) {
633:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
634:         } else {
635:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
636:         }
637:       }
638:     }
639:   }
640:   return(0);
641: }

643: /*
644:     This function sets the j and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
645:     The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
646:     No off-processor parts off the matrix are allowed here and mat->was_assembled has to be PETSC_FALSE.
647: */
648: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(Mat mat,const PetscInt mat_j[],const PetscInt mat_i[])
649: {
650:   Mat_MPIAIJ     *aij        = (Mat_MPIAIJ*)mat->data;
651:   Mat            A           = aij->A; /* diagonal part of the matrix */
652:   Mat            B           = aij->B; /* offdiagonal part of the matrix */
653:   Mat_SeqAIJ     *a          = (Mat_SeqAIJ*)A->data;
654:   Mat_SeqAIJ     *b          = (Mat_SeqAIJ*)B->data;
655:   PetscInt       cstart      = mat->cmap->rstart,cend = mat->cmap->rend,col;
656:   PetscInt       *ailen      = a->ilen,*aj = a->j;
657:   PetscInt       *bilen      = b->ilen,*bj = b->j;
658:   PetscInt       am          = aij->A->rmap->n,j;
659:   PetscInt       diag_so_far = 0,dnz;
660:   PetscInt       offd_so_far = 0,onz;

663:   /* Iterate over all rows of the matrix */
664:   for (j=0; j<am; j++) {
665:     dnz = onz = 0;
666:     /*  Iterate over all non-zero columns of the current row */
667:     for (col=mat_i[j]; col<mat_i[j+1]; col++) {
668:       /* If column is in the diagonal */
669:       if (mat_j[col] >= cstart && mat_j[col] < cend) {
670:         aj[diag_so_far++] = mat_j[col] - cstart;
671:         dnz++;
672:       } else { /* off-diagonal entries */
673:         bj[offd_so_far++] = mat_j[col];
674:         onz++;
675:       }
676:     }
677:     ailen[j] = dnz;
678:     bilen[j] = onz;
679:   }
680:   return(0);
681: }

683: /*
684:     This function sets the local j, a and ilen arrays (of the diagonal and off-diagonal part) of an MPIAIJ-matrix.
685:     The values in mat_i have to be sorted and the values in mat_j have to be sorted for each row (CSR-like).
686:     No off-processor parts off the matrix are allowed here, they are set at a later point by MatSetValues_MPIAIJ.
687:     Also, mat->was_assembled has to be false, otherwise the statement aj[rowstart_diag+dnz_row] = mat_j[col] - cstart;
688:     would not be true and the more complex MatSetValues_MPIAIJ has to be used.
689: */
690: PetscErrorCode MatSetValues_MPIAIJ_CopyFromCSRFormat(Mat mat,const PetscInt mat_j[],const PetscInt mat_i[],const PetscScalar mat_a[])
691: {
692:   Mat_MPIAIJ     *aij   = (Mat_MPIAIJ*)mat->data;
693:   Mat            A      = aij->A; /* diagonal part of the matrix */
694:   Mat            B      = aij->B; /* offdiagonal part of the matrix */
695:   Mat_SeqAIJ     *aijd  =(Mat_SeqAIJ*)(aij->A)->data,*aijo=(Mat_SeqAIJ*)(aij->B)->data;
696:   Mat_SeqAIJ     *a     = (Mat_SeqAIJ*)A->data;
697:   Mat_SeqAIJ     *b     = (Mat_SeqAIJ*)B->data;
698:   PetscInt       cstart = mat->cmap->rstart,cend = mat->cmap->rend;
699:   PetscInt       *ailen = a->ilen,*aj = a->j;
700:   PetscInt       *bilen = b->ilen,*bj = b->j;
701:   PetscInt       am     = aij->A->rmap->n,j;
702:   PetscInt       *full_diag_i=aijd->i,*full_offd_i=aijo->i; /* These variables can also include non-local elements, which are set at a later point. */
703:   PetscInt       col,dnz_row,onz_row,rowstart_diag,rowstart_offd;
704:   PetscScalar    *aa = a->a,*ba = b->a;

707:   /* Iterate over all rows of the matrix */
708:   for (j=0; j<am; j++) {
709:     dnz_row = onz_row = 0;
710:     rowstart_offd = full_offd_i[j];
711:     rowstart_diag = full_diag_i[j];
712:     /*  Iterate over all non-zero columns of the current row */
713:     for (col=mat_i[j]; col<mat_i[j+1]; col++) {
714:       /* If column is in the diagonal */
715:       if (mat_j[col] >= cstart && mat_j[col] < cend) {
716:         aj[rowstart_diag+dnz_row] = mat_j[col] - cstart;
717:         aa[rowstart_diag+dnz_row] = mat_a[col];
718:         dnz_row++;
719:       } else { /* off-diagonal entries */
720:         bj[rowstart_offd+onz_row] = mat_j[col];
721:         ba[rowstart_offd+onz_row] = mat_a[col];
722:         onz_row++;
723:       }
724:     }
725:     ailen[j] = dnz_row;
726:     bilen[j] = onz_row;
727:   }
728:   return(0);
729: }

731: PetscErrorCode MatGetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
732: {
733:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
735:   PetscInt       i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
736:   PetscInt       cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;

739:   for (i=0; i<m; i++) {
740:     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
741:     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);
742:     if (idxm[i] >= rstart && idxm[i] < rend) {
743:       row = idxm[i] - rstart;
744:       for (j=0; j<n; j++) {
745:         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
746:         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);
747:         if (idxn[j] >= cstart && idxn[j] < cend) {
748:           col  = idxn[j] - cstart;
749:           MatGetValues(aij->A,1,&row,1,&col,v+i*n+j);
750:         } else {
751:           if (!aij->colmap) {
752:             MatCreateColmap_MPIAIJ_Private(mat);
753:           }
754: #if defined(PETSC_USE_CTABLE)
755:           PetscTableFind(aij->colmap,idxn[j]+1,&col);
756:           col--;
757: #else
758:           col = aij->colmap[idxn[j]] - 1;
759: #endif
760:           if ((col < 0) || (aij->garray[col] != idxn[j])) *(v+i*n+j) = 0.0;
761:           else {
762:             MatGetValues(aij->B,1,&row,1,&col,v+i*n+j);
763:           }
764:         }
765:       }
766:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
767:   }
768:   return(0);
769: }

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

773: PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
774: {
775:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
777:   PetscInt       nstash,reallocs;

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

782:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
783:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
784:   PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
785:   return(0);
786: }

788: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat,MatAssemblyType mode)
789: {
790:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
791:   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)aij->A->data;
793:   PetscMPIInt    n;
794:   PetscInt       i,j,rstart,ncols,flg;
795:   PetscInt       *row,*col;
796:   PetscBool      other_disassembled;
797:   PetscScalar    *val;

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

802:   if (!aij->donotstash && !mat->nooffprocentries) {
803:     while (1) {
804:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
805:       if (!flg) break;

807:       for (i=0; i<n; ) {
808:         /* Now identify the consecutive vals belonging to the same row */
809:         for (j=i,rstart=row[j]; j<n; j++) {
810:           if (row[j] != rstart) break;
811:         }
812:         if (j < n) ncols = j-i;
813:         else       ncols = n-i;
814:         /* Now assemble all these values with a single function call */
815:         MatSetValues_MPIAIJ(mat,1,row+i,ncols,col+i,val+i,mat->insertmode);

817:         i = j;
818:       }
819:     }
820:     MatStashScatterEnd_Private(&mat->stash);
821:   }
822:   MatAssemblyBegin(aij->A,mode);
823:   MatAssemblyEnd(aij->A,mode);

825:   /* determine if any processor has disassembled, if so we must
826:      also disassemble ourselfs, in order that we may reassemble. */
827:   /*
828:      if nonzero structure of submatrix B cannot change then we know that
829:      no processor disassembled thus we can skip this stuff
830:   */
831:   if (!((Mat_SeqAIJ*)aij->B->data)->nonew) {
832:     MPIU_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));
833:     if (mat->was_assembled && !other_disassembled) {
834:       MatDisAssemble_MPIAIJ(mat);
835:     }
836:   }
837:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
838:     MatSetUpMultiply_MPIAIJ(mat);
839:   }
840:   MatSetOption(aij->B,MAT_USE_INODES,PETSC_FALSE);
841:   MatAssemblyBegin(aij->B,mode);
842:   MatAssemblyEnd(aij->B,mode);

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

846:   aij->rowvalues = 0;

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

851:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
852:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
853:     PetscObjectState state = aij->A->nonzerostate + aij->B->nonzerostate;
854:     MPIU_Allreduce(&state,&mat->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)mat));
855:   }
856:   return(0);
857: }

859: PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
860: {
861:   Mat_MPIAIJ     *l = (Mat_MPIAIJ*)A->data;

865:   MatZeroEntries(l->A);
866:   MatZeroEntries(l->B);
867:   return(0);
868: }

870: PetscErrorCode MatZeroRows_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
871: {
872:   Mat_MPIAIJ      *mat = (Mat_MPIAIJ *) A->data;
873:   PetscObjectState sA, sB;
874:   PetscInt        *lrows;
875:   PetscInt         r, len;
876:   PetscBool        cong, lch, gch;
877:   PetscErrorCode   ierr;

880:   /* get locally owned rows */
881:   MatZeroRowsMapLocal_Private(A,N,rows,&len,&lrows);
882:   MatHasCongruentLayouts(A,&cong);
883:   /* fix right hand side if needed */
884:   if (x && b) {
885:     const PetscScalar *xx;
886:     PetscScalar       *bb;

888:     if (!cong) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Need matching row/col layout");
889:     VecGetArrayRead(x, &xx);
890:     VecGetArray(b, &bb);
891:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag*xx[lrows[r]];
892:     VecRestoreArrayRead(x, &xx);
893:     VecRestoreArray(b, &bb);
894:   }

896:   sA = mat->A->nonzerostate;
897:   sB = mat->B->nonzerostate;

899:   if (diag != 0.0 && cong) {
900:     MatZeroRows(mat->A, len, lrows, diag, NULL, NULL);
901:     MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL);
902:   } else if (diag != 0.0) { /* non-square or non congruent layouts -> if keepnonzeropattern is false, we allow for new insertion */
903:     Mat_SeqAIJ *aijA = (Mat_SeqAIJ*)mat->A->data;
904:     Mat_SeqAIJ *aijB = (Mat_SeqAIJ*)mat->B->data;
905:     PetscInt   nnwA, nnwB;
906:     PetscBool  nnzA, nnzB;

908:     nnwA = aijA->nonew;
909:     nnwB = aijB->nonew;
910:     nnzA = aijA->keepnonzeropattern;
911:     nnzB = aijB->keepnonzeropattern;
912:     if (!nnzA) {
913:       PetscInfo(mat->A,"Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on diagonal block.\n");
914:       aijA->nonew = 0;
915:     }
916:     if (!nnzB) {
917:       PetscInfo(mat->B,"Requested to not keep the pattern and add a nonzero diagonal; may encounter reallocations on off-diagonal block.\n");
918:       aijB->nonew = 0;
919:     }
920:     /* Must zero here before the next loop */
921:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
922:     MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL);
923:     for (r = 0; r < len; ++r) {
924:       const PetscInt row = lrows[r] + A->rmap->rstart;
925:       if (row >= A->cmap->N) continue;
926:       MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES);
927:     }
928:     aijA->nonew = nnwA;
929:     aijB->nonew = nnwB;
930:   } else {
931:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
932:     MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL);
933:   }
934:   PetscFree(lrows);
935:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
936:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

938:   /* reduce nonzerostate */
939:   lch = (PetscBool)(sA != mat->A->nonzerostate || sB != mat->B->nonzerostate);
940:   MPIU_Allreduce(&lch,&gch,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)A));
941:   if (gch) A->nonzerostate++;
942:   return(0);
943: }

945: PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
946: {
947:   Mat_MPIAIJ        *l = (Mat_MPIAIJ*)A->data;
948:   PetscErrorCode    ierr;
949:   PetscMPIInt       n = A->rmap->n;
950:   PetscInt          i,j,r,m,p = 0,len = 0;
951:   PetscInt          *lrows,*owners = A->rmap->range;
952:   PetscSFNode       *rrows;
953:   PetscSF           sf;
954:   const PetscScalar *xx;
955:   PetscScalar       *bb,*mask;
956:   Vec               xmask,lmask;
957:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ*)l->B->data;
958:   const PetscInt    *aj, *ii,*ridx;
959:   PetscScalar       *aa;

962:   /* Create SF where leaves are input rows and roots are owned rows */
963:   PetscMalloc1(n, &lrows);
964:   for (r = 0; r < n; ++r) lrows[r] = -1;
965:   PetscMalloc1(N, &rrows);
966:   for (r = 0; r < N; ++r) {
967:     const PetscInt idx   = rows[r];
968:     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);
969:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
970:       PetscLayoutFindOwner(A->rmap,idx,&p);
971:     }
972:     rrows[r].rank  = p;
973:     rrows[r].index = rows[r] - owners[p];
974:   }
975:   PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
976:   PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
977:   /* Collect flags for rows to be zeroed */
978:   PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
979:   PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
980:   PetscSFDestroy(&sf);
981:   /* Compress and put in row numbers */
982:   for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
983:   /* zero diagonal part of matrix */
984:   MatZeroRowsColumns(l->A,len,lrows,diag,x,b);
985:   /* handle off diagonal part of matrix */
986:   MatCreateVecs(A,&xmask,NULL);
987:   VecDuplicate(l->lvec,&lmask);
988:   VecGetArray(xmask,&bb);
989:   for (i=0; i<len; i++) bb[lrows[i]] = 1;
990:   VecRestoreArray(xmask,&bb);
991:   VecScatterBegin(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
992:   VecScatterEnd(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
993:   VecDestroy(&xmask);
994:   if (x && b) { /* this code is buggy when the row and column layout don't match */
995:     PetscBool cong;

997:     MatHasCongruentLayouts(A,&cong);
998:     if (!cong) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Need matching row/col layout");
999:     VecScatterBegin(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
1000:     VecScatterEnd(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
1001:     VecGetArrayRead(l->lvec,&xx);
1002:     VecGetArray(b,&bb);
1003:   }
1004:   VecGetArray(lmask,&mask);
1005:   /* remove zeroed rows of off diagonal matrix */
1006:   ii = aij->i;
1007:   for (i=0; i<len; i++) {
1008:     PetscMemzero(aij->a + ii[lrows[i]],(ii[lrows[i]+1] - ii[lrows[i]])*sizeof(PetscScalar));
1009:   }
1010:   /* loop over all elements of off process part of matrix zeroing removed columns*/
1011:   if (aij->compressedrow.use) {
1012:     m    = aij->compressedrow.nrows;
1013:     ii   = aij->compressedrow.i;
1014:     ridx = aij->compressedrow.rindex;
1015:     for (i=0; i<m; i++) {
1016:       n  = ii[i+1] - ii[i];
1017:       aj = aij->j + ii[i];
1018:       aa = aij->a + ii[i];

1020:       for (j=0; j<n; j++) {
1021:         if (PetscAbsScalar(mask[*aj])) {
1022:           if (b) bb[*ridx] -= *aa*xx[*aj];
1023:           *aa = 0.0;
1024:         }
1025:         aa++;
1026:         aj++;
1027:       }
1028:       ridx++;
1029:     }
1030:   } else { /* do not use compressed row format */
1031:     m = l->B->rmap->n;
1032:     for (i=0; i<m; i++) {
1033:       n  = ii[i+1] - ii[i];
1034:       aj = aij->j + ii[i];
1035:       aa = aij->a + ii[i];
1036:       for (j=0; j<n; j++) {
1037:         if (PetscAbsScalar(mask[*aj])) {
1038:           if (b) bb[i] -= *aa*xx[*aj];
1039:           *aa = 0.0;
1040:         }
1041:         aa++;
1042:         aj++;
1043:       }
1044:     }
1045:   }
1046:   if (x && b) {
1047:     VecRestoreArray(b,&bb);
1048:     VecRestoreArrayRead(l->lvec,&xx);
1049:   }
1050:   VecRestoreArray(lmask,&mask);
1051:   VecDestroy(&lmask);
1052:   PetscFree(lrows);

1054:   /* only change matrix nonzero state if pattern was allowed to be changed */
1055:   if (!((Mat_SeqAIJ*)(l->A->data))->keepnonzeropattern) {
1056:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
1057:     MPIU_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
1058:   }
1059:   return(0);
1060: }

1062: PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
1063: {
1064:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1066:   PetscInt       nt;
1067:   VecScatter     Mvctx = a->Mvctx;

1070:   VecGetLocalSize(xx,&nt);
1071:   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);

1073:   VecScatterBegin(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1074:   (*a->A->ops->mult)(a->A,xx,yy);
1075:   VecScatterEnd(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1076:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
1077:   return(0);
1078: }

1080: PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A,Vec bb,Vec xx)
1081: {
1082:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1086:   MatMultDiagonalBlock(a->A,bb,xx);
1087:   return(0);
1088: }

1090: PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1091: {
1092:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1094:   VecScatter     Mvctx = a->Mvctx;

1097:   if (a->Mvctx_mpi1_flg) Mvctx = a->Mvctx_mpi1;
1098:   VecScatterBegin(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1099:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
1100:   VecScatterEnd(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1101:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
1102:   return(0);
1103: }

1105: PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
1106: {
1107:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1111:   /* do nondiagonal part */
1112:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1113:   /* do local part */
1114:   (*a->A->ops->multtranspose)(a->A,xx,yy);
1115:   /* add partial results together */
1116:   VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1117:   VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1118:   return(0);
1119: }

1121: PetscErrorCode MatIsTranspose_MPIAIJ(Mat Amat,Mat Bmat,PetscReal tol,PetscBool  *f)
1122: {
1123:   MPI_Comm       comm;
1124:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ*) Amat->data, *Bij;
1125:   Mat            Adia = Aij->A, Bdia, Aoff,Boff,*Aoffs,*Boffs;
1126:   IS             Me,Notme;
1128:   PetscInt       M,N,first,last,*notme,i;
1129:   PetscBool      lf;
1130:   PetscMPIInt    size;

1133:   /* Easy test: symmetric diagonal block */
1134:   Bij  = (Mat_MPIAIJ*) Bmat->data; Bdia = Bij->A;
1135:   MatIsTranspose(Adia,Bdia,tol,&lf);
1136:   MPIU_Allreduce(&lf,f,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)Amat));
1137:   if (!*f) return(0);
1138:   PetscObjectGetComm((PetscObject)Amat,&comm);
1139:   MPI_Comm_size(comm,&size);
1140:   if (size == 1) return(0);

1142:   /* Hard test: off-diagonal block. This takes a MatCreateSubMatrix. */
1143:   MatGetSize(Amat,&M,&N);
1144:   MatGetOwnershipRange(Amat,&first,&last);
1145:   PetscMalloc1(N-last+first,&notme);
1146:   for (i=0; i<first; i++) notme[i] = i;
1147:   for (i=last; i<M; i++) notme[i-last+first] = i;
1148:   ISCreateGeneral(MPI_COMM_SELF,N-last+first,notme,PETSC_COPY_VALUES,&Notme);
1149:   ISCreateStride(MPI_COMM_SELF,last-first,first,1,&Me);
1150:   MatCreateSubMatrices(Amat,1,&Me,&Notme,MAT_INITIAL_MATRIX,&Aoffs);
1151:   Aoff = Aoffs[0];
1152:   MatCreateSubMatrices(Bmat,1,&Notme,&Me,MAT_INITIAL_MATRIX,&Boffs);
1153:   Boff = Boffs[0];
1154:   MatIsTranspose(Aoff,Boff,tol,f);
1155:   MatDestroyMatrices(1,&Aoffs);
1156:   MatDestroyMatrices(1,&Boffs);
1157:   ISDestroy(&Me);
1158:   ISDestroy(&Notme);
1159:   PetscFree(notme);
1160:   return(0);
1161: }

1163: PetscErrorCode MatIsSymmetric_MPIAIJ(Mat A,PetscReal tol,PetscBool  *f)
1164: {

1168:   MatIsTranspose_MPIAIJ(A,A,tol,f);
1169:   return(0);
1170: }

1172: PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1173: {
1174:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1178:   /* do nondiagonal part */
1179:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1180:   /* do local part */
1181:   (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
1182:   /* add partial results together */
1183:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1184:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1185:   return(0);
1186: }

1188: /*
1189:   This only works correctly for square matrices where the subblock A->A is the
1190:    diagonal block
1191: */
1192: PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
1193: {
1195:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1198:   if (A->rmap->N != A->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1199:   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");
1200:   MatGetDiagonal(a->A,v);
1201:   return(0);
1202: }

1204: PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
1205: {
1206:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1210:   MatScale(a->A,aa);
1211:   MatScale(a->B,aa);
1212:   return(0);
1213: }

1215: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
1216: {
1217:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

1221: #if defined(PETSC_USE_LOG)
1222:   PetscLogObjectState((PetscObject)mat,"Rows=%D, Cols=%D",mat->rmap->N,mat->cmap->N);
1223: #endif
1224:   MatStashDestroy_Private(&mat->stash);
1225:   VecDestroy(&aij->diag);
1226:   MatDestroy(&aij->A);
1227:   MatDestroy(&aij->B);
1228: #if defined(PETSC_USE_CTABLE)
1229:   PetscTableDestroy(&aij->colmap);
1230: #else
1231:   PetscFree(aij->colmap);
1232: #endif
1233:   PetscFree(aij->garray);
1234:   VecDestroy(&aij->lvec);
1235:   VecScatterDestroy(&aij->Mvctx);
1236:   if (aij->Mvctx_mpi1) {VecScatterDestroy(&aij->Mvctx_mpi1);}
1237:   PetscFree2(aij->rowvalues,aij->rowindices);
1238:   PetscFree(aij->ld);
1239:   PetscFree(mat->data);

1241:   PetscObjectChangeTypeName((PetscObject)mat,0);
1242:   PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);
1243:   PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);
1244:   PetscObjectComposeFunction((PetscObject)mat,"MatIsTranspose_C",NULL);
1245:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocation_C",NULL);
1246:   PetscObjectComposeFunction((PetscObject)mat,"MatResetPreallocation_C",NULL);
1247:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocationCSR_C",NULL);
1248:   PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",NULL);
1249:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_mpisbaij_C",NULL);
1250: #if defined(PETSC_HAVE_ELEMENTAL)
1251:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_elemental_C",NULL);
1252: #endif
1253: #if defined(PETSC_HAVE_HYPRE)
1254:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_hypre_C",NULL);
1255:   PetscObjectComposeFunction((PetscObject)mat,"MatMatMatMult_transpose_mpiaij_mpiaij_C",NULL);
1256: #endif
1257:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_is_C",NULL);
1258:   PetscObjectComposeFunction((PetscObject)mat,"MatPtAP_is_mpiaij_C",NULL);
1259:   return(0);
1260: }

1262: PetscErrorCode MatView_MPIAIJ_Binary(Mat mat,PetscViewer viewer)
1263: {
1264:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
1265:   Mat_SeqAIJ     *A   = (Mat_SeqAIJ*)aij->A->data;
1266:   Mat_SeqAIJ     *B   = (Mat_SeqAIJ*)aij->B->data;
1268:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
1269:   int            fd;
1270:   PetscInt       nz,header[4],*row_lengths,*range=0,rlen,i;
1271:   PetscInt       nzmax,*column_indices,j,k,col,*garray = aij->garray,cnt,cstart = mat->cmap->rstart,rnz = 0;
1272:   PetscScalar    *column_values;
1273:   PetscInt       message_count,flowcontrolcount;
1274:   FILE           *file;

1277:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1278:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1279:   nz   = A->nz + B->nz;
1280:   PetscViewerBinaryGetDescriptor(viewer,&fd);
1281:   if (!rank) {
1282:     header[0] = MAT_FILE_CLASSID;
1283:     header[1] = mat->rmap->N;
1284:     header[2] = mat->cmap->N;

1286:     MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1287:     PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);
1288:     /* get largest number of rows any processor has */
1289:     rlen  = mat->rmap->n;
1290:     range = mat->rmap->range;
1291:     for (i=1; i<size; i++) rlen = PetscMax(rlen,range[i+1] - range[i]);
1292:   } else {
1293:     MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1294:     rlen = mat->rmap->n;
1295:   }

1297:   /* load up the local row counts */
1298:   PetscMalloc1(rlen+1,&row_lengths);
1299:   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];

1301:   /* store the row lengths to the file */
1302:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1303:   if (!rank) {
1304:     PetscBinaryWrite(fd,row_lengths,mat->rmap->n,PETSC_INT,PETSC_TRUE);
1305:     for (i=1; i<size; i++) {
1306:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1307:       rlen = range[i+1] - range[i];
1308:       MPIULong_Recv(row_lengths,rlen,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1309:       PetscBinaryWrite(fd,row_lengths,rlen,PETSC_INT,PETSC_TRUE);
1310:     }
1311:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1312:   } else {
1313:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1314:     MPIULong_Send(row_lengths,mat->rmap->n,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1315:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1316:   }
1317:   PetscFree(row_lengths);

1319:   /* load up the local column indices */
1320:   nzmax = nz; /* th processor needs space a largest processor needs */
1321:   MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,PetscObjectComm((PetscObject)mat));
1322:   PetscMalloc1(nzmax+1,&column_indices);
1323:   cnt   = 0;
1324:   for (i=0; i<mat->rmap->n; i++) {
1325:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1326:       if ((col = garray[B->j[j]]) > cstart) break;
1327:       column_indices[cnt++] = col;
1328:     }
1329:     for (k=A->i[i]; k<A->i[i+1]; k++) column_indices[cnt++] = A->j[k] + cstart;
1330:     for (; j<B->i[i+1]; j++) column_indices[cnt++] = garray[B->j[j]];
1331:   }
1332:   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);

1334:   /* store the column indices to the file */
1335:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1336:   if (!rank) {
1337:     MPI_Status status;
1338:     PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);
1339:     for (i=1; i<size; i++) {
1340:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1341:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1342:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1343:       MPIULong_Recv(column_indices,rnz,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1344:       PetscBinaryWrite(fd,column_indices,rnz,PETSC_INT,PETSC_TRUE);
1345:     }
1346:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1347:   } else {
1348:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1349:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1350:     MPIULong_Send(column_indices,nz,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1351:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1352:   }
1353:   PetscFree(column_indices);

1355:   /* load up the local column values */
1356:   PetscMalloc1(nzmax+1,&column_values);
1357:   cnt  = 0;
1358:   for (i=0; i<mat->rmap->n; i++) {
1359:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1360:       if (garray[B->j[j]] > cstart) break;
1361:       column_values[cnt++] = B->a[j];
1362:     }
1363:     for (k=A->i[i]; k<A->i[i+1]; k++) column_values[cnt++] = A->a[k];
1364:     for (; j<B->i[i+1]; j++) column_values[cnt++] = B->a[j];
1365:   }
1366:   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);

1368:   /* store the column values to the file */
1369:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1370:   if (!rank) {
1371:     MPI_Status status;
1372:     PetscBinaryWrite(fd,column_values,nz,PETSC_SCALAR,PETSC_TRUE);
1373:     for (i=1; i<size; i++) {
1374:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1375:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1376:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1377:       MPIULong_Recv(column_values,rnz,MPIU_SCALAR,i,tag,PetscObjectComm((PetscObject)mat));
1378:       PetscBinaryWrite(fd,column_values,rnz,PETSC_SCALAR,PETSC_TRUE);
1379:     }
1380:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1381:   } else {
1382:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1383:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1384:     MPIULong_Send(column_values,nz,MPIU_SCALAR,0,tag,PetscObjectComm((PetscObject)mat));
1385:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1386:   }
1387:   PetscFree(column_values);

1389:   PetscViewerBinaryGetInfoPointer(viewer,&file);
1390:   if (file) fprintf(file,"-matload_block_size %d\n",(int)PetscAbs(mat->rmap->bs));
1391:   return(0);
1392: }

1394:  #include <petscdraw.h>
1395: PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1396: {
1397:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*)mat->data;
1398:   PetscErrorCode    ierr;
1399:   PetscMPIInt       rank = aij->rank,size = aij->size;
1400:   PetscBool         isdraw,iascii,isbinary;
1401:   PetscViewer       sviewer;
1402:   PetscViewerFormat format;

1405:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1406:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1407:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1408:   if (iascii) {
1409:     PetscViewerGetFormat(viewer,&format);
1410:     if (format == PETSC_VIEWER_LOAD_BALANCE) {
1411:       PetscInt i,nmax = 0,nmin = PETSC_MAX_INT,navg = 0,*nz,nzlocal = ((Mat_SeqAIJ*) (aij->A->data))->nz + ((Mat_SeqAIJ*) (aij->B->data))->nz;
1412:       PetscMalloc1(size,&nz);
1413:       MPI_Allgather(&nzlocal,1,MPIU_INT,nz,1,MPIU_INT,PetscObjectComm((PetscObject)mat));
1414:       for (i=0; i<(PetscInt)size; i++) {
1415:         nmax = PetscMax(nmax,nz[i]);
1416:         nmin = PetscMin(nmin,nz[i]);
1417:         navg += nz[i];
1418:       }
1419:       PetscFree(nz);
1420:       navg = navg/size;
1421:       PetscViewerASCIIPrintf(viewer,"Load Balance - Nonzeros: Min %D  avg %D  max %D\n",nmin,navg,nmax);
1422:       return(0);
1423:     }
1424:     PetscViewerGetFormat(viewer,&format);
1425:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1426:       MatInfo   info;
1427:       PetscBool inodes;

1429:       MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1430:       MatGetInfo(mat,MAT_LOCAL,&info);
1431:       MatInodeGetInodeSizes(aij->A,NULL,(PetscInt**)&inodes,NULL);
1432:       PetscViewerASCIIPushSynchronized(viewer);
1433:       if (!inodes) {
1434:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %g, not using I-node routines\n",
1435:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(double)info.memory);
1436:       } else {
1437:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %g, using I-node routines\n",
1438:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(double)info.memory);
1439:       }
1440:       MatGetInfo(aij->A,MAT_LOCAL,&info);
1441:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1442:       MatGetInfo(aij->B,MAT_LOCAL,&info);
1443:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1444:       PetscViewerFlush(viewer);
1445:       PetscViewerASCIIPopSynchronized(viewer);
1446:       PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
1447:       VecScatterView(aij->Mvctx,viewer);
1448:       return(0);
1449:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1450:       PetscInt inodecount,inodelimit,*inodes;
1451:       MatInodeGetInodeSizes(aij->A,&inodecount,&inodes,&inodelimit);
1452:       if (inodes) {
1453:         PetscViewerASCIIPrintf(viewer,"using I-node (on process 0) routines: found %D nodes, limit used is %D\n",inodecount,inodelimit);
1454:       } else {
1455:         PetscViewerASCIIPrintf(viewer,"not using I-node (on process 0) routines\n");
1456:       }
1457:       return(0);
1458:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1459:       return(0);
1460:     }
1461:   } else if (isbinary) {
1462:     if (size == 1) {
1463:       PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1464:       MatView(aij->A,viewer);
1465:     } else {
1466:       MatView_MPIAIJ_Binary(mat,viewer);
1467:     }
1468:     return(0);
1469:   } else if (iascii && size == 1) {
1470:     PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1471:     MatView(aij->A,viewer);
1472:     return(0);
1473:   } else if (isdraw) {
1474:     PetscDraw draw;
1475:     PetscBool isnull;
1476:     PetscViewerDrawGetDraw(viewer,0,&draw);
1477:     PetscDrawIsNull(draw,&isnull);
1478:     if (isnull) return(0);
1479:   }

1481:   { /* assemble the entire matrix onto first processor */
1482:     Mat A = NULL, Av;
1483:     IS  isrow,iscol;

1485:     ISCreateStride(PetscObjectComm((PetscObject)mat),!rank ? mat->rmap->N : 0,0,1,&isrow);
1486:     ISCreateStride(PetscObjectComm((PetscObject)mat),!rank ? mat->cmap->N : 0,0,1,&iscol);
1487:     MatCreateSubMatrix(mat,isrow,iscol,MAT_INITIAL_MATRIX,&A);
1488:     MatMPIAIJGetSeqAIJ(A,&Av,NULL,NULL);
1489: /*  The commented code uses MatCreateSubMatrices instead */
1490: /*
1491:     Mat *AA, A = NULL, Av;
1492:     IS  isrow,iscol;

1494:     ISCreateStride(PetscObjectComm((PetscObject)mat),!rank ? mat->rmap->N : 0,0,1,&isrow);
1495:     ISCreateStride(PetscObjectComm((PetscObject)mat),!rank ? mat->cmap->N : 0,0,1,&iscol);
1496:     MatCreateSubMatrices(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&AA);
1497:     if (!rank) {
1498:        PetscObjectReference((PetscObject)AA[0]);
1499:        A    = AA[0];
1500:        Av   = AA[0];
1501:     }
1502:     MatDestroySubMatrices(1,&AA);
1503: */
1504:     ISDestroy(&iscol);
1505:     ISDestroy(&isrow);
1506:     /*
1507:        Everyone has to call to draw the matrix since the graphics waits are
1508:        synchronized across all processors that share the PetscDraw object
1509:     */
1510:     PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1511:     if (!rank) {
1512:       if (((PetscObject)mat)->name) {
1513:         PetscObjectSetName((PetscObject)Av,((PetscObject)mat)->name);
1514:       }
1515:       MatView_SeqAIJ(Av,sviewer);
1516:     }
1517:     PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1518:     PetscViewerFlush(viewer);
1519:     MatDestroy(&A);
1520:   }
1521:   return(0);
1522: }

1524: PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1525: {
1527:   PetscBool      iascii,isdraw,issocket,isbinary;

1530:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1531:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1532:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1533:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
1534:   if (iascii || isdraw || isbinary || issocket) {
1535:     MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);
1536:   }
1537:   return(0);
1538: }

1540: PetscErrorCode MatSOR_MPIAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1541: {
1542:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1544:   Vec            bb1 = 0;
1545:   PetscBool      hasop;

1548:   if (flag == SOR_APPLY_UPPER) {
1549:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1550:     return(0);
1551:   }

1553:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) {
1554:     VecDuplicate(bb,&bb1);
1555:   }

1557:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1558:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1559:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1560:       its--;
1561:     }

1563:     while (its--) {
1564:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1565:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1567:       /* update rhs: bb1 = bb - B*x */
1568:       VecScale(mat->lvec,-1.0);
1569:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1571:       /* local sweep */
1572:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,1,xx);
1573:     }
1574:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1575:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1576:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1577:       its--;
1578:     }
1579:     while (its--) {
1580:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1581:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1583:       /* update rhs: bb1 = bb - B*x */
1584:       VecScale(mat->lvec,-1.0);
1585:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1587:       /* local sweep */
1588:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,1,xx);
1589:     }
1590:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1591:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1592:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1593:       its--;
1594:     }
1595:     while (its--) {
1596:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1597:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1599:       /* update rhs: bb1 = bb - B*x */
1600:       VecScale(mat->lvec,-1.0);
1601:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1603:       /* local sweep */
1604:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);
1605:     }
1606:   } else if (flag & SOR_EISENSTAT) {
1607:     Vec xx1;

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

1612:     VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1613:     VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1614:     if (!mat->diag) {
1615:       MatCreateVecs(matin,&mat->diag,NULL);
1616:       MatGetDiagonal(matin,mat->diag);
1617:     }
1618:     MatHasOperation(matin,MATOP_MULT_DIAGONAL_BLOCK,&hasop);
1619:     if (hasop) {
1620:       MatMultDiagonalBlock(matin,xx,bb1);
1621:     } else {
1622:       VecPointwiseMult(bb1,mat->diag,xx);
1623:     }
1624:     VecAYPX(bb1,(omega-2.0)/omega,bb);

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

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

1634:   VecDestroy(&bb1);

1636:   matin->factorerrortype = mat->A->factorerrortype;
1637:   return(0);
1638: }

1640: PetscErrorCode MatPermute_MPIAIJ(Mat A,IS rowp,IS colp,Mat *B)
1641: {
1642:   Mat            aA,aB,Aperm;
1643:   const PetscInt *rwant,*cwant,*gcols,*ai,*bi,*aj,*bj;
1644:   PetscScalar    *aa,*ba;
1645:   PetscInt       i,j,m,n,ng,anz,bnz,*dnnz,*onnz,*tdnnz,*tonnz,*rdest,*cdest,*work,*gcdest;
1646:   PetscSF        rowsf,sf;
1647:   IS             parcolp = NULL;
1648:   PetscBool      done;

1652:   MatGetLocalSize(A,&m,&n);
1653:   ISGetIndices(rowp,&rwant);
1654:   ISGetIndices(colp,&cwant);
1655:   PetscMalloc3(PetscMax(m,n),&work,m,&rdest,n,&cdest);

1657:   /* Invert row permutation to find out where my rows should go */
1658:   PetscSFCreate(PetscObjectComm((PetscObject)A),&rowsf);
1659:   PetscSFSetGraphLayout(rowsf,A->rmap,A->rmap->n,NULL,PETSC_OWN_POINTER,rwant);
1660:   PetscSFSetFromOptions(rowsf);
1661:   for (i=0; i<m; i++) work[i] = A->rmap->rstart + i;
1662:   PetscSFReduceBegin(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);
1663:   PetscSFReduceEnd(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);

1665:   /* Invert column permutation to find out where my columns should go */
1666:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1667:   PetscSFSetGraphLayout(sf,A->cmap,A->cmap->n,NULL,PETSC_OWN_POINTER,cwant);
1668:   PetscSFSetFromOptions(sf);
1669:   for (i=0; i<n; i++) work[i] = A->cmap->rstart + i;
1670:   PetscSFReduceBegin(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1671:   PetscSFReduceEnd(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1672:   PetscSFDestroy(&sf);

1674:   ISRestoreIndices(rowp,&rwant);
1675:   ISRestoreIndices(colp,&cwant);
1676:   MatMPIAIJGetSeqAIJ(A,&aA,&aB,&gcols);

1678:   /* Find out where my gcols should go */
1679:   MatGetSize(aB,NULL,&ng);
1680:   PetscMalloc1(ng,&gcdest);
1681:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1682:   PetscSFSetGraphLayout(sf,A->cmap,ng,NULL,PETSC_OWN_POINTER,gcols);
1683:   PetscSFSetFromOptions(sf);
1684:   PetscSFBcastBegin(sf,MPIU_INT,cdest,gcdest);
1685:   PetscSFBcastEnd(sf,MPIU_INT,cdest,gcdest);
1686:   PetscSFDestroy(&sf);

1688:   PetscCalloc4(m,&dnnz,m,&onnz,m,&tdnnz,m,&tonnz);
1689:   MatGetRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1690:   MatGetRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1691:   for (i=0; i<m; i++) {
1692:     PetscInt row = rdest[i],rowner;
1693:     PetscLayoutFindOwner(A->rmap,row,&rowner);
1694:     for (j=ai[i]; j<ai[i+1]; j++) {
1695:       PetscInt cowner,col = cdest[aj[j]];
1696:       PetscLayoutFindOwner(A->cmap,col,&cowner); /* Could build an index for the columns to eliminate this search */
1697:       if (rowner == cowner) dnnz[i]++;
1698:       else onnz[i]++;
1699:     }
1700:     for (j=bi[i]; j<bi[i+1]; j++) {
1701:       PetscInt cowner,col = gcdest[bj[j]];
1702:       PetscLayoutFindOwner(A->cmap,col,&cowner);
1703:       if (rowner == cowner) dnnz[i]++;
1704:       else onnz[i]++;
1705:     }
1706:   }
1707:   PetscSFBcastBegin(rowsf,MPIU_INT,dnnz,tdnnz);
1708:   PetscSFBcastEnd(rowsf,MPIU_INT,dnnz,tdnnz);
1709:   PetscSFBcastBegin(rowsf,MPIU_INT,onnz,tonnz);
1710:   PetscSFBcastEnd(rowsf,MPIU_INT,onnz,tonnz);
1711:   PetscSFDestroy(&rowsf);

1713:   MatCreateAIJ(PetscObjectComm((PetscObject)A),A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N,0,tdnnz,0,tonnz,&Aperm);
1714:   MatSeqAIJGetArray(aA,&aa);
1715:   MatSeqAIJGetArray(aB,&ba);
1716:   for (i=0; i<m; i++) {
1717:     PetscInt *acols = dnnz,*bcols = onnz; /* Repurpose now-unneeded arrays */
1718:     PetscInt j0,rowlen;
1719:     rowlen = ai[i+1] - ai[i];
1720:     for (j0=j=0; j<rowlen; j0=j) { /* rowlen could be larger than number of rows m, so sum in batches */
1721:       for ( ; j<PetscMin(rowlen,j0+m); j++) acols[j-j0] = cdest[aj[ai[i]+j]];
1722:       MatSetValues(Aperm,1,&rdest[i],j-j0,acols,aa+ai[i]+j0,INSERT_VALUES);
1723:     }
1724:     rowlen = bi[i+1] - bi[i];
1725:     for (j0=j=0; j<rowlen; j0=j) {
1726:       for ( ; j<PetscMin(rowlen,j0+m); j++) bcols[j-j0] = gcdest[bj[bi[i]+j]];
1727:       MatSetValues(Aperm,1,&rdest[i],j-j0,bcols,ba+bi[i]+j0,INSERT_VALUES);
1728:     }
1729:   }
1730:   MatAssemblyBegin(Aperm,MAT_FINAL_ASSEMBLY);
1731:   MatAssemblyEnd(Aperm,MAT_FINAL_ASSEMBLY);
1732:   MatRestoreRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1733:   MatRestoreRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1734:   MatSeqAIJRestoreArray(aA,&aa);
1735:   MatSeqAIJRestoreArray(aB,&ba);
1736:   PetscFree4(dnnz,onnz,tdnnz,tonnz);
1737:   PetscFree3(work,rdest,cdest);
1738:   PetscFree(gcdest);
1739:   if (parcolp) {ISDestroy(&colp);}
1740:   *B = Aperm;
1741:   return(0);
1742: }

1744: PetscErrorCode  MatGetGhosts_MPIAIJ(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
1745: {
1746:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1750:   MatGetSize(aij->B,NULL,nghosts);
1751:   if (ghosts) *ghosts = aij->garray;
1752:   return(0);
1753: }

1755: PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1756: {
1757:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1758:   Mat            A    = mat->A,B = mat->B;
1760:   PetscReal      isend[5],irecv[5];

1763:   info->block_size = 1.0;
1764:   MatGetInfo(A,MAT_LOCAL,info);

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

1769:   MatGetInfo(B,MAT_LOCAL,info);

1771:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1772:   isend[3] += info->memory;  isend[4] += info->mallocs;
1773:   if (flag == MAT_LOCAL) {
1774:     info->nz_used      = isend[0];
1775:     info->nz_allocated = isend[1];
1776:     info->nz_unneeded  = isend[2];
1777:     info->memory       = isend[3];
1778:     info->mallocs      = isend[4];
1779:   } else if (flag == MAT_GLOBAL_MAX) {
1780:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

1782:     info->nz_used      = irecv[0];
1783:     info->nz_allocated = irecv[1];
1784:     info->nz_unneeded  = irecv[2];
1785:     info->memory       = irecv[3];
1786:     info->mallocs      = irecv[4];
1787:   } else if (flag == MAT_GLOBAL_SUM) {
1788:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));

1790:     info->nz_used      = irecv[0];
1791:     info->nz_allocated = irecv[1];
1792:     info->nz_unneeded  = irecv[2];
1793:     info->memory       = irecv[3];
1794:     info->mallocs      = irecv[4];
1795:   }
1796:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1797:   info->fill_ratio_needed = 0;
1798:   info->factor_mallocs    = 0;
1799:   return(0);
1800: }

1802: PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscBool flg)
1803: {
1804:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1808:   switch (op) {
1809:   case MAT_NEW_NONZERO_LOCATIONS:
1810:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1811:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1812:   case MAT_KEEP_NONZERO_PATTERN:
1813:   case MAT_NEW_NONZERO_LOCATION_ERR:
1814:   case MAT_USE_INODES:
1815:   case MAT_IGNORE_ZERO_ENTRIES:
1816:     MatCheckPreallocated(A,1);
1817:     MatSetOption(a->A,op,flg);
1818:     MatSetOption(a->B,op,flg);
1819:     break;
1820:   case MAT_ROW_ORIENTED:
1821:     MatCheckPreallocated(A,1);
1822:     a->roworiented = flg;

1824:     MatSetOption(a->A,op,flg);
1825:     MatSetOption(a->B,op,flg);
1826:     break;
1827:   case MAT_NEW_DIAGONALS:
1828:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1829:     break;
1830:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1831:     a->donotstash = flg;
1832:     break;
1833:   /* Symmetry flags are handled directly by MatSetOption() and they don't affect preallocation */
1834:   case MAT_SPD:
1835:   case MAT_SYMMETRIC:
1836:   case MAT_STRUCTURALLY_SYMMETRIC:
1837:   case MAT_HERMITIAN:
1838:   case MAT_SYMMETRY_ETERNAL:
1839:     break;
1840:   case MAT_SUBMAT_SINGLEIS:
1841:     A->submat_singleis = flg;
1842:     break;
1843:   case MAT_STRUCTURE_ONLY:
1844:     /* The option is handled directly by MatSetOption() */
1845:     break;
1846:   default:
1847:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1848:   }
1849:   return(0);
1850: }

1852: PetscErrorCode MatGetRow_MPIAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1853: {
1854:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1855:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
1857:   PetscInt       i,*cworkA,*cworkB,**pcA,**pcB,cstart = matin->cmap->rstart;
1858:   PetscInt       nztot,nzA,nzB,lrow,rstart = matin->rmap->rstart,rend = matin->rmap->rend;
1859:   PetscInt       *cmap,*idx_p;

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

1865:   if (!mat->rowvalues && (idx || v)) {
1866:     /*
1867:         allocate enough space to hold information from the longest row.
1868:     */
1869:     Mat_SeqAIJ *Aa = (Mat_SeqAIJ*)mat->A->data,*Ba = (Mat_SeqAIJ*)mat->B->data;
1870:     PetscInt   max = 1,tmp;
1871:     for (i=0; i<matin->rmap->n; i++) {
1872:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
1873:       if (max < tmp) max = tmp;
1874:     }
1875:     PetscMalloc2(max,&mat->rowvalues,max,&mat->rowindices);
1876:   }

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

1881:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1882:   if (!v)   {pvA = 0; pvB = 0;}
1883:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1884:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1885:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1886:   nztot = nzA + nzB;

1888:   cmap = mat->garray;
1889:   if (v  || idx) {
1890:     if (nztot) {
1891:       /* Sort by increasing column numbers, assuming A and B already sorted */
1892:       PetscInt imark = -1;
1893:       if (v) {
1894:         *v = v_p = mat->rowvalues;
1895:         for (i=0; i<nzB; i++) {
1896:           if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1897:           else break;
1898:         }
1899:         imark = i;
1900:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1901:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1902:       }
1903:       if (idx) {
1904:         *idx = idx_p = mat->rowindices;
1905:         if (imark > -1) {
1906:           for (i=0; i<imark; i++) {
1907:             idx_p[i] = cmap[cworkB[i]];
1908:           }
1909:         } else {
1910:           for (i=0; i<nzB; i++) {
1911:             if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1912:             else break;
1913:           }
1914:           imark = i;
1915:         }
1916:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart + cworkA[i];
1917:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]];
1918:       }
1919:     } else {
1920:       if (idx) *idx = 0;
1921:       if (v)   *v   = 0;
1922:     }
1923:   }
1924:   *nz  = nztot;
1925:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1926:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1927:   return(0);
1928: }

1930: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1931: {
1932:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1935:   if (!aij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1936:   aij->getrowactive = PETSC_FALSE;
1937:   return(0);
1938: }

1940: PetscErrorCode MatNorm_MPIAIJ(Mat mat,NormType type,PetscReal *norm)
1941: {
1942:   Mat_MPIAIJ     *aij  = (Mat_MPIAIJ*)mat->data;
1943:   Mat_SeqAIJ     *amat = (Mat_SeqAIJ*)aij->A->data,*bmat = (Mat_SeqAIJ*)aij->B->data;
1945:   PetscInt       i,j,cstart = mat->cmap->rstart;
1946:   PetscReal      sum = 0.0;
1947:   MatScalar      *v;

1950:   if (aij->size == 1) {
1951:      MatNorm(aij->A,type,norm);
1952:   } else {
1953:     if (type == NORM_FROBENIUS) {
1954:       v = amat->a;
1955:       for (i=0; i<amat->nz; i++) {
1956:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1957:       }
1958:       v = bmat->a;
1959:       for (i=0; i<bmat->nz; i++) {
1960:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1961:       }
1962:       MPIU_Allreduce(&sum,norm,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1963:       *norm = PetscSqrtReal(*norm);
1964:       PetscLogFlops(2*amat->nz+2*bmat->nz);
1965:     } else if (type == NORM_1) { /* max column norm */
1966:       PetscReal *tmp,*tmp2;
1967:       PetscInt  *jj,*garray = aij->garray;
1968:       PetscCalloc1(mat->cmap->N+1,&tmp);
1969:       PetscMalloc1(mat->cmap->N+1,&tmp2);
1970:       *norm = 0.0;
1971:       v     = amat->a; jj = amat->j;
1972:       for (j=0; j<amat->nz; j++) {
1973:         tmp[cstart + *jj++] += PetscAbsScalar(*v);  v++;
1974:       }
1975:       v = bmat->a; jj = bmat->j;
1976:       for (j=0; j<bmat->nz; j++) {
1977:         tmp[garray[*jj++]] += PetscAbsScalar(*v); v++;
1978:       }
1979:       MPIU_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1980:       for (j=0; j<mat->cmap->N; j++) {
1981:         if (tmp2[j] > *norm) *norm = tmp2[j];
1982:       }
1983:       PetscFree(tmp);
1984:       PetscFree(tmp2);
1985:       PetscLogFlops(PetscMax(amat->nz+bmat->nz-1,0));
1986:     } else if (type == NORM_INFINITY) { /* max row norm */
1987:       PetscReal ntemp = 0.0;
1988:       for (j=0; j<aij->A->rmap->n; j++) {
1989:         v   = amat->a + amat->i[j];
1990:         sum = 0.0;
1991:         for (i=0; i<amat->i[j+1]-amat->i[j]; i++) {
1992:           sum += PetscAbsScalar(*v); v++;
1993:         }
1994:         v = bmat->a + bmat->i[j];
1995:         for (i=0; i<bmat->i[j+1]-bmat->i[j]; i++) {
1996:           sum += PetscAbsScalar(*v); v++;
1997:         }
1998:         if (sum > ntemp) ntemp = sum;
1999:       }
2000:       MPIU_Allreduce(&ntemp,norm,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)mat));
2001:       PetscLogFlops(PetscMax(amat->nz+bmat->nz-1,0));
2002:     } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No support for two norm");
2003:   }
2004:   return(0);
2005: }

2007: PetscErrorCode MatTranspose_MPIAIJ(Mat A,MatReuse reuse,Mat *matout)
2008: {
2009:   Mat_MPIAIJ     *a    =(Mat_MPIAIJ*)A->data,*b;
2010:   Mat_SeqAIJ     *Aloc =(Mat_SeqAIJ*)a->A->data,*Bloc=(Mat_SeqAIJ*)a->B->data,*sub_B_diag;
2011:   PetscInt       M     = A->rmap->N,N=A->cmap->N,ma,na,mb,nb,*ai,*aj,*bi,*bj,row,*cols,*cols_tmp,*B_diag_ilen,*B_diag_i,i,ncol,A_diag_ncol;
2013:   Mat            B,A_diag,*B_diag;
2014:   MatScalar      *array;

2017:   ma = A->rmap->n; na = A->cmap->n; mb = a->B->rmap->n; nb = a->B->cmap->n;
2018:   ai = Aloc->i; aj = Aloc->j;
2019:   bi = Bloc->i; bj = Bloc->j;
2020:   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
2021:     PetscInt             *d_nnz,*g_nnz,*o_nnz;
2022:     PetscSFNode          *oloc;
2023:     PETSC_UNUSED PetscSF sf;

2025:     PetscMalloc4(na,&d_nnz,na,&o_nnz,nb,&g_nnz,nb,&oloc);
2026:     /* compute d_nnz for preallocation */
2027:     PetscMemzero(d_nnz,na*sizeof(PetscInt));
2028:     for (i=0; i<ai[ma]; i++) {
2029:       d_nnz[aj[i]]++;
2030:     }
2031:     /* compute local off-diagonal contributions */
2032:     PetscMemzero(g_nnz,nb*sizeof(PetscInt));
2033:     for (i=0; i<bi[ma]; i++) g_nnz[bj[i]]++;
2034:     /* map those to global */
2035:     PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
2036:     PetscSFSetGraphLayout(sf,A->cmap,nb,NULL,PETSC_USE_POINTER,a->garray);
2037:     PetscSFSetFromOptions(sf);
2038:     PetscMemzero(o_nnz,na*sizeof(PetscInt));
2039:     PetscSFReduceBegin(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
2040:     PetscSFReduceEnd(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
2041:     PetscSFDestroy(&sf);

2043:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2044:     MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);
2045:     MatSetBlockSizes(B,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
2046:     MatSetType(B,((PetscObject)A)->type_name);
2047:     MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
2048:     PetscFree4(d_nnz,o_nnz,g_nnz,oloc);
2049:   } else {
2050:     B    = *matout;
2051:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
2052:   }

2054:   b           = (Mat_MPIAIJ*)B->data;
2055:   A_diag      = a->A;
2056:   B_diag      = &b->A;
2057:   sub_B_diag  = (Mat_SeqAIJ*)(*B_diag)->data;
2058:   A_diag_ncol = A_diag->cmap->N;
2059:   B_diag_ilen = sub_B_diag->ilen;
2060:   B_diag_i    = sub_B_diag->i;

2062:   /* Set ilen for diagonal of B */
2063:   for (i=0; i<A_diag_ncol; i++) {
2064:     B_diag_ilen[i] = B_diag_i[i+1] - B_diag_i[i];
2065:   }

2067:   /* Transpose the diagonal part of the matrix. In contrast to the offdiagonal part, this can be done
2068:   very quickly (=without using MatSetValues), because all writes are local. */
2069:   MatTranspose(A_diag,MAT_REUSE_MATRIX,B_diag);

2071:   /* copy over the B part */
2072:   PetscCalloc1(bi[mb],&cols);
2073:   array = Bloc->a;
2074:   row   = A->rmap->rstart;
2075:   for (i=0; i<bi[mb]; i++) cols[i] = a->garray[bj[i]];
2076:   cols_tmp = cols;
2077:   for (i=0; i<mb; i++) {
2078:     ncol = bi[i+1]-bi[i];
2079:     MatSetValues(B,ncol,cols_tmp,1,&row,array,INSERT_VALUES);
2080:     row++;
2081:     array += ncol; cols_tmp += ncol;
2082:   }
2083:   PetscFree(cols);

2085:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2086:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2087:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
2088:     *matout = B;
2089:   } else {
2090:     MatHeaderMerge(A,&B);
2091:   }
2092:   return(0);
2093: }

2095: PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat,Vec ll,Vec rr)
2096: {
2097:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
2098:   Mat            a    = aij->A,b = aij->B;
2100:   PetscInt       s1,s2,s3;

2103:   MatGetLocalSize(mat,&s2,&s3);
2104:   if (rr) {
2105:     VecGetLocalSize(rr,&s1);
2106:     if (s1!=s3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
2107:     /* Overlap communication with computation. */
2108:     VecScatterBegin(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
2109:   }
2110:   if (ll) {
2111:     VecGetLocalSize(ll,&s1);
2112:     if (s1!=s2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
2113:     (*b->ops->diagonalscale)(b,ll,0);
2114:   }
2115:   /* scale  the diagonal block */
2116:   (*a->ops->diagonalscale)(a,ll,rr);

2118:   if (rr) {
2119:     /* Do a scatter end and then right scale the off-diagonal block */
2120:     VecScatterEnd(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
2121:     (*b->ops->diagonalscale)(b,0,aij->lvec);
2122:   }
2123:   return(0);
2124: }

2126: PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2127: {
2128:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2132:   MatSetUnfactored(a->A);
2133:   return(0);
2134: }

2136: PetscErrorCode MatEqual_MPIAIJ(Mat A,Mat B,PetscBool  *flag)
2137: {
2138:   Mat_MPIAIJ     *matB = (Mat_MPIAIJ*)B->data,*matA = (Mat_MPIAIJ*)A->data;
2139:   Mat            a,b,c,d;
2140:   PetscBool      flg;

2144:   a = matA->A; b = matA->B;
2145:   c = matB->A; d = matB->B;

2147:   MatEqual(a,c,&flg);
2148:   if (flg) {
2149:     MatEqual(b,d,&flg);
2150:   }
2151:   MPIU_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2152:   return(0);
2153: }

2155: PetscErrorCode MatCopy_MPIAIJ(Mat A,Mat B,MatStructure str)
2156: {
2158:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2159:   Mat_MPIAIJ     *b = (Mat_MPIAIJ*)B->data;

2162:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2163:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2164:     /* because of the column compression in the off-processor part of the matrix a->B,
2165:        the number of columns in a->B and b->B may be different, hence we cannot call
2166:        the MatCopy() directly on the two parts. If need be, we can provide a more
2167:        efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2168:        then copying the submatrices */
2169:     MatCopy_Basic(A,B,str);
2170:   } else {
2171:     MatCopy(a->A,b->A,str);
2172:     MatCopy(a->B,b->B,str);
2173:   }
2174:   PetscObjectStateIncrease((PetscObject)B);
2175:   return(0);
2176: }

2178: PetscErrorCode MatSetUp_MPIAIJ(Mat A)
2179: {

2183:   MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
2184:   return(0);
2185: }

2187: /*
2188:    Computes the number of nonzeros per row needed for preallocation when X and Y
2189:    have different nonzero structure.
2190: */
2191: 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)
2192: {
2193:   PetscInt       i,j,k,nzx,nzy;

2196:   /* Set the number of nonzeros in the new matrix */
2197:   for (i=0; i<m; i++) {
2198:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
2199:     nzx = xi[i+1] - xi[i];
2200:     nzy = yi[i+1] - yi[i];
2201:     nnz[i] = 0;
2202:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
2203:       for (; k<nzy && yltog[yjj[k]]<xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2204:       if (k<nzy && yltog[yjj[k]]==xltog[xjj[j]]) k++;             /* Skip duplicate */
2205:       nnz[i]++;
2206:     }
2207:     for (; k<nzy; k++) nnz[i]++;
2208:   }
2209:   return(0);
2210: }

2212: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2213: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y,const PetscInt *yltog,Mat X,const PetscInt *xltog,PetscInt *nnz)
2214: {
2216:   PetscInt       m = Y->rmap->N;
2217:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
2218:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

2221:   MatAXPYGetPreallocation_MPIX_private(m,x->i,x->j,xltog,y->i,y->j,yltog,nnz);
2222:   return(0);
2223: }

2225: PetscErrorCode MatAXPY_MPIAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2226: {
2228:   Mat_MPIAIJ     *xx = (Mat_MPIAIJ*)X->data,*yy = (Mat_MPIAIJ*)Y->data;
2229:   PetscBLASInt   bnz,one=1;
2230:   Mat_SeqAIJ     *x,*y;

2233:   if (str == SAME_NONZERO_PATTERN) {
2234:     PetscScalar alpha = a;
2235:     x    = (Mat_SeqAIJ*)xx->A->data;
2236:     PetscBLASIntCast(x->nz,&bnz);
2237:     y    = (Mat_SeqAIJ*)yy->A->data;
2238:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2239:     x    = (Mat_SeqAIJ*)xx->B->data;
2240:     y    = (Mat_SeqAIJ*)yy->B->data;
2241:     PetscBLASIntCast(x->nz,&bnz);
2242:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2243:     PetscObjectStateIncrease((PetscObject)Y);
2244:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2245:     MatAXPY_Basic(Y,a,X,str);
2246:   } else {
2247:     Mat      B;
2248:     PetscInt *nnz_d,*nnz_o;
2249:     PetscMalloc1(yy->A->rmap->N,&nnz_d);
2250:     PetscMalloc1(yy->B->rmap->N,&nnz_o);
2251:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2252:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2253:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2254:     MatSetBlockSizesFromMats(B,Y,Y);
2255:     MatSetType(B,MATMPIAIJ);
2256:     MatAXPYGetPreallocation_SeqAIJ(yy->A,xx->A,nnz_d);
2257:     MatAXPYGetPreallocation_MPIAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);
2258:     MatMPIAIJSetPreallocation(B,0,nnz_d,0,nnz_o);
2259:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2260:     MatHeaderReplace(Y,&B);
2261:     PetscFree(nnz_d);
2262:     PetscFree(nnz_o);
2263:   }
2264:   return(0);
2265: }

2267: extern PetscErrorCode  MatConjugate_SeqAIJ(Mat);

2269: PetscErrorCode  MatConjugate_MPIAIJ(Mat mat)
2270: {
2271: #if defined(PETSC_USE_COMPLEX)
2273:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2276:   MatConjugate_SeqAIJ(aij->A);
2277:   MatConjugate_SeqAIJ(aij->B);
2278: #else
2280: #endif
2281:   return(0);
2282: }

2284: PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2285: {
2286:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2290:   MatRealPart(a->A);
2291:   MatRealPart(a->B);
2292:   return(0);
2293: }

2295: PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2296: {
2297:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2301:   MatImaginaryPart(a->A);
2302:   MatImaginaryPart(a->B);
2303:   return(0);
2304: }

2306: PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2307: {
2308:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2310:   PetscInt       i,*idxb = 0;
2311:   PetscScalar    *va,*vb;
2312:   Vec            vtmp;

2315:   MatGetRowMaxAbs(a->A,v,idx);
2316:   VecGetArray(v,&va);
2317:   if (idx) {
2318:     for (i=0; i<A->rmap->n; i++) {
2319:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2320:     }
2321:   }

2323:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2324:   if (idx) {
2325:     PetscMalloc1(A->rmap->n,&idxb);
2326:   }
2327:   MatGetRowMaxAbs(a->B,vtmp,idxb);
2328:   VecGetArray(vtmp,&vb);

2330:   for (i=0; i<A->rmap->n; i++) {
2331:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2332:       va[i] = vb[i];
2333:       if (idx) idx[i] = a->garray[idxb[i]];
2334:     }
2335:   }

2337:   VecRestoreArray(v,&va);
2338:   VecRestoreArray(vtmp,&vb);
2339:   PetscFree(idxb);
2340:   VecDestroy(&vtmp);
2341:   return(0);
2342: }

2344: PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2345: {
2346:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2348:   PetscInt       i,*idxb = 0;
2349:   PetscScalar    *va,*vb;
2350:   Vec            vtmp;

2353:   MatGetRowMinAbs(a->A,v,idx);
2354:   VecGetArray(v,&va);
2355:   if (idx) {
2356:     for (i=0; i<A->cmap->n; i++) {
2357:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2358:     }
2359:   }

2361:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2362:   if (idx) {
2363:     PetscMalloc1(A->rmap->n,&idxb);
2364:   }
2365:   MatGetRowMinAbs(a->B,vtmp,idxb);
2366:   VecGetArray(vtmp,&vb);

2368:   for (i=0; i<A->rmap->n; i++) {
2369:     if (PetscAbsScalar(va[i]) > PetscAbsScalar(vb[i])) {
2370:       va[i] = vb[i];
2371:       if (idx) idx[i] = a->garray[idxb[i]];
2372:     }
2373:   }

2375:   VecRestoreArray(v,&va);
2376:   VecRestoreArray(vtmp,&vb);
2377:   PetscFree(idxb);
2378:   VecDestroy(&vtmp);
2379:   return(0);
2380: }

2382: PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2383: {
2384:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2385:   PetscInt       n      = A->rmap->n;
2386:   PetscInt       cstart = A->cmap->rstart;
2387:   PetscInt       *cmap  = mat->garray;
2388:   PetscInt       *diagIdx, *offdiagIdx;
2389:   Vec            diagV, offdiagV;
2390:   PetscScalar    *a, *diagA, *offdiagA;
2391:   PetscInt       r;

2395:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2396:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &diagV);
2397:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &offdiagV);
2398:   MatGetRowMin(mat->A, diagV,    diagIdx);
2399:   MatGetRowMin(mat->B, offdiagV, offdiagIdx);
2400:   VecGetArray(v,        &a);
2401:   VecGetArray(diagV,    &diagA);
2402:   VecGetArray(offdiagV, &offdiagA);
2403:   for (r = 0; r < n; ++r) {
2404:     if (PetscAbsScalar(diagA[r]) <= PetscAbsScalar(offdiagA[r])) {
2405:       a[r]   = diagA[r];
2406:       idx[r] = cstart + diagIdx[r];
2407:     } else {
2408:       a[r]   = offdiagA[r];
2409:       idx[r] = cmap[offdiagIdx[r]];
2410:     }
2411:   }
2412:   VecRestoreArray(v,        &a);
2413:   VecRestoreArray(diagV,    &diagA);
2414:   VecRestoreArray(offdiagV, &offdiagA);
2415:   VecDestroy(&diagV);
2416:   VecDestroy(&offdiagV);
2417:   PetscFree2(diagIdx, offdiagIdx);
2418:   return(0);
2419: }

2421: PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2422: {
2423:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2424:   PetscInt       n      = A->rmap->n;
2425:   PetscInt       cstart = A->cmap->rstart;
2426:   PetscInt       *cmap  = mat->garray;
2427:   PetscInt       *diagIdx, *offdiagIdx;
2428:   Vec            diagV, offdiagV;
2429:   PetscScalar    *a, *diagA, *offdiagA;
2430:   PetscInt       r;

2434:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2435:   VecCreateSeq(PETSC_COMM_SELF, n, &diagV);
2436:   VecCreateSeq(PETSC_COMM_SELF, n, &offdiagV);
2437:   MatGetRowMax(mat->A, diagV,    diagIdx);
2438:   MatGetRowMax(mat->B, offdiagV, offdiagIdx);
2439:   VecGetArray(v,        &a);
2440:   VecGetArray(diagV,    &diagA);
2441:   VecGetArray(offdiagV, &offdiagA);
2442:   for (r = 0; r < n; ++r) {
2443:     if (PetscAbsScalar(diagA[r]) >= PetscAbsScalar(offdiagA[r])) {
2444:       a[r]   = diagA[r];
2445:       idx[r] = cstart + diagIdx[r];
2446:     } else {
2447:       a[r]   = offdiagA[r];
2448:       idx[r] = cmap[offdiagIdx[r]];
2449:     }
2450:   }
2451:   VecRestoreArray(v,        &a);
2452:   VecRestoreArray(diagV,    &diagA);
2453:   VecRestoreArray(offdiagV, &offdiagA);
2454:   VecDestroy(&diagV);
2455:   VecDestroy(&offdiagV);
2456:   PetscFree2(diagIdx, offdiagIdx);
2457:   return(0);
2458: }

2460: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat,Mat *newmat)
2461: {
2463:   Mat            *dummy;

2466:   MatCreateSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,&dummy);
2467:   *newmat = *dummy;
2468:   PetscFree(dummy);
2469:   return(0);
2470: }

2472: PetscErrorCode  MatInvertBlockDiagonal_MPIAIJ(Mat A,const PetscScalar **values)
2473: {
2474:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*) A->data;

2478:   MatInvertBlockDiagonal(a->A,values);
2479:   A->factorerrortype = a->A->factorerrortype;
2480:   return(0);
2481: }

2483: static PetscErrorCode  MatSetRandom_MPIAIJ(Mat x,PetscRandom rctx)
2484: {
2486:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)x->data;

2489:   if (!x->assembled && !x->preallocated) SETERRQ(PetscObjectComm((PetscObject)x), PETSC_ERR_ARG_WRONGSTATE, "MatSetRandom on an unassembled and unpreallocated MATMPIAIJ is not allowed");
2490:   MatSetRandom(aij->A,rctx);
2491:   if (x->assembled) {
2492:     MatSetRandom(aij->B,rctx);
2493:   } else {
2494:     MatSetRandomSkipColumnRange_SeqAIJ_Private(aij->B,x->cmap->rstart,x->cmap->rend,rctx);
2495:   }
2496:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
2497:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
2498:   return(0);
2499: }

2501: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A,PetscBool sc)
2502: {
2504:   if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2505:   else A->ops->increaseoverlap    = MatIncreaseOverlap_MPIAIJ;
2506:   return(0);
2507: }

2509: /*@
2510:    MatMPIAIJSetUseScalableIncreaseOverlap - Determine if the matrix uses a scalable algorithm to compute the overlap

2512:    Collective on Mat

2514:    Input Parameters:
2515: +    A - the matrix
2516: -    sc - PETSC_TRUE indicates use the scalable algorithm (default is not to use the scalable algorithm)

2518:  Level: advanced

2520: @*/
2521: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A,PetscBool sc)
2522: {
2523:   PetscErrorCode       ierr;

2526:   PetscTryMethod(A,"MatMPIAIJSetUseScalableIncreaseOverlap_C",(Mat,PetscBool),(A,sc));
2527:   return(0);
2528: }

2530: PetscErrorCode MatSetFromOptions_MPIAIJ(PetscOptionItems *PetscOptionsObject,Mat A)
2531: {
2532:   PetscErrorCode       ierr;
2533:   PetscBool            sc = PETSC_FALSE,flg;

2536:   PetscOptionsHead(PetscOptionsObject,"MPIAIJ options");
2537:   if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2538:   PetscOptionsBool("-mat_increase_overlap_scalable","Use a scalable algorithm to compute the overlap","MatIncreaseOverlap",sc,&sc,&flg);
2539:   if (flg) {
2540:     MatMPIAIJSetUseScalableIncreaseOverlap(A,sc);
2541:   }
2542:   PetscOptionsTail();
2543:   return(0);
2544: }

2546: PetscErrorCode MatShift_MPIAIJ(Mat Y,PetscScalar a)
2547: {
2549:   Mat_MPIAIJ     *maij = (Mat_MPIAIJ*)Y->data;
2550:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)maij->A->data;

2553:   if (!Y->preallocated) {
2554:     MatMPIAIJSetPreallocation(Y,1,NULL,0,NULL);
2555:   } else if (!aij->nz) {
2556:     PetscInt nonew = aij->nonew;
2557:     MatSeqAIJSetPreallocation(maij->A,1,NULL);
2558:     aij->nonew = nonew;
2559:   }
2560:   MatShift_Basic(Y,a);
2561:   return(0);
2562: }

2564: PetscErrorCode MatMissingDiagonal_MPIAIJ(Mat A,PetscBool  *missing,PetscInt *d)
2565: {
2566:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2570:   if (A->rmap->n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only works for square matrices");
2571:   MatMissingDiagonal(a->A,missing,d);
2572:   if (d) {
2573:     PetscInt rstart;
2574:     MatGetOwnershipRange(A,&rstart,NULL);
2575:     *d += rstart;

2577:   }
2578:   return(0);
2579: }

2581: PetscErrorCode MatInvertVariableBlockDiagonal_MPIAIJ(Mat A,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *diag)
2582: {
2583:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2587:   MatInvertVariableBlockDiagonal(a->A,nblocks,bsizes,diag);
2588:   return(0);
2589: }

2591: /* -------------------------------------------------------------------*/
2592: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2593:                                        MatGetRow_MPIAIJ,
2594:                                        MatRestoreRow_MPIAIJ,
2595:                                        MatMult_MPIAIJ,
2596:                                 /* 4*/ MatMultAdd_MPIAIJ,
2597:                                        MatMultTranspose_MPIAIJ,
2598:                                        MatMultTransposeAdd_MPIAIJ,
2599:                                        0,
2600:                                        0,
2601:                                        0,
2602:                                 /*10*/ 0,
2603:                                        0,
2604:                                        0,
2605:                                        MatSOR_MPIAIJ,
2606:                                        MatTranspose_MPIAIJ,
2607:                                 /*15*/ MatGetInfo_MPIAIJ,
2608:                                        MatEqual_MPIAIJ,
2609:                                        MatGetDiagonal_MPIAIJ,
2610:                                        MatDiagonalScale_MPIAIJ,
2611:                                        MatNorm_MPIAIJ,
2612:                                 /*20*/ MatAssemblyBegin_MPIAIJ,
2613:                                        MatAssemblyEnd_MPIAIJ,
2614:                                        MatSetOption_MPIAIJ,
2615:                                        MatZeroEntries_MPIAIJ,
2616:                                 /*24*/ MatZeroRows_MPIAIJ,
2617:                                        0,
2618:                                        0,
2619:                                        0,
2620:                                        0,
2621:                                 /*29*/ MatSetUp_MPIAIJ,
2622:                                        0,
2623:                                        0,
2624:                                        MatGetDiagonalBlock_MPIAIJ,
2625:                                        0,
2626:                                 /*34*/ MatDuplicate_MPIAIJ,
2627:                                        0,
2628:                                        0,
2629:                                        0,
2630:                                        0,
2631:                                 /*39*/ MatAXPY_MPIAIJ,
2632:                                        MatCreateSubMatrices_MPIAIJ,
2633:                                        MatIncreaseOverlap_MPIAIJ,
2634:                                        MatGetValues_MPIAIJ,
2635:                                        MatCopy_MPIAIJ,
2636:                                 /*44*/ MatGetRowMax_MPIAIJ,
2637:                                        MatScale_MPIAIJ,
2638:                                        MatShift_MPIAIJ,
2639:                                        MatDiagonalSet_MPIAIJ,
2640:                                        MatZeroRowsColumns_MPIAIJ,
2641:                                 /*49*/ MatSetRandom_MPIAIJ,
2642:                                        0,
2643:                                        0,
2644:                                        0,
2645:                                        0,
2646:                                 /*54*/ MatFDColoringCreate_MPIXAIJ,
2647:                                        0,
2648:                                        MatSetUnfactored_MPIAIJ,
2649:                                        MatPermute_MPIAIJ,
2650:                                        0,
2651:                                 /*59*/ MatCreateSubMatrix_MPIAIJ,
2652:                                        MatDestroy_MPIAIJ,
2653:                                        MatView_MPIAIJ,
2654:                                        0,
2655:                                        MatMatMatMult_MPIAIJ_MPIAIJ_MPIAIJ,
2656:                                 /*64*/ MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ,
2657:                                        MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
2658:                                        0,
2659:                                        0,
2660:                                        0,
2661:                                 /*69*/ MatGetRowMaxAbs_MPIAIJ,
2662:                                        MatGetRowMinAbs_MPIAIJ,
2663:                                        0,
2664:                                        0,
2665:                                        0,
2666:                                        0,
2667:                                 /*75*/ MatFDColoringApply_AIJ,
2668:                                        MatSetFromOptions_MPIAIJ,
2669:                                        0,
2670:                                        0,
2671:                                        MatFindZeroDiagonals_MPIAIJ,
2672:                                 /*80*/ 0,
2673:                                        0,
2674:                                        0,
2675:                                 /*83*/ MatLoad_MPIAIJ,
2676:                                        MatIsSymmetric_MPIAIJ,
2677:                                        0,
2678:                                        0,
2679:                                        0,
2680:                                        0,
2681:                                 /*89*/ MatMatMult_MPIAIJ_MPIAIJ,
2682:                                        MatMatMultSymbolic_MPIAIJ_MPIAIJ,
2683:                                        MatMatMultNumeric_MPIAIJ_MPIAIJ,
2684:                                        MatPtAP_MPIAIJ_MPIAIJ,
2685:                                        MatPtAPSymbolic_MPIAIJ_MPIAIJ,
2686:                                 /*94*/ MatPtAPNumeric_MPIAIJ_MPIAIJ,
2687:                                        0,
2688:                                        0,
2689:                                        0,
2690:                                        0,
2691:                                 /*99*/ 0,
2692:                                        0,
2693:                                        0,
2694:                                        MatConjugate_MPIAIJ,
2695:                                        0,
2696:                                 /*104*/MatSetValuesRow_MPIAIJ,
2697:                                        MatRealPart_MPIAIJ,
2698:                                        MatImaginaryPart_MPIAIJ,
2699:                                        0,
2700:                                        0,
2701:                                 /*109*/0,
2702:                                        0,
2703:                                        MatGetRowMin_MPIAIJ,
2704:                                        0,
2705:                                        MatMissingDiagonal_MPIAIJ,
2706:                                 /*114*/MatGetSeqNonzeroStructure_MPIAIJ,
2707:                                        0,
2708:                                        MatGetGhosts_MPIAIJ,
2709:                                        0,
2710:                                        0,
2711:                                 /*119*/0,
2712:                                        0,
2713:                                        0,
2714:                                        0,
2715:                                        MatGetMultiProcBlock_MPIAIJ,
2716:                                 /*124*/MatFindNonzeroRows_MPIAIJ,
2717:                                        MatGetColumnNorms_MPIAIJ,
2718:                                        MatInvertBlockDiagonal_MPIAIJ,
2719:                                        MatInvertVariableBlockDiagonal_MPIAIJ,
2720:                                        MatCreateSubMatricesMPI_MPIAIJ,
2721:                                 /*129*/0,
2722:                                        MatTransposeMatMult_MPIAIJ_MPIAIJ,
2723:                                        MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ,
2724:                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2725:                                        0,
2726:                                 /*134*/0,
2727:                                        0,
2728:                                        MatRARt_MPIAIJ_MPIAIJ,
2729:                                        0,
2730:                                        0,
2731:                                 /*139*/MatSetBlockSizes_MPIAIJ,
2732:                                        0,
2733:                                        0,
2734:                                        MatFDColoringSetUp_MPIXAIJ,
2735:                                        MatFindOffBlockDiagonalEntries_MPIAIJ,
2736:                                 /*144*/MatCreateMPIMatConcatenateSeqMat_MPIAIJ
2737: };

2739: /* ----------------------------------------------------------------------------------------*/

2741: PetscErrorCode  MatStoreValues_MPIAIJ(Mat mat)
2742: {
2743:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2747:   MatStoreValues(aij->A);
2748:   MatStoreValues(aij->B);
2749:   return(0);
2750: }

2752: PetscErrorCode  MatRetrieveValues_MPIAIJ(Mat mat)
2753: {
2754:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2758:   MatRetrieveValues(aij->A);
2759:   MatRetrieveValues(aij->B);
2760:   return(0);
2761: }

2763: PetscErrorCode  MatMPIAIJSetPreallocation_MPIAIJ(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
2764: {
2765:   Mat_MPIAIJ     *b;
2767:   PetscMPIInt    size;

2770:   PetscLayoutSetUp(B->rmap);
2771:   PetscLayoutSetUp(B->cmap);
2772:   b = (Mat_MPIAIJ*)B->data;

2774: #if defined(PETSC_USE_CTABLE)
2775:   PetscTableDestroy(&b->colmap);
2776: #else
2777:   PetscFree(b->colmap);
2778: #endif
2779:   PetscFree(b->garray);
2780:   VecDestroy(&b->lvec);
2781:   VecScatterDestroy(&b->Mvctx);

2783:   /* Because the B will have been resized we simply destroy it and create a new one each time */
2784:   MPI_Comm_size(PetscObjectComm((PetscObject)B),&size);
2785:   MatDestroy(&b->B);
2786:   MatCreate(PETSC_COMM_SELF,&b->B);
2787:   MatSetSizes(b->B,B->rmap->n,size > 1 ? B->cmap->N : 0,B->rmap->n,size > 1 ? B->cmap->N : 0);
2788:   MatSetBlockSizesFromMats(b->B,B,B);
2789:   MatSetType(b->B,MATSEQAIJ);
2790:   PetscLogObjectParent((PetscObject)B,(PetscObject)b->B);

2792:   if (!B->preallocated) {
2793:     MatCreate(PETSC_COMM_SELF,&b->A);
2794:     MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
2795:     MatSetBlockSizesFromMats(b->A,B,B);
2796:     MatSetType(b->A,MATSEQAIJ);
2797:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->A);
2798:   }

2800:   MatSeqAIJSetPreallocation(b->A,d_nz,d_nnz);
2801:   MatSeqAIJSetPreallocation(b->B,o_nz,o_nnz);
2802:   B->preallocated  = PETSC_TRUE;
2803:   B->was_assembled = PETSC_FALSE;
2804:   B->assembled     = PETSC_FALSE;
2805:   return(0);
2806: }

2808: PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2809: {
2810:   Mat_MPIAIJ     *b;

2815:   PetscLayoutSetUp(B->rmap);
2816:   PetscLayoutSetUp(B->cmap);
2817:   b = (Mat_MPIAIJ*)B->data;

2819: #if defined(PETSC_USE_CTABLE)
2820:   PetscTableDestroy(&b->colmap);
2821: #else
2822:   PetscFree(b->colmap);
2823: #endif
2824:   PetscFree(b->garray);
2825:   VecDestroy(&b->lvec);
2826:   VecScatterDestroy(&b->Mvctx);

2828:   MatResetPreallocation(b->A);
2829:   MatResetPreallocation(b->B);
2830:   B->preallocated  = PETSC_TRUE;
2831:   B->was_assembled = PETSC_FALSE;
2832:   B->assembled = PETSC_FALSE;
2833:   return(0);
2834: }

2836: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
2837: {
2838:   Mat            mat;
2839:   Mat_MPIAIJ     *a,*oldmat = (Mat_MPIAIJ*)matin->data;

2843:   *newmat = 0;
2844:   MatCreate(PetscObjectComm((PetscObject)matin),&mat);
2845:   MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
2846:   MatSetBlockSizesFromMats(mat,matin,matin);
2847:   MatSetType(mat,((PetscObject)matin)->type_name);
2848:   a       = (Mat_MPIAIJ*)mat->data;

2850:   mat->factortype   = matin->factortype;
2851:   mat->assembled    = PETSC_TRUE;
2852:   mat->insertmode   = NOT_SET_VALUES;
2853:   mat->preallocated = PETSC_TRUE;

2855:   a->size         = oldmat->size;
2856:   a->rank         = oldmat->rank;
2857:   a->donotstash   = oldmat->donotstash;
2858:   a->roworiented  = oldmat->roworiented;
2859:   a->rowindices   = 0;
2860:   a->rowvalues    = 0;
2861:   a->getrowactive = PETSC_FALSE;

2863:   PetscLayoutReference(matin->rmap,&mat->rmap);
2864:   PetscLayoutReference(matin->cmap,&mat->cmap);

2866:   if (oldmat->colmap) {
2867: #if defined(PETSC_USE_CTABLE)
2868:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
2869: #else
2870:     PetscMalloc1(mat->cmap->N,&a->colmap);
2871:     PetscLogObjectMemory((PetscObject)mat,(mat->cmap->N)*sizeof(PetscInt));
2872:     PetscMemcpy(a->colmap,oldmat->colmap,(mat->cmap->N)*sizeof(PetscInt));
2873: #endif
2874:   } else a->colmap = 0;
2875:   if (oldmat->garray) {
2876:     PetscInt len;
2877:     len  = oldmat->B->cmap->n;
2878:     PetscMalloc1(len+1,&a->garray);
2879:     PetscLogObjectMemory((PetscObject)mat,len*sizeof(PetscInt));
2880:     if (len) { PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt)); }
2881:   } else a->garray = 0;

2883:   VecDuplicate(oldmat->lvec,&a->lvec);
2884:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
2885:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
2886:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);

2888:   if (oldmat->Mvctx_mpi1) {
2889:     VecScatterCopy(oldmat->Mvctx_mpi1,&a->Mvctx_mpi1);
2890:     PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx_mpi1);
2891:   }

2893:   MatDuplicate(oldmat->A,cpvalues,&a->A);
2894:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->A);
2895:   MatDuplicate(oldmat->B,cpvalues,&a->B);
2896:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->B);
2897:   PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
2898:   *newmat = mat;
2899:   return(0);
2900: }

2902: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
2903: {
2904:   PetscBool      isbinary, ishdf5;

2910:   /* force binary viewer to load .info file if it has not yet done so */
2911:   PetscViewerSetUp(viewer);
2912:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
2913:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,  &ishdf5);
2914:   if (isbinary) {
2915:     MatLoad_MPIAIJ_Binary(newMat,viewer);
2916:   } else if (ishdf5) {
2917: #if defined(PETSC_HAVE_HDF5)
2918:     MatLoad_AIJ_HDF5(newMat,viewer);
2919: #else
2920:     SETERRQ(PetscObjectComm((PetscObject)newMat),PETSC_ERR_SUP,"HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2921: #endif
2922:   } else {
2923:     SETERRQ2(PetscObjectComm((PetscObject)newMat),PETSC_ERR_SUP,"Viewer type %s not yet supported for reading %s matrices",((PetscObject)viewer)->type_name,((PetscObject)newMat)->type_name);
2924:   }
2925:   return(0);
2926: }

2928: PetscErrorCode MatLoad_MPIAIJ_Binary(Mat newMat, PetscViewer viewer)
2929: {
2930:   PetscScalar    *vals,*svals;
2931:   MPI_Comm       comm;
2933:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
2934:   PetscInt       i,nz,j,rstart,rend,mmax,maxnz = 0;
2935:   PetscInt       header[4],*rowlengths = 0,M,N,m,*cols;
2936:   PetscInt       *ourlens = NULL,*procsnz = NULL,*offlens = NULL,jj,*mycols,*smycols;
2937:   PetscInt       cend,cstart,n,*rowners;
2938:   int            fd;
2939:   PetscInt       bs = newMat->rmap->bs;

2942:   PetscObjectGetComm((PetscObject)viewer,&comm);
2943:   MPI_Comm_size(comm,&size);
2944:   MPI_Comm_rank(comm,&rank);
2945:   PetscViewerBinaryGetDescriptor(viewer,&fd);
2946:   if (!rank) {
2947:     PetscBinaryRead(fd,(char*)header,4,NULL,PETSC_INT);
2948:     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
2949:     if (header[3] < 0) SETERRQ(PetscObjectComm((PetscObject)newMat),PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format on disk,cannot load as MATMPIAIJ");
2950:   }

2952:   PetscOptionsBegin(comm,NULL,"Options for loading MATMPIAIJ matrix","Mat");
2953:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
2954:   PetscOptionsEnd();
2955:   if (bs < 0) bs = 1;

2957:   MPI_Bcast(header+1,3,MPIU_INT,0,comm);
2958:   M    = header[1]; N = header[2];

2960:   /* If global sizes are set, check if they are consistent with that given in the file */
2961:   if (newMat->rmap->N >= 0 && newMat->rmap->N != M) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Inconsistent # of rows:Matrix in file has (%D) and input matrix has (%D)",newMat->rmap->N,M);
2962:   if (newMat->cmap->N >=0 && newMat->cmap->N != N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Inconsistent # of cols:Matrix in file has (%D) and input matrix has (%D)",newMat->cmap->N,N);

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

2969:   PetscMalloc1(size+1,&rowners);
2970:   MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

2972:   /* First process needs enough room for process with most rows */
2973:   if (!rank) {
2974:     mmax = rowners[1];
2975:     for (i=2; i<=size; i++) {
2976:       mmax = PetscMax(mmax, rowners[i]);
2977:     }
2978:   } else mmax = -1;             /* unused, but compilers complain */

2980:   rowners[0] = 0;
2981:   for (i=2; i<=size; i++) {
2982:     rowners[i] += rowners[i-1];
2983:   }
2984:   rstart = rowners[rank];
2985:   rend   = rowners[rank+1];

2987:   /* distribute row lengths to all processors */
2988:   PetscMalloc2(m,&ourlens,m,&offlens);
2989:   if (!rank) {
2990:     PetscBinaryRead(fd,ourlens,m,NULL,PETSC_INT);
2991:     PetscMalloc1(mmax,&rowlengths);
2992:     PetscCalloc1(size,&procsnz);
2993:     for (j=0; j<m; j++) {
2994:       procsnz[0] += ourlens[j];
2995:     }
2996:     for (i=1; i<size; i++) {
2997:       PetscBinaryRead(fd,rowlengths,rowners[i+1]-rowners[i],NULL,PETSC_INT);
2998:       /* calculate the number of nonzeros on each processor */
2999:       for (j=0; j<rowners[i+1]-rowners[i]; j++) {
3000:         procsnz[i] += rowlengths[j];
3001:       }
3002:       MPIULong_Send(rowlengths,rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
3003:     }
3004:     PetscFree(rowlengths);
3005:   } else {
3006:     MPIULong_Recv(ourlens,m,MPIU_INT,0,tag,comm);
3007:   }

3009:   if (!rank) {
3010:     /* determine max buffer needed and allocate it */
3011:     maxnz = 0;
3012:     for (i=0; i<size; i++) {
3013:       maxnz = PetscMax(maxnz,procsnz[i]);
3014:     }
3015:     PetscMalloc1(maxnz,&cols);

3017:     /* read in my part of the matrix column indices  */
3018:     nz   = procsnz[0];
3019:     PetscMalloc1(nz,&mycols);
3020:     PetscBinaryRead(fd,mycols,nz,NULL,PETSC_INT);

3022:     /* read in every one elses and ship off */
3023:     for (i=1; i<size; i++) {
3024:       nz   = procsnz[i];
3025:       PetscBinaryRead(fd,cols,nz,NULL,PETSC_INT);
3026:       MPIULong_Send(cols,nz,MPIU_INT,i,tag,comm);
3027:     }
3028:     PetscFree(cols);
3029:   } else {
3030:     /* determine buffer space needed for message */
3031:     nz = 0;
3032:     for (i=0; i<m; i++) {
3033:       nz += ourlens[i];
3034:     }
3035:     PetscMalloc1(nz,&mycols);

3037:     /* receive message of column indices*/
3038:     MPIULong_Recv(mycols,nz,MPIU_INT,0,tag,comm);
3039:   }

3041:   /* determine column ownership if matrix is not square */
3042:   if (N != M) {
3043:     if (newMat->cmap->n < 0) n = N/size + ((N % size) > rank);
3044:     else n = newMat->cmap->n;
3045:     MPI_Scan(&n,&cend,1,MPIU_INT,MPI_SUM,comm);
3046:     cstart = cend - n;
3047:   } else {
3048:     cstart = rstart;
3049:     cend   = rend;
3050:     n      = cend - cstart;
3051:   }

3053:   /* loop over local rows, determining number of off diagonal entries */
3054:   PetscMemzero(offlens,m*sizeof(PetscInt));
3055:   jj   = 0;
3056:   for (i=0; i<m; i++) {
3057:     for (j=0; j<ourlens[i]; j++) {
3058:       if (mycols[jj] < cstart || mycols[jj] >= cend) offlens[i]++;
3059:       jj++;
3060:     }
3061:   }

3063:   for (i=0; i<m; i++) {
3064:     ourlens[i] -= offlens[i];
3065:   }
3066:   MatSetSizes(newMat,m,n,M,N);

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

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

3072:   for (i=0; i<m; i++) {
3073:     ourlens[i] += offlens[i];
3074:   }

3076:   if (!rank) {
3077:     PetscMalloc1(maxnz+1,&vals);

3079:     /* read in my part of the matrix numerical values  */
3080:     nz   = procsnz[0];
3081:     PetscBinaryRead(fd,vals,nz,NULL,PETSC_SCALAR);

3083:     /* insert into matrix */
3084:     jj      = rstart;
3085:     smycols = mycols;
3086:     svals   = vals;
3087:     for (i=0; i<m; i++) {
3088:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
3089:       smycols += ourlens[i];
3090:       svals   += ourlens[i];
3091:       jj++;
3092:     }

3094:     /* read in other processors and ship out */
3095:     for (i=1; i<size; i++) {
3096:       nz   = procsnz[i];
3097:       PetscBinaryRead(fd,vals,nz,NULL,PETSC_SCALAR);
3098:       MPIULong_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newMat)->tag,comm);
3099:     }
3100:     PetscFree(procsnz);
3101:   } else {
3102:     /* receive numeric values */
3103:     PetscMalloc1(nz+1,&vals);

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

3108:     /* insert into matrix */
3109:     jj      = rstart;
3110:     smycols = mycols;
3111:     svals   = vals;
3112:     for (i=0; i<m; i++) {
3113:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
3114:       smycols += ourlens[i];
3115:       svals   += ourlens[i];
3116:       jj++;
3117:     }
3118:   }
3119:   PetscFree2(ourlens,offlens);
3120:   PetscFree(vals);
3121:   PetscFree(mycols);
3122:   PetscFree(rowners);
3123:   MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);
3124:   MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);
3125:   return(0);
3126: }

3128: /* Not scalable because of ISAllGather() unless getting all columns. */
3129: PetscErrorCode ISGetSeqIS_Private(Mat mat,IS iscol,IS *isseq)
3130: {
3132:   IS             iscol_local;
3133:   PetscBool      isstride;
3134:   PetscMPIInt    lisstride=0,gisstride;

3137:   /* check if we are grabbing all columns*/
3138:   PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&isstride);

3140:   if (isstride) {
3141:     PetscInt  start,len,mstart,mlen;
3142:     ISStrideGetInfo(iscol,&start,NULL);
3143:     ISGetLocalSize(iscol,&len);
3144:     MatGetOwnershipRangeColumn(mat,&mstart,&mlen);
3145:     if (mstart == start && mlen-mstart == len) lisstride = 1;
3146:   }

3148:   MPIU_Allreduce(&lisstride,&gisstride,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
3149:   if (gisstride) {
3150:     PetscInt N;
3151:     MatGetSize(mat,NULL,&N);
3152:     ISCreateStride(PetscObjectComm((PetscObject)mat),N,0,1,&iscol_local);
3153:     ISSetIdentity(iscol_local);
3154:     PetscInfo(mat,"Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n");
3155:   } else {
3156:     PetscInt cbs;
3157:     ISGetBlockSize(iscol,&cbs);
3158:     ISAllGather(iscol,&iscol_local);
3159:     ISSetBlockSize(iscol_local,cbs);
3160:   }

3162:   *isseq = iscol_local;
3163:   return(0);
3164: }

3166: /*
3167:  Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3168:  (see MatCreateSubMatrix_MPIAIJ_nonscalable)

3170:  Input Parameters:
3171:    mat - matrix
3172:    isrow - parallel row index set; its local indices are a subset of local columns of mat,
3173:            i.e., mat->rstart <= isrow[i] < mat->rend
3174:    iscol - parallel column index set; its local indices are a subset of local columns of mat,
3175:            i.e., mat->cstart <= iscol[i] < mat->cend
3176:  Output Parameter:
3177:    isrow_d,iscol_d - sequential row and column index sets for retrieving mat->A
3178:    iscol_o - sequential column index set for retrieving mat->B
3179:    garray - column map; garray[i] indicates global location of iscol_o[i] in iscol
3180:  */
3181: PetscErrorCode ISGetSeqIS_SameColDist_Private(Mat mat,IS isrow,IS iscol,IS *isrow_d,IS *iscol_d,IS *iscol_o,const PetscInt *garray[])
3182: {
3184:   Vec            x,cmap;
3185:   const PetscInt *is_idx;
3186:   PetscScalar    *xarray,*cmaparray;
3187:   PetscInt       ncols,isstart,*idx,m,rstart,*cmap1,count;
3188:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)mat->data;
3189:   Mat            B=a->B;
3190:   Vec            lvec=a->lvec,lcmap;
3191:   PetscInt       i,cstart,cend,Bn=B->cmap->N;
3192:   MPI_Comm       comm;
3193:   VecScatter     Mvctx=a->Mvctx;

3196:   PetscObjectGetComm((PetscObject)mat,&comm);
3197:   ISGetLocalSize(iscol,&ncols);

3199:   /* (1) iscol is a sub-column vector of mat, pad it with '-1.' to form a full vector x */
3200:   MatCreateVecs(mat,&x,NULL);
3201:   VecSet(x,-1.0);
3202:   VecDuplicate(x,&cmap);
3203:   VecSet(cmap,-1.0);

3205:   /* Get start indices */
3206:   MPI_Scan(&ncols,&isstart,1,MPIU_INT,MPI_SUM,comm);
3207:   isstart -= ncols;
3208:   MatGetOwnershipRangeColumn(mat,&cstart,&cend);

3210:   ISGetIndices(iscol,&is_idx);
3211:   VecGetArray(x,&xarray);
3212:   VecGetArray(cmap,&cmaparray);
3213:   PetscMalloc1(ncols,&idx);
3214:   for (i=0; i<ncols; i++) {
3215:     xarray[is_idx[i]-cstart]    = (PetscScalar)is_idx[i];
3216:     cmaparray[is_idx[i]-cstart] = i + isstart;      /* global index of iscol[i] */
3217:     idx[i]                      = is_idx[i]-cstart; /* local index of iscol[i]  */
3218:   }
3219:   VecRestoreArray(x,&xarray);
3220:   VecRestoreArray(cmap,&cmaparray);
3221:   ISRestoreIndices(iscol,&is_idx);

3223:   /* Get iscol_d */
3224:   ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,iscol_d);
3225:   ISGetBlockSize(iscol,&i);
3226:   ISSetBlockSize(*iscol_d,i);

3228:   /* Get isrow_d */
3229:   ISGetLocalSize(isrow,&m);
3230:   rstart = mat->rmap->rstart;
3231:   PetscMalloc1(m,&idx);
3232:   ISGetIndices(isrow,&is_idx);
3233:   for (i=0; i<m; i++) idx[i] = is_idx[i]-rstart;
3234:   ISRestoreIndices(isrow,&is_idx);

3236:   ISCreateGeneral(PETSC_COMM_SELF,m,idx,PETSC_OWN_POINTER,isrow_d);
3237:   ISGetBlockSize(isrow,&i);
3238:   ISSetBlockSize(*isrow_d,i);

3240:   /* (2) Scatter x and cmap using aij->Mvctx to get their off-process portions (see MatMult_MPIAIJ) */
3241:   VecScatterBegin(Mvctx,x,lvec,INSERT_VALUES,SCATTER_FORWARD);
3242:   VecScatterEnd(Mvctx,x,lvec,INSERT_VALUES,SCATTER_FORWARD);

3244:   VecDuplicate(lvec,&lcmap);

3246:   VecScatterBegin(Mvctx,cmap,lcmap,INSERT_VALUES,SCATTER_FORWARD);
3247:   VecScatterEnd(Mvctx,cmap,lcmap,INSERT_VALUES,SCATTER_FORWARD);

3249:   /* (3) create sequential iscol_o (a subset of iscol) and isgarray */
3250:   /* off-process column indices */
3251:   count = 0;
3252:   PetscMalloc1(Bn,&idx);
3253:   PetscMalloc1(Bn,&cmap1);

3255:   VecGetArray(lvec,&xarray);
3256:   VecGetArray(lcmap,&cmaparray);
3257:   for (i=0; i<Bn; i++) {
3258:     if (PetscRealPart(xarray[i]) > -1.0) {
3259:       idx[count]     = i;                   /* local column index in off-diagonal part B */
3260:       cmap1[count] = (PetscInt)PetscRealPart(cmaparray[i]);  /* column index in submat */
3261:       count++;
3262:     }
3263:   }
3264:   VecRestoreArray(lvec,&xarray);
3265:   VecRestoreArray(lcmap,&cmaparray);

3267:   ISCreateGeneral(PETSC_COMM_SELF,count,idx,PETSC_COPY_VALUES,iscol_o);
3268:   /* cannot ensure iscol_o has same blocksize as iscol! */

3270:   PetscFree(idx);
3271:   *garray = cmap1;

3273:   VecDestroy(&x);
3274:   VecDestroy(&cmap);
3275:   VecDestroy(&lcmap);
3276:   return(0);
3277: }

3279: /* isrow and iscol have same processor distribution as mat, output *submat is a submatrix of local mat */
3280: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowColDist(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *submat)
3281: {
3283:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)mat->data,*asub;
3284:   Mat            M = NULL;
3285:   MPI_Comm       comm;
3286:   IS             iscol_d,isrow_d,iscol_o;
3287:   Mat            Asub = NULL,Bsub = NULL;
3288:   PetscInt       n;

3291:   PetscObjectGetComm((PetscObject)mat,&comm);

3293:   if (call == MAT_REUSE_MATRIX) {
3294:     /* Retrieve isrow_d, iscol_d and iscol_o from submat */
3295:     PetscObjectQuery((PetscObject)*submat,"isrow_d",(PetscObject*)&isrow_d);
3296:     if (!isrow_d) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"isrow_d passed in was not used before, cannot reuse");

3298:     PetscObjectQuery((PetscObject)*submat,"iscol_d",(PetscObject*)&iscol_d);
3299:     if (!iscol_d) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"iscol_d passed in was not used before, cannot reuse");

3301:     PetscObjectQuery((PetscObject)*submat,"iscol_o",(PetscObject*)&iscol_o);
3302:     if (!iscol_o) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"iscol_o passed in was not used before, cannot reuse");

3304:     /* Update diagonal and off-diagonal portions of submat */
3305:     asub = (Mat_MPIAIJ*)(*submat)->data;
3306:     MatCreateSubMatrix_SeqAIJ(a->A,isrow_d,iscol_d,PETSC_DECIDE,MAT_REUSE_MATRIX,&asub->A);
3307:     ISGetLocalSize(iscol_o,&n);
3308:     if (n) {
3309:       MatCreateSubMatrix_SeqAIJ(a->B,isrow_d,iscol_o,PETSC_DECIDE,MAT_REUSE_MATRIX,&asub->B);
3310:     }
3311:     MatAssemblyBegin(*submat,MAT_FINAL_ASSEMBLY);
3312:     MatAssemblyEnd(*submat,MAT_FINAL_ASSEMBLY);

3314:   } else { /* call == MAT_INITIAL_MATRIX) */
3315:     const PetscInt *garray;
3316:     PetscInt        BsubN;

3318:     /* Create isrow_d, iscol_d, iscol_o and isgarray (replace isgarray with array?) */
3319:     ISGetSeqIS_SameColDist_Private(mat,isrow,iscol,&isrow_d,&iscol_d,&iscol_o,&garray);

3321:     /* Create local submatrices Asub and Bsub */
3322:     MatCreateSubMatrix_SeqAIJ(a->A,isrow_d,iscol_d,PETSC_DECIDE,MAT_INITIAL_MATRIX,&Asub);
3323:     MatCreateSubMatrix_SeqAIJ(a->B,isrow_d,iscol_o,PETSC_DECIDE,MAT_INITIAL_MATRIX,&Bsub);

3325:     /* Create submatrix M */
3326:     MatCreateMPIAIJWithSeqAIJ(comm,Asub,Bsub,garray,&M);

3328:     /* If Bsub has empty columns, compress iscol_o such that it will retrieve condensed Bsub from a->B during reuse */
3329:     asub = (Mat_MPIAIJ*)M->data;

3331:     ISGetLocalSize(iscol_o,&BsubN);
3332:     n = asub->B->cmap->N;
3333:     if (BsubN > n) {
3334:       /* This case can be tested using ~petsc/src/tao/bound/examples/tutorials/runplate2_3 */
3335:       const PetscInt *idx;
3336:       PetscInt       i,j,*idx_new,*subgarray = asub->garray;
3337:       PetscInfo2(M,"submatrix Bn %D != BsubN %D, update iscol_o\n",n,BsubN);

3339:       PetscMalloc1(n,&idx_new);
3340:       j = 0;
3341:       ISGetIndices(iscol_o,&idx);
3342:       for (i=0; i<n; i++) {
3343:         if (j >= BsubN) break;
3344:         while (subgarray[i] > garray[j]) j++;

3346:         if (subgarray[i] == garray[j]) {
3347:           idx_new[i] = idx[j++];
3348:         } else SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"subgarray[%D]=%D cannot < garray[%D]=%D",i,subgarray[i],j,garray[j]);
3349:       }
3350:       ISRestoreIndices(iscol_o,&idx);

3352:       ISDestroy(&iscol_o);
3353:       ISCreateGeneral(PETSC_COMM_SELF,n,idx_new,PETSC_OWN_POINTER,&iscol_o);

3355:     } else if (BsubN < n) {
3356:       SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Columns of Bsub cannot be smaller than B's",BsubN,asub->B->cmap->N);
3357:     }

3359:     PetscFree(garray);
3360:     *submat = M;

3362:     /* Save isrow_d, iscol_d and iscol_o used in processor for next request */
3363:     PetscObjectCompose((PetscObject)M,"isrow_d",(PetscObject)isrow_d);
3364:     ISDestroy(&isrow_d);

3366:     PetscObjectCompose((PetscObject)M,"iscol_d",(PetscObject)iscol_d);
3367:     ISDestroy(&iscol_d);

3369:     PetscObjectCompose((PetscObject)M,"iscol_o",(PetscObject)iscol_o);
3370:     ISDestroy(&iscol_o);
3371:   }
3372:   return(0);
3373: }

3375: PetscErrorCode MatCreateSubMatrix_MPIAIJ(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *newmat)
3376: {
3378:   IS             iscol_local=NULL,isrow_d;
3379:   PetscInt       csize;
3380:   PetscInt       n,i,j,start,end;
3381:   PetscBool      sameRowDist=PETSC_FALSE,sameDist[2],tsameDist[2];
3382:   MPI_Comm       comm;

3385:   /* If isrow has same processor distribution as mat,
3386:      call MatCreateSubMatrix_MPIAIJ_SameRowDist() to avoid using a hash table with global size of iscol */
3387:   if (call == MAT_REUSE_MATRIX) {
3388:     PetscObjectQuery((PetscObject)*newmat,"isrow_d",(PetscObject*)&isrow_d);
3389:     if (isrow_d) {
3390:       sameRowDist  = PETSC_TRUE;
3391:       tsameDist[1] = PETSC_TRUE; /* sameColDist */
3392:     } else {
3393:       PetscObjectQuery((PetscObject)*newmat,"SubIScol",(PetscObject*)&iscol_local);
3394:       if (iscol_local) {
3395:         sameRowDist  = PETSC_TRUE;
3396:         tsameDist[1] = PETSC_FALSE; /* !sameColDist */
3397:       }
3398:     }
3399:   } else {
3400:     /* Check if isrow has same processor distribution as mat */
3401:     sameDist[0] = PETSC_FALSE;
3402:     ISGetLocalSize(isrow,&n);
3403:     if (!n) {
3404:       sameDist[0] = PETSC_TRUE;
3405:     } else {
3406:       ISGetMinMax(isrow,&i,&j);
3407:       MatGetOwnershipRange(mat,&start,&end);
3408:       if (i >= start && j < end) {
3409:         sameDist[0] = PETSC_TRUE;
3410:       }
3411:     }

3413:     /* Check if iscol has same processor distribution as mat */
3414:     sameDist[1] = PETSC_FALSE;
3415:     ISGetLocalSize(iscol,&n);
3416:     if (!n) {
3417:       sameDist[1] = PETSC_TRUE;
3418:     } else {
3419:       ISGetMinMax(iscol,&i,&j);
3420:       MatGetOwnershipRangeColumn(mat,&start,&end);
3421:       if (i >= start && j < end) sameDist[1] = PETSC_TRUE;
3422:     }

3424:     PetscObjectGetComm((PetscObject)mat,&comm);
3425:     MPIU_Allreduce(&sameDist,&tsameDist,2,MPIU_BOOL,MPI_LAND,comm);
3426:     sameRowDist = tsameDist[0];
3427:   }

3429:   if (sameRowDist) {
3430:     if (tsameDist[1]) { /* sameRowDist & sameColDist */
3431:       /* isrow and iscol have same processor distribution as mat */
3432:       MatCreateSubMatrix_MPIAIJ_SameRowColDist(mat,isrow,iscol,call,newmat);
3433:       return(0);
3434:     } else { /* sameRowDist */
3435:       /* isrow has same processor distribution as mat */
3436:       if (call == MAT_INITIAL_MATRIX) {
3437:         PetscBool sorted;
3438:         ISGetSeqIS_Private(mat,iscol,&iscol_local);
3439:         ISGetLocalSize(iscol_local,&n); /* local size of iscol_local = global columns of newmat */
3440:         ISGetSize(iscol,&i);
3441:         if (n != i) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"n %d != size of iscol %d",n,i);

3443:         ISSorted(iscol_local,&sorted);
3444:         if (sorted) {
3445:           /* MatCreateSubMatrix_MPIAIJ_SameRowDist() requires iscol_local be sorted; it can have duplicate indices */
3446:           MatCreateSubMatrix_MPIAIJ_SameRowDist(mat,isrow,iscol,iscol_local,MAT_INITIAL_MATRIX,newmat);
3447:           return(0);
3448:         }
3449:       } else { /* call == MAT_REUSE_MATRIX */
3450:         IS    iscol_sub;
3451:         PetscObjectQuery((PetscObject)*newmat,"SubIScol",(PetscObject*)&iscol_sub);
3452:         if (iscol_sub) {
3453:           MatCreateSubMatrix_MPIAIJ_SameRowDist(mat,isrow,iscol,NULL,call,newmat);
3454:           return(0);
3455:         }
3456:       }
3457:     }
3458:   }

3460:   /* General case: iscol -> iscol_local which has global size of iscol */
3461:   if (call == MAT_REUSE_MATRIX) {
3462:     PetscObjectQuery((PetscObject)*newmat,"ISAllGather",(PetscObject*)&iscol_local);
3463:     if (!iscol_local) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3464:   } else {
3465:     if (!iscol_local) {
3466:       ISGetSeqIS_Private(mat,iscol,&iscol_local);
3467:     }
3468:   }

3470:   ISGetLocalSize(iscol,&csize);
3471:   MatCreateSubMatrix_MPIAIJ_nonscalable(mat,isrow,iscol_local,csize,call,newmat);

3473:   if (call == MAT_INITIAL_MATRIX) {
3474:     PetscObjectCompose((PetscObject)*newmat,"ISAllGather",(PetscObject)iscol_local);
3475:     ISDestroy(&iscol_local);
3476:   }
3477:   return(0);
3478: }

3480: /*@C
3481:      MatCreateMPIAIJWithSeqAIJ - creates a MPIAIJ matrix using SeqAIJ matrices that contain the "diagonal"
3482:          and "off-diagonal" part of the matrix in CSR format.

3484:    Collective on MPI_Comm

3486:    Input Parameters:
3487: +  comm - MPI communicator
3488: .  A - "diagonal" portion of matrix
3489: .  B - "off-diagonal" portion of matrix, may have empty columns, will be destroyed by this routine
3490: -  garray - global index of B columns

3492:    Output Parameter:
3493: .   mat - the matrix, with input A as its local diagonal matrix
3494:    Level: advanced

3496:    Notes:
3497:        See MatCreateAIJ() for the definition of "diagonal" and "off-diagonal" portion of the matrix.
3498:        A becomes part of output mat, B is destroyed by this routine. The user cannot use A and B anymore.

3500: .seealso: MatCreateMPIAIJWithSplitArrays()
3501: @*/
3502: PetscErrorCode MatCreateMPIAIJWithSeqAIJ(MPI_Comm comm,Mat A,Mat B,const PetscInt garray[],Mat *mat)
3503: {
3505:   Mat_MPIAIJ     *maij;
3506:   Mat_SeqAIJ     *b=(Mat_SeqAIJ*)B->data,*bnew;
3507:   PetscInt       *oi=b->i,*oj=b->j,i,nz,col;
3508:   PetscScalar    *oa=b->a;
3509:   Mat            Bnew;
3510:   PetscInt       m,n,N;

3513:   MatCreate(comm,mat);
3514:   MatGetSize(A,&m,&n);
3515:   if (m != B->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Am %D != Bm %D",m,B->rmap->N);
3516:   if (A->rmap->bs != B->rmap->bs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"A row bs %D != B row bs %D",A->rmap->bs,B->rmap->bs);
3517:   /* remove check below; When B is created using iscol_o from ISGetSeqIS_SameColDist_Private(), its bs may not be same as A */
3518:   /* if (A->cmap->bs != B->cmap->bs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"A column bs %D != B column bs %D",A->cmap->bs,B->cmap->bs); */

3520:   /* Get global columns of mat */
3521:   MPIU_Allreduce(&n,&N,1,MPIU_INT,MPI_SUM,comm);

3523:   MatSetSizes(*mat,m,n,PETSC_DECIDE,N);
3524:   MatSetType(*mat,MATMPIAIJ);
3525:   MatSetBlockSizes(*mat,A->rmap->bs,A->cmap->bs);
3526:   maij = (Mat_MPIAIJ*)(*mat)->data;

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

3530:   PetscLayoutSetUp((*mat)->rmap);
3531:   PetscLayoutSetUp((*mat)->cmap);

3533:   /* Set A as diagonal portion of *mat */
3534:   maij->A = A;

3536:   nz = oi[m];
3537:   for (i=0; i<nz; i++) {
3538:     col   = oj[i];
3539:     oj[i] = garray[col];
3540:   }

3542:    /* Set Bnew as off-diagonal portion of *mat */
3543:   MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,m,N,oi,oj,oa,&Bnew);
3544:   bnew        = (Mat_SeqAIJ*)Bnew->data;
3545:   bnew->maxnz = b->maxnz; /* allocated nonzeros of B */
3546:   maij->B     = Bnew;

3548:   if (B->rmap->N != Bnew->rmap->N) SETERRQ2(PETSC_COMM_SELF,0,"BN %d != BnewN %d",B->rmap->N,Bnew->rmap->N);

3550:   b->singlemalloc = PETSC_FALSE; /* B arrays are shared by Bnew */
3551:   b->free_a       = PETSC_FALSE;
3552:   b->free_ij      = PETSC_FALSE;
3553:   MatDestroy(&B);

3555:   bnew->singlemalloc = PETSC_TRUE; /* arrays will be freed by MatDestroy(&Bnew) */
3556:   bnew->free_a       = PETSC_TRUE;
3557:   bnew->free_ij      = PETSC_TRUE;

3559:   /* condense columns of maij->B */
3560:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
3561:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
3562:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
3563:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_FALSE);
3564:   MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3565:   return(0);
3566: }

3568: extern PetscErrorCode MatCreateSubMatrices_MPIAIJ_SingleIS_Local(Mat,PetscInt,const IS[],const IS[],MatReuse,PetscBool,Mat*);

3570: PetscErrorCode MatCreateSubMatrix_MPIAIJ_SameRowDist(Mat mat,IS isrow,IS iscol,IS iscol_local,MatReuse call,Mat *newmat)
3571: {
3573:   PetscInt       i,m,n,rstart,row,rend,nz,j,bs,cbs;
3574:   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal;
3575:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)mat->data;
3576:   Mat            M,Msub,B=a->B;
3577:   MatScalar      *aa;
3578:   Mat_SeqAIJ     *aij;
3579:   PetscInt       *garray = a->garray,*colsub,Ncols;
3580:   PetscInt       count,Bn=B->cmap->N,cstart=mat->cmap->rstart,cend=mat->cmap->rend;
3581:   IS             iscol_sub,iscmap;
3582:   const PetscInt *is_idx,*cmap;
3583:   PetscBool      allcolumns=PETSC_FALSE;
3584:   MPI_Comm       comm;

3587:   PetscObjectGetComm((PetscObject)mat,&comm);

3589:   if (call == MAT_REUSE_MATRIX) {
3590:     PetscObjectQuery((PetscObject)*newmat,"SubIScol",(PetscObject*)&iscol_sub);
3591:     if (!iscol_sub) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SubIScol passed in was not used before, cannot reuse");
3592:     ISGetLocalSize(iscol_sub,&count);

3594:     PetscObjectQuery((PetscObject)*newmat,"Subcmap",(PetscObject*)&iscmap);
3595:     if (!iscmap) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Subcmap passed in was not used before, cannot reuse");

3597:     PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Msub);
3598:     if (!Msub) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");

3600:     MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat,1,&isrow,&iscol_sub,MAT_REUSE_MATRIX,PETSC_FALSE,&Msub);

3602:   } else { /* call == MAT_INITIAL_MATRIX) */
3603:     PetscBool flg;

3605:     ISGetLocalSize(iscol,&n);
3606:     ISGetSize(iscol,&Ncols);

3608:     /* (1) iscol -> nonscalable iscol_local */
3609:     /* Check for special case: each processor gets entire matrix columns */
3610:     ISIdentity(iscol_local,&flg);
3611:     if (flg && n == mat->cmap->N) allcolumns = PETSC_TRUE;
3612:     if (allcolumns) {
3613:       iscol_sub = iscol_local;
3614:       PetscObjectReference((PetscObject)iscol_local);
3615:       ISCreateStride(PETSC_COMM_SELF,n,0,1,&iscmap);

3617:     } else {
3618:       /* (2) iscol_local -> iscol_sub and iscmap. Implementation below requires iscol_local be sorted, it can have duplicate indices */
3619:       PetscInt *idx,*cmap1,k;
3620:       PetscMalloc1(Ncols,&idx);
3621:       PetscMalloc1(Ncols,&cmap1);
3622:       ISGetIndices(iscol_local,&is_idx);
3623:       count = 0;
3624:       k     = 0;
3625:       for (i=0; i<Ncols; i++) {
3626:         j = is_idx[i];
3627:         if (j >= cstart && j < cend) {
3628:           /* diagonal part of mat */
3629:           idx[count]     = j;
3630:           cmap1[count++] = i; /* column index in submat */
3631:         } else if (Bn) {
3632:           /* off-diagonal part of mat */
3633:           if (j == garray[k]) {
3634:             idx[count]     = j;
3635:             cmap1[count++] = i;  /* column index in submat */
3636:           } else if (j > garray[k]) {
3637:             while (j > garray[k] && k < Bn-1) k++;
3638:             if (j == garray[k]) {
3639:               idx[count]     = j;
3640:               cmap1[count++] = i; /* column index in submat */
3641:             }
3642:           }
3643:         }
3644:       }
3645:       ISRestoreIndices(iscol_local,&is_idx);

3647:       ISCreateGeneral(PETSC_COMM_SELF,count,idx,PETSC_OWN_POINTER,&iscol_sub);
3648:       ISGetBlockSize(iscol,&cbs);
3649:       ISSetBlockSize(iscol_sub,cbs);

3651:       ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local),count,cmap1,PETSC_OWN_POINTER,&iscmap);
3652:     }

3654:     /* (3) Create sequential Msub */
3655:     MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat,1,&isrow,&iscol_sub,MAT_INITIAL_MATRIX,allcolumns,&Msub);
3656:   }

3658:   ISGetLocalSize(iscol_sub,&count);
3659:   aij  = (Mat_SeqAIJ*)(Msub)->data;
3660:   ii   = aij->i;
3661:   ISGetIndices(iscmap,&cmap);

3663:   /*
3664:       m - number of local rows
3665:       Ncols - number of columns (same on all processors)
3666:       rstart - first row in new global matrix generated
3667:   */
3668:   MatGetSize(Msub,&m,NULL);

3670:   if (call == MAT_INITIAL_MATRIX) {
3671:     /* (4) Create parallel newmat */
3672:     PetscMPIInt    rank,size;
3673:     PetscInt       csize;

3675:     MPI_Comm_size(comm,&size);
3676:     MPI_Comm_rank(comm,&rank);

3678:     /*
3679:         Determine the number of non-zeros in the diagonal and off-diagonal
3680:         portions of the matrix in order to do correct preallocation
3681:     */

3683:     /* first get start and end of "diagonal" columns */
3684:     ISGetLocalSize(iscol,&csize);
3685:     if (csize == PETSC_DECIDE) {
3686:       ISGetSize(isrow,&mglobal);
3687:       if (mglobal == Ncols) { /* square matrix */
3688:         nlocal = m;
3689:       } else {
3690:         nlocal = Ncols/size + ((Ncols % size) > rank);
3691:       }
3692:     } else {
3693:       nlocal = csize;
3694:     }
3695:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3696:     rstart = rend - nlocal;
3697:     if (rank == size - 1 && rend != Ncols) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Local column sizes %D do not add up to total number of columns %D",rend,Ncols);

3699:     /* next, compute all the lengths */
3700:     jj    = aij->j;
3701:     PetscMalloc1(2*m+1,&dlens);
3702:     olens = dlens + m;
3703:     for (i=0; i<m; i++) {
3704:       jend = ii[i+1] - ii[i];
3705:       olen = 0;
3706:       dlen = 0;
3707:       for (j=0; j<jend; j++) {
3708:         if (cmap[*jj] < rstart || cmap[*jj] >= rend) olen++;
3709:         else dlen++;
3710:         jj++;
3711:       }
3712:       olens[i] = olen;
3713:       dlens[i] = dlen;
3714:     }

3716:     ISGetBlockSize(isrow,&bs);
3717:     ISGetBlockSize(iscol,&cbs);

3719:     MatCreate(comm,&M);
3720:     MatSetSizes(M,m,nlocal,PETSC_DECIDE,Ncols);
3721:     MatSetBlockSizes(M,bs,cbs);
3722:     MatSetType(M,((PetscObject)mat)->type_name);
3723:     MatMPIAIJSetPreallocation(M,0,dlens,0,olens);
3724:     PetscFree(dlens);

3726:   } else { /* call == MAT_REUSE_MATRIX */
3727:     M    = *newmat;
3728:     MatGetLocalSize(M,&i,NULL);
3729:     if (i != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3730:     MatZeroEntries(M);
3731:     /*
3732:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3733:        rather than the slower MatSetValues().
3734:     */
3735:     M->was_assembled = PETSC_TRUE;
3736:     M->assembled     = PETSC_FALSE;
3737:   }

3739:   /* (5) Set values of Msub to *newmat */
3740:   PetscMalloc1(count,&colsub);
3741:   MatGetOwnershipRange(M,&rstart,NULL);

3743:   jj   = aij->j;
3744:   aa   = aij->a;
3745:   for (i=0; i<m; i++) {
3746:     row = rstart + i;
3747:     nz  = ii[i+1] - ii[i];
3748:     for (j=0; j<nz; j++) colsub[j] = cmap[jj[j]];
3749:     MatSetValues_MPIAIJ(M,1,&row,nz,colsub,aa,INSERT_VALUES);
3750:     jj += nz; aa += nz;
3751:   }
3752:   ISRestoreIndices(iscmap,&cmap);

3754:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3755:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);

3757:   PetscFree(colsub);

3759:   /* save Msub, iscol_sub and iscmap used in processor for next request */
3760:   if (call ==  MAT_INITIAL_MATRIX) {
3761:     *newmat = M;
3762:     PetscObjectCompose((PetscObject)(*newmat),"SubMatrix",(PetscObject)Msub);
3763:     MatDestroy(&Msub);

3765:     PetscObjectCompose((PetscObject)(*newmat),"SubIScol",(PetscObject)iscol_sub);
3766:     ISDestroy(&iscol_sub);

3768:     PetscObjectCompose((PetscObject)(*newmat),"Subcmap",(PetscObject)iscmap);
3769:     ISDestroy(&iscmap);

3771:     if (iscol_local) {
3772:       PetscObjectCompose((PetscObject)(*newmat),"ISAllGather",(PetscObject)iscol_local);
3773:       ISDestroy(&iscol_local);
3774:     }
3775:   }
3776:   return(0);
3777: }

3779: /*
3780:     Not great since it makes two copies of the submatrix, first an SeqAIJ
3781:   in local and then by concatenating the local matrices the end result.
3782:   Writing it directly would be much like MatCreateSubMatrices_MPIAIJ()

3784:   Note: This requires a sequential iscol with all indices.
3785: */
3786: PetscErrorCode MatCreateSubMatrix_MPIAIJ_nonscalable(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
3787: {
3789:   PetscMPIInt    rank,size;
3790:   PetscInt       i,m,n,rstart,row,rend,nz,*cwork,j,bs,cbs;
3791:   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal;
3792:   Mat            M,Mreuse;
3793:   MatScalar      *aa,*vwork;
3794:   MPI_Comm       comm;
3795:   Mat_SeqAIJ     *aij;
3796:   PetscBool      colflag,allcolumns=PETSC_FALSE;

3799:   PetscObjectGetComm((PetscObject)mat,&comm);
3800:   MPI_Comm_rank(comm,&rank);
3801:   MPI_Comm_size(comm,&size);

3803:   /* Check for special case: each processor gets entire matrix columns */
3804:   ISIdentity(iscol,&colflag);
3805:   ISGetLocalSize(iscol,&n);
3806:   if (colflag && n == mat->cmap->N) allcolumns = PETSC_TRUE;

3808:   if (call ==  MAT_REUSE_MATRIX) {
3809:     PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Mreuse);
3810:     if (!Mreuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3811:     MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,allcolumns,&Mreuse);
3812:   } else {
3813:     MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,allcolumns,&Mreuse);
3814:   }

3816:   /*
3817:       m - number of local rows
3818:       n - number of columns (same on all processors)
3819:       rstart - first row in new global matrix generated
3820:   */
3821:   MatGetSize(Mreuse,&m,&n);
3822:   MatGetBlockSizes(Mreuse,&bs,&cbs);
3823:   if (call == MAT_INITIAL_MATRIX) {
3824:     aij = (Mat_SeqAIJ*)(Mreuse)->data;
3825:     ii  = aij->i;
3826:     jj  = aij->j;

3828:     /*
3829:         Determine the number of non-zeros in the diagonal and off-diagonal
3830:         portions of the matrix in order to do correct preallocation
3831:     */

3833:     /* first get start and end of "diagonal" columns */
3834:     if (csize == PETSC_DECIDE) {
3835:       ISGetSize(isrow,&mglobal);
3836:       if (mglobal == n) { /* square matrix */
3837:         nlocal = m;
3838:       } else {
3839:         nlocal = n/size + ((n % size) > rank);
3840:       }
3841:     } else {
3842:       nlocal = csize;
3843:     }
3844:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3845:     rstart = rend - nlocal;
3846:     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);

3848:     /* next, compute all the lengths */
3849:     PetscMalloc1(2*m+1,&dlens);
3850:     olens = dlens + m;
3851:     for (i=0; i<m; i++) {
3852:       jend = ii[i+1] - ii[i];
3853:       olen = 0;
3854:       dlen = 0;
3855:       for (j=0; j<jend; j++) {
3856:         if (*jj < rstart || *jj >= rend) olen++;
3857:         else dlen++;
3858:         jj++;
3859:       }
3860:       olens[i] = olen;
3861:       dlens[i] = dlen;
3862:     }
3863:     MatCreate(comm,&M);
3864:     MatSetSizes(M,m,nlocal,PETSC_DECIDE,n);
3865:     MatSetBlockSizes(M,bs,cbs);
3866:     MatSetType(M,((PetscObject)mat)->type_name);
3867:     MatMPIAIJSetPreallocation(M,0,dlens,0,olens);
3868:     PetscFree(dlens);
3869:   } else {
3870:     PetscInt ml,nl;

3872:     M    = *newmat;
3873:     MatGetLocalSize(M,&ml,&nl);
3874:     if (ml != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3875:     MatZeroEntries(M);
3876:     /*
3877:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3878:        rather than the slower MatSetValues().
3879:     */
3880:     M->was_assembled = PETSC_TRUE;
3881:     M->assembled     = PETSC_FALSE;
3882:   }
3883:   MatGetOwnershipRange(M,&rstart,&rend);
3884:   aij  = (Mat_SeqAIJ*)(Mreuse)->data;
3885:   ii   = aij->i;
3886:   jj   = aij->j;
3887:   aa   = aij->a;
3888:   for (i=0; i<m; i++) {
3889:     row   = rstart + i;
3890:     nz    = ii[i+1] - ii[i];
3891:     cwork = jj;     jj += nz;
3892:     vwork = aa;     aa += nz;
3893:     MatSetValues_MPIAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);
3894:   }

3896:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3897:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
3898:   *newmat = M;

3900:   /* save submatrix used in processor for next request */
3901:   if (call ==  MAT_INITIAL_MATRIX) {
3902:     PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);
3903:     MatDestroy(&Mreuse);
3904:   }
3905:   return(0);
3906: }

3908: PetscErrorCode MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3909: {
3910:   PetscInt       m,cstart, cend,j,nnz,i,d;
3911:   PetscInt       *d_nnz,*o_nnz,nnz_max = 0,rstart,ii;
3912:   const PetscInt *JJ;
3913:   PetscScalar    *values;
3915:   PetscBool      nooffprocentries;

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

3920:   PetscLayoutSetUp(B->rmap);
3921:   PetscLayoutSetUp(B->cmap);
3922:   m      = B->rmap->n;
3923:   cstart = B->cmap->rstart;
3924:   cend   = B->cmap->rend;
3925:   rstart = B->rmap->rstart;

3927:   PetscCalloc2(m,&d_nnz,m,&o_nnz);

3929: #if defined(PETSC_USE_DEBUG)
3930:   for (i=0; i<m && Ii; i++) {
3931:     nnz = Ii[i+1]- Ii[i];
3932:     JJ  = J + Ii[i];
3933:     if (nnz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
3934:     if (nnz && (JJ[0] < 0)) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,JJ[0]);
3935:     if (nnz && (JJ[nnz-1] >= B->cmap->N)) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Row %D ends with too large a column index %D (max allowed %D)",i,JJ[nnz-1],B->cmap->N);
3936:   }
3937: #endif

3939:   for (i=0; i<m && Ii; i++) {
3940:     nnz     = Ii[i+1]- Ii[i];
3941:     JJ      = J + Ii[i];
3942:     nnz_max = PetscMax(nnz_max,nnz);
3943:     d       = 0;
3944:     for (j=0; j<nnz; j++) {
3945:       if (cstart <= JJ[j] && JJ[j] < cend) d++;
3946:     }
3947:     d_nnz[i] = d;
3948:     o_nnz[i] = nnz - d;
3949:   }
3950:   MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
3951:   PetscFree2(d_nnz,o_nnz);

3953:   if (v) values = (PetscScalar*)v;
3954:   else {
3955:     PetscCalloc1(nnz_max+1,&values);
3956:   }

3958:   for (i=0; i<m && Ii; i++) {
3959:     ii   = i + rstart;
3960:     nnz  = Ii[i+1]- Ii[i];
3961:     MatSetValues_MPIAIJ(B,1,&ii,nnz,J+Ii[i],values+(v ? Ii[i] : 0),INSERT_VALUES);
3962:   }
3963:   nooffprocentries    = B->nooffprocentries;
3964:   B->nooffprocentries = PETSC_TRUE;
3965:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3966:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3967:   B->nooffprocentries = nooffprocentries;

3969:   if (!v) {
3970:     PetscFree(values);
3971:   }
3972:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3973:   return(0);
3974: }

3976: /*@
3977:    MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
3978:    (the default parallel PETSc format).

3980:    Collective on MPI_Comm

3982:    Input Parameters:
3983: +  B - the matrix
3984: .  i - the indices into j for the start of each local row (starts with zero)
3985: .  j - the column indices for each local row (starts with zero)
3986: -  v - optional values in the matrix

3988:    Level: developer

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

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

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

4001: $        1 0 0
4002: $        2 0 3     P0
4003: $       -------
4004: $        4 5 6     P1
4005: $
4006: $     Process0 [P0]: rows_owned=[0,1]
4007: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
4008: $        j =  {0,0,2}  [size = 3]
4009: $        v =  {1,2,3}  [size = 3]
4010: $
4011: $     Process1 [P1]: rows_owned=[2]
4012: $        i =  {0,3}    [size = nrow+1  = 1+1]
4013: $        j =  {0,1,2}  [size = 3]
4014: $        v =  {4,5,6}  [size = 3]

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

4018: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateAIJ(), MATMPIAIJ,
4019:           MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
4020: @*/
4021: PetscErrorCode  MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
4022: {

4026:   PetscTryMethod(B,"MatMPIAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
4027:   return(0);
4028: }

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

4037:    Collective on MPI_Comm

4039:    Input Parameters:
4040: +  B - the matrix
4041: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4042:            (same value is used for all local rows)
4043: .  d_nnz - array containing the number of nonzeros in the various rows of the
4044:            DIAGONAL portion of the local submatrix (possibly different for each row)
4045:            or NULL (PETSC_NULL_INTEGER in Fortran), if d_nz is used to specify the nonzero structure.
4046:            The size of this array is equal to the number of local rows, i.e 'm'.
4047:            For matrices that will be factored, you must leave room for (and set)
4048:            the diagonal entry even if it is zero.
4049: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4050:            submatrix (same value is used for all local rows).
4051: -  o_nnz - array containing the number of nonzeros in the various rows of the
4052:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4053:            each row) or NULL (PETSC_NULL_INTEGER in Fortran), if o_nz is used to specify the nonzero
4054:            structure. The size of this array is equal to the number
4055:            of local rows, i.e 'm'.

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

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

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

4068:    The DIAGONAL portion of the local submatrix of a processor can be defined
4069:    as the submatrix which is obtained by extraction the part corresponding to
4070:    the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4071:    first row that belongs to the processor, r2 is the last row belonging to
4072:    the this processor, and c1-c2 is range of indices of the local part of a
4073:    vector suitable for applying the matrix to.  This is an mxn matrix.  In the
4074:    common case of a square matrix, the row and column ranges are the same and
4075:    the DIAGONAL part is also square. The remaining portion of the local
4076:    submatrix (mxN) constitute the OFF-DIAGONAL portion.

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

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

4085:    Example usage:

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

4092: .vb
4093:             1  2  0  |  0  3  0  |  0  4
4094:     Proc0   0  5  6  |  7  0  0  |  8  0
4095:             9  0 10  | 11  0  0  | 12  0
4096:     -------------------------------------
4097:            13  0 14  | 15 16 17  |  0  0
4098:     Proc1   0 18  0  | 19 20 21  |  0  0
4099:             0  0  0  | 22 23  0  | 24  0
4100:     -------------------------------------
4101:     Proc2  25 26 27  |  0  0 28  | 29  0
4102:            30  0  0  | 31 32 33  |  0 34
4103: .ve

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

4107: .vb
4108:       A B C
4109:       D E F
4110:       G H I
4111: .ve

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

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

4120:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4121:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4122:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4123:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4124:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4125:    matrix, ans [DF] as another SeqAIJ matrix.

4127:    When d_nz, o_nz parameters are specified, d_nz storage elements are
4128:    allocated for every row of the local diagonal submatrix, and o_nz
4129:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4130:    One way to choose d_nz and o_nz is to use the max nonzerors per local
4131:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4132:    In this case, the values of d_nz,o_nz are:
4133: .vb
4134:      proc0 : dnz = 2, o_nz = 2
4135:      proc1 : dnz = 3, o_nz = 2
4136:      proc2 : dnz = 1, o_nz = 4
4137: .ve
4138:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4139:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4140:    for proc3. i.e we are using 12+15+10=37 storage locations to store
4141:    34 values.

4143:    When d_nnz, o_nnz parameters are specified, the storage is specified
4144:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4145:    In the above case the values for d_nnz,o_nnz are:
4146: .vb
4147:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4148:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4149:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4150: .ve
4151:    Here the space allocated is sum of all the above values i.e 34, and
4152:    hence pre-allocation is perfect.

4154:    Level: intermediate

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

4158: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateAIJ(), MatMPIAIJSetPreallocationCSR(),
4159:           MATMPIAIJ, MatGetInfo(), PetscSplitOwnership()
4160: @*/
4161: PetscErrorCode MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
4162: {

4168:   PetscTryMethod(B,"MatMPIAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
4169:   return(0);
4170: }

4172: /*@
4173:      MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
4174:          CSR format the local rows.

4176:    Collective on MPI_Comm

4178:    Input Parameters:
4179: +  comm - MPI communicator
4180: .  m - number of local rows (Cannot be PETSC_DECIDE)
4181: .  n - This value should be the same as the local size used in creating the
4182:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4183:        calculated if N is given) For square matrices n is almost always m.
4184: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4185: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4186: .   i - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
4187: .   j - column indices
4188: -   a - matrix values

4190:    Output Parameter:
4191: .   mat - the matrix

4193:    Level: intermediate

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

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

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

4206: $        1 0 0
4207: $        2 0 3     P0
4208: $       -------
4209: $        4 5 6     P1
4210: $
4211: $     Process0 [P0]: rows_owned=[0,1]
4212: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
4213: $        j =  {0,0,2}  [size = 3]
4214: $        v =  {1,2,3}  [size = 3]
4215: $
4216: $     Process1 [P1]: rows_owned=[2]
4217: $        i =  {0,3}    [size = nrow+1  = 1+1]
4218: $        j =  {0,1,2}  [size = 3]
4219: $        v =  {4,5,6}  [size = 3]

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

4223: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4224:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
4225: @*/
4226: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
4227: {

4231:   if (i && i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4232:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4233:   MatCreate(comm,mat);
4234:   MatSetSizes(*mat,m,n,M,N);
4235:   /* MatSetBlockSizes(M,bs,cbs); */
4236:   MatSetType(*mat,MATMPIAIJ);
4237:   MatMPIAIJSetPreallocationCSR(*mat,i,j,a);
4238:   return(0);
4239: }

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

4248:    Collective on MPI_Comm

4250:    Input Parameters:
4251: +  comm - MPI communicator
4252: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
4253:            This value should be the same as the local size used in creating the
4254:            y vector for the matrix-vector product y = Ax.
4255: .  n - This value should be the same as the local size used in creating the
4256:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4257:        calculated if N is given) For square matrices n is almost always m.
4258: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4259: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4260: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4261:            (same value is used for all local rows)
4262: .  d_nnz - array containing the number of nonzeros in the various rows of the
4263:            DIAGONAL portion of the local submatrix (possibly different for each row)
4264:            or NULL, if d_nz is used to specify the nonzero structure.
4265:            The size of this array is equal to the number of local rows, i.e 'm'.
4266: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4267:            submatrix (same value is used for all local rows).
4268: -  o_nnz - array containing the number of nonzeros in the various rows of the
4269:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4270:            each row) or NULL, if o_nz is used to specify the nonzero
4271:            structure. The size of this array is equal to the number
4272:            of local rows, i.e 'm'.

4274:    Output Parameter:
4275: .  A - the matrix

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

4281:    Notes:
4282:    If the *_nnz parameter is given then the *_nz parameter is ignored

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

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

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

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

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

4305:    The DIAGONAL portion of the local submatrix on any given processor
4306:    is the submatrix corresponding to the rows and columns m,n
4307:    corresponding to the given processor. i.e diagonal matrix on
4308:    process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4309:    etc. The remaining portion of the local submatrix [m x (N-n)]
4310:    constitute the OFF-DIAGONAL portion. The example below better
4311:    illustrates this concept.

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

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

4320:    When calling this routine with a single process communicator, a matrix of
4321:    type SEQAIJ is returned.  If a matrix of type MPIAIJ is desired for this
4322:    type of communicator, use the construction mechanism
4323: .vb
4324:      MatCreate(...,&A); MatSetType(A,MATMPIAIJ); MatSetSizes(A, m,n,M,N); MatMPIAIJSetPreallocation(A,...);
4325: .ve

4327: $     MatCreate(...,&A);
4328: $     MatSetType(A,MATMPIAIJ);
4329: $     MatSetSizes(A, m,n,M,N);
4330: $     MatMPIAIJSetPreallocation(A,...);

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

4336:    Options Database Keys:
4337: +  -mat_no_inode  - Do not use inodes
4338: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)



4342:    Example usage:

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

4349: .vb
4350:             1  2  0  |  0  3  0  |  0  4
4351:     Proc0   0  5  6  |  7  0  0  |  8  0
4352:             9  0 10  | 11  0  0  | 12  0
4353:     -------------------------------------
4354:            13  0 14  | 15 16 17  |  0  0
4355:     Proc1   0 18  0  | 19 20 21  |  0  0
4356:             0  0  0  | 22 23  0  | 24  0
4357:     -------------------------------------
4358:     Proc2  25 26 27  |  0  0 28  | 29  0
4359:            30  0  0  | 31 32 33  |  0 34
4360: .ve

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

4364: .vb
4365:       A B C
4366:       D E F
4367:       G H I
4368: .ve

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

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

4377:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4378:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4379:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4380:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4381:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4382:    matrix, ans [DF] as another SeqAIJ matrix.

4384:    When d_nz, o_nz parameters are specified, d_nz storage elements are
4385:    allocated for every row of the local diagonal submatrix, and o_nz
4386:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4387:    One way to choose d_nz and o_nz is to use the max nonzerors per local
4388:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4389:    In this case, the values of d_nz,o_nz are
4390: .vb
4391:      proc0 : dnz = 2, o_nz = 2
4392:      proc1 : dnz = 3, o_nz = 2
4393:      proc2 : dnz = 1, o_nz = 4
4394: .ve
4395:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4396:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4397:    for proc3. i.e we are using 12+15+10=37 storage locations to store
4398:    34 values.

4400:    When d_nnz, o_nnz parameters are specified, the storage is specified
4401:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4402:    In the above case the values for d_nnz,o_nnz are
4403: .vb
4404:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4405:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4406:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4407: .ve
4408:    Here the space allocated is sum of all the above values i.e 34, and
4409:    hence pre-allocation is perfect.

4411:    Level: intermediate

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

4415: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4416:           MATMPIAIJ, MatCreateMPIAIJWithArrays()
4417: @*/
4418: 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)
4419: {
4421:   PetscMPIInt    size;

4424:   MatCreate(comm,A);
4425:   MatSetSizes(*A,m,n,M,N);
4426:   MPI_Comm_size(comm,&size);
4427:   if (size > 1) {
4428:     MatSetType(*A,MATMPIAIJ);
4429:     MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);
4430:   } else {
4431:     MatSetType(*A,MATSEQAIJ);
4432:     MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);
4433:   }
4434:   return(0);
4435: }

4437: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
4438: {
4439:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
4440:   PetscBool      flg;

4444:   PetscStrbeginswith(((PetscObject)A)->type_name,MATMPIAIJ,&flg);
4445:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"This function requires a MATMPIAIJ matrix as input");
4446:   if (Ad)     *Ad     = a->A;
4447:   if (Ao)     *Ao     = a->B;
4448:   if (colmap) *colmap = a->garray;
4449:   return(0);
4450: }

4452: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4453: {
4455:   PetscInt       m,N,i,rstart,nnz,Ii;
4456:   PetscInt       *indx;
4457:   PetscScalar    *values;

4460:   MatGetSize(inmat,&m,&N);
4461:   if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4462:     PetscInt       *dnz,*onz,sum,bs,cbs;

4464:     if (n == PETSC_DECIDE) {
4465:       PetscSplitOwnership(comm,&n,&N);
4466:     }
4467:     /* Check sum(n) = N */
4468:     MPIU_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);
4469:     if (sum != N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns %D != global columns %D",sum,N);

4471:     MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);
4472:     rstart -= m;

4474:     MatPreallocateInitialize(comm,m,n,dnz,onz);
4475:     for (i=0; i<m; i++) {
4476:       MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4477:       MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);
4478:       MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4479:     }

4481:     MatCreate(comm,outmat);
4482:     MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4483:     MatGetBlockSizes(inmat,&bs,&cbs);
4484:     MatSetBlockSizes(*outmat,bs,cbs);
4485:     MatSetType(*outmat,MATAIJ);
4486:     MatSeqAIJSetPreallocation(*outmat,0,dnz);
4487:     MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);
4488:     MatPreallocateFinalize(dnz,onz);
4489:   }

4491:   /* numeric phase */
4492:   MatGetOwnershipRange(*outmat,&rstart,NULL);
4493:   for (i=0; i<m; i++) {
4494:     MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4495:     Ii   = i + rstart;
4496:     MatSetValues(*outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
4497:     MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4498:   }
4499:   MatAssemblyBegin(*outmat,MAT_FINAL_ASSEMBLY);
4500:   MatAssemblyEnd(*outmat,MAT_FINAL_ASSEMBLY);
4501:   return(0);
4502: }

4504: PetscErrorCode MatFileSplit(Mat A,char *outfile)
4505: {
4506:   PetscErrorCode    ierr;
4507:   PetscMPIInt       rank;
4508:   PetscInt          m,N,i,rstart,nnz;
4509:   size_t            len;
4510:   const PetscInt    *indx;
4511:   PetscViewer       out;
4512:   char              *name;
4513:   Mat               B;
4514:   const PetscScalar *values;

4517:   MatGetLocalSize(A,&m,0);
4518:   MatGetSize(A,0,&N);
4519:   /* Should this be the type of the diagonal block of A? */
4520:   MatCreate(PETSC_COMM_SELF,&B);
4521:   MatSetSizes(B,m,N,m,N);
4522:   MatSetBlockSizesFromMats(B,A,A);
4523:   MatSetType(B,MATSEQAIJ);
4524:   MatSeqAIJSetPreallocation(B,0,NULL);
4525:   MatGetOwnershipRange(A,&rstart,0);
4526:   for (i=0; i<m; i++) {
4527:     MatGetRow(A,i+rstart,&nnz,&indx,&values);
4528:     MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);
4529:     MatRestoreRow(A,i+rstart,&nnz,&indx,&values);
4530:   }
4531:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4532:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

4534:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);
4535:   PetscStrlen(outfile,&len);
4536:   PetscMalloc1(len+5,&name);
4537:   sprintf(name,"%s.%d",outfile,rank);
4538:   PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);
4539:   PetscFree(name);
4540:   MatView(B,out);
4541:   PetscViewerDestroy(&out);
4542:   MatDestroy(&B);
4543:   return(0);
4544: }

4546: PetscErrorCode MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
4547: {
4548:   PetscErrorCode      ierr;
4549:   Mat_Merge_SeqsToMPI *merge;
4550:   PetscContainer      container;

4553:   PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject*)&container);
4554:   if (container) {
4555:     PetscContainerGetPointer(container,(void**)&merge);
4556:     PetscFree(merge->id_r);
4557:     PetscFree(merge->len_s);
4558:     PetscFree(merge->len_r);
4559:     PetscFree(merge->bi);
4560:     PetscFree(merge->bj);
4561:     PetscFree(merge->buf_ri[0]);
4562:     PetscFree(merge->buf_ri);
4563:     PetscFree(merge->buf_rj[0]);
4564:     PetscFree(merge->buf_rj);
4565:     PetscFree(merge->coi);
4566:     PetscFree(merge->coj);
4567:     PetscFree(merge->owners_co);
4568:     PetscLayoutDestroy(&merge->rowmap);
4569:     PetscFree(merge);
4570:     PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);
4571:   }
4572:   MatDestroy_MPIAIJ(A);
4573:   return(0);
4574: }

4576:  #include <../src/mat/utils/freespace.h>
4577:  #include <petscbt.h>

4579: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat,Mat mpimat)
4580: {
4581:   PetscErrorCode      ierr;
4582:   MPI_Comm            comm;
4583:   Mat_SeqAIJ          *a  =(Mat_SeqAIJ*)seqmat->data;
4584:   PetscMPIInt         size,rank,taga,*len_s;
4585:   PetscInt            N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj;
4586:   PetscInt            proc,m;
4587:   PetscInt            **buf_ri,**buf_rj;
4588:   PetscInt            k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
4589:   PetscInt            nrows,**buf_ri_k,**nextrow,**nextai;
4590:   MPI_Request         *s_waits,*r_waits;
4591:   MPI_Status          *status;
4592:   MatScalar           *aa=a->a;
4593:   MatScalar           **abuf_r,*ba_i;
4594:   Mat_Merge_SeqsToMPI *merge;
4595:   PetscContainer      container;

4598:   PetscObjectGetComm((PetscObject)mpimat,&comm);
4599:   PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);

4601:   MPI_Comm_size(comm,&size);
4602:   MPI_Comm_rank(comm,&rank);

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

4607:   bi     = merge->bi;
4608:   bj     = merge->bj;
4609:   buf_ri = merge->buf_ri;
4610:   buf_rj = merge->buf_rj;

4612:   PetscMalloc1(size,&status);
4613:   owners = merge->rowmap->range;
4614:   len_s  = merge->len_s;

4616:   /* send and recv matrix values */
4617:   /*-----------------------------*/
4618:   PetscObjectGetNewTag((PetscObject)mpimat,&taga);
4619:   PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);

4621:   PetscMalloc1(merge->nsend+1,&s_waits);
4622:   for (proc=0,k=0; proc<size; proc++) {
4623:     if (!len_s[proc]) continue;
4624:     i    = owners[proc];
4625:     MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
4626:     k++;
4627:   }

4629:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
4630:   if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}
4631:   PetscFree(status);

4633:   PetscFree(s_waits);
4634:   PetscFree(r_waits);

4636:   /* insert mat values of mpimat */
4637:   /*----------------------------*/
4638:   PetscMalloc1(N,&ba_i);
4639:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextai);

4641:   for (k=0; k<merge->nrecv; k++) {
4642:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4643:     nrows       = *(buf_ri_k[k]);
4644:     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
4645:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4646:   }

4648:   /* set values of ba */
4649:   m = merge->rowmap->n;
4650:   for (i=0; i<m; i++) {
4651:     arow = owners[rank] + i;
4652:     bj_i = bj+bi[i];  /* col indices of the i-th row of mpimat */
4653:     bnzi = bi[i+1] - bi[i];
4654:     PetscMemzero(ba_i,bnzi*sizeof(PetscScalar));

4656:     /* add local non-zero vals of this proc's seqmat into ba */
4657:     anzi   = ai[arow+1] - ai[arow];
4658:     aj     = a->j + ai[arow];
4659:     aa     = a->a + ai[arow];
4660:     nextaj = 0;
4661:     for (j=0; nextaj<anzi; j++) {
4662:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4663:         ba_i[j] += aa[nextaj++];
4664:       }
4665:     }

4667:     /* add received vals into ba */
4668:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4669:       /* i-th row */
4670:       if (i == *nextrow[k]) {
4671:         anzi   = *(nextai[k]+1) - *nextai[k];
4672:         aj     = buf_rj[k] + *(nextai[k]);
4673:         aa     = abuf_r[k] + *(nextai[k]);
4674:         nextaj = 0;
4675:         for (j=0; nextaj<anzi; j++) {
4676:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4677:             ba_i[j] += aa[nextaj++];
4678:           }
4679:         }
4680:         nextrow[k]++; nextai[k]++;
4681:       }
4682:     }
4683:     MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);
4684:   }
4685:   MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);
4686:   MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);

4688:   PetscFree(abuf_r[0]);
4689:   PetscFree(abuf_r);
4690:   PetscFree(ba_i);
4691:   PetscFree3(buf_ri_k,nextrow,nextai);
4692:   PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);
4693:   return(0);
4694: }

4696: PetscErrorCode  MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
4697: {
4698:   PetscErrorCode      ierr;
4699:   Mat                 B_mpi;
4700:   Mat_SeqAIJ          *a=(Mat_SeqAIJ*)seqmat->data;
4701:   PetscMPIInt         size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
4702:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
4703:   PetscInt            M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
4704:   PetscInt            len,proc,*dnz,*onz,bs,cbs;
4705:   PetscInt            k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
4706:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
4707:   MPI_Request         *si_waits,*sj_waits,*ri_waits,*rj_waits;
4708:   MPI_Status          *status;
4709:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
4710:   PetscBT             lnkbt;
4711:   Mat_Merge_SeqsToMPI *merge;
4712:   PetscContainer      container;

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

4717:   /* make sure it is a PETSc comm */
4718:   PetscCommDuplicate(comm,&comm,NULL);
4719:   MPI_Comm_size(comm,&size);
4720:   MPI_Comm_rank(comm,&rank);

4722:   PetscNew(&merge);
4723:   PetscMalloc1(size,&status);

4725:   /* determine row ownership */
4726:   /*---------------------------------------------------------*/
4727:   PetscLayoutCreate(comm,&merge->rowmap);
4728:   PetscLayoutSetLocalSize(merge->rowmap,m);
4729:   PetscLayoutSetSize(merge->rowmap,M);
4730:   PetscLayoutSetBlockSize(merge->rowmap,1);
4731:   PetscLayoutSetUp(merge->rowmap);
4732:   PetscMalloc1(size,&len_si);
4733:   PetscMalloc1(size,&merge->len_s);

4735:   m      = merge->rowmap->n;
4736:   owners = merge->rowmap->range;

4738:   /* determine the number of messages to send, their lengths */
4739:   /*---------------------------------------------------------*/
4740:   len_s = merge->len_s;

4742:   len          = 0; /* length of buf_si[] */
4743:   merge->nsend = 0;
4744:   for (proc=0; proc<size; proc++) {
4745:     len_si[proc] = 0;
4746:     if (proc == rank) {
4747:       len_s[proc] = 0;
4748:     } else {
4749:       len_si[proc] = owners[proc+1] - owners[proc] + 1;
4750:       len_s[proc]  = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
4751:     }
4752:     if (len_s[proc]) {
4753:       merge->nsend++;
4754:       nrows = 0;
4755:       for (i=owners[proc]; i<owners[proc+1]; i++) {
4756:         if (ai[i+1] > ai[i]) nrows++;
4757:       }
4758:       len_si[proc] = 2*(nrows+1);
4759:       len         += len_si[proc];
4760:     }
4761:   }

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

4768:   /* post the Irecv of j-structure */
4769:   /*-------------------------------*/
4770:   PetscCommGetNewTag(comm,&tagj);
4771:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);

4773:   /* post the Isend of j-structure */
4774:   /*--------------------------------*/
4775:   PetscMalloc2(merge->nsend,&si_waits,merge->nsend,&sj_waits);

4777:   for (proc=0, k=0; proc<size; proc++) {
4778:     if (!len_s[proc]) continue;
4779:     i    = owners[proc];
4780:     MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);
4781:     k++;
4782:   }

4784:   /* receives and sends of j-structure are complete */
4785:   /*------------------------------------------------*/
4786:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,rj_waits,status);}
4787:   if (merge->nsend) {MPI_Waitall(merge->nsend,sj_waits,status);}

4789:   /* send and recv i-structure */
4790:   /*---------------------------*/
4791:   PetscCommGetNewTag(comm,&tagi);
4792:   PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);

4794:   PetscMalloc1(len+1,&buf_s);
4795:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
4796:   for (proc=0,k=0; proc<size; proc++) {
4797:     if (!len_s[proc]) continue;
4798:     /* form outgoing message for i-structure:
4799:          buf_si[0]:                 nrows to be sent
4800:                [1:nrows]:           row index (global)
4801:                [nrows+1:2*nrows+1]: i-structure index
4802:     */
4803:     /*-------------------------------------------*/
4804:     nrows       = len_si[proc]/2 - 1;
4805:     buf_si_i    = buf_si + nrows+1;
4806:     buf_si[0]   = nrows;
4807:     buf_si_i[0] = 0;
4808:     nrows       = 0;
4809:     for (i=owners[proc]; i<owners[proc+1]; i++) {
4810:       anzi = ai[i+1] - ai[i];
4811:       if (anzi) {
4812:         buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
4813:         buf_si[nrows+1]   = i-owners[proc]; /* local row index */
4814:         nrows++;
4815:       }
4816:     }
4817:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);
4818:     k++;
4819:     buf_si += len_si[proc];
4820:   }

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

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

4830:   PetscFree(len_si);
4831:   PetscFree(len_ri);
4832:   PetscFree(rj_waits);
4833:   PetscFree2(si_waits,sj_waits);
4834:   PetscFree(ri_waits);
4835:   PetscFree(buf_s);
4836:   PetscFree(status);

4838:   /* compute a local seq matrix in each processor */
4839:   /*----------------------------------------------*/
4840:   /* allocate bi array and free space for accumulating nonzero column info */
4841:   PetscMalloc1(m+1,&bi);
4842:   bi[0] = 0;

4844:   /* create and initialize a linked list */
4845:   nlnk = N+1;
4846:   PetscLLCreate(N,N,nlnk,lnk,lnkbt);

4848:   /* initial FreeSpace size is 2*(num of local nnz(seqmat)) */
4849:   len  = ai[owners[rank+1]] - ai[owners[rank]];
4850:   PetscFreeSpaceGet(PetscIntMultTruncate(2,len)+1,&free_space);

4852:   current_space = free_space;

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

4857:   for (k=0; k<merge->nrecv; k++) {
4858:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4859:     nrows       = *buf_ri_k[k];
4860:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
4861:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4862:   }

4864:   MatPreallocateInitialize(comm,m,n,dnz,onz);
4865:   len  = 0;
4866:   for (i=0; i<m; i++) {
4867:     bnzi = 0;
4868:     /* add local non-zero cols of this proc's seqmat into lnk */
4869:     arow  = owners[rank] + i;
4870:     anzi  = ai[arow+1] - ai[arow];
4871:     aj    = a->j + ai[arow];
4872:     PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4873:     bnzi += nlnk;
4874:     /* add received col data into lnk */
4875:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4876:       if (i == *nextrow[k]) { /* i-th row */
4877:         anzi  = *(nextai[k]+1) - *nextai[k];
4878:         aj    = buf_rj[k] + *nextai[k];
4879:         PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4880:         bnzi += nlnk;
4881:         nextrow[k]++; nextai[k]++;
4882:       }
4883:     }
4884:     if (len < bnzi) len = bnzi;  /* =max(bnzi) */

4886:     /* if free space is not available, make more free space */
4887:     if (current_space->local_remaining<bnzi) {
4888:       PetscFreeSpaceGet(PetscIntSumTruncate(bnzi,current_space->total_array_size),&current_space);
4889:       nspacedouble++;
4890:     }
4891:     /* copy data into free space, then initialize lnk */
4892:     PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);
4893:     MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);

4895:     current_space->array           += bnzi;
4896:     current_space->local_used      += bnzi;
4897:     current_space->local_remaining -= bnzi;

4899:     bi[i+1] = bi[i] + bnzi;
4900:   }

4902:   PetscFree3(buf_ri_k,nextrow,nextai);

4904:   PetscMalloc1(bi[m]+1,&bj);
4905:   PetscFreeSpaceContiguous(&free_space,bj);
4906:   PetscLLDestroy(lnk,lnkbt);

4908:   /* create symbolic parallel matrix B_mpi */
4909:   /*---------------------------------------*/
4910:   MatGetBlockSizes(seqmat,&bs,&cbs);
4911:   MatCreate(comm,&B_mpi);
4912:   if (n==PETSC_DECIDE) {
4913:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);
4914:   } else {
4915:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4916:   }
4917:   MatSetBlockSizes(B_mpi,bs,cbs);
4918:   MatSetType(B_mpi,MATMPIAIJ);
4919:   MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);
4920:   MatPreallocateFinalize(dnz,onz);
4921:   MatSetOption(B_mpi,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

4923:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
4924:   B_mpi->assembled    = PETSC_FALSE;
4925:   B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
4926:   merge->bi           = bi;
4927:   merge->bj           = bj;
4928:   merge->buf_ri       = buf_ri;
4929:   merge->buf_rj       = buf_rj;
4930:   merge->coi          = NULL;
4931:   merge->coj          = NULL;
4932:   merge->owners_co    = NULL;

4934:   PetscCommDestroy(&comm);

4936:   /* attach the supporting struct to B_mpi for reuse */
4937:   PetscContainerCreate(PETSC_COMM_SELF,&container);
4938:   PetscContainerSetPointer(container,merge);
4939:   PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);
4940:   PetscContainerDestroy(&container);
4941:   *mpimat = B_mpi;

4943:   PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);
4944:   return(0);
4945: }

4947: /*@C
4948:       MatCreateMPIAIJSumSeqAIJ - Creates a MATMPIAIJ matrix by adding sequential
4949:                  matrices from each processor

4951:     Collective on MPI_Comm

4953:    Input Parameters:
4954: +    comm - the communicators the parallel matrix will live on
4955: .    seqmat - the input sequential matrices
4956: .    m - number of local rows (or PETSC_DECIDE)
4957: .    n - number of local columns (or PETSC_DECIDE)
4958: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4960:    Output Parameter:
4961: .    mpimat - the parallel matrix generated

4963:     Level: advanced

4965:    Notes:
4966:      The dimensions of the sequential matrix in each processor MUST be the same.
4967:      The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
4968:      destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
4969: @*/
4970: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
4971: {
4973:   PetscMPIInt    size;

4976:   MPI_Comm_size(comm,&size);
4977:   if (size == 1) {
4978:     PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4979:     if (scall == MAT_INITIAL_MATRIX) {
4980:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
4981:     } else {
4982:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
4983:     }
4984:     PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4985:     return(0);
4986:   }
4987:   PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4988:   if (scall == MAT_INITIAL_MATRIX) {
4989:     MatCreateMPIAIJSumSeqAIJSymbolic(comm,seqmat,m,n,mpimat);
4990:   }
4991:   MatCreateMPIAIJSumSeqAIJNumeric(seqmat,*mpimat);
4992:   PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4993:   return(0);
4994: }

4996: /*@
4997:      MatMPIAIJGetLocalMat - Creates a SeqAIJ from a MATMPIAIJ matrix by taking all its local rows and putting them into a sequential matrix with
4998:           mlocal rows and n columns. Where mlocal is the row count obtained with MatGetLocalSize() and n is the global column count obtained
4999:           with MatGetSize()

5001:     Not Collective

5003:    Input Parameters:
5004: +    A - the matrix
5005: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5007:    Output Parameter:
5008: .    A_loc - the local sequential matrix generated

5010:     Level: developer

5012: .seealso: MatGetOwnershipRange(), MatMPIAIJGetLocalMatCondensed()

5014: @*/
5015: PetscErrorCode MatMPIAIJGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
5016: {
5018:   Mat_MPIAIJ     *mpimat=(Mat_MPIAIJ*)A->data;
5019:   Mat_SeqAIJ     *mat,*a,*b;
5020:   PetscInt       *ai,*aj,*bi,*bj,*cmap=mpimat->garray;
5021:   MatScalar      *aa,*ba,*cam;
5022:   PetscScalar    *ca;
5023:   PetscInt       am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
5024:   PetscInt       *ci,*cj,col,ncols_d,ncols_o,jo;
5025:   PetscBool      match;
5026:   MPI_Comm       comm;
5027:   PetscMPIInt    size;

5030:   PetscStrbeginswith(((PetscObject)A)->type_name,MATMPIAIJ,&match);
5031:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
5032:   PetscObjectGetComm((PetscObject)A,&comm);
5033:   MPI_Comm_size(comm,&size);
5034:   if (size == 1 && scall == MAT_REUSE_MATRIX) return(0);

5036:   PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);
5037:   a = (Mat_SeqAIJ*)(mpimat->A)->data;
5038:   b = (Mat_SeqAIJ*)(mpimat->B)->data;
5039:   ai = a->i; aj = a->j; bi = b->i; bj = b->j;
5040:   aa = a->a; ba = b->a;
5041:   if (scall == MAT_INITIAL_MATRIX) {
5042:     if (size == 1) {
5043:       MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ai,aj,aa,A_loc);
5044:       return(0);
5045:     }

5047:     PetscMalloc1(1+am,&ci);
5048:     ci[0] = 0;
5049:     for (i=0; i<am; i++) {
5050:       ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
5051:     }
5052:     PetscMalloc1(1+ci[am],&cj);
5053:     PetscMalloc1(1+ci[am],&ca);
5054:     k    = 0;
5055:     for (i=0; i<am; i++) {
5056:       ncols_o = bi[i+1] - bi[i];
5057:       ncols_d = ai[i+1] - ai[i];
5058:       /* off-diagonal portion of A */
5059:       for (jo=0; jo<ncols_o; jo++) {
5060:         col = cmap[*bj];
5061:         if (col >= cstart) break;
5062:         cj[k]   = col; bj++;
5063:         ca[k++] = *ba++;
5064:       }
5065:       /* diagonal portion of A */
5066:       for (j=0; j<ncols_d; j++) {
5067:         cj[k]   = cstart + *aj++;
5068:         ca[k++] = *aa++;
5069:       }
5070:       /* off-diagonal portion of A */
5071:       for (j=jo; j<ncols_o; j++) {
5072:         cj[k]   = cmap[*bj++];
5073:         ca[k++] = *ba++;
5074:       }
5075:     }
5076:     /* put together the new matrix */
5077:     MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);
5078:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5079:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5080:     mat          = (Mat_SeqAIJ*)(*A_loc)->data;
5081:     mat->free_a  = PETSC_TRUE;
5082:     mat->free_ij = PETSC_TRUE;
5083:     mat->nonew   = 0;
5084:   } else if (scall == MAT_REUSE_MATRIX) {
5085:     mat=(Mat_SeqAIJ*)(*A_loc)->data;
5086:     ci = mat->i; cj = mat->j; cam = mat->a;
5087:     for (i=0; i<am; i++) {
5088:       /* off-diagonal portion of A */
5089:       ncols_o = bi[i+1] - bi[i];
5090:       for (jo=0; jo<ncols_o; jo++) {
5091:         col = cmap[*bj];
5092:         if (col >= cstart) break;
5093:         *cam++ = *ba++; bj++;
5094:       }
5095:       /* diagonal portion of A */
5096:       ncols_d = ai[i+1] - ai[i];
5097:       for (j=0; j<ncols_d; j++) *cam++ = *aa++;
5098:       /* off-diagonal portion of A */
5099:       for (j=jo; j<ncols_o; j++) {
5100:         *cam++ = *ba++; bj++;
5101:       }
5102:     }
5103:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
5104:   PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);
5105:   return(0);
5106: }

5108: /*@C
5109:      MatMPIAIJGetLocalMatCondensed - Creates a SeqAIJ matrix from an MATMPIAIJ matrix by taking all its local rows and NON-ZERO columns

5111:     Not Collective

5113:    Input Parameters:
5114: +    A - the matrix
5115: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5116: -    row, col - index sets of rows and columns to extract (or NULL)

5118:    Output Parameter:
5119: .    A_loc - the local sequential matrix generated

5121:     Level: developer

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

5125: @*/
5126: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
5127: {
5128:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5130:   PetscInt       i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
5131:   IS             isrowa,iscola;
5132:   Mat            *aloc;
5133:   PetscBool      match;

5136:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
5137:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
5138:   PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);
5139:   if (!row) {
5140:     start = A->rmap->rstart; end = A->rmap->rend;
5141:     ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);
5142:   } else {
5143:     isrowa = *row;
5144:   }
5145:   if (!col) {
5146:     start = A->cmap->rstart;
5147:     cmap  = a->garray;
5148:     nzA   = a->A->cmap->n;
5149:     nzB   = a->B->cmap->n;
5150:     PetscMalloc1(nzA+nzB, &idx);
5151:     ncols = 0;
5152:     for (i=0; i<nzB; i++) {
5153:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5154:       else break;
5155:     }
5156:     imark = i;
5157:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;
5158:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
5159:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&iscola);
5160:   } else {
5161:     iscola = *col;
5162:   }
5163:   if (scall != MAT_INITIAL_MATRIX) {
5164:     PetscMalloc1(1,&aloc);
5165:     aloc[0] = *A_loc;
5166:   }
5167:   MatCreateSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);
5168:   if (!col) { /* attach global id of condensed columns */
5169:     PetscObjectCompose((PetscObject)aloc[0],"_petsc_GetLocalMatCondensed_iscol",(PetscObject)iscola);
5170:   }
5171:   *A_loc = aloc[0];
5172:   PetscFree(aloc);
5173:   if (!row) {
5174:     ISDestroy(&isrowa);
5175:   }
5176:   if (!col) {
5177:     ISDestroy(&iscola);
5178:   }
5179:   PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);
5180:   return(0);
5181: }

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

5186:     Collective on Mat

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

5193:    Output Parameter:
5194: +    rowb, colb - index sets of rows and columns of B to extract
5195: -    B_seq - the sequential matrix generated

5197:     Level: developer

5199: @*/
5200: PetscErrorCode MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,Mat *B_seq)
5201: {
5202:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5204:   PetscInt       *idx,i,start,ncols,nzA,nzB,*cmap,imark;
5205:   IS             isrowb,iscolb;
5206:   Mat            *bseq=NULL;

5209:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5210:     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);
5211:   }
5212:   PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);

5214:   if (scall == MAT_INITIAL_MATRIX) {
5215:     start = A->cmap->rstart;
5216:     cmap  = a->garray;
5217:     nzA   = a->A->cmap->n;
5218:     nzB   = a->B->cmap->n;
5219:     PetscMalloc1(nzA+nzB, &idx);
5220:     ncols = 0;
5221:     for (i=0; i<nzB; i++) {  /* row < local row index */
5222:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5223:       else break;
5224:     }
5225:     imark = i;
5226:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;  /* local rows */
5227:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5228:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&isrowb);
5229:     ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);
5230:   } else {
5231:     if (!rowb || !colb) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5232:     isrowb  = *rowb; iscolb = *colb;
5233:     PetscMalloc1(1,&bseq);
5234:     bseq[0] = *B_seq;
5235:   }
5236:   MatCreateSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);
5237:   *B_seq = bseq[0];
5238:   PetscFree(bseq);
5239:   if (!rowb) {
5240:     ISDestroy(&isrowb);
5241:   } else {
5242:     *rowb = isrowb;
5243:   }
5244:   if (!colb) {
5245:     ISDestroy(&iscolb);
5246:   } else {
5247:     *colb = iscolb;
5248:   }
5249:   PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);
5250:   return(0);
5251: }

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

5257:     Collective on Mat

5259:    Input Parameters:
5260: +    A,B - the matrices in mpiaij format
5261: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

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

5269:     Developer Notes: This directly accesses information inside the VecScatter associated with the matrix-vector product
5270:      for this matrix. This is not desirable..

5272:     Level: developer

5274: */
5275: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscInt **startsj_s,PetscInt **startsj_r,MatScalar **bufa_ptr,Mat *B_oth)
5276: {
5277:   PetscErrorCode         ierr;
5278:   Mat_MPIAIJ             *a=(Mat_MPIAIJ*)A->data;
5279:   Mat_SeqAIJ             *b_oth;
5280:   VecScatter             ctx;
5281:   MPI_Comm               comm;
5282:   const PetscMPIInt      *rprocs,*sprocs;
5283:   const PetscInt         *srow,*rstarts,*sstarts;
5284:   PetscInt               *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj,*rvalues=NULL,*svalues=NULL,*cols,sbs,rbs;
5285:   PetscInt               i,j,k=0,l,ll,nrecvs,nsends,nrows,*rstartsj = 0,*sstartsj,len;
5286:   PetscScalar              *b_otha,*bufa,*bufA,*vals;
5287:   MPI_Request            *rwaits = NULL,*swaits = NULL;
5288:   MPI_Status             rstatus;
5289:   PetscMPIInt            jj,size,tag,rank,nsends_mpi,nrecvs_mpi;

5292:   PetscObjectGetComm((PetscObject)A,&comm);
5293:   MPI_Comm_size(comm,&size);

5295:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5296:     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);
5297:   }
5298:   PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);
5299:   MPI_Comm_rank(comm,&rank);

5301:   if (size == 1) {
5302:     startsj_s = NULL;
5303:     bufa_ptr  = NULL;
5304:     *B_oth    = NULL;
5305:     return(0);
5306:   }

5308:   ctx = a->Mvctx;
5309:   tag = ((PetscObject)ctx)->tag;

5311:   if (ctx->inuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE," Scatter ctx already in use");
5312:   VecScatterGetRemote_Private(ctx,PETSC_TRUE/*send*/,&nsends,&sstarts,&srow,&sprocs,&sbs);
5313:   /* rprocs[] must be ordered so that indices received from them are ordered in rvalues[], which is key to algorithms used in this subroutine */
5314:   VecScatterGetRemoteOrdered_Private(ctx,PETSC_FALSE/*recv*/,&nrecvs,&rstarts,NULL/*indices not needed*/,&rprocs,&rbs);
5315:   PetscMPIIntCast(nsends,&nsends_mpi);
5316:   PetscMPIIntCast(nrecvs,&nrecvs_mpi);
5317:   PetscMalloc2(nrecvs,&rwaits,nsends,&swaits);

5319:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5320:   if (scall == MAT_INITIAL_MATRIX) {
5321:     /* i-array */
5322:     /*---------*/
5323:     /*  post receives */
5324:     if (nrecvs) {PetscMalloc1(rbs*(rstarts[nrecvs] - rstarts[0]),&rvalues);} /* rstarts can be NULL when nrecvs=0 */
5325:     for (i=0; i<nrecvs; i++) {
5326:       rowlen = rvalues + rstarts[i]*rbs;
5327:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
5328:       MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5329:     }

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

5334:     sstartsj[0] = 0;
5335:     rstartsj[0] = 0;
5336:     len         = 0; /* total length of j or a array to be sent */
5337:     if (nsends) {
5338:       k    = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5339:       PetscMalloc1(sbs*(sstarts[nsends]-sstarts[0]),&svalues);
5340:     }
5341:     for (i=0; i<nsends; i++) {
5342:       rowlen = svalues + (sstarts[i]-sstarts[0])*sbs;
5343:       nrows  = sstarts[i+1]-sstarts[i]; /* num of block rows */
5344:       for (j=0; j<nrows; j++) {
5345:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5346:         for (l=0; l<sbs; l++) {
5347:           MatGetRow_MPIAIJ(B,row+l,&ncols,NULL,NULL); /* rowlength */

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

5351:           len += ncols;
5352:           MatRestoreRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);
5353:         }
5354:         k++;
5355:       }
5356:       MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);

5358:       sstartsj[i+1] = len;  /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5359:     }
5360:     /* recvs and sends of i-array are completed */
5361:     i = nrecvs;
5362:     while (i--) {
5363:       MPI_Waitany(nrecvs_mpi,rwaits,&jj,&rstatus);
5364:     }
5365:     if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}
5366:     PetscFree(svalues);

5368:     /* allocate buffers for sending j and a arrays */
5369:     PetscMalloc1(len+1,&bufj);
5370:     PetscMalloc1(len+1,&bufa);

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

5375:     b_othi[0] = 0;
5376:     len       = 0; /* total length of j or a array to be received */
5377:     k         = 0;
5378:     for (i=0; i<nrecvs; i++) {
5379:       rowlen = rvalues + (rstarts[i]-rstarts[0])*rbs;
5380:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of rows to be received */
5381:       for (j=0; j<nrows; j++) {
5382:         b_othi[k+1] = b_othi[k] + rowlen[j];
5383:         PetscIntSumError(rowlen[j],len,&len);
5384:         k++;
5385:       }
5386:       rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5387:     }
5388:     PetscFree(rvalues);

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

5394:     /* j-array */
5395:     /*---------*/
5396:     /*  post receives of j-array */
5397:     for (i=0; i<nrecvs; i++) {
5398:       nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5399:       MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5400:     }

5402:     /* pack the outgoing message j-array */
5403:     if (nsends) k = sstarts[0];
5404:     for (i=0; i<nsends; i++) {
5405:       nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5406:       bufJ  = bufj+sstartsj[i];
5407:       for (j=0; j<nrows; j++) {
5408:         row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5409:         for (ll=0; ll<sbs; ll++) {
5410:           MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5411:           for (l=0; l<ncols; l++) {
5412:             *bufJ++ = cols[l];
5413:           }
5414:           MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5415:         }
5416:       }
5417:       MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);
5418:     }

5420:     /* recvs and sends of j-array are completed */
5421:     i = nrecvs;
5422:     while (i--) {
5423:       MPI_Waitany(nrecvs_mpi,rwaits,&jj,&rstatus);
5424:     }
5425:     if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}
5426:   } else if (scall == MAT_REUSE_MATRIX) {
5427:     sstartsj = *startsj_s;
5428:     rstartsj = *startsj_r;
5429:     bufa     = *bufa_ptr;
5430:     b_oth    = (Mat_SeqAIJ*)(*B_oth)->data;
5431:     b_otha   = b_oth->a;
5432:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");

5434:   /* a-array */
5435:   /*---------*/
5436:   /*  post receives of a-array */
5437:   for (i=0; i<nrecvs; i++) {
5438:     nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5439:     MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
5440:   }

5442:   /* pack the outgoing message a-array */
5443:   if (nsends) k = sstarts[0];
5444:   for (i=0; i<nsends; i++) {
5445:     nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5446:     bufA  = bufa+sstartsj[i];
5447:     for (j=0; j<nrows; j++) {
5448:       row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5449:       for (ll=0; ll<sbs; ll++) {
5450:         MatGetRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5451:         for (l=0; l<ncols; l++) {
5452:           *bufA++ = vals[l];
5453:         }
5454:         MatRestoreRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5455:       }
5456:     }
5457:     MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
5458:   }
5459:   /* recvs and sends of a-array are completed */
5460:   i = nrecvs;
5461:   while (i--) {
5462:     MPI_Waitany(nrecvs_mpi,rwaits,&jj,&rstatus);
5463:   }
5464:   if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}
5465:   PetscFree2(rwaits,swaits);

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

5471:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5472:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5473:     b_oth          = (Mat_SeqAIJ*)(*B_oth)->data;
5474:     b_oth->free_a  = PETSC_TRUE;
5475:     b_oth->free_ij = PETSC_TRUE;
5476:     b_oth->nonew   = 0;

5478:     PetscFree(bufj);
5479:     if (!startsj_s || !bufa_ptr) {
5480:       PetscFree2(sstartsj,rstartsj);
5481:       PetscFree(bufa_ptr);
5482:     } else {
5483:       *startsj_s = sstartsj;
5484:       *startsj_r = rstartsj;
5485:       *bufa_ptr  = bufa;
5486:     }
5487:   }

5489:   VecScatterRestoreRemote_Private(ctx,PETSC_TRUE,&nsends,&sstarts,&srow,&sprocs,&sbs);
5490:   VecScatterRestoreRemoteOrdered_Private(ctx,PETSC_FALSE,&nrecvs,&rstarts,NULL,&rprocs,&rbs);
5491:   PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);
5492:   return(0);
5493: }

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

5498:   Not Collective

5500:   Input Parameters:
5501: . A - The matrix in mpiaij format

5503:   Output Parameter:
5504: + lvec - The local vector holding off-process values from the argument to a matrix-vector product
5505: . colmap - A map from global column index to local index into lvec
5506: - multScatter - A scatter from the argument of a matrix-vector product to lvec

5508:   Level: developer

5510: @*/
5511: #if defined(PETSC_USE_CTABLE)
5512: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
5513: #else
5514: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
5515: #endif
5516: {
5517:   Mat_MPIAIJ *a;

5524:   a = (Mat_MPIAIJ*) A->data;
5525:   if (lvec) *lvec = a->lvec;
5526:   if (colmap) *colmap = a->colmap;
5527:   if (multScatter) *multScatter = a->Mvctx;
5528:   return(0);
5529: }

5531: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat,MatType,MatReuse,Mat*);
5532: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat,MatType,MatReuse,Mat*);
5533: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat,MatType,MatReuse,Mat*);
5534: #if defined(PETSC_HAVE_MKL_SPARSE)
5535: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat,MatType,MatReuse,Mat*);
5536: #endif
5537: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat,MatType,MatReuse,Mat*);
5538: #if defined(PETSC_HAVE_ELEMENTAL)
5539: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
5540: #endif
5541: #if defined(PETSC_HAVE_HYPRE)
5542: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat,MatType,MatReuse,Mat*);
5543: PETSC_INTERN PetscErrorCode MatMatMatMult_Transpose_AIJ_AIJ(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
5544: #endif
5545: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat,MatType,MatReuse,Mat*);
5546: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat,MatType,MatReuse,Mat*);
5547: PETSC_INTERN PetscErrorCode MatPtAP_IS_XAIJ(Mat,Mat,MatReuse,PetscReal,Mat*);

5549: /*
5550:     Computes (B'*A')' since computing B*A directly is untenable

5552:                n                       p                          p
5553:         (              )       (              )         (                  )
5554:       m (      A       )  *  n (       B      )   =   m (         C        )
5555:         (              )       (              )         (                  )

5557: */
5558: PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
5559: {
5561:   Mat            At,Bt,Ct;

5564:   MatTranspose(A,MAT_INITIAL_MATRIX,&At);
5565:   MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);
5566:   MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);
5567:   MatDestroy(&At);
5568:   MatDestroy(&Bt);
5569:   MatTranspose(Ct,MAT_REUSE_MATRIX,&C);
5570:   MatDestroy(&Ct);
5571:   return(0);
5572: }

5574: PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
5575: {
5577:   PetscInt       m=A->rmap->n,n=B->cmap->n;
5578:   Mat            Cmat;

5581:   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);
5582:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
5583:   MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
5584:   MatSetBlockSizesFromMats(Cmat,A,B);
5585:   MatSetType(Cmat,MATMPIDENSE);
5586:   MatMPIDenseSetPreallocation(Cmat,NULL);
5587:   MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);
5588:   MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);

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

5592:   *C = Cmat;
5593:   return(0);
5594: }

5596: /* ----------------------------------------------------------------*/
5597: PETSC_INTERN PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
5598: {

5602:   if (scall == MAT_INITIAL_MATRIX) {
5603:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
5604:     MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);
5605:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
5606:   }
5607:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
5608:   MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);
5609:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
5610:   return(0);
5611: }

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

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

5619:   Level: beginner

5621: .seealso: MatCreateAIJ()
5622: M*/

5624: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
5625: {
5626:   Mat_MPIAIJ     *b;
5628:   PetscMPIInt    size;

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

5633:   PetscNewLog(B,&b);
5634:   B->data       = (void*)b;
5635:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
5636:   B->assembled  = PETSC_FALSE;
5637:   B->insertmode = NOT_SET_VALUES;
5638:   b->size       = size;

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

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

5645:   b->donotstash  = PETSC_FALSE;
5646:   b->colmap      = 0;
5647:   b->garray      = 0;
5648:   b->roworiented = PETSC_TRUE;

5650:   /* stuff used for matrix vector multiply */
5651:   b->lvec  = NULL;
5652:   b->Mvctx = NULL;

5654:   /* stuff for MatGetRow() */
5655:   b->rowindices   = 0;
5656:   b->rowvalues    = 0;
5657:   b->getrowactive = PETSC_FALSE;

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

5662:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetUseScalableIncreaseOverlap_C",MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ);
5663:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIAIJ);
5664:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIAIJ);
5665:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_MPIAIJ);
5666:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",MatMPIAIJSetPreallocation_MPIAIJ);
5667:   PetscObjectComposeFunction((PetscObject)B,"MatResetPreallocation_C",MatResetPreallocation_MPIAIJ);
5668:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",MatMPIAIJSetPreallocationCSR_MPIAIJ);
5669:   PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIAIJ);
5670:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijperm_C",MatConvert_MPIAIJ_MPIAIJPERM);
5671:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijsell_C",MatConvert_MPIAIJ_MPIAIJSELL);
5672: #if defined(PETSC_HAVE_MKL_SPARSE)
5673:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijmkl_C",MatConvert_MPIAIJ_MPIAIJMKL);
5674: #endif
5675:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijcrl_C",MatConvert_MPIAIJ_MPIAIJCRL);
5676:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisbaij_C",MatConvert_MPIAIJ_MPISBAIJ);
5677: #if defined(PETSC_HAVE_ELEMENTAL)
5678:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_elemental_C",MatConvert_MPIAIJ_Elemental);
5679: #endif
5680: #if defined(PETSC_HAVE_HYPRE)
5681:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_hypre_C",MatConvert_AIJ_HYPRE);
5682: #endif
5683:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_is_C",MatConvert_XAIJ_IS);
5684:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisell_C",MatConvert_MPIAIJ_MPISELL);
5685:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",MatMatMult_MPIDense_MPIAIJ);
5686:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",MatMatMultSymbolic_MPIDense_MPIAIJ);
5687:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",MatMatMultNumeric_MPIDense_MPIAIJ);
5688: #if defined(PETSC_HAVE_HYPRE)
5689:   PetscObjectComposeFunction((PetscObject)B,"MatMatMatMult_transpose_mpiaij_mpiaij_C",MatMatMatMult_Transpose_AIJ_AIJ);
5690: #endif
5691:   PetscObjectComposeFunction((PetscObject)B,"MatPtAP_is_mpiaij_C",MatPtAP_IS_XAIJ);
5692:   PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);
5693:   return(0);
5694: }

5696: /*@C
5697:      MatCreateMPIAIJWithSplitArrays - creates a MPI AIJ matrix using arrays that contain the "diagonal"
5698:          and "off-diagonal" part of the matrix in CSR format.

5700:    Collective on MPI_Comm

5702:    Input Parameters:
5703: +  comm - MPI communicator
5704: .  m - number of local rows (Cannot be PETSC_DECIDE)
5705: .  n - This value should be the same as the local size used in creating the
5706:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
5707:        calculated if N is given) For square matrices n is almost always m.
5708: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
5709: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
5710: .   i - row indices for "diagonal" portion of matrix; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
5711: .   j - column indices
5712: .   a - matrix values
5713: .   oi - row indices for "off-diagonal" portion of matrix; that is oi[0] = 0, oi[row] = oi[row-1] + number of elements in that row of the matrix
5714: .   oj - column indices
5715: -   oa - matrix values

5717:    Output Parameter:
5718: .   mat - the matrix

5720:    Level: advanced

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

5726:        The i and j indices are 0 based

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

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

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

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

5741: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
5742:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithArrays()
5743: @*/
5744: 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)
5745: {
5747:   Mat_MPIAIJ     *maij;

5750:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
5751:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
5752:   if (oi[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
5753:   MatCreate(comm,mat);
5754:   MatSetSizes(*mat,m,n,M,N);
5755:   MatSetType(*mat,MATMPIAIJ);
5756:   maij = (Mat_MPIAIJ*) (*mat)->data;

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

5760:   PetscLayoutSetUp((*mat)->rmap);
5761:   PetscLayoutSetUp((*mat)->cmap);

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

5766:   MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);
5767:   MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);
5768:   MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);
5769:   MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);

5771:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
5772:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
5773:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
5774:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_FALSE);
5775:   MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
5776:   return(0);
5777: }

5779: /*
5780:     Special version for direct calls from Fortran
5781: */
5782:  #include <petsc/private/fortranimpl.h>

5784: /* Change these macros so can be used in void function */
5785: #undef CHKERRQ
5786: #define CHKERRQ(ierr) CHKERRABORT(PETSC_COMM_WORLD,ierr)
5787: #undef SETERRQ2
5788: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
5789: #undef SETERRQ3
5790: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)
5791: #undef SETERRQ
5792: #define SETERRQ(c,ierr,b) CHKERRABORT(c,ierr)

5794: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5795: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
5796: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5797: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
5798: #else
5799: #endif
5800: 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)
5801: {
5802:   Mat            mat  = *mmat;
5803:   PetscInt       m    = *mm, n = *mn;
5804:   InsertMode     addv = *maddv;
5805:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
5806:   PetscScalar    value;

5809:   MatCheckPreallocated(mat,1);
5810:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;

5812: #if defined(PETSC_USE_DEBUG)
5813:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
5814: #endif
5815:   {
5816:     PetscInt  i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
5817:     PetscInt  cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
5818:     PetscBool roworiented = aij->roworiented;

5820:     /* Some Variables required in the macro */
5821:     Mat        A                 = aij->A;
5822:     Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
5823:     PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
5824:     MatScalar  *aa               = a->a;
5825:     PetscBool  ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
5826:     Mat        B                 = aij->B;
5827:     Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
5828:     PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
5829:     MatScalar  *ba               = b->a;

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

5836:     for (i=0; i<m; i++) {
5837:       if (im[i] < 0) continue;
5838: #if defined(PETSC_USE_DEBUG)
5839:       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);
5840: #endif
5841:       if (im[i] >= rstart && im[i] < rend) {
5842:         row      = im[i] - rstart;
5843:         lastcol1 = -1;
5844:         rp1      = aj + ai[row];
5845:         ap1      = aa + ai[row];
5846:         rmax1    = aimax[row];
5847:         nrow1    = ailen[row];
5848:         low1     = 0;
5849:         high1    = nrow1;
5850:         lastcol2 = -1;
5851:         rp2      = bj + bi[row];
5852:         ap2      = ba + bi[row];
5853:         rmax2    = bimax[row];
5854:         nrow2    = bilen[row];
5855:         low2     = 0;
5856:         high2    = nrow2;

5858:         for (j=0; j<n; j++) {
5859:           if (roworiented) value = v[i*n+j];
5860:           else value = v[i+j*m];
5861:           if (in[j] >= cstart && in[j] < cend) {
5862:             col = in[j] - cstart;
5863:             if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && row != col) continue;
5864:             MatSetValues_SeqAIJ_A_Private(row,col,value,addv,im[i],in[j]);
5865:           } else if (in[j] < 0) continue;
5866: #if defined(PETSC_USE_DEBUG)
5867:           /* extra brace on SETERRQ2() is required for --with-errorchecking=0 - due to the next 'else' clause */
5868:           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);}
5869: #endif
5870:           else {
5871:             if (mat->was_assembled) {
5872:               if (!aij->colmap) {
5873:                 MatCreateColmap_MPIAIJ_Private(mat);
5874:               }
5875: #if defined(PETSC_USE_CTABLE)
5876:               PetscTableFind(aij->colmap,in[j]+1,&col);
5877:               col--;
5878: #else
5879:               col = aij->colmap[in[j]] - 1;
5880: #endif
5881:               if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && row != col) continue;
5882:               if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
5883:                 MatDisAssemble_MPIAIJ(mat);
5884:                 col  =  in[j];
5885:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
5886:                 B     = aij->B;
5887:                 b     = (Mat_SeqAIJ*)B->data;
5888:                 bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
5889:                 rp2   = bj + bi[row];
5890:                 ap2   = ba + bi[row];
5891:                 rmax2 = bimax[row];
5892:                 nrow2 = bilen[row];
5893:                 low2  = 0;
5894:                 high2 = nrow2;
5895:                 bm    = aij->B->rmap->n;
5896:                 ba    = b->a;
5897:               }
5898:             } else col = in[j];
5899:             MatSetValues_SeqAIJ_B_Private(row,col,value,addv,im[i],in[j]);
5900:           }
5901:         }
5902:       } else if (!aij->donotstash) {
5903:         if (roworiented) {
5904:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5905:         } else {
5906:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5907:         }
5908:       }
5909:     }
5910:   }
5911:   PetscFunctionReturnVoid();
5912: }