Actual source code: precon.c

  1: /*
  2:     The PC (preconditioner) interface routines, callable by users.
  3: */
  4: #include <petsc/private/pcimpl.h>
  5: #include <petscdm.h>

  7: /* Logging support */
  8: PetscClassId  PC_CLASSID;
  9: PetscLogEvent PC_SetUp, PC_SetUpOnBlocks, PC_Apply, PC_MatApply, PC_ApplyCoarse, PC_ApplySymmetricLeft;
 10: PetscLogEvent PC_ApplySymmetricRight, PC_ModifySubMatrices, PC_ApplyOnBlocks, PC_ApplyTransposeOnBlocks;
 11: PetscInt      PetscMGLevelId;
 12: PetscLogStage PCMPIStage;

 14: PETSC_INTERN PetscErrorCode PCGetDefaultType_Private(PC pc, const char *type[])
 15: {
 16:   PetscMPIInt size;
 17:   PetscBool   hasopblock, hasopsolve, flg1, flg2, set, flg3, isnormal;

 19:   PetscFunctionBegin;
 20:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)pc), &size));
 21:   if (pc->pmat) {
 22:     PetscCall(MatHasOperation(pc->pmat, MATOP_GET_DIAGONAL_BLOCK, &hasopblock));
 23:     PetscCall(MatHasOperation(pc->pmat, MATOP_SOLVE, &hasopsolve));
 24:     if (size == 1) {
 25:       PetscCall(MatGetFactorAvailable(pc->pmat, "petsc", MAT_FACTOR_ICC, &flg1));
 26:       PetscCall(MatGetFactorAvailable(pc->pmat, "petsc", MAT_FACTOR_ILU, &flg2));
 27:       PetscCall(MatIsSymmetricKnown(pc->pmat, &set, &flg3));
 28:       PetscCall(PetscObjectTypeCompareAny((PetscObject)pc->pmat, &isnormal, MATNORMAL, MATNORMALHERMITIAN, NULL));
 29:       if (flg1 && (!flg2 || (set && flg3))) {
 30:         *type = PCICC;
 31:       } else if (flg2) {
 32:         *type = PCILU;
 33:       } else if (isnormal) {
 34:         *type = PCNONE;
 35:       } else if (hasopblock) { /* likely is a parallel matrix run on one processor */
 36:         if (pc->kspnestlevel > 0) {
 37:           Mat D;

 39:           PetscCall(MatGetDiagonalBlock(pc->pmat, &D));
 40:           PetscCall(PetscObjectTypeCompare((PetscObject)D, ((PetscObject)pc->pmat)->type_name, &flg1)); /* make sure there is no recursive call to PCGetDefaultType_Private() */
 41:         } else flg1 = PETSC_FALSE;
 42:         if (!flg1) *type = PCBJACOBI;
 43:         else *type = PCNONE;
 44:       } else if (hasopsolve) {
 45:         *type = PCMAT;
 46:       } else {
 47:         *type = PCNONE;
 48:       }
 49:     } else {
 50:       if (hasopblock) {
 51:         *type = PCBJACOBI;
 52:       } else if (hasopsolve) {
 53:         *type = PCMAT;
 54:       } else {
 55:         *type = PCNONE;
 56:       }
 57:     }
 58:   } else *type = NULL;
 59:   PetscFunctionReturn(PETSC_SUCCESS);
 60: }

 62: /* do not log solves, setup, and applications of preconditioners while constructing preconditioners; perhaps they should be logged separately from the regular solves */
 63: PETSC_EXTERN PetscLogEvent KSP_Solve, KSP_SetUp;

 65: static PetscErrorCode PCLogEventsDeactivatePush(void)
 66: {
 67:   PetscFunctionBegin;
 68:   PetscCall(KSPInitializePackage());
 69:   PetscCall(PetscLogEventDeactivatePush(KSP_Solve));
 70:   PetscCall(PetscLogEventDeactivatePush(KSP_SetUp));
 71:   PetscCall(PetscLogEventDeactivatePush(PC_Apply));
 72:   PetscCall(PetscLogEventDeactivatePush(PC_SetUp));
 73:   PetscCall(PetscLogEventDeactivatePush(PC_SetUpOnBlocks));
 74:   PetscFunctionReturn(PETSC_SUCCESS);
 75: }

 77: static PetscErrorCode PCLogEventsDeactivatePop(void)
 78: {
 79:   PetscFunctionBegin;
 80:   PetscCall(KSPInitializePackage());
 81:   PetscCall(PetscLogEventDeactivatePop(KSP_Solve));
 82:   PetscCall(PetscLogEventDeactivatePop(KSP_SetUp));
 83:   PetscCall(PetscLogEventDeactivatePop(PC_Apply));
 84:   PetscCall(PetscLogEventDeactivatePop(PC_SetUp));
 85:   PetscCall(PetscLogEventDeactivatePop(PC_SetUpOnBlocks));
 86:   PetscFunctionReturn(PETSC_SUCCESS);
 87: }

 89: /*@
 90:   PCReset - Resets a `PC` context to the state it was in before `PCSetUp()` was called, and removes any allocated `Vec` and `Mat` from its data structure

 92:   Collective

 94:   Input Parameter:
 95: . pc - the `PC` preconditioner context

 97:   Level: developer

 99:   Notes:
100:   Any options set, including those set with `KSPSetFromOptions()` remain.

102:   This allows a `PC` to be reused for a different sized linear system but using the same options that have been previously set in `pc`

104: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCSetUp()`
105: @*/
106: PetscErrorCode PCReset(PC pc)
107: {
108:   PetscFunctionBegin;
110:   PetscTryTypeMethod(pc, reset);
111:   PetscCall(MatDestroy(&pc->pmat));
112:   PetscCall(MatDestroy(&pc->mat));

114:   pc->setupcalled = PETSC_FALSE;
115:   PetscFunctionReturn(PETSC_SUCCESS);
116: }

118: /*@
119:   PCDestroy - Destroys `PC` context that was created with `PCCreate()`.

121:   Collective

123:   Input Parameter:
124: . pc - the `PC` preconditioner context

126:   Level: developer

128: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCSetUp()`
129: @*/
130: PetscErrorCode PCDestroy(PC *pc)
131: {
132:   PetscFunctionBegin;
133:   if (!*pc) PetscFunctionReturn(PETSC_SUCCESS);
135:   if (--((PetscObject)*pc)->refct > 0) {
136:     *pc = NULL;
137:     PetscFunctionReturn(PETSC_SUCCESS);
138:   }

140:   PetscCall(PCReset(*pc));

142:   /* if memory was published with SAWs then destroy it */
143:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*pc));
144:   PetscTryTypeMethod(*pc, destroy);
145:   PetscCall(DMDestroy(&(*pc)->dm));
146:   PetscCall(PetscHeaderDestroy(pc));
147:   PetscFunctionReturn(PETSC_SUCCESS);
148: }

150: /*@
151:   PCSetUseAmat - Sets a flag to indicate that when the preconditioner needs to apply (part of) the
152:   operator during the preconditioning process it applies the `Amat` provided to `TSSetRHSJacobian()`,
153:   `TSSetIJacobian()`, `SNESSetJacobian()`, `KSPSetOperators()` or `PCSetOperators()` not the `Pmat`.

155:   Logically Collective

157:   Input Parameters:
158: + pc  - the `PC` preconditioner context
159: - flg - `PETSC_TRUE` to use the `Amat`, `PETSC_FALSE` to use the `Pmat` (default is `PETSC_FALSE`)

161:   Options Database Key:
162: . -pc_use_amat (true|false) - use the `Amat` argument to `KSPSetOperators()` or `PCSetOperators()` to apply the operator

164:   Level: intermediate

166:   Note:
167:   For the common case in which the linear system matrix and the matrix used to construct the
168:   preconditioner are identical, this routine has no effect.

170: .seealso: [](ch_ksp), `PC`, `PCGetUseAmat()`, `PCBJACOBI`, `PCMG`, `PCFIELDSPLIT`, `PCCOMPOSITE`,
171:           `KSPSetOperators()`, `PCSetOperators()`
172: @*/
173: PetscErrorCode PCSetUseAmat(PC pc, PetscBool flg)
174: {
175:   PetscFunctionBegin;
177:   pc->useAmat = flg;
178:   PetscFunctionReturn(PETSC_SUCCESS);
179: }

181: /*@
182:   PCSetErrorIfFailure - Causes `PC` to generate an error if a floating point exception, for example a zero pivot, is detected.

184:   Logically Collective

186:   Input Parameters:
187: + pc  - iterative context obtained from `PCCreate()`
188: - flg - `PETSC_TRUE` indicates you want the error generated

190:   Level: advanced

192:   Notes:
193:   Normally PETSc continues if a linear solver fails due to a failed setup of a preconditioner, you can call `KSPGetConvergedReason()` after a `KSPSolve()`
194:   to determine if it has converged or failed. Or use -ksp_error_if_not_converged to cause the program to terminate as soon as lack of convergence is
195:   detected.

197:   This is propagated into `KSP`s used by this `PC`, which then propagate it into `PC`s used by those `KSP`s

199: .seealso: [](ch_ksp), `PC`, `KSPSetErrorIfNotConverged()`, `PCGetInitialGuessNonzero()`, `PCSetInitialGuessKnoll()`, `PCGetInitialGuessKnoll()`
200: @*/
201: PetscErrorCode PCSetErrorIfFailure(PC pc, PetscBool flg)
202: {
203:   PetscFunctionBegin;
206:   pc->erroriffailure = flg;
207:   PetscFunctionReturn(PETSC_SUCCESS);
208: }

210: /*@
211:   PCGetUseAmat - Gets the flag that indicates that when the preconditioner needs to apply (part of) the
212:   operator during the preconditioning process it applies the `Amat` provided to `TSSetRHSJacobian()`,
213:   `TSSetIJacobian()`, `SNESSetJacobian()`, `KSPSetOperators()` or `PCSetOperators()` not the `Pmat`.

215:   Logically Collective

217:   Input Parameter:
218: . pc - the `PC` preconditioner context

220:   Output Parameter:
221: . flg - `PETSC_TRUE` to use the `Amat`, `PETSC_FALSE` to use the `Pmat`

223:   Level: intermediate

225: .seealso: [](ch_ksp), `PC`, `PCSetUseAmat()`, `PCBJACOBI`, `PCMG`, `PCFIELDSPLIT`, `PCCOMPOSITE`
226: @*/
227: PetscErrorCode PCGetUseAmat(PC pc, PetscBool *flg)
228: {
229:   PetscFunctionBegin;
231:   *flg = pc->useAmat;
232:   PetscFunctionReturn(PETSC_SUCCESS);
233: }

