Actual source code: snes.c

  1: #include <petsc/private/snesimpl.h>
  2: #include <petsc/private/linesearchimpl.h>
  3: #include <petscdmshell.h>
  4: #include <petscdraw.h>
  5: #include <petscds.h>
  6: #include <petscdmadaptor.h>
  7: #include <petscconvest.h>

  9: PetscBool         SNESRegisterAllCalled = PETSC_FALSE;
 10: PetscFunctionList SNESList              = NULL;

 12: /* Logging support */
 13: PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
 14: PetscLogEvent SNES_Solve, SNES_SetUp, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NewtonALEval, SNES_NPCSolve, SNES_ObjectiveEval;

 16: /*@
 17:   SNESSetErrorIfNotConverged - Causes `SNESSolve()` to generate an error immediately if the solver has not converged.

 19:   Logically Collective

 21:   Input Parameters:
 22: + snes - iterative context obtained from `SNESCreate()`
 23: - flg  - `PETSC_TRUE` indicates you want the error generated

 25:   Options Database Key:
 26: . -snes_error_if_not_converged (true|false) - cause an immediate error condition and stop the program if the solver does not converge

 28:   Level: intermediate

 30:   Note:
 31:   Normally PETSc continues if a solver fails to converge, you can call `SNESGetConvergedReason()` after a `SNESSolve()`
 32:   to determine if it has converged. Otherwise the solution may be inaccurate or wrong

 34: .seealso: [](ch_snes), `SNES`, `SNESGetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
 35: @*/
 36: PetscErrorCode SNESSetErrorIfNotConverged(SNES snes, PetscBool flg)
 37: {
 38:   PetscFunctionBegin;
 41:   snes->errorifnotconverged = flg;
 42:   PetscFunctionReturn(PETSC_SUCCESS);
 43: }

 45: /*@
 46:   SNESGetErrorIfNotConverged - Indicates if `SNESSolve()` will generate an error if the solver does not converge?

 48:   Not Collective

 50:   Input Parameter:
 51: . snes - iterative context obtained from `SNESCreate()`

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

 56:   Level: intermediate

 58: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
 59: @*/
 60: PetscErrorCode SNESGetErrorIfNotConverged(SNES snes, PetscBool *flag)
 61: {
 62:   PetscFunctionBegin;
 64:   PetscAssertPointer(flag, 2);
 65:   *flag = snes->errorifnotconverged;
 66:   PetscFunctionReturn(PETSC_SUCCESS);
 67: }

 69: /*@
 70:   SNESSetAlwaysComputesFinalResidual - tells the `SNES` to always compute the residual (nonlinear function value) at the final solution

 72:   Logically Collective

 74:   Input Parameters:
 75: + snes - the shell `SNES`
 76: - flg  - `PETSC_TRUE` to always compute the residual

 78:   Level: advanced

 80:   Note:
 81:   Some solvers (such as smoothers in a `SNESFAS`) do not need the residual computed at the final solution so skip computing it
 82:   to save time.

 84: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESGetAlwaysComputesFinalResidual()`
 85: @*/
 86: PetscErrorCode SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
 87: {
 88:   PetscFunctionBegin;
 90:   snes->alwayscomputesfinalresidual = flg;
 91:   PetscFunctionReturn(PETSC_SUCCESS);
 92: }

 94: /*@
 95:   SNESGetAlwaysComputesFinalResidual - checks if the `SNES` always computes the residual at the final solution

 97:   Logically Collective

 99:   Input Parameter:
100: . snes - the `SNES` context

102:   Output Parameter:
103: . flg - `PETSC_TRUE` if the residual is computed

105:   Level: advanced

107: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESSetAlwaysComputesFinalResidual()`
108: @*/
109: PetscErrorCode SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
110: {
111:   PetscFunctionBegin;
113:   *flg = snes->alwayscomputesfinalresidual;
114:   PetscFunctionReturn(PETSC_SUCCESS);
115: }

117: /*@
118:   SNESSetFunctionDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetFunction()` is not
119:   in the function's domain. For example, a step with negative pressure.

121:   Not Collective

123:   Input Parameter:
124: . snes - the `SNES` context

126:   Level: advanced

128:   Notes:
129:   This does not need to be called by all processes in the `SNES` MPI communicator.

131:   A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
132:   returns with a `SNESConvergedReason` of `SNES_DIVERGED_FUNCTION_DOMAIN`

134:   You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
135:   `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`

137:   You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).

139:   You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.

141:   Developer Note:
142:   This value is used by `SNESCheckFunctionDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_FUNCTION_DOMAIN`

144: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
145:           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
146:           `SNES_DIVERGED_FUNCTION_DOMAIN`, `SNESSetObjectiveDomainError()`, `SNES_DIVERGED_OBJECTIVE_DOMAIN`
147: @*/
148: PetscErrorCode SNESSetFunctionDomainError(SNES snes)
149: {
150:   PetscFunctionBegin;
152:   snes->functiondomainerror = PETSC_TRUE;
153:   PetscFunctionReturn(PETSC_SUCCESS);
154: }

156: /*@
157:   SNESSetObjectiveDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetObjective()` is not
158:   in the function's domain. For example, a step with negative pressure.

160:   Not Collective

162:   Input Parameter:
163: . snes - the `SNES` context

165:   Level: advanced

167:   Notes:
168:   This does not need to be called by all processes in the `SNES` MPI communicator.

170:   A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
171:   returns with a `SNESConvergedReason` of `SNES_DIVERGED_OBJECTIVE_DOMAIN`

173:   You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
174:   `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`

176:   You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).

178:   You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.

180:   Developer Note:
181:   This value is used by `SNESCheckObjectiveDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_OBJECTIVE_DOMAIN`

183: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
184:           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
185:           `SNES_DIVERGED_OBJECTIVE_DOMAIN`, `SNESSetFunctionDomainError()`, `SNES_DIVERGED_FUNCTION_DOMAIN`
186: @*/
187: PetscErrorCode SNESSetObjectiveDomainError(SNES snes)
188: {
189:   PetscFunctionBegin;
191:   snes->objectivedomainerror = PETSC_TRUE;
192:   PetscFunctionReturn(PETSC_SUCCESS);
193: }

195: /*@
196:   SNESSetJacobianDomainError - tells `SNES` that the function you provided to `SNESSetJacobian()` at the proposed step. For example there is a negative element transformation.

198:   Logically Collective

200:   Input Parameter:
201: . snes - the `SNES` context

203:   Level: advanced

205:   Notes:
206:   If this is called the `SNESSolve()` stops iterating and returns with a `SNESConvergedReason` of `SNES_DIVERGED_JACOBIAN_DOMAIN`

208:   You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).

210:   You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
211:   `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`

213: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`,
214:           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`
215: @*/
216: PetscErrorCode SNESSetJacobianDomainError(SNES snes)
217: {
218:   PetscFunctionBegin;
220:   PetscCheck(!snes->errorifnotconverged, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "User code indicates computeJacobian does not make sense");
221:   snes->jacobiandomainerror = PETSC_TRUE;
222:   PetscFunctionReturn(PETSC_SUCCESS);
223: }

225: /*@
226:   SNESSetCheckJacobianDomainError - tells `SNESSolve()` whether to check if the user called `SNESSetJacobianDomainError()` to indicate a Jacobian domain error after
227:   each Jacobian evaluation.

229:   Logically Collective

231:   Input Parameters:
232: + snes - the `SNES` context
233: - flg  - indicates if or not to check Jacobian domain error after each Jacobian evaluation

235:   Level: advanced

237:   Notes:
238:   By default, it checks for the Jacobian domain error in the debug mode, and does not check it in the optimized mode.

240:   Checks require one extra parallel synchronization for each Jacobian evaluation

242: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()`
243: @*/
244: PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
245: {
246:   PetscFunctionBegin;
248:   snes->checkjacdomainerror = flg;
249:   PetscFunctionReturn(PETSC_SUCCESS);
250: }

252: /*@
253:   SNESGetCheckJacobianDomainError - Get an indicator whether or not `SNES` is checking Jacobian domain errors after each Jacobian evaluation.

255:   Logically Collective

257:   Input Parameter:
258: . snes - the `SNES` context

260:   Output Parameter:
261: . flg - `PETSC_FALSE` indicates that it is not checking Jacobian domain errors after each Jacobian evaluation

263:   Level: advanced

265: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()`
266: @*/
267: PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
268: {
269:   PetscFunctionBegin;
271:   PetscAssertPointer(flg, 2);
272:   *flg = snes->checkjacdomainerror;
273:   PetscFunctionReturn(PETSC_SUCCESS);
274: }

276: /*@
277:   SNESLoad - Loads a `SNES` that has been stored in `PETSCVIEWERBINARY` with `SNESView()`.

279:   Collective

281:   Input Parameters:
282: + snes   - the newly loaded `SNES`, this needs to have been created with `SNESCreate()` or
283:            some related function before a call to `SNESLoad()`.
284: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`

286:   Level: intermediate

288:   Note:
289:   The `SNESType` is determined by the data in the file, any type set into the `SNES` before this call is ignored.

291: .seealso: [](ch_snes), `SNES`, `PetscViewer`, `SNESCreate()`, `SNESType`, `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()`
292: @*/
293: PetscErrorCode SNESLoad(SNES snes, PetscViewer viewer)
294: {
295:   PetscBool isbinary;
296:   PetscInt  classid;
297:   char      type[256];
298:   KSP       ksp;
299:   DM        dm;
300:   DMSNES    dmsnes;

302:   PetscFunctionBegin;
305:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
306:   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");

308:   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
309:   PetscCheck(classid == SNES_FILE_CLASSID, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Not SNES next in file");
310:   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
311:   PetscCall(SNESSetType(snes, type));
312:   PetscTryTypeMethod(snes, load, viewer);
313:   PetscCall(SNESGetDM(snes, &dm));
314:   PetscCall(DMGetDMSNES(dm, &dmsnes));
315:   PetscCall(DMSNESLoad(dmsnes, viewer));
316:   PetscCall(SNESGetKSP(snes, &ksp));
317:   PetscCall(KSPLoad(ksp, viewer));
318:   PetscFunctionReturn(PETSC_SUCCESS);
319: }

321: #include <petscdraw.h>
322: #if PetscDefined(HAVE_SAWS)
323: #include <petscviewersaws.h>
324: #endif

326: /*@
327:   SNESViewFromOptions - View a `SNES` based on values in the options database

329:   Collective

331:   Input Parameters:
332: + A    - the `SNES` context
333: . obj  - Optional object that provides the options prefix for the checks
334: - name - command line option

336:   Options Database Key:
337: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

339:   Level: intermediate

341: .seealso: [](ch_snes), `SNES`, `SNESView`, `PetscObjectViewFromOptions()`, `SNESCreate()`
342: @*/
343: PetscErrorCode SNESViewFromOptions(SNES A, PetscObject obj, const char name[])
344: {
345:   PetscFunctionBegin;
347:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
348:   PetscFunctionReturn(PETSC_SUCCESS);
349: }

351: PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES, Vec, Mat, Mat, void *);

353: /*@
354:   SNESView - Prints or visualizes the `SNES` data structure.

356:   Collective

358:   Input Parameters:
359: + snes   - the `SNES` context
360: - viewer - the `PetscViewer`

362:   Options Database Key:
363: . -snes_view - Calls `SNESView()` at end of `SNESSolve()`

365:   Level: beginner

367:   Notes:
368:   The available visualization contexts include
369: +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
370: -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
371:   output where only the first processor opens
372:   the file.  All other processors send their
373:   data to the first processor to print.

375:   The available formats include
376: +     `PETSC_VIEWER_DEFAULT` - standard output (default)
377: -     `PETSC_VIEWER_ASCII_INFO_DETAIL` - more verbose output for `SNESNASM`

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

382:   In the debugger you can do "call `SNESView`(snes,0)" to display the `SNES` solver. (The same holds for any PETSc object viewer).

384: .seealso: [](ch_snes), `SNES`, `SNESLoad()`, `SNESCreate()`, `PetscViewerASCIIOpen()`
385: @*/
386: PetscErrorCode SNESView(SNES snes, PetscViewer viewer)
387: {
388:   SNESKSPEW     *kctx;
389:   KSP            ksp;
390:   Vec            u;
391:   SNESLineSearch linesearch;
392:   PetscBool      isascii, isstring, isbinary, isdraw;
393:   DMSNES         dmsnes;
394: #if PetscDefined(HAVE_SAWS)
395:   PetscBool issaws;
396: #endif

398:   PetscFunctionBegin;
400:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &viewer));
402:   PetscCheckSameComm(snes, 1, viewer, 2);

404:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
405:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
406:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
407:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
408: #if PetscDefined(HAVE_SAWS)
409:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
410: #endif
411:   if (isascii) {
412:     SNESNormSchedule normschedule;
413:     DM               dm;
414:     SNESJacobianFn  *cJ;
415:     void            *ctx;
416:     const char      *pre = "";

418:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes, viewer));
419:     if (!snes->setupcalled) PetscCall(PetscViewerASCIIPrintf(viewer, "  SNES has not been set up so information may be incomplete\n"));
420:     if (snes->ops->view) {
421:       PetscCall(PetscViewerASCIIPushTab(viewer));
422:       PetscUseTypeMethod(snes, view, viewer);
423:       PetscCall(PetscViewerASCIIPopTab(viewer));
424:     }
425:     if (snes->max_funcs == PETSC_UNLIMITED) {
426:       PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum iterations=%" PetscInt_FMT ", maximum function evaluations=unlimited\n", snes->max_its));
427:     } else {
428:       PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n", snes->max_its, snes->max_funcs));
429:     }
430:     PetscCall(PetscViewerASCIIPrintf(viewer, "  tolerances: relative=%g, absolute=%g, solution=%g\n", (double)snes->rtol, (double)snes->abstol, (double)snes->stol));
431:     if (snes->usesksp) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", snes->linear_its));
432:     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of function evaluations=%" PetscInt_FMT "\n", snes->nfuncs));
433:     PetscCall(SNESGetNormSchedule(snes, &normschedule));
434:     if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer, "  norm schedule %s\n", SNESNormSchedules[normschedule]));
435:     if (snes->gridsequence) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of grid sequence refinements=%" PetscInt_FMT "\n", snes->gridsequence));
436:     if (snes->ksp_ewconv) {
437:       kctx = (SNESKSPEW *)snes->kspconvctx;
438:       if (kctx) {
439:         PetscCall(PetscViewerASCIIPrintf(viewer, "  Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n", kctx->version));
440:         PetscCall(PetscViewerASCIIPrintf(viewer, "    rtol_0=%g, rtol_max=%g, threshold=%g\n", (double)kctx->rtol_0, (double)kctx->rtol_max, (double)kctx->threshold));
441:         PetscCall(PetscViewerASCIIPrintf(viewer, "    gamma=%g, alpha=%g, alpha2=%g\n", (double)kctx->gamma, (double)kctx->alpha, (double)kctx->alpha2));
442:       }
443:     }
444:     if (snes->lagpreconditioner == -1) {
445:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Preconditioned is never rebuilt\n"));
446:     } else if (snes->lagpreconditioner > 1) {
447:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n", snes->lagpreconditioner));
448:     }
449:     if (snes->lagjacobian == -1) {
450:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Jacobian is never rebuilt\n"));
451:     } else if (snes->lagjacobian > 1) {
452:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n", snes->lagjacobian));
453:     }
454:     PetscCall(SNESGetDM(snes, &dm));
455:     PetscCall(DMSNESGetJacobian(dm, &cJ, &ctx));
456:     if (snes->mf_operator) {
457:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Jacobian is applied matrix-free with differencing\n"));
458:       pre = "Preconditioning ";
459:     }
460:     if (cJ == SNESComputeJacobianDefault) {
461:       PetscCall(PetscViewerASCIIPrintf(viewer, "  %sJacobian is built using finite differences one column at a time\n", pre));
462:     } else if (cJ == SNESComputeJacobianDefaultColor) {
463:       PetscCall(PetscViewerASCIIPrintf(viewer, "  %sJacobian is built using finite differences with coloring\n", pre));
464:       /* it slightly breaks data encapsulation for access the DMDA information directly */
465:     } else if (cJ == SNESComputeJacobian_DMDA) {
466:       MatFDColoring fdcoloring;
467:       PetscCall(PetscObjectQuery((PetscObject)dm, "DMDASNES_FDCOLORING", (PetscObject *)&fdcoloring));
468:       if (fdcoloring) {
469:         PetscCall(PetscViewerASCIIPrintf(viewer, "  %sJacobian is built using colored finite differences on a DMDA\n", pre));
470:       } else {
471:         PetscCall(PetscViewerASCIIPrintf(viewer, "  %sJacobian is built using a DMDA local Jacobian\n", pre));
472:       }
473:     } else if (snes->mf && !snes->mf_operator) {
474:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
475:     }
476:   } else if (isstring) {
477:     const char *type;
478:     PetscCall(SNESGetType(snes, &type));
479:     PetscCall(PetscViewerStringSPrintf(viewer, " SNESType: %-7.7s", type));
480:     PetscTryTypeMethod(snes, view, viewer);
481:   } else if (isbinary) {
482:     PetscInt    classid = SNES_FILE_CLASSID;
483:     MPI_Comm    comm;
484:     PetscMPIInt rank;
485:     char        type[256];

487:     PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
488:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
489:     if (rank == 0) {
490:       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
491:       PetscCall(PetscStrncpy(type, ((PetscObject)snes)->type_name, sizeof(type)));
492:       PetscCall(PetscViewerBinaryWrite(viewer, type, sizeof(type), PETSC_CHAR));
493:     }
494:     PetscTryTypeMethod(snes, view, viewer);
495:   } else if (isdraw) {
496:     PetscDraw draw;
497:     char      str[36];
498:     PetscReal x, y, bottom, h;

500:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
501:     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
502:     PetscCall(PetscStrncpy(str, "SNES: ", sizeof(str)));
503:     PetscCall(PetscStrlcat(str, ((PetscObject)snes)->type_name, sizeof(str)));
504:     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLUE, PETSC_DRAW_BLACK, str, NULL, &h));
505:     bottom = y - h;
506:     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
507:     PetscTryTypeMethod(snes, view, viewer);
508: #if PetscDefined(HAVE_SAWS)
509:   } else if (issaws) {
510:     PetscMPIInt rank;
511:     const char *name;

513:     PetscCall(PetscObjectGetName((PetscObject)snes, &name));
514:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
515:     if (!((PetscObject)snes)->amsmem && rank == 0) {
516:       char dir[1024];

518:       PetscCall(PetscObjectViewSAWs((PetscObject)snes, viewer));
519:       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/its", name));
520:       PetscCallSAWs(SAWs_Register, (dir, &snes->iter, 1, SAWs_READ, SAWs_INT));
521:       if (!snes->conv_hist) PetscCall(SNESSetConvergenceHistory(snes, NULL, NULL, PETSC_DECIDE, PETSC_TRUE));
522:       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/conv_hist", name));
523:       PetscCallSAWs(SAWs_Register, (dir, snes->conv_hist, 10, SAWs_READ, SAWs_DOUBLE));
524:     }
525: #endif
526:   }
527:   if (snes->linesearch) {
528:     PetscCall(SNESGetLineSearch(snes, &linesearch));
529:     PetscCall(PetscViewerASCIIPushTab(viewer));
530:     PetscCall(SNESLineSearchView(linesearch, viewer));
531:     PetscCall(PetscViewerASCIIPopTab(viewer));
532:   }
533:   if (snes->npc && snes->usesnpc) {
534:     PetscCall(PetscViewerASCIIPushTab(viewer));
535:     PetscCall(SNESView(snes->npc, viewer));
536:     PetscCall(PetscViewerASCIIPopTab(viewer));
537:   }
538:   PetscCall(PetscViewerASCIIPushTab(viewer));
539:   PetscCall(DMGetDMSNES(snes->dm, &dmsnes));
540:   PetscCall(DMSNESView(dmsnes, viewer));
541:   PetscCall(PetscViewerASCIIPopTab(viewer));
542:   if (snes->usesksp) {
543:     PetscCall(SNESGetKSP(snes, &ksp));
544:     PetscCall(PetscViewerASCIIPushTab(viewer));
545:     PetscCall(KSPView(ksp, viewer));
546:     PetscCall(PetscViewerASCIIPopTab(viewer));
547:   } else {
548:     PetscViewerFormat format;

550:     PetscCall(SNESGetSolution(snes, &u));
551:     PetscCall(PetscViewerGetFormat(viewer, &format));
552:     if (u && isascii) {
553:       if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
554:       PetscCall(PetscViewerASCIIPrintf(viewer, "solution vector:\n"));
555:       PetscCall(PetscViewerASCIIPushTab(viewer));
556:       PetscCall(VecView(u, viewer));
557:       PetscCall(PetscViewerASCIIPopTab(viewer));
558:       if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerPopFormat(viewer));
559:     }
560:   }
561:   if (isdraw) {
562:     PetscDraw draw;
563:     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
564:     PetscCall(PetscDrawPopCurrentPoint(draw));
565:   }
566:   PetscFunctionReturn(PETSC_SUCCESS);
567: }

569: /*
570:   We retain a list of functions that also take SNES command
571:   line options. These are called at the end SNESSetFromOptions()
572: */
573: #define MAXSETFROMOPTIONS 5
574: static PetscInt numberofsetfromoptions;
575: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

577: /*@
578:   SNESAddOptionsChecker - Adds an additional function to check for `SNES` options.

580:   Not Collective

582:   Input Parameter:
583: . snescheck - function that checks for options

585:   Calling sequence of `snescheck`:
586: . snes - the `SNES` object for which it is checking options

588:   Level: developer

590: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`
591: @*/
592: PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES snes))
593: {
594:   PetscFunctionBegin;
595:   PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
596:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
597:   PetscFunctionReturn(PETSC_SUCCESS);
598: }

600: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
601: {
602:   Mat          J;
603:   MatNullSpace nullsp;

605:   PetscFunctionBegin;

608:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
609:     Mat A = snes->jacobian, B = snes->jacobian_pre;
610:     PetscCall(MatCreateVecs(A ? A : B, NULL, &snes->vec_func));
611:   }

