Actual source code: matis.c

petsc-master 2019-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 <petsc/private/sfimpl.h>
 12:  #include <petsc/private/vecimpl.h>

 14: #define MATIS_MAX_ENTRIES_INSERTION 2048
 15: static PetscErrorCode MatSetValuesLocal_IS(Mat,PetscInt,const PetscInt*,PetscInt,const PetscInt*,const PetscScalar*,InsertMode);
 16: static PetscErrorCode MatSetValuesBlockedLocal_IS(Mat,PetscInt,const PetscInt*,PetscInt,const PetscInt*,const PetscScalar*,InsertMode);
 17: static PetscErrorCode MatISSetUpScatters_Private(Mat);

 19: static PetscErrorCode MatISContainerDestroyPtAP_Private(void *ptr)
 20: {
 21:   MatISPtAP      ptap = (MatISPtAP)ptr;

 25:   MatDestroySubMatrices(ptap->ris1 ? 2 : 1,&ptap->lP);
 26:   ISDestroy(&ptap->cis0);
 27:   ISDestroy(&ptap->cis1);
 28:   ISDestroy(&ptap->ris0);
 29:   ISDestroy(&ptap->ris1);
 30:   PetscFree(ptap);
 31:   return(0);
 32: }

 34: static PetscErrorCode MatPtAPNumeric_IS_XAIJ(Mat A, Mat P, Mat C)
 35: {
 36:   MatISPtAP      ptap;
 37:   Mat_IS         *matis = (Mat_IS*)A->data;
 38:   Mat            lA,lC;
 39:   MatReuse       reuse;
 40:   IS             ris[2],cis[2];
 41:   PetscContainer c;
 42:   PetscInt       n;

 46:   PetscObjectQuery((PetscObject)C,"_MatIS_PtAP",(PetscObject*)&c);
 47:   if (!c) SETERRQ(PetscObjectComm((PetscObject)C),PETSC_ERR_PLIB,"Missing PtAP information");
 48:   PetscContainerGetPointer(c,(void**)&ptap);
 49:   ris[0] = ptap->ris0;
 50:   ris[1] = ptap->ris1;
 51:   cis[0] = ptap->cis0;
 52:   cis[1] = ptap->cis1;
 53:   n      = ptap->ris1 ? 2 : 1;
 54:   reuse  = ptap->lP ? MAT_REUSE_MATRIX : MAT_INITIAL_MATRIX;
 55:   MatCreateSubMatrices(P,n,ris,cis,reuse,&ptap->lP);

 57:   MatISGetLocalMat(A,&lA);
 58:   MatISGetLocalMat(C,&lC);
 59:   if (ptap->ris1) { /* unsymmetric A mapping */
 60:     Mat lPt;

 62:     MatTranspose(ptap->lP[1],MAT_INITIAL_MATRIX,&lPt);
 63:     MatMatMatMult(lPt,lA,ptap->lP[0],reuse,ptap->fill,&lC);
 64:     if (matis->storel2l) {
 65:       PetscObjectCompose((PetscObject)(A),"_MatIS_PtAP_l2l",(PetscObject)lPt);
 66:     }
 67:     MatDestroy(&lPt);
 68:   } else {
 69:     MatPtAP(lA,ptap->lP[0],reuse,ptap->fill,&lC);
 70:     if (matis->storel2l) {
 71:      PetscObjectCompose((PetscObject)(C),"_MatIS_PtAP_l2l",(PetscObject)ptap->lP[0]);
 72:     }
 73:   }
 74:   if (reuse == MAT_INITIAL_MATRIX) {
 75:     MatISSetLocalMat(C,lC);
 76:     MatDestroy(&lC);
 77:   }
 78:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
 79:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
 80:   return(0);
 81: }

 83: static PetscErrorCode MatGetNonzeroColumnsLocal_Private(Mat PT,IS *cis)
 84: {
 85:   Mat            Po,Pd;
 86:   IS             zd,zo;
 87:   const PetscInt *garray;
 88:   PetscInt       *aux,i,bs;
 89:   PetscInt       dc,stc,oc,ctd,cto;
 90:   PetscBool      ismpiaij,ismpibaij,isseqaij,isseqbaij;
 91:   MPI_Comm       comm;

 97:   PetscObjectGetComm((PetscObject)PT,&comm);
 98:   bs   = 1;
 99:   PetscObjectTypeCompare((PetscObject)PT,MATMPIAIJ,&ismpiaij);
100:   PetscObjectTypeCompare((PetscObject)PT,MATMPIBAIJ,&ismpibaij);
101:   PetscObjectBaseTypeCompare((PetscObject)PT,MATSEQAIJ,&isseqaij);
102:   PetscObjectTypeCompare((PetscObject)PT,MATSEQBAIJ,&isseqbaij);
103:   if (isseqaij || isseqbaij) {
104:     Pd = PT;
105:     Po = NULL;
106:     garray = NULL;
107:   } else if (ismpiaij) {
108:     MatMPIAIJGetSeqAIJ(PT,&Pd,&Po,&garray);
109:   } else if (ismpibaij) {
110:     MatMPIBAIJGetSeqBAIJ(PT,&Pd,&Po,&garray);
111:     MatGetBlockSize(PT,&bs);
112:   } else SETERRQ1(comm,PETSC_ERR_SUP,"Not for matrix type %s",((PetscObject)(PT))->type_name);

114:   /* identify any null columns in Pd or Po */
115:   /* We use a tolerance comparison since it may happen that, with geometric multigrid,
116:      some of the columns are not really zero, but very close to */
117:   zo = zd = NULL;
118:   if (Po) {
119:     MatFindNonzeroRowsOrCols_Basic(Po,PETSC_TRUE,PETSC_SMALL,&zo);
120:   }
121:   MatFindNonzeroRowsOrCols_Basic(Pd,PETSC_TRUE,PETSC_SMALL,&zd);

123:   MatGetLocalSize(PT,NULL,&dc);
124:   MatGetOwnershipRangeColumn(PT,&stc,NULL);
125:   if (Po) { MatGetLocalSize(Po,NULL,&oc); }
126:   else oc = 0;
127:   PetscMalloc1((dc+oc)/bs,&aux);
128:   if (zd) {
129:     const PetscInt *idxs;
130:     PetscInt       nz;

132:     /* this will throw an error if bs is not valid */
133:     ISSetBlockSize(zd,bs);
134:     ISGetLocalSize(zd,&nz);
135:     ISGetIndices(zd,&idxs);
136:     ctd  = nz/bs;
137:     for (i=0; i<ctd; i++) aux[i] = (idxs[bs*i]+stc)/bs;
138:     ISRestoreIndices(zd,&idxs);
139:   } else {
140:     ctd = dc/bs;
141:     for (i=0; i<ctd; i++) aux[i] = i+stc/bs;
142:   }
143:   if (zo) {
144:     const PetscInt *idxs;
145:     PetscInt       nz;

147:     /* this will throw an error if bs is not valid */
148:     ISSetBlockSize(zo,bs);
149:     ISGetLocalSize(zo,&nz);
150:     ISGetIndices(zo,&idxs);
151:     cto  = nz/bs;
152:     for (i=0; i<cto; i++) aux[i+ctd] = garray[idxs[bs*i]/bs];
153:     ISRestoreIndices(zo,&idxs);
154:   } else {
155:     cto = oc/bs;
156:     for (i=0; i<cto; i++) aux[i+ctd] = garray[i];
157:   }
158:   ISCreateBlock(comm,bs,ctd+cto,aux,PETSC_OWN_POINTER,cis);
159:   ISDestroy(&zd);
160:   ISDestroy(&zo);
161:   return(0);
162: }

164: static PetscErrorCode MatPtAPSymbolic_IS_XAIJ(Mat A,Mat P,PetscReal fill,Mat *C)
165: {
166:   Mat                    PT,lA;
167:   MatISPtAP              ptap;
168:   ISLocalToGlobalMapping Crl2g,Ccl2g,rl2g,cl2g;
169:   PetscContainer         c;
170:   MatType                lmtype;
171:   const PetscInt         *garray;
172:   PetscInt               ibs,N,dc;
173:   MPI_Comm               comm;
174:   PetscErrorCode         ierr;

177:   PetscObjectGetComm((PetscObject)A,&comm);
178:   MatCreate(comm,C);
179:   MatSetType(*C,MATIS);
180:   MatISGetLocalMat(A,&lA);
181:   MatGetType(lA,&lmtype);
182:   MatISSetLocalMatType(*C,lmtype);
183:   MatGetSize(P,NULL,&N);
184:   MatGetLocalSize(P,NULL,&dc);
185:   MatSetSizes(*C,dc,dc,N,N);
186: /* Not sure about this
187:   MatGetBlockSizes(P,NULL,&ibs);
188:   MatSetBlockSize(*C,ibs);
189: */

191:   PetscNew(&ptap);
192:   PetscContainerCreate(PETSC_COMM_SELF,&c);
193:   PetscContainerSetPointer(c,ptap);
194:   PetscContainerSetUserDestroy(c,MatISContainerDestroyPtAP_Private);
195:   PetscObjectCompose((PetscObject)(*C),"_MatIS_PtAP",(PetscObject)c);
196:   PetscContainerDestroy(&c);
197:   ptap->fill = fill;

199:   MatGetLocalToGlobalMapping(A,&rl2g,&cl2g);

201:   ISLocalToGlobalMappingGetBlockSize(cl2g,&ibs);
202:   ISLocalToGlobalMappingGetSize(cl2g,&N);
203:   ISLocalToGlobalMappingGetBlockIndices(cl2g,&garray);
204:   ISCreateBlock(comm,ibs,N/ibs,garray,PETSC_COPY_VALUES,&ptap->ris0);
205:   ISLocalToGlobalMappingRestoreBlockIndices(cl2g,&garray);

207:   MatCreateSubMatrix(P,ptap->ris0,NULL,MAT_INITIAL_MATRIX,&PT);
208:   MatGetNonzeroColumnsLocal_Private(PT,&ptap->cis0);
209:   ISLocalToGlobalMappingCreateIS(ptap->cis0,&Ccl2g);
210:   MatDestroy(&PT);

212:   Crl2g = NULL;
213:   if (rl2g != cl2g) { /* unsymmetric A mapping */
214:     PetscBool same,lsame = PETSC_FALSE;
215:     PetscInt  N1,ibs1;

217:     ISLocalToGlobalMappingGetSize(rl2g,&N1);
218:     ISLocalToGlobalMappingGetBlockSize(rl2g,&ibs1);
219:     ISLocalToGlobalMappingGetBlockIndices(rl2g,&garray);
220:     ISCreateBlock(comm,ibs,N/ibs,garray,PETSC_COPY_VALUES,&ptap->ris1);
221:     ISLocalToGlobalMappingRestoreBlockIndices(rl2g,&garray);
222:     if (ibs1 == ibs && N1 == N) { /* check if the l2gmaps are the same */
223:       const PetscInt *i1,*i2;

225:       ISBlockGetIndices(ptap->ris0,&i1);
226:       ISBlockGetIndices(ptap->ris1,&i2);
227:       PetscArraycmp(i1,i2,N,&lsame);
228:     }
229:     MPIU_Allreduce(&lsame,&same,1,MPIU_BOOL,MPI_LAND,comm);
230:     if (same) {
231:       ISDestroy(&ptap->ris1);
232:     } else {
233:       MatCreateSubMatrix(P,ptap->ris1,NULL,MAT_INITIAL_MATRIX,&PT);
234:       MatGetNonzeroColumnsLocal_Private(PT,&ptap->cis1);
235:       ISLocalToGlobalMappingCreateIS(ptap->cis1,&Crl2g);
236:       MatDestroy(&PT);
237:     }
238:   }
239: /* Not sure about this
240:   if (!Crl2g) {
241:     MatGetBlockSize(*C,&ibs);
242:     ISLocalToGlobalMappingSetBlockSize(Ccl2g,ibs);
243:   }
244: */
245:   MatSetLocalToGlobalMapping(*C,Crl2g ? Crl2g : Ccl2g,Ccl2g);
246:   ISLocalToGlobalMappingDestroy(&Crl2g);
247:   ISLocalToGlobalMappingDestroy(&Ccl2g);

249:   (*C)->ops->ptapnumeric = MatPtAPNumeric_IS_XAIJ;
250:   return(0);
251: }

253: PETSC_INTERN PetscErrorCode MatPtAP_IS_XAIJ(Mat A,Mat P,MatReuse scall,PetscReal fill,Mat *C)
254: {

258:   if (scall == MAT_INITIAL_MATRIX) {
259:     PetscLogEventBegin(MAT_PtAPSymbolic,A,P,0,0);
260:     MatPtAPSymbolic_IS_XAIJ(A,P,fill,C);
261:     PetscLogEventEnd(MAT_PtAPSymbolic,A,P,0,0);
262:   }
263:   PetscLogEventBegin(MAT_PtAPNumeric,A,P,0,0);
264:   ((*C)->ops->ptapnumeric)(A,P,*C);
265:   PetscLogEventEnd(MAT_PtAPNumeric,A,P,0,0);
266:   return(0);
267: }

269: static PetscErrorCode MatISContainerDestroyFields_Private(void *ptr)
270: {
271:   MatISLocalFields lf = (MatISLocalFields)ptr;
272:   PetscInt         i;
273:   PetscErrorCode   ierr;

276:   for (i=0;i<lf->nr;i++) {
277:     ISDestroy(&lf->rf[i]);
278:   }
279:   for (i=0;i<lf->nc;i++) {
280:     ISDestroy(&lf->cf[i]);
281:   }
282:   PetscFree2(lf->rf,lf->cf);
283:   PetscFree(lf);
284:   return(0);
285: }

287: static PetscErrorCode MatConvert_SeqXAIJ_IS(Mat A,MatType type,MatReuse reuse,Mat *newmat)
288: {
289:   Mat            B,lB;

293:   if (reuse != MAT_REUSE_MATRIX) {
294:     ISLocalToGlobalMapping rl2g,cl2g;
295:     PetscInt               bs;
296:     IS                     is;

298:     MatGetBlockSize(A,&bs);
299:     ISCreateStride(PetscObjectComm((PetscObject)A),A->rmap->n/bs,0,1,&is);
300:     if (bs > 1) {
301:       IS       is2;
302:       PetscInt i,*aux;

304:       ISGetLocalSize(is,&i);
305:       ISGetIndices(is,(const PetscInt**)&aux);
306:       ISCreateBlock(PetscObjectComm((PetscObject)A),bs,i,aux,PETSC_COPY_VALUES,&is2);
307:       ISRestoreIndices(is,(const PetscInt**)&aux);
308:       ISDestroy(&is);
309:       is   = is2;
310:     }
311:     ISSetIdentity(is);
312:     ISLocalToGlobalMappingCreateIS(is,&rl2g);
313:     ISDestroy(&is);
314:     ISCreateStride(PetscObjectComm((PetscObject)A),A->cmap->n/bs,0,1,&is);
315:     if (bs > 1) {
316:       IS       is2;
317:       PetscInt i,*aux;

319:       ISGetLocalSize(is,&i);
320:       ISGetIndices(is,(const PetscInt**)&aux);
321:       ISCreateBlock(PetscObjectComm((PetscObject)A),bs,i,aux,PETSC_COPY_VALUES,&is2);
322:       ISRestoreIndices(is,(const PetscInt**)&aux);
323:       ISDestroy(&is);
324:       is   = is2;
325:     }
326:     ISSetIdentity(is);
327:     ISLocalToGlobalMappingCreateIS(is,&cl2g);
328:     ISDestroy(&is);
329:     MatCreateIS(PetscObjectComm((PetscObject)A),bs,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N,rl2g,cl2g,&B);
330:     ISLocalToGlobalMappingDestroy(&rl2g);
331:     ISLocalToGlobalMappingDestroy(&cl2g);
332:     MatDuplicate(A,MAT_COPY_VALUES,&lB);
333:     if (reuse == MAT_INITIAL_MATRIX) *newmat = B;
334:   } else {
335:     B    = *newmat;
336:     PetscObjectReference((PetscObject)A);
337:     lB   = A;
338:   }
339:   MatISSetLocalMat(B,lB);
340:   MatDestroy(&lB);
341:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
342:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
343:   if (reuse == MAT_INPLACE_MATRIX) {
344:     MatHeaderReplace(A,&B);
345:   }
346:   return(0);
347: }

349: static PetscErrorCode MatISScaleDisassembling_Private(Mat A)
350: {
351:   Mat_IS         *matis = (Mat_IS*)(A->data);
352:   PetscScalar    *aa;
353:   const PetscInt *ii,*jj;
354:   PetscInt       i,n,m;
355:   PetscInt       *ecount,**eneighs;
356:   PetscBool      flg;

360:   MatGetRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&m,&ii,&jj,&flg);
361:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get IJ structure");
362:   ISLocalToGlobalMappingGetNodeInfo(A->rmap->mapping,&n,&ecount,&eneighs);
363:   if (m != n) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected %D != %D",m,n);
364:   MatSeqAIJGetArray(matis->A,&aa);
365:   for (i=0;i<n;i++) {
366:     if (ecount[i] > 1) {
367:       PetscInt j;

369:       for (j=ii[i];j<ii[i+1];j++) {
370:         PetscInt    i2 = jj[j],p,p2;
371:         PetscReal   scal = 0.0;

373:         for (p=0;p<ecount[i];p++) {
374:           for (p2=0;p2<ecount[i2];p2++) {
375:             if (eneighs[i][p] == eneighs[i2][p2]) { scal += 1.0; break; }
376:           }
377:         }
378:         if (scal) aa[j] /= scal;
379:       }
380:     }
381:   }
382:   ISLocalToGlobalMappingRestoreNodeInfo(A->rmap->mapping,&n,&ecount,&eneighs);
383:   MatSeqAIJRestoreArray(matis->A,&aa);
384:   MatRestoreRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&m,&ii,&jj,&flg);
385:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot restore IJ structure");
386:   return(0);
387: }

389: typedef enum {MAT_IS_DISASSEMBLE_L2G_NATURAL,MAT_IS_DISASSEMBLE_L2G_MAT, MAT_IS_DISASSEMBLE_L2G_ND} MatISDisassemblel2gType;

