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: /*@
 21:   KSPComputeExtremeSingularValues - Computes the extreme singular values
 22:   for the preconditioned operator. Called after or during `KSPSolve()`.

 24:   Not Collective

 26:   Input Parameter:
 27: . ksp - iterative solver obtained from `KSPCreate()`

 29:   Output Parameters:
 30: + emax - maximum estimated singular value
 31: - emin - minimum estimated singular value

 33:   Options Database Key:
 34: . -ksp_view_singularvalues - compute extreme singular values and print when `KSPSolve()` completes.

 36:   Level: advanced

 38:   Notes:
 39:   One must call `KSPSetComputeSingularValues()` before calling `KSPSetUp()`
 40:   (or use the option `-ksp_view_singularvalues`) in order for this routine to work correctly.

 42:   Many users may just want to use the monitoring routine
 43:   `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
 44:   to print the extreme singular values at each iteration of the linear solve.

 46:   Estimates of the smallest singular value may be very inaccurate, especially if the Krylov method has not converged.
 47:   The largest singular value is usually accurate to within a few percent if the method has converged, but is still not
 48:   intended for eigenanalysis. Consider the excellent package SLEPc if accurate values are required.

 50:   Disable restarts if using `KSPGMRES`, otherwise this estimate will only be using those iterations after the last
 51:   restart. See `KSPGMRESSetRestart()` for more details.

 53: .seealso: [](ch_ksp), `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`, `KSPComputeEigenvalues()`, `KSP`, `KSPComputeRitz()`
 54: @*/
 55: PetscErrorCode KSPComputeExtremeSingularValues(KSP ksp, PetscReal *emax, PetscReal *emin)
 56: {
 57:   PetscFunctionBegin;
 59:   PetscAssertPointer(emax, 2);
 60:   PetscAssertPointer(emin, 3);
 61:   PetscCheck(ksp->calc_sings, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Singular values not requested before KSPSetUp()");

 63:   if (ksp->ops->computeextremesingularvalues) PetscUseTypeMethod(ksp, computeextremesingularvalues, emax, emin);
 64:   else {
 65:     *emin = -1.0;
 66:     *emax = -1.0;
 67:   }
 68:   PetscFunctionReturn(PETSC_SUCCESS);
 69: }

 71: /*@
 72:   KSPComputeEigenvalues - Computes the extreme eigenvalues for the
 73:   preconditioned operator. Called after or during `KSPSolve()`.

 75:   Not Collective

 77:   Input Parameters:
 78: + ksp - iterative solver obtained from `KSPCreate()`
 79: - n   - size of arrays `r` and `c`. The number of eigenvalues computed `neig` will, in general, be less than this.

 81:   Output Parameters:
 82: + r    - real part of computed eigenvalues, provided by user with a dimension of at least `n`
 83: . c    - complex part of computed eigenvalues, provided by user with a dimension of at least `n`
 84: - neig - actual number of eigenvalues computed (will be less than or equal to `n`)

 86:   Options Database Key:
 87: . -ksp_view_eigenvalues - Prints eigenvalues to stdout

 89:   Level: advanced

 91:   Notes:
 92:   The number of eigenvalues estimated depends on the size of the Krylov space
 93:   generated during the `KSPSolve()` ; for example, with
 94:   `KSPCG` it corresponds to the number of CG iterations, for `KSPGMRES` it is the number
 95:   of GMRES iterations SINCE the last restart. Any extra space in `r` and `c`
 96:   will be ignored.

 98:   `KSPComputeEigenvalues()` does not usually provide accurate estimates; it is
 99:   intended only for assistance in understanding the convergence of iterative
100:   methods, not for eigenanalysis. For accurate computation of eigenvalues we recommend using
101:   the excellent package SLEPc.

103:   One must call `KSPSetComputeEigenvalues()` before calling `KSPSetUp()`
104:   in order for this routine to work correctly.

106:   Many users may just want to use the monitoring routine
107:   `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
108:   to print the singular values at each iteration of the linear solve.

110:   `KSPComputeRitz()` provides estimates for both the eigenvalues and their corresponding eigenvectors.

112: .seealso: [](ch_ksp), `KSPSetComputeEigenvalues()`, `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`, `KSPComputeExtremeSingularValues()`, `KSP`, `KSPComputeRitz()`
113: @*/
114: PetscErrorCode KSPComputeEigenvalues(KSP ksp, PetscInt n, PetscReal r[], PetscReal c[], PetscInt *neig)
115: {
116:   PetscFunctionBegin;
118:   if (n) PetscAssertPointer(r, 3);
119:   if (n) PetscAssertPointer(c, 4);
120:   PetscCheck(n >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Requested < 0 Eigenvalues");
121:   PetscAssertPointer(neig, 5);
122:   PetscCheck(ksp->calc_sings, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Eigenvalues not requested before KSPSetUp()");

124:   if (n && ksp->ops->computeeigenvalues) PetscUseTypeMethod(ksp, computeeigenvalues, n, r, c, neig);
125:   else *neig = 0;
126:   PetscFunctionReturn(PETSC_SUCCESS);
127: }

129: /*@
130:   KSPComputeRitz - Computes the Ritz or harmonic Ritz pairs associated with the
131:   smallest or largest in modulus, for the preconditioned operator.

133:   Not Collective

135:   Input Parameters:
136: + ksp   - iterative solver obtained from `KSPCreate()`
137: . ritz  - `PETSC_TRUE` or `PETSC_FALSE` for Ritz pairs or harmonic Ritz pairs, respectively
138: - small - `PETSC_TRUE` or `PETSC_FALSE` for smallest or largest (harmonic) Ritz values, respectively

140:   Output Parameters:
141: + nrit  - On input number of (harmonic) Ritz pairs to compute; on output, actual number of computed (harmonic) Ritz pairs
142: . S     - an array of the Ritz vectors, pass in an array of vectors of size `nrit`
143: . tetar - real part of the Ritz values, pass in an array of size `nrit`
144: - tetai - imaginary part of the Ritz values, pass in an array of size `nrit`

146:   Level: advanced

148:   Notes:
149:   This only works with a `KSPType` of `KSPGMRES`.

151:   One must call `KSPSetComputeRitz()` before calling `KSPSetUp()` in order for this routine to work correctly.

153:   This routine must be called after `KSPSolve()`.

155:   In `KSPGMRES`, the (harmonic) Ritz pairs are computed from the Hessenberg matrix obtained during
156:   the last complete cycle of the GMRES solve, or during the partial cycle if the solve ended before
157:   a restart (that is a complete GMRES cycle was never achieved).

159:   The number of actual (harmonic) Ritz pairs computed is less than or equal to the restart
160:   parameter for GMRES if a complete cycle has been performed or less or equal to the number of GMRES
161:   iterations.

163:   `KSPComputeEigenvalues()` provides estimates for only the eigenvalues (Ritz values).

165:   For real matrices, the (harmonic) Ritz pairs can be complex-valued. In such a case,
166:   the routine selects the complex (harmonic) Ritz value and its conjugate, and two successive entries of the
167:   vectors `S` are equal to the real and the imaginary parts of the associated vectors.
168:   When PETSc has been built with complex scalars, the real and imaginary parts of the Ritz
169:   values are still returned in `tetar` and `tetai`, as is done in `KSPComputeEigenvalues()`, but
170:   the Ritz vectors S are complex.

172:   The (harmonic) Ritz pairs are given in order of increasing (harmonic) Ritz values in modulus.

174:   The Ritz pairs do not necessarily accurately reflect the eigenvalues and eigenvectors of the operator, consider the
175:   excellent package SLEPc if accurate values are required.

177: .seealso: [](ch_ksp), `KSPSetComputeRitz()`, `KSP`, `KSPGMRES`, `KSPComputeEigenvalues()`, `KSPSetComputeSingularValues()`, `KSPMonitorSingularValue()`
178: @*/
179: PetscErrorCode KSPComputeRitz(KSP ksp, PetscBool ritz, PetscBool small, PetscInt *nrit, Vec S[], PetscReal tetar[], PetscReal tetai[])
180: {
181:   PetscFunctionBegin;
183:   PetscCheck(ksp->calc_ritz, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Ritz pairs not requested before KSPSetUp()");
184:   PetscTryTypeMethod(ksp, computeritz, ritz, small, nrit, S, tetar, tetai);
185:   PetscFunctionReturn(PETSC_SUCCESS);
186: }

188: /*@
189:   KSPSetUpOnBlocks - Sets up the preconditioner for each block in
190:   the block Jacobi `PCJACOBI`, overlapping Schwarz `PCASM`, and fieldsplit `PCFIELDSPLIT` preconditioners

192:   Collective

194:   Input Parameter:
195: . ksp - the `KSP` context

197:   Level: advanced

199:   Notes:
200:   `KSPSetUpOnBlocks()` is a routine that the user can optionally call for
201:   more precise profiling (via `-log_view`) of the setup phase for these
202:   block preconditioners.  If the user does not call `KSPSetUpOnBlocks()`,
203:   it will automatically be called from within `KSPSolve()`.

205:   Calling `KSPSetUpOnBlocks()` is the same as calling `PCSetUpOnBlocks()`
206:   on the `PC` context within the `KSP` context.

208: .seealso: [](ch_ksp), `PCSetUpOnBlocks()`, `KSPSetUp()`, `PCSetUp()`, `KSP`
209: @*/
210: PetscErrorCode KSPSetUpOnBlocks(KSP ksp)
211: {
212:   PC             pc;
213:   PCFailedReason pcreason;

215:   PetscFunctionBegin;
217:   level++;
218:   PetscCall(KSPGetPC(ksp, &pc));
219:   PetscCall(PCSetUpOnBlocks(pc));
220:   PetscCall(PCGetFailedReason(pc, &pcreason));
221:   level--;
222:   /*
223:      This is tricky since only a subset of MPI ranks may set this; each KSPSolve_*() is responsible for checking
224:      this flag and initializing an appropriate vector with VecFlag() so that the first norm computation can
225:      produce a result at KSPCheckNorm() thus communicating the known problem to all MPI ranks so they may
226:      terminate the Krylov solve. For many KSP implementations this is handled within KSPInitialResidual()
227:   */
228:   if (pcreason) ksp->reason = KSP_DIVERGED_PC_FAILED;
229:   PetscFunctionReturn(PETSC_SUCCESS);
230: }

232: /*@
233:   KSPSetReusePreconditioner - reuse the current preconditioner for future `KSPSolve()`, do not construct a new preconditioner even if the `Mat` operator
234:   in the `KSP` has different values

236:   Collective

238:   Input Parameters:
239: + ksp  - iterative solver obtained from `KSPCreate()`
240: - flag - `PETSC_TRUE` to reuse the current preconditioner, or `PETSC_FALSE` to construct a new preconditioner

242:   Options Database Key:
243: . -ksp_reuse_preconditioner <true,false> - reuse the previously computed preconditioner

245:   Level: intermediate

247:   Notes:
248:   When using `SNES` one can use `SNESSetLagPreconditioner()` to determine when preconditioners are reused.

250:   Reusing the preconditioner reduces the time needed to form new preconditioners but may (significantly) increase the number
251:   of iterations needed for future solves depending on how much the matrix entries have changed.

253: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGetReusePreconditioner()`,
254:           `SNESSetLagPreconditioner()`, `SNES`
255: @*/
256: PetscErrorCode KSPSetReusePreconditioner(KSP ksp, PetscBool flag)
257: {
258:   PC pc;

260:   PetscFunctionBegin;
262:   PetscCall(KSPGetPC(ksp, &pc));
263:   PetscCall(PCSetReusePreconditioner(pc, flag));
264:   PetscFunctionReturn(PETSC_SUCCESS);
265: }

267: /*@
268:   KSPGetReusePreconditioner - Determines if the `KSP` reuses the current preconditioner even if the `Mat` operator in the `KSP` has changed.

270:   Collective

272:   Input Parameter:
273: . ksp - iterative solver obtained from `KSPCreate()`

275:   Output Parameter:
276: . flag - the boolean flag indicating if the current preconditioner should be reused

278:   Level: intermediate

280: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSPSetReusePreconditioner()`, `KSP`
281: @*/
282: PetscErrorCode KSPGetReusePreconditioner(KSP ksp, PetscBool *flag)
283: {
284:   PetscFunctionBegin;
286:   PetscAssertPointer(flag, 2);
287:   *flag = PETSC_FALSE;
288:   if (ksp->pc) PetscCall(PCGetReusePreconditioner(ksp->pc, flag));
289:   PetscFunctionReturn(PETSC_SUCCESS);
290: }

292: /*@
293:   KSPSetSkipPCSetFromOptions - prevents `KSPSetFromOptions()` from calling `PCSetFromOptions()`.
294:   This is used if the same `PC` is shared by more than one `KSP` so its options are not reset for each `KSP`

296:   Collective

298:   Input Parameters:
299: + ksp  - iterative solver obtained from `KSPCreate()`
300: - flag - `PETSC_TRUE` to skip calling the `PCSetFromOptions()`

302:   Level: developer

304: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `PCSetReusePreconditioner()`, `KSP`
305: @*/
306: PetscErrorCode KSPSetSkipPCSetFromOptions(KSP ksp, PetscBool flag)
307: {
308:   PetscFunctionBegin;
310:   ksp->skippcsetfromoptions = flag;
311:   PetscFunctionReturn(PETSC_SUCCESS);
312: }

314: /*@
315:   KSPSetUp - Sets up the internal data structures for the
316:   later use `KSPSolve()` the `KSP` linear iterative solver.

318:   Collective

320:   Input Parameter:
321: . ksp - iterative solver, `KSP`, obtained from `KSPCreate()`

323:   Level: developer

325:   Note:
326:   This is called automatically by `KSPSolve()` so usually does not need to be called directly.

328: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPSetUpOnBlocks()`
329: @*/
330: PetscErrorCode KSPSetUp(KSP ksp)
331: {
332:   Mat            A, B;
333:   Mat            mat, pmat;
334:   MatNullSpace   nullsp;
335:   PCFailedReason pcreason;
336:   PC             pc;
337:   PetscBool      pcmpi;

339:   PetscFunctionBegin;
341:   PetscCall(KSPGetPC(ksp, &pc));
342:   PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCMPI, &pcmpi));
343:   if (pcmpi) {
344:     PetscBool ksppreonly;
345:     PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPPREONLY, &ksppreonly));
346:     if (!ksppreonly) PetscCall(KSPSetType(ksp, KSPPREONLY));
347:   }
348:   level++;

350:   /* reset the convergence flag from the previous solves */
351:   ksp->reason = KSP_CONVERGED_ITERATING;

353:   if (!((PetscObject)ksp)->type_name) PetscCall(KSPSetType(ksp, KSPGMRES));
354:   PetscCall(KSPSetUpNorms_Private(ksp, PETSC_TRUE, &ksp->normtype, &ksp->pc_side));

356:   if (ksp->dmActive && !ksp->setupstage) {
357:     /* first time in so build matrix and vector data structures using DM */
358:     if (!ksp->vec_rhs) PetscCall(DMCreateGlobalVector(ksp->dm, &ksp->vec_rhs));
359:     if (!ksp->vec_sol) PetscCall(DMCreateGlobalVector(ksp->dm, &ksp->vec_sol));
360:     PetscCall(DMCreateMatrix(ksp->dm, &A));
361:     PetscCall(KSPSetOperators(ksp, A, A));
362:     PetscCall(PetscObjectDereference((PetscObject)A));
363:   }

365:   if (ksp->dmActive) {
366:     DMKSP kdm;
367:     PetscCall(DMGetDMKSP(ksp->dm, &kdm));

369:     if (kdm->ops->computeinitialguess && ksp->setupstage != KSP_SETUP_NEWRHS) {
370:       /* only computes initial guess the first time through */
371:       PetscCallBack("KSP callback initial guess", (*kdm->ops->computeinitialguess)(ksp, ksp->vec_sol, kdm->initialguessctx));
372:       PetscCall(KSPSetInitialGuessNonzero(ksp, PETSC_TRUE));
373:     }
374:     if (kdm->ops->computerhs) PetscCallBack("KSP callback rhs", (*kdm->ops->computerhs)(ksp, ksp->vec_rhs, kdm->rhsctx));

376:     if (ksp->setupstage != KSP_SETUP_NEWRHS) {
377:       PetscCheck(kdm->ops->computeoperators, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "You called KSPSetDM() but did not use DMKSPSetComputeOperators() or KSPSetDMActive(ksp,PETSC_FALSE);");
378:       PetscCall(KSPGetOperators(ksp, &A, &B));
379:       PetscCallBack("KSP callback operators", (*kdm->ops->computeoperators)(ksp, A, B, kdm->operatorsctx));
380:     }
381:   }

383:   if (ksp->setupstage == KSP_SETUP_NEWRHS) {
384:     level--;
385:     PetscFunctionReturn(PETSC_SUCCESS);
386:   }
387:   PetscCall(PetscLogEventBegin(KSP_SetUp, ksp, ksp->vec_rhs, ksp->vec_sol, 0));

389:   switch (ksp->setupstage) {
390:   case KSP_SETUP_NEW:
391:     PetscUseTypeMethod(ksp, setup);
392:     break;
393:   case KSP_SETUP_NEWMATRIX: /* This should be replaced with a more general mechanism */
394:     if (ksp->setupnewmatrix) PetscUseTypeMethod(ksp, setup);
395:     break;
396:   default:
397:     break;
398:   }

400:   if (!ksp->pc) PetscCall(KSPGetPC(ksp, &ksp->pc));
401:   PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
402:   /* scale the matrix if requested */
403:   if (ksp->dscale) {
404:     PetscScalar *xx;
405:     PetscInt     i, n;
406:     PetscBool    zeroflag = PETSC_FALSE;

408:     if (!ksp->diagonal) { /* allocate vector to hold diagonal */
409:       PetscCall(MatCreateVecs(pmat, &ksp->diagonal, NULL));
410:     }
411:     PetscCall(MatGetDiagonal(pmat, ksp->diagonal));
412:     PetscCall(VecGetLocalSize(ksp->diagonal, &n));
413:     PetscCall(VecGetArray(ksp->diagonal, &xx));
414:     for (i = 0; i < n; i++) {
415:       if (xx[i] != 0.0) xx[i] = 1.0 / PetscSqrtReal(PetscAbsScalar(xx[i]));
416:       else {
417:         xx[i]    = 1.0;
418:         zeroflag = PETSC_TRUE;
419:       }
420:     }
421:     PetscCall(VecRestoreArray(ksp->diagonal, &xx));
422:     if (zeroflag) PetscCall(PetscInfo(ksp, "Zero detected in diagonal of matrix, using 1 at those locations\n"));
423:     PetscCall(MatDiagonalScale(pmat, ksp->diagonal, ksp->diagonal));
424:     if (mat != pmat) PetscCall(MatDiagonalScale(mat, ksp->diagonal, ksp->diagonal));
425:     ksp->dscalefix2 = PETSC_FALSE;
426:   }
427:   PetscCall(PetscLogEventEnd(KSP_SetUp, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
428:   PetscCall(PCSetErrorIfFailure(ksp->pc, ksp->errorifnotconverged));
429:   PetscCall(PCSetUp(ksp->pc));
430:   PetscCall(PCGetFailedReason(ksp->pc, &pcreason));
431:   /* 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 */
432:   if (pcreason) ksp->reason = KSP_DIVERGED_PC_FAILED;

434:   PetscCall(MatGetNullSpace(mat, &nullsp));
435:   if (nullsp) {
436:     PetscBool test = PETSC_FALSE;
437:     PetscCall(PetscOptionsGetBool(((PetscObject)ksp)->options, ((PetscObject)ksp)->prefix, "-ksp_test_null_space", &test, NULL));
438:     if (test) PetscCall(MatNullSpaceTest(nullsp, mat, NULL));
439:   }
440:   ksp->setupstage = KSP_SETUP_NEWRHS;
441:   level--;
442:   PetscFunctionReturn(PETSC_SUCCESS);
443: }

445: /*@
446:   KSPConvergedReasonView - Displays the reason a `KSP` solve converged or diverged, `KSPConvergedReason` to a `PetscViewer`

448:   Collective

450:   Input Parameters:
451: + ksp    - iterative solver obtained from `KSPCreate()`
452: - viewer - the `PetscViewer` on which to display the reason

454:   Options Database Keys:
455: + -ksp_converged_reason          - print reason for converged or diverged, also prints number of iterations
456: - -ksp_converged_reason ::failed - only print reason and number of iterations when diverged

458:   Level: beginner

460:   Note:
461:   Use `KSPConvergedReasonViewFromOptions()` to display the reason based on values in the PETSc options database.

463:   To change the format of the output call `PetscViewerPushFormat`(`viewer`,`format`) before this call. Use `PETSC_VIEWER_DEFAULT` for the default,
464:   use `PETSC_VIEWER_FAILED` to only display a reason if it fails.

466: .seealso: [](ch_ksp), `KSPConvergedReasonViewFromOptions()`, `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
467:           `KSPSolveTranspose()`, `KSPGetIterationNumber()`, `KSP`, `KSPGetConvergedReason()`, `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
468: @*/
469: PetscErrorCode KSPConvergedReasonView(KSP ksp, PetscViewer viewer)
470: {
471:   PetscBool         isAscii;
472:   PetscViewerFormat format;

474:   PetscFunctionBegin;
475:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
476:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
477:   if (isAscii) {
478:     PetscCall(PetscViewerGetFormat(viewer, &format));
479:     PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)ksp)->tablevel + 1));
480:     if (ksp->reason > 0 && format != PETSC_VIEWER_FAILED) {
481:       if (((PetscObject)ksp)->prefix) {
482:         PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)ksp)->prefix, KSPConvergedReasons[ksp->reason], ksp->its));
483:       } else {
484:         PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve converged due to %s iterations %" PetscInt_FMT "\n", KSPConvergedReasons[ksp->reason], ksp->its));
485:       }
486:     } else if (ksp->reason <= 0) {
487:       if (((PetscObject)ksp)->prefix) {
488:         PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)ksp)->prefix, KSPConvergedReasons[ksp->reason], ksp->its));
489:       } else {
490:         PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve did not converge due to %s iterations %" PetscInt_FMT "\n", KSPConvergedReasons[ksp->reason], ksp->its));
491:       }
492:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
493:         PCFailedReason reason;
494:         PetscCall(PCGetFailedReason(ksp->pc, &reason));
495:         PetscCall(PetscViewerASCIIPrintf(viewer, "               PC failed due to %s\n", PCFailedReasons[reason]));
496:       }
497:     }
498:     PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)ksp)->tablevel + 1));
499:   }
500:   PetscFunctionReturn(PETSC_SUCCESS);
501: }

