Actual source code: matis.c

petsc-master 2017-02-22
Report Typos and Errors
  1: /*
  2:     Creates a matrix class for using the Neumann-Neumann type preconditioners.
  3:     This stores the matrices in globally unassembled form. Each processor
  4:     assembles only its local Neumann problem and the parallel matrix vector
  5:     product is handled "implicitly".

  7:     Currently this allows for only one subdomain per processor.
  8: */

 10:  #include <../src/mat/impls/is/matis.h>
 11:  #include <../src/mat/impls/aij/mpi/mpiaij.h>
 12:  #include <petsc/private/sfimpl.h>

 14: #define MATIS_MAX_ENTRIES_INSERTION 2048

 16: static PetscErrorCode MatISContainerDestroyFields_Private(void *ptr)
 17: {
 18:   MatISLocalFields lf = (MatISLocalFields)ptr;
 19:   PetscInt         i;
 20:   PetscErrorCode   ierr;

 23:   for (i=0;i<lf->nr;i++) {
 24:     ISDestroy(&lf->rf[i]);
 25:   }
 26:   for (i=0;i<lf->nc;i++) {
 27:     ISDestroy(&lf->cf[i]);
 28:   }
 29:   PetscFree2(lf->rf,lf->cf);
 30:   PetscFree(lf);
 31:   return(0);
 32: }

 34: static PetscErrorCode MatISContainerDestroyArray_Private(void *ptr)
 35: {

 39:   PetscFree(ptr);
 40:   return(0);
 41: }

 43: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_IS(Mat A,MatType type,MatReuse reuse,Mat *newmat)
 44: {
 45:   Mat_MPIAIJ             *aij  = (Mat_MPIAIJ*)A->data;
 46:   Mat_SeqAIJ             *diag = (Mat_SeqAIJ*)(aij->A->data);
 47:   Mat_SeqAIJ             *offd = (Mat_SeqAIJ*)(aij->B->data);
 48:   Mat                    lA;
 49:   ISLocalToGlobalMapping rl2g,cl2g;
 50:   IS                     is;
 51:   MPI_Comm               comm;
 52:   void                   *ptrs[2];
 53:   const char             *names[2] = {"_convert_csr_aux","_convert_csr_data"};
 54:   PetscScalar            *dd,*od,*aa,*data;
 55:   PetscInt               *di,*dj,*oi,*oj;
 56:   PetscInt               *aux,*ii,*jj;
 57:   PetscInt               lc,dr,dc,oc,str,stc,nnz,i,jd,jo,cum;
 58:   PetscErrorCode         ierr;

 61:   PetscObjectGetComm((PetscObject)A,&comm);
 62:   if (!aij->garray) SETERRQ(comm,PETSC_ERR_SUP,"garray not present");

 64:   /* access relevant information from MPIAIJ */
 65:   MatGetOwnershipRange(A,&str,NULL);
 66:   MatGetOwnershipRangeColumn(A,&stc,NULL);
 67:   MatGetLocalSize(A,&dr,&dc);
 68:   di   = diag->i;
 69:   dj   = diag->j;
 70:   dd   = diag->a;
 71:   oc   = aij->B->cmap->n;
 72:   oi   = offd->i;
 73:   oj   = offd->j;
 74:   od   = offd->a;
 75:   nnz  = diag->i[dr] + offd->i[dr];

 77:   /* generate l2g maps for rows and cols */
 78:   ISCreateStride(comm,dr,str,1,&is);
 79:   ISLocalToGlobalMappingCreateIS(is,&rl2g);
 80:   ISDestroy(&is);
 81:   if (dr) {
 82:     PetscMalloc1(dc+oc,&aux);
 83:     for (i=0; i<dc; i++) aux[i]    = i+stc;
 84:     for (i=0; i<oc; i++) aux[i+dc] = aij->garray[i];
 85:     ISCreateGeneral(comm,dc+oc,aux,PETSC_OWN_POINTER,&is);
 86:     lc   = dc+oc;
 87:   } else {
 88:     ISCreateGeneral(comm,0,NULL,PETSC_OWN_POINTER,&is);
 89:     lc   = 0;
 90:   }
 91:   ISLocalToGlobalMappingCreateIS(is,&cl2g);
 92:   ISDestroy(&is);

 94:   /* create MATIS object */
 95:   MatCreate(comm,newmat);
 96:   MatSetSizes(*newmat,dr,dc,PETSC_DECIDE,PETSC_DECIDE);
 97:   MatSetType(*newmat,MATIS);
 98:   MatSetLocalToGlobalMapping(*newmat,rl2g,cl2g);
 99:   ISLocalToGlobalMappingDestroy(&rl2g);
100:   ISLocalToGlobalMappingDestroy(&cl2g);

102:   /* merge local matrices */
103:   PetscMalloc1(nnz+dr+1,&aux);
104:   PetscMalloc1(nnz,&data);
105:   ii   = aux;
106:   jj   = aux+dr+1;
107:   aa   = data;
108:   *ii  = *(di++) + *(oi++);
109:   for (jd=0,jo=0,cum=0;*ii<nnz;cum++)
110:   {
111:      for (;jd<*di;jd++) { *jj++ = *dj++;      *aa++ = *dd++; }
112:      for (;jo<*oi;jo++) { *jj++ = *oj++ + dc; *aa++ = *od++; }
113:      *(++ii) = *(di++) + *(oi++);
114:   }
115:   for (;cum<dr;cum++) *(++ii) = nnz;
116:   ii   = aux;
117:   jj   = aux+dr+1;
118:   aa   = data;
119:   MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,dr,lc,ii,jj,aa,&lA);

121:   /* create containers to destroy the data */
122:   ptrs[0] = aux;
123:   ptrs[1] = data;
124:   for (i=0; i<2; i++) {
125:     PetscContainer c;

127:     PetscContainerCreate(PETSC_COMM_SELF,&c);
128:     PetscContainerSetPointer(c,ptrs[i]);
129:     PetscContainerSetUserDestroy(c,MatISContainerDestroyArray_Private);
130:     PetscObjectCompose((PetscObject)lA,names[i],(PetscObject)c);
131:     PetscContainerDestroy(&c);
132:   }

134:   /* finalize matrix */
135:   MatISSetLocalMat(*newmat,lA);
136:   MatDestroy(&lA);
137:   MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
138:   MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
139:   return(0);
140: }

142: /*@
143:    MatISSetUpSF - Setup star forest objects used by MatIS.

145:    Collective on MPI_Comm

147:    Input Parameters:
148: +  A - the matrix

150:    Level: advanced

152:    Notes: This function does not need to be called by the user.

154: .keywords: matrix

156: .seealso: MatCreate(), MatCreateIS(), MatISSetPreallocation(), MatISGetLocalMat()
157: @*/
158: PetscErrorCode  MatISSetUpSF(Mat A)
159: {

165:   PetscTryMethod(A,"MatISSetUpSF_C",(Mat),(A));
166:   return(0);
167: }

169: PETSC_INTERN PetscErrorCode MatConvert_Nest_IS(Mat A,MatType type,MatReuse reuse,Mat *newmat)
170: {
171:   Mat                    **nest,*snest,**rnest,lA,B;
172:   IS                     *iscol,*isrow,*islrow,*islcol;
173:   ISLocalToGlobalMapping rl2g,cl2g;
174:   MPI_Comm               comm;
175:   PetscInt               *lr,*lc,*l2gidxs;
176:   PetscInt               i,j,nr,nc,rbs,cbs;
177:   PetscBool              convert,lreuse,*istrans;
178:   PetscErrorCode         ierr;

181:   MatNestGetSubMats(A,&nr,&nc,&nest);
182:   lreuse = PETSC_FALSE;
183:   rnest  = NULL;
184:   if (reuse == MAT_REUSE_MATRIX) {
185:     PetscBool ismatis,isnest;

187:     PetscObjectTypeCompare((PetscObject)*newmat,MATIS,&ismatis);
188:     if (!ismatis) SETERRQ1(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_USER,"Cannot reuse matrix of type %s",((PetscObject)(*newmat))->type);
189:     MatISGetLocalMat(*newmat,&lA);
190:     PetscObjectTypeCompare((PetscObject)lA,MATNEST,&isnest);
191:     if (isnest) {
192:       MatNestGetSubMats(lA,&i,&j,&rnest);
193:       lreuse = (PetscBool)(i == nr && j == nc);
194:       if (!lreuse) rnest = NULL;
195:     }
196:   }
197:   PetscObjectGetComm((PetscObject)A,&comm);
198:   PetscCalloc2(nr,&lr,nc,&lc);
199:   PetscCalloc6(nr,&isrow,nc,&iscol,
200:                       nr,&islrow,nc,&islcol,
201:                       nr*nc,&snest,nr*nc,&istrans);
202:   MatNestGetISs(A,isrow,iscol);
203:   for (i=0;i<nr;i++) {
204:     for (j=0;j<nc;j++) {
205:       PetscBool ismatis;
206:       PetscInt  l1,l2,lb1,lb2,ij=i*nc+j;

208:       /* Null matrix pointers are allowed in MATNEST */
209:       if (!nest[i][j]) continue;

211:       /* Nested matrices should be of type MATIS */
212:       PetscObjectTypeCompare((PetscObject)nest[i][j],MATTRANSPOSEMAT,&istrans[ij]);
213:       if (istrans[ij]) {
214:         Mat T,lT;
215:         MatTransposeGetMat(nest[i][j],&T);
216:         PetscObjectTypeCompare((PetscObject)T,MATIS,&ismatis);
217:         if (!ismatis) SETERRQ2(comm,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) (transposed) is not of type MATIS",i,j);
218:         MatISGetLocalMat(T,&lT);
219:         MatCreateTranspose(lT,&snest[ij]);
220:       } else {
221:         PetscObjectTypeCompare((PetscObject)nest[i][j],MATIS,&ismatis);
222:         if (!ismatis) SETERRQ2(comm,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) is not of type MATIS",i,j);
223:         MatISGetLocalMat(nest[i][j],&snest[ij]);
224:       }

226:       /* Check compatibility of local sizes */
227:       MatGetSize(snest[ij],&l1,&l2);
228:       MatGetBlockSizes(snest[ij],&lb1,&lb2);
229:       if (!l1 || !l2) continue;
230:       if (lr[i] && l1 != lr[i]) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid local size %D != %D",i,j,lr[i],l1);
231:       if (lc[j] && l2 != lc[j]) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid local size %D != %D",i,j,lc[j],l2);
232:       lr[i] = l1;
233:       lc[j] = l2;

235:       /* check compatibilty for local matrix reusage */
236:       if (rnest && !rnest[i][j] != !snest[ij]) lreuse = PETSC_FALSE;
237:     }
238:   }

240: #if defined (PETSC_USE_DEBUG)
241:   /* Check compatibility of l2g maps for rows */
242:   for (i=0;i<nr;i++) {
243:     rl2g = NULL;
244:     for (j=0;j<nc;j++) {
245:       PetscInt n1,n2;

247:       if (!nest[i][j]) continue;
248:       if (istrans[i*nc+j]) {
249:         Mat T;

251:         MatTransposeGetMat(nest[i][j],&T);
252:         MatGetLocalToGlobalMapping(T,NULL,&cl2g);
253:       } else {
254:         MatGetLocalToGlobalMapping(nest[i][j],&cl2g,NULL);
255:       }
256:       ISLocalToGlobalMappingGetSize(cl2g,&n1);
257:       if (!n1) continue;
258:       if (!rl2g) {
259:         rl2g = cl2g;
260:       } else {
261:         const PetscInt *idxs1,*idxs2;
262:         PetscBool      same;

264:         ISLocalToGlobalMappingGetSize(rl2g,&n2);
265:         if (n1 != n2) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid row l2gmap size %D != %D",i,j,n1,n2);
266:         ISLocalToGlobalMappingGetIndices(cl2g,&idxs1);
267:         ISLocalToGlobalMappingGetIndices(rl2g,&idxs2);
268:         PetscMemcmp(idxs1,idxs2,n1*sizeof(PetscInt),&same);
269:         ISLocalToGlobalMappingRestoreIndices(cl2g,&idxs1);
270:         ISLocalToGlobalMappingRestoreIndices(rl2g,&idxs2);
271:         if (!same) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid row l2gmap",i,j);
272:       }
273:     }
274:   }
275:   /* Check compatibility of l2g maps for columns */
276:   for (i=0;i<nc;i++) {
277:     rl2g = NULL;
278:     for (j=0;j<nr;j++) {
279:       PetscInt n1,n2;

281:       if (!nest[j][i]) continue;
282:       if (istrans[j*nc+i]) {
283:         Mat T;

285:         MatTransposeGetMat(nest[j][i],&T);
286:         MatGetLocalToGlobalMapping(T,&cl2g,NULL);
287:       } else {
288:         MatGetLocalToGlobalMapping(nest[j][i],NULL,&cl2g);
289:       }
290:       ISLocalToGlobalMappingGetSize(cl2g,&n1);
291:       if (!n1) continue;
292:       if (!rl2g) {
293:         rl2g = cl2g;
294:       } else {
295:         const PetscInt *idxs1,*idxs2;
296:         PetscBool      same;

298:         ISLocalToGlobalMappingGetSize(rl2g,&n2);
299:         if (n1 != n2) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid column l2gmap size %D != %D",j,i,n1,n2);
300:         ISLocalToGlobalMappingGetIndices(cl2g,&idxs1);
301:         ISLocalToGlobalMappingGetIndices(rl2g,&idxs2);
302:         PetscMemcmp(idxs1,idxs2,n1*sizeof(PetscInt),&same);
303:         ISLocalToGlobalMappingRestoreIndices(cl2g,&idxs1);
304:         ISLocalToGlobalMappingRestoreIndices(rl2g,&idxs2);
305:         if (!same) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) has invalid column l2gmap",j,i);
306:       }
307:     }
308:   }
309: #endif

