Actual source code: matis.c

petsc-master 2017-06-26
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 MatCreateSubMatrix_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:   MatCreateSubMatrix(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);
1034: #if defined(PETSC_HAVE_HYPRE)
1035:   MatHYPRESetPreallocation(matis->A,0,matis->sf_leafdata,0,NULL);
1036: #endif

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

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

1044:   /* for other matrix types */
1045:   MatSetUp(matis->A);
1046:   return(0);
1047: }

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

1062:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&nsubdomains);
1063:   MatGetSize(A,&rows,&cols);
1064:   MatGetBlockSize(A,&bs);
1065:   MatGetSize(matis->A,&local_rows,&local_cols);
1066:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQDENSE,&isdense);
1067:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQSBAIJ,&issbaij);
1068:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&global_indices_r);
1069:   if (A->rmap->mapping != A->cmap->mapping) {
1070:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&global_indices_c);
1071:   } else {
1072:     global_indices_c = global_indices_r;
1073:   }

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

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

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

1188:   /* Resize preallocation if overestimated */
1189:   for (i=0;i<lrows;i++) {
1190:     dnz[i] = PetscMin(dnz[i],lcols);
1191:     onz[i] = PetscMin(onz[i],cols-lcols);
1192:   }

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

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

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

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

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

1296:   if (isseqsbaij) {
1297:     MatConvert(matis->A,MATSEQBAIJ,MAT_INITIAL_MATRIX,&local_mat);
1298:   } else {
1299:     PetscObjectReference((PetscObject)matis->A);
1300:     local_mat = matis->A;
1301:   }

1303:   /* Set values */
1304:   MatSetLocalToGlobalMapping(*M,mat->rmap->mapping,mat->cmap->mapping);
1305:   if (isseqdense) { /* special case for dense local matrices */
1306:     PetscInt i,*dummy;

1308:     PetscMalloc1(PetscMax(local_rows,local_cols),&dummy);
1309:     for (i=0;i<PetscMax(local_rows,local_cols);i++) dummy[i] = i;
1310:     MatSetOption(*M,MAT_ROW_ORIENTED,PETSC_FALSE);
1311:     MatDenseGetArray(local_mat,&array);
1312:     MatSetValuesLocal(*M,local_rows,dummy,local_cols,dummy,array,ADD_VALUES);
1313:     MatDenseRestoreArray(local_mat,&array);
1314:     PetscFree(dummy);
1315:   } else if (isseqaij) {
1316:     PetscInt  i,nvtxs,*xadj,*adjncy;
1317:     PetscBool done;

1319:     MatGetRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
1320:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatGetRowIJ");
1321:     MatSeqAIJGetArray(local_mat,&array);
1322:     for (i=0;i<nvtxs;i++) {
1323:       MatSetValuesLocal(*M,1,&i,xadj[i+1]-xadj[i],adjncy+xadj[i],array+xadj[i],ADD_VALUES);
1324:     }
1325:     MatRestoreRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
1326:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatRestoreRowIJ");
1327:     MatSeqAIJRestoreArray(local_mat,&array);
1328:   } else { /* very basic values insertion for all other matrix types */
1329:     PetscInt i;

1331:     for (i=0;i<local_rows;i++) {
1332:       PetscInt       j;
1333:       const PetscInt *local_indices_cols;

1335:       MatGetRow(local_mat,i,&j,&local_indices_cols,(const PetscScalar**)&array);
1336:       MatSetValuesLocal(*M,1,&i,j,local_indices_cols,array,ADD_VALUES);
1337:       MatRestoreRow(local_mat,i,&j,&local_indices_cols,(const PetscScalar**)&array);
1338:     }
1339:   }
1340:   MatAssemblyBegin(*M,MAT_FINAL_ASSEMBLY);
1341:   MatDestroy(&local_mat);
1342:   MatAssemblyEnd(*M,MAT_FINAL_ASSEMBLY);
1343:   if (isseqdense) {
1344:     MatSetOption(*M,MAT_ROW_ORIENTED,PETSC_TRUE);
1345:   }
1346:   return(0);
1347: }