235: /*@
236:   PCSetKSPNestLevel - sets the amount of nesting the `KSP` that contains this `PC` has

238:   Collective

240:   Input Parameters:
241: + pc    - the `PC`
242: - level - the nest level

244:   Level: developer

246: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGMRES`, `KSPType`, `KSPGetNestLevel()`, `PCGetKSPNestLevel()`, `KSPSetNestLevel()`
247: @*/
248: PetscErrorCode PCSetKSPNestLevel(PC pc, PetscInt level)
249: {
250:   PetscFunctionBegin;
253:   pc->kspnestlevel = level;
254:   PetscFunctionReturn(PETSC_SUCCESS);
255: }

257: /*@
258:   PCGetKSPNestLevel - gets the amount of nesting the `KSP` that contains this `PC` has

260:   Not Collective

262:   Input Parameter:
263: . pc - the `PC`

265:   Output Parameter:
266: . level - the nest level

268:   Level: developer

270: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGMRES`, `KSPType`, `KSPSetNestLevel()`, `PCSetKSPNestLevel()`, `KSPGetNestLevel()`
271: @*/
272: PetscErrorCode PCGetKSPNestLevel(PC pc, PetscInt *level)
273: {
274:   PetscFunctionBegin;
276:   PetscAssertPointer(level, 2);
277:   *level = pc->kspnestlevel;
278:   PetscFunctionReturn(PETSC_SUCCESS);
279: }

281: /*@
282:   PCCreate - Creates a preconditioner context, `PC`

284:   Collective

286:   Input Parameter:
287: . comm - MPI communicator

289:   Output Parameter:
290: . newpc - location to put the `PC` preconditioner context

292:   Level: developer

294:   Notes:
295:   This is rarely called directly by users since `KSP` manages the `PC` objects it uses. Use `KSPGetPC()` to access the `PC` used by a `KSP`.

297:   Use `PCSetType()` or `PCSetFromOptions()` with the option `-pc_type pctype` to set the `PCType` for this `PC`

299:   The default preconditioner type `PCType` for sparse matrices is `PCILU` or `PCICC` with 0 fill on one process and block Jacobi (`PCBJACOBI`) with `PCILU` or `PCICC`
300:   in parallel. For dense matrices it is always `PCNONE`.

302: .seealso: [](ch_ksp), `PC`, `PCType`, `PCSetType`, `PCSetUp()`, `PCApply()`, `PCDestroy()`, `KSP`, `KSPGetPC()`
303: @*/
304: PetscErrorCode PCCreate(MPI_Comm comm, PC *newpc)
305: {
306:   PC pc;

308:   PetscFunctionBegin;
309:   PetscAssertPointer(newpc, 2);
310:   PetscCall(PCInitializePackage());

312:   PetscCall(PetscHeaderCreate(pc, PC_CLASSID, "PC", "Preconditioner", "PC", comm, PCDestroy, PCView));
313:   PetscCall(PCParametersInitialize(pc));
314:   *newpc = pc;
315:   PetscFunctionReturn(PETSC_SUCCESS);
316: }

318: /*@
319:   PCParametersInitialize - Sets the base defaults for parameters in `pc`, updating a parameter's current value when it matches its previously recorded default.

321:   Logically collective

323:   Input Parameter:
324: . pc - the `PC` object

326:   Level: developer

328:   Notes:

330:   The base defaults are the non-type-specific values established when the `PC` is created. A `PCType` constructor may subsequently replace them with type-specific defaults.

332:   Developer Notes:

334:   `PCCreate()` calls this routine to establish the base defaults. `PCSetType()` calls it before constructing a new `PCType`, so the recorded defaults associated with the previous type are replaced before the new type installs its own defaults.

336:   Default tracking is based on value equality, not on whether a setter was called. Consequently, an explicitly assigned value that equals the recorded default may be updated when the type changes.

338: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCDestroy()`, `PetscObjectParameterSetDefault()`
339: @*/
340: PetscErrorCode PCParametersInitialize(PC pc)
341: {
342:   PetscObjectParameterSetDefault(pc, useAmat, PETSC_FALSE);
343:   return PETSC_SUCCESS;
344: }

346: /*@
347:   PCApply - Applies the preconditioner to a vector.

349:   Collective

351:   Input Parameters:
352: + pc - the `PC` preconditioner context
353: - x  - input vector

355:   Output Parameter:
356: . y - output vector

358:   Level: developer

360: .seealso: [](ch_ksp), `PC`, `PCApplyTranspose()`, `PCApplyBAorAB()`
361: @*/
362: PetscErrorCode PCApply(PC pc, Vec x, Vec y)
363: {
364:   PetscInt m, n, mv, nv;

366:   PetscFunctionBegin;
370:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
371:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
372:   /* use pmat to check vector sizes since for KSPLSQR the pmat may be of a different size than mat */
373:   PetscCall(MatGetLocalSize(pc->pmat, &m, &n));
374:   PetscCall(VecGetLocalSize(x, &mv));
375:   PetscCall(VecGetLocalSize(y, &nv));
376:   /* check pmat * y = x is feasible */
377:   PetscCheck(mv == m, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Preconditioner number of local rows %" PetscInt_FMT " does not equal input vector size %" PetscInt_FMT, m, mv);
378:   PetscCheck(nv == n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Preconditioner number of local columns %" PetscInt_FMT " does not equal output vector size %" PetscInt_FMT, n, nv);
379:   PetscCall(VecSetErrorIfLocked(y, 3));

381:   PetscCall(PCSetUp(pc));
382:   PetscCall(VecLockReadPush(x));
383:   PetscCall(PetscLogEventBegin(PC_Apply, pc, x, y, 0));
384:   PetscUseTypeMethod(pc, apply, x, y);
385:   PetscCall(PetscLogEventEnd(PC_Apply, pc, x, y, 0));
386:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
387:   PetscCall(VecLockReadPop(x));
388:   PetscFunctionReturn(PETSC_SUCCESS);
389: }

391: /*
392:    Checks that the blocks of vectors In and Out are dense and have layouts compatible with each other and with Pmat, inname and outname naming them in the error messages
393: */
394: static PetscErrorCode PCMatCheckBlocks_Private(PC pc, Mat In, Mat Out, const char *inname, const char *outname)
395: {
396:   Mat       A;
397:   PetscInt  m1, M1, m2, M2, n1, N1, n2, N2, m3, M3, n3, N3;
398:   PetscBool match;

400:   PetscFunctionBegin;
401:   PetscCall(PCGetOperators(pc, NULL, &A));
402:   PetscCall(MatGetLocalSize(A, &m3, &n3));
403:   PetscCall(MatGetLocalSize(In, &m2, &n2));
404:   PetscCall(MatGetLocalSize(Out, &m1, &n1));
405:   PetscCall(MatGetSize(A, &M3, &N3));
406:   PetscCall(MatGetSize(In, &M2, &N2));
407:   PetscCall(MatGetSize(Out, &M1, &N1));
408:   PetscCheck(n1 == n2 && N1 == N2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible number of columns between block of %s (n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ") and block of %s (n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ")", inname, n2, N2, outname, n1, N1);
409:   PetscCheck(m2 == m3 && M2 == M3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible layout between block of %s (m,M) = (%" PetscInt_FMT ",%" PetscInt_FMT ") and Pmat (m,M)x(n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ")x(%" PetscInt_FMT ",%" PetscInt_FMT ")", inname, m2, M2, m3, M3, n3, N3);
410:   PetscCheck(m1 == n3 && M1 == N3, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible layout between block of %s (m,M) = (%" PetscInt_FMT ",%" PetscInt_FMT ") and Pmat (m,M)x(n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ")x(%" PetscInt_FMT ",%" PetscInt_FMT ")", outname, m1, M1, m3, M3, n3, N3);
411:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)Out, &match, MATSEQDENSE, MATMPIDENSE, ""));
412:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of %s not stored in a dense Mat", outname);
413:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)In, &match, MATSEQDENSE, MATMPIDENSE, ""));
414:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of %s not stored in a dense Mat", inname);
415:   PetscFunctionReturn(PETSC_SUCCESS);
416: }

418: static PetscErrorCode PCMatApplyTranspose_Private(PC pc, Mat X, Mat Y, PetscBool transpose)
419: {
420:   Vec      cy, cx;
421:   PetscInt n1, N1;

423:   PetscFunctionBegin;
427:   PetscCheckSameComm(pc, 1, X, 2);
428:   PetscCheckSameComm(pc, 1, Y, 3);
429:   PetscCheck(Y != X, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "Y and X must be different matrices");
430:   PetscCall(PCMatCheckBlocks_Private(pc, X, Y, "input vectors", "output vectors"));
431:   PetscCall(MatGetSize(Y, NULL, &N1));
432:   PetscCall(PCSetUp(pc));
433:   if (!transpose && pc->ops->matapply) {
434:     PetscCall(PetscLogEventBegin(PC_MatApply, pc, X, Y, 0));
435:     PetscUseTypeMethod(pc, matapply, X, Y);
436:     PetscCall(PetscLogEventEnd(PC_MatApply, pc, X, Y, 0));
437:   } else if (transpose && pc->ops->matapplytranspose) {
438:     PetscCall(PetscLogEventBegin(PC_MatApply, pc, X, Y, 0));
439:     PetscUseTypeMethod(pc, matapplytranspose, X, Y);
440:     PetscCall(PetscLogEventEnd(PC_MatApply, pc, X, Y, 0));
441:   } else {
442:     PetscCall(PetscInfo(pc, "PC type %s applying column by column\n", ((PetscObject)pc)->type_name));
443:     for (n1 = 0; n1 < N1; ++n1) {
444:       PetscCall(MatDenseGetColumnVecRead(X, n1, &cx));
445:       PetscCall(MatDenseGetColumnVecWrite(Y, n1, &cy));
446:       if (!transpose) PetscCall(PCApply(pc, cx, cy));
447:       else PetscCall(PCApplyTranspose(pc, cx, cy));
448:       PetscCall(MatDenseRestoreColumnVecWrite(Y, n1, &cy));
449:       PetscCall(MatDenseRestoreColumnVecRead(X, n1, &cx));
450:     }
451:   }
452:   PetscFunctionReturn(PETSC_SUCCESS);
453: }

