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:   Options Database Key:
    337: . -name [viewertype][:...] - option name and values. See `PetscObjectViewFromOptions()` for the possible arguments

    339:   Level: intermediate

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

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

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

    356:   Collective

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

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

    365:   Level: beginner

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

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

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

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

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

    397:   PetscFunctionBegin;
    399:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &viewer));
    401:   PetscCheckSameComm(snes, 1, viewer, 2);

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

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

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

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

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

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

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

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

    566:   Not Collective

    568:   Input Parameter:
    569: . snescheck - function that checks for options

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

    574:   Level: developer

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

    586: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
    587: {
    588:   Mat          J;
    589:   MatNullSpace nullsp;

    591:   PetscFunctionBegin;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    745:   Collective

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

    750:   Level: developer

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

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

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

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

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

    813: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);

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

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

    826:   Collective

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

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

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

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

    849:   Level: advanced

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

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

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

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

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

    905:   Collective

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

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

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

    955:   Level: beginner

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

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

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

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

    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:   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() correctly */
    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:   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) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
    3308:     else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
    3309:   }
    3310:   PetscFunctionReturn(PETSC_SUCCESS);
    3311: }

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

    3317:   Collective

    3319:   Input Parameter:
    3320: . snes - the `SNES` context

    3322:   Level: advanced

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

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

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

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

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

    3358:   PetscCall(SNESGetDM(snes, &dm));
    3359:   PetscCall(DMGetDMSNES(dm, &sdm));
    3360:   PetscCall(SNESSetDefaultComputeJacobian(snes));

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

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

    3366:   if (snes->linesearch) {
    3367:     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
    3368:     PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
    3369:   }

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

    3377:   if (snes->npc) {
    3378:     /* copy the DM over */
    3379:     PetscCall(SNESGetDM(snes, &dm));
    3380:     PetscCall(SNESSetDM(snes->npc, dm));

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

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

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

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

    3418:   snes->jac_iter = 0;
    3419:   snes->pre_iter = 0;

    3421:   PetscTryTypeMethod(snes, setup);

    3423:   PetscCall(SNESSetDefaultComputeJacobian(snes));

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

    3438: /*@
    3439:   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

    3441:   Collective

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

    3446:   Level: intermediate

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

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

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

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

    3467:   PetscTryTypeMethod(snes, reset);
    3468:   if (snes->ksp) PetscCall(KSPReset(snes->ksp));

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

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

    3482:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

    3484:   snes->nwork = snes->nvwork = 0;
    3485:   snes->setupcalled          = PETSC_FALSE;
    3486:   PetscFunctionReturn(PETSC_SUCCESS);
    3487: }

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

    3493:   Collective

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

    3498:   Level: intermediate

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

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

    3516: /*@
    3517:   SNESDestroy - Destroys the nonlinear solver context that was created
    3518:   with `SNESCreate()`.

    3520:   Collective

    3522:   Input Parameter:
    3523: . snes - the `SNES` context

    3525:   Level: beginner

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

    3533:   PetscFunctionBegin;
    3534:   if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
    3536:   if (--((PetscObject)*snes)->refct > 0) {
    3537:     *snes = NULL;
    3538:     PetscFunctionReturn(PETSC_SUCCESS);
    3539:   }

    3541:   PetscCall(SNESReset(*snes));
    3542:   PetscCall(SNESDestroy(&(*snes)->npc));

    3544:   /* if memory was published with SAWs then destroy it */
    3545:   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
    3546:   PetscTryTypeMethod(*snes, destroy);

    3548:   dm = (*snes)->dm;
    3549:   while (dm) {
    3550:     PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
    3551:     PetscCall(DMGetCoarseDM(dm, &dm));
    3552:   }

    3554:   PetscCall(DMDestroy(&(*snes)->dm));
    3555:   PetscCall(KSPDestroy(&(*snes)->ksp));
    3556:   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));

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

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

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

    3572:   Logically Collective

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

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

    3585:   Level: intermediate

    3587:   Notes:
    3588:   The default is 1

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

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

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

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

    3611:   Logically Collective

    3613:   Input Parameters:
    3614: + snes  - the `SNES` context
    3615: - steps - the number of refinements to do, defaults to 0

    3617:   Options Database Key:
    3618: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess

    3620:   Level: intermediate

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

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

    3627: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
    3628:           `SNESSetDM()`, `SNESSolve()`
    3629: @*/
    3630: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
    3631: {
    3632:   PetscFunctionBegin;
    3635:   snes->gridsequence = steps;
    3636:   PetscFunctionReturn(PETSC_SUCCESS);
    3637: }

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

    3642:   Logically Collective

    3644:   Input Parameter:
    3645: . snes - the `SNES` context

    3647:   Output Parameter:
    3648: . steps - the number of refinements to do, defaults to 0

    3650:   Level: intermediate

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

    3662: /*@
    3663:   SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt

    3665:   Not Collective

    3667:   Input Parameter:
    3668: . snes - the `SNES` context

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

    3674:   Level: intermediate

    3676:   Notes:
    3677:   The default is 1

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

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

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

    3695:   Logically Collective

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

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

    3708:   Level: intermediate

    3710:   Notes:
    3711:   The default is 1

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

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

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

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

    3734:   Not Collective

    3736:   Input Parameter:
    3737: . snes - the `SNES` context

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

    3743:   Level: intermediate

    3745:   Notes:
    3746:   The default is 1

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

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

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

    3763:   Logically collective

    3765:   Input Parameters:
    3766: + snes - the `SNES` context
    3767: - flg  - jacobian lagging persists if true

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

    3775:   Level: advanced

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

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

    3784: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
    3785: @*/
    3786: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
    3787: {
    3788:   PetscFunctionBegin;
    3791:   snes->lagjac_persist = flg;
    3792:   PetscFunctionReturn(PETSC_SUCCESS);
    3793: }

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

    3798:   Logically Collective

    3800:   Input Parameters:
    3801: + snes - the `SNES` context
    3802: - flg  - preconditioner lagging persists if true

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

    3810:   Level: developer

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

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

    3819: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
    3820: @*/
    3821: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
    3822: {
    3823:   PetscFunctionBegin;
    3826:   snes->lagpre_persist = flg;
    3827:   PetscFunctionReturn(PETSC_SUCCESS);
    3828: }

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

    3833:   Logically Collective

    3835:   Input Parameters:
    3836: + snes  - the `SNES` context
    3837: - force - `PETSC_TRUE` require at least one iteration

    3839:   Options Database Key:
    3840: . -snes_force_iteration force - Sets forcing an iteration

    3842:   Level: intermediate

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

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

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

    3860:   Logically Collective

    3862:   Input Parameter:
    3863: . snes - the `SNES` context

    3865:   Output Parameter:
    3866: . force - `PETSC_TRUE` requires at least one iteration.

    3868:   Level: intermediate

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

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

    3883:   Logically Collective

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

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

    3900:   Level: intermediate

    3902:   Note:
    3903:   All parameters must be non-negative

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

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

    3910:   Fortran Note:
    3911:   Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`

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

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

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

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

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

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

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

    3969:   Logically Collective

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

    3976:   Options Database Key:
    3977: . -snes_divergence_tolerance divtol - Sets `divtol`

    3979:   Level: intermediate

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

    3984:   Fortran Note:
    3985:   Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`

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

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

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

    4009:   Not Collective

    4011:   Input Parameter:
    4012: . snes - the `SNES` context

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

    4021:   Level: intermediate

    4023:   Notes:
    4024:   See `SNESSetTolerances()` for details on the parameters.

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

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

    4042: /*@
    4043:   SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

    4045:   Not Collective

    4047:   Input Parameters:
    4048: + snes   - the `SNES` context
    4049: - divtol - divergence tolerance

    4051:   Level: intermediate

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

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

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

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

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

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

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

    4133: /*@
    4134:   SNESConverged - Run the convergence test and update the `SNESConvergedReason`.

    4136:   Collective

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

    4145:   Level: developer

    4147:   Note:
    4148:   This routine is called by the `SNESSolve()` implementations.
    4149:   It does not typically need to be called by the user.

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

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

    4171:   Collective

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

    4178:   Level: developer

    4180:   Note:
    4181:   This routine is called by the `SNESSolve()` implementations.
    4182:   It does not typically need to be called by the user.

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

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

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

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

    4202:      Synopsis:
    4203: #include <petscsnes.h>
    4204:     PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)

    4206:      Collective

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

    4214:    Level: advanced

    4216: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
    4217: M*/

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

    4224:   Logically Collective

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

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

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

    4244:   Level: intermediate

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

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

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

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

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

    4276:   Logically Collective

    4278:   Input Parameter:
    4279: . snes - the `SNES` context

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

    4286:   Level: intermediate

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

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

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

    4306: /*@C
    4307:   SNESSetConvergenceTest - Sets the function that is to be used
    4308:   to test for convergence of the nonlinear iterative solution.

    4310:   Logically Collective

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

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

    4327:   Level: advanced

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

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

    4346:   Not Collective

    4348:   Input Parameter:
    4349: . snes - the `SNES` context

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

    4354:   Options Database Key:
    4355: . -snes_converged_reason - prints the reason to standard out

    4357:   Level: intermediate

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

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

    4373: /*@C
    4374:   SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`

    4376:   Not Collective

    4378:   Input Parameter:
    4379: . snes - the `SNES` context

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

    4384:   Level: beginner

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

    4397: /*@
    4398:   SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.

    4400:   Not Collective

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

    4407:   Level: developer

    4409:   Developer Note:
    4410:   Called inside the various `SNESSolve()` implementations

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

    4423: /*@
    4424:   SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.

    4426:   Logically Collective

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

    4436:   Level: intermediate

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

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

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

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

    4469: #if defined(PETSC_HAVE_MATLAB)
    4470:   #include <engine.h> /* MATLAB include file */
    4471:   #include <mex.h>    /* MATLAB include file */

    4473: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
    4474: {
    4475:   mxArray   *mat;
    4476:   PetscInt   i;
    4477:   PetscReal *ar;

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

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

    4489:   Not Collective

    4491:   Input Parameter:
    4492: . snes - iterative context obtained from `SNESCreate()`

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

    4500:   Level: intermediate

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

    4507:   Fortran Notes:
    4508:   Return the arrays with ``SNESRestoreConvergenceHistory()`

    4510:   Use the arguments
    4511: .vb
    4512:   PetscReal, pointer :: a(:)
    4513:   PetscInt, pointer :: its(:)
    4514: .ve

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

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

    4534:   Logically Collective

    4536:   Input Parameters:
    4537: + snes - The nonlinear solver context
    4538: - func - The update function; for calling sequence see `SNESUpdateFn`

    4540:   Level: advanced

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

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

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

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

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

    4583:   Collective

    4585:   Input Parameters:
    4586: + snes   - iterative context obtained from `SNESCreate()`
    4587: - viewer - the viewer to display the reason

    4589:   Options Database Keys:
    4590: + -snes_converged_reason          - print reason for converged or diverged, also prints number of iterations
    4591: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged

    4593:   Level: beginner

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

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

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

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

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

    4657:   Logically Collective

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

    4665:   Calling sequence of `f`:
    4666: + snes - the `SNES` context
    4667: - vctx - [optional] context for private data for the function

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

    4674:   Level: intermediate

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

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

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

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

    4705:   Collective

    4707:   Input Parameter:
    4708: . snes - the `SNES` object

    4710:   Level: advanced

    4712:   Note:
    4713:   This function has a different API and behavior than `PetscObjectViewFromOptions()`

    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:     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:   Note:
    5022:   `type` should not be retained for later use as it will be an invalid pointer if the `SNESType` of `snes` is changed.

    5024: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
    5025: @*/
    5026: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
    5027: {
    5028:   PetscFunctionBegin;
    5030:   PetscAssertPointer(type, 2);
    5031:   *type = ((PetscObject)snes)->type_name;
    5032:   PetscFunctionReturn(PETSC_SUCCESS);
    5033: }

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

    5038:   Logically Collective

    5040:   Input Parameters:
    5041: + snes - the `SNES` context obtained from `SNESCreate()`
    5042: - u    - the solution vector

    5044:   Level: beginner

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

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

    5058:   snes->vec_sol = u;

    5060:   PetscCall(SNESGetDM(snes, &dm));
    5061:   PetscCall(DMShellSetGlobalVector(dm, u));
    5062:   PetscFunctionReturn(PETSC_SUCCESS);
    5063: }

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

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

    5071:   Input Parameter:
    5072: . snes - the `SNES` context

    5074:   Output Parameter:
    5075: . x - the solution

    5077:   Level: intermediate

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

    5090: /*@
    5091:   SNESGetSolutionUpdate - Returns the vector where the solution update is
    5092:   stored.

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

    5096:   Input Parameter:
    5097: . snes - the `SNES` context

    5099:   Output Parameter:
    5100: . x - the solution update

    5102:   Level: advanced

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

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

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

    5120:   Input Parameter:
    5121: . snes - the `SNES` context

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

    5128:   Level: advanced

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

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

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

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

    5161:   Input Parameter:
    5162: . snes - the `SNES` context

    5164:   Output Parameters:
    5165: + f   - the function (or `NULL`) see `SNESNGSFn` for calling sequence
    5166: - ctx - the function context (or `NULL`)

    5168:   Level: advanced

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

    5176:   PetscFunctionBegin;
    5178:   PetscCall(SNESGetDM(snes, &dm));
    5179:   PetscCall(DMSNESGetNGS(dm, f, ctx));
    5180:   PetscFunctionReturn(PETSC_SUCCESS);
    5181: }

    5183: /*@
    5184:   SNESSetOptionsPrefix - Sets the prefix used for searching for all
    5185:   `SNES` options in the database.

    5187:   Logically Collective

    5189:   Input Parameters:
    5190: + snes   - the `SNES` context
    5191: - prefix - the prefix to prepend to all option names

    5193:   Level: advanced

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

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

    5215: /*@
    5216:   SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
    5217:   `SNES` options in the database.

    5219:   Logically Collective

    5221:   Input Parameters:
    5222: + snes   - the `SNES` context
    5223: - prefix - the prefix to prepend to all option names

    5225:   Level: advanced

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

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

    5247: /*@
    5248:   SNESGetOptionsPrefix - Gets the prefix used for searching for all
    5249:   `SNES` options in the database.

    5251:   Not Collective

    5253:   Input Parameter:
    5254: . snes - the `SNES` context

    5256:   Output Parameter:
    5257: . prefix - pointer to the prefix string used

    5259:   Level: advanced

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

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

    5274:   Not Collective

    5276:   Input Parameters:
    5277: + sname    - name of a new user-defined solver
    5278: - function - routine to create method context

    5280:   Level: advanced

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

    5285:   Example Usage:
    5286: .vb
    5287:    SNESRegister("my_solver", MySolverCreate);
    5288: .ve

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

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

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

    5316:   PetscFunctionBegin;
    5317:   PetscCall(SNESGetSolution(snes, &u));
    5318:   PetscCall(VecDuplicate(u, &uh));
    5319:   PetscCall(VecDuplicate(u, &fh));

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

    5342: /*@
    5343:   SNESGetLineSearch - Returns the line search associated with the `SNES`.

    5345:   Not Collective

    5347:   Input Parameter:
    5348: . snes - iterative context obtained from `SNESCreate()`

    5350:   Output Parameter:
    5351: . linesearch - linesearch context

    5353:   Level: beginner

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

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

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

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

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

    5385:   Logically Collective

    5387:   Input Parameters:
    5388: + snes - `SNES` context
    5389: - flag - `PETSC_TRUE` or `PETSC_FALSE`

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

    5401:   Level: advanced

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

    5410: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
    5411: @*/
    5412: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
    5413: {
    5414:   PetscFunctionBegin;
    5417:   snes->ksp_ewconv = flag;
    5418:   PetscFunctionReturn(PETSC_SUCCESS);
    5419: }

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

    5426:   Not Collective

    5428:   Input Parameter:
    5429: . snes - `SNES` context

    5431:   Output Parameter:
    5432: . flag - `PETSC_TRUE` or `PETSC_FALSE`

    5434:   Level: advanced

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

    5447: /*@
    5448:   SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
    5449:   convergence criteria for the linear solvers within an inexact
    5450:   Newton method.

    5452:   Logically Collective

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

    5465:   Level: advanced

    5467:   Notes:
    5468:   Version 3 was contributed by Luis Chacon, June 2006.

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

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

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

    5490:   if (version != PETSC_CURRENT) kctx->version = version;
    5491:   if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
    5492:   if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
    5493:   if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
    5494:   if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
    5495:   if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
    5496:   if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;

    5498:   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);
    5499:   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);
    5500:   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);
    5501:   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);
    5502:   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);
    5503:   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);
    5504:   PetscFunctionReturn(PETSC_SUCCESS);
    5505: }

    5507: /*@
    5508:   SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
    5509:   convergence criteria for the linear solvers within an inexact
    5510:   Newton method.

    5512:   Not Collective

    5514:   Input Parameter:
    5515: . snes - `SNES` context

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

    5526:   Level: advanced

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

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

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

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

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

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

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

    5617:     PetscCall(KSPGetPC(ksp, &pc));
    5618:     PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
    5619:     if (!getRes) {
    5620:       KSPNormType normtype;

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

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

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

    5648:   Input Parameter:
    5649: . snes - the `SNES` context

    5651:   Output Parameter:
    5652: . ksp - the `KSP` context

    5654:   Level: beginner

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

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

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

    5671:   if (!snes->ksp) {
    5672:     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
    5673:     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));

    5675:     PetscCall(KSPSetPreSolve(snes->ksp, KSPPreSolve_SNESEW, snes));
    5676:     PetscCall(KSPSetPostSolve(snes->ksp, KSPPostSolve_SNESEW, snes));

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

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

    5689:   Logically Collective

    5691:   Input Parameters:
    5692: + snes - the nonlinear solver context
    5693: - dm   - the `DM`, cannot be `NULL`

    5695:   Level: intermediate

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

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

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

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

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

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

    5740:   Input Parameter:
    5741: . snes - the `SNES` context

    5743:   Output Parameter:
    5744: . dm - the `DM`

    5746:   Level: intermediate

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

    5762: /*@
    5763:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

    5765:   Collective

    5767:   Input Parameters:
    5768: + snes - iterative context obtained from `SNESCreate()`
    5769: - npc  - the `SNES` nonlinear preconditioner object

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

    5774:   Level: developer

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

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

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

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

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

    5800:   Input Parameter:
    5801: . snes - iterative context obtained from `SNESCreate()`

    5803:   Output Parameter:
    5804: . pc - the `SNES` preconditioner context

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

    5809:   Level: advanced

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

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

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

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

    5826:   PetscFunctionBegin;
    5828:   PetscAssertPointer(pc, 2);
    5829:   if (!snes->npc) {
    5830:     PetscCtx ctx;

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

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

    5852:   Not Collective

    5854:   Input Parameter:
    5855: . snes - iterative context obtained from `SNESCreate()`

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

    5860:   Level: developer

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

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

    5876:   Logically Collective

    5878:   Input Parameter:
    5879: . snes - iterative context obtained from `SNESCreate()`

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

    5888:   Options Database Key:
    5889: . -snes_npc_side (right|left) - nonlinear preconditioner side

    5891:   Level: intermediate

    5893:   Note:
    5894:   `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.

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

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

    5912:   Not Collective

    5914:   Input Parameter:
    5915: . snes - iterative context obtained from `SNESCreate()`

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

    5924:   Level: intermediate

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

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

    5940:   Collective

    5942:   Input Parameters:
    5943: + snes       - iterative context obtained from `SNESCreate()`
    5944: - linesearch - the linesearch object

    5946:   Level: developer

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

    5952: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
    5953: @*/
    5954: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
    5955: {
    5956:   PetscFunctionBegin;
    5959:   PetscCheckSameComm(snes, 1, linesearch, 2);
    5960:   PetscCall(PetscObjectReference((PetscObject)linesearch));
    5961:   PetscCall(SNESLineSearchDestroy(&snes->linesearch));

    5963:   snes->linesearch = linesearch;
    5964:   PetscFunctionReturn(PETSC_SUCCESS);
    5965: }