1349: /*@
1350:     MatISGetMPIXAIJ - Converts MATIS matrix into a parallel AIJ format

1352:   Input Parameter:
1353: .  mat - the matrix (should be of type MATIS)
1354: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

1356:   Output Parameter:
1357: .  newmat - the matrix in AIJ format

1359:   Level: developer

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

1363: .seealso: MATIS
1364: @*/
1365: PetscErrorCode MatISGetMPIXAIJ(Mat mat, MatReuse reuse, Mat *newmat)
1366: {

1373:   if (reuse != MAT_INITIAL_MATRIX) {
1376:     if (mat == *newmat) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse the same matrix");
1377:   }
1378:   PetscUseMethod(mat,"MatISGetMPIXAIJ_C",(Mat,MatReuse,Mat*),(mat,reuse,newmat));
1379:   return(0);
1380: }

1382: PetscErrorCode MatDuplicate_IS(Mat mat,MatDuplicateOption op,Mat *newmat)
1383: {
1385:   Mat_IS         *matis = (Mat_IS*)(mat->data);
1386:   PetscInt       bs,m,n,M,N;
1387:   Mat            B,localmat;

1390:   MatGetBlockSize(mat,&bs);
1391:   MatGetSize(mat,&M,&N);
1392:   MatGetLocalSize(mat,&m,&n);
1393:   MatCreateIS(PetscObjectComm((PetscObject)mat),bs,m,n,M,N,mat->rmap->mapping,mat->cmap->mapping,&B);
1394:   MatDuplicate(matis->A,op,&localmat);
1395:   MatISSetLocalMat(B,localmat);
1396:   MatDestroy(&localmat);
1397:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1398:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1399:   *newmat = B;
1400:   return(0);
1401: }

1403: static PetscErrorCode MatIsHermitian_IS(Mat A,PetscReal tol,PetscBool  *flg)
1404: {
1406:   Mat_IS         *matis = (Mat_IS*)A->data;
1407:   PetscBool      local_sym;

1410:   MatIsHermitian(matis->A,tol,&local_sym);
1411:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1412:   return(0);
1413: }

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

1422:   MatIsSymmetric(matis->A,tol,&local_sym);
1423:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1424:   return(0);
1425: }

1427: static PetscErrorCode MatIsStructurallySymmetric_IS(Mat A,PetscBool  *flg)
1428: {
1430:   Mat_IS         *matis = (Mat_IS*)A->data;
1431:   PetscBool      local_sym;

1434:   if (A->rmap->mapping != A->cmap->mapping) {
1435:     *flg = PETSC_FALSE;
1436:     return(0);
1437:   }
1438:   MatIsStructurallySymmetric(matis->A,&local_sym);
1439:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
1440:   return(0);
1441: }

1443: static PetscErrorCode MatDestroy_IS(Mat A)
1444: {
1446:   Mat_IS         *b = (Mat_IS*)A->data;

1449:   MatDestroy(&b->A);
1450:   VecScatterDestroy(&b->cctx);
1451:   VecScatterDestroy(&b->rctx);
1452:   VecDestroy(&b->x);
1453:   VecDestroy(&b->y);
1454:   VecDestroy(&b->counter);
1455:   ISDestroy(&b->getsub_ris);
1456:   ISDestroy(&b->getsub_cis);
1457:   if (b->sf != b->csf) {
1458:     PetscSFDestroy(&b->csf);
1459:     PetscFree2(b->csf_rootdata,b->csf_leafdata);
1460:   }
1461:   PetscSFDestroy(&b->sf);
1462:   PetscFree2(b->sf_rootdata,b->sf_leafdata);
1463:   PetscFree(A->data);
1464:   PetscObjectChangeTypeName((PetscObject)A,0);
1465:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",NULL);
1466:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",NULL);
1467:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",NULL);
1468:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",NULL);
1469:   PetscObjectComposeFunction((PetscObject)A,"MatISSetUpSF_C",NULL);
1470:   return(0);
1471: }

