Actual source code: mpiaij.c

petsc-master 2019-07-15
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:   PetscArraycpy(iis,igis,ngis);
218:   PetscArraycpy(iis+ngis,isis,nsis);
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:       PetscArrayzero(olens,m);
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:       PetscArrayzero(olens,m);
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:       PetscArrayzero(gmataa,nz);
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];                                   PetscArraycpy(ao,gmataa,nz); ao += nz; gmataa += nz;
383:       nz = Ad->i[i+1] - Ad->i[i];                   PetscArraycpy(ad,gmataa,nz); 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]; PetscArraycpy(ao,gmataa,nz); ao += nz; gmataa += nz;
387:       nz = Ad->i[i+1] - Ad->i[i];                   PetscArraycpy(ad,gmataa,nz); ad += nz; gmataa += nz;
388:     }
389:     i--;
390:     if (mat->rmap->n) {
391:       nz = Ao->i[i+1] - Ao->i[i] - ld[i];           PetscArraycpy(ao,gmataa,nz);
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:       PetscArraymove(rp1+_i+1,rp1+_i,N-_i+1);\
459:       PetscArraymove(ap1+_i+1,ap1+_i,N-_i+1);\
460:       rp1[_i] = col;  \
461:       ap1[_i] = value;  \
462:       A->nonzerostate++;\
463:       a_noinsert: ; \
464:       ailen[row] = nrow1; \
465: }

467: #define MatSetValues_SeqAIJ_B_Private(row,col,value,addv,orow,ocol) \
468:   { \
469:     if (col <= lastcol2) low2 = 0;                        \
470:     else high2 = nrow2;                                   \
471:     lastcol2 = col;                                       \
472:     while (high2-low2 > 5) {                              \
473:       t = (low2+high2)/2;                                 \
474:       if (rp2[t] > col) high2 = t;                        \
475:       else             low2  = t;                         \
476:     }                                                     \
477:     for (_i=low2; _i<high2; _i++) {                       \
478:       if (rp2[_i] > col) break;                           \
479:       if (rp2[_i] == col) {                               \
480:         if (addv == ADD_VALUES) {                         \
481:           ap2[_i] += value;                               \
482:           (void)PetscLogFlops(1.0);                       \
483:         }                                                 \
484:         else                    ap2[_i] = value;          \
485:         goto b_noinsert;                                  \
486:       }                                                   \
487:     }                                                     \
488:     if (value == 0.0 && ignorezeroentries) {low2 = 0; high2 = nrow2; goto b_noinsert;} \
489:     if (nonew == 1) {low2 = 0; high2 = nrow2; goto b_noinsert;}                        \
490:     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); \
491:     MatSeqXAIJReallocateAIJ(B,bm,1,nrow2,row,col,rmax2,ba,bi,bj,rp2,ap2,bimax,nonew,MatScalar); \
492:     N = nrow2++ - 1; b->nz++; high2++;                    \
493:     /* shift up all the later entries in this row */      \
494:     PetscArraymove(rp2+_i+1,rp2+_i,N-_i+1);\
495:     PetscArraymove(ap2+_i+1,ap2+_i,N-_i+1);\
496:     rp2[_i] = col;                                        \
497:     ap2[_i] = value;                                      \
498:     B->nonzerostate++;                                    \
499:     b_noinsert: ;                                         \
500:     bilen[row] = nrow2;                                   \
501:   }

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

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

513:   /* find size of row to the left of the diagonal part */
514:   MatGetOwnershipRange(A,&diag,0);
515:   row  = row - diag;
516:   for (l=0; l<b->i[row+1]-b->i[row]; l++) {
517:     if (garray[b->j[b->i[row]+l]] > diag) break;
518:   }
519:   PetscArraycpy(b->a+b->i[row],v,l);

521:   /* diagonal part */
522:   PetscArraycpy(a->a+a->i[row],v+l,(a->i[row+1]-a->i[row]));

524:   /* right of diagonal part */
525:   PetscArraycpy(b->a+b->i[row]+l,v+l+a->i[row+1]-a->i[row],b->i[row+1]-b->i[row]-l);
526:   return(0);
527: }

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

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

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

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

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

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

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

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

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

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

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

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

768: PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
769: {
770:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
772:   PetscInt       nstash,reallocs;

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

777:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
778:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
779:   PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
780:   return(0);
781: }

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

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

797:   if (!aij->donotstash && !mat->nooffprocentries) {
798:     while (1) {
799:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
800:       if (!flg) break;

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

812:         i = j;
813:       }
814:     }
815:     MatStashScatterEnd_Private(&mat->stash);
816:   }
817:   MatAssemblyBegin(aij->A,mode);
818:   MatAssemblyEnd(aij->A,mode);

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

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

841:   aij->rowvalues = 0;

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

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

854: PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
855: {
856:   Mat_MPIAIJ     *l = (Mat_MPIAIJ*)A->data;

860:   MatZeroEntries(l->A);
861:   MatZeroEntries(l->B);
862:   return(0);
863: }

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

875:   /* get locally owned rows */
876:   MatZeroRowsMapLocal_Private(A,N,rows,&len,&lrows);
877:   MatHasCongruentLayouts(A,&cong);
878:   /* fix right hand side if needed */
879:   if (x && b) {
880:     const PetscScalar *xx;
881:     PetscScalar       *bb;

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

891:   sA = mat->A->nonzerostate;
892:   sB = mat->B->nonzerostate;

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

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

933:   /* reduce nonzerostate */
934:   lch = (PetscBool)(sA != mat->A->nonzerostate || sB != mat->B->nonzerostate);
935:   MPIU_Allreduce(&lch,&gch,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)A));
936:   if (gch) A->nonzerostate++;
937:   return(0);
938: }

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

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

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

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

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

1057: PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
1058: {
1059:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1061:   PetscInt       nt;
1062:   VecScatter     Mvctx = a->Mvctx;

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

1068:   VecScatterBegin(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1069:   (*a->A->ops->mult)(a->A,xx,yy);
1070:   VecScatterEnd(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1071:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
1072:   return(0);
1073: }

1075: PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A,Vec bb,Vec xx)
1076: {
1077:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1081:   MatMultDiagonalBlock(a->A,bb,xx);
1082:   return(0);
1083: }

1085: PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1086: {
1087:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
1089:   VecScatter     Mvctx = a->Mvctx;

1092:   if (a->Mvctx_mpi1_flg) Mvctx = a->Mvctx_mpi1;
1093:   VecScatterBegin(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1094:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
1095:   VecScatterEnd(Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1096:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
1097:   return(0);
1098: }

1100: PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
1101: {
1102:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1106:   /* do nondiagonal part */
1107:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1108:   /* do local part */
1109:   (*a->A->ops->multtranspose)(a->A,xx,yy);
1110:   /* add partial results together */
1111:   VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1112:   VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1113:   return(0);
1114: }

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

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

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

1158: PetscErrorCode MatIsSymmetric_MPIAIJ(Mat A,PetscReal tol,PetscBool  *f)
1159: {

1163:   MatIsTranspose_MPIAIJ(A,A,tol,f);
1164:   return(0);
1165: }

1167: PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1168: {
1169:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1173:   /* do nondiagonal part */
1174:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1175:   /* do local part */
1176:   (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
1177:   /* add partial results together */
1178:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1179:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1180:   return(0);
1181: }

1183: /*
1184:   This only works correctly for square matrices where the subblock A->A is the
1185:    diagonal block
1186: */
1187: PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
1188: {
1190:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1193:   if (A->rmap->N != A->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1194:   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");
1195:   MatGetDiagonal(a->A,v);
1196:   return(0);
1197: }

1199: PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
1200: {
1201:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1205:   MatScale(a->A,aa);
1206:   MatScale(a->B,aa);
1207:   return(0);
1208: }

1210: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
1211: {
1212:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

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

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

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

1272:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1273:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1274:   nz   = A->nz + B->nz;
1275:   PetscViewerBinaryGetDescriptor(viewer,&fd);
1276:   if (!rank) {
1277:     header[0] = MAT_FILE_CLASSID;
1278:     header[1] = mat->rmap->N;
1279:     header[2] = mat->cmap->N;

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

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

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

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

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

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

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

1384:   PetscViewerBinaryGetInfoPointer(viewer,&file);
1385:   if (file) fprintf(file,"-matload_block_size %d\n",(int)PetscAbs(mat->rmap->bs));
1386:   return(0);
1387: }

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

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

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

1476:   { /* assemble the entire matrix onto first processor */
1477:     Mat A = NULL, Av;
1478:     IS  isrow,iscol;

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

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

1519: PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1520: {
1522:   PetscBool      iascii,isdraw,issocket,isbinary;

1525:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1526:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1527:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1528:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
1529:   if (iascii || isdraw || isbinary || issocket) {
1530:     MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);
1531:   }
1532:   return(0);
1533: }

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

1543:   if (flag == SOR_APPLY_UPPER) {
1544:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1545:     return(0);
1546:   }

1548:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) {
1549:     VecDuplicate(bb,&bb1);
1550:   }

1552:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1553:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1554:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1555:       its--;
1556:     }

1558:     while (its--) {
1559:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1560:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1562:       /* update rhs: bb1 = bb - B*x */
1563:       VecScale(mat->lvec,-1.0);
1564:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

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

1578:       /* update rhs: bb1 = bb - B*x */
1579:       VecScale(mat->lvec,-1.0);
1580:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

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

1594:       /* update rhs: bb1 = bb - B*x */
1595:       VecScale(mat->lvec,-1.0);
1596:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1598:       /* local sweep */
1599:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);
1600:     }
1601:   } else if (flag & SOR_EISENSTAT) {
1602:     Vec xx1;

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

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

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

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

1629:   VecDestroy(&bb1);

1631:   matin->factorerrortype = mat->A->factorerrortype;
1632:   return(0);
1633: }

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

1647:   MatGetLocalSize(A,&m,&n);
1648:   ISGetIndices(rowp,&rwant);
1649:   ISGetIndices(colp,&cwant);
1650:   PetscMalloc3(PetscMax(m,n),&work,m,&rdest,n,&cdest);

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

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

1669:   ISRestoreIndices(rowp,&rwant);
1670:   ISRestoreIndices(colp,&cwant);
1671:   MatMPIAIJGetSeqAIJ(A,&aA,&aB,&gcols);

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

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

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

1739: PetscErrorCode  MatGetGhosts_MPIAIJ(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
1740: {
1741:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1745:   MatGetSize(aij->B,NULL,nghosts);
1746:   if (ghosts) *ghosts = aij->garray;
1747:   return(0);
1748: }

1750: PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1751: {
1752:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1753:   Mat            A    = mat->A,B = mat->B;
1755:   PetscReal      isend[5],irecv[5];

1758:   info->block_size = 1.0;
1759:   MatGetInfo(A,MAT_LOCAL,info);

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

1764:   MatGetInfo(B,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;
1768:   if (flag == MAT_LOCAL) {
1769:     info->nz_used      = isend[0];
1770:     info->nz_allocated = isend[1];
1771:     info->nz_unneeded  = isend[2];
1772:     info->memory       = isend[3];
1773:     info->mallocs      = isend[4];
1774:   } else if (flag == MAT_GLOBAL_MAX) {
1775:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

1777:     info->nz_used      = irecv[0];
1778:     info->nz_allocated = irecv[1];
1779:     info->nz_unneeded  = irecv[2];
1780:     info->memory       = irecv[3];
1781:     info->mallocs      = irecv[4];
1782:   } else if (flag == MAT_GLOBAL_SUM) {
1783:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));

1785:     info->nz_used      = irecv[0];
1786:     info->nz_allocated = irecv[1];
1787:     info->nz_unneeded  = irecv[2];
1788:     info->memory       = irecv[3];
1789:     info->mallocs      = irecv[4];
1790:   }
1791:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1792:   info->fill_ratio_needed = 0;
1793:   info->factor_mallocs    = 0;
1794:   return(0);
1795: }

1797: PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscBool flg)
1798: {
1799:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1803:   switch (op) {
1804:   case MAT_NEW_NONZERO_LOCATIONS:
1805:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1806:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1807:   case MAT_KEEP_NONZERO_PATTERN:
1808:   case MAT_NEW_NONZERO_LOCATION_ERR:
1809:   case MAT_USE_INODES:
1810:   case MAT_IGNORE_ZERO_ENTRIES:
1811:     MatCheckPreallocated(A,1);
1812:     MatSetOption(a->A,op,flg);
1813:     MatSetOption(a->B,op,flg);
1814:     break;
1815:   case MAT_ROW_ORIENTED:
1816:     MatCheckPreallocated(A,1);
1817:     a->roworiented = flg;

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

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

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

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

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

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

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

1926: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1927: {
1928:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1931:   if (!aij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1932:   aij->getrowactive = PETSC_FALSE;
1933:   return(0);
1934: }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2123: PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2124: {
2125:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2129:   MatSetUnfactored(a->A);
2130:   return(0);
2131: }

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

2141:   a = matA->A; b = matA->B;
2142:   c = matB->A; d = matB->B;

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

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

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

2175: PetscErrorCode MatSetUp_MPIAIJ(Mat A)
2176: {

2180:   MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
2181:   return(0);
2182: }

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

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

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

2218:   MatAXPYGetPreallocation_MPIX_private(m,x->i,x->j,xltog,y->i,y->j,yltog,nnz);
2219:   return(0);
2220: }

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

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

2264: extern PetscErrorCode  MatConjugate_SeqAIJ(Mat);

2266: PetscErrorCode  MatConjugate_MPIAIJ(Mat mat)
2267: {
2268: #if defined(PETSC_USE_COMPLEX)
2270:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2273:   MatConjugate_SeqAIJ(aij->A);
2274:   MatConjugate_SeqAIJ(aij->B);
2275: #else
2277: #endif
2278:   return(0);
2279: }

2281: PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2282: {
2283:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2287:   MatRealPart(a->A);
2288:   MatRealPart(a->B);
2289:   return(0);
2290: }

2292: PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2293: {
2294:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2298:   MatImaginaryPart(a->A);
2299:   MatImaginaryPart(a->B);
2300:   return(0);
2301: }

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

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

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

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

2334:   VecRestoreArray(v,&va);
2335:   VecRestoreArray(vtmp,&vb);
2336:   PetscFree(idxb);
2337:   VecDestroy(&vtmp);
2338:   return(0);
2339: }

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

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

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

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

2372:   VecRestoreArray(v,&va);
2373:   VecRestoreArray(vtmp,&vb);
2374:   PetscFree(idxb);
2375:   VecDestroy(&vtmp);
2376:   return(0);
2377: }

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

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

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

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

2457: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat,Mat *newmat)
2458: {
2460:   Mat            *dummy;

2463:   MatCreateSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,&dummy);
2464:   *newmat = *dummy;
2465:   PetscFree(dummy);
2466:   return(0);
2467: }

