Actual source code: itcreate.c

  1: /*
  2:      The basic KSP routines, Create, View etc. are here.
  3: */
  4: #include <petsc/private/kspimpl.h>

  6: /* Logging support */
  7: PetscClassId  KSP_CLASSID;
  8: PetscClassId  DMKSP_CLASSID;
  9: PetscClassId  KSPGUESS_CLASSID;
 10: PetscLogEvent KSP_Orthogonalization, KSP_SetUp, KSP_Solve, KSP_SolveTranspose, KSP_MatSolve, KSP_MatSolveTranspose;

 12: /*
 13:    Contains the list of registered KSP routines
 14: */
 15: PetscFunctionList KSPList              = NULL;
 16: PetscBool         KSPRegisterAllCalled = PETSC_FALSE;

 18: /*
 19:    Contains the list of registered KSP monitors
 20: */
 21: PetscFunctionList KSPMonitorList              = NULL;
 22: PetscFunctionList KSPMonitorCreateList        = NULL;
 23: PetscFunctionList KSPMonitorDestroyList       = NULL;
 24: PetscBool         KSPMonitorRegisterAllCalled = PETSC_FALSE;

 26: /*@
 27:   KSPLoad - Loads a `KSP` that has been stored in a `PETSCVIEWERBINARY`  with `KSPView()`.

 29:   Collective

 31:   Input Parameters:
 32: + newdm  - the newly loaded `KSP`, this needs to have been created with `KSPCreate()` or
 33:            some related function before a call to `KSPLoad()`.
 34: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`

 36:   Level: intermediate

 38:   Note:
 39:   The type is determined by the data in the file, any type set into the `KSP` before this call is ignored.

 41: .seealso: [](ch_ksp), `KSP`, `PetscViewerBinaryOpen()`, `KSPView()`, `MatLoad()`, `VecLoad()`
 42: @*/
 43: PetscErrorCode KSPLoad(KSP newdm, PetscViewer viewer)
 44: {
 45:   PetscBool isbinary;
 46:   PetscInt  classid;
 47:   char      type[256];
 48:   PC        pc;

 50:   PetscFunctionBegin;
 53:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
 54:   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");

 56:   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
 57:   PetscCheck(classid == KSP_FILE_CLASSID, PetscObjectComm((PetscObject)newdm), PETSC_ERR_ARG_WRONG, "Not KSP next in file");
 58:   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
 59:   PetscCall(KSPSetType(newdm, type));
 60:   PetscTryTypeMethod(newdm, load, viewer);
 61:   PetscCall(KSPGetPC(newdm, &pc));
 62:   PetscCall(PCLoad(pc, viewer));
 63:   PetscFunctionReturn(PETSC_SUCCESS);
 64: }

 66: #include <petscdraw.h>
 67: #if PetscDefined(HAVE_SAWS)
 68: #include <petscviewersaws.h>
 69: #endif
 70: /*@
 71:   KSPView - Prints the various parameters currently set in the `KSP` object. For example, the convergence tolerances and `KSPType`.
 72:   Also views the `PC` and `Mat` contained by the `KSP` with `PCView()` and `MatView()`.

 74:   Collective

 76:   Input Parameters:
 77: + ksp    - the Krylov space context
 78: - viewer - visualization context

 80:   Options Database Key:
 81: . -ksp_view viewer_specification - Display the `KSP` at the end of each `KSPSolve()` call, see `PetscOptionsCreateViewer()` for the format of `viewer_specification`

 83:   Level: beginner

 85:   Notes:
 86:   The available visualization contexts include
 87: +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
 88: -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
 89:   output where only the first processor opens
 90:   the file.  All other processors send their
 91:   data to the first processor to print.

 93:   The available formats include
 94: +     `PETSC_VIEWER_DEFAULT` - standard output (default)
 95: -     `PETSC_VIEWER_ASCII_INFO_DETAIL` - more verbose output for `PCBJACOBI` and `PCASM`

 97:   The user can open an alternative visualization context with
 98:   `PetscViewerASCIIOpen()` - output to a specified file.

100:   Use `KSPViewFromOptions()` to allow the user to select many different `PetscViewerType` and formats from the options database.

102:   In the debugger you can do call `KSPView(ksp,0)` to display the `KSP`. (The same holds for any PETSc object viewer).

104: .seealso: [](ch_ksp), `KSP`, `PetscViewer`, `PCView()`, `PetscViewerASCIIOpen()`, `KSPViewFromOptions()`, `PetscOptionsCreateViewer()`
105: @*/
106: PetscErrorCode KSPView(KSP ksp, PetscViewer viewer)
107: {
108:   PetscBool isascii, isbinary, isdraw, isstring;
109: #if PetscDefined(HAVE_SAWS)
110:   PetscBool issaws;
111: #endif

113:   PetscFunctionBegin;
115:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ksp), &viewer));
117:   PetscCheckSameComm(ksp, 1, viewer, 2);

119:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
120:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
121:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
122:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
123: #if PetscDefined(HAVE_SAWS)
124:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
125: #endif
126:   if (isascii) {
127:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ksp, viewer));
128:     PetscCall(PetscViewerASCIIPushTab(viewer));
129:     PetscTryTypeMethod(ksp, view, viewer);
130:     PetscCall(PetscViewerASCIIPopTab(viewer));
131:     if (ksp->guess_zero) {
132:       PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum iterations=%" PetscInt_FMT ", initial guess is zero\n", ksp->max_it));
133:     } else {
134:       PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum iterations=%" PetscInt_FMT ", nonzero initial guess\n", ksp->max_it));
135:     }
136:     if (ksp->min_it) PetscCall(PetscViewerASCIIPrintf(viewer, "  minimum iterations=%" PetscInt_FMT "\n", ksp->min_it));
137:     if (ksp->guess_knoll) PetscCall(PetscViewerASCIIPrintf(viewer, "  using preconditioner applied to right-hand side for initial guess\n"));
138:     PetscCall(PetscViewerASCIIPrintf(viewer, "  tolerances: relative=%g, absolute=%g, divergence=%g\n", (double)ksp->rtol, (double)ksp->abstol, (double)ksp->divtol));
139:     if (ksp->pc_side == PC_RIGHT) {
140:       PetscCall(PetscViewerASCIIPrintf(viewer, "  right preconditioning\n"));
141:     } else if (ksp->pc_side == PC_SYMMETRIC) {
142:       PetscCall(PetscViewerASCIIPrintf(viewer, "  symmetric preconditioning\n"));
143:     } else {
144:       PetscCall(PetscViewerASCIIPrintf(viewer, "  left preconditioning\n"));
145:     }
146:     if (ksp->guess) {
147:       PetscCall(PetscViewerASCIIPushTab(viewer));
148:       PetscCall(KSPGuessView(ksp->guess, viewer));
149:       PetscCall(PetscViewerASCIIPopTab(viewer));
150:     }
151:     if (ksp->converged == KSPConvergedSkip || ksp->normtype == KSP_NORM_NONE) PetscCall(PetscViewerASCIIPrintf(viewer, "  not checking for convergence\n"));
152:     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using %s norm type for convergence test\n", KSPNormTypes[ksp->normtype]));
153:   } else if (isbinary) {
154:     PetscInt    classid = KSP_FILE_CLASSID;
155:     MPI_Comm    comm;
156:     PetscMPIInt rank;
157:     char        type[256];

159:     PetscCall(PetscObjectGetComm((PetscObject)ksp, &comm));
160:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
161:     if (rank == 0) {
162:       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
163:       PetscCall(PetscStrncpy(type, ((PetscObject)ksp)->type_name, 256));
164:       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
165:     }
166:     PetscTryTypeMethod(ksp, view, viewer);
167:   } else if (isstring) {
168:     const char *type;
169:     PetscCall(KSPGetType(ksp, &type));
170:     PetscCall(PetscViewerStringSPrintf(viewer, " KSPType: %-7.7s", type));
171:     PetscTryTypeMethod(ksp, view, viewer);
172:   } else if (isdraw) {
173:     PetscDraw draw;
174:     char      str[36];
175:     PetscReal x, y, bottom, h;
176:     PetscBool flg;

178:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
179:     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
180:     PetscCall(PetscObjectTypeCompare((PetscObject)ksp, KSPPREONLY, &flg));
181:     if (!flg) {
182:       PetscCall(PetscStrncpy(str, "KSP: ", sizeof(str)));
183:       PetscCall(PetscStrlcat(str, ((PetscObject)ksp)->type_name, sizeof(str)));
184:       PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_RED, PETSC_DRAW_BLACK, str, NULL, &h));
185:       bottom = y - h;
186:     } else {
187:       bottom = y;
188:     }
189:     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
190: #if PetscDefined(HAVE_SAWS)
191:   } else if (issaws) {
192:     PetscMPIInt rank;
193:     const char *name;

195:     PetscCall(PetscObjectGetName((PetscObject)ksp, &name));
196:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
197:     if (!((PetscObject)ksp)->amsmem && rank == 0) {
198:       char dir[1024];

200:       PetscCall(PetscObjectViewSAWs((PetscObject)ksp, viewer));
201:       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/its", name));
202:       PetscCallSAWs(SAWs_Register, (dir, &ksp->its, 1, SAWs_READ, SAWs_INT));
203:       if (!ksp->res_hist) PetscCall(KSPSetResidualHistory(ksp, NULL, PETSC_DECIDE, PETSC_TRUE));
204:       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/res_hist", name));
205:       PetscCallSAWs(SAWs_Register, (dir, ksp->res_hist, 10, SAWs_READ, SAWs_DOUBLE));
206:     }
207: #endif
208:   } else PetscTryTypeMethod(ksp, view, viewer);
209:   if (ksp->pc) PetscCall(PCView(ksp->pc, viewer));
210:   if (isdraw) {
211:     PetscDraw draw;
212:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
213:     PetscCall(PetscDrawPopCurrentPoint(draw));
214:   }
215:   PetscFunctionReturn(PETSC_SUCCESS);
216: }

218: /*@
219:   KSPViewFromOptions - View (print) a `KSP` object based on values in the options database. Also views the `PC` and `Mat` contained by the `KSP`
220:   with `PCView()` and `MatView()`.

222:   Collective

224:   Input Parameters:
225: + A    - Krylov solver context
226: . obj  - optional object that provides the options prefix used to query the options database, pass `NULL` to use the options prefix of `A`
227: - name - command line option

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

232:   Level: intermediate

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

238: .seealso: [](ch_ksp), `KSP`, `KSPView()`, `PetscObjectViewFromOptions()`, `KSPCreate()`, `PetscOptionsCreateViewer()`
239: @*/
240: PetscErrorCode KSPViewFromOptions(KSP A, PetscObject obj, const char name[])
241: {
242:   PetscFunctionBegin;
244:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
245:   PetscFunctionReturn(PETSC_SUCCESS);
246: }