1473: static PetscErrorCode MatMult_IS(Mat A,Vec x,Vec y)
1474: {
1476:   Mat_IS         *is  = (Mat_IS*)A->data;
1477:   PetscScalar    zero = 0.0;

1480:   /*  scatter the global vector x into the local work vector */
1481:   VecScatterBegin(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);
1482:   VecScatterEnd(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);

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

1487:   /* scatter product back into global memory */
1488:   VecSet(y,zero);
1489:   VecScatterBegin(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
1490:   VecScatterEnd(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
1491:   return(0);
1492: }

1494: static PetscErrorCode MatMultAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
1495: {
1496:   Vec            temp_vec;

1500:   if (v3 != v2) {
1501:     MatMult(A,v1,v3);
1502:     VecAXPY(v3,1.0,v2);
1503:   } else {
1504:     VecDuplicate(v2,&temp_vec);
1505:     MatMult(A,v1,temp_vec);
1506:     VecAXPY(temp_vec,1.0,v2);
1507:     VecCopy(temp_vec,v3);
1508:     VecDestroy(&temp_vec);
1509:   }
1510:   return(0);
1511: }

1513: static PetscErrorCode MatMultTranspose_IS(Mat A,Vec y,Vec x)
1514: {
1515:   Mat_IS         *is = (Mat_IS*)A->data;

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

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

1526:   /* scatter product back into global vector */
1527:   VecSet(x,0);
1528:   VecScatterBegin(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
1529:   VecScatterEnd(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
1530:   return(0);
1531: }

1533: static PetscErrorCode MatMultTransposeAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
1534: {
1535:   Vec            temp_vec;

1539:   if (v3 != v2) {
1540:     MatMultTranspose(A,v1,v3);
1541:     VecAXPY(v3,1.0,v2);
1542:   } else {
1543:     VecDuplicate(v2,&temp_vec);
1544:     MatMultTranspose(A,v1,temp_vec);
1545:     VecAXPY(temp_vec,1.0,v2);
1546:     VecCopy(temp_vec,v3);
1547:     VecDestroy(&temp_vec);
1548:   }
1549:   return(0);
1550: }

1552: static PetscErrorCode MatView_IS(Mat A,PetscViewer viewer)
1553: {
1554:   Mat_IS         *a = (Mat_IS*)A->data;
1556:   PetscViewer    sviewer;
1557:   PetscBool      isascii,view = PETSC_TRUE;

1560:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
1561:   if (isascii)  {
1562:     PetscViewerFormat format;

1564:     PetscViewerGetFormat(viewer,&format);
1565:     if (format == PETSC_VIEWER_ASCII_INFO) view = PETSC_FALSE;
1566:   }
1567:   if (!view) return(0);
1568:   PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1569:   MatView(a->A,sviewer);
1570:   PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
1571:   PetscViewerFlush(viewer);
1572:   return(0);
1573: }

1575: static PetscErrorCode MatSetLocalToGlobalMapping_IS(Mat A,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
1576: {
1578:   PetscInt       nr,rbs,nc,cbs;
1579:   Mat_IS         *is = (Mat_IS*)A->data;
1580:   IS             from,to;
1581:   Vec            cglobal,rglobal;

1586:   /* Destroy any previous data */
1587:   VecDestroy(&is->x);
1588:   VecDestroy(&is->y);
1589:   VecDestroy(&is->counter);
1590:   VecScatterDestroy(&is->rctx);
1591:   VecScatterDestroy(&is->cctx);
1592:   MatDestroy(&is->A);
1593:   if (is->csf != is->sf) {
1594:     PetscSFDestroy(&is->csf);
1595:     PetscFree2(is->csf_rootdata,is->csf_leafdata);
1596:   }
1597:   PetscSFDestroy(&is->sf);
1598:   PetscFree2(is->sf_rootdata,is->sf_leafdata);

1600:   /* Setup Layout and set local to global maps */
1601:   PetscLayoutSetUp(A->rmap);
1602:   PetscLayoutSetUp(A->cmap);
1603:   PetscLayoutSetISLocalToGlobalMapping(A->rmap,rmapping);
1604:   PetscLayoutSetISLocalToGlobalMapping(A->cmap,cmapping);

1606:   /* Create the local matrix A */
1607:   ISLocalToGlobalMappingGetSize(rmapping,&nr);
1608:   ISLocalToGlobalMappingGetBlockSize(rmapping,&rbs);
1609:   ISLocalToGlobalMappingGetSize(cmapping,&nc);
1610:   ISLocalToGlobalMappingGetBlockSize(cmapping,&cbs);
1611:   MatCreate(PETSC_COMM_SELF,&is->A);
1612:   MatSetType(is->A,MATAIJ);
1613:   MatSetSizes(is->A,nr,nc,nr,nc);
1614:   MatSetBlockSizes(is->A,rbs,cbs);
1615:   MatSetOptionsPrefix(is->A,((PetscObject)A)->prefix);
1616:   MatAppendOptionsPrefix(is->A,"is_");
1617:   MatSetFromOptions(is->A);
1618:   PetscLayoutSetUp(is->A->rmap);
1619:   PetscLayoutSetUp(is->A->cmap);

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

1625:     /* setup the global to local scatters */
1626:     MatCreateVecs(A,&cglobal,&rglobal);
1627:     ISCreateStride(PETSC_COMM_SELF,nr,0,1,&to);
1628:     ISLocalToGlobalMappingApplyIS(rmapping,to,&from);
1629:     VecScatterCreate(rglobal,from,is->y,to,&is->rctx);
1630:     if (rmapping != cmapping) {
1631:       ISDestroy(&to);
1632:       ISDestroy(&from);
1633:       ISCreateStride(PETSC_COMM_SELF,nc,0,1,&to);
1634:       ISLocalToGlobalMappingApplyIS(cmapping,to,&from);
1635:       VecScatterCreate(cglobal,from,is->x,to,&is->cctx);
1636:     } else {
1637:       PetscObjectReference((PetscObject)is->rctx);
1638:       is->cctx = is->rctx;
1639:     }

1641:     /* interface counter vector (local) */
1642:     VecDuplicate(is->y,&is->counter);
1643:     VecSet(is->y,1.);
1644:     VecScatterBegin(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
1645:     VecScatterEnd(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
1646:     VecScatterBegin(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);
1647:     VecScatterEnd(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);

1649:     /* free workspace */
1650:     VecDestroy(&rglobal);
1651:     VecDestroy(&cglobal);
1652:     ISDestroy(&to);
1653:     ISDestroy(&from);
1654:   }
1655:   MatSetUp(A);
1656:   return(0);
1657: }

1659: static PetscErrorCode MatSetValues_IS(Mat mat, PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols, const PetscScalar *values, InsertMode addv)
1660: {
1661:   Mat_IS         *is = (Mat_IS*)mat->data;
1663: #if defined(PETSC_USE_DEBUG)
1664:   PetscInt       i,zm,zn;
1665: #endif
1666:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

1669: #if defined(PETSC_USE_DEBUG)
1670:   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);
1671:   /* count negative indices */
1672:   for (i=0,zm=0;i<m;i++) if (rows[i] < 0) zm++;
1673:   for (i=0,zn=0;i<n;i++) if (cols[i] < 0) zn++;
1674: #endif
1675:   ISGlobalToLocalMappingApply(mat->rmap->mapping,IS_GTOLM_MASK,m,rows,&m,rows_l);
1676:   ISGlobalToLocalMappingApply(mat->cmap->mapping,IS_GTOLM_MASK,n,cols,&n,cols_l);
1677: #if defined(PETSC_USE_DEBUG)
1678:   /* count negative indices (should be the same as before) */
1679:   for (i=0;i<m;i++) if (rows_l[i] < 0) zm--;
1680:   for (i=0;i<n;i++) if (cols_l[i] < 0) zn--;
1681:   /* disable check when usesetlocal is true */
1682:   if (!is->usesetlocal && zm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the row indices can not be mapped! Maybe you should not use MATIS");
1683:   if (!is->usesetlocal && zn) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the column indices can not be mapped! Maybe you should not use MATIS");
1684: #endif
1685:   if (is->usesetlocal) {
1686:     MatSetValuesLocal(is->A,m,rows_l,n,cols_l,values,addv);
1687:   } else {
1688:     MatSetValues(is->A,m,rows_l,n,cols_l,values,addv);
1689:   }
1690:   return(0);
1691: }

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

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

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

1728:   if (is->usesetlocal) {
1729:     MatSetValuesLocal(is->A,m,rows,n,cols,values,addv);
1730:   } else {
1731:     MatSetValues(is->A,m,rows,n,cols,values,addv);
1732:   }
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:   /* fix for local empty rows/cols */
1859:   if (is->locempty && type == MAT_FINAL_ASSEMBLY) {
1860:     Mat                    newlA;
1861:     ISLocalToGlobalMapping l2g;
1862:     IS                     tis;
1863:     const PetscScalar      *v;
1864:     PetscInt               i,n,cf,*loce,*locf;
1865:     PetscBool              sym;

1867:     MatGetRowMaxAbs(is->A,is->y,NULL);
1868:     MatIsSymmetric(is->A,PETSC_SMALL,&sym);
1869:     if (!sym) SETERRQ(PetscObjectComm((PetscObject)is->A),PETSC_ERR_SUP,"Not yet implemented for unsymmetric case");
1870:     VecGetLocalSize(is->y,&n);
1871:     PetscMalloc1(n,&loce);
1872:     PetscMalloc1(n,&locf);
1873:     VecGetArrayRead(is->y,&v);
1874:     for (i=0,cf=0;i<n;i++) {
1875:       if (v[i] == 0.0) {
1876:         loce[i] = -1;
1877:       } else {
1878:         loce[i]    = cf;
1879:         locf[cf++] = i;
1880:       }
1881:     }
1882:     VecRestoreArrayRead(is->y,&v);
1883:     /* extract valid submatrix */
1884:     ISCreateGeneral(PetscObjectComm((PetscObject)is->A),cf,locf,PETSC_USE_POINTER,&tis);
1885:     MatCreateSubMatrix(is->A,tis,tis,MAT_INITIAL_MATRIX,&newlA);
1886:     ISDestroy(&tis);
1887:     /* attach local l2g map for successive calls of MatSetValues */
1888:     ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)is->A),1,n,loce,PETSC_OWN_POINTER,&l2g);
1889:     MatSetLocalToGlobalMapping(newlA,l2g,l2g);
1890:     ISLocalToGlobalMappingDestroy(&l2g);
1891:     /* flag MatSetValues */
1892:     is->usesetlocal = PETSC_TRUE;
1893:     /* attach new global l2g map */
1894:     ISLocalToGlobalMappingApply(A->rmap->mapping,cf,locf,locf);
1895:     ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)A),1,cf,locf,PETSC_OWN_POINTER,&l2g);
1896:     MatSetLocalToGlobalMapping(A,l2g,l2g);
1897:     MatISSetLocalMat(A,newlA);
1898:     MatDestroy(&newlA);
1899:     ISLocalToGlobalMappingDestroy(&l2g);
1900:   }
1901:   is->locempty = PETSC_FALSE;
1902:   return(0);
1903: }