391: static PetscErrorCode MatMPIXAIJComputeLocalToGlobalMapping_Private(Mat A, ISLocalToGlobalMapping *l2g)
392: {
393:   Mat                     Ad,Ao;
394:   IS                      is,ndmap,ndsub;
395:   MPI_Comm                comm;
396:   const PetscInt          *garray,*ndmapi;
397:   PetscInt                bs,i,cnt,nl,*ncount,*ndmapc;
398:   PetscBool               ismpiaij,ismpibaij;
399:   const char *const       MatISDisassemblel2gTypes[] = {"NATURAL","MAT","ND","MatISDisassemblel2gType","MAT_IS_DISASSEMBLE_L2G_",0};
400:   MatISDisassemblel2gType mode = MAT_IS_DISASSEMBLE_L2G_NATURAL;
401:   MatPartitioning         part;
402:   PetscSF                 sf;
403:   PetscErrorCode          ierr;

406:   PetscOptionsBegin(PetscObjectComm((PetscObject)A),((PetscObject)A)->prefix,"MatIS l2g disassembling options","Mat");
407:   PetscOptionsEnum("-mat_is_disassemble_l2g_type","Type of local-to-global mapping to be used for disassembling","MatISDisassemblel2gType",MatISDisassemblel2gTypes,(PetscEnum)mode,(PetscEnum*)&mode,NULL);
408:   PetscOptionsEnd();
409:   if (mode == MAT_IS_DISASSEMBLE_L2G_MAT) {
410:     MatGetLocalToGlobalMapping(A,l2g,NULL);
411:     return(0);
412:   }
413:   PetscObjectGetComm((PetscObject)A,&comm);
414:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ ,&ismpiaij);
415:   PetscObjectTypeCompare((PetscObject)A,MATMPIBAIJ,&ismpibaij);
416:   MatGetBlockSize(A,&bs);
417:   switch (mode) {
418:   case MAT_IS_DISASSEMBLE_L2G_ND:
419:     MatPartitioningCreate(comm,&part);
420:     MatPartitioningSetAdjacency(part,A);
421:     PetscObjectSetOptionsPrefix((PetscObject)part,((PetscObject)A)->prefix);
422:     MatPartitioningSetFromOptions(part);
423:     MatPartitioningApplyND(part,&ndmap);
424:     MatPartitioningDestroy(&part);
425:     ISBuildTwoSided(ndmap,NULL,&ndsub);
426:     MatMPIAIJSetUseScalableIncreaseOverlap(A,PETSC_TRUE);
427:     MatIncreaseOverlap(A,1,&ndsub,1);
428:     ISLocalToGlobalMappingCreateIS(ndsub,l2g);

430:     /* it may happen that a separator node is not properly shared */
431:     ISLocalToGlobalMappingGetNodeInfo(*l2g,&nl,&ncount,NULL);
432:     PetscSFCreate(comm,&sf);
433:     ISLocalToGlobalMappingGetIndices(*l2g,&garray);
434:     PetscSFSetGraphLayout(sf,A->rmap,nl,NULL,PETSC_OWN_POINTER,garray);
435:     ISLocalToGlobalMappingRestoreIndices(*l2g,&garray);
436:     PetscCalloc1(A->rmap->n,&ndmapc);
437:     PetscSFReduceBegin(sf,MPIU_INT,ncount,ndmapc,MPIU_REPLACE);
438:     PetscSFReduceEnd(sf,MPIU_INT,ncount,ndmapc,MPIU_REPLACE);
439:     ISLocalToGlobalMappingRestoreNodeInfo(*l2g,NULL,&ncount,NULL);
440:     ISGetIndices(ndmap,&ndmapi);
441:     for (i = 0, cnt = 0; i < A->rmap->n; i++)
442:       if (ndmapi[i] < 0 && ndmapc[i] < 2)
443:         cnt++;

445:     MPIU_Allreduce(&cnt,&i,1,MPIU_INT,MPI_MAX,comm);
446:     if (i) { /* we detected isolated separator nodes */
447:       Mat                    A2,A3;
448:       IS                     *workis,is2;
449:       PetscScalar            *vals;
450:       PetscInt               gcnt = i,*dnz,*onz,j,*lndmapi;
451:       ISLocalToGlobalMapping ll2g;
452:       PetscBool              flg;
453:       const PetscInt         *ii,*jj;

455:       /* communicate global id of separators */
456:       MatPreallocateInitialize(comm,A->rmap->n,A->cmap->n,dnz,onz);
457:       for (i = 0, cnt = 0; i < A->rmap->n; i++)
458:         dnz[i] = ndmapi[i] < 0 ? i + A->rmap->rstart : -1;

460:       PetscMalloc1(nl,&lndmapi);
461:       PetscSFBcastBegin(sf,MPIU_INT,dnz,lndmapi);

463:       /* compute adjacency of isolated separators node */
464:       PetscMalloc1(gcnt,&workis);
465:       for (i = 0, cnt = 0; i < A->rmap->n; i++) {
466:         if (ndmapi[i] < 0 && ndmapc[i] < 2) {
467:           ISCreateStride(comm,1,i+A->rmap->rstart,1,&workis[cnt++]);
468:         }
469:       }
470:       for (i = cnt; i < gcnt; i++) {
471:         ISCreateStride(comm,0,0,1,&workis[i]);
472:       }
473:       for (i = 0; i < gcnt; i++) {
474:         PetscObjectSetName((PetscObject)workis[i],"ISOLATED");
475:         ISViewFromOptions(workis[i],NULL,"-view_isolated_separators");
476:       }

478:       /* no communications since all the ISes correspond to locally owned rows */
479:       MatIncreaseOverlap(A,gcnt,workis,1);

481:       /* end communicate global id of separators */
482:       PetscSFBcastEnd(sf,MPIU_INT,dnz,lndmapi);

484:       /* communicate new layers : create a matrix and transpose it */
485:       PetscArrayzero(dnz,A->rmap->n);
486:       PetscArrayzero(onz,A->rmap->n);
487:       for (i = 0, j = 0; i < A->rmap->n; i++) {
488:         if (ndmapi[i] < 0 && ndmapc[i] < 2) {
489:           const PetscInt* idxs;
490:           PetscInt        s;

492:           ISGetLocalSize(workis[j],&s);
493:           ISGetIndices(workis[j],&idxs);
494:           MatPreallocateSet(i+A->rmap->rstart,s,idxs,dnz,onz);
495:           j++;
496:         }
497:       }
498:       if (j != cnt) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected local count %D != %D",j,cnt);

500:       for (i = 0; i < gcnt; i++) {
501:         PetscObjectSetName((PetscObject)workis[i],"EXTENDED");
502:         ISViewFromOptions(workis[i],NULL,"-view_isolated_separators");
503:       }

505:       for (i = 0, j = 0; i < A->rmap->n; i++) j = PetscMax(j,dnz[i]+onz[i]);
506:       PetscMalloc1(j,&vals);
507:       for (i = 0; i < j; i++) vals[i] = 1.0;

509:       MatCreate(comm,&A2);
510:       MatSetType(A2,MATMPIAIJ);
511:       MatSetSizes(A2,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N);
512:       MatMPIAIJSetPreallocation(A2,0,dnz,0,onz);
513:       MatSetOption(A2,MAT_NO_OFF_PROC_ENTRIES,PETSC_TRUE);
514:       for (i = 0, j = 0; i < A2->rmap->n; i++) {
515:         PetscInt        row = i+A2->rmap->rstart,s = dnz[i] + onz[i];
516:         const PetscInt* idxs;

518:         if (s) {
519:           ISGetIndices(workis[j],&idxs);
520:           MatSetValues(A2,1,&row,s,idxs,vals,INSERT_VALUES);
521:           ISRestoreIndices(workis[j],&idxs);
522:           j++;
523:         }
524:       }
525:       if (j != cnt) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected local count %D != %D",j,cnt);
526:       PetscFree(vals);
527:       MatAssemblyBegin(A2,MAT_FINAL_ASSEMBLY);
528:       MatAssemblyEnd(A2,MAT_FINAL_ASSEMBLY);
529:       MatTranspose(A2,MAT_INPLACE_MATRIX,&A2);

531:       /* extract submatrix corresponding to the coupling "owned separators" x "isolated separators" */
532:       for (i = 0, j = 0; i < nl; i++)
533:         if (lndmapi[i] >= 0) lndmapi[j++] = lndmapi[i];
534:       ISCreateGeneral(comm,j,lndmapi,PETSC_USE_POINTER,&is);
535:       MatMPIAIJGetLocalMatCondensed(A2,MAT_INITIAL_MATRIX,&is,NULL,&A3);
536:       ISDestroy(&is);
537:       MatDestroy(&A2);

539:       /* extend local to global map to include connected isolated separators */
540:       PetscObjectQuery((PetscObject)A3,"_petsc_GetLocalMatCondensed_iscol",(PetscObject*)&is);
541:       if (!is) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Missing column map");
542:       ISLocalToGlobalMappingCreateIS(is,&ll2g);
543:       MatGetRowIJ(A3,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&flg);
544:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get IJ structure");
545:       ISCreateGeneral(PETSC_COMM_SELF,ii[i],jj,PETSC_COPY_VALUES,&is);
546:       MatRestoreRowIJ(A3,0,PETSC_FALSE,PETSC_FALSE,&i,&ii,&jj,&flg);
547:       if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get IJ structure");
548:       ISLocalToGlobalMappingApplyIS(ll2g,is,&is2);
549:       ISDestroy(&is);
550:       ISLocalToGlobalMappingDestroy(&ll2g);

552:       /* add new nodes to the local-to-global map */
553:       ISLocalToGlobalMappingDestroy(l2g);
554:       ISExpand(ndsub,is2,&is);
555:       ISDestroy(&is2);
556:       ISLocalToGlobalMappingCreateIS(is,l2g);
557:       ISDestroy(&is);

559:       MatDestroy(&A3);
560:       PetscFree(lndmapi);
561:       MatPreallocateFinalize(dnz,onz);
562:       for (i = 0; i < gcnt; i++) {
563:         ISDestroy(&workis[i]);
564:       }
565:       PetscFree(workis);
566:     }
567:     ISRestoreIndices(ndmap,&ndmapi);
568:     PetscSFDestroy(&sf);
569:     PetscFree(ndmapc);
570:     ISDestroy(&ndmap);
571:     ISDestroy(&ndsub);
572:     ISLocalToGlobalMappingSetBlockSize(*l2g,bs);
573:     ISLocalToGlobalMappingViewFromOptions(*l2g,NULL,"-matis_nd_l2g_view");
574:     break;
575:   case MAT_IS_DISASSEMBLE_L2G_NATURAL:
576:     if (ismpiaij) {
577:       MatMPIAIJGetSeqAIJ(A,&Ad,&Ao,&garray);
578:     } else if (ismpibaij) {
579:       MatMPIBAIJGetSeqBAIJ(A,&Ad,&Ao,&garray);
580:     } else SETERRQ1(comm,PETSC_ERR_SUP,"Type %s",((PetscObject)A)->type_name);
581:     if (!garray) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"garray not present");
582:     if (A->rmap->n) {
583:       PetscInt dc,oc,stc,*aux;

585:       MatGetLocalSize(A,NULL,&dc);
586:       MatGetLocalSize(Ao,NULL,&oc);
587:       MatGetOwnershipRangeColumn(A,&stc,NULL);
588:       PetscMalloc1((dc+oc)/bs,&aux);
589:       for (i=0; i<dc/bs; i++) aux[i]       = i+stc/bs;
590:       for (i=0; i<oc/bs; i++) aux[i+dc/bs] = garray[i];
591:       ISCreateBlock(comm,bs,(dc+oc)/bs,aux,PETSC_OWN_POINTER,&is);
592:     } else {
593:       ISCreateBlock(comm,1,0,NULL,PETSC_OWN_POINTER,&is);
594:     }
595:     ISLocalToGlobalMappingCreateIS(is,l2g);
596:     ISDestroy(&is);
597:     break;
598:   default:
599:     SETERRQ1(comm,PETSC_ERR_ARG_WRONG,"Unsupported l2g disassembling type %D",mode);
600:   }
601:   return(0);
602: }

604: PETSC_INTERN PetscErrorCode MatConvert_XAIJ_IS(Mat A,MatType type,MatReuse reuse,Mat *newmat)
605: {
606:   Mat                    lA,Ad,Ao,B = NULL;
607:   ISLocalToGlobalMapping rl2g,cl2g;
608:   IS                     is;
609:   MPI_Comm               comm;
610:   void                   *ptrs[2];
611:   const char             *names[2] = {"_convert_csr_aux","_convert_csr_data"};
612:   const PetscInt         *garray;
613:   PetscScalar            *dd,*od,*aa,*data;
614:   const PetscInt         *di,*dj,*oi,*oj;
615:   const PetscInt         *odi,*odj,*ooi,*ooj;
616:   PetscInt               *aux,*ii,*jj;
617:   PetscInt               bs,lc,dr,dc,oc,str,stc,nnz,i,jd,jo,cum;
618:   PetscBool              flg,ismpiaij,ismpibaij,was_inplace = PETSC_FALSE;
619:   PetscMPIInt            size;
620:   PetscErrorCode         ierr;

623:   PetscObjectGetComm((PetscObject)A,&comm);
624:   MPI_Comm_size(comm,&size);
625:   if (size == 1) {
626:     MatConvert_SeqXAIJ_IS(A,type,reuse,newmat);
627:     return(0);
628:   }
629:   if (reuse != MAT_REUSE_MATRIX && A->cmap->N == A->rmap->N) {
630:     MatMPIXAIJComputeLocalToGlobalMapping_Private(A,&rl2g);
631:     MatCreate(comm,&B);
632:     MatSetType(B,MATIS);
633:     MatSetSizes(B,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N);
634:     MatSetLocalToGlobalMapping(B,rl2g,rl2g);
635:     MatGetBlockSize(A,&bs);
636:     MatSetBlockSize(B,bs);
637:     ISLocalToGlobalMappingDestroy(&rl2g);
638:     if (reuse == MAT_INPLACE_MATRIX) was_inplace = PETSC_TRUE;
639:     reuse = MAT_REUSE_MATRIX;
640:   }
641:   if (reuse == MAT_REUSE_MATRIX) {
642:     Mat            *newlA, lA;
643:     IS             rows, cols;
644:     const PetscInt *ridx, *cidx;
645:     PetscInt       rbs, cbs, nr, nc;

647:     if (!B) B = *newmat;
648:     MatGetLocalToGlobalMapping(B,&rl2g,&cl2g);
649:     ISLocalToGlobalMappingGetBlockIndices(rl2g,&ridx);
650:     ISLocalToGlobalMappingGetBlockIndices(cl2g,&cidx);
651:     ISLocalToGlobalMappingGetSize(rl2g,&nr);
652:     ISLocalToGlobalMappingGetSize(cl2g,&nc);
653:     ISLocalToGlobalMappingGetBlockSize(rl2g,&rbs);
654:     ISLocalToGlobalMappingGetBlockSize(cl2g,&cbs);
655:     ISCreateBlock(comm,rbs,nr/rbs,ridx,PETSC_USE_POINTER,&rows);
656:     if (rl2g != cl2g) {
657:       ISCreateBlock(comm,cbs,nc/cbs,cidx,PETSC_USE_POINTER,&cols);
658:     } else {
659:       PetscObjectReference((PetscObject)rows);
660:       cols = rows;
661:     }
662:     MatISGetLocalMat(B,&lA);
663:     MatCreateSubMatrices(A,1,&rows,&cols,MAT_INITIAL_MATRIX,&newlA);
664:     MatConvert(newlA[0],MATSEQAIJ,MAT_INPLACE_MATRIX,&newlA[0]);
665:     ISLocalToGlobalMappingRestoreBlockIndices(rl2g,&ridx);
666:     ISLocalToGlobalMappingRestoreBlockIndices(cl2g,&cidx);
667:     ISDestroy(&rows);
668:     ISDestroy(&cols);
669:     if (!lA->preallocated) { /* first time */
670:       MatDuplicate(newlA[0],MAT_COPY_VALUES,&lA);
671:       MatISSetLocalMat(B,lA);
672:       PetscObjectDereference((PetscObject)lA);
673:     }
674:     MatCopy(newlA[0],lA,SAME_NONZERO_PATTERN);
675:     MatDestroySubMatrices(1,&newlA);
676:     MatISScaleDisassembling_Private(B);
677:     MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
678:     MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
679:     if (was_inplace) { MatHeaderReplace(A,&B); }
680:     else *newmat = B;
681:     return(0);
682:   }
683:   /* rectangular case, just compress out the column space */
684:   PetscObjectTypeCompare((PetscObject)A,MATMPIAIJ ,&ismpiaij);
685:   PetscObjectTypeCompare((PetscObject)A,MATMPIBAIJ,&ismpibaij);
686:   if (ismpiaij) {
687:     bs   = 1;
688:     MatMPIAIJGetSeqAIJ(A,&Ad,&Ao,&garray);
689:   } else if (ismpibaij) {
690:     MatGetBlockSize(A,&bs);
691:     MatMPIBAIJGetSeqBAIJ(A,&Ad,&Ao,&garray);
692:     MatConvert(Ad,MATSEQAIJ,MAT_INITIAL_MATRIX,&Ad);
693:     MatConvert(Ao,MATSEQAIJ,MAT_INITIAL_MATRIX,&Ao);
694:   } else SETERRQ1(comm,PETSC_ERR_SUP,"Type %s",((PetscObject)A)->type_name);
695:   MatSeqAIJGetArray(Ad,&dd);
696:   MatSeqAIJGetArray(Ao,&od);
697:   if (!garray) SETERRQ(comm,PETSC_ERR_ARG_WRONGSTATE,"garray not present");

699:   /* access relevant information from MPIAIJ */
700:   MatGetOwnershipRange(A,&str,NULL);
701:   MatGetOwnershipRangeColumn(A,&stc,NULL);
702:   MatGetLocalSize(A,&dr,&dc);
703:   MatGetLocalSize(Ao,NULL,&oc);
704:   MatGetRowIJ(Ad,0,PETSC_FALSE,PETSC_FALSE,&i,&di,&dj,&flg);
705:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get IJ structure");
706:   MatGetRowIJ(Ao,0,PETSC_FALSE,PETSC_FALSE,&i,&oi,&oj,&flg);
707:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get IJ structure");
708:   nnz = di[dr] + oi[dr];
709:   /* store original pointers to be restored later */
710:   odi = di; odj = dj; ooi = oi; ooj = oj;

712:   /* generate l2g maps for rows and cols */
713:   ISCreateStride(comm,dr/bs,str/bs,1,&is);
714:   if (bs > 1) {
715:     IS is2;

717:     ISGetLocalSize(is,&i);
718:     ISGetIndices(is,(const PetscInt**)&aux);
719:     ISCreateBlock(comm,bs,i,aux,PETSC_COPY_VALUES,&is2);
720:     ISRestoreIndices(is,(const PetscInt**)&aux);
721:     ISDestroy(&is);
722:     is   = is2;
723:   }
724:   ISLocalToGlobalMappingCreateIS(is,&rl2g);
725:   ISDestroy(&is);
726:   if (dr) {
727:     PetscMalloc1((dc+oc)/bs,&aux);
728:     for (i=0; i<dc/bs; i++) aux[i]       = i+stc/bs;
729:     for (i=0; i<oc/bs; i++) aux[i+dc/bs] = garray[i];
730:     ISCreateBlock(comm,bs,(dc+oc)/bs,aux,PETSC_OWN_POINTER,&is);
731:     lc   = dc+oc;
732:   } else {
733:     ISCreateBlock(comm,bs,0,NULL,PETSC_OWN_POINTER,&is);
734:     lc   = 0;
735:   }
736:   ISLocalToGlobalMappingCreateIS(is,&cl2g);
737:   ISDestroy(&is);

739:   /* create MATIS object */
740:   MatCreate(comm,&B);
741:   MatSetSizes(B,dr,dc,PETSC_DECIDE,PETSC_DECIDE);
742:   MatSetType(B,MATIS);
743:   MatSetBlockSize(B,bs);
744:   MatSetLocalToGlobalMapping(B,rl2g,cl2g);
745:   ISLocalToGlobalMappingDestroy(&rl2g);
746:   ISLocalToGlobalMappingDestroy(&cl2g);

748:   /* merge local matrices */
749:   PetscMalloc1(nnz+dr+1,&aux);
750:   PetscMalloc1(nnz,&data);
751:   ii   = aux;
752:   jj   = aux+dr+1;
753:   aa   = data;
754:   *ii  = *(di++) + *(oi++);
755:   for (jd=0,jo=0,cum=0;*ii<nnz;cum++)
756:   {
757:      for (;jd<*di;jd++) { *jj++ = *dj++;      *aa++ = *dd++; }
758:      for (;jo<*oi;jo++) { *jj++ = *oj++ + dc; *aa++ = *od++; }
759:      *(++ii) = *(di++) + *(oi++);
760:   }
761:   for (;cum<dr;cum++) *(++ii) = nnz;

763:   MatRestoreRowIJ(Ad,0,PETSC_FALSE,PETSC_FALSE,&i,&odi,&odj,&flg);
764:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot restore IJ structure");
765:   MatRestoreRowIJ(Ao,0,PETSC_FALSE,PETSC_FALSE,&i,&ooi,&ooj,&flg);
766:   if (!flg) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot restore IJ structure");
767:   MatSeqAIJRestoreArray(Ad,&dd);
768:   MatSeqAIJRestoreArray(Ao,&od);

770:   ii   = aux;
771:   jj   = aux+dr+1;
772:   aa   = data;
773:   MatCreateSeqAIJWithArrays(PETSC_COMM_SELF,dr,lc,ii,jj,aa,&lA);

775:   /* create containers to destroy the data */
776:   ptrs[0] = aux;
777:   ptrs[1] = data;
778:   for (i=0; i<2; i++) {
779:     PetscContainer c;

781:     PetscContainerCreate(PETSC_COMM_SELF,&c);
782:     PetscContainerSetPointer(c,ptrs[i]);
783:     PetscContainerSetUserDestroy(c,PetscContainerUserDestroyDefault);
784:     PetscObjectCompose((PetscObject)lA,names[i],(PetscObject)c);
785:     PetscContainerDestroy(&c);
786:   }
787:   if (ismpibaij) { /* destroy converted local matrices */
788:     MatDestroy(&Ad);
789:     MatDestroy(&Ao);
790:   }

792:   /* finalize matrix */
793:   MatISSetLocalMat(B,lA);
794:   MatDestroy(&lA);
795:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
796:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
797:   if (reuse == MAT_INPLACE_MATRIX) {
798:     MatHeaderReplace(A,&B);
799:   } else *newmat = B;
800:   return(0);
801: }

