Actual source code: mpiaij.c

petsc-master 2017-02-21
Report Typos and Errors


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

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

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

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

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

 24:   Level: beginner

 26: .seealso: MatCreateAIJ(), MatCreateSeqAIJ(), MATSEQAIJ, MATMPIAIJ
 27: M*/

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

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

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

 41:   Level: beginner

 43: .seealso: MatCreateMPIAIJCRL,MATSEQAIJCRL,MATMPIAIJCRL, MATSEQAIJCRL, MATMPIAIJCRL
 44: M*/

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

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

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

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

120: PetscErrorCode  MatDiagonalSet_MPIAIJ(Mat Y,Vec D,InsertMode is)
121: {
122:   PetscErrorCode    ierr;
123:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*) Y->data;

126:   if (Y->assembled && Y->rmap->rstart == Y->cmap->rstart && Y->rmap->rend == Y->cmap->rend) {
127:     MatDiagonalSet(aij->A,D,is);
128:   } else {
129:     MatDiagonalSet_Default(Y,D,is);
130:   }
131:   return(0);
132: }


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

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

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

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

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

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

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

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

222:   ISRestoreIndices(sis,&isis);
223:   ISRestoreIndices(gis,&igis);
224:   ISDestroy(&sis);
225:   ISDestroy(&gis);
226:   return(0);
227: }

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

233:     Only for square matrices

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

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

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

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

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

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

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

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

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

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

427: #define MatSetValues_SeqAIJ_A_Private(row,col,value,addv,orow,ocol)     \
428: { \
429:     if (col <= lastcol1)  low1 = 0;     \
430:     else                 high1 = nrow1; \
431:     lastcol1 = col;\
432:     while (high1-low1 > 5) { \
433:       t = (low1+high1)/2; \
434:       if (rp1[t] > col) high1 = t; \
435:       else              low1  = t; \
436:     } \
437:       for (_i=low1; _i<high1; _i++) { \
438:         if (rp1[_i] > col) break; \
439:         if (rp1[_i] == col) { \
440:           if (addv == ADD_VALUES) ap1[_i] += value;   \
441:           else                    ap1[_i] = value; \
442:           goto a_noinsert; \
443:         } \
444:       }  \
445:       if (value == 0.0 && ignorezeroentries) {low1 = 0; high1 = nrow1;goto a_noinsert;} \
446:       if (nonew == 1) {low1 = 0; high1 = nrow1; goto a_noinsert;}                \
447:       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); \
448:       MatSeqXAIJReallocateAIJ(A,am,1,nrow1,row,col,rmax1,aa,ai,aj,rp1,ap1,aimax,nonew,MatScalar); \
449:       N = nrow1++ - 1; a->nz++; high1++; \
450:       /* shift up all the later entries in this row */ \
451:       for (ii=N; ii>=_i; ii--) { \
452:         rp1[ii+1] = rp1[ii]; \
453:         ap1[ii+1] = ap1[ii]; \
454:       } \
455:       rp1[_i] = col;  \
456:       ap1[_i] = value;  \
457:       A->nonzerostate++;\
458:       a_noinsert: ; \
459:       ailen[row] = nrow1; \
460: }


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

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

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

508:   /* find size of row to the left of the diagonal part */
509:   MatGetOwnershipRange(A,&diag,0);
510:   row  = row - diag;
511:   for (l=0; l<b->i[row+1]-b->i[row]; l++) {
512:     if (garray[b->j[b->i[row]+l]] > diag) break;
513:   }
514:   PetscMemcpy(b->a+b->i[row],v,l*sizeof(PetscScalar));

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

519:   /* right of diagonal part */
520:   PetscMemcpy(b->a+b->i[row]+l,v+l+a->i[row+1]-a->i[row],(b->i[row+1]-b->i[row]-l)*sizeof(PetscScalar));
521:   return(0);
522: }

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

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

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

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

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

630: PetscErrorCode MatGetValues_MPIAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
631: {
632:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
634:   PetscInt       i,j,rstart = mat->rmap->rstart,rend = mat->rmap->rend;
635:   PetscInt       cstart = mat->cmap->rstart,cend = mat->cmap->rend,row,col;

638:   for (i=0; i<m; i++) {
639:     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
640:     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);
641:     if (idxm[i] >= rstart && idxm[i] < rend) {
642:       row = idxm[i] - rstart;
643:       for (j=0; j<n; j++) {
644:         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
645:         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);
646:         if (idxn[j] >= cstart && idxn[j] < cend) {
647:           col  = idxn[j] - cstart;
648:           MatGetValues(aij->A,1,&row,1,&col,v+i*n+j);
649:         } else {
650:           if (!aij->colmap) {
651:             MatCreateColmap_MPIAIJ_Private(mat);
652:           }
653: #if defined(PETSC_USE_CTABLE)
654:           PetscTableFind(aij->colmap,idxn[j]+1,&col);
655:           col--;
656: #else
657:           col = aij->colmap[idxn[j]] - 1;
658: #endif
659:           if ((col < 0) || (aij->garray[col] != idxn[j])) *(v+i*n+j) = 0.0;
660:           else {
661:             MatGetValues(aij->B,1,&row,1,&col,v+i*n+j);
662:           }
663:         }
664:       }
665:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
666:   }
667:   return(0);
668: }

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

672: PetscErrorCode MatAssemblyBegin_MPIAIJ(Mat mat,MatAssemblyType mode)
673: {
674:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
676:   PetscInt       nstash,reallocs;

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

681:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
682:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
683:   PetscInfo2(aij->A,"Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
684:   return(0);
685: }

687: PetscErrorCode MatAssemblyEnd_MPIAIJ(Mat mat,MatAssemblyType mode)
688: {
689:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
690:   Mat_SeqAIJ     *a   = (Mat_SeqAIJ*)aij->A->data;
692:   PetscMPIInt    n;
693:   PetscInt       i,j,rstart,ncols,flg;
694:   PetscInt       *row,*col;
695:   PetscBool      other_disassembled;
696:   PetscScalar    *val;

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

701:   if (!aij->donotstash && !mat->nooffprocentries) {
702:     while (1) {
703:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
704:       if (!flg) break;

706:       for (i=0; i<n; ) {
707:         /* Now identify the consecutive vals belonging to the same row */
708:         for (j=i,rstart=row[j]; j<n; j++) {
709:           if (row[j] != rstart) break;
710:         }
711:         if (j < n) ncols = j-i;
712:         else       ncols = n-i;
713:         /* Now assemble all these values with a single function call */
714:         MatSetValues_MPIAIJ(mat,1,row+i,ncols,col+i,val+i,mat->insertmode);

716:         i = j;
717:       }
718:     }
719:     MatStashScatterEnd_Private(&mat->stash);
720:   }
721:   MatAssemblyBegin(aij->A,mode);
722:   MatAssemblyEnd(aij->A,mode);

724:   /* determine if any processor has disassembled, if so we must
725:      also disassemble ourselfs, in order that we may reassemble. */
726:   /*
727:      if nonzero structure of submatrix B cannot change then we know that
728:      no processor disassembled thus we can skip this stuff
729:   */
730:   if (!((Mat_SeqAIJ*)aij->B->data)->nonew) {
731:     MPIU_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));
732:     if (mat->was_assembled && !other_disassembled) {
733:       MatDisAssemble_MPIAIJ(mat);
734:     }
735:   }
736:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
737:     MatSetUpMultiply_MPIAIJ(mat);
738:   }
739:   MatSetOption(aij->B,MAT_USE_INODES,PETSC_FALSE);
740:   MatAssemblyBegin(aij->B,mode);
741:   MatAssemblyEnd(aij->B,mode);

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

745:   aij->rowvalues = 0;

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

750:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
751:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
752:     PetscObjectState state = aij->A->nonzerostate + aij->B->nonzerostate;
753:     MPIU_Allreduce(&state,&mat->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)mat));
754:   }
755:   return(0);
756: }

758: PetscErrorCode MatZeroEntries_MPIAIJ(Mat A)
759: {
760:   Mat_MPIAIJ     *l = (Mat_MPIAIJ*)A->data;

764:   MatZeroEntries(l->A);
765:   MatZeroEntries(l->B);
766:   return(0);
767: }

769: PetscErrorCode MatZeroRows_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
770: {
771:   Mat_MPIAIJ    *mat    = (Mat_MPIAIJ *) A->data;
772:   PetscInt      *lrows;
773:   PetscInt       r, len;

777:   /* get locally owned rows */
778:   MatZeroRowsMapLocal_Private(A,N,rows,&len,&lrows);
779:   /* fix right hand side if needed */
780:   if (x && b) {
781:     const PetscScalar *xx;
782:     PetscScalar       *bb;

784:     VecGetArrayRead(x, &xx);
785:     VecGetArray(b, &bb);
786:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag*xx[lrows[r]];
787:     VecRestoreArrayRead(x, &xx);
788:     VecRestoreArray(b, &bb);
789:   }
790:   /* Must zero l->B before l->A because the (diag) case below may put values into l->B*/
791:   MatZeroRows(mat->B, len, lrows, 0.0, NULL, NULL);
792:   if (A->congruentlayouts == -1) { /* first time we compare rows and cols layouts */
793:     PetscBool cong;
794:     PetscLayoutCompare(A->rmap,A->cmap,&cong);
795:     if (cong) A->congruentlayouts = 1;
796:     else      A->congruentlayouts = 0;
797:   }
798:   if ((diag != 0.0) && A->congruentlayouts) {
799:     MatZeroRows(mat->A, len, lrows, diag, NULL, NULL);
800:   } else if (diag != 0.0) {
801:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
802:     if (((Mat_SeqAIJ *) mat->A->data)->nonew) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MatZeroRows() on rectangular matrices cannot be used with the Mat options\nMAT_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
803:     for (r = 0; r < len; ++r) {
804:       const PetscInt row = lrows[r] + A->rmap->rstart;
805:       MatSetValues(A, 1, &row, 1, &row, &diag, INSERT_VALUES);
806:     }
807:     MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY);
808:     MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY);
809:   } else {
810:     MatZeroRows(mat->A, len, lrows, 0.0, NULL, NULL);
811:   }
812:   PetscFree(lrows);

814:   /* only change matrix nonzero state if pattern was allowed to be changed */
815:   if (!((Mat_SeqAIJ*)(mat->A->data))->keepnonzeropattern) {
816:     PetscObjectState state = mat->A->nonzerostate + mat->B->nonzerostate;
817:     MPIU_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
818:   }
819:   return(0);
820: }

822: PetscErrorCode MatZeroRowsColumns_MPIAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
823: {
824:   Mat_MPIAIJ        *l = (Mat_MPIAIJ*)A->data;
825:   PetscErrorCode    ierr;
826:   PetscMPIInt       n = A->rmap->n;
827:   PetscInt          i,j,r,m,p = 0,len = 0;
828:   PetscInt          *lrows,*owners = A->rmap->range;
829:   PetscSFNode       *rrows;
830:   PetscSF           sf;
831:   const PetscScalar *xx;
832:   PetscScalar       *bb,*mask;
833:   Vec               xmask,lmask;
834:   Mat_SeqAIJ        *aij = (Mat_SeqAIJ*)l->B->data;
835:   const PetscInt    *aj, *ii,*ridx;
836:   PetscScalar       *aa;

839:   /* Create SF where leaves are input rows and roots are owned rows */
840:   PetscMalloc1(n, &lrows);
841:   for (r = 0; r < n; ++r) lrows[r] = -1;
842:   PetscMalloc1(N, &rrows);
843:   for (r = 0; r < N; ++r) {
844:     const PetscInt idx   = rows[r];
845:     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);
846:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
847:       PetscLayoutFindOwner(A->rmap,idx,&p);
848:     }
849:     rrows[r].rank  = p;
850:     rrows[r].index = rows[r] - owners[p];
851:   }
852:   PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
853:   PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
854:   /* Collect flags for rows to be zeroed */
855:   PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
856:   PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
857:   PetscSFDestroy(&sf);
858:   /* Compress and put in row numbers */
859:   for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
860:   /* zero diagonal part of matrix */
861:   MatZeroRowsColumns(l->A,len,lrows,diag,x,b);
862:   /* handle off diagonal part of matrix */
863:   MatCreateVecs(A,&xmask,NULL);
864:   VecDuplicate(l->lvec,&lmask);
865:   VecGetArray(xmask,&bb);
866:   for (i=0; i<len; i++) bb[lrows[i]] = 1;
867:   VecRestoreArray(xmask,&bb);
868:   VecScatterBegin(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
869:   VecScatterEnd(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
870:   VecDestroy(&xmask);
871:   if (x) {
872:     VecScatterBegin(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
873:     VecScatterEnd(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
874:     VecGetArrayRead(l->lvec,&xx);
875:     VecGetArray(b,&bb);
876:   }
877:   VecGetArray(lmask,&mask);
878:   /* remove zeroed rows of off diagonal matrix */
879:   ii = aij->i;
880:   for (i=0; i<len; i++) {
881:     PetscMemzero(aij->a + ii[lrows[i]],(ii[lrows[i]+1] - ii[lrows[i]])*sizeof(PetscScalar));
882:   }
883:   /* loop over all elements of off process part of matrix zeroing removed columns*/
884:   if (aij->compressedrow.use) {
885:     m    = aij->compressedrow.nrows;
886:     ii   = aij->compressedrow.i;
887:     ridx = aij->compressedrow.rindex;
888:     for (i=0; i<m; i++) {
889:       n  = ii[i+1] - ii[i];
890:       aj = aij->j + ii[i];
891:       aa = aij->a + ii[i];

893:       for (j=0; j<n; j++) {
894:         if (PetscAbsScalar(mask[*aj])) {
895:           if (b) bb[*ridx] -= *aa*xx[*aj];
896:           *aa = 0.0;
897:         }
898:         aa++;
899:         aj++;
900:       }
901:       ridx++;
902:     }
903:   } else { /* do not use compressed row format */
904:     m = l->B->rmap->n;
905:     for (i=0; i<m; i++) {
906:       n  = ii[i+1] - ii[i];
907:       aj = aij->j + ii[i];
908:       aa = aij->a + ii[i];
909:       for (j=0; j<n; j++) {
910:         if (PetscAbsScalar(mask[*aj])) {
911:           if (b) bb[i] -= *aa*xx[*aj];
912:           *aa = 0.0;
913:         }
914:         aa++;
915:         aj++;
916:       }
917:     }
918:   }
919:   if (x) {
920:     VecRestoreArray(b,&bb);
921:     VecRestoreArrayRead(l->lvec,&xx);
922:   }
923:   VecRestoreArray(lmask,&mask);
924:   VecDestroy(&lmask);
925:   PetscFree(lrows);

927:   /* only change matrix nonzero state if pattern was allowed to be changed */
928:   if (!((Mat_SeqAIJ*)(l->A->data))->keepnonzeropattern) {
929:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
930:     MPIU_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
931:   }
932:   return(0);
933: }

935: PetscErrorCode MatMult_MPIAIJ(Mat A,Vec xx,Vec yy)
936: {
937:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
939:   PetscInt       nt;

942:   VecGetLocalSize(xx,&nt);
943:   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);
944:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
945:   (*a->A->ops->mult)(a->A,xx,yy);
946:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
947:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
948:   return(0);
949: }

951: PetscErrorCode MatMultDiagonalBlock_MPIAIJ(Mat A,Vec bb,Vec xx)
952: {
953:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

957:   MatMultDiagonalBlock(a->A,bb,xx);
958:   return(0);
959: }

961: PetscErrorCode MatMultAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
962: {
963:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

967:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
968:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
969:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
970:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
971:   return(0);
972: }

974: PetscErrorCode MatMultTranspose_MPIAIJ(Mat A,Vec xx,Vec yy)
975: {
976:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
978:   PetscBool      merged;

981:   VecScatterGetMerged(a->Mvctx,&merged);
982:   /* do nondiagonal part */
983:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
984:   if (!merged) {
985:     /* send it on its way */
986:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
987:     /* do local part */
988:     (*a->A->ops->multtranspose)(a->A,xx,yy);
989:     /* receive remote parts: note this assumes the values are not actually */
990:     /* added in yy until the next line, */
991:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
992:   } else {
993:     /* do local part */
994:     (*a->A->ops->multtranspose)(a->A,xx,yy);
995:     /* send it on its way */
996:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
997:     /* values actually were received in the Begin() but we need to call this nop */
998:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
999:   }
1000:   return(0);
1001: }

1003: PetscErrorCode  MatIsTranspose_MPIAIJ(Mat Amat,Mat Bmat,PetscReal tol,PetscBool  *f)
1004: {
1005:   MPI_Comm       comm;
1006:   Mat_MPIAIJ     *Aij = (Mat_MPIAIJ*) Amat->data, *Bij;
1007:   Mat            Adia = Aij->A, Bdia, Aoff,Boff,*Aoffs,*Boffs;
1008:   IS             Me,Notme;
1010:   PetscInt       M,N,first,last,*notme,i;
1011:   PetscMPIInt    size;

1014:   /* Easy test: symmetric diagonal block */
1015:   Bij  = (Mat_MPIAIJ*) Bmat->data; Bdia = Bij->A;
1016:   MatIsTranspose(Adia,Bdia,tol,f);
1017:   if (!*f) return(0);
1018:   PetscObjectGetComm((PetscObject)Amat,&comm);
1019:   MPI_Comm_size(comm,&size);
1020:   if (size == 1) return(0);

1022:   /* Hard test: off-diagonal block. This takes a MatGetSubMatrix. */
1023:   MatGetSize(Amat,&M,&N);
1024:   MatGetOwnershipRange(Amat,&first,&last);
1025:   PetscMalloc1(N-last+first,&notme);
1026:   for (i=0; i<first; i++) notme[i] = i;
1027:   for (i=last; i<M; i++) notme[i-last+first] = i;
1028:   ISCreateGeneral(MPI_COMM_SELF,N-last+first,notme,PETSC_COPY_VALUES,&Notme);
1029:   ISCreateStride(MPI_COMM_SELF,last-first,first,1,&Me);
1030:   MatGetSubMatrices(Amat,1,&Me,&Notme,MAT_INITIAL_MATRIX,&Aoffs);
1031:   Aoff = Aoffs[0];
1032:   MatGetSubMatrices(Bmat,1,&Notme,&Me,MAT_INITIAL_MATRIX,&Boffs);
1033:   Boff = Boffs[0];
1034:   MatIsTranspose(Aoff,Boff,tol,f);
1035:   MatDestroyMatrices(1,&Aoffs);
1036:   MatDestroyMatrices(1,&Boffs);
1037:   ISDestroy(&Me);
1038:   ISDestroy(&Notme);
1039:   PetscFree(notme);
1040:   return(0);
1041: }

1043: PetscErrorCode MatMultTransposeAdd_MPIAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1044: {
1045:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1049:   /* do nondiagonal part */
1050:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1051:   /* send it on its way */
1052:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1053:   /* do local part */
1054:   (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
1055:   /* receive remote parts */
1056:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1057:   return(0);
1058: }

1060: /*
1061:   This only works correctly for square matrices where the subblock A->A is the
1062:    diagonal block
1063: */
1064: PetscErrorCode MatGetDiagonal_MPIAIJ(Mat A,Vec v)
1065: {
1067:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1070:   if (A->rmap->N != A->cmap->N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1071:   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");
1072:   MatGetDiagonal(a->A,v);
1073:   return(0);
1074: }

1076: PetscErrorCode MatScale_MPIAIJ(Mat A,PetscScalar aa)
1077: {
1078:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1082:   MatScale(a->A,aa);
1083:   MatScale(a->B,aa);
1084:   return(0);
1085: }

1087: PetscErrorCode MatDestroy_MPIAIJ(Mat mat)
1088: {
1089:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

1093: #if defined(PETSC_USE_LOG)
1094:   PetscLogObjectState((PetscObject)mat,"Rows=%D, Cols=%D",mat->rmap->N,mat->cmap->N);
1095: #endif
1096:   MatStashDestroy_Private(&mat->stash);
1097:   VecDestroy(&aij->diag);
1098:   MatDestroy(&aij->A);
1099:   MatDestroy(&aij->B);
1100: #if defined(PETSC_USE_CTABLE)
1101:   PetscTableDestroy(&aij->colmap);
1102: #else
1103:   PetscFree(aij->colmap);
1104: #endif
1105:   PetscFree(aij->garray);
1106:   VecDestroy(&aij->lvec);
1107:   VecScatterDestroy(&aij->Mvctx);
1108:   PetscFree2(aij->rowvalues,aij->rowindices);
1109:   PetscFree(aij->ld);
1110:   PetscFree(mat->data);

1112:   PetscObjectChangeTypeName((PetscObject)mat,0);
1113:   PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);
1114:   PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);
1115:   PetscObjectComposeFunction((PetscObject)mat,"MatIsTranspose_C",NULL);
1116:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocation_C",NULL);
1117:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIAIJSetPreallocationCSR_C",NULL);
1118:   PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",NULL);
1119:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_mpisbaij_C",NULL);
1120: #if defined(PETSC_HAVE_ELEMENTAL)
1121:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_elemental_C",NULL);
1122: #endif
1123: #if defined(PETSC_HAVE_HYPRE)
1124:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpiaij_hypre_C",NULL);
1125:   PetscObjectComposeFunction((PetscObject)mat,"MatMatMatMult_transpose_mpiaij_mpiaij_C",NULL);
1126: #endif
1127:   return(0);
1128: }

1130: PetscErrorCode MatView_MPIAIJ_Binary(Mat mat,PetscViewer viewer)
1131: {
1132:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
1133:   Mat_SeqAIJ     *A   = (Mat_SeqAIJ*)aij->A->data;
1134:   Mat_SeqAIJ     *B   = (Mat_SeqAIJ*)aij->B->data;
1136:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
1137:   int            fd;
1138:   PetscInt       nz,header[4],*row_lengths,*range=0,rlen,i;
1139:   PetscInt       nzmax,*column_indices,j,k,col,*garray = aij->garray,cnt,cstart = mat->cmap->rstart,rnz = 0;
1140:   PetscScalar    *column_values;
1141:   PetscInt       message_count,flowcontrolcount;
1142:   FILE           *file;

1145:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1146:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1147:   nz   = A->nz + B->nz;
1148:   PetscViewerBinaryGetDescriptor(viewer,&fd);
1149:   if (!rank) {
1150:     header[0] = MAT_FILE_CLASSID;
1151:     header[1] = mat->rmap->N;
1152:     header[2] = mat->cmap->N;

1154:     MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1155:     PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);
1156:     /* get largest number of rows any processor has */
1157:     rlen  = mat->rmap->n;
1158:     range = mat->rmap->range;
1159:     for (i=1; i<size; i++) rlen = PetscMax(rlen,range[i+1] - range[i]);
1160:   } else {
1161:     MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1162:     rlen = mat->rmap->n;
1163:   }

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

1169:   /* store the row lengths to the file */
1170:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1171:   if (!rank) {
1172:     PetscBinaryWrite(fd,row_lengths,mat->rmap->n,PETSC_INT,PETSC_TRUE);
1173:     for (i=1; i<size; i++) {
1174:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1175:       rlen = range[i+1] - range[i];
1176:       MPIULong_Recv(row_lengths,rlen,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1177:       PetscBinaryWrite(fd,row_lengths,rlen,PETSC_INT,PETSC_TRUE);
1178:     }
1179:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1180:   } else {
1181:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1182:     MPIULong_Send(row_lengths,mat->rmap->n,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1183:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1184:   }
1185:   PetscFree(row_lengths);

1187:   /* load up the local column indices */
1188:   nzmax = nz; /* th processor needs space a largest processor needs */
1189:   MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,PetscObjectComm((PetscObject)mat));
1190:   PetscMalloc1(nzmax+1,&column_indices);
1191:   cnt   = 0;
1192:   for (i=0; i<mat->rmap->n; i++) {
1193:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1194:       if ((col = garray[B->j[j]]) > cstart) break;
1195:       column_indices[cnt++] = col;
1196:     }
1197:     for (k=A->i[i]; k<A->i[i+1]; k++) column_indices[cnt++] = A->j[k] + cstart;
1198:     for (; j<B->i[i+1]; j++) column_indices[cnt++] = garray[B->j[j]];
1199:   }
1200:   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);

1202:   /* store the column indices to the file */
1203:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1204:   if (!rank) {
1205:     MPI_Status status;
1206:     PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);
1207:     for (i=1; i<size; i++) {
1208:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1209:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1210:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1211:       MPIULong_Recv(column_indices,rnz,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat));
1212:       PetscBinaryWrite(fd,column_indices,rnz,PETSC_INT,PETSC_TRUE);
1213:     }
1214:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1215:   } else {
1216:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1217:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1218:     MPIULong_Send(column_indices,nz,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1219:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1220:   }
1221:   PetscFree(column_indices);

1223:   /* load up the local column values */
1224:   PetscMalloc1(nzmax+1,&column_values);
1225:   cnt  = 0;
1226:   for (i=0; i<mat->rmap->n; i++) {
1227:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1228:       if (garray[B->j[j]] > cstart) break;
1229:       column_values[cnt++] = B->a[j];
1230:     }
1231:     for (k=A->i[i]; k<A->i[i+1]; k++) column_values[cnt++] = A->a[k];
1232:     for (; j<B->i[i+1]; j++) column_values[cnt++] = B->a[j];
1233:   }
1234:   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);

