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
 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 MatSetUpMultiply_MPISBAIJ_2comm(Mat);
 10: extern int DisAssemble_MPISBAIJ(Mat);
 11: extern int MatIncreaseOverlap_MPISBAIJ(Mat,int,IS *,int);
 12: extern int MatGetSubMatrices_MPISBAIJ(Mat,int,IS *,IS *,MatReuse,Mat **);
 13: extern int MatGetValues_SeqSBAIJ(Mat,int,int *,int,int *,PetscScalar *);
 14: extern int MatSetValues_SeqSBAIJ(Mat,int,int *,int,int *,PetscScalar *,InsertMode);
 15: extern int MatSetValuesBlocked_SeqSBAIJ(Mat,int,int*,int,int*,PetscScalar*,InsertMode);
 16: extern int MatGetRow_SeqSBAIJ(Mat,int,int*,int**,PetscScalar**);
 17: extern int MatRestoreRow_SeqSBAIJ(Mat,int,int*,int**,PetscScalar**);
 18: extern int MatPrintHelp_SeqSBAIJ(Mat);
 19: extern int MatZeroRows_SeqSBAIJ(Mat,IS,PetscScalar*);
 20: extern int MatZeroRows_SeqBAIJ(Mat,IS,PetscScalar *);
 21: extern int MatGetRowMax_MPISBAIJ(Mat,Vec);
 22: extern int MatRelax_MPISBAIJ(Mat,Vec,PetscReal,MatSORType,PetscReal,int,int,Vec);
 23: extern int MatUseSpooles_MPISBAIJ(Mat);

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

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

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

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

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

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

 85: #define CHUNKSIZE  10

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

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

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

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

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

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

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

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

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

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

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

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

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

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

334:   /* for stash */
335:   int          n_loc, *in_loc=0;
336:   MatScalar    *v_loc=0;


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

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

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

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

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

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

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

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

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

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

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

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

540:   if (baij->donotstash) {
541:     return(0);
542:   }

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

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

560: int MatAssemblyEnd_MPISBAIJ(Mat mat,MatAssemblyType mode)
561: {
562:   Mat_MPISBAIJ *baij=(Mat_MPISBAIJ*)mat->data;
563:   Mat_SeqSBAIJ  *a=(Mat_SeqSBAIJ*)baij->A->data;
564:   Mat_SeqBAIJ  *b=(Mat_SeqBAIJ*)baij->B->data;
565:   int         i,j,rstart,ncols,n,ierr,flg,bs2=baij->bs2;
566:   int         *row,*col,other_disassembled;
567:   PetscTruth  r1,r2,r3;
568:   MatScalar   *val;
569:   InsertMode  addv = mat->insertmode;
570: #if defined(PETSC_HAVE_SPOOLES) 
571:   PetscTruth  flag;
572: #endif


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

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

624:   MatAssemblyBegin(baij->A,mode);
625:   MatAssemblyEnd(baij->A,mode);

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

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

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

664: #if defined(PETSC_HAVE_SPOOLES) 
665:   PetscOptionsHasName(PETSC_NULL,"-mat_sbaij_spooles",&flag);
666:   if (flag) { MatUseSpooles_MPISBAIJ(mat); }
667: #endif   
668:   return(0);
669: }

671: static int MatView_MPISBAIJ_ASCIIorDraworSocket(Mat mat,PetscViewer viewer)
672: {
673:   Mat_MPISBAIJ      *baij = (Mat_MPISBAIJ*)mat->data;
674:   int               ierr,bs = baij->bs,size = baij->size,rank = baij->rank;
675:   PetscTruth        isascii,isdraw;
676:   PetscViewer       sviewer;
677:   PetscViewerFormat format;

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

704:   if (isdraw) {
705:     PetscDraw       draw;
706:     PetscTruth isnull;
707:     PetscViewerDrawGetDraw(viewer,0,&draw);
708:     PetscDrawIsNull(draw,&isnull); if (isnull) return(0);
709:   }

711:   if (size == 1) {
712:     PetscObjectSetName((PetscObject)baij->A,mat->name);
713:     MatView(baij->A,viewer);
714:   } else {
715:     /* assemble the entire matrix onto first processor. */
716:     Mat         A;
717:     Mat_SeqSBAIJ *Aloc;
718:     Mat_SeqBAIJ *Bloc;
719:     int         M = mat->M,N = mat->N,*ai,*aj,col,i,j,k,*rvals,mbs = baij->mbs;
720:     MatScalar   *a;

722:     if (!rank) {
723:       MatCreateMPISBAIJ(mat->comm,baij->bs,M,N,M,N,0,PETSC_NULL,0,PETSC_NULL,&A);
724:     } else {
725:       MatCreateMPISBAIJ(mat->comm,baij->bs,0,0,M,N,0,PETSC_NULL,0,PETSC_NULL,&A);
726:     }
727:     PetscLogObjectParent(mat,A);

729:     /* copy over the A part */
730:     Aloc  = (Mat_SeqSBAIJ*)baij->A->data;
731:     ai    = Aloc->i; aj = Aloc->j; a = Aloc->a;
732:     ierr  = PetscMalloc(bs*sizeof(int),&rvals);

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

777: int MatView_MPISBAIJ(Mat mat,PetscViewer viewer)
778: {
779:   int        ierr;
780:   PetscTruth isascii,isdraw,issocket,isbinary;

783:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);
784:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_DRAW,&isdraw);
785:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_SOCKET,&issocket);
786:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_BINARY,&isbinary);
787:   if (isascii || isdraw || issocket || isbinary) {
788:     MatView_MPISBAIJ_ASCIIorDraworSocket(mat,viewer);
789:   } else {
790:     SETERRQ1(1,"Viewer type %s not supported by MPISBAIJ matrices",((PetscObject)viewer)->type_name);
791:   }
792:   return(0);
793: }

795: int MatDestroy_MPISBAIJ(Mat mat)
796: {
797:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
798:   int         ierr;

801: #if defined(PETSC_USE_LOG)
802:   PetscLogObjectState((PetscObject)mat,"Rows=%d,Cols=%d",mat->M,mat->N);
803: #endif
804:   MatStashDestroy_Private(&mat->stash);
805:   MatStashDestroy_Private(&mat->bstash);
806:   PetscFree(baij->rowners);
807:   MatDestroy(baij->A);
808:   MatDestroy(baij->B);
809: #if defined (PETSC_USE_CTABLE)
810:   if (baij->colmap) {PetscTableDelete(baij->colmap);}
811: #else
812:   if (baij->colmap) {PetscFree(baij->colmap);}
813: #endif
814:   if (baij->garray) {PetscFree(baij->garray);}
815:   if (baij->lvec)   {VecDestroy(baij->lvec);}
816:   if (baij->Mvctx)  {VecScatterDestroy(baij->Mvctx);}
817:   if (baij->slvec0) {
818:     VecDestroy(baij->slvec0);
819:     VecDestroy(baij->slvec0b);
820:   }
821:   if (baij->slvec1) {
822:     VecDestroy(baij->slvec1);
823:     VecDestroy(baij->slvec1a);
824:     VecDestroy(baij->slvec1b);
825:   }
826:   if (baij->sMvctx)  {VecScatterDestroy(baij->sMvctx);}
827:   if (baij->rowvalues) {PetscFree(baij->rowvalues);}
828:   if (baij->barray) {PetscFree(baij->barray);}
829:   if (baij->hd) {PetscFree(baij->hd);}
830: #if defined(PETSC_USE_MAT_SINGLE)
831:   if (baij->setvaluescopy) {PetscFree(baij->setvaluescopy);}
832: #endif
833:   PetscFree(baij);
834:   return(0);
835: }

837: int MatMult_MPISBAIJ(Mat A,Vec xx,Vec yy)
838: {
839:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
840:   int         ierr,nt,mbs=a->mbs,bs=a->bs;
841:   PetscScalar *x,*from,zero=0.0;
842: 
844:   /*
845:   PetscSynchronizedPrintf(PETSC_COMM_WORLD," _1comm is called ...n");
846:   PetscSynchronizedFlush(PETSC_COMM_WORLD);
847:   */
848:   VecGetLocalSize(xx,&nt);
849:   if (nt != A->n) {
850:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");
851:   }
852:   VecGetLocalSize(yy,&nt);
853:   if (nt != A->m) {
854:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible parition of A and yy");
855:   }

857:   /* diagonal part */
858:   (*a->A->ops->mult)(a->A,xx,a->slvec1a);
859:   VecSet(&zero,a->slvec1b);

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

864:   /* copy x into the vec slvec0 */
865:   VecGetArray(a->slvec0,&from);
866:   VecGetArray(xx,&x);
867:   PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
868:   VecRestoreArray(a->slvec0,&from);
869: 
870:   VecScatterBegin(a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD,a->sMvctx);
871:   VecRestoreArray(xx,&x);
872:   VecScatterEnd(a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD,a->sMvctx);
873: 
874:   /* supperdiagonal part */
875:   (*a->B->ops->multadd)(a->B,a->slvec1b,a->slvec1a,yy);
876: 
877:   return(0);
878: }

