Actual source code: mpisbaij.c

petsc-dev 2014-08-26
Report Typos and Errors
  2: #include <../src/mat/impls/baij/mpi/mpibaij.h>    /*I "petscmat.h" I*/
  3: #include <../src/mat/impls/sbaij/mpi/mpisbaij.h>
  4: #include <../src/mat/impls/sbaij/seq/sbaij.h>
  5: #include <petscblaslapack.h>

  7: extern PetscErrorCode MatSetUpMultiply_MPISBAIJ(Mat);
  8: extern PetscErrorCode MatSetUpMultiply_MPISBAIJ_2comm(Mat);
  9: extern PetscErrorCode MatDisAssemble_MPISBAIJ(Mat);
 10: extern PetscErrorCode MatIncreaseOverlap_MPISBAIJ(Mat,PetscInt,IS[],PetscInt);
 11: extern PetscErrorCode MatGetValues_SeqSBAIJ(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],PetscScalar []);
 12: extern PetscErrorCode MatGetValues_SeqBAIJ(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],PetscScalar []);
 13: extern PetscErrorCode MatSetValues_SeqSBAIJ(Mat,PetscInt,const PetscInt [],PetscInt,const PetscInt [],const PetscScalar [],InsertMode);
 14: extern PetscErrorCode MatSetValuesBlocked_SeqSBAIJ(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],InsertMode);
 15: extern PetscErrorCode MatSetValuesBlocked_SeqBAIJ(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],InsertMode);
 16: extern PetscErrorCode MatGetRow_SeqSBAIJ(Mat,PetscInt,PetscInt*,PetscInt**,PetscScalar**);
 17: extern PetscErrorCode MatRestoreRow_SeqSBAIJ(Mat,PetscInt,PetscInt*,PetscInt**,PetscScalar**);
 18: extern PetscErrorCode MatZeroRows_SeqSBAIJ(Mat,IS,PetscScalar*,Vec,Vec);
 19: extern PetscErrorCode MatZeroRows_SeqBAIJ(Mat,IS,PetscScalar*,Vec,Vec);
 20: extern PetscErrorCode MatGetRowMaxAbs_MPISBAIJ(Mat,Vec,PetscInt[]);
 21: extern PetscErrorCode MatSOR_MPISBAIJ(Mat,Vec,PetscReal,MatSORType,PetscReal,PetscInt,PetscInt,Vec);

 25: PetscErrorCode  MatStoreValues_MPISBAIJ(Mat mat)
 26: {
 27:   Mat_MPISBAIJ   *aij = (Mat_MPISBAIJ*)mat->data;

 31:   MatStoreValues(aij->A);
 32:   MatStoreValues(aij->B);
 33:   return(0);
 34: }

 38: PetscErrorCode  MatRetrieveValues_MPISBAIJ(Mat mat)
 39: {
 40:   Mat_MPISBAIJ   *aij = (Mat_MPISBAIJ*)mat->data;

 44:   MatRetrieveValues(aij->A);
 45:   MatRetrieveValues(aij->B);
 46:   return(0);
 47: }

 49: #define  MatSetValues_SeqSBAIJ_A_Private(row,col,value,addv) \
 50:   { \
 51:  \
 52:     brow = row/bs;  \
 53:     rp   = aj + ai[brow]; ap = aa + bs2*ai[brow]; \
 54:     rmax = aimax[brow]; nrow = ailen[brow]; \
 55:     bcol = col/bs; \
 56:     ridx = row % bs; cidx = col % bs; \
 57:     low  = 0; high = nrow; \
 58:     while (high-low > 3) { \
 59:       t = (low+high)/2; \
 60:       if (rp[t] > bcol) high = t; \
 61:       else              low  = t; \
 62:     } \
 63:     for (_i=low; _i<high; _i++) { \
 64:       if (rp[_i] > bcol) break; \
 65:       if (rp[_i] == bcol) { \
 66:         bap = ap + bs2*_i + bs*cidx + ridx; \
 67:         if (addv == ADD_VALUES) *bap += value;  \
 68:         else                    *bap  = value;  \
 69:         goto a_noinsert; \
 70:       } \
 71:     } \
 72:     if (a->nonew == 1) goto a_noinsert; \
 73:     if (a->nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
 74:     MatSeqXAIJReallocateAIJ(A,a->mbs,bs2,nrow,brow,bcol,rmax,aa,ai,aj,rp,ap,aimax,a->nonew,MatScalar); \
 75:     N = nrow++ - 1;  \
 76:     /* shift up all the later entries in this row */ \
 77:     for (ii=N; ii>=_i; ii--) { \
 78:       rp[ii+1] = rp[ii]; \
 79:       PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); \
 80:     } \
 81:     if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar)); }  \
 82:     rp[_i]                      = bcol;  \
 83:     ap[bs2*_i + bs*cidx + ridx] = value;  \
 84:     A->nonzerostate++;\
 85: a_noinsert:; \
 86:     ailen[brow] = nrow; \
 87:   }

 89: #define  MatSetValues_SeqSBAIJ_B_Private(row,col,value,addv) \
 90:   { \
 91:     brow = row/bs;  \
 92:     rp   = bj + bi[brow]; ap = ba + bs2*bi[brow]; \
 93:     rmax = bimax[brow]; nrow = bilen[brow]; \
 94:     bcol = col/bs; \
 95:     ridx = row % bs; cidx = col % bs; \
 96:     low  = 0; high = nrow; \
 97:     while (high-low > 3) { \
 98:       t = (low+high)/2; \
 99:       if (rp[t] > bcol) high = t; \
100:       else              low  = t; \
101:     } \
102:     for (_i=low; _i<high; _i++) { \
103:       if (rp[_i] > bcol) break; \
104:       if (rp[_i] == bcol) { \
105:         bap = ap + bs2*_i + bs*cidx + ridx; \
106:         if (addv == ADD_VALUES) *bap += value;  \
107:         else                    *bap  = value;  \
108:         goto b_noinsert; \
109:       } \
110:     } \
111:     if (b->nonew == 1) goto b_noinsert; \
112:     if (b->nonew == -1) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero (%D, %D) into matrix", row, col); \
113:     MatSeqXAIJReallocateAIJ(B,b->mbs,bs2,nrow,brow,bcol,rmax,ba,bi,bj,rp,ap,bimax,b->nonew,MatScalar); \
114:     N = nrow++ - 1;  \
115:     /* shift up all the later entries in this row */ \
116:     for (ii=N; ii>=_i; ii--) { \
117:       rp[ii+1] = rp[ii]; \
118:       PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); \
119:     } \
120:     if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar));}  \
121:     rp[_i]                      = bcol;  \
122:     ap[bs2*_i + bs*cidx + ridx] = value;  \
123:     B->nonzerostate++;\
124: b_noinsert:; \
125:     bilen[brow] = nrow; \
126:   }

128: /* Only add/insert a(i,j) with i<=j (blocks).
129:    Any a(i,j) with i>j input by user is ingored.
130: */
133: PetscErrorCode MatSetValues_MPISBAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const PetscScalar v[],InsertMode addv)
134: {
135:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;
136:   MatScalar      value;
137:   PetscBool      roworiented = baij->roworiented;
139:   PetscInt       i,j,row,col;
140:   PetscInt       rstart_orig=mat->rmap->rstart;
141:   PetscInt       rend_orig  =mat->rmap->rend,cstart_orig=mat->cmap->rstart;
142:   PetscInt       cend_orig  =mat->cmap->rend,bs=mat->rmap->bs;

144:   /* Some Variables required in the macro */
145:   Mat          A     = baij->A;
146:   Mat_SeqSBAIJ *a    = (Mat_SeqSBAIJ*)(A)->data;
147:   PetscInt     *aimax=a->imax,*ai=a->i,*ailen=a->ilen,*aj=a->j;
148:   MatScalar    *aa   =a->a;

150:   Mat         B     = baij->B;
151:   Mat_SeqBAIJ *b    = (Mat_SeqBAIJ*)(B)->data;
152:   PetscInt    *bimax=b->imax,*bi=b->i,*bilen=b->ilen,*bj=b->j;
153:   MatScalar   *ba   =b->a;

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

159:   /* for stash */
160:   PetscInt  n_loc, *in_loc = NULL;
161:   MatScalar *v_loc = NULL;

164:   if (!baij->donotstash) {
165:     if (n > baij->n_loc) {
166:       PetscFree(baij->in_loc);
167:       PetscFree(baij->v_loc);
168:       PetscMalloc1(n,&baij->in_loc);
169:       PetscMalloc1(n,&baij->v_loc);

171:       baij->n_loc = n;
172:     }
173:     in_loc = baij->in_loc;
174:     v_loc  = baij->v_loc;
175:   }

177:   for (i=0; i<m; i++) {
178:     if (im[i] < 0) continue;
179: #if defined(PETSC_USE_DEBUG)
180:     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);
181: #endif
182:     if (im[i] >= rstart_orig && im[i] < rend_orig) { /* this processor entry */
183:       row = im[i] - rstart_orig;              /* local row index */
184:       for (j=0; j<n; j++) {
185:         if (im[i]/bs > in[j]/bs) {
186:           if (a->ignore_ltriangular) {
187:             continue;    /* ignore lower triangular blocks */
188:           } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Lower triangular value cannot be set for sbaij format. Ignoring these values, run with -mat_ignore_lower_triangular or call MatSetOption(mat,MAT_IGNORE_LOWER_TRIANGULAR,PETSC_TRUE)");
189:         }
190:         if (in[j] >= cstart_orig && in[j] < cend_orig) {  /* diag entry (A) */
191:           col  = in[j] - cstart_orig;         /* local col index */
192:           brow = row/bs; bcol = col/bs;
193:           if (brow > bcol) continue;  /* ignore lower triangular blocks of A */
194:           if (roworiented) value = v[i*n+j];
195:           else             value = v[i+j*m];
196:           MatSetValues_SeqSBAIJ_A_Private(row,col,value,addv);
197:           /* MatSetValues_SeqBAIJ(baij->A,1,&row,1,&col,&value,addv); */
198:         } else if (in[j] < 0) continue;
199: #if defined(PETSC_USE_DEBUG)
200:         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);
201: #endif
202:         else {  /* off-diag entry (B) */
203:           if (mat->was_assembled) {
204:             if (!baij->colmap) {
205:               MatCreateColmap_MPIBAIJ_Private(mat);
206:             }
207: #if defined(PETSC_USE_CTABLE)
208:             PetscTableFind(baij->colmap,in[j]/bs + 1,&col);
209:             col  = col - 1;
210: #else
211:             col = baij->colmap[in[j]/bs] - 1;
212: #endif
213:             if (col < 0 && !((Mat_SeqSBAIJ*)(baij->A->data))->nonew) {
214:               MatDisAssemble_MPISBAIJ(mat);
215:               col  =  in[j];
216:               /* Reinitialize the variables required by MatSetValues_SeqBAIJ_B_Private() */
217:               B    = baij->B;
218:               b    = (Mat_SeqBAIJ*)(B)->data;
219:               bimax= b->imax;bi=b->i;bilen=b->ilen;bj=b->j;
220:               ba   = b->a;
221:             } else col += in[j]%bs;
222:           } else col = in[j];
223:           if (roworiented) value = v[i*n+j];
224:           else             value = v[i+j*m];
225:           MatSetValues_SeqSBAIJ_B_Private(row,col,value,addv);
226:           /* MatSetValues_SeqBAIJ(baij->B,1,&row,1,&col,&value,addv); */
227:         }
228:       }
229:     } else {  /* off processor entry */
230:       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]);
231:       if (!baij->donotstash) {
232:         mat->assembled = PETSC_FALSE;
233:         n_loc          = 0;
234:         for (j=0; j<n; j++) {
235:           if (im[i]/bs > in[j]/bs) continue; /* ignore lower triangular blocks */
236:           in_loc[n_loc] = in[j];
237:           if (roworiented) {
238:             v_loc[n_loc] = v[i*n+j];
239:           } else {
240:             v_loc[n_loc] = v[j*m+i];
241:           }
242:           n_loc++;
243:         }
244:         MatStashValuesRow_Private(&mat->stash,im[i],n_loc,in_loc,v_loc,PETSC_FALSE);
245:       }
246:     }
247:   }
248:   return(0);
249: }