1236:   /* store the column values to the file */
1237:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1238:   if (!rank) {
1239:     MPI_Status status;
1240:     PetscBinaryWrite(fd,column_values,nz,PETSC_SCALAR,PETSC_TRUE);
1241:     for (i=1; i<size; i++) {
1242:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1243:       MPI_Recv(&rnz,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1244:       if (rnz > nzmax) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: nz = %D nzmax = %D",nz,nzmax);
1245:       MPIULong_Recv(column_values,rnz,MPIU_SCALAR,i,tag,PetscObjectComm((PetscObject)mat));
1246:       PetscBinaryWrite(fd,column_values,rnz,PETSC_SCALAR,PETSC_TRUE);
1247:     }
1248:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1249:   } else {
1250:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1251:     MPI_Send(&nz,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1252:     MPIULong_Send(column_values,nz,MPIU_SCALAR,0,tag,PetscObjectComm((PetscObject)mat));
1253:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1254:   }
1255:   PetscFree(column_values);

1257:   PetscViewerBinaryGetInfoPointer(viewer,&file);
1258:   if (file) fprintf(file,"-matload_block_size %d\n",(int)PetscAbs(mat->rmap->bs));
1259:   return(0);
1260: }

1262:  #include <petscdraw.h>
1263: PetscErrorCode MatView_MPIAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1264: {
1265:   Mat_MPIAIJ        *aij = (Mat_MPIAIJ*)mat->data;
1266:   PetscErrorCode    ierr;
1267:   PetscMPIInt       rank = aij->rank,size = aij->size;
1268:   PetscBool         isdraw,iascii,isbinary;
1269:   PetscViewer       sviewer;
1270:   PetscViewerFormat format;

1273:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1274:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1275:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1276:   if (iascii) {
1277:     PetscViewerGetFormat(viewer,&format);
1278:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1279:       MatInfo   info;
1280:       PetscBool inodes;

1282:       MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1283:       MatGetInfo(mat,MAT_LOCAL,&info);
1284:       MatInodeGetInodeSizes(aij->A,NULL,(PetscInt**)&inodes,NULL);
1285:       PetscViewerASCIIPushSynchronized(viewer);
1286:       if (!inodes) {
1287:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, not using I-node routines\n",
1288:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1289:       } else {
1290:         PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D mem %D, using I-node routines\n",
1291:                                                   rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,(PetscInt)info.memory);
1292:       }
1293:       MatGetInfo(aij->A,MAT_LOCAL,&info);
1294:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1295:       MatGetInfo(aij->B,MAT_LOCAL,&info);
1296:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1297:       PetscViewerFlush(viewer);
1298:       PetscViewerASCIIPopSynchronized(viewer);
1299:       PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
1300:       VecScatterView(aij->Mvctx,viewer);
1301:       return(0);
1302:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1303:       PetscInt inodecount,inodelimit,*inodes;
1304:       MatInodeGetInodeSizes(aij->A,&inodecount,&inodes,&inodelimit);
1305:       if (inodes) {
1306:         PetscViewerASCIIPrintf(viewer,"using I-node (on process 0) routines: found %D nodes, limit used is %D\n",inodecount,inodelimit);
1307:       } else {
1308:         PetscViewerASCIIPrintf(viewer,"not using I-node (on process 0) routines\n");
1309:       }
1310:       return(0);
1311:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1312:       return(0);
1313:     }
1314:   } else if (isbinary) {
1315:     if (size == 1) {
1316:       PetscObjectSetName((PetscObject)aij->A,((PetscObject)mat)->name);
1317:       MatView(aij->A,viewer);
1318:     } else {
1319:       MatView_MPIAIJ_Binary(mat,viewer);
1320:     }
1321:     return(0);
1322:   } else if (isdraw) {
1323:     PetscDraw draw;
1324:     PetscBool isnull;
1325:     PetscViewerDrawGetDraw(viewer,0,&draw);
1326:     PetscDrawIsNull(draw,&isnull);
1327:     if (isnull) return(0);
1328:   }

1330:   {
1331:     /* assemble the entire matrix onto first processor. */
1332:     Mat        A;
1333:     Mat_SeqAIJ *Aloc;
1334:     PetscInt   M = mat->rmap->N,N = mat->cmap->N,m,*ai,*aj,row,*cols,i,*ct;
1335:     MatScalar  *a;

1337:     MatCreate(PetscObjectComm((PetscObject)mat),&A);
1338:     if (!rank) {
1339:       MatSetSizes(A,M,N,M,N);
1340:     } else {
1341:       MatSetSizes(A,0,0,M,N);
1342:     }
1343:     /* This is just a temporary matrix, so explicitly using MATMPIAIJ is probably best */
1344:     MatSetType(A,MATMPIAIJ);
1345:     MatMPIAIJSetPreallocation(A,0,NULL,0,NULL);
1346:     MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
1347:     PetscLogObjectParent((PetscObject)mat,(PetscObject)A);

1349:     /* copy over the A part */
1350:     Aloc = (Mat_SeqAIJ*)aij->A->data;
1351:     m    = aij->A->rmap->n; ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1352:     row  = mat->rmap->rstart;
1353:     for (i=0; i<ai[m]; i++) aj[i] += mat->cmap->rstart;
1354:     for (i=0; i<m; i++) {
1355:       MatSetValues(A,1,&row,ai[i+1]-ai[i],aj,a,INSERT_VALUES);
1356:       row++;
1357:       a += ai[i+1]-ai[i]; aj += ai[i+1]-ai[i];
1358:     }
1359:     aj = Aloc->j;
1360:     for (i=0; i<ai[m]; i++) aj[i] -= mat->cmap->rstart;

1362:     /* copy over the B part */
1363:     Aloc = (Mat_SeqAIJ*)aij->B->data;
1364:     m    = aij->B->rmap->n;  ai = Aloc->i; aj = Aloc->j; a = Aloc->a;
1365:     row  = mat->rmap->rstart;
1366:     PetscMalloc1(ai[m]+1,&cols);
1367:     ct   = cols;
1368:     for (i=0; i<ai[m]; i++) cols[i] = aij->garray[aj[i]];
1369:     for (i=0; i<m; i++) {
1370:       MatSetValues(A,1,&row,ai[i+1]-ai[i],cols,a,INSERT_VALUES);
1371:       row++;
1372:       a += ai[i+1]-ai[i]; cols += ai[i+1]-ai[i];
1373:     }
1374:     PetscFree(ct);
1375:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1376:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1377:     /*
1378:        Everyone has to call to draw the matrix since the graphics waits are
1379:        synchronized across all processors that share the PetscDraw object
1380:     */
1381:     PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1382:     if (!rank) {
1383:       PetscObjectSetName((PetscObject)((Mat_MPIAIJ*)(A->data))->A,((PetscObject)mat)->name);
1384:       MatView_SeqAIJ(((Mat_MPIAIJ*)(A->data))->A,sviewer);
1385:     }
1386:     PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1387:     PetscViewerFlush(viewer);
1388:     MatDestroy(&A);
1389:   }
1390:   return(0);
1391: }

1393: PetscErrorCode MatView_MPIAIJ(Mat mat,PetscViewer viewer)
1394: {
1396:   PetscBool      iascii,isdraw,issocket,isbinary;

1399:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1400:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1401:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1402:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
1403:   if (iascii || isdraw || isbinary || issocket) {
1404:     MatView_MPIAIJ_ASCIIorDraworSocket(mat,viewer);
1405:   }
1406:   return(0);
1407: }

1409: PetscErrorCode MatSOR_MPIAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
1410: {
1411:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1413:   Vec            bb1 = 0;
1414:   PetscBool      hasop;

1417:   if (flag == SOR_APPLY_UPPER) {
1418:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1419:     return(0);
1420:   }

1422:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS || flag & SOR_EISENSTAT) {
1423:     VecDuplicate(bb,&bb1);
1424:   }

1426:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
1427:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1428:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1429:       its--;
1430:     }

1432:     while (its--) {
1433:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1434:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1436:       /* update rhs: bb1 = bb - B*x */
1437:       VecScale(mat->lvec,-1.0);
1438:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1440:       /* local sweep */
1441:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,1,xx);
1442:     }
1443:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
1444:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1445:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1446:       its--;
1447:     }
1448:     while (its--) {
1449:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1450:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1452:       /* update rhs: bb1 = bb - B*x */
1453:       VecScale(mat->lvec,-1.0);
1454:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1456:       /* local sweep */
1457:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,1,xx);
1458:     }
1459:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
1460:     if (flag & SOR_ZERO_INITIAL_GUESS) {
1461:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
1462:       its--;
1463:     }
1464:     while (its--) {
1465:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1466:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

1468:       /* update rhs: bb1 = bb - B*x */
1469:       VecScale(mat->lvec,-1.0);
1470:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

1472:       /* local sweep */
1473:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);
1474:     }
1475:   } else if (flag & SOR_EISENSTAT) {
1476:     Vec xx1;

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

1481:     VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1482:     VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
1483:     if (!mat->diag) {
1484:       MatCreateVecs(matin,&mat->diag,NULL);
1485:       MatGetDiagonal(matin,mat->diag);
1486:     }
1487:     MatHasOperation(matin,MATOP_MULT_DIAGONAL_BLOCK,&hasop);
1488:     if (hasop) {
1489:       MatMultDiagonalBlock(matin,xx,bb1);
1490:     } else {
1491:       VecPointwiseMult(bb1,mat->diag,xx);
1492:     }
1493:     VecAYPX(bb1,(omega-2.0)/omega,bb);

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

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

1503:   VecDestroy(&bb1);

1505:   matin->factorerrortype = mat->A->factorerrortype;
1506:   return(0);
1507: }

1509: PetscErrorCode MatPermute_MPIAIJ(Mat A,IS rowp,IS colp,Mat *B)
1510: {
1511:   Mat            aA,aB,Aperm;
1512:   const PetscInt *rwant,*cwant,*gcols,*ai,*bi,*aj,*bj;
1513:   PetscScalar    *aa,*ba;
1514:   PetscInt       i,j,m,n,ng,anz,bnz,*dnnz,*onnz,*tdnnz,*tonnz,*rdest,*cdest,*work,*gcdest;
1515:   PetscSF        rowsf,sf;
1516:   IS             parcolp = NULL;
1517:   PetscBool      done;

1521:   MatGetLocalSize(A,&m,&n);
1522:   ISGetIndices(rowp,&rwant);
1523:   ISGetIndices(colp,&cwant);
1524:   PetscMalloc3(PetscMax(m,n),&work,m,&rdest,n,&cdest);

1526:   /* Invert row permutation to find out where my rows should go */
1527:   PetscSFCreate(PetscObjectComm((PetscObject)A),&rowsf);
1528:   PetscSFSetGraphLayout(rowsf,A->rmap,A->rmap->n,NULL,PETSC_OWN_POINTER,rwant);
1529:   PetscSFSetFromOptions(rowsf);
1530:   for (i=0; i<m; i++) work[i] = A->rmap->rstart + i;
1531:   PetscSFReduceBegin(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);
1532:   PetscSFReduceEnd(rowsf,MPIU_INT,work,rdest,MPIU_REPLACE);

1534:   /* Invert column permutation to find out where my columns should go */
1535:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1536:   PetscSFSetGraphLayout(sf,A->cmap,A->cmap->n,NULL,PETSC_OWN_POINTER,cwant);
1537:   PetscSFSetFromOptions(sf);
1538:   for (i=0; i<n; i++) work[i] = A->cmap->rstart + i;
1539:   PetscSFReduceBegin(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1540:   PetscSFReduceEnd(sf,MPIU_INT,work,cdest,MPIU_REPLACE);
1541:   PetscSFDestroy(&sf);

1543:   ISRestoreIndices(rowp,&rwant);
1544:   ISRestoreIndices(colp,&cwant);
1545:   MatMPIAIJGetSeqAIJ(A,&aA,&aB,&gcols);

1547:   /* Find out where my gcols should go */
1548:   MatGetSize(aB,NULL,&ng);
1549:   PetscMalloc1(ng,&gcdest);
1550:   PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1551:   PetscSFSetGraphLayout(sf,A->cmap,ng,NULL,PETSC_OWN_POINTER,gcols);
1552:   PetscSFSetFromOptions(sf);
1553:   PetscSFBcastBegin(sf,MPIU_INT,cdest,gcdest);
1554:   PetscSFBcastEnd(sf,MPIU_INT,cdest,gcdest);
1555:   PetscSFDestroy(&sf);

1557:   PetscCalloc4(m,&dnnz,m,&onnz,m,&tdnnz,m,&tonnz);
1558:   MatGetRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1559:   MatGetRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1560:   for (i=0; i<m; i++) {
1561:     PetscInt row = rdest[i],rowner;
1562:     PetscLayoutFindOwner(A->rmap,row,&rowner);
1563:     for (j=ai[i]; j<ai[i+1]; j++) {
1564:       PetscInt cowner,col = cdest[aj[j]];
1565:       PetscLayoutFindOwner(A->cmap,col,&cowner); /* Could build an index for the columns to eliminate this search */
1566:       if (rowner == cowner) dnnz[i]++;
1567:       else onnz[i]++;
1568:     }
1569:     for (j=bi[i]; j<bi[i+1]; j++) {
1570:       PetscInt cowner,col = gcdest[bj[j]];
1571:       PetscLayoutFindOwner(A->cmap,col,&cowner);
1572:       if (rowner == cowner) dnnz[i]++;
1573:       else onnz[i]++;
1574:     }
1575:   }
1576:   PetscSFBcastBegin(rowsf,MPIU_INT,dnnz,tdnnz);
1577:   PetscSFBcastEnd(rowsf,MPIU_INT,dnnz,tdnnz);
1578:   PetscSFBcastBegin(rowsf,MPIU_INT,onnz,tonnz);
1579:   PetscSFBcastEnd(rowsf,MPIU_INT,onnz,tonnz);
1580:   PetscSFDestroy(&rowsf);

1582:   MatCreateAIJ(PetscObjectComm((PetscObject)A),A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N,0,tdnnz,0,tonnz,&Aperm);
1583:   MatSeqAIJGetArray(aA,&aa);
1584:   MatSeqAIJGetArray(aB,&ba);
1585:   for (i=0; i<m; i++) {
1586:     PetscInt *acols = dnnz,*bcols = onnz; /* Repurpose now-unneeded arrays */
1587:     PetscInt j0,rowlen;
1588:     rowlen = ai[i+1] - ai[i];
1589:     for (j0=j=0; j<rowlen; j0=j) { /* rowlen could be larger than number of rows m, so sum in batches */
1590:       for ( ; j<PetscMin(rowlen,j0+m); j++) acols[j-j0] = cdest[aj[ai[i]+j]];
1591:       MatSetValues(Aperm,1,&rdest[i],j-j0,acols,aa+ai[i]+j0,INSERT_VALUES);
1592:     }
1593:     rowlen = bi[i+1] - bi[i];
1594:     for (j0=j=0; j<rowlen; j0=j) {
1595:       for ( ; j<PetscMin(rowlen,j0+m); j++) bcols[j-j0] = gcdest[bj[bi[i]+j]];
1596:       MatSetValues(Aperm,1,&rdest[i],j-j0,bcols,ba+bi[i]+j0,INSERT_VALUES);
1597:     }
1598:   }
1599:   MatAssemblyBegin(Aperm,MAT_FINAL_ASSEMBLY);
1600:   MatAssemblyEnd(Aperm,MAT_FINAL_ASSEMBLY);
1601:   MatRestoreRowIJ(aA,0,PETSC_FALSE,PETSC_FALSE,&anz,&ai,&aj,&done);
1602:   MatRestoreRowIJ(aB,0,PETSC_FALSE,PETSC_FALSE,&bnz,&bi,&bj,&done);
1603:   MatSeqAIJRestoreArray(aA,&aa);
1604:   MatSeqAIJRestoreArray(aB,&ba);
1605:   PetscFree4(dnnz,onnz,tdnnz,tonnz);
1606:   PetscFree3(work,rdest,cdest);
1607:   PetscFree(gcdest);
1608:   if (parcolp) {ISDestroy(&colp);}
1609:   *B = Aperm;
1610:   return(0);
1611: }

1613: PetscErrorCode  MatGetGhosts_MPIAIJ(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
1614: {
1615:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1619:   MatGetSize(aij->B,NULL,nghosts);
1620:   if (ghosts) *ghosts = aij->garray;
1621:   return(0);
1622: }

1624: PetscErrorCode MatGetInfo_MPIAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1625: {
1626:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1627:   Mat            A    = mat->A,B = mat->B;
1629:   PetscReal      isend[5],irecv[5];

1632:   info->block_size = 1.0;
1633:   MatGetInfo(A,MAT_LOCAL,info);

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

1638:   MatGetInfo(B,MAT_LOCAL,info);

1640:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1641:   isend[3] += info->memory;  isend[4] += info->mallocs;
1642:   if (flag == MAT_LOCAL) {
1643:     info->nz_used      = isend[0];
1644:     info->nz_allocated = isend[1];
1645:     info->nz_unneeded  = isend[2];
1646:     info->memory       = isend[3];
1647:     info->mallocs      = isend[4];
1648:   } else if (flag == MAT_GLOBAL_MAX) {
1649:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

1651:     info->nz_used      = irecv[0];
1652:     info->nz_allocated = irecv[1];
1653:     info->nz_unneeded  = irecv[2];
1654:     info->memory       = irecv[3];
1655:     info->mallocs      = irecv[4];
1656:   } else if (flag == MAT_GLOBAL_SUM) {
1657:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));

1659:     info->nz_used      = irecv[0];
1660:     info->nz_allocated = irecv[1];
1661:     info->nz_unneeded  = irecv[2];
1662:     info->memory       = irecv[3];
1663:     info->mallocs      = irecv[4];
1664:   }
1665:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1666:   info->fill_ratio_needed = 0;
1667:   info->factor_mallocs    = 0;
1668:   return(0);
1669: }

