Actual source code: mpisbaij.c

  1: /*$Id: mpisbaij.c,v 1.61 2001/08/10 03:31:37 bsmith Exp $*/

  3: #include "src/mat/impls/baij/mpi/mpibaij.h"    /*I "petscmat.h" I*/
  4: #include "src/vec/vecimpl.h"
 5:  #include mpisbaij.h
  6: #include "src/mat/impls/sbaij/seq/sbaij.h"

  8: extern int MatSetUpMultiply_MPISBAIJ(Mat);
  9: extern int DisAssemble_MPISBAIJ(Mat);
 10: extern int MatIncreaseOverlap_MPISBAIJ(Mat,int,IS *,int);
 11: extern int MatGetSubMatrices_MPISBAIJ(Mat,int,IS *,IS *,MatReuse,Mat **);
 12: extern int MatGetValues_SeqSBAIJ(Mat,int,int *,int,int *,PetscScalar *);
 13: extern int MatSetValues_SeqSBAIJ(Mat,int,int *,int,int *,PetscScalar *,InsertMode);
 14: extern int MatSetValuesBlocked_SeqSBAIJ(Mat,int,int*,int,int*,PetscScalar*,InsertMode);
 15: extern int MatGetRow_SeqSBAIJ(Mat,int,int*,int**,PetscScalar**);
 16: extern int MatRestoreRow_SeqSBAIJ(Mat,int,int*,int**,PetscScalar**);
 17: extern int MatPrintHelp_SeqSBAIJ(Mat);
 18: extern int MatZeroRows_SeqSBAIJ(Mat,IS,PetscScalar*);
 19: extern int MatZeroRows_SeqBAIJ(Mat,IS,PetscScalar *);
 20: extern int MatGetRowMax_MPISBAIJ(Mat,Vec);
 21: extern int MatRelax_MPISBAIJ(Mat,Vec,PetscReal,MatSORType,PetscReal,int,int,Vec);

 23: /*  UGLY, ugly, ugly
 24:    When MatScalar == PetscScalar the function MatSetValuesBlocked_MPIBAIJ_MatScalar() does 
 25:    not exist. Otherwise ..._MatScalar() takes matrix elements in single precision and 
 26:    inserts them into the single precision data structure. The function MatSetValuesBlocked_MPIBAIJ()
 27:    converts the entries into single precision and then calls ..._MatScalar() to put them
 28:    into the single precision data structures.
 29: */
 30: #if defined(PETSC_USE_MAT_SINGLE)
 31: extern int MatSetValuesBlocked_SeqSBAIJ_MatScalar(Mat,int,int*,int,int*,MatScalar*,InsertMode);
 32: extern int MatSetValues_MPISBAIJ_MatScalar(Mat,int,int*,int,int*,MatScalar*,InsertMode);
 33: extern int MatSetValuesBlocked_MPISBAIJ_MatScalar(Mat,int,int*,int,int*,MatScalar*,InsertMode);
 34: extern int MatSetValues_MPISBAIJ_HT_MatScalar(Mat,int,int*,int,int*,MatScalar*,InsertMode);
 35: extern int MatSetValuesBlocked_MPISBAIJ_HT_MatScalar(Mat,int,int*,int,int*,MatScalar*,InsertMode);
 36: #else
 37: #define MatSetValuesBlocked_SeqSBAIJ_MatScalar      MatSetValuesBlocked_SeqSBAIJ
 38: #define MatSetValues_MPISBAIJ_MatScalar             MatSetValues_MPISBAIJ
 39: #define MatSetValuesBlocked_MPISBAIJ_MatScalar      MatSetValuesBlocked_MPISBAIJ
 40: #define MatSetValues_MPISBAIJ_HT_MatScalar          MatSetValues_MPISBAIJ_HT
 41: #define MatSetValuesBlocked_MPISBAIJ_HT_MatScalar   MatSetValuesBlocked_MPISBAIJ_HT
 42: #endif

 44: EXTERN_C_BEGIN
 45: int MatStoreValues_MPISBAIJ(Mat mat)
 46: {
 47:   Mat_MPISBAIJ *aij = (Mat_MPISBAIJ *)mat->data;
 48:   int          ierr;

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

 57: EXTERN_C_BEGIN
 58: int MatRetrieveValues_MPISBAIJ(Mat mat)
 59: {
 60:   Mat_MPISBAIJ *aij = (Mat_MPISBAIJ *)mat->data;
 61:   int          ierr;

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

 70: /* 
 71:      Local utility routine that creates a mapping from the global column 
 72:    number to the local number in the off-diagonal part of the local 
 73:    storage of the matrix.  This is done in a non scable way since the 
 74:    length of colmap equals the global matrix length. 
 75: */
 76: static int CreateColmap_MPISBAIJ_Private(Mat mat)
 77: {
 79:   SETERRQ(1,"Function not yet written for SBAIJ format");
 80:   /* return(0); */
 81: }

 83: #define CHUNKSIZE  10

 85: #define  MatSetValues_SeqSBAIJ_A_Private(row,col,value,addv) 
 86: { 
 87:  
 88:     brow = row/bs;  
 89:     rp   = aj + ai[brow]; ap = aa + bs2*ai[brow]; 
 90:     rmax = aimax[brow]; nrow = ailen[brow]; 
 91:       bcol = col/bs; 
 92:       ridx = row % bs; cidx = col % bs; 
 93:       low = 0; high = nrow; 
 94:       while (high-low > 3) { 
 95:         t = (low+high)/2; 
 96:         if (rp[t] > bcol) high = t; 
 97:         else              low  = t; 
 98:       } 
 99:       for (_i=low; _i<high; _i++) { 
100:         if (rp[_i] > bcol) break; 
101:         if (rp[_i] == bcol) { 
102:           bap  = ap +  bs2*_i + bs*cidx + ridx; 
103:           if (addv == ADD_VALUES) *bap += value;  
104:           else                    *bap  = value;  
105:           goto a_noinsert; 
106:         } 
107:       } 
108:       if (a->nonew == 1) goto a_noinsert; 
109:       else if (a->nonew == -1) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero into matrix"); 
110:       if (nrow >= rmax) { 
111:         /* there is no extra room in row, therefore enlarge */ 
112:         int       new_nz = ai[a->mbs] + CHUNKSIZE,len,*new_i,*new_j; 
113:         MatScalar *new_a; 
114:  
115:         if (a->nonew == -2) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero in the matrix"); 
116:  
117:         /* malloc new storage space */ 
118:         len   = new_nz*(sizeof(int)+bs2*sizeof(MatScalar))+(a->mbs+1)*sizeof(int); 
119:         ierr  = PetscMalloc(len,&new_a); 
120:         new_j = (int*)(new_a + bs2*new_nz); 
121:         new_i = new_j + new_nz; 
122:  
123:         /* copy over old data into new slots */ 
124:         for (ii=0; ii<brow+1; ii++) {new_i[ii] = ai[ii];} 
125:         for (ii=brow+1; ii<a->mbs+1; ii++) {new_i[ii] = ai[ii]+CHUNKSIZE;} 
126:         PetscMemcpy(new_j,aj,(ai[brow]+nrow)*sizeof(int)); 
127:         len = (new_nz - CHUNKSIZE - ai[brow] - nrow); 
128:         PetscMemcpy(new_j+ai[brow]+nrow+CHUNKSIZE,aj+ai[brow]+nrow,len*sizeof(int)); 
129:         PetscMemcpy(new_a,aa,(ai[brow]+nrow)*bs2*sizeof(MatScalar)); 
130:         PetscMemzero(new_a+bs2*(ai[brow]+nrow),bs2*CHUNKSIZE*sizeof(PetscScalar)); 
131:         PetscMemcpy(new_a+bs2*(ai[brow]+nrow+CHUNKSIZE), 
132:                     aa+bs2*(ai[brow]+nrow),bs2*len*sizeof(MatScalar));  
133:         /* free up old matrix storage */ 
134:         PetscFree(a->a);  
135:         if (!a->singlemalloc) { 
136:           PetscFree(a->i); 
137:           PetscFree(a->j);
138:         } 
139:         aa = a->a = new_a; ai = a->i = new_i; aj = a->j = new_j;  
140:         a->singlemalloc = PETSC_TRUE; 
141:  
142:         rp   = aj + ai[brow]; ap = aa + bs2*ai[brow]; 
143:         rmax = aimax[brow] = aimax[brow] + CHUNKSIZE; 
144:         PetscLogObjectMemory(A,CHUNKSIZE*(sizeof(int) + bs2*sizeof(MatScalar))); 
145:         a->s_maxnz += bs2*CHUNKSIZE; 
146:         a->reallocs++; 
147:         a->s_nz++; 
148:       } 
149:       N = nrow++ - 1;  
150:       /* shift up all the later entries in this row */ 
151:       for (ii=N; ii>=_i; ii--) { 
152:         rp[ii+1] = rp[ii]; 
153:         PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); 
154:       } 
155:       if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar)); }  
156:       rp[_i]                      = bcol;  
157:       ap[bs2*_i + bs*cidx + ridx] = value;  
158:       a_noinsert:; 
159:     ailen[brow] = nrow; 
160: } 
161: #ifndef MatSetValues_SeqBAIJ_B_Private
162: #define  MatSetValues_SeqSBAIJ_B_Private(row,col,value,addv) 
163: { 
164:     brow = row/bs;  
165:     rp   = bj + bi[brow]; ap = ba + bs2*bi[brow]; 
166:     rmax = bimax[brow]; nrow = bilen[brow]; 
167:       bcol = col/bs; 
168:       ridx = row % bs; cidx = col % bs; 
169:       low = 0; high = nrow; 
170:       while (high-low > 3) { 
171:         t = (low+high)/2; 
172:         if (rp[t] > bcol) high = t; 
173:         else              low  = t; 
174:       } 
175:       for (_i=low; _i<high; _i++) { 
176:         if (rp[_i] > bcol) break; 
177:         if (rp[_i] == bcol) { 
178:           bap  = ap +  bs2*_i + bs*cidx + ridx; 
179:           if (addv == ADD_VALUES) *bap += value;  
180:           else                    *bap  = value;  
181:           goto b_noinsert; 
182:         } 
183:       } 
184:       if (b->nonew == 1) goto b_noinsert; 
185:       else if (b->nonew == -1) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero into matrix"); 
186:       if (nrow >= rmax) { 
187:         /* there is no extra room in row, therefore enlarge */ 
188:         int       new_nz = bi[b->mbs] + CHUNKSIZE,len,*new_i,*new_j; 
189:         MatScalar *new_a; 
190:  
191:         if (b->nonew == -2) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Inserting a new nonzero in the matrix"); 
192:  
193:         /* malloc new storage space */ 
194:         len   = new_nz*(sizeof(int)+bs2*sizeof(MatScalar))+(b->mbs+1)*sizeof(int); 
195:         ierr  = PetscMalloc(len,&new_a); 
196:         new_j = (int*)(new_a + bs2*new_nz); 
197:         new_i = new_j + new_nz; 
198:  
199:         /* copy over old data into new slots */ 
200:         for (ii=0; ii<brow+1; ii++) {new_i[ii] = bi[ii];} 
201:         for (ii=brow+1; ii<b->mbs+1; ii++) {new_i[ii] = bi[ii]+CHUNKSIZE;} 
202:         PetscMemcpy(new_j,bj,(bi[brow]+nrow)*sizeof(int)); 
203:         len  = (new_nz - CHUNKSIZE - bi[brow] - nrow); 
204:         PetscMemcpy(new_j+bi[brow]+nrow+CHUNKSIZE,bj+bi[brow]+nrow,len*sizeof(int)); 
205:         PetscMemcpy(new_a,ba,(bi[brow]+nrow)*bs2*sizeof(MatScalar)); 
206:         PetscMemzero(new_a+bs2*(bi[brow]+nrow),bs2*CHUNKSIZE*sizeof(MatScalar)); 
207:         PetscMemcpy(new_a+bs2*(bi[brow]+nrow+CHUNKSIZE), 
208:                     ba+bs2*(bi[brow]+nrow),bs2*len*sizeof(MatScalar));  
209:         /* free up old matrix storage */ 
210:         PetscFree(b->a);  
211:         if (!b->singlemalloc) { 
212:           PetscFree(b->i); 
213:           PetscFree(b->j); 
214:         } 
215:         ba = b->a = new_a; bi = b->i = new_i; bj = b->j = new_j;  
216:         b->singlemalloc = PETSC_TRUE; 
217:  
218:         rp   = bj + bi[brow]; ap = ba + bs2*bi[brow]; 
219:         rmax = bimax[brow] = bimax[brow] + CHUNKSIZE; 
220:         PetscLogObjectMemory(B,CHUNKSIZE*(sizeof(int) + bs2*sizeof(MatScalar))); 
221:         b->maxnz += bs2*CHUNKSIZE; 
222:         b->reallocs++; 
223:         b->nz++; 
224:       } 
225:       N = nrow++ - 1;  
226:       /* shift up all the later entries in this row */ 
227:       for (ii=N; ii>=_i; ii--) { 
228:         rp[ii+1] = rp[ii]; 
229:         PetscMemcpy(ap+bs2*(ii+1),ap+bs2*(ii),bs2*sizeof(MatScalar)); 
230:       } 
231:       if (N>=_i) { PetscMemzero(ap+bs2*_i,bs2*sizeof(MatScalar));}  
232:       rp[_i]                      = bcol;  
233:       ap[bs2*_i + bs*cidx + ridx] = value;  
234:       b_noinsert:; 
235:     bilen[brow] = nrow; 
236: } 
237: #endif

