Actual source code: matnest.c

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

  6: static PetscErrorCode MatSetUp_NestIS_Private(Mat, PetscInt, const IS[], PetscInt, const IS[]);
  7: static PetscErrorCode MatCreateVecs_Nest(Mat, Vec *, Vec *);
  8: static PetscErrorCode MatReset_Nest(Mat);

 10: PETSC_INTERN PetscErrorCode MatConvert_Nest_IS(Mat, MatType, MatReuse, Mat *);

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

 17:   PetscFunctionBegin;
 18:   *m = *n = *M = *N = 0;
 19:   for (PetscInt i = 0; i < bA->nr; i++) { /* rows */
 20:     PetscInt sm, sM;

 22:     PetscCall(ISGetLocalSize(bA->isglobal.row[i], &sm));
 23:     PetscCall(ISGetSize(bA->isglobal.row[i], &sM));
 24:     *m += sm;
 25:     *M += sM;
 26:   }
 27:   for (PetscInt j = 0; j < bA->nc; j++) { /* cols */
 28:     PetscInt sn, sN;

 30:     PetscCall(ISGetLocalSize(bA->isglobal.col[j], &sn));
 31:     PetscCall(ISGetSize(bA->isglobal.col[j], &sN));
 32:     *n += sn;
 33:     *N += sN;
 34:   }
 35:   PetscFunctionReturn(PETSC_SUCCESS);
 36: }

 38: /* operations */
 39: static PetscErrorCode MatMult_Nest(Mat A, Vec x, Vec y)
 40: {
 41:   Mat_Nest *bA = (Mat_Nest *)A->data;
 42:   Vec      *bx = bA->right, *by = bA->left;

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

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

 86: typedef struct {
 87:   Mat         *workC;      /* array of Mat with specific containers depending on the underlying MatMatMult implementation */
 88:   PetscScalar *tarray;     /* buffer for storing all temporary products A[i][j] B[j] */
 89:   PetscInt    *dm, *dn, k; /* displacements and number of submatrices */
 90: } Nest_Dense;

 92: static PetscErrorCode MatProductNumeric_Nest_Dense(Mat C)
 93: {
 94:   Mat_Nest          *bA;
 95:   Nest_Dense        *contents;
 96:   Mat                viewB, viewC, productB, workC;
 97:   const PetscScalar *barray;
 98:   PetscScalar       *carray;
 99:   PetscInt           M, N, nr, nc, ldb, ldc;
100:   Mat                A, B;

102:   PetscFunctionBegin;
103:   MatCheckProduct(C, 1);
104:   A = C->product->A;
105:   B = C->product->B;
106:   PetscCall(MatGetSize(B, NULL, &N));
107:   if (!N) {
108:     PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
109:     PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
110:     PetscFunctionReturn(PETSC_SUCCESS);
111:   }
112:   contents = (Nest_Dense *)C->product->data;
113:   PetscCheck(contents, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
114:   bA = (Mat_Nest *)A->data;
115:   nr = bA->nr;
116:   nc = bA->nc;
117:   PetscCall(MatDenseGetLDA(B, &ldb));
118:   PetscCall(MatDenseGetLDA(C, &ldc));
119:   PetscCall(MatZeroEntries(C));
120:   PetscCall(MatDenseGetArrayRead(B, &barray));
121:   PetscCall(MatDenseGetArray(C, &carray));
122:   for (PetscInt i = 0; i < nr; i++) {
123:     PetscCall(ISGetSize(bA->isglobal.row[i], &M));
124:     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)A), contents->dm[i + 1] - contents->dm[i], PETSC_DECIDE, M, N, PetscSafePointerPlusOffset(carray, contents->dm[i]), &viewC));
125:     PetscCall(MatDenseSetLDA(viewC, ldc));
126:     for (PetscInt j = 0; j < nc; j++) {
127:       if (!bA->m[i][j]) continue;
128:       PetscCall(ISGetSize(bA->isglobal.col[j], &M));
129:       PetscCall(MatCreateDense(PetscObjectComm((PetscObject)A), contents->dn[j + 1] - contents->dn[j], PETSC_DECIDE, M, N, PetscSafePointerPlusOffset((PetscScalar *)barray, contents->dn[j]), &viewB));
130:       PetscCall(MatDenseSetLDA(viewB, ldb));

132:       /* MatMatMultNumeric(bA->m[i][j],viewB,contents->workC[i*nc + j]); */
133:       workC             = contents->workC[i * nc + j];
134:       productB          = workC->product->B;
135:       workC->product->B = viewB; /* use newly created dense matrix viewB */
136:       PetscCall(MatProductNumeric(workC));
137:       PetscCall(MatDestroy(&viewB));
138:       workC->product->B = productB; /* resume original B */

140:       /* C[i] <- workC + C[i] */
141:       PetscCall(MatAXPY(viewC, 1.0, contents->workC[i * nc + j], SAME_NONZERO_PATTERN));
142:     }
143:     PetscCall(MatDestroy(&viewC));
144:   }
145:   PetscCall(MatDenseRestoreArray(C, &carray));
146:   PetscCall(MatDenseRestoreArrayRead(B, &barray));

148:   PetscCall(MatSetOption(C, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
149:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
150:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
151:   PetscFunctionReturn(PETSC_SUCCESS);
152: }

154: static PetscErrorCode MatNest_DenseDestroy(PetscCtxRt ctx)
155: {
156:   Nest_Dense *contents = *(Nest_Dense **)ctx;

158:   PetscFunctionBegin;
159:   PetscCall(PetscFree(contents->tarray));
160:   for (PetscInt i = 0; i < contents->k; i++) PetscCall(MatDestroy(contents->workC + i));
161:   PetscCall(PetscFree3(contents->dm, contents->dn, contents->workC));
162:   PetscCall(PetscFree(contents));
163:   PetscFunctionReturn(PETSC_SUCCESS);
164: }

166: static PetscErrorCode MatProductSymbolic_Nest_Dense(Mat C)
167: {
168:   Mat_Nest          *bA;
169:   Mat                viewB, workC;
170:   const PetscScalar *barray;
171:   PetscInt           M, N, m, n, nr, nc, maxm = 0, ldb;
172:   Nest_Dense        *contents = NULL;
173:   PetscBool          cisdense;
174:   Mat                A, B;
175:   PetscReal          fill;

177:   PetscFunctionBegin;
178:   MatCheckProduct(C, 1);
179:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
180:   A    = C->product->A;
181:   B    = C->product->B;
182:   fill = C->product->fill;
183:   bA   = (Mat_Nest *)A->data;
184:   nr   = bA->nr;
185:   nc   = bA->nc;
186:   PetscCall(MatGetLocalSize(B, NULL, &n));
187:   PetscCall(MatGetSize(B, NULL, &N));
188:   PetscCall(MatGetLocalSize(A, &m, NULL));
189:   PetscCall(MatGetSize(A, &M, NULL));
190:   PetscCall(MatSetSizes(C, m, n, M, N));
191:   PetscCall(PetscObjectTypeCompareAny((PetscObject)C, &cisdense, MATSEQDENSE, MATMPIDENSE, MATSEQDENSECUDA, MATMPIDENSECUDA, ""));
192:   if (!cisdense) {
193:     PetscCall(MatSetType(C, ((PetscObject)B)->type_name));
194:     PetscCall(MatSetVecType(C, B->defaultvectype));
195:   }
196:   PetscCall(MatSetUp(C));
197:   if (!N) {
198:     C->ops->productnumeric = MatProductNumeric_Nest_Dense;
199:     PetscFunctionReturn(PETSC_SUCCESS);
200:   }

202:   PetscCall(PetscNew(&contents));
203:   C->product->data    = contents;
204:   C->product->destroy = MatNest_DenseDestroy;
205:   PetscCall(PetscCalloc3(nr + 1, &contents->dm, nc + 1, &contents->dn, nr * nc, &contents->workC));
206:   contents->k = nr * nc;
207:   for (PetscInt i = 0; i < nr; i++) {
208:     PetscCall(ISGetLocalSize(bA->isglobal.row[i], contents->dm + i + 1));
209:     maxm = PetscMax(maxm, contents->dm[i + 1]);
210:     contents->dm[i + 1] += contents->dm[i];
211:   }
212:   for (PetscInt i = 0; i < nc; i++) {
213:     PetscCall(ISGetLocalSize(bA->isglobal.col[i], contents->dn + i + 1));
214:     contents->dn[i + 1] += contents->dn[i];
215:   }
216:   PetscCall(PetscMalloc1(maxm * N, &contents->tarray));
217:   PetscCall(MatDenseGetLDA(B, &ldb));
218:   PetscCall(MatGetSize(B, NULL, &N));
219:   PetscCall(MatDenseGetArrayRead(B, &barray));
220:   /* loops are permuted compared to MatMatMultNumeric so that viewB is created only once per column of A */
221:   for (PetscInt j = 0; j < nc; j++) {
222:     PetscCall(ISGetSize(bA->isglobal.col[j], &M));
223:     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)A), contents->dn[j + 1] - contents->dn[j], PETSC_DECIDE, M, N, PetscSafePointerPlusOffset((PetscScalar *)barray, contents->dn[j]), &viewB));
224:     PetscCall(MatDenseSetLDA(viewB, ldb));
225:     for (PetscInt i = 0; i < nr; i++) {
226:       if (!bA->m[i][j]) continue;
227:       /* MatMatMultSymbolic may attach a specific container (depending on MatType of bA->m[i][j]) to workC[i][j] */

229:       PetscCall(MatProductCreate(bA->m[i][j], viewB, NULL, &contents->workC[i * nc + j]));
230:       workC = contents->workC[i * nc + j];
231:       PetscCall(MatProductSetType(workC, MATPRODUCT_AB));
232:       PetscCall(MatProductSetAlgorithm(workC, "default"));
233:       PetscCall(MatProductSetFill(workC, fill));
234:       PetscCall(MatProductSetFromOptions(workC));
235:       PetscCall(MatProductSymbolic(workC));

237:       /* since tarray will be shared by all Mat */
238:       PetscCall(MatSeqDenseSetPreallocation(workC, contents->tarray));
239:       PetscCall(MatMPIDenseSetPreallocation(workC, contents->tarray));
240:     }
241:     PetscCall(MatDestroy(&viewB));
242:   }
243:   PetscCall(MatDenseRestoreArrayRead(B, &barray));

245:   C->ops->productnumeric = MatProductNumeric_Nest_Dense;
246:   PetscFunctionReturn(PETSC_SUCCESS);
247: }

249: static PetscErrorCode MatProductSetFromOptions_Nest_Dense(Mat C)
250: {
251:   Mat_Product *product = C->product;

253:   PetscFunctionBegin;
254:   if (product->type == MATPRODUCT_AB) C->ops->productsymbolic = MatProductSymbolic_Nest_Dense;
255:   PetscFunctionReturn(PETSC_SUCCESS);
256: }

258: static PetscErrorCode MatMultTransposeKernel_Nest(Mat A, Vec x, Vec y, PetscBool herm)
259: {
260:   Mat_Nest *bA = (Mat_Nest *)A->data;
261:   Vec      *bx = bA->left, *by = bA->right;

263:   PetscFunctionBegin;
264:   for (PetscInt i = 0; i < bA->nr; i++) PetscCall(VecGetSubVector(x, bA->isglobal.row[i], &bx[i]));
265:   for (PetscInt i = 0; i < bA->nc; i++) PetscCall(VecGetSubVector(y, bA->isglobal.col[i], &by[i]));
266:   for (PetscInt j = 0; j < bA->nc; j++) {
267:     PetscCall(VecZeroEntries(by[j]));
268:     for (PetscInt i = 0; i < bA->nr; i++) {
269:       if (!bA->m[i][j]) continue;
270:       if (herm) PetscCall(MatMultHermitianTransposeAdd(bA->m[i][j], bx[i], by[j], by[j])); /* y[j] <- y[j] + (A[i][j])^H * x[i] */
271:       else PetscCall(MatMultTransposeAdd(bA->m[i][j], bx[i], by[j], by[j]));               /* y[j] <- y[j] + (A[i][j])^T * x[i] */
272:     }
273:   }
274:   for (PetscInt i = 0; i < bA->nr; i++) PetscCall(VecRestoreSubVector(x, bA->isglobal.row[i], &bx[i]));
275:   for (PetscInt i = 0; i < bA->nc; i++) PetscCall(VecRestoreSubVector(y, bA->isglobal.col[i], &by[i]));
276:   PetscFunctionReturn(PETSC_SUCCESS);
277: }

279: static PetscErrorCode MatMultTranspose_Nest(Mat A, Vec x, Vec y)
280: {
281:   PetscFunctionBegin;
282:   PetscCall(MatMultTransposeKernel_Nest(A, x, y, PETSC_FALSE));
283:   PetscFunctionReturn(PETSC_SUCCESS);
284: }

286: static PetscErrorCode MatMultHermitianTranspose_Nest(Mat A, Vec x, Vec y)
287: {
288:   PetscFunctionBegin;
289:   PetscCall(MatMultTransposeKernel_Nest(A, x, y, PETSC_TRUE));
290:   PetscFunctionReturn(PETSC_SUCCESS);
291: }

293: static PetscErrorCode MatMultTransposeAddKernel_Nest(Mat A, Vec x, Vec y, Vec z, PetscBool herm)
294: {
295:   Mat_Nest *bA = (Mat_Nest *)A->data;
296:   Vec      *bx = bA->left, *bz = bA->right;

298:   PetscFunctionBegin;
299:   for (PetscInt i = 0; i < bA->nr; i++) PetscCall(VecGetSubVector(x, bA->isglobal.row[i], &bx[i]));
300:   for (PetscInt i = 0; i < bA->nc; i++) PetscCall(VecGetSubVector(z, bA->isglobal.col[i], &bz[i]));
301:   for (PetscInt j = 0; j < bA->nc; j++) {
302:     if (y != z) {
303:       Vec by;

305:       PetscCall(VecGetSubVector(y, bA->isglobal.col[j], &by));
306:       PetscCall(VecCopy(by, bz[j]));
307:       PetscCall(VecRestoreSubVector(y, bA->isglobal.col[j], &by));
308:     }
309:     for (PetscInt i = 0; i < bA->nr; i++) {
310:       if (!bA->m[i][j]) continue;
311:       if (herm) PetscCall(MatMultHermitianTransposeAdd(bA->m[i][j], bx[i], bz[j], bz[j])); /* z[j] <- y[j] + (A[i][j])^H * x[i] */
312:       else PetscCall(MatMultTransposeAdd(bA->m[i][j], bx[i], bz[j], bz[j]));               /* z[j] <- y[j] + (A[i][j])^T * x[i] */
313:     }
314:   }
315:   for (PetscInt i = 0; i < bA->nr; i++) PetscCall(VecRestoreSubVector(x, bA->isglobal.row[i], &bx[i]));
316:   for (PetscInt i = 0; i < bA->nc; i++) PetscCall(VecRestoreSubVector(z, bA->isglobal.col[i], &bz[i]));
317:   PetscFunctionReturn(PETSC_SUCCESS);
318: }

320: static PetscErrorCode MatMultTransposeAdd_Nest(Mat A, Vec x, Vec y, Vec z)
321: {
322:   PetscFunctionBegin;
323:   PetscCall(MatMultTransposeAddKernel_Nest(A, x, y, z, PETSC_FALSE));
324:   PetscFunctionReturn(PETSC_SUCCESS);
325: }

327: static PetscErrorCode MatMultHermitianTransposeAdd_Nest(Mat A, Vec x, Vec y, Vec z)
328: {
329:   PetscFunctionBegin;
330:   PetscCall(MatMultTransposeAddKernel_Nest(A, x, y, z, PETSC_TRUE));
331:   PetscFunctionReturn(PETSC_SUCCESS);
332: }