613:   PetscCheck(version == 1 || version == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
614:   if (version == 1) {
615:     PetscCall(MatCreateSNESMF(snes, &J));
616:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
617:     PetscCall(MatSetFromOptions(J));
618:     /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
619:   } else /* if (version == 2) */ {
620:     PetscCheck(snes->vec_func, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SNESSetFunction() must be called first");
621: #if !PetscDefined(USE_COMPLEX) && !PetscDefined(USE_REAL_SINGLE) && !PetscDefined(USE_REAL___FLOAT128) && !PetscDefined(USE_REAL___FP16)
622:     PetscCall(MatCreateSNESMFMore(snes, snes->vec_func, &J));
623: #else
624:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
625: #endif
626:   }

628:   /* attach any user provided null space that was on Amat to the newly created matrix-free matrix */
629:   if (snes->jacobian) {
630:     PetscCall(MatGetNullSpace(snes->jacobian, &nullsp));
631:     if (nullsp) PetscCall(MatSetNullSpace(J, nullsp));
632:   }

634:   PetscCall(PetscInfo(snes, "Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
635:   if (hasOperator) {
636:     /* This version replaces the user provided Jacobian matrix with a
637:        matrix-free version but still employs the user-provided matrix used for computing the preconditioner. */
638:     PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
639:   } else {
640:     /* This version replaces both the user-provided Jacobian and the user-
641:      provided preconditioner Jacobian with the default matrix-free version. */
642:     if (snes->npcside == PC_LEFT && snes->npc) {
643:       if (!snes->jacobian) PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
644:     } else PetscCall(SNESSetJacobian(snes, J, J, MatMFFDComputeJacobian, NULL));
645:   }
646:   PetscCall(MatDestroy(&J));
647:   PetscFunctionReturn(PETSC_SUCCESS);
648: }

650: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine, Mat Restrict, Vec Rscale, Mat Inject, DM dmcoarse, PetscCtx ctx)
651: {
652:   SNES snes = (SNES)ctx;
653:   Vec  Xfine, Xfine_named = NULL, Xcoarse;

655:   PetscFunctionBegin;
656:   if (PetscLogPrintInfo) {
657:     PetscInt finelevel, coarselevel, fineclevel, coarseclevel;
658:     PetscCall(DMGetRefineLevel(dmfine, &finelevel));
659:     PetscCall(DMGetCoarsenLevel(dmfine, &fineclevel));
660:     PetscCall(DMGetRefineLevel(dmcoarse, &coarselevel));
661:     PetscCall(DMGetCoarsenLevel(dmcoarse, &coarseclevel));
662:     PetscCall(PetscInfo(dmfine, "Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n", finelevel, fineclevel, coarselevel, coarseclevel));
663:   }
664:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
665:   else {
666:     PetscCall(DMGetNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
667:     Xfine = Xfine_named;
668:   }
669:   PetscCall(DMGetNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
670:   if (Inject) {
671:     PetscCall(MatRestrict(Inject, Xfine, Xcoarse));
672:   } else {
673:     PetscCall(MatRestrict(Restrict, Xfine, Xcoarse));
674:     PetscCall(VecPointwiseMult(Xcoarse, Xcoarse, Rscale));
675:   }
676:   PetscCall(DMRestoreNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
677:   if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
678:   PetscFunctionReturn(PETSC_SUCCESS);
679: }

681: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm, DM dmc, PetscCtx ctx)
682: {
683:   PetscFunctionBegin;
684:   PetscCall(DMCoarsenHookAdd(dmc, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, ctx));
685:   PetscFunctionReturn(PETSC_SUCCESS);
686: }

688: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
689:  * safely call SNESGetDM() in their residual evaluation routine. */
690: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp, Mat A, Mat B, PetscCtx ctx)
691: {
692:   SNES            snes = (SNES)ctx;
693:   DMSNES          sdm;
694:   Vec             X, Xnamed = NULL;
695:   DM              dmsave;
696:   void           *ctxsave;
697:   SNESJacobianFn *jac = NULL;

699:   PetscFunctionBegin;
700:   dmsave = snes->dm;
701:   PetscCall(KSPGetDM(ksp, &snes->dm));
702:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
703:   else {
704:     PetscBool has;

706:     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
707:     PetscCall(DMHasNamedGlobalVector(snes->dm, "SNESVecSol", &has));
708:     PetscCheck(has, PetscObjectComm((PetscObject)snes->dm), PETSC_ERR_PLIB, "Missing SNESVecSol");
709:     PetscCall(DMGetNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
710:     X = Xnamed;
711:     PetscCall(SNESGetJacobian(snes, NULL, NULL, &jac, &ctxsave));
712:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
713:     if (jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, SNESComputeJacobianDefaultColor, NULL));
714:   }

716:   /* Compute the operators */
717:   PetscCall(DMGetDMSNES(snes->dm, &sdm));
718:   if (Xnamed && sdm->ops->computefunction) {
719:     /* The SNES contract with the user is that ComputeFunction is always called before ComputeJacobian.
720:        We make sure of this here. Disable affine shift since it is for the finest level */
721:     Vec F, saverhs = snes->vec_rhs;

723:     snes->vec_rhs = NULL;
724:     PetscCall(DMGetGlobalVector(snes->dm, &F));
725:     PetscCall(SNESComputeFunction(snes, X, F));
726:     PetscCall(DMRestoreGlobalVector(snes->dm, &F));
727:     snes->vec_rhs = saverhs;
728:     snes->nfuncs--; /* Do not log coarser level evaluations */
729:   }
730:   /* Make sure KSP DM has the Jacobian computation routine */
731:   if (!sdm->ops->computejacobian) PetscCall(DMCopyDMSNES(dmsave, snes->dm));
732:   PetscCall(SNESComputeJacobian(snes, X, A, B)); /* cannot handle previous SNESSetJacobianDomainError() calls */

734:   /* Put the previous context back */
735:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, jac, ctxsave));

737:   if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
738:   snes->dm = dmsave;
739:   PetscFunctionReturn(PETSC_SUCCESS);
740: }

742: /*@
743:   SNESSetUpMatrices - ensures that matrices are available for `SNES` Newton-like methods, this is called by `SNESSetUp_XXX()`

745:   Collective

747:   Input Parameter:
748: . snes - `SNES` object to configure

750:   Level: developer

752:   Note:
753:   If the matrices do not yet exist it attempts to create them based on options previously set for the `SNES` such as `-snes_mf`

755:   Developer Note:
756:   The functionality of this routine overlaps in a confusing way with the functionality of `SNESSetUpMatrixFree_Private()` which is called by
757:   `SNESSetUp()` but sometimes `SNESSetUpMatrices()` is called without `SNESSetUp()` being called. A refactorization to simplify the
758:   logic that handles the matrix-free case is desirable.

760: .seealso: [](ch_snes), `SNES`, `SNESSetUp()`
761: @*/
762: PetscErrorCode SNESSetUpMatrices(SNES snes)
763: {
764:   DM     dm;
765:   DMSNES sdm;

767:   PetscFunctionBegin;
768:   PetscCall(SNESGetDM(snes, &dm));
769:   PetscCall(DMGetDMSNES(dm, &sdm));
770:   if (!snes->jacobian && snes->mf && !snes->mf_operator && !snes->jacobian_pre) {
771:     Mat   J;
772:     void *functx;
773:     PetscCall(MatCreateSNESMF(snes, &J));
774:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
775:     PetscCall(MatSetFromOptions(J));
776:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
777:     PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
778:     PetscCall(MatDestroy(&J));
779:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
780:     Mat J, B;
781:     PetscCall(MatCreateSNESMF(snes, &J));
782:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
783:     PetscCall(MatSetFromOptions(J));
784:     PetscCall(DMCreateMatrix(snes->dm, &B));
785:     /* sdm->computejacobian was already set to reach here */
786:     PetscCall(SNESSetJacobian(snes, J, B, NULL, NULL));
787:     PetscCall(MatDestroy(&J));
788:     PetscCall(MatDestroy(&B));
789:   } else if (!snes->jacobian_pre) {
790:     PetscDS   prob;
791:     Mat       J, B;
792:     PetscBool hasPrec = PETSC_FALSE;

794:     J = snes->jacobian;
795:     PetscCall(DMGetDS(dm, &prob));
796:     if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
797:     if (!J && hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
798:     else PetscCall(PetscObjectReference((PetscObject)J));
799:     PetscCall(DMCreateMatrix(snes->dm, &B));
800:     PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
801:     PetscCall(MatDestroy(&J));
802:     PetscCall(MatDestroy(&B));
803:   }
804:   {
805:     KSP ksp;
806:     PetscCall(SNESGetKSP(snes, &ksp));
807:     PetscCall(KSPSetComputeOperators(ksp, KSPComputeOperators_SNES, snes));
808:     PetscCall(DMCoarsenHookAdd(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
809:   }
810:   PetscFunctionReturn(PETSC_SUCCESS);
811: }

813: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);

815: static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
816: {
817:   PetscFunctionBegin;
818:   if (!snes->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
819:   PetscCall(PetscMonitorPauseFinal_Internal(snes->numbermonitors, snes->monitorcontext));
820:   PetscFunctionReturn(PETSC_SUCCESS);
821: }

823: /*@
824:   SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

826:   Collective

828:   Input Parameters:
829: + snes         - `SNES` object you wish to monitor
830: . name         - the monitor type one is seeking
831: . help         - message indicating what monitoring is done
832: . manual       - manual page for the monitor
833: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
834: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the `SNES` or `PetscViewer` objects

836:   Calling sequence of `monitor`:
837: + snes - the nonlinear solver context
838: . it   - the current iteration
839: . r    - the current function norm
840: - vf   - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use

842:   Calling sequence of `monitorsetup`:
843: + snes - the nonlinear solver context
844: - vf   - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use

846:   Options Database Key:
847: . -name - trigger the use of this monitor in `SNESSetFromOptions()`

849:   Level: advanced

851: .seealso: [](ch_snes), `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
852:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
853:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
854:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
855:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
856:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
857:           `PetscOptionsFList()`, `PetscOptionsEList()`
858: @*/
859: PetscErrorCode SNESMonitorSetFromOptions(SNES snes, const char name[], const char help[], const char manual[], PetscErrorCode (*monitor)(SNES snes, PetscInt it, PetscReal r, PetscViewerAndFormat *vf), PetscErrorCode (*monitorsetup)(SNES snes, PetscViewerAndFormat *vf))
860: {
861:   PetscViewer       viewer;
862:   PetscViewerFormat format;
863:   PetscBool         flg;

865:   PetscFunctionBegin;
866:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, name, &viewer, &format, &flg));
867:   if (flg) {
868:     PetscViewerAndFormat *vf;
869:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
870:     PetscCall(PetscViewerDestroy(&viewer));
871:     if (monitorsetup) PetscCall((*monitorsetup)(snes, vf));
872:     PetscCall(SNESMonitorSet(snes, (PetscErrorCode (*)(SNES, PetscInt, PetscReal, PetscCtx))monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
873:   }
874:   PetscFunctionReturn(PETSC_SUCCESS);
875: }

877: PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW *kctx, PetscBool print_api, MPI_Comm comm, const char *prefix)
878: {
879:   const char *api = print_api ? "SNESKSPSetParametersEW" : NULL;

881:   PetscFunctionBegin;
882:   PetscOptionsBegin(comm, prefix, "Eisenstat and Walker type forcing options", "KSP");
883:   PetscCall(PetscOptionsInt("-ksp_ew_version", "Version 1, 2 or 3", api, kctx->version, &kctx->version, NULL));
884:   PetscCall(PetscOptionsReal("-ksp_ew_rtol0", "0 <= rtol0 < 1", api, kctx->rtol_0, &kctx->rtol_0, NULL));
885:   kctx->rtol_max = PetscMax(kctx->rtol_0, kctx->rtol_max);
886:   PetscCall(PetscOptionsReal("-ksp_ew_rtolmax", "0 <= rtolmax < 1", api, kctx->rtol_max, &kctx->rtol_max, NULL));
887:   PetscCall(PetscOptionsReal("-ksp_ew_gamma", "0 <= gamma <= 1", api, kctx->gamma, &kctx->gamma, NULL));
888:   PetscCall(PetscOptionsReal("-ksp_ew_alpha", "1 < alpha <= 2", api, kctx->alpha, &kctx->alpha, NULL));
889:   PetscCall(PetscOptionsReal("-ksp_ew_alpha2", "alpha2", NULL, kctx->alpha2, &kctx->alpha2, NULL));
890:   PetscCall(PetscOptionsReal("-ksp_ew_threshold", "0 < threshold < 1", api, kctx->threshold, &kctx->threshold, NULL));
891:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p1", "p1", NULL, kctx->v4_p1, &kctx->v4_p1, NULL));
892:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p2", "p2", NULL, kctx->v4_p2, &kctx->v4_p2, NULL));
893:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p3", "p3", NULL, kctx->v4_p3, &kctx->v4_p3, NULL));
894:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m1", "Scaling when rk-1 in [p2,p3)", NULL, kctx->v4_m1, &kctx->v4_m1, NULL));
895:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m2", "Scaling when rk-1 in [p3,+infty)", NULL, kctx->v4_m2, &kctx->v4_m2, NULL));
896:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m3", "Threshold for successive rtol (0.1 in Eq.7)", NULL, kctx->v4_m3, &kctx->v4_m3, NULL));
897:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m4", "Adaptation scaling (0.5 in Eq.7)", NULL, kctx->v4_m4, &kctx->v4_m4, NULL));
898:   PetscOptionsEnd();
899:   PetscFunctionReturn(PETSC_SUCCESS);
900: }

902: /*@
903:   SNESSetFromOptions - Sets various `SNES` and `KSP` parameters from user options.

905:   Collective

907:   Input Parameter:
908: . snes - the `SNES` context

910:   Options Database Keys:
911: + -snes_type type                                                              - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, `SNESType` for complete list
912: . -snes_rtol rtol                                                              - relative decrease in tolerance norm from initial
913: . -snes_atol abstol                                                            - absolute tolerance of residual norm
914: . -snes_stol stol                                                              - convergence tolerance in terms of the norm of the change in the solution between steps
915: . -snes_divergence_tolerance divtol                                            - if the residual goes above divtol*rnorm0, exit with divergence
916: . -snes_max_it max_it                                                          - maximum number of iterations
917: . -snes_max_funcs max_funcs                                                    - maximum number of function evaluations
918: . -snes_force_iteration force                                                  - force `SNESSolve()` to take at least one iteration
919: . -snes_max_fail max_fail                                                      - maximum number of line search failures allowed before stopping, default is none
920: . -snes_max_linear_solve_fail                                                  - number of linear solver failures before SNESSolve() stops
921: . -snes_lag_preconditioner lag                                                 - how often preconditioner is rebuilt (use -1 to never rebuild)
922: . -snes_lag_preconditioner_persists (true|false)                               - retains the -snes_lag_preconditioner information across multiple SNESSolve()
923: . -snes_lag_jacobian lag                                                       - how often Jacobian is rebuilt (use -1 to never rebuild)
924: . -snes_lag_jacobian_persists (true|false)                                     - retains the -snes_lag_jacobian information across multiple SNESSolve()
925: . -snes_convergence_test (default|skip|correct_pressure)                       - convergence test in nonlinear solver. default `SNESConvergedDefault()`. skip `SNESConvergedSkip()` means continue
926:                                                                                  iterating until max_it or some other criterion is reached, saving expense of convergence test. correct_pressure
927:                                                                                  `SNESConvergedCorrectPressure()` has special handling of a pressure null space.
928: . -snes_monitor [ascii][:filename][:viewer format]                             - prints residual norm at each iteration. if no filename given prints to stdout
929: . -snes_monitor_solution [ascii binary draw][:filename][:viewer format]        - plots solution at each iteration
930: . -snes_monitor_residual [ascii binary draw][:filename][:viewer format]        - plots residual (not its norm) at each iteration
931: . -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
932: . -snes_monitor draw::draw_lg                                                  - plots residual norm at each iteration
933: . -snes_monitor_lg_range                                                       - plots function range at each iteration
934: . -snes_monitor_pause_final                                                    - Pauses all monitor drawing after the solver ends
935: . -snes_fd                                                                     - use finite differences to compute Jacobian; very slow, only for testing
936: . -snes_fd_color                                                               - use finite differences with coloring to compute Jacobian
937: . -snes_mf_ksp_monitor                                                         - if using matrix-free multiply then print h at each `KSP` iteration
938: . -snes_converged_reason                                                       - print the reason for convergence/divergence after each solve
939: . -npc_snes_type type                                                          - the `SNES` type to use as a nonlinear preconditioner
940: . -snes_test_jacobian [threshold]                                              - compare the user provided Jacobian with one computed via finite differences to check for errors.
941:                                                                                  If a threshold is given, display only those entries whose difference is greater than the threshold.
942: - -snes_test_jacobian_view                                                     - display the user provided Jacobian, the finite difference Jacobian and the difference between them
943:                                                                                  to help users detect the location of errors in the user provided Jacobian.

945:   Options Database Keys for Eisenstat-Walker method:
946: + -snes_ksp_ew                     - use Eisenstat-Walker method for determining linear system convergence
947: . -snes_ksp_ew_version ver         - version of  Eisenstat-Walker method
948: . -snes_ksp_ew_rtol0 rtol0         - Sets rtol0
949: . -snes_ksp_ew_rtolmax rtolmax     - Sets rtolmax
950: . -snes_ksp_ew_gamma gamma         - Sets gamma
951: . -snes_ksp_ew_alpha alpha         - Sets alpha
952: . -snes_ksp_ew_alpha2 alpha2       - Sets alpha2
953: - -snes_ksp_ew_threshold threshold - Sets threshold

955:   Level: beginner

957:   Notes:
958:   To see all options, run your program with the -help option or consult the users manual

960:   See `SNESLineSearchSetFromOptions()` for all the line search options available

962:   `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
963:   and computing explicitly with
964:   finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.

966: .seealso: [](ch_snes), `SNESType`, `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`, `MatCreateSNESMF()`, `MatFDColoring`, `SNESLineSearchSetFromOptions()`
967: @*/
968: PetscErrorCode SNESSetFromOptions(SNES snes)
969: {
970:   PetscBool   flg, pcset, persist, set;
971:   PetscInt    i, indx, lag, grids, max_its, max_funcs;
972:   const char *deft        = SNESNEWTONLS;
973:   const char *convtests[] = {"default", "skip", "correct_pressure"};
974:   SNESKSPEW  *kctx        = NULL;
975:   char        type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
976:   PCSide      pcside;
977:   const char *optionsprefix;
978:   PetscReal   rtol, abstol, stol;

980:   PetscFunctionBegin;
982:   PetscCall(SNESRegisterAll());
983:   PetscObjectOptionsBegin((PetscObject)snes);
984:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
985:   PetscCall(PetscOptionsFList("-snes_type", "Nonlinear solver method", "SNESSetType", SNESList, deft, type, 256, &flg));
986:   if (flg) PetscCall(SNESSetType(snes, type));
987:   else if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, deft));

989:   abstol    = snes->abstol;
990:   rtol      = snes->rtol;
991:   stol      = snes->stol;
992:   max_its   = snes->max_its;
993:   max_funcs = snes->max_funcs;
994:   PetscCall(PetscOptionsReal("-snes_rtol", "Stop if decrease in function norm less than", "SNESSetTolerances", snes->rtol, &rtol, NULL));
995:   PetscCall(PetscOptionsReal("-snes_atol", "Stop if function norm less than", "SNESSetTolerances", snes->abstol, &abstol, NULL));
996:   PetscCall(PetscOptionsReal("-snes_stol", "Stop if step length less than", "SNESSetTolerances", snes->stol, &stol, NULL));
997:   PetscCall(PetscOptionsInt("-snes_max_it", "Maximum iterations", "SNESSetTolerances", snes->max_its, &max_its, NULL));
998:   PetscCall(PetscOptionsInt("-snes_max_funcs", "Maximum function evaluations", "SNESSetTolerances", snes->max_funcs, &max_funcs, NULL));
999:   PetscCall(SNESSetTolerances(snes, abstol, rtol, stol, max_its, max_funcs));

1001:   PetscCall(PetscOptionsReal("-snes_divergence_tolerance", "Stop if residual norm increases by this factor", "SNESSetDivergenceTolerance", snes->divtol, &snes->divtol, &flg));
1002:   if (flg) PetscCall(SNESSetDivergenceTolerance(snes, snes->divtol));

1004:   PetscCall(PetscOptionsInt("-snes_max_fail", "Maximum nonlinear step failures", "SNESSetMaxNonlinearStepFailures", snes->maxFailures, &snes->maxFailures, &flg));
1005:   if (flg) PetscCall(SNESSetMaxNonlinearStepFailures(snes, snes->maxFailures));

1007:   PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail", "Maximum failures in linear solves allowed", "SNESSetMaxLinearSolveFailures", snes->maxLinearSolveFailures, &snes->maxLinearSolveFailures, &flg));
1008:   if (flg) PetscCall(SNESSetMaxLinearSolveFailures(snes, snes->maxLinearSolveFailures));

1010:   PetscCall(PetscOptionsBool("-snes_error_if_not_converged", "Generate error if solver does not converge", "SNESSetErrorIfNotConverged", snes->errorifnotconverged, &snes->errorifnotconverged, NULL));
1011:   PetscCall(PetscOptionsBool("-snes_force_iteration", "Force SNESSolve() to take at least one iteration", "SNESSetForceIteration", snes->forceiteration, &snes->forceiteration, NULL));
1012:   PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error", "Check Jacobian domain error after Jacobian evaluation", "SNESCheckJacobianDomainError", snes->checkjacdomainerror, &snes->checkjacdomainerror, NULL));

1014:   PetscCall(PetscOptionsInt("-snes_lag_preconditioner", "How often to rebuild preconditioner", "SNESSetLagPreconditioner", snes->lagpreconditioner, &lag, &flg));
1015:   if (flg) {
1016:     PetscCheck(lag != -1, PetscObjectComm((PetscObject)snes), PETSC_ERR_USER, "Cannot set the lag to -1 from the command line since the preconditioner must be built as least once, perhaps you mean -2");
1017:     PetscCall(SNESSetLagPreconditioner(snes, lag));
1018:   }
1019:   PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists", "Preconditioner lagging through multiple SNES solves", "SNESSetLagPreconditionerPersists", snes->lagjac_persist, &persist, &flg));
1020:   if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes, persist));
1021:   PetscCall(PetscOptionsInt("-snes_lag_jacobian", "How often to rebuild Jacobian", "SNESSetLagJacobian", snes->lagjacobian, &lag, &flg));
1022:   if (flg) {
1023:     PetscCheck(lag != -1, PetscObjectComm((PetscObject)snes), PETSC_ERR_USER, "Cannot set the lag to -1 from the command line since the Jacobian must be built as least once, perhaps you mean -2");
1024:     PetscCall(SNESSetLagJacobian(snes, lag));
1025:   }
1026:   PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists", "Jacobian lagging through multiple SNES solves", "SNESSetLagJacobianPersists", snes->lagjac_persist, &persist, &flg));
1027:   if (flg) PetscCall(SNESSetLagJacobianPersists(snes, persist));

1029:   PetscCall(PetscOptionsInt("-snes_grid_sequence", "Use grid sequencing to generate initial guess", "SNESSetGridSequence", snes->gridsequence, &grids, &flg));
1030:   if (flg) PetscCall(SNESSetGridSequence(snes, grids));

1032:   PetscCall(PetscOptionsEList("-snes_convergence_test", "Convergence test", "SNESSetConvergenceTest", convtests, PETSC_STATIC_ARRAY_LENGTH(convtests), "default", &indx, &flg));
1033:   if (flg) {
1034:     switch (indx) {
1035:     case 0:
1036:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedDefault, NULL, NULL));
1037:       break;
1038:     case 1:
1039:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedSkip, NULL, NULL));
1040:       break;
1041:     case 2:
1042:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedCorrectPressure, NULL, NULL));
1043:       break;
1044:     }
1045:   }

1047:   PetscCall(PetscOptionsEList("-snes_norm_schedule", "SNES Norm schedule", "SNESSetNormSchedule", SNESNormSchedules, 5, "function", &indx, &flg));
1048:   if (flg) PetscCall(SNESSetNormSchedule(snes, (SNESNormSchedule)indx));

1050:   PetscCall(PetscOptionsEList("-snes_function_type", "SNES Norm schedule", "SNESSetFunctionType", SNESFunctionTypes, 2, "unpreconditioned", &indx, &flg));
1051:   if (flg) PetscCall(SNESSetFunctionType(snes, (SNESFunctionType)indx));

1053:   kctx = (SNESKSPEW *)snes->kspconvctx;

1055:   PetscCall(PetscOptionsBool("-snes_ksp_ew", "Use Eisentat-Walker linear system convergence test", "SNESKSPSetUseEW", snes->ksp_ewconv, &snes->ksp_ewconv, NULL));

1057:   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1058:   PetscCall(PetscSNPrintf(ewprefix, sizeof(ewprefix), "%s%s", optionsprefix ? optionsprefix : "", "snes_"));
1059:   PetscCall(SNESEWSetFromOptions_Private(kctx, PETSC_TRUE, PetscObjectComm((PetscObject)snes), ewprefix));

1061:   flg = PETSC_FALSE;
1062:   PetscCall(PetscOptionsBool("-snes_monitor_cancel", "Remove all monitors", "SNESMonitorCancel", flg, &flg, &set));
1063:   if (set && flg) PetscCall(SNESMonitorCancel(snes));

1065:   PetscCall(PetscOptionsDeprecated("-snes_monitor_short", "-snes_monitor", "3.26", NULL));
1066:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor", "Monitor norm of function", "SNESMonitorDefault", SNESMonitorDefault, SNESMonitorDefaultSetUp));
1067:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_range", "Monitor range of elements of function", "SNESMonitorRange", SNESMonitorRange, NULL));

1069:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_ratio", "Monitor ratios of the norm of function for consecutive steps", "SNESMonitorRatio", SNESMonitorRatio, SNESMonitorRatioSetUp));
1070:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_field", "Monitor norm of function (split into fields)", "SNESMonitorDefaultField", SNESMonitorDefaultField, NULL));
1071:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution", "View solution at each iteration", "SNESMonitorSolution", SNESMonitorSolution, NULL));
1072:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution_update", "View correction at each iteration", "SNESMonitorSolutionUpdate", SNESMonitorSolutionUpdate, NULL));
1073:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_residual", "View residual at each iteration", "SNESMonitorResidual", SNESMonitorResidual, NULL));
1074:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_jacupdate_spectrum", "Print the change in the spectrum of the Jacobian", "SNESMonitorJacUpdateSpectrum", SNESMonitorJacUpdateSpectrum, NULL));
1075:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_fields", "Monitor norm of function per field", "SNESMonitorSet", SNESMonitorFields, NULL));
1076:   PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));

1078:   PetscCall(PetscOptionsString("-snes_monitor_python", "Use Python function", "SNESMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1079:   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes, monfilename));

1081:   flg = PETSC_FALSE;
1082:   PetscCall(PetscOptionsBool("-snes_monitor_lg_range", "Plot function range at each iteration", "SNESMonitorLGRange", flg, &flg, NULL));
1083:   if (flg) {
1084:     PetscViewer ctx;

1086:     PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &ctx));
1087:     PetscCall(SNESMonitorSet(snes, SNESMonitorLGRange, ctx, (PetscCtxDestroyFn *)PetscViewerDestroy));
1088:   }

1090:   PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
1091:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_converged_reason", &snes->convergedreasonviewer, &snes->convergedreasonformat, NULL));
1092:   flg = PETSC_FALSE;
1093:   PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel", "Remove all converged reason viewers", "SNESConvergedReasonViewCancel", flg, &flg, &set));
1094:   if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));

1096:   flg = PETSC_FALSE;
1097:   PetscCall(PetscOptionsBool("-snes_fd", "Use finite differences (slow) to compute Jacobian", "SNESComputeJacobianDefault", flg, &flg, NULL));
1098:   if (flg) {
1099:     void *functx;
1100:     DM    dm;
1101:     PetscCall(SNESGetDM(snes, &dm));
1102:     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1103:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
1104:     PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefault, functx));
1105:     PetscCall(PetscInfo(snes, "Setting default finite difference Jacobian matrix\n"));
1106:   }

1108:   flg = PETSC_FALSE;
1109:   PetscCall(PetscOptionsBool("-snes_fd_function", "Use finite differences (slow) to compute function from user objective", "SNESObjectiveComputeFunctionDefaultFD", flg, &flg, NULL));
1110:   if (flg) PetscCall(SNESSetFunction(snes, NULL, SNESObjectiveComputeFunctionDefaultFD, NULL));

1112:   flg = PETSC_FALSE;
1113:   PetscCall(PetscOptionsBool("-snes_fd_color", "Use finite differences with coloring to compute Jacobian", "SNESComputeJacobianDefaultColor", flg, &flg, NULL));
1114:   if (flg) {
1115:     DM dm;
1116:     PetscCall(SNESGetDM(snes, &dm));
1117:     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1118:     PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefaultColor, NULL));
1119:     PetscCall(PetscInfo(snes, "Setting default finite difference coloring Jacobian matrix\n"));
1120:   }

1122:   flg = PETSC_FALSE;
1123:   PetscCall(PetscOptionsBool("-snes_mf_operator", "Use a Matrix-Free Jacobian with user-provided matrix for computing the preconditioner", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf_operator, &flg));
1124:   if (flg && snes->mf_operator) {
1125:     snes->mf_operator = PETSC_TRUE;
1126:     snes->mf          = PETSC_TRUE;
1127:   }
1128:   flg = PETSC_FALSE;
1129:   PetscCall(PetscOptionsBool("-snes_mf", "Use a Matrix-Free Jacobian with no preconditioner by default", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf, &flg));
1130:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1131:   PetscCall(PetscOptionsInt("-snes_mf_version", "Matrix-Free routines version 1 or 2", "None", snes->mf_version, &snes->mf_version, NULL));

1133:   PetscCall(PetscOptionsName("-snes_test_function", "Compare hand-coded and finite difference functions", "None", &snes->testFunc));
1134:   PetscCall(PetscOptionsName("-snes_test_jacobian", "Compare hand-coded and finite difference Jacobians", "None", &snes->testJac));

1136:   flg = PETSC_FALSE;
1137:   PetscCall(SNESGetNPCSide(snes, &pcside));
1138:   PetscCall(PetscOptionsEnum("-snes_npc_side", "SNES nonlinear preconditioner side", "SNESSetNPCSide", PCSides, (PetscEnum)pcside, (PetscEnum *)&pcside, &flg));
1139:   if (flg) PetscCall(SNESSetNPCSide(snes, pcside));