239: #if defined(PETSC_USE_MAT_SINGLE)
240: int MatSetValues_MPISBAIJ(Mat mat,int m,int *im,int n,int *in,PetscScalar *v,InsertMode addv)
241: {
242:   Mat_MPISBAIJ *b = (Mat_MPISBAIJ*)mat->data;
243:   int          ierr,i,N = m*n;
244:   MatScalar    *vsingle;

247:   if (N > b->setvalueslen) {
248:     if (b->setvaluescopy) {PetscFree(b->setvaluescopy);}
249:     PetscMalloc(N*sizeof(MatScalar),&b->setvaluescopy);
250:     b->setvalueslen  = N;
251:   }
252:   vsingle = b->setvaluescopy;

254:   for (i=0; i<N; i++) {
255:     vsingle[i] = v[i];
256:   }
257:   MatSetValues_MPISBAIJ_MatScalar(mat,m,im,n,in,vsingle,addv);
258:   return(0);
259: }

261: int MatSetValuesBlocked_MPISBAIJ(Mat mat,int m,int *im,int n,int *in,PetscScalar *v,InsertMode addv)
262: {
263:   Mat_MPIBAIJ *b = (Mat_MPIBAIJ*)mat->data;
264:   int         ierr,i,N = m*n*b->bs2;
265:   MatScalar   *vsingle;

268:   if (N > b->setvalueslen) {
269:     if (b->setvaluescopy) {PetscFree(b->setvaluescopy);}
270:     PetscMalloc(N*sizeof(MatScalar),&b->setvaluescopy);
271:     b->setvalueslen  = N;
272:   }
273:   vsingle = b->setvaluescopy;
274:   for (i=0; i<N; i++) {
275:     vsingle[i] = v[i];
276:   }
277:   MatSetValuesBlocked_MPISBAIJ_MatScalar(mat,m,im,n,in,vsingle,addv);
278:   return(0);
279: }

281: int MatSetValues_MPISBAIJ_HT(Mat mat,int m,int *im,int n,int *in,PetscScalar *v,InsertMode addv)
282: {
283:   Mat_MPIBAIJ *b = (Mat_MPIBAIJ*)mat->data;
284:   int         ierr,i,N = m*n;
285:   MatScalar   *vsingle;

288:   SETERRQ(1,"Function not yet written for SBAIJ format");
289:   /* return(0); */
290: }

292: int MatSetValuesBlocked_MPISBAIJ_HT(Mat mat,int m,int *im,int n,int *in,PetscScalar *v,InsertMode addv)
293: {
294:   Mat_MPIBAIJ *b = (Mat_MPIBAIJ*)mat->data;
295:   int         ierr,i,N = m*n*b->bs2;
296:   MatScalar   *vsingle;

299:   SETERRQ(1,"Function not yet written for SBAIJ format");
300:   /* return(0); */
301: }
302: #endif