1905: static PetscErrorCode MatISGetLocalMat_IS(Mat mat,Mat *local)
1906: {
1907:   Mat_IS *is = (Mat_IS*)mat->data;

1910:   *local = is->A;
1911:   return(0);
1912: }

1914: static PetscErrorCode MatISRestoreLocalMat_IS(Mat mat,Mat *local)
1915: {
1917:   *local = NULL;
1918:   return(0);
1919: }

1921: /*@
1922:     MatISGetLocalMat - Gets the local matrix stored inside a MATIS matrix.

1924:   Input Parameter:
1925: .  mat - the matrix

1927:   Output Parameter:
1928: .  local - the local matrix

1930:   Level: advanced

1932:   Notes:
1933:     This can be called if you have precomputed the nonzero structure of the
1934:   matrix and want to provide it to the inner matrix object to improve the performance
1935:   of the MatSetValues() operation.

1937:   Call MatISRestoreLocalMat() when finished with the local matrix.

1939: .seealso: MATIS
1940: @*/
1941: PetscErrorCode MatISGetLocalMat(Mat mat,Mat *local)
1942: {

1948:   PetscUseMethod(mat,"MatISGetLocalMat_C",(Mat,Mat*),(mat,local));
1949:   return(0);
1950: }

1952: /*@
1953:     MatISRestoreLocalMat - Restores the local matrix obtained with MatISGetLocalMat()

1955:   Input Parameter:
1956: .  mat - the matrix

1958:   Output Parameter:
1959: .  local - the local matrix

1961:   Level: advanced

1963: .seealso: MATIS
1964: @*/
1965: PetscErrorCode MatISRestoreLocalMat(Mat mat,Mat *local)
1966: {

1972:   PetscUseMethod(mat,"MatISRestoreLocalMat_C",(Mat,Mat*),(mat,local));
1973:   return(0);
1974: }

