Actual source code: pchpddm.cxx

  1: #include <petscsf.h>
  2: #include <petsc/private/vecimpl.h>
  3: #include <petsc/private/matimpl.h>
  4: #include <petsc/private/petschpddm.h>
  5: #include <petsc/private/pcimpl.h>
  6: #include <petsc/private/dmimpl.h>
  7:                                   /* otherwise, it is assumed that one is compiling libhpddm_petsc => circular dependency */

  9: static PetscErrorCode (*loadedSym)(HPDDM::Schwarz<PetscScalar> *const, IS, Mat, Mat, Mat, std::vector<Vec>, PC_HPDDM_Level **const) = nullptr;

 11: static PetscBool     PCHPDDMPackageInitialized = PETSC_FALSE;
 12: static constexpr int i_0                       = 0;

 14: PetscLogEvent PC_HPDDM_Strc;
 15: PetscLogEvent PC_HPDDM_PtAP;
 16: PetscLogEvent PC_HPDDM_PtBP;
 17: PetscLogEvent PC_HPDDM_Next;
 18: PetscLogEvent PC_HPDDM_SetUp[PETSC_PCHPDDM_MAXLEVELS];
 19: PetscLogEvent PC_HPDDM_Solve[PETSC_PCHPDDM_MAXLEVELS];

 21: static PetscErrorCode PCHPDDMInitializeLevels_Private(PC_HPDDM *data)
 22: {
 23:   PetscFunctionBegin;
 24:   if (!data->levels) { /* usually allocated in PCSetFromOptions_HPDDM(), but PCSetUp_HPDDM() may be called without a prior PCSetFromOptions() */
 25:     PetscCall(PetscCalloc1(PETSC_PCHPDDM_MAXLEVELS, &data->levels));
 26:     PetscCall(PetscNew(data->levels));
 27:     data->levels[0]->parent = data;
 28:     data->N                 = 1;
 29:   }
 30:   PetscFunctionReturn(PETSC_SUCCESS);
 31: }

 33: static PetscErrorCode PCReset_HPDDM(PC pc)
 34: {
 35:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

 37:   PetscFunctionBegin;
 38:   if (data->levels) {
 39:     for (PetscInt i = 0; i < PETSC_PCHPDDM_MAXLEVELS && data->levels[i]; ++i) {
 40:       PetscCall(KSPDestroy(&data->levels[i]->ksp));
 41:       PetscCall(PCDestroy(&data->levels[i]->pc));
 42:       PetscCall(PetscFree(data->levels[i]));
 43:     }
 44:     PetscCall(PetscFree(data->levels));
 45:     data->N = 0;
 46:   }
 47:   PetscCall(ISDestroy(&data->is));
 48:   PetscCall(MatDestroy(&data->aux));
 49:   PetscCall(MatDestroy(&data->B));
 50:   PetscCall(VecDestroy(&data->normal));
 51:   PetscCall(VecDestroy(&data->scaling));
 52:   data->correction = PC_HPDDM_COARSE_CORRECTION_DEFLATED;
 53:   data->Neumann    = PETSC_BOOL3_UNKNOWN;
 54:   data->deflation  = PETSC_FALSE;
 55:   data->setup      = nullptr;
 56:   data->setup_ctx  = nullptr;
 57:   PetscFunctionReturn(PETSC_SUCCESS);
 58: }

 60: static PetscErrorCode PCDestroy_HPDDM(PC pc)
 61: {
 62:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

 64:   PetscFunctionBegin;
 65:   PetscCall(PCReset_HPDDM(pc));
 66:   PetscCall(PetscFree(data));
 67:   PetscCall(PetscObjectChangeTypeName((PetscObject)pc, nullptr));
 68:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", nullptr));
 69:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", nullptr));
 70:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", nullptr));
 71:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", nullptr));
 72:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", nullptr));
 73:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetSTShareSubKSP_C", nullptr));
 74:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetSTShareSubKSP_C", nullptr));
 75:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetDeflationMat_C", nullptr));
 76:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetScaling_C", nullptr));
 77:   PetscCall(PetscObjectCompose((PetscObject)pc, "_PCHPDDM_Schur", nullptr));
 78:   PetscFunctionReturn(PETSC_SUCCESS);
 79: }

 81: static inline PetscErrorCode PCHPDDMSetAuxiliaryMat_Private(PC pc, IS is, Mat A, PetscBool deflation)
 82: {
 83:   PC_HPDDM                   *data = (PC_HPDDM *)pc->data;
 84:   PCHPDDMCoarseCorrectionType type = data->correction;

 86:   PetscFunctionBegin;
 88:   if (is && A) {
 89:     PetscInt m[2];

 91:     PetscCall(ISGetLocalSize(is, m));
 92:     PetscCall(MatGetLocalSize(A, m + 1, nullptr));
 93:     PetscCheck(m[0] == m[1], PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Inconsistent IS and Mat sizes (%" PetscInt_FMT " v. %" PetscInt_FMT ")", m[0], m[1]);
 94:   }
 95:   if (is) {
 96:     PetscCall(PetscObjectReference((PetscObject)is));
 97:     /* a new overlap definition resets the PC, unless the stored IS only belongs to a scaling not yet used by PCSetUp() */
 98:     if (data->is && (data->aux || !data->scaling || pc->setupcalled)) {
 99:       PetscCall(PCReset_HPDDM(pc));
100:       pc->setfromoptionscalled = 0;
101:       pc->setupcalled          = PETSC_FALSE;
102:       data->correction         = type;
103:     }
104:     PetscCall(ISDestroy(&data->is));
105:     data->is = is;
106:   }
107:   if (A) {
108:     PetscCall(PetscObjectReference((PetscObject)A));
109:     PetscCall(MatDestroy(&data->aux));
110:     data->aux = A;
111:   }
112:   data->deflation = deflation;
113:   PetscFunctionReturn(PETSC_SUCCESS);
114: }

116: static inline PetscErrorCode PCHPDDMSplittingMatNormal_Private(Mat A, IS *is, Mat *splitting[])
117: {
118:   Mat *sub;
119:   IS   zero;

121:   PetscFunctionBegin;
122:   PetscCall(MatSetOption(A, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
123:   PetscCall(MatCreateSubMatrices(A, 1, is + 2, is, MAT_INITIAL_MATRIX, splitting));
124:   PetscCall(MatCreateSubMatrices(**splitting, 1, is + 2, is + 1, MAT_INITIAL_MATRIX, &sub));
125:   PetscCall(MatFindZeroRows(*sub, &zero));
126:   PetscCall(MatDestroySubMatrices(1, &sub));
127:   PetscCall(MatSetOption(**splitting, MAT_KEEP_NONZERO_PATTERN, PETSC_TRUE));
128:   PetscCall(MatZeroRowsIS(**splitting, zero, 0.0, nullptr, nullptr));
129:   PetscCall(ISDestroy(&zero));
130:   PetscFunctionReturn(PETSC_SUCCESS);
131: }

133: static inline PetscErrorCode PCHPDDMSetAuxiliaryMatNormal_Private(PC pc, Mat A, Mat N, Mat *B, const char *pcpre, Vec *diagonal = nullptr, Mat B01 = nullptr)
134: {
135:   PC_HPDDM *data         = (PC_HPDDM *)pc->data;
136:   Mat      *splitting[2] = {}, aux;
137:   Vec       d;
138:   IS        is[3];
139:   PetscReal norm;
140:   PetscBool flg;
141:   char      type[256] = {}; /* same size as in src/ksp/pc/interface/pcset.c */

143:   PetscFunctionBegin;
144:   if (!B01) PetscCall(MatConvert(N, MATAIJ, MAT_INITIAL_MATRIX, B));
145:   else PetscCall(MatTransposeMatMult(B01, A, MAT_INITIAL_MATRIX, PETSC_DETERMINE, B));
146:   PetscCall(MatEliminateZeros(*B, PETSC_TRUE));
147:   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->n, A->cmap->rstart, 1, is));
148:   PetscCall(MatIncreaseOverlap(*B, 1, is, 1));
149:   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->cmap->n, A->cmap->rstart, 1, is + 2));
150:   PetscCall(ISEmbed(is[0], is[2], PETSC_TRUE, is + 1));
151:   PetscCall(ISDestroy(is + 2));
152:   PetscCall(ISCreateStride(PETSC_COMM_SELF, A->rmap->N, 0, 1, is + 2));
153:   PetscCall(PCHPDDMSplittingMatNormal_Private(A, is, &splitting[0]));
154:   if (B01) {
155:     PetscCall(PCHPDDMSplittingMatNormal_Private(B01, is, &splitting[1]));
156:     PetscCall(MatDestroy(&B01));
157:   }
158:   PetscCall(ISDestroy(is + 2));
159:   PetscCall(ISDestroy(is + 1));
160:   PetscCall(PetscOptionsGetString(((PetscObject)pc)->options, pcpre, "-pc_hpddm_levels_1_sub_pc_type", type, sizeof(type), nullptr));
161:   PetscCall(PetscStrcmp(type, PCQR, &flg));
162:   if (!flg) {
163:     Mat conjugate = *splitting[splitting[1] ? 1 : 0];

165:     if (PetscDefined(USE_COMPLEX) && !splitting[1]) {
166:       PetscCall(MatDuplicate(*splitting[0], MAT_COPY_VALUES, &conjugate));
167:       PetscCall(MatConjugate(conjugate));
168:     }
169:     PetscCall(MatTransposeMatMult(conjugate, *splitting[0], MAT_INITIAL_MATRIX, PETSC_DETERMINE, &aux));
170:     if (PetscDefined(USE_COMPLEX) && !splitting[1]) PetscCall(MatDestroy(&conjugate));
171:     else if (splitting[1]) PetscCall(MatDestroySubMatrices(1, &splitting[1]));
172:     PetscCall(MatNorm(aux, NORM_FROBENIUS, &norm));
173:     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
174:     if (diagonal) {
175:       PetscReal norm;

177:       PetscCall(VecScale(*diagonal, -1.0));
178:       PetscCall(VecNorm(*diagonal, NORM_INFINITY, &norm));
179:       if (norm > PETSC_SMALL) {
180:         PetscSF  scatter;
181:         PetscInt n;

183:         PetscCall(ISGetLocalSize(*is, &n));
184:         PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)pc), n, PETSC_DECIDE, &d));
185:         PetscCall(VecScatterCreate(*diagonal, *is, d, nullptr, &scatter));
186:         PetscCall(VecScatterBegin(scatter, *diagonal, d, INSERT_VALUES, SCATTER_FORWARD));
187:         PetscCall(VecScatterEnd(scatter, *diagonal, d, INSERT_VALUES, SCATTER_FORWARD));
188:         PetscCall(PetscSFDestroy(&scatter));
189:         PetscCall(MatDiagonalSet(aux, d, ADD_VALUES));
190:         PetscCall(VecDestroy(&d));
191:       } else PetscCall(VecDestroy(diagonal));
192:     }
193:     if (!diagonal) PetscCall(MatShift(aux, PETSC_SMALL * norm));
194:     PetscCall(MatEliminateZeros(aux, PETSC_TRUE));
195:   } else {
196:     PetscBool flg;

198:     PetscCheck(!splitting[1], PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot use PCQR when A01 != A10^T");
199:     if (diagonal) {
200:       PetscCall(VecNorm(*diagonal, NORM_INFINITY, &norm));
201:       PetscCheck(norm < PETSC_SMALL, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Nonzero diagonal A11 block");
202:       PetscCall(VecDestroy(diagonal));
203:     }
204:     PetscCall(PetscObjectTypeCompare((PetscObject)N, MATNORMAL, &flg));
205:     if (flg) PetscCall(MatCreateNormal(*splitting[0], &aux));
206:     else PetscCall(MatCreateNormalHermitian(*splitting[0], &aux));
207:   }
208:   PetscCall(MatDestroySubMatrices(1, &splitting[0]));
209:   PetscCall(PCHPDDMSetAuxiliaryMat(pc, *is, aux, nullptr, nullptr));
210:   data->Neumann = PETSC_BOOL3_TRUE;
211:   PetscCall(ISDestroy(is));
212:   PetscCall(MatDestroy(&aux));
213:   PetscFunctionReturn(PETSC_SUCCESS);
214: }

216: static PetscErrorCode PCHPDDMSetAuxiliaryMat_HPDDM(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void *setup_ctx)
217: {
218:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

220:   PetscFunctionBegin;
221:   PetscCheck(!data->scaling, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "PCHPDDMSetAuxiliaryMat() cannot be combined with a user-supplied scaling, remove it first with PCHPDDMSetScaling(pc, NULL, NULL)");
222:   PetscCall(PCHPDDMSetAuxiliaryMat_Private(pc, is, A, PETSC_FALSE));
223:   if (setup) {
224:     data->setup     = setup;
225:     data->setup_ctx = setup_ctx;
226:   }
227:   PetscFunctionReturn(PETSC_SUCCESS);
228: }

230: /*@
231:   PCHPDDMSetAuxiliaryMat - Sets the auxiliary matrix used by `PCHPDDM` for the concurrent GenEO problems at the finest level.

233:   Input Parameters:
234: + pc    - preconditioner context
235: . is    - index set of the local auxiliary, e.g., Neumann, matrix
236: . A     - auxiliary sequential matrix
237: . setup - function for generating the auxiliary matrix entries, may be `NULL`
238: - ctx   - context for `setup`, may be `NULL`

240:   Calling sequence of `setup`:
241: + J   - matrix whose values are to be set
242: . t   - time
243: . X   - linearization point
244: . X_t - time-derivative of the linearization point
245: . s   - step
246: . ovl - index set of the local auxiliary, e.g., Neumann, matrix
247: - ctx - context for `setup`, may be `NULL`

249:   Level: intermediate

251:   Notes:
252:   As an example, in a finite element context with nonoverlapping subdomains plus (overlapping) ghost elements, this could be the unassembled (Neumann)
253:   local overlapping operator. As opposed to the assembled (Dirichlet) local overlapping operator obtained by summing neighborhood contributions
254:   at the interface of ghost elements.

256:   This routine does not currently support a scaling set with `PCHPDDMSetScaling()`.

258:   Fortran Notes:
259:   Only `PETSC_NULL_FUNCTION` is supported for `setup` and `ctx` is never accessed

261: .seealso: [](ch_ksp), `PCHPDDM`, `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHPDDMSetRHSMat()`, `PCHPDDMSetScaling()`, `MATIS`
262: @*/
263: PetscErrorCode PCHPDDMSetAuxiliaryMat(PC pc, IS is, Mat A, PetscErrorCode (*setup)(Mat J, PetscReal t, Vec X, Vec X_t, PetscReal s, IS ovl, PetscCtx ctx), PetscCtx ctx)
264: {
265:   PetscFunctionBegin;
269:   PetscTryMethod(pc, "PCHPDDMSetAuxiliaryMat_C", (PC, IS, Mat, PetscErrorCode (*)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void *), (pc, is, A, setup, ctx));
270:   PetscFunctionReturn(PETSC_SUCCESS);
271: }

273: static PetscErrorCode PCHPDDMHasNeumannMat_HPDDM(PC pc, PetscBool has)
274: {
275:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

277:   PetscFunctionBegin;
278:   data->Neumann = PetscBoolToBool3(has);
279:   PetscFunctionReturn(PETSC_SUCCESS);
280: }

282: /*@
283:   PCHPDDMHasNeumannMat - Informs `PCHPDDM` that the `Mat` passed to `PCHPDDMSetAuxiliaryMat()` is the local Neumann matrix.

285:   Input Parameters:
286: + pc  - preconditioner context
287: - has - Boolean value

289:   Level: intermediate

291:   Notes:
292:   This may be used to bypass a call to `MatCreateSubMatrices()` and to `MatConvert()` for `MATSBAIJ` matrices.

294:   If a function is composed with DMCreateNeumannOverlap_C implementation is available in the `DM` attached to the Pmat, or the Amat, or the `PC`, the flag is internally set to `PETSC_TRUE`. Its default value is otherwise `PETSC_FALSE`.

296: .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetAuxiliaryMat()`
297: @*/
298: PetscErrorCode PCHPDDMHasNeumannMat(PC pc, PetscBool has)
299: {
300:   PetscFunctionBegin;
302:   PetscTryMethod(pc, "PCHPDDMHasNeumannMat_C", (PC, PetscBool), (pc, has));
303:   PetscFunctionReturn(PETSC_SUCCESS);
304: }

306: static PetscErrorCode PCHPDDMSetRHSMat_HPDDM(PC pc, Mat B)
307: {
308:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

310:   PetscFunctionBegin;
311:   PetscCall(PetscObjectReference((PetscObject)B));
312:   PetscCall(MatDestroy(&data->B));
313:   data->B = B;
314:   PetscFunctionReturn(PETSC_SUCCESS);
315: }

317: /*@
318:   PCHPDDMSetRHSMat - Sets the right-hand side matrix used by `PCHPDDM` for the concurrent GenEO problems at the finest level.

320:   Input Parameters:
321: + pc - preconditioner context
322: - B  - right-hand side sequential matrix

324:   Level: advanced

326:   Note:
327:   Must be used in conjunction with `PCHPDDMSetAuxiliaryMat`(N), so that Nv = lambda Bv is solved using `EPSSetOperators`(N, B).
328:   It is assumed that N and `B` are provided using the same numbering. This provides a means to try more advanced methods such as GenEO-II or H-GenEO.

330: .seealso: [](ch_ksp), `PCHPDDMSetAuxiliaryMat()`, `PCHPDDM`
331: @*/
332: PetscErrorCode PCHPDDMSetRHSMat(PC pc, Mat B)
333: {
334:   PetscFunctionBegin;
336:   if (B) {
338:     PetscTryMethod(pc, "PCHPDDMSetRHSMat_C", (PC, Mat), (pc, B));
339:   }
340:   PetscFunctionReturn(PETSC_SUCCESS);
341: }

343: static PetscErrorCode PCSetFromOptions_HPDDM(PC pc, PetscOptionItems PetscOptionsObject)
344: {
345:   PC_HPDDM                   *data = (PC_HPDDM *)pc->data;
346:   char                        prefix[256], deprecated[256];
347:   int                         i = 1;
348:   PetscInt                    n, overlap = 1;
349:   PetscMPIInt                 size, previous;
350:   PCHPDDMCoarseCorrectionType type;
351:   PetscBool                   flg = PETSC_TRUE, set;

353:   PetscFunctionBegin;
354:   PetscCall(PCHPDDMInitializeLevels_Private(data));
355:   PetscOptionsHeadBegin(PetscOptionsObject, "PCHPDDM options");
356:   PetscCall(PetscOptionsBoundedInt("-pc_hpddm_harmonic_overlap", "Overlap prior to computing local harmonic extensions", "PCHPDDM", overlap, &overlap, &set, 1));
357:   if (!set) overlap = -1;
358:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
359:   previous = size;
360:   while (i < PETSC_PCHPDDM_MAXLEVELS) {
361:     PetscInt p = 1;

363:     if (!data->levels[i - 1]) PetscCall(PetscNew(data->levels + i - 1));
364:     data->levels[i - 1]->parent = data;
365:     /* if the previous level has a single process, it is not possible to coarsen further */
366:     if (previous == 1 || !flg) break;
367:     data->levels[i - 1]->nu        = 0;
368:     data->levels[i - 1]->threshold = -1.0;
369:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i));
370:     PetscCall(PetscOptionsBoundedInt(prefix, "Local number of deflation vectors computed by SLEPc", "EPSSetDimensions", data->levels[i - 1]->nu, &data->levels[i - 1]->nu, nullptr, 0));
371:     PetscCall(PetscSNPrintf(deprecated, sizeof(deprecated), "-pc_hpddm_levels_%d_eps_threshold", i));
372:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold_absolute", i));
373:     PetscCall(PetscOptionsDeprecated(deprecated, prefix, "3.24", nullptr));
374:     PetscCall(PetscOptionsReal(prefix, "Local absolute threshold for selecting deflation vectors returned by SLEPc", "PCHPDDM", data->levels[i - 1]->threshold, &data->levels[i - 1]->threshold, nullptr));
375:     if (i == 1) {
376:       PetscCheck(overlap == -1 || PetscAbsReal(data->levels[i - 1]->threshold + static_cast<PetscReal>(1.0)) < PETSC_MACHINE_EPSILON, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply both -pc_hpddm_levels_1_eps_threshold_absolute and -pc_hpddm_harmonic_overlap");
377:       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_svd_nsv", i));
378:       if (overlap != -1) {
379:         PetscInt  nsv    = 0;
380:         PetscBool set[2] = {PETSC_FALSE, PETSC_FALSE};

382:         PetscCall(PetscOptionsBoundedInt(prefix, "Local number of deflation vectors computed by SLEPc", "SVDSetDimensions", nsv, &nsv, nullptr, 0));
383:         PetscCheck(data->levels[0]->nu == 0 || nsv == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply both -pc_hpddm_levels_1_eps_nev and -pc_hpddm_levels_1_svd_nsv");
384:         if (data->levels[0]->nu == 0) { /* -eps_nev has not been used, so nu is 0 */
385:           data->levels[0]->nu = nsv;    /* nu may still be 0 if -svd_nsv has not been used */
386:           PetscCall(PetscSNPrintf(deprecated, sizeof(deprecated), "-pc_hpddm_levels_%d_svd_relative_threshold", i));
387:           PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_svd_threshold_relative", i));
388:           PetscCall(PetscOptionsDeprecated(deprecated, prefix, "3.24", nullptr));
389:           PetscCall(PetscOptionsReal(prefix, "Local relative threshold for selecting deflation vectors returned by SLEPc", "PCHPDDM", data->levels[0]->threshold, &data->levels[0]->threshold, set)); /* cache whether this option has been used or not to error out in case of exclusive options being used simultaneously later on */
390:         }
391:         if (data->levels[0]->nu == 0 || nsv == 0) { /* if neither -eps_nev nor -svd_nsv has been used */
392:           PetscCall(PetscSNPrintf(deprecated, sizeof(deprecated), "-pc_hpddm_levels_%d_eps_relative_threshold", i));
393:           PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold_relative", i));
394:           PetscCall(PetscOptionsDeprecated(deprecated, prefix, "3.24", nullptr));
395:           PetscCall(PetscOptionsReal(prefix, "Local relative threshold for selecting deflation vectors returned by SLEPc", "PCHPDDM", data->levels[0]->threshold, &data->levels[0]->threshold, set + 1));
396:           PetscCheck(!set[0] || !set[1], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply both -pc_hpddm_levels_1_eps_threshold_relative and -pc_hpddm_levels_1_svd_threshold_relative");
397:         }
398:         PetscCheck(data->levels[0]->nu || PetscAbsReal(data->levels[i - 1]->threshold + static_cast<PetscReal>(1.0)) > PETSC_MACHINE_EPSILON, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Need to supply at least one of 1) -pc_hpddm_levels_1_eps_nev, 2) -pc_hpddm_levels_1_svd_nsv, 3) -pc_hpddm_levels_1_eps_threshold_relative, 4) -pc_hpddm_levels_1_svd_threshold_relative (for nonsymmetric matrices, only option 2 and option 4 are appropriate)");
399:       } else if (PetscDefined(USE_DEBUG)) {
400:         PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
401:         PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply -%spc_hpddm_levels_%d_svd_nsv without -%spc_hpddm_harmonic_overlap", PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "", i,
402:                    PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "");
403:         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_svd_threshold_relative", i));
404:         PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
405:         PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply -%spc_hpddm_levels_%d_svd_threshold_relative without -%spc_hpddm_harmonic_overlap", PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "", i,
406:                    PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "");
407:         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold_relative", i));
408:         PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
409:         PetscCheck(!flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Cannot supply -%spc_hpddm_levels_%d_eps_threshold_relative without -%spc_hpddm_harmonic_overlap, maybe you meant to use -%spc_hpddm_levels_%d_eps_threshold_absolute?",
410:                    PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "", i, PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "", PetscOptionsObject->prefix ? PetscOptionsObject->prefix : "", i);
411:       }
412:       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_1_st_share_sub_ksp"));
413:       PetscCall(PetscOptionsBool(prefix, "Shared KSP between SLEPc ST and the fine-level subdomain solver", "PCHPDDMSetSTShareSubKSP", PETSC_FALSE, &data->share, nullptr));
414:     }
415:     /* if there is no prescribed coarsening, just break out of the loop */
416:     if (data->levels[i - 1]->threshold <= PetscReal() && data->levels[i - 1]->nu <= 0 && !(data->deflation && i == 1)) break;
417:     else {
418:       ++i;
419:       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_nev", i));
420:       PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
421:       if (!flg) {
422:         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_eps_threshold_absolute", i));
423:         PetscCall(PetscOptionsHasName(PetscOptionsObject->options, PetscOptionsObject->prefix, prefix, &flg));
424:       }
425:       if (flg) {
426:         /* if there are coarsening options for the next level, then register it  */
427:         /* otherwise, don't to avoid having both options levels_N_p and coarse_p */
428:         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_levels_%d_p", i));
429:         PetscCall(PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarse operator at this level", "PCHPDDM", p, &p, &flg, 1, PetscMax(1, previous / 2)));
430:         previous = p;
431:       }
432:     }
433:   }
434:   data->N = i;
435:   n       = 1;
436:   if (i > 1) {
437:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_coarse_p"));
438:     PetscCall(PetscOptionsRangeInt(prefix, "Number of processes used to assemble the coarsest operator", "PCHPDDM", n, &n, nullptr, 1, PetscMax(1, previous / 2)));
439: #if PetscDefined(HAVE_MUMPS)
440:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "pc_hpddm_coarse_"));
441:     PetscCall(PetscOptionsHasName(PetscOptionsObject->options, prefix, "-mat_mumps_use_omp_threads", &flg));
442:     if (flg) {
443:       char type[64]; /* same size as in src/ksp/pc/impls/factor/factimpl.c */

445:       PetscCall(PetscStrncpy(type, n > 1 && PetscDefined(HAVE_MUMPS) ? MATSOLVERMUMPS : MATSOLVERPETSC, sizeof(type))); /* default solver for a MatMPIAIJ or a MatSeqAIJ */
446:       PetscCall(PetscOptionsGetString(PetscOptionsObject->options, prefix, "-pc_factor_mat_solver_type", type, sizeof(type), nullptr));
447:       PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
448:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-%smat_mumps_use_omp_threads and -%spc_factor_mat_solver_type != %s", prefix, prefix, MATSOLVERMUMPS);
449:       size = n;
450:       n    = -1;
451:       PetscCall(PetscOptionsGetInt(PetscOptionsObject->options, prefix, "-mat_mumps_use_omp_threads", &n, nullptr));
452:       PetscCheck(n >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Need to specify a positive integer for -%smat_mumps_use_omp_threads", prefix);
453:       PetscCheck(n * size <= previous, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%d MPI process%s x %d OpenMP thread%s greater than %d available MPI process%s for the coarsest operator", (int)size, size > 1 ? "es" : "", (int)n, n > 1 ? "s" : "", (int)previous, previous > 1 ? "es" : "");
454:     }
455: #endif
456:     PetscCall(PetscOptionsEnum("-pc_hpddm_coarse_correction", "Type of coarse correction applied each iteration", "PCHPDDMSetCoarseCorrectionType", PCHPDDMCoarseCorrectionTypes, (PetscEnum)data->correction, (PetscEnum *)&type, &flg));
457:     if (flg) PetscCall(PCHPDDMSetCoarseCorrectionType(pc, type));
458:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_has_neumann"));
459:     PetscCall(PetscOptionsBool(prefix, "Is the auxiliary Mat the local Neumann matrix?", "PCHPDDMHasNeumannMat", PetscBool3ToBool(data->Neumann), &flg, &set));
460:     if (set) data->Neumann = PetscBoolToBool3(flg);
461:     data->log_separate = PETSC_FALSE;
462:     if (PetscDefined(USE_LOG)) {
463:       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-pc_hpddm_log_separate"));
464:       PetscCall(PetscOptionsBool(prefix, "Log events level by level instead of inside PCSetUp()/KSPSolve()", nullptr, data->log_separate, &data->log_separate, nullptr));
465:     }
466:   }
467:   PetscOptionsHeadEnd();
468:   for (; i < PETSC_PCHPDDM_MAXLEVELS && data->levels[i]; ++i) {
469:     PetscCall(KSPDestroy(&data->levels[i]->ksp));
470:     PetscCall(PCDestroy(&data->levels[i]->pc));
471:     PetscCall(PetscFree(data->levels[i]));
472:   }
473:   if (data->levels[0]->ksp) { /* PCSetUp_HPDDM() may have created this KSP initially as a single-level solver before PCSetFromOptions() enabled multiple levels */
474:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_%s_", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", data->N > 1 ? "levels_1" : "coarse"));
475:     PetscCall(KSPSetOptionsPrefix(data->levels[0]->ksp, prefix));
476:   }
477:   PetscFunctionReturn(PETSC_SUCCESS);
478: }

480: template <bool transpose>
481: static PetscErrorCode PCApply_HPDDM(PC pc, Vec x, Vec y)
482: {
483:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

485:   PetscFunctionBegin;
486:   PetscCall(PetscCitationsRegister(HPDDMCitation, &HPDDMCite));
487:   PetscCheck(data->levels[0]->ksp, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
488:   if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_Solve[0], data->levels[0]->ksp, nullptr, nullptr, nullptr)); /* coarser-level events are directly triggered in HPDDM */
489:   if (!transpose) PetscCall(KSPSolve(data->levels[0]->ksp, x, y));
490:   else PetscCall(KSPSolveTranspose(data->levels[0]->ksp, x, y));
491:   PetscCall(KSPCheckSolve(data->levels[0]->ksp, pc, y));
492:   if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Solve[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
493:   PetscFunctionReturn(PETSC_SUCCESS);
494: }