304: /* Only add/insert a(i,j) with i<=j (blocks). 
305:    Any a(i,j) with i>j input by user is ingored. 
306: */
307: int MatSetValues_MPISBAIJ_MatScalar(Mat mat,int m,int *im,int n,int *in,MatScalar *v,InsertMode addv)
308: {
309:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
310:   MatScalar    value;
311:   PetscTruth   roworiented = baij->roworiented;
312:   int          ierr,i,j,row,col;
313:   int          rstart_orig=baij->rstart_bs;
314:   int          rend_orig=baij->rend_bs,cstart_orig=baij->cstart_bs;
315:   int          cend_orig=baij->cend_bs,bs=baij->bs;

317:   /* Some Variables required in the macro */
318:   Mat          A = baij->A;
319:   Mat_SeqSBAIJ *a = (Mat_SeqSBAIJ*)(A)->data;
320:   int          *aimax=a->imax,*ai=a->i,*ailen=a->ilen,*aj=a->j;
321:   MatScalar    *aa=a->a;

323:   Mat          B = baij->B;
324:   Mat_SeqBAIJ  *b = (Mat_SeqBAIJ*)(B)->data;
325:   int          *bimax=b->imax,*bi=b->i,*bilen=b->ilen,*bj=b->j;
326:   MatScalar    *ba=b->a;

328:   int          *rp,ii,nrow,_i,rmax,N,brow,bcol;
329:   int          low,high,t,ridx,cidx,bs2=a->bs2;
330:   MatScalar    *ap,*bap;

332:   /* for stash */
333:   int          n_loc, *in_loc=0;
334:   MatScalar    *v_loc=0;


338:   if(!baij->donotstash){
339:     PetscMalloc(n*sizeof(int),&in_loc);
340:     PetscMalloc(n*sizeof(MatScalar),&v_loc);
341:   }

343:   for (i=0; i<m; i++) {
344:     if (im[i] < 0) continue;
345: #if defined(PETSC_USE_BOPT_g)
346:     if (im[i] >= mat->M) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Row too large");
347: #endif
348:     if (im[i] >= rstart_orig && im[i] < rend_orig) { /* this processor entry */
349:       row = im[i] - rstart_orig;              /* local row index */
350:       for (j=0; j<n; j++) {
351:         if (im[i]/bs > in[j]/bs) continue;    /* ignore lower triangular blocks */
352:         if (in[j] >= cstart_orig && in[j] < cend_orig){  /* diag entry (A) */
353:           col = in[j] - cstart_orig;          /* local col index */
354:           brow = row/bs; bcol = col/bs;
355:           if (brow > bcol) continue;  /* ignore lower triangular blocks of A */
356:           if (roworiented) value = v[i*n+j]; else value = v[i+j*m];
357:           MatSetValues_SeqSBAIJ_A_Private(row,col,value,addv);
358:           /* MatSetValues_SeqBAIJ(baij->A,1,&row,1,&col,&value,addv); */
359:         } else if (in[j] < 0) continue;
360: #if defined(PETSC_USE_BOPT_g)
361:         else if (in[j] >= mat->N) {SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Col too large");}
362: #endif
363:         else {  /* off-diag entry (B) */
364:           if (mat->was_assembled) {
365:             if (!baij->colmap) {
366:               CreateColmap_MPISBAIJ_Private(mat);
367:             }
368: #if defined (PETSC_USE_CTABLE)
369:             PetscTableFind(baij->colmap,in[j]/bs + 1,&col);
370:             col  = col - 1;
371: #else
372:             col = baij->colmap[in[j]/bs] - 1;
373: #endif
374:             if (col < 0 && !((Mat_SeqSBAIJ*)(baij->A->data))->nonew) {
375:               DisAssemble_MPISBAIJ(mat);
376:               col =  in[j];
377:               /* Reinitialize the variables required by MatSetValues_SeqBAIJ_B_Private() */
378:               B = baij->B;
379:               b = (Mat_SeqBAIJ*)(B)->data;
380:               bimax=b->imax;bi=b->i;bilen=b->ilen;bj=b->j;
381:               ba=b->a;
382:             } else col += in[j]%bs;
383:           } else col = in[j];
384:           if (roworiented) value = v[i*n+j]; else value = v[i+j*m];
385:           MatSetValues_SeqSBAIJ_B_Private(row,col,value,addv);
386:           /* MatSetValues_SeqBAIJ(baij->B,1,&row,1,&col,&value,addv); */
387:         }
388:       }
389:     } else {  /* off processor entry */
390:       if (!baij->donotstash) {
391:         n_loc = 0;
392:         for (j=0; j<n; j++){
393:           if (im[i]/bs > in[j]/bs) continue; /* ignore lower triangular blocks */
394:           in_loc[n_loc] = in[j];
395:           if (roworiented) {
396:             v_loc[n_loc] = v[i*n+j];
397:           } else {
398:             v_loc[n_loc] = v[j*m+i];
399:           }
400:           n_loc++;
401:         }
402:         MatStashValuesRow_Private(&mat->stash,im[i],n_loc,in_loc,v_loc);
403:       }
404:     }
405:   }

407:   if(!baij->donotstash){
408:     PetscFree(in_loc);
409:     PetscFree(v_loc);
410:   }
411:   return(0);
412: }

414: int MatSetValuesBlocked_MPISBAIJ_MatScalar(Mat mat,int m,int *im,int n,int *in,MatScalar *v,InsertMode addv)
415: {
417:   SETERRQ(1,"Function not yet written for SBAIJ format");
418:   /* return(0); */
419: }

421: #define HASH_KEY 0.6180339887
422: #define HASH(size,key,tmp) (tmp = (key)*HASH_KEY,(int)((size)*(tmp-(int)tmp)))
423: /* #define HASH(size,key) ((int)((size)*fmod(((key)*HASH_KEY),1))) */
424: /* #define HASH(size,key,tmp) ((int)((size)*fmod(((key)*HASH_KEY),1))) */
425: int MatSetValues_MPISBAIJ_HT_MatScalar(Mat mat,int m,int *im,int n,int *in,MatScalar *v,InsertMode addv)
426: {
428:   SETERRQ(1,"Function not yet written for SBAIJ format");
429:   /* return(0); */
430: }

432: int MatSetValuesBlocked_MPISBAIJ_HT_MatScalar(Mat mat,int m,int *im,int n,int *in,MatScalar *v,InsertMode addv)
433: {
435:   SETERRQ(1,"Function not yet written for SBAIJ format");
436:   /* return(0); */
437: }

439: int MatGetValues_MPISBAIJ(Mat mat,int m,int *idxm,int n,int *idxn,PetscScalar *v)
440: {
441:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
442:   int          bs=baij->bs,ierr,i,j,bsrstart = baij->rstart*bs,bsrend = baij->rend*bs;
443:   int          bscstart = baij->cstart*bs,bscend = baij->cend*bs,row,col,data;

446:   for (i=0; i<m; i++) {
447:     if (idxm[i] < 0) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Negative row");
448:     if (idxm[i] >= mat->M) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Row too large");
449:     if (idxm[i] >= bsrstart && idxm[i] < bsrend) {
450:       row = idxm[i] - bsrstart;
451:       for (j=0; j<n; j++) {
452:         if (idxn[j] < 0) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Negative column");
453:         if (idxn[j] >= mat->N) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Column too large");
454:         if (idxn[j] >= bscstart && idxn[j] < bscend){
455:           col = idxn[j] - bscstart;
456:           MatGetValues_SeqSBAIJ(baij->A,1,&row,1,&col,v+i*n+j);
457:         } else {
458:           if (!baij->colmap) {
459:             CreateColmap_MPISBAIJ_Private(mat);
460:           }
461: #if defined (PETSC_USE_CTABLE)
462:           PetscTableFind(baij->colmap,idxn[j]/bs+1,&data);
463:           data --;
464: #else
465:           data = baij->colmap[idxn[j]/bs]-1;
466: #endif
467:           if((data < 0) || (baij->garray[data/bs] != idxn[j]/bs)) *(v+i*n+j) = 0.0;
468:           else {
469:             col  = data + idxn[j]%bs;
470:             MatGetValues_SeqSBAIJ(baij->B,1,&row,1,&col,v+i*n+j);
471:           }
472:         }
473:       }
474:     } else {
475:       SETERRQ(PETSC_ERR_SUP,"Only local values currently supported");
476:     }
477:   }
478:  return(0);
479: }

481: int MatNorm_MPISBAIJ(Mat mat,NormType type,PetscReal *norm)
482: {
483:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
484:   /* Mat_SeqSBAIJ *amat = (Mat_SeqSBAIJ*)baij->A->data; */
485:   /* Mat_SeqBAIJ  *bmat = (Mat_SeqBAIJ*)baij->B->data; */
486:   int        ierr;
487:   PetscReal  sum[2],*lnorm2;

490:   if (baij->size == 1) {
491:      MatNorm(baij->A,type,norm);
492:   } else {
493:     if (type == NORM_FROBENIUS) {
494:       PetscMalloc(2*sizeof(PetscReal),&lnorm2);
495:        MatNorm(baij->A,type,lnorm2);
496:       *lnorm2 = (*lnorm2)*(*lnorm2); lnorm2++;            /* squar power of norm(A) */
497:        MatNorm(baij->B,type,lnorm2);
498:       *lnorm2 = (*lnorm2)*(*lnorm2); lnorm2--;             /* squar power of norm(B) */
499:       /*
500:       MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
501:       PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d], lnorm2=%g, %gn",rank,lnorm2[0],lnorm2[1]);
502:       */
503:       MPI_Allreduce(lnorm2,&sum,2,MPIU_REAL,MPI_SUM,mat->comm);
504:       /*
505:       PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d], sum=%g, %gn",rank,sum[0],sum[1]);
506:       PetscSynchronizedFlush(PETSC_COMM_WORLD); */
507: 
508:       *norm = sqrt(sum[0] + 2*sum[1]);
509:       PetscFree(lnorm2);
510:     } else {
511:       SETERRQ(PETSC_ERR_SUP,"No support for this norm yet");
512:     }
513:   }
514:   return(0);
515: }

517: /*
518:   Creates the hash table, and sets the table 
519:   This table is created only once. 
520:   If new entried need to be added to the matrix
521:   then the hash table has to be destroyed and
522:   recreated.
523: */
524: int MatCreateHashTable_MPISBAIJ_Private(Mat mat,PetscReal factor)
525: {
527:   SETERRQ(1,"Function not yet written for SBAIJ format");
528:   /* return(0); */
529: }

531: int MatAssemblyBegin_MPISBAIJ(Mat mat,MatAssemblyType mode)
532: {
533:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
534:   int         ierr,nstash,reallocs;
535:   InsertMode  addv;

538:   if (baij->donotstash) {
539:     return(0);
540:   }

542:   /* make sure all processors are either in INSERTMODE or ADDMODE */
543:   MPI_Allreduce(&mat->insertmode,&addv,1,MPI_INT,MPI_BOR,mat->comm);
544:   if (addv == (ADD_VALUES|INSERT_VALUES)) {
545:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Some processors inserted others added");
546:   }
547:   mat->insertmode = addv; /* in case this processor had no cache */

549:   MatStashScatterBegin_Private(&mat->stash,baij->rowners_bs);
550:   MatStashScatterBegin_Private(&mat->bstash,baij->rowners);
551:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
552:   PetscLogInfo(0,"MatAssemblyBegin_MPISBAIJ:Stash has %d entries,uses %d mallocs.n",nstash,reallocs);
553:   MatStashGetInfo_Private(&mat->stash,&nstash,&reallocs);
554:   PetscLogInfo(0,"MatAssemblyBegin_MPISBAIJ:Block-Stash has %d entries, uses %d mallocs.n",nstash,reallocs);
555:   return(0);
556: }

558: int MatAssemblyEnd_MPISBAIJ(Mat mat,MatAssemblyType mode)
559: {
560:   Mat_MPISBAIJ *baij=(Mat_MPISBAIJ*)mat->data;
561:   Mat_SeqSBAIJ  *a=(Mat_SeqSBAIJ*)baij->A->data;
562:   Mat_SeqBAIJ  *b=(Mat_SeqBAIJ*)baij->B->data;
563:   int         i,j,rstart,ncols,n,ierr,flg,bs2=baij->bs2;
564:   int         *row,*col,other_disassembled;
565:   PetscTruth  r1,r2,r3;
566:   MatScalar   *val;
567:   InsertMode  addv = mat->insertmode;
568:   /* int         rank;*/

571:   /* remove 2 line below later */
572:   /*MPI_Comm_rank(PETSC_COMM_WORLD, &rank); */

574:   if (!baij->donotstash) {
575:     while (1) {
576:       MatStashScatterGetMesg_Private(&mat->stash,&n,&row,&col,&val,&flg);
577:       /*
578:       PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d]: in AssemblyEnd, stash, flg=%dn",rank,flg);
579:       PetscSynchronizedFlush(PETSC_COMM_WORLD); 
580:       */
581:       if (!flg) break;

583:       for (i=0; i<n;) {
584:         /* Now identify the consecutive vals belonging to the same row */
585:         for (j=i,rstart=row[j]; j<n; j++) { if (row[j] != rstart) break; }
586:         if (j < n) ncols = j-i;
587:         else       ncols = n-i;
588:         /* Now assemble all these values with a single function call */
589:         MatSetValues_MPISBAIJ_MatScalar(mat,1,row+i,ncols,col+i,val+i,addv);
590:         i = j;
591:       }
592:     }
593:     MatStashScatterEnd_Private(&mat->stash);
594:     /* Now process the block-stash. Since the values are stashed column-oriented,
595:        set the roworiented flag to column oriented, and after MatSetValues() 
596:        restore the original flags */
597:     r1 = baij->roworiented;
598:     r2 = a->roworiented;
599:     r3 = b->roworiented;
600:     baij->roworiented = PETSC_FALSE;
601:     a->roworiented    = PETSC_FALSE;
602:     b->roworiented    = PETSC_FALSE;
603:     while (1) {
604:       MatStashScatterGetMesg_Private(&mat->bstash,&n,&row,&col,&val,&flg);
605:       if (!flg) break;
606: 
607:       for (i=0; i<n;) {
608:         /* Now identify the consecutive vals belonging to the same row */
609:         for (j=i,rstart=row[j]; j<n; j++) { if (row[j] != rstart) break; }
610:         if (j < n) ncols = j-i;
611:         else       ncols = n-i;
612:         MatSetValuesBlocked_MPISBAIJ_MatScalar(mat,1,row+i,ncols,col+i,val+i*bs2,addv);
613:         i = j;
614:       }
615:     }
616:     MatStashScatterEnd_Private(&mat->bstash);
617:     baij->roworiented = r1;
618:     a->roworiented    = r2;
619:     b->roworiented    = r3;
620:   }

622:   MatAssemblyBegin(baij->A,mode);
623:   MatAssemblyEnd(baij->A,mode);

625:   /* determine if any processor has disassembled, if so we must 
626:      also disassemble ourselfs, in order that we may reassemble. */
627:   /*
628:      if nonzero structure of submatrix B cannot change then we know that
629:      no processor disassembled thus we can skip this stuff
630:   */
631:   if (!((Mat_SeqBAIJ*)baij->B->data)->nonew)  {
632:     MPI_Allreduce(&mat->was_assembled,&other_disassembled,1,MPI_INT,MPI_PROD,mat->comm);
633:     if (mat->was_assembled && !other_disassembled) {
634:       DisAssemble_MPISBAIJ(mat);
635:     }
636:   }

638:   if (!mat->was_assembled && mode == MAT_FINAL_ASSEMBLY) {
639:     MatSetUpMultiply_MPISBAIJ(mat);
640:   }
641:   MatAssemblyBegin(baij->B,mode);
642:   MatAssemblyEnd(baij->B,mode);
643: 
644: #if defined(PETSC_USE_BOPT_g)
645:   if (baij->ht && mode== MAT_FINAL_ASSEMBLY) {
646:     PetscLogInfo(0,"MatAssemblyEnd_MPISBAIJ:Average Hash Table Search in MatSetValues = %5.2fn",((PetscReal)baij->ht_total_ct)/baij->ht_insert_ct);
647:     baij->ht_total_ct  = 0;
648:     baij->ht_insert_ct = 0;
649:   }
650: #endif
651:   if (baij->ht_flag && !baij->ht && mode == MAT_FINAL_ASSEMBLY) {
652:     MatCreateHashTable_MPISBAIJ_Private(mat,baij->ht_fact);
653:     mat->ops->setvalues        = MatSetValues_MPISBAIJ_HT;
654:     mat->ops->setvaluesblocked = MatSetValuesBlocked_MPISBAIJ_HT;
655:   }

657:   if (baij->rowvalues) {
658:     PetscFree(baij->rowvalues);
659:     baij->rowvalues = 0;
660:   }
661:   return(0);
662: }

664: static int MatView_MPISBAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
665: {
666:   Mat_MPISBAIJ      *baij = (Mat_MPISBAIJ*)mat->data;
667:   int               ierr,bs = baij->bs,size = baij->size,rank = baij->rank;
668:   PetscTruth        isascii,isdraw;
669:   PetscViewer       sviewer;
670:   PetscViewerFormat format;

673:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);
674:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
675:   if (isascii) {
676:     PetscViewerGetFormat(viewer,&format);
677:     if (format == PETSC_VIEWER_ASCII_INFO_LONG) {
678:       MatInfo info;
679:       MPI_Comm_rank(mat->comm,&rank);
680:       MatGetInfo(mat,MAT_LOCAL,&info);
681:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] Local rows %d nz %d nz alloced %d bs %d mem %dn",
682:               rank,mat->m,(int)info.nz_used*bs,(int)info.nz_allocated*bs,
683:               baij->bs,(int)info.memory);
684:       MatGetInfo(baij->A,MAT_LOCAL,&info);
685:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] on-diagonal part: nz %d n",rank,(int)info.nz_used*bs);
686:       MatGetInfo(baij->B,MAT_LOCAL,&info);
687:       PetscViewerASCIISynchronizedPrintf(viewer,"[%d] off-diagonal part: nz %d n",rank,(int)info.nz_used*bs);
688:       PetscViewerFlush(viewer);
689:       VecScatterView(baij->Mvctx,viewer);
690:       return(0);
691:     } else if (format == PETSC_VIEWER_ASCII_INFO) {
692:       PetscViewerASCIIPrintf(viewer,"  block size is %dn",bs);
693:       return(0);
694:     }
695:   }

697:   if (isdraw) {
698:     PetscDraw       draw;
699:     PetscTruth isnull;
700:     PetscViewerDrawGetDraw(viewer,0,&draw);
701:     PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
702:   }

704:   if (size == 1) {
705:     PetscObjectSetName((PetscObject)baij->A,mat->name);
706:     MatView(baij->A,viewer);
707:   } else {
708:     /* assemble the entire matrix onto first processor. */
709:     Mat         A;
710:     Mat_SeqSBAIJ *Aloc;
711:     Mat_SeqBAIJ *Bloc;
712:     int         M = mat->M,N = mat->N,*ai,*aj,col,i,j,k,*rvals,mbs = baij->mbs;
713:     MatScalar   *a;

715:     if (!rank) {
716:       MatCreateMPISBAIJ(mat->comm,baij->bs,M,N,M,N,0,PETSC_NULL,0,PETSC_NULL,&A);
717:     } else {
718:       MatCreateMPISBAIJ(mat->comm,baij->bs,0,0,M,N,0,PETSC_NULL,0,PETSC_NULL,&A);
719:     }
720:     PetscLogObjectParent(mat,A);

722:     /* copy over the A part */
723:     Aloc  = (Mat_SeqSBAIJ*)baij->A->data;
724:     ai    = Aloc->i; aj = Aloc->j; a = Aloc->a;
725:     ierr  = PetscMalloc(bs*sizeof(int),&rvals);

727:     for (i=0; i<mbs; i++) {
728:       rvals[0] = bs*(baij->rstart + i);
729:       for (j=1; j<bs; j++) { rvals[j] = rvals[j-1] + 1; }
730:       for (j=ai[i]; j<ai[i+1]; j++) {
731:         col = (baij->cstart+aj[j])*bs;
732:         for (k=0; k<bs; k++) {
733:           MatSetValues_MPISBAIJ_MatScalar(A,bs,rvals,1,&col,a,INSERT_VALUES);
734:           col++; a += bs;
735:         }
736:       }
737:     }
738:     /* copy over the B part */
739:     Bloc = (Mat_SeqBAIJ*)baij->B->data;
740:     ai = Bloc->i; aj = Bloc->j; a = Bloc->a;
741:     for (i=0; i<mbs; i++) {
742:       rvals[0] = bs*(baij->rstart + i);
743:       for (j=1; j<bs; j++) { rvals[j] = rvals[j-1] + 1; }
744:       for (j=ai[i]; j<ai[i+1]; j++) {
745:         col = baij->garray[aj[j]]*bs;
746:         for (k=0; k<bs; k++) {
747:           MatSetValues_MPISBAIJ_MatScalar(A,bs,rvals,1,&col,a,INSERT_VALUES);
748:           col++; a += bs;
749:         }
750:       }
751:     }
752:     PetscFree(rvals);
753:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
754:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
755:     /* 
756:        Everyone has to call to draw the matrix since the graphics waits are
757:        synchronized across all processors that share the PetscDraw object
758:     */
759:     PetscViewerGetSingleton(viewer,&sviewer);
760:     if (!rank) {
761:       PetscObjectSetName((PetscObject)((Mat_MPISBAIJ*)(A->data))->A,mat->name);
762:       MatView(((Mat_MPISBAIJ*)(A->data))->A,sviewer);
763:     }
764:     PetscViewerRestoreSingleton(viewer,&sviewer);
765:     MatDestroy(A);
766:   }
767:   return(0);
768: }