1976: static PetscErrorCode MatISSetLocalMat_IS(Mat mat,Mat local)
1977: {
1978:   Mat_IS         *is = (Mat_IS*)mat->data;
1979:   PetscInt       nrows,ncols,orows,ocols;

1983:   if (is->A) {
1984:     MatGetSize(is->A,&orows,&ocols);
1985:     MatGetSize(local,&nrows,&ncols);
1986:     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);
1987:   }
1988:   PetscObjectReference((PetscObject)local);
1989:   MatDestroy(&is->A);
1990:   is->A = local;
1991:   return(0);
1992: }

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

1997:   Input Parameter:
1998: .  mat - the matrix
1999: .  local - the local matrix

2001:   Output Parameter:

2003:   Level: advanced

2005:   Notes:
2006:     This can be called if you have precomputed the local matrix and
2007:   want to provide it to the matrix object MATIS.

2009: .seealso: MATIS
2010: @*/
2011: PetscErrorCode MatISSetLocalMat(Mat mat,Mat local)
2012: {

2018:   PetscUseMethod(mat,"MatISSetLocalMat_C",(Mat,Mat),(mat,local));
2019:   return(0);
2020: }

2022: static PetscErrorCode MatZeroEntries_IS(Mat A)
2023: {
2024:   Mat_IS         *a = (Mat_IS*)A->data;

2028:   MatZeroEntries(a->A);
2029:   return(0);
2030: }