1671: PetscErrorCode MatSetOption_MPIAIJ(Mat A,MatOption op,PetscBool flg)
1672: {
1673:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

1677:   switch (op) {
1678:   case MAT_NEW_NONZERO_LOCATIONS:
1679:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1680:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1681:   case MAT_KEEP_NONZERO_PATTERN:
1682:   case MAT_NEW_NONZERO_LOCATION_ERR:
1683:   case MAT_USE_INODES:
1684:   case MAT_IGNORE_ZERO_ENTRIES:
1685:     MatCheckPreallocated(A,1);
1686:     MatSetOption(a->A,op,flg);
1687:     MatSetOption(a->B,op,flg);
1688:     break;
1689:   case MAT_ROW_ORIENTED:
1690:     MatCheckPreallocated(A,1);
1691:     a->roworiented = flg;

1693:     MatSetOption(a->A,op,flg);
1694:     MatSetOption(a->B,op,flg);
1695:     break;
1696:   case MAT_NEW_DIAGONALS:
1697:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1698:     break;
1699:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1700:     a->donotstash = flg;
1701:     break;
1702:   case MAT_SPD:
1703:     A->spd_set = PETSC_TRUE;
1704:     A->spd     = flg;
1705:     if (flg) {
1706:       A->symmetric                  = PETSC_TRUE;
1707:       A->structurally_symmetric     = PETSC_TRUE;
1708:       A->symmetric_set              = PETSC_TRUE;
1709:       A->structurally_symmetric_set = PETSC_TRUE;
1710:     }
1711:     break;
1712:   case MAT_SYMMETRIC:
1713:     MatCheckPreallocated(A,1);
1714:     MatSetOption(a->A,op,flg);
1715:     break;
1716:   case MAT_STRUCTURALLY_SYMMETRIC:
1717:     MatCheckPreallocated(A,1);
1718:     MatSetOption(a->A,op,flg);
1719:     break;
1720:   case MAT_HERMITIAN:
1721:     MatCheckPreallocated(A,1);
1722:     MatSetOption(a->A,op,flg);
1723:     break;
1724:   case MAT_SYMMETRY_ETERNAL:
1725:     MatCheckPreallocated(A,1);
1726:     MatSetOption(a->A,op,flg);
1727:     break;
1728:   case MAT_SUBMAT_SINGLEIS:
1729:     A->submat_singleis = flg;
1730:     break;
1731:   default:
1732:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1733:   }
1734:   return(0);
1735: }

1737: PetscErrorCode MatGetRow_MPIAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1738: {
1739:   Mat_MPIAIJ     *mat = (Mat_MPIAIJ*)matin->data;
1740:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
1742:   PetscInt       i,*cworkA,*cworkB,**pcA,**pcB,cstart = matin->cmap->rstart;
1743:   PetscInt       nztot,nzA,nzB,lrow,rstart = matin->rmap->rstart,rend = matin->rmap->rend;
1744:   PetscInt       *cmap,*idx_p;

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

1750:   if (!mat->rowvalues && (idx || v)) {
1751:     /*
1752:         allocate enough space to hold information from the longest row.
1753:     */
1754:     Mat_SeqAIJ *Aa = (Mat_SeqAIJ*)mat->A->data,*Ba = (Mat_SeqAIJ*)mat->B->data;
1755:     PetscInt   max = 1,tmp;
1756:     for (i=0; i<matin->rmap->n; i++) {
1757:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
1758:       if (max < tmp) max = tmp;
1759:     }
1760:     PetscMalloc2(max,&mat->rowvalues,max,&mat->rowindices);
1761:   }

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

1766:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1767:   if (!v)   {pvA = 0; pvB = 0;}
1768:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1769:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1770:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1771:   nztot = nzA + nzB;

1773:   cmap = mat->garray;
1774:   if (v  || idx) {
1775:     if (nztot) {
1776:       /* Sort by increasing column numbers, assuming A and B already sorted */
1777:       PetscInt imark = -1;
1778:       if (v) {
1779:         *v = v_p = mat->rowvalues;
1780:         for (i=0; i<nzB; i++) {
1781:           if (cmap[cworkB[i]] < cstart) v_p[i] = vworkB[i];
1782:           else break;
1783:         }
1784:         imark = i;
1785:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1786:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1787:       }
1788:       if (idx) {
1789:         *idx = idx_p = mat->rowindices;
1790:         if (imark > -1) {
1791:           for (i=0; i<imark; i++) {
1792:             idx_p[i] = cmap[cworkB[i]];
1793:           }
1794:         } else {
1795:           for (i=0; i<nzB; i++) {
1796:             if (cmap[cworkB[i]] < cstart) idx_p[i] = cmap[cworkB[i]];
1797:             else break;
1798:           }
1799:           imark = i;
1800:         }
1801:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart + cworkA[i];
1802:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]];
1803:       }
1804:     } else {
1805:       if (idx) *idx = 0;
1806:       if (v)   *v   = 0;
1807:     }
1808:   }
1809:   *nz  = nztot;
1810:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1811:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1812:   return(0);
1813: }

1815: PetscErrorCode MatRestoreRow_MPIAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1816: {
1817:   Mat_MPIAIJ *aij = (Mat_MPIAIJ*)mat->data;

1820:   if (!aij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1821:   aij->getrowactive = PETSC_FALSE;
1822:   return(0);
1823: }

1825: PetscErrorCode MatNorm_MPIAIJ(Mat mat,NormType type,PetscReal *norm)
1826: {
1827:   Mat_MPIAIJ     *aij  = (Mat_MPIAIJ*)mat->data;
1828:   Mat_SeqAIJ     *amat = (Mat_SeqAIJ*)aij->A->data,*bmat = (Mat_SeqAIJ*)aij->B->data;
1830:   PetscInt       i,j,cstart = mat->cmap->rstart;
1831:   PetscReal      sum = 0.0;
1832:   MatScalar      *v;

1835:   if (aij->size == 1) {
1836:      MatNorm(aij->A,type,norm);
1837:   } else {
1838:     if (type == NORM_FROBENIUS) {
1839:       v = amat->a;
1840:       for (i=0; i<amat->nz; i++) {
1841:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1842:       }
1843:       v = bmat->a;
1844:       for (i=0; i<bmat->nz; i++) {
1845:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
1846:       }
1847:       MPIU_Allreduce(&sum,norm,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1848:       *norm = PetscSqrtReal(*norm);
1849:       PetscLogFlops(2*amat->nz+2*bmat->nz);
1850:     } else if (type == NORM_1) { /* max column norm */
1851:       PetscReal *tmp,*tmp2;
1852:       PetscInt  *jj,*garray = aij->garray;
1853:       PetscCalloc1(mat->cmap->N+1,&tmp);
1854:       PetscMalloc1(mat->cmap->N+1,&tmp2);
1855:       *norm = 0.0;
1856:       v     = amat->a; jj = amat->j;
1857:       for (j=0; j<amat->nz; j++) {
1858:         tmp[cstart + *jj++] += PetscAbsScalar(*v);  v++;
1859:       }
1860:       v = bmat->a; jj = bmat->j;
1861:       for (j=0; j<bmat->nz; j++) {
1862:         tmp[garray[*jj++]] += PetscAbsScalar(*v); v++;
1863:       }
1864:       MPIU_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
1865:       for (j=0; j<mat->cmap->N; j++) {
1866:         if (tmp2[j] > *norm) *norm = tmp2[j];
1867:       }
1868:       PetscFree(tmp);
1869:       PetscFree(tmp2);
1870:       PetscLogFlops(PetscMax(amat->nz+bmat->nz-1,0));
1871:     } else if (type == NORM_INFINITY) { /* max row norm */
1872:       PetscReal ntemp = 0.0;
1873:       for (j=0; j<aij->A->rmap->n; j++) {
1874:         v   = amat->a + amat->i[j];
1875:         sum = 0.0;
1876:         for (i=0; i<amat->i[j+1]-amat->i[j]; i++) {
1877:           sum += PetscAbsScalar(*v); v++;
1878:         }
1879:         v = bmat->a + bmat->i[j];
1880:         for (i=0; i<bmat->i[j+1]-bmat->i[j]; i++) {
1881:           sum += PetscAbsScalar(*v); v++;
1882:         }
1883:         if (sum > ntemp) ntemp = sum;
1884:       }
1885:       MPIU_Allreduce(&ntemp,norm,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)mat));
1886:       PetscLogFlops(PetscMax(amat->nz+bmat->nz-1,0));
1887:     } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No support for two norm");
1888:   }
1889:   return(0);
1890: }

1892: PetscErrorCode MatTranspose_MPIAIJ(Mat A,MatReuse reuse,Mat *matout)
1893: {
1894:   Mat_MPIAIJ     *a   = (Mat_MPIAIJ*)A->data;
1895:   Mat_SeqAIJ     *Aloc=(Mat_SeqAIJ*)a->A->data,*Bloc=(Mat_SeqAIJ*)a->B->data;
1897:   PetscInt       M      = A->rmap->N,N = A->cmap->N,ma,na,mb,nb,*ai,*aj,*bi,*bj,row,*cols,*cols_tmp,i;
1898:   PetscInt       cstart = A->cmap->rstart,ncol;
1899:   Mat            B;
1900:   MatScalar      *array;

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

1905:   ma = A->rmap->n; na = A->cmap->n; mb = a->B->rmap->n; nb = a->B->cmap->n;
1906:   ai = Aloc->i; aj = Aloc->j;
1907:   bi = Bloc->i; bj = Bloc->j;
1908:   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1909:     PetscInt             *d_nnz,*g_nnz,*o_nnz;
1910:     PetscSFNode          *oloc;
1911:     PETSC_UNUSED PetscSF sf;

1913:     PetscMalloc4(na,&d_nnz,na,&o_nnz,nb,&g_nnz,nb,&oloc);
1914:     /* compute d_nnz for preallocation */
1915:     PetscMemzero(d_nnz,na*sizeof(PetscInt));
1916:     for (i=0; i<ai[ma]; i++) {
1917:       d_nnz[aj[i]]++;
1918:       aj[i] += cstart; /* global col index to be used by MatSetValues() */
1919:     }
1920:     /* compute local off-diagonal contributions */
1921:     PetscMemzero(g_nnz,nb*sizeof(PetscInt));
1922:     for (i=0; i<bi[ma]; i++) g_nnz[bj[i]]++;
1923:     /* map those to global */
1924:     PetscSFCreate(PetscObjectComm((PetscObject)A),&sf);
1925:     PetscSFSetGraphLayout(sf,A->cmap,nb,NULL,PETSC_USE_POINTER,a->garray);
1926:     PetscSFSetFromOptions(sf);
1927:     PetscMemzero(o_nnz,na*sizeof(PetscInt));
1928:     PetscSFReduceBegin(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
1929:     PetscSFReduceEnd(sf,MPIU_INT,g_nnz,o_nnz,MPIU_SUM);
1930:     PetscSFDestroy(&sf);

1932:     MatCreate(PetscObjectComm((PetscObject)A),&B);
1933:     MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);
1934:     MatSetBlockSizes(B,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
1935:     MatSetType(B,((PetscObject)A)->type_name);
1936:     MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
1937:     PetscFree4(d_nnz,o_nnz,g_nnz,oloc);
1938:   } else {
1939:     B    = *matout;
1940:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
1941:     for (i=0; i<ai[ma]; i++) aj[i] += cstart; /* global col index to be used by MatSetValues() */
1942:   }

1944:   /* copy over the A part */
1945:   array = Aloc->a;
1946:   row   = A->rmap->rstart;
1947:   for (i=0; i<ma; i++) {
1948:     ncol = ai[i+1]-ai[i];
1949:     MatSetValues(B,ncol,aj,1,&row,array,INSERT_VALUES);
1950:     row++;
1951:     array += ncol; aj += ncol;
1952:   }
1953:   aj = Aloc->j;
1954:   for (i=0; i<ai[ma]; i++) aj[i] -= cstart; /* resume local col index */

1956:   /* copy over the B part */
1957:   PetscCalloc1(bi[mb],&cols);
1958:   array = Bloc->a;
1959:   row   = A->rmap->rstart;
1960:   for (i=0; i<bi[mb]; i++) cols[i] = a->garray[bj[i]];
1961:   cols_tmp = cols;
1962:   for (i=0; i<mb; i++) {
1963:     ncol = bi[i+1]-bi[i];
1964:     MatSetValues(B,ncol,cols_tmp,1,&row,array,INSERT_VALUES);
1965:     row++;
1966:     array += ncol; cols_tmp += ncol;
1967:   }
1968:   PetscFree(cols);

1970:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1971:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1972:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1973:     *matout = B;
1974:   } else {
1975:     MatHeaderMerge(A,&B);
1976:   }
1977:   return(0);
1978: }

1980: PetscErrorCode MatDiagonalScale_MPIAIJ(Mat mat,Vec ll,Vec rr)
1981: {
1982:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
1983:   Mat            a    = aij->A,b = aij->B;
1985:   PetscInt       s1,s2,s3;

1988:   MatGetLocalSize(mat,&s2,&s3);
1989:   if (rr) {
1990:     VecGetLocalSize(rr,&s1);
1991:     if (s1!=s3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
1992:     /* Overlap communication with computation. */
1993:     VecScatterBegin(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1994:   }
1995:   if (ll) {
1996:     VecGetLocalSize(ll,&s1);
1997:     if (s1!=s2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
1998:     (*b->ops->diagonalscale)(b,ll,0);
1999:   }
2000:   /* scale  the diagonal block */
2001:   (*a->ops->diagonalscale)(a,ll,rr);

2003:   if (rr) {
2004:     /* Do a scatter end and then right scale the off-diagonal block */
2005:     VecScatterEnd(aij->Mvctx,rr,aij->lvec,INSERT_VALUES,SCATTER_FORWARD);
2006:     (*b->ops->diagonalscale)(b,0,aij->lvec);
2007:   }
2008:   return(0);
2009: }

2011: PetscErrorCode MatSetUnfactored_MPIAIJ(Mat A)
2012: {
2013:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2017:   MatSetUnfactored(a->A);
2018:   return(0);
2019: }

2021: PetscErrorCode MatEqual_MPIAIJ(Mat A,Mat B,PetscBool  *flag)
2022: {
2023:   Mat_MPIAIJ     *matB = (Mat_MPIAIJ*)B->data,*matA = (Mat_MPIAIJ*)A->data;
2024:   Mat            a,b,c,d;
2025:   PetscBool      flg;

2029:   a = matA->A; b = matA->B;
2030:   c = matB->A; d = matB->B;

2032:   MatEqual(a,c,&flg);
2033:   if (flg) {
2034:     MatEqual(b,d,&flg);
2035:   }
2036:   MPIU_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2037:   return(0);
2038: }

2040: PetscErrorCode MatCopy_MPIAIJ(Mat A,Mat B,MatStructure str)
2041: {
2043:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2044:   Mat_MPIAIJ     *b = (Mat_MPIAIJ*)B->data;

2047:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2048:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2049:     /* because of the column compression in the off-processor part of the matrix a->B,
2050:        the number of columns in a->B and b->B may be different, hence we cannot call
2051:        the MatCopy() directly on the two parts. If need be, we can provide a more
2052:        efficient copy than the MatCopy_Basic() by first uncompressing the a->B matrices
2053:        then copying the submatrices */
2054:     MatCopy_Basic(A,B,str);
2055:   } else {
2056:     MatCopy(a->A,b->A,str);
2057:     MatCopy(a->B,b->B,str);
2058:   }
2059:   return(0);
2060: }

2062: PetscErrorCode MatSetUp_MPIAIJ(Mat A)
2063: {

2067:    MatMPIAIJSetPreallocation(A,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
2068:   return(0);
2069: }

2071: /*
2072:    Computes the number of nonzeros per row needed for preallocation when X and Y
2073:    have different nonzero structure.
2074: */
2075: 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)
2076: {
2077:   PetscInt       i,j,k,nzx,nzy;

2080:   /* Set the number of nonzeros in the new matrix */
2081:   for (i=0; i<m; i++) {
2082:     const PetscInt *xjj = xj+xi[i],*yjj = yj+yi[i];
2083:     nzx = xi[i+1] - xi[i];
2084:     nzy = yi[i+1] - yi[i];
2085:     nnz[i] = 0;
2086:     for (j=0,k=0; j<nzx; j++) {                   /* Point in X */
2087:       for (; k<nzy && yltog[yjj[k]]<xltog[xjj[j]]; k++) nnz[i]++; /* Catch up to X */
2088:       if (k<nzy && yltog[yjj[k]]==xltog[xjj[j]]) k++;             /* Skip duplicate */
2089:       nnz[i]++;
2090:     }
2091:     for (; k<nzy; k++) nnz[i]++;
2092:   }
2093:   return(0);
2094: }

2096: /* This is the same as MatAXPYGetPreallocation_SeqAIJ, except that the local-to-global map is provided */
2097: static PetscErrorCode MatAXPYGetPreallocation_MPIAIJ(Mat Y,const PetscInt *yltog,Mat X,const PetscInt *xltog,PetscInt *nnz)
2098: {
2100:   PetscInt       m = Y->rmap->N;
2101:   Mat_SeqAIJ     *x = (Mat_SeqAIJ*)X->data;
2102:   Mat_SeqAIJ     *y = (Mat_SeqAIJ*)Y->data;

2105:   MatAXPYGetPreallocation_MPIX_private(m,x->i,x->j,xltog,y->i,y->j,yltog,nnz);
2106:   return(0);
2107: }

2109: PetscErrorCode MatAXPY_MPIAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2110: {
2112:   Mat_MPIAIJ     *xx = (Mat_MPIAIJ*)X->data,*yy = (Mat_MPIAIJ*)Y->data;
2113:   PetscBLASInt   bnz,one=1;
2114:   Mat_SeqAIJ     *x,*y;

2117:   if (str == SAME_NONZERO_PATTERN) {
2118:     PetscScalar alpha = a;
2119:     x    = (Mat_SeqAIJ*)xx->A->data;
2120:     PetscBLASIntCast(x->nz,&bnz);
2121:     y    = (Mat_SeqAIJ*)yy->A->data;
2122:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2123:     x    = (Mat_SeqAIJ*)xx->B->data;
2124:     y    = (Mat_SeqAIJ*)yy->B->data;
2125:     PetscBLASIntCast(x->nz,&bnz);
2126:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2127:     PetscObjectStateIncrease((PetscObject)Y);
2128:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2129:     MatAXPY_Basic(Y,a,X,str);
2130:   } else {
2131:     Mat      B;
2132:     PetscInt *nnz_d,*nnz_o;
2133:     PetscMalloc1(yy->A->rmap->N,&nnz_d);
2134:     PetscMalloc1(yy->B->rmap->N,&nnz_o);
2135:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2136:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2137:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2138:     MatSetBlockSizesFromMats(B,Y,Y);
2139:     MatSetType(B,MATMPIAIJ);
2140:     MatAXPYGetPreallocation_SeqAIJ(yy->A,xx->A,nnz_d);
2141:     MatAXPYGetPreallocation_MPIAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);
2142:     MatMPIAIJSetPreallocation(B,0,nnz_d,0,nnz_o);
2143:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2144:     MatHeaderReplace(Y,&B);
2145:     PetscFree(nnz_d);
2146:     PetscFree(nnz_o);
2147:   }
2148:   return(0);
2149: }

2151: extern PetscErrorCode  MatConjugate_SeqAIJ(Mat);

2153: PetscErrorCode  MatConjugate_MPIAIJ(Mat mat)
2154: {
2155: #if defined(PETSC_USE_COMPLEX)
2157:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2160:   MatConjugate_SeqAIJ(aij->A);
2161:   MatConjugate_SeqAIJ(aij->B);
2162: #else
2164: #endif
2165:   return(0);
2166: }

2168: PetscErrorCode MatRealPart_MPIAIJ(Mat A)
2169: {
2170:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2174:   MatRealPart(a->A);
2175:   MatRealPart(a->B);
2176:   return(0);
2177: }

2179: PetscErrorCode MatImaginaryPart_MPIAIJ(Mat A)
2180: {
2181:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2185:   MatImaginaryPart(a->A);
2186:   MatImaginaryPart(a->B);
2187:   return(0);
2188: }

2190: PetscErrorCode MatGetRowMaxAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2191: {
2192:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2194:   PetscInt       i,*idxb = 0;
2195:   PetscScalar    *va,*vb;
2196:   Vec            vtmp;

2199:   MatGetRowMaxAbs(a->A,v,idx);
2200:   VecGetArray(v,&va);
2201:   if (idx) {
2202:     for (i=0; i<A->rmap->n; i++) {
2203:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2204:     }
2205:   }

2207:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2208:   if (idx) {
2209:     PetscMalloc1(A->rmap->n,&idxb);
2210:   }
2211:   MatGetRowMaxAbs(a->B,vtmp,idxb);
2212:   VecGetArray(vtmp,&vb);

2214:   for (i=0; i<A->rmap->n; i++) {
2215:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
2216:       va[i] = vb[i];
2217:       if (idx) idx[i] = a->garray[idxb[i]];
2218:     }
2219:   }

2221:   VecRestoreArray(v,&va);
2222:   VecRestoreArray(vtmp,&vb);
2223:   PetscFree(idxb);
2224:   VecDestroy(&vtmp);
2225:   return(0);
2226: }

