Actual source code: mpibaij.c

petsc-master 2016-02-10
Report Typos and Errors
  2: #include <../src/mat/impls/baij/mpi/mpibaij.h>   /*I  "petscmat.h"  I*/

  4: #include <petscblaslapack.h>
  5: #include <petscsf.h>

  9: PetscErrorCode MatGetRowMaxAbs_MPIBAIJ(Mat A,Vec v,PetscInt idx[])
 10: {
 11:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;
 13:   PetscInt       i,*idxb = 0;
 14:   PetscScalar    *va,*vb;
 15:   Vec            vtmp;

 18:   MatGetRowMaxAbs(a->A,v,idx);
 19:   VecGetArray(v,&va);
 20:   if (idx) {
 21:     for (i=0; i<A->rmap->n; i++) {
 22:       if (PetscAbsScalar(va[i])) idx[i] += A->cmap->rstart;
 23:     }
 24:   }

 26:   VecCreateSeq(PETSC_COMM_SELF,A->rmap->n,&vtmp);
 27:   if (idx) {PetscMalloc1(A->rmap->n,&idxb);}
 28:   MatGetRowMaxAbs(a->B,vtmp,idxb);
 29:   VecGetArray(vtmp,&vb);

 31:   for (i=0; i<A->rmap->n; i++) {
 32:     if (PetscAbsScalar(va[i]) < PetscAbsScalar(vb[i])) {
 33:       va[i] = vb[i];
 34:       if (idx) idx[i] = A->cmap->bs*a->garray[idxb[i]/A->cmap->bs] + (idxb[i] % A->cmap->bs);
 35:     }
 36:   }

 38:   VecRestoreArray(v,&va);
 39:   VecRestoreArray(vtmp,&vb);
 40:   PetscFree(idxb);
 41:   VecDestroy(&vtmp);
 42:   return(0);
 43: }

 47: PetscErrorCode  MatStoreValues_MPIBAIJ(Mat mat)
 48: {
 49:   Mat_MPIBAIJ    *aij = (Mat_MPIBAIJ*)mat->data;

 53:   MatStoreValues(aij->A);
 54:   MatStoreValues(aij->B);
 55:   return(0);
 56: }

 60: PetscErrorCode  MatRetrieveValues_MPIBAIJ(Mat mat)
 61: {
 62:   Mat_MPIBAIJ    *aij = (Mat_MPIBAIJ*)mat->data;

 66:   MatRetrieveValues(aij->A);
 67:   MatRetrieveValues(aij->B);
 68:   return(0);
 69: }

 71: /*
 72:      Local utility routine that creates a mapping from the global column
 73:    number to the local number in the off-diagonal part of the local
 74:    storage of the matrix.  This is done in a non scalable way since the
 75:    length of colmap equals the global matrix length.
 76: */
 79: PetscErrorCode MatCreateColmap_MPIBAIJ_Private(Mat mat)
 80: {
 81:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
 82:   Mat_SeqBAIJ    *B    = (Mat_SeqBAIJ*)baij->B->data;
 84:   PetscInt       nbs = B->nbs,i,bs=mat->rmap->bs;

 87: #if defined(PETSC_USE_CTABLE)
 88:   PetscTableCreate(baij->nbs,baij->Nbs+1,&baij->colmap);
 89:   for (i=0; i<nbs; i++) {
 90:     PetscTableAdd(baij->colmap,baij->garray[i]+1,i*bs+1,INSERT_VALUES);
 91:   }
 92: #else
 93:   PetscMalloc1(baij->Nbs+1,&baij->colmap);
 94:   PetscLogObjectMemory((PetscObject)mat,baij->Nbs*sizeof(PetscInt));
 95:   PetscMemzero(baij->colmap,baij->Nbs*sizeof(PetscInt));
 96:   for (i=0; i<nbs; i++) baij->colmap[baij->garray[i]] = i*bs+1;
 97: #endif
 98:   return(0);
 99: }

101: #define  MatSetValues_SeqBAIJ_A_Private(row,col,value,addv,orow,ocol)       \
102:   { \
103:  \
104:     brow = row/bs;  \
105:     rp   = aj + ai[brow]; ap = aa + bs2*ai[brow]; \
106:     rmax = aimax[brow]; nrow = ailen[brow]; \
107:     bcol = col/bs; \
108:     ridx = row % bs; cidx = col % bs; \
109:     low  = 0; high = nrow; \
110:     while (high-low > 3) { \
111:       t = (low+high)/2; \
112:       if (rp[t] > bcol) high = t; \
113:       else              low  = t; \
114:     } \
115:     for (_i=low; _i<high; _i++) { \
116:       if (rp[_i] > bcol) break; \
117:       if (rp[_i] == bcol) { \
118:         bap = ap +  bs2*_i + bs*cidx + ridx; \
119:         if (addv == ADD_VALUES) *bap += value;  \
120:         else                    *bap  = value;  \
121:         goto a_noinsert; \
122:       } \
123:     } \
124:     if (a->nonew == 1) goto a_noinsert; \
125:     if (a->nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at global row/column (%D, %D) into matrix", orow, ocol); \
126:     MatSeqXAIJReallocateAIJ(A,a->mbs,bs2,nrow,brow,bcol,rmax,aa,ai,aj,rp,ap,aimax,a->nonew,MatScalar); \
127:     N = nrow++ - 1;  \
128:     /* shift up all the later entries in this row */ \
129:     for (ii=N; ii>=_i; ii--) { \
130:       rp[ii+1] = rp[ii]; \
131:       PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); \
132:     } \
133:     if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar)); }  \
134:     rp[_i]                      = bcol;  \
135:     ap[bs2*_i + bs*cidx + ridx] = value;  \
136: a_noinsert:; \
137:     ailen[brow] = nrow; \
138:   }

140: #define  MatSetValues_SeqBAIJ_B_Private(row,col,value,addv,orow,ocol)       \
141:   { \
142:     brow = row/bs;  \
143:     rp   = bj + bi[brow]; ap = ba + bs2*bi[brow]; \
144:     rmax = bimax[brow]; nrow = bilen[brow]; \
145:     bcol = col/bs; \
146:     ridx = row % bs; cidx = col % bs; \
147:     low  = 0; high = nrow; \
148:     while (high-low > 3) { \
149:       t = (low+high)/2; \
150:       if (rp[t] > bcol) high = t; \
151:       else              low  = t; \
152:     } \
153:     for (_i=low; _i<high; _i++) { \
154:       if (rp[_i] > bcol) break; \
155:       if (rp[_i] == bcol) { \
156:         bap = ap +  bs2*_i + bs*cidx + ridx; \
157:         if (addv == ADD_VALUES) *bap += value;  \
158:         else                    *bap  = value;  \
159:         goto b_noinsert; \
160:       } \
161:     } \
162:     if (b->nonew == 1) goto b_noinsert; \
163:     if (b->nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero at global row/column  (%D, %D) into matrix", orow, ocol); \
164:     MatSeqXAIJReallocateAIJ(B,b->mbs,bs2,nrow,brow,bcol,rmax,ba,bi,bj,rp,ap,bimax,b->nonew,MatScalar); \
165:     N = nrow++ - 1;  \
166:     /* shift up all the later entries in this row */ \
167:     for (ii=N; ii>=_i; ii--) { \
168:       rp[ii+1] = rp[ii]; \
169:       PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); \
170:     } \
171:     if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar));}  \
172:     rp[_i]                      = bcol;  \
173:     ap[bs2*_i + bs*cidx + ridx] = value;  \
174: b_noinsert:; \
175:     bilen[brow] = nrow; \
176:   }

180: PetscErrorCode MatSetValues_MPIBAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
181: {
182:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
183:   MatScalar      value;
184:   PetscBool      roworiented = baij->roworiented;
186:   PetscInt       i,j,row,col;
187:   PetscInt       rstart_orig=mat->rmap->rstart;
188:   PetscInt       rend_orig  =mat->rmap->rend,cstart_orig=mat->cmap->rstart;
189:   PetscInt       cend_orig  =mat->cmap->rend,bs=mat->rmap->bs;

191:   /* Some Variables required in the macro */
192:   Mat         A     = baij->A;
193:   Mat_SeqBAIJ *a    = (Mat_SeqBAIJ*)(A)->data;
194:   PetscInt    *aimax=a->imax,*ai=a->i,*ailen=a->ilen,*aj=a->j;
195:   MatScalar   *aa   =a->a;

197:   Mat         B     = baij->B;
198:   Mat_SeqBAIJ *b    = (Mat_SeqBAIJ*)(B)->data;
199:   PetscInt    *bimax=b->imax,*bi=b->i,*bilen=b->ilen,*bj=b->j;
200:   MatScalar   *ba   =b->a;

202:   PetscInt  *rp,ii,nrow,_i,rmax,N,brow,bcol;
203:   PetscInt  low,high,t,ridx,cidx,bs2=a->bs2;
204:   MatScalar *ap,*bap;

207:   for (i=0; i<m; i++) {
208:     if (im[i] < 0) continue;
209: #if defined(PETSC_USE_DEBUG)
210:     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);
211: #endif
212:     if (im[i] >= rstart_orig && im[i] < rend_orig) {
213:       row = im[i] - rstart_orig;
214:       for (j=0; j<n; j++) {
215:         if (in[j] >= cstart_orig && in[j] < cend_orig) {
216:           col = in[j] - cstart_orig;
217:           if (roworiented) value = v[i*n+j];
218:           else             value = v[i+j*m];
219:           MatSetValues_SeqBAIJ_A_Private(row,col,value,addv,im[i],in[j]);
220:           /* MatSetValues_SeqBAIJ(baij->A,1,&row,1,&col,&value,addv); */
221:         } else if (in[j] < 0) continue;
222: #if defined(PETSC_USE_DEBUG)
223:         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);
224: #endif
225:         else {
226:           if (mat->was_assembled) {
227:             if (!baij->colmap) {
228:               MatCreateColmap_MPIBAIJ_Private(mat);
229:             }
230: #if defined(PETSC_USE_CTABLE)
231:             PetscTableFind(baij->colmap,in[j]/bs + 1,&col);
232:             col  = col - 1;
233: #else
234:             col = baij->colmap[in[j]/bs] - 1;
235: #endif
236:             if (col < 0 && !((Mat_SeqBAIJ*)(baij->B->data))->nonew) {
237:               MatDisAssemble_MPIBAIJ(mat);
238:               col  =  in[j];
239:               /* Reinitialize the variables required by MatSetValues_SeqBAIJ_B_Private() */
240:               B    = baij->B;
241:               b    = (Mat_SeqBAIJ*)(B)->data;
242:               bimax=b->imax;bi=b->i;bilen=b->ilen;bj=b->j;
243:               ba   =b->a;
244:             } else if (col < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", im[i], in[j]);
245:             else col += in[j]%bs;
246:           } else col = in[j];
247:           if (roworiented) value = v[i*n+j];
248:           else             value = v[i+j*m];
249:           MatSetValues_SeqBAIJ_B_Private(row,col,value,addv,im[i],in[j]);
250:           /* MatSetValues_SeqBAIJ(baij->B,1,&row,1,&col,&value,addv); */
251:         }
252:       }
253:     } else {
254:       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]);
255:       if (!baij->donotstash) {
256:         mat->assembled = PETSC_FALSE;
257:         if (roworiented) {
258:           MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,PETSC_FALSE);
259:         } else {
260:           MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,PETSC_FALSE);
261:         }
262:       }
263:     }
264:   }
265:   return(0);
266: }

270: PETSC_STATIC_INLINE PetscErrorCode MatSetValuesBlocked_SeqBAIJ_Inlined(Mat A,PetscInt row,PetscInt col,const PetscScalar v[],InsertMode is,PetscInt orow,PetscInt ocol)
271: {
272:   Mat_SeqBAIJ       *a = (Mat_SeqBAIJ*)A->data;
273:   PetscInt          *rp,low,high,t,ii,jj,nrow,i,rmax,N;
274:   PetscInt          *imax=a->imax,*ai=a->i,*ailen=a->ilen;
275:   PetscErrorCode    ierr;
276:   PetscInt          *aj        =a->j,nonew=a->nonew,bs2=a->bs2,bs=A->rmap->bs;
277:   PetscBool         roworiented=a->roworiented;
278:   const PetscScalar *value     = v;
279:   MatScalar         *ap,*aa = a->a,*bap;

282:   rp   = aj + ai[row];
283:   ap   = aa + bs2*ai[row];
284:   rmax = imax[row];
285:   nrow = ailen[row];
286:   low  = 0;
287:   high = nrow;
288:   value = v;
289:   low = 0;
290:   high = nrow;
291:   while (high-low > 7) {
292:     t = (low+high)/2;
293:     if (rp[t] > col) high = t;
294:     else             low  = t;
295:   }
296:   for (i=low; i<high; i++) {
297:     if (rp[i] > col) break;
298:     if (rp[i] == col) {
299:       bap = ap +  bs2*i;
300:       if (roworiented) {
301:         if (is == ADD_VALUES) {
302:           for (ii=0; ii<bs; ii++) {
303:             for (jj=ii; jj<bs2; jj+=bs) {
304:               bap[jj] += *value++;
305:             }
306:           }
307:         } else {
308:           for (ii=0; ii<bs; ii++) {
309:             for (jj=ii; jj<bs2; jj+=bs) {
310:               bap[jj] = *value++;
311:             }
312:           }
313:         }
314:       } else {
315:         if (is == ADD_VALUES) {
316:           for (ii=0; ii<bs; ii++,value+=bs) {
317:             for (jj=0; jj<bs; jj++) {
318:               bap[jj] += value[jj];
319:             }
320:             bap += bs;
321:           }
322:         } else {
323:           for (ii=0; ii<bs; ii++,value+=bs) {
324:             for (jj=0; jj<bs; jj++) {
325:               bap[jj]  = value[jj];
326:             }
327:             bap += bs;
328:           }
329:         }
330:       }
331:       goto noinsert2;
332:     }
333:   }
334:   if (nonew == 1) goto noinsert2;
335:   if (nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new global block indexed nonzero block (%D, %D) in the matrix", orow, ocol);
336:   MatSeqXAIJReallocateAIJ(A,a->mbs,bs2,nrow,row,col,rmax,aa,ai,aj,rp,ap,imax,nonew,MatScalar);
337:   N = nrow++ - 1; high++;
338:   /* shift up all the later entries in this row */
339:   for (ii=N; ii>=i; ii--) {
340:     rp[ii+1] = rp[ii];
341:     PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar));
342:   }
343:   if (N >= i) {
344:     PetscMemzero(ap+bs2*i,bs2*sizeof(MatScalar));
345:   }
346:   rp[i] = col;
347:   bap   = ap +  bs2*i;
348:   if (roworiented) {
349:     for (ii=0; ii<bs; ii++) {
350:       for (jj=ii; jj<bs2; jj+=bs) {
351:         bap[jj] = *value++;
352:       }
353:     }
354:   } else {
355:     for (ii=0; ii<bs; ii++) {
356:       for (jj=0; jj<bs; jj++) {
357:         *bap++ = *value++;
358:       }
359:     }
360:   }
361:   noinsert2:;
362:   ailen[row] = nrow;
363:   return(0);
364: }