455: /*@
456:   PCMatApply - Applies the preconditioner to multiple vectors stored as a `MATDENSE`. Like `PCApply()`, `Y` and `X` must be different matrices.

458:   Collective

460:   Input Parameters:
461: + pc - the `PC` preconditioner context
462: - X  - block of input vectors

464:   Output Parameter:
465: . Y - block of output vectors

467:   Level: developer

469: .seealso: [](ch_ksp), `PC`, `PCApply()`, `KSPMatSolve()`
470: @*/
471: PetscErrorCode PCMatApply(PC pc, Mat X, Mat Y)
472: {
473:   PetscFunctionBegin;
474:   PetscCall(PCMatApplyTranspose_Private(pc, X, Y, PETSC_FALSE));
475:   PetscFunctionReturn(PETSC_SUCCESS);
476: }

478: /*@
479:   PCMatApplyTranspose - Applies the transpose of preconditioner to multiple vectors stored as a `MATDENSE`. Like `PCApplyTranspose()`, `Y` and `X` must be different matrices.

481:   Collective

483:   Input Parameters:
484: + pc - the `PC` preconditioner context
485: - X  - block of input vectors

487:   Output Parameter:
488: . Y - block of output vectors

490:   Level: developer

492: .seealso: [](ch_ksp), `PC`, `PCApplyTranspose()`, `KSPMatSolveTranspose()`
493: @*/
494: PetscErrorCode PCMatApplyTranspose(PC pc, Mat X, Mat Y)
495: {
496:   PetscFunctionBegin;
497:   PetscCall(PCMatApplyTranspose_Private(pc, X, Y, PETSC_TRUE));
498:   PetscFunctionReturn(PETSC_SUCCESS);
499: }

501: /*@
502:   PCApplySymmetricLeft - Applies the left part of a symmetric preconditioner to a vector.

504:   Collective

506:   Input Parameters:
507: + pc - the `PC` preconditioner context
508: - x  - input vector

510:   Output Parameter:
511: . y - output vector

513:   Level: developer

515:   Note:
516:   Currently, this routine is implemented only for `PCICC` and `PCJACOBI` preconditioners.

518: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCApplySymmetricRight()`
519: @*/
520: PetscErrorCode PCApplySymmetricLeft(PC pc, Vec x, Vec y)
521: {
522:   PetscFunctionBegin;
526:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
527:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
528:   PetscCall(PCSetUp(pc));
529:   PetscCall(VecLockReadPush(x));
530:   PetscCall(PetscLogEventBegin(PC_ApplySymmetricLeft, pc, x, y, 0));
531:   PetscUseTypeMethod(pc, applysymmetricleft, x, y);
532:   PetscCall(PetscLogEventEnd(PC_ApplySymmetricLeft, pc, x, y, 0));
533:   PetscCall(VecLockReadPop(x));
534:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
535:   PetscFunctionReturn(PETSC_SUCCESS);
536: }

538: /*@
539:   PCApplySymmetricRight - Applies the right part of a symmetric preconditioner to a vector.

541:   Collective

543:   Input Parameters:
544: + pc - the `PC` preconditioner context
545: - x  - input vector

547:   Output Parameter:
548: . y - output vector

550:   Level: developer

552:   Note:
553:   Currently, this routine is implemented only for `PCICC` and `PCJACOBI` preconditioners.

555: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCApplySymmetricLeft()`
556: @*/
557: PetscErrorCode PCApplySymmetricRight(PC pc, Vec x, Vec y)
558: {
559:   PetscFunctionBegin;
563:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
564:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
565:   PetscCall(PCSetUp(pc));
566:   PetscCall(VecLockReadPush(x));
567:   PetscCall(PetscLogEventBegin(PC_ApplySymmetricRight, pc, x, y, 0));
568:   PetscUseTypeMethod(pc, applysymmetricright, x, y);
569:   PetscCall(PetscLogEventEnd(PC_ApplySymmetricRight, pc, x, y, 0));
570:   PetscCall(VecLockReadPop(x));
571:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
572:   PetscFunctionReturn(PETSC_SUCCESS);
573: }

575: /*@
576:   PCApplyTranspose - Applies the transpose of preconditioner to a vector.

578:   Collective

580:   Input Parameters:
581: + pc - the `PC` preconditioner context
582: - x  - input vector

584:   Output Parameter:
585: . y - output vector

587:   Level: developer

589:   Note:
590:   For complex numbers this applies the non-Hermitian transpose.

592:   Developer Note:
593:   We need to implement a `PCApplyHermitianTranspose()`

595: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCApplyBAorAB()`, `PCApplyBAorABTranspose()`, `PCApplyTransposeExists()`
596: @*/
597: PetscErrorCode PCApplyTranspose(PC pc, Vec x, Vec y)
598: {
599:   PetscFunctionBegin;
603:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
604:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
605:   PetscCall(PCSetUp(pc));
606:   PetscCall(VecLockReadPush(x));
607:   PetscCall(PetscLogEventBegin(PC_Apply, pc, x, y, 0));
608:   PetscUseTypeMethod(pc, applytranspose, x, y);
609:   PetscCall(PetscLogEventEnd(PC_Apply, pc, x, y, 0));
610:   PetscCall(VecLockReadPop(x));
611:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 3, PETSC_FALSE));
612:   PetscFunctionReturn(PETSC_SUCCESS);
613: }

615: /*@
616:   PCApplyTransposeExists - Test whether the preconditioner has a transpose apply operation

618:   Collective

620:   Input Parameter:
621: . pc - the `PC` preconditioner context

623:   Output Parameter:
624: . flg - `PETSC_TRUE` if a transpose operation is defined

626:   Level: developer

628: .seealso: [](ch_ksp), `PC`, `PCApplyTranspose()`
629: @*/
630: PetscErrorCode PCApplyTransposeExists(PC pc, PetscBool *flg)
631: {
632:   PetscFunctionBegin;
634:   PetscAssertPointer(flg, 2);
635:   if (pc->ops->applytranspose) *flg = PETSC_TRUE;
636:   else *flg = PETSC_FALSE;
637:   PetscFunctionReturn(PETSC_SUCCESS);
638: }

640: /*@
641:   PCApplyBAorAB - Applies the preconditioner and operator to a vector. $y = B*A*x $ or $ y = A*B*x$.

643:   Collective

645:   Input Parameters:
646: + pc   - the `PC` preconditioner context
647: . side - indicates the preconditioner side, one of `PC_LEFT`, `PC_RIGHT`, or `PC_SYMMETRIC`
648: . x    - input vector
649: - work - work vector

651:   Output Parameter:
652: . y - output vector

654:   Level: developer

656: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCApplyTranspose()`, `PCApplyBAorABTranspose()`
657: @*/
658: PetscErrorCode PCApplyBAorAB(PC pc, PCSide side, Vec x, Vec y, Vec work)
659: {
660:   PetscFunctionBegin;
666:   PetscCheckSameComm(pc, 1, x, 3);
667:   PetscCheckSameComm(pc, 1, y, 4);
668:   PetscCheckSameComm(pc, 1, work, 5);
669:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
670:   PetscCheck(side == PC_LEFT || side == PC_SYMMETRIC || side == PC_RIGHT, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Side must be right, left, or symmetric");
671:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 3, PETSC_TRUE));

673:   PetscCall(PCSetUp(pc));
674:   if (pc->ops->applyBA) {
675:     PetscUseTypeMethod(pc, applyBA, side, x, y, work);
676:   } else if (side == PC_RIGHT) {
677:     PetscCall(PCApply(pc, x, work));
678:     PetscCall(MatMult(pc->mat, work, y));
679:   } else if (side == PC_LEFT) {
680:     PetscCall(MatMult(pc->mat, x, work));
681:     PetscCall(PCApply(pc, work, y));
682:   } else if (side == PC_SYMMETRIC) {
683:     /* There's an extra copy here; maybe should provide 2 work vectors instead? */
684:     PetscCall(PCApplySymmetricRight(pc, x, work));
685:     PetscCall(MatMult(pc->mat, work, y));
686:     PetscCall(VecCopy(y, work));
687:     PetscCall(PCApplySymmetricLeft(pc, work, y));
688:   }
689:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 4, PETSC_FALSE));
690:   PetscFunctionReturn(PETSC_SUCCESS);
691: }

693: /*@
694:   PCApplyBAorABTranspose - Applies the transpose of the preconditioner
695:   and operator to a vector. That is, applies $B^T * A^T$ with left preconditioning,
696:   NOT $(B*A)^T = A^T*B^T$.

698:   Collective

700:   Input Parameters:
701: + pc   - the `PC` preconditioner context
702: . side - indicates the preconditioner side, one of `PC_LEFT`, `PC_RIGHT`, or `PC_SYMMETRIC`
703: . x    - input vector
704: - work - work vector

706:   Output Parameter:
707: . y - output vector

709:   Level: developer

711:   Note:
712:   This routine is used internally so that the same Krylov code can be used to solve $A x = b$ and $A^T x = b$, with a preconditioner
713:   defined by $B^T$. This is why this has the funny form that it computes $B^T * A^T$

715: .seealso: [](ch_ksp), `PC`, `PCApply()`, `PCApplyTranspose()`, `PCApplyBAorAB()`
716: @*/
717: PetscErrorCode PCApplyBAorABTranspose(PC pc, PCSide side, Vec x, Vec y, Vec work)
718: {
719:   PetscFunctionBegin;
724:   PetscCheck(x != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "x and y must be different vectors");
725:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(x, 3, PETSC_TRUE));
726:   if (pc->ops->applyBAtranspose) {
727:     PetscUseTypeMethod(pc, applyBAtranspose, side, x, y, work);
728:     if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 4, PETSC_FALSE));
729:     PetscFunctionReturn(PETSC_SUCCESS);
730:   }
731:   PetscCheck(side == PC_LEFT || side == PC_RIGHT, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Side must be right or left");

733:   PetscCall(PCSetUp(pc));
734:   if (side == PC_RIGHT) {
735:     PetscCall(PCApplyTranspose(pc, x, work));
736:     PetscCall(MatMultTranspose(pc->mat, work, y));
737:   } else if (side == PC_LEFT) {
738:     PetscCall(MatMultTranspose(pc->mat, x, work));
739:     PetscCall(PCApplyTranspose(pc, work, y));
740:   }
741:   /* add support for PC_SYMMETRIC */
742:   if (pc->erroriffailure) PetscCall(VecValidValues_Internal(y, 4, PETSC_FALSE));
743:   PetscFunctionReturn(PETSC_SUCCESS);
744: }