334: static PetscErrorCode MatTranspose_Nest(Mat A, MatReuse reuse, Mat *B)
335: {
336:   Mat_Nest *bA = (Mat_Nest *)A->data, *bC;
337:   Mat       C;
338:   PetscInt  i, j, nr = bA->nr, nc = bA->nc;

340:   PetscFunctionBegin;
341:   if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *B));
342:   PetscCheck(reuse != MAT_INPLACE_MATRIX || nr == nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_SIZ, "Square nested matrix only for in-place");

344:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
345:     Mat *subs;
346:     IS  *is_row, *is_col;

348:     PetscCall(PetscCalloc1(nr * nc, &subs));
349:     PetscCall(PetscMalloc2(nr, &is_row, nc, &is_col));
350:     PetscCall(MatNestGetISs(A, is_row, is_col));
351:     if (reuse == MAT_INPLACE_MATRIX) {
352:       for (i = 0; i < nr; i++) {
353:         for (j = 0; j < nc; j++) subs[i + nr * j] = bA->m[i][j];
354:       }
355:     }

357:     PetscCall(MatCreateNest(PetscObjectComm((PetscObject)A), nc, is_col, nr, is_row, subs, &C));
358:     PetscCall(PetscFree(subs));
359:     PetscCall(PetscFree2(is_row, is_col));
360:   } else {
361:     C = *B;
362:   }

364:   bC = (Mat_Nest *)C->data;
365:   for (i = 0; i < nr; i++) {
366:     for (j = 0; j < nc; j++) {
367:       if (bA->m[i][j]) {
368:         PetscCall(MatTranspose(bA->m[i][j], reuse, &bC->m[j][i]));
369:       } else {
370:         bC->m[j][i] = NULL;
371:       }
372:     }
373:   }

375:   if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_REUSE_MATRIX) {
376:     *B = C;
377:   } else {
378:     PetscCall(MatHeaderMerge(A, &C));
379:   }
380:   PetscFunctionReturn(PETSC_SUCCESS);
381: }

383: static PetscErrorCode MatNestDestroyISList(PetscInt n, IS **list)
384: {
385:   IS *lst = *list;

387:   PetscFunctionBegin;
388:   if (!lst) PetscFunctionReturn(PETSC_SUCCESS);
389:   for (PetscInt i = 0; i < n; i++) PetscCall(ISDestroy(&lst[i]));
390:   PetscCall(PetscFree(lst));
391:   *list = NULL;
392:   PetscFunctionReturn(PETSC_SUCCESS);
393: }

395: static PetscErrorCode MatReset_Nest(Mat A)
396: {
397:   Mat_Nest *vs = (Mat_Nest *)A->data;

399:   PetscFunctionBegin;
400:   /* release the matrices and the place holders */
401:   PetscCall(MatNestDestroyISList(vs->nr, &vs->isglobal.row));
402:   PetscCall(MatNestDestroyISList(vs->nc, &vs->isglobal.col));
403:   PetscCall(MatNestDestroyISList(vs->nr, &vs->islocal.row));
404:   PetscCall(MatNestDestroyISList(vs->nc, &vs->islocal.col));

406:   PetscCall(PetscFree(vs->row_len));
407:   PetscCall(PetscFree(vs->col_len));
408:   PetscCall(PetscFree(vs->nnzstate));

410:   PetscCall(PetscFree2(vs->left, vs->right));

412:   /* release the matrices and the place holders */
413:   if (vs->m) {
414:     for (PetscInt i = 0; i < vs->nr; i++) {
415:       for (PetscInt j = 0; j < vs->nc; j++) PetscCall(MatDestroy(&vs->m[i][j]));
416:     }
417:     PetscCall(PetscFree(vs->m[0]));
418:     PetscCall(PetscFree(vs->m));
419:   }

421:   /* restore defaults */
422:   vs->nr            = 0;
423:   vs->nc            = 0;
424:   vs->splitassembly = PETSC_FALSE;
425:   PetscFunctionReturn(PETSC_SUCCESS);
426: }

428: static PetscErrorCode MatDestroy_Nest(Mat A)
429: {
430:   PetscFunctionBegin;
431:   PetscCall(MatReset_Nest(A));
432:   PetscCall(PetscFree(A->data));
433:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSubMat_C", NULL));
434:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetSubMat_C", NULL));
435:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSubMats_C", NULL));
436:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSize_C", NULL));
437:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetISs_C", NULL));
438:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetLocalISs_C", NULL));
439:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetVecType_C", NULL));
440:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetSubMats_C", NULL));
441:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_mpiaij_C", NULL));
442:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_seqaij_C", NULL));
443:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_aij_C", NULL));
444:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_is_C", NULL));
445:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_mpidense_C", NULL));
446:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_seqdense_C", NULL));
447:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_nest_seqdense_C", NULL));
448:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_nest_mpidense_C", NULL));
449:   PetscFunctionReturn(PETSC_SUCCESS);
450: }

452: static PetscErrorCode MatAssemblyBegin_Nest(Mat A, MatAssemblyType type)
453: {
454:   Mat_Nest *vs       = (Mat_Nest *)A->data;
455:   PetscBool nnzstate = PETSC_FALSE;

457:   PetscFunctionBegin;
458:   for (PetscInt i = 0; i < vs->nr; i++) {
459:     for (PetscInt j = 0; j < vs->nc; j++) {
460:       PetscObjectState subnnzstate = 0;
461:       if (vs->m[i][j]) {
462:         PetscCall(MatAssemblyBegin(vs->m[i][j], type));
463:         if (!vs->splitassembly) {
464:           /* Note: split assembly will fail if the same block appears more than once (even indirectly through a nested
465:            * sub-block). This could be fixed by adding a flag to Mat so that there was a way to check if a Mat was
466:            * already performing an assembly, but the result would by more complicated and appears to offer less
467:            * potential for diagnostics and correctness checking. Split assembly should be fixed once there is an
468:            * interface for libraries to make asynchronous progress in "user-defined non-blocking collectives".
469:            */
470:           PetscCall(MatAssemblyEnd(vs->m[i][j], type));
471:           PetscCall(MatGetNonzeroState(vs->m[i][j], &subnnzstate));
472:         }
473:       }
474:       nnzstate                     = (PetscBool)(nnzstate || vs->nnzstate[i * vs->nc + j] != subnnzstate);
475:       vs->nnzstate[i * vs->nc + j] = subnnzstate;
476:     }
477:   }
478:   if (nnzstate) A->nonzerostate++;
479:   PetscFunctionReturn(PETSC_SUCCESS);
480: }

482: static PetscErrorCode MatAssemblyEnd_Nest(Mat A, MatAssemblyType type)
483: {
484:   Mat_Nest *vs = (Mat_Nest *)A->data;

486:   PetscFunctionBegin;
487:   for (PetscInt i = 0; i < vs->nr; i++) {
488:     for (PetscInt j = 0; j < vs->nc; j++) {
489:       if (vs->m[i][j]) {
490:         if (vs->splitassembly) PetscCall(MatAssemblyEnd(vs->m[i][j], type));
491:       }
492:     }
493:   }
494:   PetscFunctionReturn(PETSC_SUCCESS);
495: }

497: static PetscErrorCode MatNestFindNonzeroSubMatRow(Mat A, PetscInt row, Mat *B)
498: {
499:   Mat_Nest *vs = (Mat_Nest *)A->data;
500:   Mat       sub;

502:   PetscFunctionBegin;
503:   sub = (row < vs->nc) ? vs->m[row][row] : (Mat)NULL; /* Prefer to find on the diagonal */
504:   for (PetscInt j = 0; !sub && j < vs->nc; j++) sub = vs->m[row][j];
505:   if (sub) PetscCall(MatSetUp(sub)); /* Ensure that the sizes are available */
506:   *B = sub;
507:   PetscFunctionReturn(PETSC_SUCCESS);
508: }

510: static PetscErrorCode MatNestFindNonzeroSubMatCol(Mat A, PetscInt col, Mat *B)
511: {
512:   Mat_Nest *vs = (Mat_Nest *)A->data;
513:   Mat       sub;

515:   PetscFunctionBegin;
516:   sub = (col < vs->nr) ? vs->m[col][col] : (Mat)NULL; /* Prefer to find on the diagonal */
517:   for (PetscInt i = 0; !sub && i < vs->nr; i++) sub = vs->m[i][col];
518:   if (sub) PetscCall(MatSetUp(sub)); /* Ensure that the sizes are available */
519:   *B = sub;
520:   PetscFunctionReturn(PETSC_SUCCESS);
521: }

523: static PetscErrorCode MatNestFindISRange(Mat A, PetscInt n, const IS list[], IS is, PetscInt *begin, PetscInt *end)
524: {
525:   PetscInt  i, j, size, m;
526:   PetscBool flg;
527:   IS        out, concatenate[2];

529:   PetscFunctionBegin;
530:   PetscAssertPointer(list, 3);
532:   if (begin) {
533:     PetscAssertPointer(begin, 5);
534:     *begin = -1;
535:   }
536:   if (end) {
537:     PetscAssertPointer(end, 6);
538:     *end = -1;
539:   }
540:   for (i = 0; i < n; i++) {
541:     if (!list[i]) continue;
542:     PetscCall(ISEqualUnsorted(list[i], is, &flg));
543:     if (flg) {
544:       if (begin) *begin = i;
545:       if (end) *end = i + 1;
546:       PetscFunctionReturn(PETSC_SUCCESS);
547:     }
548:   }
549:   PetscCall(ISGetSize(is, &size));
550:   for (i = 0; i < n - 1; i++) {
551:     if (!list[i]) continue;
552:     m = 0;
553:     PetscCall(ISConcatenate(PetscObjectComm((PetscObject)A), 2, list + i, &out));
554:     PetscCall(ISGetSize(out, &m));
555:     for (j = i + 2; j < n && m < size; j++) {
556:       if (list[j]) {
557:         concatenate[0] = out;
558:         concatenate[1] = list[j];
559:         PetscCall(ISConcatenate(PetscObjectComm((PetscObject)A), 2, concatenate, &out));
560:         PetscCall(ISDestroy(concatenate));
561:         PetscCall(ISGetSize(out, &m));
562:       }
563:     }
564:     if (m == size) {
565:       PetscCall(ISEqualUnsorted(out, is, &flg));
566:       if (flg) {
567:         if (begin) *begin = i;
568:         if (end) *end = j;
569:         PetscCall(ISDestroy(&out));
570:         PetscFunctionReturn(PETSC_SUCCESS);
571:       }
572:     }
573:     PetscCall(ISDestroy(&out));
574:   }
575:   PetscFunctionReturn(PETSC_SUCCESS);
576: }

578: static PetscErrorCode MatNestFillEmptyMat_Private(Mat A, PetscInt i, PetscInt j, Mat *B)
579: {
580:   Mat_Nest *vs = (Mat_Nest *)A->data;
581:   PetscInt  lr, lc;

583:   PetscFunctionBegin;
584:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
585:   PetscCall(ISGetLocalSize(vs->isglobal.row[i], &lr));
586:   PetscCall(ISGetLocalSize(vs->isglobal.col[j], &lc));
587:   PetscCall(MatSetSizes(*B, lr, lc, PETSC_DECIDE, PETSC_DECIDE));
588:   PetscCall(MatSetType(*B, MATAIJ));
589:   PetscCall(MatSeqAIJSetPreallocation(*B, 0, NULL));
590:   PetscCall(MatMPIAIJSetPreallocation(*B, 0, NULL, 0, NULL));
591:   PetscCall(MatSetUp(*B));
592:   PetscCall(MatSetOption(*B, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
593:   PetscCall(MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY));
594:   PetscCall(MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY));
595:   PetscFunctionReturn(PETSC_SUCCESS);
596: }

598: static PetscErrorCode MatNestGetBlock_Private(Mat A, PetscInt rbegin, PetscInt rend, PetscInt cbegin, PetscInt cend, Mat *B)
599: {
600:   Mat_Nest  *vs = (Mat_Nest *)A->data;
601:   Mat       *a;
602:   PetscInt   i, j, k, l, nr = rend - rbegin, nc = cend - cbegin;
603:   char       keyname[256];
604:   PetscBool *b;
605:   PetscBool  flg;

607:   PetscFunctionBegin;
608:   *B = NULL;
609:   PetscCall(PetscSNPrintf(keyname, sizeof(keyname), "NestBlock_%" PetscInt_FMT "-%" PetscInt_FMT "x%" PetscInt_FMT "-%" PetscInt_FMT, rbegin, rend, cbegin, cend));
610:   PetscCall(PetscObjectQuery((PetscObject)A, keyname, (PetscObject *)B));
611:   if (*B) PetscFunctionReturn(PETSC_SUCCESS);

613:   PetscCall(PetscMalloc2(nr * nc, &a, nr * nc, &b));
614:   for (i = 0; i < nr; i++) {
615:     for (j = 0; j < nc; j++) {
616:       a[i * nc + j] = vs->m[rbegin + i][cbegin + j];
617:       b[i * nc + j] = PETSC_FALSE;
618:     }
619:   }
620:   if (nc != vs->nc && nr != vs->nr) {
621:     for (i = 0; i < nr; i++) {
622:       for (j = 0; j < nc; j++) {
623:         flg = PETSC_FALSE;
624:         for (k = 0; (k < nr && !flg); k++) {
625:           if (a[j + k * nc]) flg = PETSC_TRUE;
626:         }
627:         if (flg) {
628:           flg = PETSC_FALSE;
629:           for (l = 0; (l < nc && !flg); l++) {
630:             if (a[i * nc + l]) flg = PETSC_TRUE;
631:           }
632:         }
633:         if (!flg) {
634:           b[i * nc + j] = PETSC_TRUE;
635:           PetscCall(MatNestFillEmptyMat_Private(A, rbegin + i, cbegin + j, a + i * nc + j));
636:         }
637:       }
638:     }
639:   }
640:   PetscCall(MatCreateNest(PetscObjectComm((PetscObject)A), nr, nr != vs->nr ? NULL : vs->isglobal.row, nc, nc != vs->nc ? NULL : vs->isglobal.col, a, B));
641:   for (i = 0; i < nr; i++) {
642:     for (j = 0; j < nc; j++) {
643:       if (b[i * nc + j]) PetscCall(MatDestroy(a + i * nc + j));
644:     }
645:   }
646:   PetscCall(PetscFree2(a, b));
647:   (*B)->assembled = A->assembled;
648:   PetscCall(PetscObjectCompose((PetscObject)A, keyname, (PetscObject)*B));
649:   PetscCall(PetscObjectDereference((PetscObject)*B)); /* Leave the only remaining reference in the composition */
650:   PetscFunctionReturn(PETSC_SUCCESS);
651: }

653: static PetscErrorCode MatNestFindSubMat(Mat A, IS isrow, IS iscol, PetscBool global, PetscBool *found, Mat *B)
654: {
655:   Mat_Nest *vs = (Mat_Nest *)A->data;
656:   PetscInt  rbegin, rend, cbegin, cend;

658:   PetscFunctionBegin;
659:   *B = NULL;
660:   PetscCall(MatNestFindISRange(A, vs->nr, global ? vs->isglobal.row : vs->islocal.row, isrow, &rbegin, &rend));
661:   PetscCall(MatNestFindISRange(A, vs->nc, global ? vs->isglobal.col : vs->islocal.col, iscol, &cbegin, &cend));
662:   if (rend == rbegin + 1 && cend == cbegin + 1) {
663:     if (!vs->m[rbegin][cbegin]) PetscCall(MatNestFillEmptyMat_Private(A, rbegin, cbegin, vs->m[rbegin] + cbegin));
664:     *B = vs->m[rbegin][cbegin];
665:     if (found) *found = PETSC_TRUE;
666:   } else if (rbegin != -1 && cbegin != -1) {
667:     PetscCheck(global == PETSC_TRUE, PETSC_COMM_SELF, PETSC_ERR_SUP, "MATNEST local submatrix cannot select more than a single submatrix");
668:     PetscCall(MatNestGetBlock_Private(A, rbegin, rend, cbegin, cend, B));
669:     if (found) *found = PETSC_TRUE;
670:   } else if (found) *found = PETSC_FALSE;
671:   PetscFunctionReturn(PETSC_SUCCESS);
672: }

