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 defined(PETSC_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:   Level: intermediate

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

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

350: /*@
351:   SNESView - Prints or visualizes the `SNES` data structure.

353:   Collective

355:   Input Parameters:
356: + snes   - the `SNES` context
357: - viewer - the `PetscViewer`

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

362:   Level: beginner

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

372:   The available formats include
373: +     `PETSC_VIEWER_DEFAULT` - standard output (default)
374: -     `PETSC_VIEWER_ASCII_INFO_DETAIL` - more verbose output for `SNESNASM`

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

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

381: .seealso: [](ch_snes), `SNES`, `SNESLoad()`, `SNESCreate()`, `PetscViewerASCIIOpen()`
382: @*/
383: PetscErrorCode SNESView(SNES snes, PetscViewer viewer)
384: {
385:   SNESKSPEW     *kctx;
386:   KSP            ksp;
387:   SNESLineSearch linesearch;
388:   PetscBool      isascii, isstring, isbinary, isdraw;
389:   DMSNES         dmsnes;
390: #if defined(PETSC_HAVE_SAWS)
391:   PetscBool issaws;
392: #endif

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

400:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
401:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
402:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
403:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
404: #if defined(PETSC_HAVE_SAWS)
405:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
406: #endif
407:   if (isascii) {
408:     SNESNormSchedule normschedule;
409:     DM               dm;
410:     SNESJacobianFn  *cJ;
411:     void            *ctx;
412:     const char      *pre = "";

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

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

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

509:     PetscCall(PetscObjectGetName((PetscObject)snes, &name));
510:     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
511:     if (!((PetscObject)snes)->amsmem && rank == 0) {
512:       char dir[1024];

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

552: /*
553:   We retain a list of functions that also take SNES command
554:   line options. These are called at the end SNESSetFromOptions()
555: */
556: #define MAXSETFROMOPTIONS 5
557: static PetscInt numberofsetfromoptions;
558: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

560: /*@C
561:   SNESAddOptionsChecker - Adds an additional function to check for `SNES` options.

563:   Not Collective

565:   Input Parameter:
566: . snescheck - function that checks for options

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

571:   Level: developer

573: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`
574: @*/
575: PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES snes))
576: {
577:   PetscFunctionBegin;
578:   PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
579:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
580:   PetscFunctionReturn(PETSC_SUCCESS);
581: }

583: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
584: {
585:   Mat          J;
586:   MatNullSpace nullsp;

588:   PetscFunctionBegin;

591:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
592:     Mat A = snes->jacobian, B = snes->jacobian_pre;
593:     PetscCall(MatCreateVecs(A ? A : B, NULL, &snes->vec_func));
594:   }

596:   PetscCheck(version == 1 || version == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
597:   if (version == 1) {
598:     PetscCall(MatCreateSNESMF(snes, &J));
599:     PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
600:     PetscCall(MatSetFromOptions(J));
601:     /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
602:   } else /* if (version == 2) */ {
603:     PetscCheck(snes->vec_func, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SNESSetFunction() must be called first");
604: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
605:     PetscCall(MatCreateSNESMFMore(snes, snes->vec_func, &J));
606: #else
607:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
608: #endif
609:   }

611:   /* attach any user provided null space that was on Amat to the newly created matrix-free matrix */
612:   if (snes->jacobian) {
613:     PetscCall(MatGetNullSpace(snes->jacobian, &nullsp));
614:     if (nullsp) PetscCall(MatSetNullSpace(J, nullsp));
615:   }

617:   PetscCall(PetscInfo(snes, "Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
618:   if (hasOperator) {
619:     /* This version replaces the user provided Jacobian matrix with a
620:        matrix-free version but still employs the user-provided matrix used for computing the preconditioner. */
621:     PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
622:   } else {
623:     /* This version replaces both the user-provided Jacobian and the user-
624:      provided preconditioner Jacobian with the default matrix-free version. */
625:     if (snes->npcside == PC_LEFT && snes->npc) {
626:       if (!snes->jacobian) PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
627:     } else {
628:       KSP       ksp;
629:       PC        pc;
630:       PetscBool match;

632:       PetscCall(SNESSetJacobian(snes, J, J, MatMFFDComputeJacobian, NULL));
633:       /* Force no preconditioner */
634:       PetscCall(SNESGetKSP(snes, &ksp));
635:       PetscCall(KSPGetPC(ksp, &pc));
636:       PetscCall(PetscObjectTypeCompareAny((PetscObject)pc, &match, PCSHELL, PCH2OPUS, ""));
637:       if (!match) {
638:         PetscCall(PetscInfo(snes, "Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
639:         PetscCall(PCSetType(pc, PCNONE));
640:       }
641:     }
642:   }
643:   PetscCall(MatDestroy(&J));
644:   PetscFunctionReturn(PETSC_SUCCESS);
645: }

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

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

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

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

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

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

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

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

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

734:   if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
735:   snes->dm = dmsave;
736:   PetscFunctionReturn(PETSC_SUCCESS);
737: }

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

742:   Collective

744:   Input Parameter:
745: . snes - `SNES` object to configure

747:   Level: developer

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

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

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

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

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

810: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);

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

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

823:   Collective

825:   Input Parameters:
826: + snes         - `SNES` object you wish to monitor
827: . name         - the monitor type one is seeking
828: . help         - message indicating what monitoring is done
829: . manual       - manual page for the monitor
830: . monitor      - the monitor function, this must use a `PetscViewerFormat` as its context
831: - 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

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

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

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

846:   Level: advanced

848: .seealso: [](ch_snes), `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
849:           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
850:           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
851:           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
852:           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
853:           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
854:           `PetscOptionsFList()`, `PetscOptionsEList()`
855: @*/
856: 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))
857: {
858:   PetscViewer       viewer;
859:   PetscViewerFormat format;
860:   PetscBool         flg;

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

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

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

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

902:   Collective

904:   Input Parameter:
905: . snes - the `SNES` context

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

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

952:   Level: beginner

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

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

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

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

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

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

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

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

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

1012:   PetscCall(PetscOptionsInt("-snes_lag_preconditioner", "How often to rebuild preconditioner", "SNESSetLagPreconditioner", snes->lagpreconditioner, &lag, &flg));
1013:   if (flg) {
1014:     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");
1015:     PetscCall(SNESSetLagPreconditioner(snes, lag));
1016:   }
1017:   PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists", "Preconditioner lagging through multiple SNES solves", "SNESSetLagPreconditionerPersists", snes->lagjac_persist, &persist, &flg));
1018:   if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes, persist));
1019:   PetscCall(PetscOptionsInt("-snes_lag_jacobian", "How often to rebuild Jacobian", "SNESSetLagJacobian", snes->lagjacobian, &lag, &flg));
1020:   if (flg) {
1021:     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");
1022:     PetscCall(SNESSetLagJacobian(snes, lag));
1023:   }
1024:   PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists", "Jacobian lagging through multiple SNES solves", "SNESSetLagJacobianPersists", snes->lagjac_persist, &persist, &flg));
1025:   if (flg) PetscCall(SNESSetLagJacobianPersists(snes, persist));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1120:   flg = PETSC_FALSE;
1121:   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));
1122:   if (flg && snes->mf_operator) {
1123:     snes->mf_operator = PETSC_TRUE;
1124:     snes->mf          = PETSC_TRUE;
1125:   }
1126:   flg = PETSC_FALSE;
1127:   PetscCall(PetscOptionsBool("-snes_mf", "Use a Matrix-Free Jacobian with no matrix for computing the preconditioner", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf, &flg));
1128:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1129:   PetscCall(PetscOptionsInt("-snes_mf_version", "Matrix-Free routines version 1 or 2", "None", snes->mf_version, &snes->mf_version, NULL));

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

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

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

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

1162:   PetscTryTypeMethod(snes, setfromoptions, PetscOptionsObject);

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

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

1173:   if (snes->usesksp) {
1174:     if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
1175:     PetscCall(KSPSetOperators(snes->ksp, snes->jacobian, snes->jacobian_pre));
1176:     PetscCall(KSPSetFromOptions(snes->ksp));
1177:   }

1179:   /* if user has set the SNES NPC type via options database, create it. */
1180:   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1181:   PetscCall(PetscOptionsHasName(((PetscObject)snes)->options, optionsprefix, "-npc_snes_type", &pcset));
1182:   if (pcset && (!snes->npc)) PetscCall(SNESGetNPC(snes, &snes->npc));
1183:   if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1184:   snes->setfromoptionscalled++;
1185:   PetscFunctionReturn(PETSC_SUCCESS);
1186: }

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

1191:   Collective

1193:   Input Parameter:
1194: . snes - the `SNES` context

1196:   Level: advanced

1198: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1199: @*/
1200: PetscErrorCode SNESResetFromOptions(SNES snes)
1201: {
1202:   PetscFunctionBegin;
1203:   if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1204:   PetscFunctionReturn(PETSC_SUCCESS);
1205: }

1207: /*@C
1208:   SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1209:   the nonlinear solvers.

1211:   Logically Collective; No Fortran Support

1213:   Input Parameters:
1214: + snes    - the `SNES` context
1215: . compute - function to compute the context
1216: - destroy - function to destroy the context, see `PetscCtxDestroyFn` for the calling sequence

1218:   Calling sequence of `compute`:
1219: + snes - the `SNES` context
1220: - ctx  - context to be computed

1222:   Level: intermediate

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

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

1229: .seealso: [](ch_snes), `SNESGetApplicationContext()`, `SNESSetApplicationContext()`, `PetscCtxDestroyFn`
1230: @*/
1231: PetscErrorCode SNESSetComputeApplicationContext(SNES snes, PetscErrorCode (*compute)(SNES snes, PetscCtxRt ctx), PetscCtxDestroyFn *destroy)
1232: {
1233:   PetscFunctionBegin;
1235:   snes->ops->ctxcompute = compute;
1236:   snes->ops->ctxdestroy = destroy;
1237:   PetscFunctionReturn(PETSC_SUCCESS);
1238: }

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

1243:   Logically Collective

1245:   Input Parameters:
1246: + snes - the `SNES` context
1247: - ctx  - the user context

1249:   Level: intermediate

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

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

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

1262: .seealso: [](ch_snes), `SNES`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1263: @*/
1264: PetscErrorCode SNESSetApplicationContext(SNES snes, PetscCtx ctx)
1265: {
1266:   KSP ksp;

1268:   PetscFunctionBegin;
1270:   PetscCall(SNESGetKSP(snes, &ksp));
1271:   PetscCall(KSPSetApplicationContext(ksp, ctx));
1272:   snes->ctx = ctx;
1273:   PetscFunctionReturn(PETSC_SUCCESS);
1274: }

1276: /*@
1277:   SNESGetApplicationContext - Gets the user-defined context for the
1278:   nonlinear solvers set with `SNESGetApplicationContext()` or `SNESSetComputeApplicationContext()`

1280:   Not Collective

1282:   Input Parameter:
1283: . snes - `SNES` context

1285:   Output Parameter:
1286: . ctx - the application context

1288:   Level: intermediate

1290:   Fortran Notes:
1291:   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
1292: .vb
1293:   type(tUsertype), pointer :: ctx
1294: .ve

1296: .seealso: [](ch_snes), `SNESSetApplicationContext()`, `SNESSetComputeApplicationContext()`
1297: @*/
1298: PetscErrorCode SNESGetApplicationContext(SNES snes, PetscCtxRt ctx)
1299: {
1300:   PetscFunctionBegin;
1302:   *(void **)ctx = snes->ctx;
1303:   PetscFunctionReturn(PETSC_SUCCESS);
1304: }

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

1309:   Logically Collective

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

1317:   Options Database Keys:
1318: + -snes_mf_operator - use matrix-free only for the mat operator
1319: . -snes_mf          - use matrix-free for both the mat and pmat operator
1320: . -snes_fd_color    - compute the Jacobian via coloring and finite differences.
1321: - -snes_fd          - compute the Jacobian via finite differences (slow)

1323:   Level: intermediate

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

1330: .seealso: [](ch_snes), `SNES`, `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`, `MatFDColoring`
1331: @*/
1332: PetscErrorCode SNESSetUseMatrixFree(SNES snes, PetscBool mf_operator, PetscBool mf)
1333: {
1334:   PetscFunctionBegin;
1338:   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1339:   snes->mf_operator = mf_operator;
1340:   PetscFunctionReturn(PETSC_SUCCESS);
1341: }

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

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

1348:   Input Parameter:
1349: . snes - `SNES` context

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

1355:   Level: intermediate

1357: .seealso: [](ch_snes), `SNES`, `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1358: @*/
1359: PetscErrorCode SNESGetUseMatrixFree(SNES snes, PetscBool *mf_operator, PetscBool *mf)
1360: {
1361:   PetscFunctionBegin;
1363:   if (mf) *mf = snes->mf;
1364:   if (mf_operator) *mf_operator = snes->mf_operator;
1365:   PetscFunctionReturn(PETSC_SUCCESS);
1366: }

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

1371:   Not Collective

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

1376:   Output Parameter:
1377: . iter - iteration number

1379:   Level: intermediate

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

1384:   This is useful for using lagged Jacobians (where one does not recompute the
1385:   Jacobian at each `SNES` iteration). For example, the code
1386: .vb
1387:       ierr = SNESGetIterationNumber(snes,&it);
1388:       if (!(it % 2)) {
1389:         [compute Jacobian here]
1390:       }
1391: .ve
1392:   can be used in your function that computes the Jacobian to cause the Jacobian to be
1393:   recomputed every second `SNES` iteration. See also `SNESSetLagJacobian()`

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

1397: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetLagJacobian()`, `SNESGetLinearSolveIterations()`, `SNESSetMonitor()`
1398: @*/
1399: PetscErrorCode SNESGetIterationNumber(SNES snes, PetscInt *iter)
1400: {
1401:   PetscFunctionBegin;
1403:   PetscAssertPointer(iter, 2);
1404:   *iter = snes->iter;
1405:   PetscFunctionReturn(PETSC_SUCCESS);
1406: }

1408: /*@
1409:   SNESSetIterationNumber - Sets the current iteration number.

1411:   Not Collective

1413:   Input Parameters:
1414: + snes - `SNES` context
1415: - iter - iteration number

1417:   Level: developer

1419:   Note:
1420:   This should only be called inside a `SNES` nonlinear solver.

1422: .seealso: [](ch_snes), `SNESGetLinearSolveIterations()`
1423: @*/
1424: PetscErrorCode SNESSetIterationNumber(SNES snes, PetscInt iter)
1425: {
1426:   PetscFunctionBegin;
1428:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1429:   snes->iter = iter;
1430:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1431:   PetscFunctionReturn(PETSC_SUCCESS);
1432: }

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

1438:   Not Collective

1440:   Input Parameter:
1441: . snes - `SNES` context

1443:   Output Parameter:
1444: . nfails - number of unsuccessful steps attempted

1446:   Level: intermediate

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

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

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

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

1459: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1460:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1461: @*/
1462: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes, PetscInt *nfails)
1463: {
1464:   PetscFunctionBegin;
1466:   PetscAssertPointer(nfails, 2);
1467:   *nfails = snes->numFailures;
1468:   PetscFunctionReturn(PETSC_SUCCESS);
1469: }

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

1475:   Not Collective

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

1481:   Options Database Key:
1482: . -snes_max_fail n - maximum number of unsuccessful steps allowed

1484:   Level: intermediate

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

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

1493:   Developer Note:
1494:   The options database key is wrong for this function name

1496: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1497:           `SNESGetLinearSolveFailures()`, `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`, `SNESCheckLineSearchFailure()`
1498: @*/
1499: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1500: {
1501:   PetscFunctionBegin;

1504:   if (maxFails == PETSC_UNLIMITED) {
1505:     snes->maxFailures = PETSC_INT_MAX;
1506:   } else {
1507:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1508:     snes->maxFailures = maxFails;
1509:   }
1510:   PetscFunctionReturn(PETSC_SUCCESS);
1511: }

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

1517:   Not Collective

1519:   Input Parameter:
1520: . snes - `SNES` context

1522:   Output Parameter:
1523: . maxFails - maximum of unsuccessful steps

1525:   Level: intermediate

1527: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1528:           `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1529: @*/
1530: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1531: {
1532:   PetscFunctionBegin;
1534:   PetscAssertPointer(maxFails, 2);
1535:   *maxFails = snes->maxFailures;
1536:   PetscFunctionReturn(PETSC_SUCCESS);
1537: }

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

1543:   Not Collective

1545:   Input Parameter:
1546: . snes - `SNES` context

1548:   Output Parameter:
1549: . nfuncs - number of evaluations

1551:   Level: intermediate

1553:   Note:
1554:   Reset every time `SNESSolve()` is called unless `SNESSetCountersReset()` is used.

1556: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1557: @*/
1558: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1559: {
1560:   PetscFunctionBegin;
1562:   PetscAssertPointer(nfuncs, 2);
1563:   *nfuncs = snes->nfuncs;
1564:   PetscFunctionReturn(PETSC_SUCCESS);
1565: }

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

1571:   Not Collective

1573:   Input Parameter:
1574: . snes - `SNES` context

1576:   Output Parameter:
1577: . nfails - number of failed solves

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

1582:   Level: intermediate

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

1587: .seealso: [](ch_snes), `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1588: @*/
1589: PetscErrorCode SNESGetLinearSolveFailures(SNES snes, PetscInt *nfails)
1590: {
1591:   PetscFunctionBegin;
1593:   PetscAssertPointer(nfails, 2);
1594:   *nfails = snes->numLinearSolveFailures;
1595:   PetscFunctionReturn(PETSC_SUCCESS);
1596: }

1598: /*@
1599:   SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1600:   allowed before `SNES` returns with a diverged reason of `SNES_DIVERGED_LINEAR_SOLVE`

1602:   Logically Collective

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

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

1611:   Level: intermediate

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

1616:   Developer Note:
1617:   The options database key is wrong for this function name

1619: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1620: @*/
1621: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1622: {
1623:   PetscFunctionBegin;

1627:   if (maxFails == PETSC_UNLIMITED) {
1628:     snes->maxLinearSolveFailures = PETSC_INT_MAX;
1629:   } else {
1630:     PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1631:     snes->maxLinearSolveFailures = maxFails;
1632:   }
1633:   PetscFunctionReturn(PETSC_SUCCESS);
1634: }

1636: /*@
1637:   SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1638:   are allowed before `SNES` returns as unsuccessful

1640:   Not Collective

1642:   Input Parameter:
1643: . snes - `SNES` context

1645:   Output Parameter:
1646: . maxFails - maximum of unsuccessful solves allowed

1648:   Level: intermediate

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

1653: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1654: @*/
1655: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1656: {
1657:   PetscFunctionBegin;
1659:   PetscAssertPointer(maxFails, 2);
1660:   *maxFails = snes->maxLinearSolveFailures;
1661:   PetscFunctionReturn(PETSC_SUCCESS);
1662: }

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

1668:   Not Collective

1670:   Input Parameter:
1671: . snes - `SNES` context

1673:   Output Parameter:
1674: . lits - number of linear iterations

1676:   Level: intermediate

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

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

1684: .seealso: [](ch_snes), `SNES`, `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1685: @*/
1686: PetscErrorCode SNESGetLinearSolveIterations(SNES snes, PetscInt *lits)
1687: {
1688:   PetscFunctionBegin;
1690:   PetscAssertPointer(lits, 2);
1691:   *lits = snes->linear_its;
1692:   PetscFunctionReturn(PETSC_SUCCESS);
1693: }

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

1699:   Logically Collective

1701:   Input Parameters:
1702: + snes  - `SNES` context
1703: - reset - whether to reset the counters or not, defaults to `PETSC_TRUE`

1705:   Level: developer

1707: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1708: @*/
1709: PetscErrorCode SNESSetCountersReset(SNES snes, PetscBool reset)
1710: {
1711:   PetscFunctionBegin;
1714:   snes->counters_reset = reset;
1715:   PetscFunctionReturn(PETSC_SUCCESS);
1716: }

1718: /*@
1719:   SNESResetCounters - Reset counters for linear iterations and function evaluations.

1721:   Logically Collective

1723:   Input Parameters:
1724: . snes - `SNES` context

1726:   Level: developer

1728:   Note:
1729:   It honors the flag set with `SNESSetCountersReset()`

1731: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1732: @*/
1733: PetscErrorCode SNESResetCounters(SNES snes)
1734: {
1735:   PetscFunctionBegin;
1737:   if (snes->counters_reset) {
1738:     snes->nfuncs      = 0;
1739:     snes->linear_its  = 0;
1740:     snes->numFailures = 0;
1741:   }
1742:   PetscFunctionReturn(PETSC_SUCCESS);
1743: }

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

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

1750:   Input Parameters:
1751: + snes - the `SNES` context
1752: - ksp  - the `KSP` context

1754:   Level: developer

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

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

1763: .seealso: [](ch_snes), `SNES`, `KSP`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`
1764: @*/
1765: PetscErrorCode SNESSetKSP(SNES snes, KSP ksp)
1766: {
1767:   PetscFunctionBegin;
1770:   PetscCheckSameComm(snes, 1, ksp, 2);
1771:   PetscCall(PetscObjectReference((PetscObject)ksp));
1772:   if (snes->ksp) PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1773:   snes->ksp = ksp;
1774:   PetscFunctionReturn(PETSC_SUCCESS);
1775: }

1777: /*@
1778:   SNESParametersInitialize - Sets all the parameters in `snes` to their default value (when `SNESCreate()` was called) if they
1779:   currently contain default values

1781:   Collective

1783:   Input Parameter:
1784: . snes - the `SNES` object

1786:   Level: developer

1788:   Developer Note:
1789:   This is called by all the `SNESCreate_XXX()` routines.

1791: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
1792:           `PetscObjectParameterSetDefault()`
1793: @*/
1794: PetscErrorCode SNESParametersInitialize(SNES snes)
1795: {
1796:   PetscObjectParameterSetDefault(snes, max_its, 50);
1797:   PetscObjectParameterSetDefault(snes, max_funcs, 10000);
1798:   PetscObjectParameterSetDefault(snes, rtol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1799:   PetscObjectParameterSetDefault(snes, abstol, PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50);
1800:   PetscObjectParameterSetDefault(snes, stol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1801:   PetscObjectParameterSetDefault(snes, divtol, 1.e4);
1802:   return PETSC_SUCCESS;
1803: }

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

1808:   Collective

1810:   Input Parameter:
1811: . comm - MPI communicator

1813:   Output Parameter:
1814: . outsnes - the new `SNES` context

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

1822:   Level: beginner

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

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

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

1835: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1836: @*/
1837: PetscErrorCode SNESCreate(MPI_Comm comm, SNES *outsnes)
1838: {
1839:   SNES       snes;
1840:   SNESKSPEW *kctx;

1842:   PetscFunctionBegin;
1843:   PetscAssertPointer(outsnes, 2);
1844:   PetscCall(SNESInitializePackage());

1846:   PetscCall(PetscHeaderCreate(snes, SNES_CLASSID, "SNES", "Nonlinear solver", "SNES", comm, SNESDestroy, SNESView));
1847:   snes->ops->converged = SNESConvergedDefault;
1848:   snes->usesksp        = PETSC_TRUE;
1849:   snes->norm           = 0.0;
1850:   snes->xnorm          = 0.0;
1851:   snes->ynorm          = 0.0;
1852:   snes->normschedule   = SNES_NORM_ALWAYS;
1853:   snes->functype       = SNES_FUNCTION_DEFAULT;
1854:   snes->ttol           = 0.0;

1856:   snes->rnorm0               = 0;
1857:   snes->nfuncs               = 0;
1858:   snes->numFailures          = 0;
1859:   snes->maxFailures          = 1;
1860:   snes->linear_its           = 0;
1861:   snes->lagjacobian          = 1;
1862:   snes->jac_iter             = 0;
1863:   snes->lagjac_persist       = PETSC_FALSE;
1864:   snes->lagpreconditioner    = 1;
1865:   snes->pre_iter             = 0;
1866:   snes->lagpre_persist       = PETSC_FALSE;
1867:   snes->numbermonitors       = 0;
1868:   snes->numberreasonviews    = 0;
1869:   snes->data                 = NULL;
1870:   snes->setupcalled          = PETSC_FALSE;
1871:   snes->ksp_ewconv           = PETSC_FALSE;
1872:   snes->nwork                = 0;
1873:   snes->work                 = NULL;
1874:   snes->nvwork               = 0;
1875:   snes->vwork                = NULL;
1876:   snes->conv_hist_len        = 0;
1877:   snes->conv_hist_max        = 0;
1878:   snes->conv_hist            = NULL;
1879:   snes->conv_hist_its        = NULL;
1880:   snes->conv_hist_reset      = PETSC_TRUE;
1881:   snes->counters_reset       = PETSC_TRUE;
1882:   snes->vec_func_init_set    = PETSC_FALSE;
1883:   snes->reason               = SNES_CONVERGED_ITERATING;
1884:   snes->npcside              = PC_RIGHT;
1885:   snes->setfromoptionscalled = 0;

1887:   snes->mf          = PETSC_FALSE;
1888:   snes->mf_operator = PETSC_FALSE;
1889:   snes->mf_version  = 1;

1891:   snes->numLinearSolveFailures = 0;
1892:   snes->maxLinearSolveFailures = 1;

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

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

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

1903:   snes->kspconvctx  = kctx;
1904:   kctx->version     = 2;
1905:   kctx->rtol_0      = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1906:                              this was too large for some test cases */
1907:   kctx->rtol_last   = 0.0;
1908:   kctx->rtol_max    = 0.9;
1909:   kctx->gamma       = 1.0;
1910:   kctx->alpha       = 0.5 * (1.0 + PetscSqrtReal(5.0));
1911:   kctx->alpha2      = kctx->alpha;
1912:   kctx->threshold   = 0.1;
1913:   kctx->lresid_last = 0.0;
1914:   kctx->norm_last   = 0.0;

1916:   kctx->rk_last     = 0.0;
1917:   kctx->rk_last_2   = 0.0;
1918:   kctx->rtol_last_2 = 0.0;
1919:   kctx->v4_p1       = 0.1;
1920:   kctx->v4_p2       = 0.4;
1921:   kctx->v4_p3       = 0.7;
1922:   kctx->v4_m1       = 0.8;
1923:   kctx->v4_m2       = 0.5;
1924:   kctx->v4_m3       = 0.1;
1925:   kctx->v4_m4       = 0.5;

1927:   PetscCall(SNESParametersInitialize(snes));
1928:   *outsnes = snes;
1929:   PetscFunctionReturn(PETSC_SUCCESS);
1930: }

1932: /*@C
1933:   SNESSetFunction - Sets the function evaluation routine and function
1934:   vector for use by the `SNES` routines in solving systems of nonlinear
1935:   equations.

1937:   Logically Collective

1939:   Input Parameters:
1940: + snes - the `SNES` context
1941: . r    - vector to store function values, may be `NULL`
1942: . f    - function evaluation routine;  for calling sequence see `SNESFunctionFn`
1943: - ctx  - [optional] user-defined context for private data for the
1944:          function evaluation routine (may be `NULL`)

1946:   Level: beginner

1948: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunctionFn`
1949: @*/
1950: PetscErrorCode SNESSetFunction(SNES snes, Vec r, SNESFunctionFn *f, PetscCtx ctx)
1951: {
1952:   DM dm;

1954:   PetscFunctionBegin;
1956:   if (r) {
1958:     PetscCheckSameComm(snes, 1, r, 2);
1959:     PetscCall(PetscObjectReference((PetscObject)r));
1960:     PetscCall(VecDestroy(&snes->vec_func));
1961:     snes->vec_func = r;
1962:   }
1963:   PetscCall(SNESGetDM(snes, &dm));
1964:   PetscCall(DMSNESSetFunction(dm, f, ctx));
1965:   if (f == SNESPicardComputeFunction) PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
1966:   PetscFunctionReturn(PETSC_SUCCESS);
1967: }

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

1972:   Logically Collective

1974:   Input Parameters:
1975: + snes - the `SNES` context
1976: - f    - vector to store function value

1978:   Level: developer

1980:   Notes:
1981:   This should not be modified during the solution procedure.

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

1985: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
1986: @*/
1987: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
1988: {
1989:   Vec vec_func;

1991:   PetscFunctionBegin;
1994:   PetscCheckSameComm(snes, 1, f, 2);
1995:   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1996:     snes->vec_func_init_set = PETSC_FALSE;
1997:     PetscFunctionReturn(PETSC_SUCCESS);
1998:   }
1999:   PetscCall(SNESGetFunction(snes, &vec_func, NULL, NULL));
2000:   PetscCall(VecCopy(f, vec_func));

2002:   snes->vec_func_init_set = PETSC_TRUE;
2003:   PetscFunctionReturn(PETSC_SUCCESS);
2004: }

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

2010:   Logically Collective

2012:   Input Parameters:
2013: + snes         - the `SNES` context
2014: - normschedule - the frequency of norm computation

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

2019:   Level: advanced

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

2030: .seealso: [](ch_snes), `SNESNormSchedule`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`
2031: @*/
2032: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
2033: {
2034:   PetscFunctionBegin;
2036:   snes->normschedule = normschedule;
2037:   PetscFunctionReturn(PETSC_SUCCESS);
2038: }

2040: /*@
2041:   SNESGetNormSchedule - Gets the `SNESNormSchedule` used in convergence and monitoring
2042:   of the `SNES` method.

2044:   Logically Collective

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

2050:   Level: advanced

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

2062: /*@
2063:   SNESSetFunctionNorm - Sets the last computed residual norm.

2065:   Logically Collective

2067:   Input Parameters:
2068: + snes - the `SNES` context
2069: - norm - the value of the norm

2071:   Level: developer

2073: .seealso: [](ch_snes), `SNES`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2074: @*/
2075: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2076: {
2077:   PetscFunctionBegin;
2079:   snes->norm = norm;
2080:   PetscFunctionReturn(PETSC_SUCCESS);
2081: }

2083: /*@
2084:   SNESGetFunctionNorm - Gets the last computed norm of the residual

2086:   Not Collective

2088:   Input Parameter:
2089: . snes - the `SNES` context

2091:   Output Parameter:
2092: . norm - the last computed residual norm

2094:   Level: developer

2096: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2097: @*/
2098: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2099: {
2100:   PetscFunctionBegin;
2102:   PetscAssertPointer(norm, 2);
2103:   *norm = snes->norm;
2104:   PetscFunctionReturn(PETSC_SUCCESS);
2105: }

2107: /*@
2108:   SNESGetUpdateNorm - Gets the last computed norm of the solution update

2110:   Not Collective

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

2115:   Output Parameter:
2116: . ynorm - the last computed update norm

2118:   Level: developer

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

2123: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2124: @*/
2125: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2126: {
2127:   PetscFunctionBegin;
2129:   PetscAssertPointer(ynorm, 2);
2130:   *ynorm = snes->ynorm;
2131:   PetscFunctionReturn(PETSC_SUCCESS);
2132: }

2134: /*@
2135:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2137:   Not Collective

2139:   Input Parameter:
2140: . snes - the `SNES` context

2142:   Output Parameter:
2143: . xnorm - the last computed solution norm

2145:   Level: developer

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

2158: /*@
2159:   SNESSetFunctionType - Sets the `SNESFunctionType`
2160:   of the `SNES` method.

2162:   Logically Collective

2164:   Input Parameters:
2165: + snes - the `SNES` context
2166: - type - the function type

2168:   Level: developer

2170:   Values of the function type\:
2171: +  `SNES_FUNCTION_DEFAULT`          - the default for the given `SNESType`
2172: .  `SNES_FUNCTION_UNPRECONDITIONED` - an unpreconditioned function evaluation (this is the function provided with `SNESSetFunction()`
2173: -  `SNES_FUNCTION_PRECONDITIONED`   - a transformation of the function provided with `SNESSetFunction()`

2175:   Note:
2176:   Different `SNESType`s use this value in different ways

2178: .seealso: [](ch_snes), `SNES`, `SNESFunctionType`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2179: @*/
2180: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2181: {
2182:   PetscFunctionBegin;
2184:   snes->functype = type;
2185:   PetscFunctionReturn(PETSC_SUCCESS);
2186: }

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

2192:   Logically Collective

2194:   Input Parameters:
2195: + snes - the `SNES` context
2196: - type - the type of the function evaluation, see `SNESSetFunctionType()`

2198:   Level: advanced

2200: .seealso: [](ch_snes), `SNESSetFunctionType()`, `SNESFunctionType`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2201: @*/
2202: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2203: {
2204:   PetscFunctionBegin;
2206:   *type = snes->functype;
2207:   PetscFunctionReturn(PETSC_SUCCESS);
2208: }

2210: /*@C
2211:   SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2212:   use with composed nonlinear solvers.

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

2219:   Level: intermediate

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

2225: .seealso: [](ch_snes), `SNESNGS`, `SNESGetNGS()`, `SNESNCG`, `SNESGetFunction()`, `SNESComputeNGS()`, `SNESNGSFn`
2226: @*/
2227: PetscErrorCode SNESSetNGS(SNES snes, SNESNGSFn *f, PetscCtx ctx)
2228: {
2229:   DM dm;

2231:   PetscFunctionBegin;
2233:   PetscCall(SNESGetDM(snes, &dm));
2234:   PetscCall(DMSNESSetNGS(dm, f, ctx));
2235:   PetscFunctionReturn(PETSC_SUCCESS);
2236: }

2238: /*
2239:      This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2240:    changed during the KSPSolve()
2241: */
2242: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2243: {
2244:   DM     dm;
2245:   DMSNES sdm;

2247:   PetscFunctionBegin;
2248:   PetscCall(SNESGetDM(snes, &dm));
2249:   PetscCall(DMGetDMSNES(dm, &sdm));
2250:   /*  A(x)*x - b(x) */
2251:   if (sdm->ops->computepfunction) {
2252:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2253:     PetscCall(VecScale(f, -1.0));
2254:     /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2255:     if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2256:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2257:     PetscCall(MatMultAdd(snes->picard, x, f, f));
2258:   } else {
2259:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2260:     PetscCall(MatMult(snes->picard, x, f));
2261:   }
2262:   PetscFunctionReturn(PETSC_SUCCESS);
2263: }

2265: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2266: {
2267:   DM     dm;
2268:   DMSNES sdm;

2270:   PetscFunctionBegin;
2271:   PetscCall(SNESGetDM(snes, &dm));
2272:   PetscCall(DMGetDMSNES(dm, &sdm));
2273:   /*  A(x)*x - b(x) */
2274:   if (sdm->ops->computepfunction) {
2275:     PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2276:     PetscCall(VecScale(f, -1.0));
2277:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2278:     PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2279:   } else {
2280:     PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2281:     PetscCall(MatMult(snes->jacobian_pre, x, f));
2282:   }
2283:   PetscFunctionReturn(PETSC_SUCCESS);
2284: }

2286: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2287: {
2288:   PetscFunctionBegin;
2289:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2290:   /* must assembly if matrix-free to get the last SNES solution */
2291:   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2292:   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2293:   PetscFunctionReturn(PETSC_SUCCESS);
2294: }

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

2299:   Logically Collective

2301:   Input Parameters:
2302: + snes - the `SNES` context
2303: . r    - vector to store function values, may be `NULL`
2304: . bp   - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2305: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2306: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2307: . J    - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2308: - ctx  - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)

2310:   Level: intermediate

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

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

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

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

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

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

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

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

2335:   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
2336:   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
2337:   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`.
2338:   See the comment in src/snes/tutorials/ex15.c.

2340: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2341:           `SNESFunctionFn`, `SNESJacobianFn`
2342: @*/
2343: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2344: {
2345:   DM dm;

2347:   PetscFunctionBegin;
2349:   PetscCall(SNESGetDM(snes, &dm));
2350:   PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2351:   PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2352:   PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2353:   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2354:   PetscFunctionReturn(PETSC_SUCCESS);
2355: }

2357: /*@C
2358:   SNESGetPicard - Returns the context for the Picard iteration

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

2362:   Input Parameter:
2363: . snes - the `SNES` context

2365:   Output Parameters:
2366: + r    - the function (or `NULL`)
2367: . f    - the function (or `NULL`);  for calling sequence see `SNESFunctionFn`
2368: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2369: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2370: . J    - the function for matrix evaluation (or `NULL`);  for calling sequence see `SNESJacobianFn`
2371: - ctx  - the function context (or `NULL`)

2373:   Level: advanced

2375: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2376: @*/
2377: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2378: {
2379:   DM dm;

2381:   PetscFunctionBegin;
2383:   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2384:   PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2385:   PetscCall(SNESGetDM(snes, &dm));
2386:   PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2387:   PetscFunctionReturn(PETSC_SUCCESS);
2388: }

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

2393:   Logically Collective

2395:   Input Parameters:
2396: + snes - the `SNES` context
2397: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2398: - ctx  - [optional] user-defined context for private data for the
2399:          function evaluation routine (may be `NULL`)

2401:   Level: intermediate

2403: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2404: @*/
2405: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2406: {
2407:   PetscFunctionBegin;
2409:   if (func) snes->ops->computeinitialguess = func;
2410:   if (ctx) snes->initialguessP = ctx;
2411:   PetscFunctionReturn(PETSC_SUCCESS);
2412: }

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

2418:   Logically Collective

2420:   Input Parameter:
2421: . snes - the `SNES` context

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

2426:   Level: intermediate

2428: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2429: @*/
2430: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2431: {
2432:   PetscFunctionBegin;
2434:   PetscAssertPointer(rhs, 2);
2435:   *rhs = snes->vec_rhs;
2436:   PetscFunctionReturn(PETSC_SUCCESS);
2437: }

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

2442:   Collective

2444:   Input Parameters:
2445: + snes - the `SNES` context
2446: - x    - input vector

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

2451:   Level: developer

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

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

2459:   This function usually appears in the pattern.
2460: .vb
2461:   SNESComputeFunction(snes, x, f);
2462:   VecNorm(f, &fnorm);
2463:   SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2464: .ve
2465:   to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.

2467: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2468: @*/
2469: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2470: {
2471:   DM     dm;
2472:   DMSNES sdm;

2474:   PetscFunctionBegin;
2478:   PetscCheckSameComm(snes, 1, x, 2);
2479:   PetscCheckSameComm(snes, 1, f, 3);
2480:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

2482:   PetscCall(SNESGetDM(snes, &dm));
2483:   PetscCall(DMGetDMSNES(dm, &sdm));
2484:   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().");
2485:   if (sdm->ops->computefunction) {
2486:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2487:     PetscCall(VecLockReadPush(x));
2488:     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2489:     snes->functiondomainerror = PETSC_FALSE;
2490:     {
2491:       void           *ctx;
2492:       SNESFunctionFn *computefunction;
2493:       PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2494:       PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2495:     }
2496:     PetscCall(VecLockReadPop(x));
2497:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2498:   } else /* if (snes->vec_rhs) */ {
2499:     PetscCall(MatMult(snes->jacobian, x, f));
2500:   }
2501:   if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2502:   snes->nfuncs++;
2503:   /*
2504:      domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2505:      propagate the value to all processes
2506:   */
2507:   PetscCall(VecFlag(f, snes->functiondomainerror));
2508:   PetscFunctionReturn(PETSC_SUCCESS);
2509: }

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

2514:   Collective

2516:   Input Parameters:
2517: + snes - the `SNES` context
2518: - x    - input vector

2520:   Output Parameter:
2521: . y - output vector

2523:   Level: developer

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

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

2533: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2534: @*/
2535: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2536: {
2537:   DM     dm;
2538:   DMSNES sdm;

2540:   PetscFunctionBegin;
2544:   PetscCheckSameComm(snes, 1, x, 2);
2545:   PetscCheckSameComm(snes, 1, y, 3);
2546:   PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));

2548:   PetscCall(SNESGetDM(snes, &dm));
2549:   PetscCall(DMGetDMSNES(dm, &sdm));
2550:   PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, y, 0));
2551:   PetscCall(VecLockReadPush(x));
2552:   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2553:   snes->functiondomainerror = PETSC_FALSE;
2554:   PetscCallBack("SNES callback function", (*sdm->ops->computemffunction)(snes, x, y, sdm->mffunctionctx));
2555:   PetscCall(VecLockReadPop(x));
2556:   PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, y, 0));
2557:   snes->nfuncs++;
2558:   /*
2559:      domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2560:      propagate the value to all processes
2561:   */
2562:   PetscCall(VecFlag(y, snes->functiondomainerror));
2563:   PetscFunctionReturn(PETSC_SUCCESS);
2564: }

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

