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: /*@C
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 {
645:       KSP       ksp;
646:       PC        pc;
647:       PetscBool match;

649:       PetscCall(SNESSetJacobian(snes, J, J, MatMFFDComputeJacobian, NULL));
650:       /* Force no preconditioner */
651:       PetscCall(SNESGetKSP(snes, &ksp));
652:       PetscCall(KSPGetPC(ksp, &pc));
653:       PetscCall(PetscObjectTypeCompareAny((PetscObject)pc, &match, PCSHELL, PCH2OPUS, ""));
654:       if (!match) {
655:         PetscCall(PetscInfo(snes, "Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
656:         PetscCall(PCSetType(pc, PCNONE));
657:       }
658:     }
659:   }
660:   PetscCall(MatDestroy(&J));
661:   PetscFunctionReturn(PETSC_SUCCESS);
662: }

664: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine, Mat Restrict, Vec Rscale, Mat Inject, DM dmcoarse, PetscCtx ctx)
665: {
666:   SNES snes = (SNES)ctx;
667:   Vec  Xfine, Xfine_named = NULL, Xcoarse;

669:   PetscFunctionBegin;
670:   if (PetscLogPrintInfo) {
671:     PetscInt finelevel, coarselevel, fineclevel, coarseclevel;
672:     PetscCall(DMGetRefineLevel(dmfine, &finelevel));
673:     PetscCall(DMGetCoarsenLevel(dmfine, &fineclevel));
674:     PetscCall(DMGetRefineLevel(dmcoarse, &coarselevel));
675:     PetscCall(DMGetCoarsenLevel(dmcoarse, &coarseclevel));
676:     PetscCall(PetscInfo(dmfine, "Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n", finelevel, fineclevel, coarselevel, coarseclevel));
677:   }
678:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
679:   else {
680:     PetscCall(DMGetNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
681:     Xfine = Xfine_named;
682:   }
683:   PetscCall(DMGetNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
684:   if (Inject) {
685:     PetscCall(MatRestrict(Inject, Xfine, Xcoarse));
686:   } else {
687:     PetscCall(MatRestrict(Restrict, Xfine, Xcoarse));
688:     PetscCall(VecPointwiseMult(Xcoarse, Xcoarse, Rscale));
689:   }
690:   PetscCall(DMRestoreNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
691:   if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
692:   PetscFunctionReturn(PETSC_SUCCESS);
693: }

695: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm, DM dmc, PetscCtx ctx)
696: {
697:   PetscFunctionBegin;
698:   PetscCall(DMCoarsenHookAdd(dmc, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, ctx));
699:   PetscFunctionReturn(PETSC_SUCCESS);
700: }

702: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
703:  * safely call SNESGetDM() in their residual evaluation routine. */
704: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp, Mat A, Mat B, PetscCtx ctx)
705: {
706:   SNES            snes = (SNES)ctx;
707:   DMSNES          sdm;
708:   Vec             X, Xnamed = NULL;
709:   DM              dmsave;
710:   void           *ctxsave;
711:   SNESJacobianFn *jac = NULL;

713:   PetscFunctionBegin;
714:   dmsave = snes->dm;
715:   PetscCall(KSPGetDM(ksp, &snes->dm));
716:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
717:   else {
718:     PetscBool has;

720:     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
721:     PetscCall(DMHasNamedGlobalVector(snes->dm, "SNESVecSol", &has));
722:     PetscCheck(has, PetscObjectComm((PetscObject)snes->dm), PETSC_ERR_PLIB, "Missing SNESVecSol");
723:     PetscCall(DMGetNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
724:     X = Xnamed;
725:     PetscCall(SNESGetJacobian(snes, NULL, NULL, &jac, &ctxsave));
726:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
727:     if (jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, SNESComputeJacobianDefaultColor, NULL));
728:   }

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

737:     snes->vec_rhs = NULL;
738:     PetscCall(DMGetGlobalVector(snes->dm, &F));
739:     PetscCall(SNESComputeFunction(snes, X, F));
740:     PetscCall(DMRestoreGlobalVector(snes->dm, &F));
741:     snes->vec_rhs = saverhs;
742:     snes->nfuncs--; /* Do not log coarser level evaluations */
743:   }
744:   /* Make sure KSP DM has the Jacobian computation routine */
745:   if (!sdm->ops->computejacobian) PetscCall(DMCopyDMSNES(dmsave, snes->dm));
746:   PetscCall(SNESComputeJacobian(snes, X, A, B)); /* cannot handle previous SNESSetJacobianDomainError() calls */

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

751:   if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
752:   snes->dm = dmsave;
753:   PetscFunctionReturn(PETSC_SUCCESS);
754: }

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

759:   Collective

761:   Input Parameter:
762: . snes - `SNES` object to configure

764:   Level: developer

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

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

774: .seealso: [](ch_snes), `SNES`, `SNESSetUp()`
775: @*/
776: PetscErrorCode SNESSetUpMatrices(SNES snes)
777: {
778:   DM     dm;
779:   DMSNES sdm;

781:   PetscFunctionBegin;
782:   PetscCall(SNESGetDM(snes, &dm));
783:   PetscCall(DMGetDMSNES(dm, &sdm));
784:   if (!snes->jacobian && snes->mf && !snes->mf_operator && !snes->jacobian_pre) {
785:     Mat   J;
786:     void *functx;
787:     PetscCall(MatCreateSNESMF(snes, &J));
788:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
789:     PetscCall(MatSetFromOptions(J));
790:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
791:     PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
792:     PetscCall(MatDestroy(&J));
793:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
794:     Mat J, B;
795:     PetscCall(MatCreateSNESMF(snes, &J));
796:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
797:     PetscCall(MatSetFromOptions(J));
798:     PetscCall(DMCreateMatrix(snes->dm, &B));
799:     /* sdm->computejacobian was already set to reach here */
800:     PetscCall(SNESSetJacobian(snes, J, B, NULL, NULL));
801:     PetscCall(MatDestroy(&J));
802:     PetscCall(MatDestroy(&B));
803:   } else if (!snes->jacobian_pre) {
804:     PetscDS   prob;
805:     Mat       J, B;
806:     PetscBool hasPrec = PETSC_FALSE;

808:     J = snes->jacobian;
809:     PetscCall(DMGetDS(dm, &prob));
810:     if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
811:     if (!J && hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
812:     else PetscCall(PetscObjectReference((PetscObject)J));
813:     PetscCall(DMCreateMatrix(snes->dm, &B));
814:     PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
815:     PetscCall(MatDestroy(&J));
816:     PetscCall(MatDestroy(&B));
817:   }
818:   {
819:     KSP ksp;
820:     PetscCall(SNESGetKSP(snes, &ksp));
821:     PetscCall(KSPSetComputeOperators(ksp, KSPComputeOperators_SNES, snes));
822:     PetscCall(DMCoarsenHookAdd(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
823:   }
824:   PetscFunctionReturn(PETSC_SUCCESS);
825: }

827: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);

829: static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
830: {
831:   PetscFunctionBegin;
832:   if (!snes->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
833:   PetscCall(PetscMonitorPauseFinal_Internal(snes->numbermonitors, snes->monitorcontext));
834:   PetscFunctionReturn(PETSC_SUCCESS);
835: }

837: /*@C
838:   SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

840:   Collective

842:   Input Parameters:
843: + snes         - `SNES` object you wish to monitor
844: . name         - the monitor type one is seeking
845: . help         - message indicating what monitoring is done
846: . manual       - manual page for the monitor
847: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
848: - 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

850:   Calling sequence of `monitor`:
851: + snes - the nonlinear solver context
852: . it   - the current iteration
853: . r    - the current function norm
854: - vf   - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use

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

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

863:   Level: advanced

865: .seealso: [](ch_snes), `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
866:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
867:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
868:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
869:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
870:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
871:           `PetscOptionsFList()`, `PetscOptionsEList()`
872: @*/
873: 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))
874: {
875:   PetscViewer       viewer;
876:   PetscViewerFormat format;
877:   PetscBool         flg;

879:   PetscFunctionBegin;
880:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, name, &viewer, &format, &flg));
881:   if (flg) {
882:     PetscViewerAndFormat *vf;
883:     PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
884:     PetscCall(PetscViewerDestroy(&viewer));
885:     if (monitorsetup) PetscCall((*monitorsetup)(snes, vf));
886:     PetscCall(SNESMonitorSet(snes, (PetscErrorCode (*)(SNES, PetscInt, PetscReal, PetscCtx))monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
887:   }
888:   PetscFunctionReturn(PETSC_SUCCESS);
889: }

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

895:   PetscFunctionBegin;
896:   PetscOptionsBegin(comm, prefix, "Eisenstat and Walker type forcing options", "KSP");
897:   PetscCall(PetscOptionsInt("-ksp_ew_version", "Version 1, 2 or 3", api, kctx->version, &kctx->version, NULL));
898:   PetscCall(PetscOptionsReal("-ksp_ew_rtol0", "0 <= rtol0 < 1", api, kctx->rtol_0, &kctx->rtol_0, NULL));
899:   kctx->rtol_max = PetscMax(kctx->rtol_0, kctx->rtol_max);
900:   PetscCall(PetscOptionsReal("-ksp_ew_rtolmax", "0 <= rtolmax < 1", api, kctx->rtol_max, &kctx->rtol_max, NULL));
901:   PetscCall(PetscOptionsReal("-ksp_ew_gamma", "0 <= gamma <= 1", api, kctx->gamma, &kctx->gamma, NULL));
902:   PetscCall(PetscOptionsReal("-ksp_ew_alpha", "1 < alpha <= 2", api, kctx->alpha, &kctx->alpha, NULL));
903:   PetscCall(PetscOptionsReal("-ksp_ew_alpha2", "alpha2", NULL, kctx->alpha2, &kctx->alpha2, NULL));
904:   PetscCall(PetscOptionsReal("-ksp_ew_threshold", "0 < threshold < 1", api, kctx->threshold, &kctx->threshold, NULL));
905:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p1", "p1", NULL, kctx->v4_p1, &kctx->v4_p1, NULL));
906:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p2", "p2", NULL, kctx->v4_p2, &kctx->v4_p2, NULL));
907:   PetscCall(PetscOptionsReal("-ksp_ew_v4_p3", "p3", NULL, kctx->v4_p3, &kctx->v4_p3, NULL));
908:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m1", "Scaling when rk-1 in [p2,p3)", NULL, kctx->v4_m1, &kctx->v4_m1, NULL));
909:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m2", "Scaling when rk-1 in [p3,+infty)", NULL, kctx->v4_m2, &kctx->v4_m2, NULL));
910:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m3", "Threshold for successive rtol (0.1 in Eq.7)", NULL, kctx->v4_m3, &kctx->v4_m3, NULL));
911:   PetscCall(PetscOptionsReal("-ksp_ew_v4_m4", "Adaptation scaling (0.5 in Eq.7)", NULL, kctx->v4_m4, &kctx->v4_m4, NULL));
912:   PetscOptionsEnd();
913:   PetscFunctionReturn(PETSC_SUCCESS);
914: }

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

919:   Collective

921:   Input Parameter:
922: . snes - the `SNES` context

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

959:   Options Database Keys for Eisenstat-Walker method:
960: + -snes_ksp_ew                     - use Eisenstat-Walker method for determining linear system convergence
961: . -snes_ksp_ew_version ver         - version of  Eisenstat-Walker method
962: . -snes_ksp_ew_rtol0 rtol0         - Sets rtol0
963: . -snes_ksp_ew_rtolmax rtolmax     - Sets rtolmax
964: . -snes_ksp_ew_gamma gamma         - Sets gamma
965: . -snes_ksp_ew_alpha alpha         - Sets alpha
966: . -snes_ksp_ew_alpha2 alpha2       - Sets alpha2
967: - -snes_ksp_ew_threshold threshold - Sets threshold

969:   Level: beginner

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

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

978: .seealso: [](ch_snes), `SNESType`, `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`, `MatCreateSNESMF()`, `MatFDColoring`
979: @*/
980: PetscErrorCode SNESSetFromOptions(SNES snes)
981: {
982:   PetscBool   flg, pcset, persist, set;
983:   PetscInt    i, indx, lag, grids, max_its, max_funcs;
984:   const char *deft        = SNESNEWTONLS;
985:   const char *convtests[] = {"default", "skip", "correct_pressure"};
986:   SNESKSPEW  *kctx        = NULL;
987:   char        type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
988:   PCSide      pcside;
989:   const char *optionsprefix;
990:   PetscReal   rtol, abstol, stol;

992:   PetscFunctionBegin;
994:   PetscCall(SNESRegisterAll());
995:   PetscObjectOptionsBegin((PetscObject)snes);
996:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
997:   PetscCall(PetscOptionsFList("-snes_type", "Nonlinear solver method", "SNESSetType", SNESList, deft, type, 256, &flg));
998:   if (flg) PetscCall(SNESSetType(snes, type));
999:   else if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, deft));

1001:   abstol    = snes->abstol;
1002:   rtol      = snes->rtol;
1003:   stol      = snes->stol;
1004:   max_its   = snes->max_its;
1005:   max_funcs = snes->max_funcs;
1006:   PetscCall(PetscOptionsReal("-snes_rtol", "Stop if decrease in function norm less than", "SNESSetTolerances", snes->rtol, &rtol, NULL));
1007:   PetscCall(PetscOptionsReal("-snes_atol", "Stop if function norm less than", "SNESSetTolerances", snes->abstol, &abstol, NULL));
1008:   PetscCall(PetscOptionsReal("-snes_stol", "Stop if step length less than", "SNESSetTolerances", snes->stol, &stol, NULL));
1009:   PetscCall(PetscOptionsInt("-snes_max_it", "Maximum iterations", "SNESSetTolerances", snes->max_its, &max_its, NULL));
1010:   PetscCall(PetscOptionsInt("-snes_max_funcs", "Maximum function evaluations", "SNESSetTolerances", snes->max_funcs, &max_funcs, NULL));
1011:   PetscCall(SNESSetTolerances(snes, abstol, rtol, stol, max_its, max_funcs));

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

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

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

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

1026:   PetscCall(PetscOptionsInt("-snes_lag_preconditioner", "How often to rebuild preconditioner", "SNESSetLagPreconditioner", snes->lagpreconditioner, &lag, &flg));
1027:   if (flg) {
1028:     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");
1029:     PetscCall(SNESSetLagPreconditioner(snes, lag));
1030:   }
1031:   PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists", "Preconditioner lagging through multiple SNES solves", "SNESSetLagPreconditionerPersists", snes->lagjac_persist, &persist, &flg));
1032:   if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes, persist));
1033:   PetscCall(PetscOptionsInt("-snes_lag_jacobian", "How often to rebuild Jacobian", "SNESSetLagJacobian", snes->lagjacobian, &lag, &flg));
1034:   if (flg) {
1035:     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");
1036:     PetscCall(SNESSetLagJacobian(snes, lag));
1037:   }
1038:   PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists", "Jacobian lagging through multiple SNES solves", "SNESSetLagJacobianPersists", snes->lagjac_persist, &persist, &flg));
1039:   if (flg) PetscCall(SNESSetLagJacobianPersists(snes, persist));

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

1044:   PetscCall(PetscOptionsEList("-snes_convergence_test", "Convergence test", "SNESSetConvergenceTest", convtests, PETSC_STATIC_ARRAY_LENGTH(convtests), "default", &indx, &flg));
1045:   if (flg) {
1046:     switch (indx) {
1047:     case 0:
1048:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedDefault, NULL, NULL));
1049:       break;
1050:     case 1:
1051:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedSkip, NULL, NULL));
1052:       break;
1053:     case 2:
1054:       PetscCall(SNESSetConvergenceTest(snes, SNESConvergedCorrectPressure, NULL, NULL));
1055:       break;
1056:     }
1057:   }

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

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

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

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

1069:   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1070:   PetscCall(PetscSNPrintf(ewprefix, sizeof(ewprefix), "%s%s", optionsprefix ? optionsprefix : "", "snes_"));
1071:   PetscCall(SNESEWSetFromOptions_Private(kctx, PETSC_TRUE, PetscObjectComm((PetscObject)snes), ewprefix));

1073:   flg = PETSC_FALSE;
1074:   PetscCall(PetscOptionsBool("-snes_monitor_cancel", "Remove all monitors", "SNESMonitorCancel", flg, &flg, &set));
1075:   if (set && flg) PetscCall(SNESMonitorCancel(snes));

1077:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor", "Monitor norm of function", "SNESMonitorDefault", SNESMonitorDefault, SNESMonitorDefaultSetUp));
1078:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_short", "Monitor norm of function with fewer digits", "SNESMonitorDefaultShort", SNESMonitorDefaultShort, NULL));
1079:   PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_range", "Monitor range of elements of function", "SNESMonitorRange", SNESMonitorRange, NULL));

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

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