2228: PetscErrorCode MatGetRowMinAbs_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2229: {
2230:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
2232:   PetscInt       i,*idxb = 0;
2233:   PetscScalar    *va,*vb;
2234:   Vec            vtmp;

2237:   MatGetRowMinAbs(a->A,v,idx);
2238:   VecGetArray(v,&va);
2239:   if (idx) {
2240:     for (i=0; i<A->cmap->n; i++) {
2241:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
2242:     }
2243:   }

2245:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
2246:   if (idx) {
2247:     PetscMalloc1(A->rmap->n,&idxb);
2248:   }
2249:   MatGetRowMinAbs(a->B,vtmp,idxb);
2250:   VecGetArray(vtmp,&vb);

2252:   for (i=0; i<A->rmap->n; i++) {
2253:     if (PetscAbsScalar(va[i]) > PetscAbsScalar(vb[i])) {
2254:       va[i] = vb[i];
2255:       if (idx) idx[i] = a->garray[idxb[i]];
2256:     }
2257:   }

2259:   VecRestoreArray(v,&va);
2260:   VecRestoreArray(vtmp,&vb);
2261:   PetscFree(idxb);
2262:   VecDestroy(&vtmp);
2263:   return(0);
2264: }

2266: PetscErrorCode MatGetRowMin_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2267: {
2268:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2269:   PetscInt       n      = A->rmap->n;
2270:   PetscInt       cstart = A->cmap->rstart;
2271:   PetscInt       *cmap  = mat->garray;
2272:   PetscInt       *diagIdx, *offdiagIdx;
2273:   Vec            diagV, offdiagV;
2274:   PetscScalar    *a, *diagA, *offdiagA;
2275:   PetscInt       r;

2279:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2280:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &diagV);
2281:   VecCreateSeq(PetscObjectComm((PetscObject)A), n, &offdiagV);
2282:   MatGetRowMin(mat->A, diagV,    diagIdx);
2283:   MatGetRowMin(mat->B, offdiagV, offdiagIdx);
2284:   VecGetArray(v,        &a);
2285:   VecGetArray(diagV,    &diagA);
2286:   VecGetArray(offdiagV, &offdiagA);
2287:   for (r = 0; r < n; ++r) {
2288:     if (PetscAbsScalar(diagA[r]) <= PetscAbsScalar(offdiagA[r])) {
2289:       a[r]   = diagA[r];
2290:       idx[r] = cstart + diagIdx[r];
2291:     } else {
2292:       a[r]   = offdiagA[r];
2293:       idx[r] = cmap[offdiagIdx[r]];
2294:     }
2295:   }
2296:   VecRestoreArray(v,        &a);
2297:   VecRestoreArray(diagV,    &diagA);
2298:   VecRestoreArray(offdiagV, &offdiagA);
2299:   VecDestroy(&diagV);
2300:   VecDestroy(&offdiagV);
2301:   PetscFree2(diagIdx, offdiagIdx);
2302:   return(0);
2303: }

2305: PetscErrorCode MatGetRowMax_MPIAIJ(Mat A, Vec v, PetscInt idx[])
2306: {
2307:   Mat_MPIAIJ     *mat   = (Mat_MPIAIJ*) A->data;
2308:   PetscInt       n      = A->rmap->n;
2309:   PetscInt       cstart = A->cmap->rstart;
2310:   PetscInt       *cmap  = mat->garray;
2311:   PetscInt       *diagIdx, *offdiagIdx;
2312:   Vec            diagV, offdiagV;
2313:   PetscScalar    *a, *diagA, *offdiagA;
2314:   PetscInt       r;

2318:   PetscMalloc2(n,&diagIdx,n,&offdiagIdx);
2319:   VecCreateSeq(PETSC_COMM_SELF, n, &diagV);
2320:   VecCreateSeq(PETSC_COMM_SELF, n, &offdiagV);
2321:   MatGetRowMax(mat->A, diagV,    diagIdx);
2322:   MatGetRowMax(mat->B, offdiagV, offdiagIdx);
2323:   VecGetArray(v,        &a);
2324:   VecGetArray(diagV,    &diagA);
2325:   VecGetArray(offdiagV, &offdiagA);
2326:   for (r = 0; r < n; ++r) {
2327:     if (PetscAbsScalar(diagA[r]) >= PetscAbsScalar(offdiagA[r])) {
2328:       a[r]   = diagA[r];
2329:       idx[r] = cstart + diagIdx[r];
2330:     } else {
2331:       a[r]   = offdiagA[r];
2332:       idx[r] = cmap[offdiagIdx[r]];
2333:     }
2334:   }
2335:   VecRestoreArray(v,        &a);
2336:   VecRestoreArray(diagV,    &diagA);
2337:   VecRestoreArray(offdiagV, &offdiagA);
2338:   VecDestroy(&diagV);
2339:   VecDestroy(&offdiagV);
2340:   PetscFree2(diagIdx, offdiagIdx);
2341:   return(0);
2342: }

2344: PetscErrorCode MatGetSeqNonzeroStructure_MPIAIJ(Mat mat,Mat *newmat)
2345: {
2347:   Mat            *dummy;

2350:   MatGetSubMatrix_MPIAIJ_All(mat,MAT_DO_NOT_GET_VALUES,MAT_INITIAL_MATRIX,&dummy);
2351:   *newmat = *dummy;
2352:   PetscFree(dummy);
2353:   return(0);
2354: }

2356: PetscErrorCode  MatInvertBlockDiagonal_MPIAIJ(Mat A,const PetscScalar **values)
2357: {
2358:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*) A->data;

2362:   MatInvertBlockDiagonal(a->A,values);
2363:   A->factorerrortype = a->A->factorerrortype;
2364:   return(0);
2365: }

2367: static PetscErrorCode  MatSetRandom_MPIAIJ(Mat x,PetscRandom rctx)
2368: {
2370:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)x->data;

2373:   MatSetRandom(aij->A,rctx);
2374:   MatSetRandom(aij->B,rctx);
2375:   MatAssemblyBegin(x,MAT_FINAL_ASSEMBLY);
2376:   MatAssemblyEnd(x,MAT_FINAL_ASSEMBLY);
2377:   return(0);
2378: }

2380: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ(Mat A,PetscBool sc)
2381: {
2383:   if (sc) A->ops->increaseoverlap = MatIncreaseOverlap_MPIAIJ_Scalable;
2384:   else A->ops->increaseoverlap    = MatIncreaseOverlap_MPIAIJ;
2385:   return(0);
2386: }

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

2391:    Collective on Mat

2393:    Input Parameters:
2394: +    A - the matrix
2395: -    sc - PETSC_TRUE indicates use the scalable algorithm (default is not to use the scalable algorithm)

2397:  Level: advanced

2399: @*/
2400: PetscErrorCode MatMPIAIJSetUseScalableIncreaseOverlap(Mat A,PetscBool sc)
2401: {
2402:   PetscErrorCode       ierr;

2405:   PetscTryMethod(A,"MatMPIAIJSetUseScalableIncreaseOverlap_C",(Mat,PetscBool),(A,sc));
2406:   return(0);
2407: }

2409: PetscErrorCode MatSetFromOptions_MPIAIJ(PetscOptionItems *PetscOptionsObject,Mat A)
2410: {
2411:   PetscErrorCode       ierr;
2412:   PetscBool            sc = PETSC_FALSE,flg;

2415:   PetscOptionsHead(PetscOptionsObject,"MPIAIJ options");
2416:   PetscObjectOptionsBegin((PetscObject)A);
2417:     if (A->ops->increaseoverlap == MatIncreaseOverlap_MPIAIJ_Scalable) sc = PETSC_TRUE;
2418:     PetscOptionsBool("-mat_increase_overlap_scalable","Use a scalable algorithm to compute the overlap","MatIncreaseOverlap",sc,&sc,&flg);
2419:     if (flg) {
2420:       MatMPIAIJSetUseScalableIncreaseOverlap(A,sc);
2421:     }
2422:   PetscOptionsEnd();
2423:   return(0);
2424: }

2426: PetscErrorCode MatShift_MPIAIJ(Mat Y,PetscScalar a)
2427: {
2429:   Mat_MPIAIJ     *maij = (Mat_MPIAIJ*)Y->data;
2430:   Mat_SeqAIJ     *aij = (Mat_SeqAIJ*)maij->A->data;

2433:   if (!Y->preallocated) {
2434:     MatMPIAIJSetPreallocation(Y,1,NULL,0,NULL);
2435:   } else if (!aij->nz) {
2436:     PetscInt nonew = aij->nonew;
2437:     MatSeqAIJSetPreallocation(maij->A,1,NULL);
2438:     aij->nonew = nonew;
2439:   }
2440:   MatShift_Basic(Y,a);
2441:   return(0);
2442: }

2444: PetscErrorCode MatMissingDiagonal_MPIAIJ(Mat A,PetscBool  *missing,PetscInt *d)
2445: {
2446:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;

2450:   if (A->rmap->n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only works for square matrices");
2451:   MatMissingDiagonal(a->A,missing,d);
2452:   if (d) {
2453:     PetscInt rstart;
2454:     MatGetOwnershipRange(A,&rstart,NULL);
2455:     *d += rstart;

2457:   }
2458:   return(0);
2459: }


2462: /* -------------------------------------------------------------------*/
2463: static struct _MatOps MatOps_Values = {MatSetValues_MPIAIJ,
2464:                                        MatGetRow_MPIAIJ,
2465:                                        MatRestoreRow_MPIAIJ,
2466:                                        MatMult_MPIAIJ,
2467:                                 /* 4*/ MatMultAdd_MPIAIJ,
2468:                                        MatMultTranspose_MPIAIJ,
2469:                                        MatMultTransposeAdd_MPIAIJ,
2470:                                        0,
2471:                                        0,
2472:                                        0,
2473:                                 /*10*/ 0,
2474:                                        0,
2475:                                        0,
2476:                                        MatSOR_MPIAIJ,
2477:                                        MatTranspose_MPIAIJ,
2478:                                 /*15*/ MatGetInfo_MPIAIJ,
2479:                                        MatEqual_MPIAIJ,
2480:                                        MatGetDiagonal_MPIAIJ,
2481:                                        MatDiagonalScale_MPIAIJ,
2482:                                        MatNorm_MPIAIJ,
2483:                                 /*20*/ MatAssemblyBegin_MPIAIJ,
2484:                                        MatAssemblyEnd_MPIAIJ,
2485:                                        MatSetOption_MPIAIJ,
2486:                                        MatZeroEntries_MPIAIJ,
2487:                                 /*24*/ MatZeroRows_MPIAIJ,
2488:                                        0,
2489:                                        0,
2490:                                        0,
2491:                                        0,
2492:                                 /*29*/ MatSetUp_MPIAIJ,
2493:                                        0,
2494:                                        0,
2495:                                        MatGetDiagonalBlock_MPIAIJ,
2496:                                        0,
2497:                                 /*34*/ MatDuplicate_MPIAIJ,
2498:                                        0,
2499:                                        0,
2500:                                        0,
2501:                                        0,
2502:                                 /*39*/ MatAXPY_MPIAIJ,
2503:                                        MatGetSubMatrices_MPIAIJ,
2504:                                        MatIncreaseOverlap_MPIAIJ,
2505:                                        MatGetValues_MPIAIJ,
2506:                                        MatCopy_MPIAIJ,
2507:                                 /*44*/ MatGetRowMax_MPIAIJ,
2508:                                        MatScale_MPIAIJ,
2509:                                        MatShift_MPIAIJ,
2510:                                        MatDiagonalSet_MPIAIJ,
2511:                                        MatZeroRowsColumns_MPIAIJ,
2512:                                 /*49*/ MatSetRandom_MPIAIJ,
2513:                                        0,
2514:                                        0,
2515:                                        0,
2516:                                        0,
2517:                                 /*54*/ MatFDColoringCreate_MPIXAIJ,
2518:                                        0,
2519:                                        MatSetUnfactored_MPIAIJ,
2520:                                        MatPermute_MPIAIJ,
2521:                                        0,
2522:                                 /*59*/ MatGetSubMatrix_MPIAIJ,
2523:                                        MatDestroy_MPIAIJ,
2524:                                        MatView_MPIAIJ,
2525:                                        0,
2526:                                        MatMatMatMult_MPIAIJ_MPIAIJ_MPIAIJ,
2527:                                 /*64*/ MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ,
2528:                                        MatMatMatMultNumeric_MPIAIJ_MPIAIJ_MPIAIJ,
2529:                                        0,
2530:                                        0,
2531:                                        0,
2532:                                 /*69*/ MatGetRowMaxAbs_MPIAIJ,
2533:                                        MatGetRowMinAbs_MPIAIJ,
2534:                                        0,
2535:                                        0,
2536:                                        0,
2537:                                        0,
2538:                                 /*75*/ MatFDColoringApply_AIJ,
2539:                                        MatSetFromOptions_MPIAIJ,
2540:                                        0,
2541:                                        0,
2542:                                        MatFindZeroDiagonals_MPIAIJ,
2543:                                 /*80*/ 0,
2544:                                        0,
2545:                                        0,
2546:                                 /*83*/ MatLoad_MPIAIJ,
2547:                                        0,
2548:                                        0,
2549:                                        0,
2550:                                        0,
2551:                                        0,
2552:                                 /*89*/ MatMatMult_MPIAIJ_MPIAIJ,
2553:                                        MatMatMultSymbolic_MPIAIJ_MPIAIJ,
2554:                                        MatMatMultNumeric_MPIAIJ_MPIAIJ,
2555:                                        MatPtAP_MPIAIJ_MPIAIJ,
2556:                                        MatPtAPSymbolic_MPIAIJ_MPIAIJ,
2557:                                 /*94*/ MatPtAPNumeric_MPIAIJ_MPIAIJ,
2558:                                        0,
2559:                                        0,
2560:                                        0,
2561:                                        0,
2562:                                 /*99*/ 0,
2563:                                        0,
2564:                                        0,
2565:                                        MatConjugate_MPIAIJ,
2566:                                        0,
2567:                                 /*104*/MatSetValuesRow_MPIAIJ,
2568:                                        MatRealPart_MPIAIJ,
2569:                                        MatImaginaryPart_MPIAIJ,
2570:                                        0,
2571:                                        0,
2572:                                 /*109*/0,
2573:                                        0,
2574:                                        MatGetRowMin_MPIAIJ,
2575:                                        0,
2576:                                        MatMissingDiagonal_MPIAIJ,
2577:                                 /*114*/MatGetSeqNonzeroStructure_MPIAIJ,
2578:                                        0,
2579:                                        MatGetGhosts_MPIAIJ,
2580:                                        0,
2581:                                        0,
2582:                                 /*119*/0,
2583:                                        0,
2584:                                        0,
2585:                                        0,
2586:                                        MatGetMultiProcBlock_MPIAIJ,
2587:                                 /*124*/MatFindNonzeroRows_MPIAIJ,
2588:                                        MatGetColumnNorms_MPIAIJ,
2589:                                        MatInvertBlockDiagonal_MPIAIJ,
2590:                                        0,
2591:                                        MatGetSubMatricesMPI_MPIAIJ,
2592:                                 /*129*/0,
2593:                                        MatTransposeMatMult_MPIAIJ_MPIAIJ,
2594:                                        MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ,
2595:                                        MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ,
2596:                                        0,
2597:                                 /*134*/0,
2598:                                        0,
2599:                                        0,
2600:                                        0,
2601:                                        0,
2602:                                 /*139*/MatSetBlockSizes_MPIAIJ,
2603:                                        0,
2604:                                        0,
2605:                                        MatFDColoringSetUp_MPIXAIJ,
2606:                                        MatFindOffBlockDiagonalEntries_MPIAIJ,
2607:                                 /*144*/MatCreateMPIMatConcatenateSeqMat_MPIAIJ
2608: };

2610: /* ----------------------------------------------------------------------------------------*/

2612: PetscErrorCode  MatStoreValues_MPIAIJ(Mat mat)
2613: {
2614:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2618:   MatStoreValues(aij->A);
2619:   MatStoreValues(aij->B);
2620:   return(0);
2621: }

2623: PetscErrorCode  MatRetrieveValues_MPIAIJ(Mat mat)
2624: {
2625:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;

2629:   MatRetrieveValues(aij->A);
2630:   MatRetrieveValues(aij->B);
2631:   return(0);
2632: }

2634: PetscErrorCode  MatMPIAIJSetPreallocation_MPIAIJ(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
2635: {
2636:   Mat_MPIAIJ     *b;

2640:   PetscLayoutSetUp(B->rmap);
2641:   PetscLayoutSetUp(B->cmap);
2642:   b = (Mat_MPIAIJ*)B->data;

2644: #if defined(PETSC_USE_CTABLE)
2645:   PetscTableDestroy(&b->colmap);
2646: #else
2647:   PetscFree(b->colmap);
2648: #endif
2649:   PetscFree(b->garray);
2650:   VecDestroy(&b->lvec);
2651:   VecScatterDestroy(&b->Mvctx);

2653:   /* Because the B will have been resized we simply destroy it and create a new one each time */
2654:   MatDestroy(&b->B);
2655:   MatCreate(PETSC_COMM_SELF,&b->B);
2656:   MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);
2657:   MatSetBlockSizesFromMats(b->B,B,B);
2658:   MatSetType(b->B,MATSEQAIJ);
2659:   PetscLogObjectParent((PetscObject)B,(PetscObject)b->B);

2661:   if (!B->preallocated) {
2662:     MatCreate(PETSC_COMM_SELF,&b->A);
2663:     MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
2664:     MatSetBlockSizesFromMats(b->A,B,B);
2665:     MatSetType(b->A,MATSEQAIJ);
2666:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->A);
2667:   }

2669:   MatSeqAIJSetPreallocation(b->A,d_nz,d_nnz);
2670:   MatSeqAIJSetPreallocation(b->B,o_nz,o_nnz);
2671:   B->preallocated  = PETSC_TRUE;
2672:   B->was_assembled = PETSC_FALSE;
2673:   B->assembled     = PETSC_FALSE;;
2674:   return(0);
2675: }

2677: PetscErrorCode MatDuplicate_MPIAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
2678: {
2679:   Mat            mat;
2680:   Mat_MPIAIJ     *a,*oldmat = (Mat_MPIAIJ*)matin->data;

2684:   *newmat = 0;
2685:   MatCreate(PetscObjectComm((PetscObject)matin),&mat);
2686:   MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
2687:   MatSetBlockSizesFromMats(mat,matin,matin);
2688:   MatSetType(mat,((PetscObject)matin)->type_name);
2689:   PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));
2690:   a       = (Mat_MPIAIJ*)mat->data;

2692:   mat->factortype   = matin->factortype;
2693:   mat->assembled    = PETSC_TRUE;
2694:   mat->insertmode   = NOT_SET_VALUES;
2695:   mat->preallocated = PETSC_TRUE;

2697:   a->size         = oldmat->size;
2698:   a->rank         = oldmat->rank;
2699:   a->donotstash   = oldmat->donotstash;
2700:   a->roworiented  = oldmat->roworiented;
2701:   a->rowindices   = 0;
2702:   a->rowvalues    = 0;
2703:   a->getrowactive = PETSC_FALSE;

2705:   PetscLayoutReference(matin->rmap,&mat->rmap);
2706:   PetscLayoutReference(matin->cmap,&mat->cmap);

2708:   if (oldmat->colmap) {
2709: #if defined(PETSC_USE_CTABLE)
2710:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
2711: #else
2712:     PetscMalloc1(mat->cmap->N,&a->colmap);
2713:     PetscLogObjectMemory((PetscObject)mat,(mat->cmap->N)*sizeof(PetscInt));
2714:     PetscMemcpy(a->colmap,oldmat->colmap,(mat->cmap->N)*sizeof(PetscInt));
2715: #endif
2716:   } else a->colmap = 0;
2717:   if (oldmat->garray) {
2718:     PetscInt len;
2719:     len  = oldmat->B->cmap->n;
2720:     PetscMalloc1(len+1,&a->garray);
2721:     PetscLogObjectMemory((PetscObject)mat,len*sizeof(PetscInt));
2722:     if (len) { PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt)); }
2723:   } else a->garray = 0;

2725:   VecDuplicate(oldmat->lvec,&a->lvec);
2726:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
2727:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
2728:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);
2729:   MatDuplicate(oldmat->A,cpvalues,&a->A);
2730:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->A);
2731:   MatDuplicate(oldmat->B,cpvalues,&a->B);
2732:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->B);
2733:   PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
2734:   *newmat = mat;
2735:   return(0);
2736: }