248: /*@
249:   KSPSetNormType - Sets the type of residual norm that is used for convergence testing in `KSPSolve()` for the given `KSP` context

251:   Logically Collective

253:   Input Parameters:
254: + ksp      - Krylov solver context
255: - normtype - one of
256: .vb
257:    KSP_NORM_NONE             - skips computing the norm, this should generally only be used if you are using
258:                                the Krylov method as a smoother with a fixed small number of iterations.
259:                                Implicitly sets `KSPConvergedSkip()` as the `KSP` convergence test.
260:                                Note that certain algorithms such as `KSPGMRES` ALWAYS require the norm calculation,
261:                                for these methods the norms are still computed, they are just not used in
262:                                the convergence test.
263:    KSP_NORM_PRECONDITIONED   - the default for left-preconditioned solves, uses the 2-norm
264:                                of the preconditioned residual  $B^{-1}(b - A x)$.
265:    KSP_NORM_UNPRECONDITIONED - uses the 2-norm of the true $b - Ax$ residual.
266:    KSP_NORM_NATURAL          - uses the $A$ norm of the true $b - Ax$ residual; supported by `KSPCG`, `KSPCR`, `KSPCGNE`, `KSPCGS`
267: .ve

269:   Options Database Key:
270: . -ksp_norm_type (none|preconditioned|unpreconditioned|natural) - set `KSP` norm type

272:   Level: advanced

274:   Notes:
275:   The norm is always of the equations residual $\| b - A x^n \|$  (or an approximation to that norm), they are never a norm of the error in the equation.

277:   Not all combinations of preconditioner side (see `KSPSetPCSide()`) and norm types are supported by all Krylov methods.
278:   If only one is set, PETSc tries to automatically change the other to find a compatible pair.  If no such combination
279:   is supported, PETSc will generate an error.

281:   Developer Note:
282:   Supported combinations of norm and preconditioner side are set using `KSPSetSupportedNorm()` for each `KSPType`.

284: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSPConvergedSkip()`, `KSPSetCheckNormIteration()`, `KSPSetPCSide()`, `KSPGetPCSide()`, `KSPNormType`
285: @*/
286: PetscErrorCode KSPSetNormType(KSP ksp, KSPNormType normtype)
287: {
288:   PetscFunctionBegin;
291:   ksp->normtype = ksp->normtype_set = normtype;
292:   PetscFunctionReturn(PETSC_SUCCESS);
293: }

295: /*@
296:   KSPSetCheckNormIteration - Sets the first iteration at which the norm of the residual will be
297:   computed and used in the convergence test of `KSPSolve()` for the given `KSP` context

299:   Logically Collective

301:   Input Parameters:
302: + ksp - Krylov solver context
303: - it  - use -1 to check at all iterations

305:   Level: advanced

307:   Notes:
308:   Currently only works with `KSPCG`, `KSPBCGS` and `KSPIBCGS`

310:   Use `KSPSetNormType`(ksp,`KSP_NORM_NONE`) to never check the norm

312:   On steps where the norm is not computed, the previous norm is still in the variable, so if you run with, for example,
313:   `-ksp_monitor` the residual norm will appear to be unchanged for several iterations (though it is not really unchanged).

315:   Certain methods such as `KSPGMRES` always compute the residual norm, this routine will not change that computation, but it will
316:   prevent the computed norm from being checked.

318: .seealso: [](ch_ksp), `KSP`, `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSPConvergedSkip()`, `KSPSetNormType()`, `KSPSetLagNorm()`
319: @*/
320: PetscErrorCode KSPSetCheckNormIteration(KSP ksp, PetscInt it)
321: {
322:   PetscFunctionBegin;
325:   ksp->chknorm = it;
326:   PetscFunctionReturn(PETSC_SUCCESS);
327: }

329: /*@
330:   KSPSetLagNorm - Lags the residual norm calculation so that it is computed as part of the `MPI_Allreduce()` used for
331:   computing the inner products needed for the next iteration.

333:   Logically Collective

335:   Input Parameters:
336: + ksp - Krylov solver context
337: - flg - `PETSC_TRUE` or `PETSC_FALSE`

339:   Options Database Key:
340: . -ksp_lag_norm - lag the calculated residual norm

342:   Level: advanced

344:   Notes:
345:   Currently only works with `KSPIBCGS`.

347:   This can reduce communication costs at the expense of doing
348:   one additional iteration because the norm used in the convergence test of `KSPSolve()` is one iteration behind the actual
349:   current residual norm (which has not yet been computed due to the lag).

351:   Use `KSPSetNormType`(ksp,`KSP_NORM_NONE`) to never check the norm

353:   If you lag the norm and run with, for example, `-ksp_monitor`, the residual norm reported will be the lagged one.

355:   `KSPSetCheckNormIteration()` is an alternative way of avoiding the expense of computing the residual norm at each iteration.

357: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSPConvergedSkip()`, `KSPSetNormType()`, `KSPSetCheckNormIteration()`
358: @*/
359: PetscErrorCode KSPSetLagNorm(KSP ksp, PetscBool flg)
360: {
361:   PetscFunctionBegin;
364:   ksp->lagnorm = flg;
365:   PetscFunctionReturn(PETSC_SUCCESS);
366: }

368: /*@
369:   KSPSetSupportedNorm - Sets a norm and preconditioner side supported by a `KSPType`

371:   Logically Collective

373:   Input Parameters:
374: + ksp      - Krylov method
375: . normtype - supported norm type of the type `KSPNormType`
376: . pcside   - preconditioner side, of the type `PCSide` that can be used with this `KSPNormType`
377: - priority - positive integer preference for this combination; larger values have higher priority

379:   Level: developer

381:   Notes:
382:   This function should be called from the implementation files `KSPCreate_XXX()` to declare
383:   which norms and preconditioner sides are supported. Users should not call this
384:   function.

386:   This function can be called multiple times for each combination of `KSPNormType` and `PCSide`
387:   the `KSPType` supports

389: .seealso: [](ch_ksp), `KSP`, `KSPNormType`, `PCSide`, `KSPSetNormType()`, `KSPSetPCSide()`
390: @*/
391: PetscErrorCode KSPSetSupportedNorm(KSP ksp, KSPNormType normtype, PCSide pcside, PetscInt priority)
392: {
393:   PetscFunctionBegin;
395:   ksp->normsupporttable[normtype][pcside] = priority;
396:   PetscFunctionReturn(PETSC_SUCCESS);
397: }