368: /*
369:     This routine should be optimized so that the block copy at ** Here a copy is required ** below is not needed
370:     by passing additional stride information into the MatSetValuesBlocked_SeqBAIJ_Inlined() routine
371: */
372: PetscErrorCode MatSetValuesBlocked_MPIBAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
373: {
374:   Mat_MPIBAIJ       *baij = (Mat_MPIBAIJ*)mat->data;
375:   const PetscScalar *value;
376:   MatScalar         *barray     = baij->barray;
377:   PetscBool         roworiented = baij->roworiented;
378:   PetscErrorCode    ierr;
379:   PetscInt          i,j,ii,jj,row,col,rstart=baij->rstartbs;
380:   PetscInt          rend=baij->rendbs,cstart=baij->cstartbs,stepval;
381:   PetscInt          cend=baij->cendbs,bs=mat->rmap->bs,bs2=baij->bs2;

384:   if (!barray) {
385:     PetscMalloc1(bs2,&barray);
386:     baij->barray = barray;
387:   }

389:   if (roworiented) stepval = (n-1)*bs;
390:   else stepval = (m-1)*bs;

392:   for (i=0; i<m; i++) {
393:     if (im[i] < 0) continue;
394: #if defined(PETSC_USE_DEBUG)
395:     if (im[i] >= baij->Mbs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Block indexed row too large %D max %D",im[i],baij->Mbs-1);
396: #endif
397:     if (im[i] >= rstart && im[i] < rend) {
398:       row = im[i] - rstart;
399:       for (j=0; j<n; j++) {
400:         /* If NumCol = 1 then a copy is not required */
401:         if ((roworiented) && (n == 1)) {
402:           barray = (MatScalar*)v + i*bs2;
403:         } else if ((!roworiented) && (m == 1)) {
404:           barray = (MatScalar*)v + j*bs2;
405:         } else { /* Here a copy is required */
406:           if (roworiented) {
407:             value = v + (i*(stepval+bs) + j)*bs;
408:           } else {
409:             value = v + (j*(stepval+bs) + i)*bs;
410:           }
411:           for (ii=0; ii<bs; ii++,value+=bs+stepval) {
412:             for (jj=0; jj<bs; jj++) barray[jj] = value[jj];
413:             barray += bs;
414:           }
415:           barray -= bs2;
416:         }

418:         if (in[j] >= cstart && in[j] < cend) {
419:           col  = in[j] - cstart;
420:           MatSetValuesBlocked_SeqBAIJ_Inlined(baij->A,row,col,barray,addv,im[i],in[j]);
421:         } else if (in[j] < 0) continue;
422: #if defined(PETSC_USE_DEBUG)
423:         else if (in[j] >= baij->Nbs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Block indexed column too large %D max %D",in[j],baij->Nbs-1);
424: #endif
425:         else {
426:           if (mat->was_assembled) {
427:             if (!baij->colmap) {
428:               MatCreateColmap_MPIBAIJ_Private(mat);
429:             }

431: #if defined(PETSC_USE_DEBUG)
432: #if defined(PETSC_USE_CTABLE)
433:             { PetscInt data;
434:               PetscTableFind(baij->colmap,in[j]+1,&data);
435:               if ((data - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
436:             }
437: #else
438:             if ((baij->colmap[in[j]] - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
439: #endif
440: #endif
441: #if defined(PETSC_USE_CTABLE)
442:             PetscTableFind(baij->colmap,in[j]+1,&col);
443:             col  = (col - 1)/bs;
444: #else
445:             col = (baij->colmap[in[j]] - 1)/bs;
446: #endif
447:             if (col < 0 && !((Mat_SeqBAIJ*)(baij->B->data))->nonew) {
448:               MatDisAssemble_MPIBAIJ(mat);
449:               col  =  in[j];
450:             } else if (col < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new blocked indexed nonzero block (%D, %D) into matrix",im[i],in[j]);
451:           } else col = in[j];
452:           MatSetValuesBlocked_SeqBAIJ_Inlined(baij->B,row,col,barray,addv,im[i],in[j]);
453:         }
454:       }
455:     } else {
456:       if (mat->nooffprocentries) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Setting off process block indexed row %D even though MatSetOption(,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE) was set",im[i]);
457:       if (!baij->donotstash) {
458:         if (roworiented) {
459:           MatStashValuesRowBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
460:         } else {
461:           MatStashValuesColBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
462:         }
463:       }
464:     }
465:   }
466:   return(0);
467: }

469: #define HASH_KEY 0.6180339887
470: #define HASH(size,key,tmp) (tmp = (key)*HASH_KEY,(PetscInt)((size)*(tmp-(PetscInt)tmp)))
471: /* #define HASH(size,key) ((PetscInt)((size)*fmod(((key)*HASH_KEY),1))) */
472: /* #define HASH(size,key,tmp) ((PetscInt)((size)*fmod(((key)*HASH_KEY),1))) */
475: PetscErrorCode MatSetValues_MPIBAIJ_HT(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
476: {
477:   Mat_MPIBAIJ    *baij       = (Mat_MPIBAIJ*)mat->data;
478:   PetscBool      roworiented = baij->roworiented;
480:   PetscInt       i,j,row,col;
481:   PetscInt       rstart_orig=mat->rmap->rstart;
482:   PetscInt       rend_orig  =mat->rmap->rend,Nbs=baij->Nbs;
483:   PetscInt       h1,key,size=baij->ht_size,bs=mat->rmap->bs,*HT=baij->ht,idx;
484:   PetscReal      tmp;
485:   MatScalar      **HD = baij->hd,value;
486: #if defined(PETSC_USE_DEBUG)
487:   PetscInt total_ct=baij->ht_total_ct,insert_ct=baij->ht_insert_ct;
488: #endif

491:   for (i=0; i<m; i++) {
492: #if defined(PETSC_USE_DEBUG)
493:     if (im[i] < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row");
494:     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);
495: #endif
496:     row = im[i];
497:     if (row >= rstart_orig && row < rend_orig) {
498:       for (j=0; j<n; j++) {
499:         col = in[j];
500:         if (roworiented) value = v[i*n+j];
501:         else             value = v[i+j*m];
502:         /* Look up PetscInto the Hash Table */
503:         key = (row/bs)*Nbs+(col/bs)+1;
504:         h1  = HASH(size,key,tmp);


507:         idx = h1;
508: #if defined(PETSC_USE_DEBUG)
509:         insert_ct++;
510:         total_ct++;
511:         if (HT[idx] != key) {
512:           for (idx=h1; (idx<size) && (HT[idx]!=key); idx++,total_ct++) ;
513:           if (idx == size) {
514:             for (idx=0; (idx<h1) && (HT[idx]!=key); idx++,total_ct++) ;
515:             if (idx == h1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"(%D,%D) has no entry in the hash table", row, col);
516:           }
517:         }
518: #else
519:         if (HT[idx] != key) {
520:           for (idx=h1; (idx<size) && (HT[idx]!=key); idx++) ;
521:           if (idx == size) {
522:             for (idx=0; (idx<h1) && (HT[idx]!=key); idx++) ;
523:             if (idx == h1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"(%D,%D) has no entry in the hash table", row, col);
524:           }
525:         }
526: #endif
527:         /* A HASH table entry is found, so insert the values at the correct address */
528:         if (addv == ADD_VALUES) *(HD[idx]+ (col % bs)*bs + (row % bs)) += value;
529:         else                    *(HD[idx]+ (col % bs)*bs + (row % bs))  = value;
530:       }
531:     } else if (!baij->donotstash) {
532:       if (roworiented) {
533:         MatStashValuesRow_Private(&mat->stash,im[i],n,in,v+i*n,PETSC_FALSE);
534:       } else {
535:         MatStashValuesCol_Private(&mat->stash,im[i],n,in,v+i,m,PETSC_FALSE);
536:       }
537:     }
538:   }
539: #if defined(PETSC_USE_DEBUG)
540:   baij->ht_total_ct  = total_ct;
541:   baij->ht_insert_ct = insert_ct;
542: #endif
543:   return(0);
544: }

548: PetscErrorCode MatSetValuesBlocked_MPIBAIJ_HT(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
549: {
550:   Mat_MPIBAIJ       *baij       = (Mat_MPIBAIJ*)mat->data;
551:   PetscBool         roworiented = baij->roworiented;
552:   PetscErrorCode    ierr;
553:   PetscInt          i,j,ii,jj,row,col;
554:   PetscInt          rstart=baij->rstartbs;
555:   PetscInt          rend  =mat->rmap->rend,stepval,bs=mat->rmap->bs,bs2=baij->bs2,nbs2=n*bs2;
556:   PetscInt          h1,key,size=baij->ht_size,idx,*HT=baij->ht,Nbs=baij->Nbs;
557:   PetscReal         tmp;
558:   MatScalar         **HD = baij->hd,*baij_a;
559:   const PetscScalar *v_t,*value;
560: #if defined(PETSC_USE_DEBUG)
561:   PetscInt total_ct=baij->ht_total_ct,insert_ct=baij->ht_insert_ct;
562: #endif

565:   if (roworiented) stepval = (n-1)*bs;
566:   else stepval = (m-1)*bs;

568:   for (i=0; i<m; i++) {
569: #if defined(PETSC_USE_DEBUG)
570:     if (im[i] < 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",im[i]);
571:     if (im[i] >= baij->Mbs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",im[i],baij->Mbs-1);
572: #endif
573:     row = im[i];
574:     v_t = v + i*nbs2;
575:     if (row >= rstart && row < rend) {
576:       for (j=0; j<n; j++) {
577:         col = in[j];

579:         /* Look up into the Hash Table */
580:         key = row*Nbs+col+1;
581:         h1  = HASH(size,key,tmp);

583:         idx = h1;
584: #if defined(PETSC_USE_DEBUG)
585:         total_ct++;
586:         insert_ct++;
587:         if (HT[idx] != key) {
588:           for (idx=h1; (idx<size) && (HT[idx]!=key); idx++,total_ct++) ;
589:           if (idx == size) {
590:             for (idx=0; (idx<h1) && (HT[idx]!=key); idx++,total_ct++) ;
591:             if (idx == h1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"(%D,%D) has no entry in the hash table", row, col);
592:           }
593:         }
594: #else
595:         if (HT[idx] != key) {
596:           for (idx=h1; (idx<size) && (HT[idx]!=key); idx++) ;
597:           if (idx == size) {
598:             for (idx=0; (idx<h1) && (HT[idx]!=key); idx++) ;
599:             if (idx == h1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"(%D,%D) has no entry in the hash table", row, col);
600:           }
601:         }
602: #endif
603:         baij_a = HD[idx];
604:         if (roworiented) {
605:           /*value = v + i*(stepval+bs)*bs + j*bs;*/
606:           /* value = v + (i*(stepval+bs)+j)*bs; */
607:           value = v_t;
608:           v_t  += bs;
609:           if (addv == ADD_VALUES) {
610:             for (ii=0; ii<bs; ii++,value+=stepval) {
611:               for (jj=ii; jj<bs2; jj+=bs) {
612:                 baij_a[jj] += *value++;
613:               }
614:             }
615:           } else {
616:             for (ii=0; ii<bs; ii++,value+=stepval) {
617:               for (jj=ii; jj<bs2; jj+=bs) {
618:                 baij_a[jj] = *value++;
619:               }
620:             }
621:           }
622:         } else {
623:           value = v + j*(stepval+bs)*bs + i*bs;
624:           if (addv == ADD_VALUES) {
625:             for (ii=0; ii<bs; ii++,value+=stepval,baij_a+=bs) {
626:               for (jj=0; jj<bs; jj++) {
627:                 baij_a[jj] += *value++;
628:               }
629:             }
630:           } else {
631:             for (ii=0; ii<bs; ii++,value+=stepval,baij_a+=bs) {
632:               for (jj=0; jj<bs; jj++) {
633:                 baij_a[jj] = *value++;
634:               }
635:             }
636:           }
637:         }
638:       }
639:     } else {
640:       if (!baij->donotstash) {
641:         if (roworiented) {
642:           MatStashValuesRowBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
643:         } else {
644:           MatStashValuesColBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
645:         }
646:       }
647:     }
648:   }
649: #if defined(PETSC_USE_DEBUG)
650:   baij->ht_total_ct  = total_ct;
651:   baij->ht_insert_ct = insert_ct;
652: #endif
653:   return(0);
654: }

658: PetscErrorCode MatGetValues_MPIBAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
659: {
660:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
662:   PetscInt       bs       = mat->rmap->bs,i,j,bsrstart = mat->rmap->rstart,bsrend = mat->rmap->rend;
663:   PetscInt       bscstart = mat->cmap->rstart,bscend = mat->cmap->rend,row,col,data;

666:   for (i=0; i<m; i++) {
667:     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]);*/
668:     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);
669:     if (idxm[i] >= bsrstart && idxm[i] < bsrend) {
670:       row = idxm[i] - bsrstart;
671:       for (j=0; j<n; j++) {
672:         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column: %D",idxn[j]); */
673:         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);
674:         if (idxn[j] >= bscstart && idxn[j] < bscend) {
675:           col  = idxn[j] - bscstart;
676:           MatGetValues_SeqBAIJ(baij->A,1,&row,1,&col,v+i*n+j);
677:         } else {
678:           if (!baij->colmap) {
679:             MatCreateColmap_MPIBAIJ_Private(mat);
680:           }
681: #if defined(PETSC_USE_CTABLE)
682:           PetscTableFind(baij->colmap,idxn[j]/bs+1,&data);
683:           data--;
684: #else
685:           data = baij->colmap[idxn[j]/bs]-1;
686: #endif
687:           if ((data < 0) || (baij->garray[data/bs] != idxn[j]/bs)) *(v+i*n+j) = 0.0;
688:           else {
689:             col  = data + idxn[j]%bs;
690:             MatGetValues_SeqBAIJ(baij->B,1,&row,1,&col,v+i*n+j);
691:           }
692:         }
693:       }
694:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
695:   }
696:   return(0);
697: }

701: PetscErrorCode MatNorm_MPIBAIJ(Mat mat,NormType type,PetscReal *nrm)
702: {
703:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
704:   Mat_SeqBAIJ    *amat = (Mat_SeqBAIJ*)baij->A->data,*bmat = (Mat_SeqBAIJ*)baij->B->data;
706:   PetscInt       i,j,bs2=baij->bs2,bs=baij->A->rmap->bs,nz,row,col;
707:   PetscReal      sum = 0.0;
708:   MatScalar      *v;

711:   if (baij->size == 1) {
712:      MatNorm(baij->A,type,nrm);
713:   } else {
714:     if (type == NORM_FROBENIUS) {
715:       v  = amat->a;
716:       nz = amat->nz*bs2;
717:       for (i=0; i<nz; i++) {
718:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
719:       }
720:       v  = bmat->a;
721:       nz = bmat->nz*bs2;
722:       for (i=0; i<nz; i++) {
723:         sum += PetscRealPart(PetscConj(*v)*(*v)); v++;
724:       }
725:       MPIU_Allreduce(&sum,nrm,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
726:       *nrm = PetscSqrtReal(*nrm);
727:     } else if (type == NORM_1) { /* max column sum */
728:       PetscReal *tmp,*tmp2;
729:       PetscInt  *jj,*garray=baij->garray,cstart=baij->rstartbs;
730:       PetscMalloc2(mat->cmap->N,&tmp,mat->cmap->N,&tmp2);
731:       PetscMemzero(tmp,mat->cmap->N*sizeof(PetscReal));
732:       v    = amat->a; jj = amat->j;
733:       for (i=0; i<amat->nz; i++) {
734:         for (j=0; j<bs; j++) {
735:           col = bs*(cstart + *jj) + j; /* column index */
736:           for (row=0; row<bs; row++) {
737:             tmp[col] += PetscAbsScalar(*v);  v++;
738:           }
739:         }
740:         jj++;
741:       }
742:       v = bmat->a; jj = bmat->j;
743:       for (i=0; i<bmat->nz; i++) {
744:         for (j=0; j<bs; j++) {
745:           col = bs*garray[*jj] + j;
746:           for (row=0; row<bs; row++) {
747:             tmp[col] += PetscAbsScalar(*v); v++;
748:           }
749:         }
750:         jj++;
751:       }
752:       MPIU_Allreduce(tmp,tmp2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
753:       *nrm = 0.0;
754:       for (j=0; j<mat->cmap->N; j++) {
755:         if (tmp2[j] > *nrm) *nrm = tmp2[j];
756:       }
757:       PetscFree2(tmp,tmp2);
758:     } else if (type == NORM_INFINITY) { /* max row sum */
759:       PetscReal *sums;
760:       PetscMalloc1(bs,&sums);
761:       sum  = 0.0;
762:       for (j=0; j<amat->mbs; j++) {
763:         for (row=0; row<bs; row++) sums[row] = 0.0;
764:         v  = amat->a + bs2*amat->i[j];
765:         nz = amat->i[j+1]-amat->i[j];
766:         for (i=0; i<nz; i++) {
767:           for (col=0; col<bs; col++) {
768:             for (row=0; row<bs; row++) {
769:               sums[row] += PetscAbsScalar(*v); v++;
770:             }
771:           }
772:         }
773:         v  = bmat->a + bs2*bmat->i[j];
774:         nz = bmat->i[j+1]-bmat->i[j];
775:         for (i=0; i<nz; i++) {
776:           for (col=0; col<bs; col++) {
777:             for (row=0; row<bs; row++) {
778:               sums[row] += PetscAbsScalar(*v); v++;
779:             }
780:           }
781:         }
782:         for (row=0; row<bs; row++) {
783:           if (sums[row] > sum) sum = sums[row];
784:         }
785:       }
786:       MPIU_Allreduce(&sum,nrm,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)mat));
787:       PetscFree(sums);
788:     } else SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"No support for this norm yet");
789:   }
790:   return(0);
791: }

793: /*
794:   Creates the hash table, and sets the table
795:   This table is created only once.
796:   If new entried need to be added to the matrix
797:   then the hash table has to be destroyed and
798:   recreated.
799: */
802: PetscErrorCode MatCreateHashTable_MPIBAIJ_Private(Mat mat,PetscReal factor)
803: {
804:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
805:   Mat            A     = baij->A,B=baij->B;
806:   Mat_SeqBAIJ    *a    = (Mat_SeqBAIJ*)A->data,*b=(Mat_SeqBAIJ*)B->data;
807:   PetscInt       i,j,k,nz=a->nz+b->nz,h1,*ai=a->i,*aj=a->j,*bi=b->i,*bj=b->j;
809:   PetscInt       ht_size,bs2=baij->bs2,rstart=baij->rstartbs;
810:   PetscInt       cstart=baij->cstartbs,*garray=baij->garray,row,col,Nbs=baij->Nbs;
811:   PetscInt       *HT,key;
812:   MatScalar      **HD;
813:   PetscReal      tmp;
814: #if defined(PETSC_USE_INFO)
815:   PetscInt ct=0,max=0;
816: #endif

819:   if (baij->ht) return(0);

821:   baij->ht_size = (PetscInt)(factor*nz);
822:   ht_size       = baij->ht_size;

824:   /* Allocate Memory for Hash Table */
825:   PetscCalloc2(ht_size,&baij->hd,ht_size,&baij->ht);
826:   HD   = baij->hd;
827:   HT   = baij->ht;

829:   /* Loop Over A */
830:   for (i=0; i<a->mbs; i++) {
831:     for (j=ai[i]; j<ai[i+1]; j++) {
832:       row = i+rstart;
833:       col = aj[j]+cstart;

835:       key = row*Nbs + col + 1;
836:       h1  = HASH(ht_size,key,tmp);
837:       for (k=0; k<ht_size; k++) {
838:         if (!HT[(h1+k)%ht_size]) {
839:           HT[(h1+k)%ht_size] = key;
840:           HD[(h1+k)%ht_size] = a->a + j*bs2;
841:           break;
842: #if defined(PETSC_USE_INFO)
843:         } else {
844:           ct++;
845: #endif
846:         }
847:       }
848: #if defined(PETSC_USE_INFO)
849:       if (k> max) max = k;
850: #endif
851:     }
852:   }
853:   /* Loop Over B */
854:   for (i=0; i<b->mbs; i++) {
855:     for (j=bi[i]; j<bi[i+1]; j++) {
856:       row = i+rstart;
857:       col = garray[bj[j]];
858:       key = row*Nbs + col + 1;
859:       h1  = HASH(ht_size,key,tmp);
860:       for (k=0; k<ht_size; k++) {
861:         if (!HT[(h1+k)%ht_size]) {
862:           HT[(h1+k)%ht_size] = key;
863:           HD[(h1+k)%ht_size] = b->a + j*bs2;
864:           break;
865: #if defined(PETSC_USE_INFO)
866:         } else {
867:           ct++;
868: #endif
869:         }
870:       }
871: #if defined(PETSC_USE_INFO)
872:       if (k> max) max = k;
873: #endif
874:     }
875:   }

877:   /* Print Summary */
878: #if defined(PETSC_USE_INFO)
879:   for (i=0,j=0; i<ht_size; i++) {
880:     if (HT[i]) j++;
881:   }
882:   PetscInfo2(mat,"Average Search = %5.2f,max search = %D\n",(!j)? 0.0:((PetscReal)(ct+j))/j,max);
883: #endif
884:   return(0);
885: }

889: PetscErrorCode MatAssemblyBegin_MPIBAIJ(Mat mat,MatAssemblyType mode)
890: {
891:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
893:   PetscInt       nstash,reallocs;

896:   if (baij->donotstash || mat->nooffprocentries) return(0);

898:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
899:   MatStashScatterBegin_Private(mat,&mat->bstash,baij->rangebs);
900:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
901:   PetscInfo2(mat,"Stash has %D entries,uses %D mallocs.\n",nstash,reallocs);
902:   MatStashGetInfo_Private(&mat->bstash,&nstash,&reallocs);
903:   PetscInfo2(mat,"Block-Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
904:   return(0);
905: }

909: PetscErrorCode MatAssemblyEnd_MPIBAIJ(Mat mat,MatAssemblyType mode)
910: {
911:   Mat_MPIBAIJ    *baij=(Mat_MPIBAIJ*)mat->data;
912:   Mat_SeqBAIJ    *a   =(Mat_SeqBAIJ*)baij->A->data;
914:   PetscInt       i,j,rstart,ncols,flg,bs2=baij->bs2;
915:   PetscInt       *row,*col;
916:   PetscBool      r1,r2,r3,other_disassembled;
917:   MatScalar      *val;
918:   PetscMPIInt    n;

921:   /* do not use 'b=(Mat_SeqBAIJ*)baij->B->data' as B can be reset in disassembly */
922:   if (!baij->donotstash && !mat->nooffprocentries) {
923:     while (1) {
924:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
925:       if (!flg) break;

927:       for (i=0; i<n;) {
928:         /* Now identify the consecutive vals belonging to the same row */
929:         for (j=i,rstart=row[j]; j<n; j++) {
930:           if (row[j] != rstart) break;
931:         }
932:         if (j < n) ncols = j-i;
933:         else       ncols = n-i;
934:         /* Now assemble all these values with a single function call */
935:         MatSetValues_MPIBAIJ(mat,1,row+i,ncols,col+i,val+i,mat->insertmode);
936:         i    = j;
937:       }
938:     }
939:     MatStashScatterEnd_Private(&mat->stash);
940:     /* Now process the block-stash. Since the values are stashed column-oriented,
941:        set the roworiented flag to column oriented, and after MatSetValues()
942:        restore the original flags */
943:     r1 = baij->roworiented;
944:     r2 = a->roworiented;
945:     r3 = ((Mat_SeqBAIJ*)baij->B->data)->roworiented;

947:     baij->roworiented = PETSC_FALSE;
948:     a->roworiented    = PETSC_FALSE;

950:     (((Mat_SeqBAIJ*)baij->B->data))->roworiented = PETSC_FALSE; /* b->roworiented */
951:     while (1) {
952:       MatStashScatterGetMesg_Private(&mat->bstash,&n,&row,&col,&val,&flg);
953:       if (!flg) break;

955:       for (i=0; i<n;) {
956:         /* Now identify the consecutive vals belonging to the same row */
957:         for (j=i,rstart=row[j]; j<n; j++) {
958:           if (row[j] != rstart) break;
959:         }
960:         if (j < n) ncols = j-i;
961:         else       ncols = n-i;
962:         MatSetValuesBlocked_MPIBAIJ(mat,1,row+i,ncols,col+i,val+i*bs2,mat->insertmode);
963:         i    = j;
964:       }
965:     }
966:     MatStashScatterEnd_Private(&mat->bstash);

968:     baij->roworiented = r1;
969:     a->roworiented    = r2;

971:     ((Mat_SeqBAIJ*)baij->B->data)->roworiented = r3; /* b->roworiented */
972:   }

974:   MatAssemblyBegin(baij->A,mode);
975:   MatAssemblyEnd(baij->A,mode);

977:   /* determine if any processor has disassembled, if so we must
978:      also disassemble ourselfs, in order that we may reassemble. */
979:   /*
980:      if nonzero structure of submatrix B cannot change then we know that
981:      no processor disassembled thus we can skip this stuff
982:   */
983:   if (!((Mat_SeqBAIJ*)baij->B->data)->nonew) {
984:     MPIU_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));
985:     if (mat->was_assembled && !other_disassembled) {
986:       MatDisAssemble_MPIBAIJ(mat);
987:     }
988:   }

990:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
991:     MatSetUpMultiply_MPIBAIJ(mat);
992:   }
993:   MatAssemblyBegin(baij->B,mode);
994:   MatAssemblyEnd(baij->B,mode);

996: #if defined(PETSC_USE_INFO)
997:   if (baij->ht && mode== MAT_FINAL_ASSEMBLY) {
998:     PetscInfo1(mat,"Average Hash Table Search in MatSetValues = %5.2f\n",((PetscReal)baij->ht_total_ct)/baij->ht_insert_ct);

1000:     baij->ht_total_ct  = 0;
1001:     baij->ht_insert_ct = 0;
1002:   }
1003: #endif
1004:   if (baij->ht_flag && !baij->ht && mode == MAT_FINAL_ASSEMBLY) {
1005:     MatCreateHashTable_MPIBAIJ_Private(mat,baij->ht_fact);

1007:     mat->ops->setvalues        = MatSetValues_MPIBAIJ_HT;
1008:     mat->ops->setvaluesblocked = MatSetValuesBlocked_MPIBAIJ_HT;
1009:   }

1011:   PetscFree2(baij->rowvalues,baij->rowindices);

1013:   baij->rowvalues = 0;

1015:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
1016:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqBAIJ*)(baij->A->data))->nonew) {
1017:     PetscObjectState state = baij->A->nonzerostate + baij->B->nonzerostate;
1018:     MPIU_Allreduce(&state,&mat->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)mat));
1019:   }
1020:   return(0);
1021: }