253: PetscErrorCode MatSetValuesBlocked_MPISBAIJ(Mat mat,PetscInt m,const PetscInt im[],PetscInt n,const PetscInt in[],const MatScalar v[],InsertMode addv)
254: {
255:   Mat_MPISBAIJ    *baij = (Mat_MPISBAIJ*)mat->data;
256:   const MatScalar *value;
257:   MatScalar       *barray     =baij->barray;
258:   PetscBool       roworiented = baij->roworiented,ignore_ltriangular = ((Mat_SeqSBAIJ*)baij->A->data)->ignore_ltriangular;
259:   PetscErrorCode  ierr;
260:   PetscInt        i,j,ii,jj,row,col,rstart=baij->rstartbs;
261:   PetscInt        rend=baij->rendbs,cstart=baij->rstartbs,stepval;
262:   PetscInt        cend=baij->rendbs,bs=mat->rmap->bs,bs2=baij->bs2;

265:   if (!barray) {
266:     PetscMalloc1(bs2,&barray);
267:     baij->barray = barray;
268:   }

270:   if (roworiented) {
271:     stepval = (n-1)*bs;
272:   } else {
273:     stepval = (m-1)*bs;
274:   }
275:   for (i=0; i<m; i++) {
276:     if (im[i] < 0) continue;
277: #if defined(PETSC_USE_DEBUG)
278:     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);
279: #endif
280:     if (im[i] >= rstart && im[i] < rend) {
281:       row = im[i] - rstart;
282:       for (j=0; j<n; j++) {
283:         if (im[i] > in[j]) {
284:           if (ignore_ltriangular) continue; /* ignore lower triangular blocks */
285:           else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_USER,"Lower triangular value cannot be set for sbaij format. Ignoring these values, run with -mat_ignore_lower_triangular or call MatSetOption(mat,MAT_IGNORE_LOWER_TRIANGULAR,PETSC_TRUE)");
286:         }
287:         /* If NumCol = 1 then a copy is not required */
288:         if ((roworiented) && (n == 1)) {
289:           barray = (MatScalar*) v + i*bs2;
290:         } else if ((!roworiented) && (m == 1)) {
291:           barray = (MatScalar*) v + j*bs2;
292:         } else { /* Here a copy is required */
293:           if (roworiented) {
294:             value = v + i*(stepval+bs)*bs + j*bs;
295:           } else {
296:             value = v + j*(stepval+bs)*bs + i*bs;
297:           }
298:           for (ii=0; ii<bs; ii++,value+=stepval) {
299:             for (jj=0; jj<bs; jj++) {
300:               *barray++ = *value++;
301:             }
302:           }
303:           barray -=bs2;
304:         }

306:         if (in[j] >= cstart && in[j] < cend) {
307:           col  = in[j] - cstart;
308:           MatSetValuesBlocked_SeqSBAIJ(baij->A,1,&row,1,&col,barray,addv);
309:         } else if (in[j] < 0) continue;
310: #if defined(PETSC_USE_DEBUG)
311:         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);
312: #endif
313:         else {
314:           if (mat->was_assembled) {
315:             if (!baij->colmap) {
316:               MatCreateColmap_MPIBAIJ_Private(mat);
317:             }

319: #if defined(PETSC_USE_DEBUG)
320: #if defined(PETSC_USE_CTABLE)
321:             { PetscInt data;
322:               PetscTableFind(baij->colmap,in[j]+1,&data);
323:               if ((data - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
324:             }
325: #else
326:             if ((baij->colmap[in[j]] - 1) % bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Incorrect colmap");
327: #endif
328: #endif
329: #if defined(PETSC_USE_CTABLE)
330:             PetscTableFind(baij->colmap,in[j]+1,&col);
331:             col  = (col - 1)/bs;
332: #else
333:             col = (baij->colmap[in[j]] - 1)/bs;
334: #endif
335:             if (col < 0 && !((Mat_SeqBAIJ*)(baij->A->data))->nonew) {
336:               MatDisAssemble_MPISBAIJ(mat);
337:               col  = in[j];
338:             }
339:           } else col = in[j];
340:           MatSetValuesBlocked_SeqBAIJ(baij->B,1,&row,1,&col,barray,addv);
341:         }
342:       }
343:     } else {
344:       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]);
345:       if (!baij->donotstash) {
346:         if (roworiented) {
347:           MatStashValuesRowBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
348:         } else {
349:           MatStashValuesColBlocked_Private(&mat->bstash,im[i],n,in,v,m,n,i);
350:         }
351:       }
352:     }
353:   }
354:   return(0);
355: }

359: PetscErrorCode MatGetValues_MPISBAIJ(Mat mat,PetscInt m,const PetscInt idxm[],PetscInt n,const PetscInt idxn[],PetscScalar v[])
360: {
361:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;
363:   PetscInt       bs       = mat->rmap->bs,i,j,bsrstart = mat->rmap->rstart,bsrend = mat->rmap->rend;
364:   PetscInt       bscstart = mat->cmap->rstart,bscend = mat->cmap->rend,row,col,data;

367:   for (i=0; i<m; i++) {
368:     if (idxm[i] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative row: %D",idxm[i]); */
369:     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);
370:     if (idxm[i] >= bsrstart && idxm[i] < bsrend) {
371:       row = idxm[i] - bsrstart;
372:       for (j=0; j<n; j++) {
373:         if (idxn[j] < 0) continue; /* SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Negative column %D",idxn[j]); */
374:         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);
375:         if (idxn[j] >= bscstart && idxn[j] < bscend) {
376:           col  = idxn[j] - bscstart;
377:           MatGetValues_SeqSBAIJ(baij->A,1,&row,1,&col,v+i*n+j);
378:         } else {
379:           if (!baij->colmap) {
380:             MatCreateColmap_MPIBAIJ_Private(mat);
381:           }
382: #if defined(PETSC_USE_CTABLE)
383:           PetscTableFind(baij->colmap,idxn[j]/bs+1,&data);
384:           data--;
385: #else
386:           data = baij->colmap[idxn[j]/bs]-1;
387: #endif
388:           if ((data < 0) || (baij->garray[data/bs] != idxn[j]/bs)) *(v+i*n+j) = 0.0;
389:           else {
390:             col  = data + idxn[j]%bs;
391:             MatGetValues_SeqBAIJ(baij->B,1,&row,1,&col,v+i*n+j);
392:           }
393:         }
394:       }
395:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local values currently supported");
396:   }
397:   return(0);
398: }

402: PetscErrorCode MatNorm_MPISBAIJ(Mat mat,NormType type,PetscReal *norm)
403: {
404:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;
406:   PetscReal      sum[2],*lnorm2;

409:   if (baij->size == 1) {
410:      MatNorm(baij->A,type,norm);
411:   } else {
412:     if (type == NORM_FROBENIUS) {
413:       PetscMalloc1(2,&lnorm2);
414:        MatNorm(baij->A,type,lnorm2);
415:       *lnorm2 = (*lnorm2)*(*lnorm2); lnorm2++;            /* squar power of norm(A) */
416:        MatNorm(baij->B,type,lnorm2);
417:       *lnorm2 = (*lnorm2)*(*lnorm2); lnorm2--;             /* squar power of norm(B) */
418:       MPI_Allreduce(lnorm2,sum,2,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
419:       *norm   = PetscSqrtReal(sum[0] + 2*sum[1]);
420:       PetscFree(lnorm2);
421:     } else if (type == NORM_INFINITY || type == NORM_1) { /* max row/column sum */
422:       Mat_SeqSBAIJ *amat=(Mat_SeqSBAIJ*)baij->A->data;
423:       Mat_SeqBAIJ  *bmat=(Mat_SeqBAIJ*)baij->B->data;
424:       PetscReal    *rsum,*rsum2,vabs;
425:       PetscInt     *jj,*garray=baij->garray,rstart=baij->rstartbs,nz;
426:       PetscInt     brow,bcol,col,bs=baij->A->rmap->bs,row,grow,gcol,mbs=amat->mbs;
427:       MatScalar    *v;

429:       PetscMalloc2(mat->cmap->N,&rsum,mat->cmap->N,&rsum2);
430:       PetscMemzero(rsum,mat->cmap->N*sizeof(PetscReal));
431:       /* Amat */
432:       v = amat->a; jj = amat->j;
433:       for (brow=0; brow<mbs; brow++) {
434:         grow = bs*(rstart + brow);
435:         nz   = amat->i[brow+1] - amat->i[brow];
436:         for (bcol=0; bcol<nz; bcol++) {
437:           gcol = bs*(rstart + *jj); jj++;
438:           for (col=0; col<bs; col++) {
439:             for (row=0; row<bs; row++) {
440:               vabs            = PetscAbsScalar(*v); v++;
441:               rsum[gcol+col] += vabs;
442:               /* non-diagonal block */
443:               if (bcol > 0 && vabs > 0.0) rsum[grow+row] += vabs;
444:             }
445:           }
446:         }
447:       }
448:       /* Bmat */
449:       v = bmat->a; jj = bmat->j;
450:       for (brow=0; brow<mbs; brow++) {
451:         grow = bs*(rstart + brow);
452:         nz = bmat->i[brow+1] - bmat->i[brow];
453:         for (bcol=0; bcol<nz; bcol++) {
454:           gcol = bs*garray[*jj]; jj++;
455:           for (col=0; col<bs; col++) {
456:             for (row=0; row<bs; row++) {
457:               vabs            = PetscAbsScalar(*v); v++;
458:               rsum[gcol+col] += vabs;
459:               rsum[grow+row] += vabs;
460:             }
461:           }
462:         }
463:       }
464:       MPI_Allreduce(rsum,rsum2,mat->cmap->N,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)mat));
465:       *norm = 0.0;
466:       for (col=0; col<mat->cmap->N; col++) {
467:         if (rsum2[col] > *norm) *norm = rsum2[col];
468:       }
469:       PetscFree2(rsum,rsum2);
470:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for this norm yet");
471:   }
472:   return(0);
473: }

477: PetscErrorCode MatAssemblyBegin_MPISBAIJ(Mat mat,MatAssemblyType mode)
478: {
479:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;
481:   PetscInt       nstash,reallocs;
482:   InsertMode     addv;

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

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

492:   MatStashScatterBegin_Private(mat,&mat->stash,mat->rmap->range);
493:   MatStashScatterBegin_Private(mat,&mat->bstash,baij->rangebs);
494:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
495:   PetscInfo2(mat,"Stash has %D entries,uses %D mallocs.\n",nstash,reallocs);
496:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
497:   PetscInfo2(mat,"Block-Stash has %D entries, uses %D mallocs.\n",nstash,reallocs);
498:   return(0);
499: }

503: PetscErrorCode MatAssemblyEnd_MPISBAIJ(Mat mat,MatAssemblyType mode)
504: {
505:   Mat_MPISBAIJ   *baij=(Mat_MPISBAIJ*)mat->data;
506:   Mat_SeqSBAIJ   *a   =(Mat_SeqSBAIJ*)baij->A->data;
508:   PetscInt       i,j,rstart,ncols,flg,bs2=baij->bs2;
509:   PetscInt       *row,*col;
510:   PetscBool      other_disassembled;
511:   PetscMPIInt    n;
512:   PetscBool      r1,r2,r3;
513:   MatScalar      *val;
514:   InsertMode     addv = mat->insertmode;

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

523:       for (i=0; i<n;) {
524:         /* Now identify the consecutive vals belonging to the same row */
525:         for (j=i,rstart=row[j]; j<n; j++) {
526:           if (row[j] != rstart) break;
527:         }
528:         if (j < n) ncols = j-i;
529:         else       ncols = n-i;
530:         /* Now assemble all these values with a single function call */
531:         MatSetValues_MPISBAIJ(mat,1,row+i,ncols,col+i,val+i,addv);
532:         i    = j;
533:       }
534:     }
535:     MatStashScatterEnd_Private(&mat->stash);
536:     /* Now process the block-stash. Since the values are stashed column-oriented,
537:        set the roworiented flag to column oriented, and after MatSetValues()
538:        restore the original flags */
539:     r1 = baij->roworiented;
540:     r2 = a->roworiented;
541:     r3 = ((Mat_SeqBAIJ*)baij->B->data)->roworiented;

543:     baij->roworiented = PETSC_FALSE;
544:     a->roworiented    = PETSC_FALSE;

546:     ((Mat_SeqBAIJ*)baij->B->data)->roworiented = PETSC_FALSE; /* b->roworinted */
547:     while (1) {
548:       MatStashScatterGetMesg_Private(&mat->bstash,&n,&row,&col,&val,&flg);
549:       if (!flg) break;

551:       for (i=0; i<n;) {
552:         /* Now identify the consecutive vals belonging to the same row */
553:         for (j=i,rstart=row[j]; j<n; j++) {
554:           if (row[j] != rstart) break;
555:         }
556:         if (j < n) ncols = j-i;
557:         else       ncols = n-i;
558:         MatSetValuesBlocked_MPISBAIJ(mat,1,row+i,ncols,col+i,val+i*bs2,addv);
559:         i    = j;
560:       }
561:     }
562:     MatStashScatterEnd_Private(&mat->bstash);

564:     baij->roworiented = r1;
565:     a->roworiented    = r2;

567:     ((Mat_SeqBAIJ*)baij->B->data)->roworiented = r3; /* b->roworinted */
568:   }

570:   MatAssemblyBegin(baij->A,mode);
571:   MatAssemblyEnd(baij->A,mode);

573:   /* determine if any processor has disassembled, if so we must
574:      also disassemble ourselfs, in order that we may reassemble. */
575:   /*
576:      if nonzero structure of submatrix B cannot change then we know that
577:      no processor disassembled thus we can skip this stuff
578:   */
579:   if (!((Mat_SeqBAIJ*)baij->B->data)->nonew) {
580:     MPI_Allreduce(&mat->was_assembled,&other_disassembled,1,MPIU_BOOL,MPI_PROD,PetscObjectComm((PetscObject)mat));
581:     if (mat->was_assembled && !other_disassembled) {
582:       MatDisAssemble_MPISBAIJ(mat);
583:     }
584:   }

586:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
587:     MatSetUpMultiply_MPISBAIJ(mat); /* setup Mvctx and sMvctx */
588:   }
589:   MatAssemblyBegin(baij->B,mode);
590:   MatAssemblyEnd(baij->B,mode);

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

594:   baij->rowvalues = 0;

596:   /* if no new nonzero locations are allowed in matrix then only set the matrix state the first time through */
597:   if ((!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) || !((Mat_SeqBAIJ*)(baij->A->data))->nonew) {
598:     PetscObjectState state = baij->A->nonzerostate + baij->B->nonzerostate;
599:     MPI_Allreduce(&state,&mat->nonzerostate,1,MPIU_INT64,MPI_SUM,PetscObjectComm((PetscObject)mat));
600:   }
601:   return(0);
602: }

604: extern PetscErrorCode MatView_SeqSBAIJ_ASCII(Mat,PetscViewer);
605: extern PetscErrorCode MatSetValues_MPIBAIJ(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[],const PetscScalar[],InsertMode);
606: #include <petscdraw.h>
609: static PetscErrorCode MatView_MPISBAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
610: {
611:   Mat_MPISBAIJ      *baij = (Mat_MPISBAIJ*)mat->data;
612:   PetscErrorCode    ierr;
613:   PetscInt          bs   = mat->rmap->bs;
614:   PetscMPIInt       rank = baij->rank;
615:   PetscBool         iascii,isdraw;
616:   PetscViewer       sviewer;
617:   PetscViewerFormat format;

620:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
621:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
622:   if (iascii) {
623:     PetscViewerGetFormat(viewer,&format);
624:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
625:       MatInfo info;
626:       MPI_Comm_rank(PetscObjectComm((PetscObject)mat),&rank);
627:       MatGetInfo(mat,MAT_LOCAL,&info);
628:       PetscViewerASCIISynchronizedAllow(viewer,PETSC_TRUE);
629:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %D nz %D nz alloced %D bs %D mem %D\n",rank,mat->rmap->n,(PetscInt)info.nz_used,(PetscInt)info.nz_allocated,mat->rmap->bs,(PetscInt)info.memory);
630:       MatGetInfo(baij->A,MAT_LOCAL,&info);
631:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
632:       MatGetInfo(baij->B,MAT_LOCAL,&info);
633:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %D \n",rank,(PetscInt)info.nz_used);
634:       PetscViewerFlush(viewer);
635:       PetscViewerASCIISynchronizedAllow(viewer,PETSC_FALSE);
636:       PetscViewerASCIIPrintf(viewer,"Information on VecScatter used in matrix-vector product: \n");
637:       VecScatterView(baij->Mvctx,viewer);
638:       return(0);
639:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
640:       PetscViewerASCIIPrintf(viewer,"  block size is %D\n",bs);
641:       return(0);
642:     } else if (format == PETSC_VIEWER_ASCII_FACTOR_INFO) {
643:       return(0);
644:     }
645:   }