399: static PetscErrorCode KSPNormSupportTableReset_Private(KSP ksp)
400: {
401:   PetscFunctionBegin;
402:   PetscCall(PetscMemzero(ksp->normsupporttable, sizeof(ksp->normsupporttable)));
403:   ksp->pc_side  = ksp->pc_side_set;
404:   ksp->normtype = ksp->normtype_set;
405:   PetscFunctionReturn(PETSC_SUCCESS);
406: }

408: PetscErrorCode KSPSetUpNorms_Private(KSP ksp, PetscBool errorifnotsupported, KSPNormType *normtype, PCSide *pcside)
409: {
410:   PetscInt i, j, best, ibest = 0, jbest = 0;

412:   PetscFunctionBegin;
413:   best = 0;
414:   for (i = 0; i < KSP_NORM_MAX; i++) {
415:     for (j = 0; j < PC_SIDE_MAX; j++) {
416:       if ((ksp->normtype == KSP_NORM_DEFAULT || ksp->normtype == i) && (ksp->pc_side == PC_SIDE_DEFAULT || ksp->pc_side == j) && ksp->normsupporttable[i][j] > best) {
417:         best  = ksp->normsupporttable[i][j];
418:         ibest = i;
419:         jbest = j;
420:       }
421:     }
422:   }
423:   if (best < 1 && errorifnotsupported) {
424:     PetscCheck(ksp->normtype != KSP_NORM_DEFAULT || ksp->pc_side != PC_SIDE_DEFAULT, PetscObjectComm((PetscObject)ksp), PETSC_ERR_PLIB, "The %s KSP implementation did not call KSPSetSupportedNorm()", ((PetscObject)ksp)->type_name);
425:     PetscCheck(ksp->normtype != KSP_NORM_DEFAULT, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "KSP %s does not support preconditioner side %s", ((PetscObject)ksp)->type_name, PCSides[ksp->pc_side]);
426:     PetscCheck(ksp->pc_side != PC_SIDE_DEFAULT, PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "KSP %s does not support norm type %s", ((PetscObject)ksp)->type_name, KSPNormTypes[ksp->normtype]);
427:     SETERRQ(PetscObjectComm((PetscObject)ksp), PETSC_ERR_SUP, "KSP %s does not support norm type %s with preconditioner side %s", ((PetscObject)ksp)->type_name, KSPNormTypes[ksp->normtype], PCSides[ksp->pc_side]);
428:   }
429:   if (normtype) *normtype = (KSPNormType)ibest;
430:   if (pcside) *pcside = (PCSide)jbest;
431:   PetscFunctionReturn(PETSC_SUCCESS);
432: }

434: /*@
435:   KSPGetNormType - Gets the `KSPNormType` that is used for convergence testing during `KSPSolve()` for this `KSP` context

437:   Not Collective

439:   Input Parameter:
440: . ksp - Krylov solver context

442:   Output Parameter:
443: . normtype - the `KSPNormType` that is used for convergence testing

445:   Level: advanced

447: .seealso: [](ch_ksp), `KSPNormType`, `KSPSetNormType()`, `KSPConvergedSkip()`
448: @*/
449: PetscErrorCode KSPGetNormType(KSP ksp, KSPNormType *normtype)
450: {
451:   PetscFunctionBegin;
453:   PetscAssertPointer(normtype, 2);
454:   PetscCall(KSPSetUpNorms_Private(ksp, PETSC_TRUE, &ksp->normtype, &ksp->pc_side));
455:   *normtype = ksp->normtype;
456:   PetscFunctionReturn(PETSC_SUCCESS);
457: }

459: #if PetscDefined(HAVE_SAWS)
460: #include <petscviewersaws.h>
461: #endif