1093:   flg = PETSC_FALSE;
1094:   PetscCall(PetscOptionsBool("-snes_monitor_lg_range", "Plot function range at each iteration", "SNESMonitorLGRange", flg, &flg, NULL));
1095:   if (flg) {
1096:     PetscViewer ctx;

1098:     PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &ctx));
1099:     PetscCall(SNESMonitorSet(snes, SNESMonitorLGRange, ctx, (PetscCtxDestroyFn *)PetscViewerDestroy));
1100:   }

1102:   PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
1103:   PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_converged_reason", &snes->convergedreasonviewer, &snes->convergedreasonformat, NULL));
1104:   flg = PETSC_FALSE;
1105:   PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel", "Remove all converged reason viewers", "SNESConvergedReasonViewCancel", flg, &flg, &set));
1106:   if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));

1108:   flg = PETSC_FALSE;
1109:   PetscCall(PetscOptionsBool("-snes_fd", "Use finite differences (slow) to compute Jacobian", "SNESComputeJacobianDefault", flg, &flg, NULL));
1110:   if (flg) {
1111:     void *functx;
1112:     DM    dm;
1113:     PetscCall(SNESGetDM(snes, &dm));
1114:     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1115:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
1116:     PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefault, functx));
1117:     PetscCall(PetscInfo(snes, "Setting default finite difference Jacobian matrix\n"));
1118:   }

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

1124:   flg = PETSC_FALSE;
1125:   PetscCall(PetscOptionsBool("-snes_fd_color", "Use finite differences with coloring to compute Jacobian", "SNESComputeJacobianDefaultColor", flg, &flg, NULL));
1126:   if (flg) {
1127:     DM dm;
1128:     PetscCall(SNESGetDM(snes, &dm));
1129:     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1130:     PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefaultColor, NULL));
1131:     PetscCall(PetscInfo(snes, "Setting default finite difference coloring Jacobian matrix\n"));
1132:   }

1134:   flg = PETSC_FALSE;
1135:   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));
1136:   if (flg && snes->mf_operator) {
1137:     snes->mf_operator = PETSC_TRUE;
1138:     snes->mf          = PETSC_TRUE;
1139:   }
1140:   flg = PETSC_FALSE;
1141:   PetscCall(PetscOptionsBool("-snes_mf", "Use a Matrix-Free Jacobian with no matrix for computing the preconditioner", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf, &flg));
1142:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1143:   PetscCall(PetscOptionsInt("-snes_mf_version", "Matrix-Free routines version 1 or 2", "None", snes->mf_version, &snes->mf_version, NULL));

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

1148:   flg = PETSC_FALSE;
1149:   PetscCall(SNESGetNPCSide(snes, &pcside));
1150:   PetscCall(PetscOptionsEnum("-snes_npc_side", "SNES nonlinear preconditioner side", "SNESSetNPCSide", PCSides, (PetscEnum)pcside, (PetscEnum *)&pcside, &flg));
1151:   if (flg) PetscCall(SNESSetNPCSide(snes, pcside));

1153: #if PetscDefined(HAVE_SAWS)
1154:   /*
1155:     Publish convergence information using SAWs
1156:   */
1157:   flg = PETSC_FALSE;
1158:   PetscCall(PetscOptionsBool("-snes_monitor_saws", "Publish SNES progress using SAWs", "SNESMonitorSet", flg, &flg, NULL));
1159:   if (flg) {
1160:     PetscCtx ctx;
1161:     PetscCall(SNESMonitorSAWsCreate(snes, &ctx));
1162:     PetscCall(SNESMonitorSet(snes, SNESMonitorSAWs, ctx, SNESMonitorSAWsDestroy));
1163:   }
1164: #endif
1165: #if PetscDefined(HAVE_SAWS)
1166:   {
1167:     PetscBool set;
1168:     flg = PETSC_FALSE;
1169:     PetscCall(PetscOptionsBool("-snes_saws_block", "Block for SAWs at end of SNESSolve", "PetscObjectSAWsBlock", ((PetscObject)snes)->amspublishblock, &flg, &set));
1170:     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes, flg));
1171:   }
1172: #endif

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

1176:   PetscTryTypeMethod(snes, setfromoptions, PetscOptionsObject);

1178:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1179:   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)snes, PetscOptionsObject));
1180:   PetscOptionsEnd();

1182:   if (snes->linesearch) {
1183:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
1184:     PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1185:   }

1187:   if (snes->usesksp) {
1188:     if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
1189:     PetscCall(KSPSetOperators(snes->ksp, snes->jacobian, snes->jacobian_pre));
1190:     PetscCall(KSPSetFromOptions(snes->ksp));
1191:   }

1193:   /* if user has set the SNES NPC type via options database, create it. */
1194:   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1195:   PetscCall(PetscOptionsHasName(((PetscObject)snes)->options, optionsprefix, "-npc_snes_type", &pcset));
1196:   if (pcset && !snes->npc) PetscCall(SNESGetNPC(snes, &snes->npc));
1197:   if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1198:   snes->setfromoptionscalled++;
1199:   PetscFunctionReturn(PETSC_SUCCESS);
1200: }

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

1205:   Collective

1207:   Input Parameter:
1208: . snes - the `SNES` context

1210:   Level: advanced

1212: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1213: @*/
1214: PetscErrorCode SNESResetFromOptions(SNES snes)
1215: {
1216:   PetscFunctionBegin;
1217:   if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1218:   PetscFunctionReturn(PETSC_SUCCESS);
1219: }

1221: /*@C
1222:   SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1223:   the nonlinear solvers.

1225:   Logically Collective; No Fortran Support

1227:   Input Parameters:
1228: + snes    - the `SNES` context
1229: . compute - function to compute the context
1230: - destroy - function to destroy the context, see `PetscCtxDestroyFn` for the calling sequence

1232:   Calling sequence of `compute`:
1233: + snes - the `SNES` context
1234: - ctx  - context to be computed

1236:   Level: intermediate

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

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

1243: .seealso: [](ch_snes), `SNESGetApplicationContext()`, `SNESSetApplicationContext()`, `PetscCtxDestroyFn`
1244: @*/
1245: PetscErrorCode SNESSetComputeApplicationContext(SNES snes, PetscErrorCode (*compute)(SNES snes, PetscCtxRt ctx), PetscCtxDestroyFn *destroy)
1246: {
1247:   PetscFunctionBegin;
1249:   snes->ops->ctxcompute = compute;
1250:   snes->ops->ctxdestroy = destroy;
1251:   PetscFunctionReturn(PETSC_SUCCESS);
1252: }

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

1257:   Logically Collective

1259:   Input Parameters:
1260: + snes - the `SNES` context
1261: - ctx  - the application context

1263:   Level: intermediate

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

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

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

1276: .seealso: [](ch_snes), `SNES`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1277: @*/
1278: PetscErrorCode SNESSetApplicationContext(SNES snes, PetscCtx ctx)
1279: {
1280:   KSP ksp;

1282:   PetscFunctionBegin;
1284:   PetscCall(SNESGetKSP(snes, &ksp));
1285:   PetscCall(KSPSetApplicationContext(ksp, ctx));
1286:   snes->ctx = ctx;
1287:   PetscFunctionReturn(PETSC_SUCCESS);
1288: }

1290: /*@
1291:   SNESGetApplicationContext - Gets the user-defined context for the
1292:   nonlinear solvers set with `SNESGetApplicationContext()` or `SNESSetComputeApplicationContext()`

1294:   Not Collective

1296:   Input Parameter:
1297: . snes - `SNES` context

1299:   Output Parameter:
1300: . ctx - the application context

1302:   Level: intermediate

1304:   Fortran Notes:
1305:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
1306: .vb
1307:   type(tUsertype), pointer :: ctx
1308: .ve

1310: .seealso: [](ch_snes), `SNESSetApplicationContext()`, `SNESSetComputeApplicationContext()`
1311: @*/
1312: PetscErrorCode SNESGetApplicationContext(SNES snes, PetscCtxRt ctx)
1313: {
1314:   PetscFunctionBegin;
1316:   *(void **)ctx = snes->ctx;
1317:   PetscFunctionReturn(PETSC_SUCCESS);
1318: }

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

1323:   Logically Collective

1325:   Input Parameters:
1326: + snes        - `SNES` context
1327: . mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1328: - 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
1329:                 this option no matrix-element based preconditioners can be used in the linear solve since the matrix won't be explicitly available

1331:   Options Database Keys:
1332: + -snes_mf_operator - use matrix-free only for the mat operator
1333: . -snes_mf          - use matrix-free for both the mat and pmat operator
1334: . -snes_fd_color    - compute the Jacobian via coloring and finite differences.
1335: - -snes_fd          - compute the Jacobian via finite differences (slow)

1337:   Level: intermediate

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

1344: .seealso: [](ch_snes), `SNES`, `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`, `MatFDColoring`
1345: @*/
1346: PetscErrorCode SNESSetUseMatrixFree(SNES snes, PetscBool mf_operator, PetscBool mf)
1347: {
1348:   PetscFunctionBegin;
1352:   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1353:   snes->mf_operator = mf_operator;
1354:   PetscFunctionReturn(PETSC_SUCCESS);
1355: }

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

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

1362:   Input Parameter:
1363: . snes - `SNES` context

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

1369:   Level: intermediate

1371: .seealso: [](ch_snes), `SNES`, `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1372: @*/
1373: PetscErrorCode SNESGetUseMatrixFree(SNES snes, PetscBool *mf_operator, PetscBool *mf)
1374: {
1375:   PetscFunctionBegin;
1377:   if (mf) *mf = snes->mf;
1378:   if (mf_operator) *mf_operator = snes->mf_operator;
1379:   PetscFunctionReturn(PETSC_SUCCESS);
1380: }

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

1385:   Not Collective

1387:   Input Parameter:
1388: . snes - `SNES` context

1390:   Output Parameter:
1391: . iter - iteration number

1393:   Level: intermediate

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

1398:   This is useful for using lagged Jacobians (where one does not recompute the
1399:   Jacobian at each `SNES` iteration). For example, the code
1400: .vb
1401:       ierr = SNESGetIterationNumber(snes,&it);
1402:       if (!(it % 2)) {
1403:         [compute Jacobian here]
1404:       }
1405: .ve
1406:   can be used in your function that computes the Jacobian to cause the Jacobian to be
1407:   recomputed every second `SNES` iteration. See also `SNESSetLagJacobian()`

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

1411: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetLagJacobian()`, `SNESGetLinearSolveIterations()`, `SNESSetMonitor()`
1412: @*/
1413: PetscErrorCode SNESGetIterationNumber(SNES snes, PetscInt *iter)
1414: {
1415:   PetscFunctionBegin;
1417:   PetscAssertPointer(iter, 2);
1418:   *iter = snes->iter;
1419:   PetscFunctionReturn(PETSC_SUCCESS);
1420: }

1422: /*@
1423:   SNESSetIterationNumber - Sets the current iteration number.

1425:   Not Collective

1427:   Input Parameters:
1428: + snes - `SNES` context
1429: - iter - iteration number

1431:   Level: developer

1433:   Note:
1434:   This should only be called inside a `SNES` nonlinear solver.

1436: .seealso: [](ch_snes), `SNESGetLinearSolveIterations()`
1437: @*/
1438: PetscErrorCode SNESSetIterationNumber(SNES snes, PetscInt iter)
1439: {
1440:   PetscFunctionBegin;
1442:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1443:   snes->iter = iter;
1444:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1445:   PetscFunctionReturn(PETSC_SUCCESS);
1446: }

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

1452:   Not Collective

1454:   Input Parameter:
1455: . snes - `SNES` context

1457:   Output Parameter:
1458: . nfails - number of unsuccessful steps attempted

1460:   Level: intermediate

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

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

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

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

1473: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1474:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1475: @*/
1476: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes, PetscInt *nfails)
1477: {
1478:   PetscFunctionBegin;
1480:   PetscAssertPointer(nfails, 2);
1481:   *nfails = snes->numFailures;
1482:   PetscFunctionReturn(PETSC_SUCCESS);
1483: }

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

1489:   Not Collective

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

1495:   Options Database Key:
1496: . -snes_max_fail n - maximum number of unsuccessful steps allowed

1498:   Level: intermediate

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

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

1507:   Developer Note:
1508:   The options database key is wrong for this function name

1510: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1511:           `SNESGetLinearSolveFailures()`, `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`, `SNESCheckLineSearchFailure()`
1512: @*/
1513: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1514: {
1515:   PetscFunctionBegin;

1518:   if (maxFails == PETSC_UNLIMITED) {
1519:     snes->maxFailures = PETSC_INT_MAX;
1520:   } else {
1521:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1522:     snes->maxFailures = maxFails;
1523:   }
1524:   PetscFunctionReturn(PETSC_SUCCESS);
1525: }

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

1531:   Not Collective

1533:   Input Parameter:
1534: . snes - `SNES` context

1536:   Output Parameter:
1537: . maxFails - maximum of unsuccessful steps

1539:   Level: intermediate

1541: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1542:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1543: @*/
1544: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1545: {
1546:   PetscFunctionBegin;
1548:   PetscAssertPointer(maxFails, 2);
1549:   *maxFails = snes->maxFailures;
1550:   PetscFunctionReturn(PETSC_SUCCESS);
1551: }

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

1557:   Not Collective

1559:   Input Parameter:
1560: . snes - `SNES` context

1562:   Output Parameter:
1563: . nfuncs - number of evaluations

1565:   Level: intermediate

1567:   Note:
1568:   Reset every time `SNESSolve()` is called unless `SNESSetCountersReset()` is used.

1570: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1571: @*/
1572: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1573: {
1574:   PetscFunctionBegin;
1576:   PetscAssertPointer(nfuncs, 2);
1577:   *nfuncs = snes->nfuncs;
1578:   PetscFunctionReturn(PETSC_SUCCESS);
1579: }

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

1585:   Not Collective

1587:   Input Parameter:
1588: . snes - `SNES` context

1590:   Output Parameter:
1591: . nfails - number of failed solves

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

1596:   Level: intermediate

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

1601: .seealso: [](ch_snes), `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1602: @*/
1603: PetscErrorCode SNESGetLinearSolveFailures(SNES snes, PetscInt *nfails)
1604: {
1605:   PetscFunctionBegin;
1607:   PetscAssertPointer(nfails, 2);
1608:   *nfails = snes->numLinearSolveFailures;
1609:   PetscFunctionReturn(PETSC_SUCCESS);
1610: }

1612: /*@
1613:   SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1614:   allowed before `SNES` returns with a diverged reason of `SNES_DIVERGED_LINEAR_SOLVE`

1616:   Logically Collective

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

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

1625:   Level: intermediate

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

1630:   Developer Note:
1631:   The options database key is wrong for this function name

1633: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1634: @*/
1635: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1636: {
1637:   PetscFunctionBegin;

1641:   if (maxFails == PETSC_UNLIMITED) {
1642:     snes->maxLinearSolveFailures = PETSC_INT_MAX;
1643:   } else {
1644:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1645:     snes->maxLinearSolveFailures = maxFails;
1646:   }
1647:   PetscFunctionReturn(PETSC_SUCCESS);
1648: }

1650: /*@
1651:   SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1652:   are allowed before `SNES` returns as unsuccessful

1654:   Not Collective

1656:   Input Parameter:
1657: . snes - `SNES` context

1659:   Output Parameter:
1660: . maxFails - maximum of unsuccessful solves allowed

1662:   Level: intermediate

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

1667: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1668: @*/
1669: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1670: {
1671:   PetscFunctionBegin;
1673:   PetscAssertPointer(maxFails, 2);
1674:   *maxFails = snes->maxLinearSolveFailures;
1675:   PetscFunctionReturn(PETSC_SUCCESS);
1676: }

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

1682:   Not Collective

1684:   Input Parameter:
1685: . snes - `SNES` context

1687:   Output Parameter:
1688: . lits - number of linear iterations

1690:   Level: intermediate

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

1695:   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
1696:   then call `KSPGetIterationNumber()` after the failed solve.

1698: .seealso: [](ch_snes), `SNES`, `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1699: @*/
1700: PetscErrorCode SNESGetLinearSolveIterations(SNES snes, PetscInt *lits)
1701: {
1702:   PetscFunctionBegin;
1704:   PetscAssertPointer(lits, 2);
1705:   *lits = snes->linear_its;
1706:   PetscFunctionReturn(PETSC_SUCCESS);
1707: }

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

1713:   Logically Collective

1715:   Input Parameters:
1716: + snes  - `SNES` context
1717: - reset - whether to reset the counters or not, defaults to `PETSC_TRUE`

1719:   Level: developer

1721: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1722: @*/
1723: PetscErrorCode SNESSetCountersReset(SNES snes, PetscBool reset)
1724: {
1725:   PetscFunctionBegin;
1728:   snes->counters_reset = reset;
1729:   PetscFunctionReturn(PETSC_SUCCESS);
1730: }