1141: #if PetscDefined(HAVE_SAWS)
1142:   /*
1143:     Publish convergence information using SAWs
1144:   */
1145:   flg = PETSC_FALSE;
1146:   PetscCall(PetscOptionsBool("-snes_monitor_saws", "Publish SNES progress using SAWs", "SNESMonitorSet", flg, &flg, NULL));
1147:   if (flg) {
1148:     PetscCtx ctx;
1149:     PetscCall(SNESMonitorSAWsCreate(snes, &ctx));
1150:     PetscCall(SNESMonitorSet(snes, SNESMonitorSAWs, ctx, SNESMonitorSAWsDestroy));
1151:   }
1152: #endif
1153: #if PetscDefined(HAVE_SAWS)
1154:   {
1155:     PetscBool set;
1156:     flg = PETSC_FALSE;
1157:     PetscCall(PetscOptionsBool("-snes_saws_block", "Block for SAWs at end of SNESSolve", "PetscObjectSAWsBlock", ((PetscObject)snes)->amspublishblock, &flg, &set));
1158:     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes, flg));
1159:   }
1160: #endif

1162:   for (i = 0; i < numberofsetfromoptions; i++) PetscCall((*othersetfromoptions[i])(snes));

1164:   PetscTryTypeMethod(snes, setfromoptions, PetscOptionsObject);

1166:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1167:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)snes, PetscOptionsObject));
1168:   PetscOptionsEnd();

1170:   if (snes->linesearch) {
1171:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
1172:     PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1173:   }

1175:   /* if user has set the SNES NPC type via options database, create it. */
1176:   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1177:   PetscCall(PetscOptionsHasName(((PetscObject)snes)->options, optionsprefix, "-npc_snes_type", &pcset));
1178:   if (pcset && !snes->npc) PetscCall(SNESGetNPC(snes, &snes->npc));

1180:   if (snes->usesksp) {
1181:     PC     pc;
1182:     PCType pctype;

1184:     if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
1185:     PetscCall(KSPSetOperators(snes->ksp, snes->jacobian, snes->jacobian_pre));
1186:     PetscCall(KSPGetPC(snes->ksp, &pc));
1187:     PetscCall(PCGetType(pc, &pctype));
1188:     /* If the first two conditions in the following conditional are true, we know a matrix-free Mat
1189:        will be used eventually with the PC, but we cannot provide the matrix-free Mat to the PC here
1190:        since we do not have enough information to construct it here (it is constructed after the
1191:        start of SNESSetUp()). If we do not set the PCNONE here, then the PCSetFromOptions() called
1192:        from KSPSetFromOptions() below will use PCGetDefaultType_Private() to set a PCType
1193:        appropriate for the current pc->pmat that will likely not work for the matrix-free Mat, thus
1194:        producing a later confusing error message. A significant refactoring of how SNES handles
1195:        matrix-free Mat would be needed to eliminate the next line of code. Note that if the PC type
1196:        has already been set (third condition), we do not override it. The fourth condition exempts
1197:        left-side nonlinear preconditioners, which require a real PC */
1198:     if (snes->mf && !snes->mf_operator && !pctype && !(snes->npcside == PC_LEFT && snes->npc)) {
1199:       PetscCall(PetscInfo(snes, "Setting PCNONE since no PC type was set and the Jacobian will be matrix-free\n"));
1200:       PetscCall(PCSetType(pc, PCNONE));
1201:     }
1202:     PetscCall(KSPSetFromOptions(snes->ksp));
1203:   }

1205:   if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1206:   snes->setfromoptionscalled++;
1207:   PetscFunctionReturn(PETSC_SUCCESS);
1208: }

1210: /*@
1211:   SNESResetFromOptions - Sets various `SNES` and `KSP` parameters from user options ONLY if the `SNESSetFromOptions()` was previously called

1213:   Collective

1215:   Input Parameter:
1216: . snes - the `SNES` context

1218:   Level: advanced

1220: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1221: @*/
1222: PetscErrorCode SNESResetFromOptions(SNES snes)
1223: {
1224:   PetscFunctionBegin;
1225:   if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1226:   PetscFunctionReturn(PETSC_SUCCESS);
1227: }

1229: /*@
1230:   SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1231:   the nonlinear solvers.

1233:   Logically Collective; No Fortran Support

1235:   Input Parameters:
1236: + snes    - the `SNES` context
1237: . compute - function to compute the context
1238: - destroy - function to destroy the context, see `PetscCtxDestroyFn` for the calling sequence

1240:   Calling sequence of `compute`:
1241: + snes - the `SNES` context
1242: - ctx  - context to be computed

1244:   Level: intermediate

1246:   Note:
1247:   This routine is useful if you are performing grid sequencing or using `SNESFAS` and need the appropriate context generated for each level.

1249:   Use `SNESSetApplicationContext()` to see the context immediately

1251: .seealso: [](ch_snes), `SNESGetApplicationContext()`, `SNESSetApplicationContext()`, `PetscCtxDestroyFn`
1252: @*/
1253: PetscErrorCode SNESSetComputeApplicationContext(SNES snes, PetscErrorCode (*compute)(SNES snes, PetscCtxRt ctx), PetscCtxDestroyFn *destroy)
1254: {
1255:   PetscFunctionBegin;
1257:   snes->ops->ctxcompute = compute;
1258:   snes->ops->ctxdestroy = destroy;
1259:   PetscFunctionReturn(PETSC_SUCCESS);
1260: }

1262: /*@
1263:   SNESSetApplicationContext - Sets the optional user-defined context for the nonlinear solvers.

1265:   Logically Collective

1267:   Input Parameters:
1268: + snes - the `SNES` context
1269: - ctx  - the application context

1271:   Level: intermediate

1273:   Notes:
1274:   Users can provide a context when constructing the `SNES` options and then access it inside their function, Jacobian computation, or other evaluation function
1275:   with `SNESGetApplicationContext()`

1277:   To provide a function that computes the context for you use `SNESSetComputeApplicationContext()`

1279:   Fortran Note:
1280:   This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
1281:   function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `SNESGetApplicationContext()` for
1282:   an example.

1284: .seealso: [](ch_snes), `SNES`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1285: @*/
1286: PetscErrorCode SNESSetApplicationContext(SNES snes, PetscCtx ctx)
1287: {
1288:   KSP ksp;

1290:   PetscFunctionBegin;
1292:   PetscCall(SNESGetKSP(snes, &ksp));
1293:   PetscCall(KSPSetApplicationContext(ksp, ctx));
1294:   snes->ctx = ctx;
1295:   PetscFunctionReturn(PETSC_SUCCESS);
1296: }

1298: /*@
1299:   SNESGetApplicationContext - Gets the user-defined context for the
1300:   nonlinear solvers set with `SNESGetApplicationContext()` or `SNESSetComputeApplicationContext()`

1302:   Not Collective

1304:   Input Parameter:
1305: . snes - `SNES` context

1307:   Output Parameter:
1308: . ctx - the application context

1310:   Level: intermediate

1312:   Fortran Notes:
1313:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
1314: .vb
1315:   type(tUsertype), pointer :: ctx
1316: .ve

1318: .seealso: [](ch_snes), `SNESSetApplicationContext()`, `SNESSetComputeApplicationContext()`
1319: @*/
1320: PetscErrorCode SNESGetApplicationContext(SNES snes, PetscCtxRt ctx)
1321: {
1322:   PetscFunctionBegin;
1324:   *(void **)ctx = snes->ctx;
1325:   PetscFunctionReturn(PETSC_SUCCESS);
1326: }

1328: /*@
1329:   SNESSetUseMatrixFree - indicates that `SNES` should use matrix-free finite difference matrix-vector products to apply the Jacobian.

1331:   Logically Collective

1333:   Input Parameters:
1334: + snes        - `SNES` context
1335: . mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1336: - mf          - use matrix-free for both the Amat and Pmat used by `SNESSetJacobian()`, both the Amat and Pmat set in `SNESSetJacobian()` will be ignored. With
1337:                 this option no matrix-element based preconditioners can be used in the linear solve since the matrix won't be explicitly available

1339:   Options Database Keys:
1340: + -snes_mf_operator - use matrix-free only for the mat operator
1341: . -snes_mf          - use matrix-free for both the mat and pmat operator
1342: . -snes_fd_color    - compute the Jacobian via coloring and finite differences.
1343: - -snes_fd          - compute the Jacobian via finite differences (slow)

1345:   Level: intermediate

1347:   Notes:
1348:   `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
1349:   and computing explicitly with
1350:   finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.

1352:   When `mf` is used, `SNESSetFromOptions()` sets the `KSP`'s `PC` to `PCNONE` unless a `PC` type has already been selected.

1354: .seealso: [](ch_snes), `SNES`, `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`, `MatFDColoring`
1355: @*/
1356: PetscErrorCode SNESSetUseMatrixFree(SNES snes, PetscBool mf_operator, PetscBool mf)
1357: {
1358:   PetscFunctionBegin;
1362:   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1363:   snes->mf_operator = mf_operator;
1364:   PetscFunctionReturn(PETSC_SUCCESS);
1365: }

1367: /*@
1368:   SNESGetUseMatrixFree - indicates if the `SNES` uses matrix-free finite difference matrix vector products to apply the Jacobian.

1370:   Not Collective, but the resulting flags will be the same on all MPI processes

1372:   Input Parameter:
1373: . snes - `SNES` context

1375:   Output Parameters:
1376: + mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1377: - mf          - use matrix-free for both the Amat and Pmat used by `SNESSetJacobian()`, both the Amat and Pmat set in `SNESSetJacobian()` will be ignored

1379:   Level: intermediate

1381: .seealso: [](ch_snes), `SNES`, `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1382: @*/
1383: PetscErrorCode SNESGetUseMatrixFree(SNES snes, PetscBool *mf_operator, PetscBool *mf)
1384: {
1385:   PetscFunctionBegin;
1387:   if (mf) *mf = snes->mf;
1388:   if (mf_operator) *mf_operator = snes->mf_operator;
1389:   PetscFunctionReturn(PETSC_SUCCESS);
1390: }

1392: /*@
1393:   SNESGetIterationNumber - Gets the number of nonlinear iterations completed in the current or most recent `SNESSolve()`

1395:   Not Collective

1397:   Input Parameter:
1398: . snes - `SNES` context

1400:   Output Parameter:
1401: . iter - iteration number

1403:   Level: intermediate

1405:   Notes:
1406:   For example, during the computation of iteration 2 this would return 1.

1408:   This is useful for using lagged Jacobians (where one does not recompute the
1409:   Jacobian at each `SNES` iteration). For example, the code
1410: .vb
1411:       ierr = SNESGetIterationNumber(snes,&it);
1412:       if (!(it % 2)) {
1413:         [compute Jacobian here]
1414:       }
1415: .ve
1416:   can be used in your function that computes the Jacobian to cause the Jacobian to be
1417:   recomputed every second `SNES` iteration. See also `SNESSetLagJacobian()`

1419:   After the `SNES` solve is complete this will return the number of nonlinear iterations used.

1421: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetLagJacobian()`, `SNESGetLinearSolveIterations()`, `SNESSetMonitor()`
1422: @*/
1423: PetscErrorCode SNESGetIterationNumber(SNES snes, PetscInt *iter)
1424: {
1425:   PetscFunctionBegin;
1427:   PetscAssertPointer(iter, 2);
1428:   *iter = snes->iter;
1429:   PetscFunctionReturn(PETSC_SUCCESS);
1430: }

1432: /*@
1433:   SNESSetIterationNumber - Sets the current iteration number.

1435:   Not Collective

1437:   Input Parameters:
1438: + snes - `SNES` context
1439: - iter - iteration number

1441:   Level: developer

1443:   Note:
1444:   This should only be called inside a `SNES` nonlinear solver.

1446: .seealso: [](ch_snes), `SNESGetLinearSolveIterations()`
1447: @*/
1448: PetscErrorCode SNESSetIterationNumber(SNES snes, PetscInt iter)
1449: {
1450:   PetscFunctionBegin;
1452:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1453:   snes->iter = iter;
1454:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1455:   PetscFunctionReturn(PETSC_SUCCESS);
1456: }

1458: /*@
1459:   SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1460:   taken by the nonlinear solver in the current or most recent `SNESSolve()` .

1462:   Not Collective

1464:   Input Parameter:
1465: . snes - `SNES` context

1467:   Output Parameter:
1468: . nfails - number of unsuccessful steps attempted

1470:   Level: intermediate

1472:   Notes:
1473:   A failed step is a step that was generated and taken but did not satisfy the requested step criteria. For example,
1474:   the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).

1476:   Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1477:   will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.

1479:   `SNESSetMaxNonlinearStepFailures()` determines how many unsuccessful steps are allowed before the `SNESSolve()` terminates

1481:   This counter is reset to zero for each successive call to `SNESSolve()`.

1483: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1484:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1485: @*/
1486: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes, PetscInt *nfails)
1487: {
1488:   PetscFunctionBegin;
1490:   PetscAssertPointer(nfails, 2);
1491:   *nfails = snes->numFailures;
1492:   PetscFunctionReturn(PETSC_SUCCESS);
1493: }

1495: /*@
1496:   SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1497:   attempted by the nonlinear solver before it gives up and returns unconverged or generates an error

1499:   Not Collective

1501:   Input Parameters:
1502: + snes     - `SNES` context
1503: - maxFails - maximum of unsuccessful steps allowed, use `PETSC_UNLIMITED` to have no limit on the number of failures

1505:   Options Database Key:
1506: . -snes_max_fail n - maximum number of unsuccessful steps allowed

1508:   Level: intermediate

1510:   Note:
1511:   A failed step is a step that was generated and taken but did not satisfy the requested criteria. For example,
1512:   the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).

1514:   Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1515:   will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.

1517:   Developer Note:
1518:   The options database key is wrong for this function name

1520: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1521:           `SNESGetLinearSolveFailures()`, `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`, `SNESCheckLineSearchFailure()`
1522: @*/
1523: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1524: {
1525:   PetscFunctionBegin;

1528:   if (maxFails == PETSC_UNLIMITED) {
1529:     snes->maxFailures = PETSC_INT_MAX;
1530:   } else {
1531:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1532:     snes->maxFailures = maxFails;
1533:   }
1534:   PetscFunctionReturn(PETSC_SUCCESS);
1535: }

1537: /*@
1538:   SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1539:   attempted by the nonlinear solver before it gives up and returns unconverged or generates an error

1541:   Not Collective

1543:   Input Parameter:
1544: . snes - `SNES` context

1546:   Output Parameter:
1547: . maxFails - maximum of unsuccessful steps

1549:   Level: intermediate

1551: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1552:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1553: @*/
1554: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1555: {
1556:   PetscFunctionBegin;
1558:   PetscAssertPointer(maxFails, 2);
1559:   *maxFails = snes->maxFailures;
1560:   PetscFunctionReturn(PETSC_SUCCESS);
1561: }

1563: /*@
1564:   SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1565:   done by the `SNES` object in the current or most recent `SNESSolve()`

1567:   Not Collective

1569:   Input Parameter:
1570: . snes - `SNES` context

1572:   Output Parameter:
1573: . nfuncs - number of evaluations

1575:   Level: intermediate

1577:   Note:
1578:   Reset every time `SNESSolve()` is called unless `SNESSetCountersReset()` is used.

1580: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1581: @*/
1582: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1583: {
1584:   PetscFunctionBegin;
1586:   PetscAssertPointer(nfuncs, 2);
1587:   *nfuncs = snes->nfuncs;
1588:   PetscFunctionReturn(PETSC_SUCCESS);
1589: }

1591: /*@
1592:   SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1593:   linear solvers in the current or most recent `SNESSolve()`

1595:   Not Collective

1597:   Input Parameter:
1598: . snes - `SNES` context

1600:   Output Parameter:
1601: . nfails - number of failed solves

1603:   Options Database Key:
1604: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated

1606:   Level: intermediate

1608:   Note:
1609:   This counter is reset to zero for each successive call to `SNESSolve()`.

1611: .seealso: [](ch_snes), `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1612: @*/
1613: PetscErrorCode SNESGetLinearSolveFailures(SNES snes, PetscInt *nfails)
1614: {
1615:   PetscFunctionBegin;
1617:   PetscAssertPointer(nfails, 2);
1618:   *nfails = snes->numLinearSolveFailures;
1619:   PetscFunctionReturn(PETSC_SUCCESS);
1620: }

1622: /*@
1623:   SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1624:   allowed before `SNES` returns with a diverged reason of `SNES_DIVERGED_LINEAR_SOLVE`

1626:   Logically Collective

1628:   Input Parameters:
1629: + snes     - `SNES` context
1630: - maxFails - maximum allowed linear solve failures, use `PETSC_UNLIMITED` to have no limit on the number of failures

1632:   Options Database Key:
1633: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated

1635:   Level: intermediate

1637:   Note:
1638:   By default this is 0; that is `SNES` returns on the first failed linear solve

1640:   Developer Note:
1641:   The options database key is wrong for this function name

1643: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1644: @*/
1645: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1646: {
1647:   PetscFunctionBegin;

1651:   if (maxFails == PETSC_UNLIMITED) {
1652:     snes->maxLinearSolveFailures = PETSC_INT_MAX;
1653:   } else {
1654:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1655:     snes->maxLinearSolveFailures = maxFails;
1656:   }
1657:   PetscFunctionReturn(PETSC_SUCCESS);
1658: }

1660: /*@
1661:   SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1662:   are allowed before `SNES` returns as unsuccessful

1664:   Not Collective

1666:   Input Parameter:
1667: . snes - `SNES` context

1669:   Output Parameter:
1670: . maxFails - maximum of unsuccessful solves allowed

1672:   Level: intermediate

1674:   Note:
1675:   By default this is 1; that is `SNES` returns on the first failed linear solve

1677: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1678: @*/
1679: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1680: {
1681:   PetscFunctionBegin;
1683:   PetscAssertPointer(maxFails, 2);
1684:   *maxFails = snes->maxLinearSolveFailures;
1685:   PetscFunctionReturn(PETSC_SUCCESS);
1686: }

1688: /*@
1689:   SNESGetLinearSolveIterations - Gets the total number of linear iterations
1690:   used by the nonlinear solver in the most recent `SNESSolve()`

1692:   Not Collective

1694:   Input Parameter:
1695: . snes - `SNES` context

1697:   Output Parameter:
1698: . lits - number of linear iterations

1700:   Level: intermediate

1702:   Notes:
1703:   This counter is reset to zero for each successive call to `SNESSolve()` unless `SNESSetCountersReset()` is used.

1705:   If the linear solver fails inside the `SNESSolve()` the iterations for that call to the linear solver are not included. If you wish to count them
1706:   then call `KSPGetIterationNumber()` after the failed solve.

1708: .seealso: [](ch_snes), `SNES`, `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1709: @*/
1710: PetscErrorCode SNESGetLinearSolveIterations(SNES snes, PetscInt *lits)
1711: {
1712:   PetscFunctionBegin;
1714:   PetscAssertPointer(lits, 2);
1715:   *lits = snes->linear_its;
1716:   PetscFunctionReturn(PETSC_SUCCESS);
1717: }

1719: /*@
1720:   SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1721:   are reset every time `SNESSolve()` is called.

1723:   Logically Collective

1725:   Input Parameters:
1726: + snes  - `SNES` context
1727: - reset - whether to reset the counters or not, defaults to `PETSC_TRUE`

1729:   Level: developer

1731: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1732: @*/
1733: PetscErrorCode SNESSetCountersReset(SNES snes, PetscBool reset)
1734: {
1735:   PetscFunctionBegin;
1738:   snes->counters_reset = reset;
1739:   PetscFunctionReturn(PETSC_SUCCESS);
1740: }

1742: /*@
1743:   SNESResetCounters - Reset counters for linear iterations and function evaluations.

1745:   Logically Collective

1747:   Input Parameters:
1748: . snes - `SNES` context

1750:   Level: developer

1752:   Note:
1753:   It honors the flag set with `SNESSetCountersReset()`

1755: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1756: @*/
1757: PetscErrorCode SNESResetCounters(SNES snes)
1758: {
1759:   PetscFunctionBegin;
1761:   if (snes->counters_reset) {
1762:     snes->nfuncs      = 0;
1763:     snes->linear_its  = 0;
1764:     snes->numFailures = 0;
1765:   }
1766:   PetscFunctionReturn(PETSC_SUCCESS);
1767: }

1769: /*@
1770:   SNESSetKSP - Sets a `KSP` context for the `SNES` object to use

1772:   Not Collective, but the `SNES` and `KSP` objects must live on the same `MPI_Comm`

1774:   Input Parameters:
1775: + snes - the `SNES` context
1776: - ksp  - the `KSP` context

1778:   Level: developer

1780:   Notes:
1781:   The `SNES` object already has its `KSP` object, you can obtain with `SNESGetKSP()`
1782:   so this routine is rarely needed.

1784:   The `KSP` object that is already in the `SNES` object has its reference count
1785:   decreased by one when this is called.

1787: .seealso: [](ch_snes), `SNES`, `KSP`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`
1788: @*/
1789: PetscErrorCode SNESSetKSP(SNES snes, KSP ksp)
1790: {
1791:   PetscFunctionBegin;
1794:   PetscCheckSameComm(snes, 1, ksp, 2);
1795:   PetscCall(PetscObjectReference((PetscObject)ksp));
1796:   PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1797:   snes->ksp = ksp;
1798:   PetscFunctionReturn(PETSC_SUCCESS);
1799: }