803: PETSC_INTERN PetscErrorCode MatConvert_Nest_IS(Mat A,MatType type,MatReuse reuse,Mat *newmat)
804: {
805:   Mat                    **nest,*snest,**rnest,lA,B;
806:   IS                     *iscol,*isrow,*islrow,*islcol;
807:   ISLocalToGlobalMapping rl2g,cl2g;
808:   MPI_Comm               comm;
809:   PetscInt               *lr,*lc,*l2gidxs;
810:   PetscInt               i,j,nr,nc,rbs,cbs;
811:   PetscBool              convert,lreuse,*istrans;
812:   PetscErrorCode         ierr;

815:   MatNestGetSubMats(A,&nr,&nc,&nest);
816:   lreuse = PETSC_FALSE;
817:   rnest  = NULL;
818:   if (reuse == MAT_REUSE_MATRIX) {
819:     PetscBool ismatis,isnest;

821:     PetscObjectTypeCompare((PetscObject)*newmat,MATIS,&ismatis);
822:     if (!ismatis) SETERRQ1(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_USER,"Cannot reuse matrix of type %s",((PetscObject)(*newmat))->type);
823:     MatISGetLocalMat(*newmat,&lA);
824:     PetscObjectTypeCompare((PetscObject)lA,MATNEST,&isnest);
825:     if (isnest) {
826:       MatNestGetSubMats(lA,&i,&j,&rnest);
827:       lreuse = (PetscBool)(i == nr && j == nc);
828:       if (!lreuse) rnest = NULL;
829:     }
830:   }
831:   PetscObjectGetComm((PetscObject)A,&comm);
832:   PetscCalloc2(nr,&lr,nc,&lc);
833:   PetscCalloc6(nr,&isrow,nc,&iscol,
834:                       nr,&islrow,nc,&islcol,
835:                       nr*nc,&snest,nr*nc,&istrans);
836:   MatNestGetISs(A,isrow,iscol);
837:   for (i=0;i<nr;i++) {
838:     for (j=0;j<nc;j++) {
839:       PetscBool ismatis;
840:       PetscInt  l1,l2,lb1,lb2,ij=i*nc+j;

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

845:       /* Nested matrices should be of type MATIS */
846:       PetscObjectTypeCompare((PetscObject)nest[i][j],MATTRANSPOSEMAT,&istrans[ij]);
847:       if (istrans[ij]) {
848:         Mat T,lT;
849:         MatTransposeGetMat(nest[i][j],&T);
850:         PetscObjectTypeCompare((PetscObject)T,MATIS,&ismatis);
851:         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);
852:         MatISGetLocalMat(T,&lT);
853:         MatCreateTranspose(lT,&snest[ij]);
854:       } else {
855:         PetscObjectTypeCompare((PetscObject)nest[i][j],MATIS,&ismatis);
856:         if (!ismatis) SETERRQ2(comm,PETSC_ERR_SUP,"Cannot convert from MATNEST to MATIS! Matrix block (%D,%D) is not of type MATIS",i,j);
857:         MatISGetLocalMat(nest[i][j],&snest[ij]);
858:       }

860:       /* Check compatibility of local sizes */
861:       MatGetSize(snest[ij],&l1,&l2);
862:       MatGetBlockSizes(snest[ij],&lb1,&lb2);
863:       if (!l1 || !l2) continue;
864:       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);
865:       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);
866:       lr[i] = l1;
867:       lc[j] = l2;

869:       /* check compatibilty for local matrix reusage */
870:       if (rnest && !rnest[i][j] != !snest[ij]) lreuse = PETSC_FALSE;
871:     }
872:   }

874: #if defined (PETSC_USE_DEBUG)
875:   /* Check compatibility of l2g maps for rows */
876:   for (i=0;i<nr;i++) {
877:     rl2g = NULL;
878:     for (j=0;j<nc;j++) {
879:       PetscInt n1,n2;

881:       if (!nest[i][j]) continue;
882:       if (istrans[i*nc+j]) {
883:         Mat T;

885:         MatTransposeGetMat(nest[i][j],&T);
886:         MatGetLocalToGlobalMapping(T,NULL,&cl2g);
887:       } else {
888:         MatGetLocalToGlobalMapping(nest[i][j],&cl2g,NULL);
889:       }
890:       ISLocalToGlobalMappingGetSize(cl2g,&n1);
891:       if (!n1) continue;
892:       if (!rl2g) {
893:         rl2g = cl2g;
894:       } else {
895:         const PetscInt *idxs1,*idxs2;
896:         PetscBool      same;

898:         ISLocalToGlobalMappingGetSize(rl2g,&n2);
899:         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);
900:         ISLocalToGlobalMappingGetIndices(cl2g,&idxs1);
901:         ISLocalToGlobalMappingGetIndices(rl2g,&idxs2);
902:         PetscArraycmp(idxs1,idxs2,n1,&same);
903:         ISLocalToGlobalMappingRestoreIndices(cl2g,&idxs1);
904:         ISLocalToGlobalMappingRestoreIndices(rl2g,&idxs2);
905:         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);
906:       }
907:     }
908:   }
909:   /* Check compatibility of l2g maps for columns */
910:   for (i=0;i<nc;i++) {
911:     rl2g = NULL;
912:     for (j=0;j<nr;j++) {
913:       PetscInt n1,n2;

915:       if (!nest[j][i]) continue;
916:       if (istrans[j*nc+i]) {
917:         Mat T;

919:         MatTransposeGetMat(nest[j][i],&T);
920:         MatGetLocalToGlobalMapping(T,&cl2g,NULL);
921:       } else {
922:         MatGetLocalToGlobalMapping(nest[j][i],NULL,&cl2g);
923:       }
924:       ISLocalToGlobalMappingGetSize(cl2g,&n1);
925:       if (!n1) continue;
926:       if (!rl2g) {
927:         rl2g = cl2g;
928:       } else {
929:         const PetscInt *idxs1,*idxs2;
930:         PetscBool      same;

932:         ISLocalToGlobalMappingGetSize(rl2g,&n2);
933:         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);
934:         ISLocalToGlobalMappingGetIndices(cl2g,&idxs1);
935:         ISLocalToGlobalMappingGetIndices(rl2g,&idxs2);
936:         PetscArraycmp(idxs1,idxs2,n1,&same);
937:         ISLocalToGlobalMappingRestoreIndices(cl2g,&idxs1);
938:         ISLocalToGlobalMappingRestoreIndices(rl2g,&idxs2);
939:         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);
940:       }
941:     }
942:   }
943: #endif

945:   B = NULL;
946:   if (reuse != MAT_REUSE_MATRIX) {
947:     PetscInt stl;

949:     /* Create l2g map for the rows of the new matrix and index sets for the local MATNEST */
950:     for (i=0,stl=0;i<nr;i++) stl += lr[i];
951:     PetscMalloc1(stl,&l2gidxs);
952:     for (i=0,stl=0;i<nr;i++) {
953:       Mat            usedmat;
954:       Mat_IS         *matis;
955:       const PetscInt *idxs;

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

960:       /* l2gmap */
961:       j = 0;
962:       usedmat = nest[i][j];
963:       while (!usedmat && j < nc-1) usedmat = nest[i][++j];
964:       if (!usedmat) SETERRQ(comm,PETSC_ERR_SUP,"Cannot find valid row mat");

966:       if (istrans[i*nc+j]) {
967:         Mat T;
968:         MatTransposeGetMat(usedmat,&T);
969:         usedmat = T;
970:       }
971:       matis = (Mat_IS*)(usedmat->data);
972:       ISGetIndices(isrow[i],&idxs);
973:       if (istrans[i*nc+j]) {
974:         PetscSFBcastBegin(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
975:         PetscSFBcastEnd(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
976:       } else {
977:         PetscSFBcastBegin(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
978:         PetscSFBcastEnd(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
979:       }
980:       ISRestoreIndices(isrow[i],&idxs);
981:       stl += lr[i];
982:     }
983:     ISLocalToGlobalMappingCreate(comm,1,stl,l2gidxs,PETSC_OWN_POINTER,&rl2g);

985:     /* Create l2g map for columns of the new matrix and index sets for the local MATNEST */
986:     for (i=0,stl=0;i<nc;i++) stl += lc[i];
987:     PetscMalloc1(stl,&l2gidxs);
988:     for (i=0,stl=0;i<nc;i++) {
989:       Mat            usedmat;
990:       Mat_IS         *matis;
991:       const PetscInt *idxs;

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

996:       /* l2gmap */
997:       j = 0;
998:       usedmat = nest[j][i];
999:       while (!usedmat && j < nr-1) usedmat = nest[++j][i];
1000:       if (!usedmat) SETERRQ(comm,PETSC_ERR_SUP,"Cannot find valid column mat");
1001:       if (istrans[j*nc+i]) {
1002:         Mat T;
1003:         MatTransposeGetMat(usedmat,&T);
1004:         usedmat = T;
1005:       }
1006:       matis = (Mat_IS*)(usedmat->data);
1007:       ISGetIndices(iscol[i],&idxs);
1008:       if (istrans[j*nc+i]) {
1009:         PetscSFBcastBegin(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
1010:         PetscSFBcastEnd(matis->sf,MPIU_INT,idxs,l2gidxs+stl);
1011:       } else {
1012:         PetscSFBcastBegin(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
1013:         PetscSFBcastEnd(matis->csf,MPIU_INT,idxs,l2gidxs+stl);
1014:       }
1015:       ISRestoreIndices(iscol[i],&idxs);
1016:       stl += lc[i];
1017:     }
1018:     ISLocalToGlobalMappingCreate(comm,1,stl,l2gidxs,PETSC_OWN_POINTER,&cl2g);

1020:     /* Create MATIS */
1021:     MatCreate(comm,&B);
1022:     MatSetSizes(B,A->rmap->n,A->cmap->n,A->rmap->N,A->cmap->N);
1023:     MatGetBlockSizes(A,&rbs,&cbs);
1024:     MatSetBlockSizes(B,rbs,cbs);
1025:     MatSetType(B,MATIS);
1026:     MatISSetLocalMatType(B,MATNEST);
1027:     { /* hack : avoid setup of scatters */
1028:       Mat_IS *matis = (Mat_IS*)(B->data);
1029:       matis->islocalref = PETSC_TRUE;
1030:     }
1031:     MatSetLocalToGlobalMapping(B,rl2g,cl2g);
1032:     ISLocalToGlobalMappingDestroy(&rl2g);
1033:     ISLocalToGlobalMappingDestroy(&cl2g);
1034:     MatCreateNest(PETSC_COMM_SELF,nr,islrow,nc,islcol,snest,&lA);
1035:     MatNestSetVecType(lA,VECNEST);
1036:     for (i=0;i<nr*nc;i++) {
1037:       if (istrans[i]) {
1038:         MatDestroy(&snest[i]);
1039:       }
1040:     }
1041:     MatISSetLocalMat(B,lA);
1042:     MatDestroy(&lA);
1043:     { /* hack : setup of scatters done here */
1044:       Mat_IS *matis = (Mat_IS*)(B->data);

1046:       matis->islocalref = PETSC_FALSE;
1047:       MatISSetUpScatters_Private(B);
1048:     }
1049:     MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1050:     MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1051:     if (reuse == MAT_INPLACE_MATRIX) {
1052:       MatHeaderReplace(A,&B);
1053:     } else {
1054:       *newmat = B;
1055:     }
1056:   } else {
1057:     if (lreuse) {
1058:       MatISGetLocalMat(*newmat,&lA);
1059:       for (i=0;i<nr;i++) {
1060:         for (j=0;j<nc;j++) {
1061:           if (snest[i*nc+j]) {
1062:             MatNestSetSubMat(lA,i,j,snest[i*nc+j]);
1063:             if (istrans[i*nc+j]) {
1064:               MatDestroy(&snest[i*nc+j]);
1065:             }
1066:           }
1067:         }
1068:       }
1069:     } else {
1070:       PetscInt stl;
1071:       for (i=0,stl=0;i<nr;i++) {
1072:         ISCreateStride(PETSC_COMM_SELF,lr[i],stl,1,&islrow[i]);
1073:         stl  += lr[i];
1074:       }
1075:       for (i=0,stl=0;i<nc;i++) {
1076:         ISCreateStride(PETSC_COMM_SELF,lc[i],stl,1,&islcol[i]);
1077:         stl  += lc[i];
1078:       }
1079:       MatCreateNest(PETSC_COMM_SELF,nr,islrow,nc,islcol,snest,&lA);
1080:       for (i=0;i<nr*nc;i++) {
1081:         if (istrans[i]) {
1082:           MatDestroy(&snest[i]);
1083:         }
1084:       }
1085:       MatISSetLocalMat(*newmat,lA);
1086:       MatDestroy(&lA);
1087:     }
1088:     MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
1089:     MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
1090:   }

1092:   /* Create local matrix in MATNEST format */
1093:   convert = PETSC_FALSE;
1094:   PetscOptionsGetBool(NULL,((PetscObject)A)->prefix,"-matis_convert_local_nest",&convert,NULL);
1095:   if (convert) {
1096:     Mat              M;
1097:     MatISLocalFields lf;
1098:     PetscContainer   c;

1100:     MatISGetLocalMat(*newmat,&lA);
1101:     MatConvert(lA,MATAIJ,MAT_INITIAL_MATRIX,&M);
1102:     MatISSetLocalMat(*newmat,M);
1103:     MatDestroy(&M);

1105:     /* attach local fields to the matrix */
1106:     PetscNew(&lf);
1107:     PetscCalloc2(nr,&lf->rf,nc,&lf->cf);
1108:     for (i=0;i<nr;i++) {
1109:       PetscInt n,st;

1111:       ISGetLocalSize(islrow[i],&n);
1112:       ISStrideGetInfo(islrow[i],&st,NULL);
1113:       ISCreateStride(comm,n,st,1,&lf->rf[i]);
1114:     }
1115:     for (i=0;i<nc;i++) {
1116:       PetscInt n,st;

1118:       ISGetLocalSize(islcol[i],&n);
1119:       ISStrideGetInfo(islcol[i],&st,NULL);
1120:       ISCreateStride(comm,n,st,1,&lf->cf[i]);
1121:     }
1122:     lf->nr = nr;
1123:     lf->nc = nc;
1124:     PetscContainerCreate(PetscObjectComm((PetscObject)(*newmat)),&c);
1125:     PetscContainerSetPointer(c,lf);
1126:     PetscContainerSetUserDestroy(c,MatISContainerDestroyFields_Private);
1127:     PetscObjectCompose((PetscObject)(*newmat),"_convert_nest_lfields",(PetscObject)c);
1128:     PetscContainerDestroy(&c);
1129:   }

1131:   /* Free workspace */
1132:   for (i=0;i<nr;i++) {
1133:     ISDestroy(&islrow[i]);
1134:   }
1135:   for (i=0;i<nc;i++) {
1136:     ISDestroy(&islcol[i]);
1137:   }
1138:   PetscFree6(isrow,iscol,islrow,islcol,snest,istrans);
1139:   PetscFree2(lr,lc);
1140:   return(0);
1141: }

1143: static PetscErrorCode MatDiagonalScale_IS(Mat A, Vec l, Vec r)
1144: {
1145:   Mat_IS            *matis = (Mat_IS*)A->data;
1146:   Vec               ll,rr;
1147:   const PetscScalar *Y,*X;
1148:   PetscScalar       *x,*y;
1149:   PetscErrorCode    ierr;

1152:   if (l) {
1153:     ll   = matis->y;
1154:     VecGetArrayRead(l,&Y);
1155:     VecGetArray(ll,&y);
1156:     PetscSFBcastBegin(matis->sf,MPIU_SCALAR,Y,y);
1157:   } else {
1158:     ll = NULL;
1159:   }
1160:   if (r) {
1161:     rr   = matis->x;
1162:     VecGetArrayRead(r,&X);
1163:     VecGetArray(rr,&x);
1164:     PetscSFBcastBegin(matis->csf,MPIU_SCALAR,X,x);
1165:   } else {
1166:     rr = NULL;
1167:   }
1168:   if (ll) {
1169:     PetscSFBcastEnd(matis->sf,MPIU_SCALAR,Y,y);
1170:     VecRestoreArrayRead(l,&Y);
1171:     VecRestoreArray(ll,&y);
1172:   }
1173:   if (rr) {
1174:     PetscSFBcastEnd(matis->csf,MPIU_SCALAR,X,x);
1175:     VecRestoreArrayRead(r,&X);
1176:     VecRestoreArray(rr,&x);
1177:   }
1178:   MatDiagonalScale(matis->A,ll,rr);
1179:   return(0);
1180: }

1182: static PetscErrorCode MatGetInfo_IS(Mat A,MatInfoType flag,MatInfo *ginfo)
1183: {
1184:   Mat_IS         *matis = (Mat_IS*)A->data;
1185:   MatInfo        info;
1186:   PetscReal      isend[6],irecv[6];
1187:   PetscInt       bs;

1191:   MatGetBlockSize(A,&bs);
1192:   if (matis->A->ops->getinfo) {
1193:     MatGetInfo(matis->A,MAT_LOCAL,&info);
1194:     isend[0] = info.nz_used;
1195:     isend[1] = info.nz_allocated;
1196:     isend[2] = info.nz_unneeded;
1197:     isend[3] = info.memory;
1198:     isend[4] = info.mallocs;
1199:   } else {
1200:     isend[0] = 0.;
1201:     isend[1] = 0.;
1202:     isend[2] = 0.;
1203:     isend[3] = 0.;
1204:     isend[4] = 0.;
1205:   }
1206:   isend[5] = matis->A->num_ass;
1207:   if (flag == MAT_LOCAL) {
1208:     ginfo->nz_used      = isend[0];
1209:     ginfo->nz_allocated = isend[1];
1210:     ginfo->nz_unneeded  = isend[2];
1211:     ginfo->memory       = isend[3];
1212:     ginfo->mallocs      = isend[4];
1213:     ginfo->assemblies   = isend[5];
1214:   } else if (flag == MAT_GLOBAL_MAX) {
1215:     MPIU_Allreduce(isend,irecv,6,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)A));

1217:     ginfo->nz_used      = irecv[0];
1218:     ginfo->nz_allocated = irecv[1];
1219:     ginfo->nz_unneeded  = irecv[2];
1220:     ginfo->memory       = irecv[3];
1221:     ginfo->mallocs      = irecv[4];
1222:     ginfo->assemblies   = irecv[5];
1223:   } else if (flag == MAT_GLOBAL_SUM) {
1224:     MPIU_Allreduce(isend,irecv,5,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)A));

1226:     ginfo->nz_used      = irecv[0];
1227:     ginfo->nz_allocated = irecv[1];
1228:     ginfo->nz_unneeded  = irecv[2];
1229:     ginfo->memory       = irecv[3];
1230:     ginfo->mallocs      = irecv[4];
1231:     ginfo->assemblies   = A->num_ass;
1232:   }
1233:   ginfo->block_size        = bs;
1234:   ginfo->fill_ratio_given  = 0;
1235:   ginfo->fill_ratio_needed = 0;
1236:   ginfo->factor_mallocs    = 0;
1237:   return(0);
1238: }

1240: PetscErrorCode MatTranspose_IS(Mat A,MatReuse reuse,Mat *B)
1241: {
1242:   Mat                    C,lC,lA;
1243:   PetscErrorCode         ierr;

1246:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
1247:     ISLocalToGlobalMapping rl2g,cl2g;
1248:     MatCreate(PetscObjectComm((PetscObject)A),&C);
1249:     MatSetSizes(C,A->cmap->n,A->rmap->n,A->cmap->N,A->rmap->N);
1250:     MatSetBlockSizes(C,PetscAbs(A->cmap->bs),PetscAbs(A->rmap->bs));
1251:     MatSetType(C,MATIS);
1252:     MatGetLocalToGlobalMapping(A,&rl2g,&cl2g);
1253:     MatSetLocalToGlobalMapping(C,cl2g,rl2g);
1254:   } else {
1255:     C = *B;
1256:   }

1258:   /* perform local transposition */
1259:   MatISGetLocalMat(A,&lA);
1260:   MatTranspose(lA,MAT_INITIAL_MATRIX,&lC);
1261:   MatISSetLocalMat(C,lC);
1262:   MatDestroy(&lC);

1264:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
1265:     *B = C;
1266:   } else {
1267:     MatHeaderMerge(A,&C);
1268:   }
1269:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
1270:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
1271:   return(0);
1272: }