647:   if (isdraw) {
648:     PetscDraw draw;
649:     PetscBool isnull;
650:     PetscViewerDrawGetDraw(viewer,0,&draw);
651:     PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
652:   }

654:   {
655:     /* assemble the entire matrix onto first processor. */
656:     Mat          A;
657:     Mat_SeqSBAIJ *Aloc;
658:     Mat_SeqBAIJ  *Bloc;
659:     PetscInt     M = mat->rmap->N,N = mat->cmap->N,*ai,*aj,col,i,j,k,*rvals,mbs = baij->mbs;
660:     MatScalar    *a;

662:     /* Should this be the same type as mat? */
663:     MatCreate(PetscObjectComm((PetscObject)mat),&A);
664:     if (!rank) {
665:       MatSetSizes(A,M,N,M,N);
666:     } else {
667:       MatSetSizes(A,0,0,M,N);
668:     }
669:     MatSetType(A,MATMPISBAIJ);
670:     MatMPISBAIJSetPreallocation(A,mat->rmap->bs,0,NULL,0,NULL);
671:     MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_FALSE);
672:     PetscLogObjectParent((PetscObject)mat,(PetscObject)A);

674:     /* copy over the A part */
675:     Aloc = (Mat_SeqSBAIJ*)baij->A->data;
676:     ai   = Aloc->i; aj = Aloc->j; a = Aloc->a;
677:     PetscMalloc1(bs,&rvals);

679:     for (i=0; i<mbs; i++) {
680:       rvals[0] = bs*(baij->rstartbs + i);
681:       for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
682:       for (j=ai[i]; j<ai[i+1]; j++) {
683:         col = (baij->cstartbs+aj[j])*bs;
684:         for (k=0; k<bs; k++) {
685:           MatSetValues_MPISBAIJ(A,bs,rvals,1,&col,a,INSERT_VALUES);
686:           col++;
687:           a += bs;
688:         }
689:       }
690:     }
691:     /* copy over the B part */
692:     Bloc = (Mat_SeqBAIJ*)baij->B->data;
693:     ai   = Bloc->i; aj = Bloc->j; a = Bloc->a;
694:     for (i=0; i<mbs; i++) {

696:       rvals[0] = bs*(baij->rstartbs + i);
697:       for (j=1; j<bs; j++) rvals[j] = rvals[j-1] + 1;
698:       for (j=ai[i]; j<ai[i+1]; j++) {
699:         col = baij->garray[aj[j]]*bs;
700:         for (k=0; k<bs; k++) {
701:           MatSetValues_MPIBAIJ(A,bs,rvals,1,&col,a,INSERT_VALUES);
702:           col++;
703:           a += bs;
704:         }
705:       }
706:     }
707:     PetscFree(rvals);
708:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
709:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
710:     /*
711:        Everyone has to call to draw the matrix since the graphics waits are
712:        synchronized across all processors that share the PetscDraw object
713:     */
714:     PetscViewerGetSingleton(viewer,&sviewer);
715:     if (!rank) {
716:         MatView_SeqSBAIJ_ASCII(((Mat_MPISBAIJ*)(A->data))->A,sviewer);
717:     }
718:     PetscViewerRestoreSingleton(viewer,&sviewer);
719:     MatDestroy(&A);
720:   }
721:   return(0);
722: }

726: PetscErrorCode MatView_MPISBAIJ(Mat mat,PetscViewer viewer)
727: {
729:   PetscBool      iascii,isdraw,issocket,isbinary;

732:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
733:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
734:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSOCKET,&issocket);
735:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
736:   if (iascii || isdraw || issocket || isbinary) {
737:     MatView_MPISBAIJ_ASCIIorDraworSocket(mat,viewer);
738:   }
739:   return(0);
740: }

744: PetscErrorCode MatDestroy_MPISBAIJ(Mat mat)
745: {
746:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;

750: #if defined(PETSC_USE_LOG)
751:   PetscLogObjectState((PetscObject)mat,"Rows=%D,Cols=%D",mat->rmap->N,mat->cmap->N);
752: #endif
753:   MatStashDestroy_Private(&mat->stash);
754:   MatStashDestroy_Private(&mat->bstash);
755:   MatDestroy(&baij->A);
756:   MatDestroy(&baij->B);
757: #if defined(PETSC_USE_CTABLE)
758:   PetscTableDestroy(&baij->colmap);
759: #else
760:   PetscFree(baij->colmap);
761: #endif
762:   PetscFree(baij->garray);
763:   VecDestroy(&baij->lvec);
764:   VecScatterDestroy(&baij->Mvctx);
765:   VecDestroy(&baij->slvec0);
766:   VecDestroy(&baij->slvec0b);
767:   VecDestroy(&baij->slvec1);
768:   VecDestroy(&baij->slvec1a);
769:   VecDestroy(&baij->slvec1b);
770:   VecScatterDestroy(&baij->sMvctx);
771:   PetscFree2(baij->rowvalues,baij->rowindices);
772:   PetscFree(baij->barray);
773:   PetscFree(baij->hd);
774:   VecDestroy(&baij->diag);
775:   VecDestroy(&baij->bb1);
776:   VecDestroy(&baij->xx1);
777: #if defined(PETSC_USE_REAL_MAT_SINGLE)
778:   PetscFree(baij->setvaluescopy);
779: #endif
780:   PetscFree(baij->in_loc);
781:   PetscFree(baij->v_loc);
782:   PetscFree(baij->rangebs);
783:   PetscFree(mat->data);

785:   PetscObjectChangeTypeName((PetscObject)mat,0);
786:   PetscObjectComposeFunction((PetscObject)mat,"MatStoreValues_C",NULL);
787:   PetscObjectComposeFunction((PetscObject)mat,"MatRetrieveValues_C",NULL);
788:   PetscObjectComposeFunction((PetscObject)mat,"MatGetDiagonalBlock_C",NULL);
789:   PetscObjectComposeFunction((PetscObject)mat,"MatMPISBAIJSetPreallocation_C",NULL);
790:   PetscObjectComposeFunction((PetscObject)mat,"MatConvert_mpisbaij_mpisbstrm_C",NULL);
791:   return(0);
792: }

796: PetscErrorCode MatMult_MPISBAIJ_Hermitian(Mat A,Vec xx,Vec yy)
797: {
798:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
800:   PetscInt       nt,mbs=a->mbs,bs=A->rmap->bs;
801:   PetscScalar    *x,*from;

804:   VecGetLocalSize(xx,&nt);
805:   if (nt != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");

807:   /* diagonal part */
808:   (*a->A->ops->mult)(a->A,xx,a->slvec1a);
809:   VecSet(a->slvec1b,0.0);

811:   /* subdiagonal part */
812:   (*a->B->ops->multhermitiantranspose)(a->B,xx,a->slvec0b);

814:   /* copy x into the vec slvec0 */
815:   VecGetArray(a->slvec0,&from);
816:   VecGetArray(xx,&x);

818:   PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
819:   VecRestoreArray(a->slvec0,&from);
820:   VecRestoreArray(xx,&x);

822:   VecScatterBegin(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);
823:   VecScatterEnd(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);
824:   /* supperdiagonal part */
825:   (*a->B->ops->multadd)(a->B,a->slvec1b,a->slvec1a,yy);
826:   return(0);
827: }

831: PetscErrorCode MatMult_MPISBAIJ(Mat A,Vec xx,Vec yy)
832: {
833:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
835:   PetscInt       nt,mbs=a->mbs,bs=A->rmap->bs;
836:   PetscScalar    *x,*from;

839:   VecGetLocalSize(xx,&nt);
840:   if (nt != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");

842:   /* diagonal part */
843:   (*a->A->ops->mult)(a->A,xx,a->slvec1a);
844:   VecSet(a->slvec1b,0.0);

846:   /* subdiagonal part */
847:   (*a->B->ops->multtranspose)(a->B,xx,a->slvec0b);

849:   /* copy x into the vec slvec0 */
850:   VecGetArray(a->slvec0,&from);
851:   VecGetArray(xx,&x);

853:   PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
854:   VecRestoreArray(a->slvec0,&from);
855:   VecRestoreArray(xx,&x);

857:   VecScatterBegin(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);
858:   VecScatterEnd(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);
859:   /* supperdiagonal part */
860:   (*a->B->ops->multadd)(a->B,a->slvec1b,a->slvec1a,yy);
861:   return(0);
862: }

866: PetscErrorCode MatMult_MPISBAIJ_2comm(Mat A,Vec xx,Vec yy)
867: {
868:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
870:   PetscInt       nt;

873:   VecGetLocalSize(xx,&nt);
874:   if (nt != A->cmap->n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");

876:   VecGetLocalSize(yy,&nt);
877:   if (nt != A->rmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Incompatible parition of A and yy");

879:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
880:   /* do diagonal part */
881:   (*a->A->ops->mult)(a->A,xx,yy);
882:   /* do supperdiagonal part */
883:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
884:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
885:   /* do subdiagonal part */
886:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
887:   VecScatterBegin(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
888:   VecScatterEnd(a->Mvctx,a->lvec,yy,ADD_VALUES,SCATTER_REVERSE);
889:   return(0);
890: }

894: PetscErrorCode MatMultAdd_MPISBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
895: {
896:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
898:   PetscInt       mbs=a->mbs,bs=A->rmap->bs;
899:   PetscScalar    *x,*from,zero=0.0;

902:   /*
903:   PetscSynchronizedPrintf(PetscObjectComm((PetscObject)A)," MatMultAdd is called ...\n");
904:   PetscSynchronizedFlush(PetscObjectComm((PetscObject)A),PETSC_STDOUT);
905:   */
906:   /* diagonal part */
907:   (*a->A->ops->multadd)(a->A,xx,yy,a->slvec1a);
908:   VecSet(a->slvec1b,zero);

910:   /* subdiagonal part */
911:   (*a->B->ops->multtranspose)(a->B,xx,a->slvec0b);

913:   /* copy x into the vec slvec0 */
914:   VecGetArray(a->slvec0,&from);
915:   VecGetArray(xx,&x);
916:   PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
917:   VecRestoreArray(a->slvec0,&from);

919:   VecScatterBegin(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);
920:   VecRestoreArray(xx,&x);
921:   VecScatterEnd(a->sMvctx,a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD);

923:   /* supperdiagonal part */
924:   (*a->B->ops->multadd)(a->B,a->slvec1b,a->slvec1a,zz);
925:   return(0);
926: }

930: PetscErrorCode MatMultAdd_MPISBAIJ_2comm(Mat A,Vec xx,Vec yy,Vec zz)
931: {
932:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

936:   VecScatterBegin(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
937:   /* do diagonal part */
938:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
939:   /* do supperdiagonal part */
940:   VecScatterEnd(a->Mvctx,xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD);
941:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);

943:   /* do subdiagonal part */
944:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
945:   VecScatterBegin(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
946:   VecScatterEnd(a->Mvctx,a->lvec,zz,ADD_VALUES,SCATTER_REVERSE);
947:   return(0);
948: }

950: /*
951:   This only works correctly for square matrices where the subblock A->A is the
952:    diagonal block
953: */
956: PetscErrorCode MatGetDiagonal_MPISBAIJ(Mat A,Vec v)
957: {
958:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

962:   /* if (a->rmap->N != a->cmap->N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block"); */
963:   MatGetDiagonal(a->A,v);
964:   return(0);
965: }

969: PetscErrorCode MatScale_MPISBAIJ(Mat A,PetscScalar aa)
970: {
971:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

975:   MatScale(a->A,aa);
976:   MatScale(a->B,aa);
977:   return(0);
978: }

982: PetscErrorCode MatGetRow_MPISBAIJ(Mat matin,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
983: {
984:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
985:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
987:   PetscInt       bs = matin->rmap->bs,bs2 = mat->bs2,i,*cworkA,*cworkB,**pcA,**pcB;
988:   PetscInt       nztot,nzA,nzB,lrow,brstart = matin->rmap->rstart,brend = matin->rmap->rend;
989:   PetscInt       *cmap,*idx_p,cstart = mat->rstartbs;

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

995:   if (!mat->rowvalues && (idx || v)) {
996:     /*
997:         allocate enough space to hold information from the longest row.
998:     */
999:     Mat_SeqSBAIJ *Aa = (Mat_SeqSBAIJ*)mat->A->data;
1000:     Mat_SeqBAIJ  *Ba = (Mat_SeqBAIJ*)mat->B->data;
1001:     PetscInt     max = 1,mbs = mat->mbs,tmp;
1002:     for (i=0; i<mbs; i++) {
1003:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i]; /* row length */
1004:       if (max < tmp) max = tmp;
1005:     }
1006:     PetscMalloc2(max*bs2,&mat->rowvalues,max*bs2,&mat->rowindices);
1007:   }

1009:   if (row < brstart || row >= brend) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Only local rows");
1010:   lrow = row - brstart;  /* local row index */

1012:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1013:   if (!v)   {pvA = 0; pvB = 0;}
1014:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1015:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1016:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1017:   nztot = nzA + nzB;

1019:   cmap = mat->garray;
1020:   if (v  || idx) {
1021:     if (nztot) {
1022:       /* Sort by increasing column numbers, assuming A and B already sorted */
1023:       PetscInt imark = -1;
1024:       if (v) {
1025:         *v = v_p = mat->rowvalues;
1026:         for (i=0; i<nzB; i++) {
1027:           if (cmap[cworkB[i]/bs] < cstart) v_p[i] = vworkB[i];
1028:           else break;
1029:         }
1030:         imark = i;
1031:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1032:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1033:       }
1034:       if (idx) {
1035:         *idx = idx_p = mat->rowindices;
1036:         if (imark > -1) {
1037:           for (i=0; i<imark; i++) {
1038:             idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
1039:           }
1040:         } else {
1041:           for (i=0; i<nzB; i++) {
1042:             if (cmap[cworkB[i]/bs] < cstart) idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
1043:             else break;
1044:           }
1045:           imark = i;
1046:         }
1047:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart*bs + cworkA[i];
1048:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
1049:       }
1050:     } else {
1051:       if (idx) *idx = 0;
1052:       if (v)   *v   = 0;
1053:     }
1054:   }
1055:   *nz  = nztot;
1056:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1057:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1058:   return(0);
1059: }

1063: PetscErrorCode MatRestoreRow_MPISBAIJ(Mat mat,PetscInt row,PetscInt *nz,PetscInt **idx,PetscScalar **v)
1064: {
1065:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;

1068:   if (!baij->getrowactive) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"MatGetRow() must be called first");
1069:   baij->getrowactive = PETSC_FALSE;
1070:   return(0);
1071: }

1075: PetscErrorCode MatGetRowUpperTriangular_MPISBAIJ(Mat A)
1076: {
1077:   Mat_MPISBAIJ *a  = (Mat_MPISBAIJ*)A->data;
1078:   Mat_SeqSBAIJ *aA = (Mat_SeqSBAIJ*)a->A->data;

1081:   aA->getrow_utriangular = PETSC_TRUE;
1082:   return(0);
1083: }
1086: PetscErrorCode MatRestoreRowUpperTriangular_MPISBAIJ(Mat A)
1087: {
1088:   Mat_MPISBAIJ *a  = (Mat_MPISBAIJ*)A->data;
1089:   Mat_SeqSBAIJ *aA = (Mat_SeqSBAIJ*)a->A->data;

1092:   aA->getrow_utriangular = PETSC_FALSE;
1093:   return(0);
1094: }

1098: PetscErrorCode MatRealPart_MPISBAIJ(Mat A)
1099: {
1100:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

1104:   MatRealPart(a->A);
1105:   MatRealPart(a->B);
1106:   return(0);
1107: }

1111: PetscErrorCode MatImaginaryPart_MPISBAIJ(Mat A)
1112: {
1113:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

1117:   MatImaginaryPart(a->A);
1118:   MatImaginaryPart(a->B);
1119:   return(0);
1120: }

1124: PetscErrorCode MatZeroEntries_MPISBAIJ(Mat A)
1125: {
1126:   Mat_MPISBAIJ   *l = (Mat_MPISBAIJ*)A->data;

1130:   MatZeroEntries(l->A);
1131:   MatZeroEntries(l->B);
1132:   return(0);
1133: }

1137: PetscErrorCode MatGetInfo_MPISBAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1138: {
1139:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)matin->data;
1140:   Mat            A  = a->A,B = a->B;
1142:   PetscReal      isend[5],irecv[5];

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

1147:   MatGetInfo(A,MAT_LOCAL,info);

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

1152:   MatGetInfo(B,MAT_LOCAL,info);

1154:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1155:   isend[3] += info->memory;  isend[4] += info->mallocs;
1156:   if (flag == MAT_LOCAL) {
1157:     info->nz_used      = isend[0];
1158:     info->nz_allocated = isend[1];
1159:     info->nz_unneeded  = isend[2];
1160:     info->memory       = isend[3];
1161:     info->mallocs      = isend[4];
1162:   } else if (flag == MAT_GLOBAL_MAX) {
1163:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)matin));

1165:     info->nz_used      = irecv[0];
1166:     info->nz_allocated = irecv[1];
1167:     info->nz_unneeded  = irecv[2];
1168:     info->memory       = irecv[3];
1169:     info->mallocs      = irecv[4];
1170:   } else if (flag == MAT_GLOBAL_SUM) {
1171:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)matin));