1801: /*@
1802:   SNESParametersInitialize - Sets the base defaults for parameters in `snes`, updating a parameter's current value when it matches its previously recorded default.

1804:   Logically collective

1806:   Input Parameter:
1807: . snes - the `SNES` object

1809:   Level: developer

1811:   Notes:

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

1815:   Developer Notes:

1817:   `SNESCreate()` calls this routine to establish the base defaults. `SNESSetType()` calls it before constructing a new `SNESType`, so the recorded defaults associated with the previous type are replaced before the new type installs its own defaults.

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

1821: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
1822:           `PetscObjectParameterSetDefault()`
1823: @*/
1824: PetscErrorCode SNESParametersInitialize(SNES snes)
1825: {
1826:   PetscObjectParameterSetDefault(snes, max_its, 50);
1827:   PetscObjectParameterSetDefault(snes, max_funcs, 10000);
1828:   PetscObjectParameterSetDefault(snes, rtol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1829:   PetscObjectParameterSetDefault(snes, abstol, PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50);
1830:   PetscObjectParameterSetDefault(snes, stol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1831:   PetscObjectParameterSetDefault(snes, divtol, 1.e4);
1832:   return PETSC_SUCCESS;
1833: }

1835: /*@
1836:   SNESCreate - Creates a nonlinear solver context used to manage a set of nonlinear solves

1838:   Collective

1840:   Input Parameter:
1841: . comm - MPI communicator

1843:   Output Parameter:
1844: . outsnes - the new `SNES` context

1846:   Options Database Keys:
1847: + -snes_mf          - Activates default matrix-free Jacobian-vector products, with no preconditioner by default
1848: . -snes_mf_operator - Activates default matrix-free Jacobian-vector products, and a user-provided matrix as set by `SNESSetJacobian()`
1849: . -snes_fd_coloring - uses a relative fast computation of the Jacobian using finite differences and a graph coloring
1850: - -snes_fd          - Uses (slow!) finite differences to compute Jacobian

1852:   Level: beginner

1854:   Developer Notes:
1855:   `SNES` always creates a `KSP` object even though many `SNES` methods do not use it. This is
1856:   unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1857:   particular method does use `KSP` and regulates if the information about the `KSP` is printed
1858:   in `SNESView()`.

1860:   `TSSetFromOptions()` does call `SNESSetFromOptions()` which can lead to users being confused
1861:   by help messages about meaningless `SNES` options.

1863:   `SNES` always creates the `snes->kspconvctx` even though it is used by only one type. This should be fixed.

1865: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1866: @*/
1867: PetscErrorCode SNESCreate(MPI_Comm comm, SNES *outsnes)
1868: {
1869:   SNES       snes;
1870:   SNESKSPEW *kctx;

1872:   PetscFunctionBegin;
1873:   PetscAssertPointer(outsnes, 2);
1874:   PetscCall(SNESInitializePackage());

1876:   PetscCall(PetscHeaderCreate(snes, SNES_CLASSID, "SNES", "Nonlinear solver", "SNES", comm, SNESDestroy, SNESView));
1877:   snes->ops->converged = SNESConvergedDefault;
1878:   snes->usesksp        = PETSC_TRUE;
1879:   snes->norm           = 0.0;
1880:   snes->xnorm          = 0.0;
1881:   snes->ynorm          = 0.0;
1882:   snes->normschedule   = SNES_NORM_ALWAYS;
1883:   snes->functype       = SNES_FUNCTION_DEFAULT;
1884:   snes->ttol           = 0.0;

1886:   snes->rnorm0               = 0;
1887:   snes->nfuncs               = 0;
1888:   snes->numFailures          = 0;
1889:   snes->maxFailures          = 1;
1890:   snes->linear_its           = 0;
1891:   snes->lagjacobian          = 1;
1892:   snes->jac_iter             = 0;
1893:   snes->lagjac_persist       = PETSC_FALSE;
1894:   snes->lagpreconditioner    = 1;
1895:   snes->pre_iter             = 0;
1896:   snes->lagpre_persist       = PETSC_FALSE;
1897:   snes->numbermonitors       = 0;
1898:   snes->numberreasonviews    = 0;
1899:   snes->data                 = NULL;
1900:   snes->setupcalled          = PETSC_FALSE;
1901:   snes->ksp_ewconv           = PETSC_FALSE;
1902:   snes->nwork                = 0;
1903:   snes->work                 = NULL;
1904:   snes->nvwork               = 0;
1905:   snes->vwork                = NULL;
1906:   snes->conv_hist_len        = 0;
1907:   snes->conv_hist_max        = 0;
1908:   snes->conv_hist            = NULL;
1909:   snes->conv_hist_its        = NULL;
1910:   snes->conv_hist_reset      = PETSC_TRUE;
1911:   snes->counters_reset       = PETSC_TRUE;
1912:   snes->vec_func_init_set    = PETSC_FALSE;
1913:   snes->reason               = SNES_CONVERGED_ITERATING;
1914:   snes->npcside              = PC_RIGHT;
1915:   snes->setfromoptionscalled = 0;

1917:   snes->mf          = PETSC_FALSE;
1918:   snes->mf_operator = PETSC_FALSE;
1919:   snes->mf_version  = 1;

1921:   snes->numLinearSolveFailures = 0;
1922:   snes->maxLinearSolveFailures = 1;

1924:   snes->vizerotolerance     = 1.e-8;
1925:   snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;

1927:   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1928:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

1930:   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1931:   PetscCall(PetscNew(&kctx));

1933:   snes->kspconvctx  = kctx;
1934:   kctx->version     = 2;
1935:   kctx->rtol_0      = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1936:                              this was too large for some test cases */
1937:   kctx->rtol_last   = 0.0;
1938:   kctx->rtol_max    = 0.9;
1939:   kctx->gamma       = 1.0;
1940:   kctx->alpha       = 0.5 * (1.0 + PetscSqrtReal(5.0));
1941:   kctx->alpha2      = kctx->alpha;
1942:   kctx->threshold   = 0.1;
1943:   kctx->lresid_last = 0.0;
1944:   kctx->norm_last   = 0.0;

1946:   kctx->rk_last     = 0.0;
1947:   kctx->rk_last_2   = 0.0;
1948:   kctx->rtol_last_2 = 0.0;
1949:   kctx->v4_p1       = 0.1;
1950:   kctx->v4_p2       = 0.4;
1951:   kctx->v4_p3       = 0.7;
1952:   kctx->v4_m1       = 0.8;
1953:   kctx->v4_m2       = 0.5;
1954:   kctx->v4_m3       = 0.1;
1955:   kctx->v4_m4       = 0.5;

1957:   PetscCall(SNESParametersInitialize(snes));
1958:   *outsnes = snes;
1959:   PetscFunctionReturn(PETSC_SUCCESS);
1960: }

1962: /*@
1963:   SNESSetFunction - Sets the function evaluation routine and function
1964:   vector for use by the `SNES` routines in solving systems of nonlinear
1965:   equations.

1967:   Logically Collective

1969:   Input Parameters:
1970: + snes - the `SNES` context
1971: . r    - vector to store function values, may be `NULL`
1972: . f    - function evaluation routine;  for calling sequence see `SNESFunctionFn`
1973: - ctx  - [optional] user-defined context for private data for the
1974:          function evaluation routine (may be `NULL`)

1976:   Level: beginner

1978: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunctionFn`
1979: @*/
1980: PetscErrorCode SNESSetFunction(SNES snes, Vec r, SNESFunctionFn *f, PetscCtx ctx)
1981: {
1982:   DM dm;

1984:   PetscFunctionBegin;
1986:   if (r) {
1988:     PetscCheckSameComm(snes, 1, r, 2);
1989:     PetscCall(PetscObjectReference((PetscObject)r));
1990:     PetscCall(VecDestroy(&snes->vec_func));
1991:     snes->vec_func = r;
1992:   }
1993:   /* update DMSNES
1994:      We support incremental information; so update the function context only if r is not specified
1995:      (which allows to disable the callbacks when both f and ctx are NULL),
1996:      or, if r is specified, when at least one of f and ctx is not NULL */
1997:   PetscCall(SNESGetDM(snes, &dm));
1998:   if (!r || f || ctx) PetscCall(DMSNESSetFunction(dm, f, ctx));
1999:   if (f == SNESPicardComputeFunction) PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2000:   PetscFunctionReturn(PETSC_SUCCESS);
2001: }

2003: /*@
2004:   SNESSetInitialFunction - Set an already computed function evaluation at the initial guess to be reused by `SNESSolve()`.

2006:   Logically Collective

2008:   Input Parameters:
2009: + snes - the `SNES` context
2010: - f    - vector to store function value

2012:   Level: developer

2014:   Notes:
2015:   This should not be modified during the solution procedure.

2017:   This is used extensively in the `SNESFAS` hierarchy and in nonlinear preconditioning.

2019: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
2020: @*/
2021: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
2022: {
2023:   Vec vec_func;

2025:   PetscFunctionBegin;
2028:   PetscCheckSameComm(snes, 1, f, 2);
2029:   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2030:     snes->vec_func_init_set = PETSC_FALSE;
2031:     PetscFunctionReturn(PETSC_SUCCESS);
2032:   }
2033:   PetscCall(SNESGetFunction(snes, &vec_func, NULL, NULL));
2034:   PetscCall(VecCopy(f, vec_func));

2036:   snes->vec_func_init_set = PETSC_TRUE;
2037:   PetscFunctionReturn(PETSC_SUCCESS);
2038: }

2040: /*@
2041:   SNESSetNormSchedule - Sets the `SNESNormSchedule` used in convergence and monitoring
2042:   of the `SNES` method, when norms are computed in the solving process

2044:   Logically Collective

2046:   Input Parameters:
2047: + snes         - the `SNES` context
2048: - normschedule - the frequency of norm computation

2050:   Options Database Key:
2051: . -snes_norm_schedule (none|always|initialonly|finalonly|initialfinalonly) - set the schedule

2053:   Level: advanced

2055:   Notes:
2056:   Only certain `SNES` methods support certain `SNESNormSchedules`.  Most require evaluation
2057:   of the nonlinear function and the taking of its norm at every iteration to
2058:   even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2059:   `SNESNGS` and the like do not require the norm of the function to be computed, and therefore
2060:   may either be monitored for convergence or not.  As these are often used as nonlinear
2061:   preconditioners, monitoring the norm of their error is not a useful enterprise within
2062:   their solution.

2064: .seealso: [](ch_snes), `SNESNormSchedule`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`
2065: @*/
2066: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
2067: {
2068:   PetscFunctionBegin;
2071:   snes->normschedule = normschedule;
2072:   PetscFunctionReturn(PETSC_SUCCESS);
2073: }

2075: /*@
2076:   SNESGetNormSchedule - Gets the `SNESNormSchedule` used in convergence and monitoring
2077:   of the `SNES` method.

2079:   Logically Collective

2081:   Input Parameters:
2082: + snes         - the `SNES` context
2083: - normschedule - the type of the norm used

2085:   Level: advanced

2087: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2088: @*/
2089: PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
2090: {
2091:   PetscFunctionBegin;
2093:   *normschedule = snes->normschedule;
2094:   PetscFunctionReturn(PETSC_SUCCESS);
2095: }

2097: /*@
2098:   SNESSetFunctionNorm - Sets the last computed residual norm.

2100:   Logically Collective

2102:   Input Parameters:
2103: + snes - the `SNES` context
2104: - norm - the value of the norm

2106:   Level: developer

2108: .seealso: [](ch_snes), `SNES`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2109: @*/
2110: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2111: {
2112:   PetscFunctionBegin;
2114:   snes->norm = norm;
2115:   PetscFunctionReturn(PETSC_SUCCESS);
2116: }

2118: /*@
2119:   SNESGetFunctionNorm - Gets the last computed norm of the residual

2121:   Not Collective

2123:   Input Parameter:
2124: . snes - the `SNES` context

2126:   Output Parameter:
2127: . norm - the last computed residual norm

2129:   Level: developer

2131: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2132: @*/
2133: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2134: {
2135:   PetscFunctionBegin;
2137:   PetscAssertPointer(norm, 2);
2138:   *norm = snes->norm;
2139:   PetscFunctionReturn(PETSC_SUCCESS);
2140: }

2142: /*@
2143:   SNESGetUpdateNorm - Gets the last computed norm of the solution update

2145:   Not Collective

2147:   Input Parameter:
2148: . snes - the `SNES` context

2150:   Output Parameter:
2151: . ynorm - the last computed update norm

2153:   Level: developer

2155:   Note:
2156:   The new solution is the current solution plus the update, so this norm is an indication of the size of the update

2158: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2159: @*/
2160: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2161: {
2162:   PetscFunctionBegin;
2164:   PetscAssertPointer(ynorm, 2);
2165:   *ynorm = snes->ynorm;
2166:   PetscFunctionReturn(PETSC_SUCCESS);
2167: }

2169: /*@
2170:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2172:   Not Collective

2174:   Input Parameter:
2175: . snes - the `SNES` context

2177:   Output Parameter:
2178: . xnorm - the last computed solution norm

2180:   Level: developer

2182: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2183: @*/
2184: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2185: {
2186:   PetscFunctionBegin;
2188:   PetscAssertPointer(xnorm, 2);
2189:   *xnorm = snes->xnorm;
2190:   PetscFunctionReturn(PETSC_SUCCESS);
2191: }

2193: /*@
2194:   SNESSetFunctionType - Sets the `SNESFunctionType`
2195:   of the `SNES` method.

2197:   Logically Collective

2199:   Input Parameters:
2200: + snes - the `SNES` context
2201: - type - the function type

2203:   Level: developer

2205:   Values of the function type\:
2206: +  `SNES_FUNCTION_DEFAULT`          - the default for the given `SNESType`
2207: .  `SNES_FUNCTION_UNPRECONDITIONED` - an unpreconditioned function evaluation (this is the function provided with `SNESSetFunction()`
2208: -  `SNES_FUNCTION_PRECONDITIONED`   - a transformation of the function provided with `SNESSetFunction()`

2210:   Note:
2211:   Different `SNESType`s use this value in different ways

2213: .seealso: [](ch_snes), `SNES`, `SNESFunctionType`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2214: @*/
2215: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2216: {
2217:   PetscFunctionBegin;
2219:   snes->functype = type;
2220:   PetscFunctionReturn(PETSC_SUCCESS);
2221: }

2223: /*@
2224:   SNESGetFunctionType - Gets the `SNESFunctionType` used in convergence and monitoring set with `SNESSetFunctionType()`
2225:   of the SNES method.

2227:   Logically Collective

2229:   Input Parameters:
2230: + snes - the `SNES` context
2231: - type - the type of the function evaluation, see `SNESSetFunctionType()`

2233:   Level: advanced

2235: .seealso: [](ch_snes), `SNESSetFunctionType()`, `SNESFunctionType`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2236: @*/
2237: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2238: {
2239:   PetscFunctionBegin;
2241:   *type = snes->functype;
2242:   PetscFunctionReturn(PETSC_SUCCESS);
2243: }

2245: /*@
2246:   SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2247:   use with composed nonlinear solvers.

2249:   Input Parameters:
2250: + snes - the `SNES` context, usually of the `SNESType` `SNESNGS`
2251: . f    - function evaluation routine to apply Gauss-Seidel, see `SNESNGSFn` for calling sequence
2252: - ctx  - [optional] user-defined context for private data for the smoother evaluation routine (may be `NULL`)

2254:   Level: intermediate

2256:   Note:
2257:   The `SNESNGS` routines are used by the composed nonlinear solver to generate
2258:   a problem appropriate update to the solution, particularly `SNESFAS`.

2260: .seealso: [](ch_snes), `SNESNGS`, `SNESGetNGS()`, `SNESNCG`, `SNESGetFunction()`, `SNESComputeNGS()`, `SNESNGSFn`
2261: @*/
2262: PetscErrorCode SNESSetNGS(SNES snes, SNESNGSFn *f, PetscCtx ctx)
2263: {
2264:   DM dm;

2266:   PetscFunctionBegin;
2268:   PetscCall(SNESGetDM(snes, &dm));
2269:   PetscCall(DMSNESSetNGS(dm, f, ctx));
2270:   PetscFunctionReturn(PETSC_SUCCESS);
2271: }

2273: /*@
2274:   SNESPicardComputeMFFunction - Matrix-free residual $A(x) x - b(x)$ used by `SNESSetPicard()` when the operator is applied through `-snes_mf_operator`

2276:   Collective

2278:   Input Parameters:
2279: + snes - the `SNES` context
2280: . x    - the current iterate
2281: - ctx  - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`

2283:   Output Parameter:
2284: . f - the residual vector

2286:   Level: developer

2288:   Note:
2289:   Uses a duplicate of `snes->jacobian_pre` because `snes->jacobian_pre` cannot be changed during the `KSPSolve()`.

2291: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeJacobian()`
2292: @*/
2293: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2294: {
2295:   DM     dm;
2296:   DMSNES sdm;

2298:   PetscFunctionBegin;
2299:   PetscCall(SNESGetDM(snes, &dm));
2300:   PetscCall(DMGetDMSNES(dm, &sdm));
2301:   /*  A(x)*x - b(x) */
2302:   if (sdm->ops->computepfunction) {
2303:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2304:     PetscCall(VecScale(f, -1.0));
2305:     /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2306:     if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2307:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2308:     PetscCall(MatMultAdd(snes->picard, x, f, f));
2309:   } else {
2310:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2311:     PetscCall(MatMult(snes->picard, x, f));
2312:   }
2313:   PetscFunctionReturn(PETSC_SUCCESS);
2314: }

2316: /*@
2317:   SNESPicardComputeFunction - Compute the residual $A(x) x - b(x)$ using the callbacks registered by `SNESSetPicard()`

2319:   Collective

2321:   Input Parameters:
2322: + snes - the `SNES` context
2323: . x    - the current iterate
2324: - ctx  - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`

2326:   Output Parameter:
2327: . f - the residual vector

2329:   Level: developer

2331: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeMFFunction()`, `SNESPicardComputeJacobian()`
2332: @*/
2333: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2334: {
2335:   DM     dm;
2336:   DMSNES sdm;

2338:   PetscFunctionBegin;
2339:   PetscCall(SNESGetDM(snes, &dm));
2340:   PetscCall(DMGetDMSNES(dm, &sdm));
2341:   /*  A(x)*x - b(x) */
2342:   if (sdm->ops->computepfunction) {
2343:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2344:     PetscCall(VecScale(f, -1.0));
2345:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2346:     PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2347:   } else {
2348:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2349:     PetscCall(MatMult(snes->jacobian_pre, x, f));
2350:   }
2351:   PetscFunctionReturn(PETSC_SUCCESS);
2352: }

2354: /*@
2355:   SNESPicardComputeJacobian - Trivial Jacobian assembly callback used by `SNESSetPicard()`; the Picard operator is filled in by `SNESPicardComputeFunction()`

2357:   Collective

2359:   Input Parameters:
2360: + snes - the `SNES` context
2361: . x1   - the current iterate (unused)
2362: . J    - the Jacobian matrix to assemble
2363: . B    - the preconditioning matrix (unused)
2364: - ctx  - unused application context

2366:   Level: developer

2368:   Note:
2369:   Only calls `MatAssemblyBegin()`/`MatAssemblyEnd()` on `J`, because the Picard iteration reuses the operator already assembled by `SNESPicardComputeFunction()`.

2371: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeMFFunction()`
2372: @*/
2373: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2374: {
2375:   PetscFunctionBegin;
2376:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2377:   /* must assembly if matrix-free to get the last SNES solution */
2378:   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2379:   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2380:   PetscFunctionReturn(PETSC_SUCCESS);
2381: }

2383: /*@
2384:   SNESSetPicard - Use `SNES` to solve the system $A(x) x = bp(x) + b $ via a Picard type iteration (Picard linearization)

2386:   Logically Collective

2388:   Input Parameters:
2389: + snes - the `SNES` context
2390: . r    - vector to store function values, may be `NULL`
2391: . bp   - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2392: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2393: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2394: . J    - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2395: - ctx  - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)

2397:   Level: intermediate

2399:   Notes:
2400:   It is often better to provide the nonlinear function $F()$ and some approximation to its Jacobian directly and use
2401:   an approximate Newton solver. This interface is provided to allow porting/testing a previous Picard based code in PETSc before converting it to approximate Newton.

2403:   One can call `SNESSetPicard()` or `SNESSetFunction()` (and possibly `SNESSetJacobian()`) but cannot call both

2405:   Solves the equation $A(x) x = bp(x) + b$ via the defect correction algorithm $A(x^{n}) (x^{n+1} - x^{n}) = bp(x^{n}) + b - A(x^{n})x^{n}$.
2406:   When an exact solver is used this corresponds to the "classic" Picard $A(x^{n}) x^{n+1} = bp(x^{n}) + b$ iteration.

2408:   Run with `-snes_mf_operator` to solve the system with Newton's method using $A(x^{n})$ to construct the preconditioner.

2410:   We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2411:   the direct Picard iteration $A(x^n) x^{n+1} = bp(x^n) + b$

2413:   There is some controversity over the definition of a Picard iteration for nonlinear systems but almost everyone agrees that it involves a linear solve and some
2414:   believe it is the iteration  $A(x^{n}) x^{n+1} = b(x^{n})$ hence we use the name Picard. If anyone has an authoritative  reference that defines the Picard iteration
2415:   different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument \:-).

2417:   When used with `-snes_mf_operator` this will run matrix-free Newton's method where the matrix-vector product is of the true Jacobian of $A(x)x - bp(x) - b$ and
2418:   $A(x^{n})$ is used to build the preconditioner

2420:   When used with `-snes_fd` this will compute the true Jacobian (very slowly one column at a time) and thus represent Newton's method.

2422:   When used with `-snes_fd_coloring` this will compute the Jacobian via coloring and thus represent a faster implementation of Newton's method. But the
2423:   the nonzero structure of the Jacobian is, in general larger than that of the Picard matrix $A$ so you must provide in $A$ the needed nonzero structure for the correct
2424:   coloring. When using `DMDA` this may mean creating the matrix $A$ with `DMCreateMatrix()` using a wider stencil than strictly needed for $A$ or with a `DMDA_STENCIL_BOX`.
2425:   See the comment in src/snes/tutorials/ex15.c.

2427: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2428:           `SNESFunctionFn`, `SNESJacobianFn`
2429: @*/
2430: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2431: {
2432:   DM dm;

2434:   PetscFunctionBegin;
2436:   PetscCall(SNESGetDM(snes, &dm));
2437:   PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2438:   PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2439:   PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2440:   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2441:   PetscFunctionReturn(PETSC_SUCCESS);
2442: }

2444: /*@
2445:   SNESGetPicard - Returns the context for the Picard iteration

2447:   Not Collective, but `Vec` is parallel if `SNES` is parallel. Collective if `Vec` is requested, but has not been created yet.

2449:   Input Parameter:
2450: . snes - the `SNES` context

2452:   Output Parameters:
2453: + r    - the function (or `NULL`)
2454: . f    - the function (or `NULL`);  for calling sequence see `SNESFunctionFn`
2455: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2456: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2457: . J    - the function for matrix evaluation (or `NULL`);  for calling sequence see `SNESJacobianFn`
2458: - ctx  - the function context (or `NULL`)

2460:   Level: advanced

2462: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2463: @*/
2464: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2465: {
2466:   DM dm;

2468:   PetscFunctionBegin;
2470:   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2471:   PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2472:   PetscCall(SNESGetDM(snes, &dm));
2473:   PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2474:   PetscFunctionReturn(PETSC_SUCCESS);
2475: }

2477: /*@
2478:   SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the nonlinear problem

2480:   Logically Collective

2482:   Input Parameters:
2483: + snes - the `SNES` context
2484: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2485: - ctx  - [optional] user-defined context for private data for the
2486:          function evaluation routine (may be `NULL`)

2488:   Level: intermediate

2490: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2491: @*/
2492: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2493: {
2494:   PetscFunctionBegin;
2496:   if (func) snes->ops->computeinitialguess = func;
2497:   if (ctx) snes->initialguessP = ctx;
2498:   PetscFunctionReturn(PETSC_SUCCESS);
2499: }

2501: /*@
2502:   SNESGetRhs - Gets the vector for solving F(x) = `rhs`. If `rhs` is not set
2503:   it assumes a zero right-hand side.

2505:   Logically Collective

2507:   Input Parameter:
2508: . snes - the `SNES` context

2510:   Output Parameter:
2511: . rhs - the right-hand side vector or `NULL` if there is no right-hand side vector

2513:   Level: intermediate

2515: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2516: @*/
2517: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2518: {
2519:   PetscFunctionBegin;
2521:   PetscAssertPointer(rhs, 2);
2522:   *rhs = snes->vec_rhs;
2523:   PetscFunctionReturn(PETSC_SUCCESS);
2524: }

2526: /*@
2527:   SNESComputeFunction - Calls the function that has been set with `SNESSetFunction()`.

2529:   Collective

2531:   Input Parameters:
2532: + snes - the `SNES` context
2533: - x    - input vector

2535:   Output Parameter:
2536: . f - function vector, as set by `SNESSetFunction()`

2538:   Level: developer

2540:   Notes:
2541:   `SNESComputeFunction()` is typically used within nonlinear solvers
2542:   implementations, so users would not generally call this routine themselves.

2544:   When solving for $F(x) = b$, this routine computes $f = F(x) - b$.

2546:   This function usually appears in the pattern.
2547: .vb
2548:   SNESComputeFunction(snes, x, f);
2549:   VecNorm(f, &fnorm);
2550:   SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2551: .ve
2552:   to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.

2554: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2555: @*/
2556: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2557: {
2558:   DM     dm;
2559:   DMSNES sdm;

2561:   PetscFunctionBegin;
2565:   PetscCheckSameComm(snes, 1, x, 2);
2566:   PetscCheckSameComm(snes, 1, f, 3);
2567:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

2569:   PetscCall(SNESGetDM(snes, &dm));
2570:   PetscCall(DMGetDMSNES(dm, &sdm));
2571:   PetscCheck(sdm->ops->computefunction || snes->vec_rhs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2572:   if (sdm->ops->computefunction) {
2573:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2574:     PetscCall(VecLockReadPush(x));
2575:     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2576:     snes->functiondomainerror = PETSC_FALSE;
2577:     {
2578:       void           *ctx;
2579:       SNESFunctionFn *computefunction;
2580:       PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2581:       PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2582:     }
2583:     PetscCall(VecLockReadPop(x));
2584:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2585:   } else /* if (snes->vec_rhs) */ {
2586:     PetscCall(MatMult(snes->jacobian, x, f));
2587:   }
2588:   if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2589:   snes->nfuncs++;
2590:   /*
2591:      domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2592:      propagate the value to all processes
2593:   */
2594:   PetscCall(VecFlag(f, snes->functiondomainerror));
2595:   PetscFunctionReturn(PETSC_SUCCESS);
2596: }

2598: /*@
2599:   SNESComputeMFFunction - Calls the function that has been set with `DMSNESSetMFFunction()`.

2601:   Collective

2603:   Input Parameters:
2604: + snes - the `SNES` context
2605: - x    - input vector

2607:   Output Parameter:
2608: . y - output vector

2610:   Level: developer

2612:   Notes:
2613:   `SNESComputeMFFunction()` is used within the matrix-vector products called by the matrix created with `MatCreateSNESMF()`
2614:   so users would not generally call this routine themselves.

2616:   Since this function is intended for use with finite differencing it does not subtract the right-hand side vector provided with `SNESSolve()`
2617:   while `SNESComputeFunction()` does. As such, this routine cannot be used with  `MatMFFDSetBase()` with a provided F function value even if it applies the
2618:   same function as `SNESComputeFunction()` if a `SNESSolve()` right-hand side vector is use because the two functions difference would include this right hand side function.

2620: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2621: @*/
2622: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2623: {
2624:   DM     dm;
2625:   DMSNES sdm;

2627:   PetscFunctionBegin;
2631:   PetscCheckSameComm(snes, 1, x, 2);
2632:   PetscCheckSameComm(snes, 1, y, 3);
2633:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

2635:   PetscCall(SNESGetDM(snes, &dm));
2636:   PetscCall(DMGetDMSNES(dm, &sdm));
2637:   PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, y, 0));
2638:   PetscCall(VecLockReadPush(x));
2639:   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2640:   snes->functiondomainerror = PETSC_FALSE;
2641:   PetscCallBack("SNES callback function", (*sdm->ops->computemffunction)(snes, x, y, sdm->mffunctionctx));
2642:   PetscCall(VecLockReadPop(x));
2643:   PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, y, 0));
2644:   snes->nfuncs++;
2645:   /*
2646:      domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2647:      propagate the value to all processes
2648:   */
2649:   PetscCall(VecFlag(y, snes->functiondomainerror));
2650:   PetscFunctionReturn(PETSC_SUCCESS);
2651: }

2653: /*@
2654:   SNESComputeNGS - Calls the Gauss-Seidel function that has been set with `SNESSetNGS()`.

2656:   Collective

2658:   Input Parameters:
2659: + snes - the `SNES` context
2660: . x    - input vector
2661: - b    - rhs vector

2663:   Output Parameter:
2664: . x - new solution vector

2666:   Level: developer

2668:   Note:
2669:   `SNESComputeNGS()` is typically used within composed nonlinear solver
2670:   implementations, so most users would not generally call this routine
2671:   themselves.

2673: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2674: @*/
2675: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2676: {
2677:   DM     dm;
2678:   DMSNES sdm;

2680:   PetscFunctionBegin;
2684:   PetscCheckSameComm(snes, 1, x, 3);
2685:   if (b) PetscCheckSameComm(snes, 1, b, 2);
2686:   if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2687:   PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2688:   PetscCall(SNESGetDM(snes, &dm));
2689:   PetscCall(DMGetDMSNES(dm, &sdm));
2690:   PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2691:   if (b) PetscCall(VecLockReadPush(b));
2692:   PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2693:   if (b) PetscCall(VecLockReadPop(b));
2694:   PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2695:   PetscFunctionReturn(PETSC_SUCCESS);
2696: }

2698: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2699: {
2700:   Vec          X;
2701:   PetscScalar *g;
2702:   PetscReal    f, f2;
2703:   PetscInt     low, high, N, i;
2704:   PetscBool    flg;
2705:   PetscReal    h = .5 * PETSC_SQRT_MACHINE_EPSILON;

2707:   PetscFunctionBegin;
2708:   PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2709:   PetscCall(VecDuplicate(Xin, &X));
2710:   PetscCall(VecCopy(Xin, X));
2711:   PetscCall(VecGetSize(X, &N));
2712:   PetscCall(VecGetOwnershipRange(X, &low, &high));
2713:   PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2714:   PetscCall(VecGetArray(G, &g));
2715:   for (i = 0; i < N; i++) {
2716:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2717:     PetscCall(VecAssemblyBegin(X));
2718:     PetscCall(VecAssemblyEnd(X));
2719:     PetscCall(SNESComputeObjective(snes, X, &f));
2720:     PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2721:     PetscCall(VecAssemblyBegin(X));
2722:     PetscCall(VecAssemblyEnd(X));
2723:     PetscCall(SNESComputeObjective(snes, X, &f2));
2724:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2725:     PetscCall(VecAssemblyBegin(X));
2726:     PetscCall(VecAssemblyEnd(X));
2727:     if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2728:   }
2729:   PetscCall(VecRestoreArray(G, &g));
2730:   PetscCall(VecDestroy(&X));
2731:   PetscFunctionReturn(PETSC_SUCCESS);
2732: }