2569:   Collective

2571:   Input Parameters:
2572: + snes - the `SNES` context
2573: . x    - input vector
2574: - b    - rhs vector

2576:   Output Parameter:
2577: . x - new solution vector

2579:   Level: developer

2581:   Note:
2582:   `SNESComputeNGS()` is typically used within composed nonlinear solver
2583:   implementations, so most users would not generally call this routine
2584:   themselves.

2586: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2587: @*/
2588: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2589: {
2590:   DM     dm;
2591:   DMSNES sdm;

2593:   PetscFunctionBegin;
2597:   PetscCheckSameComm(snes, 1, x, 3);
2598:   if (b) PetscCheckSameComm(snes, 1, b, 2);
2599:   if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2600:   PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2601:   PetscCall(SNESGetDM(snes, &dm));
2602:   PetscCall(DMGetDMSNES(dm, &sdm));
2603:   PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2604:   if (b) PetscCall(VecLockReadPush(b));
2605:   PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2606:   if (b) PetscCall(VecLockReadPop(b));
2607:   PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2608:   PetscFunctionReturn(PETSC_SUCCESS);
2609: }

2611: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2612: {
2613:   Vec          X;
2614:   PetscScalar *g;
2615:   PetscReal    f, f2;
2616:   PetscInt     low, high, N, i;
2617:   PetscBool    flg;
2618:   PetscReal    h = .5 * PETSC_SQRT_MACHINE_EPSILON;

2620:   PetscFunctionBegin;
2621:   PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2622:   PetscCall(VecDuplicate(Xin, &X));
2623:   PetscCall(VecCopy(Xin, X));
2624:   PetscCall(VecGetSize(X, &N));
2625:   PetscCall(VecGetOwnershipRange(X, &low, &high));
2626:   PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2627:   PetscCall(VecGetArray(G, &g));
2628:   for (i = 0; i < N; i++) {
2629:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2630:     PetscCall(VecAssemblyBegin(X));
2631:     PetscCall(VecAssemblyEnd(X));
2632:     PetscCall(SNESComputeObjective(snes, X, &f));
2633:     PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2634:     PetscCall(VecAssemblyBegin(X));
2635:     PetscCall(VecAssemblyEnd(X));
2636:     PetscCall(SNESComputeObjective(snes, X, &f2));
2637:     PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2638:     PetscCall(VecAssemblyBegin(X));
2639:     PetscCall(VecAssemblyEnd(X));
2640:     if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2641:   }
2642:   PetscCall(VecRestoreArray(G, &g));
2643:   PetscCall(VecDestroy(&X));
2644:   PetscFunctionReturn(PETSC_SUCCESS);
2645: }