503: /*@C
504:   KSPConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
505:   end of the linear solver to display the convergence reason of the linear solver.

507:   Logically Collective

509:   Input Parameters:
510: + ksp               - the `KSP` context
511: . f                 - the ksp converged reason view function
512: . vctx              - [optional] user-defined context for private data for the
513:                       `KSPConvergedReason` view routine (use `NULL` if no context is desired)
514: - reasonviewdestroy - [optional] routine that frees `vctx` (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

516:   Options Database Keys:
517: + -ksp_converged_reason             - sets a default `KSPConvergedReasonView()`
518: - -ksp_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
519:                                       calls to `KSPConvergedReasonViewSet()`, but does not cancel those set via the options database.

521:   Level: intermediate

523:   Note:
524:   Several different converged reason view routines may be set by calling
525:   `KSPConvergedReasonViewSet()` multiple times; all will be called in the
526:   order in which they were set.

528:   Developer Note:
529:   Should be named KSPConvergedReasonViewAdd().

531: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPConvergedReasonViewCancel()`, `PetscCtxDestroyFn`
532: @*/
533: PetscErrorCode KSPConvergedReasonViewSet(KSP ksp, PetscErrorCode (*f)(KSP, void *), void *vctx, PetscCtxDestroyFn *reasonviewdestroy)
534: {
535:   PetscInt  i;
536:   PetscBool identical;

538:   PetscFunctionBegin;
540:   for (i = 0; i < ksp->numberreasonviews; i++) {
541:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))ksp->reasonview[i], ksp->reasonviewcontext[i], ksp->reasonviewdestroy[i], &identical));
542:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
543:   }
544:   PetscCheck(ksp->numberreasonviews < MAXKSPREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many KSP reasonview set");
545:   ksp->reasonview[ksp->numberreasonviews]          = f;
546:   ksp->reasonviewdestroy[ksp->numberreasonviews]   = reasonviewdestroy;
547:   ksp->reasonviewcontext[ksp->numberreasonviews++] = vctx;
548:   PetscFunctionReturn(PETSC_SUCCESS);
549: }

551: /*@
552:   KSPConvergedReasonViewCancel - Clears all the `KSPConvergedReason` view functions for a `KSP` object set with `KSPConvergedReasonViewSet()`
553:   as well as the default viewer.

555:   Collective

557:   Input Parameter:
558: . ksp - iterative solver obtained from `KSPCreate()`

560:   Level: intermediate

562: .seealso: [](ch_ksp), `KSPCreate()`, `KSPDestroy()`, `KSPReset()`, `KSPConvergedReasonViewSet()`
563: @*/
564: PetscErrorCode KSPConvergedReasonViewCancel(KSP ksp)
565: {
566:   PetscInt i;

568:   PetscFunctionBegin;
570:   for (i = 0; i < ksp->numberreasonviews; i++) {
571:     if (ksp->reasonviewdestroy[i]) PetscCall((*ksp->reasonviewdestroy[i])(&ksp->reasonviewcontext[i]));
572:   }
573:   ksp->numberreasonviews = 0;
574:   PetscCall(PetscViewerDestroy(&ksp->convergedreasonviewer));
575:   PetscFunctionReturn(PETSC_SUCCESS);
576: }

578: /*@
579:   KSPConvergedReasonViewFromOptions - Processes command line options to determine if/how a `KSPReason` is to be viewed.

581:   Collective

583:   Input Parameter:
584: . ksp - the `KSP` object

586:   Level: intermediate

588:   Note:
589:   This is called automatically at the conclusion of `KSPSolve()` so is rarely called directly by user code.

591: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPConvergedReasonViewSet()`
592: @*/
593: PetscErrorCode KSPConvergedReasonViewFromOptions(KSP ksp)
594: {
595:   PetscFunctionBegin;
596:   /* Call all user-provided reason review routines */
597:   for (PetscInt i = 0; i < ksp->numberreasonviews; i++) PetscCall((*ksp->reasonview[i])(ksp, ksp->reasonviewcontext[i]));

599:   /* Call the default PETSc routine */
600:   if (ksp->convergedreasonviewer) {
601:     PetscCall(PetscViewerPushFormat(ksp->convergedreasonviewer, ksp->convergedreasonformat));
602:     PetscCall(KSPConvergedReasonView(ksp, ksp->convergedreasonviewer));
603:     PetscCall(PetscViewerPopFormat(ksp->convergedreasonviewer));
604:   }
605:   PetscFunctionReturn(PETSC_SUCCESS);
606: }

608: /*@
609:   KSPConvergedRateView - Displays the convergence rate <https://en.wikipedia.org/wiki/Coefficient_of_determination> of `KSPSolve()` to a viewer

611:   Collective

613:   Input Parameters:
614: + ksp    - iterative solver obtained from `KSPCreate()`
615: - viewer - the `PetscViewer` to display the reason

617:   Options Database Key:
618: . -ksp_converged_rate - print reason for convergence or divergence and the convergence rate (or 0.0 for divergence)

620:   Level: intermediate

622:   Notes:
623:   To change the format of the output, call `PetscViewerPushFormat`(`viewer`,`format`) before this call.

625:   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,
626:   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)}$,

628: .seealso: [](ch_ksp), `KSPConvergedReasonView()`, `KSPGetConvergedRate()`, `KSPSetTolerances()`, `KSPConvergedDefault()`
629: @*/
630: PetscErrorCode KSPConvergedRateView(KSP ksp, PetscViewer viewer)
631: {
632:   PetscViewerFormat format;
633:   PetscBool         isAscii;
634:   PetscReal         rrate, rRsq, erate = 0.0, eRsq = 0.0;
635:   PetscInt          its;
636:   const char       *prefix, *reason = KSPConvergedReasons[ksp->reason];

638:   PetscFunctionBegin;
639:   PetscCall(KSPGetIterationNumber(ksp, &its));
640:   PetscCall(KSPComputeConvergenceRate(ksp, &rrate, &rRsq, &erate, &eRsq));
641:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ksp));
642:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
643:   if (isAscii) {
644:     PetscCall(KSPGetOptionsPrefix(ksp, &prefix));
645:     PetscCall(PetscViewerGetFormat(viewer, &format));
646:     PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)ksp)->tablevel));
647:     if (ksp->reason > 0) {
648:       if (prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve converged due to %s iterations %" PetscInt_FMT, prefix, reason, its));
649:       else PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve converged due to %s iterations %" PetscInt_FMT, reason, its));
650:       PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_FALSE));
651:       if (rRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " res rate %g R^2 %g", (double)rrate, (double)rRsq));
652:       if (eRsq >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, " error rate %g R^2 %g", (double)erate, (double)eRsq));
653:       PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
654:       PetscCall(PetscViewerASCIIUseTabs(viewer, PETSC_TRUE));
655:     } else if (ksp->reason <= 0) {
656:       if (prefix) PetscCall(PetscViewerASCIIPrintf(viewer, "Linear %s solve did not converge due to %s iterations %" PetscInt_FMT, prefix, reason, its));
657:       else PetscCall(PetscViewerASCIIPrintf(viewer, "Linear solve did not converge 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:       if (ksp->reason == KSP_DIVERGED_PC_FAILED) {
664:         PCFailedReason reason;
665:         PetscCall(PCGetFailedReason(ksp->pc, &reason));
666:         PetscCall(PetscViewerASCIIPrintf(viewer, "               PC failed due to %s\n", PCFailedReasons[reason]));
667:       }
668:     }
669:     PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)ksp)->tablevel));
670:   }
671:   PetscFunctionReturn(PETSC_SUCCESS);
672: }

674: #include <petscdraw.h>

676: static PetscErrorCode KSPViewEigenvalues_Internal(KSP ksp, PetscBool isExplicit, PetscViewer viewer, PetscViewerFormat format)
677: {
678:   PetscReal  *r, *c;
679:   PetscInt    n, i, neig;
680:   PetscBool   isascii, isdraw;
681:   PetscMPIInt rank;

683:   PetscFunctionBegin;
684:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ksp), &rank));
685:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
686:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
687:   if (isExplicit) {
688:     PetscCall(VecGetSize(ksp->vec_sol, &n));
689:     PetscCall(PetscMalloc2(n, &r, n, &c));
690:     PetscCall(KSPComputeEigenvaluesExplicitly(ksp, n, r, c));
691:     neig = n;
692:   } else {
693:     PetscInt nits;

695:     PetscCall(KSPGetIterationNumber(ksp, &nits));
696:     n = nits + 2;
697:     if (!nits) {
698:       PetscCall(PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any eigenvalues\n"));
699:       PetscFunctionReturn(PETSC_SUCCESS);
700:     }
701:     PetscCall(PetscMalloc2(n, &r, n, &c));
702:     PetscCall(KSPComputeEigenvalues(ksp, n, r, c, &neig));
703:   }
704:   if (isascii) {
705:     PetscCall(PetscViewerASCIIPrintf(viewer, "%s computed eigenvalues\n", isExplicit ? "Explicitly" : "Iteratively"));
706:     for (i = 0; i < neig; ++i) {
707:       if (c[i] >= 0.0) PetscCall(PetscViewerASCIIPrintf(viewer, "%g + %gi\n", (double)r[i], (double)c[i]));
708:       else PetscCall(PetscViewerASCIIPrintf(viewer, "%g - %gi\n", (double)r[i], -(double)c[i]));
709:     }
710:   } else if (isdraw && rank == 0) {
711:     PetscDraw   draw;
712:     PetscDrawSP drawsp;

714:     if (format == PETSC_VIEWER_DRAW_CONTOUR) {
715:       PetscCall(KSPPlotEigenContours_Private(ksp, neig, r, c));
716:     } else {
717:       PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
718:       PetscCall(PetscDrawSPCreate(draw, 1, &drawsp));
719:       PetscCall(PetscDrawSPReset(drawsp));
720:       for (i = 0; i < neig; ++i) PetscCall(PetscDrawSPAddPoint(drawsp, r + i, c + i));
721:       PetscCall(PetscDrawSPDraw(drawsp, PETSC_TRUE));
722:       PetscCall(PetscDrawSPSave(drawsp));
723:       PetscCall(PetscDrawSPDestroy(&drawsp));
724:     }
725:   }
726:   PetscCall(PetscFree2(r, c));
727:   PetscFunctionReturn(PETSC_SUCCESS);
728: }

730: static PetscErrorCode KSPViewSingularvalues_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
731: {
732:   PetscReal smax, smin;
733:   PetscInt  nits;
734:   PetscBool isascii;

736:   PetscFunctionBegin;
737:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
738:   PetscCall(KSPGetIterationNumber(ksp, &nits));
739:   if (!nits) {
740:     PetscCall(PetscViewerASCIIPrintf(viewer, "Zero iterations in solver, cannot approximate any singular values\n"));
741:     PetscFunctionReturn(PETSC_SUCCESS);
742:   }
743:   PetscCall(KSPComputeExtremeSingularValues(ksp, &smax, &smin));
744:   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)));
745:   PetscFunctionReturn(PETSC_SUCCESS);
746: }

748: static PetscErrorCode KSPViewFinalResidual_Internal(KSP ksp, PetscViewer viewer, PetscViewerFormat format)
749: {
750:   PetscBool isascii;

752:   PetscFunctionBegin;
753:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
754:   PetscCheck(!ksp->dscale || ksp->dscalefix, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONGSTATE, "Cannot compute final scale with -ksp_diagonal_scale except also with -ksp_diagonal_scale_fix");
755:   if (isascii) {
756:     Mat       A;
757:     Vec       t;
758:     PetscReal norm;

760:     PetscCall(PCGetOperators(ksp->pc, &A, NULL));
761:     PetscCall(VecDuplicate(ksp->vec_rhs, &t));
762:     PetscCall(KSP_MatMult(ksp, A, ksp->vec_sol, t));
763:     PetscCall(VecAYPX(t, -1.0, ksp->vec_rhs));
764:     PetscCall(VecViewFromOptions(t, (PetscObject)ksp, "-ksp_view_final_residual_vec"));
765:     PetscCall(VecNorm(t, NORM_2, &norm));
766:     PetscCall(VecDestroy(&t));
767:     PetscCall(PetscViewerASCIIPrintf(viewer, "KSP final norm of residual %g\n", (double)norm));
768:   }
769:   PetscFunctionReturn(PETSC_SUCCESS);
770: }