311:   B = NULL;
312:   if (reuse != MAT_REUSE_MATRIX) {
313:     PetscInt stl;

315:     /* Create l2g map for the rows of the new matrix and index sets for the local MATNEST */
316:     for (i=0,stl=0;i<nr;i++) stl += lr[i];
317:     PetscMalloc1(stl,&l2gidxs);
318:     for (i=0,stl=0;i<nr;i++) {
319:       Mat            usedmat;
320:       Mat_IS         *matis;
321:       const PetscInt *idxs;

323:       /* local IS for local NEST */
324:       ISCreateStride(PETSC_COMM_SELF,lr[i],stl,1,&islrow[i]);

326:       /* l2gmap */
327:       j = 0;
328:       usedmat = nest[i][j];
329:       while (!usedmat && j < nc-1) usedmat = nest[i][++j];
330:       if (!usedmat) SETERRQ(comm,PETSC_ERR_SUP,"Cannot find valid row mat");

332:       if (istrans[i*nc+j]) {
333:         Mat T;
334:         MatTransposeGetMat(usedmat,&T);
335:         usedmat = T;
336:       }
337:       MatISSetUpSF(usedmat);
338:       matis = (Mat_IS*)(usedmat->data);
339:       ISGetIndices(isrow[i],&idxs);
340:       if (istrans[i*nc+j]) {
341:         PetscSFBcastBegin(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
342:         PetscSFBcastEnd(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
343:       } else {
344:         PetscSFBcastBegin(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
345:         PetscSFBcastEnd(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
346:       }
347:       ISRestoreIndices(isrow[i],&idxs);
348:       stl += lr[i];
349:     }
350:     ISLocalToGlobalMappingCreate(comm,1,stl,l2gidxs,PETSC_OWN_POINTER,&rl2g);

352:     /* Create l2g map for columns of the new matrix and index sets for the local MATNEST */
353:     for (i=0,stl=0;i<nc;i++) stl += lc[i];
354:     PetscMalloc1(stl,&l2gidxs);
355:     for (i=0,stl=0;i<nc;i++) {
356:       Mat            usedmat;
357:       Mat_IS         *matis;
358:       const PetscInt *idxs;

360:       /* local IS for local NEST */
361:       ISCreateStride(PETSC_COMM_SELF,lc[i],stl,1,&islcol[i]);

363:       /* l2gmap */
364:       j = 0;
365:       usedmat = nest[j][i];
366:       while (!usedmat && j < nr-1) usedmat = nest[++j][i];
367:       if (!usedmat) SETERRQ(comm,PETSC_ERR_SUP,"Cannot find valid column mat");
368:       if (istrans[j*nc+i]) {
369:         Mat T;
370:         MatTransposeGetMat(usedmat,&T);
371:         usedmat = T;
372:       }
373:       MatISSetUpSF(usedmat);
374:       matis = (Mat_IS*)(usedmat->data);
375:       ISGetIndices(iscol[i],&idxs);
376:       if (istrans[j*nc+i]) {
377:         PetscSFBcastBegin(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
378:         PetscSFBcastEnd(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
379:       } else {
380:         PetscSFBcastBegin(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
381:         PetscSFBcastEnd(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
382:       }
383:       ISRestoreIndices(iscol[i],&idxs);
384:       stl += lc[i];
385:     }
386:     ISLocalToGlobalMappingCreate(comm,1,stl,l2gidxs,PETSC_OWN_POINTER,&cl2g);

388:     /* Create MATIS */
389:     MatCreate(comm,&B);
390:     MatSetSizes(B,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N);
391:     MatGetBlockSizes(A,&rbs,&cbs);
392:     MatSetBlockSizes(B,rbs,cbs);
393:     MatSetType(B,MATIS);
394:     MatSetLocalToGlobalMapping(B,rl2g,cl2g);
395:     ISLocalToGlobalMappingDestroy(&rl2g);
396:     ISLocalToGlobalMappingDestroy(&cl2g);
397:     MatCreateNest(PETSC_COMM_SELF,nr,islrow,nc,islcol,snest,&lA);
398:     for (i=0;i<nr*nc;i++) {
399:       if (istrans[i]) {
400:         MatDestroy(&snest[i]);
401:       }
402:     }
403:     MatISSetLocalMat(B,lA);
404:     MatDestroy(&lA);
405:     MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
406:     MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
407:     if (reuse == MAT_INPLACE_MATRIX) {
408:       MatHeaderReplace(A,&B);
409:     } else {
410:       *newmat = B;
411:     }
412:   } else {
413:     if (lreuse) {
414:       MatISGetLocalMat(*newmat,&lA);
415:       for (i=0;i<nr;i++) {
416:         for (j=0;j<nc;j++) {
417:           if (snest[i*nc+j]) {
418:             MatNestSetSubMat(lA,i,j,snest[i*nc+j]);
419:             if (istrans[i*nc+j]) {
420:               MatDestroy(&snest[i*nc+j]);
421:             }
422:           }
423:         }
424:       }
425:     } else {
426:       PetscInt stl;
427:       for (i=0,stl=0;i<nr;i++) {
428:         ISCreateStride(PETSC_COMM_SELF,lr[i],stl,1,&islrow[i]);
429:         stl  += lr[i];
430:       }
431:       for (i=0,stl=0;i<nc;i++) {
432:         ISCreateStride(PETSC_COMM_SELF,lc[i],stl,1,&islcol[i]);
433:         stl  += lc[i];
434:       }
435:       MatCreateNest(PETSC_COMM_SELF,nr,islrow,nc,islcol,snest,&lA);
436:       if (istrans[i]) {
437:         MatDestroy(&snest[i]);
438:       }
439:       MatISSetLocalMat(*newmat,lA);
440:       MatDestroy(&lA);
441:     }
442:     MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
443:     MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
444:   }

446:   /* Create local matrix in MATNEST format */
447:   convert = PETSC_FALSE;
448:   PetscOptionsGetBool(NULL,((PetscObject)A)->prefix,"-matis_convert_local_nest",&convert,NULL);
449:   if (convert) {
450:     Mat              M;
451:     MatISLocalFields lf;
452:     PetscContainer   c;

454:     MatISGetLocalMat(*newmat,&lA);
455:     MatConvert(lA,MATAIJ,MAT_INITIAL_MATRIX,&M);
456:     MatISSetLocalMat(*newmat,M);
457:     MatDestroy(&M);

459:     /* attach local fields to the matrix */
460:     PetscNew(&lf);
461:     PetscCalloc2(nr,&lf->rf,nc,&lf->cf);
462:     for (i=0;i<nr;i++) {
463:       PetscInt n,st;

465:       ISGetLocalSize(islrow[i],&n);
466:       ISStrideGetInfo(islrow[i],&st,NULL);
467:       ISCreateStride(comm,n,st,1,&lf->rf[i]);
468:     }
469:     for (i=0;i<nc;i++) {
470:       PetscInt n,st;

472:       ISGetLocalSize(islcol[i],&n);
473:       ISStrideGetInfo(islcol[i],&st,NULL);
474:       ISCreateStride(comm,n,st,1,&lf->cf[i]);
475:     }
476:     lf->nr = nr;
477:     lf->nc = nc;
478:     PetscContainerCreate(PetscObjectComm((PetscObject)(*newmat)),&c);
479:     PetscContainerSetPointer(c,lf);
480:     PetscContainerSetUserDestroy(c,MatISContainerDestroyFields_Private);
481:     PetscObjectCompose((PetscObject)(*newmat),"_convert_nest_lfields",(PetscObject)c);
482:     PetscContainerDestroy(&c);
483:   }

485:   /* Free workspace */
486:   for (i=0;i<nr;i++) {
487:     ISDestroy(&islrow[i]);
488:   }
489:   for (i=0;i<nc;i++) {
490:     ISDestroy(&islcol[i]);
491:   }
492:   PetscFree6(isrow,iscol,islrow,islcol,snest,istrans);
493:   PetscFree2(lr,lc);
494:   return(0);
495: }

497: static PetscErrorCode MatDiagonalScale_IS(Mat A, Vec l, Vec r)
498: {
499:   Mat_IS            *matis = (Mat_IS*)A->data;
500:   Vec               ll,rr;
501:   const PetscScalar *Y,*X;
502:   PetscScalar       *x,*y;
503:   PetscErrorCode    ierr;

506:   MatISSetUpSF(A);
507:   if (l) {
508:     ll   = matis->y;
509:     VecGetArrayRead(l,&Y);
510:     VecGetArray(ll,&y);
511:     PetscSFBcastBegin(matis->sf,MPIU_SCALAR,Y,y);
512:   } else {
513:     ll = NULL;
514:   }
515:   if (r) {
516:     rr   = matis->x;
517:     VecGetArrayRead(r,&X);
518:     VecGetArray(rr,&x);
519:     PetscSFBcastBegin(matis->csf,MPIU_SCALAR,X,x);
520:   } else {
521:     rr = NULL;
522:   }
523:   if (ll) {
524:     PetscSFBcastEnd(matis->sf,MPIU_SCALAR,Y,y);
525:     VecRestoreArrayRead(l,&Y);
526:     VecRestoreArray(ll,&y);
527:   }
528:   if (rr) {
529:     PetscSFBcastEnd(matis->csf,MPIU_SCALAR,X,x);
530:     VecRestoreArrayRead(r,&X);
531:     VecRestoreArray(rr,&x);
532:   }
533:   MatDiagonalScale(matis->A,ll,rr);
534:   return(0);
535: }

537: static PetscErrorCode MatGetInfo_IS(Mat A,MatInfoType flag,MatInfo *ginfo)
538: {
539:   Mat_IS         *matis = (Mat_IS*)A->data;
540:   MatInfo        info;
541:   PetscReal      isend[6],irecv[6];
542:   PetscInt       bs;

546:   MatGetBlockSize(A,&bs);
547:   if (matis->A->ops->getinfo) {
548:     MatGetInfo(matis->A,MAT_LOCAL,&info);
549:     isend[0] = info.nz_used;
550:     isend[1] = info.nz_allocated;
551:     isend[2] = info.nz_unneeded;
552:     isend[3] = info.memory;
553:     isend[4] = info.mallocs;
554:   } else {
555:     isend[0] = 0.;
556:     isend[1] = 0.;
557:     isend[2] = 0.;
558:     isend[3] = 0.;
559:     isend[4] = 0.;
560:   }
561:   isend[5] = matis->A->num_ass;
562:   if (flag == MAT_LOCAL) {
563:     ginfo->nz_used      = isend[0];
564:     ginfo->nz_allocated = isend[1];
565:     ginfo->nz_unneeded  = isend[2];
566:     ginfo->memory       = isend[3];
567:     ginfo->mallocs      = isend[4];
568:     ginfo->assemblies   = isend[5];
569:   } else if (flag == MAT_GLOBAL_MAX) {
570:     MPIU_Allreduce(isend,irecv,6,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)A));

572:     ginfo->nz_used      = irecv[0];
573:     ginfo->nz_allocated = irecv[1];
574:     ginfo->nz_unneeded  = irecv[2];
575:     ginfo->memory       = irecv[3];
576:     ginfo->mallocs      = irecv[4];
577:     ginfo->assemblies   = irecv[5];
578:   } else if (flag == MAT_GLOBAL_SUM) {
579:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)A));

581:     ginfo->nz_used      = irecv[0];
582:     ginfo->nz_allocated = irecv[1];
583:     ginfo->nz_unneeded  = irecv[2];
584:     ginfo->memory       = irecv[3];
585:     ginfo->mallocs      = irecv[4];
586:     ginfo->assemblies   = A->num_ass;
587:   }
588:   ginfo->block_size        = bs;
589:   ginfo->fill_ratio_given  = 0;
590:   ginfo->fill_ratio_needed = 0;
591:   ginfo->factor_mallocs    = 0;
592:   return(0);
593: }

595: PetscErrorCode MatTranspose_IS(Mat A,MatReuse reuse,Mat *B)
596: {
597:   Mat                    C,lC,lA;
598:   PetscErrorCode         ierr;

601:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
602:     ISLocalToGlobalMapping rl2g,cl2g;
603:     MatCreate(PetscObjectComm((PetscObject)A),&C);
604:     MatSetSizes(C,A->cmap->n,A->rmap->n,A->cmap->N,A->rmap->N);
605:     MatSetBlockSizes(C,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
606:     MatSetType(C,MATIS);
607:     MatGetLocalToGlobalMapping(A,&rl2g,&cl2g);
608:     MatSetLocalToGlobalMapping(C,cl2g,rl2g);
609:   } else {
610:     C = *B;
611:   }

613:   /* perform local transposition */
614:   MatISGetLocalMat(A,&lA);
615:   MatTranspose(lA,MAT_INITIAL_MATRIX,&lC);
616:   MatISSetLocalMat(C,lC);
617:   MatDestroy(&lC);

619:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
620:     *B = C;
621:   } else {
622:     MatHeaderMerge(A,&C);
623:   }
624:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
625:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
626:   return(0);
627: }

629: PetscErrorCode  MatDiagonalSet_IS(Mat A,Vec D,InsertMode insmode)
630: {
631:   Mat_IS         *is = (Mat_IS*)A->data;

635:   if (!D) { /* this code branch is used by MatShift_IS */
636:     VecSet(is->y,1.);
637:   } else {
638:     VecScatterBegin(is->rctx,D,is->y,INSERT_VALUES,SCATTER_FORWARD);
639:     VecScatterEnd(is->rctx,D,is->y,INSERT_VALUES,SCATTER_FORWARD);
640:   }
641:   VecPointwiseDivide(is->y,is->y,is->counter);
642:   MatDiagonalSet(is->A,is->y,insmode);
643:   return(0);
644: }

646: PetscErrorCode  MatShift_IS(Mat A,PetscScalar a)
647: {

651:   MatDiagonalSet_IS(A,NULL,ADD_VALUES);
652:   return(0);
653: }

655: static PetscErrorCode MatSetValuesLocal_SubMat_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
656: {
658:   Mat_IS         *is = (Mat_IS*)A->data;
659:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

662: #if defined(PETSC_USE_DEBUG)
663:   if (m > MATIS_MAX_ENTRIES_INSERTION || n > MATIS_MAX_ENTRIES_INSERTION) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of row/column indices must be <= %D: they are %D %D",MATIS_MAX_ENTRIES_INSERTION,m,n);
664: #endif
665:   ISLocalToGlobalMappingApply(A->rmap->mapping,m,rows,rows_l);
666:   ISLocalToGlobalMappingApply(A->cmap->mapping,n,cols,cols_l);
667:   MatSetValues(is->A,m,rows_l,n,cols_l,values,addv);
668:   return(0);
669: }

671: static PetscErrorCode MatSetValuesBlockedLocal_SubMat_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
672: {
674:   Mat_IS         *is = (Mat_IS*)A->data;
675:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

678: #if defined(PETSC_USE_DEBUG)
679:   if (m > MATIS_MAX_ENTRIES_INSERTION || n > MATIS_MAX_ENTRIES_INSERTION) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of row/column block indices must be <= %D: they are %D %D",MATIS_MAX_ENTRIES_INSERTION,m,n);
680: #endif
681:   ISLocalToGlobalMappingApplyBlock(A->rmap->mapping,m,rows,rows_l);
682:   ISLocalToGlobalMappingApplyBlock(A->cmap->mapping,n,cols,cols_l);
683:   MatSetValuesBlocked(is->A,m,rows_l,n,cols_l,values,addv);
684:   return(0);
685: }

687: static PetscErrorCode PetscLayoutMapLocal_Private(PetscLayout map,PetscInt N,const PetscInt idxs[], PetscInt *on,PetscInt **oidxs,PetscInt **ogidxs)
688: {
689:   PetscInt      *owners = map->range;
690:   PetscInt       n      = map->n;
691:   PetscSF        sf;
692:   PetscInt      *lidxs,*work = NULL;
693:   PetscSFNode   *ridxs;
694:   PetscMPIInt    rank;
695:   PetscInt       r, p = 0, len = 0;

699:   if (on) *on = 0;              /* squelch -Wmaybe-uninitialized */
700:   /* Create SF where leaves are input idxs and roots are owned idxs (code adapted from MatZeroRowsMapLocal_Private) */
701:   MPI_Comm_rank(map->comm,&rank);
702:   PetscMalloc1(n,&lidxs);
703:   for (r = 0; r < n; ++r) lidxs[r] = -1;
704:   PetscMalloc1(N,&ridxs);
705:   for (r = 0; r < N; ++r) {
706:     const PetscInt idx = idxs[r];
707:     if (idx < 0 || map->N <= idx) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Index %D out of range [0,%D)",idx,map->N);
708:     if (idx < owners[p] || owners[p+1] <= idx) { /* short-circuit the search if the last p owns this idx too */
709:       PetscLayoutFindOwner(map,idx,&p);
710:     }
711:     ridxs[r].rank = p;
712:     ridxs[r].index = idxs[r] - owners[p];
713:   }
714:   PetscSFCreate(map->comm,&sf);
715:   PetscSFSetGraph(sf,n,N,NULL,PETSC_OWN_POINTER,ridxs,PETSC_OWN_POINTER);
716:   PetscSFReduceBegin(sf,MPIU_INT,(PetscInt*)idxs,lidxs,MPI_LOR);
717:   PetscSFReduceEnd(sf,MPIU_INT,(PetscInt*)idxs,lidxs,MPI_LOR);
718:   if (ogidxs) { /* communicate global idxs */
719:     PetscInt cum = 0,start,*work2;

721:     PetscMalloc1(n,&work);
722:     PetscCalloc1(N,&work2);
723:     for (r = 0; r < N; ++r) if (idxs[r] >=0) cum++;
724:     MPI_Scan(&cum,&start,1,MPIU_INT,MPI_SUM,map->comm);
725:     start -= cum;
726:     cum = 0;
727:     for (r = 0; r < N; ++r) if (idxs[r] >=0) work2[r] = start+cum++;
728:     PetscSFReduceBegin(sf,MPIU_INT,work2,work,MPIU_REPLACE);
729:     PetscSFReduceEnd(sf,MPIU_INT,work2,work,MPIU_REPLACE);
730:     PetscFree(work2);
731:   }
732:   PetscSFDestroy(&sf);
733:   /* Compress and put in indices */
734:   for (r = 0; r < n; ++r)
735:     if (lidxs[r] >= 0) {
736:       if (work) work[len] = work[r];
737:       lidxs[len++] = r;
738:     }
739:   if (on) *on = len;
740:   if (oidxs) *oidxs = lidxs;
741:   if (ogidxs) *ogidxs = work;
742:   return(0);
743: }

745: static PetscErrorCode MatGetSubMatrix_IS(Mat mat,IS irow,IS icol,MatReuse scall,Mat *newmat)
746: {
747:   Mat               locmat,newlocmat;
748:   Mat_IS            *newmatis;
749: #if defined(PETSC_USE_DEBUG)
750:   Vec               rtest,ltest;
751:   const PetscScalar *array;
752: #endif
753:   const PetscInt    *idxs;
754:   PetscInt          i,m,n;
755:   PetscErrorCode    ierr;

758:   if (scall == MAT_REUSE_MATRIX) {
759:     PetscBool ismatis;

761:     PetscObjectTypeCompare((PetscObject)*newmat,MATIS,&ismatis);
762:     if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Not of MATIS type");
763:     newmatis = (Mat_IS*)(*newmat)->data;
764:     if (!newmatis->getsub_ris) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Misses local row IS");
765:     if (!newmatis->getsub_cis) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Misses local col IS");
766:   }
767:   /* irow and icol may not have duplicate entries */
768: #if defined(PETSC_USE_DEBUG)
769:   MatCreateVecs(mat,&ltest,&rtest);
770:   ISGetLocalSize(irow,&n);
771:   ISGetIndices(irow,&idxs);
772:   for (i=0;i<n;i++) {
773:     VecSetValue(rtest,idxs[i],1.0,ADD_VALUES);
774:   }
775:   VecAssemblyBegin(rtest);
776:   VecAssemblyEnd(rtest);
777:   VecGetLocalSize(rtest,&n);
778:   VecGetOwnershipRange(rtest,&m,NULL);
779:   VecGetArrayRead(rtest,&array);
780:   for (i=0;i<n;i++) if (array[i] != 0. && array[i] != 1.) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Index %D counted %D times! Irow may not have duplicate entries",i+m,(PetscInt)PetscRealPart(array[i]));
781:   VecRestoreArrayRead(rtest,&array);
782:   ISRestoreIndices(irow,&idxs);
783:   ISGetLocalSize(icol,&n);
784:   ISGetIndices(icol,&idxs);
785:   for (i=0;i<n;i++) {
786:     VecSetValue(ltest,idxs[i],1.0,ADD_VALUES);
787:   }
788:   VecAssemblyBegin(ltest);
789:   VecAssemblyEnd(ltest);
790:   VecGetLocalSize(ltest,&n);
791:   VecGetOwnershipRange(ltest,&m,NULL);
792:   VecGetArrayRead(ltest,&array);
793:   for (i=0;i<n;i++) if (array[i] != 0. && array[i] != 1.) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Index %D counted %D times! Icol may not have duplicate entries",i+m,(PetscInt)PetscRealPart(array[i]));
794:   VecRestoreArrayRead(ltest,&array);
795:   ISRestoreIndices(icol,&idxs);
796:   VecDestroy(&rtest);
797:   VecDestroy(&ltest);
798: #endif
799:   if (scall == MAT_INITIAL_MATRIX) {
800:     Mat_IS                 *matis = (Mat_IS*)mat->data;
801:     ISLocalToGlobalMapping rl2g;
802:     IS                     is;
803:     PetscInt               *lidxs,*lgidxs,*newgidxs;
804:     PetscInt               ll,newloc;
805:     MPI_Comm               comm;

807:     PetscObjectGetComm((PetscObject)mat,&comm);
808:     ISGetLocalSize(irow,&m);
809:     ISGetLocalSize(icol,&n);
810:     MatCreate(comm,newmat);
811:     MatSetType(*newmat,MATIS);
812:     MatSetSizes(*newmat,m,n,PETSC_DECIDE,PETSC_DECIDE);
813:     /* communicate irow to their owners in the layout */
814:     ISGetIndices(irow,&idxs);
815:     PetscLayoutMapLocal_Private(mat->rmap,m,idxs,&ll,&lidxs,&lgidxs);
816:     ISRestoreIndices(irow,&idxs);
817:     MatISSetUpSF(mat);
818:     PetscMemzero(matis->sf_rootdata,matis->sf->nroots*sizeof(PetscInt));
819:     for (i=0;i<ll;i++) matis->sf_rootdata[lidxs[i]] = lgidxs[i]+1;
820:     PetscFree(lidxs);
821:     PetscFree(lgidxs);
822:     PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
823:     PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
824:     for (i=0,newloc=0;i<matis->sf->nleaves;i++) if (matis->sf_leafdata[i]) newloc++;
825:     PetscMalloc1(newloc,&newgidxs);
826:     PetscMalloc1(newloc,&lidxs);
827:     for (i=0,newloc=0;i<matis->sf->nleaves;i++)
828:       if (matis->sf_leafdata[i]) {
829:         lidxs[newloc] = i;
830:         newgidxs[newloc++] = matis->sf_leafdata[i]-1;
831:       }
832:     ISCreateGeneral(comm,newloc,newgidxs,PETSC_OWN_POINTER,&is);
833:     ISLocalToGlobalMappingCreateIS(is,&rl2g);
834:     ISDestroy(&is);
835:     /* local is to extract local submatrix */
836:     newmatis = (Mat_IS*)(*newmat)->data;
837:     ISCreateGeneral(comm,newloc,lidxs,PETSC_OWN_POINTER,&newmatis->getsub_ris);
838:     if (mat->congruentlayouts == -1) { /* first time we compare rows and cols layouts */
839:       PetscBool cong;
840:       PetscLayoutCompare(mat->rmap,mat->cmap,&cong);
841:       if (cong) mat->congruentlayouts = 1;
842:       else      mat->congruentlayouts = 0;
843:     }
844:     if (mat->congruentlayouts && irow == icol) {
845:       MatSetLocalToGlobalMapping(*newmat,rl2g,rl2g);
846:       PetscObjectReference((PetscObject)newmatis->getsub_ris);
847:       newmatis->getsub_cis = newmatis->getsub_ris;
848:     } else {
849:       ISLocalToGlobalMapping cl2g;

851:       /* communicate icol to their owners in the layout */
852:       ISGetIndices(icol,&idxs);
853:       PetscLayoutMapLocal_Private(mat->cmap,n,idxs,&ll,&lidxs,&lgidxs);
854:       ISRestoreIndices(icol,&idxs);
855:       PetscMemzero(matis->csf_rootdata,matis->csf->nroots*sizeof(PetscInt));
856:       for (i=0;i<ll;i++) matis->csf_rootdata[lidxs[i]] = lgidxs[i]+1;
857:       PetscFree(lidxs);
858:       PetscFree(lgidxs);
859:       PetscSFBcastBegin(matis->csf,MPIU_INT,matis->csf_rootdata,matis->csf_leafdata);
860:       PetscSFBcastEnd(matis->csf,MPIU_INT,matis->csf_rootdata,matis->csf_leafdata);
861:       for (i=0,newloc=0;i<matis->csf->nleaves;i++) if (matis->csf_leafdata[i]) newloc++;
862:       PetscMalloc1(newloc,&newgidxs);
863:       PetscMalloc1(newloc,&lidxs);
864:       for (i=0,newloc=0;i<matis->csf->nleaves;i++)
865:         if (matis->csf_leafdata[i]) {
866:           lidxs[newloc] = i;
867:           newgidxs[newloc++] = matis->csf_leafdata[i]-1;
868:         }
869:       ISCreateGeneral(comm,newloc,newgidxs,PETSC_OWN_POINTER,&is);
870:       ISLocalToGlobalMappingCreateIS(is,&cl2g);
871:       ISDestroy(&is);
872:       /* local is to extract local submatrix */
873:       ISCreateGeneral(comm,newloc,lidxs,PETSC_OWN_POINTER,&newmatis->getsub_cis);
874:       MatSetLocalToGlobalMapping(*newmat,rl2g,cl2g);
875:       ISLocalToGlobalMappingDestroy(&cl2g);
876:     }
877:     ISLocalToGlobalMappingDestroy(&rl2g);
878:   } else {
879:     MatISGetLocalMat(*newmat,&newlocmat);
880:   }
881:   MatISGetLocalMat(mat,&locmat);
882:   newmatis = (Mat_IS*)(*newmat)->data;
883:   MatGetSubMatrix(locmat,newmatis->getsub_ris,newmatis->getsub_cis,scall,&newlocmat);
884:   if (scall == MAT_INITIAL_MATRIX) {
885:     MatISSetLocalMat(*newmat,newlocmat);
886:     MatDestroy(&newlocmat);
887:   }
888:   MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
889:   MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
890:   return(0);
891: }

893: static PetscErrorCode MatCopy_IS(Mat A,Mat B,MatStructure str)
894: {
895:   Mat_IS         *a = (Mat_IS*)A->data,*b;
896:   PetscBool      ismatis;

900:   PetscObjectTypeCompare((PetscObject)B,MATIS,&ismatis);
901:   if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_SUP,"Need to be implemented");
902:   b = (Mat_IS*)B->data;
903:   MatCopy(a->A,b->A,str);
904:   return(0);
905: }