2647: /*@
2648:   SNESTestFunction - Computes the difference between the computed and finite-difference functions

2650:   Collective

2652:   Input Parameter:
2653: . snes - the `SNES` context

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

2659:   Level: developer

2661: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2662: @*/
2663: PetscErrorCode SNESTestFunction(SNES snes)
2664: {
2665:   Vec               x, g1, g2, g3;
2666:   PetscBool         complete_print = PETSC_FALSE;
2667:   PetscReal         hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2668:   PetscScalar       dot;
2669:   MPI_Comm          comm;
2670:   PetscViewer       viewer, mviewer;
2671:   PetscViewerFormat format;
2672:   PetscInt          tabs;
2673:   static PetscBool  directionsprinted = PETSC_FALSE;
2674:   SNESObjectiveFn  *objective;

2676:   PetscFunctionBegin;
2677:   PetscCall(SNESGetObjective(snes, &objective, NULL));
2678:   if (!objective) PetscFunctionReturn(PETSC_SUCCESS);

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

2684:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2685:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2686:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2687:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2688:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Function -------------\n"));
2689:   if (!complete_print && !directionsprinted) {
2690:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2691:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference function entries greater than <threshold>.\n"));
2692:   }
2693:   if (!directionsprinted) {
2694:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2695:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Function is probably correct.\n"));
2696:     directionsprinted = PETSC_TRUE;
2697:   }
2698:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2700:   PetscCall(SNESGetSolution(snes, &x));
2701:   PetscCall(VecDuplicate(x, &g1));
2702:   PetscCall(VecDuplicate(x, &g2));
2703:   PetscCall(VecDuplicate(x, &g3));
2704:   PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() corrrectly */
2705:   PetscCall(SNESComputeFunction_FD(snes, x, g2));

2707:   PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2708:   PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2709:   PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2710:   PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2711:   PetscCall(VecDot(g1, g2, &dot));
2712:   PetscCall(VecCopy(g1, g3));
2713:   PetscCall(VecAXPY(g3, -1.0, g2));
2714:   PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2715:   PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2716:   PetscCall(PetscViewerASCIIPrintf(viewer, "  ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2717:   PetscCall(PetscViewerASCIIPrintf(viewer, "  2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2718:   PetscCall(PetscViewerASCIIPrintf(viewer, "  max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));

2720:   if (complete_print) {
2721:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded function ----------\n"));
2722:     PetscCall(VecView(g1, mviewer));
2723:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference function ----------\n"));
2724:     PetscCall(VecView(g2, mviewer));
2725:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded minus finite-difference function ----------\n"));
2726:     PetscCall(VecView(g3, mviewer));
2727:   }
2728:   PetscCall(VecDestroy(&g1));
2729:   PetscCall(VecDestroy(&g2));
2730:   PetscCall(VecDestroy(&g3));

2732:   if (complete_print) {
2733:     PetscCall(PetscViewerPopFormat(mviewer));
2734:     PetscCall(PetscViewerDestroy(&mviewer));
2735:   }
2736:   PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2737:   PetscFunctionReturn(PETSC_SUCCESS);
2738: }

2740: /*@
2741:   SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians

2743:   Collective

2745:   Input Parameter:
2746: . snes - the `SNES` context

2748:   Output Parameters:
2749: + Jnorm    - the Frobenius norm of the computed Jacobian, or `NULL`
2750: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`

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

2756:   Level: developer

2758:   Note:
2759:   Directions and norms are printed to stdout if `diffNorm` is `NULL`.

2761: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2762: @*/
2763: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2764: {
2765:   Mat               A, B, C, D, jacobian;
2766:   Vec               x = snes->vec_sol, f;
2767:   PetscReal         nrm, gnorm;
2768:   PetscReal         threshold = 1.e-5;
2769:   void             *functx;
2770:   PetscBool         complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2771:   PetscBool         silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2772:   PetscViewer       viewer, mviewer;
2773:   MPI_Comm          comm;
2774:   PetscInt          tabs;
2775:   static PetscBool  directionsprinted = PETSC_FALSE;
2776:   PetscViewerFormat format;

2778:   PetscFunctionBegin;
2779:   PetscObjectOptionsBegin((PetscObject)snes);
2780:   PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2781:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2782:   PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2783:   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2784:   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));
2785:   PetscOptionsEnd();

2787:   PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2788:   PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2789:   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2790:   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2791:   if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Jacobian -------------\n"));
2792:   if (!complete_print && !silent && !directionsprinted) {
2793:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2794:     PetscCall(PetscViewerASCIIPrintf(viewer, "    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2795:   }
2796:   if (!directionsprinted && !silent) {
2797:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2798:     PetscCall(PetscViewerASCIIPrintf(viewer, "    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2799:     directionsprinted = PETSC_TRUE;
2800:   }
2801:   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));

2803:   PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2804:   if (!flg) jacobian = snes->jacobian;
2805:   else jacobian = snes->jacobian_pre;

2807:   if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2808:   else PetscCall(PetscObjectReference((PetscObject)x));
2809:   PetscCall(VecDuplicate(x, &f));

2811:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2812:   PetscCall(SNESComputeFunction(snes, x, f));
2813:   PetscCall(VecDestroy(&f));
2814:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2815:   while (jacobian) {
2816:     Mat JT = NULL, Jsave = NULL;

2818:     if (istranspose) {
2819:       PetscCall(MatCreateTranspose(jacobian, &JT));
2820:       Jsave    = jacobian;
2821:       jacobian = JT;
2822:     }
2823:     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2824:     if (flg) {
2825:       A = jacobian;
2826:       PetscCall(PetscObjectReference((PetscObject)A));
2827:     } else {
2828:       PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2829:     }

2831:     PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2832:     PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

2834:     PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2835:     PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));

2837:     PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2838:     PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2839:     PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2840:     PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2841:     PetscCall(MatDestroy(&D));
2842:     if (!gnorm) gnorm = 1; /* just in case */
2843:     if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2844:     if (complete_print) {
2845:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded Jacobian ----------\n"));
2846:       PetscCall(MatView(A, mviewer));
2847:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Finite difference Jacobian ----------\n"));
2848:       PetscCall(MatView(B, mviewer));
2849:     }

2851:     if (threshold_print || complete_print) {
2852:       PetscInt           Istart, Iend, *ccols, bncols, cncols, j, row;
2853:       PetscScalar       *cvals;
2854:       const PetscInt    *bcols;
2855:       const PetscScalar *bvals;

2857:       PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2858:       PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));

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

2863:       for (row = Istart; row < Iend; row++) {
2864:         PetscCall(MatGetRow(B, row, &bncols, &bcols, &bvals));
2865:         PetscCall(PetscMalloc2(bncols, &ccols, bncols, &cvals));
2866:         for (j = 0, cncols = 0; j < bncols; j++) {
2867:           if (PetscAbsScalar(bvals[j]) > threshold) {
2868:             ccols[cncols] = bcols[j];
2869:             cvals[cncols] = bvals[j];
2870:             cncols += 1;
2871:           }
2872:         }
2873:         if (cncols) PetscCall(MatSetValues(C, 1, &row, cncols, ccols, cvals, INSERT_VALUES));
2874:         PetscCall(MatRestoreRow(B, row, &bncols, &bcols, &bvals));
2875:         PetscCall(PetscFree2(ccols, cvals));
2876:       }
2877:       PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2878:       PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2879:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n", (double)threshold));
2880:       PetscCall(MatView(C, complete_print ? mviewer : viewer));
2881:       PetscCall(MatDestroy(&C));
2882:     }
2883:     PetscCall(MatDestroy(&A));
2884:     PetscCall(MatDestroy(&B));
2885:     PetscCall(MatDestroy(&JT));
2886:     if (Jsave) jacobian = Jsave;
2887:     if (jacobian != snes->jacobian_pre) {
2888:       jacobian = snes->jacobian_pre;
2889:       if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, "  ---------- Testing Jacobian for preconditioner -------------\n"));
2890:     } else jacobian = NULL;
2891:   }
2892:   PetscCall(VecDestroy(&x));
2893:   if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2894:   if (mviewer) PetscCall(PetscViewerDestroy(&mviewer));
2895:   PetscCall(PetscViewerASCIISetTab(viewer, tabs));