1023: extern PetscErrorCode MatView_SeqBAIJ(Mat,PetscViewer);
1024: #include <petscdraw.h>
1027: static PetscErrorCode MatView_MPIBAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
1028: {
1029:   Mat_MPIBAIJ       *baij = (Mat_MPIBAIJ*)mat->data;
1030:   PetscErrorCode    ierr;
1031:   PetscMPIInt       rank = baij->rank;
1032:   PetscInt          bs   = mat->rmap->bs;
1033:   PetscBool         iascii,isdraw;
1034:   PetscViewer       sviewer;
1035:   PetscViewerFormat format;

1038:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1039:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1040:   if (iascii) {
1041:     PetscViewerGetFormat(viewer,&format);
1042:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
1043:       MatInfo info;
1044:       MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1045:       MatGetInfo(mat,MAT_LOCAL,&info);
1046:       PetscViewerASCIIPushSynchronized(viewer);
1047:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D bs %D mem %D\n",
1048:                                                 rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,mat->rmap->bs,(PetscInt)info.memory);
1049:       MatGetInfo(baij->A,MAT_LOCAL,&info);
1050:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1051:       MatGetInfo(baij->B,MAT_LOCAL,&info);
1052:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
1053:       PetscViewerFlush(viewer);
1054:       PetscViewerASCIIPopSynchronized(viewer);
1055:       PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
1056:       VecScatterView(baij->Mvctx,viewer);
1057:       return(0);
1058:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
1059:       PetscViewerASCIIPrintf(viewer,"  block size is %D\n",bs);
1060:       return(0);
1061:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
1062:       return(0);
1063:     }
1064:   }

1066:   if (isdraw) {
1067:     PetscDraw draw;
1068:     PetscBool isnull;
1069:     PetscViewerDrawGetDraw(viewer,0,&draw);
1070:     PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
1071:   }

1073:   {
1074:     /* assemble the entire matrix onto first processor. */
1075:     Mat         A;
1076:     Mat_SeqBAIJ *Aloc;
1077:     PetscInt    M = mat->rmap->N,N = mat->cmap->N,*ai,*aj,col,i,j,k,*rvals,mbs = baij->mbs;
1078:     MatScalar   *a;
1079:     const char  *matname;

1081:     /* Here we are creating a temporary matrix, so will assume MPIBAIJ is acceptable */
1082:     /* Perhaps this should be the type of mat? */
1083:     MatCreate(PetscObjectComm((PetscObject)mat),&A);
1084:     if (!rank) {
1085:       MatSetSizes(A,M,N,M,N);
1086:     } else {
1087:       MatSetSizes(A,0,0,M,N);
1088:     }
1089:     MatSetType(A,MATMPIBAIJ);
1090:     MatMPIBAIJSetPreallocation(A,mat->rmap->bs,0,NULL,0,NULL);
1091:     MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
1092:     PetscLogObjectParent((PetscObject)mat,(PetscObject)A);

1094:     /* copy over the A part */
1095:     Aloc = (Mat_SeqBAIJ*)baij->A->data;
1096:     ai   = Aloc->i; aj = Aloc->j; a = Aloc->a;
1097:     PetscMalloc1(bs,&rvals);

1099:     for (i=0; i<mbs; i++) {
1100:       rvals[0] = bs*(baij->rstartbs + i);
1101:       for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
1102:       for (j=ai[i]; j<ai[i+1]; j++) {
1103:         col = (baij->cstartbs+aj[j])*bs;
1104:         for (k=0; k<bs; k++) {
1105:           MatSetValues_MPIBAIJ(A,bs,rvals,1,&col,a,INSERT_VALUES);
1106:           col++; a += bs;
1107:         }
1108:       }
1109:     }
1110:     /* copy over the B part */
1111:     Aloc = (Mat_SeqBAIJ*)baij->B->data;
1112:     ai   = Aloc->i; aj = Aloc->j; a = Aloc->a;
1113:     for (i=0; i<mbs; i++) {
1114:       rvals[0] = bs*(baij->rstartbs + i);
1115:       for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
1116:       for (j=ai[i]; j<ai[i+1]; j++) {
1117:         col = baij->garray[aj[j]]*bs;
1118:         for (k=0; k<bs; k++) {
1119:           MatSetValues_MPIBAIJ(A,bs,rvals,1,&col,a,INSERT_VALUES);
1120:           col++; a += bs;
1121:         }
1122:       }
1123:     }
1124:     PetscFree(rvals);
1125:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1126:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1127:     /*
1128:        Everyone has to call to draw the matrix since the graphics waits are
1129:        synchronized across all processors that share the PetscDraw object
1130:     */
1131:     PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1132:     PetscObjectGetName((PetscObject)mat,&matname);
1133:     if (!rank) {
1134:       PetscObjectSetName((PetscObject)((Mat_MPIBAIJ*)(A->data))->A,matname);
1135:       MatView_SeqBAIJ(((Mat_MPIBAIJ*)(A->data))->A,sviewer);
1136:     }
1137:     PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1138:     PetscViewerFlush(viewer);
1139:     MatDestroy(&A);
1140:   }
1141:   return(0);
1142: }

1146: static PetscErrorCode MatView_MPIBAIJ_Binary(Mat mat,PetscViewer viewer)
1147: {
1148:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)mat->data;
1149:   Mat_SeqBAIJ    *A = (Mat_SeqBAIJ*)a->A->data;
1150:   Mat_SeqBAIJ    *B = (Mat_SeqBAIJ*)a->B->data;
1152:   PetscInt       i,*row_lens,*crow_lens,bs = mat->rmap->bs,j,k,bs2=a->bs2,header[4],nz,rlen;
1153:   PetscInt       *range=0,nzmax,*column_indices,cnt,col,*garray = a->garray,cstart = mat->cmap->rstart/bs,len,pcnt,l,ll;
1154:   int            fd;
1155:   PetscScalar    *column_values;
1156:   FILE           *file;
1157:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag;
1158:   PetscInt       message_count,flowcontrolcount;