674: static PetscErrorCode MatNestFindFullBlocks_Private(Mat A, PetscInt n, const IS blockis[], IS is, const char axis[], PetscInt *nselected, PetscInt **selected, IS **isout)
675: {
676:   const PetscInt *idx;
677:   PetscInt       *blocks;
678:   IS             *out;
679:   PetscInt        N, bs, cursor = 0, i, nblock, nlocal, nout = 0, offset = 0, start;
680:   PetscBool       complete, match;

682:   PetscFunctionBegin;
683:   PetscCall(ISGetSize(is, &N));
684:   PetscCheck(N, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Empty %s index sets are not supported for MATNEST submatrices", axis);
685:   PetscCall(ISGetLocalSize(is, &nlocal));
686:   PetscCall(ISGetIndices(is, &idx));
687:   PetscCall(PetscMalloc1(n, &blocks));
688:   for (i = 0; i < n; i++) {
689:     const PetscInt *bidx;

691:     PetscCall(ISGetSize(blockis[i], &N));
692:     if (!N) continue;
693:     PetscCall(ISGetLocalSize(blockis[i], &nblock));
694:     match = (PetscBool)(cursor + nblock <= nlocal);
695:     if (match && nblock) {
696:       PetscCall(ISGetIndices(blockis[i], &bidx));
697:       PetscCall(PetscArraycmp(idx + cursor, bidx, nblock, &match));
698:       PetscCall(ISRestoreIndices(blockis[i], &bidx));
699:     }
700:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &match, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
701:     if (match) {
702:       blocks[nout++] = i;
703:       cursor += nblock;
704:     }
705:   }
706:   complete = (PetscBool)(cursor == nlocal);
707:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &complete, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)A)));
708:   PetscCall(ISRestoreIndices(is, &idx));
709:   if (!complete || !nout) PetscCall(PetscFree(blocks));
710:   PetscCheck(complete && nout, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "MATNEST submatrix %s index set must be an ordered union of complete MATNEST blocks", axis);

712:   PetscCallMPI(MPI_Scan(&nlocal, &start, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)A)));
713:   start -= nlocal;
714:   PetscCall(PetscMalloc1(nout, &out));
715:   for (i = 0; i < nout; i++) {
716:     PetscCall(ISGetLocalSize(blockis[blocks[i]], &nblock));
717:     PetscCall(ISGetBlockSize(blockis[blocks[i]], &bs));
718:     PetscCall(ISCreateStride(PetscObjectComm((PetscObject)A), nblock, start + offset, 1, out + i));
719:     PetscCall(ISSetBlockSize(out[i], bs));
720:     offset += nblock;
721:   }
722:   PetscCheck(offset == nlocal, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Inconsistent MATNEST submatrix %s layout", axis);
723:   *nselected = nout;
724:   *selected  = blocks;
725:   *isout     = out;
726:   PetscFunctionReturn(PETSC_SUCCESS);
727: }