880: int MatMult_MPISBAIJ_2comm(Mat A,Vec xx,Vec yy)
881: {
882:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
883:   int         ierr,nt;

886:   VecGetLocalSize(xx,&nt);
887:   if (nt != A->n) {
888:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible partition of A and xx");
889:   }
890:   VecGetLocalSize(yy,&nt);
891:   if (nt != A->m) {
892:     SETERRQ(PETSC_ERR_ARG_SIZ,"Incompatible parition of A and yy");
893:   }

895:   VecScatterBegin(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
896:   /* do diagonal part */
897:   (*a->A->ops->mult)(a->A,xx,yy);
898:   /* do supperdiagonal part */
899:   VecScatterEnd(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
900:   (*a->B->ops->multadd)(a->B,a->lvec,yy,yy);
901:   /* do subdiagonal part */
902:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
903:   VecScatterBegin(a->lvec,yy,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);
904:   VecScatterEnd(a->lvec,yy,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);

906:   return(0);
907: }

909: int MatMultAdd_MPISBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
910: {
911:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
912:   int          ierr,mbs=a->mbs,bs=a->bs;
913:   PetscScalar  *x,*from,zero=0.0;
914: 
916:   /*
917:   PetscSynchronizedPrintf(PETSC_COMM_WORLD," MatMultAdd is called ...n");
918:   PetscSynchronizedFlush(PETSC_COMM_WORLD);
919:   */
920:   /* diagonal part */
921:   (*a->A->ops->multadd)(a->A,xx,yy,a->slvec1a);
922:   VecSet(&zero,a->slvec1b);

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

927:   /* copy x into the vec slvec0 */
928:   VecGetArray(a->slvec0,&from);
929:   VecGetArray(xx,&x);
930:   PetscMemcpy(from,x,bs*mbs*sizeof(MatScalar));
931:   VecRestoreArray(a->slvec0,&from);
932: 
933:   VecScatterBegin(a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD,a->sMvctx);
934:   VecRestoreArray(xx,&x);
935:   VecScatterEnd(a->slvec0,a->slvec1,ADD_VALUES,SCATTER_FORWARD,a->sMvctx);
936: 
937:   /* supperdiagonal part */
938:   (*a->B->ops->multadd)(a->B,a->slvec1b,a->slvec1a,zz);
939: 
940:   return(0);
941: }

943: int MatMultAdd_MPISBAIJ_2comm(Mat A,Vec xx,Vec yy,Vec zz)
944: {
945:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
946:   int        ierr;

949:   VecScatterBegin(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
950:   /* do diagonal part */
951:   (*a->A->ops->multadd)(a->A,xx,yy,zz);
952:   /* do supperdiagonal part */
953:   VecScatterEnd(xx,a->lvec,INSERT_VALUES,SCATTER_FORWARD,a->Mvctx);
954:   (*a->B->ops->multadd)(a->B,a->lvec,zz,zz);

956:   /* do subdiagonal part */
957:   (*a->B->ops->multtranspose)(a->B,xx,a->lvec);
958:   VecScatterBegin(a->lvec,zz,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);
959:   VecScatterEnd(a->lvec,zz,ADD_VALUES,SCATTER_REVERSE,a->Mvctx);

961:   return(0);
962: }

964: int MatMultTranspose_MPISBAIJ(Mat A,Vec xx,Vec yy)
965: {
967:   SETERRQ(1,"Matrix is symmetric. Call MatMult().");
968:   /* return(0); */
969: }

971: int MatMultTransposeAdd_MPISBAIJ(Mat A,Vec xx,Vec yy,Vec zz)
972: {
974:   SETERRQ(1,"Matrix is symmetric. Call MatMultAdd().");
975:   /* return(0); */
976: }

978: /*
979:   This only works correctly for square matrices where the subblock A->A is the 
980:    diagonal block
981: */
982: int MatGetDiagonal_MPISBAIJ(Mat A,Vec v)
983: {
984:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
985:   int         ierr;

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

993: int MatScale_MPISBAIJ(PetscScalar *aa,Mat A)
994: {
995:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
996:   int         ierr;

999:   MatScale(aa,a->A);
1000:   MatScale(aa,a->B);
1001:   return(0);
1002: }

1004: int MatGetRow_MPISBAIJ(Mat matin,int row,int *nz,int **idx,PetscScalar **v)
1005: {
1006:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
1007:   PetscScalar    *vworkA,*vworkB,**pvA,**pvB,*v_p;
1008:   int            bs = mat->bs,bs2 = mat->bs2,i,ierr,*cworkA,*cworkB,**pcA,**pcB;
1009:   int            nztot,nzA,nzB,lrow,brstart = mat->rstart*bs,brend = mat->rend*bs;
1010:   int            *cmap,*idx_p,cstart = mat->cstart;

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

1016:   if (!mat->rowvalues && (idx || v)) {
1017:     /*
1018:         allocate enough space to hold information from the longest row.
1019:     */
1020:     Mat_SeqSBAIJ *Aa = (Mat_SeqSBAIJ*)mat->A->data;
1021:     Mat_SeqBAIJ  *Ba = (Mat_SeqBAIJ*)mat->B->data;
1022:     int     max = 1,mbs = mat->mbs,tmp;
1023:     for (i=0; i<mbs; i++) {
1024:       tmp = Aa->i[i+1] - Aa->i[i] + Ba->i[i+1] - Ba->i[i]; /* row length */
1025:       if (max < tmp) { max = tmp; }
1026:     }
1027:     PetscMalloc(max*bs2*(sizeof(int)+sizeof(PetscScalar)),&mat->rowvalues);
1028:     mat->rowindices = (int*)(mat->rowvalues + max*bs2);
1029:   }
1030: 
1031:   if (row < brstart || row >= brend) SETERRQ(PETSC_ERR_SUP,"Only local rows")
1032:   lrow = row - brstart;  /* local row index */

1034:   pvA = &vworkA; pcA = &cworkA; pvB = &vworkB; pcB = &cworkB;
1035:   if (!v)   {pvA = 0; pvB = 0;}
1036:   if (!idx) {pcA = 0; if (!v) pcB = 0;}
1037:   (*mat->A->ops->getrow)(mat->A,lrow,&nzA,pcA,pvA);
1038:   (*mat->B->ops->getrow)(mat->B,lrow,&nzB,pcB,pvB);
1039:   nztot = nzA + nzB;

1041:   cmap  = mat->garray;
1042:   if (v  || idx) {
1043:     if (nztot) {
1044:       /* Sort by increasing column numbers, assuming A and B already sorted */
1045:       int imark = -1;
1046:       if (v) {
1047:         *v = v_p = mat->rowvalues;
1048:         for (i=0; i<nzB; i++) {
1049:           if (cmap[cworkB[i]/bs] < cstart)   v_p[i] = vworkB[i];
1050:           else break;
1051:         }
1052:         imark = i;
1053:         for (i=0; i<nzA; i++)     v_p[imark+i] = vworkA[i];
1054:         for (i=imark; i<nzB; i++) v_p[nzA+i]   = vworkB[i];
1055:       }
1056:       if (idx) {
1057:         *idx = idx_p = mat->rowindices;
1058:         if (imark > -1) {
1059:           for (i=0; i<imark; i++) {
1060:             idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs;
1061:           }
1062:         } else {
1063:           for (i=0; i<nzB; i++) {
1064:             if (cmap[cworkB[i]/bs] < cstart)
1065:               idx_p[i] = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
1066:             else break;
1067:           }
1068:           imark = i;
1069:         }
1070:         for (i=0; i<nzA; i++)     idx_p[imark+i] = cstart*bs + cworkA[i];
1071:         for (i=imark; i<nzB; i++) idx_p[nzA+i]   = cmap[cworkB[i]/bs]*bs + cworkB[i]%bs ;
1072:       }
1073:     } else {
1074:       if (idx) *idx = 0;
1075:       if (v)   *v   = 0;
1076:     }
1077:   }
1078:   *nz = nztot;
1079:   (*mat->A->ops->restorerow)(mat->A,lrow,&nzA,pcA,pvA);
1080:   (*mat->B->ops->restorerow)(mat->B,lrow,&nzB,pcB,pvB);
1081:   return(0);
1082: }

1084: int MatRestoreRow_MPISBAIJ(Mat mat,int row,int *nz,int **idx,PetscScalar **v)
1085: {
1086:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;

1089:   if (baij->getrowactive == PETSC_FALSE) {
1090:     SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"MatGetRow not called");
1091:   }
1092:   baij->getrowactive = PETSC_FALSE;
1093:   return(0);
1094: }

1096: int MatGetBlockSize_MPISBAIJ(Mat mat,int *bs)
1097: {
1098:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;

1101:   *bs = baij->bs;
1102:   return(0);
1103: }

1105: int MatZeroEntries_MPISBAIJ(Mat A)
1106: {
1107:   Mat_MPISBAIJ *l = (Mat_MPISBAIJ*)A->data;
1108:   int         ierr;

1111:   MatZeroEntries(l->A);
1112:   MatZeroEntries(l->B);
1113:   return(0);
1114: }

1116: int MatGetInfo_MPISBAIJ(Mat matin,MatInfoType flag,MatInfo *info)
1117: {
1118:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)matin->data;
1119:   Mat         A = a->A,B = a->B;
1120:   int         ierr;
1121:   PetscReal   isend[5],irecv[5];

1124:   info->block_size     = (PetscReal)a->bs;
1125:   MatGetInfo(A,MAT_LOCAL,info);
1126:   isend[0] = info->nz_used; isend[1] = info->nz_allocated; isend[2] = info->nz_unneeded;
1127:   isend[3] = info->memory;  isend[4] = info->mallocs;
1128:   MatGetInfo(B,MAT_LOCAL,info);
1129:   isend[0] += info->nz_used; isend[1] += info->nz_allocated; isend[2] += info->nz_unneeded;
1130:   isend[3] += info->memory;  isend[4] += info->mallocs;
1131:   if (flag == MAT_LOCAL) {
1132:     info->nz_used      = isend[0];
1133:     info->nz_allocated = isend[1];
1134:     info->nz_unneeded  = isend[2];
1135:     info->memory       = isend[3];
1136:     info->mallocs      = isend[4];
1137:   } else if (flag == MAT_GLOBAL_MAX) {
1138:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_MAX,matin->comm);
1139:     info->nz_used      = irecv[0];
1140:     info->nz_allocated = irecv[1];
1141:     info->nz_unneeded  = irecv[2];
1142:     info->memory       = irecv[3];
1143:     info->mallocs      = irecv[4];
1144:   } else if (flag == MAT_GLOBAL_SUM) {
1145:     MPI_Allreduce(isend,irecv,5,MPIU_REAL,MPI_SUM,matin->comm);
1146:     info->nz_used      = irecv[0];
1147:     info->nz_allocated = irecv[1];
1148:     info->nz_unneeded  = irecv[2];
1149:     info->memory       = irecv[3];
1150:     info->mallocs      = irecv[4];
1151:   } else {
1152:     SETERRQ1(1,"Unknown MatInfoType argument %d",flag);
1153:   }
1154:   info->rows_global       = (PetscReal)A->M;
1155:   info->columns_global    = (PetscReal)A->N;
1156:   info->rows_local        = (PetscReal)A->m;
1157:   info->columns_local     = (PetscReal)A->N;
1158:   info->fill_ratio_given  = 0; /* no parallel LU/ILU/Cholesky */
1159:   info->fill_ratio_needed = 0;
1160:   info->factor_mallocs    = 0;
1161:   return(0);
1162: }

1164: int MatSetOption_MPISBAIJ(Mat A,MatOption op)
1165: {
1166:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
1167:   int         ierr;

1170:   switch (op) {
1171:   case MAT_NO_NEW_NONZERO_LOCATIONS:
1172:   case MAT_YES_NEW_NONZERO_LOCATIONS:
1173:   case MAT_COLUMNS_UNSORTED:
1174:   case MAT_COLUMNS_SORTED:
1175:   case MAT_NEW_NONZERO_ALLOCATION_ERR:
1176:   case MAT_KEEP_ZEROED_ROWS:
1177:   case MAT_NEW_NONZERO_LOCATION_ERR:
1178:     MatSetOption(a->A,op);
1179:     MatSetOption(a->B,op);
1180:     break;
1181:   case MAT_ROW_ORIENTED:
1182:     a->roworiented = PETSC_TRUE;
1183:     MatSetOption(a->A,op);
1184:     MatSetOption(a->B,op);
1185:     break;
1186:   case MAT_ROWS_SORTED:
1187:   case MAT_ROWS_UNSORTED:
1188:   case MAT_YES_NEW_DIAGONALS:
1189:   case MAT_USE_SINGLE_PRECISION_SOLVES:
1190:     PetscLogInfo(A,"Info:MatSetOption_MPIBAIJ:Option ignoredn");
1191:     break;
1192:   case MAT_COLUMN_ORIENTED:
1193:     a->roworiented = PETSC_FALSE;
1194:     MatSetOption(a->A,op);
1195:     MatSetOption(a->B,op);
1196:     break;
1197:   case MAT_IGNORE_OFF_PROC_ENTRIES:
1198:     a->donotstash = PETSC_TRUE;
1199:     break;
1200:   case MAT_NO_NEW_DIAGONALS:
1201:     SETERRQ(PETSC_ERR_SUP,"MAT_NO_NEW_DIAGONALS");
1202:   case MAT_USE_HASH_TABLE:
1203:     a->ht_flag = PETSC_TRUE;
1204:     break;
1205:   default:
1206:     SETERRQ(PETSC_ERR_SUP,"unknown option");
1207:   }
1208:   return(0);
1209: }

1211: int MatTranspose_MPISBAIJ(Mat A,Mat *matout)
1212: {
1214:   SETERRQ(1,"Matrix is symmetric. MatTranspose() should not be called");
1215:   /* return(0); */
1216: }

1218: int MatDiagonalScale_MPISBAIJ(Mat mat,Vec ll,Vec rr)
1219: {
1220:   Mat_MPISBAIJ *baij = (Mat_MPISBAIJ*)mat->data;
1221:   Mat         a = baij->A,b = baij->B;
1222:   int         ierr,s1,s2,s3;

1225:   if (ll != rr) {
1226:     SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"For symmetric format, left and right scaling vectors must be samen");
1227:   }
1228:   MatGetLocalSize(mat,&s2,&s3);
1229:   if (rr) {
1230:     VecGetLocalSize(rr,&s1);
1231:     if (s1!=s3) SETERRQ(PETSC_ERR_ARG_SIZ,"right vector non-conforming local size");
1232:     /* Overlap communication with computation. */
1233:     VecScatterBegin(rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD,baij->Mvctx);
1234:     /*} if (ll) { */
1235:     VecGetLocalSize(ll,&s1);
1236:     if (s1!=s2) SETERRQ(PETSC_ERR_ARG_SIZ,"left vector non-conforming local size");
1237:     (*b->ops->diagonalscale)(b,ll,PETSC_NULL);
1238:     /* } */
1239:   /* scale  the diagonal block */
1240:   (*a->ops->diagonalscale)(a,ll,rr);

1242:   /* if (rr) { */
1243:     /* Do a scatter end and then right scale the off-diagonal block */
1244:     VecScatterEnd(rr,baij->lvec,INSERT_VALUES,SCATTER_FORWARD,baij->Mvctx);
1245:     (*b->ops->diagonalscale)(b,PETSC_NULL,baij->lvec);
1246:   }
1247: 
1248:   return(0);
1249: }