770: int MatView_MPISBAIJ(Mat mat,PetscViewer viewer)
771: {
772:   int        ierr;
773:   PetscTruth isascii,isdraw,issocket,isbinary;

776:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);
777:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
778:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_SOCKET,&issocket);
779:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_BINARY,&isbinary);
780:   if (isascii || isdraw || issocket || isbinary) {
781:     MatView_MPISBAIJ_ASCIIorDraworSocket(mat,viewer);
782:   } else {
783:     SETERRQ1(1,"Viewer type %s not supported by MPISBAIJ matrices",((PetscObject)viewer)->type_name);
784:   }
785:   return(0);
786: }

788: int MatDestroy_MPISBAIJ(Mat mat)
789: {
790:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
791:   int         ierr;

794: #if defined(PETSC_USE_LOG)
795:   PetscLogObjectState((PetscObject)mat,"Rows=%d,Cols=%d",mat->M,mat->N);
796: #endif
797:   MatStashDestroy_Private(&mat->stash);
798:   MatStashDestroy_Private(&mat->bstash);
799:   PetscFree(baij->rowners);
800:   MatDestroy(baij->A);
801:   MatDestroy(baij->B);
802: #if defined (PETSC_USE_CTABLE)
803:   if (baij->colmap) {PetscTableDelete(baij->colmap);}
804: #else
805:   if (baij->colmap) {PetscFree(baij->colmap);}
806: #endif
807:   if (baij->garray) {PetscFree(baij->garray);}
808:   if (baij->lvec)   {VecDestroy(baij->lvec);}
809:   if (baij->Mvctx)  {VecScatterDestroy(baij->Mvctx);}
810:   /* if (baij->slvec0) {VecDestroy(baij->slvec0);}
811:   if (baij->slvec1) {VecDestroy(baij->slvec1);}
812:   if (baij->sMvctx)  {VecScatterDestroy(baij->sMvctx);} */
813:   if (baij->rowvalues) {PetscFree(baij->rowvalues);}
814:   if (baij->barray) {PetscFree(baij->barray);}
815:   if (baij->hd) {PetscFree(baij->hd);}
816: #if defined(PETSC_USE_MAT_SINGLE)
817:   if (baij->setvaluescopy) {PetscFree(baij->setvaluescopy);}
818: #endif
819:   PetscFree(baij);
820:   return(0);
821: }

823: int MatMult_MPISBAIJ(Mat A,Vec xx,Vec yy)
824: {
825:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
826:   int         ierr,nt;

829:   VecGetLocalSize(xx,&nt);
830:   if (nt != A->n) {
831:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");
832:   }
833:   VecGetLocalSize(yy,&nt);
834:   if (nt != A->m) {
835:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible parition of A and yy");
836:   }

838:   VecScatterBegin(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
839:   /* do diagonal part */
840:   (*a->A->ops->mult)(a->A,xx,yy);
841:   /* do supperdiagonal part */
842:   VecScatterEnd(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
843:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
844:   /* do subdiagonal part */
845:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
846:   VecScatterBegin(a->lvec,yy,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);
847:   VecScatterEnd(a->lvec,yy,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);

849:   return(0);
850: }

852: int MatMultAdd_MPISBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
853: {
854:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
855:   int        ierr;

858:   VecScatterBegin(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
859:   /* do diagonal part */
860:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
861:   /* do supperdiagonal part */
862:   VecScatterEnd(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
863:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);

865:   /* do subdiagonal part */
866:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
867:   VecScatterBegin(a->lvec,zz,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);
868:   VecScatterEnd(a->lvec,zz,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);

870:   return(0);
871: }

873: int MatMultTranspose_MPISBAIJ(Mat A,Vec xx,Vec yy)
874: {
876:   SETERRQ(1,"Matrix is symmetric. Call MatMult().");
877:   /* return(0); */
878: }

880: int MatMultTransposeAdd_MPISBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
881: {
883:   SETERRQ(1,"Matrix is symmetric. Call MatMultAdd().");
884:   /* return(0); */
885: }

887: /*
888:   This only works correctly for square matrices where the subblock A->A is the 
889:    diagonal block
890: */
891: int MatGetDiagonal_MPISBAIJ(Mat A,Vec v)
892: {
893:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
894:   int         ierr;

897:   /* if (a->M != a->N) SETERRQ(PETSC_ERR_SUP,"Supports only square matrix where A->A is diag block"); */
898:   MatGetDiagonal(a->A,v);
899:   return(0);
900: }

902: int MatScale_MPISBAIJ(PetscScalar *aa,Mat A)
903: {
904:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
905:   int         ierr;

908:   MatScale(aa,a->A);
909:   MatScale(aa,a->B);
910:   return(0);
911: }

913: int MatGetRow_MPISBAIJ(Mat matin,int row,int *nz,int **idx,PetscScalar **v)
914: {
915:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
916:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
917:   int            bs = mat->bs,bs2 = mat->bs2,i,ierr,*cworkA,*cworkB,**pcA,**pcB;
918:   int            nztot,nzA,nzB,lrow,brstart = mat->rstart*bs,brend = mat->rend*bs;
919:   int            *cmap,*idx_p,cstart = mat->cstart;

922:   if (mat->getrowactive == PETSC_TRUE) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Already active");
923:   mat->getrowactive = PETSC_TRUE;

925:   if (!mat->rowvalues && (idx || v)) {
926:     /*
927:         allocate enough space to hold information from the longest row.
928:     */
929:     Mat_SeqSBAIJ *Aa = (Mat_SeqSBAIJ*)mat->A->data;
930:     Mat_SeqBAIJ  *Ba = (Mat_SeqBAIJ*)mat->B->data;
931:     int     max = 1,mbs = mat->mbs,tmp;
932:     for (i=0; i<mbs; i++) {
933:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i]; /* row length */
934:       if (max < tmp) { max = tmp; }
935:     }
936:     PetscMalloc(max*bs2*(sizeof(int)+sizeof(PetscScalar)),&mat->rowvalues);
937:     mat->rowindices = (int*)(mat->rowvalues + max*bs2);
938:   }
939: 
940:   if (row < brstart || row >= brend) SETERRQ(PETSC_ERR_SUP,"Only local rows")
941:   lrow = row - brstart;  /* local row index */

943:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
944:   if (!v)   {pvA = 0; pvB = 0;}
945:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
946:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
947:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
948:   nztot = nzA + nzB;

950:   cmap  = mat->garray;
951:   if (v  || idx) {
952:     if (nztot) {
953:       /* Sort by increasing column numbers, assuming A and B already sorted */
954:       int imark = -1;
955:       if (v) {
956:         *v = v_p = mat->rowvalues;
957:         for (i=0; i<nzB; i++) {
958:           if (cmap[cworkB[i]/bs] < cstart)   v_p[i] = vworkB[i];
959:           else break;
960:         }
961:         imark = i;
962:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
963:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
964:       }
965:       if (idx) {
966:         *idx = idx_p = mat->rowindices;
967:         if (imark > -1) {
968:           for (i=0; i<imark; i++) {
969:             idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
970:           }
971:         } else {
972:           for (i=0; i<nzB; i++) {
973:             if (cmap[cworkB[i]/bs] < cstart)
974:               idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
975:             else break;
976:           }
977:           imark = i;
978:         }
979:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart*bs + cworkA[i];
980:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
981:       }
982:     } else {
983:       if (idx) *idx = 0;
984:       if (v)   *v   = 0;
985:     }
986:   }
987:   *nz = nztot;
988:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
989:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
990:   return(0);
991: }

993: int MatRestoreRow_MPISBAIJ(Mat mat,int row,int *nz,int **idx,PetscScalar **v)
994: {
995:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;

998:   if (baij->getrowactive == PETSC_FALSE) {
999:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"MatGetRow not called");
1000:   }
1001:   baij->getrowactive = PETSC_FALSE;
1002:   return(0);
1003: }

1005: int MatGetBlockSize_MPISBAIJ(Mat mat,int *bs)
1006: {
1007:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;

1010:   *bs = baij->bs;
1011:   return(0);
1012: }

1014: int MatZeroEntries_MPISBAIJ(Mat A)
1015: {
1016:   Mat_MPISBAIJ *l = (Mat_MPISBAIJ*)A->data;
1017:   int         ierr;

1020:   MatZeroEntries(l->A);
1021:   MatZeroEntries(l->B);
1022:   return(0);
1023: }

1025: int MatGetInfo_MPISBAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1026: {
1027:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)matin->data;
1028:   Mat         A = a->A,B = a->B;
1029:   int         ierr;
1030:   PetscReal   isend[5],irecv[5];

1033:   info->block_size     = (PetscReal)a->bs;
1034:   MatGetInfo(A,MAT_LOCAL,info);
1035:   isend[0] = info->nz_used; isend[1] = info->nz_allocated; isend[2] = info->nz_unneeded;
1036:   isend[3] = info->memory;  isend[4] = info->mallocs;
1037:   MatGetInfo(B,MAT_LOCAL,info);
1038:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1039:   isend[3] += info->memory;  isend[4] += info->mallocs;
1040:   if (flag == MAT_LOCAL) {
1041:     info->nz_used      = isend[0];
1042:     info->nz_allocated = isend[1];
1043:     info->nz_unneeded  = isend[2];
1044:     info->memory       = isend[3];
1045:     info->mallocs      = isend[4];
1046:   } else if (flag == MAT_GLOBAL_MAX) {
1047:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_MAX,matin->comm);
1048:     info->nz_used      = irecv[0];
1049:     info->nz_allocated = irecv[1];
1050:     info->nz_unneeded  = irecv[2];
1051:     info->memory       = irecv[3];
1052:     info->mallocs      = irecv[4];
1053:   } else if (flag == MAT_GLOBAL_SUM) {
1054:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_SUM,matin->comm);
1055:     info->nz_used      = irecv[0];
1056:     info->nz_allocated = irecv[1];
1057:     info->nz_unneeded  = irecv[2];
1058:     info->memory       = irecv[3];
1059:     info->mallocs      = irecv[4];
1060:   } else {
1061:     SETERRQ1(1,"Unknown MatInfoType argument %d",flag);
1062:   }
1063:   info->rows_global       = (PetscReal)A->M;
1064:   info->columns_global    = (PetscReal)A->N;
1065:   info->rows_local        = (PetscReal)A->m;
1066:   info->columns_local     = (PetscReal)A->N;
1067:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1068:   info->fill_ratio_needed = 0;
1069:   info->factor_mallocs    = 0;
1070:   return(0);
1071: }

1073: int MatSetOption_MPISBAIJ(Mat A,MatOption op)
1074: {
1075:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
1076:   int         ierr;

1079:   switch (op) {
1080:   case MAT_NO_NEW_NONZERO_LOCATIONS:
1081:   case MAT_YES_NEW_NONZERO_LOCATIONS:
1082:   case MAT_COLUMNS_UNSORTED:
1083:   case MAT_COLUMNS_SORTED:
1084:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1085:   case MAT_KEEP_ZEROED_ROWS:
1086:   case MAT_NEW_NONZERO_LOCATION_ERR:
1087:     MatSetOption(a->A,op);
1088:     MatSetOption(a->B,op);
1089:     break;
1090:   case MAT_ROW_ORIENTED:
1091:     a->roworiented = PETSC_TRUE;
1092:     MatSetOption(a->A,op);
1093:     MatSetOption(a->B,op);
1094:     break;
1095:   case MAT_ROWS_SORTED:
1096:   case MAT_ROWS_UNSORTED:
1097:   case MAT_YES_NEW_DIAGONALS:
1098:   case MAT_USE_SINGLE_PRECISION_SOLVES:
1099:     PetscLogInfo(A,"Info:MatSetOption_MPIBAIJ:Option ignoredn");
1100:     break;
1101:   case MAT_COLUMN_ORIENTED:
1102:     a->roworiented = PETSC_FALSE;
1103:     MatSetOption(a->A,op);
1104:     MatSetOption(a->B,op);
1105:     break;
1106:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1107:     a->donotstash = PETSC_TRUE;
1108:     break;
1109:   case MAT_NO_NEW_DIAGONALS:
1110:     SETERRQ(PETSC_ERR_SUP,"MAT_NO_NEW_DIAGONALS");
1111:   case MAT_USE_HASH_TABLE:
1112:     a->ht_flag = PETSC_TRUE;
1113:     break;
1114:   default:
1115:     SETERRQ(PETSC_ERR_SUP,"unknown option");
1116:   }
1117:   return(0);
1118: }

