Actual source code: matnest.c

petsc-master 2017-05-29
Report Typos and Errors

  2:  #include <../src/mat/impls/nest/matnestimpl.h>
  3:  #include <../src/mat/impls/aij/seq/aij.h>
  4:  #include <petscsf.h>

  6: static PetscErrorCode MatSetUp_NestIS_Private(Mat,PetscInt,const IS[],PetscInt,const IS[]);
  7: static PetscErrorCode MatCreateVecs_Nest(Mat A,Vec *right,Vec *left);
  8: PETSC_INTERN PetscErrorCode MatConvert_Nest_IS(Mat,MatType,MatReuse,Mat*);

 10: /* private functions */
 11: static PetscErrorCode MatNestGetSizes_Private(Mat A,PetscInt *m,PetscInt *n,PetscInt *M,PetscInt *N)
 12: {
 13:   Mat_Nest       *bA = (Mat_Nest*)A->data;
 14:   PetscInt       i,j;

 18:   *m = *n = *M = *N = 0;
 19:   for (i=0; i<bA->nr; i++) {  /* rows */
 20:     PetscInt sm,sM;
 21:     ISGetLocalSize(bA->isglobal.row[i],&sm);
 22:     ISGetSize(bA->isglobal.row[i],&sM);
 23:     *m  += sm;
 24:     *M  += sM;
 25:   }
 26:   for (j=0; j<bA->nc; j++) {  /* cols */
 27:     PetscInt sn,sN;
 28:     ISGetLocalSize(bA->isglobal.col[j],&sn);
 29:     ISGetSize(bA->isglobal.col[j],&sN);
 30:     *n  += sn;
 31:     *N  += sN;
 32:   }
 33:   return(0);
 34: }

 36: /* operations */
 37: static PetscErrorCode MatMult_Nest(Mat A,Vec x,Vec y)
 38: {
 39:   Mat_Nest       *bA = (Mat_Nest*)A->data;
 40:   Vec            *bx = bA->right,*by = bA->left;
 41:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

 45:   for (i=0; i<nr; i++) {VecGetSubVector(y,bA->isglobal.row[i],&by[i]);}
 46:   for (i=0; i<nc; i++) {VecGetSubVector(x,bA->isglobal.col[i],&bx[i]);}
 47:   for (i=0; i<nr; i++) {
 48:     VecZeroEntries(by[i]);
 49:     for (j=0; j<nc; j++) {
 50:       if (!bA->m[i][j]) continue;
 51:       /* y[i] <- y[i] + A[i][j] * x[j] */
 52:       MatMultAdd(bA->m[i][j],bx[j],by[i],by[i]);
 53:     }
 54:   }
 55:   for (i=0; i<nr; i++) {VecRestoreSubVector(y,bA->isglobal.row[i],&by[i]);}
 56:   for (i=0; i<nc; i++) {VecRestoreSubVector(x,bA->isglobal.col[i],&bx[i]);}
 57:   return(0);
 58: }

 60: static PetscErrorCode MatMultAdd_Nest(Mat A,Vec x,Vec y,Vec z)
 61: {
 62:   Mat_Nest       *bA = (Mat_Nest*)A->data;
 63:   Vec            *bx = bA->right,*bz = bA->left;
 64:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

 68:   for (i=0; i<nr; i++) {VecGetSubVector(z,bA->isglobal.row[i],&bz[i]);}
 69:   for (i=0; i<nc; i++) {VecGetSubVector(x,bA->isglobal.col[i],&bx[i]);}
 70:   for (i=0; i<nr; i++) {
 71:     if (y != z) {
 72:       Vec by;
 73:       VecGetSubVector(y,bA->isglobal.row[i],&by);
 74:       VecCopy(by,bz[i]);
 75:       VecRestoreSubVector(y,bA->isglobal.row[i],&by);
 76:     }
 77:     for (j=0; j<nc; j++) {
 78:       if (!bA->m[i][j]) continue;
 79:       /* y[i] <- y[i] + A[i][j] * x[j] */
 80:       MatMultAdd(bA->m[i][j],bx[j],bz[i],bz[i]);
 81:     }
 82:   }
 83:   for (i=0; i<nr; i++) {VecRestoreSubVector(z,bA->isglobal.row[i],&bz[i]);}
 84:   for (i=0; i<nc; i++) {VecRestoreSubVector(x,bA->isglobal.col[i],&bx[i]);}
 85:   return(0);
 86: }

 88: static PetscErrorCode MatMultTranspose_Nest(Mat A,Vec x,Vec y)
 89: {
 90:   Mat_Nest       *bA = (Mat_Nest*)A->data;
 91:   Vec            *bx = bA->left,*by = bA->right;
 92:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

 96:   for (i=0; i<nr; i++) {VecGetSubVector(x,bA->isglobal.row[i],&bx[i]);}
 97:   for (i=0; i<nc; i++) {VecGetSubVector(y,bA->isglobal.col[i],&by[i]);}
 98:   for (j=0; j<nc; j++) {
 99:     VecZeroEntries(by[j]);
100:     for (i=0; i<nr; i++) {
101:       if (!bA->m[i][j]) continue;
102:       /* y[j] <- y[j] + (A[i][j])^T * x[i] */
103:       MatMultTransposeAdd(bA->m[i][j],bx[i],by[j],by[j]);
104:     }
105:   }
106:   for (i=0; i<nr; i++) {VecRestoreSubVector(x,bA->isglobal.row[i],&bx[i]);}
107:   for (i=0; i<nc; i++) {VecRestoreSubVector(y,bA->isglobal.col[i],&by[i]);}
108:   return(0);
109: }

111: static PetscErrorCode MatMultTransposeAdd_Nest(Mat A,Vec x,Vec y,Vec z)
112: {
113:   Mat_Nest       *bA = (Mat_Nest*)A->data;
114:   Vec            *bx = bA->left,*bz = bA->right;
115:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

119:   for (i=0; i<nr; i++) {VecGetSubVector(x,bA->isglobal.row[i],&bx[i]);}
120:   for (i=0; i<nc; i++) {VecGetSubVector(z,bA->isglobal.col[i],&bz[i]);}
121:   for (j=0; j<nc; j++) {
122:     if (y != z) {
123:       Vec by;
124:       VecGetSubVector(y,bA->isglobal.col[j],&by);
125:       VecCopy(by,bz[j]);
126:       VecRestoreSubVector(y,bA->isglobal.col[j],&by);
127:     }
128:     for (i=0; i<nr; i++) {
129:       if (!bA->m[i][j]) continue;
130:       /* z[j] <- y[j] + (A[i][j])^T * x[i] */
131:       MatMultTransposeAdd(bA->m[i][j],bx[i],bz[j],bz[j]);
132:     }
133:   }
134:   for (i=0; i<nr; i++) {VecRestoreSubVector(x,bA->isglobal.row[i],&bx[i]);}
135:   for (i=0; i<nc; i++) {VecRestoreSubVector(z,bA->isglobal.col[i],&bz[i]);}
136:   return(0);
137: }

139: static PetscErrorCode MatTranspose_Nest(Mat A,MatReuse reuse,Mat *B)
140: {
141:   Mat_Nest       *bA = (Mat_Nest*)A->data, *bC;
142:   Mat            C;
143:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

147:   if (reuse == MAT_INPLACE_MATRIX && nr != nc) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_SIZ,"Square nested matrix only for in-place");

149:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
150:     Mat *subs;
151:     IS  *is_row,*is_col;

153:     PetscCalloc1(nr * nc,&subs);
154:     PetscMalloc2(nr,&is_row,nc,&is_col);
155:     MatNestGetISs(A,is_row,is_col);
156:     if (reuse == MAT_INPLACE_MATRIX) {
157:       for (i=0; i<nr; i++) {
158:         for (j=0; j<nc; j++) {
159:           subs[i + nr * j] = bA->m[i][j];
160:         }
161:       }
162:     }

164:     MatCreateNest(PetscObjectComm((PetscObject)A),nc,is_col,nr,is_row,subs,&C);
165:     PetscFree(subs);
166:     PetscFree2(is_row,is_col);
167:   } else {
168:     C = *B;
169:   }

171:   bC = (Mat_Nest*)C->data;
172:   for (i=0; i<nr; i++) {
173:     for (j=0; j<nc; j++) {
174:       if (bA->m[i][j]) {
175:         MatTranspose(bA->m[i][j], reuse, &(bC->m[j][i]));
176:       } else {
177:         bC->m[j][i] = NULL;
178:       }
179:     }
180:   }

182:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
183:     *B = C;
184:   } else {
185:     MatHeaderMerge(A, &C);
186:   }
187:   return(0);
188: }

190: static PetscErrorCode MatNestDestroyISList(PetscInt n,IS **list)
191: {
193:   IS             *lst = *list;
194:   PetscInt       i;

197:   if (!lst) return(0);
198:   for (i=0; i<n; i++) if (lst[i]) {ISDestroy(&lst[i]);}
199:   PetscFree(lst);
200:   *list = NULL;
201:   return(0);
202: }

204: static PetscErrorCode MatDestroy_Nest(Mat A)
205: {
206:   Mat_Nest       *vs = (Mat_Nest*)A->data;
207:   PetscInt       i,j;

211:   /* release the matrices and the place holders */
212:   MatNestDestroyISList(vs->nr,&vs->isglobal.row);
213:   MatNestDestroyISList(vs->nc,&vs->isglobal.col);
214:   MatNestDestroyISList(vs->nr,&vs->islocal.row);
215:   MatNestDestroyISList(vs->nc,&vs->islocal.col);

217:   PetscFree(vs->row_len);
218:   PetscFree(vs->col_len);

220:   PetscFree2(vs->left,vs->right);

222:   /* release the matrices and the place holders */
223:   if (vs->m) {
224:     for (i=0; i<vs->nr; i++) {
225:       for (j=0; j<vs->nc; j++) {
226:         MatDestroy(&vs->m[i][j]);
227:       }
228:       PetscFree(vs->m[i]);
229:     }
230:     PetscFree(vs->m);
231:   }
232:   PetscFree(A->data);

234:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSubMat_C",0);
235:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetSubMat_C",0);
236:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSubMats_C",0);
237:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSize_C",0);
238:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetISs_C",0);
239:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetLocalISs_C",0);
240:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetVecType_C",0);
241:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetSubMats_C",0);
242:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_nest_aij_C",0);
243:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_nest_is_C",0);
244:   return(0);
245: }