2469: PetscErrorCode  MatInvertBlockDiagonal_MPIAIJ(Mat A,const PetscScalar **values)
2470: {
2471:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*) A->data;

2475:   MatInvertBlockDiagonal(a->A,values);
2476:   A->factorerrortype = a->A->factorerrortype;
2477:   return(0);
2478: }

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

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

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

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

2509:    Collective on Mat

2511:    Input Parameters:
2512: +    A - the matrix
2513: -    sc - PETSC_TRUE indicates use the scalable algorithm (default is not to use the scalable algorithm)

2515:  Level: advanced

2517: @*/
2518: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A,PetscBool sc)
2519: {
2520:   PetscErrorCode       ierr;

2523:   PetscTryMethod(A,"MatMPIAIJSetUseScalableIncreaseOverlap_C",(Mat,PetscBool),(A,sc));
2524:   return(0);
2525: }

2527: PetscErrorCode MatSetFromOptions_MPIAIJ(PetscOptionItems *PetscOptionsObject,Mat A)
2528: {
2529:   PetscErrorCode       ierr;
2530:   PetscBool            sc = PETSC_FALSE,flg;

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

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

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

2561: PetscErrorCode MatMissingDiagonal_MPIAIJ(Mat A,PetscBool  *missing,PetscInt *d)
2562: {
2563:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

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

2574:   }
2575:   return(0);
2576: }

2578: PetscErrorCode MatInvertVariableBlockDiagonal_MPIAIJ(Mat A,PetscInt nblocks,const PetscInt *bsizes,PetscScalar *diag)
2579: {
2580:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2584:   MatInvertVariableBlockDiagonal(a->A,nblocks,bsizes,diag);
2585:   return(0);
2586: }

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

2736: /* ----------------------------------------------------------------------------------------*/

2738: PetscErrorCode  MatStoreValues_MPIAIJ(Mat mat)
2739: {
2740:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2744:   MatStoreValues(aij->A);
2745:   MatStoreValues(aij->B);
2746:   return(0);
2747: }

2749: PetscErrorCode  MatRetrieveValues_MPIAIJ(Mat mat)
2750: {
2751:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2755:   MatRetrieveValues(aij->A);
2756:   MatRetrieveValues(aij->B);
2757:   return(0);
2758: }

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

2767:   PetscLayoutSetUp(B->rmap);
2768:   PetscLayoutSetUp(B->cmap);
2769:   b = (Mat_MPIAIJ*)B->data;

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

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

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

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

2805: PetscErrorCode MatResetPreallocation_MPIAIJ(Mat B)
2806: {
2807:   Mat_MPIAIJ     *b;

2812:   PetscLayoutSetUp(B->rmap);
2813:   PetscLayoutSetUp(B->cmap);
2814:   b = (Mat_MPIAIJ*)B->data;

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

2825:   MatResetPreallocation(b->A);
2826:   MatResetPreallocation(b->B);
2827:   B->preallocated  = PETSC_TRUE;
2828:   B->was_assembled = PETSC_FALSE;
2829:   B->assembled = PETSC_FALSE;
2830:   return(0);
2831: }

2833: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
2834: {
2835:   Mat            mat;
2836:   Mat_MPIAIJ     *a,*oldmat = (Mat_MPIAIJ*)matin->data;

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

2847:   mat->factortype   = matin->factortype;
2848:   mat->assembled    = PETSC_TRUE;
2849:   mat->insertmode   = NOT_SET_VALUES;
2850:   mat->preallocated = PETSC_TRUE;

2852:   a->size         = oldmat->size;
2853:   a->rank         = oldmat->rank;
2854:   a->donotstash   = oldmat->donotstash;
2855:   a->roworiented  = oldmat->roworiented;
2856:   a->rowindices   = 0;
2857:   a->rowvalues    = 0;
2858:   a->getrowactive = PETSC_FALSE;

2860:   PetscLayoutReference(matin->rmap,&mat->rmap);
2861:   PetscLayoutReference(matin->cmap,&mat->cmap);

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

2880:   VecDuplicate(oldmat->lvec,&a->lvec);
2881:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
2882:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
2883:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);

2885:   if (oldmat->Mvctx_mpi1) {
2886:     VecScatterCopy(oldmat->Mvctx_mpi1,&a->Mvctx_mpi1);
2887:     PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx_mpi1);
2888:   }

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

2899: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
2900: {
2901:   PetscBool      isbinary, ishdf5;

2907:   /* force binary viewer to load .info file if it has not yet done so */
2908:   PetscViewerSetUp(viewer);
2909:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
2910:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,  &ishdf5);
2911:   if (isbinary) {
2912:     MatLoad_MPIAIJ_Binary(newMat,viewer);
2913:   } else if (ishdf5) {
2914: #if defined(PETSC_HAVE_HDF5)
2915:     MatLoad_AIJ_HDF5(newMat,viewer);
2916: #else
2917:     SETERRQ(PetscObjectComm((PetscObject)newMat),PETSC_ERR_SUP,"HDF5 not supported in this build.\nPlease reconfigure using --download-hdf5");
2918: #endif
2919:   } else {
2920:     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);
2921:   }
2922:   return(0);
2923: }

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

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

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

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

2957:   /* If global sizes are set, check if they are consistent with that given in the file */
2958:   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);
2959:   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);

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

2966:   PetscMalloc1(size+1,&rowners);
2967:   MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

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

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

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

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

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

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

3034:     /* receive message of column indices*/
3035:     MPIULong_Recv(mycols,nz,MPIU_INT,0,tag,comm);
3036:   }

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

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

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

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

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

3069:   for (i=0; i<m; i++) {
3070:     ourlens[i] += offlens[i];
3071:   }

3073:   if (!rank) {
3074:     PetscMalloc1(maxnz+1,&vals);

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

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

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

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

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

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

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

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

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

3159:   *isseq = iscol_local;
3160:   return(0);
3161: }

3163: /*
3164:  Used by MatCreateSubMatrix_MPIAIJ_SameRowColDist() to avoid ISAllGather() and global size of iscol_local
3165:  (see MatCreateSubMatrix_MPIAIJ_nonscalable)

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

3193:   PetscObjectGetComm((PetscObject)mat,&comm);
3194:   ISGetLocalSize(iscol,&ncols);

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

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

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

3220:   /* Get iscol_d */
3221:   ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,iscol_d);
3222:   ISGetBlockSize(iscol,&i);
3223:   ISSetBlockSize(*iscol_d,i);

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

3233:   ISCreateGeneral(PETSC_COMM_SELF,m,idx,PETSC_OWN_POINTER,isrow_d);
3234:   ISGetBlockSize(isrow,&i);
3235:   ISSetBlockSize(*isrow_d,i);

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

3241:   VecDuplicate(lvec,&lcmap);

3243:   VecScatterBegin(Mvctx,cmap,lcmap,INSERT_VALUES,SCATTER_FORWARD);
3244:   VecScatterEnd(Mvctx,cmap,lcmap,INSERT_VALUES,SCATTER_FORWARD);

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

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

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

3267:   PetscFree(idx);
3268:   *garray = cmap1;

3270:   VecDestroy(&x);
3271:   VecDestroy(&cmap);
3272:   VecDestroy(&lcmap);
3273:   return(0);
3274: }

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

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

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

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

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

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

3311:   } else { /* call == MAT_INITIAL_MATRIX) */
3312:     const PetscInt *garray;
3313:     PetscInt        BsubN;

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

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

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

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

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

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

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

3349:       ISDestroy(&iscol_o);
3350:       ISCreateGeneral(PETSC_COMM_SELF,n,idx_new,PETSC_OWN_POINTER,&iscol_o);

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

3356:     PetscFree(garray);
3357:     *submat = M;

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

3363:     PetscObjectCompose((PetscObject)M,"iscol_d",(PetscObject)iscol_d);
3364:     ISDestroy(&iscol_d);

3366:     PetscObjectCompose((PetscObject)M,"iscol_o",(PetscObject)iscol_o);
3367:     ISDestroy(&iscol_o);
3368:   }
3369:   return(0);
3370: }

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

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

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

3421:     PetscObjectGetComm((PetscObject)mat,&comm);
3422:     MPIU_Allreduce(&sameDist,&tsameDist,2,MPIU_BOOL,MPI_LAND,comm);
3423:     sameRowDist = tsameDist[0];
3424:   }

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

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

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