1274: PetscErrorCode  MatDiagonalSet_IS(Mat A,Vec D,InsertMode insmode)
1275: {
1276:   Mat_IS         *is = (Mat_IS*)A->data;

1280:   if (D) { /* MatShift_IS pass D = NULL */
1281:     VecScatterBegin(is->rctx,D,is->y,INSERT_VALUES,SCATTER_FORWARD);
1282:     VecScatterEnd(is->rctx,D,is->y,INSERT_VALUES,SCATTER_FORWARD);
1283:   }
1284:   VecPointwiseDivide(is->y,is->y,is->counter);
1285:   MatDiagonalSet(is->A,is->y,insmode);
1286:   return(0);
1287: }

1289: PetscErrorCode  MatShift_IS(Mat A,PetscScalar a)
1290: {
1291:   Mat_IS         *is = (Mat_IS*)A->data;

1295:   VecSet(is->y,a);
1296:   MatDiagonalSet_IS(A,NULL,ADD_VALUES);
1297:   return(0);
1298: }

1300: static PetscErrorCode MatSetValuesLocal_SubMat_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
1301: {
1303:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

1306: #if defined(PETSC_USE_DEBUG)
1307:   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);
1308: #endif
1309:   ISLocalToGlobalMappingApply(A->rmap->mapping,m,rows,rows_l);
1310:   ISLocalToGlobalMappingApply(A->cmap->mapping,n,cols,cols_l);
1311:   MatSetValuesLocal_IS(A,m,rows_l,n,cols_l,values,addv);
1312:   return(0);
1313: }

1315: static PetscErrorCode MatSetValuesBlockedLocal_SubMat_IS(Mat A,PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols,const PetscScalar *values,InsertMode addv)
1316: {
1318:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

1321: #if defined(PETSC_USE_DEBUG)
1322:   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);
1323: #endif
1324:   ISLocalToGlobalMappingApplyBlock(A->rmap->mapping,m,rows,rows_l);
1325:   ISLocalToGlobalMappingApplyBlock(A->cmap->mapping,n,cols,cols_l);
1326:   MatSetValuesBlockedLocal_IS(A,m,rows_l,n,cols_l,values,addv);
1327:   return(0);
1328: }

1330: static PetscErrorCode MatCreateSubMatrix_IS(Mat mat,IS irow,IS icol,MatReuse scall,Mat *newmat)
1331: {
1332:   Mat               locmat,newlocmat;
1333:   Mat_IS            *newmatis;
1334: #if defined(PETSC_USE_DEBUG)
1335:   Vec               rtest,ltest;
1336:   const PetscScalar *array;
1337: #endif
1338:   const PetscInt    *idxs;
1339:   PetscInt          i,m,n;
1340:   PetscErrorCode    ierr;

1343:   if (scall == MAT_REUSE_MATRIX) {
1344:     PetscBool ismatis;

1346:     PetscObjectTypeCompare((PetscObject)*newmat,MATIS,&ismatis);
1347:     if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Not of MATIS type");
1348:     newmatis = (Mat_IS*)(*newmat)->data;
1349:     if (!newmatis->getsub_ris) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Misses local row IS");
1350:     if (!newmatis->getsub_cis) SETERRQ(PetscObjectComm((PetscObject)*newmat),PETSC_ERR_ARG_WRONG,"Cannot reuse matrix! Misses local col IS");
1351:   }
1352:   /* irow and icol may not have duplicate entries */
1353: #if defined(PETSC_USE_DEBUG)
1354:   MatCreateVecs(mat,&ltest,&rtest);
1355:   ISGetLocalSize(irow,&n);
1356:   ISGetIndices(irow,&idxs);
1357:   for (i=0;i<n;i++) {
1358:     VecSetValue(rtest,idxs[i],1.0,ADD_VALUES);
1359:   }
1360:   VecAssemblyBegin(rtest);
1361:   VecAssemblyEnd(rtest);
1362:   VecGetLocalSize(rtest,&n);
1363:   VecGetOwnershipRange(rtest,&m,NULL);
1364:   VecGetArrayRead(rtest,&array);
1365:   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]));
1366:   VecRestoreArrayRead(rtest,&array);
1367:   ISRestoreIndices(irow,&idxs);
1368:   ISGetLocalSize(icol,&n);
1369:   ISGetIndices(icol,&idxs);
1370:   for (i=0;i<n;i++) {
1371:     VecSetValue(ltest,idxs[i],1.0,ADD_VALUES);
1372:   }
1373:   VecAssemblyBegin(ltest);
1374:   VecAssemblyEnd(ltest);
1375:   VecGetLocalSize(ltest,&n);
1376:   VecGetOwnershipRange(ltest,&m,NULL);
1377:   VecGetArrayRead(ltest,&array);
1378:   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]));
1379:   VecRestoreArrayRead(ltest,&array);
1380:   ISRestoreIndices(icol,&idxs);
1381:   VecDestroy(&rtest);
1382:   VecDestroy(&ltest);
1383: #endif
1384:   if (scall == MAT_INITIAL_MATRIX) {
1385:     Mat_IS                 *matis = (Mat_IS*)mat->data;
1386:     ISLocalToGlobalMapping rl2g;
1387:     IS                     is;
1388:     PetscInt               *lidxs,*lgidxs,*newgidxs;
1389:     PetscInt               ll,newloc,irbs,icbs,arbs,acbs,rbs,cbs;
1390:     PetscBool              cong;
1391:     MPI_Comm               comm;

1393:     PetscObjectGetComm((PetscObject)mat,&comm);
1394:     MatGetBlockSizes(mat,&arbs,&acbs);
1395:     ISGetBlockSize(irow,&irbs);
1396:     ISGetBlockSize(icol,&icbs);
1397:     rbs  = arbs == irbs ? irbs : 1;
1398:     cbs  = acbs == icbs ? icbs : 1;
1399:     ISGetLocalSize(irow,&m);
1400:     ISGetLocalSize(icol,&n);
1401:     MatCreate(comm,newmat);
1402:     MatSetType(*newmat,MATIS);
1403:     MatSetSizes(*newmat,m,n,PETSC_DECIDE,PETSC_DECIDE);
1404:     MatSetBlockSizes(*newmat,rbs,cbs);
1405:     /* communicate irow to their owners in the layout */
1406:     ISGetIndices(irow,&idxs);
1407:     PetscLayoutMapLocal(mat->rmap,m,idxs,&ll,&lidxs,&lgidxs);
1408:     ISRestoreIndices(irow,&idxs);
1409:     PetscArrayzero(matis->sf_rootdata,matis->sf->nroots);
1410:     for (i=0;i<ll;i++) matis->sf_rootdata[lidxs[i]] = lgidxs[i]+1;
1411:     PetscFree(lidxs);
1412:     PetscFree(lgidxs);
1413:     PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1414:     PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1415:     for (i=0,newloc=0;i<matis->sf->nleaves;i++) if (matis->sf_leafdata[i]) newloc++;
1416:     PetscMalloc1(newloc,&newgidxs);
1417:     PetscMalloc1(newloc,&lidxs);
1418:     for (i=0,newloc=0;i<matis->sf->nleaves;i++)
1419:       if (matis->sf_leafdata[i]) {
1420:         lidxs[newloc] = i;
1421:         newgidxs[newloc++] = matis->sf_leafdata[i]-1;
1422:       }
1423:     ISCreateGeneral(comm,newloc,newgidxs,PETSC_OWN_POINTER,&is);
1424:     ISLocalToGlobalMappingCreateIS(is,&rl2g);
1425:     ISLocalToGlobalMappingSetBlockSize(rl2g,rbs);
1426:     ISDestroy(&is);
1427:     /* local is to extract local submatrix */
1428:     newmatis = (Mat_IS*)(*newmat)->data;
1429:     ISCreateGeneral(comm,newloc,lidxs,PETSC_OWN_POINTER,&newmatis->getsub_ris);
1430:     MatHasCongruentLayouts(mat,&cong);
1431:     if (cong && irow == icol && matis->csf == matis->sf) {
1432:       MatSetLocalToGlobalMapping(*newmat,rl2g,rl2g);
1433:       PetscObjectReference((PetscObject)newmatis->getsub_ris);
1434:       newmatis->getsub_cis = newmatis->getsub_ris;
1435:     } else {
1436:       ISLocalToGlobalMapping cl2g;

1438:       /* communicate icol to their owners in the layout */
1439:       ISGetIndices(icol,&idxs);
1440:       PetscLayoutMapLocal(mat->cmap,n,idxs,&ll,&lidxs,&lgidxs);
1441:       ISRestoreIndices(icol,&idxs);
1442:       PetscArrayzero(matis->csf_rootdata,matis->csf->nroots);
1443:       for (i=0;i<ll;i++) matis->csf_rootdata[lidxs[i]] = lgidxs[i]+1;
1444:       PetscFree(lidxs);
1445:       PetscFree(lgidxs);
1446:       PetscSFBcastBegin(matis->csf,MPIU_INT,matis->csf_rootdata,matis->csf_leafdata);
1447:       PetscSFBcastEnd(matis->csf,MPIU_INT,matis->csf_rootdata,matis->csf_leafdata);
1448:       for (i=0,newloc=0;i<matis->csf->nleaves;i++) if (matis->csf_leafdata[i]) newloc++;
1449:       PetscMalloc1(newloc,&newgidxs);
1450:       PetscMalloc1(newloc,&lidxs);
1451:       for (i=0,newloc=0;i<matis->csf->nleaves;i++)
1452:         if (matis->csf_leafdata[i]) {
1453:           lidxs[newloc] = i;
1454:           newgidxs[newloc++] = matis->csf_leafdata[i]-1;
1455:         }
1456:       ISCreateGeneral(comm,newloc,newgidxs,PETSC_OWN_POINTER,&is);
1457:       ISLocalToGlobalMappingCreateIS(is,&cl2g);
1458:       ISLocalToGlobalMappingSetBlockSize(cl2g,cbs);
1459:       ISDestroy(&is);
1460:       /* local is to extract local submatrix */
1461:       ISCreateGeneral(comm,newloc,lidxs,PETSC_OWN_POINTER,&newmatis->getsub_cis);
1462:       MatSetLocalToGlobalMapping(*newmat,rl2g,cl2g);
1463:       ISLocalToGlobalMappingDestroy(&cl2g);
1464:     }
1465:     ISLocalToGlobalMappingDestroy(&rl2g);
1466:   } else {
1467:     MatISGetLocalMat(*newmat,&newlocmat);
1468:   }
1469:   MatISGetLocalMat(mat,&locmat);
1470:   newmatis = (Mat_IS*)(*newmat)->data;
1471:   MatCreateSubMatrix(locmat,newmatis->getsub_ris,newmatis->getsub_cis,scall,&newlocmat);
1472:   if (scall == MAT_INITIAL_MATRIX) {
1473:     MatISSetLocalMat(*newmat,newlocmat);
1474:     MatDestroy(&newlocmat);
1475:   }
1476:   MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
1477:   MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
1478:   return(0);
1479: }

1481: static PetscErrorCode MatCopy_IS(Mat A,Mat B,MatStructure str)
1482: {
1483:   Mat_IS         *a = (Mat_IS*)A->data,*b;
1484:   PetscBool      ismatis;

1488:   PetscObjectTypeCompare((PetscObject)B,MATIS,&ismatis);
1489:   if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_SUP,"Need to be implemented");
1490:   b = (Mat_IS*)B->data;
1491:   MatCopy(a->A,b->A,str);
1492:   PetscObjectStateIncrease((PetscObject)B);
1493:   return(0);
1494: }

1496: static PetscErrorCode MatMissingDiagonal_IS(Mat A,PetscBool  *missing,PetscInt *d)
1497: {
1498:   Vec               v;
1499:   const PetscScalar *array;
1500:   PetscInt          i,n;
1501:   PetscErrorCode    ierr;

1504:   *missing = PETSC_FALSE;
1505:   MatCreateVecs(A,NULL,&v);
1506:   MatGetDiagonal(A,v);
1507:   VecGetLocalSize(v,&n);
1508:   VecGetArrayRead(v,&array);
1509:   for (i=0;i<n;i++) if (array[i] == 0.) break;
1510:   VecRestoreArrayRead(v,&array);
1511:   VecDestroy(&v);
1512:   if (i != n) *missing = PETSC_TRUE;
1513:   if (d) {
1514:     *d = -1;
1515:     if (*missing) {
1516:       PetscInt rstart;
1517:       MatGetOwnershipRange(A,&rstart,NULL);
1518:       *d = i+rstart;
1519:     }
1520:   }
1521:   return(0);
1522: }

1524: static PetscErrorCode MatISSetUpSF_IS(Mat B)
1525: {
1526:   Mat_IS         *matis = (Mat_IS*)(B->data);
1527:   const PetscInt *gidxs;
1528:   PetscInt       nleaves;

1532:   if (matis->sf) return(0);
1533:   PetscSFCreate(PetscObjectComm((PetscObject)B),&matis->sf);
1534:   ISLocalToGlobalMappingGetIndices(B->rmap->mapping,&gidxs);
1535:   ISLocalToGlobalMappingGetSize(B->rmap->mapping,&nleaves);
1536:   PetscSFSetGraphLayout(matis->sf,B->rmap,nleaves,NULL,PETSC_OWN_POINTER,gidxs);
1537:   ISLocalToGlobalMappingRestoreIndices(B->rmap->mapping,&gidxs);
1538:   PetscMalloc2(matis->sf->nroots,&matis->sf_rootdata,matis->sf->nleaves,&matis->sf_leafdata);
1539:   if (B->rmap->mapping != B->cmap->mapping) { /* setup SF for columns */
1540:     ISLocalToGlobalMappingGetSize(B->cmap->mapping,&nleaves);
1541:     PetscSFCreate(PetscObjectComm((PetscObject)B),&matis->csf);
1542:     ISLocalToGlobalMappingGetIndices(B->cmap->mapping,&gidxs);
1543:     PetscSFSetGraphLayout(matis->csf,B->cmap,nleaves,NULL,PETSC_OWN_POINTER,gidxs);
1544:     ISLocalToGlobalMappingRestoreIndices(B->cmap->mapping,&gidxs);
1545:     PetscMalloc2(matis->csf->nroots,&matis->csf_rootdata,matis->csf->nleaves,&matis->csf_leafdata);
1546:   } else {
1547:     matis->csf = matis->sf;
1548:     matis->csf_leafdata = matis->sf_leafdata;
1549:     matis->csf_rootdata = matis->sf_rootdata;
1550:   }
1551:   return(0);
1552: }

1554: /*@
1555:    MatISStoreL2L - Store local-to-local operators during the Galerkin process of MatPtAP.

1557:    Collective

1559:    Input Parameters:
1560: +  A - the matrix
1561: -  store - the boolean flag

1563:    Level: advanced

1565:    Notes:

1567: .seealso: MatCreate(), MatCreateIS(), MatISSetPreallocation(), MatPtAP()
1568: @*/
1569: PetscErrorCode  MatISStoreL2L(Mat A, PetscBool store)
1570: {

1577:   PetscTryMethod(A,"MatISStoreL2L_C",(Mat,PetscBool),(A,store));
1578:   return(0);
1579: }