496: template <bool transpose>
497: static PetscErrorCode PCMatApply_HPDDM(PC pc, Mat X, Mat Y)
498: {
499:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

501:   PetscFunctionBegin;
502:   PetscCall(PetscCitationsRegister(HPDDMCitation, &HPDDMCite));
503:   PetscCheck(data->levels[0]->ksp, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No KSP attached to PCHPDDM");
504:   if (!transpose) PetscCall(KSPMatSolve(data->levels[0]->ksp, X, Y));
505:   else PetscCall(KSPMatSolveTranspose(data->levels[0]->ksp, X, Y));
506:   PetscCall(KSPCheckMatSolve(data->levels[0]->ksp, pc, Y));
507:   PetscFunctionReturn(PETSC_SUCCESS);
508: }

510: /*@
511:   PCHPDDMGetComplexities - Computes the grid and operator complexities.

513:   Collective

515:   Input Parameter:
516: . pc - preconditioner context

518:   Output Parameters:
519: + gc - grid complexity $\sum_i m_i / m_1$
520: - oc - operator complexity $\sum_i nnz_i / nnz_1$

522:   Level: advanced

524: .seealso: [](ch_ksp), `PCMGGetGridComplexity()`, `PCHPDDM`, `PCHYPRE`, `PCGAMG`
525: @*/
526: PetscErrorCode PCHPDDMGetComplexities(PC pc, PetscReal *gc, PetscReal *oc)
527: {
528:   PC_HPDDM      *data = (PC_HPDDM *)pc->data;
529:   MatInfo        info;
530:   PetscLogDouble accumulate[2]{}, nnz1 = 1.0, m1 = 1.0;

532:   PetscFunctionBegin;
533:   if (gc) {
534:     PetscAssertPointer(gc, 2);
535:     *gc = 0;
536:   }
537:   if (oc) {
538:     PetscAssertPointer(oc, 3);
539:     *oc = 0;
540:   }
541:   for (PetscInt n = 0; n < data->N; ++n) {
542:     if (data->levels[n]->ksp) {
543:       Mat       P, A = nullptr;
544:       PetscInt  m;
545:       PetscBool flg = PETSC_FALSE;

547:       PetscCall(KSPGetOperators(data->levels[n]->ksp, nullptr, &P));
548:       PetscCall(MatGetSize(P, &m, nullptr));
549:       accumulate[0] += m;
550:       if (n == 0) {
551:         PetscCall(PetscObjectTypeCompareAny((PetscObject)P, &flg, MATNORMAL, MATNORMALHERMITIAN, ""));
552:         if (flg) {
553:           PetscCall(MatConvert(P, MATAIJ, MAT_INITIAL_MATRIX, &A));
554:           P = A;
555:         } else {
556:           PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
557:           PetscCall(PetscObjectReference((PetscObject)P));
558:         }
559:       }
560:       if (!A && flg) accumulate[1] += m * m; /* assumption that a MATSCHURCOMPLEMENT is dense if stored explicitly */
561:       else if (P->ops->getinfo) {
562:         PetscCall(MatGetInfo(P, MAT_GLOBAL_SUM, &info));
563:         accumulate[1] += info.nz_used;
564:       }
565:       if (n == 0) {
566:         m1 = m;
567:         if (!A && flg) nnz1 = m * m;
568:         else if (P->ops->getinfo) nnz1 = info.nz_used;
569:         PetscCall(MatDestroy(&P));
570:       }
571:     }
572:   }
573:   /* only process #0 has access to the full hierarchy by construction, so broadcast to ensure consistent outputs */
574:   PetscCallMPI(MPI_Bcast(accumulate, 2, MPIU_PETSCLOGDOUBLE, 0, PetscObjectComm((PetscObject)pc)));
575:   if (gc) *gc = static_cast<PetscReal>(accumulate[0] / m1);
576:   if (oc) *oc = static_cast<PetscReal>(accumulate[1] / nnz1);
577:   PetscFunctionReturn(PETSC_SUCCESS);
578: }

580: static PetscErrorCode PCView_HPDDM(PC pc, PetscViewer viewer)
581: {
582:   PC_HPDDM         *data = (PC_HPDDM *)pc->data;
583:   PetscViewer       subviewer;
584:   PetscViewerFormat format;
585:   PetscSubcomm      subcomm;
586:   PetscReal         oc, gc;
587:   PetscInt          tabs;
588:   PetscMPIInt       size, color, rank;
589:   PetscBool         flg;
590:   const char       *name;

592:   PetscFunctionBegin;
593:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg));
594:   if (flg) {
595:     PetscCall(PetscViewerASCIIPrintf(viewer, "level%s: %" PetscInt_FMT "\n", data->N > 1 ? "s" : "", data->N));
596:     PetscCall(PCHPDDMGetComplexities(pc, &gc, &oc));
597:     if (data->N > 1) {
598:       if (!data->deflation) {
599:         PetscCall(PetscViewerASCIIPrintf(viewer, "Neumann matrix attached? %s\n", PetscBools[PetscBool3ToBool(data->Neumann)]));
600:         PetscCall(PetscViewerASCIIPrintf(viewer, "shared subdomain KSP between SLEPc and PETSc? %s\n", PetscBools[data->share]));
601:       } else PetscCall(PetscViewerASCIIPrintf(viewer, "user-supplied deflation matrix%s\n", data->scaling ? " and scaling" : ""));
602:       PetscCall(PetscViewerASCIIPrintf(viewer, "coarse correction: %s\n", PCHPDDMCoarseCorrectionTypes[data->correction]));
603:       PetscCall(PetscViewerASCIIPrintf(viewer, "on process #0, value%s (+ threshold%s if available) for selecting deflation vectors:", data->N > 2 ? "s" : "", data->N > 2 ? "s" : ""));
604:       PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
605:       PetscCall(PetscViewerASCIISetTab(viewer, 0));
606:       for (PetscInt i = 1; i < data->N; ++i) {
607:         PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, data->levels[i - 1]->nu));
608:         if (data->levels[i - 1]->threshold > static_cast<PetscReal>(-0.1)) PetscCall(PetscViewerASCIIPrintf(viewer, " (%g)", (double)data->levels[i - 1]->threshold));
609:       }
610:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
611:       PetscCall(PetscViewerASCIISetTab(viewer, tabs));
612:     }
613:     PetscCall(PetscViewerASCIIPrintf(viewer, "grid and operator complexities: %g %g\n", (double)gc, (double)oc));
614:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
615:     if (data->levels && data->levels[0]->ksp) {
616:       PetscCall(KSPView(data->levels[0]->ksp, viewer));
617:       if (data->levels[0]->pc) PetscCall(PCView(data->levels[0]->pc, viewer));
618:       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)pc), &rank));
619:       for (PetscInt i = 1; i < data->N; ++i) {
620:         if (data->levels[i]->ksp) color = 1;
621:         else color = 0;
622:         PetscCall(PetscSubcommCreate(PetscObjectComm((PetscObject)pc), &subcomm));
623:         PetscCall(PetscSubcommSetNumber(subcomm, PetscMin(size, 2)));
624:         PetscCall(PetscSubcommSetTypeGeneral(subcomm, color, rank));
625:         PetscCall(PetscViewerASCIIPushTab(viewer));
626:         PetscCall(PetscViewerGetSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer));
627:         if (color == 1) {
628:           PetscCall(KSPView(data->levels[i]->ksp, subviewer));
629:           if (data->levels[i]->pc) PetscCall(PCView(data->levels[i]->pc, subviewer));
630:           PetscCall(PetscViewerFlush(subviewer));
631:         }
632:         PetscCall(PetscViewerRestoreSubViewer(viewer, PetscSubcommChild(subcomm), &subviewer));
633:         PetscCall(PetscViewerASCIIPopTab(viewer));
634:         PetscCall(PetscSubcommDestroy(&subcomm));
635:       }
636:     }
637:     PetscCall(PetscViewerGetFormat(viewer, &format));
638:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
639:       PetscCall(PetscViewerFileGetName(viewer, &name));
640:       if (name) {
641:         Mat             aux[2];
642:         IS              is;
643:         const PetscInt *indices;
644:         PetscInt        m, n, sizes[5] = {pc->mat->rmap->n, pc->mat->cmap->n, pc->mat->rmap->N, pc->mat->cmap->N, 0};
645:         char           *tmp;
646:         std::string     prefix, suffix;
647:         size_t          pos;

649:         PetscCall(PetscStrstr(name, ".", &tmp));
650:         if (tmp) {
651:           pos    = std::distance(const_cast<char *>(name), tmp);
652:           prefix = std::string(name, pos);
653:           suffix = std::string(name + pos + 1);
654:         } else prefix = name;
655:         if (data->aux) {
656:           PetscCall(MatGetSize(data->aux, &m, &n));
657:           PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), aux));
658:           PetscCall(MatSetSizes(aux[0], m, n, PETSC_DETERMINE, PETSC_DETERMINE));
659:           PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQAIJ, &flg));
660:           if (flg) PetscCall(MatSetType(aux[0], MATMPIAIJ));
661:           else {
662:             PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQBAIJ, &flg));
663:             if (flg) PetscCall(MatSetType(aux[0], MATMPIBAIJ));
664:             else {
665:               PetscCall(PetscObjectBaseTypeCompare((PetscObject)data->aux, MATSEQSBAIJ, &flg));
666:               PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "MatType of auxiliary Mat (%s) is not any of the following: MATSEQAIJ, MATSEQBAIJ, or MATSEQSBAIJ", ((PetscObject)data->aux)->type_name);
667:               PetscCall(MatSetType(aux[0], MATMPISBAIJ));
668:             }
669:           }
670:           PetscCall(MatSetBlockSizesFromMats(aux[0], data->aux, data->aux));
671:           PetscCall(MatAssemblyBegin(aux[0], MAT_FINAL_ASSEMBLY));
672:           PetscCall(MatAssemblyEnd(aux[0], MAT_FINAL_ASSEMBLY));
673:           PetscCall(MatGetDiagonalBlock(aux[0], aux + 1));
674:           PetscCall(MatCopy(data->aux, aux[1], DIFFERENT_NONZERO_PATTERN));
675:           PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_aux_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
676:           PetscCall(MatView(aux[0], subviewer));
677:           PetscCall(PetscViewerDestroy(&subviewer));
678:           PetscCall(MatDestroy(aux));
679:         }
680:         if (data->is) {
681:           PetscCall(ISGetIndices(data->is, &indices));
682:           PetscCall(ISGetSize(data->is, sizes + 4));
683:           PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), sizes[4], indices, PETSC_USE_POINTER, &is));
684:           PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_is_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
685:           PetscCall(ISView(is, subviewer));
686:           PetscCall(PetscViewerDestroy(&subviewer));
687:           PetscCall(ISDestroy(&is));
688:           PetscCall(ISRestoreIndices(data->is, &indices));
689:         }
690:         PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)pc), PETSC_STATIC_ARRAY_LENGTH(sizes), sizes, PETSC_USE_POINTER, &is));
691:         PetscCall(PetscViewerBinaryOpen(PetscObjectComm((PetscObject)pc), std::string(prefix + "_sizes_" + std::to_string(size) + (tmp ? ("." + suffix) : "")).c_str(), FILE_MODE_WRITE, &subviewer));
692:         PetscCall(ISView(is, subviewer));
693:         PetscCall(PetscViewerDestroy(&subviewer));
694:         PetscCall(ISDestroy(&is));
695:       }
696:     }
697:   }
698:   PetscFunctionReturn(PETSC_SUCCESS);
699: }

701: static PetscErrorCode PCPreSolve_HPDDM(PC pc, KSP ksp, Vec, Vec)
702: {
703:   PC_HPDDM *data = (PC_HPDDM *)pc->data;
704:   Mat       A;
705:   PetscBool flg;

707:   PetscFunctionBegin;
708:   if (ksp) {
709:     PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPLSQR, &flg));
710:     if (flg && !data->normal) {
711:       PetscCall(KSPGetOperators(ksp, &A, nullptr));
712:       PetscCall(MatCreateVecs(A, nullptr, &data->normal)); /* temporary Vec used in PCApply_HPDDMShell() for coarse grid corrections */
713:     } else if (!flg) {
714:       PetscCall(PetscObjectTypeCompareAny((PetscObject)ksp, &flg, KSPCG, KSPGROPPCG, KSPPIPECG, KSPPIPECGRR, KSPPIPELCG, KSPPIPEPRCG, KSPPIPECG2, KSPSTCG, KSPFCG, KSPPIPEFCG, KSPMINRES, KSPNASH, KSPSYMMLQ, ""));
715:       if (!flg) {
716:         PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPHPDDM, &flg));
717:         if (flg) {
718:           KSPHPDDMType type;

720:           PetscCall(KSPHPDDMGetType(ksp, &type));
721:           flg = (type == KSP_HPDDM_TYPE_CG || type == KSP_HPDDM_TYPE_BCG || type == KSP_HPDDM_TYPE_BFBCG ? PETSC_TRUE : PETSC_FALSE);
722:         }
723:       }
724:     }
725:     if (flg) {
726:       if (data->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || data->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED_REVERSED) {
727:         PetscCall(PetscOptionsHasName(((PetscObject)pc)->options, ((PetscObject)pc)->prefix, "-pc_hpddm_coarse_correction", &flg));
728:         PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_INCOMP, "PCHPDDMCoarseCorrectionType %s is known to be not symmetric, but KSPType %s requires a symmetric PC, if you insist on using this configuration, use the additional option -%spc_hpddm_coarse_correction %s, or alternatively, switch to a symmetric PCHPDDMCoarseCorrectionType such as %s",
729:                    PCHPDDMCoarseCorrectionTypes[data->correction], ((PetscObject)ksp)->type_name, ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", PCHPDDMCoarseCorrectionTypes[data->correction], PCHPDDMCoarseCorrectionTypes[PC_HPDDM_COARSE_CORRECTION_BALANCED]);
730:       }
731:       for (PetscInt n = 0; n < data->N; ++n) {
732:         PC inner = data->levels[n]->pc;

734:         /* with a single level, no inner PCSHELL is used; inspect directly the PC attached to the KSP */
735:         if (!inner && data->N == 1) PetscCall(KSPGetPC(data->levels[n]->ksp, &inner));
736:         if (inner) {
737:           PetscCall(PetscObjectTypeCompare((PetscObject)inner, PCASM, &flg));
738:           if (flg) {
739:             PCASMType type;

741:             PetscCall(PCASMGetType(inner, &type));
742:             if (type == PC_ASM_RESTRICT || type == PC_ASM_INTERPOLATE || type == PC_ASM_WEIGHTED) {
743:               PetscCall(PetscOptionsHasName(((PetscObject)inner)->options, ((PetscObject)inner)->prefix, "-pc_asm_type", &flg));
744:               PetscCheck(flg, PetscObjectComm((PetscObject)inner), PETSC_ERR_ARG_INCOMP, "PCASMType %s is known to be not symmetric, but KSPType %s requires a symmetric PC, if you insist on using this configuration, use the additional option -%spc_asm_type %s, or alternatively, switch to a symmetric PCASMType such as %s", PCASMTypes[type],
745:                          ((PetscObject)ksp)->type_name, ((PetscObject)inner)->prefix, PCASMTypes[type], PCASMTypes[PC_ASM_BASIC]);
746:             }
747:           }
748:         }
749:       }
750:     }
751:   }
752:   PetscFunctionReturn(PETSC_SUCCESS);
753: }

755: static PetscErrorCode PCReset_HPDDMShell(PC pc)
756: {
757:   Mat  A;
758:   Mat *shared;

760:   PetscFunctionBegin;
761:   if (pc->matwork != nullptr && pc->matwork[1] != nullptr) {
762:     PetscCall(MatProductGetMats(pc->matwork[1], &A, nullptr, nullptr));
763:     if (A != nullptr) {
764:       PetscCall(PetscObjectContainerQuery((PetscObject)A, "_HPDDM_MatProduct", static_cast<void *>(&shared)));
765:       if (shared == pc->matwork + 1) PetscCall(PetscObjectCompose((PetscObject)A, "_HPDDM_MatProduct", nullptr));
766:     }
767:   }
768:   PetscCall(PCMatWorkReset(pc));
769:   PetscFunctionReturn(PETSC_SUCCESS);
770: }

772: static PetscErrorCode PCSetUp_HPDDMShell(PC pc)
773: {
774:   PC_HPDDM_Level *ctx;
775:   Mat             A, P;
776:   Vec             x;
777:   const char     *pcpre;

779:   PetscFunctionBegin;
780:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
781:   PetscCall(KSPGetOptionsPrefix(ctx->ksp, &pcpre));
782:   PetscCall(KSPGetOperators(ctx->ksp, &A, &P));
783:   /* smoother */
784:   PetscCall(PCSetOptionsPrefix(ctx->pc, pcpre));
785:   PetscCall(PCSetOperators(ctx->pc, A, P));
786:   if (!ctx->v[0]) {
787:     PetscCall(VecDuplicateVecs(ctx->D, 1, &ctx->v[0]));
788:     if (!std::is_same<PetscScalar, PetscReal>::value) PetscCall(VecDestroy(&ctx->D));
789:     PetscCall(MatCreateVecs(A, &x, nullptr));
790:     PetscCall(VecDuplicateVecs(x, 2, &ctx->v[1]));
791:     PetscCall(VecDestroy(&x));
792:   }
793:   PetscCall(PCReset_HPDDMShell(pc));
794:   /* indices 0-2 are for the deflation matrices, 3-4 for the coarse solves, and 5 when using PC[G]ASM with a larger overlap than PCHPDDM */
795:   PetscCall(PCMatWorkSetUp(pc, 6, PETSC_DECIDE));
796:   PetscFunctionReturn(PETSC_SUCCESS);
797: }

799: template <char trans = 'N', class Type = Vec, std::enable_if_t<std::is_same<Type, Vec>::value> * = nullptr>
800: static inline PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type x, Type y)
801: {
802:   PC_HPDDM_Level *ctx;

804:   PetscFunctionBegin;
805:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
806:   /* going from PETSc to HPDDM numbering */
807:   PetscCall(VecScatterBegin(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD));
808:   PetscCall(VecScatterEnd(ctx->scatter, x, ctx->v[0][0], INSERT_VALUES, SCATTER_FORWARD));
809:   PetscCall(ctx->P->deflation<false, trans>(ctx->v[0][0], ctx->D)); /* y = Q x */
810:   /* going from HPDDM to PETSc numbering */
811:   PetscCall(VecSet(y, 0.0));
812:   PetscCall(VecScatterBegin(ctx->scatter, ctx->v[0][0], y, ADD_VALUES, SCATTER_REVERSE));
813:   PetscCall(VecScatterEnd(ctx->scatter, ctx->v[0][0], y, ADD_VALUES, SCATTER_REVERSE));
814:   PetscFunctionReturn(PETSC_SUCCESS);
815: }

817: template <char trans = 'N', class Type = Mat, std::enable_if_t<std::is_same<Type, Mat>::value> * = nullptr>
818: static inline PetscErrorCode PCHPDDMDeflate_Private(PC pc, Type X, Type Y)
819: {
820:   PC_HPDDM_Level *ctx;
821:   PetscInt        N, ld[2];

823:   PetscFunctionBegin;
824:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
825:   PetscCall(MatGetSize(X, nullptr, &N));
826:   PetscCall(MatDenseGetLDA(X, ld));
827:   PetscCall(MatDenseGetLDA(Y, ld + 1));
828:   PetscCheck(ld[0] == ld[1], PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Leading dimension of input Mat different than the one of output Mat");
829:   /* going from PETSc to HPDDM numbering */
830:   PetscCall(MatDenseScatter_Private(ctx->scatter, X, pc->matwork[0], INSERT_VALUES, SCATTER_FORWARD));
831:   PetscCall(ctx->P->deflation<false, trans>(pc->matwork[0], ctx->D)); /* Y = Q X */
832:   /* going from HPDDM to PETSc numbering */
833:   PetscCall(MatZeroEntries(Y));
834:   PetscCall(MatDenseScatter_Private(ctx->scatter, pc->matwork[0], Y, ADD_VALUES, SCATTER_REVERSE));
835:   PetscFunctionReturn(PETSC_SUCCESS);
836: }

838: static PetscErrorCode PCApply_HPDDMShell(PC pc, Vec x, Vec y)
839: {
840:   PC_HPDDM_Level *ctx;
841:   Mat             A;

843:   PetscFunctionBegin;
844:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
845:   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
846:   PetscCall(KSPGetOperators(ctx->ksp, &A, nullptr));
847:   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCApply(ctx->pc, x, y)); /* y = M^-1 x */
848:   else if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED_REVERSED) {
849:     PetscCall(PCApply(ctx->pc, x, y)); /* y = M^-1 x */
850:     PetscCall(MatMult(A, y, ctx->v[1][0]));
851:     PetscCall(VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x));          /* z = (I - A M^-1) x            */
852:     PetscCall(PCHPDDMDeflate_Private(pc, ctx->v[1][1], ctx->v[1][0])); /* z = Q (I - A M^-1) x          */
853:     PetscCall(VecAXPY(y, 1.0, ctx->v[1][0]));                          /* y = M^-1 x + Q (I - A M^-1) x */
854:   } else {
855:     PetscCall(PCHPDDMDeflate_Private(pc, x, y)); /* y = Q x */
856:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
857:       if (!ctx->parent->normal || ctx != ctx->parent->levels[0]) PetscCall(MatMult(A, y, ctx->v[1][0])); /* y = A Q x */
858:       else {
859:         /* KSPLSQR and finest level */
860:         PetscCall(MatMult(A, y, ctx->parent->normal));                              /* y = A Q x     */
861:         PetscCall(MatMultHermitianTranspose(A, ctx->parent->normal, ctx->v[1][0])); /* y = A^H A Q x */
862:       }
863:       PetscCall(VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x)); /* y = (I - A Q) x                   */
864:       PetscCall(PCApply(ctx->pc, ctx->v[1][1], ctx->v[1][0]));  /* y = M^-1 (I - A Q) x              */
865:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
866:         if (!ctx->parent->normal || ctx != ctx->parent->levels[0]) PetscCall(MatMult(A, ctx->v[1][0], ctx->v[1][1])); /* z = A y */
867:         else {
868:           PetscCall(MatMult(A, ctx->v[1][0], ctx->parent->normal));
869:           PetscCall(MatMultHermitianTranspose(A, ctx->parent->normal, ctx->v[1][1])); /* z = A^H A y         */
870:         }
871:         PetscCall(PCHPDDMDeflate_Private(pc, ctx->v[1][1], ctx->v[1][1]));     /* z = Q z                    */
872:         PetscCall(VecAXPBYPCZ(y, -1.0, 1.0, 1.0, ctx->v[1][1], ctx->v[1][0])); /* y = (I - Q A) y + Q x      */
873:       } else PetscCall(VecAXPY(y, 1.0, ctx->v[1][0]));                         /* y = M^-1 (I - A Q) x + Q x */
874:     } else {
875:       PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
876:       PetscCall(PCApply(ctx->pc, x, ctx->v[1][0]));
877:       PetscCall(VecAXPY(y, 1.0, ctx->v[1][0])); /* y = M^-1 x + Q x */
878:     }
879:   }
880:   PetscFunctionReturn(PETSC_SUCCESS);
881: }

883: template <bool transpose>
884: static PetscErrorCode PCHPDDMMatApply_Private(PC_HPDDM_Level *ctx, Mat *V, Mat Y, PetscMemType *type, PetscBool *reset)
885: {
886:   Mat            A, *ptr;
887:   PetscScalar   *array;
888:   PetscInt       m, M = 0, N, prev = 0;
889:   PetscContainer container = nullptr;

891:   PetscFunctionBegin;
892:   PetscCall(KSPGetOperators(ctx->ksp, &A, nullptr));
893:   PetscCall(MatGetSize(Y, nullptr, &N));
894:   PetscCall(PetscObjectQuery((PetscObject)A, "_HPDDM_MatProduct", (PetscObject *)&container));
895:   *reset = static_cast<PetscBool>(container != nullptr);
896:   if (container) { /* MatProduct container already attached */
897:     PetscCall(PetscContainerGetPointer(container, static_cast<void *>(&ptr)));
898:     if (ptr[1] != V[2]) /* Mat has changed or may have been set first in KSPHPDDM */
899:       for (m = 0; m < 2; ++m) {
900:         PetscCall(MatDestroy(V + m + 1));
901:         V[m + 1] = ptr[m];
902:         PetscCall(PetscObjectReference((PetscObject)V[m + 1]));
903:       }
904:   }
905:   if (V[1] != nullptr) PetscCall(MatGetSize(V[1], nullptr, &prev));
906:   if (V[0] != nullptr) PetscCall(MatGetSize(V[0], nullptr, &M));
907:   if (N != prev || N != M) {
908:     PetscCall(MatDestroy(V));
909:     PetscCall(MatDestroy(V + 5));
910:     PetscCall(VecGetLocalSize(ctx->v[0][0], &m));
911: #if PetscDefined(HAVE_HPDDM)
912:     /* only PETSc builds can borrow workspace through the private PCASM and PCGASM accessors */
913:     {
914:       PetscBool flg[2] = {PETSC_FALSE, PETSC_FALSE};

916:       PetscCall(PetscObjectTypeCompare((PetscObject)ctx->pc, PCASM, flg));
917:       if (flg[0] == PETSC_FALSE) PetscCall(PetscObjectTypeCompare((PetscObject)ctx->pc, PCGASM, flg + 1));
918:       if (flg[0] == PETSC_TRUE || flg[1] == PETSC_TRUE) {
919:         Mat     W;
920:         VecType vtype;

922:         PetscCall(PCSetUp(ctx->pc));
923:         if (flg[0] == PETSC_TRUE) PetscCall(PCMatWorkGet_ASM(ctx->pc, N, nullptr, &W));
924:         else PetscCall(PCMatWorkGet_GASM(ctx->pc, N, nullptr, &W));
925:         PetscCall(MatGetLocalSize(W, &M, nullptr));
926:         PetscCall(VecGetRootType_Private(ctx->v[1][0], &vtype));
927:         PetscCall(PetscStrcmp(W->defaultvectype, vtype, flg));
928:         if (m <= M && flg[0] == PETSC_TRUE) {
929:           PetscCall(MatDenseGetLocalMatrix(W, &W));
930:           PetscCall(PetscObjectReference((PetscObject)W));
931:           if (m == M) V[0] = W;
932:           else {
933:             V[5] = W;
934:             PetscCall(MatDenseGetArrayWriteAndMemType(W, &array, type));
935:             PetscCall(MatCreateDenseWithMemType(PETSC_COMM_SELF, *type, m, N, m, N, m, array, V));
936:             PetscCall(MatDenseRestoreArrayWriteAndMemType(W, &array));
937:           }
938:         }
939:       }
940:     }
941: #endif
942:     if (V[0] == nullptr) PetscCall(MatCreateDenseFromVecType(PETSC_COMM_SELF, A->defaultvectype, m, N, m, N, PETSC_DECIDE, nullptr, V));
943:     if (N != prev) {
944:       PetscCall(MatDestroy(V + 1));
945:       PetscCall(MatDestroy(V + 2));
946:       PetscCall(MatGetLocalSize(Y, &m, nullptr));
947:       PetscCall(MatGetSize(Y, &M, nullptr));
948:       PetscCall(MatDenseGetArrayWriteAndMemType(V[0], &array, type));
949:       PetscCall(MatCreateDenseWithMemType(PetscObjectComm((PetscObject)Y), *type, m, PETSC_DECIDE, M, N, PETSC_DECIDE, array, V + 1));
950:       PetscCall(MatDenseRestoreArrayWriteAndMemType(V[0], &array));
951:       PetscCall(MatDuplicate(V[1], MAT_DO_NOT_COPY_VALUES, V + 2));
952:       PetscCall(MatProductCreateWithMat(A, !transpose ? Y : V[2], nullptr, V[1]));
953:       PetscCall(MatProductSetType(V[1], !transpose ? MATPRODUCT_AB : MATPRODUCT_AtB));
954:       PetscCall(MatProductSetFromOptions(V[1]));
955:       PetscCall(MatProductSymbolic(V[1]));
956:       if (container == nullptr)
957:         PetscCall(PetscObjectContainerCompose((PetscObject)A, "_HPDDM_MatProduct", static_cast<void *>(V + 1), nullptr)); /* no MatProduct container attached, create one to be queried in KSPHPDDM or at the next call to PCMatApply() */
958:       else PetscCall(PetscContainerSetPointer(container, static_cast<void *>(V + 1)));                                    /* need to compose B and D from MatProductCreateWithMat(A, B, NULL, D), which are stored in the contiguous array V */
959:     }
960:     PetscCallCXX(ctx->P->start(N));
961:   }
962:   if (N == prev || container) { /* when MatProduct container is attached, always need to MatProductReplaceMats() since KSPHPDDM may have replaced the Mat as well */
963:     MatProductType ptype;

965:     PetscCall(MatProductReplaceMats(nullptr, transpose == PETSC_FALSE ? Y : V[2], nullptr, V[1]));
966:     PetscCall(MatProductGetType(V[1], &ptype));
967:     if (ptype != (transpose == PETSC_FALSE ? MATPRODUCT_AB : MATPRODUCT_AtB)) { /* MatProduct previously setup for the other type, e.g., by PCMatApply() before PCMatApplyTranspose() */
968:       PetscCall(MatProductSetType(V[1], transpose == PETSC_FALSE ? MATPRODUCT_AB : MATPRODUCT_AtB));
969:       PetscCall(MatProductSetFromOptions(V[1]));
970:       PetscCall(MatProductSymbolic(V[1]));
971:     }
972:     if (container != nullptr) {
973:       PetscCall(MatDenseGetArrayWriteAndMemType(V[0], &array, type));
974:       PetscCall(MatDensePlaceArrayWithMemType(V[1], *type, array));
975:       PetscCall(MatDenseRestoreArrayWriteAndMemType(V[0], &array));
976:     }
977:   }
978:   PetscFunctionReturn(PETSC_SUCCESS);
979: }

981: /*
982:      PCMatApply_HPDDMShell - Variant of PCApply_HPDDMShell() for blocks of vectors.

984:    Input Parameters:
985: +     pc - preconditioner context
986: -     X - block of input vectors

988:    Output Parameter:
989: .     Y - block of output vectors

991:    Level: advanced

993: .seealso: [](ch_ksp), `PCHPDDM`, `PCApply_HPDDMShell()`, `PCHPDDMCoarseCorrectionType`
994: */
995: static PetscErrorCode PCMatApply_HPDDMShell(PC pc, Mat X, Mat Y)
996: {
997:   PC_HPDDM_Level *ctx;
998:   Mat            *V = pc->matwork;
999:   PetscMemType    type;
1000:   PetscBool       reset = PETSC_FALSE;

1002:   PetscFunctionBegin;
1003:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
1004:   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
1005:   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCMatApply(ctx->pc, X, Y));
1006:   else if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED_REVERSED) {
1007:     PetscCall(PCMatApply(ctx->pc, X, Y));
1008:     PetscCall(PCHPDDMMatApply_Private<false>(ctx, V, Y, &type, &reset));
1009:     PetscCall(MatProductNumeric(V[1]));
1010:     PetscCall(MatCopy(V[1], V[2], SAME_NONZERO_PATTERN));
1011:     PetscCall(MatAXPY(V[2], -1.0, X, SAME_NONZERO_PATTERN));
1012:     PetscCall(PCHPDDMDeflate_Private(pc, V[2], V[2]));
1013:     PetscCall(MatAXPY(Y, -1.0, V[2], SAME_NONZERO_PATTERN));
1014:   } else {
1015:     PetscCall(PCHPDDMMatApply_Private<false>(ctx, V, Y, &type, &reset));
1016:     PetscCall(PCHPDDMDeflate_Private(pc, X, Y));
1017:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
1018:       PetscCall(MatProductNumeric(V[1]));
1019:       PetscCall(MatAXPY(V[1], -1.0, X, SAME_NONZERO_PATTERN));
1020:       PetscCall(PCMatApply(ctx->pc, V[1], V[2]));
1021:       PetscCall(MatAXPY(Y, -1.0, V[2], SAME_NONZERO_PATTERN));
1022:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
1023:         PetscCall(MatProductReplaceMats(nullptr, V[2], nullptr, V[1]));
1024:         PetscCall(MatProductNumeric(V[1]));
1025:         PetscCall(MatCopy(V[1], V[2], SAME_NONZERO_PATTERN));
1026:         PetscCall(PCHPDDMDeflate_Private(pc, V[2], V[2]));
1027:         PetscCall(MatAXPY(Y, 1.0, V[2], SAME_NONZERO_PATTERN));
1028:       }
1029:     } else {
1030:       PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
1031:       PetscCall(PCMatApply(ctx->pc, X, V[2]));
1032:       PetscCall(MatAXPY(Y, 1.0, V[2], SAME_NONZERO_PATTERN));
1033:     }
1034:   }
1035:   if (reset == PETSC_TRUE) PetscCall(MatDenseResetArrayWithMemType(V[1], type));
1036:   PetscFunctionReturn(PETSC_SUCCESS);
1037: }