3467:   ISGetLocalSize(iscol,&csize);
3468:   MatCreateSubMatrix_MPIAIJ_nonscalable(mat,isrow,iscol_local,csize,call,newmat);

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

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

3481:    Collective

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

3489:    Output Parameter:
3490: .   mat - the matrix, with input A as its local diagonal matrix
3491:    Level: advanced

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

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

3510:   MatCreate(comm,mat);
3511:   MatGetSize(A,&m,&n);
3512:   if (m != B->rmap->N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Am %D != Bm %D",m,B->rmap->N);
3513:   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);
3514:   /* remove check below; When B is created using iscol_o from ISGetSeqIS_SameColDist_Private(), its bs may not be same as A */
3515:   /* 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); */

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

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

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

3527:   PetscLayoutSetUp((*mat)->rmap);
3528:   PetscLayoutSetUp((*mat)->cmap);

3530:   /* Set A as diagonal portion of *mat */
3531:   maij->A = A;

3533:   nz = oi[m];
3534:   for (i=0; i<nz; i++) {
3535:     col   = oj[i];
3536:     oj[i] = garray[col];
3537:   }

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

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

3547:   b->singlemalloc = PETSC_FALSE; /* B arrays are shared by Bnew */
3548:   b->free_a       = PETSC_FALSE;
3549:   b->free_ij      = PETSC_FALSE;
3550:   MatDestroy(&B);

3552:   bnew->singlemalloc = PETSC_TRUE; /* arrays will be freed by MatDestroy(&Bnew) */
3553:   bnew->free_a       = PETSC_TRUE;
3554:   bnew->free_ij      = PETSC_TRUE;

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

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

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

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

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

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

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

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

3599:   } else { /* call == MAT_INITIAL_MATRIX) */
3600:     PetscBool flg;

3602:     ISGetLocalSize(iscol,&n);
3603:     ISGetSize(iscol,&Ncols);

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

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

3644:       ISCreateGeneral(PETSC_COMM_SELF,count,idx,PETSC_OWN_POINTER,&iscol_sub);
3645:       ISGetBlockSize(iscol,&cbs);
3646:       ISSetBlockSize(iscol_sub,cbs);

3648:       ISCreateGeneral(PetscObjectComm((PetscObject)iscol_local),count,cmap1,PETSC_OWN_POINTER,&iscmap);
3649:     }

3651:     /* (3) Create sequential Msub */
3652:     MatCreateSubMatrices_MPIAIJ_SingleIS_Local(mat,1,&isrow,&iscol_sub,MAT_INITIAL_MATRIX,allcolumns,&Msub);
3653:   }

3655:   ISGetLocalSize(iscol_sub,&count);
3656:   aij  = (Mat_SeqAIJ*)(Msub)->data;
3657:   ii   = aij->i;
3658:   ISGetIndices(iscmap,&cmap);

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

3667:   if (call == MAT_INITIAL_MATRIX) {
3668:     /* (4) Create parallel newmat */
3669:     PetscMPIInt    rank,size;
3670:     PetscInt       csize;

3672:     MPI_Comm_size(comm,&size);
3673:     MPI_Comm_rank(comm,&rank);

3675:     /*
3676:         Determine the number of non-zeros in the diagonal and off-diagonal
3677:         portions of the matrix in order to do correct preallocation
3678:     */

3680:     /* first get start and end of "diagonal" columns */
3681:     ISGetLocalSize(iscol,&csize);
3682:     if (csize == PETSC_DECIDE) {
3683:       ISGetSize(isrow,&mglobal);
3684:       if (mglobal == Ncols) { /* square matrix */
3685:         nlocal = m;
3686:       } else {
3687:         nlocal = Ncols/size + ((Ncols % size) > rank);
3688:       }
3689:     } else {
3690:       nlocal = csize;
3691:     }
3692:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3693:     rstart = rend - nlocal;
3694:     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);

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

3713:     ISGetBlockSize(isrow,&bs);
3714:     ISGetBlockSize(iscol,&cbs);

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

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

3736:   /* (5) Set values of Msub to *newmat */
3737:   PetscMalloc1(count,&colsub);
3738:   MatGetOwnershipRange(M,&rstart,NULL);

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

3751:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3752:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);

3754:   PetscFree(colsub);

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

3762:     PetscObjectCompose((PetscObject)(*newmat),"SubIScol",(PetscObject)iscol_sub);
3763:     ISDestroy(&iscol_sub);

3765:     PetscObjectCompose((PetscObject)(*newmat),"Subcmap",(PetscObject)iscmap);
3766:     ISDestroy(&iscmap);

3768:     if (iscol_local) {
3769:       PetscObjectCompose((PetscObject)(*newmat),"ISAllGather",(PetscObject)iscol_local);
3770:       ISDestroy(&iscol_local);
3771:     }
3772:   }
3773:   return(0);
3774: }

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

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

3796:   PetscObjectGetComm((PetscObject)mat,&comm);
3797:   MPI_Comm_rank(comm,&rank);
3798:   MPI_Comm_size(comm,&size);

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

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

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

3825:     /*
3826:         Determine the number of non-zeros in the diagonal and off-diagonal
3827:         portions of the matrix in order to do correct preallocation
3828:     */

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

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

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

3893:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3894:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
3895:   *newmat = M;

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

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

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

3916:   PetscLayoutSetUp(B->rmap);
3917:   PetscLayoutSetUp(B->cmap);
3918:   m      = B->rmap->n;
3919:   cstart = B->cmap->rstart;
3920:   cend   = B->cmap->rend;
3921:   rstart = B->rmap->rstart;

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

3925: #if defined(PETSC_USE_DEBUG)
3926:   for (i=0; i<m; i++) {
3927:     nnz = Ii[i+1]- Ii[i];
3928:     JJ  = J + Ii[i];
3929:     if (nnz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
3930:     if (nnz && (JJ[0] < 0)) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,JJ[0]);
3931:     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);
3932:   }
3933: #endif

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

3949:   for (i=0; i<m; i++) {
3950:     ii   = i + rstart;
3951:     MatSetValues_MPIAIJ(B,1,&ii,Ii[i+1] - Ii[i],J+Ii[i], v ? v + Ii[i] : NULL,INSERT_VALUES);
3952:   }
3953:   nooffprocentries    = B->nooffprocentries;
3954:   B->nooffprocentries = PETSC_TRUE;
3955:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3956:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3957:   B->nooffprocentries = nooffprocentries;

3959:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3960:   return(0);
3961: }

3963: /*@
3964:    MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
3965:    (the default parallel PETSc format).

3967:    Collective

3969:    Input Parameters:
3970: +  B - the matrix
3971: .  i - the indices into j for the start of each local row (starts with zero)
3972: .  j - the column indices for each local row (starts with zero)
3973: -  v - optional values in the matrix

3975:    Level: developer

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

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

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

3988: $        1 0 0
3989: $        2 0 3     P0
3990: $       -------
3991: $        4 5 6     P1
3992: $
3993: $     Process0 [P0]: rows_owned=[0,1]
3994: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
3995: $        j =  {0,0,2}  [size = 3]
3996: $        v =  {1,2,3}  [size = 3]
3997: $
3998: $     Process1 [P1]: rows_owned=[2]
3999: $        i =  {0,3}    [size = nrow+1  = 1+1]
4000: $        j =  {0,1,2}  [size = 3]
4001: $        v =  {4,5,6}  [size = 3]

4003: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateAIJ(), MATMPIAIJ,
4004:           MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
4005: @*/
4006: PetscErrorCode  MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
4007: {

4011:   PetscTryMethod(B,"MatMPIAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
4012:   return(0);
4013: }

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

4022:    Collective

4024:    Input Parameters:
4025: +  B - the matrix
4026: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4027:            (same value is used for all local rows)
4028: .  d_nnz - array containing the number of nonzeros in the various rows of the
4029:            DIAGONAL portion of the local submatrix (possibly different for each row)
4030:            or NULL (PETSC_NULL_INTEGER in Fortran), if d_nz is used to specify the nonzero structure.
4031:            The size of this array is equal to the number of local rows, i.e 'm'.
4032:            For matrices that will be factored, you must leave room for (and set)
4033:            the diagonal entry even if it is zero.
4034: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4035:            submatrix (same value is used for all local rows).
4036: -  o_nnz - array containing the number of nonzeros in the various rows of the
4037:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4038:            each row) or NULL (PETSC_NULL_INTEGER in Fortran), if o_nz is used to specify the nonzero
4039:            structure. The size of this array is equal to the number
4040:            of local rows, i.e 'm'.

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

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

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

4053:    The DIAGONAL portion of the local submatrix of a processor can be defined
4054:    as the submatrix which is obtained by extraction the part corresponding to
4055:    the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
4056:    first row that belongs to the processor, r2 is the last row belonging to
4057:    the this processor, and c1-c2 is range of indices of the local part of a
4058:    vector suitable for applying the matrix to.  This is an mxn matrix.  In the
4059:    common case of a square matrix, the row and column ranges are the same and
4060:    the DIAGONAL part is also square. The remaining portion of the local
4061:    submatrix (mxN) constitute the OFF-DIAGONAL portion.

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

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

4070:    Example usage:

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

4077: .vb
4078:             1  2  0  |  0  3  0  |  0  4
4079:     Proc0   0  5  6  |  7  0  0  |  8  0
4080:             9  0 10  | 11  0  0  | 12  0
4081:     -------------------------------------
4082:            13  0 14  | 15 16 17  |  0  0
4083:     Proc1   0 18  0  | 19 20 21  |  0  0
4084:             0  0  0  | 22 23  0  | 24  0
4085:     -------------------------------------
4086:     Proc2  25 26 27  |  0  0 28  | 29  0
4087:            30  0  0  | 31 32 33  |  0 34
4088: .ve

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

4092: .vb
4093:       A B C
4094:       D E F
4095:       G H I
4096: .ve

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

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

4105:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4106:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4107:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4108:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4109:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4110:    matrix, ans [DF] as another SeqAIJ matrix.

4112:    When d_nz, o_nz parameters are specified, d_nz storage elements are
4113:    allocated for every row of the local diagonal submatrix, and o_nz
4114:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4115:    One way to choose d_nz and o_nz is to use the max nonzerors per local
4116:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4117:    In this case, the values of d_nz,o_nz are:
4118: .vb
4119:      proc0 : dnz = 2, o_nz = 2
4120:      proc1 : dnz = 3, o_nz = 2
4121:      proc2 : dnz = 1, o_nz = 4
4122: .ve
4123:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4124:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4125:    for proc3. i.e we are using 12+15+10=37 storage locations to store
4126:    34 values.

4128:    When d_nnz, o_nnz parameters are specified, the storage is specified
4129:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4130:    In the above case the values for d_nnz,o_nnz are:
4131: .vb
4132:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4133:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4134:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4135: .ve
4136:    Here the space allocated is sum of all the above values i.e 34, and
4137:    hence pre-allocation is perfect.

4139:    Level: intermediate