772: PETSC_EXTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt n, void *ctx[])
773: {
774:   PetscFunctionBegin;
775:   for (PetscInt i = 0; i < n; ++i) {
776:     PetscViewerAndFormat *vf = (PetscViewerAndFormat *)ctx[i];
777:     PetscDraw             draw;
778:     PetscReal             lpause;
779:     PetscBool             isdraw;

781:     if (!vf) continue;
782:     if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue;
783:     if (((PetscObject)vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
784:     PetscCall(PetscObjectTypeCompare((PetscObject)vf->viewer, PETSCVIEWERDRAW, &isdraw));
785:     if (!isdraw) continue;

787:     PetscCall(PetscViewerDrawGetDraw(vf->viewer, 0, &draw));
788:     PetscCall(PetscDrawGetPause(draw, &lpause));
789:     PetscCall(PetscDrawSetPause(draw, -1.0));
790:     PetscCall(PetscDrawPause(draw));
791:     PetscCall(PetscDrawSetPause(draw, lpause));
792:   }
793:   PetscFunctionReturn(PETSC_SUCCESS);
794: }

796: static PetscErrorCode KSPMonitorPauseFinal_Internal(KSP ksp)
797: {
798:   PetscFunctionBegin;
799:   if (!ksp->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
800:   PetscCall(PetscMonitorPauseFinal_Internal(ksp->numbermonitors, ksp->monitorcontext));
801:   PetscFunctionReturn(PETSC_SUCCESS);
802: }

804: static PetscErrorCode KSPSolve_Private(KSP ksp, Vec b, Vec x)
805: {
806:   PetscBool    flg = PETSC_FALSE, inXisinB = PETSC_FALSE, guess_zero;
807:   Mat          mat, pmat;
808:   MPI_Comm     comm;
809:   MatNullSpace nullsp;
810:   Vec          btmp, vec_rhs = NULL;

812:   PetscFunctionBegin;
813:   level++;
814:   comm = PetscObjectComm((PetscObject)ksp);
815:   if (x && x == b) {
816:     PetscCheck(ksp->guess_zero, comm, PETSC_ERR_ARG_INCOMP, "Cannot use x == b with nonzero initial guess");
817:     PetscCall(VecDuplicate(b, &x));
818:     inXisinB = PETSC_TRUE;
819:   }
820:   if (b) {
821:     PetscCall(PetscObjectReference((PetscObject)b));
822:     PetscCall(VecDestroy(&ksp->vec_rhs));
823:     ksp->vec_rhs = b;
824:   }
825:   if (x) {
826:     PetscCall(PetscObjectReference((PetscObject)x));
827:     PetscCall(VecDestroy(&ksp->vec_sol));
828:     ksp->vec_sol = x;
829:   }

831:   if (ksp->viewPre) PetscCall(ObjectView((PetscObject)ksp, ksp->viewerPre, ksp->formatPre));

833:   if (ksp->presolve) PetscCall((*ksp->presolve)(ksp, ksp->vec_rhs, ksp->vec_sol, ksp->prectx));

835:   /* reset the residual history list if requested */
836:   if (ksp->res_hist_reset) ksp->res_hist_len = 0;
837:   if (ksp->err_hist_reset) ksp->err_hist_len = 0;

839:   /* KSPSetUp() scales the matrix if needed */
840:   PetscCall(KSPSetUp(ksp));
841:   PetscCall(KSPSetUpOnBlocks(ksp));

843:   if (ksp->guess) {
844:     PetscObjectState ostate, state;

846:     PetscCall(KSPGuessSetUp(ksp->guess));
847:     PetscCall(PetscObjectStateGet((PetscObject)ksp->vec_sol, &ostate));
848:     PetscCall(KSPGuessFormGuess(ksp->guess, ksp->vec_rhs, ksp->vec_sol));
849:     PetscCall(PetscObjectStateGet((PetscObject)ksp->vec_sol, &state));
850:     if (state != ostate) {
851:       ksp->guess_zero = PETSC_FALSE;
852:     } else {
853:       PetscCall(PetscInfo(ksp, "Using zero initial guess since the KSPGuess object did not change the vector\n"));
854:       ksp->guess_zero = PETSC_TRUE;
855:     }
856:   }

858:   PetscCall(VecSetErrorIfLocked(ksp->vec_sol, 3));

860:   PetscCall(PetscLogEventBegin(!ksp->transpose_solve ? KSP_Solve : KSP_SolveTranspose, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
861:   PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
862:   /* diagonal scale RHS if called for */
863:   if (ksp->dscale) {
864:     PetscCall(VecPointwiseMult(ksp->vec_rhs, ksp->vec_rhs, ksp->diagonal));
865:     /* second time in, but matrix was scaled back to original */
866:     if (ksp->dscalefix && ksp->dscalefix2) {
867:       Mat mat, pmat;

869:       PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
870:       PetscCall(MatDiagonalScale(pmat, ksp->diagonal, ksp->diagonal));
871:       if (mat != pmat) PetscCall(MatDiagonalScale(mat, ksp->diagonal, ksp->diagonal));
872:     }

874:     /* scale initial guess */
875:     if (!ksp->guess_zero) {
876:       if (!ksp->truediagonal) {
877:         PetscCall(VecDuplicate(ksp->diagonal, &ksp->truediagonal));
878:         PetscCall(VecCopy(ksp->diagonal, ksp->truediagonal));
879:         PetscCall(VecReciprocal(ksp->truediagonal));
880:       }
881:       PetscCall(VecPointwiseMult(ksp->vec_sol, ksp->vec_sol, ksp->truediagonal));
882:     }
883:   }
884:   PetscCall(PCPreSolve(ksp->pc, ksp));

886:   if (ksp->guess_zero && !ksp->guess_not_read) PetscCall(VecSet(ksp->vec_sol, 0.0));
887:   if (ksp->guess_knoll) { /* The Knoll trick is independent on the KSPGuess specified */
888:     PetscCall(PCApply(ksp->pc, ksp->vec_rhs, ksp->vec_sol));
889:     PetscCall(KSP_RemoveNullSpace(ksp, ksp->vec_sol));
890:     ksp->guess_zero = PETSC_FALSE;
891:   }

893:   /* can we mark the initial guess as zero for this solve? */
894:   guess_zero = ksp->guess_zero;
895:   if (!ksp->guess_zero) {
896:     PetscReal norm;

898:     PetscCall(VecNormAvailable(ksp->vec_sol, NORM_2, &flg, &norm));
899:     if (flg && !norm) ksp->guess_zero = PETSC_TRUE;
900:   }
901:   if (ksp->transpose_solve) {
902:     PetscCall(MatGetNullSpace(mat, &nullsp));
903:   } else {
904:     PetscCall(MatGetTransposeNullSpace(mat, &nullsp));
905:   }
906:   if (nullsp) {
907:     PetscCall(VecDuplicate(ksp->vec_rhs, &btmp));
908:     PetscCall(VecCopy(ksp->vec_rhs, btmp));
909:     PetscCall(MatNullSpaceRemove(nullsp, btmp));
910:     vec_rhs      = ksp->vec_rhs;
911:     ksp->vec_rhs = btmp;
912:   }
913:   PetscCall(VecLockReadPush(ksp->vec_rhs));
914:   PetscUseTypeMethod(ksp, solve);
915:   PetscCall(KSPMonitorPauseFinal_Internal(ksp));

917:   PetscCall(VecLockReadPop(ksp->vec_rhs));
918:   if (nullsp) {
919:     ksp->vec_rhs = vec_rhs;
920:     PetscCall(VecDestroy(&btmp));
921:   }

923:   ksp->guess_zero = guess_zero;

925:   PetscCheck(ksp->reason, comm, PETSC_ERR_PLIB, "Internal error, solver returned without setting converged reason");
926:   ksp->totalits += ksp->its;

928:   PetscCall(KSPConvergedReasonViewFromOptions(ksp));

930:   if (ksp->viewRate) {
931:     PetscCall(PetscViewerPushFormat(ksp->viewerRate, ksp->formatRate));
932:     PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
933:     PetscCall(PetscViewerPopFormat(ksp->viewerRate));
934:   }
935:   PetscCall(PCPostSolve(ksp->pc, ksp));

937:   /* diagonal scale solution if called for */
938:   if (ksp->dscale) {
939:     PetscCall(VecPointwiseMult(ksp->vec_sol, ksp->vec_sol, ksp->diagonal));
940:     /* unscale right-hand side and matrix */
941:     if (ksp->dscalefix) {
942:       Mat mat, pmat;

944:       PetscCall(VecReciprocal(ksp->diagonal));
945:       PetscCall(VecPointwiseMult(ksp->vec_rhs, ksp->vec_rhs, ksp->diagonal));
946:       PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
947:       PetscCall(MatDiagonalScale(pmat, ksp->diagonal, ksp->diagonal));
948:       if (mat != pmat) PetscCall(MatDiagonalScale(mat, ksp->diagonal, ksp->diagonal));
949:       PetscCall(VecReciprocal(ksp->diagonal));
950:       ksp->dscalefix2 = PETSC_TRUE;
951:     }
952:   }
953:   PetscCall(PetscLogEventEnd(!ksp->transpose_solve ? KSP_Solve : KSP_SolveTranspose, ksp, ksp->vec_rhs, ksp->vec_sol, 0));
954:   if (ksp->guess) PetscCall(KSPGuessUpdate(ksp->guess, ksp->vec_rhs, ksp->vec_sol));
955:   if (ksp->postsolve) PetscCall((*ksp->postsolve)(ksp, ksp->vec_rhs, ksp->vec_sol, ksp->postctx));

957:   PetscCall(PCGetOperators(ksp->pc, &mat, &pmat));
958:   if (ksp->viewEV) PetscCall(KSPViewEigenvalues_Internal(ksp, PETSC_FALSE, ksp->viewerEV, ksp->formatEV));
959:   if (ksp->viewEVExp) PetscCall(KSPViewEigenvalues_Internal(ksp, PETSC_TRUE, ksp->viewerEVExp, ksp->formatEVExp));
960:   if (ksp->viewSV) PetscCall(KSPViewSingularvalues_Internal(ksp, ksp->viewerSV, ksp->formatSV));
961:   if (ksp->viewFinalRes) PetscCall(KSPViewFinalResidual_Internal(ksp, ksp->viewerFinalRes, ksp->formatFinalRes));
962:   if (ksp->viewMat) PetscCall(ObjectView((PetscObject)mat, ksp->viewerMat, ksp->formatMat));
963:   if (ksp->viewPMat) PetscCall(ObjectView((PetscObject)pmat, ksp->viewerPMat, ksp->formatPMat));
964:   if (ksp->viewRhs) PetscCall(ObjectView((PetscObject)ksp->vec_rhs, ksp->viewerRhs, ksp->formatRhs));
965:   if (ksp->viewSol) PetscCall(ObjectView((PetscObject)ksp->vec_sol, ksp->viewerSol, ksp->formatSol));
966:   if (ksp->view) PetscCall(ObjectView((PetscObject)ksp, ksp->viewer, ksp->format));
967:   if (ksp->viewDScale) PetscCall(ObjectView((PetscObject)ksp->diagonal, ksp->viewerDScale, ksp->formatDScale));
968:   if (ksp->viewMatExp) {
969:     Mat A, B;

971:     PetscCall(PCGetOperators(ksp->pc, &A, NULL));
972:     if (ksp->transpose_solve) {
973:       Mat AT;

975:       PetscCall(MatCreateTranspose(A, &AT));
976:       PetscCall(MatComputeOperator(AT, MATAIJ, &B));
977:       PetscCall(MatDestroy(&AT));
978:     } else {
979:       PetscCall(MatComputeOperator(A, MATAIJ, &B));
980:     }
981:     PetscCall(ObjectView((PetscObject)B, ksp->viewerMatExp, ksp->formatMatExp));
982:     PetscCall(MatDestroy(&B));
983:   }
984:   if (ksp->viewPOpExp) {
985:     Mat B;

987:     PetscCall(KSPComputeOperator(ksp, MATAIJ, &B));
988:     PetscCall(ObjectView((PetscObject)B, ksp->viewerPOpExp, ksp->formatPOpExp));
989:     PetscCall(MatDestroy(&B));
990:   }

992:   if (inXisinB) {
993:     PetscCall(VecCopy(x, b));
994:     PetscCall(VecDestroy(&x));
995:   }
996:   PetscCall(PetscObjectSAWsBlock((PetscObject)ksp));
997:   if (ksp->errorifnotconverged && ksp->reason < 0 && ((level == 1) || (ksp->reason != KSP_DIVERGED_ITS))) {
998:     PCFailedReason reason;

1000:     PetscCheck(ksp->reason == KSP_DIVERGED_PC_FAILED, comm, PETSC_ERR_NOT_CONVERGED, "KSPSolve%s() has not converged, reason %s", !ksp->transpose_solve ? "" : "Transpose", KSPConvergedReasons[ksp->reason]);
1001:     PetscCall(PCGetFailedReason(ksp->pc, &reason));
1002:     SETERRQ(comm, PETSC_ERR_NOT_CONVERGED, "KSPSolve%s() has not converged, reason %s PC failed due to %s", !ksp->transpose_solve ? "" : "Transpose", KSPConvergedReasons[ksp->reason], PCFailedReasons[reason]);
1003:   }
1004:   level--;
1005:   PetscFunctionReturn(PETSC_SUCCESS);
1006: }

1008: /*@
1009:   KSPSolve - Solves a linear system associated with `KSP` object

1011:   Collective

1013:   Input Parameters:
1014: + ksp - iterative solver obtained from `KSPCreate()`
1015: . b   - the right-hand side vector
1016: - x   - the solution (this may be the same vector as `b`, then `b` will be overwritten with the answer)

1018:   Options Database Keys:
1019: + -ksp_view_eigenvalues                      - compute preconditioned operators eigenvalues
1020: . -ksp_view_eigenvalues_explicit             - compute the eigenvalues by forming the dense operator and using LAPACK
1021: . -ksp_view_mat binary                       - save matrix to the default binary viewer
1022: . -ksp_view_pmat binary                      - save matrix used to build preconditioner to the default binary viewer
1023: . -ksp_view_rhs binary                       - save right-hand side vector to the default binary viewer
1024: . -ksp_view_solution binary                  - save computed solution vector to the default binary viewer
1025:                                                (can be read later with src/ksp/tutorials/ex10.c for testing solvers)
1026: . -ksp_view_mat_explicit                     - for matrix-free operators, computes the matrix entries and views them
1027: . -ksp_view_preconditioned_operator_explicit - computes the product of the preconditioner and matrix as an explicit matrix and views it
1028: . -ksp_converged_reason                      - print reason for converged or diverged, also prints number of iterations
1029: . -ksp_view_final_residual                   - print 2-norm of true linear system residual at the end of the solution process
1030: . -ksp_error_if_not_converged                - stop the program as soon as an error is detected in a `KSPSolve()`
1031: . -ksp_view_pre                              - print the ksp data structure before the system solution
1032: - -ksp_view                                  - print the ksp data structure at the end of the system solution

1034:   Level: beginner

1036:   Notes:
1037:   See `KSPSetFromOptions()` for additional options database keys that affect `KSPSolve()`

1039:   If one uses `KSPSetDM()` then `x` or `b` need not be passed. Use `KSPGetSolution()` to access the solution in this case.

1041:   The operator is specified with `KSPSetOperators()`.

1043:   `KSPSolve()` will normally return without generating an error regardless of whether the linear system was solved or if constructing the preconditioner failed.
1044:   Call `KSPGetConvergedReason()` to determine if the solver converged or failed and why. The option -ksp_error_if_not_converged or function `KSPSetErrorIfNotConverged()`
1045:   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
1046:   it may be fine that inner solvers in the preconditioner do not converge during the solution process.

1048:   The number of iterations can be obtained from `KSPGetIterationNumber()`.

1050:   If you provide a matrix that has a `MatSetNullSpace()` and `MatSetTransposeNullSpace()` this will use that information to solve singular systems
1051:   in the least squares sense with a norm minimizing solution.

1053:   $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()`).

1055:   `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
1056:   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
1057:   direction thus the solution which is a linear combination of the search directions has no component in the nullspace(A).

1059:   We recommend always using `KSPGMRES` for such singular systems.
1060:   If $ nullspace(A) = nullspace(A^T)$ (note symmetric matrices always satisfy this property) then both left and right preconditioning will work
1061:   If $nullspace(A) \neq nullspace(A^T)$ then left preconditioning will work but right preconditioning may not work (or it may).

1063:   Developer Notes:
1064:   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
1065:   $ 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
1066:   such as diagonal scaling we cannot apply the inverse of the preconditioner to a vector and thus cannot compute $nullspace(AB)$.

1068:   If using a direct method (e.g., via the `KSP` solver
1069:   `KSPPREONLY` and a preconditioner such as `PCLU` or `PCCHOLESKY` then usually one iteration of the `KSP` method will be needed for convergence.

1071:   To solve a linear system with the transpose of the matrix use `KSPSolveTranspose()`.

1073:   Understanding Convergence\:
1074:   The manual pages `KSPMonitorSet()`, `KSPComputeEigenvalues()`, and
1075:   `KSPComputeEigenvaluesExplicitly()` provide information on additional
1076:   options to monitor convergence and print eigenvalue information.

1078: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
1079:           `KSPSolveTranspose()`, `KSPGetIterationNumber()`, `MatNullSpaceCreate()`, `MatSetNullSpace()`, `MatSetTransposeNullSpace()`, `KSP`,
1080:           `KSPConvergedReasonView()`, `KSPCheckSolve()`, `KSPSetErrorIfNotConverged()`
1081: @*/
1082: PetscErrorCode KSPSolve(KSP ksp, Vec b, Vec x)
1083: {
1084:   PetscBool isPCMPI;

1086:   PetscFunctionBegin;
1090:   ksp->transpose_solve = PETSC_FALSE;
1091:   PetscCall(KSPSolve_Private(ksp, b, x));
1092:   PetscCall(PetscObjectTypeCompare((PetscObject)ksp->pc, PCMPI, &isPCMPI));
1093:   if (PCMPIServerActive && isPCMPI) {
1094:     KSP subksp;

1096:     PetscCall(PCMPIGetKSP(ksp->pc, &subksp));
1097:     ksp->its    = subksp->its;
1098:     ksp->reason = subksp->reason;
1099:   }
1100:   PetscFunctionReturn(PETSC_SUCCESS);
1101: }

1103: /*@
1104:   KSPSolveTranspose - Solves a linear system with the transpose of the matrix associated with the `KSP` object, $ A^T x = b$.

1106:   Collective

1108:   Input Parameters:
1109: + ksp - iterative solver obtained from `KSPCreate()`
1110: . b   - right-hand side vector
1111: - x   - solution vector

1113:   Level: developer

1115:   Note:
1116:   For complex numbers this solve the non-Hermitian transpose system.

1118:   Developer Note:
1119:   We need to implement a `KSPSolveHermitianTranspose()`

1121: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPDestroy()`, `KSPSetTolerances()`, `KSPConvergedDefault()`,
1122:           `KSPSolve()`, `KSP`, `KSPSetOperators()`
1123: @*/
1124: PetscErrorCode KSPSolveTranspose(KSP ksp, Vec b, Vec x)
1125: {
1126:   PetscFunctionBegin;
1130:   if (ksp->transpose.use_explicittranspose) {
1131:     Mat J, Jpre;
1132:     PetscCall(KSPGetOperators(ksp, &J, &Jpre));
1133:     if (!ksp->transpose.reuse_transpose) {
1134:       PetscCall(MatTranspose(J, MAT_INITIAL_MATRIX, &ksp->transpose.AT));
1135:       if (J != Jpre) PetscCall(MatTranspose(Jpre, MAT_INITIAL_MATRIX, &ksp->transpose.BT));
1136:       ksp->transpose.reuse_transpose = PETSC_TRUE;
1137:     } else {
1138:       PetscCall(MatTranspose(J, MAT_REUSE_MATRIX, &ksp->transpose.AT));
1139:       if (J != Jpre) PetscCall(MatTranspose(Jpre, MAT_REUSE_MATRIX, &ksp->transpose.BT));
1140:     }
1141:     if (J == Jpre && ksp->transpose.BT != ksp->transpose.AT) {
1142:       PetscCall(PetscObjectReference((PetscObject)ksp->transpose.AT));
1143:       ksp->transpose.BT = ksp->transpose.AT;
1144:     }
1145:     PetscCall(KSPSetOperators(ksp, ksp->transpose.AT, ksp->transpose.BT));
1146:   } else {
1147:     ksp->transpose_solve = PETSC_TRUE;
1148:   }
1149:   PetscCall(KSPSolve_Private(ksp, b, x));
1150:   PetscFunctionReturn(PETSC_SUCCESS);
1151: }

1153: static PetscErrorCode KSPViewFinalMatResidual_Internal(KSP ksp, Mat B, Mat X, PetscViewer viewer, PetscViewerFormat format, PetscInt shift)
1154: {
1155:   Mat        A, R;
1156:   PetscReal *norms;
1157:   PetscInt   i, N;
1158:   PetscBool  flg;

1160:   PetscFunctionBegin;
1161:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &flg));
1162:   if (flg) {
1163:     PetscCall(PCGetOperators(ksp->pc, &A, NULL));
1164:     if (!ksp->transpose_solve) PetscCall(MatMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DETERMINE, &R));
1165:     else PetscCall(MatTransposeMatMult(A, X, MAT_INITIAL_MATRIX, PETSC_DETERMINE, &R));
1166:     PetscCall(MatAYPX(R, -1.0, B, SAME_NONZERO_PATTERN));
1167:     PetscCall(MatGetSize(R, NULL, &N));
1168:     PetscCall(PetscMalloc1(N, &norms));
1169:     PetscCall(MatGetColumnNorms(R, NORM_2, norms));
1170:     PetscCall(MatDestroy(&R));
1171:     for (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]));
1172:     PetscCall(PetscFree(norms));
1173:   }
1174:   PetscFunctionReturn(PETSC_SUCCESS);
1175: }