1732: /*@
1733:   SNESResetCounters - Reset counters for linear iterations and function evaluations.

1735:   Logically Collective

1737:   Input Parameters:
1738: . snes - `SNES` context

1740:   Level: developer

1742:   Note:
1743:   It honors the flag set with `SNESSetCountersReset()`

1745: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1746: @*/
1747: PetscErrorCode SNESResetCounters(SNES snes)
1748: {
1749:   PetscFunctionBegin;
1751:   if (snes->counters_reset) {
1752:     snes->nfuncs      = 0;
1753:     snes->linear_its  = 0;
1754:     snes->numFailures = 0;
1755:   }
1756:   PetscFunctionReturn(PETSC_SUCCESS);
1757: }

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

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

1764:   Input Parameters:
1765: + snes - the `SNES` context
1766: - ksp  - the `KSP` context

1768:   Level: developer

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

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

1777: .seealso: [](ch_snes), `SNES`, `KSP`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`
1778: @*/
1779: PetscErrorCode SNESSetKSP(SNES snes, KSP ksp)
1780: {
1781:   PetscFunctionBegin;
1784:   PetscCheckSameComm(snes, 1, ksp, 2);
1785:   PetscCall(PetscObjectReference((PetscObject)ksp));
1786:   PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1787:   snes->ksp = ksp;
1788:   PetscFunctionReturn(PETSC_SUCCESS);
1789: }

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

1794:   Logically collective

1796:   Input Parameter:
1797: . snes - the `SNES` object

1799:   Level: developer

1801:   Notes:

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

1805:   Developer Notes:

1807:   `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.

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

1811: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
1812:           `PetscObjectParameterSetDefault()`
1813: @*/
1814: PetscErrorCode SNESParametersInitialize(SNES snes)
1815: {
1816:   PetscObjectParameterSetDefault(snes, max_its, 50);
1817:   PetscObjectParameterSetDefault(snes, max_funcs, 10000);
1818:   PetscObjectParameterSetDefault(snes, rtol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1819:   PetscObjectParameterSetDefault(snes, abstol, PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50);
1820:   PetscObjectParameterSetDefault(snes, stol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1821:   PetscObjectParameterSetDefault(snes, divtol, 1.e4);
1822:   return PETSC_SUCCESS;
1823: }

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

1828:   Collective

1830:   Input Parameter:
1831: . comm - MPI communicator

1833:   Output Parameter:
1834: . outsnes - the new `SNES` context

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

1842:   Level: beginner

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

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

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

1855: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1856: @*/
1857: PetscErrorCode SNESCreate(MPI_Comm comm, SNES *outsnes)
1858: {
1859:   SNES       snes;
1860:   SNESKSPEW *kctx;

1862:   PetscFunctionBegin;
1863:   PetscAssertPointer(outsnes, 2);
1864:   PetscCall(SNESInitializePackage());

1866:   PetscCall(PetscHeaderCreate(snes, SNES_CLASSID, "SNES", "Nonlinear solver", "SNES", comm, SNESDestroy, SNESView));
1867:   snes->ops->converged = SNESConvergedDefault;
1868:   snes->usesksp        = PETSC_TRUE;
1869:   snes->norm           = 0.0;
1870:   snes->xnorm          = 0.0;
1871:   snes->ynorm          = 0.0;
1872:   snes->normschedule   = SNES_NORM_ALWAYS;
1873:   snes->functype       = SNES_FUNCTION_DEFAULT;
1874:   snes->ttol           = 0.0;

1876:   snes->rnorm0               = 0;
1877:   snes->nfuncs               = 0;
1878:   snes->numFailures          = 0;
1879:   snes->maxFailures          = 1;
1880:   snes->linear_its           = 0;
1881:   snes->lagjacobian          = 1;
1882:   snes->jac_iter             = 0;
1883:   snes->lagjac_persist       = PETSC_FALSE;
1884:   snes->lagpreconditioner    = 1;
1885:   snes->pre_iter             = 0;
1886:   snes->lagpre_persist       = PETSC_FALSE;
1887:   snes->numbermonitors       = 0;
1888:   snes->numberreasonviews    = 0;
1889:   snes->data                 = NULL;
1890:   snes->setupcalled          = PETSC_FALSE;
1891:   snes->ksp_ewconv           = PETSC_FALSE;
1892:   snes->nwork                = 0;
1893:   snes->work                 = NULL;
1894:   snes->nvwork               = 0;
1895:   snes->vwork                = NULL;
1896:   snes->conv_hist_len        = 0;
1897:   snes->conv_hist_max        = 0;
1898:   snes->conv_hist            = NULL;
1899:   snes->conv_hist_its        = NULL;
1900:   snes->conv_hist_reset      = PETSC_TRUE;
1901:   snes->counters_reset       = PETSC_TRUE;
1902:   snes->vec_func_init_set    = PETSC_FALSE;
1903:   snes->reason               = SNES_CONVERGED_ITERATING;
1904:   snes->npcside              = PC_RIGHT;
1905:   snes->setfromoptionscalled = 0;

1907:   snes->mf          = PETSC_FALSE;
1908:   snes->mf_operator = PETSC_FALSE;
1909:   snes->mf_version  = 1;

1911:   snes->numLinearSolveFailures = 0;
1912:   snes->maxLinearSolveFailures = 1;

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

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

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

1923:   snes->kspconvctx  = kctx;
1924:   kctx->version     = 2;
1925:   kctx->rtol_0      = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1926:                              this was too large for some test cases */
1927:   kctx->rtol_last   = 0.0;
1928:   kctx->rtol_max    = 0.9;
1929:   kctx->gamma       = 1.0;
1930:   kctx->alpha       = 0.5 * (1.0 + PetscSqrtReal(5.0));
1931:   kctx->alpha2      = kctx->alpha;
1932:   kctx->threshold   = 0.1;
1933:   kctx->lresid_last = 0.0;
1934:   kctx->norm_last   = 0.0;

1936:   kctx->rk_last     = 0.0;
1937:   kctx->rk_last_2   = 0.0;
1938:   kctx->rtol_last_2 = 0.0;
1939:   kctx->v4_p1       = 0.1;
1940:   kctx->v4_p2       = 0.4;
1941:   kctx->v4_p3       = 0.7;
1942:   kctx->v4_m1       = 0.8;
1943:   kctx->v4_m2       = 0.5;
1944:   kctx->v4_m3       = 0.1;
1945:   kctx->v4_m4       = 0.5;

1947:   PetscCall(SNESParametersInitialize(snes));
1948:   *outsnes = snes;
1949:   PetscFunctionReturn(PETSC_SUCCESS);
1950: }

1952: /*@C
1953:   SNESSetFunction - Sets the function evaluation routine and function
1954:   vector for use by the `SNES` routines in solving systems of nonlinear
1955:   equations.

1957:   Logically Collective

1959:   Input Parameters:
1960: + snes - the `SNES` context
1961: . r    - vector to store function values, may be `NULL`
1962: . f    - function evaluation routine;  for calling sequence see `SNESFunctionFn`
1963: - ctx  - [optional] user-defined context for private data for the
1964:          function evaluation routine (may be `NULL`)

1966:   Level: beginner

1968: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunctionFn`
1969: @*/
1970: PetscErrorCode SNESSetFunction(SNES snes, Vec r, SNESFunctionFn *f, PetscCtx ctx)
1971: {
1972:   DM dm;

1974:   PetscFunctionBegin;
1976:   if (r) {
1978:     PetscCheckSameComm(snes, 1, r, 2);
1979:     PetscCall(PetscObjectReference((PetscObject)r));
1980:     PetscCall(VecDestroy(&snes->vec_func));
1981:     snes->vec_func = r;
1982:   }
1983:   /* update DMSNES
1984:      We support incremental information; so update the function context only if r is not specified
1985:      (which allows to disable the callbacks when both f and ctx are NULL),
1986:      or, if r is specified, when at least one of f and ctx is not NULL */
1987:   PetscCall(SNESGetDM(snes, &dm));
1988:   if (!r || f || ctx) PetscCall(DMSNESSetFunction(dm, f, ctx));
1989:   if (f == SNESPicardComputeFunction) PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
1990:   PetscFunctionReturn(PETSC_SUCCESS);
1991: }

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

1996:   Logically Collective

1998:   Input Parameters:
1999: + snes - the `SNES` context
2000: - f    - vector to store function value

2002:   Level: developer

2004:   Notes:
2005:   This should not be modified during the solution procedure.

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

2009: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
2010: @*/
2011: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
2012: {
2013:   Vec vec_func;

2015:   PetscFunctionBegin;
2018:   PetscCheckSameComm(snes, 1, f, 2);
2019:   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2020:     snes->vec_func_init_set = PETSC_FALSE;
2021:     PetscFunctionReturn(PETSC_SUCCESS);
2022:   }
2023:   PetscCall(SNESGetFunction(snes, &vec_func, NULL, NULL));
2024:   PetscCall(VecCopy(f, vec_func));

2026:   snes->vec_func_init_set = PETSC_TRUE;
2027:   PetscFunctionReturn(PETSC_SUCCESS);
2028: }

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

2034:   Logically Collective

2036:   Input Parameters:
2037: + snes         - the `SNES` context
2038: - normschedule - the frequency of norm computation

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

2043:   Level: advanced

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

2054: .seealso: [](ch_snes), `SNESNormSchedule`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`
2055: @*/
2056: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
2057: {
2058:   PetscFunctionBegin;
2061:   snes->normschedule = normschedule;
2062:   PetscFunctionReturn(PETSC_SUCCESS);
2063: }

2065: /*@
2066:   SNESGetNormSchedule - Gets the `SNESNormSchedule` used in convergence and monitoring
2067:   of the `SNES` method.

2069:   Logically Collective

2071:   Input Parameters:
2072: + snes         - the `SNES` context
2073: - normschedule - the type of the norm used

2075:   Level: advanced

2077: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2078: @*/
2079: PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
2080: {
2081:   PetscFunctionBegin;
2083:   *normschedule = snes->normschedule;
2084:   PetscFunctionReturn(PETSC_SUCCESS);
2085: }

2087: /*@
2088:   SNESSetFunctionNorm - Sets the last computed residual norm.

2090:   Logically Collective

2092:   Input Parameters:
2093: + snes - the `SNES` context
2094: - norm - the value of the norm

2096:   Level: developer

2098: .seealso: [](ch_snes), `SNES`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2099: @*/
2100: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2101: {
2102:   PetscFunctionBegin;
2104:   snes->norm = norm;
2105:   PetscFunctionReturn(PETSC_SUCCESS);
2106: }

2108: /*@
2109:   SNESGetFunctionNorm - Gets the last computed norm of the residual

2111:   Not Collective

2113:   Input Parameter:
2114: . snes - the `SNES` context

2116:   Output Parameter:
2117: . norm - the last computed residual norm

2119:   Level: developer

2121: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2122: @*/
2123: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2124: {
2125:   PetscFunctionBegin;
2127:   PetscAssertPointer(norm, 2);
2128:   *norm = snes->norm;
2129:   PetscFunctionReturn(PETSC_SUCCESS);
2130: }

2132: /*@
2133:   SNESGetUpdateNorm - Gets the last computed norm of the solution update

2135:   Not Collective

2137:   Input Parameter:
2138: . snes - the `SNES` context

2140:   Output Parameter:
2141: . ynorm - the last computed update norm

2143:   Level: developer

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

2148: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2149: @*/
2150: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2151: {
2152:   PetscFunctionBegin;
2154:   PetscAssertPointer(ynorm, 2);
2155:   *ynorm = snes->ynorm;
2156:   PetscFunctionReturn(PETSC_SUCCESS);
2157: }

2159: /*@
2160:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2162:   Not Collective

2164:   Input Parameter:
2165: . snes - the `SNES` context

2167:   Output Parameter:
2168: . xnorm - the last computed solution norm

2170:   Level: developer

2172: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2173: @*/
2174: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2175: {
2176:   PetscFunctionBegin;
2178:   PetscAssertPointer(xnorm, 2);
2179:   *xnorm = snes->xnorm;
2180:   PetscFunctionReturn(PETSC_SUCCESS);
2181: }

2183: /*@
2184:   SNESSetFunctionType - Sets the `SNESFunctionType`
2185:   of the `SNES` method.

2187:   Logically Collective

2189:   Input Parameters:
2190: + snes - the `SNES` context
2191: - type - the function type

2193:   Level: developer

2195:   Values of the function type\:
2196: +  `SNES_FUNCTION_DEFAULT`          - the default for the given `SNESType`
2197: .  `SNES_FUNCTION_UNPRECONDITIONED` - an unpreconditioned function evaluation (this is the function provided with `SNESSetFunction()`
2198: -  `SNES_FUNCTION_PRECONDITIONED`   - a transformation of the function provided with `SNESSetFunction()`

2200:   Note:
2201:   Different `SNESType`s use this value in different ways

2203: .seealso: [](ch_snes), `SNES`, `SNESFunctionType`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2204: @*/
2205: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2206: {
2207:   PetscFunctionBegin;
2209:   snes->functype = type;
2210:   PetscFunctionReturn(PETSC_SUCCESS);
2211: }

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

2217:   Logically Collective

2219:   Input Parameters:
2220: + snes - the `SNES` context
2221: - type - the type of the function evaluation, see `SNESSetFunctionType()`

2223:   Level: advanced

2225: .seealso: [](ch_snes), `SNESSetFunctionType()`, `SNESFunctionType`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2226: @*/
2227: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2228: {
2229:   PetscFunctionBegin;
2231:   *type = snes->functype;
2232:   PetscFunctionReturn(PETSC_SUCCESS);
2233: }

2235: /*@C
2236:   SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2237:   use with composed nonlinear solvers.

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

2244:   Level: intermediate

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

2250: .seealso: [](ch_snes), `SNESNGS`, `SNESGetNGS()`, `SNESNCG`, `SNESGetFunction()`, `SNESComputeNGS()`, `SNESNGSFn`
2251: @*/
2252: PetscErrorCode SNESSetNGS(SNES snes, SNESNGSFn *f, PetscCtx ctx)
2253: {
2254:   DM dm;

2256:   PetscFunctionBegin;
2258:   PetscCall(SNESGetDM(snes, &dm));
2259:   PetscCall(DMSNESSetNGS(dm, f, ctx));
2260:   PetscFunctionReturn(PETSC_SUCCESS);
2261: }

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

2266:   Collective

2268:   Input Parameters:
2269: + snes - the `SNES` context
2270: . x    - the current iterate
2271: - ctx  - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`

2273:   Output Parameter:
2274: . f - the residual vector

2276:   Level: developer

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

2281: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeJacobian()`
2282: @*/
2283: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2284: {
2285:   DM     dm;
2286:   DMSNES sdm;

2288:   PetscFunctionBegin;
2289:   PetscCall(SNESGetDM(snes, &dm));
2290:   PetscCall(DMGetDMSNES(dm, &sdm));
2291:   /*  A(x)*x - b(x) */
2292:   if (sdm->ops->computepfunction) {
2293:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2294:     PetscCall(VecScale(f, -1.0));
2295:     /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2296:     if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2297:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2298:     PetscCall(MatMultAdd(snes->picard, x, f, f));
2299:   } else {
2300:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2301:     PetscCall(MatMult(snes->picard, x, f));
2302:   }
2303:   PetscFunctionReturn(PETSC_SUCCESS);
2304: }

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

2309:   Collective

2311:   Input Parameters:
2312: + snes - the `SNES` context
2313: . x    - the current iterate
2314: - ctx  - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`

2316:   Output Parameter:
2317: . f - the residual vector

2319:   Level: developer

2321: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeMFFunction()`, `SNESPicardComputeJacobian()`
2322: @*/
2323: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2324: {
2325:   DM     dm;
2326:   DMSNES sdm;

2328:   PetscFunctionBegin;
2329:   PetscCall(SNESGetDM(snes, &dm));
2330:   PetscCall(DMGetDMSNES(dm, &sdm));
2331:   /*  A(x)*x - b(x) */
2332:   if (sdm->ops->computepfunction) {
2333:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2334:     PetscCall(VecScale(f, -1.0));
2335:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2336:     PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2337:   } else {
2338:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2339:     PetscCall(MatMult(snes->jacobian_pre, x, f));
2340:   }
2341:   PetscFunctionReturn(PETSC_SUCCESS);
2342: }

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

2347:   Collective

2349:   Input Parameters:
2350: + snes - the `SNES` context
2351: . x1   - the current iterate (unused)
2352: . J    - the Jacobian matrix to assemble
2353: . B    - the preconditioning matrix (unused)
2354: - ctx  - unused application context

2356:   Level: developer

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

2361: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeMFFunction()`
2362: @*/
2363: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2364: {
2365:   PetscFunctionBegin;
2366:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2367:   /* must assembly if matrix-free to get the last SNES solution */
2368:   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2369:   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2370:   PetscFunctionReturn(PETSC_SUCCESS);
2371: }

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

2376:   Logically Collective

2378:   Input Parameters:
2379: + snes - the `SNES` context
2380: . r    - vector to store function values, may be `NULL`
2381: . bp   - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2382: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2383: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2384: . J    - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2385: - ctx  - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)

2387:   Level: intermediate