4141: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateAIJ(), MatMPIAIJSetPreallocationCSR(),
4142:           MATMPIAIJ, MatGetInfo(), PetscSplitOwnership()
4143: @*/
4144: PetscErrorCode MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
4145: {

4151:   PetscTryMethod(B,"MatMPIAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
4152:   return(0);
4153: }

4155: /*@
4156:      MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
4157:          CSR format for the local rows.

4159:    Collective

4161:    Input Parameters:
4162: +  comm - MPI communicator
4163: .  m - number of local rows (Cannot be PETSC_DECIDE)
4164: .  n - This value should be the same as the local size used in creating the
4165:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4166:        calculated if N is given) For square matrices n is almost always m.
4167: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4168: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4169: .   i - row indices; that is i[0] = 0, i[row] = i[row-1] + number of elements in that row of the matrix
4170: .   j - column indices
4171: -   a - matrix values

4173:    Output Parameter:
4174: .   mat - the matrix

4176:    Level: intermediate

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

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

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

4189:        Once you have created the matrix you can update it with new numerical values using MatUpdateMPIAIJWithArrays

4191: $        1 0 0
4192: $        2 0 3     P0
4193: $       -------
4194: $        4 5 6     P1
4195: $
4196: $     Process0 [P0]: rows_owned=[0,1]
4197: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
4198: $        j =  {0,0,2}  [size = 3]
4199: $        v =  {1,2,3}  [size = 3]
4200: $
4201: $     Process1 [P1]: rows_owned=[2]
4202: $        i =  {0,3}    [size = nrow+1  = 1+1]
4203: $        j =  {0,1,2}  [size = 3]
4204: $        v =  {4,5,6}  [size = 3]

4206: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4207:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays(), MatUpdateMPIAIJWithArrays()
4208: @*/
4209: PetscErrorCode MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
4210: {

4214:   if (i && i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4215:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4216:   MatCreate(comm,mat);
4217:   MatSetSizes(*mat,m,n,M,N);
4218:   /* MatSetBlockSizes(M,bs,cbs); */
4219:   MatSetType(*mat,MATMPIAIJ);
4220:   MatMPIAIJSetPreallocationCSR(*mat,i,j,a);
4221:   return(0);
4222: }

4224: /*@
4225:      MatUpdateMPIAIJWithArrays - updates a MPI AIJ matrix using arrays that contain in standard
4226:          CSR format for the local rows. Only the numerical values are updated the other arrays must be identical

4228:    Collective

4230:    Input Parameters:
4231: +  mat - the matrix
4232: .  m - number of local rows (Cannot be PETSC_DECIDE)
4233: .  n - This value should be the same as the local size used in creating the
4234:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4235:        calculated if N is given) For square matrices n is almost always m.
4236: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4237: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4238: .  Ii - row indices; that is Ii[0] = 0, Ii[row] = Ii[row-1] + number of elements in that row of the matrix
4239: .  J - column indices
4240: -  v - matrix values

4242:    Level: intermediate

4244: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4245:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays(), MatUpdateMPIAIJWithArrays()
4246: @*/
4247: PetscErrorCode MatUpdateMPIAIJWithArrays(Mat mat,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
4248: {
4250:   PetscInt       cstart,nnz,i,j;
4251:   PetscInt       *ld;
4252:   PetscBool      nooffprocentries;
4253:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ*)mat->data;
4254:   Mat_SeqAIJ     *Ad  = (Mat_SeqAIJ*)Aij->A->data, *Ao  = (Mat_SeqAIJ*)Aij->B->data;
4255:   PetscScalar    *ad = Ad->a, *ao = Ao->a;
4256:   const PetscInt *Adi = Ad->i;
4257:   PetscInt       ldi,Iii,md;

4260:   if (Ii[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4261:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4262:   if (m != mat->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local number of rows cannot change from call to MatUpdateMPIAIJWithArrays()");
4263:   if (n != mat->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local number of columns cannot change from call to MatUpdateMPIAIJWithArrays()");

4265:   cstart = mat->cmap->rstart;
4266:   if (!Aij->ld) {
4267:     /* count number of entries below block diagonal */
4268:     PetscCalloc1(m,&ld);
4269:     Aij->ld = ld;
4270:     for (i=0; i<m; i++) {
4271:       nnz  = Ii[i+1]- Ii[i];
4272:       j     = 0;
4273:       while  (J[j] < cstart && j < nnz) {j++;}
4274:       J    += nnz;
4275:       ld[i] = j;
4276:     }
4277:   } else {
4278:     ld = Aij->ld;
4279:   }

4281:   for (i=0; i<m; i++) {
4282:     nnz  = Ii[i+1]- Ii[i];
4283:     Iii  = Ii[i];
4284:     ldi  = ld[i];
4285:     md   = Adi[i+1]-Adi[i];
4286:     PetscArraycpy(ao,v + Iii,ldi);
4287:     PetscArraycpy(ad,v + Iii + ldi,md);
4288:     PetscArraycpy(ao + ldi,v + Iii + ldi + md,nnz - ldi - md);
4289:     ad  += md;
4290:     ao  += nnz - md;
4291:   }
4292:   nooffprocentries      = mat->nooffprocentries;
4293:   mat->nooffprocentries = PETSC_TRUE;
4294:   PetscObjectStateIncrease((PetscObject)Aij->A);
4295:   PetscObjectStateIncrease((PetscObject)Aij->B);
4296:   PetscObjectStateIncrease((PetscObject)mat);
4297:   MatAssemblyBegin(mat,MAT_FINAL_ASSEMBLY);
4298:   MatAssemblyEnd(mat,MAT_FINAL_ASSEMBLY);
4299:   mat->nooffprocentries = nooffprocentries;
4300:   return(0);
4301: }

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

4310:    Collective

4312:    Input Parameters:
4313: +  comm - MPI communicator
4314: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
4315:            This value should be the same as the local size used in creating the
4316:            y vector for the matrix-vector product y = Ax.
4317: .  n - This value should be the same as the local size used in creating the
4318:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4319:        calculated if N is given) For square matrices n is almost always m.
4320: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4321: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4322: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
4323:            (same value is used for all local rows)
4324: .  d_nnz - array containing the number of nonzeros in the various rows of the
4325:            DIAGONAL portion of the local submatrix (possibly different for each row)
4326:            or NULL, if d_nz is used to specify the nonzero structure.
4327:            The size of this array is equal to the number of local rows, i.e 'm'.
4328: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
4329:            submatrix (same value is used for all local rows).
4330: -  o_nnz - array containing the number of nonzeros in the various rows of the
4331:            OFF-DIAGONAL portion of the local submatrix (possibly different for
4332:            each row) or NULL, if o_nz is used to specify the nonzero
4333:            structure. The size of this array is equal to the number
4334:            of local rows, i.e 'm'.

4336:    Output Parameter:
4337: .  A - the matrix

4339:    It is recommended that one use the MatCreate(), MatSetType() and/or MatSetFromOptions(),
4340:    MatXXXXSetPreallocation() paradigm instead of this routine directly.
4341:    [MatXXXXSetPreallocation() is, for example, MatSeqAIJSetPreallocation]

4343:    Notes:
4344:    If the *_nnz parameter is given then the *_nz parameter is ignored

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

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

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

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

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

4367:    The DIAGONAL portion of the local submatrix on any given processor
4368:    is the submatrix corresponding to the rows and columns m,n
4369:    corresponding to the given processor. i.e diagonal matrix on
4370:    process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
4371:    etc. The remaining portion of the local submatrix [m x (N-n)]
4372:    constitute the OFF-DIAGONAL portion. The example below better
4373:    illustrates this concept.

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

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

4382:    When calling this routine with a single process communicator, a matrix of
4383:    type SEQAIJ is returned.  If a matrix of type MPIAIJ is desired for this
4384:    type of communicator, use the construction mechanism
4385: .vb
4386:      MatCreate(...,&A); MatSetType(A,MATMPIAIJ); MatSetSizes(A, m,n,M,N); MatMPIAIJSetPreallocation(A,...);
4387: .ve

4389: $     MatCreate(...,&A);
4390: $     MatSetType(A,MATMPIAIJ);
4391: $     MatSetSizes(A, m,n,M,N);
4392: $     MatMPIAIJSetPreallocation(A,...);

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

4398:    Options Database Keys:
4399: +  -mat_no_inode  - Do not use inodes
4400: -  -mat_inode_limit <limit> - Sets inode limit (max limit=5)



4404:    Example usage:

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

4411: .vb
4412:             1  2  0  |  0  3  0  |  0  4
4413:     Proc0   0  5  6  |  7  0  0  |  8  0
4414:             9  0 10  | 11  0  0  | 12  0
4415:     -------------------------------------
4416:            13  0 14  | 15 16 17  |  0  0
4417:     Proc1   0 18  0  | 19 20 21  |  0  0
4418:             0  0  0  | 22 23  0  | 24  0
4419:     -------------------------------------
4420:     Proc2  25 26 27  |  0  0 28  | 29  0
4421:            30  0  0  | 31 32 33  |  0 34
4422: .ve

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

4426: .vb
4427:       A B C
4428:       D E F
4429:       G H I
4430: .ve

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

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

4439:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
4440:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
4441:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
4442:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
4443:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
4444:    matrix, ans [DF] as another SeqAIJ matrix.

4446:    When d_nz, o_nz parameters are specified, d_nz storage elements are
4447:    allocated for every row of the local diagonal submatrix, and o_nz
4448:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
4449:    One way to choose d_nz and o_nz is to use the max nonzerors per local
4450:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
4451:    In this case, the values of d_nz,o_nz are
4452: .vb
4453:      proc0 : dnz = 2, o_nz = 2
4454:      proc1 : dnz = 3, o_nz = 2
4455:      proc2 : dnz = 1, o_nz = 4
4456: .ve
4457:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
4458:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
4459:    for proc3. i.e we are using 12+15+10=37 storage locations to store
4460:    34 values.

4462:    When d_nnz, o_nnz parameters are specified, the storage is specified
4463:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
4464:    In the above case the values for d_nnz,o_nnz are
4465: .vb
4466:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
4467:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
4468:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
4469: .ve
4470:    Here the space allocated is sum of all the above values i.e 34, and
4471:    hence pre-allocation is perfect.

4473:    Level: intermediate

4475: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4476:           MATMPIAIJ, MatCreateMPIAIJWithArrays()
4477: @*/
4478: 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)
4479: {
4481:   PetscMPIInt    size;

4484:   MatCreate(comm,A);
4485:   MatSetSizes(*A,m,n,M,N);
4486:   MPI_Comm_size(comm,&size);
4487:   if (size > 1) {
4488:     MatSetType(*A,MATMPIAIJ);
4489:     MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);
4490:   } else {
4491:     MatSetType(*A,MATSEQAIJ);
4492:     MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);
4493:   }
4494:   return(0);
4495: }

4497: PetscErrorCode MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
4498: {
4499:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
4500:   PetscBool      flg;

4504:   PetscStrbeginswith(((PetscObject)A)->type_name,MATMPIAIJ,&flg);
4505:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"This function requires a MATMPIAIJ matrix as input");
4506:   if (Ad)     *Ad     = a->A;
4507:   if (Ao)     *Ao     = a->B;
4508:   if (colmap) *colmap = a->garray;
4509:   return(0);
4510: }

4512: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4513: {
4515:   PetscInt       m,N,i,rstart,nnz,Ii;
4516:   PetscInt       *indx;
4517:   PetscScalar    *values;

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

4524:     if (n == PETSC_DECIDE) {
4525:       PetscSplitOwnership(comm,&n,&N);
4526:     }
4527:     /* Check sum(n) = N */
4528:     MPIU_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);
4529:     if (sum != N) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns %D != global columns %D",sum,N);

4531:     MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);
4532:     rstart -= m;

4534:     MatPreallocateInitialize(comm,m,n,dnz,onz);
4535:     for (i=0; i<m; i++) {
4536:       MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4537:       MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);
4538:       MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
4539:     }