1177: static PetscErrorCode KSPMatSolve_Private(KSP ksp, Mat B, Mat X)
1178: {
1179:   Mat       A, P, vB, vX;
1180:   Vec       cb, cx;
1181:   PetscInt  n1, N1, n2, N2, Bbn = PETSC_DECIDE;
1182:   PetscBool match;

1184:   PetscFunctionBegin;
1188:   PetscCheckSameComm(ksp, 1, B, 2);
1189:   PetscCheckSameComm(ksp, 1, X, 3);
1190:   PetscCheckSameType(B, 2, X, 3);
1191:   PetscCheck(B->assembled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
1192:   MatCheckPreallocated(X, 3);
1193:   if (!X->assembled) {
1194:     PetscCall(MatSetOption(X, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
1195:     PetscCall(MatAssemblyBegin(X, MAT_FINAL_ASSEMBLY));
1196:     PetscCall(MatAssemblyEnd(X, MAT_FINAL_ASSEMBLY));
1197:   }
1198:   PetscCheck(B != X, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_IDN, "B and X must be different matrices");
1199:   PetscCheck(!ksp->transpose_solve || !ksp->transpose.use_explicittranspose, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "KSPMatSolveTranspose() does not support -ksp_use_explicittranspose");
1200:   PetscCall(KSPGetOperators(ksp, &A, &P));
1201:   PetscCall(MatGetLocalSize(B, NULL, &n2));
1202:   PetscCall(MatGetLocalSize(X, NULL, &n1));
1203:   PetscCall(MatGetSize(B, NULL, &N2));
1204:   PetscCall(MatGetSize(X, NULL, &N1));
1205:   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);
1206:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &match, MATSEQDENSE, MATMPIDENSE, ""));
1207:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of right-hand sides not stored in a dense Mat");
1208:   PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)X, &match, MATSEQDENSE, MATMPIDENSE, ""));
1209:   PetscCheck(match, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Provided block of solutions not stored in a dense Mat");
1210:   PetscCall(KSPSetUp(ksp));
1211:   PetscCall(KSPSetUpOnBlocks(ksp));
1212:   if (ksp->ops->matsolve) {
1213:     level++;
1214:     if (ksp->guess_zero) PetscCall(MatZeroEntries(X));
1215:     PetscCall(PetscLogEventBegin(!ksp->transpose_solve ? KSP_MatSolve : KSP_MatSolveTranspose, ksp, B, X, 0));
1216:     PetscCall(KSPGetMatSolveBatchSize(ksp, &Bbn));
1217:     /* by default, do a single solve with all columns */
1218:     if (Bbn == PETSC_DECIDE) Bbn = N2;
1219:     else PetscCheck(Bbn >= 1, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "KSPMatSolve() batch size %" PetscInt_FMT " must be positive", Bbn);
1220:     PetscCall(PetscInfo(ksp, "KSP type %s solving using batches of width at most %" PetscInt_FMT "\n", ((PetscObject)ksp)->type_name, Bbn));
1221:     /* if -ksp_matsolve_batch_size is greater than the actual number of columns, do a single solve with all columns */
1222:     if (Bbn >= N2) {
1223:       PetscUseTypeMethod(ksp, matsolve, B, X);
1224:       if (ksp->viewFinalRes) PetscCall(KSPViewFinalMatResidual_Internal(ksp, B, X, ksp->viewerFinalRes, ksp->formatFinalRes, 0));

1226:       PetscCall(KSPConvergedReasonViewFromOptions(ksp));

1228:       if (ksp->viewRate) {
1229:         PetscCall(PetscViewerPushFormat(ksp->viewerRate, PETSC_VIEWER_DEFAULT));
1230:         PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
1231:         PetscCall(PetscViewerPopFormat(ksp->viewerRate));
1232:       }
1233:     } else {
1234:       for (n2 = 0; n2 < N2; n2 += Bbn) {
1235:         PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, n2, PetscMin(n2 + Bbn, N2), &vB));
1236:         PetscCall(MatDenseGetSubMatrix(X, PETSC_DECIDE, PETSC_DECIDE, n2, PetscMin(n2 + Bbn, N2), &vX));
1237:         PetscUseTypeMethod(ksp, matsolve, vB, vX);
1238:         if (ksp->viewFinalRes) PetscCall(KSPViewFinalMatResidual_Internal(ksp, vB, vX, ksp->viewerFinalRes, ksp->formatFinalRes, n2));

1240:         PetscCall(KSPConvergedReasonViewFromOptions(ksp));

1242:         if (ksp->viewRate) {
1243:           PetscCall(PetscViewerPushFormat(ksp->viewerRate, PETSC_VIEWER_DEFAULT));
1244:           PetscCall(KSPConvergedRateView(ksp, ksp->viewerRate));
1245:           PetscCall(PetscViewerPopFormat(ksp->viewerRate));
1246:         }
1247:         PetscCall(MatDenseRestoreSubMatrix(B, &vB));
1248:         PetscCall(MatDenseRestoreSubMatrix(X, &vX));
1249:       }
1250:     }
1251:     if (ksp->viewMat) PetscCall(ObjectView((PetscObject)A, ksp->viewerMat, ksp->formatMat));
1252:     if (ksp->viewPMat) PetscCall(ObjectView((PetscObject)P, ksp->viewerPMat, ksp->formatPMat));
1253:     if (ksp->viewRhs) PetscCall(ObjectView((PetscObject)B, ksp->viewerRhs, ksp->formatRhs));
1254:     if (ksp->viewSol) PetscCall(ObjectView((PetscObject)X, ksp->viewerSol, ksp->formatSol));
1255:     if (ksp->view) PetscCall(KSPView(ksp, ksp->viewer));
1256:     PetscCall(PetscLogEventEnd(!ksp->transpose_solve ? KSP_MatSolve : KSP_MatSolveTranspose, ksp, B, X, 0));
1257:     if (ksp->errorifnotconverged && ksp->reason < 0 && (level == 1 || ksp->reason != KSP_DIVERGED_ITS)) {
1258:       PCFailedReason reason;

1260:       PetscCheck(ksp->reason == KSP_DIVERGED_PC_FAILED, PetscObjectComm((PetscObject)ksp), PETSC_ERR_NOT_CONVERGED, "KSPMatSolve%s() has not converged, reason %s", !ksp->transpose_solve ? "" : "Transpose", KSPConvergedReasons[ksp->reason]);
1261:       PetscCall(PCGetFailedReason(ksp->pc, &reason));
1262:       SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_NOT_CONVERGED, "KSPMatSolve%s() has not converged, reason %s PC failed due to %s", !ksp->transpose_solve ? "" : "Transpose", KSPConvergedReasons[ksp->reason], PCFailedReasons[reason]);
1263:     }
1264:     level--;
1265:   } else {
1266:     PetscCall(PetscInfo(ksp, "KSP type %s solving column by column\n", ((PetscObject)ksp)->type_name));
1267:     for (n2 = 0; n2 < N2; ++n2) {
1268:       PetscCall(MatDenseGetColumnVecRead(B, n2, &cb));
1269:       PetscCall(MatDenseGetColumnVecWrite(X, n2, &cx));
1270:       PetscCall(KSPSolve_Private(ksp, cb, cx));
1271:       PetscCall(MatDenseRestoreColumnVecWrite(X, n2, &cx));
1272:       PetscCall(MatDenseRestoreColumnVecRead(B, n2, &cb));
1273:     }
1274:   }
1275:   PetscFunctionReturn(PETSC_SUCCESS);
1276: }

1278: /*@
1279:   KSPMatSolve - Solves a linear system with multiple right-hand sides stored as a `MATDENSE`.

1281:   Input Parameters:
1282: + ksp - iterative solver
1283: - B   - block of right-hand sides

1285:   Output Parameter:
1286: . X - block of solutions

1288:   Level: intermediate

1290:   Notes:
1291:   This is a stripped-down version of `KSPSolve()`, which only handles `-ksp_view`, `-ksp_converged_reason`, `-ksp_converged_rate`, and `-ksp_view_final_residual`.

1293:   Unlike with `KSPSolve()`, `B` and `X` must be different matrices.

1295: .seealso: [](ch_ksp), `KSPSolve()`, `MatMatSolve()`, `KSPMatSolveTranspose()`, `MATDENSE`, `KSPHPDDM`, `PCBJACOBI`, `PCASM`, `KSPSetMatSolveBatchSize()`
1296: @*/
1297: PetscErrorCode KSPMatSolve(KSP ksp, Mat B, Mat X)
1298: {
1299:   PetscFunctionBegin;
1300:   ksp->transpose_solve = PETSC_FALSE;
1301:   PetscCall(KSPMatSolve_Private(ksp, B, X));
1302:   PetscFunctionReturn(PETSC_SUCCESS);
1303: }

1305: /*@
1306:   KSPMatSolveTranspose - Solves a linear system with the transposed matrix with multiple right-hand sides stored as a `MATDENSE`.

1308:   Input Parameters:
1309: + ksp - iterative solver
1310: - B   - block of right-hand sides

1312:   Output Parameter:
1313: . X - block of solutions

1315:   Level: intermediate

1317:   Notes:
1318:   This is a stripped-down version of `KSPSolveTranspose()`, which only handles `-ksp_view`, `-ksp_converged_reason`, `-ksp_converged_rate`, and `-ksp_view_final_residual`.

1320:   Unlike `KSPSolveTranspose()`,
1321:   `B` and `X` must be different matrices and the transposed matrix cannot be assembled explicitly for the user.

1323: .seealso: [](ch_ksp), `KSPSolveTranspose()`, `MatMatTransposeSolve()`, `KSPMatSolve()`, `MATDENSE`, `KSPHPDDM`, `PCBJACOBI`, `PCASM`
1324: @*/
1325: PetscErrorCode KSPMatSolveTranspose(KSP ksp, Mat B, Mat X)
1326: {
1327:   PetscFunctionBegin;
1328:   ksp->transpose_solve = PETSC_TRUE;
1329:   PetscCall(KSPMatSolve_Private(ksp, B, X));
1330:   PetscFunctionReturn(PETSC_SUCCESS);
1331: }

1333: /*@
1334:   KSPSetMatSolveBatchSize - Sets the maximum number of columns treated simultaneously in `KSPMatSolve()`.

1336:   Logically Collective

1338:   Input Parameters:
1339: + ksp - the `KSP` iterative solver
1340: - bs  - batch size

1342:   Level: advanced

1344:   Note:
1345:   Using a larger block size can improve the efficiency of the solver.

1347: .seealso: [](ch_ksp), `KSPMatSolve()`, `KSPGetMatSolveBatchSize()`, `-mat_mumps_icntl_27`, `-matmatmult_Bbn`
1348: @*/
1349: PetscErrorCode KSPSetMatSolveBatchSize(KSP ksp, PetscInt bs)
1350: {
1351:   PetscFunctionBegin;
1354:   ksp->nmax = bs;
1355:   PetscFunctionReturn(PETSC_SUCCESS);
1356: }

1358: /*@
1359:   KSPGetMatSolveBatchSize - Gets the maximum number of columns treated simultaneously in `KSPMatSolve()`.

1361:   Input Parameter:
1362: . ksp - iterative solver context

1364:   Output Parameter:
1365: . bs - batch size

1367:   Level: advanced

1369: .seealso: [](ch_ksp), `KSPMatSolve()`, `KSPSetMatSolveBatchSize()`, `-mat_mumps_icntl_27`, `-matmatmult_Bbn`
1370: @*/
1371: PetscErrorCode KSPGetMatSolveBatchSize(KSP ksp, PetscInt *bs)
1372: {
1373:   PetscFunctionBegin;
1375:   PetscAssertPointer(bs, 2);
1376:   *bs = ksp->nmax;
1377:   PetscFunctionReturn(PETSC_SUCCESS);
1378: }

1380: /*@
1381:   KSPResetViewers - Resets all the viewers set from the options database during `KSPSetFromOptions()`

1383:   Collective

1385:   Input Parameter:
1386: . ksp - the `KSP` iterative solver context obtained from `KSPCreate()`

1388:   Level: beginner

1390: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSPSetFromOptions()`, `KSP`
1391: @*/
1392: PetscErrorCode KSPResetViewers(KSP ksp)
1393: {
1394:   PetscFunctionBegin;
1396:   if (!ksp) PetscFunctionReturn(PETSC_SUCCESS);
1397:   PetscCall(PetscViewerDestroy(&ksp->viewer));
1398:   PetscCall(PetscViewerDestroy(&ksp->viewerPre));
1399:   PetscCall(PetscViewerDestroy(&ksp->viewerRate));
1400:   PetscCall(PetscViewerDestroy(&ksp->viewerMat));
1401:   PetscCall(PetscViewerDestroy(&ksp->viewerPMat));
1402:   PetscCall(PetscViewerDestroy(&ksp->viewerRhs));
1403:   PetscCall(PetscViewerDestroy(&ksp->viewerSol));
1404:   PetscCall(PetscViewerDestroy(&ksp->viewerMatExp));
1405:   PetscCall(PetscViewerDestroy(&ksp->viewerEV));
1406:   PetscCall(PetscViewerDestroy(&ksp->viewerSV));
1407:   PetscCall(PetscViewerDestroy(&ksp->viewerEVExp));
1408:   PetscCall(PetscViewerDestroy(&ksp->viewerFinalRes));
1409:   PetscCall(PetscViewerDestroy(&ksp->viewerPOpExp));
1410:   PetscCall(PetscViewerDestroy(&ksp->viewerDScale));
1411:   ksp->view         = PETSC_FALSE;
1412:   ksp->viewPre      = PETSC_FALSE;
1413:   ksp->viewMat      = PETSC_FALSE;
1414:   ksp->viewPMat     = PETSC_FALSE;
1415:   ksp->viewRhs      = PETSC_FALSE;
1416:   ksp->viewSol      = PETSC_FALSE;
1417:   ksp->viewMatExp   = PETSC_FALSE;
1418:   ksp->viewEV       = PETSC_FALSE;
1419:   ksp->viewSV       = PETSC_FALSE;
1420:   ksp->viewEVExp    = PETSC_FALSE;
1421:   ksp->viewFinalRes = PETSC_FALSE;
1422:   ksp->viewPOpExp   = PETSC_FALSE;
1423:   ksp->viewDScale   = PETSC_FALSE;
1424:   PetscFunctionReturn(PETSC_SUCCESS);
1425: }