1039: static PetscErrorCode PCApplyTranspose_HPDDMShell(PC pc, Vec x, Vec y)
1040: {
1041:   PC_HPDDM_Level *ctx;
1042:   Mat             A;

1044:   PetscFunctionBegin;
1045:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
1046:   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
1047:   PetscCheck(!ctx->parent->normal, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Not implemented for the normal equations");
1048:   PetscCall(KSPGetOperators(ctx->ksp, &A, nullptr));
1049:   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCApplyTranspose(ctx->pc, x, y)); /* y = M^-T x */
1050:   else {
1051:     PetscCall(PCHPDDMDeflate_Private<'T'>(pc, x, y)); /* y = Q^T x */
1052:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
1053:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
1054:         PetscCall(MatMultTranspose(A, y, ctx->v[1][0]));                      /* z = A^T Q^T x               */
1055:         PetscCall(VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x));             /* z = (I - A^T Q^T) x         */
1056:         PetscCall(PCApplyTranspose(ctx->pc, ctx->v[1][1], ctx->v[1][0]));     /* y = M^-T (I - A^T Q^T) x    */
1057:       } else PetscCall(PCApplyTranspose(ctx->pc, x, ctx->v[1][0]));           /* y = M^-T x                  */
1058:       PetscCall(MatMultTranspose(A, ctx->v[1][0], ctx->v[1][1]));             /* z = A^T y                   */
1059:       PetscCall(PCHPDDMDeflate_Private<'T'>(pc, ctx->v[1][1], ctx->v[1][1])); /* z = Q^T z                   */
1060:       PetscCall(VecAXPBYPCZ(y, -1.0, 1.0, 1.0, ctx->v[1][1], ctx->v[1][0]));  /* y = (I - Q^T A^T) y + Q^T x */
1061:     } else {
1062:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED_REVERSED) {
1063:         PetscCall(MatMultTranspose(A, y, ctx->v[1][0]));
1064:         PetscCall(VecWAXPY(ctx->v[1][1], -1.0, ctx->v[1][0], x));
1065:       } else PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
1066:       PetscCall(PCApplyTranspose(ctx->pc, ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE ? x : ctx->v[1][1], ctx->v[1][0]));
1067:       PetscCall(VecAXPY(y, 1.0, ctx->v[1][0])); /* y = M^-T x + Q^T x or M^-T (I - A^T Q^T) x + Q^T x */
1068:     }
1069:   }
1070:   PetscFunctionReturn(PETSC_SUCCESS);
1071: }

1073: /*
1074:      PCMatApplyTranspose_HPDDMShell - Variant of PCApplyTranspose_HPDDMShell() for blocks of vectors.

1076:    Input Parameters:
1077: +     pc - preconditioner context
1078: -     X - block of input vectors

1080:    Output Parameter:
1081: .     Y - block of output vectors

1083:    Level: advanced

1085: .seealso: [](ch_ksp), `PCHPDDM`, `PCApplyTranspose_HPDDMShell()`, `PCHPDDMCoarseCorrectionType`
1086: */
1087: static PetscErrorCode PCMatApplyTranspose_HPDDMShell(PC pc, Mat X, Mat Y)
1088: {
1089:   PC_HPDDM_Level *ctx;
1090:   Mat            *V = pc->matwork;
1091:   PetscMemType    type;
1092:   PetscBool       reset = PETSC_FALSE;

1094:   PetscFunctionBegin;
1095:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
1096:   PetscCheck(ctx->P, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with no HPDDM object");
1097:   if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_NONE) PetscCall(PCMatApplyTranspose(ctx->pc, X, Y));
1098:   else {
1099:     PetscCall(PCHPDDMMatApply_Private<true>(ctx, V, Y, &type, &reset));
1100:     PetscCall(PCHPDDMDeflate_Private<'T'>(pc, X, Y));
1101:     if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED) {
1102:       PetscCall(PCMatApplyTranspose(ctx->pc, X, V[2]));
1103:       PetscCall(MatAXPY(Y, 1.0, V[2], SAME_NONZERO_PATTERN));
1104:       PetscCall(MatProductNumeric(V[1]));
1105:       /* V[0] and V[1] memory regions overlap, so need to copy to V[2] and switch array */
1106:       PetscCall(MatCopy(V[1], V[2], SAME_NONZERO_PATTERN));
1107:       if (reset == PETSC_TRUE) PetscCall(MatDenseResetArrayWithMemType(V[1], type));
1108:       PetscCall(PCHPDDMDeflate_Private<'T'>(pc, V[2], V[2]));
1109:       PetscCall(MatAXPY(Y, -1.0, V[2], SAME_NONZERO_PATTERN));
1110:     } else {
1111:       if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED || ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED_REVERSED) {
1112:         PetscCall(MatCopy(Y, V[2], SAME_NONZERO_PATTERN));
1113:         PetscCall(MatProductNumeric(V[1]));
1114:         PetscCall(MatAXPY(V[1], -1.0, X, SAME_NONZERO_PATTERN));
1115:         PetscCall(PCMatApplyTranspose(ctx->pc, V[1], V[2]));
1116:         PetscCall(MatAXPY(Y, -1.0, V[2], SAME_NONZERO_PATTERN));
1117:         if (ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_BALANCED) {
1118:           PetscCall(MatProductNumeric(V[1]));
1119:           PetscCall(MatCopy(V[1], V[2], SAME_NONZERO_PATTERN));
1120:           PetscCall(PCHPDDMDeflate_Private<'T'>(pc, V[2], V[2]));
1121:           PetscCall(MatAXPY(Y, 1.0, V[2], SAME_NONZERO_PATTERN));
1122:         }
1123:       } else {
1124:         PetscCheck(ctx->parent->correction == PC_HPDDM_COARSE_CORRECTION_ADDITIVE, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "PCSHELL from PCHPDDM called with an unknown PCHPDDMCoarseCorrectionType %d", ctx->parent->correction);
1125:         PetscCall(PCMatApplyTranspose(ctx->pc, X, V[2]));
1126:         PetscCall(MatAXPY(Y, 1.0, V[2], SAME_NONZERO_PATTERN));
1127:       }
1128:       if (reset == PETSC_TRUE) PetscCall(MatDenseResetArrayWithMemType(V[1], type));
1129:     }
1130:   }
1131:   PetscFunctionReturn(PETSC_SUCCESS);
1132: }

1134: static PetscErrorCode PCDestroy_HPDDMShell(PC pc)
1135: {
1136:   PC_HPDDM_Level *ctx;

1138:   PetscFunctionBegin;
1139:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&ctx)));
1140:   PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(ctx, PETSC_TRUE));
1141:   PetscCall(VecDestroyVecs(1, &ctx->v[0]));
1142:   PetscCall(VecDestroyVecs(2, &ctx->v[1]));
1143:   PetscCall(PetscObjectCompose((PetscObject)ctx->pc->mat, "_HPDDM_MatProduct", nullptr));
1144:   PetscCall(PCReset_HPDDMShell(pc));
1145:   PetscCall(VecDestroy(&ctx->D));
1146:   PetscCall(PetscSFDestroy(&ctx->scatter));
1147:   PetscCall(PCDestroy(&ctx->pc));
1148:   PetscFunctionReturn(PETSC_SUCCESS);
1149: }

1151: template <class Type, bool T = false, std::enable_if_t<std::is_same<Type, Vec>::value> * = nullptr>
1152: static inline PetscErrorCode PCApply_Schur_Private(PC, std::tuple<KSP, VecScatter, Vec[2]> *p, PC factor, Type x, Type y)
1153: {
1154:   PetscFunctionBegin;
1155:   PetscCall(VecScatterBegin(std::get<1>(*p), x, std::get<2>(*p)[0], INSERT_VALUES, SCATTER_REVERSE));
1156:   PetscCall(VecScatterEnd(std::get<1>(*p), x, std::get<2>(*p)[0], INSERT_VALUES, SCATTER_REVERSE));
1157:   if (!T) PetscCall(PCApply(factor, std::get<2>(*p)[0], std::get<2>(*p)[1]));
1158:   else PetscCall(PCApplyTranspose(factor, std::get<2>(*p)[0], std::get<2>(*p)[1]));
1159:   PetscCall(VecScatterBegin(std::get<1>(*p), std::get<2>(*p)[1], y, INSERT_VALUES, SCATTER_FORWARD));
1160:   PetscCall(VecScatterEnd(std::get<1>(*p), std::get<2>(*p)[1], y, INSERT_VALUES, SCATTER_FORWARD));
1161:   PetscFunctionReturn(PETSC_SUCCESS);
1162: }

1164: template <class Type, bool = false, std::enable_if_t<std::is_same<Type, Mat>::value> * = nullptr>
1165: static inline PetscErrorCode PCApply_Schur_Private(PC pc, std::tuple<KSP, VecScatter, Vec[2]> *p, PC factor, Type X, Type Y)
1166: {
1167:   Mat *B;

1169:   PetscFunctionBegin;
1170:   PetscCall(PCMatWorkSetUp(pc, 2, X->cmap->N));
1171:   B = pc->matwork;
1172:   if (B[0] == nullptr) PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, factor->mat->rmap->n, X->cmap->N, nullptr, B));
1173:   if (B[1] == nullptr) PetscCall(MatDuplicate(B[0], MAT_DO_NOT_COPY_VALUES, B + 1));
1174:   PetscCall(MatDenseScatter_Private(std::get<1>(*p), X, B[0], INSERT_VALUES, SCATTER_REVERSE));
1175:   PetscCall(PCMatApply(factor, B[0], B[1]));
1176:   PetscCall(MatDenseScatter_Private(std::get<1>(*p), B[1], Y, INSERT_VALUES, SCATTER_FORWARD));
1177:   PetscFunctionReturn(PETSC_SUCCESS);
1178: }

1180: template <class Type = Vec, bool T = false>
1181: static PetscErrorCode PCApply_Schur(PC pc, Type x, Type y)
1182: {
1183:   PC                                   factor;
1184:   Mat                                  A;
1185:   MatSolverType                        type;
1186:   PetscBool                            flg;
1187:   std::tuple<KSP, VecScatter, Vec[2]> *p;

1189:   PetscFunctionBegin;
1190:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&p)));
1191:   PetscCall(KSPGetPC(std::get<0>(*p), &factor));
1192:   PetscCall(PCFactorGetMatSolverType(factor, &type));
1193:   PetscCall(PCFactorGetMatrix(factor, &A));
1194:   PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
1195:   if (flg) {
1196:     PetscCheck(PetscDefined(HAVE_MUMPS), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Inconsistent MatSolverType");
1197:     PetscCall(MatMumpsSetIcntl(A, 26, 0));
1198:   } else {
1199:     PetscCall(PetscStrcmp(type, MATSOLVERMKL_PARDISO, &flg));
1200:     PetscCheck(flg && PetscDefined(HAVE_MKL_PARDISO), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Inconsistent MatSolverType");
1201:     flg = PETSC_FALSE;
1202: #if PetscDefined(HAVE_MKL_PARDISO)
1203:     PetscCall(MatMkl_PardisoSetCntl(A, 70, 1));
1204: #endif
1205:   }
1206:   PetscCall(PCApply_Schur_Private<Type, T>(pc, p, factor, x, y));
1207:   if (flg) PetscCall(MatMumpsSetIcntl(A, 26, -1));
1208:   else {
1209: #if PetscDefined(HAVE_MKL_PARDISO)
1210:     PetscCall(MatMkl_PardisoSetCntl(A, 70, 0));
1211: #endif
1212:   }
1213:   PetscFunctionReturn(PETSC_SUCCESS);
1214: }

1216: static PetscErrorCode PCDestroy_Schur(PC pc)
1217: {
1218:   std::tuple<KSP, VecScatter, Vec[2]> *p;

1220:   PetscFunctionBegin;
1221:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&p)));
1222:   PetscCall(VecScatterDestroy(&std::get<1>(*p)));
1223:   PetscCall(VecDestroy(std::get<2>(*p)));
1224:   PetscCall(VecDestroy(std::get<2>(*p) + 1));
1225:   PetscCall(PetscFree(p));
1226:   PetscFunctionReturn(PETSC_SUCCESS);
1227: }

1229: template <char trans>
1230: static PetscErrorCode PCHPDDMSolve_Private(const PC_HPDDM_Level *ctx, PetscScalar *rhs, const unsigned short &mu)
1231: {
1232:   PC                 pc;
1233:   Mat                B, X = nullptr;
1234:   const PetscScalar *array;
1235:   PetscCount         count;
1236:   PetscInt           n, j = 0;
1237:   PetscBool          nonzero;

1239:   PetscFunctionBegin;
1240:   PetscCall(KSPGetOperators(ctx->ksp, &B, nullptr));
1241:   PetscCall(MatGetLocalSize(B, &n, nullptr));
1242:   PetscCall(PetscIntCast(std::distance(ctx->parent->levels, std::find(ctx->parent->levels, ctx->parent->levels + ctx->parent->N, ctx)), &j));
1243:   PetscCheck(j > 0 && j < ctx->parent->N, PetscObjectComm((PetscObject)ctx->ksp), PETSC_ERR_PLIB, "No finer level found for PCHPDDM solve");
1244:   PetscCall(KSPGetPC(ctx->parent->levels[j - 1]->ksp, &pc));
1245:   if (ctx->parent->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_Solve[j], ctx->ksp, nullptr, nullptr, nullptr));
1246:   count = static_cast<PetscCount>(n) * mu;
1247:   if (PetscDefined(USE_COMPLEX) && trans == 'H') PetscCallCXX(std::for_each(rhs, rhs + count, [](PetscScalar &v) { v = PetscConj(v); }));
1248:   PetscCall(KSPGetInitialGuessNonzero(ctx->ksp, &nonzero));
1249:   if (mu == 1) {
1250:     if (!ctx->ksp->vec_rhs) {
1251:       PetscCall(MatCreateVecs(B, nullptr, &ctx->ksp->vec_rhs));
1252:       PetscCall(VecDuplicate(ctx->ksp->vec_rhs, &ctx->ksp->vec_sol));
1253:     }
1254:     PetscCall(VecPlaceArray(ctx->ksp->vec_rhs, rhs));
1255:     if (nonzero == PETSC_TRUE) PetscCall(VecCopy(ctx->ksp->vec_rhs, ctx->ksp->vec_sol));
1256:     if (trans == 'N') PetscCall(KSPSolve(ctx->ksp, nullptr, nullptr));
1257:     else PetscCall(KSPSolveTranspose(ctx->ksp, nullptr, nullptr)); /* TODO: missing KSPSolveHermitianTranspose() */
1258:     PetscCall(VecResetArray(ctx->ksp->vec_rhs));
1259:     PetscCall(KSPCheckSolve(ctx->ksp, pc, ctx->ksp->vec_sol));
1260:     PetscCall(VecGetArrayRead(ctx->ksp->vec_sol, &array));
1261:   } else {
1262:     Mat *work = pc->matwork + 3;

1264:     PetscCheck(pc->nmatwork >= 5, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCSetUp_HPDDMShell() allocated only %" PetscInt_FMT " working matrices, instead of at least 5", pc->nmatwork);
1265:     if (work[0] != nullptr && work[0]->cmap->N != mu) {
1266:       PetscCall(MatDestroy(work));
1267:       PetscCall(MatDestroy(work + 1));
1268:     }
1269:     if (work[0] == nullptr) {
1270:       PetscBool host;

1272:       PetscCall(PetscStrcmpAny(B->defaultvectype, &host, VECSTANDARD, VECSEQ, VECMPI, ""));
1273:       PetscCall(MatCreateDenseFromVecType(PetscObjectComm((PetscObject)ctx->ksp), B->defaultvectype, n, PETSC_DECIDE, B->rmap->N, mu, PETSC_DECIDE, host == PETSC_TRUE ? rhs : nullptr, work));
1274:       if (host == PETSC_TRUE) PetscCall(MatDenseReplaceArray(work[0], nullptr));
1275:     }
1276:     B = work[0];
1277:     if (work[1] == nullptr) PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, work + 1));
1278:     X = work[1];
1279:     PetscCall(MatDensePlaceArray(B, rhs));
1280:     if (nonzero == PETSC_TRUE) PetscCall(MatCopy(B, X, SAME_NONZERO_PATTERN));
1281:     if (trans == 'N') PetscCall(KSPMatSolve(ctx->ksp, B, X));
1282:     else PetscCall(KSPMatSolveTranspose(ctx->ksp, B, X)); /* TODO: missing KSPMatSolveHermitianTranspose() */
1283:     PetscCall(MatDenseResetArray(B));
1284:     PetscCall(KSPCheckMatSolve(ctx->ksp, pc, X));
1285:     PetscCall(MatDenseGetArrayRead(X, &array));
1286:   }
1287:   if (PetscDefined(USE_COMPLEX) && trans == 'H') PetscCallCXX(std::transform(array, array + count, rhs, [](const PetscScalar &v) { return PetscConj(v); }));
1288:   else PetscCall(PetscArraycpy(rhs, array, count));
1289:   if (mu == 1) PetscCall(VecRestoreArrayRead(ctx->ksp->vec_sol, &array));
1290:   else PetscCall(MatDenseRestoreArrayRead(X, &array));
1291:   if (ctx->parent->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Solve[j], ctx->ksp, nullptr, nullptr, nullptr));
1292:   PetscFunctionReturn(PETSC_SUCCESS);
1293: }

1295: static PetscErrorCode PCHPDDMSetUpNeumannOverlap_Private(PC pc)
1296: {
1297:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

1299:   PetscFunctionBegin;
1300:   if (data->setup) {
1301:     Mat       P;
1302:     Vec       x, xt = nullptr;
1303:     PetscReal t = 0.0, s = 0.0;

1305:     PetscCall(PCGetOperators(pc, nullptr, &P));
1306:     PetscCall(PetscObjectQuery((PetscObject)P, "__SNES_latest_X", (PetscObject *)&x));
1307:     PetscCallBack("PCHPDDM Neumann callback", (*data->setup)(data->aux, t, x, xt, s, data->is, data->setup_ctx));
1308:   }
1309:   PetscFunctionReturn(PETSC_SUCCESS);
1310: }

1312: static PetscErrorCode PCHPDDMCreateSubMatrices_Private(Mat mat, PetscInt n, const IS *, const IS *, MatReuse scall, Mat *submat[])
1313: {
1314:   Mat       A;
1315:   PetscBool flg;

1317:   PetscFunctionBegin;
1318:   PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "MatCreateSubMatrices() called to extract %" PetscInt_FMT " submatrices, which is different than 1", n);
1319:   /* previously composed Mat */
1320:   PetscCall(PetscObjectQuery((PetscObject)mat, "_PCHPDDM_SubMatrices", (PetscObject *)&A));
1321:   PetscCheck(A, PETSC_COMM_SELF, PETSC_ERR_PLIB, "SubMatrices not found in Mat");
1322:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSCHURCOMPLEMENT, &flg)); /* MATSCHURCOMPLEMENT has neither a MatDuplicate() nor a MatCopy() implementation */
1323:   if (scall == MAT_INITIAL_MATRIX) {
1324:     PetscCall(PetscCalloc1(2, submat)); /* allocate an extra Mat to avoid errors in MatDestroySubMatrices_SeqXAIJ() */
1325:     if (!flg) PetscCall(MatDuplicate(A, MAT_COPY_VALUES, *submat));
1326:   } else if (!flg) PetscCall(MatCopy(A, (*submat)[0], SAME_NONZERO_PATTERN));
1327:   if (flg) {
1328:     PetscCall(MatDestroy(*submat)); /* previously created Mat has to be destroyed */
1329:     (*submat)[0] = A;
1330:     PetscCall(PetscObjectReference((PetscObject)A));
1331:   }
1332:   PetscFunctionReturn(PETSC_SUCCESS);
1333: }

1335: static PetscErrorCode PCHPDDMCommunicationAvoidingPCASM_Private(PC pc, Mat C, PetscBool sorted)
1336: {
1337:   PetscErrorCodeFn *op;

1339:   PetscFunctionBegin;
1340:   /* previously-composed Mat */
1341:   PetscCall(PetscObjectCompose((PetscObject)pc->pmat, "_PCHPDDM_SubMatrices", (PetscObject)C));
1342:   PetscCall(MatGetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, &op));
1343:   /* see https://mailman.cels.anl.gov/archives/list/petsc-dev@lists.mcs.anl.gov/message/22HXNMER6OU7N7CXWA2LJAY6RZPGQYXT/ */
1344:   PetscCall(MatSetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, (PetscErrorCodeFn *)PCHPDDMCreateSubMatrices_Private));
1345:   if (sorted) PetscCall(PCASMSetSortIndices(pc, PETSC_FALSE)); /* everything is already sorted */
1346:   PetscCall(PCSetFromOptions(pc));                             /* otherwise -pc_hpddm_levels_1_pc_asm_sub_mat_type is not used */
1347:   PetscCall(PCSetUp(pc));
1348:   /* reset MatCreateSubMatrices() */
1349:   PetscCall(MatSetOperation(pc->pmat, MATOP_CREATE_SUBMATRICES, op));
1350:   PetscCall(PetscObjectCompose((PetscObject)pc->pmat, "_PCHPDDM_SubMatrices", nullptr));
1351:   PetscFunctionReturn(PETSC_SUCCESS);
1352: }

1354: static PetscErrorCode PCHPDDMPermute_Private(IS is, IS in_is, IS *out_is, Mat in_C, Mat *out_C, IS *p)
1355: {
1356:   IS                           perm;
1357:   const PetscInt              *ptr;
1358:   PetscInt                    *compressed, size, bs;
1359:   std::map<PetscInt, PetscInt> order;
1360:   PetscBool                    flg;

1362:   PetscFunctionBegin;
1365:   PetscCall(ISGetLocalSize(is, &size));
1366:   PetscCall(ISGetBlockSize(is, &bs));
1367:   PetscCall(ISSorted(is, &flg));
1368:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)in_C)));
1369:   if (!flg) {
1370:     PetscCall(ISGetIndices(is, &ptr));
1371:     /* MatCreateSubMatrices(), called by PCASM, follows the global numbering of Pmat */
1372:     for (PetscInt n = 0; n < size; n += bs) order.insert(std::make_pair(ptr[n] / bs, (in_C->rmap->rstart + n) / bs));
1373:     PetscCall(ISRestoreIndices(is, &ptr));
1374:     size /= bs;
1375:     if (out_C) {
1376:       PetscCall(PetscMalloc1(size, &compressed));
1377:       std::transform(order.cbegin(), order.cend(), compressed, [](const std::pair<const PetscInt, PetscInt> &i) { return i.second; });
1378:       PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_C), bs, size, compressed, PETSC_OWN_POINTER, &perm));
1379:       PetscCall(ISSetPermutation(perm));
1380:       /* permute user-provided Mat so that it matches with MatCreateSubMatrices() numbering */
1381:       PetscCall(MatPermute(in_C, perm, perm, out_C));
1382:       if (p) *p = perm;
1383:       else PetscCall(ISDestroy(&perm)); /* no need to save the permutation */
1384:     }
1385:     if (out_is) {
1386:       PetscCall(PetscMalloc1(size, &compressed));
1387:       std::transform(order.cbegin(), order.cend(), compressed, [](const std::pair<const PetscInt, PetscInt> &i) { return i.first; });
1388:       /* permute user-provided IS so that it matches with MatCreateSubMatrices() numbering */
1389:       PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_is), bs, size, compressed, PETSC_OWN_POINTER, out_is));
1390:     }
1391:   } else { /* input IS is sorted, nothing to permute, simply duplicate inputs when needed */
1392:     if (out_C) PetscCall(MatDuplicate(in_C, MAT_COPY_VALUES, out_C));
1393:     if (out_is) {
1394:       PetscCall(PetscObjectTypeCompare((PetscObject)in_is, ISBLOCK, &flg));
1395:       if (flg) PetscCall(ISDuplicate(in_is, out_is));
1396:       else {
1397:         PetscCall(ISGetIndices(is, &ptr));
1398:         if (bs > 1) {
1399:           size /= bs;
1400:           PetscCall(PetscMalloc1(size, &compressed));
1401:           for (PetscInt n = 0; n < size; ++n) compressed[n] = ptr[static_cast<PetscCount>(n) * bs] / bs;
1402:           PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_is), bs, size, compressed, PETSC_OWN_POINTER, out_is));
1403:         } else PetscCall(ISCreateBlock(PetscObjectComm((PetscObject)in_is), 1, size, ptr, PETSC_COPY_VALUES, out_is));
1404:         PetscCall(ISRestoreIndices(is, &ptr));
1405:         PetscCall(ISSetInfo(*out_is, IS_SORTED, IS_LOCAL, PETSC_TRUE, PETSC_TRUE));
1406:       }
1407:     }
1408:   }
1409:   PetscFunctionReturn(PETSC_SUCCESS);
1410: }

1412: static PetscErrorCode PCHPDDMCheckSymmetry_Private(PC pc, Mat A01, Mat A10, Mat *B01 = nullptr)
1413: {
1414:   Mat       T, U = nullptr, B = nullptr;
1415:   IS        z;
1416:   PetscBool flg, conjugate = PETSC_FALSE;

1418:   PetscFunctionBegin;
1419:   PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
1420:   if (B01) *B01 = nullptr;
1421:   if (flg) {
1422:     PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1423:     PetscCall(MatTransposeGetMat(A10, &U));
1424:   } else {
1425:     PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
1426:     if (flg) {
1427:       PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1428:       PetscCall(MatHermitianTransposeGetMat(A10, &U));
1429:       conjugate = PETSC_TRUE;
1430:     }
1431:   }
1432:   if (U) PetscCall(MatDuplicate(U, MAT_COPY_VALUES, &T));
1433:   else PetscCall(MatHermitianTranspose(A10, MAT_INITIAL_MATRIX, &T));
1434:   PetscCall(PetscObjectTypeCompare((PetscObject)A01, MATTRANSPOSEVIRTUAL, &flg));
1435:   if (flg) {
1436:     PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1437:     PetscCall(MatTransposeGetMat(A01, &A01));
1438:     PetscCall(MatTranspose(A01, MAT_INITIAL_MATRIX, &B));
1439:     A01 = B;
1440:   } else {
1441:     PetscCall(PetscObjectTypeCompare((PetscObject)A01, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
1442:     if (flg) {
1443:       PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
1444:       PetscCall(MatHermitianTransposeGetMat(A01, &A01));
1445:       PetscCall(MatHermitianTranspose(A01, MAT_INITIAL_MATRIX, &B));
1446:       A01 = B;
1447:     }
1448:   }
1449:   PetscCall(PetscLayoutCompare(T->rmap, A01->rmap, &flg));
1450:   if (flg) {
1451:     PetscCall(PetscLayoutCompare(T->cmap, A01->cmap, &flg));
1452:     if (flg) {
1453:       PetscCall(MatFindZeroRows(A01, &z)); /* for essential boundary conditions, some implementations will */
1454:       if (z) {                             /*  zero rows in [P00 A01] except for the diagonal of P00       */
1455:         if (B01) PetscCall(MatDuplicate(T, MAT_COPY_VALUES, B01));
1456:         PetscCall(MatSetOption(T, MAT_NO_OFF_PROC_ZERO_ROWS, PETSC_TRUE));
1457:         PetscCall(MatZeroRowsIS(T, z, 0.0, nullptr, nullptr)); /* corresponding zero rows from A01 */
1458:       }
1459:       PetscCall(MatMultEqual(A01, T, 20, &flg));
1460:       if (!B01) PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "A01 != A10^T");
1461:       else {
1462:         PetscCall(PetscInfo(pc, "A01 and A10^T are equal? %s\n", PetscBools[flg]));
1463:         if (!flg) {
1464:           if (z) PetscCall(MatDestroy(&T));
1465:           else *B01 = T;
1466:           flg = PETSC_TRUE;
1467:         } else PetscCall(MatDestroy(B01));
1468:       }
1469:       PetscCall(ISDestroy(&z));
1470:     }
1471:   }
1472:   if (!flg) PetscCall(PetscInfo(pc, "A01 and A10^T have non-congruent layouts, cannot test for equality\n"));
1473:   if (!B01 || !*B01) PetscCall(MatDestroy(&T));
1474:   else if (conjugate) PetscCall(MatConjugate(T));
1475:   PetscCall(MatDestroy(&B));
1476:   PetscFunctionReturn(PETSC_SUCCESS);
1477: }

1479: static PetscErrorCode PCHPDDMCheckInclusion_Private(PC pc, IS is, IS is_local, PetscBool check)
1480: {
1481:   IS          intersect;
1482:   const char *str = "IS of the auxiliary Mat does not include all local rows of A";
1483:   PetscBool   equal;

1485:   PetscFunctionBegin;
1486:   PetscCall(ISIntersect(is, is_local, &intersect));
1487:   PetscCall(ISEqualUnsorted(is_local, intersect, &equal));
1488:   PetscCall(ISDestroy(&intersect));
1489:   if (check) PetscCheck(equal, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", str);
1490:   else if (!equal) PetscCall(PetscInfo(pc, "%s\n", str));
1491:   PetscFunctionReturn(PETSC_SUCCESS);
1492: }

1494: static PetscErrorCode PCHPDDMCheckMatStructure_Private(PC pc, Mat A, Mat B)
1495: {
1496:   Mat             X, Y;
1497:   const PetscInt *j[2];
1498:   PetscInt        m[2], n[2];
1499:   PetscBool       flg = PETSC_TRUE;

1501:   PetscFunctionBegin;
1502:   PetscCall(MatConvert(A, MATAIJ, MAT_INITIAL_MATRIX, &X)); /* no common way to compare sparsity pattern, so just convert to MATAIJ */
1503:   PetscCall(MatConvert(B, MATAIJ, MAT_INITIAL_MATRIX, &Y)); /* the second Mat (B = Neumann) should have a SUBSET_NONZERO_PATTERN MatStructure of the first one (A = Dirichlet) */
1504:   PetscCall(MatGetOwnershipRange(X, m, m + 1));
1505:   for (PetscInt row = m[0]; row < m[1] && flg; ++row) {
1506:     PetscCall(MatGetRow(X, row, n, j, nullptr));
1507:     PetscCall(MatGetRow(Y, row, n + 1, j + 1, nullptr));

1509:     for (PetscInt k = 0, location; k < n[1]; ++k) {
1510:       PetscCall(PetscFindInt(j[1][k], n[0], j[0], &location));
1511:       if (location < 0) {
1512:         flg = PETSC_FALSE;
1513:         break;
1514:       }
1515:     }
1516:     PetscCall(MatRestoreRow(Y, row, n + 1, j + 1, nullptr));
1517:     PetscCall(MatRestoreRow(X, row, n, j, nullptr));
1518:   }
1519:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LAND, PetscObjectComm((PetscObject)pc)));
1520:   PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_USER_INPUT, "Auxiliary Mat is supposedly the local Neumann matrix but it has a sparsity pattern which is not a subset of the one of the local assembled matrix");
1521:   PetscCall(MatDestroy(&Y));
1522:   PetscCall(MatDestroy(&X));
1523:   PetscFunctionReturn(PETSC_SUCCESS);
1524: }

1526: static PetscErrorCode PCHPDDMDestroySubMatrices_Private(PetscBool flg, PetscBool algebraic, Mat *sub)
1527: {
1528:   IS is;

1530:   PetscFunctionBegin;
1531:   if (!flg) {
1532:     if (algebraic) {
1533:       PetscCall(PetscObjectQuery((PetscObject)sub[0], "_PCHPDDM_Embed", (PetscObject *)&is));
1534:       PetscCall(ISDestroy(&is));
1535:       PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Embed", nullptr));
1536:       PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Compact", nullptr));
1537:     }
1538:     PetscCall(MatDestroySubMatrices(algebraic ? 2 : 1, &sub));
1539:   }
1540:   PetscFunctionReturn(PETSC_SUCCESS);
1541: }