4541:     MatCreate(comm,outmat);
4542:     MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4543:     MatGetBlockSizes(inmat,&bs,&cbs);
4544:     MatSetBlockSizes(*outmat,bs,cbs);
4545:     MatSetType(*outmat,MATAIJ);
4546:     MatSeqAIJSetPreallocation(*outmat,0,dnz);
4547:     MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);
4548:     MatPreallocateFinalize(dnz,onz);
4549:   }

4551:   /* numeric phase */
4552:   MatGetOwnershipRange(*outmat,&rstart,NULL);
4553:   for (i=0; i<m; i++) {
4554:     MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4555:     Ii   = i + rstart;
4556:     MatSetValues(*outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
4557:     MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
4558:   }
4559:   MatAssemblyBegin(*outmat,MAT_FINAL_ASSEMBLY);
4560:   MatAssemblyEnd(*outmat,MAT_FINAL_ASSEMBLY);
4561:   return(0);
4562: }

4564: PetscErrorCode MatFileSplit(Mat A,char *outfile)
4565: {
4566:   PetscErrorCode    ierr;
4567:   PetscMPIInt       rank;
4568:   PetscInt          m,N,i,rstart,nnz;
4569:   size_t            len;
4570:   const PetscInt    *indx;
4571:   PetscViewer       out;
4572:   char              *name;
4573:   Mat               B;
4574:   const PetscScalar *values;

4577:   MatGetLocalSize(A,&m,0);
4578:   MatGetSize(A,0,&N);
4579:   /* Should this be the type of the diagonal block of A? */
4580:   MatCreate(PETSC_COMM_SELF,&B);
4581:   MatSetSizes(B,m,N,m,N);
4582:   MatSetBlockSizesFromMats(B,A,A);
4583:   MatSetType(B,MATSEQAIJ);
4584:   MatSeqAIJSetPreallocation(B,0,NULL);
4585:   MatGetOwnershipRange(A,&rstart,0);
4586:   for (i=0; i<m; i++) {
4587:     MatGetRow(A,i+rstart,&nnz,&indx,&values);
4588:     MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);
4589:     MatRestoreRow(A,i+rstart,&nnz,&indx,&values);
4590:   }
4591:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
4592:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

4594:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);
4595:   PetscStrlen(outfile,&len);
4596:   PetscMalloc1(len+5,&name);
4597:   sprintf(name,"%s.%d",outfile,rank);
4598:   PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);
4599:   PetscFree(name);
4600:   MatView(B,out);
4601:   PetscViewerDestroy(&out);
4602:   MatDestroy(&B);
4603:   return(0);
4604: }

4606: PetscErrorCode MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
4607: {
4608:   PetscErrorCode      ierr;
4609:   Mat_Merge_SeqsToMPI *merge;
4610:   PetscContainer      container;

4613:   PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject*)&container);
4614:   if (container) {
4615:     PetscContainerGetPointer(container,(void**)&merge);
4616:     PetscFree(merge->id_r);
4617:     PetscFree(merge->len_s);
4618:     PetscFree(merge->len_r);
4619:     PetscFree(merge->bi);
4620:     PetscFree(merge->bj);
4621:     PetscFree(merge->buf_ri[0]);
4622:     PetscFree(merge->buf_ri);
4623:     PetscFree(merge->buf_rj[0]);
4624:     PetscFree(merge->buf_rj);
4625:     PetscFree(merge->coi);
4626:     PetscFree(merge->coj);
4627:     PetscFree(merge->owners_co);
4628:     PetscLayoutDestroy(&merge->rowmap);
4629:     PetscFree(merge);
4630:     PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);
4631:   }
4632:   MatDestroy_MPIAIJ(A);
4633:   return(0);
4634: }

4636:  #include <../src/mat/utils/freespace.h>
4637:  #include <petscbt.h>

4639: PetscErrorCode MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat,Mat mpimat)
4640: {
4641:   PetscErrorCode      ierr;
4642:   MPI_Comm            comm;
4643:   Mat_SeqAIJ          *a  =(Mat_SeqAIJ*)seqmat->data;
4644:   PetscMPIInt         size,rank,taga,*len_s;
4645:   PetscInt            N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj;
4646:   PetscInt            proc,m;
4647:   PetscInt            **buf_ri,**buf_rj;
4648:   PetscInt            k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
4649:   PetscInt            nrows,**buf_ri_k,**nextrow,**nextai;
4650:   MPI_Request         *s_waits,*r_waits;
4651:   MPI_Status          *status;
4652:   MatScalar           *aa=a->a;
4653:   MatScalar           **abuf_r,*ba_i;
4654:   Mat_Merge_SeqsToMPI *merge;
4655:   PetscContainer      container;

4658:   PetscObjectGetComm((PetscObject)mpimat,&comm);
4659:   PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);

4661:   MPI_Comm_size(comm,&size);
4662:   MPI_Comm_rank(comm,&rank);

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

4667:   bi     = merge->bi;
4668:   bj     = merge->bj;
4669:   buf_ri = merge->buf_ri;
4670:   buf_rj = merge->buf_rj;

4672:   PetscMalloc1(size,&status);
4673:   owners = merge->rowmap->range;
4674:   len_s  = merge->len_s;

4676:   /* send and recv matrix values */
4677:   /*-----------------------------*/
4678:   PetscObjectGetNewTag((PetscObject)mpimat,&taga);
4679:   PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);

4681:   PetscMalloc1(merge->nsend+1,&s_waits);
4682:   for (proc=0,k=0; proc<size; proc++) {
4683:     if (!len_s[proc]) continue;
4684:     i    = owners[proc];
4685:     MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
4686:     k++;
4687:   }

4689:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
4690:   if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}
4691:   PetscFree(status);

4693:   PetscFree(s_waits);
4694:   PetscFree(r_waits);

4696:   /* insert mat values of mpimat */
4697:   /*----------------------------*/
4698:   PetscMalloc1(N,&ba_i);
4699:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextai);

4701:   for (k=0; k<merge->nrecv; k++) {
4702:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4703:     nrows       = *(buf_ri_k[k]);
4704:     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
4705:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4706:   }

4708:   /* set values of ba */
4709:   m = merge->rowmap->n;
4710:   for (i=0; i<m; i++) {
4711:     arow = owners[rank] + i;
4712:     bj_i = bj+bi[i];  /* col indices of the i-th row of mpimat */
4713:     bnzi = bi[i+1] - bi[i];
4714:     PetscArrayzero(ba_i,bnzi);

4716:     /* add local non-zero vals of this proc's seqmat into ba */
4717:     anzi   = ai[arow+1] - ai[arow];
4718:     aj     = a->j + ai[arow];
4719:     aa     = a->a + ai[arow];
4720:     nextaj = 0;
4721:     for (j=0; nextaj<anzi; j++) {
4722:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4723:         ba_i[j] += aa[nextaj++];
4724:       }
4725:     }

4727:     /* add received vals into ba */
4728:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4729:       /* i-th row */
4730:       if (i == *nextrow[k]) {
4731:         anzi   = *(nextai[k]+1) - *nextai[k];
4732:         aj     = buf_rj[k] + *(nextai[k]);
4733:         aa     = abuf_r[k] + *(nextai[k]);
4734:         nextaj = 0;
4735:         for (j=0; nextaj<anzi; j++) {
4736:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
4737:             ba_i[j] += aa[nextaj++];
4738:           }
4739:         }
4740:         nextrow[k]++; nextai[k]++;
4741:       }
4742:     }
4743:     MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);
4744:   }
4745:   MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);
4746:   MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);

4748:   PetscFree(abuf_r[0]);
4749:   PetscFree(abuf_r);
4750:   PetscFree(ba_i);
4751:   PetscFree3(buf_ri_k,nextrow,nextai);
4752:   PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);
4753:   return(0);
4754: }

4756: PetscErrorCode  MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
4757: {
4758:   PetscErrorCode      ierr;
4759:   Mat                 B_mpi;
4760:   Mat_SeqAIJ          *a=(Mat_SeqAIJ*)seqmat->data;
4761:   PetscMPIInt         size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
4762:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
4763:   PetscInt            M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
4764:   PetscInt            len,proc,*dnz,*onz,bs,cbs;
4765:   PetscInt            k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
4766:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
4767:   MPI_Request         *si_waits,*sj_waits,*ri_waits,*rj_waits;
4768:   MPI_Status          *status;
4769:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
4770:   PetscBT             lnkbt;
4771:   Mat_Merge_SeqsToMPI *merge;
4772:   PetscContainer      container;

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

4777:   /* make sure it is a PETSc comm */
4778:   PetscCommDuplicate(comm,&comm,NULL);
4779:   MPI_Comm_size(comm,&size);
4780:   MPI_Comm_rank(comm,&rank);

4782:   PetscNew(&merge);
4783:   PetscMalloc1(size,&status);

4785:   /* determine row ownership */
4786:   /*---------------------------------------------------------*/
4787:   PetscLayoutCreate(comm,&merge->rowmap);
4788:   PetscLayoutSetLocalSize(merge->rowmap,m);
4789:   PetscLayoutSetSize(merge->rowmap,M);
4790:   PetscLayoutSetBlockSize(merge->rowmap,1);
4791:   PetscLayoutSetUp(merge->rowmap);
4792:   PetscMalloc1(size,&len_si);
4793:   PetscMalloc1(size,&merge->len_s);

4795:   m      = merge->rowmap->n;
4796:   owners = merge->rowmap->range;

4798:   /* determine the number of messages to send, their lengths */
4799:   /*---------------------------------------------------------*/
4800:   len_s = merge->len_s;

4802:   len          = 0; /* length of buf_si[] */
4803:   merge->nsend = 0;
4804:   for (proc=0; proc<size; proc++) {
4805:     len_si[proc] = 0;
4806:     if (proc == rank) {
4807:       len_s[proc] = 0;
4808:     } else {
4809:       len_si[proc] = owners[proc+1] - owners[proc] + 1;
4810:       len_s[proc]  = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
4811:     }
4812:     if (len_s[proc]) {
4813:       merge->nsend++;
4814:       nrows = 0;
4815:       for (i=owners[proc]; i<owners[proc+1]; i++) {
4816:         if (ai[i+1] > ai[i]) nrows++;
4817:       }
4818:       len_si[proc] = 2*(nrows+1);
4819:       len         += len_si[proc];
4820:     }
4821:   }

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

4828:   /* post the Irecv of j-structure */
4829:   /*-------------------------------*/
4830:   PetscCommGetNewTag(comm,&tagj);
4831:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);

4833:   /* post the Isend of j-structure */
4834:   /*--------------------------------*/
4835:   PetscMalloc2(merge->nsend,&si_waits,merge->nsend,&sj_waits);

4837:   for (proc=0, k=0; proc<size; proc++) {
4838:     if (!len_s[proc]) continue;
4839:     i    = owners[proc];
4840:     MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);
4841:     k++;
4842:   }

4844:   /* receives and sends of j-structure are complete */
4845:   /*------------------------------------------------*/
4846:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,rj_waits,status);}
4847:   if (merge->nsend) {MPI_Waitall(merge->nsend,sj_waits,status);}

4849:   /* send and recv i-structure */
4850:   /*---------------------------*/
4851:   PetscCommGetNewTag(comm,&tagi);
4852:   PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);