1161:   MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
1162:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1163:   nz   = bs2*(A->nz + B->nz);
1164:   rlen = mat->rmap->n;
1165:   PetscViewerBinaryGetDescriptor(viewer,&fd);
1166:   if (!rank) {
1167:     header[0] = MAT_FILE_CLASSID;
1168:     header[1] = mat->rmap->N;
1169:     header[2] = mat->cmap->N;

1171:     MPI_Reduce(&nz,&header[3],1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1172:     PetscBinaryWrite(fd,header,4,PETSC_INT,PETSC_TRUE);
1173:     /* get largest number of rows any processor has */
1174:     range = mat->rmap->range;
1175:     for (i=1; i<size; i++) {
1176:       rlen = PetscMax(rlen,range[i+1] - range[i]);
1177:     }
1178:   } else {
1179:     MPI_Reduce(&nz,0,1,MPIU_INT,MPI_SUM,0,PetscObjectComm((PetscObject)mat));
1180:   }

1182:   PetscMalloc1(rlen/bs,&crow_lens);
1183:   /* compute lengths of each row  */
1184:   for (i=0; i<a->mbs; i++) {
1185:     crow_lens[i] = A->i[i+1] - A->i[i] + B->i[i+1] - B->i[i];
1186:   }
1187:   /* store the row lengths to the file */
1188:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1189:   if (!rank) {
1190:     MPI_Status status;
1191:     PetscMalloc1(rlen,&row_lens);
1192:     rlen = (range[1] - range[0])/bs;
1193:     for (i=0; i<rlen; i++) {
1194:       for (j=0; j<bs; j++) {
1195:         row_lens[i*bs+j] = bs*crow_lens[i];
1196:       }
1197:     }
1198:     PetscBinaryWrite(fd,row_lens,bs*rlen,PETSC_INT,PETSC_TRUE);
1199:     for (i=1; i<size; i++) {
1200:       rlen = (range[i+1] - range[i])/bs;
1201:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1202:       MPI_Recv(crow_lens,rlen,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1203:       for (k=0; k<rlen; k++) {
1204:         for (j=0; j<bs; j++) {
1205:           row_lens[k*bs+j] = bs*crow_lens[k];
1206:         }
1207:       }
1208:       PetscBinaryWrite(fd,row_lens,bs*rlen,PETSC_INT,PETSC_TRUE);
1209:     }
1210:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1211:     PetscFree(row_lens);
1212:   } else {
1213:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1214:     MPI_Send(crow_lens,mat->rmap->n/bs,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1215:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1216:   }
1217:   PetscFree(crow_lens);

1219:   /* load up the local column indices. Include for all rows not just one for each block row since process 0 does not have the
1220:      information needed to make it for each row from a block row. This does require more communication but still not more than
1221:      the communication needed for the nonzero values  */
1222:   nzmax = nz; /*  space a largest processor needs */
1223:   MPI_Reduce(&nz,&nzmax,1,MPIU_INT,MPI_MAX,0,PetscObjectComm((PetscObject)mat));
1224:   PetscMalloc1(nzmax,&column_indices);
1225:   cnt   = 0;
1226:   for (i=0; i<a->mbs; i++) {
1227:     pcnt = cnt;
1228:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1229:       if ((col = garray[B->j[j]]) > cstart) break;
1230:       for (l=0; l<bs; l++) {
1231:         column_indices[cnt++] = bs*col+l;
1232:       }
1233:     }
1234:     for (k=A->i[i]; k<A->i[i+1]; k++) {
1235:       for (l=0; l<bs; l++) {
1236:         column_indices[cnt++] = bs*(A->j[k] + cstart)+l;
1237:       }
1238:     }
1239:     for (; j<B->i[i+1]; j++) {
1240:       for (l=0; l<bs; l++) {
1241:         column_indices[cnt++] = bs*garray[B->j[j]]+l;
1242:       }
1243:     }
1244:     len = cnt - pcnt;
1245:     for (k=1; k<bs; k++) {
1246:       PetscMemcpy(&column_indices[cnt],&column_indices[pcnt],len*sizeof(PetscInt));
1247:       cnt += len;
1248:     }
1249:   }
1250:   if (cnt != nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_LIB,"Internal PETSc error: cnt = %D nz = %D",cnt,nz);

1252:   /* store the columns to the file */
1253:   PetscViewerFlowControlStart(viewer,&message_count,&flowcontrolcount);
1254:   if (!rank) {
1255:     MPI_Status status;
1256:     PetscBinaryWrite(fd,column_indices,nz,PETSC_INT,PETSC_TRUE);
1257:     for (i=1; i<size; i++) {
1258:       PetscViewerFlowControlStepMaster(viewer,i,&message_count,flowcontrolcount);
1259:       MPI_Recv(&cnt,1,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1260:       MPI_Recv(column_indices,cnt,MPIU_INT,i,tag,PetscObjectComm((PetscObject)mat),&status);
1261:       PetscBinaryWrite(fd,column_indices,cnt,PETSC_INT,PETSC_TRUE);
1262:     }
1263:     PetscViewerFlowControlEndMaster(viewer,&message_count);
1264:   } else {
1265:     PetscViewerFlowControlStepWorker(viewer,rank,&message_count);
1266:     MPI_Send(&cnt,1,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1267:     MPI_Send(column_indices,cnt,MPIU_INT,0,tag,PetscObjectComm((PetscObject)mat));
1268:     PetscViewerFlowControlEndWorker(viewer,&message_count);
1269:   }
1270:   PetscFree(column_indices);

1272:   /* load up the numerical values */
1273:   PetscMalloc1(nzmax,&column_values);
1274:   cnt  = 0;
1275:   for (i=0; i<a->mbs; i++) {
1276:     rlen = bs*(B->i[i+1] - B->i[i] + A->i[i+1] - A->i[i]);
1277:     for (j=B->i[i]; j<B->i[i+1]; j++) {
1278:       if (garray[B->j[j]] > cstart) break;
1279:       for (l=0; l<bs; l++) {
1280:         for (ll=0; ll<bs; ll++) {
1281:           column_values[cnt + l*rlen + ll] = B->a[bs2*j+l+bs*ll];
1282:         }
1283:       }
1284:       cnt += bs;
1285:     }
1286:     for (k=A->i[i]; k<A->i[i+1]; k++) {
1287:       for (l=0; l<bs; l++) {
1288:         for (ll=0; ll<bs; ll++) {
1289:           column_values[cnt + l*rlen + ll] = A->a[bs2*k+l+bs*ll];
1290:         }
1291:       }
1292:       cnt += bs;
1293:     }
1294:     for (; j<B->i[i+1]; j++) {
1295:       for (l=0; l<bs; l++) {
1296:         for (ll=0; ll<bs; ll++) {
1297:           column_values[cnt + l*rlen + ll] = B->a[bs2*j+l+bs*ll];
1298:         }
1299:       }
1300:       cnt += bs;
1301:     }
1302:     cnt += (bs-1)*rlen;
1303:   }
1304:   if (cnt != nz) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal PETSc error: cnt = %D nz = %D",cnt,nz);

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

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

1335: PetscErrorCode MatView_MPIBAIJ(Mat mat,PetscViewer viewer)
1336: {
1338:   PetscBool      iascii,isdraw,issocket,isbinary;

1341:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1342:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1343:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
1344:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1345:   if (iascii || isdraw || issocket) {
1346:     MatView_MPIBAIJ_ASCIIorDraworSocket(mat,viewer);
1347:   } else if (isbinary) {
1348:     MatView_MPIBAIJ_Binary(mat,viewer);
1349:   }
1350:   return(0);
1351: }

1355: PetscErrorCode MatDestroy_MPIBAIJ(Mat mat)
1356: {
1357:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;

1361: #if defined(PETSC_USE_LOG)
1362:   PetscLogObjectState((PetscObject)mat,"Rows=%D,Cols=%D",mat->rmap->N,mat->cmap->N);
1363: #endif
1364:   MatStashDestroy_Private(&mat->stash);
1365:   MatStashDestroy_Private(&mat->bstash);
1366:   MatDestroy(&baij->A);
1367:   MatDestroy(&baij->B);
1368: #if defined(PETSC_USE_CTABLE)
1369:   PetscTableDestroy(&baij->colmap);
1370: #else
1371:   PetscFree(baij->colmap);
1372: #endif
1373:   PetscFree(baij->garray);
1374:   VecDestroy(&baij->lvec);
1375:   VecScatterDestroy(&baij->Mvctx);
1376:   PetscFree2(baij->rowvalues,baij->rowindices);
1377:   PetscFree(baij->barray);
1378:   PetscFree2(baij->hd,baij->ht);
1379:   PetscFree(baij->rangebs);
1380:   PetscFree(mat->data);

1382:   PetscObjectChangeTypeName((PetscObject)mat,0);
1383:   PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);
1384:   PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);
1385:   PetscObjectComposeFunction((PetscObject)mat,"MatGetDiagonalBlock_C",NULL);
1386:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIBAIJSetPreallocation_C",NULL);
1387:   PetscObjectComposeFunction((PetscObject)mat,"MatMPIBAIJSetPreallocationCSR_C",NULL);
1388:   PetscObjectComposeFunction((PetscObject)mat,"MatDiagonalScaleLocal_C",NULL);
1389:   PetscObjectComposeFunction((PetscObject)mat,"MatSetHashTableFactor_C",NULL);
1390:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpibaij_mpisbaij_C",NULL);
1391:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpibaij_mpibstrm_C",NULL);
1392:   return(0);
1393: }

1397: PetscErrorCode MatMult_MPIBAIJ(Mat A,Vec xx,Vec yy)
1398: {
1399:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;
1401:   PetscInt       nt;

1404:   VecGetLocalSize(xx,&nt);
1405:   if (nt != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");
1406:   VecGetLocalSize(yy,&nt);
1407:   if (nt != A->rmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible parition of A and yy");
1408:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1409:   (*a->A->ops->mult)(a->A,xx,yy);
1410:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1411:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
1412:   return(0);
1413: }

1417: PetscErrorCode MatMultAdd_MPIBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1418: {
1419:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

1423:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1424:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
1425:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
1426:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);
1427:   return(0);
1428: }

1432: PetscErrorCode MatMultTranspose_MPIBAIJ(Mat A,Vec xx,Vec yy)
1433: {
1434:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;
1436:   PetscBool      merged;

1439:   VecScatterGetMerged(a->Mvctx,&merged);
1440:   /* do nondiagonal part */
1441:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1442:   if (!merged) {
1443:     /* send it on its way */
1444:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1445:     /* do local part */
1446:     (*a->A->ops->multtranspose)(a->A,xx,yy);
1447:     /* receive remote parts: note this assumes the values are not actually */
1448:     /* inserted in yy until the next line */
1449:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1450:   } else {
1451:     /* do local part */
1452:     (*a->A->ops->multtranspose)(a->A,xx,yy);
1453:     /* send it on its way */
1454:     VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1455:     /* values actually were received in the Begin() but we need to call this nop */
1456:     VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
1457:   }
1458:   return(0);
1459: }

1463: PetscErrorCode MatMultTransposeAdd_MPIBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
1464: {
1465:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

1469:   /* do nondiagonal part */
1470:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
1471:   /* send it on its way */
1472:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1473:   /* do local part */
1474:   (*a->A->ops->multtransposeadd)(a->A,xx,yy,zz);
1475:   /* receive remote parts: note this assumes the values are not actually */
1476:   /* inserted in yy until the next line, which is true for my implementation*/
1477:   /* but is not perhaps always true. */
1478:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
1479:   return(0);
1480: }

1482: /*
1483:   This only works correctly for square matrices where the subblock A->A is the
1484:    diagonal block
1485: */
1488: PetscErrorCode MatGetDiagonal_MPIBAIJ(Mat A,Vec v)
1489: {
1490:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

1494:   if (A->rmap->N != A->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block");
1495:   MatGetDiagonal(a->A,v);
1496:   return(0);
1497: }

1501: PetscErrorCode MatScale_MPIBAIJ(Mat A,PetscScalar aa)
1502: {
1503:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

1507:   MatScale(a->A,aa);
1508:   MatScale(a->B,aa);
1509:   return(0);
1510: }

1514: PetscErrorCode MatGetRow_MPIBAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1515: {
1516:   Mat_MPIBAIJ    *mat = (Mat_MPIBAIJ*)matin->data;
1517:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
1519:   PetscInt       bs = matin->rmap->bs,bs2 = mat->bs2,i,*cworkA,*cworkB,**pcA,**pcB;
1520:   PetscInt       nztot,nzA,nzB,lrow,brstart = matin->rmap->rstart,brend = matin->rmap->rend;
1521:   PetscInt       *cmap,*idx_p,cstart = mat->cstartbs;

1524:   if (row < brstart || row >= brend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local rows");
1525:   if (mat->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Already active");
1526:   mat->getrowactive = PETSC_TRUE;

1528:   if (!mat->rowvalues && (idx || v)) {
1529:     /*
1530:         allocate enough space to hold information from the longest row.
1531:     */
1532:     Mat_SeqBAIJ *Aa = (Mat_SeqBAIJ*)mat->A->data,*Ba = (Mat_SeqBAIJ*)mat->B->data;
1533:     PetscInt    max = 1,mbs = mat->mbs,tmp;
1534:     for (i=0; i<mbs; i++) {
1535:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i];
1536:       if (max < tmp) max = tmp;
1537:     }
1538:     PetscMalloc2(max*bs2,&mat->rowvalues,max*bs2,&mat->rowindices);
1539:   }
1540:   lrow = row - brstart;

1542:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1543:   if (!v)   {pvA = 0; pvB = 0;}
1544:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1545:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1546:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1547:   nztot = nzA + nzB;

1549:   cmap = mat->garray;
1550:   if (v  || idx) {
1551:     if (nztot) {
1552:       /* Sort by increasing column numbers, assuming A and B already sorted */
1553:       PetscInt imark = -1;
1554:       if (v) {
1555:         *v = v_p = mat->rowvalues;
1556:         for (i=0; i<nzB; i++) {
1557:           if (cmap[cworkB[i]/bs] < cstart) v_p[i] = vworkB[i];
1558:           else break;
1559:         }
1560:         imark = i;
1561:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1562:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1563:       }
1564:       if (idx) {
1565:         *idx = idx_p = mat->rowindices;
1566:         if (imark > -1) {
1567:           for (i=0; i<imark; i++) {
1568:             idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
1569:           }
1570:         } else {
1571:           for (i=0; i<nzB; i++) {
1572:             if (cmap[cworkB[i]/bs] < cstart) idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
1573:             else break;
1574:           }
1575:           imark = i;
1576:         }
1577:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart*bs + cworkA[i];
1578:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
1579:       }
1580:     } else {
1581:       if (idx) *idx = 0;
1582:       if (v)   *v   = 0;
1583:     }
1584:   }
1585:   *nz  = nztot;
1586:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1587:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1588:   return(0);
1589: }

1593: PetscErrorCode MatRestoreRow_MPIBAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1594: {
1595:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ*)mat->data;

1598:   if (!baij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow not called");
1599:   baij->getrowactive = PETSC_FALSE;
1600:   return(0);
1601: }

1605: PetscErrorCode MatZeroEntries_MPIBAIJ(Mat A)
1606: {
1607:   Mat_MPIBAIJ    *l = (Mat_MPIBAIJ*)A->data;

1611:   MatZeroEntries(l->A);
1612:   MatZeroEntries(l->B);
1613:   return(0);
1614: }

1618: PetscErrorCode MatGetInfo_MPIBAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1619: {
1620:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)matin->data;
1621:   Mat            A  = a->A,B = a->B;
1623:   PetscReal      isend[5],irecv[5];

1626:   info->block_size = (PetscReal)matin->rmap->bs;

1628:   MatGetInfo(A,MAT_LOCAL,info);

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

1633:   MatGetInfo(B,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:   if (flag == MAT_LOCAL) {
1639:     info->nz_used      = isend[0];
1640:     info->nz_allocated = isend[1];
1641:     info->nz_unneeded  = isend[2];
1642:     info->memory       = isend[3];
1643:     info->mallocs      = isend[4];
1644:   } else if (flag == MAT_GLOBAL_MAX) {
1645:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

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

1655:     info->nz_used      = irecv[0];
1656:     info->nz_allocated = irecv[1];
1657:     info->nz_unneeded  = irecv[2];
1658:     info->memory       = irecv[3];
1659:     info->mallocs      = irecv[4];
1660:   } else SETERRQ1(PetscObjectComm((PetscObject)matin),PETSC_ERR_ARG_WRONG,"Unknown MatInfoType argument %d",(int)flag);
1661:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1662:   info->fill_ratio_needed = 0;
1663:   info->factor_mallocs    = 0;
1664:   return(0);
1665: }

1669: PetscErrorCode MatSetOption_MPIBAIJ(Mat A,MatOption op,PetscBool flg)
1670: {
1671:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

1675:   switch (op) {
1676:   case MAT_NEW_NONZERO_LOCATIONS:
1677:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1678:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1679:   case MAT_KEEP_NONZERO_PATTERN:
1680:   case MAT_NEW_NONZERO_LOCATION_ERR:
1681:     MatSetOption(a->A,op,flg);
1682:     MatSetOption(a->B,op,flg);
1683:     break;
1684:   case MAT_ROW_ORIENTED:
1685:     a->roworiented = flg;

1687:     MatSetOption(a->A,op,flg);
1688:     MatSetOption(a->B,op,flg);
1689:     break;
1690:   case MAT_NEW_DIAGONALS:
1691:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1692:     break;
1693:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1694:     a->donotstash = flg;
1695:     break;
1696:   case MAT_USE_HASH_TABLE:
1697:     a->ht_flag = flg;
1698:     break;
1699:   case MAT_SYMMETRIC:
1700:   case MAT_STRUCTURALLY_SYMMETRIC:
1701:   case MAT_HERMITIAN:
1702:   case MAT_SYMMETRY_ETERNAL:
1703:     MatSetOption(a->A,op,flg);
1704:     break;
1705:   default:
1706:     SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"unknown option %d",op);
1707:   }
1708:   return(0);
1709: }

1713: PetscErrorCode MatTranspose_MPIBAIJ(Mat A,MatReuse reuse,Mat *matout)
1714: {
1715:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)A->data;
1716:   Mat_SeqBAIJ    *Aloc;
1717:   Mat            B;
1719:   PetscInt       M =A->rmap->N,N=A->cmap->N,*ai,*aj,i,*rvals,j,k,col;
1720:   PetscInt       bs=A->rmap->bs,mbs=baij->mbs;
1721:   MatScalar      *a;

1724:   if (reuse == MAT_REUSE_MATRIX && A == *matout && M != N) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Square matrix only for in-place");
1725:   if (reuse == MAT_INITIAL_MATRIX || *matout == A) {
1726:     MatCreate(PetscObjectComm((PetscObject)A),&B);
1727:     MatSetSizes(B,A->cmap->n,A->rmap->n,N,M);
1728:     MatSetType(B,((PetscObject)A)->type_name);
1729:     /* Do not know preallocation information, but must set block size */
1730:     MatMPIBAIJSetPreallocation(B,A->rmap->bs,PETSC_DECIDE,NULL,PETSC_DECIDE,NULL);
1731:   } else {
1732:     B = *matout;
1733:   }

1735:   /* copy over the A part */
1736:   Aloc = (Mat_SeqBAIJ*)baij->A->data;
1737:   ai   = Aloc->i; aj = Aloc->j; a = Aloc->a;
1738:   PetscMalloc1(bs,&rvals);

1740:   for (i=0; i<mbs; i++) {
1741:     rvals[0] = bs*(baij->rstartbs + i);
1742:     for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
1743:     for (j=ai[i]; j<ai[i+1]; j++) {
1744:       col = (baij->cstartbs+aj[j])*bs;
1745:       for (k=0; k<bs; k++) {
1746:         MatSetValues_MPIBAIJ(B,1,&col,bs,rvals,a,INSERT_VALUES);

1748:         col++; a += bs;
1749:       }
1750:     }
1751:   }
1752:   /* copy over the B part */
1753:   Aloc = (Mat_SeqBAIJ*)baij->B->data;
1754:   ai   = Aloc->i; aj = Aloc->j; a = Aloc->a;
1755:   for (i=0; i<mbs; i++) {
1756:     rvals[0] = bs*(baij->rstartbs + i);
1757:     for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
1758:     for (j=ai[i]; j<ai[i+1]; j++) {
1759:       col = baij->garray[aj[j]]*bs;
1760:       for (k=0; k<bs; k++) {
1761:         MatSetValues_MPIBAIJ(B,1,&col,bs,rvals,a,INSERT_VALUES);
1762:         col++;
1763:         a += bs;
1764:       }
1765:     }
1766:   }
1767:   PetscFree(rvals);
1768:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1769:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

1771:   if (reuse == MAT_INITIAL_MATRIX || *matout != A) *matout = B;
1772:   else {
1773:     MatHeaderMerge(A,&B);
1774:   }
1775:   return(0);
1776: }

1780: PetscErrorCode MatDiagonalScale_MPIBAIJ(Mat mat,Vec ll,Vec rr)
1781: {
1782:   Mat_MPIBAIJ    *baij = (Mat_MPIBAIJ*)mat->data;
1783:   Mat            a     = baij->A,b = baij->B;
1785:   PetscInt       s1,s2,s3;

1788:   MatGetLocalSize(mat,&s2,&s3);
1789:   if (rr) {
1790:     VecGetLocalSize(rr,&s1);
1791:     if (s1!=s3) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
1792:     /* Overlap communication with computation. */
1793:     VecScatterBegin(baij->Mvctx,rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1794:   }
1795:   if (ll) {
1796:     VecGetLocalSize(ll,&s1);
1797:     if (s1!=s2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
1798:     (*b->ops->diagonalscale)(b,ll,NULL);
1799:   }
1800:   /* scale  the diagonal block */
1801:   (*a->ops->diagonalscale)(a,ll,rr);

1803:   if (rr) {
1804:     /* Do a scatter end and then right scale the off-diagonal block */
1805:     VecScatterEnd(baij->Mvctx,rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1806:     (*b->ops->diagonalscale)(b,NULL,baij->lvec);
1807:   }
1808:   return(0);
1809: }

1813: PetscErrorCode MatZeroRows_MPIBAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1814: {
1815:   Mat_MPIBAIJ   *l      = (Mat_MPIBAIJ *) A->data;
1816:   PetscInt      *owners = A->rmap->range;
1817:   PetscInt       n      = A->rmap->n;
1818:   PetscSF        sf;
1819:   PetscInt      *lrows;
1820:   PetscSFNode   *rrows;
1821:   PetscInt       r, p = 0, len = 0;

1825:   /* Create SF where leaves are input rows and roots are owned rows */
1826:   PetscMalloc1(n, &lrows);
1827:   for (r = 0; r < n; ++r) lrows[r] = -1;
1828:   if (!A->nooffproczerorows) {PetscMalloc1(N, &rrows);}
1829:   for (r = 0; r < N; ++r) {
1830:     const PetscInt idx   = rows[r];
1831:     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);
1832:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
1833:       PetscLayoutFindOwner(A->rmap,idx,&p);
1834:     }
1835:     if (A->nooffproczerorows) {
1836:       if (p != l->rank) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"MAT_NO_OFF_PROC_ZERO_ROWS set, but row %D is not owned by rank %d",idx,l->rank);
1837:       lrows[len++] = idx - owners[p];
1838:     } else {
1839:       rrows[r].rank = p;
1840:       rrows[r].index = rows[r] - owners[p];
1841:     }
1842:   }
1843:   if (!A->nooffproczerorows) {
1844:     PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
1845:     PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
1846:     /* Collect flags for rows to be zeroed */
1847:     PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
1848:     PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
1849:     PetscSFDestroy(&sf);
1850:     /* Compress and put in row numbers */
1851:     for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
1852:   }
1853:   /* fix right hand side if needed */
1854:   if (x && b) {
1855:     const PetscScalar *xx;
1856:     PetscScalar       *bb;

1858:     VecGetArrayRead(x,&xx);
1859:     VecGetArray(b,&bb);
1860:     for (r = 0; r < len; ++r) bb[lrows[r]] = diag*xx[lrows[r]];
1861:     VecRestoreArrayRead(x,&xx);
1862:     VecRestoreArray(b,&bb);
1863:   }

1865:   /* actually zap the local rows */
1866:   /*
1867:         Zero the required rows. If the "diagonal block" of the matrix
1868:      is square and the user wishes to set the diagonal we use separate
1869:      code so that MatSetValues() is not called for each diagonal allocating
1870:      new memory, thus calling lots of mallocs and slowing things down.

1872:   */
1873:   /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
1874:   MatZeroRows_SeqBAIJ(l->B,len,lrows,0.0,NULL,NULL);
1875:   if ((diag != 0.0) && (l->A->rmap->N == l->A->cmap->N)) {
1876:     MatZeroRows_SeqBAIJ(l->A,len,lrows,diag,NULL,NULL);
1877:   } else if (diag != 0.0) {
1878:     MatZeroRows_SeqBAIJ(l->A,len,lrows,0.0,0,0);
1879:     if (((Mat_SeqBAIJ*)l->A->data)->nonew) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatZeroRows() on rectangular matrices cannot be used with the Mat options \n\
1880:        MAT_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
1881:     for (r = 0; r < len; ++r) {
1882:       const PetscInt row = lrows[r] + A->rmap->rstart;
1883:       MatSetValues(A,1,&row,1,&row,&diag,INSERT_VALUES);
1884:     }
1885:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1886:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1887:   } else {
1888:     MatZeroRows_SeqBAIJ(l->A,len,lrows,0.0,NULL,NULL);
1889:   }
1890:   PetscFree(lrows);

1892:   /* only change matrix nonzero state if pattern was allowed to be changed */
1893:   if (!((Mat_SeqBAIJ*)(l->A->data))->keepnonzeropattern) {
1894:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
1895:     MPIU_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
1896:   }
1897:   return(0);
1898: }

1902: PetscErrorCode MatZeroRowsColumns_MPIBAIJ(Mat A,PetscInt N,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1903: {
1904:   Mat_MPIBAIJ       *l = (Mat_MPIBAIJ*)A->data;
1905:   PetscErrorCode    ierr;
1906:   PetscMPIInt       n = A->rmap->n;
1907:   PetscInt          i,j,k,r,p = 0,len = 0,row,col,count;
1908:   PetscInt          *lrows,*owners = A->rmap->range;
1909:   PetscSFNode       *rrows;
1910:   PetscSF           sf;
1911:   const PetscScalar *xx;
1912:   PetscScalar       *bb,*mask;
1913:   Vec               xmask,lmask;
1914:   Mat_SeqBAIJ       *baij = (Mat_SeqBAIJ*)l->B->data;
1915:   PetscInt           bs = A->rmap->bs, bs2 = baij->bs2;
1916:   PetscScalar       *aa;

1919:   /* Create SF where leaves are input rows and roots are owned rows */
1920:   PetscMalloc1(n, &lrows);
1921:   for (r = 0; r < n; ++r) lrows[r] = -1;
1922:   PetscMalloc1(N, &rrows);
1923:   for (r = 0; r < N; ++r) {
1924:     const PetscInt idx   = rows[r];
1925:     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);
1926:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this row too */
1927:       PetscLayoutFindOwner(A->rmap,idx,&p);
1928:     }
1929:     rrows[r].rank  = p;
1930:     rrows[r].index = rows[r] - owners[p];
1931:   }
1932:   PetscSFCreate(PetscObjectComm((PetscObject) A), &sf);
1933:   PetscSFSetGraph(sf, n, N, NULL, PETSC_OWN_POINTER, rrows, PETSC_OWN_POINTER);
1934:   /* Collect flags for rows to be zeroed */
1935:   PetscSFReduceBegin(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
1936:   PetscSFReduceEnd(sf, MPIU_INT, (PetscInt *) rows, lrows, MPI_LOR);
1937:   PetscSFDestroy(&sf);
1938:   /* Compress and put in row numbers */
1939:   for (r = 0; r < n; ++r) if (lrows[r] >= 0) lrows[len++] = r;
1940:   /* zero diagonal part of matrix */
1941:   MatZeroRowsColumns(l->A,len,lrows,diag,x,b);
1942:   /* handle off diagonal part of matrix */
1943:   MatCreateVecs(A,&xmask,NULL);
1944:   VecDuplicate(l->lvec,&lmask);
1945:   VecGetArray(xmask,&bb);
1946:   for (i=0; i<len; i++) bb[lrows[i]] = 1;
1947:   VecRestoreArray(xmask,&bb);
1948:   VecScatterBegin(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
1949:   VecScatterEnd(l->Mvctx,xmask,lmask,ADD_VALUES,SCATTER_FORWARD);
1950:   VecDestroy(&xmask);
1951:   if (x) {
1952:     VecScatterBegin(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
1953:     VecScatterEnd(l->Mvctx,x,l->lvec,INSERT_VALUES,SCATTER_FORWARD);
1954:     VecGetArrayRead(l->lvec,&xx);
1955:     VecGetArray(b,&bb);
1956:   }
1957:   VecGetArray(lmask,&mask);
1958:   /* remove zeroed rows of off diagonal matrix */
1959:   for (i = 0; i < len; ++i) {
1960:     row   = lrows[i];
1961:     count = (baij->i[row/bs +1] - baij->i[row/bs])*bs;
1962:     aa    = ((MatScalar*)(baij->a)) + baij->i[row/bs]*bs2 + (row%bs);
1963:     for (k = 0; k < count; ++k) {
1964:       aa[0] = 0.0;
1965:       aa   += bs;
1966:     }
1967:   }
1968:   /* loop over all elements of off process part of matrix zeroing removed columns*/
1969:   for (i = 0; i < l->B->rmap->N; ++i) {
1970:     row = i/bs;
1971:     for (j = baij->i[row]; j < baij->i[row+1]; ++j) {
1972:       for (k = 0; k < bs; ++k) {
1973:         col = bs*baij->j[j] + k;
1974:         if (PetscAbsScalar(mask[col])) {
1975:           aa = ((MatScalar*)(baij->a)) + j*bs2 + (i%bs) + bs*k;
1976:           if (b) bb[i] -= aa[0]*xx[col];
1977:           aa[0] = 0.0;
1978:         }
1979:       }
1980:     }
1981:   }
1982:   if (x) {
1983:     VecRestoreArray(b,&bb);
1984:     VecRestoreArrayRead(l->lvec,&xx);
1985:   }
1986:   VecRestoreArray(lmask,&mask);
1987:   VecDestroy(&lmask);
1988:   PetscFree(lrows);

1990:   /* only change matrix nonzero state if pattern was allowed to be changed */
1991:   if (!((Mat_SeqBAIJ*)(l->A->data))->keepnonzeropattern) {
1992:     PetscObjectState state = l->A->nonzerostate + l->B->nonzerostate;
1993:     MPIU_Allreduce(&state,&A->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)A));
1994:   }
1995:   return(0);
1996: }

2000: PetscErrorCode MatSetUnfactored_MPIBAIJ(Mat A)
2001: {
2002:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

2006:   MatSetUnfactored(a->A);
2007:   return(0);
2008: }

2010: static PetscErrorCode MatDuplicate_MPIBAIJ(Mat,MatDuplicateOption,Mat*);

2014: PetscErrorCode MatEqual_MPIBAIJ(Mat A,Mat B,PetscBool  *flag)
2015: {
2016:   Mat_MPIBAIJ    *matB = (Mat_MPIBAIJ*)B->data,*matA = (Mat_MPIBAIJ*)A->data;
2017:   Mat            a,b,c,d;
2018:   PetscBool      flg;

2022:   a = matA->A; b = matA->B;
2023:   c = matB->A; d = matB->B;

2025:   MatEqual(a,c,&flg);
2026:   if (flg) {
2027:     MatEqual(b,d,&flg);
2028:   }
2029:   MPIU_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2030:   return(0);
2031: }

2035: PetscErrorCode MatCopy_MPIBAIJ(Mat A,Mat B,MatStructure str)
2036: {
2038:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;
2039:   Mat_MPIBAIJ    *b = (Mat_MPIBAIJ*)B->data;

2042:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
2043:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
2044:     MatCopy_Basic(A,B,str);
2045:   } else {
2046:     MatCopy(a->A,b->A,str);
2047:     MatCopy(a->B,b->B,str);
2048:   }
2049:   return(0);
2050: }

2054: PetscErrorCode MatSetUp_MPIBAIJ(Mat A)
2055: {

2059:   MatMPIBAIJSetPreallocation(A,A->rmap->bs,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
2060:   return(0);
2061: }

2065: PetscErrorCode MatAXPYGetPreallocation_MPIBAIJ(Mat Y,const PetscInt *yltog,Mat X,const PetscInt *xltog,PetscInt *nnz)
2066: {
2068:   PetscInt       bs = Y->rmap->bs,m = Y->rmap->N/bs;
2069:   Mat_SeqBAIJ    *x = (Mat_SeqBAIJ*)X->data;
2070:   Mat_SeqBAIJ    *y = (Mat_SeqBAIJ*)Y->data;

2073:   MatAXPYGetPreallocation_MPIX_private(m,x->i,x->j,xltog,y->i,y->j,yltog,nnz);
2074:   return(0);
2075: }

2079: PetscErrorCode MatAXPY_MPIBAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
2080: {
2082:   Mat_MPIBAIJ    *xx=(Mat_MPIBAIJ*)X->data,*yy=(Mat_MPIBAIJ*)Y->data;
2083:   PetscBLASInt   bnz,one=1;
2084:   Mat_SeqBAIJ    *x,*y;

2087:   if (str == SAME_NONZERO_PATTERN) {
2088:     PetscScalar alpha = a;
2089:     x    = (Mat_SeqBAIJ*)xx->A->data;
2090:     y    = (Mat_SeqBAIJ*)yy->A->data;
2091:     PetscBLASIntCast(x->nz,&bnz);
2092:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2093:     x    = (Mat_SeqBAIJ*)xx->B->data;
2094:     y    = (Mat_SeqBAIJ*)yy->B->data;
2095:     PetscBLASIntCast(x->nz,&bnz);
2096:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,x->a,&one,y->a,&one));
2097:     PetscObjectStateIncrease((PetscObject)Y);
2098:   } else if (str == SUBSET_NONZERO_PATTERN) { /* nonzeros of X is a subset of Y's */
2099:     MatAXPY_Basic(Y,a,X,str);
2100:   } else {
2101:     Mat      B;
2102:     PetscInt *nnz_d,*nnz_o,bs=Y->rmap->bs;
2103:     PetscMalloc1(yy->A->rmap->N,&nnz_d);
2104:     PetscMalloc1(yy->B->rmap->N,&nnz_o);
2105:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
2106:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
2107:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
2108:     MatSetBlockSizesFromMats(B,Y,Y);
2109:     MatSetType(B,MATMPIBAIJ);
2110:     MatAXPYGetPreallocation_SeqBAIJ(yy->A,xx->A,nnz_d);
2111:     MatAXPYGetPreallocation_MPIBAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);
2112:     MatMPIBAIJSetPreallocation(B,bs,0,nnz_d,0,nnz_o);
2113:     /* MatAXPY_BasicWithPreallocation() for BAIJ matrix is much slower than AIJ, even for bs=1 ! */
2114:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
2115:     MatHeaderReplace(Y,&B);
2116:     PetscFree(nnz_d);
2117:     PetscFree(nnz_o);
2118:   }
2119:   return(0);
2120: }

2124: PetscErrorCode MatRealPart_MPIBAIJ(Mat A)
2125: {
2126:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

2130:   MatRealPart(a->A);
2131:   MatRealPart(a->B);
2132:   return(0);
2133: }