1427: /*@
1428:   KSPReset - Removes any allocated `Vec` and `Mat` from the `KSP` data structures.

1430:   Collective

1432:   Input Parameter:
1433: . ksp - iterative solver obtained from `KSPCreate()`

1435:   Level: intermediate

1437:   Notes:
1438:   Any options set in the `KSP`, including those set with `KSPSetFromOptions()` remain.

1440:   Call `KSPReset()` only before you call `KSPSetOperators()` with a different sized matrix than the previous matrix used with the `KSP`.

1442: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSP`
1443: @*/
1444: PetscErrorCode KSPReset(KSP ksp)
1445: {
1446:   PetscFunctionBegin;
1448:   if (!ksp) PetscFunctionReturn(PETSC_SUCCESS);
1449:   PetscTryTypeMethod(ksp, reset);
1450:   if (ksp->pc) PetscCall(PCReset(ksp->pc));
1451:   if (ksp->guess) {
1452:     KSPGuess guess = ksp->guess;
1453:     PetscTryTypeMethod(guess, reset);
1454:   }
1455:   PetscCall(VecDestroyVecs(ksp->nwork, &ksp->work));
1456:   PetscCall(VecDestroy(&ksp->vec_rhs));
1457:   PetscCall(VecDestroy(&ksp->vec_sol));
1458:   PetscCall(VecDestroy(&ksp->diagonal));
1459:   PetscCall(VecDestroy(&ksp->truediagonal));

1461:   ksp->setupstage = KSP_SETUP_NEW;
1462:   ksp->nmax       = PETSC_DECIDE;
1463:   PetscFunctionReturn(PETSC_SUCCESS);
1464: }

1466: /*@
1467:   KSPDestroy - Destroys a `KSP` context.

1469:   Collective

1471:   Input Parameter:
1472: . ksp - iterative solver obtained from `KSPCreate()`

1474:   Level: beginner

1476: .seealso: [](ch_ksp), `KSPCreate()`, `KSPSetUp()`, `KSPSolve()`, `KSP`
1477: @*/
1478: PetscErrorCode KSPDestroy(KSP *ksp)
1479: {
1480:   PC pc;

1482:   PetscFunctionBegin;
1483:   if (!*ksp) PetscFunctionReturn(PETSC_SUCCESS);
1485:   if (--((PetscObject)*ksp)->refct > 0) {
1486:     *ksp = NULL;
1487:     PetscFunctionReturn(PETSC_SUCCESS);
1488:   }

1490:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ksp));

1492:   /*
1493:    Avoid a cascading call to PCReset(ksp->pc) from the following call:
1494:    PCReset() shouldn't be called from KSPDestroy() as it is unprotected by pc's
1495:    refcount (and may be shared, e.g., by other ksps).
1496:    */
1497:   pc         = (*ksp)->pc;
1498:   (*ksp)->pc = NULL;
1499:   PetscCall(KSPReset(*ksp));
1500:   PetscCall(KSPResetViewers(*ksp));
1501:   (*ksp)->pc = pc;
1502:   PetscTryTypeMethod(*ksp, destroy);

1504:   if ((*ksp)->transpose.use_explicittranspose) {
1505:     PetscCall(MatDestroy(&(*ksp)->transpose.AT));
1506:     PetscCall(MatDestroy(&(*ksp)->transpose.BT));
1507:     (*ksp)->transpose.reuse_transpose = PETSC_FALSE;
1508:   }

1510:   PetscCall(KSPGuessDestroy(&(*ksp)->guess));
1511:   PetscCall(DMDestroy(&(*ksp)->dm));
1512:   PetscCall(PCDestroy(&(*ksp)->pc));
1513:   PetscCall(PetscFree((*ksp)->res_hist_alloc));
1514:   PetscCall(PetscFree((*ksp)->err_hist_alloc));
1515:   if ((*ksp)->convergeddestroy) PetscCall((*(*ksp)->convergeddestroy)((*ksp)->cnvP));
1516:   PetscCall(KSPMonitorCancel(*ksp));
1517:   PetscCall(KSPConvergedReasonViewCancel(*ksp));
1518:   PetscCall(PetscHeaderDestroy(ksp));
1519:   PetscFunctionReturn(PETSC_SUCCESS);
1520: }

1522: /*@
1523:   KSPSetPCSide - Sets the preconditioning side.

1525:   Logically Collective

1527:   Input Parameter:
1528: . ksp - iterative solver obtained from `KSPCreate()`

1530:   Output Parameter:
1531: . side - the preconditioning side, where side is one of
1532: .vb
1533:   PC_LEFT      - left preconditioning (default)
1534:   PC_RIGHT     - right preconditioning
1535:   PC_SYMMETRIC - symmetric preconditioning
1536: .ve

1538:   Options Database Key:
1539: . -ksp_pc_side <right,left,symmetric> - `KSP` preconditioner side

1541:   Level: intermediate

1543:   Notes:
1544:   Left preconditioning is used by default for most Krylov methods except `KSPFGMRES` which only supports right preconditioning.

1546:   For methods changing the side of the preconditioner changes the norm type that is used, see `KSPSetNormType()`.

1548:   Symmetric preconditioning is currently available only for the `KSPQCG` method. However, note that
1549:   symmetric preconditioning can be emulated by using either right or left
1550:   preconditioning, modifying the application of the matrix (with a custom `Mat` argument to `KSPSetOperators()`,
1551:   and using a pre 'KSPSetPreSolve()` or post processing `KSPSetPostSolve()` step).

1553:   Setting the `PCSide` often affects the default norm type. See `KSPSetNormType()` for details.

1555: .seealso: [](ch_ksp), `KSPGetPCSide()`, `KSPSetNormType()`, `KSPGetNormType()`, `KSP`, `KSPSetPreSolve()`, `KSPSetPostSolve()`
1556: @*/
1557: PetscErrorCode KSPSetPCSide(KSP ksp, PCSide side)
1558: {
1559:   PetscFunctionBegin;
1562:   ksp->pc_side = ksp->pc_side_set = side;
1563:   PetscFunctionReturn(PETSC_SUCCESS);
1564: }

1566: /*@
1567:   KSPGetPCSide - Gets the preconditioning side.

1569:   Not Collective

1571:   Input Parameter:
1572: . ksp - iterative solver obtained from `KSPCreate()`

1574:   Output Parameter:
1575: . side - the preconditioning side, where side is one of
1576: .vb
1577:   PC_LEFT      - left preconditioning (default)
1578:   PC_RIGHT     - right preconditioning
1579:   PC_SYMMETRIC - symmetric preconditioning
1580: .ve

1582:   Level: intermediate

1584: .seealso: [](ch_ksp), `KSPSetPCSide()`, `KSP`
1585: @*/
1586: PetscErrorCode KSPGetPCSide(KSP ksp, PCSide *side)
1587: {
1588:   PetscFunctionBegin;
1590:   PetscAssertPointer(side, 2);
1591:   PetscCall(KSPSetUpNorms_Private(ksp, PETSC_TRUE, &ksp->normtype, &ksp->pc_side));
1592:   *side = ksp->pc_side;
1593:   PetscFunctionReturn(PETSC_SUCCESS);
1594: }

1596: /*@
1597:   KSPGetTolerances - Gets the relative, absolute, divergence, and maximum
1598:   iteration tolerances used by the default `KSP` convergence tests.

1600:   Not Collective

1602:   Input Parameter:
1603: . ksp - the Krylov subspace context

1605:   Output Parameters:
1606: + rtol   - the relative convergence tolerance
1607: . abstol - the absolute convergence tolerance
1608: . dtol   - the divergence tolerance
1609: - maxits - maximum number of iterations

1611:   Level: intermediate

1613:   Note:
1614:   The user can specify `NULL` for any parameter that is not needed.

1616: .seealso: [](ch_ksp), `KSPSetTolerances()`, `KSP`, `KSPSetMinimumIterations()`, `KSPGetMinimumIterations()`
1617: @*/
1618: PetscErrorCode KSPGetTolerances(KSP ksp, PeOp PetscReal *rtol, PeOp PetscReal *abstol, PeOp PetscReal *dtol, PeOp PetscInt *maxits)
1619: {
1620:   PetscFunctionBegin;
1622:   if (abstol) *abstol = ksp->abstol;
1623:   if (rtol) *rtol = ksp->rtol;
1624:   if (dtol) *dtol = ksp->divtol;
1625:   if (maxits) *maxits = ksp->max_it;
1626:   PetscFunctionReturn(PETSC_SUCCESS);
1627: }

1629: /*@
1630:   KSPSetTolerances - Sets the relative, absolute, divergence, and maximum
1631:   iteration tolerances used by the default `KSP` convergence testers.

1633:   Logically Collective

1635:   Input Parameters:
1636: + ksp    - the Krylov subspace context
1637: . rtol   - the relative convergence tolerance, relative decrease in the (possibly preconditioned) residual norm
1638: . abstol - the absolute convergence tolerance   absolute size of the (possibly preconditioned) residual norm
1639: . dtol   - the divergence tolerance,   amount (possibly preconditioned) residual norm can increase before `KSPConvergedDefault()` concludes that the method is diverging
1640: - maxits - maximum number of iterations to use

1642:   Options Database Keys:
1643: + -ksp_atol <abstol>   - Sets `abstol`
1644: . -ksp_rtol <rtol>     - Sets `rtol`
1645: . -ksp_divtol <dtol>   - Sets `dtol`
1646: - -ksp_max_it <maxits> - Sets `maxits`

1648:   Level: intermediate

1650:   Notes:
1651:   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.
1652:   The norm used depends on the `KSPNormType` that has been set with `KSPSetNormType()`, the default depends on the `KSPType` used.

1654:   All parameters must be non-negative.

1656:   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).

1658:   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.

1660:   For `dtol` and `maxits` use `PETSC_UMLIMITED` to indicate there is no upper bound on these values

1662:   See `KSPConvergedDefault()` for details how these parameters are used in the default convergence test.  See also `KSPSetConvergenceTest()`
1663:   for setting user-defined stopping criteria.

1665:   Fortran Note:
1666:   Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`

1668: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetMinimumIterations()`
1669: @*/
1670: PetscErrorCode KSPSetTolerances(KSP ksp, PetscReal rtol, PetscReal abstol, PetscReal dtol, PetscInt maxits)
1671: {
1672:   PetscFunctionBegin;

1679:   if (rtol == (PetscReal)PETSC_DETERMINE) {
1680:     ksp->rtol = ksp->default_rtol;
1681:   } else if (rtol != (PetscReal)PETSC_CURRENT) {
1682:     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);
1683:     ksp->rtol = rtol;
1684:   }
1685:   if (abstol == (PetscReal)PETSC_DETERMINE) {
1686:     ksp->abstol = ksp->default_abstol;
1687:   } else if (abstol != (PetscReal)PETSC_CURRENT) {
1688:     PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
1689:     ksp->abstol = abstol;
1690:   }
1691:   if (dtol == (PetscReal)PETSC_DETERMINE) {
1692:     ksp->divtol = ksp->default_divtol;
1693:   } else if (dtol == (PetscReal)PETSC_UNLIMITED) {
1694:     ksp->divtol = PETSC_MAX_REAL;
1695:   } else if (dtol != (PetscReal)PETSC_CURRENT) {
1696:     PetscCheck(dtol >= 0.0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be larger than 1.0", (double)dtol);
1697:     ksp->divtol = dtol;
1698:   }
1699:   if (maxits == PETSC_DETERMINE) {
1700:     ksp->max_it = ksp->default_max_it;
1701:   } else if (maxits == PETSC_UNLIMITED) {
1702:     ksp->max_it = PETSC_INT_MAX;
1703:   } else if (maxits != PETSC_CURRENT) {
1704:     PetscCheck(maxits >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxits);
1705:     ksp->max_it = maxits;
1706:   }
1707:   PetscFunctionReturn(PETSC_SUCCESS);
1708: }