247: static PetscErrorCode MatAssemblyBegin_Nest(Mat A,MatAssemblyType type)
248: {
249:   Mat_Nest       *vs = (Mat_Nest*)A->data;
250:   PetscInt       i,j;

254:   for (i=0; i<vs->nr; i++) {
255:     for (j=0; j<vs->nc; j++) {
256:       if (vs->m[i][j]) {
257:         MatAssemblyBegin(vs->m[i][j],type);
258:         if (!vs->splitassembly) {
259:           /* Note: split assembly will fail if the same block appears more than once (even indirectly through a nested
260:            * sub-block). This could be fixed by adding a flag to Mat so that there was a way to check if a Mat was
261:            * already performing an assembly, but the result would by more complicated and appears to offer less
262:            * potential for diagnostics and correctness checking. Split assembly should be fixed once there is an
263:            * interface for libraries to make asynchronous progress in "user-defined non-blocking collectives".
264:            */
265:           MatAssemblyEnd(vs->m[i][j],type);
266:         }
267:       }
268:     }
269:   }
270:   return(0);
271: }

273: static PetscErrorCode MatAssemblyEnd_Nest(Mat A, MatAssemblyType type)
274: {
275:   Mat_Nest       *vs = (Mat_Nest*)A->data;
276:   PetscInt       i,j;

280:   for (i=0; i<vs->nr; i++) {
281:     for (j=0; j<vs->nc; j++) {
282:       if (vs->m[i][j]) {
283:         if (vs->splitassembly) {
284:           MatAssemblyEnd(vs->m[i][j],type);
285:         }
286:       }
287:     }
288:   }
289:   return(0);
290: }

292: static PetscErrorCode MatNestFindNonzeroSubMatRow(Mat A,PetscInt row,Mat *B)
293: {
295:   Mat_Nest       *vs = (Mat_Nest*)A->data;
296:   PetscInt       j;
297:   Mat            sub;

300:   sub = (row < vs->nc) ? vs->m[row][row] : (Mat)NULL; /* Prefer to find on the diagonal */
301:   for (j=0; !sub && j<vs->nc; j++) sub = vs->m[row][j];
302:   if (sub) {MatSetUp(sub);}       /* Ensure that the sizes are available */
303:   *B = sub;
304:   return(0);
305: }

307: static PetscErrorCode MatNestFindNonzeroSubMatCol(Mat A,PetscInt col,Mat *B)
308: {
310:   Mat_Nest       *vs = (Mat_Nest*)A->data;
311:   PetscInt       i;
312:   Mat            sub;

315:   sub = (col < vs->nr) ? vs->m[col][col] : (Mat)NULL; /* Prefer to find on the diagonal */
316:   for (i=0; !sub && i<vs->nr; i++) sub = vs->m[i][col];
317:   if (sub) {MatSetUp(sub);}       /* Ensure that the sizes are available */
318:   *B = sub;
319:   return(0);
320: }

322: static PetscErrorCode MatNestFindIS(Mat A,PetscInt n,const IS list[],IS is,PetscInt *found)
323: {
325:   PetscInt       i;
326:   PetscBool      flg;

332:   *found = -1;
333:   for (i=0; i<n; i++) {
334:     if (!list[i]) continue;
335:     ISEqual(list[i],is,&flg);
336:     if (flg) {
337:       *found = i;
338:       return(0);
339:     }
340:   }
341:   SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"Could not find index set");
342:   return(0);
343: }

345: /* Get a block row as a new MatNest */
346: static PetscErrorCode MatNestGetRow(Mat A,PetscInt row,Mat *B)
347: {
348:   Mat_Nest       *vs = (Mat_Nest*)A->data;
349:   char           keyname[256];

353:   *B   = NULL;
354:   PetscSNPrintf(keyname,sizeof(keyname),"NestRow_%D",row);
355:   PetscObjectQuery((PetscObject)A,keyname,(PetscObject*)B);
356:   if (*B) return(0);

358:   MatCreateNest(PetscObjectComm((PetscObject)A),1,NULL,vs->nc,vs->isglobal.col,vs->m[row],B);

360:   (*B)->assembled = A->assembled;

362:   PetscObjectCompose((PetscObject)A,keyname,(PetscObject)*B);
363:   PetscObjectDereference((PetscObject)*B); /* Leave the only remaining reference in the composition */
364:   return(0);
365: }

367: static PetscErrorCode MatNestFindSubMat(Mat A,struct MatNestISPair *is,IS isrow,IS iscol,Mat *B)
368: {
369:   Mat_Nest       *vs = (Mat_Nest*)A->data;
371:   PetscInt       row,col;
372:   PetscBool      same,isFullCol,isFullColGlobal;

375:   /* Check if full column space. This is a hack */
376:   isFullCol = PETSC_FALSE;
377:   PetscObjectTypeCompare((PetscObject)iscol,ISSTRIDE,&same);
378:   if (same) {
379:     PetscInt n,first,step,i,an,am,afirst,astep;
380:     ISStrideGetInfo(iscol,&first,&step);
381:     ISGetLocalSize(iscol,&n);
382:     isFullCol = PETSC_TRUE;
383:     for (i=0,an=A->cmap->rstart; i<vs->nc; i++) {
384:       ISStrideGetInfo(is->col[i],&afirst,&astep);
385:       ISGetLocalSize(is->col[i],&am);
386:       if (afirst != an || astep != step) isFullCol = PETSC_FALSE;
387:       an += am;
388:     }
389:     if (an != A->cmap->rstart+n) isFullCol = PETSC_FALSE;
390:   }
391:   MPIU_Allreduce(&isFullCol,&isFullColGlobal,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)iscol));

393:   if (isFullColGlobal && vs->nc > 1) {
394:     PetscInt row;
395:     MatNestFindIS(A,vs->nr,is->row,isrow,&row);
396:     MatNestGetRow(A,row,B);
397:   } else {
398:     MatNestFindIS(A,vs->nr,is->row,isrow,&row);
399:     MatNestFindIS(A,vs->nc,is->col,iscol,&col);
400:     if (!vs->m[row][col]) {
401:       PetscInt lr,lc;

403:       MatCreate(PetscObjectComm((PetscObject)A),&vs->m[row][col]);
404:       ISGetLocalSize(vs->isglobal.row[row],&lr);
405:       ISGetLocalSize(vs->isglobal.col[col],&lc);
406:       MatSetSizes(vs->m[row][col],lr,lc,PETSC_DECIDE,PETSC_DECIDE);
407:       MatSetUp(vs->m[row][col]);
408:       MatAssemblyBegin(vs->m[row][col],MAT_FINAL_ASSEMBLY);
409:       MatAssemblyEnd(vs->m[row][col],MAT_FINAL_ASSEMBLY);
410:     }
411:     *B = vs->m[row][col];
412:   }
413:   return(0);
414: }

416: static PetscErrorCode MatCreateSubMatrix_Nest(Mat A,IS isrow,IS iscol,MatReuse reuse,Mat *B)
417: {
419:   Mat_Nest       *vs = (Mat_Nest*)A->data;
420:   Mat            sub;

423:   MatNestFindSubMat(A,&vs->isglobal,isrow,iscol,&sub);
424:   switch (reuse) {
425:   case MAT_INITIAL_MATRIX:
426:     if (sub) { PetscObjectReference((PetscObject)sub); }
427:     *B = sub;
428:     break;
429:   case MAT_REUSE_MATRIX:
430:     if (sub != *B) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Submatrix was not used before in this call");
431:     break;
432:   case MAT_IGNORE_MATRIX:       /* Nothing to do */
433:     break;
434:   case MAT_INPLACE_MATRIX:       /* Nothing to do */
435:     SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MAT_INPLACE_MATRIX is not supported yet");
436:     break;
437:   }
438:   return(0);
439: }

441: PetscErrorCode MatGetLocalSubMatrix_Nest(Mat A,IS isrow,IS iscol,Mat *B)
442: {
444:   Mat_Nest       *vs = (Mat_Nest*)A->data;
445:   Mat            sub;

448:   MatNestFindSubMat(A,&vs->islocal,isrow,iscol,&sub);
449:   /* We allow the submatrix to be NULL, perhaps it would be better for the user to return an empty matrix instead */
450:   if (sub) {PetscObjectReference((PetscObject)sub);}
451:   *B = sub;
452:   return(0);
453: }

455: static PetscErrorCode MatRestoreLocalSubMatrix_Nest(Mat A,IS isrow,IS iscol,Mat *B)
456: {
458:   Mat_Nest       *vs = (Mat_Nest*)A->data;
459:   Mat            sub;

462:   MatNestFindSubMat(A,&vs->islocal,isrow,iscol,&sub);
463:   if (*B != sub) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Local submatrix has not been gotten");
464:   if (sub) {
465:     if (((PetscObject)sub)->refct <= 1) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Local submatrix has had reference count decremented too many times");
466:     MatDestroy(B);
467:   }
468:   return(0);
469: }

471: static PetscErrorCode MatGetDiagonal_Nest(Mat A,Vec v)
472: {
473:   Mat_Nest       *bA = (Mat_Nest*)A->data;
474:   PetscInt       i;

478:   for (i=0; i<bA->nr; i++) {
479:     Vec bv;
480:     VecGetSubVector(v,bA->isglobal.row[i],&bv);
481:     if (bA->m[i][i]) {
482:       MatGetDiagonal(bA->m[i][i],bv);
483:     } else {
484:       VecSet(bv,0.0);
485:     }
486:     VecRestoreSubVector(v,bA->isglobal.row[i],&bv);
487:   }
488:   return(0);
489: }