2137: PetscErrorCode MatImaginaryPart_MPIBAIJ(Mat A)
2138: {
2139:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

2143:   MatImaginaryPart(a->A);
2144:   MatImaginaryPart(a->B);
2145:   return(0);
2146: }

2150: PetscErrorCode MatGetSubMatrix_MPIBAIJ(Mat mat,IS isrow,IS iscol,MatReuse call,Mat *newmat)
2151: {
2153:   IS             iscol_local;
2154:   PetscInt       csize;

2157:   ISGetLocalSize(iscol,&csize);
2158:   if (call == MAT_REUSE_MATRIX) {
2159:     PetscObjectQuery((PetscObject)*newmat,"ISAllGather",(PetscObject*)&iscol_local);
2160:     if (!iscol_local) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
2161:   } else {
2162:     ISAllGather(iscol,&iscol_local);
2163:   }
2164:   MatGetSubMatrix_MPIBAIJ_Private(mat,isrow,iscol_local,csize,call,newmat);
2165:   if (call == MAT_INITIAL_MATRIX) {
2166:     PetscObjectCompose((PetscObject)*newmat,"ISAllGather",(PetscObject)iscol_local);
2167:     ISDestroy(&iscol_local);
2168:   }
2169:   return(0);
2170: }
2171: extern PetscErrorCode MatGetSubMatrices_MPIBAIJ_local(Mat,PetscInt,const IS[],const IS[],MatReuse,PetscBool*,PetscBool*,Mat*);
2174: /*
2175:   Not great since it makes two copies of the submatrix, first an SeqBAIJ
2176:   in local and then by concatenating the local matrices the end result.
2177:   Writing it directly would be much like MatGetSubMatrices_MPIBAIJ().
2178:   This routine is used for BAIJ and SBAIJ matrices (unfortunate dependency).
2179: */
2180: PetscErrorCode MatGetSubMatrix_MPIBAIJ_Private(Mat mat,IS isrow,IS iscol,PetscInt csize,MatReuse call,Mat *newmat)
2181: {
2183:   PetscMPIInt    rank,size;
2184:   PetscInt       i,m,n,rstart,row,rend,nz,*cwork,j,bs;
2185:   PetscInt       *ii,*jj,nlocal,*dlens,*olens,dlen,olen,jend,mglobal,ncol,nrow;
2186:   Mat            M,Mreuse;
2187:   MatScalar      *vwork,*aa;
2188:   MPI_Comm       comm;
2189:   IS             isrow_new, iscol_new;
2190:   PetscBool      idflag,allrows, allcols;
2191:   Mat_SeqBAIJ    *aij;

2194:   PetscObjectGetComm((PetscObject)mat,&comm);
2195:   MPI_Comm_rank(comm,&rank);
2196:   MPI_Comm_size(comm,&size);
2197:   /* The compression and expansion should be avoided. Doesn't point
2198:      out errors, might change the indices, hence buggey */
2199:   ISCompressIndicesGeneral(mat->rmap->N,mat->rmap->n,mat->rmap->bs,1,&isrow,&isrow_new);
2200:   ISCompressIndicesGeneral(mat->cmap->N,mat->cmap->n,mat->cmap->bs,1,&iscol,&iscol_new);

2202:   /* Check for special case: each processor gets entire matrix columns */
2203:   ISIdentity(iscol,&idflag);
2204:   ISGetLocalSize(iscol,&ncol);
2205:   if (idflag && ncol == mat->cmap->N) allcols = PETSC_TRUE;
2206:   else allcols = PETSC_FALSE;

2208:   ISIdentity(isrow,&idflag);
2209:   ISGetLocalSize(isrow,&nrow);
2210:   if (idflag && nrow == mat->rmap->N) allrows = PETSC_TRUE;
2211:   else allrows = PETSC_FALSE;

2213:   if (call ==  MAT_REUSE_MATRIX) {
2214:     PetscObjectQuery((PetscObject)*newmat,"SubMatrix",(PetscObject*)&Mreuse);
2215:     if (!Mreuse) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Submatrix passed in was not used before, cannot reuse");
2216:     MatGetSubMatrices_MPIBAIJ_local(mat,1,&isrow_new,&iscol_new,MAT_REUSE_MATRIX,&allrows,&allcols,&Mreuse);
2217:   } else {
2218:     MatGetSubMatrices_MPIBAIJ_local(mat,1,&isrow_new,&iscol_new,MAT_INITIAL_MATRIX,&allrows,&allcols,&Mreuse);
2219:   }
2220:   ISDestroy(&isrow_new);
2221:   ISDestroy(&iscol_new);
2222:   /*
2223:       m - number of local rows
2224:       n - number of columns (same on all processors)
2225:       rstart - first row in new global matrix generated
2226:   */
2227:   MatGetBlockSize(mat,&bs);
2228:   MatGetSize(Mreuse,&m,&n);
2229:   m    = m/bs;
2230:   n    = n/bs;

2232:   if (call == MAT_INITIAL_MATRIX) {
2233:     aij = (Mat_SeqBAIJ*)(Mreuse)->data;
2234:     ii  = aij->i;
2235:     jj  = aij->j;

2237:     /*
2238:         Determine the number of non-zeros in the diagonal and off-diagonal
2239:         portions of the matrix in order to do correct preallocation
2240:     */

2242:     /* first get start and end of "diagonal" columns */
2243:     if (csize == PETSC_DECIDE) {
2244:       ISGetSize(isrow,&mglobal);
2245:       if (mglobal == n*bs) { /* square matrix */
2246:         nlocal = m;
2247:       } else {
2248:         nlocal = n/size + ((n % size) > rank);
2249:       }
2250:     } else {
2251:       nlocal = csize/bs;
2252:     }
2253:     MPI_Scan(&nlocal,&rend,1,MPIU_INT,MPI_SUM,comm);
2254:     rstart = rend - nlocal;
2255:     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);

2257:     /* next, compute all the lengths */
2258:     PetscMalloc2(m+1,&dlens,m+1,&olens);
2259:     for (i=0; i<m; i++) {
2260:       jend = ii[i+1] - ii[i];
2261:       olen = 0;
2262:       dlen = 0;
2263:       for (j=0; j<jend; j++) {
2264:         if (*jj < rstart || *jj >= rend) olen++;
2265:         else dlen++;
2266:         jj++;
2267:       }
2268:       olens[i] = olen;
2269:       dlens[i] = dlen;
2270:     }
2271:     MatCreate(comm,&M);
2272:     MatSetSizes(M,bs*m,bs*nlocal,PETSC_DECIDE,bs*n);
2273:     MatSetType(M,((PetscObject)mat)->type_name);
2274:     MatMPIBAIJSetPreallocation(M,bs,0,dlens,0,olens);
2275:     MatMPISBAIJSetPreallocation(M,bs,0,dlens,0,olens);
2276:     PetscFree2(dlens,olens);
2277:   } else {
2278:     PetscInt ml,nl;

2280:     M    = *newmat;
2281:     MatGetLocalSize(M,&ml,&nl);
2282:     if (ml != m) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Previous matrix must be same size/layout as request");
2283:     MatZeroEntries(M);
2284:     /*
2285:          The next two lines are needed so we may call MatSetValues_MPIAIJ() below directly,
2286:        rather than the slower MatSetValues().
2287:     */
2288:     M->was_assembled = PETSC_TRUE;
2289:     M->assembled     = PETSC_FALSE;
2290:   }
2291:   MatSetOption(M,MAT_ROW_ORIENTED,PETSC_FALSE);
2292:   MatGetOwnershipRange(M,&rstart,&rend);
2293:   aij  = (Mat_SeqBAIJ*)(Mreuse)->data;
2294:   ii   = aij->i;
2295:   jj   = aij->j;
2296:   aa   = aij->a;
2297:   for (i=0; i<m; i++) {
2298:     row   = rstart/bs + i;
2299:     nz    = ii[i+1] - ii[i];
2300:     cwork = jj;     jj += nz;
2301:     vwork = aa;     aa += nz*bs*bs;
2302:     MatSetValuesBlocked_MPIBAIJ(M,1,&row,nz,cwork,vwork,INSERT_VALUES);
2303:   }

2305:   MatAssemblyBegin(M,MAT_FINAL_ASSEMBLY);
2306:   MatAssemblyEnd(M,MAT_FINAL_ASSEMBLY);
2307:   *newmat = M;

2309:   /* save submatrix used in processor for next request */
2310:   if (call ==  MAT_INITIAL_MATRIX) {
2311:     PetscObjectCompose((PetscObject)M,"SubMatrix",(PetscObject)Mreuse);
2312:     PetscObjectDereference((PetscObject)Mreuse);
2313:   }
2314:   return(0);
2315: }

2319: PetscErrorCode MatPermute_MPIBAIJ(Mat A,IS rowp,IS colp,Mat *B)
2320: {
2321:   MPI_Comm       comm,pcomm;
2322:   PetscInt       clocal_size,nrows;
2323:   const PetscInt *rows;
2324:   PetscMPIInt    size;
2325:   IS             crowp,lcolp;

2329:   PetscObjectGetComm((PetscObject)A,&comm);
2330:   /* make a collective version of 'rowp' */
2331:   PetscObjectGetComm((PetscObject)rowp,&pcomm);
2332:   if (pcomm==comm) {
2333:     crowp = rowp;
2334:   } else {
2335:     ISGetSize(rowp,&nrows);
2336:     ISGetIndices(rowp,&rows);
2337:     ISCreateGeneral(comm,nrows,rows,PETSC_COPY_VALUES,&crowp);
2338:     ISRestoreIndices(rowp,&rows);
2339:   }
2340:   ISSetPermutation(crowp);
2341:   /* make a local version of 'colp' */
2342:   PetscObjectGetComm((PetscObject)colp,&pcomm);
2343:   MPI_Comm_size(pcomm,&size);
2344:   if (size==1) {
2345:     lcolp = colp;
2346:   } else {
2347:     ISAllGather(colp,&lcolp);
2348:   }
2349:   ISSetPermutation(lcolp);
2350:   /* now we just get the submatrix */
2351:   MatGetLocalSize(A,NULL,&clocal_size);
2352:   MatGetSubMatrix_MPIBAIJ_Private(A,crowp,lcolp,clocal_size,MAT_INITIAL_MATRIX,B);
2353:   /* clean up */
2354:   if (pcomm!=comm) {
2355:     ISDestroy(&crowp);
2356:   }
2357:   if (size>1) {
2358:     ISDestroy(&lcolp);
2359:   }
2360:   return(0);
2361: }

2365: PetscErrorCode  MatGetGhosts_MPIBAIJ(Mat mat,PetscInt *nghosts,const PetscInt *ghosts[])
2366: {
2367:   Mat_MPIBAIJ *baij = (Mat_MPIBAIJ*) mat->data;
2368:   Mat_SeqBAIJ *B    = (Mat_SeqBAIJ*)baij->B->data;

2371:   if (nghosts) *nghosts = B->nbs;
2372:   if (ghosts) *ghosts = baij->garray;
2373:   return(0);
2374: }

2378: PetscErrorCode MatGetSeqNonzeroStructure_MPIBAIJ(Mat A,Mat *newmat)
2379: {
2380:   Mat            B;
2381:   Mat_MPIBAIJ    *a  = (Mat_MPIBAIJ*)A->data;
2382:   Mat_SeqBAIJ    *ad = (Mat_SeqBAIJ*)a->A->data,*bd = (Mat_SeqBAIJ*)a->B->data;
2383:   Mat_SeqAIJ     *b;
2385:   PetscMPIInt    size,rank,*recvcounts = 0,*displs = 0;
2386:   PetscInt       sendcount,i,*rstarts = A->rmap->range,n,cnt,j,bs = A->rmap->bs;
2387:   PetscInt       m,*garray = a->garray,*lens,*jsendbuf,*a_jsendbuf,*b_jsendbuf;

2390:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
2391:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);

2393:   /* ----------------------------------------------------------------
2394:      Tell every processor the number of nonzeros per row
2395:   */
2396:   PetscMalloc1(A->rmap->N/bs,&lens);
2397:   for (i=A->rmap->rstart/bs; i<A->rmap->rend/bs; i++) {
2398:     lens[i] = ad->i[i-A->rmap->rstart/bs+1] - ad->i[i-A->rmap->rstart/bs] + bd->i[i-A->rmap->rstart/bs+1] - bd->i[i-A->rmap->rstart/bs];
2399:   }
2400:   sendcount = A->rmap->rend/bs - A->rmap->rstart/bs;
2401:   PetscMalloc1(2*size,&recvcounts);
2402:   displs    = recvcounts + size;
2403:   for (i=0; i<size; i++) {
2404:     recvcounts[i] = A->rmap->range[i+1]/bs - A->rmap->range[i]/bs;
2405:     displs[i]     = A->rmap->range[i]/bs;
2406:   }
2407: #if defined(PETSC_HAVE_MPI_IN_PLACE)
2408:   MPI_Allgatherv(MPI_IN_PLACE,0,MPI_DATATYPE_NULL,lens,recvcounts,displs,MPIU_INT,PetscObjectComm((PetscObject)A));
2409: #else
2410:   MPI_Allgatherv(lens+A->rmap->rstart/bs,sendcount,MPIU_INT,lens,recvcounts,displs,MPIU_INT,PetscObjectComm((PetscObject)A));
2411: #endif
2412:   /* ---------------------------------------------------------------
2413:      Create the sequential matrix of the same type as the local block diagonal
2414:   */
2415:   MatCreate(PETSC_COMM_SELF,&B);
2416:   MatSetSizes(B,A->rmap->N/bs,A->cmap->N/bs,PETSC_DETERMINE,PETSC_DETERMINE);
2417:   MatSetType(B,MATSEQAIJ);
2418:   MatSeqAIJSetPreallocation(B,0,lens);
2419:   b    = (Mat_SeqAIJ*)B->data;

2421:   /*--------------------------------------------------------------------
2422:     Copy my part of matrix column indices over
2423:   */
2424:   sendcount  = ad->nz + bd->nz;
2425:   jsendbuf   = b->j + b->i[rstarts[rank]/bs];
2426:   a_jsendbuf = ad->j;
2427:   b_jsendbuf = bd->j;
2428:   n          = A->rmap->rend/bs - A->rmap->rstart/bs;
2429:   cnt        = 0;
2430:   for (i=0; i<n; i++) {

2432:     /* put in lower diagonal portion */
2433:     m = bd->i[i+1] - bd->i[i];
2434:     while (m > 0) {
2435:       /* is it above diagonal (in bd (compressed) numbering) */
2436:       if (garray[*b_jsendbuf] > A->rmap->rstart/bs + i) break;
2437:       jsendbuf[cnt++] = garray[*b_jsendbuf++];
2438:       m--;
2439:     }

2441:     /* put in diagonal portion */
2442:     for (j=ad->i[i]; j<ad->i[i+1]; j++) {
2443:       jsendbuf[cnt++] = A->rmap->rstart/bs + *a_jsendbuf++;
2444:     }

2446:     /* put in upper diagonal portion */
2447:     while (m-- > 0) {
2448:       jsendbuf[cnt++] = garray[*b_jsendbuf++];
2449:     }
2450:   }
2451:   if (cnt != sendcount) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Corrupted PETSc matrix: nz given %D actual nz %D",sendcount,cnt);

2453:   /*--------------------------------------------------------------------
2454:     Gather all column indices to all processors
2455:   */
2456:   for (i=0; i<size; i++) {
2457:     recvcounts[i] = 0;
2458:     for (j=A->rmap->range[i]/bs; j<A->rmap->range[i+1]/bs; j++) {
2459:       recvcounts[i] += lens[j];
2460:     }
2461:   }
2462:   displs[0] = 0;
2463:   for (i=1; i<size; i++) {
2464:     displs[i] = displs[i-1] + recvcounts[i-1];
2465:   }
2466: #if defined(PETSC_HAVE_MPI_IN_PLACE)
2467:   MPI_Allgatherv(MPI_IN_PLACE,0,MPI_DATATYPE_NULL,b->j,recvcounts,displs,MPIU_INT,PetscObjectComm((PetscObject)A));
2468: #else
2469:   MPI_Allgatherv(jsendbuf,sendcount,MPIU_INT,b->j,recvcounts,displs,MPIU_INT,PetscObjectComm((PetscObject)A));
2470: #endif
2471:   /*--------------------------------------------------------------------
2472:     Assemble the matrix into useable form (note numerical values not yet set)
2473:   */
2474:   /* set the b->ilen (length of each row) values */
2475:   PetscMemcpy(b->ilen,lens,(A->rmap->N/bs)*sizeof(PetscInt));
2476:   /* set the b->i indices */
2477:   b->i[0] = 0;
2478:   for (i=1; i<=A->rmap->N/bs; i++) {
2479:     b->i[i] = b->i[i-1] + lens[i-1];
2480:   }
2481:   PetscFree(lens);
2482:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2483:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2484:   PetscFree(recvcounts);

2486:   if (A->symmetric) {
2487:     MatSetOption(B,MAT_SYMMETRIC,PETSC_TRUE);
2488:   } else if (A->hermitian) {
2489:     MatSetOption(B,MAT_HERMITIAN,PETSC_TRUE);
2490:   } else if (A->structurally_symmetric) {
2491:     MatSetOption(B,MAT_STRUCTURALLY_SYMMETRIC,PETSC_TRUE);
2492:   }
2493:   *newmat = B;
2494:   return(0);
2495: }

2499: PetscErrorCode MatSOR_MPIBAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
2500: {
2501:   Mat_MPIBAIJ    *mat = (Mat_MPIBAIJ*)matin->data;
2503:   Vec            bb1 = 0;

2506:   if (flag == SOR_APPLY_UPPER) {
2507:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2508:     return(0);
2509:   }

2511:   if (its > 1 || ~flag & SOR_ZERO_INITIAL_GUESS) {
2512:     VecDuplicate(bb,&bb1);
2513:   }

2515:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
2516:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2517:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2518:       its--;
2519:     }

2521:     while (its--) {
2522:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
2523:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

2525:       /* update rhs: bb1 = bb - B*x */
2526:       VecScale(mat->lvec,-1.0);
2527:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

2529:       /* local sweep */
2530:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,1,xx);
2531:     }
2532:   } else if (flag & SOR_LOCAL_FORWARD_SWEEP) {
2533:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2534:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2535:       its--;
2536:     }
2537:     while (its--) {
2538:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
2539:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

2541:       /* update rhs: bb1 = bb - B*x */
2542:       VecScale(mat->lvec,-1.0);
2543:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

2545:       /* local sweep */
2546:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_FORWARD_SWEEP,fshift,lits,1,xx);
2547:     }
2548:   } else if (flag & SOR_LOCAL_BACKWARD_SWEEP) {
2549:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2550:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2551:       its--;
2552:     }
2553:     while (its--) {
2554:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
2555:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

2557:       /* update rhs: bb1 = bb - B*x */
2558:       VecScale(mat->lvec,-1.0);
2559:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb,bb1);

2561:       /* local sweep */
2562:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_BACKWARD_SWEEP,fshift,lits,1,xx);
2563:     }
2564:   } else SETERRQ(PetscObjectComm((PetscObject)matin),PETSC_ERR_SUP,"Parallel version of SOR requested not supported");

2566:   VecDestroy(&bb1);
2567:   return(0);
2568: }

