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: PetscCheck(Y != B, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "Y and B must be different matrices");
889: PetscCheck(!W || (W != Y && W != B), PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_IDN, "W must be different from B and Y");
890: PetscCall(PCMatCheckBlocks_Private(pc, B, Y, "right-hand sides", "solutions"));
891: /* 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 */
892: if (W) PetscCall(PCMatCheckBlocks_Private(pc, W, Y, "work vectors", "solutions"));
893: PetscCall(PCSetUp(pc));
894: PetscUseTypeMethod(pc, matapplyrichardson, B, Y, W, rtol, abstol, dtol, its, guesszero, outits, reason);
895: PetscFunctionReturn(PETSC_SUCCESS);
896: }
898: /*@
899: PCSetFailedReason - Sets the reason a `PCSetUp()` failed or `PC_NOERROR` if it did not fail
901: Logically Collective
903: Input Parameters:
904: + pc - the `PC` preconditioner context
905: - reason - the reason it failed
907: Level: advanced
909: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCFailedReason`
910: @*/
911: PetscErrorCode PCSetFailedReason(PC pc, PCFailedReason reason)
912: {
913: PetscFunctionBegin;
915: pc->failedreason = reason;
916: PetscFunctionReturn(PETSC_SUCCESS);
917: }
919: /*@
920: PCGetFailedReason - Gets the reason a `PCSetUp()` failed or `PC_NOERROR` if it did not fail
922: Not Collective
924: Input Parameter:
925: . pc - the `PC` preconditioner context
927: Output Parameter:
928: . reason - the reason it failed
930: Level: advanced
932: Note:
933: After a call to `KSPCheckDot()` or `KSPCheckNorm()` inside a `KSPSolve()` or a call to `PCReduceFailedReason()`
934: this is the maximum reason over all MPI processes in the `PC` communicator and hence logically collective.
935: Otherwise it returns the local value.
937: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCSetFailedReason()`, `PCFailedReason`
938: @*/
939: PetscErrorCode PCGetFailedReason(PC pc, PCFailedReason *reason)
940: {
941: PetscFunctionBegin;
943: *reason = pc->failedreason;
944: PetscFunctionReturn(PETSC_SUCCESS);
945: }
947: /*@
948: PCReduceFailedReason - Reduce the failed reason among the MPI processes that share the `PC`
950: Collective
952: Input Parameter:
953: . pc - the `PC` preconditioner context
955: Level: advanced
957: Note:
958: Different MPI processes may have different reasons or no reason, see `PCGetFailedReason()`. This routine
959: makes them have a common value (failure if any MPI process had a failure).
961: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `PCGetFailedReason()`, `PCSetFailedReason()`, `PCFailedReason`
962: @*/
963: PetscErrorCode PCReduceFailedReason(PC pc)
964: {
965: PetscInt buf;
967: PetscFunctionBegin;
969: buf = (PetscInt)pc->failedreason;
970: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &buf, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)pc)));
971: pc->failedreason = (PCFailedReason)buf;
972: PetscFunctionReturn(PETSC_SUCCESS);
973: }
975: /*
976: a setupcall of 0 indicates never setup,
977: 1 indicates has been previously setup
978: -1 indicates a PCSetUp() was attempted and failed
979: */
980: /*@
981: PCSetUp - Prepares for the use of a preconditioner. Performs all the one-time operations needed before the preconditioner
982: can be used with `PCApply()`
984: Collective
986: Input Parameter:
987: . pc - the `PC` preconditioner context
989: Level: developer
991: Notes:
992: For example, for `PCLU` this will compute the factorization.
994: This is called automatically by `KSPSetUp()` or `PCApply()` so rarely needs to be called directly.
996: For nested preconditioners, such as `PCFIELDSPLIT` or `PCBJACOBI` this may not finish the construction of the preconditioner
997: on the inner levels, the routine `PCSetUpOnBlocks()` may compute more of the preconditioner in those situations.
999: .seealso: [](ch_ksp), `PC`, `PCCreate()`, `PCApply()`, `PCDestroy()`, `KSPSetUp()`, `PCSetUpOnBlocks()`
1000: @*/
1001: PetscErrorCode PCSetUp(PC pc)
1002: {
1003: const char *def;
1004: MatState matstate;
1006: PetscFunctionBegin;
1008: PetscCheck(pc->mat, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Missing A matrix. Use PCSetOperators()");
1009: PetscCheck(pc->pmat, PetscObjectComm((PetscObject)pc), PETSC_ERR_ORDER, "Missing P matrix. Use PCSetOperators()");
1011: if (pc->setupcalled && pc->reusepreconditioner) {
1012: PetscCall(PetscInfo(pc, "Leaving PC with identical preconditioner since reuse preconditioner is set\n"));
1013: PetscFunctionReturn(PETSC_SUCCESS);
1014: }
1016: PetscCall(MatGetState(pc->pmat, &matstate));
1017: if (!pc->setupcalled) pc->flag = DIFFERENT_NONZERO_PATTERN;
1018: else {
1019: PetscBool same;
1021: PetscCall(MatStateCompare(matstate, pc->matstate, &same));
1022: if (same) PetscFunctionReturn(PETSC_SUCCESS);
1023: pc->flag = SAME_NONZERO_PATTERN;
1024: if (matstate.nonzerostate != pc->matstate.nonzerostate) {
1025: PetscCall(PetscInfo(pc, "Setting up PC with different nonzero pattern\n"));
1026: pc->flag = DIFFERENT_NONZERO_PATTERN;
1027: }
1028: }
1029: pc->matstate = matstate;
1031: if (!((PetscObject)pc)->type_name) {
1032: PetscCall(PCGetDefaultType_Private(pc, &def));
1033: PetscCall(PCSetType(pc, def));
1034: }
1036: PetscCall(MatSetErrorIfFailure(pc->pmat, pc->erroriffailure));
1037: PetscCall(MatSetErrorIfFailure(pc->mat, pc->erroriffailure));
1038: PetscCall(PetscLogEventBegin(PC_SetUp, pc, 0, 0, 0));
1039: if (pc->ops->setup) {
1040: PetscCall(PCLogEventsDeactivatePush());
1041: PetscUseTypeMethod(pc, setup);
1042: PetscCall(PCLogEventsDeactivatePop());
1043: }
1044: PetscCall(PetscLogEventEnd(PC_SetUp, pc, 0, 0, 0));
1045: if (pc->postsetup) PetscCall((*pc->postsetup)(pc));
1046: pc->setupcalled = PETSC_TRUE;
1047: PetscFunctionReturn(PETSC_SUCCESS);
1048: }
1050: /*@
1051: PCSetUpOnBlocks - Sets up the preconditioner for each block in
1052: the block Jacobi, overlapping Schwarz, and fieldsplit methods.
1054: Collective
1056: Input Parameter:
1057: . pc - the `PC` preconditioner context
1059: Level: developer
1061: Notes:
1062: For nested preconditioners such as `PCBJACOBI`, `PCSetUp()` is not called on each sub-`KSP` when `PCSetUp()` is
1063: called on the outer `PC`, this routine ensures it is called.
1065: It calls `PCSetUp()` if not yet called.
1067: .seealso: [](ch_ksp), `PC`, `PCSetUp()`, `PCCreate()`, `PCApply()`, `PCDestroy()`
1068: @*/
1069: PetscErrorCode PCSetUpOnBlocks(PC pc)
1070: {
1071: PetscFunctionBegin;
1073: if (!pc->setupcalled) PetscCall(PCSetUp(pc)); /* "if" to prevent -info extra prints */
1074: if (!pc->ops->setuponblocks) PetscFunctionReturn(PETSC_SUCCESS);
1075: PetscCall(MatSetErrorIfFailure(pc->pmat, pc->erroriffailure));
1076: PetscCall(PetscLogEventBegin(PC_SetUpOnBlocks, pc, 0, 0, 0));
1077: PetscCall(PCLogEventsDeactivatePush());
1078: PetscUseTypeMethod(pc, setuponblocks);
1079: PetscCall(PCLogEventsDeactivatePop());
1080: PetscCall(PetscLogEventEnd(PC_SetUpOnBlocks, pc, 0, 0, 0));
1081: PetscFunctionReturn(PETSC_SUCCESS);
1082: }
1084: /*@
1085: PCSetModifySubMatrices - Sets a user-defined routine for modifying the
1086: submatrices that arise within certain subdomain-based preconditioners such as `PCASM`
1088: Logically Collective
1090: Input Parameters:
1091: + pc - the `PC` preconditioner context
1092: . func - routine for modifying the submatrices, see `PCModifySubMatricesFn`
1093: - ctx - optional user-defined context (may be `NULL`)
1095: Level: advanced
1097: Notes:
1098: The basic submatrices are extracted from the matrix used to construct the preconditioner as
1099: usual; the user can then alter these (for example, to set different boundary
1100: conditions for each submatrix) before they are used for the local solves.
1102: `PCSetModifySubMatrices()` MUST be called before `KSPSetUp()` and
1103: `KSPSolve()`.
1105: A routine set by `PCSetModifySubMatrices()` is currently called within
1106: `PCBJACOBI`, `PCASM`, `PCGASM`, and `PCHPDDM`.
1107: All other preconditioners ignore this routine.
1109: .seealso: [](ch_ksp), `PC`, `PCModifySubMatricesFn`, `PCBJACOBI`, `PCASM`, `PCModifySubMatrices()`
1110: @*/
1111: PetscErrorCode PCSetModifySubMatrices(PC pc, PCModifySubMatricesFn *func, PetscCtx ctx)
1112: {
1113: PetscFunctionBegin;
1115: pc->modifysubmatrices = func;
1116: pc->modifysubmatricesP = ctx;
1117: PetscFunctionReturn(PETSC_SUCCESS);
1118: }
1120: /*@
1121: PCModifySubMatrices - Calls an optional user-defined routine within
1122: certain preconditioners if one has been set with `PCSetModifySubMatrices()`.
1124: Collective
1126: Input Parameters:
1127: + pc - the `PC` preconditioner context
1128: . nsub - the number of local submatrices
1129: . row - an array of index sets that contain the global row numbers
1130: that comprise each local submatrix
1131: . col - an array of index sets that contain the global column numbers
1132: that comprise each local submatrix
1133: . submat - array of local submatrices
1134: - ctx - optional user-defined context for private data for the
1135: user-defined routine (may be `NULL`)
1137: Output Parameter:
1138: . submat - array of local submatrices (the entries of which may
1139: have been modified)
1141: Level: developer
1143: Note:
1144: The user should NOT generally call this routine, as it will
1145: automatically be called within certain preconditioners.
1147: .seealso: [](ch_ksp), `PC`, `PCModifySubMatricesFn`, `PCSetModifySubMatrices()`
1148: @*/
1149: PetscErrorCode PCModifySubMatrices(PC pc, PetscInt nsub, const IS row[], const IS col[], Mat submat[], PetscCtx ctx)
1150: {
1151: PetscFunctionBegin;
1153: if (!pc->modifysubmatrices) PetscFunctionReturn(PETSC_SUCCESS);
1154: PetscCall(PetscLogEventBegin(PC_ModifySubMatrices, pc, 0, 0, 0));
1155: PetscCall((*pc->modifysubmatrices)(pc, nsub, row, col, submat, ctx));
1156: PetscCall(PetscLogEventEnd(PC_ModifySubMatrices, pc, 0, 0, 0));
1157: PetscFunctionReturn(PETSC_SUCCESS);
1158: }
1160: /*@
1161: PCSetOperators - Sets the matrix associated with the linear system and
1162: a (possibly) different one from which the preconditioner will be constructed.
1164: Logically Collective
1166: Input Parameters:
1167: + pc - the `PC` preconditioner context
1168: . Amat - the matrix that defines the linear system
1169: - Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
1171: Level: advanced
1173: Notes:
1174: Using this routine directly is rarely needed, the preferred, and equivalent, usage is `KSPSetOperators()`.
1176: Passing a `NULL` for `Amat` or `Pmat` removes the matrix that is currently used.
1178: If you wish to replace either `Amat` or `Pmat` but leave the other one untouched then
1179: first call `KSPGetOperators()` to get the one you wish to keep, call `PetscObjectReference()`
1180: on it and then pass it back in in your call to `KSPSetOperators()`.
1182: More Notes about Repeated Solution of Linear Systems:
1183: PETSc does NOT reset the matrix entries of either `Amat` or `Pmat`
1184: to zero after a linear solve; the user is completely responsible for
1185: matrix assembly. See the routine `MatZeroEntries()` if desiring to
1186: zero all elements of a matrix.
1188: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`
1189: @*/
1190: PetscErrorCode PCSetOperators(PC pc, Mat Amat, Mat Pmat)
1191: {
1192: PetscInt m1, n1, m2, n2;
1194: PetscFunctionBegin;
1198: if (Amat) PetscCheckSameComm(pc, 1, Amat, 2);
1199: if (Pmat) PetscCheckSameComm(pc, 1, Pmat, 3);
1200: if (pc->setupcalled && pc->mat && pc->pmat && Amat && Pmat) {
1201: PetscCall(MatGetLocalSize(Amat, &m1, &n1));
1202: PetscCall(MatGetLocalSize(pc->mat, &m2, &n2));
1203: 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);
1204: PetscCall(MatGetLocalSize(Pmat, &m1, &n1));
1205: PetscCall(MatGetLocalSize(pc->pmat, &m2, &n2));
1206: 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);
1207: }
1209: if (Pmat != pc->pmat) {
1210: /* changing the operator that defines the preconditioner thus reneed to clear current states so new preconditioner is built */
1211: PetscCall(MatStateInvalidate(pc->matstate));
1212: }
1214: /* reference first in case the matrices are the same */
1215: PetscCall(PetscObjectReference((PetscObject)Amat));
1216: PetscCall(MatDestroy(&pc->mat));
1217: PetscCall(PetscObjectReference((PetscObject)Pmat));
1218: PetscCall(MatDestroy(&pc->pmat));
1219: pc->mat = Amat;
1220: pc->pmat = Pmat;
1221: PetscFunctionReturn(PETSC_SUCCESS);
1222: }
1224: /*@
1225: PCSetReusePreconditioner - reuse the current preconditioner even if the operator in the preconditioner `PC` has changed.
1227: Logically Collective
1229: Input Parameters:
1230: + pc - the `PC` preconditioner context
1231: - flag - `PETSC_TRUE` do not compute a new preconditioner, `PETSC_FALSE` do compute a new preconditioner
1233: Level: intermediate
1235: Note:
1236: Normally if a matrix inside a `PC` changes the `PC` automatically updates itself using information from the changed matrix. This option
1237: prevents this.
1239: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`, `PCGetReusePreconditioner()`, `KSPSetReusePreconditioner()`
1240: @*/
1241: PetscErrorCode PCSetReusePreconditioner(PC pc, PetscBool flag)
1242: {
1243: PetscFunctionBegin;
1246: pc->reusepreconditioner = flag;
1247: PetscTryMethod(pc, "PCSetReusePreconditioner_C", (PC, PetscBool), (pc, flag));
1248: PetscFunctionReturn(PETSC_SUCCESS);
1249: }
1251: /*@
1252: PCGetReusePreconditioner - Determines if the `PC` reuses the current preconditioner even if the operator in the preconditioner has changed.
1254: Not Collective
1256: Input Parameter:
1257: . pc - the `PC` preconditioner context
1259: Output Parameter:
1260: . flag - `PETSC_TRUE` do not compute a new preconditioner, `PETSC_FALSE` do compute a new preconditioner
1262: Level: intermediate
1264: .seealso: [](ch_ksp), `PC`, `PCGetOperators()`, `MatZeroEntries()`, `PCSetReusePreconditioner()`
1265: @*/
1266: PetscErrorCode PCGetReusePreconditioner(PC pc, PetscBool *flag)
1267: {
1268: PetscFunctionBegin;
1270: PetscAssertPointer(flag, 2);
1271: *flag = pc->reusepreconditioner;
1272: PetscFunctionReturn(PETSC_SUCCESS);
1273: }
1275: /*@
1276: PCGetOperators - Gets the matrix associated with the linear system and
1277: possibly a different one which is used to construct the preconditioner.
1279: Not Collective, though parallel `Mat`s are returned if `pc` is parallel
1281: Input Parameter:
1282: . pc - the `PC` preconditioner context
1284: Output Parameters:
1285: + Amat - the matrix defining the linear system
1286: - Pmat - the matrix from which the preconditioner is constructed, usually the same as Amat.
1288: Level: intermediate
1290: Note:
1291: Does not increase the reference count of the matrices, so you should not destroy them
1293: Alternative usage: If the operators have NOT been set with `KSPSetOperators()`/`PCSetOperators()` then the operators
1294: are created in `PC` and returned to the user. In this case, if both operators
1295: mat and pmat are requested, two DIFFERENT operators will be returned. If
1296: only one is requested both operators in the PC will be the same (i.e. as
1297: if one had called `KSPSetOperators()`/`PCSetOperators()` with the same argument for both Mats).
1298: The user must set the sizes of the returned matrices and their type etc just
1299: as if the user created them with `MatCreate()`. For example,
1301: .vb
1302: KSP/PCGetOperators(ksp/pc,&Amat,NULL); is equivalent to
1303: set size, type, etc of Amat
1305: MatCreate(comm,&mat);
1306: KSP/PCSetOperators(ksp/pc,Amat,Amat);
1307: PetscObjectDereference((PetscObject)mat);
1308: set size, type, etc of Amat
1309: .ve
1311: and
1313: .vb
1314: KSP/PCGetOperators(ksp/pc,&Amat,&Pmat); is equivalent to
1315: set size, type, etc of Amat and Pmat
1317: MatCreate(comm,&Amat);
1318: MatCreate(comm,&Pmat);
1319: KSP/PCSetOperators(ksp/pc,Amat,Pmat);
1320: PetscObjectDereference((PetscObject)Amat);
1321: PetscObjectDereference((PetscObject)Pmat);
1322: set size, type, etc of Amat and Pmat
1323: .ve
1325: The rationale for this support is so that when creating a `TS`, `SNES`, or `KSP` the hierarchy
1326: of underlying objects (i.e. `SNES`, `KSP`, `PC`, `Mat`) and their lifespans can be completely
1327: managed by the top most level object (i.e. the `TS`, `SNES`, or `KSP`). Another way to look
1328: at this is when you create a `SNES` you do not NEED to create a `KSP` and attach it to
1329: the `SNES` object (the `SNES` object manages it for you). Similarly when you create a KSP
1330: you do not need to attach a `PC` to it (the `KSP` object manages the `PC` object for you).
1331: Thus, why should YOU have to create the `Mat` and attach it to the `SNES`/`KSP`/`PC`, when
1332: it can be created for you?
1334: .seealso: [](ch_ksp), `PC`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetOperators()`, `PCGetOperatorsSet()`
1335: @*/
1336: PetscErrorCode PCGetOperators(PC pc, Mat *Amat, Mat *Pmat)
1337: {
1338: PetscFunctionBegin;
1340: if (Amat) {
1341: if (!pc->mat) {
1342: if (pc->pmat && !Pmat) { /* Pmat has been set, but user did not request it, so use for Amat */
1343: pc->mat = pc->pmat;
1344: PetscCall(PetscObjectReference((PetscObject)pc->mat));
1345: } else { /* both Amat and Pmat are empty */
1346: PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), &pc->mat));
1347: if (!Pmat) { /* user did NOT request Pmat, so make same as Amat */
1348: pc->pmat = pc->mat;
1349: PetscCall(PetscObjectReference((PetscObject)pc->pmat));
1350: }
1351: }
1352: }
1353: *Amat = pc->mat;
1354: }
1355: if (Pmat) {
1356: if (!pc->pmat) {
1357: if (pc->mat && !Amat) { /* Amat has been set but was not requested, so use for pmat */
1358: pc->pmat = pc->mat;
1359: PetscCall(PetscObjectReference((PetscObject)pc->pmat));
1360: } else {
1361: PetscCall(MatCreate(PetscObjectComm((PetscObject)pc), &pc->pmat));
1362: if (!Amat) { /* user did NOT request Amat, so make same as Pmat */
1363: pc->mat = pc->pmat;
1364: PetscCall(PetscObjectReference((PetscObject)pc->mat));
1365: }
1366: }
1367: }
1368: *Pmat = pc->pmat;
1369: }
1370: PetscFunctionReturn(PETSC_SUCCESS);
1371: }
1373: /*@
1374: PCGetOperatorsSet - Determines if the matrix associated with the linear system and
1375: possibly a different one associated with the preconditioner have been set in the `PC`.
1377: Not Collective, though the results on all processes should be the same
1379: Input Parameter:
1380: . pc - the `PC` preconditioner context
1382: Output Parameters:
1383: + mat - the matrix associated with the linear system was set
1384: - pmat - matrix associated with the preconditioner was set, usually the same
1386: Level: intermediate
1388: .seealso: [](ch_ksp), `PC`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetOperators()`, `PCGetOperators()`
1389: @*/
1390: PetscErrorCode PCGetOperatorsSet(PC pc, PetscBool *mat, PetscBool *pmat)
1391: {
1392: PetscFunctionBegin;
1394: if (mat) *mat = pc->mat ? PETSC_TRUE : PETSC_FALSE;
1395: if (pmat) *pmat = pc->pmat ? PETSC_TRUE : PETSC_FALSE;
1396: PetscFunctionReturn(PETSC_SUCCESS);
1397: }
1399: /*@
1400: PCFactorGetMatrix - Gets the factored matrix from the
1401: preconditioner context. This routine is valid only for the `PCLU`,
1402: `PCILU`, `PCCHOLESKY`, and `PCICC` methods.
1404: Not Collective though `mat` is parallel if `pc` is parallel
1406: Input Parameter:
1407: . pc - the `PC` preconditioner context
1409: Output Parameters:
1410: . mat - the factored matrix
1412: Level: advanced
1414: Note:
1415: Does not increase the reference count for `mat` so DO NOT destroy it
1417: .seealso: [](ch_ksp), `PC`, `PCLU`, `PCILU`, `PCCHOLESKY`, `PCICC`
1418: @*/
1419: PetscErrorCode PCFactorGetMatrix(PC pc, Mat *mat)
1420: {
1421: PetscFunctionBegin;
1423: PetscAssertPointer(mat, 2);
1424: PetscCall(PCFactorSetUpMatSolverType(pc));
1425: PetscUseTypeMethod(pc, getfactoredmatrix, mat);
1426: PetscFunctionReturn(PETSC_SUCCESS);
1427: }
1429: /*@
1430: PCSetOptionsPrefix - Sets the prefix used for searching for all
1431: `PC` options in the database.
1433: Logically Collective
1435: Input Parameters:
1436: + pc - the `PC` preconditioner context
1437: - prefix - the prefix string to prepend to all `PC` option requests
1439: Level: advanced
1441: Note:
1442: A hyphen (-) must NOT be given at the beginning of the prefix name.
1443: The first character of all runtime options is AUTOMATICALLY the
1444: hyphen.
1446: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCAppendOptionsPrefix()`, `PCGetOptionsPrefix()`
1447: @*/
1448: PetscErrorCode PCSetOptionsPrefix(PC pc, const char prefix[])
1449: {
1450: PetscFunctionBegin;
1452: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)pc, prefix));
1453: PetscFunctionReturn(PETSC_SUCCESS);
1454: }
1456: /*@
1457: PCAppendOptionsPrefix - Appends to the prefix used for searching for all
1458: `PC` options in the database.
1460: Logically Collective
1462: Input Parameters:
1463: + pc - the `PC` preconditioner context
1464: - prefix - the prefix string to prepend to all `PC` option requests
1466: Level: advanced
1468: Note:
1469: A hyphen (-) must NOT be given at the beginning of the prefix name.
1470: The first character of all runtime options is AUTOMATICALLY the
1471: hyphen.
1473: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCSetOptionsPrefix()`, `PCGetOptionsPrefix()`
1474: @*/
1475: PetscErrorCode PCAppendOptionsPrefix(PC pc, const char prefix[])
1476: {
1477: PetscFunctionBegin;
1479: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)pc, prefix));
1480: PetscFunctionReturn(PETSC_SUCCESS);
1481: }
1483: /*@
1484: PCGetOptionsPrefix - Gets the prefix used for searching for all
1485: `PC` options in the database.
1487: Not Collective
1489: Input Parameter:
1490: . pc - the `PC` preconditioner context
1492: Output Parameter:
1493: . prefix - pointer to the prefix string used, is returned
1495: Level: advanced
1497: .seealso: [](ch_ksp), `PC`, `PCSetFromOptions()`, `PCSetOptionsPrefix()`, `PCAppendOptionsPrefix()`
1498: @*/
1499: PetscErrorCode PCGetOptionsPrefix(PC pc, const char *prefix[])
1500: {
1501: PetscFunctionBegin;
1503: PetscAssertPointer(prefix, 2);
1504: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)pc, prefix));
1505: PetscFunctionReturn(PETSC_SUCCESS);
1506: }
1508: /*
1509: Indicates the right-hand side will be changed by KSPSolve(), this occurs for a few
1510: preconditioners including BDDC and Eisentat that transform the equations before applying
1511: the Krylov methods
1512: */
1513: PETSC_INTERN PetscErrorCode PCPreSolveChangeRHS(PC pc, PetscBool *change)
1514: {
1515: PetscFunctionBegin;
1517: PetscAssertPointer(change, 2);
1518: *change = PETSC_FALSE;
1519: PetscTryMethod(pc, "PCPreSolveChangeRHS_C", (PC, PetscBool *), (pc, change));
1520: PetscFunctionReturn(PETSC_SUCCESS);
1521: }
1523: /*@
1524: PCPreSolve - Optional pre-solve phase, intended for any preconditioner-specific actions that must be performed before
1525: the iterative solve itself. Used in conjunction with `PCPostSolve()`
1527: Collective
1529: Input Parameters:
1530: + pc - the `PC` preconditioner context
1531: - ksp - the Krylov subspace context
1533: Level: developer
1535: Notes:
1536: `KSPSolve()` calls this directly, so is rarely called by the user.
1538: Certain preconditioners, such as the `PCType` of `PCEISENSTAT`, change the formulation of the linear system to be solved iteratively.
1539: This function performs that transformation. `PCPostSolve()` then transforms the system back to its original form after the solve.
1540: `PCPostSolve()` also transforms the resulting solution of the transformed system to the solution of the original problem.
1542: `KSPSetPostSolve()` provides an alternative way to provide such transformations.
1544: .seealso: [](ch_ksp), `PC`, `PCPostSolve()`, `KSP`, `PCSetPostSetUp()`, `KSPSetPreSolve()`, `KSPSetPostSolve()`
1545: @*/
1546: PetscErrorCode PCPreSolve(PC pc, KSP ksp)
1547: {
1548: Vec x, rhs;
1550: PetscFunctionBegin;
1553: pc->presolvedone++;
1554: PetscCheck(pc->presolvedone <= 2, PetscObjectComm((PetscObject)pc), PETSC_ERR_SUP, "Cannot embed PCPreSolve() more than twice");
1555: PetscCall(KSPGetSolution(ksp, &x));
1556: PetscCall(KSPGetRhs(ksp, &rhs));
1557: PetscTryTypeMethod(pc, presolve, ksp, rhs, x);
1558: PetscFunctionReturn(PETSC_SUCCESS);
1559: }
1561: /*@
1562: PCSetPostSetUp - Sets function called at the end of `PCSetUp()` to adjust the computed preconditioner
1564: Logically Collective
1566: Input Parameters:
1567: + pc - the preconditioner object
1568: - postsetup - the function to call after `PCSetUp()`
1570: Calling sequence of `postsetup`:
1571: . pc - the `PC` context
1573: Level: developer
1575: .seealso: [](ch_ksp), `PC`, `PCSetUp()`
1576: @*/
1577: PetscErrorCode PCSetPostSetUp(PC pc, PetscErrorCode (*postsetup)(PC pc))
1578: {
1579: PetscFunctionBegin;
1581: pc->postsetup = postsetup;
1582: PetscFunctionReturn(PETSC_SUCCESS);
1583: }
1585: /*@
1586: PCPostSolve - Optional post-solve phase, intended for any
1587: preconditioner-specific actions that must be performed after
1588: the iterative solve itself.
1590: Collective
1592: Input Parameters:
1593: + pc - the `PC` preconditioner context
1594: - ksp - the `KSP` Krylov subspace context
1596: Example Usage:
1597: .vb
1598: PCPreSolve(pc,ksp);
1599: KSPSolve(ksp,b,x);
1600: PCPostSolve(pc,ksp);
1601: .ve
1603: Level: developer
1605: Note:
1606: `KSPSolve()` calls this routine directly, so it is rarely called by the user.
1608: .seealso: [](ch_ksp), `PC`, `KSPSetPostSolve()`, `KSPSetPreSolve()`, `PCPreSolve()`, `KSPSolve()`
1609: @*/
1610: PetscErrorCode PCPostSolve(PC pc, KSP ksp)
1611: {
1612: Vec x, rhs;
1614: PetscFunctionBegin;
1617: pc->presolvedone--;
1618: PetscCall(KSPGetSolution(ksp, &x));
1619: PetscCall(KSPGetRhs(ksp, &rhs));
1620: PetscTryTypeMethod(pc, postsolve, ksp, rhs, x);
1621: PetscFunctionReturn(PETSC_SUCCESS);
1622: }
1624: /*@
1625: PCLoad - Loads a `PC` that has been stored in binary with `PCView()`.
1627: Collective
1629: Input Parameters:
1630: + newdm - the newly loaded `PC`, this needs to have been created with `PCCreate()` or
1631: some related function before a call to `PCLoad()`.
1632: - viewer - binary file viewer `PETSCVIEWERBINARY`, obtained from `PetscViewerBinaryOpen()`
1634: Level: intermediate
1636: Note:
1637: The type is determined by the data in the file, any `PCType` set into the `PC` before this call is ignored.
1639: .seealso: [](ch_ksp), `PC`, `PetscViewerBinaryOpen()`, `PCView()`, `MatLoad()`, `VecLoad()`, `PETSCVIEWERBINARY`
1640: @*/
1641: PetscErrorCode PCLoad(PC newdm, PetscViewer viewer)
1642: {
1643: PetscBool isbinary;
1644: PetscInt classid;
1645: char type[256];
1647: PetscFunctionBegin;
1650: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1651: PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1653: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
1654: PetscCheck(classid == PC_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not PC next in file");
1655: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
1656: PetscCall(PCSetType(newdm, type));
1657: PetscTryTypeMethod(newdm, load, viewer);
1658: PetscFunctionReturn(PETSC_SUCCESS);
1659: }
1661: #include <petscdraw.h>
1662: #if PetscDefined(HAVE_SAWS)
1663: #include <petscviewersaws.h>
1664: #endif
1666: /*@
1667: PCViewFromOptions - View (print or provide information about) the `PC`, based on options in the options database
1669: Collective
1671: Input Parameters:
1672: + A - the `PC` context
1673: . obj - optional object that provides the options prefix, pass `NULL` to use the options prefix of `A`
1674: - name - command line option name
1676: Options Database Key:
1677: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
1679: Level: developer
1681: Note:
1682: 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,
1683: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
1685: .seealso: [](ch_ksp), `PC`, `PCView()`, `PetscObjectViewFromOptions()`, `PCCreate()`, `PetscOptionsCreateViewer()`
1686: @*/
1687: PetscErrorCode PCViewFromOptions(PC A, PetscObject obj, const char name[])
1688: {
1689: PetscFunctionBegin;
1691: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
1692: PetscFunctionReturn(PETSC_SUCCESS);
1693: }
1695: /*@
1696: PCView - Prints information about the `PC`
1698: Collective
1700: Input Parameters:
1701: + pc - the `PC` preconditioner context
1702: - viewer - optional `PetscViewer` visualization context
1704: Level: intermediate
1706: Notes:
1707: The available visualization contexts include
1708: + `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1709: - `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1710: output where only the first processor opens
1711: the file. All other processors send their
1712: data to the first processor to print.
1714: The user can open an alternative visualization contexts with
1715: `PetscViewerASCIIOpen()` (output to a specified file).
1717: .seealso: [](ch_ksp), `PC`, `PetscViewer`, `PetscViewerType`, `KSPView()`, `PetscViewerASCIIOpen()`
1718: @*/
1719: PetscErrorCode PCView(PC pc, PetscViewer viewer)
1720: {
1721: PCType cstr;
1722: PetscViewerFormat format;
1723: PetscBool isascii, isstring, isbinary, isdraw, pop = PETSC_FALSE;
1724: #if PetscDefined(HAVE_SAWS)
1725: PetscBool issaws;
1726: #endif
1728: PetscFunctionBegin;
1730: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)pc), &viewer));
1732: PetscCheckSameComm(pc, 1, viewer, 2);
1734: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
1735: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
1736: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
1737: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1738: #if PetscDefined(HAVE_SAWS)
1739: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1740: #endif
1742: if (isascii) {
1743: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)pc, viewer));
1744: if (!pc->setupcalled) PetscCall(PetscViewerASCIIPrintf(viewer, " PC has not been set up so information may be incomplete\n"));
1745: PetscCall(PetscViewerASCIIPushTab(viewer));
1746: PetscTryTypeMethod(pc, view, viewer);
1747: PetscCall(PetscViewerASCIIPopTab(viewer));
1748: if (pc->mat) {
1749: PetscCall(PetscViewerGetFormat(viewer, &format));
1750: if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) {
1751: PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
1752: pop = PETSC_TRUE;
1753: }
1754: if (pc->pmat == pc->mat) {
1755: PetscCall(PetscViewerASCIIPrintf(viewer, " linear system matrix, which is also used to construct the preconditioner:\n"));
1756: PetscCall(PetscViewerASCIIPushTab(viewer));
1757: PetscCall(MatView(pc->mat, viewer));
1758: PetscCall(PetscViewerASCIIPopTab(viewer));
1759: } else {
1760: if (pc->pmat) {
1761: PetscCall(PetscViewerASCIIPrintf(viewer, " linear system matrix, followed by the matrix used to construct the preconditioner:\n"));
1762: } else {
1763: PetscCall(PetscViewerASCIIPrintf(viewer, " linear system matrix:\n"));
1764: }
1765: PetscCall(PetscViewerASCIIPushTab(viewer));
1766: PetscCall(MatView(pc->mat, viewer));
1767: if (pc->pmat) PetscCall(MatView(pc->pmat, viewer));
1768: PetscCall(PetscViewerASCIIPopTab(viewer));
1769: }
1770: if (pop) PetscCall(PetscViewerPopFormat(viewer));
1771: }
1772: } else if (isstring) {
1773: PetscCall(PCGetType(pc, &cstr));
1774: PetscCall(PetscViewerStringSPrintf(viewer, " PCType: %-7.7s", cstr));
1775: PetscTryTypeMethod(pc, view, viewer);
1776: if (pc->mat) PetscCall(MatView(pc->mat, viewer));
1777: if (pc->pmat && pc->pmat != pc->mat) PetscCall(MatView(pc->pmat, viewer));
1778: } else if (isbinary) {
1779: PetscInt classid = PC_FILE_CLASSID;
1780: MPI_Comm comm;
1781: PetscMPIInt rank;
1782: char type[256];
1784: PetscCall(PetscObjectGetComm((PetscObject)pc, &comm));
1785: PetscCallMPI(MPI_Comm_rank(comm, &rank));
1786: if (rank == 0) {
1787: PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
1788: PetscCall(PetscStrncpy(type, ((PetscObject)pc)->type_name, 256));
1789: PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
1790: }
1791: PetscTryTypeMethod(pc, view, viewer);
1792: } else if (isdraw) {
1793: PetscDraw draw;
1794: char str[25];
1795: PetscReal x, y, bottom, h;
1796: PetscInt n;
1798: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
1799: PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1800: if (pc->mat) {
1801: PetscCall(MatGetSize(pc->mat, &n, NULL));
1802: PetscCall(PetscSNPrintf(str, 25, "PC: %s (%" PetscInt_FMT ")", ((PetscObject)pc)->type_name, n));
1803: } else {
1804: PetscCall(PetscSNPrintf(str, 25, "PC: %s", ((PetscObject)pc)->type_name));
1805: }
1806: PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_RED, PETSC_DRAW_BLACK, str, NULL, &h));
1807: bottom = y - h;
1808: PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1809: PetscTryTypeMethod(pc, view, viewer);
1810: PetscCall(PetscDrawPopCurrentPoint(draw));
1811: #if PetscDefined(HAVE_SAWS)
1812: } else if (issaws) {
1813: PetscMPIInt rank;
1815: PetscCall(PetscObjectName((PetscObject)pc));
1816: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1817: if (!((PetscObject)pc)->amsmem && rank == 0) PetscCall(PetscObjectViewSAWs((PetscObject)pc, viewer));
1818: if (pc->mat) PetscCall(MatView(pc->mat, viewer));
1819: if (pc->pmat && pc->pmat != pc->mat) PetscCall(MatView(pc->pmat, viewer));
1820: #endif
1821: }
1822: PetscFunctionReturn(PETSC_SUCCESS);
1823: }
1825: /*@
1826: PCRegister - Adds a method (`PCType`) to the PETSc preconditioner package.
1828: Not collective. No Fortran Support
1830: Input Parameters:
1831: + sname - name of a new user-defined solver
1832: - function - routine to create the method context which will be stored in a `PC` when `PCSetType()` is called
1834: Example Usage:
1835: .vb
1836: PCRegister("my_solver", MySolverCreate);
1837: .ve
1839: Then, your solver can be chosen with the procedural interface via
1840: .vb
1841: PCSetType(pc, "my_solver")
1842: .ve
1843: or at runtime via the option
1844: .vb
1845: -pc_type my_solver
1846: .ve
1848: Level: advanced
1850: Note:
1851: A simpler alternative to using `PCRegister()` for an application specific preconditioner is to use a `PC` of `PCType` `PCSHELL` and
1852: provide your customizations with `PCShellSetContext()` and `PCShellSetApply()`
1854: `PCRegister()` may be called multiple times to add several user-defined preconditioners.
1856: .seealso: [](ch_ksp), `PC`, `PCType`, `PCRegisterAll()`, `PCSetType()`, `PCShellSetContext()`, `PCShellSetApply()`, `PCSHELL`
1857: @*/
1858: PetscErrorCode PCRegister(const char sname[], PetscErrorCode (*function)(PC))
1859: {
1860: PetscFunctionBegin;
1861: PetscCall(PCInitializePackage());
1862: PetscCall(PetscFunctionListAdd(&PCList, sname, function));
1863: PetscFunctionReturn(PETSC_SUCCESS);
1864: }
1866: static PetscErrorCode MatMult_PC(Mat A, Vec X, Vec Y)
1867: {
1868: PC pc;
1870: PetscFunctionBegin;
1871: PetscCall(MatShellGetContext(A, &pc));
1872: PetscCall(PCApply(pc, X, Y));
1873: PetscFunctionReturn(PETSC_SUCCESS);
1874: }
1876: /*@
1877: PCComputeOperator - Computes the explicit preconditioned operator as a matrix `Mat`.
1879: Collective
1881: Input Parameters:
1882: + pc - the `PC` preconditioner object
1883: - mattype - the `MatType` to be used for the operator
1885: Output Parameter:
1886: . mat - the explicit preconditioned operator
1888: Level: advanced
1890: Note:
1891: This computation is done by applying the operators to columns of the identity matrix.
1892: This routine is costly in general, and is recommended for use only with relatively small systems.
1893: Currently, this routine uses a dense matrix format when `mattype` == `NULL`
1895: Developer Note:
1896: This should be called `PCCreateExplicitOperator()`
1898: .seealso: [](ch_ksp), `PC`, `KSPComputeOperator()`, `MatType`
1899: @*/
1900: PetscErrorCode PCComputeOperator(PC pc, MatType mattype, Mat *mat)
1901: {
1902: PetscInt N, M, m, n;
1903: Mat A, Apc;
1905: PetscFunctionBegin;
1907: PetscAssertPointer(mat, 3);
1908: PetscCall(PCGetOperators(pc, &A, NULL));
1909: PetscCall(MatGetLocalSize(A, &m, &n));
1910: PetscCall(MatGetSize(A, &M, &N));
1911: PetscCall(MatCreateShell(PetscObjectComm((PetscObject)pc), m, n, M, N, pc, &Apc));
1912: PetscCall(MatShellSetOperation(Apc, MATOP_MULT, (PetscErrorCodeFn *)MatMult_PC));
1913: PetscCall(MatComputeOperator(Apc, mattype, mat));
1914: PetscCall(MatDestroy(&Apc));
1915: PetscFunctionReturn(PETSC_SUCCESS);
1916: }
1918: /*@
1919: PCSetCoordinates - sets the coordinates of all the nodes (degrees of freedom in the vector) on the local process
1921: Collective
1923: Input Parameters:
1924: + pc - the `PC` preconditioner context
1925: . dim - the dimension of the coordinates 1, 2, or 3
1926: . nloc - the blocked size of the coordinates array
1927: - coords - the coordinates array
1929: Level: intermediate
1931: Notes:
1932: `coords` is an array of the dim coordinates for the nodes on
1933: the local processor, of size `dim`*`nloc`.
1934: If there are 108 equations (dofs) on a processor
1935: for a 3d displacement finite element discretization of elasticity (so
1936: that there are nloc = 36 = 108/3 nodes) then the array must have 108
1937: double precision values (ie, 3 * 36). These x y z coordinates
1938: should be ordered for nodes 0 to N-1 like so: [ 0.x, 0.y, 0.z, 1.x,
1939: ... , N-1.z ].
1941: The information provided here can be used by some preconditioners, such as `PCGAMG`, to produce a better preconditioner.
1942: See also `MatSetNearNullSpace()`.
1944: .seealso: [](ch_ksp), `PC`, `MatSetNearNullSpace()`
1945: @*/
1946: PetscErrorCode PCSetCoordinates(PC pc, PetscInt dim, PetscInt nloc, PetscReal coords[])
1947: {
1948: PetscFunctionBegin;
1951: PetscTryMethod(pc, "PCSetCoordinates_C", (PC, PetscInt, PetscInt, PetscReal[]), (pc, dim, nloc, coords));
1952: PetscFunctionReturn(PETSC_SUCCESS);
1953: }
1955: /*@
1956: PCGetInterpolations - Gets interpolation matrices for all levels (except level 0)
1958: Logically Collective
1960: Input Parameter:
1961: . pc - the precondition context
1963: Output Parameters:
1964: + num_levels - the number of levels
1965: - interpolations - the interpolation matrices (size of `num_levels`-1)
1967: Level: advanced
1969: Developer Note:
1970: Why is this here instead of in `PCMG` etc?
1972: .seealso: [](ch_ksp), `PC`, `PCMG`, `PCMGGetRestriction()`, `PCMGSetInterpolation()`, `PCMGGetInterpolation()`, `PCGetCoarseOperators()`
1973: @*/
1974: PetscErrorCode PCGetInterpolations(PC pc, PetscInt *num_levels, Mat *interpolations[])
1975: {
1976: PetscFunctionBegin;
1978: PetscAssertPointer(num_levels, 2);
1979: PetscAssertPointer(interpolations, 3);
1980: PetscUseMethod(pc, "PCGetInterpolations_C", (PC, PetscInt *, Mat *[]), (pc, num_levels, interpolations));
1981: PetscFunctionReturn(PETSC_SUCCESS);
1982: }
1984: /*@
1985: PCGetCoarseOperators - Gets coarse operator matrices for all levels (except the finest level)
1987: Logically Collective
1989: Input Parameter:
1990: . pc - the precondition context
1992: Output Parameters:
1993: + num_levels - the number of levels
1994: - coarseOperators - the coarse operator matrices (size of `num_levels`-1)
1996: Level: advanced
1998: Developer Note:
1999: Why is this here instead of in `PCMG` etc?
2001: .seealso: [](ch_ksp), `PC`, `PCMG`, `PCMGGetRestriction()`, `PCMGSetInterpolation()`, `PCMGGetRScale()`, `PCMGGetInterpolation()`, `PCGetInterpolations()`
2002: @*/
2003: PetscErrorCode PCGetCoarseOperators(PC pc, PetscInt *num_levels, Mat *coarseOperators[])
2004: {
2005: PetscFunctionBegin;
2007: PetscAssertPointer(num_levels, 2);
2008: PetscAssertPointer(coarseOperators, 3);
2009: PetscUseMethod(pc, "PCGetCoarseOperators_C", (PC, PetscInt *, Mat *[]), (pc, num_levels, coarseOperators));
2010: PetscFunctionReturn(PETSC_SUCCESS);
2011: }