1543: static PetscErrorCode PCHPDDMAlgebraicAuxiliaryMat_Private(Mat Q, IS *is, Mat *sub[], PetscBool block)
1544: {
1545:   IS         icol[3], irow[2];
1546:   Mat       *M;
1547:   Mat        P = Q;
1548:   PetscReal *ptr;
1549:   PetscInt  *idx, p = 0, bs = P->cmap->bs;
1550:   PetscBool  flg;

1552:   PetscFunctionBegin;
1553:   /* MatCreateSubMatrices_MPISBAIJ() may return a rectangular MATSEQSBAIJ containing only the explicitly stored upper-triangular entries */
1554:   /* of the selected rows. But the missing lower-triangular entries are needed by MatGetColumnNorms(), MatGetRowSum(), and MatMatMult()  */
1555:   PetscCall(PetscObjectTypeCompare((PetscObject)Q, MATMPISBAIJ, &flg));
1556:   if (flg) PetscCall(MatConvert(Q, MATBAIJ, MAT_INITIAL_MATRIX, &P));
1557:   PetscCall(ISCreateStride(PETSC_COMM_SELF, P->cmap->N, 0, 1, icol + 2));
1558:   PetscCall(ISSetBlockSize(icol[2], bs));
1559:   PetscCall(ISSetIdentity(icol[2]));
1560:   PetscCall(MatCreateSubMatrices(P, 1, is, icol + 2, MAT_INITIAL_MATRIX, &M));
1561:   if (flg) {
1562:     PetscCall(MatDestroy(&P));
1563:     P = Q; /* continue using the caller-owned (MATMPISBAIJ) matrix */
1564:   }
1565:   PetscCall(ISDestroy(icol + 2));
1566:   PetscCall(ISCreateStride(PETSC_COMM_SELF, M[0]->rmap->N, 0, 1, irow));
1567:   PetscCall(ISSetBlockSize(irow[0], bs));
1568:   PetscCall(ISSetIdentity(irow[0]));
1569:   if (!block) {
1570:     PetscCall(PetscMalloc2(P->cmap->N, &ptr, P->cmap->N / bs, &idx));
1571:     PetscCall(MatGetColumnNorms(M[0], NORM_INFINITY, ptr));
1572:     /* check for nonzero columns so that M[0] may be expressed in compact form */
1573:     for (PetscInt n = 0; n < P->cmap->N; n += bs) {
1574:       if (std::find_if(ptr + n, ptr + n + bs, [](PetscReal v) { return v > PETSC_MACHINE_EPSILON; }) != ptr + n + bs) idx[p++] = n / bs;
1575:     }
1576:     PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, p, idx, PETSC_USE_POINTER, icol + 1));
1577:     PetscCall(ISSetInfo(icol[1], IS_SORTED, IS_GLOBAL, PETSC_TRUE, PETSC_TRUE));
1578:     PetscCall(ISEmbed(*is, icol[1], PETSC_FALSE, icol + 2));
1579:     irow[1] = irow[0];
1580:     /* first Mat will be used in PCASM (if it is used as a PC on this level) and as the left-hand side of GenEO */
1581:     icol[0] = is[0];
1582:     PetscCall(MatCreateSubMatrices(M[0], 2, irow, icol, MAT_INITIAL_MATRIX, sub));
1583:     PetscCall(ISDestroy(icol + 1));
1584:     PetscCall(PetscFree2(ptr, idx));
1585:     PetscCall(MatPropagateSymmetryOptions(P, (*sub)[0]));
1586:     if (flg) PetscCall(MatConvert((*sub)[0], MATSBAIJ, MAT_INPLACE_MATRIX, sub[0]));
1587:     /* IS used to go back and forth between the augmented and the original local linear system, see eq. (3.4) of [2022b] */
1588:     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Embed", (PetscObject)icol[2]));
1589:     /* Mat used in eq. (3.1) of [2022b] */
1590:     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Compact", (PetscObject)(*sub)[1]));
1591:   } else {
1592:     Mat aux;

1594:     PetscCall(MatSetOption(M[0], MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
1595:     /* diagonal block of the overlapping rows */
1596:     PetscCall(MatCreateSubMatrices(M[0], 1, irow, is, MAT_INITIAL_MATRIX, sub));
1597:     PetscCall(MatPropagateSymmetryOptions(P, (*sub)[0]));
1598:     if (flg && bs == 1) PetscCall(MatConvert((*sub)[0], MATSBAIJ, MAT_INPLACE_MATRIX, sub[0]));
1599:     PetscCall(MatDuplicate((*sub)[0], MAT_COPY_VALUES, &aux));
1600:     aux->spd = PETSC_BOOL3_UNKNOWN; /* the auxiliary Mat need not be SPD */
1601:     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
1602:     if (bs == 1) { /* scalar case */
1603:       Vec sum[2];

1605:       PetscCall(MatCreateVecs(aux, sum, sum + 1));
1606:       PetscCall(MatGetRowSum(M[0], sum[0]));
1607:       PetscCall(MatGetRowSum(aux, sum[1]));
1608:       /* off-diagonal block row sum (full rows - diagonal block rows) */
1609:       PetscCall(VecAXPY(sum[0], -1.0, sum[1]));
1610:       /* subdomain matrix plus off-diagonal block row sum */
1611:       PetscCall(MatDiagonalSet(aux, sum[0], ADD_VALUES));
1612:       PetscCall(VecDestroy(sum));
1613:       PetscCall(VecDestroy(sum + 1));
1614:     } else { /* vectorial case */
1615:       /* TODO: missing MatGetValuesBlocked(), so the code below is     */
1616:       /* an extension of the scalar case for when bs > 1, but it could */
1617:       /* be more efficient by avoiding all these MatMatMult()          */
1618:       Mat          sum[2], ones;
1619:       PetscScalar *ptr;

1621:       aux->symmetry_eternal = PETSC_FALSE;
1622:       aux->symmetric        = PETSC_BOOL3_UNKNOWN;
1623:       aux->hermitian        = PETSC_BOOL3_UNKNOWN;
1624:       PetscCall(PetscCalloc1(M[0]->cmap->n * bs, &ptr));
1625:       PetscCall(MatCreateDense(PETSC_COMM_SELF, M[0]->cmap->n, bs, M[0]->cmap->n, bs, ptr, &ones));
1626:       for (PetscInt n = 0; n < M[0]->cmap->n; n += bs) {
1627:         for (p = 0; p < bs; ++p) ptr[n + p * (M[0]->cmap->n + 1)] = 1.0;
1628:       }
1629:       PetscCall(MatMatMult(M[0], ones, MAT_INITIAL_MATRIX, PETSC_CURRENT, sum));
1630:       PetscCall(MatDestroy(&ones));
1631:       PetscCall(MatCreateDense(PETSC_COMM_SELF, aux->cmap->n, bs, aux->cmap->n, bs, ptr, &ones));
1632:       PetscCall(MatDenseSetLDA(ones, M[0]->cmap->n));
1633:       PetscCall(MatMatMult(aux, ones, MAT_INITIAL_MATRIX, PETSC_CURRENT, sum + 1));
1634:       PetscCall(MatDestroy(&ones));
1635:       PetscCall(PetscFree(ptr));
1636:       /* off-diagonal block row sum (full rows - diagonal block rows) */
1637:       PetscCall(MatAXPY(sum[0], -1.0, sum[1], SAME_NONZERO_PATTERN));
1638:       PetscCall(MatDestroy(sum + 1));
1639:       /* re-order values to be consistent with MatSetValuesBlocked()           */
1640:       /* equivalent to MatTranspose() which does not truly handle              */
1641:       /* MAT_INPLACE_MATRIX in the rectangular case, as it calls PetscMalloc() */
1642:       PetscCall(MatDenseGetArrayWrite(sum[0], &ptr));
1643:       HPDDM::Wrapper<PetscScalar>::imatcopy<'T'>(bs, sum[0]->rmap->n, ptr, sum[0]->rmap->n, bs);
1644:       /* subdomain matrix plus off-diagonal block row sum */
1645:       for (PetscInt n = 0; n < aux->cmap->n / bs; ++n) PetscCall(MatSetValuesBlocked(aux, 1, &n, 1, &n, ptr + static_cast<PetscCount>(n) * bs * bs, ADD_VALUES));
1646:       PetscCall(MatAssemblyBegin(aux, MAT_FINAL_ASSEMBLY));
1647:       PetscCall(MatAssemblyEnd(aux, MAT_FINAL_ASSEMBLY));
1648:       PetscCall(MatDenseRestoreArrayWrite(sum[0], &ptr));
1649:       PetscCall(MatDestroy(sum));
1650:     }
1651:     PetscCall(MatSetOption(aux, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
1652:     /* left-hand side of GenEO, with the same sparsity pattern as PCASM subdomain solvers */
1653:     PetscCall(PetscObjectCompose((PetscObject)(*sub)[0], "_PCHPDDM_Neumann_Mat", (PetscObject)aux));
1654:   }
1655:   PetscCall(ISDestroy(irow));
1656:   PetscCall(MatDestroySubMatrices(1, &M));
1657:   PetscFunctionReturn(PETSC_SUCCESS);
1658: }

1660: static PetscErrorCode PCApply_Nest(PC pc, Vec x, Vec y)
1661: {
1662:   Mat                    A;
1663:   MatSolverType          type;
1664:   IS                     is[2];
1665:   PetscBool              flg;
1666:   std::pair<PC, Vec[2]> *p;

1668:   PetscFunctionBegin;
1669:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&p)));
1670:   if (p->second[0]) { /* in case of a centralized Schur complement, some processes may have no local operator */
1671:     PetscCall(PCGetOperators(p->first, &A, nullptr));
1672:     PetscCall(MatNestGetISs(A, is, nullptr));
1673:     PetscCall(PetscObjectTypeCompareAny((PetscObject)p->first, &flg, PCLU, PCCHOLESKY, ""));
1674:     if (flg) { /* partial solve currently only makes sense with exact factorizations */
1675:       PetscCall(PCFactorGetMatSolverType(p->first, &type));
1676:       PetscCall(PCFactorGetMatrix(p->first, &A));
1677:       if (A->schur) {
1678:         PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
1679:         if (flg) PetscCall(MatMumpsSetIcntl(A, 26, 1)); /* reduction/condensation phase followed by Schur complement solve */
1680:       } else flg = PETSC_FALSE;
1681:     }
1682:     PetscCall(VecISCopy(p->second[0], is[1], SCATTER_FORWARD, x)); /* assign the RHS associated to the Schur complement */
1683:     PetscCall(PCApply(p->first, p->second[0], p->second[1]));
1684:     PetscCall(VecISCopy(p->second[1], is[1], SCATTER_REVERSE, y)); /* retrieve the partial solution associated to the Schur complement */
1685:     if (flg) PetscCall(MatMumpsSetIcntl(A, 26, -1));               /* default ICNTL(26) value in PETSc */
1686:   }
1687:   PetscFunctionReturn(PETSC_SUCCESS);
1688: }

1690: static PetscErrorCode PCView_Nest(PC pc, PetscViewer viewer)
1691: {
1692:   std::pair<PC, Vec[2]> *p;

1694:   PetscFunctionBegin;
1695:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&p)));
1696:   PetscCall(PCView(p->first, viewer));
1697:   PetscFunctionReturn(PETSC_SUCCESS);
1698: }

1700: static PetscErrorCode PCDestroy_Nest(PC pc)
1701: {
1702:   std::pair<PC, Vec[2]> *p;

1704:   PetscFunctionBegin;
1705:   PetscCall(PCShellGetContext(pc, static_cast<void *>(&p)));
1706:   PetscCall(VecDestroy(p->second));
1707:   PetscCall(VecDestroy(p->second + 1));
1708:   PetscCall(PCDestroy(&p->first));
1709:   PetscCall(PetscFree(p));
1710:   PetscFunctionReturn(PETSC_SUCCESS);
1711: }

1713: template <bool T = false>
1714: static PetscErrorCode MatMult_Schur(Mat A, Vec x, Vec y)
1715: {
1716:   std::tuple<Mat, PetscSF, Vec[2]> *ctx;

1718:   PetscFunctionBegin;
1719:   PetscCall(MatShellGetContext(A, static_cast<void *>(&ctx)));
1720:   PetscCall(VecScatterBegin(std::get<1>(*ctx), x, std::get<2>(*ctx)[0], INSERT_VALUES, SCATTER_FORWARD)); /* local Vec with overlap */
1721:   PetscCall(VecScatterEnd(std::get<1>(*ctx), x, std::get<2>(*ctx)[0], INSERT_VALUES, SCATTER_FORWARD));
1722:   if (!T) PetscCall(MatMult(std::get<0>(*ctx), std::get<2>(*ctx)[0], std::get<2>(*ctx)[1])); /* local Schur complement */
1723:   else PetscCall(MatMultTranspose(std::get<0>(*ctx), std::get<2>(*ctx)[0], std::get<2>(*ctx)[1]));
1724:   PetscCall(VecSet(y, 0.0));
1725:   PetscCall(VecScatterBegin(std::get<1>(*ctx), std::get<2>(*ctx)[1], y, ADD_VALUES, SCATTER_REVERSE)); /* global Vec with summed up contributions on the overlap */
1726:   PetscCall(VecScatterEnd(std::get<1>(*ctx), std::get<2>(*ctx)[1], y, ADD_VALUES, SCATTER_REVERSE));
1727:   PetscFunctionReturn(PETSC_SUCCESS);
1728: }

1730: static PetscErrorCode MatDestroy_Schur(Mat A)
1731: {
1732:   std::tuple<Mat, PetscSF, Vec[2]> *ctx;

1734:   PetscFunctionBegin;
1735:   PetscCall(MatShellGetContext(A, static_cast<void *>(&ctx)));
1736:   PetscCall(VecDestroy(std::get<2>(*ctx)));
1737:   PetscCall(VecDestroy(std::get<2>(*ctx) + 1));
1738:   PetscCall(PetscFree(ctx));
1739:   PetscFunctionReturn(PETSC_SUCCESS);
1740: }

1742: static PetscErrorCode MatMult_SchurCorrection(Mat A, Vec x, Vec y)
1743: {
1744:   PC                                         pc;
1745:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;

1747:   PetscFunctionBegin;
1748:   PetscCall(MatShellGetContext(A, static_cast<void *>(&ctx)));
1749:   pc = static_cast<PC_HPDDM *>(std::get<0>(*ctx)[0]->data)->levels[0]->ksp->pc;
1750:   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {             /* Q_0 is the coarse correction associated to the A00 block from PCFIELDSPLIT */
1751:     PetscCall(MatMult(std::get<1>(*ctx)[0], x, std::get<3>(*ctx)[1]));                    /*     A_01 x                 */
1752:     PetscCall(PCHPDDMDeflate_Private(pc, std::get<3>(*ctx)[1], std::get<3>(*ctx)[1]));    /*     Q_0 A_01 x             */
1753:     PetscCall(MatMult(std::get<1>(*ctx)[1], std::get<3>(*ctx)[1], std::get<3>(*ctx)[0])); /*     A_10 Q_0 A_01 x        */
1754:     PetscCall(PCApply(std::get<0>(*ctx)[1], std::get<3>(*ctx)[0], y));                    /* y = M_S^-1 A_10 Q_0 A_01 x */
1755:   } else {
1756:     PetscCall(PCApply(std::get<0>(*ctx)[1], x, std::get<3>(*ctx)[0]));                    /*     M_S^-1 x               */
1757:     PetscCall(MatMult(std::get<1>(*ctx)[0], std::get<3>(*ctx)[0], std::get<3>(*ctx)[1])); /*     A_01 M_S^-1 x          */
1758:     PetscCall(PCHPDDMDeflate_Private(pc, std::get<3>(*ctx)[1], std::get<3>(*ctx)[1]));    /*     Q_0 A_01 M_S^-1 x      */
1759:     PetscCall(MatMult(std::get<1>(*ctx)[1], std::get<3>(*ctx)[1], y));                    /* y = A_10 Q_0 A_01 M_S^-1 x */
1760:   }
1761:   PetscCall(VecAXPY(y, -1.0, x)); /* y -= x, preconditioned eq. (24) of https://hal.science/hal-02343808v6/document (with a sign flip) */
1762:   PetscFunctionReturn(PETSC_SUCCESS);
1763: }

1765: static PetscErrorCode MatView_SchurCorrection(Mat A, PetscViewer viewer)
1766: {
1767:   PetscBool                                  ascii;
1768:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;

1770:   PetscFunctionBegin;
1771:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &ascii));
1772:   if (ascii) {
1773:     PetscCall(MatShellGetContext(A, static_cast<void *>(&ctx)));
1774:     PetscCall(PetscViewerASCIIPrintf(viewer, "action of %s\n", std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT ? "(I - M_S^-1 A_10 Q_0 A_01)" : "(I - A_10 Q_0 A_01 M_S^-1)"));
1775:     PetscCall(PCView(std::get<0>(*ctx)[1], viewer)); /* no need to PCView(Q_0) since it will be done by PCFIELDSPLIT */
1776:   }
1777:   PetscFunctionReturn(PETSC_SUCCESS);
1778: }

1780: static PetscErrorCode MatDestroy_SchurCorrection(Mat A)
1781: {
1782:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx;

1784:   PetscFunctionBegin;
1785:   PetscCall(MatShellGetContext(A, static_cast<void *>(&ctx)));
1786:   PetscCall(VecDestroy(std::get<3>(*ctx)));
1787:   PetscCall(VecDestroy(std::get<3>(*ctx) + 1));
1788:   PetscCall(VecDestroy(std::get<3>(*ctx) + 2));
1789:   PetscCall(PCDestroy(std::get<0>(*ctx) + 1));
1790:   PetscCall(PetscFree(ctx));
1791:   PetscFunctionReturn(PETSC_SUCCESS);
1792: }

1794: static PetscErrorCode PCPostSolve_SchurPreLeastSquares(PC, KSP, Vec, Vec x)
1795: {
1796:   PetscFunctionBegin;
1797:   PetscCall(VecScale(x, -1.0));
1798:   PetscFunctionReturn(PETSC_SUCCESS);
1799: }

1801: static PetscErrorCode KSPPreSolve_SchurCorrection(KSP, Vec b, Vec, void *context)
1802: {
1803:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = reinterpret_cast<std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *>(context);

1805:   PetscFunctionBegin;
1806:   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {
1807:     PetscCall(PCApply(std::get<0>(*ctx)[1], b, std::get<3>(*ctx)[2]));
1808:     std::swap(*b, *std::get<3>(*ctx)[2]); /* replace b by M^-1 b, but need to keep a copy of the original RHS, so swap it with the work Vec */
1809:   }
1810:   PetscFunctionReturn(PETSC_SUCCESS);
1811: }

1813: static PetscErrorCode KSPPostSolve_SchurCorrection(KSP, Vec b, Vec x, void *context)
1814: {
1815:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = reinterpret_cast<std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *>(context);

1817:   PetscFunctionBegin;
1818:   if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) std::swap(*b, *std::get<3>(*ctx)[2]); /* put back the original RHS where it belongs */
1819:   else {
1820:     PetscCall(PCApply(std::get<0>(*ctx)[1], x, std::get<3>(*ctx)[2]));
1821:     PetscCall(VecCopy(std::get<3>(*ctx)[2], x)); /* replace x by M^-1 x */
1822:   }
1823:   PetscFunctionReturn(PETSC_SUCCESS);
1824: }

1826: static PetscErrorCode MatMult_Harmonic(Mat, Vec, Vec);
1827: static PetscErrorCode MatMultTranspose_Harmonic(Mat, Vec, Vec);
1828: static PetscErrorCode MatProduct_AB_Harmonic(Mat, Mat, Mat, void *);
1829: static PetscErrorCode MatProduct_AtB_Harmonic(Mat, Mat, Mat, void *);
1830: static PetscErrorCode MatDestroy_Harmonic(Mat);

1832: static PetscErrorCode PCHPDDMComputeScaling_Private(PC_HPDDM *data, IS is, Vec scaling)
1833: {
1834:   IS       perm;
1835:   PetscInt n, m;

1837:   PetscFunctionBegin;
1838:   PetscCall(ISGetLocalSize(is, &n));
1839:   PetscCall(VecGetSize(data->scaling, &m));
1840:   PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Overlapping subdomain size differs from the supplied scaling vector size");
1841:   PetscCall(ISEmbed(is, data->is, PETSC_TRUE, &perm));
1842:   PetscCall(ISGetLocalSize(perm, &m));
1843:   PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Expected all %" PetscInt_FMT " overlapping subdomain indices to be in the IS supplied to PCHPDDMSetScaling() or PCHPDDMSetDeflationMat(), but only %" PetscInt_FMT " were found", n, m);
1844:   PetscCall(VecISCopy(data->scaling, perm, SCATTER_REVERSE, scaling));
1845:   PetscCall(ISDestroy(&perm));
1846:   PetscFunctionReturn(PETSC_SUCCESS);
1847: }

1849: static PetscErrorCode PCSetUp_HPDDM(PC pc)
1850: {
1851:   PC_HPDDM                                  *data = (PC_HPDDM *)pc->data;
1852:   PC                                         inner;
1853:   KSP                                       *ksp = nullptr;
1854:   Mat                                       *sub, A, P, N, C = nullptr, uaux = nullptr, weighted, subA[2], S, ev, daux = nullptr;
1855:   Vec                                        xin, v;
1856:   std::vector<Vec>                           initial;
1857:   IS                                         is[1], loc, uis = data->is, unsorted = nullptr, dis = nullptr;
1858:   ISLocalToGlobalMapping                     l2g;
1859:   char                                       prefix[256];
1860:   const char                                *pcpre;
1861:   PetscInt                                   n, requested, reused = 0, overlap = -1;
1862:   MatStructure                               structure  = UNKNOWN_NONZERO_PATTERN;
1863:   PetscBool                                  subdomains = PETSC_FALSE, flg = PETSC_FALSE, ismatis, swap = PETSC_FALSE, algebraic = PETSC_FALSE, block = PETSC_FALSE;
1864:   DM                                         dm;
1865:   std::tuple<PC[2], Mat[2], PCSide, Vec[3]> *ctx = nullptr;

1867:   PetscFunctionBegin;
1868:   if (!data->levels) PetscCall(PetscInfo(pc, "No level allocated, defaulting to a single level, PCSetFromOptions() should be called before PCSetUp() to avoid this\n"));
1869:   PetscCall(PCHPDDMInitializeLevels_Private(data));
1870:   requested = data->N;
1871:   PetscCall(PCGetOptionsPrefix(pc, &pcpre));
1872:   PetscCall(PCGetOperators(pc, &A, &P));
1873:   if (data->scaling) {
1874:     PetscCheck(data->is, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "User-supplied scaling requires an IS, passed to PCHPDDMSetScaling() or PCHPDDMSetDeflationMat()");
1875:     if (data->deflation) {
1876:       PetscCheck(data->N == 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling with a deflation space requires exactly two levels");
1877:       PetscCall(MatGetSize(data->aux, nullptr, &n));
1878:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &n, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc)));
1879:       PetscCheck(n > 0, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling with a deflation space requires at least one deflation vector globally");
1880:     } else PetscCheck(data->N == 1, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling without a deflation space only applies to the fine level, use a single level");
1881:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)P, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
1882:     PetscCheck(flg, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling requires an assembled MATAIJ, MATBAIJ, or MATSBAIJ PMat");
1883:     PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, pcpre, "-pc_hpddm_define_subdomains", &subdomains, nullptr));
1884:     PetscCheck(subdomains, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling requires -%spc_hpddm_define_subdomains true", pcpre ? pcpre : "");
1885:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_%s_", pcpre ? pcpre : "", data->N > 1 ? "levels_1" : "coarse"));
1886:     n = 0;
1887:     PetscCall(PetscOptionsGetInt(((PetscObject)pc)->options, prefix, "-pc_asm_overlap", &n, nullptr));
1888:     PetscCheck(n <= 0, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling requires the overlap of the supplied IS; -%spc_asm_overlap cannot expand it", prefix);
1889:     PetscCall(PetscOptionsGetInt(((PetscObject)pc)->options, pcpre, "-pc_hpddm_harmonic_overlap", &overlap, nullptr));
1890:     PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, pcpre, "-pc_hpddm_block_splitting", &block, nullptr));
1891:     PetscCheck(overlap == -1 && !block && !PetscBool3ToBool(data->Neumann), PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling cannot be combined with -%spc_hpddm_harmonic_overlap, -%spc_hpddm_block_splitting, or Neumann auxiliary problems", pcpre ? pcpre : "", pcpre ? pcpre : "");
1892:   }
1893:   if (!data->levels[0]->ksp) {
1894:     PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->ksp));
1895:     PetscCall(KSPSetNestLevel(data->levels[0]->ksp, pc->kspnestlevel));
1896:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_%s_", pcpre ? pcpre : "", data->N > 1 ? "levels_1" : "coarse"));
1897:     PetscCall(KSPSetOptionsPrefix(data->levels[0]->ksp, prefix));
1898:     PetscCall(KSPSetType(data->levels[0]->ksp, KSPPREONLY));
1899:   } else if (data->levels[0]->ksp->pc && data->levels[0]->ksp->pc->setupcalled && data->levels[0]->ksp->pc->reusepreconditioner) {
1900:     /* if the fine-level PCSHELL exists, its setup has succeeded, and one wants to reuse it, */
1901:     /* then just propagate the appropriate flag to the coarser levels                        */
1902:     for (n = 0; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
1903:       /* the following KSP and PC may be NULL for some processes, hence the check            */
1904:       if (data->levels[n]->ksp) PetscCall(KSPSetReusePreconditioner(data->levels[n]->ksp, PETSC_TRUE));
1905:       if (data->levels[n]->pc) PetscCall(PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE));
1906:     }
1907:     /* early bail out because there is nothing to do */
1908:     PetscFunctionReturn(PETSC_SUCCESS);
1909:   } else {
1910:     /* reset coarser levels */
1911:     for (n = 1; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
1912:       if (data->levels[n]->ksp && data->levels[n]->ksp->pc && data->levels[n]->ksp->pc->setupcalled && data->levels[n]->ksp->pc->reusepreconditioner && n < data->N) {
1913:         reused = data->N - n;
1914:         break;
1915:       }
1916:       PetscCall(KSPDestroy(&data->levels[n]->ksp));
1917:       PetscCall(PCDestroy(&data->levels[n]->pc));
1918:     }
1919:     /* check if some coarser levels are being reused */
1920:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &reused, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc)));
1921:     const int *addr = data->levels[0]->P ? data->levels[0]->P->getAddrLocal() : &i_0;

1923:     if (!data->deflation && *addr != 0 && reused != data->N - 1) {
1924:       /* reuse previously computed eigenvectors */
1925:       ev = data->levels[0]->P->getMat();
1926:       if (ev) {
1927:         initial.reserve(*addr);
1928:         for (n = 0; n < *addr; ++n) {
1929:           PetscCall(MatDenseGetColumnVecRead(ev, n, &xin));
1930:           PetscCall(VecDuplicate(xin, &v));
1931:           PetscCall(VecCopy(xin, v));
1932:           initial.emplace_back(v);
1933:           PetscCall(MatDenseRestoreColumnVecRead(ev, n, &xin));
1934:         }
1935:       }
1936:     }
1937:   }
1938:   data->N -= reused;
1939:   PetscCall(KSPSetOperators(data->levels[0]->ksp, A, P));

1941:   PetscCall(PetscObjectTypeCompare((PetscObject)P, MATIS, &ismatis));
1942:   if (!data->is && !ismatis) {
1943:     PetscErrorCode (*create)(DM, IS *, Mat *, PetscErrorCode (**)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *), void **) = nullptr;
1944:     PetscErrorCode (*usetup)(Mat, PetscReal, Vec, Vec, PetscReal, IS, void *)                                                = nullptr;
1945:     void *uctx                                                                                                               = nullptr;

1947:     /* first see if we can get the data from the DM */
1948:     PetscCall(MatGetDM(P, &dm));
1949:     if (!dm) PetscCall(MatGetDM(A, &dm));
1950:     if (!dm) PetscCall(PCGetDM(pc, &dm));
1951:     if (dm) { /* this is the hook for DMPLEX for which the auxiliary Mat is the local Neumann matrix */
1952:       PetscCall(PetscObjectQueryFunction((PetscObject)dm, "DMCreateNeumannOverlap_C", &create));
1953:       if (create) {
1954:         PetscCall((*create)(dm, &uis, &uaux, &usetup, &uctx));
1955:         if (data->Neumann == PETSC_BOOL3_UNKNOWN) data->Neumann = PETSC_BOOL3_TRUE; /* set the value only if it was not already provided by the user */
1956:       }
1957:     }
1958:     if (!create) {
1959:       if (!uis) {
1960:         PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_IS", (PetscObject *)&uis));
1961:         PetscCall(PetscObjectReference((PetscObject)uis));
1962:       }
1963:       if (!uaux) {
1964:         PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Neumann_Mat", (PetscObject *)&uaux));
1965:         PetscCall(PetscObjectReference((PetscObject)uaux));
1966:       }
1967:       /* look inside the Pmat instead of the PC, needed for MatSchurComplementComputeExplicitOperator() */
1968:       if (!uis) {
1969:         PetscCall(PetscObjectQuery((PetscObject)P, "_PCHPDDM_Neumann_IS", (PetscObject *)&uis));
1970:         PetscCall(PetscObjectReference((PetscObject)uis));
1971:       }
1972:       if (!uaux) {
1973:         PetscCall(PetscObjectQuery((PetscObject)P, "_PCHPDDM_Neumann_Mat", (PetscObject *)&uaux));
1974:         PetscCall(PetscObjectReference((PetscObject)uaux));
1975:       }
1976:     }
1977:     PetscCall(PCHPDDMSetAuxiliaryMat(pc, uis, uaux, usetup, uctx));
1978:     PetscCall(MatDestroy(&uaux));
1979:     PetscCall(ISDestroy(&uis));
1980:   }