4854:   PetscMalloc1(len+1,&buf_s);
4855:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
4856:   for (proc=0,k=0; proc<size; proc++) {
4857:     if (!len_s[proc]) continue;
4858:     /* form outgoing message for i-structure:
4859:          buf_si[0]:                 nrows to be sent
4860:                [1:nrows]:           row index (global)
4861:                [nrows+1:2*nrows+1]: i-structure index
4862:     */
4863:     /*-------------------------------------------*/
4864:     nrows       = len_si[proc]/2 - 1;
4865:     buf_si_i    = buf_si + nrows+1;
4866:     buf_si[0]   = nrows;
4867:     buf_si_i[0] = 0;
4868:     nrows       = 0;
4869:     for (i=owners[proc]; i<owners[proc+1]; i++) {
4870:       anzi = ai[i+1] - ai[i];
4871:       if (anzi) {
4872:         buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
4873:         buf_si[nrows+1]   = i-owners[proc]; /* local row index */
4874:         nrows++;
4875:       }
4876:     }
4877:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);
4878:     k++;
4879:     buf_si += len_si[proc];
4880:   }

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

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

4890:   PetscFree(len_si);
4891:   PetscFree(len_ri);
4892:   PetscFree(rj_waits);
4893:   PetscFree2(si_waits,sj_waits);
4894:   PetscFree(ri_waits);
4895:   PetscFree(buf_s);
4896:   PetscFree(status);

4898:   /* compute a local seq matrix in each processor */
4899:   /*----------------------------------------------*/
4900:   /* allocate bi array and free space for accumulating nonzero column info */
4901:   PetscMalloc1(m+1,&bi);
4902:   bi[0] = 0;

4904:   /* create and initialize a linked list */
4905:   nlnk = N+1;
4906:   PetscLLCreate(N,N,nlnk,lnk,lnkbt);

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

4912:   current_space = free_space;

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

4917:   for (k=0; k<merge->nrecv; k++) {
4918:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4919:     nrows       = *buf_ri_k[k];
4920:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
4921:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4922:   }

4924:   MatPreallocateInitialize(comm,m,n,dnz,onz);
4925:   len  = 0;
4926:   for (i=0; i<m; i++) {
4927:     bnzi = 0;
4928:     /* add local non-zero cols of this proc's seqmat into lnk */
4929:     arow  = owners[rank] + i;
4930:     anzi  = ai[arow+1] - ai[arow];
4931:     aj    = a->j + ai[arow];
4932:     PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4933:     bnzi += nlnk;
4934:     /* add received col data into lnk */
4935:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4936:       if (i == *nextrow[k]) { /* i-th row */
4937:         anzi  = *(nextai[k]+1) - *nextai[k];
4938:         aj    = buf_rj[k] + *nextai[k];
4939:         PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4940:         bnzi += nlnk;
4941:         nextrow[k]++; nextai[k]++;
4942:       }
4943:     }
4944:     if (len < bnzi) len = bnzi;  /* =max(bnzi) */

4946:     /* if free space is not available, make more free space */
4947:     if (current_space->local_remaining<bnzi) {
4948:       PetscFreeSpaceGet(PetscIntSumTruncate(bnzi,current_space->total_array_size),&current_space);
4949:       nspacedouble++;
4950:     }
4951:     /* copy data into free space, then initialize lnk */
4952:     PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);
4953:     MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);

4955:     current_space->array           += bnzi;
4956:     current_space->local_used      += bnzi;
4957:     current_space->local_remaining -= bnzi;

4959:     bi[i+1] = bi[i] + bnzi;
4960:   }

4962:   PetscFree3(buf_ri_k,nextrow,nextai);

4964:   PetscMalloc1(bi[m]+1,&bj);
4965:   PetscFreeSpaceContiguous(&free_space,bj);
4966:   PetscLLDestroy(lnk,lnkbt);

4968:   /* create symbolic parallel matrix B_mpi */
4969:   /*---------------------------------------*/
4970:   MatGetBlockSizes(seqmat,&bs,&cbs);
4971:   MatCreate(comm,&B_mpi);
4972:   if (n==PETSC_DECIDE) {
4973:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);
4974:   } else {
4975:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4976:   }
4977:   MatSetBlockSizes(B_mpi,bs,cbs);
4978:   MatSetType(B_mpi,MATMPIAIJ);
4979:   MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);
4980:   MatPreallocateFinalize(dnz,onz);
4981:   MatSetOption(B_mpi,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

4983:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
4984:   B_mpi->assembled    = PETSC_FALSE;
4985:   B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
4986:   merge->bi           = bi;
4987:   merge->bj           = bj;
4988:   merge->buf_ri       = buf_ri;
4989:   merge->buf_rj       = buf_rj;
4990:   merge->coi          = NULL;
4991:   merge->coj          = NULL;
4992:   merge->owners_co    = NULL;

4994:   PetscCommDestroy(&comm);

4996:   /* attach the supporting struct to B_mpi for reuse */
4997:   PetscContainerCreate(PETSC_COMM_SELF,&container);
4998:   PetscContainerSetPointer(container,merge);
4999:   PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);
5000:   PetscContainerDestroy(&container);
5001:   *mpimat = B_mpi;

5003:   PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);
5004:   return(0);
5005: }

5007: /*@C
5008:       MatCreateMPIAIJSumSeqAIJ - Creates a MATMPIAIJ matrix by adding sequential
5009:                  matrices from each processor

5011:     Collective

5013:    Input Parameters:
5014: +    comm - the communicators the parallel matrix will live on
5015: .    seqmat - the input sequential matrices
5016: .    m - number of local rows (or PETSC_DECIDE)
5017: .    n - number of local columns (or PETSC_DECIDE)
5018: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5020:    Output Parameter:
5021: .    mpimat - the parallel matrix generated

5023:     Level: advanced

5025:    Notes:
5026:      The dimensions of the sequential matrix in each processor MUST be the same.
5027:      The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
5028:      destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
5029: @*/
5030: PetscErrorCode MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
5031: {
5033:   PetscMPIInt    size;

5036:   MPI_Comm_size(comm,&size);
5037:   if (size == 1) {
5038:     PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
5039:     if (scall == MAT_INITIAL_MATRIX) {
5040:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
5041:     } else {
5042:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
5043:     }
5044:     PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
5045:     return(0);
5046:   }
5047:   PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
5048:   if (scall == MAT_INITIAL_MATRIX) {
5049:     MatCreateMPIAIJSumSeqAIJSymbolic(comm,seqmat,m,n,mpimat);
5050:   }
5051:   MatCreateMPIAIJSumSeqAIJNumeric(seqmat,*mpimat);
5052:   PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
5053:   return(0);
5054: }

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

5061:     Not Collective

5063:    Input Parameters:
5064: +    A - the matrix
5065: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

5067:    Output Parameter:
5068: .    A_loc - the local sequential matrix generated

5070:     Level: developer

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

5074: @*/
5075: PetscErrorCode MatMPIAIJGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
5076: {
5078:   Mat_MPIAIJ     *mpimat=(Mat_MPIAIJ*)A->data;
5079:   Mat_SeqAIJ     *mat,*a,*b;
5080:   PetscInt       *ai,*aj,*bi,*bj,*cmap=mpimat->garray;
5081:   MatScalar      *aa,*ba,*cam;
5082:   PetscScalar    *ca;
5083:   PetscInt       am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
5084:   PetscInt       *ci,*cj,col,ncols_d,ncols_o,jo;
5085:   PetscBool      match;
5086:   MPI_Comm       comm;
5087:   PetscMPIInt    size;

5090:   PetscStrbeginswith(((PetscObject)A)->type_name,MATMPIAIJ,&match);
5091:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
5092:   PetscObjectGetComm((PetscObject)A,&comm);
5093:   MPI_Comm_size(comm,&size);
5094:   if (size == 1 && scall == MAT_REUSE_MATRIX) return(0);

5096:   PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);
5097:   a = (Mat_SeqAIJ*)(mpimat->A)->data;
5098:   b = (Mat_SeqAIJ*)(mpimat->B)->data;
5099:   ai = a->i; aj = a->j; bi = b->i; bj = b->j;
5100:   aa = a->a; ba = b->a;
5101:   if (scall == MAT_INITIAL_MATRIX) {
5102:     if (size == 1) {
5103:       MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ai,aj,aa,A_loc);
5104:       return(0);
5105:     }

5107:     PetscMalloc1(1+am,&ci);
5108:     ci[0] = 0;
5109:     for (i=0; i<am; i++) {
5110:       ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
5111:     }
5112:     PetscMalloc1(1+ci[am],&cj);
5113:     PetscMalloc1(1+ci[am],&ca);
5114:     k    = 0;
5115:     for (i=0; i<am; i++) {
5116:       ncols_o = bi[i+1] - bi[i];
5117:       ncols_d = ai[i+1] - ai[i];
5118:       /* off-diagonal portion of A */
5119:       for (jo=0; jo<ncols_o; jo++) {
5120:         col = cmap[*bj];
5121:         if (col >= cstart) break;
5122:         cj[k]   = col; bj++;
5123:         ca[k++] = *ba++;
5124:       }
5125:       /* diagonal portion of A */
5126:       for (j=0; j<ncols_d; j++) {
5127:         cj[k]   = cstart + *aj++;
5128:         ca[k++] = *aa++;
5129:       }
5130:       /* off-diagonal portion of A */
5131:       for (j=jo; j<ncols_o; j++) {
5132:         cj[k]   = cmap[*bj++];
5133:         ca[k++] = *ba++;
5134:       }
5135:     }
5136:     /* put together the new matrix */
5137:     MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);
5138:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5139:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5140:     mat          = (Mat_SeqAIJ*)(*A_loc)->data;
5141:     mat->free_a  = PETSC_TRUE;
5142:     mat->free_ij = PETSC_TRUE;
5143:     mat->nonew   = 0;
5144:   } else if (scall == MAT_REUSE_MATRIX) {
5145:     mat=(Mat_SeqAIJ*)(*A_loc)->data;
5146:     ci = mat->i; cj = mat->j; cam = mat->a;
5147:     for (i=0; i<am; i++) {
5148:       /* off-diagonal portion of A */
5149:       ncols_o = bi[i+1] - bi[i];
5150:       for (jo=0; jo<ncols_o; jo++) {
5151:         col = cmap[*bj];
5152:         if (col >= cstart) break;
5153:         *cam++ = *ba++; bj++;
5154:       }
5155:       /* diagonal portion of A */
5156:       ncols_d = ai[i+1] - ai[i];
5157:       for (j=0; j<ncols_d; j++) *cam++ = *aa++;
5158:       /* off-diagonal portion of A */
5159:       for (j=jo; j<ncols_o; j++) {
5160:         *cam++ = *ba++; bj++;
5161:       }
5162:     }
5163:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
5164:   PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);
5165:   return(0);
5166: }

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

5171:     Not Collective

5173:    Input Parameters:
5174: +    A - the matrix
5175: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
5176: -    row, col - index sets of rows and columns to extract (or NULL)

5178:    Output Parameter:
5179: .    A_loc - the local sequential matrix generated

5181:     Level: developer

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

5185: @*/
5186: PetscErrorCode MatMPIAIJGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
5187: {
5188:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5190:   PetscInt       i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
5191:   IS             isrowa,iscola;
5192:   Mat            *aloc;
5193:   PetscBool      match;

5196:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
5197:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
5198:   PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);
5199:   if (!row) {
5200:     start = A->rmap->rstart; end = A->rmap->rend;
5201:     ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);
5202:   } else {
5203:     isrowa = *row;
5204:   }
5205:   if (!col) {
5206:     start = A->cmap->rstart;
5207:     cmap  = a->garray;
5208:     nzA   = a->A->cmap->n;
5209:     nzB   = a->B->cmap->n;
5210:     PetscMalloc1(nzA+nzB, &idx);
5211:     ncols = 0;
5212:     for (i=0; i<nzB; i++) {
5213:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5214:       else break;
5215:     }
5216:     imark = i;
5217:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;
5218:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
5219:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&iscola);
5220:   } else {
5221:     iscola = *col;
5222:   }
5223:   if (scall != MAT_INITIAL_MATRIX) {
5224:     PetscMalloc1(1,&aloc);
5225:     aloc[0] = *A_loc;
5226:   }
5227:   MatCreateSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);
5228:   if (!col) { /* attach global id of condensed columns */
5229:     PetscObjectCompose((PetscObject)aloc[0],"_petsc_GetLocalMatCondensed_iscol",(PetscObject)iscola);
5230:   }
5231:   *A_loc = aloc[0];
5232:   PetscFree(aloc);
5233:   if (!row) {
5234:     ISDestroy(&isrowa);
5235:   }
5236:   if (!col) {
5237:     ISDestroy(&iscola);
5238:   }
5239:   PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);
5240:   return(0);
5241: }

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