1710: /*@
1711:   KSPSetMinimumIterations - Sets the minimum number of iterations to use, regardless of the tolerances

1713:   Logically Collective

1715:   Input Parameters:
1716: + ksp   - the Krylov subspace context
1717: - minit - minimum number of iterations to use

1719:   Options Database Key:
1720: . -ksp_min_it <minits> - Sets `minit`

1722:   Level: intermediate

1724:   Notes:
1725:   Use `KSPSetTolerances()` to set a variety of other tolerances

1727:   See `KSPConvergedDefault()` for details on how these parameters are used in the default convergence test. See also `KSPSetConvergenceTest()`
1728:   for setting user-defined stopping criteria.

1730:   If the initial residual norm is small enough solvers may return immediately without computing any improvement to the solution. Using this routine
1731:   prevents that which usually ensures the solution is changed (often minimally) from the previous solution. This option may be used with ODE integrators
1732:   to ensure the integrator does not fall into a false steady-state solution of the ODE.

1734: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetTolerances()`, `KSPGetMinimumIterations()`
1735: @*/
1736: PetscErrorCode KSPSetMinimumIterations(KSP ksp, PetscInt minit)
1737: {
1738:   PetscFunctionBegin;

1742:   PetscCheck(minit >= 0, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Minimum number of iterations %" PetscInt_FMT " must be non-negative", minit);
1743:   ksp->min_it = minit;
1744:   PetscFunctionReturn(PETSC_SUCCESS);
1745: }

1747: /*@
1748:   KSPGetMinimumIterations - Gets the minimum number of iterations to use, regardless of the tolerances, that was set with `KSPSetMinimumIterations()` or `-ksp_min_it`

1750:   Not Collective

1752:   Input Parameter:
1753: . ksp - the Krylov subspace context

1755:   Output Parameter:
1756: . minit - minimum number of iterations to use

1758:   Level: intermediate

1760: .seealso: [](ch_ksp), `KSPGetTolerances()`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSP`, `KSPSetTolerances()`, `KSPSetMinimumIterations()`
1761: @*/
1762: PetscErrorCode KSPGetMinimumIterations(KSP ksp, PetscInt *minit)
1763: {
1764:   PetscFunctionBegin;
1766:   PetscAssertPointer(minit, 2);

1768:   *minit = ksp->min_it;
1769:   PetscFunctionReturn(PETSC_SUCCESS);
1770: }

1772: /*@
1773:   KSPSetInitialGuessNonzero - Tells the iterative solver that the
1774:   initial guess is nonzero; otherwise `KSP` assumes the initial guess
1775:   is to be zero (and thus zeros it out before solving).

1777:   Logically Collective

1779:   Input Parameters:
1780: + ksp - iterative solver obtained from `KSPCreate()`
1781: - flg - ``PETSC_TRUE`` indicates the guess is non-zero, `PETSC_FALSE` indicates the guess is zero

1783:   Options Database Key:
1784: . -ksp_initial_guess_nonzero <true,false> - use nonzero initial guess

1786:   Level: beginner

1788: .seealso: [](ch_ksp), `KSPGetInitialGuessNonzero()`, `KSPGuessSetType()`, `KSPGuessType`, `KSP`
1789: @*/
1790: PetscErrorCode KSPSetInitialGuessNonzero(KSP ksp, PetscBool flg)
1791: {
1792:   PetscFunctionBegin;
1795:   ksp->guess_zero = (PetscBool)!flg;
1796:   PetscFunctionReturn(PETSC_SUCCESS);
1797: }

1799: /*@
1800:   KSPGetInitialGuessNonzero - Determines whether the `KSP` solver is using
1801:   a zero initial guess.

1803:   Not Collective

1805:   Input Parameter:
1806: . ksp - iterative solver obtained from `KSPCreate()`

1808:   Output Parameter:
1809: . flag - `PETSC_TRUE` if guess is nonzero, else `PETSC_FALSE`

1811:   Level: intermediate

1813: .seealso: [](ch_ksp), `KSPSetInitialGuessNonzero()`, `KSP`
1814: @*/
1815: PetscErrorCode KSPGetInitialGuessNonzero(KSP ksp, PetscBool *flag)
1816: {
1817:   PetscFunctionBegin;
1819:   PetscAssertPointer(flag, 2);
1820:   if (ksp->guess_zero) *flag = PETSC_FALSE;
1821:   else *flag = PETSC_TRUE;
1822:   PetscFunctionReturn(PETSC_SUCCESS);
1823: }

1825: /*@
1826:   KSPSetErrorIfNotConverged - Causes `KSPSolve()` to generate an error if the solver has not converged as soon as the error is detected.

1828:   Logically Collective

1830:   Input Parameters:
1831: + ksp - iterative solver obtained from `KSPCreate()`
1832: - flg - `PETSC_TRUE` indicates you want the error generated

1834:   Options Database Key:
1835: . -ksp_error_if_not_converged <true,false> - generate an error and stop the program

1837:   Level: intermediate

1839:   Notes:
1840:   Normally PETSc continues if a linear solver fails to converge, you can call `KSPGetConvergedReason()` after a `KSPSolve()`
1841:   to determine if it has converged. This functionality is mostly helpful while running in a debugger (`-start_in_debugger`) to determine exactly where
1842:   the failure occurs and why.

1844:   A `KSP_DIVERGED_ITS` will not generate an error in a `KSPSolve()` inside a nested linear solver

1846: .seealso: [](ch_ksp), `KSPGetErrorIfNotConverged()`, `KSP`
1847: @*/
1848: PetscErrorCode KSPSetErrorIfNotConverged(KSP ksp, PetscBool flg)
1849: {
1850:   PetscFunctionBegin;
1853:   ksp->errorifnotconverged = flg;
1854:   PetscFunctionReturn(PETSC_SUCCESS);
1855: }

1857: /*@
1858:   KSPGetErrorIfNotConverged - Will `KSPSolve()` generate an error if the solver does not converge?

1860:   Not Collective

1862:   Input Parameter:
1863: . ksp - iterative solver obtained from KSPCreate()

1865:   Output Parameter:
1866: . flag - `PETSC_TRUE` if it will generate an error, else `PETSC_FALSE`

1868:   Level: intermediate

1870: .seealso: [](ch_ksp), `KSPSetErrorIfNotConverged()`, `KSP`
1871: @*/
1872: PetscErrorCode KSPGetErrorIfNotConverged(KSP ksp, PetscBool *flag)
1873: {
1874:   PetscFunctionBegin;
1876:   PetscAssertPointer(flag, 2);
1877:   *flag = ksp->errorifnotconverged;
1878:   PetscFunctionReturn(PETSC_SUCCESS);
1879: }

1881: /*@
1882:   KSPSetInitialGuessKnoll - Tells the iterative solver to use `PCApply()` on the right hand side vector to compute the initial guess (The Knoll trick)

1884:   Logically Collective

1886:   Input Parameters:
1887: + ksp - iterative solver obtained from `KSPCreate()`
1888: - flg - `PETSC_TRUE` or `PETSC_FALSE`

1890:   Level: advanced

1892:   Developer Note:
1893:   The Knoll trick is not currently implemented using the `KSPGuess` class which provides a variety of ways of computing
1894:   an initial guess based on previous solves.

1896: .seealso: [](ch_ksp), `KSPGetInitialGuessKnoll()`, `KSPGuess`, `KSPSetInitialGuessNonzero()`, `KSPGetInitialGuessNonzero()`, `KSP`
1897: @*/
1898: PetscErrorCode KSPSetInitialGuessKnoll(KSP ksp, PetscBool flg)
1899: {
1900:   PetscFunctionBegin;
1903:   ksp->guess_knoll = flg;
1904:   PetscFunctionReturn(PETSC_SUCCESS);
1905: }

1907: /*@
1908:   KSPGetInitialGuessKnoll - Determines whether the `KSP` solver is using the Knoll trick (using PCApply(pc,b,...) to compute
1909:   the initial guess

1911:   Not Collective

1913:   Input Parameter:
1914: . ksp - iterative solver obtained from `KSPCreate()`

1916:   Output Parameter:
1917: . flag - `PETSC_TRUE` if using Knoll trick, else `PETSC_FALSE`

1919:   Level: advanced

1921: .seealso: [](ch_ksp), `KSPSetInitialGuessKnoll()`, `KSPSetInitialGuessNonzero()`, `KSPGetInitialGuessNonzero()`, `KSP`
1922: @*/
1923: PetscErrorCode KSPGetInitialGuessKnoll(KSP ksp, PetscBool *flag)
1924: {
1925:   PetscFunctionBegin;
1927:   PetscAssertPointer(flag, 2);
1928:   *flag = ksp->guess_knoll;
1929:   PetscFunctionReturn(PETSC_SUCCESS);
1930: }

1932: /*@
1933:   KSPGetComputeSingularValues - Gets the flag indicating whether the extreme singular
1934:   values will be calculated via a Lanczos or Arnoldi process as the linear
1935:   system is solved.

1937:   Not Collective

1939:   Input Parameter:
1940: . ksp - iterative solver obtained from `KSPCreate()`

1942:   Output Parameter:
1943: . flg - `PETSC_TRUE` or `PETSC_FALSE`

1945:   Options Database Key:
1946: . -ksp_monitor_singular_value - Activates `KSPSetComputeSingularValues()`

1948:   Level: advanced

1950:   Notes:
1951:   This option is not valid for `KSPType`.

1953:   Many users may just want to use the monitoring routine
1954:   `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
1955:   to print the singular values at each iteration of the linear solve.

1957: .seealso: [](ch_ksp), `KSPComputeExtremeSingularValues()`, `KSPMonitorSingularValue()`, `KSP`
1958: @*/
1959: PetscErrorCode KSPGetComputeSingularValues(KSP ksp, PetscBool *flg)
1960: {
1961:   PetscFunctionBegin;
1963:   PetscAssertPointer(flg, 2);
1964:   *flg = ksp->calc_sings;
1965:   PetscFunctionReturn(PETSC_SUCCESS);
1966: }

1968: /*@
1969:   KSPSetComputeSingularValues - Sets a flag so that the extreme singular
1970:   values will be calculated via a Lanczos or Arnoldi process as the linear
1971:   system is solved.

1973:   Logically Collective

1975:   Input Parameters:
1976: + ksp - iterative solver obtained from `KSPCreate()`
1977: - flg - `PETSC_TRUE` or `PETSC_FALSE`

1979:   Options Database Key:
1980: . -ksp_monitor_singular_value - Activates `KSPSetComputeSingularValues()`

1982:   Level: advanced

1984:   Notes:
1985:   This option is not valid for all iterative methods.

1987:   Many users may just want to use the monitoring routine
1988:   `KSPMonitorSingularValue()` (which can be set with option `-ksp_monitor_singular_value`)
1989:   to print the singular values at each iteration of the linear solve.

1991:   Consider using the excellant package SLEPc for accurate efficient computations of singular or eigenvalues.

1993: .seealso: [](ch_ksp), `KSPComputeExtremeSingularValues()`, `KSPMonitorSingularValue()`, `KSP`, `KSPSetComputeRitz()`
1994: @*/
1995: PetscErrorCode KSPSetComputeSingularValues(KSP ksp, PetscBool flg)
1996: {
1997:   PetscFunctionBegin;
2000:   ksp->calc_sings = flg;
2001:   PetscFunctionReturn(PETSC_SUCCESS);
2002: }

2004: /*@
2005:   KSPGetComputeEigenvalues - Gets the flag indicating that the extreme eigenvalues
2006:   values will be calculated via a Lanczos or Arnoldi process as the linear
2007:   system is solved.

2009:   Not Collective

2011:   Input Parameter:
2012: . ksp - iterative solver obtained from `KSPCreate()`

2014:   Output Parameter:
2015: . flg - `PETSC_TRUE` or `PETSC_FALSE`

2017:   Level: advanced

2019:   Note:
2020:   Currently this option is not valid for all iterative methods.

2022: .seealso: [](ch_ksp), `KSPComputeEigenvalues()`, `KSPComputeEigenvaluesExplicitly()`, `KSP`, `KSPSetComputeRitz()`
2023: @*/
2024: PetscErrorCode KSPGetComputeEigenvalues(KSP ksp, PetscBool *flg)
2025: {
2026:   PetscFunctionBegin;
2028:   PetscAssertPointer(flg, 2);
2029:   *flg = ksp->calc_sings;
2030:   PetscFunctionReturn(PETSC_SUCCESS);
2031: }

2033: /*@
2034:   KSPSetComputeEigenvalues - Sets a flag so that the extreme eigenvalues
2035:   values will be calculated via a Lanczos or Arnoldi process as the linear
2036:   system is solved.

2038:   Logically Collective

2040:   Input Parameters:
2041: + ksp - iterative solver obtained from `KSPCreate()`
2042: - flg - `PETSC_TRUE` or `PETSC_FALSE`

2044:   Level: advanced

2046:   Note:
2047:   Currently this option is not valid for all iterative methods.

2049:   Consider using the excellant package SLEPc for accurate efficient computations of singular or eigenvalues.

2051: .seealso: [](ch_ksp), `KSPComputeEigenvalues()`, `KSPComputeEigenvaluesExplicitly()`, `KSP`, `KSPSetComputeRitz()`
2052: @*/
2053: PetscErrorCode KSPSetComputeEigenvalues(KSP ksp, PetscBool flg)
2054: {
2055:   PetscFunctionBegin;
2058:   ksp->calc_sings = flg;
2059:   PetscFunctionReturn(PETSC_SUCCESS);
2060: }

2062: /*@
2063:   KSPSetComputeRitz - Sets a flag so that the Ritz or harmonic Ritz pairs
2064:   will be calculated via a Lanczos or Arnoldi process as the linear
2065:   system is solved.

2067:   Logically Collective

2069:   Input Parameters:
2070: + ksp - iterative solver obtained from `KSPCreate()`
2071: - flg - `PETSC_TRUE` or `PETSC_FALSE`

2073:   Level: advanced

2075:   Note:
2076:   Currently this option is only valid for the `KSPGMRES` method.

2078: .seealso: [](ch_ksp), `KSPComputeRitz()`, `KSP`, `KSPComputeEigenvalues()`, `KSPComputeExtremeSingularValues()`
2079: @*/
2080: PetscErrorCode KSPSetComputeRitz(KSP ksp, PetscBool flg)
2081: {
2082:   PetscFunctionBegin;
2085:   ksp->calc_ritz = flg;
2086:   PetscFunctionReturn(PETSC_SUCCESS);
2087: }

2089: /*@
2090:   KSPGetRhs - Gets the right-hand-side vector for the linear system to
2091:   be solved.

2093:   Not Collective

2095:   Input Parameter:
2096: . ksp - iterative solver obtained from `KSPCreate()`

2098:   Output Parameter:
2099: . r - right-hand-side vector

2101:   Level: developer

2103: .seealso: [](ch_ksp), `KSPGetSolution()`, `KSPSolve()`, `KSP`
2104: @*/
2105: PetscErrorCode KSPGetRhs(KSP ksp, Vec *r)
2106: {
2107:   PetscFunctionBegin;
2109:   PetscAssertPointer(r, 2);
2110:   *r = ksp->vec_rhs;
2111:   PetscFunctionReturn(PETSC_SUCCESS);
2112: }

2114: /*@
2115:   KSPGetSolution - Gets the location of the solution for the
2116:   linear system to be solved.

2118:   Not Collective

2120:   Input Parameter:
2121: . ksp - iterative solver obtained from `KSPCreate()`

2123:   Output Parameter:
2124: . v - solution vector

2126:   Level: developer

2128:   Note:
2129:   If this is called during a `KSPSolve()` the vector's values may not represent the solution
2130:   to the linear system.

2132: .seealso: [](ch_ksp), `KSPGetRhs()`, `KSPBuildSolution()`, `KSPSolve()`, `KSP`
2133: @*/
2134: PetscErrorCode KSPGetSolution(KSP ksp, Vec *v)
2135: {
2136:   PetscFunctionBegin;
2138:   PetscAssertPointer(v, 2);
2139:   *v = ksp->vec_sol;
2140:   PetscFunctionReturn(PETSC_SUCCESS);
2141: }

2143: /*@
2144:   KSPSetPC - Sets the preconditioner to be used to calculate the
2145:   application of the preconditioner on a vector into a `KSP`.

2147:   Collective

2149:   Input Parameters:
2150: + ksp - the `KSP` iterative solver obtained from `KSPCreate()`
2151: - pc  - the preconditioner object (if `NULL` it returns the `PC` currently held by the `KSP`)

2153:   Level: developer

2155:   Note:
2156:   This routine is almost never used since `KSP` creates its own `PC` when needed.
2157:   Use `KSPGetPC()` to retrieve the preconditioner context instead of creating a new one.

2159: .seealso: [](ch_ksp), `KSPGetPC()`, `KSP`
2160: @*/
2161: PetscErrorCode KSPSetPC(KSP ksp, PC pc)
2162: {
2163:   PetscFunctionBegin;
2165:   if (pc) {
2167:     PetscCheckSameComm(ksp, 1, pc, 2);
2168:   }
2169:   if (ksp->pc != pc && ksp->setupstage) ksp->setupstage = KSP_SETUP_NEWMATRIX;
2170:   PetscCall(PetscObjectReference((PetscObject)pc));
2171:   PetscCall(PCDestroy(&ksp->pc));
2172:   ksp->pc = pc;
2173:   PetscFunctionReturn(PETSC_SUCCESS);
2174: }

2176: PETSC_INTERN PetscErrorCode PCCreate_MPI(PC);

2178: // PetscClangLinter pragma disable: -fdoc-internal-linkage
2179: /*@C
2180:    KSPCheckPCMPI - Checks if `-mpi_linear_solver_server` is active and the `PC` should be changed to `PCMPI`

2182:    Collective, No Fortran Support

2184:    Input Parameter:
2185: .  ksp - iterative solver obtained from `KSPCreate()`

2187:    Level: developer

2189: .seealso: [](ch_ksp), `KSPSetPC()`, `KSP`, `PCMPIServerBegin()`, `PCMPIServerEnd()`
2190: @*/
2191: PETSC_INTERN PetscErrorCode KSPCheckPCMPI(KSP ksp)
2192: {
2193:   PetscBool isPCMPI;

2195:   PetscFunctionBegin;
2197:   PetscCall(PetscObjectTypeCompare((PetscObject)ksp->pc, PCMPI, &isPCMPI));
2198:   if (PCMPIServerActive && ksp->nestlevel == 0 && !isPCMPI) {
2199:     const char *prefix;
2200:     char       *found = NULL;

2202:     PetscCall(KSPGetOptionsPrefix(ksp, &prefix));
2203:     if (prefix) PetscCall(PetscStrstr(prefix, "mpi_linear_solver_server_", &found));
2204:     if (!found) PetscCall(KSPAppendOptionsPrefix(ksp, "mpi_linear_solver_server_"));
2205:     PetscCall(PetscInfo(NULL, "In MPI Linear Solver Server and detected (root) PC that must be changed to PCMPI\n"));
2206:     PetscCall(PCSetType(ksp->pc, PCMPI));
2207:   }
2208:   PetscFunctionReturn(PETSC_SUCCESS);
2209: }

2211: /*@
2212:   KSPGetPC - Returns a pointer to the preconditioner context with the `KSP`

2214:   Not Collective

2216:   Input Parameter:
2217: . ksp - iterative solver obtained from `KSPCreate()`

2219:   Output Parameter:
2220: . pc - preconditioner context

2222:   Level: beginner

2224:   Note:
2225:   The `PC` is created if it does not already exist.

2227:   Developer Note:
2228:   Calls `KSPCheckPCMPI()` to check if the `KSP` is effected by `-mpi_linear_solver_server`

2230: .seealso: [](ch_ksp), `KSPSetPC()`, `KSP`, `PC`
2231: @*/
2232: PetscErrorCode KSPGetPC(KSP ksp, PC *pc)
2233: {
2234:   PetscFunctionBegin;
2236:   PetscAssertPointer(pc, 2);
2237:   if (!ksp->pc) {
2238:     PetscCall(PCCreate(PetscObjectComm((PetscObject)ksp), &ksp->pc));
2239:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ksp->pc, (PetscObject)ksp, 0));
2240:     PetscCall(PetscObjectSetOptions((PetscObject)ksp->pc, ((PetscObject)ksp)->options));
2241:     PetscCall(PCSetKSPNestLevel(ksp->pc, ksp->nestlevel));
2242:   }
2243:   PetscCall(KSPCheckPCMPI(ksp));
2244:   *pc = ksp->pc;
2245:   PetscFunctionReturn(PETSC_SUCCESS);
2246: }

2248: /*@
2249:   KSPMonitor - runs the user provided monitor routines, if they exist

2251:   Collective

2253:   Input Parameters:
2254: + ksp   - iterative solver obtained from `KSPCreate()`
2255: . it    - iteration number
2256: - rnorm - relative norm of the residual

2258:   Level: developer

2260:   Notes:
2261:   This routine is called by the `KSP` implementations.
2262:   It does not typically need to be called by the user.

2264:   For Krylov methods that do not keep a running value of the current solution (such as `KSPGMRES`) this
2265:   cannot be called after the `KSPConvergedReason` has been set but before the final solution has been computed.

2267: .seealso: [](ch_ksp), `KSPMonitorSet()`
2268: @*/
2269: PetscErrorCode KSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm)
2270: {
2271:   PetscInt i, n = ksp->numbermonitors;

2273:   PetscFunctionBegin;
2274:   for (i = 0; i < n; i++) PetscCall((*ksp->monitor[i])(ksp, it, rnorm, ksp->monitorcontext[i]));
2275:   PetscFunctionReturn(PETSC_SUCCESS);
2276: }