1251: int MatZeroRows_MPISBAIJ(Mat A,IS is,PetscScalar *diag)
1252: {
1253:   Mat_MPISBAIJ   *l = (Mat_MPISBAIJ*)A->data;
1254:   int            i,ierr,N,*rows,*owners = l->rowners,size = l->size;
1255:   int            *procs,*nprocs,j,idx,nsends,*work,row;
1256:   int            nmax,*svalues,*starts,*owner,nrecvs,rank = l->rank;
1257:   int            *rvalues,tag = A->tag,count,base,slen,n,*source;
1258:   int            *lens,imdex,*lrows,*values,bs=l->bs,rstart_bs=l->rstart_bs;
1259:   MPI_Comm       comm = A->comm;
1260:   MPI_Request    *send_waits,*recv_waits;
1261:   MPI_Status     recv_status,*send_status;
1262:   IS             istmp;
1263:   PetscTruth     found;

1266:   ISGetSize(is,&N);
1267:   ISGetIndices(is,&rows);
1268: 
1269:   /*  first count number of contributors to each processor */
1270:   ierr  = PetscMalloc(2*size*sizeof(int),&nprocs);
1271:   ierr  = PetscMemzero(nprocs,2*size*sizeof(int));
1272:   procs = nprocs + size;
1273:   ierr  = PetscMalloc((N+1)*sizeof(int),&owner); /* see note*/
1274:   for (i=0; i<N; i++) {
1275:     idx   = rows[i];
1276:     found = PETSC_FALSE;
1277:     for (j=0; j<size; j++) {
1278:       if (idx >= owners[j]*bs && idx < owners[j+1]*bs) {
1279:         nprocs[j]++; procs[j] = 1; owner[i] = j; found = PETSC_TRUE; break;
1280:       }
1281:     }
1282:     if (!found) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Index out of range");
1283:   }
1284:   nsends = 0;  for (i=0; i<size; i++) { nsends += procs[i];}
1285: 
1286:   /* inform other processors of number of messages and max length*/
1287:   ierr   = PetscMalloc(2*size*sizeof(int),&work);
1288:   ierr   = MPI_Allreduce(nprocs,work,2*size,MPI_INT,PetscMaxSum_Op,comm);
1289:   nmax   = work[rank];
1290:   nrecvs = work[size+rank];
1291:   ierr   = PetscFree(work);
1292: 
1293:   /* post receives:   */
1294:   PetscMalloc((nrecvs+1)*(nmax+1)*sizeof(int),&rvalues);
1295:   PetscMalloc((nrecvs+1)*sizeof(MPI_Request),&recv_waits);
1296:   for (i=0; i<nrecvs; i++) {
1297:     MPI_Irecv(rvalues+nmax*i,nmax,MPI_INT,MPI_ANY_SOURCE,tag,comm,recv_waits+i);
1298:   }
1299: 
1300:   /* do sends:
1301:      1) starts[i] gives the starting index in svalues for stuff going to 
1302:      the ith processor
1303:   */
1304:   PetscMalloc((N+1)*sizeof(int),&svalues);
1305:   PetscMalloc((nsends+1)*sizeof(MPI_Request),&send_waits);
1306:   PetscMalloc((size+1)*sizeof(int),&starts);
1307:   starts[0]  = 0;
1308:   for (i=1; i<size; i++) { starts[i] = starts[i-1] + nprocs[i-1];}
1309:   for (i=0; i<N; i++) {
1310:     svalues[starts[owner[i]]++] = rows[i];
1311:   }
1312:   ISRestoreIndices(is,&rows);
1313: 
1314:   starts[0] = 0;
1315:   for (i=1; i<size+1; i++) { starts[i] = starts[i-1] + nprocs[i-1];}
1316:   count = 0;
1317:   for (i=0; i<size; i++) {
1318:     if (procs[i]) {
1319:       MPI_Isend(svalues+starts[i],nprocs[i],MPI_INT,i,tag,comm,send_waits+count++);
1320:     }
1321:   }
1322:   PetscFree(starts);

1324:   base = owners[rank]*bs;
1325: 
1326:   /*  wait on receives */
1327:   ierr   = PetscMalloc(2*(nrecvs+1)*sizeof(int),&lens);
1328:   source = lens + nrecvs;
1329:   count  = nrecvs; slen = 0;
1330:   while (count) {
1331:     MPI_Waitany(nrecvs,recv_waits,&imdex,&recv_status);
1332:     /* unpack receives into our local space */
1333:     MPI_Get_count(&recv_status,MPI_INT,&n);
1334:     source[imdex]  = recv_status.MPI_SOURCE;
1335:     lens[imdex]    = n;
1336:     slen          += n;
1337:     count--;
1338:   }
1339:   PetscFree(recv_waits);
1340: 
1341:   /* move the data into the send scatter */
1342:   PetscMalloc((slen+1)*sizeof(int),&lrows);
1343:   count = 0;
1344:   for (i=0; i<nrecvs; i++) {
1345:     values = rvalues + i*nmax;
1346:     for (j=0; j<lens[i]; j++) {
1347:       lrows[count++] = values[j] - base;
1348:     }
1349:   }
1350:   PetscFree(rvalues);
1351:   PetscFree(lens);
1352:   PetscFree(owner);
1353:   PetscFree(nprocs);
1354: 
1355:   /* actually zap the local rows */
1356:   ISCreateGeneral(PETSC_COMM_SELF,slen,lrows,&istmp);
1357:   PetscLogObjectParent(A,istmp);

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

1365:        Contributed by: Mathew Knepley
1366:   */
1367:   /* must zero l->B before l->A because the (diag) case below may put values into l->B*/
1368:   MatZeroRows_SeqBAIJ(l->B,istmp,0);
1369:   if (diag && (l->A->M == l->A->N)) {
1370:     MatZeroRows_SeqSBAIJ(l->A,istmp,diag);
1371:   } else if (diag) {
1372:     MatZeroRows_SeqSBAIJ(l->A,istmp,0);
1373:     if (((Mat_SeqSBAIJ*)l->A->data)->nonew) {
1374:       SETERRQ(PETSC_ERR_SUP,"MatZeroRows() on rectangular matrices cannot be used with the Mat options n
1375: MAT_NO_NEW_NONZERO_LOCATIONS,MAT_NEW_NONZERO_LOCATION_ERR,MAT_NEW_NONZERO_ALLOCATION_ERR");
1376:     }
1377:     for (i=0; i<slen; i++) {
1378:       row  = lrows[i] + rstart_bs;
1379:       MatSetValues(A,1,&row,1,&row,diag,INSERT_VALUES);
1380:     }
1381:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1382:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1383:   } else {
1384:     MatZeroRows_SeqSBAIJ(l->A,istmp,0);
1385:   }

1387:   ISDestroy(istmp);
1388:   PetscFree(lrows);

1390:   /* wait on sends */
1391:   if (nsends) {
1392:     PetscMalloc(nsends*sizeof(MPI_Status),&send_status);
1393:     ierr        = MPI_Waitall(nsends,send_waits,send_status);
1394:     ierr        = PetscFree(send_status);
1395:   }
1396:   PetscFree(send_waits);
1397:   PetscFree(svalues);

1399:   return(0);
1400: }

1402: int MatPrintHelp_MPISBAIJ(Mat A)
1403: {
1404:   Mat_MPISBAIJ *a   = (Mat_MPISBAIJ*)A->data;
1405:   MPI_Comm    comm = A->comm;
1406:   static int  called = 0;
1407:   int         ierr;

1410:   if (!a->rank) {
1411:     MatPrintHelp_SeqSBAIJ(a->A);
1412:   }
1413:   if (called) {return(0);} else called = 1;
1414:   (*PetscHelpPrintf)(comm," Options for MATMPISBAIJ matrix format (the defaults):n");
1415:   (*PetscHelpPrintf)(comm,"  -mat_use_hash_table <factor>: Use hashtable for efficient matrix assemblyn");
1416:   return(0);
1417: }

1419: int MatSetUnfactored_MPISBAIJ(Mat A)
1420: {
1421:   Mat_MPISBAIJ *a   = (Mat_MPISBAIJ*)A->data;
1422:   int         ierr;

1425:   MatSetUnfactored(a->A);
1426:   return(0);
1427: }

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

1431: int MatEqual_MPISBAIJ(Mat A,Mat B,PetscTruth *flag)
1432: {
1433:   Mat_MPISBAIJ *matB = (Mat_MPISBAIJ*)B->data,*matA = (Mat_MPISBAIJ*)A->data;
1434:   Mat         a,b,c,d;
1435:   PetscTruth  flg;
1436:   int         ierr;

1439:   PetscTypeCompare((PetscObject)B,MATMPISBAIJ,&flg);
1440:   if (!flg) SETERRQ(PETSC_ERR_ARG_INCOMP,"Matrices must be same type");
1441:   a = matA->A; b = matA->B;
1442:   c = matB->A; d = matB->B;

1444:   MatEqual(a,c,&flg);
1445:   if (flg == PETSC_TRUE) {
1446:     MatEqual(b,d,&flg);
1447:   }
1448:   MPI_Allreduce(&flg,flag,1,MPI_INT,MPI_LAND,A->comm);
1449:   return(0);
1450: }

1452: int MatSetUpPreallocation_MPISBAIJ(Mat A)
1453: {
1454:   int        ierr;

1457:   MatMPISBAIJSetPreallocation(A,1,PETSC_DEFAULT,0,PETSC_DEFAULT,0);
1458:   return(0);
1459: }
1460: /* -------------------------------------------------------------------*/
1461: static struct _MatOps MatOps_Values = {
1462:   MatSetValues_MPISBAIJ,
1463:   MatGetRow_MPISBAIJ,
1464:   MatRestoreRow_MPISBAIJ,
1465:   MatMult_MPISBAIJ,
1466:   MatMultAdd_MPISBAIJ,
1467:   MatMultTranspose_MPISBAIJ,
1468:   MatMultTransposeAdd_MPISBAIJ,
1469:   0,
1470:   0,
1471:   0,
1472:   0,
1473:   0,
1474:   0,
1475:   MatRelax_MPISBAIJ,
1476:   MatTranspose_MPISBAIJ,
1477:   MatGetInfo_MPISBAIJ,
1478:   MatEqual_MPISBAIJ,
1479:   MatGetDiagonal_MPISBAIJ,
1480:   MatDiagonalScale_MPISBAIJ,
1481:   MatNorm_MPISBAIJ,
1482:   MatAssemblyBegin_MPISBAIJ,
1483:   MatAssemblyEnd_MPISBAIJ,
1484:   0,
1485:   MatSetOption_MPISBAIJ,
1486:   MatZeroEntries_MPISBAIJ,
1487:   MatZeroRows_MPISBAIJ,
1488:   0,
1489:   0,
1490:   0,
1491:   0,
1492:   MatSetUpPreallocation_MPISBAIJ,
1493:   0,
1494:   0,
1495:   0,
1496:   0,
1497:   MatDuplicate_MPISBAIJ,
1498:   0,
1499:   0,
1500:   0,
1501:   0,
1502:   0,
1503:   MatGetSubMatrices_MPISBAIJ,
1504:   MatIncreaseOverlap_MPISBAIJ,
1505:   MatGetValues_MPISBAIJ,
1506:   0,
1507:   MatPrintHelp_MPISBAIJ,
1508:   MatScale_MPISBAIJ,
1509:   0,
1510:   0,
1511:   0,
1512:   MatGetBlockSize_MPISBAIJ,
1513:   0,
1514:   0,
1515:   0,
1516:   0,
1517:   0,
1518:   0,
1519:   MatSetUnfactored_MPISBAIJ,
1520:   0,
1521:   MatSetValuesBlocked_MPISBAIJ,
1522:   0,
1523:   0,
1524:   0,
1525:   MatGetPetscMaps_Petsc,
1526:   0,
1527:   0,
1528:   0,
1529:   0,
1530:   0,
1531:   0,
1532:   MatGetRowMax_MPISBAIJ};


1535: EXTERN_C_BEGIN
1536: int MatGetDiagonalBlock_MPISBAIJ(Mat A,PetscTruth *iscopy,MatReuse reuse,Mat *a)
1537: {
1539:   *a      = ((Mat_MPISBAIJ *)A->data)->A;
1540:   *iscopy = PETSC_FALSE;
1541:   return(0);
1542: }
1543: EXTERN_C_END

1545: EXTERN_C_BEGIN
1546: int MatCreate_MPISBAIJ(Mat B)
1547: {
1548:   Mat_MPISBAIJ *b;
1549:   int          ierr;
1550:   PetscTruth   flg;


1554:   ierr    = PetscNew(Mat_MPISBAIJ,&b);
1555:   B->data = (void*)b;
1556:   ierr    = PetscMemzero(b,sizeof(Mat_MPISBAIJ));
1557:   ierr    = PetscMemcpy(B->ops,&MatOps_Values,sizeof(struct _MatOps));

1559:   B->ops->destroy    = MatDestroy_MPISBAIJ;
1560:   B->ops->view       = MatView_MPISBAIJ;
1561:   B->mapping    = 0;
1562:   B->factor     = 0;
1563:   B->assembled  = PETSC_FALSE;

1565:   B->insertmode = NOT_SET_VALUES;
1566:   MPI_Comm_rank(B->comm,&b->rank);
1567:   MPI_Comm_size(B->comm,&b->size);

1569:   /* build local table of row and column ownerships */
1570:   ierr          = PetscMalloc(3*(b->size+2)*sizeof(int),&b->rowners);
1571:   b->cowners    = b->rowners + b->size + 2;
1572:   b->rowners_bs = b->cowners + b->size + 2;
1573:   PetscLogObjectMemory(B,3*(b->size+2)*sizeof(int)+sizeof(struct _p_Mat)+sizeof(Mat_MPISBAIJ));

1575:   /* build cache for off array entries formed */
1576:   MatStashCreate_Private(B->comm,1,&B->stash);
1577:   b->donotstash  = PETSC_FALSE;
1578:   b->colmap      = PETSC_NULL;
1579:   b->garray      = PETSC_NULL;
1580:   b->roworiented = PETSC_TRUE;

1582: #if defined(PETSC_USE_MAT_SINGLE)
1583:   /* stuff for MatSetValues_XXX in single precision */
1584:   b->setvalueslen     = 0;
1585:   b->setvaluescopy    = PETSC_NULL;
1586: #endif

1588:   /* stuff used in block assembly */
1589:   b->barray       = 0;

1591:   /* stuff used for matrix vector multiply */
1592:   b->lvec         = 0;
1593:   b->Mvctx        = 0;
1594:   b->slvec0       = 0;
1595:   b->slvec0b      = 0;
1596:   b->slvec1       = 0;
1597:   b->slvec1a      = 0;
1598:   b->slvec1b      = 0;
1599:   b->sMvctx       = 0;

1601:   /* stuff for MatGetRow() */
1602:   b->rowindices   = 0;
1603:   b->rowvalues    = 0;
1604:   b->getrowactive = PETSC_FALSE;

1606:   /* hash table stuff */
1607:   b->ht           = 0;
1608:   b->hd           = 0;
1609:   b->ht_size      = 0;
1610:   b->ht_flag      = PETSC_FALSE;
1611:   b->ht_fact      = 0;
1612:   b->ht_total_ct  = 0;
1613:   b->ht_insert_ct = 0;

1615:   PetscOptionsHasName(PETSC_NULL,"-mat_use_hash_table",&flg);
1616:   if (flg) {
1617:     PetscReal fact = 1.39;
1618:     MatSetOption(B,MAT_USE_HASH_TABLE);
1619:     PetscOptionsGetReal(PETSC_NULL,"-mat_use_hash_table",&fact,PETSC_NULL);
1620:     if (fact <= 1.0) fact = 1.39;
1621:     MatMPIBAIJSetHashTableFactor(B,fact);
1622:     PetscLogInfo(0,"MatCreateMPISBAIJ:Hash table Factor used %5.2fn",fact);
1623:   }
1624:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatStoreValues_C",
1625:                                      "MatStoreValues_MPISBAIJ",
1626:                                      MatStoreValues_MPISBAIJ);
1627:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatRetrieveValues_C",
1628:                                      "MatRetrieveValues_MPISBAIJ",
1629:                                      MatRetrieveValues_MPISBAIJ);
1630:   PetscObjectComposeFunctionDynamic((PetscObject)B,"MatGetDiagonalBlock_C",
1631:                                      "MatGetDiagonalBlock_MPISBAIJ",
1632:                                      MatGetDiagonalBlock_MPISBAIJ);
1633:   return(0);
1634: }
1635: EXTERN_C_END

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