1173:     info->nz_used      = irecv[0];
1174:     info->nz_allocated = irecv[1];
1175:     info->nz_unneeded  = irecv[2];
1176:     info->memory       = irecv[3];
1177:     info->mallocs      = irecv[4];
1178:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown MatInfoType argument %d",(int)flag);
1179:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1180:   info->fill_ratio_needed = 0;
1181:   info->factor_mallocs    = 0;
1182:   return(0);
1183: }

1187: PetscErrorCode MatSetOption_MPISBAIJ(Mat A,MatOption op,PetscBool flg)
1188: {
1189:   Mat_MPISBAIJ   *a  = (Mat_MPISBAIJ*)A->data;
1190:   Mat_SeqSBAIJ   *aA = (Mat_SeqSBAIJ*)a->A->data;

1194:   switch (op) {
1195:   case MAT_NEW_NONZERO_LOCATIONS:
1196:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1197:   case MAT_UNUSED_NONZERO_LOCATION_ERR:
1198:   case MAT_KEEP_NONZERO_PATTERN:
1199:   case MAT_NEW_NONZERO_LOCATION_ERR:
1200:     MatSetOption(a->A,op,flg);
1201:     MatSetOption(a->B,op,flg);
1202:     break;
1203:   case MAT_ROW_ORIENTED:
1204:     a->roworiented = flg;

1206:     MatSetOption(a->A,op,flg);
1207:     MatSetOption(a->B,op,flg);
1208:     break;
1209:   case MAT_NEW_DIAGONALS:
1210:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1211:     break;
1212:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1213:     a->donotstash = flg;
1214:     break;
1215:   case MAT_USE_HASH_TABLE:
1216:     a->ht_flag = flg;
1217:     break;
1218:   case MAT_HERMITIAN:
1219:     if (!A->assembled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call MatAssemblyEnd() first");
1220:     MatSetOption(a->A,op,flg);

1222:     A->ops->mult = MatMult_MPISBAIJ_Hermitian;
1223:     break;
1224:   case MAT_SPD:
1225:     A->spd_set = PETSC_TRUE;
1226:     A->spd     = flg;
1227:     if (flg) {
1228:       A->symmetric                  = PETSC_TRUE;
1229:       A->structurally_symmetric     = PETSC_TRUE;
1230:       A->symmetric_set              = PETSC_TRUE;
1231:       A->structurally_symmetric_set = PETSC_TRUE;
1232:     }
1233:     break;
1234:   case MAT_SYMMETRIC:
1235:     MatSetOption(a->A,op,flg);
1236:     break;
1237:   case MAT_STRUCTURALLY_SYMMETRIC:
1238:     MatSetOption(a->A,op,flg);
1239:     break;
1240:   case MAT_SYMMETRY_ETERNAL:
1241:     if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Matrix must be symmetric");
1242:     PetscInfo1(A,"Option %s ignored\n",MatOptions[op]);
1243:     break;
1244:   case MAT_IGNORE_LOWER_TRIANGULAR:
1245:     aA->ignore_ltriangular = flg;
1246:     break;
1247:   case MAT_ERROR_LOWER_TRIANGULAR:
1248:     aA->ignore_ltriangular = flg;
1249:     break;
1250:   case MAT_GETROW_UPPERTRIANGULAR:
1251:     aA->getrow_utriangular = flg;
1252:     break;
1253:   default:
1254:     SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"unknown option %d",op);
1255:   }
1256:   return(0);
1257: }

1261: PetscErrorCode MatTranspose_MPISBAIJ(Mat A,MatReuse reuse,Mat *B)
1262: {

1266:   if (MAT_INITIAL_MATRIX || *B != A) {
1267:     MatDuplicate(A,MAT_COPY_VALUES,B);
1268:   }
1269:   return(0);
1270: }

1274: PetscErrorCode MatDiagonalScale_MPISBAIJ(Mat mat,Vec ll,Vec rr)
1275: {
1276:   Mat_MPISBAIJ   *baij = (Mat_MPISBAIJ*)mat->data;
1277:   Mat            a     = baij->A, b=baij->B;
1279:   PetscInt       nv,m,n;
1280:   PetscBool      flg;

1283:   if (ll != rr) {
1284:     VecEqual(ll,rr,&flg);
1285:     if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"For symmetric format, left and right scaling vectors must be same\n");
1286:   }
1287:   if (!ll) return(0);

1289:   MatGetLocalSize(mat,&m,&n);
1290:   if (m != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"For symmetric format, local size %d %d must be same",m,n);

1292:   VecGetLocalSize(rr,&nv);
1293:   if (nv!=n) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Left and right vector non-conforming local size");

1295:   VecScatterBegin(baij->Mvctx,rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD);

1297:   /* left diagonalscale the off-diagonal part */
1298:   (*b->ops->diagonalscale)(b,ll,NULL);

1300:   /* scale the diagonal part */
1301:   (*a->ops->diagonalscale)(a,ll,rr);

1303:   /* right diagonalscale the off-diagonal part */
1304:   VecScatterEnd(baij->Mvctx,rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD);
1305:   (*b->ops->diagonalscale)(b,NULL,baij->lvec);
1306:   return(0);
1307: }

1311: PetscErrorCode MatSetUnfactored_MPISBAIJ(Mat A)
1312: {
1313:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;

1317:   MatSetUnfactored(a->A);
1318:   return(0);
1319: }

1321: static PetscErrorCode MatDuplicate_MPISBAIJ(Mat,MatDuplicateOption,Mat*);

1325: PetscErrorCode MatEqual_MPISBAIJ(Mat A,Mat B,PetscBool  *flag)
1326: {
1327:   Mat_MPISBAIJ   *matB = (Mat_MPISBAIJ*)B->data,*matA = (Mat_MPISBAIJ*)A->data;
1328:   Mat            a,b,c,d;
1329:   PetscBool      flg;

1333:   a = matA->A; b = matA->B;
1334:   c = matB->A; d = matB->B;

1336:   MatEqual(a,c,&flg);
1337:   if (flg) {
1338:     MatEqual(b,d,&flg);
1339:   }
1340:   MPI_Allreduce(&flg,flag,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1341:   return(0);
1342: }

1346: PetscErrorCode MatCopy_MPISBAIJ(Mat A,Mat B,MatStructure str)
1347: {
1349:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
1350:   Mat_MPISBAIJ   *b = (Mat_MPISBAIJ*)B->data;

1353:   /* If the two matrices don't have the same copy implementation, they aren't compatible for fast copy. */
1354:   if ((str != SAME_NONZERO_PATTERN) || (A->ops->copy != B->ops->copy)) {
1355:     MatGetRowUpperTriangular(A);
1356:     MatCopy_Basic(A,B,str);
1357:     MatRestoreRowUpperTriangular(A);
1358:   } else {
1359:     MatCopy(a->A,b->A,str);
1360:     MatCopy(a->B,b->B,str);
1361:   }
1362:   return(0);
1363: }

1367: PetscErrorCode MatSetUp_MPISBAIJ(Mat A)
1368: {

1372:   MatMPISBAIJSetPreallocation(A,A->rmap->bs,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
1373:   return(0);
1374: }

1378: PetscErrorCode MatAXPY_MPISBAIJ(Mat Y,PetscScalar a,Mat X,MatStructure str)
1379: {
1381:   Mat_MPISBAIJ   *xx=(Mat_MPISBAIJ*)X->data,*yy=(Mat_MPISBAIJ*)Y->data;
1382:   PetscBLASInt   bnz,one=1;
1383:   Mat_SeqSBAIJ   *xa,*ya;
1384:   Mat_SeqBAIJ    *xb,*yb;

1387:   if (str == SAME_NONZERO_PATTERN) {
1388:     PetscScalar alpha = a;
1389:     xa   = (Mat_SeqSBAIJ*)xx->A->data;
1390:     ya   = (Mat_SeqSBAIJ*)yy->A->data;
1391:     PetscBLASIntCast(xa->nz,&bnz);
1392:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,xa->a,&one,ya->a,&one));
1393:     xb   = (Mat_SeqBAIJ*)xx->B->data;
1394:     yb   = (Mat_SeqBAIJ*)yy->B->data;
1395:     PetscBLASIntCast(xb->nz,&bnz);
1396:     PetscStackCallBLAS("BLASaxpy",BLASaxpy_(&bnz,&alpha,xb->a,&one,yb->a,&one));
1397:     PetscObjectStateIncrease((PetscObject)Y);
1398:   } else {
1399:     Mat      B;
1400:     PetscInt *nnz_d,*nnz_o,bs=Y->rmap->bs;
1401:     if (bs != X->rmap->bs) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Matrices must have same block size");
1402:     MatGetRowUpperTriangular(X);
1403:     MatGetRowUpperTriangular(Y);
1404:     PetscMalloc1(yy->A->rmap->N,&nnz_d);
1405:     PetscMalloc1(yy->B->rmap->N,&nnz_o);
1406:     MatCreate(PetscObjectComm((PetscObject)Y),&B);
1407:     PetscObjectSetName((PetscObject)B,((PetscObject)Y)->name);
1408:     MatSetSizes(B,Y->rmap->n,Y->cmap->n,Y->rmap->N,Y->cmap->N);
1409:     MatSetBlockSizesFromMats(B,Y,Y);
1410:     MatSetType(B,MATMPISBAIJ);
1411:     MatAXPYGetPreallocation_SeqSBAIJ(yy->A,xx->A,nnz_d);
1412:     MatAXPYGetPreallocation_MPIBAIJ(yy->B,yy->garray,xx->B,xx->garray,nnz_o);
1413:     MatMPISBAIJSetPreallocation(B,bs,0,nnz_d,0,nnz_o);
1414:     MatAXPY_BasicWithPreallocation(B,Y,a,X,str);
1415:     MatHeaderReplace(Y,B);
1416:     PetscFree(nnz_d);
1417:     PetscFree(nnz_o);
1418:     MatRestoreRowUpperTriangular(X);
1419:     MatRestoreRowUpperTriangular(Y);
1420:   }
1421:   return(0);
1422: }

1426: PetscErrorCode MatGetSubMatrices_MPISBAIJ(Mat A,PetscInt n,const IS irow[],const IS icol[],MatReuse scall,Mat *B[])
1427: {
1429:   PetscInt       i;
1430:   PetscBool      flg;

1433:   for (i=0; i<n; i++) {
1434:     ISEqual(irow[i],icol[i],&flg);
1435:     if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Can only get symmetric submatrix for MPISBAIJ matrices");
1436:   }
1437:   MatGetSubMatrices_MPIBAIJ(A,n,irow,icol,scall,B);
1438:   return(0);
1439: }