2572: PetscErrorCode MatGetColumnNorms_MPIBAIJ(Mat A,NormType type,PetscReal *norms)
2573: {
2575:   Mat_MPIBAIJ    *aij = (Mat_MPIBAIJ*)A->data;
2576:   PetscInt       N,i,*garray = aij->garray;
2577:   PetscInt       ib,jb,bs = A->rmap->bs;
2578:   Mat_SeqBAIJ    *a_aij = (Mat_SeqBAIJ*) aij->A->data;
2579:   MatScalar      *a_val = a_aij->a;
2580:   Mat_SeqBAIJ    *b_aij = (Mat_SeqBAIJ*) aij->B->data;
2581:   MatScalar      *b_val = b_aij->a;
2582:   PetscReal      *work;

2585:   MatGetSize(A,NULL,&N);
2586:   PetscCalloc1(N,&work);
2587:   if (type == NORM_2) {
2588:     for (i=a_aij->i[0]; i<a_aij->i[aij->A->rmap->n/bs]; i++) {
2589:       for (jb=0; jb<bs; jb++) {
2590:         for (ib=0; ib<bs; ib++) {
2591:           work[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscAbsScalar(*a_val * *a_val);
2592:           a_val++;
2593:         }
2594:       }
2595:     }
2596:     for (i=b_aij->i[0]; i<b_aij->i[aij->B->rmap->n/bs]; i++) {
2597:       for (jb=0; jb<bs; jb++) {
2598:         for (ib=0; ib<bs; ib++) {
2599:           work[garray[b_aij->j[i]] * bs + jb] += PetscAbsScalar(*b_val * *b_val);
2600:           b_val++;
2601:         }
2602:       }
2603:     }
2604:   } else if (type == NORM_1) {
2605:     for (i=a_aij->i[0]; i<a_aij->i[aij->A->rmap->n/bs]; i++) {
2606:       for (jb=0; jb<bs; jb++) {
2607:         for (ib=0; ib<bs; ib++) {
2608:           work[A->cmap->rstart + a_aij->j[i] * bs + jb] += PetscAbsScalar(*a_val);
2609:           a_val++;
2610:         }
2611:       }
2612:     }
2613:     for (i=b_aij->i[0]; i<b_aij->i[aij->B->rmap->n/bs]; i++) {
2614:       for (jb=0; jb<bs; jb++) {
2615:        for (ib=0; ib<bs; ib++) {
2616:           work[garray[b_aij->j[i]] * bs + jb] += PetscAbsScalar(*b_val);
2617:           b_val++;
2618:         }
2619:       }
2620:     }
2621:   } else if (type == NORM_INFINITY) {
2622:     for (i=a_aij->i[0]; i<a_aij->i[aij->A->rmap->n/bs]; i++) {
2623:       for (jb=0; jb<bs; jb++) {
2624:         for (ib=0; ib<bs; ib++) {
2625:           int col = A->cmap->rstart + a_aij->j[i] * bs + jb;
2626:           work[col] = PetscMax(PetscAbsScalar(*a_val), work[col]);
2627:           a_val++;
2628:         }
2629:       }
2630:     }
2631:     for (i=b_aij->i[0]; i<b_aij->i[aij->B->rmap->n/bs]; i++) {
2632:       for (jb=0; jb<bs; jb++) {
2633:         for (ib=0; ib<bs; ib++) {
2634:           int col = garray[b_aij->j[i]] * bs + jb;
2635:           work[col] = PetscMax(PetscAbsScalar(*b_val), work[col]);
2636:           b_val++;
2637:         }
2638:       }
2639:     }
2640:   } else SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"Unknown NormType");
2641:   if (type == NORM_INFINITY) {
2642:     MPIU_Allreduce(work,norms,N,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)A));
2643:   } else {
2644:     MPIU_Allreduce(work,norms,N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)A));
2645:   }
2646:   PetscFree(work);
2647:   if (type == NORM_2) {
2648:     for (i=0; i<N; i++) norms[i] = PetscSqrtReal(norms[i]);
2649:   }
2650:   return(0);
2651: }

2655: PetscErrorCode MatInvertBlockDiagonal_MPIBAIJ(Mat A,const PetscScalar **values)
2656: {
2657:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*) A->data;

2661:   MatInvertBlockDiagonal(a->A,values);
2662:   A->errortype = a->A->errortype;
2663:   return(0);
2664: }

2668: PetscErrorCode MatShift_MPIBAIJ(Mat Y,PetscScalar a)
2669: {
2671:   Mat_MPIBAIJ    *maij = (Mat_MPIBAIJ*)Y->data;
2672:   Mat_SeqBAIJ    *aij = (Mat_SeqBAIJ*)maij->A->data;

2675:   if (!Y->preallocated) {
2676:     MatMPIBAIJSetPreallocation(Y,Y->rmap->bs,1,NULL,0,NULL);
2677:   } else if (!aij->nz) {
2678:     PetscInt nonew = aij->nonew;
2679:     MatSeqBAIJSetPreallocation(maij->A,Y->rmap->bs,1,NULL);
2680:     aij->nonew = nonew;
2681:   }
2682:   MatShift_Basic(Y,a);
2683:   return(0);
2684: }

2688: PetscErrorCode MatMissingDiagonal_MPIBAIJ(Mat A,PetscBool  *missing,PetscInt *d)
2689: {
2690:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;

2694:   if (A->rmap->n != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only works for square matrices");
2695:   MatMissingDiagonal(a->A,missing,d);
2696:   if (d) {
2697:     PetscInt rstart;
2698:     MatGetOwnershipRange(A,&rstart,NULL);
2699:     *d += rstart/A->rmap->bs;

2701:   }
2702:   return(0);
2703: }

2705: /* -------------------------------------------------------------------*/
2706: static struct _MatOps MatOps_Values = {MatSetValues_MPIBAIJ,
2707:                                        MatGetRow_MPIBAIJ,
2708:                                        MatRestoreRow_MPIBAIJ,
2709:                                        MatMult_MPIBAIJ,
2710:                                 /* 4*/ MatMultAdd_MPIBAIJ,
2711:                                        MatMultTranspose_MPIBAIJ,
2712:                                        MatMultTransposeAdd_MPIBAIJ,
2713:                                        0,
2714:                                        0,
2715:                                        0,
2716:                                 /*10*/ 0,
2717:                                        0,
2718:                                        0,
2719:                                        MatSOR_MPIBAIJ,
2720:                                        MatTranspose_MPIBAIJ,
2721:                                 /*15*/ MatGetInfo_MPIBAIJ,
2722:                                        MatEqual_MPIBAIJ,
2723:                                        MatGetDiagonal_MPIBAIJ,
2724:                                        MatDiagonalScale_MPIBAIJ,
2725:                                        MatNorm_MPIBAIJ,
2726:                                 /*20*/ MatAssemblyBegin_MPIBAIJ,
2727:                                        MatAssemblyEnd_MPIBAIJ,
2728:                                        MatSetOption_MPIBAIJ,
2729:                                        MatZeroEntries_MPIBAIJ,
2730:                                 /*24*/ MatZeroRows_MPIBAIJ,
2731:                                        0,
2732:                                        0,
2733:                                        0,
2734:                                        0,
2735:                                 /*29*/ MatSetUp_MPIBAIJ,
2736:                                        0,
2737:                                        0,
2738:                                        0,
2739:                                        0,
2740:                                 /*34*/ MatDuplicate_MPIBAIJ,
2741:                                        0,
2742:                                        0,
2743:                                        0,
2744:                                        0,
2745:                                 /*39*/ MatAXPY_MPIBAIJ,
2746:                                        MatGetSubMatrices_MPIBAIJ,
2747:                                        MatIncreaseOverlap_MPIBAIJ,
2748:                                        MatGetValues_MPIBAIJ,
2749:                                        MatCopy_MPIBAIJ,
2750:                                 /*44*/ 0,
2751:                                        MatScale_MPIBAIJ,
2752:                                        MatShift_MPIBAIJ,
2753:                                        0,
2754:                                        MatZeroRowsColumns_MPIBAIJ,
2755:                                 /*49*/ 0,
2756:                                        0,
2757:                                        0,
2758:                                        0,
2759:                                        0,
2760:                                 /*54*/ MatFDColoringCreate_MPIXAIJ,
2761:                                        0,
2762:                                        MatSetUnfactored_MPIBAIJ,
2763:                                        MatPermute_MPIBAIJ,
2764:                                        MatSetValuesBlocked_MPIBAIJ,
2765:                                 /*59*/ MatGetSubMatrix_MPIBAIJ,
2766:                                        MatDestroy_MPIBAIJ,
2767:                                        MatView_MPIBAIJ,
2768:                                        0,
2769:                                        0,
2770:                                 /*64*/ 0,
2771:                                        0,
2772:                                        0,
2773:                                        0,
2774:                                        0,
2775:                                 /*69*/ MatGetRowMaxAbs_MPIBAIJ,
2776:                                        0,
2777:                                        0,
2778:                                        0,
2779:                                        0,
2780:                                 /*74*/ 0,
2781:                                        MatFDColoringApply_BAIJ,
2782:                                        0,
2783:                                        0,
2784:                                        0,
2785:                                 /*79*/ 0,
2786:                                        0,
2787:                                        0,
2788:                                        0,
2789:                                        MatLoad_MPIBAIJ,
2790:                                 /*84*/ 0,
2791:                                        0,
2792:                                        0,
2793:                                        0,
2794:                                        0,
2795:                                 /*89*/ 0,
2796:                                        0,
2797:                                        0,
2798:                                        0,
2799:                                        0,
2800:                                 /*94*/ 0,
2801:                                        0,
2802:                                        0,
2803:                                        0,
2804:                                        0,
2805:                                 /*99*/ 0,
2806:                                        0,
2807:                                        0,
2808:                                        0,
2809:                                        0,
2810:                                 /*104*/0,
2811:                                        MatRealPart_MPIBAIJ,
2812:                                        MatImaginaryPart_MPIBAIJ,
2813:                                        0,
2814:                                        0,
2815:                                 /*109*/0,
2816:                                        0,
2817:                                        0,
2818:                                        0,
2819:                                        MatMissingDiagonal_MPIBAIJ,
2820:                                 /*114*/MatGetSeqNonzeroStructure_MPIBAIJ,
2821:                                        0,
2822:                                        MatGetGhosts_MPIBAIJ,
2823:                                        0,
2824:                                        0,
2825:                                 /*119*/0,
2826:                                        0,
2827:                                        0,
2828:                                        0,
2829:                                        MatGetMultiProcBlock_MPIBAIJ,
2830:                                 /*124*/0,
2831:                                        MatGetColumnNorms_MPIBAIJ,
2832:                                        MatInvertBlockDiagonal_MPIBAIJ,
2833:                                        0,
2834:                                        0,
2835:                                /*129*/ 0,
2836:                                        0,
2837:                                        0,
2838:                                        0,
2839:                                        0,
2840:                                /*134*/ 0,
2841:                                        0,
2842:                                        0,
2843:                                        0,
2844:                                        0,
2845:                                /*139*/ 0,
2846:                                        0,
2847:                                        0,
2848:                                        MatFDColoringSetUp_MPIXAIJ,
2849:                                        0,
2850:                                 /*144*/MatCreateMPIMatConcatenateSeqMat_MPIBAIJ
2851: };

2855: PetscErrorCode  MatGetDiagonalBlock_MPIBAIJ(Mat A,Mat *a)
2856: {
2858:   *a = ((Mat_MPIBAIJ*)A->data)->A;
2859:   return(0);
2860: }

2862: PETSC_EXTERN PetscErrorCode MatConvert_MPIBAIJ_MPISBAIJ(Mat, MatType,MatReuse,Mat*);

2866: PetscErrorCode MatMPIBAIJSetPreallocationCSR_MPIBAIJ(Mat B,PetscInt bs,const PetscInt ii[],const PetscInt jj[],const PetscScalar V[])
2867: {
2868:   PetscInt       m,rstart,cstart,cend;
2869:   PetscInt       i,j,d,nz,nz_max=0,*d_nnz=0,*o_nnz=0;
2870:   const PetscInt *JJ    =0;
2871:   PetscScalar    *values=0;
2872:   PetscBool      roworiented = ((Mat_MPIBAIJ*)B->data)->roworiented;

2876:   PetscLayoutSetBlockSize(B->rmap,bs);
2877:   PetscLayoutSetBlockSize(B->cmap,bs);
2878:   PetscLayoutSetUp(B->rmap);
2879:   PetscLayoutSetUp(B->cmap);
2880:   PetscLayoutGetBlockSize(B->rmap,&bs);
2881:   m      = B->rmap->n/bs;
2882:   rstart = B->rmap->rstart/bs;
2883:   cstart = B->cmap->rstart/bs;
2884:   cend   = B->cmap->rend/bs;

2886:   if (ii[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"ii[0] must be 0 but it is %D",ii[0]);
2887:   PetscMalloc2(m,&d_nnz,m,&o_nnz);
2888:   for (i=0; i<m; i++) {
2889:     nz = ii[i+1] - ii[i];
2890:     if (nz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative number of columns %D",i,nz);
2891:     nz_max = PetscMax(nz_max,nz);
2892:     JJ     = jj + ii[i];
2893:     for (j=0; j<nz; j++) {
2894:       if (*JJ >= cstart) break;
2895:       JJ++;
2896:     }
2897:     d = 0;
2898:     for (; j<nz; j++) {
2899:       if (*JJ++ >= cend) break;
2900:       d++;
2901:     }
2902:     d_nnz[i] = d;
2903:     o_nnz[i] = nz - d;
2904:   }
2905:   MatMPIBAIJSetPreallocation(B,bs,0,d_nnz,0,o_nnz);
2906:   PetscFree2(d_nnz,o_nnz);

2908:   values = (PetscScalar*)V;
2909:   if (!values) {
2910:     PetscMalloc1(bs*bs*nz_max,&values);
2911:     PetscMemzero(values,bs*bs*nz_max*sizeof(PetscScalar));
2912:   }
2913:   for (i=0; i<m; i++) {
2914:     PetscInt          row    = i + rstart;
2915:     PetscInt          ncols  = ii[i+1] - ii[i];
2916:     const PetscInt    *icols = jj + ii[i];
2917:     if (!roworiented) {         /* block ordering matches the non-nested layout of MatSetValues so we can insert entire rows */
2918:       const PetscScalar *svals = values + (V ? (bs*bs*ii[i]) : 0);
2919:       MatSetValuesBlocked_MPIBAIJ(B,1,&row,ncols,icols,svals,INSERT_VALUES);
2920:     } else {                    /* block ordering does not match so we can only insert one block at a time. */
2921:       PetscInt j;
2922:       for (j=0; j<ncols; j++) {
2923:         const PetscScalar *svals = values + (V ? (bs*bs*(ii[i]+j)) : 0);
2924:         MatSetValuesBlocked_MPIBAIJ(B,1,&row,1,&icols[j],svals,INSERT_VALUES);
2925:       }
2926:     }
2927:   }

2929:   if (!V) { PetscFree(values); }
2930:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2931:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2932:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
2933:   return(0);
2934: }

2938: /*@C
2939:    MatMPIBAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in BAIJ format
2940:    (the default parallel PETSc format).

2942:    Collective on MPI_Comm

2944:    Input Parameters:
2945: +  B - the matrix
2946: .  bs - the block size
2947: .  i - the indices into j for the start of each local row (starts with zero)
2948: .  j - the column indices for each local row (starts with zero) these must be sorted for each row
2949: -  v - optional values in the matrix

2951:    Level: developer

2953:    Notes: The order of the entries in values is specified by the MatOption MAT_ROW_ORIENTED.  For example, C programs
2954:    may want to use the default MAT_ROW_ORIENTED=PETSC_TRUE and use an array v[nnz][bs][bs] where the second index is
2955:    over rows within a block and the last index is over columns within a block row.  Fortran programs will likely set
2956:    MAT_ROW_ORIENTED=PETSC_FALSE and use a Fortran array v(bs,bs,nnz) in which the first index is over rows within a
2957:    block column and the second index is over columns within a block.

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

2961: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIBAIJSetPreallocation(), MatCreateAIJ(), MPIAIJ, MatCreateMPIBAIJWithArrays(), MPIBAIJ
2962: @*/
2963: PetscErrorCode  MatMPIBAIJSetPreallocationCSR(Mat B,PetscInt bs,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
2964: {

2971:   PetscTryMethod(B,"MatMPIBAIJSetPreallocationCSR_C",(Mat,PetscInt,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,bs,i,j,v));
2972:   return(0);
2973: }

2977: PetscErrorCode  MatMPIBAIJSetPreallocation_MPIBAIJ(Mat B,PetscInt bs,PetscInt d_nz,const PetscInt *d_nnz,PetscInt o_nz,const PetscInt *o_nnz)
2978: {
2979:   Mat_MPIBAIJ    *b;
2981:   PetscInt       i;

2984:   MatSetBlockSize(B,PetscAbs(bs));
2985:   PetscLayoutSetUp(B->rmap);
2986:   PetscLayoutSetUp(B->cmap);
2987:   PetscLayoutGetBlockSize(B->rmap,&bs);

2989:   if (d_nnz) {
2990:     for (i=0; i<B->rmap->n/bs; i++) {
2991:       if (d_nnz[i] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"d_nnz cannot be less than -1: local row %D value %D",i,d_nnz[i]);
2992:     }
2993:   }
2994:   if (o_nnz) {
2995:     for (i=0; i<B->rmap->n/bs; i++) {
2996:       if (o_nnz[i] < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"o_nnz cannot be less than -1: local row %D value %D",i,o_nnz[i]);
2997:     }
2998:   }

3000:   b      = (Mat_MPIBAIJ*)B->data;
3001:   b->bs2 = bs*bs;
3002:   b->mbs = B->rmap->n/bs;
3003:   b->nbs = B->cmap->n/bs;
3004:   b->Mbs = B->rmap->N/bs;
3005:   b->Nbs = B->cmap->N/bs;

3007:   for (i=0; i<=b->size; i++) {
3008:     b->rangebs[i] = B->rmap->range[i]/bs;
3009:   }
3010:   b->rstartbs = B->rmap->rstart/bs;
3011:   b->rendbs   = B->rmap->rend/bs;
3012:   b->cstartbs = B->cmap->rstart/bs;
3013:   b->cendbs   = B->cmap->rend/bs;

3015:   if (!B->preallocated) {
3016:     MatCreate(PETSC_COMM_SELF,&b->A);
3017:     MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
3018:     MatSetType(b->A,MATSEQBAIJ);
3019:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->A);
3020:     MatCreate(PETSC_COMM_SELF,&b->B);
3021:     MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);
3022:     MatSetType(b->B,MATSEQBAIJ);
3023:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->B);
3024:     MatStashCreate_Private(PetscObjectComm((PetscObject)B),bs,&B->bstash);
3025:   }

3027:   MatSeqBAIJSetPreallocation(b->A,bs,d_nz,d_nnz);
3028:   MatSeqBAIJSetPreallocation(b->B,bs,o_nz,o_nnz);
3029:   B->preallocated = PETSC_TRUE;
3030:   return(0);
3031: }

3033: extern PetscErrorCode  MatDiagonalScaleLocal_MPIBAIJ(Mat,Vec);
3034: extern PetscErrorCode  MatSetHashTableFactor_MPIBAIJ(Mat,PetscReal);

3038: PETSC_EXTERN PetscErrorCode MatConvert_MPIBAIJ_MPIAdj(Mat B, MatType newtype,MatReuse reuse,Mat *adj)
3039: {
3040:   Mat_MPIBAIJ    *b = (Mat_MPIBAIJ*)B->data;
3042:   Mat_SeqBAIJ    *d  = (Mat_SeqBAIJ*) b->A->data,*o = (Mat_SeqBAIJ*) b->B->data;
3043:   PetscInt       M   = B->rmap->n/B->rmap->bs,i,*ii,*jj,cnt,j,k,rstart = B->rmap->rstart/B->rmap->bs;
3044:   const PetscInt *id = d->i, *jd = d->j, *io = o->i, *jo = o->j, *garray = b->garray;

3047:   PetscMalloc1(M+1,&ii);
3048:   ii[0] = 0;
3049:   for (i=0; i<M; i++) {
3050:     if ((id[i+1] - id[i]) < 0) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Indices wrong %D %D %D",i,id[i],id[i+1]);
3051:     if ((io[i+1] - io[i]) < 0) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Indices wrong %D %D %D",i,io[i],io[i+1]);
3052:     ii[i+1] = ii[i] + id[i+1] - id[i] + io[i+1] - io[i];
3053:     /* remove one from count of matrix has diagonal */
3054:     for (j=id[i]; j<id[i+1]; j++) {
3055:       if (jd[j] == i) {ii[i+1]--;break;}
3056:     }
3057:   }
3058:   PetscMalloc1(ii[M],&jj);
3059:   cnt  = 0;
3060:   for (i=0; i<M; i++) {
3061:     for (j=io[i]; j<io[i+1]; j++) {
3062:       if (garray[jo[j]] > rstart) break;
3063:       jj[cnt++] = garray[jo[j]];
3064:     }
3065:     for (k=id[i]; k<id[i+1]; k++) {
3066:       if (jd[k] != i) {
3067:         jj[cnt++] = rstart + jd[k];
3068:       }
3069:     }
3070:     for (; j<io[i+1]; j++) {
3071:       jj[cnt++] = garray[jo[j]];
3072:     }
3073:   }
3074:   MatCreateMPIAdj(PetscObjectComm((PetscObject)B),M,B->cmap->N/B->rmap->bs,ii,jj,NULL,adj);
3075:   return(0);
3076: }

3078: #include <../src/mat/impls/aij/mpi/mpiaij.h>

3080: PETSC_EXTERN PetscErrorCode MatConvert_SeqBAIJ_SeqAIJ(Mat,MatType,MatReuse,Mat*);

3084: PETSC_EXTERN PetscErrorCode MatConvert_MPIBAIJ_MPIAIJ(Mat A,MatType newtype,MatReuse reuse,Mat *newmat)
3085: {
3087:   Mat_MPIBAIJ    *a = (Mat_MPIBAIJ*)A->data;
3088:   Mat            B;
3089:   Mat_MPIAIJ     *b;

3092:   if (!A->assembled) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Matrix must be assembled");

3094:   MatCreate(PetscObjectComm((PetscObject)A),&B);
3095:   MatSetType(B,MATMPIAIJ);
3096:   MatSetSizes(B,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N);
3097:   MatSetBlockSizes(B,A->rmap->bs,A->cmap->bs);
3098:   MatSeqAIJSetPreallocation(B,0,NULL);
3099:   MatMPIAIJSetPreallocation(B,0,NULL,0,NULL);
3100:   b    = (Mat_MPIAIJ*) B->data;

3102:   MatDestroy(&b->A);
3103:   MatDestroy(&b->B);
3104:   MatDisAssemble_MPIBAIJ(A);
3105:   MatConvert_SeqBAIJ_SeqAIJ(a->A, MATSEQAIJ, MAT_INITIAL_MATRIX, &b->A);
3106:   MatConvert_SeqBAIJ_SeqAIJ(a->B, MATSEQAIJ, MAT_INITIAL_MATRIX, &b->B);
3107:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
3108:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
3109:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
3110:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
3111:   if (reuse == MAT_INPLACE_MATRIX) {
3112:     MatHeaderReplace(A,&B);
3113:   } else {
3114:    *newmat = B;
3115:   }
3116:   return(0);
3117: }

3119: /*MC
3120:    MATMPIBAIJ - MATMPIBAIJ = "mpibaij" - A matrix type to be used for distributed block sparse matrices.

3122:    Options Database Keys:
3123: + -mat_type mpibaij - sets the matrix type to "mpibaij" during a call to MatSetFromOptions()
3124: . -mat_block_size <bs> - set the blocksize used to store the matrix
3125: - -mat_use_hash_table <fact>

3127:   Level: beginner

3129: .seealso: MatCreateMPIBAIJ
3130: M*/

3132: PETSC_EXTERN PetscErrorCode MatConvert_MPIBAIJ_MPIBSTRM(Mat,MatType,MatReuse,Mat*);

3136: PETSC_EXTERN PetscErrorCode MatCreate_MPIBAIJ(Mat B)
3137: {
3138:   Mat_MPIBAIJ    *b;
3140:   PetscBool      flg = PETSC_FALSE;

3143:   PetscNewLog(B,&b);
3144:   B->data = (void*)b;

3146:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));
3147:   B->assembled = PETSC_FALSE;