2278: /*@C
2279:   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,
2280:   the residual norm computed in a `KSPSolve()`

2282:   Logically Collective

2284:   Input Parameters:
2285: + ksp            - iterative solver obtained from `KSPCreate()`
2286: . monitor        - pointer to function (if this is `NULL`, it turns off monitoring
2287: . ctx            - [optional] context for private data for the monitor routine (use `NULL` if no context is needed)
2288: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

2290:   Calling sequence of `monitor`:
2291: + ksp   - iterative solver obtained from `KSPCreate()`
2292: . it    - iteration number
2293: . rnorm - (estimated) 2-norm of (preconditioned) residual
2294: - ctx   - optional monitoring context, as set by `KSPMonitorSet()`

2296:   Options Database Keys:
2297: + -ksp_monitor                             - sets `KSPMonitorResidual()`
2298: . -ksp_monitor draw                        - sets `KSPMonitorResidualDraw()` and plots residual
2299: . -ksp_monitor draw::draw_lg               - sets `KSPMonitorResidualDrawLG()` and plots residual
2300: . -ksp_monitor_pause_final                 - Pauses any graphics when the solve finishes (only works for internal monitors)
2301: . -ksp_monitor_true_residual               - sets `KSPMonitorTrueResidual()`
2302: . -ksp_monitor_true_residual draw::draw_lg - sets `KSPMonitorTrueResidualDrawLG()` and plots residual
2303: . -ksp_monitor_max                         - sets `KSPMonitorTrueResidualMax()`
2304: . -ksp_monitor_singular_value              - sets `KSPMonitorSingularValue()`
2305: - -ksp_monitor_cancel                      - cancels all monitors that have been hardwired into a code by calls to `KSPMonitorSet()`, but
2306:                                              does not cancel those set via the options database.

2308:   Level: beginner

2310:   Notes:
2311:   The options database option `-ksp_monitor` and related options are the easiest way to turn on `KSP` iteration monitoring

2313:   `KSPMonitorRegister()` provides a way to associate an options database key with `KSP` monitor function.

2315:   The default is to do no monitoring.  To print the residual, or preconditioned
2316:   residual if `KSPSetNormType`(ksp,`KSP_NORM_PRECONDITIONED`) was called, use
2317:   `KSPMonitorResidual()` as the monitoring routine, with a `PETSCVIEWERASCII` as the
2318:   context.

2320:   Several different monitoring routines may be set by calling
2321:   `KSPMonitorSet()` multiple times; all will be called in the
2322:   order in which they were set.

2324:   Fortran Note:
2325:   Only a single monitor function can be set for each `KSP` object

2327: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSPMonitorRegister()`, `KSPMonitorCancel()`, `KSP`, `PetscCtxDestroyFn`
2328: @*/
2329: PetscErrorCode KSPMonitorSet(KSP ksp, PetscErrorCode (*monitor)(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx), void *ctx, PetscCtxDestroyFn *monitordestroy)
2330: {
2331:   PetscInt  i;
2332:   PetscBool identical;

2334:   PetscFunctionBegin;
2336:   for (i = 0; i < ksp->numbermonitors; i++) {
2337:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))monitor, ctx, monitordestroy, (PetscErrorCode (*)(void))ksp->monitor[i], ksp->monitorcontext[i], ksp->monitordestroy[i], &identical));
2338:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
2339:   }
2340:   PetscCheck(ksp->numbermonitors < MAXKSPMONITORS, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Too many KSP monitors set");
2341:   ksp->monitor[ksp->numbermonitors]          = monitor;
2342:   ksp->monitordestroy[ksp->numbermonitors]   = monitordestroy;
2343:   ksp->monitorcontext[ksp->numbermonitors++] = ctx;
2344:   PetscFunctionReturn(PETSC_SUCCESS);
2345: }

2347: /*@
2348:   KSPMonitorCancel - Clears all monitors for a `KSP` object.

2350:   Logically Collective

2352:   Input Parameter:
2353: . ksp - iterative solver obtained from `KSPCreate()`

2355:   Options Database Key:
2356: . -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.

2358:   Level: intermediate

2360: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSPMonitorSet()`, `KSP`
2361: @*/
2362: PetscErrorCode KSPMonitorCancel(KSP ksp)
2363: {
2364:   PetscInt i;

2366:   PetscFunctionBegin;
2368:   for (i = 0; i < ksp->numbermonitors; i++) {
2369:     if (ksp->monitordestroy[i]) PetscCall((*ksp->monitordestroy[i])(&ksp->monitorcontext[i]));
2370:   }
2371:   ksp->numbermonitors = 0;
2372:   PetscFunctionReturn(PETSC_SUCCESS);
2373: }

2375: /*@C
2376:   KSPGetMonitorContext - Gets the monitoring context, as set by `KSPMonitorSet()` for the FIRST monitor only.

2378:   Not Collective

2380:   Input Parameter:
2381: . ksp - iterative solver obtained from `KSPCreate()`

2383:   Output Parameter:
2384: . ctx - monitoring context

2386:   Level: intermediate

2388: .seealso: [](ch_ksp), `KSPMonitorResidual()`, `KSP`
2389: @*/
2390: PetscErrorCode KSPGetMonitorContext(KSP ksp, void *ctx)
2391: {
2392:   PetscFunctionBegin;
2394:   *(void **)ctx = ksp->monitorcontext[0];
2395:   PetscFunctionReturn(PETSC_SUCCESS);
2396: }

2398: /*@
2399:   KSPSetResidualHistory - Sets the array used to hold the residual history.
2400:   If set, this array will contain the residual norms computed at each
2401:   iteration of the solver.

2403:   Not Collective

2405:   Input Parameters:
2406: + ksp   - iterative solver obtained from `KSPCreate()`
2407: . a     - array to hold history
2408: . na    - size of `a`
2409: - reset - `PETSC_TRUE` indicates the history counter is reset to zero
2410:            for each new linear solve

2412:   Level: advanced

2414:   Notes:
2415:   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.
2416:   If 'a' is `NULL` then space is allocated for the history. If 'na' `PETSC_DECIDE` or (deprecated) `PETSC_DEFAULT` then a
2417:   default array of length 10,000 is allocated.

2419:   If the array is not long enough then once the iterations is longer than the array length `KSPSolve()` stops recording the history

2421: .seealso: [](ch_ksp), `KSPGetResidualHistory()`, `KSP`
2422: @*/
2423: PetscErrorCode KSPSetResidualHistory(KSP ksp, PetscReal a[], PetscCount na, PetscBool reset)
2424: {
2425:   PetscFunctionBegin;

2428:   PetscCall(PetscFree(ksp->res_hist_alloc));
2429:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2430:     ksp->res_hist     = a;
2431:     ksp->res_hist_max = na;
2432:   } else {
2433:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->res_hist_max = (size_t)na;
2434:     else ksp->res_hist_max = 10000; /* like default ksp->max_it */
2435:     PetscCall(PetscCalloc1(ksp->res_hist_max, &ksp->res_hist_alloc));

2437:     ksp->res_hist = ksp->res_hist_alloc;
2438:   }
2439:   ksp->res_hist_len   = 0;
2440:   ksp->res_hist_reset = reset;
2441:   PetscFunctionReturn(PETSC_SUCCESS);
2442: }

2444: /*@C
2445:   KSPGetResidualHistory - Gets the array used to hold the residual history and the number of residuals it contains.

2447:   Not Collective

2449:   Input Parameter:
2450: . ksp - iterative solver obtained from `KSPCreate()`

2452:   Output Parameters:
2453: + a  - pointer to array to hold history (or `NULL`)
2454: - na - number of used entries in a (or `NULL`). Note this has different meanings depending on the `reset` argument to `KSPSetResidualHistory()`

2456:   Level: advanced

2458:   Note:
2459:   This array is borrowed and should not be freed by the caller.

2461:   Can only be called after a `KSPSetResidualHistory()` otherwise `a` and `na` are set to `NULL` and zero

2463:   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
2464:   returned with `KSPGetIterationNumber()`.

2466:   Some Krylov methods may not compute the final residual norm when convergence is declared because the maximum number of iterations allowed has been reached.
2467:   In this situation, when `reset` was `PETSC_TRUE`, `na` will then equal the number of iterations reported with `KSPGetIterationNumber()`

2469:   Some Krylov methods (such as `KSPSTCG`), under certain circumstances, do not compute the final residual norm. In this situation, when `reset` was `PETSC_TRUE`,
2470:   `na` will then equal the number of iterations reported with `KSPGetIterationNumber()`

2472:   `KSPBCGSL` does not record the residual norms for the "subiterations" hence the results from `KSPGetResidualHistory()` and `KSPGetIterationNumber()` will be different

2474:   Fortran Note:
2475:   Call `KSPRestoreResidualHistory()` when access to the history is no longer needed.

2477: .seealso: [](ch_ksp), `KSPSetResidualHistory()`, `KSP`, `KSPGetIterationNumber()`, `KSPSTCG`, `KSPBCGSL`
2478: @*/
2479: PetscErrorCode KSPGetResidualHistory(KSP ksp, const PetscReal *a[], PetscInt *na)
2480: {
2481:   PetscFunctionBegin;
2483:   if (a) *a = ksp->res_hist;
2484:   if (na) PetscCall(PetscIntCast(ksp->res_hist_len, na));
2485:   PetscFunctionReturn(PETSC_SUCCESS);
2486: }

2488: /*@
2489:   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.

2491:   Not Collective

2493:   Input Parameters:
2494: + ksp   - iterative solver obtained from `KSPCreate()`
2495: . a     - array to hold history
2496: . na    - size of `a`
2497: - reset - `PETSC_TRUE` indicates the history counter is reset to zero for each new linear solve

2499:   Level: advanced

2501:   Notes:
2502:   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.
2503:   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.

2505:   If the array is not long enough then once the iterations is longer than the array length `KSPSolve()` stops recording the history

2507: .seealso: [](ch_ksp), `KSPGetErrorHistory()`, `KSPSetResidualHistory()`, `KSP`
2508: @*/
2509: PetscErrorCode KSPSetErrorHistory(KSP ksp, PetscReal a[], PetscCount na, PetscBool reset)
2510: {
2511:   PetscFunctionBegin;

2514:   PetscCall(PetscFree(ksp->err_hist_alloc));
2515:   if (na != PETSC_DECIDE && na != PETSC_DEFAULT && a) {
2516:     ksp->err_hist     = a;
2517:     ksp->err_hist_max = na;
2518:   } else {
2519:     if (na != PETSC_DECIDE && na != PETSC_DEFAULT) ksp->err_hist_max = (size_t)na;
2520:     else ksp->err_hist_max = 10000; /* like default ksp->max_it */
2521:     PetscCall(PetscCalloc1(ksp->err_hist_max, &ksp->err_hist_alloc));
2522:     ksp->err_hist = ksp->err_hist_alloc;
2523:   }
2524:   ksp->err_hist_len   = 0;
2525:   ksp->err_hist_reset = reset;
2526:   PetscFunctionReturn(PETSC_SUCCESS);
2527: }

2529: /*@C
2530:   KSPGetErrorHistory - Gets the array used to hold the error history and the number of residuals it contains.

2532:   Not Collective

2534:   Input Parameter:
2535: . ksp - iterative solver obtained from `KSPCreate()`

2537:   Output Parameters:
2538: + a  - pointer to array to hold history (or `NULL`)
2539: - na - number of used entries in a (or `NULL`)

2541:   Level: advanced

2543:   Note:
2544:   This array is borrowed and should not be freed by the caller.
2545:   Can only be called after a `KSPSetErrorHistory()` otherwise `a` and `na` are set to `NULL` and zero

2547:   Fortran Note:
2548: .vb
2549:   PetscReal, pointer :: a(:)
2550: .ve

2552: .seealso: [](ch_ksp), `KSPSetErrorHistory()`, `KSPGetResidualHistory()`, `KSP`
2553: @*/
2554: PetscErrorCode KSPGetErrorHistory(KSP ksp, const PetscReal *a[], PetscInt *na)
2555: {
2556:   PetscFunctionBegin;
2558:   if (a) *a = ksp->err_hist;
2559:   if (na) PetscCall(PetscIntCast(ksp->err_hist_len, na));
2560:   PetscFunctionReturn(PETSC_SUCCESS);
2561: }

2563: /*@
2564:   KSPComputeConvergenceRate - Compute the convergence rate for the iteration <https:/en.wikipedia.org/wiki/Coefficient_of_determination>

2566:   Not Collective

2568:   Input Parameter:
2569: . ksp - The `KSP`

2571:   Output Parameters:
2572: + cr   - The residual contraction rate
2573: . rRsq - The coefficient of determination, $R^2$, indicating the linearity of the data
2574: . ce   - The error contraction rate
2575: - eRsq - The coefficient of determination, $R^2$, indicating the linearity of the data

2577:   Level: advanced

2579:   Note:
2580:   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,
2581:   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)}$,

2583: .seealso: [](ch_ksp), `KSP`, `KSPConvergedRateView()`
2584: @*/
2585: PetscErrorCode KSPComputeConvergenceRate(KSP ksp, PetscReal *cr, PetscReal *rRsq, PetscReal *ce, PetscReal *eRsq)
2586: {
2587:   PetscReal const *hist;
2588:   PetscReal       *x, *y, slope, intercept, mean = 0.0, var = 0.0, res = 0.0;
2589:   PetscInt         n, k;

2591:   PetscFunctionBegin;
2592:   if (cr || rRsq) {
2593:     PetscCall(KSPGetResidualHistory(ksp, &hist, &n));
2594:     if (!n) {
2595:       if (cr) *cr = 0.0;
2596:       if (rRsq) *rRsq = -1.0;
2597:     } else {
2598:       PetscCall(PetscMalloc2(n, &x, n, &y));
2599:       for (k = 0; k < n; ++k) {
2600:         x[k] = k;
2601:         y[k] = PetscLogReal(hist[k]);
2602:         mean += y[k];
2603:       }
2604:       mean /= n;
2605:       PetscCall(PetscLinearRegression(n, x, y, &slope, &intercept));
2606:       for (k = 0; k < n; ++k) {
2607:         res += PetscSqr(y[k] - (slope * x[k] + intercept));
2608:         var += PetscSqr(y[k] - mean);
2609:       }
2610:       PetscCall(PetscFree2(x, y));
2611:       if (cr) *cr = PetscExpReal(slope);
2612:       if (rRsq) *rRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2613:     }
2614:   }
2615:   if (ce || eRsq) {
2616:     PetscCall(KSPGetErrorHistory(ksp, &hist, &n));
2617:     if (!n) {
2618:       if (ce) *ce = 0.0;
2619:       if (eRsq) *eRsq = -1.0;
2620:     } else {
2621:       PetscCall(PetscMalloc2(n, &x, n, &y));
2622:       for (k = 0; k < n; ++k) {
2623:         x[k] = k;
2624:         y[k] = PetscLogReal(hist[k]);
2625:         mean += y[k];
2626:       }
2627:       mean /= n;
2628:       PetscCall(PetscLinearRegression(n, x, y, &slope, &intercept));
2629:       for (k = 0; k < n; ++k) {
2630:         res += PetscSqr(y[k] - (slope * x[k] + intercept));
2631:         var += PetscSqr(y[k] - mean);
2632:       }
2633:       PetscCall(PetscFree2(x, y));
2634:       if (ce) *ce = PetscExpReal(slope);
2635:       if (eRsq) *eRsq = var < PETSC_MACHINE_EPSILON ? 0.0 : 1.0 - (res / var);
2636:     }
2637:   }
2638:   PetscFunctionReturn(PETSC_SUCCESS);
2639: }

2641: /*@C
2642:   KSPSetConvergenceTest - Sets the function to be used to determine convergence of `KSPSolve()`

2644:   Logically Collective

2646:   Input Parameters:
2647: + ksp      - iterative solver obtained from `KSPCreate()`
2648: . converge - pointer to the function
2649: . ctx      - context for private data for the convergence routine (may be `NULL`)
2650: - destroy  - a routine for destroying the context (may be `NULL`)

2652:   Calling sequence of `converge`:
2653: + ksp    - iterative solver obtained from `KSPCreate()`
2654: . it     - iteration number
2655: . rnorm  - (estimated) 2-norm of (preconditioned) residual
2656: . reason - the reason why it has converged or diverged
2657: - ctx    - optional convergence context, as set by `KSPSetConvergenceTest()`

2659:   Calling sequence of `destroy`:
2660: . ctx - the context

2662:   Level: advanced

2664:   Notes:
2665:   Must be called after the `KSP` type has been set so put this after
2666:   a call to `KSPSetType()`, or `KSPSetFromOptions()`.

2668:   The default convergence test, `KSPConvergedDefault()`, aborts if the
2669:   residual grows to more than 10000 times the initial residual.

2671:   The default is a combination of relative and absolute tolerances.
2672:   The residual value that is tested may be an approximation; routines
2673:   that need exact values should compute them.

2675:   In the default PETSc convergence test, the precise values of reason
2676:   are macros such as `KSP_CONVERGED_RTOL`, which are defined in petscksp.h.

2678: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPGetConvergenceTest()`, `KSPGetAndClearConvergenceTest()`
2679: @*/
2680: PetscErrorCode KSPSetConvergenceTest(KSP ksp, PetscErrorCode (*converge)(KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason, void *ctx), void *ctx, PetscErrorCode (*destroy)(void *ctx))
2681: {
2682:   PetscFunctionBegin;
2684:   if (ksp->convergeddestroy) PetscCall((*ksp->convergeddestroy)(ksp->cnvP));
2685:   ksp->converged        = converge;
2686:   ksp->convergeddestroy = destroy;
2687:   ksp->cnvP             = ctx;
2688:   PetscFunctionReturn(PETSC_SUCCESS);
2689: }