2389:   Notes:
2390:   It is often better to provide the nonlinear function $F()$ and some approximation to its Jacobian directly and use
2391:   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.

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

2395:   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}$.
2396:   When an exact solver is used this corresponds to the "classic" Picard $A(x^{n}) x^{n+1} = bp(x^{n}) + b$ iteration.

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

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

2403:   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
2404:   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
2405:   different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument \:-).

2407:   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
2408:   $A(x^{n})$ is used to build the preconditioner

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

2412:   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
2413:   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
2414:   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`.
2415:   See the comment in src/snes/tutorials/ex15.c.

2417: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2418:           `SNESFunctionFn`, `SNESJacobianFn`
2419: @*/
2420: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2421: {
2422:   DM dm;

2424:   PetscFunctionBegin;
2426:   PetscCall(SNESGetDM(snes, &dm));
2427:   PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2428:   PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2429:   PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2430:   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2431:   PetscFunctionReturn(PETSC_SUCCESS);
2432: }

2434: /*@C
2435:   SNESGetPicard - Returns the context for the Picard iteration

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

2439:   Input Parameter:
2440: . snes - the `SNES` context

2442:   Output Parameters:
2443: + r    - the function (or `NULL`)
2444: . f    - the function (or `NULL`);  for calling sequence see `SNESFunctionFn`
2445: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2446: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2447: . J    - the function for matrix evaluation (or `NULL`);  for calling sequence see `SNESJacobianFn`
2448: - ctx  - the function context (or `NULL`)

2450:   Level: advanced

2452: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2453: @*/
2454: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2455: {
2456:   DM dm;

2458:   PetscFunctionBegin;
2460:   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2461:   PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2462:   PetscCall(SNESGetDM(snes, &dm));
2463:   PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2464:   PetscFunctionReturn(PETSC_SUCCESS);
2465: }

2467: /*@C
2468:   SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the nonlinear problem

2470:   Logically Collective

2472:   Input Parameters:
2473: + snes - the `SNES` context
2474: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2475: - ctx  - [optional] user-defined context for private data for the
2476:          function evaluation routine (may be `NULL`)

2478:   Level: intermediate

2480: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2481: @*/
2482: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2483: {
2484:   PetscFunctionBegin;
2486:   if (func) snes->ops->computeinitialguess = func;
2487:   if (ctx) snes->initialguessP = ctx;
2488:   PetscFunctionReturn(PETSC_SUCCESS);
2489: }

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

2495:   Logically Collective

2497:   Input Parameter:
2498: . snes - the `SNES` context

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

2503:   Level: intermediate

2505: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2506: @*/
2507: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2508: {
2509:   PetscFunctionBegin;
2511:   PetscAssertPointer(rhs, 2);
2512:   *rhs = snes->vec_rhs;
2513:   PetscFunctionReturn(PETSC_SUCCESS);
2514: }

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

2519:   Collective

2521:   Input Parameters:
2522: + snes - the `SNES` context
2523: - x    - input vector

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

2528:   Level: developer

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

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

2536:   This function usually appears in the pattern.
2537: .vb
2538:   SNESComputeFunction(snes, x, f);
2539:   VecNorm(f, &fnorm);
2540:   SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2541: .ve
2542:   to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.

2544: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2545: @*/
2546: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2547: {
2548:   DM     dm;
2549:   DMSNES sdm;

2551:   PetscFunctionBegin;
2555:   PetscCheckSameComm(snes, 1, x, 2);
2556:   PetscCheckSameComm(snes, 1, f, 3);
2557:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

2559:   PetscCall(SNESGetDM(snes, &dm));
2560:   PetscCall(DMGetDMSNES(dm, &sdm));
2561:   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().");
2562:   if (sdm->ops->computefunction) {
2563:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2564:     PetscCall(VecLockReadPush(x));
2565:     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2566:     snes->functiondomainerror = PETSC_FALSE;
2567:     {
2568:       void           *ctx;
2569:       SNESFunctionFn *computefunction;
2570:       PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2571:       PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2572:     }
2573:     PetscCall(VecLockReadPop(x));
2574:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2575:   } else /* if (snes->vec_rhs) */ {
2576:     PetscCall(MatMult(snes->jacobian, x, f));
2577:   }
2578:   if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2579:   snes->nfuncs++;
2580:   /*
2581:      domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2582:      propagate the value to all processes
2583:   */
2584:   PetscCall(VecFlag(f, snes->functiondomainerror));
2585:   PetscFunctionReturn(PETSC_SUCCESS);
2586: }

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

2591:   Collective

2593:   Input Parameters:
2594: + snes - the `SNES` context
2595: - x    - input vector

2597:   Output Parameter:
2598: . y - output vector

2600:   Level: developer

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

2606:   Since this function is intended for use with finite differencing it does not subtract the right-hand side vector provided with `SNESSolve()`
2607:   while `SNESComputeFunction()` does. As such, this routine cannot be used with  `MatMFFDSetBase()` with a provided F function value even if it applies the
2608:   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.

2610: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2611: @*/
2612: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2613: {
2614:   DM     dm;
2615:   DMSNES sdm;

2617:   PetscFunctionBegin;
2621:   PetscCheckSameComm(snes, 1, x, 2);
2622:   PetscCheckSameComm(snes, 1, y, 3);
2623:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

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

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

2646:   Collective

2648:   Input Parameters:
2649: + snes - the `SNES` context
2650: . x    - input vector
2651: - b    - rhs vector

2653:   Output Parameter:
2654: . x - new solution vector

2656:   Level: developer

2658:   Note:
2659:   `SNESComputeNGS()` is typically used within composed nonlinear solver
2660:   implementations, so most users would not generally call this routine
2661:   themselves.

2663: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2664: @*/
2665: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2666: {
2667:   DM     dm;
2668:   DMSNES sdm;

2670:   PetscFunctionBegin;
2674:   PetscCheckSameComm(snes, 1, x, 3);
2675:   if (b) PetscCheckSameComm(snes, 1, b, 2);
2676:   if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2677:   PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2678:   PetscCall(SNESGetDM(snes, &dm));
2679:   PetscCall(DMGetDMSNES(dm, &sdm));
2680:   PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2681:   if (b) PetscCall(VecLockReadPush(b));
2682:   PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2683:   if (b) PetscCall(VecLockReadPop(b));
2684:   PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2685:   PetscFunctionReturn(PETSC_SUCCESS);
2686: }

2688: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2689: {
2690:   Vec          X;
2691:   PetscScalar *g;
2692:   PetscReal    f, f2;
2693:   PetscInt     low, high, N, i;
2694:   PetscBool    flg;
2695:   PetscReal    h = .5 * PETSC_SQRT_MACHINE_EPSILON;

2697:   PetscFunctionBegin;
2698:   PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2699:   PetscCall(VecDuplicate(Xin, &X));
2700:   PetscCall(VecCopy(Xin, X));
2701:   PetscCall(VecGetSize(X, &N));
2702:   PetscCall(VecGetOwnershipRange(X, &low, &high));
2703:   PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2704:   PetscCall(VecGetArray(G, &g));
2705:   for (i = 0; i < N; i++) {
2706:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2707:     PetscCall(VecAssemblyBegin(X));
2708:     PetscCall(VecAssemblyEnd(X));
2709:     PetscCall(SNESComputeObjective(snes, X, &f));
2710:     PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2711:     PetscCall(VecAssemblyBegin(X));
2712:     PetscCall(VecAssemblyEnd(X));
2713:     PetscCall(SNESComputeObjective(snes, X, &f2));
2714:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2715:     PetscCall(VecAssemblyBegin(X));
2716:     PetscCall(VecAssemblyEnd(X));
2717:     if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2718:   }
2719:   PetscCall(VecRestoreArray(G, &g));
2720:   PetscCall(VecDestroy(&X));
2721:   PetscFunctionReturn(PETSC_SUCCESS);
2722: }

2724: /*@
2725:   SNESTestFunction - Computes the difference between the computed and finite-difference functions

2727:   Collective

2729:   Input Parameter:
2730: . snes - the `SNES` context

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

2736:   Level: developer

2738: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2739: @*/
2740: PetscErrorCode SNESTestFunction(SNES snes)
2741: {
2742:   Vec               x, g1, g2, g3;
2743:   PetscBool         complete_print = PETSC_FALSE;
2744:   PetscReal         hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2745:   PetscScalar       dot;
2746:   MPI_Comm          comm;
2747:   PetscViewer       viewer, mviewer;
2748:   PetscViewerFormat format;
2749:   PetscInt          tabs;
2750:   static PetscBool  directionsprinted = PETSC_FALSE;
2751:   SNESObjectiveFn  *objective;

2753:   PetscFunctionBegin;
2754:   PetscCall(SNESGetObjective(snes, &objective, NULL));
2755:   if (!objective) PetscFunctionReturn(PETSC_SUCCESS);

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

2761:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2762:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2763:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2764:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2765:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Function -------------\n"));
2766:   if (!complete_print && !directionsprinted) {
2767:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2768:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference function entries greater than <threshold>.\n"));
2769:   }
2770:   if (!directionsprinted) {
2771:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2772:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Function is probably correct.\n"));
2773:     directionsprinted = PETSC_TRUE;
2774:   }
2775:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2777:   PetscCall(SNESGetSolution(snes, &x));
2778:   PetscCall(VecDuplicate(x, &g1));
2779:   PetscCall(VecDuplicate(x, &g2));
2780:   PetscCall(VecDuplicate(x, &g3));
2781:   PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() correctly */
2782:   PetscCall(SNESComputeFunction_FD(snes, x, g2));

2784:   PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2785:   PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2786:   PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2787:   PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2788:   PetscCall(VecDot(g1, g2, &dot));
2789:   PetscCall(VecCopy(g1, g3));
2790:   PetscCall(VecAXPY(g3, -1.0, g2));
2791:   PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2792:   PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2793:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2794:   PetscCall(PetscViewerASCIIPrintf(viewer, "  2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2795:   PetscCall(PetscViewerASCIIPrintf(viewer, "  max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));

2797:   if (complete_print) {
2798:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded function ----------\n"));
2799:     PetscCall(VecView(g1, mviewer));
2800:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference function ----------\n"));
2801:     PetscCall(VecView(g2, mviewer));
2802:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded minus finite-difference function ----------\n"));
2803:     PetscCall(VecView(g3, mviewer));
2804:   }
2805:   PetscCall(VecDestroy(&g1));
2806:   PetscCall(VecDestroy(&g2));
2807:   PetscCall(VecDestroy(&g3));

2809:   if (complete_print) {
2810:     PetscCall(PetscViewerPopFormat(mviewer));
2811:     PetscCall(PetscViewerDestroy(&mviewer));
2812:   }
2813:   PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2814:   PetscFunctionReturn(PETSC_SUCCESS);
2815: }

2817: /*@
2818:   SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians

2820:   Collective

2822:   Input Parameter:
2823: . snes - the `SNES` context

2825:   Output Parameters:
2826: + Jnorm    - the Frobenius norm of the computed Jacobian, or `NULL`
2827: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`

2829:   Options Database Keys:
2830: + -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.
2831: - -snes_test_jacobian_view        - display the user provided Jacobian, the finite difference Jacobian and the difference

2833:   Level: developer

2835:   Note:
2836:   Directions and norms are printed to stdout if `diffNorm` is `NULL`.

2838: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2839: @*/
2840: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2841: {
2842:   Mat               A, B, C, D, jacobian;
2843:   Vec               x = snes->vec_sol, f;
2844:   PetscReal         nrm, gnorm;
2845:   PetscReal         threshold = 1.e-5;
2846:   void             *functx;
2847:   PetscBool         complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2848:   PetscBool         silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2849:   PetscViewer       viewer, mviewer;
2850:   MPI_Comm          comm;
2851:   PetscInt          tabs;
2852:   static PetscBool  directionsprinted = PETSC_FALSE;
2853:   PetscViewerFormat format;

2855:   PetscFunctionBegin;
2856:   PetscObjectOptionsBegin((PetscObject)snes);
2857:   PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2858:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2859:   PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2860:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2861:   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));
2862:   PetscOptionsEnd();

2864:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2865:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2866:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2867:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2868:   if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Jacobian -------------\n"));
2869:   if (!complete_print && !silent && !directionsprinted) {
2870:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2871:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2872:   }
2873:   if (!directionsprinted && !silent) {
2874:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2875:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2876:     directionsprinted = PETSC_TRUE;
2877:   }
2878:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2880:   PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2881:   if (!flg) jacobian = snes->jacobian;
2882:   else jacobian = snes->jacobian_pre;

2884:   if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2885:   else PetscCall(PetscObjectReference((PetscObject)x));
2886:   PetscCall(VecDuplicate(x, &f));

2888:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2889:   PetscCall(SNESComputeFunction(snes, x, f));
2890:   PetscCall(VecDestroy(&f));
2891:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2892:   while (jacobian) {
2893:     Mat JT = NULL, Jsave = NULL;

2895:     if (istranspose) {
2896:       PetscCall(MatCreateTranspose(jacobian, &JT));
2897:       Jsave    = jacobian;
2898:       jacobian = JT;
2899:     }
2900:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2901:     if (flg) {
2902:       A = jacobian;
2903:       PetscCall(PetscObjectReference((PetscObject)A));
2904:     } else {
2905:       PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2906:     }

2908:     PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2909:     PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

2911:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2912:     PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));

2914:     PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2915:     PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2916:     PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2917:     PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2918:     PetscCall(MatDestroy(&D));
2919:     if (!gnorm) gnorm = 1; /* just in case */
2920:     if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2921:     if (complete_print) {
2922:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded Jacobian ----------\n"));
2923:       PetscCall(MatView(A, mviewer));
2924:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference Jacobian ----------\n"));
2925:       PetscCall(MatView(B, mviewer));
2926:     }

2928:     if (threshold_print || complete_print) {
2929:       PetscInt           Istart, Iend, *ccols, bncols, cncols, j, row;
2930:       PetscScalar       *cvals;
2931:       const PetscInt    *bcols;
2932:       const PetscScalar *bvals;

2934:       PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2935:       PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

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

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

2974:   if (Jnorm) *Jnorm = gnorm;
2975:   if (diffNorm) *diffNorm = nrm;
2976:   PetscFunctionReturn(PETSC_SUCCESS);
2977: }

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

2982:   Collective

2984:   Input Parameters:
2985: + snes - the `SNES` context
2986: - X    - input vector

2988:   Output Parameters:
2989: + A - Jacobian matrix
2990: - B - optional matrix for building the preconditioner, usually the same as `A`

2992:   Options Database Keys:
2993: + -snes_lag_preconditioner lag          - how often to rebuild preconditioner
2994: . -snes_lag_jacobian lag                - how often to rebuild Jacobian
2995: . -snes_test_jacobian [threshold]       - compare the user provided Jacobian with one compute via finite differences to check for errors.
2996:                                           If a threshold is given, display only those entries whose difference is greater than the threshold.
2997: . -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
2998: . -snes_compare_explicit                - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2999: . -snes_compare_explicit_draw           - Compare the computed Jacobian to the finite difference Jacobian and draw the result
3000: . -snes_compare_explicit_contour        - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
3001: . -snes_compare_operator                - Make the comparison options above use the operator instead of the matrix used to construct the preconditioner
3002: . -snes_compare_coloring                - Compute the finite difference Jacobian using coloring and display norms of difference
3003: . -snes_compare_coloring_display        - Compute the finite difference Jacobian using coloring and display verbose differences
3004: . -snes_compare_coloring_threshold      - Display only those matrix entries that differ by more than a given threshold
3005: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3006: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3007: . -snes_compare_coloring_draw           - Compute the finite difference Jacobian using coloring and draw differences
3008: - -snes_compare_coloring_draw_contour   - Compute the finite difference Jacobian using coloring and show contours of matrices and differences

3010:   Level: developer

3012:   Note:
3013:   Most users should not need to explicitly call this routine, as it
3014:   is used internally within the nonlinear solvers.

3016:   Developer Note:
3017:   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
3018:   with the `SNESType` of test that has been removed.