1643:    Collective on Mat

1645:    Input Parameters:
1646: +  A - the matrix 
1647: .  bs   - size of blockk
1648: .  d_nz  - number of block nonzeros per block row in diagonal portion of local 
1649:            submatrix  (same for all local rows)
1650: .  d_nnz - array containing the number of block nonzeros in the various block rows 
1651:            of the in diagonal portion of the local (possibly different for each block
1652:            row) or PETSC_NULL.  You must leave room for the diagonal entry even if it is zero.
1653: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1654:            submatrix (same for all local rows).
1655: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1656:            off-diagonal portion of the local submatrix (possibly different for
1657:            each block row) or PETSC_NULL.


1660:    Options Database Keys:
1661: .   -mat_no_unroll - uses code that does not unroll the loops in the 
1662:                      block calculations (much slower)
1663: .   -mat_block_size - size of the blocks to use

1665:    Notes:

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

1670:    Storage Information:
1671:    For a square global matrix we define each processor's diagonal portion 
1672:    to be its local rows and the corresponding columns (a square submatrix);  
1673:    each processor's off-diagonal portion encompasses the remainder of the
1674:    local matrix (a rectangular submatrix). 

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

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

1685: .vb
1686:            0 1 2 3 4 5 6 7 8 9 10 11
1687:           -------------------
1688:    row 3  |  o o o d d d o o o o o o
1689:    row 4  |  o o o d d d o o o o o o
1690:    row 5  |  o o o d d d o o o o o o
1691:           -------------------
1692: .ve
1693:   
1694:    Thus, any entries in the d locations are stored in the d (diagonal) 
1695:    submatrix, and any entries in the o locations are stored in the
1696:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
1697:    stored simply in the MATSEQBAIJ format for compressed row storage.

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