2032: static PetscErrorCode MatScale_IS(Mat A,PetscScalar a)
2033: {
2034:   Mat_IS         *is = (Mat_IS*)A->data;

2038:   MatScale(is->A,a);
2039:   return(0);
2040: }

2042: static PetscErrorCode MatGetDiagonal_IS(Mat A, Vec v)
2043: {
2044:   Mat_IS         *is = (Mat_IS*)A->data;

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

2051:   /* scatter diagonal back into global vector */
2052:   VecSet(v,0);
2053:   VecScatterBegin(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
2054:   VecScatterEnd(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
2055:   return(0);
2056: }

2058: static PetscErrorCode MatSetOption_IS(Mat A,MatOption op,PetscBool flg)
2059: {
2060:   Mat_IS         *a = (Mat_IS*)A->data;

2064:   MatSetOption(a->A,op,flg);
2065:   return(0);
2066: }

2068: static PetscErrorCode MatAXPY_IS(Mat Y,PetscScalar a,Mat X,MatStructure str)
2069: {
2070:   Mat_IS         *y = (Mat_IS*)Y->data;
2071:   Mat_IS         *x;
2072: #if defined(PETSC_USE_DEBUG)
2073:   PetscBool      ismatis;
2074: #endif

2078: #if defined(PETSC_USE_DEBUG)
2079:   PetscObjectTypeCompare((PetscObject)X,MATIS,&ismatis);
2080:   if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)Y),PETSC_ERR_SUP,"Cannot call MatAXPY(Y,a,X,str) with X not of type MATIS");
2081: #endif
2082:   x = (Mat_IS*)X->data;
2083:   MatAXPY(y->A,a,x->A,str);
2084:   return(0);
2085: }

2087: static PetscErrorCode MatGetLocalSubMatrix_IS(Mat A,IS row,IS col,Mat *submat)
2088: {
2089:   Mat                    lA;
2090:   Mat_IS                 *matis;
2091:   ISLocalToGlobalMapping rl2g,cl2g;
2092:   IS                     is;
2093:   const PetscInt         *rg,*rl;
2094:   PetscInt               nrg;
2095:   PetscInt               N,M,nrl,i,*idxs;
2096:   PetscErrorCode         ierr;

2099:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&rg);
2100:   ISGetLocalSize(row,&nrl);
2101:   ISGetIndices(row,&rl);
2102:   ISLocalToGlobalMappingGetSize(A->rmap->mapping,&nrg);
2103: #if defined(PETSC_USE_DEBUG)
2104:   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);
2105: #endif
2106:   PetscMalloc1(nrg,&idxs);
2107:   /* map from [0,nrl) to row */
2108:   for (i=0;i<nrl;i++) idxs[i] = rl[i];
2109: #if defined(PETSC_USE_DEBUG)
2110:   for (i=nrl;i<nrg;i++) idxs[i] = nrg;
2111: #else
2112:   for (i=nrl;i<nrg;i++) idxs[i] = -1;
2113: #endif
2114:   ISRestoreIndices(row,&rl);
2115:   ISLocalToGlobalMappingRestoreIndices(A->rmap->mapping,&rg);
2116:   ISCreateGeneral(PetscObjectComm((PetscObject)A),nrg,idxs,PETSC_OWN_POINTER,&is);
2117:   ISLocalToGlobalMappingCreateIS(is,&rl2g);
2118:   ISDestroy(&is);
2119:   /* compute new l2g map for columns */
2120:   if (col != row || A->rmap->mapping != A->cmap->mapping) {
2121:     const PetscInt *cg,*cl;
2122:     PetscInt       ncg;
2123:     PetscInt       ncl;

2125:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&cg);
2126:     ISGetLocalSize(col,&ncl);
2127:     ISGetIndices(col,&cl);
2128:     ISLocalToGlobalMappingGetSize(A->cmap->mapping,&ncg);
2129: #if defined(PETSC_USE_DEBUG)
2130:     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);
2131: #endif
2132:     PetscMalloc1(ncg,&idxs);
2133:     /* map from [0,ncl) to col */
2134:     for (i=0;i<ncl;i++) idxs[i] = cl[i];
2135: #if defined(PETSC_USE_DEBUG)
2136:     for (i=ncl;i<ncg;i++) idxs[i] = ncg;
2137: #else
2138:     for (i=ncl;i<ncg;i++) idxs[i] = -1;
2139: #endif
2140:     ISRestoreIndices(col,&cl);
2141:     ISLocalToGlobalMappingRestoreIndices(A->cmap->mapping,&cg);
2142:     ISCreateGeneral(PetscObjectComm((PetscObject)A),ncg,idxs,PETSC_OWN_POINTER,&is);
2143:     ISLocalToGlobalMappingCreateIS(is,&cl2g);
2144:     ISDestroy(&is);
2145:   } else {
2146:     PetscObjectReference((PetscObject)rl2g);
2147:     cl2g = rl2g;
2148:   }
2149:   /* create the MATIS submatrix */
2150:   MatGetSize(A,&M,&N);
2151:   MatCreate(PetscObjectComm((PetscObject)A),submat);
2152:   MatSetSizes(*submat,PETSC_DECIDE,PETSC_DECIDE,M,N);
2153:   MatSetType(*submat,MATIS);
2154:   matis = (Mat_IS*)((*submat)->data);
2155:   matis->islocalref = PETSC_TRUE;
2156:   MatSetLocalToGlobalMapping(*submat,rl2g,cl2g);
2157:   MatISGetLocalMat(A,&lA);
2158:   MatISSetLocalMat(*submat,lA);
2159:   MatSetUp(*submat);
2160:   MatAssemblyBegin(*submat,MAT_FINAL_ASSEMBLY);
2161:   MatAssemblyEnd(*submat,MAT_FINAL_ASSEMBLY);
2162:   ISLocalToGlobalMappingDestroy(&rl2g);
2163:   ISLocalToGlobalMappingDestroy(&cl2g);
2164:   /* remove unsupported ops */
2165:   PetscMemzero((*submat)->ops,sizeof(struct _MatOps));
2166:   (*submat)->ops->destroy               = MatDestroy_IS;
2167:   (*submat)->ops->setvalueslocal        = MatSetValuesLocal_SubMat_IS;
2168:   (*submat)->ops->setvaluesblockedlocal = MatSetValuesBlockedLocal_SubMat_IS;
2169:   (*submat)->ops->assemblybegin         = MatAssemblyBegin_IS;
2170:   (*submat)->ops->assemblyend           = MatAssemblyEnd_IS;
2171:   return(0);
2172: }