3149:   B->insertmode = NOT_SET_VALUES;
3150:   MPI_Comm_rank(PetscObjectComm((PetscObject)B),&b->rank);
3151:   MPI_Comm_size(PetscObjectComm((PetscObject)B),&b->size);

3153:   /* build local table of row and column ownerships */
3154:   PetscMalloc1(b->size+1,&b->rangebs);

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

3159:   b->donotstash  = PETSC_FALSE;
3160:   b->colmap      = NULL;
3161:   b->garray      = NULL;
3162:   b->roworiented = PETSC_TRUE;

3164:   /* stuff used in block assembly */
3165:   b->barray = 0;

3167:   /* stuff used for matrix vector multiply */
3168:   b->lvec  = 0;
3169:   b->Mvctx = 0;

3171:   /* stuff for MatGetRow() */
3172:   b->rowindices   = 0;
3173:   b->rowvalues    = 0;
3174:   b->getrowactive = PETSC_FALSE;

3176:   /* hash table stuff */
3177:   b->ht           = 0;
3178:   b->hd           = 0;
3179:   b->ht_size      = 0;
3180:   b->ht_flag      = PETSC_FALSE;
3181:   b->ht_fact      = 0;
3182:   b->ht_total_ct  = 0;
3183:   b->ht_insert_ct = 0;

3185:   /* stuff for MatGetSubMatrices_MPIBAIJ_local() */
3186:   b->ijonly = PETSC_FALSE;


3189:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpibaij_mpiadj_C",MatConvert_MPIBAIJ_MPIAdj);
3190:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpibaij_mpiaij_C",MatConvert_MPIBAIJ_MPIAIJ);
3191:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpibaij_mpisbaij_C",MatConvert_MPIBAIJ_MPISBAIJ);
3192:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPIBAIJ);
3193:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPIBAIJ);
3194:   PetscObjectComposeFunction((PetscObject)B,"MatGetDiagonalBlock_C",MatGetDiagonalBlock_MPIBAIJ);
3195:   PetscObjectComposeFunction((PetscObject)B,"MatMPIBAIJSetPreallocation_C",MatMPIBAIJSetPreallocation_MPIBAIJ);
3196:   PetscObjectComposeFunction((PetscObject)B,"MatMPIBAIJSetPreallocationCSR_C",MatMPIBAIJSetPreallocationCSR_MPIBAIJ);
3197:   PetscObjectComposeFunction((PetscObject)B,"MatDiagonalScaleLocal_C",MatDiagonalScaleLocal_MPIBAIJ);
3198:   PetscObjectComposeFunction((PetscObject)B,"MatSetHashTableFactor_C",MatSetHashTableFactor_MPIBAIJ);
3199:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpibaij_mpibstrm_C",MatConvert_MPIBAIJ_MPIBSTRM);
3200:   PetscObjectChangeTypeName((PetscObject)B,MATMPIBAIJ);

3202:   PetscOptionsBegin(PetscObjectComm((PetscObject)B),NULL,"Options for loading MPIBAIJ matrix 1","Mat");
3203:   PetscOptionsBool("-mat_use_hash_table","Use hash table to save memory in constructing matrix","MatSetOption",flg,&flg,NULL);
3204:   if (flg) {
3205:     PetscReal fact = 1.39;
3206:     MatSetOption(B,MAT_USE_HASH_TABLE,PETSC_TRUE);
3207:     PetscOptionsReal("-mat_use_hash_table","Use hash table factor","MatMPIBAIJSetHashTableFactor",fact,&fact,NULL);
3208:     if (fact <= 1.0) fact = 1.39;
3209:     MatMPIBAIJSetHashTableFactor(B,fact);
3210:     PetscInfo1(B,"Hash table Factor used %5.2f\n",fact);
3211:   }
3212:   PetscOptionsEnd();
3213:   return(0);
3214: }

3216: /*MC
3217:    MATBAIJ - MATBAIJ = "baij" - A matrix type to be used for block sparse matrices.

3219:    This matrix type is identical to MATSEQBAIJ when constructed with a single process communicator,
3220:    and MATMPIBAIJ otherwise.

3222:    Options Database Keys:
3223: . -mat_type baij - sets the matrix type to "baij" during a call to MatSetFromOptions()

3225:   Level: beginner

3227: .seealso: MatCreateBAIJ(),MATSEQBAIJ,MATMPIBAIJ, MatMPIBAIJSetPreallocation(), MatMPIBAIJSetPreallocationCSR()
3228: M*/

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

3239:    Collective on Mat

3241:    Input Parameters:
3242: +  B - the matrix
3243: .  bs   - size of block, the blocks are ALWAYS square. One can use MatSetBlockSizes() to set a different row and column blocksize but the row
3244:           blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with MatCreateVecs()
3245: .  d_nz  - number of block nonzeros per block row in diagonal portion of local
3246:            submatrix  (same for all local rows)
3247: .  d_nnz - array containing the number of block nonzeros in the various block rows
3248:            of the in diagonal portion of the local (possibly different for each block
3249:            row) or NULL.  If you plan to factor the matrix you must leave room for the diagonal entry and
3250:            set it even if it is zero.
3251: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
3252:            submatrix (same for all local rows).
3253: -  o_nnz - array containing the number of nonzeros in the various block rows of the
3254:            off-diagonal portion of the local submatrix (possibly different for
3255:            each block row) or NULL.

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

3259:    Options Database Keys:
3260: +   -mat_block_size - size of the blocks to use
3261: -   -mat_use_hash_table <fact>

3263:    Notes:
3264:    If PETSC_DECIDE or  PETSC_DETERMINE is used for a particular argument on one processor
3265:    than it must be used on all processors that share the object for that argument.

3267:    Storage Information:
3268:    For a square global matrix we define each processor's diagonal portion
3269:    to be its local rows and the corresponding columns (a square submatrix);
3270:    each processor's off-diagonal portion encompasses the remainder of the
3271:    local matrix (a rectangular submatrix).

3273:    The user can specify preallocated storage for the diagonal part of
3274:    the local submatrix with either d_nz or d_nnz (not both).  Set
3275:    d_nz=PETSC_DEFAULT and d_nnz=NULL for PETSc to control dynamic
3276:    memory allocation.  Likewise, specify preallocated storage for the
3277:    off-diagonal part of the local submatrix with o_nz or o_nnz (not both).

3279:    Consider a processor that owns rows 3, 4 and 5 of a parallel matrix. In
3280:    the figure below we depict these three local rows and all columns (0-11).

3282: .vb
3283:            0 1 2 3 4 5 6 7 8 9 10 11
3284:           --------------------------
3285:    row 3  |o o o d d d o o o o  o  o
3286:    row 4  |o o o d d d o o o o  o  o
3287:    row 5  |o o o d d d o o o o  o  o
3288:           --------------------------
3289: .ve

3291:    Thus, any entries in the d locations are stored in the d (diagonal)
3292:    submatrix, and any entries in the o locations are stored in the
3293:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
3294:    stored simply in the MATSEQBAIJ format for compressed row storage.

3296:    Now d_nz should indicate the number of block nonzeros per row in the d matrix,
3297:    and o_nz should indicate the number of block nonzeros per row in the o matrix.
3298:    In general, for PDE problems in which most nonzeros are near the diagonal,
3299:    one expects d_nz >> o_nz.   For large problems you MUST preallocate memory
3300:    or you will get TERRIBLE performance; see the users' manual chapter on
3301:    matrices.

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

3308:    Level: intermediate

3310: .keywords: matrix, block, aij, compressed row, sparse, parallel

3312: .seealso: MatCreate(), MatCreateSeqBAIJ(), MatSetValues(), MatCreateBAIJ(), MatMPIBAIJSetPreallocationCSR(), PetscSplitOwnership()
3313: @*/
3314: PetscErrorCode  MatMPIBAIJSetPreallocation(Mat B,PetscInt bs,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
3315: {

3322:   PetscTryMethod(B,"MatMPIBAIJSetPreallocation_C",(Mat,PetscInt,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,bs,d_nz,d_nnz,o_nz,o_nnz));
3323:   return(0);
3324: }

3328: /*@C
3329:    MatCreateBAIJ - Creates a sparse parallel matrix in block AIJ format
3330:    (block compressed row).  For good matrix assembly performance
3331:    the user should preallocate the matrix storage by setting the parameters
3332:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
3333:    performance can be increased by more than a factor of 50.

3335:    Collective on MPI_Comm

3337:    Input Parameters:
3338: +  comm - MPI communicator
3339: .  bs   - size of block, the blocks are ALWAYS square. One can use MatSetBlockSizes() to set a different row and column blocksize but the row
3340:           blocksize always defines the size of the blocks. The column blocksize sets the blocksize of the vectors obtained with MatCreateVecs()
3341: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
3342:            This value should be the same as the local size used in creating the
3343:            y vector for the matrix-vector product y = Ax.
3344: .  n - number of local columns (or PETSC_DECIDE to have calculated if N is given)
3345:            This value should be the same as the local size used in creating the
3346:            x vector for the matrix-vector product y = Ax.
3347: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
3348: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
3349: .  d_nz  - number of nonzero blocks per block row in diagonal portion of local
3350:            submatrix  (same for all local rows)
3351: .  d_nnz - array containing the number of nonzero blocks in the various block rows
3352:            of the in diagonal portion of the local (possibly different for each block
3353:            row) or NULL.  If you plan to factor the matrix you must leave room for the diagonal entry
3354:            and set it even if it is zero.
3355: .  o_nz  - number of nonzero blocks per block row in the off-diagonal portion of local
3356:            submatrix (same for all local rows).
3357: -  o_nnz - array containing the number of nonzero blocks in the various block rows of the
3358:            off-diagonal portion of the local submatrix (possibly different for
3359:            each block row) or NULL.

3361:    Output Parameter:
3362: .  A - the matrix

3364:    Options Database Keys:
3365: +   -mat_block_size - size of the blocks to use
3366: -   -mat_use_hash_table <fact>

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

3372:    Notes:
3373:    If the *_nnz parameter is given then the *_nz parameter is ignored

3375:    A nonzero block is any block that as 1 or more nonzeros in it

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

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

3383:    Storage Information:
3384:    For a square global matrix we define each processor's diagonal portion
3385:    to be its local rows and the corresponding columns (a square submatrix);
3386:    each processor's off-diagonal portion encompasses the remainder of the
3387:    local matrix (a rectangular submatrix).

3389:    The user can specify preallocated storage for the diagonal part of
3390:    the local submatrix with either d_nz or d_nnz (not both).  Set
3391:    d_nz=PETSC_DEFAULT and d_nnz=NULL for PETSc to control dynamic
3392:    memory allocation.  Likewise, specify preallocated storage for the
3393:    off-diagonal part of the local submatrix with o_nz or o_nnz (not both).

3395:    Consider a processor that owns rows 3, 4 and 5 of a parallel matrix. In
3396:    the figure below we depict these three local rows and all columns (0-11).

3398: .vb
3399:            0 1 2 3 4 5 6 7 8 9 10 11
3400:           --------------------------
3401:    row 3  |o o o d d d o o o o  o  o
3402:    row 4  |o o o d d d o o o o  o  o
3403:    row 5  |o o o d d d o o o o  o  o
3404:           --------------------------
3405: .ve

3407:    Thus, any entries in the d locations are stored in the d (diagonal)
3408:    submatrix, and any entries in the o locations are stored in the
3409:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
3410:    stored simply in the MATSEQBAIJ format for compressed row storage.

3412:    Now d_nz should indicate the number of block nonzeros per row in the d matrix,
3413:    and o_nz should indicate the number of block nonzeros per row in the o matrix.
3414:    In general, for PDE problems in which most nonzeros are near the diagonal,
3415:    one expects d_nz >> o_nz.   For large problems you MUST preallocate memory
3416:    or you will get TERRIBLE performance; see the users' manual chapter on
3417:    matrices.

3419:    Level: intermediate

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

3423: .seealso: MatCreate(), MatCreateSeqBAIJ(), MatSetValues(), MatCreateBAIJ(), MatMPIBAIJSetPreallocation(), MatMPIBAIJSetPreallocationCSR()
3424: @*/
3425: PetscErrorCode  MatCreateBAIJ(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[],Mat *A)
3426: {
3428:   PetscMPIInt    size;

3431:   MatCreate(comm,A);
3432:   MatSetSizes(*A,m,n,M,N);
3433:   MPI_Comm_size(comm,&size);
3434:   if (size > 1) {
3435:     MatSetType(*A,MATMPIBAIJ);
3436:     MatMPIBAIJSetPreallocation(*A,bs,d_nz,d_nnz,o_nz,o_nnz);
3437:   } else {
3438:     MatSetType(*A,MATSEQBAIJ);
3439:     MatSeqBAIJSetPreallocation(*A,bs,d_nz,d_nnz);
3440:   }
3441:   return(0);
3442: }

3446: static PetscErrorCode MatDuplicate_MPIBAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
3447: {
3448:   Mat            mat;
3449:   Mat_MPIBAIJ    *a,*oldmat = (Mat_MPIBAIJ*)matin->data;
3451:   PetscInt       len=0;

3454:   *newmat = 0;
3455:   MatCreate(PetscObjectComm((PetscObject)matin),&mat);
3456:   MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
3457:   MatSetType(mat,((PetscObject)matin)->type_name);
3458:   PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));

3460:   mat->factortype   = matin->factortype;
3461:   mat->preallocated = PETSC_TRUE;
3462:   mat->assembled    = PETSC_TRUE;
3463:   mat->insertmode   = NOT_SET_VALUES;

3465:   a             = (Mat_MPIBAIJ*)mat->data;
3466:   mat->rmap->bs = matin->rmap->bs;
3467:   a->bs2        = oldmat->bs2;
3468:   a->mbs        = oldmat->mbs;
3469:   a->nbs        = oldmat->nbs;
3470:   a->Mbs        = oldmat->Mbs;
3471:   a->Nbs        = oldmat->Nbs;

3473:   PetscLayoutReference(matin->rmap,&mat->rmap);
3474:   PetscLayoutReference(matin->cmap,&mat->cmap);

3476:   a->size         = oldmat->size;
3477:   a->rank         = oldmat->rank;
3478:   a->donotstash   = oldmat->donotstash;
3479:   a->roworiented  = oldmat->roworiented;
3480:   a->rowindices   = 0;
3481:   a->rowvalues    = 0;
3482:   a->getrowactive = PETSC_FALSE;
3483:   a->barray       = 0;
3484:   a->rstartbs     = oldmat->rstartbs;
3485:   a->rendbs       = oldmat->rendbs;
3486:   a->cstartbs     = oldmat->cstartbs;
3487:   a->cendbs       = oldmat->cendbs;

3489:   /* hash table stuff */
3490:   a->ht           = 0;
3491:   a->hd           = 0;
3492:   a->ht_size      = 0;
3493:   a->ht_flag      = oldmat->ht_flag;
3494:   a->ht_fact      = oldmat->ht_fact;
3495:   a->ht_total_ct  = 0;
3496:   a->ht_insert_ct = 0;

3498:   PetscMemcpy(a->rangebs,oldmat->rangebs,(a->size+1)*sizeof(PetscInt));
3499:   if (oldmat->colmap) {
3500: #if defined(PETSC_USE_CTABLE)
3501:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
3502: #else
3503:     PetscMalloc1(a->Nbs,&a->colmap);
3504:     PetscLogObjectMemory((PetscObject)mat,(a->Nbs)*sizeof(PetscInt));
3505:     PetscMemcpy(a->colmap,oldmat->colmap,(a->Nbs)*sizeof(PetscInt));
3506: #endif
3507:   } else a->colmap = 0;

3509:   if (oldmat->garray && (len = ((Mat_SeqBAIJ*)(oldmat->B->data))->nbs)) {
3510:     PetscMalloc1(len,&a->garray);
3511:     PetscLogObjectMemory((PetscObject)mat,len*sizeof(PetscInt));
3512:     PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt));
3513:   } else a->garray = 0;

3515:   MatStashCreate_Private(PetscObjectComm((PetscObject)matin),matin->rmap->bs,&mat->bstash);
3516:   VecDuplicate(oldmat->lvec,&a->lvec);
3517:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
3518:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
3519:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);

3521:   MatDuplicate(oldmat->A,cpvalues,&a->A);
3522:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->A);
3523:   MatDuplicate(oldmat->B,cpvalues,&a->B);
3524:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->B);
3525:   PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
3526:   *newmat = mat;
3527:   return(0);
3528: }