1706:    Level: intermediate

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

1710: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateMPIBAIJ()
1711: @*/

1713: int MatMPISBAIJSetPreallocation(Mat B,int bs,int d_nz,int *d_nnz,int o_nz,int *o_nnz)
1714: {
1715:   Mat_MPISBAIJ *b;
1716:   int          ierr,i,mbs,Mbs;
1717:   PetscTruth   flg2;

1720:   PetscTypeCompare((PetscObject)B,MATMPISBAIJ,&flg2);
1721:   if (!flg2) return(0);

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

1725:   if (bs < 1) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Invalid block size specified, must be positive");
1726:   if (d_nz == PETSC_DECIDE || d_nz == PETSC_DEFAULT) d_nz = 3;
1727:   if (o_nz == PETSC_DECIDE || o_nz == PETSC_DEFAULT) o_nz = 1;
1728:   if (d_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"d_nz cannot be less than 0: value %d",d_nz);
1729:   if (o_nz < 0) SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE,"o_nz cannot be less than 0: value %d",o_nz);
1730:   if (d_nnz) {
1731:     for (i=0; i<B->m/bs; i++) {
1732:       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]);
1733:     }
1734:   }
1735:   if (o_nnz) {
1736:     for (i=0; i<B->m/bs; i++) {
1737:       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]);
1738:     }
1739:   }
1740:   B->preallocated = PETSC_TRUE;
1741:   PetscSplitOwnershipBlock(B->comm,bs,&B->m,&B->M);
1742:   PetscSplitOwnershipBlock(B->comm,bs,&B->n,&B->N);
1743:   PetscMapCreateMPI(B->comm,B->m,B->M,&B->rmap);
1744:   PetscMapCreateMPI(B->comm,B->m,B->M,&B->cmap);

1746:   b   = (Mat_MPISBAIJ*)B->data;
1747:   mbs = B->m/bs;
1748:   Mbs = B->M/bs;
1749:   if (mbs*bs != B->m) {
1750:     SETERRQ2(PETSC_ERR_ARG_SIZ,"No of local rows %d must be divisible by blocksize %d",B->m,bs);
1751:   }

1753:   b->bs  = bs;
1754:   b->bs2 = bs*bs;
1755:   b->mbs = mbs;
1756:   b->nbs = mbs;
1757:   b->Mbs = Mbs;
1758:   b->Nbs = Mbs;

1760:   MPI_Allgather(&b->mbs,1,MPI_INT,b->rowners+1,1,MPI_INT,B->comm);
1761:   b->rowners[0]    = 0;
1762:   for (i=2; i<=b->size; i++) {
1763:     b->rowners[i] += b->rowners[i-1];
1764:   }
1765:   b->rstart    = b->rowners[b->rank];
1766:   b->rend      = b->rowners[b->rank+1];
1767:   b->cstart    = b->rstart;
1768:   b->cend      = b->rend;
1769:   for (i=0; i<=b->size; i++) {
1770:     b->rowners_bs[i] = b->rowners[i]*bs;
1771:   }
1772:   b->rstart_bs = b-> rstart*bs;
1773:   b->rend_bs   = b->rend*bs;
1774: 
1775:   b->cstart_bs = b->cstart*bs;
1776:   b->cend_bs   = b->cend*bs;
1777: 

1779:   MatCreateSeqSBAIJ(PETSC_COMM_SELF,bs,B->m,B->m,d_nz,d_nnz,&b->A);
1780:   PetscLogObjectParent(B,b->A);
1781:   MatCreateSeqBAIJ(PETSC_COMM_SELF,bs,B->m,B->M,o_nz,o_nnz,&b->B);
1782:   PetscLogObjectParent(B,b->B);

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

1787:   return(0);
1788: }

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

1797:    Collective on MPI_Comm

1799:    Input Parameters:
1800: +  comm - MPI communicator
1801: .  bs   - size of blockk
1802: .  m - number of local rows (or PETSC_DECIDE to have calculated if M is given)
1803:            This value should be the same as the local size used in creating the 
1804:            y vector for the matrix-vector product y = Ax.
1805: .  n - number of local columns (or PETSC_DECIDE to have calculated if N is given)
1806:            This value should be the same as the local size used in creating the 
1807:            x vector for the matrix-vector product y = Ax.
1808: .  M - number of global rows (or PETSC_DETERMINE to have calculated if m is given)
1809: .  N - number of global columns (or PETSC_DETERMINE to have calculated if n is given)
1810: .  d_nz  - number of block nonzeros per block row in diagonal portion of local 
1811:            submatrix  (same for all local rows)
1812: .  d_nnz - array containing the number of block nonzeros in the various block rows 
1813:            of the in diagonal portion of the local (possibly different for each block
1814:            row) or PETSC_NULL.  You must leave room for the diagonal entry even if it is zero.
1815: .  o_nz  - number of block nonzeros per block row in the off-diagonal portion of local
1816:            submatrix (same for all local rows).
1817: -  o_nnz - array containing the number of nonzeros in the various block rows of the
1818:            off-diagonal portion of the local submatrix (possibly different for
1819:            each block row) or PETSC_NULL.