3020: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
3021:           `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
3022: @*/
3023: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
3024: {
3025:   PetscBool flag;
3026:   DM        dm;
3027:   DMSNES    sdm;
3028:   KSP       ksp;

3030:   PetscFunctionBegin;
3033:   PetscCheckSameComm(snes, 1, X, 2);
3034:   PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
3035:   PetscCall(SNESGetDM(snes, &dm));
3036:   PetscCall(DMGetDMSNES(dm, &sdm));

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

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

3075:   PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
3076:   PetscCall(VecLockReadPush(X));
3077:   {
3078:     void           *ctx;
3079:     SNESJacobianFn *J;
3080:     PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
3081:     PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
3082:   }
3083:   PetscCall(VecLockReadPop(X));
3084:   PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));

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

3089:   /* the next line ensures that snes->ksp exists */
3090:   PetscCall(SNESGetKSP(snes, &ksp));
3091:   if (snes->lagpreconditioner == -2) {
3092:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3093:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3094:     snes->lagpreconditioner = -1;
3095:   } else if (snes->lagpreconditioner == -1) {
3096:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3097:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3098:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3099:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3100:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3101:   } else {
3102:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3103:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3104:   }

3106:   /* monkey business to allow testing Jacobians in multilevel solvers.
3107:      This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3108:   {
3109:     Vec xsave            = snes->vec_sol;
3110:     Mat jacobiansave     = snes->jacobian;
3111:     Mat jacobian_presave = snes->jacobian_pre;

3113:     snes->vec_sol      = X;
3114:     snes->jacobian     = A;
3115:     snes->jacobian_pre = B;
3116:     if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3117:     if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));

3119:     snes->vec_sol      = xsave;
3120:     snes->jacobian     = jacobiansave;
3121:     snes->jacobian_pre = jacobian_presave;
3122:   }

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

3196:       PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3197:       PetscCall(MatColoringCreate(Bfd, &coloring));
3198:       PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3199:       PetscCall(MatColoringSetFromOptions(coloring));
3200:       PetscCall(MatColoringApply(coloring, &iscoloring));
3201:       PetscCall(MatColoringDestroy(&coloring));
3202:       PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3203:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3204:       PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3205:       PetscCall(ISColoringDestroy(&iscoloring));

3207:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3208:       PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3209:       PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3210:       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3211:       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3212:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3213:       PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3214:       PetscCall(MatFDColoringDestroy(&matfdcoloring));

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

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

3287: /*@C
3288:   SNESSetJacobian - Sets the function to compute Jacobian as well as the
3289:   location to store the matrix.

3291:   Logically Collective

3293:   Input Parameters:
3294: + snes - the `SNES` context
3295: . Amat - the matrix that defines the (approximate) Jacobian
3296: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3297: . J    - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3298: - ctx  - [optional] user-defined context for private data for the
3299:          Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)

3301:   Level: beginner

3303:   Notes:
3304:   If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3305:   each matrix.

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

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

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

3316: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3317:           `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3318: @*/
3319: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3320: {
3321:   DM dm;

3323:   PetscFunctionBegin;
3327:   if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3328:   if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3329:   /* update DMSNES
3330:      We support incremental information; so update the function context only if both Amat and Pmat are not specified
3331:      (which allows to disable the callbacks when both J and ctx are NULL),
3332:      or, if any of the mats is specified, when at least one of J and ctx is not NULL */
3333:   PetscCall(SNESGetDM(snes, &dm));
3334:   if ((!Amat && !Pmat) || J || ctx) PetscCall(DMSNESSetJacobian(dm, J, ctx));
3335:   if (Amat) {
3336:     PetscCall(PetscObjectReference((PetscObject)Amat));
3337:     PetscCall(MatDestroy(&snes->jacobian));

3339:     snes->jacobian = Amat;
3340:   }
3341:   if (Pmat) {
3342:     PetscCall(PetscObjectReference((PetscObject)Pmat));
3343:     PetscCall(MatDestroy(&snes->jacobian_pre));

3345:     snes->jacobian_pre = Pmat;
3346:   }
3347:   PetscFunctionReturn(PETSC_SUCCESS);
3348: }

3350: /*@C
3351:   SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3352:   provided context for evaluating the Jacobian.

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

3356:   Input Parameter:
3357: . snes - the nonlinear solver context

3359:   Output Parameters:
3360: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3361: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3362: . J    - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3363: - ctx  - location to stash Jacobian ctx (or `NULL`)

3365:   Level: advanced

3367: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3368: @*/
3369: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3370: {
3371:   DM dm;

3373:   PetscFunctionBegin;
3375:   if (Amat) *Amat = snes->jacobian;
3376:   if (Pmat) *Pmat = snes->jacobian_pre;
3377:   PetscCall(SNESGetDM(snes, &dm));
3378:   PetscCall(DMSNESGetJacobian(dm, J, ctx));
3379:   PetscFunctionReturn(PETSC_SUCCESS);
3380: }

3382: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3383: {
3384:   DM     dm;
3385:   DMSNES sdm;

3387:   PetscFunctionBegin;
3388:   PetscCall(SNESGetDM(snes, &dm));
3389:   PetscCall(DMGetDMSNES(dm, &sdm));
3390:   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3391:     DM        dm;
3392:     PetscBool isdense, ismf;

3394:     PetscCall(SNESGetDM(snes, &dm));
3395:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3396:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3397:     if (isdense) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3398:     else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3399:   }
3400:   PetscFunctionReturn(PETSC_SUCCESS);
3401: }

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

3407:   Collective

3409:   Input Parameter:
3410: . snes - the `SNES` context

3412:   Level: advanced

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

3421: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3422: @*/
3423: PetscErrorCode SNESSetUp(SNES snes)
3424: {
3425:   DM             dm;
3426:   DMSNES         sdm;
3427:   SNESLineSearch linesearch, pclinesearch;
3428:   void          *lsprectx, *lspostctx;
3429:   PetscBool      mf_operator, mf;
3430:   Vec            f, fpc;
3431:   void          *funcctx;
3432:   void          *jacctx, *appctx;
3433:   Mat            j, jpre;
3434:   PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3435:   PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3436:   SNESFunctionFn *func;
3437:   SNESJacobianFn *jac;

3439:   PetscFunctionBegin;
3441:   if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3442:   PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));

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

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

3448:   PetscCall(SNESGetDM(snes, &dm));
3449:   PetscCall(DMGetDMSNES(dm, &sdm));
3450:   PetscCall(SNESSetDefaultComputeJacobian(snes));

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

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

3456:   if (snes->linesearch) {
3457:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3458:     PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3459:   }

3461:   PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3462:   if (snes->npc && snes->npcside == PC_LEFT) {
3463:     snes->mf          = PETSC_TRUE;
3464:     snes->mf_operator = PETSC_FALSE;
3465:   }
3466:   if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));
3467:   if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));

3469:   if (snes->npc) {
3470:     SNESNormSchedule npc_norm_schedule;

3472:     /* copy the DM over and the functions if NPC DM is not present */
3473:     if (!snes->npc->dm) {
3474:       PetscCall(SNESGetDM(snes, &dm));
3475:       PetscCall(SNESSetDM(snes->npc, dm));

3477:       PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3478:       PetscCall(VecDuplicate(f, &fpc));
3479:       PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3480:       PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3481:       PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3482:       PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3483:       PetscCall(VecDestroy(&fpc));

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

3488:       /* Propagate app context if not present */
3489:       PetscCall(SNESGetApplicationContext(snes->npc, &appctx));
3490:       if (!appctx && !snes->npc->ops->ctxcompute) {
3491:         if (snes->ops->ctxcompute) {
3492:           PetscCall(SNESSetComputeApplicationContext(snes->npc, snes->ops->ctxcompute, snes->ops->ctxdestroy));
3493:         } else {
3494:           PetscCall(SNESGetApplicationContext(snes, &appctx));
3495:           PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3496:         }
3497:       }
3498:     }

3500:     /* Set default norm schedule for NPC if not yet set */
3501:     PetscCall(SNESGetNormSchedule(snes->npc, &npc_norm_schedule));
3502:     if (npc_norm_schedule == SNES_NORM_DEFAULT) {
3503:       if (snes->npcside == PC_RIGHT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3504:       else if (snes->npcside == PC_LEFT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3505:     }

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

3509:     /* copy the line search context over */
3510:     if (snes->dm == snes->npc->dm && snes->linesearch && snes->npc->linesearch) {
3511:       PetscCall(SNESGetLineSearch(snes, &linesearch));
3512:       PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3513:       PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3514:       PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3515:       PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3516:       PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3517:       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3518:     }
3519:   }

3521:   snes->jac_iter = 0;
3522:   snes->pre_iter = 0;

3524:   PetscTryTypeMethod(snes, setup);

3526:   PetscCall(SNESSetDefaultComputeJacobian(snes));

3528:   if (snes->npc && snes->npcside == PC_LEFT) {
3529:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3530:       if (snes->linesearch) {
3531:         PetscCall(SNESGetLineSearch(snes, &linesearch));
3532:         PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3533:       }
3534:     }
3535:   }
3536:   PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3537:   snes->setupcalled = PETSC_TRUE;
3538:   PetscFunctionReturn(PETSC_SUCCESS);
3539: }

3541: /*@
3542:   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

3544:   Collective

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

3549:   Level: intermediate

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

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

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

3558: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3559: @*/
3560: PetscErrorCode SNESReset(SNES snes)
3561: {
3562:   PetscFunctionBegin;
3564:   if (snes->ops->ctxdestroy && snes->ctx) {
3565:     PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3566:     snes->ctx = NULL;
3567:   }
3568:   if (snes->npc) PetscCall(SNESReset(snes->npc));

3570:   PetscTryTypeMethod(snes, reset);
3571:   if (snes->ksp) PetscCall(KSPReset(snes->ksp));

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

3575:   PetscCall(VecDestroy(&snes->vec_rhs));
3576:   PetscCall(VecDestroy(&snes->vec_sol));
3577:   PetscCall(VecDestroy(&snes->vec_sol_update));
3578:   PetscCall(VecDestroy(&snes->vec_func));
3579:   PetscCall(MatDestroy(&snes->jacobian));
3580:   PetscCall(MatDestroy(&snes->jacobian_pre));
3581:   PetscCall(MatDestroy(&snes->picard));
3582:   PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3583:   PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));

3585:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3587:   snes->nwork = snes->nvwork = 0;
3588:   snes->setupcalled          = PETSC_FALSE;
3589:   PetscFunctionReturn(PETSC_SUCCESS);
3590: }

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

3596:   Collective

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

3601:   Level: intermediate

3603: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3604: @*/
3605: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3606: {
3607:   PetscFunctionBegin;
3609:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
3610:     if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3611:   }
3612:   snes->numberreasonviews = 0;
3613:   PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3614:   PetscFunctionReturn(PETSC_SUCCESS);
3615: }

3617: /*@
3618:   SNESDestroy - Destroys the nonlinear solver context that was created
3619:   with `SNESCreate()`.

3621:   Collective

3623:   Input Parameter:
3624: . snes - the `SNES` context

3626:   Level: beginner

3628: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3629: @*/
3630: PetscErrorCode SNESDestroy(SNES *snes)
3631: {
3632:   DM dm;

3634:   PetscFunctionBegin;
3635:   if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3637:   if (--((PetscObject)*snes)->refct > 0) {
3638:     *snes = NULL;
3639:     PetscFunctionReturn(PETSC_SUCCESS);
3640:   }

3642:   PetscCall(SNESReset(*snes));
3643:   PetscCall(SNESDestroy(&(*snes)->npc));

3645:   /* if memory was published with SAWs then destroy it */
3646:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3647:   PetscTryTypeMethod(*snes, destroy);

3649:   dm = (*snes)->dm;
3650:   while (dm) {
3651:     PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3652:     PetscCall(DMGetCoarseDM(dm, &dm));
3653:   }

3655:   PetscCall(DMDestroy(&(*snes)->dm));
3656:   PetscCall(KSPDestroy(&(*snes)->ksp));
3657:   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));

3659:   PetscCall(PetscFree((*snes)->kspconvctx));
3660:   if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3661:   if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3662:   PetscCall(SNESMonitorCancel(*snes));
3663:   PetscCall(SNESConvergedReasonViewCancel(*snes));
3664:   PetscCall(PetscHeaderDestroy(snes));
3665:   PetscFunctionReturn(PETSC_SUCCESS);
3666: }

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

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

3673:   Logically Collective

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

3680:   Options Database Keys:
3681: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple `SNESSolve()`
3682: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3683: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3684: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3686:   Level: intermediate

3688:   Notes:
3689:   The default is 1

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

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

3695: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3696:           `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3697: @*/
3698: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3699: {
3700:   PetscFunctionBegin;
3703:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3704:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3705:   snes->lagpreconditioner = lag;
3706:   PetscFunctionReturn(PETSC_SUCCESS);
3707: }

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

3712:   Logically Collective

3714:   Input Parameters:
3715: + snes  - the `SNES` context
3716: - steps - the number of refinements to do, defaults to 0

3718:   Options Database Key:
3719: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess

3721:   Level: intermediate

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

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

3728: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3729:           `SNESSetDM()`, `SNESSolve()`
3730: @*/
3731: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3732: {
3733:   PetscFunctionBegin;
3736:   snes->gridsequence = steps;
3737:   PetscFunctionReturn(PETSC_SUCCESS);
3738: }

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

3743:   Logically Collective

3745:   Input Parameter:
3746: . snes - the `SNES` context

3748:   Output Parameter:
3749: . steps - the number of refinements to do, defaults to 0

3751:   Level: intermediate

3753: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3754: @*/
3755: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3756: {
3757:   PetscFunctionBegin;
3759:   *steps = snes->gridsequence;
3760:   PetscFunctionReturn(PETSC_SUCCESS);
3761: }

3763: /*@
3764:   SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt

3766:   Not Collective

3768:   Input Parameter:
3769: . snes - the `SNES` context

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

3775:   Level: intermediate

3777:   Notes:
3778:   The default is 1

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

3782: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3783: @*/
3784: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3785: {
3786:   PetscFunctionBegin;
3788:   *lag = snes->lagpreconditioner;
3789:   PetscFunctionReturn(PETSC_SUCCESS);
3790: }

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

3796:   Logically Collective

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

3803:   Options Database Keys:
3804: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3805: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3806: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3807: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag.

3809:   Level: intermediate

3811:   Notes:
3812:   The default is 1

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

3816:   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
3817:   at the next Newton step but never again (unless it is reset to another value)

3819: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3820: @*/
3821: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3822: {
3823:   PetscFunctionBegin;
3825:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3826:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3828:   snes->lagjacobian = lag;
3829:   PetscFunctionReturn(PETSC_SUCCESS);
3830: }

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

3835:   Not Collective

3837:   Input Parameter:
3838: . snes - the `SNES` context

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

3844:   Level: intermediate

3846:   Notes:
3847:   The default is 1

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

3851: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3852: @*/
3853: PetscErrorCode SNESGetLagJacobian(SNES snes, PetscInt *lag)
3854: {
3855:   PetscFunctionBegin;
3857:   *lag = snes->lagjacobian;
3858:   PetscFunctionReturn(PETSC_SUCCESS);
3859: }

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

3864:   Logically collective

3866:   Input Parameters:
3867: + snes - the `SNES` context
3868: - flg  - jacobian lagging persists if true

3870:   Options Database Keys:
3871: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3872: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3873: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3874: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3876:   Level: advanced

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

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

3885: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3886: @*/
3887: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3888: {
3889:   PetscFunctionBegin;
3892:   snes->lagjac_persist = flg;
3893:   PetscFunctionReturn(PETSC_SUCCESS);
3894: }

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

3899:   Logically Collective

3901:   Input Parameters:
3902: + snes - the `SNES` context
3903: - flg  - preconditioner lagging persists if true

3905:   Options Database Keys:
3906: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3907: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3908: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3909: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3911:   Level: developer

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

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

3920: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3921: @*/
3922: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3923: {
3924:   PetscFunctionBegin;
3927:   snes->lagpre_persist = flg;
3928:   PetscFunctionReturn(PETSC_SUCCESS);
3929: }

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

3934:   Logically Collective

3936:   Input Parameters:
3937: + snes  - the `SNES` context
3938: - force - `PETSC_TRUE` require at least one iteration

3940:   Options Database Key:
3941: . -snes_force_iteration force - Sets forcing an iteration

3943:   Level: intermediate

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

3948: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3949: @*/
3950: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3951: {
3952:   PetscFunctionBegin;
3954:   snes->forceiteration = force;
3955:   PetscFunctionReturn(PETSC_SUCCESS);
3956: }

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

3961:   Logically Collective

3963:   Input Parameter:
3964: . snes - the `SNES` context

3966:   Output Parameter:
3967: . force - `PETSC_TRUE` requires at least one iteration.

3969:   Level: intermediate

3971: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3972: @*/
3973: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3974: {
3975:   PetscFunctionBegin;
3977:   *force = snes->forceiteration;
3978:   PetscFunctionReturn(PETSC_SUCCESS);
3979: }

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

3984:   Logically Collective

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

3994:   Options Database Keys:
3995: + -snes_atol abstol    - Sets `abstol`
3996: . -snes_rtol rtol      - Sets `rtol`
3997: . -snes_stol stol      - Sets `stol`
3998: . -snes_max_it maxit   - Sets `maxit`
3999: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)

4001:   Level: intermediate

4003:   Note:
4004:   All parameters must be non-negative

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

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

4011:   Fortran Note:
4012:   Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`

4014: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
4015: @*/
4016: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
4017: {
4018:   PetscFunctionBegin;

4026:   if (abstol == (PetscReal)PETSC_DETERMINE) {
4027:     snes->abstol = snes->default_abstol;
4028:   } else if (abstol != (PetscReal)PETSC_CURRENT) {
4029:     PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
4030:     snes->abstol = abstol;
4031:   }

4033:   if (rtol == (PetscReal)PETSC_DETERMINE) {
4034:     snes->rtol = snes->default_rtol;
4035:   } else if (rtol != (PetscReal)PETSC_CURRENT) {
4036:     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);
4037:     snes->rtol = rtol;
4038:   }