2740: PetscErrorCode MatLoad_MPIAIJ(Mat newMat, PetscViewer viewer)
2741: {
2742:   PetscScalar    *vals,*svals;
2743:   MPI_Comm       comm;
2745:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
2746:   PetscInt       i,nz,j,rstart,rend,mmax,maxnz = 0;
2747:   PetscInt       header[4],*rowlengths = 0,M,N,m,*cols;
2748:   PetscInt       *ourlens = NULL,*procsnz = NULL,*offlens = NULL,jj,*mycols,*smycols;
2749:   PetscInt       cend,cstart,n,*rowners;
2750:   int            fd;
2751:   PetscInt       bs = newMat->rmap->bs;

2754:   /* force binary viewer to load .info file if it has not yet done so */
2755:   PetscViewerSetUp(viewer);
2756:   PetscObjectGetComm((PetscObject)viewer,&comm);
2757:   MPI_Comm_size(comm,&size);
2758:   MPI_Comm_rank(comm,&rank);
2759:   PetscViewerBinaryGetDescriptor(viewer,&fd);
2760:   if (!rank) {
2761:     PetscBinaryRead(fd,(char*)header,4,PETSC_INT);
2762:     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
2763:     if (header[3] < 0) SETERRQ(PetscObjectComm((PetscObject)newMat),PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format on disk,cannot load as MATMPIAIJ");
2764:   }

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

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

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

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

2783:   PetscMalloc1(size+1,&rowners);
2784:   MPI_Allgather(&m,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

2786:   /* First process needs enough room for process with most rows */
2787:   if (!rank) {
2788:     mmax = rowners[1];
2789:     for (i=2; i<=size; i++) {
2790:       mmax = PetscMax(mmax, rowners[i]);
2791:     }
2792:   } else mmax = -1;             /* unused, but compilers complain */

2794:   rowners[0] = 0;
2795:   for (i=2; i<=size; i++) {
2796:     rowners[i] += rowners[i-1];
2797:   }
2798:   rstart = rowners[rank];
2799:   rend   = rowners[rank+1];

2801:   /* distribute row lengths to all processors */
2802:   PetscMalloc2(m,&ourlens,m,&offlens);
2803:   if (!rank) {
2804:     PetscBinaryRead(fd,ourlens,m,PETSC_INT);
2805:     PetscMalloc1(mmax,&rowlengths);
2806:     PetscCalloc1(size,&procsnz);
2807:     for (j=0; j<m; j++) {
2808:       procsnz[0] += ourlens[j];
2809:     }
2810:     for (i=1; i<size; i++) {
2811:       PetscBinaryRead(fd,rowlengths,rowners[i+1]-rowners[i],PETSC_INT);
2812:       /* calculate the number of nonzeros on each processor */
2813:       for (j=0; j<rowners[i+1]-rowners[i]; j++) {
2814:         procsnz[i] += rowlengths[j];
2815:       }
2816:       MPIULong_Send(rowlengths,rowners[i+1]-rowners[i],MPIU_INT,i,tag,comm);
2817:     }
2818:     PetscFree(rowlengths);
2819:   } else {
2820:     MPIULong_Recv(ourlens,m,MPIU_INT,0,tag,comm);
2821:   }

2823:   if (!rank) {
2824:     /* determine max buffer needed and allocate it */
2825:     maxnz = 0;
2826:     for (i=0; i<size; i++) {
2827:       maxnz = PetscMax(maxnz,procsnz[i]);
2828:     }
2829:     PetscMalloc1(maxnz,&cols);

2831:     /* read in my part of the matrix column indices  */
2832:     nz   = procsnz[0];
2833:     PetscMalloc1(nz,&mycols);
2834:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);

2836:     /* read in every one elses and ship off */
2837:     for (i=1; i<size; i++) {
2838:       nz   = procsnz[i];
2839:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
2840:       MPIULong_Send(cols,nz,MPIU_INT,i,tag,comm);
2841:     }
2842:     PetscFree(cols);
2843:   } else {
2844:     /* determine buffer space needed for message */
2845:     nz = 0;
2846:     for (i=0; i<m; i++) {
2847:       nz += ourlens[i];
2848:     }
2849:     PetscMalloc1(nz,&mycols);

2851:     /* receive message of column indices*/
2852:     MPIULong_Recv(mycols,nz,MPIU_INT,0,tag,comm);
2853:   }

2855:   /* determine column ownership if matrix is not square */
2856:   if (N != M) {
2857:     if (newMat->cmap->n < 0) n = N/size + ((N % size) > rank);
2858:     else n = newMat->cmap->n;
2859:     MPI_Scan(&n,&cend,1,MPIU_INT,MPI_SUM,comm);
2860:     cstart = cend - n;
2861:   } else {
2862:     cstart = rstart;
2863:     cend   = rend;
2864:     n      = cend - cstart;
2865:   }

2867:   /* loop over local rows, determining number of off diagonal entries */
2868:   PetscMemzero(offlens,m*sizeof(PetscInt));
2869:   jj   = 0;
2870:   for (i=0; i<m; i++) {
2871:     for (j=0; j<ourlens[i]; j++) {
2872:       if (mycols[jj] < cstart || mycols[jj] >= cend) offlens[i]++;
2873:       jj++;
2874:     }
2875:   }

2877:   for (i=0; i<m; i++) {
2878:     ourlens[i] -= offlens[i];
2879:   }
2880:   MatSetSizes(newMat,m,n,M,N);

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

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

2886:   for (i=0; i<m; i++) {
2887:     ourlens[i] += offlens[i];
2888:   }

2890:   if (!rank) {
2891:     PetscMalloc1(maxnz+1,&vals);

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

2897:     /* insert into matrix */
2898:     jj      = rstart;
2899:     smycols = mycols;
2900:     svals   = vals;
2901:     for (i=0; i<m; i++) {
2902:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
2903:       smycols += ourlens[i];
2904:       svals   += ourlens[i];
2905:       jj++;
2906:     }

2908:     /* read in other processors and ship out */
2909:     for (i=1; i<size; i++) {
2910:       nz   = procsnz[i];
2911:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2912:       MPIULong_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newMat)->tag,comm);
2913:     }
2914:     PetscFree(procsnz);
2915:   } else {
2916:     /* receive numeric values */
2917:     PetscMalloc1(nz+1,&vals);

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

2922:     /* insert into matrix */
2923:     jj      = rstart;
2924:     smycols = mycols;
2925:     svals   = vals;
2926:     for (i=0; i<m; i++) {
2927:       MatSetValues_MPIAIJ(newMat,1,&jj,ourlens[i],smycols,svals,INSERT_VALUES);
2928:       smycols += ourlens[i];
2929:       svals   += ourlens[i];
2930:       jj++;
2931:     }
2932:   }
2933:   PetscFree2(ourlens,offlens);
2934:   PetscFree(vals);
2935:   PetscFree(mycols);
2936:   PetscFree(rowners);
2937:   MatAssemblyBegin(newMat,MAT_FINAL_ASSEMBLY);
2938:   MatAssemblyEnd(newMat,MAT_FINAL_ASSEMBLY);
2939:   return(0);
2940: }

2942: /* TODO: Not scalable because of ISAllGather() unless getting all columns. */
2943: PetscErrorCode MatGetSubMatrix_MPIAIJ(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *newmat)
2944: {
2946:   IS             iscol_local;
2947:   PetscInt       csize;

2950:   ISGetLocalSize(iscol,&csize);
2951:   if (call == MAT_REUSE_MATRIX) {
2952:     PetscObjectQuery((PetscObject)*newmat,"ISAllGather",(PetscObject*)&iscol_local);
2953:     if (!iscol_local) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
2954:   } else {
2955:     /* check if we are grabbing all columns*/
2956:     PetscBool    isstride;
2957:     PetscMPIInt  lisstride = 0,gisstride;
2958:     PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&isstride);
2959:     if (isstride) {
2960:       PetscInt  start,len,mstart,mlen;
2961:       ISStrideGetInfo(iscol,&start,NULL);
2962:       ISGetLocalSize(iscol,&len);
2963:       MatGetOwnershipRangeColumn(mat,&mstart,&mlen);
2964:       if (mstart == start && mlen-mstart == len) lisstride = 1;
2965:     }
2966:     MPIU_Allreduce(&lisstride,&gisstride,1,MPI_INT,MPI_MIN,PetscObjectComm((PetscObject)mat));
2967:     if (gisstride) {
2968:       PetscInt N;
2969:       MatGetSize(mat,NULL,&N);
2970:       ISCreateStride(PetscObjectComm((PetscObject)mat),N,0,1,&iscol_local);
2971:       ISSetIdentity(iscol_local);
2972:       PetscInfo(mat,"Optimizing for obtaining all columns of the matrix; skipping ISAllGather()\n");
2973:     } else {
2974:       PetscInt cbs;
2975:       ISGetBlockSize(iscol,&cbs);
2976:       ISAllGather(iscol,&iscol_local);
2977:       ISSetBlockSize(iscol_local,cbs);
2978:     }
2979:   }
2980:   MatGetSubMatrix_MPIAIJ_Private(mat,isrow,iscol_local,csize,call,newmat);
2981:   if (call == MAT_INITIAL_MATRIX) {
2982:     PetscObjectCompose((PetscObject)*newmat,"ISAllGather",(PetscObject)iscol_local);
2983:     ISDestroy(&iscol_local);
2984:   }
2985:   return(0);
2986: }

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

2994:   Note: This requires a sequential iscol with all indices.
2995: */
2996: PetscErrorCode MatGetSubMatrix_MPIAIJ_Private(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
2997: {
2999:   PetscMPIInt    rank,size;
3000:   PetscInt       i,m,n,rstart,row,rend,nz,*cwork,j,bs,cbs;
3001:   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal;
3002:   Mat            M,Mreuse;
3003:   MatScalar      *vwork,*aa;
3004:   MPI_Comm       comm;
3005:   Mat_SeqAIJ     *aij;

3008:   PetscObjectGetComm((PetscObject)mat,&comm);
3009:   MPI_Comm_rank(comm,&rank);
3010:   MPI_Comm_size(comm,&size);

3012:   if (call ==  MAT_REUSE_MATRIX) {
3013:     PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Mreuse);
3014:     if (!Mreuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
3015:     MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_REUSE_MATRIX,&Mreuse);
3016:   } else {
3017:     MatGetSubMatrices_MPIAIJ_Local(mat,1,&isrow,&iscol,MAT_INITIAL_MATRIX,&Mreuse);
3018:   }

3020:   /*
3021:       m - number of local rows
3022:       n - number of columns (same on all processors)
3023:       rstart - first row in new global matrix generated
3024:   */
3025:   MatGetSize(Mreuse,&m,&n);
3026:   MatGetBlockSizes(Mreuse,&bs,&cbs);
3027:   if (call == MAT_INITIAL_MATRIX) {
3028:     aij = (Mat_SeqAIJ*)(Mreuse)->data;
3029:     ii  = aij->i;
3030:     jj  = aij->j;

3032:     /*
3033:         Determine the number of non-zeros in the diagonal and off-diagonal
3034:         portions of the matrix in order to do correct preallocation
3035:     */

3037:     /* first get start and end of "diagonal" columns */
3038:     if (csize == PETSC_DECIDE) {
3039:       ISGetSize(isrow,&mglobal);
3040:       if (mglobal == n) { /* square matrix */
3041:         nlocal = m;
3042:       } else {
3043:         nlocal = n/size + ((n % size) > rank);
3044:       }
3045:     } else {
3046:       nlocal = csize;
3047:     }
3048:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
3049:     rstart = rend - nlocal;
3050:     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);

3052:     /* next, compute all the lengths */
3053:     PetscMalloc1(2*m+1,&dlens);
3054:     olens = dlens + m;
3055:     for (i=0; i<m; i++) {
3056:       jend = ii[i+1] - ii[i];
3057:       olen = 0;
3058:       dlen = 0;
3059:       for (j=0; j<jend; j++) {
3060:         if (*jj < rstart || *jj >= rend) olen++;
3061:         else dlen++;
3062:         jj++;
3063:       }
3064:       olens[i] = olen;
3065:       dlens[i] = dlen;
3066:     }
3067:     MatCreate(comm,&M);
3068:     MatSetSizes(M,m,nlocal,PETSC_DECIDE,n);
3069:     MatSetBlockSizes(M,bs,cbs);
3070:     MatSetType(M,((PetscObject)mat)->type_name);
3071:     MatMPIAIJSetPreallocation(M,0,dlens,0,olens);
3072:     PetscFree(dlens);
3073:   } else {
3074:     PetscInt ml,nl;

3076:     M    = *newmat;
3077:     MatGetLocalSize(M,&ml,&nl);
3078:     if (ml != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
3079:     MatZeroEntries(M);
3080:     /*
3081:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
3082:        rather than the slower MatSetValues().
3083:     */
3084:     M->was_assembled = PETSC_TRUE;
3085:     M->assembled     = PETSC_FALSE;
3086:   }
3087:   MatGetOwnershipRange(M,&rstart,&rend);
3088:   aij  = (Mat_SeqAIJ*)(Mreuse)->data;
3089:   ii   = aij->i;
3090:   jj   = aij->j;
3091:   aa   = aij->a;
3092:   for (i=0; i<m; i++) {
3093:     row   = rstart + i;
3094:     nz    = ii[i+1] - ii[i];
3095:     cwork = jj;     jj += nz;
3096:     vwork = aa;     aa += nz;
3097:     MatSetValues_MPIAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);
3098:   }

3100:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
3101:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
3102:   *newmat = M;

3104:   /* save submatrix used in processor for next request */
3105:   if (call ==  MAT_INITIAL_MATRIX) {
3106:     PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);
3107:     MatDestroy(&Mreuse);
3108:   }
3109:   return(0);
3110: }

3112: PetscErrorCode  MatMPIAIJSetPreallocationCSR_MPIAIJ(Mat B,const PetscInt Ii[],const PetscInt J[],const PetscScalar v[])
3113: {
3114:   PetscInt       m,cstart, cend,j,nnz,i,d;
3115:   PetscInt       *d_nnz,*o_nnz,nnz_max = 0,rstart,ii;
3116:   const PetscInt *JJ;
3117:   PetscScalar    *values;

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

3123:   PetscLayoutSetUp(B->rmap);
3124:   PetscLayoutSetUp(B->cmap);
3125:   m      = B->rmap->n;
3126:   cstart = B->cmap->rstart;
3127:   cend   = B->cmap->rend;
3128:   rstart = B->rmap->rstart;

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

3132: #if defined(PETSC_USE_DEBUGGING)
3133:   for (i=0; i<m; i++) {
3134:     nnz = Ii[i+1]- Ii[i];
3135:     JJ  = J + Ii[i];
3136:     if (nnz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative %D number of columns",i,nnz);
3137:     if (nnz && (JJ[0] < 0)) SETERRRQ1(PETSC_ERR_ARG_WRONGSTATE,"Row %D starts with negative column index",i,j);
3138:     if (nnz && (JJ[nnz-1] >= B->cmap->N) SETERRRQ3(PETSC_ERR_ARG_WRONGSTATE,"Row %D ends with too large a column index %D (max allowed %D)",i,JJ[nnz-1],B->cmap->N);
3139:   }
3140: #endif

3142:   for (i=0; i<m; i++) {
3143:     nnz     = Ii[i+1]- Ii[i];
3144:     JJ      = J + Ii[i];
3145:     nnz_max = PetscMax(nnz_max,nnz);
3146:     d       = 0;
3147:     for (j=0; j<nnz; j++) {
3148:       if (cstart <= JJ[j] && JJ[j] < cend) d++;
3149:     }
3150:     d_nnz[i] = d;
3151:     o_nnz[i] = nnz - d;
3152:   }
3153:   MatMPIAIJSetPreallocation(B,0,d_nnz,0,o_nnz);
3154:   PetscFree2(d_nnz,o_nnz);

3156:   if (v) values = (PetscScalar*)v;
3157:   else {
3158:     PetscCalloc1(nnz_max+1,&values);
3159:   }

3161:   for (i=0; i<m; i++) {
3162:     ii   = i + rstart;
3163:     nnz  = Ii[i+1]- Ii[i];
3164:     MatSetValues_MPIAIJ(B,1,&ii,nnz,J+Ii[i],values+(v ? Ii[i] : 0),INSERT_VALUES);
3165:   }
3166:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3167:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

3169:   if (!v) {
3170:     PetscFree(values);
3171:   }
3172:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
3173:   return(0);
3174: }

3176: /*@
3177:    MatMPIAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in AIJ format
3178:    (the default parallel PETSc format).

3180:    Collective on MPI_Comm

3182:    Input Parameters:
3183: +  B - the matrix
3184: .  i - the indices into j for the start of each local row (starts with zero)
3185: .  j - the column indices for each local row (starts with zero)
3186: -  v - optional values in the matrix

3188:    Level: developer

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

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

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

3201: $        1 0 0
3202: $        2 0 3     P0
3203: $       -------
3204: $        4 5 6     P1
3205: $
3206: $     Process0 [P0]: rows_owned=[0,1]
3207: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
3208: $        j =  {0,0,2}  [size = 3]
3209: $        v =  {1,2,3}  [size = 3]
3210: $
3211: $     Process1 [P1]: rows_owned=[2]
3212: $        i =  {0,3}    [size = nrow+1  = 1+1]
3213: $        j =  {0,1,2}  [size = 3]
3214: $        v =  {4,5,6}  [size = 3]

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

3218: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatCreateAIJ(), MATMPIAIJ,
3219:           MatCreateSeqAIJWithArrays(), MatCreateMPIAIJWithSplitArrays()
3220: @*/
3221: PetscErrorCode  MatMPIAIJSetPreallocationCSR(Mat B,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
3222: {

3226:   PetscTryMethod(B,"MatMPIAIJSetPreallocationCSR_C",(Mat,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,i,j,v));
3227:   return(0);
3228: }

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

3237:    Collective on MPI_Comm

3239:    Input Parameters:
3240: +  B - the matrix
3241: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
3242:            (same value is used for all local rows)
3243: .  d_nnz - array containing the number of nonzeros in the various rows of the
3244:            DIAGONAL portion of the local submatrix (possibly different for each row)
3245:            or NULL (PETSC_NULL_INTEGER in Fortran), if d_nz is used to specify the nonzero structure.
3246:            The size of this array is equal to the number of local rows, i.e 'm'.
3247:            For matrices that will be factored, you must leave room for (and set)
3248:            the diagonal entry even if it is zero.
3249: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
3250:            submatrix (same value is used for all local rows).
3251: -  o_nnz - array containing the number of nonzeros in the various rows of the
3252:            OFF-DIAGONAL portion of the local submatrix (possibly different for
3253:            each row) or NULL (PETSC_NULL_INTEGER in Fortran), if o_nz is used to specify the nonzero
3254:            structure. The size of this array is equal to the number
3255:            of local rows, i.e 'm'.

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

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

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

3268:    The DIAGONAL portion of the local submatrix of a processor can be defined
3269:    as the submatrix which is obtained by extraction the part corresponding to
3270:    the rows r1-r2 and columns c1-c2 of the global matrix, where r1 is the
3271:    first row that belongs to the processor, r2 is the last row belonging to
3272:    the this processor, and c1-c2 is range of indices of the local part of a
3273:    vector suitable for applying the matrix to.  This is an mxn matrix.  In the
3274:    common case of a square matrix, the row and column ranges are the same and
3275:    the DIAGONAL part is also square. The remaining portion of the local
3276:    submatrix (mxN) constitute the OFF-DIAGONAL portion.

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

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

3285:    Example usage:

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

3292: .vb
3293:             1  2  0  |  0  3  0  |  0  4
3294:     Proc0   0  5  6  |  7  0  0  |  8  0
3295:             9  0 10  | 11  0  0  | 12  0
3296:     -------------------------------------
3297:            13  0 14  | 15 16 17  |  0  0
3298:     Proc1   0 18  0  | 19 20 21  |  0  0
3299:             0  0  0  | 22 23  0  | 24  0
3300:     -------------------------------------
3301:     Proc2  25 26 27  |  0  0 28  | 29  0
3302:            30  0  0  | 31 32 33  |  0 34
3303: .ve

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

3307: .vb
3308:       A B C
3309:       D E F
3310:       G H I
3311: .ve

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

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

3320:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
3321:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
3322:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
3323:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
3324:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
3325:    matrix, ans [DF] as another SeqAIJ matrix.

3327:    When d_nz, o_nz parameters are specified, d_nz storage elements are
3328:    allocated for every row of the local diagonal submatrix, and o_nz
3329:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
3330:    One way to choose d_nz and o_nz is to use the max nonzerors per local
3331:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
3332:    In this case, the values of d_nz,o_nz are:
3333: .vb
3334:      proc0 : dnz = 2, o_nz = 2
3335:      proc1 : dnz = 3, o_nz = 2
3336:      proc2 : dnz = 1, o_nz = 4
3337: .ve
3338:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
3339:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
3340:    for proc3. i.e we are using 12+15+10=37 storage locations to store
3341:    34 values.

3343:    When d_nnz, o_nnz parameters are specified, the storage is specified
3344:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
3345:    In the above case the values for d_nnz,o_nnz are:
3346: .vb
3347:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
3348:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
3349:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
3350: .ve
3351:    Here the space allocated is sum of all the above values i.e 34, and
3352:    hence pre-allocation is perfect.

3354:    Level: intermediate

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

3358: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatCreateAIJ(), MatMPIAIJSetPreallocationCSR(),
3359:           MATMPIAIJ, MatGetInfo(), PetscSplitOwnership()
3360: @*/
3361: PetscErrorCode  MatMPIAIJSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3362: {

3368:   PetscTryMethod(B,"MatMPIAIJSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
3369:   return(0);
3370: }

3372: /*@
3373:      MatCreateMPIAIJWithArrays - creates a MPI AIJ matrix using arrays that contain in standard
3374:          CSR format the local rows.

3376:    Collective on MPI_Comm

3378:    Input Parameters:
3379: +  comm - MPI communicator
3380: .  m - number of local rows (Cannot be PETSC_DECIDE)
3381: .  n - This value should be the same as the local size used in creating the
3382:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
3383:        calculated if N is given) For square matrices n is almost always m.
3384: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3385: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3386: .   i - row indices
3387: .   j - column indices
3388: -   a - matrix values

3390:    Output Parameter:
3391: .   mat - the matrix

3393:    Level: intermediate

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

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

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

3406: $        1 0 0
3407: $        2 0 3     P0
3408: $       -------
3409: $        4 5 6     P1
3410: $
3411: $     Process0 [P0]: rows_owned=[0,1]
3412: $        i =  {0,1,3}  [size = nrow+1  = 2+1]
3413: $        j =  {0,0,2}  [size = 3]
3414: $        v =  {1,2,3}  [size = 3]
3415: $
3416: $     Process1 [P1]: rows_owned=[2]
3417: $        i =  {0,3}    [size = nrow+1  = 1+1]
3418: $        j =  {0,1,2}  [size = 3]
3419: $        v =  {4,5,6}  [size = 3]

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

3423: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
3424:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
3425: @*/
3426: PetscErrorCode  MatCreateMPIAIJWithArrays(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
3427: {

3431:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
3432:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
3433:   MatCreate(comm,mat);
3434:   MatSetSizes(*mat,m,n,M,N);
3435:   /* MatSetBlockSizes(M,bs,cbs); */
3436:   MatSetType(*mat,MATMPIAIJ);
3437:   MatMPIAIJSetPreallocationCSR(*mat,i,j,a);
3438:   return(0);
3439: }

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

3448:    Collective on MPI_Comm

3450:    Input Parameters:
3451: +  comm - MPI communicator
3452: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
3453:            This value should be the same as the local size used in creating the
3454:            y vector for the matrix-vector product y = Ax.
3455: .  n - This value should be the same as the local size used in creating the
3456:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
3457:        calculated if N is given) For square matrices n is almost always m.
3458: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3459: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3460: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
3461:            (same value is used for all local rows)
3462: .  d_nnz - array containing the number of nonzeros in the various rows of the
3463:            DIAGONAL portion of the local submatrix (possibly different for each row)
3464:            or NULL, if d_nz is used to specify the nonzero structure.
3465:            The size of this array is equal to the number of local rows, i.e 'm'.
3466: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
3467:            submatrix (same value is used for all local rows).
3468: -  o_nnz - array containing the number of nonzeros in the various rows of the
3469:            OFF-DIAGONAL portion of the local submatrix (possibly different for
3470:            each row) or NULL, if o_nz is used to specify the nonzero
3471:            structure. The size of this array is equal to the number
3472:            of local rows, i.e 'm'.

3474:    Output Parameter:
3475: .  A - the matrix

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

3481:    Notes:
3482:    If the *_nnz parameter is given then the *_nz parameter is ignored

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

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

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

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

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

3505:    The DIAGONAL portion of the local submatrix on any given processor
3506:    is the submatrix corresponding to the rows and columns m,n
3507:    corresponding to the given processor. i.e diagonal matrix on
3508:    process 0 is [m0 x n0], diagonal matrix on process 1 is [m1 x n1]
3509:    etc. The remaining portion of the local submatrix [m x (N-n)]
3510:    constitute the OFF-DIAGONAL portion. The example below better
3511:    illustrates this concept.

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

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

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

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

3529:    Options Database Keys:
3530: +  -mat_no_inode  - Do not use inodes
3531: .  -mat_inode_limit <limit> - Sets inode limit (max limit=5)
3532: -  -mat_aij_oneindex - Internally use indexing starting at 1
3533:         rather than 0.  Note that when calling MatSetValues(),
3534:         the user still MUST index entries starting at 0!


3537:    Example usage:

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

3544: .vb
3545:             1  2  0  |  0  3  0  |  0  4
3546:     Proc0   0  5  6  |  7  0  0  |  8  0
3547:             9  0 10  | 11  0  0  | 12  0
3548:     -------------------------------------
3549:            13  0 14  | 15 16 17  |  0  0
3550:     Proc1   0 18  0  | 19 20 21  |  0  0
3551:             0  0  0  | 22 23  0  | 24  0
3552:     -------------------------------------
3553:     Proc2  25 26 27  |  0  0 28  | 29  0
3554:            30  0  0  | 31 32 33  |  0 34
3555: .ve

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

3559: .vb
3560:       A B C
3561:       D E F
3562:       G H I
3563: .ve

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

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

3572:    The DIAGONAL submatrices corresponding to proc0,proc1,proc2 are
3573:    submatrices [A], [E], [I] respectively. The OFF-DIAGONAL submatrices
3574:    corresponding to proc0,proc1,proc2 are [BC], [DF], [GH] respectively.
3575:    Internally, each processor stores the DIAGONAL part, and the OFF-DIAGONAL
3576:    part as SeqAIJ matrices. for eg: proc1 will store [E] as a SeqAIJ
3577:    matrix, ans [DF] as another SeqAIJ matrix.

3579:    When d_nz, o_nz parameters are specified, d_nz storage elements are
3580:    allocated for every row of the local diagonal submatrix, and o_nz
3581:    storage locations are allocated for every row of the OFF-DIAGONAL submat.
3582:    One way to choose d_nz and o_nz is to use the max nonzerors per local
3583:    rows for each of the local DIAGONAL, and the OFF-DIAGONAL submatrices.
3584:    In this case, the values of d_nz,o_nz are:
3585: .vb
3586:      proc0 : dnz = 2, o_nz = 2
3587:      proc1 : dnz = 3, o_nz = 2
3588:      proc2 : dnz = 1, o_nz = 4
3589: .ve
3590:    We are allocating m*(d_nz+o_nz) storage locations for every proc. This
3591:    translates to 3*(2+2)=12 for proc0, 3*(3+2)=15 for proc1, 2*(1+4)=10
3592:    for proc3. i.e we are using 12+15+10=37 storage locations to store
3593:    34 values.

3595:    When d_nnz, o_nnz parameters are specified, the storage is specified
3596:    for every row, coresponding to both DIAGONAL and OFF-DIAGONAL submatrices.
3597:    In the above case the values for d_nnz,o_nnz are:
3598: .vb
3599:      proc0: d_nnz = [2,2,2] and o_nnz = [2,2,2]
3600:      proc1: d_nnz = [3,3,2] and o_nnz = [2,1,1]
3601:      proc2: d_nnz = [1,1]   and o_nnz = [4,4]
3602: .ve
3603:    Here the space allocated is sum of all the above values i.e 34, and
3604:    hence pre-allocation is perfect.

3606:    Level: intermediate

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

3610: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
3611:           MATMPIAIJ, MatCreateMPIAIJWithArrays()
3612: @*/
3613: 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)
3614: {
3616:   PetscMPIInt    size;

3619:   MatCreate(comm,A);
3620:   MatSetSizes(*A,m,n,M,N);
3621:   MPI_Comm_size(comm,&size);
3622:   if (size > 1) {
3623:     MatSetType(*A,MATMPIAIJ);
3624:     MatMPIAIJSetPreallocation(*A,d_nz,d_nnz,o_nz,o_nnz);
3625:   } else {
3626:     MatSetType(*A,MATSEQAIJ);
3627:     MatSeqAIJSetPreallocation(*A,d_nz,d_nnz);
3628:   }
3629:   return(0);
3630: }

3632: PetscErrorCode  MatMPIAIJGetSeqAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
3633: {
3634:   Mat_MPIAIJ     *a = (Mat_MPIAIJ*)A->data;
3635:   PetscBool      flg;
3637: 
3639:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&flg);
3640:   if (!flg) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"This function requires a MATMPIAIJ matrix as input");
3641:   if (Ad)     *Ad     = a->A;
3642:   if (Ao)     *Ao     = a->B;
3643:   if (colmap) *colmap = a->garray;
3644:   return(0);
3645: }

3647: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
3648: {
3650:   PetscInt       m,N,i,rstart,nnz,Ii;
3651:   PetscInt       *indx;
3652:   PetscScalar    *values;

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

3659:     if (n == PETSC_DECIDE) {
3660:       PetscSplitOwnership(comm,&n,&N);
3661:     }
3662:     /* Check sum(n) = N */
3663:     MPIU_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);
3664:     if (sum != N) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns != global columns %d",N);

3666:     MPI_Scan(&m, &rstart,1,MPIU_INT,MPI_SUM,comm);
3667:     rstart -= m;

3669:     MatPreallocateInitialize(comm,m,n,dnz,onz);
3670:     for (i=0; i<m; i++) {
3671:       MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
3672:       MatPreallocateSet(i+rstart,nnz,indx,dnz,onz);
3673:       MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,NULL);
3674:     }