2734: /*@
2735:   SNESTestFunction - Computes the difference between the computed and finite-difference functions

2737:   Collective

2739:   Input Parameter:
2740: . snes - the `SNES` context

2742:   Options Database Keys:
2743: + -snes_test_function      - compare the user provided function with one compute via finite differences to check for errors.
2744: - -snes_test_function_view - display the user provided function, the finite difference function and the difference

2746:   Level: developer

2748: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2749: @*/
2750: PetscErrorCode SNESTestFunction(SNES snes)
2751: {
2752:   Vec               x, g1, g2, g3;
2753:   PetscBool         complete_print = PETSC_FALSE;
2754:   PetscReal         hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2755:   PetscScalar       dot;
2756:   MPI_Comm          comm;
2757:   PetscViewer       viewer, mviewer;
2758:   PetscViewerFormat format;
2759:   PetscInt          tabs;
2760:   static PetscBool  directionsprinted = PETSC_FALSE;
2761:   SNESObjectiveFn  *objective;

2763:   PetscFunctionBegin;
2764:   PetscCall(SNESGetObjective(snes, &objective, NULL));
2765:   if (!objective) PetscFunctionReturn(PETSC_SUCCESS);

2767:   PetscObjectOptionsBegin((PetscObject)snes);
2768:   PetscCall(PetscOptionsViewer("-snes_test_function_view", "View difference between hand-coded and finite difference function element entries", "None", &mviewer, &format, &complete_print));
2769:   PetscOptionsEnd();

2771:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2772:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2773:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2774:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2775:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Function -------------\n"));
2776:   if (!complete_print && !directionsprinted) {
2777:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2778:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference function entries greater than <threshold>.\n"));
2779:   }
2780:   if (!directionsprinted) {
2781:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2782:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Function is probably correct.\n"));
2783:     directionsprinted = PETSC_TRUE;
2784:   }
2785:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2787:   PetscCall(SNESGetSolution(snes, &x));
2788:   PetscCall(VecDuplicate(x, &g1));
2789:   PetscCall(VecDuplicate(x, &g2));
2790:   PetscCall(VecDuplicate(x, &g3));
2791:   PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() correctly */
2792:   PetscCall(SNESComputeFunction_FD(snes, x, g2));

2794:   PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2795:   PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2796:   PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2797:   PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2798:   PetscCall(VecDot(g1, g2, &dot));
2799:   PetscCall(VecCopy(g1, g3));
2800:   PetscCall(VecAXPY(g3, -1.0, g2));
2801:   PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2802:   PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2803:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2804:   PetscCall(PetscViewerASCIIPrintf(viewer, "  2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2805:   PetscCall(PetscViewerASCIIPrintf(viewer, "  max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));

2807:   if (complete_print) {
2808:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded function ----------\n"));
2809:     PetscCall(VecView(g1, mviewer));
2810:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference function ----------\n"));
2811:     PetscCall(VecView(g2, mviewer));
2812:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded minus finite-difference function ----------\n"));
2813:     PetscCall(VecView(g3, mviewer));
2814:   }
2815:   PetscCall(VecDestroy(&g1));
2816:   PetscCall(VecDestroy(&g2));
2817:   PetscCall(VecDestroy(&g3));

2819:   if (complete_print) {
2820:     PetscCall(PetscViewerPopFormat(mviewer));
2821:     PetscCall(PetscViewerDestroy(&mviewer));
2822:   }
2823:   PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2824:   PetscFunctionReturn(PETSC_SUCCESS);
2825: }

2827: /*@
2828:   SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians

2830:   Collective

2832:   Input Parameter:
2833: . snes - the `SNES` context

2835:   Output Parameters:
2836: + Jnorm    - the Frobenius norm of the computed Jacobian, or `NULL`
2837: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`

2839:   Options Database Keys:
2840: + -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors.  If a threshold is given, display only those entries whose difference is greater than the threshold.
2841: - -snes_test_jacobian_view        - display the user provided Jacobian, the finite difference Jacobian and the difference

2843:   Level: developer

2845:   Note:
2846:   Directions and norms are printed to stdout if `diffNorm` is `NULL`.

2848: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2849: @*/
2850: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2851: {
2852:   Mat               A, B, C, D, jacobian;
2853:   Vec               x = snes->vec_sol, f;
2854:   PetscReal         nrm, gnorm;
2855:   PetscReal         threshold = 1.e-5;
2856:   void             *functx;
2857:   PetscBool         complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2858:   PetscBool         silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2859:   PetscViewer       viewer, mviewer;
2860:   MPI_Comm          comm;
2861:   PetscInt          tabs;
2862:   static PetscBool  directionsprinted = PETSC_FALSE;
2863:   PetscViewerFormat format;

2865:   PetscFunctionBegin;
2866:   PetscObjectOptionsBegin((PetscObject)snes);
2867:   PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2868:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2869:   PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2870:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2871:   PetscCall(PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print));
2872:   PetscOptionsEnd();

2874:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2875:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2876:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2877:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2878:   if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Jacobian -------------\n"));
2879:   if (!complete_print && !silent && !directionsprinted) {
2880:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2881:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2882:   }
2883:   if (!directionsprinted && !silent) {
2884:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2885:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2886:     directionsprinted = PETSC_TRUE;
2887:   }
2888:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2890:   PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2891:   if (!flg) jacobian = snes->jacobian;
2892:   else jacobian = snes->jacobian_pre;

2894:   if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2895:   else PetscCall(PetscObjectReference((PetscObject)x));
2896:   PetscCall(VecDuplicate(x, &f));

2898:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2899:   PetscCall(SNESComputeFunction(snes, x, f));
2900:   PetscCall(VecDestroy(&f));
2901:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2902:   while (jacobian) {
2903:     Mat JT = NULL, Jsave = NULL;

2905:     if (istranspose) {
2906:       PetscCall(MatCreateTranspose(jacobian, &JT));
2907:       Jsave    = jacobian;
2908:       jacobian = JT;
2909:     }
2910:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2911:     if (flg) {
2912:       A = jacobian;
2913:       PetscCall(PetscObjectReference((PetscObject)A));
2914:     } else {
2915:       PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2916:     }

2918:     PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2919:     PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

2921:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2922:     PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));

2924:     PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2925:     PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2926:     PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2927:     PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2928:     PetscCall(MatDestroy(&D));
2929:     if (!gnorm) gnorm = 1; /* just in case */
2930:     if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2931:     if (complete_print) {
2932:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded Jacobian ----------\n"));
2933:       PetscCall(MatView(A, mviewer));
2934:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference Jacobian ----------\n"));
2935:       PetscCall(MatView(B, mviewer));
2936:     }

2938:     if (threshold_print || complete_print) {
2939:       PetscInt           Istart, Iend, *ccols, bncols, cncols, j, row;
2940:       PetscScalar       *cvals;
2941:       const PetscInt    *bcols;
2942:       const PetscScalar *bvals;

2944:       PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2945:       PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

2947:       PetscCall(MatAYPX(B, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2948:       PetscCall(MatGetOwnershipRange(B, &Istart, &Iend));

2950:       for (row = Istart; row < Iend; row++) {
2951:         PetscCall(MatGetRow(B, row, &bncols, &bcols, &bvals));
2952:         PetscCall(PetscMalloc2(bncols, &ccols, bncols, &cvals));
2953:         for (j = 0, cncols = 0; j < bncols; j++) {
2954:           if (PetscAbsScalar(bvals[j]) > threshold) {
2955:             ccols[cncols] = bcols[j];
2956:             cvals[cncols] = bvals[j];
2957:             cncols += 1;
2958:           }
2959:         }
2960:         if (cncols) PetscCall(MatSetValues(C, 1, &row, cncols, ccols, cvals, INSERT_VALUES));
2961:         PetscCall(MatRestoreRow(B, row, &bncols, &bcols, &bvals));
2962:         PetscCall(PetscFree2(ccols, cvals));
2963:       }
2964:       PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2965:       PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2966:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n", (double)threshold));
2967:       PetscCall(MatView(C, complete_print ? mviewer : viewer));
2968:       PetscCall(MatDestroy(&C));
2969:     }
2970:     PetscCall(MatDestroy(&A));
2971:     PetscCall(MatDestroy(&B));
2972:     PetscCall(MatDestroy(&JT));
2973:     if (Jsave) jacobian = Jsave;
2974:     if (jacobian != snes->jacobian_pre) {
2975:       jacobian = snes->jacobian_pre;
2976:       if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Jacobian for preconditioner -------------\n"));
2977:     } else jacobian = NULL;
2978:   }
2979:   PetscCall(VecDestroy(&x));
2980:   if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2981:   PetscCall(PetscViewerDestroy(&mviewer));
2982:   PetscCall(PetscViewerASCIISetTab(viewer, tabs));

2984:   if (Jnorm) *Jnorm = gnorm;
2985:   if (diffNorm) *diffNorm = nrm;
2986:   PetscFunctionReturn(PETSC_SUCCESS);
2987: }

2989: /*@
2990:   SNESComputeJacobian - Computes the Jacobian matrix that has been set with `SNESSetJacobian()`.

2992:   Collective

2994:   Input Parameters:
2995: + snes - the `SNES` context
2996: - X    - input vector

2998:   Output Parameters:
2999: + A - Jacobian matrix
3000: - B - optional matrix for building the preconditioner, usually the same as `A`

3002:   Options Database Keys:
3003: + -snes_lag_preconditioner lag          - how often to rebuild preconditioner
3004: . -snes_lag_jacobian lag                - how often to rebuild Jacobian
3005: . -snes_test_jacobian [threshold]       - compare the user provided Jacobian with one compute via finite differences to check for errors.
3006:                                           If a threshold is given, display only those entries whose difference is greater than the threshold.
3007: . -snes_test_jacobian_view [viewer]     - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
3008: . -snes_compare_explicit                - Compare the computed Jacobian to the finite difference Jacobian and output the differences
3009: . -snes_compare_explicit_draw           - Compare the computed Jacobian to the finite difference Jacobian and draw the result
3010: . -snes_compare_explicit_contour        - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
3011: . -snes_compare_operator                - Make the comparison options above use the operator instead of the matrix used to construct the preconditioner
3012: . -snes_compare_coloring                - Compute the finite difference Jacobian using coloring and display norms of difference
3013: . -snes_compare_coloring_display        - Compute the finite difference Jacobian using coloring and display verbose differences
3014: . -snes_compare_coloring_threshold      - Display only those matrix entries that differ by more than a given threshold
3015: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3016: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3017: . -snes_compare_coloring_draw           - Compute the finite difference Jacobian using coloring and draw differences
3018: - -snes_compare_coloring_draw_contour   - Compute the finite difference Jacobian using coloring and show contours of matrices and differences

3020:   Level: developer

3022:   Note:
3023:   Most users should not need to explicitly call this routine, as it
3024:   is used internally within the nonlinear solvers.

3026:   Developer Note:
3027:   This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons, the routine `SNESTestJacobian()` use to used
3028:   with the `SNESType` of test that has been removed.

3030: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
3031:           `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
3032: @*/
3033: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
3034: {
3035:   PetscBool flag;
3036:   DM        dm;
3037:   DMSNES    sdm;
3038:   KSP       ksp;

3040:   PetscFunctionBegin;
3043:   PetscCheckSameComm(snes, 1, X, 2);
3044:   PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
3045:   PetscCall(SNESGetDM(snes, &dm));
3046:   PetscCall(DMGetDMSNES(dm, &sdm));

3048:   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix-free */
3049:   if (snes->lagjacobian == -2) {
3050:     snes->lagjacobian = -1;

3052:     PetscCall(PetscInfo(snes, "Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
3053:   } else if (snes->lagjacobian == -1) {
3054:     PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is -1\n"));
3055:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3056:     if (flag) {
3057:       PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3058:       PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3059:     }
3060:     PetscFunctionReturn(PETSC_SUCCESS);
3061:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
3062:     PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagjacobian, snes->iter));
3063:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3064:     if (flag) {
3065:       PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3066:       PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3067:     }
3068:     PetscFunctionReturn(PETSC_SUCCESS);
3069:   }
3070:   if (snes->npc && snes->npcside == PC_LEFT) {
3071:     /* SNESASPIN uses SNESNASM as the nonlinear preconditioner. When SNESNASM
3072:        is done solving the sub-systems it calls the user-provided Jacobian function
3073:        (corresponding to the unpreconditioned residual) retrieved through the DM.
3074:        Consequently it would be redundant to call the Jacobian function here. In
3075:        the future we may move the outer Jacobian function call out of SNESNASM
3076:        in which case no special casing will be required here. */
3077:     PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESASPIN, &flag));
3078:     if (flag) {
3079:       PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3080:       PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3081:       PetscFunctionReturn(PETSC_SUCCESS);
3082:     }
3083:   }

3085:   PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
3086:   PetscCall(VecLockReadPush(X));
3087:   {
3088:     void           *ctx;
3089:     SNESJacobianFn *J;
3090:     PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
3091:     PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
3092:   }
3093:   PetscCall(VecLockReadPop(X));
3094:   PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));

3096:   /* attach latest linearization point to the matrix used to construct the preconditioner */
3097:   PetscCall(PetscObjectCompose((PetscObject)B, "__SNES_latest_X", (PetscObject)X));

3099:   /* the next line ensures that snes->ksp exists */
3100:   PetscCall(SNESGetKSP(snes, &ksp));
3101:   if (snes->lagpreconditioner == -2) {
3102:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3103:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3104:     snes->lagpreconditioner = -1;
3105:   } else if (snes->lagpreconditioner == -1) {
3106:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3107:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3108:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3109:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3110:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3111:   } else {
3112:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3113:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3114:   }

3116:   /* monkey business to allow testing Jacobians in multilevel solvers.
3117:      This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3118:   {
3119:     Vec xsave            = snes->vec_sol;
3120:     Mat jacobiansave     = snes->jacobian;
3121:     Mat jacobian_presave = snes->jacobian_pre;

3123:     snes->vec_sol      = X;
3124:     snes->jacobian     = A;
3125:     snes->jacobian_pre = B;
3126:     if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3127:     if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));

3129:     snes->vec_sol      = xsave;
3130:     snes->jacobian     = jacobiansave;
3131:     snes->jacobian_pre = jacobian_presave;
3132:   }

3134:   {
3135:     PetscBool flag = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_operator = PETSC_FALSE;
3136:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit", NULL, NULL, &flag));
3137:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw", NULL, NULL, &flag_draw));
3138:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw_contour", NULL, NULL, &flag_contour));
3139:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_operator", NULL, NULL, &flag_operator));
3140:     if (flag || flag_draw || flag_contour) {
3141:       Mat         Bexp_mine = NULL, Bexp, FDexp;
3142:       PetscViewer vdraw, vstdout;
3143:       PetscBool   flg;
3144:       if (flag_operator) {
3145:         PetscCall(MatComputeOperator(A, MATAIJ, &Bexp_mine));
3146:         Bexp = Bexp_mine;
3147:       } else {
3148:         /* See if the matrix used to construct the preconditioner can be viewed and added directly */
3149:         PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
3150:         if (flg) Bexp = B;
3151:         else {
3152:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
3153:           PetscCall(MatComputeOperator(B, MATAIJ, &Bexp_mine));
3154:           Bexp = Bexp_mine;
3155:         }
3156:       }
3157:       PetscCall(MatConvert(Bexp, MATSAME, MAT_INITIAL_MATRIX, &FDexp));
3158:       PetscCall(SNESComputeJacobianDefault(snes, X, FDexp, FDexp, NULL));
3159:       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3160:       if (flag_draw || flag_contour) {
3161:         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Explicit Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3162:         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3163:       } else vdraw = NULL;
3164:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit %s\n", flag_operator ? "Jacobian" : "preconditioning Jacobian"));
3165:       if (flag) PetscCall(MatView(Bexp, vstdout));
3166:       if (vdraw) PetscCall(MatView(Bexp, vdraw));
3167:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Finite difference Jacobian\n"));
3168:       if (flag) PetscCall(MatView(FDexp, vstdout));
3169:       if (vdraw) PetscCall(MatView(FDexp, vdraw));
3170:       PetscCall(MatAYPX(FDexp, -1.0, Bexp, SAME_NONZERO_PATTERN));
3171:       PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian\n"));
3172:       if (flag) PetscCall(MatView(FDexp, vstdout));
3173:       if (vdraw) { /* Always use contour for the difference */
3174:         PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3175:         PetscCall(MatView(FDexp, vdraw));
3176:         PetscCall(PetscViewerPopFormat(vdraw));
3177:       }
3178:       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3179:       PetscCall(PetscViewerDestroy(&vdraw));
3180:       PetscCall(MatDestroy(&Bexp_mine));
3181:       PetscCall(MatDestroy(&FDexp));
3182:     }
3183:   }
3184:   {
3185:     PetscBool flag = PETSC_FALSE, flag_display = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_threshold = PETSC_FALSE;
3186:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON, threshold_rtol = 10 * PETSC_SQRT_MACHINE_EPSILON;
3187:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring", NULL, NULL, &flag));
3188:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_display", NULL, NULL, &flag_display));
3189:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw", NULL, NULL, &flag_draw));
3190:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw_contour", NULL, NULL, &flag_contour));
3191:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold", NULL, NULL, &flag_threshold));
3192:     if (flag_threshold) {
3193:       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_rtol", &threshold_rtol, NULL));
3194:       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_atol", &threshold_atol, NULL));
3195:     }
3196:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
3197:       Mat             Bfd;
3198:       PetscViewer     vdraw, vstdout;
3199:       MatColoring     coloring;
3200:       ISColoring      iscoloring;
3201:       MatFDColoring   matfdcoloring;
3202:       SNESFunctionFn *func;
3203:       void           *funcctx;
3204:       PetscReal       norm1, norm2, normmax;

3206:       PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3207:       PetscCall(MatColoringCreate(Bfd, &coloring));
3208:       PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3209:       PetscCall(MatColoringSetFromOptions(coloring));
3210:       PetscCall(MatColoringApply(coloring, &iscoloring));
3211:       PetscCall(MatColoringDestroy(&coloring));
3212:       PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3213:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3214:       PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3215:       PetscCall(ISColoringDestroy(&iscoloring));

3217:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3218:       PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3219:       PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3220:       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3221:       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3222:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3223:       PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3224:       PetscCall(MatFDColoringDestroy(&matfdcoloring));

3226:       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3227:       if (flag_draw || flag_contour) {
3228:         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Colored Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3229:         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3230:       } else vdraw = NULL;
3231:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit preconditioning Jacobian\n"));
3232:       if (flag_display) PetscCall(MatView(B, vstdout));
3233:       if (vdraw) PetscCall(MatView(B, vdraw));
3234:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Colored Finite difference Jacobian\n"));
3235:       if (flag_display) PetscCall(MatView(Bfd, vstdout));
3236:       if (vdraw) PetscCall(MatView(Bfd, vdraw));
3237:       PetscCall(MatAYPX(Bfd, -1.0, B, SAME_NONZERO_PATTERN));
3238:       PetscCall(MatNorm(Bfd, NORM_1, &norm1));
3239:       PetscCall(MatNorm(Bfd, NORM_FROBENIUS, &norm2));
3240:       PetscCall(MatNorm(Bfd, NORM_MAX, &normmax));
3241:       PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n", (double)norm1, (double)norm2, (double)normmax));
3242:       if (flag_display) PetscCall(MatView(Bfd, vstdout));
3243:       if (vdraw) { /* Always use contour for the difference */
3244:         PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3245:         PetscCall(MatView(Bfd, vdraw));
3246:         PetscCall(PetscViewerPopFormat(vdraw));
3247:       }
3248:       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));

3250:       if (flag_threshold) {
3251:         PetscInt bs, rstart, rend, i;
3252:         PetscCall(MatGetBlockSize(B, &bs));
3253:         PetscCall(MatGetOwnershipRange(B, &rstart, &rend));
3254:         for (i = rstart; i < rend; i++) {
3255:           const PetscScalar *ba, *ca;
3256:           const PetscInt    *bj, *cj;
3257:           PetscInt           bn, cn, j, maxentrycol = -1, maxdiffcol = -1, maxrdiffcol = -1;
3258:           PetscReal          maxentry = 0, maxdiff = 0, maxrdiff = 0;
3259:           PetscCall(MatGetRow(B, i, &bn, &bj, &ba));
3260:           PetscCall(MatGetRow(Bfd, i, &cn, &cj, &ca));
3261:           PetscCheck(bn == cn, ((PetscObject)A)->comm, PETSC_ERR_PLIB, "Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
3262:           for (j = 0; j < bn; j++) {
3263:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3264:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
3265:               maxentrycol = bj[j];
3266:               maxentry    = PetscRealPart(ba[j]);
3267:             }
3268:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
3269:               maxdiffcol = bj[j];
3270:               maxdiff    = PetscRealPart(ca[j]);
3271:             }
3272:             if (rdiff > maxrdiff) {
3273:               maxrdiffcol = bj[j];
3274:               maxrdiff    = rdiff;
3275:             }
3276:           }
3277:           if (maxrdiff > 1) {
3278:             PetscCall(PetscViewerASCIIPrintf(vstdout, "row %" PetscInt_FMT " (maxentry=%g at %" PetscInt_FMT ", maxdiff=%g at %" PetscInt_FMT ", maxrdiff=%g at %" PetscInt_FMT "):", i, (double)maxentry, maxentrycol, (double)maxdiff, maxdiffcol, (double)maxrdiff, maxrdiffcol));
3279:             for (j = 0; j < bn; j++) {
3280:               PetscReal rdiff;
3281:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3282:               if (rdiff > 1) PetscCall(PetscViewerASCIIPrintf(vstdout, " (%" PetscInt_FMT ",%g:%g)", bj[j], (double)PetscRealPart(ba[j]), (double)PetscRealPart(ca[j])));
3283:             }
3284:             PetscCall(PetscViewerASCIIPrintf(vstdout, "\n"));
3285:           }
3286:           PetscCall(MatRestoreRow(B, i, &bn, &bj, &ba));
3287:           PetscCall(MatRestoreRow(Bfd, i, &cn, &cj, &ca));
3288:         }
3289:       }
3290:       PetscCall(PetscViewerDestroy(&vdraw));
3291:       PetscCall(MatDestroy(&Bfd));
3292:     }
3293:   }
3294:   PetscFunctionReturn(PETSC_SUCCESS);
3295: }

3297: /*@
3298:   SNESSetJacobian - Sets the function to compute Jacobian as well as the
3299:   location to store the matrix.

3301:   Logically Collective

3303:   Input Parameters:
3304: + snes - the `SNES` context
3305: . Amat - the matrix that defines the (approximate) Jacobian
3306: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3307: . J    - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3308: - ctx  - [optional] user-defined context for private data for the
3309:          Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)

3311:   Level: beginner

3313:   Notes:
3314:   If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3315:   each matrix.

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

3320:   If using `SNESComputeJacobianDefaultColor()` to assemble a Jacobian, the `ctx` argument
3321:   must be a `MatFDColoring`.

3323:   Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
3324:   example is to use the "Picard linearization" which only differentiates through the highest order parts of each term using `SNESSetPicard()`

3326: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3327:           `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3328: @*/
3329: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3330: {
3331:   DM dm;

3333:   PetscFunctionBegin;
3337:   if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3338:   if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3339:   /* update DMSNES
3340:      We support incremental information; so update the function context only if both Amat and Pmat are not specified
3341:      (which allows to disable the callbacks when both J and ctx are NULL),
3342:      or, if any of the mats is specified, when at least one of J and ctx is not NULL */
3343:   PetscCall(SNESGetDM(snes, &dm));
3344:   if ((!Amat && !Pmat) || J || ctx) PetscCall(DMSNESSetJacobian(dm, J, ctx));
3345:   if (Amat) {
3346:     PetscCall(PetscObjectReference((PetscObject)Amat));
3347:     PetscCall(MatDestroy(&snes->jacobian));

3349:     snes->jacobian = Amat;
3350:   }
3351:   if (Pmat) {
3352:     PetscCall(PetscObjectReference((PetscObject)Pmat));
3353:     PetscCall(MatDestroy(&snes->jacobian_pre));

3355:     snes->jacobian_pre = Pmat;
3356:   }
3357:   PetscFunctionReturn(PETSC_SUCCESS);
3358: }

3360: /*@
3361:   SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3362:   provided context for evaluating the Jacobian.

3364:   Not Collective, but `Mat` object will be parallel if `SNES` is

3366:   Input Parameter:
3367: . snes - the nonlinear solver context

3369:   Output Parameters:
3370: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3371: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3372: . J    - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3373: - ctx  - location to stash Jacobian ctx (or `NULL`)

3375:   Level: advanced

3377: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3378: @*/
3379: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3380: {
3381:   DM dm;

3383:   PetscFunctionBegin;
3385:   if (Amat) *Amat = snes->jacobian;
3386:   if (Pmat) *Pmat = snes->jacobian_pre;
3387:   PetscCall(SNESGetDM(snes, &dm));
3388:   PetscCall(DMSNESGetJacobian(dm, J, ctx));
3389:   PetscFunctionReturn(PETSC_SUCCESS);
3390: }

3392: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3393: {
3394:   DM     dm;
3395:   DMSNES sdm;

3397:   PetscFunctionBegin;
3398:   PetscCall(SNESGetDM(snes, &dm));
3399:   PetscCall(DMGetDMSNES(dm, &sdm));
3400:   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3401:     DM        dm;
3402:     PetscBool isdense, ismf;

3404:     PetscCall(SNESGetDM(snes, &dm));
3405:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3406:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3407:     if (isdense) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3408:     else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3409:   }
3410:   PetscFunctionReturn(PETSC_SUCCESS);
3411: }