1442: /* -------------------------------------------------------------------*/
1443: static struct _MatOps MatOps_Values = {MatSetValues_MPISBAIJ,
1444:                                        MatGetRow_MPISBAIJ,
1445:                                        MatRestoreRow_MPISBAIJ,
1446:                                        MatMult_MPISBAIJ,
1447:                                /*  4*/ MatMultAdd_MPISBAIJ,
1448:                                        MatMult_MPISBAIJ,       /* transpose versions are same as non-transpose */
1449:                                        MatMultAdd_MPISBAIJ,
1450:                                        0,
1451:                                        0,
1452:                                        0,
1453:                                /* 10*/ 0,
1454:                                        0,
1455:                                        0,
1456:                                        MatSOR_MPISBAIJ,
1457:                                        MatTranspose_MPISBAIJ,
1458:                                /* 15*/ MatGetInfo_MPISBAIJ,
1459:                                        MatEqual_MPISBAIJ,
1460:                                        MatGetDiagonal_MPISBAIJ,
1461:                                        MatDiagonalScale_MPISBAIJ,
1462:                                        MatNorm_MPISBAIJ,
1463:                                /* 20*/ MatAssemblyBegin_MPISBAIJ,
1464:                                        MatAssemblyEnd_MPISBAIJ,
1465:                                        MatSetOption_MPISBAIJ,
1466:                                        MatZeroEntries_MPISBAIJ,
1467:                                /* 24*/ 0,
1468:                                        0,
1469:                                        0,
1470:                                        0,
1471:                                        0,
1472:                                /* 29*/ MatSetUp_MPISBAIJ,
1473:                                        0,
1474:                                        0,
1475:                                        0,
1476:                                        0,
1477:                                /* 34*/ MatDuplicate_MPISBAIJ,
1478:                                        0,
1479:                                        0,
1480:                                        0,
1481:                                        0,
1482:                                /* 39*/ MatAXPY_MPISBAIJ,
1483:                                        MatGetSubMatrices_MPISBAIJ,
1484:                                        MatIncreaseOverlap_MPISBAIJ,
1485:                                        MatGetValues_MPISBAIJ,
1486:                                        MatCopy_MPISBAIJ,
1487:                                /* 44*/ 0,
1488:                                        MatScale_MPISBAIJ,
1489:                                        0,
1490:                                        0,
1491:                                        0,
1492:                                /* 49*/ 0,
1493:                                        0,
1494:                                        0,
1495:                                        0,
1496:                                        0,
1497:                                /* 54*/ 0,
1498:                                        0,
1499:                                        MatSetUnfactored_MPISBAIJ,
1500:                                        0,
1501:                                        MatSetValuesBlocked_MPISBAIJ,
1502:                                /* 59*/ 0,
1503:                                        0,
1504:                                        0,
1505:                                        0,
1506:                                        0,
1507:                                /* 64*/ 0,
1508:                                        0,
1509:                                        0,
1510:                                        0,
1511:                                        0,
1512:                                /* 69*/ MatGetRowMaxAbs_MPISBAIJ,
1513:                                        0,
1514:                                        0,
1515:                                        0,
1516:                                        0,
1517:                                /* 74*/ 0,
1518:                                        0,
1519:                                        0,
1520:                                        0,
1521:                                        0,
1522:                                /* 79*/ 0,
1523:                                        0,
1524:                                        0,
1525:                                        0,
1526:                                        MatLoad_MPISBAIJ,
1527:                                /* 84*/ 0,
1528:                                        0,
1529:                                        0,
1530:                                        0,
1531:                                        0,
1532:                                /* 89*/ 0,
1533:                                        0,
1534:                                        0,
1535:                                        0,
1536:                                        0,
1537:                                /* 94*/ 0,
1538:                                        0,
1539:                                        0,
1540:                                        0,
1541:                                        0,
1542:                                /* 99*/ 0,
1543:                                        0,
1544:                                        0,
1545:                                        0,
1546:                                        0,
1547:                                /*104*/ 0,
1548:                                        MatRealPart_MPISBAIJ,
1549:                                        MatImaginaryPart_MPISBAIJ,
1550:                                        MatGetRowUpperTriangular_MPISBAIJ,
1551:                                        MatRestoreRowUpperTriangular_MPISBAIJ,
1552:                                /*109*/ 0,
1553:                                        0,
1554:                                        0,
1555:                                        0,
1556:                                        0,
1557:                                /*114*/ 0,
1558:                                        0,
1559:                                        0,
1560:                                        0,
1561:                                        0,
1562:                                /*119*/ 0,
1563:                                        0,
1564:                                        0,
1565:                                        0,
1566:                                        0,
1567:                                /*124*/ 0,
1568:                                        0,
1569:                                        0,
1570:                                        0,
1571:                                        0,
1572:                                /*129*/ 0,
1573:                                        0,
1574:                                        0,
1575:                                        0,
1576:                                        0,
1577:                                /*134*/ 0,
1578:                                        0,
1579:                                        0,
1580:                                        0,
1581:                                        0,
1582:                                /*139*/ 0,
1583:                                        0,
1584:                                        0
1585: };


1590: PetscErrorCode  MatGetDiagonalBlock_MPISBAIJ(Mat A,Mat *a)
1591: {
1593:   *a = ((Mat_MPISBAIJ*)A->data)->A;
1594:   return(0);
1595: }

1599: PetscErrorCode  MatMPISBAIJSetPreallocation_MPISBAIJ(Mat B,PetscInt bs,PetscInt d_nz,const PetscInt *d_nnz,PetscInt o_nz,const PetscInt *o_nnz)
1600: {
1601:   Mat_MPISBAIJ   *b;
1603:   PetscInt       i,mbs,Mbs;

1606:   MatSetBlockSize(B,PetscAbs(bs));
1607:   PetscLayoutSetUp(B->rmap);
1608:   PetscLayoutSetUp(B->cmap);
1609:   PetscLayoutGetBlockSize(B->rmap,&bs);

1611:   b   = (Mat_MPISBAIJ*)B->data;
1612:   mbs = B->rmap->n/bs;
1613:   Mbs = B->rmap->N/bs;
1614:   if (mbs*bs != B->rmap->n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"No of local rows %D must be divisible by blocksize %D",B->rmap->N,bs);

1616:   B->rmap->bs = bs;
1617:   b->bs2      = bs*bs;
1618:   b->mbs      = mbs;
1619:   b->nbs      = mbs;
1620:   b->Mbs      = Mbs;
1621:   b->Nbs      = Mbs;

1623:   for (i=0; i<=b->size; i++) {
1624:     b->rangebs[i] = B->rmap->range[i]/bs;
1625:   }
1626:   b->rstartbs = B->rmap->rstart/bs;
1627:   b->rendbs   = B->rmap->rend/bs;

1629:   b->cstartbs = B->cmap->rstart/bs;
1630:   b->cendbs   = B->cmap->rend/bs;

1632:   if (!B->preallocated) {
1633:     MatCreate(PETSC_COMM_SELF,&b->A);
1634:     MatSetSizes(b->A,B->rmap->n,B->cmap->n,B->rmap->n,B->cmap->n);
1635:     MatSetType(b->A,MATSEQSBAIJ);
1636:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->A);
1637:     MatCreate(PETSC_COMM_SELF,&b->B);
1638:     MatSetSizes(b->B,B->rmap->n,B->cmap->N,B->rmap->n,B->cmap->N);
1639:     MatSetType(b->B,MATSEQBAIJ);
1640:     PetscLogObjectParent((PetscObject)B,(PetscObject)b->B);
1641:     MatStashCreate_Private(PetscObjectComm((PetscObject)B),bs,&B->bstash);
1642:   }

1644:   MatSeqSBAIJSetPreallocation(b->A,bs,d_nz,d_nnz);
1645:   MatSeqBAIJSetPreallocation(b->B,bs,o_nz,o_nnz);

1647:   B->preallocated = PETSC_TRUE;
1648:   return(0);
1649: }

1653: PetscErrorCode MatMPISBAIJSetPreallocationCSR_MPISBAIJ(Mat B,PetscInt bs,const PetscInt ii[],const PetscInt jj[],const PetscScalar V[])
1654: {
1655:   PetscInt       m,rstart,cstart,cend;
1656:   PetscInt       i,j,d,nz,nz_max=0,*d_nnz=0,*o_nnz=0;
1657:   const PetscInt *JJ    =0;
1658:   PetscScalar    *values=0;

1662:   if (bs < 1) SETERRQ1(PetscObjectComm((PetscObject)B),PETSC_ERR_ARG_OUTOFRANGE,"Invalid block size specified, must be positive but it is %D",bs);
1663:   PetscLayoutSetBlockSize(B->rmap,bs);
1664:   PetscLayoutSetBlockSize(B->cmap,bs);
1665:   PetscLayoutSetUp(B->rmap);
1666:   PetscLayoutSetUp(B->cmap);
1667:   PetscLayoutGetBlockSize(B->rmap,&bs);
1668:   m      = B->rmap->n/bs;
1669:   rstart = B->rmap->rstart/bs;
1670:   cstart = B->cmap->rstart/bs;
1671:   cend   = B->cmap->rend/bs;

1673:   if (ii[0]) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"ii[0] must be 0 but it is %D",ii[0]);
1674:   PetscMalloc2(m,&d_nnz,m,&o_nnz);
1675:   for (i=0; i<m; i++) {
1676:     nz = ii[i+1] - ii[i];
1677:     if (nz < 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Local row %D has a negative number of columns %D",i,nz);
1678:     nz_max = PetscMax(nz_max,nz);
1679:     JJ     = jj + ii[i];
1680:     for (j=0; j<nz; j++) {
1681:       if (*JJ >= cstart) break;
1682:       JJ++;
1683:     }
1684:     d = 0;
1685:     for (; j<nz; j++) {
1686:       if (*JJ++ >= cend) break;
1687:       d++;
1688:     }
1689:     d_nnz[i] = d;
1690:     o_nnz[i] = nz - d;
1691:   }
1692:   MatMPISBAIJSetPreallocation(B,bs,0,d_nnz,0,o_nnz);
1693:   PetscFree2(d_nnz,o_nnz);

1695:   values = (PetscScalar*)V;
1696:   if (!values) {
1697:     PetscMalloc1(bs*bs*nz_max,&values);
1698:     PetscMemzero(values,bs*bs*nz_max*sizeof(PetscScalar));
1699:   }
1700:   for (i=0; i<m; i++) {
1701:     PetscInt          row    = i + rstart;
1702:     PetscInt          ncols  = ii[i+1] - ii[i];
1703:     const PetscInt    *icols = jj + ii[i];
1704:     const PetscScalar *svals = values + (V ? (bs*bs*ii[i]) : 0);
1705:     MatSetValuesBlocked_MPISBAIJ(B,1,&row,ncols,icols,svals,INSERT_VALUES);
1706:   }

1708:   if (!V) { PetscFree(values); }
1709:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1710:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1711:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
1712:   return(0);
1713: }

1715: #if defined(PETSC_HAVE_MUMPS)
1716: PETSC_EXTERN PetscErrorCode MatGetFactor_sbaij_mumps(Mat,MatFactorType,Mat*);
1717: #endif
1718: #if defined(PETSC_HAVE_PASTIX)
1719: PETSC_EXTERN PetscErrorCode MatGetFactor_mpisbaij_pastix(Mat,MatFactorType,Mat*);
1720: #endif

1722: /*MC
1723:    MATMPISBAIJ - MATMPISBAIJ = "mpisbaij" - A matrix type to be used for distributed symmetric sparse block matrices,
1724:    based on block compressed sparse row format.  Only the upper triangular portion of the "diagonal" portion of
1725:    the matrix is stored.

1727:   For complex numbers by default this matrix is symmetric, NOT Hermitian symmetric. To make it Hermitian symmetric you
1728:   can call MatSetOption(Mat, MAT_HERMITIAN);

1730:    Options Database Keys:
1731: . -mat_type mpisbaij - sets the matrix type to "mpisbaij" during a call to MatSetFromOptions()

1733:   Level: beginner

1735: .seealso: MatCreateMPISBAIJ
1736: M*/

1738: PETSC_EXTERN PetscErrorCode MatConvert_MPISBAIJ_MPISBSTRM(Mat,MatType,MatReuse,Mat*);

1742: PETSC_EXTERN PetscErrorCode MatCreate_MPISBAIJ(Mat B)
1743: {
1744:   Mat_MPISBAIJ   *b;
1746:   PetscBool      flg;

1749:   PetscNewLog(B,&b);
1750:   B->data = (void*)b;
1751:   PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));

1753:   B->ops->destroy = MatDestroy_MPISBAIJ;
1754:   B->ops->view    = MatView_MPISBAIJ;
1755:   B->assembled    = PETSC_FALSE;
1756:   B->insertmode   = NOT_SET_VALUES;

1758:   MPI_Comm_rank(PetscObjectComm((PetscObject)B),&b->rank);
1759:   MPI_Comm_size(PetscObjectComm((PetscObject)B),&b->size);

1761:   /* build local table of row and column ownerships */
1762:   PetscMalloc1((b->size+2),&b->rangebs);

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

1767:   b->donotstash  = PETSC_FALSE;
1768:   b->colmap      = NULL;
1769:   b->garray      = NULL;
1770:   b->roworiented = PETSC_TRUE;

1772:   /* stuff used in block assembly */
1773:   b->barray = 0;

1775:   /* stuff used for matrix vector multiply */
1776:   b->lvec    = 0;
1777:   b->Mvctx   = 0;
1778:   b->slvec0  = 0;
1779:   b->slvec0b = 0;
1780:   b->slvec1  = 0;
1781:   b->slvec1a = 0;
1782:   b->slvec1b = 0;
1783:   b->sMvctx  = 0;

1785:   /* stuff for MatGetRow() */
1786:   b->rowindices   = 0;
1787:   b->rowvalues    = 0;
1788:   b->getrowactive = PETSC_FALSE;

1790:   /* hash table stuff */
1791:   b->ht           = 0;
1792:   b->hd           = 0;
1793:   b->ht_size      = 0;
1794:   b->ht_flag      = PETSC_FALSE;
1795:   b->ht_fact      = 0;
1796:   b->ht_total_ct  = 0;
1797:   b->ht_insert_ct = 0;

1799:   /* stuff for MatGetSubMatrices_MPIBAIJ_local() */
1800:   b->ijonly = PETSC_FALSE;