1821:    Output Parameter:
1822: .  A - the matrix 

1824:    Options Database Keys:
1825: .   -mat_no_unroll - uses code that does not unroll the loops in the 
1826:                      block calculations (much slower)
1827: .   -mat_block_size - size of the blocks to use
1828: .   -mat_mpi - use the parallel matrix data structures even on one processor 
1829:                (defaults to using SeqBAIJ format on one processor)

1831:    Notes:
1832:    The user MUST specify either the local or global matrix dimensions
1833:    (possibly both).

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

1838:    Storage Information:
1839:    For a square global matrix we define each processor's diagonal portion 
1840:    to be its local rows and the corresponding columns (a square submatrix);  
1841:    each processor's off-diagonal portion encompasses the remainder of the
1842:    local matrix (a rectangular submatrix). 

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

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

1853: .vb
1854:            0 1 2 3 4 5 6 7 8 9 10 11
1855:           -------------------
1856:    row 3  |  o o o d d d o o o o o o
1857:    row 4  |  o o o d d d o o o o o o
1858:    row 5  |  o o o d d d o o o o o o
1859:           -------------------
1860: .ve
1861:   
1862:    Thus, any entries in the d locations are stored in the d (diagonal) 
1863:    submatrix, and any entries in the o locations are stored in the
1864:    o (off-diagonal) submatrix.  Note that the d and the o submatrices are
1865:    stored simply in the MATSEQBAIJ format for compressed row storage.

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

1874:    Level: intermediate

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

1878: .seealso: MatCreate(), MatCreateSeqSBAIJ(), MatSetValues(), MatCreateMPIBAIJ()
1879: @*/

1881: 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)
1882: {
1883:   int ierr,size;

1886:   MatCreate(comm,m,n,M,N,A);
1887:   MPI_Comm_size(comm,&size);
1888:   if (size > 1) {
1889:     MatSetType(*A,MATMPISBAIJ);
1890:     MatMPISBAIJSetPreallocation(*A,bs,d_nz,d_nnz,o_nz,o_nnz);
1891:   } else {
1892:     MatSetType(*A,MATSEQSBAIJ);
1893:     MatSeqSBAIJSetPreallocation(*A,bs,d_nz,d_nnz);
1894:   }
1895:   return(0);
1896: }


1899: static int MatDuplicate_MPISBAIJ(Mat matin,MatDuplicateOption cpvalues,Mat *newmat)
1900: {
1901:   Mat          mat;
1902:   Mat_MPISBAIJ *a,*oldmat = (Mat_MPISBAIJ*)matin->data;
1903:   int          ierr,len=0;

1906:   *newmat       = 0;
1907:   MatCreate(matin->comm,matin->m,matin->n,matin->M,matin->N,&mat);
1908:   MatSetType(mat,MATMPISBAIJ);
1909:   mat->preallocated = PETSC_TRUE;
1910:   a = (Mat_MPISBAIJ*)mat->data;
1911:   a->bs  = oldmat->bs;
1912:   a->bs2 = oldmat->bs2;
1913:   a->mbs = oldmat->mbs;
1914:   a->nbs = oldmat->nbs;
1915:   a->Mbs = oldmat->Mbs;
1916:   a->Nbs = oldmat->Nbs;
1917: 
1918:   a->rstart       = oldmat->rstart;
1919:   a->rend         = oldmat->rend;
1920:   a->cstart       = oldmat->cstart;
1921:   a->cend         = oldmat->cend;
1922:   a->size         = oldmat->size;
1923:   a->rank         = oldmat->rank;
1924:   a->donotstash   = oldmat->donotstash;
1925:   a->roworiented  = oldmat->roworiented;
1926:   a->rowindices   = 0;
1927:   a->rowvalues    = 0;
1928:   a->getrowactive = PETSC_FALSE;
1929:   a->barray       = 0;
1930:   a->rstart_bs    = oldmat->rstart_bs;
1931:   a->rend_bs      = oldmat->rend_bs;
1932:   a->cstart_bs    = oldmat->cstart_bs;
1933:   a->cend_bs      = oldmat->cend_bs;

1935:   /* hash table stuff */
1936:   a->ht           = 0;
1937:   a->hd           = 0;
1938:   a->ht_size      = 0;
1939:   a->ht_flag      = oldmat->ht_flag;
1940:   a->ht_fact      = oldmat->ht_fact;
1941:   a->ht_total_ct  = 0;
1942:   a->ht_insert_ct = 0;

1944:   PetscMalloc(3*(a->size+2)*sizeof(int),&a->rowners);
1945:   PetscLogObjectMemory(mat,3*(a->size+2)*sizeof(int)+sizeof(struct _p_Mat)+sizeof(Mat_MPISBAIJ));
1946:   a->cowners    = a->rowners + a->size + 2;
1947:   a->rowners_bs = a->cowners + a->size + 2;
1948:   PetscMemcpy(a->rowners,oldmat->rowners,3*(a->size+2)*sizeof(int));
1949:   MatStashCreate_Private(matin->comm,1,&mat->stash);
1950:   MatStashCreate_Private(matin->comm,oldmat->bs,&mat->bstash);
1951:   if (oldmat->colmap) {
1952: #if defined (PETSC_USE_CTABLE)
1953:     PetscTableCreateCopy(oldmat->colmap,&a->colmap);
1954: #else
1955:     PetscMalloc((a->Nbs)*sizeof(int),&a->colmap);
1956:     PetscLogObjectMemory(mat,(a->Nbs)*sizeof(int));
1957:     PetscMemcpy(a->colmap,oldmat->colmap,(a->Nbs)*sizeof(int));
1958: #endif
1959:   } else a->colmap = 0;
1960:   if (oldmat->garray && (len = ((Mat_SeqBAIJ*)(oldmat->B->data))->nbs)) {
1961:     PetscMalloc(len*sizeof(int),&a->garray);
1962:     PetscLogObjectMemory(mat,len*sizeof(int));
1963:     PetscMemcpy(a->garray,oldmat->garray,len*sizeof(int));
1964:   } else a->garray = 0;
1965: 
1966:    VecDuplicate(oldmat->lvec,&a->lvec);
1967:   PetscLogObjectParent(mat,a->lvec);
1968:    VecScatterCopy(oldmat->Mvctx,&a->Mvctx);

1970:   PetscLogObjectParent(mat,a->Mvctx);
1971:    MatDuplicate(oldmat->A,cpvalues,&a->A);
1972:   PetscLogObjectParent(mat,a->A);
1973:    MatDuplicate(oldmat->B,cpvalues,&a->B);
1974:   PetscLogObjectParent(mat,a->B);
1975:   PetscFListDuplicate(mat->qlist,&matin->qlist);
1976:   *newmat = mat;
1977:   return(0);
1978: }

1980:  #include petscsys.h

1982: EXTERN_C_BEGIN
1983: int MatLoad_MPISBAIJ(PetscViewer viewer,MatType type,Mat *newmat)
1984: {
1985:   Mat          A;
1986:   int          i,nz,ierr,j,rstart,rend,fd;
1987:   PetscScalar  *vals,*buf;
1988:   MPI_Comm     comm = ((PetscObject)viewer)->comm;
1989:   MPI_Status   status;
1990:   int          header[4],rank,size,*rowlengths = 0,M,N,m,*rowners,*browners,maxnz,*cols;
1991:   int          *locrowlens,*sndcounts = 0,*procsnz = 0,jj,*mycols,*ibuf;
1992:   int          tag = ((PetscObject)viewer)->tag,bs=1,Mbs,mbs,extra_rows;
1993:   int          *dlens,*odlens,*mask,*masked1,*masked2,rowcount,odcount;
1994:   int          dcount,kmax,k,nzcount,tmp;
1995: 
1997:   PetscOptionsGetInt(PETSC_NULL,"-matload_block_size",&bs,PETSC_NULL);

1999:   MPI_Comm_size(comm,&size);
2000:   MPI_Comm_rank(comm,&rank);
2001:   if (!rank) {
2002:     PetscViewerBinaryGetDescriptor(viewer,&fd);
2003:     PetscBinaryRead(fd,(char *)header,4,PETSC_INT);
2004:     if (header[0] != MAT_FILE_COOKIE) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"not matrix object");
2005:     if (header[3] < 0) {
2006:       SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"Matrix stored in special format, cannot load as MPISBAIJ");
2007:     }
2008:   }

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

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

2015:   /* 
2016:      This code adds extra rows to make sure the number of rows is 
2017:      divisible by the blocksize
2018:   */
2019:   Mbs        = M/bs;
2020:   extra_rows = bs - M + bs*(Mbs);
2021:   if (extra_rows == bs) extra_rows = 0;
2022:   else                  Mbs++;
2023:   if (extra_rows &&!rank) {
2024:     PetscLogInfo(0,"MatLoad_MPISBAIJ:Padding loaded matrix to match blocksizen");
2025:   }