2897:   if (Jnorm) *Jnorm = gnorm;
2898:   if (diffNorm) *diffNorm = nrm;
2899:   PetscFunctionReturn(PETSC_SUCCESS);
2900: }

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

2905:   Collective

2907:   Input Parameters:
2908: + snes - the `SNES` context
2909: - X    - input vector

2911:   Output Parameters:
2912: + A - Jacobian matrix
2913: - B - optional matrix for building the preconditioner, usually the same as `A`

2915:   Options Database Keys:
2916: + -snes_lag_preconditioner lag          - how often to rebuild preconditioner
2917: . -snes_lag_jacobian lag                - how often to rebuild Jacobian
2918: . -snes_test_jacobian [threshold]       - compare the user provided Jacobian with one compute via finite differences to check for errors.
2919:                                           If a threshold is given, display only those entries whose difference is greater than the threshold.
2920: . -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
2921: . -snes_compare_explicit                - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2922: . -snes_compare_explicit_draw           - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2923: . -snes_compare_explicit_contour        - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2924: . -snes_compare_operator                - Make the comparison options above use the operator instead of the matrix used to construct the preconditioner
2925: . -snes_compare_coloring                - Compute the finite difference Jacobian using coloring and display norms of difference
2926: . -snes_compare_coloring_display        - Compute the finite difference Jacobian using coloring and display verbose differences
2927: . -snes_compare_coloring_threshold      - Display only those matrix entries that differ by more than a given threshold
2928: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2929: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2930: . -snes_compare_coloring_draw           - Compute the finite difference Jacobian using coloring and draw differences
2931: - -snes_compare_coloring_draw_contour   - Compute the finite difference Jacobian using coloring and show contours of matrices and differences

2933:   Level: developer

2935:   Note:
2936:   Most users should not need to explicitly call this routine, as it
2937:   is used internally within the nonlinear solvers.

2939:   Developer Note:
2940:   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
2941:   with the `SNESType` of test that has been removed.

2943: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
2944:           `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
2945: @*/
2946: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
2947: {
2948:   PetscBool flag;
2949:   DM        dm;
2950:   DMSNES    sdm;
2951:   KSP       ksp;

2953:   PetscFunctionBegin;
2956:   PetscCheckSameComm(snes, 1, X, 2);
2957:   PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
2958:   PetscCall(SNESGetDM(snes, &dm));
2959:   PetscCall(DMGetDMSNES(dm, &sdm));

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

2965:     PetscCall(PetscInfo(snes, "Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
2966:   } else if (snes->lagjacobian == -1) {
2967:     PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is -1\n"));
2968:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
2969:     if (flag) {
2970:       PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2971:       PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2972:     }
2973:     PetscFunctionReturn(PETSC_SUCCESS);
2974:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2975:     PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagjacobian, snes->iter));
2976:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
2977:     if (flag) {
2978:       PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2979:       PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2980:     }
2981:     PetscFunctionReturn(PETSC_SUCCESS);
2982:   }
2983:   if (snes->npc && snes->npcside == PC_LEFT) {
2984:     PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2985:     PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2986:     PetscFunctionReturn(PETSC_SUCCESS);
2987:   }

2989:   PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
2990:   PetscCall(VecLockReadPush(X));
2991:   {
2992:     void           *ctx;
2993:     SNESJacobianFn *J;
2994:     PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
2995:     PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
2996:   }
2997:   PetscCall(VecLockReadPop(X));
2998:   PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));

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

3003:   /* the next line ensures that snes->ksp exists */
3004:   PetscCall(SNESGetKSP(snes, &ksp));
3005:   if (snes->lagpreconditioner == -2) {
3006:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3007:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3008:     snes->lagpreconditioner = -1;
3009:   } else if (snes->lagpreconditioner == -1) {
3010:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3011:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3012:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3013:     PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3014:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3015:   } else {
3016:     PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3017:     PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3018:   }

3020:   /* monkey business to allow testing Jacobians in multilevel solvers.
3021:      This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3022:   {
3023:     Vec xsave            = snes->vec_sol;
3024:     Mat jacobiansave     = snes->jacobian;
3025:     Mat jacobian_presave = snes->jacobian_pre;

3027:     snes->vec_sol      = X;
3028:     snes->jacobian     = A;
3029:     snes->jacobian_pre = B;
3030:     if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3031:     if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));

3033:     snes->vec_sol      = xsave;
3034:     snes->jacobian     = jacobiansave;
3035:     snes->jacobian_pre = jacobian_presave;
3036:   }

3038:   {
3039:     PetscBool flag = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_operator = PETSC_FALSE;
3040:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit", NULL, NULL, &flag));
3041:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw", NULL, NULL, &flag_draw));
3042:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw_contour", NULL, NULL, &flag_contour));
3043:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_operator", NULL, NULL, &flag_operator));
3044:     if (flag || flag_draw || flag_contour) {
3045:       Mat         Bexp_mine = NULL, Bexp, FDexp;
3046:       PetscViewer vdraw, vstdout;
3047:       PetscBool   flg;
3048:       if (flag_operator) {
3049:         PetscCall(MatComputeOperator(A, MATAIJ, &Bexp_mine));
3050:         Bexp = Bexp_mine;
3051:       } else {
3052:         /* See if the matrix used to construct the preconditioner can be viewed and added directly */
3053:         PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
3054:         if (flg) Bexp = B;
3055:         else {
3056:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
3057:           PetscCall(MatComputeOperator(B, MATAIJ, &Bexp_mine));
3058:           Bexp = Bexp_mine;
3059:         }
3060:       }
3061:       PetscCall(MatConvert(Bexp, MATSAME, MAT_INITIAL_MATRIX, &FDexp));
3062:       PetscCall(SNESComputeJacobianDefault(snes, X, FDexp, FDexp, NULL));
3063:       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3064:       if (flag_draw || flag_contour) {
3065:         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Explicit Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3066:         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3067:       } else vdraw = NULL;
3068:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit %s\n", flag_operator ? "Jacobian" : "preconditioning Jacobian"));
3069:       if (flag) PetscCall(MatView(Bexp, vstdout));
3070:       if (vdraw) PetscCall(MatView(Bexp, vdraw));
3071:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Finite difference Jacobian\n"));
3072:       if (flag) PetscCall(MatView(FDexp, vstdout));
3073:       if (vdraw) PetscCall(MatView(FDexp, vdraw));
3074:       PetscCall(MatAYPX(FDexp, -1.0, Bexp, SAME_NONZERO_PATTERN));
3075:       PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian\n"));
3076:       if (flag) PetscCall(MatView(FDexp, vstdout));
3077:       if (vdraw) { /* Always use contour for the difference */
3078:         PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3079:         PetscCall(MatView(FDexp, vdraw));
3080:         PetscCall(PetscViewerPopFormat(vdraw));
3081:       }
3082:       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3083:       PetscCall(PetscViewerDestroy(&vdraw));
3084:       PetscCall(MatDestroy(&Bexp_mine));
3085:       PetscCall(MatDestroy(&FDexp));
3086:     }
3087:   }
3088:   {
3089:     PetscBool flag = PETSC_FALSE, flag_display = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_threshold = PETSC_FALSE;
3090:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON, threshold_rtol = 10 * PETSC_SQRT_MACHINE_EPSILON;
3091:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring", NULL, NULL, &flag));
3092:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_display", NULL, NULL, &flag_display));
3093:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw", NULL, NULL, &flag_draw));
3094:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw_contour", NULL, NULL, &flag_contour));
3095:     PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold", NULL, NULL, &flag_threshold));
3096:     if (flag_threshold) {
3097:       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_rtol", &threshold_rtol, NULL));
3098:       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_atol", &threshold_atol, NULL));
3099:     }
3100:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
3101:       Mat             Bfd;
3102:       PetscViewer     vdraw, vstdout;
3103:       MatColoring     coloring;
3104:       ISColoring      iscoloring;
3105:       MatFDColoring   matfdcoloring;
3106:       SNESFunctionFn *func;
3107:       void           *funcctx;
3108:       PetscReal       norm1, norm2, normmax;

3110:       PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3111:       PetscCall(MatColoringCreate(Bfd, &coloring));
3112:       PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3113:       PetscCall(MatColoringSetFromOptions(coloring));
3114:       PetscCall(MatColoringApply(coloring, &iscoloring));
3115:       PetscCall(MatColoringDestroy(&coloring));
3116:       PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3117:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3118:       PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3119:       PetscCall(ISColoringDestroy(&iscoloring));

3121:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3122:       PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3123:       PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3124:       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3125:       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3126:       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3127:       PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3128:       PetscCall(MatFDColoringDestroy(&matfdcoloring));

3130:       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3131:       if (flag_draw || flag_contour) {
3132:         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Colored Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3133:         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3134:       } else vdraw = NULL;
3135:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit preconditioning Jacobian\n"));
3136:       if (flag_display) PetscCall(MatView(B, vstdout));
3137:       if (vdraw) PetscCall(MatView(B, vdraw));
3138:       PetscCall(PetscViewerASCIIPrintf(vstdout, "Colored Finite difference Jacobian\n"));
3139:       if (flag_display) PetscCall(MatView(Bfd, vstdout));
3140:       if (vdraw) PetscCall(MatView(Bfd, vdraw));
3141:       PetscCall(MatAYPX(Bfd, -1.0, B, SAME_NONZERO_PATTERN));
3142:       PetscCall(MatNorm(Bfd, NORM_1, &norm1));
3143:       PetscCall(MatNorm(Bfd, NORM_FROBENIUS, &norm2));
3144:       PetscCall(MatNorm(Bfd, NORM_MAX, &normmax));
3145:       PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n", (double)norm1, (double)norm2, (double)normmax));
3146:       if (flag_display) PetscCall(MatView(Bfd, vstdout));
3147:       if (vdraw) { /* Always use contour for the difference */
3148:         PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3149:         PetscCall(MatView(Bfd, vdraw));
3150:         PetscCall(PetscViewerPopFormat(vdraw));
3151:       }
3152:       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));

3154:       if (flag_threshold) {
3155:         PetscInt bs, rstart, rend, i;
3156:         PetscCall(MatGetBlockSize(B, &bs));
3157:         PetscCall(MatGetOwnershipRange(B, &rstart, &rend));
3158:         for (i = rstart; i < rend; i++) {
3159:           const PetscScalar *ba, *ca;
3160:           const PetscInt    *bj, *cj;
3161:           PetscInt           bn, cn, j, maxentrycol = -1, maxdiffcol = -1, maxrdiffcol = -1;
3162:           PetscReal          maxentry = 0, maxdiff = 0, maxrdiff = 0;
3163:           PetscCall(MatGetRow(B, i, &bn, &bj, &ba));
3164:           PetscCall(MatGetRow(Bfd, i, &cn, &cj, &ca));
3165:           PetscCheck(bn == cn, ((PetscObject)A)->comm, PETSC_ERR_PLIB, "Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
3166:           for (j = 0; j < bn; j++) {
3167:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3168:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
3169:               maxentrycol = bj[j];
3170:               maxentry    = PetscRealPart(ba[j]);
3171:             }
3172:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
3173:               maxdiffcol = bj[j];
3174:               maxdiff    = PetscRealPart(ca[j]);
3175:             }
3176:             if (rdiff > maxrdiff) {
3177:               maxrdiffcol = bj[j];
3178:               maxrdiff    = rdiff;
3179:             }
3180:           }
3181:           if (maxrdiff > 1) {
3182:             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));
3183:             for (j = 0; j < bn; j++) {
3184:               PetscReal rdiff;
3185:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3186:               if (rdiff > 1) PetscCall(PetscViewerASCIIPrintf(vstdout, " (%" PetscInt_FMT ",%g:%g)", bj[j], (double)PetscRealPart(ba[j]), (double)PetscRealPart(ca[j])));
3187:             }
3188:             PetscCall(PetscViewerASCIIPrintf(vstdout, "\n"));
3189:           }
3190:           PetscCall(MatRestoreRow(B, i, &bn, &bj, &ba));
3191:           PetscCall(MatRestoreRow(Bfd, i, &cn, &cj, &ca));
3192:         }
3193:       }
3194:       PetscCall(PetscViewerDestroy(&vdraw));
3195:       PetscCall(MatDestroy(&Bfd));
3196:     }
3197:   }
3198:   PetscFunctionReturn(PETSC_SUCCESS);
3199: }

3201: /*@C
3202:   SNESSetJacobian - Sets the function to compute Jacobian as well as the
3203:   location to store the matrix.

3205:   Logically Collective

3207:   Input Parameters:
3208: + snes - the `SNES` context
3209: . Amat - the matrix that defines the (approximate) Jacobian
3210: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3211: . J    - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3212: - ctx  - [optional] user-defined context for private data for the
3213:          Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)

3215:   Level: beginner

3217:   Notes:
3218:   If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3219:   each matrix.

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

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

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

3230: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3231:           `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3232: @*/
3233: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3234: {
3235:   DM dm;

3237:   PetscFunctionBegin;
3241:   if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3242:   if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3243:   PetscCall(SNESGetDM(snes, &dm));
3244:   PetscCall(DMSNESSetJacobian(dm, J, ctx));
3245:   if (Amat) {
3246:     PetscCall(PetscObjectReference((PetscObject)Amat));
3247:     PetscCall(MatDestroy(&snes->jacobian));

3249:     snes->jacobian = Amat;
3250:   }
3251:   if (Pmat) {
3252:     PetscCall(PetscObjectReference((PetscObject)Pmat));
3253:     PetscCall(MatDestroy(&snes->jacobian_pre));

3255:     snes->jacobian_pre = Pmat;
3256:   }
3257:   PetscFunctionReturn(PETSC_SUCCESS);
3258: }