1802:   b->in_loc = 0;
1803:   b->v_loc  = 0;
1804:   b->n_loc  = 0;
1805:   PetscOptionsBegin(PetscObjectComm((PetscObject)B),NULL,"Options for loading MPISBAIJ matrix 1","Mat");
1806:   PetscOptionsBool("-mat_use_hash_table","Use hash table to save memory in constructing matrix","MatSetOption",PETSC_FALSE,&flg,NULL);
1807:   if (flg) {
1808:     PetscReal fact = 1.39;
1809:     MatSetOption(B,MAT_USE_HASH_TABLE,PETSC_TRUE);
1810:     PetscOptionsReal("-mat_use_hash_table","Use hash table factor","MatMPIBAIJSetHashTableFactor",fact,&fact,NULL);
1811:     if (fact <= 1.0) fact = 1.39;
1812:     MatMPIBAIJSetHashTableFactor(B,fact);
1813:     PetscInfo1(B,"Hash table Factor used %5.2f\n",fact);
1814:   }
1815:   PetscOptionsEnd();

1817: #if defined(PETSC_HAVE_PASTIX)
1818:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_pastix_C",MatGetFactor_mpisbaij_pastix);
1819: #endif
1820: #if defined(PETSC_HAVE_MUMPS)
1821:   PetscObjectComposeFunction((PetscObject)B,"MatGetFactor_mumps_C",MatGetFactor_sbaij_mumps);
1822: #endif
1823:   PetscObjectComposeFunction((PetscObject)B,"MatStoreValues_C",MatStoreValues_MPISBAIJ);
1824:   PetscObjectComposeFunction((PetscObject)B,"MatRetrieveValues_C",MatRetrieveValues_MPISBAIJ);
1825:   PetscObjectComposeFunction((PetscObject)B,"MatGetDiagonalBlock_C",MatGetDiagonalBlock_MPISBAIJ);
1826:   PetscObjectComposeFunction((PetscObject)B,"MatMPISBAIJSetPreallocation_C",MatMPISBAIJSetPreallocation_MPISBAIJ);
1827:   PetscObjectComposeFunction((PetscObject)B,"MatMPISBAIJSetPreallocationCSR_C",MatMPISBAIJSetPreallocationCSR_MPISBAIJ);
1828:   PetscObjectComposeFunction((PetscObject)B,"MatConvert_mpisbaij_mpisbstrm_C",MatConvert_MPISBAIJ_MPISBSTRM);

1830:   B->symmetric                  = PETSC_TRUE;
1831:   B->structurally_symmetric     = PETSC_TRUE;
1832:   B->symmetric_set              = PETSC_TRUE;
1833:   B->structurally_symmetric_set = PETSC_TRUE;

1835:   PetscObjectChangeTypeName((PetscObject)B,MATMPISBAIJ);
1836:   return(0);
1837: }

1839: /*MC
1840:    MATSBAIJ - MATSBAIJ = "sbaij" - A matrix type to be used for symmetric block sparse matrices.

1842:    This matrix type is identical to MATSEQSBAIJ when constructed with a single process communicator,
1843:    and MATMPISBAIJ otherwise.

1845:    Options Database Keys:
1846: . -mat_type sbaij - sets the matrix type to "sbaij" during a call to MatSetFromOptions()

1848:   Level: beginner

1850: .seealso: MatCreateMPISBAIJ,MATSEQSBAIJ,MATMPISBAIJ
1851: M*/

1855: /*@C
1856:    MatMPISBAIJSetPreallocation - For good matrix assembly performance
1857:    the user should preallocate the matrix storage by setting the parameters
1858:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
1859:    performance can be increased by more than a factor of 50.

1861:    Collective on Mat

1863:    Input Parameters:
1864: +  B - the matrix
1865: .  bs   - size of blockk
1866: .  d_nz  - number of block nonzeros per block row in diagonal portion of local
1867:            submatrix  (same for all local rows)
1868: .  d_nnz - array containing the number of block nonzeros in the various block rows
1869:            in the upper triangular and diagonal part of the in diagonal portion of the local
1870:            (possibly different for each block row) or NULL.  If you plan to factor the matrix you must leave room
1871:            for the diagonal entry and set a value even if it is zero.
1872: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1873:            submatrix (same for all local rows).
1874: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1875:            off-diagonal portion of the local submatrix that is right of the diagonal
1876:            (possibly different for each block row) or NULL.


1879:    Options Database Keys:
1880: .   -mat_no_unroll - uses code that does not unroll the loops in the
1881:                      block calculations (much slower)
1882: .   -mat_block_size - size of the blocks to use

1884:    Notes:

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

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

1891:    Storage Information:
1892:    For a square global matrix we define each processor's diagonal portion
1893:    to be its local rows and the corresponding columns (a square submatrix);
1894:    each processor's off-diagonal portion encompasses the remainder of the
1895:    local matrix (a rectangular submatrix).

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

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

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

1911: .vb
1912:            0 1 2 3 4 5 6 7 8 9 10 11
1913:           --------------------------
1914:    row 3  |. . . d d d o o o o  o  o
1915:    row 4  |. . . d d d o o o o  o  o
1916:    row 5  |. . . d d d o o o o  o  o
1917:           --------------------------
1918: .ve

1920:    Thus, any entries in the d locations are stored in the d (diagonal)
1921:    submatrix, and any entries in the o locations are stored in the
1922:    o (off-diagonal) submatrix.  Note that the d matrix is stored in
1923:    MatSeqSBAIJ format and the o submatrix in MATSEQBAIJ format.

1925:    Now d_nz should indicate the number of block nonzeros per row in the upper triangular
1926:    plus the diagonal part of the d matrix,
1927:    and o_nz should indicate the number of block nonzeros per row in the o matrix

1929:    In general, for PDE problems in which most nonzeros are near the diagonal,
1930:    one expects d_nz >> o_nz.   For large problems you MUST preallocate memory
1931:    or you will get TERRIBLE performance; see the users' manual chapter on
1932:    matrices.

1934:    Level: intermediate

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

1938: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateBAIJ(), PetscSplitOwnership()
1939: @*/
1940: PetscErrorCode  MatMPISBAIJSetPreallocation(Mat B,PetscInt bs,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
1941: {

1948:   PetscTryMethod(B,"MatMPISBAIJSetPreallocation_C",(Mat,PetscInt,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,bs,d_nz,d_nnz,o_nz,o_nnz));
1949:   return(0);
1950: }

1954: /*@C
1955:    MatCreateSBAIJ - Creates a sparse parallel matrix in symmetric block AIJ format
1956:    (block compressed row).  For good matrix assembly performance
1957:    the user should preallocate the matrix storage by setting the parameters
1958:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
1959:    performance can be increased by more than a factor of 50.

1961:    Collective on MPI_Comm

1963:    Input Parameters:
1964: +  comm - MPI communicator
1965: .  bs   - size of blockk
1966: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
1967:            This value should be the same as the local size used in creating the
1968:            y vector for the matrix-vector product y = Ax.
1969: .  n - number of local columns (or PETSC_DECIDE to have calculated if N is given)
1970:            This value should be the same as the local size used in creating the
1971:            x vector for the matrix-vector product y = Ax.
1972: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
1973: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
1974: .  d_nz  - number of block nonzeros per block row in diagonal portion of local
1975:            submatrix  (same for all local rows)
1976: .  d_nnz - array containing the number of block nonzeros in the various block rows
1977:            in the upper triangular portion of the in diagonal portion of the local
1978:            (possibly different for each block block row) or NULL.
1979:            If you plan to factor the matrix you must leave room for the diagonal entry and
1980:            set its value even if it is zero.
1981: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1982:            submatrix (same for all local rows).
1983: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1984:            off-diagonal portion of the local submatrix (possibly different for
1985:            each block row) or NULL.

1987:    Output Parameter:
1988: .  A - the matrix

1990:    Options Database Keys:
1991: .   -mat_no_unroll - uses code that does not unroll the loops in the
1992:                      block calculations (much slower)
1993: .   -mat_block_size - size of the blocks to use
1994: .   -mat_mpi - use the parallel matrix data structures even on one processor
1995:                (defaults to using SeqBAIJ format on one processor)

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

2001:    Notes:
2002:    The number of rows and columns must be divisible by blocksize.
2003:    This matrix type does not support complex Hermitian operation.

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

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

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

2013:    Storage Information:
2014:    For a square global matrix we define each processor's diagonal portion
2015:    to be its local rows and the corresponding columns (a square submatrix);
2016:    each processor's off-diagonal portion encompasses the remainder of the
2017:    local matrix (a rectangular submatrix).

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

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

2028: .vb
2029:            0 1 2 3 4 5 6 7 8 9 10 11
2030:           --------------------------
2031:    row 3  |. . . d d d o o o o  o  o
2032:    row 4  |. . . d d d o o o o  o  o
2033:    row 5  |. . . d d d o o o o  o  o
2034:           --------------------------
2035: .ve

2037:    Thus, any entries in the d locations are stored in the d (diagonal)
2038:    submatrix, and any entries in the o locations are stored in the
2039:    o (off-diagonal) submatrix.  Note that the d matrix is stored in
2040:    MatSeqSBAIJ format and the o submatrix in MATSEQBAIJ format.

2042:    Now d_nz should indicate the number of block nonzeros per row in the upper triangular
2043:    plus the diagonal part of the d matrix,
2044:    and o_nz should indicate the number of block nonzeros per row in the o matrix.
2045:    In general, for PDE problems in which most nonzeros are near the diagonal,
2046:    one expects d_nz >> o_nz.   For large problems you MUST preallocate memory
2047:    or you will get TERRIBLE performance; see the users' manual chapter on
2048:    matrices.

2050:    Level: intermediate

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

2054: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateBAIJ()
2055: @*/

2057: PetscErrorCode  MatCreateSBAIJ(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)
2058: {
2060:   PetscMPIInt    size;

2063:   MatCreate(comm,A);
2064:   MatSetSizes(*A,m,n,M,N);
2065:   MPI_Comm_size(comm,&size);
2066:   if (size > 1) {
2067:     MatSetType(*A,MATMPISBAIJ);
2068:     MatMPISBAIJSetPreallocation(*A,bs,d_nz,d_nnz,o_nz,o_nnz);
2069:   } else {
2070:     MatSetType(*A,MATSEQSBAIJ);
2071:     MatSeqSBAIJSetPreallocation(*A,bs,d_nz,d_nnz);
2072:   }
2073:   return(0);
2074: }


2079: static PetscErrorCode MatDuplicate_MPISBAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
2080: {
2081:   Mat            mat;
2082:   Mat_MPISBAIJ   *a,*oldmat = (Mat_MPISBAIJ*)matin->data;
2084:   PetscInt       len=0,nt,bs=matin->rmap->bs,mbs=oldmat->mbs;
2085:   PetscScalar    *array;

2088:   *newmat = 0;

2090:   MatCreate(PetscObjectComm((PetscObject)matin),&mat);
2091:   MatSetSizes(mat,matin->rmap->n,matin->cmap->n,matin->rmap->N,matin->cmap->N);
2092:   MatSetType(mat,((PetscObject)matin)->type_name);
2093:   PetscMemcpy(mat->ops,matin->ops,sizeof(struct _MatOps));
2094:   PetscLayoutReference(matin->rmap,&mat->rmap);
2095:   PetscLayoutReference(matin->cmap,&mat->cmap);

2097:   mat->factortype   = matin->factortype;
2098:   mat->preallocated = PETSC_TRUE;
2099:   mat->assembled    = PETSC_TRUE;
2100:   mat->insertmode   = NOT_SET_VALUES;

2102:   a      = (Mat_MPISBAIJ*)mat->data;
2103:   a->bs2 = oldmat->bs2;
2104:   a->mbs = oldmat->mbs;
2105:   a->nbs = oldmat->nbs;
2106:   a->Mbs = oldmat->Mbs;
2107:   a->Nbs = oldmat->Nbs;


2110:   a->size         = oldmat->size;
2111:   a->rank         = oldmat->rank;
2112:   a->donotstash   = oldmat->donotstash;
2113:   a->roworiented  = oldmat->roworiented;
2114:   a->rowindices   = 0;
2115:   a->rowvalues    = 0;
2116:   a->getrowactive = PETSC_FALSE;
2117:   a->barray       = 0;
2118:   a->rstartbs     = oldmat->rstartbs;
2119:   a->rendbs       = oldmat->rendbs;
2120:   a->cstartbs     = oldmat->cstartbs;
2121:   a->cendbs       = oldmat->cendbs;

2123:   /* hash table stuff */
2124:   a->ht           = 0;
2125:   a->hd           = 0;
2126:   a->ht_size      = 0;
2127:   a->ht_flag      = oldmat->ht_flag;
2128:   a->ht_fact      = oldmat->ht_fact;
2129:   a->ht_total_ct  = 0;
2130:   a->ht_insert_ct = 0;

2132:   PetscMemcpy(a->rangebs,oldmat->rangebs,(a->size+2)*sizeof(PetscInt));
2133:   if (oldmat->colmap) {
2134: #if defined(PETSC_USE_CTABLE)
2135:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
2136: #else
2137:     PetscMalloc1((a->Nbs),&a->colmap);
2138:     PetscLogObjectMemory((PetscObject)mat,(a->Nbs)*sizeof(PetscInt));
2139:     PetscMemcpy(a->colmap,oldmat->colmap,(a->Nbs)*sizeof(PetscInt));
2140: #endif
2141:   } else a->colmap = 0;

2143:   if (oldmat->garray && (len = ((Mat_SeqBAIJ*)(oldmat->B->data))->nbs)) {
2144:     PetscMalloc1(len,&a->garray);
2145:     PetscLogObjectMemory((PetscObject)mat,len*sizeof(PetscInt));
2146:     PetscMemcpy(a->garray,oldmat->garray,len*sizeof(PetscInt));
2147:   } else a->garray = 0;

2149:   MatStashCreate_Private(PetscObjectComm((PetscObject)matin),matin->rmap->bs,&mat->bstash);
2150:   VecDuplicate(oldmat->lvec,&a->lvec);
2151:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->lvec);
2152:   VecScatterCopy(oldmat->Mvctx,&a->Mvctx);
2153:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->Mvctx);

2155:    VecDuplicate(oldmat->slvec0,&a->slvec0);
2156:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec0);
2157:    VecDuplicate(oldmat->slvec1,&a->slvec1);
2158:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec1);