5246:     Collective on Mat

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

5253:    Output Parameter:
5254: +    rowb, colb - index sets of rows and columns of B to extract
5255: -    B_seq - the sequential matrix generated

5257:     Level: developer

5259: @*/
5260: PetscErrorCode MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,Mat *B_seq)
5261: {
5262:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
5264:   PetscInt       *idx,i,start,ncols,nzA,nzB,*cmap,imark;
5265:   IS             isrowb,iscolb;
5266:   Mat            *bseq=NULL;

5269:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5270:     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);
5271:   }
5272:   PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);

5274:   if (scall == MAT_INITIAL_MATRIX) {
5275:     start = A->cmap->rstart;
5276:     cmap  = a->garray;
5277:     nzA   = a->A->cmap->n;
5278:     nzB   = a->B->cmap->n;
5279:     PetscMalloc1(nzA+nzB, &idx);
5280:     ncols = 0;
5281:     for (i=0; i<nzB; i++) {  /* row < local row index */
5282:       if (cmap[i] < start) idx[ncols++] = cmap[i];
5283:       else break;
5284:     }
5285:     imark = i;
5286:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;  /* local rows */
5287:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
5288:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&isrowb);
5289:     ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);
5290:   } else {
5291:     if (!rowb || !colb) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
5292:     isrowb  = *rowb; iscolb = *colb;
5293:     PetscMalloc1(1,&bseq);
5294:     bseq[0] = *B_seq;
5295:   }
5296:   MatCreateSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);
5297:   *B_seq = bseq[0];
5298:   PetscFree(bseq);
5299:   if (!rowb) {
5300:     ISDestroy(&isrowb);
5301:   } else {
5302:     *rowb = isrowb;
5303:   }
5304:   if (!colb) {
5305:     ISDestroy(&iscolb);
5306:   } else {
5307:     *colb = iscolb;
5308:   }
5309:   PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);
5310:   return(0);
5311: }

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

5317:     Collective on Mat

5319:    Input Parameters:
5320: +    A,B - the matrices in mpiaij format
5321: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

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

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

5332:     Level: developer

5334: */
5335: PetscErrorCode MatGetBrowsOfAoCols_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscInt **startsj_s,PetscInt **startsj_r,MatScalar **bufa_ptr,Mat *B_oth)
5336: {
5337:   PetscErrorCode         ierr;
5338:   Mat_MPIAIJ             *a=(Mat_MPIAIJ*)A->data;
5339:   Mat_SeqAIJ             *b_oth;
5340:   VecScatter             ctx;
5341:   MPI_Comm               comm;
5342:   const PetscMPIInt      *rprocs,*sprocs;
5343:   const PetscInt         *srow,*rstarts,*sstarts;
5344:   PetscInt               *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj,*rvalues=NULL,*svalues=NULL,*cols,sbs,rbs;
5345:   PetscInt               i,j,k=0,l,ll,nrecvs,nsends,nrows,*rstartsj = 0,*sstartsj,len;
5346:   PetscScalar              *b_otha,*bufa,*bufA,*vals;
5347:   MPI_Request            *rwaits = NULL,*swaits = NULL;
5348:   MPI_Status             rstatus;
5349:   PetscMPIInt            jj,size,tag,rank,nsends_mpi,nrecvs_mpi;

5352:   PetscObjectGetComm((PetscObject)A,&comm);
5353:   MPI_Comm_size(comm,&size);

5355:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
5356:     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);
5357:   }
5358:   PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);
5359:   MPI_Comm_rank(comm,&rank);

5361:   if (size == 1) {
5362:     startsj_s = NULL;
5363:     bufa_ptr  = NULL;
5364:     *B_oth    = NULL;
5365:     return(0);
5366:   }

5368:   ctx = a->Mvctx;
5369:   tag = ((PetscObject)ctx)->tag;

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

5379:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
5380:   if (scall == MAT_INITIAL_MATRIX) {
5381:     /* i-array */
5382:     /*---------*/
5383:     /*  post receives */
5384:     if (nrecvs) {PetscMalloc1(rbs*(rstarts[nrecvs] - rstarts[0]),&rvalues);} /* rstarts can be NULL when nrecvs=0 */
5385:     for (i=0; i<nrecvs; i++) {
5386:       rowlen = rvalues + rstarts[i]*rbs;
5387:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
5388:       MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5389:     }

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

5394:     sstartsj[0] = 0;
5395:     rstartsj[0] = 0;
5396:     len         = 0; /* total length of j or a array to be sent */
5397:     if (nsends) {
5398:       k    = sstarts[0]; /* ATTENTION: sstarts[0] and rstarts[0] are not necessarily zero */
5399:       PetscMalloc1(sbs*(sstarts[nsends]-sstarts[0]),&svalues);
5400:     }
5401:     for (i=0; i<nsends; i++) {
5402:       rowlen = svalues + (sstarts[i]-sstarts[0])*sbs;
5403:       nrows  = sstarts[i+1]-sstarts[i]; /* num of block rows */
5404:       for (j=0; j<nrows; j++) {
5405:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
5406:         for (l=0; l<sbs; l++) {
5407:           MatGetRow_MPIAIJ(B,row+l,&ncols,NULL,NULL); /* rowlength */

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

5411:           len += ncols;
5412:           MatRestoreRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);
5413:         }
5414:         k++;
5415:       }
5416:       MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);

5418:       sstartsj[i+1] = len;  /* starting point of (i+1)-th outgoing msg in bufj and bufa */
5419:     }
5420:     /* recvs and sends of i-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:     PetscFree(svalues);

5428:     /* allocate buffers for sending j and a arrays */
5429:     PetscMalloc1(len+1,&bufj);
5430:     PetscMalloc1(len+1,&bufa);

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

5435:     b_othi[0] = 0;
5436:     len       = 0; /* total length of j or a array to be received */
5437:     k         = 0;
5438:     for (i=0; i<nrecvs; i++) {
5439:       rowlen = rvalues + (rstarts[i]-rstarts[0])*rbs;
5440:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of rows to be received */
5441:       for (j=0; j<nrows; j++) {
5442:         b_othi[k+1] = b_othi[k] + rowlen[j];
5443:         PetscIntSumError(rowlen[j],len,&len);
5444:         k++;
5445:       }
5446:       rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
5447:     }
5448:     PetscFree(rvalues);

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

5454:     /* j-array */
5455:     /*---------*/
5456:     /*  post receives of j-array */
5457:     for (i=0; i<nrecvs; i++) {
5458:       nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5459:       MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
5460:     }

5462:     /* pack the outgoing message j-array */
5463:     if (nsends) k = sstarts[0];
5464:     for (i=0; i<nsends; i++) {
5465:       nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5466:       bufJ  = bufj+sstartsj[i];
5467:       for (j=0; j<nrows; j++) {
5468:         row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5469:         for (ll=0; ll<sbs; ll++) {
5470:           MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5471:           for (l=0; l<ncols; l++) {
5472:             *bufJ++ = cols[l];
5473:           }
5474:           MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
5475:         }
5476:       }
5477:       MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);
5478:     }

5480:     /* recvs and sends of j-array are completed */
5481:     i = nrecvs;
5482:     while (i--) {
5483:       MPI_Waitany(nrecvs_mpi,rwaits,&jj,&rstatus);
5484:     }
5485:     if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}
5486:   } else if (scall == MAT_REUSE_MATRIX) {
5487:     sstartsj = *startsj_s;
5488:     rstartsj = *startsj_r;
5489:     bufa     = *bufa_ptr;
5490:     b_oth    = (Mat_SeqAIJ*)(*B_oth)->data;
5491:     b_otha   = b_oth->a;
5492:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");

5494:   /* a-array */
5495:   /*---------*/
5496:   /*  post receives of a-array */
5497:   for (i=0; i<nrecvs; i++) {
5498:     nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
5499:     MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
5500:   }

5502:   /* pack the outgoing message a-array */
5503:   if (nsends) k = sstarts[0];
5504:   for (i=0; i<nsends; i++) {
5505:     nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
5506:     bufA  = bufa+sstartsj[i];
5507:     for (j=0; j<nrows; j++) {
5508:       row = srow[k++] + B->rmap->range[rank];  /* global row idx */
5509:       for (ll=0; ll<sbs; ll++) {
5510:         MatGetRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5511:         for (l=0; l<ncols; l++) {
5512:           *bufA++ = vals[l];
5513:         }
5514:         MatRestoreRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
5515:       }
5516:     }
5517:     MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
5518:   }
5519:   /* recvs and sends of a-array are completed */
5520:   i = nrecvs;
5521:   while (i--) {
5522:     MPI_Waitany(nrecvs_mpi,rwaits,&jj,&rstatus);
5523:   }
5524:   if (nsends) {MPI_Waitall(nsends_mpi,swaits,MPI_STATUSES_IGNORE);}
5525:   PetscFree2(rwaits,swaits);

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

5531:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
5532:     /* Since these are PETSc arrays, change flags to free them as necessary. */
5533:     b_oth          = (Mat_SeqAIJ*)(*B_oth)->data;
5534:     b_oth->free_a  = PETSC_TRUE;
5535:     b_oth->free_ij = PETSC_TRUE;
5536:     b_oth->nonew   = 0;

5538:     PetscFree(bufj);
5539:     if (!startsj_s || !bufa_ptr) {
5540:       PetscFree2(sstartsj,rstartsj);
5541:       PetscFree(bufa_ptr);
5542:     } else {
5543:       *startsj_s = sstartsj;
5544:       *startsj_r = rstartsj;
5545:       *bufa_ptr  = bufa;
5546:     }
5547:   }

5549:   VecScatterRestoreRemote_Private(ctx,PETSC_TRUE,&nsends,&sstarts,&srow,&sprocs,&sbs);
5550:   VecScatterRestoreRemoteOrdered_Private(ctx,PETSC_FALSE,&nrecvs,&rstarts,NULL,&rprocs,&rbs);
5551:   PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);
5552:   return(0);
5553: }

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

5558:   Not Collective

5560:   Input Parameters:
5561: . A - The matrix in mpiaij format

5563:   Output Parameter:
5564: + lvec - The local vector holding off-process values from the argument to a matrix-vector product
5565: . colmap - A map from global column index to local index into lvec
5566: - multScatter - A scatter from the argument of a matrix-vector product to lvec

5568:   Level: developer

5570: @*/
5571: #if defined(PETSC_USE_CTABLE)
5572: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
5573: #else
5574: PetscErrorCode MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
5575: #endif
5576: {
5577:   Mat_MPIAIJ *a;

5584:   a = (Mat_MPIAIJ*) A->data;
5585:   if (lvec) *lvec = a->lvec;
5586:   if (colmap) *colmap = a->colmap;
5587:   if (multScatter) *multScatter = a->Mvctx;
5588:   return(0);
5589: }