3260: /*@C
3261:   SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3262:   provided context for evaluating the Jacobian.

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

3266:   Input Parameter:
3267: . snes - the nonlinear solver context

3269:   Output Parameters:
3270: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3271: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3272: . J    - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3273: - ctx  - location to stash Jacobian ctx (or `NULL`)

3275:   Level: advanced

3277: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3278: @*/
3279: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3280: {
3281:   DM dm;

3283:   PetscFunctionBegin;
3285:   if (Amat) *Amat = snes->jacobian;
3286:   if (Pmat) *Pmat = snes->jacobian_pre;
3287:   PetscCall(SNESGetDM(snes, &dm));
3288:   PetscCall(DMSNESGetJacobian(dm, J, ctx));
3289:   PetscFunctionReturn(PETSC_SUCCESS);
3290: }

3292: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3293: {
3294:   DM     dm;
3295:   DMSNES sdm;

3297:   PetscFunctionBegin;
3298:   PetscCall(SNESGetDM(snes, &dm));
3299:   PetscCall(DMGetDMSNES(dm, &sdm));
3300:   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3301:     DM        dm;
3302:     PetscBool isdense, ismf;

3304:     PetscCall(SNESGetDM(snes, &dm));
3305:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3306:     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3307:     if (isdense) {
3308:       PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3309:     } else if (!ismf) {
3310:       PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3311:     }
3312:   }
3313:   PetscFunctionReturn(PETSC_SUCCESS);
3314: }

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

3320:   Collective

3322:   Input Parameter:
3323: . snes - the `SNES` context

3325:   Level: advanced

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

3334: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3335: @*/
3336: PetscErrorCode SNESSetUp(SNES snes)
3337: {
3338:   DM             dm;
3339:   DMSNES         sdm;
3340:   SNESLineSearch linesearch, pclinesearch;
3341:   void          *lsprectx, *lspostctx;
3342:   PetscBool      mf_operator, mf;
3343:   Vec            f, fpc;
3344:   void          *funcctx;
3345:   void          *jacctx, *appctx;
3346:   Mat            j, jpre;
3347:   PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3348:   PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3349:   SNESFunctionFn *func;
3350:   SNESJacobianFn *jac;

3352:   PetscFunctionBegin;
3354:   if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3355:   PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));

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

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

3361:   PetscCall(SNESGetDM(snes, &dm));
3362:   PetscCall(DMGetDMSNES(dm, &sdm));
3363:   PetscCall(SNESSetDefaultComputeJacobian(snes));

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

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

3369:   if (snes->linesearch) {
3370:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3371:     PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3372:   }

3374:   PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3375:   if (snes->npc && snes->npcside == PC_LEFT) {
3376:     snes->mf          = PETSC_TRUE;
3377:     snes->mf_operator = PETSC_FALSE;
3378:   }

3380:   if (snes->npc) {
3381:     /* copy the DM over */
3382:     PetscCall(SNESGetDM(snes, &dm));
3383:     PetscCall(SNESSetDM(snes->npc, dm));

3385:     PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3386:     PetscCall(VecDuplicate(f, &fpc));
3387:     PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3388:     PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3389:     PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3390:     PetscCall(SNESGetApplicationContext(snes, &appctx));
3391:     PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3392:     PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3393:     PetscCall(VecDestroy(&fpc));

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

3398:     /* default to 1 iteration */
3399:     PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
3400:     if (snes->npcside == PC_RIGHT) {
3401:       PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3402:     } else {
3403:       PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3404:     }
3405:     PetscCall(SNESSetFromOptions(snes->npc));

3407:     /* copy the line search context over */
3408:     if (snes->linesearch && snes->npc->linesearch) {
3409:       PetscCall(SNESGetLineSearch(snes, &linesearch));
3410:       PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3411:       PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3412:       PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3413:       PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3414:       PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3415:       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3416:     }
3417:   }
3418:   if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
3419:   if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));

3421:   snes->jac_iter = 0;
3422:   snes->pre_iter = 0;

3424:   PetscTryTypeMethod(snes, setup);

3426:   PetscCall(SNESSetDefaultComputeJacobian(snes));

3428:   if (snes->npc && snes->npcside == PC_LEFT) {
3429:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3430:       if (snes->linesearch) {
3431:         PetscCall(SNESGetLineSearch(snes, &linesearch));
3432:         PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3433:       }
3434:     }
3435:   }
3436:   PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3437:   snes->setupcalled = PETSC_TRUE;
3438:   PetscFunctionReturn(PETSC_SUCCESS);
3439: }

3441: /*@
3442:   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

3444:   Collective

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

3449:   Level: intermediate

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

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

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

3458: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3459: @*/
3460: PetscErrorCode SNESReset(SNES snes)
3461: {
3462:   PetscFunctionBegin;
3464:   if (snes->ops->ctxdestroy && snes->ctx) {
3465:     PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3466:     snes->ctx = NULL;
3467:   }
3468:   if (snes->npc) PetscCall(SNESReset(snes->npc));

3470:   PetscTryTypeMethod(snes, reset);
3471:   if (snes->ksp) PetscCall(KSPReset(snes->ksp));

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

3475:   PetscCall(VecDestroy(&snes->vec_rhs));
3476:   PetscCall(VecDestroy(&snes->vec_sol));
3477:   PetscCall(VecDestroy(&snes->vec_sol_update));
3478:   PetscCall(VecDestroy(&snes->vec_func));
3479:   PetscCall(MatDestroy(&snes->jacobian));
3480:   PetscCall(MatDestroy(&snes->jacobian_pre));
3481:   PetscCall(MatDestroy(&snes->picard));
3482:   PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3483:   PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));

3485:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3487:   snes->nwork = snes->nvwork = 0;
3488:   snes->setupcalled          = PETSC_FALSE;
3489:   PetscFunctionReturn(PETSC_SUCCESS);
3490: }

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

3496:   Collective

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

3501:   Level: intermediate

3503: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3504: @*/
3505: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3506: {
3507:   PetscInt i;

3509:   PetscFunctionBegin;
3511:   for (i = 0; i < snes->numberreasonviews; i++) {
3512:     if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3513:   }
3514:   snes->numberreasonviews = 0;
3515:   PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3516:   PetscFunctionReturn(PETSC_SUCCESS);
3517: }

3519: /*@
3520:   SNESDestroy - Destroys the nonlinear solver context that was created
3521:   with `SNESCreate()`.

3523:   Collective

3525:   Input Parameter:
3526: . snes - the `SNES` context

3528:   Level: beginner

3530: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3531: @*/
3532: PetscErrorCode SNESDestroy(SNES *snes)
3533: {
3534:   DM dm;

3536:   PetscFunctionBegin;
3537:   if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3539:   if (--((PetscObject)*snes)->refct > 0) {
3540:     *snes = NULL;
3541:     PetscFunctionReturn(PETSC_SUCCESS);
3542:   }

3544:   PetscCall(SNESReset(*snes));
3545:   PetscCall(SNESDestroy(&(*snes)->npc));

3547:   /* if memory was published with SAWs then destroy it */
3548:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3549:   PetscTryTypeMethod(*snes, destroy);

3551:   dm = (*snes)->dm;
3552:   while (dm) {
3553:     PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3554:     PetscCall(DMGetCoarseDM(dm, &dm));
3555:   }

3557:   PetscCall(DMDestroy(&(*snes)->dm));
3558:   PetscCall(KSPDestroy(&(*snes)->ksp));
3559:   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));

3561:   PetscCall(PetscFree((*snes)->kspconvctx));
3562:   if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3563:   if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3564:   PetscCall(SNESMonitorCancel(*snes));
3565:   PetscCall(SNESConvergedReasonViewCancel(*snes));
3566:   PetscCall(PetscHeaderDestroy(snes));
3567:   PetscFunctionReturn(PETSC_SUCCESS);
3568: }

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

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

3575:   Logically Collective

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

3582:   Options Database Keys:
3583: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple `SNESSolve()`
3584: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3585: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3586: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3588:   Level: intermediate

3590:   Notes:
3591:   The default is 1

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

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

3597: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3598:           `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3599: @*/
3600: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3601: {
3602:   PetscFunctionBegin;
3604:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3605:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3607:   snes->lagpreconditioner = lag;
3608:   PetscFunctionReturn(PETSC_SUCCESS);
3609: }

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

3614:   Logically Collective

3616:   Input Parameters:
3617: + snes  - the `SNES` context
3618: - steps - the number of refinements to do, defaults to 0

3620:   Options Database Key:
3621: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess

3623:   Level: intermediate

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

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

3630: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3631:           `SNESSetDM()`, `SNESSolve()`
3632: @*/
3633: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3634: {
3635:   PetscFunctionBegin;
3638:   snes->gridsequence = steps;
3639:   PetscFunctionReturn(PETSC_SUCCESS);
3640: }

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

3645:   Logically Collective

3647:   Input Parameter:
3648: . snes - the `SNES` context

3650:   Output Parameter:
3651: . steps - the number of refinements to do, defaults to 0

3653:   Level: intermediate

3655: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3656: @*/
3657: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3658: {
3659:   PetscFunctionBegin;
3661:   *steps = snes->gridsequence;
3662:   PetscFunctionReturn(PETSC_SUCCESS);
3663: }

3665: /*@
3666:   SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt

3668:   Not Collective

3670:   Input Parameter:
3671: . snes - the `SNES` context

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

3677:   Level: intermediate

3679:   Notes:
3680:   The default is 1

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

3684: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3685: @*/
3686: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3687: {
3688:   PetscFunctionBegin;
3690:   *lag = snes->lagpreconditioner;
3691:   PetscFunctionReturn(PETSC_SUCCESS);
3692: }

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

3698:   Logically Collective

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

3705:   Options Database Keys:
3706: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3707: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3708: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3709: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag.

3711:   Level: intermediate

3713:   Notes:
3714:   The default is 1

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

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

3721: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3722: @*/
3723: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3724: {
3725:   PetscFunctionBegin;
3727:   PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3728:   PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3730:   snes->lagjacobian = lag;
3731:   PetscFunctionReturn(PETSC_SUCCESS);
3732: }

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

3737:   Not Collective

3739:   Input Parameter:
3740: . snes - the `SNES` context

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

3746:   Level: intermediate

3748:   Notes:
3749:   The default is 1

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

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

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

3766:   Logically collective

3768:   Input Parameters:
3769: + snes - the `SNES` context
3770: - flg  - jacobian lagging persists if true

3772:   Options Database Keys:
3773: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3774: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3775: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3776: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3778:   Level: advanced

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

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

3787: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3788: @*/
3789: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3790: {
3791:   PetscFunctionBegin;
3794:   snes->lagjac_persist = flg;
3795:   PetscFunctionReturn(PETSC_SUCCESS);
3796: }

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

3801:   Logically Collective

3803:   Input Parameters:
3804: + snes - the `SNES` context
3805: - flg  - preconditioner lagging persists if true

3807:   Options Database Keys:
3808: + -snes_lag_jacobian_persists (true|false)       - sets the persistence through multiple SNES solves
3809: . -snes_lag_jacobian (-2|1|2|...)                - sets the lag
3810: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3811: - -snes_lag_preconditioner (-2|1|2|...)          - sets the lag

3813:   Level: developer

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

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

3822: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3823: @*/
3824: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3825: {
3826:   PetscFunctionBegin;
3829:   snes->lagpre_persist = flg;
3830:   PetscFunctionReturn(PETSC_SUCCESS);
3831: }

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

3836:   Logically Collective

3838:   Input Parameters:
3839: + snes  - the `SNES` context
3840: - force - `PETSC_TRUE` require at least one iteration

3842:   Options Database Key:
3843: . -snes_force_iteration force - Sets forcing an iteration

3845:   Level: intermediate

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

3850: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3851: @*/
3852: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3853: {
3854:   PetscFunctionBegin;
3856:   snes->forceiteration = force;
3857:   PetscFunctionReturn(PETSC_SUCCESS);
3858: }

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

3863:   Logically Collective

3865:   Input Parameter:
3866: . snes - the `SNES` context

3868:   Output Parameter:
3869: . force - `PETSC_TRUE` requires at least one iteration.

3871:   Level: intermediate

3873: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3874: @*/
3875: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3876: {
3877:   PetscFunctionBegin;
3879:   *force = snes->forceiteration;
3880:   PetscFunctionReturn(PETSC_SUCCESS);
3881: }

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

3886:   Logically Collective

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

3896:   Options Database Keys:
3897: + -snes_atol abstol    - Sets `abstol`
3898: . -snes_rtol rtol      - Sets `rtol`
3899: . -snes_stol stol      - Sets `stol`
3900: . -snes_max_it maxit   - Sets `maxit`
3901: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)

3903:   Level: intermediate

3905:   Note:
3906:   All parameters must be non-negative

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

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

3913:   Fortran Note:
3914:   Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`

3916: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
3917: @*/
3918: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
3919: {
3920:   PetscFunctionBegin;

3928:   if (abstol == (PetscReal)PETSC_DETERMINE) {
3929:     snes->abstol = snes->default_abstol;
3930:   } else if (abstol != (PetscReal)PETSC_CURRENT) {
3931:     PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
3932:     snes->abstol = abstol;
3933:   }

3935:   if (rtol == (PetscReal)PETSC_DETERMINE) {
3936:     snes->rtol = snes->default_rtol;
3937:   } else if (rtol != (PetscReal)PETSC_CURRENT) {
3938:     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);
3939:     snes->rtol = rtol;
3940:   }

3942:   if (stol == (PetscReal)PETSC_DETERMINE) {
3943:     snes->stol = snes->default_stol;
3944:   } else if (stol != (PetscReal)PETSC_CURRENT) {
3945:     PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
3946:     snes->stol = stol;
3947:   }

3949:   if (maxit == PETSC_DETERMINE) {
3950:     snes->max_its = snes->default_max_its;
3951:   } else if (maxit == PETSC_UNLIMITED) {
3952:     snes->max_its = PETSC_INT_MAX;
3953:   } else if (maxit != PETSC_CURRENT) {
3954:     PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
3955:     snes->max_its = maxit;
3956:   }

3958:   if (maxf == PETSC_DETERMINE) {
3959:     snes->max_funcs = snes->default_max_funcs;
3960:   } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
3961:     snes->max_funcs = PETSC_UNLIMITED;
3962:   } else if (maxf != PETSC_CURRENT) {
3963:     PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
3964:     snes->max_funcs = maxf;
3965:   }
3966:   PetscFunctionReturn(PETSC_SUCCESS);
3967: }

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

3972:   Logically Collective

3974:   Input Parameters:
3975: + snes   - the `SNES` context
3976: - 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
3977:            is stopped due to divergence.

3979:   Options Database Key:
3980: . -snes_divergence_tolerance divtol - Sets `divtol`

3982:   Level: intermediate

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