3413: /*@
3414:   SNESSetUp - Sets up the internal data structures for the later use
3415:   of a nonlinear solver `SNESSolve()`.

3417:   Collective

3419:   Input Parameter:
3420: . snes - the `SNES` context

3422:   Level: advanced

3424:   Note:
3425:   For basic use of the `SNES` solvers the user does not need to explicitly call
3426:   `SNESSetUp()`, since these actions will automatically occur during
3427:   the call to `SNESSolve()`.  However, if one wishes to control this
3428:   phase separately, `SNESSetUp()` should be called after `SNESCreate()`
3429:   and optional routines of the form SNESSetXXX(), but before `SNESSolve()`.

3431: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3432: @*/
3433: PetscErrorCode SNESSetUp(SNES snes)
3434: {
3435:   DM             dm;
3436:   DMSNES         sdm;
3437:   SNESLineSearch linesearch, pclinesearch;
3438:   void          *lsprectx, *lspostctx;
3439:   PetscBool      mf_operator, mf;
3440:   Vec            f, fpc;
3441:   void          *funcctx;
3442:   void          *jacctx, *appctx;
3443:   Mat            j, jpre;
3444:   PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3445:   PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3446:   SNESFunctionFn *func;
3447:   SNESJacobianFn *jac;

3449:   PetscFunctionBegin;
3451:   if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3452:   PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));

3454:   if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, SNESNEWTONLS));

3456:   PetscCall(SNESGetFunction(snes, &snes->vec_func, NULL, NULL));

3458:   PetscCall(SNESGetDM(snes, &dm));
3459:   PetscCall(DMGetDMSNES(dm, &sdm));
3460:   PetscCall(SNESSetDefaultComputeJacobian(snes));

3462:   if (!snes->vec_func) PetscCall(DMCreateGlobalVector(dm, &snes->vec_func));

3464:   if (snes->usesksp && !snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));

3466:   if (snes->linesearch) {
3467:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3468:     PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3469:   }

3471:   PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3472:   if (snes->npc && snes->npcside == PC_LEFT) {
3473:     snes->mf          = PETSC_TRUE;
3474:     snes->mf_operator = PETSC_FALSE;
3475:   }
3476:   if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));
3477:   if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));

3479:   if (snes->npc) {
3480:     SNESNormSchedule npc_norm_schedule;

3482:     /* copy the DM over and the functions if NPC DM is not present */
3483:     if (!snes->npc->dm) {
3484:       PetscCall(SNESGetDM(snes, &dm));
3485:       PetscCall(SNESSetDM(snes->npc, dm));

3487:       PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3488:       PetscCall(VecDuplicate(f, &fpc));
3489:       PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3490:       PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3491:       PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3492:       PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3493:       PetscCall(VecDestroy(&fpc));

3495:       /* copy the function pointers over */
3496:       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes, (PetscObject)snes->npc));

3498:       /* Propagate app context if not present */
3499:       PetscCall(SNESGetApplicationContext(snes->npc, &appctx));
3500:       if (!appctx && !snes->npc->ops->ctxcompute) {
3501:         if (snes->ops->ctxcompute) {
3502:           PetscCall(SNESSetComputeApplicationContext(snes->npc, snes->ops->ctxcompute, snes->ops->ctxdestroy));
3503:         } else {
3504:           PetscCall(SNESGetApplicationContext(snes, &appctx));
3505:           PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3506:         }
3507:       }
3508:     }

3510:     /* Set default norm schedule for NPC if not yet set */
3511:     PetscCall(SNESGetNormSchedule(snes->npc, &npc_norm_schedule));
3512:     if (npc_norm_schedule == SNES_NORM_DEFAULT) {
3513:       if (snes->npcside == PC_RIGHT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3514:       else if (snes->npcside == PC_LEFT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3515:     }

3517:     PetscCall(SNESSetFromOptions(snes->npc));

3519:     /* copy the line search context over */
3520:     if (snes->dm == snes->npc->dm && snes->linesearch && snes->npc->linesearch) {
3521:       PetscCall(SNESGetLineSearch(snes, &linesearch));
3522:       PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3523:       PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3524:       PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3525:       PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3526:       PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3527:       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3528:     }
3529:   }

3531:   snes->jac_iter = 0;
3532:   snes->pre_iter = 0;

3534:   PetscTryTypeMethod(snes, setup);

3536:   PetscCall(SNESSetDefaultComputeJacobian(snes));

3538:   if (snes->npc && snes->npcside == PC_LEFT) {
3539:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3540:       if (snes->linesearch) {
3541:         PetscCall(SNESGetLineSearch(snes, &linesearch));
3542:         PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3543:       }
3544:     }
3545:   }
3546:   PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3547:   snes->setupcalled = PETSC_TRUE;
3548:   PetscFunctionReturn(PETSC_SUCCESS);
3549: }

3551: /*@
3552:   SNESReset - Resets a `SNES` context to the state it was in before `SNESSetUp()` was called and removes any allocated `Vec` and `Mat` from its data structures

3554:   Collective

3556:   Input Parameter:
3557: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`

3559:   Level: intermediate

3561:   Notes:
3562:   Any options set on the `SNES` object, including those set with `SNESSetFromOptions()` remain.

3564:   Call this if you wish to reuse a `SNES` but with different size vectors

3566:   Also calls the application context destroy routine set with `SNESSetComputeApplicationContext()`

3568: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3569: @*/
3570: PetscErrorCode SNESReset(SNES snes)
3571: {
3572:   PetscFunctionBegin;
3574:   if (snes->ops->ctxdestroy && snes->ctx) {
3575:     PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3576:     snes->ctx = NULL;
3577:   }
3578:   if (snes->npc) PetscCall(SNESReset(snes->npc));

3580:   PetscTryTypeMethod(snes, reset);
3581:   if (snes->ksp) PetscCall(KSPReset(snes->ksp));

3583:   if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));

3585:   PetscCall(VecDestroy(&snes->vec_rhs));
3586:   PetscCall(VecDestroy(&snes->vec_sol));
3587:   PetscCall(VecDestroy(&snes->vec_sol_update));
3588:   PetscCall(VecDestroy(&snes->vec_func));
3589:   PetscCall(MatDestroy(&snes->jacobian));
3590:   PetscCall(MatDestroy(&snes->jacobian_pre));
3591:   PetscCall(MatDestroy(&snes->picard));
3592:   PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3593:   PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));

3595:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3597:   snes->nwork = snes->nvwork = 0;
3598:   snes->setupcalled          = PETSC_FALSE;
3599:   PetscFunctionReturn(PETSC_SUCCESS);
3600: }

3602: /*@
3603:   SNESConvergedReasonViewCancel - Clears all the reason view functions for a `SNES` object provided with `SNESConvergedReasonViewSet()` also
3604:   removes the default viewer.

3606:   Collective

3608:   Input Parameter:
3609: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`

3611:   Level: intermediate

3613: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3614: @*/
3615: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3616: {
3617:   PetscFunctionBegin;
3619:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
3620:     if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3621:   }
3622:   snes->numberreasonviews = 0;
3623:   PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3624:   PetscFunctionReturn(PETSC_SUCCESS);
3625: }

3627: /*@
3628:   SNESDestroy - Destroys the nonlinear solver context that was created
3629:   with `SNESCreate()`.

3631:   Collective

3633:   Input Parameter:
3634: . snes - the `SNES` context

3636:   Level: beginner

3638: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3639: @*/
3640: PetscErrorCode SNESDestroy(SNES *snes)
3641: {
3642:   DM dm;

3644:   PetscFunctionBegin;
3645:   if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3647:   if (--((PetscObject)*snes)->refct > 0) {
3648:     *snes = NULL;
3649:     PetscFunctionReturn(PETSC_SUCCESS);
3650:   }

3652:   PetscCall(SNESReset(*snes));
3653:   PetscCall(SNESDestroy(&(*snes)->npc));

3655:   /* if memory was published with SAWs then destroy it */
3656:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3657:   PetscTryTypeMethod(*snes, destroy);

3659:   dm = (*snes)->dm;
3660:   while (dm) {
3661:     PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3662:     PetscCall(DMGetCoarseDM(dm, &dm));
3663:   }

3665:   PetscCall(DMDestroy(&(*snes)->dm));
3666:   PetscCall(KSPDestroy(&(*snes)->ksp));
3667:   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));

3669:   PetscCall(PetscFree((*snes)->kspconvctx));
3670:   if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3671:   if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3672:   PetscCall(SNESMonitorCancel(*snes));
3673:   PetscCall(SNESConvergedReasonViewCancel(*snes));
3674:   PetscCall(PetscHeaderDestroy(snes));
3675:   PetscFunctionReturn(PETSC_SUCCESS);
3676: }

3678: /* ----------- Routines to set solver parameters ---------- */

3680: /*@
3681:   SNESSetLagPreconditioner - Sets when the preconditioner is rebuilt in the nonlinear solve `SNESSolve()`.

3683:   Logically Collective

3685:   Input Parameters:
3686: + snes - the `SNES` context
3687: - lag  - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3688:          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that

3690:   Options Database Keys:
3691: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple `SNESSolve()`
3692: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3693: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3694: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3696:   Level: intermediate

3698:   Notes:
3699:   The default is 1

3701:   The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagPreconditionerPersists()` was called

3703:   `SNESSetLagPreconditionerPersists()` allows using the same uniform lagging (for example every second linear solve) across multiple nonlinear solves.

3705: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3706:           `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3707: @*/
3708: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3709: {
3710:   PetscFunctionBegin;
3713:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3714:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3715:   snes->lagpreconditioner = lag;
3716:   PetscFunctionReturn(PETSC_SUCCESS);
3717: }

3719: /*@
3720:   SNESSetGridSequence - sets the number of steps of grid sequencing that `SNES` will do

3722:   Logically Collective

3724:   Input Parameters:
3725: + snes  - the `SNES` context
3726: - steps - the number of refinements to do, defaults to 0

3728:   Options Database Key:
3729: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess

3731:   Level: intermediate

3733:   Notes:
3734:   Once grid sequencing is turned on `SNESSolve()` will automatically perform the solve on each grid refinement.

3736:   Use `SNESGetSolution()` to extract the fine grid solution after grid sequencing.

3738: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3739:           `SNESSetDM()`, `SNESSolve()`
3740: @*/
3741: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3742: {
3743:   PetscFunctionBegin;
3746:   snes->gridsequence = steps;
3747:   PetscFunctionReturn(PETSC_SUCCESS);
3748: }

3750: /*@
3751:   SNESGetGridSequence - gets the number of steps of grid sequencing that `SNES` will do

3753:   Logically Collective

3755:   Input Parameter:
3756: . snes - the `SNES` context

3758:   Output Parameter:
3759: . steps - the number of refinements to do, defaults to 0

3761:   Level: intermediate

3763: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3764: @*/
3765: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3766: {
3767:   PetscFunctionBegin;
3769:   *steps = snes->gridsequence;
3770:   PetscFunctionReturn(PETSC_SUCCESS);
3771: }

3773: /*@
3774:   SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt

3776:   Not Collective

3778:   Input Parameter:
3779: . snes - the `SNES` context

3781:   Output Parameter:
3782: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3783:          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that

3785:   Level: intermediate

3787:   Notes:
3788:   The default is 1

3790:   The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3792: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3793: @*/
3794: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3795: {
3796:   PetscFunctionBegin;
3798:   *lag = snes->lagpreconditioner;
3799:   PetscFunctionReturn(PETSC_SUCCESS);
3800: }

3802: /*@
3803:   SNESSetLagJacobian - Set when the Jacobian is rebuilt in the nonlinear solve. See `SNESSetLagPreconditioner()` for determining how
3804:   often the preconditioner is rebuilt.

3806:   Logically Collective

3808:   Input Parameters:
3809: + snes - the `SNES` context
3810: - lag  - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3811:          the Jacobian is built etc. -2 means rebuild at next chance but then never again

3813:   Options Database Keys:
3814: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3815: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3816: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3817: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag.

3819:   Level: intermediate

3821:   Notes:
3822:   The default is 1

3824:   The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3826:   If  -1 is used before the very first nonlinear solve the CODE WILL FAIL! because no Jacobian is used, use -2 to indicate you want it recomputed
3827:   at the next Newton step but never again (unless it is reset to another value)

3829: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3830: @*/
3831: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3832: {
3833:   PetscFunctionBegin;
3835:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3836:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3838:   snes->lagjacobian = lag;
3839:   PetscFunctionReturn(PETSC_SUCCESS);
3840: }

3842: /*@
3843:   SNESGetLagJacobian - Get how often the Jacobian is rebuilt. See `SNESGetLagPreconditioner()` to determine when the preconditioner is rebuilt

3845:   Not Collective

3847:   Input Parameter:
3848: . snes - the `SNES` context

3850:   Output Parameter:
3851: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3852:          the Jacobian is built etc.

3854:   Level: intermediate

3856:   Notes:
3857:   The default is 1

3859:   The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagJacobianPersists()` was called.

3861: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3862: @*/
3863: PetscErrorCode SNESGetLagJacobian(SNES snes, PetscInt *lag)
3864: {
3865:   PetscFunctionBegin;
3867:   *lag = snes->lagjacobian;
3868:   PetscFunctionReturn(PETSC_SUCCESS);
3869: }

3871: /*@
3872:   SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple nonlinear solves

3874:   Logically collective

3876:   Input Parameters:
3877: + snes - the `SNES` context
3878: - flg  - jacobian lagging persists if true

3880:   Options Database Keys:
3881: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3882: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3883: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3884: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3886:   Level: advanced

3888:   Notes:
3889:   Normally when `SNESSetLagJacobian()` is used, the Jacobian is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior

3891:   This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3892:   several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3893:   timesteps may present huge efficiency gains.

3895: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3896: @*/
3897: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3898: {
3899:   PetscFunctionBegin;
3902:   snes->lagjac_persist = flg;
3903:   PetscFunctionReturn(PETSC_SUCCESS);
3904: }

3906: /*@
3907:   SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves

3909:   Logically Collective

3911:   Input Parameters:
3912: + snes - the `SNES` context
3913: - flg  - preconditioner lagging persists if true

3915:   Options Database Keys:
3916: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3917: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3918: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3919: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3921:   Level: developer

3923:   Notes:
3924:   Normally when `SNESSetLagPreconditioner()` is used, the preconditioner is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior

3926:   This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3927:   by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3928:   several timesteps may present huge efficiency gains.

3930: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3931: @*/
3932: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3933: {
3934:   PetscFunctionBegin;
3937:   snes->lagpre_persist = flg;
3938:   PetscFunctionReturn(PETSC_SUCCESS);
3939: }

3941: /*@
3942:   SNESSetForceIteration - force `SNESSolve()` to take at least one iteration regardless of the initial residual norm

3944:   Logically Collective

3946:   Input Parameters:
3947: + snes  - the `SNES` context
3948: - force - `PETSC_TRUE` require at least one iteration

3950:   Options Database Key:
3951: . -snes_force_iteration force - Sets forcing an iteration

3953:   Level: intermediate

3955:   Note:
3956:   This is used sometimes with `TS` to prevent `TS` from detecting a false steady state solution

3958: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3959: @*/
3960: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3961: {
3962:   PetscFunctionBegin;
3964:   snes->forceiteration = force;
3965:   PetscFunctionReturn(PETSC_SUCCESS);
3966: }

3968: /*@
3969:   SNESGetForceIteration - Check whether or not `SNESSolve()` take at least one iteration regardless of the initial residual norm

3971:   Logically Collective

3973:   Input Parameter:
3974: . snes - the `SNES` context

3976:   Output Parameter:
3977: . force - `PETSC_TRUE` requires at least one iteration.

3979:   Level: intermediate

3981: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3982: @*/
3983: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3984: {
3985:   PetscFunctionBegin;
3987:   *force = snes->forceiteration;
3988:   PetscFunctionReturn(PETSC_SUCCESS);
3989: }

3991: /*@
3992:   SNESSetTolerances - Sets various parameters used in `SNES` convergence tests.

3994:   Logically Collective

3996:   Input Parameters:
3997: + snes   - the `SNES` context
3998: . abstol - the absolute convergence tolerance, $ F(x^n) \le abstol $
3999: . rtol   - the relative convergence tolerance, $ F(x^n) \le reltol * F(x^0) $
4000: . stol   - convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
4001: . maxit  - the maximum number of iterations allowed in the solver, default 50.
4002: - maxf   - the maximum number of function evaluations allowed in the solver (use `PETSC_UNLIMITED` indicates no limit), default 10,000

4004:   Options Database Keys:
4005: + -snes_atol abstol    - Sets `abstol`
4006: . -snes_rtol rtol      - Sets `rtol`
4007: . -snes_stol stol      - Sets `stol`
4008: . -snes_max_it maxit   - Sets `maxit`
4009: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)

4011:   Level: intermediate

4013:   Note:
4014:   All parameters must be non-negative

4016:   Use `PETSC_CURRENT` to retain the current value of any parameter and `PETSC_DETERMINE` to use the default value for the given `SNES`.
4017:   The default value is the value in the object when its type is set.

4019:   Use `PETSC_UNLIMITED` on `maxit` or `maxf` to indicate there is no bound on the number of iterations or number of function evaluations.

4021:   Fortran Note:
4022:   Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`

4024: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
4025: @*/
4026: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
4027: {
4028:   PetscFunctionBegin;

4036:   if (abstol == (PetscReal)PETSC_DETERMINE) {
4037:     snes->abstol = snes->default_abstol;
4038:   } else if (abstol != (PetscReal)PETSC_CURRENT) {
4039:     PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
4040:     snes->abstol = abstol;
4041:   }

4043:   if (rtol == (PetscReal)PETSC_DETERMINE) {
4044:     snes->rtol = snes->default_rtol;
4045:   } else if (rtol != (PetscReal)PETSC_CURRENT) {
4046:     PetscCheck(rtol >= 0.0 && 1.0 > rtol, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative and less than 1.0", (double)rtol);
4047:     snes->rtol = rtol;
4048:   }

4050:   if (stol == (PetscReal)PETSC_DETERMINE) {
4051:     snes->stol = snes->default_stol;
4052:   } else if (stol != (PetscReal)PETSC_CURRENT) {
4053:     PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
4054:     snes->stol = stol;
4055:   }

4057:   if (maxit == PETSC_DETERMINE) {
4058:     snes->max_its = snes->default_max_its;
4059:   } else if (maxit == PETSC_UNLIMITED) {
4060:     snes->max_its = PETSC_INT_MAX;
4061:   } else if (maxit != PETSC_CURRENT) {
4062:     PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
4063:     snes->max_its = maxit;
4064:   }

4066:   if (maxf == PETSC_DETERMINE) {
4067:     snes->max_funcs = snes->default_max_funcs;
4068:   } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
4069:     snes->max_funcs = PETSC_UNLIMITED;
4070:   } else if (maxf != PETSC_CURRENT) {
4071:     PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
4072:     snes->max_funcs = maxf;
4073:   }
4074:   PetscFunctionReturn(PETSC_SUCCESS);
4075: }

4077: /*@
4078:   SNESSetDivergenceTolerance - Sets the divergence tolerance used for the `SNES` divergence test.

4080:   Logically Collective

4082:   Input Parameters:
4083: + snes   - the `SNES` context
4084: - divtol - the divergence tolerance. Use `PETSC_UNLIMITED` to deactivate the test. If the residual norm $ F(x^n) \ge divtol * F(x^0) $ the solver
4085:            is stopped due to divergence.

4087:   Options Database Key:
4088: . -snes_divergence_tolerance divtol - Sets `divtol`

4090:   Level: intermediate

4092:   Notes:
4093:   Use `PETSC_DETERMINE` to use the default value from when the object's type was set.

4095:   Fortran Note:
4096:   Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`

4098: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
4099: @*/
4100: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
4101: {
4102:   PetscFunctionBegin;

4106:   if (divtol == (PetscReal)PETSC_DETERMINE) {
4107:     snes->divtol = snes->default_divtol;
4108:   } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
4109:     snes->divtol = PETSC_UNLIMITED;
4110:   } else if (divtol != (PetscReal)PETSC_CURRENT) {
4111:     PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
4112:     snes->divtol = divtol;
4113:   }
4114:   PetscFunctionReturn(PETSC_SUCCESS);
4115: }

4117: /*@
4118:   SNESGetTolerances - Gets various parameters used in `SNES` convergence tests.

4120:   Not Collective

4122:   Input Parameter:
4123: . snes - the `SNES` context

4125:   Output Parameters:
4126: + atol  - the absolute convergence tolerance
4127: . rtol  - the relative convergence tolerance
4128: . stol  - convergence tolerance in terms of the norm of the change in the solution between steps
4129: . maxit - the maximum number of iterations allowed
4130: - maxf  - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound

4132:   Level: intermediate

4134:   Notes:
4135:   See `SNESSetTolerances()` for details on the parameters.

4137:   The user can specify `NULL` for any parameter that is not needed.

4139: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4140: @*/
4141: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4142: {
4143:   PetscFunctionBegin;
4145:   if (atol) *atol = snes->abstol;
4146:   if (rtol) *rtol = snes->rtol;
4147:   if (stol) *stol = snes->stol;
4148:   if (maxit) *maxit = snes->max_its;
4149:   if (maxf) *maxf = snes->max_funcs;
4150:   PetscFunctionReturn(PETSC_SUCCESS);
4151: }

4153: /*@
4154:   SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

4156:   Not Collective

4158:   Input Parameters:
4159: + snes   - the `SNES` context
4160: - divtol - divergence tolerance

4162:   Level: intermediate

4164: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4165: @*/
4166: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4167: {
4168:   PetscFunctionBegin;
4170:   if (divtol) *divtol = snes->divtol;
4171:   PetscFunctionReturn(PETSC_SUCCESS);
4172: }

4174: PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES, PetscInt, PetscReal *);

4176: /*@
4177:   SNESMonitorLGRange - Line-graph monitor that plots the residual norm together with residual-range statistics for a `SNESSolve()`

4179:   Collective

4181:   Input Parameters:
4182: + snes   - the `SNES` context
4183: . n      - the iteration number
4184: . rnorm  - the 2-norm of the residual
4185: - monctx - a `PetscViewer` of type `PETSCVIEWERDRAW` set up with `PetscViewerMonitorLGSetUp()`

4187:   Level: intermediate

4189:   Note:
4190:   Plots four line graphs in the viewer: the residual norm (log scale), the fraction of residual entries larger than 20% of the maximum entry, the relative decrease `(prev - rnorm)/prev`, and their product.

4192: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`, `SNESMonitorDefault()`, `PetscViewerDrawGetDrawLG()`, `PetscDrawLG`
4193: @*/
4194: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4195: {
4196:   PetscDrawLG      lg;
4197:   PetscReal        x, y, per;
4198:   PetscViewer      v = (PetscViewer)monctx;
4199:   static PetscReal prev; /* should be in the context */
4200:   PetscDraw        draw;

4202:   PetscFunctionBegin;
4204:   PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4205:   if (!n) PetscCall(PetscDrawLGReset(lg));
4206:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4207:   PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4208:   x = (PetscReal)n;
4209:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4210:   else y = -15.0;
4211:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4212:   if (n < 20 || !(n % 5) || snes->reason) {
4213:     PetscCall(PetscDrawLGDraw(lg));
4214:     PetscCall(PetscDrawLGSave(lg));
4215:   }

4217:   PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4218:   if (!n) PetscCall(PetscDrawLGReset(lg));
4219:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4220:   PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4221:   PetscCall(SNESMonitorRange_Private(snes, n, &per));
4222:   x = (PetscReal)n;
4223:   y = 100.0 * per;
4224:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4225:   if (n < 20 || !(n % 5) || snes->reason) {
4226:     PetscCall(PetscDrawLGDraw(lg));
4227:     PetscCall(PetscDrawLGSave(lg));
4228:   }

4230:   PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4231:   if (!n) {
4232:     prev = rnorm;
4233:     PetscCall(PetscDrawLGReset(lg));
4234:   }
4235:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4236:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4237:   x = (PetscReal)n;
4238:   y = (prev - rnorm) / prev;
4239:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4240:   if (n < 20 || !(n % 5) || snes->reason) {
4241:     PetscCall(PetscDrawLGDraw(lg));
4242:     PetscCall(PetscDrawLGSave(lg));
4243:   }

4245:   PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4246:   if (!n) PetscCall(PetscDrawLGReset(lg));
4247:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4248:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4249:   x = (PetscReal)n;
4250:   y = (prev - rnorm) / (prev * per);
4251:   if (n > 2) { /*skip initial crazy value */
4252:     PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4253:   }
4254:   if (n < 20 || !(n % 5) || snes->reason) {
4255:     PetscCall(PetscDrawLGDraw(lg));
4256:     PetscCall(PetscDrawLGSave(lg));
4257:   }
4258:   prev = rnorm;
4259:   PetscFunctionReturn(PETSC_SUCCESS);
4260: }

4262: /*@
4263:   SNESConverged - Run the convergence test and update the `SNESConvergedReason`.

4265:   Collective

4267:   Input Parameters:
4268: + snes  - the `SNES` context
4269: . it    - current iteration
4270: . xnorm - 2-norm of current iterate
4271: . snorm - 2-norm of current step
4272: - fnorm - 2-norm of function

4274:   Level: developer

4276:   Note:
4277:   This routine is called by the `SNESSolve()` implementations.
4278:   It does not typically need to be called by the user.

4280: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4281: @*/
4282: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4283: {
4284:   PetscFunctionBegin;
4285:   if (!snes->reason) {
4286:     if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4287:     if (it == snes->max_its && !snes->reason) {
4288:       if (snes->normschedule == SNES_NORM_ALWAYS) {
4289:         PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4290:         snes->reason = SNES_DIVERGED_MAX_IT;
4291:       } else snes->reason = SNES_CONVERGED_ITS;
4292:     }
4293:   }
4294:   PetscFunctionReturn(PETSC_SUCCESS);
4295: }

4297: /*@
4298:   SNESMonitor - runs any `SNES` monitor routines provided with `SNESMonitor()` or the options database

4300:   Collective

4302:   Input Parameters:
4303: + snes  - nonlinear solver context obtained from `SNESCreate()`
4304: . iter  - current iteration number
4305: - rnorm - current relative norm of the residual

4307:   Level: developer

4309:   Note:
4310:   This routine is called by the `SNESSolve()` implementations.
4311:   It does not typically need to be called by the user.

4313: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4314: @*/
4315: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4316: {
4317:   PetscInt i, n = snes->numbermonitors;

4319:   PetscFunctionBegin;
4320:   PetscCall(VecLockReadPush(snes->vec_sol));
4321:   for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4322:   PetscCall(VecLockReadPop(snes->vec_sol));
4323:   PetscFunctionReturn(PETSC_SUCCESS);
4324: }

4326: /* ------------ Routines to set performance monitoring options ----------- */