1581: static PetscErrorCode MatISStoreL2L_IS(Mat A, PetscBool store)
1582: {
1583:   Mat_IS         *matis = (Mat_IS*)(A->data);

1587:   matis->storel2l = store;
1588:   if (!store) {
1589:     PetscObjectCompose((PetscObject)(A),"_MatIS_PtAP_l2l",NULL);
1590:   }
1591:   return(0);
1592: }

1594: /*@
1595:    MatISFixLocalEmpty - Compress out zero local rows from the local matrices

1597:    Collective

1599:    Input Parameters:
1600: +  A - the matrix
1601: -  fix - the boolean flag

1603:    Level: advanced

1605:    Notes: When fix is true, new local matrices and l2g maps are generated during the final assembly process.

1607: .seealso: MatCreate(), MatCreateIS(), MatISSetPreallocation(), MatAssemblyEnd(), MAT_FINAL_ASSEMBLY
1608: @*/
1609: PetscErrorCode  MatISFixLocalEmpty(Mat A, PetscBool fix)
1610: {

1617:   PetscTryMethod(A,"MatISFixLocalEmpty_C",(Mat,PetscBool),(A,fix));
1618:   return(0);
1619: }

1621: static PetscErrorCode MatISFixLocalEmpty_IS(Mat A, PetscBool fix)
1622: {
1623:   Mat_IS *matis = (Mat_IS*)(A->data);

1626:   matis->locempty = fix;
1627:   return(0);
1628: }

1630: /*@
1631:    MatISSetPreallocation - Preallocates memory for a MATIS parallel matrix.

1633:    Collective

1635:    Input Parameters:
1636: +  B - the matrix
1637: .  d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
1638:            (same value is used for all local rows)
1639: .  d_nnz - array containing the number of nonzeros in the various rows of the
1640:            DIAGONAL portion of the local submatrix (possibly different for each row)
1641:            or NULL, if d_nz is used to specify the nonzero structure.
1642:            The size of this array is equal to the number of local rows, i.e 'm'.
1643:            For matrices that will be factored, you must leave room for (and set)
1644:            the diagonal entry even if it is zero.
1645: .  o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
1646:            submatrix (same value is used for all local rows).
1647: -  o_nnz - array containing the number of nonzeros in the various rows of the
1648:            OFF-DIAGONAL portion of the local submatrix (possibly different for
1649:            each row) or NULL, if o_nz is used to specify the nonzero
1650:            structure. The size of this array is equal to the number
1651:            of local rows, i.e 'm'.

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

1655:    Level: intermediate

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

1662: .seealso: MatCreate(), MatCreateIS(), MatMPIAIJSetPreallocation(), MatISGetLocalMat(), MATIS
1663: @*/
1664: PetscErrorCode  MatISSetPreallocation(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
1665: {

1671:   PetscTryMethod(B,"MatISSetPreallocation_C",(Mat,PetscInt,const PetscInt[],PetscInt,const PetscInt[]),(B,d_nz,d_nnz,o_nz,o_nnz));
1672:   return(0);
1673: }

1675: /* this is used by DMDA */
1676: PETSC_EXTERN PetscErrorCode  MatISSetPreallocation_IS(Mat B,PetscInt d_nz,const PetscInt d_nnz[],PetscInt o_nz,const PetscInt o_nnz[])
1677: {
1678:   Mat_IS         *matis = (Mat_IS*)(B->data);
1679:   PetscInt       bs,i,nlocalcols;

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

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

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

1691:   PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
1692:   MatGetSize(matis->A,NULL,&nlocalcols);
1693:   MatGetBlockSize(matis->A,&bs);
1694:   PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);

1696:   for (i=0;i<matis->sf->nleaves;i++) matis->sf_leafdata[i] = PetscMin(matis->sf_leafdata[i],nlocalcols);
1697:   MatSeqAIJSetPreallocation(matis->A,0,matis->sf_leafdata);
1698: #if defined(PETSC_HAVE_HYPRE)
1699:   MatHYPRESetPreallocation(matis->A,0,matis->sf_leafdata,0,NULL);
1700: #endif

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

1705:   nlocalcols /= bs;
1706:   for (i=0;i<matis->sf->nleaves/bs;i++) matis->sf_leafdata[i] = PetscMin(matis->sf_leafdata[i],nlocalcols - i);
1707:   MatSeqSBAIJSetPreallocation(matis->A,bs,0,matis->sf_leafdata);

1709:   /* for other matrix types */
1710:   MatSetUp(matis->A);
1711:   return(0);
1712: }

1714: PETSC_EXTERN PetscErrorCode MatISSetMPIXAIJPreallocation_Private(Mat A, Mat B, PetscBool maxreduce)
1715: {
1716:   Mat_IS          *matis = (Mat_IS*)(A->data);
1717:   PetscInt        *my_dnz,*my_onz,*dnz,*onz,*mat_ranges,*row_ownership;
1718:   const PetscInt  *global_indices_r,*global_indices_c;
1719:   PetscInt        i,j,bs,rows,cols;
1720:   PetscInt        lrows,lcols;
1721:   PetscInt        local_rows,local_cols;
1722:   PetscMPIInt     size;
1723:   PetscBool       isdense,issbaij;
1724:   PetscErrorCode  ierr;

1727:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
1728:   MatGetSize(A,&rows,&cols);
1729:   MatGetBlockSize(A,&bs);
1730:   MatGetSize(matis->A,&local_rows,&local_cols);
1731:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQDENSE,&isdense);
1732:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQSBAIJ,&issbaij);
1733:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&global_indices_r);
1734:   if (A->rmap->mapping != A->cmap->mapping) {
1735:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&global_indices_c);
1736:   } else {
1737:     global_indices_c = global_indices_r;
1738:   }

1740:   if (issbaij) {
1741:     MatGetRowUpperTriangular(matis->A);
1742:   }
1743:   /*
1744:      An SF reduce is needed to sum up properly on shared rows.
1745:      Note that generally preallocation is not exact, since it overestimates nonzeros
1746:   */
1747:   MatGetLocalSize(A,&lrows,&lcols);
1748:   MatPreallocateInitialize(PetscObjectComm((PetscObject)A),lrows,lcols,dnz,onz);
1749:   /* All processes need to compute entire row ownership */
1750:   PetscMalloc1(rows,&row_ownership);
1751:   MatGetOwnershipRanges(A,(const PetscInt**)&mat_ranges);
1752:   for (i=0;i<size;i++) {
1753:     for (j=mat_ranges[i];j<mat_ranges[i+1];j++) {
1754:       row_ownership[j] = i;
1755:     }
1756:   }
1757:   MatGetOwnershipRangesColumn(A,(const PetscInt**)&mat_ranges);

1759:   /*
1760:      my_dnz and my_onz contains exact contribution to preallocation from each local mat
1761:      then, they will be summed up properly. This way, preallocation is always sufficient
1762:   */
1763:   PetscCalloc2(local_rows,&my_dnz,local_rows,&my_onz);
1764:   /* preallocation as a MATAIJ */
1765:   if (isdense) { /* special case for dense local matrices */
1766:     for (i=0;i<local_rows;i++) {
1767:       PetscInt owner = row_ownership[global_indices_r[i]];
1768:       for (j=0;j<local_cols;j++) {
1769:         PetscInt index_col = global_indices_c[j];
1770:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1771:           my_dnz[i] += 1;
1772:         } else { /* offdiag block */
1773:           my_onz[i] += 1;
1774:         }
1775:       }
1776:     }
1777:   } else if (matis->A->ops->getrowij) {
1778:     const PetscInt *ii,*jj,*jptr;
1779:     PetscBool      done;
1780:     MatGetRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&local_rows,&ii,&jj,&done);
1781:     if (!done) SETERRQ(PetscObjectComm((PetscObject)(matis->A)),PETSC_ERR_PLIB,"Error in MatGetRowIJ");
1782:     jptr = jj;
1783:     for (i=0;i<local_rows;i++) {
1784:       PetscInt index_row = global_indices_r[i];
1785:       for (j=0;j<ii[i+1]-ii[i];j++,jptr++) {
1786:         PetscInt owner = row_ownership[index_row];
1787:         PetscInt index_col = global_indices_c[*jptr];
1788:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1789:           my_dnz[i] += 1;
1790:         } else { /* offdiag block */
1791:           my_onz[i] += 1;
1792:         }
1793:         /* same as before, interchanging rows and cols */
1794:         if (issbaij && index_col != index_row) {
1795:           owner = row_ownership[index_col];
1796:           if (index_row > mat_ranges[owner]-1 && index_row < mat_ranges[owner+1] ) {
1797:             my_dnz[*jptr] += 1;
1798:           } else {
1799:             my_onz[*jptr] += 1;
1800:           }
1801:         }
1802:       }
1803:     }
1804:     MatRestoreRowIJ(matis->A,0,PETSC_FALSE,PETSC_FALSE,&local_rows,&ii,&jj,&done);
1805:     if (!done) SETERRQ(PetscObjectComm((PetscObject)(matis->A)),PETSC_ERR_PLIB,"Error in MatRestoreRowIJ");
1806:   } else { /* loop over rows and use MatGetRow */
1807:     for (i=0;i<local_rows;i++) {
1808:       const PetscInt *cols;
1809:       PetscInt       ncols,index_row = global_indices_r[i];
1810:       MatGetRow(matis->A,i,&ncols,&cols,NULL);
1811:       for (j=0;j<ncols;j++) {
1812:         PetscInt owner = row_ownership[index_row];
1813:         PetscInt index_col = global_indices_c[cols[j]];
1814:         if (index_col > mat_ranges[owner]-1 && index_col < mat_ranges[owner+1] ) { /* diag block */
1815:           my_dnz[i] += 1;
1816:         } else { /* offdiag block */
1817:           my_onz[i] += 1;
1818:         }
1819:         /* same as before, interchanging rows and cols */
1820:         if (issbaij && index_col != index_row) {
1821:           owner = row_ownership[index_col];
1822:           if (index_row > mat_ranges[owner]-1 && index_row < mat_ranges[owner+1] ) {
1823:             my_dnz[cols[j]] += 1;
1824:           } else {
1825:             my_onz[cols[j]] += 1;
1826:           }
1827:         }
1828:       }
1829:       MatRestoreRow(matis->A,i,&ncols,&cols,NULL);
1830:     }
1831:   }
1832:   if (global_indices_c != global_indices_r) {
1833:     ISLocalToGlobalMappingRestoreIndices(A->cmap->mapping,&global_indices_c);
1834:   }
1835:   ISLocalToGlobalMappingRestoreIndices(A->rmap->mapping,&global_indices_r);
1836:   PetscFree(row_ownership);

1838:   /* Reduce my_dnz and my_onz */
1839:   if (maxreduce) {
1840:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_dnz,dnz,MPI_MAX);
1841:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_onz,onz,MPI_MAX);
1842:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_dnz,dnz,MPI_MAX);
1843:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_onz,onz,MPI_MAX);
1844:   } else {
1845:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_dnz,dnz,MPI_SUM);
1846:     PetscSFReduceBegin(matis->sf,MPIU_INT,my_onz,onz,MPI_SUM);
1847:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_dnz,dnz,MPI_SUM);
1848:     PetscSFReduceEnd(matis->sf,MPIU_INT,my_onz,onz,MPI_SUM);
1849:   }
1850:   PetscFree2(my_dnz,my_onz);

1852:   /* Resize preallocation if overestimated */
1853:   for (i=0;i<lrows;i++) {
1854:     dnz[i] = PetscMin(dnz[i],lcols);
1855:     onz[i] = PetscMin(onz[i],cols-lcols);
1856:   }

1858:   /* Set preallocation */
1859:   MatSeqAIJSetPreallocation(B,0,dnz);
1860:   MatMPIAIJSetPreallocation(B,0,dnz,0,onz);
1861:   for (i=0;i<lrows;i+=bs) {
1862:     PetscInt b, d = dnz[i],o = onz[i];

1864:     for (b=1;b<bs;b++) {
1865:       d = PetscMax(d,dnz[i+b]);
1866:       o = PetscMax(o,onz[i+b]);
1867:     }
1868:     dnz[i/bs] = PetscMin(d/bs + d%bs,lcols/bs);
1869:     onz[i/bs] = PetscMin(o/bs + o%bs,(cols-lcols)/bs);
1870:   }
1871:   MatSeqBAIJSetPreallocation(B,bs,0,dnz);
1872:   MatMPIBAIJSetPreallocation(B,bs,0,dnz,0,onz);
1873:   MatMPISBAIJSetPreallocation(B,bs,0,dnz,0,onz);
1874:   MatPreallocateFinalize(dnz,onz);
1875:   if (issbaij) {
1876:     MatRestoreRowUpperTriangular(matis->A);
1877:   }
1878:   MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_TRUE);
1879:   return(0);
1880: }