1982:   if (!ismatis) {
1983:     PetscCall(PCHPDDMSetUpNeumannOverlap_Private(pc));
1984:     PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, pcpre, "-pc_hpddm_block_splitting", &block, nullptr));
1985:     PetscCall(PetscOptionsGetInt(((PetscObject)pc)->options, pcpre, "-pc_hpddm_harmonic_overlap", &overlap, nullptr));
1986:     {
1987:       char type[256] = {}; /* same size as in src/ksp/pc/interface/pcset.c */

1989:       PetscCall(PetscOptionsGetString(((PetscObject)pc)->options, pcpre, "-pc_hpddm_levels_1_st_pc_type", type, sizeof(type), nullptr));
1990:       PetscCall(PetscStrcmp(type, PCMAT, &algebraic));
1991:     }
1992:     PetscCheck(!algebraic || !block, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_levels_1_st_pc_type mat and -%spc_hpddm_block_splitting", pcpre ? pcpre : "", pcpre ? pcpre : "");
1993:     if (overlap != -1) {
1994:       PetscCheck(!block && !algebraic, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_%s and -%spc_hpddm_harmonic_overlap", pcpre ? pcpre : "", block ? "block_splitting" : "levels_1_st_pc_type mat", pcpre ? pcpre : "");
1995:       PetscCheck(overlap >= 1, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_WRONG, "-%spc_hpddm_harmonic_overlap %" PetscInt_FMT " < 1", pcpre ? pcpre : "", overlap);
1996:     }
1997:     if (block || overlap != -1) algebraic = PETSC_TRUE;
1998:     PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
1999:     if (data->is || flg) {
2000:       if (algebraic) {
2001:         if (!reused || data->N > 1) {
2002:           PetscCall(ISDestroy(&data->is));
2003:           PetscCall(MatDestroy(&data->aux));
2004:         }
2005:       } else if (flg) {
2006:         PCHPDDMSchurPreType type = PC_HPDDM_SCHUR_PRE_GENEO;

2008:         PetscCall(PetscOptionsGetEnum(((PetscObject)pc)->options, pcpre, "-pc_hpddm_schur_precondition", PCHPDDMSchurPreTypes, (PetscEnum *)&type, &flg));
2009:         if (type == PC_HPDDM_SCHUR_PRE_LEAST_SQUARES) {
2010:           PetscCall(ISDestroy(&data->is)); /* destroy any previously user-set objects since they will be set automatically */
2011:           PetscCall(MatDestroy(&data->aux));
2012:         } else if (type == PC_HPDDM_SCHUR_PRE_GENEO) {
2013:           PetscContainer container = nullptr;

2015:           PetscCall(PetscObjectQuery((PetscObject)pc, "_PCHPDDM_Schur", (PetscObject *)&container));
2016:           if (!container) { /* first call to PCSetUp() on the PC associated to the Schur complement */
2017:             PC_HPDDM       *data_00;
2018:             KSP             ksp, inner_ksp;
2019:             PC              pc_00;
2020:             Mat             A11;
2021:             Vec             d = nullptr;
2022:             PetscReal       norm;
2023:             const PetscInt *ranges;
2024:             PetscMPIInt     size;
2025:             char           *prefix;

2027:             PetscCall(MatSchurComplementGetKSP(P, &ksp));
2028:             PetscCall(KSPGetPC(ksp, &pc_00));
2029:             PetscCall(PetscObjectTypeCompare((PetscObject)pc_00, PCHPDDM, &flg));
2030:             PetscCheck(flg, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and -%spc_type %s (!= %s)", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], ((PetscObject)pc_00)->prefix ? ((PetscObject)pc_00)->prefix : "",
2031:                        ((PetscObject)pc_00)->type_name, PCHPDDM);
2032:             data_00 = static_cast<PC_HPDDM *>(pc_00->data);
2033:             PetscCheck(data_00->N == 2, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and %" PetscInt_FMT " level%s instead of 2 for the A00 block -%s", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type],
2034:                        data_00->N, data_00->N > 1 ? "s" : "", ((PetscObject)pc_00)->prefix);
2035:             PetscCheck(data_00->levels[0]->pc, PetscObjectComm((PetscObject)P), PETSC_ERR_ORDER, "PC of the first block%s not setup yet", ((PetscObject)pc_00)->prefix ? std::string(std::string(" (") + ((PetscObject)pc_00)->prefix + std::string(")")).c_str() : "");
2036:             PetscCall(PetscObjectTypeCompare((PetscObject)data_00->levels[0]->pc, PCASM, &flg));
2037:             PetscCheck(flg, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s and -%spc_type %s (!= %s)", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], ((PetscObject)data_00->levels[0]->pc)->prefix,
2038:                        ((PetscObject)data_00->levels[0]->pc)->type_name, PCASM);
2039:             PetscCall(PetscNew(&ctx)); /* context to pass data around for the inner-most PC, which will be a proper PCHPDDM (or a dummy variable if the Schur complement is centralized on a single process)  */
2040:             PetscCall(MatSchurComplementGetSubMatrices(P, nullptr, nullptr, nullptr, nullptr, &A11));
2041:             PetscCall(MatGetOwnershipRanges(P, &ranges));
2042:             PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)P), &size));
2043:             flg = static_cast<PetscBool>(std::find_if(ranges, ranges + size + 1, [&](PetscInt v) { return v != ranges[0] && v != ranges[size]; }) == ranges + size + 1); /* are all local matrices but one of dimension 0 (centralized Schur complement)? */
2044:             if (!flg) {
2045:               if (PetscDefined(USE_DEBUG) || !data->is) {
2046:                 Mat A01, A10, B = nullptr, C = nullptr, *sub;

2048:                 PetscCall(MatSchurComplementGetSubMatrices(P, &A, nullptr, &A01, &A10, nullptr));
2049:                 PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
2050:                 if (flg) {
2051:                   PetscCall(MatTransposeGetMat(A10, &C));
2052:                   PetscCall(MatTranspose(C, MAT_INITIAL_MATRIX, &B));
2053:                 } else {
2054:                   PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
2055:                   if (flg) {
2056:                     PetscCall(MatHermitianTransposeGetMat(A10, &C));
2057:                     PetscCall(MatHermitianTranspose(C, MAT_INITIAL_MATRIX, &B));
2058:                   }
2059:                 }
2060:                 if (flg)
2061:                   PetscCall(MatShellGetScalingShifts(A10, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
2062:                 if (!B) {
2063:                   B = A10;
2064:                   PetscCall(PetscObjectReference((PetscObject)B));
2065:                 } else if (!data->is) {
2066:                   PetscCall(PetscObjectTypeCompareAny((PetscObject)A01, &flg, MATTRANSPOSEVIRTUAL, MATHERMITIANTRANSPOSEVIRTUAL, ""));
2067:                   if (!flg) C = A01;
2068:                   else
2069:                     PetscCall(MatShellGetScalingShifts(A01, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (PetscScalar *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Vec *)MAT_SHELL_NOT_ALLOWED, (Mat *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED, (IS *)MAT_SHELL_NOT_ALLOWED));
2070:                 }
2071:                 PetscCall(ISCreateStride(PETSC_COMM_SELF, B->rmap->N, 0, 1, &uis));
2072:                 PetscCall(ISSetIdentity(uis));
2073:                 if (!data->is) {
2074:                   if (!C) PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &C));
2075:                   else PetscCall(PetscObjectReference((PetscObject)C));
2076:                   PetscCall(ISDuplicate(data_00->is, is));
2077:                   PetscCall(MatIncreaseOverlap(A, 1, is, 1));
2078:                   PetscCall(MatSetOption(C, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
2079:                   PetscCall(MatCreateSubMatrices(C, 1, is, &uis, MAT_INITIAL_MATRIX, &sub));
2080:                   PetscCall(MatDestroy(&C));
2081:                   PetscCall(MatTranspose(sub[0], MAT_INITIAL_MATRIX, &C));
2082:                   PetscCall(MatDestroySubMatrices(1, &sub));
2083:                   PetscCall(MatFindNonzeroRows(C, &data->is));
2084:                   PetscCheck(data->is, PetscObjectComm((PetscObject)C), PETSC_ERR_SUP, "No empty row, which likely means that some rows of A_10 are dense");
2085:                   PetscCall(MatDestroy(&C));
2086:                   PetscCall(ISDestroy(is));
2087:                   PetscCall(ISCreateStride(PetscObjectComm((PetscObject)data->is), P->rmap->n, P->rmap->rstart, 1, &loc));
2088:                   if (PetscDefined(USE_DEBUG)) PetscCall(PCHPDDMCheckInclusion_Private(pc, data->is, loc, PETSC_FALSE));
2089:                   PetscCall(ISExpand(data->is, loc, is));
2090:                   PetscCall(ISDestroy(&loc));
2091:                   PetscCall(ISDestroy(&data->is));
2092:                   data->is = is[0];
2093:                   is[0]    = nullptr;
2094:                 }
2095:                 if (PetscDefined(USE_DEBUG)) {
2096:                   PetscCall(PCHPDDMCheckSymmetry_Private(pc, A01, A10));
2097:                   PetscCall(MatCreateSubMatrices(B, 1, &uis, &data_00->is, MAT_INITIAL_MATRIX, &sub)); /* expensive check since all processes fetch all rows (but only some columns) of the constraint matrix */
2098:                   PetscCall(ISDestroy(&uis));
2099:                   PetscCall(ISDuplicate(data->is, &uis));
2100:                   PetscCall(ISSort(uis));
2101:                   PetscCall(ISComplement(uis, 0, B->rmap->N, is));
2102:                   PetscCall(MatDuplicate(sub[0], MAT_COPY_VALUES, &C));
2103:                   PetscCall(MatZeroRowsIS(C, is[0], 0.0, nullptr, nullptr));
2104:                   PetscCall(ISDestroy(is));
2105:                   PetscCall(MatMultEqual(sub[0], C, 20, &flg));
2106:                   PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "The image of A_10 (R_i^p)^T from the local primal (e.g., velocity) space to the full dual (e.g., pressure) space is not restricted to the local dual space: A_10 (R_i^p)^T != R_i^d (R_i^d)^T A_10 (R_i^p)^T"); /* cf. eq. (9) of https://hal.science/hal-02343808v6/document */
2107:                   PetscCall(MatDestroy(&C));
2108:                   PetscCall(MatDestroySubMatrices(1, &sub));
2109:                 }
2110:                 PetscCall(ISDestroy(&uis));
2111:                 PetscCall(MatDestroy(&B));
2112:               }
2113:               flg = PETSC_FALSE;
2114:               if (!data->aux && A11) {
2115:                 Mat D;

2117:                 PetscCall(MatCreateVecs(A11, &d, nullptr));
2118:                 PetscCall(MatGetDiagonal(A11, d));
2119:                 PetscCall(PetscObjectTypeCompareAny((PetscObject)A11, &flg, MATDIAGONAL, MATCONSTANTDIAGONAL, ""));
2120:                 if (!flg) {
2121:                   PetscCall(MatCreateDiagonal(d, &D));
2122:                   PetscCall(MatMultEqual(A11, D, 20, &flg));
2123:                   PetscCall(MatDestroy(&D));
2124:                 }
2125:                 if (flg) PetscCall(PetscInfo(pc, "A11 block is likely diagonal so the PC will build an auxiliary Mat (which was not initially provided by the user)\n"));
2126:               }
2127:               if (PetscDefined(USE_DEBUG) || (data->Neumann != PETSC_BOOL3_TRUE && !flg)) {
2128:                 if (A11) PetscCall(MatNorm(A11, NORM_INFINITY, &norm));
2129:                 else norm = 0.0;
2130:                 if (data->Neumann != PETSC_BOOL3_TRUE && !flg) {
2131:                   PetscCheck(norm < PETSC_MACHINE_EPSILON * static_cast<PetscReal>(10.0), PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_has_neumann != true with a nonzero or non-diagonal A11 block", pcpre ? pcpre : "", pcpre ? pcpre : "");
2132:                   PetscCall(PetscInfo(pc, "A11 block is likely zero so the PC will build an auxiliary Mat (which was%s initially provided by the user)\n", data->aux ? "" : " not"));
2133:                   PetscCall(MatDestroy(&data->aux));
2134:                   flg = PETSC_TRUE;
2135:                 }
2136:               }
2137:               if (!data->aux) { /* if A11 is near zero, e.g., Stokes equation, or diagonal, build an auxiliary (Neumann) Mat which is a (possibly slightly shifted) diagonal weighted by the inverse of the multiplicity */
2138:                 PetscSF            scatter;
2139:                 const PetscScalar *read;
2140:                 PetscScalar       *write, *diagonal = nullptr;

2142:                 PetscCall(MatDestroy(&data->aux));
2143:                 PetscCall(ISGetLocalSize(data->is, &n));
2144:                 PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)P), n, PETSC_DECIDE, &xin));
2145:                 PetscCall(VecDuplicate(xin, &v));
2146:                 PetscCall(VecScatterCreate(xin, data->is, v, nullptr, &scatter));
2147:                 PetscCall(VecSet(v, 1.0));
2148:                 PetscCall(VecSet(xin, 1.0));
2149:                 PetscCall(VecScatterBegin(scatter, v, xin, ADD_VALUES, SCATTER_REVERSE));
2150:                 PetscCall(VecScatterEnd(scatter, v, xin, ADD_VALUES, SCATTER_REVERSE)); /* v has the multiplicity of all unknowns on the overlap */
2151:                 PetscCall(PetscSFDestroy(&scatter));
2152:                 if (d) {
2153:                   PetscCall(VecScatterCreate(d, data->is, v, nullptr, &scatter));
2154:                   PetscCall(VecScatterBegin(scatter, d, v, INSERT_VALUES, SCATTER_FORWARD));
2155:                   PetscCall(VecScatterEnd(scatter, d, v, INSERT_VALUES, SCATTER_FORWARD));
2156:                   PetscCall(PetscSFDestroy(&scatter));
2157:                   PetscCall(VecDestroy(&d));
2158:                   PetscCall(PetscMalloc1(n, &diagonal));
2159:                   PetscCall(VecGetArrayRead(v, &read));
2160:                   PetscCallCXX(std::copy_n(read, n, diagonal));
2161:                   PetscCall(VecRestoreArrayRead(v, &read));
2162:                 }
2163:                 PetscCall(VecDestroy(&v));
2164:                 PetscCall(VecCreateSeq(PETSC_COMM_SELF, n, &v));
2165:                 PetscCall(VecGetArrayRead(xin, &read));
2166:                 PetscCall(VecGetArrayWrite(v, &write));
2167:                 for (PetscInt i = 0; i < n; ++i) write[i] = (!diagonal || std::abs(diagonal[i]) < PETSC_MACHINE_EPSILON) ? PETSC_SMALL / (static_cast<PetscReal>(1000.0) * read[i]) : diagonal[i] / read[i];
2168:                 PetscCall(PetscFree(diagonal));
2169:                 PetscCall(VecRestoreArrayRead(xin, &read));
2170:                 PetscCall(VecRestoreArrayWrite(v, &write));
2171:                 PetscCall(VecDestroy(&xin));
2172:                 PetscCall(MatCreateDiagonal(v, &data->aux));
2173:                 PetscCall(VecDestroy(&v));
2174:               }
2175:               uis  = data->is;
2176:               uaux = data->aux;
2177:               PetscCall(PetscObjectReference((PetscObject)uis));
2178:               PetscCall(PetscObjectReference((PetscObject)uaux));
2179:               PetscCall(PetscStrallocpy(pcpre, &prefix));
2180:               PetscCall(PCSetOptionsPrefix(pc, nullptr));
2181:               PetscCall(PCSetType(pc, PCKSP));                                    /* replace the PC associated to the Schur complement by PCKSP */
2182:               PetscCall(KSPCreate(PetscObjectComm((PetscObject)pc), &inner_ksp)); /* new KSP that will be attached to the previously set PC */
2183:               PetscCall(PetscObjectGetTabLevel((PetscObject)pc, &n));
2184:               PetscCall(PetscObjectSetTabLevel((PetscObject)inner_ksp, n + 2));
2185:               PetscCall(KSPSetOperators(inner_ksp, pc->mat, pc->pmat));
2186:               PetscCall(KSPSetOptionsPrefix(inner_ksp, prefix));
2187:               PetscCall(KSPAppendOptionsPrefix(inner_ksp, "pc_hpddm_"));
2188:               PetscCall(KSPSetSkipPCSetFromOptions(inner_ksp, PETSC_TRUE));
2189:               PetscCall(KSPSetFromOptions(inner_ksp));
2190:               PetscCall(KSPGetPC(inner_ksp, &inner));
2191:               PetscCall(PCSetOptionsPrefix(inner, nullptr));
2192:               PetscCall(PCSetType(inner, PCNONE)); /* no preconditioner since the action of M^-1 A or A M^-1 will be computed by the Amat */
2193:               PetscCall(PCKSPSetKSP(pc, inner_ksp));
2194:               std::get<0>(*ctx)[0] = pc_00; /* for coarse correction on the primal (e.g., velocity) space */
2195:               PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &std::get<0>(*ctx)[1]));
2196:               PetscCall(PCSetOptionsPrefix(pc, prefix)); /* both PC share the same prefix so that the outer PC can be reset with PCSetFromOptions() */
2197:               PetscCall(PCSetOptionsPrefix(std::get<0>(*ctx)[1], prefix));
2198:               PetscCall(PetscFree(prefix));
2199:               PetscCall(PCSetOperators(std::get<0>(*ctx)[1], pc->mat, pc->pmat));
2200:               PetscCall(PCSetType(std::get<0>(*ctx)[1], PCHPDDM));
2201:               PetscCall(PCHPDDMSetAuxiliaryMat(std::get<0>(*ctx)[1], uis, uaux, nullptr, nullptr)); /* transfer ownership of the auxiliary inputs from the inner (PCKSP) to the inner-most (PCHPDDM) PC */
2202:               if (flg) static_cast<PC_HPDDM *>(std::get<0>(*ctx)[1]->data)->Neumann = PETSC_BOOL3_TRUE;
2203:               else if (PetscDefined(USE_DEBUG) && norm > PETSC_MACHINE_EPSILON * static_cast<PetscReal>(10.0)) {
2204:                 /* no check when A11 is near zero */
2205:                 PetscCall(MatCreateSubMatrices(A11, 1, &uis, &uis, MAT_INITIAL_MATRIX, &sub));
2206:                 PetscCall(PCHPDDMCheckMatStructure_Private(pc, sub[0], uaux));
2207:                 PetscCall(MatDestroySubMatrices(1, &sub));
2208:               }
2209:               PetscCall(PCSetFromOptions(std::get<0>(*ctx)[1]));
2210:               PetscCall(PetscObjectDereference((PetscObject)uis));
2211:               PetscCall(PetscObjectDereference((PetscObject)uaux));
2212:               PetscCall(MatCreateShell(PetscObjectComm((PetscObject)pc), inner->mat->rmap->n, inner->mat->cmap->n, inner->mat->rmap->N, inner->mat->cmap->N, ctx, &S)); /* MatShell computing the action of M^-1 A or A M^-1 */
2213:               PetscCall(MatShellSetOperation(S, MATOP_MULT, (PetscErrorCodeFn *)MatMult_SchurCorrection));
2214:               PetscCall(MatShellSetOperation(S, MATOP_VIEW, (PetscErrorCodeFn *)MatView_SchurCorrection));
2215:               PetscCall(MatShellSetOperation(S, MATOP_DESTROY, (PetscErrorCodeFn *)MatDestroy_SchurCorrection));
2216:               PetscCall(KSPGetPCSide(inner_ksp, &(std::get<2>(*ctx))));
2217:               if (std::get<2>(*ctx) == PC_LEFT || std::get<2>(*ctx) == PC_SIDE_DEFAULT) {
2218:                 PetscCall(KSPSetPreSolve(inner_ksp, KSPPreSolve_SchurCorrection, ctx));
2219:               } else { /* no support for PC_SYMMETRIC */
2220:                 PetscCheck(std::get<2>(*ctx) == PC_RIGHT, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "PCSide %s (!= %s or %s or %s)", PCSides[std::get<2>(*ctx)], PCSides[PC_SIDE_DEFAULT], PCSides[PC_LEFT], PCSides[PC_RIGHT]);
2221:               }
2222:               PetscCall(KSPSetPostSolve(inner_ksp, KSPPostSolve_SchurCorrection, ctx));
2223:               PetscCall(PetscObjectContainerCompose((PetscObject)std::get<0>(*ctx)[1], "_PCHPDDM_Schur", ctx, nullptr));
2224:               PetscCall(PCSetUp(std::get<0>(*ctx)[1]));
2225:               PetscCall(KSPSetOperators(inner_ksp, S, S));
2226:               PetscCall(MatCreateVecs(std::get<1>(*ctx)[0], std::get<3>(*ctx), std::get<3>(*ctx) + 1));
2227:               PetscCall(VecDuplicate(std::get<3>(*ctx)[0], std::get<3>(*ctx) + 2));
2228:               PetscCall(PetscObjectDereference((PetscObject)inner_ksp));
2229:               PetscCall(PetscObjectDereference((PetscObject)S));
2230:             } else {
2231:               std::get<0>(*ctx)[0] = pc_00;
2232:               PetscCall(PetscObjectContainerCompose((PetscObject)pc, "_PCHPDDM_Schur", ctx, nullptr));
2233:               PetscCall(ISCreateStride(PetscObjectComm((PetscObject)data_00->is), P->rmap->n, P->rmap->rstart, 1, &data->is)); /* dummy variables in the case of a centralized Schur complement */
2234:               if (A11) {
2235:                 PetscCall(MatGetDiagonalBlock(A11, &data->aux));
2236:                 PetscCall(PetscObjectReference((PetscObject)data->aux));
2237:               } else {
2238:                 PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, P->rmap->n, P->rmap->n, 0, nullptr, &data->aux));
2239:                 PetscCall(MatAssemblyBegin(data->aux, MAT_FINAL_ASSEMBLY));
2240:                 PetscCall(MatAssemblyEnd(data->aux, MAT_FINAL_ASSEMBLY));
2241:               }
2242:               PetscCall(PCSetUp(pc));
2243:             }
2244:             for (Vec &v : initial) PetscCall(VecDestroy(&v));
2245:             PetscFunctionReturn(PETSC_SUCCESS);
2246:           } else { /* second call to PCSetUp() on the PC associated to the Schur complement, retrieve previously set context */
2247:             PetscCall(PetscContainerGetPointer(container, static_cast<void *>(&ctx)));
2248:           }
2249:         }
2250:       }
2251:     }
2252:     if (!data->is && data->N > 1) {
2253:       PetscCall(PetscObjectTypeCompareAny((PetscObject)P, &flg, MATNORMAL, MATNORMALHERMITIAN, ""));
2254:       if (flg || (A->rmap->N != A->cmap->N && P->rmap->N == P->cmap->N && P->rmap->N == A->cmap->N)) {
2255:         Mat B;

2257:         PetscCall(PCHPDDMSetAuxiliaryMatNormal_Private(pc, A, P, &B, pcpre));
2258:         if (data->correction == PC_HPDDM_COARSE_CORRECTION_DEFLATED) data->correction = PC_HPDDM_COARSE_CORRECTION_BALANCED;
2259:         PetscCall(MatDestroy(&B));
2260:       } else {
2261:         PetscCall(PetscObjectTypeCompare((PetscObject)P, MATSCHURCOMPLEMENT, &flg));
2262:         if (flg) {
2263:           Mat                 A00, P00, A01, A10, A11, B, N;
2264:           PCHPDDMSchurPreType type = PC_HPDDM_SCHUR_PRE_LEAST_SQUARES;

2266:           PetscCall(MatSchurComplementGetSubMatrices(P, &A00, &P00, &A01, &A10, &A11));
2267:           PetscCall(PetscOptionsGetEnum(((PetscObject)pc)->options, pcpre, "-pc_hpddm_schur_precondition", PCHPDDMSchurPreTypes, (PetscEnum *)&type, &flg));
2268:           if (type == PC_HPDDM_SCHUR_PRE_LEAST_SQUARES) {
2269:             Mat                        B01;
2270:             Vec                        diagonal = nullptr;
2271:             MatSchurComplementAinvType type;

2273:             PetscCall(PCHPDDMCheckSymmetry_Private(pc, A01, A10, &B01));
2274:             if (A11) {
2275:               PetscCall(MatCreateVecs(A11, &diagonal, nullptr));
2276:               PetscCall(MatGetDiagonal(A11, diagonal));
2277:             }
2278:             PetscCall(MatCreateVecs(P00, &v, nullptr));
2279:             PetscCall(MatSchurComplementGetAinvType(P, &type));
2280:             PetscCheck(type == MAT_SCHUR_COMPLEMENT_AINV_DIAG || type == MAT_SCHUR_COMPLEMENT_AINV_LUMP || type == MAT_SCHUR_COMPLEMENT_AINV_BLOCK_DIAG, PetscObjectComm((PetscObject)P), PETSC_ERR_SUP, "-%smat_schur_complement_ainv_type %s",
2281:                        ((PetscObject)P)->prefix ? ((PetscObject)P)->prefix : "", MatSchurComplementAinvTypes[type]);
2282:             if (type != MAT_SCHUR_COMPLEMENT_AINV_BLOCK_DIAG) {
2283:               if (type == MAT_SCHUR_COMPLEMENT_AINV_LUMP) {
2284:                 Vec d;

2286:                 PetscCall(MatGetRowSum(P00, v));
2287:                 if (A00 == P00) PetscCall(PetscObjectReference((PetscObject)A00));
2288:                 PetscCall(MatDestroy(&P00));
2289:                 PetscCall(VecDuplicate(v, &d));
2290:                 PetscCall(VecCopy(v, d));
2291:                 PetscCall(MatCreateDiagonal(d, &P00));
2292:                 PetscCall(VecDestroy(&d));
2293:                 PetscCall(MatSchurComplementUpdateSubMatrices(P, A00, P00, A01, A10, A11)); /* replace P00 by diag(sum of each row of P00) */
2294:                 PetscCall(MatDestroy(&P00));
2295:               } else PetscCall(MatGetDiagonal(P00, v));
2296:               PetscCall(VecReciprocal(v)); /* inv(diag(P00))       */
2297:               PetscCall(VecSqrtAbs(v));    /* sqrt(inv(diag(P00))) */
2298:               PetscCall(MatDuplicate(A01, MAT_COPY_VALUES, &B));
2299:               PetscCall(MatDiagonalScale(B, v, nullptr));
2300:               if (B01) PetscCall(MatDiagonalScale(B01, v, nullptr));
2301:             } else {
2302:               Mat     D00;
2303:               MatType type;

2305:               PetscCall(MatCreate(PetscObjectComm((PetscObject)A00), &D00));
2306:               PetscCall(MatSetType(D00, MATAIJ));
2307:               PetscCall(MatSetOptionsPrefix(D00, ((PetscObject)A00)->prefix));
2308:               PetscCall(MatAppendOptionsPrefix(D00, "block_diagonal_"));
2309:               PetscCall(MatSetFromOptions(D00));                          /* for setting -mat_block_size dynamically */
2310:               PetscCall(MatConvert(A00, MATAIJ, MAT_INITIAL_MATRIX, &B)); /* not all MatTypes have a MatInvertBlockDiagonal() implementation, plus one may want to use a different block size than the one of A00 */
2311:               PetscCall(MatSetBlockSizesFromMats(B, D00, D00));
2312:               PetscCall(MatInvertBlockDiagonalMat(B, D00));
2313:               PetscCall(MatDestroy(&B));
2314:               PetscCall(MatGetType(A01, &type));                            /* cache MatType */
2315:               PetscCall(MatConvert(A01, MATAIJ, MAT_INPLACE_MATRIX, &A01)); /* MatProduct is not versatile enough to fallback gracefully if no implementation found, so MatConvert() */
2316:               PetscCall(MatMatMult(D00, A01, MAT_INITIAL_MATRIX, PETSC_CURRENT, &B));
2317:               PetscCall(MatDestroy(&D00));
2318:               PetscCall(MatConvert(A01, type, MAT_INPLACE_MATRIX, &A01)); /* reset to previous MatType */
2319:               PetscCall(MatConvert(B, type, MAT_INPLACE_MATRIX, &B));
2320:               if (!B01) { /* symmetric case */
2321:                 B01 = A01;
2322:                 PetscCall(PetscObjectReference((PetscObject)B01));
2323:               }
2324:             }
2325:             if (B01 && B01 != A01) PetscCall(MatSetBlockSizesFromMats(B01, A01, A01)); /* TODO: remove this line once Firedrake is fixed */
2326:             PetscCall(VecDestroy(&v));
2327:             PetscCall(MatCreateNormalHermitian(B, &N));
2328:             PetscCall(PCHPDDMSetAuxiliaryMatNormal_Private(pc, B, N, &P, pcpre, &diagonal, B01));
2329:             PetscCall(PetscObjectTypeCompare((PetscObject)data->aux, MATSEQAIJ, &flg));
2330:             if (!flg) {
2331:               PetscCall(MatDestroy(&P));
2332:               P = N;
2333:               PetscCall(PetscObjectReference((PetscObject)P));
2334:             }
2335:             if (diagonal) {
2336:               PetscCall(MatSetOption(P, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_FALSE)); /* may have missing diagonal entries */
2337:               PetscCall(MatDiagonalSet(P, diagonal, ADD_VALUES));
2338:               PetscCall(PCSetOperators(pc, P, P)); /* replace P by A01^T inv(diag(P00)) A01 - diag(P11) */
2339:               PetscCall(VecDestroy(&diagonal));
2340:             } else PetscCall(PCSetOperators(pc, B01 ? P : N, P));  /* replace P by A01^T inv(diag(P00)) A01                         */
2341:             pc->ops->postsolve = PCPostSolve_SchurPreLeastSquares; /*  PCFIELDSPLIT expect a KSP for (P11 - A10 inv(diag(P00)) A01) */
2342:             PetscCall(MatDestroy(&N));                             /*  but a PC for (A10 inv(diag(P00)) A10 - P11) is setup instead */
2343:             PetscCall(MatDestroy(&P));                             /*  so the sign of the solution must be flipped                  */
2344:             PetscCall(MatDestroy(&B));
2345:           } else
2346:             PetscCheck(type != PC_HPDDM_SCHUR_PRE_GENEO, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition %s without a prior call to PCHPDDMSetAuxiliaryMat() on the A11 block%s%s", pcpre ? pcpre : "", PCHPDDMSchurPreTypes[type], pcpre ? " -" : "", pcpre ? pcpre : "");
2347:           for (Vec &v : initial) PetscCall(VecDestroy(&v));
2348:           PetscFunctionReturn(PETSC_SUCCESS);
2349:         } else {
2350:           PetscCheck(!data->scaling || !algebraic, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "User-supplied scaling cannot be combined with an internally assembled auxiliary problem");
2351:           if (algebraic) {
2352:             PetscCall(ISCreateStride(PETSC_COMM_SELF, P->rmap->n, P->rmap->rstart, 1, &data->is));
2353:             PetscCall(MatIncreaseOverlap(P, 1, &data->is, 1));
2354:             PetscCall(ISSort(data->is));
2355:           } else
2356:             PetscCall(PetscInfo(pc, "Cannot assemble a fully-algebraic coarse operator with an assembled Pmat and -%spc_hpddm_levels_1_st_pc_type != mat and -%spc_hpddm_block_splitting != true and -%spc_hpddm_harmonic_overlap < 1\n", pcpre ? pcpre : "", pcpre ? pcpre : "", pcpre ? pcpre : ""));
2357:         }
2358:       }
2359:     }
2360:   }
2361:   if (PetscDefined(USE_DEBUG)) {
2362:     if (data->is) PetscCall(ISDuplicate(data->is, &dis));
2363:     if (data->aux) PetscCall(MatDuplicate(data->aux, MAT_COPY_VALUES, &daux));
2364:   }
2365:   if (data->is || (ismatis && data->N > 1)) {
2366:     if (ismatis) {
2367:       PetscCall(MatISGetLocalMat(P, &N));
2368:       PetscCall(PetscObjectTypeCompareAny((PetscObject)N, &flg, MATSEQBAIJ, MATSEQSBAIJ, ""));
2369:       PetscCall(MatISRestoreLocalMat(P, &N));
2370:       PetscCall(MatConvert(P, flg ? MATMPIBAIJ : MATMPIAIJ, MAT_INITIAL_MATRIX, &C));
2371:       PetscCall(MatISGetLocalToGlobalMapping(P, &l2g, nullptr));
2372:       PetscCall(PetscObjectReference((PetscObject)P));
2373:       PetscCall(KSPSetOperators(data->levels[0]->ksp, A, C));
2374:       std::swap(C, P);
2375:       PetscCall(ISLocalToGlobalMappingGetSize(l2g, &n));
2376:       PetscCall(ISCreateStride(PETSC_COMM_SELF, n, 0, 1, &loc));
2377:       PetscCall(ISLocalToGlobalMappingApplyIS(l2g, loc, &is[0]));
2378:       PetscCall(ISDestroy(&loc));
2379:       /* the auxiliary Mat is _not_ the local Neumann matrix                                */
2380:       /* it is the local Neumann matrix augmented (with zeros) through MatIncreaseOverlap() */
2381:       data->Neumann = PETSC_BOOL3_FALSE;
2382:       structure     = SAME_NONZERO_PATTERN;
2383:     } else {
2384:       is[0] = data->is;
2385:       if (algebraic || ctx) subdomains = PETSC_TRUE;
2386:       PetscCall(PetscOptionsGetBool(((PetscObject)pc)->options, pcpre, "-pc_hpddm_define_subdomains", &subdomains, nullptr));
2387:       if (ctx) PetscCheck(subdomains, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_define_subdomains false", pcpre, pcpre);
2388:       if (PetscBool3ToBool(data->Neumann)) {
2389:         PetscCheck(!block, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_block_splitting and -%spc_hpddm_has_neumann", pcpre ? pcpre : "", pcpre ? pcpre : "");
2390:         PetscCheck(overlap == -1, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_harmonic_overlap %" PetscInt_FMT " and -%spc_hpddm_has_neumann", pcpre ? pcpre : "", overlap, pcpre ? pcpre : "");
2391:         PetscCheck(!algebraic, PetscObjectComm((PetscObject)P), PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_levels_1_st_pc_type mat and -%spc_hpddm_has_neumann", pcpre ? pcpre : "", pcpre ? pcpre : "");
2392:       }
2393:       if (PetscBool3ToBool(data->Neumann) || block) structure = SAME_NONZERO_PATTERN;
2394:       PetscCall(ISCreateStride(PetscObjectComm((PetscObject)data->is), P->rmap->n, P->rmap->rstart, 1, &loc));
2395:     }
2396:     PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
2397:     PetscCall(PetscOptionsGetEnum(((PetscObject)pc)->options, prefix, "-st_matstructure", MatStructures, (PetscEnum *)&structure, &flg)); /* if not user-provided, force its value when possible */
2398:     if (!flg && structure == SAME_NONZERO_PATTERN) { /* cannot call STSetMatStructure() yet, insert the appropriate option in the database, parsed by STSetFromOptions() */
2399:       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-%spc_hpddm_levels_1_st_matstructure", pcpre ? pcpre : ""));
2400:       PetscCall(PetscOptionsSetValue(((PetscObject)pc)->options, prefix, MatStructures[structure]));
2401:     }
2402:     flg = PETSC_FALSE;
2403:     if (data->share) {
2404:       data->share = PETSC_FALSE; /* will be reset to PETSC_TRUE if none of the conditions below are true */
2405:       if (!subdomains) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since -%spc_hpddm_define_subdomains is not true\n", pcpre ? pcpre : ""));
2406:       else if (data->deflation) PetscCall(PetscInfo(pc, "Nothing to share since PCHPDDMSetDeflationMat() has been called\n"));
2407:       else if (ismatis) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc with a Pmat of type MATIS\n"));
2408:       else if (!algebraic && structure != SAME_NONZERO_PATTERN)
2409:         PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since -%spc_hpddm_levels_1_st_matstructure %s (!= %s)\n", pcpre ? pcpre : "", MatStructures[structure], MatStructures[SAME_NONZERO_PATTERN]));
2410:       else {
2411:         PetscCall(PetscObjectTypeCompare((PetscObject)P, MATHTOOL, &flg));
2412:         if (flg) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since Pmat is of type MATHTOOL\n"));
2413:         else data->share = PETSC_TRUE;
2414:       }
2415:       if (!data->share) {
2416:         PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "-%spc_hpddm_levels_1_st_share_sub_ksp", pcpre ? pcpre : ""));
2417:         PetscCall(PetscOptionsClearValue(((PetscObject)pc)->options, prefix));
2418:       }
2419:     }
2420:     if (!ismatis) {
2421:       if (data->share || (!PetscBool3ToBool(data->Neumann) && subdomains)) PetscCall(ISDuplicate(is[0], &unsorted));
2422:       else unsorted = is[0];
2423:     }
2424:     if ((ctx || data->N > 1) && (data->aux || ismatis || algebraic)) {
2425:       PetscCheck(loadedSym, PETSC_COMM_SELF, PETSC_ERR_PLIB, "HPDDM library not loaded, cannot use more than one level");
2426:       PetscCall(MatSetOption(P, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
2427:       if (ismatis) {
2428:         /* needed by HPDDM (currently) so that the partition of unity is 0 on subdomain interfaces */
2429:         PetscCall(MatIncreaseOverlap(P, 1, is, 1));
2430:         PetscCall(ISDestroy(&data->is));
2431:         data->is = is[0];
2432:       } else {
2433:         if (PetscDefined(USE_DEBUG)) PetscCall(PCHPDDMCheckInclusion_Private(pc, data->is, loc, PETSC_TRUE));
2434:         if (!ctx && overlap == -1) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", PCHPDDMAlgebraicAuxiliaryMat_Private));
2435:       }
2436:       if (algebraic && overlap == -1) {
2437:         PetscUseMethod(pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", (Mat, IS *, Mat *[], PetscBool), (P, is, &sub, block));
2438:         if (block) {
2439:           PetscCall(PetscObjectQuery((PetscObject)sub[0], "_PCHPDDM_Neumann_Mat", (PetscObject *)&data->aux));
2440:           PetscCall(PetscObjectCompose((PetscObject)sub[0], "_PCHPDDM_Neumann_Mat", nullptr));
2441:         }
2442:       } else if (!ctx) {
2443:         if (PetscBool3ToBool(data->Neumann)) sub = &data->aux;
2444:         else {
2445:           PetscBool flg;

2447:           if (overlap != -1) {
2448:             Harmonic              h;
2449:             Mat                   A0, *a;                 /* with an SVD: [ A_00  A_01       ] */
2450:             IS                    ov[2], restriction[3];  /*              [ A_10  A_11  A_12 ] */
2451:             const PetscInt       *i[2], bs = P->cmap->bs; /* with a GEVP: [ A_00  A_01       ] */
2452:             PetscInt              n[2], location;         /*              [ A_10  A_11  A_12 ] */
2453:             std::vector<PetscInt> v[2];                   /*              [       A_21  A_22 ] */

2455:             do {
2456:               PetscCall(ISDuplicate(data->is, ov));
2457:               if (overlap > 1) PetscCall(MatIncreaseOverlap(P, 1, ov, overlap - 1));
2458:               PetscCall(ISDuplicate(ov[0], ov + 1));
2459:               PetscCall(MatIncreaseOverlap(P, 1, ov + 1, 1));
2460:               PetscCall(ISGetLocalSize(ov[0], n));
2461:               PetscCall(ISGetLocalSize(ov[1], n + 1));
2462:               flg = static_cast<PetscBool>(n[0] == n[1] && n[0] != P->rmap->n);
2463:               PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &flg, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)pc)));
2464:               if (flg) {
2465:                 PetscCall(ISDestroy(ov));
2466:                 PetscCall(ISDestroy(ov + 1));
2467:                 PetscCheck(--overlap, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "No oversampling possible");
2468:                 PetscCall(PetscInfo(pc, "Supplied -%spc_hpddm_harmonic_overlap parameter is too large, it has been decreased to %" PetscInt_FMT "\n", pcpre ? pcpre : "", overlap));
2469:               } else break;
2470:             } while (1);
2471:             PetscCall(PetscNew(&h));
2472:             h->ksp = nullptr;
2473:             PetscCall(PetscCalloc1(2, &h->A));
2474:             PetscCall(PetscOptionsHasName(((PetscObject)pc)->options, prefix, "-eps_nev", &flg));
2475:             if (!flg) {
2476:               PetscCall(PetscOptionsHasName(((PetscObject)pc)->options, prefix, "-svd_nsv", &flg));
2477:               if (!flg) PetscCall(PetscOptionsHasName(((PetscObject)pc)->options, prefix, "-svd_threshold_relative", &flg));
2478:             } else flg = PETSC_FALSE;
2479:             PetscCall(ISSort(ov[0]));
2480:             if (!flg) PetscCall(ISSort(ov[1]));
2481:             PetscCall(PetscCalloc1(3, &h->is));
2482:             PetscCall(MatCreateSubMatrices(P, 1, ov + !flg, ov + 1, MAT_INITIAL_MATRIX, &a)); /* submatrix from above, either square (!flg) or rectangular (flg) */
2483:             for (PetscInt j = 0; j < 2; ++j) PetscCall(ISGetIndices(ov[j], i + j));
2484:             v[1].reserve((n[1] - n[0]) / bs);
2485:             for (PetscInt j = 0; j < n[1]; j += bs) { /* indices of the (2,2) block */
2486:               PetscCall(ISLocate(ov[0], i[1][j], &location));
2487:               if (location < 0) v[1].emplace_back(j / bs);
2488:             }
2489:             if (!flg) {
2490:               h->A[1] = a[0];
2491:               PetscCall(PetscObjectReference((PetscObject)h->A[1]));
2492:               v[0].reserve((n[0] - P->rmap->n) / bs);
2493:               for (PetscInt j = 0; j < n[1]; j += bs) { /* row indices of the (1,2) block */
2494:                 PetscCall(ISLocate(loc, i[1][j], &location));
2495:                 if (location < 0) {
2496:                   PetscCall(ISLocate(ov[0], i[1][j], &location));
2497:                   if (location >= 0) v[0].emplace_back(j / bs);
2498:                 }
2499:               }
2500:               PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[0].size(), v[0].data(), PETSC_USE_POINTER, restriction));
2501:               PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[1].size(), v[1].data(), PETSC_COPY_VALUES, h->is + 2));
2502:               PetscCall(MatCreateSubMatrix(a[0], restriction[0], h->is[2], MAT_INITIAL_MATRIX, h->A)); /* A_12 submatrix from above */
2503:               PetscCall(ISDestroy(restriction));
2504:               PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, restriction));
2505:               PetscCall(MatCreateSubMatrix(a[0], restriction[0], restriction[2] = restriction[0], MAT_INITIAL_MATRIX, &A0)); /* [ A_00  A_01 ; A_10  A_11 ] submatrix from above */
2506:               PetscCall(ISDestroy(restriction));
2507:               v[0].clear();
2508:               PetscCall(ISEmbed(loc, ov[1], PETSC_TRUE, h->is + 1));
2509:               PetscCall(ISEmbed(data->is, ov[1], PETSC_TRUE, h->is));
2510:             }
2511:             v[0].reserve((n[0] - P->rmap->n) / bs);
2512:             for (PetscInt j = 0; j < n[0]; j += bs) {
2513:               PetscCall(ISLocate(loc, i[0][j], &location));
2514:               if (location < 0) v[0].emplace_back(j / bs);
2515:             }
2516:             PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[0].size(), v[0].data(), PETSC_USE_POINTER, restriction));
2517:             for (PetscInt j = 0; j < 2; ++j) PetscCall(ISRestoreIndices(ov[j], i + j));
2518:             if (flg) {
2519:               PetscCall(ISCreateStride(PETSC_COMM_SELF, a[0]->rmap->n, 0, 1, restriction + 1));
2520:               PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, restriction + 2));
2521:               PetscCall(MatCreateSubMatrix(a[0], restriction[1], restriction[2], MAT_INITIAL_MATRIX, &A0)); /* [ A_00  A_01 ; A_10  A_11 ] submatrix from above */
2522:               PetscCall(ISDestroy(restriction + 2));
2523:               PetscCall(ISDestroy(restriction + 1));
2524:               PetscCall(PetscObjectTypeCompare((PetscObject)P, MATMPISBAIJ, &flg));
2525:               if (flg) { /* initial Pmat was MATSBAIJ, convert back to the same format since this submatrix is square */
2526:                 PetscCall(MatSetOption(A0, MAT_SYMMETRIC, PETSC_TRUE));
2527:                 PetscCall(MatConvert(A0, MATSEQSBAIJ, MAT_INPLACE_MATRIX, &A0));
2528:               }
2529:               flg = PETSC_TRUE;
2530:               PetscCall(ISEmbed(loc, data->is, PETSC_TRUE, h->is));
2531:               PetscCall(ISCreateBlock(PETSC_COMM_SELF, bs, v[1].size(), v[1].data(), PETSC_USE_POINTER, restriction + 2));
2532:               PetscCall(MatCreateSubMatrix(a[0], restriction[0], restriction[2], MAT_INITIAL_MATRIX, h->A)); /* A_12 submatrix from above */
2533:               PetscCall(ISDestroy(restriction + 2));
2534:             }
2535:             PetscCall(ISEmbed(loc, ov[0], PETSC_TRUE, restriction + 1));
2536:             if (subdomains) {
2537:               if (!data->levels[0]->pc) {
2538:                 PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->pc));
2539:                 PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
2540:                 PetscCall(PCSetOptionsPrefix(data->levels[0]->pc, prefix));
2541:                 PetscCall(PCSetOperators(data->levels[0]->pc, A, P));
2542:               }
2543:               PetscCall(PCSetType(data->levels[0]->pc, PCASM));
2544:               if (!data->levels[0]->pc->setupcalled) PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, ov + !flg, &loc));
2545:               PetscCall(PCSetModifySubMatrices(data->levels[0]->pc, pc->modifysubmatrices, pc->modifysubmatricesP));
2546:               PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(data->levels[0]->pc, flg ? A0 : a[0], PETSC_TRUE));
2547:               if (!flg) ++overlap;
2548:               if (data->share) {
2549:                 PetscInt n = -1;

2551:                 PetscTryMethod(data->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data->levels[0]->pc, &n, nullptr, &ksp));
2552:                 PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
2553:                 if (flg) {
2554:                   h->ksp = ksp[0];
2555:                   PetscCall(PetscObjectReference((PetscObject)h->ksp));
2556:                 }
2557:               }
2558:             }
2559:             if (!h->ksp) {
2560:               PetscBool share = data->share;

2562:               PetscCall(KSPCreate(PETSC_COMM_SELF, &h->ksp));
2563:               PetscCall(KSPSetType(h->ksp, KSPPREONLY));
2564:               PetscCall(KSPSetOperators(h->ksp, A0, A0));
2565:               do {
2566:                 if (!data->share) {
2567:                   share = PETSC_FALSE;
2568:                   PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_%s", pcpre ? pcpre : "", flg ? "svd_" : "eps_"));
2569:                   PetscCall(KSPSetOptionsPrefix(h->ksp, prefix));
2570:                   PetscCall(KSPSetFromOptions(h->ksp));
2571:                 } else {
2572:                   MatSolverType type;

2574:                   PetscCall(PetscObjectTypeCompareAny((PetscObject)ksp[0]->pc, &data->share, PCLU, PCCHOLESKY, ""));
2575:                   if (data->share) {
2576:                     PetscCall(PCFactorGetMatSolverType(ksp[0]->pc, &type));
2577:                     if (!type) {
2578:                       if (PetscDefined(HAVE_MUMPS)) PetscCall(PCFactorSetMatSolverType(ksp[0]->pc, MATSOLVERMUMPS));
2579:                       else if (PetscDefined(HAVE_MKL_PARDISO)) PetscCall(PCFactorSetMatSolverType(ksp[0]->pc, MATSOLVERMKL_PARDISO));
2580:                       else data->share = PETSC_FALSE;
2581:                       if (data->share) PetscCall(PCSetFromOptions(ksp[0]->pc));
2582:                     } else {
2583:                       PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &data->share));
2584:                       if (!data->share) PetscCall(PetscStrcmp(type, MATSOLVERMKL_PARDISO, &data->share));
2585:                     }
2586:                     if (data->share) {
2587:                       IS                                   embed;
2588:                       std::tuple<KSP, VecScatter, Vec[2]> *p;

2590:                       PetscCall(PCFactorGetMatrix(ksp[0]->pc, &A));
2591:                       PetscCall(MatFactorSetSchurIS(A, h->is[2]));
2592:                       PetscCall(KSPSetUp(ksp[0]));
2593:                       PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_eps_shell_", pcpre ? pcpre : ""));
2594:                       PetscCall(KSPSetOptionsPrefix(h->ksp, prefix));
2595:                       PetscCall(KSPSetFromOptions(h->ksp));
2596:                       PetscCall(PCSetType(h->ksp->pc, PCSHELL));
2597:                       PetscCall(PetscNew(&p));
2598:                       std::get<0>(*p) = ksp[0];
2599:                       PetscCall(ISEmbed(ov[0], ov[1], PETSC_TRUE, &embed));
2600:                       PetscCall(MatCreateVecs(A, std::get<2>(*p), std::get<2>(*p) + 1));
2601:                       PetscCall(MatCreateVecs(A0, &xin, nullptr));
2602:                       PetscCall(VecScatterCreate(std::get<2>(*p)[0], embed, xin, nullptr, &std::get<1>(*p)));
2603:                       PetscCall(VecDestroy(&xin));
2604:                       PetscCall(ISDestroy(&embed));
2605:                       PetscCall(PCShellSetContext(h->ksp->pc, p));
2606:                       PetscCall(PCShellSetApply(h->ksp->pc, PCApply_Schur));
2607:                       PetscCall(PCShellSetApplyTranspose(h->ksp->pc, PCApply_Schur<Vec, true>));
2608:                       PetscCall(PCShellSetMatApply(h->ksp->pc, PCApply_Schur<Mat>));
2609:                       PetscCall(PCShellSetDestroy(h->ksp->pc, PCDestroy_Schur));
2610:                     }
2611:                   }
2612:                   if (!data->share) PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since neither MUMPS nor MKL PARDISO is used\n"));
2613:                 }
2614:               } while (!share != !data->share); /* if data->share is initially PETSC_TRUE, but then reset to PETSC_FALSE, then go back to the beginning of the do loop */
2615:             }
2616:             PetscCall(ISDestroy(ov));
2617:             PetscCall(ISDestroy(ov + 1));
2618:             if (overlap == 1 && subdomains && flg) {
2619:               *subA = A0;
2620:               sub   = subA;
2621:             } else PetscCall(MatDestroy(&A0));
2622:             PetscCall(MatCreateShell(PETSC_COMM_SELF, P->rmap->n, n[1] - n[0], P->rmap->n, n[1] - n[0], h, &data->aux));
2623:             PetscCall(MatSetVecType(data->aux, h->A[0]->defaultvectype));
2624:             PetscCall(KSPSetErrorIfNotConverged(h->ksp, PETSC_TRUE)); /* bail out as early as possible to avoid (apparently) unrelated error messages */
2625:             PetscCall(MatCreateVecs(h->ksp->pc->pmat, h->v, nullptr));
2626:             PetscCall(MatCreateVecs(data->aux, nullptr, h->v + 1));
2627:             PetscCall(VecScatterCreate(h->v[0], restriction[1], h->v[1], nullptr, h->scatter + 1));
2628:             PetscCall(ISDestroy(restriction + 1));
2629:             PetscCall(VecDestroy(h->v + 1));
2630:             PetscCall(MatCreateVecs(h->A[0], nullptr, h->v + 1));
2631:             PetscCall(VecScatterCreate(h->v[0], restriction[0], h->v[1], nullptr, h->scatter));
2632:             PetscCall(ISDestroy(restriction));
2633:             PetscCall(MatShellSetOperation(data->aux, MATOP_MULT, (PetscErrorCodeFn *)MatMult_Harmonic));
2634:             PetscCall(MatShellSetOperation(data->aux, MATOP_MULT_TRANSPOSE, (PetscErrorCodeFn *)MatMultTranspose_Harmonic));
2635:             PetscCall(MatShellSetMatProductOperation(data->aux, MATPRODUCT_AB, nullptr, MatProduct_AB_Harmonic, nullptr, MATDENSE, MATDENSE));
2636:             PetscCall(MatShellSetMatProductOperation(data->aux, MATPRODUCT_AtB, nullptr, MatProduct_AtB_Harmonic, nullptr, MATDENSE, MATDENSE));
2637:             PetscCall(MatShellSetOperation(data->aux, MATOP_DESTROY, (PetscErrorCodeFn *)MatDestroy_Harmonic));
2638:             PetscCall(MatDestroySubMatrices(1, &a));
2639:           }
2640:           if (overlap != 1 || !subdomains) {
2641:             PetscCall(MatCreateSubMatrices(P, 1, is, is, MAT_INITIAL_MATRIX, &sub));
2642:             if (ismatis) {
2643:               PetscCall(MatISGetLocalMat(C, &N));
2644:               PetscCall(PetscObjectTypeCompare((PetscObject)N, MATSEQSBAIJ, &flg));
2645:               if (flg) PetscCall(MatConvert(sub[0], MATSEQSBAIJ, MAT_INPLACE_MATRIX, sub));
2646:               PetscCall(MatISRestoreLocalMat(C, &N));
2647:             }
2648:           }
2649:         }
2650:       }
2651:       if (data->N > 1) {
2652:         /* Vec holding the partition of unity */
2653:         if (!data->levels[0]->D) {
2654:           PetscCall(ISGetLocalSize(data->is, &n));
2655:           PetscCall(VecCreate(PETSC_COMM_SELF, &data->levels[0]->D));
2656:           PetscCall(VecSetSizes(data->levels[0]->D, n, n));
2657:           PetscCall(VecSetType(data->levels[0]->D, A->defaultvectype));
2658:         }
2659:         if (data->share && overlap == -1) {
2660:           Mat      D;
2661:           IS       perm = nullptr;
2662:           PetscInt size = -1;

2664:           if (!data->levels[0]->pc) {
2665:             PetscCall(PetscSNPrintf(prefix, sizeof(prefix), "%spc_hpddm_levels_1_", pcpre ? pcpre : ""));
2666:             PetscCall(PCCreate(PetscObjectComm((PetscObject)pc), &data->levels[0]->pc));
2667:             PetscCall(PCSetOptionsPrefix(data->levels[0]->pc, prefix));
2668:             PetscCall(PCSetOperators(data->levels[0]->pc, A, P));
2669:           }
2670:           PetscCall(PCSetType(data->levels[0]->pc, PCASM));
2671:           if (!ctx) {
2672:             if (!data->levels[0]->pc->setupcalled) {
2673:               IS sorted; /* PCASM will sort the input IS, duplicate it to return an unmodified (PCHPDDM) input IS */

2675:               PetscCall(ISDuplicate(is[0], &sorted));
2676:               PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, &sorted, &loc));
2677:               PetscCall(PetscObjectDereference((PetscObject)sorted));
2678:             }
2679:             PetscCall(PCSetFromOptions(data->levels[0]->pc));
2680:             PetscCall(PCSetModifySubMatrices(data->levels[0]->pc, pc->modifysubmatrices, pc->modifysubmatricesP));
2681:             if (block) {
2682:               PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, sub[0], &C, &perm));
2683:               PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(data->levels[0]->pc, C, algebraic));
2684:             } else PetscCall(PCSetUp(data->levels[0]->pc));
2685:             PetscTryMethod(data->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data->levels[0]->pc, &size, nullptr, &ksp));
2686:             if (size != 1) {
2687:               data->share = PETSC_FALSE;
2688:               PetscCheck(size == -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", size);
2689:               PetscCall(PetscInfo(pc, "Cannot share subdomain KSP between SLEPc and PETSc since PCASMGetSubKSP() not found in fine-level PC\n"));
2690:               PetscCall(ISDestroy(&unsorted));
2691:               unsorted = is[0];
2692:             } else {
2693:               const char *matpre;
2694:               PetscBool   cmp[4];

2696:               if (!block && !ctx) PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, PetscBool3ToBool(data->Neumann) ? sub[0] : data->aux, &C, &perm));
2697:               if (perm) { /* unsorted input IS */
2698:                 if (!PetscBool3ToBool(data->Neumann) && !block) {
2699:                   PetscCall(MatPermute(sub[0], perm, perm, &D)); /* permute since PCASM will call ISSort() */
2700:                   PetscCall(MatHeaderReplace(sub[0], &D));
2701:                 }
2702:                 if (data->B) { /* see PCHPDDMSetRHSMat() */
2703:                   PetscCall(MatPermute(data->B, perm, perm, &D));
2704:                   PetscCall(MatHeaderReplace(data->B, &D));
2705:                 }
2706:                 PetscCall(ISDestroy(&perm));
2707:               }
2708:               PetscCall(KSPGetOperators(ksp[0], subA, subA + 1));
2709:               PetscCall(PetscObjectReference((PetscObject)subA[0]));
2710:               PetscCall(MatDuplicate(subA[1], MAT_SHARE_NONZERO_PATTERN, &D));
2711:               PetscCall(MatGetOptionsPrefix(subA[1], &matpre));
2712:               PetscCall(MatSetOptionsPrefix(D, matpre));
2713:               PetscCall(PetscObjectTypeCompare((PetscObject)D, MATNORMAL, cmp));
2714:               PetscCall(PetscObjectTypeCompare((PetscObject)C, MATNORMAL, cmp + 1));
2715:               if (!cmp[0]) PetscCall(PetscObjectTypeCompare((PetscObject)D, MATNORMALHERMITIAN, cmp + 2));
2716:               else cmp[2] = PETSC_FALSE;
2717:               if (!cmp[1]) PetscCall(PetscObjectTypeCompare((PetscObject)C, MATNORMALHERMITIAN, cmp + 3));
2718:               else cmp[3] = PETSC_FALSE;
2719:               PetscCheck(cmp[0] == cmp[1] && cmp[2] == cmp[3], PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_levels_1_pc_asm_sub_mat_type %s and auxiliary Mat of type %s", pcpre ? pcpre : "", ((PetscObject)D)->type_name, ((PetscObject)C)->type_name);
2720:               if (!cmp[0] && !cmp[2]) {
2721:                 if (!block) {
2722:                   if (PetscDefined(USE_DEBUG)) PetscCall(PCHPDDMCheckMatStructure_Private(pc, D, C));
2723:                   PetscCall(MatAXPY(D, 1.0, C, SUBSET_NONZERO_PATTERN));
2724:                 } else {
2725:                   structure = DIFFERENT_NONZERO_PATTERN;
2726:                   PetscCall(MatAXPY(D, 1.0, data->aux, structure));
2727:                 }
2728:               } else {
2729:                 Mat mat[2];

2731:                 if (cmp[0]) {
2732:                   PetscCall(MatNormalGetMat(D, mat));
2733:                   PetscCall(MatNormalGetMat(C, mat + 1));
2734:                 } else {
2735:                   PetscCall(MatNormalHermitianGetMat(D, mat));
2736:                   PetscCall(MatNormalHermitianGetMat(C, mat + 1));
2737:                 }
2738:                 PetscCall(MatAXPY(mat[0], 1.0, mat[1], SUBSET_NONZERO_PATTERN));
2739:               }
2740:               PetscCall(MatPropagateSymmetryOptions(C, D));
2741:               PetscCall(MatDestroy(&C));
2742:               C = D;
2743:               /* swap pointers so that variables stay consistent throughout PCSetUp() */
2744:               std::swap(C, data->aux);
2745:               std::swap(uis, data->is);
2746:               swap = PETSC_TRUE;
2747:             }
2748:           }
2749:         }
2750:       }
2751:       if (ctx) {
2752:         PC_HPDDM              *data_00 = (PC_HPDDM *)std::get<0>(*ctx)[0]->data;
2753:         PC                     s;
2754:         Mat                    A00, P00, A01 = nullptr, A10, N, b[4];
2755:         IS                     sorted, is[2], *is_00;
2756:         MatSolverType          type;
2757:         std::pair<PC, Vec[2]> *p;

2759:         n = -1;
2760:         PetscTryMethod(data_00->levels[0]->pc, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (data_00->levels[0]->pc, &n, nullptr, &ksp));
2761:         PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
2762:         PetscCall(KSPGetOperators(ksp[0], subA, subA + 1));
2763:         PetscCall(ISGetLocalSize(data_00->is, &n));
2764:         if (n != subA[0]->rmap->n || n != subA[0]->cmap->n) {
2765:           PetscCall(PCASMGetLocalSubdomains(data_00->levels[0]->pc, &n, &is_00, nullptr));
2766:           PetscCall(ISGetLocalSize(*is_00, &n));
2767:           PetscCheck(n == subA[0]->rmap->n && n == subA[0]->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "-%spc_hpddm_schur_precondition geneo and -%spc_hpddm_define_subdomains false", pcpre ? pcpre : "", ((PetscObject)pc)->prefix);
2768:         } else is_00 = &data_00->is;
2769:         PetscCall(PCHPDDMPermute_Private(unsorted, data->is, &uis, data->aux, &C, nullptr)); /* permute since PCASM works with a sorted IS */
2770:         std::swap(C, data->aux);
2771:         std::swap(uis, data->is);
2772:         swap = PETSC_TRUE;
2773:         PetscCall(MatSchurComplementGetSubMatrices(P, &A00, &P00, std::get<1>(*ctx), &A10, nullptr));
2774:         std::get<1>(*ctx)[1] = A10;
2775:         PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATTRANSPOSEVIRTUAL, &flg));
2776:         if (flg) PetscCall(MatTransposeGetMat(A10, &A01));
2777:         else {
2778:           PetscBool flg;

2780:           PetscCall(PetscObjectTypeCompare((PetscObject)A10, MATHERMITIANTRANSPOSEVIRTUAL, &flg));
2781:           if (flg) PetscCall(MatHermitianTransposeGetMat(A10, &A01));
2782:         }
2783:         PetscCall(ISDuplicate(*is_00, &sorted)); /* during setup of the PC associated to the A00 block, this IS has already been sorted, but it's put back to its original state at the end of PCSetUp_HPDDM(), which may be unsorted */
2784:         PetscCall(ISSort(sorted));               /* this is to avoid changing users inputs, but it requires a new call to ISSort() here                                                                                               */
2785:         if (!A01) {
2786:           PetscCall(MatSetOption(A10, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
2787:           PetscCall(MatCreateSubMatrices(A10, 1, &data->is, &sorted, MAT_INITIAL_MATRIX, &sub));
2788:           b[2] = sub[0];
2789:           PetscCall(PetscObjectReference((PetscObject)sub[0]));
2790:           PetscCall(MatDestroySubMatrices(1, &sub));
2791:           PetscCall(PetscObjectTypeCompare((PetscObject)std::get<1>(*ctx)[0], MATTRANSPOSEVIRTUAL, &flg));
2792:           A10 = nullptr;
2793:           if (flg) PetscCall(MatTransposeGetMat(std::get<1>(*ctx)[0], &A10));
2794:           else {
2795:             PetscBool flg;

2797:             PetscCall(PetscObjectTypeCompare((PetscObject)std::get<1>(*ctx)[0], MATHERMITIANTRANSPOSEVIRTUAL, &flg));
2798:             if (flg) PetscCall(MatHermitianTransposeGetMat(std::get<1>(*ctx)[0], &A10));
2799:           }
2800:           if (!A10) PetscCall(MatCreateSubMatrices(std::get<1>(*ctx)[0], 1, &sorted, &data->is, MAT_INITIAL_MATRIX, &sub));
2801:           else {
2802:             if (flg) PetscCall(MatCreateTranspose(b[2], b + 1));
2803:             else PetscCall(MatCreateHermitianTranspose(b[2], b + 1));
2804:           }
2805:         } else {
2806:           PetscCall(MatSetOption(A01, MAT_SUBMAT_SINGLEIS, PETSC_TRUE));
2807:           PetscCall(MatCreateSubMatrices(A01, 1, &sorted, &data->is, MAT_INITIAL_MATRIX, &sub));
2808:           if (flg) PetscCall(MatCreateTranspose(*sub, b + 2));
2809:           else PetscCall(MatCreateHermitianTranspose(*sub, b + 2));
2810:         }
2811:         if (A01 || !A10) {
2812:           b[1] = sub[0];
2813:           PetscCall(PetscObjectReference((PetscObject)sub[0]));
2814:         }
2815:         PetscCall(MatDestroySubMatrices(1, &sub));
2816:         PetscCall(ISDestroy(&sorted));
2817:         b[3] = data->aux;
2818:         PetscCall(MatCreateSchurComplement(subA[0], subA[1], b[1], b[2], b[3], &S));
2819:         PetscCall(MatSchurComplementSetKSP(S, ksp[0]));
2820:         if (data->N != 1) {
2821:           PetscCall(PCASMSetType(data->levels[0]->pc, PC_ASM_NONE)); /* "Neumann--Neumann" preconditioning with overlap and a Boolean partition of unity */
2822:           PetscCall(PCASMSetLocalSubdomains(data->levels[0]->pc, 1, &data->is, &loc));
2823:           PetscCall(PCSetFromOptions(data->levels[0]->pc)); /* action of eq. (15) of https://hal.science/hal-02343808v6/document (with a sign flip) */
2824:           s = data->levels[0]->pc;
2825:         } else {
2826:           is[0] = data->is;
2827:           PetscCall(PetscObjectReference((PetscObject)is[0]));
2828:           PetscCall(PetscObjectReference((PetscObject)b[3]));
2829:           PetscCall(PCSetType(pc, PCASM));                          /* change the type of the current PC */
2830:           data = nullptr;                                           /* destroyed in the previous PCSetType(), so reset to NULL to avoid any faulty use */
2831:           PetscCall(PCAppendOptionsPrefix(pc, "pc_hpddm_coarse_")); /* same prefix as when using PCHPDDM with a single level */
2832:           PetscCall(PCASMSetLocalSubdomains(pc, 1, is, &loc));
2833:           PetscCall(ISDestroy(is));
2834:           PetscCall(ISDestroy(&loc));
2835:           s = pc;
2836:         }
2837:         PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(s, S, PETSC_TRUE)); /* the subdomain Mat is already known and the input IS of PCASMSetLocalSubdomains() is already sorted */
2838:         PetscTryMethod(s, "PCASMGetSubKSP_C", (PC, PetscInt *, PetscInt *, KSP **), (s, &n, nullptr, &ksp));
2839:         PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
2840:         PetscCall(KSPGetPC(ksp[0], &inner));
2841:         PetscCall(PCSetType(inner, PCSHELL)); /* compute the action of the inverse of the local Schur complement with a PCSHELL */
2842:         b[0] = subA[0];
2843:         PetscCall(MatCreateNest(PETSC_COMM_SELF, 2, nullptr, 2, nullptr, b, &N)); /* instead of computing inv(A11 - A10 inv(A00) A01), compute inv([A00, A01; A10, A11]) followed by a partial solution associated to the A11 block */
2844:         if (!data) PetscCall(PetscObjectDereference((PetscObject)b[3]));
2845:         PetscCall(PetscObjectDereference((PetscObject)b[1]));
2846:         PetscCall(PetscObjectDereference((PetscObject)b[2]));
2847:         PetscCall(PCCreate(PETSC_COMM_SELF, &s));
2848:         PetscCall(PCSetOptionsPrefix(s, ((PetscObject)inner)->prefix));
2849:         PetscCall(PCSetOptionsPrefix(inner, nullptr));
2850:         PetscCall(KSPSetSkipPCSetFromOptions(ksp[0], PETSC_TRUE));
2851:         PetscCall(PCSetType(s, PCLU));
2852:         if (PetscDefined(HAVE_MUMPS)) PetscCall(PCFactorSetMatSolverType(s, MATSOLVERMUMPS)); /* only MATSOLVERMUMPS handles MATNEST, so for the others, e.g., MATSOLVERPETSC or MATSOLVERMKL_PARDISO, convert to plain MATAIJ */
2853:         PetscCall(PCSetFromOptions(s));
2854:         PetscCall(PCFactorGetMatSolverType(s, &type));
2855:         PetscCall(PetscStrcmp(type, MATSOLVERMUMPS, &flg));
2856:         PetscCall(MatGetLocalSize(P, &n, nullptr));
2857:         if (flg || n == 0) {
2858:           PetscCall(PCSetOperators(s, N, N));
2859:           if (n) {
2860:             PetscCall(PCFactorGetMatrix(s, b));
2861:             PetscCall(MatSetOptionsPrefix(*b, ((PetscObject)s)->prefix));
2862:             n = -1;
2863:             PetscCall(PetscOptionsGetInt(((PetscObject)pc)->options, ((PetscObject)s)->prefix, "-mat_mumps_icntl_26", &n, nullptr));
2864:             if (n == 1) {                                /* allocates a square MatDense of size is[1]->map->n, so one */
2865:               PetscCall(MatNestGetISs(N, is, nullptr));  /*  needs to be able to deactivate this path when dealing    */
2866:               PetscCall(MatFactorSetSchurIS(*b, is[1])); /*  with a large constraint space in order to avoid OOM      */
2867:             }
2868:           } else PetscCall(PCSetType(s, PCNONE)); /* empty local Schur complement (e.g., centralized on another process) */
2869:         } else {
2870:           MatInfo info;

2872:           PetscCall(MatGetInfo(b[3], MAT_LOCAL, &info));
2873:           if (info.nz_used == 0.0) {
2874:             PetscCall(MatCreateSeqAIJ(PETSC_COMM_SELF, b[3]->rmap->n, b[3]->cmap->n, 1, nullptr, b + 3));
2875:             for (PetscInt i = 0; i < b[3]->rmap->n; ++i) PetscCall(MatSetValue(b[3], i, i, 0.0, INSERT_VALUES));
2876:             PetscCall(MatAssemblyBegin(b[3], MAT_FINAL_ASSEMBLY));
2877:             PetscCall(MatAssemblyEnd(b[3], MAT_FINAL_ASSEMBLY));
2878:             PetscCall(MatNestSetSubMat(N, 1, 1, b[3]));
2879:             PetscCall(PetscObjectDereference((PetscObject)b[3]));
2880:           }
2881:           PetscCall(MatConvert(N, MATAIJ, MAT_INITIAL_MATRIX, b));
2882:           PetscCall(PCSetOperators(s, N, *b));
2883:           PetscCall(PetscObjectDereference((PetscObject)*b));
2884:           PetscCall(PetscObjectTypeCompareAny((PetscObject)s, &flg, PCLU, PCCHOLESKY, PCILU, PCICC, PCQR, ""));
2885:           if (flg) {
2886:             PetscCall(PCFactorGetMatrix(s, b)); /* MATSOLVERMKL_PARDISO cannot compute in PETSc (yet) a partial solution associated to the A11 block, only partial solution associated to the A00 block or full solution */
2887:             if (info.nz_used == 0.0) {
2888:               PetscCall(PetscObjectTypeCompareAny((PetscObject)s, &flg, PCLU, PCCHOLESKY, ""));
2889:               if (flg) {
2890:                 PetscCall(MatFactorGetSolverType(*b, &type));
2891:                 PetscCall(PetscStrcmp(type, MATSOLVERPETSC, &flg));
2892:                 if (flg) {
2893:                   PetscCall(PetscOptionsHasName(((PetscObject)s)->options, ((PetscObject)s)->prefix, "-pc_factor_mat_ordering_type", &flg));
2894:                   if (!flg) PetscCall(PCFactorSetMatOrderingType(s, MATORDERINGNATURAL));
2895:                 }
2896:               }
2897:               flg = PETSC_TRUE;
2898:             }
2899:           }
2900:         }
2901:         PetscCall(PetscNew(&p));
2902:         p->first = s;
2903:         if (n != 0) PetscCall(MatCreateVecs(*b, p->second, p->second + 1));
2904:         else p->second[0] = p->second[1] = nullptr;
2905:         PetscCall(PCShellSetContext(inner, p));
2906:         PetscCall(PCShellSetApply(inner, PCApply_Nest));
2907:         PetscCall(PCShellSetView(inner, PCView_Nest));
2908:         PetscCall(PCShellSetDestroy(inner, PCDestroy_Nest));
2909:         PetscCall(PetscObjectDereference((PetscObject)N));
2910:         if (!data) {
2911:           PetscCall(MatDestroy(&S));
2912:           PetscCall(ISDestroy(&unsorted));
2913:           PetscCall(MatDestroy(&C));
2914:           PetscCall(ISDestroy(&uis));
2915:           PetscCall(PetscFree(ctx));
2916:           if (PetscDefined(USE_DEBUG)) {
2917:             PetscCall(ISDestroy(&dis));
2918:             PetscCall(MatDestroy(&daux));
2919:           }
2920:           PetscFunctionReturn(PETSC_SUCCESS);
2921:         }
2922:       }
2923:       if (!data->levels[0]->scatter) {
2924:         PetscCall(MatCreateVecs(P, &xin, nullptr));
2925:         if (ismatis) PetscCall(MatDestroy(&P));
2926:         PetscCall(VecScatterCreate(xin, data->is, data->levels[0]->D, nullptr, &data->levels[0]->scatter));
2927:         PetscCall(VecDestroy(&xin));
2928:       }
2929:       if (data->levels[0]->P) {
2930:         /* if the pattern is the same and PCSetUp() has previously succeeded, reuse HPDDM buffers and connectivity */
2931:         PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(data->levels[0], !pc->setupcalled || pc->flag == DIFFERENT_NONZERO_PATTERN ? PETSC_TRUE : PETSC_FALSE));
2932:       }
2933:       if (!data->levels[0]->P) data->levels[0]->P = new HPDDM::Schwarz<PetscScalar>();
2934:       if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_SetUp[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
2935:       else PetscCall(PetscLogEventBegin(PC_HPDDM_Strc, data->levels[0]->ksp, nullptr, nullptr, nullptr));
2936:       /* HPDDM internal data structure */
2937:       PetscCall(data->levels[0]->P->structure(loc, data->is, !ctx ? sub[0] : nullptr, ismatis ? C : data->aux, data->levels));
2938:       if (data->scaling && data->deflation) {
2939:         const PetscScalar *array;
2940:         PetscReal         *d;

2942:         PetscCall(PCHPDDMComputeScaling_Private(data, data->is, data->levels[0]->D));
2943:         PetscCall(VecGetArrayRead(data->levels[0]->D, &array));
2944:         /* HPDDM owns mutable real storage; in complex builds it is separate from the PETSc Vec */
2945:         d = const_cast<PetscReal *>(data->levels[0]->P->getScaling());
2946:         for (PetscInt i = 0; i < data->levels[0]->P->getDof(); ++i) d[i] = PetscRealPart(array[i]);
2947:         PetscCall(VecRestoreArrayRead(data->levels[0]->D, &array));
2948:       }
2949:       if (!data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_Strc, data->levels[0]->ksp, nullptr, nullptr, nullptr));
2950:       /* matrix pencil of the generalized eigenvalue problem on the overlap (GenEO) */
2951:       if (!ctx) {
2952:         if (data->deflation || overlap != -1) weighted = data->aux;
2953:         else if (!data->B) {
2954:           PetscBool cmp;

2956:           PetscCall(MatDuplicate(sub[0], MAT_COPY_VALUES, &weighted));
2957:           PetscCall(PetscObjectTypeCompareAny((PetscObject)weighted, &cmp, MATNORMAL, MATNORMALHERMITIAN, ""));
2958:           if (cmp) flg = PETSC_FALSE;
2959:           PetscCall(MatDiagonalScale(weighted, data->levels[0]->D, data->levels[0]->D));
2960:           /* neither MatDuplicate() nor MatDiagonalScale() handles the symmetry options, so propagate the options explicitly */
2961:           /* only useful for -mat_type baij -pc_hpddm_levels_1_st_pc_type cholesky (no problem with MATAIJ or MATSBAIJ)      */
2962:           PetscCall(MatPropagateSymmetryOptions(sub[0], weighted));
2963:           if (PetscDefined(USE_DEBUG) && PetscBool3ToBool(data->Neumann)) {
2964:             Mat      *sub, A[2];
2965:             PetscReal norm[2];

2967:             PetscCall(MatCreateSubMatrices(P, 1, &data->is, &data->is, MAT_INITIAL_MATRIX, &sub));
2968:             PetscCall(MatDiagonalScale(sub[0], data->levels[0]->D, data->levels[0]->D));
2969:             PetscCall(MatConvert(sub[0], MATSEQAIJ, MAT_INITIAL_MATRIX, A)); /* too many corner cases to handle (MATNORMAL, MATNORMALHERMITIAN, MATBAIJ with different block sizes...), so just MatConvert() to MATSEQAIJ since this is just for debugging */
2970:             PetscCall(MatConvert(weighted, MATSEQAIJ, MAT_INITIAL_MATRIX, A + 1));
2971:             PetscCall(MatAXPY(A[0], -1.0, A[1], UNKNOWN_NONZERO_PATTERN));
2972:             PetscCall(MatNorm(A[0], NORM_FROBENIUS, norm));
2973:             if (norm[0]) {
2974:               PetscCall(MatNorm(A[1], NORM_FROBENIUS, norm + 1));
2975:               PetscCheck(PetscAbsReal(norm[0] / norm[1]) < PetscSqrtReal(PETSC_SMALL), PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Auxiliary Mat is different from the (assembled) subdomain Mat for the interior unknowns, so it cannot be the Neumann matrix, remove -%spc_hpddm_has_neumann", pcpre ? pcpre : "");
2976:             }
2977:             PetscCall(MatDestroySubMatrices(1, &sub));
2978:             for (PetscInt i = 0; i < 2; ++i) PetscCall(MatDestroy(A + i));
2979:           }
2980:         } else weighted = data->B;
2981:       } else weighted = nullptr;
2982:       /* SLEPc is used inside the loaded symbol */
2983:       PetscCall((*loadedSym)(data->levels[0]->P, data->is, ismatis ? C : (algebraic && !block && overlap == -1 ? sub[0] : (!ctx ? data->aux : S)), weighted, data->B, initial, data->levels));
2984:       if (!ctx && data->share && overlap == -1) {
2985:         Mat st[2];

2987:         PetscCheck(ksp && ksp[0], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing shared subdomain KSP");
2988:         PetscCall(KSPGetOperators(ksp[0], st, st + 1));
2989:         PetscCall(MatCopy(subA[0], st[0], structure));
2990:         if (subA[1] != subA[0] || st[1] != st[0]) PetscCall(MatCopy(subA[1], st[1], SAME_NONZERO_PATTERN));
2991:         PetscCall(PetscObjectDereference((PetscObject)subA[0]));
2992:       }
2993:       if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_SetUp[0], data->levels[0]->ksp, nullptr, nullptr, nullptr));
2994:       if (ismatis) PetscCall(MatISGetLocalMat(C, &N));
2995:       else N = data->aux;
2996:       if (!ctx) P = sub[0];
2997:       else P = S;
2998:       /* going through the grid hierarchy */
2999:       for (n = 1; n < data->N; ++n) {
3000:         if (data->log_separate) PetscCall(PetscLogEventBegin(PC_HPDDM_SetUp[n], data->levels[n]->ksp, nullptr, nullptr, nullptr));
3001:         /* method composed in the loaded symbol since there, SLEPc is used as well */
3002:         PetscTryMethod(data->levels[0]->ksp, "PCHPDDMSetUp_Private_C", (Mat *, Mat *, PetscInt, PetscInt *const, PC_HPDDM_Level **const), (&P, &N, n, &data->N, data->levels));
3003:         if (data->log_separate) PetscCall(PetscLogEventEnd(PC_HPDDM_SetUp[n], data->levels[n]->ksp, nullptr, nullptr, nullptr));
3004:       }
3005:       /* reset to NULL to avoid any faulty use */
3006:       PetscCall(PetscObjectComposeFunction((PetscObject)data->levels[0]->ksp, "PCHPDDMSetUp_Private_C", nullptr));
3007:       if (!ismatis) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_C", nullptr));
3008:       else PetscCall(PetscObjectDereference((PetscObject)C)); /* matching PetscObjectReference() above */
3009:       for (n = 0; n < data->N - 1; ++n) {
3010:         /* HPDDM internal work buffers */
3011:         if (data->levels[n]->P) PetscCallCXX(data->levels[n]->P->start());
3012:       }
3013:       if (ismatis || !subdomains) PetscCall(PCHPDDMDestroySubMatrices_Private(PetscBool3ToBool(data->Neumann), PetscBool(algebraic && !block && overlap == -1), sub));
3014:       if (ismatis) data->is = nullptr;
3015:       for (n = 0; n < data->N - 1 + (reused > 0); ++n) {
3016:         if (data->levels[n]->P) {
3017:           PC spc;

3019:           /* force the PC to be PCSHELL to do the coarse grid corrections */
3020:           PetscCall(KSPSetSkipPCSetFromOptions(data->levels[n]->ksp, PETSC_TRUE));
3021:           PetscCall(KSPGetPC(data->levels[n]->ksp, &spc));
3022:           PetscCall(PCSetType(spc, PCSHELL));
3023:           PetscCall(PCShellSetContext(spc, data->levels[n]));
3024:           spc->ops->reset = PCReset_HPDDMShell;
3025:           PetscCall(PCShellSetSetUp(spc, PCSetUp_HPDDMShell));
3026:           PetscCall(PCShellSetApply(spc, PCApply_HPDDMShell));
3027:           PetscCall(PCShellSetMatApply(spc, PCMatApply_HPDDMShell));
3028:           PetscCall(PCShellSetApplyTranspose(spc, PCApplyTranspose_HPDDMShell));
3029:           PetscCall(PCShellSetMatApplyTranspose(spc, PCMatApplyTranspose_HPDDMShell));
3030:           if (ctx && n == 0) {
3031:             Mat                               Amat, Pmat;
3032:             PetscInt                          m, M;
3033:             std::tuple<Mat, PetscSF, Vec[2]> *ctx;

3035:             PetscCall(KSPGetOperators(data->levels[n]->ksp, nullptr, &Pmat));
3036:             PetscCall(MatGetLocalSize(Pmat, &m, nullptr));
3037:             PetscCall(MatGetSize(Pmat, &M, nullptr));
3038:             PetscCall(PetscNew(&ctx));
3039:             std::get<0>(*ctx) = S;
3040:             std::get<1>(*ctx) = data->levels[n]->scatter;
3041:             PetscCall(MatCreateShell(PetscObjectComm((PetscObject)data->levels[n]->ksp), m, m, M, M, ctx, &Amat));
3042:             PetscCall(MatShellSetOperation(Amat, MATOP_MULT, (PetscErrorCodeFn *)MatMult_Schur<false>));
3043:             PetscCall(MatShellSetOperation(Amat, MATOP_MULT_TRANSPOSE, (PetscErrorCodeFn *)MatMult_Schur<true>));
3044:             PetscCall(MatShellSetOperation(Amat, MATOP_DESTROY, (PetscErrorCodeFn *)MatDestroy_Schur));
3045:             PetscCall(MatCreateVecs(S, std::get<2>(*ctx), std::get<2>(*ctx) + 1));
3046:             PetscCall(KSPSetOperators(data->levels[n]->ksp, Amat, Pmat));
3047:             PetscCall(PetscObjectDereference((PetscObject)Amat));
3048:           }
3049:           PetscCall(PCShellSetDestroy(spc, PCDestroy_HPDDMShell));
3050:           if (!data->levels[n]->pc) PetscCall(PCCreate(PetscObjectComm((PetscObject)data->levels[n]->ksp), &data->levels[n]->pc));
3051:           if (n < reused) {
3052:             PetscCall(PCSetReusePreconditioner(spc, PETSC_TRUE));
3053:             PetscCall(PCSetReusePreconditioner(data->levels[n]->pc, PETSC_TRUE));
3054:           }
3055:           PetscCall(PCSetUp(spc));
3056:         }
3057:       }
3058:       if (ctx) PetscCall(MatDestroy(&S));
3059:       if (overlap == -1) PetscCall(PetscObjectComposeFunction((PetscObject)pc->pmat, "PCHPDDMAlgebraicAuxiliaryMat_Private_C", nullptr));
3060:     } else flg = reused ? PETSC_FALSE : PETSC_TRUE;
3061:     if (!ismatis && subdomains) {
3062:       if (flg) PetscCall(KSPGetPC(data->levels[0]->ksp, &inner));
3063:       else inner = data->levels[0]->pc;
3064:       if (inner) {
3065:         if (subdomains) {
3066:           if (!inner->setupcalled) {
3067:             PetscCall(PCSetType(inner, PCASM));
3068:             if (data->scaling) PetscCall(PCASMSetType(inner, PC_ASM_WEIGHTED));
3069:           }
3070:           PetscCall(PCSetFromOptions(inner));
3071:           PetscCall(PCSetModifySubMatrices(inner, pc->modifysubmatrices, pc->modifysubmatricesP));
3072:         }
3073:         PetscCall(PetscStrcmp(((PetscObject)inner)->type_name, PCASM, &flg));
3074:         if (flg) {
3075:           if (!PetscBool3ToBool(data->Neumann) && reused > 0 && reused == requested - 1 && inner->setupcalled) {
3076:             IS  *is;
3077:             Mat *sub;

3079:             PetscCall(PCASMGetLocalSubdomains(inner, &n, &is, nullptr));
3080:             PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "Number of subdomain solver %" PetscInt_FMT " != 1", n);
3081:             PetscCall(MatCreateSubMatrices(P, n, is, is, MAT_INITIAL_MATRIX, &sub));
3082:             PetscCall(PCSetOperators(inner, A, P));
3083:             PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(inner, sub[0], PETSC_FALSE));
3084:             PetscCall(MatDestroySubMatrices(n, &sub));
3085:           } else if (subdomains) {
3086:             if (!inner->setupcalled) { /* evaluates to PETSC_FALSE when -pc_hpddm_block_splitting */
3087:               IS sorted;               /* PCASM will sort the input IS, duplicate it to return an unmodified (PCHPDDM) input IS */

3089:               PetscCall(ISDuplicate(is[0], &sorted));
3090:               PetscCall(PCASMSetLocalSubdomains(inner, 1, &sorted, &loc));
3091:               PetscCall(PetscObjectDereference((PetscObject)sorted));
3092:             }
3093:             if (!PetscBool3ToBool(data->Neumann) && data->N > 1) { /* subdomain matrices are already created for the eigenproblem, reuse them for the fine-level PC */
3094:               PetscCall(PCHPDDMPermute_Private(*is, nullptr, nullptr, sub[0], &P, nullptr));
3095:               PetscCall(PCHPDDMCommunicationAvoidingPCASM_Private(inner, P, algebraic));
3096:               PetscCall(PetscObjectDereference((PetscObject)P));
3097:             }
3098:           }
3099:         }
3100:       }
3101:       if (data->N > 1) {
3102:         if (overlap != 1) PetscCall(PCHPDDMDestroySubMatrices_Private(PetscBool3ToBool(data->Neumann), PetscBool(algebraic && !block && overlap == -1), sub));
3103:         else PetscCall(MatDestroy(subA));
3104:       }
3105:     }
3106:     PetscCall(ISDestroy(&loc));
3107:   } else data->N = 1; /* reused levels are added back below */
3108:   if (requested != data->N + reused) {
3109:     PetscCall(PetscInfo(pc, "%" PetscInt_FMT " levels requested, only %" PetscInt_FMT " built + %" PetscInt_FMT " reused. Options for level(s) > %" PetscInt_FMT ", including -%spc_hpddm_coarse_ will not be taken into account\n", requested, data->N, reused,
3110:                         data->N, pcpre ? pcpre : ""));
3111:     PetscCall(PetscInfo(pc, "It is best to tune parameters, e.g., a higher value for -%spc_hpddm_levels_%" PetscInt_FMT "_eps_threshold_absolute or a lower value for -%spc_hpddm_levels_%" PetscInt_FMT "_svd_threshold_relative, so that at least one local deflation vector will be selected\n", pcpre ? pcpre : "",
3112:                         data->N, pcpre ? pcpre : "", data->N));
3113:     /* cannot use PCDestroy_HPDDMShell() because PCSHELL not set for unassembled levels */
3114:     for (n = data->N - 1; n < requested - 1; ++n) {
3115:       if (data->levels[n]->P) {
3116:         PetscCall(HPDDM::Schwarz<PetscScalar>::destroy(data->levels[n], PETSC_TRUE));
3117:         PetscCall(VecDestroyVecs(1, &data->levels[n]->v[0]));
3118:         PetscCall(VecDestroyVecs(2, &data->levels[n]->v[1]));
3119:         PetscCall(VecDestroy(&data->levels[n]->D));
3120:         PetscCall(PetscSFDestroy(&data->levels[n]->scatter));
3121:       }
3122:     }
3123:     if (reused) {
3124:       for (n = reused; n < PETSC_PCHPDDM_MAXLEVELS && data->levels[n]; ++n) {
3125:         PetscCall(KSPDestroy(&data->levels[n]->ksp));
3126:         PetscCall(PCDestroy(&data->levels[n]->pc));
3127:       }
3128:     }
3129:     PetscCheck(!PetscDefined(USE_DEBUG), PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "%" PetscInt_FMT " levels requested, only %" PetscInt_FMT " built + %" PetscInt_FMT " reused. Options for level(s) > %" PetscInt_FMT ", including -%spc_hpddm_coarse_ will not be taken into account. It is best to tune parameters, e.g., a higher value for -%spc_hpddm_levels_%" PetscInt_FMT "_eps_threshold or a lower value for -%spc_hpddm_levels_%" PetscInt_FMT "_svd_threshold_relative, so that at least one local deflation vector will be selected. If you don't want this to error out, compile --with-debugging=0", requested,
3130:                data->N, reused, data->N, pcpre ? pcpre : "", pcpre ? pcpre : "", data->N, pcpre ? pcpre : "", data->N);
3131:   }
3132:   /* these solvers are created after PCSetFromOptions() is called */
3133:   if (pc->setfromoptionscalled) {
3134:     for (n = 0; n < data->N; ++n) {
3135:       if (data->levels[n]->ksp) PetscCall(KSPSetFromOptions(data->levels[n]->ksp));
3136:       if (data->levels[n]->pc) PetscCall(PCSetFromOptions(data->levels[n]->pc));
3137:     }
3138:     pc->setfromoptionscalled = 0;
3139:   }
3140:   data->N += reused;
3141:   if (data->share && swap) {
3142:     /* swap back pointers so that variables follow the user-provided numbering */
3143:     std::swap(C, data->aux);
3144:     std::swap(uis, data->is);
3145:     PetscCall(MatDestroy(&C));
3146:     PetscCall(ISDestroy(&uis));
3147:   }
3148:   if (data->scaling) {
3149:     if (!data->levels[0]->pc) PetscCall(KSPGetPC(data->levels[0]->ksp, &inner)); /* single level: inspect directly the PC attached to the KSP */
3150:     else inner = data->levels[0]->pc;
3151:     PetscCall(PetscObjectTypeCompare((PetscObject)inner, PCASM, &flg));
3152:     if (flg) {
3153:       PCASMType type;

3155:       PetscCall(PCASMGetType(inner, &type));
3156:       flg = (type == PC_ASM_WEIGHTED ? PETSC_TRUE : PETSC_FALSE);
3157:     }
3158:     if (flg) { /* forward the scaling to PC_ASM_WEIGHTED, otherwise it only scales the coarse space */
3159:       IS *is;

3161:       PetscCall(PCSetUp(inner));
3162:       PetscCall(PCASMGetLocalSubdomains(inner, &n, &is, nullptr));
3163:       PetscCheck(n == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "User-supplied scaling requires one overlapping subdomain per process");
3164:       PetscCall(PCASMGetLocalSubmatrices(inner, nullptr, &sub));
3165:       PetscCall(MatCreateVecs(sub[0], &v, nullptr));
3166:       PetscCall(PCHPDDMComputeScaling_Private(data, is[0], v));
3167:       PetscCall(PCASMWeightedSetScaling(inner, 1, &v));
3168:       PetscCall(VecDestroy(&v));
3169:     }
3170:   }
3171:   if (algebraic) PetscCall(MatDestroy(&data->aux));
3172:   if (unsorted && unsorted != is[0]) {
3173:     PetscCall(ISCopy(unsorted, data->is));
3174:     PetscCall(ISDestroy(&unsorted));
3175:   }
3176:   if (PetscDefined(USE_DEBUG)) {
3177:     PetscCheck((data->is && dis) || (!data->is && !dis), PETSC_COMM_SELF, PETSC_ERR_PLIB, "An IS pointer is NULL but not the other: input IS pointer (%p) v. output IS pointer (%p)", (void *)dis, (void *)data->is);
3178:     if (data->is) {
3179:       PetscCall(ISEqualUnsorted(data->is, dis, &flg));
3180:       PetscCall(ISDestroy(&dis));
3181:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input IS and output IS are not equal");
3182:     }
3183:     PetscCheck((data->aux && daux) || (!data->aux && !daux), PETSC_COMM_SELF, PETSC_ERR_PLIB, "A Mat pointer is NULL but not the other: input Mat pointer (%p) v. output Mat pointer (%p)", (void *)daux, (void *)data->aux);
3184:     if (data->aux) {
3185:       PetscCall(MatMultEqual(data->aux, daux, 20, &flg));
3186:       PetscCall(MatDestroy(&daux));
3187:       PetscCheck(flg, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Input Mat and output Mat are not equal");
3188:     }
3189:   }
3190:   PetscFunctionReturn(PETSC_SUCCESS);
3191: }