2174: static PetscErrorCode MatSetFromOptions_IS(PetscOptionItems *PetscOptionsObject, Mat A)
2175: {
2176:   Mat_IS         *a = (Mat_IS*)A->data;

2180:   PetscOptionsHead(PetscOptionsObject,"MATIS options");
2181:   PetscObjectOptionsBegin((PetscObject)A);
2182:   PetscOptionsBool("-matis_fixempty","Fix local matrices in case of empty local rows/columns",NULL,a->locempty,&a->locempty,NULL);
2183:   PetscOptionsEnd();
2184:   return(0);
2185: }

2187: /*@
2188:     MatCreateIS - Creates a "process" unassembled matrix, assembled on each
2189:        process but not across processes.

2191:    Input Parameters:
2192: +     comm    - MPI communicator that will share the matrix
2193: .     bs      - block size of the matrix
2194: .     m,n,M,N - local and/or global sizes of the left and right vector used in matrix vector products
2195: .     rmap    - local to global map for rows
2196: -     cmap    - local to global map for cols

2198:    Output Parameter:
2199: .    A - the resulting matrix

2201:    Level: advanced

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

2208: .seealso: MATIS, MatSetLocalToGlobalMapping()
2209: @*/
2210: PetscErrorCode  MatCreateIS(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,ISLocalToGlobalMapping rmap,ISLocalToGlobalMapping cmap,Mat *A)
2211: {

2215:   if (!rmap && !cmap) SETERRQ(comm,PETSC_ERR_USER,"You need to provide at least one of the mappings");
2216:   MatCreate(comm,A);
2217:   MatSetSizes(*A,m,n,M,N);
2218:   if (bs > 0) {
2219:     MatSetBlockSize(*A,bs);
2220:   }
2221:   MatSetType(*A,MATIS);
2222:   if (rmap && cmap) {
2223:     MatSetLocalToGlobalMapping(*A,rmap,cmap);
2224:   } else if (!rmap) {
2225:     MatSetLocalToGlobalMapping(*A,cmap,cmap);
2226:   } else {
2227:     MatSetLocalToGlobalMapping(*A,rmap,rmap);
2228:   }
2229:   return(0);
2230: }

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