5591: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat,MatType,MatReuse,Mat*);
5592: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat,MatType,MatReuse,Mat*);
5593: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJSELL(Mat,MatType,MatReuse,Mat*);
5594: #if defined(PETSC_HAVE_MKL_SPARSE)
5595: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJMKL(Mat,MatType,MatReuse,Mat*);
5596: #endif
5597: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat,MatType,MatReuse,Mat*);
5598: #if defined(PETSC_HAVE_ELEMENTAL)
5599: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
5600: #endif
5601: #if defined(PETSC_HAVE_HYPRE)
5602: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat,MatType,MatReuse,Mat*);
5603: PETSC_INTERN PetscErrorCode MatMatMatMult_Transpose_AIJ_AIJ(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
5604: #endif
5605: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat,MatType,MatReuse,Mat*);
5606: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISELL(Mat,MatType,MatReuse,Mat*);
5607: PETSC_INTERN PetscErrorCode MatPtAP_IS_XAIJ(Mat,Mat,MatReuse,PetscReal,Mat*);

5609: /*
5610:     Computes (B'*A')' since computing B*A directly is untenable

5612:                n                       p                          p
5613:         (              )       (              )         (                  )
5614:       m (      A       )  *  n (       B      )   =   m (         C        )
5615:         (              )       (              )         (                  )

5617: */
5618: PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
5619: {
5621:   Mat            At,Bt,Ct;

5624:   MatTranspose(A,MAT_INITIAL_MATRIX,&At);
5625:   MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);
5626:   MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);
5627:   MatDestroy(&At);
5628:   MatDestroy(&Bt);
5629:   MatTranspose(Ct,MAT_REUSE_MATRIX,&C);
5630:   MatDestroy(&Ct);
5631:   return(0);
5632: }

5634: PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
5635: {
5637:   PetscInt       m=A->rmap->n,n=B->cmap->n;
5638:   Mat            Cmat;

5641:   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);
5642:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
5643:   MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
5644:   MatSetBlockSizesFromMats(Cmat,A,B);
5645:   MatSetType(Cmat,MATMPIDENSE);
5646:   MatMPIDenseSetPreallocation(Cmat,NULL);
5647:   MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);
5648:   MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);

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

5652:   *C = Cmat;
5653:   return(0);
5654: }

5656: /* ----------------------------------------------------------------*/
5657: PETSC_INTERN PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
5658: {

5662:   if (scall == MAT_INITIAL_MATRIX) {
5663:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
5664:     MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);
5665:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
5666:   }
5667:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
5668:   MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);
5669:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
5670:   return(0);
5671: }

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

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

5679:   Level: beginner

5681: .seealso: MatCreateAIJ()
5682: M*/

5684: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
5685: {
5686:   Mat_MPIAIJ     *b;
5688:   PetscMPIInt    size;

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

5693:   PetscNewLog(B,&b);
5694:   B->data       = (void*)b;
5695:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
5696:   B->assembled  = PETSC_FALSE;
5697:   B->insertmode = NOT_SET_VALUES;
5698:   b->size       = size;

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

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

5705:   b->donotstash  = PETSC_FALSE;
5706:   b->colmap      = 0;
5707:   b->garray      = 0;
5708:   b->roworiented = PETSC_TRUE;

5710:   /* stuff used for matrix vector multiply */
5711:   b->lvec  = NULL;
5712:   b->Mvctx = NULL;

5714:   /* stuff for MatGetRow() */
5715:   b->rowindices   = 0;
5716:   b->rowvalues    = 0;
5717:   b->getrowactive = PETSC_FALSE;

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

5722:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetUseScalableIncreaseOverlap_C",MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ);
5723:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIAIJ);
5724:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIAIJ);
5725:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_MPIAIJ);
5726:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",MatMPIAIJSetPreallocation_MPIAIJ);
5727:   PetscObjectComposeFunction((PetscObject)B,"MatResetPreallocation_C",MatResetPreallocation_MPIAIJ);
5728:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",MatMPIAIJSetPreallocationCSR_MPIAIJ);
5729:   PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIAIJ);
5730:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijperm_C",MatConvert_MPIAIJ_MPIAIJPERM);
5731:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijsell_C",MatConvert_MPIAIJ_MPIAIJSELL);
5732: #if defined(PETSC_HAVE_MKL_SPARSE)
5733:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijmkl_C",MatConvert_MPIAIJ_MPIAIJMKL);
5734: #endif
5735:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijcrl_C",MatConvert_MPIAIJ_MPIAIJCRL);
5736:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisbaij_C",MatConvert_MPIAIJ_MPISBAIJ);
5737: #if defined(PETSC_HAVE_ELEMENTAL)
5738:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_elemental_C",MatConvert_MPIAIJ_Elemental);
5739: #endif
5740: #if defined(PETSC_HAVE_HYPRE)
5741:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_hypre_C",MatConvert_AIJ_HYPRE);
5742: #endif
5743:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_is_C",MatConvert_XAIJ_IS);
5744:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisell_C",MatConvert_MPIAIJ_MPISELL);
5745:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",MatMatMult_MPIDense_MPIAIJ);
5746:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",MatMatMultSymbolic_MPIDense_MPIAIJ);
5747:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",MatMatMultNumeric_MPIDense_MPIAIJ);
5748: #if defined(PETSC_HAVE_HYPRE)
5749:   PetscObjectComposeFunction((PetscObject)B,"MatMatMatMult_transpose_mpiaij_mpiaij_C",MatMatMatMult_Transpose_AIJ_AIJ);
5750: #endif
5751:   PetscObjectComposeFunction((PetscObject)B,"MatPtAP_is_mpiaij_C",MatPtAP_IS_XAIJ);
5752:   PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);
5753:   return(0);
5754: }

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

5760:    Collective

5762:    Input Parameters:
5763: +  comm - MPI communicator
5764: .  m - number of local rows (Cannot be PETSC_DECIDE)
5765: .  n - This value should be the same as the local size used in creating the
5766:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
5767:        calculated if N is given) For square matrices n is almost always m.
5768: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
5769: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
5770: .   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
5771: .   j - column indices
5772: .   a - matrix values
5773: .   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
5774: .   oj - column indices
5775: -   oa - matrix values

5777:    Output Parameter:
5778: .   mat - the matrix

5780:    Level: advanced

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

5786:        The i and j indices are 0 based

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

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

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

5799: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
5800:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithArrays()
5801: @*/
5802: 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)
5803: {
5805:   Mat_MPIAIJ     *maij;

5808:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
5809:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
5810:   if (oi[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
5811:   MatCreate(comm,mat);
5812:   MatSetSizes(*mat,m,n,M,N);
5813:   MatSetType(*mat,MATMPIAIJ);
5814:   maij = (Mat_MPIAIJ*) (*mat)->data;

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

5818:   PetscLayoutSetUp((*mat)->rmap);
5819:   PetscLayoutSetUp((*mat)->cmap);

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

5824:   MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);
5825:   MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);
5826:   MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);
5827:   MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);

5829:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
5830:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
5831:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
5832:   MatSetOption(*mat,MAT_NO_OFF_PROC_ENTRIES,PETSC_FALSE);
5833:   MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
5834:   return(0);
5835: }

5837: /*
5838:     Special version for direct calls from Fortran
5839: */
5840:  #include <petsc/private/fortranimpl.h>

5842: /* Change these macros so can be used in void function */
5843: #undef CHKERRQ
5844: #define CHKERRQ(ierr) CHKERRABORT(PETSC_COMM_WORLD,ierr)
5845: #undef SETERRQ2
5846: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
5847: #undef SETERRQ3
5848: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)
5849: #undef SETERRQ
5850: #define SETERRQ(c,ierr,b) CHKERRABORT(c,ierr)

5852: #if defined(PETSC_HAVE_FORTRAN_CAPS)
5853: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
5854: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
5855: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
5856: #else
5857: #endif
5858: 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)
5859: {
5860:   Mat            mat  = *mmat;
5861:   PetscInt       m    = *mm, n = *mn;
5862:   InsertMode     addv = *maddv;
5863:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
5864:   PetscScalar    value;

5867:   MatCheckPreallocated(mat,1);
5868:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;

5870: #if defined(PETSC_USE_DEBUG)
5871:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
5872: #endif
5873:   {
5874:     PetscInt  i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
5875:     PetscInt  cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
5876:     PetscBool roworiented = aij->roworiented;

5878:     /* Some Variables required in the macro */
5879:     Mat        A                 = aij->A;
5880:     Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
5881:     PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
5882:     MatScalar  *aa               = a->a;
5883:     PetscBool  ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
5884:     Mat        B                 = aij->B;
5885:     Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
5886:     PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
5887:     MatScalar  *ba               = b->a;

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

5894:     for (i=0; i<m; i++) {
5895:       if (im[i] < 0) continue;
5896: #if defined(PETSC_USE_DEBUG)
5897:       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);
5898: #endif
5899:       if (im[i] >= rstart && im[i] < rend) {
5900:         row      = im[i] - rstart;
5901:         lastcol1 = -1;
5902:         rp1      = aj + ai[row];
5903:         ap1      = aa + ai[row];
5904:         rmax1    = aimax[row];
5905:         nrow1    = ailen[row];
5906:         low1     = 0;
5907:         high1    = nrow1;
5908:         lastcol2 = -1;
5909:         rp2      = bj + bi[row];
5910:         ap2      = ba + bi[row];
5911:         rmax2    = bimax[row];
5912:         nrow2    = bilen[row];
5913:         low2     = 0;
5914:         high2    = nrow2;

5916:         for (j=0; j<n; j++) {
5917:           if (roworiented) value = v[i*n+j];
5918:           else value = v[i+j*m];
5919:           if (in[j] >= cstart && in[j] < cend) {
5920:             col = in[j] - cstart;
5921:             if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && row != col) continue;
5922:             MatSetValues_SeqAIJ_A_Private(row,col,value,addv,im[i],in[j]);
5923:           } else if (in[j] < 0) continue;
5924: #if defined(PETSC_USE_DEBUG)
5925:           /* extra brace on SETERRQ2() is required for --with-errorchecking=0 - due to the next 'else' clause */
5926:           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);}
5927: #endif
5928:           else {
5929:             if (mat->was_assembled) {
5930:               if (!aij->colmap) {
5931:                 MatCreateColmap_MPIAIJ_Private(mat);
5932:               }
5933: #if defined(PETSC_USE_CTABLE)
5934:               PetscTableFind(aij->colmap,in[j]+1,&col);
5935:               col--;
5936: #else
5937:               col = aij->colmap[in[j]] - 1;
5938: #endif
5939:               if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES) && row != col) continue;
5940:               if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
5941:                 MatDisAssemble_MPIAIJ(mat);
5942:                 col  =  in[j];
5943:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
5944:                 B     = aij->B;
5945:                 b     = (Mat_SeqAIJ*)B->data;
5946:                 bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
5947:                 rp2   = bj + bi[row];
5948:                 ap2   = ba + bi[row];
5949:                 rmax2 = bimax[row];
5950:                 nrow2 = bilen[row];
5951:                 low2  = 0;
5952:                 high2 = nrow2;
5953:                 bm    = aij->B->rmap->n;
5954:                 ba    = b->a;
5955:               }
5956:             } else col = in[j];
5957:             MatSetValues_SeqAIJ_B_Private(row,col,value,addv,im[i],in[j]);
5958:           }
5959:         }
5960:       } else if (!aij->donotstash) {
5961:         if (roworiented) {
5962:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5963:         } else {
5964:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5965:         }
5966:       }
5967:     }
5968:   }
5969:   PetscFunctionReturnVoid();
5970: }