2691: /*@C
2692:   KSPGetConvergenceTest - Gets the function to be used to determine convergence.

2694:   Logically Collective

2696:   Input Parameter:
2697: . ksp - iterative solver obtained from `KSPCreate()`

2699:   Output Parameters:
2700: + converge - pointer to convergence test function
2701: . ctx      - context for private data for the convergence routine (may be `NULL`)
2702: - destroy  - a routine for destroying the context (may be `NULL`)

2704:   Calling sequence of `converge`:
2705: + ksp    - iterative solver obtained from `KSPCreate()`
2706: . it     - iteration number
2707: . rnorm  - (estimated) 2-norm of (preconditioned) residual
2708: . reason - the reason why it has converged or diverged
2709: - ctx    - optional convergence context, as set by `KSPSetConvergenceTest()`

2711:   Calling sequence of `destroy`:
2712: . ctx - the convergence test context

2714:   Level: advanced

2716: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPSetConvergenceTest()`, `KSPGetAndClearConvergenceTest()`
2717: @*/
2718: PetscErrorCode KSPGetConvergenceTest(KSP ksp, PetscErrorCode (**converge)(KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason, void *ctx), void **ctx, PetscErrorCode (**destroy)(void *ctx))
2719: {
2720:   PetscFunctionBegin;
2722:   if (converge) *converge = ksp->converged;
2723:   if (destroy) *destroy = ksp->convergeddestroy;
2724:   if (ctx) *ctx = ksp->cnvP;
2725:   PetscFunctionReturn(PETSC_SUCCESS);
2726: }

2728: /*@C
2729:   KSPGetAndClearConvergenceTest - Gets the function to be used to determine convergence. Removes the current test without calling destroy on the test context

2731:   Logically Collective

2733:   Input Parameter:
2734: . ksp - iterative solver obtained from `KSPCreate()`

2736:   Output Parameters:
2737: + converge - pointer to convergence test function
2738: . ctx      - context for private data for the convergence routine
2739: - destroy  - a routine for destroying the context

2741:   Calling sequence of `converge`:
2742: + ksp    - iterative solver obtained from `KSPCreate()`
2743: . it     - iteration number
2744: . rnorm  - (estimated) 2-norm of (preconditioned) residual
2745: . reason - the reason why it has converged or diverged
2746: - ctx    - optional convergence context, as set by `KSPSetConvergenceTest()`

2748:   Calling sequence of `destroy`:
2749: . ctx - the convergence test context

2751:   Level: advanced

2753:   Note:
2754:   This is intended to be used to allow transferring the convergence test (and its context) to another testing object (for example another `KSP`)
2755:   and then calling `KSPSetConvergenceTest()` on this original `KSP`. If you just called `KSPGetConvergenceTest()` followed
2756:   by `KSPSetConvergenceTest()` the original context information
2757:   would be destroyed and hence the transferred context would be invalid and trigger a crash on use

2759: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPGetConvergenceContext()`, `KSPSetTolerances()`, `KSPSetConvergenceTest()`, `KSPGetConvergenceTest()`
2760: @*/
2761: PetscErrorCode KSPGetAndClearConvergenceTest(KSP ksp, PetscErrorCode (**converge)(KSP ksp, PetscInt it, PetscReal rnorm, KSPConvergedReason *reason, void *ctx), void **ctx, PetscErrorCode (**destroy)(void *ctx))
2762: {
2763:   PetscFunctionBegin;
2765:   *converge             = ksp->converged;
2766:   *destroy              = ksp->convergeddestroy;
2767:   *ctx                  = ksp->cnvP;
2768:   ksp->converged        = NULL;
2769:   ksp->cnvP             = NULL;
2770:   ksp->convergeddestroy = NULL;
2771:   PetscFunctionReturn(PETSC_SUCCESS);
2772: }

2774: /*@C
2775:   KSPGetConvergenceContext - Gets the convergence context set with `KSPSetConvergenceTest()`.

2777:   Not Collective

2779:   Input Parameter:
2780: . ksp - iterative solver obtained from `KSPCreate()`

2782:   Output Parameter:
2783: . ctx - monitoring context

2785:   Level: advanced

2787: .seealso: [](ch_ksp), `KSP`, `KSPConvergedDefault()`, `KSPSetConvergenceTest()`, `KSPGetConvergenceTest()`
2788: @*/
2789: PetscErrorCode KSPGetConvergenceContext(KSP ksp, void *ctx)
2790: {
2791:   PetscFunctionBegin;
2793:   *(void **)ctx = ksp->cnvP;
2794:   PetscFunctionReturn(PETSC_SUCCESS);
2795: }

2797: /*@
2798:   KSPBuildSolution - Builds the approximate solution in a vector provided.

2800:   Collective

2802:   Input Parameter:
2803: . ksp - iterative solver obtained from `KSPCreate()`

2805:   Output Parameter:
2806:    Provide exactly one of
2807: + v - location to stash solution, optional, otherwise pass `NULL`
2808: - V - the solution is returned in this location. This vector is created internally. This vector should NOT be destroyed by the user with `VecDestroy()`.

2810:   Level: developer

2812:   Notes:
2813:   This routine can be used in one of two ways
2814: .vb
2815:       KSPBuildSolution(ksp,NULL,&V);
2816:    or
2817:       KSPBuildSolution(ksp,v,NULL); or KSPBuildSolution(ksp,v,&v);
2818: .ve
2819:   In the first case an internal vector is allocated to store the solution
2820:   (the user cannot destroy this vector). In the second case the solution
2821:   is generated in the vector that the user provides. Note that for certain
2822:   methods, such as `KSPCG`, the second case requires a copy of the solution,
2823:   while in the first case the call is essentially free since it simply
2824:   returns the vector where the solution already is stored. For some methods
2825:   like `KSPGMRES` during the solve this is a reasonably expensive operation and should only be
2826:   used if truly needed.

2828: .seealso: [](ch_ksp), `KSPGetSolution()`, `KSPBuildResidual()`, `KSP`
2829: @*/
2830: PetscErrorCode KSPBuildSolution(KSP ksp, Vec v, Vec *V)
2831: {
2832:   PetscFunctionBegin;
2834:   PetscCheck(V || v, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_WRONG, "Must provide either v or V");
2835:   if (!V) V = &v;
2836:   if (ksp->reason != KSP_CONVERGED_ITERATING) {
2837:     if (!v) PetscCall(KSPGetSolution(ksp, V));
2838:     else PetscCall(VecCopy(ksp->vec_sol, v));
2839:   } else {
2840:     PetscUseTypeMethod(ksp, buildsolution, v, V);
2841:   }
2842:   PetscFunctionReturn(PETSC_SUCCESS);
2843: }

2845: /*@
2846:   KSPBuildResidual - Builds the residual in a vector provided.

2848:   Collective

2850:   Input Parameter:
2851: . ksp - iterative solver obtained from `KSPCreate()`

2853:   Output Parameters:
2854: + t - work vector.  If not provided then one is generated.
2855: . v - optional location to stash residual.  If `v` is not provided, then a location is generated.
2856: - V - the residual

2858:   Level: advanced

2860:   Note:
2861:   Regardless of whether or not `v` is provided, the residual is
2862:   returned in `V`.

2864: .seealso: [](ch_ksp), `KSP`, `KSPBuildSolution()`
2865: @*/
2866: PetscErrorCode KSPBuildResidual(KSP ksp, Vec t, Vec v, Vec *V)
2867: {
2868:   PetscBool flag = PETSC_FALSE;
2869:   Vec       w = v, tt = t;

2871:   PetscFunctionBegin;
2873:   if (!w) PetscCall(VecDuplicate(ksp->vec_rhs, &w));
2874:   if (!tt) {
2875:     PetscCall(VecDuplicate(ksp->vec_sol, &tt));
2876:     flag = PETSC_TRUE;
2877:   }
2878:   PetscUseTypeMethod(ksp, buildresidual, tt, w, V);
2879:   if (flag) PetscCall(VecDestroy(&tt));
2880:   PetscFunctionReturn(PETSC_SUCCESS);
2881: }

2883: /*@
2884:   KSPSetDiagonalScale - Tells `KSP` to symmetrically diagonally scale the system
2885:   before solving. This actually CHANGES the matrix (and right-hand side).

2887:   Logically Collective

2889:   Input Parameters:
2890: + ksp   - the `KSP` context
2891: - scale - `PETSC_TRUE` or `PETSC_FALSE`

2893:   Options Database Keys:
2894: + -ksp_diagonal_scale     - perform a diagonal scaling before the solve
2895: - -ksp_diagonal_scale_fix - scale the matrix back AFTER the solve

2897:   Level: advanced

2899:   Notes:
2900:   Scales the matrix by  $D^{-1/2}  A  D^{-1/2}  [D^{1/2} x ] = D^{-1/2} b $
2901:   where $D_{ii}$ is $1/abs(A_{ii}) $ unless $A_{ii}$ is zero and then it is 1.

2903:   BE CAREFUL with this routine: it actually scales the matrix and right
2904:   hand side that define the system. After the system is solved the matrix
2905:   and right-hand side remain scaled unless you use `KSPSetDiagonalScaleFix()`

2907:   This should NOT be used within the `SNES` solves if you are using a line
2908:   search.

2910:   If you use this with the `PCType` `PCEISENSTAT` preconditioner than you can
2911:   use the `PCEisenstatSetNoDiagonalScaling()` option, or `-pc_eisenstat_no_diagonal_scaling`
2912:   to save some unneeded, redundant flops.

2914: .seealso: [](ch_ksp), `KSPGetDiagonalScale()`, `KSPSetDiagonalScaleFix()`, `KSP`
2915: @*/
2916: PetscErrorCode KSPSetDiagonalScale(KSP ksp, PetscBool scale)
2917: {
2918:   PetscFunctionBegin;
2921:   ksp->dscale = scale;
2922:   PetscFunctionReturn(PETSC_SUCCESS);
2923: }

2925: /*@
2926:   KSPGetDiagonalScale - Checks if `KSP` solver scales the matrix and right-hand side, that is if `KSPSetDiagonalScale()` has been called

2928:   Not Collective

2930:   Input Parameter:
2931: . ksp - the `KSP` context

2933:   Output Parameter:
2934: . scale - `PETSC_TRUE` or `PETSC_FALSE`

2936:   Level: intermediate

2938: .seealso: [](ch_ksp), `KSP`, `KSPSetDiagonalScale()`, `KSPSetDiagonalScaleFix()`
2939: @*/
2940: PetscErrorCode KSPGetDiagonalScale(KSP ksp, PetscBool *scale)
2941: {
2942:   PetscFunctionBegin;
2944:   PetscAssertPointer(scale, 2);
2945:   *scale = ksp->dscale;
2946:   PetscFunctionReturn(PETSC_SUCCESS);
2947: }

2949: /*@
2950:   KSPSetDiagonalScaleFix - Tells `KSP` to diagonally scale the system back after solving.

2952:   Logically Collective

2954:   Input Parameters:
2955: + ksp - the `KSP` context
2956: - fix - `PETSC_TRUE` to scale back after the system solve, `PETSC_FALSE` to not
2957:          rescale (default)

2959:   Level: intermediate

2961:   Notes:
2962:   Must be called after `KSPSetDiagonalScale()`

2964:   Using this will slow things down, because it rescales the matrix before and
2965:   after each linear solve. This is intended mainly for testing to allow one
2966:   to easily get back the original system to make sure the solution computed is
2967:   accurate enough.

2969: .seealso: [](ch_ksp), `KSPGetDiagonalScale()`, `KSPSetDiagonalScale()`, `KSPGetDiagonalScaleFix()`, `KSP`
2970: @*/
2971: PetscErrorCode KSPSetDiagonalScaleFix(KSP ksp, PetscBool fix)
2972: {
2973:   PetscFunctionBegin;
2976:   ksp->dscalefix = fix;
2977:   PetscFunctionReturn(PETSC_SUCCESS);
2978: }

2980: /*@
2981:   KSPGetDiagonalScaleFix - Determines if `KSP` diagonally scales the system back after solving. That is `KSPSetDiagonalScaleFix()` has been called

2983:   Not Collective

2985:   Input Parameter:
2986: . ksp - the `KSP` context

2988:   Output Parameter:
2989: . fix - `PETSC_TRUE` to scale back after the system solve, `PETSC_FALSE` to not
2990:          rescale (default)

2992:   Level: intermediate

2994: .seealso: [](ch_ksp), `KSPGetDiagonalScale()`, `KSPSetDiagonalScale()`, `KSPSetDiagonalScaleFix()`, `KSP`
2995: @*/
2996: PetscErrorCode KSPGetDiagonalScaleFix(KSP ksp, PetscBool *fix)
2997: {
2998:   PetscFunctionBegin;
3000:   PetscAssertPointer(fix, 2);
3001:   *fix = ksp->dscalefix;
3002:   PetscFunctionReturn(PETSC_SUCCESS);
3003: }

3005: /*@C
3006:   KSPSetComputeOperators - set routine to compute the linear operators

3008:   Logically Collective

3010:   Input Parameters:
3011: + ksp  - the `KSP` context
3012: . func - function to compute the operators, see `KSPComputeOperatorsFn` for the calling sequence
3013: - ctx  - optional context

3015:   Level: beginner

3017:   Notes:
3018:   `func()` will be called automatically at the very next call to `KSPSolve()`. It will NOT be called at future `KSPSolve()` calls
3019:   unless either `KSPSetComputeOperators()` or `KSPSetOperators()` is called before that `KSPSolve()` is called. This allows the same system to be solved several times
3020:   with different right-hand side functions but is a confusing API since one might expect it to be called for each `KSPSolve()`

3022:   To reuse the same preconditioner for the next `KSPSolve()` and not compute a new one based on the most recently computed matrix call `KSPSetReusePreconditioner()`

3024:   Developer Note:
3025:   Perhaps this routine and `KSPSetComputeRHS()` could be combined into a new API that makes clear when new matrices are computing without requiring call this
3026:   routine to indicate when the new matrix should be computed.

3028: .seealso: [](ch_ksp), `KSP`, `KSPSetOperators()`, `KSPSetComputeRHS()`, `DMKSPSetComputeOperators()`, `KSPSetComputeInitialGuess()`, `KSPComputeOperatorsFn`
3029: @*/
3030: PetscErrorCode KSPSetComputeOperators(KSP ksp, KSPComputeOperatorsFn *func, void *ctx)
3031: {
3032:   DM dm;

3034:   PetscFunctionBegin;
3036:   PetscCall(KSPGetDM(ksp, &dm));
3037:   PetscCall(DMKSPSetComputeOperators(dm, func, ctx));
3038:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX;
3039:   PetscFunctionReturn(PETSC_SUCCESS);
3040: }

3042: /*@C
3043:   KSPSetComputeRHS - set routine to compute the right-hand side of the linear system

3045:   Logically Collective

3047:   Input Parameters:
3048: + ksp  - the `KSP` context
3049: . func - function to compute the right-hand side, see `KSPComputeRHSFn` for the calling sequence
3050: - ctx  - optional context

3052:   Level: beginner

3054:   Note:
3055:   The routine you provide will be called EACH you call `KSPSolve()` to prepare the new right-hand side for that solve

3057: .seealso: [](ch_ksp), `KSP`, `KSPSolve()`, `DMKSPSetComputeRHS()`, `KSPSetComputeOperators()`, `KSPSetOperators()`, `KSPComputeRHSFn`
3058: @*/
3059: PetscErrorCode KSPSetComputeRHS(KSP ksp, KSPComputeRHSFn *func, void *ctx)
3060: {
3061:   DM dm;

3063:   PetscFunctionBegin;
3065:   PetscCall(KSPGetDM(ksp, &dm));
3066:   PetscCall(DMKSPSetComputeRHS(dm, func, ctx));
3067:   PetscFunctionReturn(PETSC_SUCCESS);
3068: }

3070: /*@C
3071:   KSPSetComputeInitialGuess - set routine to compute the initial guess of the linear system

3073:   Logically Collective

3075:   Input Parameters:
3076: + ksp  - the `KSP` context
3077: . func - function to compute the initial guess, see `KSPComputeInitialGuessFn` for calling sequence
3078: - ctx  - optional context

3080:   Level: beginner

3082:   Note:
3083:   This should only be used in conjunction with `KSPSetComputeRHS()` and `KSPSetComputeOperators()`, otherwise
3084:   call `KSPSetInitialGuessNonzero()` and set the initial guess values in the solution vector passed to `KSPSolve()` before calling the solver

3086: .seealso: [](ch_ksp), `KSP`, `KSPSolve()`, `KSPSetComputeRHS()`, `KSPSetComputeOperators()`, `DMKSPSetComputeInitialGuess()`, `KSPSetInitialGuessNonzero()`,
3087:           `KSPComputeInitialGuessFn`
3088: @*/
3089: PetscErrorCode KSPSetComputeInitialGuess(KSP ksp, KSPComputeInitialGuessFn *func, void *ctx)
3090: {
3091:   DM dm;

3093:   PetscFunctionBegin;
3095:   PetscCall(KSPGetDM(ksp, &dm));
3096:   PetscCall(DMKSPSetComputeInitialGuess(dm, func, ctx));
3097:   PetscFunctionReturn(PETSC_SUCCESS);
3098: }

3100: /*@
3101:   KSPSetUseExplicitTranspose - Determines the explicit transpose of the operator is formed in `KSPSolveTranspose()`. In some configurations (like GPUs) it may
3102:   be explicitly formed since the solve is much more efficient.

3104:   Logically Collective

3106:   Input Parameter:
3107: . ksp - the `KSP` context

3109:   Output Parameter:
3110: . flg - `PETSC_TRUE` to transpose the system in `KSPSolveTranspose()`, `PETSC_FALSE` to not transpose (default)

3112:   Level: advanced

3114: .seealso: [](ch_ksp), `KSPSolveTranspose()`, `KSP`
3115: @*/
3116: PetscErrorCode KSPSetUseExplicitTranspose(KSP ksp, PetscBool flg)
3117: {
3118:   PetscFunctionBegin;
3121:   ksp->transpose.use_explicittranspose = flg;
3122:   PetscFunctionReturn(PETSC_SUCCESS);
3123: }