491: static PetscErrorCode MatDiagonalScale_Nest(Mat A,Vec l,Vec r)
492: {
493:   Mat_Nest       *bA = (Mat_Nest*)A->data;
494:   Vec            bl,*br;
495:   PetscInt       i,j;

499:   PetscCalloc1(bA->nc,&br);
500:   if (r) {
501:     for (j=0; j<bA->nc; j++) {VecGetSubVector(r,bA->isglobal.col[j],&br[j]);}
502:   }
503:   bl = NULL;
504:   for (i=0; i<bA->nr; i++) {
505:     if (l) {
506:       VecGetSubVector(l,bA->isglobal.row[i],&bl);
507:     }
508:     for (j=0; j<bA->nc; j++) {
509:       if (bA->m[i][j]) {
510:         MatDiagonalScale(bA->m[i][j],bl,br[j]);
511:       }
512:     }
513:     if (l) {
514:       VecRestoreSubVector(l,bA->isglobal.row[i],&bl);
515:     }
516:   }
517:   if (r) {
518:     for (j=0; j<bA->nc; j++) {VecRestoreSubVector(r,bA->isglobal.col[j],&br[j]);}
519:   }
520:   PetscFree(br);
521:   return(0);
522: }

524: static PetscErrorCode MatScale_Nest(Mat A,PetscScalar a)
525: {
526:   Mat_Nest       *bA = (Mat_Nest*)A->data;
527:   PetscInt       i,j;

531:   for (i=0; i<bA->nr; i++) {
532:     for (j=0; j<bA->nc; j++) {
533:       if (bA->m[i][j]) {
534:         MatScale(bA->m[i][j],a);
535:       }
536:     }
537:   }
538:   return(0);
539: }

541: static PetscErrorCode MatShift_Nest(Mat A,PetscScalar a)
542: {
543:   Mat_Nest       *bA = (Mat_Nest*)A->data;
544:   PetscInt       i;

548:   for (i=0; i<bA->nr; i++) {
549:     if (!bA->m[i][i]) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support for shifting an empty diagonal block, insert a matrix in block (%D,%D)",i,i);
550:     MatShift(bA->m[i][i],a);
551:   }
552:   return(0);
553: }

555: static PetscErrorCode MatDiagonalSet_Nest(Mat A,Vec D,InsertMode is)
556: {
557:   Mat_Nest       *bA = (Mat_Nest*)A->data;
558:   PetscInt       i;

562:   for (i=0; i<bA->nr; i++) {
563:     Vec bv;
564:     VecGetSubVector(D,bA->isglobal.row[i],&bv);
565:     if (bA->m[i][i]) {
566:       MatDiagonalSet(bA->m[i][i],bv,is);
567:     }
568:     VecRestoreSubVector(D,bA->isglobal.row[i],&bv);
569:   }
570:   return(0);
571: }

573: static PetscErrorCode MatSetRandom_Nest(Mat A,PetscRandom rctx)
574: {
575:   Mat_Nest       *bA = (Mat_Nest*)A->data;
576:   PetscInt       i,j;

580:   for (i=0; i<bA->nr; i++) {
581:     for (j=0; j<bA->nc; j++) {
582:       if (bA->m[i][j]) {
583:         MatSetRandom(bA->m[i][j],rctx);
584:       }
585:     }
586:   }
587:   return(0);
588: }

590: static PetscErrorCode MatCreateVecs_Nest(Mat A,Vec *right,Vec *left)
591: {
592:   Mat_Nest       *bA = (Mat_Nest*)A->data;
593:   Vec            *L,*R;
594:   MPI_Comm       comm;
595:   PetscInt       i,j;

599:   PetscObjectGetComm((PetscObject)A,&comm);
600:   if (right) {
601:     /* allocate R */
602:     PetscMalloc1(bA->nc, &R);
603:     /* Create the right vectors */
604:     for (j=0; j<bA->nc; j++) {
605:       for (i=0; i<bA->nr; i++) {
606:         if (bA->m[i][j]) {
607:           MatCreateVecs(bA->m[i][j],&R[j],NULL);
608:           break;
609:         }
610:       }
611:       if (i==bA->nr) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Mat(Nest) contains a null column.");
612:     }
613:     VecCreateNest(comm,bA->nc,bA->isglobal.col,R,right);
614:     /* hand back control to the nest vector */
615:     for (j=0; j<bA->nc; j++) {
616:       VecDestroy(&R[j]);
617:     }
618:     PetscFree(R);
619:   }

621:   if (left) {
622:     /* allocate L */
623:     PetscMalloc1(bA->nr, &L);
624:     /* Create the left vectors */
625:     for (i=0; i<bA->nr; i++) {
626:       for (j=0; j<bA->nc; j++) {
627:         if (bA->m[i][j]) {
628:           MatCreateVecs(bA->m[i][j],NULL,&L[i]);
629:           break;
630:         }
631:       }
632:       if (j==bA->nc) SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Mat(Nest) contains a null row.");
633:     }

635:     VecCreateNest(comm,bA->nr,bA->isglobal.row,L,left);
636:     for (i=0; i<bA->nr; i++) {
637:       VecDestroy(&L[i]);
638:     }

640:     PetscFree(L);
641:   }
642:   return(0);
643: }

645: static PetscErrorCode MatView_Nest(Mat A,PetscViewer viewer)
646: {
647:   Mat_Nest       *bA = (Mat_Nest*)A->data;
648:   PetscBool      isascii;
649:   PetscInt       i,j;

653:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);
654:   if (isascii) {

656:     PetscViewerASCIIPrintf(viewer,"Matrix object: \n");
657:     PetscViewerASCIIPushTab(viewer);
658:     PetscViewerASCIIPrintf(viewer, "type=nest, rows=%D, cols=%D \n",bA->nr,bA->nc);

660:     PetscViewerASCIIPrintf(viewer,"MatNest structure: \n");
661:     for (i=0; i<bA->nr; i++) {
662:       for (j=0; j<bA->nc; j++) {
663:         MatType   type;
664:         char      name[256] = "",prefix[256] = "";
665:         PetscInt  NR,NC;
666:         PetscBool isNest = PETSC_FALSE;

668:         if (!bA->m[i][j]) {
669:           PetscViewerASCIIPrintf(viewer, "(%D,%D) : NULL \n",i,j);
670:           continue;
671:         }
672:         MatGetSize(bA->m[i][j],&NR,&NC);
673:         MatGetType(bA->m[i][j], &type);
674:         if (((PetscObject)bA->m[i][j])->name) {PetscSNPrintf(name,sizeof(name),"name=\"%s\", ",((PetscObject)bA->m[i][j])->name);}
675:         if (((PetscObject)bA->m[i][j])->prefix) {PetscSNPrintf(prefix,sizeof(prefix),"prefix=\"%s\", ",((PetscObject)bA->m[i][j])->prefix);}
676:         PetscObjectTypeCompare((PetscObject)bA->m[i][j],MATNEST,&isNest);

678:         PetscViewerASCIIPrintf(viewer,"(%D,%D) : %s%stype=%s, rows=%D, cols=%D \n",i,j,name,prefix,type,NR,NC);

680:         if (isNest) {
681:           PetscViewerASCIIPushTab(viewer);  /* push1 */
682:           MatView(bA->m[i][j],viewer);
683:           PetscViewerASCIIPopTab(viewer);    /* pop1 */
684:         }
685:       }
686:     }
687:     PetscViewerASCIIPopTab(viewer);    /* pop0 */
688:   }
689:   return(0);
690: }

692: static PetscErrorCode MatZeroEntries_Nest(Mat A)
693: {
694:   Mat_Nest       *bA = (Mat_Nest*)A->data;
695:   PetscInt       i,j;

699:   for (i=0; i<bA->nr; i++) {
700:     for (j=0; j<bA->nc; j++) {
701:       if (!bA->m[i][j]) continue;
702:       MatZeroEntries(bA->m[i][j]);
703:     }
704:   }
705:   return(0);
706: }

708: static PetscErrorCode MatCopy_Nest(Mat A,Mat B,MatStructure str)
709: {
710:   Mat_Nest       *bA = (Mat_Nest*)A->data,*bB = (Mat_Nest*)B->data;
711:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

715:   if (nr != bB->nr || nc != bB->nc) SETERRQ4(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"Cannot copy a Mat_Nest of block size (%D,%D) to a Mat_Nest of block size (%D,%D)",bB->nr,bB->nc,nr,nc);
716:   for (i=0; i<nr; i++) {
717:     for (j=0; j<nc; j++) {
718:       if (bA->m[i][j] && bB->m[i][j]) {
719:         MatCopy(bA->m[i][j],bB->m[i][j],str);
720:       } else if (bA->m[i][j] || bB->m[i][j]) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_INCOMP,"Matrix block does not exist at %D,%D",i,j);
721:     }
722:   }
723:   return(0);
724: }

726: static PetscErrorCode MatDuplicate_Nest(Mat A,MatDuplicateOption op,Mat *B)
727: {
728:   Mat_Nest       *bA = (Mat_Nest*)A->data;
729:   Mat            *b;
730:   PetscInt       i,j,nr = bA->nr,nc = bA->nc;

734:   PetscMalloc1(nr*nc,&b);
735:   for (i=0; i<nr; i++) {
736:     for (j=0; j<nc; j++) {
737:       if (bA->m[i][j]) {
738:         MatDuplicate(bA->m[i][j],op,&b[i*nc+j]);
739:       } else {
740:         b[i*nc+j] = NULL;
741:       }
742:     }
743:   }
744:   MatCreateNest(PetscObjectComm((PetscObject)A),nr,bA->isglobal.row,nc,bA->isglobal.col,b,B);
745:   /* Give the new MatNest exclusive ownership */
746:   for (i=0; i<nr*nc; i++) {
747:     MatDestroy(&b[i]);
748:   }
749:   PetscFree(b);

751:   MatAssemblyBegin(*B,MAT_FINAL_ASSEMBLY);
752:   MatAssemblyEnd(*B,MAT_FINAL_ASSEMBLY);
753:   return(0);
754: }