746: /*@
747:   PCApplyRichardsonExists - Determines whether a particular preconditioner has a
748:   built-in fast application of Richardson's method.

750:   Not Collective

752:   Input Parameter:
753: . pc - the preconditioner

755:   Output Parameter:
756: . exists - `PETSC_TRUE` or `PETSC_FALSE`

758:   Level: developer

760: .seealso: [](ch_ksp), `PC`, `KSPRICHARDSON`, `PCApplyRichardson()`, `PCMatApplyRichardsonExists()`
761: @*/
762: PetscErrorCode PCApplyRichardsonExists(PC pc, PetscBool *exists)
763: {
764:   PetscFunctionBegin;
766:   PetscAssertPointer(exists, 2);
767:   if (pc->ops->applyrichardson) *exists = PETSC_TRUE;
768:   else *exists = PETSC_FALSE;
769:   PetscFunctionReturn(PETSC_SUCCESS);
770: }

772: /*@
773:   PCApplyRichardson - Applies several steps of Richardson iteration with
774:   the particular preconditioner. This routine is usually used by the
775:   Krylov solvers and not the application code directly.

777:   Collective

779:   Input Parameters:
780: + pc        - the `PC` preconditioner context
781: . b         - the right-hand side
782: . w         - one work vector
783: . rtol      - relative decrease in residual norm convergence criteria
784: . abstol    - absolute residual norm convergence criteria
785: . dtol      - divergence residual norm increase criteria
786: . its       - the number of iterations to apply.
787: - guesszero - if the input x contains nonzero initial guess

789:   Output Parameters:
790: + outits - number of iterations actually used (for SOR this always equals its)
791: . reason - the reason the apply terminated
792: - y      - the solution (also contains initial guess if guesszero is `PETSC_FALSE`

794:   Level: developer

796:   Notes:
797:   Most preconditioners do not support this function. Use the command
798:   `PCApplyRichardsonExists()` to determine if one does.

800:   Except for the `PCMG` this routine ignores the convergence tolerances
801:   and always runs for the number of iterations

803: .seealso: [](ch_ksp), `PC`, `PCApplyRichardsonExists()`, `PCMatApplyRichardson()`
804: @*/
805: PetscErrorCode PCApplyRichardson(PC pc, Vec b, Vec y, Vec w, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
806: {
807:   PetscFunctionBegin;
812:   PetscCheck(b != y, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "b and y must be different vectors");
813:   PetscCall(PCSetUp(pc));
814:   PetscUseTypeMethod(pc, applyrichardson, b, y, w, rtol, abstol, dtol, its, guesszero, outits, reason);
815:   PetscFunctionReturn(PETSC_SUCCESS);
816: }

818: /*@
819:   PCMatApplyRichardsonExists - Determines whether a particular preconditioner has a
820:   built-in fast application of Richardson's method on a block of vectors stored as a `MATDENSE`.

822:   Not Collective

824:   Input Parameter:
825: . pc - the preconditioner

827:   Output Parameter:
828: . exists - `PETSC_TRUE` or `PETSC_FALSE`

830:   Level: developer

832: .seealso: [](ch_ksp), `PC`, `KSPRICHARDSON`, `PCMatApplyRichardson()`, `PCApplyRichardsonExists()`
833: @*/
834: PetscErrorCode PCMatApplyRichardsonExists(PC pc, PetscBool *exists)
835: {
836:   PetscFunctionBegin;
838:   PetscAssertPointer(exists, 2);
839:   if (pc->ops->matapplyrichardson) *exists = PETSC_TRUE;
840:   else *exists = PETSC_FALSE;
841:   PetscFunctionReturn(PETSC_SUCCESS);
842: }

844: /*@
845:   PCMatApplyRichardson - Applies several steps of Richardson iteration with the particular preconditioner
846:   to multiple vectors stored as a `MATDENSE`. This routine is usually used by the Krylov solvers and not
847:   the application code directly.

849:   Collective

851:   Input Parameters:
852: + pc        - the `PC` preconditioner context
853: . B         - the block of right-hand sides
854: . W         - one work block of vectors, may be `NULL`
855: . rtol      - relative decrease in residual norm convergence criteria
856: . abstol    - absolute residual norm convergence criteria
857: . dtol      - divergence residual norm increase criteria
858: . its       - the number of iterations to apply
859: - guesszero - `PETSC_TRUE` if `Y` is known to be initially zero

861:   Output Parameters:
862: + outits - number of iterations actually used
863: . reason - the reason the apply terminated
864: - Y      - the block of solutions (also contains the initial guess if guesszero is `PETSC_FALSE`)

866:   Level: developer

868:   Notes:
869:   Most preconditioners do not support this function. Use the command
870:   `PCMatApplyRichardsonExists()` to determine if one does.

872:   `W` may be `NULL`. For example `KSPRICHARDSON` does not provide one, so implementations that need scratch space must allocate it themselves.

874:   Like `PCMatApply()`, `B` and `Y` must be different matrices.

876: .seealso: [](ch_ksp), `PC`, `PCMatApplyRichardsonExists()`, `PCApplyRichardson()`, `PCMatApply()`, `KSPMatSolve()`
877: @*/
878: PetscErrorCode PCMatApplyRichardson(PC pc, Mat B, Mat Y, Mat W, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt its, PetscBool guesszero, PetscInt *outits, PCRichardsonConvergedReason *reason)
879: {
880:   PetscFunctionBegin;
885:   PetscCheckSameComm(pc, 1, B, 2);
886:   PetscCheckSameComm(pc, 1, Y, 3);
887:   if (W) PetscCheckSameComm(pc, 1, W, 4);
888:   PetscCheckSameType(B, 2, Y, 3);
889:   PetscCheck(Y != B, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "Y and B must be different matrices");
890:   PetscCheck(!W || (W != Y && W != B), PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "W must be different from B and Y");
891:   PetscCall(PCMatCheckBlocks_Private(pc, B, Y, "right-hand sides", "solutions"));
892:   /* W has the same layout as B, so it is checked against Pmat and against the number of columns of Y in the same way */
893:   if (W) PetscCall(PCMatCheckBlocks_Private(pc, W, Y, "work vectors", "solutions"));
894:   PetscCall(PCSetUp(pc));
895:   PetscUseTypeMethod(pc, matapplyrichardson, B, Y, W, rtol, abstol, dtol, its, guesszero, outits, reason);
896:   PetscFunctionReturn(PETSC_SUCCESS);
897: }

899: /*@
900:   PCSetFailedReason - Sets the reason a `PCSetUp()` failed or `PC_NOERROR` if it did not fail

902:   Logically Collective

904:   Input Parameters:
905: + pc     - the `PC` preconditioner context
906: - reason - the reason it failed

908:   Level: advanced

910: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCFailedReason`
911: @*/
912: PetscErrorCode PCSetFailedReason(PC pc, PCFailedReason reason)
913: {
914:   PetscFunctionBegin;
916:   pc->failedreason = reason;
917:   PetscFunctionReturn(PETSC_SUCCESS);
918: }

920: /*@
921:   PCGetFailedReason - Gets the reason a `PCSetUp()` failed or `PC_NOERROR` if it did not fail

923:   Not Collective

925:   Input Parameter:
926: . pc - the `PC` preconditioner context

928:   Output Parameter:
929: . reason - the reason it failed

931:   Level: advanced

933:   Note:
934:   After a call to `KSPCheckDot()` or  `KSPCheckNorm()` inside a `KSPSolve()` or a call to `PCReduceFailedReason()`
935:   this is the maximum reason over all MPI processes in the `PC` communicator and hence logically collective.
936:   Otherwise it returns the local value.

938: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCSetFailedReason()`, `PCFailedReason`
939: @*/
940: PetscErrorCode PCGetFailedReason(PC pc, PCFailedReason *reason)
941: {
942:   PetscFunctionBegin;
944:   *reason = pc->failedreason;
945:   PetscFunctionReturn(PETSC_SUCCESS);
946: }

948: /*@
949:   PCReduceFailedReason - Reduce the failed reason among the MPI processes that share the `PC`

951:   Collective

953:   Input Parameter:
954: . pc - the `PC` preconditioner context

956:   Level: advanced

958:   Note:
959:   Different MPI processes may have different reasons or no reason, see `PCGetFailedReason()`. This routine
960:   makes them have a common value (failure if any MPI process had a failure).

962: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCGetFailedReason()`, `PCSetFailedReason()`, `PCFailedReason`
963: @*/
964: PetscErrorCode PCReduceFailedReason(PC pc)
965: {
966:   PetscInt buf;

968:   PetscFunctionBegin;
970:   buf = (PetscInt)pc->failedreason;
971:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &buf, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc)));
972:   pc->failedreason = (PCFailedReason)buf;
973:   PetscFunctionReturn(PETSC_SUCCESS);
974: }