3193: /*@
3194:   PCHPDDMSetCoarseCorrectionType - Sets the coarse correction type.

3196:   Collective

3198:   Input Parameters:
3199: + pc   - preconditioner context
3200: - type - coarse correction type, see `PCHPDDMCoarseCorrectionType`

3202:   Options Database Key:
3203: . -pc_hpddm_coarse_correction (deflated|additive|balanced|none|deflated_reversed) - type of coarse correction to apply

3205:   Level: intermediate

3207: .seealso: [](ch_ksp), `PCHPDDMGetCoarseCorrectionType()`, `PCHPDDM`, `PCHPDDMCoarseCorrectionType`
3208: @*/
3209: PetscErrorCode PCHPDDMSetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType type)
3210: {
3211:   PetscFunctionBegin;
3214:   PetscTryMethod(pc, "PCHPDDMSetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType), (pc, type));
3215:   PetscFunctionReturn(PETSC_SUCCESS);
3216: }

3218: /*@
3219:   PCHPDDMGetCoarseCorrectionType - Gets the coarse correction type.

3221:   Input Parameter:
3222: . pc - preconditioner context

3224:   Output Parameter:
3225: . type - coarse correction type, see `PCHPDDMCoarseCorrectionType`

3227:   Level: intermediate

3229: .seealso: [](ch_ksp), `PCHPDDMSetCoarseCorrectionType()`, `PCHPDDM`, `PCHPDDMCoarseCorrectionType`
3230: @*/
3231: PetscErrorCode PCHPDDMGetCoarseCorrectionType(PC pc, PCHPDDMCoarseCorrectionType *type)
3232: {
3233:   PetscFunctionBegin;
3235:   if (type) {
3236:     PetscAssertPointer(type, 2);
3237:     PetscUseMethod(pc, "PCHPDDMGetCoarseCorrectionType_C", (PC, PCHPDDMCoarseCorrectionType *), (pc, type));
3238:   }
3239:   PetscFunctionReturn(PETSC_SUCCESS);
3240: }

3242: static PetscErrorCode PCHPDDMSetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType type)
3243: {
3244:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

3246:   PetscFunctionBegin;
3247:   data->correction = type;
3248:   PetscFunctionReturn(PETSC_SUCCESS);
3249: }