907: static PetscErrorCode MatMissingDiagonal_IS(Mat A,PetscBool  *missing,PetscInt *d)
908: {
909:   Vec               v;
910:   const PetscScalar *array;
911:   PetscInt          i,n;
912:   PetscErrorCode    ierr;

915:   *missing = PETSC_FALSE;
916:   MatCreateVecs(A,NULL,&v);
917:   MatGetDiagonal(A,v);
918:   VecGetLocalSize(v,&n);
919:   VecGetArrayRead(v,&array);
920:   for (i=0;i<n;i++) if (array[i] == 0.) break;
921:   VecRestoreArrayRead(v,&array);
922:   VecDestroy(&v);
923:   if (i != n) *missing = PETSC_TRUE;
924:   if (d) {
925:     *d = -1;
926:     if (*missing) {
927:       PetscInt rstart;
928:       MatGetOwnershipRange(A,&rstart,NULL);
929:       *d = i+rstart;
930:     }
931:   }
932:   return(0);
933: }

935: static PetscErrorCode MatISSetUpSF_IS(Mat B)
936: {
937:   Mat_IS         *matis = (Mat_IS*)(B->data);
938:   const PetscInt *gidxs;
939:   PetscInt       nleaves;

943:   if (matis->sf) return(0);
944:   PetscSFCreate(PetscObjectComm((PetscObject)B),&matis->sf);
945:   ISLocalToGlobalMappingGetIndices(B->rmap->mapping,&gidxs);
946:   ISLocalToGlobalMappingGetSize(B->rmap->mapping,&nleaves);
947:   PetscSFSetGraphLayout(matis->sf,B->rmap,nleaves,NULL,PETSC_OWN_POINTER,gidxs);
948:   ISLocalToGlobalMappingRestoreIndices(B->rmap->mapping,&gidxs);
949:   PetscMalloc2(matis->sf->nroots,&matis->sf_rootdata,matis->sf->nleaves,&matis->sf_leafdata);
950:   if (B->rmap->mapping != B->cmap->mapping) { /* setup SF for columns */
951:     ISLocalToGlobalMappingGetSize(B->cmap->mapping,&nleaves);
952:     PetscSFCreate(PetscObjectComm((PetscObject)B),&matis->csf);
953:     ISLocalToGlobalMappingGetIndices(B->cmap->mapping,&gidxs);
954:     PetscSFSetGraphLayout(matis->csf,B->cmap,nleaves,NULL,PETSC_OWN_POINTER,gidxs);
955:     ISLocalToGlobalMappingRestoreIndices(B->cmap->mapping,&gidxs);
956:     PetscMalloc2(matis->csf->nroots,&matis->csf_rootdata,matis->csf->nleaves,&matis->csf_leafdata);
957:   } else {
958:     matis->csf = matis->sf;
959:     matis->csf_leafdata = matis->sf_leafdata;
960:     matis->csf_rootdata = matis->sf_rootdata;
961:   }
962:   return(0);
963: }