3987:   Fortran Note:
3988:   Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`

3990: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
3991: @*/
3992: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
3993: {
3994:   PetscFunctionBegin;

3998:   if (divtol == (PetscReal)PETSC_DETERMINE) {
3999:     snes->divtol = snes->default_divtol;
4000:   } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
4001:     snes->divtol = PETSC_UNLIMITED;
4002:   } else if (divtol != (PetscReal)PETSC_CURRENT) {
4003:     PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
4004:     snes->divtol = divtol;
4005:   }
4006:   PetscFunctionReturn(PETSC_SUCCESS);
4007: }

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

4012:   Not Collective

4014:   Input Parameter:
4015: . snes - the `SNES` context

4017:   Output Parameters:
4018: + atol  - the absolute convergence tolerance
4019: . rtol  - the relative convergence tolerance
4020: . stol  - convergence tolerance in terms of the norm of the change in the solution between steps
4021: . maxit - the maximum number of iterations allowed
4022: - maxf  - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound

4024:   Level: intermediate

4026:   Notes:
4027:   See `SNESSetTolerances()` for details on the parameters.

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

4031: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4032: @*/
4033: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4034: {
4035:   PetscFunctionBegin;
4037:   if (atol) *atol = snes->abstol;
4038:   if (rtol) *rtol = snes->rtol;
4039:   if (stol) *stol = snes->stol;
4040:   if (maxit) *maxit = snes->max_its;
4041:   if (maxf) *maxf = snes->max_funcs;
4042:   PetscFunctionReturn(PETSC_SUCCESS);
4043: }

4045: /*@
4046:   SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

4048:   Not Collective

4050:   Input Parameters:
4051: + snes   - the `SNES` context
4052: - divtol - divergence tolerance

4054:   Level: intermediate

4056: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4057: @*/
4058: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4059: {
4060:   PetscFunctionBegin;
4062:   if (divtol) *divtol = snes->divtol;
4063:   PetscFunctionReturn(PETSC_SUCCESS);
4064: }

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

4068: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4069: {
4070:   PetscDrawLG      lg;
4071:   PetscReal        x, y, per;
4072:   PetscViewer      v = (PetscViewer)monctx;
4073:   static PetscReal prev; /* should be in the context */
4074:   PetscDraw        draw;

4076:   PetscFunctionBegin;
4078:   PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4079:   if (!n) PetscCall(PetscDrawLGReset(lg));
4080:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4081:   PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4082:   x = (PetscReal)n;
4083:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4084:   else y = -15.0;
4085:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4086:   if (n < 20 || !(n % 5) || snes->reason) {
4087:     PetscCall(PetscDrawLGDraw(lg));
4088:     PetscCall(PetscDrawLGSave(lg));
4089:   }

4091:   PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4092:   if (!n) PetscCall(PetscDrawLGReset(lg));
4093:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4094:   PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4095:   PetscCall(SNESMonitorRange_Private(snes, n, &per));
4096:   x = (PetscReal)n;
4097:   y = 100.0 * per;
4098:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4099:   if (n < 20 || !(n % 5) || snes->reason) {
4100:     PetscCall(PetscDrawLGDraw(lg));
4101:     PetscCall(PetscDrawLGSave(lg));
4102:   }

4104:   PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4105:   if (!n) {
4106:     prev = rnorm;
4107:     PetscCall(PetscDrawLGReset(lg));
4108:   }
4109:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4110:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4111:   x = (PetscReal)n;
4112:   y = (prev - rnorm) / prev;
4113:   PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4114:   if (n < 20 || !(n % 5) || snes->reason) {
4115:     PetscCall(PetscDrawLGDraw(lg));
4116:     PetscCall(PetscDrawLGSave(lg));
4117:   }

4119:   PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4120:   if (!n) PetscCall(PetscDrawLGReset(lg));
4121:   PetscCall(PetscDrawLGGetDraw(lg, &draw));
4122:   PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4123:   x = (PetscReal)n;
4124:   y = (prev - rnorm) / (prev * per);
4125:   if (n > 2) { /*skip initial crazy value */
4126:     PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4127:   }
4128:   if (n < 20 || !(n % 5) || snes->reason) {
4129:     PetscCall(PetscDrawLGDraw(lg));
4130:     PetscCall(PetscDrawLGSave(lg));
4131:   }
4132:   prev = rnorm;
4133:   PetscFunctionReturn(PETSC_SUCCESS);
4134: }

4136: /*@
4137:   SNESConverged - Run the convergence test and update the `SNESConvergedReason`.

4139:   Collective

4141:   Input Parameters:
4142: + snes  - the `SNES` context
4143: . it    - current iteration
4144: . xnorm - 2-norm of current iterate
4145: . snorm - 2-norm of current step
4146: - fnorm - 2-norm of function

4148:   Level: developer

4150:   Note:
4151:   This routine is called by the `SNESSolve()` implementations.
4152:   It does not typically need to be called by the user.

4154: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4155: @*/
4156: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4157: {
4158:   PetscFunctionBegin;
4159:   if (!snes->reason) {
4160:     if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4161:     if (it == snes->max_its && !snes->reason) {
4162:       if (snes->normschedule == SNES_NORM_ALWAYS) {
4163:         PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4164:         snes->reason = SNES_DIVERGED_MAX_IT;
4165:       } else snes->reason = SNES_CONVERGED_ITS;
4166:     }
4167:   }
4168:   PetscFunctionReturn(PETSC_SUCCESS);
4169: }

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

4174:   Collective

4176:   Input Parameters:
4177: + snes  - nonlinear solver context obtained from `SNESCreate()`
4178: . iter  - current iteration number
4179: - rnorm - current relative norm of the residual

4181:   Level: developer

4183:   Note:
4184:   This routine is called by the `SNESSolve()` implementations.
4185:   It does not typically need to be called by the user.

4187: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4188: @*/
4189: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4190: {
4191:   PetscInt i, n = snes->numbermonitors;

4193:   PetscFunctionBegin;
4194:   PetscCall(VecLockReadPush(snes->vec_sol));
4195:   for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4196:   PetscCall(VecLockReadPop(snes->vec_sol));
4197:   PetscFunctionReturn(PETSC_SUCCESS);
4198: }

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

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

4205:      Synopsis:
4206: #include <petscsnes.h>
4207:     PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)

4209:      Collective

4211:     Input Parameters:
4212: +    snes - the `SNES` context
4213: .    its - iteration number
4214: .    norm - 2-norm function value (may be estimated)
4215: -    mctx - [optional] monitoring context

4217:    Level: advanced

4219: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4220: M*/

4222: /*@C
4223:   SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4224:   iteration of the `SNES` nonlinear solver to display the iteration's
4225:   progress.

4227:   Logically Collective

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

4235:   Calling sequence of f:
4236: + snes  - the `SNES` object
4237: . it    - the current iteration
4238: . rnorm - norm of the residual
4239: - mctx  - the optional monitor context

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

4247:   Level: intermediate

4249:   Note:
4250:   Several different monitoring routines may be set by calling
4251:   `SNESMonitorSet()` multiple times; all will be called in the
4252:   order in which they were set.

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

4257: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4258: @*/
4259: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4260: {
4261:   PetscFunctionBegin;
4263:   for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4264:     PetscBool identical;

4266:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4267:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4268:   }
4269:   PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4270:   snes->monitor[snes->numbermonitors]          = f;
4271:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4272:   snes->monitorcontext[snes->numbermonitors++] = mctx;
4273:   PetscFunctionReturn(PETSC_SUCCESS);
4274: }

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

4279:   Logically Collective

4281:   Input Parameter:
4282: . snes - the `SNES` context

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

4289:   Level: intermediate

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

4294: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4295: @*/
4296: PetscErrorCode SNESMonitorCancel(SNES snes)
4297: {
4298:   PetscInt i;

4300:   PetscFunctionBegin;
4302:   for (i = 0; i < snes->numbermonitors; i++) {
4303:     if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4304:   }
4305:   snes->numbermonitors = 0;
4306:   PetscFunctionReturn(PETSC_SUCCESS);
4307: }

4309: /*@C
4310:   SNESSetConvergenceTest - Sets the function that is to be used
4311:   to test for convergence of the nonlinear iterative solution.

4313:   Logically Collective

4315:   Input Parameters:
4316: + snes    - the `SNES` context
4317: . func    - routine to test for convergence
4318: . ctx     - [optional] context for private data for the convergence routine  (may be `NULL`)
4319: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)

4321:   Calling sequence of func:
4322: + snes   - the `SNES` context
4323: . it     - the current iteration number
4324: . xnorm  - the norm of the new solution
4325: . snorm  - the norm of the step
4326: . fnorm  - the norm of the function value
4327: . reason - output, the reason convergence or divergence as declared
4328: - ctx    - the optional convergence test context

4330:   Level: advanced

4332: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4333: @*/
4334: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4335: {
4336:   PetscFunctionBegin;
4338:   if (!func) func = SNESConvergedSkip;
4339:   if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4340:   snes->ops->converged        = func;
4341:   snes->ops->convergeddestroy = destroy;
4342:   snes->cnvP                  = ctx;
4343:   PetscFunctionReturn(PETSC_SUCCESS);
4344: }

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

4349:   Not Collective

4351:   Input Parameter:
4352: . snes - the `SNES` context

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

4357:   Options Database Key:
4358: . -snes_converged_reason - prints the reason to standard out

4360:   Level: intermediate

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

4365: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4366: @*/
4367: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4368: {
4369:   PetscFunctionBegin;
4371:   PetscAssertPointer(reason, 2);
4372:   *reason = snes->reason;
4373:   PetscFunctionReturn(PETSC_SUCCESS);
4374: }

4376: /*@C
4377:   SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`

4379:   Not Collective

4381:   Input Parameter:
4382: . snes - the `SNES` context

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

4387:   Level: beginner

4389: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4390: @*/
4391: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char **strreason)
4392: {
4393:   PetscFunctionBegin;
4395:   PetscAssertPointer(strreason, 2);
4396:   *strreason = SNESConvergedReasons[snes->reason];
4397:   PetscFunctionReturn(PETSC_SUCCESS);
4398: }

4400: /*@
4401:   SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.

4403:   Not Collective

4405:   Input Parameters:
4406: + snes   - the `SNES` context
4407: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4408:             manual pages for the individual convergence tests for complete lists

4410:   Level: developer

4412:   Developer Note:
4413:   Called inside the various `SNESSolve()` implementations

4415: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4416: @*/
4417: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4418: {
4419:   PetscFunctionBegin;
4421:   PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4422:   snes->reason = reason;
4423:   PetscFunctionReturn(PETSC_SUCCESS);
4424: }

4426: /*@
4427:   SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.

4429:   Logically Collective

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

4439:   Level: intermediate

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

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

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

4451: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4452: @*/
4453: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4454: {
4455:   PetscFunctionBegin;
4457:   if (a) PetscAssertPointer(a, 2);
4458:   if (its) PetscAssertPointer(its, 3);
4459:   if (!a) {
4460:     if (na == PETSC_DECIDE) na = 1000;
4461:     PetscCall(PetscCalloc2(na, &a, na, &its));
4462:     snes->conv_hist_alloc = PETSC_TRUE;
4463:   }
4464:   snes->conv_hist       = a;
4465:   snes->conv_hist_its   = its;
4466:   snes->conv_hist_max   = (size_t)na;
4467:   snes->conv_hist_len   = 0;
4468:   snes->conv_hist_reset = reset;
4469:   PetscFunctionReturn(PETSC_SUCCESS);
4470: }

4472: #if defined(PETSC_HAVE_MATLAB)
4473:   #include <engine.h> /* MATLAB include file */
4474:   #include <mex.h>    /* MATLAB include file */

4476: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4477: {
4478:   mxArray   *mat;
4479:   PetscInt   i;
4480:   PetscReal *ar;

4482:   mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4483:   ar  = (PetscReal *)mxGetData(mat);
4484:   for (i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4485:   return mat;
4486: }
4487: #endif

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

4492:   Not Collective

4494:   Input Parameter:
4495: . snes - iterative context obtained from `SNESCreate()`

4497:   Output Parameters:
4498: + a   - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4499: . its - integer array holds the number of linear iterations (or
4500:          negative if not converged) for each solve.
4501: - na  - size of `a` and `its`

4503:   Level: intermediate

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

4510:   Fortran Notes:
4511:   Return the arrays with ``SNESRestoreConvergenceHistory()`

4513:   Use the arguments
4514: .vb
4515:   PetscReal, pointer :: a(:)
4516:   PetscInt, pointer :: its(:)
4517: .ve

4519: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4520: @*/
4521: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4522: {
4523:   PetscFunctionBegin;
4525:   if (a) *a = snes->conv_hist;
4526:   if (its) *its = snes->conv_hist_its;
4527:   if (na) *na = (PetscInt)snes->conv_hist_len;
4528:   PetscFunctionReturn(PETSC_SUCCESS);
4529: }

4531: /*@C
4532:   SNESSetUpdate - Sets the general-purpose update function called
4533:   at the beginning of every iteration of the nonlinear solve. Specifically
4534:   it is called just before the Jacobian is "evaluated" and after the function
4535:   evaluation.

4537:   Logically Collective

4539:   Input Parameters:
4540: + snes - The nonlinear solver context
4541: - func - The update function; for calling sequence see `SNESUpdateFn`

4543:   Level: advanced

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

4551:   Users are free to modify the current residual vector,
4552:   the current linearization point, or any other vector associated to the specific solver used.
4553:   If such modifications take place, it is the user responsibility to update all the relevant
4554:   vectors. For example, if one is adjusting the model parameters at each Newton step their code may look like
4555: .vb
4556:   PetscErrorCode update(SNES snes, PetscInt iteration)
4557:   {
4558:     PetscFunctionBeginUser;
4559:     if (iteration > 0) {
4560:       // update the model parameters here
4561:       Vec x,f;
4562:       PetscCall(SNESGetSolution(snes,&x));
4563:       PetcCall(SNESGetFunction(snes,&f,NULL,NULL));
4564:       PetscCall(SNESComputeFunction(snes,x,f));
4565:     }
4566:     PetscFunctionReturn(PETSC_SUCCESS);
4567:   }
4568: .ve

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

4572: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4573:          `SNESMonitorSet()`
4574: @*/
4575: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4576: {
4577:   PetscFunctionBegin;
4579:   snes->ops->update = func;
4580:   PetscFunctionReturn(PETSC_SUCCESS);
4581: }

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

4586:   Collective

4588:   Input Parameters:
4589: + snes   - iterative context obtained from `SNESCreate()`
4590: - viewer - the viewer to display the reason

4592:   Options Database Keys:
4593: + -snes_converged_reason          - print reason for converged or diverged, also prints number of iterations
4594: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged

4596:   Level: beginner

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

4602: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4603:           `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4604:           `SNESConvergedReasonViewFromOptions()`,
4605:           `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4606: @*/
4607: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4608: {
4609:   PetscViewerFormat format;
4610:   PetscBool         isAscii;

4612:   PetscFunctionBegin;
4613:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4614:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4615:   if (isAscii) {
4616:     PetscCall(PetscViewerGetFormat(viewer, &format));
4617:     PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4618:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4619:       DM       dm;
4620:       Vec      u;
4621:       PetscDS  prob;
4622:       PetscInt Nf, f;
4623:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4624:       void    **exactCtx;
4625:       PetscReal error;

4627:       PetscCall(SNESGetDM(snes, &dm));
4628:       PetscCall(SNESGetSolution(snes, &u));
4629:       PetscCall(DMGetDS(dm, &prob));
4630:       PetscCall(PetscDSGetNumFields(prob, &Nf));
4631:       PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4632:       for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4633:       PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4634:       PetscCall(PetscFree2(exactSol, exactCtx));
4635:       if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4636:       else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4637:     }
4638:     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4639:       if (((PetscObject)snes)->prefix) {
4640:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4641:       } else {
4642:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4643:       }
4644:     } else if (snes->reason <= 0) {
4645:       if (((PetscObject)snes)->prefix) {
4646:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4647:       } else {
4648:         PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4649:       }
4650:     }
4651:     PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)snes)->tablevel + 1));
4652:   }
4653:   PetscFunctionReturn(PETSC_SUCCESS);
4654: }

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

4660:   Logically Collective

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

4668:   Calling sequence of `f`:
4669: + snes - the `SNES` context
4670: - vctx - [optional] context for private data for the function

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

4677:   Level: intermediate

4679:   Note:
4680:   Several different converged reason view routines may be set by calling
4681:   `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4682:   order in which they were set.

4684: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4685:           `PetscCtxDestroyFn`
4686: @*/
4687: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4688: {
4689:   PetscFunctionBegin;
4691:   for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4692:     PetscBool identical;

4694:     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4695:     if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4696:   }
4697:   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4698:   snes->reasonview[snes->numberreasonviews]          = f;
4699:   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4700:   snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4701:   PetscFunctionReturn(PETSC_SUCCESS);
4702: }

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