4040:   if (stol == (PetscReal)PETSC_DETERMINE) {
4041:     snes->stol = snes->default_stol;
4042:   } else if (stol != (PetscReal)PETSC_CURRENT) {
4043:     PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
4044:     snes->stol = stol;
4045:   }

4047:   if (maxit == PETSC_DETERMINE) {
4048:     snes->max_its = snes->default_max_its;
4049:   } else if (maxit == PETSC_UNLIMITED) {
4050:     snes->max_its = PETSC_INT_MAX;
4051:   } else if (maxit != PETSC_CURRENT) {
4052:     PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
4053:     snes->max_its = maxit;
4054:   }

4056:   if (maxf == PETSC_DETERMINE) {
4057:     snes->max_funcs = snes->default_max_funcs;
4058:   } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
4059:     snes->max_funcs = PETSC_UNLIMITED;
4060:   } else if (maxf != PETSC_CURRENT) {
4061:     PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
4062:     snes->max_funcs = maxf;
4063:   }
4064:   PetscFunctionReturn(PETSC_SUCCESS);
4065: }

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

4070:   Logically Collective

4072:   Input Parameters:
4073: + snes   - the `SNES` context
4074: - 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
4075:            is stopped due to divergence.

4077:   Options Database Key:
4078: . -snes_divergence_tolerance divtol - Sets `divtol`

4080:   Level: intermediate

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

4085:   Fortran Note:
4086:   Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`

4088: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
4089: @*/
4090: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
4091: {
4092:   PetscFunctionBegin;

4096:   if (divtol == (PetscReal)PETSC_DETERMINE) {
4097:     snes->divtol = snes->default_divtol;
4098:   } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
4099:     snes->divtol = PETSC_UNLIMITED;
4100:   } else if (divtol != (PetscReal)PETSC_CURRENT) {
4101:     PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
4102:     snes->divtol = divtol;
4103:   }
4104:   PetscFunctionReturn(PETSC_SUCCESS);
4105: }

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

4110:   Not Collective

4112:   Input Parameter:
4113: . snes - the `SNES` context

4115:   Output Parameters:
4116: + atol  - the absolute convergence tolerance
4117: . rtol  - the relative convergence tolerance
4118: . stol  - convergence tolerance in terms of the norm of the change in the solution between steps
4119: . maxit - the maximum number of iterations allowed
4120: - maxf  - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound

4122:   Level: intermediate

4124:   Notes:
4125:   See `SNESSetTolerances()` for details on the parameters.

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

4129: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4130: @*/
4131: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4132: {
4133:   PetscFunctionBegin;
4135:   if (atol) *atol = snes->abstol;
4136:   if (rtol) *rtol = snes->rtol;
4137:   if (stol) *stol = snes->stol;
4138:   if (maxit) *maxit = snes->max_its;
4139:   if (maxf) *maxf = snes->max_funcs;
4140:   PetscFunctionReturn(PETSC_SUCCESS);
4141: }

4143: /*@
4144:   SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

4146:   Not Collective

4148:   Input Parameters:
4149: + snes   - the `SNES` context
4150: - divtol - divergence tolerance

4152:   Level: intermediate

4154: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4155: @*/
4156: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4157: {
4158:   PetscFunctionBegin;
4160:   if (divtol) *divtol = snes->divtol;
4161:   PetscFunctionReturn(PETSC_SUCCESS);
4162: }

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

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

4169:   Collective

4171:   Input Parameters:
4172: + snes   - the `SNES` context
4173: . n      - the iteration number
4174: . rnorm  - the 2-norm of the residual
4175: - monctx - a `PetscViewer` of type `PETSCVIEWERDRAW` set up with `PetscViewerMonitorLGSetUp()`

4177:   Level: intermediate

4179:   Note:
4180:   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.

4182: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`, `SNESMonitorDefault()`, `PetscViewerDrawGetDrawLG()`, `PetscDrawLG`
4183: @*/
4184: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4185: {
4186:   PetscDrawLG      lg;
4187:   PetscReal        x, y, per;
4188:   PetscViewer      v = (PetscViewer)monctx;
4189:   static PetscReal prev; /* should be in the context */
4190:   PetscDraw        draw;

4192:   PetscFunctionBegin;
4194:   PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4195:   if (!n) PetscCall(PetscDrawLGReset(lg));
4196:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4197:   PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4198:   x = (PetscReal)n;
4199:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4200:   else y = -15.0;
4201:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4202:   if (n < 20 || !(n % 5) || snes->reason) {
4203:     PetscCall(PetscDrawLGDraw(lg));
4204:     PetscCall(PetscDrawLGSave(lg));
4205:   }

4207:   PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4208:   if (!n) PetscCall(PetscDrawLGReset(lg));
4209:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4210:   PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4211:   PetscCall(SNESMonitorRange_Private(snes, n, &per));
4212:   x = (PetscReal)n;
4213:   y = 100.0 * per;
4214:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4215:   if (n < 20 || !(n % 5) || snes->reason) {
4216:     PetscCall(PetscDrawLGDraw(lg));
4217:     PetscCall(PetscDrawLGSave(lg));
4218:   }

4220:   PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4221:   if (!n) {
4222:     prev = rnorm;
4223:     PetscCall(PetscDrawLGReset(lg));
4224:   }
4225:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4226:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4227:   x = (PetscReal)n;
4228:   y = (prev - rnorm) / prev;
4229:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4230:   if (n < 20 || !(n % 5) || snes->reason) {
4231:     PetscCall(PetscDrawLGDraw(lg));
4232:     PetscCall(PetscDrawLGSave(lg));
4233:   }

4235:   PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4236:   if (!n) PetscCall(PetscDrawLGReset(lg));
4237:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4238:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4239:   x = (PetscReal)n;
4240:   y = (prev - rnorm) / (prev * per);
4241:   if (n > 2) { /*skip initial crazy value */
4242:     PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4243:   }
4244:   if (n < 20 || !(n % 5) || snes->reason) {
4245:     PetscCall(PetscDrawLGDraw(lg));
4246:     PetscCall(PetscDrawLGSave(lg));
4247:   }
4248:   prev = rnorm;
4249:   PetscFunctionReturn(PETSC_SUCCESS);
4250: }

4252: /*@
4253:   SNESConverged - Run the convergence test and update the `SNESConvergedReason`.

4255:   Collective

4257:   Input Parameters:
4258: + snes  - the `SNES` context
4259: . it    - current iteration
4260: . xnorm - 2-norm of current iterate
4261: . snorm - 2-norm of current step
4262: - fnorm - 2-norm of function

4264:   Level: developer

4266:   Note:
4267:   This routine is called by the `SNESSolve()` implementations.
4268:   It does not typically need to be called by the user.

4270: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4271: @*/
4272: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4273: {
4274:   PetscFunctionBegin;
4275:   if (!snes->reason) {
4276:     if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4277:     if (it == snes->max_its && !snes->reason) {
4278:       if (snes->normschedule == SNES_NORM_ALWAYS) {
4279:         PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4280:         snes->reason = SNES_DIVERGED_MAX_IT;
4281:       } else snes->reason = SNES_CONVERGED_ITS;
4282:     }
4283:   }
4284:   PetscFunctionReturn(PETSC_SUCCESS);
4285: }

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

4290:   Collective

4292:   Input Parameters:
4293: + snes  - nonlinear solver context obtained from `SNESCreate()`
4294: . iter  - current iteration number
4295: - rnorm - current relative norm of the residual

4297:   Level: developer

4299:   Note:
4300:   This routine is called by the `SNESSolve()` implementations.
4301:   It does not typically need to be called by the user.

4303: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4304: @*/
4305: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4306: {
4307:   PetscInt i, n = snes->numbermonitors;

4309:   PetscFunctionBegin;
4310:   PetscCall(VecLockReadPush(snes->vec_sol));
4311:   for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4312:   PetscCall(VecLockReadPop(snes->vec_sol));
4313:   PetscFunctionReturn(PETSC_SUCCESS);
4314: }

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

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

4321:      Synopsis:
4322: #include <petscsnes.h>
4323:     PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)

4325:      Collective

4327:     Input Parameters:
4328: +    snes - the `SNES` context
4329: .    its - iteration number
4330: .    norm - 2-norm function value (may be estimated)
4331: -    mctx - [optional] monitoring context

4333:    Level: advanced

4335: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4336: M*/

4338: /*@C
4339:   SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4340:   iteration of the `SNES` nonlinear solver to display the iteration's
4341:   progress.

4343:   Logically Collective

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

4351:   Calling sequence of f:
4352: + snes  - the `SNES` object
4353: . it    - the current iteration
4354: . rnorm - norm of the residual
4355: - mctx  - the optional monitor context

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

4363:   Level: intermediate

4365:   Note:
4366:   Several different monitoring routines may be set by calling
4367:   `SNESMonitorSet()` multiple times; all will be called in the
4368:   order in which they were set.

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

4373: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4374: @*/
4375: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4376: {
4377:   PetscFunctionBegin;
4379:   for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4380:     PetscBool identical;

4382:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4383:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4384:   }
4385:   PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4386:   snes->monitor[snes->numbermonitors]          = f;
4387:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4388:   snes->monitorcontext[snes->numbermonitors++] = mctx;
4389:   PetscFunctionReturn(PETSC_SUCCESS);
4390: }

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

4395:   Logically Collective

4397:   Input Parameter:
4398: . snes - the `SNES` context

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

4405:   Level: intermediate

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

4410: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4411: @*/
4412: PetscErrorCode SNESMonitorCancel(SNES snes)
4413: {
4414:   PetscFunctionBegin;
4416:   for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4417:     if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4418:   }
4419:   snes->numbermonitors = 0;
4420:   PetscFunctionReturn(PETSC_SUCCESS);
4421: }

4423: /*@C
4424:   SNESSetConvergenceTest - Sets the function that is to be used
4425:   to test for convergence of the nonlinear iterative solution.

4427:   Logically Collective

4429:   Input Parameters:
4430: + snes    - the `SNES` context
4431: . func    - routine to test for convergence
4432: . ctx     - [optional] context for private data for the convergence routine  (may be `NULL`)
4433: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)

4435:   Calling sequence of func:
4436: + snes   - the `SNES` context
4437: . it     - the current iteration number
4438: . xnorm  - the norm of the new solution
4439: . snorm  - the norm of the step
4440: . fnorm  - the norm of the function value
4441: . reason - output, the reason convergence or divergence as declared
4442: - ctx    - the optional convergence test context

4444:   Level: advanced

4446: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4447: @*/
4448: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4449: {
4450:   PetscFunctionBegin;
4452:   if (!func) func = SNESConvergedSkip;
4453:   if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4454:   snes->ops->converged        = func;
4455:   snes->ops->convergeddestroy = destroy;
4456:   snes->cnvP                  = ctx;
4457:   PetscFunctionReturn(PETSC_SUCCESS);
4458: }

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

4463:   Not Collective

4465:   Input Parameter:
4466: . snes - the `SNES` context

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

4471:   Options Database Key:
4472: . -snes_converged_reason - prints the reason to standard out

4474:   Level: intermediate

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

4479: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4480: @*/
4481: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4482: {
4483:   PetscFunctionBegin;
4485:   PetscAssertPointer(reason, 2);
4486:   *reason = snes->reason;
4487:   PetscFunctionReturn(PETSC_SUCCESS);
4488: }

4490: /*@C
4491:   SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`

4493:   Not Collective

4495:   Input Parameter:
4496: . snes - the `SNES` context

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

4501:   Level: beginner

4503: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4504: @*/
4505: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char *strreason[])
4506: {
4507:   PetscFunctionBegin;
4509:   PetscAssertPointer(strreason, 2);
4510:   *strreason = SNESConvergedReasons[snes->reason];
4511:   PetscFunctionReturn(PETSC_SUCCESS);
4512: }

4514: /*@
4515:   SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.

4517:   Not Collective

4519:   Input Parameters:
4520: + snes   - the `SNES` context
4521: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4522:             manual pages for the individual convergence tests for complete lists

4524:   Level: developer

4526:   Developer Note:
4527:   Called inside the various `SNESSolve()` implementations

4529: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4530: @*/
4531: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4532: {
4533:   PetscFunctionBegin;
4535:   PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4536:   snes->reason = reason;
4537:   PetscFunctionReturn(PETSC_SUCCESS);
4538: }

4540: /*@
4541:   SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.

4543:   Logically Collective

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

4553:   Level: intermediate

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

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

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

4565: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4566: @*/
4567: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4568: {
4569:   PetscFunctionBegin;
4571:   if (a) PetscAssertPointer(a, 2);
4572:   if (its) PetscAssertPointer(its, 3);
4573:   if (!a) {
4574:     if (na == PETSC_DECIDE) na = 1000;
4575:     PetscCall(PetscCalloc2(na, &a, na, &its));
4576:     snes->conv_hist_alloc = PETSC_TRUE;
4577:   }
4578:   snes->conv_hist       = a;
4579:   snes->conv_hist_its   = its;
4580:   snes->conv_hist_max   = (size_t)na;
4581:   snes->conv_hist_len   = 0;
4582:   snes->conv_hist_reset = reset;
4583:   PetscFunctionReturn(PETSC_SUCCESS);
4584: }

4586: #if PetscDefined(HAVE_MATLAB)
4587:   #include <engine.h> /* MATLAB include file */
4588:   #include <mex.h>    /* MATLAB include file */