965: /*@
966:    MatISSetPreallocation - Preallocates memory for a MATIS parallel matrix.

968:    Collective on MPI_Comm

970:    Input Parameters:
971: +  B - the matrix
972: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
973:            (same value is used for all local rows)
974: .  d_nnz - array containing the number of nonzeros in the various rows of the
975:            DIAGONAL portion of the local submatrix (possibly different for each row)
976:            or NULL, if d_nz is used to specify the nonzero structure.
977:            The size of this array is equal to the number of local rows, i.e 'm'.
978:            For matrices that will be factored, you must leave room for (and set)
979:            the diagonal entry even if it is zero.
980: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
981:            submatrix (same value is used for all local rows).
982: -  o_nnz - array containing the number of nonzeros in the various rows of the
983:            OFF-DIAGONAL portion of the local submatrix (possibly different for
984:            each row) or NULL, if o_nz is used to specify the nonzero
985:            structure. The size of this array is equal to the number
986:            of local rows, i.e 'm'.

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

990:    Level: intermediate

992:    Notes: This function has the same interface as the MPIAIJ preallocation routine in order to simplify the transition
993:           from the asssembled format to the unassembled one. It overestimates the preallocation of MATIS local
994:           matrices; for exact preallocation, the user should set the preallocation directly on local matrix objects.

996: .keywords: matrix

998: .seealso: MatCreate(), MatCreateIS(), MatMPIAIJSetPreallocation(), MatISGetLocalMat(), MATIS
999: @*/
1000: PetscErrorCode  MatISSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
1001: {

1007:   PetscTryMethod(B,"MatISSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
1008:   return(0);
1009: }

1011: static PetscErrorCode  MatISSetPreallocation_IS(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
1012: {
1013:   Mat_IS         *matis = (Mat_IS*)(B->data);
1014:   PetscInt       bs,i,nlocalcols;

1018:   if (!matis->A) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_SUP,"You should first call MatSetLocalToGlobalMapping");
1019:   MatISSetUpSF(B);

1021:   if (!d_nnz) for (i=0;i<matis->sf->nroots;i++) matis->sf_rootdata[i] = d_nz;
1022:   else for (i=0;i<matis->sf->nroots;i++) matis->sf_rootdata[i] = d_nnz[i];

1024:   if (!o_nnz) for (i=0;i<matis->sf->nroots;i++) matis->sf_rootdata[i] += o_nz;
1025:   else for (i=0;i<matis->sf->nroots;i++) matis->sf_rootdata[i] += o_nnz[i];

1027:   PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1028:   MatGetSize(matis->A,NULL,&nlocalcols);
1029:   MatGetBlockSize(matis->A,&bs);
1030:   PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);

1032:   for (i=0;i<matis->sf->nleaves;i++) matis->sf_leafdata[i] = PetscMin(matis->sf_leafdata[i],nlocalcols);
1033:   MatSeqAIJSetPreallocation(matis->A,0,matis->sf_leafdata);

1035:   for (i=0;i<matis->sf->nleaves/bs;i++) matis->sf_leafdata[i] = matis->sf_leafdata[i*bs]/bs;
1036:   MatSeqBAIJSetPreallocation(matis->A,bs,0,matis->sf_leafdata);

1038:   for (i=0;i<matis->sf->nleaves/bs;i++) matis->sf_leafdata[i] = matis->sf_leafdata[i]-i;
1039:   MatSeqSBAIJSetPreallocation(matis->A,bs,0,matis->sf_leafdata);
1040:   return(0);
1041: }

1043: PETSC_EXTERN PetscErrorCode MatISSetMPIXAIJPreallocation_Private(Mat A, Mat B, PetscBool maxreduce)
1044: {
1045:   Mat_IS          *matis = (Mat_IS*)(A->data);
1046:   PetscInt        *my_dnz,*my_onz,*dnz,*onz,*mat_ranges,*row_ownership;
1047:   const PetscInt  *global_indices_r,*global_indices_c;
1048:   PetscInt        i,j,bs,rows,cols;
1049:   PetscInt        lrows,lcols;
1050:   PetscInt        local_rows,local_cols;
1051:   PetscMPIInt     nsubdomains;
1052:   PetscBool       isdense,issbaij;
1053:   PetscErrorCode  ierr;

1056:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&nsubdomains);
1057:   MatGetSize(A,&rows,&cols);
1058:   MatGetBlockSize(A,&bs);
1059:   MatGetSize(matis->A,&local_rows,&local_cols);
1060:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQDENSE,&isdense);
1061:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQSBAIJ,&issbaij);
1062:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&global_indices_r);
1063:   if (A->rmap->mapping != A->cmap->mapping) {
1064:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&global_indices_c);
1065:   } else {
1066:     global_indices_c = global_indices_r;
1067:   }

1069:   if (issbaij) {
1070:     MatGetRowUpperTriangular(matis->A);
1071:   }
1072:   /*
1073:      An SF reduce is needed to sum up properly on shared rows.
1074:      Note that generally preallocation is not exact, since it overestimates nonzeros
1075:   */
1076:   MatISSetUpSF(A);
1077:   MatGetLocalSize(A,&lrows,&lcols);
1078:   MatPreallocateInitialize(PetscObjectComm((PetscObject)A),lrows,lcols,dnz,onz);
1079:   /* All processes need to compute entire row ownership */
1080:   PetscMalloc1(rows,&row_ownership);
1081:   MatGetOwnershipRanges(A,(const PetscInt**)&mat_ranges);
1082:   for (i=0;i<nsubdomains;i++) {
1083:     for (j=mat_ranges[i];j<mat_ranges[i+1];j++) {
1084:       row_ownership[j] = i;
1085:     }
1086:   }
1087:   MatGetOwnershipRangesColumn(A,(const PetscInt**)&mat_ranges);