1120: int MatTranspose_MPISBAIJ(Mat A,Mat *matout)
1121: {
1123:   SETERRQ(1,"Matrix is symmetric. MatTranspose() should not be called");
1124:   /* return(0); */
1125: }

1127: int MatDiagonalScale_MPISBAIJ(Mat mat,Vec ll,Vec rr)
1128: {
1129:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
1130:   Mat         a = baij->A,b = baij->B;
1131:   int         ierr,s1,s2,s3;

1134:   if (ll != rr) {
1135:     SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"For symmetric format, left and right scaling vectors must be samen");
1136:   }
1137:   MatGetLocalSize(mat,&s2,&s3);
1138:   if (rr) {
1139:     VecGetLocalSize(rr,&s1);
1140:     if (s1!=s3) SETERRQ(PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
1141:     /* Overlap communication with computation. */
1142:     VecScatterBegin(rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD,baij->Mvctx);
1143:     /*} if (ll) { */
1144:     VecGetLocalSize(ll,&s1);
1145:     if (s1!=s2) SETERRQ(PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
1146:     (*b->ops->diagonalscale)(b,ll,PETSC_NULL);
1147:     /* } */
1148:   /* scale  the diagonal block */
1149:   (*a->ops->diagonalscale)(a,ll,rr);

1151:   /* if (rr) { */
1152:     /* Do a scatter end and then right scale the off-diagonal block */
1153:     VecScatterEnd(rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD,baij->Mvctx);
1154:     (*b->ops->diagonalscale)(b,PETSC_NULL,baij->lvec);
1155:   }
1156: 
1157:   return(0);
1158: }

1160: int MatZeroRows_MPISBAIJ(Mat A,IS is,PetscScalar *diag)
1161: {
1162:   Mat_MPISBAIJ   *l = (Mat_MPISBAIJ*)A->data;
1163:   int            i,ierr,N,*rows,*owners = l->rowners,size = l->size;
1164:   int            *procs,*nprocs,j,idx,nsends,*work,row;
1165:   int            nmax,*svalues,*starts,*owner,nrecvs,rank = l->rank;
1166:   int            *rvalues,tag = A->tag,count,base,slen,n,*source;
1167:   int            *lens,imdex,*lrows,*values,bs=l->bs,rstart_bs=l->rstart_bs;
1168:   MPI_Comm       comm = A->comm;
1169:   MPI_Request    *send_waits,*recv_waits;
1170:   MPI_Status     recv_status,*send_status;
1171:   IS             istmp;
1172:   PetscTruth     found;

1175:   ISGetSize(is,&N);
1176:   ISGetIndices(is,&rows);
1177: 
1178:   /*  first count number of contributors to each processor */
1179:   ierr  = PetscMalloc(2*size*sizeof(int),&nprocs);
1180:   ierr  = PetscMemzero(nprocs,2*size*sizeof(int));
1181:   procs = nprocs + size;
1182:   ierr  = PetscMalloc((N+1)*sizeof(int),&owner); /* see note*/
1183:   for (i=0; i<N; i++) {
1184:     idx   = rows[i];
1185:     found = PETSC_FALSE;
1186:     for (j=0; j<size; j++) {
1187:       if (idx >= owners[j]*bs && idx < owners[j+1]*bs) {
1188:         nprocs[j]++; procs[j] = 1; owner[i] = j; found = PETSC_TRUE; break;
1189:       }
1190:     }
1191:     if (!found) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Index out of range");
1192:   }
1193:   nsends = 0;  for (i=0; i<size; i++) { nsends += procs[i];}
1194: 
1195:   /* inform other processors of number of messages and max length*/
1196:   ierr   = PetscMalloc(2*size*sizeof(int),&work);
1197:   ierr   = MPI_Allreduce(nprocs,work,2*size,MPI_INT,PetscMaxSum_Op,comm);
1198:   nmax   = work[rank];
1199:   nrecvs = work[size+rank];
1200:   ierr   = PetscFree(work);
1201: 
1202:   /* post receives:   */
1203:   PetscMalloc((nrecvs+1)*(nmax+1)*sizeof(int),&rvalues);
1204:   PetscMalloc((nrecvs+1)*sizeof(MPI_Request),&recv_waits);
1205:   for (i=0; i<nrecvs; i++) {
1206:     MPI_Irecv(rvalues+nmax*i,nmax,MPI_INT,MPI_ANY_SOURCE,tag,comm,recv_waits+i);
1207:   }
1208: 
1209:   /* do sends:
1210:      1) starts[i] gives the starting index in svalues for stuff going to 
1211:      the ith processor
1212:   */
1213:   PetscMalloc((N+1)*sizeof(int),&svalues);
1214:   PetscMalloc((nsends+1)*sizeof(MPI_Request),&send_waits);
1215:   PetscMalloc((size+1)*sizeof(int),&starts);
1216:   starts[0]  = 0;
1217:   for (i=1; i<size; i++) { starts[i] = starts[i-1] + nprocs[i-1];}
1218:   for (i=0; i<N; i++) {
1219:     svalues[starts[owner[i]]++] = rows[i];
1220:   }
1221:   ISRestoreIndices(is,&rows);
1222: 
1223:   starts[0] = 0;
1224:   for (i=1; i<size+1; i++) { starts[i] = starts[i-1] + nprocs[i-1];}
1225:   count = 0;
1226:   for (i=0; i<size; i++) {
1227:     if (procs[i]) {
1228:       MPI_Isend(svalues+starts[i],nprocs[i],MPI_INT,i,tag,comm,send_waits+count++);
1229:     }
1230:   }
1231:   PetscFree(starts);

1233:   base = owners[rank]*bs;
1234: 
1235:   /*  wait on receives */
1236:   ierr   = PetscMalloc(2*(nrecvs+1)*sizeof(int),&lens);
1237:   source = lens + nrecvs;
1238:   count  = nrecvs; slen = 0;
1239:   while (count) {
1240:     MPI_Waitany(nrecvs,recv_waits,&imdex,&recv_status);
1241:     /* unpack receives into our local space */
1242:     MPI_Get_count(&recv_status,MPI_INT,&n);
1243:     source[imdex]  = recv_status.MPI_SOURCE;
1244:     lens[imdex]    = n;
1245:     slen          += n;
1246:     count--;
1247:   }
1248:   PetscFree(recv_waits);
1249: 
1250:   /* move the data into the send scatter */
1251:   PetscMalloc((slen+1)*sizeof(int),&lrows);
1252:   count = 0;
1253:   for (i=0; i<nrecvs; i++) {
1254:     values = rvalues + i*nmax;
1255:     for (j=0; j<lens[i]; j++) {
1256:       lrows[count++] = values[j] - base;
1257:     }
1258:   }
1259:   PetscFree(rvalues);
1260:   PetscFree(lens);
1261:   PetscFree(owner);
1262:   PetscFree(nprocs);
1263: 
1264:   /* actually zap the local rows */
1265:   ISCreateGeneral(PETSC_COMM_SELF,slen,lrows,&istmp);
1266:   PetscLogObjectParent(A,istmp);

1268:   /*
1269:         Zero the required rows. If the "diagonal block" of the matrix
1270:      is square and the user wishes to set the diagonal we use seperate
1271:      code so that MatSetValues() is not called for each diagonal allocating
1272:      new memory, thus calling lots of mallocs and slowing things down.

1274:        Contributed by: Mathew Knepley
1275:   */
1276:   /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
1277:   MatZeroRows_SeqBAIJ(l->B,istmp,0);
1278:   if (diag && (l->A->M == l->A->N)) {
1279:     MatZeroRows_SeqSBAIJ(l->A,istmp,diag);
1280:   } else if (diag) {
1281:     MatZeroRows_SeqSBAIJ(l->A,istmp,0);
1282:     if (((Mat_SeqSBAIJ*)l->A->data)->nonew) {
1283:       SETERRQ(PETSC_ERR_SUP,"MatZeroRows() on rectangular matrices cannot be used with the Mat options n
1284: MAT_NO_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
1285:     }
1286:     for (i=0; i<slen; i++) {
1287:       row  = lrows[i] + rstart_bs;
1288:       MatSetValues(A,1,&row,1,&row,diag,INSERT_VALUES);
1289:     }
1290:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1291:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1292:   } else {
1293:     MatZeroRows_SeqSBAIJ(l->A,istmp,0);
1294:   }

1296:   ISDestroy(istmp);
1297:   PetscFree(lrows);

1299:   /* wait on sends */
1300:   if (nsends) {
1301:     PetscMalloc(nsends*sizeof(MPI_Status),&send_status);
1302:     ierr        = MPI_Waitall(nsends,send_waits,send_status);
1303:     ierr        = PetscFree(send_status);
1304:   }
1305:   PetscFree(send_waits);
1306:   PetscFree(svalues);

1308:   return(0);
1309: }

1311: int MatPrintHelp_MPISBAIJ(Mat A)
1312: {
1313:   Mat_MPISBAIJ *a   = (Mat_MPISBAIJ*)A->data;
1314:   MPI_Comm    comm = A->comm;
1315:   static int  called = 0;
1316:   int         ierr;

1319:   if (!a->rank) {
1320:     MatPrintHelp_SeqSBAIJ(a->A);
1321:   }
1322:   if (called) {return(0);} else called = 1;
1323:   (*PetscHelpPrintf)(comm," Options for MATMPISBAIJ matrix format (the defaults):n");
1324:   (*PetscHelpPrintf)(comm,"  -mat_use_hash_table <factor>: Use hashtable for efficient matrix assemblyn");
1325:   return(0);
1326: }

1328: int MatSetUnfactored_MPISBAIJ(Mat A)
1329: {
1330:   Mat_MPISBAIJ *a   = (Mat_MPISBAIJ*)A->data;
1331:   int         ierr;

1334:   MatSetUnfactored(a->A);
1335:   return(0);
1336: }

1338: static int MatDuplicate_MPISBAIJ(Mat,MatDuplicateOption,Mat *);

1340: int MatEqual_MPISBAIJ(Mat A,Mat B,PetscTruth *flag)
1341: {
1342:   Mat_MPISBAIJ *matB = (Mat_MPISBAIJ*)B->data,*matA = (Mat_MPISBAIJ*)A->data;
1343:   Mat         a,b,c,d;
1344:   PetscTruth  flg;
1345:   int         ierr;

1348:   PetscTypeCompare((PetscObject)B,MATMPISBAIJ,&flg);
1349:   if (!flg) SETERRQ(PETSC_ERR_ARG_INCOMP,"Matrices must be same type");
1350:   a = matA->A; b = matA->B;
1351:   c = matB->A; d = matB->B;

1353:   MatEqual(a,c,&flg);
1354:   if (flg == PETSC_TRUE) {
1355:     MatEqual(b,d,&flg);
1356:   }
1357:   MPI_Allreduce(&flg,flag,1,MPI_INT,MPI_LAND,A->comm);
1358:   return(0);
1359: }

1361: int MatSetUpPreallocation_MPISBAIJ(Mat A)
1362: {
1363:   int        ierr;

1366:   MatMPISBAIJSetPreallocation(A,1,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
1367:   return(0);
1368: }
1369: /* -------------------------------------------------------------------*/
1370: static struct _MatOps MatOps_Values = {
1371:   MatSetValues_MPISBAIJ,
1372:   MatGetRow_MPISBAIJ,
1373:   MatRestoreRow_MPISBAIJ,
1374:   MatMult_MPISBAIJ,
1375:   MatMultAdd_MPISBAIJ,
1376:   MatMultTranspose_MPISBAIJ,
1377:   MatMultTransposeAdd_MPISBAIJ,
1378:   0,
1379:   0,
1380:   0,
1381:   0,
1382:   0,
1383:   0,
1384:   MatRelax_MPISBAIJ,
1385:   MatTranspose_MPISBAIJ,
1386:   MatGetInfo_MPISBAIJ,
1387:   MatEqual_MPISBAIJ,
1388:   MatGetDiagonal_MPISBAIJ,
1389:   MatDiagonalScale_MPISBAIJ,
1390:   MatNorm_MPISBAIJ,
1391:   MatAssemblyBegin_MPISBAIJ,
1392:   MatAssemblyEnd_MPISBAIJ,
1393:   0,
1394:   MatSetOption_MPISBAIJ,
1395:   MatZeroEntries_MPISBAIJ,
1396:   MatZeroRows_MPISBAIJ,
1397:   0,
1398:   0,
1399:   0,
1400:   0,
1401:   MatSetUpPreallocation_MPISBAIJ,
1402:   0,
1403:   0,
1404:   0,
1405:   0,
1406:   MatDuplicate_MPISBAIJ,
1407:   0,
1408:   0,
1409:   0,
1410:   0,
1411:   0,
1412:   MatGetSubMatrices_MPISBAIJ,
1413:   MatIncreaseOverlap_MPISBAIJ,
1414:   MatGetValues_MPISBAIJ,
1415:   0,
1416:   MatPrintHelp_MPISBAIJ,
1417:   MatScale_MPISBAIJ,
1418:   0,
1419:   0,
1420:   0,
1421:   MatGetBlockSize_MPISBAIJ,
1422:   0,
1423:   0,
1424:   0,
1425:   0,
1426:   0,
1427:   0,
1428:   MatSetUnfactored_MPISBAIJ,
1429:   0,
1430:   MatSetValuesBlocked_MPISBAIJ,
1431:   0,
1432:   0,
1433:   0,
1434:   MatGetPetscMaps_Petsc,
1435:   0,
1436:   0,
1437:   0,
1438:   0,
1439:   0,
1440:   0,
1441:   MatGetRowMax_MPISBAIJ};


1444: EXTERN_C_BEGIN
1445: int MatGetDiagonalBlock_MPISBAIJ(Mat A,PetscTruth *iscopy,MatReuse reuse,Mat *a)
1446: {
1448:   *a      = ((Mat_MPISBAIJ *)A->data)->A;
1449:   *iscopy = PETSC_FALSE;
1450:   return(0);
1451: }
1452: EXTERN_C_END

1454: EXTERN_C_BEGIN
1455: int MatCreate_MPISBAIJ(Mat B)
1456: {
1457:   Mat_MPISBAIJ *b;
1458:   int          ierr;
1459:   PetscTruth   flg;


1463:   ierr    = PetscNew(Mat_MPISBAIJ,&b);
1464:   B->data = (void*)b;
1465:   ierr    = PetscMemzero(b,sizeof(Mat_MPISBAIJ));
1466:   ierr    = PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));

1468:   B->ops->destroy    = MatDestroy_MPISBAIJ;
1469:   B->ops->view       = MatView_MPISBAIJ;
1470:   B->mapping    = 0;
1471:   B->factor     = 0;
1472:   B->assembled  = PETSC_FALSE;

1474:   B->insertmode = NOT_SET_VALUES;
1475:   MPI_Comm_rank(B->comm,&b->rank);
1476:   MPI_Comm_size(B->comm,&b->size);

1478:   /* build local table of row and column ownerships */
1479:   ierr          = PetscMalloc(3*(b->size+2)*sizeof(int),&b->rowners);
1480:   b->cowners    = b->rowners + b->size + 2;
1481:   b->rowners_bs = b->cowners + b->size + 2;
1482:   PetscLogObjectMemory(B,3*(b->size+2)*sizeof(int)+sizeof(struct _p_Mat)+sizeof(Mat_MPISBAIJ));

1484:   /* build cache for off array entries formed */
1485:   MatStashCreate_Private(B->comm,1,&B->stash);
1486:   b->donotstash  = PETSC_FALSE;
1487:   b->colmap      = PETSC_NULL;
1488:   b->garray      = PETSC_NULL;
1489:   b->roworiented = PETSC_TRUE;

1491: #if defined(PETSC_USE_MAT_SINGLE)
1492:   /* stuff for MatSetValues_XXX in single precision */
1493:   b->setvalueslen     = 0;
1494:   b->setvaluescopy    = PETSC_NULL;
1495: #endif

1497:   /* stuff used in block assembly */
1498:   b->barray       = 0;

1500:   /* stuff used for matrix vector multiply */
1501:   b->lvec         = 0;
1502:   b->Mvctx        = 0;

1504:   /* stuff for MatGetRow() */
1505:   b->rowindices   = 0;
1506:   b->rowvalues    = 0;
1507:   b->getrowactive = PETSC_FALSE;

1509:   /* hash table stuff */
1510:   b->ht           = 0;
1511:   b->hd           = 0;
1512:   b->ht_size      = 0;
1513:   b->ht_flag      = PETSC_FALSE;
1514:   b->ht_fact      = 0;
1515:   b->ht_total_ct  = 0;
1516:   b->ht_insert_ct = 0;

1518:   PetscOptionsHasName(PETSC_NULL,"-mat_use_hash_table",&flg);
1519:   if (flg) {
1520:     PetscReal fact = 1.39;
1521:     MatSetOption(B,MAT_USE_HASH_TABLE);
1522:     PetscOptionsGetReal(PETSC_NULL,"-mat_use_hash_table",&fact,PETSC_NULL);
1523:     if (fact <= 1.0) fact = 1.39;
1524:     MatMPIBAIJSetHashTableFactor(B,fact);
1525:     PetscLogInfo(0,"MatCreateMPISBAIJ:Hash table Factor used %5.2fn",fact);
1526:   }
1527:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatStoreValues_C",
1528:                                      "MatStoreValues_MPISBAIJ",
1529:                                      MatStoreValues_MPISBAIJ);
1530:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatRetrieveValues_C",
1531:                                      "MatRetrieveValues_MPISBAIJ",
1532:                                      MatRetrieveValues_MPISBAIJ);
1533:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetDiagonalBlock_C",
1534:                                      "MatGetDiagonalBlock_MPISBAIJ",
1535:                                      MatGetDiagonalBlock_MPISBAIJ);
1536:   return(0);
1537: }
1538: EXTERN_C_END

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