2027:   /* determine ownership of all rows */
2028:   mbs        = Mbs/size + ((Mbs % size) > rank);
2029:   m          = mbs*bs;
2030:   ierr       = PetscMalloc(2*(size+2)*sizeof(int),&rowners);
2031:   browners   = rowners + size + 1;
2032:   ierr       = MPI_Allgather(&mbs,1,MPI_INT,rowners+1,1,MPI_INT,comm);
2033:   rowners[0] = 0;
2034:   for (i=2; i<=size; i++) rowners[i] += rowners[i-1];
2035:   for (i=0; i<=size;  i++) browners[i] = rowners[i]*bs;
2036:   rstart = rowners[rank];
2037:   rend   = rowners[rank+1];
2038: 
2039:   /* distribute row lengths to all processors */
2040:   PetscMalloc((rend-rstart)*bs*sizeof(int),&locrowlens);
2041:   if (!rank) {
2042:     PetscMalloc((M+extra_rows)*sizeof(int),&rowlengths);
2043:     PetscBinaryRead(fd,rowlengths,M,PETSC_INT);
2044:     for (i=0; i<extra_rows; i++) rowlengths[M+i] = 1;
2045:     PetscMalloc(size*sizeof(int),&sndcounts);
2046:     for (i=0; i<size; i++) sndcounts[i] = browners[i+1] - browners[i];
2047:     MPI_Scatterv(rowlengths,sndcounts,browners,MPI_INT,locrowlens,(rend-rstart)*bs,MPI_INT,0,comm);
2048:     PetscFree(sndcounts);
2049:   } else {
2050:     MPI_Scatterv(0,0,0,MPI_INT,locrowlens,(rend-rstart)*bs,MPI_INT,0,comm);
2051:   }
2052: 
2053:   if (!rank) {   /* procs[0] */
2054:     /* calculate the number of nonzeros on each processor */
2055:     PetscMalloc(size*sizeof(int),&procsnz);
2056:     PetscMemzero(procsnz,size*sizeof(int));
2057:     for (i=0; i<size; i++) {
2058:       for (j=rowners[i]*bs; j< rowners[i+1]*bs; j++) {
2059:         procsnz[i] += rowlengths[j];
2060:       }
2061:     }
2062:     PetscFree(rowlengths);
2063: 
2064:     /* determine max buffer needed and allocate it */
2065:     maxnz = 0;
2066:     for (i=0; i<size; i++) {
2067:       maxnz = PetscMax(maxnz,procsnz[i]);
2068:     }
2069:     PetscMalloc(maxnz*sizeof(int),&cols);

2071:     /* read in my part of the matrix column indices  */
2072:     nz     = procsnz[0];
2073:     ierr   = PetscMalloc(nz*sizeof(int),&ibuf);
2074:     mycols = ibuf;
2075:     if (size == 1)  nz -= extra_rows;
2076:     PetscBinaryRead(fd,mycols,nz,PETSC_INT);
2077:     if (size == 1)  for (i=0; i< extra_rows; i++) { mycols[nz+i] = M+i; }

2079:     /* read in every ones (except the last) and ship off */
2080:     for (i=1; i<size-1; i++) {
2081:       nz   = procsnz[i];
2082:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
2083:       MPI_Send(cols,nz,MPI_INT,i,tag,comm);
2084:     }
2085:     /* read in the stuff for the last proc */
2086:     if (size != 1) {
2087:       nz   = procsnz[size-1] - extra_rows;  /* the extra rows are not on the disk */
2088:       PetscBinaryRead(fd,cols,nz,PETSC_INT);
2089:       for (i=0; i<extra_rows; i++) cols[nz+i] = M+i;
2090:       MPI_Send(cols,nz+extra_rows,MPI_INT,size-1,tag,comm);
2091:     }
2092:     PetscFree(cols);
2093:   } else {  /* procs[i], i>0 */
2094:     /* determine buffer space needed for message */
2095:     nz = 0;
2096:     for (i=0; i<m; i++) {
2097:       nz += locrowlens[i];
2098:     }
2099:     ierr   = PetscMalloc(nz*sizeof(int),&ibuf);
2100:     mycols = ibuf;
2101:     /* receive message of column indices*/
2102:     MPI_Recv(mycols,nz,MPI_INT,0,tag,comm,&status);
2103:     MPI_Get_count(&status,MPI_INT,&maxnz);
2104:     if (maxnz != nz) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");
2105:   }

2107:   /* loop over local rows, determining number of off diagonal entries */
2108:   ierr     = PetscMalloc(2*(rend-rstart+1)*sizeof(int),&dlens);
2109:   odlens   = dlens + (rend-rstart);
2110:   ierr     = PetscMalloc(3*Mbs*sizeof(int),&mask);
2111:   ierr     = PetscMemzero(mask,3*Mbs*sizeof(int));
2112:   masked1  = mask    + Mbs;
2113:   masked2  = masked1 + Mbs;
2114:   rowcount = 0; nzcount = 0;
2115:   for (i=0; i<mbs; i++) {
2116:     dcount  = 0;
2117:     odcount = 0;
2118:     for (j=0; j<bs; j++) {
2119:       kmax = locrowlens[rowcount];
2120:       for (k=0; k<kmax; k++) {
2121:         tmp = mycols[nzcount++]/bs; /* block col. index */
2122:         if (!mask[tmp]) {
2123:           mask[tmp] = 1;
2124:           if (tmp < rstart || tmp >= rend) masked2[odcount++] = tmp; /* entry in off-diag portion */
2125:           else masked1[dcount++] = tmp; /* entry in diag portion */
2126:         }
2127:       }
2128:       rowcount++;
2129:     }
2130: 
2131:     dlens[i]  = dcount;  /* d_nzz[i] */
2132:     odlens[i] = odcount; /* o_nzz[i] */

2134:     /* zero out the mask elements we set */
2135:     for (j=0; j<dcount; j++) mask[masked1[j]] = 0;
2136:     for (j=0; j<odcount; j++) mask[masked2[j]] = 0;
2137:   }
2138: 
2139:   /* create our matrix */
2140:   MatCreateMPISBAIJ(comm,bs,m,m,PETSC_DETERMINE,PETSC_DETERMINE,0,dlens,0,odlens,newmat);
2141: 
2142:   A = *newmat;
2143:   MatSetOption(A,MAT_COLUMNS_SORTED);
2144: 
2145:   if (!rank) {
2146:     PetscMalloc(maxnz*sizeof(PetscScalar),&buf);
2147:     /* read in my part of the matrix numerical values  */
2148:     nz = procsnz[0];
2149:     vals = buf;
2150:     mycols = ibuf;
2151:     if (size == 1)  nz -= extra_rows;
2152:     PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2153:     if (size == 1)  for (i=0; i< extra_rows; i++) { vals[nz+i] = 1.0; }

2155:     /* insert into matrix */
2156:     jj      = rstart*bs;
2157:     for (i=0; i<m; i++) {
2158:       MatSetValues(A,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2159:       mycols += locrowlens[i];
2160:       vals   += locrowlens[i];
2161:       jj++;
2162:     }

2164:     /* read in other processors (except the last one) and ship out */
2165:     for (i=1; i<size-1; i++) {
2166:       nz   = procsnz[i];
2167:       vals = buf;
2168:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2169:       MPI_Send(vals,nz,MPIU_SCALAR,i,A->tag,comm);
2170:     }
2171:     /* the last proc */
2172:     if (size != 1){
2173:       nz   = procsnz[i] - extra_rows;
2174:       vals = buf;
2175:       PetscBinaryRead(fd,vals,nz,PETSC_SCALAR);
2176:       for (i=0; i<extra_rows; i++) vals[nz+i] = 1.0;
2177:       MPI_Send(vals,nz+extra_rows,MPIU_SCALAR,size-1,A->tag,comm);
2178:     }
2179:     PetscFree(procsnz);

2181:   } else {
2182:     /* receive numeric values */
2183:     PetscMalloc(nz*sizeof(PetscScalar),&buf);

2185:     /* receive message of values*/
2186:     vals   = buf;
2187:     mycols = ibuf;
2188:     ierr   = MPI_Recv(vals,nz,MPIU_SCALAR,0,A->tag,comm,&status);
2189:     ierr   = MPI_Get_count(&status,MPIU_SCALAR,&maxnz);
2190:     if (maxnz != nz) SETERRQ(PETSC_ERR_FILE_UNEXPECTED,"something is wrong with file");

2192:     /* insert into matrix */
2193:     jj      = rstart*bs;
2194:     for (i=0; i<m; i++) {
2195:       ierr    = MatSetValues_MPISBAIJ(A,1,&jj,locrowlens[i],mycols,vals,INSERT_VALUES);
2196:       mycols += locrowlens[i];
2197:       vals   += locrowlens[i];
2198:       jj++;
2199:     }
2200:   }

2202:   PetscFree(locrowlens);
2203:   PetscFree(buf);
2204:   PetscFree(ibuf);
2205:   PetscFree(rowners);
2206:   PetscFree(dlens);
2207:   PetscFree(mask);
2208:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2209:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2210:   return(0);
2211: }
2212: EXTERN_C_END

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

2217:    Input Parameters:
2218: .  mat  - the matrix
2219: .  fact - factor

2221:    Collective on Mat

2223:    Level: advanced

2225:   Notes:
2226:    This can also be set by the command line option: -mat_use_hash_table fact

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

2230: .seealso: MatSetOption()
2231: @*/
2232: int MatMPISBAIJSetHashTableFactor(Mat mat,PetscReal fact)
2233: {
2235:   SETERRQ(1,"Function not yet written for SBAIJ format");
2236:   /* return(0); */
2237: }

2239: int MatGetRowMax_MPISBAIJ(Mat A,Vec v)
2240: {
2241:   Mat_MPISBAIJ *a = (Mat_MPISBAIJ*)A->data;
2242:   Mat_SeqBAIJ  *b = (Mat_SeqBAIJ*)(a->B)->data;
2243:   PetscReal    atmp;
2244:   PetscReal    *work,*svalues,*rvalues;
2245:   int          ierr,i,bs,mbs,*bi,*bj,brow,j,ncols,krow,kcol,col,row,Mbs,bcol;
2246:   int          rank,size,*rowners_bs,dest,count,source;
2247:   PetscScalar  *va;
2248:   MatScalar    *ba;
2249:   MPI_Status   stat;

2252:   MatGetRowMax(a->A,v);
2253:   VecGetArray(v,&va);

2255:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
2256:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);