4708:   Collective

4710:   Input Parameter:
4711: . snes - the `SNES` object

4713:   Level: advanced

4715: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4716:           `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4717: @*/
4718: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4719: {
4720:   static PetscBool incall = PETSC_FALSE;

4722:   PetscFunctionBegin;
4723:   if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4724:   incall = PETSC_TRUE;

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

4729:   /* Call PETSc default routine if users ask for it */
4730:   if (snes->convergedreasonviewer) {
4731:     PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4732:     PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4733:     PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4734:   }
4735:   incall = PETSC_FALSE;
4736:   PetscFunctionReturn(PETSC_SUCCESS);
4737: }

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

4742:   Collective

4744:   Input Parameters:
4745: + snes - the `SNES` context
4746: . b    - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4747: - x    - the solution vector.

4749:   Level: beginner

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

4755: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4756:           `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4757:           `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4758: @*/
4759: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4760: {
4761:   PetscBool flg;
4762:   PetscInt  grid;
4763:   Vec       xcreated = NULL;
4764:   DM        dm;

4766:   PetscFunctionBegin;
4769:   if (x) PetscCheckSameComm(snes, 1, x, 3);
4771:   if (b) PetscCheckSameComm(snes, 1, b, 2);

4773:   /* High level operations using the nonlinear solver */
4774:   {
4775:     PetscViewer       viewer;
4776:     PetscViewerFormat format;
4777:     PetscInt          num;
4778:     PetscBool         flg;
4779:     static PetscBool  incall = PETSC_FALSE;

4781:     if (!incall) {
4782:       /* Estimate the convergence rate of the discretization */
4783:       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4784:       if (flg) {
4785:         PetscConvEst conv;
4786:         DM           dm;
4787:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4788:         PetscInt     Nf;

4790:         incall = PETSC_TRUE;
4791:         PetscCall(SNESGetDM(snes, &dm));
4792:         PetscCall(DMGetNumFields(dm, &Nf));
4793:         PetscCall(PetscCalloc1(Nf, &alpha));
4794:         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4795:         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4796:         PetscCall(PetscConvEstSetFromOptions(conv));
4797:         PetscCall(PetscConvEstSetUp(conv));
4798:         PetscCall(PetscConvEstGetConvRate(conv, alpha));
4799:         PetscCall(PetscViewerPushFormat(viewer, format));
4800:         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4801:         PetscCall(PetscViewerPopFormat(viewer));
4802:         PetscCall(PetscViewerDestroy(&viewer));
4803:         PetscCall(PetscConvEstDestroy(&conv));
4804:         PetscCall(PetscFree(alpha));
4805:         incall = PETSC_FALSE;
4806:       }
4807:       /* Adaptively refine the initial grid */
4808:       num = 1;
4809:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4810:       if (flg) {
4811:         DMAdaptor adaptor;

4813:         incall = PETSC_TRUE;
4814:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4815:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4816:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4817:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4818:         PetscCall(DMAdaptorSetUp(adaptor));
4819:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4820:         PetscCall(DMAdaptorDestroy(&adaptor));
4821:         incall = PETSC_FALSE;
4822:       }
4823:       /* Use grid sequencing to adapt */
4824:       num = 0;
4825:       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4826:       if (num) {
4827:         DMAdaptor   adaptor;
4828:         const char *prefix;

4830:         incall = PETSC_TRUE;
4831:         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4832:         PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4833:         PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4834:         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4835:         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4836:         PetscCall(DMAdaptorSetFromOptions(adaptor));
4837:         PetscCall(DMAdaptorSetUp(adaptor));
4838:         PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4839:         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4840:         PetscCall(DMAdaptorDestroy(&adaptor));
4841:         incall = PETSC_FALSE;
4842:       }
4843:     }
4844:   }
4845:   if (!x) x = snes->vec_sol;
4846:   if (!x) {
4847:     PetscCall(SNESGetDM(snes, &dm));
4848:     PetscCall(DMCreateGlobalVector(dm, &xcreated));
4849:     x = xcreated;
4850:   }
4851:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));

4853:   for (grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4854:   for (grid = 0; grid < snes->gridsequence + 1; grid++) {
4855:     /* set solution vector */
4856:     if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4857:     PetscCall(VecDestroy(&snes->vec_sol));
4858:     snes->vec_sol = x;
4859:     PetscCall(SNESGetDM(snes, &dm));

4861:     /* set affine vector if provided */
4862:     if (b) PetscCall(PetscObjectReference((PetscObject)b));
4863:     PetscCall(VecDestroy(&snes->vec_rhs));
4864:     snes->vec_rhs = b;

4866:     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");
4867:     PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
4868:     PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
4869:     if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
4870:     PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
4871:     PetscCall(SNESSetUp(snes));

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

4877:     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4878:     PetscCall(SNESResetCounters(snes));
4879:     snes->reason = SNES_CONVERGED_ITERATING;
4880:     PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
4881:     PetscUseTypeMethod(snes, solve);
4882:     PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
4883:     PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
4884:     snes->functiondomainerror  = PETSC_FALSE; /* clear the flag if it has been set */
4885:     snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4886:     snes->jacobiandomainerror  = PETSC_FALSE; /* clear the flag if it has been set */

4888:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4889:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4896:     if (snes->errorifnotconverged) {
4897:       if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
4898:       PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
4899:     }
4900:     if (snes->reason < 0) break;
4901:     if (grid < snes->gridsequence) {
4902:       DM  fine;
4903:       Vec xnew;
4904:       Mat interp;

4906:       PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
4907:       PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
4908:       PetscCall(DMGetCoordinatesLocalSetUp(fine));
4909:       PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
4910:       PetscCall(DMCreateGlobalVector(fine, &xnew));
4911:       PetscCall(MatInterpolate(interp, x, xnew));
4912:       PetscCall(DMInterpolate(snes->dm, interp, fine));
4913:       PetscCall(MatDestroy(&interp));
4914:       x = xnew;

4916:       PetscCall(SNESReset(snes));
4917:       PetscCall(SNESSetDM(snes, fine));
4918:       PetscCall(SNESResetFromOptions(snes));
4919:       PetscCall(DMDestroy(&fine));
4920:       PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4921:     }
4922:   }
4923:   PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
4924:   PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
4925:   PetscCall(DMMonitor(snes->dm));
4926:   PetscCall(SNESMonitorPauseFinal_Internal(snes));

4928:   PetscCall(VecDestroy(&xcreated));
4929:   PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
4930:   PetscFunctionReturn(PETSC_SUCCESS);
4931: }

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

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

4938:   Collective

4940:   Input Parameters:
4941: + snes - the `SNES` context
4942: - type - a known method

4944:   Options Database Key:
4945: . -snes_type type - Sets the method; see `SNESType`

4947:   Level: intermediate

4949:   Notes:
4950:   See `SNESType` for available methods (for instance)
4951: +    `SNESNEWTONLS` - Newton's method with line search
4952:   (systems of nonlinear equations)
4953: -    `SNESNEWTONTR` - Newton's method with trust region
4954:   (systems of nonlinear equations)

4956:   Normally, it is best to use the `SNESSetFromOptions()` command and then
4957:   set the `SNES` solver type from the options database rather than by using
4958:   this routine.  Using the options database provides the user with
4959:   maximum flexibility in evaluating the many nonlinear solvers.
4960:   The `SNESSetType()` routine is provided for those situations where it
4961:   is necessary to set the nonlinear solver independently of the command
4962:   line or options database.  This might be the case, for example, when
4963:   the choice of solver changes during the execution of the program,
4964:   and the user's application is taking responsibility for choosing the
4965:   appropriate method.

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

4971: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
4972: @*/
4973: PetscErrorCode SNESSetType(SNES snes, SNESType type)
4974: {
4975:   PetscBool match;
4976:   PetscErrorCode (*r)(SNES);

4978:   PetscFunctionBegin;
4980:   PetscAssertPointer(type, 2);

4982:   PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
4983:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

4985:   PetscCall(PetscFunctionListFind(SNESList, type, &r));
4986:   PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
4987:   /* Destroy the previous private SNES context */
4988:   PetscTryTypeMethod(snes, destroy);
4989:   /* Reinitialize type-specific function pointers in SNESOps structure */
4990:   snes->ops->reset          = NULL;
4991:   snes->ops->setup          = NULL;
4992:   snes->ops->solve          = NULL;
4993:   snes->ops->view           = NULL;
4994:   snes->ops->setfromoptions = NULL;
4995:   snes->ops->destroy        = NULL;

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

5000:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
5001:   snes->setupcalled = PETSC_FALSE;

5003:   PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
5004:   PetscCall((*r)(snes));
5005:   PetscFunctionReturn(PETSC_SUCCESS);
5006: }

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

5011:   Not Collective

5013:   Input Parameter:
5014: . snes - nonlinear solver context

5016:   Output Parameter:
5017: . type - `SNES` method (a character string)

5019:   Level: intermediate

5021: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`
5022: @*/
5023: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5024: {
5025:   PetscFunctionBegin;
5027:   PetscAssertPointer(type, 2);
5028:   *type = ((PetscObject)snes)->type_name;
5029:   PetscFunctionReturn(PETSC_SUCCESS);
5030: }

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

5035:   Logically Collective

5037:   Input Parameters:
5038: + snes - the `SNES` context obtained from `SNESCreate()`
5039: - u    - the solution vector

5041:   Level: beginner

5043: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5044: @*/
5045: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5046: {
5047:   DM dm;

5049:   PetscFunctionBegin;
5052:   PetscCall(PetscObjectReference((PetscObject)u));
5053:   PetscCall(VecDestroy(&snes->vec_sol));

5055:   snes->vec_sol = u;

5057:   PetscCall(SNESGetDM(snes, &dm));
5058:   PetscCall(DMShellSetGlobalVector(dm, u));
5059:   PetscFunctionReturn(PETSC_SUCCESS);
5060: }

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

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

5068:   Input Parameter:
5069: . snes - the `SNES` context

5071:   Output Parameter:
5072: . x - the solution

5074:   Level: intermediate

5076: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5077: @*/
5078: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5079: {
5080:   PetscFunctionBegin;
5082:   PetscAssertPointer(x, 2);
5083:   *x = snes->vec_sol;
5084:   PetscFunctionReturn(PETSC_SUCCESS);
5085: }

5087: /*@
5088:   SNESGetSolutionUpdate - Returns the vector where the solution update is
5089:   stored.

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

5093:   Input Parameter:
5094: . snes - the `SNES` context

5096:   Output Parameter:
5097: . x - the solution update

5099:   Level: advanced

5101: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5102: @*/
5103: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5104: {
5105:   PetscFunctionBegin;
5107:   PetscAssertPointer(x, 2);
5108:   *x = snes->vec_sol_update;
5109:   PetscFunctionReturn(PETSC_SUCCESS);
5110: }

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

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

5117:   Input Parameter:
5118: . snes - the `SNES` context

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

5125:   Level: advanced

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

5130: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5131: @*/
5132: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5133: {
5134:   DM dm;

5136:   PetscFunctionBegin;
5138:   if (r) {
5139:     if (!snes->vec_func) {
5140:       if (snes->vec_rhs) {
5141:         PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5142:       } else if (snes->vec_sol) {
5143:         PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5144:       } else if (snes->dm) {
5145:         PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5146:       }
5147:     }
5148:     *r = snes->vec_func;
5149:   }
5150:   PetscCall(SNESGetDM(snes, &dm));
5151:   PetscCall(DMSNESGetFunction(dm, f, ctx));
5152:   PetscFunctionReturn(PETSC_SUCCESS);
5153: }

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

5158:   Input Parameter:
5159: . snes - the `SNES` context

5161:   Output Parameters:
5162: + f   - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5163: - ctx - the function context (or `NULL`)

5165:   Level: advanced

5167: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5168: @*/
5169: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5170: {
5171:   DM dm;

5173:   PetscFunctionBegin;
5175:   PetscCall(SNESGetDM(snes, &dm));
5176:   PetscCall(DMSNESGetNGS(dm, f, ctx));
5177:   PetscFunctionReturn(PETSC_SUCCESS);
5178: }

5180: /*@
5181:   SNESSetOptionsPrefix - Sets the prefix used for searching for all
5182:   `SNES` options in the database.

5184:   Logically Collective

5186:   Input Parameters:
5187: + snes   - the `SNES` context
5188: - prefix - the prefix to prepend to all option names

5190:   Level: advanced

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

5196: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5197: @*/
5198: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5199: {
5200:   PetscFunctionBegin;
5202:   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5203:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5204:   if (snes->linesearch) {
5205:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5206:     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5207:   }
5208:   PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5209:   PetscFunctionReturn(PETSC_SUCCESS);
5210: }

5212: /*@
5213:   SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5214:   `SNES` options in the database.

5216:   Logically Collective

5218:   Input Parameters:
5219: + snes   - the `SNES` context
5220: - prefix - the prefix to prepend to all option names

5222:   Level: advanced

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

5228: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5229: @*/
5230: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5231: {
5232:   PetscFunctionBegin;
5234:   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5235:   if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5236:   if (snes->linesearch) {
5237:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5238:     PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5239:   }
5240:   PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5241:   PetscFunctionReturn(PETSC_SUCCESS);
5242: }

5244: /*@
5245:   SNESGetOptionsPrefix - Gets the prefix used for searching for all
5246:   `SNES` options in the database.

5248:   Not Collective

5250:   Input Parameter:
5251: . snes - the `SNES` context

5253:   Output Parameter:
5254: . prefix - pointer to the prefix string used

5256:   Level: advanced

5258: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5259: @*/
5260: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5261: {
5262:   PetscFunctionBegin;
5264:   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5265:   PetscFunctionReturn(PETSC_SUCCESS);
5266: }

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

5271:   Not Collective

5273:   Input Parameters:
5274: + sname    - name of a new user-defined solver
5275: - function - routine to create method context

5277:   Level: advanced

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

5282:   Example Usage:
5283: .vb
5284:    SNESRegister("my_solver", MySolverCreate);
5285: .ve

5287:   Then, your solver can be chosen with the procedural interface via
5288: .vb
5289:   SNESSetType(snes, "my_solver")
5290: .ve
5291:   or at runtime via the option
5292: .vb
5293:   -snes_type my_solver
5294: .ve

5296: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5297: @*/
5298: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5299: {
5300:   PetscFunctionBegin;
5301:   PetscCall(SNESInitializePackage());
5302:   PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5303:   PetscFunctionReturn(PETSC_SUCCESS);
5304: }

5306: PetscErrorCode SNESTestLocalMin(SNES snes)
5307: {
5308:   PetscInt    N, i, j;
5309:   Vec         u, uh, fh;
5310:   PetscScalar value;
5311:   PetscReal   norm;

5313:   PetscFunctionBegin;
5314:   PetscCall(SNESGetSolution(snes, &u));
5315:   PetscCall(VecDuplicate(u, &uh));
5316:   PetscCall(VecDuplicate(u, &fh));

5318:   /* currently only works for sequential */
5319:   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5320:   PetscCall(VecGetSize(u, &N));
5321:   for (i = 0; i < N; i++) {
5322:     PetscCall(VecCopy(u, uh));
5323:     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5324:     for (j = -10; j < 11; j++) {
5325:       value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5326:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5327:       PetscCall(SNESComputeFunction(snes, uh, fh));
5328:       PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5329:       PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "       j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5330:       value = -value;
5331:       PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5332:     }
5333:   }
5334:   PetscCall(VecDestroy(&uh));
5335:   PetscCall(VecDestroy(&fh));
5336:   PetscFunctionReturn(PETSC_SUCCESS);
5337: }