4328: /*MC
4329:     SNESMonitorFunction - functional form passed to `SNESMonitorSet()` to monitor convergence of nonlinear solver

4331:      Synopsis:
4332: #include <petscsnes.h>
4333:     PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)

4335:      Collective

4337:     Input Parameters:
4338: +    snes - the `SNES` context
4339: .    its - iteration number
4340: .    norm - 2-norm function value (may be estimated)
4341: -    mctx - [optional] monitoring context

4343:    Level: advanced

4345: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4346: M*/

4348: /*@
4349:   SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4350:   iteration of the `SNES` nonlinear solver to display the iteration's
4351:   progress.

4353:   Logically Collective

4355:   Input Parameters:
4356: + snes           - the `SNES` context
4357: . f              - the monitor function,  for the calling sequence see `SNESMonitorFunction`
4358: . mctx           - [optional] user-defined context for private data for the monitor routine (use `NULL` if no context is desired)
4359: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

4361:   Calling sequence of f:
4362: + snes  - the `SNES` object
4363: . it    - the current iteration
4364: . rnorm - norm of the residual
4365: - mctx  - the optional monitor context

4367:   Options Database Keys:
4368: + -snes_monitor               - sets `SNESMonitorDefault()`
4369: . -snes_monitor draw::draw_lg - sets line graph monitor
4370: - -snes_monitor_cancel        - cancels all monitors that have been hardwired into a code by calls to `SNESMonitorSet()`, but does not cancel those set via
4371:                                 the options database.

4373:   Level: intermediate

4375:   Note:
4376:   Several different monitoring routines may be set by calling
4377:   `SNESMonitorSet()` multiple times; all will be called in the
4378:   order in which they were set.

4380:   Fortran Note:
4381:   Only a single monitor function can be set for each `SNES` object

4383: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4384: @*/
4385: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4386: {
4387:   PetscFunctionBegin;
4389:   for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4390:     PetscBool identical;

4392:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4393:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4394:   }
4395:   PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4396:   snes->monitor[snes->numbermonitors]          = f;
4397:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4398:   snes->monitorcontext[snes->numbermonitors++] = mctx;
4399:   PetscFunctionReturn(PETSC_SUCCESS);
4400: }

4402: /*@
4403:   SNESMonitorCancel - Clears all the monitor functions for a `SNES` object.

4405:   Logically Collective

4407:   Input Parameter:
4408: . snes - the `SNES` context

4410:   Options Database Key:
4411: . -snes_monitor_cancel - cancels all monitors that have been hardwired
4412:                          into a code by calls to `SNESMonitorSet()`, but does not cancel those
4413:                          set via the options database

4415:   Level: intermediate

4417:   Note:
4418:   There is no way to clear one specific monitor from a `SNES` object.

4420: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4421: @*/
4422: PetscErrorCode SNESMonitorCancel(SNES snes)
4423: {
4424:   PetscFunctionBegin;
4426:   for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4427:     if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4428:   }
4429:   snes->numbermonitors = 0;
4430:   PetscFunctionReturn(PETSC_SUCCESS);
4431: }

4433: /*@
4434:   SNESSetConvergenceTest - Sets the function that is to be used
4435:   to test for convergence of the nonlinear iterative solution.

4437:   Logically Collective

4439:   Input Parameters:
4440: + snes    - the `SNES` context
4441: . func    - routine to test for convergence
4442: . ctx     - [optional] context for private data for the convergence routine  (may be `NULL`)
4443: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)

4445:   Calling sequence of func:
4446: + snes   - the `SNES` context
4447: . it     - the current iteration number
4448: . xnorm  - the norm of the new solution
4449: . snorm  - the norm of the step
4450: . fnorm  - the norm of the function value
4451: . reason - output, the reason convergence or divergence as declared
4452: - ctx    - the optional convergence test context

4454:   Level: advanced

4456: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4457: @*/
4458: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4459: {
4460:   PetscFunctionBegin;
4462:   if (!func) func = SNESConvergedSkip;
4463:   if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4464:   snes->ops->converged        = func;
4465:   snes->ops->convergeddestroy = destroy;
4466:   snes->cnvP                  = ctx;
4467:   PetscFunctionReturn(PETSC_SUCCESS);
4468: }

4470: /*@
4471:   SNESGetConvergedReason - Gets the reason the `SNES` iteration was stopped, which may be due to convergence, divergence, or stagnation

4473:   Not Collective

4475:   Input Parameter:
4476: . snes - the `SNES` context

4478:   Output Parameter:
4479: . reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` for the individual convergence tests for complete lists

4481:   Options Database Key:
4482: . -snes_converged_reason - prints the reason to standard out

4484:   Level: intermediate

4486:   Note:
4487:   Should only be called after the call the `SNESSolve()` is complete, if it is called earlier it returns the value `SNES__CONVERGED_ITERATING`.

4489: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4490: @*/
4491: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4492: {
4493:   PetscFunctionBegin;
4495:   PetscAssertPointer(reason, 2);
4496:   *reason = snes->reason;
4497:   PetscFunctionReturn(PETSC_SUCCESS);
4498: }

4500: /*@
4501:   SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`

4503:   Not Collective

4505:   Input Parameter:
4506: . snes - the `SNES` context

4508:   Output Parameter:
4509: . strreason - a human readable string that describes `SNES` converged reason

4511:   Level: beginner

4513: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4514: @*/
4515: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char *strreason[])
4516: {
4517:   PetscFunctionBegin;
4519:   PetscAssertPointer(strreason, 2);
4520:   *strreason = SNESConvergedReasons[snes->reason];
4521:   PetscFunctionReturn(PETSC_SUCCESS);
4522: }

4524: /*@
4525:   SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.

4527:   Not Collective

4529:   Input Parameters:
4530: + snes   - the `SNES` context
4531: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4532:             manual pages for the individual convergence tests for complete lists

4534:   Level: developer

4536:   Developer Note:
4537:   Called inside the various `SNESSolve()` implementations

4539: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4540: @*/
4541: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4542: {
4543:   PetscFunctionBegin;
4545:   PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4546:   snes->reason = reason;
4547:   PetscFunctionReturn(PETSC_SUCCESS);
4548: }

4550: /*@
4551:   SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.

4553:   Logically Collective

4555:   Input Parameters:
4556: + snes  - iterative context obtained from `SNESCreate()`
4557: . a     - array to hold history, this array will contain the function norms computed at each step
4558: . its   - integer array holds the number of linear iterations for each solve.
4559: . na    - size of `a` and `its`
4560: - reset - `PETSC_TRUE` indicates each new nonlinear solve resets the history counter to zero,
4561:           else it continues storing new values for new nonlinear solves after the old ones

4563:   Level: intermediate

4565:   Notes:
4566:   If 'a' and 'its' are `NULL` then space is allocated for the history. If 'na' is `PETSC_DECIDE` (or, deprecated, `PETSC_DEFAULT`) then a
4567:   default array of length 1,000 is allocated.

4569:   This routine is useful, e.g., when running a code for purposes
4570:   of accurate performance monitoring, when no I/O should be done
4571:   during the section of code that is being timed.

4573:   If the arrays run out of space after a number of iterations then the later values are not saved in the history

4575: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4576: @*/
4577: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4578: {
4579:   PetscFunctionBegin;
4581:   if (a) PetscAssertPointer(a, 2);
4582:   if (its) PetscAssertPointer(its, 3);
4583:   if (!a) {
4584:     if (na == PETSC_DECIDE) na = 1000;
4585:     PetscCall(PetscCalloc2(na, &a, na, &its));
4586:     snes->conv_hist_alloc = PETSC_TRUE;
4587:   }
4588:   snes->conv_hist       = a;
4589:   snes->conv_hist_its   = its;
4590:   snes->conv_hist_max   = (size_t)na;
4591:   snes->conv_hist_len   = 0;
4592:   snes->conv_hist_reset = reset;
4593:   PetscFunctionReturn(PETSC_SUCCESS);
4594: }

4596: #if PetscDefined(HAVE_MATLAB)
4597:   #include <engine.h> /* MATLAB include file */
4598:   #include <mex.h>    /* MATLAB include file */

4600: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4601: {
4602:   mxArray   *mat;
4603:   PetscReal *ar;

4605:   mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4606:   ar  = (PetscReal *)mxGetData(mat);
4607:   for (PetscInt i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4608:   return mat;
4609: }
4610: #endif

4612: /*@
4613:   SNESGetConvergenceHistory - Gets the arrays used to hold the convergence history.

4615:   Not Collective

4617:   Input Parameter:
4618: . snes - iterative context obtained from `SNESCreate()`

4620:   Output Parameters:
4621: + a   - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4622: . its - integer array holds the number of linear iterations (or
4623:          negative if not converged) for each solve.
4624: - na  - size of `a` and `its`

4626:   Level: intermediate

4628:   Note:
4629:   This routine is useful, e.g., when running a code for purposes
4630:   of accurate performance monitoring, when no I/O should be done
4631:   during the section of code that is being timed.

4633:   Fortran Notes:
4634:   Return the arrays with ``SNESRestoreConvergenceHistory()`

4636:   Use the arguments
4637: .vb
4638:   PetscReal, pointer :: a(:)
4639:   PetscInt, pointer :: its(:)
4640: .ve

4642: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4643: @*/
4644: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4645: {
4646:   PetscFunctionBegin;
4648:   if (a) *a = snes->conv_hist;
4649:   if (its) *its = snes->conv_hist_its;
4650:   if (na) *na = (PetscInt)snes->conv_hist_len;
4651:   PetscFunctionReturn(PETSC_SUCCESS);
4652: }

4654: /*@
4655:   SNESSetUpdate - Sets the general-purpose update function called
4656:   at the beginning of every iteration of the nonlinear solve. Specifically
4657:   it is called just before the Jacobian is "evaluated" and after the function
4658:   evaluation.

4660:   Logically Collective

4662:   Input Parameters:
4663: + snes - The nonlinear solver context
4664: - func - The update function; for calling sequence see `SNESUpdateFn`

4666:   Level: advanced

4668:   Notes:
4669:   This is NOT what one uses to update the ghost points before a function evaluation, that should be done at the beginning of your function provided
4670:   to `SNESSetFunction()`, or `SNESSetPicard()`
4671:   This is not used by most users, and it is intended to provide a general hook that is run
4672:   right before the direction step is computed.

4674:   Users are free to modify the current residual vector,
4675:   the current linearization point, or any other vector associated to the specific solver used.
4676:   If such modifications take place, it is the user responsibility to update all the relevant
4677:   vectors. For example, if one is adjusting the model parameters at each Newton step their code may look like
4678: .vb
4679:   PetscErrorCode update(SNES snes, PetscInt iteration)
4680:   {
4681:     PetscFunctionBeginUser;
4682:     if (iteration > 0) {
4683:       // update the model parameters here
4684:       Vec x,f;
4685:       PetscCall(SNESGetSolution(snes,&x));
4686:       PetcCall(SNESGetFunction(snes,&f,NULL,NULL));
4687:       PetscCall(SNESComputeFunction(snes,x,f));
4688:     }
4689:     PetscFunctionReturn(PETSC_SUCCESS);
4690:   }
4691: .ve

4693:   There are a variety of function hooks one many set that are called at different stages of the nonlinear solution process, see the functions listed below.

4695: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4696:          `SNESMonitorSet()`
4697: @*/
4698: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4699: {
4700:   PetscFunctionBegin;
4702:   snes->ops->update = func;
4703:   PetscFunctionReturn(PETSC_SUCCESS);
4704: }

4706: /*@
4707:   SNESConvergedReasonView - Displays the reason a `SNES` solve converged or diverged to a viewer

4709:   Collective

4711:   Input Parameters:
4712: + snes   - iterative context obtained from `SNESCreate()`
4713: - viewer - the viewer to display the reason

4715:   Options Database Keys:
4716: + -snes_converged_reason          - print reason for converged or diverged, also prints number of iterations
4717: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged

4719:   Level: beginner

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

4725: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4726:           `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4727:           `SNESConvergedReasonViewFromOptions()`,
4728:           `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4729: @*/
4730: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4731: {
4732:   PetscViewerFormat format;
4733:   PetscBool         isAscii;

4735:   PetscFunctionBegin;
4736:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4737:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4738:   if (isAscii) {
4739:     PetscCall(PetscViewerGetFormat(viewer, &format));
4740:     PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4741:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4742:       DM       dm;
4743:       Vec      u;
4744:       PetscDS  prob;
4745:       PetscInt Nf;
4746:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4747:       void    **exactCtx;
4748:       PetscReal error;

4750:       PetscCall(SNESGetDM(snes, &dm));
4751:       PetscCall(SNESGetSolution(snes, &u));
4752:       PetscCall(DMGetDS(dm, &prob));
4753:       PetscCall(PetscDSGetNumFields(prob, &Nf));
4754:       PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4755:       for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4756:       PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4757:       PetscCall(PetscFree2(exactSol, exactCtx));
4758:       if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4759:       else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4760:     }
4761:     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4762:       if (((PetscObject)snes)->prefix) {
4763:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4764:       } else {
4765:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4766:       }
4767:     } else if (snes->reason <= 0) {
4768:       if (((PetscObject)snes)->prefix) {
4769:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4770:       } else {
4771:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4772:       }
4773:     }
4774:     PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)snes)->tablevel + 1));
4775:   }
4776:   PetscFunctionReturn(PETSC_SUCCESS);
4777: }

4779: /*@
4780:   SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4781:   end of the nonlinear solver to display the convergence reason of the nonlinear solver.

4783:   Logically Collective

4785:   Input Parameters:
4786: + snes              - the `SNES` context
4787: . f                 - the `SNESConvergedReason` view function
4788: . vctx              - [optional] user-defined context for private data for the `SNESConvergedReason` view function (use `NULL` if no context is desired)
4789: - reasonviewdestroy - [optional] routine that frees the context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence

4791:   Calling sequence of `f`:
4792: + snes - the `SNES` context
4793: - vctx - [optional] context for private data for the function

4795:   Options Database Keys:
4796: + -snes_converged_reason             - sets a default `SNESConvergedReasonView()`
4797: - -snes_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
4798:                                        calls to `SNESConvergedReasonViewSet()`, but does not cancel those set via the options database.

4800:   Level: intermediate

4802:   Note:
4803:   Several different converged reason view routines may be set by calling
4804:   `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4805:   order in which they were set.

4807: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4808:           `PetscCtxDestroyFn`
4809: @*/
4810: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4811: {
4812:   PetscFunctionBegin;
4814:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4815:     PetscBool identical;

4817:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4818:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4819:   }
4820:   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4821:   snes->reasonview[snes->numberreasonviews]          = f;
4822:   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4823:   snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4824:   PetscFunctionReturn(PETSC_SUCCESS);
4825: }

4827: /*@
4828:   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a `SNESConvergedReason` is to be viewed at the end of `SNESSolve()`
4829:   All the user-provided viewer routines set with `SNESConvergedReasonViewSet()` will be called, if they exist.

4831:   Collective

4833:   Input Parameter:
4834: . snes - the `SNES` object

4836:   Level: advanced

4838:   Note:
4839:   This function has a different API and behavior than `PetscObjectViewFromOptions()`

4841: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4842:           `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4843: @*/
4844: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4845: {
4846:   static PetscBool incall = PETSC_FALSE;

4848:   PetscFunctionBegin;
4849:   if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4850:   incall = PETSC_TRUE;

4852:   /* All user-provided viewers are called first, if they exist. */
4853:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) PetscCall((*snes->reasonview[i])(snes, snes->reasonviewcontext[i]));

4855:   /* Call PETSc default routine if users ask for it */
4856:   if (snes->convergedreasonviewer) {
4857:     PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4858:     PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4859:     PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4860:   }
4861:   incall = PETSC_FALSE;
4862:   PetscFunctionReturn(PETSC_SUCCESS);
4863: }

4865: /*@
4866:   SNESSolve - Solves a nonlinear system $F(x) = b $ associated with a `SNES` object

4868:   Collective

4870:   Input Parameters:
4871: + snes - the `SNES` context
4872: . b    - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4873: - x    - the solution vector.

4875:   Level: beginner

4877:   Note:
4878:   The user should initialize the vector, `x`, with the initial guess
4879:   for the nonlinear solve prior to calling `SNESSolve()` .

4881: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4882:           `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4883:           `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4884: @*/
4885: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4886: {
4887:   PetscBool flg;
4888:   Vec       xcreated = NULL;
4889:   DM        dm;

4891:   PetscFunctionBegin;
4894:   if (x) PetscCheckSameComm(snes, 1, x, 3);
4896:   if (b) PetscCheckSameComm(snes, 1, b, 2);

4898:   /* High level operations using the nonlinear solver */
4899:   {
4900:     PetscViewer       viewer;
4901:     PetscViewerFormat format;
4902:     PetscInt          num;
4903:     PetscBool         flg;
4904:     static PetscBool  incall = PETSC_FALSE;

4906:     if (!incall) {
4907:       /* Estimate the convergence rate of the discretization */
4908:       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4909:       if (flg) {
4910:         PetscConvEst conv;
4911:         DM           dm;
4912:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4913:         PetscInt     Nf;

4915:         incall = PETSC_TRUE;
4916:         PetscCall(SNESGetDM(snes, &dm));
4917:         PetscCall(DMGetNumFields(dm, &Nf));
4918:         PetscCall(PetscCalloc1(Nf, &alpha));
4919:         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4920:         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4921:         PetscCall(PetscConvEstSetFromOptions(conv));
4922:         PetscCall(PetscConvEstSetUp(conv));
4923:         PetscCall(PetscConvEstGetConvRate(conv, alpha));
4924:         PetscCall(PetscViewerPushFormat(viewer, format));
4925:         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4926:         PetscCall(PetscViewerPopFormat(viewer));
4927:         PetscCall(PetscViewerDestroy(&viewer));
4928:         PetscCall(PetscConvEstDestroy(&conv));
4929:         PetscCall(PetscFree(alpha));
4930:         incall = PETSC_FALSE;
4931:       }
4932:       /* Adaptively refine the initial grid */
4933:       num = 1;
4934:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4935:       if (flg) {
4936:         DMAdaptor adaptor;

4938:         incall = PETSC_TRUE;
4939:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4940:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4941:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4942:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4943:         PetscCall(DMAdaptorSetUp(adaptor));
4944:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4945:         PetscCall(DMAdaptorDestroy(&adaptor));
4946:         incall = PETSC_FALSE;
4947:       }
4948:       /* Use grid sequencing to adapt */
4949:       num = 0;
4950:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4951:       if (num) {
4952:         DMAdaptor   adaptor;
4953:         const char *prefix;

4955:         incall = PETSC_TRUE;
4956:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4957:         PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4958:         PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4959:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4960:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4961:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4962:         PetscCall(DMAdaptorSetUp(adaptor));
4963:         PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4964:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4965:         PetscCall(DMAdaptorDestroy(&adaptor));
4966:         incall = PETSC_FALSE;
4967:       }
4968:     }
4969:   }
4970:   if (!x) x = snes->vec_sol;
4971:   if (!x) {
4972:     PetscCall(SNESGetDM(snes, &dm));
4973:     PetscCall(DMCreateGlobalVector(dm, &xcreated));
4974:     x = xcreated;
4975:   }
4976:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));

4978:   for (PetscInt grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4979:   for (PetscInt grid = 0; grid < snes->gridsequence + 1; grid++) {
4980:     /* set solution vector */
4981:     if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4982:     PetscCall(VecDestroy(&snes->vec_sol));
4983:     snes->vec_sol = x;
4984:     PetscCall(SNESGetDM(snes, &dm));

4986:     /* set affine vector if provided */
4987:     PetscCall(PetscObjectReference((PetscObject)b));
4988:     PetscCall(VecDestroy(&snes->vec_rhs));
4989:     snes->vec_rhs = b;

4991:     if (snes->vec_rhs) PetscCheck(snes->vec_func != snes->vec_rhs, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Right hand side vector cannot be function vector");
4992:     PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
4993:     PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
4994:     if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
4995:     PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
4996:     PetscCall(SNESSetUp(snes));

4998:     if (!grid) {
4999:       if (snes->ops->computeinitialguess) PetscCallBack("SNES callback compute initial guess", (*snes->ops->computeinitialguess)(snes, snes->vec_sol, snes->initialguessP));
5000:     }

5002:     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
5003:     PetscCall(SNESResetCounters(snes));
5004:     snes->reason = SNES_CONVERGED_ITERATING;
5005:     PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
5006:     PetscUseTypeMethod(snes, solve);
5007:     PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
5008:     PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
5009:     snes->functiondomainerror  = PETSC_FALSE; /* clear the flag if it has been set */
5010:     snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
5011:     snes->jacobiandomainerror  = PETSC_FALSE; /* clear the flag if it has been set */

5013:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
5014:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

5016:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_test_local_min", NULL, NULL, &flg));
5017:     if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
5018:     /* Call converged reason views. This may involve user-provided viewers as well */
5019:     PetscCall(SNESConvergedReasonViewFromOptions(snes));

5021:     if (snes->errorifnotconverged) {
5022:       if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
5023:       PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
5024:     }
5025:     if (snes->reason < 0) break;
5026:     if (grid < snes->gridsequence) {
5027:       DM  fine;
5028:       Vec xnew;
5029:       Mat interp;

5031:       PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
5032:       PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
5033:       PetscCall(DMGetCoordinatesLocalSetUp(fine));
5034:       PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
5035:       PetscCall(DMCreateGlobalVector(fine, &xnew));
5036:       PetscCall(MatInterpolate(interp, x, xnew));
5037:       PetscCall(DMInterpolate(snes->dm, interp, fine));
5038:       PetscCall(MatDestroy(&interp));
5039:       x = xnew;

5041:       PetscCall(SNESReset(snes));
5042:       PetscCall(SNESSetDM(snes, fine));
5043:       PetscCall(SNESResetFromOptions(snes));
5044:       PetscCall(DMDestroy(&fine));
5045:       PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
5046:     }
5047:   }
5048:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
5049:   PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
5050:   PetscCall(DMMonitor(snes->dm));
5051:   PetscCall(SNESMonitorPauseFinal_Internal(snes));

5053:   PetscCall(VecDestroy(&xcreated));
5054:   PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
5055:   PetscFunctionReturn(PETSC_SUCCESS);
5056: }

5058: /* --------- Internal routines for SNES Package --------- */

5060: /*@
5061:   SNESSetType - Sets the algorithm/method to be used to solve the nonlinear system with the given `SNES`

5063:   Collective

5065:   Input Parameters:
5066: + snes - the `SNES` context
5067: - type - a known method

5069:   Options Database Key:
5070: . -snes_type type - Sets the method; see `SNESType`

5072:   Level: intermediate

5074:   Notes:
5075:   See `SNESType` for available methods (for instance)
5076: +    `SNESNEWTONLS` - Newton's method with line search
5077:   (systems of nonlinear equations)
5078: -    `SNESNEWTONTR` - Newton's method with trust region
5079:   (systems of nonlinear equations)

5081:   Normally, it is best to use the `SNESSetFromOptions()` command and then
5082:   set the `SNES` solver type from the options database rather than by using
5083:   this routine.  Using the options database provides the user with
5084:   maximum flexibility in evaluating the many nonlinear solvers.
5085:   The `SNESSetType()` routine is provided for those situations where it
5086:   is necessary to set the nonlinear solver independently of the command
5087:   line or options database.  This might be the case, for example, when
5088:   the choice of solver changes during the execution of the program,
5089:   and the user's application is taking responsibility for choosing the
5090:   appropriate method.

5092:   Developer Note:
5093:   `SNESRegister()` adds a constructor for a new `SNESType` to `SNESList`, `SNESSetType()` locates
5094:   the constructor in that list and calls it to create the specific object.

5096: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
5097: @*/
5098: PetscErrorCode SNESSetType(SNES snes, SNESType type)
5099: {
5100:   PetscBool match;
5101:   PetscErrorCode (*r)(SNES);

5103:   PetscFunctionBegin;
5105:   PetscAssertPointer(type, 2);

5107:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
5108:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

5110:   PetscCall(PetscFunctionListFind(SNESList, type, &r));
5111:   PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
5112:   /* Destroy the previous private SNES context */
5113:   PetscTryTypeMethod(snes, destroy);
5114:   /* Reinitialize type-specific function pointers in SNESOps structure */
5115:   snes->ops->reset          = NULL;
5116:   snes->ops->setup          = NULL;
5117:   snes->ops->solve          = NULL;
5118:   snes->ops->view           = NULL;
5119:   snes->ops->setfromoptions = NULL;
5120:   snes->ops->destroy        = NULL;

5122:   /* It may happen the user has customized the line search before calling SNESSetType */
5123:   if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));

5125:   /* Reinitialize default parameters */
5126:   PetscCall(SNESParametersInitialize(snes));

5128:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
5129:   snes->setupcalled = PETSC_FALSE;
5130:   PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
5131:   PetscCall((*r)(snes));
5132:   PetscFunctionReturn(PETSC_SUCCESS);
5133: }

5135: /*@
5136:   SNESGetType - Gets the `SNES` method type and name (as a string).

5138:   Not Collective

5140:   Input Parameter:
5141: . snes - nonlinear solver context

5143:   Output Parameter:
5144: . type - `SNES` method (a character string)

5146:   Level: intermediate

5148:   Note:
5149:   `type` should not be retained for later use as it will be an invalid pointer if the `SNESType` of `snes` is changed.

5151: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
5152: @*/
5153: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5154: {
5155:   PetscFunctionBegin;
5157:   PetscAssertPointer(type, 2);
5158:   *type = ((PetscObject)snes)->type_name;
5159:   PetscFunctionReturn(PETSC_SUCCESS);
5160: }

5162: /*@
5163:   SNESSetSolution - Sets the solution vector for use by the `SNES` routines.

5165:   Logically Collective

5167:   Input Parameters:
5168: + snes - the `SNES` context obtained from `SNESCreate()`
5169: - u    - the solution vector

5171:   Level: beginner

5173: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5174: @*/
5175: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5176: {
5177:   DM dm;

5179:   PetscFunctionBegin;
5182:   PetscCall(PetscObjectReference((PetscObject)u));
5183:   PetscCall(VecDestroy(&snes->vec_sol));

5185:   snes->vec_sol = u;

5187:   PetscCall(SNESGetDM(snes, &dm));
5188:   PetscCall(DMShellSetGlobalVector(dm, u));
5189:   PetscFunctionReturn(PETSC_SUCCESS);
5190: }