4590: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4591: {
4592:   mxArray   *mat;
4593:   PetscReal *ar;

4595:   mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4596:   ar  = (PetscReal *)mxGetData(mat);
4597:   for (PetscInt i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4598:   return mat;
4599: }
4600: #endif

4602: /*@C
4603:   SNESGetConvergenceHistory - Gets the arrays used to hold the convergence history.

4605:   Not Collective

4607:   Input Parameter:
4608: . snes - iterative context obtained from `SNESCreate()`

4610:   Output Parameters:
4611: + a   - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4612: . its - integer array holds the number of linear iterations (or
4613:          negative if not converged) for each solve.
4614: - na  - size of `a` and `its`

4616:   Level: intermediate

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

4623:   Fortran Notes:
4624:   Return the arrays with ``SNESRestoreConvergenceHistory()`

4626:   Use the arguments
4627: .vb
4628:   PetscReal, pointer :: a(:)
4629:   PetscInt, pointer :: its(:)
4630: .ve

4632: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4633: @*/
4634: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4635: {
4636:   PetscFunctionBegin;
4638:   if (a) *a = snes->conv_hist;
4639:   if (its) *its = snes->conv_hist_its;
4640:   if (na) *na = (PetscInt)snes->conv_hist_len;
4641:   PetscFunctionReturn(PETSC_SUCCESS);
4642: }

4644: /*@C
4645:   SNESSetUpdate - Sets the general-purpose update function called
4646:   at the beginning of every iteration of the nonlinear solve. Specifically
4647:   it is called just before the Jacobian is "evaluated" and after the function
4648:   evaluation.

4650:   Logically Collective

4652:   Input Parameters:
4653: + snes - The nonlinear solver context
4654: - func - The update function; for calling sequence see `SNESUpdateFn`

4656:   Level: advanced

4658:   Notes:
4659:   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
4660:   to `SNESSetFunction()`, or `SNESSetPicard()`
4661:   This is not used by most users, and it is intended to provide a general hook that is run
4662:   right before the direction step is computed.

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

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

4685: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4686:          `SNESMonitorSet()`
4687: @*/
4688: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4689: {
4690:   PetscFunctionBegin;
4692:   snes->ops->update = func;
4693:   PetscFunctionReturn(PETSC_SUCCESS);
4694: }

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

4699:   Collective

4701:   Input Parameters:
4702: + snes   - iterative context obtained from `SNESCreate()`
4703: - viewer - the viewer to display the reason

4705:   Options Database Keys:
4706: + -snes_converged_reason          - print reason for converged or diverged, also prints number of iterations
4707: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged

4709:   Level: beginner

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

4715: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4716:           `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4717:           `SNESConvergedReasonViewFromOptions()`,
4718:           `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4719: @*/
4720: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4721: {
4722:   PetscViewerFormat format;
4723:   PetscBool         isAscii;

4725:   PetscFunctionBegin;
4726:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4727:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4728:   if (isAscii) {
4729:     PetscCall(PetscViewerGetFormat(viewer, &format));
4730:     PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4731:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4732:       DM       dm;
4733:       Vec      u;
4734:       PetscDS  prob;
4735:       PetscInt Nf;
4736:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4737:       void    **exactCtx;
4738:       PetscReal error;

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

4769: /*@C
4770:   SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4771:   end of the nonlinear solver to display the convergence reason of the nonlinear solver.

4773:   Logically Collective

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

4781:   Calling sequence of `f`:
4782: + snes - the `SNES` context
4783: - vctx - [optional] context for private data for the function

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

4790:   Level: intermediate

4792:   Note:
4793:   Several different converged reason view routines may be set by calling
4794:   `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4795:   order in which they were set.

4797: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4798:           `PetscCtxDestroyFn`
4799: @*/
4800: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4801: {
4802:   PetscFunctionBegin;
4804:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4805:     PetscBool identical;

4807:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4808:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4809:   }
4810:   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4811:   snes->reasonview[snes->numberreasonviews]          = f;
4812:   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4813:   snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4814:   PetscFunctionReturn(PETSC_SUCCESS);
4815: }

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

4821:   Collective

4823:   Input Parameter:
4824: . snes - the `SNES` object

4826:   Level: advanced

4828:   Note:
4829:   This function has a different API and behavior than `PetscObjectViewFromOptions()`

4831: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4832:           `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4833: @*/
4834: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4835: {
4836:   static PetscBool incall = PETSC_FALSE;

4838:   PetscFunctionBegin;
4839:   if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4840:   incall = PETSC_TRUE;

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

4845:   /* Call PETSc default routine if users ask for it */
4846:   if (snes->convergedreasonviewer) {
4847:     PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4848:     PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4849:     PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4850:   }
4851:   incall = PETSC_FALSE;
4852:   PetscFunctionReturn(PETSC_SUCCESS);
4853: }

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

4858:   Collective

4860:   Input Parameters:
4861: + snes - the `SNES` context
4862: . b    - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4863: - x    - the solution vector.

4865:   Level: beginner

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

4871: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4872:           `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4873:           `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4874: @*/
4875: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4876: {
4877:   PetscBool flg;
4878:   Vec       xcreated = NULL;
4879:   DM        dm;

4881:   PetscFunctionBegin;
4884:   if (x) PetscCheckSameComm(snes, 1, x, 3);
4886:   if (b) PetscCheckSameComm(snes, 1, b, 2);

4888:   /* High level operations using the nonlinear solver */
4889:   {
4890:     PetscViewer       viewer;
4891:     PetscViewerFormat format;
4892:     PetscInt          num;
4893:     PetscBool         flg;
4894:     static PetscBool  incall = PETSC_FALSE;

4896:     if (!incall) {
4897:       /* Estimate the convergence rate of the discretization */
4898:       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4899:       if (flg) {
4900:         PetscConvEst conv;
4901:         DM           dm;
4902:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4903:         PetscInt     Nf;

4905:         incall = PETSC_TRUE;
4906:         PetscCall(SNESGetDM(snes, &dm));
4907:         PetscCall(DMGetNumFields(dm, &Nf));
4908:         PetscCall(PetscCalloc1(Nf, &alpha));
4909:         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4910:         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4911:         PetscCall(PetscConvEstSetFromOptions(conv));
4912:         PetscCall(PetscConvEstSetUp(conv));
4913:         PetscCall(PetscConvEstGetConvRate(conv, alpha));
4914:         PetscCall(PetscViewerPushFormat(viewer, format));
4915:         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4916:         PetscCall(PetscViewerPopFormat(viewer));
4917:         PetscCall(PetscViewerDestroy(&viewer));
4918:         PetscCall(PetscConvEstDestroy(&conv));
4919:         PetscCall(PetscFree(alpha));
4920:         incall = PETSC_FALSE;
4921:       }
4922:       /* Adaptively refine the initial grid */
4923:       num = 1;
4924:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4925:       if (flg) {
4926:         DMAdaptor adaptor;

4928:         incall = PETSC_TRUE;
4929:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4930:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4931:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4932:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4933:         PetscCall(DMAdaptorSetUp(adaptor));
4934:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4935:         PetscCall(DMAdaptorDestroy(&adaptor));
4936:         incall = PETSC_FALSE;
4937:       }
4938:       /* Use grid sequencing to adapt */
4939:       num = 0;
4940:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4941:       if (num) {
4942:         DMAdaptor   adaptor;
4943:         const char *prefix;

4945:         incall = PETSC_TRUE;
4946:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4947:         PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4948:         PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4949:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4950:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4951:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4952:         PetscCall(DMAdaptorSetUp(adaptor));
4953:         PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4954:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4955:         PetscCall(DMAdaptorDestroy(&adaptor));
4956:         incall = PETSC_FALSE;
4957:       }
4958:     }
4959:   }
4960:   if (!x) x = snes->vec_sol;
4961:   if (!x) {
4962:     PetscCall(SNESGetDM(snes, &dm));
4963:     PetscCall(DMCreateGlobalVector(dm, &xcreated));
4964:     x = xcreated;
4965:   }
4966:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));

4968:   for (PetscInt grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4969:   for (PetscInt grid = 0; grid < snes->gridsequence + 1; grid++) {
4970:     /* set solution vector */
4971:     if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4972:     PetscCall(VecDestroy(&snes->vec_sol));
4973:     snes->vec_sol = x;
4974:     PetscCall(SNESGetDM(snes, &dm));

4976:     /* set affine vector if provided */
4977:     PetscCall(PetscObjectReference((PetscObject)b));
4978:     PetscCall(VecDestroy(&snes->vec_rhs));
4979:     snes->vec_rhs = b;

4981:     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");
4982:     PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
4983:     PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
4984:     if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
4985:     PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
4986:     PetscCall(SNESSetUp(snes));

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

4992:     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4993:     PetscCall(SNESResetCounters(snes));
4994:     snes->reason = SNES_CONVERGED_ITERATING;
4995:     PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
4996:     PetscUseTypeMethod(snes, solve);
4997:     PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
4998:     PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
4999:     snes->functiondomainerror  = PETSC_FALSE; /* clear the flag if it has been set */
5000:     snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
5001:     snes->jacobiandomainerror  = PETSC_FALSE; /* clear the flag if it has been set */

5003:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
5004:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

5011:     if (snes->errorifnotconverged) {
5012:       if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
5013:       PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
5014:     }
5015:     if (snes->reason < 0) break;
5016:     if (grid < snes->gridsequence) {
5017:       DM  fine;
5018:       Vec xnew;
5019:       Mat interp;

5021:       PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
5022:       PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
5023:       PetscCall(DMGetCoordinatesLocalSetUp(fine));
5024:       PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
5025:       PetscCall(DMCreateGlobalVector(fine, &xnew));
5026:       PetscCall(MatInterpolate(interp, x, xnew));
5027:       PetscCall(DMInterpolate(snes->dm, interp, fine));
5028:       PetscCall(MatDestroy(&interp));
5029:       x = xnew;

5031:       PetscCall(SNESReset(snes));
5032:       PetscCall(SNESSetDM(snes, fine));
5033:       PetscCall(SNESResetFromOptions(snes));
5034:       PetscCall(DMDestroy(&fine));
5035:       PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
5036:     }
5037:   }
5038:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
5039:   PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
5040:   PetscCall(DMMonitor(snes->dm));
5041:   PetscCall(SNESMonitorPauseFinal_Internal(snes));

5043:   PetscCall(VecDestroy(&xcreated));
5044:   PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
5045:   PetscFunctionReturn(PETSC_SUCCESS);
5046: }

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

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

5053:   Collective

5055:   Input Parameters:
5056: + snes - the `SNES` context
5057: - type - a known method

5059:   Options Database Key:
5060: . -snes_type type - Sets the method; see `SNESType`

5062:   Level: intermediate

5064:   Notes:
5065:   See `SNESType` for available methods (for instance)
5066: +    `SNESNEWTONLS` - Newton's method with line search
5067:   (systems of nonlinear equations)
5068: -    `SNESNEWTONTR` - Newton's method with trust region
5069:   (systems of nonlinear equations)

5071:   Normally, it is best to use the `SNESSetFromOptions()` command and then
5072:   set the `SNES` solver type from the options database rather than by using
5073:   this routine.  Using the options database provides the user with
5074:   maximum flexibility in evaluating the many nonlinear solvers.
5075:   The `SNESSetType()` routine is provided for those situations where it
5076:   is necessary to set the nonlinear solver independently of the command
5077:   line or options database.  This might be the case, for example, when
5078:   the choice of solver changes during the execution of the program,
5079:   and the user's application is taking responsibility for choosing the
5080:   appropriate method.

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

5086: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
5087: @*/
5088: PetscErrorCode SNESSetType(SNES snes, SNESType type)
5089: {
5090:   PetscBool match;
5091:   PetscErrorCode (*r)(SNES);

5093:   PetscFunctionBegin;
5095:   PetscAssertPointer(type, 2);

5097:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
5098:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

5100:   PetscCall(PetscFunctionListFind(SNESList, type, &r));
5101:   PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
5102:   /* Destroy the previous private SNES context */
5103:   PetscTryTypeMethod(snes, destroy);
5104:   /* Reinitialize type-specific function pointers in SNESOps structure */
5105:   snes->ops->reset          = NULL;
5106:   snes->ops->setup          = NULL;
5107:   snes->ops->solve          = NULL;
5108:   snes->ops->view           = NULL;
5109:   snes->ops->setfromoptions = NULL;
5110:   snes->ops->destroy        = NULL;

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

5115:   /* Reinitialize default parameters */
5116:   PetscCall(SNESParametersInitialize(snes));

5118:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
5119:   snes->setupcalled = PETSC_FALSE;
5120:   PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
5121:   PetscCall((*r)(snes));
5122:   PetscFunctionReturn(PETSC_SUCCESS);
5123: }

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

5128:   Not Collective

5130:   Input Parameter:
5131: . snes - nonlinear solver context

5133:   Output Parameter:
5134: . type - `SNES` method (a character string)

5136:   Level: intermediate

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

5141: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
5142: @*/
5143: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5144: {
5145:   PetscFunctionBegin;
5147:   PetscAssertPointer(type, 2);
5148:   *type = ((PetscObject)snes)->type_name;
5149:   PetscFunctionReturn(PETSC_SUCCESS);
5150: }

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

5155:   Logically Collective

5157:   Input Parameters:
5158: + snes - the `SNES` context obtained from `SNESCreate()`
5159: - u    - the solution vector

5161:   Level: beginner

5163: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5164: @*/
5165: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5166: {
5167:   DM dm;

5169:   PetscFunctionBegin;
5172:   PetscCall(PetscObjectReference((PetscObject)u));
5173:   PetscCall(VecDestroy(&snes->vec_sol));

5175:   snes->vec_sol = u;

5177:   PetscCall(SNESGetDM(snes, &dm));
5178:   PetscCall(DMShellSetGlobalVector(dm, u));
5179:   PetscFunctionReturn(PETSC_SUCCESS);
5180: }

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

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

5188:   Input Parameter:
5189: . snes - the `SNES` context

5191:   Output Parameter:
5192: . x - the solution

5194:   Level: intermediate

5196: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5197: @*/
5198: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5199: {
5200:   PetscFunctionBegin;
5202:   PetscAssertPointer(x, 2);
5203:   *x = snes->vec_sol;
5204:   PetscFunctionReturn(PETSC_SUCCESS);
5205: }

5207: /*@
5208:   SNESGetSolutionUpdate - Returns the vector where the solution update is
5209:   stored.

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

5213:   Input Parameter:
5214: . snes - the `SNES` context

5216:   Output Parameter:
5217: . x - the solution update

5219:   Level: advanced

5221: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5222: @*/
5223: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5224: {
5225:   PetscFunctionBegin;
5227:   PetscAssertPointer(x, 2);
5228:   *x = snes->vec_sol_update;
5229:   PetscFunctionReturn(PETSC_SUCCESS);
5230: }

5232: /*@C
5233:   SNESGetFunction - Returns the function that defines the nonlinear system set with `SNESSetFunction()`

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

5237:   Input Parameter:
5238: . snes - the `SNES` context

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

5245:   Level: advanced

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

5250: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5251: @*/
5252: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5253: {
5254:   DM dm;

5256:   PetscFunctionBegin;
5258:   if (r) {
5259:     if (!snes->vec_func) {
5260:       if (snes->vec_rhs) {
5261:         PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5262:       } else if (snes->vec_sol) {
5263:         PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5264:       } else if (snes->dm) {
5265:         PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5266:       }
5267:     }
5268:     *r = snes->vec_func;
5269:   }
5270:   PetscCall(SNESGetDM(snes, &dm));
5271:   PetscCall(DMSNESGetFunction(dm, f, ctx));
5272:   PetscFunctionReturn(PETSC_SUCCESS);
5273: }

5275: /*@C
5276:   SNESGetNGS - Returns the function and context set with `SNESSetNGS()`

5278:   Input Parameter:
5279: . snes - the `SNES` context

5281:   Output Parameters:
5282: + f   - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5283: - ctx - the function context (or `NULL`)

5285:   Level: advanced

5287: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5288: @*/
5289: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5290: {
5291:   DM dm;

5293:   PetscFunctionBegin;
5295:   PetscCall(SNESGetDM(snes, &dm));
5296:   PetscCall(DMSNESGetNGS(dm, f, ctx));
5297:   PetscFunctionReturn(PETSC_SUCCESS);
5298: }

5300: /*@
5301:   SNESSetOptionsPrefix - Sets the prefix used for searching for all
5302:   `SNES` options in the database.

5304:   Logically Collective

5306:   Input Parameters:
5307: + snes   - the `SNES` context
5308: - prefix - the prefix to prepend to all option names

5310:   Level: advanced

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

5316: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5317: @*/
5318: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5319: {
5320:   PetscFunctionBegin;
5322:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5323:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5324:   if (snes->linesearch) {
5325:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5326:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5327:   }
5328:   PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5329:   PetscFunctionReturn(PETSC_SUCCESS);
5330: }

5332: /*@
5333:   SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5334:   `SNES` options in the database.

5336:   Logically Collective

5338:   Input Parameters:
5339: + snes   - the `SNES` context
5340: - prefix - the prefix to prepend to all option names

5342:   Level: advanced

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

5348: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5349: @*/
5350: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5351: {
5352:   PetscFunctionBegin;
5354:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5355:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5356:   if (snes->linesearch) {
5357:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5358:     PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5359:   }
5360:   PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5361:   PetscFunctionReturn(PETSC_SUCCESS);
5362: }

5364: /*@
5365:   SNESGetOptionsPrefix - Gets the prefix used for searching for all
5366:   `SNES` options in the database.

5368:   Not Collective

5370:   Input Parameter:
5371: . snes - the `SNES` context

5373:   Output Parameter:
5374: . prefix - pointer to the prefix string used

5376:   Level: advanced

5378: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5379: @*/
5380: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5381: {
5382:   PetscFunctionBegin;
5384:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5385:   PetscFunctionReturn(PETSC_SUCCESS);
5386: }

5388: /*@C
5389:   SNESRegister - Adds a method to the nonlinear solver package.

5391:   Not Collective

5393:   Input Parameters:
5394: + sname    - name of a new user-defined solver
5395: - function - routine to create method context

5397:   Level: advanced

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

5402:   Example Usage:
5403: .vb
5404:    SNESRegister("my_solver", MySolverCreate);
5405: .ve

5407:   Then, your solver can be chosen with the procedural interface via
5408: .vb
5409:   SNESSetType(snes, "my_solver")
5410: .ve
5411:   or at runtime via the option
5412: .vb
5413:   -snes_type my_solver
5414: .ve

5416: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5417: @*/
5418: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5419: {
5420:   PetscFunctionBegin;
5421:   PetscCall(SNESInitializePackage());
5422:   PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5423:   PetscFunctionReturn(PETSC_SUCCESS);
5424: }

5426: /*@
5427:   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

5429:   Collective

5431:   Input Parameter:
5432: . snes - the `SNES` context

5434:   Level: developer

5436:   Note:
5437:   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.

5439: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESComputeFunction()`
5440: @*/
5441: PetscErrorCode SNESTestLocalMin(SNES snes)
5442: {
5443:   PetscInt    N, i, j;
5444:   Vec         u, uh, fh;
5445:   PetscScalar value;
5446:   PetscReal   norm;

5448:   PetscFunctionBegin;
5449:   PetscCall(SNESGetSolution(snes, &u));
5450:   PetscCall(VecDuplicate(u, &uh));
5451:   PetscCall(VecDuplicate(u, &fh));

5453:   /* currently only works for sequential */
5454:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5455:   PetscCall(VecGetSize(u, &N));
5456:   for (i = 0; i < N; i++) {
5457:     PetscCall(VecCopy(u, uh));
5458:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5459:     for (j = -10; j < 11; j++) {
5460:       value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5461:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5462:       PetscCall(SNESComputeFunction(snes, uh, fh));
5463:       PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5464:       PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "       j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5465:       value = -value;
5466:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5467:     }
5468:   }
5469:   PetscCall(VecDestroy(&uh));
5470:   PetscCall(VecDestroy(&fh));
5471:   PetscFunctionReturn(PETSC_SUCCESS);
5472: }

5474: /*@
5475:   SNESGetLineSearch - Returns the line search associated with the `SNES`.

5477:   Not Collective

5479:   Input Parameter:
5480: . snes - iterative context obtained from `SNESCreate()`

5482:   Output Parameter:
5483: . linesearch - linesearch context

5485:   Level: beginner

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

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

5492: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5493: @*/
5494: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5495: {
5496:   const char *optionsprefix;

5498:   PetscFunctionBegin;
5500:   PetscAssertPointer(linesearch, 2);
5501:   if (!snes->linesearch) {
5502:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5503:     PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5504:     PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5505:     PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5506:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5507:   }
5508:   *linesearch = snes->linesearch;
5509:   PetscFunctionReturn(PETSC_SUCCESS);
5510: }

5512: /*@
5513:   SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5514:   computing relative tolerance for linear solvers within an inexact
5515:   Newton method.

5517:   Logically Collective

5519:   Input Parameters:
5520: + snes - `SNES` context
5521: - flag - `PETSC_TRUE` or `PETSC_FALSE`

5523:   Options Database Keys:
5524: + -snes_ksp_ew                     - use Eisenstat-Walker method for determining linear system convergence
5525: . -snes_ksp_ew_version ver         - version of  Eisenstat-Walker method
5526: . -snes_ksp_ew_rtol0 rtol0         - Sets rtol0
5527: . -snes_ksp_ew_rtolmax rtolmax     - Sets rtolmax
5528: . -snes_ksp_ew_gamma gamma         - Sets gamma
5529: . -snes_ksp_ew_alpha alpha         - Sets alpha
5530: . -snes_ksp_ew_alpha2 alpha2       - Sets alpha2
5531: - -snes_ksp_ew_threshold threshold - Sets threshold

5533:   Level: advanced

5535:   Note:
5536:   The default is to use a constant relative tolerance for
5537:   the inner linear solvers.  Alternatively, one can use the
5538:   Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5539:   is reset at each Newton iteration according progress of the nonlinear
5540:   solver.

5542: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5543: @*/
5544: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5545: {
5546:   PetscFunctionBegin;
5549:   snes->ksp_ewconv = flag;
5550:   PetscFunctionReturn(PETSC_SUCCESS);
5551: }

5553: /*@
5554:   SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5555:   for computing relative tolerance for linear solvers within an
5556:   inexact Newton method.

5558:   Not Collective

5560:   Input Parameter:
5561: . snes - `SNES` context

5563:   Output Parameter:
5564: . flag - `PETSC_TRUE` or `PETSC_FALSE`

5566:   Level: advanced

5568: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5569: @*/
5570: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5571: {
5572:   PetscFunctionBegin;
5574:   PetscAssertPointer(flag, 2);
5575:   *flag = snes->ksp_ewconv;
5576:   PetscFunctionReturn(PETSC_SUCCESS);
5577: }

5579: /*@
5580:   SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5581:   convergence criteria for the linear solvers within an inexact
5582:   Newton method.

5584:   Logically Collective

5586:   Input Parameters:
5587: + snes      - `SNES` context
5588: . version   - version 1, 2 (default is 2), 3 or 4
5589: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5590: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5591: . gamma     - multiplicative factor for version 2 rtol computation
5592:              (0 <= gamma2 <= 1)
5593: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5594: . alpha2    - power for safeguard
5595: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5597:   Level: advanced

5599:   Notes:
5600:   Version 3 was contributed by Luis Chacon, June 2006.

5602:   Use `PETSC_CURRENT` to retain the default for any of the parameters.

5604: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5605: @*/
5606: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5607: {
5608:   SNESKSPEW *kctx;

5610:   PetscFunctionBegin;
5612:   kctx = (SNESKSPEW *)snes->kspconvctx;
5613:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");

5622:   if (version != PETSC_CURRENT) kctx->version = version;
5623:   if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5624:   if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5625:   if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5626:   if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5627:   if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5628:   if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;

5630:   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);
5631:   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);
5632:   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);
5633:   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);
5634:   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);
5635:   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);
5636:   PetscFunctionReturn(PETSC_SUCCESS);
5637: }

