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 application 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: /*@C
2239: SNESPicardComputeMFFunction - Matrix-free residual $A(x) x - b(x)$ used by `SNESSetPicard()` when the operator is applied through `-snes_mf_operator`
2241: Collective
2243: Input Parameters:
2244: + snes - the `SNES` context
2245: . x - the current iterate
2246: - ctx - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`
2248: Output Parameter:
2249: . f - the residual vector
2251: Level: developer
2253: Note:
2254: Uses a duplicate of `snes->jacobian_pre` because `snes->jacobian_pre` cannot be changed during the `KSPSolve()`.
2256: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeJacobian()`
2257: @*/
2258: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2259: {
2260: DM dm;
2261: DMSNES sdm;
2263: PetscFunctionBegin;
2264: PetscCall(SNESGetDM(snes, &dm));
2265: PetscCall(DMGetDMSNES(dm, &sdm));
2266: /* A(x)*x - b(x) */
2267: if (sdm->ops->computepfunction) {
2268: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2269: PetscCall(VecScale(f, -1.0));
2270: /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2271: if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2272: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2273: PetscCall(MatMultAdd(snes->picard, x, f, f));
2274: } else {
2275: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2276: PetscCall(MatMult(snes->picard, x, f));
2277: }
2278: PetscFunctionReturn(PETSC_SUCCESS);
2279: }
2281: /*@C
2282: SNESPicardComputeFunction - Compute the residual $A(x) x - b(x)$ using the callbacks registered by `SNESSetPicard()`
2284: Collective
2286: Input Parameters:
2287: + snes - the `SNES` context
2288: . x - the current iterate
2289: - ctx - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`
2291: Output Parameter:
2292: . f - the residual vector
2294: Level: developer
2296: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeMFFunction()`, `SNESPicardComputeJacobian()`
2297: @*/
2298: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2299: {
2300: DM dm;
2301: DMSNES sdm;
2303: PetscFunctionBegin;
2304: PetscCall(SNESGetDM(snes, &dm));
2305: PetscCall(DMGetDMSNES(dm, &sdm));
2306: /* A(x)*x - b(x) */
2307: if (sdm->ops->computepfunction) {
2308: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2309: PetscCall(VecScale(f, -1.0));
2310: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2311: PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2312: } else {
2313: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2314: PetscCall(MatMult(snes->jacobian_pre, x, f));
2315: }
2316: PetscFunctionReturn(PETSC_SUCCESS);
2317: }
2319: /*@C
2320: SNESPicardComputeJacobian - Trivial Jacobian assembly callback used by `SNESSetPicard()`; the Picard operator is filled in by `SNESPicardComputeFunction()`
2322: Collective
2324: Input Parameters:
2325: + snes - the `SNES` context
2326: . x1 - the current iterate (unused)
2327: . J - the Jacobian matrix to assemble
2328: . B - the preconditioning matrix (unused)
2329: - ctx - unused application context
2331: Level: developer
2333: Note:
2334: Only calls `MatAssemblyBegin()`/`MatAssemblyEnd()` on `J`, because the Picard iteration reuses the operator already assembled by `SNESPicardComputeFunction()`.
2336: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeMFFunction()`
2337: @*/
2338: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2339: {
2340: PetscFunctionBegin;
2341: /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2342: /* must assembly if matrix-free to get the last SNES solution */
2343: PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2344: PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2345: PetscFunctionReturn(PETSC_SUCCESS);
2346: }
2348: /*@C
2349: SNESSetPicard - Use `SNES` to solve the system $A(x) x = bp(x) + b $ via a Picard type iteration (Picard linearization)
2351: Logically Collective
2353: Input Parameters:
2354: + snes - the `SNES` context
2355: . r - vector to store function values, may be `NULL`
2356: . bp - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2357: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2358: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2359: . J - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2360: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
2362: Level: intermediate
2364: Notes:
2365: It is often better to provide the nonlinear function $F()$ and some approximation to its Jacobian directly and use
2366: 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.
2368: One can call `SNESSetPicard()` or `SNESSetFunction()` (and possibly `SNESSetJacobian()`) but cannot call both
2370: 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}$.
2371: When an exact solver is used this corresponds to the "classic" Picard $A(x^{n}) x^{n+1} = bp(x^{n}) + b$ iteration.
2373: Run with `-snes_mf_operator` to solve the system with Newton's method using $A(x^{n})$ to construct the preconditioner.
2375: We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2376: the direct Picard iteration $A(x^n) x^{n+1} = bp(x^n) + b$
2378: 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
2379: 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
2380: different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument \:-).
2382: 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
2383: $A(x^{n})$ is used to build the preconditioner
2385: When used with `-snes_fd` this will compute the true Jacobian (very slowly one column at a time) and thus represent Newton's method.
2387: 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
2388: 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
2389: 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`.
2390: See the comment in src/snes/tutorials/ex15.c.
2392: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2393: `SNESFunctionFn`, `SNESJacobianFn`
2394: @*/
2395: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2396: {
2397: DM dm;
2399: PetscFunctionBegin;
2401: PetscCall(SNESGetDM(snes, &dm));
2402: PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2403: PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2404: PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2405: PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2406: PetscFunctionReturn(PETSC_SUCCESS);
2407: }
2409: /*@C
2410: SNESGetPicard - Returns the context for the Picard iteration
2412: Not Collective, but `Vec` is parallel if `SNES` is parallel. Collective if `Vec` is requested, but has not been created yet.
2414: Input Parameter:
2415: . snes - the `SNES` context
2417: Output Parameters:
2418: + r - the function (or `NULL`)
2419: . f - the function (or `NULL`); for calling sequence see `SNESFunctionFn`
2420: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2421: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2422: . J - the function for matrix evaluation (or `NULL`); for calling sequence see `SNESJacobianFn`
2423: - ctx - the function context (or `NULL`)
2425: Level: advanced
2427: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2428: @*/
2429: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2430: {
2431: DM dm;
2433: PetscFunctionBegin;
2435: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2436: PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2437: PetscCall(SNESGetDM(snes, &dm));
2438: PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2439: PetscFunctionReturn(PETSC_SUCCESS);
2440: }
2442: /*@C
2443: SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the nonlinear problem
2445: Logically Collective
2447: Input Parameters:
2448: + snes - the `SNES` context
2449: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2450: - ctx - [optional] user-defined context for private data for the
2451: function evaluation routine (may be `NULL`)
2453: Level: intermediate
2455: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2456: @*/
2457: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2458: {
2459: PetscFunctionBegin;
2461: if (func) snes->ops->computeinitialguess = func;
2462: if (ctx) snes->initialguessP = ctx;
2463: PetscFunctionReturn(PETSC_SUCCESS);
2464: }
2466: /*@C
2467: SNESGetRhs - Gets the vector for solving F(x) = `rhs`. If `rhs` is not set
2468: it assumes a zero right-hand side.
2470: Logically Collective
2472: Input Parameter:
2473: . snes - the `SNES` context
2475: Output Parameter:
2476: . rhs - the right-hand side vector or `NULL` if there is no right-hand side vector
2478: Level: intermediate
2480: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2481: @*/
2482: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2483: {
2484: PetscFunctionBegin;
2486: PetscAssertPointer(rhs, 2);
2487: *rhs = snes->vec_rhs;
2488: PetscFunctionReturn(PETSC_SUCCESS);
2489: }
2491: /*@
2492: SNESComputeFunction - Calls the function that has been set with `SNESSetFunction()`.
2494: Collective
2496: Input Parameters:
2497: + snes - the `SNES` context
2498: - x - input vector
2500: Output Parameter:
2501: . f - function vector, as set by `SNESSetFunction()`
2503: Level: developer
2505: Notes:
2506: `SNESComputeFunction()` is typically used within nonlinear solvers
2507: implementations, so users would not generally call this routine themselves.
2509: When solving for $F(x) = b$, this routine computes $f = F(x) - b$.
2511: This function usually appears in the pattern.
2512: .vb
2513: SNESComputeFunction(snes, x, f);
2514: VecNorm(f, &fnorm);
2515: SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2516: .ve
2517: to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.
2519: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2520: @*/
2521: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2522: {
2523: DM dm;
2524: DMSNES sdm;
2526: PetscFunctionBegin;
2530: PetscCheckSameComm(snes, 1, x, 2);
2531: PetscCheckSameComm(snes, 1, f, 3);
2532: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2534: PetscCall(SNESGetDM(snes, &dm));
2535: PetscCall(DMGetDMSNES(dm, &sdm));
2536: 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().");
2537: if (sdm->ops->computefunction) {
2538: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2539: PetscCall(VecLockReadPush(x));
2540: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2541: snes->functiondomainerror = PETSC_FALSE;
2542: {
2543: void *ctx;
2544: SNESFunctionFn *computefunction;
2545: PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2546: PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2547: }
2548: PetscCall(VecLockReadPop(x));
2549: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2550: } else /* if (snes->vec_rhs) */ {
2551: PetscCall(MatMult(snes->jacobian, x, f));
2552: }
2553: if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2554: snes->nfuncs++;
2555: /*
2556: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2557: propagate the value to all processes
2558: */
2559: PetscCall(VecFlag(f, snes->functiondomainerror));
2560: PetscFunctionReturn(PETSC_SUCCESS);
2561: }
2563: /*@
2564: SNESComputeMFFunction - Calls the function that has been set with `DMSNESSetMFFunction()`.
2566: Collective
2568: Input Parameters:
2569: + snes - the `SNES` context
2570: - x - input vector
2572: Output Parameter:
2573: . y - output vector
2575: Level: developer
2577: Notes:
2578: `SNESComputeMFFunction()` is used within the matrix-vector products called by the matrix created with `MatCreateSNESMF()`
2579: so users would not generally call this routine themselves.
2581: Since this function is intended for use with finite differencing it does not subtract the right-hand side vector provided with `SNESSolve()`
2582: while `SNESComputeFunction()` does. As such, this routine cannot be used with `MatMFFDSetBase()` with a provided F function value even if it applies the
2583: 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.
2585: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2586: @*/
2587: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2588: {
2589: DM dm;
2590: DMSNES sdm;
2592: PetscFunctionBegin;
2596: PetscCheckSameComm(snes, 1, x, 2);
2597: PetscCheckSameComm(snes, 1, y, 3);
2598: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2600: PetscCall(SNESGetDM(snes, &dm));
2601: PetscCall(DMGetDMSNES(dm, &sdm));
2602: PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, y, 0));
2603: PetscCall(VecLockReadPush(x));
2604: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2605: snes->functiondomainerror = PETSC_FALSE;
2606: PetscCallBack("SNES callback function", (*sdm->ops->computemffunction)(snes, x, y, sdm->mffunctionctx));
2607: PetscCall(VecLockReadPop(x));
2608: PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, y, 0));
2609: snes->nfuncs++;
2610: /*
2611: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2612: propagate the value to all processes
2613: */
2614: PetscCall(VecFlag(y, snes->functiondomainerror));
2615: PetscFunctionReturn(PETSC_SUCCESS);
2616: }
2618: /*@
2619: SNESComputeNGS - Calls the Gauss-Seidel function that has been set with `SNESSetNGS()`.
2621: Collective
2623: Input Parameters:
2624: + snes - the `SNES` context
2625: . x - input vector
2626: - b - rhs vector
2628: Output Parameter:
2629: . x - new solution vector
2631: Level: developer
2633: Note:
2634: `SNESComputeNGS()` is typically used within composed nonlinear solver
2635: implementations, so most users would not generally call this routine
2636: themselves.
2638: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2639: @*/
2640: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2641: {
2642: DM dm;
2643: DMSNES sdm;
2645: PetscFunctionBegin;
2649: PetscCheckSameComm(snes, 1, x, 3);
2650: if (b) PetscCheckSameComm(snes, 1, b, 2);
2651: if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2652: PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2653: PetscCall(SNESGetDM(snes, &dm));
2654: PetscCall(DMGetDMSNES(dm, &sdm));
2655: PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2656: if (b) PetscCall(VecLockReadPush(b));
2657: PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2658: if (b) PetscCall(VecLockReadPop(b));
2659: PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2660: PetscFunctionReturn(PETSC_SUCCESS);
2661: }
2663: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2664: {
2665: Vec X;
2666: PetscScalar *g;
2667: PetscReal f, f2;
2668: PetscInt low, high, N, i;
2669: PetscBool flg;
2670: PetscReal h = .5 * PETSC_SQRT_MACHINE_EPSILON;
2672: PetscFunctionBegin;
2673: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2674: PetscCall(VecDuplicate(Xin, &X));
2675: PetscCall(VecCopy(Xin, X));
2676: PetscCall(VecGetSize(X, &N));
2677: PetscCall(VecGetOwnershipRange(X, &low, &high));
2678: PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2679: PetscCall(VecGetArray(G, &g));
2680: for (i = 0; i < N; i++) {
2681: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2682: PetscCall(VecAssemblyBegin(X));
2683: PetscCall(VecAssemblyEnd(X));
2684: PetscCall(SNESComputeObjective(snes, X, &f));
2685: PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2686: PetscCall(VecAssemblyBegin(X));
2687: PetscCall(VecAssemblyEnd(X));
2688: PetscCall(SNESComputeObjective(snes, X, &f2));
2689: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2690: PetscCall(VecAssemblyBegin(X));
2691: PetscCall(VecAssemblyEnd(X));
2692: if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2693: }
2694: PetscCall(VecRestoreArray(G, &g));
2695: PetscCall(VecDestroy(&X));
2696: PetscFunctionReturn(PETSC_SUCCESS);
2697: }
2699: /*@
2700: SNESTestFunction - Computes the difference between the computed and finite-difference functions
2702: Collective
2704: Input Parameter:
2705: . snes - the `SNES` context
2707: Options Database Keys:
2708: + -snes_test_function - compare the user provided function with one compute via finite differences to check for errors.
2709: - -snes_test_function_view - display the user provided function, the finite difference function and the difference
2711: Level: developer
2713: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2714: @*/
2715: PetscErrorCode SNESTestFunction(SNES snes)
2716: {
2717: Vec x, g1, g2, g3;
2718: PetscBool complete_print = PETSC_FALSE;
2719: PetscReal hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2720: PetscScalar dot;
2721: MPI_Comm comm;
2722: PetscViewer viewer, mviewer;
2723: PetscViewerFormat format;
2724: PetscInt tabs;
2725: static PetscBool directionsprinted = PETSC_FALSE;
2726: SNESObjectiveFn *objective;
2728: PetscFunctionBegin;
2729: PetscCall(SNESGetObjective(snes, &objective, NULL));
2730: if (!objective) PetscFunctionReturn(PETSC_SUCCESS);
2732: PetscObjectOptionsBegin((PetscObject)snes);
2733: PetscCall(PetscOptionsViewer("-snes_test_function_view", "View difference between hand-coded and finite difference function element entries", "None", &mviewer, &format, &complete_print));
2734: PetscOptionsEnd();
2736: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2737: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2738: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2739: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2740: PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Function -------------\n"));
2741: if (!complete_print && !directionsprinted) {
2742: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2743: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference function entries greater than <threshold>.\n"));
2744: }
2745: if (!directionsprinted) {
2746: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2747: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Function is probably correct.\n"));
2748: directionsprinted = PETSC_TRUE;
2749: }
2750: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2752: PetscCall(SNESGetSolution(snes, &x));
2753: PetscCall(VecDuplicate(x, &g1));
2754: PetscCall(VecDuplicate(x, &g2));
2755: PetscCall(VecDuplicate(x, &g3));
2756: PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() correctly */
2757: PetscCall(SNESComputeFunction_FD(snes, x, g2));
2759: PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2760: PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2761: PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2762: PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2763: PetscCall(VecDot(g1, g2, &dot));
2764: PetscCall(VecCopy(g1, g3));
2765: PetscCall(VecAXPY(g3, -1.0, g2));
2766: PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2767: PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2768: PetscCall(PetscViewerASCIIPrintf(viewer, " ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2769: PetscCall(PetscViewerASCIIPrintf(viewer, " 2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2770: PetscCall(PetscViewerASCIIPrintf(viewer, " max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));
2772: if (complete_print) {
2773: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded function ----------\n"));
2774: PetscCall(VecView(g1, mviewer));
2775: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference function ----------\n"));
2776: PetscCall(VecView(g2, mviewer));
2777: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference function ----------\n"));
2778: PetscCall(VecView(g3, mviewer));
2779: }
2780: PetscCall(VecDestroy(&g1));
2781: PetscCall(VecDestroy(&g2));
2782: PetscCall(VecDestroy(&g3));
2784: if (complete_print) {
2785: PetscCall(PetscViewerPopFormat(mviewer));
2786: PetscCall(PetscViewerDestroy(&mviewer));
2787: }
2788: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2789: PetscFunctionReturn(PETSC_SUCCESS);
2790: }
2792: /*@
2793: SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians
2795: Collective
2797: Input Parameter:
2798: . snes - the `SNES` context
2800: Output Parameters:
2801: + Jnorm - the Frobenius norm of the computed Jacobian, or `NULL`
2802: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`
2804: Options Database Keys:
2805: + -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.
2806: - -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference
2808: Level: developer
2810: Note:
2811: Directions and norms are printed to stdout if `diffNorm` is `NULL`.
2813: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2814: @*/
2815: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2816: {
2817: Mat A, B, C, D, jacobian;
2818: Vec x = snes->vec_sol, f;
2819: PetscReal nrm, gnorm;
2820: PetscReal threshold = 1.e-5;
2821: void *functx;
2822: PetscBool complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2823: PetscBool silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2824: PetscViewer viewer, mviewer;
2825: MPI_Comm comm;
2826: PetscInt tabs;
2827: static PetscBool directionsprinted = PETSC_FALSE;
2828: PetscViewerFormat format;
2830: PetscFunctionBegin;
2831: PetscObjectOptionsBegin((PetscObject)snes);
2832: PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2833: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2834: PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2835: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2836: 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));
2837: PetscOptionsEnd();
2839: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2840: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2841: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2842: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2843: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian -------------\n"));
2844: if (!complete_print && !silent && !directionsprinted) {
2845: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2846: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2847: }
2848: if (!directionsprinted && !silent) {
2849: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2850: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2851: directionsprinted = PETSC_TRUE;
2852: }
2853: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2855: PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2856: if (!flg) jacobian = snes->jacobian;
2857: else jacobian = snes->jacobian_pre;
2859: if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2860: else PetscCall(PetscObjectReference((PetscObject)x));
2861: PetscCall(VecDuplicate(x, &f));
2863: /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2864: PetscCall(SNESComputeFunction(snes, x, f));
2865: PetscCall(VecDestroy(&f));
2866: PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2867: while (jacobian) {
2868: Mat JT = NULL, Jsave = NULL;
2870: if (istranspose) {
2871: PetscCall(MatCreateTranspose(jacobian, &JT));
2872: Jsave = jacobian;
2873: jacobian = JT;
2874: }
2875: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2876: if (flg) {
2877: A = jacobian;
2878: PetscCall(PetscObjectReference((PetscObject)A));
2879: } else {
2880: PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2881: }
2883: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2884: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2886: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2887: PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));
2889: PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2890: PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2891: PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2892: PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2893: PetscCall(MatDestroy(&D));
2894: if (!gnorm) gnorm = 1; /* just in case */
2895: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2896: if (complete_print) {
2897: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded Jacobian ----------\n"));
2898: PetscCall(MatView(A, mviewer));
2899: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference Jacobian ----------\n"));
2900: PetscCall(MatView(B, mviewer));
2901: }
2903: if (threshold_print || complete_print) {
2904: PetscInt Istart, Iend, *ccols, bncols, cncols, j, row;
2905: PetscScalar *cvals;
2906: const PetscInt *bcols;
2907: const PetscScalar *bvals;
2909: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2910: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2912: PetscCall(MatAYPX(B, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2913: PetscCall(MatGetOwnershipRange(B, &Istart, &Iend));
2915: for (row = Istart; row < Iend; row++) {
2916: PetscCall(MatGetRow(B, row, &bncols, &bcols, &bvals));
2917: PetscCall(PetscMalloc2(bncols, &ccols, bncols, &cvals));
2918: for (j = 0, cncols = 0; j < bncols; j++) {
2919: if (PetscAbsScalar(bvals[j]) > threshold) {
2920: ccols[cncols] = bcols[j];
2921: cvals[cncols] = bvals[j];
2922: cncols += 1;
2923: }
2924: }
2925: if (cncols) PetscCall(MatSetValues(C, 1, &row, cncols, ccols, cvals, INSERT_VALUES));
2926: PetscCall(MatRestoreRow(B, row, &bncols, &bcols, &bvals));
2927: PetscCall(PetscFree2(ccols, cvals));
2928: }
2929: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2930: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2931: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n", (double)threshold));
2932: PetscCall(MatView(C, complete_print ? mviewer : viewer));
2933: PetscCall(MatDestroy(&C));
2934: }
2935: PetscCall(MatDestroy(&A));
2936: PetscCall(MatDestroy(&B));
2937: PetscCall(MatDestroy(&JT));
2938: if (Jsave) jacobian = Jsave;
2939: if (jacobian != snes->jacobian_pre) {
2940: jacobian = snes->jacobian_pre;
2941: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian for preconditioner -------------\n"));
2942: } else jacobian = NULL;
2943: }
2944: PetscCall(VecDestroy(&x));
2945: if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2946: PetscCall(PetscViewerDestroy(&mviewer));
2947: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2949: if (Jnorm) *Jnorm = gnorm;
2950: if (diffNorm) *diffNorm = nrm;
2951: PetscFunctionReturn(PETSC_SUCCESS);
2952: }
2954: /*@
2955: SNESComputeJacobian - Computes the Jacobian matrix that has been set with `SNESSetJacobian()`.
2957: Collective
2959: Input Parameters:
2960: + snes - the `SNES` context
2961: - X - input vector
2963: Output Parameters:
2964: + A - Jacobian matrix
2965: - B - optional matrix for building the preconditioner, usually the same as `A`
2967: Options Database Keys:
2968: + -snes_lag_preconditioner lag - how often to rebuild preconditioner
2969: . -snes_lag_jacobian lag - how often to rebuild Jacobian
2970: . -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors.
2971: If a threshold is given, display only those entries whose difference is greater than the threshold.
2972: . -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
2973: . -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2974: . -snes_compare_explicit_draw - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2975: . -snes_compare_explicit_contour - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2976: . -snes_compare_operator - Make the comparison options above use the operator instead of the matrix used to construct the preconditioner
2977: . -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2978: . -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2979: . -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2980: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2981: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2982: . -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2983: - -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences
2985: Level: developer
2987: Note:
2988: Most users should not need to explicitly call this routine, as it
2989: is used internally within the nonlinear solvers.
2991: Developer Note:
2992: 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
2993: with the `SNESType` of test that has been removed.
2995: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
2996: `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
2997: @*/
2998: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
2999: {
3000: PetscBool flag;
3001: DM dm;
3002: DMSNES sdm;
3003: KSP ksp;
3005: PetscFunctionBegin;
3008: PetscCheckSameComm(snes, 1, X, 2);
3009: PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
3010: PetscCall(SNESGetDM(snes, &dm));
3011: PetscCall(DMGetDMSNES(dm, &sdm));
3013: /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix-free */
3014: if (snes->lagjacobian == -2) {
3015: snes->lagjacobian = -1;
3017: PetscCall(PetscInfo(snes, "Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
3018: } else if (snes->lagjacobian == -1) {
3019: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is -1\n"));
3020: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3021: if (flag) {
3022: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3023: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3024: }
3025: PetscFunctionReturn(PETSC_SUCCESS);
3026: } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
3027: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagjacobian, snes->iter));
3028: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3029: if (flag) {
3030: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3031: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3032: }
3033: PetscFunctionReturn(PETSC_SUCCESS);
3034: }
3035: if (snes->npc && snes->npcside == PC_LEFT) {
3036: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3037: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3038: PetscFunctionReturn(PETSC_SUCCESS);
3039: }
3041: PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
3042: PetscCall(VecLockReadPush(X));
3043: {
3044: void *ctx;
3045: SNESJacobianFn *J;
3046: PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
3047: PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
3048: }
3049: PetscCall(VecLockReadPop(X));
3050: PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));
3052: /* attach latest linearization point to the matrix used to construct the preconditioner */
3053: PetscCall(PetscObjectCompose((PetscObject)B, "__SNES_latest_X", (PetscObject)X));
3055: /* the next line ensures that snes->ksp exists */
3056: PetscCall(SNESGetKSP(snes, &ksp));
3057: if (snes->lagpreconditioner == -2) {
3058: PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3059: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3060: snes->lagpreconditioner = -1;
3061: } else if (snes->lagpreconditioner == -1) {
3062: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3063: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3064: } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3065: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3066: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3067: } else {
3068: PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3069: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3070: }
3072: /* monkey business to allow testing Jacobians in multilevel solvers.
3073: This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3074: {
3075: Vec xsave = snes->vec_sol;
3076: Mat jacobiansave = snes->jacobian;
3077: Mat jacobian_presave = snes->jacobian_pre;
3079: snes->vec_sol = X;
3080: snes->jacobian = A;
3081: snes->jacobian_pre = B;
3082: if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3083: if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));
3085: snes->vec_sol = xsave;
3086: snes->jacobian = jacobiansave;
3087: snes->jacobian_pre = jacobian_presave;
3088: }
3090: {
3091: PetscBool flag = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_operator = PETSC_FALSE;
3092: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit", NULL, NULL, &flag));
3093: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw", NULL, NULL, &flag_draw));
3094: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw_contour", NULL, NULL, &flag_contour));
3095: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_operator", NULL, NULL, &flag_operator));
3096: if (flag || flag_draw || flag_contour) {
3097: Mat Bexp_mine = NULL, Bexp, FDexp;
3098: PetscViewer vdraw, vstdout;
3099: PetscBool flg;
3100: if (flag_operator) {
3101: PetscCall(MatComputeOperator(A, MATAIJ, &Bexp_mine));
3102: Bexp = Bexp_mine;
3103: } else {
3104: /* See if the matrix used to construct the preconditioner can be viewed and added directly */
3105: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
3106: if (flg) Bexp = B;
3107: else {
3108: /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
3109: PetscCall(MatComputeOperator(B, MATAIJ, &Bexp_mine));
3110: Bexp = Bexp_mine;
3111: }
3112: }
3113: PetscCall(MatConvert(Bexp, MATSAME, MAT_INITIAL_MATRIX, &FDexp));
3114: PetscCall(SNESComputeJacobianDefault(snes, X, FDexp, FDexp, NULL));
3115: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3116: if (flag_draw || flag_contour) {
3117: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Explicit Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3118: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3119: } else vdraw = NULL;
3120: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit %s\n", flag_operator ? "Jacobian" : "preconditioning Jacobian"));
3121: if (flag) PetscCall(MatView(Bexp, vstdout));
3122: if (vdraw) PetscCall(MatView(Bexp, vdraw));
3123: PetscCall(PetscViewerASCIIPrintf(vstdout, "Finite difference Jacobian\n"));
3124: if (flag) PetscCall(MatView(FDexp, vstdout));
3125: if (vdraw) PetscCall(MatView(FDexp, vdraw));
3126: PetscCall(MatAYPX(FDexp, -1.0, Bexp, SAME_NONZERO_PATTERN));
3127: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian\n"));
3128: if (flag) PetscCall(MatView(FDexp, vstdout));
3129: if (vdraw) { /* Always use contour for the difference */
3130: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3131: PetscCall(MatView(FDexp, vdraw));
3132: PetscCall(PetscViewerPopFormat(vdraw));
3133: }
3134: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3135: PetscCall(PetscViewerDestroy(&vdraw));
3136: PetscCall(MatDestroy(&Bexp_mine));
3137: PetscCall(MatDestroy(&FDexp));
3138: }
3139: }
3140: {
3141: PetscBool flag = PETSC_FALSE, flag_display = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_threshold = PETSC_FALSE;
3142: PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON, threshold_rtol = 10 * PETSC_SQRT_MACHINE_EPSILON;
3143: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring", NULL, NULL, &flag));
3144: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_display", NULL, NULL, &flag_display));
3145: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw", NULL, NULL, &flag_draw));
3146: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw_contour", NULL, NULL, &flag_contour));
3147: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold", NULL, NULL, &flag_threshold));
3148: if (flag_threshold) {
3149: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_rtol", &threshold_rtol, NULL));
3150: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_atol", &threshold_atol, NULL));
3151: }
3152: if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
3153: Mat Bfd;
3154: PetscViewer vdraw, vstdout;
3155: MatColoring coloring;
3156: ISColoring iscoloring;
3157: MatFDColoring matfdcoloring;
3158: SNESFunctionFn *func;
3159: void *funcctx;
3160: PetscReal norm1, norm2, normmax;
3162: PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3163: PetscCall(MatColoringCreate(Bfd, &coloring));
3164: PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3165: PetscCall(MatColoringSetFromOptions(coloring));
3166: PetscCall(MatColoringApply(coloring, &iscoloring));
3167: PetscCall(MatColoringDestroy(&coloring));
3168: PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3169: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3170: PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3171: PetscCall(ISColoringDestroy(&iscoloring));
3173: /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3174: PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3175: PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3176: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3177: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3178: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3179: PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3180: PetscCall(MatFDColoringDestroy(&matfdcoloring));
3182: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3183: if (flag_draw || flag_contour) {
3184: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Colored Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3185: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3186: } else vdraw = NULL;
3187: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit preconditioning Jacobian\n"));
3188: if (flag_display) PetscCall(MatView(B, vstdout));
3189: if (vdraw) PetscCall(MatView(B, vdraw));
3190: PetscCall(PetscViewerASCIIPrintf(vstdout, "Colored Finite difference Jacobian\n"));
3191: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3192: if (vdraw) PetscCall(MatView(Bfd, vdraw));
3193: PetscCall(MatAYPX(Bfd, -1.0, B, SAME_NONZERO_PATTERN));
3194: PetscCall(MatNorm(Bfd, NORM_1, &norm1));
3195: PetscCall(MatNorm(Bfd, NORM_FROBENIUS, &norm2));
3196: PetscCall(MatNorm(Bfd, NORM_MAX, &normmax));
3197: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n", (double)norm1, (double)norm2, (double)normmax));
3198: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3199: if (vdraw) { /* Always use contour for the difference */
3200: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3201: PetscCall(MatView(Bfd, vdraw));
3202: PetscCall(PetscViewerPopFormat(vdraw));
3203: }
3204: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3206: if (flag_threshold) {
3207: PetscInt bs, rstart, rend, i;
3208: PetscCall(MatGetBlockSize(B, &bs));
3209: PetscCall(MatGetOwnershipRange(B, &rstart, &rend));
3210: for (i = rstart; i < rend; i++) {
3211: const PetscScalar *ba, *ca;
3212: const PetscInt *bj, *cj;
3213: PetscInt bn, cn, j, maxentrycol = -1, maxdiffcol = -1, maxrdiffcol = -1;
3214: PetscReal maxentry = 0, maxdiff = 0, maxrdiff = 0;
3215: PetscCall(MatGetRow(B, i, &bn, &bj, &ba));
3216: PetscCall(MatGetRow(Bfd, i, &cn, &cj, &ca));
3217: PetscCheck(bn == cn, ((PetscObject)A)->comm, PETSC_ERR_PLIB, "Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
3218: for (j = 0; j < bn; j++) {
3219: PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3220: if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
3221: maxentrycol = bj[j];
3222: maxentry = PetscRealPart(ba[j]);
3223: }
3224: if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
3225: maxdiffcol = bj[j];
3226: maxdiff = PetscRealPart(ca[j]);
3227: }
3228: if (rdiff > maxrdiff) {
3229: maxrdiffcol = bj[j];
3230: maxrdiff = rdiff;
3231: }
3232: }
3233: if (maxrdiff > 1) {
3234: 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));
3235: for (j = 0; j < bn; j++) {
3236: PetscReal rdiff;
3237: rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3238: if (rdiff > 1) PetscCall(PetscViewerASCIIPrintf(vstdout, " (%" PetscInt_FMT ",%g:%g)", bj[j], (double)PetscRealPart(ba[j]), (double)PetscRealPart(ca[j])));
3239: }
3240: PetscCall(PetscViewerASCIIPrintf(vstdout, "\n"));
3241: }
3242: PetscCall(MatRestoreRow(B, i, &bn, &bj, &ba));
3243: PetscCall(MatRestoreRow(Bfd, i, &cn, &cj, &ca));
3244: }
3245: }
3246: PetscCall(PetscViewerDestroy(&vdraw));
3247: PetscCall(MatDestroy(&Bfd));
3248: }
3249: }
3250: PetscFunctionReturn(PETSC_SUCCESS);
3251: }
3253: /*@C
3254: SNESSetJacobian - Sets the function to compute Jacobian as well as the
3255: location to store the matrix.
3257: Logically Collective
3259: Input Parameters:
3260: + snes - the `SNES` context
3261: . Amat - the matrix that defines the (approximate) Jacobian
3262: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3263: . J - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3264: - ctx - [optional] user-defined context for private data for the
3265: Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)
3267: Level: beginner
3269: Notes:
3270: If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3271: each matrix.
3273: If you know the operator `Amat` has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
3274: space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
3276: If using `SNESComputeJacobianDefaultColor()` to assemble a Jacobian, the `ctx` argument
3277: must be a `MatFDColoring`.
3279: Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian. One common
3280: example is to use the "Picard linearization" which only differentiates through the highest order parts of each term using `SNESSetPicard()`
3282: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3283: `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3284: @*/
3285: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3286: {
3287: DM dm;
3289: PetscFunctionBegin;
3293: if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3294: if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3295: PetscCall(SNESGetDM(snes, &dm));
3296: PetscCall(DMSNESSetJacobian(dm, J, ctx));
3297: if (Amat) {
3298: PetscCall(PetscObjectReference((PetscObject)Amat));
3299: PetscCall(MatDestroy(&snes->jacobian));
3301: snes->jacobian = Amat;
3302: }
3303: if (Pmat) {
3304: PetscCall(PetscObjectReference((PetscObject)Pmat));
3305: PetscCall(MatDestroy(&snes->jacobian_pre));
3307: snes->jacobian_pre = Pmat;
3308: }
3309: PetscFunctionReturn(PETSC_SUCCESS);
3310: }
3312: /*@C
3313: SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3314: provided context for evaluating the Jacobian.
3316: Not Collective, but `Mat` object will be parallel if `SNES` is
3318: Input Parameter:
3319: . snes - the nonlinear solver context
3321: Output Parameters:
3322: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3323: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3324: . J - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3325: - ctx - location to stash Jacobian ctx (or `NULL`)
3327: Level: advanced
3329: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3330: @*/
3331: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3332: {
3333: DM dm;
3335: PetscFunctionBegin;
3337: if (Amat) *Amat = snes->jacobian;
3338: if (Pmat) *Pmat = snes->jacobian_pre;
3339: PetscCall(SNESGetDM(snes, &dm));
3340: PetscCall(DMSNESGetJacobian(dm, J, ctx));
3341: PetscFunctionReturn(PETSC_SUCCESS);
3342: }
3344: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3345: {
3346: DM dm;
3347: DMSNES sdm;
3349: PetscFunctionBegin;
3350: PetscCall(SNESGetDM(snes, &dm));
3351: PetscCall(DMGetDMSNES(dm, &sdm));
3352: if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3353: DM dm;
3354: PetscBool isdense, ismf;
3356: PetscCall(SNESGetDM(snes, &dm));
3357: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3358: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3359: if (isdense) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3360: else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3361: }
3362: PetscFunctionReturn(PETSC_SUCCESS);
3363: }
3365: /*@
3366: SNESSetUp - Sets up the internal data structures for the later use
3367: of a nonlinear solver `SNESSolve()`.
3369: Collective
3371: Input Parameter:
3372: . snes - the `SNES` context
3374: Level: advanced
3376: Note:
3377: For basic use of the `SNES` solvers the user does not need to explicitly call
3378: `SNESSetUp()`, since these actions will automatically occur during
3379: the call to `SNESSolve()`. However, if one wishes to control this
3380: phase separately, `SNESSetUp()` should be called after `SNESCreate()`
3381: and optional routines of the form SNESSetXXX(), but before `SNESSolve()`.
3383: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3384: @*/
3385: PetscErrorCode SNESSetUp(SNES snes)
3386: {
3387: DM dm;
3388: DMSNES sdm;
3389: SNESLineSearch linesearch, pclinesearch;
3390: void *lsprectx, *lspostctx;
3391: PetscBool mf_operator, mf;
3392: Vec f, fpc;
3393: void *funcctx;
3394: void *jacctx, *appctx;
3395: Mat j, jpre;
3396: PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3397: PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3398: SNESFunctionFn *func;
3399: SNESJacobianFn *jac;
3401: PetscFunctionBegin;
3403: if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3404: PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));
3406: if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, SNESNEWTONLS));
3408: PetscCall(SNESGetFunction(snes, &snes->vec_func, NULL, NULL));
3410: PetscCall(SNESGetDM(snes, &dm));
3411: PetscCall(DMGetDMSNES(dm, &sdm));
3412: PetscCall(SNESSetDefaultComputeJacobian(snes));
3414: if (!snes->vec_func) PetscCall(DMCreateGlobalVector(dm, &snes->vec_func));
3416: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
3418: if (snes->linesearch) {
3419: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3420: PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3421: }
3423: PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3424: if (snes->npc && snes->npcside == PC_LEFT) {
3425: snes->mf = PETSC_TRUE;
3426: snes->mf_operator = PETSC_FALSE;
3427: }
3429: if (snes->npc) {
3430: /* copy the DM over */
3431: PetscCall(SNESGetDM(snes, &dm));
3432: PetscCall(SNESSetDM(snes->npc, dm));
3434: PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3435: PetscCall(VecDuplicate(f, &fpc));
3436: PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3437: PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3438: PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3439: PetscCall(SNESGetApplicationContext(snes, &appctx));
3440: PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3441: PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3442: PetscCall(VecDestroy(&fpc));
3444: /* copy the function pointers over */
3445: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes, (PetscObject)snes->npc));
3447: /* default to 1 iteration */
3448: PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
3449: if (snes->npcside == PC_RIGHT) {
3450: PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3451: } else {
3452: PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3453: }
3454: PetscCall(SNESSetFromOptions(snes->npc));
3456: /* copy the line search context over */
3457: if (snes->linesearch && snes->npc->linesearch) {
3458: PetscCall(SNESGetLineSearch(snes, &linesearch));
3459: PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3460: PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3461: PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3462: PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3463: PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3464: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3465: }
3466: }
3467: if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
3468: if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));
3470: snes->jac_iter = 0;
3471: snes->pre_iter = 0;
3473: PetscTryTypeMethod(snes, setup);
3475: PetscCall(SNESSetDefaultComputeJacobian(snes));
3477: if (snes->npc && snes->npcside == PC_LEFT) {
3478: if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3479: if (snes->linesearch) {
3480: PetscCall(SNESGetLineSearch(snes, &linesearch));
3481: PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3482: }
3483: }
3484: }
3485: PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3486: snes->setupcalled = PETSC_TRUE;
3487: PetscFunctionReturn(PETSC_SUCCESS);
3488: }
3490: /*@
3491: 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
3493: Collective
3495: Input Parameter:
3496: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3498: Level: intermediate
3500: Notes:
3501: Any options set on the `SNES` object, including those set with `SNESSetFromOptions()` remain.
3503: Call this if you wish to reuse a `SNES` but with different size vectors
3505: Also calls the application context destroy routine set with `SNESSetComputeApplicationContext()`
3507: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3508: @*/
3509: PetscErrorCode SNESReset(SNES snes)
3510: {
3511: PetscFunctionBegin;
3513: if (snes->ops->ctxdestroy && snes->ctx) {
3514: PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3515: snes->ctx = NULL;
3516: }
3517: if (snes->npc) PetscCall(SNESReset(snes->npc));
3519: PetscTryTypeMethod(snes, reset);
3520: if (snes->ksp) PetscCall(KSPReset(snes->ksp));
3522: if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));
3524: PetscCall(VecDestroy(&snes->vec_rhs));
3525: PetscCall(VecDestroy(&snes->vec_sol));
3526: PetscCall(VecDestroy(&snes->vec_sol_update));
3527: PetscCall(VecDestroy(&snes->vec_func));
3528: PetscCall(MatDestroy(&snes->jacobian));
3529: PetscCall(MatDestroy(&snes->jacobian_pre));
3530: PetscCall(MatDestroy(&snes->picard));
3531: PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3532: PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));
3534: snes->alwayscomputesfinalresidual = PETSC_FALSE;
3536: snes->nwork = snes->nvwork = 0;
3537: snes->setupcalled = PETSC_FALSE;
3538: PetscFunctionReturn(PETSC_SUCCESS);
3539: }
3541: /*@
3542: SNESConvergedReasonViewCancel - Clears all the reason view functions for a `SNES` object provided with `SNESConvergedReasonViewSet()` also
3543: removes the default viewer.
3545: Collective
3547: Input Parameter:
3548: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3550: Level: intermediate
3552: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3553: @*/
3554: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3555: {
3556: PetscInt i;
3558: PetscFunctionBegin;
3560: for (i = 0; i < snes->numberreasonviews; i++) {
3561: if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3562: }
3563: snes->numberreasonviews = 0;
3564: PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3565: PetscFunctionReturn(PETSC_SUCCESS);
3566: }
3568: /*@
3569: SNESDestroy - Destroys the nonlinear solver context that was created
3570: with `SNESCreate()`.
3572: Collective
3574: Input Parameter:
3575: . snes - the `SNES` context
3577: Level: beginner
3579: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3580: @*/
3581: PetscErrorCode SNESDestroy(SNES *snes)
3582: {
3583: DM dm;
3585: PetscFunctionBegin;
3586: if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3588: if (--((PetscObject)*snes)->refct > 0) {
3589: *snes = NULL;
3590: PetscFunctionReturn(PETSC_SUCCESS);
3591: }
3593: PetscCall(SNESReset(*snes));
3594: PetscCall(SNESDestroy(&(*snes)->npc));
3596: /* if memory was published with SAWs then destroy it */
3597: PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3598: PetscTryTypeMethod(*snes, destroy);
3600: dm = (*snes)->dm;
3601: while (dm) {
3602: PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3603: PetscCall(DMGetCoarseDM(dm, &dm));
3604: }
3606: PetscCall(DMDestroy(&(*snes)->dm));
3607: PetscCall(KSPDestroy(&(*snes)->ksp));
3608: PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));
3610: PetscCall(PetscFree((*snes)->kspconvctx));
3611: if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3612: if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3613: PetscCall(SNESMonitorCancel(*snes));
3614: PetscCall(SNESConvergedReasonViewCancel(*snes));
3615: PetscCall(PetscHeaderDestroy(snes));
3616: PetscFunctionReturn(PETSC_SUCCESS);
3617: }
3619: /* ----------- Routines to set solver parameters ---------- */
3621: /*@
3622: SNESSetLagPreconditioner - Sets when the preconditioner is rebuilt in the nonlinear solve `SNESSolve()`.
3624: Logically Collective
3626: Input Parameters:
3627: + snes - the `SNES` context
3628: - lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3629: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3631: Options Database Keys:
3632: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3633: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3634: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3635: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3637: Level: intermediate
3639: Notes:
3640: The default is 1
3642: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagPreconditionerPersists()` was called
3644: `SNESSetLagPreconditionerPersists()` allows using the same uniform lagging (for example every second linear solve) across multiple nonlinear solves.
3646: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3647: `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3648: @*/
3649: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3650: {
3651: PetscFunctionBegin;
3653: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3654: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3656: snes->lagpreconditioner = lag;
3657: PetscFunctionReturn(PETSC_SUCCESS);
3658: }
3660: /*@
3661: SNESSetGridSequence - sets the number of steps of grid sequencing that `SNES` will do
3663: Logically Collective
3665: Input Parameters:
3666: + snes - the `SNES` context
3667: - steps - the number of refinements to do, defaults to 0
3669: Options Database Key:
3670: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess
3672: Level: intermediate
3674: Notes:
3675: Once grid sequencing is turned on `SNESSolve()` will automatically perform the solve on each grid refinement.
3677: Use `SNESGetSolution()` to extract the fine grid solution after grid sequencing.
3679: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3680: `SNESSetDM()`, `SNESSolve()`
3681: @*/
3682: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3683: {
3684: PetscFunctionBegin;
3687: snes->gridsequence = steps;
3688: PetscFunctionReturn(PETSC_SUCCESS);
3689: }
3691: /*@
3692: SNESGetGridSequence - gets the number of steps of grid sequencing that `SNES` will do
3694: Logically Collective
3696: Input Parameter:
3697: . snes - the `SNES` context
3699: Output Parameter:
3700: . steps - the number of refinements to do, defaults to 0
3702: Level: intermediate
3704: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3705: @*/
3706: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3707: {
3708: PetscFunctionBegin;
3710: *steps = snes->gridsequence;
3711: PetscFunctionReturn(PETSC_SUCCESS);
3712: }
3714: /*@
3715: SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt
3717: Not Collective
3719: Input Parameter:
3720: . snes - the `SNES` context
3722: Output Parameter:
3723: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3724: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3726: Level: intermediate
3728: Notes:
3729: The default is 1
3731: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3733: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3734: @*/
3735: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3736: {
3737: PetscFunctionBegin;
3739: *lag = snes->lagpreconditioner;
3740: PetscFunctionReturn(PETSC_SUCCESS);
3741: }
3743: /*@
3744: SNESSetLagJacobian - Set when the Jacobian is rebuilt in the nonlinear solve. See `SNESSetLagPreconditioner()` for determining how
3745: often the preconditioner is rebuilt.
3747: Logically Collective
3749: Input Parameters:
3750: + snes - the `SNES` context
3751: - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3752: the Jacobian is built etc. -2 means rebuild at next chance but then never again
3754: Options Database Keys:
3755: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3756: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3757: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3758: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag.
3760: Level: intermediate
3762: Notes:
3763: The default is 1
3765: The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3767: 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
3768: at the next Newton step but never again (unless it is reset to another value)
3770: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3771: @*/
3772: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3773: {
3774: PetscFunctionBegin;
3776: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3777: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3779: snes->lagjacobian = lag;
3780: PetscFunctionReturn(PETSC_SUCCESS);
3781: }
3783: /*@
3784: SNESGetLagJacobian - Get how often the Jacobian is rebuilt. See `SNESGetLagPreconditioner()` to determine when the preconditioner is rebuilt
3786: Not Collective
3788: Input Parameter:
3789: . snes - the `SNES` context
3791: Output Parameter:
3792: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3793: the Jacobian is built etc.
3795: Level: intermediate
3797: Notes:
3798: The default is 1
3800: The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagJacobianPersists()` was called.
3802: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3803: @*/
3804: PetscErrorCode SNESGetLagJacobian(SNES snes, PetscInt *lag)
3805: {
3806: PetscFunctionBegin;
3808: *lag = snes->lagjacobian;
3809: PetscFunctionReturn(PETSC_SUCCESS);
3810: }
3812: /*@
3813: SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple nonlinear solves
3815: Logically collective
3817: Input Parameters:
3818: + snes - the `SNES` context
3819: - flg - jacobian lagging persists if true
3821: Options Database Keys:
3822: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3823: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3824: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3825: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3827: Level: advanced
3829: Notes:
3830: Normally when `SNESSetLagJacobian()` is used, the Jacobian is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3832: This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3833: several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3834: timesteps may present huge efficiency gains.
3836: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3837: @*/
3838: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3839: {
3840: PetscFunctionBegin;
3843: snes->lagjac_persist = flg;
3844: PetscFunctionReturn(PETSC_SUCCESS);
3845: }
3847: /*@
3848: SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
3850: Logically Collective
3852: Input Parameters:
3853: + snes - the `SNES` context
3854: - flg - preconditioner lagging persists if true
3856: Options Database Keys:
3857: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3858: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3859: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3860: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3862: Level: developer
3864: Notes:
3865: Normally when `SNESSetLagPreconditioner()` is used, the preconditioner is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3867: This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3868: by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3869: several timesteps may present huge efficiency gains.
3871: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3872: @*/
3873: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3874: {
3875: PetscFunctionBegin;
3878: snes->lagpre_persist = flg;
3879: PetscFunctionReturn(PETSC_SUCCESS);
3880: }
3882: /*@
3883: SNESSetForceIteration - force `SNESSolve()` to take at least one iteration regardless of the initial residual norm
3885: Logically Collective
3887: Input Parameters:
3888: + snes - the `SNES` context
3889: - force - `PETSC_TRUE` require at least one iteration
3891: Options Database Key:
3892: . -snes_force_iteration force - Sets forcing an iteration
3894: Level: intermediate
3896: Note:
3897: This is used sometimes with `TS` to prevent `TS` from detecting a false steady state solution
3899: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3900: @*/
3901: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3902: {
3903: PetscFunctionBegin;
3905: snes->forceiteration = force;
3906: PetscFunctionReturn(PETSC_SUCCESS);
3907: }
3909: /*@
3910: SNESGetForceIteration - Check whether or not `SNESSolve()` take at least one iteration regardless of the initial residual norm
3912: Logically Collective
3914: Input Parameter:
3915: . snes - the `SNES` context
3917: Output Parameter:
3918: . force - `PETSC_TRUE` requires at least one iteration.
3920: Level: intermediate
3922: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3923: @*/
3924: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3925: {
3926: PetscFunctionBegin;
3928: *force = snes->forceiteration;
3929: PetscFunctionReturn(PETSC_SUCCESS);
3930: }
3932: /*@
3933: SNESSetTolerances - Sets various parameters used in `SNES` convergence tests.
3935: Logically Collective
3937: Input Parameters:
3938: + snes - the `SNES` context
3939: . abstol - the absolute convergence tolerance, $ F(x^n) \le abstol $
3940: . rtol - the relative convergence tolerance, $ F(x^n) \le reltol * F(x^0) $
3941: . stol - convergence tolerance in terms of the norm of the change in the solution between steps, || delta x || < stol*|| x ||
3942: . maxit - the maximum number of iterations allowed in the solver, default 50.
3943: - maxf - the maximum number of function evaluations allowed in the solver (use `PETSC_UNLIMITED` indicates no limit), default 10,000
3945: Options Database Keys:
3946: + -snes_atol abstol - Sets `abstol`
3947: . -snes_rtol rtol - Sets `rtol`
3948: . -snes_stol stol - Sets `stol`
3949: . -snes_max_it maxit - Sets `maxit`
3950: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)
3952: Level: intermediate
3954: Note:
3955: All parameters must be non-negative
3957: Use `PETSC_CURRENT` to retain the current value of any parameter and `PETSC_DETERMINE` to use the default value for the given `SNES`.
3958: The default value is the value in the object when its type is set.
3960: Use `PETSC_UNLIMITED` on `maxit` or `maxf` to indicate there is no bound on the number of iterations or number of function evaluations.
3962: Fortran Note:
3963: Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`
3965: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
3966: @*/
3967: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
3968: {
3969: PetscFunctionBegin;
3977: if (abstol == (PetscReal)PETSC_DETERMINE) {
3978: snes->abstol = snes->default_abstol;
3979: } else if (abstol != (PetscReal)PETSC_CURRENT) {
3980: PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
3981: snes->abstol = abstol;
3982: }
3984: if (rtol == (PetscReal)PETSC_DETERMINE) {
3985: snes->rtol = snes->default_rtol;
3986: } else if (rtol != (PetscReal)PETSC_CURRENT) {
3987: 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);
3988: snes->rtol = rtol;
3989: }
3991: if (stol == (PetscReal)PETSC_DETERMINE) {
3992: snes->stol = snes->default_stol;
3993: } else if (stol != (PetscReal)PETSC_CURRENT) {
3994: PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
3995: snes->stol = stol;
3996: }
3998: if (maxit == PETSC_DETERMINE) {
3999: snes->max_its = snes->default_max_its;
4000: } else if (maxit == PETSC_UNLIMITED) {
4001: snes->max_its = PETSC_INT_MAX;
4002: } else if (maxit != PETSC_CURRENT) {
4003: PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
4004: snes->max_its = maxit;
4005: }
4007: if (maxf == PETSC_DETERMINE) {
4008: snes->max_funcs = snes->default_max_funcs;
4009: } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
4010: snes->max_funcs = PETSC_UNLIMITED;
4011: } else if (maxf != PETSC_CURRENT) {
4012: PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
4013: snes->max_funcs = maxf;
4014: }
4015: PetscFunctionReturn(PETSC_SUCCESS);
4016: }
4018: /*@
4019: SNESSetDivergenceTolerance - Sets the divergence tolerance used for the `SNES` divergence test.
4021: Logically Collective
4023: Input Parameters:
4024: + snes - the `SNES` context
4025: - 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
4026: is stopped due to divergence.
4028: Options Database Key:
4029: . -snes_divergence_tolerance divtol - Sets `divtol`
4031: Level: intermediate
4033: Notes:
4034: Use `PETSC_DETERMINE` to use the default value from when the object's type was set.
4036: Fortran Note:
4037: Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`
4039: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
4040: @*/
4041: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
4042: {
4043: PetscFunctionBegin;
4047: if (divtol == (PetscReal)PETSC_DETERMINE) {
4048: snes->divtol = snes->default_divtol;
4049: } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
4050: snes->divtol = PETSC_UNLIMITED;
4051: } else if (divtol != (PetscReal)PETSC_CURRENT) {
4052: PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
4053: snes->divtol = divtol;
4054: }
4055: PetscFunctionReturn(PETSC_SUCCESS);
4056: }
4058: /*@
4059: SNESGetTolerances - Gets various parameters used in `SNES` convergence tests.
4061: Not Collective
4063: Input Parameter:
4064: . snes - the `SNES` context
4066: Output Parameters:
4067: + atol - the absolute convergence tolerance
4068: . rtol - the relative convergence tolerance
4069: . stol - convergence tolerance in terms of the norm of the change in the solution between steps
4070: . maxit - the maximum number of iterations allowed
4071: - maxf - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound
4073: Level: intermediate
4075: Notes:
4076: See `SNESSetTolerances()` for details on the parameters.
4078: The user can specify `NULL` for any parameter that is not needed.
4080: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4081: @*/
4082: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4083: {
4084: PetscFunctionBegin;
4086: if (atol) *atol = snes->abstol;
4087: if (rtol) *rtol = snes->rtol;
4088: if (stol) *stol = snes->stol;
4089: if (maxit) *maxit = snes->max_its;
4090: if (maxf) *maxf = snes->max_funcs;
4091: PetscFunctionReturn(PETSC_SUCCESS);
4092: }
4094: /*@
4095: SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
4097: Not Collective
4099: Input Parameters:
4100: + snes - the `SNES` context
4101: - divtol - divergence tolerance
4103: Level: intermediate
4105: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4106: @*/
4107: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4108: {
4109: PetscFunctionBegin;
4111: if (divtol) *divtol = snes->divtol;
4112: PetscFunctionReturn(PETSC_SUCCESS);
4113: }
4115: PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES, PetscInt, PetscReal *);
4117: /*@C
4118: SNESMonitorLGRange - Line-graph monitor that plots the residual norm together with residual-range statistics for a `SNESSolve()`
4120: Collective
4122: Input Parameters:
4123: + snes - the `SNES` context
4124: . n - the iteration number
4125: . rnorm - the 2-norm of the residual
4126: - monctx - a `PetscViewer` of type `PETSCVIEWERDRAW` set up with `PetscViewerMonitorLGSetUp()`
4128: Level: intermediate
4130: Note:
4131: Plots four line graphs in the viewer: the residual norm (log scale), the fraction of residual entries larger than 20% of the maximum entry, the relative decrease `(prev - rnorm)/prev`, and their product.
4133: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`, `SNESMonitorDefault()`, `PetscViewerDrawGetDrawLG()`, `PetscDrawLG`
4134: @*/
4135: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4136: {
4137: PetscDrawLG lg;
4138: PetscReal x, y, per;
4139: PetscViewer v = (PetscViewer)monctx;
4140: static PetscReal prev; /* should be in the context */
4141: PetscDraw draw;
4143: PetscFunctionBegin;
4145: PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4146: if (!n) PetscCall(PetscDrawLGReset(lg));
4147: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4148: PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4149: x = (PetscReal)n;
4150: if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4151: else y = -15.0;
4152: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4153: if (n < 20 || !(n % 5) || snes->reason) {
4154: PetscCall(PetscDrawLGDraw(lg));
4155: PetscCall(PetscDrawLGSave(lg));
4156: }
4158: PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4159: if (!n) PetscCall(PetscDrawLGReset(lg));
4160: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4161: PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4162: PetscCall(SNESMonitorRange_Private(snes, n, &per));
4163: x = (PetscReal)n;
4164: y = 100.0 * per;
4165: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4166: if (n < 20 || !(n % 5) || snes->reason) {
4167: PetscCall(PetscDrawLGDraw(lg));
4168: PetscCall(PetscDrawLGSave(lg));
4169: }
4171: PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4172: if (!n) {
4173: prev = rnorm;
4174: PetscCall(PetscDrawLGReset(lg));
4175: }
4176: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4177: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4178: x = (PetscReal)n;
4179: y = (prev - rnorm) / prev;
4180: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4181: if (n < 20 || !(n % 5) || snes->reason) {
4182: PetscCall(PetscDrawLGDraw(lg));
4183: PetscCall(PetscDrawLGSave(lg));
4184: }
4186: PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4187: if (!n) PetscCall(PetscDrawLGReset(lg));
4188: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4189: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4190: x = (PetscReal)n;
4191: y = (prev - rnorm) / (prev * per);
4192: if (n > 2) { /*skip initial crazy value */
4193: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4194: }
4195: if (n < 20 || !(n % 5) || snes->reason) {
4196: PetscCall(PetscDrawLGDraw(lg));
4197: PetscCall(PetscDrawLGSave(lg));
4198: }
4199: prev = rnorm;
4200: PetscFunctionReturn(PETSC_SUCCESS);
4201: }
4203: /*@
4204: SNESConverged - Run the convergence test and update the `SNESConvergedReason`.
4206: Collective
4208: Input Parameters:
4209: + snes - the `SNES` context
4210: . it - current iteration
4211: . xnorm - 2-norm of current iterate
4212: . snorm - 2-norm of current step
4213: - fnorm - 2-norm of function
4215: Level: developer
4217: Note:
4218: This routine is called by the `SNESSolve()` implementations.
4219: It does not typically need to be called by the user.
4221: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4222: @*/
4223: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4224: {
4225: PetscFunctionBegin;
4226: if (!snes->reason) {
4227: if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4228: if (it == snes->max_its && !snes->reason) {
4229: if (snes->normschedule == SNES_NORM_ALWAYS) {
4230: PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4231: snes->reason = SNES_DIVERGED_MAX_IT;
4232: } else snes->reason = SNES_CONVERGED_ITS;
4233: }
4234: }
4235: PetscFunctionReturn(PETSC_SUCCESS);
4236: }
4238: /*@
4239: SNESMonitor - runs any `SNES` monitor routines provided with `SNESMonitor()` or the options database
4241: Collective
4243: Input Parameters:
4244: + snes - nonlinear solver context obtained from `SNESCreate()`
4245: . iter - current iteration number
4246: - rnorm - current relative norm of the residual
4248: Level: developer
4250: Note:
4251: This routine is called by the `SNESSolve()` implementations.
4252: It does not typically need to be called by the user.
4254: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4255: @*/
4256: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4257: {
4258: PetscInt i, n = snes->numbermonitors;
4260: PetscFunctionBegin;
4261: PetscCall(VecLockReadPush(snes->vec_sol));
4262: for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4263: PetscCall(VecLockReadPop(snes->vec_sol));
4264: PetscFunctionReturn(PETSC_SUCCESS);
4265: }
4267: /* ------------ Routines to set performance monitoring options ----------- */
4269: /*MC
4270: SNESMonitorFunction - functional form passed to `SNESMonitorSet()` to monitor convergence of nonlinear solver
4272: Synopsis:
4273: #include <petscsnes.h>
4274: PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)
4276: Collective
4278: Input Parameters:
4279: + snes - the `SNES` context
4280: . its - iteration number
4281: . norm - 2-norm function value (may be estimated)
4282: - mctx - [optional] monitoring context
4284: Level: advanced
4286: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4287: M*/
4289: /*@C
4290: SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4291: iteration of the `SNES` nonlinear solver to display the iteration's
4292: progress.
4294: Logically Collective
4296: Input Parameters:
4297: + snes - the `SNES` context
4298: . f - the monitor function, for the calling sequence see `SNESMonitorFunction`
4299: . mctx - [optional] user-defined context for private data for the monitor routine (use `NULL` if no context is desired)
4300: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4302: Calling sequence of f:
4303: + snes - the `SNES` object
4304: . it - the current iteration
4305: . rnorm - norm of the residual
4306: - mctx - the optional monitor context
4308: Options Database Keys:
4309: + -snes_monitor - sets `SNESMonitorDefault()`
4310: . -snes_monitor draw::draw_lg - sets line graph monitor
4311: - -snes_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `SNESMonitorSet()`, but does not cancel those set via
4312: the options database.
4314: Level: intermediate
4316: Note:
4317: Several different monitoring routines may be set by calling
4318: `SNESMonitorSet()` multiple times; all will be called in the
4319: order in which they were set.
4321: Fortran Note:
4322: Only a single monitor function can be set for each `SNES` object
4324: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4325: @*/
4326: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4327: {
4328: PetscFunctionBegin;
4330: for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4331: PetscBool identical;
4333: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4334: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4335: }
4336: PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4337: snes->monitor[snes->numbermonitors] = f;
4338: snes->monitordestroy[snes->numbermonitors] = monitordestroy;
4339: snes->monitorcontext[snes->numbermonitors++] = mctx;
4340: PetscFunctionReturn(PETSC_SUCCESS);
4341: }
4343: /*@
4344: SNESMonitorCancel - Clears all the monitor functions for a `SNES` object.
4346: Logically Collective
4348: Input Parameter:
4349: . snes - the `SNES` context
4351: Options Database Key:
4352: . -snes_monitor_cancel - cancels all monitors that have been hardwired
4353: into a code by calls to `SNESMonitorSet()`, but does not cancel those
4354: set via the options database
4356: Level: intermediate
4358: Note:
4359: There is no way to clear one specific monitor from a `SNES` object.
4361: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4362: @*/
4363: PetscErrorCode SNESMonitorCancel(SNES snes)
4364: {
4365: PetscInt i;
4367: PetscFunctionBegin;
4369: for (i = 0; i < snes->numbermonitors; i++) {
4370: if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4371: }
4372: snes->numbermonitors = 0;
4373: PetscFunctionReturn(PETSC_SUCCESS);
4374: }
4376: /*@C
4377: SNESSetConvergenceTest - Sets the function that is to be used
4378: to test for convergence of the nonlinear iterative solution.
4380: Logically Collective
4382: Input Parameters:
4383: + snes - the `SNES` context
4384: . func - routine to test for convergence
4385: . ctx - [optional] context for private data for the convergence routine (may be `NULL`)
4386: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)
4388: Calling sequence of func:
4389: + snes - the `SNES` context
4390: . it - the current iteration number
4391: . xnorm - the norm of the new solution
4392: . snorm - the norm of the step
4393: . fnorm - the norm of the function value
4394: . reason - output, the reason convergence or divergence as declared
4395: - ctx - the optional convergence test context
4397: Level: advanced
4399: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4400: @*/
4401: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4402: {
4403: PetscFunctionBegin;
4405: if (!func) func = SNESConvergedSkip;
4406: if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4407: snes->ops->converged = func;
4408: snes->ops->convergeddestroy = destroy;
4409: snes->cnvP = ctx;
4410: PetscFunctionReturn(PETSC_SUCCESS);
4411: }
4413: /*@
4414: SNESGetConvergedReason - Gets the reason the `SNES` iteration was stopped, which may be due to convergence, divergence, or stagnation
4416: Not Collective
4418: Input Parameter:
4419: . snes - the `SNES` context
4421: Output Parameter:
4422: . reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` for the individual convergence tests for complete lists
4424: Options Database Key:
4425: . -snes_converged_reason - prints the reason to standard out
4427: Level: intermediate
4429: Note:
4430: Should only be called after the call the `SNESSolve()` is complete, if it is called earlier it returns the value `SNES__CONVERGED_ITERATING`.
4432: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4433: @*/
4434: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4435: {
4436: PetscFunctionBegin;
4438: PetscAssertPointer(reason, 2);
4439: *reason = snes->reason;
4440: PetscFunctionReturn(PETSC_SUCCESS);
4441: }
4443: /*@C
4444: SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`
4446: Not Collective
4448: Input Parameter:
4449: . snes - the `SNES` context
4451: Output Parameter:
4452: . strreason - a human readable string that describes `SNES` converged reason
4454: Level: beginner
4456: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4457: @*/
4458: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char **strreason)
4459: {
4460: PetscFunctionBegin;
4462: PetscAssertPointer(strreason, 2);
4463: *strreason = SNESConvergedReasons[snes->reason];
4464: PetscFunctionReturn(PETSC_SUCCESS);
4465: }
4467: /*@
4468: SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.
4470: Not Collective
4472: Input Parameters:
4473: + snes - the `SNES` context
4474: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4475: manual pages for the individual convergence tests for complete lists
4477: Level: developer
4479: Developer Note:
4480: Called inside the various `SNESSolve()` implementations
4482: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4483: @*/
4484: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4485: {
4486: PetscFunctionBegin;
4488: PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4489: snes->reason = reason;
4490: PetscFunctionReturn(PETSC_SUCCESS);
4491: }
4493: /*@
4494: SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.
4496: Logically Collective
4498: Input Parameters:
4499: + snes - iterative context obtained from `SNESCreate()`
4500: . a - array to hold history, this array will contain the function norms computed at each step
4501: . its - integer array holds the number of linear iterations for each solve.
4502: . na - size of `a` and `its`
4503: - reset - `PETSC_TRUE` indicates each new nonlinear solve resets the history counter to zero,
4504: else it continues storing new values for new nonlinear solves after the old ones
4506: Level: intermediate
4508: Notes:
4509: If 'a' and 'its' are `NULL` then space is allocated for the history. If 'na' is `PETSC_DECIDE` (or, deprecated, `PETSC_DEFAULT`) then a
4510: default array of length 1,000 is allocated.
4512: This routine is useful, e.g., when running a code for purposes
4513: of accurate performance monitoring, when no I/O should be done
4514: during the section of code that is being timed.
4516: If the arrays run out of space after a number of iterations then the later values are not saved in the history
4518: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4519: @*/
4520: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4521: {
4522: PetscFunctionBegin;
4524: if (a) PetscAssertPointer(a, 2);
4525: if (its) PetscAssertPointer(its, 3);
4526: if (!a) {
4527: if (na == PETSC_DECIDE) na = 1000;
4528: PetscCall(PetscCalloc2(na, &a, na, &its));
4529: snes->conv_hist_alloc = PETSC_TRUE;
4530: }
4531: snes->conv_hist = a;
4532: snes->conv_hist_its = its;
4533: snes->conv_hist_max = (size_t)na;
4534: snes->conv_hist_len = 0;
4535: snes->conv_hist_reset = reset;
4536: PetscFunctionReturn(PETSC_SUCCESS);
4537: }
4539: #if defined(PETSC_HAVE_MATLAB)
4540: #include <engine.h> /* MATLAB include file */
4541: #include <mex.h> /* MATLAB include file */
4543: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4544: {
4545: mxArray *mat;
4546: PetscInt i;
4547: PetscReal *ar;
4549: mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4550: ar = (PetscReal *)mxGetData(mat);
4551: for (i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4552: return mat;
4553: }
4554: #endif
4556: /*@C
4557: SNESGetConvergenceHistory - Gets the arrays used to hold the convergence history.
4559: Not Collective
4561: Input Parameter:
4562: . snes - iterative context obtained from `SNESCreate()`
4564: Output Parameters:
4565: + a - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4566: . its - integer array holds the number of linear iterations (or
4567: negative if not converged) for each solve.
4568: - na - size of `a` and `its`
4570: Level: intermediate
4572: Note:
4573: This routine is useful, e.g., when running a code for purposes
4574: of accurate performance monitoring, when no I/O should be done
4575: during the section of code that is being timed.
4577: Fortran Notes:
4578: Return the arrays with ``SNESRestoreConvergenceHistory()`
4580: Use the arguments
4581: .vb
4582: PetscReal, pointer :: a(:)
4583: PetscInt, pointer :: its(:)
4584: .ve
4586: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4587: @*/
4588: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4589: {
4590: PetscFunctionBegin;
4592: if (a) *a = snes->conv_hist;
4593: if (its) *its = snes->conv_hist_its;
4594: if (na) *na = (PetscInt)snes->conv_hist_len;
4595: PetscFunctionReturn(PETSC_SUCCESS);
4596: }
4598: /*@C
4599: SNESSetUpdate - Sets the general-purpose update function called
4600: at the beginning of every iteration of the nonlinear solve. Specifically
4601: it is called just before the Jacobian is "evaluated" and after the function
4602: evaluation.
4604: Logically Collective
4606: Input Parameters:
4607: + snes - The nonlinear solver context
4608: - func - The update function; for calling sequence see `SNESUpdateFn`
4610: Level: advanced
4612: Notes:
4613: 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
4614: to `SNESSetFunction()`, or `SNESSetPicard()`
4615: This is not used by most users, and it is intended to provide a general hook that is run
4616: right before the direction step is computed.
4618: Users are free to modify the current residual vector,
4619: the current linearization point, or any other vector associated to the specific solver used.
4620: If such modifications take place, it is the user responsibility to update all the relevant
4621: vectors. For example, if one is adjusting the model parameters at each Newton step their code may look like
4622: .vb
4623: PetscErrorCode update(SNES snes, PetscInt iteration)
4624: {
4625: PetscFunctionBeginUser;
4626: if (iteration > 0) {
4627: // update the model parameters here
4628: Vec x,f;
4629: PetscCall(SNESGetSolution(snes,&x));
4630: PetcCall(SNESGetFunction(snes,&f,NULL,NULL));
4631: PetscCall(SNESComputeFunction(snes,x,f));
4632: }
4633: PetscFunctionReturn(PETSC_SUCCESS);
4634: }
4635: .ve
4637: 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.
4639: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4640: `SNESMonitorSet()`
4641: @*/
4642: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4643: {
4644: PetscFunctionBegin;
4646: snes->ops->update = func;
4647: PetscFunctionReturn(PETSC_SUCCESS);
4648: }
4650: /*@
4651: SNESConvergedReasonView - Displays the reason a `SNES` solve converged or diverged to a viewer
4653: Collective
4655: Input Parameters:
4656: + snes - iterative context obtained from `SNESCreate()`
4657: - viewer - the viewer to display the reason
4659: Options Database Keys:
4660: + -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4661: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4663: Level: beginner
4665: Note:
4666: To change the format of the output call `PetscViewerPushFormat`(viewer,format) before this call. Use `PETSC_VIEWER_DEFAULT` for the default,
4667: use `PETSC_VIEWER_FAILED` to only display a reason if it fails.
4669: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4670: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4671: `SNESConvergedReasonViewFromOptions()`,
4672: `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4673: @*/
4674: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4675: {
4676: PetscViewerFormat format;
4677: PetscBool isAscii;
4679: PetscFunctionBegin;
4680: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4681: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4682: if (isAscii) {
4683: PetscCall(PetscViewerGetFormat(viewer, &format));
4684: PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4685: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4686: DM dm;
4687: Vec u;
4688: PetscDS prob;
4689: PetscInt Nf, f;
4690: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4691: void **exactCtx;
4692: PetscReal error;
4694: PetscCall(SNESGetDM(snes, &dm));
4695: PetscCall(SNESGetSolution(snes, &u));
4696: PetscCall(DMGetDS(dm, &prob));
4697: PetscCall(PetscDSGetNumFields(prob, &Nf));
4698: PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4699: for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4700: PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4701: PetscCall(PetscFree2(exactSol, exactCtx));
4702: if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4703: else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4704: }
4705: if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4706: if (((PetscObject)snes)->prefix) {
4707: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4708: } else {
4709: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4710: }
4711: } else if (snes->reason <= 0) {
4712: if (((PetscObject)snes)->prefix) {
4713: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4714: } else {
4715: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4716: }
4717: }
4718: PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)snes)->tablevel + 1));
4719: }
4720: PetscFunctionReturn(PETSC_SUCCESS);
4721: }
4723: /*@C
4724: SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4725: end of the nonlinear solver to display the convergence reason of the nonlinear solver.
4727: Logically Collective
4729: Input Parameters:
4730: + snes - the `SNES` context
4731: . f - the `SNESConvergedReason` view function
4732: . vctx - [optional] user-defined context for private data for the `SNESConvergedReason` view function (use `NULL` if no context is desired)
4733: - reasonviewdestroy - [optional] routine that frees the context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4735: Calling sequence of `f`:
4736: + snes - the `SNES` context
4737: - vctx - [optional] context for private data for the function
4739: Options Database Keys:
4740: + -snes_converged_reason - sets a default `SNESConvergedReasonView()`
4741: - -snes_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
4742: calls to `SNESConvergedReasonViewSet()`, but does not cancel those set via the options database.
4744: Level: intermediate
4746: Note:
4747: Several different converged reason view routines may be set by calling
4748: `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4749: order in which they were set.
4751: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4752: `PetscCtxDestroyFn`
4753: @*/
4754: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4755: {
4756: PetscFunctionBegin;
4758: for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4759: PetscBool identical;
4761: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4762: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4763: }
4764: PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4765: snes->reasonview[snes->numberreasonviews] = f;
4766: snes->reasonviewdestroy[snes->numberreasonviews] = reasonviewdestroy;
4767: snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4768: PetscFunctionReturn(PETSC_SUCCESS);
4769: }
4771: /*@
4772: SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a `SNESConvergedReason` is to be viewed at the end of `SNESSolve()`
4773: All the user-provided viewer routines set with `SNESConvergedReasonViewSet()` will be called, if they exist.
4775: Collective
4777: Input Parameter:
4778: . snes - the `SNES` object
4780: Level: advanced
4782: Note:
4783: This function has a different API and behavior than `PetscObjectViewFromOptions()`
4785: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4786: `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4787: @*/
4788: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4789: {
4790: static PetscBool incall = PETSC_FALSE;
4792: PetscFunctionBegin;
4793: if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4794: incall = PETSC_TRUE;
4796: /* All user-provided viewers are called first, if they exist. */
4797: for (PetscInt i = 0; i < snes->numberreasonviews; i++) PetscCall((*snes->reasonview[i])(snes, snes->reasonviewcontext[i]));
4799: /* Call PETSc default routine if users ask for it */
4800: if (snes->convergedreasonviewer) {
4801: PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4802: PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4803: PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4804: }
4805: incall = PETSC_FALSE;
4806: PetscFunctionReturn(PETSC_SUCCESS);
4807: }
4809: /*@
4810: SNESSolve - Solves a nonlinear system $F(x) = b $ associated with a `SNES` object
4812: Collective
4814: Input Parameters:
4815: + snes - the `SNES` context
4816: . b - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4817: - x - the solution vector.
4819: Level: beginner
4821: Note:
4822: The user should initialize the vector, `x`, with the initial guess
4823: for the nonlinear solve prior to calling `SNESSolve()` .
4825: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4826: `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4827: `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4828: @*/
4829: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4830: {
4831: PetscBool flg;
4832: PetscInt grid;
4833: Vec xcreated = NULL;
4834: DM dm;
4836: PetscFunctionBegin;
4839: if (x) PetscCheckSameComm(snes, 1, x, 3);
4841: if (b) PetscCheckSameComm(snes, 1, b, 2);
4843: /* High level operations using the nonlinear solver */
4844: {
4845: PetscViewer viewer;
4846: PetscViewerFormat format;
4847: PetscInt num;
4848: PetscBool flg;
4849: static PetscBool incall = PETSC_FALSE;
4851: if (!incall) {
4852: /* Estimate the convergence rate of the discretization */
4853: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4854: if (flg) {
4855: PetscConvEst conv;
4856: DM dm;
4857: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4858: PetscInt Nf;
4860: incall = PETSC_TRUE;
4861: PetscCall(SNESGetDM(snes, &dm));
4862: PetscCall(DMGetNumFields(dm, &Nf));
4863: PetscCall(PetscCalloc1(Nf, &alpha));
4864: PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4865: PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4866: PetscCall(PetscConvEstSetFromOptions(conv));
4867: PetscCall(PetscConvEstSetUp(conv));
4868: PetscCall(PetscConvEstGetConvRate(conv, alpha));
4869: PetscCall(PetscViewerPushFormat(viewer, format));
4870: PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4871: PetscCall(PetscViewerPopFormat(viewer));
4872: PetscCall(PetscViewerDestroy(&viewer));
4873: PetscCall(PetscConvEstDestroy(&conv));
4874: PetscCall(PetscFree(alpha));
4875: incall = PETSC_FALSE;
4876: }
4877: /* Adaptively refine the initial grid */
4878: num = 1;
4879: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4880: if (flg) {
4881: DMAdaptor adaptor;
4883: incall = PETSC_TRUE;
4884: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4885: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4886: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4887: PetscCall(DMAdaptorSetFromOptions(adaptor));
4888: PetscCall(DMAdaptorSetUp(adaptor));
4889: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4890: PetscCall(DMAdaptorDestroy(&adaptor));
4891: incall = PETSC_FALSE;
4892: }
4893: /* Use grid sequencing to adapt */
4894: num = 0;
4895: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4896: if (num) {
4897: DMAdaptor adaptor;
4898: const char *prefix;
4900: incall = PETSC_TRUE;
4901: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4902: PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4903: PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4904: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4905: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4906: PetscCall(DMAdaptorSetFromOptions(adaptor));
4907: PetscCall(DMAdaptorSetUp(adaptor));
4908: PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4909: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4910: PetscCall(DMAdaptorDestroy(&adaptor));
4911: incall = PETSC_FALSE;
4912: }
4913: }
4914: }
4915: if (!x) x = snes->vec_sol;
4916: if (!x) {
4917: PetscCall(SNESGetDM(snes, &dm));
4918: PetscCall(DMCreateGlobalVector(dm, &xcreated));
4919: x = xcreated;
4920: }
4921: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));
4923: for (grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4924: for (grid = 0; grid < snes->gridsequence + 1; grid++) {
4925: /* set solution vector */
4926: if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4927: PetscCall(VecDestroy(&snes->vec_sol));
4928: snes->vec_sol = x;
4929: PetscCall(SNESGetDM(snes, &dm));
4931: /* set affine vector if provided */
4932: PetscCall(PetscObjectReference((PetscObject)b));
4933: PetscCall(VecDestroy(&snes->vec_rhs));
4934: snes->vec_rhs = b;
4936: 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");
4937: PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
4938: PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
4939: if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
4940: PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
4941: PetscCall(SNESSetUp(snes));
4943: if (!grid) {
4944: if (snes->ops->computeinitialguess) PetscCallBack("SNES callback compute initial guess", (*snes->ops->computeinitialguess)(snes, snes->vec_sol, snes->initialguessP));
4945: }
4947: if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4948: PetscCall(SNESResetCounters(snes));
4949: snes->reason = SNES_CONVERGED_ITERATING;
4950: PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
4951: PetscUseTypeMethod(snes, solve);
4952: PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
4953: PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
4954: snes->functiondomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4955: snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4956: snes->jacobiandomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4958: if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4959: if (snes->lagpre_persist) snes->pre_iter += snes->iter;
4961: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_test_local_min", NULL, NULL, &flg));
4962: if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
4963: /* Call converged reason views. This may involve user-provided viewers as well */
4964: PetscCall(SNESConvergedReasonViewFromOptions(snes));
4966: if (snes->errorifnotconverged) {
4967: if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
4968: PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
4969: }
4970: if (snes->reason < 0) break;
4971: if (grid < snes->gridsequence) {
4972: DM fine;
4973: Vec xnew;
4974: Mat interp;
4976: PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
4977: PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
4978: PetscCall(DMGetCoordinatesLocalSetUp(fine));
4979: PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
4980: PetscCall(DMCreateGlobalVector(fine, &xnew));
4981: PetscCall(MatInterpolate(interp, x, xnew));
4982: PetscCall(DMInterpolate(snes->dm, interp, fine));
4983: PetscCall(MatDestroy(&interp));
4984: x = xnew;
4986: PetscCall(SNESReset(snes));
4987: PetscCall(SNESSetDM(snes, fine));
4988: PetscCall(SNESResetFromOptions(snes));
4989: PetscCall(DMDestroy(&fine));
4990: PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4991: }
4992: }
4993: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
4994: PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
4995: PetscCall(DMMonitor(snes->dm));
4996: PetscCall(SNESMonitorPauseFinal_Internal(snes));
4998: PetscCall(VecDestroy(&xcreated));
4999: PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
5000: PetscFunctionReturn(PETSC_SUCCESS);
5001: }
5003: /* --------- Internal routines for SNES Package --------- */
5005: /*@
5006: SNESSetType - Sets the algorithm/method to be used to solve the nonlinear system with the given `SNES`
5008: Collective
5010: Input Parameters:
5011: + snes - the `SNES` context
5012: - type - a known method
5014: Options Database Key:
5015: . -snes_type type - Sets the method; see `SNESType`
5017: Level: intermediate
5019: Notes:
5020: See `SNESType` for available methods (for instance)
5021: + `SNESNEWTONLS` - Newton's method with line search
5022: (systems of nonlinear equations)
5023: - `SNESNEWTONTR` - Newton's method with trust region
5024: (systems of nonlinear equations)
5026: Normally, it is best to use the `SNESSetFromOptions()` command and then
5027: set the `SNES` solver type from the options database rather than by using
5028: this routine. Using the options database provides the user with
5029: maximum flexibility in evaluating the many nonlinear solvers.
5030: The `SNESSetType()` routine is provided for those situations where it
5031: is necessary to set the nonlinear solver independently of the command
5032: line or options database. This might be the case, for example, when
5033: the choice of solver changes during the execution of the program,
5034: and the user's application is taking responsibility for choosing the
5035: appropriate method.
5037: Developer Note:
5038: `SNESRegister()` adds a constructor for a new `SNESType` to `SNESList`, `SNESSetType()` locates
5039: the constructor in that list and calls it to create the specific object.
5041: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
5042: @*/
5043: PetscErrorCode SNESSetType(SNES snes, SNESType type)
5044: {
5045: PetscBool match;
5046: PetscErrorCode (*r)(SNES);
5048: PetscFunctionBegin;
5050: PetscAssertPointer(type, 2);
5052: PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
5053: if (match) PetscFunctionReturn(PETSC_SUCCESS);
5055: PetscCall(PetscFunctionListFind(SNESList, type, &r));
5056: PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
5057: /* Destroy the previous private SNES context */
5058: PetscTryTypeMethod(snes, destroy);
5059: /* Reinitialize type-specific function pointers in SNESOps structure */
5060: snes->ops->reset = NULL;
5061: snes->ops->setup = NULL;
5062: snes->ops->solve = NULL;
5063: snes->ops->view = NULL;
5064: snes->ops->setfromoptions = NULL;
5065: snes->ops->destroy = NULL;
5067: /* It may happen the user has customized the line search before calling SNESSetType */
5068: if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));
5070: /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
5071: snes->setupcalled = PETSC_FALSE;
5073: PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
5074: PetscCall((*r)(snes));
5075: PetscFunctionReturn(PETSC_SUCCESS);
5076: }
5078: /*@
5079: SNESGetType - Gets the `SNES` method type and name (as a string).
5081: Not Collective
5083: Input Parameter:
5084: . snes - nonlinear solver context
5086: Output Parameter:
5087: . type - `SNES` method (a character string)
5089: Level: intermediate
5091: Note:
5092: `type` should not be retained for later use as it will be an invalid pointer if the `SNESType` of `snes` is changed.
5094: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
5095: @*/
5096: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5097: {
5098: PetscFunctionBegin;
5100: PetscAssertPointer(type, 2);
5101: *type = ((PetscObject)snes)->type_name;
5102: PetscFunctionReturn(PETSC_SUCCESS);
5103: }
5105: /*@
5106: SNESSetSolution - Sets the solution vector for use by the `SNES` routines.
5108: Logically Collective
5110: Input Parameters:
5111: + snes - the `SNES` context obtained from `SNESCreate()`
5112: - u - the solution vector
5114: Level: beginner
5116: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5117: @*/
5118: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5119: {
5120: DM dm;
5122: PetscFunctionBegin;
5125: PetscCall(PetscObjectReference((PetscObject)u));
5126: PetscCall(VecDestroy(&snes->vec_sol));
5128: snes->vec_sol = u;
5130: PetscCall(SNESGetDM(snes, &dm));
5131: PetscCall(DMShellSetGlobalVector(dm, u));
5132: PetscFunctionReturn(PETSC_SUCCESS);
5133: }
5135: /*@
5136: SNESGetSolution - Returns the vector where the approximate solution is
5137: stored. This is the fine grid solution when using `SNESSetGridSequence()`.
5139: Not Collective, but `x` is parallel if `snes` is parallel
5141: Input Parameter:
5142: . snes - the `SNES` context
5144: Output Parameter:
5145: . x - the solution
5147: Level: intermediate
5149: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5150: @*/
5151: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5152: {
5153: PetscFunctionBegin;
5155: PetscAssertPointer(x, 2);
5156: *x = snes->vec_sol;
5157: PetscFunctionReturn(PETSC_SUCCESS);
5158: }
5160: /*@
5161: SNESGetSolutionUpdate - Returns the vector where the solution update is
5162: stored.
5164: Not Collective, but `x` is parallel if `snes` is parallel
5166: Input Parameter:
5167: . snes - the `SNES` context
5169: Output Parameter:
5170: . x - the solution update
5172: Level: advanced
5174: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5175: @*/
5176: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5177: {
5178: PetscFunctionBegin;
5180: PetscAssertPointer(x, 2);
5181: *x = snes->vec_sol_update;
5182: PetscFunctionReturn(PETSC_SUCCESS);
5183: }
5185: /*@C
5186: SNESGetFunction - Returns the function that defines the nonlinear system set with `SNESSetFunction()`
5188: Not Collective, but `r` is parallel if `snes` is parallel. Collective if `r` is requested, but has not been created yet.
5190: Input Parameter:
5191: . snes - the `SNES` context
5193: Output Parameters:
5194: + r - the vector that is used to store residuals (or `NULL` if you don't want it)
5195: . f - the function (or `NULL` if you don't want it); for calling sequence see `SNESFunctionFn`
5196: - ctx - the function context (or `NULL` if you don't want it)
5198: Level: advanced
5200: Note:
5201: The vector `r` DOES NOT, in general, contain the current value of the `SNES` nonlinear function
5203: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5204: @*/
5205: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5206: {
5207: DM dm;
5209: PetscFunctionBegin;
5211: if (r) {
5212: if (!snes->vec_func) {
5213: if (snes->vec_rhs) {
5214: PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5215: } else if (snes->vec_sol) {
5216: PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5217: } else if (snes->dm) {
5218: PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5219: }
5220: }
5221: *r = snes->vec_func;
5222: }
5223: PetscCall(SNESGetDM(snes, &dm));
5224: PetscCall(DMSNESGetFunction(dm, f, ctx));
5225: PetscFunctionReturn(PETSC_SUCCESS);
5226: }
5228: /*@C
5229: SNESGetNGS - Returns the function and context set with `SNESSetNGS()`
5231: Input Parameter:
5232: . snes - the `SNES` context
5234: Output Parameters:
5235: + f - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5236: - ctx - the function context (or `NULL`)
5238: Level: advanced
5240: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5241: @*/
5242: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5243: {
5244: DM dm;
5246: PetscFunctionBegin;
5248: PetscCall(SNESGetDM(snes, &dm));
5249: PetscCall(DMSNESGetNGS(dm, f, ctx));
5250: PetscFunctionReturn(PETSC_SUCCESS);
5251: }
5253: /*@
5254: SNESSetOptionsPrefix - Sets the prefix used for searching for all
5255: `SNES` options in the database.
5257: Logically Collective
5259: Input Parameters:
5260: + snes - the `SNES` context
5261: - prefix - the prefix to prepend to all option names
5263: Level: advanced
5265: Note:
5266: A hyphen (-) must NOT be given at the beginning of the prefix name.
5267: The first character of all runtime options is AUTOMATICALLY the hyphen.
5269: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5270: @*/
5271: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5272: {
5273: PetscFunctionBegin;
5275: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5276: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5277: if (snes->linesearch) {
5278: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5279: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5280: }
5281: PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5282: PetscFunctionReturn(PETSC_SUCCESS);
5283: }
5285: /*@
5286: SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5287: `SNES` options in the database.
5289: Logically Collective
5291: Input Parameters:
5292: + snes - the `SNES` context
5293: - prefix - the prefix to prepend to all option names
5295: Level: advanced
5297: Note:
5298: A hyphen (-) must NOT be given at the beginning of the prefix name.
5299: The first character of all runtime options is AUTOMATICALLY the hyphen.
5301: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5302: @*/
5303: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5304: {
5305: PetscFunctionBegin;
5307: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5308: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5309: if (snes->linesearch) {
5310: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5311: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5312: }
5313: PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5314: PetscFunctionReturn(PETSC_SUCCESS);
5315: }
5317: /*@
5318: SNESGetOptionsPrefix - Gets the prefix used for searching for all
5319: `SNES` options in the database.
5321: Not Collective
5323: Input Parameter:
5324: . snes - the `SNES` context
5326: Output Parameter:
5327: . prefix - pointer to the prefix string used
5329: Level: advanced
5331: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5332: @*/
5333: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5334: {
5335: PetscFunctionBegin;
5337: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5338: PetscFunctionReturn(PETSC_SUCCESS);
5339: }
5341: /*@C
5342: SNESRegister - Adds a method to the nonlinear solver package.
5344: Not Collective
5346: Input Parameters:
5347: + sname - name of a new user-defined solver
5348: - function - routine to create method context
5350: Level: advanced
5352: Note:
5353: `SNESRegister()` may be called multiple times to add several user-defined solvers.
5355: Example Usage:
5356: .vb
5357: SNESRegister("my_solver", MySolverCreate);
5358: .ve
5360: Then, your solver can be chosen with the procedural interface via
5361: .vb
5362: SNESSetType(snes, "my_solver")
5363: .ve
5364: or at runtime via the option
5365: .vb
5366: -snes_type my_solver
5367: .ve
5369: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5370: @*/
5371: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5372: {
5373: PetscFunctionBegin;
5374: PetscCall(SNESInitializePackage());
5375: PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5376: PetscFunctionReturn(PETSC_SUCCESS);
5377: }
5379: /*@
5380: SNESTestLocalMin - Diagnostic that probes each entry of the current `SNES` solution to check whether the residual norm has a local minimum along the coordinate directions
5382: Collective
5384: Input Parameter:
5385: . snes - the `SNES` context
5387: Level: developer
5389: Note:
5390: Currently intended for serial runs. For each degree of freedom it perturbs the solution by increasing amounts and prints the resulting `SNESComputeFunction()` residual norms so the user can inspect local behavior.
5392: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESComputeFunction()`
5393: @*/
5394: PetscErrorCode SNESTestLocalMin(SNES snes)
5395: {
5396: PetscInt N, i, j;
5397: Vec u, uh, fh;
5398: PetscScalar value;
5399: PetscReal norm;
5401: PetscFunctionBegin;
5402: PetscCall(SNESGetSolution(snes, &u));
5403: PetscCall(VecDuplicate(u, &uh));
5404: PetscCall(VecDuplicate(u, &fh));
5406: /* currently only works for sequential */
5407: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5408: PetscCall(VecGetSize(u, &N));
5409: for (i = 0; i < N; i++) {
5410: PetscCall(VecCopy(u, uh));
5411: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5412: for (j = -10; j < 11; j++) {
5413: value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5414: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5415: PetscCall(SNESComputeFunction(snes, uh, fh));
5416: PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5417: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), " j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5418: value = -value;
5419: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5420: }
5421: }
5422: PetscCall(VecDestroy(&uh));
5423: PetscCall(VecDestroy(&fh));
5424: PetscFunctionReturn(PETSC_SUCCESS);
5425: }
5427: /*@
5428: SNESGetLineSearch - Returns the line search associated with the `SNES`.
5430: Not Collective
5432: Input Parameter:
5433: . snes - iterative context obtained from `SNESCreate()`
5435: Output Parameter:
5436: . linesearch - linesearch context
5438: Level: beginner
5440: Notes:
5441: It creates a default line search instance which can be configured as needed in case it has not been already set with `SNESSetLineSearch()`.
5443: You can also use the options database keys `-snes_linesearch_*` to configure the line search. See `SNESLineSearchSetFromOptions()` for the possible options.
5445: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5446: @*/
5447: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5448: {
5449: const char *optionsprefix;
5451: PetscFunctionBegin;
5453: PetscAssertPointer(linesearch, 2);
5454: if (!snes->linesearch) {
5455: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5456: PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5457: PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5458: PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5459: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5460: }
5461: *linesearch = snes->linesearch;
5462: PetscFunctionReturn(PETSC_SUCCESS);
5463: }
5465: /*@
5466: SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5467: computing relative tolerance for linear solvers within an inexact
5468: Newton method.
5470: Logically Collective
5472: Input Parameters:
5473: + snes - `SNES` context
5474: - flag - `PETSC_TRUE` or `PETSC_FALSE`
5476: Options Database Keys:
5477: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5478: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
5479: . -snes_ksp_ew_rtol0 rtol0 - Sets rtol0
5480: . -snes_ksp_ew_rtolmax rtolmax - Sets rtolmax
5481: . -snes_ksp_ew_gamma gamma - Sets gamma
5482: . -snes_ksp_ew_alpha alpha - Sets alpha
5483: . -snes_ksp_ew_alpha2 alpha2 - Sets alpha2
5484: - -snes_ksp_ew_threshold threshold - Sets threshold
5486: Level: advanced
5488: Note:
5489: The default is to use a constant relative tolerance for
5490: the inner linear solvers. Alternatively, one can use the
5491: Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5492: is reset at each Newton iteration according progress of the nonlinear
5493: solver.
5495: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5496: @*/
5497: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5498: {
5499: PetscFunctionBegin;
5502: snes->ksp_ewconv = flag;
5503: PetscFunctionReturn(PETSC_SUCCESS);
5504: }
5506: /*@
5507: SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5508: for computing relative tolerance for linear solvers within an
5509: inexact Newton method.
5511: Not Collective
5513: Input Parameter:
5514: . snes - `SNES` context
5516: Output Parameter:
5517: . flag - `PETSC_TRUE` or `PETSC_FALSE`
5519: Level: advanced
5521: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5522: @*/
5523: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5524: {
5525: PetscFunctionBegin;
5527: PetscAssertPointer(flag, 2);
5528: *flag = snes->ksp_ewconv;
5529: PetscFunctionReturn(PETSC_SUCCESS);
5530: }
5532: /*@
5533: SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5534: convergence criteria for the linear solvers within an inexact
5535: Newton method.
5537: Logically Collective
5539: Input Parameters:
5540: + snes - `SNES` context
5541: . version - version 1, 2 (default is 2), 3 or 4
5542: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5543: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5544: . gamma - multiplicative factor for version 2 rtol computation
5545: (0 <= gamma2 <= 1)
5546: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5547: . alpha2 - power for safeguard
5548: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5550: Level: advanced
5552: Notes:
5553: Version 3 was contributed by Luis Chacon, June 2006.
5555: Use `PETSC_CURRENT` to retain the default for any of the parameters.
5557: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5558: @*/
5559: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5560: {
5561: SNESKSPEW *kctx;
5563: PetscFunctionBegin;
5565: kctx = (SNESKSPEW *)snes->kspconvctx;
5566: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5575: if (version != PETSC_CURRENT) kctx->version = version;
5576: if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5577: if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5578: if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5579: if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5580: if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5581: if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;
5583: 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);
5584: 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);
5585: 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);
5586: 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);
5587: 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);
5588: 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);
5589: PetscFunctionReturn(PETSC_SUCCESS);
5590: }
5592: /*@
5593: SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5594: convergence criteria for the linear solvers within an inexact
5595: Newton method.
5597: Not Collective
5599: Input Parameter:
5600: . snes - `SNES` context
5602: Output Parameters:
5603: + version - version 1, 2 (default is 2), 3 or 4
5604: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5605: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5606: . gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5607: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5608: . alpha2 - power for safeguard
5609: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5611: Level: advanced
5613: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5614: @*/
5615: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5616: {
5617: SNESKSPEW *kctx;
5619: PetscFunctionBegin;
5621: kctx = (SNESKSPEW *)snes->kspconvctx;
5622: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5623: if (version) *version = kctx->version;
5624: if (rtol_0) *rtol_0 = kctx->rtol_0;
5625: if (rtol_max) *rtol_max = kctx->rtol_max;
5626: if (gamma) *gamma = kctx->gamma;
5627: if (alpha) *alpha = kctx->alpha;
5628: if (alpha2) *alpha2 = kctx->alpha2;
5629: if (threshold) *threshold = kctx->threshold;
5630: PetscFunctionReturn(PETSC_SUCCESS);
5631: }
5633: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5634: {
5635: SNES snes = (SNES)ctx;
5636: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5637: PetscReal rtol = PETSC_CURRENT, stol;
5639: PetscFunctionBegin;
5640: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5641: if (!snes->iter) {
5642: rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5643: PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5644: } else {
5645: PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5646: if (kctx->version == 1) {
5647: rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5648: stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5649: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5650: } else if (kctx->version == 2) {
5651: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5652: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5653: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5654: } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5655: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5656: /* safeguard: avoid sharp decrease of rtol */
5657: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5658: stol = PetscMax(rtol, stol);
5659: rtol = PetscMin(kctx->rtol_0, stol);
5660: /* safeguard: avoid oversolving */
5661: stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5662: stol = PetscMax(rtol, stol);
5663: rtol = PetscMin(kctx->rtol_0, stol);
5664: } else /* if (kctx->version == 4) */ {
5665: /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5666: PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5667: PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5668: PetscReal rk = ared / pred;
5669: if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5670: else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5671: else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5672: else rtol = kctx->v4_m2 * kctx->rtol_last;
5674: 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;
5675: kctx->rtol_last_2 = kctx->rtol_last;
5676: kctx->rk_last_2 = kctx->rk_last;
5677: kctx->rk_last = rk;
5678: }
5679: }
5680: /* safeguard: avoid rtol greater than rtol_max */
5681: rtol = PetscMin(rtol, kctx->rtol_max);
5682: PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5683: PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5684: PetscFunctionReturn(PETSC_SUCCESS);
5685: }
5687: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5688: {
5689: SNES snes = (SNES)ctx;
5690: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5691: PCSide pcside;
5692: Vec lres;
5694: PetscFunctionBegin;
5695: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5696: PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5697: kctx->norm_last = snes->norm;
5698: if (kctx->version == 1 || kctx->version == 4) {
5699: PC pc;
5700: PetscBool getRes;
5702: PetscCall(KSPGetPC(ksp, &pc));
5703: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5704: if (!getRes) {
5705: KSPNormType normtype;
5707: PetscCall(KSPGetNormType(ksp, &normtype));
5708: getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5709: }
5710: PetscCall(KSPGetPCSide(ksp, &pcside));
5711: if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5712: PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5713: } else {
5714: /* KSP residual is preconditioned residual */
5715: /* compute true linear residual norm */
5716: Mat J;
5717: PetscCall(KSPGetOperators(ksp, &J, NULL));
5718: PetscCall(VecDuplicate(b, &lres));
5719: PetscCall(MatMult(J, x, lres));
5720: PetscCall(VecAYPX(lres, -1.0, b));
5721: PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5722: PetscCall(VecDestroy(&lres));
5723: }
5724: }
5725: PetscFunctionReturn(PETSC_SUCCESS);
5726: }
5728: /*@
5729: SNESGetKSP - Returns the `KSP` context for a `SNES` solver.
5731: Not Collective, but if `snes` is parallel, then `ksp` is parallel
5733: Input Parameter:
5734: . snes - the `SNES` context
5736: Output Parameter:
5737: . ksp - the `KSP` context
5739: Level: beginner
5741: Notes:
5742: The user can then directly manipulate the `KSP` context to set various
5743: options, etc. Likewise, the user can then extract and manipulate the
5744: `PC` contexts as well.
5746: 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.
5748: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5749: @*/
5750: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5751: {
5752: PetscFunctionBegin;
5754: PetscAssertPointer(ksp, 2);
5756: if (!snes->ksp) {
5757: PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5758: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));
5760: PetscCall(KSPSetPreSolve(snes->ksp, KSPPreSolve_SNESEW, snes));
5761: PetscCall(KSPSetPostSolve(snes->ksp, KSPPostSolve_SNESEW, snes));
5763: PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5764: PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5765: }
5766: *ksp = snes->ksp;
5767: PetscFunctionReturn(PETSC_SUCCESS);
5768: }
5770: #include <petsc/private/dmimpl.h>
5771: /*@
5772: SNESSetDM - Sets the `DM` that may be used by some `SNES` nonlinear solvers or their underlying preconditioners
5774: Logically Collective
5776: Input Parameters:
5777: + snes - the nonlinear solver context
5778: - dm - the `DM`, cannot be `NULL`
5780: Level: intermediate
5782: Note:
5783: A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
5784: even when not using interfaces like `DMSNESSetFunction()`. Use `DMClone()` to get a distinct `DM` when solving different
5785: problems using the same function space.
5787: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5788: @*/
5789: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5790: {
5791: KSP ksp;
5792: DMSNES sdm;
5794: PetscFunctionBegin;
5797: PetscCall(PetscObjectReference((PetscObject)dm));
5798: if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5799: if (snes->dm->dmsnes && !dm->dmsnes) {
5800: PetscCall(DMCopyDMSNES(snes->dm, dm));
5801: PetscCall(DMGetDMSNES(snes->dm, &sdm));
5802: if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5803: }
5804: PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5805: PetscCall(DMDestroy(&snes->dm));
5806: }
5807: snes->dm = dm;
5808: snes->dmAuto = PETSC_FALSE;
5810: PetscCall(SNESGetKSP(snes, &ksp));
5811: PetscCall(KSPSetDM(ksp, dm));
5812: PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5813: if (snes->npc) {
5814: PetscCall(SNESSetDM(snes->npc, snes->dm));
5815: PetscCall(SNESSetNPCSide(snes, snes->npcside));
5816: }
5817: PetscFunctionReturn(PETSC_SUCCESS);
5818: }
5820: /*@
5821: SNESGetDM - Gets the `DM` that may be used by some `SNES` nonlinear solvers/preconditioners
5823: Not Collective but `dm` obtained is parallel on `snes`
5825: Input Parameter:
5826: . snes - the `SNES` context
5828: Output Parameter:
5829: . dm - the `DM`
5831: Level: intermediate
5833: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5834: @*/
5835: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5836: {
5837: PetscFunctionBegin;
5839: if (!snes->dm) {
5840: PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5841: snes->dmAuto = PETSC_TRUE;
5842: }
5843: *dm = snes->dm;
5844: PetscFunctionReturn(PETSC_SUCCESS);
5845: }
5847: /*@
5848: SNESSetNPC - Sets the nonlinear preconditioner to be used.
5850: Collective
5852: Input Parameters:
5853: + snes - iterative context obtained from `SNESCreate()`
5854: - npc - the `SNES` nonlinear preconditioner object
5856: Options Database Key:
5857: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner
5859: Level: developer
5861: Notes:
5862: This is rarely used, rather use `SNESGetNPC()` to retrieve the preconditioner and configure it using the API.
5864: Only some `SNESType` can use a nonlinear preconditioner
5866: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5867: @*/
5868: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5869: {
5870: PetscFunctionBegin;
5873: PetscCheckSameComm(snes, 1, npc, 2);
5874: PetscCall(PetscObjectReference((PetscObject)npc));
5875: PetscCall(SNESDestroy(&snes->npc));
5876: snes->npc = npc;
5877: PetscFunctionReturn(PETSC_SUCCESS);
5878: }
5880: /*@
5881: SNESGetNPC - Gets a nonlinear preconditioning solver SNES` to be used to precondition the original nonlinear solver.
5883: Not Collective; but any changes to the obtained the `pc` object must be applied collectively
5885: Input Parameter:
5886: . snes - iterative context obtained from `SNESCreate()`
5888: Output Parameter:
5889: . pc - the `SNES` preconditioner context
5891: Options Database Key:
5892: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner
5894: Level: advanced
5896: Notes:
5897: If a `SNES` was previously set with `SNESSetNPC()` then that value is returned, otherwise a new `SNES` object is created that will
5898: be used as the nonlinear preconditioner for the current `SNES`.
5900: The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5901: `SNES`. These may be overwritten if needed.
5903: Use the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration of the nonlinear preconditioner
5905: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5906: @*/
5907: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5908: {
5909: const char *optionsprefix;
5911: PetscFunctionBegin;
5913: PetscAssertPointer(pc, 2);
5914: if (!snes->npc) {
5915: PetscCtx ctx;
5917: PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5918: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5919: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5920: PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5921: PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5922: if (snes->ops->ctxcompute) {
5923: PetscCall(SNESSetComputeApplicationContext(snes, snes->ops->ctxcompute, snes->ops->ctxdestroy));
5924: } else {
5925: PetscCall(SNESGetApplicationContext(snes, &ctx));
5926: PetscCall(SNESSetApplicationContext(snes->npc, ctx));
5927: }
5928: PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5929: }
5930: *pc = snes->npc;
5931: PetscFunctionReturn(PETSC_SUCCESS);
5932: }
5934: /*@
5935: SNESHasNPC - Returns whether a nonlinear preconditioner is associated with the given `SNES`
5937: Not Collective
5939: Input Parameter:
5940: . snes - iterative context obtained from `SNESCreate()`
5942: Output Parameter:
5943: . has_npc - whether the `SNES` has a nonlinear preconditioner or not
5945: Level: developer
5947: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
5948: @*/
5949: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5950: {
5951: PetscFunctionBegin;
5953: PetscAssertPointer(has_npc, 2);
5954: *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
5955: PetscFunctionReturn(PETSC_SUCCESS);
5956: }
5958: /*@
5959: SNESSetNPCSide - Sets the nonlinear preconditioning side used by the nonlinear preconditioner inside `SNES`.
5961: Logically Collective
5963: Input Parameter:
5964: . snes - iterative context obtained from `SNESCreate()`
5966: Output Parameter:
5967: . side - the preconditioning side, where side is one of
5968: .vb
5969: PC_LEFT - left preconditioning
5970: PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5971: .ve
5973: Options Database Key:
5974: . -snes_npc_side (right|left) - nonlinear preconditioner side
5976: Level: intermediate
5978: Note:
5979: `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.
5981: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
5982: @*/
5983: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
5984: {
5985: PetscFunctionBegin;
5988: if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
5989: PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
5990: snes->npcside = side;
5991: PetscFunctionReturn(PETSC_SUCCESS);
5992: }
5994: /*@
5995: SNESGetNPCSide - Gets the preconditioning side used by the nonlinear preconditioner inside `SNES`.
5997: Not Collective
5999: Input Parameter:
6000: . snes - iterative context obtained from `SNESCreate()`
6002: Output Parameter:
6003: . side - the preconditioning side, where side is one of
6004: .vb
6005: `PC_LEFT` - left preconditioning
6006: `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
6007: .ve
6009: Level: intermediate
6011: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6012: @*/
6013: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
6014: {
6015: PetscFunctionBegin;
6017: PetscAssertPointer(side, 2);
6018: *side = snes->npcside;
6019: PetscFunctionReturn(PETSC_SUCCESS);
6020: }
6022: /*@
6023: SNESSetLineSearch - Sets the `SNESLineSearch` to be used for a given `SNES`
6025: Collective
6027: Input Parameters:
6028: + snes - iterative context obtained from `SNESCreate()`
6029: - linesearch - the linesearch object
6031: Level: developer
6033: Note:
6034: This is almost never used, rather one uses `SNESGetLineSearch()` to retrieve the line search and set options on it
6035: to configure it using the API).
6037: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
6038: @*/
6039: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
6040: {
6041: PetscFunctionBegin;
6044: PetscCheckSameComm(snes, 1, linesearch, 2);
6045: PetscCall(PetscObjectReference((PetscObject)linesearch));
6046: PetscCall(SNESLineSearchDestroy(&snes->linesearch));
6048: snes->linesearch = linesearch;
6049: PetscFunctionReturn(PETSC_SUCCESS);
6050: }