3251: static PetscErrorCode PCHPDDMGetCoarseCorrectionType_HPDDM(PC pc, PCHPDDMCoarseCorrectionType *type)
3252: {
3253:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

3255:   PetscFunctionBegin;
3256:   *type = data->correction;
3257:   PetscFunctionReturn(PETSC_SUCCESS);
3258: }

3260: /*@
3261:   PCHPDDMSetSTShareSubKSP - Sets whether the `KSP` in SLEPc `ST` and the fine-level subdomain solver should be shared.

3263:   Input Parameters:
3264: + pc    - preconditioner context
3265: - share - whether the `KSP` should be shared or not

3267:   Note:
3268:   This is not the same as `PCSetReusePreconditioner()`. Given certain conditions (visible using -info), a symbolic factorization can be skipped
3269:   when using a subdomain `PCType` such as `PCLU` or `PCCHOLESKY`.

3271:   Level: advanced

3273: .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMGetSTShareSubKSP()`
3274: @*/
3275: PetscErrorCode PCHPDDMSetSTShareSubKSP(PC pc, PetscBool share)
3276: {
3277:   PetscFunctionBegin;
3279:   PetscTryMethod(pc, "PCHPDDMSetSTShareSubKSP_C", (PC, PetscBool), (pc, share));
3280:   PetscFunctionReturn(PETSC_SUCCESS);
3281: }