2160:   VecGetLocalSize(a->slvec1,&nt);
2161:   VecGetArray(a->slvec1,&array);
2162:   VecCreateSeqWithArray(PETSC_COMM_SELF,1,bs*mbs,array,&a->slvec1a);
2163:   VecCreateSeqWithArray(PETSC_COMM_SELF,1,nt-bs*mbs,array+bs*mbs,&a->slvec1b);
2164:   VecRestoreArray(a->slvec1,&array);
2165:   VecGetArray(a->slvec0,&array);
2166:   VecCreateSeqWithArray(PETSC_COMM_SELF,1,nt-bs*mbs,array+bs*mbs,&a->slvec0b);
2167:   VecRestoreArray(a->slvec0,&array);
2168:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec0);
2169:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec1);
2170:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec0b);
2171:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec1a);
2172:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->slvec1b);

2174:   /*  VecScatterCopy(oldmat->sMvctx,&a->sMvctx); - not written yet, replaced by the lazy trick: */
2175:   PetscObjectReference((PetscObject)oldmat->sMvctx);
2176:   a->sMvctx = oldmat->sMvctx;
2177:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->sMvctx);

2179:    MatDuplicate(oldmat->A,cpvalues,&a->A);
2180:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->A);
2181:    MatDuplicate(oldmat->B,cpvalues,&a->B);
2182:   PetscLogObjectParent((PetscObject)mat,(PetscObject)a->B);
2183:   PetscFunctionListDuplicate(((PetscObject)matin)->qlist,&((PetscObject)mat)->qlist);
2184:   *newmat = mat;
2185:   return(0);
2186: }

2190: PetscErrorCode MatLoad_MPISBAIJ(Mat newmat,PetscViewer viewer)
2191: {
2193:   PetscInt       i,nz,j,rstart,rend;
2194:   PetscScalar    *vals,*buf;
2195:   MPI_Comm       comm;
2196:   MPI_Status     status;
2197:   PetscMPIInt    rank,size,tag = ((PetscObject)viewer)->tag,*sndcounts = 0,*browners,maxnz,*rowners,mmbs;
2198:   PetscInt       header[4],*rowlengths = 0,M,N,m,*cols,*locrowlens;
2199:   PetscInt       *procsnz = 0,jj,*mycols,*ibuf;
2200:   PetscInt       bs       =1,Mbs,mbs,extra_rows;
2201:   PetscInt       *dlens,*odlens,*mask,*masked1,*masked2,rowcount,odcount;
2202:   PetscInt       dcount,kmax,k,nzcount,tmp,sizesset=1,grows,gcols;
2203:   int            fd;

2206:   PetscObjectGetComm((PetscObject)viewer,&comm);
2207:   PetscOptionsBegin(comm,NULL,"Options for loading MPISBAIJ matrix 2","Mat");
2208:   PetscOptionsInt("-matload_block_size","Set the blocksize used to store the matrix","MatLoad",bs,&bs,NULL);
2209:   PetscOptionsEnd();

2211:   MPI_Comm_size(comm,&size);
2212:   MPI_Comm_rank(comm,&rank);
2213:   if (!rank) {
2214:     PetscViewerBinaryGetDescriptor(viewer,&fd);
2215:     PetscBinaryRead(fd,(char*)header,4,PETSC_INT);
2216:     if (header[0] != MAT_FILE_CLASSID) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
2217:     if (header[3] < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format, cannot load as MPISBAIJ");
2218:   }

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

2222:   MPI_Bcast(header+1,3,MPIU_INT,0,comm);
2223:   M    = header[1];
2224:   N    = header[2];

2226:   /* If global rows/cols are set to PETSC_DECIDE, set it to the sizes given in the file */
2227:   if (sizesset && newmat->rmap->N < 0) newmat->rmap->N = M;
2228:   if (sizesset && newmat->cmap->N < 0) newmat->cmap->N = N;

2230:   /* If global sizes are set, check if they are consistent with that given in the file */
2231:   if (sizesset) {
2232:     MatGetSize(newmat,&grows,&gcols);
2233:   }
2234:   if (sizesset && newmat->rmap->N != grows) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of rows:Matrix in file has (%d) and input matrix has (%d)",M,grows);
2235:   if (sizesset && newmat->cmap->N != gcols) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED, "Inconsistent # of cols:Matrix in file has (%d) and input matrix has (%d)",N,gcols);

2237:   if (M != N) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Can only do square matrices");

2239:   /*
2240:      This code adds extra rows to make sure the number of rows is
2241:      divisible by the blocksize
2242:   */
2243:   Mbs        = M/bs;
2244:   extra_rows = bs - M + bs*(Mbs);
2245:   if (extra_rows == bs) extra_rows = 0;
2246:   else                  Mbs++;
2247:   if (extra_rows &&!rank) {
2248:     PetscInfo(viewer,"Padding loaded matrix to match blocksize\n");
2249:   }

2251:   /* determine ownership of all rows */
2252:   if (newmat->rmap->n < 0) { /* PETSC_DECIDE */
2253:     mbs = Mbs/size + ((Mbs % size) > rank);
2254:     m   = mbs*bs;
2255:   } else { /* User Set */
2256:     m   = newmat->rmap->n;
2257:     mbs = m/bs;
2258:   }
2259:   PetscMalloc2(size+1,&rowners,size+1,&browners);
2260:   PetscMPIIntCast(mbs,&mmbs);
2261:   MPI_Allgather(&mmbs,1,MPI_INT,rowners+1,1,MPI_INT,comm);
2262:   rowners[0] = 0;
2263:   for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
2264:   for (i=0; i<=size; i++) browners[i] = rowners[i]*bs;
2265:   rstart = rowners[rank];
2266:   rend   = rowners[rank+1];

2268:   /* distribute row lengths to all processors */
2269:   PetscMalloc1((rend-rstart)*bs,&locrowlens);
2270:   if (!rank) {
2271:     PetscMalloc1((M+extra_rows),&rowlengths);
2272:     PetscBinaryRead(fd,rowlengths,M,PETSC_INT);
2273:     for (i=0; i<extra_rows; i++) rowlengths[M+i] = 1;
2274:     PetscMalloc1(size,&sndcounts);
2275:     for (i=0; i<size; i++) sndcounts[i] = browners[i+1] - browners[i];
2276:     MPI_Scatterv(rowlengths,sndcounts,browners,MPIU_INT,locrowlens,(rend-rstart)*bs,MPIU_INT,0,comm);
2277:     PetscFree(sndcounts);
2278:   } else {
2279:     MPI_Scatterv(0,0,0,MPIU_INT,locrowlens,(rend-rstart)*bs,MPIU_INT,0,comm);
2280:   }

2282:   if (!rank) {   /* procs[0] */
2283:     /* calculate the number of nonzeros on each processor */
2284:     PetscMalloc1(size,&procsnz);
2285:     PetscMemzero(procsnz,size*sizeof(PetscInt));
2286:     for (i=0; i<size; i++) {
2287:       for (j=rowners[i]*bs; j< rowners[i+1]*bs; j++) {
2288:         procsnz[i] += rowlengths[j];
2289:       }
2290:     }
2291:     PetscFree(rowlengths);

2293:     /* determine max buffer needed and allocate it */
2294:     maxnz = 0;
2295:     for (i=0; i<size; i++) {
2296:       maxnz = PetscMax(maxnz,procsnz[i]);
2297:     }
2298:     PetscMalloc1(maxnz,&cols);

2300:     /* read in my part of the matrix column indices  */
2301:     nz     = procsnz[0];
2302:     PetscMalloc1(nz,&ibuf);
2303:     mycols = ibuf;
2304:     if (size == 1) nz -= extra_rows;
2305:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);
2306:     if (size == 1) {
2307:       for (i=0; i< extra_rows; i++) mycols[nz+i] = M+i;
2308:     }

2310:     /* read in every ones (except the last) and ship off */
2311:     for (i=1; i<size-1; i++) {
2312:       nz   = procsnz[i];
2313:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
2314:       MPI_Send(cols,nz,MPIU_INT,i,tag,comm);
2315:     }
2316:     /* read in the stuff for the last proc */
2317:     if (size != 1) {
2318:       nz   = procsnz[size-1] - extra_rows;  /* the extra rows are not on the disk */
2319:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
2320:       for (i=0; i<extra_rows; i++) cols[nz+i] = M+i;
2321:       MPI_Send(cols,nz+extra_rows,MPIU_INT,size-1,tag,comm);
2322:     }
2323:     PetscFree(cols);
2324:   } else {  /* procs[i], i>0 */
2325:     /* determine buffer space needed for message */
2326:     nz = 0;
2327:     for (i=0; i<m; i++) nz += locrowlens[i];
2328:     PetscMalloc1(nz,&ibuf);
2329:     mycols = ibuf;
2330:     /* receive message of column indices*/
2331:     MPI_Recv(mycols,nz,MPIU_INT,0,tag,comm,&status);
2332:     MPI_Get_count(&status,MPIU_INT,&maxnz);
2333:     if (maxnz != nz) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");
2334:   }

2336:   /* loop over local rows, determining number of off diagonal entries */
2337:   PetscMalloc2(rend-rstart,&dlens,rend-rstart,&odlens);
2338:   PetscMalloc3(Mbs,&mask,Mbs,&masked1,Mbs,&masked2);
2339:   PetscMemzero(mask,Mbs*sizeof(PetscInt));
2340:   PetscMemzero(masked1,Mbs*sizeof(PetscInt));
2341:   PetscMemzero(masked2,Mbs*sizeof(PetscInt));
2342:   rowcount = 0;
2343:   nzcount  = 0;
2344:   for (i=0; i<mbs; i++) {
2345:     dcount  = 0;
2346:     odcount = 0;
2347:     for (j=0; j<bs; j++) {
2348:       kmax = locrowlens[rowcount];
2349:       for (k=0; k<kmax; k++) {
2350:         tmp = mycols[nzcount++]/bs; /* block col. index */
2351:         if (!mask[tmp]) {
2352:           mask[tmp] = 1;
2353:           if (tmp < rstart || tmp >= rend) masked2[odcount++] = tmp; /* entry in off-diag portion */
2354:           else masked1[dcount++] = tmp; /* entry in diag portion */
2355:         }
2356:       }
2357:       rowcount++;
2358:     }

2360:     dlens[i]  = dcount;  /* d_nzz[i] */
2361:     odlens[i] = odcount; /* o_nzz[i] */

2363:     /* zero out the mask elements we set */
2364:     for (j=0; j<dcount; j++) mask[masked1[j]] = 0;
2365:     for (j=0; j<odcount; j++) mask[masked2[j]] = 0;
2366:   }
2367:   if (!sizesset) {
2368:     MatSetSizes(newmat,m,m,M+extra_rows,N+extra_rows);
2369:   }
2370:   MatMPISBAIJSetPreallocation(newmat,bs,0,dlens,0,odlens);
2371:   MatSetOption(newmat,MAT_IGNORE_LOWER_TRIANGULAR,PETSC_TRUE);