3676:     MatCreate(comm,outmat);
3677:     MatSetSizes(*outmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
3678:     MatGetBlockSizes(inmat,&bs,&cbs);
3679:     MatSetBlockSizes(*outmat,bs,cbs);
3680:     MatSetType(*outmat,MATAIJ);
3681:     MatSeqAIJSetPreallocation(*outmat,0,dnz);
3682:     MatMPIAIJSetPreallocation(*outmat,0,dnz,0,onz);
3683:     MatPreallocateFinalize(dnz,onz);
3684:   }

3686:   /* numeric phase */
3687:   MatGetOwnershipRange(*outmat,&rstart,NULL);
3688:   for (i=0; i<m; i++) {
3689:     MatGetRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
3690:     Ii   = i + rstart;
3691:     MatSetValues(*outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
3692:     MatRestoreRow_SeqAIJ(inmat,i,&nnz,&indx,&values);
3693:   }
3694:   MatAssemblyBegin(*outmat,MAT_FINAL_ASSEMBLY);
3695:   MatAssemblyEnd(*outmat,MAT_FINAL_ASSEMBLY);
3696:   return(0);
3697: }

3699: PetscErrorCode MatFileSplit(Mat A,char *outfile)
3700: {
3701:   PetscErrorCode    ierr;
3702:   PetscMPIInt       rank;
3703:   PetscInt          m,N,i,rstart,nnz;
3704:   size_t            len;
3705:   const PetscInt    *indx;
3706:   PetscViewer       out;
3707:   char              *name;
3708:   Mat               B;
3709:   const PetscScalar *values;

3712:   MatGetLocalSize(A,&m,0);
3713:   MatGetSize(A,0,&N);
3714:   /* Should this be the type of the diagonal block of A? */
3715:   MatCreate(PETSC_COMM_SELF,&B);
3716:   MatSetSizes(B,m,N,m,N);
3717:   MatSetBlockSizesFromMats(B,A,A);
3718:   MatSetType(B,MATSEQAIJ);
3719:   MatSeqAIJSetPreallocation(B,0,NULL);
3720:   MatGetOwnershipRange(A,&rstart,0);
3721:   for (i=0; i<m; i++) {
3722:     MatGetRow(A,i+rstart,&nnz,&indx,&values);
3723:     MatSetValues(B,1,&i,nnz,indx,values,INSERT_VALUES);
3724:     MatRestoreRow(A,i+rstart,&nnz,&indx,&values);
3725:   }
3726:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3727:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

3729:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);
3730:   PetscStrlen(outfile,&len);
3731:   PetscMalloc1(len+5,&name);
3732:   sprintf(name,"%s.%d",outfile,rank);
3733:   PetscViewerBinaryOpen(PETSC_COMM_SELF,name,FILE_MODE_APPEND,&out);
3734:   PetscFree(name);
3735:   MatView(B,out);
3736:   PetscViewerDestroy(&out);
3737:   MatDestroy(&B);
3738:   return(0);
3739: }

3741: extern PetscErrorCode MatDestroy_MPIAIJ(Mat);
3742: PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat A)
3743: {
3744:   PetscErrorCode      ierr;
3745:   Mat_Merge_SeqsToMPI *merge;
3746:   PetscContainer      container;

3749:   PetscObjectQuery((PetscObject)A,"MatMergeSeqsToMPI",(PetscObject*)&container);
3750:   if (container) {
3751:     PetscContainerGetPointer(container,(void**)&merge);
3752:     PetscFree(merge->id_r);
3753:     PetscFree(merge->len_s);
3754:     PetscFree(merge->len_r);
3755:     PetscFree(merge->bi);
3756:     PetscFree(merge->bj);
3757:     PetscFree(merge->buf_ri[0]);
3758:     PetscFree(merge->buf_ri);
3759:     PetscFree(merge->buf_rj[0]);
3760:     PetscFree(merge->buf_rj);
3761:     PetscFree(merge->coi);
3762:     PetscFree(merge->coj);
3763:     PetscFree(merge->owners_co);
3764:     PetscLayoutDestroy(&merge->rowmap);
3765:     PetscFree(merge);
3766:     PetscObjectCompose((PetscObject)A,"MatMergeSeqsToMPI",0);
3767:   }
3768:   MatDestroy_MPIAIJ(A);
3769:   return(0);
3770: }

3772:  #include <../src/mat/utils/freespace.h>
3773:  #include <petscbt.h>

3775: PetscErrorCode  MatCreateMPIAIJSumSeqAIJNumeric(Mat seqmat,Mat mpimat)
3776: {
3777:   PetscErrorCode      ierr;
3778:   MPI_Comm            comm;
3779:   Mat_SeqAIJ          *a  =(Mat_SeqAIJ*)seqmat->data;
3780:   PetscMPIInt         size,rank,taga,*len_s;
3781:   PetscInt            N=mpimat->cmap->N,i,j,*owners,*ai=a->i,*aj;
3782:   PetscInt            proc,m;
3783:   PetscInt            **buf_ri,**buf_rj;
3784:   PetscInt            k,anzi,*bj_i,*bi,*bj,arow,bnzi,nextaj;
3785:   PetscInt            nrows,**buf_ri_k,**nextrow,**nextai;
3786:   MPI_Request         *s_waits,*r_waits;
3787:   MPI_Status          *status;
3788:   MatScalar           *aa=a->a;
3789:   MatScalar           **abuf_r,*ba_i;
3790:   Mat_Merge_SeqsToMPI *merge;
3791:   PetscContainer      container;

3794:   PetscObjectGetComm((PetscObject)mpimat,&comm);
3795:   PetscLogEventBegin(MAT_Seqstompinum,seqmat,0,0,0);

3797:   MPI_Comm_size(comm,&size);
3798:   MPI_Comm_rank(comm,&rank);

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

3803:   bi     = merge->bi;
3804:   bj     = merge->bj;
3805:   buf_ri = merge->buf_ri;
3806:   buf_rj = merge->buf_rj;

3808:   PetscMalloc1(size,&status);
3809:   owners = merge->rowmap->range;
3810:   len_s  = merge->len_s;

3812:   /* send and recv matrix values */
3813:   /*-----------------------------*/
3814:   PetscObjectGetNewTag((PetscObject)mpimat,&taga);
3815:   PetscPostIrecvScalar(comm,taga,merge->nrecv,merge->id_r,merge->len_r,&abuf_r,&r_waits);

3817:   PetscMalloc1(merge->nsend+1,&s_waits);
3818:   for (proc=0,k=0; proc<size; proc++) {
3819:     if (!len_s[proc]) continue;
3820:     i    = owners[proc];
3821:     MPI_Isend(aa+ai[i],len_s[proc],MPIU_MATSCALAR,proc,taga,comm,s_waits+k);
3822:     k++;
3823:   }

3825:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,r_waits,status);}
3826:   if (merge->nsend) {MPI_Waitall(merge->nsend,s_waits,status);}
3827:   PetscFree(status);

3829:   PetscFree(s_waits);
3830:   PetscFree(r_waits);

3832:   /* insert mat values of mpimat */
3833:   /*----------------------------*/
3834:   PetscMalloc1(N,&ba_i);
3835:   PetscMalloc3(merge->nrecv,&buf_ri_k,merge->nrecv,&nextrow,merge->nrecv,&nextai);

3837:   for (k=0; k<merge->nrecv; k++) {
3838:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
3839:     nrows       = *(buf_ri_k[k]);
3840:     nextrow[k]  = buf_ri_k[k]+1;  /* next row number of k-th recved i-structure */
3841:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
3842:   }

3844:   /* set values of ba */
3845:   m = merge->rowmap->n;
3846:   for (i=0; i<m; i++) {
3847:     arow = owners[rank] + i;
3848:     bj_i = bj+bi[i];  /* col indices of the i-th row of mpimat */
3849:     bnzi = bi[i+1] - bi[i];
3850:     PetscMemzero(ba_i,bnzi*sizeof(PetscScalar));

3852:     /* add local non-zero vals of this proc's seqmat into ba */
3853:     anzi   = ai[arow+1] - ai[arow];
3854:     aj     = a->j + ai[arow];
3855:     aa     = a->a + ai[arow];
3856:     nextaj = 0;
3857:     for (j=0; nextaj<anzi; j++) {
3858:       if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
3859:         ba_i[j] += aa[nextaj++];
3860:       }
3861:     }

3863:     /* add received vals into ba */
3864:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
3865:       /* i-th row */
3866:       if (i == *nextrow[k]) {
3867:         anzi   = *(nextai[k]+1) - *nextai[k];
3868:         aj     = buf_rj[k] + *(nextai[k]);
3869:         aa     = abuf_r[k] + *(nextai[k]);
3870:         nextaj = 0;
3871:         for (j=0; nextaj<anzi; j++) {
3872:           if (*(bj_i + j) == aj[nextaj]) { /* bcol == acol */
3873:             ba_i[j] += aa[nextaj++];
3874:           }
3875:         }
3876:         nextrow[k]++; nextai[k]++;
3877:       }
3878:     }
3879:     MatSetValues(mpimat,1,&arow,bnzi,bj_i,ba_i,INSERT_VALUES);
3880:   }
3881:   MatAssemblyBegin(mpimat,MAT_FINAL_ASSEMBLY);
3882:   MatAssemblyEnd(mpimat,MAT_FINAL_ASSEMBLY);

3884:   PetscFree(abuf_r[0]);
3885:   PetscFree(abuf_r);
3886:   PetscFree(ba_i);
3887:   PetscFree3(buf_ri_k,nextrow,nextai);
3888:   PetscLogEventEnd(MAT_Seqstompinum,seqmat,0,0,0);
3889:   return(0);
3890: }

3892: extern PetscErrorCode  MatDestroy_MPIAIJ_SeqsToMPI(Mat);