2258:   bs   = a->bs;
2259:   mbs  = a->mbs;
2260:   Mbs  = a->Mbs;
2261:   ba   = b->a;
2262:   bi   = b->i;
2263:   bj   = b->j;
2264:   /*
2265:   PetscSynchronizedPrintf(PETSC_COMM_WORLD,"[%d] M: %d, bs: %d, mbs: %d n",rank,bs*Mbs,bs,mbs); 
2266:   PetscSynchronizedFlush(PETSC_COMM_WORLD);
2267:   */

2269:   /* find ownerships */
2270:   rowners_bs = a->rowners_bs;
2271:   /*
2272:   if (!rank){
2273:     for (i=0; i<size+1; i++) PetscPrintf(PETSC_COMM_SELF," rowners_bs[%d]: %dn",i,rowners_bs[i]); 
2274:   }
2275:   */

2277:   /* each proc creates an array to be distributed */
2278:   PetscMalloc(bs*Mbs*sizeof(PetscReal),&work);
2279:   PetscMemzero(work,bs*Mbs*sizeof(PetscReal));

2281:   /* row_max for B */
2282:   if (rank != size-1){
2283:     for (i=0; i<mbs; i++) {
2284:       ncols = bi[1] - bi[0]; bi++;
2285:       brow  = bs*i;
2286:       for (j=0; j<ncols; j++){
2287:         bcol = bs*(*bj);
2288:         for (kcol=0; kcol<bs; kcol++){
2289:           col = bcol + kcol;                 /* local col index */
2290:           col += rowners_bs[rank+1];      /* global col index */
2291:           /* PetscPrintf(PETSC_COMM_SELF,"[%d], col: %dn",rank,col); */
2292:           for (krow=0; krow<bs; krow++){
2293:             atmp = PetscAbsScalar(*ba); ba++;
2294:             row = brow + krow;    /* local row index */
2295:             /* printf("val[%d,%d]: %gn",row,col,atmp); */
2296:             if (PetscRealPart(va[row]) < atmp) va[row] = atmp;
2297:             if (work[col] < atmp) work[col] = atmp;
2298:           }
2299:         }
2300:         bj++;
2301:       }
2302:     }
2303:     /*
2304:       PetscPrintf(PETSC_COMM_SELF,"[%d], work: ",rank);
2305:       for (i=0; i<bs*Mbs; i++) PetscPrintf(PETSC_COMM_SELF,"%g ",work[i]);
2306:       PetscPrintf(PETSC_COMM_SELF,"[%d]: n");
2307:       */

2309:     /* send values to its owners */
2310:     for (dest=rank+1; dest<size; dest++){
2311:       svalues = work + rowners_bs[dest];
2312:       count   = rowners_bs[dest+1]-rowners_bs[dest];
2313:       ierr    = MPI_Send(svalues,count,MPIU_REAL,dest,rank,PETSC_COMM_WORLD);
2314:       /*
2315:       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]); 
2316:       PetscSynchronizedFlush(PETSC_COMM_WORLD);
2317:       */
2318:     }
2319:   }
2320: 
2321:   /* receive values */
2322:   if (rank){
2323:     rvalues = work;
2324:     count   = rowners_bs[rank+1]-rowners_bs[rank];
2325:     for (source=0; source<rank; source++){
2326:       MPI_Recv(rvalues,count,MPIU_REAL,MPI_ANY_SOURCE,MPI_ANY_TAG,PETSC_COMM_WORLD,&stat);
2327:       /* process values */
2328:       for (i=0; i<count; i++){
2329:         if (PetscRealPart(va[i]) < rvalues[i]) va[i] = rvalues[i];
2330:       }
2331:       /*
2332:       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]);  
2333:       PetscSynchronizedFlush(PETSC_COMM_WORLD);
2334:       */
2335:     }
2336:   }

2338:   VecRestoreArray(v,&va);
2339:   PetscFree(work);
2340:   return(0);
2341: }

2343: int MatRelax_MPISBAIJ(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,int its,int lits,Vec xx)
2344: {
2345:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
2346:   int            ierr,mbs=mat->mbs,bs=mat->bs;
2347:   PetscScalar    mone=-1.0,*x,*b,*ptr,zero=0.0;
2348:   Vec            bb1;
2349: 
2351:   if (its <= 0 || lits <= 0) SETERRQ2(PETSC_ERR_ARG_WRONG,"Relaxation requires global its %d and local its %d both positive",its,lits);
2352:   if (bs > 1)
2353:     SETERRQ(PETSC_ERR_SUP,"SSOR for block size > 1 is not yet implemented");

2355:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP){
2356:     if ( flag & SOR_ZERO_INITIAL_GUESS ) {
2357:       (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,lits,xx);
2358:       its--;
2359:     }

2361:     VecDuplicate(bb,&bb1);
2362:     while (its--){
2363: 
2364:       /* lower triangular part: slvec0b = - B^T*xx */
2365:       (*mat->B->ops->multtranspose)(mat->B,xx,mat->slvec0b);
2366: 
2367:       /* copy xx into slvec0a */
2368:       VecGetArray(mat->slvec0,&ptr);
2369:       VecGetArray(xx,&x);
2370:       PetscMemcpy(ptr,x,bs*mbs*sizeof(MatScalar));
2371:       VecRestoreArray(mat->slvec0,&ptr);

2373:       VecScale(&mone,mat->slvec0);

2375:       /* copy bb into slvec1a */
2376:       VecGetArray(mat->slvec1,&ptr);
2377:       VecGetArray(bb,&b);
2378:       PetscMemcpy(ptr,b,bs*mbs*sizeof(MatScalar));
2379:       VecRestoreArray(mat->slvec1,&ptr);

2381:       /* set slvec1b = 0 */
2382:       VecSet(&zero,mat->slvec1b);

2384:       VecScatterBegin(mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD,mat->sMvctx);
2385:       VecRestoreArray(xx,&x);
2386:       VecRestoreArray(bb,&b);
2387:       VecScatterEnd(mat->slvec0,mat->slvec1,ADD_VALUES,SCATTER_FORWARD,mat->sMvctx);

2389:       /* upper triangular part: bb1 = bb1 - B*x */
2390:       (*mat->B->ops->multadd)(mat->B,mat->slvec1b,mat->slvec1a,bb1);
2391: 
2392:       /* local diagonal sweep */
2393:       (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,lits,xx);
2394:     }
2395:     VecDestroy(bb1);
2396:   } else {
2397:     SETERRQ(PETSC_ERR_SUP,"MatSORType is not supported for SBAIJ matrix format");
2398:   }
2399:   return(0);
2400: }

2402: int MatRelax_MPISBAIJ_2comm(Mat matin,Vec bb,PetscReal omega,MatSORType flag,PetscReal fshift,int its,int lits,Vec xx)
2403: {
2404:   Mat_MPISBAIJ   *mat = (Mat_MPISBAIJ*)matin->data;
2405:   int            ierr;
2406:   PetscScalar    mone=-1.0;
2407:   Vec            lvec1,bb1;
2408: 
2410:   if (its <= 0 || lits <= 0) SETERRQ2(PETSC_ERR_ARG_WRONG,"Relaxation requires global its %d and local its %d both positive",its,lits);
2411:   if (mat->bs > 1)
2412:     SETERRQ(PETSC_ERR_SUP,"SSOR for block size > 1 is not yet implemented");

2414:   if ((flag & SOR_LOCAL_SYMMETRIC_SWEEP) == SOR_LOCAL_SYMMETRIC_SWEEP){
2415:     if ( flag & SOR_ZERO_INITIAL_GUESS ) {
2416:       (*mat->A->ops->relax)(mat->A,bb,omega,flag,fshift,lits,lits,xx);
2417:       its--;
2418:     }

2420:     VecDuplicate(mat->lvec,&lvec1);
2421:     VecDuplicate(bb,&bb1);
2422:     while (its--){
2423:       VecScatterBegin(xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD,mat->Mvctx);
2424: 
2425:       /* lower diagonal part: bb1 = bb - B^T*xx */
2426:       (*mat->B->ops->multtranspose)(mat->B,xx,lvec1);
2427:       VecScale(&mone,lvec1);

2429:       VecScatterEnd(xx,mat->lvec,INSERT_VALUES,SCATTER_FORWARD,mat->Mvctx);
2430:       VecCopy(bb,bb1);
2431:       VecScatterBegin(lvec1,bb1,ADD_VALUES,SCATTER_REVERSE,mat->Mvctx);

2433:       /* upper diagonal part: bb1 = bb1 - B*x */
2434:       VecScale(&mone,mat->lvec);
2435:       (*mat->B->ops->multadd)(mat->B,mat->lvec,bb1,bb1);

2437:       VecScatterEnd(lvec1,bb1,ADD_VALUES,SCATTER_REVERSE,mat->Mvctx);
2438: 
2439:       /* diagonal sweep */
2440:       (*mat->A->ops->relax)(mat->A,bb1,omega,SOR_SYMMETRIC_SWEEP,fshift,lits,lits,xx);
2441:     }
2442:     VecDestroy(lvec1);
2443:     VecDestroy(bb1);
2444:   } else {
2445:     SETERRQ(PETSC_ERR_SUP,"MatSORType is not supported for SBAIJ matrix format");
2446:   }
2447:   return(0);
2448: }