756: /* nest api */
757: PetscErrorCode MatNestGetSubMat_Nest(Mat A,PetscInt idxm,PetscInt jdxm,Mat *mat)
758: {
759:   Mat_Nest *bA = (Mat_Nest*)A->data;

762:   if (idxm >= bA->nr) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",idxm,bA->nr-1);
763:   if (jdxm >= bA->nc) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Col too large: row %D max %D",jdxm,bA->nc-1);
764:   *mat = bA->m[idxm][jdxm];
765:   return(0);
766: }

768: /*@
769:  MatNestGetSubMat - Returns a single, sub-matrix from a nest matrix.

771:  Not collective

773:  Input Parameters:
774: +   A  - nest matrix
775: .   idxm - index of the matrix within the nest matrix
776: -   jdxm - index of the matrix within the nest matrix

778:  Output Parameter:
779: .   sub - matrix at index idxm,jdxm within the nest matrix

781:  Level: developer

783: .seealso: MatNestGetSize(), MatNestGetSubMats()
784: @*/
785: PetscErrorCode  MatNestGetSubMat(Mat A,PetscInt idxm,PetscInt jdxm,Mat *sub)
786: {

790:   PetscUseMethod(A,"MatNestGetSubMat_C",(Mat,PetscInt,PetscInt,Mat*),(A,idxm,jdxm,sub));
791:   return(0);
792: }

794: PetscErrorCode MatNestSetSubMat_Nest(Mat A,PetscInt idxm,PetscInt jdxm,Mat mat)
795: {
796:   Mat_Nest       *bA = (Mat_Nest*)A->data;
797:   PetscInt       m,n,M,N,mi,ni,Mi,Ni;

801:   if (idxm >= bA->nr) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Row too large: row %D max %D",idxm,bA->nr-1);
802:   if (jdxm >= bA->nc) SETERRQ2(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Col too large: row %D max %D",jdxm,bA->nc-1);
803:   MatGetLocalSize(mat,&m,&n);
804:   MatGetSize(mat,&M,&N);
805:   ISGetLocalSize(bA->isglobal.row[idxm],&mi);
806:   ISGetSize(bA->isglobal.row[idxm],&Mi);
807:   ISGetLocalSize(bA->isglobal.col[jdxm],&ni);
808:   ISGetSize(bA->isglobal.col[jdxm],&Ni);
809:   if (M != Mi || N != Ni) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_INCOMP,"Submatrix dimension (%D,%D) incompatible with nest block (%D,%D)",M,N,Mi,Ni);
810:   if (m != mi || n != ni) SETERRQ4(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_INCOMP,"Submatrix local dimension (%D,%D) incompatible with nest block (%D,%D)",m,n,mi,ni);

812:   PetscObjectReference((PetscObject)mat);
813:   MatDestroy(&bA->m[idxm][jdxm]);
814:   bA->m[idxm][jdxm] = mat;
815:   return(0);
816: }

818: /*@
819:  MatNestSetSubMat - Set a single submatrix in the nest matrix.

821:  Logically collective on the submatrix communicator

823:  Input Parameters:
824: +   A  - nest matrix
825: .   idxm - index of the matrix within the nest matrix
826: .   jdxm - index of the matrix within the nest matrix
827: -   sub - matrix at index idxm,jdxm within the nest matrix

829:  Notes:
830:  The new submatrix must have the same size and communicator as that block of the nest.

832:  This increments the reference count of the submatrix.

834:  Level: developer

836: .seealso: MatNestSetSubMats(), MatNestGetSubMats()
837: @*/
838: PetscErrorCode  MatNestSetSubMat(Mat A,PetscInt idxm,PetscInt jdxm,Mat sub)
839: {

843:   PetscUseMethod(A,"MatNestSetSubMat_C",(Mat,PetscInt,PetscInt,Mat),(A,idxm,jdxm,sub));
844:   return(0);
845: }

847: PetscErrorCode MatNestGetSubMats_Nest(Mat A,PetscInt *M,PetscInt *N,Mat ***mat)
848: {
849:   Mat_Nest *bA = (Mat_Nest*)A->data;

852:   if (M)   *M   = bA->nr;
853:   if (N)   *N   = bA->nc;
854:   if (mat) *mat = bA->m;
855:   return(0);
856: }

858: /*@C
859:  MatNestGetSubMats - Returns the entire two dimensional array of matrices defining a nest matrix.

861:  Not collective

863:  Input Parameters:
864: .   A  - nest matrix

866:  Output Parameter:
867: +   M - number of rows in the nest matrix
868: .   N - number of cols in the nest matrix
869: -   mat - 2d array of matrices

871:  Notes:

873:  The user should not free the array mat.

875:  In Fortran, this routine has a calling sequence
876: $   call MatNestGetSubMats(A, M, N, mat, ierr)
877:  where the space allocated for the optional argument mat is assumed large enough (if provided).

879:  Level: developer

881: .seealso: MatNestGetSize(), MatNestGetSubMat()
882: @*/
883: PetscErrorCode  MatNestGetSubMats(Mat A,PetscInt *M,PetscInt *N,Mat ***mat)
884: {

888:   PetscUseMethod(A,"MatNestGetSubMats_C",(Mat,PetscInt*,PetscInt*,Mat***),(A,M,N,mat));
889:   return(0);
890: }

892: PetscErrorCode  MatNestGetSize_Nest(Mat A,PetscInt *M,PetscInt *N)
893: {
894:   Mat_Nest *bA = (Mat_Nest*)A->data;

897:   if (M) *M = bA->nr;
898:   if (N) *N = bA->nc;
899:   return(0);
900: }

902: /*@
903:  MatNestGetSize - Returns the size of the nest matrix.

905:  Not collective

907:  Input Parameters:
908: .   A  - nest matrix

910:  Output Parameter:
911: +   M - number of rows in the nested mat
912: -   N - number of cols in the nested mat

914:  Notes:

916:  Level: developer

918: .seealso: MatNestGetSubMat(), MatNestGetSubMats()
919: @*/
920: PetscErrorCode  MatNestGetSize(Mat A,PetscInt *M,PetscInt *N)
921: {

925:   PetscUseMethod(A,"MatNestGetSize_C",(Mat,PetscInt*,PetscInt*),(A,M,N));
926:   return(0);
927: }

929: static PetscErrorCode MatNestGetISs_Nest(Mat A,IS rows[],IS cols[])
930: {
931:   Mat_Nest *vs = (Mat_Nest*)A->data;
932:   PetscInt i;

935:   if (rows) for (i=0; i<vs->nr; i++) rows[i] = vs->isglobal.row[i];
936:   if (cols) for (i=0; i<vs->nc; i++) cols[i] = vs->isglobal.col[i];
937:   return(0);
938: }

940: /*@C
941:  MatNestGetISs - Returns the index sets partitioning the row and column spaces

943:  Not collective

945:  Input Parameters:
946: .   A  - nest matrix

948:  Output Parameter:
949: +   rows - array of row index sets
950: -   cols - array of column index sets

952:  Level: advanced

954:  Notes:
955:  The user must have allocated arrays of the correct size. The reference count is not increased on the returned ISs.

957: .seealso: MatNestGetSubMat(), MatNestGetSubMats(), MatNestGetSize(), MatNestGetLocalISs()
958: @*/
959: PetscErrorCode  MatNestGetISs(Mat A,IS rows[],IS cols[])
960: {

965:   PetscUseMethod(A,"MatNestGetISs_C",(Mat,IS[],IS[]),(A,rows,cols));
966:   return(0);
967: }

969: static PetscErrorCode MatNestGetLocalISs_Nest(Mat A,IS rows[],IS cols[])
970: {
971:   Mat_Nest *vs = (Mat_Nest*)A->data;
972:   PetscInt i;

975:   if (rows) for (i=0; i<vs->nr; i++) rows[i] = vs->islocal.row[i];
976:   if (cols) for (i=0; i<vs->nc; i++) cols[i] = vs->islocal.col[i];
977:   return(0);
978: }

980: /*@C
981:  MatNestGetLocalISs - Returns the index sets partitioning the row and column spaces

983:  Not collective

985:  Input Parameters:
986: .   A  - nest matrix

988:  Output Parameter:
989: +   rows - array of row index sets (or NULL to ignore)
990: -   cols - array of column index sets (or NULL to ignore)

992:  Level: advanced

994:  Notes:
995:  The user must have allocated arrays of the correct size. The reference count is not increased on the returned ISs.

997: .seealso: MatNestGetSubMat(), MatNestGetSubMats(), MatNestGetSize(), MatNestGetISs()
998: @*/
999: PetscErrorCode  MatNestGetLocalISs(Mat A,IS rows[],IS cols[])
1000: {

1005:   PetscUseMethod(A,"MatNestGetLocalISs_C",(Mat,IS[],IS[]),(A,rows,cols));
1006:   return(0);
1007: }

1009: PetscErrorCode  MatNestSetVecType_Nest(Mat A,VecType vtype)
1010: {
1012:   PetscBool      flg;

1015:   PetscStrcmp(vtype,VECNEST,&flg);
1016:   /* In reality, this only distinguishes VECNEST and "other" */
1017:   if (flg) A->ops->getvecs = MatCreateVecs_Nest;
1018:   else A->ops->getvecs = (PetscErrorCode (*)(Mat,Vec*,Vec*)) 0;
1019:   return(0);
1020: }

1022: /*@C
1023:  MatNestSetVecType - Sets the type of Vec returned by MatCreateVecs()

1025:  Not collective

1027:  Input Parameters:
1028: +  A  - nest matrix
1029: -  vtype - type to use for creating vectors

1031:  Notes:

1033:  Level: developer

1035: .seealso: MatCreateVecs()
1036: @*/
1037: PetscErrorCode  MatNestSetVecType(Mat A,VecType vtype)
1038: {

1042:   PetscTryMethod(A,"MatNestSetVecType_C",(Mat,VecType),(A,vtype));
1043:   return(0);
1044: }