976: /*
977:       a setupcall of 0 indicates never setup,
978:                      1 indicates has been previously setup
979:                     -1 indicates a PCSetUp() was attempted and failed
980: */
981: /*@
982:   PCSetUp - Prepares for the use of a preconditioner. Performs all the one-time operations needed before the preconditioner
983:   can be used with `PCApply()`

985:   Collective

987:   Input Parameter:
988: . pc - the `PC` preconditioner context

990:   Level: developer

992:   Notes:
993:   For example, for `PCLU` this will compute the factorization.

995:   This is called automatically by `KSPSetUp()` or `PCApply()` so rarely needs to be called directly.

997:   For nested preconditioners, such as `PCFIELDSPLIT` or `PCBJACOBI` this may not finish the construction of the preconditioner
998:   on the inner levels, the routine `PCSetUpOnBlocks()` may compute more of the preconditioner in those situations.

1000: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `KSPSetUp()`, `PCSetUpOnBlocks()`
1001: @*/
1002: PetscErrorCode PCSetUp(PC pc)
1003: {
1004:   const char *def;
1005:   MatState    matstate;

1007:   PetscFunctionBegin;
1009:   PetscCheck(pc->mat, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Missing A matrix. Use PCSetOperators()");
1010:   PetscCheck(pc->pmat, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Missing P matrix. Use PCSetOperators()");

1012:   if (pc->setupcalled && pc->reusepreconditioner) {
1013:     PetscCall(PetscInfo(pc, "Leaving PC with identical preconditioner since reuse preconditioner is set\n"));
1014:     PetscFunctionReturn(PETSC_SUCCESS);
1015:   }

1017:   PetscCall(MatGetState(pc->pmat, &matstate));
1018:   if (!pc->setupcalled) pc->flag = DIFFERENT_NONZERO_PATTERN;
1019:   else {
1020:     PetscBool same;

1022:     PetscCall(MatStateCompare(matstate, pc->matstate, &same));
1023:     if (same) PetscFunctionReturn(PETSC_SUCCESS);
1024:     pc->flag = SAME_NONZERO_PATTERN;
1025:     if (matstate.nonzerostate != pc->matstate.nonzerostate) {
1026:       PetscCall(PetscInfo(pc, "Setting up PC with different nonzero pattern\n"));
1027:       pc->flag = DIFFERENT_NONZERO_PATTERN;
1028:     }
1029:   }
1030:   pc->matstate = matstate;

1032:   if (!((PetscObject)pc)->type_name) {
1033:     PetscCall(PCGetDefaultType_Private(pc, &def));
1034:     PetscCall(PCSetType(pc, def));
1035:   }

1037:   PetscCall(MatSetErrorIfFailure(pc->pmat, pc->erroriffailure));
1038:   PetscCall(MatSetErrorIfFailure(pc->mat, pc->erroriffailure));
1039:   PetscCall(PetscLogEventBegin(PC_SetUp, pc, 0, 0, 0));
1040:   if (pc->ops->setup) {
1041:     PetscCall(PCLogEventsDeactivatePush());
1042:     PetscUseTypeMethod(pc, setup);
1043:     PetscCall(PCLogEventsDeactivatePop());
1044:   }
1045:   PetscCall(PetscLogEventEnd(PC_SetUp, pc, 0, 0, 0));
1046:   if (pc->postsetup) PetscCall((*pc->postsetup)(pc));
1047:   pc->setupcalled = PETSC_TRUE;
1048:   PetscFunctionReturn(PETSC_SUCCESS);
1049: }

1051: /*@
1052:   PCSetUpOnBlocks - Sets up the preconditioner for each block in
1053:   the block Jacobi, overlapping Schwarz, and fieldsplit methods.

1055:   Collective

1057:   Input Parameter:
1058: . pc - the `PC` preconditioner context

1060:   Level: developer

1062:   Notes:
1063:   For nested preconditioners such as `PCBJACOBI`, `PCSetUp()` is not called on each sub-`KSP` when `PCSetUp()` is
1064:   called on the outer `PC`, this routine ensures it is called.

1066:   It calls `PCSetUp()` if not yet called.

1068: .seealso: [](ch_ksp), `PC`, `PCSetUp()`, `PCCreate()`, `PCApply()`, `PCDestroy()`
1069: @*/
1070: PetscErrorCode PCSetUpOnBlocks(PC pc)
1071: {
1072:   PetscFunctionBegin;
1074:   if (!pc->setupcalled) PetscCall(PCSetUp(pc)); /* "if" to prevent -info extra prints */
1075:   if (!pc->ops->setuponblocks) PetscFunctionReturn(PETSC_SUCCESS);
1076:   PetscCall(MatSetErrorIfFailure(pc->pmat, pc->erroriffailure));
1077:   PetscCall(PetscLogEventBegin(PC_SetUpOnBlocks, pc, 0, 0, 0));
1078:   PetscCall(PCLogEventsDeactivatePush());
1079:   PetscUseTypeMethod(pc, setuponblocks);
1080:   PetscCall(PCLogEventsDeactivatePop());
1081:   PetscCall(PetscLogEventEnd(PC_SetUpOnBlocks, pc, 0, 0, 0));
1082:   PetscFunctionReturn(PETSC_SUCCESS);
1083: }

1085: /*@
1086:   PCSetModifySubMatrices - Sets a user-defined routine for modifying the
1087:   submatrices that arise within certain subdomain-based preconditioners such as `PCASM`

1089:   Logically Collective

1091:   Input Parameters:
1092: + pc   - the `PC` preconditioner context
1093: . func - routine for modifying the submatrices, see `PCModifySubMatricesFn`
1094: - ctx  - optional user-defined context (may be `NULL`)

1096:   Level: advanced

1098:   Notes:
1099:   The basic submatrices are extracted from the matrix used to construct the preconditioner as
1100:   usual; the user can then alter these (for example, to set different boundary
1101:   conditions for each submatrix) before they are used for the local solves.

1103:   `PCSetModifySubMatrices()` MUST be called before `KSPSetUp()` and
1104:   `KSPSolve()`.

1106:   A routine set by `PCSetModifySubMatrices()` is currently called within
1107:   `PCBJACOBI`, `PCASM`, `PCGASM`, and `PCHPDDM`.
1108:   All other preconditioners ignore this routine.

1110: .seealso: [](ch_ksp), `PC`, `PCModifySubMatricesFn`, `PCBJACOBI`, `PCASM`, `PCModifySubMatrices()`
1111: @*/
1112: PetscErrorCode PCSetModifySubMatrices(PC pc, PCModifySubMatricesFn *func, PetscCtx ctx)
1113: {
1114:   PetscFunctionBegin;
1116:   pc->modifysubmatrices  = func;
1117:   pc->modifysubmatricesP = ctx;
1118:   PetscFunctionReturn(PETSC_SUCCESS);
1119: }

1121: /*@
1122:   PCModifySubMatrices - Calls an optional user-defined routine within
1123:   certain preconditioners if one has been set with `PCSetModifySubMatrices()`.

1125:   Collective

1127:   Input Parameters:
1128: + pc     - the `PC` preconditioner context
1129: . nsub   - the number of local submatrices
1130: . row    - an array of index sets that contain the global row numbers
1131:          that comprise each local submatrix
1132: . col    - an array of index sets that contain the global column numbers
1133:          that comprise each local submatrix
1134: . submat - array of local submatrices
1135: - ctx    - optional user-defined context for private data for the
1136:          user-defined routine (may be `NULL`)

1138:   Output Parameter:
1139: . submat - array of local submatrices (the entries of which may
1140:             have been modified)

1142:   Level: developer

1144:   Note:
1145:   The user should NOT generally call this routine, as it will
1146:   automatically be called within certain preconditioners.

1148: .seealso: [](ch_ksp), `PC`, `PCModifySubMatricesFn`, `PCSetModifySubMatrices()`
1149: @*/
1150: PetscErrorCode PCModifySubMatrices(PC pc, PetscInt nsub, const IS row[], const IS col[], Mat submat[], PetscCtx ctx)
1151: {
1152:   PetscFunctionBegin;
1154:   if (!pc->modifysubmatrices) PetscFunctionReturn(PETSC_SUCCESS);
1155:   PetscCall(PetscLogEventBegin(PC_ModifySubMatrices, pc, 0, 0, 0));
1156:   PetscCall((*pc->modifysubmatrices)(pc, nsub, row, col, submat, ctx));
1157:   PetscCall(PetscLogEventEnd(PC_ModifySubMatrices, pc, 0, 0, 0));
1158:   PetscFunctionReturn(PETSC_SUCCESS);
1159: }

1161: /*@
1162:   PCSetOperators - Sets the matrix associated with the linear system and
1163:   a (possibly) different one from which the preconditioner will be constructed.

1165:   Logically Collective

1167:   Input Parameters:
1168: + pc   - the `PC` preconditioner context
1169: . Amat - the matrix that defines the linear system
1170: - Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.

1172:   Level: advanced

1174:   Notes:
1175:   Using this routine directly is rarely needed, the preferred, and equivalent, usage is `KSPSetOperators()`.

1177:   Passing a `NULL` for `Amat` or `Pmat` removes the matrix that is currently used.

1179:   If you wish to replace either `Amat` or `Pmat` but leave the other one untouched then
1180:   first call `KSPGetOperators()` to get the one you wish to keep, call `PetscObjectReference()`
1181:   on it and then pass it back in in your call to `KSPSetOperators()`.

1183:   More Notes about Repeated Solution of Linear Systems:
1184:   PETSc does NOT reset the matrix entries of either `Amat` or `Pmat`
1185:   to zero after a linear solve; the user is completely responsible for
1186:   matrix assembly.  See the routine `MatZeroEntries()` if desiring to
1187:   zero all elements of a matrix.

1189: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`
1190:  @*/
1191: PetscErrorCode PCSetOperators(PC pc, Mat Amat, Mat Pmat)
1192: {
1193:   PetscInt m1, n1, m2, n2;

1195:   PetscFunctionBegin;
1199:   if (Amat) PetscCheckSameComm(pc, 1, Amat, 2);
1200:   if (Pmat) PetscCheckSameComm(pc, 1, Pmat, 3);
1201:   if (pc->setupcalled && pc->mat && pc->pmat && Amat && Pmat) {
1202:     PetscCall(MatGetLocalSize(Amat, &m1, &n1));
1203:     PetscCall(MatGetLocalSize(pc->mat, &m2, &n2));
1204:     PetscCheck(m1 == m2 && n1 == n2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot change local size of Amat after use old sizes %" PetscInt_FMT " %" PetscInt_FMT " new sizes %" PetscInt_FMT " %" PetscInt_FMT, m2, n2, m1, n1);
1205:     PetscCall(MatGetLocalSize(Pmat, &m1, &n1));
1206:     PetscCall(MatGetLocalSize(pc->pmat, &m2, &n2));
1207:     PetscCheck(m1 == m2 && n1 == n2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Cannot change local size of Pmat after use old sizes %" PetscInt_FMT " %" PetscInt_FMT " new sizes %" PetscInt_FMT " %" PetscInt_FMT, m2, n2, m1, n1);
1208:   }

1210:   if (Pmat != pc->pmat) {
1211:     /* changing the operator that defines the preconditioner thus reneed to clear current states so new preconditioner is built */
1212:     PetscCall(MatStateInvalidate(pc->matstate));
1213:   }

1215:   /* reference first in case the matrices are the same */
1216:   PetscCall(PetscObjectReference((PetscObject)Amat));
1217:   PetscCall(MatDestroy(&pc->mat));
1218:   PetscCall(PetscObjectReference((PetscObject)Pmat));
1219:   PetscCall(MatDestroy(&pc->pmat));
1220:   pc->mat  = Amat;
1221:   pc->pmat = Pmat;
1222:   PetscFunctionReturn(PETSC_SUCCESS);
1223: }

1225: /*@
1226:   PCSetReusePreconditioner - reuse the current preconditioner even if the operator in the preconditioner `PC` has changed.

1228:   Logically Collective

1230:   Input Parameters:
1231: + pc   - the `PC` preconditioner context
1232: - flag - `PETSC_TRUE` do not compute a new preconditioner, `PETSC_FALSE` do compute a new preconditioner

1234:   Level: intermediate

1236:   Note:
1237:   Normally if a matrix inside a `PC` changes the `PC` automatically updates itself using information from the changed matrix. This option
1238:   prevents this.

1240: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`, `PCGetReusePreconditioner()`, `KSPSetReusePreconditioner()`
1241:  @*/
1242: PetscErrorCode PCSetReusePreconditioner(PC pc, PetscBool flag)
1243: {
1244:   PetscFunctionBegin;
1247:   pc->reusepreconditioner = flag;
1248:   PetscTryMethod(pc, "PCSetReusePreconditioner_C", (PC, PetscBool), (pc, flag));
1249:   PetscFunctionReturn(PETSC_SUCCESS);
1250: }

1252: /*@
1253:   PCGetReusePreconditioner - Determines if the `PC` reuses the current preconditioner even if the operator in the preconditioner has changed.

1255:   Not Collective

1257:   Input Parameter:
1258: . pc - the `PC` preconditioner context

1260:   Output Parameter:
1261: . flag - `PETSC_TRUE` do not compute a new preconditioner, `PETSC_FALSE` do compute a new preconditioner

1263:   Level: intermediate

1265: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`, `PCSetReusePreconditioner()`
1266:  @*/
1267: PetscErrorCode PCGetReusePreconditioner(PC pc, PetscBool *flag)
1268: {
1269:   PetscFunctionBegin;
1271:   PetscAssertPointer(flag, 2);
1272:   *flag = pc->reusepreconditioner;
1273:   PetscFunctionReturn(PETSC_SUCCESS);
1274: }

1276: /*@
1277:   PCGetOperators - Gets the matrix associated with the linear system and
1278:   possibly a different one which is used to construct the preconditioner.

1280:   Not Collective, though parallel `Mat`s are returned if `pc` is parallel

1282:   Input Parameter:
1283: . pc - the `PC` preconditioner context

1285:   Output Parameters:
1286: + Amat - the matrix defining the linear system
1287: - Pmat - the matrix from which the preconditioner is constructed, usually the same as Amat.

1289:   Level: intermediate

1291:   Note:
1292:   Does not increase the reference count of the matrices, so you should not destroy them

1294:   Alternative usage: If the operators have NOT been set with `KSPSetOperators()`/`PCSetOperators()` then the operators
1295:   are created in `PC` and returned to the user. In this case, if both operators
1296:   mat and pmat are requested, two DIFFERENT operators will be returned. If
1297:   only one is requested both operators in the PC will be the same (i.e. as
1298:   if one had called `KSPSetOperators()`/`PCSetOperators()` with the same argument for both Mats).
1299:   The user must set the sizes of the returned matrices and their type etc just
1300:   as if the user created them with `MatCreate()`. For example,

1302: .vb
1303:          KSP/PCGetOperators(ksp/pc,&Amat,NULL); is equivalent to
1304:            set size, type, etc of Amat

1306:          MatCreate(comm,&mat);
1307:          KSP/PCSetOperators(ksp/pc,Amat,Amat);
1308:          PetscObjectDereference((PetscObject)mat);
1309:            set size, type, etc of Amat
1310: .ve

1312:   and

1314: .vb
1315:          KSP/PCGetOperators(ksp/pc,&Amat,&Pmat); is equivalent to
1316:            set size, type, etc of Amat and Pmat

1318:          MatCreate(comm,&Amat);
1319:          MatCreate(comm,&Pmat);
1320:          KSP/PCSetOperators(ksp/pc,Amat,Pmat);
1321:          PetscObjectDereference((PetscObject)Amat);
1322:          PetscObjectDereference((PetscObject)Pmat);
1323:            set size, type, etc of Amat and Pmat
1324: .ve

1326:   The rationale for this support is so that when creating a `TS`, `SNES`, or `KSP` the hierarchy
1327:   of underlying objects (i.e. `SNES`, `KSP`, `PC`, `Mat`) and their lifespans can be completely
1328:   managed by the top most level object (i.e. the `TS`, `SNES`, or `KSP`). Another way to look
1329:   at this is when you create a `SNES` you do not NEED to create a `KSP` and attach it to
1330:   the `SNES` object (the `SNES` object manages it for you). Similarly when you create a KSP
1331:   you do not need to attach a `PC` to it (the `KSP` object manages the `PC` object for you).
1332:   Thus, why should YOU have to create the `Mat` and attach it to the `SNES`/`KSP`/`PC`, when
1333:   it can be created for you?

1335: .seealso: [](ch_ksp), `PC`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetOperators()`, `PCGetOperatorsSet()`
1336: @*/
1337: PetscErrorCode PCGetOperators(PC pc, Mat *Amat, Mat *Pmat)
1338: {
1339:   PetscFunctionBegin;
1341:   if (Amat) {
1342:     if (!pc->mat) {
1343:       if (pc->pmat && !Pmat) { /* Pmat has been set, but user did not request it, so use for Amat */
1344:         pc->mat = pc->pmat;
1345:         PetscCall(PetscObjectReference((PetscObject)pc->mat));
1346:       } else { /* both Amat and Pmat are empty */
1347:         PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), &pc->mat));
1348:         if (!Pmat) { /* user did NOT request Pmat, so make same as Amat */
1349:           pc->pmat = pc->mat;
1350:           PetscCall(PetscObjectReference((PetscObject)pc->pmat));
1351:         }
1352:       }
1353:     }
1354:     *Amat = pc->mat;
1355:   }
1356:   if (Pmat) {
1357:     if (!pc->pmat) {
1358:       if (pc->mat && !Amat) { /* Amat has been set but was not requested, so use for pmat */
1359:         pc->pmat = pc->mat;
1360:         PetscCall(PetscObjectReference((PetscObject)pc->pmat));
1361:       } else {
1362:         PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), &pc->pmat));
1363:         if (!Amat) { /* user did NOT request Amat, so make same as Pmat */
1364:           pc->mat = pc->pmat;
1365:           PetscCall(PetscObjectReference((PetscObject)pc->mat));
1366:         }
1367:       }
1368:     }
1369:     *Pmat = pc->pmat;
1370:   }
1371:   PetscFunctionReturn(PETSC_SUCCESS);
1372: }