1546:    Collective on Mat

1548:    Input Parameters:
1549: +  A - the matrix 
1550: .  bs   - size of blockk
1551: .  d_nz  - number of block nonzeros per block row in diagonal portion of local 
1552:            submatrix  (same for all local rows)
1553: .  d_nnz - array containing the number of block nonzeros in the various block rows 
1554:            of the in diagonal portion of the local (possibly different for each block
1555:            row) or PETSC_NULL.  You must leave room for the diagonal entry even if it is zero.
1556: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1557:            submatrix (same for all local rows).
1558: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1559:            off-diagonal portion of the local submatrix (possibly different for
1560:            each block row) or PETSC_NULL.


1563:    Options Database Keys:
1564: .   -mat_no_unroll - uses code that does not unroll the loops in the 
1565:                      block calculations (much slower)
1566: .   -mat_block_size - size of the blocks to use

1568:    Notes:

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

1573:    Storage Information:
1574:    For a square global matrix we define each processor's diagonal portion 
1575:    to be its local rows and the corresponding columns (a square submatrix);  
1576:    each processor's off-diagonal portion encompasses the remainder of the
1577:    local matrix (a rectangular submatrix). 

1579:    The user can specify preallocated storage for the diagonal part of
1580:    the local submatrix with either d_nz or d_nnz (not both).  Set 
1581:    d_nz=PETSC_DEFAULT and d_nnz=PETSC_NULL for PETSc to control dynamic
1582:    memory allocation.  Likewise, specify preallocated storage for the
1583:    off-diagonal part of the local submatrix with o_nz or o_nnz (not both).

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

1588: .vb
1589:            0 1 2 3 4 5 6 7 8 9 10 11
1590:           -------------------
1591:    row 3  |  o o o d d d o o o o o o
1592:    row 4  |  o o o d d d o o o o o o
1593:    row 5  |  o o o d d d o o o o o o
1594:           -------------------
1595: .ve
1596:   
1597:    Thus, any entries in the d locations are stored in the d (diagonal) 
1598:    submatrix, and any entries in the o locations are stored in the
1599:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
1600:    stored simply in the MATSEQBAIJ format for compressed row storage.

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

1609:    Level: intermediate

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

1613: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateMPIBAIJ()
1614: @*/

1616: int MatMPISBAIJSetPreallocation(Mat B,int bs,int d_nz,int *d_nnz,int o_nz,int *o_nnz)
1617: {
1618:   Mat_MPISBAIJ *b;
1619:   int          ierr,i,mbs,Mbs;
1620:   PetscTruth   flg2;

1623:   PetscTypeCompare((PetscObject)B,MATMPISBAIJ,&flg2);
1624:   if (!flg2) return(0);

1626:   PetscOptionsGetInt(PETSC_NULL,"-mat_block_size",&bs,PETSC_NULL);

1628:   if (bs < 1) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Invalid block size specified, must be positive");
1629:   if (d_nz == PETSC_DECIDE || d_nz == PETSC_DEFAULT) d_nz = 3;
1630:   if (o_nz == PETSC_DECIDE || o_nz == PETSC_DEFAULT) o_nz = 1;
1631:   if (d_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"d_nz cannot be less than 0: value %d",d_nz);
1632:   if (o_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"o_nz cannot be less than 0: value %d",o_nz);
1633:   if (d_nnz) {
1634:     for (i=0; i<B->m/bs; i++) {
1635:       if (d_nnz[i] < 0) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"d_nnz cannot be less than -1: local row %d value %d",i,d_nnz[i]);
1636:     }
1637:   }
1638:   if (o_nnz) {
1639:     for (i=0; i<B->m/bs; i++) {
1640:       if (o_nnz[i] < 0) SETERRQ2(PETSC_ERR_ARG_OUTOFRANGE,"o_nnz cannot be less than -1: local row %d value %d",i,o_nnz[i]);
1641:     }
1642:   }
1643:   B->preallocated = PETSC_TRUE;
1644:   PetscSplitOwnershipBlock(B->comm,bs,&B->m,&B->M);
1645:   PetscSplitOwnershipBlock(B->comm,bs,&B->n,&B->N);
1646:   PetscMapCreateMPI(B->comm,B->m,B->M,&B->rmap);
1647:   PetscMapCreateMPI(B->comm,B->m,B->M,&B->cmap);

1649:   b   = (Mat_MPISBAIJ*)B->data;
1650:   mbs = B->m/bs;
1651:   Mbs = B->M/bs;
1652:   if (mbs*bs != B->m) {
1653:     SETERRQ2(PETSC_ERR_ARG_SIZ,"No of local rows %d must be divisible by blocksize %d",B->m,bs);
1654:   }

1656:   b->bs  = bs;
1657:   b->bs2 = bs*bs;
1658:   b->mbs = mbs;
1659:   b->nbs = mbs;
1660:   b->Mbs = Mbs;
1661:   b->Nbs = Mbs;

1663:   MPI_Allgather(&b->mbs,1,MPI_INT,b->rowners+1,1,MPI_INT,B->comm);
1664:   b->rowners[0]    = 0;
1665:   for (i=2; i<=b->size; i++) {
1666:     b->rowners[i] += b->rowners[i-1];
1667:   }
1668:   b->rstart    = b->rowners[b->rank];
1669:   b->rend      = b->rowners[b->rank+1];
1670:   b->cstart    = b->rstart;
1671:   b->cend      = b->rend;
1672:   for (i=0; i<=b->size; i++) {
1673:     b->rowners_bs[i] = b->rowners[i]*bs;
1674:   }
1675:   b->rstart_bs = b-> rstart*bs;
1676:   b->rend_bs   = b->rend*bs;
1677: 
1678:   b->cstart_bs = b->cstart*bs;
1679:   b->cend_bs   = b->cend*bs;
1680: 

1682:   MatCreateSeqSBAIJ(PETSC_COMM_SELF,bs,B->m,B->m,d_nz,d_nnz,&b->A);
1683:   PetscLogObjectParent(B,b->A);
1684:   MatCreateSeqBAIJ(PETSC_COMM_SELF,bs,B->m,B->M,o_nz,o_nnz,&b->B);
1685:   PetscLogObjectParent(B,b->B);

1687:   /* build cache for off array entries formed */
1688:   MatStashCreate_Private(B->comm,bs,&B->bstash);

1690:   return(0);
1691: }