1046: PetscErrorCode MatNestSetSubMats_Nest(Mat A,PetscInt nr,const IS is_row[],PetscInt nc,const IS is_col[],const Mat a[])
1047: {
1048:   Mat_Nest       *s = (Mat_Nest*)A->data;
1049:   PetscInt       i,j,m,n,M,N;

1053:   s->nr = nr;
1054:   s->nc = nc;

1056:   /* Create space for submatrices */
1057:   PetscMalloc1(nr,&s->m);
1058:   for (i=0; i<nr; i++) {
1059:     PetscMalloc1(nc,&s->m[i]);
1060:   }
1061:   for (i=0; i<nr; i++) {
1062:     for (j=0; j<nc; j++) {
1063:       s->m[i][j] = a[i*nc+j];
1064:       if (a[i*nc+j]) {
1065:         PetscObjectReference((PetscObject)a[i*nc+j]);
1066:       }
1067:     }
1068:   }

1070:   MatSetUp_NestIS_Private(A,nr,is_row,nc,is_col);

1072:   PetscMalloc1(nr,&s->row_len);
1073:   PetscMalloc1(nc,&s->col_len);
1074:   for (i=0; i<nr; i++) s->row_len[i]=-1;
1075:   for (j=0; j<nc; j++) s->col_len[j]=-1;

1077:   MatNestGetSizes_Private(A,&m,&n,&M,&N);

1079:   PetscLayoutSetSize(A->rmap,M);
1080:   PetscLayoutSetLocalSize(A->rmap,m);
1081:   PetscLayoutSetSize(A->cmap,N);
1082:   PetscLayoutSetLocalSize(A->cmap,n);

1084:   PetscLayoutSetUp(A->rmap);
1085:   PetscLayoutSetUp(A->cmap);

1087:   PetscCalloc2(nr,&s->left,nc,&s->right);
1088:   return(0);
1089: }

1091: /*@
1092:    MatNestSetSubMats - Sets the nested submatrices

1094:    Collective on Mat

1096:    Input Parameter:
1097: +  N - nested matrix
1098: .  nr - number of nested row blocks
1099: .  is_row - index sets for each nested row block, or NULL to make contiguous
1100: .  nc - number of nested column blocks
1101: .  is_col - index sets for each nested column block, or NULL to make contiguous
1102: -  a - row-aligned array of nr*nc submatrices, empty submatrices can be passed using NULL

1104:    Level: advanced

1106: .seealso: MatCreateNest(), MATNEST
1107: @*/
1108: PetscErrorCode MatNestSetSubMats(Mat A,PetscInt nr,const IS is_row[],PetscInt nc,const IS is_col[],const Mat a[])
1109: {
1111:   PetscInt       i,nr_nc;

1115:   if (nr < 0) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Number of rows cannot be negative");
1116:   if (nr && is_row) {
1119:   }
1120:   if (nc < 0) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_OUTOFRANGE,"Number of columns cannot be negative");
1121:   if (nc && is_col) {
1124:   }
1125:   nr_nc=nr*nc;
1127:   PetscUseMethod(A,"MatNestSetSubMats_C",(Mat,PetscInt,const IS[],PetscInt,const IS[],const Mat[]),(A,nr,is_row,nc,is_col,a));
1128:   return(0);
1129: }

1131: static PetscErrorCode MatNestCreateAggregateL2G_Private(Mat A,PetscInt n,const IS islocal[],const IS isglobal[],PetscBool colflg,ISLocalToGlobalMapping *ltog)
1132: {
1134:   PetscBool      flg;
1135:   PetscInt       i,j,m,mi,*ix;

1138:   for (i=0,m=0,flg=PETSC_FALSE; i<n; i++) {
1139:     if (islocal[i]) {
1140:       ISGetSize(islocal[i],&mi);
1141:       flg  = PETSC_TRUE;      /* We found a non-trivial entry */
1142:     } else {
1143:       ISGetSize(isglobal[i],&mi);
1144:     }
1145:     m += mi;
1146:   }
1147:   if (flg) {
1148:     PetscMalloc1(m,&ix);
1149:     for (i=0,n=0; i<n; i++) {
1150:       ISLocalToGlobalMapping smap = NULL;
1151:       VecScatter             scat;
1152:       IS                     isreq;
1153:       Vec                    lvec,gvec;
1154:       union {char padding[sizeof(PetscScalar)]; PetscInt integer;} *x;
1155:       Mat sub;

1157:       if (sizeof(*x) != sizeof(PetscScalar)) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"No support when scalars smaller than integers");
1158:       if (colflg) {
1159:         MatNestFindNonzeroSubMatRow(A,i,&sub);
1160:       } else {
1161:         MatNestFindNonzeroSubMatCol(A,i,&sub);
1162:       }
1163:       if (sub) {MatGetLocalToGlobalMapping(sub,&smap,NULL);}
1164:       if (islocal[i]) {
1165:         ISGetSize(islocal[i],&mi);
1166:       } else {
1167:         ISGetSize(isglobal[i],&mi);
1168:       }
1169:       for (j=0; j<mi; j++) ix[m+j] = j;
1170:       if (smap) {ISLocalToGlobalMappingApply(smap,mi,ix+m,ix+m);}
1171:       /*
1172:         Now we need to extract the monolithic global indices that correspond to the given split global indices.
1173:         In many/most cases, we only want MatGetLocalSubMatrix() to work, in which case we only need to know the size of the local spaces.
1174:         The approach here is ugly because it uses VecScatter to move indices.
1175:        */
1176:       VecCreateSeq(PETSC_COMM_SELF,mi,&lvec);
1177:       VecCreateMPI(((PetscObject)isglobal[i])->comm,mi,PETSC_DECIDE,&gvec);
1178:       ISCreateGeneral(((PetscObject)isglobal[i])->comm,mi,ix+m,PETSC_COPY_VALUES,&isreq);
1179:       VecScatterCreate(gvec,isreq,lvec,NULL,&scat);
1180:       VecGetArray(gvec,(PetscScalar**)&x);
1181:       for (j=0; j<mi; j++) x[j].integer = ix[m+j];
1182:       VecRestoreArray(gvec,(PetscScalar**)&x);
1183:       VecScatterBegin(scat,gvec,lvec,INSERT_VALUES,SCATTER_FORWARD);
1184:       VecScatterEnd(scat,gvec,lvec,INSERT_VALUES,SCATTER_FORWARD);
1185:       VecGetArray(lvec,(PetscScalar**)&x);
1186:       for (j=0; j<mi; j++) ix[m+j] = x[j].integer;
1187:       VecRestoreArray(lvec,(PetscScalar**)&x);
1188:       VecDestroy(&lvec);
1189:       VecDestroy(&gvec);
1190:       ISDestroy(&isreq);
1191:       VecScatterDestroy(&scat);
1192:       m   += mi;
1193:     }
1194:     ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)A),1,m,ix,PETSC_OWN_POINTER,ltog);
1195:   } else {
1196:     *ltog  = NULL;
1197:   }
1198:   return(0);
1199: }


1202: /* If an IS was provided, there is nothing Nest needs to do, otherwise Nest will build a strided IS */
1203: /*
1204:   nprocessors = NP
1205:   Nest x^T = ((g_0,g_1,...g_nprocs-1), (h_0,h_1,...h_NP-1))
1206:        proc 0: => (g_0,h_0,)
1207:        proc 1: => (g_1,h_1,)
1208:        ...
1209:        proc nprocs-1: => (g_NP-1,h_NP-1,)

1211:             proc 0:                      proc 1:                    proc nprocs-1:
1212:     is[0] = (0,1,2,...,nlocal(g_0)-1)  (0,1,...,nlocal(g_1)-1)  (0,1,...,nlocal(g_NP-1))

1214:             proc 0:
1215:     is[1] = (nlocal(g_0),nlocal(g_0)+1,...,nlocal(g_0)+nlocal(h_0)-1)
1216:             proc 1:
1217:     is[1] = (nlocal(g_1),nlocal(g_1)+1,...,nlocal(g_1)+nlocal(h_1)-1)

1219:             proc NP-1:
1220:     is[1] = (nlocal(g_NP-1),nlocal(g_NP-1)+1,...,nlocal(g_NP-1)+nlocal(h_NP-1)-1)
1221: */
1222: static PetscErrorCode MatSetUp_NestIS_Private(Mat A,PetscInt nr,const IS is_row[],PetscInt nc,const IS is_col[])
1223: {
1224:   Mat_Nest       *vs = (Mat_Nest*)A->data;
1225:   PetscInt       i,j,offset,n,nsum,bs;
1227:   Mat            sub = NULL;

1230:   PetscMalloc1(nr,&vs->isglobal.row);
1231:   PetscMalloc1(nc,&vs->isglobal.col);
1232:   if (is_row) { /* valid IS is passed in */
1233:     /* refs on is[] are incremeneted */
1234:     for (i=0; i<vs->nr; i++) {
1235:       PetscObjectReference((PetscObject)is_row[i]);

1237:       vs->isglobal.row[i] = is_row[i];
1238:     }
1239:   } else {                      /* Create the ISs by inspecting sizes of a submatrix in each row */
1240:     nsum = 0;
1241:     for (i=0; i<vs->nr; i++) {  /* Add up the local sizes to compute the aggregate offset */
1242:       MatNestFindNonzeroSubMatRow(A,i,&sub);
1243:       if (!sub) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"No nonzero submatrix in row %D",i);
1244:       MatGetLocalSize(sub,&n,NULL);
1245:       if (n < 0) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Sizes have not yet been set for submatrix");
1246:       nsum += n;
1247:     }
1248:     MPI_Scan(&nsum,&offset,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)A));
1249:     offset -= nsum;
1250:     for (i=0; i<vs->nr; i++) {
1251:       MatNestFindNonzeroSubMatRow(A,i,&sub);
1252:       MatGetLocalSize(sub,&n,NULL);
1253:       MatGetBlockSize(sub,&bs);
1254:       ISCreateStride(PetscObjectComm((PetscObject)sub),n,offset,1,&vs->isglobal.row[i]);
1255:       ISSetBlockSize(vs->isglobal.row[i],bs);
1256:       offset += n;
1257:     }
1258:   }