1374: /*@
1375:   PCGetOperatorsSet - Determines if the matrix associated with the linear system and
1376:   possibly a different one associated with the preconditioner have been set in the `PC`.

1378:   Not Collective, though the results on all processes should be the same

1380:   Input Parameter:
1381: . pc - the `PC` preconditioner context

1383:   Output Parameters:
1384: + mat  - the matrix associated with the linear system was set
1385: - pmat - matrix associated with the preconditioner was set, usually the same

1387:   Level: intermediate

1389: .seealso: [](ch_ksp), `PC`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetOperators()`, `PCGetOperators()`
1390: @*/
1391: PetscErrorCode PCGetOperatorsSet(PC pc, PetscBool *mat, PetscBool *pmat)
1392: {
1393:   PetscFunctionBegin;
1395:   if (mat) *mat = (pc->mat) ? PETSC_TRUE : PETSC_FALSE;
1396:   if (pmat) *pmat = (pc->pmat) ? PETSC_TRUE : PETSC_FALSE;
1397:   PetscFunctionReturn(PETSC_SUCCESS);
1398: }

1400: /*@
1401:   PCFactorGetMatrix - Gets the factored matrix from the
1402:   preconditioner context.  This routine is valid only for the `PCLU`,
1403:   `PCILU`, `PCCHOLESKY`, and `PCICC` methods.

1405:   Not Collective though `mat` is parallel if `pc` is parallel

1407:   Input Parameter:
1408: . pc - the `PC` preconditioner context

1410:   Output Parameters:
1411: . mat - the factored matrix

1413:   Level: advanced

1415:   Note:
1416:   Does not increase the reference count for `mat` so DO NOT destroy it

1418: .seealso: [](ch_ksp), `PC`, `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
1419: @*/
1420: PetscErrorCode PCFactorGetMatrix(PC pc, Mat *mat)
1421: {
1422:   PetscFunctionBegin;
1424:   PetscAssertPointer(mat, 2);
1425:   PetscCall(PCFactorSetUpMatSolverType(pc));
1426:   PetscUseTypeMethod(pc, getfactoredmatrix, mat);
1427:   PetscFunctionReturn(PETSC_SUCCESS);
1428: }

1430: /*@
1431:   PCSetOptionsPrefix - Sets the prefix used for searching for all
1432:   `PC` options in the database.

1434:   Logically Collective

1436:   Input Parameters:
1437: + pc     - the `PC` preconditioner context
1438: - prefix - the prefix string to prepend to all `PC` option requests

1440:   Level: advanced

1442:   Note:
1443:   A hyphen (-) must NOT be given at the beginning of the prefix name.
1444:   The first character of all runtime options is AUTOMATICALLY the
1445:   hyphen.

1447: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCAppendOptionsPrefix()`, `PCGetOptionsPrefix()`
1448: @*/
1449: PetscErrorCode PCSetOptionsPrefix(PC pc, const char prefix[])
1450: {
1451:   PetscFunctionBegin;
1453:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)pc, prefix));
1454:   PetscFunctionReturn(PETSC_SUCCESS);
1455: }

1457: /*@
1458:   PCAppendOptionsPrefix - Appends to the prefix used for searching for all
1459:   `PC` options in the database.

1461:   Logically Collective

1463:   Input Parameters:
1464: + pc     - the `PC` preconditioner context
1465: - prefix - the prefix string to prepend to all `PC` option requests

1467:   Level: advanced

1469:   Note:
1470:   A hyphen (-) must NOT be given at the beginning of the prefix name.
1471:   The first character of all runtime options is AUTOMATICALLY the
1472:   hyphen.

1474: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCSetOptionsPrefix()`, `PCGetOptionsPrefix()`
1475: @*/
1476: PetscErrorCode PCAppendOptionsPrefix(PC pc, const char prefix[])
1477: {
1478:   PetscFunctionBegin;
1480:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)pc, prefix));
1481:   PetscFunctionReturn(PETSC_SUCCESS);
1482: }