1882: PETSC_INTERN PetscErrorCode MatConvert_IS_XAIJ(Mat mat, MatType mtype, MatReuse reuse, Mat *M)
1883: {
1884:   Mat_IS            *matis = (Mat_IS*)(mat->data);
1885:   Mat               local_mat,MT;
1886:   PetscInt          rbs,cbs,rows,cols,lrows,lcols;
1887:   PetscInt          local_rows,local_cols;
1888:   PetscBool         isseqdense,isseqsbaij,isseqaij,isseqbaij;
1889: #if defined (PETSC_USE_DEBUG)
1890:   PetscBool         lb[4],bb[4];
1891: #endif
1892:   PetscMPIInt       size;
1893:   const PetscScalar *array;
1894:   PetscErrorCode    ierr;

1897:   MPI_Comm_size(PetscObjectComm((PetscObject)mat),&size);
1898:   if (size == 1 && mat->rmap->N == matis->A->rmap->N && mat->cmap->N == matis->A->cmap->N) {
1899:     Mat      B;
1900:     IS       irows = NULL,icols = NULL;
1901:     PetscInt rbs,cbs;

1903:     ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&rbs);
1904:     ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&cbs);
1905:     if (reuse != MAT_REUSE_MATRIX) { /* check if l2g maps are one-to-one */
1906:       IS             rows,cols;
1907:       const PetscInt *ridxs,*cidxs;
1908:       PetscInt       i,nw,*work;

1910:       ISLocalToGlobalMappingGetBlockIndices(mat->rmap->mapping,&ridxs);
1911:       ISLocalToGlobalMappingGetSize(mat->rmap->mapping,&nw);
1912:       nw   = nw/rbs;
1913:       PetscCalloc1(nw,&work);
1914:       for (i=0;i<nw;i++) work[ridxs[i]] += 1;
1915:       for (i=0;i<nw;i++) if (!work[i] || work[i] > 1) break;
1916:       if (i == nw) {
1917:         ISCreateBlock(PETSC_COMM_SELF,rbs,nw,ridxs,PETSC_USE_POINTER,&rows);
1918:         ISSetPermutation(rows);
1919:         ISInvertPermutation(rows,PETSC_DECIDE,&irows);
1920:         ISDestroy(&rows);
1921:       }
1922:       ISLocalToGlobalMappingRestoreBlockIndices(mat->rmap->mapping,&ridxs);
1923:       PetscFree(work);
1924:       if (irows && mat->rmap->mapping != mat->cmap->mapping) {
1925:         ISLocalToGlobalMappingGetBlockIndices(mat->cmap->mapping,&cidxs);
1926:         ISLocalToGlobalMappingGetSize(mat->cmap->mapping,&nw);
1927:         nw   = nw/cbs;
1928:         PetscCalloc1(nw,&work);
1929:         for (i=0;i<nw;i++) work[cidxs[i]] += 1;
1930:         for (i=0;i<nw;i++) if (!work[i] || work[i] > 1) break;
1931:         if (i == nw) {
1932:           ISCreateBlock(PETSC_COMM_SELF,cbs,nw,cidxs,PETSC_USE_POINTER,&cols);
1933:           ISSetPermutation(cols);
1934:           ISInvertPermutation(cols,PETSC_DECIDE,&icols);
1935:           ISDestroy(&cols);
1936:         }
1937:         ISLocalToGlobalMappingRestoreBlockIndices(mat->cmap->mapping,&cidxs);
1938:         PetscFree(work);
1939:       } else if (irows) {
1940:         PetscObjectReference((PetscObject)irows);
1941:         icols = irows;
1942:       }
1943:     } else {
1944:       PetscObjectQuery((PetscObject)(*M),"_MatIS_IS_XAIJ_irows",(PetscObject*)&irows);
1945:       PetscObjectQuery((PetscObject)(*M),"_MatIS_IS_XAIJ_icols",(PetscObject*)&icols);
1946:       if (irows) { PetscObjectReference((PetscObject)irows); }
1947:       if (icols) { PetscObjectReference((PetscObject)icols); }
1948:     }
1949:     if (!irows || !icols) {
1950:       ISDestroy(&icols);
1951:       ISDestroy(&irows);
1952:       goto general_assembly;
1953:     }
1954:     MatConvert(matis->A,(rbs == cbs && rbs > 1) ? MATSEQBAIJ : MATSEQAIJ,MAT_INITIAL_MATRIX,&B);
1955:     if (reuse != MAT_INPLACE_MATRIX) {
1956:       MatCreateSubMatrix(B,irows,icols,reuse,M);
1957:       PetscObjectCompose((PetscObject)(*M),"_MatIS_IS_XAIJ_irows",(PetscObject)irows);
1958:       PetscObjectCompose((PetscObject)(*M),"_MatIS_IS_XAIJ_icols",(PetscObject)icols);
1959:     } else {
1960:       Mat C;

1962:       MatCreateSubMatrix(B,irows,icols,MAT_INITIAL_MATRIX,&C);
1963:       MatHeaderReplace(mat,&C);
1964:     }
1965:     MatDestroy(&B);
1966:     ISDestroy(&icols);
1967:     ISDestroy(&irows);
1968:     return(0);
1969:   }
1970: general_assembly:
1971:   MatGetSize(mat,&rows,&cols);
1972:   ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&rbs);
1973:   ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&cbs);
1974:   MatGetLocalSize(mat,&lrows,&lcols);
1975:   MatGetSize(matis->A,&local_rows,&local_cols);
1976:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQDENSE,&isseqdense);
1977:   PetscObjectBaseTypeCompare((PetscObject)matis->A,MATSEQAIJ,&isseqaij);
1978:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQBAIJ,&isseqbaij);
1979:   PetscObjectTypeCompare((PetscObject)matis->A,MATSEQSBAIJ,&isseqsbaij);
1980:   if (!isseqdense && !isseqaij && !isseqbaij && !isseqsbaij) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"Not for matrix type %s",((PetscObject)(matis->A))->type_name);
1981: #if defined (PETSC_USE_DEBUG)
1982:   lb[0] = isseqdense;
1983:   lb[1] = isseqaij;
1984:   lb[2] = isseqbaij;
1985:   lb[3] = isseqsbaij;
1986:   MPIU_Allreduce(lb,bb,4,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)mat));
1987:   if (!bb[0] && !bb[1] && !bb[2] && !bb[3]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Local matrices must have the same type");
1988: #endif

1990:   if (reuse != MAT_REUSE_MATRIX) {
1991:     MatCreate(PetscObjectComm((PetscObject)mat),&MT);
1992:     MatSetSizes(MT,lrows,lcols,rows,cols);
1993:     MatSetType(MT,mtype);
1994:     MatSetBlockSizes(MT,rbs,cbs);
1995:     MatISSetMPIXAIJPreallocation_Private(mat,MT,PETSC_FALSE);
1996:   } else {
1997:     PetscInt mrbs,mcbs,mrows,mcols,mlrows,mlcols;

1999:     /* some checks */
2000:     MT   = *M;
2001:     MatGetBlockSizes(MT,&mrbs,&mcbs);
2002:     MatGetSize(MT,&mrows,&mcols);
2003:     MatGetLocalSize(MT,&mlrows,&mlcols);
2004:     if (mrows != rows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of rows (%d != %d)",rows,mrows);
2005:     if (mcols != cols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of cols (%d != %d)",cols,mcols);
2006:     if (mlrows != lrows) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of local rows (%d != %d)",lrows,mlrows);
2007:     if (mlcols != lcols) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong number of local cols (%d != %d)",lcols,mlcols);
2008:     if (mrbs != rbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong row block size (%d != %d)",rbs,mrbs);
2009:     if (mcbs != cbs) SETERRQ2(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse matrix. Wrong col block size (%d != %d)",cbs,mcbs);
2010:     MatZeroEntries(MT);
2011:   }

2013:   if (isseqsbaij || isseqbaij) {
2014:     MatConvert(matis->A,MATSEQAIJ,MAT_INITIAL_MATRIX,&local_mat);
2015:     isseqaij = PETSC_TRUE;
2016:   } else {
2017:     PetscObjectReference((PetscObject)matis->A);
2018:     local_mat = matis->A;
2019:   }

2021:   /* Set values */
2022:   MatSetLocalToGlobalMapping(MT,mat->rmap->mapping,mat->cmap->mapping);
2023:   if (isseqdense) { /* special case for dense local matrices */
2024:     PetscInt          i,*dummy;

2026:     PetscMalloc1(PetscMax(local_rows,local_cols),&dummy);
2027:     for (i=0;i<PetscMax(local_rows,local_cols);i++) dummy[i] = i;
2028:     MatSetOption(MT,MAT_ROW_ORIENTED,PETSC_FALSE);
2029:     MatDenseGetArrayRead(local_mat,&array);
2030:     MatSetValuesLocal(MT,local_rows,dummy,local_cols,dummy,array,ADD_VALUES);
2031:     MatDenseRestoreArrayRead(local_mat,&array);
2032:     PetscFree(dummy);
2033:   } else if (isseqaij) {
2034:     const PetscInt *blocks;
2035:     PetscInt       i,nvtxs,*xadj,*adjncy, nb;
2036:     PetscBool      done;
2037:     PetscScalar    *sarray;

2039:     MatGetRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
2040:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatGetRowIJ");
2041:     MatSeqAIJGetArray(local_mat,&sarray);
2042:     MatGetVariableBlockSizes(local_mat,&nb,&blocks);
2043:     if (nb) { /* speed up assembly for special blocked matrices (used by BDDC) */
2044:       PetscInt sum;

2046:       for (i=0,sum=0;i<nb;i++) sum += blocks[i];
2047:       if (sum == nvtxs) {
2048:         PetscInt r;

2050:         for (i=0,r=0;i<nb;i++) {
2051:           if (blocks[i] != xadj[r+1] - xadj[r]) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Invalid block sizes prescribed for block %D: expected %D, got %D",i,blocks[i],xadj[r+1] - xadj[r]);
2052:           MatSetValuesLocal(MT,blocks[i],adjncy+xadj[r],blocks[i],adjncy+xadj[r],sarray+xadj[r],ADD_VALUES);
2053:           r   += blocks[i];
2054:         }
2055:       } else {
2056:         for (i=0;i<nvtxs;i++) {
2057:           MatSetValuesLocal(MT,1,&i,xadj[i+1]-xadj[i],adjncy+xadj[i],sarray+xadj[i],ADD_VALUES);
2058:         }
2059:       }
2060:     } else {
2061:       for (i=0;i<nvtxs;i++) {
2062:         MatSetValuesLocal(MT,1,&i,xadj[i+1]-xadj[i],adjncy+xadj[i],sarray+xadj[i],ADD_VALUES);
2063:       }
2064:     }
2065:     MatRestoreRowIJ(local_mat,0,PETSC_FALSE,PETSC_FALSE,&nvtxs,(const PetscInt**)&xadj,(const PetscInt**)&adjncy,&done);
2066:     if (!done) SETERRQ(PetscObjectComm((PetscObject)local_mat),PETSC_ERR_PLIB,"Error in MatRestoreRowIJ");
2067:     MatSeqAIJRestoreArray(local_mat,&sarray);
2068:   } else { /* very basic values insertion for all other matrix types */
2069:     PetscInt i;

2071:     for (i=0;i<local_rows;i++) {
2072:       PetscInt       j;
2073:       const PetscInt *local_indices_cols;

2075:       MatGetRow(local_mat,i,&j,&local_indices_cols,&array);
2076:       MatSetValuesLocal(MT,1,&i,j,local_indices_cols,array,ADD_VALUES);
2077:       MatRestoreRow(local_mat,i,&j,&local_indices_cols,&array);
2078:     }
2079:   }
2080:   MatAssemblyBegin(MT,MAT_FINAL_ASSEMBLY);
2081:   MatDestroy(&local_mat);
2082:   MatAssemblyEnd(MT,MAT_FINAL_ASSEMBLY);
2083:   if (isseqdense) {
2084:     MatSetOption(MT,MAT_ROW_ORIENTED,PETSC_TRUE);
2085:   }
2086:   if (reuse == MAT_INPLACE_MATRIX) {
2087:     MatHeaderReplace(mat,&MT);
2088:   } else if (reuse == MAT_INITIAL_MATRIX) {
2089:     *M = MT;
2090:   }
2091:   return(0);
2092: }

2094: /*@
2095:     MatISGetMPIXAIJ - Converts MATIS matrix into a parallel AIJ format

2097:   Input Parameter:
2098: .  mat - the matrix (should be of type MATIS)
2099: .  reuse - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX

2101:   Output Parameter:
2102: .  newmat - the matrix in AIJ format

2104:   Level: developer

2106:   Notes:
2107:     This function has been deprecated and it will be removed in future releases. Update your code to use the MatConvert() interface.

2109: .seealso: MATIS, MatConvert()
2110: @*/
2111: PetscErrorCode MatISGetMPIXAIJ(Mat mat, MatReuse reuse, Mat *newmat)
2112: {

2119:   if (reuse == MAT_REUSE_MATRIX) {
2122:     if (mat == *newmat) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_SUP,"Cannot reuse the same matrix");
2123:   }
2124:   PetscUseMethod(mat,"MatISGetMPIXAIJ_C",(Mat,MatType,MatReuse,Mat*),(mat,MATAIJ,reuse,newmat));
2125:   return(0);
2126: }

2128: PetscErrorCode MatDuplicate_IS(Mat mat,MatDuplicateOption op,Mat *newmat)
2129: {
2131:   Mat_IS         *matis = (Mat_IS*)(mat->data);
2132:   PetscInt       rbs,cbs,m,n,M,N;
2133:   Mat            B,localmat;

2136:   ISLocalToGlobalMappingGetBlockSize(mat->rmap->mapping,&rbs);
2137:   ISLocalToGlobalMappingGetBlockSize(mat->cmap->mapping,&cbs);
2138:   MatGetSize(mat,&M,&N);
2139:   MatGetLocalSize(mat,&m,&n);
2140:   MatCreate(PetscObjectComm((PetscObject)mat),&B);
2141:   MatSetSizes(B,m,n,M,N);
2142:   MatSetBlockSize(B,rbs == cbs ? rbs : 1);
2143:   MatSetType(B,MATIS);
2144:   MatISSetLocalMatType(B,matis->lmattype);
2145:   MatSetLocalToGlobalMapping(B,mat->rmap->mapping,mat->cmap->mapping);
2146:   MatDuplicate(matis->A,op,&localmat);
2147:   MatISSetLocalMat(B,localmat);
2148:   MatDestroy(&localmat);
2149:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
2150:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
2151:   *newmat = B;
2152:   return(0);
2153: }

2155: static PetscErrorCode MatIsHermitian_IS(Mat A,PetscReal tol,PetscBool  *flg)
2156: {
2158:   Mat_IS         *matis = (Mat_IS*)A->data;
2159:   PetscBool      local_sym;

2162:   MatIsHermitian(matis->A,tol,&local_sym);
2163:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2164:   return(0);
2165: }

2167: static PetscErrorCode MatIsSymmetric_IS(Mat A,PetscReal tol,PetscBool  *flg)
2168: {
2170:   Mat_IS         *matis = (Mat_IS*)A->data;
2171:   PetscBool      local_sym;

2174:   MatIsSymmetric(matis->A,tol,&local_sym);
2175:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2176:   return(0);
2177: }

2179: static PetscErrorCode MatIsStructurallySymmetric_IS(Mat A,PetscBool  *flg)
2180: {
2182:   Mat_IS         *matis = (Mat_IS*)A->data;
2183:   PetscBool      local_sym;

2186:   if (A->rmap->mapping != A->cmap->mapping) {
2187:     *flg = PETSC_FALSE;
2188:     return(0);
2189:   }
2190:   MatIsStructurallySymmetric(matis->A,&local_sym);
2191:   MPIU_Allreduce(&local_sym,flg,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2192:   return(0);
2193: }

2195: static PetscErrorCode MatDestroy_IS(Mat A)
2196: {
2198:   Mat_IS         *b = (Mat_IS*)A->data;

2201:   PetscFree(b->bdiag);
2202:   PetscFree(b->lmattype);
2203:   MatDestroy(&b->A);
2204:   VecScatterDestroy(&b->cctx);
2205:   VecScatterDestroy(&b->rctx);
2206:   VecDestroy(&b->x);
2207:   VecDestroy(&b->y);
2208:   VecDestroy(&b->counter);
2209:   ISDestroy(&b->getsub_ris);
2210:   ISDestroy(&b->getsub_cis);
2211:   if (b->sf != b->csf) {
2212:     PetscSFDestroy(&b->csf);
2213:     PetscFree2(b->csf_rootdata,b->csf_leafdata);
2214:   } else b->csf = NULL;
2215:   PetscSFDestroy(&b->sf);
2216:   PetscFree2(b->sf_rootdata,b->sf_leafdata);
2217:   PetscFree(A->data);
2218:   PetscObjectChangeTypeName((PetscObject)A,0);
2219:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMatType_C",NULL);
2220:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",NULL);
2221:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",NULL);
2222:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",NULL);
2223:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",NULL);
2224:   PetscObjectComposeFunction((PetscObject)A,"MatISStoreL2L_C",NULL);
2225:   PetscObjectComposeFunction((PetscObject)A,"MatISFixLocalEmpty_C",NULL);
2226:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpiaij_C",NULL);
2227:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpibaij_C",NULL);
2228:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpisbaij_C",NULL);
2229:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqaij_C",NULL);
2230:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqbaij_C",NULL);
2231:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqsbaij_C",NULL);
2232:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_aij_C",NULL);
2233:   return(0);
2234: }

2236: static PetscErrorCode MatMult_IS(Mat A,Vec x,Vec y)
2237: {
2239:   Mat_IS         *is  = (Mat_IS*)A->data;
2240:   PetscScalar    zero = 0.0;

2243:   /*  scatter the global vector x into the local work vector */
2244:   VecScatterBegin(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);
2245:   VecScatterEnd(is->cctx,x,is->x,INSERT_VALUES,SCATTER_FORWARD);

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

2250:   /* scatter product back into global memory */
2251:   VecSet(y,zero);
2252:   VecScatterBegin(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
2253:   VecScatterEnd(is->rctx,is->y,y,ADD_VALUES,SCATTER_REVERSE);
2254:   return(0);
2255: }

2257: static PetscErrorCode MatMultAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
2258: {
2259:   Vec            temp_vec;

2263:   if (v3 != v2) {
2264:     MatMult(A,v1,v3);
2265:     VecAXPY(v3,1.0,v2);
2266:   } else {
2267:     VecDuplicate(v2,&temp_vec);
2268:     MatMult(A,v1,temp_vec);
2269:     VecAXPY(temp_vec,1.0,v2);
2270:     VecCopy(temp_vec,v3);
2271:     VecDestroy(&temp_vec);
2272:   }
2273:   return(0);
2274: }

2276: static PetscErrorCode MatMultTranspose_IS(Mat A,Vec y,Vec x)
2277: {
2278:   Mat_IS         *is = (Mat_IS*)A->data;

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

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

2289:   /* scatter product back into global vector */
2290:   VecSet(x,0);
2291:   VecScatterBegin(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
2292:   VecScatterEnd(is->cctx,is->x,x,ADD_VALUES,SCATTER_REVERSE);
2293:   return(0);
2294: }

2296: static PetscErrorCode MatMultTransposeAdd_IS(Mat A,Vec v1,Vec v2,Vec v3)
2297: {
2298:   Vec            temp_vec;

2302:   if (v3 != v2) {
2303:     MatMultTranspose(A,v1,v3);
2304:     VecAXPY(v3,1.0,v2);
2305:   } else {
2306:     VecDuplicate(v2,&temp_vec);
2307:     MatMultTranspose(A,v1,temp_vec);
2308:     VecAXPY(temp_vec,1.0,v2);
2309:     VecCopy(temp_vec,v3);
2310:     VecDestroy(&temp_vec);
2311:   }
2312:   return(0);
2313: }

2315: static PetscErrorCode MatView_IS(Mat A,PetscViewer viewer)
2316: {
2317:   Mat_IS         *a = (Mat_IS*)A->data;
2319:   PetscViewer    sviewer;
2320:   PetscBool      isascii,view = PETSC_TRUE;

2323:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
2324:   if (isascii)  {
2325:     PetscViewerFormat format;

2327:     PetscViewerGetFormat(viewer,&format);
2328:     if (format == PETSC_VIEWER_ASCII_INFO) view = PETSC_FALSE;
2329:   }
2330:   if (!view) return(0);
2331:   PetscViewerGetSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
2332:   MatView(a->A,sviewer);
2333:   PetscViewerRestoreSubViewer(viewer,PETSC_COMM_SELF,&sviewer);
2334:   PetscViewerFlush(viewer);
2335:   return(0);
2336: }

2338: static PetscErrorCode MatInvertBlockDiagonal_IS(Mat mat,const PetscScalar **values)
2339: {
2340:   Mat_IS            *is = (Mat_IS*)mat->data;
2341:   MPI_Datatype      nodeType;
2342:   const PetscScalar *lv;
2343:   PetscInt          bs;
2344:   PetscErrorCode    ierr;

2347:   MatGetBlockSize(mat,&bs);
2348:   MatSetBlockSize(is->A,bs);
2349:   MatInvertBlockDiagonal(is->A,&lv);
2350:   if (!is->bdiag) {
2351:     PetscMalloc1(bs*mat->rmap->n,&is->bdiag);
2352:   }
2353:   MPI_Type_contiguous(bs,MPIU_SCALAR,&nodeType);
2354:   MPI_Type_commit(&nodeType);
2355:   PetscSFReduceBegin(is->sf,nodeType,lv,is->bdiag,MPIU_REPLACE);
2356:   PetscSFReduceEnd(is->sf,nodeType,lv,is->bdiag,MPIU_REPLACE);
2357:   MPI_Type_free(&nodeType);
2358:   if (values) *values = is->bdiag;
2359:   return(0);
2360: }

2362: static PetscErrorCode MatISSetUpScatters_Private(Mat A)
2363: {
2364:   Vec            cglobal,rglobal;
2365:   IS             from;
2366:   Mat_IS         *is = (Mat_IS*)A->data;
2367:   PetscScalar    sum;
2368:   const PetscInt *garray;
2369:   PetscInt       nr,rbs,nc,cbs;
2370:   PetscBool      iscuda;

2374:   ISLocalToGlobalMappingGetSize(A->rmap->mapping,&nr);
2375:   ISLocalToGlobalMappingGetBlockSize(A->rmap->mapping,&rbs);
2376:   ISLocalToGlobalMappingGetSize(A->cmap->mapping,&nc);
2377:   ISLocalToGlobalMappingGetBlockSize(A->cmap->mapping,&cbs);
2378:   VecDestroy(&is->x);
2379:   VecDestroy(&is->y);
2380:   VecDestroy(&is->counter);
2381:   VecScatterDestroy(&is->rctx);
2382:   VecScatterDestroy(&is->cctx);
2383:   MatCreateVecs(is->A,&is->x,&is->y);
2384:   PetscObjectTypeCompare((PetscObject)is->y,VECSEQCUDA,&iscuda);
2385:   if (iscuda) {
2386:     PetscFree(A->defaultvectype);
2387:     PetscStrallocpy(VECCUDA,&A->defaultvectype);
2388:   }
2389:   MatCreateVecs(A,&cglobal,&rglobal);
2390:   ISLocalToGlobalMappingGetBlockIndices(A->rmap->mapping,&garray);
2391:   ISCreateBlock(PetscObjectComm((PetscObject)A),rbs,nr/rbs,garray,PETSC_USE_POINTER,&from);
2392:   VecScatterCreate(rglobal,from,is->y,NULL,&is->rctx);
2393:   ISLocalToGlobalMappingRestoreBlockIndices(A->rmap->mapping,&garray);
2394:   ISDestroy(&from);
2395:   if (A->rmap->mapping != A->cmap->mapping) {
2396:     ISLocalToGlobalMappingGetBlockIndices(A->cmap->mapping,&garray);
2397:     ISCreateBlock(PetscObjectComm((PetscObject)A),cbs,nc/cbs,garray,PETSC_USE_POINTER,&from);
2398:     VecScatterCreate(cglobal,from,is->x,NULL,&is->cctx);
2399:     ISLocalToGlobalMappingRestoreBlockIndices(A->cmap->mapping,&garray);
2400:     ISDestroy(&from);
2401:   } else {
2402:     PetscObjectReference((PetscObject)is->rctx);
2403:     is->cctx = is->rctx;
2404:   }
2405:   VecDestroy(&cglobal);

2407:   /* interface counter vector (local) */
2408:   VecDuplicate(is->y,&is->counter);
2409:   VecSet(is->y,1.);
2410:   VecScatterBegin(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
2411:   VecScatterEnd(is->rctx,is->y,rglobal,ADD_VALUES,SCATTER_REVERSE);
2412:   VecScatterBegin(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);
2413:   VecScatterEnd(is->rctx,rglobal,is->counter,INSERT_VALUES,SCATTER_FORWARD);

2415:   /* special functions for block-diagonal matrices */
2416:   VecSum(rglobal,&sum);
2417:   if ((PetscInt)(PetscRealPart(sum)) == A->rmap->N && A->rmap->N == A->cmap->N && A->rmap->mapping == A->cmap->mapping) {
2418:     A->ops->invertblockdiagonal = MatInvertBlockDiagonal_IS;
2419:   } else {
2420:     A->ops->invertblockdiagonal = NULL;
2421:   }
2422:   VecDestroy(&rglobal);

2424:   /* setup SF for general purpose shared indices based communications */
2425:   MatISSetUpSF_IS(A);
2426:   return(0);
2427: }

2429: static PetscErrorCode MatSetLocalToGlobalMapping_IS(Mat A,ISLocalToGlobalMapping rmapping,ISLocalToGlobalMapping cmapping)
2430: {
2432:   PetscInt       nr,rbs,nc,cbs;
2433:   Mat_IS         *is = (Mat_IS*)A->data;

2438:   MatDestroy(&is->A);
2439:   if (is->csf != is->sf) {
2440:     PetscSFDestroy(&is->csf);
2441:     PetscFree2(is->csf_rootdata,is->csf_leafdata);
2442:   } else is->csf = NULL;
2443:   PetscSFDestroy(&is->sf);
2444:   PetscFree2(is->sf_rootdata,is->sf_leafdata);
2445:   PetscFree(is->bdiag);

2447:   /* Setup Layout and set local to global maps */
2448:   PetscLayoutSetUp(A->rmap);
2449:   PetscLayoutSetUp(A->cmap);
2450:   ISLocalToGlobalMappingGetSize(rmapping,&nr);
2451:   ISLocalToGlobalMappingGetBlockSize(rmapping,&rbs);
2452:   ISLocalToGlobalMappingGetSize(cmapping,&nc);
2453:   ISLocalToGlobalMappingGetBlockSize(cmapping,&cbs);
2454:   /* check if the two mappings are actually the same for square matrices (DOLFIN passes 2 different objects) */
2455:   if (rmapping != cmapping && A->rmap->N == A->cmap->N) {
2456:     PetscBool same,gsame;

2458:     same = PETSC_FALSE;
2459:     if (nr == nc && cbs == rbs) {
2460:       const PetscInt *idxs1,*idxs2;

2462:       ISLocalToGlobalMappingGetBlockIndices(rmapping,&idxs1);
2463:       ISLocalToGlobalMappingGetBlockIndices(cmapping,&idxs2);
2464:       PetscArraycmp(idxs1,idxs2,nr/rbs,&same);
2465:       ISLocalToGlobalMappingRestoreBlockIndices(rmapping,&idxs1);
2466:       ISLocalToGlobalMappingRestoreBlockIndices(cmapping,&idxs2);
2467:     }
2468:     MPIU_Allreduce(&same,&gsame,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)A));
2469:     if (gsame) cmapping = rmapping;
2470:   }
2471:   PetscLayoutSetBlockSize(A->rmap,rbs);
2472:   PetscLayoutSetBlockSize(A->cmap,cbs);
2473:   PetscLayoutSetISLocalToGlobalMapping(A->rmap,rmapping);
2474:   PetscLayoutSetISLocalToGlobalMapping(A->cmap,cmapping);

2476:   /* Create the local matrix A */
2477:   MatCreate(PETSC_COMM_SELF,&is->A);
2478:   MatSetType(is->A,is->lmattype);
2479:   MatSetSizes(is->A,nr,nc,nr,nc);
2480:   MatSetBlockSizes(is->A,rbs,cbs);
2481:   MatSetOptionsPrefix(is->A,"is_");
2482:   MatAppendOptionsPrefix(is->A,((PetscObject)A)->prefix);
2483:   PetscLayoutSetUp(is->A->rmap);
2484:   PetscLayoutSetUp(is->A->cmap);

2486:   if (!is->islocalref) { /* setup scatters and local vectors for MatMult */
2487:     MatISSetUpScatters_Private(A);
2488:   }
2489:   MatSetUp(A);
2490:   return(0);
2491: }

2493: static PetscErrorCode MatSetValues_IS(Mat mat, PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols, const PetscScalar *values, InsertMode addv)
2494: {
2495:   Mat_IS         *is = (Mat_IS*)mat->data;
2497: #if defined(PETSC_USE_DEBUG)
2498:   PetscInt       i,zm,zn;
2499: #endif
2500:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

2503: #if defined(PETSC_USE_DEBUG)
2504:   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);
2505:   /* count negative indices */
2506:   for (i=0,zm=0;i<m;i++) if (rows[i] < 0) zm++;
2507:   for (i=0,zn=0;i<n;i++) if (cols[i] < 0) zn++;
2508: #endif
2509:   ISGlobalToLocalMappingApply(mat->rmap->mapping,IS_GTOLM_MASK,m,rows,&m,rows_l);
2510:   ISGlobalToLocalMappingApply(mat->cmap->mapping,IS_GTOLM_MASK,n,cols,&n,cols_l);
2511: #if defined(PETSC_USE_DEBUG)
2512:   /* count negative indices (should be the same as before) */
2513:   for (i=0;i<m;i++) if (rows_l[i] < 0) zm--;
2514:   for (i=0;i<n;i++) if (cols_l[i] < 0) zn--;
2515:   if (!is->A->rmap->mapping && zm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the row indices can not be mapped! Maybe you should not use MATIS");
2516:   if (!is->A->cmap->mapping && zn) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the column indices can not be mapped! Maybe you should not use MATIS");
2517: #endif
2518:   MatSetValues(is->A,m,rows_l,n,cols_l,values,addv);
2519:   return(0);
2520: }

2522: static PetscErrorCode MatSetValuesBlocked_IS(Mat mat, PetscInt m,const PetscInt *rows, PetscInt n,const PetscInt *cols, const PetscScalar *values, InsertMode addv)
2523: {
2524:   Mat_IS         *is = (Mat_IS*)mat->data;
2526: #if defined(PETSC_USE_DEBUG)
2527:   PetscInt       i,zm,zn;
2528: #endif
2529:   PetscInt       rows_l[MATIS_MAX_ENTRIES_INSERTION],cols_l[MATIS_MAX_ENTRIES_INSERTION];

2532: #if defined(PETSC_USE_DEBUG)
2533:   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);
2534:   /* count negative indices */
2535:   for (i=0,zm=0;i<m;i++) if (rows[i] < 0) zm++;
2536:   for (i=0,zn=0;i<n;i++) if (cols[i] < 0) zn++;
2537: #endif
2538:   ISGlobalToLocalMappingApplyBlock(mat->rmap->mapping,IS_GTOLM_MASK,m,rows,&m,rows_l);
2539:   ISGlobalToLocalMappingApplyBlock(mat->cmap->mapping,IS_GTOLM_MASK,n,cols,&n,cols_l);
2540: #if defined(PETSC_USE_DEBUG)
2541:   /* count negative indices (should be the same as before) */
2542:   for (i=0;i<m;i++) if (rows_l[i] < 0) zm--;
2543:   for (i=0;i<n;i++) if (cols_l[i] < 0) zn--;
2544:   if (!is->A->rmap->mapping && zm) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the row indices can not be mapped! Maybe you should not use MATIS");
2545:   if (!is->A->cmap->mapping && zn) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Some of the column indices can not be mapped! Maybe you should not use MATIS");
2546: #endif
2547:   MatSetValuesBlocked(is->A,m,rows_l,n,cols_l,values,addv);
2548:   return(0);
2549: }

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

2557:   if (is->A->rmap->mapping) {
2558:     MatSetValuesLocal(is->A,m,rows,n,cols,values,addv);
2559:   } else {
2560:     MatSetValues(is->A,m,rows,n,cols,values,addv);
2561:   }
2562:   return(0);
2563: }

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

2571:   if (is->A->rmap->mapping) {
2572: #if defined(PETSC_USE_DEBUG)
2573:     PetscInt ibs,bs;

2575:     ISLocalToGlobalMappingGetBlockSize(is->A->rmap->mapping,&ibs);
2576:     MatGetBlockSize(is->A,&bs);
2577:     if (ibs != bs) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_SUP,"Different block sizes! local mat %D, local l2g map %D",bs,ibs);
2578: #endif
2579:     MatSetValuesBlockedLocal(is->A,m,rows,n,cols,values,addv);
2580:   } else {
2581:     MatSetValuesBlocked(is->A,m,rows,n,cols,values,addv);
2582:   }
2583:   return(0);
2584: }

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

2592:   if (!n) {
2593:     is->pure_neumann = PETSC_TRUE;
2594:   } else {
2595:     PetscInt i;
2596:     is->pure_neumann = PETSC_FALSE;

2598:     if (columns) {
2599:       MatZeroRowsColumns(is->A,n,rows,diag,0,0);
2600:     } else {
2601:       MatZeroRows(is->A,n,rows,diag,0,0);
2602:     }
2603:     if (diag != 0.) {
2604:       const PetscScalar *array;
2605:       VecGetArrayRead(is->counter,&array);
2606:       for (i=0; i<n; i++) {
2607:         MatSetValue(is->A,rows[i],rows[i],diag/(array[rows[i]]),INSERT_VALUES);
2608:       }
2609:       VecRestoreArrayRead(is->counter,&array);
2610:     }
2611:     MatAssemblyBegin(is->A,MAT_FINAL_ASSEMBLY);
2612:     MatAssemblyEnd(is->A,MAT_FINAL_ASSEMBLY);
2613:   }
2614:   return(0);
2615: }