729: static PetscErrorCode MatCreateSubMatrix_Nest_Nontrivial(Mat A, IS isrow, IS iscol, MatReuse reuse, Mat *B)
730: {
731:   Mat_Nest *vs = (Mat_Nest *)A->data;
732:   Mat      *submats;
733:   IS       *rowis, *colis;
734:   PetscInt *rows, *cols;
735:   PetscInt  nr, nc;
736:   PetscBool flg;

738:   PetscFunctionBegin;
739:   PetscCall(MatNestFindFullBlocks_Private(A, vs->nr, vs->isglobal.row, isrow, "row", &nr, &rows, &rowis));
740:   PetscCall(MatNestFindFullBlocks_Private(A, vs->nc, vs->isglobal.col, iscol, "column", &nc, &cols, &colis));
741:   PetscCall(PetscMalloc1(nr * nc, &submats));
742:   for (PetscInt i = 0; i < nr; i++) {
743:     for (PetscInt j = 0; j < nc; j++) submats[i * nc + j] = vs->m[rows[i]][cols[j]];
744:   }
745:   if (reuse == MAT_INITIAL_MATRIX) {
746:     PetscCall(MatCreateNest(PetscObjectComm((PetscObject)A), nr, rowis, nc, colis, submats, B));
747:     (*B)->assembled = A->assembled;
748:   } else {
749:     PetscCheck(reuse == MAT_REUSE_MATRIX, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Invalid MatReuse %d", (int)reuse);
750:     PetscCall(PetscObjectTypeCompare((PetscObject)*B, MATNEST, &flg));
751:     PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot reuse a non-MATNEST matrix for this MATNEST submatrix");
752:     vs = (Mat_Nest *)(*B)->data;
753:     PetscCheck(vs->nr == nr && vs->nc == nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot reuse MATNEST submatrix with a different block layout");
754:     for (PetscInt i = 0; i < nr; i++) {
755:       PetscCall(ISEqualUnsorted(vs->isglobal.row[i], rowis[i], &flg));
756:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot reuse MATNEST submatrix with a different row layout");
757:     }
758:     for (PetscInt j = 0; j < nc; j++) {
759:       PetscCall(ISEqualUnsorted(vs->isglobal.col[j], colis[j], &flg));
760:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Cannot reuse MATNEST submatrix with a different column layout");
761:     }
762:     PetscCall(MatNestSetSubMats(*B, nr, rowis, nc, colis, submats));
763:     (*B)->assembled = A->assembled;
764:   }
765:   PetscCall(PetscFree(submats));
766:   for (PetscInt i = 0; i < nr; i++) PetscCall(ISDestroy(rowis + i));
767:   for (PetscInt j = 0; j < nc; j++) PetscCall(ISDestroy(colis + j));
768:   PetscCall(PetscFree(rows));
769:   PetscCall(PetscFree(rowis));
770:   PetscCall(PetscFree(cols));
771:   PetscCall(PetscFree(colis));
772:   PetscFunctionReturn(PETSC_SUCCESS);
773: }

775: /*
776:    TODO: This does not actually returns a submatrix we can modify
777: */
778: static PetscErrorCode MatCreateSubMatrix_Nest(Mat A, IS isrow, IS iscol, MatReuse reuse, Mat *B)
779: {
780:   Mat       sub;
781:   PetscBool found;

783:   PetscFunctionBegin;
784:   PetscCall(MatNestFindSubMat(A, isrow, iscol, PETSC_TRUE, &found, &sub));
785:   if (!found) {
786:     PetscCall(MatCreateSubMatrix_Nest_Nontrivial(A, isrow, iscol, reuse, B));
787:     PetscFunctionReturn(PETSC_SUCCESS);
788:   }
789:   switch (reuse) {
790:   case MAT_INITIAL_MATRIX:
791:     PetscCall(PetscObjectReference((PetscObject)sub));
792:     if (sub) PetscCall(PetscObjectStateIncrease((PetscObject)sub));
793:     *B = sub;
794:     break;
795:   case MAT_REUSE_MATRIX:
796:     PetscCheck(sub == *B, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Submatrix was not used before in this call");
797:     if (sub) PetscCall(PetscObjectStateIncrease((PetscObject)sub));
798:     break;
799:   default:
800:     break;
801:   }
802:   PetscFunctionReturn(PETSC_SUCCESS);
803: }

805: static PetscErrorCode MatGetLocalSubMatrix_Nest(Mat A, IS isrow, IS iscol, Mat *B)
806: {
807:   Mat sub;

809:   PetscFunctionBegin;
810:   PetscCall(MatNestFindSubMat(A, isrow, iscol, PETSC_FALSE, NULL, &sub));
811:   /* We allow the submatrix to be NULL, perhaps it would be better for the user to return an empty matrix instead */
812:   PetscCall(PetscObjectReference((PetscObject)sub));
813:   *B = sub;
814:   PetscFunctionReturn(PETSC_SUCCESS);
815: }

817: static PetscErrorCode MatRestoreLocalSubMatrix_Nest(Mat A, IS isrow, IS iscol, Mat *B)
818: {
819:   Mat sub;

821:   PetscFunctionBegin;
822:   PetscCall(MatNestFindSubMat(A, isrow, iscol, PETSC_FALSE, NULL, &sub));
823:   PetscCheck(*B == sub, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Local submatrix has not been gotten");
824:   if (sub) {
825:     PetscCheck(((PetscObject)sub)->refct > 1, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Local submatrix has had reference count decremented too many times");
826:     PetscCall(MatDestroy(B));
827:   }
828:   PetscFunctionReturn(PETSC_SUCCESS);
829: }

831: static PetscErrorCode MatGetDiagonal_Nest(Mat A, Vec v)
832: {
833:   Mat_Nest *bA = (Mat_Nest *)A->data;

835:   PetscFunctionBegin;
836:   for (PetscInt i = 0; i < bA->nr; i++) {
837:     Vec bv;
838:     PetscCall(VecGetSubVector(v, bA->isglobal.row[i], &bv));
839:     if (bA->m[i][i]) PetscCall(MatGetDiagonal(bA->m[i][i], bv));
840:     else PetscCall(VecSet(bv, 0.0));
841:     PetscCall(VecRestoreSubVector(v, bA->isglobal.row[i], &bv));
842:   }
843:   PetscFunctionReturn(PETSC_SUCCESS);
844: }

846: static PetscErrorCode MatDiagonalScale_Nest(Mat A, Vec l, Vec r)
847: {
848:   Mat_Nest *bA = (Mat_Nest *)A->data;
849:   Vec       bl, *br;

851:   PetscFunctionBegin;
852:   PetscCall(PetscCalloc1(bA->nc, &br));
853:   if (r) {
854:     for (PetscInt j = 0; j < bA->nc; j++) PetscCall(VecGetSubVector(r, bA->isglobal.col[j], &br[j]));
855:   }
856:   bl = NULL;
857:   for (PetscInt i = 0; i < bA->nr; i++) {
858:     if (l) PetscCall(VecGetSubVector(l, bA->isglobal.row[i], &bl));
859:     for (PetscInt j = 0; j < bA->nc; j++) {
860:       if (bA->m[i][j]) PetscCall(MatDiagonalScale(bA->m[i][j], bl, br[j]));
861:     }
862:     if (l) PetscCall(VecRestoreSubVector(l, bA->isglobal.row[i], &bl));
863:   }
864:   if (r) {
865:     for (PetscInt j = 0; j < bA->nc; j++) PetscCall(VecRestoreSubVector(r, bA->isglobal.col[j], &br[j]));
866:   }
867:   PetscCall(PetscFree(br));
868:   PetscFunctionReturn(PETSC_SUCCESS);
869: }

871: static PetscErrorCode MatScale_Nest(Mat A, PetscScalar a)
872: {
873:   Mat_Nest *bA = (Mat_Nest *)A->data;

875:   PetscFunctionBegin;
876:   for (PetscInt i = 0; i < bA->nr; i++) {
877:     for (PetscInt j = 0; j < bA->nc; j++) {
878:       if (bA->m[i][j]) PetscCall(MatScale(bA->m[i][j], a));
879:     }
880:   }
881:   PetscFunctionReturn(PETSC_SUCCESS);
882: }

884: static PetscErrorCode MatShift_Nest(Mat A, PetscScalar a)
885: {
886:   Mat_Nest *bA       = (Mat_Nest *)A->data;
887:   PetscBool nnzstate = PETSC_FALSE;

889:   PetscFunctionBegin;
890:   for (PetscInt i = 0; i < bA->nr; i++) {
891:     PetscObjectState subnnzstate = 0;
892:     PetscCheck(bA->m[i][i], PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "No support for shifting an empty diagonal block, insert a matrix in block (%" PetscInt_FMT ",%" PetscInt_FMT ")", i, i);
893:     PetscCall(MatShift(bA->m[i][i], a));
894:     PetscCall(MatGetNonzeroState(bA->m[i][i], &subnnzstate));
895:     nnzstate                     = (PetscBool)(nnzstate || bA->nnzstate[i * bA->nc + i] != subnnzstate);
896:     bA->nnzstate[i * bA->nc + i] = subnnzstate;
897:   }
898:   if (nnzstate) A->nonzerostate++;
899:   PetscFunctionReturn(PETSC_SUCCESS);
900: }

902: static PetscErrorCode MatDiagonalSet_Nest(Mat A, Vec D, InsertMode is)
903: {
904:   Mat_Nest *bA       = (Mat_Nest *)A->data;
905:   PetscBool nnzstate = PETSC_FALSE;

907:   PetscFunctionBegin;
908:   for (PetscInt i = 0; i < bA->nr; i++) {
909:     PetscObjectState subnnzstate = 0;
910:     Vec              bv;
911:     PetscCall(VecGetSubVector(D, bA->isglobal.row[i], &bv));
912:     if (bA->m[i][i]) {
913:       PetscCall(MatDiagonalSet(bA->m[i][i], bv, is));
914:       PetscCall(MatGetNonzeroState(bA->m[i][i], &subnnzstate));
915:     }
916:     PetscCall(VecRestoreSubVector(D, bA->isglobal.row[i], &bv));
917:     nnzstate                     = (PetscBool)(nnzstate || bA->nnzstate[i * bA->nc + i] != subnnzstate);
918:     bA->nnzstate[i * bA->nc + i] = subnnzstate;
919:   }
920:   if (nnzstate) A->nonzerostate++;
921:   PetscFunctionReturn(PETSC_SUCCESS);
922: }

924: static PetscErrorCode MatSetRandom_Nest(Mat A, PetscRandom rctx)
925: {
926:   Mat_Nest *bA = (Mat_Nest *)A->data;

928:   PetscFunctionBegin;
929:   for (PetscInt i = 0; i < bA->nr; i++) {
930:     for (PetscInt j = 0; j < bA->nc; j++) {
931:       if (bA->m[i][j]) PetscCall(MatSetRandom(bA->m[i][j], rctx));
932:     }
933:   }
934:   PetscFunctionReturn(PETSC_SUCCESS);
935: }

937: static PetscErrorCode MatCreateVecs_Nest(Mat A, Vec *right, Vec *left)
938: {
939:   Mat_Nest *bA = (Mat_Nest *)A->data;
940:   Vec      *L, *R;
941:   MPI_Comm  comm;
942:   PetscInt  i, j;

944:   PetscFunctionBegin;
945:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
946:   if (right) {
947:     /* allocate R */
948:     PetscCall(PetscMalloc1(bA->nc, &R));
949:     /* Create the right vectors */
950:     for (j = 0; j < bA->nc; j++) {
951:       for (i = 0; i < bA->nr; i++) {
952:         if (bA->m[i][j]) {
953:           PetscCall(MatCreateVecs(bA->m[i][j], &R[j], NULL));
954:           break;
955:         }
956:       }
957:       PetscCheck(i != bA->nr, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Mat(Nest) contains a null column.");
958:     }
959:     PetscCall(VecCreateNest(comm, bA->nc, bA->isglobal.col, R, right));
960:     /* hand back control to the nest vector */
961:     for (j = 0; j < bA->nc; j++) PetscCall(VecDestroy(&R[j]));
962:     PetscCall(PetscFree(R));
963:   }

965:   if (left) {
966:     /* allocate L */
967:     PetscCall(PetscMalloc1(bA->nr, &L));
968:     /* Create the left vectors */
969:     for (i = 0; i < bA->nr; i++) {
970:       for (j = 0; j < bA->nc; j++) {
971:         if (bA->m[i][j]) {
972:           PetscCall(MatCreateVecs(bA->m[i][j], NULL, &L[i]));
973:           break;
974:         }
975:       }
976:       PetscCheck(j != bA->nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Mat(Nest) contains a null row.");
977:     }

979:     PetscCall(VecCreateNest(comm, bA->nr, bA->isglobal.row, L, left));
980:     for (i = 0; i < bA->nr; i++) PetscCall(VecDestroy(&L[i]));

982:     PetscCall(PetscFree(L));
983:   }
984:   PetscFunctionReturn(PETSC_SUCCESS);
985: }

987: static PetscErrorCode MatView_Nest(Mat A, PetscViewer viewer)
988: {
989:   Mat_Nest *bA = (Mat_Nest *)A->data;
990:   PetscBool isascii, viewSub = PETSC_FALSE;

992:   PetscFunctionBegin;
993:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
994:   if (isascii) {
995:     PetscViewerFormat format;

997:     PetscCall(PetscViewerGetFormat(viewer, &format));
998:     if (format == PETSC_VIEWER_ASCII_MATLAB) {
999:       Mat T;

1001:       PetscCall(MatConvert(A, MATAIJ, MAT_INITIAL_MATRIX, &T));
1002:       PetscCall(MatView(T, viewer));
1003:       PetscCall(MatDestroy(&T));
1004:       PetscFunctionReturn(PETSC_SUCCESS);
1005:     }
1006:     PetscCall(PetscOptionsGetBool(((PetscObject)A)->options, ((PetscObject)A)->prefix, "-mat_view_nest_sub", &viewSub, NULL));
1007:     PetscCall(PetscViewerASCIIPushTab(viewer));
1008:     PetscCall(PetscViewerASCIIPrintf(viewer, "MatNest, rows=%" PetscInt_FMT ", cols=%" PetscInt_FMT ", structure:\n", bA->nr, bA->nc));
1009:     for (PetscInt i = 0; i < bA->nr; i++) {
1010:       for (PetscInt j = 0; j < bA->nc; j++) {
1011:         MatType   type;
1012:         char      name[256] = "", prefix[256] = "";
1013:         PetscInt  NR, NC;
1014:         PetscBool isNest = PETSC_FALSE;

1016:         if (!bA->m[i][j]) {
1017:           PetscCall(PetscViewerASCIIPrintf(viewer, "(%" PetscInt_FMT ",%" PetscInt_FMT ") : NULL\n", i, j));
1018:           continue;
1019:         }
1020:         PetscCall(MatGetSize(bA->m[i][j], &NR, &NC));
1021:         PetscCall(MatGetType(bA->m[i][j], &type));
1022:         if (((PetscObject)bA->m[i][j])->name) PetscCall(PetscSNPrintf(name, sizeof(name), "name=\"%s\", ", ((PetscObject)bA->m[i][j])->name));
1023:         if (((PetscObject)bA->m[i][j])->prefix) PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "prefix=\"%s\", ", ((PetscObject)bA->m[i][j])->prefix));
1024:         PetscCall(PetscObjectTypeCompare((PetscObject)bA->m[i][j], MATNEST, &isNest));

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

1028:         if (isNest || viewSub) {
1029:           PetscCall(PetscViewerASCIIPushTab(viewer)); /* push1 */
1030:           PetscCall(MatView(bA->m[i][j], viewer));
1031:           PetscCall(PetscViewerASCIIPopTab(viewer)); /* pop1 */
1032:         }
1033:       }
1034:     }
1035:     PetscCall(PetscViewerASCIIPopTab(viewer)); /* pop0 */
1036:   }
1037:   PetscFunctionReturn(PETSC_SUCCESS);
1038: }

1040: static PetscErrorCode MatZeroEntries_Nest(Mat A)
1041: {
1042:   Mat_Nest *bA = (Mat_Nest *)A->data;

1044:   PetscFunctionBegin;
1045:   for (PetscInt i = 0; i < bA->nr; i++) {
1046:     for (PetscInt j = 0; j < bA->nc; j++) {
1047:       if (!bA->m[i][j]) continue;
1048:       PetscCall(MatZeroEntries(bA->m[i][j]));
1049:     }
1050:   }
1051:   PetscFunctionReturn(PETSC_SUCCESS);
1052: }

1054: static PetscErrorCode MatCopy_Nest(Mat A, Mat B, MatStructure str)
1055: {
1056:   Mat_Nest *bA = (Mat_Nest *)A->data, *bB = (Mat_Nest *)B->data;
1057:   PetscInt  i, j, nr = bA->nr, nc = bA->nc;
1058:   PetscBool nnzstate = PETSC_FALSE;

1060:   PetscFunctionBegin;
1061:   PetscCheck(nr == bB->nr && nc == bB->nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_INCOMP, "Cannot copy a Mat_Nest of block size (%" PetscInt_FMT ",%" PetscInt_FMT ") to a Mat_Nest of block size (%" PetscInt_FMT ",%" PetscInt_FMT ")", bB->nr, bB->nc, nr, nc);
1062:   for (i = 0; i < nr; i++) {
1063:     for (j = 0; j < nc; j++) {
1064:       PetscObjectState subnnzstate = 0;
1065:       if (bA->m[i][j] && bB->m[i][j]) {
1066:         PetscCall(MatCopy(bA->m[i][j], bB->m[i][j], str));
1067:         PetscCall(MatGetNonzeroState(bB->m[i][j], &subnnzstate));
1068:         nnzstate                 = (PetscBool)(nnzstate || bB->nnzstate[i * nc + j] != subnnzstate);
1069:         bB->nnzstate[i * nc + j] = subnnzstate;
1070:       } else if (bA->m[i][j]) { // bB->m[i][j] is NULL
1071:         Mat M;

1073:         PetscCheck(str == DIFFERENT_NONZERO_PATTERN || str == UNKNOWN_NONZERO_PATTERN, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_INCOMP, "Matrix block does not exist at %" PetscInt_FMT ",%" PetscInt_FMT ". Use DIFFERENT_NONZERO_PATTERN or UNKNOWN_NONZERO_PATTERN", i, j);
1074:         PetscCall(MatDuplicate(bA->m[i][j], MAT_COPY_VALUES, &M));
1075:         PetscCall(MatNestSetSubMat(B, i, j, M));
1076:         PetscCall(MatDestroy(&M));
1077:       } else if (bB->m[i][j]) { // bA->m[i][j] is NULL
1078:         PetscCheck(str == DIFFERENT_NONZERO_PATTERN || str == SUBSET_NONZERO_PATTERN || str == UNKNOWN_NONZERO_PATTERN, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_INCOMP, "Matrix block does not exist at %" PetscInt_FMT ",%" PetscInt_FMT ". Use DIFFERENT_NONZERO_PATTERN, SUBSET_NONZERO_PATTERN or UNKNOWN_NONZERO_PATTERN", i, j);
1079:         PetscCall(MatNestSetSubMat(B, i, j, NULL));
1080:       }
1081:     }
1082:   }
1083:   if (nnzstate) B->nonzerostate++;
1084:   PetscFunctionReturn(PETSC_SUCCESS);
1085: }

1087: static PetscErrorCode MatAXPY_Nest(Mat Y, PetscScalar a, Mat X, MatStructure str)
1088: {
1089:   Mat_Nest *bY = (Mat_Nest *)Y->data, *bX = (Mat_Nest *)X->data;
1090:   PetscInt  i, j, nr = bY->nr, nc = bY->nc;
1091:   PetscBool nnzstate = PETSC_FALSE;

1093:   PetscFunctionBegin;
1094:   PetscCheck(nr == bX->nr && nc == bX->nc, PetscObjectComm((PetscObject)Y), PETSC_ERR_ARG_INCOMP, "Cannot AXPY a MatNest of block size (%" PetscInt_FMT ",%" PetscInt_FMT ") with a MatNest of block size (%" PetscInt_FMT ",%" PetscInt_FMT ")", bX->nr, bX->nc, nr, nc);
1095:   for (i = 0; i < nr; i++) {
1096:     for (j = 0; j < nc; j++) {
1097:       PetscObjectState subnnzstate = 0;
1098:       if (bY->m[i][j] && bX->m[i][j]) {
1099:         PetscCall(MatAXPY(bY->m[i][j], a, bX->m[i][j], str));
1100:       } else if (bX->m[i][j]) {
1101:         Mat M;

1103:         PetscCheck(str == DIFFERENT_NONZERO_PATTERN || str == UNKNOWN_NONZERO_PATTERN, PetscObjectComm((PetscObject)Y), PETSC_ERR_ARG_INCOMP, "Matrix block does not exist at %" PetscInt_FMT ",%" PetscInt_FMT ". Use DIFFERENT_NONZERO_PATTERN or UNKNOWN_NONZERO_PATTERN", i, j);
1104:         PetscCall(MatDuplicate(bX->m[i][j], MAT_COPY_VALUES, &M));
1105:         PetscCall(MatScale(M, a));
1106:         PetscCall(MatNestSetSubMat(Y, i, j, M));
1107:         PetscCall(MatDestroy(&M));
1108:       }
1109:       if (bY->m[i][j]) PetscCall(MatGetNonzeroState(bY->m[i][j], &subnnzstate));
1110:       nnzstate                 = (PetscBool)(nnzstate || bY->nnzstate[i * nc + j] != subnnzstate);
1111:       bY->nnzstate[i * nc + j] = subnnzstate;
1112:     }
1113:   }
1114:   if (nnzstate) Y->nonzerostate++;
1115:   PetscFunctionReturn(PETSC_SUCCESS);
1116: }

1118: static PetscErrorCode MatDuplicate_Nest(Mat A, MatDuplicateOption op, Mat *B)
1119: {
1120:   Mat_Nest *bA = (Mat_Nest *)A->data;
1121:   Mat      *b;
1122:   PetscInt  i, j, nr = bA->nr, nc = bA->nc;

1124:   PetscFunctionBegin;
1125:   PetscCall(PetscMalloc1(nr * nc, &b));
1126:   for (i = 0; i < nr; i++) {
1127:     for (j = 0; j < nc; j++) {
1128:       if (bA->m[i][j]) PetscCall(MatDuplicate(bA->m[i][j], op, &b[i * nc + j]));
1129:       else b[i * nc + j] = NULL;
1130:     }
1131:   }
1132:   PetscCall(MatCreateNest(PetscObjectComm((PetscObject)A), nr, bA->isglobal.row, nc, bA->isglobal.col, b, B));
1133:   /* Give the new MatNest exclusive ownership */
1134:   for (i = 0; i < nr * nc; i++) PetscCall(MatDestroy(&b[i]));
1135:   PetscCall(PetscFree(b));

1137:   PetscCall(MatAssemblyBegin(*B, MAT_FINAL_ASSEMBLY));
1138:   PetscCall(MatAssemblyEnd(*B, MAT_FINAL_ASSEMBLY));
1139:   PetscFunctionReturn(PETSC_SUCCESS);
1140: }

1142: /* nest api */
1143: static PetscErrorCode MatNestGetSubMat_Nest(Mat A, PetscInt idxm, PetscInt jdxm, Mat *mat)
1144: {
1145:   Mat_Nest *bA = (Mat_Nest *)A->data;

1147:   PetscFunctionBegin;
1148:   PetscCheck(idxm < bA->nr, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, idxm, bA->nr - 1);
1149:   PetscCheck(jdxm < bA->nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Col too large: row %" PetscInt_FMT " max %" PetscInt_FMT, jdxm, bA->nc - 1);
1150:   *mat = bA->m[idxm][jdxm];
1151:   PetscFunctionReturn(PETSC_SUCCESS);
1152: }

1154: /*@
1155:   MatNestGetSubMat - Returns a single, sub-matrix from a `MATNEST`

1157:   Not Collective

1159:   Input Parameters:
1160: + A    - `MATNEST` matrix
1161: . idxm - index of the matrix within the nest matrix
1162: - jdxm - index of the matrix within the nest matrix

1164:   Output Parameter:
1165: . sub - matrix at index `idxm`, `jdxm` within the nest matrix

1167:   Level: developer

1169: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestGetSize()`, `MatNestGetSubMats()`, `MatCreateNest()`, `MatNestSetSubMat()`,
1170:           `MatNestGetLocalISs()`, `MatNestGetISs()`
1171: @*/
1172: PetscErrorCode MatNestGetSubMat(Mat A, PetscInt idxm, PetscInt jdxm, Mat *sub)
1173: {
1174:   PetscFunctionBegin;
1178:   PetscAssertPointer(sub, 4);
1179:   PetscUseMethod(A, "MatNestGetSubMat_C", (Mat, PetscInt, PetscInt, Mat *), (A, idxm, jdxm, sub));
1180:   PetscFunctionReturn(PETSC_SUCCESS);
1181: }

1183: static PetscErrorCode MatNestSetSubMat_Nest(Mat A, PetscInt idxm, PetscInt jdxm, Mat mat)
1184: {
1185:   Mat_Nest *bA = (Mat_Nest *)A->data;
1186:   PetscInt  m, n, M, N, mi, ni, Mi, Ni;

1188:   PetscFunctionBegin;
1189:   PetscCheck(idxm < bA->nr, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Row too large: row %" PetscInt_FMT " max %" PetscInt_FMT, idxm, bA->nr - 1);
1190:   PetscCheck(jdxm < bA->nc, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Col too large: row %" PetscInt_FMT " max %" PetscInt_FMT, jdxm, bA->nc - 1);
1191:   if (mat) {
1192:     PetscCall(MatGetLocalSize(mat, &m, &n));
1193:     PetscCall(MatGetSize(mat, &M, &N));
1194:     PetscCall(ISGetLocalSize(bA->isglobal.row[idxm], &mi));
1195:     PetscCall(ISGetSize(bA->isglobal.row[idxm], &Mi));
1196:     PetscCall(ISGetLocalSize(bA->isglobal.col[jdxm], &ni));
1197:     PetscCall(ISGetSize(bA->isglobal.col[jdxm], &Ni));
1198:     PetscCheck(M == Mi && N == Ni, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Submatrix dimension (%" PetscInt_FMT ",%" PetscInt_FMT ") incompatible with nest block (%" PetscInt_FMT ",%" PetscInt_FMT ")", M, N, Mi, Ni);
1199:     PetscCheck(m == mi && n == ni, PetscObjectComm((PetscObject)mat), PETSC_ERR_ARG_INCOMP, "Submatrix local dimension (%" PetscInt_FMT ",%" PetscInt_FMT ") incompatible with nest block (%" PetscInt_FMT ",%" PetscInt_FMT ")", m, n, mi, ni);
1200:   }

1202:   /* do not increase object state */
1203:   if (mat == bA->m[idxm][jdxm]) PetscFunctionReturn(PETSC_SUCCESS);

1205:   PetscCall(PetscObjectReference((PetscObject)mat));
1206:   PetscCall(MatDestroy(&bA->m[idxm][jdxm]));
1207:   bA->m[idxm][jdxm] = mat;
1208:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1209:   if (mat) PetscCall(MatGetNonzeroState(mat, &bA->nnzstate[idxm * bA->nc + jdxm]));
1210:   else bA->nnzstate[idxm * bA->nc + jdxm] = 0;
1211:   A->nonzerostate++;
1212:   PetscFunctionReturn(PETSC_SUCCESS);
1213: }

1215: /*@
1216:   MatNestSetSubMat - Set a single submatrix in the `MATNEST`

1218:   Logically Collective

1220:   Input Parameters:
1221: + A    - `MATNEST` matrix
1222: . idxm - index of the matrix within the nest matrix
1223: . jdxm - index of the matrix within the nest matrix
1224: - sub  - matrix at index `idxm`, `jdxm` within the nest matrix

1226:   Level: developer

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

1231:   This increments the reference count of the submatrix.

1233: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestSetSubMats()`, `MatNestGetSubMats()`, `MatNestGetLocalISs()`, `MatCreateNest()`,
1234:           `MatNestGetSubMat()`, `MatNestGetISs()`, `MatNestGetSize()`
1235: @*/
1236: PetscErrorCode MatNestSetSubMat(Mat A, PetscInt idxm, PetscInt jdxm, Mat sub)
1237: {
1238:   PetscFunctionBegin;
1243:   PetscTryMethod(A, "MatNestSetSubMat_C", (Mat, PetscInt, PetscInt, Mat), (A, idxm, jdxm, sub));
1244:   PetscFunctionReturn(PETSC_SUCCESS);
1245: }

1247: static PetscErrorCode MatNestGetSubMats_Nest(Mat A, PetscInt *M, PetscInt *N, Mat ***mat)
1248: {
1249:   Mat_Nest *bA = (Mat_Nest *)A->data;

1251:   PetscFunctionBegin;
1252:   if (M) *M = bA->nr;
1253:   if (N) *N = bA->nc;
1254:   if (mat) *mat = bA->m;
1255:   PetscFunctionReturn(PETSC_SUCCESS);
1256: }

1258: /*@
1259:   MatNestGetSubMats - Returns the entire two dimensional array of matrices defining a `MATNEST` matrix.

1261:   Not Collective

1263:   Input Parameter:
1264: . A - nest matrix

1266:   Output Parameters:
1267: + M   - number of submatrix rows in the nest matrix
1268: . N   - number of submatrix columns in the nest matrix
1269: - mat - array of matrices

1271:   Level: developer

1273:   Note:
1274:   The user should not free the array `mat`.

1276:   Fortran Notes:
1277:   This routine has a calling sequence `call MatNestGetSubMats(A, M, N, mat, ierr)`
1278:   where the space allocated for the optional argument `mat` is assumed large enough (if provided).
1279:   Matrices in `mat` are returned in row-major order, see `MatCreateNest()` for an example.

1281: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestGetSize()`, `MatNestGetSubMat()`, `MatNestGetLocalISs()`, `MatCreateNest()`,
1282:           `MatNestSetSubMats()`, `MatNestGetISs()`, `MatNestSetSubMat()`
1283: @*/
1284: PetscErrorCode MatNestGetSubMats(Mat A, PetscInt *M, PetscInt *N, Mat ***mat)
1285: {
1286:   PetscFunctionBegin;
1288:   PetscUseMethod(A, "MatNestGetSubMats_C", (Mat, PetscInt *, PetscInt *, Mat ***), (A, M, N, mat));
1289:   PetscFunctionReturn(PETSC_SUCCESS);
1290: }

1292: static PetscErrorCode MatNestGetSize_Nest(Mat A, PetscInt *M, PetscInt *N)
1293: {
1294:   Mat_Nest *bA = (Mat_Nest *)A->data;

1296:   PetscFunctionBegin;
1297:   if (M) *M = bA->nr;
1298:   if (N) *N = bA->nc;
1299:   PetscFunctionReturn(PETSC_SUCCESS);
1300: }

1302: /*@
1303:   MatNestGetSize - Returns the size of the `MATNEST` matrix.

1305:   Not Collective

1307:   Input Parameter:
1308: . A - `MATNEST` matrix

1310:   Output Parameters:
1311: + M - number of rows in the nested mat
1312: - N - number of cols in the nested mat

1314:   Level: developer

1316:   Note:
1317:   `size` refers to the number of submatrices in the row and column directions of the nested matrix

1319: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestGetSubMat()`, `MatNestGetSubMats()`, `MatCreateNest()`, `MatNestGetLocalISs()`,
1320:           `MatNestGetISs()`
1321: @*/
1322: PetscErrorCode MatNestGetSize(Mat A, PetscInt *M, PetscInt *N)
1323: {
1324:   PetscFunctionBegin;
1326:   PetscUseMethod(A, "MatNestGetSize_C", (Mat, PetscInt *, PetscInt *), (A, M, N));
1327:   PetscFunctionReturn(PETSC_SUCCESS);
1328: }

1330: static PetscErrorCode MatNestGetISs_Nest(Mat A, IS rows[], IS cols[])
1331: {
1332:   Mat_Nest *vs = (Mat_Nest *)A->data;

1334:   PetscFunctionBegin;
1335:   if (rows) {
1336:     for (PetscInt i = 0; i < vs->nr; i++) rows[i] = vs->isglobal.row[i];
1337:   }
1338:   if (cols) {
1339:     for (PetscInt i = 0; i < vs->nc; i++) cols[i] = vs->isglobal.col[i];
1340:   }
1341:   PetscFunctionReturn(PETSC_SUCCESS);
1342: }

1344: /*@
1345:   MatNestGetISs - Returns the index sets partitioning the row and column spaces of a `MATNEST`

1347:   Not Collective

1349:   Input Parameter:
1350: . A - `MATNEST` matrix

1352:   Output Parameters:
1353: + rows - array of row index sets (pass `NULL` to ignore)
1354: - cols - array of column index sets (pass `NULL` to ignore)

1356:   Level: advanced

1358:   Note:
1359:   The user must have allocated arrays of the correct size. The reference count is not increased on the returned `IS`s.

1361: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestGetSubMat()`, `MatNestGetSubMats()`, `MatNestGetSize()`, `MatNestGetLocalISs()`,
1362:           `MatCreateNest()`, `MatNestSetSubMats()`
1363: @*/
1364: PetscErrorCode MatNestGetISs(Mat A, IS rows[], IS cols[])
1365: {
1366:   PetscFunctionBegin;
1368:   PetscUseMethod(A, "MatNestGetISs_C", (Mat, IS[], IS[]), (A, rows, cols));
1369:   PetscFunctionReturn(PETSC_SUCCESS);
1370: }

1372: static PetscErrorCode MatNestGetLocalISs_Nest(Mat A, IS rows[], IS cols[])
1373: {
1374:   Mat_Nest *vs = (Mat_Nest *)A->data;

1376:   PetscFunctionBegin;
1377:   if (rows) {
1378:     for (PetscInt i = 0; i < vs->nr; i++) rows[i] = vs->islocal.row[i];
1379:   }
1380:   if (cols) {
1381:     for (PetscInt i = 0; i < vs->nc; i++) cols[i] = vs->islocal.col[i];
1382:   }
1383:   PetscFunctionReturn(PETSC_SUCCESS);
1384: }

1386: /*@
1387:   MatNestGetLocalISs - Returns the index sets partitioning the row and column spaces of a `MATNEST`

1389:   Not Collective

1391:   Input Parameter:
1392: . A - `MATNEST` matrix

1394:   Output Parameters:
1395: + rows - array of row index sets (pass `NULL` to ignore)
1396: - cols - array of column index sets (pass `NULL` to ignore)

1398:   Level: advanced

1400:   Note:
1401:   The user must have allocated arrays of the correct size. The reference count is not increased on the returned `IS`s.

1403: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatNestGetSubMat()`, `MatNestGetSubMats()`, `MatNestGetSize()`, `MatNestGetISs()`, `MatCreateNest()`,
1404:           `MatNestSetSubMats()`, `MatNestSetSubMat()`
1405: @*/
1406: PetscErrorCode MatNestGetLocalISs(Mat A, IS rows[], IS cols[])
1407: {
1408:   PetscFunctionBegin;
1410:   PetscUseMethod(A, "MatNestGetLocalISs_C", (Mat, IS[], IS[]), (A, rows, cols));
1411:   PetscFunctionReturn(PETSC_SUCCESS);
1412: }

1414: static PetscErrorCode MatNestSetVecType_Nest(Mat A, VecType vtype)
1415: {
1416:   PetscBool flg;

1418:   PetscFunctionBegin;
1419:   PetscCall(PetscStrcmp(vtype, VECNEST, &flg));
1420:   /* In reality, this only distinguishes VECNEST and "other" */
1421:   if (flg) A->ops->getvecs = MatCreateVecs_Nest;
1422:   else A->ops->getvecs = NULL;
1423:   PetscFunctionReturn(PETSC_SUCCESS);
1424: }

1426: /*@
1427:   MatNestSetVecType - Sets the type of `Vec` returned by `MatCreateVecs()`

1429:   Not Collective

1431:   Input Parameters:
1432: + A     - `MATNEST` matrix
1433: - vtype - `VecType` to use for creating vectors

1435:   Level: developer

1437: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatCreateVecs()`, `MatCreateNest()`, `VecType`
1438: @*/
1439: PetscErrorCode MatNestSetVecType(Mat A, VecType vtype)
1440: {
1441:   PetscFunctionBegin;
1443:   PetscTryMethod(A, "MatNestSetVecType_C", (Mat, VecType), (A, vtype));
1444:   PetscFunctionReturn(PETSC_SUCCESS);
1445: }

1447: static PetscErrorCode MatNestSetSubMats_Nest(Mat A, PetscInt nr, const IS is_row[], PetscInt nc, const IS is_col[], const Mat a[])
1448: {
1449:   Mat_Nest *s = (Mat_Nest *)A->data;
1450:   PetscInt  i, j, m, n, M, N;
1451:   PetscBool cong, isstd, sametype = PETSC_FALSE;
1452:   VecType   vtype, type;

1454:   PetscFunctionBegin;
1455:   PetscCall(MatReset_Nest(A));

1457:   s->nr = nr;
1458:   s->nc = nc;

1460:   /* Create space for submatrices */
1461:   PetscCall(PetscMalloc1(nr, &s->m));
1462:   PetscCall(PetscMalloc1(nr * nc, &s->m[0]));
1463:   for (i = 0; i < nr; i++) {
1464:     s->m[i] = s->m[0] + i * nc;
1465:     for (j = 0; j < nc; j++) {
1466:       s->m[i][j] = a ? a[i * nc + j] : NULL;
1467:       PetscCall(PetscObjectReference((PetscObject)s->m[i][j]));
1468:     }
1469:   }
1470:   PetscCall(MatGetVecType(A, &vtype));
1471:   PetscCall(PetscStrcmp(vtype, VECSTANDARD, &isstd));
1472:   if (isstd) {
1473:     /* check if all blocks have the same vectype */
1474:     vtype = NULL;
1475:     for (i = 0; i < nr; i++) {
1476:       for (j = 0; j < nc; j++) {
1477:         if (s->m[i][j]) {
1478:           if (!vtype) { /* first visited block */
1479:             PetscCall(MatGetVecType(s->m[i][j], &vtype));
1480:             sametype = PETSC_TRUE;
1481:           } else if (sametype) {
1482:             PetscCall(MatGetVecType(s->m[i][j], &type));
1483:             PetscCall(PetscStrcmp(vtype, type, &sametype));
1484:           }
1485:         }
1486:       }
1487:     }
1488:     if (sametype) { /* propagate vectype */
1489:       PetscCall(MatSetVecType(A, vtype));
1490:     }
1491:   }

1493:   PetscCall(MatSetUp_NestIS_Private(A, nr, is_row, nc, is_col));

1495:   PetscCall(PetscMalloc1(nr, &s->row_len));
1496:   PetscCall(PetscMalloc1(nc, &s->col_len));
1497:   for (i = 0; i < nr; i++) s->row_len[i] = -1;
1498:   for (j = 0; j < nc; j++) s->col_len[j] = -1;

1500:   PetscCall(PetscCalloc1(nr * nc, &s->nnzstate));
1501:   for (i = 0; i < nr; i++) {
1502:     for (j = 0; j < nc; j++) {
1503:       if (s->m[i][j]) PetscCall(MatGetNonzeroState(s->m[i][j], &s->nnzstate[i * nc + j]));
1504:     }
1505:   }

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

1509:   PetscCall(PetscLayoutSetSize(A->rmap, M));
1510:   PetscCall(PetscLayoutSetLocalSize(A->rmap, m));
1511:   PetscCall(PetscLayoutSetSize(A->cmap, N));
1512:   PetscCall(PetscLayoutSetLocalSize(A->cmap, n));

1514:   PetscCall(PetscLayoutSetUp(A->rmap));
1515:   PetscCall(PetscLayoutSetUp(A->cmap));

1517:   /* disable operations that are not supported for non-square matrices,
1518:      or matrices for which is_row != is_col  */
1519:   PetscCall(MatHasCongruentLayouts(A, &cong));
1520:   if (cong && nr != nc) cong = PETSC_FALSE;
1521:   if (cong) {
1522:     for (i = 0; cong && i < nr; i++) PetscCall(ISEqualUnsorted(s->isglobal.row[i], s->isglobal.col[i], &cong));
1523:   }
1524:   if (!cong) {
1525:     A->ops->getdiagonal = NULL;
1526:     A->ops->shift       = NULL;
1527:     A->ops->diagonalset = NULL;
1528:   }

1530:   PetscCall(PetscCalloc2(nr, &s->left, nc, &s->right));
1531:   PetscCall(PetscObjectStateIncrease((PetscObject)A));
1532:   A->nonzerostate++;
1533:   PetscFunctionReturn(PETSC_SUCCESS);
1534: }

1536: /*@
1537:   MatNestSetSubMats - Sets the nested submatrices in a `MATNEST`

1539:   Collective

1541:   Input Parameters:
1542: + A      - `MATNEST` matrix
1543: . nr     - number of nested row blocks
1544: . is_row - index sets for each nested row block, or `NULL` to make contiguous
1545: . nc     - number of nested column blocks
1546: . is_col - index sets for each nested column block, or `NULL` to make contiguous
1547: - a      - array of $ nr \times nc$ submatrices, or `NULL`

1549:   Level: advanced

1551:   Notes:
1552:   This always resets any block matrix information previously set.

1554:   Pass `NULL` in the corresponding entry of `a` for an empty block.

1556:   In both C and Fortran, `a` must be a one-dimensional array representing a two-dimensional row-major order array containing the matrices. See
1557:   `MatCreateNest()` for an example.

1559:   Fortran Note:
1560:   Pass `PETSC_NULL_MAT` in the corresponding entry of `a` for an empty block

1562: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatCreateNest()`, `MatNestSetSubMat()`, `MatNestGetSubMat()`, `MatNestGetSubMats()`
1563: @*/
1564: PetscErrorCode MatNestSetSubMats(Mat A, PetscInt nr, const IS is_row[], PetscInt nc, const IS is_col[], const Mat a[]) PeNSS
1565: {
1566:   PetscFunctionBegin;
1569:   PetscCheck(nr >= 0, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Number of rows cannot be negative");
1570:   if (nr && is_row) {
1571:     PetscAssertPointer(is_row, 3);
1573:   }
1575:   PetscCheck(nc >= 0, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_OUTOFRANGE, "Number of columns cannot be negative");
1576:   if (nc && is_col) {
1577:     PetscAssertPointer(is_col, 5);
1579:   }
1580:   PetscTryMethod(A, "MatNestSetSubMats_C", (Mat, PetscInt, const IS[], PetscInt, const IS[], const Mat[]), (A, nr, is_row, nc, is_col, a));
1581:   PetscFunctionReturn(PETSC_SUCCESS);
1582: }

1584: static PetscErrorCode MatNestCreateAggregateL2G_Private(Mat A, PetscInt n, const IS islocal[], const IS isglobal[], PetscBool colflg, ISLocalToGlobalMapping *ltog)
1585: {
1586:   PetscBool flg;
1587:   PetscInt  i, j, m, mi, *ix;

1589:   PetscFunctionBegin;
1590:   *ltog = NULL;
1591:   for (i = 0, m = 0, flg = PETSC_FALSE; i < n; i++) {
1592:     if (islocal[i]) {
1593:       PetscCall(ISGetLocalSize(islocal[i], &mi));
1594:       flg = PETSC_TRUE; /* We found a non-trivial entry */
1595:     } else {
1596:       PetscCall(ISGetLocalSize(isglobal[i], &mi));
1597:     }
1598:     m += mi;
1599:   }
1600:   if (!flg) PetscFunctionReturn(PETSC_SUCCESS);

1602:   PetscCall(PetscMalloc1(m, &ix));
1603:   for (i = 0, m = 0; i < n; i++) {
1604:     ISLocalToGlobalMapping smap = NULL;
1605:     Mat                    sub  = NULL;
1606:     PetscSF                sf;
1607:     PetscLayout            map;
1608:     const PetscInt        *ix2;

1610:     if (!colflg) {
1611:       PetscCall(MatNestFindNonzeroSubMatRow(A, i, &sub));
1612:     } else {
1613:       PetscCall(MatNestFindNonzeroSubMatCol(A, i, &sub));
1614:     }
1615:     if (sub) {
1616:       if (!colflg) PetscCall(MatGetLocalToGlobalMapping(sub, &smap, NULL));
1617:       else PetscCall(MatGetLocalToGlobalMapping(sub, NULL, &smap));
1618:     }
1619:     /*
1620:        Now we need to extract the monolithic global indices that correspond to the given split global indices.
1621:        In many/most cases, we only want MatGetLocalSubMatrix() to work, in which case we only need to know the size of the local spaces.
1622:     */
1623:     PetscCall(ISGetIndices(isglobal[i], &ix2));
1624:     if (islocal[i]) {
1625:       PetscInt *ilocal, *iremote;
1626:       PetscInt  mil, nleaves;

1628:       PetscCall(ISGetLocalSize(islocal[i], &mi));
1629:       PetscCheck(smap, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Missing local to global map");
1630:       for (j = 0; j < mi; j++) ix[m + j] = j;
1631:       PetscCall(ISLocalToGlobalMappingApply(smap, mi, ix + m, ix + m));

1633:       /* PetscSFSetGraphLayout does not like negative indices */
1634:       PetscCall(PetscMalloc2(mi, &ilocal, mi, &iremote));
1635:       for (j = 0, nleaves = 0; j < mi; j++) {
1636:         if (ix[m + j] < 0) continue;
1637:         ilocal[nleaves]  = j;
1638:         iremote[nleaves] = ix[m + j];
1639:         nleaves++;
1640:       }
1641:       PetscCall(ISGetLocalSize(isglobal[i], &mil));
1642:       PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &sf));
1643:       PetscCall(PetscLayoutCreate(PetscObjectComm((PetscObject)A), &map));
1644:       PetscCall(PetscLayoutSetLocalSize(map, mil));
1645:       PetscCall(PetscLayoutSetUp(map));
1646:       PetscCall(PetscSFSetGraphLayout(sf, map, nleaves, ilocal, PETSC_USE_POINTER, iremote));
1647:       PetscCall(PetscLayoutDestroy(&map));
1648:       PetscCall(PetscSFBcastBegin(sf, MPIU_INT, ix2, ix + m, MPI_REPLACE));
1649:       PetscCall(PetscSFBcastEnd(sf, MPIU_INT, ix2, ix + m, MPI_REPLACE));
1650:       PetscCall(PetscSFDestroy(&sf));
1651:       PetscCall(PetscFree2(ilocal, iremote));
1652:     } else {
1653:       PetscCall(ISGetLocalSize(isglobal[i], &mi));
1654:       for (j = 0; j < mi; j++) ix[m + j] = ix2[j];
1655:     }
1656:     PetscCall(ISRestoreIndices(isglobal[i], &ix2));
1657:     m += mi;
1658:   }
1659:   PetscCall(ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)A), 1, m, ix, PETSC_OWN_POINTER, ltog));
1660:   PetscFunctionReturn(PETSC_SUCCESS);
1661: }

1663: /* If an IS was provided, there is nothing Nest needs to do, otherwise Nest will build a strided IS */
1664: /*
1665:   nprocessors = NP
1666:   Nest x^T = ((g_0,g_1,...g_nprocs-1), (h_0,h_1,...h_NP-1))
1667:        proc 0: => (g_0,h_0,)
1668:        proc 1: => (g_1,h_1,)
1669:        ...
1670:        proc nprocs-1: => (g_NP-1,h_NP-1,)

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

1675:             proc 0:
1676:     is[1] = (nlocal(g_0),nlocal(g_0)+1,...,nlocal(g_0)+nlocal(h_0)-1)
1677:             proc 1:
1678:     is[1] = (nlocal(g_1),nlocal(g_1)+1,...,nlocal(g_1)+nlocal(h_1)-1)

1680:             proc NP-1:
1681:     is[1] = (nlocal(g_NP-1),nlocal(g_NP-1)+1,...,nlocal(g_NP-1)+nlocal(h_NP-1)-1)
1682: */
1683: static PetscErrorCode MatSetUp_NestIS_Private(Mat A, PetscInt nr, const IS is_row[], PetscInt nc, const IS is_col[])
1684: {
1685:   Mat_Nest *vs = (Mat_Nest *)A->data;
1686:   PetscInt  i, j, offset, n, nsum, bs;
1687:   Mat       sub = NULL;

1689:   PetscFunctionBegin;
1690:   PetscCall(PetscMalloc1(nr, &vs->isglobal.row));
1691:   PetscCall(PetscMalloc1(nc, &vs->isglobal.col));
1692:   if (is_row) { /* valid IS is passed in */
1693:     /* refs on is[] are incremented */
1694:     for (i = 0; i < vs->nr; i++) {
1695:       PetscCall(PetscObjectReference((PetscObject)is_row[i]));
1696:       vs->isglobal.row[i] = is_row[i];
1697:     }
1698:   } else { /* Create the ISs by inspecting sizes of a submatrix in each row */
1699:     nsum = 0;
1700:     for (i = 0; i < vs->nr; i++) { /* Add up the local sizes to compute the aggregate offset */
1701:       PetscCall(MatNestFindNonzeroSubMatRow(A, i, &sub));
1702:       PetscCheck(sub, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "No nonzero submatrix in row %" PetscInt_FMT, i);
1703:       PetscCall(MatGetLocalSize(sub, &n, NULL));
1704:       PetscCheck(n >= 0, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Sizes have not yet been set for submatrix");
1705:       nsum += n;
1706:     }
1707:     PetscCallMPI(MPI_Scan(&nsum, &offset, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)A)));
1708:     offset -= nsum;
1709:     for (i = 0; i < vs->nr; i++) {
1710:       PetscCall(MatNestFindNonzeroSubMatRow(A, i, &sub));
1711:       PetscCall(MatGetLocalSize(sub, &n, NULL));
1712:       PetscCall(MatGetBlockSizes(sub, &bs, NULL));
1713:       PetscCall(ISCreateStride(PetscObjectComm((PetscObject)sub), n, offset, 1, &vs->isglobal.row[i]));
1714:       PetscCall(ISSetBlockSize(vs->isglobal.row[i], bs));
1715:       offset += n;
1716:     }
1717:   }

1719:   if (is_col) { /* valid IS is passed in */
1720:     /* refs on is[] are incremented */
1721:     for (j = 0; j < vs->nc; j++) {
1722:       PetscCall(PetscObjectReference((PetscObject)is_col[j]));
1723:       vs->isglobal.col[j] = is_col[j];
1724:     }
1725:   } else { /* Create the ISs by inspecting sizes of a submatrix in each column */
1726:     offset = A->cmap->rstart;
1727:     nsum   = 0;
1728:     for (j = 0; j < vs->nc; j++) {
1729:       PetscCall(MatNestFindNonzeroSubMatCol(A, j, &sub));
1730:       PetscCheck(sub, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "No nonzero submatrix in column %" PetscInt_FMT, i);
1731:       PetscCall(MatGetLocalSize(sub, NULL, &n));
1732:       PetscCheck(n >= 0, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Sizes have not yet been set for submatrix");
1733:       nsum += n;
1734:     }
1735:     PetscCallMPI(MPI_Scan(&nsum, &offset, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)A)));
1736:     offset -= nsum;
1737:     for (j = 0; j < vs->nc; j++) {
1738:       PetscCall(MatNestFindNonzeroSubMatCol(A, j, &sub));
1739:       PetscCall(MatGetLocalSize(sub, NULL, &n));
1740:       PetscCall(MatGetBlockSizes(sub, NULL, &bs));
1741:       PetscCall(ISCreateStride(PetscObjectComm((PetscObject)sub), n, offset, 1, &vs->isglobal.col[j]));
1742:       PetscCall(ISSetBlockSize(vs->isglobal.col[j], bs));
1743:       offset += n;
1744:     }
1745:   }

1747:   /* Set up the local ISs */
1748:   PetscCall(PetscMalloc1(vs->nr, &vs->islocal.row));
1749:   PetscCall(PetscMalloc1(vs->nc, &vs->islocal.col));
1750:   for (i = 0, offset = 0; i < vs->nr; i++) {
1751:     IS                     isloc;
1752:     ISLocalToGlobalMapping rmap = NULL;
1753:     PetscInt               nlocal, bs;
1754:     PetscCall(MatNestFindNonzeroSubMatRow(A, i, &sub));
1755:     if (sub) PetscCall(MatGetLocalToGlobalMapping(sub, &rmap, NULL));
1756:     if (rmap) {
1757:       PetscCall(MatGetBlockSizes(sub, &bs, NULL));
1758:       PetscCall(ISLocalToGlobalMappingGetSize(rmap, &nlocal));
1759:       PetscCall(ISCreateStride(PETSC_COMM_SELF, nlocal, offset, 1, &isloc));
1760:       PetscCall(ISSetBlockSize(isloc, bs));
1761:     } else {
1762:       nlocal = 0;
1763:       isloc  = NULL;
1764:     }
1765:     vs->islocal.row[i] = isloc;
1766:     offset += nlocal;
1767:   }
1768:   for (i = 0, offset = 0; i < vs->nc; i++) {
1769:     IS                     isloc;
1770:     ISLocalToGlobalMapping cmap = NULL;
1771:     PetscInt               nlocal, bs;
1772:     PetscCall(MatNestFindNonzeroSubMatCol(A, i, &sub));
1773:     if (sub) PetscCall(MatGetLocalToGlobalMapping(sub, NULL, &cmap));
1774:     if (cmap) {
1775:       PetscCall(MatGetBlockSizes(sub, NULL, &bs));
1776:       PetscCall(ISLocalToGlobalMappingGetSize(cmap, &nlocal));
1777:       PetscCall(ISCreateStride(PETSC_COMM_SELF, nlocal, offset, 1, &isloc));
1778:       PetscCall(ISSetBlockSize(isloc, bs));
1779:     } else {
1780:       nlocal = 0;
1781:       isloc  = NULL;
1782:     }
1783:     vs->islocal.col[i] = isloc;
1784:     offset += nlocal;
1785:   }

1787:   /* Set up the aggregate ISLocalToGlobalMapping */
1788:   {
1789:     ISLocalToGlobalMapping rmap, cmap;
1790:     PetscCall(MatNestCreateAggregateL2G_Private(A, vs->nr, vs->islocal.row, vs->isglobal.row, PETSC_FALSE, &rmap));
1791:     PetscCall(MatNestCreateAggregateL2G_Private(A, vs->nc, vs->islocal.col, vs->isglobal.col, PETSC_TRUE, &cmap));
1792:     if (rmap && cmap) PetscCall(MatSetLocalToGlobalMapping(A, rmap, cmap));
1793:     PetscCall(ISLocalToGlobalMappingDestroy(&rmap));
1794:     PetscCall(ISLocalToGlobalMappingDestroy(&cmap));
1795:   }

1797:   if (PetscDefined(USE_DEBUG)) {
1798:     for (i = 0; i < vs->nr; i++) {
1799:       for (j = 0; j < vs->nc; j++) {
1800:         PetscInt m, n, M, N, mi, ni, Mi, Ni;
1801:         Mat      B = vs->m[i][j];
1802:         if (!B) continue;
1803:         PetscCall(MatGetSize(B, &M, &N));
1804:         PetscCall(MatGetLocalSize(B, &m, &n));
1805:         PetscCall(ISGetSize(vs->isglobal.row[i], &Mi));
1806:         PetscCall(ISGetSize(vs->isglobal.col[j], &Ni));
1807:         PetscCall(ISGetLocalSize(vs->isglobal.row[i], &mi));
1808:         PetscCall(ISGetLocalSize(vs->isglobal.col[j], &ni));
1809:         PetscCheck(M == Mi && N == Ni, PetscObjectComm((PetscObject)sub), PETSC_ERR_ARG_INCOMP, "Global sizes (%" PetscInt_FMT ",%" PetscInt_FMT ") of nested submatrix (%" PetscInt_FMT ",%" PetscInt_FMT ") do not agree with space defined by index sets (%" PetscInt_FMT ",%" PetscInt_FMT ")", M, N, i, j, Mi, Ni);
1810:         PetscCheck(m == mi && n == ni, PetscObjectComm((PetscObject)sub), PETSC_ERR_ARG_INCOMP, "Local sizes (%" PetscInt_FMT ",%" PetscInt_FMT ") of nested submatrix (%" PetscInt_FMT ",%" PetscInt_FMT ") do not agree with space defined by index sets (%" PetscInt_FMT ",%" PetscInt_FMT ")", m, n, i, j, mi, ni);
1811:       }
1812:     }
1813:   }

1815:   /* Set A->assembled if all non-null blocks are currently assembled */
1816:   for (i = 0; i < vs->nr; i++) {
1817:     for (j = 0; j < vs->nc; j++) {
1818:       if (vs->m[i][j] && !vs->m[i][j]->assembled) PetscFunctionReturn(PETSC_SUCCESS);
1819:     }
1820:   }
1821:   A->assembled = PETSC_TRUE;
1822:   PetscFunctionReturn(PETSC_SUCCESS);
1823: }

1825: /*@
1826:   MatCreateNest - Creates a new `MATNEST` matrix containing several nested submatrices, each stored separately

1828:   Collective

1830:   Input Parameters:
1831: + comm   - Communicator for the new `MATNEST`
1832: . nr     - number of nested row blocks
1833: . is_row - index sets for each nested row block, or `NULL` to make contiguous
1834: . nc     - number of nested column blocks
1835: . is_col - index sets for each nested column block, or `NULL` to make contiguous
1836: - a      - array of $nr \times nc$ submatrices, empty submatrices can be passed using `NULL`

1838:   Output Parameter:
1839: . B - new matrix

1841:   Level: advanced

1843:   Note:
1844:   In both C and Fortran, `a` must be a one-dimensional array representing a two-dimensional row-major order array holding references to the matrices.
1845:   For instance, to represent the matrix
1846:   $\begin{bmatrix} A_{11} & A_{12} \\ A_{21} & A_{22}\end{bmatrix}$
1847:   one should use `Mat a[4]={A11,A12,A21,A22}`.

1849:   Fortran Note:
1850:   Pass `PETSC_NULL_MAT` in the corresponding entry of `a` for an empty block

1852: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatCreate()`, `VecCreateNest()`, `DMCreateMatrix()`, `MatNestSetSubMat()`,
1853:           `MatNestGetSubMat()`, `MatNestGetLocalISs()`, `MatNestGetSize()`,
1854:           `MatNestGetISs()`, `MatNestSetSubMats()`, `MatNestGetSubMats()`
1855: @*/
1856: PetscErrorCode MatCreateNest(MPI_Comm comm, PetscInt nr, const IS is_row[], PetscInt nc, const IS is_col[], const Mat a[], Mat *B) PeNSS
1857: {
1858:   PetscFunctionBegin;
1859:   PetscCall(MatCreate(comm, B));
1860:   PetscCall(MatSetType(*B, MATNEST));
1861:   (*B)->preallocated = PETSC_TRUE;
1862:   PetscCall(MatNestSetSubMats(*B, nr, is_row, nc, is_col, a));
1863:   PetscFunctionReturn(PETSC_SUCCESS);
1864: }

1866: static PetscErrorCode MatConvert_Nest_SeqAIJ_fast(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
1867: {
1868:   Mat_Nest     *nest = (Mat_Nest *)A->data;
1869:   Mat          *trans;
1870:   PetscScalar **avv;
1871:   PetscScalar  *vv;
1872:   PetscInt    **aii, **ajj;
1873:   PetscInt     *ii, *jj, *ci;
1874:   PetscInt      nr, nc, nnz, i, j;
1875:   PetscBool     done;

1877:   PetscFunctionBegin;
1878:   PetscCall(MatGetSize(A, &nr, &nc));
1879:   if (reuse == MAT_REUSE_MATRIX) {
1880:     PetscInt rnr;

1882:     PetscCall(MatGetRowIJ(*newmat, 0, PETSC_FALSE, PETSC_FALSE, &rnr, (const PetscInt **)&ii, (const PetscInt **)&jj, &done));
1883:     PetscCheck(done, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "MatGetRowIJ");
1884:     PetscCheck(rnr == nr, PetscObjectComm((PetscObject)A), PETSC_ERR_USER, "Cannot reuse matrix, wrong number of rows");
1885:     PetscCall(MatSeqAIJGetArray(*newmat, &vv));
1886:   }
1887:   /* extract CSR for nested SeqAIJ matrices */
1888:   nnz = 0;
1889:   PetscCall(PetscCalloc4(nest->nr * nest->nc, &aii, nest->nr * nest->nc, &ajj, nest->nr * nest->nc, &avv, nest->nr * nest->nc, &trans));
1890:   for (i = 0; i < nest->nr; ++i) {
1891:     for (j = 0; j < nest->nc; ++j) {
1892:       Mat B = nest->m[i][j];
1893:       if (B) {
1894:         PetscScalar *naa;
1895:         PetscInt    *nii, *njj, nnr;
1896:         PetscBool    istrans;

1898:         PetscCall(PetscObjectTypeCompare((PetscObject)B, MATTRANSPOSEVIRTUAL, &istrans));
1899:         if (istrans) {
1900:           Mat Bt;

1902:           PetscCall(MatTransposeGetMat(B, &Bt));
1903:           PetscCall(MatTranspose(Bt, MAT_INITIAL_MATRIX, &trans[i * nest->nc + j]));
1904:           B = trans[i * nest->nc + j];
1905:         } else {
1906:           PetscCall(PetscObjectTypeCompare((PetscObject)B, MATHERMITIANTRANSPOSEVIRTUAL, &istrans));
1907:           if (istrans) {
1908:             Mat Bt;

1910:             PetscCall(MatHermitianTransposeGetMat(B, &Bt));
1911:             PetscCall(MatHermitianTranspose(Bt, MAT_INITIAL_MATRIX, &trans[i * nest->nc + j]));
1912:             B = trans[i * nest->nc + j];
1913:           }
1914:         }
1915:         PetscCall(MatGetRowIJ(B, 0, PETSC_FALSE, PETSC_FALSE, &nnr, (const PetscInt **)&nii, (const PetscInt **)&njj, &done));
1916:         PetscCheck(done, PetscObjectComm((PetscObject)B), PETSC_ERR_PLIB, "MatGetRowIJ");
1917:         PetscCall(MatSeqAIJGetArray(B, &naa));
1918:         nnz += nii[nnr];

1920:         aii[i * nest->nc + j] = nii;
1921:         ajj[i * nest->nc + j] = njj;
1922:         avv[i * nest->nc + j] = naa;
1923:       }
1924:     }
1925:   }
1926:   if (reuse != MAT_REUSE_MATRIX) {
1927:     PetscCall(PetscMalloc1(nr + 1, &ii));
1928:     PetscCall(PetscMalloc1(nnz, &jj));
1929:     PetscCall(PetscMalloc1(nnz, &vv));
1930:   } else {
1931:     PetscCheck(nnz == ii[nr], PetscObjectComm((PetscObject)A), PETSC_ERR_USER, "Cannot reuse matrix, wrong number of nonzeros");
1932:   }

1934:   /* new row pointer */
1935:   PetscCall(PetscArrayzero(ii, nr + 1));
1936:   for (i = 0; i < nest->nr; ++i) {
1937:     PetscInt ncr, rst;

1939:     PetscCall(ISStrideGetInfo(nest->isglobal.row[i], &rst, NULL));
1940:     PetscCall(ISGetLocalSize(nest->isglobal.row[i], &ncr));
1941:     for (j = 0; j < nest->nc; ++j) {
1942:       if (aii[i * nest->nc + j]) {
1943:         PetscInt *nii = aii[i * nest->nc + j];

1945:         for (PetscInt ir = rst; ir < ncr + rst; ++ir) {
1946:           ii[ir + 1] += nii[1] - nii[0];
1947:           nii++;
1948:         }
1949:       }
1950:     }
1951:   }
1952:   for (i = 0; i < nr; i++) ii[i + 1] += ii[i];

1954:   /* construct CSR for the new matrix */
1955:   PetscCall(PetscCalloc1(nr, &ci));
1956:   for (i = 0; i < nest->nr; ++i) {
1957:     PetscInt ncr, rst;

1959:     PetscCall(ISStrideGetInfo(nest->isglobal.row[i], &rst, NULL));
1960:     PetscCall(ISGetLocalSize(nest->isglobal.row[i], &ncr));
1961:     for (j = 0; j < nest->nc; ++j) {
1962:       if (aii[i * nest->nc + j]) {
1963:         PetscScalar *nvv = avv[i * nest->nc + j], vscale = 1.0, vshift = 0.0;
1964:         PetscInt    *nii = aii[i * nest->nc + j];
1965:         PetscInt    *njj = ajj[i * nest->nc + j];
1966:         PetscInt     cst;

1968:         if (trans[i * nest->nc + j]) {
1969:           vscale = ((Mat_Shell *)nest->m[i][j]->data)->vscale;
1970:           vshift = ((Mat_Shell *)nest->m[i][j]->data)->vshift;
1971:         }
1972:         PetscCall(ISStrideGetInfo(nest->isglobal.col[j], &cst, NULL));
1973:         for (PetscInt ir = rst; ir < ncr + rst; ++ir) {
1974:           PetscInt ij, rsize = nii[1] - nii[0], ist = ii[ir] + ci[ir];

1976:           for (ij = 0; ij < rsize; ij++) {
1977:             jj[ist + ij] = *njj + cst;
1978:             vv[ist + ij] = vscale * *nvv;
1979:             if (PetscUnlikely(vshift != 0.0 && *njj == ir - rst)) vv[ist + ij] += vshift;
1980:             njj++;
1981:             nvv++;
1982:           }
1983:           ci[ir] += rsize;
1984:           nii++;
1985:         }
1986:       }
1987:     }
1988:   }
1989:   PetscCall(PetscFree(ci));

1991:   /* restore info */
1992:   for (i = 0; i < nest->nr; ++i) {
1993:     for (j = 0; j < nest->nc; ++j) {
1994:       Mat B = nest->m[i][j];
1995:       if (B) {
1996:         PetscInt nnr = 0, k = i * nest->nc + j;

1998:         B = (trans[k] ? trans[k] : B);
1999:         PetscCall(MatRestoreRowIJ(B, 0, PETSC_FALSE, PETSC_FALSE, &nnr, (const PetscInt **)&aii[k], (const PetscInt **)&ajj[k], &done));
2000:         PetscCheck(done, PetscObjectComm((PetscObject)B), PETSC_ERR_PLIB, "MatRestoreRowIJ");
2001:         PetscCall(MatSeqAIJRestoreArray(B, &avv[k]));
2002:         PetscCall(MatDestroy(&trans[k]));
2003:       }
2004:     }
2005:   }
2006:   PetscCall(PetscFree4(aii, ajj, avv, trans));

2008:   /* finalize newmat */
2009:   if (reuse == MAT_INITIAL_MATRIX) {
2010:     PetscCall(MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A), nr, nc, ii, jj, vv, newmat));
2011:   } else if (reuse == MAT_INPLACE_MATRIX) {
2012:     Mat B;

2014:     PetscCall(MatCreateSeqAIJWithArrays(PetscObjectComm((PetscObject)A), nr, nc, ii, jj, vv, &B));
2015:     PetscCall(MatHeaderReplace(A, &B));
2016:   }
2017:   PetscCall(MatAssemblyBegin(*newmat, MAT_FINAL_ASSEMBLY));
2018:   PetscCall(MatAssemblyEnd(*newmat, MAT_FINAL_ASSEMBLY));
2019:   {
2020:     Mat_SeqAIJ *a = (Mat_SeqAIJ *)(*newmat)->data;
2021:     a->free_a     = PETSC_TRUE;
2022:     a->free_ij    = PETSC_TRUE;
2023:   }
2024:   PetscFunctionReturn(PETSC_SUCCESS);
2025: }

2027: PETSC_INTERN PetscErrorCode MatAXPY_Dense_Nest(Mat Y, PetscScalar a, Mat X)
2028: {
2029:   Mat_Nest *nest = (Mat_Nest *)X->data;
2030:   PetscInt  i, j, k, rstart;
2031:   PetscBool flg;

2033:   PetscFunctionBegin;
2034:   /* Fill by row */
2035:   for (j = 0; j < nest->nc; ++j) {
2036:     /* Using global column indices and ISAllGather() is not scalable. */
2037:     IS              bNis;
2038:     PetscInt        bN;
2039:     const PetscInt *bNindices;
2040:     PetscCall(ISAllGather(nest->isglobal.col[j], &bNis));
2041:     PetscCall(ISGetSize(bNis, &bN));
2042:     PetscCall(ISGetIndices(bNis, &bNindices));
2043:     for (i = 0; i < nest->nr; ++i) {
2044:       Mat             B = nest->m[i][j], D = NULL;
2045:       PetscInt        bm, br;
2046:       const PetscInt *bmindices;
2047:       if (!B) continue;
2048:       PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &flg, MATTRANSPOSEVIRTUAL, MATHERMITIANTRANSPOSEVIRTUAL, ""));
2049:       if (flg) {
2050:         PetscTryMethod(B, "MatTransposeGetMat_C", (Mat, Mat *), (B, &D));
2051:         PetscTryMethod(B, "MatHermitianTransposeGetMat_C", (Mat, Mat *), (B, &D));
2052:         PetscCall(MatConvert(B, ((PetscObject)D)->type_name, MAT_INITIAL_MATRIX, &D));
2053:         B = D;
2054:       }
2055:       PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
2056:       if (flg) {
2057:         if (D) PetscCall(MatConvert(D, MATBAIJ, MAT_INPLACE_MATRIX, &D));
2058:         else PetscCall(MatConvert(B, MATBAIJ, MAT_INITIAL_MATRIX, &D));
2059:         B = D;
2060:       }
2061:       PetscCall(ISGetLocalSize(nest->isglobal.row[i], &bm));
2062:       PetscCall(ISGetIndices(nest->isglobal.row[i], &bmindices));
2063:       PetscCall(MatGetOwnershipRange(B, &rstart, NULL));
2064:       for (br = 0; br < bm; ++br) {
2065:         PetscInt           row = bmindices[br], brncols, *cols;
2066:         const PetscInt    *brcols;
2067:         const PetscScalar *brcoldata;
2068:         PetscScalar       *vals = NULL;
2069:         PetscCall(MatGetRow(B, br + rstart, &brncols, &brcols, &brcoldata));
2070:         PetscCall(PetscMalloc1(brncols, &cols));
2071:         for (k = 0; k < brncols; k++) cols[k] = bNindices[brcols[k]];
2072:         /*
2073:           Nest blocks are required to be nonoverlapping -- otherwise nest and monolithic index layouts wouldn't match.
2074:           Thus, we could use INSERT_VALUES, but I prefer ADD_VALUES.
2075:          */
2076:         if (a != 1.0) {
2077:           PetscCall(PetscMalloc1(brncols, &vals));
2078:           for (k = 0; k < brncols; k++) vals[k] = a * brcoldata[k];
2079:           PetscCall(MatSetValues(Y, 1, &row, brncols, cols, vals, ADD_VALUES));
2080:           PetscCall(PetscFree(vals));
2081:         } else {
2082:           PetscCall(MatSetValues(Y, 1, &row, brncols, cols, brcoldata, ADD_VALUES));
2083:         }
2084:         PetscCall(MatRestoreRow(B, br + rstart, &brncols, &brcols, &brcoldata));
2085:         PetscCall(PetscFree(cols));
2086:       }
2087:       PetscCall(MatDestroy(&D));
2088:       PetscCall(ISRestoreIndices(nest->isglobal.row[i], &bmindices));
2089:     }
2090:     PetscCall(ISRestoreIndices(bNis, &bNindices));
2091:     PetscCall(ISDestroy(&bNis));
2092:   }
2093:   PetscCall(MatAssemblyBegin(Y, MAT_FINAL_ASSEMBLY));
2094:   PetscCall(MatAssemblyEnd(Y, MAT_FINAL_ASSEMBLY));
2095:   PetscFunctionReturn(PETSC_SUCCESS);
2096: }

2098: static PetscErrorCode MatConvert_Nest_AIJ(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
2099: {
2100:   Mat_Nest   *nest = (Mat_Nest *)A->data;
2101:   PetscInt    m, n, M, N, i, j, k, *dnnz, *onnz = NULL, rstart, cstart, cend;
2102:   PetscMPIInt size;
2103:   Mat         C;

2105:   PetscFunctionBegin;
2106:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)A), &size));
2107:   if (size == 1) { /* look for a special case with SeqAIJ matrices and strided-1, contiguous, blocks */
2108:     PetscInt  nf;
2109:     PetscBool fast;

2111:     PetscCall(PetscStrcmp(newtype, MATAIJ, &fast));
2112:     if (!fast) PetscCall(PetscStrcmp(newtype, MATSEQAIJ, &fast));
2113:     for (i = 0; i < nest->nr && fast; ++i) {
2114:       for (j = 0; j < nest->nc && fast; ++j) {
2115:         Mat B = nest->m[i][j];
2116:         if (B) {
2117:           PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQAIJ, &fast));
2118:           if (!fast) {
2119:             PetscBool istrans;

2121:             PetscCall(PetscObjectTypeCompare((PetscObject)B, MATTRANSPOSEVIRTUAL, &istrans));
2122:             if (istrans) {
2123:               Mat Bt;

2125:               PetscCall(MatTransposeGetMat(B, &Bt));
2126:               PetscCall(PetscObjectTypeCompare((PetscObject)Bt, MATSEQAIJ, &fast));
2127:             } else {
2128:               PetscCall(PetscObjectTypeCompare((PetscObject)B, MATHERMITIANTRANSPOSEVIRTUAL, &istrans));
2129:               if (istrans) {
2130:                 Mat Bt;

2132:                 PetscCall(MatHermitianTransposeGetMat(B, &Bt));
2133:                 PetscCall(PetscObjectTypeCompare((PetscObject)Bt, MATSEQAIJ, &fast));
2134:               }
2135:             }
2136:             if (fast) fast = (PetscBool)(!((Mat_Shell *)B->data)->zrows && !((Mat_Shell *)B->data)->zcols && !((Mat_Shell *)B->data)->axpy && !((Mat_Shell *)B->data)->left && !((Mat_Shell *)B->data)->right && !((Mat_Shell *)B->data)->dshift);
2137:           }
2138:         }
2139:       }
2140:     }
2141:     for (i = 0, nf = 0; i < nest->nr && fast; ++i) {
2142:       PetscCall(PetscObjectTypeCompare((PetscObject)nest->isglobal.row[i], ISSTRIDE, &fast));
2143:       if (fast) {
2144:         PetscInt f, s;

2146:         PetscCall(ISStrideGetInfo(nest->isglobal.row[i], &f, &s));
2147:         if (f != nf || s != 1) {
2148:           fast = PETSC_FALSE;
2149:         } else {
2150:           PetscCall(ISGetSize(nest->isglobal.row[i], &f));
2151:           nf += f;
2152:         }
2153:       }
2154:     }
2155:     for (i = 0, nf = 0; i < nest->nc && fast; ++i) {
2156:       PetscCall(PetscObjectTypeCompare((PetscObject)nest->isglobal.col[i], ISSTRIDE, &fast));
2157:       if (fast) {
2158:         PetscInt f, s;

2160:         PetscCall(ISStrideGetInfo(nest->isglobal.col[i], &f, &s));
2161:         if (f != nf || s != 1) {
2162:           fast = PETSC_FALSE;
2163:         } else {
2164:           PetscCall(ISGetSize(nest->isglobal.col[i], &f));
2165:           nf += f;
2166:         }
2167:       }
2168:     }
2169:     if (fast) {
2170:       PetscCall(MatConvert_Nest_SeqAIJ_fast(A, newtype, reuse, newmat));
2171:       PetscFunctionReturn(PETSC_SUCCESS);
2172:     }
2173:   }
2174:   PetscCall(MatGetSize(A, &M, &N));
2175:   PetscCall(MatGetLocalSize(A, &m, &n));
2176:   PetscCall(MatGetOwnershipRangeColumn(A, &cstart, &cend));
2177:   if (reuse == MAT_REUSE_MATRIX) C = *newmat;
2178:   else {
2179:     PetscCall(MatCreate(PetscObjectComm((PetscObject)A), &C));
2180:     PetscCall(MatSetType(C, newtype));
2181:     PetscCall(MatSetSizes(C, m, n, M, N));
2182:   }
2183:   PetscCall(PetscMalloc1(2 * m, &dnnz));
2184:   if (m) {
2185:     onnz = dnnz + m;
2186:     for (k = 0; k < m; k++) {
2187:       dnnz[k] = 0;
2188:       onnz[k] = 0;
2189:     }
2190:   }
2191:   for (j = 0; j < nest->nc; ++j) {
2192:     IS              bNis;
2193:     PetscInt        bN;
2194:     const PetscInt *bNindices;
2195:     PetscBool       flg;
2196:     /* Using global column indices and ISAllGather() is not scalable. */
2197:     PetscCall(ISAllGather(nest->isglobal.col[j], &bNis));
2198:     PetscCall(ISGetSize(bNis, &bN));
2199:     PetscCall(ISGetIndices(bNis, &bNindices));
2200:     for (i = 0; i < nest->nr; ++i) {
2201:       PetscSF         bmsf;
2202:       PetscSFNode    *iremote;
2203:       Mat             B = nest->m[i][j], D = NULL;
2204:       PetscInt        bm, *sub_dnnz, *sub_onnz, br;
2205:       const PetscInt *bmindices;
2206:       if (!B) continue;
2207:       PetscCall(ISGetLocalSize(nest->isglobal.row[i], &bm));
2208:       PetscCall(ISGetIndices(nest->isglobal.row[i], &bmindices));
2209:       PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)A), &bmsf));
2210:       PetscCall(PetscMalloc1(bm, &iremote));
2211:       PetscCall(PetscMalloc1(bm, &sub_dnnz));
2212:       PetscCall(PetscMalloc1(bm, &sub_onnz));
2213:       for (k = 0; k < bm; ++k) {
2214:         sub_dnnz[k] = 0;
2215:         sub_onnz[k] = 0;
2216:       }
2217:       PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &flg, MATTRANSPOSEVIRTUAL, MATHERMITIANTRANSPOSEVIRTUAL, ""));
2218:       if (flg) {
2219:         PetscTryMethod(B, "MatTransposeGetMat_C", (Mat, Mat *), (B, &D));
2220:         PetscTryMethod(B, "MatHermitianTransposeGetMat_C", (Mat, Mat *), (B, &D));
2221:         PetscCall(MatConvert(B, ((PetscObject)D)->type_name, MAT_INITIAL_MATRIX, &D));
2222:         B = D;
2223:       }
2224:       PetscCall(PetscObjectTypeCompareAny((PetscObject)B, &flg, MATSEQSBAIJ, MATMPISBAIJ, ""));
2225:       if (flg) {
2226:         if (D) PetscCall(MatConvert(D, MATBAIJ, MAT_INPLACE_MATRIX, &D));
2227:         else PetscCall(MatConvert(B, MATBAIJ, MAT_INITIAL_MATRIX, &D));
2228:         B = D;
2229:       }
2230:       /*
2231:        Locate the owners for all of the locally-owned global row indices for this row block.
2232:        These determine the roots of PetscSF used to communicate preallocation data to row owners.
2233:        The roots correspond to the dnnz and onnz entries; thus, there are two roots per row.
2234:        */
2235:       PetscCall(MatGetOwnershipRange(B, &rstart, NULL));
2236:       for (br = 0; br < bm; ++br) {
2237:         PetscInt        row = bmindices[br], brncols, col;
2238:         const PetscInt *brcols;
2239:         PetscInt        rowrel   = 0; /* row's relative index on its owner rank */
2240:         PetscMPIInt     rowowner = 0;
2241:         PetscCall(PetscLayoutFindOwnerIndex(A->rmap, row, &rowowner, &rowrel));
2242:         /* how many roots  */
2243:         iremote[br].rank  = rowowner;
2244:         iremote[br].index = rowrel; /* edge from bmdnnz to dnnz */
2245:         /* get nonzero pattern */
2246:         PetscCall(MatGetRow(B, br + rstart, &brncols, &brcols, NULL));
2247:         for (k = 0; k < brncols; k++) {
2248:           col = bNindices[brcols[k]];
2249:           if (col >= A->cmap->range[rowowner] && col < A->cmap->range[rowowner + 1]) {
2250:             sub_dnnz[br]++;
2251:           } else {
2252:             sub_onnz[br]++;
2253:           }
2254:         }
2255:         PetscCall(MatRestoreRow(B, br + rstart, &brncols, &brcols, NULL));
2256:       }
2257:       PetscCall(MatDestroy(&D));
2258:       PetscCall(ISRestoreIndices(nest->isglobal.row[i], &bmindices));
2259:       /* bsf will have to take care of disposing of bedges. */
2260:       PetscCall(PetscSFSetGraph(bmsf, m, bm, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
2261:       PetscCall(PetscSFReduceBegin(bmsf, MPIU_INT, sub_dnnz, dnnz, MPI_SUM));
2262:       PetscCall(PetscSFReduceEnd(bmsf, MPIU_INT, sub_dnnz, dnnz, MPI_SUM));
2263:       PetscCall(PetscSFReduceBegin(bmsf, MPIU_INT, sub_onnz, onnz, MPI_SUM));
2264:       PetscCall(PetscSFReduceEnd(bmsf, MPIU_INT, sub_onnz, onnz, MPI_SUM));
2265:       PetscCall(PetscFree(sub_dnnz));
2266:       PetscCall(PetscFree(sub_onnz));
2267:       PetscCall(PetscSFDestroy(&bmsf));
2268:     }
2269:     PetscCall(ISRestoreIndices(bNis, &bNindices));
2270:     PetscCall(ISDestroy(&bNis));
2271:   }
2272:   /* Resize preallocation if overestimated */
2273:   for (i = 0; i < m; i++) {
2274:     dnnz[i] = PetscMin(dnnz[i], A->cmap->n);
2275:     onnz[i] = PetscMin(onnz[i], A->cmap->N - A->cmap->n);
2276:   }
2277:   PetscCall(MatSeqAIJSetPreallocation(C, 0, dnnz));
2278:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnnz, 0, onnz));
2279:   PetscCall(PetscFree(dnnz));
2280:   PetscCall(MatAXPY_Dense_Nest(C, 1.0, A));
2281:   if (reuse == MAT_INPLACE_MATRIX) PetscCall(MatHeaderReplace(A, &C));
2282:   else *newmat = C;
2283:   PetscFunctionReturn(PETSC_SUCCESS);
2284: }