463: /*@
464:   KSPSetOperators - Sets the matrix associated with the linear system
465:   and a (possibly) different one from which the preconditioner will be built into the `KSP` context. The matrix will then be used during `KSPSolve()`

467:   Collective

469:   Input Parameters:
470: + ksp  - the `KSP` context
471: . Amat - the matrix that defines the linear system
472: - Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.

474:   Level: beginner

476:   Notes:
477: .vb
478:   KSPSetOperators(ksp, Amat, Pmat);
479: .ve
480:   is the same as
481: .vb
482:   KSPGetPC(ksp, &pc);
483:   PCSetOperators(pc, Amat, Pmat);
484: .ve
485:   and is equivalent to
486: .vb
487:   PCCreate(PetscObjectComm((PetscObject)ksp), &pc);
488:   PCSetOperators(pc, Amat, Pmat);
489:   KSPSetPC(ksp, pc);
490: .ve

492:   If you know the operator `Amat` has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
493:   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.

495:   All future calls to `KSPSetOperators()` must use the same size matrices, unless `KSPReset()` is called!

497:   Passing a `NULL` for `Amat` or `Pmat` removes the matrix that is currently being used from the `KSP` context.

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

503:   Developer Notes:
504:   If the operators have NOT been set with `KSPSetOperators()` then the operators
505:   are created in the `PC` and returned to the user. In this case, if both operators
506:   mat and pmat are requested, two DIFFERENT operators will be returned. If
507:   only one is requested both operators in the `PC` will be the same (i.e. as
508:   if one had called `KSPSetOperators()` with the same argument for both `Mat`s).
509:   The user must set the sizes of the returned matrices and their type etc just
510:   as if the user created them with `MatCreate()`. For example,

512: .vb
513:          KSPGetOperators(ksp/pc,&mat,NULL); is equivalent to
514:            set size, type, etc of mat

516:          MatCreate(comm,&mat);
517:          KSP/PCSetOperators(ksp/pc,mat,mat);
518:          PetscObjectDereference((PetscObject)mat);
519:            set size, type, etc of mat

521:      and

523:          KSP/PCGetOperators(ksp/pc,&mat,&pmat); is equivalent to
524:            set size, type, etc of mat and pmat

526:          MatCreate(comm,&mat);
527:          MatCreate(comm,&pmat);
528:          KSP/PCSetOperators(ksp/pc,mat,pmat);
529:          PetscObjectDereference((PetscObject)mat);
530:          PetscObjectDereference((PetscObject)pmat);
531:            set size, type, etc of mat and pmat
532: .ve

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

543: .seealso: [](ch_ksp), `KSP`, `Mat`, `KSPSolve()`, `KSPGetPC()`, `PCGetOperators()`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetComputeOperators()`, `KSPSetComputeInitialGuess()`, `KSPSetComputeRHS()`
544: @*/
545: PetscErrorCode KSPSetOperators(KSP ksp, Mat Amat, Mat Pmat)
546: {
547:   PetscFunctionBegin;
551:   if (Amat) PetscCheckSameComm(ksp, 1, Amat, 2);
552:   if (Pmat) PetscCheckSameComm(ksp, 1, Pmat, 3);
553:   if (!ksp->pc) PetscCall(KSPGetPC(ksp, &ksp->pc));
554:   PetscCall(PCSetOperators(ksp->pc, Amat, Pmat));
555:   if (ksp->setupstage == KSP_SETUP_NEWRHS) ksp->setupstage = KSP_SETUP_NEWMATRIX; /* so that next solve call will call PCSetUp() on new matrix */
556:   PetscFunctionReturn(PETSC_SUCCESS);
557: }

559: /*@
560:   KSPGetOperators - Gets the matrix associated with the linear system
561:   and a (possibly) different one used to construct the preconditioner from the `KSP` context

563:   Collective

565:   Input Parameter:
566: . ksp - the `KSP` context

568:   Output Parameters:
569: + Amat - the matrix that defines the linear system
570: - Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.

572:   Level: intermediate

574:   Notes:
575:   If `KSPSetOperators()` has not been called then the `KSP` object will attempt to automatically create the matrix `Amat` and return it

577:   Use `KSPGetOperatorsSet()` to determine if matrices have been provided. After `KSPSolveTranspose()` or `KSPMatSolveTranspose()` with explicit transposition enabled by
578:   `KSPSetUseExplicitTranspose()`, this function returns the explicitly transposed operators until a non-transpose solve restores their parent operators. These explicitly transposed
579:   operators are owned by the `KSP` and may be destroyed by `KSPSetUseExplicitTranspose(ksp, PETSC_FALSE)`, by `KSPReset()`, or by a non-transpose solve after `KSPSetOperators()`
580:   changes the operators.

582:   DOES NOT increase the reference counts of the matrix, so you should NOT destroy them.

584: .seealso: [](ch_ksp), `KSP`, `KSPSolve()`, `KSPGetPC()`, `PCSetOperators()`, `KSPSetOperators()`, `KSPGetOperatorsSet()`, `KSPSetUseExplicitTranspose()`
585: @*/
586: PetscErrorCode KSPGetOperators(KSP ksp, Mat *Amat, Mat *Pmat)
587: {
588:   PetscFunctionBegin;
590:   if (!ksp->pc) PetscCall(KSPGetPC(ksp, &ksp->pc));
591:   PetscCall(PCGetOperators(ksp->pc, Amat, Pmat));
592:   PetscFunctionReturn(PETSC_SUCCESS);
593: }

595: /*@
596:   KSPGetOperatorsSet - Determines if the matrix associated with the linear system and
597:   possibly a different one from which the preconditioner will be built have been set in the `KSP` with `KSPSetOperators()`

599:   Not Collective, though the results on all processes will be the same

601:   Input Parameter:
602: . ksp - the `KSP` context

604:   Output Parameters:
605: + mat  - the matrix associated with the linear system was set
606: - pmat - matrix from which the preconditioner will be built, usually the same as `mat` was set

608:   Level: intermediate

610:   Note:
611:   This routine exists because if you call `KSPGetOperators()` on a `KSP` that does not yet have operators they are
612:   automatically created in the call.

614: .seealso: [](ch_ksp), `KSP`, `PCSetOperators()`, `KSPGetOperators()`, `KSPSetOperators()`, `PCGetOperators()`, `PCGetOperatorsSet()`
615: @*/
616: PetscErrorCode KSPGetOperatorsSet(KSP ksp, PetscBool *mat, PetscBool *pmat)
617: {
618:   PetscFunctionBegin;
620:   if (!ksp->pc) PetscCall(KSPGetPC(ksp, &ksp->pc));
621:   PetscCall(PCGetOperatorsSet(ksp->pc, mat, pmat));
622:   PetscFunctionReturn(PETSC_SUCCESS);
623: }