3532: PetscErrorCode MatLoad_MPIBAIJ(Mat newmat,PetscViewer viewer)
3533: {
3535:   int            fd;
3536:   PetscInt       i,nz,j,rstart,rend;
3537:   PetscScalar    *vals,*buf;
3538:   MPI_Comm       comm;
3539:   MPI_Status     status;
3540:   PetscMPIInt    rank,size,maxnz;
3541:   PetscInt       header[4],*rowlengths = 0,M,N,m,*rowners,*cols;
3542:   PetscInt       *locrowlens = NULL,*procsnz = NULL,*browners = NULL;
3543:   PetscInt       jj,*mycols,*ibuf,bs = newmat->rmap->bs,Mbs,mbs,extra_rows,mmax;
3544:   PetscMPIInt    tag    = ((PetscObject)viewer)->tag;
3545:   PetscInt       *dlens = NULL,*odlens = NULL,*mask = NULL,*masked1 = NULL,*masked2 = NULL,rowcount,odcount;
3546:   PetscInt       dcount,kmax,k,nzcount,tmp,mend;

3549:   /* force binary viewer to load .info file if it has not yet done so */
3550:   PetscViewerSetUp(viewer);
3551:   PetscObjectGetComm((PetscObject)viewer,&comm);
3552:   PetscOptionsBegin(comm,NULL,"Options for loading MPIBAIJ matrix 2","Mat");
3553:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
3554:   PetscOptionsEnd();
3555:   if (bs < 0) bs = 1;

3557:   MPI_Comm_size(comm,&size);
3558:   MPI_Comm_rank(comm,&rank);
3559:   PetscViewerBinaryGetDescriptor(viewer,&fd);
3560:   if (!rank) {
3561:     PetscBinaryRead(fd,(char*)header,4,PETSC_INT);
3562:     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
3563:   }
3564:   MPI_Bcast(header+1,3,MPIU_INT,0,comm);
3565:   M    = header[1]; N = header[2];

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

3571:   if (M != N) SETERRQ(PetscObjectComm((PetscObject)viewer),PETSC_ERR_SUP,"Can only do square matrices");

3573:   /*
3574:      This code adds extra rows to make sure the number of rows is
3575:      divisible by the blocksize
3576:   */
3577:   Mbs        = M/bs;
3578:   extra_rows = bs - M + bs*Mbs;
3579:   if (extra_rows == bs) extra_rows = 0;
3580:   else                  Mbs++;
3581:   if (extra_rows && !rank) {
3582:     PetscInfo(viewer,"Padding loaded matrix to match blocksize\n");
3583:   }

3585:   /* determine ownership of all rows */
3586:   if (newmat->rmap->n < 0) { /* PETSC_DECIDE */
3587:     mbs = Mbs/size + ((Mbs % size) > rank);
3588:     m   = mbs*bs;
3589:   } else { /* User set */
3590:     m   = newmat->rmap->n;
3591:     mbs = m/bs;
3592:   }
3593:   PetscMalloc2(size+1,&rowners,size+1,&browners);
3594:   MPI_Allgather(&mbs,1,MPIU_INT,rowners+1,1,MPIU_INT,comm);

3596:   /* process 0 needs enough room for process with most rows */
3597:   if (!rank) {
3598:     mmax = rowners[1];
3599:     for (i=2; i<=size; i++) {
3600:       mmax = PetscMax(mmax,rowners[i]);
3601:     }
3602:     mmax*=bs;
3603:   } else mmax = -1;             /* unused, but compiler warns anyway */

3605:   rowners[0] = 0;
3606:   for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
3607:   for (i=0; i<=size; i++) browners[i] = rowners[i]*bs;
3608:   rstart = rowners[rank];
3609:   rend   = rowners[rank+1];

3611:   /* distribute row lengths to all processors */
3612:   PetscMalloc1(m,&locrowlens);
3613:   if (!rank) {
3614:     mend = m;
3615:     if (size == 1) mend = mend - extra_rows;
3616:     PetscBinaryRead(fd,locrowlens,mend,PETSC_INT);
3617:     for (j=mend; j<m; j++) locrowlens[j] = 1;
3618:     PetscMalloc1(mmax,&rowlengths);
3619:     PetscCalloc1(size,&procsnz);
3620:     for (j=0; j<m; j++) {
3621:       procsnz[0] += locrowlens[j];
3622:     }
3623:     for (i=1; i<size; i++) {
3624:       mend = browners[i+1] - browners[i];
3625:       if (i == size-1) mend = mend - extra_rows;
3626:       PetscBinaryRead(fd,rowlengths,mend,PETSC_INT);
3627:       for (j=mend; j<browners[i+1] - browners[i]; j++) rowlengths[j] = 1;
3628:       /* calculate the number of nonzeros on each processor */
3629:       for (j=0; j<browners[i+1]-browners[i]; j++) {
3630:         procsnz[i] += rowlengths[j];
3631:       }
3632:       MPI_Send(rowlengths,browners[i+1]-browners[i],MPIU_INT,i,tag,comm);
3633:     }
3634:     PetscFree(rowlengths);
3635:   } else {
3636:     MPI_Recv(locrowlens,m,MPIU_INT,0,tag,comm,&status);
3637:   }

3639:   if (!rank) {
3640:     /* determine max buffer needed and allocate it */
3641:     maxnz = procsnz[0];
3642:     for (i=1; i<size; i++) {
3643:       maxnz = PetscMax(maxnz,procsnz[i]);
3644:     }
3645:     PetscMalloc1(maxnz,&cols);

3647:     /* read in my part of the matrix column indices  */
3648:     nz     = procsnz[0];
3649:     PetscMalloc1(nz+1,&ibuf);
3650:     mycols = ibuf;
3651:     if (size == 1) nz -= extra_rows;
3652:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);
3653:     if (size == 1) {
3654:       for (i=0; i< extra_rows; i++) mycols[nz+i] = M+i;
3655:     }

3657:     /* read in every ones (except the last) and ship off */
3658:     for (i=1; i<size-1; i++) {
3659:       nz   = procsnz[i];
3660:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
3661:       MPI_Send(cols,nz,MPIU_INT,i,tag,comm);
3662:     }
3663:     /* read in the stuff for the last proc */
3664:     if (size != 1) {
3665:       nz   = procsnz[size-1] - extra_rows;  /* the extra rows are not on the disk */
3666:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
3667:       for (i=0; i<extra_rows; i++) cols[nz+i] = M+i;
3668:       MPI_Send(cols,nz+extra_rows,MPIU_INT,size-1,tag,comm);
3669:     }
3670:     PetscFree(cols);
3671:   } else {
3672:     /* determine buffer space needed for message */
3673:     nz = 0;
3674:     for (i=0; i<m; i++) {
3675:       nz += locrowlens[i];
3676:     }
3677:     PetscMalloc1(nz+1,&ibuf);
3678:     mycols = ibuf;
3679:     /* receive message of column indices*/
3680:     MPI_Recv(mycols,nz,MPIU_INT,0,tag,comm,&status);
3681:     MPI_Get_count(&status,MPIU_INT,&maxnz);
3682:     if (maxnz != nz) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");
3683:   }

3685:   /* loop over local rows, determining number of off diagonal entries */
3686:   PetscMalloc2(rend-rstart,&dlens,rend-rstart,&odlens);
3687:   PetscCalloc3(Mbs,&mask,Mbs,&masked1,Mbs,&masked2);
3688:   rowcount = 0; nzcount = 0;
3689:   for (i=0; i<mbs; i++) {
3690:     dcount  = 0;
3691:     odcount = 0;
3692:     for (j=0; j<bs; j++) {
3693:       kmax = locrowlens[rowcount];
3694:       for (k=0; k<kmax; k++) {
3695:         tmp = mycols[nzcount++]/bs;
3696:         if (!mask[tmp]) {
3697:           mask[tmp] = 1;
3698:           if (tmp < rstart || tmp >= rend) masked2[odcount++] = tmp;
3699:           else masked1[dcount++] = tmp;
3700:         }
3701:       }
3702:       rowcount++;
3703:     }

3705:     dlens[i]  = dcount;
3706:     odlens[i] = odcount;

3708:     /* zero out the mask elements we set */
3709:     for (j=0; j<dcount; j++) mask[masked1[j]] = 0;
3710:     for (j=0; j<odcount; j++) mask[masked2[j]] = 0;
3711:   }

3713:   MatSetSizes(newmat,m,m,M+extra_rows,N+extra_rows);
3714:   MatMPIBAIJSetPreallocation(newmat,bs,0,dlens,0,odlens);

3716:   if (!rank) {
3717:     PetscMalloc1(maxnz+1,&buf);
3718:     /* read in my part of the matrix numerical values  */
3719:     nz     = procsnz[0];
3720:     vals   = buf;
3721:     mycols = ibuf;
3722:     if (size == 1) nz -= extra_rows;
3723:     PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
3724:     if (size == 1) {
3725:       for (i=0; i< extra_rows; i++) vals[nz+i] = 1.0;
3726:     }

3728:     /* insert into matrix */
3729:     jj = rstart*bs;
3730:     for (i=0; i<m; i++) {
3731:       MatSetValues_MPIBAIJ(newmat,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
3732:       mycols += locrowlens[i];
3733:       vals   += locrowlens[i];
3734:       jj++;
3735:     }
3736:     /* read in other processors (except the last one) and ship out */
3737:     for (i=1; i<size-1; i++) {
3738:       nz   = procsnz[i];
3739:       vals = buf;
3740:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
3741:       MPIULong_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newmat)->tag,comm);
3742:     }
3743:     /* the last proc */
3744:     if (size != 1) {
3745:       nz   = procsnz[i] - extra_rows;
3746:       vals = buf;
3747:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
3748:       for (i=0; i<extra_rows; i++) vals[nz+i] = 1.0;
3749:       MPIULong_Send(vals,nz+extra_rows,MPIU_SCALAR,size-1,((PetscObject)newmat)->tag,comm);
3750:     }
3751:     PetscFree(procsnz);
3752:   } else {
3753:     /* receive numeric values */
3754:     PetscMalloc1(nz+1,&buf);

3756:     /* receive message of values*/
3757:     vals   = buf;
3758:     mycols = ibuf;
3759:     MPIULong_Recv(vals,nz,MPIU_SCALAR,0,((PetscObject)newmat)->tag,comm);

3761:     /* insert into matrix */
3762:     jj = rstart*bs;
3763:     for (i=0; i<m; i++) {
3764:       MatSetValues_MPIBAIJ(newmat,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
3765:       mycols += locrowlens[i];
3766:       vals   += locrowlens[i];
3767:       jj++;
3768:     }
3769:   }
3770:   PetscFree(locrowlens);
3771:   PetscFree(buf);
3772:   PetscFree(ibuf);
3773:   PetscFree2(rowners,browners);
3774:   PetscFree2(dlens,odlens);
3775:   PetscFree3(mask,masked1,masked2);
3776:   MatAssemblyBegin(newmat,MAT_FINAL_ASSEMBLY);
3777:   MatAssemblyEnd(newmat,MAT_FINAL_ASSEMBLY);
3778:   return(0);
3779: }

3783: /*@
3784:    MatMPIBAIJSetHashTableFactor - Sets the factor required to compute the size of the HashTable.

3786:    Input Parameters:
3787: .  mat  - the matrix
3788: .  fact - factor

3790:    Not Collective, each process can use a different factor

3792:    Level: advanced

3794:   Notes:
3795:    This can also be set by the command line option: -mat_use_hash_table <fact>

3797: .keywords: matrix, hashtable, factor, HT

3799: .seealso: MatSetOption()
3800: @*/
3801: PetscErrorCode  MatMPIBAIJSetHashTableFactor(Mat mat,PetscReal fact)
3802: {

3806:   PetscTryMethod(mat,"MatSetHashTableFactor_C",(Mat,PetscReal),(mat,fact));
3807:   return(0);
3808: }

3812: PetscErrorCode  MatSetHashTableFactor_MPIBAIJ(Mat mat,PetscReal fact)
3813: {
3814:   Mat_MPIBAIJ *baij;

3817:   baij          = (Mat_MPIBAIJ*)mat->data;
3818:   baij->ht_fact = fact;
3819:   return(0);
3820: }

3824: PetscErrorCode  MatMPIBAIJGetSeqBAIJ(Mat A,Mat *Ad,Mat *Ao,const PetscInt *colmap[])
3825: {
3826:   Mat_MPIBAIJ *a = (Mat_MPIBAIJ*)A->data;

3829:   if (Ad)     *Ad     = a->A;
3830:   if (Ao)     *Ao     = a->B;
3831:   if (colmap) *colmap = a->garray;
3832:   return(0);
3833: }

3835: /*
3836:     Special version for direct calls from Fortran (to eliminate two function call overheads
3837: */
3838: #if defined(PETSC_HAVE_FORTRAN_CAPS)
3839: #define matmpibaijsetvaluesblocked_ MATMPIBAIJSETVALUESBLOCKED
3840: #elif !defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
3841: #define matmpibaijsetvaluesblocked_ matmpibaijsetvaluesblocked
3842: #endif

3846: /*@C
3847:   MatMPIBAIJSetValuesBlocked - Direct Fortran call to replace call to MatSetValuesBlocked()

3849:   Collective on Mat

3851:   Input Parameters:
3852: + mat - the matrix
3853: . min - number of input rows
3854: . im - input rows
3855: . nin - number of input columns
3856: . in - input columns
3857: . v - numerical values input
3858: - addvin - INSERT_VALUES or ADD_VALUES

3860:   Notes: This has a complete copy of MatSetValuesBlocked_MPIBAIJ() which is terrible code un-reuse.

3862:   Level: advanced

3864: .seealso:   MatSetValuesBlocked()
3865: @*/
3866: PetscErrorCode matmpibaijsetvaluesblocked_(Mat *matin,PetscInt *min,const PetscInt im[],PetscInt *nin,const PetscInt in[],const MatScalar v[],InsertMode *addvin)
3867: {
3868:   /* convert input arguments to C version */
3869:   Mat        mat  = *matin;
3870:   PetscInt   m    = *min, n = *nin;
3871:   InsertMode addv = *addvin;

3873:   Mat_MPIBAIJ     *baij = (Mat_MPIBAIJ*)mat->data;
3874:   const MatScalar *value;
3875:   MatScalar       *barray     = baij->barray;
3876:   PetscBool       roworiented = baij->roworiented;
3877:   PetscErrorCode  ierr;
3878:   PetscInt        i,j,ii,jj,row,col,rstart=baij->rstartbs;
3879:   PetscInt        rend=baij->rendbs,cstart=baij->cstartbs,stepval;
3880:   PetscInt        cend=baij->cendbs,bs=mat->rmap->bs,bs2=baij->bs2;

3883:   /* tasks normally handled by MatSetValuesBlocked() */
3884:   if (mat->insertmode == NOT_SET_VALUES) mat->insertmode = addv;
3885: #if defined(PETSC_USE_DEBUG)
3886:   else if (mat->insertmode != addv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Cannot mix add values and insert values");
3887:   if (mat->factortype) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Not for factored matrix");
3888: #endif
3889:   if (mat->assembled) {
3890:     mat->was_assembled = PETSC_TRUE;
3891:     mat->assembled     = PETSC_FALSE;
3892:   }
3893:   PetscLogEventBegin(MAT_SetValues,mat,0,0,0);


3896:   if (!barray) {
3897:     PetscMalloc1(bs2,&barray);
3898:     baij->barray = barray;
3899:   }

3901:   if (roworiented) stepval = (n-1)*bs;
3902:   else stepval = (m-1)*bs;

3904:   for (i=0; i<m; i++) {
3905:     if (im[i] < 0) continue;
3906: #if defined(PETSC_USE_DEBUG)
3907:     if (im[i] >= baij->Mbs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Row too large, row %D max %D",im[i],baij->Mbs-1);
3908: #endif
3909:     if (im[i] >= rstart && im[i] < rend) {
3910:       row = im[i] - rstart;
3911:       for (j=0; j<n; j++) {
3912:         /* If NumCol = 1 then a copy is not required */
3913:         if ((roworiented) && (n == 1)) {
3914:           barray = (MatScalar*)v + i*bs2;
3915:         } else if ((!roworiented) && (m == 1)) {
3916:           barray = (MatScalar*)v + j*bs2;
3917:         } else { /* Here a copy is required */
3918:           if (roworiented) {
3919:             value = v + i*(stepval+bs)*bs + j*bs;
3920:           } else {
3921:             value = v + j*(stepval+bs)*bs + i*bs;
3922:           }
3923:           for (ii=0; ii<bs; ii++,value+=stepval) {
3924:             for (jj=0; jj<bs; jj++) {
3925:               *barray++ = *value++;
3926:             }
3927:           }
3928:           barray -=bs2;
3929:         }

3931:         if (in[j] >= cstart && in[j] < cend) {
3932:           col  = in[j] - cstart;
3933:           MatSetValuesBlocked_SeqBAIJ_Inlined(baij->A,row,col,barray,addv,im[i],in[j]);
3934:         } else if (in[j] < 0) continue;
3935: #if defined(PETSC_USE_DEBUG)
3936:         else if (in[j] >= baij->Nbs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Column too large, col %D max %D",in[j],baij->Nbs-1);
3937: #endif
3938:         else {
3939:           if (mat->was_assembled) {
3940:             if (!baij->colmap) {
3941:               MatCreateColmap_MPIBAIJ_Private(mat);
3942:             }

3944: #if defined(PETSC_USE_DEBUG)
3945: #if defined(PETSC_USE_CTABLE)
3946:             { PetscInt data;
3947:               PetscTableFind(baij->colmap,in[j]+1,&data);
3948:               if ((data - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
3949:             }
3950: #else
3951:             if ((baij->colmap[in[j]] - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
3952: #endif
3953: #endif
3954: #if defined(PETSC_USE_CTABLE)
3955:             PetscTableFind(baij->colmap,in[j]+1,&col);
3956:             col  = (col - 1)/bs;
3957: #else
3958:             col = (baij->colmap[in[j]] - 1)/bs;
3959: #endif
3960:             if (col < 0 && !((Mat_SeqBAIJ*)(baij->A->data))->nonew) {
3961:               MatDisAssemble_MPIBAIJ(mat);
3962:               col  =  in[j];
3963:             }
3964:           } else col = in[j];
3965:           MatSetValuesBlocked_SeqBAIJ_Inlined(baij->B,row,col,barray,addv,im[i],in[j]);
3966:         }
3967:       }
3968:     } else {
3969:       if (!baij->donotstash) {
3970:         if (roworiented) {
3971:           MatStashValuesRowBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
3972:         } else {
3973:           MatStashValuesColBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
3974:         }
3975:       }
3976:     }
3977:   }

3979:   /* task normally handled by MatSetValuesBlocked() */
3980:   PetscLogEventEnd(MAT_SetValues,mat,0,0,0);
3981:   return(0);
3982: }

3986: /*@
3987:      MatCreateMPIBAIJWithArrays - creates a MPI BAIJ matrix using arrays that contain in standard
3988:          CSR format the local rows.

3990:    Collective on MPI_Comm

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

4005:    Output Parameter:
4006: .   mat - the matrix

4008:    Level: intermediate

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

4015:      The order of the entries in values is the same as the block compressed sparse row storage format; that is, it is
4016:      the same as a three dimensional array in Fortran values(bs,bs,nnz) that contains the first column of the first
4017:      block, followed by the second column of the first block etc etc.  That is, the blocks are contiguous in memory
4018:      with column-major ordering within blocks.

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

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

4024: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
4025:           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
4026: @*/
4027: PetscErrorCode  MatCreateMPIBAIJWithArrays(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
4028: {

4032:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
4033:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
4034:   MatCreate(comm,mat);
4035:   MatSetSizes(*mat,m,n,M,N);
4036:   MatSetType(*mat,MATMPISBAIJ);
4037:   MatSetOption(*mat,MAT_ROW_ORIENTED,PETSC_FALSE);
4038:   MatMPIBAIJSetPreallocationCSR(*mat,bs,i,j,a);
4039:   MatSetOption(*mat,MAT_ROW_ORIENTED,PETSC_TRUE);
4040:   return(0);
4041: }

4045: PetscErrorCode MatCreateMPIMatConcatenateSeqMat_MPIBAIJ(MPI_Comm comm,Mat inmat,PetscInt n,MatReuse scall,Mat *outmat)
4046: {
4048:   PetscInt       m,N,i,rstart,nnz,Ii,bs,cbs;
4049:   PetscInt       *indx;
4050:   PetscScalar    *values;

4053:   MatGetSize(inmat,&m,&N);
4054:   if (scall == MAT_INITIAL_MATRIX) { /* symbolic phase */
4055:     Mat_SeqBAIJ    *a = (Mat_SeqBAIJ*)inmat->data;
4056:     PetscInt       *dnz,*onz,sum,mbs,Nbs;
4057:     PetscInt       *bindx,rmax=a->rmax,j;
4058: 
4059:     MatGetBlockSizes(inmat,&bs,&cbs);
4060:     mbs = m/bs; Nbs = N/cbs;
4061:     if (n == PETSC_DECIDE) {
4062:       PetscSplitOwnership(comm,&n,&Nbs);
4063:     }
4064:     /* Check sum(n) = Nbs */
4065:     MPIU_Allreduce(&n,&sum,1,MPIU_INT,MPI_SUM,comm);
4066:     if (sum != Nbs) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"Sum of local columns != global columns %d",Nbs);

4068:     MPI_Scan(&mbs, &rstart,1,MPIU_INT,MPI_SUM,comm);
4069:     rstart -= mbs;

4071:     PetscMalloc1(rmax,&bindx);
4072:     MatPreallocateInitialize(comm,mbs,n,dnz,onz);
4073:     for (i=0; i<mbs; i++) {
4074:       MatGetRow_SeqBAIJ(inmat,i*bs,&nnz,&indx,NULL); /* non-blocked nnz and indx */
4075:       nnz = nnz/bs;
4076:       for (j=0; j<nnz; j++) bindx[j] = indx[j*bs]/bs;
4077:       MatPreallocateSet(i+rstart,nnz,bindx,dnz,onz);
4078:       MatRestoreRow_SeqBAIJ(inmat,i*bs,&nnz,&indx,NULL);
4079:     }
4080:     PetscFree(bindx);

4082:     MatCreate(comm,outmat);
4083:     MatSetSizes(*outmat,m,n*bs,PETSC_DETERMINE,PETSC_DETERMINE);
4084:     MatSetBlockSizes(*outmat,bs,cbs);
4085:     MatSetType(*outmat,MATMPIBAIJ);
4086:     MatMPIBAIJSetPreallocation(*outmat,bs,0,dnz,0,onz);
4087:     MatPreallocateFinalize(dnz,onz);
4088:   }
4089: 
4090:   /* numeric phase */
4091:   MatGetBlockSizes(inmat,&bs,&cbs);
4092:   MatGetOwnershipRange(*outmat,&rstart,NULL);

4094:   for (i=0; i<m; i++) {
4095:     MatGetRow_SeqBAIJ(inmat,i,&nnz,&indx,&values);
4096:     Ii   = i + rstart;
4097:     MatSetValues(*outmat,1,&Ii,nnz,indx,values,INSERT_VALUES);
4098:     MatRestoreRow_SeqBAIJ(inmat,i,&nnz,&indx,&values);
4099:   }
4100:   MatAssemblyBegin(*outmat,MAT_FINAL_ASSEMBLY);
4101:   MatAssemblyEnd(*outmat,MAT_FINAL_ASSEMBLY);
4102:   return(0);
4103: }