2286: static PetscErrorCode MatConvert_Nest_Dense(Mat A, MatType newtype, MatReuse reuse, Mat *newmat)
2287: {
2288:   Mat      B;
2289:   PetscInt m, n, M, N;

2291:   PetscFunctionBegin;
2292:   PetscCall(MatGetSize(A, &M, &N));
2293:   PetscCall(MatGetLocalSize(A, &m, &n));
2294:   if (reuse == MAT_REUSE_MATRIX) {
2295:     B = *newmat;
2296:     PetscCall(MatZeroEntries(B));
2297:   } else {
2298:     PetscCall(MatCreateDense(PetscObjectComm((PetscObject)A), m, PETSC_DECIDE, M, N, NULL, &B));
2299:   }
2300:   PetscCall(MatAXPY_Dense_Nest(B, 1.0, A));
2301:   if (reuse == MAT_INPLACE_MATRIX) PetscCall(MatHeaderReplace(A, &B));
2302:   else if (reuse == MAT_INITIAL_MATRIX) *newmat = B;
2303:   PetscFunctionReturn(PETSC_SUCCESS);
2304: }

2306: static PetscErrorCode MatHasOperation_Nest(Mat mat, MatOperation op, PetscBool *has)
2307: {
2308:   Mat_Nest *bA  = (Mat_Nest *)mat->data;
2309:   PetscBool flg = PETSC_TRUE;

2311:   PetscFunctionBegin;
2312:   *has = PETSC_FALSE;
2313:   if (op == MATOP_MULT || op == MATOP_MULT_ADD || op == MATOP_MULT_TRANSPOSE || op == MATOP_MULT_TRANSPOSE_ADD || op == MATOP_MULT_HERMITIAN_TRANSPOSE || op == MATOP_MULT_HERMITIAN_TRANS_ADD) {
2314:     MatOperation opAdd;

2316:     if (op == MATOP_MULT || op == MATOP_MULT_ADD) opAdd = MATOP_MULT_ADD;
2317:     else if (op == MATOP_MULT_TRANSPOSE || op == MATOP_MULT_TRANSPOSE_ADD) opAdd = MATOP_MULT_TRANSPOSE_ADD;
2318:     else opAdd = MATOP_MULT_HERMITIAN_TRANS_ADD;
2319:     for (PetscInt j = 0; j < bA->nc && flg; j++) {
2320:       for (PetscInt i = 0; i < bA->nr; i++) {
2321:         if (!bA->m[i][j]) continue;
2322:         PetscCall(MatHasOperation(bA->m[i][j], opAdd, &flg));
2323:         if (!flg) break;
2324:       }
2325:     }
2326:   }
2327:   if (flg && ((void **)mat->ops)[op]) *has = PETSC_TRUE;
2328:   PetscFunctionReturn(PETSC_SUCCESS);
2329: }