1693: /*@C
1694:    MatCreateMPISBAIJ - Creates a sparse parallel matrix in symmetric block AIJ format
1695:    (block compressed row).  For good matrix assembly performance
1696:    the user should preallocate the matrix storage by setting the parameters 
1697:    d_nz (or d_nnz) and o_nz (or o_nnz).  By setting these parameters accurately,
1698:    performance can be increased by more than a factor of 50.

1700:    Collective on MPI_Comm

1702:    Input Parameters:
1703: +  comm - MPI communicator
1704: .  bs   - size of blockk
1705: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
1706:            This value should be the same as the local size used in creating the 
1707:            y vector for the matrix-vector product y = Ax.
1708: .  n - number of local columns (or PETSC_DECIDE to have calculated if N is given)
1709:            This value should be the same as the local size used in creating the 
1710:            x vector for the matrix-vector product y = Ax.
1711: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
1712: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
1713: .  d_nz  - number of block nonzeros per block row in diagonal portion of local 
1714:            submatrix  (same for all local rows)
1715: .  d_nnz - array containing the number of block nonzeros in the various block rows 
1716:            of the in diagonal portion of the local (possibly different for each block
1717:            row) or PETSC_NULL.  You must leave room for the diagonal entry even if it is zero.
1718: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1719:            submatrix (same for all local rows).
1720: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1721:            off-diagonal portion of the local submatrix (possibly different for
1722:            each block row) or PETSC_NULL.

1724:    Output Parameter:
1725: .  A - the matrix 

1727:    Options Database Keys:
1728: .   -mat_no_unroll - uses code that does not unroll the loops in the 
1729:                      block calculations (much slower)
1730: .   -mat_block_size - size of the blocks to use
1731: .   -mat_mpi - use the parallel matrix data structures even on one processor 
1732:                (defaults to using SeqBAIJ format on one processor)

1734:    Notes:
1735:    The user MUST specify either the local or global matrix dimensions
1736:    (possibly both).

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

1741:    Storage Information:
1742:    For a square global matrix we define each processor's diagonal portion 
1743:    to be its local rows and the corresponding columns (a square submatrix);  
1744:    each processor's off-diagonal portion encompasses the remainder of the
1745:    local matrix (a rectangular submatrix). 

1747:    The user can specify preallocated storage for the diagonal part of
1748:    the local submatrix with either d_nz or d_nnz (not both).  Set 
1749:    d_nz=PETSC_DEFAULT and d_nnz=PETSC_NULL for PETSc to control dynamic
1750:    memory allocation.  Likewise, specify preallocated storage for the
1751:    off-diagonal part of the local submatrix with o_nz or o_nnz (not both).

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

1756: .vb
1757:            0 1 2 3 4 5 6 7 8 9 10 11
1758:           -------------------
1759:    row 3  |  o o o d d d o o o o o o
1760:    row 4  |  o o o d d d o o o o o o
1761:    row 5  |  o o o d d d o o o o o o
1762:           -------------------
1763: .ve
1764:   
1765:    Thus, any entries in the d locations are stored in the d (diagonal) 
1766:    submatrix, and any entries in the o locations are stored in the
1767:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
1768:    stored simply in the MATSEQBAIJ format for compressed row storage.

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

1777:    Level: intermediate

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

1781: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateMPIBAIJ()
1782: @*/

1784: int MatCreateMPISBAIJ(MPI_Comm comm,int bs,int m,int n,int M,int N,int d_nz,int *d_nnz,int o_nz,int *o_nnz,Mat *A)
1785: {
1786:   int ierr,size;

1789:   MatCreate(comm,m,n,M,N,A);
1790:   MPI_Comm_size(comm,&size);
1791:   if (size > 1) {
1792:     MatSetType(*A,MATMPISBAIJ);
1793:     MatMPISBAIJSetPreallocation(*A,bs,d_nz,d_nnz,o_nz,o_nnz);
1794:   } else {
1795:     MatSetType(*A,MATSEQSBAIJ);
1796:     MatSeqSBAIJSetPreallocation(*A,bs,d_nz,d_nnz);
1797:   }
1798:   return(0);
1799: }


1802: static int MatDuplicate_MPISBAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
1803: {
1804:   Mat          mat;
1805:   Mat_MPISBAIJ *a,*oldmat = (Mat_MPISBAIJ*)matin->data;
1806:   int          ierr,len=0;

1809:   *newmat       = 0;
1810:   MatCreate(matin->comm,matin->m,matin->n,matin->M,matin->N,&mat);
1811:   MatSetType(mat,MATMPISBAIJ);
1812:   mat->preallocated = PETSC_TRUE;
1813:   a = (Mat_MPISBAIJ*)mat->data;
1814:   a->bs  = oldmat->bs;
1815:   a->bs2 = oldmat->bs2;
1816:   a->mbs = oldmat->mbs;
1817:   a->nbs = oldmat->nbs;
1818:   a->Mbs = oldmat->Mbs;
1819:   a->Nbs = oldmat->Nbs;
1820: 
1821:   a->rstart       = oldmat->rstart;
1822:   a->rend         = oldmat->rend;
1823:   a->cstart       = oldmat->cstart;
1824:   a->cend         = oldmat->cend;
1825:   a->size         = oldmat->size;
1826:   a->rank         = oldmat->rank;
1827:   a->donotstash   = oldmat->donotstash;
1828:   a->roworiented  = oldmat->roworiented;
1829:   a->rowindices   = 0;
1830:   a->rowvalues    = 0;
1831:   a->getrowactive = PETSC_FALSE;
1832:   a->barray       = 0;
1833:   a->rstart_bs    = oldmat->rstart_bs;
1834:   a->rend_bs      = oldmat->rend_bs;
1835:   a->cstart_bs    = oldmat->cstart_bs;
1836:   a->cend_bs      = oldmat->cend_bs;

1838:   /* hash table stuff */
1839:   a->ht           = 0;
1840:   a->hd           = 0;
1841:   a->ht_size      = 0;
1842:   a->ht_flag      = oldmat->ht_flag;
1843:   a->ht_fact      = oldmat->ht_fact;
1844:   a->ht_total_ct  = 0;
1845:   a->ht_insert_ct = 0;

1847:   PetscMalloc(3*(a->size+2)*sizeof(int),&a->rowners);
1848:   PetscLogObjectMemory(mat,3*(a->size+2)*sizeof(int)+sizeof(struct _p_Mat)+sizeof(Mat_MPISBAIJ));
1849:   a->cowners    = a->rowners + a->size + 2;
1850:   a->rowners_bs = a->cowners + a->size + 2;
1851:   PetscMemcpy(a->rowners,oldmat->rowners,3*(a->size+2)*sizeof(int));
1852:   MatStashCreate_Private(matin->comm,1,&mat->stash);
1853:   MatStashCreate_Private(matin->comm,oldmat->bs,&mat->bstash);
1854:   if (oldmat->colmap) {
1855: #if defined (PETSC_USE_CTABLE)
1856:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
1857: #else
1858:     PetscMalloc((a->Nbs)*sizeof(int),&a->colmap);
1859:     PetscLogObjectMemory(mat,(a->Nbs)*sizeof(int));
1860:     PetscMemcpy(a->colmap,oldmat->colmap,(a->Nbs)*sizeof(int));
1861: #endif
1862:   } else a->colmap = 0;
1863:   if (oldmat->garray && (len = ((Mat_SeqBAIJ*)(oldmat->B->data))->nbs)) {
1864:     PetscMalloc(len*sizeof(int),&a->garray);
1865:     PetscLogObjectMemory(mat,len*sizeof(int));
1866:     PetscMemcpy(a->garray,oldmat->garray,len*sizeof(int));
1867:   } else a->garray = 0;
1868: 
1869:    VecDuplicate(oldmat->lvec,&a->lvec);
1870:   PetscLogObjectParent(mat,a->lvec);
1871:    VecScatterCopy(oldmat->Mvctx,&a->Mvctx);

1873:   PetscLogObjectParent(mat,a->Mvctx);
1874:    MatDuplicate(oldmat->A,cpvalues,&a->A);
1875:   PetscLogObjectParent(mat,a->A);
1876:    MatDuplicate(oldmat->B,cpvalues,&a->B);
1877:   PetscLogObjectParent(mat,a->B);
1878:   PetscFListDuplicate(mat->qlist,&matin->qlist);
1879:   *newmat = mat;
1880:   return(0);
1881: }

1883: #include "petscsys.h"

1885: EXTERN_C_BEGIN
1886: int MatLoad_MPISBAIJ(PetscViewer viewer,MatType type,Mat *newmat)
1887: {
1888:   Mat          A;
1889:   int          i,nz,ierr,j,rstart,rend,fd;
1890:   PetscScalar  *vals,*buf;
1891:   MPI_Comm     comm = ((PetscObject)viewer)->comm;
1892:   MPI_Status   status;
1893:   int          header[4],rank,size,*rowlengths = 0,M,N,m,*rowners,*browners,maxnz,*cols;
1894:   int          *locrowlens,*sndcounts = 0,*procsnz = 0,jj,*mycols,*ibuf;
1895:   int          tag = ((PetscObject)viewer)->tag,bs=1,Mbs,mbs,extra_rows;
1896:   int          *dlens,*odlens,*mask,*masked1,*masked2,rowcount,odcount;
1897:   int          dcount,kmax,k,nzcount,tmp;
1898: 
1900:   PetscOptionsGetInt(PETSC_NULL,"-matload_block_size",&bs,PETSC_NULL);

1902:   MPI_Comm_size(comm,&size);
1903:   MPI_Comm_rank(comm,&rank);
1904:   if (!rank) {
1905:     PetscViewerBinaryGetDescriptor(viewer,&fd);
1906:     PetscBinaryRead(fd,(char *)header,4,PETSC_INT);
1907:     if (header[0] != MAT_FILE_COOKIE) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
1908:     if (header[3] < 0) {
1909:       SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format, cannot load as MPISBAIJ");
1910:     }
1911:   }

1913:   MPI_Bcast(header+1,3,MPI_INT,0,comm);
1914:   M = header[1]; N = header[2];

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

1918:   /* 
1919:      This code adds extra rows to make sure the number of rows is 
1920:      divisible by the blocksize
1921:   */
1922:   Mbs        = M/bs;
1923:   extra_rows = bs - M + bs*(Mbs);
1924:   if (extra_rows == bs) extra_rows = 0;
1925:   else                  Mbs++;
1926:   if (extra_rows &&!rank) {
1927:     PetscLogInfo(0,"MatLoad_MPISBAIJ:Padding loaded matrix to match blocksizen");
1928:   }

1930:   /* determine ownership of all rows */
1931:   mbs        = Mbs/size + ((Mbs % size) > rank);
1932:   m          = mbs*bs;
1933:   ierr       = PetscMalloc(2*(size+2)*sizeof(int),&rowners);
1934:   browners   = rowners + size + 1;
1935:   ierr       = MPI_Allgather(&mbs,1,MPI_INT,rowners+1,1,MPI_INT,comm);
1936:   rowners[0] = 0;
1937:   for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
1938:   for (i=0; i<=size;  i++) browners[i] = rowners[i]*bs;
1939:   rstart = rowners[rank];
1940:   rend   = rowners[rank+1];
1941: 
1942:   /* distribute row lengths to all processors */
1943:   PetscMalloc((rend-rstart)*bs*sizeof(int),&locrowlens);
1944:   if (!rank) {
1945:     PetscMalloc((M+extra_rows)*sizeof(int),&rowlengths);
1946:     PetscBinaryRead(fd,rowlengths,M,PETSC_INT);
1947:     for (i=0; i<extra_rows; i++) rowlengths[M+i] = 1;
1948:     PetscMalloc(size*sizeof(int),&sndcounts);
1949:     for (i=0; i<size; i++) sndcounts[i] = browners[i+1] - browners[i];
1950:     MPI_Scatterv(rowlengths,sndcounts,browners,MPI_INT,locrowlens,(rend-rstart)*bs,MPI_INT,0,comm);
1951:     PetscFree(sndcounts);
1952:   } else {
1953:     MPI_Scatterv(0,0,0,MPI_INT,locrowlens,(rend-rstart)*bs,MPI_INT,0,comm);
1954:   }
1955: 
1956:   if (!rank) {   /* procs[0] */
1957:     /* calculate the number of nonzeros on each processor */
1958:     PetscMalloc(size*sizeof(int),&procsnz);
1959:     PetscMemzero(procsnz,size*sizeof(int));
1960:     for (i=0; i<size; i++) {
1961:       for (j=rowners[i]*bs; j< rowners[i+1]*bs; j++) {
1962:         procsnz[i] += rowlengths[j];
1963:       }
1964:     }
1965:     PetscFree(rowlengths);
1966: 
1967:     /* determine max buffer needed and allocate it */
1968:     maxnz = 0;
1969:     for (i=0; i<size; i++) {
1970:       maxnz = PetscMax(maxnz,procsnz[i]);
1971:     }
1972:     PetscMalloc(maxnz*sizeof(int),&cols);

1974:     /* read in my part of the matrix column indices  */
1975:     nz     = procsnz[0];
1976:     ierr   = PetscMalloc(nz*sizeof(int),&ibuf);
1977:     mycols = ibuf;
1978:     if (size == 1)  nz -= extra_rows;
1979:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);
1980:     if (size == 1)  for (i=0; i< extra_rows; i++) { mycols[nz+i] = M+i; }

1982:     /* read in every ones (except the last) and ship off */
1983:     for (i=1; i<size-1; i++) {
1984:       nz   = procsnz[i];
1985:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
1986:       MPI_Send(cols,nz,MPI_INT,i,tag,comm);
1987:     }
1988:     /* read in the stuff for the last proc */
1989:     if (size != 1) {
1990:       nz   = procsnz[size-1] - extra_rows;  /* the extra rows are not on the disk */
1991:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
1992:       for (i=0; i<extra_rows; i++) cols[nz+i] = M+i;
1993:       MPI_Send(cols,nz+extra_rows,MPI_INT,size-1,tag,comm);
1994:     }
1995:     PetscFree(cols);
1996:   } else {  /* procs[i], i>0 */
1997:     /* determine buffer space needed for message */
1998:     nz = 0;
1999:     for (i=0; i<m; i++) {
2000:       nz += locrowlens[i];
2001:     }
2002:     ierr   = PetscMalloc(nz*sizeof(int),&ibuf);
2003:     mycols = ibuf;
2004:     /* receive message of column indices*/
2005:     MPI_Recv(mycols,nz,MPI_INT,0,tag,comm,&status);
2006:     MPI_Get_count(&status,MPI_INT,&maxnz);
2007:     if (maxnz != nz) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");
2008:   }