2238:    Operations Provided:
2239: +  MatMult()
2240: .  MatMultAdd()
2241: .  MatMultTranspose()
2242: .  MatMultTransposeAdd()
2243: .  MatZeroEntries()
2244: .  MatSetOption()
2245: .  MatZeroRows()
2246: .  MatSetValues()
2247: .  MatSetValuesBlocked()
2248: .  MatSetValuesLocal()
2249: .  MatSetValuesBlockedLocal()
2250: .  MatScale()
2251: .  MatGetDiagonal()
2252: .  MatMissingDiagonal()
2253: .  MatDuplicate()
2254: .  MatCopy()
2255: .  MatAXPY()
2256: .  MatCreateSubMatrix()
2257: .  MatGetLocalSubMatrix()
2258: .  MatTranspose()
2259: -  MatSetLocalToGlobalMapping()

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

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

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

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

2271:   Level: advanced

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

2275: M*/

2277: PETSC_EXTERN PetscErrorCode MatCreate_IS(Mat A)
2278: {
2280:   Mat_IS         *b;

2283:   PetscNewLog(A,&b);
2284:   A->data = (void*)b;

2286:   /* matrix ops */
2287:   PetscMemzero(A->ops,sizeof(struct _MatOps));
2288:   A->ops->mult                    = MatMult_IS;
2289:   A->ops->multadd                 = MatMultAdd_IS;
2290:   A->ops->multtranspose           = MatMultTranspose_IS;
2291:   A->ops->multtransposeadd        = MatMultTransposeAdd_IS;
2292:   A->ops->destroy                 = MatDestroy_IS;
2293:   A->ops->setlocaltoglobalmapping = MatSetLocalToGlobalMapping_IS;
2294:   A->ops->setvalues               = MatSetValues_IS;
2295:   A->ops->setvaluesblocked        = MatSetValuesBlocked_IS;
2296:   A->ops->setvalueslocal          = MatSetValuesLocal_IS;
2297:   A->ops->setvaluesblockedlocal   = MatSetValuesBlockedLocal_IS;
2298:   A->ops->zerorows                = MatZeroRows_IS;
2299:   A->ops->zerorowscolumns         = MatZeroRowsColumns_IS;
2300:   A->ops->assemblybegin           = MatAssemblyBegin_IS;
2301:   A->ops->assemblyend             = MatAssemblyEnd_IS;
2302:   A->ops->view                    = MatView_IS;
2303:   A->ops->zeroentries             = MatZeroEntries_IS;
2304:   A->ops->scale                   = MatScale_IS;
2305:   A->ops->getdiagonal             = MatGetDiagonal_IS;
2306:   A->ops->setoption               = MatSetOption_IS;
2307:   A->ops->ishermitian             = MatIsHermitian_IS;
2308:   A->ops->issymmetric             = MatIsSymmetric_IS;
2309:   A->ops->isstructurallysymmetric = MatIsStructurallySymmetric_IS;
2310:   A->ops->duplicate               = MatDuplicate_IS;
2311:   A->ops->missingdiagonal         = MatMissingDiagonal_IS;
2312:   A->ops->copy                    = MatCopy_IS;
2313:   A->ops->getlocalsubmatrix       = MatGetLocalSubMatrix_IS;
2314:   A->ops->createsubmatrix         = MatCreateSubMatrix_IS;
2315:   A->ops->axpy                    = MatAXPY_IS;
2316:   A->ops->diagonalset             = MatDiagonalSet_IS;
2317:   A->ops->shift                   = MatShift_IS;
2318:   A->ops->transpose               = MatTranspose_IS;
2319:   A->ops->getinfo                 = MatGetInfo_IS;
2320:   A->ops->diagonalscale           = MatDiagonalScale_IS;
2321:   A->ops->setfromoptions          = MatSetFromOptions_IS;

2323:   /* special MATIS functions */
2324:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",MatISGetLocalMat_IS);
2325:   PetscObjectComposeFunction((PetscObject)A,"MatISRestoreLocalMat_C",MatISRestoreLocalMat_IS);
2326:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",MatISSetLocalMat_IS);
2327:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",MatISGetMPIXAIJ_IS);
2328:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",MatISSetPreallocation_IS);
2329:   PetscObjectComposeFunction((PetscObject)A,"MatISSetUpSF_C",MatISSetUpSF_IS);
2330:   PetscObjectChangeTypeName((PetscObject)A,MATIS);
2331:   return(0);
2332: }