625: /*@
626:   KSPSetPreSolve - Sets a function that is called at the beginning of each `KSPSolve()`. Used in conjunction with `KSPSetPostSolve()`.

628:   Logically Collective

630:   Input Parameters:
631: + ksp      - the solver object
632: . presolve - the function to call before the solve, see` KSPPSolveFn`
633: - ctx      - an optional context needed by the function

635:   Level: developer

637:   Notes:
638:   The function provided here `presolve` is used to modify the right hand side, and possibly the matrix, of the linear system to be solved.
639:   The function provided with `KSPSetPostSolve()` then modifies the resulting solution of that linear system to obtain the correct solution
640:   to the initial linear system.

642:   The functions `PCPreSolve()` and `PCPostSolve()` provide a similar functionality and are used, for example with `PCEISENSTAT`.

644: .seealso: [](ch_ksp), `KSPPSolveFn`, `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPSetPostSolve()`, `PCPreSolve()`, `PCPostSolve()`
645: @*/
646: PetscErrorCode KSPSetPreSolve(KSP ksp, KSPPSolveFn *presolve, PetscCtx ctx)
647: {
648:   PetscFunctionBegin;
650:   ksp->presolve = presolve;
651:   ksp->prectx   = ctx;
652:   PetscFunctionReturn(PETSC_SUCCESS);
653: }

655: /*@
656:   KSPSetPostSolve - Sets a function that is called at the end of each `KSPSolve()` (whether it converges or not). Used in conjunction with `KSPSetPreSolve()`.

658:   Logically Collective

660:   Input Parameters:
661: + ksp       - the solver object
662: . postsolve - the function to call after the solve, see` KSPPSolveFn`
663: - ctx       - an optional context needed by the function

665:   Level: developer

667: .seealso: [](ch_ksp), `KSPPSolveFn`, `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPSetPreSolve()`, `KSPPostSolve()`
668: @*/
669: PetscErrorCode KSPSetPostSolve(KSP ksp, KSPPSolveFn *postsolve, PetscCtx ctx)
670: {
671:   PetscFunctionBegin;
673:   ksp->postsolve = postsolve;
674:   ksp->postctx   = ctx;
675:   PetscFunctionReturn(PETSC_SUCCESS);
676: }

678: /*@
679:   KSPPreSolve - Runs the KSP pre-solve callbacks. Used in conjunction with `KSPSetPreSolve()` or the Eisenstat-Walker method.

681:   Collective

683:   Input Parameters:
684: + ksp - the solver object
685: . rhs - the right-hand side vector
686: - sol - the solution vector

688:   Level: developer

690:   Note:
691:   `KSPPreSolve()` is typically used within `KSPSolve()`, so most users would not generally call this routine themselves.

693: .seealso: [](ch_ksp), `KSPSolve()`, `KSP`, `KSPSetPreSolve()`, `KSPPostSolve()`, `SNESKSPSetUseEW()`
694: @*/
695: PetscErrorCode KSPPreSolve(KSP ksp, Vec rhs, Vec sol)
696: {
697:   PetscFunctionBegin;
701:   if (ksp->presolve_ew) PetscCall((*ksp->presolve_ew)(ksp, rhs, sol, ksp->prectx_ew));
702:   if (ksp->presolve) PetscCall((*ksp->presolve)(ksp, rhs, sol, ksp->prectx));
703:   PetscFunctionReturn(PETSC_SUCCESS);
704: }

706: /*@
707:   KSPPostSolve - Runs the KSP post-solve callbacks. Used in conjunction with `KSPSetPostSolve()` or the Eisenstat-Walker method.

709:   Collective

711:   Input Parameters:
712: + ksp - the solver object
713: . rhs - the right-hand side vector
714: - sol - the solution vector

716:   Level: developer

718:   Note:
719:   `KSPPostSolve()` is typically used within `KSPSolve()`, so most users would not generally call this routine themselves.

721: .seealso: [](ch_ksp), `KSPSolve()`, `KSP`, `KSPSetPostSolve()`, `KSPPreSolve()`, `SNESKSPSetUseEW()`
722: @*/
723: PetscErrorCode KSPPostSolve(KSP ksp, Vec rhs, Vec sol)
724: {
725:   PetscFunctionBegin;
729:   if (ksp->postsolve_ew) PetscCall((*ksp->postsolve_ew)(ksp, rhs, sol, ksp->postctx_ew));
730:   if (ksp->postsolve) PetscCall((*ksp->postsolve)(ksp, rhs, sol, ksp->postctx));
731:   PetscFunctionReturn(PETSC_SUCCESS);
732: }

734: /*@
735:   KSPSetNestLevel - sets the amount of nesting the `KSP` has. That is the number of levels of `KSP` above this `KSP` in a linear solve.

737:   Collective

739:   Input Parameters:
740: + ksp   - the `KSP`
741: - level - the nest level

743:   Level: developer

745:   Note:
746:   For example, the `KSP` in each block of a `KSPBJACOBI` has a level of 1, while the outer `KSP` has a level of 0.

748: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGMRES`, `KSPType`, `KSPGetNestLevel()`, `PCSetKSPNestLevel()`, `PCGetKSPNestLevel()`
749: @*/
750: PetscErrorCode KSPSetNestLevel(KSP ksp, PetscInt level)
751: {
752:   PetscFunctionBegin;
755:   ksp->nestlevel = level;
756:   PetscFunctionReturn(PETSC_SUCCESS);
757: }

759: /*@
760:   KSPGetNestLevel - gets the amount of nesting the `KSP` has

762:   Not Collective

764:   Input Parameter:
765: . ksp - the `KSP`

767:   Output Parameter:
768: . level - the nest level

770:   Level: developer

772: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGMRES`, `KSPType`, `KSPSetNestLevel()`, `PCSetKSPNestLevel()`, `PCGetKSPNestLevel()`
773: @*/
774: PetscErrorCode KSPGetNestLevel(KSP ksp, PetscInt *level)
775: {
776:   PetscFunctionBegin;
778:   PetscAssertPointer(level, 2);
779:   *level = ksp->nestlevel;
780:   PetscFunctionReturn(PETSC_SUCCESS);
781: }