1484: /*@
1485:   PCGetOptionsPrefix - Gets the prefix used for searching for all
1486:   `PC` options in the database.

1488:   Not Collective

1490:   Input Parameter:
1491: . pc - the `PC` preconditioner context

1493:   Output Parameter:
1494: . prefix - pointer to the prefix string used, is returned

1496:   Level: advanced

1498: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCSetOptionsPrefix()`, `PCAppendOptionsPrefix()`
1499: @*/
1500: PetscErrorCode PCGetOptionsPrefix(PC pc, const char *prefix[])
1501: {
1502:   PetscFunctionBegin;
1504:   PetscAssertPointer(prefix, 2);
1505:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)pc, prefix));
1506:   PetscFunctionReturn(PETSC_SUCCESS);
1507: }

1509: /*
1510:    Indicates the right-hand side will be changed by KSPSolve(), this occurs for a few
1511:   preconditioners including BDDC and Eisentat that transform the equations before applying
1512:   the Krylov methods
1513: */
1514: PETSC_INTERN PetscErrorCode PCPreSolveChangeRHS(PC pc, PetscBool *change)
1515: {
1516:   PetscFunctionBegin;
1518:   PetscAssertPointer(change, 2);
1519:   *change = PETSC_FALSE;
1520:   PetscTryMethod(pc, "PCPreSolveChangeRHS_C", (PC, PetscBool *), (pc, change));
1521:   PetscFunctionReturn(PETSC_SUCCESS);
1522: }

1524: /*@
1525:   PCPreSolve - Optional pre-solve phase, intended for any preconditioner-specific actions that must be performed before
1526:   the iterative solve itself. Used in conjunction with `PCPostSolve()`

1528:   Collective

1530:   Input Parameters:
1531: + pc  - the `PC` preconditioner context
1532: - ksp - the Krylov subspace context

1534:   Level: developer

1536:   Notes:
1537:   `KSPSolve()` calls this directly, so is rarely called by the user.

1539:   Certain preconditioners, such as the `PCType` of `PCEISENSTAT`, change the formulation of the linear system to be solved iteratively.
1540:   This function performs that transformation. `PCPostSolve()` then transforms the system back to its original form after the solve.
1541:   `PCPostSolve()` also transforms the resulting solution of the transformed system to the solution of the original problem.

1543:   `KSPSetPostSolve()` provides an alternative way to provide such transformations.

1545: .seealso: [](ch_ksp), `PC`, `PCPostSolve()`, `KSP`, `PCSetPostSetUp()`, `KSPSetPreSolve()`, `KSPSetPostSolve()`
1546: @*/
1547: PetscErrorCode PCPreSolve(PC pc, KSP ksp)
1548: {
1549:   Vec x, rhs;

1551:   PetscFunctionBegin;
1554:   pc->presolvedone++;
1555:   PetscCheck(pc->presolvedone <= 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot embed PCPreSolve() more than twice");
1556:   PetscCall(KSPGetSolution(ksp, &x));
1557:   PetscCall(KSPGetRhs(ksp, &rhs));
1558:   PetscTryTypeMethod(pc, presolve, ksp, rhs, x);
1559:   PetscFunctionReturn(PETSC_SUCCESS);
1560: }

1562: /*@
1563:   PCSetPostSetUp - Sets function called at the end of `PCSetUp()` to adjust the computed preconditioner

1565:   Logically Collective

1567:   Input Parameters:
1568: + pc        - the preconditioner object
1569: - postsetup - the function to call after `PCSetUp()`

1571:   Calling sequence of `postsetup`:
1572: . pc - the `PC` context

1574:   Level: developer

1576: .seealso: [](ch_ksp), `PC`, `PCSetUp()`
1577: @*/
1578: PetscErrorCode PCSetPostSetUp(PC pc, PetscErrorCode (*postsetup)(PC pc))
1579: {
1580:   PetscFunctionBegin;
1582:   pc->postsetup = postsetup;
1583:   PetscFunctionReturn(PETSC_SUCCESS);
1584: }

1586: /*@
1587:   PCPostSolve - Optional post-solve phase, intended for any
1588:   preconditioner-specific actions that must be performed after
1589:   the iterative solve itself.

1591:   Collective

1593:   Input Parameters:
1594: + pc  - the `PC` preconditioner context
1595: - ksp - the `KSP` Krylov subspace context

1597:   Example Usage:
1598: .vb
1599:     PCPreSolve(pc,ksp);
1600:     KSPSolve(ksp,b,x);
1601:     PCPostSolve(pc,ksp);
1602: .ve

1604:   Level: developer

1606:   Note:
1607:   `KSPSolve()` calls this routine directly, so it is rarely called by the user.

1609: .seealso: [](ch_ksp), `PC`, `KSPSetPostSolve()`, `KSPSetPreSolve()`, `PCPreSolve()`, `KSPSolve()`
1610: @*/
1611: PetscErrorCode PCPostSolve(PC pc, KSP ksp)
1612: {
1613:   Vec x, rhs;

1615:   PetscFunctionBegin;
1618:   pc->presolvedone--;
1619:   PetscCall(KSPGetSolution(ksp, &x));
1620:   PetscCall(KSPGetRhs(ksp, &rhs));
1621:   PetscTryTypeMethod(pc, postsolve, ksp, rhs, x);
1622:   PetscFunctionReturn(PETSC_SUCCESS);
1623: }

1625: /*@
1626:   PCLoad - Loads a `PC` that has been stored in binary  with `PCView()`.

1628:   Collective

1630:   Input Parameters:
1631: + newdm  - the newly loaded `PC`, this needs to have been created with `PCCreate()` or
1632:            some related function before a call to `PCLoad()`.
1633: - viewer - binary file viewer `PETSCVIEWERBINARY`, obtained from `PetscViewerBinaryOpen()`

1635:   Level: intermediate

1637:   Note:
1638:   The type is determined by the data in the file, any `PCType` set into the `PC` before this call is ignored.

1640: .seealso: [](ch_ksp), `PC`, `PetscViewerBinaryOpen()`, `PCView()`, `MatLoad()`, `VecLoad()`, `PETSCVIEWERBINARY`
1641: @*/
1642: PetscErrorCode PCLoad(PC newdm, PetscViewer viewer)
1643: {
1644:   PetscBool isbinary;
1645:   PetscInt  classid;
1646:   char      type[256];

1648:   PetscFunctionBegin;
1651:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1652:   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");

1654:   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
1655:   PetscCheck(classid == PC_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not PC next in file");
1656:   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
1657:   PetscCall(PCSetType(newdm, type));
1658:   PetscTryTypeMethod(newdm, load, viewer);
1659:   PetscFunctionReturn(PETSC_SUCCESS);
1660: }

1662: #include <petscdraw.h>
1663: #if PetscDefined(HAVE_SAWS)
1664: #include <petscviewersaws.h>
1665: #endif

1667: /*@
1668:   PCViewFromOptions - View (print or provide information about) the `PC`, based on options in the options database

1670:   Collective

1672:   Input Parameters:
1673: + A    - the `PC` context
1674: . obj  - optional object that provides the options prefix, pass `NULL` to use the options prefix of `A`
1675: - name - command line option name

1677:   Options Database Key:
1678: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

1680:   Level: developer

1682:   Note:
1683:   This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
1684:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

1686: .seealso: [](ch_ksp), `PC`, `PCView()`, `PetscObjectViewFromOptions()`, `PCCreate()`, `PetscOptionsCreateViewer()`
1687: @*/
1688: PetscErrorCode PCViewFromOptions(PC A, PetscObject obj, const char name[])
1689: {
1690:   PetscFunctionBegin;
1692:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1693:   PetscFunctionReturn(PETSC_SUCCESS);
1694: }

1696: /*@
1697:   PCView - Prints information about the `PC`

1699:   Collective

1701:   Input Parameters:
1702: + pc     - the `PC` preconditioner context
1703: - viewer - optional `PetscViewer` visualization context

1705:   Level: intermediate

1707:   Notes:
1708:   The available visualization contexts include
1709: +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1710: -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1711:   output where only the first processor opens
1712:   the file. All other processors send their
1713:   data to the first processor to print.

1715:   The user can open an alternative visualization contexts with
1716:   `PetscViewerASCIIOpen()` (output to a specified file).

1718: .seealso: [](ch_ksp), `PC`, `PetscViewer`, `PetscViewerType`, `KSPView()`, `PetscViewerASCIIOpen()`
1719: @*/
1720: PetscErrorCode PCView(PC pc, PetscViewer viewer)
1721: {
1722:   PCType            cstr;
1723:   PetscViewerFormat format;
1724:   PetscBool         isascii, isstring, isbinary, isdraw, pop = PETSC_FALSE;
1725: #if PetscDefined(HAVE_SAWS)
1726:   PetscBool issaws;
1727: #endif

1729:   PetscFunctionBegin;
1731:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)pc), &viewer));
1733:   PetscCheckSameComm(pc, 1, viewer, 2);

1735:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1736:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1737:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1738:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1739: #if PetscDefined(HAVE_SAWS)
1740:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1741: #endif