2617: static PetscErrorCode MatZeroRowsColumns_Private_IS(Mat A,PetscInt n,const PetscInt rows[],PetscScalar diag,Vec x,Vec b,PetscBool columns)
2618: {
2619:   Mat_IS         *matis = (Mat_IS*)A->data;
2620:   PetscInt       nr,nl,len,i;
2621:   PetscInt       *lrows;

2625: #if defined(PETSC_USE_DEBUG)
2626:   if (columns || diag != 0. || (x && b)) {
2627:     PetscBool cong;

2629:     PetscLayoutCompare(A->rmap,A->cmap,&cong);
2630:     cong = (PetscBool)(cong && matis->sf == matis->csf);
2631:     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 and the l2g maps are the same for MATIS");
2632:     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 and the l2g maps are the same for MATIS");
2633:     if (!cong && x && b) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"A->rmap and A->cmap need to be congruent, and the l2g maps be the same");
2634:   }
2635: #endif
2636:   /* get locally owned rows */
2637:   PetscLayoutMapLocal(A->rmap,n,rows,&len,&lrows,NULL);
2638:   /* fix right hand side if needed */
2639:   if (x && b) {
2640:     const PetscScalar *xx;
2641:     PetscScalar       *bb;

2643:     VecGetArrayRead(x, &xx);
2644:     VecGetArray(b, &bb);
2645:     for (i=0;i<len;++i) bb[lrows[i]] = diag*xx[lrows[i]];
2646:     VecRestoreArrayRead(x, &xx);
2647:     VecRestoreArray(b, &bb);
2648:   }
2649:   /* get rows associated to the local matrices */
2650:   MatGetSize(matis->A,&nl,NULL);
2651:   PetscArrayzero(matis->sf_leafdata,nl);
2652:   PetscArrayzero(matis->sf_rootdata,A->rmap->n);
2653:   for (i=0;i<len;i++) matis->sf_rootdata[lrows[i]] = 1;
2654:   PetscFree(lrows);
2655:   PetscSFBcastBegin(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
2656:   PetscSFBcastEnd(matis->sf,MPIU_INT,matis->sf_rootdata,matis->sf_leafdata);
2657:   PetscMalloc1(nl,&lrows);
2658:   for (i=0,nr=0;i<nl;i++) if (matis->sf_leafdata[i]) lrows[nr++] = i;
2659:   MatISZeroRowsColumnsLocal_Private(A,nr,lrows,diag,columns);
2660:   PetscFree(lrows);
2661:   return(0);
2662: }

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

2669:   MatZeroRowsColumns_Private_IS(A,n,rows,diag,x,b,PETSC_FALSE);
2670:   return(0);
2671: }

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

2678:   MatZeroRowsColumns_Private_IS(A,n,rows,diag,x,b,PETSC_TRUE);
2679:   return(0);
2680: }

2682: static PetscErrorCode MatAssemblyBegin_IS(Mat A,MatAssemblyType type)
2683: {
2684:   Mat_IS         *is = (Mat_IS*)A->data;

2688:   MatAssemblyBegin(is->A,type);
2689:   return(0);
2690: }

2692: static PetscErrorCode MatAssemblyEnd_IS(Mat A,MatAssemblyType type)
2693: {
2694:   Mat_IS         *is = (Mat_IS*)A->data;

2698:   MatAssemblyEnd(is->A,type);
2699:   /* fix for local empty rows/cols */
2700:   if (is->locempty && type == MAT_FINAL_ASSEMBLY) {
2701:     Mat                    newlA;
2702:     ISLocalToGlobalMapping rl2g,cl2g;
2703:     IS                     nzr,nzc;
2704:     PetscInt               nr,nc,nnzr,nnzc;
2705:     PetscBool              lnewl2g,newl2g;

2707:     MatGetSize(is->A,&nr,&nc);
2708:     MatFindNonzeroRowsOrCols_Basic(is->A,PETSC_FALSE,PETSC_SMALL,&nzr);
2709:     if (!nzr) {
2710:       ISCreateStride(PetscObjectComm((PetscObject)is->A),nr,0,1,&nzr);
2711:     }
2712:     MatFindNonzeroRowsOrCols_Basic(is->A,PETSC_TRUE,PETSC_SMALL,&nzc);
2713:     if (!nzc) {
2714:       ISCreateStride(PetscObjectComm((PetscObject)is->A),nc,0,1,&nzc);
2715:     }
2716:     ISGetSize(nzr,&nnzr);
2717:     ISGetSize(nzc,&nnzc);
2718:     if (nnzr != nr || nnzc != nc) {
2719:       ISLocalToGlobalMapping l2g;
2720:       IS                     is1,is2;

2722:       /* need new global l2g map */
2723:       lnewl2g = PETSC_TRUE;
2724:       MPI_Allreduce(&lnewl2g,&newl2g,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)A));

2726:       /* extract valid submatrix */
2727:       MatCreateSubMatrix(is->A,nzr,nzc,MAT_INITIAL_MATRIX,&newlA);

2729:       /* attach local l2g maps for successive calls of MatSetValues on the local matrix */
2730:       ISLocalToGlobalMappingCreateIS(nzr,&l2g);
2731:       ISCreateStride(PetscObjectComm((PetscObject)is->A),nr,0,1,&is1);
2732:       ISGlobalToLocalMappingApplyIS(l2g,IS_GTOLM_MASK,is1,&is2);
2733:       ISLocalToGlobalMappingDestroy(&l2g);
2734:       if (is->A->rmap->mapping) { /* the matrix has a local-to-local map already attached (probably DMDA generated) */
2735:         const PetscInt *idxs1,*idxs2;
2736:         PetscInt       j,i,nl,*tidxs;

2738:         ISLocalToGlobalMappingGetSize(is->A->rmap->mapping,&nl);
2739:         ISLocalToGlobalMappingGetIndices(is->A->rmap->mapping,&idxs1);
2740:         PetscMalloc1(nl,&tidxs);
2741:         ISGetIndices(is2,&idxs2);
2742:         for (i=0,j=0;i<nl;i++) tidxs[i] = idxs1[i] < 0 ? -1 : idxs2[j++];
2743:         if (j != nr) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected count %D != %D",j,nr);
2744:         ISLocalToGlobalMappingRestoreIndices(is->A->rmap->mapping,&idxs1);
2745:         ISRestoreIndices(is2,&idxs2);
2746:         ISDestroy(&is2);
2747:         ISCreateGeneral(PetscObjectComm((PetscObject)is->A->rmap->mapping),nl,tidxs,PETSC_OWN_POINTER,&is2);
2748:       }
2749:       ISLocalToGlobalMappingCreateIS(is2,&rl2g);
2750:       ISDestroy(&is1);
2751:       ISDestroy(&is2);

2753:       ISLocalToGlobalMappingCreateIS(nzc,&l2g);
2754:       ISCreateStride(PetscObjectComm((PetscObject)is->A),nc,0,1,&is1);
2755:       ISGlobalToLocalMappingApplyIS(l2g,IS_GTOLM_MASK,is1,&is2);
2756:       ISLocalToGlobalMappingDestroy(&l2g);
2757:       if (is->A->cmap->mapping) { /* the matrix has a local-to-local map already attached (probably DMDA generated) */
2758:         const PetscInt *idxs1,*idxs2;
2759:         PetscInt       j,i,nl,*tidxs;

2761:         ISLocalToGlobalMappingGetSize(is->A->cmap->mapping,&nl);
2762:         ISLocalToGlobalMappingGetIndices(is->A->cmap->mapping,&idxs1);
2763:         PetscMalloc1(nl,&tidxs);
2764:         ISGetIndices(is2,&idxs2);
2765:         for (i=0,j=0;i<nl;i++) tidxs[i] = idxs1[i] < 0 ? -1 : idxs2[j++];
2766:         if (j != nc) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Unexpected count %D != %D",j,nc);
2767:         ISLocalToGlobalMappingRestoreIndices(is->A->cmap->mapping,&idxs1);
2768:         ISRestoreIndices(is2,&idxs2);
2769:         ISDestroy(&is2);
2770:         ISCreateGeneral(PetscObjectComm((PetscObject)is->A->cmap->mapping),nl,tidxs,PETSC_OWN_POINTER,&is2);
2771:       }
2772:       ISLocalToGlobalMappingCreateIS(is2,&cl2g);
2773:       ISDestroy(&is1);
2774:       ISDestroy(&is2);

2776:       MatSetLocalToGlobalMapping(newlA,rl2g,cl2g);

2778:       ISLocalToGlobalMappingDestroy(&rl2g);
2779:       ISLocalToGlobalMappingDestroy(&cl2g);
2780:     } else { /* local matrix fully populated */
2781:       lnewl2g = PETSC_FALSE;
2782:       MPI_Allreduce(&lnewl2g,&newl2g,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)A));
2783:       PetscObjectReference((PetscObject)is->A);
2784:       newlA   = is->A;
2785:     }
2786:     /* attach new global l2g map if needed */
2787:     if (newl2g) {
2788:       IS             gnzr,gnzc;
2789:       const PetscInt *grid,*gcid;

2791:       ISLocalToGlobalMappingApplyIS(A->rmap->mapping,nzr,&gnzr);
2792:       ISLocalToGlobalMappingApplyIS(A->cmap->mapping,nzc,&gnzc);
2793:       ISGetIndices(gnzr,&grid);
2794:       ISGetIndices(gnzc,&gcid);
2795:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)A),1,nnzr,grid,PETSC_COPY_VALUES,&rl2g);
2796:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)A),1,nnzc,gcid,PETSC_COPY_VALUES,&cl2g);
2797:       ISRestoreIndices(gnzr,&grid);
2798:       ISRestoreIndices(gnzc,&gcid);
2799:       ISDestroy(&gnzr);
2800:       ISDestroy(&gnzc);
2801:       MatSetLocalToGlobalMapping(A,rl2g,cl2g);
2802:       ISLocalToGlobalMappingDestroy(&rl2g);
2803:       ISLocalToGlobalMappingDestroy(&cl2g);
2804:     }
2805:     MatISSetLocalMat(A,newlA);
2806:     MatDestroy(&newlA);
2807:     ISDestroy(&nzr);
2808:     ISDestroy(&nzc);
2809:     is->locempty = PETSC_FALSE;
2810:   }
2811:   return(0);
2812: }