1260:   if (is_col) { /* valid IS is passed in */
1261:     /* refs on is[] are incremeneted */
1262:     for (j=0; j<vs->nc; j++) {
1263:       PetscObjectReference((PetscObject)is_col[j]);

1265:       vs->isglobal.col[j] = is_col[j];
1266:     }
1267:   } else {                      /* Create the ISs by inspecting sizes of a submatrix in each column */
1268:     offset = A->cmap->rstart;
1269:     nsum   = 0;
1270:     for (j=0; j<vs->nc; j++) {
1271:       MatNestFindNonzeroSubMatCol(A,j,&sub);
1272:       if (!sub) SETERRQ1(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONG,"No nonzero submatrix in column %D",i);
1273:       MatGetLocalSize(sub,NULL,&n);
1274:       if (n < 0) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_ARG_WRONGSTATE,"Sizes have not yet been set for submatrix");
1275:       nsum += n;
1276:     }
1277:     MPI_Scan(&nsum,&offset,1,MPIU_INT,MPI_SUM,PetscObjectComm((PetscObject)A));
1278:     offset -= nsum;
1279:     for (j=0; j<vs->nc; j++) {
1280:       MatNestFindNonzeroSubMatCol(A,j,&sub);
1281:       MatGetLocalSize(sub,NULL,&n);
1282:       MatGetBlockSize(sub,&bs);
1283:       ISCreateStride(PetscObjectComm((PetscObject)sub),n,offset,1,&vs->isglobal.col[j]);
1284:       ISSetBlockSize(vs->isglobal.col[j],bs);
1285:       offset += n;
1286:     }
1287:   }

1289:   /* Set up the local ISs */
1290:   PetscMalloc1(vs->nr,&vs->islocal.row);
1291:   PetscMalloc1(vs->nc,&vs->islocal.col);
1292:   for (i=0,offset=0; i<vs->nr; i++) {
1293:     IS                     isloc;
1294:     ISLocalToGlobalMapping rmap = NULL;
1295:     PetscInt               nlocal,bs;
1296:     MatNestFindNonzeroSubMatRow(A,i,&sub);
1297:     if (sub) {MatGetLocalToGlobalMapping(sub,&rmap,NULL);}
1298:     if (rmap) {
1299:       MatGetBlockSize(sub,&bs);
1300:       ISLocalToGlobalMappingGetSize(rmap,&nlocal);
1301:       ISCreateStride(PETSC_COMM_SELF,nlocal,offset,1,&isloc);
1302:       ISSetBlockSize(isloc,bs);
1303:     } else {
1304:       nlocal = 0;
1305:       isloc  = NULL;
1306:     }
1307:     vs->islocal.row[i] = isloc;
1308:     offset            += nlocal;
1309:   }
1310:   for (i=0,offset=0; i<vs->nc; i++) {
1311:     IS                     isloc;
1312:     ISLocalToGlobalMapping cmap = NULL;
1313:     PetscInt               nlocal,bs;
1314:     MatNestFindNonzeroSubMatCol(A,i,&sub);
1315:     if (sub) {MatGetLocalToGlobalMapping(sub,NULL,&cmap);}
1316:     if (cmap) {
1317:       MatGetBlockSize(sub,&bs);
1318:       ISLocalToGlobalMappingGetSize(cmap,&nlocal);
1319:       ISCreateStride(PETSC_COMM_SELF,nlocal,offset,1,&isloc);
1320:       ISSetBlockSize(isloc,bs);
1321:     } else {
1322:       nlocal = 0;
1323:       isloc  = NULL;
1324:     }
1325:     vs->islocal.col[i] = isloc;
1326:     offset            += nlocal;
1327:   }

1329:   /* Set up the aggregate ISLocalToGlobalMapping */
1330:   {
1331:     ISLocalToGlobalMapping rmap,cmap;
1332:     MatNestCreateAggregateL2G_Private(A,vs->nr,vs->islocal.row,vs->isglobal.row,PETSC_FALSE,&rmap);
1333:     MatNestCreateAggregateL2G_Private(A,vs->nc,vs->islocal.col,vs->isglobal.col,PETSC_TRUE,&cmap);
1334:     if (rmap && cmap) {MatSetLocalToGlobalMapping(A,rmap,cmap);}
1335:     ISLocalToGlobalMappingDestroy(&rmap);
1336:     ISLocalToGlobalMappingDestroy(&cmap);
1337:   }

1339: #if defined(PETSC_USE_DEBUG)
1340:   for (i=0; i<vs->nr; i++) {
1341:     for (j=0; j<vs->nc; j++) {
1342:       PetscInt m,n,M,N,mi,ni,Mi,Ni;
1343:       Mat      B = vs->m[i][j];
1344:       if (!B) continue;
1345:       MatGetSize(B,&M,&N);
1346:       MatGetLocalSize(B,&m,&n);
1347:       ISGetSize(vs->isglobal.row[i],&Mi);
1348:       ISGetSize(vs->isglobal.col[j],&Ni);
1349:       ISGetLocalSize(vs->isglobal.row[i],&mi);
1350:       ISGetLocalSize(vs->isglobal.col[j],&ni);
1351:       if (M != Mi || N != Ni) SETERRQ6(PetscObjectComm((PetscObject)sub),PETSC_ERR_ARG_INCOMP,"Global sizes (%D,%D) of nested submatrix (%D,%D) do not agree with space defined by index sets (%D,%D)",M,N,i,j,Mi,Ni);
1352:       if (m != mi || n != ni) SETERRQ6(PetscObjectComm((PetscObject)sub),PETSC_ERR_ARG_INCOMP,"Local sizes (%D,%D) of nested submatrix (%D,%D) do not agree with space defined by index sets (%D,%D)",m,n,i,j,mi,ni);
1353:     }
1354:   }
1355: #endif

1357:   /* Set A->assembled if all non-null blocks are currently assembled */
1358:   for (i=0; i<vs->nr; i++) {
1359:     for (j=0; j<vs->nc; j++) {
1360:       if (vs->m[i][j] && !vs->m[i][j]->assembled) return(0);
1361:     }
1362:   }
1363:   A->assembled = PETSC_TRUE;
1364:   return(0);
1365: }

1367: /*@C
1368:    MatCreateNest - Creates a new matrix containing several nested submatrices, each stored separately

1370:    Collective on Mat

1372:    Input Parameter:
1373: +  comm - Communicator for the new Mat
1374: .  nr - number of nested row blocks
1375: .  is_row - index sets for each nested row block, or NULL to make contiguous
1376: .  nc - number of nested column blocks
1377: .  is_col - index sets for each nested column block, or NULL to make contiguous
1378: -  a - row-aligned array of nr*nc submatrices, empty submatrices can be passed using NULL

1380:    Output Parameter:
1381: .  B - new matrix

1383:    Level: advanced

1385: .seealso: MatCreate(), VecCreateNest(), DMCreateMatrix(), MATNEST
1386: @*/
1387: PetscErrorCode MatCreateNest(MPI_Comm comm,PetscInt nr,const IS is_row[],PetscInt nc,const IS is_col[],const Mat a[],Mat *B)
1388: {
1389:   Mat            A;

1393:   *B   = 0;
1394:   MatCreate(comm,&A);
1395:   MatSetType(A,MATNEST);
1396:   A->preallocated = PETSC_TRUE;
1397:   MatNestSetSubMats(A,nr,is_row,nc,is_col,a);
1398:   *B   = A;
1399:   return(0);
1400: }

1402: static PetscErrorCode MatConvert_Nest_SeqAIJ_fast(Mat A,MatType newtype,MatReuse reuse,Mat *newmat)
1403: {
1404:   Mat_Nest       *nest = (Mat_Nest*)A->data;
1405:   Mat            *trans;
1406:   PetscScalar    **avv;
1407:   PetscScalar    *vv;
1408:   PetscInt       **aii,**ajj;
1409:   PetscInt       *ii,*jj,*ci;
1410:   PetscInt       nr,nc,nnz,i,j;
1411:   PetscBool      done;

1415:   MatGetSize(A,&nr,&nc);
1416:   if (reuse == MAT_REUSE_MATRIX) {
1417:     PetscInt rnr;

1419:     MatGetRowIJ(*newmat,0,PETSC_FALSE,PETSC_FALSE,&rnr,(const PetscInt**)&ii,(const PetscInt**)&jj,&done);
1420:     if (!done) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_PLIB,"MatGetRowIJ");
1421:     if (rnr != nr) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_USER,"Cannot reuse matrix, wrong number of rows");
1422:     MatSeqAIJGetArray(*newmat,&vv);
1423:   }
1424:   /* extract CSR for nested SeqAIJ matrices */
1425:   nnz  = 0;
1426:   PetscCalloc4(nest->nr*nest->nc,&aii,nest->nr*nest->nc,&ajj,nest->nr*nest->nc,&avv,nest->nr*nest->nc,&trans);
1427:   for (i=0; i<nest->nr; ++i) {
1428:     for (j=0; j<nest->nc; ++j) {
1429:       Mat B = nest->m[i][j];
1430:       if (B) {
1431:         PetscScalar *naa;
1432:         PetscInt    *nii,*njj,nnr;
1433:         PetscBool   istrans;

1435:         PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);
1436:         if (istrans) {
1437:           Mat Bt;

1439:           MatTransposeGetMat(B,&Bt);
1440:           MatTranspose(Bt,MAT_INITIAL_MATRIX,&trans[i*nest->nc+j]);
1441:           B    = trans[i*nest->nc+j];
1442:         }
1443:         MatGetRowIJ(B,0,PETSC_FALSE,PETSC_FALSE,&nnr,(const PetscInt**)&nii,(const PetscInt**)&njj,&done);
1444:         if (!done) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_PLIB,"MatGetRowIJ");
1445:         MatSeqAIJGetArray(B,&naa);
1446:         nnz += nii[nnr];

1448:         aii[i*nest->nc+j] = nii;
1449:         ajj[i*nest->nc+j] = njj;
1450:         avv[i*nest->nc+j] = naa;
1451:       }
1452:     }
1453:   }
1454:   if (reuse != MAT_REUSE_MATRIX) {
1455:     PetscMalloc1(nr+1,&ii);
1456:     PetscMalloc1(nnz,&jj);
1457:     PetscMalloc1(nnz,&vv);
1458:   } else {
1459:     if (nnz != ii[nr]) SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_USER,"Cannot reuse matrix, wrong number of nonzeros");
1460:   }