783: /*@
784:   KSPCreate - Creates the `KSP` context. This `KSP` context is used in PETSc to solve linear systems with `KSPSolve()`

786:   Collective

788:   Input Parameter:
789: . comm - MPI communicator

791:   Output Parameter:
792: . inksp - location to put the `KSP` context

794:   Level: beginner

796:   Note:
797:   The default `KSPType` is `KSPGMRES` with a restart of 30, using modified Gram-Schmidt orthogonalization. The `KSPType` may be
798:   changed with `KSPSetType()`

800: .seealso: [](ch_ksp), `KSPSetUp()`, `KSPSolve()`, `KSPDestroy()`, `KSP`, `KSPGMRES`, `KSPType`, `KSPSetType()`
801: @*/
802: PetscErrorCode KSPCreate(MPI_Comm comm, KSP *inksp)
803: {
804:   KSP      ksp;
805:   PetscCtx ctx;

807:   PetscFunctionBegin;
808:   PetscAssertPointer(inksp, 2);
809:   PetscCall(KSPInitializePackage());

811:   PetscCall(PetscHeaderCreate(ksp, KSP_CLASSID, "KSP", "Krylov Method", "KSP", comm, KSPDestroy, KSPView));
812:   ksp->default_max_it = ksp->max_it = 10000;
813:   ksp->pc_side = ksp->pc_side_set = PC_SIDE_DEFAULT;

815:   ksp->default_rtol = ksp->rtol = 1.e-5;
816:   ksp->default_abstol = ksp->abstol = PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50;
817:   ksp->default_divtol = ksp->divtol = 1.e4;

819:   ksp->normtype = ksp->normtype_set = KSP_NORM_DEFAULT;

821:   ksp->chknorm        = -1;
822:   ksp->guess_zero     = PETSC_TRUE;
823:   ksp->res_hist_reset = PETSC_TRUE;
824:   ksp->err_hist_reset = PETSC_TRUE;
825:   ksp->nmax           = PETSC_DECIDE;
826:   ksp->orthog         = KSPOrthogonalizationClassicalGramSchmidt;
827:   ksp->cgstype        = KSP_ORTHOGONALIZATION_CGS_REFINE_NEVER;
828:   ksp->reason         = KSP_CONVERGED_ITERATING;
829:   ksp->setupstage     = KSP_SETUP_NEW;

831:   PetscCall(MatStateInvalidate(ksp->amatstate));

833:   PetscCall(KSPConvergedDefaultCreate(&ctx));
834:   PetscCall(KSPSetConvergenceTest(ksp, KSPConvergedDefault, ctx, KSPConvergedDefaultDestroy));
835:   ksp->ops->buildsolution = KSPBuildSolutionDefault;
836:   ksp->ops->buildresidual = KSPBuildResidualDefault;

838:   PetscCall(KSPNormSupportTableReset_Private(ksp));

840:   *inksp = ksp;
841:   PetscFunctionReturn(PETSC_SUCCESS);
842: }