5639: /*@
5640:   SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5641:   convergence criteria for the linear solvers within an inexact
5642:   Newton method.

5644:   Not Collective

5646:   Input Parameter:
5647: . snes - `SNES` context

5649:   Output Parameters:
5650: + version   - version 1, 2 (default is 2), 3 or 4
5651: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5652: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5653: . gamma     - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5654: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5655: . alpha2    - power for safeguard
5656: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5658:   Level: advanced

5660: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5661: @*/
5662: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5663: {
5664:   SNESKSPEW *kctx;

5666:   PetscFunctionBegin;
5668:   kctx = (SNESKSPEW *)snes->kspconvctx;
5669:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5670:   if (version) *version = kctx->version;
5671:   if (rtol_0) *rtol_0 = kctx->rtol_0;
5672:   if (rtol_max) *rtol_max = kctx->rtol_max;
5673:   if (gamma) *gamma = kctx->gamma;
5674:   if (alpha) *alpha = kctx->alpha;
5675:   if (alpha2) *alpha2 = kctx->alpha2;
5676:   if (threshold) *threshold = kctx->threshold;
5677:   PetscFunctionReturn(PETSC_SUCCESS);
5678: }

5680: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5681: {
5682:   SNES       snes = (SNES)ctx;
5683:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5684:   PetscReal  rtol = PETSC_CURRENT, stol;

5686:   PetscFunctionBegin;
5687:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5688:   if (!snes->iter) {
5689:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5690:     PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5691:   } else {
5692:     PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5693:     if (kctx->version == 1) {
5694:       rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5695:       stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5696:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5697:     } else if (kctx->version == 2) {
5698:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5699:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5700:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5701:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5702:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5703:       /* safeguard: avoid sharp decrease of rtol */
5704:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5705:       stol = PetscMax(rtol, stol);
5706:       rtol = PetscMin(kctx->rtol_0, stol);
5707:       /* safeguard: avoid oversolving */
5708:       stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5709:       stol = PetscMax(rtol, stol);
5710:       rtol = PetscMin(kctx->rtol_0, stol);
5711:     } else /* if (kctx->version == 4) */ {
5712:       /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5713:       PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5714:       PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5715:       PetscReal rk   = ared / pred;
5716:       if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5717:       else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5718:       else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5719:       else rtol = kctx->v4_m2 * kctx->rtol_last;

5721:       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;
5722:       kctx->rtol_last_2 = kctx->rtol_last;
5723:       kctx->rk_last_2   = kctx->rk_last;
5724:       kctx->rk_last     = rk;
5725:     }
5726:   }
5727:   /* safeguard: avoid rtol greater than rtol_max */
5728:   rtol = PetscMin(rtol, kctx->rtol_max);
5729:   PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5730:   PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5731:   PetscFunctionReturn(PETSC_SUCCESS);
5732: }

5734: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5735: {
5736:   SNES       snes = (SNES)ctx;
5737:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5738:   PCSide     pcside;
5739:   Vec        lres;

5741:   PetscFunctionBegin;
5742:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5743:   PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5744:   kctx->norm_last = snes->norm;
5745:   if (kctx->version == 1 || kctx->version == 4) {
5746:     PC        pc;
5747:     PetscBool getRes;

5749:     PetscCall(KSPGetPC(ksp, &pc));
5750:     PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5751:     if (!getRes) {
5752:       KSPNormType normtype;

5754:       PetscCall(KSPGetNormType(ksp, &normtype));
5755:       getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5756:     }
5757:     PetscCall(KSPGetPCSide(ksp, &pcside));
5758:     if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5759:       PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5760:     } else {
5761:       /* KSP residual is preconditioned residual */
5762:       /* compute true linear residual norm */
5763:       Mat J;
5764:       PetscCall(KSPGetOperators(ksp, &J, NULL));
5765:       PetscCall(VecDuplicate(b, &lres));
5766:       PetscCall(MatMult(J, x, lres));
5767:       PetscCall(VecAYPX(lres, -1.0, b));
5768:       PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5769:       PetscCall(VecDestroy(&lres));
5770:     }
5771:   }
5772:   PetscFunctionReturn(PETSC_SUCCESS);
5773: }

5775: #include <petsc/private/kspimpl.h>
5776: /*@
5777:   SNESGetKSP - Returns the `KSP` context for a `SNES` solver.

5779:   Not Collective, but if `snes` is parallel, then `ksp` is parallel

5781:   Input Parameter:
5782: . snes - the `SNES` context

5784:   Output Parameter:
5785: . ksp - the `KSP` context

5787:   Level: beginner

5789:   Notes:
5790:   The user can then directly manipulate the `KSP` context to set various
5791:   options, etc.  Likewise, the user can then extract and manipulate the
5792:   `PC` contexts as well.

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

5796: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5797: @*/
5798: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5799: {
5800:   PetscFunctionBegin;
5802:   PetscAssertPointer(ksp, 2);

5804:   if (!snes->ksp) {
5805:     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5806:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));

5808:     snes->ksp->presolve_ew  = KSPPreSolve_SNESEW;
5809:     snes->ksp->prectx_ew    = snes;
5810:     snes->ksp->postsolve_ew = KSPPostSolve_SNESEW;
5811:     snes->ksp->postctx_ew   = snes;

5813:     PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5814:     PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5815:   }
5816:   *ksp = snes->ksp;
5817:   PetscFunctionReturn(PETSC_SUCCESS);
5818: }

5820: #include <petsc/private/dmimpl.h>
5821: /*@
5822:   SNESSetDM - Sets the `DM` that may be used by some `SNES` nonlinear solvers or their underlying preconditioners

5824:   Logically Collective

5826:   Input Parameters:
5827: + snes - the nonlinear solver context
5828: - dm   - the `DM`, cannot be `NULL`

5830:   Level: intermediate

5832:   Note:
5833:   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
5834:   even when not using interfaces like `DMSNESSetFunction()`.  Use `DMClone()` to get a distinct `DM` when solving different
5835:   problems using the same function space.

5837: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5838: @*/
5839: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5840: {
5841:   KSP    ksp;
5842:   DMSNES sdm;
5843:   DM     odm;

5845:   PetscFunctionBegin;
5848:   PetscCall(PetscObjectReference((PetscObject)dm));
5849:   odm = snes->dm;
5850:   if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5851:     if (snes->dm->dmsnes && !dm->dmsnes) {
5852:       PetscCall(DMCopyDMSNES(snes->dm, dm));
5853:       PetscCall(DMGetDMSNES(snes->dm, &sdm));
5854:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5855:     }
5856:     PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5857:     PetscCall(DMDestroy(&snes->dm));
5858:   }
5859:   snes->dm     = dm;
5860:   snes->dmAuto = PETSC_FALSE;

5862:   PetscCall(SNESGetKSP(snes, &ksp));
5863:   PetscCall(KSPSetDM(ksp, dm));
5864:   PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5865:   /* Propagate DM to NPC if npc does not have one yet or
5866:      if it has the same DM SNES had before (like for gridsequencing) */
5867:   if (snes->npc && (!snes->npc->dm || snes->npc->dm == odm)) PetscCall(SNESSetDM(snes->npc, snes->dm));
5868:   PetscFunctionReturn(PETSC_SUCCESS);
5869: }

5871: /*@
5872:   SNESGetDM - Gets the `DM` that may be used by some `SNES` nonlinear solvers/preconditioners

5874:   Not Collective but `dm` obtained is parallel on `snes`

5876:   Input Parameter:
5877: . snes - the `SNES` context

5879:   Output Parameter:
5880: . dm - the `DM`

5882:   Level: intermediate

5884: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5885: @*/
5886: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5887: {
5888:   PetscFunctionBegin;
5890:   if (!snes->dm) {
5891:     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5892:     snes->dmAuto = PETSC_TRUE;
5893:   }
5894:   *dm = snes->dm;
5895:   PetscFunctionReturn(PETSC_SUCCESS);
5896: }

5898: /*@
5899:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5901:   Collective

5903:   Input Parameters:
5904: + snes - iterative context obtained from `SNESCreate()`
5905: - npc  - the `SNES` nonlinear preconditioner object

5907:   Level: developer

5909:   Notes:
5910:   This is rarely used, rather use `SNESGetNPC()` to retrieve the preconditioner and configure it using the API.

5912:   Only some `SNESType` can use a nonlinear preconditioner

5914: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5915: @*/
5916: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5917: {
5918:   PetscFunctionBegin;
5921:   PetscCheckSameComm(snes, 1, npc, 2);
5922:   PetscCall(PetscObjectReference((PetscObject)npc));
5923:   PetscCall(SNESDestroy(&snes->npc));
5924:   snes->npc = npc;
5925:   PetscFunctionReturn(PETSC_SUCCESS);
5926: }

5928: /*@
5929:   SNESGetNPC - Gets a nonlinear preconditioning solver SNES` to be used to precondition the original nonlinear solver.

5931:   Collective the first time it is called if the `SNES` has no NPC set.

5933:   Input Parameter:
5934: . snes - iterative context obtained from `SNESCreate()`

5936:   Output Parameter:
5937: . npc - the `SNES` preconditioner context

5939:   Options Database Key:
5940: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner

5942:   Level: advanced

5944:   Notes:
5945:   If a `SNES` was previously set with `SNESSetNPC()` then that object is returned, otherwise a new `SNES` object is created that will
5946:   be used as the nonlinear preconditioner for the current `SNES` if no nonlinear preconditioner is present.

5948:   The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5949:   `SNES`. These may be overwritten if needed by calling `SNESSetDM()` on the nonlinear preconditioner followed by `SNESSetFunction()`
5950:   and `SNESSetJacobian()`.

5952:   The default preconditioner uses the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration.

5954: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5955: @*/
5956: PetscErrorCode SNESGetNPC(SNES snes, SNES *npc)
5957: {
5958:   const char *optionsprefix;

5960:   PetscFunctionBegin;
5962:   PetscAssertPointer(npc, 2);
5963:   if (!snes->npc) {
5964:     PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5965:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5966:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5967:     PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5968:     PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5969:     PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5970:     PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_DEFAULT));

5972:     /* default to 1 iteration */
5973:     PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
5974:   }
5975:   *npc = snes->npc;
5976:   PetscFunctionReturn(PETSC_SUCCESS);
5977: }

5979: /*@
5980:   SNESHasNPC - Returns whether a nonlinear preconditioner is associated with the given `SNES`

5982:   Not Collective

5984:   Input Parameter:
5985: . snes - iterative context obtained from `SNESCreate()`

5987:   Output Parameter:
5988: . has_npc - whether the `SNES` has a nonlinear preconditioner or not

5990:   Level: developer

5992: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
5993: @*/
5994: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5995: {
5996:   PetscFunctionBegin;
5998:   PetscAssertPointer(has_npc, 2);
5999:   *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
6000:   PetscFunctionReturn(PETSC_SUCCESS);
6001: }

6003: /*@
6004:   SNESSetNPCSide - Sets the nonlinear preconditioning side used by the nonlinear preconditioner inside `SNES`.

6006:   Logically Collective

6008:   Input Parameter:
6009: . snes - iterative context obtained from `SNESCreate()`

6011:   Output Parameter:
6012: . side - the preconditioning side, where side is one of
6013: .vb
6014:       PC_LEFT  - left preconditioning
6015:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
6016: .ve

6018:   Options Database Key:
6019: . -snes_npc_side (right|left) - nonlinear preconditioner side

6021:   Level: intermediate

6023:   Note:
6024:   `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.

6026: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6027: @*/
6028: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
6029: {
6030:   PetscFunctionBegin;
6033:   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
6034:   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
6035:   snes->npcside = side;
6036:   PetscFunctionReturn(PETSC_SUCCESS);
6037: }

6039: /*@
6040:   SNESGetNPCSide - Gets the preconditioning side used by the nonlinear preconditioner inside `SNES`.

6042:   Not Collective

6044:   Input Parameter:
6045: . snes - iterative context obtained from `SNESCreate()`

6047:   Output Parameter:
6048: . side - the preconditioning side, where side is one of
6049: .vb
6050:       `PC_LEFT` - left preconditioning
6051:       `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
6052: .ve

6054:   Level: intermediate

6056: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6057: @*/
6058: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
6059: {
6060:   PetscFunctionBegin;
6062:   PetscAssertPointer(side, 2);
6063:   *side = snes->npcside;
6064:   PetscFunctionReturn(PETSC_SUCCESS);
6065: }

6067: /*@
6068:   SNESSetLineSearch - Sets the `SNESLineSearch` to be used for a given `SNES`

6070:   Collective

6072:   Input Parameters:
6073: + snes       - iterative context obtained from `SNESCreate()`
6074: - linesearch - the linesearch object

6076:   Level: developer

6078:   Note:
6079:   This is almost never used, rather one uses `SNESGetLineSearch()` to retrieve the line search and set options on it
6080:   to configure it using the API).

6082: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
6083: @*/
6084: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
6085: {
6086:   PetscFunctionBegin;
6089:   PetscCheckSameComm(snes, 1, linesearch, 2);
6090:   PetscCall(PetscObjectReference((PetscObject)linesearch));
6091:   PetscCall(SNESLineSearchDestroy(&snes->linesearch));

6093:   snes->linesearch = linesearch;
6094:   PetscFunctionReturn(PETSC_SUCCESS);
6095: }