1462:   /* new row pointer */
1463:   PetscMemzero(ii,(nr+1)*sizeof(PetscInt));
1464:   for (i=0; i<nest->nr; ++i) {
1465:     PetscInt       ncr,rst;

1467:     ISStrideGetInfo(nest->isglobal.row[i],&rst,NULL);
1468:     ISGetLocalSize(nest->isglobal.row[i],&ncr);
1469:     for (j=0; j<nest->nc; ++j) {
1470:       if (aii[i*nest->nc+j]) {
1471:         PetscInt    *nii = aii[i*nest->nc+j];
1472:         PetscInt    ir;

1474:         for (ir=rst; ir<ncr+rst; ++ir) {
1475:           ii[ir+1] += nii[1]-nii[0];
1476:           nii++;
1477:         }
1478:       }
1479:     }
1480:   }
1481:   for (i=0; i<nr; i++) ii[i+1] += ii[i];

1483:   /* construct CSR for the new matrix */
1484:   PetscCalloc1(nr,&ci);
1485:   for (i=0; i<nest->nr; ++i) {
1486:     PetscInt       ncr,rst;

1488:     ISStrideGetInfo(nest->isglobal.row[i],&rst,NULL);
1489:     ISGetLocalSize(nest->isglobal.row[i],&ncr);
1490:     for (j=0; j<nest->nc; ++j) {
1491:       if (aii[i*nest->nc+j]) {
1492:         PetscScalar *nvv = avv[i*nest->nc+j];
1493:         PetscInt    *nii = aii[i*nest->nc+j];
1494:         PetscInt    *njj = ajj[i*nest->nc+j];
1495:         PetscInt    ir,cst;

1497:         ISStrideGetInfo(nest->isglobal.col[j],&cst,NULL);
1498:         for (ir=rst; ir<ncr+rst; ++ir) {
1499:           PetscInt ij,rsize = nii[1]-nii[0],ist = ii[ir]+ci[ir];

1501:           for (ij=0;ij<rsize;ij++) {
1502:             jj[ist+ij] = *njj+cst;
1503:             vv[ist+ij] = *nvv;
1504:             njj++;
1505:             nvv++;
1506:           }
1507:           ci[ir] += rsize;
1508:           nii++;
1509:         }
1510:       }
1511:     }
1512:   }
1513:   PetscFree(ci);

1515:   /* restore info */
1516:   for (i=0; i<nest->nr; ++i) {
1517:     for (j=0; j<nest->nc; ++j) {
1518:       Mat B = nest->m[i][j];
1519:       if (B) {
1520:         PetscInt nnr = 0, k = i*nest->nc+j;

1522:         B    = (trans[k] ? trans[k] : B);
1523:         MatRestoreRowIJ(B,0,PETSC_FALSE,PETSC_FALSE,&nnr,(const PetscInt**)&aii[k],(const PetscInt**)&ajj[k],&done);
1524:         if (!done) SETERRQ(PetscObjectComm((PetscObject)B),PETSC_ERR_PLIB,"MatRestoreRowIJ");
1525:         MatSeqAIJRestoreArray(B,&avv[k]);
1526:         MatDestroy(&trans[k]);
1527:       }
1528:     }
1529:   }
1530:   PetscFree4(aii,ajj,avv,trans);

1532:   /* finalize newmat */
1533:   if (reuse == MAT_INITIAL_MATRIX) {
1534:     MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A),nr,nc,ii,jj,vv,newmat);
1535:   } else if (reuse == MAT_INPLACE_MATRIX) {
1536:     Mat B;

1538:     MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A),nr,nc,ii,jj,vv,&B);
1539:     MatHeaderReplace(A,&B);
1540:   }
1541:   MatAssemblyBegin(*newmat,MAT_FINAL_ASSEMBLY);
1542:   MatAssemblyEnd(*newmat,MAT_FINAL_ASSEMBLY);
1543:   {
1544:     Mat_SeqAIJ *a = (Mat_SeqAIJ*)((*newmat)->data);
1545:     a->free_a     = PETSC_TRUE;
1546:     a->free_ij    = PETSC_TRUE;
1547:   }
1548:   return(0);
1549: }

1551: PETSC_INTERN PetscErrorCode MatConvert_Nest_AIJ(Mat A,MatType newtype,MatReuse reuse,Mat *newmat)
1552: {
1554:   Mat_Nest       *nest = (Mat_Nest*)A->data;
1555:   PetscInt       m,n,M,N,i,j,k,*dnnz,*onnz,rstart;
1556:   PetscInt       cstart,cend;
1557:   PetscMPIInt    size;
1558:   Mat            C;

1561:   MPI_Comm_size(PetscObjectComm((PetscObject)A),&size);
1562:   if (size == 1) { /* look for a special case with SeqAIJ matrices and strided-1, contiguous, blocks */
1563:     PetscInt  nf;
1564:     PetscBool fast;

1566:     PetscStrcmp(newtype,MATAIJ,&fast);
1567:     if (!fast) {
1568:       PetscStrcmp(newtype,MATSEQAIJ,&fast);
1569:     }
1570:     for (i=0; i<nest->nr && fast; ++i) {
1571:       for (j=0; j<nest->nc && fast; ++j) {
1572:         Mat B = nest->m[i][j];
1573:         if (B) {
1574:           PetscObjectTypeCompare((PetscObject)B,MATSEQAIJ,&fast);
1575:           if (!fast) {
1576:             PetscBool istrans;

1578:             PetscObjectTypeCompare((PetscObject)B,MATTRANSPOSEMAT,&istrans);
1579:             if (istrans) {
1580:               Mat Bt;

1582:               MatTransposeGetMat(B,&Bt);
1583:               PetscObjectTypeCompare((PetscObject)Bt,MATSEQAIJ,&fast);
1584:             }
1585:           }
1586:         }
1587:       }
1588:     }
1589:     for (i=0, nf=0; i<nest->nr && fast; ++i) {
1590:       PetscObjectTypeCompare((PetscObject)nest->isglobal.row[i],ISSTRIDE,&fast);
1591:       if (fast) {
1592:         PetscInt f,s;

1594:         ISStrideGetInfo(nest->isglobal.row[i],&f,&s);
1595:         if (f != nf || s != 1) { fast = PETSC_FALSE; }
1596:         else {
1597:           ISGetSize(nest->isglobal.row[i],&f);
1598:           nf  += f;
1599:         }
1600:       }
1601:     }
1602:     for (i=0, nf=0; i<nest->nc && fast; ++i) {
1603:       PetscObjectTypeCompare((PetscObject)nest->isglobal.col[i],ISSTRIDE,&fast);
1604:       if (fast) {
1605:         PetscInt f,s;

1607:         ISStrideGetInfo(nest->isglobal.col[i],&f,&s);
1608:         if (f != nf || s != 1) { fast = PETSC_FALSE; }
1609:         else {
1610:           ISGetSize(nest->isglobal.col[i],&f);
1611:           nf  += f;
1612:         }
1613:       }
1614:     }
1615:     if (fast) {
1616:       MatConvert_Nest_SeqAIJ_fast(A,newtype,reuse,newmat);
1617:       return(0);
1618:     }
1619:   }
1620:   MatGetSize(A,&M,&N);
1621:   MatGetLocalSize(A,&m,&n);
1622:   MatGetOwnershipRangeColumn(A,&cstart,&cend);
1623:   switch (reuse) {
1624:   case MAT_INITIAL_MATRIX:
1625:     MatCreate(PetscObjectComm((PetscObject)A),&C);
1626:     MatSetType(C,newtype);
1627:     MatSetSizes(C,m,n,M,N);
1628:     *newmat = C;
1629:     break;
1630:   case MAT_REUSE_MATRIX:
1631:     C = *newmat;
1632:     break;
1633:   default: SETERRQ(PetscObjectComm((PetscObject)A),PETSC_ERR_SUP,"MatReuse");
1634:   }
1635:   PetscMalloc1(2*m,&dnnz);
1636:   onnz = dnnz + m;
1637:   for (k=0; k<m; k++) {
1638:     dnnz[k] = 0;
1639:     onnz[k] = 0;
1640:   }
1641:   for (j=0; j<nest->nc; ++j) {
1642:     IS             bNis;
1643:     PetscInt       bN;
1644:     const PetscInt *bNindices;
1645:     /* Using global column indices and ISAllGather() is not scalable. */
1646:     ISAllGather(nest->isglobal.col[j], &bNis);
1647:     ISGetSize(bNis, &bN);
1648:     ISGetIndices(bNis,&bNindices);
1649:     for (i=0; i<nest->nr; ++i) {
1650:       PetscSF        bmsf;
1651:       PetscSFNode    *iremote;
1652:       Mat            B;
1653:       PetscInt       bm, *sub_dnnz,*sub_onnz, br;
1654:       const PetscInt *bmindices;
1655:       B = nest->m[i][j];
1656:       if (!B) continue;
1657:       ISGetLocalSize(nest->isglobal.row[i],&bm);
1658:       ISGetIndices(nest->isglobal.row[i],&bmindices);
1659:       PetscSFCreate(PetscObjectComm((PetscObject)A), &bmsf);
1660:       PetscMalloc1(bm,&iremote);
1661:       PetscMalloc1(bm,&sub_dnnz);
1662:       PetscMalloc1(bm,&sub_onnz);
1663:       for (k = 0; k < bm; ++k){
1664:             sub_dnnz[k] = 0;
1665:             sub_onnz[k] = 0;
1666:       }
1667:       /*
1668:        Locate the owners for all of the locally-owned global row indices for this row block.
1669:        These determine the roots of PetscSF used to communicate preallocation data to row owners.
1670:        The roots correspond to the dnnz and onnz entries; thus, there are two roots per row.
1671:        */
1672:       MatGetOwnershipRange(B,&rstart,NULL);
1673:       for (br = 0; br < bm; ++br) {
1674:         PetscInt       row = bmindices[br], rowowner = 0, brncols, col;
1675:         const PetscInt *brcols;
1676:         PetscInt       rowrel = 0; /* row's relative index on its owner rank */
1677:         PetscLayoutFindOwnerIndex(A->rmap,row,&rowowner,&rowrel);
1678:         /* how many roots  */
1679:         iremote[br].rank = rowowner; iremote[br].index = rowrel;           /* edge from bmdnnz to dnnz */
1680:         /* get nonzero pattern */
1681:         MatGetRow(B,br+rstart,&brncols,&brcols,NULL);
1682:         for (k=0; k<brncols; k++) {
1683:           col  = bNindices[brcols[k]];
1684:           if (col>=A->cmap->range[rowowner] && col<A->cmap->range[rowowner+1]) {
1685:             sub_dnnz[br]++;
1686:           } else {
1687:             sub_onnz[br]++;
1688:           }
1689:         }
1690:         MatRestoreRow(B,br+rstart,&brncols,&brcols,NULL);
1691:       }
1692:       ISRestoreIndices(nest->isglobal.row[i],&bmindices);
1693:       /* bsf will have to take care of disposing of bedges. */
1694:       PetscSFSetGraph(bmsf,m,bm,NULL,PETSC_OWN_POINTER,iremote,PETSC_OWN_POINTER);
1695:       PetscSFReduceBegin(bmsf,MPIU_INT,sub_dnnz,dnnz,MPI_SUM);
1696:       PetscSFReduceEnd(bmsf,MPIU_INT,sub_dnnz,dnnz,MPI_SUM);
1697:       PetscSFReduceBegin(bmsf,MPIU_INT,sub_onnz,onnz,MPI_SUM);
1698:       PetscSFReduceEnd(bmsf,MPIU_INT,sub_onnz,onnz,MPI_SUM);
1699:       PetscFree(sub_dnnz);
1700:       PetscFree(sub_onnz);
1701:       PetscSFDestroy(&bmsf);
1702:     }
1703:     ISRestoreIndices(bNis,&bNindices);
1704:     ISDestroy(&bNis);
1705:   }
1706:   /* Resize preallocation if overestimated */
1707:   for (i=0;i<m;i++) {
1708:     dnnz[i] = PetscMin(dnnz[i],A->cmap->n);
1709:     onnz[i] = PetscMin(onnz[i],A->cmap->N - A->cmap->n);
1710:   }
1711:   MatSeqAIJSetPreallocation(C,0,dnnz);
1712:   MatMPIAIJSetPreallocation(C,0,dnnz,0,onnz);
1713:   PetscFree(dnnz);

1715:   /* Fill by row */
1716:   for (j=0; j<nest->nc; ++j) {
1717:     /* Using global column indices and ISAllGather() is not scalable. */
1718:     IS             bNis;
1719:     PetscInt       bN;
1720:     const PetscInt *bNindices;
1721:     ISAllGather(nest->isglobal.col[j], &bNis);
1722:     ISGetSize(bNis,&bN);
1723:     ISGetIndices(bNis,&bNindices);
1724:     for (i=0; i<nest->nr; ++i) {
1725:       Mat            B;
1726:       PetscInt       bm, br;
1727:       const PetscInt *bmindices;
1728:       B = nest->m[i][j];
1729:       if (!B) continue;
1730:       ISGetLocalSize(nest->isglobal.row[i],&bm);
1731:       ISGetIndices(nest->isglobal.row[i],&bmindices);
1732:       MatGetOwnershipRange(B,&rstart,NULL);
1733:       for (br = 0; br < bm; ++br) {
1734:         PetscInt          row = bmindices[br], brncols,  *cols;
1735:         const PetscInt    *brcols;
1736:         const PetscScalar *brcoldata;
1737:         MatGetRow(B,br+rstart,&brncols,&brcols,&brcoldata);
1738:         PetscMalloc1(brncols,&cols);
1739:         for (k=0; k<brncols; k++) cols[k] = bNindices[brcols[k]];
1740:         /*
1741:           Nest blocks are required to be nonoverlapping -- otherwise nest and monolithic index layouts wouldn't match.
1742:           Thus, we could use INSERT_VALUES, but I prefer ADD_VALUES.
1743:          */
1744:         MatSetValues(C,1,&row,brncols,cols,brcoldata,ADD_VALUES);
1745:         MatRestoreRow(B,br+rstart,&brncols,&brcols,&brcoldata);
1746:         PetscFree(cols);
1747:       }
1748:       ISRestoreIndices(nest->isglobal.row[i],&bmindices);
1749:     }
1750:     ISRestoreIndices(bNis,&bNindices);
1751:     ISDestroy(&bNis);
1752:   }
1753:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
1754:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
1755:   return(0);
1756: }