3283: /*@
3284:   PCHPDDMGetSTShareSubKSP - Gets whether the `KSP` in SLEPc `ST` and the fine-level subdomain solver is shared.

3286:   Input Parameter:
3287: . pc - preconditioner context

3289:   Output Parameter:
3290: . share - whether the `KSP` is shared or not

3292:   Note:
3293:   This is not the same as `PCGetReusePreconditioner()`. The return value is unlikely to be true, but when it is, a symbolic factorization can be skipped
3294:   when using a subdomain `PCType` such as `PCLU` or `PCCHOLESKY`.

3296:   Level: advanced

3298: .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetSTShareSubKSP()`
3299: @*/
3300: PetscErrorCode PCHPDDMGetSTShareSubKSP(PC pc, PetscBool *share)
3301: {
3302:   PetscFunctionBegin;
3304:   if (share) {
3305:     PetscAssertPointer(share, 2);
3306:     PetscUseMethod(pc, "PCHPDDMGetSTShareSubKSP_C", (PC, PetscBool *), (pc, share));
3307:   }
3308:   PetscFunctionReturn(PETSC_SUCCESS);
3309: }

3311: static PetscErrorCode PCHPDDMSetSTShareSubKSP_HPDDM(PC pc, PetscBool share)
3312: {
3313:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

3315:   PetscFunctionBegin;
3316:   data->share = share;
3317:   PetscFunctionReturn(PETSC_SUCCESS);
3318: }

3320: static PetscErrorCode PCHPDDMGetSTShareSubKSP_HPDDM(PC pc, PetscBool *share)
3321: {
3322:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

3324:   PetscFunctionBegin;
3325:   *share = data->share;
3326:   PetscFunctionReturn(PETSC_SUCCESS);
3327: }

3329: /*@
3330:   PCHPDDMSetDeflationMat - Sets the deflation space used to assemble a coarser operator.

3332:   Logically Collective; `U` must be `NULL` on all processes or on none

3334:   Input Parameters:
3335: + pc - preconditioner context
3336: . is - index set of the local deflation matrix, or `NULL` to use the stored one
3337: - U  - deflation sequential matrix stored as a `MATSEQDENSE`, or `NULL` to remove the stored one

3339:   Level: advanced

3341:   Notes:
3342:   The `is` argument is shared with `PCHPDDMSetScaling()`. Both routines can be called in any order, or
3343:   only one of them. If `is` is not `NULL`, it replaces the stored one, and a stored scaling is kept and
3344:   must have the same size. If `is` is `NULL`, the stored one, which must exist, is used. When `U` is
3345:   `NULL`, `is` must be `NULL` too, and the stored one is discarded unless a scaling still uses it; remove
3346:   the deflation space before `PCSetUp()`, or call `PCReset()`, which discards the deflation space, the
3347:   scaling, and their index set.

3349: .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetScaling()`, `PCDeflationSetSpace()`, `PCMGSetRestriction()`
3350: @*/
3351: PetscErrorCode PCHPDDMSetDeflationMat(PC pc, IS is, Mat U)
3352: {
3353:   PetscFunctionBegin;
3357:   PetscTryMethod(pc, "PCHPDDMSetDeflationMat_C", (PC, IS, Mat), (pc, is, U));
3358:   PetscFunctionReturn(PETSC_SUCCESS);
3359: }

3361: static PetscErrorCode PCHPDDMSetDeflationMat_HPDDM(PC pc, IS is, Mat U)
3362: {
3363:   PC_HPDDM *data    = (PC_HPDDM *)pc->data;
3364:   Vec       scaling = data->scaling;

3366:   PetscFunctionBegin;
3367:   if (U) {
3368:     if (!is) is = data->is;
3369:     PetscCheck(is, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No stored IS, supply one to PCHPDDMSetDeflationMat() or PCHPDDMSetScaling()");
3370:     if (scaling) {
3371:       PetscInt n, m;

3373:       PetscCall(ISGetLocalSize(is, &n));
3374:       PetscCall(VecGetSize(scaling, &m));
3375:       PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "IS has size %" PetscInt_FMT ", but the stored scaling has size %" PetscInt_FMT, n, m);
3376:       PetscCall(PetscObjectReference((PetscObject)scaling));
3377:     }
3378:     /* the scaling shares the IS, but PCHPDDMSetAuxiliaryMat_Private() destroys it if it resets the PC */
3379:     PetscCall(PCHPDDMSetAuxiliaryMat_Private(pc, is, U, PETSC_TRUE));
3380:     PetscCall(VecDestroy(&data->scaling));
3381:     data->scaling = scaling;
3382:   } else {
3383:     PetscCheck(!is, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Pass a NULL IS to remove the deflation space");
3384:     PetscCheck(!pc->setupcalled, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Remove the deflation space before PCSetUp() or after PCReset()");
3385:     if (data->deflation) {
3386:       PetscCall(MatDestroy(&data->aux));
3387:       data->deflation = PETSC_FALSE;
3388:     }
3389:     if (!data->aux && !scaling) PetscCall(ISDestroy(&data->is));
3390:   }
3391:   PetscFunctionReturn(PETSC_SUCCESS);
3392: }

3394: /*@
3395:   PCHPDDMSetScaling - Sets a diagonal scaling for supplied deflation vectors and, by default, the fine-level `PCASM`

3397:   Logically Collective; `scaling` must be `NULL` on all processes or on none

3399:   Input Parameters:
3400: + pc      - preconditioner context
3401: . is      - index set of the local scaling, or `NULL` to use the stored one
3402: - scaling - local diagonal scaling, or `NULL` to remove the stored one and restore the default Boolean scaling before setup

3404:   Level: advanced

3406:   Notes:
3407:   The `is` argument is shared with `PCHPDDMSetDeflationMat()`. Both routines can be called in any
3408:   order before `PCSetUp()`, and the second call can provide `NULL` for `is`.

3410:   Setting a scaling sets the default `PCASMType` of the fine-level `PCASM` to `PC_ASM_WEIGHTED`. It can be changed with
3411:   `-pc_hpddm_levels_1_pc_asm_type`, or `-pc_hpddm_coarse_pc_asm_type` with a single level; the scaling then only applies
3412:   to the coarse correction, if any.

3414:   Currently, this cannot be used when `PCHPDDM` generates the second level with `PCHPDDMSetAuxiliaryMat()`.

3416: .seealso: [](ch_ksp), `PCHPDDM`, `PCHPDDMSetDeflationMat()`, `PCASMWeightedSetScaling()`, `PCHPDDMSetCoarseCorrectionType()`
3417: @*/
3418: PetscErrorCode PCHPDDMSetScaling(PC pc, IS is, Vec scaling)
3419: {
3420:   PetscFunctionBegin;
3424:   PetscTryMethod(pc, "PCHPDDMSetScaling_C", (PC, IS, Vec), (pc, is, scaling));
3425:   PetscFunctionReturn(PETSC_SUCCESS);
3426: }

3428: static PetscErrorCode PCHPDDMSetScaling_HPDDM(PC pc, IS is, Vec scaling)
3429: {
3430:   PC_HPDDM *data = (PC_HPDDM *)pc->data;

3432:   PetscFunctionBegin;
3433:   PetscCheck(!pc->setupcalled, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Set the scaling before PCSetUp() or after PCReset()");
3434:   if (scaling) {
3435:     const PetscScalar *array;
3436:     PetscInt           n, m;
3437:     PetscMPIInt        size;
3438:     PetscBool          valid = PETSC_TRUE;

3440:     PetscCheck(!data->aux || data->deflation, PETSC_COMM_SELF, PETSC_ERR_SUP, "User-supplied scaling cannot be combined with an auxiliary matrix supplied with PCHPDDMSetAuxiliaryMat()");
3441:     if (!is) is = data->is;
3442:     PetscCheck(is, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No stored IS, supply one to PCHPDDMSetScaling() or PCHPDDMSetDeflationMat()");
3443:     PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)scaling), &size));
3444:     PetscCheck(size == 1, PETSC_COMM_SELF, PETSC_ERR_WRONG_MPI_SIZE, "Scaling must have a single-process communicator");
3445:     PetscCall(VecGetSize(scaling, &n));
3446:     PetscCall(ISGetLocalSize(is, &m));
3447:     PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Scaling has size %" PetscInt_FMT ", expected %" PetscInt_FMT, n, m);
3448:     if (data->aux && is != data->is) {
3449:       PetscCall(MatGetLocalSize(data->aux, &n, nullptr));
3450:       PetscCheck(n == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "IS has size %" PetscInt_FMT ", but the stored matrix has %" PetscInt_FMT " rows", m, n);
3451:     }
3452:     PetscCall(VecGetArrayRead(scaling, &array));
3453:     valid = static_cast<PetscBool>(m == 0 || std::all_of(array, array + m, [](const PetscScalar &v) { return PetscImaginaryPart(v) == 0 && PetscRealPart(v) >= 0 && !PetscIsInfOrNanScalar(v); }));
3454:     PetscCall(VecRestoreArrayRead(scaling, &array));
3455:     PetscCheck(valid, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Scaling must contain finite, real, nonnegative entries");
3456:     PetscCall(PetscObjectReference((PetscObject)scaling));
3457:     PetscCall(PetscObjectReference((PetscObject)is));
3458:     PetscCall(ISDestroy(&data->is));
3459:     data->is = is;
3460:   } else {
3461:     PetscCheck(!is, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Pass a NULL IS to remove previously stored scaling");
3462:     if (!data->aux) PetscCall(ISDestroy(&data->is));
3463:   }
3464:   PetscCall(VecDestroy(&data->scaling));
3465:   data->scaling = scaling;
3466:   PetscFunctionReturn(PETSC_SUCCESS);
3467: }

3469: PetscErrorCode HPDDMLoadDL_Private(PetscBool *found)
3470: {
3471:   PetscBool flg;
3472:   char      lib[PETSC_MAX_PATH_LEN], dlib[PETSC_MAX_PATH_LEN], dir[PETSC_MAX_PATH_LEN];

3474:   PetscFunctionBegin;
3475:   PetscAssertPointer(found, 1);
3476:   PetscCall(PetscStrncpy(dir, "${PETSC_LIB_DIR}", sizeof(dir)));
3477:   PetscCall(PetscOptionsGetString(nullptr, nullptr, "-hpddm_dir", dir, sizeof(dir), nullptr));
3478:   PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir));
3479:   PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
3480: #if defined(SLEPC_LIB_DIR) /* this variable is passed during SLEPc ./configure when PETSc has not been configured   */
3481:   if (!*found) {           /* with --download-hpddm since slepcconf.h is not yet built (and thus can't be included) */
3482:     PetscCall(PetscStrncpy(dir, HPDDM_STR(SLEPC_LIB_DIR), sizeof(dir)));
3483:     PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/libhpddm_petsc", dir));
3484:     PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
3485:   }
3486: #endif
3487:   if (!*found) { /* probable options for this to evaluate to PETSC_TRUE: system inconsistency (libhpddm_petsc moved by user?) or PETSc configured without --download-slepc */
3488:     PetscCall(PetscOptionsGetenv(PETSC_COMM_SELF, "SLEPC_DIR", dir, sizeof(dir), &flg));
3489:     if (flg) { /* if both PETSc and SLEPc are configured with --download-hpddm but PETSc has been configured without --download-slepc, one must ensure that libslepc is loaded before libhpddm_petsc */
3490:       PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/lib/libslepc", dir));
3491:       PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
3492:       PetscCheck(*found, PETSC_COMM_SELF, PETSC_ERR_PLIB, "%s not found but SLEPC_DIR=%s", lib, dir);
3493:       PetscCall(PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib));
3494:       PetscCall(PetscSNPrintf(lib, sizeof(lib), "%s/lib/libhpddm_petsc", dir)); /* libhpddm_petsc is always in the same directory as libslepc */
3495:       PetscCall(PetscDLLibraryRetrieve(PETSC_COMM_SELF, lib, dlib, 1024, found));
3496:     }
3497:   }
3498:   PetscCheck(*found, PETSC_COMM_SELF, PETSC_ERR_PLIB, "%s not found", lib);
3499:   PetscCall(PetscDLLibraryAppend(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, dlib));
3500:   PetscFunctionReturn(PETSC_SUCCESS);
3501: }

3503: /*MC
3504:    PCHPDDM - Interface with the HPDDM library.

3506:    This `PC` may be used to build multilevel spectral domain decomposition methods based on the GenEO framework {cite}`spillane2011robust` {cite}`al2021multilevel`.
3507:    It may be viewed as an alternative to spectral
3508:    AMGe or `PCBDDC` with adaptive selection of constraints. The interface is explained in details in {cite}`jolivetromanzampini2020`

3510:    The matrix used for building the preconditioner (Pmat) may be unassembled (`MATIS`), assembled (`MATAIJ`, `MATBAIJ`, or `MATSBAIJ`), hierarchical (`MATHTOOL`), `MATNORMAL`, `MATNORMALHERMITIAN`, or `MATSCHURCOMPLEMENT` (when `PCHPDDM` is used as part of an outer `PCFIELDSPLIT`).

3512:    For multilevel preconditioning, when using an assembled or hierarchical Pmat, one must provide an auxiliary local `Mat` (unassembled local operator for GenEO) using
3513:    `PCHPDDMSetAuxiliaryMat()`. Calling this routine is not needed when using a `MATIS` Pmat, assembly is done internally using `MatConvert()`.

3515:    Options Database Keys:
3516: +   -pc_hpddm_define_subdomains (true|false) - on the finest level, calls `PCASMSetLocalSubdomains()` with the `IS` supplied in `PCHPDDMSetAuxiliaryMat()`
3517:                                                (not relevant with an unassembled Pmat)
3518: .   -pc_hpddm_has_neumann (true|false)       - on the finest level, informs the `PC` that the local Neumann matrix is supplied in `PCHPDDMSetAuxiliaryMat()`
3519: -   -pc_hpddm_coarse_correction type         - determines the `PCHPDDMCoarseCorrectionType` when calling `PCApply()` default is `deflated`

3521:    Options for subdomain solvers, subdomain eigensolvers (for computing deflation vectors), and the coarse solver can be set using the following options database prefixes.
3522: .vb
3523:       -pc_hpddm_levels_%d_pc_
3524:       -pc_hpddm_levels_%d_ksp_
3525:       -pc_hpddm_levels_%d_eps_
3526:       -pc_hpddm_levels_%d_p
3527:       -pc_hpddm_levels_%d_mat_type
3528:       -pc_hpddm_coarse_
3529:       -pc_hpddm_coarse_p
3530:       -pc_hpddm_coarse_mat_type
3531:       -pc_hpddm_coarse_mat_filter
3532: .ve

3534:    E.g., `-pc_hpddm_levels_1_sub_pc_type lu -pc_hpddm_levels_1_eps_nev 10 -pc_hpddm_levels_2_p 4 -pc_hpddm_levels_2_sub_pc_type lu -pc_hpddm_levels_2_eps_nev 10
3535:     -pc_hpddm_coarse_p 2 -pc_hpddm_coarse_mat_type baij` will use 10 deflation vectors per subdomain on the fine "level 1",
3536:     aggregate the fine subdomains into 4 "level 2" subdomains, then use 10 deflation vectors per subdomain on "level 2",
3537:     and assemble the coarse matrix (of dimension 4 x 10 = 40) on two processes as a `MATBAIJ` (default is `MATSBAIJ`).

3539:    In order to activate a "level N+1" coarse correction, it is mandatory to call `-pc_hpddm_levels_N_eps_nev nu` or `-pc_hpddm_levels_N_eps_threshold_absolute val`. The default `-pc_hpddm_coarse_p value` is 1, meaning that the coarse operator is aggregated on a single process.

3541:    Level: intermediate

3543:    Notes:
3544:    This preconditioner requires that PETSc is built with SLEPc (`--download-slepc`).

3546:    By default, the underlying concurrent eigenproblems
3547:    are solved using SLEPc shift-and-invert spectral transformation. This is usually what gives the best performance for GenEO, cf.
3548:    {cite}`spillane2011robust` {cite}`jolivet2013scalabledd`. As
3549:    stated above, SLEPc options are available through `-pc_hpddm_levels_%d_`, e.g., `-pc_hpddm_levels_1_eps_type arpack -pc_hpddm_levels_1_eps_nev 10
3550:    -pc_hpddm_levels_1_st_type sinvert`. There are furthermore three options related to the (subdomain-wise local) eigensolver that are not described in
3551:    SLEPc documentation since they are specific to `PCHPDDM`.
3552: .vb
3553:       -pc_hpddm_levels_1_st_share_sub_ksp
3554:       -pc_hpddm_levels_%d_eps_threshold_absolute
3555:       -pc_hpddm_levels_1_eps_use_inertia
3556: .ve

3558:    The first option from the list only applies to the fine-level eigensolver, see `PCHPDDMSetSTShareSubKSP()`. The second option from the list is
3559:    used to filter eigenmodes retrieved after convergence of `EPSSolve()` at "level N" such that eigenvectors used to define a "level N+1" coarse
3560:    correction are associated to eigenvalues whose magnitude are lower or equal than `-pc_hpddm_levels_N_eps_threshold_absolute`. When using an `EPS` which cannot
3561:    determine a priori the proper `-pc_hpddm_levels_N_eps_nev` such that all wanted eigenmodes are retrieved, it is possible to get an estimation of the
3562:    correct value using the third option from the list, `-pc_hpddm_levels_1_eps_use_inertia`, see `MatGetInertia()`. In that case, there is no need
3563:    to supply `-pc_hpddm_levels_1_eps_nev`. This last option also only applies to the fine-level (N = 1) eigensolver.

3565:    See also {cite}`dolean2015introduction`, {cite}`al2022robust`, {cite}`al2022robustpd`, and {cite}`nataf2022recent`

3567: .seealso: [](ch_ksp), `PCCreate()`, `PCSetType()`, `PCType`, `PC`, `PCHPDDMSetAuxiliaryMat()`, `MATIS`, `PCBDDC`, `PCDEFLATION`, `PCTELESCOPE`, `PCASM`,
3568:           `PCHPDDMSetCoarseCorrectionType()`, `PCHPDDMHasNeumannMat()`, `PCHPDDMSetRHSMat()`, `PCHPDDMSetDeflationMat()`, `PCHPDDMSetScaling()`, `PCHPDDMSetSTShareSubKSP()`,
3569:           `PCHPDDMGetSTShareSubKSP()`, `PCHPDDMGetCoarseCorrectionType()`, `PCHPDDMGetComplexities()`
3570: M*/
3571: PETSC_EXTERN PetscErrorCode PCCreate_HPDDM(PC pc)
3572: {
3573:   PC_HPDDM *data;
3574:   PetscBool found;

3576:   PetscFunctionBegin;
3577:   if (!loadedSym) {
3578:     PetscCall(HPDDMLoadDL_Private(&found));
3579:     if (found) PetscCall(PetscDLLibrarySym(PETSC_COMM_SELF, &PetscDLLibrariesLoaded, nullptr, "PCHPDDM_Internal", (void **)&loadedSym));
3580:   }
3581:   PetscCheck(loadedSym, PETSC_COMM_SELF, PETSC_ERR_PLIB, "PCHPDDM_Internal symbol not found in loaded libhpddm_petsc");
3582:   PetscCall(PetscNew(&data));
3583:   pc->data                   = data;
3584:   data->Neumann              = PETSC_BOOL3_UNKNOWN;
3585:   pc->ops->reset             = PCReset_HPDDM;
3586:   pc->ops->destroy           = PCDestroy_HPDDM;
3587:   pc->ops->setfromoptions    = PCSetFromOptions_HPDDM;
3588:   pc->ops->setup             = PCSetUp_HPDDM;
3589:   pc->ops->apply             = PCApply_HPDDM<false>;
3590:   pc->ops->matapply          = PCMatApply_HPDDM<false>;
3591:   pc->ops->applytranspose    = PCApply_HPDDM<true>;
3592:   pc->ops->matapplytranspose = PCMatApply_HPDDM<true>;
3593:   pc->ops->view              = PCView_HPDDM;
3594:   pc->ops->presolve          = PCPreSolve_HPDDM;

3596:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetAuxiliaryMat_C", PCHPDDMSetAuxiliaryMat_HPDDM));
3597:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMHasNeumannMat_C", PCHPDDMHasNeumannMat_HPDDM));
3598:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetRHSMat_C", PCHPDDMSetRHSMat_HPDDM));
3599:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetCoarseCorrectionType_C", PCHPDDMSetCoarseCorrectionType_HPDDM));
3600:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetCoarseCorrectionType_C", PCHPDDMGetCoarseCorrectionType_HPDDM));
3601:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetSTShareSubKSP_C", PCHPDDMSetSTShareSubKSP_HPDDM));
3602:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMGetSTShareSubKSP_C", PCHPDDMGetSTShareSubKSP_HPDDM));
3603:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetDeflationMat_C", PCHPDDMSetDeflationMat_HPDDM));
3604:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCHPDDMSetScaling_C", PCHPDDMSetScaling_HPDDM));
3605:   PetscFunctionReturn(PETSC_SUCCESS);
3606: }

3608: /*@
3609:   PCHPDDMInitializePackage - This function initializes everything in the `PCHPDDM` package. It is called from `PCInitializePackage()`.

3611:   Level: developer

3613: .seealso: [](ch_ksp), `PetscInitialize()`
3614: @*/
3615: PetscErrorCode PCHPDDMInitializePackage(void)
3616: {
3617:   char ename[32];

3619:   PetscFunctionBegin;
3620:   if (PCHPDDMPackageInitialized) PetscFunctionReturn(PETSC_SUCCESS);
3621:   PCHPDDMPackageInitialized = PETSC_TRUE;
3622:   PetscCall(PetscRegisterFinalize(PCHPDDMFinalizePackage));
3623:   /* general events registered once during package initialization */
3624:   /* some of these events are not triggered in libpetsc,          */
3625:   /* but rather directly in libhpddm_petsc,                       */
3626:   /* which is in charge of performing the following operations    */

3628:   /* domain decomposition structure from Pmat sparsity pattern    */
3629:   PetscCall(PetscLogEventRegister("PCHPDDMStrc", PC_CLASSID, &PC_HPDDM_Strc));
3630:   /* Galerkin product, redistribution, and setup (not triggered in libpetsc)                */
3631:   PetscCall(PetscLogEventRegister("PCHPDDMPtAP", PC_CLASSID, &PC_HPDDM_PtAP));
3632:   /* Galerkin product with summation, redistribution, and setup (not triggered in libpetsc) */
3633:   PetscCall(PetscLogEventRegister("PCHPDDMPtBP", PC_CLASSID, &PC_HPDDM_PtBP));
3634:   /* next level construction using PtAP and PtBP (not triggered in libpetsc)                */
3635:   PetscCall(PetscLogEventRegister("PCHPDDMNext", PC_CLASSID, &PC_HPDDM_Next));
3636:   static_assert(PETSC_PCHPDDM_MAXLEVELS <= 9, "PETSC_PCHPDDM_MAXLEVELS value is too high");
3637:   for (PetscInt i = 1; i < PETSC_PCHPDDM_MAXLEVELS; ++i) {
3638:     PetscCall(PetscSNPrintf(ename, sizeof(ename), "PCHPDDMSetUp L%1" PetscInt_FMT, i));
3639:     /* events during a PCSetUp() at level #i _except_ the assembly */
3640:     /* of the Galerkin operator of the coarser level #(i + 1)      */
3641:     PetscCall(PetscLogEventRegister(ename, PC_CLASSID, &PC_HPDDM_SetUp[i - 1]));
3642:     PetscCall(PetscSNPrintf(ename, sizeof(ename), "PCHPDDMSolve L%1" PetscInt_FMT, i));
3643:     /* events during a PCApply() at level #i _except_              */
3644:     /* the KSPSolve() of the coarser level #(i + 1)                */
3645:     PetscCall(PetscLogEventRegister(ename, PC_CLASSID, &PC_HPDDM_Solve[i - 1]));
3646:   }
3647:   PetscFunctionReturn(PETSC_SUCCESS);
3648: }

3650: /*@
3651:   PCHPDDMFinalizePackage - This function frees everything from the `PCHPDDM` package. It is called from `PetscFinalize()`.

3653:   Level: developer

3655: .seealso: [](ch_ksp), `PetscFinalize()`
3656: @*/
3657: PetscErrorCode PCHPDDMFinalizePackage(void)
3658: {
3659:   PetscFunctionBegin;
3660:   PCHPDDMPackageInitialized = PETSC_FALSE;
3661:   PetscFunctionReturn(PETSC_SUCCESS);
3662: }

3664: static PetscErrorCode MatMult_Harmonic(Mat A, Vec x, Vec y)
3665: {
3666:   Harmonic h; /* [ A_00  A_01       ], furthermore, A_00 = [ A_loc,loc  A_loc,ovl ], thus, A_01 = [         ] */
3667:               /* [ A_10  A_11  A_12 ]                      [ A_ovl,loc  A_ovl,ovl ]               [ A_ovl,1 ] */
3668:               /*  y = A x = R_loc R_0 [ A_00  A_01 ]^-1                                   R_loc = [  I_loc  ] */
3669:               /*                      [ A_10  A_11 ]    R_1^T A_12 x                              [         ] */
3670:   PetscFunctionBegin;
3671:   PetscCall(MatShellGetContext(A, static_cast<void *>(&h)));
3672:   PetscCall(VecSet(h->v[0], 0.0));
3673:   PetscCall(MatMult(h->A[0], x, h->v[1]));
3674:   PetscCall(VecScatterBegin(h->scatter[0], h->v[1], h->v[0], INSERT_VALUES, SCATTER_REVERSE));
3675:   PetscCall(VecScatterEnd(h->scatter[0], h->v[1], h->v[0], INSERT_VALUES, SCATTER_REVERSE));
3676:   PetscCall(KSPSolve(h->ksp, h->v[0], h->v[0]));
3677:   PetscCall(VecScatterBegin(h->scatter[1], h->v[0], y, INSERT_VALUES, SCATTER_FORWARD));
3678:   PetscCall(VecScatterEnd(h->scatter[1], h->v[0], y, INSERT_VALUES, SCATTER_FORWARD));
3679:   PetscFunctionReturn(PETSC_SUCCESS);
3680: }

3682: static PetscErrorCode MatMultTranspose_Harmonic(Mat A, Vec y, Vec x)
3683: {
3684:   Harmonic h; /* x = A^T y =            [ A_00  A_01 ]^-T R_0^T R_loc^T y */
3685:               /*             A_12^T R_1 [ A_10  A_11 ]                    */
3686:   PetscFunctionBegin;
3687:   PetscCall(MatShellGetContext(A, static_cast<void *>(&h)));
3688:   PetscCall(VecSet(h->v[0], 0.0));
3689:   PetscCall(VecScatterBegin(h->scatter[1], y, h->v[0], INSERT_VALUES, SCATTER_REVERSE));
3690:   PetscCall(VecScatterEnd(h->scatter[1], y, h->v[0], INSERT_VALUES, SCATTER_REVERSE));
3691:   PetscCall(KSPSolveTranspose(h->ksp, h->v[0], h->v[0]));
3692:   PetscCall(VecScatterBegin(h->scatter[0], h->v[0], h->v[1], INSERT_VALUES, SCATTER_FORWARD));
3693:   PetscCall(VecScatterEnd(h->scatter[0], h->v[0], h->v[1], INSERT_VALUES, SCATTER_FORWARD));
3694:   PetscCall(MatMultTranspose(h->A[0], h->v[1], x));
3695:   PetscFunctionReturn(PETSC_SUCCESS);
3696: }

3698: static PetscErrorCode MatProduct_AB_Harmonic(Mat S, Mat X, Mat Y, void *)
3699: {
3700:   Harmonic h;
3701:   Mat      A, B;

3703:   PetscFunctionBegin;
3704:   PetscCall(MatShellGetContext(S, static_cast<void *>(&h)));
3705:   PetscCall(MatMatMult(h->A[0], X, MAT_INITIAL_MATRIX, PETSC_CURRENT, &A));
3706:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, h->ksp->pc->mat->rmap->n, A->cmap->n, nullptr, &B));
3707:   PetscCall(MatDenseScatter_Private(h->scatter[0], A, B, INSERT_VALUES, SCATTER_REVERSE));
3708:   PetscCall(MatDestroy(&A));
3709:   PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &A));
3710:   PetscCall(KSPMatSolve(h->ksp, B, A));
3711:   PetscCall(MatDestroy(&B));
3712:   PetscCall(MatDenseScatter_Private(h->scatter[1], A, Y, INSERT_VALUES, SCATTER_FORWARD));
3713:   PetscCall(MatDestroy(&A));
3714:   PetscFunctionReturn(PETSC_SUCCESS);
3715: }

3717: static PetscErrorCode MatProduct_AtB_Harmonic(Mat S, Mat Y, Mat X, void *)
3718: {
3719:   Harmonic h;
3720:   Mat      A, B;

3722:   PetscFunctionBegin;
3723:   PetscCall(MatShellGetContext(S, static_cast<void *>(&h)));
3724:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, h->ksp->pc->mat->rmap->n, Y->cmap->n, nullptr, &A));
3725:   PetscCall(MatDenseScatter_Private(h->scatter[1], Y, A, INSERT_VALUES, SCATTER_REVERSE));
3726:   PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
3727:   PetscCall(KSPMatSolveTranspose(h->ksp, A, B));
3728:   PetscCall(MatDestroy(&A));
3729:   PetscCall(MatCreateSeqDense(PETSC_COMM_SELF, h->A[0]->rmap->n, B->cmap->n, nullptr, &A));
3730:   PetscCall(MatDenseScatter_Private(h->scatter[0], B, A, INSERT_VALUES, SCATTER_FORWARD));
3731:   PetscCall(MatDestroy(&B));
3732:   PetscCall(MatTransposeMatMult(h->A[0], A, MAT_REUSE_MATRIX, PETSC_CURRENT, &X));
3733:   PetscCall(MatDestroy(&A));
3734:   PetscFunctionReturn(PETSC_SUCCESS);
3735: }

3737: static PetscErrorCode MatDestroy_Harmonic(Mat A)
3738: {
3739:   Harmonic h;

3741:   PetscFunctionBegin;
3742:   PetscCall(MatShellGetContext(A, static_cast<void *>(&h)));
3743:   if (h->is) {
3744:     for (PetscInt i = 0; i < 3; ++i) PetscCall(ISDestroy(h->is + i));
3745:     PetscCall(PetscFree(h->is));
3746:   }
3747:   for (PetscInt i = 0; i < 2; ++i) {
3748:     PetscCall(VecDestroy(h->v + i));
3749:     PetscCall(MatDestroy(h->A + i));
3750:     PetscCall(VecScatterDestroy(h->scatter + i));
3751:   }
3752:   PetscCall(PetscFree(h->A));
3753:   PetscCall(KSPDestroy(&h->ksp));
3754:   PetscCall(PetscFree(h));
3755:   PetscFunctionReturn(PETSC_SUCCESS);
3756: }