844: /*@
845:   KSPSetType - Sets the algorithm/method to be used to solve the linear system with the given `KSP`

847:   Logically Collective

849:   Input Parameters:
850: + ksp  - the Krylov space context
851: - type - a known method

853:   Options Database Key:
854: . -ksp_type type - Sets the method; see `KSPType`

856:   Level: intermediate

858:   Notes:
859:   See `KSPType` for available methods (for instance, `KSPCG` or `KSPGMRES`).

861:   Normally, it is best to use the `KSPSetFromOptions()` command and
862:   then set the `KSP` type from the options database rather than by using
863:   this routine.  Using the options database provides the user with
864:   maximum flexibility in evaluating the many different Krylov methods.
865:   The `KSPSetType()` routine is provided for those situations where it
866:   is necessary to set the iterative solver independently of the command
867:   line or options database.  This might be the case, for example, when
868:   the choice of iterative solver changes during the execution of the
869:   program, and the user's application is taking responsibility for
870:   choosing the appropriate method.  In other words, this routine is
871:   not for beginners.

873:   Developer Note:
874:   `KSPRegister()` is used to add Krylov types to `KSPList` from which they are accessed by `KSPSetType()`.

876: .seealso: [](ch_ksp), `PCSetType()`, `KSPType`, `KSPRegister()`, `KSPCreate()`, `KSP`
877: @*/
878: PetscErrorCode KSPSetType(KSP ksp, KSPType type)
879: {
880:   PetscBool match;
881:   PetscErrorCode (*r)(KSP);

883:   PetscFunctionBegin;
885:   PetscAssertPointer(type, 2);

887:   PetscCall(PetscObjectTypeCompare((PetscObject)ksp, type, &match));
888:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

890:   PetscCall(PetscFunctionListFind(KSPList, type, &r));
891:   PetscCheck(r, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested KSP type %s", type);
892:   /* Destroy the previous private KSP context */
893:   PetscTryTypeMethod(ksp, destroy);

895:   /* Reinitialize function pointers in KSPOps structure */
896:   PetscCall(PetscMemzero(ksp->ops, sizeof(struct _KSPOps)));
897:   ksp->ops->buildsolution = KSPBuildSolutionDefault;
898:   ksp->ops->buildresidual = KSPBuildResidualDefault;
899:   PetscCall(KSPNormSupportTableReset_Private(ksp));
900:   ksp->converged_neg_curve = PETSC_FALSE; // restore default
901:   ksp->setupnewmatrix      = PETSC_FALSE; // restore default (setup not called in case of new matrix)
902:   /* Call the KSPCreate_XXX routine for this particular Krylov solver */
903:   ksp->setupstage     = KSP_SETUP_NEW;
904:   ksp->guess_not_read = PETSC_FALSE; // restore default
905:   PetscCall((*r)(ksp));
906:   PetscCall(PetscObjectChangeTypeName((PetscObject)ksp, type));
907:   PetscFunctionReturn(PETSC_SUCCESS);
908: }

910: /*@
911:   KSPGetType - Gets the `KSP` type as a string from the `KSP` object.

913:   Not Collective

915:   Input Parameter:
916: . ksp - Krylov context

918:   Output Parameter:
919: . type - name of the `KSP` method

921:   Level: intermediate

923:   Note:
924:   `type` should not be retained for later use as it will be an invalid pointer if the `KSPType` of `ksp` is changed.

926: .seealso: [](ch_ksp), `KSPType`, `KSP`, `KSPSetType()`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
927: @*/
928: PetscErrorCode KSPGetType(KSP ksp, KSPType *type)
929: {
930:   PetscFunctionBegin;
932:   PetscAssertPointer(type, 2);
933:   *type = ((PetscObject)ksp)->type_name;
934:   PetscFunctionReturn(PETSC_SUCCESS);
935: }

937: /*@
938:   KSPRegister -  Adds a method, `KSPType`, to the Krylov subspace solver package.

940:   Not Collective, No Fortran Support

942:   Input Parameters:
943: + sname    - name of a new user-defined solver
944: - function - routine to create method

946:   Level: advanced

948:   Note:
949:   `KSPRegister()` may be called multiple times to add several user-defined solvers.

951:   Example Usage:
952: .vb
953:    KSPRegister("my_solver", MySolverCreate);
954: .ve

956:   Then, your solver can be chosen with the procedural interface via
957: .vb
958:   KSPSetType(ksp, "my_solver")
959: .ve
960:   or at runtime via the option `-ksp_type my_solver`

962: .seealso: [](ch_ksp), `KSP`, `KSPType`, `KSPSetType`, `KSPRegisterAll()`
963: @*/
964: PetscErrorCode KSPRegister(const char sname[], PetscErrorCode (*function)(KSP))
965: {
966:   PetscFunctionBegin;
967:   PetscCall(KSPInitializePackage());
968:   PetscCall(PetscFunctionListAdd(&KSPList, sname, function));
969:   PetscFunctionReturn(PETSC_SUCCESS);
970: }

972: PetscErrorCode KSPMonitorMakeKey_Internal(const char name[], PetscViewerType vtype, PetscViewerFormat format, char key[])
973: {
974:   PetscFunctionBegin;
975:   PetscCall(PetscStrncpy(key, name, PETSC_MAX_PATH_LEN));
976:   PetscCall(PetscStrlcat(key, ":", PETSC_MAX_PATH_LEN));
977:   PetscCall(PetscStrlcat(key, vtype, PETSC_MAX_PATH_LEN));
978:   PetscCall(PetscStrlcat(key, ":", PETSC_MAX_PATH_LEN));
979:   PetscCall(PetscStrlcat(key, PetscViewerFormats[format], PETSC_MAX_PATH_LEN));
980:   PetscFunctionReturn(PETSC_SUCCESS);
981: }

983: /*@
984:   KSPMonitorRegister -  Registers a Krylov subspace solver monitor routine that may be accessed with `KSPMonitorSetFromOptions()`

986:   Not Collective

988:   Input Parameters:
989: + name    - name of a new monitor type
990: . vtype   - A `PetscViewerType` for the output
991: . format  - A `PetscViewerFormat` for the output
992: . monitor - Monitor routine, see `KSPMonitorRegisterFn`
993: . create  - Creation routine, or `NULL`
994: - destroy - Destruction routine, or `NULL`

996:   Level: advanced

998:   Notes:
999:   `KSPMonitorRegister()` may be called multiple times to add several user-defined monitors.

1001:   The calling sequence for the given function matches the calling sequence used by `KSPMonitorFn` functions passed to `KSPMonitorSet()` with the additional
1002:   requirement that its final argument be a `PetscViewerAndFormat`.

1004:   Example Usage:
1005: .vb
1006:   KSPMonitorRegister("my_monitor", PETSCVIEWERASCII, PETSC_VIEWER_ASCII_INFO_DETAIL, MyMonitor, NULL, NULL);
1007: .ve

1009:   Then, your monitor can be chosen with the procedural interface via
1010: .vb
1011:   KSPMonitorSetFromOptions(ksp, "-ksp_monitor_my_monitor", "my_monitor", NULL)
1012: .ve
1013:   or at runtime via the option `-ksp_monitor_my_monitor`

1015: .seealso: [](ch_ksp), `KSP`, `KSPMonitorSet()`, `KSPMonitorRegisterAll()`, `KSPMonitorSetFromOptions()`
1016: @*/
1017: PetscErrorCode KSPMonitorRegister(const char name[], PetscViewerType vtype, PetscViewerFormat format, KSPMonitorRegisterFn *monitor, KSPMonitorRegisterCreateFn *create, KSPMonitorRegisterDestroyFn *destroy)
1018: {
1019:   char key[PETSC_MAX_PATH_LEN];

1021:   PetscFunctionBegin;
1022:   PetscCall(KSPInitializePackage());
1023:   PetscCall(KSPMonitorMakeKey_Internal(name, vtype, format, key));
1024:   PetscCall(PetscFunctionListAdd(&KSPMonitorList, key, monitor));
1025:   if (create) PetscCall(PetscFunctionListAdd(&KSPMonitorCreateList, key, create));
1026:   if (destroy) PetscCall(PetscFunctionListAdd(&KSPMonitorDestroyList, key, destroy));
1027:   PetscFunctionReturn(PETSC_SUCCESS);
1028: }