2331: /*MC
2332:   MATNEST -  "nest" - Matrix type consisting of nested submatrices, each stored separately.

2334:   Level: intermediate

2336:   Notes:
2337:   This matrix type permits scalable use of `PCFIELDSPLIT` and avoids the large memory costs of extracting submatrices.
2338:   It allows the use of symmetric and block formats for parts of multi-physics simulations.
2339:   It is usually used with `DMCOMPOSITE` and `DMCreateMatrix()`

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

2345: .seealso: [](ch_matrices), `Mat`, `MATNEST`, `MatCreate()`, `MatType`, `MatCreateNest()`, `MatNestSetSubMat()`, `MatNestGetSubMat()`,
2346:           `VecCreateNest()`, `DMCreateMatrix()`, `DMCOMPOSITE`, `MatNestSetVecType()`, `MatNestGetLocalISs()`,
2347:           `MatNestGetISs()`, `MatNestSetSubMats()`, `MatNestGetSubMats()`
2348: M*/
2349: PETSC_EXTERN PetscErrorCode MatCreate_Nest(Mat A)
2350: {
2351:   Mat_Nest *s;

2353:   PetscFunctionBegin;
2354:   PetscCall(PetscNew(&s));
2355:   A->data = (void *)s;

2357:   s->nr            = -1;
2358:   s->nc            = -1;
2359:   s->m             = NULL;
2360:   s->splitassembly = PETSC_FALSE;

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

2364:   A->ops->mult                      = MatMult_Nest;
2365:   A->ops->multadd                   = MatMultAdd_Nest;
2366:   A->ops->multtranspose             = MatMultTranspose_Nest;
2367:   A->ops->multtransposeadd          = MatMultTransposeAdd_Nest;
2368:   A->ops->transpose                 = MatTranspose_Nest;
2369:   A->ops->multhermitiantranspose    = MatMultHermitianTranspose_Nest;
2370:   A->ops->multhermitiantransposeadd = MatMultHermitianTransposeAdd_Nest;
2371:   A->ops->assemblybegin             = MatAssemblyBegin_Nest;
2372:   A->ops->assemblyend               = MatAssemblyEnd_Nest;
2373:   A->ops->zeroentries               = MatZeroEntries_Nest;
2374:   A->ops->copy                      = MatCopy_Nest;
2375:   A->ops->axpy                      = MatAXPY_Nest;
2376:   A->ops->duplicate                 = MatDuplicate_Nest;
2377:   A->ops->createsubmatrix           = MatCreateSubMatrix_Nest;
2378:   A->ops->destroy                   = MatDestroy_Nest;
2379:   A->ops->view                      = MatView_Nest;
2380:   A->ops->getvecs                   = NULL; /* Use VECNEST by calling MatNestSetVecType(A,VECNEST) */
2381:   A->ops->getlocalsubmatrix         = MatGetLocalSubMatrix_Nest;
2382:   A->ops->restorelocalsubmatrix     = MatRestoreLocalSubMatrix_Nest;
2383:   A->ops->getdiagonal               = MatGetDiagonal_Nest;
2384:   A->ops->diagonalscale             = MatDiagonalScale_Nest;
2385:   A->ops->scale                     = MatScale_Nest;
2386:   A->ops->shift                     = MatShift_Nest;
2387:   A->ops->diagonalset               = MatDiagonalSet_Nest;
2388:   A->ops->setrandom                 = MatSetRandom_Nest;
2389:   A->ops->hasoperation              = MatHasOperation_Nest;

2391:   A->spptr     = NULL;
2392:   A->assembled = PETSC_FALSE;

2394:   /* expose Nest api's */
2395:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSubMat_C", MatNestGetSubMat_Nest));
2396:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetSubMat_C", MatNestSetSubMat_Nest));
2397:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSubMats_C", MatNestGetSubMats_Nest));
2398:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetSize_C", MatNestGetSize_Nest));
2399:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetISs_C", MatNestGetISs_Nest));
2400:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestGetLocalISs_C", MatNestGetLocalISs_Nest));
2401:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetVecType_C", MatNestSetVecType_Nest));
2402:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatNestSetSubMats_C", MatNestSetSubMats_Nest));
2403:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_mpiaij_C", MatConvert_Nest_AIJ));
2404:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_seqaij_C", MatConvert_Nest_AIJ));
2405:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_aij_C", MatConvert_Nest_AIJ));
2406:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_is_C", MatConvert_Nest_IS));
2407:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_mpidense_C", MatConvert_Nest_Dense));
2408:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_nest_seqdense_C", MatConvert_Nest_Dense));
2409:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_nest_seqdense_C", MatProductSetFromOptions_Nest_Dense));
2410:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_nest_mpidense_C", MatProductSetFromOptions_Nest_Dense));

2412:   PetscCall(PetscObjectChangeTypeName((PetscObject)A, MATNEST));
2413:   PetscFunctionReturn(PETSC_SUCCESS);
2414: }