1743:   if (isascii) {
1744:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)pc, viewer));
1745:     if (!pc->setupcalled) PetscCall(PetscViewerASCIIPrintf(viewer, "  PC has not been set up so information may be incomplete\n"));
1746:     PetscCall(PetscViewerASCIIPushTab(viewer));
1747:     PetscTryTypeMethod(pc, view, viewer);
1748:     PetscCall(PetscViewerASCIIPopTab(viewer));
1749:     if (pc->mat) {
1750:       PetscCall(PetscViewerGetFormat(viewer, &format));
1751:       if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) {
1752:         PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
1753:         pop = PETSC_TRUE;
1754:       }
1755:       if (pc->pmat == pc->mat) {
1756:         PetscCall(PetscViewerASCIIPrintf(viewer, "  linear system matrix, which is also used to construct the preconditioner:\n"));
1757:         PetscCall(PetscViewerASCIIPushTab(viewer));
1758:         PetscCall(MatView(pc->mat, viewer));
1759:         PetscCall(PetscViewerASCIIPopTab(viewer));
1760:       } else {
1761:         if (pc->pmat) {
1762:           PetscCall(PetscViewerASCIIPrintf(viewer, "  linear system matrix, followed by the matrix used to construct the preconditioner:\n"));
1763:         } else {
1764:           PetscCall(PetscViewerASCIIPrintf(viewer, "  linear system matrix:\n"));
1765:         }
1766:         PetscCall(PetscViewerASCIIPushTab(viewer));
1767:         PetscCall(MatView(pc->mat, viewer));
1768:         if (pc->pmat) PetscCall(MatView(pc->pmat, viewer));
1769:         PetscCall(PetscViewerASCIIPopTab(viewer));
1770:       }
1771:       if (pop) PetscCall(PetscViewerPopFormat(viewer));
1772:     }
1773:   } else if (isstring) {
1774:     PetscCall(PCGetType(pc, &cstr));
1775:     PetscCall(PetscViewerStringSPrintf(viewer, " PCType: %-7.7s", cstr));
1776:     PetscTryTypeMethod(pc, view, viewer);
1777:     if (pc->mat) PetscCall(MatView(pc->mat, viewer));
1778:     if (pc->pmat && pc->pmat != pc->mat) PetscCall(MatView(pc->pmat, viewer));
1779:   } else if (isbinary) {
1780:     PetscInt    classid = PC_FILE_CLASSID;
1781:     MPI_Comm    comm;
1782:     PetscMPIInt rank;
1783:     char        type[256];

1785:     PetscCall(PetscObjectGetComm((PetscObject)pc, &comm));
1786:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1787:     if (rank == 0) {
1788:       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
1789:       PetscCall(PetscStrncpy(type, ((PetscObject)pc)->type_name, 256));
1790:       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
1791:     }
1792:     PetscTryTypeMethod(pc, view, viewer);
1793:   } else if (isdraw) {
1794:     PetscDraw draw;
1795:     char      str[25];
1796:     PetscReal x, y, bottom, h;
1797:     PetscInt  n;

1799:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1800:     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1801:     if (pc->mat) {
1802:       PetscCall(MatGetSize(pc->mat, &n, NULL));
1803:       PetscCall(PetscSNPrintf(str, 25, "PC: %s (%" PetscInt_FMT ")", ((PetscObject)pc)->type_name, n));
1804:     } else {
1805:       PetscCall(PetscSNPrintf(str, 25, "PC: %s", ((PetscObject)pc)->type_name));
1806:     }
1807:     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_RED, PETSC_DRAW_BLACK, str, NULL, &h));
1808:     bottom = y - h;
1809:     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1810:     PetscTryTypeMethod(pc, view, viewer);
1811:     PetscCall(PetscDrawPopCurrentPoint(draw));
1812: #if PetscDefined(HAVE_SAWS)
1813:   } else if (issaws) {
1814:     PetscMPIInt rank;

1816:     PetscCall(PetscObjectName((PetscObject)pc));
1817:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1818:     if (!((PetscObject)pc)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)pc, viewer));
1819:     if (pc->mat) PetscCall(MatView(pc->mat, viewer));
1820:     if (pc->pmat && pc->pmat != pc->mat) PetscCall(MatView(pc->pmat, viewer));
1821: #endif
1822:   }
1823:   PetscFunctionReturn(PETSC_SUCCESS);
1824: }

1826: /*@
1827:   PCRegister -  Adds a method (`PCType`) to the PETSc preconditioner package.

1829:   Not collective. No Fortran Support

1831:   Input Parameters:
1832: + sname    - name of a new user-defined solver
1833: - function - routine to create the method context which will be stored in a `PC` when `PCSetType()` is called

1835:   Example Usage:
1836: .vb
1837:    PCRegister("my_solver", MySolverCreate);
1838: .ve

1840:   Then, your solver can be chosen with the procedural interface via
1841: .vb
1842:   PCSetType(pc, "my_solver")
1843: .ve
1844:   or at runtime via the option
1845: .vb
1846:   -pc_type my_solver
1847: .ve

1849:   Level: advanced

1851:   Note:
1852:   A simpler alternative to using `PCRegister()` for an application specific preconditioner is to use a `PC` of `PCType` `PCSHELL` and
1853:   provide your customizations with `PCShellSetContext()` and `PCShellSetApply()`

1855:   `PCRegister()` may be called multiple times to add several user-defined preconditioners.

1857: .seealso: [](ch_ksp), `PC`, `PCType`, `PCRegisterAll()`, `PCSetType()`, `PCShellSetContext()`, `PCShellSetApply()`, `PCSHELL`
1858: @*/
1859: PetscErrorCode PCRegister(const char sname[], PetscErrorCode (*function)(PC))
1860: {
1861:   PetscFunctionBegin;
1862:   PetscCall(PCInitializePackage());
1863:   PetscCall(PetscFunctionListAdd(&PCList, sname, function));
1864:   PetscFunctionReturn(PETSC_SUCCESS);
1865: }

1867: static PetscErrorCode MatMult_PC(Mat A, Vec X, Vec Y)
1868: {
1869:   PC pc;

1871:   PetscFunctionBegin;
1872:   PetscCall(MatShellGetContext(A, &pc));
1873:   PetscCall(PCApply(pc, X, Y));
1874:   PetscFunctionReturn(PETSC_SUCCESS);
1875: }

1877: /*@
1878:   PCComputeOperator - Computes the explicit preconditioned operator as a matrix `Mat`.

1880:   Collective

1882:   Input Parameters:
1883: + pc      - the `PC` preconditioner object
1884: - mattype - the `MatType` to be used for the operator

1886:   Output Parameter:
1887: . mat - the explicit preconditioned operator

1889:   Level: advanced

1891:   Note:
1892:   This computation is done by applying the operators to columns of the identity matrix.
1893:   This routine is costly in general, and is recommended for use only with relatively small systems.
1894:   Currently, this routine uses a dense matrix format when `mattype` == `NULL`

1896:   Developer Note:
1897:   This should be called `PCCreateExplicitOperator()`

1899: .seealso: [](ch_ksp), `PC`, `KSPComputeOperator()`, `MatType`
1900: @*/
1901: PetscErrorCode PCComputeOperator(PC pc, MatType mattype, Mat *mat)
1902: {
1903:   PetscInt N, M, m, n;
1904:   Mat      A, Apc;

1906:   PetscFunctionBegin;
1908:   PetscAssertPointer(mat, 3);
1909:   PetscCall(PCGetOperators(pc, &A, NULL));
1910:   PetscCall(MatGetLocalSize(A, &m, &n));
1911:   PetscCall(MatGetSize(A, &M, &N));
1912:   PetscCall(MatCreateShell(PetscObjectComm((PetscObject)pc), m, n, M, N, pc, &Apc));
1913:   PetscCall(MatShellSetOperation(Apc, MATOP_MULT, (PetscErrorCodeFn *)MatMult_PC));
1914:   PetscCall(MatComputeOperator(Apc, mattype, mat));
1915:   PetscCall(MatDestroy(&Apc));
1916:   PetscFunctionReturn(PETSC_SUCCESS);
1917: }

1919: /*@
1920:   PCSetCoordinates - sets the coordinates of all the nodes (degrees of freedom in the vector) on the local process

1922:   Collective

1924:   Input Parameters:
1925: + pc     - the `PC` preconditioner context
1926: . dim    - the dimension of the coordinates 1, 2, or 3
1927: . nloc   - the blocked size of the coordinates array
1928: - coords - the coordinates array

1930:   Level: intermediate

1932:   Notes:
1933:   `coords` is an array of the dim coordinates for the nodes on
1934:   the local processor, of size `dim`*`nloc`.
1935:   If there are 108 equations (dofs) on a processor
1936:   for a 3d displacement finite element discretization of elasticity (so
1937:   that there are nloc = 36 = 108/3 nodes) then the array must have 108
1938:   double precision values (ie, 3 * 36).  These x y z coordinates
1939:   should be ordered for nodes 0 to N-1 like so: [ 0.x, 0.y, 0.z, 1.x,
1940:   ... , N-1.z ].

1942:   The information provided here can be used by some preconditioners, such as `PCGAMG`, to produce a better preconditioner.
1943:   See also  `MatSetNearNullSpace()`.

1945: .seealso: [](ch_ksp), `PC`, `MatSetNearNullSpace()`
1946: @*/
1947: PetscErrorCode PCSetCoordinates(PC pc, PetscInt dim, PetscInt nloc, PetscReal coords[])
1948: {
1949:   PetscFunctionBegin;
1952:   PetscTryMethod(pc, "PCSetCoordinates_C", (PC, PetscInt, PetscInt, PetscReal[]), (pc, dim, nloc, coords));
1953:   PetscFunctionReturn(PETSC_SUCCESS);
1954: }

1956: /*@
1957:   PCGetInterpolations - Gets interpolation matrices for all levels (except level 0)

1959:   Logically Collective

1961:   Input Parameter:
1962: . pc - the precondition context

1964:   Output Parameters:
1965: + num_levels     - the number of levels
1966: - interpolations - the interpolation matrices (size of `num_levels`-1)

1968:   Level: advanced

1970:   Developer Note:
1971:   Why is this here instead of in `PCMG` etc?

1973: .seealso: [](ch_ksp), `PC`, `PCMG`, `PCMGGetRestriction()`, `PCMGSetInterpolation()`, `PCMGGetInterpolation()`, `PCGetCoarseOperators()`
1974: @*/
1975: PetscErrorCode PCGetInterpolations(PC pc, PetscInt *num_levels, Mat *interpolations[])
1976: {
1977:   PetscFunctionBegin;
1979:   PetscAssertPointer(num_levels, 2);
1980:   PetscAssertPointer(interpolations, 3);
1981:   PetscUseMethod(pc, "PCGetInterpolations_C", (PC, PetscInt *, Mat *[]), (pc, num_levels, interpolations));
1982:   PetscFunctionReturn(PETSC_SUCCESS);
1983: }

1985: /*@
1986:   PCGetCoarseOperators - Gets coarse operator matrices for all levels (except the finest level)

1988:   Logically Collective

1990:   Input Parameter:
1991: . pc - the precondition context

1993:   Output Parameters:
1994: + num_levels      - the number of levels
1995: - coarseOperators - the coarse operator matrices (size of `num_levels`-1)

1997:   Level: advanced

1999:   Developer Note:
2000:   Why is this here instead of in `PCMG` etc?

2002: .seealso: [](ch_ksp), `PC`, `PCMG`, `PCMGGetRestriction()`, `PCMGSetInterpolation()`, `PCMGGetRScale()`, `PCMGGetInterpolation()`, `PCGetInterpolations()`
2003: @*/
2004: PetscErrorCode PCGetCoarseOperators(PC pc, PetscInt *num_levels, Mat *coarseOperators[])
2005: {
2006:   PetscFunctionBegin;
2008:   PetscAssertPointer(num_levels, 2);
2009:   PetscAssertPointer(coarseOperators, 3);
2010:   PetscUseMethod(pc, "PCGetCoarseOperators_C", (PC, PetscInt *, Mat *[]), (pc, num_levels, coarseOperators));
2011:   PetscFunctionReturn(PETSC_SUCCESS);
2012: }