Actual source code: itfunc.c
1: /*
2: Interface KSP routines that the user calls.
3: */
5: #include <petsc/private/kspimpl.h>
6: #include <petsc/private/matimpl.h>
7: #include <petscdm.h>
9: /* number of nested levels of KSPSetUp/Solve(). This is used to determine if KSP_DIVERGED_ITS should be fatal. */
10: static PetscInt level = 0;
12: static inline PetscErrorCode ObjectView(PetscObject obj, PetscViewer viewer, PetscViewerFormat format)
13: {
14: PetscCall(PetscViewerPushFormat(viewer, format));
15: PetscCall(PetscObjectView(obj, viewer));
16: PetscCall(PetscViewerPopFormat(viewer));
17: return PETSC_SUCCESS;
18: }
20: static PetscErrorCode KSPRestoreExplicitTranspose_Private(KSP);
22: /*@
23: KSPComputeExtremeSingularValues - Computes the extreme singular values
24: for the preconditioned operator. Called after or during `KSPSolve()`.
26: Not Collective
28: Input Parameter:
29: . ksp - iterative solver obtained from `KSPCreate()`
31: Output Parameters:
32: + emax - maximum estimated singular value
33: - emin - minimum estimated singular value
35: Options Database Key:
36: . -ksp_view_singularvalues - compute extreme singular values and print when `KSPSolve()` completes.
38: Level: advanced
40: Notes:
41: One must call `KSPSetComputeSingularValues()` before calling `KSPSetUp()`
42: (or use the option `-ksp_view_singularvalues`) in order for this routine to work correctly.
44: Many users may just want to use the monitoring routine
45: `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
46: to print the extreme singular values at each iteration of the linear solve.
48: Estimates of the smallest singular value may be very inaccurate, especially if the Krylov method has not converged.
49: The largest singular value is usually accurate to within a few percent if the method has converged, but is still not
50: intended for eigenanalysis. Consider the excellent package SLEPc if accurate values are required.
52: Disable restarts if using `KSPGMRES`, otherwise this estimate will only be using those iterations after the last
53: restart. See `KSPGMRESSetRestart()` for more details.
55: .seealso: [](ch_ksp), `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`, `KSPComputeEigenvalues()`, `KSP`, `KSPComputeRitz()`
56: @*/
57: PetscErrorCode KSPComputeExtremeSingularValues(KSP ksp, PetscReal *emax, PetscReal *emin)
58: {
59: PetscFunctionBegin;
61: PetscAssertPointer(emax, 2);
62: PetscAssertPointer(emin, 3);
63: PetscCheck(ksp->calc_sings, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Singular values not requested before KSPSetUp()");
65: if (ksp->ops->computeextremesingularvalues) PetscUseTypeMethod(ksp, computeextremesingularvalues, emax, emin);
66: else {
67: *emin = -1.0;
68: *emax = -1.0;
69: }
70: PetscFunctionReturn(PETSC_SUCCESS);
71: }
73: /*@
74: KSPComputeEigenvalues - Computes the extreme eigenvalues for the
75: preconditioned operator. Called after or during `KSPSolve()`.
77: Not Collective
79: Input Parameters:
80: + ksp - iterative solver obtained from `KSPCreate()`
81: - n - size of arrays `r` and `c`. The number of eigenvalues computed `neig` will, in general, be less than this.
83: Output Parameters:
84: + r - real part of computed eigenvalues, provided by user with a dimension of at least `n`
85: . c - complex part of computed eigenvalues, provided by user with a dimension of at least `n`
86: - neig - actual number of eigenvalues computed (will be less than or equal to `n`)
88: Options Database Key:
89: . -ksp_view_eigenvalues - Prints eigenvalues to stdout
91: Level: advanced
93: Notes:
94: The number of eigenvalues estimated depends on the size of the Krylov space
95: generated during the `KSPSolve()` ; for example, with
96: `KSPCG` it corresponds to the number of CG iterations, for `KSPGMRES` it is the number
97: of GMRES iterations SINCE the last restart. Any extra space in `r` and `c`
98: will be ignored.
100: `KSPComputeEigenvalues()` does not usually provide accurate estimates; it is
101: intended only for assistance in understanding the convergence of iterative
102: methods, not for eigenanalysis. For accurate computation of eigenvalues we recommend using
103: the excellent package SLEPc.
105: One must call `KSPSetComputeEigenvalues()` before calling `KSPSetUp()`
106: in order for this routine to work correctly.
108: Many users may just want to use the monitoring routine
109: `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
110: to print the singular values at each iteration of the linear solve.
112: `KSPComputeRitz()` provides estimates for both the eigenvalues and their corresponding eigenvectors.
114: .seealso: [](ch_ksp), `KSPSetComputeEigenvalues()`, `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`, `KSPComputeExtremeSingularValues()`, `KSP`, `KSPComputeRitz()`
115: @*/
116: PetscErrorCode KSPComputeEigenvalues(KSP ksp, PetscInt n, PetscReal r[], PetscReal c[], PetscInt *neig)
117: {
118: PetscFunctionBegin;
120: if (n) PetscAssertPointer(r, 3);
121: if (n) PetscAssertPointer(c, 4);
122: PetscCheck(n >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Requested < 0 Eigenvalues");
123: PetscAssertPointer(neig, 5);
124: PetscCheck(ksp->calc_sings, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Eigenvalues not requested before KSPSetUp()");
126: if (n && ksp->ops->computeeigenvalues) PetscUseTypeMethod(ksp, computeeigenvalues, n, r, c, neig);
127: else *neig = 0;
128: PetscFunctionReturn(PETSC_SUCCESS);
129: }
131: /*@
132: KSPComputeRitz - Computes the Ritz or harmonic Ritz pairs associated with the
133: smallest or largest in modulus, for the preconditioned operator.
135: Not Collective
137: Input Parameters:
138: + ksp - iterative solver obtained from `KSPCreate()`
139: . ritz - `PETSC_TRUE` or `PETSC_FALSE` for Ritz pairs or harmonic Ritz pairs, respectively
140: - small - `PETSC_TRUE` or `PETSC_FALSE` for smallest or largest (harmonic) Ritz values, respectively
142: Output Parameters:
143: + nrit - On input number of (harmonic) Ritz pairs to compute; on output, actual number of computed (harmonic) Ritz pairs
144: . S - an array of the Ritz vectors, pass in an array of vectors of size `nrit`
145: . tetar - real part of the Ritz values, pass in an array of size `nrit`
146: - tetai - imaginary part of the Ritz values, pass in an array of size `nrit`
148: Level: advanced
150: Notes:
151: This only works with a `KSPType` of `KSPGMRES`.
153: One must call `KSPSetComputeRitz()` before calling `KSPSetUp()` in order for this routine to work correctly.
155: This routine must be called after `KSPSolve()`.
157: In `KSPGMRES`, the (harmonic) Ritz pairs are computed from the Hessenberg matrix obtained during
158: the last complete cycle of the GMRES solve, or during the partial cycle if the solve ended before
159: a restart (that is a complete GMRES cycle was never achieved).
161: The number of actual (harmonic) Ritz pairs computed is less than or equal to the restart
162: parameter for GMRES if a complete cycle has been performed or less or equal to the number of GMRES
163: iterations.
165: `KSPComputeEigenvalues()` provides estimates for only the eigenvalues (Ritz values).
167: For real matrices, the (harmonic) Ritz pairs can be complex-valued. In such a case,
168: the routine selects the complex (harmonic) Ritz value and its conjugate, and two successive entries of the
169: vectors `S` are equal to the real and the imaginary parts of the associated vectors.
170: When PETSc has been built with complex scalars, the real and imaginary parts of the Ritz
171: values are still returned in `tetar` and `tetai`, as is done in `KSPComputeEigenvalues()`, but
172: the Ritz vectors S are complex.
174: The (harmonic) Ritz pairs are given in order of increasing (harmonic) Ritz values in modulus.
176: The Ritz pairs do not necessarily accurately reflect the eigenvalues and eigenvectors of the operator, consider the
177: excellent package SLEPc if accurate values are required.
179: .seealso: [](ch_ksp), `KSPSetComputeRitz()`, `KSP`, `KSPGMRES`, `KSPComputeEigenvalues()`, `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`
180: @*/
181: PetscErrorCode KSPComputeRitz(KSP ksp, PetscBool ritz, PetscBool small, PetscInt *nrit, Vec S[], PetscReal tetar[], PetscReal tetai[])
182: {
183: PetscFunctionBegin;
185: PetscCheck(ksp->calc_ritz, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Ritz pairs not requested before KSPSetUp()");
186: PetscTryTypeMethod(ksp, computeritz, ritz, small, nrit, S, tetar, tetai);
187: PetscFunctionReturn(PETSC_SUCCESS);
188: }
190: /*@
191: KSPSetUpOnBlocks - Sets up the preconditioner for each block in
192: the block Jacobi `PCJACOBI`, overlapping Schwarz `PCASM`, and fieldsplit `PCFIELDSPLIT` preconditioners
194: Collective
196: Input Parameter:
197: . ksp - the `KSP` context
199: Level: advanced
201: Notes:
202: `KSPSetUpOnBlocks()` is a routine that the user can optionally call for
203: more precise profiling (via `-log_view`) of the setup phase for these
204: block preconditioners. If the user does not call `KSPSetUpOnBlocks()`,
205: it will automatically be called from within `KSPSolve()`.
207: Calling `KSPSetUpOnBlocks()` is the same as calling `PCSetUpOnBlocks()`
208: on the `PC` context within the `KSP` context.
210: .seealso: [](ch_ksp), `PCSetUpOnBlocks()`, `KSPSetUp()`, `PCSetUp()`, `KSP`
211: @*/
212: PetscErrorCode KSPSetUpOnBlocks(KSP ksp)
213: {
214: PC pc;
215: PCFailedReason pcreason;
217: PetscFunctionBegin;
219: level++;
220: PetscCall(KSPGetPC(ksp, &pc));
221: PetscCall(PCSetUpOnBlocks(pc));
222: PetscCall(PCGetFailedReason(pc, &pcreason));
223: level--;
224: /*
225: This is tricky since only a subset of MPI ranks may set this; each KSPSolve_*() is responsible for checking
226: this flag and initializing an appropriate vector with VecFlag() so that the first norm computation can
227: produce a result at KSPCheckNorm() thus communicating the known problem to all MPI ranks so they may
228: terminate the Krylov solve. For many KSP implementations this is handled within KSPInitialResidual()
229: */
230: if (pcreason) ksp->reason = KSP_DIVERGED_PC_FAILED;
231: PetscFunctionReturn(PETSC_SUCCESS);
232: }
234: /*@
235: KSPSetReusePreconditioner - reuse the current preconditioner for future `KSPSolve()`, do not construct a new preconditioner even if the `Mat` operator
236: in the `KSP` has different values
238: Collective
240: Input Parameters:
241: + ksp - iterative solver obtained from `KSPCreate()`
242: - flag - `PETSC_TRUE` to reuse the current preconditioner, or `PETSC_FALSE` to construct a new preconditioner
244: Options Database Key:
245: . -ksp_reuse_preconditioner (true|false) - reuse the previously computed preconditioner
247: Level: intermediate
249: Notes:
250: When using `SNES` one can use `SNESSetLagPreconditioner()` to determine when preconditioners are reused.
252: Reusing the preconditioner reduces the time needed to form new preconditioners but may (significantly) increase the number
253: of iterations needed for future solves depending on how much the matrix entries have changed.
255: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGetReusePreconditioner()`,
256: `SNESSetLagPreconditioner()`, `SNES`
257: @*/
258: PetscErrorCode KSPSetReusePreconditioner(KSP ksp, PetscBool flag)
259: {
260: PC pc;
262: PetscFunctionBegin;
264: PetscCall(KSPGetPC(ksp, &pc));
265: PetscCall(PCSetReusePreconditioner(pc, flag));
266: PetscFunctionReturn(PETSC_SUCCESS);
267: }
269: /*@
270: KSPGetReusePreconditioner - Determines if the `KSP` reuses the current preconditioner even if the `Mat` operator in the `KSP` has changed.
272: Collective
274: Input Parameter:
275: . ksp - iterative solver obtained from `KSPCreate()`
277: Output Parameter:
278: . flag - the boolean flag indicating if the current preconditioner should be reused
280: Level: intermediate
282: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSPSetReusePreconditioner()`, `KSP`
283: @*/
284: PetscErrorCode KSPGetReusePreconditioner(KSP ksp, PetscBool *flag)
285: {
286: PetscFunctionBegin;
288: PetscAssertPointer(flag, 2);
289: *flag = PETSC_FALSE;
290: if (ksp->pc) PetscCall(PCGetReusePreconditioner(ksp->pc, flag));
291: PetscFunctionReturn(PETSC_SUCCESS);
292: }
294: /*@
295: KSPSetSkipPCSetFromOptions - prevents `KSPSetFromOptions()` from calling `PCSetFromOptions()`.
296: This is used if the same `PC` is shared by more than one `KSP` so its options are not reset for each `KSP`
298: Collective
300: Input Parameters:
301: + ksp - iterative solver obtained from `KSPCreate()`
302: - flag - `PETSC_TRUE` to skip calling the `PCSetFromOptions()`
304: Level: developer
306: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `PCSetReusePreconditioner()`, `KSP`
307: @*/
308: PetscErrorCode KSPSetSkipPCSetFromOptions(KSP ksp, PetscBool flag)
309: {
310: PetscFunctionBegin;
312: ksp->skippcsetfromoptions = flag;
313: PetscFunctionReturn(PETSC_SUCCESS);
314: }
316: /*@
317: KSPSetUp - Sets up the internal data structures for the
318: later use `KSPSolve()` the `KSP` linear iterative solver.
320: Collective
322: Input Parameter:
323: . ksp - iterative solver, `KSP`, obtained from `KSPCreate()`
325: Level: developer
327: Note:
328: This is called automatically by `KSPSolve()` so usually does not need to be called directly.
330: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPSetUpOnBlocks()`
331: @*/
332: PetscErrorCode KSPSetUp(KSP ksp)
333: {
334: Mat A, B;
335: Mat mat;
336: MatNullSpace nullsp;
337: PCFailedReason pcreason;
338: PC pc;
339: PetscBool pcmpi, Aopset, Bopset;
340: MatState amatstate;
342: PetscFunctionBegin;
344: PetscCall(KSPGetPC(ksp, &pc));
345: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCMPI, &pcmpi));
346: if (pcmpi) {
347: PetscBool ksppreonly;
348: PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPPREONLY, &ksppreonly));
349: if (!ksppreonly) PetscCall(KSPSetType(ksp, KSPPREONLY));
350: }
351: level++;
353: /* reset the convergence flag from the previous solves */
354: ksp->reason = KSP_CONVERGED_ITERATING;
356: if (!((PetscObject)ksp)->type_name) PetscCall(KSPSetType(ksp, KSPGMRES));
357: PetscCall(KSPSetUpNorms_Private(ksp, PETSC_TRUE, &ksp->normtype, &ksp->pc_side));
359: PetscCall(KSPGetOperatorsSet(ksp, &Aopset, &Bopset));
360: PetscCheck(Aopset == Bopset, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Operators set inconsistency: Amat %d, Pmat %d", (int)Aopset, (int)Bopset);
362: if ((ksp->dmActive & KSP_DMACTIVE_OPERATOR) && !ksp->setupstage) {
363: /* first time in so build matrix and vector data structures using DM */
364: if (!ksp->vec_rhs) PetscCall(DMCreateGlobalVector(ksp->dm, &ksp->vec_rhs));
365: if (!ksp->vec_sol) PetscCall(DMCreateGlobalVector(ksp->dm, &ksp->vec_sol));
367: if (!Aopset) {
368: DMKSP kdm;
370: PetscCall(DMGetDMKSP(ksp->dm, &kdm));
371: if (kdm->ops->createoperators) {
372: A = B = NULL;
373: PetscCallBack("KSP callback create operators", (*kdm->ops->createoperators)(ksp, &A, &B, kdm->createoperatorsctx));
374: PetscCheck(A, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Missing A operator from DMKSPSetCreateOperators() callback");
375: if (!B) B = A;
376: if (B == A) PetscCall(PetscObjectReference((PetscObject)B));
377: PetscCall(KSPSetOperators(ksp, A, B));
378: PetscCall(MatDestroy(&A));
379: PetscCall(MatDestroy(&B));
380: } else {
381: PetscCall(DMCreateMatrix(ksp->dm, &A));
382: PetscCall(KSPSetOperators(ksp, A, A));
383: PetscCall(MatDestroy(&A));
384: }
385: }
386: }
388: if (ksp->dmActive) {
389: DMKSP kdm;
390: PetscCall(DMGetDMKSP(ksp->dm, &kdm));
392: if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS && (ksp->dmActive & KSP_DMACTIVE_INITIAL_GUESS)) {
393: /* only computes initial guess the first time through */
394: PetscCallBack("KSP callback initial guess", (*kdm->ops->computeinitialguess)(ksp, ksp->vec_sol, kdm->initialguessctx));
395: PetscCall(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
396: }
397: if (kdm->ops->computerhs && (ksp->dmActive & KSP_DMACTIVE_RHS)) PetscCallBack("KSP callback rhs", (*kdm->ops->computerhs)(ksp, ksp->vec_rhs, kdm->rhsctx));
398: if (ksp->setupstage != KSP_SETUP_NEWRHS && (ksp->dmActive & KSP_DMACTIVE_OPERATOR)) {
399: PetscCheck(kdm->ops->computeoperators, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE);");
400: PetscCall(KSPGetOperators(ksp, &A, &B));
401: PetscCallBack("KSP callback operators", (*kdm->ops->computeoperators)(ksp, A, B, kdm->operatorsctx));
402: }
403: }
405: /* Final decision if a KSP_SETUP_NEWMATRIX stage is needed */
406: PetscCall(KSPGetOperators(ksp, &A, NULL));
407: PetscCall(MatGetState(A, &amatstate));
408: if (ksp->setupstage == KSP_SETUP_NEWRHS) {
409: PetscBool same;
411: PetscCall(MatStateCompare(amatstate, ksp->amatstate, &same));
412: if (!same) ksp->setupstage = KSP_SETUP_NEWMATRIX;
413: }
415: if (ksp->setupstage != KSP_SETUP_NEWRHS) {
416: PetscCall(PetscLogEventBegin(KSP_SetUp, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
417: switch (ksp->setupstage) {
418: case KSP_SETUP_NEW:
419: PetscUseTypeMethod(ksp, setup);
420: break;
421: case KSP_SETUP_NEWMATRIX: /* This should be replaced with a more general mechanism */
422: if (ksp->setupnewmatrix) PetscUseTypeMethod(ksp, setup);
423: break;
424: default:
425: break;
426: }
427: PetscCall(PetscLogEventEnd(KSP_SetUp, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
428: }
430: /* setup PC if needed */
431: PetscCall(PCSetErrorIfFailure(pc, ksp->errorifnotconverged));
432: PetscCall(PCSetUp(pc));
433: PetscCall(PCGetFailedReason(pc, &pcreason));
434: /* TODO: this code was wrong and is still wrong, there is no way to propagate the failure to all processes; their is no code to handle a ksp->reason on only some ranks */
435: if (pcreason) ksp->reason = KSP_DIVERGED_PC_FAILED;
437: PetscCall(PCGetOperators(pc, &mat, NULL));
438: if (ksp->setupstage != KSP_SETUP_NEWRHS) {
439: PetscCall(MatGetNullSpace(mat, &nullsp));
440: if (nullsp) {
441: PetscBool test = PETSC_FALSE;
442: PetscCall(PetscOptionsGetBool(((PetscObject)ksp)->options, ((PetscObject)ksp)->prefix, "-ksp_test_null_space", &test, NULL));
443: if (test) PetscCall(MatNullSpaceTest(nullsp, mat, NULL));
444: }
445: }
447: PetscCall(MatGetState(mat, &ksp->amatstate));
448: ksp->setupstage = KSP_SETUP_NEWRHS;
449: level--;
450: PetscFunctionReturn(PETSC_SUCCESS);
451: }
453: /*@
454: KSPConvergedReasonView - Displays the reason a `KSP` solve converged or diverged, `KSPConvergedReason` to a `PetscViewer`
456: Collective
458: Input Parameters:
459: + ksp - iterative solver obtained from `KSPCreate()`
460: - viewer - the `PetscViewer` on which to display the reason
462: Options Database Keys:
463: + -ksp_converged_reason - print reason for converged or diverged, also prints number of iterations
464: - -ksp_converged_reason ::failed - only print reason and number of iterations when diverged
466: Level: beginner
468: Note:
469: Use `KSPConvergedReasonViewFromOptions()` to display the reason based on values in the PETSc options database.
471: To change the format of the output call `PetscViewerPushFormat`(`viewer`,`format`) before this call. Use `PETSC_VIEWER_DEFAULT` for the default,
472: use `PETSC_VIEWER_FAILED` to only display a reason if it fails.
474: .seealso: [](ch_ksp), `KSPConvergedReasonViewFromOptions()`, `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
475: `KSPSolveTranspose()`, `KSPGetIterationNumber()`, `KSP`, `KSPGetConvergedReason()`, `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
476: @*/
477: PetscErrorCode KSPConvergedReasonView(KSP ksp, PetscViewer viewer)
478: {
479: PetscBool isAscii;
480: PetscViewerFormat format;
482: PetscFunctionBegin;
483: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
484: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
485: if (isAscii) {
486: PetscCall(PetscViewerGetFormat(viewer, &format));
487: PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)ksp)->tablevel + 1));
488: if (ksp->reason > 0 && format != PETSC_VIEWER_FAILED) {
489: if (((PetscObject)ksp)->prefix) {
490: PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)ksp)->prefix, KSPConvergedReasons[ksp->reason], ksp->its));
491: } else {
492: PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve converged due to %s iterations %" PetscInt_FMT "\n", KSPConvergedReasons[ksp->reason], ksp->its));
493: }
494: } else if (ksp->reason <= 0) {
495: if (((PetscObject)ksp)->prefix) {
496: PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)ksp)->prefix, KSPConvergedReasons[ksp->reason], ksp->its));
497: } else {
498: PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve did not converge due to %s iterations %" PetscInt_FMT "\n", KSPConvergedReasons[ksp->reason], ksp->its));
499: }
500: if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
501: PCFailedReason reason;
502: PetscCall(PCGetFailedReason(ksp->pc, &reason));
503: PetscCall(PetscViewerASCIIPrintf(viewer, " PC failed due to %s\n", PCFailedReasons[reason]));
504: }
505: }
506: PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)ksp)->tablevel + 1));
507: }
508: PetscFunctionReturn(PETSC_SUCCESS);
509: }
511: /*@
512: KSPConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
513: end of the linear solver to display the convergence reason of the linear solver.
515: Logically Collective
517: Input Parameters:
518: + ksp - the `KSP` context
519: . f - the `ksp` converged reason view function, see `KSPConvergedReasonViewFn`
520: . ctx - [optional] context for private data for the `KSPConvergedReason` view routine (use `NULL` if context is not needed)
521: - reasonviewdestroy - [optional] routine that frees `ctx` (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
523: Options Database Keys:
524: + -ksp_converged_reason - sets a default `KSPConvergedReasonView()`
525: - -ksp_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
526: calls to `KSPConvergedReasonViewSet()`, but does not cancel those set via the options database.
528: Level: intermediate
530: Note:
531: Several different converged reason view routines may be set by calling
532: `KSPConvergedReasonViewSet()` multiple times; all will be called in the
533: order in which they were set.
535: Developer Note:
536: Should be named KSPConvergedReasonViewAdd().
538: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPConvergedReasonViewFn`, `KSPConvergedReasonViewCancel()`, `PetscCtxDestroyFn`
539: @*/
540: PetscErrorCode KSPConvergedReasonViewSet(KSP ksp, KSPConvergedReasonViewFn *f, PetscCtx ctx, PetscCtxDestroyFn *reasonviewdestroy)
541: {
542: PetscFunctionBegin;
544: for (PetscInt i = 0; i < ksp->numberreasonviews; i++) {
545: PetscBool identical;
547: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, ctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)ksp->reasonview[i], ksp->reasonviewcontext[i], ksp->reasonviewdestroy[i], &identical));
548: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
549: }
550: PetscCheck(ksp->numberreasonviews < MAXKSPREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many KSP reasonview set");
551: ksp->reasonview[ksp->numberreasonviews] = f;
552: ksp->reasonviewdestroy[ksp->numberreasonviews] = reasonviewdestroy;
553: ksp->reasonviewcontext[ksp->numberreasonviews++] = ctx;
554: PetscFunctionReturn(PETSC_SUCCESS);
555: }
557: /*@
558: KSPConvergedReasonViewCancel - Clears all the `KSPConvergedReason` view functions for a `KSP` object set with `KSPConvergedReasonViewSet()`
559: as well as the default viewer.
561: Collective
563: Input Parameter:
564: . ksp - iterative solver obtained from `KSPCreate()`
566: Level: intermediate
568: .seealso: [](ch_ksp), `KSPCreate()`, `KSPDestroy()`, `KSPReset()`, `KSPConvergedReasonViewSet()`
569: @*/
570: PetscErrorCode KSPConvergedReasonViewCancel(KSP ksp)
571: {
572: PetscInt i;
574: PetscFunctionBegin;
576: for (i = 0; i < ksp->numberreasonviews; i++) {
577: if (ksp->reasonviewdestroy[i]) PetscCall((*ksp->reasonviewdestroy[i])(&ksp->reasonviewcontext[i]));
578: }
579: ksp->numberreasonviews = 0;
580: PetscCall(PetscViewerDestroy(&ksp->convergedreasonviewer));
581: PetscFunctionReturn(PETSC_SUCCESS);
582: }
584: /*@
585: KSPConvergedReasonViewFromOptions - Processes command line options to determine if/how a `KSPConvergedReason` is to be viewed.
587: Collective
589: Input Parameter:
590: . ksp - the `KSP` object
592: Level: intermediate
594: Notes:
595: This function has a different API and behavior than `PetscObjectViewFromOptions()`
597: This is called automatically at the conclusion of `KSPSolve()` so is rarely called directly by user code.
599: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPConvergedReasonViewSet()`
600: @*/
601: PetscErrorCode KSPConvergedReasonViewFromOptions(KSP ksp)
602: {
603: PetscFunctionBegin;
604: /* Call all user-provided reason review routines */
605: for (PetscInt i = 0; i < ksp->numberreasonviews; i++) PetscCall((*ksp->reasonview[i])(ksp, ksp->reasonviewcontext[i]));
607: /* Call the default PETSc routine */
608: if (ksp->convergedreasonviewer) {
609: PetscCall(PetscViewerPushFormat(ksp->convergedreasonviewer, ksp->convergedreasonformat));
610: PetscCall(KSPConvergedReasonView(ksp, ksp->convergedreasonviewer));
611: PetscCall(PetscViewerPopFormat(ksp->convergedreasonviewer));
612: }
613: PetscFunctionReturn(PETSC_SUCCESS);
614: }
616: /*@
617: KSPConvergedRateView - Displays the convergence rate <https://en.wikipedia.org/wiki/Coefficient_of_determination> of `KSPSolve()` to a viewer
619: Collective
621: Input Parameters:
622: + ksp - iterative solver obtained from `KSPCreate()`
623: - viewer - the `PetscViewer` to display the reason
625: Options Database Key:
626: . -ksp_converged_rate - print reason for convergence or divergence and the convergence rate (or 0.0 for divergence)
628: Level: intermediate
630: Notes:
631: To change the format of the output, call `PetscViewerPushFormat`(`viewer`,`format`) before this call.
633: Suppose that the residual is reduced linearly, $r_k = c^k r_0$, which means $\log r_k = \log r_0 + k \log c$. After linear regression,
634: the slope is $\log c$. The coefficient of determination is given by $1 - \frac{\sum_i (y_i - f(x_i))^2}{\sum_i (y_i - \bar y)}$,
636: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPGetConvergedRate()`, `KSPSetTolerances()`, `KSPConvergedDefault()`
637: @*/
638: PetscErrorCode KSPConvergedRateView(KSP ksp, PetscViewer viewer)
639: {
640: PetscViewerFormat format;
641: PetscBool isAscii;
642: PetscReal rrate, rRsq, erate = 0.0, eRsq = 0.0;
643: PetscInt its;
644: const char *prefix, *reason = KSPConvergedReasons[ksp->reason];
646: PetscFunctionBegin;
647: PetscCall(KSPGetIterationNumber(ksp, &its));
648: PetscCall(KSPComputeConvergenceRate(ksp, &rrate, &rRsq, &erate, &eRsq));
649: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
650: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
651: if (isAscii) {
652: PetscCall(KSPGetOptionsPrefix(ksp, &prefix));
653: PetscCall(PetscViewerGetFormat(viewer, &format));
654: PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)ksp)->tablevel));
655: if (ksp->reason > 0) {
656: if (prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve converged due to %s iterations %" PetscInt_FMT, prefix, reason, its));
657: else PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve converged due to %s iterations %" PetscInt_FMT, reason, its));
658: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
659: if (rRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " res rate %g R^2 %g", (double)rrate, (double)rRsq));
660: if (eRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " error rate %g R^2 %g", (double)erate, (double)eRsq));
661: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
662: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
663: } else if (ksp->reason <= 0) {
664: if (prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve did not converge due to %s iterations %" PetscInt_FMT, prefix, reason, its));
665: else PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve did not converge due to %s iterations %" PetscInt_FMT, reason, its));
666: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
667: if (rRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " res rate %g R^2 %g", (double)rrate, (double)rRsq));
668: if (eRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " error rate %g R^2 %g", (double)erate, (double)eRsq));
669: PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
670: PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
671: if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
672: PCFailedReason reason;
673: PetscCall(PCGetFailedReason(ksp->pc, &reason));
674: PetscCall(PetscViewerASCIIPrintf(viewer, " PC failed due to %s\n", PCFailedReasons[reason]));
675: }
676: }
677: PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)ksp)->tablevel));
678: }
679: PetscFunctionReturn(PETSC_SUCCESS);
680: }
682: #include <petscdraw.h>
684: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
685: {
686: PetscReal *r, *c;
687: PetscInt n, i, neig;
688: PetscBool isascii, isdraw;
689: PetscMPIInt rank;
691: PetscFunctionBegin;
692: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ksp), &rank));
693: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
694: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
695: if (isExplicit) {
696: PetscCall(VecGetSize(ksp->vec_sol, &n));
697: PetscCall(PetscMalloc2(n, &r, n, &c));
698: PetscCall(KSPComputeEigenvaluesExplicitly(ksp, n, r, c));
699: neig = n;
700: } else {
701: PetscInt nits;
703: PetscCall(KSPGetIterationNumber(ksp, &nits));
704: n = nits + 2;
705: if (!nits) {
706: PetscCall(PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n"));
707: PetscFunctionReturn(PETSC_SUCCESS);
708: }
709: PetscCall(PetscMalloc2(n, &r, n, &c));
710: PetscCall(KSPComputeEigenvalues(ksp, n, r, c, &neig));
711: }
712: if (isascii) {
713: PetscCall(PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively"));
714: for (i = 0; i < neig; ++i) {
715: if (c[i] >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double)r[i], (double)c[i]));
716: else PetscCall(PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double)r[i], -(double)c[i]));
717: }
718: } else if (isdraw && rank == 0) {
719: PetscDraw draw;
720: PetscDrawSP drawsp;
722: if (format == PETSC_VIEWER_DRAW_CONTOUR) {
723: PetscCall(KSPPlotEigenContours_Private(ksp, neig, r, c));
724: } else {
725: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
726: PetscCall(PetscDrawSPCreate(draw, 1, &drawsp));
727: PetscCall(PetscDrawSPReset(drawsp));
728: for (i = 0; i < neig; ++i) PetscCall(PetscDrawSPAddPoint(drawsp, r + i, c + i));
729: PetscCall(PetscDrawSPDraw(drawsp, PETSC_TRUE));
730: PetscCall(PetscDrawSPSave(drawsp));
731: PetscCall(PetscDrawSPDestroy(&drawsp));
732: }
733: }
734: PetscCall(PetscFree2(r, c));
735: PetscFunctionReturn(PETSC_SUCCESS);
736: }
738: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
739: {
740: PetscReal smax, smin;
741: PetscInt nits;
742: PetscBool isascii;
744: PetscFunctionBegin;
745: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
746: PetscCall(KSPGetIterationNumber(ksp, &nits));
747: if (!nits) {
748: PetscCall(PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n"));
749: PetscFunctionReturn(PETSC_SUCCESS);
750: }
751: PetscCall(KSPComputeExtremeSingularValues(ksp, &smax, &smin));
752: if (isascii) PetscCall(PetscViewerASCIIPrintf(viewer, "Iteratively computed extreme %svalues: max %g min %g max/min %g\n", smin < 0 ? "eigen" : "singular ", (double)smax, (double)smin, (double)(smax / smin)));
753: PetscFunctionReturn(PETSC_SUCCESS);
754: }
756: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
757: {
758: PetscBool isascii;
760: PetscFunctionBegin;
761: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
762: if (isascii) {
763: Mat A;
764: Vec t;
765: PetscReal norm;
767: PetscCall(PCGetOperators(ksp->pc, &A, NULL));
768: PetscCall(VecDuplicate(ksp->vec_rhs, &t));
769: PetscCall(KSP_MatMult(ksp, A, ksp->vec_sol, t));
770: PetscCall(VecAYPX(t, -1.0, ksp->vec_rhs));
771: PetscCall(PetscOptionsPushCreateViewerOff(PETSC_FALSE));
772: PetscCall(VecViewFromOptions(t, (PetscObject)ksp, "-ksp_view_final_residual_vec"));
773: PetscCall(PetscOptionsPopCreateViewerOff());
774: PetscCall(VecNorm(t, NORM_2, &norm));
775: PetscCall(VecDestroy(&t));
776: PetscCall(PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double)norm));
777: }
778: PetscFunctionReturn(PETSC_SUCCESS);
779: }
781: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt n, PetscCtx ctx[])
782: {
783: PetscFunctionBegin;
784: for (PetscInt i = 0; i < n; ++i) {
785: PetscViewerAndFormat *vf = (PetscViewerAndFormat *)ctx[i];
786: PetscDraw draw;
787: PetscReal lpause;
788: PetscBool isdraw;
790: if (!vf) continue;
791: if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue;
792: if (((PetscObject)vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
793: PetscCall(PetscObjectTypeCompare((PetscObject)vf->viewer, PETSCVIEWERDRAW, &isdraw));
794: if (!isdraw) continue;
796: PetscCall(PetscViewerDrawGetDraw(vf->viewer, 0, &draw));
797: PetscCall(PetscDrawGetPause(draw, &lpause));
798: PetscCall(PetscDrawSetPause(draw, -1.0));
799: PetscCall(PetscDrawPause(draw));
800: PetscCall(PetscDrawSetPause(draw, lpause));
801: }
802: PetscFunctionReturn(PETSC_SUCCESS);
803: }
805: static PetscErrorCode KSPMonitorPauseFinal_Internal(KSP ksp)
806: {
807: PetscFunctionBegin;
808: if (!ksp->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
809: PetscCall(PetscMonitorPauseFinal_Internal(ksp->numbermonitors, ksp->monitorcontext));
810: PetscFunctionReturn(PETSC_SUCCESS);
811: }
813: static PetscErrorCode KSPSolve_Private(KSP ksp, Vec b, Vec x)
814: {
815: PetscBool flg = PETSC_FALSE, inXisinB = PETSC_FALSE, guess_zero;
816: Mat mat, pmat;
817: MPI_Comm comm;
818: MatNullSpace nullsp;
819: Vec btmp, vec_rhs = NULL;
821: PetscFunctionBegin;
822: level++;
823: comm = PetscObjectComm((PetscObject)ksp);
824: /* ksp->mat_rhs is only set around the ksp->ops->matsolve call in KSPMatSolve_Private(), so clearing it here keeps KSPConvergedDefault() from reading a block of right-hand sides that this solve does not own */
825: ksp->mat_rhs = NULL;
826: if (x && x == b) {
827: PetscCheck(ksp->guess_zero, comm, PETSC_ERR_ARG_INCOMP, "Cannot use x == b with nonzero initial guess");
828: PetscCall(VecDuplicate(b, &x));
829: inXisinB = PETSC_TRUE;
830: }
831: if (b) {
832: PetscCall(PetscObjectReference((PetscObject)b));
833: PetscCall(VecDestroy(&ksp->vec_rhs));
834: ksp->vec_rhs = b;
835: }
836: if (x) {
837: PetscCall(PetscObjectReference((PetscObject)x));
838: PetscCall(VecDestroy(&ksp->vec_sol));
839: ksp->vec_sol = x;
840: }
842: if (ksp->viewPre) PetscCall(ObjectView((PetscObject)ksp, ksp->viewerPre, ksp->formatPre));
844: /* reset the residual history list if requested */
845: if (ksp->res_hist_reset) ksp->res_hist_len = 0;
846: if (ksp->err_hist_reset) ksp->err_hist_len = 0;
848: PetscCall(KSPSetUp(ksp));
849: PetscCall(KSPSetUpOnBlocks(ksp));
851: if (ksp->guess) {
852: PetscObjectState ostate, state;
854: PetscCall(KSPGuessSetUp(ksp->guess));
855: PetscCall(PetscObjectStateGet((PetscObject)ksp->vec_sol, &ostate));
856: PetscCall(KSPGuessFormGuess(ksp->guess, ksp->vec_rhs, ksp->vec_sol));
857: PetscCall(PetscObjectStateGet((PetscObject)ksp->vec_sol, &state));
858: if (state != ostate) {
859: ksp->guess_zero = PETSC_FALSE;
860: } else {
861: PetscCall(PetscInfo(ksp, "Using zero initial guess since the KSPGuess object did not change the vector\n"));
862: ksp->guess_zero = PETSC_TRUE;
863: }
864: }
866: PetscCall(KSPPreSolve(ksp, ksp->vec_rhs, ksp->vec_sol));
868: PetscCall(VecSetErrorIfLocked(ksp->vec_sol, 3));
870: PetscCall(PetscLogEventBegin(!ksp->transpose.solve_requested ? KSP_Solve : KSP_SolveTranspose, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
871: PetscCall(PCGetOperators(ksp->pc, &mat, NULL));
872: PetscCall(PCPreSolve(ksp->pc, ksp));
874: if (ksp->guess_zero && !ksp->guess_not_read) PetscCall(VecSet(ksp->vec_sol, 0.0));
875: if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
876: PetscCall(PCApply(ksp->pc, ksp->vec_rhs, ksp->vec_sol));
877: PetscCall(KSP_RemoveNullSpace(ksp, ksp->vec_sol));
878: ksp->guess_zero = PETSC_FALSE;
879: }
881: /* can we mark the initial guess as zero for this solve? */
882: guess_zero = ksp->guess_zero;
883: if (!ksp->guess_zero) {
884: PetscReal norm;
886: PetscCall(VecNormAvailable(ksp->vec_sol, NORM_2, &flg, &norm));
887: if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
888: }
889: if (ksp->transpose_solve) {
890: PetscCall(MatGetNullSpace(mat, &nullsp));
891: } else {
892: PetscCall(MatGetTransposeNullSpace(mat, &nullsp));
893: }
894: if (nullsp) {
895: PetscCall(VecDuplicate(ksp->vec_rhs, &btmp));
896: PetscCall(VecCopy(ksp->vec_rhs, btmp));
897: PetscCall(MatNullSpaceRemove(nullsp, btmp));
898: vec_rhs = ksp->vec_rhs;
899: ksp->vec_rhs = btmp;
900: }
901: PetscCall(VecLockReadPush(ksp->vec_rhs));
902: PetscUseTypeMethod(ksp, solve);
903: PetscCall(KSPMonitorPauseFinal_Internal(ksp));
905: PetscCall(VecLockReadPop(ksp->vec_rhs));
906: if (nullsp) {
907: ksp->vec_rhs = vec_rhs;
908: PetscCall(VecDestroy(&btmp));
909: }
911: ksp->guess_zero = guess_zero;
913: PetscCheck(ksp->reason, comm, PETSC_ERR_PLIB, "Internal error, solver returned without setting converged reason");
914: ksp->totalits += ksp->its;
916: PetscCall(KSPConvergedReasonViewFromOptions(ksp));
918: if (ksp->viewRate) {
919: PetscCall(PetscViewerPushFormat(ksp->viewerRate, ksp->formatRate));
920: PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
921: PetscCall(PetscViewerPopFormat(ksp->viewerRate));
922: }
923: PetscCall(PCPostSolve(ksp->pc, ksp));
925: PetscCall(PetscLogEventEnd(!ksp->transpose.solve_requested ? KSP_Solve : KSP_SolveTranspose, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
926: if (ksp->guess) PetscCall(KSPGuessUpdate(ksp->guess, ksp->vec_rhs, ksp->vec_sol));
927: PetscCall(KSPPostSolve(ksp, ksp->vec_rhs, ksp->vec_sol));
929: PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
930: if (ksp->viewEV) PetscCall(KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV, ksp->formatEV));
931: if (ksp->viewEVExp) PetscCall(KSPViewEigenvalues_Internal(ksp, PETSC_TRUE, ksp->viewerEVExp, ksp->formatEVExp));
932: if (ksp->viewSV) PetscCall(KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV));
933: if (ksp->viewFinalRes) PetscCall(KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes));
934: if (ksp->viewMat) PetscCall(ObjectView((PetscObject)mat, ksp->viewerMat, ksp->formatMat));
935: if (ksp->viewPMat) PetscCall(ObjectView((PetscObject)pmat, ksp->viewerPMat, ksp->formatPMat));
936: if (ksp->viewRhs) PetscCall(ObjectView((PetscObject)ksp->vec_rhs, ksp->viewerRhs, ksp->formatRhs));
937: if (ksp->viewSol) PetscCall(ObjectView((PetscObject)ksp->vec_sol, ksp->viewerSol, ksp->formatSol));
938: if (ksp->view) PetscCall(ObjectView((PetscObject)ksp, ksp->viewer, ksp->format));
939: if (ksp->viewMatExp) {
940: Mat B;
942: if (ksp->transpose_solve) {
943: Mat AT;
945: PetscCall(MatCreateTranspose(mat, &AT));
946: PetscCall(MatComputeOperator(AT, MATAIJ, &B));
947: PetscCall(MatDestroy(&AT));
948: } else {
949: PetscCall(MatComputeOperator(mat, MATAIJ, &B));
950: }
951: PetscCall(ObjectView((PetscObject)B, ksp->viewerMatExp, ksp->formatMatExp));
952: PetscCall(MatDestroy(&B));
953: }
954: if (ksp->viewPOpExp) {
955: Mat B;
957: PetscCall(KSPComputeOperator(ksp, MATAIJ, &B));
958: PetscCall(ObjectView((PetscObject)B, ksp->viewerPOpExp, ksp->formatPOpExp));
959: PetscCall(MatDestroy(&B));
960: }
962: if (inXisinB) {
963: PetscCall(VecCopy(x, b));
964: PetscCall(VecDestroy(&x));
965: }
966: PetscCall(PetscObjectSAWsBlock((PetscObject)ksp));
967: if (ksp->errorifnotconverged && ksp->reason < 0 && ((level == 1) || (ksp->reason != KSP_DIVERGED_ITS))) {
968: PCFailedReason reason;
970: PetscCheck(ksp->reason == KSP_DIVERGED_PC_FAILED, comm, PETSC_ERR_NOT_CONVERGED, "KSPSolve%s() has not converged, reason %s", !ksp->transpose.solve_requested ? "" : "Transpose", KSPConvergedReasons[ksp->reason]);
971: PetscCall(PCGetFailedReason(ksp->pc, &reason));
972: SETERRQ(comm, PETSC_ERR_NOT_CONVERGED, "KSPSolve%s() has not converged, reason %s PC failed due to %s", !ksp->transpose.solve_requested ? "" : "Transpose", KSPConvergedReasons[ksp->reason], PCFailedReasons[reason]);
973: }
974: level--;
975: PetscFunctionReturn(PETSC_SUCCESS);
976: }
978: /*@
979: KSPSolve - Solves a linear system associated with `KSP` object
981: Collective
983: Input Parameters:
984: + ksp - iterative solver obtained from `KSPCreate()`
985: . b - the right-hand side vector
986: - x - the solution (this may be the same vector as `b`, then `b` will be overwritten with the answer)
988: Level: beginner
990: Notes:
991: See `KSPSetFromOptions()` for options database keys that affect `KSPSolve()`
993: If one uses `KSPSetDM()` then `x` or `b` need not be passed. Use `KSPGetSolution()` to access the solution in this case.
995: The operator is specified with `KSPSetOperators()`.
997: `KSPSolve()` will normally return without generating an error regardless of whether the linear system was solved or if constructing the preconditioner failed.
998: Call `KSPGetConvergedReason()` to determine if the solver converged or failed and why. The option -ksp_error_if_not_converged or function `KSPSetErrorIfNotConverged()`
999: will cause `KSPSolve()` to error as soon as an error occurs in the linear solver. In inner `KSPSolve()` `KSP_DIVERGED_ITS` is not treated as an error because when using nested solvers
1000: it may be fine that inner solvers in the preconditioner do not converge during the solution process.
1002: The number of iterations can be obtained from `KSPGetIterationNumber()`.
1004: If you provide a matrix that has a `MatSetNullSpace()` and `MatSetTransposeNullSpace()` this will use that information to solve singular systems
1005: in the least squares sense with a norm minimizing solution.
1007: $A x = b $ where $b = b_p + b_t$ where $b_t$ is not in the range of $A$ (and hence by the fundamental theorem of linear algebra is in the nullspace(A'), see `MatSetNullSpace()`).
1009: `KSP` first removes $b_t$ producing the linear system $A x = b_p$ (which has multiple solutions) and solves this to find the $\|x\|$ minimizing solution (and hence
1010: it finds the solution $x$ orthogonal to the nullspace(A). The algorithm is simply in each iteration of the Krylov method we remove the nullspace(A) from the search
1011: direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).
1013: We recommend always using `KSPGMRES` for such singular systems.
1014: If $ nullspace(A) = nullspace(A^T)$ (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
1015: If $nullspace(A) \neq nullspace(A^T)$ then left preconditioning will work but right preconditioning may not work (or it may).
1017: Developer Notes:
1018: The reason we cannot always solve $nullspace(A) \neq nullspace(A^T)$ systems with right preconditioning is because we need to remove at each iteration
1019: $ nullspace(AB) $ from the search direction. While we know the $nullspace(A)$, $nullspace(AB)$ equals $B^{-1}$ times $nullspace(A)$ but except for trivial preconditioners
1020: such as diagonal scaling we cannot apply the inverse of the preconditioner to a vector and thus cannot compute $nullspace(AB)$.
1022: If using a direct method (e.g., via the `KSP` solver
1023: `KSPPREONLY` and a preconditioner such as `PCLU` or `PCCHOLESKY` then usually one iteration of the `KSP` method will be needed for convergence.
1025: To solve a linear system with the transpose of the matrix use `KSPSolveTranspose()`.
1027: Understanding Convergence\:
1028: The manual pages `KSPMonitorSet()`, `KSPComputeEigenvalues()`, and
1029: `KSPComputeEigenvaluesExplicitly()` provide information on additional
1030: options to monitor convergence and print eigenvalue information.
1032: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
1033: `KSPSolveTranspose()`, `KSPGetIterationNumber()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatSetTransposeNullSpace()`, `KSP`,
1034: `KSPConvergedReasonView()`, `KSPCheckSolve()`, `KSPSetErrorIfNotConverged()`
1035: @*/
1036: PetscErrorCode KSPSolve(KSP ksp, Vec b, Vec x)
1037: {
1038: PetscBool isPCMPI;
1040: PetscFunctionBegin;
1044: PetscCall(KSPRestoreExplicitTranspose_Private(ksp));
1045: ksp->transpose_solve = PETSC_FALSE;
1046: ksp->transpose.solve_requested = PETSC_FALSE;
1047: PetscCall(KSPSolve_Private(ksp, b, x));
1048: PetscCall(PetscObjectTypeCompare((PetscObject)ksp->pc, PCMPI, &isPCMPI));
1049: if (PCMPIServerActive && isPCMPI) {
1050: KSP subksp;
1052: PetscCall(PCMPIGetKSP(ksp->pc, &subksp));
1053: ksp->its = subksp->its;
1054: ksp->reason = subksp->reason;
1055: }
1056: PetscFunctionReturn(PETSC_SUCCESS);
1057: }
1059: static PetscErrorCode KSPResetExplicitTranspose_Private(KSP ksp)
1060: {
1061: PetscFunctionBegin;
1062: PetscCall(MatDestroy(&ksp->transpose.AT));
1063: PetscCall(MatDestroy(&ksp->transpose.BT));
1064: PetscCall(MatDestroy(&ksp->transpose.A));
1065: PetscCall(MatDestroy(&ksp->transpose.B));
1066: ksp->transpose.Aid = 0;
1067: ksp->transpose.Bid = 0;
1068: ksp->transpose.Anonzerostate = 0;
1069: ksp->transpose.Bnonzerostate = 0;
1070: ksp->transpose.reuse_transpose = PETSC_FALSE;
1071: PetscFunctionReturn(PETSC_SUCCESS);
1072: }
1074: static PetscErrorCode KSPRestoreExplicitTranspose_Private(KSP ksp)
1075: {
1076: Mat J, Jpre;
1077: PetscObjectState Jnonzerostate, Jprenonzerostate;
1078: PetscBool reset, restore = PETSC_FALSE;
1080: PetscFunctionBegin;
1081: if (!ksp->transpose.reuse_transpose) PetscFunctionReturn(PETSC_SUCCESS);
1082: PetscCall(KSPGetOperators(ksp, &J, &Jpre));
1083: if (J == ksp->transpose.AT) {
1084: J = ksp->transpose.A;
1085: restore = PETSC_TRUE;
1086: }
1087: if (Jpre == ksp->transpose.BT) {
1088: Jpre = ksp->transpose.B;
1089: restore = PETSC_TRUE;
1090: }
1091: PetscCall(MatGetNonzeroState(J, &Jnonzerostate));
1092: PetscCall(MatGetNonzeroState(Jpre, &Jprenonzerostate));
1093: reset = (PetscBool)(((PetscObject)J)->id != ksp->transpose.Aid || ((PetscObject)Jpre)->id != ksp->transpose.Bid || Jnonzerostate != ksp->transpose.Anonzerostate || Jprenonzerostate != ksp->transpose.Bnonzerostate);
1094: if (restore) PetscCall(KSPSetOperators(ksp, J, Jpre));
1095: if (reset) PetscCall(KSPResetExplicitTranspose_Private(ksp));
1096: PetscFunctionReturn(PETSC_SUCCESS);
1097: }
1099: static PetscErrorCode KSPUseExplicitTranspose_Private(KSP ksp)
1100: {
1101: Mat J, Jpre, holdJ = NULL, holdJpre = NULL;
1102: PetscObjectState ATstate, BTstate, Jnonzerostate, Jprenonzerostate, state;
1103: PetscBool rebuild, transposes_set = PETSC_FALSE;
1105: PetscFunctionBegin;
1106: ksp->transpose_solve = PETSC_FALSE;
1107: PetscCall(KSPGetOperators(ksp, &J, &Jpre));
1108: if (ksp->transpose.reuse_transpose) {
1109: transposes_set = (PetscBool)(J == ksp->transpose.AT && Jpre == ksp->transpose.BT);
1110: /* A previous call set the cached transposes as the KSP operators; update them from their parent operators */
1111: if (J == ksp->transpose.AT) J = ksp->transpose.A;
1112: if (Jpre == ksp->transpose.BT) Jpre = ksp->transpose.B;
1113: }
1114: PetscCall(MatGetNonzeroState(J, &Jnonzerostate));
1115: PetscCall(MatGetNonzeroState(Jpre, &Jprenonzerostate));
1116: if (ksp->transpose.reuse_transpose && (((PetscObject)J)->id != ksp->transpose.Aid || ((PetscObject)Jpre)->id != ksp->transpose.Bid || Jnonzerostate != ksp->transpose.Anonzerostate || Jprenonzerostate != ksp->transpose.Bnonzerostate)) {
1117: PetscCall(PetscObjectReference((PetscObject)J));
1118: PetscCall(PetscObjectReference((PetscObject)Jpre));
1119: holdJ = J;
1120: holdJpre = Jpre;
1121: PetscCall(KSPResetExplicitTranspose_Private(ksp));
1122: }
1123: if (!ksp->transpose.reuse_transpose) {
1124: PetscCall(PetscObjectReference((PetscObject)J));
1125: PetscCall(PetscObjectReference((PetscObject)Jpre));
1126: ksp->transpose.A = J;
1127: ksp->transpose.B = Jpre;
1128: ksp->transpose.Aid = ((PetscObject)J)->id;
1129: ksp->transpose.Bid = ((PetscObject)Jpre)->id;
1130: ksp->transpose.Anonzerostate = Jnonzerostate;
1131: ksp->transpose.Bnonzerostate = Jprenonzerostate;
1132: PetscCall(MatTranspose(J, MAT_INITIAL_MATRIX, &ksp->transpose.AT));
1133: if (J != Jpre) PetscCall(MatTranspose(Jpre, MAT_INITIAL_MATRIX, &ksp->transpose.BT));
1134: else {
1135: PetscCall(PetscObjectReference((PetscObject)ksp->transpose.AT));
1136: ksp->transpose.BT = ksp->transpose.AT;
1137: }
1138: ksp->transpose.reuse_transpose = PETSC_TRUE;
1139: rebuild = PETSC_TRUE;
1140: } else {
1141: PetscCall(PetscObjectStateGet((PetscObject)ksp->transpose.AT, &ATstate));
1142: PetscCall(PetscObjectStateGet((PetscObject)ksp->transpose.BT, &BTstate));
1143: PetscCall(MatTranspose(J, MAT_REUSE_MATRIX, &ksp->transpose.AT));
1144: if (J != Jpre) PetscCall(MatTranspose(Jpre, MAT_REUSE_MATRIX, &ksp->transpose.BT));
1145: PetscCall(PetscObjectStateGet((PetscObject)ksp->transpose.AT, &state));
1146: rebuild = (PetscBool)(ATstate != state);
1147: PetscCall(PetscObjectStateGet((PetscObject)ksp->transpose.BT, &state));
1148: rebuild = (PetscBool)(rebuild || BTstate != state);
1149: }
1150: if (rebuild || !transposes_set) PetscCall(KSPSetOperators(ksp, ksp->transpose.AT, ksp->transpose.BT));
1151: PetscCall(MatDestroy(&holdJ));
1152: PetscCall(MatDestroy(&holdJpre));
1153: PetscFunctionReturn(PETSC_SUCCESS);
1154: }
1156: /*@
1157: KSPSolveTranspose - Solves a linear system with the transpose of the matrix associated with the `KSP` object, $A^T x = b$.
1159: Collective
1161: Input Parameters:
1162: + ksp - iterative solver obtained from `KSPCreate()`
1163: . b - right-hand side vector
1164: - x - solution vector
1166: Level: developer
1168: Note:
1169: For complex numbers, this solves the non-Hermitian transpose system. `KSPSetUseExplicitTranspose()` controls whether the transpose is formed explicitly and describes the
1170: effect on the `KSP` operators.
1172: Developer Note:
1173: We need to implement a `KSPSolveHermitianTranspose()`
1175: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
1176: `KSPSolve()`, `KSPSetUseExplicitTranspose()`, `KSP`, `KSPSetOperators()`
1177: @*/
1178: PetscErrorCode KSPSolveTranspose(KSP ksp, Vec b, Vec x)
1179: {
1180: PetscFunctionBegin;
1184: ksp->transpose.solve_requested = PETSC_TRUE;
1185: if (ksp->transpose.use_explicittranspose) PetscCall(KSPUseExplicitTranspose_Private(ksp));
1186: else ksp->transpose_solve = PETSC_TRUE;
1187: PetscCall(KSPSolve_Private(ksp, b, x));
1188: PetscFunctionReturn(PETSC_SUCCESS);
1189: }
1191: static PetscErrorCode KSPViewFinalMatResidual_Internal(KSP ksp, Mat B, Mat X, PetscViewer viewer, PetscViewerFormat format, PetscInt shift)
1192: {
1193: Mat A, R;
1194: PetscReal *norms;
1195: PetscInt N;
1196: PetscBool flg;
1198: PetscFunctionBegin;
1199: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg));
1200: if (flg) {
1201: PetscCall(PCGetOperators(ksp->pc, &A, NULL));
1202: if (!ksp->transpose_solve) PetscCall(MatMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DETERMINE, &R));
1203: else PetscCall(MatTransposeMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DETERMINE, &R));
1204: PetscCall(MatAYPX(R, -1.0, B, SAME_NONZERO_PATTERN));
1205: PetscCall(MatGetSize(R, NULL, &N));
1206: PetscCall(PetscMalloc1(N, &norms));
1207: PetscCall(MatGetColumnNorms(R, NORM_2, norms));
1208: PetscCall(MatDestroy(&R));
1209: for (PetscInt i = 0; i < N; ++i) PetscCall(PetscViewerASCIIPrintf(viewer, "%s #%" PetscInt_FMT " %g\n", i == 0 ? "KSP final norm of residual" : " ", shift + i, (double)norms[i]));
1210: PetscCall(PetscFree(norms));
1211: }
1212: PetscFunctionReturn(PETSC_SUCCESS);
1213: }
1215: static PetscErrorCode KSPMatSolve_Private(KSP ksp, Mat B, Mat X)
1216: {
1217: Mat A, P, vB, vX;
1218: Vec cb, cx;
1219: PetscInt n1, N1, n2, N2, Bbn = PETSC_DECIDE;
1220: PetscBool match;
1222: PetscFunctionBegin;
1223: PetscCheckSameComm(ksp, 1, B, 2);
1224: PetscCheckSameComm(ksp, 1, X, 3);
1225: ksp->mat_rhs = NULL; /* it is set around the ksp->ops->matsolve calls below, an erroring type method must not leave it dangling */
1226: PetscCheck(B->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
1227: MatCheckPreallocated(X, 3);
1228: if (!X->assembled) {
1229: PetscCall(MatSetOption(X, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1230: PetscCall(MatAssemblyBegin(X, MAT_FINAL_ASSEMBLY));
1231: PetscCall(MatAssemblyEnd(X, MAT_FINAL_ASSEMBLY));
1232: }
1233: PetscCheck(B != X, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_IDN, "B and X must be different matrices");
1234: PetscCall(KSPGetOperators(ksp, &A, &P));
1235: PetscCall(MatGetLocalSize(B, NULL, &n2));
1236: PetscCall(MatGetLocalSize(X, NULL, &n1));
1237: PetscCall(MatGetSize(B, NULL, &N2));
1238: PetscCall(MatGetSize(X, NULL, &N1));
1239: PetscCheck(n1 == n2 && N1 == N2, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible number of columns between block of right-hand sides (n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ") and block of solutions (n,N) = (%" PetscInt_FMT ",%" PetscInt_FMT ")", n2, N2, n1, N1);
1240: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &match, MATSEQDENSE, MATMPIDENSE, ""));
1241: PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of right-hand sides not stored in a dense Mat");
1242: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)X, &match, MATSEQDENSE, MATMPIDENSE, ""));
1243: PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of solutions not stored in a dense Mat");
1244: PetscCall(KSPSetUp(ksp));
1245: PetscCall(KSPSetUpOnBlocks(ksp));
1246: if (ksp->ops->matsolve) {
1247: level++;
1248: if (ksp->guess_zero) PetscCall(MatZeroEntries(X));
1249: PetscCall(PetscLogEventBegin(!ksp->transpose.solve_requested ? KSP_MatSolve : KSP_MatSolveTranspose, ksp, B, X, 0));
1250: PetscCall(KSPGetMatSolveBatchSize(ksp, &Bbn));
1251: /* by default, do a single solve with all columns */
1252: if (Bbn == PETSC_DECIDE) Bbn = N2;
1253: else PetscCheck(Bbn >= 1, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "KSPMatSolve() batch size %" PetscInt_FMT " must be positive", Bbn);
1254: PetscCall(PetscInfo(ksp, "KSP type %s%s solving using batches of width at most %" PetscInt_FMT "\n", ((PetscObject)ksp)->type_name, ksp->transpose.solve_requested ? " transpose" : "", Bbn));
1255: /* if -ksp_matsolve_batch_size is greater than the actual number of columns, do a single solve with all columns */
1256: if (Bbn >= N2) {
1257: /* reset the history lists (residual and error) if requested, as in KSPSolve_Private(), since KSPMatSolve() supports -ksp_converged_rate, which reads the residual history */
1258: if (ksp->res_hist_reset) ksp->res_hist_len = 0;
1259: if (ksp->err_hist_reset) ksp->err_hist_len = 0;
1260: ksp->mat_rhs = B;
1261: PetscUseTypeMethod(ksp, matsolve, B, X);
1262: ksp->mat_rhs = NULL;
1263: if (ksp->viewFinalRes) PetscCall(KSPViewFinalMatResidual_Internal(ksp, B, X, ksp->viewerFinalRes, ksp->formatFinalRes, 0));
1265: PetscCall(KSPConvergedReasonViewFromOptions(ksp));
1267: if (ksp->viewRate) {
1268: PetscCall(PetscViewerPushFormat(ksp->viewerRate, PETSC_VIEWER_DEFAULT));
1269: PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
1270: PetscCall(PetscViewerPopFormat(ksp->viewerRate));
1271: }
1272: } else {
1273: for (n2 = 0; n2 < N2; n2 += Bbn) {
1274: PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, n2, PetscMin(n2 + Bbn, N2), &vB));
1275: PetscCall(MatDenseGetSubMatrix(X, PETSC_DECIDE, PETSC_DECIDE, n2, PetscMin(n2 + Bbn, N2), &vX));
1276: if (ksp->res_hist_reset) ksp->res_hist_len = 0;
1277: if (ksp->err_hist_reset) ksp->err_hist_len = 0;
1278: ksp->mat_rhs = vB;
1279: PetscUseTypeMethod(ksp, matsolve, vB, vX);
1280: ksp->mat_rhs = NULL;
1281: if (ksp->viewFinalRes) PetscCall(KSPViewFinalMatResidual_Internal(ksp, vB, vX, ksp->viewerFinalRes, ksp->formatFinalRes, n2));
1283: PetscCall(KSPConvergedReasonViewFromOptions(ksp));
1285: if (ksp->viewRate) {
1286: PetscCall(PetscViewerPushFormat(ksp->viewerRate, PETSC_VIEWER_DEFAULT));
1287: PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
1288: PetscCall(PetscViewerPopFormat(ksp->viewerRate));
1289: }
1290: PetscCall(MatDenseRestoreSubMatrix(B, &vB));
1291: PetscCall(MatDenseRestoreSubMatrix(X, &vX));
1292: /* the state increase a failed solve does on the view is not propagated by the restore above, so it is redone on the whole block of solutions */
1293: if (ksp->reason < 0) PetscCall(PetscObjectStateIncrease((PetscObject)X));
1294: }
1295: }
1296: if (ksp->viewMat) PetscCall(ObjectView((PetscObject)A, ksp->viewerMat, ksp->formatMat));
1297: if (ksp->viewPMat) PetscCall(ObjectView((PetscObject)P, ksp->viewerPMat, ksp->formatPMat));
1298: if (ksp->viewRhs) PetscCall(ObjectView((PetscObject)B, ksp->viewerRhs, ksp->formatRhs));
1299: if (ksp->viewSol) PetscCall(ObjectView((PetscObject)X, ksp->viewerSol, ksp->formatSol));
1300: if (ksp->view) PetscCall(KSPView(ksp, ksp->viewer));
1301: PetscCall(PetscLogEventEnd(!ksp->transpose.solve_requested ? KSP_MatSolve : KSP_MatSolveTranspose, ksp, B, X, 0));
1302: if (ksp->errorifnotconverged && ksp->reason < 0 && (level == 1 || ksp->reason != KSP_DIVERGED_ITS)) {
1303: PCFailedReason reason;
1305: PetscCheck(ksp->reason == KSP_DIVERGED_PC_FAILED, PetscObjectComm((PetscObject)ksp), PETSC_ERR_NOT_CONVERGED, "KSPMatSolve%s() has not converged, reason %s", !ksp->transpose.solve_requested ? "" : "Transpose", KSPConvergedReasons[ksp->reason]);
1306: PetscCall(PCGetFailedReason(ksp->pc, &reason));
1307: SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_NOT_CONVERGED, "KSPMatSolve%s() has not converged, reason %s PC failed due to %s", !ksp->transpose.solve_requested ? "" : "Transpose", KSPConvergedReasons[ksp->reason], PCFailedReasons[reason]);
1308: }
1309: level--;
1310: } else {
1311: PetscCall(PetscInfo(ksp, "KSP type %s solving column by column\n", ((PetscObject)ksp)->type_name));
1312: for (n2 = 0; n2 < N2; ++n2) {
1313: PetscCall(MatDenseGetColumnVecRead(B, n2, &cb));
1314: PetscCall(MatDenseGetColumnVecWrite(X, n2, &cx));
1315: PetscCall(KSPSolve_Private(ksp, cb, cx));
1316: PetscCall(MatDenseRestoreColumnVecWrite(X, n2, &cx));
1317: PetscCall(MatDenseRestoreColumnVecRead(B, n2, &cb));
1318: }
1319: }
1320: PetscFunctionReturn(PETSC_SUCCESS);
1321: }
1323: /*@
1324: KSPMatSolve - Solves a linear system with multiple right-hand sides stored as a `MATDENSE`.
1326: Input Parameters:
1327: + ksp - iterative solver
1328: - B - block of right-hand sides
1330: Output Parameter:
1331: . X - block of solutions
1333: Level: intermediate
1335: Notes:
1336: This is a stripped-down version of `KSPSolve()`, which only handles `-ksp_view`, `-ksp_converged_reason`, `-ksp_converged_rate`, and `-ksp_view_final_residual`.
1338: Unlike with `KSPSolve()`, `B` and `X` must be different matrices.
1340: The columns of `B` are solved in batches of at most the size set with `KSPSetMatSolveBatchSize()`, which defaults to the whole block, and the `KSPType`
1341: implementation is called once per batch.
1343: As `KSPSolve()` does, this resets the residual and error history lists at the start of the solve, and at the start of each batch when `KSPSetMatSolveBatchSize()` is
1344: used, unless `KSPSetResidualHistory()` or `KSPSetErrorHistory()` was called with `reset` set to `PETSC_FALSE`.
1346: .seealso: [](ch_ksp), `KSPSolve()`, `MatMatSolve()`, `KSPMatSolveTranspose()`, `MATDENSE`, `KSPHPDDM`, `KSPRICHARDSON`, `PCBJACOBI`, `PCASM`, `KSPSetMatSolveBatchSize()`
1347: @*/
1348: PetscErrorCode KSPMatSolve(KSP ksp, Mat B, Mat X)
1349: {
1350: PetscFunctionBegin;
1354: PetscCall(KSPRestoreExplicitTranspose_Private(ksp));
1355: ksp->transpose_solve = PETSC_FALSE;
1356: ksp->transpose.solve_requested = PETSC_FALSE;
1357: PetscCall(KSPMatSolve_Private(ksp, B, X));
1358: PetscFunctionReturn(PETSC_SUCCESS);
1359: }
1361: /*@
1362: KSPMatSolveTranspose - Solves a linear system with the transposed matrix with multiple right-hand sides stored as a `MATDENSE`.
1364: Input Parameters:
1365: + ksp - iterative solver
1366: - B - block of right-hand sides
1368: Output Parameter:
1369: . X - block of solutions
1371: Level: intermediate
1373: Notes:
1374: This is a stripped-down version of `KSPSolveTranspose()`, which only handles `-ksp_view`, `-ksp_converged_reason`, `-ksp_converged_rate`, and `-ksp_view_final_residual`.
1376: Unlike `KSPSolveTranspose()`, `B` and `X` must be different matrices.
1378: The columns of `B` are solved in batches of at most the size set with `KSPSetMatSolveBatchSize()`, which defaults to the whole block, and the `KSPType`
1379: implementation is called once per batch.
1381: As `KSPSolveTranspose()` does, this resets the residual and error history lists at the start of the solve, and at the start of each batch when
1382: `KSPSetMatSolveBatchSize()` is used, unless `KSPSetResidualHistory()` or `KSPSetErrorHistory()` was called with `reset` set to `PETSC_FALSE`.
1384: .seealso: [](ch_ksp), `KSPSolveTranspose()`, `KSPSetUseExplicitTranspose()`, `MatMatTransposeSolve()`, `KSPMatSolve()`, `MATDENSE`, `KSPHPDDM`, `KSPRICHARDSON`, `PCBJACOBI`, `PCASM`
1385: @*/
1386: PetscErrorCode KSPMatSolveTranspose(KSP ksp, Mat B, Mat X)
1387: {
1388: PetscFunctionBegin;
1392: ksp->transpose.solve_requested = PETSC_TRUE;
1393: if (ksp->transpose.use_explicittranspose) PetscCall(KSPUseExplicitTranspose_Private(ksp));
1394: else ksp->transpose_solve = PETSC_TRUE;
1395: PetscCall(KSPMatSolve_Private(ksp, B, X));
1396: PetscFunctionReturn(PETSC_SUCCESS);
1397: }
1399: /*@
1400: KSPSetMatSolveBatchSize - Sets the maximum number of columns treated simultaneously in `KSPMatSolve()`.
1402: Logically Collective
1404: Input Parameters:
1405: + ksp - the `KSP` iterative solver
1406: - bs - batch size
1408: Options Database Key:
1409: . -ksp_matsolve_batch_size bs - the maximum number of columns treated simultaneously
1411: Level: advanced
1413: Note:
1414: `KSPMatSolve()` splits the columns of the block of right-hand sides into batches of at most `bs` columns and calls the `KSPType` implementation once per batch.
1415: The default is to treat the whole block at once. Using a larger batch size can improve the solver's efficiency but requires more memory.
1417: .seealso: [](ch_ksp), `KSPMatSolve()`, `KSPMatSolveTranspose()`, `KSPGetMatSolveBatchSize()`, `-mat_mumps_icntl_27`, `-matproduct_batch_size`
1418: @*/
1419: PetscErrorCode KSPSetMatSolveBatchSize(KSP ksp, PetscInt bs)
1420: {
1421: PetscFunctionBegin;
1424: ksp->nmax = bs;
1425: PetscFunctionReturn(PETSC_SUCCESS);
1426: }
1428: /*@
1429: KSPGetMatSolveBatchSize - Gets the maximum number of columns treated simultaneously in `KSPMatSolve()`.
1431: Input Parameter:
1432: . ksp - iterative solver context
1434: Output Parameter:
1435: . bs - batch size
1437: Level: advanced
1439: Note:
1440: `PETSC_DECIDE` means that `KSPMatSolve()` treats the whole block of right-hand sides at once.
1442: .seealso: [](ch_ksp), `KSPMatSolve()`, `KSPMatSolveTranspose()`, `KSPSetMatSolveBatchSize()`, `-mat_mumps_icntl_27`, `-matproduct_batch_size`
1443: @*/
1444: PetscErrorCode KSPGetMatSolveBatchSize(KSP ksp, PetscInt *bs)
1445: {
1446: PetscFunctionBegin;
1448: PetscAssertPointer(bs, 2);
1449: *bs = ksp->nmax;
1450: PetscFunctionReturn(PETSC_SUCCESS);
1451: }
1453: /*@
1454: KSPResetViewers - Resets all the viewers set from the options database during `KSPSetFromOptions()`
1456: Collective
1458: Input Parameter:
1459: . ksp - the `KSP` iterative solver context obtained from `KSPCreate()`
1461: Level: beginner
1463: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSPSetFromOptions()`, `KSP`
1464: @*/
1465: PetscErrorCode KSPResetViewers(KSP ksp)
1466: {
1467: PetscFunctionBegin;
1469: if (!ksp) PetscFunctionReturn(PETSC_SUCCESS);
1470: PetscCall(PetscViewerDestroy(&ksp->viewer));
1471: PetscCall(PetscViewerDestroy(&ksp->viewerPre));
1472: PetscCall(PetscViewerDestroy(&ksp->viewerRate));
1473: PetscCall(PetscViewerDestroy(&ksp->viewerMat));
1474: PetscCall(PetscViewerDestroy(&ksp->viewerPMat));
1475: PetscCall(PetscViewerDestroy(&ksp->viewerRhs));
1476: PetscCall(PetscViewerDestroy(&ksp->viewerSol));
1477: PetscCall(PetscViewerDestroy(&ksp->viewerMatExp));
1478: PetscCall(PetscViewerDestroy(&ksp->viewerEV));
1479: PetscCall(PetscViewerDestroy(&ksp->viewerSV));
1480: PetscCall(PetscViewerDestroy(&ksp->viewerEVExp));
1481: PetscCall(PetscViewerDestroy(&ksp->viewerFinalRes));
1482: PetscCall(PetscViewerDestroy(&ksp->viewerPOpExp));
1483: ksp->view = PETSC_FALSE;
1484: ksp->viewPre = PETSC_FALSE;
1485: ksp->viewMat = PETSC_FALSE;
1486: ksp->viewPMat = PETSC_FALSE;
1487: ksp->viewRhs = PETSC_FALSE;
1488: ksp->viewSol = PETSC_FALSE;
1489: ksp->viewMatExp = PETSC_FALSE;
1490: ksp->viewEV = PETSC_FALSE;
1491: ksp->viewSV = PETSC_FALSE;
1492: ksp->viewEVExp = PETSC_FALSE;
1493: ksp->viewFinalRes = PETSC_FALSE;
1494: ksp->viewPOpExp = PETSC_FALSE;
1495: PetscFunctionReturn(PETSC_SUCCESS);
1496: }
1498: /*@
1499: KSPReset - Removes any allocated `Vec` and `Mat` from the `KSP` data structures.
1501: Collective
1503: Input Parameter:
1504: . ksp - iterative solver obtained from `KSPCreate()`
1506: Level: intermediate
1508: Notes:
1509: Any options set in the `KSP`, including those set with `KSPSetFromOptions()` remain.
1511: Call `KSPReset()` only before you call `KSPSetOperators()` with a different sized matrix than the previous matrix used with the `KSP`.
1513: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSP`
1514: @*/
1515: PetscErrorCode KSPReset(KSP ksp)
1516: {
1517: PetscFunctionBegin;
1519: if (!ksp) PetscFunctionReturn(PETSC_SUCCESS);
1520: PetscTryTypeMethod(ksp, reset);
1521: if (ksp->pc) PetscCall(PCReset(ksp->pc));
1522: if (ksp->guess) {
1523: KSPGuess guess = ksp->guess;
1524: PetscTryTypeMethod(guess, reset);
1525: }
1526: PetscCall(VecDestroyVecs(ksp->nwork, &ksp->work));
1527: PetscCall(VecDestroy(&ksp->vec_rhs));
1528: PetscCall(VecDestroy(&ksp->vec_sol));
1529: PetscCall(KSPResetExplicitTranspose_Private(ksp));
1530: PetscCall(MatStateInvalidate(ksp->amatstate));
1532: ksp->mat_rhs = NULL;
1533: ksp->setupstage = KSP_SETUP_NEW;
1534: ksp->nmax = PETSC_DECIDE;
1535: PetscFunctionReturn(PETSC_SUCCESS);
1536: }
1538: /*@
1539: KSPDestroy - Destroys a `KSP` context.
1541: Collective
1543: Input Parameter:
1544: . ksp - iterative solver obtained from `KSPCreate()`
1546: Level: beginner
1548: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSP`
1549: @*/
1550: PetscErrorCode KSPDestroy(KSP *ksp)
1551: {
1552: PC pc;
1554: PetscFunctionBegin;
1555: if (!*ksp) PetscFunctionReturn(PETSC_SUCCESS);
1557: if (--((PetscObject)*ksp)->refct > 0) {
1558: *ksp = NULL;
1559: PetscFunctionReturn(PETSC_SUCCESS);
1560: }
1562: PetscCall(PetscObjectSAWsViewOff((PetscObject)*ksp));
1564: /*
1565: Avoid a cascading call to PCReset(ksp->pc) from the following call:
1566: PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1567: refcount (and may be shared, e.g., by other ksps).
1568: */
1569: pc = (*ksp)->pc;
1570: (*ksp)->pc = NULL;
1571: PetscCall(KSPReset(*ksp));
1572: PetscCall(KSPResetViewers(*ksp));
1573: (*ksp)->pc = pc;
1574: PetscTryTypeMethod(*ksp, destroy);
1576: PetscCall(KSPGuessDestroy(&(*ksp)->guess));
1577: PetscCall(DMDestroy(&(*ksp)->dm));
1578: PetscCall(PCDestroy(&(*ksp)->pc));
1579: PetscCall(PetscFree((*ksp)->res_hist_alloc));
1580: PetscCall(PetscFree((*ksp)->err_hist_alloc));
1581: PetscCall(PetscFree((*ksp)->orthogwork));
1582: if ((*ksp)->convergeddestroy) PetscCall((*(*ksp)->convergeddestroy)(&(*ksp)->cnvP));
1583: PetscCall(KSPMonitorCancel(*ksp));
1584: PetscCall(KSPConvergedReasonViewCancel(*ksp));
1585: PetscCall(PetscHeaderDestroy(ksp));
1586: PetscFunctionReturn(PETSC_SUCCESS);
1587: }
1589: /*@
1590: KSPSetPCSide - Sets the preconditioning side.
1592: Logically Collective
1594: Input Parameter:
1595: . ksp - iterative solver obtained from `KSPCreate()`
1597: Output Parameter:
1598: . side - the preconditioning side, where side is one of
1599: .vb
1600: PC_LEFT - left preconditioning (default)
1601: PC_RIGHT - right preconditioning
1602: PC_SYMMETRIC - symmetric preconditioning
1603: .ve
1605: Options Database Key:
1606: . -ksp_pc_side (right|left|symmetric) - `KSP` preconditioner side
1608: Level: intermediate
1610: Notes:
1611: Left preconditioning is used by default for most Krylov methods except `KSPFGMRES` which only supports right preconditioning.
1613: For methods changing the side of the preconditioner changes the norm type that is used, see `KSPSetNormType()`.
1615: Symmetric preconditioning is currently available only for the `KSPQCG` method. However, note that
1616: symmetric preconditioning can be emulated by using either right or left
1617: preconditioning, modifying the application of the matrix (with a custom `Mat` argument to `KSPSetOperators()`,
1618: and using a pre 'KSPSetPreSolve()` or post processing `KSPSetPostSolve()` step).
1620: Setting the `PCSide` often affects the default norm type. See `KSPSetNormType()` for details.
1622: .seealso: [](ch_ksp), `KSPGetPCSide()`, `KSPSetNormType()`, `KSPGetNormType()`, `KSP`, `KSPSetPreSolve()`, `KSPSetPostSolve()`
1623: @*/
1624: PetscErrorCode KSPSetPCSide(KSP ksp, PCSide side)
1625: {
1626: PetscFunctionBegin;
1629: ksp->pc_side = ksp->pc_side_set = side;
1630: PetscFunctionReturn(PETSC_SUCCESS);
1631: }
1633: /*@
1634: KSPGetPCSide - Gets the preconditioning side.
1636: Not Collective
1638: Input Parameter:
1639: . ksp - iterative solver obtained from `KSPCreate()`
1641: Output Parameter:
1642: . side - the preconditioning side, where side is one of
1643: .vb
1644: PC_LEFT - left preconditioning (default)
1645: PC_RIGHT - right preconditioning
1646: PC_SYMMETRIC - symmetric preconditioning
1647: .ve
1649: Level: intermediate
1651: .seealso: [](ch_ksp), `KSPSetPCSide()`, `KSP`
1652: @*/
1653: PetscErrorCode KSPGetPCSide(KSP ksp, PCSide *side)
1654: {
1655: PetscFunctionBegin;
1657: PetscAssertPointer(side, 2);
1658: PetscCall(KSPSetUpNorms_Private(ksp, PETSC_TRUE, &ksp->normtype, &ksp->pc_side));
1659: *side = ksp->pc_side;
1660: PetscFunctionReturn(PETSC_SUCCESS);
1661: }
1663: /*@
1664: KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1665: iteration tolerances used by the default `KSP` convergence tests.
1667: Not Collective
1669: Input Parameter:
1670: . ksp - the Krylov subspace context
1672: Output Parameters:
1673: + rtol - the relative convergence tolerance
1674: . abstol - the absolute convergence tolerance
1675: . dtol - the divergence tolerance
1676: - maxits - maximum number of iterations
1678: Level: intermediate
1680: Note:
1681: The user can specify `NULL` for any parameter that is not needed.
1683: .seealso: [](ch_ksp), `KSPSetTolerances()`, `KSP`, `KSPSetMinimumIterations()`, `KSPGetMinimumIterations()`
1684: @*/
1685: PetscErrorCode KSPGetTolerances(KSP ksp, PeOp PetscReal *rtol, PeOp PetscReal *abstol, PeOp PetscReal *dtol, PeOp PetscInt *maxits)
1686: {
1687: PetscFunctionBegin;
1689: if (abstol) *abstol = ksp->abstol;
1690: if (rtol) *rtol = ksp->rtol;
1691: if (dtol) *dtol = ksp->divtol;
1692: if (maxits) *maxits = ksp->max_it;
1693: PetscFunctionReturn(PETSC_SUCCESS);
1694: }
1696: /*@
1697: KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1698: iteration tolerances used by the default `KSP` convergence testers.
1700: Logically Collective
1702: Input Parameters:
1703: + ksp - the Krylov subspace context
1704: . rtol - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1705: . abstol - the absolute convergence tolerance absolute size of the (possibly preconditioned) residual norm
1706: . dtol - the divergence tolerance, amount (possibly preconditioned) residual norm can increase before `KSPConvergedDefault()` concludes that the method is diverging
1707: - maxits - maximum number of iterations to use
1709: Options Database Keys:
1710: + -ksp_atol abstol - Sets `abstol`
1711: . -ksp_rtol rtol - Sets `rtol`
1712: . -ksp_divtol dtol - Sets `dtol`
1713: - -ksp_max_it maxits - Sets `maxits`
1715: Level: intermediate
1717: Notes:
1718: The tolerances are with respect to a norm of the residual of the equation $ \| b - A x^n \|$, they do not directly use the error of the equation.
1719: The norm used depends on the `KSPNormType` that has been set with `KSPSetNormType()`, the default depends on the `KSPType` used.
1721: All parameters must be non-negative.
1723: Use `PETSC_CURRENT` to retain the current value of any of the parameters. The deprecated `PETSC_DEFAULT` also retains the current value (though the name is confusing).
1725: Use `PETSC_DETERMINE` to use the default value for the given `KSP`. The default value is the value when the object's type is set.
1727: For `dtol` and `maxits` use `PETSC_UNLIMITED` to indicate there is no upper bound on these values
1729: See `KSPConvergedDefault()` for details how these parameters are used in the default convergence test. See also `KSPSetConvergenceTest()`
1730: for setting user-defined stopping criteria.
1732: Fortran Note:
1733: Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`
1735: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetMinimumIterations()`
1736: @*/
1737: PetscErrorCode KSPSetTolerances(KSP ksp, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt maxits)
1738: {
1739: PetscFunctionBegin;
1746: if (rtol == (PetscReal)PETSC_DETERMINE) {
1747: ksp->rtol = ksp->default_rtol;
1748: } else if (rtol != (PetscReal)PETSC_CURRENT) {
1749: PetscCheck(rtol >= 0.0 && rtol < 1.0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative and less than 1.0", (double)rtol);
1750: ksp->rtol = rtol;
1751: }
1752: if (abstol == (PetscReal)PETSC_DETERMINE) {
1753: ksp->abstol = ksp->default_abstol;
1754: } else if (abstol != (PetscReal)PETSC_CURRENT) {
1755: PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
1756: ksp->abstol = abstol;
1757: }
1758: if (dtol == (PetscReal)PETSC_DETERMINE) {
1759: ksp->divtol = ksp->default_divtol;
1760: } else if (dtol == (PetscReal)PETSC_UNLIMITED) {
1761: ksp->divtol = PETSC_MAX_REAL;
1762: } else if (dtol != (PetscReal)PETSC_CURRENT) {
1763: PetscCheck(dtol >= 0.0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be larger than 1.0", (double)dtol);
1764: ksp->divtol = dtol;
1765: }
1766: if (maxits == PETSC_DETERMINE) {
1767: ksp->max_it = ksp->default_max_it;
1768: } else if (maxits == PETSC_UNLIMITED) {
1769: ksp->max_it = PETSC_INT_MAX;
1770: } else if (maxits != PETSC_CURRENT) {
1771: PetscCheck(maxits >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxits);
1772: ksp->max_it = maxits;
1773: }
1774: PetscFunctionReturn(PETSC_SUCCESS);
1775: }
1777: /*@
1778: KSPSetMinimumIterations - Sets the minimum number of iterations to use, regardless of the tolerances
1780: Logically Collective
1782: Input Parameters:
1783: + ksp - the Krylov subspace context
1784: - minit - minimum number of iterations to use
1786: Options Database Key:
1787: . -ksp_min_it minit - Sets `minit`
1789: Level: intermediate
1791: Notes:
1792: Use `KSPSetTolerances()` to set a variety of other tolerances
1794: See `KSPConvergedDefault()` for details on how these parameters are used in the default convergence test. See also `KSPSetConvergenceTest()`
1795: for setting user-defined stopping criteria.
1797: If the initial residual norm is small enough solvers may return immediately without computing any improvement to the solution. Using this routine
1798: prevents that which usually ensures the solution is changed (often minimally) from the previous solution. This option may be used with ODE integrators
1799: to ensure the integrator does not fall into a false steady-state solution of the ODE.
1801: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetTolerances()`, `KSPGetMinimumIterations()`
1802: @*/
1803: PetscErrorCode KSPSetMinimumIterations(KSP ksp, PetscInt minit)
1804: {
1805: PetscFunctionBegin;
1809: PetscCheck(minit >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Minimum number of iterations %" PetscInt_FMT " must be non-negative", minit);
1810: ksp->min_it = minit;
1811: PetscFunctionReturn(PETSC_SUCCESS);
1812: }
1814: /*@
1815: KSPGetMinimumIterations - Gets the minimum number of iterations to use, regardless of the tolerances, that was set with `KSPSetMinimumIterations()` or `-ksp_min_it`
1817: Not Collective
1819: Input Parameter:
1820: . ksp - the Krylov subspace context
1822: Output Parameter:
1823: . minit - minimum number of iterations to use
1825: Level: intermediate
1827: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetTolerances()`, `KSPSetMinimumIterations()`
1828: @*/
1829: PetscErrorCode KSPGetMinimumIterations(KSP ksp, PetscInt *minit)
1830: {
1831: PetscFunctionBegin;
1833: PetscAssertPointer(minit, 2);
1835: *minit = ksp->min_it;
1836: PetscFunctionReturn(PETSC_SUCCESS);
1837: }
1839: /*@
1840: KSPSetInitialGuessNonzero - Tells the iterative solver that the
1841: initial guess is nonzero; otherwise `KSP` assumes the initial guess
1842: is to be zero (and thus zeros it out before solving).
1844: Logically Collective
1846: Input Parameters:
1847: + ksp - iterative solver obtained from `KSPCreate()`
1848: - flg - ``PETSC_TRUE`` indicates the guess is non-zero, `PETSC_FALSE` indicates the guess is zero
1850: Options Database Key:
1851: . -ksp_initial_guess_nonzero (true|false) - use nonzero initial guess
1853: Level: beginner
1855: .seealso: [](ch_ksp), `KSPGetInitialGuessNonzero()`, `KSPGuessSetType()`, `KSPGuessType`, `KSP`
1856: @*/
1857: PetscErrorCode KSPSetInitialGuessNonzero(KSP ksp, PetscBool flg)
1858: {
1859: PetscFunctionBegin;
1862: ksp->guess_zero = (PetscBool)!flg;
1863: PetscFunctionReturn(PETSC_SUCCESS);
1864: }
1866: /*@
1867: KSPGetInitialGuessNonzero - Determines whether the `KSP` solver is using
1868: a zero initial guess.
1870: Not Collective
1872: Input Parameter:
1873: . ksp - iterative solver obtained from `KSPCreate()`
1875: Output Parameter:
1876: . flag - `PETSC_TRUE` if guess is nonzero, else `PETSC_FALSE`
1878: Level: intermediate
1880: .seealso: [](ch_ksp), `KSPSetInitialGuessNonzero()`, `KSP`
1881: @*/
1882: PetscErrorCode KSPGetInitialGuessNonzero(KSP ksp, PetscBool *flag)
1883: {
1884: PetscFunctionBegin;
1886: PetscAssertPointer(flag, 2);
1887: if (ksp->guess_zero) *flag = PETSC_FALSE;
1888: else *flag = PETSC_TRUE;
1889: PetscFunctionReturn(PETSC_SUCCESS);
1890: }
1892: /*@
1893: KSPSetErrorIfNotConverged - Causes `KSPSolve()` to generate an error if the solver has not converged as soon as the error is detected.
1895: Logically Collective
1897: Input Parameters:
1898: + ksp - iterative solver obtained from `KSPCreate()`
1899: - flg - `PETSC_TRUE` indicates you want the error generated
1901: Options Database Key:
1902: . -ksp_error_if_not_converged (true|false) - generate an error and stop the program
1904: Level: intermediate
1906: Notes:
1907: Normally PETSc continues if a linear solver fails to converge, you can call `KSPGetConvergedReason()` after a `KSPSolve()`
1908: to determine if it has converged. This functionality is mostly helpful while running in a debugger (`-start_in_debugger`) to determine exactly where
1909: the failure occurs and why.
1911: A `KSP_DIVERGED_ITS` will not generate an error in a `KSPSolve()` inside a nested linear solver
1913: .seealso: [](ch_ksp), `KSPGetErrorIfNotConverged()`, `KSP`
1914: @*/
1915: PetscErrorCode KSPSetErrorIfNotConverged(KSP ksp, PetscBool flg)
1916: {
1917: PC pc;
1919: PetscFunctionBegin;
1922: ksp->errorifnotconverged = flg;
1923: PetscCall(KSPGetPC(ksp, &pc));
1924: PetscCall(PCSetErrorIfFailure(pc, flg));
1925: PetscFunctionReturn(PETSC_SUCCESS);
1926: }
1928: /*@
1929: KSPGetErrorIfNotConverged - Will `KSPSolve()` generate an error if the solver does not converge?
1931: Not Collective
1933: Input Parameter:
1934: . ksp - iterative solver obtained from KSPCreate()
1936: Output Parameter:
1937: . flag - `PETSC_TRUE` if it will generate an error, else `PETSC_FALSE`
1939: Level: intermediate
1941: .seealso: [](ch_ksp), `KSPSetErrorIfNotConverged()`, `KSP`
1942: @*/
1943: PetscErrorCode KSPGetErrorIfNotConverged(KSP ksp, PetscBool *flag)
1944: {
1945: PetscFunctionBegin;
1947: PetscAssertPointer(flag, 2);
1948: *flag = ksp->errorifnotconverged;
1949: PetscFunctionReturn(PETSC_SUCCESS);
1950: }
1952: /*@
1953: KSPSetInitialGuessKnoll - Tells the iterative solver to use `PCApply()` on the right hand side vector to compute the initial guess (The Knoll trick)
1955: Logically Collective
1957: Input Parameters:
1958: + ksp - iterative solver obtained from `KSPCreate()`
1959: - flg - `PETSC_TRUE` or `PETSC_FALSE`
1961: Level: advanced
1963: Developer Note:
1964: The Knoll trick is not currently implemented using the `KSPGuess` class which provides a variety of ways of computing
1965: an initial guess based on previous solves.
1967: .seealso: [](ch_ksp), `KSPGetInitialGuessKnoll()`, `KSPGuess`, `KSPSetInitialGuessNonzero()`, `KSPGetInitialGuessNonzero()`, `KSP`
1968: @*/
1969: PetscErrorCode KSPSetInitialGuessKnoll(KSP ksp, PetscBool flg)
1970: {
1971: PetscFunctionBegin;
1974: ksp->guess_knoll = flg;
1975: PetscFunctionReturn(PETSC_SUCCESS);
1976: }
1978: /*@
1979: KSPGetInitialGuessKnoll - Determines whether the `KSP` solver is using the Knoll trick (using PCApply(pc,b,...) to compute
1980: the initial guess
1982: Not Collective
1984: Input Parameter:
1985: . ksp - iterative solver obtained from `KSPCreate()`
1987: Output Parameter:
1988: . flag - `PETSC_TRUE` if using Knoll trick, else `PETSC_FALSE`
1990: Level: advanced
1992: .seealso: [](ch_ksp), `KSPSetInitialGuessKnoll()`, `KSPSetInitialGuessNonzero()`, `KSPGetInitialGuessNonzero()`, `KSP`
1993: @*/
1994: PetscErrorCode KSPGetInitialGuessKnoll(KSP ksp, PetscBool *flag)
1995: {
1996: PetscFunctionBegin;
1998: PetscAssertPointer(flag, 2);
1999: *flag = ksp->guess_knoll;
2000: PetscFunctionReturn(PETSC_SUCCESS);
2001: }
2003: /*@
2004: KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
2005: values will be calculated via a Lanczos or Arnoldi process as the linear
2006: system is solved.
2008: Not Collective
2010: Input Parameter:
2011: . ksp - iterative solver obtained from `KSPCreate()`
2013: Output Parameter:
2014: . flg - `PETSC_TRUE` or `PETSC_FALSE`
2016: Options Database Key:
2017: . -ksp_monitor_singular_value - Activates `KSPSetComputeSingularValues()`
2019: Level: advanced
2021: Notes:
2022: This option is not valid for `KSPType`.
2024: Many users may just want to use the monitoring routine
2025: `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
2026: to print the singular values at each iteration of the linear solve.
2028: .seealso: [](ch_ksp), `KSPComputeExtremeSingularValues()`, `KSPMonitorSingularValue()`, `KSP`
2029: @*/
2030: PetscErrorCode KSPGetComputeSingularValues(KSP ksp, PetscBool *flg)
2031: {
2032: PetscFunctionBegin;
2034: PetscAssertPointer(flg, 2);
2035: *flg = ksp->calc_sings;
2036: PetscFunctionReturn(PETSC_SUCCESS);
2037: }
2039: /*@
2040: KSPSetComputeSingularValues - Sets a flag so that the extreme singular
2041: values will be calculated via a Lanczos or Arnoldi process as the linear
2042: system is solved.
2044: Logically Collective
2046: Input Parameters:
2047: + ksp - iterative solver obtained from `KSPCreate()`
2048: - flg - `PETSC_TRUE` or `PETSC_FALSE`
2050: Options Database Key:
2051: . -ksp_monitor_singular_value - Activates `KSPSetComputeSingularValues()`
2053: Level: advanced
2055: Notes:
2056: This option is not valid for all iterative methods.
2058: Many users may just want to use the monitoring routine
2059: `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
2060: to print the singular values at each iteration of the linear solve.
2062: Consider using the excellent package SLEPc for accurate efficient computations of singular or eigenvalues.
2064: .seealso: [](ch_ksp), `KSPComputeExtremeSingularValues()`, `KSPMonitorSingularValue()`, `KSP`, `KSPSetComputeRitz()`
2065: @*/
2066: PetscErrorCode KSPSetComputeSingularValues(KSP ksp, PetscBool flg)
2067: {
2068: PetscFunctionBegin;
2071: ksp->calc_sings = flg;
2072: PetscFunctionReturn(PETSC_SUCCESS);
2073: }
2075: /*@
2076: KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
2077: values will be calculated via a Lanczos or Arnoldi process as the linear
2078: system is solved.
2080: Not Collective
2082: Input Parameter:
2083: . ksp - iterative solver obtained from `KSPCreate()`
2085: Output Parameter:
2086: . flg - `PETSC_TRUE` or `PETSC_FALSE`
2088: Level: advanced
2090: Note:
2091: Currently this option is not valid for all iterative methods.
2093: .seealso: [](ch_ksp), `KSPComputeEigenvalues()`, `KSPComputeEigenvaluesExplicitly()`, `KSP`, `KSPSetComputeRitz()`
2094: @*/
2095: PetscErrorCode KSPGetComputeEigenvalues(KSP ksp, PetscBool *flg)
2096: {
2097: PetscFunctionBegin;
2099: PetscAssertPointer(flg, 2);
2100: *flg = ksp->calc_sings;
2101: PetscFunctionReturn(PETSC_SUCCESS);
2102: }
2104: /*@
2105: KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
2106: values will be calculated via a Lanczos or Arnoldi process as the linear
2107: system is solved.
2109: Logically Collective
2111: Input Parameters:
2112: + ksp - iterative solver obtained from `KSPCreate()`
2113: - flg - `PETSC_TRUE` or `PETSC_FALSE`
2115: Level: advanced
2117: Note:
2118: Currently this option is not valid for all iterative methods.
2120: Consider using the excellent package SLEPc for accurate efficient computations of singular or eigenvalues.
2122: .seealso: [](ch_ksp), `KSPComputeEigenvalues()`, `KSPComputeEigenvaluesExplicitly()`, `KSP`, `KSPSetComputeRitz()`
2123: @*/
2124: PetscErrorCode KSPSetComputeEigenvalues(KSP ksp, PetscBool flg)
2125: {
2126: PetscFunctionBegin;
2129: ksp->calc_sings = flg;
2130: PetscFunctionReturn(PETSC_SUCCESS);
2131: }
2133: /*@
2134: KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
2135: will be calculated via a Lanczos or Arnoldi process as the linear
2136: system is solved.
2138: Logically Collective
2140: Input Parameters:
2141: + ksp - iterative solver obtained from `KSPCreate()`
2142: - flg - `PETSC_TRUE` or `PETSC_FALSE`
2144: Level: advanced
2146: Note:
2147: Currently this option is only valid for the `KSPGMRES` method.
2149: .seealso: [](ch_ksp), `KSPComputeRitz()`, `KSP`, `KSPComputeEigenvalues()`, `KSPComputeExtremeSingularValues()`
2150: @*/
2151: PetscErrorCode KSPSetComputeRitz(KSP ksp, PetscBool flg)
2152: {
2153: PetscFunctionBegin;
2156: ksp->calc_ritz = flg;
2157: PetscFunctionReturn(PETSC_SUCCESS);
2158: }
2160: /*@
2161: KSPGetRhs - Gets the right-hand-side vector for the linear system to
2162: be solved.
2164: Not Collective
2166: Input Parameter:
2167: . ksp - iterative solver obtained from `KSPCreate()`
2169: Output Parameter:
2170: . r - right-hand-side vector
2172: Level: developer
2174: .seealso: [](ch_ksp), `KSPGetSolution()`, `KSPSolve()`, `KSP`
2175: @*/
2176: PetscErrorCode KSPGetRhs(KSP ksp, Vec *r)
2177: {
2178: PetscFunctionBegin;
2180: PetscAssertPointer(r, 2);
2181: *r = ksp->vec_rhs;
2182: PetscFunctionReturn(PETSC_SUCCESS);
2183: }
2185: /*@
2186: KSPGetSolution - Gets the location of the solution for the
2187: linear system to be solved.
2189: Not Collective
2191: Input Parameter:
2192: . ksp - iterative solver obtained from `KSPCreate()`
2194: Output Parameter:
2195: . v - solution vector
2197: Level: developer
2199: Note:
2200: If this is called during a `KSPSolve()` the vector's values may not represent the solution
2201: to the linear system.
2203: .seealso: [](ch_ksp), `KSPGetRhs()`, `KSPBuildSolution()`, `KSPSolve()`, `KSP`
2204: @*/
2205: PetscErrorCode KSPGetSolution(KSP ksp, Vec *v)
2206: {
2207: PetscFunctionBegin;
2209: PetscAssertPointer(v, 2);
2210: *v = ksp->vec_sol;
2211: PetscFunctionReturn(PETSC_SUCCESS);
2212: }
2214: /*@
2215: KSPSetPC - Sets the preconditioner to be used to calculate the
2216: application of the preconditioner on a vector into a `KSP`.
2218: Collective
2220: Input Parameters:
2221: + ksp - the `KSP` iterative solver obtained from `KSPCreate()`
2222: - pc - the preconditioner object (if `NULL` it returns the `PC` currently held by the `KSP`)
2224: Level: developer
2226: Note:
2227: This routine is almost never used since `KSP` creates its own `PC` when needed.
2228: Use `KSPGetPC()` to retrieve the preconditioner context instead of creating a new one.
2230: .seealso: [](ch_ksp), `KSPGetPC()`, `KSP`
2231: @*/
2232: PetscErrorCode KSPSetPC(KSP ksp, PC pc)
2233: {
2234: PetscFunctionBegin;
2236: if (pc) {
2238: PetscCheckSameComm(ksp, 1, pc, 2);
2239: }
2240: if (ksp->pc != pc && ksp->setupstage) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2241: PetscCall(PetscObjectReference((PetscObject)pc));
2242: PetscCall(PCDestroy(&ksp->pc));
2243: ksp->pc = pc;
2244: PetscFunctionReturn(PETSC_SUCCESS);
2245: }
2247: PETSC_INTERN PetscErrorCode PCCreate_MPI(PC);
2249: // PetscClangLinter pragma disable: -fdoc-internal-linkage
2250: /*@
2251: KSPCheckPCMPI - Checks if `-mpi_linear_solver_server` is active and the `PC` should be changed to `PCMPI`
2253: Collective, No Fortran Support
2255: Input Parameter:
2256: . ksp - iterative solver obtained from `KSPCreate()`
2258: Level: developer
2260: .seealso: [](ch_ksp), `KSPSetPC()`, `KSP`, `PCMPIServerBegin()`, `PCMPIServerEnd()`
2261: @*/
2262: PETSC_INTERN PetscErrorCode KSPCheckPCMPI(KSP ksp)
2263: {
2264: PetscBool isPCMPI;
2266: PetscFunctionBegin;
2268: PetscCall(PetscObjectTypeCompare((PetscObject)ksp->pc, PCMPI, &isPCMPI));
2269: if (PCMPIServerActive && ksp->nestlevel == 0 && !isPCMPI) {
2270: const char *prefix;
2271: char *found = NULL;
2273: PetscCall(KSPGetOptionsPrefix(ksp, &prefix));
2274: if (prefix) PetscCall(PetscStrstr(prefix, "mpi_linear_solver_server_", &found));
2275: if (!found) PetscCall(KSPAppendOptionsPrefix(ksp, "mpi_linear_solver_server_"));
2276: PetscCall(PetscInfo(NULL, "In MPI Linear Solver Server and detected (root) PC that must be changed to PCMPI\n"));
2277: PetscCall(PCSetType(ksp->pc, PCMPI));
2278: }
2279: PetscFunctionReturn(PETSC_SUCCESS);
2280: }
2282: /*@
2283: KSPGetPC - Returns a pointer to the preconditioner context with the `KSP`
2285: Not Collective
2287: Input Parameter:
2288: . ksp - iterative solver obtained from `KSPCreate()`
2290: Output Parameter:
2291: . pc - preconditioner context
2293: Level: beginner
2295: Note:
2296: The `PC` is created if it does not already exist.
2298: Developer Note:
2299: Calls `KSPCheckPCMPI()` to check if the `KSP` is effected by `-mpi_linear_solver_server`
2301: .seealso: [](ch_ksp), `KSPSetPC()`, `KSP`, `PC`
2302: @*/
2303: PetscErrorCode KSPGetPC(KSP ksp, PC *pc)
2304: {
2305: PetscFunctionBegin;
2307: PetscAssertPointer(pc, 2);
2308: if (!ksp->pc) {
2309: PetscCall(PCCreate(PetscObjectComm((PetscObject)ksp), &ksp->pc));
2310: PetscCall(PetscObjectIncrementTabLevel((PetscObject)ksp->pc, (PetscObject)ksp, 0));
2311: PetscCall(PetscObjectSetOptions((PetscObject)ksp->pc, ((PetscObject)ksp)->options));
2312: PetscCall(PCSetKSPNestLevel(ksp->pc, ksp->nestlevel));
2313: PetscCall(PCSetErrorIfFailure(ksp->pc, ksp->errorifnotconverged));
2314: if (ksp->dm) PetscCall(PCSetDM(ksp->pc, ksp->dm));
2315: }
2316: PetscCall(KSPCheckPCMPI(ksp));
2317: *pc = ksp->pc;
2318: PetscFunctionReturn(PETSC_SUCCESS);
2319: }
2321: /*@
2322: KSPMonitor - runs the user provided monitor routines, if they exist
2324: Collective
2326: Input Parameters:
2327: + ksp - iterative solver obtained from `KSPCreate()`
2328: . it - iteration number
2329: - rnorm - relative norm of the residual
2331: Level: developer
2333: Notes:
2334: This routine is called by the `KSP` implementations.
2335: It does not typically need to be called by the user.
2337: For Krylov methods that do not keep a running value of the current solution (such as `KSPGMRES`) this
2338: cannot be called after the `KSPConvergedReason` has been set but before the final solution has been computed.
2340: .seealso: [](ch_ksp), `KSPMonitorSet()`
2341: @*/
2342: PetscErrorCode KSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm)
2343: {
2344: PetscInt i, n = ksp->numbermonitors;
2346: PetscFunctionBegin;
2347: for (i = 0; i < n; i++) PetscCall((*ksp->monitor[i])(ksp, it, rnorm, ksp->monitorcontext[i]));
2348: PetscFunctionReturn(PETSC_SUCCESS);
2349: }
2351: /*@
2352: KSPMonitorSet - Sets an ADDITIONAL function to be called at every iteration to monitor, i.e. display in some way, perhaps by printing in the terminal,
2353: the residual norm computed in a `KSPSolve()`
2355: Logically Collective
2357: Input Parameters:
2358: + ksp - iterative solver obtained from `KSPCreate()`
2359: . monitor - pointer to function (if this is `NULL`, it turns off monitoring, see `KSPMonitorFn`
2360: . ctx - [optional] context for private data for the monitor routine (use `NULL` if no context is needed)
2361: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
2363: Options Database Keys:
2364: + -ksp_monitor - sets `KSPMonitorResidual()`
2365: . -ksp_monitor hdf5:filename - sets `KSPMonitorResidualView()` and saves residual
2366: . -ksp_monitor draw - sets `KSPMonitorResidualView()` and plots residual
2367: . -ksp_monitor draw::draw_lg - sets `KSPMonitorResidualDrawLG()` and plots residual
2368: . -ksp_monitor_pause_final - Pauses any graphics when the solve finishes (only works for internal monitors)
2369: . -ksp_monitor_true_residual - sets `KSPMonitorTrueResidual()`
2370: . -ksp_monitor_true_residual draw::draw_lg - sets `KSPMonitorTrueResidualDrawLG()` and plots residual
2371: . -ksp_monitor_max - sets `KSPMonitorTrueResidualMax()`
2372: . -ksp_monitor_singular_value - sets `KSPMonitorSingularValue()`
2373: - -ksp_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `KSPMonitorSet()`, but
2374: does not cancel those set via the options database.
2376: Level: beginner
2378: Notes:
2379: The options database option `-ksp_monitor` and related options are the easiest way to turn on `KSP` iteration monitoring
2381: `KSPMonitorRegister()` provides a way to associate an options database key with `KSP` monitor function.
2383: The default is to do no monitoring. To print the residual, or preconditioned
2384: residual if `KSPSetNormType`(ksp,`KSP_NORM_PRECONDITIONED`) was called, use
2385: `KSPMonitorResidual()` as the monitoring routine, with a `PETSCVIEWERASCII` as the
2386: context.
2388: Several different monitoring routines may be set by calling
2389: `KSPMonitorSet()` multiple times; they will be called in the
2390: order in which they were set.
2392: Fortran Note:
2393: Only a single monitor function can be set for each `KSP` object
2395: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSPMonitorRegister()`, `KSPMonitorCancel()`, `KSP`, `PetscCtxDestroyFn`
2396: @*/
2397: PetscErrorCode KSPMonitorSet(KSP ksp, KSPMonitorFn *monitor, PetscCtx ctx, PetscCtxDestroyFn *monitordestroy)
2398: {
2399: PetscFunctionBegin;
2401: for (PetscInt i = 0; i < ksp->numbermonitors; i++) {
2402: PetscBool identical;
2404: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)monitor, ctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)ksp->monitor[i], ksp->monitorcontext[i], ksp->monitordestroy[i], &identical));
2405: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
2406: }
2407: PetscCheck(ksp->numbermonitors < MAXKSPMONITORS, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Too many KSP monitors set");
2408: ksp->monitor[ksp->numbermonitors] = monitor;
2409: ksp->monitordestroy[ksp->numbermonitors] = monitordestroy;
2410: ksp->monitorcontext[ksp->numbermonitors++] = ctx;
2411: PetscFunctionReturn(PETSC_SUCCESS);
2412: }
2414: /*@
2415: KSPMonitorCancel - Clears all monitors for a `KSP` object.
2417: Logically Collective
2419: Input Parameter:
2420: . ksp - iterative solver obtained from `KSPCreate()`
2422: Options Database Key:
2423: . -ksp_monitor_cancel - Cancels all monitors that have been hardwired into a code by calls to `KSPMonitorSet()`, but does not cancel those set via the options database.
2425: Level: intermediate
2427: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSPMonitorSet()`, `KSP`
2428: @*/
2429: PetscErrorCode KSPMonitorCancel(KSP ksp)
2430: {
2431: PetscFunctionBegin;
2433: for (PetscInt i = 0; i < ksp->numbermonitors; i++) {
2434: if (ksp->monitordestroy[i]) PetscCall((*ksp->monitordestroy[i])(&ksp->monitorcontext[i]));
2435: }
2436: ksp->numbermonitors = 0;
2437: PetscFunctionReturn(PETSC_SUCCESS);
2438: }
2440: /*@
2441: KSPGetMonitorContext - Gets the monitoring context, as set by `KSPMonitorSet()` for the FIRST monitor only.
2443: Not Collective
2445: Input Parameter:
2446: . ksp - iterative solver obtained from `KSPCreate()`
2448: Output Parameter:
2449: . ctx - monitoring context
2451: Level: intermediate
2453: Fortran Notes:
2454: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
2455: .vb
2456: type(tUsertype), pointer :: ctx
2457: .ve
2459: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSP`
2460: @*/
2461: PetscErrorCode KSPGetMonitorContext(KSP ksp, PetscCtxRt ctx)
2462: {
2463: PetscFunctionBegin;
2465: *(void **)ctx = ksp->monitorcontext[0];
2466: PetscFunctionReturn(PETSC_SUCCESS);
2467: }
2469: /*@
2470: KSPSetResidualHistory - Sets the array used to hold the residual history.
2471: If set, this array will contain the residual norms computed at each
2472: iteration of the solver.
2474: Not Collective
2476: Input Parameters:
2477: + ksp - iterative solver obtained from `KSPCreate()`
2478: . a - array to hold history
2479: . na - size of `a`
2480: - reset - `PETSC_TRUE` indicates the history counter is reset to zero
2481: for each new linear solve
2483: Level: advanced
2485: Notes:
2486: If provided, `a` is NOT freed by PETSc so the user needs to keep track of it and destroy once the `KSP` object is destroyed.
2487: If `a` is `NULL` then space is allocated for the history. If `na` is `PETSC_DECIDE` or (deprecated) `PETSC_DEFAULT` then a
2488: default array of length 10,000 is allocated.
2490: If the array is not long enough then once the iterations is longer than the array length `KSPSolve()` stops recording the history
2492: .seealso: [](ch_ksp), `KSPGetResidualHistory()`, `KSP`
2493: @*/
2494: PetscErrorCode KSPSetResidualHistory(KSP ksp, PetscReal a[], PetscCount na, PetscBool reset)
2495: {
2496: PetscFunctionBegin;
2499: PetscCall(PetscFree(ksp->res_hist_alloc));
2500: if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2501: ksp->res_hist = a;
2502: ksp->res_hist_max = na;
2503: } else {
2504: if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = (size_t)na;
2505: else ksp->res_hist_max = 10000; /* like default ksp->max_it */
2506: PetscCall(PetscCalloc1(ksp->res_hist_max, &ksp->res_hist_alloc));
2508: ksp->res_hist = ksp->res_hist_alloc;
2509: }
2510: ksp->res_hist_len = 0;
2511: ksp->res_hist_reset = reset;
2512: PetscFunctionReturn(PETSC_SUCCESS);
2513: }
2515: /*@
2516: KSPGetResidualHistory - Gets the array used to hold the residual history and the number of residuals it contains.
2518: Not Collective
2520: Input Parameter:
2521: . ksp - iterative solver obtained from `KSPCreate()`
2523: Output Parameters:
2524: + a - pointer to array to hold history (or `NULL`)
2525: - na - number of used entries in a (or `NULL`). Note this has different meanings depending on the `reset` argument to `KSPSetResidualHistory()`
2527: Level: advanced
2529: Note:
2530: This array is borrowed and should not be freed by the caller.
2532: Can only be called after a `KSPSetResidualHistory()` otherwise `a` and `na` are set to `NULL` and zero
2534: When `reset` was `PETSC_TRUE` since a residual is computed before the first iteration, the value of `na` is generally one more than the value
2535: returned with `KSPGetIterationNumber()`.
2537: Some Krylov methods may not compute the final residual norm when convergence is declared because the maximum number of iterations allowed has been reached.
2538: In this situation, when `reset` was `PETSC_TRUE`, `na` will then equal the number of iterations reported with `KSPGetIterationNumber()`
2540: Some Krylov methods (such as `KSPSTCG`), under certain circumstances, do not compute the final residual norm. In this situation, when `reset` was `PETSC_TRUE`,
2541: `na` will then equal the number of iterations reported with `KSPGetIterationNumber()`
2543: `KSPBCGSL` does not record the residual norms for the "subiterations" hence the results from `KSPGetResidualHistory()` and `KSPGetIterationNumber()` will be different
2545: Fortran Note:
2546: Call `KSPRestoreResidualHistory()` when access to the history is no longer needed.
2548: .seealso: [](ch_ksp), `KSPSetResidualHistory()`, `KSP`, `KSPGetIterationNumber()`, `KSPSTCG`, `KSPBCGSL`
2549: @*/
2550: PetscErrorCode KSPGetResidualHistory(KSP ksp, const PetscReal *a[], PetscInt *na)
2551: {
2552: PetscFunctionBegin;
2554: if (a) *a = ksp->res_hist;
2555: if (na) PetscCall(PetscIntCast(ksp->res_hist_len, na));
2556: PetscFunctionReturn(PETSC_SUCCESS);
2557: }
2559: /*@
2560: KSPSetErrorHistory - Sets the array used to hold the error history. If set, this array will contain the error norms computed at each iteration of the solver.
2562: Not Collective
2564: Input Parameters:
2565: + ksp - iterative solver obtained from `KSPCreate()`
2566: . a - array to hold history
2567: . na - size of `a`
2568: - reset - `PETSC_TRUE` indicates the history counter is reset to zero for each new linear solve
2570: Level: advanced
2572: Notes:
2573: If provided, `a` is NOT freed by PETSc so the user needs to keep track of it and destroy once the `KSP` object is destroyed.
2574: If `a` is `NULL` then space is allocated for the history. If `na` is `PETSC_DECIDE` or (deprecated) `PETSC_DEFAULT` then a default array of length 1,0000 is allocated.
2576: If the array is not long enough then once the iterations is longer than the array length `KSPSolve()` stops recording the history
2578: .seealso: [](ch_ksp), `KSPGetErrorHistory()`, `KSPSetResidualHistory()`, `KSP`
2579: @*/
2580: PetscErrorCode KSPSetErrorHistory(KSP ksp, PetscReal a[], PetscCount na, PetscBool reset)
2581: {
2582: PetscFunctionBegin;
2585: PetscCall(PetscFree(ksp->err_hist_alloc));
2586: if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2587: ksp->err_hist = a;
2588: ksp->err_hist_max = na;
2589: } else {
2590: if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->err_hist_max = (size_t)na;
2591: else ksp->err_hist_max = 10000; /* like default ksp->max_it */
2592: PetscCall(PetscCalloc1(ksp->err_hist_max, &ksp->err_hist_alloc));
2593: ksp->err_hist = ksp->err_hist_alloc;
2594: }
2595: ksp->err_hist_len = 0;
2596: ksp->err_hist_reset = reset;
2597: PetscFunctionReturn(PETSC_SUCCESS);
2598: }
2600: /*@
2601: KSPGetErrorHistory - Gets the array used to hold the error history and the number of residuals it contains.
2603: Not Collective
2605: Input Parameter:
2606: . ksp - iterative solver obtained from `KSPCreate()`
2608: Output Parameters:
2609: + a - pointer to array to hold history (or `NULL`)
2610: - na - number of used entries in a (or `NULL`)
2612: Level: advanced
2614: Note:
2615: This array is borrowed and should not be freed by the caller.
2616: Can only be called after a `KSPSetErrorHistory()` otherwise `a` and `na` are set to `NULL` and zero
2618: Fortran Note:
2619: .vb
2620: PetscReal, pointer :: a(:)
2621: .ve
2623: .seealso: [](ch_ksp), `KSPSetErrorHistory()`, `KSPGetResidualHistory()`, `KSP`
2624: @*/
2625: PetscErrorCode KSPGetErrorHistory(KSP ksp, const PetscReal *a[], PetscInt *na)
2626: {
2627: PetscFunctionBegin;
2629: if (a) *a = ksp->err_hist;
2630: if (na) PetscCall(PetscIntCast(ksp->err_hist_len, na));
2631: PetscFunctionReturn(PETSC_SUCCESS);
2632: }
2634: /*@
2635: KSPComputeConvergenceRate - Compute the convergence rate for the iteration <https:/en.wikipedia.org/wiki/Coefficient_of_determination>
2637: Not Collective
2639: Input Parameter:
2640: . ksp - The `KSP`
2642: Output Parameters:
2643: + cr - The residual contraction rate
2644: . rRsq - The coefficient of determination, $R^2$, indicating the linearity of the data
2645: . ce - The error contraction rate
2646: - eRsq - The coefficient of determination, $R^2$, indicating the linearity of the data
2648: Level: advanced
2650: Note:
2651: Suppose that the residual is reduced linearly, $r_k = c^k r_0$, which means $log r_k = log r_0 + k log c$. After linear regression,
2652: the slope is $\log c$. The coefficient of determination is given by $1 - \frac{\sum_i (y_i - f(x_i))^2}{\sum_i (y_i - \bar y)}$,
2654: .seealso: [](ch_ksp), `KSP`, `KSPConvergedRateView()`
2655: @*/
2656: PetscErrorCode KSPComputeConvergenceRate(KSP ksp, PetscReal *cr, PetscReal *rRsq, PetscReal *ce, PetscReal *eRsq)
2657: {
2658: PetscReal const *hist;
2659: PetscReal *x, *y, slope, intercept, mean = 0.0, var = 0.0, res = 0.0;
2660: PetscInt n;
2662: PetscFunctionBegin;
2663: if (cr || rRsq) {
2664: PetscCall(KSPGetResidualHistory(ksp, &hist, &n));
2665: if (!n) {
2666: if (cr) *cr = 0.0;
2667: if (rRsq) *rRsq = -1.0;
2668: } else {
2669: PetscCall(PetscMalloc2(n, &x, n, &y));
2670: for (PetscInt k = 0; k < n; ++k) {
2671: x[k] = k;
2672: y[k] = PetscLogReal(hist[k]);
2673: mean += y[k];
2674: }
2675: mean /= n;
2676: PetscCall(PetscLinearRegression(n, x, y, &slope, &intercept));
2677: for (PetscInt k = 0; k < n; ++k) {
2678: res += PetscSqr(y[k] - (slope * x[k] + intercept));
2679: var += PetscSqr(y[k] - mean);
2680: }
2681: PetscCall(PetscFree2(x, y));
2682: if (cr) *cr = PetscExpReal(slope);
2683: if (rRsq) *rRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2684: }
2685: }
2686: if (ce || eRsq) {
2687: PetscCall(KSPGetErrorHistory(ksp, &hist, &n));
2688: if (!n) {
2689: if (ce) *ce = 0.0;
2690: if (eRsq) *eRsq = -1.0;
2691: } else {
2692: PetscCall(PetscMalloc2(n, &x, n, &y));
2693: for (PetscInt k = 0; k < n; ++k) {
2694: x[k] = k;
2695: y[k] = PetscLogReal(hist[k]);
2696: mean += y[k];
2697: }
2698: mean /= n;
2699: PetscCall(PetscLinearRegression(n, x, y, &slope, &intercept));
2700: for (PetscInt k = 0; k < n; ++k) {
2701: res += PetscSqr(y[k] - (slope * x[k] + intercept));
2702: var += PetscSqr(y[k] - mean);
2703: }
2704: PetscCall(PetscFree2(x, y));
2705: if (ce) *ce = PetscExpReal(slope);
2706: if (eRsq) *eRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2707: }
2708: }
2709: PetscFunctionReturn(PETSC_SUCCESS);
2710: }
2712: /*@
2713: KSPSetConvergenceTest - Sets the function to be used to determine convergence of `KSPSolve()`
2715: Logically Collective
2717: Input Parameters:
2718: + ksp - iterative solver obtained from `KSPCreate()`
2719: . converge - pointer to the function, see `KSPConvergenceTestFn`
2720: . ctx - context for private data for the convergence routine (may be `NULL`)
2721: - destroy - a routine for destroying the context (may be `NULL`)
2723: Level: advanced
2725: Notes:
2726: Must be called after the `KSP` type has been set so put this after
2727: a call to `KSPSetType()`, or `KSPSetFromOptions()`.
2729: The default convergence test, `KSPConvergedDefault()`, aborts if the
2730: residual grows to more than 10000 times the initial residual.
2732: The default is a combination of relative and absolute tolerances.
2733: The residual value that is tested may be an approximation; routines
2734: that need exact values should compute them.
2736: In the default PETSc convergence test, the precise values of reason
2737: are macros such as `KSP_CONVERGED_RTOL`, which are defined in petscksp.h.
2739: .seealso: [](ch_ksp), `KSP`, `KSPConvergenceTestFn`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPGetConvergenceTest()`, `KSPGetAndClearConvergenceTest()`
2740: @*/
2741: PetscErrorCode KSPSetConvergenceTest(KSP ksp, KSPConvergenceTestFn *converge, PetscCtx ctx, PetscCtxDestroyFn *destroy)
2742: {
2743: PetscFunctionBegin;
2745: if (ksp->convergeddestroy) PetscCall((*ksp->convergeddestroy)(&ksp->cnvP));
2746: ksp->converged = converge;
2747: ksp->convergeddestroy = destroy;
2748: ksp->cnvP = ctx;
2749: PetscFunctionReturn(PETSC_SUCCESS);
2750: }
2752: /*@
2753: KSPGetConvergenceTest - Gets the function to be used to determine convergence.
2755: Logically Collective
2757: Input Parameter:
2758: . ksp - iterative solver obtained from `KSPCreate()`
2760: Output Parameters:
2761: + converge - pointer to convergence test function, see `KSPConvergenceTestFn`
2762: . ctx - context for private data for the convergence routine (may be `NULL`)
2763: - destroy - a routine for destroying the context (may be `NULL`)
2765: Level: advanced
2767: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPSetConvergenceTest()`, `KSPGetAndClearConvergenceTest()`
2768: @*/
2769: PetscErrorCode KSPGetConvergenceTest(KSP ksp, KSPConvergenceTestFn **converge, PetscCtxRt ctx, PetscCtxDestroyFn **destroy)
2770: {
2771: PetscFunctionBegin;
2773: if (converge) *converge = ksp->converged;
2774: if (destroy) *destroy = ksp->convergeddestroy;
2775: if (ctx) *(void **)ctx = ksp->cnvP;
2776: PetscFunctionReturn(PETSC_SUCCESS);
2777: }
2779: /*@
2780: KSPGetAndClearConvergenceTest - Gets the function to be used to determine convergence. Removes the current test without calling destroy on the test context
2782: Logically Collective
2784: Input Parameter:
2785: . ksp - iterative solver obtained from `KSPCreate()`
2787: Output Parameters:
2788: + converge - pointer to convergence test function, see `KSPConvergenceTestFn`
2789: . ctx - context for private data for the convergence routine
2790: - destroy - a routine for destroying the context
2792: Level: advanced
2794: Note:
2795: This is intended to be used to allow transferring the convergence test (and its context) to another testing object (for example another `KSP`)
2796: and then calling `KSPSetConvergenceTest()` on this original `KSP`. If you just called `KSPGetConvergenceTest()` followed
2797: by `KSPSetConvergenceTest()` the original context information
2798: would be destroyed and hence the transferred context would be invalid and trigger a crash on use
2800: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPSetConvergenceTest()`, `KSPGetConvergenceTest()`
2801: @*/
2802: PetscErrorCode KSPGetAndClearConvergenceTest(KSP ksp, KSPConvergenceTestFn **converge, PetscCtxRt ctx, PetscCtxDestroyFn **destroy)
2803: {
2804: PetscFunctionBegin;
2806: *converge = ksp->converged;
2807: *destroy = ksp->convergeddestroy;
2808: *(void **)ctx = ksp->cnvP;
2809: ksp->converged = NULL;
2810: ksp->cnvP = NULL;
2811: ksp->convergeddestroy = NULL;
2812: PetscFunctionReturn(PETSC_SUCCESS);
2813: }
2815: /*@
2816: KSPGetConvergenceContext - Gets the convergence context set with `KSPSetConvergenceTest()`.
2818: Not Collective
2820: Input Parameter:
2821: . ksp - iterative solver obtained from `KSPCreate()`
2823: Output Parameter:
2824: . ctx - monitoring context
2826: Level: advanced
2828: Fortran Note:
2829: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
2830: .vb
2831: type(tUsertype), pointer :: ctx
2832: .ve
2834: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSPGetConvergenceTest()`
2835: @*/
2836: PetscErrorCode KSPGetConvergenceContext(KSP ksp, PetscCtxRt ctx)
2837: {
2838: PetscFunctionBegin;
2840: *(void **)ctx = ksp->cnvP;
2841: PetscFunctionReturn(PETSC_SUCCESS);
2842: }
2844: /*@
2845: KSPBuildSolution - Builds the approximate solution in a vector provided.
2847: Collective
2849: Input Parameter:
2850: . ksp - iterative solver obtained from `KSPCreate()`
2852: Output Parameter:
2853: Provide exactly one of
2854: + v - location to stash solution, optional, otherwise pass `NULL`
2855: - V - the solution is returned in this location. This vector is created internally. This vector should NOT be destroyed by the user with `VecDestroy()`.
2857: Level: developer
2859: Notes:
2860: This routine can be used in one of two ways
2861: .vb
2862: KSPBuildSolution(ksp,NULL,&V);
2863: or
2864: KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2865: .ve
2866: In the first case an internal vector is allocated to store the solution
2867: (the user cannot destroy this vector). In the second case the solution
2868: is generated in the vector that the user provides. Note that for certain
2869: methods, such as `KSPCG`, the second case requires a copy of the solution,
2870: while in the first case the call is essentially free since it simply
2871: returns the vector where the solution already is stored. For some methods
2872: like `KSPGMRES` during the solve this is a reasonably expensive operation and should only be
2873: used if truly needed.
2875: .seealso: [](ch_ksp), `KSPGetSolution()`, `KSPBuildResidual()`, `KSP`
2876: @*/
2877: PetscErrorCode KSPBuildSolution(KSP ksp, Vec v, Vec *V)
2878: {
2879: PetscFunctionBegin;
2881: PetscCheck(V || v, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONG, "Must provide either v or V");
2882: if (!V) V = &v;
2883: if (ksp->reason != KSP_CONVERGED_ITERATING) {
2884: if (!v) PetscCall(KSPGetSolution(ksp, V));
2885: else PetscCall(VecCopy(ksp->vec_sol, v));
2886: } else {
2887: PetscUseTypeMethod(ksp, buildsolution, v, V);
2888: }
2889: PetscFunctionReturn(PETSC_SUCCESS);
2890: }
2892: /*@
2893: KSPBuildResidual - Builds the residual in a vector provided.
2895: Collective
2897: Input Parameter:
2898: . ksp - iterative solver obtained from `KSPCreate()`
2900: Output Parameters:
2901: + t - work vector. If not provided then one is generated.
2902: . v - optional location to stash residual. If `v` is not provided, then a location is generated.
2903: - V - the residual
2905: Level: advanced
2907: Note:
2908: Regardless of whether or not `v` is provided, the residual is
2909: returned in `V`.
2911: .seealso: [](ch_ksp), `KSP`, `KSPBuildSolution()`
2912: @*/
2913: PetscErrorCode KSPBuildResidual(KSP ksp, Vec t, Vec v, Vec *V)
2914: {
2915: PetscBool flag = PETSC_FALSE;
2916: Vec w = v, tt = t;
2918: PetscFunctionBegin;
2920: if (!w) PetscCall(VecDuplicate(ksp->vec_rhs, &w));
2921: if (!tt) {
2922: PetscCall(VecDuplicate(ksp->vec_sol, &tt));
2923: flag = PETSC_TRUE;
2924: }
2925: PetscUseTypeMethod(ksp, buildresidual, tt, w, V);
2926: if (flag) PetscCall(VecDestroy(&tt));
2927: PetscFunctionReturn(PETSC_SUCCESS);
2928: }
2930: /*@
2931: KSPSetComputeOperators - set routine to compute the linear operators
2933: Logically Collective
2935: Input Parameters:
2936: + ksp - the `KSP` context
2937: . func - function to compute the operators, see `KSPComputeOperatorsFn` for the calling sequence
2938: - ctx - optional context
2940: Level: beginner
2942: Notes:
2943: `func()` will be called automatically at the very next call to `KSPSolve()`. It will NOT be called at future `KSPSolve()` calls
2944: unless either `KSPSetComputeOperators()` or `KSPSetOperators()` is called before that `KSPSolve()` is called. This allows the same system to be solved several times
2945: with different right-hand side functions but is a confusing API since one might expect it to be called for each `KSPSolve()`
2947: To reuse the same preconditioner for the next `KSPSolve()` and not compute a new one based on the most recently computed matrix call `KSPSetReusePreconditioner()`
2949: Developer Note:
2950: Perhaps this routine and `KSPSetComputeRHS()` could be combined into a new API that makes clear when new matrices are computing without requiring call this
2951: routine to indicate when the new matrix should be computed.
2953: .seealso: [](ch_ksp), `KSP`, `KSPSetOperators()`, `KSPSetComputeRHS()`, `DMKSPSetComputeOperators()`, `KSPSetComputeInitialGuess()`, `KSPComputeOperatorsFn`
2954: @*/
2955: PetscErrorCode KSPSetComputeOperators(KSP ksp, KSPComputeOperatorsFn *func, PetscCtx ctx)
2956: {
2957: DM dm;
2959: PetscFunctionBegin;
2961: PetscCall(KSPGetDM(ksp, &dm));
2962: PetscCall(DMKSPSetComputeOperators(dm, func, ctx));
2963: if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2964: PetscFunctionReturn(PETSC_SUCCESS);
2965: }
2967: /*@
2968: KSPSetComputeRHS - set routine to compute the right-hand side of the linear system
2970: Logically Collective
2972: Input Parameters:
2973: + ksp - the `KSP` context
2974: . func - function to compute the right-hand side, see `KSPComputeRHSFn` for the calling sequence
2975: - ctx - optional context
2977: Level: beginner
2979: Note:
2980: The routine you provide will be called EACH you call `KSPSolve()` to prepare the new right-hand side for that solve
2982: .seealso: [](ch_ksp), `KSP`, `KSPSolve()`, `DMKSPSetComputeRHS()`, `KSPSetComputeOperators()`, `KSPSetOperators()`, `KSPComputeRHSFn`
2983: @*/
2984: PetscErrorCode KSPSetComputeRHS(KSP ksp, KSPComputeRHSFn *func, PetscCtx ctx)
2985: {
2986: DM dm;
2988: PetscFunctionBegin;
2990: PetscCall(KSPGetDM(ksp, &dm));
2991: PetscCall(DMKSPSetComputeRHS(dm, func, ctx));
2992: PetscFunctionReturn(PETSC_SUCCESS);
2993: }
2995: /*@
2996: KSPSetComputeInitialGuess - set routine to compute the initial guess of the linear system
2998: Logically Collective
3000: Input Parameters:
3001: + ksp - the `KSP` context
3002: . func - function to compute the initial guess, see `KSPComputeInitialGuessFn` for calling sequence
3003: - ctx - optional context
3005: Level: beginner
3007: Note:
3008: This should only be used in conjunction with `KSPSetComputeRHS()` and `KSPSetComputeOperators()`, otherwise
3009: call `KSPSetInitialGuessNonzero()` and set the initial guess values in the solution vector passed to `KSPSolve()` before calling the solver
3011: .seealso: [](ch_ksp), `KSP`, `KSPSolve()`, `KSPSetComputeRHS()`, `KSPSetComputeOperators()`, `DMKSPSetComputeInitialGuess()`, `KSPSetInitialGuessNonzero()`,
3012: `KSPComputeInitialGuessFn`
3013: @*/
3014: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp, KSPComputeInitialGuessFn *func, PetscCtx ctx)
3015: {
3016: DM dm;
3018: PetscFunctionBegin;
3020: PetscCall(KSPGetDM(ksp, &dm));
3021: PetscCall(DMKSPSetComputeInitialGuess(dm, func, ctx));
3022: PetscFunctionReturn(PETSC_SUCCESS);
3023: }
3025: /*@
3026: KSPSetUseExplicitTranspose - Determines whether the explicit transpose of the operator is formed in `KSPSolveTranspose()` and `KSPMatSolveTranspose()`
3028: Collective
3030: Input Parameters:
3031: + ksp - the `KSP` context
3032: - flg - `PETSC_TRUE` to transpose the system explicitly, `PETSC_FALSE` to not transpose explicitly (default)
3034: Options Database Key:
3035: . -ksp_use_explicittranspose - transpose the system explicitly in `KSPSolveTranspose()` and `KSPMatSolveTranspose()`
3037: Level: advanced
3039: Note:
3040: Explicitly forming the transpose may improve solve performance in some configurations, such as on GPUs. When enabled, the explicitly transposed operators replace the `KSP`
3041: operators and remain set after `KSPSolveTranspose()` or `KSPMatSolveTranspose()`, so `KSPGetOperators()` returns the transposed operators. A subsequent non-transpose
3042: `KSPSolve()` or `KSPMatSolve()`, or disabling this option, restores any cached transposed operator that is still set to its parent operator. Alternating between transpose
3043: and non-transpose solves requires the preconditioner to be set up again on every direction change; use separate `KSP` objects when both directions are solved repeatedly.
3045: .seealso: [](ch_ksp), `KSPSolveTranspose()`, `KSPMatSolveTranspose()`, `KSPSetOperators()`, `KSPGetOperators()`, `KSP`
3046: @*/
3047: PetscErrorCode KSPSetUseExplicitTranspose(KSP ksp, PetscBool flg)
3048: {
3049: PetscFunctionBegin;
3052: if (!flg && ksp->transpose.reuse_transpose) {
3053: PetscCall(KSPRestoreExplicitTranspose_Private(ksp));
3054: PetscCall(KSPResetExplicitTranspose_Private(ksp));
3055: }
3056: ksp->transpose.use_explicittranspose = flg;
3057: PetscFunctionReturn(PETSC_SUCCESS);
3058: }