2814: static PetscErrorCode MatISGetLocalMat_IS(Mat mat,Mat *local)
2815: {
2816:   Mat_IS *is = (Mat_IS*)mat->data;

2819:   *local = is->A;
2820:   return(0);
2821: }

2823: static PetscErrorCode MatISRestoreLocalMat_IS(Mat mat,Mat *local)
2824: {
2826:   *local = NULL;
2827:   return(0);
2828: }

2830: /*@
2831:     MatISGetLocalMat - Gets the local matrix stored inside a MATIS matrix.

2833:   Input Parameter:
2834: .  mat - the matrix

2836:   Output Parameter:
2837: .  local - the local matrix

2839:   Level: advanced

2841:   Notes:
2842:     This can be called if you have precomputed the nonzero structure of the
2843:   matrix and want to provide it to the inner matrix object to improve the performance
2844:   of the MatSetValues() operation.

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

2848: .seealso: MATIS
2849: @*/
2850: PetscErrorCode MatISGetLocalMat(Mat mat,Mat *local)
2851: {

2857:   PetscUseMethod(mat,"MatISGetLocalMat_C",(Mat,Mat*),(mat,local));
2858:   return(0);
2859: }

2861: /*@
2862:     MatISRestoreLocalMat - Restores the local matrix obtained with MatISGetLocalMat()

2864:   Input Parameter:
2865: .  mat - the matrix

2867:   Output Parameter:
2868: .  local - the local matrix

2870:   Level: advanced

2872: .seealso: MATIS
2873: @*/
2874: PetscErrorCode MatISRestoreLocalMat(Mat mat,Mat *local)
2875: {

2881:   PetscUseMethod(mat,"MatISRestoreLocalMat_C",(Mat,Mat*),(mat,local));
2882:   return(0);
2883: }

2885: static PetscErrorCode MatISSetLocalMatType_IS(Mat mat,MatType mtype)
2886: {
2887:   Mat_IS         *is = (Mat_IS*)mat->data;

2891:   if (is->A) {
2892:     MatSetType(is->A,mtype);
2893:   }
2894:   PetscFree(is->lmattype);
2895:   PetscStrallocpy(mtype,&is->lmattype);
2896:   return(0);
2897: }

2899: /*@
2900:     MatISSetLocalMatType - Specifies the type of local matrix

2902:   Input Parameter:
2903: .  mat - the matrix
2904: .  mtype - the local matrix type

2906:   Output Parameter:

2908:   Level: advanced

2910: .seealso: MATIS, MatSetType(), MatType
2911: @*/
2912: PetscErrorCode MatISSetLocalMatType(Mat mat,MatType mtype)
2913: {

2918:   PetscUseMethod(mat,"MatISSetLocalMatType_C",(Mat,MatType),(mat,mtype));
2919:   return(0);
2920: }

2922: static PetscErrorCode MatISSetLocalMat_IS(Mat mat,Mat local)
2923: {
2924:   Mat_IS         *is = (Mat_IS*)mat->data;
2925:   PetscInt       nrows,ncols,orows,ocols;
2927:   MatType        mtype,otype;
2928:   PetscBool      sametype = PETSC_TRUE;

2931:   if (is->A) {
2932:     MatGetSize(is->A,&orows,&ocols);
2933:     MatGetSize(local,&nrows,&ncols);
2934:     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);
2935:     MatGetType(local,&mtype);
2936:     MatGetType(is->A,&otype);
2937:     PetscStrcmp(mtype,otype,&sametype);
2938:   }
2939:   PetscObjectReference((PetscObject)local);
2940:   MatDestroy(&is->A);
2941:   is->A = local;
2942:   MatGetType(is->A,&mtype);
2943:   MatISSetLocalMatType(mat,mtype);
2944:   if (!sametype && !is->islocalref) {
2945:     MatISSetUpScatters_Private(mat);
2946:   }
2947:   return(0);
2948: }

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

2953:   Collective on Mat

2955:   Input Parameter:
2956: .  mat - the matrix
2957: .  local - the local matrix

2959:   Output Parameter:

2961:   Level: advanced

2963:   Notes:
2964:     This can be called if you have precomputed the local matrix and
2965:   want to provide it to the matrix object MATIS.

2967: .seealso: MATIS
2968: @*/
2969: PetscErrorCode MatISSetLocalMat(Mat mat,Mat local)
2970: {

2976:   PetscUseMethod(mat,"MatISSetLocalMat_C",(Mat,Mat),(mat,local));
2977:   return(0);
2978: }

2980: static PetscErrorCode MatZeroEntries_IS(Mat A)
2981: {
2982:   Mat_IS         *a = (Mat_IS*)A->data;

2986:   MatZeroEntries(a->A);
2987:   return(0);
2988: }

2990: static PetscErrorCode MatScale_IS(Mat A,PetscScalar a)
2991: {
2992:   Mat_IS         *is = (Mat_IS*)A->data;

2996:   MatScale(is->A,a);
2997:   return(0);
2998: }

3000: static PetscErrorCode MatGetDiagonal_IS(Mat A, Vec v)
3001: {
3002:   Mat_IS         *is = (Mat_IS*)A->data;

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

3009:   /* scatter diagonal back into global vector */
3010:   VecSet(v,0);
3011:   VecScatterBegin(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
3012:   VecScatterEnd(is->rctx,is->y,v,ADD_VALUES,SCATTER_REVERSE);
3013:   return(0);
3014: }

3016: static PetscErrorCode MatSetOption_IS(Mat A,MatOption op,PetscBool flg)
3017: {
3018:   Mat_IS         *a = (Mat_IS*)A->data;

3022:   MatSetOption(a->A,op,flg);
3023:   return(0);
3024: }

3026: static PetscErrorCode MatAXPY_IS(Mat Y,PetscScalar a,Mat X,MatStructure str)
3027: {
3028:   Mat_IS         *y = (Mat_IS*)Y->data;
3029:   Mat_IS         *x;
3030: #if defined(PETSC_USE_DEBUG)
3031:   PetscBool      ismatis;
3032: #endif

3036: #if defined(PETSC_USE_DEBUG)
3037:   PetscObjectTypeCompare((PetscObject)X,MATIS,&ismatis);
3038:   if (!ismatis) SETERRQ(PetscObjectComm((PetscObject)Y),PETSC_ERR_SUP,"Cannot call MatAXPY(Y,a,X,str) with X not of type MATIS");
3039: #endif
3040:   x = (Mat_IS*)X->data;
3041:   MatAXPY(y->A,a,x->A,str);
3042:   return(0);
3043: }

3045: static PetscErrorCode MatGetLocalSubMatrix_IS(Mat A,IS row,IS col,Mat *submat)
3046: {
3047:   Mat                    lA;
3048:   Mat_IS                 *matis;
3049:   ISLocalToGlobalMapping rl2g,cl2g;
3050:   IS                     is;
3051:   const PetscInt         *rg,*rl;
3052:   PetscInt               nrg;
3053:   PetscInt               N,M,nrl,i,*idxs;
3054:   PetscErrorCode         ierr;

3057:   ISLocalToGlobalMappingGetIndices(A->rmap->mapping,&rg);
3058:   ISGetLocalSize(row,&nrl);
3059:   ISGetIndices(row,&rl);
3060:   ISLocalToGlobalMappingGetSize(A->rmap->mapping,&nrg);
3061: #if defined(PETSC_USE_DEBUG)
3062:   for (i=0;i<nrl;i++) if (rl[i]>=nrg) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local row index %D -> %D greater then maximum possible %D",i,rl[i],nrg);
3063: #endif
3064:   PetscMalloc1(nrg,&idxs);
3065:   /* map from [0,nrl) to row */
3066:   for (i=0;i<nrl;i++) idxs[i] = rl[i];
3067:   for (i=nrl;i<nrg;i++) idxs[i] = -1;
3068:   ISRestoreIndices(row,&rl);
3069:   ISLocalToGlobalMappingRestoreIndices(A->rmap->mapping,&rg);
3070:   ISCreateGeneral(PetscObjectComm((PetscObject)A),nrg,idxs,PETSC_OWN_POINTER,&is);
3071:   ISLocalToGlobalMappingCreateIS(is,&rl2g);
3072:   ISDestroy(&is);
3073:   /* compute new l2g map for columns */
3074:   if (col != row || A->rmap->mapping != A->cmap->mapping) {
3075:     const PetscInt *cg,*cl;
3076:     PetscInt       ncg;
3077:     PetscInt       ncl;

3079:     ISLocalToGlobalMappingGetIndices(A->cmap->mapping,&cg);
3080:     ISGetLocalSize(col,&ncl);
3081:     ISGetIndices(col,&cl);
3082:     ISLocalToGlobalMappingGetSize(A->cmap->mapping,&ncg);
3083: #if defined(PETSC_USE_DEBUG)
3084:     for (i=0;i<ncl;i++) if (cl[i]>=ncg) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Local column index %D -> %D greater then maximum possible %D",i,cl[i],ncg);
3085: #endif
3086:     PetscMalloc1(ncg,&idxs);
3087:     /* map from [0,ncl) to col */
3088:     for (i=0;i<ncl;i++) idxs[i] = cl[i];
3089:     for (i=ncl;i<ncg;i++) idxs[i] = -1;
3090:     ISRestoreIndices(col,&cl);
3091:     ISLocalToGlobalMappingRestoreIndices(A->cmap->mapping,&cg);
3092:     ISCreateGeneral(PetscObjectComm((PetscObject)A),ncg,idxs,PETSC_OWN_POINTER,&is);
3093:     ISLocalToGlobalMappingCreateIS(is,&cl2g);
3094:     ISDestroy(&is);
3095:   } else {
3096:     PetscObjectReference((PetscObject)rl2g);
3097:     cl2g = rl2g;
3098:   }
3099:   /* create the MATIS submatrix */
3100:   MatGetSize(A,&M,&N);
3101:   MatCreate(PetscObjectComm((PetscObject)A),submat);
3102:   MatSetSizes(*submat,PETSC_DECIDE,PETSC_DECIDE,M,N);
3103:   MatSetType(*submat,MATIS);
3104:   matis = (Mat_IS*)((*submat)->data);
3105:   matis->islocalref = PETSC_TRUE;
3106:   MatSetLocalToGlobalMapping(*submat,rl2g,cl2g);
3107:   MatISGetLocalMat(A,&lA);
3108:   MatISSetLocalMat(*submat,lA);
3109:   MatSetUp(*submat);
3110:   MatAssemblyBegin(*submat,MAT_FINAL_ASSEMBLY);
3111:   MatAssemblyEnd(*submat,MAT_FINAL_ASSEMBLY);
3112:   ISLocalToGlobalMappingDestroy(&rl2g);
3113:   ISLocalToGlobalMappingDestroy(&cl2g);
3114:   /* remove unsupported ops */
3115:   PetscMemzero((*submat)->ops,sizeof(struct _MatOps));
3116:   (*submat)->ops->destroy               = MatDestroy_IS;
3117:   (*submat)->ops->setvalueslocal        = MatSetValuesLocal_SubMat_IS;
3118:   (*submat)->ops->setvaluesblockedlocal = MatSetValuesBlockedLocal_SubMat_IS;
3119:   (*submat)->ops->assemblybegin         = MatAssemblyBegin_IS;
3120:   (*submat)->ops->assemblyend           = MatAssemblyEnd_IS;
3121:   return(0);
3122: }

3124: static PetscErrorCode MatSetFromOptions_IS(PetscOptionItems *PetscOptionsObject, Mat A)
3125: {
3126:   Mat_IS         *a = (Mat_IS*)A->data;
3127:   char           type[256];
3128:   PetscBool      flg;

3132:   PetscOptionsHead(PetscOptionsObject,"MATIS options");
3133:   PetscOptionsBool("-matis_fixempty","Fix local matrices in case of empty local rows/columns","MatISFixLocalEmpty",a->locempty,&a->locempty,NULL);
3134:   PetscOptionsBool("-matis_storel2l","Store local-to-local matrices generated from PtAP operations","MatISStoreL2L",a->storel2l,&a->storel2l,NULL);
3135:   PetscOptionsFList("-matis_localmat_type","Matrix type","MatISSetLocalMatType",MatList,a->lmattype,type,256,&flg);
3136:   if (flg) {
3137:     MatISSetLocalMatType(A,type);
3138:   }
3139:   if (a->A) {
3140:     MatSetFromOptions(a->A);
3141:   }
3142:   PetscOptionsTail();
3143:   return(0);
3144: }

3146: /*@
3147:     MatCreateIS - Creates a "process" unassembled matrix, assembled on each
3148:        process but not across processes.

3150:    Input Parameters:
3151: +     comm    - MPI communicator that will share the matrix
3152: .     bs      - block size of the matrix
3153: .     m,n,M,N - local and/or global sizes of the left and right vector used in matrix vector products
3154: .     rmap    - local to global map for rows
3155: -     cmap    - local to global map for cols

3157:    Output Parameter:
3158: .    A - the resulting matrix

3160:    Level: advanced

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

3168: .seealso: MATIS, MatSetLocalToGlobalMapping()
3169: @*/
3170: PetscErrorCode  MatCreateIS(MPI_Comm comm,PetscInt bs,PetscInt m,PetscInt n,PetscInt M,PetscInt N,ISLocalToGlobalMapping rmap,ISLocalToGlobalMapping cmap,Mat *A)
3171: {

3175:   if (!rmap && !cmap) SETERRQ(comm,PETSC_ERR_USER,"You need to provide at least one of the mappings");
3176:   MatCreate(comm,A);
3177:   MatSetSizes(*A,m,n,M,N);
3178:   if (bs > 0) {
3179:     MatSetBlockSize(*A,bs);
3180:   }
3181:   MatSetType(*A,MATIS);
3182:   if (rmap && cmap) {
3183:     MatSetLocalToGlobalMapping(*A,rmap,cmap);
3184:   } else if (!rmap) {
3185:     MatSetLocalToGlobalMapping(*A,cmap,cmap);
3186:   } else {
3187:     MatSetLocalToGlobalMapping(*A,rmap,rmap);
3188:   }
3189:   return(0);
3190: }

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

3197:    Options Database Keys:
3198: + -mat_type is - sets the matrix type to "is" during a call to MatSetFromOptions()
3199: . -matis_fixempty - Fixes local matrices in case of empty local rows/columns.
3200: - -matis_storel2l - stores the local-to-local operators generated by the Galerkin process of MatPtAP().

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

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

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

3210:   Level: advanced

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

3214: M*/

3216: PETSC_EXTERN PetscErrorCode MatCreate_IS(Mat A)
3217: {
3219:   Mat_IS         *b;

3222:   PetscNewLog(A,&b);
3223:   PetscStrallocpy(MATAIJ,&b->lmattype);
3224:   A->data = (void*)b;

3226:   /* matrix ops */
3227:   PetscMemzero(A->ops,sizeof(struct _MatOps));
3228:   A->ops->mult                    = MatMult_IS;
3229:   A->ops->multadd                 = MatMultAdd_IS;
3230:   A->ops->multtranspose           = MatMultTranspose_IS;
3231:   A->ops->multtransposeadd        = MatMultTransposeAdd_IS;
3232:   A->ops->destroy                 = MatDestroy_IS;
3233:   A->ops->setlocaltoglobalmapping = MatSetLocalToGlobalMapping_IS;
3234:   A->ops->setvalues               = MatSetValues_IS;
3235:   A->ops->setvaluesblocked        = MatSetValuesBlocked_IS;
3236:   A->ops->setvalueslocal          = MatSetValuesLocal_IS;
3237:   A->ops->setvaluesblockedlocal   = MatSetValuesBlockedLocal_IS;
3238:   A->ops->zerorows                = MatZeroRows_IS;
3239:   A->ops->zerorowscolumns         = MatZeroRowsColumns_IS;
3240:   A->ops->assemblybegin           = MatAssemblyBegin_IS;
3241:   A->ops->assemblyend             = MatAssemblyEnd_IS;
3242:   A->ops->view                    = MatView_IS;
3243:   A->ops->zeroentries             = MatZeroEntries_IS;
3244:   A->ops->scale                   = MatScale_IS;
3245:   A->ops->getdiagonal             = MatGetDiagonal_IS;
3246:   A->ops->setoption               = MatSetOption_IS;
3247:   A->ops->ishermitian             = MatIsHermitian_IS;
3248:   A->ops->issymmetric             = MatIsSymmetric_IS;
3249:   A->ops->isstructurallysymmetric = MatIsStructurallySymmetric_IS;
3250:   A->ops->duplicate               = MatDuplicate_IS;
3251:   A->ops->missingdiagonal         = MatMissingDiagonal_IS;
3252:   A->ops->copy                    = MatCopy_IS;
3253:   A->ops->getlocalsubmatrix       = MatGetLocalSubMatrix_IS;
3254:   A->ops->createsubmatrix         = MatCreateSubMatrix_IS;
3255:   A->ops->axpy                    = MatAXPY_IS;
3256:   A->ops->diagonalset             = MatDiagonalSet_IS;
3257:   A->ops->shift                   = MatShift_IS;
3258:   A->ops->transpose               = MatTranspose_IS;
3259:   A->ops->getinfo                 = MatGetInfo_IS;
3260:   A->ops->diagonalscale           = MatDiagonalScale_IS;
3261:   A->ops->setfromoptions          = MatSetFromOptions_IS;

3263:   /* special MATIS functions */
3264:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMatType_C",MatISSetLocalMatType_IS);
3265:   PetscObjectComposeFunction((PetscObject)A,"MatISGetLocalMat_C",MatISGetLocalMat_IS);
3266:   PetscObjectComposeFunction((PetscObject)A,"MatISRestoreLocalMat_C",MatISRestoreLocalMat_IS);
3267:   PetscObjectComposeFunction((PetscObject)A,"MatISSetLocalMat_C",MatISSetLocalMat_IS);
3268:   PetscObjectComposeFunction((PetscObject)A,"MatISGetMPIXAIJ_C",MatConvert_IS_XAIJ);
3269:   PetscObjectComposeFunction((PetscObject)A,"MatISSetPreallocation_C",MatISSetPreallocation_IS);
3270:   PetscObjectComposeFunction((PetscObject)A,"MatISStoreL2L_C",MatISStoreL2L_IS);
3271:   PetscObjectComposeFunction((PetscObject)A,"MatISFixLocalEmpty_C",MatISFixLocalEmpty_IS);
3272:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpiaij_C",MatConvert_IS_XAIJ);
3273:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpibaij_C",MatConvert_IS_XAIJ);
3274:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_mpisbaij_C",MatConvert_IS_XAIJ);
3275:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqaij_C",MatConvert_IS_XAIJ);
3276:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqbaij_C",MatConvert_IS_XAIJ);
3277:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_seqsbaij_C",MatConvert_IS_XAIJ);
3278:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_is_aij_C",MatConvert_IS_XAIJ);
3279:   PetscObjectChangeTypeName((PetscObject)A,MATIS);
3280:   return(0);
3281: }