2010:   /* loop over local rows, determining number of off diagonal entries */
2011:   ierr     = PetscMalloc(2*(rend-rstart+1)*sizeof(int),&dlens);
2012:   odlens   = dlens + (rend-rstart);
2013:   ierr     = PetscMalloc(3*Mbs*sizeof(int),&mask);
2014:   ierr     = PetscMemzero(mask,3*Mbs*sizeof(int));
2015:   masked1  = mask    + Mbs;
2016:   masked2  = masked1 + Mbs;
2017:   rowcount = 0; nzcount = 0;
2018:   for (i=0; i<mbs; i++) {
2019:     dcount  = 0;
2020:     odcount = 0;
2021:     for (j=0; j<bs; j++) {
2022:       kmax = locrowlens[rowcount];
2023:       for (k=0; k<kmax; k++) {
2024:         tmp = mycols[nzcount++]/bs; /* block col. index */
2025:         if (!mask[tmp]) {
2026:           mask[tmp] = 1;
2027:           if (tmp < rstart || tmp >= rend) masked2[odcount++] = tmp; /* entry in off-diag portion */
2028:           else masked1[dcount++] = tmp; /* entry in diag portion */
2029:         }
2030:       }
2031:       rowcount++;
2032:     }
2033: 
2034:     dlens[i]  = dcount;  /* d_nzz[i] */
2035:     odlens[i] = odcount; /* o_nzz[i] */

2037:     /* zero out the mask elements we set */
2038:     for (j=0; j<dcount; j++) mask[masked1[j]] = 0;
2039:     for (j=0; j<odcount; j++) mask[masked2[j]] = 0;
2040:   }
2041: 
2042:   /* create our matrix */
2043:   MatCreateMPISBAIJ(comm,bs,m,m,PETSC_DETERMINE,PETSC_DETERMINE,0,dlens,0,odlens,newmat);
2044: 
2045:   A = *newmat;
2046:   MatSetOption(A,MAT_COLUMNS_SORTED);
2047: 
2048:   if (!rank) {
2049:     PetscMalloc(maxnz*sizeof(PetscScalar),&buf);
2050:     /* read in my part of the matrix numerical values  */
2051:     nz = procsnz[0];
2052:     vals = buf;
2053:     mycols = ibuf;
2054:     if (size == 1)  nz -= extra_rows;
2055:     PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2056:     if (size == 1)  for (i=0; i< extra_rows; i++) { vals[nz+i] = 1.0; }

2058:     /* insert into matrix */
2059:     jj      = rstart*bs;
2060:     for (i=0; i<m; i++) {
2061:       MatSetValues(A,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2062:       mycols += locrowlens[i];
2063:       vals   += locrowlens[i];
2064:       jj++;
2065:     }

2067:     /* read in other processors (except the last one) and ship out */
2068:     for (i=1; i<size-1; i++) {
2069:       nz   = procsnz[i];
2070:       vals = buf;
2071:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2072:       MPI_Send(vals,nz,MPIU_SCALAR,i,A->tag,comm);
2073:     }
2074:     /* the last proc */
2075:     if (size != 1){
2076:       nz   = procsnz[i] - extra_rows;
2077:       vals = buf;
2078:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2079:       for (i=0; i<extra_rows; i++) vals[nz+i] = 1.0;
2080:       MPI_Send(vals,nz+extra_rows,MPIU_SCALAR,size-1,A->tag,comm);
2081:     }
2082:     PetscFree(procsnz);

2084:   } else {
2085:     /* receive numeric values */
2086:     PetscMalloc(nz*sizeof(PetscScalar),&buf);

2088:     /* receive message of values*/
2089:     vals   = buf;
2090:     mycols = ibuf;
2091:     ierr   = MPI_Recv(vals,nz,MPIU_SCALAR,0,A->tag,comm,&status);
2092:     ierr   = MPI_Get_count(&status,MPIU_SCALAR,&maxnz);
2093:     if (maxnz != nz) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");

2095:     /* insert into matrix */
2096:     jj      = rstart*bs;
2097:     for (i=0; i<m; i++) {
2098:       ierr    = MatSetValues_MPISBAIJ(A,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2099:       mycols += locrowlens[i];
2100:       vals   += locrowlens[i];
2101:       jj++;
2102:     }
2103:   }

2105:   PetscFree(locrowlens);
2106:   PetscFree(buf);
2107:   PetscFree(ibuf);
2108:   PetscFree(rowners);
2109:   PetscFree(dlens);
2110:   PetscFree(mask);
2111:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2112:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2113:   return(0);
2114: }
2115: EXTERN_C_END

2117: /*@
2118:    MatMPISBAIJSetHashTableFactor - Sets the factor required to compute the size of the HashTable.

2120:    Input Parameters:
2121: .  mat  - the matrix
2122: .  fact - factor

2124:    Collective on Mat

2126:    Level: advanced

2128:   Notes:
2129:    This can also be set by the command line option: -mat_use_hash_table fact

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

2133: .seealso: MatSetOption()
2134: @*/
2135: int MatMPISBAIJSetHashTableFactor(Mat mat,PetscReal fact)
2136: {
2138:   SETERRQ(1,"Function not yet written for SBAIJ format");
2139:   /* return(0); */
2140: }

2142: int MatGetRowMax_MPISBAIJ(Mat A,Vec v)
2143: {
2144:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
2145:   Mat_SeqBAIJ  *b = (Mat_SeqBAIJ*)(a->B)->data;
2146:   PetscReal    atmp;
2147:   PetscReal    *work,*svalues,*rvalues;
2148:   int          ierr,i,bs,mbs,*bi,*bj,brow,j,ncols,krow,kcol,col,row,Mbs,bcol;
2149:   int          rank,size,*rowners_bs,dest,count,source;
2150:   PetscScalar  *va;
2151:   MatScalar    *ba;
2152:   MPI_Status   stat;

2155:   MatGetRowMax(a->A,v);
2156:   VecGetArray(v,&va);

2158:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
2159:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

2161:   bs   = a->bs;
2162:   mbs  = a->mbs;
2163:   Mbs  = a->Mbs;
2164:   ba   = b->a;
2165:   bi   = b->i;
2166:   bj   = b->j;
2167:   /*
2168:   PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d] M: %d, bs: %d, mbs: %d n",rank,bs*Mbs,bs,mbs); 
2169:   PetscSynchronizedFlush(PETSC_COMM_WORLD);
2170:   */

2172:   /* find ownerships */
2173:   rowners_bs = a->rowners_bs;
2174:   /*
2175:   if (!rank){
2176:     for (i=0; i<size+1; i++) PetscPrintf(PETSC_COMM_SELF," rowners_bs[%d]: %dn",i,rowners_bs[i]); 
2177:   }
2178:   */

2180:   /* each proc creates an array to be distributed */
2181:   PetscMalloc(bs*Mbs*sizeof(PetscReal),&work);
2182:   PetscMemzero(work,bs*Mbs*sizeof(PetscReal));

2184:   /* row_max for B */
2185:   if (rank != size-1){
2186:     for (i=0; i<mbs; i++) {
2187:       ncols = bi[1] - bi[0]; bi++;
2188:       brow  = bs*i;
2189:       for (j=0; j<ncols; j++){
2190:         bcol = bs*(*bj);
2191:         for (kcol=0; kcol<bs; kcol++){
2192:           col = bcol + kcol;                 /* local col index */
2193:           col += rowners_bs[rank+1];      /* global col index */
2194:           /* PetscPrintf(PETSC_COMM_SELF,"[%d], col: %dn",rank,col); */
2195:           for (krow=0; krow<bs; krow++){
2196:             atmp = PetscAbsScalar(*ba); ba++;
2197:             row = brow + krow;    /* local row index */
2198:             /* printf("val[%d,%d]: %gn",row,col,atmp); */
2199:             if (PetscRealPart(va[row]) < atmp) va[row] = atmp;
2200:             if (work[col] < atmp) work[col] = atmp;
2201:           }
2202:         }
2203:         bj++;
2204:       }
2205:     }
2206:     /*
2207:       PetscPrintf(PETSC_COMM_SELF,"[%d], work: ",rank);
2208:       for (i=0; i<bs*Mbs; i++) PetscPrintf(PETSC_COMM_SELF,"%g ",work[i]);
2209:       PetscPrintf(PETSC_COMM_SELF,"[%d]: n");
2210:       */

2212:     /* send values to its owners */
2213:     for (dest=rank+1; dest<size; dest++){
2214:       svalues = work + rowners_bs[dest];
2215:       count   = rowners_bs[dest+1]-rowners_bs[dest];
2216:       ierr    = MPI_Send(svalues,count,MPIU_REAL,dest,rank,PETSC_COMM_WORLD);
2217:       /*
2218:       PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d] sends %d values to [%d]: %g, %g, %g, %gn",rank,count,dest,svalues[0],svalues[1],svalues[2],svalues[3]); 
2219:       PetscSynchronizedFlush(PETSC_COMM_WORLD);
2220:       */
2221:     }
2222:   }
2223: 
2224:   /* receive values */
2225:   if (rank){
2226:     rvalues = work;
2227:     count   = rowners_bs[rank+1]-rowners_bs[rank];
2228:     for (source=0; source<rank; source++){
2229:       MPI_Recv(rvalues,count,MPIU_REAL,MPI_ANY_SOURCE,MPI_ANY_TAG,PETSC_COMM_WORLD,&stat);
2230:       /* process values */
2231:       for (i=0; i<count; i++){
2232:         if (PetscRealPart(va[i]) < rvalues[i]) va[i] = rvalues[i];
2233:       }
2234:       /*
2235:       PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d] received %d values from [%d]: %g, %g, %g, %g n",rank,count,stat.MPI_SOURCE,rvalues[0],rvalues[1],rvalues[2],rvalues[3]);  
2236:       PetscSynchronizedFlush(PETSC_COMM_WORLD);
2237:       */
2238:     }
2239:   }

2241:   VecRestoreArray(v,&va);
2242:   PetscFree(work);
2243:   return(0);
2244: }

2246: int MatRelax_MPISBAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,int its,int lits,Vec xx)
2247: {
2248:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
2249:   int            ierr;
2250:   PetscScalar    mone=-1.0;
2251:   Vec            lvec1,bb1;
2252: 
2254:   if (its <= 0 || lits <= 0) SETERRQ2(PETSC_ERR_ARG_WRONG,"Relaxation requires global its %d and local its %d both positive",its,lits);
2255:   if (mat->bs > 1)
2256:     SETERRQ(PETSC_ERR_SUP,"SSOR for block size > 1 is not yet implemented");

2258:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP){
2259:     if ( flag & SOR_ZERO_INITIAL_GUESS ) {
2260:       (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,PETSC_NULL,xx);
2261:       its--;
2262:     }

2264:     VecDuplicate(mat->lvec,&lvec1);
2265:     VecDuplicate(bb,&bb1);
2266:     while (its--){
2267:       VecScatterBegin(xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD,mat->Mvctx);
2268: 
2269:       /* lower diagonal part: bb1 = bb - B^T*xx */
2270:       (*mat->B->ops->multtranspose)(mat->B,xx,lvec1);
2271:       VecScale(&mone,lvec1);

2273:       VecScatterEnd(xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD,mat->Mvctx);
2274:       VecCopy(bb,bb1);
2275:       VecScatterBegin(lvec1,bb1,ADD_VALUES,SCATTER_REVERSE,mat->Mvctx);

2277:       /* upper diagonal part: bb1 = bb1 - B*x */
2278:       VecScale(&mone,mat->lvec);
2279:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb1,bb1);

2281:       VecScatterEnd(lvec1,bb1,ADD_VALUES,SCATTER_REVERSE,mat->Mvctx);
2282: 
2283:       /* diagonal sweep */
2284:       (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,PETSC_NULL,xx);
2285:     }
2286:     VecDestroy(lvec1);
2287:     VecDestroy(bb1);
2288:   } else {
2289:     SETERRQ(PETSC_ERR_SUP,"MatSORType is not supported for SBAIJ matrix format");
2290:   }
2291:   return(0);
2292: }