5339: /*@
5340:   SNESGetLineSearch - Returns the line search associated with the `SNES`.

5342:   Not Collective

5344:   Input Parameter:
5345: . snes - iterative context obtained from `SNESCreate()`

5347:   Output Parameter:
5348: . linesearch - linesearch context

5350:   Level: beginner

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

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

5357: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5358: @*/
5359: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5360: {
5361:   const char *optionsprefix;

5363:   PetscFunctionBegin;
5365:   PetscAssertPointer(linesearch, 2);
5366:   if (!snes->linesearch) {
5367:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5368:     PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5369:     PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5370:     PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5371:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5372:   }
5373:   *linesearch = snes->linesearch;
5374:   PetscFunctionReturn(PETSC_SUCCESS);
5375: }

5377: /*@
5378:   SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5379:   computing relative tolerance for linear solvers within an inexact
5380:   Newton method.

5382:   Logically Collective

5384:   Input Parameters:
5385: + snes - `SNES` context
5386: - flag - `PETSC_TRUE` or `PETSC_FALSE`

5388:   Options Database Keys:
5389: + -snes_ksp_ew                     - use Eisenstat-Walker method for determining linear system convergence
5390: . -snes_ksp_ew_version ver         - version of  Eisenstat-Walker method
5391: . -snes_ksp_ew_rtol0 rtol0         - Sets rtol0
5392: . -snes_ksp_ew_rtolmax rtolmax     - Sets rtolmax
5393: . -snes_ksp_ew_gamma gamma         - Sets gamma
5394: . -snes_ksp_ew_alpha alpha         - Sets alpha
5395: . -snes_ksp_ew_alpha2 alpha2       - Sets alpha2
5396: - -snes_ksp_ew_threshold threshold - Sets threshold

5398:   Level: advanced

5400:   Note:
5401:   The default is to use a constant relative tolerance for
5402:   the inner linear solvers.  Alternatively, one can use the
5403:   Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5404:   is reset at each Newton iteration according progress of the nonlinear
5405:   solver.

5407: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5408: @*/
5409: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5410: {
5411:   PetscFunctionBegin;
5414:   snes->ksp_ewconv = flag;
5415:   PetscFunctionReturn(PETSC_SUCCESS);
5416: }

5418: /*@
5419:   SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5420:   for computing relative tolerance for linear solvers within an
5421:   inexact Newton method.

5423:   Not Collective

5425:   Input Parameter:
5426: . snes - `SNES` context

5428:   Output Parameter:
5429: . flag - `PETSC_TRUE` or `PETSC_FALSE`

5431:   Level: advanced

5433: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5434: @*/
5435: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5436: {
5437:   PetscFunctionBegin;
5439:   PetscAssertPointer(flag, 2);
5440:   *flag = snes->ksp_ewconv;
5441:   PetscFunctionReturn(PETSC_SUCCESS);
5442: }

5444: /*@
5445:   SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5446:   convergence criteria for the linear solvers within an inexact
5447:   Newton method.

5449:   Logically Collective

5451:   Input Parameters:
5452: + snes      - `SNES` context
5453: . version   - version 1, 2 (default is 2), 3 or 4
5454: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5455: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5456: . gamma     - multiplicative factor for version 2 rtol computation
5457:              (0 <= gamma2 <= 1)
5458: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5459: . alpha2    - power for safeguard
5460: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5462:   Level: advanced

5464:   Notes:
5465:   Version 3 was contributed by Luis Chacon, June 2006.

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

5469: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5470: @*/
5471: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5472: {
5473:   SNESKSPEW *kctx;

5475:   PetscFunctionBegin;
5477:   kctx = (SNESKSPEW *)snes->kspconvctx;
5478:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");

5487:   if (version != PETSC_CURRENT) kctx->version = version;
5488:   if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5489:   if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5490:   if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5491:   if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5492:   if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5493:   if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;

5495:   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);
5496:   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);
5497:   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);
5498:   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);
5499:   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);
5500:   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);
5501:   PetscFunctionReturn(PETSC_SUCCESS);
5502: }

5504: /*@
5505:   SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5506:   convergence criteria for the linear solvers within an inexact
5507:   Newton method.

5509:   Not Collective

5511:   Input Parameter:
5512: . snes - `SNES` context

5514:   Output Parameters:
5515: + version   - version 1, 2 (default is 2), 3 or 4
5516: . rtol_0    - initial relative tolerance (0 <= rtol_0 < 1)
5517: . rtol_max  - maximum relative tolerance (0 <= rtol_max < 1)
5518: . gamma     - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5519: . alpha     - power for version 2 rtol computation (1 < alpha <= 2)
5520: . alpha2    - power for safeguard
5521: - threshold - threshold for imposing safeguard (0 < threshold < 1)

5523:   Level: advanced

5525: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5526: @*/
5527: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5528: {
5529:   SNESKSPEW *kctx;

5531:   PetscFunctionBegin;
5533:   kctx = (SNESKSPEW *)snes->kspconvctx;
5534:   PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5535:   if (version) *version = kctx->version;
5536:   if (rtol_0) *rtol_0 = kctx->rtol_0;
5537:   if (rtol_max) *rtol_max = kctx->rtol_max;
5538:   if (gamma) *gamma = kctx->gamma;
5539:   if (alpha) *alpha = kctx->alpha;
5540:   if (alpha2) *alpha2 = kctx->alpha2;
5541:   if (threshold) *threshold = kctx->threshold;
5542:   PetscFunctionReturn(PETSC_SUCCESS);
5543: }

5545: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5546: {
5547:   SNES       snes = (SNES)ctx;
5548:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5549:   PetscReal  rtol = PETSC_CURRENT, stol;

5551:   PetscFunctionBegin;
5552:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5553:   if (!snes->iter) {
5554:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5555:     PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5556:   } else {
5557:     PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5558:     if (kctx->version == 1) {
5559:       rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5560:       stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5561:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5562:     } else if (kctx->version == 2) {
5563:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5564:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5565:       if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5566:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5567:       rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5568:       /* safeguard: avoid sharp decrease of rtol */
5569:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5570:       stol = PetscMax(rtol, stol);
5571:       rtol = PetscMin(kctx->rtol_0, stol);
5572:       /* safeguard: avoid oversolving */
5573:       stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5574:       stol = PetscMax(rtol, stol);
5575:       rtol = PetscMin(kctx->rtol_0, stol);
5576:     } else /* if (kctx->version == 4) */ {
5577:       /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5578:       PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5579:       PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5580:       PetscReal rk   = ared / pred;
5581:       if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5582:       else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5583:       else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5584:       else rtol = kctx->v4_m2 * kctx->rtol_last;

5586:       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;
5587:       kctx->rtol_last_2 = kctx->rtol_last;
5588:       kctx->rk_last_2   = kctx->rk_last;
5589:       kctx->rk_last     = rk;
5590:     }
5591:   }
5592:   /* safeguard: avoid rtol greater than rtol_max */
5593:   rtol = PetscMin(rtol, kctx->rtol_max);
5594:   PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5595:   PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5596:   PetscFunctionReturn(PETSC_SUCCESS);
5597: }

5599: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5600: {
5601:   SNES       snes = (SNES)ctx;
5602:   SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5603:   PCSide     pcside;
5604:   Vec        lres;

5606:   PetscFunctionBegin;
5607:   if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5608:   PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5609:   kctx->norm_last = snes->norm;
5610:   if (kctx->version == 1 || kctx->version == 4) {
5611:     PC        pc;
5612:     PetscBool getRes;

5614:     PetscCall(KSPGetPC(ksp, &pc));
5615:     PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5616:     if (!getRes) {
5617:       KSPNormType normtype;

5619:       PetscCall(KSPGetNormType(ksp, &normtype));
5620:       getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5621:     }
5622:     PetscCall(KSPGetPCSide(ksp, &pcside));
5623:     if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5624:       PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5625:     } else {
5626:       /* KSP residual is preconditioned residual */
5627:       /* compute true linear residual norm */
5628:       Mat J;
5629:       PetscCall(KSPGetOperators(ksp, &J, NULL));
5630:       PetscCall(VecDuplicate(b, &lres));
5631:       PetscCall(MatMult(J, x, lres));
5632:       PetscCall(VecAYPX(lres, -1.0, b));
5633:       PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5634:       PetscCall(VecDestroy(&lres));
5635:     }
5636:   }
5637:   PetscFunctionReturn(PETSC_SUCCESS);
5638: }

5640: /*@
5641:   SNESGetKSP - Returns the `KSP` context for a `SNES` solver.

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

5645:   Input Parameter:
5646: . snes - the `SNES` context

5648:   Output Parameter:
5649: . ksp - the `KSP` context

5651:   Level: beginner

5653:   Notes:
5654:   The user can then directly manipulate the `KSP` context to set various
5655:   options, etc.  Likewise, the user can then extract and manipulate the
5656:   `PC` contexts as well.

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

5660: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5661: @*/
5662: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5663: {
5664:   PetscFunctionBegin;
5666:   PetscAssertPointer(ksp, 2);

5668:   if (!snes->ksp) {
5669:     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5670:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));

5672:     PetscCall(KSPSetPreSolve(snes->ksp, KSPPreSolve_SNESEW, snes));
5673:     PetscCall(KSPSetPostSolve(snes->ksp, KSPPostSolve_SNESEW, snes));

5675:     PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5676:     PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5677:   }
5678:   *ksp = snes->ksp;
5679:   PetscFunctionReturn(PETSC_SUCCESS);
5680: }

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

5686:   Logically Collective

5688:   Input Parameters:
5689: + snes - the nonlinear solver context
5690: - dm   - the `DM`, cannot be `NULL`

5692:   Level: intermediate

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

5699: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5700: @*/
5701: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5702: {
5703:   KSP    ksp;
5704:   DMSNES sdm;

5706:   PetscFunctionBegin;
5709:   PetscCall(PetscObjectReference((PetscObject)dm));
5710:   if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5711:     if (snes->dm->dmsnes && !dm->dmsnes) {
5712:       PetscCall(DMCopyDMSNES(snes->dm, dm));
5713:       PetscCall(DMGetDMSNES(snes->dm, &sdm));
5714:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5715:     }
5716:     PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5717:     PetscCall(DMDestroy(&snes->dm));
5718:   }
5719:   snes->dm     = dm;
5720:   snes->dmAuto = PETSC_FALSE;

5722:   PetscCall(SNESGetKSP(snes, &ksp));
5723:   PetscCall(KSPSetDM(ksp, dm));
5724:   PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5725:   if (snes->npc) {
5726:     PetscCall(SNESSetDM(snes->npc, snes->dm));
5727:     PetscCall(SNESSetNPCSide(snes, snes->npcside));
5728:   }
5729:   PetscFunctionReturn(PETSC_SUCCESS);
5730: }

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

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

5737:   Input Parameter:
5738: . snes - the `SNES` context

5740:   Output Parameter:
5741: . dm - the `DM`

5743:   Level: intermediate

5745: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5746: @*/
5747: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5748: {
5749:   PetscFunctionBegin;
5751:   if (!snes->dm) {
5752:     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5753:     snes->dmAuto = PETSC_TRUE;
5754:   }
5755:   *dm = snes->dm;
5756:   PetscFunctionReturn(PETSC_SUCCESS);
5757: }

5759: /*@
5760:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5762:   Collective

5764:   Input Parameters:
5765: + snes - iterative context obtained from `SNESCreate()`
5766: - npc  - the `SNES` nonlinear preconditioner object

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

5771:   Level: developer

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

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

5778: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5779: @*/
5780: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5781: {
5782:   PetscFunctionBegin;
5785:   PetscCheckSameComm(snes, 1, npc, 2);
5786:   PetscCall(PetscObjectReference((PetscObject)npc));
5787:   PetscCall(SNESDestroy(&snes->npc));
5788:   snes->npc = npc;
5789:   PetscFunctionReturn(PETSC_SUCCESS);
5790: }

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

5795:   Not Collective; but any changes to the obtained the `pc` object must be applied collectively

5797:   Input Parameter:
5798: . snes - iterative context obtained from `SNESCreate()`

5800:   Output Parameter:
5801: . pc - the `SNES` preconditioner context

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

5806:   Level: advanced

5808:   Notes:
5809:   If a `SNES` was previously set with `SNESSetNPC()` then that value is returned, otherwise a new `SNES` object is created that will
5810:   be used as the nonlinear preconditioner for the current `SNES`.

5812:   The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5813:   `SNES`. These may be overwritten if needed.

5815:   Use the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration of the nonlinear preconditioner

5817: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5818: @*/
5819: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5820: {
5821:   const char *optionsprefix;

5823:   PetscFunctionBegin;
5825:   PetscAssertPointer(pc, 2);
5826:   if (!snes->npc) {
5827:     PetscCtx ctx;

5829:     PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5830:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5831:     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5832:     PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5833:     PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5834:     if (snes->ops->ctxcompute) {
5835:       PetscCall(SNESSetComputeApplicationContext(snes, snes->ops->ctxcompute, snes->ops->ctxdestroy));
5836:     } else {
5837:       PetscCall(SNESGetApplicationContext(snes, &ctx));
5838:       PetscCall(SNESSetApplicationContext(snes->npc, ctx));
5839:     }
5840:     PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5841:   }
5842:   *pc = snes->npc;
5843:   PetscFunctionReturn(PETSC_SUCCESS);
5844: }

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

5849:   Not Collective

5851:   Input Parameter:
5852: . snes - iterative context obtained from `SNESCreate()`

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

5857:   Level: developer

5859: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
5860: @*/
5861: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5862: {
5863:   PetscFunctionBegin;
5865:   PetscAssertPointer(has_npc, 2);
5866:   *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
5867:   PetscFunctionReturn(PETSC_SUCCESS);
5868: }

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

5873:   Logically Collective

5875:   Input Parameter:
5876: . snes - iterative context obtained from `SNESCreate()`

5878:   Output Parameter:
5879: . side - the preconditioning side, where side is one of
5880: .vb
5881:       PC_LEFT  - left preconditioning
5882:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5883: .ve

5885:   Options Database Key:
5886: . -snes_npc_side (right|left) - nonlinear preconditioner side

5888:   Level: intermediate

5890:   Note:
5891:   `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.

5893: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
5894: @*/
5895: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
5896: {
5897:   PetscFunctionBegin;
5900:   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
5901:   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
5902:   snes->npcside = side;
5903:   PetscFunctionReturn(PETSC_SUCCESS);
5904: }

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

5909:   Not Collective

5911:   Input Parameter:
5912: . snes - iterative context obtained from `SNESCreate()`

5914:   Output Parameter:
5915: . side - the preconditioning side, where side is one of
5916: .vb
5917:       `PC_LEFT` - left preconditioning
5918:       `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
5919: .ve

5921:   Level: intermediate

5923: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
5924: @*/
5925: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
5926: {
5927:   PetscFunctionBegin;
5929:   PetscAssertPointer(side, 2);
5930:   *side = snes->npcside;
5931:   PetscFunctionReturn(PETSC_SUCCESS);
5932: }

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

5937:   Collective

5939:   Input Parameters:
5940: + snes       - iterative context obtained from `SNESCreate()`
5941: - linesearch - the linesearch object

5943:   Level: developer

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

5949: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
5950: @*/
5951: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5952: {
5953:   PetscFunctionBegin;
5956:   PetscCheckSameComm(snes, 1, linesearch, 2);
5957:   PetscCall(PetscObjectReference((PetscObject)linesearch));
5958:   PetscCall(SNESLineSearchDestroy(&snes->linesearch));

5960:   snes->linesearch = linesearch;
5961:   PetscFunctionReturn(PETSC_SUCCESS);
5962: }