3894: PetscErrorCode  MatCreateMPIAIJSumSeqAIJSymbolic(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,Mat *mpimat)
3895: {
3896:   PetscErrorCode      ierr;
3897:   Mat                 B_mpi;
3898:   Mat_SeqAIJ          *a=(Mat_SeqAIJ*)seqmat->data;
3899:   PetscMPIInt         size,rank,tagi,tagj,*len_s,*len_si,*len_ri;
3900:   PetscInt            **buf_rj,**buf_ri,**buf_ri_k;
3901:   PetscInt            M=seqmat->rmap->n,N=seqmat->cmap->n,i,*owners,*ai=a->i,*aj=a->j;
3902:   PetscInt            len,proc,*dnz,*onz,bs,cbs;
3903:   PetscInt            k,anzi,*bi,*bj,*lnk,nlnk,arow,bnzi,nspacedouble=0;
3904:   PetscInt            nrows,*buf_s,*buf_si,*buf_si_i,**nextrow,**nextai;
3905:   MPI_Request         *si_waits,*sj_waits,*ri_waits,*rj_waits;
3906:   MPI_Status          *status;
3907:   PetscFreeSpaceList  free_space=NULL,current_space=NULL;
3908:   PetscBT             lnkbt;
3909:   Mat_Merge_SeqsToMPI *merge;
3910:   PetscContainer      container;

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

3915:   /* make sure it is a PETSc comm */
3916:   PetscCommDuplicate(comm,&comm,NULL);
3917:   MPI_Comm_size(comm,&size);
3918:   MPI_Comm_rank(comm,&rank);

3920:   PetscNew(&merge);
3921:   PetscMalloc1(size,&status);

3923:   /* determine row ownership */
3924:   /*---------------------------------------------------------*/
3925:   PetscLayoutCreate(comm,&merge->rowmap);
3926:   PetscLayoutSetLocalSize(merge->rowmap,m);
3927:   PetscLayoutSetSize(merge->rowmap,M);
3928:   PetscLayoutSetBlockSize(merge->rowmap,1);
3929:   PetscLayoutSetUp(merge->rowmap);
3930:   PetscMalloc1(size,&len_si);
3931:   PetscMalloc1(size,&merge->len_s);

3933:   m      = merge->rowmap->n;
3934:   owners = merge->rowmap->range;

3936:   /* determine the number of messages to send, their lengths */
3937:   /*---------------------------------------------------------*/
3938:   len_s = merge->len_s;

3940:   len          = 0; /* length of buf_si[] */
3941:   merge->nsend = 0;
3942:   for (proc=0; proc<size; proc++) {
3943:     len_si[proc] = 0;
3944:     if (proc == rank) {
3945:       len_s[proc] = 0;
3946:     } else {
3947:       len_si[proc] = owners[proc+1] - owners[proc] + 1;
3948:       len_s[proc]  = ai[owners[proc+1]] - ai[owners[proc]]; /* num of rows to be sent to [proc] */
3949:     }
3950:     if (len_s[proc]) {
3951:       merge->nsend++;
3952:       nrows = 0;
3953:       for (i=owners[proc]; i<owners[proc+1]; i++) {
3954:         if (ai[i+1] > ai[i]) nrows++;
3955:       }
3956:       len_si[proc] = 2*(nrows+1);
3957:       len         += len_si[proc];
3958:     }
3959:   }

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

3966:   /* post the Irecv of j-structure */
3967:   /*-------------------------------*/
3968:   PetscCommGetNewTag(comm,&tagj);
3969:   PetscPostIrecvInt(comm,tagj,merge->nrecv,merge->id_r,merge->len_r,&buf_rj,&rj_waits);

3971:   /* post the Isend of j-structure */
3972:   /*--------------------------------*/
3973:   PetscMalloc2(merge->nsend,&si_waits,merge->nsend,&sj_waits);

3975:   for (proc=0, k=0; proc<size; proc++) {
3976:     if (!len_s[proc]) continue;
3977:     i    = owners[proc];
3978:     MPI_Isend(aj+ai[i],len_s[proc],MPIU_INT,proc,tagj,comm,sj_waits+k);
3979:     k++;
3980:   }

3982:   /* receives and sends of j-structure are complete */
3983:   /*------------------------------------------------*/
3984:   if (merge->nrecv) {MPI_Waitall(merge->nrecv,rj_waits,status);}
3985:   if (merge->nsend) {MPI_Waitall(merge->nsend,sj_waits,status);}

3987:   /* send and recv i-structure */
3988:   /*---------------------------*/
3989:   PetscCommGetNewTag(comm,&tagi);
3990:   PetscPostIrecvInt(comm,tagi,merge->nrecv,merge->id_r,len_ri,&buf_ri,&ri_waits);

3992:   PetscMalloc1(len+1,&buf_s);
3993:   buf_si = buf_s;  /* points to the beginning of k-th msg to be sent */
3994:   for (proc=0,k=0; proc<size; proc++) {
3995:     if (!len_s[proc]) continue;
3996:     /* form outgoing message for i-structure:
3997:          buf_si[0]:                 nrows to be sent
3998:                [1:nrows]:           row index (global)
3999:                [nrows+1:2*nrows+1]: i-structure index
4000:     */
4001:     /*-------------------------------------------*/
4002:     nrows       = len_si[proc]/2 - 1;
4003:     buf_si_i    = buf_si + nrows+1;
4004:     buf_si[0]   = nrows;
4005:     buf_si_i[0] = 0;
4006:     nrows       = 0;
4007:     for (i=owners[proc]; i<owners[proc+1]; i++) {
4008:       anzi = ai[i+1] - ai[i];
4009:       if (anzi) {
4010:         buf_si_i[nrows+1] = buf_si_i[nrows] + anzi; /* i-structure */
4011:         buf_si[nrows+1]   = i-owners[proc]; /* local row index */
4012:         nrows++;
4013:       }
4014:     }
4015:     MPI_Isend(buf_si,len_si[proc],MPIU_INT,proc,tagi,comm,si_waits+k);
4016:     k++;
4017:     buf_si += len_si[proc];
4018:   }

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

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

4028:   PetscFree(len_si);
4029:   PetscFree(len_ri);
4030:   PetscFree(rj_waits);
4031:   PetscFree2(si_waits,sj_waits);
4032:   PetscFree(ri_waits);
4033:   PetscFree(buf_s);
4034:   PetscFree(status);

4036:   /* compute a local seq matrix in each processor */
4037:   /*----------------------------------------------*/
4038:   /* allocate bi array and free space for accumulating nonzero column info */
4039:   PetscMalloc1(m+1,&bi);
4040:   bi[0] = 0;

4042:   /* create and initialize a linked list */
4043:   nlnk = N+1;
4044:   PetscLLCreate(N,N,nlnk,lnk,lnkbt);

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

4050:   current_space = free_space;

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

4055:   for (k=0; k<merge->nrecv; k++) {
4056:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
4057:     nrows       = *buf_ri_k[k];
4058:     nextrow[k]  = buf_ri_k[k] + 1;  /* next row number of k-th recved i-structure */
4059:     nextai[k]   = buf_ri_k[k] + (nrows + 1); /* poins to the next i-structure of k-th recved i-structure  */
4060:   }

4062:   MatPreallocateInitialize(comm,m,n,dnz,onz);
4063:   len  = 0;
4064:   for (i=0; i<m; i++) {
4065:     bnzi = 0;
4066:     /* add local non-zero cols of this proc's seqmat into lnk */
4067:     arow  = owners[rank] + i;
4068:     anzi  = ai[arow+1] - ai[arow];
4069:     aj    = a->j + ai[arow];
4070:     PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4071:     bnzi += nlnk;
4072:     /* add received col data into lnk */
4073:     for (k=0; k<merge->nrecv; k++) { /* k-th received message */
4074:       if (i == *nextrow[k]) { /* i-th row */
4075:         anzi  = *(nextai[k]+1) - *nextai[k];
4076:         aj    = buf_rj[k] + *nextai[k];
4077:         PetscLLAddSorted(anzi,aj,N,nlnk,lnk,lnkbt);
4078:         bnzi += nlnk;
4079:         nextrow[k]++; nextai[k]++;
4080:       }
4081:     }
4082:     if (len < bnzi) len = bnzi;  /* =max(bnzi) */

4084:     /* if free space is not available, make more free space */
4085:     if (current_space->local_remaining<bnzi) {
4086:       PetscFreeSpaceGet(PetscIntSumTruncate(bnzi,current_space->total_array_size),&current_space);
4087:       nspacedouble++;
4088:     }
4089:     /* copy data into free space, then initialize lnk */
4090:     PetscLLClean(N,N,bnzi,lnk,current_space->array,lnkbt);
4091:     MatPreallocateSet(i+owners[rank],bnzi,current_space->array,dnz,onz);

4093:     current_space->array           += bnzi;
4094:     current_space->local_used      += bnzi;
4095:     current_space->local_remaining -= bnzi;

4097:     bi[i+1] = bi[i] + bnzi;
4098:   }

4100:   PetscFree3(buf_ri_k,nextrow,nextai);

4102:   PetscMalloc1(bi[m]+1,&bj);
4103:   PetscFreeSpaceContiguous(&free_space,bj);
4104:   PetscLLDestroy(lnk,lnkbt);

4106:   /* create symbolic parallel matrix B_mpi */
4107:   /*---------------------------------------*/
4108:   MatGetBlockSizes(seqmat,&bs,&cbs);
4109:   MatCreate(comm,&B_mpi);
4110:   if (n==PETSC_DECIDE) {
4111:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,N);
4112:   } else {
4113:     MatSetSizes(B_mpi,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4114:   }
4115:   MatSetBlockSizes(B_mpi,bs,cbs);
4116:   MatSetType(B_mpi,MATMPIAIJ);
4117:   MatMPIAIJSetPreallocation(B_mpi,0,dnz,0,onz);
4118:   MatPreallocateFinalize(dnz,onz);
4119:   MatSetOption(B_mpi,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

4121:   /* B_mpi is not ready for use - assembly will be done by MatCreateMPIAIJSumSeqAIJNumeric() */
4122:   B_mpi->assembled    = PETSC_FALSE;
4123:   B_mpi->ops->destroy = MatDestroy_MPIAIJ_SeqsToMPI;
4124:   merge->bi           = bi;
4125:   merge->bj           = bj;
4126:   merge->buf_ri       = buf_ri;
4127:   merge->buf_rj       = buf_rj;
4128:   merge->coi          = NULL;
4129:   merge->coj          = NULL;
4130:   merge->owners_co    = NULL;

4132:   PetscCommDestroy(&comm);

4134:   /* attach the supporting struct to B_mpi for reuse */
4135:   PetscContainerCreate(PETSC_COMM_SELF,&container);
4136:   PetscContainerSetPointer(container,merge);
4137:   PetscObjectCompose((PetscObject)B_mpi,"MatMergeSeqsToMPI",(PetscObject)container);
4138:   PetscContainerDestroy(&container);
4139:   *mpimat = B_mpi;

4141:   PetscLogEventEnd(MAT_Seqstompisym,seqmat,0,0,0);
4142:   return(0);
4143: }

4145: /*@C
4146:       MatCreateMPIAIJSumSeqAIJ - Creates a MATMPIAIJ matrix by adding sequential
4147:                  matrices from each processor

4149:     Collective on MPI_Comm

4151:    Input Parameters:
4152: +    comm - the communicators the parallel matrix will live on
4153: .    seqmat - the input sequential matrices
4154: .    m - number of local rows (or PETSC_DECIDE)
4155: .    n - number of local columns (or PETSC_DECIDE)
4156: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4158:    Output Parameter:
4159: .    mpimat - the parallel matrix generated

4161:     Level: advanced

4163:    Notes:
4164:      The dimensions of the sequential matrix in each processor MUST be the same.
4165:      The input seqmat is included into the container "Mat_Merge_SeqsToMPI", and will be
4166:      destroyed when mpimat is destroyed. Call PetscObjectQuery() to access seqmat.
4167: @*/
4168: PetscErrorCode  MatCreateMPIAIJSumSeqAIJ(MPI_Comm comm,Mat seqmat,PetscInt m,PetscInt n,MatReuse scall,Mat *mpimat)
4169: {
4171:   PetscMPIInt    size;

4174:   MPI_Comm_size(comm,&size);
4175:   if (size == 1) {
4176:     PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4177:     if (scall == MAT_INITIAL_MATRIX) {
4178:       MatDuplicate(seqmat,MAT_COPY_VALUES,mpimat);
4179:     } else {
4180:       MatCopy(seqmat,*mpimat,SAME_NONZERO_PATTERN);
4181:     }
4182:     PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4183:     return(0);
4184:   }
4185:   PetscLogEventBegin(MAT_Seqstompi,seqmat,0,0,0);
4186:   if (scall == MAT_INITIAL_MATRIX) {
4187:     MatCreateMPIAIJSumSeqAIJSymbolic(comm,seqmat,m,n,mpimat);
4188:   }
4189:   MatCreateMPIAIJSumSeqAIJNumeric(seqmat,*mpimat);
4190:   PetscLogEventEnd(MAT_Seqstompi,seqmat,0,0,0);
4191:   return(0);
4192: }

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

4199:     Not Collective

4201:    Input Parameters:
4202: +    A - the matrix
4203: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

4205:    Output Parameter:
4206: .    A_loc - the local sequential matrix generated

4208:     Level: developer

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

4212: @*/
4213: PetscErrorCode  MatMPIAIJGetLocalMat(Mat A,MatReuse scall,Mat *A_loc)
4214: {
4216:   Mat_MPIAIJ     *mpimat=(Mat_MPIAIJ*)A->data;
4217:   Mat_SeqAIJ     *mat,*a,*b;
4218:   PetscInt       *ai,*aj,*bi,*bj,*cmap=mpimat->garray;
4219:   MatScalar      *aa,*ba,*cam;
4220:   PetscScalar    *ca;
4221:   PetscInt       am=A->rmap->n,i,j,k,cstart=A->cmap->rstart;
4222:   PetscInt       *ci,*cj,col,ncols_d,ncols_o,jo;
4223:   PetscBool      match;
4224:   MPI_Comm       comm;
4225:   PetscMPIInt    size;

4228:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
4229:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
4230:   PetscObjectGetComm((PetscObject)A,&comm);
4231:   MPI_Comm_size(comm,&size);
4232:   if (size == 1 && scall == MAT_REUSE_MATRIX) return(0);

4234:   PetscLogEventBegin(MAT_Getlocalmat,A,0,0,0);
4235:   a = (Mat_SeqAIJ*)(mpimat->A)->data;
4236:   b = (Mat_SeqAIJ*)(mpimat->B)->data;
4237:   ai = a->i; aj = a->j; bi = b->i; bj = b->j;
4238:   aa = a->a; ba = b->a;
4239:   if (scall == MAT_INITIAL_MATRIX) {
4240:     if (size == 1) {
4241:       MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ai,aj,aa,A_loc);
4242:       return(0);
4243:     }

4245:     PetscMalloc1(1+am,&ci);
4246:     ci[0] = 0;
4247:     for (i=0; i<am; i++) {
4248:       ci[i+1] = ci[i] + (ai[i+1] - ai[i]) + (bi[i+1] - bi[i]);
4249:     }
4250:     PetscMalloc1(1+ci[am],&cj);
4251:     PetscMalloc1(1+ci[am],&ca);
4252:     k    = 0;
4253:     for (i=0; i<am; i++) {
4254:       ncols_o = bi[i+1] - bi[i];
4255:       ncols_d = ai[i+1] - ai[i];
4256:       /* off-diagonal portion of A */
4257:       for (jo=0; jo<ncols_o; jo++) {
4258:         col = cmap[*bj];
4259:         if (col >= cstart) break;
4260:         cj[k]   = col; bj++;
4261:         ca[k++] = *ba++;
4262:       }
4263:       /* diagonal portion of A */
4264:       for (j=0; j<ncols_d; j++) {
4265:         cj[k]   = cstart + *aj++;
4266:         ca[k++] = *aa++;
4267:       }
4268:       /* off-diagonal portion of A */
4269:       for (j=jo; j<ncols_o; j++) {
4270:         cj[k]   = cmap[*bj++];
4271:         ca[k++] = *ba++;
4272:       }
4273:     }
4274:     /* put together the new matrix */
4275:     MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,am,A->cmap->N,ci,cj,ca,A_loc);
4276:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
4277:     /* Since these are PETSc arrays, change flags to free them as necessary. */
4278:     mat          = (Mat_SeqAIJ*)(*A_loc)->data;
4279:     mat->free_a  = PETSC_TRUE;
4280:     mat->free_ij = PETSC_TRUE;
4281:     mat->nonew   = 0;
4282:   } else if (scall == MAT_REUSE_MATRIX) {
4283:     mat=(Mat_SeqAIJ*)(*A_loc)->data;
4284:     ci = mat->i; cj = mat->j; cam = mat->a;
4285:     for (i=0; i<am; i++) {
4286:       /* off-diagonal portion of A */
4287:       ncols_o = bi[i+1] - bi[i];
4288:       for (jo=0; jo<ncols_o; jo++) {
4289:         col = cmap[*bj];
4290:         if (col >= cstart) break;
4291:         *cam++ = *ba++; bj++;
4292:       }
4293:       /* diagonal portion of A */
4294:       ncols_d = ai[i+1] - ai[i];
4295:       for (j=0; j<ncols_d; j++) *cam++ = *aa++;
4296:       /* off-diagonal portion of A */
4297:       for (j=jo; j<ncols_o; j++) {
4298:         *cam++ = *ba++; bj++;
4299:       }
4300:     }
4301:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid MatReuse %d",(int)scall);
4302:   PetscLogEventEnd(MAT_Getlocalmat,A,0,0,0);
4303:   return(0);
4304: }

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

4309:     Not Collective

4311:    Input Parameters:
4312: +    A - the matrix
4313: .    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
4314: -    row, col - index sets of rows and columns to extract (or NULL)

4316:    Output Parameter:
4317: .    A_loc - the local sequential matrix generated

4319:     Level: developer

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

4323: @*/
4324: PetscErrorCode  MatMPIAIJGetLocalMatCondensed(Mat A,MatReuse scall,IS *row,IS *col,Mat *A_loc)
4325: {
4326:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
4328:   PetscInt       i,start,end,ncols,nzA,nzB,*cmap,imark,*idx;
4329:   IS             isrowa,iscola;
4330:   Mat            *aloc;
4331:   PetscBool      match;

4334:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ,&match);
4335:   if (!match) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_SUP,"Requires MATMPIAIJ matrix as input");
4336:   PetscLogEventBegin(MAT_Getlocalmatcondensed,A,0,0,0);
4337:   if (!row) {
4338:     start = A->rmap->rstart; end = A->rmap->rend;
4339:     ISCreateStride(PETSC_COMM_SELF,end-start,start,1,&isrowa);
4340:   } else {
4341:     isrowa = *row;
4342:   }
4343:   if (!col) {
4344:     start = A->cmap->rstart;
4345:     cmap  = a->garray;
4346:     nzA   = a->A->cmap->n;
4347:     nzB   = a->B->cmap->n;
4348:     PetscMalloc1(nzA+nzB, &idx);
4349:     ncols = 0;
4350:     for (i=0; i<nzB; i++) {
4351:       if (cmap[i] < start) idx[ncols++] = cmap[i];
4352:       else break;
4353:     }
4354:     imark = i;
4355:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;
4356:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i];
4357:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&iscola);
4358:   } else {
4359:     iscola = *col;
4360:   }
4361:   if (scall != MAT_INITIAL_MATRIX) {
4362:     PetscMalloc1(1,&aloc);
4363:     aloc[0] = *A_loc;
4364:   }
4365:   MatGetSubMatrices(A,1,&isrowa,&iscola,scall,&aloc);
4366:   *A_loc = aloc[0];
4367:   PetscFree(aloc);
4368:   if (!row) {
4369:     ISDestroy(&isrowa);
4370:   }
4371:   if (!col) {
4372:     ISDestroy(&iscola);
4373:   }
4374:   PetscLogEventEnd(MAT_Getlocalmatcondensed,A,0,0,0);
4375:   return(0);
4376: }

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

4381:     Collective on Mat

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

4388:    Output Parameter:
4389: +    rowb, colb - index sets of rows and columns of B to extract
4390: -    B_seq - the sequential matrix generated

4392:     Level: developer

4394: @*/
4395: PetscErrorCode  MatGetBrowsOfAcols(Mat A,Mat B,MatReuse scall,IS *rowb,IS *colb,Mat *B_seq)
4396: {
4397:   Mat_MPIAIJ     *a=(Mat_MPIAIJ*)A->data;
4399:   PetscInt       *idx,i,start,ncols,nzA,nzB,*cmap,imark;
4400:   IS             isrowb,iscolb;
4401:   Mat            *bseq=NULL;

4404:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
4405:     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);
4406:   }
4407:   PetscLogEventBegin(MAT_GetBrowsOfAcols,A,B,0,0);

4409:   if (scall == MAT_INITIAL_MATRIX) {
4410:     start = A->cmap->rstart;
4411:     cmap  = a->garray;
4412:     nzA   = a->A->cmap->n;
4413:     nzB   = a->B->cmap->n;
4414:     PetscMalloc1(nzA+nzB, &idx);
4415:     ncols = 0;
4416:     for (i=0; i<nzB; i++) {  /* row < local row index */
4417:       if (cmap[i] < start) idx[ncols++] = cmap[i];
4418:       else break;
4419:     }
4420:     imark = i;
4421:     for (i=0; i<nzA; i++) idx[ncols++] = start + i;  /* local rows */
4422:     for (i=imark; i<nzB; i++) idx[ncols++] = cmap[i]; /* row > local row index */
4423:     ISCreateGeneral(PETSC_COMM_SELF,ncols,idx,PETSC_OWN_POINTER,&isrowb);
4424:     ISCreateStride(PETSC_COMM_SELF,B->cmap->N,0,1,&iscolb);
4425:   } else {
4426:     if (!rowb || !colb) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"IS rowb and colb must be provided for MAT_REUSE_MATRIX");
4427:     isrowb  = *rowb; iscolb = *colb;
4428:     PetscMalloc1(1,&bseq);
4429:     bseq[0] = *B_seq;
4430:   }
4431:   MatGetSubMatrices(B,1,&isrowb,&iscolb,scall,&bseq);
4432:   *B_seq = bseq[0];
4433:   PetscFree(bseq);
4434:   if (!rowb) {
4435:     ISDestroy(&isrowb);
4436:   } else {
4437:     *rowb = isrowb;
4438:   }
4439:   if (!colb) {
4440:     ISDestroy(&iscolb);
4441:   } else {
4442:     *colb = iscolb;
4443:   }
4444:   PetscLogEventEnd(MAT_GetBrowsOfAcols,A,B,0,0);
4445:   return(0);
4446: }

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

4452:     Collective on Mat

4454:    Input Parameters:
4455: +    A,B - the matrices in mpiaij format
4456: -    scall - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

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

4464:     Level: developer

4466: */
4467: PetscErrorCode  MatGetBrowsOfAoCols_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscInt **startsj_s,PetscInt **startsj_r,MatScalar **bufa_ptr,Mat *B_oth)
4468: {
4469:   VecScatter_MPI_General *gen_to,*gen_from;
4470:   PetscErrorCode         ierr;
4471:   Mat_MPIAIJ             *a=(Mat_MPIAIJ*)A->data;
4472:   Mat_SeqAIJ             *b_oth;
4473:   VecScatter             ctx =a->Mvctx;
4474:   MPI_Comm               comm;
4475:   PetscMPIInt            *rprocs,*sprocs,tag=((PetscObject)ctx)->tag,rank;
4476:   PetscInt               *rowlen,*bufj,*bufJ,ncols,aBn=a->B->cmap->n,row,*b_othi,*b_othj;
4477:   PetscInt               *rvalues,*svalues;
4478:   MatScalar              *b_otha,*bufa,*bufA;
4479:   PetscInt               i,j,k,l,ll,nrecvs,nsends,nrows,*srow,*rstarts,*rstartsj = 0,*sstarts,*sstartsj,len;
4480:   MPI_Request            *rwaits = NULL,*swaits = NULL;
4481:   MPI_Status             *sstatus,rstatus;
4482:   PetscMPIInt            jj,size;
4483:   PetscInt               *cols,sbs,rbs;
4484:   PetscScalar            *vals;

4487:   PetscObjectGetComm((PetscObject)A,&comm);
4488:   MPI_Comm_size(comm,&size);

4490:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend) {
4491:     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);
4492:   }
4493:   PetscLogEventBegin(MAT_GetBrowsOfAocols,A,B,0,0);
4494:   MPI_Comm_rank(comm,&rank);

4496:   gen_to   = (VecScatter_MPI_General*)ctx->todata;
4497:   gen_from = (VecScatter_MPI_General*)ctx->fromdata;
4498:   nrecvs   = gen_from->n;
4499:   nsends   = gen_to->n;

4501:   PetscMalloc2(nrecvs,&rwaits,nsends,&swaits);
4502:   srow    = gen_to->indices;    /* local row index to be sent */
4503:   sstarts = gen_to->starts;
4504:   sprocs  = gen_to->procs;
4505:   sstatus = gen_to->sstatus;
4506:   sbs     = gen_to->bs;
4507:   rstarts = gen_from->starts;
4508:   rprocs  = gen_from->procs;
4509:   rbs     = gen_from->bs;