5192: /*@
5193:   SNESGetSolution - Returns the vector where the approximate solution is
5194:   stored. This is the fine grid solution when using `SNESSetGridSequence()`.

5196:   Not Collective, but `x` is parallel if `snes` is parallel

5198:   Input Parameter:
5199: . snes - the `SNES` context

5201:   Output Parameter:
5202: . x - the solution

5204:   Level: intermediate

5206: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5207: @*/
5208: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5209: {
5210:   PetscFunctionBegin;
5212:   PetscAssertPointer(x, 2);
5213:   *x = snes->vec_sol;
5214:   PetscFunctionReturn(PETSC_SUCCESS);
5215: }

5217: /*@
5218:   SNESGetSolutionUpdate - Returns the vector where the solution update is
5219:   stored.

5221:   Not Collective, but `x` is parallel if `snes` is parallel

5223:   Input Parameter:
5224: . snes - the `SNES` context

5226:   Output Parameter:
5227: . x - the solution update

5229:   Level: advanced

5231: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5232: @*/
5233: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5234: {
5235:   PetscFunctionBegin;
5237:   PetscAssertPointer(x, 2);
5238:   *x = snes->vec_sol_update;
5239:   PetscFunctionReturn(PETSC_SUCCESS);
5240: }

5242: /*@
5243:   SNESGetFunction - Returns the function that defines the nonlinear system set with `SNESSetFunction()`

5245:   Not Collective, but `r` is parallel if `snes` is parallel. Collective if `r` is requested, but has not been created yet.

5247:   Input Parameter:
5248: . snes - the `SNES` context

5250:   Output Parameters:
5251: + r   - the vector that is used to store residuals (or `NULL` if you don't want it)
5252: . f   - the function (or `NULL` if you don't want it);  for calling sequence see `SNESFunctionFn`
5253: - ctx - the function context (or `NULL` if you don't want it)

5255:   Level: advanced

5257:   Note:
5258:   The vector `r` DOES NOT, in general, contain the current value of the `SNES` nonlinear function

5260: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5261: @*/
5262: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5263: {
5264:   DM dm;

5266:   PetscFunctionBegin;
5268:   if (r) {
5269:     if (!snes->vec_func) {
5270:       if (snes->vec_rhs) {
5271:         PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5272:       } else if (snes->vec_sol) {
5273:         PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5274:       } else if (snes->dm) {
5275:         PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5276:       }
5277:     }
5278:     *r = snes->vec_func;
5279:   }
5280:   PetscCall(SNESGetDM(snes, &dm));
5281:   PetscCall(DMSNESGetFunction(dm, f, ctx));
5282:   PetscFunctionReturn(PETSC_SUCCESS);
5283: }

5285: /*@
5286:   SNESGetNGS - Returns the function and context set with `SNESSetNGS()`

5288:   Input Parameter:
5289: . snes - the `SNES` context

5291:   Output Parameters:
5292: + f   - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5293: - ctx - the function context (or `NULL`)

5295:   Level: advanced

5297: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5298: @*/
5299: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5300: {
5301:   DM dm;

5303:   PetscFunctionBegin;
5305:   PetscCall(SNESGetDM(snes, &dm));
5306:   PetscCall(DMSNESGetNGS(dm, f, ctx));
5307:   PetscFunctionReturn(PETSC_SUCCESS);
5308: }

5310: /*@
5311:   SNESSetOptionsPrefix - Sets the prefix used for searching for all
5312:   `SNES` options in the database.

5314:   Logically Collective

5316:   Input Parameters:
5317: + snes   - the `SNES` context
5318: - prefix - the prefix to prepend to all option names

5320:   Level: advanced

5322:   Note:
5323:   A hyphen (-) must NOT be given at the beginning of the prefix name.
5324:   The first character of all runtime options is AUTOMATICALLY the hyphen.

5326: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5327: @*/
5328: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5329: {
5330:   PetscFunctionBegin;
5332:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5333:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5334:   if (snes->linesearch) {
5335:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5336:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5337:   }
5338:   PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5339:   PetscFunctionReturn(PETSC_SUCCESS);
5340: }

5342: /*@
5343:   SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5344:   `SNES` options in the database.

5346:   Logically Collective

5348:   Input Parameters:
5349: + snes   - the `SNES` context
5350: - prefix - the prefix to prepend to all option names

5352:   Level: advanced

5354:   Note:
5355:   A hyphen (-) must NOT be given at the beginning of the prefix name.
5356:   The first character of all runtime options is AUTOMATICALLY the hyphen.

5358: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5359: @*/
5360: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5361: {
5362:   PetscFunctionBegin;
5364:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5365:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5366:   if (snes->linesearch) {
5367:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5368:     PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5369:   }
5370:   PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5371:   PetscFunctionReturn(PETSC_SUCCESS);
5372: }

5374: /*@
5375:   SNESGetOptionsPrefix - Gets the prefix used for searching for all
5376:   `SNES` options in the database.

5378:   Not Collective

5380:   Input Parameter:
5381: . snes - the `SNES` context

5383:   Output Parameter:
5384: . prefix - pointer to the prefix string used

5386:   Level: advanced

5388: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5389: @*/
5390: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5391: {
5392:   PetscFunctionBegin;
5394:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5395:   PetscFunctionReturn(PETSC_SUCCESS);
5396: }

5398: /*@
5399:   SNESRegister - Adds a method to the nonlinear solver package.

5401:   Not Collective

5403:   Input Parameters:
5404: + sname    - name of a new user-defined solver
5405: - function - routine to create method context

5407:   Level: advanced

5409:   Note:
5410:   `SNESRegister()` may be called multiple times to add several user-defined solvers.

5412:   Example Usage:
5413: .vb
5414:    SNESRegister("my_solver", MySolverCreate);
5415: .ve

5417:   Then, your solver can be chosen with the procedural interface via
5418: .vb
5419:   SNESSetType(snes, "my_solver")
5420: .ve
5421:   or at runtime via the option
5422: .vb
5423:   -snes_type my_solver
5424: .ve

5426: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5427: @*/
5428: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5429: {
5430:   PetscFunctionBegin;
5431:   PetscCall(SNESInitializePackage());
5432:   PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5433:   PetscFunctionReturn(PETSC_SUCCESS);
5434: }

5436: /*@
5437:   SNESTestLocalMin - Diagnostic that probes each entry of the current `SNES` solution to check whether the residual norm has a local minimum along the coordinate directions

5439:   Collective

5441:   Input Parameter:
5442: . snes - the `SNES` context

5444:   Level: developer

5446:   Note:
5447:   Currently intended for serial runs. For each degree of freedom it perturbs the solution by increasing amounts and prints the resulting `SNESComputeFunction()` residual norms so the user can inspect local behavior.

5449: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESComputeFunction()`
5450: @*/
5451: PetscErrorCode SNESTestLocalMin(SNES snes)
5452: {
5453:   PetscInt    N, i, j;
5454:   Vec         u, uh, fh;
5455:   PetscScalar value;
5456:   PetscReal   norm;

5458:   PetscFunctionBegin;
5459:   PetscCall(SNESGetSolution(snes, &u));
5460:   PetscCall(VecDuplicate(u, &uh));
5461:   PetscCall(VecDuplicate(u, &fh));

5463:   /* currently only works for sequential */
5464:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5465:   PetscCall(VecGetSize(u, &N));
5466:   for (i = 0; i < N; i++) {
5467:     PetscCall(VecCopy(u, uh));
5468:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5469:     for (j = -10; j < 11; j++) {
5470:       value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5471:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5472:       PetscCall(SNESComputeFunction(snes, uh, fh));
5473:       PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5474:       PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "       j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5475:       value = -value;
5476:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5477:     }
5478:   }
5479:   PetscCall(VecDestroy(&uh));
5480:   PetscCall(VecDestroy(&fh));
5481:   PetscFunctionReturn(PETSC_SUCCESS);
5482: }

5484: /*@
5485:   SNESGetLineSearch - Returns the line search associated with the `SNES`.

5487:   Not Collective

5489:   Input Parameter:
5490: . snes - iterative context obtained from `SNESCreate()`

5492:   Output Parameter:
5493: . linesearch - linesearch context

5495:   Level: beginner

5497:   Notes:
5498:   It creates a default line search instance which can be configured as needed in case it has not been already set with `SNESSetLineSearch()`.

5500:   You can also use the options database keys `-snes_linesearch_*` to configure the line search. See `SNESLineSearchSetFromOptions()` for the possible options.

5502: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5503: @*/
5504: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5505: {
5506:   const char *optionsprefix;

5508:   PetscFunctionBegin;
5510:   PetscAssertPointer(linesearch, 2);
5511:   if (!snes->linesearch) {
5512:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5513:     PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5514:     PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5515:     PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5516:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5517:   }
5518:   *linesearch = snes->linesearch;
5519:   PetscFunctionReturn(PETSC_SUCCESS);
5520: }

5522: /*@
5523:   SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5524:   computing relative tolerance for linear solvers within an inexact
5525:   Newton method.

5527:   Logically Collective

5529:   Input Parameters:
5530: + snes - `SNES` context
5531: - flag - `PETSC_TRUE` or `PETSC_FALSE`

5533:   Options Database Keys:
5534: + -snes_ksp_ew                     - use Eisenstat-Walker method for determining linear system convergence
5535: . -snes_ksp_ew_version ver         - version of  Eisenstat-Walker method
5536: . -snes_ksp_ew_rtol0 rtol0         - Sets rtol0
5537: . -snes_ksp_ew_rtolmax rtolmax     - Sets rtolmax
5538: . -snes_ksp_ew_gamma gamma         - Sets gamma
5539: . -snes_ksp_ew_alpha alpha         - Sets alpha
5540: . -snes_ksp_ew_alpha2 alpha2       - Sets alpha2
5541: - -snes_ksp_ew_threshold threshold - Sets threshold

5543:   Level: advanced

5545:   Note:
5546:   The default is to use a constant relative tolerance for
5547:   the inner linear solvers.  Alternatively, one can use the
5548:   Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5549:   is reset at each Newton iteration according progress of the nonlinear
5550:   solver.

5552: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5553: @*/
5554: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5555: {
5556:   PetscFunctionBegin;
5559:   snes->ksp_ewconv = flag;
5560:   PetscFunctionReturn(PETSC_SUCCESS);
5561: }

5563: /*@
5564:   SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5565:   for computing relative tolerance for linear solvers within an
5566:   inexact Newton method.

5568:   Not Collective

5570:   Input Parameter:
5571: . snes - `SNES` context

5573:   Output Parameter:
5574: . flag - `PETSC_TRUE` or `PETSC_FALSE`

5576:   Level: advanced

5578: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5579: @*/
5580: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5581: {
5582:   PetscFunctionBegin;
5584:   PetscAssertPointer(flag, 2);
5585:   *flag = snes->ksp_ewconv;
5586:   PetscFunctionReturn(PETSC_SUCCESS);
5587: }

5589: /*@
5590:   SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5591:   convergence criteria for the linear solvers within an inexact
5592:   Newton method.

5594:   Logically Collective

5596:   Input Parameters:
5597: + snes      - `SNES` context
5598: . version   - version 1, 2 (default is 2), 3 or 4
5599: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5600: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5601: . gamma     - multiplicative factor for version 2 rtol computation
5602:              (0 <= gamma2 <= 1)
5603: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5604: . alpha2    - power for safeguard
5605: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5607:   Level: advanced

5609:   Notes:
5610:   Version 3 was contributed by Luis Chacon, June 2006.

5612:   Use `PETSC_CURRENT` to retain the default for any of the parameters.

5614: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5615: @*/
5616: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5617: {
5618:   SNESKSPEW *kctx;

5620:   PetscFunctionBegin;
5622:   kctx = (SNESKSPEW *)snes->kspconvctx;
5623:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");

5632:   if (version != PETSC_CURRENT) kctx->version = version;
5633:   if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5634:   if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5635:   if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5636:   if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5637:   if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5638:   if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;

5640:   PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1 to 4 are supported: %" PetscInt_FMT, kctx->version);
5641:   PetscCheck(kctx->rtol_0 >= 0.0 && kctx->rtol_0 < 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "0.0 <= rtol_0 < 1.0: %g", (double)kctx->rtol_0);
5642:   PetscCheck(kctx->rtol_max >= 0.0 && kctx->rtol_max < 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "0.0 <= rtol_max (%g) < 1.0", (double)kctx->rtol_max);
5643:   PetscCheck(kctx->gamma >= 0.0 && kctx->gamma <= 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "0.0 <= gamma (%g) <= 1.0", (double)kctx->gamma);
5644:   PetscCheck(kctx->alpha > 1.0 && kctx->alpha <= 2.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "1.0 < alpha (%g) <= 2.0", (double)kctx->alpha);
5645:   PetscCheck(kctx->threshold > 0.0 && kctx->threshold < 1.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "0.0 < threshold (%g) < 1.0", (double)kctx->threshold);
5646:   PetscFunctionReturn(PETSC_SUCCESS);
5647: }

5649: /*@
5650:   SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5651:   convergence criteria for the linear solvers within an inexact
5652:   Newton method.

5654:   Not Collective

5656:   Input Parameter:
5657: . snes - `SNES` context

5659:   Output Parameters:
5660: + version   - version 1, 2 (default is 2), 3 or 4
5661: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5662: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5663: . gamma     - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5664: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5665: . alpha2    - power for safeguard
5666: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5668:   Level: advanced

5670: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5671: @*/
5672: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5673: {
5674:   SNESKSPEW *kctx;

5676:   PetscFunctionBegin;
5678:   kctx = (SNESKSPEW *)snes->kspconvctx;
5679:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5680:   if (version) *version = kctx->version;
5681:   if (rtol_0) *rtol_0 = kctx->rtol_0;
5682:   if (rtol_max) *rtol_max = kctx->rtol_max;
5683:   if (gamma) *gamma = kctx->gamma;
5684:   if (alpha) *alpha = kctx->alpha;
5685:   if (alpha2) *alpha2 = kctx->alpha2;
5686:   if (threshold) *threshold = kctx->threshold;
5687:   PetscFunctionReturn(PETSC_SUCCESS);
5688: }

5690: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5691: {
5692:   SNES       snes = (SNES)ctx;
5693:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5694:   PetscReal  rtol = PETSC_CURRENT, stol;

5696:   PetscFunctionBegin;
5697:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5698:   if (!snes->iter) {
5699:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5700:     PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5701:   } else {
5702:     PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5703:     if (kctx->version == 1) {
5704:       rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5705:       stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5706:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5707:     } else if (kctx->version == 2) {
5708:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5709:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5710:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5711:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5712:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5713:       /* safeguard: avoid sharp decrease of rtol */
5714:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5715:       stol = PetscMax(rtol, stol);
5716:       rtol = PetscMin(kctx->rtol_0, stol);
5717:       /* safeguard: avoid oversolving */
5718:       stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5719:       stol = PetscMax(rtol, stol);
5720:       rtol = PetscMin(kctx->rtol_0, stol);
5721:     } else /* if (kctx->version == 4) */ {
5722:       /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5723:       PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5724:       PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5725:       PetscReal rk   = ared / pred;
5726:       if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5727:       else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5728:       else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5729:       else rtol = kctx->v4_m2 * kctx->rtol_last;

5731:       if (kctx->rtol_last_2 > kctx->v4_m3 && kctx->rtol_last > kctx->v4_m3 && kctx->rk_last_2 < kctx->v4_p1 && kctx->rk_last < kctx->v4_p1) rtol = kctx->v4_m4 * kctx->rtol_last;
5732:       kctx->rtol_last_2 = kctx->rtol_last;
5733:       kctx->rk_last_2   = kctx->rk_last;
5734:       kctx->rk_last     = rk;
5735:     }
5736:   }
5737:   /* safeguard: avoid rtol greater than rtol_max */
5738:   rtol = PetscMin(rtol, kctx->rtol_max);
5739:   PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5740:   PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5741:   PetscFunctionReturn(PETSC_SUCCESS);
5742: }

5744: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5745: {
5746:   SNES       snes = (SNES)ctx;
5747:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5748:   PCSide     pcside;
5749:   Vec        lres;

5751:   PetscFunctionBegin;
5752:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5753:   PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5754:   kctx->norm_last = snes->norm;
5755:   if (kctx->version == 1 || kctx->version == 4) {
5756:     PC        pc;
5757:     PetscBool getRes;

5759:     PetscCall(KSPGetPC(ksp, &pc));
5760:     PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5761:     if (!getRes) {
5762:       KSPNormType normtype;

5764:       PetscCall(KSPGetNormType(ksp, &normtype));
5765:       getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5766:     }
5767:     PetscCall(KSPGetPCSide(ksp, &pcside));
5768:     if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5769:       PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5770:     } else {
5771:       /* KSP residual is preconditioned residual */
5772:       /* compute true linear residual norm */
5773:       Mat J;
5774:       PetscCall(KSPGetOperators(ksp, &J, NULL));
5775:       PetscCall(VecDuplicate(b, &lres));
5776:       PetscCall(MatMult(J, x, lres));
5777:       PetscCall(VecAYPX(lres, -1.0, b));
5778:       PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5779:       PetscCall(VecDestroy(&lres));
5780:     }
5781:   }
5782:   PetscFunctionReturn(PETSC_SUCCESS);
5783: }

5785: #include <petsc/private/kspimpl.h>
5786: /*@
5787:   SNESGetKSP - Returns the `KSP` context for a `SNES` solver.

5789:   Not Collective, but if `snes` is parallel, then `ksp` is parallel

5791:   Input Parameter:
5792: . snes - the `SNES` context

5794:   Output Parameter:
5795: . ksp - the `KSP` context

5797:   Level: beginner

5799:   Notes:
5800:   The user can then directly manipulate the `KSP` context to set various
5801:   options, etc.  Likewise, the user can then extract and manipulate the
5802:   `PC` contexts as well.

5804:   Some `SNESType`s do not use a `KSP` but a `KSP` is still returned by this function, changes to that `KSP` will have no effect.

5806: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5807: @*/
5808: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5809: {
5810:   PetscFunctionBegin;
5812:   PetscAssertPointer(ksp, 2);

5814:   if (!snes->ksp) {
5815:     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5816:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));

5818:     snes->ksp->presolve_ew  = KSPPreSolve_SNESEW;
5819:     snes->ksp->prectx_ew    = snes;
5820:     snes->ksp->postsolve_ew = KSPPostSolve_SNESEW;
5821:     snes->ksp->postctx_ew   = snes;

5823:     PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5824:     PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5825:   }
5826:   *ksp = snes->ksp;
5827:   PetscFunctionReturn(PETSC_SUCCESS);
5828: }

5830: #include <petsc/private/dmimpl.h>
5831: /*@
5832:   SNESSetDM - Sets the `DM` that may be used by some `SNES` nonlinear solvers or their underlying preconditioners

5834:   Logically Collective

5836:   Input Parameters:
5837: + snes - the nonlinear solver context
5838: - dm   - the `DM`, cannot be `NULL`

5840:   Level: intermediate

5842:   Note:
5843:   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
5844:   even when not using interfaces like `DMSNESSetFunction()`.  Use `DMClone()` to get a distinct `DM` when solving different
5845:   problems using the same function space.

5847: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5848: @*/
5849: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5850: {
5851:   KSP    ksp;
5852:   DMSNES sdm;
5853:   DM     odm;

5855:   PetscFunctionBegin;
5858:   PetscCall(PetscObjectReference((PetscObject)dm));
5859:   odm = snes->dm;
5860:   if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5861:     if (snes->dm->dmsnes && !dm->dmsnes) {
5862:       PetscCall(DMCopyDMSNES(snes->dm, dm));
5863:       PetscCall(DMGetDMSNES(snes->dm, &sdm));
5864:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5865:     }
5866:     PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5867:     PetscCall(DMDestroy(&snes->dm));
5868:   }
5869:   snes->dm     = dm;
5870:   snes->dmAuto = PETSC_FALSE;

5872:   PetscCall(SNESGetKSP(snes, &ksp));
5873:   PetscCall(KSPSetDM(ksp, dm));
5874:   PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5875:   /* Propagate DM to NPC if npc does not have one yet or
5876:      if it has the same DM SNES had before (like for gridsequencing) */
5877:   if (snes->npc && (!snes->npc->dm || snes->npc->dm == odm)) PetscCall(SNESSetDM(snes->npc, snes->dm));
5878:   PetscFunctionReturn(PETSC_SUCCESS);
5879: }

5881: /*@
5882:   SNESGetDM - Gets the `DM` that may be used by some `SNES` nonlinear solvers/preconditioners

5884:   Not Collective but `dm` obtained is parallel on `snes`

5886:   Input Parameter:
5887: . snes - the `SNES` context

5889:   Output Parameter:
5890: . dm - the `DM`

5892:   Level: intermediate

5894: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5895: @*/
5896: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5897: {
5898:   PetscFunctionBegin;
5900:   if (!snes->dm) {
5901:     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5902:     snes->dmAuto = PETSC_TRUE;
5903:   }
5904:   *dm = snes->dm;
5905:   PetscFunctionReturn(PETSC_SUCCESS);
5906: }

5908: /*@
5909:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5911:   Collective

5913:   Input Parameters:
5914: + snes - iterative context obtained from `SNESCreate()`
5915: - npc  - the `SNES` nonlinear preconditioner object

5917:   Level: developer

5919:   Notes:
5920:   This is rarely used, rather use `SNESGetNPC()` to retrieve the preconditioner and configure it using the API.

5922:   Only some `SNESType` can use a nonlinear preconditioner

5924: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5925: @*/
5926: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5927: {
5928:   PetscFunctionBegin;
5931:   PetscCheckSameComm(snes, 1, npc, 2);
5932:   PetscCall(PetscObjectReference((PetscObject)npc));
5933:   PetscCall(SNESDestroy(&snes->npc));
5934:   snes->npc = npc;
5935:   PetscFunctionReturn(PETSC_SUCCESS);
5936: }

5938: /*@
5939:   SNESGetNPC - Gets a nonlinear preconditioning solver SNES` to be used to precondition the original nonlinear solver.

5941:   Collective the first time it is called if the `SNES` has no NPC set.

5943:   Input Parameter:
5944: . snes - iterative context obtained from `SNESCreate()`

5946:   Output Parameter:
5947: . npc - the `SNES` preconditioner context

5949:   Options Database Key:
5950: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner

5952:   Level: advanced

5954:   Notes:
5955:   If a `SNES` was previously set with `SNESSetNPC()` then that object is returned, otherwise a new `SNES` object is created that will
5956:   be used as the nonlinear preconditioner for the current `SNES` if no nonlinear preconditioner is present.

5958:   The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5959:   `SNES`. These may be overwritten if needed by calling `SNESSetDM()` on the nonlinear preconditioner followed by `SNESSetFunction()`
5960:   and `SNESSetJacobian()`.

5962:   The default preconditioner uses the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration.

5964: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5965: @*/
5966: PetscErrorCode SNESGetNPC(SNES snes, SNES *npc)
5967: {
5968:   const char *optionsprefix;

5970:   PetscFunctionBegin;
5972:   PetscAssertPointer(npc, 2);
5973:   if (!snes->npc) {
5974:     PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5975:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5976:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5977:     PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5978:     PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5979:     PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5980:     PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_DEFAULT));

5982:     /* default to 1 iteration */
5983:     PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
5984:   }
5985:   *npc = snes->npc;
5986:   PetscFunctionReturn(PETSC_SUCCESS);
5987: }

5989: /*@
5990:   SNESHasNPC - Returns whether a nonlinear preconditioner is associated with the given `SNES`

5992:   Not Collective

5994:   Input Parameter:
5995: . snes - iterative context obtained from `SNESCreate()`

5997:   Output Parameter:
5998: . has_npc - whether the `SNES` has a nonlinear preconditioner or not

6000:   Level: developer

6002: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
6003: @*/
6004: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
6005: {
6006:   PetscFunctionBegin;
6008:   PetscAssertPointer(has_npc, 2);
6009:   *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
6010:   PetscFunctionReturn(PETSC_SUCCESS);
6011: }

6013: /*@
6014:   SNESSetNPCSide - Sets the nonlinear preconditioning side used by the nonlinear preconditioner inside `SNES`.

6016:   Logically Collective

6018:   Input Parameter:
6019: . snes - iterative context obtained from `SNESCreate()`

6021:   Output Parameter:
6022: . side - the preconditioning side, where side is one of
6023: .vb
6024:       PC_LEFT  - left preconditioning
6025:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
6026: .ve

6028:   Options Database Key:
6029: . -snes_npc_side (right|left) - nonlinear preconditioner side

6031:   Level: intermediate

6033:   Note:
6034:   `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.

6036: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6037: @*/
6038: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
6039: {
6040:   PetscFunctionBegin;
6043:   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
6044:   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
6045:   snes->npcside = side;
6046:   PetscFunctionReturn(PETSC_SUCCESS);
6047: }

6049: /*@
6050:   SNESGetNPCSide - Gets the preconditioning side used by the nonlinear preconditioner inside `SNES`.

6052:   Not Collective

6054:   Input Parameter:
6055: . snes - iterative context obtained from `SNESCreate()`

6057:   Output Parameter:
6058: . side - the preconditioning side, where side is one of
6059: .vb
6060:       `PC_LEFT` - left preconditioning
6061:       `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
6062: .ve

6064:   Level: intermediate

6066: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6067: @*/
6068: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
6069: {
6070:   PetscFunctionBegin;
6072:   PetscAssertPointer(side, 2);
6073:   *side = snes->npcside;
6074:   PetscFunctionReturn(PETSC_SUCCESS);
6075: }

6077: /*@
6078:   SNESSetLineSearch - Sets the `SNESLineSearch` to be used for a given `SNES`

6080:   Collective

6082:   Input Parameters:
6083: + snes       - iterative context obtained from `SNESCreate()`
6084: - linesearch - the linesearch object

6086:   Level: developer

6088:   Note:
6089:   This is almost never used, rather one uses `SNESGetLineSearch()` to retrieve the line search and set options on it
6090:   to configure it using the API).

6092: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
6093: @*/
6094: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
6095: {
6096:   PetscFunctionBegin;
6099:   PetscCheckSameComm(snes, 1, linesearch, 2);
6100:   PetscCall(PetscObjectReference((PetscObject)linesearch));
6101:   PetscCall(SNESLineSearchDestroy(&snes->linesearch));

6103:   snes->linesearch = linesearch;
6104:   PetscFunctionReturn(PETSC_SUCCESS);
6105: }