1089:   /*
1090:      my_dnz and my_onz contains exact contribution to preallocation from each local mat
1091:      then, they will be summed up properly. This way, preallocation is always sufficient
1092:   */
1093:   PetscCalloc2(local_rows,&my_dnz,local_rows,&my_onz);
1094:   /* preallocation as a MATAIJ */
1095:   if (isdense) { /* special case for dense local matrices */
1096:     for (i=0;i<local_rows;i++) {
1097:       PetscInt index_row = global_indices_r[i];
1098:       for (j=i;j<local_rows;j++) {
1099:         PetscInt owner = row_ownership[index_row];
1100:         PetscInt index_col = global_indices_c[j];
1101:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1102:           my_dnz[i] += 1;
1103:         } else { /* offdiag block */
1104:           my_onz[i] += 1;
1105:         }
1106:         /* same as before, interchanging rows and cols */
1107:         if (i != j) {
1108:           owner = row_ownership[index_col];
1109:           if (index_row > mat_ranges[owner]-1 && index_row < mat_ranges[owner+1] ) {
1110:             my_dnz[j] += 1;
1111:           } else {
1112:             my_onz[j] += 1;
1113:           }
1114:         }
1115:       }
1116:     }
1117:   } else if (matis->A->ops->getrowij) {
1118:     const PetscInt *ii,*jj,*jptr;
1119:     PetscBool      done;
1120:     MatGetRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&local_rows,&ii,&jj,&done);
1121:     if (!done) SETERRQ(PetscObjectComm((PetscObject)(matis->A)),PETSC_ERR_PLIB,"Error in MatGetRowIJ");
1122:     jptr = jj;
1123:     for (i=0;i<local_rows;i++) {
1124:       PetscInt index_row = global_indices_r[i];
1125:       for (j=0;j<ii[i+1]-ii[i];j++,jptr++) {
1126:         PetscInt owner = row_ownership[index_row];
1127:         PetscInt index_col = global_indices_c[*jptr];
1128:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1129:           my_dnz[i] += 1;
1130:         } else { /* offdiag block */
1131:           my_onz[i] += 1;
1132:         }
1133:         /* same as before, interchanging rows and cols */
1134:         if (issbaij && index_col != index_row) {
1135:           owner = row_ownership[index_col];
1136:           if (index_row > mat_ranges[owner]-1 && index_row < mat_ranges[owner+1] ) {
1137:             my_dnz[*jptr] += 1;
1138:           } else {
1139:             my_onz[*jptr] += 1;
1140:           }
1141:         }
1142:       }
1143:     }
1144:     MatRestoreRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&local_rows,&ii,&jj,&done);
1145:     if (!done) SETERRQ(PetscObjectComm((PetscObject)(matis->A)),PETSC_ERR_PLIB,"Error in MatRestoreRowIJ");
1146:   } else { /* loop over rows and use MatGetRow */
1147:     for (i=0;i<local_rows;i++) {
1148:       const PetscInt *cols;
1149:       PetscInt       ncols,index_row = global_indices_r[i];
1150:       MatGetRow(matis->A,i,&ncols,&cols,NULL);
1151:       for (j=0;j<ncols;j++) {
1152:         PetscInt owner = row_ownership[index_row];
1153:         PetscInt index_col = global_indices_c[cols[j]];
1154:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1155:           my_dnz[i] += 1;
1156:         } else { /* offdiag block */
1157:           my_onz[i] += 1;
1158:         }
1159:         /* same as before, interchanging rows and cols */
1160:         if (issbaij && index_col != index_row) {
1161:           owner = row_ownership[index_col];
1162:           if (index_row > mat_ranges[owner]-1 && index_row < mat_ranges[owner+1] ) {
1163:             my_dnz[cols[j]] += 1;
1164:           } else {
1165:             my_onz[cols[j]] += 1;
1166:           }
1167:         }
1168:       }
1169:       MatRestoreRow(matis->A,i,&ncols,&cols,NULL);
1170:     }
1171:   }
1172:   if (global_indices_c != global_indices_r) {
1173:     ISLocalToGlobalMappingRestoreIndices(A->cmap->mapping,&global_indices_c);
1174:   }
1175:   ISLocalToGlobalMappingRestoreIndices(A->rmap->mapping,&global_indices_r);
1176:   PetscFree(row_ownership);

1178:   /* Reduce my_dnz and my_onz */
1179:   if (maxreduce) {
1180:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_dnz,dnz,MPI_MAX);
1181:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_onz,onz,MPI_MAX);
1182:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_dnz,dnz,MPI_MAX);
1183:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_onz,onz,MPI_MAX);
1184:   } else {
1185:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_dnz,dnz,MPI_SUM);
1186:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_onz,onz,MPI_SUM);
1187:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_dnz,dnz,MPI_SUM);
1188:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_onz,onz,MPI_SUM);
1189:   }
1190:   PetscFree2(my_dnz,my_onz);

1192:   /* Resize preallocation if overestimated */
1193:   for (i=0;i<lrows;i++) {
1194:     dnz[i] = PetscMin(dnz[i],lcols);
1195:     onz[i] = PetscMin(onz[i],cols-lcols);
1196:   }

1198:   /* Set preallocation */
1199:   MatMPIAIJSetPreallocation(B,0,dnz,0,onz);
1200:   for (i=0;i<lrows/bs;i++) {
1201:     dnz[i] = dnz[i*bs]/bs;
1202:     onz[i] = onz[i*bs]/bs;
1203:   }
1204:   MatMPIBAIJSetPreallocation(B,bs,0,dnz,0,onz);
1205:   MatMPISBAIJSetPreallocation(B,bs,0,dnz,0,onz);
1206:   MatPreallocateFinalize(dnz,onz);
1207:   if (issbaij) {
1208:     MatRestoreRowUpperTriangular(matis->A);
1209:   }
1210:   return(0);
1211: }