2373:   if (!rank) {
2374:     PetscMalloc1(maxnz,&buf);
2375:     /* read in my part of the matrix numerical values  */
2376:     nz     = procsnz[0];
2377:     vals   = buf;
2378:     mycols = ibuf;
2379:     if (size == 1) nz -= extra_rows;
2380:     PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2381:     if (size == 1) {
2382:       for (i=0; i< extra_rows; i++) vals[nz+i] = 1.0;
2383:     }

2385:     /* insert into matrix */
2386:     jj = rstart*bs;
2387:     for (i=0; i<m; i++) {
2388:       MatSetValues(newmat,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2389:       mycols += locrowlens[i];
2390:       vals   += locrowlens[i];
2391:       jj++;
2392:     }

2394:     /* read in other processors (except the last one) and ship out */
2395:     for (i=1; i<size-1; i++) {
2396:       nz   = procsnz[i];
2397:       vals = buf;
2398:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2399:       MPI_Send(vals,nz,MPIU_SCALAR,i,((PetscObject)newmat)->tag,comm);
2400:     }
2401:     /* the last proc */
2402:     if (size != 1) {
2403:       nz   = procsnz[i] - extra_rows;
2404:       vals = buf;
2405:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2406:       for (i=0; i<extra_rows; i++) vals[nz+i] = 1.0;
2407:       MPI_Send(vals,nz+extra_rows,MPIU_SCALAR,size-1,((PetscObject)newmat)->tag,comm);
2408:     }
2409:     PetscFree(procsnz);

2411:   } else {
2412:     /* receive numeric values */
2413:     PetscMalloc1(nz,&buf);

2415:     /* receive message of values*/
2416:     vals   = buf;
2417:     mycols = ibuf;
2418:     MPI_Recv(vals,nz,MPIU_SCALAR,0,((PetscObject)newmat)->tag,comm,&status);
2419:     MPI_Get_count(&status,MPIU_SCALAR,&maxnz);
2420:     if (maxnz != nz) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");

2422:     /* insert into matrix */
2423:     jj = rstart*bs;
2424:     for (i=0; i<m; i++) {
2425:       MatSetValues_MPISBAIJ(newmat,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2426:       mycols += locrowlens[i];
2427:       vals   += locrowlens[i];
2428:       jj++;
2429:     }
2430:   }

2432:   PetscFree(locrowlens);
2433:   PetscFree(buf);
2434:   PetscFree(ibuf);
2435:   PetscFree2(rowners,browners);
2436:   PetscFree2(dlens,odlens);
2437:   PetscFree3(mask,masked1,masked2);
2438:   MatAssemblyBegin(newmat,MAT_FINAL_ASSEMBLY);
2439:   MatAssemblyEnd(newmat,MAT_FINAL_ASSEMBLY);
2440:   return(0);
2441: }

2445: /*XXXXX@
2446:    MatMPISBAIJSetHashTableFactor - Sets the factor required to compute the size of the HashTable.

2448:    Input Parameters:
2449: .  mat  - the matrix
2450: .  fact - factor

2452:    Not Collective on Mat, each process can have a different hash factor

2454:    Level: advanced

2456:   Notes:
2457:    This can also be set by the command line option: -mat_use_hash_table fact

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

2461: .seealso: MatSetOption()
2462: @XXXXX*/


2467: PetscErrorCode MatGetRowMaxAbs_MPISBAIJ(Mat A,Vec v,PetscInt idx[])
2468: {
2469:   Mat_MPISBAIJ   *a = (Mat_MPISBAIJ*)A->data;
2470:   Mat_SeqBAIJ    *b = (Mat_SeqBAIJ*)(a->B)->data;
2471:   PetscReal      atmp;
2472:   PetscReal      *work,*svalues,*rvalues;
2474:   PetscInt       i,bs,mbs,*bi,*bj,brow,j,ncols,krow,kcol,col,row,Mbs,bcol;
2475:   PetscMPIInt    rank,size;
2476:   PetscInt       *rowners_bs,dest,count,source;
2477:   PetscScalar    *va;
2478:   MatScalar      *ba;
2479:   MPI_Status     stat;

2482:   if (idx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Send email to petsc-maint@mcs.anl.gov");
2483:   MatGetRowMaxAbs(a->A,v,NULL);
2484:   VecGetArray(v,&va);

2486:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
2487:   MPI_Comm_rank(PetscObjectComm((PetscObject)A),&rank);

2489:   bs  = A->rmap->bs;
2490:   mbs = a->mbs;
2491:   Mbs = a->Mbs;
2492:   ba  = b->a;
2493:   bi  = b->i;
2494:   bj  = b->j;

2496:   /* find ownerships */
2497:   rowners_bs = A->rmap->range;

2499:   /* each proc creates an array to be distributed */
2500:   PetscMalloc1(bs*Mbs,&work);
2501:   PetscMemzero(work,bs*Mbs*sizeof(PetscReal));

2503:   /* row_max for B */
2504:   if (rank != size-1) {
2505:     for (i=0; i<mbs; i++) {
2506:       ncols = bi[1] - bi[0]; bi++;
2507:       brow  = bs*i;
2508:       for (j=0; j<ncols; j++) {
2509:         bcol = bs*(*bj);
2510:         for (kcol=0; kcol<bs; kcol++) {
2511:           col  = bcol + kcol;                /* local col index */
2512:           col += rowners_bs[rank+1];      /* global col index */
2513:           for (krow=0; krow<bs; krow++) {
2514:             atmp = PetscAbsScalar(*ba); ba++;
2515:             row  = brow + krow;   /* local row index */
2516:             if (PetscRealPart(va[row]) < atmp) va[row] = atmp;
2517:             if (work[col] < atmp) work[col] = atmp;
2518:           }
2519:         }
2520:         bj++;
2521:       }
2522:     }

2524:     /* send values to its owners */
2525:     for (dest=rank+1; dest<size; dest++) {
2526:       svalues = work + rowners_bs[dest];
2527:       count   = rowners_bs[dest+1]-rowners_bs[dest];
2528:       MPI_Send(svalues,count,MPIU_REAL,dest,rank,PetscObjectComm((PetscObject)A));
2529:     }
2530:   }

2532:   /* receive values */
2533:   if (rank) {
2534:     rvalues = work;
2535:     count   = rowners_bs[rank+1]-rowners_bs[rank];
2536:     for (source=0; source<rank; source++) {
2537:       MPI_Recv(rvalues,count,MPIU_REAL,MPI_ANY_SOURCE,MPI_ANY_TAG,PetscObjectComm((PetscObject)A),&stat);
2538:       /* process values */
2539:       for (i=0; i<count; i++) {
2540:         if (PetscRealPart(va[i]) < rvalues[i]) va[i] = rvalues[i];
2541:       }
2542:     }
2543:   }

2545:   VecRestoreArray(v,&va);
2546:   PetscFree(work);
2547:   return(0);
2548: }

2552: PetscErrorCode MatSOR_MPISBAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
2553: {
2554:   Mat_MPISBAIJ      *mat = (Mat_MPISBAIJ*)matin->data;
2555:   PetscErrorCode    ierr;
2556:   PetscInt          mbs=mat->mbs,bs=matin->rmap->bs;
2557:   PetscScalar       *x,*ptr,*from;
2558:   Vec               bb1;
2559:   const PetscScalar *b;

2562:   if (its <= 0 || lits <= 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D and local its %D both positive",its,lits);
2563:   if (bs > 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"SSOR for block size > 1 is not yet implemented");

2565:   if (flag == SOR_APPLY_UPPER) {
2566:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2567:     return(0);
2568:   }

2570:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
2571:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2572:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,lits,xx);
2573:       its--;
2574:     }

2576:     VecDuplicate(bb,&bb1);
2577:     while (its--) {

2579:       /* lower triangular part: slvec0b = - B^T*xx */
2580:       (*mat->B->ops->multtranspose)(mat->B,xx,mat->slvec0b);

2582:       /* copy xx into slvec0a */
2583:       VecGetArray(mat->slvec0,&ptr);
2584:       VecGetArray(xx,&x);
2585:       PetscMemcpy(ptr,x,bs*mbs*sizeof(MatScalar));
2586:       VecRestoreArray(mat->slvec0,&ptr);

2588:       VecScale(mat->slvec0,-1.0);

2590:       /* copy bb into slvec1a */
2591:       VecGetArray(mat->slvec1,&ptr);
2592:       VecGetArrayRead(bb,&b);
2593:       PetscMemcpy(ptr,b,bs*mbs*sizeof(MatScalar));
2594:       VecRestoreArray(mat->slvec1,&ptr);

2596:       /* set slvec1b = 0 */
2597:       VecSet(mat->slvec1b,0.0);

2599:       VecScatterBegin(mat->sMvctx,mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD);
2600:       VecRestoreArray(xx,&x);
2601:       VecRestoreArrayRead(bb,&b);
2602:       VecScatterEnd(mat->sMvctx,mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD);

2604:       /* upper triangular part: bb1 = bb1 - B*x */
2605:       (*mat->B->ops->multadd)(mat->B,mat->slvec1b,mat->slvec1a,bb1);

2607:       /* local diagonal sweep */
2608:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,lits,xx);
2609:     }
2610:     VecDestroy(&bb1);
2611:   } else if ((flag & SOR_LOCAL_FORWARD_SWEEP) && (its == 1) && (flag & SOR_ZERO_INITIAL_GUESS)) {
2612:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2613:   } else if ((flag & SOR_LOCAL_BACKWARD_SWEEP) && (its == 1) && (flag & SOR_ZERO_INITIAL_GUESS)) {
2614:     (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,1,xx);
2615:   } else if (flag & SOR_EISENSTAT) {
2616:     Vec               xx1;
2617:     PetscBool         hasop;
2618:     const PetscScalar *diag;
2619:     PetscScalar       *sl,scale = (omega - 2.0)/omega;
2620:     PetscInt          i,n;

2622:     if (!mat->xx1) {
2623:       VecDuplicate(bb,&mat->xx1);
2624:       VecDuplicate(bb,&mat->bb1);
2625:     }
2626:     xx1 = mat->xx1;
2627:     bb1 = mat->bb1;

2629:     (*mat->A->ops->sor)(mat->A,bb,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_BACKWARD_SWEEP),fshift,lits,1,xx);

2631:     if (!mat->diag) {
2632:       /* this is wrong for same matrix with new nonzero values */
2633:       MatGetVecs(matin,&mat->diag,NULL);
2634:       MatGetDiagonal(matin,mat->diag);
2635:     }
2636:     MatHasOperation(matin,MATOP_MULT_DIAGONAL_BLOCK,&hasop);

2638:     if (hasop) {
2639:       MatMultDiagonalBlock(matin,xx,bb1);
2640:       VecAYPX(mat->slvec1a,scale,bb);
2641:     } else {
2642:       /*
2643:           These two lines are replaced by code that may be a bit faster for a good compiler
2644:       VecPointwiseMult(mat->slvec1a,mat->diag,xx);
2645:       VecAYPX(mat->slvec1a,scale,bb);
2646:       */
2647:       VecGetArray(mat->slvec1a,&sl);
2648:       VecGetArrayRead(mat->diag,&diag);
2649:       VecGetArrayRead(bb,&b);
2650:       VecGetArray(xx,&x);
2651:       VecGetLocalSize(xx,&n);
2652:       if (omega == 1.0) {
2653:         for (i=0; i<n; i++) sl[i] = b[i] - diag[i]*x[i];
2654:         PetscLogFlops(2.0*n);
2655:       } else {
2656:         for (i=0; i<n; i++) sl[i] = b[i] + scale*diag[i]*x[i];
2657:         PetscLogFlops(3.0*n);
2658:       }
2659:       VecRestoreArray(mat->slvec1a,&sl);
2660:       VecRestoreArrayRead(mat->diag,&diag);
2661:       VecRestoreArrayRead(bb,&b);
2662:       VecRestoreArray(xx,&x);
2663:     }

2665:     /* multiply off-diagonal portion of matrix */
2666:     VecSet(mat->slvec1b,0.0);
2667:     (*mat->B->ops->multtranspose)(mat->B,xx,mat->slvec0b);
2668:     VecGetArray(mat->slvec0,&from);
2669:     VecGetArray(xx,&x);
2670:     PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
2671:     VecRestoreArray(mat->slvec0,&from);
2672:     VecRestoreArray(xx,&x);
2673:     VecScatterBegin(mat->sMvctx,mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD);
2674:     VecScatterEnd(mat->sMvctx,mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD);
2675:     (*mat->B->ops->multadd)(mat->B,mat->slvec1b,mat->slvec1a,mat->slvec1a);

2677:     /* local sweep */
2678:     (*mat->A->ops->sor)(mat->A,mat->slvec1a,omega,(MatSORType)(SOR_ZERO_INITIAL_GUESS | SOR_LOCAL_FORWARD_SWEEP),fshift,lits,1,xx1);
2679:     VecAXPY(xx,1.0,xx1);
2680:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatSORType is not supported for SBAIJ matrix format");
2681:   return(0);
2682: }

2686: PetscErrorCode MatSOR_MPISBAIJ_2comm(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,PetscInt its,PetscInt lits,Vec xx)
2687: {
2688:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
2690:   Vec            lvec1,bb1;

2693:   if (its <= 0 || lits <= 0) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Relaxation requires global its %D and local its %D both positive",its,lits);
2694:   if (matin->rmap->bs > 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"SSOR for block size > 1 is not yet implemented");

2696:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP) {
2697:     if (flag & SOR_ZERO_INITIAL_GUESS) {
2698:       (*mat->A->ops->sor)(mat->A,bb,omega,flag,fshift,lits,lits,xx);
2699:       its--;
2700:     }

2702:     VecDuplicate(mat->lvec,&lvec1);
2703:     VecDuplicate(bb,&bb1);
2704:     while (its--) {
2705:       VecScatterBegin(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);

2707:       /* lower diagonal part: bb1 = bb - B^T*xx */
2708:       (*mat->B->ops->multtranspose)(mat->B,xx,lvec1);
2709:       VecScale(lvec1,-1.0);

2711:       VecScatterEnd(mat->Mvctx,xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD);
2712:       VecCopy(bb,bb1);
2713:       VecScatterBegin(mat->Mvctx,lvec1,bb1,ADD_VALUES,SCATTER_REVERSE);

2715:       /* upper diagonal part: bb1 = bb1 - B*x */
2716:       VecScale(mat->lvec,-1.0);
2717:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb1,bb1);

2719:       VecScatterEnd(mat->Mvctx,lvec1,bb1,ADD_VALUES,SCATTER_REVERSE);

2721:       /* diagonal sweep */
2722:       (*mat->A->ops->sor)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,lits,xx);
2723:     }
2724:     VecDestroy(&lvec1);
2725:     VecDestroy(&bb1);
2726:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"MatSORType is not supported for SBAIJ matrix format");
2727:   return(0);
2728: }

2732: /*@
2733:      MatCreateMPISBAIJWithArrays - creates a MPI SBAIJ matrix using arrays that contain in standard
2734:          CSR format the local rows.

2736:    Collective on MPI_Comm

2738:    Input Parameters:
2739: +  comm - MPI communicator
2740: .  bs - the block size, only a block size of 1 is supported
2741: .  m - number of local rows (Cannot be PETSC_DECIDE)
2742: .  n - This value should be the same as the local size used in creating the
2743:        x vector for the matrix-vector product y = Ax. (or PETSC_DECIDE to have
2744:        calculated if N is given) For square matrices n is almost always m.
2745: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
2746: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
2747: .   i - row indices
2748: .   j - column indices
2749: -   a - matrix values

2751:    Output Parameter:
2752: .   mat - the matrix

2754:    Level: intermediate

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

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

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

2765: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIAIJSetPreallocation(), MatMPIAIJSetPreallocationCSR(),
2766:           MPIAIJ, MatCreateAIJ(), MatCreateMPIAIJWithSplitArrays()
2767: @*/
2768: PetscErrorCode  MatCreateMPISBAIJWithArrays(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,const PetscInt i[],const PetscInt j[],const PetscScalar a[],Mat *mat)
2769: {


2774:   if (i[0]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"i (row indices) must start with 0");
2775:   if (m < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"local number of rows (m) cannot be PETSC_DECIDE, or negative");
2776:   MatCreate(comm,mat);
2777:   MatSetSizes(*mat,m,n,M,N);
2778:   MatSetType(*mat,MATMPISBAIJ);
2779:   MatMPISBAIJSetPreallocationCSR(*mat,bs,i,j,a);
2780:   return(0);
2781: }


2786: /*@C
2787:    MatMPISBAIJSetPreallocationCSR - Allocates memory for a sparse parallel matrix in BAIJ format
2788:    (the default parallel PETSc format).

2790:    Collective on MPI_Comm

2792:    Input Parameters:
2793: +  B - the matrix
2794: .  bs - the block size
2795: .  i - the indices into j for the start of each local row (starts with zero)
2796: .  j - the column indices for each local row (starts with zero) these must be sorted for each row
2797: -  v - optional values in the matrix

2799:    Level: developer

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

2803: .seealso: MatCreate(), MatCreateSeqAIJ(), MatSetValues(), MatMPIBAIJSetPreallocation(), MatCreateAIJ(), MPIAIJ
2804: @*/
2805: PetscErrorCode  MatMPISBAIJSetPreallocationCSR(Mat B,PetscInt bs,const PetscInt i[],const PetscInt j[], const PetscScalar v[])
2806: {

2810:   PetscTryMethod(B,"MatMPISBAIJSetPreallocationCSR_C",(Mat,PetscInt,const PetscInt[],const PetscInt[],const PetscScalar[]),(B,bs,i,j,v));
2811:   return(0);
2812: }