1758: PetscErrorCode  MatHasOperation_Nest(Mat mat,MatOperation op,PetscBool  *has)
1759: {
1761:   *has = PETSC_FALSE;
1762:   if (op == MATOP_MULT_TRANSPOSE) {
1763:     Mat_Nest       *bA = (Mat_Nest*)mat->data;
1764:     PetscInt       i,j,nr = bA->nr,nc = bA->nc;
1766:     PetscBool      flg;

1768:     for (j=0; j<nc; j++) {
1769:       for (i=0; i<nr; i++) {
1770:         if (!bA->m[i][j]) continue;
1771:         MatHasOperation(bA->m[i][j],MATOP_MULT_TRANSPOSE_ADD,&flg);
1772:         if (!flg) return(0);
1773:       }
1774:     }
1775:   }
1776:   if (((void**)mat->ops)[op]) *has =  PETSC_TRUE;
1777:   return(0);
1778: }

1780: /*MC
1781:   MATNEST - MATNEST = "nest" - Matrix type consisting of nested submatrices, each stored separately.

1783:   Level: intermediate

1785:   Notes:
1786:   This matrix type permits scalable use of PCFieldSplit and avoids the large memory costs of extracting submatrices.
1787:   It allows the use of symmetric and block formats for parts of multi-physics simulations.
1788:   It is usually used with DMComposite and DMCreateMatrix()

1790:   Each of the submatrices lives on the same MPI communicator as the original nest matrix (though they can have zero
1791:   rows/columns on some processes.) Thus this is not meant for cases where the submatrices live on far fewer processes
1792:   than the nest matrix.

1794: .seealso: MatCreate(), MatType, MatCreateNest()
1795: M*/
1796: PETSC_EXTERN PetscErrorCode MatCreate_Nest(Mat A)
1797: {
1798:   Mat_Nest       *s;

1802:   PetscNewLog(A,&s);
1803:   A->data = (void*)s;

1805:   s->nr            = -1;
1806:   s->nc            = -1;
1807:   s->m             = NULL;
1808:   s->splitassembly = PETSC_FALSE;

1810:   PetscMemzero(A->ops,sizeof(*A->ops));

1812:   A->ops->mult                  = MatMult_Nest;
1813:   A->ops->multadd               = MatMultAdd_Nest;
1814:   A->ops->multtranspose         = MatMultTranspose_Nest;
1815:   A->ops->multtransposeadd      = MatMultTransposeAdd_Nest;
1816:   A->ops->transpose             = MatTranspose_Nest;
1817:   A->ops->assemblybegin         = MatAssemblyBegin_Nest;
1818:   A->ops->assemblyend           = MatAssemblyEnd_Nest;
1819:   A->ops->zeroentries           = MatZeroEntries_Nest;
1820:   A->ops->copy                  = MatCopy_Nest;
1821:   A->ops->duplicate             = MatDuplicate_Nest;
1822:   A->ops->createsubmatrix       = MatCreateSubMatrix_Nest;
1823:   A->ops->destroy               = MatDestroy_Nest;
1824:   A->ops->view                  = MatView_Nest;
1825:   A->ops->getvecs               = 0; /* Use VECNEST by calling MatNestSetVecType(A,VECNEST) */
1826:   A->ops->getlocalsubmatrix     = MatGetLocalSubMatrix_Nest;
1827:   A->ops->restorelocalsubmatrix = MatRestoreLocalSubMatrix_Nest;
1828:   A->ops->getdiagonal           = MatGetDiagonal_Nest;
1829:   A->ops->diagonalscale         = MatDiagonalScale_Nest;
1830:   A->ops->scale                 = MatScale_Nest;
1831:   A->ops->shift                 = MatShift_Nest;
1832:   A->ops->diagonalset           = MatDiagonalSet_Nest;
1833:   A->ops->setrandom             = MatSetRandom_Nest;
1834:   A->ops->hasoperation          = MatHasOperation_Nest;

1836:   A->spptr        = 0;
1837:   A->assembled    = PETSC_FALSE;

1839:   /* expose Nest api's */
1840:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSubMat_C",   MatNestGetSubMat_Nest);
1841:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetSubMat_C",   MatNestSetSubMat_Nest);
1842:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSubMats_C",  MatNestGetSubMats_Nest);
1843:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetSize_C",     MatNestGetSize_Nest);
1844:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetISs_C",      MatNestGetISs_Nest);
1845:   PetscObjectComposeFunction((PetscObject)A,"MatNestGetLocalISs_C", MatNestGetLocalISs_Nest);
1846:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetVecType_C",  MatNestSetVecType_Nest);
1847:   PetscObjectComposeFunction((PetscObject)A,"MatNestSetSubMats_C",  MatNestSetSubMats_Nest);
1848:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_nest_aij_C",MatConvert_Nest_AIJ);
1849:   PetscObjectComposeFunction((PetscObject)A,"MatConvert_nest_is_C", MatConvert_Nest_IS);

1851:   PetscObjectChangeTypeName((PetscObject)A,MATNEST);
1852:   return(0);
1853: }