1213: static PetscErrorCode MatISGetMPIXAIJ_IS(Mat mat, MatReuse reuse, Mat *M)
1214: {
1215:   Mat_IS         *matis = (Mat_IS*)(mat->data);
1216:   Mat            local_mat;
1217:   /* info on mat */
1218:   PetscInt       bs,rows,cols,lrows,lcols;
1219:   PetscInt       local_rows,local_cols;
1220:   PetscBool      isseqdense,isseqsbaij,isseqaij,isseqbaij;
1221: #if defined (PETSC_USE_DEBUG)
1222:   PetscBool      lb[4],bb[4];
1223: #endif
1224:   PetscMPIInt    nsubdomains;
1225:   /* values insertion */
1226:   PetscScalar    *array;
1227:   /* work */

1231:   /* get info from mat */
1232:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&nsubdomains);
1233:   if (nsubdomains == 1) {
1234:     Mat            B;
1235:     IS             rows,cols;
1236:     IS             irows,icols;
1237:     const PetscInt *ridxs,*cidxs;

1239:     ISLocalToGlobalMappingGetIndices(mat->rmap->mapping,&ridxs);
1240:     ISLocalToGlobalMappingGetIndices(mat->cmap->mapping,&cidxs);
1241:     ISCreateGeneral(PETSC_COMM_SELF,mat->rmap->n,ridxs,PETSC_USE_POINTER,&rows);
1242:     ISCreateGeneral(PETSC_COMM_SELF,mat->cmap->n,cidxs,PETSC_USE_POINTER,&cols);
1243:     ISLocalToGlobalMappingRestoreIndices(mat->rmap->mapping,&ridxs);
1244:     ISLocalToGlobalMappingRestoreIndices(mat->cmap->mapping,&cidxs);
1245:     ISSetPermutation(rows);
1246:     ISSetPermutation(cols);
1247:     ISInvertPermutation(rows,mat->rmap->n,&irows);
1248:     ISInvertPermutation(cols,mat->cmap->n,&icols);
1249:     ISDestroy(&cols);
1250:     ISDestroy(&rows);
1251:     MatConvert(matis->A,MATAIJ,MAT_INITIAL_MATRIX,&B);
1252:     MatGetSubMatrix(B,irows,icols,reuse,M);
1253:     MatDestroy(&B);
1254:     ISDestroy(&icols);
1255:     ISDestroy(&irows);
1256:     return(0);
1257:   }
1258:   MatGetSize(mat,&rows,&cols);
1259:   MatGetBlockSize(mat,&bs);
1260:   MatGetLocalSize(mat,&lrows,&lcols);
1261:   MatGetSize(matis->A,&local_rows,&local_cols);
1262:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQDENSE,&isseqdense);
1263:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQAIJ,&isseqaij);
1264:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQBAIJ,&isseqbaij);
1265:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQSBAIJ,&isseqsbaij);
1266:   if (!isseqdense && !isseqaij && !isseqbaij && !isseqsbaij) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not for matrix type %s",((PetscObject)(matis->A))->type_name);
1267: #if defined (PETSC_USE_DEBUG)
1268:   lb[0] = isseqdense;
1269:   lb[1] = isseqaij;
1270:   lb[2] = isseqbaij;
1271:   lb[3] = isseqsbaij;
1272:   MPIU_Allreduce(lb,bb,4,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)mat));
1273:   if (!bb[0] && !bb[1] && !bb[2] && !bb[3]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Local matrices must have the same type");
1274: #endif

1276:   if (reuse == MAT_INITIAL_MATRIX) {
1277:     MatCreate(PetscObjectComm((PetscObject)mat),M);
1278:     MatSetSizes(*M,lrows,lcols,rows,cols);
1279:     MatSetBlockSize(*M,bs);
1280:     if (!isseqsbaij) {
1281:       MatSetType(*M,MATAIJ);
1282:     } else {
1283:       MatSetType(*M,MATSBAIJ);
1284:     }
1285:     MatISSetMPIXAIJPreallocation_Private(mat,*M,PETSC_FALSE);
1286:   } else {
1287:     PetscInt mbs,mrows,mcols,mlrows,mlcols;
1288:     /* some checks */
1289:     MatGetBlockSize(*M,&mbs);
1290:     MatGetSize(*M,&mrows,&mcols);
1291:     MatGetLocalSize(*M,&mlrows,&mlcols);
1292:     if (mrows != rows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of rows (%d != %d)",rows,mrows);
1293:     if (mcols != cols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of cols (%d != %d)",cols,mcols);
1294:     if (mlrows != lrows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of local rows (%d != %d)",lrows,mlrows);
1295:     if (mlcols != lcols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of local cols (%d != %d)",lcols,mlcols);
1296:     if (mbs != bs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong block size (%d != %d)",bs,mbs);
1297:     MatZeroEntries(*M);
1298:   }

1300:   if (isseqsbaij) {
1301:     MatConvert(matis->A,MATSEQBAIJ,MAT_INITIAL_MATRIX,&local_mat);
1302:   } else {
1303:     PetscObjectReference((PetscObject)matis->A);
1304:     local_mat = matis->A;
1305:   }

1307:   /* Set values */
1308:   MatSetLocalToGlobalMapping(*M,mat->rmap->mapping,mat->cmap->mapping);
1309:   if (isseqdense) { /* special case for dense local matrices */
1310:     PetscInt i,*dummy_rows,*dummy_cols;

1312:     if (local_rows != local_cols) {
1313:       PetscMalloc2(local_rows,&dummy_rows,local_cols,&dummy_cols);
1314:       for (i=0;i<local_rows;i++) dummy_rows[i] = i;
1315:       for (i=0;i<local_cols;i++) dummy_cols[i] = i;
1316:     } else {
1317:       PetscMalloc1(local_rows,&dummy_rows);
1318:       for (i=0;i<local_rows;i++) dummy_rows[i] = i;
1319:       dummy_cols = dummy_rows;
1320:     }
1321:     MatSetOption(*M,MAT_ROW_ORIENTED,PETSC_FALSE);
1322:     MatDenseGetArray(local_mat,&array);
1323:     MatSetValuesLocal(*M,local_rows,dummy_rows,local_cols,dummy_cols,array,ADD_VALUES);
1324:     MatDenseRestoreArray(local_mat,&array);
1325:     if (dummy_rows != dummy_cols) {
1326:       PetscFree2(dummy_rows,dummy_cols);
1327:     } else {
1328:       PetscFree(dummy_rows);
1329:     }
1330:   } else if (isseqaij) {
1331:     PetscInt  i,nvtxs,*xadj,*adjncy;
1332:     PetscBool done;

1334:     MatGetRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
1335:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatGetRowIJ");
1336:     MatSeqAIJGetArray(local_mat,&array);
1337:     for (i=0;i<nvtxs;i++) {
1338:       MatSetValuesLocal(*M,1,&i,xadj[i+1]-xadj[i],adjncy+xadj[i],array+xadj[i],ADD_VALUES);
1339:     }
1340:     MatRestoreRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
1341:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatRestoreRowIJ");
1342:     MatSeqAIJRestoreArray(local_mat,&array);
1343:   } else { /* very basic values insertion for all other matrix types */
1344:     PetscInt i;

1346:     for (i=0;i<local_rows;i++) {
1347:       PetscInt       j;
1348:       const PetscInt *local_indices_cols;

1350:       MatGetRow(local_mat,i,&j,&local_indices_cols,(const PetscScalar**)&array);
1351:       MatSetValuesLocal(*M,1,&i,j,local_indices_cols,array,ADD_VALUES);
1352:       MatRestoreRow(local_mat,i,&j,&local_indices_cols,(const PetscScalar**)&array);
1353:     }
1354:   }
1355:   MatAssemblyBegin(*M,MAT_FINAL_ASSEMBLY);
1356:   MatDestroy(&local_mat);
1357:   MatAssemblyEnd(*M,MAT_FINAL_ASSEMBLY);
1358:   if (isseqdense) {
1359:     MatSetOption(*M,MAT_ROW_ORIENTED,PETSC_TRUE);
1360:   }
1361:   return(0);
1362: }

1364: /*@
1365:     MatISGetMPIXAIJ - Converts MATIS matrix into a parallel AIJ format

1367:   Input Parameter:
1368: .  mat - the matrix (should be of type MATIS)
1369: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

1371:   Output Parameter:
1372: .  newmat - the matrix in AIJ format

1374:   Level: developer

1376:   Notes: mat and *newmat cannot be the same object when MAT_REUSE_MATRIX is requested.

1378: .seealso: MATIS
1379: @*/
1380: PetscErrorCode MatISGetMPIXAIJ(Mat mat, MatReuse reuse, Mat *newmat)
1381: {

1388:   if (reuse != MAT_INITIAL_MATRIX) {
1391:     if (mat == *newmat) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse the same matrix");
1392:   }
1393:   PetscUseMethod(mat,"MatISGetMPIXAIJ_C",(Mat,MatReuse,Mat*),(mat,reuse,newmat));
1394:   return(0);
1395: }

1397: PetscErrorCode MatDuplicate_IS(Mat mat,MatDuplicateOption op,Mat *newmat)
1398: {
1400:   Mat_IS         *matis = (Mat_IS*)(mat->data);
1401:   PetscInt       bs,m,n,M,N;
1402:   Mat            B,localmat;

1405:   MatGetBlockSize(mat,&bs);
1406:   MatGetSize(mat,&M,&N);
1407:   MatGetLocalSize(mat,&m,&n);
1408:   MatCreateIS(PetscObjectComm((PetscObject)mat),bs,m,n,M,N,mat->rmap->mapping,mat->cmap->mapping,&B);
1409:   MatDuplicate(matis->A,op,&localmat);
1410:   MatISSetLocalMat(B,localmat);
1411:   MatDestroy(&localmat);
1412:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1413:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1414:   *newmat = B;
1415:   return(0);
1416: }

1418: static PetscErrorCode MatIsHermitian_IS(Mat A,PetscReal tol,PetscBool  *flg)
1419: {
1421:   Mat_IS         *matis = (Mat_IS*)A->data;
1422:   PetscBool      local_sym;

1425:   MatIsHermitian(matis->A,tol,&local_sym);
1426:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1427:   return(0);
1428: }

1430: static PetscErrorCode MatIsSymmetric_IS(Mat A,PetscReal tol,PetscBool  *flg)
1431: {
1433:   Mat_IS         *matis = (Mat_IS*)A->data;
1434:   PetscBool      local_sym;

1437:   MatIsSymmetric(matis->A,tol,&local_sym);
1438:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1439:   return(0);
1440: }

1442: static PetscErrorCode MatIsStructurallySymmetric_IS(Mat A,PetscBool  *flg)
1443: {
1445:   Mat_IS         *matis = (Mat_IS*)A->data;
1446:   PetscBool      local_sym;

1449:   if (A->rmap->mapping != A->cmap->mapping) {
1450:     *flg = PETSC_FALSE;
1451:     return(0);
1452:   }
1453:   MatIsStructurallySymmetric(matis->A,&local_sym);
1454:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1455:   return(0);
1456: }

1458: static PetscErrorCode MatDestroy_IS(Mat A)
1459: {
1461:   Mat_IS         *b = (Mat_IS*)A->data;

1464:   MatDestroy(&b->A);
1465:   VecScatterDestroy(&b->cctx);
1466:   VecScatterDestroy(&b->rctx);
1467:   VecDestroy(&b->x);
1468:   VecDestroy(&b->y);
1469:   VecDestroy(&b->counter);
1470:   ISDestroy(&b->getsub_ris);
1471:   ISDestroy(&b->getsub_cis);
1472:   if (b->sf != b->csf) {
1473:     PetscSFDestroy(&b->csf);
1474:     PetscFree2(b->csf_rootdata,b->csf_leafdata);
1475:   }
1476:   PetscSFDestroy(&b->sf);
1477:   PetscFree2(b->sf_rootdata,b->sf_leafdata);
1478:   PetscFree(A->data);
1479:   PetscObjectChangeTypeName((PetscObject)A,0);
1480:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",NULL);
1481:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",NULL);
1482:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",NULL);
1483:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",NULL);
1484:   PetscObjectComposeFunction((PetscObject)A,"MatISSetUpSF_C",NULL);
1485:   return(0);
1486: }

1488: static PetscErrorCode MatMult_IS(Mat A,Vec x,Vec y)
1489: {
1491:   Mat_IS         *is  = (Mat_IS*)A->data;
1492:   PetscScalar    zero = 0.0;

1495:   /*  scatter the global vector x into the local work vector */
1496:   VecScatterBegin(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);
1497:   VecScatterEnd(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);

1499:   /* multiply the local matrix */
1500:   MatMult(is->A,is->x,is->y);

1502:   /* scatter product back into global memory */
1503:   VecSet(y,zero);
1504:   VecScatterBegin(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
1505:   VecScatterEnd(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
1506:   return(0);
1507: }

1509: static PetscErrorCode MatMultAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
1510: {
1511:   Vec            temp_vec;

1515:   if (v3 != v2) {
1516:     MatMult(A,v1,v3);
1517:     VecAXPY(v3,1.0,v2);
1518:   } else {
1519:     VecDuplicate(v2,&temp_vec);
1520:     MatMult(A,v1,temp_vec);
1521:     VecAXPY(temp_vec,1.0,v2);
1522:     VecCopy(temp_vec,v3);
1523:     VecDestroy(&temp_vec);
1524:   }
1525:   return(0);
1526: }

1528: static PetscErrorCode MatMultTranspose_IS(Mat A,Vec y,Vec x)
1529: {
1530:   Mat_IS         *is = (Mat_IS*)A->data;

1534:   /*  scatter the global vector x into the local work vector */
1535:   VecScatterBegin(is->rctx,y,is->y,INSERT_VALUES,SCATTER_FORWARD);
1536:   VecScatterEnd(is->rctx,y,is->y,INSERT_VALUES,SCATTER_FORWARD);

1538:   /* multiply the local matrix */
1539:   MatMultTranspose(is->A,is->y,is->x);

1541:   /* scatter product back into global vector */
1542:   VecSet(x,0);
1543:   VecScatterBegin(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
1544:   VecScatterEnd(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
1545:   return(0);
1546: }

1548: static PetscErrorCode MatMultTransposeAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
1549: {
1550:   Vec            temp_vec;

1554:   if (v3 != v2) {
1555:     MatMultTranspose(A,v1,v3);
1556:     VecAXPY(v3,1.0,v2);
1557:   } else {
1558:     VecDuplicate(v2,&temp_vec);
1559:     MatMultTranspose(A,v1,temp_vec);
1560:     VecAXPY(temp_vec,1.0,v2);
1561:     VecCopy(temp_vec,v3);
1562:     VecDestroy(&temp_vec);
1563:   }
1564:   return(0);
1565: }

1567: static PetscErrorCode MatView_IS(Mat A,PetscViewer viewer)
1568: {
1569:   Mat_IS         *a = (Mat_IS*)A->data;
1571:   PetscViewer    sviewer;
1572:   PetscBool      isascii,view = PETSC_TRUE;

1575:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
1576:   if (isascii)  {
1577:     PetscViewerFormat format;

1579:     PetscViewerGetFormat(viewer,&format);
1580:     if (format == PETSC_VIEWER_ASCII_INFO) view = PETSC_FALSE;
1581:   }
1582:   if (!view) return(0);
1583:   PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1584:   MatView(a->A,sviewer);
1585:   PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1586:   PetscViewerFlush(viewer);
1587:   return(0);
1588: }

1590: static PetscErrorCode MatSetLocalToGlobalMapping_IS(Mat A,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1591: {
1593:   PetscInt       nr,rbs,nc,cbs;
1594:   Mat_IS         *is = (Mat_IS*)A->data;
1595:   IS             from,to;
1596:   Vec            cglobal,rglobal;

1601:   /* Destroy any previous data */
1602:   VecDestroy(&is->x);
1603:   VecDestroy(&is->y);
1604:   VecDestroy(&is->counter);
1605:   VecScatterDestroy(&is->rctx);
1606:   VecScatterDestroy(&is->cctx);
1607:   MatDestroy(&is->A);
1608:   PetscSFDestroy(&is->sf);
1609:   PetscFree2(is->sf_rootdata,is->sf_leafdata);

1611:   /* Setup Layout and set local to global maps */
1612:   PetscLayoutSetUp(A->rmap);
1613:   PetscLayoutSetUp(A->cmap);
1614:   PetscLayoutSetISLocalToGlobalMapping(A->rmap,rmapping);
1615:   PetscLayoutSetISLocalToGlobalMapping(A->cmap,cmapping);

1617:   /* Create the local matrix A */
1618:   ISLocalToGlobalMappingGetSize(rmapping,&nr);
1619:   ISLocalToGlobalMappingGetBlockSize(rmapping,&rbs);
1620:   ISLocalToGlobalMappingGetSize(cmapping,&nc);
1621:   ISLocalToGlobalMappingGetBlockSize(cmapping,&cbs);
1622:   MatCreate(PETSC_COMM_SELF,&is->A);
1623:   MatSetType(is->A,MATAIJ);
1624:   MatSetSizes(is->A,nr,nc,nr,nc);
1625:   MatSetBlockSizes(is->A,rbs,cbs);
1626:   MatSetOptionsPrefix(is->A,((PetscObject)A)->prefix);
1627:   MatAppendOptionsPrefix(is->A,"is_");
1628:   MatSetFromOptions(is->A);

1630:   if (!is->islocalref) { /* setup scatters and local vectors for MatMult */
1631:     /* Create the local work vectors */
1632:     MatCreateVecs(is->A,&is->x,&is->y);

1634:     /* setup the global to local scatters */
1635:     MatCreateVecs(A,&cglobal,&rglobal);
1636:     ISCreateStride(PETSC_COMM_SELF,nr,0,1,&to);
1637:     ISLocalToGlobalMappingApplyIS(rmapping,to,&from);
1638:     VecScatterCreate(rglobal,from,is->y,to,&is->rctx);
1639:     if (rmapping != cmapping) {
1640:       ISDestroy(&to);
1641:       ISDestroy(&from);
1642:       ISCreateStride(PETSC_COMM_SELF,nc,0,1,&to);
1643:       ISLocalToGlobalMappingApplyIS(cmapping,to,&from);
1644:       VecScatterCreate(cglobal,from,is->x,to,&is->cctx);
1645:     } else {
1646:       PetscObjectReference((PetscObject)is->rctx);
1647:       is->cctx = is->rctx;
1648:     }

1650:     /* interface counter vector (local) */
1651:     VecDuplicate(is->y,&is->counter);
1652:     VecSet(is->y,1.);
1653:     VecScatterBegin(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
1654:     VecScatterEnd(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
1655:     VecScatterBegin(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);
1656:     VecScatterEnd(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);

1658:     /* free workspace */
1659:     VecDestroy(&rglobal);
1660:     VecDestroy(&cglobal);
1661:     ISDestroy(&to);
1662:     ISDestroy(&from);
1663:   }
1664:   MatSetUp(A);
1665:   return(0);
1666: }

1668: static PetscErrorCode MatSetValues_IS(Mat mat, PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols, const PetscScalar *values, InsertMode addv)
1669: {
1670:   Mat_IS         *is = (Mat_IS*)mat->data;
1672: #if defined(PETSC_USE_DEBUG)
1673:   PetscInt       i,zm,zn;
1674: #endif
1675:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

1678: #if defined(PETSC_USE_DEBUG)
1679:   if (m > MATIS_MAX_ENTRIES_INSERTION || n > MATIS_MAX_ENTRIES_INSERTION) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of row/column indices must be <= %D: they are %D %D",MATIS_MAX_ENTRIES_INSERTION,m,n);
1680:   /* count negative indices */
1681:   for (i=0,zm=0;i<m;i++) if (rows[i] < 0) zm++;
1682:   for (i=0,zn=0;i<n;i++) if (cols[i] < 0) zn++;
1683: #endif
1684:   ISGlobalToLocalMappingApply(mat->rmap->mapping,IS_GTOLM_MASK,m,rows,&m,rows_l);
1685:   ISGlobalToLocalMappingApply(mat->cmap->mapping,IS_GTOLM_MASK,n,cols,&n,cols_l);
1686: #if defined(PETSC_USE_DEBUG)
1687:   /* count negative indices (should be the same as before) */
1688:   for (i=0;i<m;i++) if (rows_l[i] < 0) zm--;
1689:   for (i=0;i<n;i++) if (cols_l[i] < 0) zn--;
1690:   if (zm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the row indices can not be mapped! Maybe you should not use MATIS");
1691:   if (zn) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the column indices can not be mapped! Maybe you should not use MATIS");
1692: #endif
1693:   MatSetValues(is->A,m,rows_l,n,cols_l,values,addv);
1694:   return(0);
1695: }

1697: static PetscErrorCode MatSetValuesBlocked_IS(Mat mat, PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols, const PetscScalar *values, InsertMode addv)
1698: {
1699:   Mat_IS         *is = (Mat_IS*)mat->data;
1701: #if defined(PETSC_USE_DEBUG)
1702:   PetscInt       i,zm,zn;
1703: #endif
1704:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

1707: #if defined(PETSC_USE_DEBUG)
1708:   if (m > MATIS_MAX_ENTRIES_INSERTION || n > MATIS_MAX_ENTRIES_INSERTION) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_SUP,"Number of row/column block indices must be <= %D: they are %D %D",MATIS_MAX_ENTRIES_INSERTION,m,n);
1709:   /* count negative indices */
1710:   for (i=0,zm=0;i<m;i++) if (rows[i] < 0) zm++;
1711:   for (i=0,zn=0;i<n;i++) if (cols[i] < 0) zn++;
1712: #endif
1713:   ISGlobalToLocalMappingApplyBlock(mat->rmap->mapping,IS_GTOLM_MASK,m,rows,&m,rows_l);
1714:   ISGlobalToLocalMappingApplyBlock(mat->cmap->mapping,IS_GTOLM_MASK,n,cols,&n,cols_l);
1715: #if defined(PETSC_USE_DEBUG)
1716:   /* count negative indices (should be the same as before) */
1717:   for (i=0;i<m;i++) if (rows_l[i] < 0) zm--;
1718:   for (i=0;i<n;i++) if (cols_l[i] < 0) zn--;
1719:   if (zm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the row indices can not be mapped! Maybe you should not use MATIS");
1720:   if (zn) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the column indices can not be mapped! Maybe you should not use MATIS");
1721: #endif
1722:   MatSetValuesBlocked(is->A,m,rows_l,n,cols_l,values,addv);
1723:   return(0);
1724: }

1726: static PetscErrorCode MatSetValuesLocal_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
1727: {
1729:   Mat_IS         *is = (Mat_IS*)A->data;

1732:   MatSetValues(is->A,m,rows,n,cols,values,addv);
1733:   return(0);
1734: }

1736: static PetscErrorCode MatSetValuesBlockedLocal_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
1737: {
1739:   Mat_IS         *is = (Mat_IS*)A->data;

1742:   MatSetValuesBlocked(is->A,m,rows,n,cols,values,addv);
1743:   return(0);
1744: }

1746: static PetscErrorCode MatISZeroRowsColumnsLocal_Private(Mat A,PetscInt n,const PetscInt rows[],PetscScalar diag,PetscBool columns)
1747: {
1748:   Mat_IS         *is = (Mat_IS*)A->data;

1752:   if (!n) {
1753:     is->pure_neumann = PETSC_TRUE;
1754:   } else {
1755:     PetscInt i;
1756:     is->pure_neumann = PETSC_FALSE;

1758:     if (columns) {
1759:       MatZeroRowsColumns(is->A,n,rows,diag,0,0);
1760:     } else {
1761:       MatZeroRows(is->A,n,rows,diag,0,0);
1762:     }
1763:     if (diag != 0.) {
1764:       const PetscScalar *array;
1765:       VecGetArrayRead(is->counter,&array);
1766:       for (i=0; i<n; i++) {
1767:         MatSetValue(is->A,rows[i],rows[i],diag/(array[rows[i]]),INSERT_VALUES);
1768:       }
1769:       VecRestoreArrayRead(is->counter,&array);
1770:     }
1771:     MatAssemblyBegin(is->A,MAT_FINAL_ASSEMBLY);
1772:     MatAssemblyEnd(is->A,MAT_FINAL_ASSEMBLY);
1773:   }
1774:   return(0);
1775: }

1777: static PetscErrorCode MatZeroRowsColumns_Private_IS(Mat A,PetscInt n,const PetscInt rows[],PetscScalar diag,Vec x,Vec b,PetscBool columns)
1778: {
1779:   Mat_IS         *matis = (Mat_IS*)A->data;
1780:   PetscInt       nr,nl,len,i;
1781:   PetscInt       *lrows;

1785: #if defined(PETSC_USE_DEBUG)
1786:   if (columns || diag != 0. || (x && b)) {
1787:     PetscBool cong;
1788:     PetscLayoutCompare(A->rmap,A->cmap,&cong);
1789:     if (!cong && columns) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Columns can be zeroed if and only if A->rmap and A->cmap are congruent for MATIS");
1790:     if (!cong && diag != 0.) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"Nonzero diagonal value supported if and only if A->rmap and A->cmap are congruent for MATIS");
1791:     if (!cong && x && b) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"A->rmap and A->cmap need to be congruent");
1792:   }
1793: #endif
1794:   /* get locally owned rows */
1795:   PetscLayoutMapLocal_Private(A->rmap,n,rows,&len,&lrows,NULL);
1796:   /* fix right hand side if needed */
1797:   if (x && b) {
1798:     const PetscScalar *xx;
1799:     PetscScalar       *bb;

1801:     VecGetArrayRead(x, &xx);
1802:     VecGetArray(b, &bb);
1803:     for (i=0;i<len;++i) bb[lrows[i]] = diag*xx[lrows[i]];
1804:     VecRestoreArrayRead(x, &xx);
1805:     VecRestoreArray(b, &bb);
1806:   }
1807:   /* get rows associated to the local matrices */
1808:   MatISSetUpSF(A);
1809:   MatGetSize(matis->A,&nl,NULL);
1810:   PetscMemzero(matis->sf_leafdata,nl*sizeof(PetscInt));
1811:   PetscMemzero(matis->sf_rootdata,A->rmap->n*sizeof(PetscInt));
1812:   for (i=0;i<len;i++) matis->sf_rootdata[lrows[i]] = 1;
1813:   PetscFree(lrows);
1814:   PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1815:   PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1816:   PetscMalloc1(nl,&lrows);
1817:   for (i=0,nr=0;i<nl;i++) if (matis->sf_leafdata[i]) lrows[nr++] = i;
1818:   MatISZeroRowsColumnsLocal_Private(A,nr,lrows,diag,columns);
1819:   PetscFree(lrows);
1820:   return(0);
1821: }

1823: static PetscErrorCode MatZeroRows_IS(Mat A,PetscInt n,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1824: {

1828:   MatZeroRowsColumns_Private_IS(A,n,rows,diag,x,b,PETSC_FALSE);
1829:   return(0);
1830: }

1832: static PetscErrorCode MatZeroRowsColumns_IS(Mat A,PetscInt n,const PetscInt rows[],PetscScalar diag,Vec x,Vec b)
1833: {

1837:   MatZeroRowsColumns_Private_IS(A,n,rows,diag,x,b,PETSC_TRUE);
1838:   return(0);
1839: }

1841: static PetscErrorCode MatAssemblyBegin_IS(Mat A,MatAssemblyType type)
1842: {
1843:   Mat_IS         *is = (Mat_IS*)A->data;

1847:   MatAssemblyBegin(is->A,type);
1848:   return(0);
1849: }

1851: static PetscErrorCode MatAssemblyEnd_IS(Mat A,MatAssemblyType type)
1852: {
1853:   Mat_IS         *is = (Mat_IS*)A->data;

1857:   MatAssemblyEnd(is->A,type);
1858:   return(0);
1859: }

1861: static PetscErrorCode MatISGetLocalMat_IS(Mat mat,Mat *local)
1862: {
1863:   Mat_IS *is = (Mat_IS*)mat->data;

1866:   *local = is->A;
1867:   return(0);
1868: }

1870: /*@
1871:     MatISGetLocalMat - Gets the local matrix stored inside a MATIS matrix.

1873:   Input Parameter:
1874: .  mat - the matrix

1876:   Output Parameter:
1877: .  local - the local matrix

1879:   Level: advanced

1881:   Notes:
1882:     This can be called if you have precomputed the nonzero structure of the
1883:   matrix and want to provide it to the inner matrix object to improve the performance
1884:   of the MatSetValues() operation.

1886: .seealso: MATIS
1887: @*/
1888: PetscErrorCode MatISGetLocalMat(Mat mat,Mat *local)
1889: {

1895:   PetscUseMethod(mat,"MatISGetLocalMat_C",(Mat,Mat*),(mat,local));
1896:   return(0);
1897: }

1899: static PetscErrorCode MatISSetLocalMat_IS(Mat mat,Mat local)
1900: {
1901:   Mat_IS         *is = (Mat_IS*)mat->data;
1902:   PetscInt       nrows,ncols,orows,ocols;

1906:   if (is->A) {
1907:     MatGetSize(is->A,&orows,&ocols);
1908:     MatGetSize(local,&nrows,&ncols);
1909:     if (orows != nrows || ocols != ncols) SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Local MATIS matrix should be of size %Dx%D (you passed a %Dx%D matrix)",orows,ocols,nrows,ncols);
1910:   }
1911:   PetscObjectReference((PetscObject)local);
1912:   MatDestroy(&is->A);
1913:   is->A = local;
1914:   return(0);
1915: }

1917: /*@
1918:     MatISSetLocalMat - Replace the local matrix stored inside a MATIS object.

1920:   Input Parameter:
1921: .  mat - the matrix
1922: .  local - the local matrix

1924:   Output Parameter:

1926:   Level: advanced

1928:   Notes:
1929:     This can be called if you have precomputed the local matrix and
1930:   want to provide it to the matrix object MATIS.

1932: .seealso: MATIS
1933: @*/
1934: PetscErrorCode MatISSetLocalMat(Mat mat,Mat local)
1935: {

1941:   PetscUseMethod(mat,"MatISSetLocalMat_C",(Mat,Mat),(mat,local));
1942:   return(0);
1943: }

1945: static PetscErrorCode MatZeroEntries_IS(Mat A)
1946: {
1947:   Mat_IS         *a = (Mat_IS*)A->data;

1951:   MatZeroEntries(a->A);
1952:   return(0);
1953: }

1955: static PetscErrorCode MatScale_IS(Mat A,PetscScalar a)
1956: {
1957:   Mat_IS         *is = (Mat_IS*)A->data;

1961:   MatScale(is->A,a);
1962:   return(0);
1963: }

1965: static PetscErrorCode MatGetDiagonal_IS(Mat A, Vec v)
1966: {
1967:   Mat_IS         *is = (Mat_IS*)A->data;

1971:   /* get diagonal of the local matrix */
1972:   MatGetDiagonal(is->A,is->y);

1974:   /* scatter diagonal back into global vector */
1975:   VecSet(v,0);
1976:   VecScatterBegin(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
1977:   VecScatterEnd(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
1978:   return(0);
1979: }

1981: static PetscErrorCode MatSetOption_IS(Mat A,MatOption op,PetscBool flg)
1982: {
1983:   Mat_IS         *a = (Mat_IS*)A->data;

1987:   MatSetOption(a->A,op,flg);
1988:   return(0);
1989: }

1991: static PetscErrorCode MatAXPY_IS(Mat Y,PetscScalar a,Mat X,MatStructure str)
1992: {
1993:   Mat_IS         *y = (Mat_IS*)Y->data;
1994:   Mat_IS         *x;
1995: #if defined(PETSC_USE_DEBUG)
1996:   PetscBool      ismatis;
1997: #endif

2001: #if defined(PETSC_USE_DEBUG)
2002:   PetscObjectTypeCompare((PetscObject)X,MATIS,&ismatis);
2003:   if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)Y),PETSC_ERR_SUP,"Cannot call MatAXPY(Y,a,X,str) with X not of type MATIS");
2004: #endif
2005:   x = (Mat_IS*)X->data;
2006:   MatAXPY(y->A,a,x->A,str);
2007:   return(0);
2008: }

2010: static PetscErrorCode MatGetLocalSubMatrix_IS(Mat A,IS row,IS col,Mat *submat)
2011: {
2012:   Mat                    lA;
2013:   Mat_IS                 *matis;
2014:   ISLocalToGlobalMapping rl2g,cl2g;
2015:   IS                     is;
2016:   const PetscInt         *rg,*rl;
2017:   PetscInt               nrg;
2018:   PetscInt               N,M,nrl,i,*idxs;
2019:   PetscErrorCode         ierr;

2022:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&rg);
2023:   ISGetLocalSize(row,&nrl);
2024:   ISGetIndices(row,&rl);
2025:   ISLocalToGlobalMappingGetSize(A->rmap->mapping,&nrg);
2026: #if defined(PETSC_USE_DEBUG)
2027:   for (i=0;i<nrl;i++) if (rl[i]>=nrg) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local row index %D -> %D greater than maximum possible %D",i,rl[i],nrg);
2028: #endif
2029:   PetscMalloc1(nrg,&idxs);
2030:   /* map from [0,nrl) to row */
2031:   for (i=0;i<nrl;i++) idxs[i] = rl[i];
2032: #if defined(PETSC_USE_DEBUG)
2033:   for (i=nrl;i<nrg;i++) idxs[i] = nrg;
2034: #else
2035:   for (i=nrl;i<nrg;i++) idxs[i] = -1;
2036: #endif
2037:   ISRestoreIndices(row,&rl);
2038:   ISLocalToGlobalMappingRestoreIndices(A->rmap->mapping,&rg);
2039:   ISCreateGeneral(PetscObjectComm((PetscObject)A),nrg,idxs,PETSC_OWN_POINTER,&is);
2040:   ISLocalToGlobalMappingCreateIS(is,&rl2g);
2041:   ISDestroy(&is);
2042:   /* compute new l2g map for columns */
2043:   if (col != row || A->rmap->mapping != A->cmap->mapping) {
2044:     const PetscInt *cg,*cl;
2045:     PetscInt       ncg;
2046:     PetscInt       ncl;

2048:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&cg);
2049:     ISGetLocalSize(col,&ncl);
2050:     ISGetIndices(col,&cl);
2051:     ISLocalToGlobalMappingGetSize(A->cmap->mapping,&ncg);
2052: #if defined(PETSC_USE_DEBUG)
2053:     for (i=0;i<ncl;i++) if (cl[i]>=ncg) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local column index %D -> %D greater than maximum possible %D",i,cl[i],ncg);
2054: #endif
2055:     PetscMalloc1(ncg,&idxs);
2056:     /* map from [0,ncl) to col */
2057:     for (i=0;i<ncl;i++) idxs[i] = cl[i];
2058: #if defined(PETSC_USE_DEBUG)
2059:     for (i=ncl;i<ncg;i++) idxs[i] = ncg;
2060: #else
2061:     for (i=ncl;i<ncg;i++) idxs[i] = -1;
2062: #endif
2063:     ISRestoreIndices(col,&cl);
2064:     ISLocalToGlobalMappingRestoreIndices(A->cmap->mapping,&cg);
2065:     ISCreateGeneral(PetscObjectComm((PetscObject)A),ncg,idxs,PETSC_OWN_POINTER,&is);
2066:     ISLocalToGlobalMappingCreateIS(is,&cl2g);
2067:     ISDestroy(&is);
2068:   } else {
2069:     PetscObjectReference((PetscObject)rl2g);
2070:     cl2g = rl2g;
2071:   }
2072:   /* create the MATIS submatrix */
2073:   MatGetSize(A,&M,&N);
2074:   MatCreate(PetscObjectComm((PetscObject)A),submat);
2075:   MatSetSizes(*submat,PETSC_DECIDE,PETSC_DECIDE,M,N);
2076:   MatSetType(*submat,MATIS);
2077:   matis = (Mat_IS*)((*submat)->data);
2078:   matis->islocalref = PETSC_TRUE;
2079:   MatSetLocalToGlobalMapping(*submat,rl2g,cl2g);
2080:   MatISGetLocalMat(A,&lA);
2081:   MatISSetLocalMat(*submat,lA);
2082:   MatSetUp(*submat);
2083:   MatAssemblyBegin(*submat,MAT_FINAL_ASSEMBLY);
2084:   MatAssemblyEnd(*submat,MAT_FINAL_ASSEMBLY);
2085:   ISLocalToGlobalMappingDestroy(&rl2g);
2086:   ISLocalToGlobalMappingDestroy(&cl2g);
2087:   /* remove unsupported ops */
2088:   PetscMemzero((*submat)->ops,sizeof(struct _MatOps));
2089:   (*submat)->ops->destroy               = MatDestroy_IS;
2090:   (*submat)->ops->setvalueslocal        = MatSetValuesLocal_SubMat_IS;
2091:   (*submat)->ops->setvaluesblockedlocal = MatSetValuesBlockedLocal_SubMat_IS;
2092:   (*submat)->ops->assemblybegin         = MatAssemblyBegin_IS;
2093:   (*submat)->ops->assemblyend           = MatAssemblyEnd_IS;
2094:   return(0);
2095: }

2097: /*@
2098:     MatCreateIS - Creates a "process" unassembled matrix, assembled on each
2099:        process but not across processes.

2101:    Input Parameters:
2102: +     comm    - MPI communicator that will share the matrix
2103: .     bs      - block size of the matrix
2104: .     m,n,M,N - local and/or global sizes of the left and right vector used in matrix vector products
2105: .     rmap    - local to global map for rows
2106: -     cmap    - local to global map for cols

2108:    Output Parameter:
2109: .    A - the resulting matrix

2111:    Level: advanced

2113:    Notes: See MATIS for more details.
2114:           m and n are NOT related to the size of the map; they represent the size of the local parts of the vectors
2115:           used in MatMult operations. The sizes of rmap and cmap define the size of the local matrices.
2116:           If either rmap or cmap are NULL, then the matrix is assumed to be square.

2118: .seealso: MATIS, MatSetLocalToGlobalMapping()
2119: @*/
2120: PetscErrorCode  MatCreateIS(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,ISLocalToGlobalMapping rmap,ISLocalToGlobalMapping cmap,Mat *A)
2121: {

2125:   if (!rmap && !cmap) SETERRQ(comm,PETSC_ERR_USER,"You need to provide at least one of the mappings");
2126:   MatCreate(comm,A);
2127:   MatSetSizes(*A,m,n,M,N);
2128:   if (bs > 0) {
2129:     MatSetBlockSize(*A,bs);
2130:   }
2131:   MatSetType(*A,MATIS);
2132:   if (rmap && cmap) {
2133:     MatSetLocalToGlobalMapping(*A,rmap,cmap);
2134:   } else if (!rmap) {
2135:     MatSetLocalToGlobalMapping(*A,cmap,cmap);
2136:   } else {
2137:     MatSetLocalToGlobalMapping(*A,rmap,rmap);
2138:   }
2139:   return(0);
2140: }

2142: /*MC
2143:    MATIS - MATIS = "is" - A matrix type to be used for using the non-overlapping domain decomposition methods (e.g. PCBDDC or KSPFETIDP).
2144:    This stores the matrices in globally unassembled form. Each processor
2145:    assembles only its local Neumann problem and the parallel matrix vector
2146:    product is handled "implicitly".

2148:    Operations Provided:
2149: +  MatMult()
2150: .  MatMultAdd()
2151: .  MatMultTranspose()
2152: .  MatMultTransposeAdd()
2153: .  MatZeroEntries()
2154: .  MatSetOption()
2155: .  MatZeroRows()
2156: .  MatSetValues()
2157: .  MatSetValuesBlocked()
2158: .  MatSetValuesLocal()
2159: .  MatSetValuesBlockedLocal()
2160: .  MatScale()
2161: .  MatGetDiagonal()
2162: .  MatMissingDiagonal()
2163: .  MatDuplicate()
2164: .  MatCopy()
2165: .  MatAXPY()
2166: .  MatGetSubMatrix()
2167: .  MatGetLocalSubMatrix()
2168: .  MatTranspose()
2169: -  MatSetLocalToGlobalMapping()

2171:    Options Database Keys:
2172: . -mat_type is - sets the matrix type to "is" during a call to MatSetFromOptions()

2174:    Notes: Options prefix for the inner matrix are given by -is_mat_xxx

2176:           You must call MatSetLocalToGlobalMapping() before using this matrix type.

2178:           You can do matrix preallocation on the local matrix after you obtain it with
2179:           MatISGetLocalMat(); otherwise, you could use MatISSetPreallocation()

2181:   Level: advanced

2183: .seealso: Mat, MatISGetLocalMat(), MatSetLocalToGlobalMapping(), MatISSetPreallocation(), MatCreateIS(), PCBDDC, KSPFETIDP

2185: M*/

2187: PETSC_EXTERN PetscErrorCode MatCreate_IS(Mat A)
2188: {
2190:   Mat_IS         *b;

2193:   PetscNewLog(A,&b);
2194:   A->data = (void*)b;

2196:   /* matrix ops */
2197:   PetscMemzero(A->ops,sizeof(struct _MatOps));
2198:   A->ops->mult                    = MatMult_IS;
2199:   A->ops->multadd                 = MatMultAdd_IS;
2200:   A->ops->multtranspose           = MatMultTranspose_IS;
2201:   A->ops->multtransposeadd        = MatMultTransposeAdd_IS;
2202:   A->ops->destroy                 = MatDestroy_IS;
2203:   A->ops->setlocaltoglobalmapping = MatSetLocalToGlobalMapping_IS;
2204:   A->ops->setvalues               = MatSetValues_IS;
2205:   A->ops->setvaluesblocked        = MatSetValuesBlocked_IS;
2206:   A->ops->setvalueslocal          = MatSetValuesLocal_IS;
2207:   A->ops->setvaluesblockedlocal   = MatSetValuesBlockedLocal_IS;
2208:   A->ops->zerorows                = MatZeroRows_IS;
2209:   A->ops->zerorowscolumns         = MatZeroRowsColumns_IS;
2210:   A->ops->assemblybegin           = MatAssemblyBegin_IS;
2211:   A->ops->assemblyend             = MatAssemblyEnd_IS;
2212:   A->ops->view                    = MatView_IS;
2213:   A->ops->zeroentries             = MatZeroEntries_IS;
2214:   A->ops->scale                   = MatScale_IS;
2215:   A->ops->getdiagonal             = MatGetDiagonal_IS;
2216:   A->ops->setoption               = MatSetOption_IS;
2217:   A->ops->ishermitian             = MatIsHermitian_IS;
2218:   A->ops->issymmetric             = MatIsSymmetric_IS;
2219:   A->ops->isstructurallysymmetric = MatIsStructurallySymmetric_IS;
2220:   A->ops->duplicate               = MatDuplicate_IS;
2221:   A->ops->missingdiagonal         = MatMissingDiagonal_IS;
2222:   A->ops->copy                    = MatCopy_IS;
2223:   A->ops->getlocalsubmatrix       = MatGetLocalSubMatrix_IS;
2224:   A->ops->getsubmatrix            = MatGetSubMatrix_IS;
2225:   A->ops->axpy                    = MatAXPY_IS;
2226:   A->ops->diagonalset             = MatDiagonalSet_IS;
2227:   A->ops->shift                   = MatShift_IS;
2228:   A->ops->transpose               = MatTranspose_IS;
2229:   A->ops->getinfo                 = MatGetInfo_IS;
2230:   A->ops->diagonalscale           = MatDiagonalScale_IS;

2232:   /* special MATIS functions */
2233:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",MatISGetLocalMat_IS);
2234:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",MatISSetLocalMat_IS);
2235:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",MatISGetMPIXAIJ_IS);
2236:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",MatISSetPreallocation_IS);
2237:   PetscObjectComposeFunction((PetscObject)A,"MatISSetUpSF_C",MatISSetUpSF_IS);
2238:   PetscObjectChangeTypeName((PetscObject)A,MATIS);
2239:   return(0);
2240: }