4511:   if (!startsj_s || !bufa_ptr) scall = MAT_INITIAL_MATRIX;
4512:   if (scall == MAT_INITIAL_MATRIX) {
4513:     /* i-array */
4514:     /*---------*/
4515:     /*  post receives */
4516:     PetscMalloc1(rbs*(rstarts[nrecvs] - rstarts[0]),&rvalues);
4517:     for (i=0; i<nrecvs; i++) {
4518:       rowlen = rvalues + rstarts[i]*rbs;
4519:       nrows  = (rstarts[i+1]-rstarts[i])*rbs; /* num of indices to be received */
4520:       MPI_Irecv(rowlen,nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
4521:     }

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

4526:     sstartsj[0] = 0;
4527:     rstartsj[0] = 0;
4528:     len         = 0; /* total length of j or a array to be sent */
4529:     k           = 0;
4530:     PetscMalloc1(sbs*(sstarts[nsends] - sstarts[0]),&svalues);
4531:     for (i=0; i<nsends; i++) {
4532:       rowlen = svalues + sstarts[i]*sbs;
4533:       nrows  = sstarts[i+1]-sstarts[i]; /* num of block rows */
4534:       for (j=0; j<nrows; j++) {
4535:         row = srow[k] + B->rmap->range[rank]; /* global row idx */
4536:         for (l=0; l<sbs; l++) {
4537:           MatGetRow_MPIAIJ(B,row+l,&ncols,NULL,NULL); /* rowlength */

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

4541:           len += ncols;
4542:           MatRestoreRow_MPIAIJ(B,row+l,&ncols,NULL,NULL);
4543:         }
4544:         k++;
4545:       }
4546:       MPI_Isend(rowlen,nrows*sbs,MPIU_INT,sprocs[i],tag,comm,swaits+i);

4548:       sstartsj[i+1] = len;  /* starting point of (i+1)-th outgoing msg in bufj and bufa */
4549:     }
4550:     /* recvs and sends of i-array are completed */
4551:     i = nrecvs;
4552:     while (i--) {
4553:       MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4554:     }
4555:     if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4556:     PetscFree(svalues);

4558:     /* allocate buffers for sending j and a arrays */
4559:     PetscMalloc1(len+1,&bufj);
4560:     PetscMalloc1(len+1,&bufa);

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

4565:     b_othi[0] = 0;
4566:     len       = 0; /* total length of j or a array to be received */
4567:     k         = 0;
4568:     for (i=0; i<nrecvs; i++) {
4569:       rowlen = rvalues + rstarts[i]*rbs;
4570:       nrows  = rbs*(rstarts[i+1]-rstarts[i]); /* num of rows to be received */
4571:       for (j=0; j<nrows; j++) {
4572:         b_othi[k+1] = b_othi[k] + rowlen[j];
4573:         PetscIntSumError(rowlen[j],len,&len);
4574:         k++;
4575:       }
4576:       rstartsj[i+1] = len; /* starting point of (i+1)-th incoming msg in bufj and bufa */
4577:     }
4578:     PetscFree(rvalues);

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

4584:     /* j-array */
4585:     /*---------*/
4586:     /*  post receives of j-array */
4587:     for (i=0; i<nrecvs; i++) {
4588:       nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
4589:       MPI_Irecv(b_othj+rstartsj[i],nrows,MPIU_INT,rprocs[i],tag,comm,rwaits+i);
4590:     }

4592:     /* pack the outgoing message j-array */
4593:     k = 0;
4594:     for (i=0; i<nsends; i++) {
4595:       nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
4596:       bufJ  = bufj+sstartsj[i];
4597:       for (j=0; j<nrows; j++) {
4598:         row = srow[k++] + B->rmap->range[rank];  /* global row idx */
4599:         for (ll=0; ll<sbs; ll++) {
4600:           MatGetRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
4601:           for (l=0; l<ncols; l++) {
4602:             *bufJ++ = cols[l];
4603:           }
4604:           MatRestoreRow_MPIAIJ(B,row+ll,&ncols,&cols,NULL);
4605:         }
4606:       }
4607:       MPI_Isend(bufj+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_INT,sprocs[i],tag,comm,swaits+i);
4608:     }

4610:     /* recvs and sends of j-array are completed */
4611:     i = nrecvs;
4612:     while (i--) {
4613:       MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4614:     }
4615:     if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4616:   } else if (scall == MAT_REUSE_MATRIX) {
4617:     sstartsj = *startsj_s;
4618:     rstartsj = *startsj_r;
4619:     bufa     = *bufa_ptr;
4620:     b_oth    = (Mat_SeqAIJ*)(*B_oth)->data;
4621:     b_otha   = b_oth->a;
4622:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Matrix P does not posses an object container");

4624:   /* a-array */
4625:   /*---------*/
4626:   /*  post receives of a-array */
4627:   for (i=0; i<nrecvs; i++) {
4628:     nrows = rstartsj[i+1]-rstartsj[i]; /* length of the msg received */
4629:     MPI_Irecv(b_otha+rstartsj[i],nrows,MPIU_SCALAR,rprocs[i],tag,comm,rwaits+i);
4630:   }

4632:   /* pack the outgoing message a-array */
4633:   k = 0;
4634:   for (i=0; i<nsends; i++) {
4635:     nrows = sstarts[i+1]-sstarts[i]; /* num of block rows */
4636:     bufA  = bufa+sstartsj[i];
4637:     for (j=0; j<nrows; j++) {
4638:       row = srow[k++] + B->rmap->range[rank];  /* global row idx */
4639:       for (ll=0; ll<sbs; ll++) {
4640:         MatGetRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
4641:         for (l=0; l<ncols; l++) {
4642:           *bufA++ = vals[l];
4643:         }
4644:         MatRestoreRow_MPIAIJ(B,row+ll,&ncols,NULL,&vals);
4645:       }
4646:     }
4647:     MPI_Isend(bufa+sstartsj[i],sstartsj[i+1]-sstartsj[i],MPIU_SCALAR,sprocs[i],tag,comm,swaits+i);
4648:   }
4649:   /* recvs and sends of a-array are completed */
4650:   i = nrecvs;
4651:   while (i--) {
4652:     MPI_Waitany(nrecvs,rwaits,&jj,&rstatus);
4653:   }
4654:   if (nsends) {MPI_Waitall(nsends,swaits,sstatus);}
4655:   PetscFree2(rwaits,swaits);

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

4661:     /* MatCreateSeqAIJWithArrays flags matrix so PETSc doesn't free the user's arrays. */
4662:     /* Since these are PETSc arrays, change flags to free them as necessary. */
4663:     b_oth          = (Mat_SeqAIJ*)(*B_oth)->data;
4664:     b_oth->free_a  = PETSC_TRUE;
4665:     b_oth->free_ij = PETSC_TRUE;
4666:     b_oth->nonew   = 0;

4668:     PetscFree(bufj);
4669:     if (!startsj_s || !bufa_ptr) {
4670:       PetscFree2(sstartsj,rstartsj);
4671:       PetscFree(bufa_ptr);
4672:     } else {
4673:       *startsj_s = sstartsj;
4674:       *startsj_r = rstartsj;
4675:       *bufa_ptr  = bufa;
4676:     }
4677:   }
4678:   PetscLogEventEnd(MAT_GetBrowsOfAocols,A,B,0,0);
4679:   return(0);
4680: }

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

4685:   Not Collective

4687:   Input Parameters:
4688: . A - The matrix in mpiaij format

4690:   Output Parameter:
4691: + lvec - The local vector holding off-process values from the argument to a matrix-vector product
4692: . colmap - A map from global column index to local index into lvec
4693: - multScatter - A scatter from the argument of a matrix-vector product to lvec

4695:   Level: developer

4697: @*/
4698: #if defined(PETSC_USE_CTABLE)
4699: PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscTable *colmap, VecScatter *multScatter)
4700: #else
4701: PetscErrorCode  MatGetCommunicationStructs(Mat A, Vec *lvec, PetscInt *colmap[], VecScatter *multScatter)
4702: #endif
4703: {
4704:   Mat_MPIAIJ *a;

4711:   a = (Mat_MPIAIJ*) A->data;
4712:   if (lvec) *lvec = a->lvec;
4713:   if (colmap) *colmap = a->colmap;
4714:   if (multScatter) *multScatter = a->Mvctx;
4715:   return(0);
4716: }

4718: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJCRL(Mat,MatType,MatReuse,Mat*);
4719: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJPERM(Mat,MatType,MatReuse,Mat*);
4720: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPISBAIJ(Mat,MatType,MatReuse,Mat*);
4721: #if defined(PETSC_HAVE_ELEMENTAL)
4722: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_Elemental(Mat,MatType,MatReuse,Mat*);
4723: #endif
4724: #if defined(PETSC_HAVE_HYPRE)
4725: PETSC_INTERN PetscErrorCode MatConvert_AIJ_HYPRE(Mat,MatType,MatReuse,Mat*);
4726: PETSC_INTERN PetscErrorCode MatMatMatMult_Transpose_AIJ_AIJ(Mat,Mat,Mat,MatReuse,PetscReal,Mat*);
4727: #endif
4728: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_IS(Mat,MatType,MatReuse,Mat*);

4730: /*
4731:     Computes (B'*A')' since computing B*A directly is untenable

4733:                n                       p                          p
4734:         (              )       (              )         (                  )
4735:       m (      A       )  *  n (       B      )   =   m (         C        )
4736:         (              )       (              )         (                  )

4738: */
4739: PetscErrorCode MatMatMultNumeric_MPIDense_MPIAIJ(Mat A,Mat B,Mat C)
4740: {
4742:   Mat            At,Bt,Ct;

4745:   MatTranspose(A,MAT_INITIAL_MATRIX,&At);
4746:   MatTranspose(B,MAT_INITIAL_MATRIX,&Bt);
4747:   MatMatMult(Bt,At,MAT_INITIAL_MATRIX,1.0,&Ct);
4748:   MatDestroy(&At);
4749:   MatDestroy(&Bt);
4750:   MatTranspose(Ct,MAT_REUSE_MATRIX,&C);
4751:   MatDestroy(&Ct);
4752:   return(0);
4753: }

4755: PetscErrorCode MatMatMultSymbolic_MPIDense_MPIAIJ(Mat A,Mat B,PetscReal fill,Mat *C)
4756: {
4758:   PetscInt       m=A->rmap->n,n=B->cmap->n;
4759:   Mat            Cmat;

4762:   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);
4763:   MatCreate(PetscObjectComm((PetscObject)A),&Cmat);
4764:   MatSetSizes(Cmat,m,n,PETSC_DETERMINE,PETSC_DETERMINE);
4765:   MatSetBlockSizesFromMats(Cmat,A,B);
4766:   MatSetType(Cmat,MATMPIDENSE);
4767:   MatMPIDenseSetPreallocation(Cmat,NULL);
4768:   MatAssemblyBegin(Cmat,MAT_FINAL_ASSEMBLY);
4769:   MatAssemblyEnd(Cmat,MAT_FINAL_ASSEMBLY);

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

4773:   *C = Cmat;
4774:   return(0);
4775: }

4777: /* ----------------------------------------------------------------*/
4778: PETSC_INTERN PetscErrorCode MatMatMult_MPIDense_MPIAIJ(Mat A,Mat B,MatReuse scall,PetscReal fill,Mat *C)
4779: {

4783:   if (scall == MAT_INITIAL_MATRIX) {
4784:     PetscLogEventBegin(MAT_MatMultSymbolic,A,B,0,0);
4785:     MatMatMultSymbolic_MPIDense_MPIAIJ(A,B,fill,C);
4786:     PetscLogEventEnd(MAT_MatMultSymbolic,A,B,0,0);
4787:   }
4788:   PetscLogEventBegin(MAT_MatMultNumeric,A,B,0,0);
4789:   MatMatMultNumeric_MPIDense_MPIAIJ(A,B,*C);
4790:   PetscLogEventEnd(MAT_MatMultNumeric,A,B,0,0);
4791:   return(0);
4792: }

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

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

4800:   Level: beginner

4802: .seealso: MatCreateAIJ()
4803: M*/

4805: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJ(Mat B)
4806: {
4807:   Mat_MPIAIJ     *b;
4809:   PetscMPIInt    size;

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

4814:   PetscNewLog(B,&b);
4815:   B->data       = (void*)b;
4816:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
4817:   B->assembled  = PETSC_FALSE;
4818:   B->insertmode = NOT_SET_VALUES;
4819:   b->size       = size;

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

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

4826:   b->donotstash  = PETSC_FALSE;
4827:   b->colmap      = 0;
4828:   b->garray      = 0;
4829:   b->roworiented = PETSC_TRUE;

4831:   /* stuff used for matrix vector multiply */
4832:   b->lvec  = NULL;
4833:   b->Mvctx = NULL;

4835:   /* stuff for MatGetRow() */
4836:   b->rowindices   = 0;
4837:   b->rowvalues    = 0;
4838:   b->getrowactive = PETSC_FALSE;

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

4843:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetUseScalableIncreaseOverlap_C",MatMPIAIJSetUseScalableIncreaseOverlap_MPIAIJ);
4844:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIAIJ);
4845:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIAIJ);
4846:   PetscObjectComposeFunction((PetscObject)B,"MatIsTranspose_C",MatIsTranspose_MPIAIJ);
4847:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocation_C",MatMPIAIJSetPreallocation_MPIAIJ);
4848:   PetscObjectComposeFunction((PetscObject)B,"MatMPIAIJSetPreallocationCSR_C",MatMPIAIJSetPreallocationCSR_MPIAIJ);
4849:   PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIAIJ);
4850:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijperm_C",MatConvert_MPIAIJ_MPIAIJPERM);
4851:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpiaijcrl_C",MatConvert_MPIAIJ_MPIAIJCRL);
4852:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_mpisbaij_C",MatConvert_MPIAIJ_MPISBAIJ);
4853: #if defined(PETSC_HAVE_ELEMENTAL)
4854:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_elemental_C",MatConvert_MPIAIJ_Elemental);
4855: #endif
4856: #if defined(PETSC_HAVE_HYPRE)
4857:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_hypre_C",MatConvert_AIJ_HYPRE);
4858: #endif
4859:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpiaij_is_C",MatConvert_MPIAIJ_IS);
4860:   PetscObjectComposeFunction((PetscObject)B,"MatMatMult_mpidense_mpiaij_C",MatMatMult_MPIDense_MPIAIJ);
4861:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultSymbolic_mpidense_mpiaij_C",MatMatMultSymbolic_MPIDense_MPIAIJ);
4862:   PetscObjectComposeFunction((PetscObject)B,"MatMatMultNumeric_mpidense_mpiaij_C",MatMatMultNumeric_MPIDense_MPIAIJ);
4863: #if defined(PETSC_HAVE_HYPRE)
4864:   PetscObjectComposeFunction((PetscObject)B,"MatMatMatMult_transpose_mpiaij_mpiaij_C",MatMatMatMult_Transpose_AIJ_AIJ);
4865: #endif
4866:   PetscObjectChangeTypeName((PetscObject)B,MATMPIAIJ);
4867:   return(0);
4868: }

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

4874:    Collective on MPI_Comm

4876:    Input Parameters:
4877: +  comm - MPI communicator
4878: .  m - number of local rows (Cannot be PETSC_DECIDE)
4879: .  n - This value should be the same as the local size used in creating the
4880:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
4881:        calculated if N is given) For square matrices n is almost always m.
4882: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
4883: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
4884: .   i - row indices for "diagonal" portion of matrix
4885: .   j - column indices
4886: .   a - matrix values
4887: .   oi - row indices for "off-diagonal" portion of matrix
4888: .   oj - column indices
4889: -   oa - matrix values

4891:    Output Parameter:
4892: .   mat - the matrix

4894:    Level: advanced

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

4900:        The i and j indices are 0 based

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

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

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

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

4915: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4916:           MATMPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithArrays()
4917: @*/
4918: 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)
4919: {
4921:   Mat_MPIAIJ     *maij;

4924:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4925:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4926:   if (oi[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"oi (row indices) must start with 0");
4927:   MatCreate(comm,mat);
4928:   MatSetSizes(*mat,m,n,M,N);
4929:   MatSetType(*mat,MATMPIAIJ);
4930:   maij = (Mat_MPIAIJ*) (*mat)->data;

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

4934:   PetscLayoutSetUp((*mat)->rmap);
4935:   PetscLayoutSetUp((*mat)->cmap);

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

4940:   MatAssemblyBegin(maij->A,MAT_FINAL_ASSEMBLY);
4941:   MatAssemblyEnd(maij->A,MAT_FINAL_ASSEMBLY);
4942:   MatAssemblyBegin(maij->B,MAT_FINAL_ASSEMBLY);
4943:   MatAssemblyEnd(maij->B,MAT_FINAL_ASSEMBLY);

4945:   MatAssemblyBegin(*mat,MAT_FINAL_ASSEMBLY);
4946:   MatAssemblyEnd(*mat,MAT_FINAL_ASSEMBLY);
4947:   MatSetOption(*mat,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
4948:   return(0);
4949: }

4951: /*
4952:     Special version for direct calls from Fortran
4953: */
4954:  #include <petsc/private/fortranimpl.h>

4956: /* Change these macros so can be used in void function */
4957: #undef CHKERRQ
4958: #define CHKERRQ(ierr) CHKERRABORT(PETSC_COMM_WORLD,ierr)
4959: #undef SETERRQ2
4960: #define SETERRQ2(comm,ierr,b,c,d) CHKERRABORT(comm,ierr)
4961: #undef SETERRQ3
4962: #define SETERRQ3(comm,ierr,b,c,d,e) CHKERRABORT(comm,ierr)
4963: #undef SETERRQ
4964: #define SETERRQ(c,ierr,b) CHKERRABORT(c,ierr)

4966: #if defined(PETSC_HAVE_FORTRAN_CAPS)
4967: #define matsetvaluesmpiaij_ MATSETVALUESMPIAIJ
4968: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
4969: #define matsetvaluesmpiaij_ matsetvaluesmpiaij
4970: #else
4971: #endif
4972: 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)
4973: {
4974:   Mat            mat  = *mmat;
4975:   PetscInt       m    = *mm, n = *mn;
4976:   InsertMode     addv = *maddv;
4977:   Mat_MPIAIJ     *aij = (Mat_MPIAIJ*)mat->data;
4978:   PetscScalar    value;

4981:   MatCheckPreallocated(mat,1);
4982:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;

4984: #if defined(PETSC_USE_DEBUG)
4985:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
4986: #endif
4987:   {
4988:     PetscInt  i,j,rstart  = mat->rmap->rstart,rend = mat->rmap->rend;
4989:     PetscInt  cstart      = mat->cmap->rstart,cend = mat->cmap->rend,row,col;
4990:     PetscBool roworiented = aij->roworiented;

4992:     /* Some Variables required in the macro */
4993:     Mat        A                 = aij->A;
4994:     Mat_SeqAIJ *a                = (Mat_SeqAIJ*)A->data;
4995:     PetscInt   *aimax            = a->imax,*ai = a->i,*ailen = a->ilen,*aj = a->j;
4996:     MatScalar  *aa               = a->a;
4997:     PetscBool  ignorezeroentries = (((a->ignorezeroentries)&&(addv==ADD_VALUES)) ? PETSC_TRUE : PETSC_FALSE);
4998:     Mat        B                 = aij->B;
4999:     Mat_SeqAIJ *b                = (Mat_SeqAIJ*)B->data;
5000:     PetscInt   *bimax            = b->imax,*bi = b->i,*bilen = b->ilen,*bj = b->j,bm = aij->B->rmap->n,am = aij->A->rmap->n;
5001:     MatScalar  *ba               = b->a;

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

5008:     for (i=0; i<m; i++) {
5009:       if (im[i] < 0) continue;
5010: #if defined(PETSC_USE_DEBUG)
5011:       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);
5012: #endif
5013:       if (im[i] >= rstart && im[i] < rend) {
5014:         row      = im[i] - rstart;
5015:         lastcol1 = -1;
5016:         rp1      = aj + ai[row];
5017:         ap1      = aa + ai[row];
5018:         rmax1    = aimax[row];
5019:         nrow1    = ailen[row];
5020:         low1     = 0;
5021:         high1    = nrow1;
5022:         lastcol2 = -1;
5023:         rp2      = bj + bi[row];
5024:         ap2      = ba + bi[row];
5025:         rmax2    = bimax[row];
5026:         nrow2    = bilen[row];
5027:         low2     = 0;
5028:         high2    = nrow2;

5030:         for (j=0; j<n; j++) {
5031:           if (roworiented) value = v[i*n+j];
5032:           else value = v[i+j*m];
5033:           if (ignorezeroentries && value == 0.0 && (addv == ADD_VALUES)) continue;
5034:           if (in[j] >= cstart && in[j] < cend) {
5035:             col = in[j] - cstart;
5036:             MatSetValues_SeqAIJ_A_Private(row,col,value,addv,im[i],in[j]);
5037:           } else if (in[j] < 0) continue;
5038: #if defined(PETSC_USE_DEBUG)
5039:           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);
5040: #endif
5041:           else {
5042:             if (mat->was_assembled) {
5043:               if (!aij->colmap) {
5044:                 MatCreateColmap_MPIAIJ_Private(mat);
5045:               }
5046: #if defined(PETSC_USE_CTABLE)
5047:               PetscTableFind(aij->colmap,in[j]+1,&col);
5048:               col--;
5049: #else
5050:               col = aij->colmap[in[j]] - 1;
5051: #endif
5052:               if (col < 0 && !((Mat_SeqAIJ*)(aij->A->data))->nonew) {
5053:                 MatDisAssemble_MPIAIJ(mat);
5054:                 col  =  in[j];
5055:                 /* Reinitialize the variables required by MatSetValues_SeqAIJ_B_Private() */
5056:                 B     = aij->B;
5057:                 b     = (Mat_SeqAIJ*)B->data;
5058:                 bimax = b->imax; bi = b->i; bilen = b->ilen; bj = b->j;
5059:                 rp2   = bj + bi[row];
5060:                 ap2   = ba + bi[row];
5061:                 rmax2 = bimax[row];
5062:                 nrow2 = bilen[row];
5063:                 low2  = 0;
5064:                 high2 = nrow2;
5065:                 bm    = aij->B->rmap->n;
5066:                 ba    = b->a;
5067:               }
5068:             } else col = in[j];
5069:             MatSetValues_SeqAIJ_B_Private(row,col,value,addv,im[i],in[j]);
5070:           }
5071:         }
5072:       } else if (!aij->donotstash) {
5073:         if (roworiented) {
5074:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5075:         } else {
5076:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,(PetscBool)(ignorezeroentries && (addv == ADD_VALUES)));
5077:         }
5078:       }
5079:     }
5080:   }
5081:   PetscFunctionReturnVoid();
5082: }